From f812e3417988e13ed638434f892cff5c4ab843ad Mon Sep 17 00:00:00 2001 From: "Hiram R. Chirino" Date: Wed, 8 Aug 2007 18:56:59 +0000 Subject: [PATCH] More checkstyle fixes git-svn-id: https://svn.apache.org/repos/asf/activemq/trunk@563982 13f79535-47bb-0310-9956-ffa450edef68 --- .../ActiveMQMessageTransformation.java | 85 +- .../activemq/ActiveMQQueueReceiver.java | 45 +- .../apache/activemq/ActiveMQQueueSender.java | 91 +- .../activemq/ActiveMQSessionExecutor.java | 7 +- .../apache/activemq/ActiveMQTopicSession.java | 12 +- .../java/org/apache/activemq/Closeable.java | 27 +- .../org/apache/activemq/StreamConnection.java | 41 +- .../activemq/advisory/AdvisorySupport.java | 10 +- .../blob/DefaultBlobUploadStrategy.java | 39 +- .../apache/activemq/broker/BrokerFactory.java | 32 +- .../broker/BrokerStoppedException.java | 33 +- .../apache/activemq/broker/Connection.java | 16 +- .../activemq/broker/TransportConnection.java | 68 +- .../activemq/broker/jmx/BrokerView.java | 116 +-- .../activemq/broker/jmx/ConnectionView.java | 26 +- .../jmx/ManagedTransportConnection.java | 81 +- .../broker/jmx/NetworkBridgeView.java | 24 +- .../broker/jmx/NetworkConnectorView.java | 126 +-- .../broker/jmx/NetworkConnectorViewMBean.java | 56 +- .../activemq/broker/jmx/SubscriptionView.java | 107 ++- .../broker/jmx/TopicSubscriptionView.java | 8 +- .../activemq/broker/region/Destination.java | 21 +- .../broker/region/DestinationFilter.java | 22 +- .../broker/region/NullMessageReference.java | 147 ++- .../region/QueueBrowserSubscription.java | 28 +- .../activemq/broker/region/QueueRegion.java | 25 +- .../apache/activemq/broker/region/Topic.java | 12 +- .../FilePendingQueueMessageStoragePolicy.java | 18 +- ...PendingSubscriberMessageStoragePolicy.java | 21 +- ...StorePendingQueueMessageStoragePolicy.java | 18 +- .../VMPendingQueueMessageStoragePolicy.java | 13 +- ...PendingSubscriberMessageStoragePolicy.java | 16 +- .../util/MulticastTraceBrokerPlugin.java | 41 +- .../broker/util/TimeStampingBrokerPlugin.java | 28 +- .../view/DestinationDotFileInterceptor.java | 33 +- .../activemq/camel/CamelQueueSender.java | 76 +- .../activemq/command/ActiveMQDestination.java | 9 +- .../activemq/command/ActiveMQMapMessage.java | 375 ++++---- .../command/ActiveMQObjectMessage.java | 94 +- .../activemq/command/ActiveMQQueue.java | 7 +- .../command/ActiveMQStreamMessage.java | 3 +- .../activemq/command/ActiveMQTempTopic.java | 7 +- .../activemq/command/ActiveMQTextMessage.java | 3 +- .../org/apache/activemq/command/BrokerId.java | 6 +- .../activemq/command/ConnectionError.java | 16 +- .../activemq/command/ConnectionInfo.java | 105 ++- .../apache/activemq/command/ConsumerInfo.java | 13 +- .../apache/activemq/command/DataResponse.java | 18 +- .../activemq/command/MessageDispatch.java | 30 +- .../apache/activemq/command/ProducerInfo.java | 57 +- .../apache/activemq/command/RemoveInfo.java | 31 +- .../apache/activemq/command/SessionId.java | 51 +- .../apache/activemq/command/SessionInfo.java | 17 +- .../apache/activemq/command/ShutdownInfo.java | 11 +- .../activemq/command/SubscriptionInfo.java | 74 +- .../activemq/command/TransactionInfo.java | 46 +- .../activemq/command/WireFormatInfo.java | 123 +-- .../activemq/command/XATransactionId.java | 49 +- .../activemq/filter/ArithmeticExpression.java | 63 +- .../activemq/filter/ComparisonExpression.java | 299 +++---- .../activemq/filter/ConstantExpression.java | 48 +- .../activemq/filter/DestinationFilter.java | 12 +- .../activemq/filter/DestinationMapNode.java | 99 +- .../activemq/filter/PropertyExpression.java | 119 +-- .../activemq/filter/UnaryExpression.java | 154 ++-- .../activemq/filter/XPathExpression.java | 46 +- .../activemq/filter/XQueryExpression.java | 6 +- .../activemq/filter/XalanXPathEvaluator.java | 39 +- .../jndi/ActiveMQInitialContextFactory.java | 83 +- .../apache/activemq/kaha/BytesMarshaller.java | 13 +- .../org/apache/activemq/kaha/ContainerId.java | 54 +- .../apache/activemq/kaha/ListContainer.java | 36 +- .../apache/activemq/kaha/MapContainer.java | 158 ++-- .../activemq/kaha/MessageIdMarshaller.java | 5 +- .../activemq/kaha/ObjectMarshaller.java | 24 +- .../activemq/kaha/RuntimeStoreException.java | 29 +- .../java/org/apache/activemq/kaha/Store.java | 81 +- .../apache/activemq/kaha/StoreFactory.java | 17 +- .../activemq/kaha/StringMarshaller.java | 5 +- .../activemq/kaha/impl/DataManager.java | 33 +- .../kaha/impl/IndexRootContainer.java | 97 +- .../kaha/impl/StoreLockedExcpetion.java | 18 +- .../kaha/impl/async/DataFileAccessor.java | 201 ++--- .../kaha/impl/async/DataFileAppender.java | 591 ++++++------ .../kaha/impl/async/DataManagerFacade.java | 203 +++-- .../kaha/impl/async/JournalFacade.java | 120 +-- .../activemq/kaha/impl/async/Location.java | 133 +-- .../kaha/impl/async/NIODataFileAppender.java | 327 +++---- .../impl/container/ContainerEntrySet.java | 72 +- .../container/ContainerEntrySetIterator.java | 32 +- .../kaha/impl/container/ContainerKeySet.java | 66 +- .../container/ContainerKeySetIterator.java | 41 +- .../impl/container/ContainerListIterator.java | 68 +- .../impl/container/ContainerMapEntry.java | 26 +- .../container/ContainerValueCollection.java | 113 ++- .../ContainerValueCollectionIterator.java | 36 +- .../impl/container/ListContainerImpl.java | 602 +++++++------ .../kaha/impl/container/MapContainerImpl.java | 356 ++++---- .../activemq/kaha/impl/data/DataItem.java | 40 +- .../kaha/impl/data/DataManagerImpl.java | 408 +++++---- .../apache/activemq/kaha/impl/data/Item.java | 12 +- .../kaha/impl/data/SyncDataFileReader.java | 38 +- .../kaha/impl/data/SyncDataFileWriter.java | 88 +- .../kaha/impl/index/BadMagicException.java | 11 +- .../activemq/kaha/impl/index/Index.java | 32 +- .../kaha/impl/index/IndexLinkedList.java | 69 +- .../kaha/impl/index/RedoStoreIndexItem.java | 21 +- .../kaha/impl/index/StoreIndexReader.java | 23 +- .../kaha/impl/index/StoreIndexWriter.java | 33 +- .../activemq/kaha/impl/index/VMIndex.java | 56 +- .../kaha/impl/index/hash/HashEntry.java | 52 +- .../kaha/impl/index/tree/TreeEntry.java | 89 +- .../kaha/impl/index/tree/TreePageEntry.java | 44 +- .../management/CountStatisticImpl.java | 88 +- .../management/PollCountStatisticImpl.java | 34 +- .../org/apache/activemq/memory/Cache.java | 57 +- .../apache/activemq/memory/CacheEntry.java | 20 +- .../activemq/memory/CacheEntryList.java | 30 +- .../memory/CacheEvictionUsageListener.java | 37 +- .../apache/activemq/memory/UsageManager.java | 312 +++---- .../memory/UsageManagerCacheFilter.java | 11 +- .../memory/list/SimpleMessageList.java | 30 +- .../CompositeDemandForwardingBridge.java | 34 +- .../activemq/network/ConduitBridge.java | 70 +- .../network/DemandForwardingBridge.java | 43 +- .../activemq/network/DemandSubscription.java | 47 +- .../network/DiscoveryNetworkConnector.java | 107 ++- .../network/DurableConduitBridge.java | 68 +- .../activemq/network/ForwardingBridge.java | 241 ++--- .../network/MulticastNetworkConnector.java | 11 +- .../network/NetworkBridgeFactory.java | 82 +- .../network/NetworkBridgeListener.java | 17 +- .../activemq/network/NetworkConnector.java | 237 +++-- .../network/jms/InboundQueueBridge.java | 33 +- .../network/jms/InboundTopicBridge.java | 31 +- .../network/jms/JmsQueueConnector.java | 396 ++++---- .../network/jms/JmsTopicConnector.java | 396 ++++---- .../network/jms/OutboundQueueBridge.java | 31 +- .../network/jms/OutboundTopicBridge.java | 31 +- .../activemq/network/jms/QueueBridge.java | 89 +- .../jms/SimpleJmsMessageConvertor.java | 38 +- .../activemq/network/jms/TopicBridge.java | 115 ++- .../activemq/openwire/BooleanStream.java | 86 +- .../openwire/OpenWireFormatFactory.java | 75 +- .../openwire/v1/BaseDataStreamMarshaller.java | 412 +++++---- .../openwire/v1/ConnectionInfoMarshaller.java | 53 +- .../openwire/v1/ConsumerIdMarshaller.java | 36 +- .../openwire/v1/ConsumerInfoMarshaller.java | 75 +- .../v1/DataArrayResponseMarshaller.java | 48 +- .../v1/DestinationInfoMarshaller.java | 66 +- .../openwire/v1/MarshallerFactory.java | 19 +- .../openwire/v1/MessageIdMarshaller.java | 42 +- .../openwire/v1/ProducerIdMarshaller.java | 36 +- .../openwire/v1/SessionIdMarshaller.java | 34 +- .../openwire/v2/BaseDataStreamMarshaller.java | 412 +++++---- .../openwire/v2/BrokerInfoMarshaller.java | 55 +- .../openwire/v2/ConnectionInfoMarshaller.java | 53 +- .../openwire/v2/ConsumerIdMarshaller.java | 36 +- .../openwire/v2/ConsumerInfoMarshaller.java | 81 +- .../v2/DataArrayResponseMarshaller.java | 48 +- .../v2/DestinationInfoMarshaller.java | 66 +- .../openwire/v2/MessageIdMarshaller.java | 42 +- .../openwire/v2/ProducerIdMarshaller.java | 36 +- .../openwire/v2/SessionIdMarshaller.java | 34 +- .../openwire/v3/BaseDataStreamMarshaller.java | 216 ++--- .../openwire/v3/BrokerInfoMarshaller.java | 55 +- .../openwire/v3/ConnectionInfoMarshaller.java | 53 +- .../openwire/v3/ConsumerIdMarshaller.java | 36 +- .../openwire/v3/ConsumerInfoMarshaller.java | 75 +- .../v3/DataArrayResponseMarshaller.java | 48 +- .../v3/DestinationInfoMarshaller.java | 66 +- .../openwire/v3/MessagePullMarshaller.java | 57 +- .../openwire/v3/ProducerInfoMarshaller.java | 64 +- .../openwire/v3/SessionIdMarshaller.java | 34 +- .../apache/activemq/pool/ConnectionKey.java | 9 +- .../apache/activemq/pool/ConnectionPool.java | 164 ++-- .../activemq/pool/PooledConnection.java | 46 +- .../pool/PooledConnectionFactory.java | 41 +- .../apache/activemq/proxy/ProxyConnector.java | 43 +- .../activemq/security/AuthenticationUser.java | 71 +- .../security/AuthorizationBroker.java | 205 ++--- .../activemq/security/AuthorizationEntry.java | 123 +-- .../security/DefaultAuthorizationMap.java | 73 +- .../security/JaasAuthenticationBroker.java | 35 +- .../activemq/security/SecurityContext.java | 6 +- .../security/SimpleAuthenticationBroker.java | 34 +- .../security/SimpleAuthenticationPlugin.java | 34 +- .../security/SimpleAuthorizationMap.java | 52 +- .../apache/activemq/state/CommandVisitor.java | 56 +- .../activemq/state/CommandVisitorAdapter.java | 205 ++--- .../activemq/state/ConnectionState.java | 74 +- .../state/ConnectionStateTracker.java | 433 ++++----- .../apache/activemq/state/ProducerState.java | 12 +- .../apache/activemq/state/SessionState.java | 66 +- .../org/apache/activemq/state/Tracked.java | 36 +- .../activemq/state/TransactionState.java | 80 +- .../apache/activemq/store/MessageStore.java | 46 +- .../activemq/store/ProxyMessageStore.java | 25 +- .../store/ProxyTopicMessageStore.java | 63 +- .../apache/activemq/store/ReferenceStore.java | 82 +- .../activemq/store/ReferenceStoreAdapter.java | 52 +- .../activemq/store/TopicMessageStore.java | 68 +- .../activemq/store/TopicReferenceStore.java | 65 +- .../activemq/store/amq/AMQMessageStore.java | 440 ++++----- .../store/amq/AMQPersistenceAdapter.java | 559 ++++++------ .../amq/AMQPersistenceAdapterFactory.java | 63 +- .../store/amq/AMQTopicMessageStore.java | 156 ++-- .../store/amq/AMQTransactionStore.java | 220 ++--- .../org/apache/activemq/store/amq/AMQTx.java | 59 +- .../activemq/store/amq/AMQTxOperation.java | 80 +- .../store/amq/RecoveryListenerAdapter.java | 43 +- .../store/jdbc/DataSourceSupport.java | 8 +- .../activemq/store/jdbc/JDBCAdapter.java | 98 +- .../activemq/store/jdbc/JDBCMessageStore.java | 115 ++- .../store/jdbc/JDBCPersistenceAdapter.java | 101 +-- .../store/jdbc/JDBCTopicMessageStore.java | 151 ++-- .../activemq/store/jdbc/Statements.java | 211 ++--- .../store/jdbc/TransactionContext.java | 70 +- .../store/jdbc/adapter/BlobJDBCAdapter.java | 98 +- .../jdbc/adapter/DefaultJDBCAdapter.java | 847 +++++++++--------- .../store/jdbc/adapter/StreamJDBCAdapter.java | 20 +- .../store/journal/JournalMessageStore.java | 197 ++-- .../journal/JournalPersistenceAdapter.java | 283 +++--- .../JournalPersistenceAdapterFactory.java | 76 +- .../journal/JournalTopicMessageStore.java | 128 +-- .../journal/JournalTransactionStore.java | 228 ++--- .../store/kahadaptor/AMQTxMarshaller.java | 29 +- .../kahadaptor/AtomicIntegerMarshaller.java | 13 +- .../store/kahadaptor/ConsumerMessageRef.java | 39 +- .../ConsumerMessageRefMarshaller.java | 31 +- .../store/kahadaptor/IntegerMarshaller.java | 10 +- .../store/kahadaptor/KahaMessageStore.java | 126 +-- .../kahadaptor/KahaPersistenceAdapter.java | 214 ++--- .../store/kahadaptor/KahaReferenceStore.java | 143 +-- .../kahadaptor/KahaReferenceStoreAdapter.java | 245 ++--- .../kahadaptor/KahaTopicMessageStore.java | 238 +++-- .../kahadaptor/KahaTopicReferenceStore.java | 274 +++--- .../store/kahadaptor/KahaTransaction.java | 75 +- .../kahadaptor/KahaTransactionStore.java | 125 +-- .../store/kahadaptor/ReferenceRecord.java | 30 +- .../kahadaptor/ReferenceRecordMarshaller.java | 11 +- .../kahadaptor/StoreEntryMarshaller.java | 17 +- .../store/kahadaptor/TopicSubAck.java | 23 +- .../kahadaptor/TopicSubAckMarshaller.java | 21 +- .../store/kahadaptor/TopicSubContainer.java | 30 +- .../kahadaptor/TransactionMarshaller.java | 43 +- .../activemq/store/kahadaptor/TxCommand.java | 85 +- .../store/memory/MemoryMessageStore.java | 118 +-- .../memory/MemoryPersistenceAdapter.java | 38 +- .../store/memory/MemoryTopicMessageStore.java | 98 +- .../activemq/store/memory/MemoryTopicSub.java | 63 +- .../store/memory/MemoryTransactionStore.java | 105 +-- .../activemq/thread/DedicatedTaskRunner.java | 74 +- .../activemq/thread/PooledTaskRunner.java | 95 +- .../org/apache/activemq/thread/Scheduler.java | 21 +- .../activemq/thread/TaskRunnerFactory.java | 33 +- .../org/apache/activemq/thread/Valve.java | 84 +- .../activemq/transaction/Synchronization.java | 14 +- .../activemq/transaction/Transaction.java | 50 +- .../activemq/transaction/XATransaction.java | 132 ++- .../activemq/transport/FutureResponse.java | 21 +- .../activemq/transport/InactivityMonitor.java | 80 +- .../activemq/transport/MutexTransport.java | 24 +- .../transport/ResponseCorrelator.java | 83 +- .../apache/activemq/transport/Transport.java | 127 +-- .../TransportDisposedIOException.java | 3 +- .../activemq/transport/TransportFactory.java | 58 +- .../activemq/transport/TransportFilter.java | 62 +- .../activemq/transport/TransportLogger.java | 51 +- .../transport/TransportServerSupport.java | 21 +- .../TransportServerThreadSupport.java | 18 +- .../activemq/transport/TransportSupport.java | 13 +- .../transport/TransportThreadSupport.java | 15 +- .../transport/WireFormatNegotiator.java | 109 ++- .../discovery/DiscoveryAgentFactory.java | 46 +- .../discovery/DiscoveryTransportFactory.java | 10 +- .../discovery/rendezvous/JmDNSFactory.java | 23 +- .../rendezvous/RendezvousDiscoveryAgent.java | 60 +- .../simple/SimpleDiscoveryAgent.java | 227 ++--- .../transport/failover/FailoverTransport.java | 303 ++++--- .../failover/FailoverTransportFactory.java | 14 +- .../transport/fanout/FanoutTransport.java | 236 +++-- .../fanout/FanoutTransportFactory.java | 22 +- .../transport/mock/MockTransport.java | 30 +- .../transport/mock/MockTransportFactory.java | 14 +- .../transport/nio/NIOInputStream.java | 49 +- .../transport/nio/NIOOutputStream.java | 104 ++- .../activemq/transport/nio/NIOTransport.java | 175 ++-- .../transport/nio/NIOTransportFactory.java | 117 +-- .../transport/nio/SelectorManager.java | 121 +-- .../transport/nio/SelectorWorker.java | 177 ++-- .../transport/peer/PeerTransportFactory.java | 29 +- .../transport/reliable/ReliableTransport.java | 31 +- .../transport/stomp/FrameTranslator.java | 45 +- .../stomp/LegacyFrameTranslator.java | 48 +- .../transport/stomp/ProtocolConverter.java | 445 +++++---- .../transport/stomp/ProtocolException.java | 48 +- .../activemq/transport/stomp/StompFrame.java | 216 ++--- .../transport/stomp/StompFrameError.java | 18 +- .../transport/stomp/StompSubscription.java | 107 ++- .../transport/stomp/StompTransportFilter.java | 94 +- .../transport/stomp/StompWireFormat.java | 248 +++-- .../activemq/transport/tcp/SslTransport.java | 53 +- .../transport/tcp/SslTransportFactory.java | 66 +- .../transport/tcp/TcpBufferedInputStream.java | 101 +-- .../tcp/TcpBufferedOutputStream.java | 43 +- .../activemq/transport/tcp/TcpTransport.java | 82 +- .../transport/tcp/TcpTransportFactory.java | 49 +- .../transport/tcp/TcpTransportServer.java | 59 +- .../transport/udp/CommandDatagramChannel.java | 34 +- .../transport/udp/CommandDatagramSocket.java | 34 +- .../activemq/transport/udp/UdpTransport.java | 103 +-- .../activemq/transport/vm/VMTransport.java | 238 +++-- .../transport/vm/VMTransportFactory.java | 208 ++--- .../transport/vm/VMTransportServer.java | 39 +- .../org/apache/activemq/util/BitArray.java | 82 +- .../org/apache/activemq/util/BitArrayBin.java | 93 +- .../apache/activemq/util/BrokerSupport.java | 18 +- .../activemq/util/ByteArrayInputStream.java | 27 +- .../apache/activemq/util/ByteSequence.java | 49 +- .../activemq/util/ByteSequenceData.java | 189 ++-- .../util/DataByteArrayInputStream.java | 249 ++--- .../apache/activemq/util/FactoryFinder.java | 27 +- .../org/apache/activemq/util/IdGenerator.java | 143 +-- .../activemq/util/IntrospectionSupport.java | 171 ++-- .../activemq/util/JMSExceptionSupport.java | 16 +- .../org/apache/activemq/util/LRUCache.java | 71 +- .../org/apache/activemq/util/LinkedNode.java | 241 +++-- .../activemq/util/MarshallingSupport.java | 229 +++-- .../util/MemoryIntPropertyEditor.java | 70 +- .../activemq/util/MemoryPropertyEditor.java | 70 +- .../apache/activemq/util/ServiceStopper.java | 20 +- .../apache/activemq/util/SubscriptionKey.java | 16 +- .../activemq/util/TransactionTemplate.java | 27 +- .../org/apache/activemq/util/URISupport.java | 172 ++-- .../wireformat/ObjectStreamWireFormat.java | 6 +- .../xbean/PooledBrokerFactoryBean.java | 38 +- .../org/apache/activemq/AMQDeadlockTest3.java | 676 +++++++------- .../activemq/ActiveMQMessageAuditTest.java | 48 +- .../activemq/CombinationTestSupport.java | 60 +- .../ConsumerReceiveWithTimeoutTest.java | 33 +- .../org/apache/activemq/JMSConsumerTest.java | 12 +- .../JMSDurableTopicRedeliverTest.java | 25 +- .../activemq/JMSExclusiveConsumerTest.java | 30 +- .../org/apache/activemq/JMSUsecaseTest.java | 76 +- .../activemq/JmsAutoAckListenerTest.java | 13 +- .../org/apache/activemq/JmsBenchmark.java | 26 +- .../activemq/JmsDurableTopicSelectorTest.java | 2 +- .../JmsDurableTopicSendReceiveTest.java | 18 +- .../apache/activemq/JmsQueueSelectorTest.java | 2 +- .../activemq/JmsQueueTransactionTest.java | 86 +- .../JmsQueueWildcardSendReceiveTest.java | 67 +- .../activemq/JmsTempDestinationTest.java | 125 +-- .../org/apache/activemq/JmsTestSupport.java | 34 +- .../JmsTopicWildcardSendReceiveTest.java | 65 +- .../activemq/LargeMessageTestSupport.java | 9 +- .../apache/activemq/LargeStreamletTest.java | 81 +- .../org/apache/activemq/LoadTestBurnIn.java | 22 +- .../activemq/ProducerFlowControlTest.java | 3 +- .../ReconnectWithSameClientIDTest.java | 20 +- .../activemq/broker/BrokerBenchmark.java | 23 +- .../activemq/broker/BrokerServiceTest.java | 100 +-- .../apache/activemq/broker/BrokerTest.java | 199 ++-- .../broker/DoubleSubscriptionTest.java | 2 +- .../broker/MessageExpirationTest.java | 12 +- .../region/cursors/CursorDurableTest.java | 20 +- .../command/ActiveMQDestinationTest.java | 52 +- .../network/ForwardingBridgeTest.java | 43 +- .../network/MulticastNetworkTest.java | 3 +- .../SSHTunnelNetworkReconnectTest.java | 6 +- .../NumberRangesWhileMarshallingTest.java | 84 +- .../openwire/v1/ActiveMQBytesMessageTest.java | 37 +- .../v1/ActiveMQDestinationTestSupport.java | 31 +- .../openwire/v1/ActiveMQMapMessageTest.java | 37 +- .../openwire/v1/ActiveMQMessageTest.java | 37 +- .../v1/ActiveMQObjectMessageTest.java | 37 +- .../openwire/v1/ActiveMQQueueTest.java | 37 +- .../v1/ActiveMQStreamMessageTest.java | 37 +- .../ActiveMQTempDestinationTestSupport.java | 30 +- .../openwire/v1/ActiveMQTempQueueTest.java | 37 +- .../openwire/v1/ActiveMQTempTopicTest.java | 37 +- .../openwire/v1/ActiveMQTextMessageTest.java | 37 +- .../openwire/v1/ActiveMQTopicTest.java | 37 +- .../openwire/v1/BaseCommandTestSupport.java | 31 +- .../activemq/openwire/v1/BrokerIdTest.java | 38 +- .../openwire/v1/ConnectionControlTest.java | 37 +- .../openwire/v1/ConnectionErrorTest.java | 37 +- .../openwire/v1/ConnectionIdTest.java | 38 +- .../openwire/v1/ConsumerControlTest.java | 37 +- .../activemq/openwire/v1/ConsumerIdTest.java | 38 +- .../openwire/v1/ControlCommandTest.java | 37 +- .../openwire/v1/DataResponseTest.java | 37 +- .../openwire/v1/DiscoveryEventTest.java | 38 +- .../openwire/v1/ExceptionResponseTest.java | 37 +- .../openwire/v1/FlushCommandTest.java | 37 +- .../openwire/v1/IntegerResponseTest.java | 37 +- .../openwire/v1/JournalQueueAckTest.java | 38 +- .../openwire/v1/JournalTopicAckTest.java | 38 +- .../openwire/v1/JournalTraceTest.java | 38 +- .../openwire/v1/JournalTransactionTest.java | 40 +- .../openwire/v1/KeepAliveInfoTest.java | 37 +- .../openwire/v1/LastPartialCommandTest.java | 37 +- .../openwire/v1/LocalTransactionIdTest.java | 37 +- .../activemq/openwire/v1/MessageAckTest.java | 39 +- .../v1/MessageDispatchNotificationTest.java | 37 +- .../openwire/v1/MessageDispatchTest.java | 37 +- .../activemq/openwire/v1/MessageIdTest.java | 38 +- .../openwire/v1/NetworkBridgeFilterTest.java | 38 +- .../openwire/v1/PartialCommandTest.java | 38 +- .../activemq/openwire/v1/ProducerIdTest.java | 38 +- .../activemq/openwire/v1/RemoveInfoTest.java | 37 +- .../v1/RemoveSubscriptionInfoTest.java | 37 +- .../openwire/v1/ReplayCommandTest.java | 37 +- .../activemq/openwire/v1/ResponseTest.java | 37 +- .../activemq/openwire/v1/SessionIdTest.java | 38 +- .../activemq/openwire/v1/SessionInfoTest.java | 37 +- .../openwire/v1/ShutdownInfoTest.java | 37 +- .../openwire/v1/SubscriptionInfoTest.java | 38 +- .../openwire/v1/TransactionIdTestSupport.java | 31 +- .../openwire/v1/TransactionInfoTest.java | 39 +- .../openwire/v1/XATransactionIdTest.java | 37 +- .../openwire/v2/ActiveMQBytesMessageTest.java | 30 +- .../v2/ActiveMQDestinationTestSupport.java | 23 +- .../openwire/v2/ActiveMQMapMessageTest.java | 31 +- .../openwire/v2/ActiveMQMessageTest.java | 30 +- .../v2/ActiveMQObjectMessageTest.java | 30 +- .../openwire/v2/ActiveMQQueueTest.java | 30 +- .../v2/ActiveMQStreamMessageTest.java | 30 +- .../ActiveMQTempDestinationTestSupport.java | 30 +- .../openwire/v2/ActiveMQTempQueueTest.java | 37 +- .../openwire/v2/ActiveMQTempTopicTest.java | 37 +- .../openwire/v2/ActiveMQTextMessageTest.java | 37 +- .../openwire/v2/ActiveMQTopicTest.java | 37 +- .../openwire/v2/BaseCommandTestSupport.java | 31 +- .../openwire/v3/BaseCommandTestSupport.java | 24 +- .../activemq/proxy/ProxyConnectorTest.java | 36 +- .../security/AuthorizationMapTest.java | 57 +- .../security/SecurityTestSupport.java | 105 ++- .../activemq/transport/QueueClusterTest.java | 17 +- .../activemq/transport/StubTransport.java | 14 +- .../failover/FailoverConsumerTest.java | 145 +-- .../reliable/ReliableTransportTest.java | 59 +- .../UnreliableCommandDatagramSocket.java | 20 +- .../transport/stomp/StompConnection.java | 29 +- .../stomp/StompSubscriptionRemoveTest.java | 43 +- .../tcp/SslTransportFactoryTest.java | 72 +- .../transport/tcp/StubSSLSocketFactory.java | 19 +- .../transport/tcp/StubX509Certificate.java | 157 ++-- .../transport/udp/UdpTestSupport.java | 38 +- .../activemq/usecases/AMQFailoverIssue.java | 2 +- .../usecases/AMQStackOverFlowTest.java | 155 ++-- .../TwoBrokerTopicSendReceiveTest.java | 20 +- 452 files changed, 17426 insertions(+), 17633 deletions(-) diff --git a/activemq-core/src/main/java/org/apache/activemq/ActiveMQMessageTransformation.java b/activemq-core/src/main/java/org/apache/activemq/ActiveMQMessageTransformation.java index 4026355830..9af7a8cd98 100755 --- a/activemq-core/src/main/java/org/apache/activemq/ActiveMQMessageTransformation.java +++ b/activemq-core/src/main/java/org/apache/activemq/ActiveMQMessageTransformation.java @@ -32,7 +32,6 @@ import javax.jms.TemporaryTopic; import javax.jms.TextMessage; import javax.jms.Topic; - import org.apache.activemq.command.ActiveMQBytesMessage; import org.apache.activemq.command.ActiveMQDestination; import org.apache.activemq.command.ActiveMQMapMessage; @@ -46,65 +45,66 @@ import org.apache.activemq.command.ActiveMQTextMessage; import org.apache.activemq.command.ActiveMQTopic; /** - * A helper class for converting normal JMS interfaces into ActiveMQ specific ones. + * A helper class for converting normal JMS interfaces into ActiveMQ specific + * ones. * * @version $Revision: 1.1 $ */ public class ActiveMQMessageTransformation { - /** + /** * Creates a an available JMS message from another provider. - * - * @param destination - Destination to be converted into ActiveMQ's implementation. - * @return ActiveMQDestination - ActiveMQ's implementation of the destination. - * @throws JMSException if an error occurs - */ - public static ActiveMQDestination transformDestination(Destination destination) throws JMSException { + * + * @param destination - Destination to be converted into ActiveMQ's + * implementation. + * @return ActiveMQDestination - ActiveMQ's implementation of the + * destination. + * @throws JMSException if an error occurs + */ + public static ActiveMQDestination transformDestination(Destination destination) throws JMSException { ActiveMQDestination activeMQDestination = null; - + if (destination != null) { if (destination instanceof ActiveMQDestination) { - return (ActiveMQDestination) destination; - - } - else { + return (ActiveMQDestination)destination; + + } else { if (destination instanceof TemporaryQueue) { - activeMQDestination = new ActiveMQTempQueue(((Queue) destination).getQueueName()); - } - else if (destination instanceof TemporaryTopic) { - activeMQDestination = new ActiveMQTempTopic(((Topic) destination).getTopicName()); - } - else if (destination instanceof Queue) { - activeMQDestination = new ActiveMQQueue(((Queue) destination).getQueueName()); - } - else if (destination instanceof Topic) { - activeMQDestination = new ActiveMQTopic(((Topic) destination).getTopicName()); + activeMQDestination = new ActiveMQTempQueue(((Queue)destination).getQueueName()); + } else if (destination instanceof TemporaryTopic) { + activeMQDestination = new ActiveMQTempTopic(((Topic)destination).getTopicName()); + } else if (destination instanceof Queue) { + activeMQDestination = new ActiveMQQueue(((Queue)destination).getQueueName()); + } else if (destination instanceof Topic) { + activeMQDestination = new ActiveMQTopic(((Topic)destination).getTopicName()); } } } - return activeMQDestination; - } - - + return activeMQDestination; + } + /** - * Creates a fast shallow copy of the current ActiveMQMessage or creates a whole new - * message instance from an available JMS message from another provider. - * + * Creates a fast shallow copy of the current ActiveMQMessage or creates a + * whole new message instance from an available JMS message from another + * provider. + * * @param message - Message to be converted into ActiveMQ's implementation. - * @param connection - * @return ActiveMQMessage - ActiveMQ's implementation object of the message. + * @param connection + * @return ActiveMQMessage - ActiveMQ's implementation object of the + * message. * @throws JMSException if an error occurs */ - public static final ActiveMQMessage transformMessage(Message message, ActiveMQConnection connection) throws JMSException { + public static final ActiveMQMessage transformMessage(Message message, ActiveMQConnection connection) + throws JMSException { if (message instanceof ActiveMQMessage) { - return (ActiveMQMessage) message; + return (ActiveMQMessage)message; } else { ActiveMQMessage activeMessage = null; if (message instanceof BytesMessage) { - BytesMessage bytesMsg = (BytesMessage) message; + BytesMessage bytesMsg = (BytesMessage)message; bytesMsg.reset(); ActiveMQBytesMessage msg = new ActiveMQBytesMessage(); msg.setConnection(connection); @@ -121,7 +121,7 @@ public class ActiveMQMessageTransformation { activeMessage = msg; } else if (message instanceof MapMessage) { - MapMessage mapMsg = (MapMessage) message; + MapMessage mapMsg = (MapMessage)message; ActiveMQMapMessage msg = new ActiveMQMapMessage(); msg.setConnection(connection); Enumeration iter = mapMsg.getMapNames(); @@ -133,14 +133,14 @@ public class ActiveMQMessageTransformation { activeMessage = msg; } else if (message instanceof ObjectMessage) { - ObjectMessage objMsg = (ObjectMessage) message; + ObjectMessage objMsg = (ObjectMessage)message; ActiveMQObjectMessage msg = new ActiveMQObjectMessage(); msg.setConnection(connection); msg.setObject(objMsg.getObject()); msg.storeContent(); activeMessage = msg; } else if (message instanceof StreamMessage) { - StreamMessage streamMessage = (StreamMessage) message; + StreamMessage streamMessage = (StreamMessage)message; streamMessage.reset(); ActiveMQStreamMessage msg = new ActiveMQStreamMessage(); msg.setConnection(connection); @@ -157,7 +157,7 @@ public class ActiveMQMessageTransformation { activeMessage = msg; } else if (message instanceof TextMessage) { - TextMessage textMsg = (TextMessage) message; + TextMessage textMsg = (TextMessage)message; ActiveMQTextMessage msg = new ActiveMQTextMessage(); msg.setConnection(connection); msg.setText(textMsg.getText()); @@ -174,8 +174,9 @@ public class ActiveMQMessageTransformation { } /** - * Copies the standard JMS and user defined properties from the givem message to the specified message - * + * Copies the standard JMS and user defined properties from the givem + * message to the specified message + * * @param fromMessage the message to take the properties from * @param toMesage the message to add the properties to * @throws JMSException diff --git a/activemq-core/src/main/java/org/apache/activemq/ActiveMQQueueReceiver.java b/activemq-core/src/main/java/org/apache/activemq/ActiveMQQueueReceiver.java index bb7e8d4d9a..ab77aff77b 100755 --- a/activemq-core/src/main/java/org/apache/activemq/ActiveMQQueueReceiver.java +++ b/activemq-core/src/main/java/org/apache/activemq/ActiveMQQueueReceiver.java @@ -16,22 +16,20 @@ */ package org.apache.activemq; -import org.apache.activemq.command.ActiveMQDestination; -import org.apache.activemq.command.ConsumerId; - import javax.jms.JMSException; import javax.jms.Queue; import javax.jms.QueueReceiver; +import org.apache.activemq.command.ActiveMQDestination; +import org.apache.activemq.command.ConsumerId; + /** * A client uses a QueueReceiver object to receive messages that - * have been delivered to a queue. - *

+ * have been delivered to a queue.

*

* Although it is possible to have multiple QueueReceiver s for * the same queue, the JMS API does not define how messages are distributed - * between the QueueReceivers. - *

+ * between the QueueReceivers.

*

* If a QueueReceiver specifies a message selector, the messages * that are not selected remain on the queue. By definition, a message selector @@ -39,14 +37,14 @@ import javax.jms.QueueReceiver; * the skipped messages are eventually read, the total ordering of the reads * does not retain the partial order defined by each message producer. Only * QueueReceiver s without a message selector will read messages - * in message producer order. - *

+ * in message producer order.

*

* Creating a MessageConsumer provides the same features as * creating a QueueReceiver. A MessageConsumer * object is recommended for creating new code. The QueueReceiver - * is provided to support existing code. - * + * + * is provided to support existing code. + * * @see javax.jms.Session#createConsumer(javax.jms.Destination, String) * @see javax.jms.Session#createConsumer(javax.jms.Destination) * @see javax.jms.QueueSession#createReceiver(Queue, String) @@ -54,8 +52,7 @@ import javax.jms.QueueReceiver; * @see javax.jms.MessageConsumer */ -public class ActiveMQQueueReceiver extends ActiveMQMessageConsumer implements - QueueReceiver { +public class ActiveMQQueueReceiver extends ActiveMQMessageConsumer implements QueueReceiver { /** * @param theSession @@ -63,26 +60,28 @@ public class ActiveMQQueueReceiver extends ActiveMQMessageConsumer implements * @param destination * @param messageSelector * @param prefetch - * @param asyncDispatch + * @param asyncDispatch * @throws JMSException */ - protected ActiveMQQueueReceiver(ActiveMQSession theSession, - ConsumerId consumerId, ActiveMQDestination destination, String selector, int prefetch, int maximumPendingMessageCount, boolean asyncDispatch) - throws JMSException { - super(theSession, consumerId, destination, null, selector, prefetch, maximumPendingMessageCount, false, false, asyncDispatch); + protected ActiveMQQueueReceiver(ActiveMQSession theSession, ConsumerId consumerId, + ActiveMQDestination destination, String selector, int prefetch, + int maximumPendingMessageCount, boolean asyncDispatch) + throws JMSException { + super(theSession, consumerId, destination, null, selector, prefetch, maximumPendingMessageCount, + false, false, asyncDispatch); } /** * Gets the Queue associated with this queue receiver. - * + * * @return this receiver's Queue - * @throws JMSException if the JMS provider fails to get the queue for this queue - * receiver due to some internal error. + * @throws JMSException if the JMS provider fails to get the queue for this + * queue receiver due to some internal error. */ public Queue getQueue() throws JMSException { checkClosed(); - return (Queue) super.getDestination(); + return (Queue)super.getDestination(); } - + } diff --git a/activemq-core/src/main/java/org/apache/activemq/ActiveMQQueueSender.java b/activemq-core/src/main/java/org/apache/activemq/ActiveMQQueueSender.java index d17d26ec7f..53acda67aa 100755 --- a/activemq-core/src/main/java/org/apache/activemq/ActiveMQQueueSender.java +++ b/activemq-core/src/main/java/org/apache/activemq/ActiveMQQueueSender.java @@ -26,47 +26,46 @@ import org.apache.activemq.command.ActiveMQDestination; /** * A client uses a QueueSender object to send messages to a - * queue. - *

+ * queue.

*

* Normally, the Queue is specified when a QueueSender - * is created. In this case, an attempt to use the send - * methods for an unidentified QueueSender will throw a + * + * is created. In this case, an attempt to use the send methods + * for an unidentified QueueSender will throw a * java.lang.UnsupportedOperationException. *

*

* If the QueueSender is created with an unidentified - * Queue, an attempt to use the send methods that - * assume that the Queue has been identified will throw a + * Queue, + * an attempt to use the send methods that assume that the + * Queue has been identified will throw a * java.lang.UnsupportedOperationException. *

*

- * During the execution of its send method, a message must not - * be changed by other threads within the client. If the message is modified, - * the result of the send is undefined. - *

+ * During the execution of its send method, a message must not be + * changed by other threads within the client. If the message is modified, the + * result of the send is undefined.

*

* After sending a message, a client may retain and modify it without affecting * the message that has been sent. The same message object may be sent multiple - * times. - *

+ * times.

*

- * The following message headers are set as part of sending a message: JMSDestination, - * JMSDeliveryMode,JMSExpiration,JMSPriority, + * The following message headers are set as part of sending a message: + * JMSDestination, JMSDeliveryMode,JMSExpiration,JMSPriority, * JMSMessageID and JMSTimeStamp. When the * message is sent, the values of these headers are ignored. After the - * completion of the send, the headers hold the values - * specified by the method sending the message. It is possible for the send + * completion of the send, the headers hold the values specified + * by the method sending the message. It is possible for the send * method not to set JMSMessageID and JMSTimeStamp - * if the setting of these headers is explicitly disabled by the MessageProducer.setDisableMessageID - * or MessageProducer.setDisableMessageTimestamp method. - *

+ * if the setting of these headers is explicitly disabled by the + * MessageProducer.setDisableMessageID or + * MessageProducer.setDisableMessageTimestamp method.

*

* Creating a MessageProducer provides the same features as * creating a QueueSender. A MessageProducer * object is recommended when creating new code. The QueueSender * is provided to support existing code. - * + * * @see javax.jms.MessageProducer * @see javax.jms.QueueSession#createSender(Queue) */ @@ -74,38 +73,35 @@ import org.apache.activemq.command.ActiveMQDestination; public class ActiveMQQueueSender extends ActiveMQMessageProducer implements QueueSender { protected ActiveMQQueueSender(ActiveMQSession session, ActiveMQDestination destination) - throws JMSException { - super(session, - session.getNextProducerId(), - destination); + throws JMSException { + super(session, session.getNextProducerId(), destination); } /** * Gets the queue associated with this QueueSender. - * + * * @return this sender's queue * @throws JMSException if the JMS provider fails to get the queue for this - * QueueSender due to some internal error. + * QueueSender due to some internal error. */ public Queue getQueue() throws JMSException { - return (Queue) super.getDestination(); + return (Queue)super.getDestination(); } /** - * Sends a message to a queue for an unidentified message producer. Uses - * the QueueSender's default delivery mode, priority, and - * time to live. - *

+ * Sends a message to a queue for an unidentified message producer. Uses the + * QueueSender's default delivery mode, priority, and time + * to live.

*

* Typically, a message producer is assigned a queue at creation time; * however, the JMS API also supports unidentified message producers, which * require that the queue be supplied every time a message is sent. - * - * @param queue the queue to send this message to + * + * @param queue the queue to send this message to * @param message the message to send - * @throws JMSException if the JMS provider fails to send the message due to some - * internal error. + * @throws JMSException if the JMS provider fails to send the message due to + * some internal error. * @see javax.jms.MessageProducer#getDeliveryMode() * @see javax.jms.MessageProducer#getTimeToLive() * @see javax.jms.MessageProducer#getPriority() @@ -117,28 +113,23 @@ public class ActiveMQQueueSender extends ActiveMQMessageProducer implements Queu /** * Sends a message to a queue for an unidentified message producer, - * specifying delivery mode, priority and time to live. - *

+ * specifying delivery mode, priority and time to live.

*

* Typically, a message producer is assigned a queue at creation time; * however, the JMS API also supports unidentified message producers, which * require that the queue be supplied every time a message is sent. - * - * @param queue the queue to send this message to - * @param message the message to send + * + * @param queue the queue to send this message to + * @param message the message to send * @param deliveryMode the delivery mode to use - * @param priority the priority for this message - * @param timeToLive the message's lifetime (in milliseconds) - * @throws JMSException if the JMS provider fails to send the message due to some - * internal error. + * @param priority the priority for this message + * @param timeToLive the message's lifetime (in milliseconds) + * @throws JMSException if the JMS provider fails to send the message due to + * some internal error. */ public void send(Queue queue, Message message, int deliveryMode, int priority, long timeToLive) - throws JMSException { - super.send(queue, - message, - deliveryMode, - priority, - timeToLive); + throws JMSException { + super.send(queue, message, deliveryMode, priority, timeToLive); } } diff --git a/activemq-core/src/main/java/org/apache/activemq/ActiveMQSessionExecutor.java b/activemq-core/src/main/java/org/apache/activemq/ActiveMQSessionExecutor.java index 0db152bed3..68ed99a810 100755 --- a/activemq-core/src/main/java/org/apache/activemq/ActiveMQSessionExecutor.java +++ b/activemq-core/src/main/java/org/apache/activemq/ActiveMQSessionExecutor.java @@ -96,8 +96,8 @@ public class ActiveMQSessionExecutor implements Task { Thread.currentThread().interrupt(); } } else { - while (iterate()) - ; + while (iterate()) { + } } } } @@ -128,8 +128,9 @@ public class ActiveMQSessionExecutor implements Task { synchronized void start() { if (!messageQueue.isRunning()) { messageQueue.start(); - if (hasUncomsumedMessages()) + if (hasUncomsumedMessages()) { wakeup(); + } } } diff --git a/activemq-core/src/main/java/org/apache/activemq/ActiveMQTopicSession.java b/activemq-core/src/main/java/org/apache/activemq/ActiveMQTopicSession.java index abf2ff6095..1ef36841cb 100755 --- a/activemq-core/src/main/java/org/apache/activemq/ActiveMQTopicSession.java +++ b/activemq-core/src/main/java/org/apache/activemq/ActiveMQTopicSession.java @@ -104,8 +104,9 @@ public class ActiveMQTopicSession implements TopicSession { * @throws JMSException */ public MessageConsumer createConsumer(Destination destination) throws JMSException { - if (destination instanceof Queue) + if (destination instanceof Queue) { throw new InvalidDestinationException("Queues are not supported by a TopicSession"); + } return next.createConsumer(destination); } @@ -116,8 +117,9 @@ public class ActiveMQTopicSession implements TopicSession { * @throws JMSException */ public MessageConsumer createConsumer(Destination destination, String messageSelector) throws JMSException { - if (destination instanceof Queue) + if (destination instanceof Queue) { throw new InvalidDestinationException("Queues are not supported by a TopicSession"); + } return next.createConsumer(destination, messageSelector); } @@ -129,8 +131,9 @@ public class ActiveMQTopicSession implements TopicSession { * @throws JMSException */ public MessageConsumer createConsumer(Destination destination, String messageSelector, boolean NoLocal) throws JMSException { - if (destination instanceof Queue) + if (destination instanceof Queue) { throw new InvalidDestinationException("Queues are not supported by a TopicSession"); + } return next.createConsumer(destination, messageSelector, NoLocal); } @@ -195,8 +198,9 @@ public class ActiveMQTopicSession implements TopicSession { * @throws JMSException */ public MessageProducer createProducer(Destination destination) throws JMSException { - if (destination instanceof Queue) + if (destination instanceof Queue) { throw new InvalidDestinationException("Queues are not supported by a TopicSession"); + } return next.createProducer(destination); } diff --git a/activemq-core/src/main/java/org/apache/activemq/Closeable.java b/activemq-core/src/main/java/org/apache/activemq/Closeable.java index e8b21a0602..c9ae669b10 100755 --- a/activemq-core/src/main/java/org/apache/activemq/Closeable.java +++ b/activemq-core/src/main/java/org/apache/activemq/Closeable.java @@ -20,20 +20,21 @@ import javax.jms.JMSException; /** * Provides a uniform interface that can be used to close all the JMS obejcts - * that provide a close() method. Useful for when you want to collect - * a heterogeous set of JMS object in a collection to be closed at a later time. - * + * that provide a close() method. Useful for when you want to collect a + * heterogeous set of JMS object in a collection to be closed at a later time. + * * @version $Revision: 1.2 $ */ public interface Closeable { - - /** - * Closes a JMS object. - *

- * Many JMS objects are closeable such as Connections, Sessions, Consumers and Producers. - * - * @throws JMSException if the JMS provider fails to close the object due to - * some internal error. - */ - public void close() throws JMSException; + + /** + * Closes a JMS object. + *

+ * Many JMS objects are closeable such as Connections, Sessions, Consumers + * and Producers. + * + * @throws JMSException if the JMS provider fails to close the object due to + * some internal error. + */ + public void close() throws JMSException; } diff --git a/activemq-core/src/main/java/org/apache/activemq/StreamConnection.java b/activemq-core/src/main/java/org/apache/activemq/StreamConnection.java index aff87b87d8..e7180f896f 100644 --- a/activemq-core/src/main/java/org/apache/activemq/StreamConnection.java +++ b/activemq-core/src/main/java/org/apache/activemq/StreamConnection.java @@ -27,27 +27,31 @@ import javax.jms.JMSException; import javax.jms.Topic; /** - * The StreamConnection interface allows you to send and receive - * data from a Destination in using standard java InputStream and OutputStream - * objects. It's best use case is to send and receive large amounts of data - * that would be to large to hold in a single JMS message. + * The StreamConnection interface allows you to send and receive data from a + * Destination in using standard java InputStream and OutputStream objects. It's + * best use case is to send and receive large amounts of data that would be to + * large to hold in a single JMS message. * * @version $Revision$ */ public interface StreamConnection extends Connection { - public InputStream createInputStream(Destination dest) throws JMSException; + public InputStream createInputStream(Destination dest) throws JMSException; + public InputStream createInputStream(Destination dest, String messageSelector) throws JMSException; + public InputStream createInputStream(Destination dest, String messageSelector, boolean noLocal) throws JMSException; - + public InputStream createDurableInputStream(Topic dest, String name) throws JMSException; + public InputStream createDurableInputStream(Topic dest, String name, String messageSelector) throws JMSException; + public InputStream createDurableInputStream(Topic dest, String name, String messageSelector, boolean noLocal) throws JMSException; public OutputStream createOutputStream(Destination dest) throws JMSException; - public OutputStream createOutputStream(Destination dest, Map streamProperties, int deliveryMode, - int priority, long timeToLive) throws JMSException; - + + public OutputStream createOutputStream(Destination dest, Map streamProperties, int deliveryMode, int priority, long timeToLive) throws JMSException; + /** * Unsubscribes a durable subscription that has been created by a client. *

@@ -55,17 +59,16 @@ public interface StreamConnection extends Connection { * subscriber by its provider. *

* It is erroneous for a client to delete a durable subscription while there - * is an active MessageConsumer or TopicSubscriber - * for the subscription, or while a consumed message is part of a pending - * transaction or has not been acknowledged in the session. + * is an active MessageConsumer or + * TopicSubscriber for the subscription, or while a consumed + * message is part of a pending transaction or has not been acknowledged in + * the session. * - * @param name - * the name used to identify this subscription - * @throws JMSException - * if the session fails to unsubscribe to the durable - * subscription due to some internal error. - * @throws InvalidDestinationException - * if an invalid subscription name is specified. + * @param name the name used to identify this subscription + * @throws JMSException if the session fails to unsubscribe to the durable + * subscription due to some internal error. + * @throws InvalidDestinationException if an invalid subscription name is + * specified. * @since 1.1 */ public void unsubscribe(String name) throws JMSException; diff --git a/activemq-core/src/main/java/org/apache/activemq/advisory/AdvisorySupport.java b/activemq-core/src/main/java/org/apache/activemq/advisory/AdvisorySupport.java index d0f8f9d480..778b7164c7 100755 --- a/activemq-core/src/main/java/org/apache/activemq/advisory/AdvisorySupport.java +++ b/activemq-core/src/main/java/org/apache/activemq/advisory/AdvisorySupport.java @@ -50,17 +50,19 @@ public class AdvisorySupport { } public static ActiveMQTopic getConsumerAdvisoryTopic(ActiveMQDestination destination) { - if (destination.isQueue()) + if (destination.isQueue()) { return new ActiveMQTopic(QUEUE_CONSUMER_ADVISORY_TOPIC_PREFIX + destination.getPhysicalName()); - else + } else { return new ActiveMQTopic(TOPIC_CONSUMER_ADVISORY_TOPIC_PREFIX + destination.getPhysicalName()); + } } public static ActiveMQTopic getProducerAdvisoryTopic(ActiveMQDestination destination) { - if (destination.isQueue()) + if (destination.isQueue()) { return new ActiveMQTopic(QUEUE_PRODUCER_ADVISORY_TOPIC_PREFIX + destination.getPhysicalName()); - else + } else { return new ActiveMQTopic(TOPIC_PRODUCER_ADVISORY_TOPIC_PREFIX + destination.getPhysicalName()); + } } public static ActiveMQTopic getExpiredMessageTopic(ActiveMQDestination destination) { diff --git a/activemq-core/src/main/java/org/apache/activemq/blob/DefaultBlobUploadStrategy.java b/activemq-core/src/main/java/org/apache/activemq/blob/DefaultBlobUploadStrategy.java index 5711a2c4f3..48568f8221 100644 --- a/activemq-core/src/main/java/org/apache/activemq/blob/DefaultBlobUploadStrategy.java +++ b/activemq-core/src/main/java/org/apache/activemq/blob/DefaultBlobUploadStrategy.java @@ -30,8 +30,8 @@ import javax.jms.JMSException; import org.apache.activemq.command.ActiveMQBlobMessage; /** - * A default implementation of {@link BlobUploadStrategy} which uses the URL class to upload - * files or streams to a remote URL + * A default implementation of {@link BlobUploadStrategy} which uses the URL + * class to upload files or streams to a remote URL */ public class DefaultBlobUploadStrategy implements BlobUploadStrategy { private BlobTransferPolicy transferPolicy; @@ -50,30 +50,31 @@ public class DefaultBlobUploadStrategy implements BlobUploadStrategy { HttpURLConnection connection = (HttpURLConnection)url.openConnection(); connection.setRequestMethod("PUT"); connection.setDoOutput(true); - - // use chunked mode or otherwise URLConnection loads everything into memory + + // use chunked mode or otherwise URLConnection loads everything into + // memory // (chunked mode not supported before JRE 1.5) connection.setChunkedStreamingMode(transferPolicy.getBufferSize()); - + OutputStream os = connection.getOutputStream(); byte[] buf = new byte[transferPolicy.getBufferSize()]; for (int c = fis.read(buf); c != -1; c = fis.read(buf)) { - os.write(buf, 0, c); - os.flush(); + os.write(buf, 0, c); + os.flush(); } os.close(); fis.close(); - + if (!isSuccessfulCode(connection.getResponseCode())) { - throw new IOException("PUT was not successful: " - + connection.getResponseCode() + " " + connection.getResponseMessage()); + throw new IOException("PUT was not successful: " + connection.getResponseCode() + " " + + connection.getResponseMessage()); } return url; } - public void deleteFile(ActiveMQBlobMessage message) throws IOException, JMSException { + public void deleteFile(ActiveMQBlobMessage message) throws IOException, JMSException { URL url = createUploadURL(message); HttpURLConnection connection = (HttpURLConnection)url.openConnection(); @@ -82,16 +83,16 @@ public class DefaultBlobUploadStrategy implements BlobUploadStrategy { connection.disconnect(); if (!isSuccessfulCode(connection.getResponseCode())) { - throw new IOException("DELETE was not successful: " - + connection.getResponseCode() + " " + connection.getResponseMessage()); + throw new IOException("DELETE was not successful: " + connection.getResponseCode() + " " + + connection.getResponseMessage()); } - } - - private boolean isSuccessfulCode(int responseCode) { - return responseCode >= 200 && responseCode < 300; // 2xx => successful - } + } - protected URL createUploadURL(ActiveMQBlobMessage message) throws JMSException, MalformedURLException { + private boolean isSuccessfulCode(int responseCode) { + return responseCode >= 200 && responseCode < 300; // 2xx => successful + } + + protected URL createUploadURL(ActiveMQBlobMessage message) throws JMSException, MalformedURLException { return new URL(transferPolicy.getUploadUrl() + message.getMessageId().toString()); } } diff --git a/activemq-core/src/main/java/org/apache/activemq/broker/BrokerFactory.java b/activemq-core/src/main/java/org/apache/activemq/broker/BrokerFactory.java index b087430b3d..96c4713336 100755 --- a/activemq-core/src/main/java/org/apache/activemq/broker/BrokerFactory.java +++ b/activemq-core/src/main/java/org/apache/activemq/broker/BrokerFactory.java @@ -23,26 +23,28 @@ import org.apache.activemq.util.FactoryFinder; import org.apache.activemq.util.IOExceptionSupport; /** - * A helper class to create a fully configured broker service using a URI. - * The list of currently supported URI syntaxes is described - * here + * A helper class to create a fully configured broker service using a URI. The + * list of currently supported URI syntaxes is described here * * @version $Revision$ */ public class BrokerFactory { - static final private FactoryFinder brokerFactoryHandlerFinder = new FactoryFinder("META-INF/services/org/apache/activemq/broker/"); + static final private FactoryFinder brokerFactoryHandlerFinder = new FactoryFinder( + "META-INF/services/org/apache/activemq/broker/"); public static BrokerFactoryHandler createBrokerFactoryHandler(String type) throws IOException { try { return (BrokerFactoryHandler)brokerFactoryHandlerFinder.newInstance(type); } catch (Throwable e) { - throw IOExceptionSupport.create("Could load "+type+" factory:"+e, e); + throw IOExceptionSupport.create("Could load " + type + " factory:" + e, e); } } /** * Creates a broker from a URI configuration + * * @param brokerURI the URI scheme to configure the broker * @throws Exception */ @@ -52,14 +54,17 @@ public class BrokerFactory { /** * Creates a broker from a URI configuration + * * @param brokerURI the URI scheme to configure the broker - * @param startBroker whether or not the broker should have its {@link BrokerService#start()} method called after construction + * @param startBroker whether or not the broker should have its + * {@link BrokerService#start()} method called after + * construction * @throws Exception */ public static BrokerService createBroker(URI brokerURI, boolean startBroker) throws Exception { - if( brokerURI.getScheme() == null ) - throw new IllegalArgumentException("Invalid broker URI, no scheme specified: "+brokerURI); - + if (brokerURI.getScheme() == null) { + throw new IllegalArgumentException("Invalid broker URI, no scheme specified: " + brokerURI); + } BrokerFactoryHandler handler = createBrokerFactoryHandler(brokerURI.getScheme()); BrokerService broker = handler.createBroker(brokerURI); if (startBroker) { @@ -68,9 +73,9 @@ public class BrokerFactory { return broker; } - /** * Creates a broker from a URI configuration + * * @param brokerURI the URI scheme to configure the broker * @throws Exception */ @@ -78,16 +83,17 @@ public class BrokerFactory { return createBroker(new URI(brokerURI)); } - /** * Creates a broker from a URI configuration + * * @param brokerURI the URI scheme to configure the broker - * @param startBroker whether or not the broker should have its {@link BrokerService#start()} method called after construction + * @param startBroker whether or not the broker should have its + * {@link BrokerService#start()} method called after + * construction * @throws Exception */ public static BrokerService createBroker(String brokerURI, boolean startBroker) throws Exception { return createBroker(new URI(brokerURI), startBroker); } - } diff --git a/activemq-core/src/main/java/org/apache/activemq/broker/BrokerStoppedException.java b/activemq-core/src/main/java/org/apache/activemq/broker/BrokerStoppedException.java index 3713655808..974017f9da 100644 --- a/activemq-core/src/main/java/org/apache/activemq/broker/BrokerStoppedException.java +++ b/activemq-core/src/main/java/org/apache/activemq/broker/BrokerStoppedException.java @@ -17,29 +17,30 @@ package org.apache.activemq.broker; /** - * This exception is thrown by the broker when you try to use it after it has been stopped. - * + * This exception is thrown by the broker when you try to use it after it has + * been stopped. + * * @author chirino */ public class BrokerStoppedException extends IllegalStateException { - private static final long serialVersionUID = -3435230276850902220L; + private static final long serialVersionUID = -3435230276850902220L; - public BrokerStoppedException() { - super(); - } + public BrokerStoppedException() { + super(); + } - public BrokerStoppedException(String message, Throwable cause) { - super(message); - initCause(cause); - } + public BrokerStoppedException(String message, Throwable cause) { + super(message); + initCause(cause); + } - public BrokerStoppedException(String s) { - super(s); - } + public BrokerStoppedException(String s) { + super(s); + } - public BrokerStoppedException(Throwable cause) { - initCause(cause); - } + public BrokerStoppedException(Throwable cause) { + initCause(cause); + } } diff --git a/activemq-core/src/main/java/org/apache/activemq/broker/Connection.java b/activemq-core/src/main/java/org/apache/activemq/broker/Connection.java index 370eb9dc86..f77b27f81d 100755 --- a/activemq-core/src/main/java/org/apache/activemq/broker/Connection.java +++ b/activemq-core/src/main/java/org/apache/activemq/broker/Connection.java @@ -24,7 +24,6 @@ import org.apache.activemq.command.Command; import org.apache.activemq.command.Response; /** - * * @version $Revision: 1.5 $ */ public interface Connection extends Service { @@ -37,8 +36,7 @@ public interface Connection extends Service { /** * Sends a message to the client. * - * @param message - * the message to send to the client. + * @param message the message to send to the client. */ public void dispatchSync(Command message); @@ -87,12 +85,12 @@ public interface Connection extends Service { * Returns the number of messages to be dispatched to this connection */ public int getDispatchQueueSize(); - + /** * Returns the statistics for this connection */ public ConnectionStatistics getStatistics(); - + /** * @return true if the Connection will process control commands */ @@ -101,10 +99,10 @@ public interface Connection extends Service { /** * @return the source address for this connection */ - public String getRemoteAddress(); + public String getRemoteAddress(); - public void serviceExceptionAsync(IOException e); - - public String getConnectionId(); + public void serviceExceptionAsync(IOException e); + + public String getConnectionId(); } diff --git a/activemq-core/src/main/java/org/apache/activemq/broker/TransportConnection.java b/activemq-core/src/main/java/org/apache/activemq/broker/TransportConnection.java index 0d180c6b6a..0d5ebb32f2 100755 --- a/activemq-core/src/main/java/org/apache/activemq/broker/TransportConnection.java +++ b/activemq-core/src/main/java/org/apache/activemq/broker/TransportConnection.java @@ -97,7 +97,8 @@ import org.apache.commons.logging.LogFactory; public class TransportConnection implements Service, Connection, Task, CommandVisitor { private static final Log LOG = LogFactory.getLog(TransportConnection.class); - private static final Log TRANSPORTLOG = LogFactory.getLog(TransportConnection.class.getName() + ".Transport"); + private static final Log TRANSPORTLOG = LogFactory.getLog(TransportConnection.class.getName() + + ".Transport"); private static final Log SERVICELOG = LogFactory.getLog(TransportConnection.class.getName() + ".Service"); // Keeps track of the broker and connector that created this connection. protected final Broker broker; @@ -190,7 +191,8 @@ public class TransportConnection implements Service, Connection, Task, CommandVi * @param taskRunnerFactory - can be null if you want direct dispatch to the * transport else commands are sent async. */ - public TransportConnection(TransportConnector connector, final Transport transport, Broker broker, TaskRunnerFactory taskRunnerFactory) { + public TransportConnection(TransportConnector connector, final Transport transport, Broker broker, + TaskRunnerFactory taskRunnerFactory) { this.connector = connector; this.broker = broker; RegionBroker rb = (RegionBroker)broker.getAdaptor(RegionBroker.class); @@ -270,7 +272,8 @@ public class TransportConnection implements Service, Connection, Task, CommandVi else if (e.getClass() == BrokerStoppedException.class) { if (!disposed.get()) { if (SERVICELOG.isDebugEnabled()) - SERVICELOG.debug("Broker has been stopped. Notifying client and closing his connection."); + SERVICELOG + .debug("Broker has been stopped. Notifying client and closing his connection."); ConnectionError ce = new ConnectionError(); ce.setException(e); dispatchSync(ce); @@ -400,7 +403,8 @@ public class TransportConnection implements Service, Connection, Task, CommandVi } TransactionState transactionState = cs.getTransactionState(info.getTransactionId()); if (transactionState == null) - throw new IllegalStateException("Cannot prepare a transaction that had not been started: " + info.getTransactionId()); + throw new IllegalStateException("Cannot prepare a transaction that had not been started: " + + info.getTransactionId()); // Avoid dups. if (!transactionState.isPrepared()) { transactionState.setPrepared(true); @@ -469,7 +473,8 @@ public class TransportConnection implements Service, Connection, Task, CommandVi return broker.messagePull(lookupConnectionState(pull.getConsumerId()).getContext(), pull); } - public Response processMessageDispatchNotification(MessageDispatchNotification notification) throws Exception { + public Response processMessageDispatchNotification(MessageDispatchNotification notification) + throws Exception { broker.processDispatchNotification(notification); return null; } @@ -498,7 +503,9 @@ public class TransportConnection implements Service, Connection, Task, CommandVi TransportConnectionState cs = lookupConnectionState(connectionId); SessionState ss = cs.getSessionState(sessionId); if (ss == null) - throw new IllegalStateException("Cannot add a producer to a session that had not been registered: " + sessionId); + throw new IllegalStateException( + "Cannot add a producer to a session that had not been registered: " + + sessionId); // Avoid replaying dup commands if (!ss.getProducerIds().contains(info.getProducerId())) { broker.addProducer(cs.getContext(), info); @@ -517,7 +524,9 @@ public class TransportConnection implements Service, Connection, Task, CommandVi TransportConnectionState cs = lookupConnectionState(connectionId); SessionState ss = cs.getSessionState(sessionId); if (ss == null) - throw new IllegalStateException("Cannot remove a producer from a session that had not been registered: " + sessionId); + throw new IllegalStateException( + "Cannot remove a producer from a session that had not been registered: " + + sessionId); ProducerState ps = ss.removeProducer(id); if (ps == null) throw new IllegalStateException("Cannot remove a producer that had not been registered: " + id); @@ -532,7 +541,9 @@ public class TransportConnection implements Service, Connection, Task, CommandVi TransportConnectionState cs = lookupConnectionState(connectionId); SessionState ss = cs.getSessionState(sessionId); if (ss == null) - throw new IllegalStateException("Cannot add a consumer to a session that had not been registered: " + sessionId); + throw new IllegalStateException( + "Cannot add a consumer to a session that had not been registered: " + + sessionId); // Avoid replaying dup commands if (!ss.getConsumerIds().contains(info.getConsumerId())) { broker.addConsumer(cs.getContext(), info); @@ -551,7 +562,9 @@ public class TransportConnection implements Service, Connection, Task, CommandVi TransportConnectionState cs = lookupConnectionState(connectionId); SessionState ss = cs.getSessionState(sessionId); if (ss == null) - throw new IllegalStateException("Cannot remove a consumer from a session that had not been registered: " + sessionId); + throw new IllegalStateException( + "Cannot remove a consumer from a session that had not been registered: " + + sessionId); ConsumerState consumerState = ss.removeConsumer(id); if (consumerState == null) throw new IllegalStateException("Cannot remove a consumer that had not been registered: " + id); @@ -628,7 +641,8 @@ public class TransportConnection implements Service, Connection, Task, CommandVi if (state.getConnection() != this) { LOG.debug("Killing previous stale connection: " + state.getConnection().getRemoteAddress()); state.getConnection().stop(); - LOG.debug("Connection " + getRemoteAddress() + " taking over previous connection: " + state.getConnection().getRemoteAddress()); + LOG.debug("Connection " + getRemoteAddress() + " taking over previous connection: " + + state.getConnection().getRemoteAddress()); state.setConnection(this); state.reset(info); } @@ -751,7 +765,8 @@ public class TransportConnection implements Service, Connection, Task, CommandVi } protected void processDispatch(Command command) throws IOException { - final MessageDispatch messageDispatch = (MessageDispatch)(command.isMessageDispatch() ? command : null); + final MessageDispatch messageDispatch = (MessageDispatch)(command.isMessageDispatch() + ? command : null); try { if (!disposed.get()) { if (messageDispatch != null) { @@ -831,7 +846,8 @@ public class TransportConnection implements Service, Connection, Task, CommandVi transport.start(); if (taskRunnerFactory != null) { - taskRunner = taskRunnerFactory.createTaskRunner(this, "ActiveMQ Connection Dispatcher: " + getRemoteAddress()); + taskRunner = taskRunnerFactory.createTaskRunner(this, "ActiveMQ Connection Dispatcher: " + + getRemoteAddress()); } else { taskRunner = null; } @@ -1098,7 +1114,8 @@ public class TransportConnection implements Service, Connection, Task, CommandVi uri = URISupport.createURIWithQuery(uri, URISupport.createQueryString(map)); Transport localTransport = TransportFactory.connect(uri); Transport remoteBridgeTransport = new ResponseCorrelator(transport); - duplexBridge = NetworkBridgeFactory.createBridge(config, localTransport, remoteBridgeTransport); + duplexBridge = NetworkBridgeFactory.createBridge(config, localTransport, + remoteBridgeTransport); // now turn duplex off this side info.setDuplexConnection(false); duplexBridge.setCreatedByDuplex(true); @@ -1163,7 +1180,8 @@ public class TransportConnection implements Service, Connection, Task, CommandVi ProducerState producerState = ss.getProducerState(id); if (producerState != null && producerState.getInfo() != null) { ProducerInfo info = producerState.getInfo(); - result.setMutable(info.getDestination() == null || info.getDestination().isComposite()); + result.setMutable(info.getDestination() == null + || info.getDestination().isComposite()); } } producerExchanges.put(id, result); @@ -1267,7 +1285,8 @@ public class TransportConnection implements Service, Connection, Task, CommandVi // // ///////////////////////////////////////////////////////////////// - protected TransportConnectionState registerConnectionState(ConnectionId connectionId, TransportConnectionState state) { + protected TransportConnectionState registerConnectionState(ConnectionId connectionId, + TransportConnectionState state) { TransportConnectionState rc = connectionState; connectionState = state; return rc; @@ -1290,35 +1309,44 @@ public class TransportConnection implements Service, Connection, Task, CommandVi protected TransportConnectionState lookupConnectionState(String connectionId) { TransportConnectionState cs = connectionState; if (cs == null) - throw new IllegalStateException("Cannot lookup a connectionId for a connection that had not been registered: " + connectionId); + throw new IllegalStateException( + "Cannot lookup a connectionId for a connection that had not been registered: " + + connectionId); return cs; } protected TransportConnectionState lookupConnectionState(ConsumerId id) { TransportConnectionState cs = connectionState; if (cs == null) - throw new IllegalStateException("Cannot lookup a consumer from a connection that had not been registered: " + id.getParentId().getParentId()); + throw new IllegalStateException( + "Cannot lookup a consumer from a connection that had not been registered: " + + id.getParentId().getParentId()); return cs; } protected TransportConnectionState lookupConnectionState(ProducerId id) { TransportConnectionState cs = connectionState; if (cs == null) - throw new IllegalStateException("Cannot lookup a producer from a connection that had not been registered: " + id.getParentId().getParentId()); + throw new IllegalStateException( + "Cannot lookup a producer from a connection that had not been registered: " + + id.getParentId().getParentId()); return cs; } protected TransportConnectionState lookupConnectionState(SessionId id) { TransportConnectionState cs = connectionState; if (cs == null) - throw new IllegalStateException("Cannot lookup a session from a connection that had not been registered: " + id.getParentId()); + throw new IllegalStateException( + "Cannot lookup a session from a connection that had not been registered: " + + id.getParentId()); return cs; } protected TransportConnectionState lookupConnectionState(ConnectionId connectionId) { TransportConnectionState cs = connectionState; if (cs == null) - throw new IllegalStateException("Cannot lookup a connection that had not been registered: " + connectionId); + throw new IllegalStateException("Cannot lookup a connection that had not been registered: " + + connectionId); return cs; } diff --git a/activemq-core/src/main/java/org/apache/activemq/broker/jmx/BrokerView.java b/activemq-core/src/main/java/org/apache/activemq/broker/jmx/BrokerView.java index d555cec9b0..a838809983 100755 --- a/activemq-core/src/main/java/org/apache/activemq/broker/jmx/BrokerView.java +++ b/activemq-core/src/main/java/org/apache/activemq/broker/jmx/BrokerView.java @@ -31,16 +31,16 @@ import org.apache.activemq.command.ConsumerInfo; import org.apache.activemq.command.RemoveSubscriptionInfo; public class BrokerView implements BrokerViewMBean { - + final ManagedRegionBroker broker; - private final BrokerService brokerService; + private final BrokerService brokerService; private final AtomicInteger sessionIdCounter = new AtomicInteger(0); public BrokerView(BrokerService brokerService, ManagedRegionBroker managedBroker) throws Exception { this.brokerService = brokerService; - this.broker = managedBroker; + this.broker = managedBroker; } - + public ManagedRegionBroker getBroker() { return broker; } @@ -48,31 +48,35 @@ public class BrokerView implements BrokerViewMBean { public String getBrokerId() { return broker.getBrokerId().toString(); } - + public void gc() throws Exception { - brokerService.getBroker().gc(); + brokerService.getBroker().gc(); } public void start() throws Exception { - brokerService.start(); + brokerService.start(); } - + public void stop() throws Exception { - brokerService.stop(); + brokerService.stop(); } - + public long getTotalEnqueueCount() { - return broker.getDestinationStatistics().getEnqueues().getCount(); + return broker.getDestinationStatistics().getEnqueues().getCount(); } + public long getTotalDequeueCount() { return broker.getDestinationStatistics().getDequeues().getCount(); } + public long getTotalConsumerCount() { return broker.getDestinationStatistics().getConsumers().getCount(); } + public long getTotalMessageCount() { return broker.getDestinationStatistics().getMessages().getCount(); - } + } + public long getTotalMessagesCached() { return broker.getDestinationStatistics().getMessagesCached().getCount(); } @@ -80,71 +84,72 @@ public class BrokerView implements BrokerViewMBean { public int getMemoryPercentageUsed() { return brokerService.getMemoryManager().getPercentUsage(); } + public long getMemoryLimit() { return brokerService.getMemoryManager().getLimit(); } + public void setMemoryLimit(long limit) { - brokerService.getMemoryManager().setLimit(limit); + brokerService.getMemoryManager().setLimit(limit); } - + public void resetStatistics() { broker.getDestinationStatistics().reset(); } - + public void enableStatistics() { broker.getDestinationStatistics().setEnabled(true); - } - + } + public void disableStatistics() { broker.getDestinationStatistics().setEnabled(false); - } - - public boolean isStatisticsEnabled() { - return broker.getDestinationStatistics().isEnabled(); } - + + public boolean isStatisticsEnabled() { + return broker.getDestinationStatistics().isEnabled(); + } public void terminateJVM(int exitCode) { System.exit(exitCode); } - public ObjectName[] getTopics(){ + public ObjectName[] getTopics() { return broker.getTopics(); } - public ObjectName[] getQueues(){ + public ObjectName[] getQueues() { return broker.getQueues(); } - public ObjectName[] getTemporaryTopics(){ + public ObjectName[] getTemporaryTopics() { return broker.getTemporaryTopics(); } - public ObjectName[] getTemporaryQueues(){ + public ObjectName[] getTemporaryQueues() { return broker.getTemporaryQueues(); } - public ObjectName[] getTopicSubscribers(){ - return broker.getTemporaryTopicSubscribers(); - } - - public ObjectName[] getDurableTopicSubscribers(){ - return broker.getDurableTopicSubscribers(); - } - - public ObjectName[] getQueueSubscribers(){ - return broker.getQueueSubscribers(); - } - - public ObjectName[] getTemporaryTopicSubscribers(){ + public ObjectName[] getTopicSubscribers() { return broker.getTemporaryTopicSubscribers(); } - public ObjectName[] getTemporaryQueueSubscribers(){ + public ObjectName[] getDurableTopicSubscribers() { + return broker.getDurableTopicSubscribers(); + } + + public ObjectName[] getQueueSubscribers() { + return broker.getQueueSubscribers(); + } + + public ObjectName[] getTemporaryTopicSubscribers() { + return broker.getTemporaryTopicSubscribers(); + } + + public ObjectName[] getTemporaryQueueSubscribers() { return broker.getTemporaryQueueSubscribers(); } - - public ObjectName[] getInactiveDurableTopicSubscribers(){ + + public ObjectName[] getInactiveDurableTopicSubscribers() { return broker.getInactiveDurableTopicSubscribers(); } @@ -157,14 +162,17 @@ public class BrokerView implements BrokerViewMBean { } public void removeTopic(String name) throws Exception { - broker.removeDestination(getConnectionContext(broker.getContextBroker()), new ActiveMQTopic(name), 1000); + broker.removeDestination(getConnectionContext(broker.getContextBroker()), new ActiveMQTopic(name), + 1000); } public void removeQueue(String name) throws Exception { - broker.removeDestination(getConnectionContext(broker.getContextBroker()), new ActiveMQQueue(name), 1000); + broker.removeDestination(getConnectionContext(broker.getContextBroker()), new ActiveMQQueue(name), + 1000); } - - public ObjectName createDurableSubscriber(String clientId, String subscriberName, String topicName, String selector) throws Exception { + + public ObjectName createDurableSubscriber(String clientId, String subscriberName, String topicName, + String selector) throws Exception { ConnectionContext context = new ConnectionContext(); context.setBroker(broker); context.setClientId(clientId); @@ -194,11 +202,10 @@ public class BrokerView implements BrokerViewMBean { context.setClientId(clientId); broker.removeSubscription(context, info); } - - + /** - * Returns the broker's administration connection context used for configuring the broker - * at startup + * Returns the broker's administration connection context used for + * configuring the broker at startup */ public static ConnectionContext getConnectionContext(Broker broker) { ConnectionContext adminConnectionContext = broker.getAdminConnectionContext(); @@ -208,11 +215,12 @@ public class BrokerView implements BrokerViewMBean { } return adminConnectionContext; } - + /** - * Factory method to create the new administration connection context object. - * Note this method is here rather than inside a default broker implementation to - * ensure that the broker reference inside it is the outer most interceptor + * Factory method to create the new administration connection context + * object. Note this method is here rather than inside a default broker + * implementation to ensure that the broker reference inside it is the outer + * most interceptor */ protected static ConnectionContext createAdminConnectionContext(Broker broker) { ConnectionContext context = new ConnectionContext(); diff --git a/activemq-core/src/main/java/org/apache/activemq/broker/jmx/ConnectionView.java b/activemq-core/src/main/java/org/apache/activemq/broker/jmx/ConnectionView.java index a07a2a5555..e836ffed08 100755 --- a/activemq-core/src/main/java/org/apache/activemq/broker/jmx/ConnectionView.java +++ b/activemq-core/src/main/java/org/apache/activemq/broker/jmx/ConnectionView.java @@ -33,36 +33,34 @@ public class ConnectionView implements ConnectionViewMBean { public void stop() throws Exception { connection.stop(); } - + /** * @return true if the Connection is slow */ public boolean isSlow() { return connection.isSlow(); } - + /** * @return if after being marked, the Connection is still writing */ public boolean isBlocked() { return connection.isBlocked(); } - - + /** * @return true if the Connection is connected */ public boolean isConnected() { return connection.isConnected(); } - + /** * @return true if the Connection is active */ public boolean isActive() { return connection.isActive(); } - /** * Returns the number of messages to be dispatched to this connection @@ -70,7 +68,7 @@ public class ConnectionView implements ConnectionViewMBean { public int getDispatchQueueSize() { return connection.getDispatchQueueSize(); } - + /** * Resets the statistics */ @@ -85,7 +83,7 @@ public class ConnectionView implements ConnectionViewMBean { */ public long getEnqueueCount() { return connection.getStatistics().getEnqueues().getCount(); - + } /** @@ -97,12 +95,12 @@ public class ConnectionView implements ConnectionViewMBean { return connection.getStatistics().getDequeues().getCount(); } - public String getRemoteAddress() { - return connection.getRemoteAddress(); - } + public String getRemoteAddress() { + return connection.getRemoteAddress(); + } - public String getConnectionId() { - return connection.getConnectionId(); - } + public String getConnectionId() { + return connection.getConnectionId(); + } } diff --git a/activemq-core/src/main/java/org/apache/activemq/broker/jmx/ManagedTransportConnection.java b/activemq-core/src/main/java/org/apache/activemq/broker/jmx/ManagedTransportConnection.java index 2327fd1fb8..dc7de3407c 100644 --- a/activemq-core/src/main/java/org/apache/activemq/broker/jmx/ManagedTransportConnection.java +++ b/activemq-core/src/main/java/org/apache/activemq/broker/jmx/ManagedTransportConnection.java @@ -47,10 +47,11 @@ public class ManagedTransportConnection extends TransportConnection { private ConnectionViewMBean mbean; private ObjectName byClientIdName; - private ObjectName byAddressName; + private ObjectName byAddressName; - public ManagedTransportConnection(TransportConnector connector, Transport transport, Broker broker, TaskRunnerFactory factory, MBeanServer server, - ObjectName connectorName) throws IOException { + public ManagedTransportConnection(TransportConnector connector, Transport transport, Broker broker, + TaskRunnerFactory factory, MBeanServer server, ObjectName connectorName) + throws IOException { super(connector, transport, broker, factory); this.server = server; this.connectorName = connectorName; @@ -64,12 +65,12 @@ public class ManagedTransportConnection extends TransportConnection { setPendingStop(true); return; } - synchronized(this) { - unregisterMBean(byClientIdName); - unregisterMBean(byAddressName); - byClientIdName=null; - byAddressName=null; - } + synchronized (this) { + unregisterMBean(byClientIdName); + unregisterMBean(byAddressName); + byClientIdName = null; + byAddressName = null; + } super.doStop(); } @@ -85,9 +86,9 @@ public class ManagedTransportConnection extends TransportConnection { Response answer = super.processAddConnection(info); String clientId = info.getClientId(); if (clientId != null) { - if(byClientIdName==null) { - byClientIdName = createByClientIdObjectName(clientId); - registerMBean(byClientIdName); + if (byClientIdName == null) { + byClientIdName = createByClientIdObjectName(clientId); + registerMBean(byClientIdName); } } return answer; @@ -96,24 +97,23 @@ public class ManagedTransportConnection extends TransportConnection { // Implementation methods // ------------------------------------------------------------------------- protected void registerMBean(ObjectName name) { - if( name!=null ) { - try { - server.registerMBean(mbean, name); - } catch (Throwable e) { - log.warn("Failed to register MBean: "+name); - log.debug("Failure reason: "+e,e); - } - } + if (name != null) { + try { + server.registerMBean(mbean, name); + } catch (Throwable e) { + log.warn("Failed to register MBean: " + name); + log.debug("Failure reason: " + e, e); + } + } } protected void unregisterMBean(ObjectName name) { if (name != null) { try { server.unregisterMBean(name); - } - catch (Throwable e) { + } catch (Throwable e) { log.warn("Failed to unregister mbean: " + name); - log.debug("Failure reason: "+e,e); + log.debug("Failure reason: " + e, e); } } } @@ -122,36 +122,29 @@ public class ManagedTransportConnection extends TransportConnection { // Build the object name for the destination Hashtable map = connectorName.getKeyPropertyList(); try { - return new ObjectName( - connectorName.getDomain()+":"+ - "BrokerName="+JMXSupport.encodeObjectNamePart((String) map.get("BrokerName"))+","+ - "Type=Connection,"+ - "ConnectorName="+JMXSupport.encodeObjectNamePart((String) map.get("ConnectorName"))+","+ - "ViewType="+JMXSupport.encodeObjectNamePart(type)+","+ - "Name="+JMXSupport.encodeObjectNamePart(value) - ); - } - catch (Throwable e) { + return new ObjectName(connectorName.getDomain() + ":" + "BrokerName=" + + JMXSupport.encodeObjectNamePart((String)map.get("BrokerName")) + "," + + "Type=Connection," + "ConnectorName=" + + JMXSupport.encodeObjectNamePart((String)map.get("ConnectorName")) + "," + + "ViewType=" + JMXSupport.encodeObjectNamePart(type) + "," + "Name=" + + JMXSupport.encodeObjectNamePart(value)); + } catch (Throwable e) { throw IOExceptionSupport.create(e); } } - + protected ObjectName createByClientIdObjectName(String value) throws IOException { // Build the object name for the destination Hashtable map = connectorName.getKeyPropertyList(); try { - return new ObjectName( - connectorName.getDomain()+":"+ - "BrokerName="+JMXSupport.encodeObjectNamePart((String) map.get("BrokerName"))+","+ - "Type=Connection,"+ - "ConnectorName="+JMXSupport.encodeObjectNamePart((String) map.get("ConnectorName"))+","+ - "Connection="+JMXSupport.encodeObjectNamePart(value) - ); - } - catch (Throwable e) { + return new ObjectName(connectorName.getDomain() + ":" + "BrokerName=" + + JMXSupport.encodeObjectNamePart((String)map.get("BrokerName")) + "," + + "Type=Connection," + "ConnectorName=" + + JMXSupport.encodeObjectNamePart((String)map.get("ConnectorName")) + "," + + "Connection=" + JMXSupport.encodeObjectNamePart(value)); + } catch (Throwable e) { throw IOExceptionSupport.create(e); } } - } diff --git a/activemq-core/src/main/java/org/apache/activemq/broker/jmx/NetworkBridgeView.java b/activemq-core/src/main/java/org/apache/activemq/broker/jmx/NetworkBridgeView.java index 4d06be87dd..7eb9f505c2 100644 --- a/activemq-core/src/main/java/org/apache/activemq/broker/jmx/NetworkBridgeView.java +++ b/activemq-core/src/main/java/org/apache/activemq/broker/jmx/NetworkBridgeView.java @@ -22,40 +22,40 @@ public class NetworkBridgeView implements NetworkBridgeViewMBean { private final NetworkBridge bridge; - public NetworkBridgeView(NetworkBridge bridge) { - this.bridge = bridge; + public NetworkBridgeView(NetworkBridge bridge) { + this.bridge = bridge; } - + public void start() throws Exception { - bridge.start(); + bridge.start(); } public void stop() throws Exception { - bridge.stop(); + bridge.stop(); } - + public String getLocalAddress() { - return bridge.getLocalAddress(); + return bridge.getLocalAddress(); } public String getRemoteAddress() { - return bridge.getRemoteAddress(); + return bridge.getRemoteAddress(); } public String getRemoteBrokerName() { - return bridge.getRemoteBrokerName(); + return bridge.getRemoteBrokerName(); } public String getLocalBrokerName() { - return bridge.getLocalBrokerName(); + return bridge.getLocalBrokerName(); } public long getEnqueueCounter() { - return bridge.getEnqueueCounter(); + return bridge.getEnqueueCounter(); } public long getDequeueCounter() { - return bridge.getDequeueCounter(); + return bridge.getDequeueCounter(); } } diff --git a/activemq-core/src/main/java/org/apache/activemq/broker/jmx/NetworkConnectorView.java b/activemq-core/src/main/java/org/apache/activemq/broker/jmx/NetworkConnectorView.java index 909fc96924..391bad9a6b 100644 --- a/activemq-core/src/main/java/org/apache/activemq/broker/jmx/NetworkConnectorView.java +++ b/activemq-core/src/main/java/org/apache/activemq/broker/jmx/NetworkConnectorView.java @@ -25,92 +25,92 @@ public class NetworkConnectorView implements NetworkConnectorViewMBean { public NetworkConnectorView(NetworkConnector connector) { this.connector = connector; } - + public void start() throws Exception { connector.start(); } public void stop() throws Exception { - connector.stop(); + connector.stop(); } - public String getName() { - return connector.getName(); - } + public String getName() { + return connector.getName(); + } - public int getNetworkTTL() { - return connector.getNetworkTTL(); - } + public int getNetworkTTL() { + return connector.getNetworkTTL(); + } - public int getPrefetchSize() { - return connector.getPrefetchSize(); - } + public int getPrefetchSize() { + return connector.getPrefetchSize(); + } - public String getUserName() { - return connector.getUserName(); - } + public String getUserName() { + return connector.getUserName(); + } - public boolean isBridgeTempDestinations() { - return connector.isBridgeTempDestinations(); - } + public boolean isBridgeTempDestinations() { + return connector.isBridgeTempDestinations(); + } - public boolean isConduitSubscriptions() { - return connector.isConduitSubscriptions(); - } + public boolean isConduitSubscriptions() { + return connector.isConduitSubscriptions(); + } - public boolean isDecreaseNetworkConsumerPriority() { - return connector.isDecreaseNetworkConsumerPriority(); - } + public boolean isDecreaseNetworkConsumerPriority() { + return connector.isDecreaseNetworkConsumerPriority(); + } - public boolean isDispatchAsync() { - return connector.isDispatchAsync(); - } + public boolean isDispatchAsync() { + return connector.isDispatchAsync(); + } - public boolean isDynamicOnly() { - return connector.isDynamicOnly(); - } + public boolean isDynamicOnly() { + return connector.isDynamicOnly(); + } - public void setBridgeTempDestinations(boolean bridgeTempDestinations) { - connector.setBridgeTempDestinations(bridgeTempDestinations); - } + public void setBridgeTempDestinations(boolean bridgeTempDestinations) { + connector.setBridgeTempDestinations(bridgeTempDestinations); + } - public void setConduitSubscriptions(boolean conduitSubscriptions) { - connector.setConduitSubscriptions(conduitSubscriptions); - } + public void setConduitSubscriptions(boolean conduitSubscriptions) { + connector.setConduitSubscriptions(conduitSubscriptions); + } - public void setDispatchAsync(boolean dispatchAsync) { - connector.setDispatchAsync(dispatchAsync); - } + public void setDispatchAsync(boolean dispatchAsync) { + connector.setDispatchAsync(dispatchAsync); + } - public void setDynamicOnly(boolean dynamicOnly) { - connector.setDynamicOnly(dynamicOnly); - } + public void setDynamicOnly(boolean dynamicOnly) { + connector.setDynamicOnly(dynamicOnly); + } - public void setNetworkTTL(int networkTTL) { - connector.setNetworkTTL(networkTTL); - } + public void setNetworkTTL(int networkTTL) { + connector.setNetworkTTL(networkTTL); + } - public void setPassword(String password) { - connector.setPassword(password); - } + public void setPassword(String password) { + connector.setPassword(password); + } - public void setPrefetchSize(int prefetchSize) { - connector.setPrefetchSize(prefetchSize); - } + public void setPrefetchSize(int prefetchSize) { + connector.setPrefetchSize(prefetchSize); + } - public void setUserName(String userName) { - connector.setUserName(userName); - } + public void setUserName(String userName) { + connector.setUserName(userName); + } - public String getPassword() { - String pw = connector.getPassword(); - // Hide the password for security reasons. - if( pw!= null ) - pw = pw.replaceAll(".", "*"); - return pw; - } + public String getPassword() { + String pw = connector.getPassword(); + // Hide the password for security reasons. + if (pw != null) + pw = pw.replaceAll(".", "*"); + return pw; + } - public void setDecreaseNetworkConsumerPriority(boolean decreaseNetworkConsumerPriority) { - connector.setDecreaseNetworkConsumerPriority(decreaseNetworkConsumerPriority); - } + public void setDecreaseNetworkConsumerPriority(boolean decreaseNetworkConsumerPriority) { + connector.setDecreaseNetworkConsumerPriority(decreaseNetworkConsumerPriority); + } } diff --git a/activemq-core/src/main/java/org/apache/activemq/broker/jmx/NetworkConnectorViewMBean.java b/activemq-core/src/main/java/org/apache/activemq/broker/jmx/NetworkConnectorViewMBean.java index feff5158e7..2cbac83c33 100644 --- a/activemq-core/src/main/java/org/apache/activemq/broker/jmx/NetworkConnectorViewMBean.java +++ b/activemq-core/src/main/java/org/apache/activemq/broker/jmx/NetworkConnectorViewMBean.java @@ -20,24 +20,42 @@ import org.apache.activemq.Service; public interface NetworkConnectorViewMBean extends Service { - public String getName(); - public int getNetworkTTL(); - public int getPrefetchSize(); - public String getUserName(); - public boolean isBridgeTempDestinations(); - public boolean isConduitSubscriptions(); - public boolean isDecreaseNetworkConsumerPriority(); - public boolean isDispatchAsync(); - public boolean isDynamicOnly(); - public void setBridgeTempDestinations(boolean bridgeTempDestinations); - public void setConduitSubscriptions(boolean conduitSubscriptions); - public void setDispatchAsync(boolean dispatchAsync); - public void setDynamicOnly(boolean dynamicOnly); - public void setNetworkTTL(int networkTTL); - public void setPassword(String password); - public void setPrefetchSize(int prefetchSize); - public void setUserName(String userName); - public String getPassword(); - public void setDecreaseNetworkConsumerPriority(boolean decreaseNetworkConsumerPriority); + public String getName(); + + public int getNetworkTTL(); + + public int getPrefetchSize(); + + public String getUserName(); + + public boolean isBridgeTempDestinations(); + + public boolean isConduitSubscriptions(); + + public boolean isDecreaseNetworkConsumerPriority(); + + public boolean isDispatchAsync(); + + public boolean isDynamicOnly(); + + public void setBridgeTempDestinations(boolean bridgeTempDestinations); + + public void setConduitSubscriptions(boolean conduitSubscriptions); + + public void setDispatchAsync(boolean dispatchAsync); + + public void setDynamicOnly(boolean dynamicOnly); + + public void setNetworkTTL(int networkTTL); + + public void setPassword(String password); + + public void setPrefetchSize(int prefetchSize); + + public void setUserName(String userName); + + public String getPassword(); + + public void setDecreaseNetworkConsumerPriority(boolean decreaseNetworkConsumerPriority); } diff --git a/activemq-core/src/main/java/org/apache/activemq/broker/jmx/SubscriptionView.java b/activemq-core/src/main/java/org/apache/activemq/broker/jmx/SubscriptionView.java index 4b20025159..73341d1c05 100755 --- a/activemq-core/src/main/java/org/apache/activemq/broker/jmx/SubscriptionView.java +++ b/activemq-core/src/main/java/org/apache/activemq/broker/jmx/SubscriptionView.java @@ -22,40 +22,37 @@ import org.apache.activemq.command.ConsumerInfo; import javax.jms.InvalidSelectorException; - - /** * @version $Revision: 1.5 $ */ public class SubscriptionView implements SubscriptionViewMBean { - - + protected final Subscription subscription; protected final String clientId; - - + /** * Constructor + * * @param subs */ - public SubscriptionView(String clientId,Subscription subs){ + public SubscriptionView(String clientId, Subscription subs) { this.clientId = clientId; this.subscription = subs; } - + /** * @return the clientId */ - public String getClientId(){ + public String getClientId() { return clientId; } - + /** * @return the id of the Connection the Subscription is on */ - public String getConnectionId(){ + public String getConnectionId() { ConsumerInfo info = getConsumerInfo(); - if (info != null){ + if (info != null) { return info.getConsumerId().getConnectionId(); } return "NOTSET"; @@ -64,9 +61,9 @@ public class SubscriptionView implements SubscriptionViewMBean { /** * @return the id of the Session the subscription is on */ - public long getSessionId(){ + public long getSessionId() { ConsumerInfo info = getConsumerInfo(); - if (info != null){ + if (info != null) { return info.getConsumerId().getSessionId(); } return 0; @@ -75,9 +72,9 @@ public class SubscriptionView implements SubscriptionViewMBean { /** * @return the id of the Subscription */ - public long getSubcriptionId(){ + public long getSubcriptionId() { ConsumerInfo info = getConsumerInfo(); - if (info != null){ + if (info != null) { return info.getConsumerId().getValue(); } return 0; @@ -86,9 +83,9 @@ public class SubscriptionView implements SubscriptionViewMBean { /** * @return the destination name */ - public String getDestinationName(){ + public String getDestinationName() { ConsumerInfo info = getConsumerInfo(); - if (info != null){ + if (info != null) { ActiveMQDestination dest = info.getDestination(); return dest.getPhysicalName(); } @@ -105,8 +102,7 @@ public class SubscriptionView implements SubscriptionViewMBean { public void setSelector(String selector) throws InvalidSelectorException, UnsupportedOperationException { if (subscription != null) { subscription.setSelector(selector); - } - else { + } else { throw new UnsupportedOperationException("No subscription object"); } } @@ -114,9 +110,9 @@ public class SubscriptionView implements SubscriptionViewMBean { /** * @return true if the destination is a Queue */ - public boolean isDestinationQueue(){ + public boolean isDestinationQueue() { ConsumerInfo info = getConsumerInfo(); - if (info != null){ + if (info != null) { ActiveMQDestination dest = info.getDestination(); return dest.isQueue(); } @@ -126,9 +122,9 @@ public class SubscriptionView implements SubscriptionViewMBean { /** * @return true of the destination is a Topic */ - public boolean isDestinationTopic(){ + public boolean isDestinationTopic() { ConsumerInfo info = getConsumerInfo(); - if (info != null){ + if (info != null) { ActiveMQDestination dest = info.getDestination(); return dest.isTopic(); } @@ -138,32 +134,32 @@ public class SubscriptionView implements SubscriptionViewMBean { /** * @return true if the destination is temporary */ - public boolean isDestinationTemporary(){ + public boolean isDestinationTemporary() { ConsumerInfo info = getConsumerInfo(); - if (info != null){ + if (info != null) { ActiveMQDestination dest = info.getDestination(); return dest.isTemporary(); } return false; } - + /** * @return true if the subscriber is active */ - public boolean isActive(){ + public boolean isActive() { return true; } /** - * The subscription should release as may references as it can to help the garbage collector - * reclaim memory. + * The subscription should release as may references as it can to help the + * garbage collector reclaim memory. */ - public void gc(){ - if (subscription != null){ - subscription.gc(); + public void gc() { + if (subscription != null) { + subscription.gc(); } } - + /** * @return whether or not the subscriber is retroactive or not */ @@ -171,7 +167,7 @@ public class SubscriptionView implements SubscriptionViewMBean { ConsumerInfo info = getConsumerInfo(); return info != null ? info.isRetroactive() : false; } - + /** * @return whether or not the subscriber is an exclusive consumer */ @@ -179,8 +175,7 @@ public class SubscriptionView implements SubscriptionViewMBean { ConsumerInfo info = getConsumerInfo(); return info != null ? info.isExclusive() : false; } - - + /** * @return whether or not the subscriber is durable (persistent) */ @@ -188,7 +183,7 @@ public class SubscriptionView implements SubscriptionViewMBean { ConsumerInfo info = getConsumerInfo(); return info != null ? info.isDurable() : false; } - + /** * @return whether or not the subscriber ignores local messages */ @@ -196,17 +191,18 @@ public class SubscriptionView implements SubscriptionViewMBean { ConsumerInfo info = getConsumerInfo(); return info != null ? info.isNoLocal() : false; } - - + /** - * @return the maximum number of pending messages allowed in addition to the prefetch size. If enabled - * to a non-zero value then this will perform eviction of messages for slow consumers on non-durable topics. + * @return the maximum number of pending messages allowed in addition to the + * prefetch size. If enabled to a non-zero value then this will + * perform eviction of messages for slow consumers on non-durable + * topics. */ public int getMaximumPendingMessageLimit() { ConsumerInfo info = getConsumerInfo(); return info != null ? info.getMaximumPendingMessageLimit() : 0; } - + /** * @return the consumer priority */ @@ -214,29 +210,30 @@ public class SubscriptionView implements SubscriptionViewMBean { ConsumerInfo info = getConsumerInfo(); return info != null ? info.getPriority() : 0; } - + /** - * @return the name of the consumer which is only used for durable consumers. + * @return the name of the consumer which is only used for durable + * consumers. */ public String getSubcriptionName() { ConsumerInfo info = getConsumerInfo(); return info != null ? info.getSubscriptionName() : null; } - + /** * @return number of messages pending delivery */ - public int getPendingQueueSize(){ + public int getPendingQueueSize() { return subscription != null ? subscription.getPendingQueueSize() : 0; } - + /** * @return number of messages dispatched */ - public int getDispatchedQueueSize(){ + public int getDispatchedQueueSize() { return subscription != null ? subscription.getDispatchedQueueSize() : 0; } - + /** * @return number of messages that matched the subscription */ @@ -258,15 +255,15 @@ public class SubscriptionView implements SubscriptionViewMBean { return subscription != null ? subscription.getDequeueCounter() : 0; } - protected ConsumerInfo getConsumerInfo(){ + protected ConsumerInfo getConsumerInfo() { return subscription != null ? subscription.getConsumerInfo() : null; } - + /** - *@return pretty print + * @return pretty print */ - public String toString(){ - return "SubscriptionView: " + getClientId() + ":" + getConnectionId(); + public String toString() { + return "SubscriptionView: " + getClientId() + ":" + getConnectionId(); } /** diff --git a/activemq-core/src/main/java/org/apache/activemq/broker/jmx/TopicSubscriptionView.java b/activemq-core/src/main/java/org/apache/activemq/broker/jmx/TopicSubscriptionView.java index f404757328..0687066976 100644 --- a/activemq-core/src/main/java/org/apache/activemq/broker/jmx/TopicSubscriptionView.java +++ b/activemq-core/src/main/java/org/apache/activemq/broker/jmx/TopicSubscriptionView.java @@ -29,7 +29,7 @@ public class TopicSubscriptionView extends SubscriptionView implements TopicSubs } protected TopicSubscription getTopicSubscription() { - return (TopicSubscription) subscription; + return (TopicSubscription)subscription; } /** @@ -47,14 +47,14 @@ public class TopicSubscriptionView extends SubscriptionView implements TopicSubs TopicSubscription topicSubscription = getTopicSubscription(); return topicSubscription != null ? topicSubscription.getMaximumPendingMessages() : 0; } - + /** * */ public void setMaximumPendingQueueSize(int max) { TopicSubscription topicSubscription = getTopicSubscription(); - if ( topicSubscription != null ) { - topicSubscription.setMaximumPendingMessages(max); + if (topicSubscription != null) { + topicSubscription.setMaximumPendingMessages(max); } } } diff --git a/activemq-core/src/main/java/org/apache/activemq/broker/region/Destination.java b/activemq-core/src/main/java/org/apache/activemq/broker/region/Destination.java index 08d42fd7e8..a726da8927 100755 --- a/activemq-core/src/main/java/org/apache/activemq/broker/region/Destination.java +++ b/activemq-core/src/main/java/org/apache/activemq/broker/region/Destination.java @@ -27,32 +27,37 @@ import org.apache.activemq.command.Message; import org.apache.activemq.command.MessageAck; import org.apache.activemq.memory.UsageManager; import org.apache.activemq.store.MessageStore; -import org.apache.activemq.store.TopicMessageStore; /** - * * @version $Revision: 1.12 $ */ public interface Destination extends Service { void addSubscription(ConnectionContext context, Subscription sub) throws Exception; + void removeSubscription(ConnectionContext context, Subscription sub) throws Exception; - + void send(ProducerBrokerExchange producerExchange, Message messageSend) throws Exception; + boolean lock(MessageReference node, LockOwner lockOwner); + void acknowledge(ConnectionContext context, Subscription sub, final MessageAck ack, final MessageReference node) throws IOException; - + void gc(); - + ActiveMQDestination getActiveMQDestination(); + UsageManager getUsageManager(); void dispose(ConnectionContext context) throws IOException; - + DestinationStatistics getDestinationStatistics(); + DeadLetterStrategy getDeadLetterStrategy(); - + public Message[] browse(); + public String getName(); - public MessageStore getMessageStore(); + + public MessageStore getMessageStore(); } diff --git a/activemq-core/src/main/java/org/apache/activemq/broker/region/DestinationFilter.java b/activemq-core/src/main/java/org/apache/activemq/broker/region/DestinationFilter.java index fffbdd8e90..9869d2a593 100644 --- a/activemq-core/src/main/java/org/apache/activemq/broker/region/DestinationFilter.java +++ b/activemq-core/src/main/java/org/apache/activemq/broker/region/DestinationFilter.java @@ -16,6 +16,10 @@ */ package org.apache.activemq.broker.region; +import java.io.IOException; +import java.util.Iterator; +import java.util.Set; + import org.apache.activemq.broker.Broker; import org.apache.activemq.broker.ConnectionContext; import org.apache.activemq.broker.ProducerBrokerExchange; @@ -26,10 +30,6 @@ import org.apache.activemq.command.MessageAck; import org.apache.activemq.memory.UsageManager; import org.apache.activemq.store.MessageStore; -import java.io.IOException; -import java.util.Iterator; -import java.util.Set; - /** * * @version $Revision$ @@ -42,7 +42,8 @@ public class DestinationFilter implements Destination { this.next = next; } - public void acknowledge(ConnectionContext context, Subscription sub, MessageAck ack, MessageReference node) throws IOException { + public void acknowledge(ConnectionContext context, Subscription sub, MessageAck ack, MessageReference node) + throws IOException { next.acknowledge(context, sub, ack, node); } @@ -105,17 +106,18 @@ public class DestinationFilter implements Destination { /** * Sends a message to the given destination which may be a wildcard */ - protected void send(ProducerBrokerExchange context, Message message, ActiveMQDestination destination) throws Exception { + protected void send(ProducerBrokerExchange context, Message message, ActiveMQDestination destination) + throws Exception { Broker broker = context.getConnectionContext().getBroker(); Set destinations = broker.getDestinations(destination); for (Iterator iter = destinations.iterator(); iter.hasNext();) { - Destination dest = (Destination) iter.next(); + Destination dest = (Destination)iter.next(); dest.send(context, message); } } - public MessageStore getMessageStore() { - return next.getMessageStore(); - } + public MessageStore getMessageStore() { + return next.getMessageStore(); + } } diff --git a/activemq-core/src/main/java/org/apache/activemq/broker/region/NullMessageReference.java b/activemq-core/src/main/java/org/apache/activemq/broker/region/NullMessageReference.java index 98099f53fc..7a27b47dfd 100644 --- a/activemq-core/src/main/java/org/apache/activemq/broker/region/NullMessageReference.java +++ b/activemq-core/src/main/java/org/apache/activemq/broker/region/NullMessageReference.java @@ -24,103 +24,102 @@ import org.apache.activemq.command.Message; import org.apache.activemq.command.MessageId; /** - * Only used by the {@link QueueMessageReference#NULL_MESSAGE} + * Only used by the {@link QueueMessageReference#NULL_MESSAGE} */ -final class NullMessageReference implements - QueueMessageReference { +final class NullMessageReference implements QueueMessageReference { - private ActiveMQMessage message = new ActiveMQMessage(); - private volatile int references; - - public void drop() { - throw new RuntimeException("not implemented"); - } + private ActiveMQMessage message = new ActiveMQMessage(); + private volatile int references; - public LockOwner getLockOwner() { - throw new RuntimeException("not implemented"); - } + public void drop() { + throw new RuntimeException("not implemented"); + } - public boolean isAcked() { - return false; - } + public LockOwner getLockOwner() { + throw new RuntimeException("not implemented"); + } - public boolean isDropped() { - throw new RuntimeException("not implemented"); - } + public boolean isAcked() { + return false; + } - public boolean lock(LockOwner subscription) { - return true; - } + public boolean isDropped() { + throw new RuntimeException("not implemented"); + } - public void setAcked(boolean b) { - throw new RuntimeException("not implemented"); - } + public boolean lock(LockOwner subscription) { + return true; + } - public void unlock() { - } + public void setAcked(boolean b) { + throw new RuntimeException("not implemented"); + } - public int decrementReferenceCount() { - return --references; - } + public void unlock() { + } - public long getExpiration() { - throw new RuntimeException("not implemented"); - } + public int decrementReferenceCount() { + return --references; + } - public String getGroupID() { - return null; - } + public long getExpiration() { + throw new RuntimeException("not implemented"); + } - public int getGroupSequence() { - return 0; - } + public String getGroupID() { + return null; + } - public Message getMessage() throws IOException { - return message; - } + public int getGroupSequence() { + return 0; + } - public Message getMessageHardRef() { - throw new RuntimeException("not implemented"); - } + public Message getMessage() throws IOException { + return message; + } - public MessageId getMessageId() { - return message.getMessageId(); - } + public Message getMessageHardRef() { + throw new RuntimeException("not implemented"); + } - public int getRedeliveryCounter() { - throw new RuntimeException("not implemented"); - } + public MessageId getMessageId() { + return message.getMessageId(); + } - public int getReferenceCount() { - return references; - } + public int getRedeliveryCounter() { + throw new RuntimeException("not implemented"); + } - public Destination getRegionDestination() { - return null; - } + public int getReferenceCount() { + return references; + } - public int getSize() { - throw new RuntimeException("not implemented"); - } + public Destination getRegionDestination() { + return null; + } - public ConsumerId getTargetConsumerId() { - throw new RuntimeException("not implemented"); - } + public int getSize() { + throw new RuntimeException("not implemented"); + } - public void incrementRedeliveryCounter() { - throw new RuntimeException("not implemented"); - } + public ConsumerId getTargetConsumerId() { + throw new RuntimeException("not implemented"); + } - public int incrementReferenceCount() { - return ++references; - } + public void incrementRedeliveryCounter() { + throw new RuntimeException("not implemented"); + } - public boolean isExpired() { - throw new RuntimeException("not implemented"); - } + public int incrementReferenceCount() { + return ++references; + } - public boolean isPersistent() { - throw new RuntimeException("not implemented"); - } + public boolean isExpired() { + throw new RuntimeException("not implemented"); + } + + public boolean isPersistent() { + throw new RuntimeException("not implemented"); + } } diff --git a/activemq-core/src/main/java/org/apache/activemq/broker/region/QueueBrowserSubscription.java b/activemq-core/src/main/java/org/apache/activemq/broker/region/QueueBrowserSubscription.java index cacd4b2838..b0bf3d9d04 100755 --- a/activemq-core/src/main/java/org/apache/activemq/broker/region/QueueBrowserSubscription.java +++ b/activemq-core/src/main/java/org/apache/activemq/broker/region/QueueBrowserSubscription.java @@ -27,32 +27,29 @@ import org.apache.activemq.command.MessageDispatch; import org.apache.activemq.filter.MessageEvaluationContext; public class QueueBrowserSubscription extends QueueSubscription { - + boolean browseDone; - - public QueueBrowserSubscription(Broker broker,ConnectionContext context, ConsumerInfo info) throws InvalidSelectorException { - super(broker,context, info); + + public QueueBrowserSubscription(Broker broker, ConnectionContext context, ConsumerInfo info) + throws InvalidSelectorException { + super(broker, context, info); } - + protected boolean canDispatch(MessageReference node) { return !((QueueMessageReference)node).isAcked(); } - + public synchronized String toString() { - return - "QueueBrowserSubscription:" + - " consumer="+info.getConsumerId()+ - ", destinations="+destinations.size()+ - ", dispatched="+dispatched.size()+ - ", delivered="+this.prefetchExtension+ - ", pending="+getPendingQueueSize(); + return "QueueBrowserSubscription:" + " consumer=" + info.getConsumerId() + ", destinations=" + + destinations.size() + ", dispatched=" + dispatched.size() + ", delivered=" + + this.prefetchExtension + ", pending=" + getPendingQueueSize(); } public void browseDone() throws Exception { browseDone = true; add(QueueMessageReference.NULL_MESSAGE); } - + public boolean matches(MessageReference node, MessageEvaluationContext context) throws IOException { return !browseDone && super.matches(node, context); } @@ -60,7 +57,8 @@ public class QueueBrowserSubscription extends QueueSubscription { /** * Since we are a browser we don't really remove the message from the queue. */ - protected void acknowledge(ConnectionContext context, final MessageAck ack, final MessageReference n) throws IOException { + protected void acknowledge(ConnectionContext context, final MessageAck ack, final MessageReference n) + throws IOException { } } diff --git a/activemq-core/src/main/java/org/apache/activemq/broker/region/QueueRegion.java b/activemq-core/src/main/java/org/apache/activemq/broker/region/QueueRegion.java index eb6c2fa03f..09643beb64 100755 --- a/activemq-core/src/main/java/org/apache/activemq/broker/region/QueueRegion.java +++ b/activemq-core/src/main/java/org/apache/activemq/broker/region/QueueRegion.java @@ -33,31 +33,30 @@ import java.util.Set; */ public class QueueRegion extends AbstractRegion { - - - public QueueRegion(RegionBroker broker,DestinationStatistics destinationStatistics, UsageManager memoryManager, TaskRunnerFactory taskRunnerFactory, - DestinationFactory destinationFactory) { - super(broker,destinationStatistics, memoryManager, taskRunnerFactory, destinationFactory); + public QueueRegion(RegionBroker broker, DestinationStatistics destinationStatistics, + UsageManager memoryManager, TaskRunnerFactory taskRunnerFactory, + DestinationFactory destinationFactory) { + super(broker, destinationStatistics, memoryManager, taskRunnerFactory, destinationFactory); } public String toString() { - return "QueueRegion: destinations=" + destinations.size() + ", subscriptions=" + subscriptions.size() + ", memory=" + memoryManager.getPercentUsage() - + "%"; + return "QueueRegion: destinations=" + destinations.size() + ", subscriptions=" + subscriptions.size() + + ", memory=" + memoryManager.getPercentUsage() + "%"; } - protected Subscription createSubscription(ConnectionContext context, ConsumerInfo info) throws InvalidSelectorException { + protected Subscription createSubscription(ConnectionContext context, ConsumerInfo info) + throws InvalidSelectorException { if (info.isBrowser()) { - return new QueueBrowserSubscription(broker,context, info); - } - else { - return new QueueSubscription(broker,context, info); + return new QueueBrowserSubscription(broker, context, info); + } else { + return new QueueSubscription(broker, context, info); } } protected Set getInactiveDestinations() { Set inactiveDestinations = super.getInactiveDestinations(); for (Iterator iter = inactiveDestinations.iterator(); iter.hasNext();) { - ActiveMQDestination dest = (ActiveMQDestination) iter.next(); + ActiveMQDestination dest = (ActiveMQDestination)iter.next(); if (!dest.isQueue()) iter.remove(); } diff --git a/activemq-core/src/main/java/org/apache/activemq/broker/region/Topic.java b/activemq-core/src/main/java/org/apache/activemq/broker/region/Topic.java index 9890380ca5..d2c3c725bb 100755 --- a/activemq-core/src/main/java/org/apache/activemq/broker/region/Topic.java +++ b/activemq-core/src/main/java/org/apache/activemq/broker/region/Topic.java @@ -60,12 +60,12 @@ import org.apache.commons.logging.LogFactory; * @version $Revision: 1.21 $ */ public class Topic implements Destination { - private static final Log log = LogFactory.getLog(Topic.class); + private static final Log LOG = LogFactory.getLog(Topic.class); protected final ActiveMQDestination destination; protected final CopyOnWriteArrayList consumers = new CopyOnWriteArrayList(); protected final Valve dispatchValve = new Valve(true); - protected final TopicMessageStore store;// this could be NULL! (If an - // advsiory) + // this could be NULL! (If an advisory) + protected final TopicMessageStore store; protected final UsageManager usageManager; protected final DestinationStatistics destinationStatistics = new DestinationStatistics(); @@ -349,8 +349,8 @@ public class Topic implements Destination { // The usage manager could have delayed us by the time // we unblock the message could have expired.. if (message.isExpired()) { - if (log.isDebugEnabled()) { - log.debug("Expired message: " + message); + if (LOG.isDebugEnabled()) { + LOG.debug("Expired message: " + message); } return; } @@ -468,7 +468,7 @@ public class Topic implements Destination { } } } catch (Throwable e) { - log.warn("Failed to browse Topic: " + getActiveMQDestination().getPhysicalName(), e); + LOG.warn("Failed to browse Topic: " + getActiveMQDestination().getPhysicalName(), e); } return (Message[])result.toArray(new Message[result.size()]); } diff --git a/activemq-core/src/main/java/org/apache/activemq/broker/region/policy/FilePendingQueueMessageStoragePolicy.java b/activemq-core/src/main/java/org/apache/activemq/broker/region/policy/FilePendingQueueMessageStoragePolicy.java index 2c2b5830ad..49301117ca 100755 --- a/activemq-core/src/main/java/org/apache/activemq/broker/region/policy/FilePendingQueueMessageStoragePolicy.java +++ b/activemq-core/src/main/java/org/apache/activemq/broker/region/policy/FilePendingQueueMessageStoragePolicy.java @@ -19,25 +19,25 @@ import org.apache.activemq.broker.region.cursors.FilePendingMessageCursor; import org.apache.activemq.broker.region.cursors.PendingMessageCursor; import org.apache.activemq.kaha.Store; - /** - * Creates a FilePendingMessageCursor - * * - * @org.apache.xbean.XBean element="fileQueueCursor" description="Pending messages paged in from file" + * Creates a FilePendingMessageCursor * + * + * @org.apache.xbean.XBean element="fileQueueCursor" description="Pending + * messages paged in from file" * * @version $Revision$ */ -public class FilePendingQueueMessageStoragePolicy implements PendingQueueMessageStoragePolicy{ +public class FilePendingQueueMessageStoragePolicy implements PendingQueueMessageStoragePolicy { /** * @param queue * @param tmpStore * @return the cursor - * @see org.apache.activemq.broker.region.policy.PendingQueueMessageStoragePolicy#getQueuePendingMessageCursor(org.apache.openjpa.lib.util.concurrent.Queue, org.apache.activemq.kaha.Store) + * @see org.apache.activemq.broker.region.policy.PendingQueueMessageStoragePolicy#getQueuePendingMessageCursor(org.apache.openjpa.lib.util.concurrent.Queue, + * org.apache.activemq.kaha.Store) */ - public PendingMessageCursor getQueuePendingMessageCursor(Queue queue,Store tmpStore){ - return new FilePendingMessageCursor("PendingCursor:" + queue.getName(),tmpStore); + public PendingMessageCursor getQueuePendingMessageCursor(Queue queue, Store tmpStore) { + return new FilePendingMessageCursor("PendingCursor:" + queue.getName(), tmpStore); } - } diff --git a/activemq-core/src/main/java/org/apache/activemq/broker/region/policy/FilePendingSubscriberMessageStoragePolicy.java b/activemq-core/src/main/java/org/apache/activemq/broker/region/policy/FilePendingSubscriberMessageStoragePolicy.java index af2ec7b4bb..1707c99c4b 100644 --- a/activemq-core/src/main/java/org/apache/activemq/broker/region/policy/FilePendingSubscriberMessageStoragePolicy.java +++ b/activemq-core/src/main/java/org/apache/activemq/broker/region/policy/FilePendingSubscriberMessageStoragePolicy.java @@ -17,25 +17,26 @@ import org.apache.activemq.broker.region.cursors.FilePendingMessageCursor; import org.apache.activemq.broker.region.cursors.PendingMessageCursor; import org.apache.activemq.kaha.Store; - /** - * Creates a PendIngMessageCursor for Durable subscribers - * * - * @org.apache.xbean.XBean element="fileCursor" description="Pending messages for durable subscribers - * held in temporary files" + * Creates a PendIngMessageCursor for Durable subscribers * + * + * @org.apache.xbean.XBean element="fileCursor" description="Pending messages + * for durable subscribers held in temporary files" * * @version $Revision$ */ -public class FilePendingSubscriberMessageStoragePolicy implements PendingSubscriberMessageStoragePolicy{ +public class FilePendingSubscriberMessageStoragePolicy implements PendingSubscriberMessageStoragePolicy { /** * @param name * @param tmpStorage * @param maxBatchSize * @return a Cursor - * @see org.apache.activemq.broker.region.policy.PendingSubscriberMessageStoragePolicy#getSubscriberPendingMessageCursor(java.lang.String, org.apache.activemq.kaha.Store, int) + * @see org.apache.activemq.broker.region.policy.PendingSubscriberMessageStoragePolicy#getSubscriberPendingMessageCursor(java.lang.String, + * org.apache.activemq.kaha.Store, int) */ - public PendingMessageCursor getSubscriberPendingMessageCursor(String name,Store tmpStorage,int maxBatchSize){ - return new FilePendingMessageCursor("PendingCursor:" + name,tmpStorage); + public PendingMessageCursor getSubscriberPendingMessageCursor(String name, Store tmpStorage, + int maxBatchSize) { + return new FilePendingMessageCursor("PendingCursor:" + name, tmpStorage); } -} \ No newline at end of file +} diff --git a/activemq-core/src/main/java/org/apache/activemq/broker/region/policy/StorePendingQueueMessageStoragePolicy.java b/activemq-core/src/main/java/org/apache/activemq/broker/region/policy/StorePendingQueueMessageStoragePolicy.java index 666571b2f2..138e1eb28f 100755 --- a/activemq-core/src/main/java/org/apache/activemq/broker/region/policy/StorePendingQueueMessageStoragePolicy.java +++ b/activemq-core/src/main/java/org/apache/activemq/broker/region/policy/StorePendingQueueMessageStoragePolicy.java @@ -19,25 +19,25 @@ import org.apache.activemq.broker.region.cursors.PendingMessageCursor; import org.apache.activemq.broker.region.cursors.StoreQueueCursor; import org.apache.activemq.kaha.Store; - /** - * Creates a StoreQueueCursor - * * - * @org.apache.xbean.XBean element="storeCursor" description="Pending messages paged in from the Store" + * Creates a StoreQueueCursor * + * + * @org.apache.xbean.XBean element="storeCursor" description="Pending messages + * paged in from the Store" * * @version $Revision$ */ -public class StorePendingQueueMessageStoragePolicy implements PendingQueueMessageStoragePolicy{ +public class StorePendingQueueMessageStoragePolicy implements PendingQueueMessageStoragePolicy { /** * @param queue * @param tmpStore * @return the cursor - * @see org.apache.activemq.broker.region.policy.PendingQueueMessageStoragePolicy#getQueuePendingMessageCursor(org.apache.openjpa.lib.util.concurrent.Queue, org.apache.activemq.kaha.Store) + * @see org.apache.activemq.broker.region.policy.PendingQueueMessageStoragePolicy#getQueuePendingMessageCursor(org.apache.openjpa.lib.util.concurrent.Queue, + * org.apache.activemq.kaha.Store) */ - public PendingMessageCursor getQueuePendingMessageCursor(Queue queue,Store tmpStore){ - return new StoreQueueCursor(queue,tmpStore); + public PendingMessageCursor getQueuePendingMessageCursor(Queue queue, Store tmpStore) { + return new StoreQueueCursor(queue, tmpStore); } - } diff --git a/activemq-core/src/main/java/org/apache/activemq/broker/region/policy/VMPendingQueueMessageStoragePolicy.java b/activemq-core/src/main/java/org/apache/activemq/broker/region/policy/VMPendingQueueMessageStoragePolicy.java index f1e964887c..e1dfdff4cd 100755 --- a/activemq-core/src/main/java/org/apache/activemq/broker/region/policy/VMPendingQueueMessageStoragePolicy.java +++ b/activemq-core/src/main/java/org/apache/activemq/broker/region/policy/VMPendingQueueMessageStoragePolicy.java @@ -20,20 +20,21 @@ import org.apache.activemq.broker.region.cursors.VMPendingMessageCursor; import org.apache.activemq.kaha.Store; /** - * Creates a VMPendingMessageCursor - * * - * @org.apache.xbean.XBean element="vmQueueCursor" description="Pending messages held in the JVM" + * Creates a VMPendingMessageCursor * + * + * @org.apache.xbean.XBean element="vmQueueCursor" description="Pending messages + * held in the JVM" * * @version $Revision$ */ -public class VMPendingQueueMessageStoragePolicy implements PendingQueueMessageStoragePolicy{ +public class VMPendingQueueMessageStoragePolicy implements PendingQueueMessageStoragePolicy { /** * @param queue * @param tmpStore - * @return the cursor + * @return the cursor */ - public PendingMessageCursor getQueuePendingMessageCursor(Queue queue,Store tmpStore){ + public PendingMessageCursor getQueuePendingMessageCursor(Queue queue, Store tmpStore) { return new VMPendingMessageCursor(); } } diff --git a/activemq-core/src/main/java/org/apache/activemq/broker/region/policy/VMPendingSubscriberMessageStoragePolicy.java b/activemq-core/src/main/java/org/apache/activemq/broker/region/policy/VMPendingSubscriberMessageStoragePolicy.java index a754967c5d..e7f95ebb7c 100644 --- a/activemq-core/src/main/java/org/apache/activemq/broker/region/policy/VMPendingSubscriberMessageStoragePolicy.java +++ b/activemq-core/src/main/java/org/apache/activemq/broker/region/policy/VMPendingSubscriberMessageStoragePolicy.java @@ -17,24 +17,26 @@ import org.apache.activemq.broker.region.cursors.PendingMessageCursor; import org.apache.activemq.broker.region.cursors.VMPendingMessageCursor; import org.apache.activemq.kaha.Store; - /** - * Creates a VMPendingMessageCursor - * * - * @org.apache.xbean.XBean element="vmCursor" description="Pending messages held in the JVM" + * Creates a VMPendingMessageCursor * + * + * @org.apache.xbean.XBean element="vmCursor" description="Pending messages held + * in the JVM" * * @version $Revision$ */ -public class VMPendingSubscriberMessageStoragePolicy implements PendingSubscriberMessageStoragePolicy{ +public class VMPendingSubscriberMessageStoragePolicy implements PendingSubscriberMessageStoragePolicy { /** * @param name * @param tmpStorage * @param maxBatchSize * @return a Cursor - * @see org.apache.activemq.broker.region.policy.PendingSubscriberMessageStoragePolicy#getSubscriberPendingMessageCursor(java.lang.String, org.apache.activemq.kaha.Store, int) + * @see org.apache.activemq.broker.region.policy.PendingSubscriberMessageStoragePolicy#getSubscriberPendingMessageCursor(java.lang.String, + * org.apache.activemq.kaha.Store, int) */ - public PendingMessageCursor getSubscriberPendingMessageCursor(String name,Store tmpStorage,int maxBatchSize){ + public PendingMessageCursor getSubscriberPendingMessageCursor(String name, Store tmpStorage, + int maxBatchSize) { return new VMPendingMessageCursor(); } } diff --git a/activemq-core/src/main/java/org/apache/activemq/broker/util/MulticastTraceBrokerPlugin.java b/activemq-core/src/main/java/org/apache/activemq/broker/util/MulticastTraceBrokerPlugin.java index 86663cc41d..7e49580c4b 100644 --- a/activemq-core/src/main/java/org/apache/activemq/broker/util/MulticastTraceBrokerPlugin.java +++ b/activemq-core/src/main/java/org/apache/activemq/broker/util/MulticastTraceBrokerPlugin.java @@ -23,7 +23,8 @@ import java.net.URI; import java.net.URISyntaxException; /** - * A Broker interceptor which allows you to trace all operations to a Multicast socket. + * A Broker interceptor which allows you to trace all operations to a Multicast + * socket. * * @org.apache.xbean.XBean * @@ -31,30 +32,30 @@ import java.net.URISyntaxException; */ public class MulticastTraceBrokerPlugin extends UDPTraceBrokerPlugin { - private int timeToLive = 1; - - public MulticastTraceBrokerPlugin() { - try { - destination = new URI("multicast://224.1.2.3:61616"); - } catch (URISyntaxException wontHappen) { - } - } - - protected DatagramSocket createSocket() throws IOException { + private int timeToLive = 1; + + public MulticastTraceBrokerPlugin() { + try { + destination = new URI("multicast://224.1.2.3:61616"); + } catch (URISyntaxException wontHappen) { + } + } + + protected DatagramSocket createSocket() throws IOException { MulticastSocket s = new MulticastSocket(); - s.setSendBufferSize(maxTraceDatagramSize); - s.setBroadcast(broadcast); + s.setSendBufferSize(maxTraceDatagramSize); + s.setBroadcast(broadcast); s.setLoopbackMode(true); s.setTimeToLive(timeToLive); return s; - } + } - public int getTimeToLive() { - return timeToLive; - } + public int getTimeToLive() { + return timeToLive; + } - public void setTimeToLive(int timeToLive) { - this.timeToLive = timeToLive; - } + public void setTimeToLive(int timeToLive) { + this.timeToLive = timeToLive; + } } diff --git a/activemq-core/src/main/java/org/apache/activemq/broker/util/TimeStampingBrokerPlugin.java b/activemq-core/src/main/java/org/apache/activemq/broker/util/TimeStampingBrokerPlugin.java index 27b093f8a1..2842c66c9b 100644 --- a/activemq-core/src/main/java/org/apache/activemq/broker/util/TimeStampingBrokerPlugin.java +++ b/activemq-core/src/main/java/org/apache/activemq/broker/util/TimeStampingBrokerPlugin.java @@ -20,27 +20,27 @@ import org.apache.activemq.broker.BrokerPluginSupport; import org.apache.activemq.broker.ProducerBrokerExchange; import org.apache.activemq.command.Message; - /** * A Broker interceptor which updates a JMS Client's timestamp on the message - * with a broker timestamp. Useful when the clocks on client machines are known to - * not be correct and you can only trust the time set on the broker machines. + * with a broker timestamp. Useful when the clocks on client machines are known + * to not be correct and you can only trust the time set on the broker machines. * - * Enabling this plugin will break JMS compliance since the timestamp that the producer - * sees on the messages after as send() will be different from the timestamp the consumer - * will observe when he receives the message. This plugin is not enabled in the default - * ActiveMQ configuration. + * Enabling this plugin will break JMS compliance since the timestamp that the + * producer sees on the messages after as send() will be different from the + * timestamp the consumer will observe when he receives the message. This plugin + * is not enabled in the default ActiveMQ configuration. * - * @org.apache.xbean.XBean element="timeStampingBrokerPlugin" + * @org.apache.xbean.XBean element="timeStampingBrokerPlugin" * * @version $Revision$ */ -public class TimeStampingBrokerPlugin extends BrokerPluginSupport { - public void send(ProducerBrokerExchange producerExchange, Message message) throws Exception { - if (message.getTimestamp() > 0 && (message.getBrokerPath() == null || message.getBrokerPath().length == 0)) { - //timestamp not been disabled and has not passed through a network +public class TimeStampingBrokerPlugin extends BrokerPluginSupport { + public void send(ProducerBrokerExchange producerExchange, Message message) throws Exception { + if (message.getTimestamp() > 0 + && (message.getBrokerPath() == null || message.getBrokerPath().length == 0)) { + // timestamp not been disabled and has not passed through a network message.setTimestamp(System.currentTimeMillis()); } - super.send(producerExchange, message); - } + super.send(producerExchange, message); + } } diff --git a/activemq-core/src/main/java/org/apache/activemq/broker/view/DestinationDotFileInterceptor.java b/activemq-core/src/main/java/org/apache/activemq/broker/view/DestinationDotFileInterceptor.java index 074d520a43..a0d2f11464 100644 --- a/activemq-core/src/main/java/org/apache/activemq/broker/view/DestinationDotFileInterceptor.java +++ b/activemq-core/src/main/java/org/apache/activemq/broker/view/DestinationDotFileInterceptor.java @@ -16,6 +16,10 @@ */ package org.apache.activemq.broker.view; +import java.io.PrintWriter; +import java.util.Collection; +import java.util.Iterator; + import org.apache.activemq.broker.Broker; import org.apache.activemq.broker.ConnectionContext; import org.apache.activemq.broker.region.Destination; @@ -23,12 +27,7 @@ import org.apache.activemq.command.ActiveMQDestination; import org.apache.activemq.filter.DestinationMap; import org.apache.activemq.filter.DestinationMapNode; -import java.io.PrintWriter; -import java.util.Collection; -import java.util.Iterator; - /** - * * @version $Revision: $ */ public class DestinationDotFileInterceptor extends DotFileInterceptorSupport { @@ -45,13 +44,11 @@ public class DestinationDotFileInterceptor extends DotFileInterceptorSupport { return answer; } - public void removeDestination(ConnectionContext context, ActiveMQDestination destination, long timeout) - throws Exception { + public void removeDestination(ConnectionContext context, ActiveMQDestination destination, long timeout) throws Exception { super.removeDestination(context, destination, timeout); generateFile(); } - protected void generateFile(PrintWriter writer) throws Exception { ActiveMQDestination[] destinations = getDestinations(); @@ -71,7 +68,7 @@ public class DestinationDotFileInterceptor extends DotFileInterceptorSupport { writer.println("topic_root [fillcolor = deepskyblue, label = \"Topics\" ];"); writer.println("queue_root [fillcolor = deepskyblue, label = \"Queues\" ];"); writer.println(); - + writer.println("subgraph queues {"); writer.println(" node [fillcolor=red]; "); writer.println(" label = \"Queues\""); @@ -83,20 +80,20 @@ public class DestinationDotFileInterceptor extends DotFileInterceptorSupport { writer.println("subgraph topics {"); writer.println(" node [fillcolor=green]; "); writer.println(" label = \"Topics\""); - writer.println(); + writer.println(); printNodeLinks(writer, map.getTopicRootNode(), "topic"); writer.println("}"); writer.println(); - + printNodes(writer, map.getQueueRootNode(), "queue"); writer.println(); - + printNodes(writer, map.getTopicRootNode(), "topic"); writer.println(); - + writer.println("}"); } - + protected void printNodes(PrintWriter writer, DestinationMapNode node, String prefix) { String path = getPath(node); writer.print(" "); @@ -106,8 +103,7 @@ public class DestinationDotFileInterceptor extends DotFileInterceptorSupport { String label = path; if (prefix.equals("topic")) { label = "Topics"; - } - else if (prefix.equals("queue")) { + } else if (prefix.equals("queue")) { label = "Queues"; } writer.print("[ label = \""); @@ -116,7 +112,7 @@ public class DestinationDotFileInterceptor extends DotFileInterceptorSupport { Collection children = node.getChildren(); for (Iterator iter = children.iterator(); iter.hasNext();) { - DestinationMapNode child = (DestinationMapNode) iter.next(); + DestinationMapNode child = (DestinationMapNode)iter.next(); printNodes(writer, child, prefix + ID_SEPARATOR + path); } } @@ -125,7 +121,7 @@ public class DestinationDotFileInterceptor extends DotFileInterceptorSupport { String path = getPath(node); Collection children = node.getChildren(); for (Iterator iter = children.iterator(); iter.hasNext();) { - DestinationMapNode child = (DestinationMapNode) iter.next(); + DestinationMapNode child = (DestinationMapNode)iter.next(); writer.print(" "); writer.print(prefix); @@ -143,7 +139,6 @@ public class DestinationDotFileInterceptor extends DotFileInterceptorSupport { } } - protected String getPath(DestinationMapNode node) { String path = node.getPath(); if (path.equals("*")) { diff --git a/activemq-core/src/main/java/org/apache/activemq/camel/CamelQueueSender.java b/activemq-core/src/main/java/org/apache/activemq/camel/CamelQueueSender.java index 3924a8a3cf..8785541937 100644 --- a/activemq-core/src/main/java/org/apache/activemq/camel/CamelQueueSender.java +++ b/activemq-core/src/main/java/org/apache/activemq/camel/CamelQueueSender.java @@ -16,18 +16,18 @@ */ package org.apache.activemq.camel; -import org.apache.activemq.ActiveMQSession; -import org.apache.camel.Endpoint; - import javax.jms.JMSException; import javax.jms.Message; import javax.jms.Queue; import javax.jms.QueueSender; +import org.apache.activemq.ActiveMQSession; +import org.apache.camel.Endpoint; + /** - * A JMS {@link javax.jms.QueueSender} which sends message exchanges to a - * Camel {@link org.apache.camel.Endpoint} - * + * A JMS {@link javax.jms.QueueSender} which sends message exchanges to a Camel + * {@link org.apache.camel.Endpoint} + * * @version $Revision: $ */ public class CamelQueueSender extends CamelMessageProducer implements QueueSender { @@ -36,33 +36,30 @@ public class CamelQueueSender extends CamelMessageProducer implements QueueSende super(destination, endpoint, session); } - /** * Gets the queue associated with this QueueSender. - * + * * @return this sender's queue * @throws JMSException if the JMS provider fails to get the queue for this - * QueueSender due to some internal error. + * QueueSender due to some internal error. */ public Queue getQueue() throws JMSException { - return (Queue) super.getDestination(); + return (Queue)super.getDestination(); } /** - * Sends a message to a queue for an unidentified message producer. Uses - * the QueueSender's default delivery mode, priority, and - * time to live. - *

- *

- * Typically, a message producer is assigned a queue at creation time; - * however, the JMS API also supports unidentified message producers, which - * require that the queue be supplied every time a message is sent. - * - * @param queue the queue to send this message to + * Sends a message to a queue for an unidentified message producer. Uses the + * QueueSender's default delivery mode, priority, and time + * to live.

Typically, a message producer is assigned a queue at + * creation time; however, the JMS API also supports unidentified message + * producers, which require that the queue be supplied every time a message + * is sent. + * + * @param queue the queue to send this message to * @param message the message to send - * @throws JMSException if the JMS provider fails to send the message due to some - * internal error. + * @throws JMSException if the JMS provider fails to send the message due to + * some internal error. * @see javax.jms.MessageProducer#getDeliveryMode() * @see javax.jms.MessageProducer#getTimeToLive() * @see javax.jms.MessageProducer#getPriority() @@ -74,28 +71,21 @@ public class CamelQueueSender extends CamelMessageProducer implements QueueSende /** * Sends a message to a queue for an unidentified message producer, - * specifying delivery mode, priority and time to live. - *

- *

- * Typically, a message producer is assigned a queue at creation time; - * however, the JMS API also supports unidentified message producers, which - * require that the queue be supplied every time a message is sent. - * - * @param queue the queue to send this message to - * @param message the message to send + * specifying delivery mode, priority and time to live.

Typically, + * a message producer is assigned a queue at creation time; however, the JMS + * API also supports unidentified message producers, which require that the + * queue be supplied every time a message is sent. + * + * @param queue the queue to send this message to + * @param message the message to send * @param deliveryMode the delivery mode to use - * @param priority the priority for this message - * @param timeToLive the message's lifetime (in milliseconds) - * @throws JMSException if the JMS provider fails to send the message due to some - * internal error. + * @param priority the priority for this message + * @param timeToLive the message's lifetime (in milliseconds) + * @throws JMSException if the JMS provider fails to send the message due to + * some internal error. */ - public void send(Queue queue, Message message, int deliveryMode, int priority, long timeToLive) - throws JMSException { - super.send(queue, - message, - deliveryMode, - priority, - timeToLive); + public void send(Queue queue, Message message, int deliveryMode, int priority, long timeToLive) throws JMSException { + super.send(queue, message, deliveryMode, priority, timeToLive); } -} \ No newline at end of file +} diff --git a/activemq-core/src/main/java/org/apache/activemq/command/ActiveMQDestination.java b/activemq-core/src/main/java/org/apache/activemq/command/ActiveMQDestination.java index 63d88ac44e..bb04a187e7 100755 --- a/activemq-core/src/main/java/org/apache/activemq/command/ActiveMQDestination.java +++ b/activemq-core/src/main/java/org/apache/activemq/command/ActiveMQDestination.java @@ -41,7 +41,8 @@ import java.util.StringTokenizer; * @openwire:marshaller * @version $Revision: 1.10 $ */ -abstract public class ActiveMQDestination extends JNDIBaseStorable implements DataStructure, Destination, Externalizable, Comparable { +abstract public class ActiveMQDestination extends JNDIBaseStorable implements DataStructure, Destination, + Externalizable, Comparable { private static final long serialVersionUID = -3885260014960795889L; @@ -196,7 +197,8 @@ abstract public class ActiveMQDestination extends JNDIBaseStorable implements Da public void setPhysicalName(String physicalName) { final int len = physicalName.length(); - int p = -1;// options offset + // options offset + int p = -1; boolean composite = false; for (int i = 0; i < len; i++) { char c = physicalName.charAt(i); @@ -219,7 +221,8 @@ abstract public class ActiveMQDestination extends JNDIBaseStorable implements Da try { options = URISupport.parseQuery(optstring); } catch (URISyntaxException e) { - throw new IllegalArgumentException("Invalid destination name: " + physicalName + ", it's options are not encoded properly: " + e); + throw new IllegalArgumentException("Invalid destination name: " + physicalName + + ", it's options are not encoded properly: " + e); } } this.physicalName = physicalName; diff --git a/activemq-core/src/main/java/org/apache/activemq/command/ActiveMQMapMessage.java b/activemq-core/src/main/java/org/apache/activemq/command/ActiveMQMapMessage.java index 3b80ef3f42..c589ba1c69 100755 --- a/activemq-core/src/main/java/org/apache/activemq/command/ActiveMQMapMessage.java +++ b/activemq-core/src/main/java/org/apache/activemq/command/ActiveMQMapMessage.java @@ -42,33 +42,51 @@ import org.apache.activemq.util.MarshallingSupport; import org.apache.activemq.wireformat.WireFormat; /** - * A MapMessage object is used to send a set of name-value pairs. The names are String - * objects, and the values are primitive data types in the Java programming language. The names must have a value that - * is not null, and not an empty string. The entries can be accessed sequentially or randomly by name. The order of the - * entries is undefined. MapMessage inherits from the Message interface and adds a message - * body that contains a Map.

The primitive types can be read or written explicitly using methods for each type. They - * may also be read or written generically as objects. For instance, a call to MapMessage.setInt("foo", 6) - * is equivalent to MapMessage.setObject("foo", new Integer(6)). Both forms are provided, because the - * explicit form is convenient for static programming, and the object form is needed when types are not known at compile - * time.

When a client receives a MapMessage, it is in read-only mode. If a client attempts to write to - * the message at this point, a MessageNotWriteableException is thrown. If clearBody is - * called, the message can now be both read from and written to.

MapMessage objects support the - * following conversion table. The marked cases must be supported. The unmarked cases must throw a - * JMSException. The String -to-primitive conversions may throw a runtime exception if the - * primitive's valueOf() method does not accept it as a valid String representation of the - * primitive.

A value written as the row type can be read as the column type. - *

- *

| | boolean byte short char int long float double String byte[] |----------------------------------------------------------------------
+ * A MapMessage object is used to send a set of name-value pairs.
+ * The names are String objects, and the values are primitive
+ * data types in the Java programming language. The names must have a value that
+ * is not null, and not an empty string. The entries can be accessed
+ * sequentially or randomly by name. The order of the entries is undefined.
+ * MapMessage inherits from the Message interface
+ * and adds a message body that contains a Map.
+ * 

+ * The primitive types can be read or written explicitly using methods for each + * type. They may also be read or written generically as objects. For instance, + * a call to MapMessage.setInt("foo", 6) is equivalent to + * MapMessage.setObject("foo", new Integer(6)). Both forms are + * provided, because the explicit form is convenient for static programming, and + * the object form is needed when types are not known at compile time. + *

+ * When a client receives a MapMessage, it is in read-only mode. + * If a client attempts to write to the message at this point, a + * MessageNotWriteableException is thrown. If + * clearBody is called, the message can now be both read from and + * written to. + *

+ * MapMessage objects support the following conversion table. The + * marked cases must be supported. The unmarked cases must throw a + * JMSException. The String -to-primitive + * conversions may throw a runtime exception if the primitive's + * valueOf() method does not accept it as a valid + * String representation of the primitive. + *

+ * A value written as the row type can be read as the column type.

+ * + *

+ * | | boolean byte short char int long float double String byte[] |----------------------------------------------------------------------
  * |boolean | X X |byte | X X X X X |short | X X X X |char | X X |int | X X X |long | X X |float | X X X |double | X X
  * |String | X X X X X X X X |byte[] | X |----------------------------------------------------------------------
- * 

+ * <p/> *

+ * *

- *

Attempting to read a null value as a primitive type must be treated as calling the primitive's corresponding - * valueOf(String) conversion method with a null value. Since char does not support a - * String conversion, attempting to read a null value as a char must throw a - * NullPointerException. - * + *

+ * Attempting to read a null value as a primitive type must be treated as + * calling the primitive's corresponding valueOf(String) + * conversion method with a null value. Since char does not + * support a String conversion, attempting to read a null value + * as a char must throw a NullPointerException. + * * @openwire:marshaller code="25" * @see javax.jms.Session#createMapMessage() * @see javax.jms.BytesMessage @@ -99,14 +117,14 @@ public class ActiveMQMapMessage extends ActiveMQMessage implements MapMessage { super.beforeMarshall(wireFormat); storeContent(); } - + private void storeContent() { try { - if( getContent()==null && !map.isEmpty()) { + if (getContent() == null && !map.isEmpty()) { ByteArrayOutputStream bytesOut = new ByteArrayOutputStream(); OutputStream os = bytesOut; ActiveMQConnection connection = getConnection(); - if( connection!= null && connection.isUseCompression() ) { + if (connection != null && connection.isUseCompression()) { compressed = true; os = new DeflaterOutputStream(os); } @@ -119,19 +137,20 @@ public class ActiveMQMapMessage extends ActiveMQMessage implements MapMessage { throw new RuntimeException(e); } } - + /** * Builds the message body from data - * @throws JMSException - * + * + * @throws JMSException + * * @throws IOException */ private void loadContent() throws JMSException { try { - if( getContent()!=null && map.isEmpty() ) { + if (getContent() != null && map.isEmpty()) { ByteSequence content = getContent(); InputStream is = new ByteArrayInputStream(content); - if( isCompressed() ) { + if (isCompressed()) { is = new InflaterInputStream(is); } DataInputStream dataIn = new DataInputStream(is); @@ -146,16 +165,18 @@ public class ActiveMQMapMessage extends ActiveMQMessage implements MapMessage { public byte getDataStructureType() { return DATA_STRUCTURE_TYPE; } - + public String getJMSXMimeType() { return "jms/map-message"; } - /** - * Clears out the message body. Clearing a message's body does not clear its header values or property entries.

- * If this message body was read-only, calling this method leaves the message body in the same state as an empty - * body in a newly created message. + * Clears out the message body. Clearing a message's body does not clear its + * header values or property entries. + *

+ * If this message body was read-only, calling this method leaves the + * message body in the same state as an empty body in a newly created + * message. */ public void clearBody() throws JMSException { super.clearBody(); @@ -164,10 +185,11 @@ public class ActiveMQMapMessage extends ActiveMQMessage implements MapMessage { /** * Returns the boolean value with the specified name. - * + * * @param name the name of the boolean * @return the boolean value with the specified name - * @throws JMSException if the JMS provider fails to read the message due to some internal error. + * @throws JMSException if the JMS provider fails to read the message due to + * some internal error. * @throws MessageFormatException if this type conversion is invalid. */ public boolean getBoolean(String name) throws JMSException { @@ -177,7 +199,7 @@ public class ActiveMQMapMessage extends ActiveMQMessage implements MapMessage { return false; } if (value instanceof Boolean) { - return ((Boolean) value).booleanValue(); + return ((Boolean)value).booleanValue(); } if (value instanceof String) { return Boolean.valueOf(value.toString()).booleanValue(); @@ -188,10 +210,11 @@ public class ActiveMQMapMessage extends ActiveMQMessage implements MapMessage { /** * Returns the byte value with the specified name. - * + * * @param name the name of the byte * @return the byte value with the specified name - * @throws JMSException if the JMS provider fails to read the message due to some internal error. + * @throws JMSException if the JMS provider fails to read the message due to + * some internal error. * @throws MessageFormatException if this type conversion is invalid. */ public byte getByte(String name) throws JMSException { @@ -201,7 +224,7 @@ public class ActiveMQMapMessage extends ActiveMQMessage implements MapMessage { return 0; } if (value instanceof Byte) { - return ((Byte) value).byteValue(); + return ((Byte)value).byteValue(); } if (value instanceof String) { return Byte.valueOf(value.toString()).byteValue(); @@ -212,10 +235,11 @@ public class ActiveMQMapMessage extends ActiveMQMessage implements MapMessage { /** * Returns the short value with the specified name. - * + * * @param name the name of the short * @return the short value with the specified name - * @throws JMSException if the JMS provider fails to read the message due to some internal error. + * @throws JMSException if the JMS provider fails to read the message due to + * some internal error. * @throws MessageFormatException if this type conversion is invalid. */ public short getShort(String name) throws JMSException { @@ -225,10 +249,10 @@ public class ActiveMQMapMessage extends ActiveMQMessage implements MapMessage { return 0; } if (value instanceof Short) { - return ((Short) value).shortValue(); + return ((Short)value).shortValue(); } if (value instanceof Byte) { - return ((Byte) value).shortValue(); + return ((Byte)value).shortValue(); } if (value instanceof String) { return Short.valueOf(value.toString()).shortValue(); @@ -239,10 +263,11 @@ public class ActiveMQMapMessage extends ActiveMQMessage implements MapMessage { /** * Returns the Unicode character value with the specified name. - * + * * @param name the name of the Unicode character * @return the Unicode character value with the specified name - * @throws JMSException if the JMS provider fails to read the message due to some internal error. + * @throws JMSException if the JMS provider fails to read the message due to + * some internal error. * @throws MessageFormatException if this type conversion is invalid. */ public char getChar(String name) throws JMSException { @@ -252,7 +277,7 @@ public class ActiveMQMapMessage extends ActiveMQMessage implements MapMessage { throw new NullPointerException(); } if (value instanceof Character) { - return ((Character) value).charValue(); + return ((Character)value).charValue(); } else { throw new MessageFormatException(" cannot read a short from " + value.getClass().getName()); } @@ -260,10 +285,11 @@ public class ActiveMQMapMessage extends ActiveMQMessage implements MapMessage { /** * Returns the int value with the specified name. - * + * * @param name the name of the int * @return the int value with the specified name - * @throws JMSException if the JMS provider fails to read the message due to some internal error. + * @throws JMSException if the JMS provider fails to read the message due to + * some internal error. * @throws MessageFormatException if this type conversion is invalid. */ public int getInt(String name) throws JMSException { @@ -273,13 +299,13 @@ public class ActiveMQMapMessage extends ActiveMQMessage implements MapMessage { return 0; } if (value instanceof Integer) { - return ((Integer) value).intValue(); + return ((Integer)value).intValue(); } if (value instanceof Short) { - return ((Short) value).intValue(); + return ((Short)value).intValue(); } if (value instanceof Byte) { - return ((Byte) value).intValue(); + return ((Byte)value).intValue(); } if (value instanceof String) { return Integer.valueOf(value.toString()).intValue(); @@ -290,10 +316,11 @@ public class ActiveMQMapMessage extends ActiveMQMessage implements MapMessage { /** * Returns the long value with the specified name. - * + * * @param name the name of the long * @return the long value with the specified name - * @throws JMSException if the JMS provider fails to read the message due to some internal error. + * @throws JMSException if the JMS provider fails to read the message due to + * some internal error. * @throws MessageFormatException if this type conversion is invalid. */ public long getLong(String name) throws JMSException { @@ -303,16 +330,16 @@ public class ActiveMQMapMessage extends ActiveMQMessage implements MapMessage { return 0; } if (value instanceof Long) { - return ((Long) value).longValue(); + return ((Long)value).longValue(); } if (value instanceof Integer) { - return ((Integer) value).longValue(); + return ((Integer)value).longValue(); } if (value instanceof Short) { - return ((Short) value).longValue(); + return ((Short)value).longValue(); } if (value instanceof Byte) { - return ((Byte) value).longValue(); + return ((Byte)value).longValue(); } if (value instanceof String) { return Long.valueOf(value.toString()).longValue(); @@ -323,10 +350,11 @@ public class ActiveMQMapMessage extends ActiveMQMessage implements MapMessage { /** * Returns the float value with the specified name. - * + * * @param name the name of the float * @return the float value with the specified name - * @throws JMSException if the JMS provider fails to read the message due to some internal error. + * @throws JMSException if the JMS provider fails to read the message due to + * some internal error. * @throws MessageFormatException if this type conversion is invalid. */ public float getFloat(String name) throws JMSException { @@ -336,7 +364,7 @@ public class ActiveMQMapMessage extends ActiveMQMessage implements MapMessage { return 0; } if (value instanceof Float) { - return ((Float) value).floatValue(); + return ((Float)value).floatValue(); } if (value instanceof String) { return Float.valueOf(value.toString()).floatValue(); @@ -347,10 +375,11 @@ public class ActiveMQMapMessage extends ActiveMQMessage implements MapMessage { /** * Returns the double value with the specified name. - * + * * @param name the name of the double * @return the double value with the specified name - * @throws JMSException if the JMS provider fails to read the message due to some internal error. + * @throws JMSException if the JMS provider fails to read the message due to + * some internal error. * @throws MessageFormatException if this type conversion is invalid. */ public double getDouble(String name) throws JMSException { @@ -360,10 +389,10 @@ public class ActiveMQMapMessage extends ActiveMQMessage implements MapMessage { return 0; } if (value instanceof Double) { - return ((Double) value).doubleValue(); + return ((Double)value).doubleValue(); } if (value instanceof Float) { - return ((Float) value).floatValue(); + return ((Float)value).floatValue(); } if (value instanceof String) { return Float.valueOf(value.toString()).floatValue(); @@ -374,11 +403,12 @@ public class ActiveMQMapMessage extends ActiveMQMessage implements MapMessage { /** * Returns the String value with the specified name. - * + * * @param name the name of the String - * @return the String value with the specified name; if there is no item by this name, a null value is - * returned - * @throws JMSException if the JMS provider fails to read the message due to some internal error. + * @return the String value with the specified name; if there + * is no item by this name, a null value is returned + * @throws JMSException if the JMS provider fails to read the message due to + * some internal error. * @throws MessageFormatException if this type conversion is invalid. */ public String getString(String name) throws JMSException { @@ -396,34 +426,42 @@ public class ActiveMQMapMessage extends ActiveMQMessage implements MapMessage { /** * Returns the byte array value with the specified name. - * + * * @param name the name of the byte array - * @return a copy of the byte array value with the specified name; if there is no item by this name, a null value is - * returned. - * @throws JMSException if the JMS provider fails to read the message due to some internal error. + * @return a copy of the byte array value with the specified name; if there + * is no item by this name, a null value is returned. + * @throws JMSException if the JMS provider fails to read the message due to + * some internal error. * @throws MessageFormatException if this type conversion is invalid. */ public byte[] getBytes(String name) throws JMSException { initializeReading(); - Object value = map.get(name); - if ( value instanceof byte[] ) { - return (byte[]) value; + Object value = map.get(name); + if (value instanceof byte[]) { + return (byte[])value; } else { throw new MessageFormatException(" cannot read a byte[] from " + value.getClass().getName()); } } /** - * Returns the value of the object with the specified name.

This method can be used to return, in objectified - * format, an object in the Java programming language ("Java object") that had been stored in the Map with the - * equivalent setObject method call, or its equivalent primitive set type method. - *

Note that byte values are returned as byte[], not Byte[]. - * + * Returns the value of the object with the specified name. + *

+ * This method can be used to return, in objectified format, an object in + * the Java programming language ("Java object") that had been stored in the + * Map with the equivalent setObject method call, or its + * equivalent primitive set type method. + *

+ * Note that byte values are returned as byte[], not + * Byte[]. + * * @param name the name of the Java object - * @return a copy of the Java object value with the specified name, in objectified format (for example, if the - * object was set as an int, an Integer is returned); if there is no item by this - * name, a null value is returned - * @throws JMSException if the JMS provider fails to read the message due to some internal error. + * @return a copy of the Java object value with the specified name, in + * objectified format (for example, if the object was set as an + * int, an Integer is returned); if + * there is no item by this name, a null value is returned + * @throws JMSException if the JMS provider fails to read the message due to + * some internal error. */ public Object getObject(String name) throws JMSException { initializeReading(); @@ -431,8 +469,9 @@ public class ActiveMQMapMessage extends ActiveMQMessage implements MapMessage { } /** - * Returns an Enumeration of all the names in the MapMessage object. - * + * Returns an Enumeration of all the names in the + * MapMessage object. + * * @return an enumeration of all the names in this MapMessage * @throws JMSException */ @@ -453,11 +492,13 @@ public class ActiveMQMapMessage extends ActiveMQMessage implements MapMessage { /** * Sets a boolean value with the specified name into the Map. - * - * @param name the name of the boolean + * + * @param name the name of the boolean * @param value the boolean value to set in the Map - * @throws JMSException if the JMS provider fails to write the message due to some internal error. - * @throws IllegalArgumentException if the name is null or if the name is an empty string. + * @throws JMSException if the JMS provider fails to write the message due + * to some internal error. + * @throws IllegalArgumentException if the name is null or if the name is an + * empty string. * @throws MessageNotWriteableException if the message is in read-only mode. */ public void setBoolean(String name, boolean value) throws JMSException { @@ -467,11 +508,13 @@ public class ActiveMQMapMessage extends ActiveMQMessage implements MapMessage { /** * Sets a byte value with the specified name into the Map. - * - * @param name the name of the byte + * + * @param name the name of the byte * @param value the byte value to set in the Map - * @throws JMSException if the JMS provider fails to write the message due to some internal error. - * @throws IllegalArgumentException if the name is null or if the name is an empty string. + * @throws JMSException if the JMS provider fails to write the message due + * to some internal error. + * @throws IllegalArgumentException if the name is null or if the name is an + * empty string. * @throws MessageNotWriteableException if the message is in read-only mode. */ public void setByte(String name, byte value) throws JMSException { @@ -481,11 +524,13 @@ public class ActiveMQMapMessage extends ActiveMQMessage implements MapMessage { /** * Sets a short value with the specified name into the Map. - * - * @param name the name of the short + * + * @param name the name of the short * @param value the short value to set in the Map - * @throws JMSException if the JMS provider fails to write the message due to some internal error. - * @throws IllegalArgumentException if the name is null or if the name is an empty string. + * @throws JMSException if the JMS provider fails to write the message due + * to some internal error. + * @throws IllegalArgumentException if the name is null or if the name is an + * empty string. * @throws MessageNotWriteableException if the message is in read-only mode. */ public void setShort(String name, short value) throws JMSException { @@ -495,11 +540,13 @@ public class ActiveMQMapMessage extends ActiveMQMessage implements MapMessage { /** * Sets a Unicode character value with the specified name into the Map. - * - * @param name the name of the Unicode character + * + * @param name the name of the Unicode character * @param value the Unicode character value to set in the Map - * @throws JMSException if the JMS provider fails to write the message due to some internal error. - * @throws IllegalArgumentException if the name is null or if the name is an empty string. + * @throws JMSException if the JMS provider fails to write the message due + * to some internal error. + * @throws IllegalArgumentException if the name is null or if the name is an + * empty string. * @throws MessageNotWriteableException if the message is in read-only mode. */ public void setChar(String name, char value) throws JMSException { @@ -509,11 +556,13 @@ public class ActiveMQMapMessage extends ActiveMQMessage implements MapMessage { /** * Sets an int value with the specified name into the Map. - * - * @param name the name of the int + * + * @param name the name of the int * @param value the int value to set in the Map - * @throws JMSException if the JMS provider fails to write the message due to some internal error. - * @throws IllegalArgumentException if the name is null or if the name is an empty string. + * @throws JMSException if the JMS provider fails to write the message due + * to some internal error. + * @throws IllegalArgumentException if the name is null or if the name is an + * empty string. * @throws MessageNotWriteableException if the message is in read-only mode. */ public void setInt(String name, int value) throws JMSException { @@ -523,11 +572,13 @@ public class ActiveMQMapMessage extends ActiveMQMessage implements MapMessage { /** * Sets a long value with the specified name into the Map. - * - * @param name the name of the long + * + * @param name the name of the long * @param value the long value to set in the Map - * @throws JMSException if the JMS provider fails to write the message due to some internal error. - * @throws IllegalArgumentException if the name is null or if the name is an empty string. + * @throws JMSException if the JMS provider fails to write the message due + * to some internal error. + * @throws IllegalArgumentException if the name is null or if the name is an + * empty string. * @throws MessageNotWriteableException if the message is in read-only mode. */ public void setLong(String name, long value) throws JMSException { @@ -537,11 +588,13 @@ public class ActiveMQMapMessage extends ActiveMQMessage implements MapMessage { /** * Sets a float value with the specified name into the Map. - * - * @param name the name of the float + * + * @param name the name of the float * @param value the float value to set in the Map - * @throws JMSException if the JMS provider fails to write the message due to some internal error. - * @throws IllegalArgumentException if the name is null or if the name is an empty string. + * @throws JMSException if the JMS provider fails to write the message due + * to some internal error. + * @throws IllegalArgumentException if the name is null or if the name is an + * empty string. * @throws MessageNotWriteableException if the message is in read-only mode. */ public void setFloat(String name, float value) throws JMSException { @@ -551,11 +604,13 @@ public class ActiveMQMapMessage extends ActiveMQMessage implements MapMessage { /** * Sets a double value with the specified name into the Map. - * - * @param name the name of the double + * + * @param name the name of the double * @param value the double value to set in the Map - * @throws JMSException if the JMS provider fails to write the message due to some internal error. - * @throws IllegalArgumentException if the name is null or if the name is an empty string. + * @throws JMSException if the JMS provider fails to write the message due + * to some internal error. + * @throws IllegalArgumentException if the name is null or if the name is an + * empty string. * @throws MessageNotWriteableException if the message is in read-only mode. */ public void setDouble(String name, double value) throws JMSException { @@ -565,11 +620,13 @@ public class ActiveMQMapMessage extends ActiveMQMessage implements MapMessage { /** * Sets a String value with the specified name into the Map. - * - * @param name the name of the String + * + * @param name the name of the String * @param value the String value to set in the Map - * @throws JMSException if the JMS provider fails to write the message due to some internal error. - * @throws IllegalArgumentException if the name is null or if the name is an empty string. + * @throws JMSException if the JMS provider fails to write the message due + * to some internal error. + * @throws IllegalArgumentException if the name is null or if the name is an + * empty string. * @throws MessageNotWriteableException if the message is in read-only mode. */ public void setString(String name, String value) throws JMSException { @@ -579,12 +636,15 @@ public class ActiveMQMapMessage extends ActiveMQMessage implements MapMessage { /** * Sets a byte array value with the specified name into the Map. - * - * @param name the name of the byte array - * @param value the byte array value to set in the Map; the array is copied so that the value for name - * will not be altered by future modifications - * @throws JMSException if the JMS provider fails to write the message due to some internal error. - * @throws NullPointerException if the name is null, or if the name is an empty string. + * + * @param name the name of the byte array + * @param value the byte array value to set in the Map; the array is copied + * so that the value for name will not be + * altered by future modifications + * @throws JMSException if the JMS provider fails to write the message due + * to some internal error. + * @throws NullPointerException if the name is null, or if the name is an + * empty string. * @throws MessageNotWriteableException if the message is in read-only mode. */ public void setBytes(String name, byte[] value) throws JMSException { @@ -597,14 +657,17 @@ public class ActiveMQMapMessage extends ActiveMQMessage implements MapMessage { } /** - * Sets a portion of the byte array value with the specified name into the Map. - * - * @param name the name of the byte array - * @param value the byte array value to set in the Map + * Sets a portion of the byte array value with the specified name into the + * Map. + * + * @param name the name of the byte array + * @param value the byte array value to set in the Map * @param offset the initial offset within the byte array * @param length the number of bytes to use - * @throws JMSException if the JMS provider fails to write the message due to some internal error. - * @throws IllegalArgumentException if the name is null or if the name is an empty string. + * @throws JMSException if the JMS provider fails to write the message due + * to some internal error. + * @throws IllegalArgumentException if the name is null or if the name is an + * empty string. * @throws MessageNotWriteableException if the message is in read-only mode. */ public void setBytes(String name, byte[] value, int offset, int length) throws JMSException { @@ -615,15 +678,19 @@ public class ActiveMQMapMessage extends ActiveMQMessage implements MapMessage { } /** - * Sets an object value with the specified name into the Map.

This method works only for the objectified - * primitive object types (Integer,Double, Long  ...), - * String objects, and byte arrays. - * - * @param name the name of the Java object + * Sets an object value with the specified name into the Map. + *

+ * This method works only for the objectified primitive object types (Integer,Double, + * Long  ...), String objects, and byte + * arrays. + * + * @param name the name of the Java object * @param value the Java object value to set in the Map - * @throws JMSException if the JMS provider fails to write the message due to some internal error. - * @throws IllegalArgumentException if the name is null or if the name is an empty string. - * @throws MessageFormatException if the object is invalid. + * @throws JMSException if the JMS provider fails to write the message due + * to some internal error. + * @throws IllegalArgumentException if the name is null or if the name is an + * empty string. + * @throws MessageFormatException if the object is invalid. * @throws MessageNotWriteableException if the message is in read-only mode. */ public void setObject(String name, Object value) throws JMSException { @@ -640,32 +707,32 @@ public class ActiveMQMapMessage extends ActiveMQMessage implements MapMessage { } /** - * Indicates whether an item exists in this MapMessage object. - * + * Indicates whether an item exists in this MapMessage + * object. + * * @param name the name of the item to test * @return true if the item exists - * @throws JMSException if the JMS provider fails to determine if the item exists due to some internal error. + * @throws JMSException if the JMS provider fails to determine if the item + * exists due to some internal error. */ public boolean itemExists(String name) throws JMSException { initializeReading(); return map.containsKey(name); } - + private void initializeReading() throws JMSException { loadContent(); } - + private void initializeWriting() throws MessageNotWriteableException { checkReadOnlyBody(); setContent(null); } public String toString() { - return super.toString() + " ActiveMQMapMessage{ " + - "theTable = " + map + - " }"; + return super.toString() + " ActiveMQMapMessage{ " + "theTable = " + map + " }"; } - + public Map getContentMap() throws JMSException { initializeReading(); return map; diff --git a/activemq-core/src/main/java/org/apache/activemq/command/ActiveMQObjectMessage.java b/activemq-core/src/main/java/org/apache/activemq/command/ActiveMQObjectMessage.java index d6d89c9aae..16f4973556 100755 --- a/activemq-core/src/main/java/org/apache/activemq/command/ActiveMQObjectMessage.java +++ b/activemq-core/src/main/java/org/apache/activemq/command/ActiveMQObjectMessage.java @@ -17,9 +17,6 @@ package org.apache.activemq.command; - - - import org.apache.activemq.ActiveMQConnection; import org.apache.activemq.util.ByteArrayInputStream; import org.apache.activemq.util.ByteArrayOutputStream; @@ -40,17 +37,21 @@ import java.util.zip.DeflaterOutputStream; import java.util.zip.InflaterInputStream; /** - * An ObjectMessage object is used to send a message that contains a serializable object in the Java - * programming language ("Java object"). It inherits from the Message interface and adds a body containing - * a single reference to an object. Only Serializable Java objects can be used. - *

- *

If a collection of Java objects must be sent, one of the Collection classes provided since JDK 1.2 - * can be used. - *

- *

When a client receives an ObjectMessage, it is in read-only mode. If a client attempts to write to - * the message at this point, a MessageNotWriteableException is thrown. If clearBody is - * called, the message can now be both read from and written to. - * + * An ObjectMessage object is used to send a message that + * contains a serializable object in the Java programming language ("Java + * object"). It inherits from the Message interface and adds a + * body containing a single reference to an object. Only + * Serializable Java objects can be used.

+ *

+ * If a collection of Java objects must be sent, one of the + * Collection classes provided since JDK 1.2 can be used.

+ *

+ * When a client receives an ObjectMessage, it is in read-only + * mode. If a client attempts to write to the message at this point, a + * MessageNotWriteableException is thrown. If + * clearBody is called, the message can now be both read from and + * written to. + * * @openwire:marshaller code="26" * @see javax.jms.Session#createObjectMessage() * @see javax.jms.Session#createObjectMessage(Serializable) @@ -61,7 +62,9 @@ import java.util.zip.InflaterInputStream; * @see javax.jms.TextMessage */ public class ActiveMQObjectMessage extends ActiveMQMessage implements ObjectMessage { - static final ClassLoader ACTIVEMQ_CLASSLOADER = ActiveMQObjectMessage.class.getClassLoader(); //TODO verify classloader + static final ClassLoader ACTIVEMQ_CLASSLOADER = ActiveMQObjectMessage.class.getClassLoader(); // TODO + // verify + // classloader public static final byte DATA_STRUCTURE_TYPE = CommandTypes.ACTIVEMQ_OBJECT_MESSAGE; protected transient Serializable object; @@ -75,9 +78,9 @@ public class ActiveMQObjectMessage extends ActiveMQMessage implements ObjectMess private void copy(ActiveMQObjectMessage copy) { storeContent(); super.copy(copy); - copy.object=null; + copy.object = null; } - + public void storeContent() { ByteSequence bodyAsBytes = getContent(); if (bodyAsBytes == null && object != null) { @@ -85,7 +88,7 @@ public class ActiveMQObjectMessage extends ActiveMQMessage implements ObjectMess ByteArrayOutputStream bytesOut = new ByteArrayOutputStream(); OutputStream os = bytesOut; ActiveMQConnection connection = getConnection(); - if (connection!=null && connection.isUseCompression()) { + if (connection != null && connection.isUseCompression()) { compressed = true; os = new DeflaterOutputStream(os); } @@ -110,14 +113,16 @@ public class ActiveMQObjectMessage extends ActiveMQMessage implements ObjectMess return "jms/object-message"; } - /** - * Clears out the message body. Clearing a message's body does not clear its header values or property entries. - *

- *

If this message body was read-only, calling this method leaves the message body in the same state as an empty - * body in a newly created message. - * - * @throws JMSException if the JMS provider fails to clear the message body due to some internal error. + * Clears out the message body. Clearing a message's body does not clear its + * header values or property entries.

+ *

+ * If this message body was read-only, calling this method leaves the + * message body in the same state as an empty body in a newly created + * message. + * + * @throws JMSException if the JMS provider fails to clear the message body + * due to some internal error. */ public void clearBody() throws JMSException { @@ -126,16 +131,18 @@ public class ActiveMQObjectMessage extends ActiveMQMessage implements ObjectMess } /** - * Sets the serializable object containing this message's data. It is important to note that an - * ObjectMessage contains a snapshot of the object at the time setObject() is called; - * subsequent modifications of the object will have no effect on the ObjectMessage body. - * + * Sets the serializable object containing this message's data. It is + * important to note that an ObjectMessage contains a + * snapshot of the object at the time setObject() is called; + * subsequent modifications of the object will have no effect on the + * ObjectMessage body. + * * @param newObject the message's data - * @throws JMSException if the JMS provider fails to set the object due to some internal error. - * @throws javax.jms.MessageFormatException - * if object serialization fails. - * @throws javax.jms.MessageNotWriteableException - * if the message is in read-only mode. + * @throws JMSException if the JMS provider fails to set the object due to + * some internal error. + * @throws javax.jms.MessageFormatException if object serialization fails. + * @throws javax.jms.MessageNotWriteableException if the message is in + * read-only mode. */ public void setObject(Serializable newObject) throws JMSException { @@ -143,30 +150,30 @@ public class ActiveMQObjectMessage extends ActiveMQMessage implements ObjectMess this.object = newObject; setContent(null); ActiveMQConnection connection = getConnection(); - if( connection==null || !connection.isObjectMessageSerializationDefered() ) { + if (connection == null || !connection.isObjectMessageSerializationDefered()) { storeContent(); } } - /** - * Gets the serializable object containing this message's data. The default value is null. - * + * Gets the serializable object containing this message's data. The default + * value is null. + * * @return the serializable object containing this message's data * @throws JMSException */ public Serializable getObject() throws JMSException { - if (object == null && getContent()!=null ) { + if (object == null && getContent() != null) { try { ByteSequence content = getContent(); InputStream is = new ByteArrayInputStream(content); - if( isCompressed() ) { + if (isCompressed()) { is = new InflaterInputStream(is); } DataInputStream dataIn = new DataInputStream(is); ClassLoadingAwareObjectInputStream objIn = new ClassLoadingAwareObjectInputStream(dataIn); try { - object = (Serializable) objIn.readObject(); + object = (Serializable)objIn.readObject(); } catch (ClassNotFoundException ce) { throw new IOException(ce.getMessage()); } @@ -180,8 +187,9 @@ public class ActiveMQObjectMessage extends ActiveMQMessage implements ObjectMess public void onMessageRolledBack() { super.onMessageRolledBack(); - - // lets force the object to be deserialized again - as we could have changed the object + + // lets force the object to be deserialized again - as we could have + // changed the object object = null; } diff --git a/activemq-core/src/main/java/org/apache/activemq/command/ActiveMQQueue.java b/activemq-core/src/main/java/org/apache/activemq/command/ActiveMQQueue.java index 1ba47f39c0..84712b403a 100755 --- a/activemq-core/src/main/java/org/apache/activemq/command/ActiveMQQueue.java +++ b/activemq-core/src/main/java/org/apache/activemq/command/ActiveMQQueue.java @@ -21,15 +21,16 @@ import javax.jms.Queue; /** * - * @org.apache.xbean.XBean element="queue" description="An ActiveMQ Queue Destination" - * + * @org.apache.xbean.XBean element="queue" description="An ActiveMQ Queue + * Destination" + * * @openwire:marshaller code="100" * @version $Revision: 1.5 $ */ public class ActiveMQQueue extends ActiveMQDestination implements Queue { private static final long serialVersionUID = -3885260014960795889L; - public static final byte DATA_STRUCTURE_TYPE=CommandTypes.ACTIVEMQ_QUEUE; + public static final byte DATA_STRUCTURE_TYPE = CommandTypes.ACTIVEMQ_QUEUE; public ActiveMQQueue() { } diff --git a/activemq-core/src/main/java/org/apache/activemq/command/ActiveMQStreamMessage.java b/activemq-core/src/main/java/org/apache/activemq/command/ActiveMQStreamMessage.java index ca4269989b..82c9f8eb02 100755 --- a/activemq-core/src/main/java/org/apache/activemq/command/ActiveMQStreamMessage.java +++ b/activemq-core/src/main/java/org/apache/activemq/command/ActiveMQStreamMessage.java @@ -1130,8 +1130,9 @@ public class ActiveMQStreamMessage extends ActiveMQMessage implements StreamMess checkWriteOnlyBody(); if (this.dataIn == null) { ByteSequence data = getContent(); - if (data == null) + if (data == null) { data = new ByteSequence(new byte[] {}, 0, 0); + } InputStream is = new ByteArrayInputStream(data); if (isCompressed()) { is = new InflaterInputStream(is); diff --git a/activemq-core/src/main/java/org/apache/activemq/command/ActiveMQTempTopic.java b/activemq-core/src/main/java/org/apache/activemq/command/ActiveMQTempTopic.java index 9696b8f128..6ccb242c01 100755 --- a/activemq-core/src/main/java/org/apache/activemq/command/ActiveMQTempTopic.java +++ b/activemq-core/src/main/java/org/apache/activemq/command/ActiveMQTempTopic.java @@ -26,20 +26,19 @@ import javax.jms.TemporaryTopic; public class ActiveMQTempTopic extends ActiveMQTempDestination implements TemporaryTopic { private static final long serialVersionUID = -4325596784597300253L; - public static final byte DATA_STRUCTURE_TYPE=CommandTypes.ACTIVEMQ_TEMP_TOPIC; + public static final byte DATA_STRUCTURE_TYPE = CommandTypes.ACTIVEMQ_TEMP_TOPIC; public ActiveMQTempTopic() { } - + public ActiveMQTempTopic(String name) { super(name); } - + public ActiveMQTempTopic(ConnectionId connectionId, long sequenceId) { super(connectionId.getValue(), sequenceId); } - public byte getDataStructureType() { return DATA_STRUCTURE_TYPE; } diff --git a/activemq-core/src/main/java/org/apache/activemq/command/ActiveMQTextMessage.java b/activemq-core/src/main/java/org/apache/activemq/command/ActiveMQTextMessage.java index 86dfc952c4..9daaa67ee8 100755 --- a/activemq-core/src/main/java/org/apache/activemq/command/ActiveMQTextMessage.java +++ b/activemq-core/src/main/java/org/apache/activemq/command/ActiveMQTextMessage.java @@ -138,8 +138,9 @@ public class ActiveMQTextMessage extends ActiveMQMessage implements TextMessage public int getSize() { if (size == 0 && content == null && text != null) { size = AVERAGE_MESSAGE_SIZE_OVERHEAD; - if (marshalledProperties != null) + if (marshalledProperties != null) { size += marshalledProperties.getLength(); + } size = text.length() * 2; } return super.getSize(); diff --git a/activemq-core/src/main/java/org/apache/activemq/command/BrokerId.java b/activemq-core/src/main/java/org/apache/activemq/command/BrokerId.java index 28ec61daeb..acc57f049d 100755 --- a/activemq-core/src/main/java/org/apache/activemq/command/BrokerId.java +++ b/activemq-core/src/main/java/org/apache/activemq/command/BrokerId.java @@ -37,10 +37,12 @@ public class BrokerId implements DataStructure { } public boolean equals(Object o) { - if (this == o) + if (this == o) { return true; - if (o == null || o.getClass() != BrokerId.class) + } + if (o == null || o.getClass() != BrokerId.class) { return false; + } BrokerId id = (BrokerId)o; return value.equals(id.value); } diff --git a/activemq-core/src/main/java/org/apache/activemq/command/ConnectionError.java b/activemq-core/src/main/java/org/apache/activemq/command/ConnectionError.java index e54334c67a..e702eb6f46 100644 --- a/activemq-core/src/main/java/org/apache/activemq/command/ConnectionError.java +++ b/activemq-core/src/main/java/org/apache/activemq/command/ConnectionError.java @@ -18,7 +18,6 @@ package org.apache.activemq.command; import org.apache.activemq.state.CommandVisitor; - /** * * @openwire:marshaller code="16" @@ -26,38 +25,39 @@ import org.apache.activemq.state.CommandVisitor; */ public class ConnectionError extends BaseCommand { - public static final byte DATA_STRUCTURE_TYPE=CommandTypes.CONNECTION_ERROR; + public static final byte DATA_STRUCTURE_TYPE = CommandTypes.CONNECTION_ERROR; protected ConnectionId connectionId; Throwable exception; - + public byte getDataStructureType() { return DATA_STRUCTURE_TYPE; } - + public Response visit(CommandVisitor visitor) throws Exception { return visitor.processConnectionError(this); } /** * @openwire:property version=1 - */ + */ public Throwable getException() { return exception; } - + public void setException(Throwable exception) { this.exception = exception; } /** * @openwire:property version=1 - */ + */ public ConnectionId getConnectionId() { return connectionId; } + public void setConnectionId(ConnectionId connectionId) { this.connectionId = connectionId; } - + } diff --git a/activemq-core/src/main/java/org/apache/activemq/command/ConnectionInfo.java b/activemq-core/src/main/java/org/apache/activemq/command/ConnectionInfo.java index 1797e6c38a..cb2f99e1cb 100755 --- a/activemq-core/src/main/java/org/apache/activemq/command/ConnectionInfo.java +++ b/activemq-core/src/main/java/org/apache/activemq/command/ConnectionInfo.java @@ -18,16 +18,15 @@ package org.apache.activemq.command; import org.apache.activemq.state.CommandVisitor; - /** * * @openwire:marshaller code="3" * @version $Revision: 1.11 $ */ public class ConnectionInfo extends BaseCommand { - - public static final byte DATA_STRUCTURE_TYPE=CommandTypes.CONNECTION_INFO; - + + public static final byte DATA_STRUCTURE_TYPE = CommandTypes.CONNECTION_INFO; + protected ConnectionId connectionId; protected String clientId; protected String userName; @@ -35,19 +34,20 @@ public class ConnectionInfo extends BaseCommand { protected BrokerId[] brokerPath; protected boolean brokerMasterConnector; protected boolean manageable; - protected boolean clientMaster=true; - protected transient Object transportContext; - - public ConnectionInfo() { - } - public ConnectionInfo(ConnectionId connectionId) { - this.connectionId=connectionId; + protected boolean clientMaster = true; + protected transient Object transportContext; + + public ConnectionInfo() { } - + + public ConnectionInfo(ConnectionId connectionId) { + this.connectionId = connectionId; + } + public byte getDataStructureType() { return DATA_STRUCTURE_TYPE; } - + public void copy(ConnectionInfo copy) { super.copy(copy); copy.clientId = clientId; @@ -56,7 +56,7 @@ public class ConnectionInfo extends BaseCommand { copy.brokerPath = brokerPath; copy.brokerMasterConnector = brokerMasterConnector; copy.manageable = manageable; - } + } /** * @openwire:property version=1 cache=true @@ -64,20 +64,22 @@ public class ConnectionInfo extends BaseCommand { public ConnectionId getConnectionId() { return connectionId; } + public void setConnectionId(ConnectionId connectionId) { this.connectionId = connectionId; } - + /** * @openwire:property version=1 */ public String getClientId() { return clientId; } + public void setClientId(String clientId) { this.clientId = clientId; } - + public RemoveInfo createRemoveCommand() { RemoveInfo command = new RemoveInfo(getConnectionId()); command.setResponseRequired(isResponseRequired()); @@ -90,6 +92,7 @@ public class ConnectionInfo extends BaseCommand { public String getPassword() { return password; } + public void setPassword(String password) { this.password = password; } @@ -100,85 +103,91 @@ public class ConnectionInfo extends BaseCommand { public String getUserName() { return userName; } + public void setUserName(String userName) { this.userName = userName; } /** - * The route of brokers the command has moved through. + * The route of brokers the command has moved through. * * @openwire:property version=1 cache=true */ public BrokerId[] getBrokerPath() { return brokerPath; } + public void setBrokerPath(BrokerId[] brokerPath) { this.brokerPath = brokerPath; } - + public Response visit(CommandVisitor visitor) throws Exception { - return visitor.processAddConnection( this ); + return visitor.processAddConnection(this); } + /** * @openwire:property version=1 */ - public boolean isBrokerMasterConnector(){ + public boolean isBrokerMasterConnector() { return brokerMasterConnector; } + /** * @param brokerMasterConnector The brokerMasterConnector to set. */ - public void setBrokerMasterConnector(boolean slaveBroker){ - this.brokerMasterConnector=slaveBroker; + public void setBrokerMasterConnector(boolean slaveBroker) { + this.brokerMasterConnector = slaveBroker; } + /** * @openwire:property version=1 */ - public boolean isManageable(){ + public boolean isManageable() { return manageable; } + /** * @param manageable The manageable to set. */ - public void setManageable(boolean manageable){ - this.manageable=manageable; + public void setManageable(boolean manageable) { + this.manageable = manageable; } - + /** - * Transports may wish to associate additional data with the connection. For - * example, an SSL transport may use this field to attach the client certificates - * used when the conection was established. + * Transports may wish to associate additional data with the connection. For + * example, an SSL transport may use this field to attach the client + * certificates used when the conection was established. * * @return the transport context. */ - public Object getTransportContext() { - return transportContext; - } - - /** - * Transports may wish to associate additional data with the connection. For - * example, an SSL transport may use this field to attach the client certificates - * used when the conection was established. - * - * @param transportContext value used to set the transport context - */ - public void setTransportContext(Object transportContext) { - this.transportContext = transportContext; - } - + public Object getTransportContext() { + return transportContext; + } + + /** + * Transports may wish to associate additional data with the connection. For + * example, an SSL transport may use this field to attach the client + * certificates used when the conection was established. + * + * @param transportContext value used to set the transport context + */ + public void setTransportContext(Object transportContext) { + this.transportContext = transportContext; + } + /** * @openwire:property version=2 * @return the clientMaster */ - public boolean isClientMaster(){ + public boolean isClientMaster() { return this.clientMaster; } - + /** * @param clientMaster the clientMaster to set */ - public void setClientMaster(boolean clientMaster){ - this.clientMaster=clientMaster; + public void setClientMaster(boolean clientMaster) { + this.clientMaster = clientMaster; } } diff --git a/activemq-core/src/main/java/org/apache/activemq/command/ConsumerInfo.java b/activemq-core/src/main/java/org/apache/activemq/command/ConsumerInfo.java index c6b43146df..925cf9d9a8 100755 --- a/activemq-core/src/main/java/org/apache/activemq/command/ConsumerInfo.java +++ b/activemq-core/src/main/java/org/apache/activemq/command/ConsumerInfo.java @@ -46,14 +46,17 @@ public class ConsumerInfo extends BaseCommand { protected byte priority; protected BrokerId[] brokerPath; protected boolean optimizedAcknowledge; - protected transient int currentPrefetchSize;// used by the broker - protected boolean noRangeAcks; // if true, the consumer will not send range - // acks. + // used by the broker + protected transient int currentPrefetchSize; + // if true, the consumer will not send range + protected boolean noRangeAcks; + // acks. protected BooleanExpression additionalPredicate; protected transient boolean networkSubscription; // this subscription - // originated from a - // network connection + + // originated from a + // network connection public ConsumerInfo() { } diff --git a/activemq-core/src/main/java/org/apache/activemq/command/DataResponse.java b/activemq-core/src/main/java/org/apache/activemq/command/DataResponse.java index 87cf277247..92b9bbddb5 100755 --- a/activemq-core/src/main/java/org/apache/activemq/command/DataResponse.java +++ b/activemq-core/src/main/java/org/apache/activemq/command/DataResponse.java @@ -22,15 +22,16 @@ package org.apache.activemq.command; * @version $Revision$ */ public class DataResponse extends Response { - + DataStructure data; - - public static final byte DATA_STRUCTURE_TYPE=CommandTypes.DATA_RESPONSE; - - public DataResponse() { + + public static final byte DATA_STRUCTURE_TYPE = CommandTypes.DATA_RESPONSE; + + public DataResponse() { } + public DataResponse(DataStructure data) { - this.data=data; + this.data = data; } public byte getDataStructureType() { @@ -39,12 +40,13 @@ public class DataResponse extends Response { /** * @openwire:property version=1 - */ + */ public DataStructure getData() { return data; } + public void setData(DataStructure data) { this.data = data; } - + } diff --git a/activemq-core/src/main/java/org/apache/activemq/command/MessageDispatch.java b/activemq-core/src/main/java/org/apache/activemq/command/MessageDispatch.java index 4d7eff643a..11fc09182a 100755 --- a/activemq-core/src/main/java/org/apache/activemq/command/MessageDispatch.java +++ b/activemq-core/src/main/java/org/apache/activemq/command/MessageDispatch.java @@ -18,7 +18,6 @@ package org.apache.activemq.command; import org.apache.activemq.state.CommandVisitor; - /** * * @openwire:marshaller code="21" @@ -26,7 +25,7 @@ import org.apache.activemq.state.CommandVisitor; */ public class MessageDispatch extends BaseCommand { - public static final byte DATA_STRUCTURE_TYPE=CommandTypes.MESSAGE_DISPATCH; + public static final byte DATA_STRUCTURE_TYPE = CommandTypes.MESSAGE_DISPATCH; protected ConsumerId consumerId; protected ActiveMQDestination destination; @@ -36,11 +35,11 @@ public class MessageDispatch extends BaseCommand { transient protected long deliverySequenceId; transient protected Object consumer; transient protected Runnable transmitCallback; - + public byte getDataStructureType() { return DATA_STRUCTURE_TYPE; } - + public boolean isMessageDispatch() { return true; } @@ -51,6 +50,7 @@ public class MessageDispatch extends BaseCommand { public ConsumerId getConsumerId() { return consumerId; } + public void setConsumerId(ConsumerId consumerId) { this.consumerId = consumerId; } @@ -61,16 +61,18 @@ public class MessageDispatch extends BaseCommand { public ActiveMQDestination getDestination() { return destination; } + public void setDestination(ActiveMQDestination destination) { this.destination = destination; } - + /** * @openwire:property version=1 */ public Message getMessage() { return message; } + public void setMessage(Message message) { this.message = message; } @@ -78,16 +80,18 @@ public class MessageDispatch extends BaseCommand { public long getDeliverySequenceId() { return deliverySequenceId; } + public void setDeliverySequenceId(long deliverySequenceId) { this.deliverySequenceId = deliverySequenceId; } - + /** * @openwire:property version=1 */ public int getRedeliveryCounter() { return redeliveryCounter; } + public void setRedeliveryCounter(int deliveryCounter) { this.redeliveryCounter = deliveryCounter; } @@ -104,12 +108,12 @@ public class MessageDispatch extends BaseCommand { return visitor.processMessageDispatch(this); } - public Runnable getTransmitCallback() { - return transmitCallback; - } + public Runnable getTransmitCallback() { + return transmitCallback; + } + + public void setTransmitCallback(Runnable transmitCallback) { + this.transmitCallback = transmitCallback; + } - public void setTransmitCallback(Runnable transmitCallback) { - this.transmitCallback = transmitCallback; - } - } diff --git a/activemq-core/src/main/java/org/apache/activemq/command/ProducerInfo.java b/activemq-core/src/main/java/org/apache/activemq/command/ProducerInfo.java index 4730fe5693..b21cab1b92 100755 --- a/activemq-core/src/main/java/org/apache/activemq/command/ProducerInfo.java +++ b/activemq-core/src/main/java/org/apache/activemq/command/ProducerInfo.java @@ -25,14 +25,14 @@ import org.apache.activemq.state.CommandVisitor; */ public class ProducerInfo extends BaseCommand { - public static final byte DATA_STRUCTURE_TYPE=CommandTypes.PRODUCER_INFO; + public static final byte DATA_STRUCTURE_TYPE = CommandTypes.PRODUCER_INFO; protected ProducerId producerId; protected ActiveMQDestination destination; protected BrokerId[] brokerPath; protected boolean dispatchAsync; protected int windowSize; - + public ProducerInfo() { } @@ -59,77 +59,80 @@ public class ProducerInfo extends BaseCommand { public byte getDataStructureType() { return DATA_STRUCTURE_TYPE; } - + /** * @openwire:property version=1 cache=true */ public ProducerId getProducerId() { return producerId; } + public void setProducerId(ProducerId producerId) { this.producerId = producerId; } - + /** * @openwire:property version=1 cache=true */ public ActiveMQDestination getDestination() { return destination; - } + } + public void setDestination(ActiveMQDestination destination) { this.destination = destination; } - + public RemoveInfo createRemoveCommand() { RemoveInfo command = new RemoveInfo(getProducerId()); command.setResponseRequired(isResponseRequired()); return command; } - + /** - * The route of brokers the command has moved through. + * The route of brokers the command has moved through. * * @openwire:property version=1 cache=true */ public BrokerId[] getBrokerPath() { return brokerPath; } + public void setBrokerPath(BrokerId[] brokerPath) { this.brokerPath = brokerPath; } public Response visit(CommandVisitor visitor) throws Exception { - return visitor.processAddProducer( this ); + return visitor.processAddProducer(this); } /** - * If the broker should dispatch messages from this producer async. Since sync - * dispatch could potentally block the producer thread, this could be an important - * setting for the producer. + * If the broker should dispatch messages from this producer async. Since + * sync dispatch could potentally block the producer thread, this could be + * an important setting for the producer. * * @openwire:property version=2 */ - public boolean isDispatchAsync() { - return dispatchAsync; - } + public boolean isDispatchAsync() { + return dispatchAsync; + } - public void setDispatchAsync(boolean dispatchAsync) { - this.dispatchAsync = dispatchAsync; - } + public void setDispatchAsync(boolean dispatchAsync) { + this.dispatchAsync = dispatchAsync; + } /** - * Used to configure the producer window size. A producer will - * send up to the configured window size worth of payload data to - * the broker before waiting for an Ack that allows him to send more. + * Used to configure the producer window size. A producer will send up to + * the configured window size worth of payload data to the broker before + * waiting for an Ack that allows him to send more. * * @openwire:property version=3 */ - public int getWindowSize() { - return windowSize; - } + public int getWindowSize() { + return windowSize; + } - public void setWindowSize(int windowSize) { - this.windowSize = windowSize; - } + public void setWindowSize(int windowSize) { + this.windowSize = windowSize; + } } diff --git a/activemq-core/src/main/java/org/apache/activemq/command/RemoveInfo.java b/activemq-core/src/main/java/org/apache/activemq/command/RemoveInfo.java index f58d1fc681..a9d717168a 100755 --- a/activemq-core/src/main/java/org/apache/activemq/command/RemoveInfo.java +++ b/activemq-core/src/main/java/org/apache/activemq/command/RemoveInfo.java @@ -22,26 +22,27 @@ import org.apache.activemq.state.CommandVisitor; /** * Removes a consumer, producer, session or connection. - * + * * @openwire:marshaller code="12" * @version $Revision$ */ public class RemoveInfo extends BaseCommand { - - public static final byte DATA_STRUCTURE_TYPE=CommandTypes.REMOVE_INFO; + + public static final byte DATA_STRUCTURE_TYPE = CommandTypes.REMOVE_INFO; protected DataStructure objectId; public byte getDataStructureType() { return DATA_STRUCTURE_TYPE; - } + } - public RemoveInfo() { + public RemoveInfo() { } + public RemoveInfo(DataStructure objectId) { - this.objectId=objectId; + this.objectId = objectId; } - + /** * @openwire:property version=1 cache=true */ @@ -56,32 +57,32 @@ public class RemoveInfo extends BaseCommand { public Response visit(CommandVisitor visitor) throws Exception { switch (objectId.getDataStructureType()) { case ConnectionId.DATA_STRUCTURE_TYPE: - return visitor.processRemoveConnection((ConnectionId) objectId); + return visitor.processRemoveConnection((ConnectionId)objectId); case SessionId.DATA_STRUCTURE_TYPE: - return visitor.processRemoveSession((SessionId) objectId); + return visitor.processRemoveSession((SessionId)objectId); case ConsumerId.DATA_STRUCTURE_TYPE: - return visitor.processRemoveConsumer((ConsumerId) objectId); + return visitor.processRemoveConsumer((ConsumerId)objectId); case ProducerId.DATA_STRUCTURE_TYPE: - return visitor.processRemoveProducer((ProducerId) objectId); + return visitor.processRemoveProducer((ProducerId)objectId); default: - throw new IOException("Unknown remove command type: "+ objectId.getDataStructureType()); + throw new IOException("Unknown remove command type: " + objectId.getDataStructureType()); } } - + /** * Returns true if this event is for a removed connection */ public boolean isConnectionRemove() { return objectId.getDataStructureType() == ConnectionId.DATA_STRUCTURE_TYPE; } - + /** * Returns true if this event is for a removed session */ public boolean isSessionRemove() { return objectId.getDataStructureType() == SessionId.DATA_STRUCTURE_TYPE; } - + /** * Returns true if this event is for a removed consumer */ diff --git a/activemq-core/src/main/java/org/apache/activemq/command/SessionId.java b/activemq-core/src/main/java/org/apache/activemq/command/SessionId.java index 523c7e850a..92e08061b5 100755 --- a/activemq-core/src/main/java/org/apache/activemq/command/SessionId.java +++ b/activemq-core/src/main/java/org/apache/activemq/command/SessionId.java @@ -21,62 +21,61 @@ package org.apache.activemq.command; * @openwire:marshaller code="121" * @version $Revision$ */ -public class SessionId implements DataStructure { +public class SessionId implements DataStructure { - public static final byte DATA_STRUCTURE_TYPE=CommandTypes.SESSION_ID; + public static final byte DATA_STRUCTURE_TYPE = CommandTypes.SESSION_ID; protected String connectionId; protected long value; - + protected transient int hashCode; protected transient String key; protected transient ConnectionId parentId; - - public SessionId() { + + public SessionId() { } - + public SessionId(ConnectionId connectionId, long sessionId) { this.connectionId = connectionId.getValue(); - this.value=sessionId; + this.value = sessionId; } - + public SessionId(SessionId id) { this.connectionId = id.getConnectionId(); - this.value=id.getValue(); + this.value = id.getValue(); } public SessionId(ProducerId id) { this.connectionId = id.getConnectionId(); - this.value=id.getSessionId(); + this.value = id.getSessionId(); } - + public SessionId(ConsumerId id) { this.connectionId = id.getConnectionId(); - this.value=id.getSessionId(); + this.value = id.getSessionId(); } - + public ConnectionId getParentId() { - if( parentId == null ) { + if (parentId == null) { parentId = new ConnectionId(this); } return parentId; } public int hashCode() { - if( hashCode == 0 ) { + if (hashCode == 0) { hashCode = connectionId.hashCode() ^ (int)value; } return hashCode; } - + public boolean equals(Object o) { - if( this == o ) + if (this == o) return true; - if( o == null || o.getClass()!=SessionId.class ) + if (o == null || o.getClass() != SessionId.class) return false; - SessionId id = (SessionId) o; - return value==id.value - && connectionId.equals(id.connectionId); + SessionId id = (SessionId)o; + return value == id.value && connectionId.equals(id.connectionId); } public byte getDataStructureType() { @@ -88,7 +87,8 @@ public class SessionId implements DataStructure { */ public String getConnectionId() { return connectionId; - } + } + public void setConnectionId(String connectionId) { this.connectionId = connectionId; } @@ -99,13 +99,14 @@ public class SessionId implements DataStructure { public long getValue() { return value; } + public void setValue(long sessionId) { this.value = sessionId; } - + public String toString() { - if( key==null ) { - key = connectionId+":"+value; + if (key == null) { + key = connectionId + ":" + value; } return key; } diff --git a/activemq-core/src/main/java/org/apache/activemq/command/SessionInfo.java b/activemq-core/src/main/java/org/apache/activemq/command/SessionInfo.java index b3896824d8..14eed10cd8 100755 --- a/activemq-core/src/main/java/org/apache/activemq/command/SessionInfo.java +++ b/activemq-core/src/main/java/org/apache/activemq/command/SessionInfo.java @@ -25,22 +25,22 @@ import org.apache.activemq.state.CommandVisitor; */ public class SessionInfo extends BaseCommand { - public static final byte DATA_STRUCTURE_TYPE=CommandTypes.SESSION_INFO; + public static final byte DATA_STRUCTURE_TYPE = CommandTypes.SESSION_INFO; protected SessionId sessionId; - + public SessionInfo() { sessionId = new SessionId(); } - + public SessionInfo(ConnectionInfo connectionInfo, long sessionId) { this.sessionId = new SessionId(connectionInfo.getConnectionId(), sessionId); } - + public SessionInfo(SessionId sessionId) { this.sessionId = sessionId; } - + public byte getDataStructureType() { return DATA_STRUCTURE_TYPE; } @@ -50,11 +50,12 @@ public class SessionInfo extends BaseCommand { */ public SessionId getSessionId() { return sessionId; - } + } + public void setSessionId(SessionId sessionId) { this.sessionId = sessionId; } - + public RemoveInfo createRemoveCommand() { RemoveInfo command = new RemoveInfo(getSessionId()); command.setResponseRequired(isResponseRequired()); @@ -62,7 +63,7 @@ public class SessionInfo extends BaseCommand { } public Response visit(CommandVisitor visitor) throws Exception { - return visitor.processAddSession( this); + return visitor.processAddSession(this); } } diff --git a/activemq-core/src/main/java/org/apache/activemq/command/ShutdownInfo.java b/activemq-core/src/main/java/org/apache/activemq/command/ShutdownInfo.java index b8ba8df6e3..25a4f8e0b0 100755 --- a/activemq-core/src/main/java/org/apache/activemq/command/ShutdownInfo.java +++ b/activemq-core/src/main/java/org/apache/activemq/command/ShutdownInfo.java @@ -25,19 +25,18 @@ import org.apache.activemq.state.CommandVisitor; */ public class ShutdownInfo extends BaseCommand { - public static final byte DATA_STRUCTURE_TYPE=CommandTypes.SHUTDOWN_INFO; - + public static final byte DATA_STRUCTURE_TYPE = CommandTypes.SHUTDOWN_INFO; + public byte getDataStructureType() { return DATA_STRUCTURE_TYPE; } public Response visit(CommandVisitor visitor) throws Exception { - return visitor.processShutdown( this ); + return visitor.processShutdown(this); } - - public boolean isShutdownInfo(){ + + public boolean isShutdownInfo() { return true; } - } diff --git a/activemq-core/src/main/java/org/apache/activemq/command/SubscriptionInfo.java b/activemq-core/src/main/java/org/apache/activemq/command/SubscriptionInfo.java index 934446ead6..467eea1bd3 100755 --- a/activemq-core/src/main/java/org/apache/activemq/command/SubscriptionInfo.java +++ b/activemq-core/src/main/java/org/apache/activemq/command/SubscriptionInfo.java @@ -18,7 +18,6 @@ package org.apache.activemq.command; import org.apache.activemq.util.IntrospectionSupport; - /** * Used to represent a durable subscription. * @@ -27,14 +26,14 @@ import org.apache.activemq.util.IntrospectionSupport; */ public class SubscriptionInfo implements DataStructure { - public static final byte DATA_STRUCTURE_TYPE=CommandTypes.DURABLE_SUBSCRIPTION_INFO; + public static final byte DATA_STRUCTURE_TYPE = CommandTypes.DURABLE_SUBSCRIPTION_INFO; protected ActiveMQDestination subscribedDestination; protected ActiveMQDestination destination; protected String clientId; protected String subscriptionName; protected String selector; - + public byte getDataStructureType() { return DATA_STRUCTURE_TYPE; } @@ -51,8 +50,8 @@ public class SubscriptionInfo implements DataStructure { } /** - * This is the a resolved destination that the subscription is receiving messages from. - * This will never be a pattern or a composite destination. + * This is the a resolved destination that the subscription is receiving + * messages from. This will never be a pattern or a composite destination. * * @openwire:property version=1 cache=true */ @@ -84,13 +83,13 @@ public class SubscriptionInfo implements DataStructure { } /** - * @param subscriptionName - * * @deprecated + * @param subscriptionName * + * @deprecated */ public void setSubcriptionName(String subscriptionName) { this.subscriptionName = subscriptionName; } - + public String getSubscriptionName() { return subscriptionName; } @@ -102,46 +101,51 @@ public class SubscriptionInfo implements DataStructure { public boolean isMarshallAware() { return false; } - + public String toString() { return IntrospectionSupport.toString(this); } - + public int hashCode() { - int h1 = clientId != null ? clientId.hashCode():-1; - int h2 = subscriptionName != null ? subscriptionName.hashCode():-1; + int h1 = clientId != null ? clientId.hashCode() : -1; + int h2 = subscriptionName != null ? subscriptionName.hashCode() : -1; return h1 ^ h2; } - - public boolean equals(Object obj){ - boolean result=false; - if(obj instanceof SubscriptionInfo){ - SubscriptionInfo other=(SubscriptionInfo)obj; - result=(clientId==null&&other.clientId==null||clientId!=null&&other.clientId!=null - &&clientId.equals(other.clientId)) - &&(subscriptionName==null&&other.subscriptionName==null||subscriptionName!=null - &&other.subscriptionName!=null&&subscriptionName.equals(other.subscriptionName)); + + public boolean equals(Object obj) { + boolean result = false; + if (obj instanceof SubscriptionInfo) { + SubscriptionInfo other = (SubscriptionInfo)obj; + result = (clientId == null && other.clientId == null || clientId != null + && other.clientId != null + && clientId.equals(other.clientId)) + && (subscriptionName == null && other.subscriptionName == null || subscriptionName != null + && other.subscriptionName != null + && subscriptionName + .equals(other.subscriptionName)); } return result; } /** - * The destination the client originally subscribed to.. This may not match the {@see getDestination} method - * if the subscribed destination uses patterns or composites. - * - * If the subscribed destinationis not set, this just ruturns the desitination. - * + * The destination the client originally subscribed to.. This may not match + * the {@see getDestination} method if the subscribed destination uses + * patterns or composites. + * + * If the subscribed destinationis not set, this just ruturns the + * desitination. + * * @openwire:property version=3 */ - public ActiveMQDestination getSubscribedDestination() { - if( subscribedDestination == null ) { - return getDestination(); - } - return subscribedDestination; - } + public ActiveMQDestination getSubscribedDestination() { + if (subscribedDestination == null) { + return getDestination(); + } + return subscribedDestination; + } - public void setSubscribedDestination(ActiveMQDestination subscribedDestination) { - this.subscribedDestination = subscribedDestination; - } + public void setSubscribedDestination(ActiveMQDestination subscribedDestination) { + this.subscribedDestination = subscribedDestination; + } } diff --git a/activemq-core/src/main/java/org/apache/activemq/command/TransactionInfo.java b/activemq-core/src/main/java/org/apache/activemq/command/TransactionInfo.java index 916a0354d2..053dfc7715 100755 --- a/activemq-core/src/main/java/org/apache/activemq/command/TransactionInfo.java +++ b/activemq-core/src/main/java/org/apache/activemq/command/TransactionInfo.java @@ -27,29 +27,28 @@ import org.apache.activemq.state.CommandVisitor; */ public class TransactionInfo extends BaseCommand { - public static final byte DATA_STRUCTURE_TYPE=CommandTypes.TRANSACTION_INFO; - + public static final byte DATA_STRUCTURE_TYPE = CommandTypes.TRANSACTION_INFO; public static final byte BEGIN = 0; - public static final byte PREPARE=1; - public static final byte COMMIT_ONE_PHASE=2; - public static final byte COMMIT_TWO_PHASE=3; - public static final byte ROLLBACK=4; - public static final byte RECOVER=5; - public static final byte FORGET=6; - public static final byte END=7; - + public static final byte PREPARE = 1; + public static final byte COMMIT_ONE_PHASE = 2; + public static final byte COMMIT_TWO_PHASE = 3; + public static final byte ROLLBACK = 4; + public static final byte RECOVER = 5; + public static final byte FORGET = 6; + public static final byte END = 7; + protected byte type; protected ConnectionId connectionId; protected TransactionId transactionId; - - public TransactionInfo() { + + public TransactionInfo() { } - + public TransactionInfo(ConnectionId connectionId, TransactionId transactionId, byte type) { - this.connectionId=connectionId; - this.transactionId=transactionId; - this.type=type; + this.connectionId = connectionId; + this.transactionId = transactionId; + this.type = type; } public byte getDataStructureType() { @@ -58,20 +57,22 @@ public class TransactionInfo extends BaseCommand { /** * @openwire:property version=1 cache=true - */ + */ public ConnectionId getConnectionId() { return connectionId; } + public void setConnectionId(ConnectionId connectionId) { this.connectionId = connectionId; } /** * @openwire:property version=1 cache=true - */ + */ public TransactionId getTransactionId() { return transactionId; - } + } + public void setTransactionId(TransactionId transactionId) { this.transactionId = transactionId; } @@ -81,13 +82,14 @@ public class TransactionInfo extends BaseCommand { */ public byte getType() { return type; - } + } + public void setType(byte type) { this.type = type; } public Response visit(CommandVisitor visitor) throws Exception { - switch( type ) { + switch (type) { case TransactionInfo.BEGIN: return visitor.processBeginTransaction(this); case TransactionInfo.END: @@ -105,7 +107,7 @@ public class TransactionInfo extends BaseCommand { case TransactionInfo.FORGET: return visitor.processForgetTransaction(this); default: - throw new IOException("Transaction info type unknown: "+type); + throw new IOException("Transaction info type unknown: " + type); } } diff --git a/activemq-core/src/main/java/org/apache/activemq/command/WireFormatInfo.java b/activemq-core/src/main/java/org/apache/activemq/command/WireFormatInfo.java index 4bf674030e..f276cc7a57 100755 --- a/activemq-core/src/main/java/org/apache/activemq/command/WireFormatInfo.java +++ b/activemq-core/src/main/java/org/apache/activemq/command/WireFormatInfo.java @@ -38,14 +38,14 @@ import org.apache.activemq.wireformat.WireFormat; */ public class WireFormatInfo implements Command, MarshallAware { - private static final int MAX_PROPERTY_SIZE = 1024*4; - public static final byte DATA_STRUCTURE_TYPE = CommandTypes.WIREFORMAT_INFO; - static final private byte MAGIC[] = new byte[] { 'A', 'c', 't', 'i', 'v', 'e', 'M', 'Q' }; + private static final int MAX_PROPERTY_SIZE = 1024 * 4; + public static final byte DATA_STRUCTURE_TYPE = CommandTypes.WIREFORMAT_INFO; + static final private byte MAGIC[] = new byte[] {'A', 'c', 't', 'i', 'v', 'e', 'M', 'Q'}; protected byte magic[] = MAGIC; protected int version; protected ByteSequence marshalledProperties; - + protected transient Map properties; private transient Endpoint from; private transient Endpoint to; @@ -68,6 +68,7 @@ public class WireFormatInfo implements Command, MarshallAware { public byte[] getMagic() { return magic; } + public void setMagic(byte[] magic) { this.magic = magic; } @@ -78,16 +79,18 @@ public class WireFormatInfo implements Command, MarshallAware { public int getVersion() { return version; } + public void setVersion(int version) { this.version = version; } - + /** * @openwire:property version=1 */ public ByteSequence getMarshalledProperties() { return marshalledProperties; } + public void setMarshalledProperties(ByteSequence marshalledProperties) { this.marshalledProperties = marshalledProperties; } @@ -104,7 +107,8 @@ public class WireFormatInfo implements Command, MarshallAware { } /** - * The endpoint within the transport where this message is going to - null means all endpoints. + * The endpoint within the transport where this message is going to - null + * means all endpoints. */ public Endpoint getTo() { return to; @@ -113,34 +117,34 @@ public class WireFormatInfo implements Command, MarshallAware { public void setTo(Endpoint to) { this.to = to; } - - ////////////////////// + + // //////////////////// // // Implementation Methods. // - ////////////////////// - + // //////////////////// + public Object getProperty(String name) throws IOException { - if( properties == null ) { - if( marshalledProperties ==null ) + if (properties == null) { + if (marshalledProperties == null) return null; properties = unmarsallProperties(marshalledProperties); } return properties.get(name); } - + public Map getProperties() throws IOException { - if( properties == null ) { - if( marshalledProperties==null ) + if (properties == null) { + if (marshalledProperties == null) return Collections.EMPTY_MAP; properties = unmarsallProperties(marshalledProperties); } return Collections.unmodifiableMap(properties); } - + public void clearProperties() { marshalledProperties = null; - properties=null; + properties = null; } public void setProperty(String name, Object value) throws IOException { @@ -149,8 +153,8 @@ public class WireFormatInfo implements Command, MarshallAware { } protected void lazyCreateProperties() throws IOException { - if( properties == null ) { - if( marshalledProperties == null ) { + if (properties == null) { + if (marshalledProperties == null) { properties = new HashMap(); } else { properties = unmarsallProperties(marshalledProperties); @@ -158,14 +162,16 @@ public class WireFormatInfo implements Command, MarshallAware { } } } - + private Map unmarsallProperties(ByteSequence marshalledProperties) throws IOException { - return MarshallingSupport.unmarshalPrimitiveMap(new DataInputStream(new ByteArrayInputStream(marshalledProperties)), MAX_PROPERTY_SIZE); + return MarshallingSupport + .unmarshalPrimitiveMap(new DataInputStream(new ByteArrayInputStream(marshalledProperties)), + MAX_PROPERTY_SIZE); } public void beforeMarshall(WireFormat wireFormat) throws IOException { // Need to marshal the properties. - if( marshalledProperties==null && properties!=null ) { + if (marshalledProperties == null && properties != null) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); DataOutputStream os = new DataOutputStream(baos); MarshallingSupport.marshalPrimitiveMap(properties, os); @@ -183,7 +189,6 @@ public class WireFormatInfo implements Command, MarshallAware { public void afterUnmarshall(WireFormat wireFormat) throws IOException { } - public boolean isValid() { return magic != null && Arrays.equals(magic, MAGIC); } @@ -192,141 +197,159 @@ public class WireFormatInfo implements Command, MarshallAware { } /** - * @throws IOException + * @throws IOException */ public boolean isCacheEnabled() throws IOException { return Boolean.TRUE == getProperty("CacheEnabled"); } + public void setCacheEnabled(boolean cacheEnabled) throws IOException { setProperty("CacheEnabled", cacheEnabled ? Boolean.TRUE : Boolean.FALSE); } /** - * @throws IOException + * @throws IOException */ public boolean isStackTraceEnabled() throws IOException { return Boolean.TRUE == getProperty("StackTraceEnabled"); } + public void setStackTraceEnabled(boolean stackTraceEnabled) throws IOException { setProperty("StackTraceEnabled", stackTraceEnabled ? Boolean.TRUE : Boolean.FALSE); } /** - * @throws IOException + * @throws IOException */ public boolean isTcpNoDelayEnabled() throws IOException { return Boolean.TRUE == getProperty("TcpNoDelayEnabled"); } + public void setTcpNoDelayEnabled(boolean tcpNoDelayEnabled) throws IOException { setProperty("TcpNoDelayEnabled", tcpNoDelayEnabled ? Boolean.TRUE : Boolean.FALSE); } /** - * @throws IOException + * @throws IOException */ public boolean isSizePrefixDisabled() throws IOException { return Boolean.TRUE == getProperty("SizePrefixDisabled"); } + public void setSizePrefixDisabled(boolean prefixPacketSize) throws IOException { setProperty("SizePrefixDisabled", prefixPacketSize ? Boolean.TRUE : Boolean.FALSE); } /** - * @throws IOException + * @throws IOException */ public boolean isTightEncodingEnabled() throws IOException { return Boolean.TRUE == getProperty("TightEncodingEnabled"); } + public void setTightEncodingEnabled(boolean tightEncodingEnabled) throws IOException { setProperty("TightEncodingEnabled", tightEncodingEnabled ? Boolean.TRUE : Boolean.FALSE); } - + /** - * @throws IOException + * @throws IOException */ public long getMaxInactivityDuration() throws IOException { - Long l = (Long) getProperty("MaxInactivityDuration"); + Long l = (Long)getProperty("MaxInactivityDuration"); return l == null ? 0 : l.longValue(); } + public void seMaxInactivityDuration(long maxInactivityDuration) throws IOException { setProperty("MaxInactivityDuration", new Long(maxInactivityDuration)); } /** - * @throws IOException + * @throws IOException */ public int getCacheSize() throws IOException { - Integer i = (Integer) getProperty("CacheSize"); + Integer i = (Integer)getProperty("CacheSize"); return i == null ? 0 : i.intValue(); } + public void setCacheSize(int cacheSize) throws IOException { setProperty("CacheSize", new Integer(cacheSize)); } - - + public Response visit(CommandVisitor visitor) throws Exception { return visitor.processWireFormat(this); } public String toString() { - Map p=null; - try { - p = getProperties(); - } catch (IOException e) { - } - return "WireFormatInfo { version="+version+", properties="+p+", magic="+toString(magic)+"}"; + Map p = null; + try { + p = getProperties(); + } catch (IOException e) { + } + return "WireFormatInfo { version=" + version + ", properties=" + p + ", magic=" + toString(magic) + + "}"; } - - private String toString(byte []data) { + + private String toString(byte[] data) { StringBuffer sb = new StringBuffer(); sb.append('['); for (int i = 0; i < data.length; i++) { - if( i != 0 ) { + if (i != 0) { sb.append(','); } - sb.append((char)data[i]); + sb.append((char)data[i]); } sb.append(']'); return sb.toString(); } - /////////////////////////////////////////////////////////////// + // ///////////////////////////////////////////////////////////// // // This are not implemented. // - /////////////////////////////////////////////////////////////// - + // ///////////////////////////////////////////////////////////// + public void setCommandId(int value) { } + public int getCommandId() { return 0; } + public boolean isResponseRequired() { return false; } + public boolean isResponse() { return false; } + public boolean isBrokerInfo() { return false; } + public boolean isMessageDispatch() { return false; } + public boolean isMessage() { return false; } + public boolean isMessageAck() { return false; } - public boolean isMessageDispatchNotification(){ + + public boolean isMessageDispatchNotification() { return false; } - public boolean isShutdownInfo(){ + + public boolean isShutdownInfo() { return false; } + public void setCachedMarshalledForm(WireFormat wireFormat, ByteSequence data) { } + public ByteSequence getCachedMarshalledForm(WireFormat wireFormat) { return null; } diff --git a/activemq-core/src/main/java/org/apache/activemq/command/XATransactionId.java b/activemq-core/src/main/java/org/apache/activemq/command/XATransactionId.java index 0d79cd0b12..5337bcaae4 100755 --- a/activemq-core/src/main/java/org/apache/activemq/command/XATransactionId.java +++ b/activemq-core/src/main/java/org/apache/activemq/command/XATransactionId.java @@ -20,39 +20,38 @@ import java.util.Arrays; import javax.transaction.xa.Xid; import org.apache.activemq.util.HexSupport; - /** * @openwire:marshaller code="112" * @version $Revision: 1.6 $ */ -public class XATransactionId extends TransactionId implements Xid, Comparable{ - - public static final byte DATA_STRUCTURE_TYPE=CommandTypes.ACTIVEMQ_XA_TRANSACTION_ID; +public class XATransactionId extends TransactionId implements Xid, Comparable { + + public static final byte DATA_STRUCTURE_TYPE = CommandTypes.ACTIVEMQ_XA_TRANSACTION_ID; private int formatId; private byte[] branchQualifier; private byte[] globalTransactionId; - + private transient int hash; private transient String transactionKey; - - public XATransactionId() { + + public XATransactionId() { } - + public XATransactionId(Xid xid) { this.formatId = xid.getFormatId(); this.globalTransactionId = xid.getGlobalTransactionId(); this.branchQualifier = xid.getBranchQualifier(); } - + public byte getDataStructureType() { return DATA_STRUCTURE_TYPE; } - - public synchronized String getTransactionKey(){ - if(transactionKey==null){ - transactionKey="XID:"+formatId+":"+HexSupport.toHexFromBytes(globalTransactionId)+":" - +HexSupport.toHexFromBytes(branchQualifier); + + public synchronized String getTransactionKey() { + if (transactionKey == null) { + transactionKey = "XID:" + formatId + ":" + HexSupport.toHexFromBytes(globalTransactionId) + ":" + + HexSupport.toHexFromBytes(branchQualifier); } return transactionKey; } @@ -60,7 +59,7 @@ public class XATransactionId extends TransactionId implements Xid, Comparable{ public String toString() { return getTransactionKey(); } - + public boolean isXATransaction() { return true; } @@ -92,21 +91,21 @@ public class XATransactionId extends TransactionId implements Xid, Comparable{ public void setBranchQualifier(byte[] branchQualifier) { this.branchQualifier = branchQualifier; - this.hash=0; + this.hash = 0; } public void setFormatId(int formatId) { this.formatId = formatId; - this.hash=0; + this.hash = 0; } public void setGlobalTransactionId(byte[] globalTransactionId) { this.globalTransactionId = globalTransactionId; - this.hash=0; + this.hash = 0; } public int hashCode() { - if( hash==0 ) { + if (hash == 0) { hash = formatId; hash = hash(globalTransactionId, hash); hash = hash(branchQualifier, hash); @@ -123,20 +122,20 @@ public class XATransactionId extends TransactionId implements Xid, Comparable{ } return hash; } - + public boolean equals(Object o) { - if( o==null || o.getClass()!=XATransactionId.class ) + if (o == null || o.getClass() != XATransactionId.class) return false; XATransactionId xid = (XATransactionId)o; - return xid.formatId==formatId && Arrays.equals(xid.globalTransactionId,globalTransactionId) + return xid.formatId == formatId && Arrays.equals(xid.globalTransactionId, globalTransactionId) && Arrays.equals(xid.branchQualifier, branchQualifier); } - public int compareTo(Object o){ - if( o==null || o.getClass()!=XATransactionId.class ) + public int compareTo(Object o) { + if (o == null || o.getClass() != XATransactionId.class) return -1; XATransactionId xid = (XATransactionId)o; return getTransactionKey().compareTo(xid.getTransactionKey()); } - + } diff --git a/activemq-core/src/main/java/org/apache/activemq/filter/ArithmeticExpression.java b/activemq-core/src/main/java/org/apache/activemq/filter/ArithmeticExpression.java index 49889090c9..ae7092c6aa 100755 --- a/activemq-core/src/main/java/org/apache/activemq/filter/ArithmeticExpression.java +++ b/activemq-core/src/main/java/org/apache/activemq/filter/ArithmeticExpression.java @@ -41,12 +41,11 @@ public abstract class ArithmeticExpression extends BinaryExpression { return new ArithmeticExpression(left, right) { protected Object evaluate(Object lvalue, Object rvalue) { if (lvalue instanceof String) { - String text = (String) lvalue; + String text = (String)lvalue; String answer = text + rvalue; return answer; - } - else if (lvalue instanceof Number) { - return plus((Number) lvalue, asNumber(rvalue)); + } else if (lvalue instanceof Number) { + return plus((Number)lvalue, asNumber(rvalue)); } throw new RuntimeException("Cannot call plus operation on: " + lvalue + " and: " + rvalue); } @@ -61,7 +60,7 @@ public abstract class ArithmeticExpression extends BinaryExpression { return new ArithmeticExpression(left, right) { protected Object evaluate(Object lvalue, Object rvalue) { if (lvalue instanceof Number) { - return minus((Number) lvalue, asNumber(rvalue)); + return minus((Number)lvalue, asNumber(rvalue)); } throw new RuntimeException("Cannot call minus operation on: " + lvalue + " and: " + rvalue); } @@ -77,7 +76,7 @@ public abstract class ArithmeticExpression extends BinaryExpression { protected Object evaluate(Object lvalue, Object rvalue) { if (lvalue instanceof Number) { - return multiply((Number) lvalue, asNumber(rvalue)); + return multiply((Number)lvalue, asNumber(rvalue)); } throw new RuntimeException("Cannot call multiply operation on: " + lvalue + " and: " + rvalue); } @@ -93,7 +92,7 @@ public abstract class ArithmeticExpression extends BinaryExpression { protected Object evaluate(Object lvalue, Object rvalue) { if (lvalue instanceof Number) { - return divide((Number) lvalue, asNumber(rvalue)); + return divide((Number)lvalue, asNumber(rvalue)); } throw new RuntimeException("Cannot call divide operation on: " + lvalue + " and: " + rvalue); } @@ -109,7 +108,7 @@ public abstract class ArithmeticExpression extends BinaryExpression { protected Object evaluate(Object lvalue, Object rvalue) { if (lvalue instanceof Number) { - return mod((Number) lvalue, asNumber(rvalue)); + return mod((Number)lvalue, asNumber(rvalue)); } throw new RuntimeException("Cannot call mod operation on: " + lvalue + " and: " + rvalue); } @@ -122,34 +121,34 @@ public abstract class ArithmeticExpression extends BinaryExpression { protected Number plus(Number left, Number right) { switch (numberType(left, right)) { - case INTEGER: - return new Integer(left.intValue() + right.intValue()); - case LONG: - return new Long(left.longValue() + right.longValue()); - default: - return new Double(left.doubleValue() + right.doubleValue()); + case INTEGER: + return new Integer(left.intValue() + right.intValue()); + case LONG: + return new Long(left.longValue() + right.longValue()); + default: + return new Double(left.doubleValue() + right.doubleValue()); } } protected Number minus(Number left, Number right) { switch (numberType(left, right)) { - case INTEGER: - return new Integer(left.intValue() - right.intValue()); - case LONG: - return new Long(left.longValue() - right.longValue()); - default: - return new Double(left.doubleValue() - right.doubleValue()); + case INTEGER: + return new Integer(left.intValue() - right.intValue()); + case LONG: + return new Long(left.longValue() - right.longValue()); + default: + return new Double(left.doubleValue() - right.doubleValue()); } } protected Number multiply(Number left, Number right) { switch (numberType(left, right)) { - case INTEGER: - return new Integer(left.intValue() * right.intValue()); - case LONG: - return new Long(left.longValue() * right.longValue()); - default: - return new Double(left.doubleValue() * right.doubleValue()); + case INTEGER: + return new Integer(left.intValue() * right.intValue()); + case LONG: + return new Long(left.longValue() * right.longValue()); + default: + return new Double(left.doubleValue() * right.doubleValue()); } } @@ -164,11 +163,9 @@ public abstract class ArithmeticExpression extends BinaryExpression { private int numberType(Number left, Number right) { if (isDouble(left) || isDouble(right)) { return DOUBLE; - } - else if (left instanceof Long || right instanceof Long) { + } else if (left instanceof Long || right instanceof Long) { return LONG; - } - else { + } else { return INTEGER; } } @@ -179,9 +176,8 @@ public abstract class ArithmeticExpression extends BinaryExpression { protected Number asNumber(Object value) { if (value instanceof Number) { - return (Number) value; - } - else { + return (Number)value; + } else { throw new RuntimeException("Cannot convert value: " + value + " into a number"); } } @@ -198,7 +194,6 @@ public abstract class ArithmeticExpression extends BinaryExpression { return evaluate(lvalue, rvalue); } - /** * @param lvalue * @param rvalue diff --git a/activemq-core/src/main/java/org/apache/activemq/filter/ComparisonExpression.java b/activemq-core/src/main/java/org/apache/activemq/filter/ComparisonExpression.java index bdbcb0f3e7..2231bb66f4 100755 --- a/activemq-core/src/main/java/org/apache/activemq/filter/ComparisonExpression.java +++ b/activemq-core/src/main/java/org/apache/activemq/filter/ComparisonExpression.java @@ -30,7 +30,8 @@ import javax.jms.JMSException; public abstract class ComparisonExpression extends BinaryExpression implements BooleanExpression { public static BooleanExpression createBetween(Expression value, Expression left, Expression right) { - return LogicExpression.createAND(createGreaterThanEqual(value, left), createLessThanEqual(value, right)); + return LogicExpression.createAND(createGreaterThanEqual(value, left), createLessThanEqual(value, + right)); } public static BooleanExpression createNotBetween(Expression value, Expression left, Expression right) { @@ -86,18 +87,14 @@ public abstract class ComparisonExpression extends BinaryExpression implements B char t = like.charAt(i); regexp.append("\\x"); regexp.append(Integer.toHexString(0xFFFF & t)); - } - else if (c == '%') { - regexp.append(".*?"); // Do a non-greedy match - } - else if (c == '_') { - regexp.append("."); // match one - } - else if (REGEXP_CONTROL_CHARS.contains(new Character(c))) { + } else if (c == '%') { + regexp.append(".*?"); // Do a non-greedy match + } else if (c == '_') { + regexp.append("."); // match one + } else if (REGEXP_CONTROL_CHARS.contains(new Character(c))) { regexp.append("\\x"); regexp.append(Integer.toHexString(0xFFFF & c)); - } - else { + } else { regexp.append(c); } } @@ -125,22 +122,25 @@ public abstract class ComparisonExpression extends BinaryExpression implements B } if (!(rv instanceof String)) { - return Boolean.FALSE; - //throw new RuntimeException("LIKE can only operate on String identifiers. LIKE attemped on: '" + rv.getClass()); + return Boolean.FALSE; + // throw new RuntimeException("LIKE can only operate on String + // identifiers. LIKE attemped on: '" + rv.getClass()); } - return likePattern.matcher((String) rv).matches() ? Boolean.TRUE : Boolean.FALSE; + return likePattern.matcher((String)rv).matches() ? Boolean.TRUE : Boolean.FALSE; } - + public boolean matches(MessageEvaluationContext message) throws JMSException { Object object = evaluate(message); - return object!=null && object==Boolean.TRUE; + return object != null && object == Boolean.TRUE; } } public static BooleanExpression createLike(Expression left, String right, String escape) { if (escape != null && escape.length() != 1) { - throw new RuntimeException("The ESCAPE string litteral is invalid. It can only be one character. Litteral used: " + escape); + throw new RuntimeException( + "The ESCAPE string litteral is invalid. It can only be one character. Litteral used: " + + escape); } int c = -1; if (escape != null) { @@ -152,21 +152,21 @@ public abstract class ComparisonExpression extends BinaryExpression implements B public static BooleanExpression createNotLike(Expression left, String right, String escape) { return UnaryExpression.createNOT(createLike(left, right, escape)); - } + } public static BooleanExpression createInFilter(Expression left, List elements) { - - if( !(left instanceof PropertyExpression) ) - throw new RuntimeException("Expected a property for In expression, got: "+left); - return UnaryExpression.createInExpression((PropertyExpression)left, elements, false); - + + if (!(left instanceof PropertyExpression)) + throw new RuntimeException("Expected a property for In expression, got: " + left); + return UnaryExpression.createInExpression((PropertyExpression)left, elements, false); + } public static BooleanExpression createNotInFilter(Expression left, List elements) { - - if( !(left instanceof PropertyExpression) ) - throw new RuntimeException("Expected a property for In expression, got: "+left); - return UnaryExpression.createInExpression((PropertyExpression)left, elements, true); + + if (!(left instanceof PropertyExpression)) + throw new RuntimeException("Expected a property for In expression, got: " + left); + return UnaryExpression.createInExpression((PropertyExpression)left, elements, true); } @@ -183,27 +183,27 @@ public abstract class ComparisonExpression extends BinaryExpression implements B } public static BooleanExpression createEqual(Expression left, Expression right) { - checkEqualOperand(left); - checkEqualOperand(right); - checkEqualOperandCompatability(left, right); - return doCreateEqual(left, right); + checkEqualOperand(left); + checkEqualOperand(right); + checkEqualOperandCompatability(left, right); + return doCreateEqual(left, right); } - - private static BooleanExpression doCreateEqual(Expression left, Expression right) { + + private static BooleanExpression doCreateEqual(Expression left, Expression right) { return new ComparisonExpression(left, right) { public Object evaluate(MessageEvaluationContext message) throws JMSException { Object lv = left.evaluate(message); Object rv = right.evaluate(message); - + // Iff one of the values is null if (lv == null ^ rv == null) { return Boolean.FALSE; } if (lv == rv || lv.equals(rv)) { return Boolean.TRUE; - } - if( lv instanceof Comparable && rv instanceof Comparable ) { + } + if (lv instanceof Comparable && rv instanceof Comparable) { return compare((Comparable)lv, (Comparable)rv); } return Boolean.FALSE; @@ -220,8 +220,8 @@ public abstract class ComparisonExpression extends BinaryExpression implements B } public static BooleanExpression createGreaterThan(final Expression left, final Expression right) { - checkLessThanOperand(left); - checkLessThanOperand(right); + checkLessThanOperand(left); + checkLessThanOperand(right); return new ComparisonExpression(left, right) { protected boolean asBoolean(int answer) { return answer > 0; @@ -234,8 +234,8 @@ public abstract class ComparisonExpression extends BinaryExpression implements B } public static BooleanExpression createGreaterThanEqual(final Expression left, final Expression right) { - checkLessThanOperand(left); - checkLessThanOperand(right); + checkLessThanOperand(left); + checkLessThanOperand(right); return new ComparisonExpression(left, right) { protected boolean asBoolean(int answer) { return answer >= 0; @@ -248,8 +248,8 @@ public abstract class ComparisonExpression extends BinaryExpression implements B } public static BooleanExpression createLessThan(final Expression left, final Expression right) { - checkLessThanOperand(left); - checkLessThanOperand(right); + checkLessThanOperand(left); + checkLessThanOperand(right); return new ComparisonExpression(left, right) { protected boolean asBoolean(int answer) { @@ -263,9 +263,9 @@ public abstract class ComparisonExpression extends BinaryExpression implements B }; } - public static BooleanExpression createLessThanEqual(final Expression left, final Expression right) { - checkLessThanOperand(left); - checkLessThanOperand(right); + public static BooleanExpression createLessThanEqual(final Expression left, final Expression right) { + checkLessThanOperand(left); + checkLessThanOperand(right); return new ComparisonExpression(left, right) { protected boolean asBoolean(int answer) { @@ -278,53 +278,51 @@ public abstract class ComparisonExpression extends BinaryExpression implements B }; } - /** - * Only Numeric expressions can be used in >, >=, < or <= expressions.s + /** + * Only Numeric expressions can be used in >, >=, < or <= expressions.s * - * @param expr - */ - public static void checkLessThanOperand(Expression expr ) { - if( expr instanceof ConstantExpression ) { - Object value = ((ConstantExpression)expr).getValue(); - if( value instanceof Number ) - return; - - // Else it's boolean or a String.. - throw new RuntimeException("Value '"+expr+"' cannot be compared."); - } - if( expr instanceof BooleanExpression ) { - throw new RuntimeException("Value '"+expr+"' cannot be compared."); - } - } + * @param expr + */ + public static void checkLessThanOperand(Expression expr) { + if (expr instanceof ConstantExpression) { + Object value = ((ConstantExpression)expr).getValue(); + if (value instanceof Number) + return; - /** - * Validates that the expression can be used in == or <> expression. - * Cannot not be NULL TRUE or FALSE litterals. + // Else it's boolean or a String.. + throw new RuntimeException("Value '" + expr + "' cannot be compared."); + } + if (expr instanceof BooleanExpression) { + throw new RuntimeException("Value '" + expr + "' cannot be compared."); + } + } + + /** + * Validates that the expression can be used in == or <> expression. Cannot + * not be NULL TRUE or FALSE litterals. * - * @param expr - */ - public static void checkEqualOperand(Expression expr ) { - if( expr instanceof ConstantExpression ) { - Object value = ((ConstantExpression)expr).getValue(); - if( value == null ) - throw new RuntimeException("'"+expr+"' cannot be compared."); - } - } + * @param expr + */ + public static void checkEqualOperand(Expression expr) { + if (expr instanceof ConstantExpression) { + Object value = ((ConstantExpression)expr).getValue(); + if (value == null) + throw new RuntimeException("'" + expr + "' cannot be compared."); + } + } - /** - * - * @param left - * @param right - */ - private static void checkEqualOperandCompatability(Expression left, Expression right) { - if( left instanceof ConstantExpression && right instanceof ConstantExpression ) { - if( left instanceof BooleanExpression && !(right instanceof BooleanExpression) ) - throw new RuntimeException("'"+left+"' cannot be compared with '"+right+"'"); - } - } + /** + * + * @param left + * @param right + */ + private static void checkEqualOperandCompatability(Expression left, Expression right) { + if (left instanceof ConstantExpression && right instanceof ConstantExpression) { + if (left instanceof BooleanExpression && !(right instanceof BooleanExpression)) + throw new RuntimeException("'" + left + "' cannot be compared with '" + right + "'"); + } + } - - /** * @param left * @param right @@ -334,11 +332,11 @@ public abstract class ComparisonExpression extends BinaryExpression implements B } public Object evaluate(MessageEvaluationContext message) throws JMSException { - Comparable lv = (Comparable) left.evaluate(message); + Comparable lv = (Comparable)left.evaluate(message); if (lv == null) { return null; } - Comparable rv = (Comparable) right.evaluate(message); + Comparable rv = (Comparable)right.evaluate(message); if (rv == null) { return null; } @@ -353,106 +351,81 @@ public abstract class ComparisonExpression extends BinaryExpression implements B if (lc != rc) { if (lc == Byte.class) { if (rc == Short.class) { - lv = Short.valueOf(((Number) lv).shortValue()); - } - else if (rc == Integer.class) { - lv = Integer.valueOf(((Number) lv).intValue()); - } - else if (rc == Long.class) { - lv = Long.valueOf(((Number) lv).longValue()); - } - else if (rc == Float.class) { - lv = new Float(((Number) lv).floatValue()); - } - else if (rc == Double.class) { - lv = new Double(((Number) lv).doubleValue()); - } - else { + lv = Short.valueOf(((Number)lv).shortValue()); + } else if (rc == Integer.class) { + lv = Integer.valueOf(((Number)lv).intValue()); + } else if (rc == Long.class) { + lv = Long.valueOf(((Number)lv).longValue()); + } else if (rc == Float.class) { + lv = new Float(((Number)lv).floatValue()); + } else if (rc == Double.class) { + lv = new Double(((Number)lv).doubleValue()); + } else { return Boolean.FALSE; } - } else if (lc == Short.class) { + } else if (lc == Short.class) { if (rc == Integer.class) { - lv = Integer.valueOf(((Number) lv).intValue()); - } - else if (rc == Long.class) { - lv = Long.valueOf(((Number) lv).longValue()); - } - else if (rc == Float.class) { - lv = new Float(((Number) lv).floatValue()); - } - else if (rc == Double.class) { - lv = new Double(((Number) lv).doubleValue()); - } - else { + lv = Integer.valueOf(((Number)lv).intValue()); + } else if (rc == Long.class) { + lv = Long.valueOf(((Number)lv).longValue()); + } else if (rc == Float.class) { + lv = new Float(((Number)lv).floatValue()); + } else if (rc == Double.class) { + lv = new Double(((Number)lv).doubleValue()); + } else { return Boolean.FALSE; } } else if (lc == Integer.class) { if (rc == Long.class) { - lv = Long.valueOf(((Number) lv).longValue()); - } - else if (rc == Float.class) { - lv = new Float(((Number) lv).floatValue()); - } - else if (rc == Double.class) { - lv = new Double(((Number) lv).doubleValue()); - } - else { + lv = Long.valueOf(((Number)lv).longValue()); + } else if (rc == Float.class) { + lv = new Float(((Number)lv).floatValue()); + } else if (rc == Double.class) { + lv = new Double(((Number)lv).doubleValue()); + } else { return Boolean.FALSE; } - } - else if (lc == Long.class) { + } else if (lc == Long.class) { if (rc == Integer.class) { - rv = Long.valueOf(((Number) rv).longValue()); - } - else if (rc == Float.class) { - lv = new Float(((Number) lv).floatValue()); - } - else if (rc == Double.class) { - lv = new Double(((Number) lv).doubleValue()); - } - else { + rv = Long.valueOf(((Number)rv).longValue()); + } else if (rc == Float.class) { + lv = new Float(((Number)lv).floatValue()); + } else if (rc == Double.class) { + lv = new Double(((Number)lv).doubleValue()); + } else { return Boolean.FALSE; } - } - else if (lc == Float.class) { + } else if (lc == Float.class) { if (rc == Integer.class) { - rv = new Float(((Number) rv).floatValue()); - } - else if (rc == Long.class) { - rv = new Float(((Number) rv).floatValue()); - } - else if (rc == Double.class) { - lv = new Double(((Number) lv).doubleValue()); - } - else { + rv = new Float(((Number)rv).floatValue()); + } else if (rc == Long.class) { + rv = new Float(((Number)rv).floatValue()); + } else if (rc == Double.class) { + lv = new Double(((Number)lv).doubleValue()); + } else { return Boolean.FALSE; } - } - else if (lc == Double.class) { + } else if (lc == Double.class) { if (rc == Integer.class) { - rv = new Double(((Number) rv).doubleValue()); - } - else if (rc == Long.class) { - rv = new Double(((Number) rv).doubleValue()); - } - else if (rc == Float.class) { - rv = new Float(((Number) rv).doubleValue()); - } - else { + rv = new Double(((Number)rv).doubleValue()); + } else if (rc == Long.class) { + rv = new Double(((Number)rv).doubleValue()); + } else if (rc == Float.class) { + rv = new Float(((Number)rv).doubleValue()); + } else { return Boolean.FALSE; } - } - else + } else return Boolean.FALSE; } return asBoolean(lv.compareTo(rv)) ? Boolean.TRUE : Boolean.FALSE; } protected abstract boolean asBoolean(int answer); - + public boolean matches(MessageEvaluationContext message) throws JMSException { Object object = evaluate(message); - return object!=null && object==Boolean.TRUE; + return object != null && object == Boolean.TRUE; } } diff --git a/activemq-core/src/main/java/org/apache/activemq/filter/ConstantExpression.java b/activemq-core/src/main/java/org/apache/activemq/filter/ConstantExpression.java index 4d2b3fb7e4..11b884fbb0 100755 --- a/activemq-core/src/main/java/org/apache/activemq/filter/ConstantExpression.java +++ b/activemq-core/src/main/java/org/apache/activemq/filter/ConstantExpression.java @@ -31,10 +31,11 @@ public class ConstantExpression implements Expression { public BooleanConstantExpression(Object value) { super(value); } + public boolean matches(MessageEvaluationContext message) throws JMSException { Object object = evaluate(message); - return object!=null && object==Boolean.TRUE; - } + return object != null && object == Boolean.TRUE; + } } public static final BooleanConstantExpression NULL = new BooleanConstantExpression(null); @@ -44,19 +45,19 @@ public class ConstantExpression implements Expression { private Object value; public static ConstantExpression createFromDecimal(String text) { - - // Strip off the 'l' or 'L' if needed. - if( text.endsWith("l") || text.endsWith("L") ) - text = text.substring(0, text.length()-1); - Number value; - try { - value = new Long(text); - } catch ( NumberFormatException e) { - // The number may be too big to fit in a long. - value = new BigDecimal(text); - } - + // Strip off the 'l' or 'L' if needed. + if (text.endsWith("l") || text.endsWith("L")) + text = text.substring(0, text.length() - 1); + + Number value; + try { + value = new Long(text); + } catch (NumberFormatException e) { + // The number may be too big to fit in a long. + value = new BigDecimal(text); + } + long l = value.longValue(); if (Integer.MIN_VALUE <= l && l <= Integer.MAX_VALUE) { value = Integer.valueOf(value.intValue()); @@ -97,7 +98,7 @@ public class ConstantExpression implements Expression { public Object getValue() { return value; - } + } /** * @see java.lang.Object#toString() @@ -107,17 +108,17 @@ public class ConstantExpression implements Expression { return "NULL"; } if (value instanceof Boolean) { - return ((Boolean) value).booleanValue() ? "TRUE" : "FALSE"; + return ((Boolean)value).booleanValue() ? "TRUE" : "FALSE"; } if (value instanceof String) { - return encodeString((String) value); + return encodeString((String)value); } return value.toString(); } /** * TODO: more efficient hashCode() - * + * * @see java.lang.Object#hashCode() */ public int hashCode() { @@ -126,7 +127,7 @@ public class ConstantExpression implements Expression { /** * TODO: more efficient hashCode() - * + * * @see java.lang.Object#equals(java.lang.Object) */ public boolean equals(Object o) { @@ -138,11 +139,10 @@ public class ConstantExpression implements Expression { } - /** - * Encodes the value of string so that it looks like it would look like - * when it was provided in a selector. - * + * Encodes the value of string so that it looks like it would look like when + * it was provided in a selector. + * * @param string * @return */ @@ -159,5 +159,5 @@ public class ConstantExpression implements Expression { b.append('\''); return b.toString(); } - + } diff --git a/activemq-core/src/main/java/org/apache/activemq/filter/DestinationFilter.java b/activemq-core/src/main/java/org/apache/activemq/filter/DestinationFilter.java index 266d7a1f36..9fdbc19de6 100755 --- a/activemq-core/src/main/java/org/apache/activemq/filter/DestinationFilter.java +++ b/activemq-core/src/main/java/org/apache/activemq/filter/DestinationFilter.java @@ -24,24 +24,23 @@ import javax.jms.JMSException; import org.apache.activemq.command.ActiveMQDestination; import org.apache.activemq.util.JMSExceptionSupport; - /** * Represents a filter which only operates on Destinations - * + * * @version $Revision: 1.3 $ */ public abstract class DestinationFilter implements BooleanExpression { - + public static final String ANY_DESCENDENT = ">"; public static final String ANY_CHILD = "*"; public Object evaluate(MessageEvaluationContext message) throws JMSException { return matches(message) ? Boolean.TRUE : Boolean.FALSE; } - + public boolean matches(MessageEvaluationContext message) throws JMSException { try { - if( message.isDropped() ) + if (message.isDropped()) return false; return matches(message.getMessage().getDestination()); } catch (IOException e) { @@ -61,8 +60,7 @@ public abstract class DestinationFilter implements BooleanExpression { String lastPath = paths[idx]; if (lastPath.equals(ANY_DESCENDENT)) { return new PrefixDestinationFilter(paths); - } - else { + } else { while (idx >= 0) { lastPath = paths[idx--]; if (lastPath.equals(ANY_CHILD)) { diff --git a/activemq-core/src/main/java/org/apache/activemq/filter/DestinationMapNode.java b/activemq-core/src/main/java/org/apache/activemq/filter/DestinationMapNode.java index 417e5789f9..9030ae9429 100755 --- a/activemq-core/src/main/java/org/apache/activemq/filter/DestinationMapNode.java +++ b/activemq-core/src/main/java/org/apache/activemq/filter/DestinationMapNode.java @@ -39,15 +39,14 @@ public class DestinationMapNode implements DestinationNode { private List values = new ArrayList(); private Map childNodes = new HashMap(); private String path = "Root"; -// private DestinationMapNode anyChild; + // private DestinationMapNode anyChild; private int pathLength; public DestinationMapNode(DestinationMapNode parent) { this.parent = parent; if (parent == null) { pathLength = 0; - } - else { + } else { pathLength = parent.pathLength + 1; } } @@ -57,7 +56,7 @@ public class DestinationMapNode implements DestinationNode { * exist */ public DestinationMapNode getChild(String path) { - return (DestinationMapNode) childNodes.get(path); + return (DestinationMapNode)childNodes.get(path); } /** @@ -66,7 +65,7 @@ public class DestinationMapNode implements DestinationNode { public Collection getChildren() { return childNodes.values(); } - + public int getChildCount() { return childNodes.size(); } @@ -76,7 +75,7 @@ public class DestinationMapNode implements DestinationNode { * it does not yet exist */ public DestinationMapNode getChildOrCreate(String path) { - DestinationMapNode answer = (DestinationMapNode) childNodes.get(path); + DestinationMapNode answer = (DestinationMapNode)childNodes.get(path); if (answer == null) { answer = createChildNode(); answer.path = path; @@ -88,13 +87,12 @@ public class DestinationMapNode implements DestinationNode { /** * Returns the node which represents all children (i.e. the * node) */ -// public DestinationMapNode getAnyChildNode() { -// if (anyChild == null) { -// anyChild = createChildNode(); -// } -// return anyChild; -// } - + // public DestinationMapNode getAnyChildNode() { + // if (anyChild == null) { + // anyChild = createChildNode(); + // } + // return anyChild; + // } /** * Returns a mutable List of the values available at this node in the tree */ @@ -106,24 +104,23 @@ public class DestinationMapNode implements DestinationNode { * Returns a mutable List of the values available at this node in the tree */ public List removeValues() { - ArrayList v = new ArrayList(values); -// parent.getAnyChildNode().getValues().removeAll(v); - values.clear(); - pruneIfEmpty(); + ArrayList v = new ArrayList(values); + // parent.getAnyChildNode().getValues().removeAll(v); + values.clear(); + pruneIfEmpty(); return v; } - - + public Set removeDesendentValues() { Set answer = new HashSet(); removeDesendentValues(answer); return answer; } - + protected void removeDesendentValues(Set answer) { -// if (anyChild != null) { -// anyChild.removeDesendentValues(answer); -// } + // if (anyChild != null) { + // anyChild.removeDesendentValues(answer); + // } answer.addAll(removeValues()); } @@ -139,14 +136,13 @@ public class DestinationMapNode implements DestinationNode { public void add(String[] paths, int idx, Object value) { if (idx >= paths.length) { values.add(value); - } - else { -// if (idx == paths.length - 1) { -// getAnyChildNode().getValues().add(value); -// } -// else { -// getAnyChildNode().add(paths, idx + 1, value); -// } + } else { + // if (idx == paths.length - 1) { + // getAnyChildNode().getValues().add(value); + // } + // else { + // getAnyChildNode().add(paths, idx + 1, value); + // } getChildOrCreate(paths[idx]).add(paths, idx + 1, value); } } @@ -155,14 +151,13 @@ public class DestinationMapNode implements DestinationNode { if (idx >= paths.length) { values.remove(value); pruneIfEmpty(); - } - else { -// if (idx == paths.length - 1) { -// getAnyChildNode().getValues().remove(value); -// } -// else { -// getAnyChildNode().remove(paths, idx + 1, value); -// } + } else { + // if (idx == paths.length - 1) { + // getAnyChildNode().getValues().remove(value); + // } + // else { + // getAnyChildNode().remove(paths, idx + 1, value); + // } getChildOrCreate(paths[idx]).remove(paths, ++idx, value); } } @@ -171,7 +166,7 @@ public class DestinationMapNode implements DestinationNode { DestinationNode node = this; for (int i = startIndex, size = paths.length; i < size && node != null; i++) { - String path = paths[i]; + String path = paths[i]; if (path.equals(ANY_DESCENDENT)) { answer.addAll(node.removeDesendentValues()); break; @@ -179,19 +174,17 @@ public class DestinationMapNode implements DestinationNode { node.appendMatchingWildcards(answer, paths, i); if (path.equals(ANY_CHILD)) { - //node = node.getAnyChildNode(); + // node = node.getAnyChildNode(); node = new AnyChildDestinationNode(node); - } - else { + } else { node = node.getChild(path); } } - + if (node != null) { answer.addAll(node.removeValues()); } - } public void appendDescendantValues(Set answer) { @@ -200,14 +193,14 @@ public class DestinationMapNode implements DestinationNode { // lets add all the children too Iterator iter = childNodes.values().iterator(); while (iter.hasNext()) { - DestinationNode child = (DestinationNode) iter.next(); + DestinationNode child = (DestinationNode)iter.next(); child.appendDescendantValues(answer); } - + // TODO??? -// if (anyChild != null) { -// anyChild.appendDescendantValues(answer); -// } + // if (anyChild != null) { + // anyChild.appendDescendantValues(answer); + // } } /** @@ -226,7 +219,7 @@ public class DestinationMapNode implements DestinationNode { } DestinationMapNode wildCardNode = getChild(ANY_CHILD); if (wildCardNode != null) { - wildCardNode.appendMatchingValues(answer, paths, idx+1); + wildCardNode.appendMatchingValues(answer, paths, idx + 1); } wildCardNode = getChild(ANY_DESCENDENT); if (wildCardNode != null) { @@ -247,11 +240,9 @@ public class DestinationMapNode implements DestinationNode { node.appendMatchingWildcards(answer, paths, i); - if (path.equals(ANY_CHILD)) { node = new AnyChildDestinationNode(node); - } - else { + } else { node = node.getChild(path); } } diff --git a/activemq-core/src/main/java/org/apache/activemq/filter/PropertyExpression.java b/activemq-core/src/main/java/org/apache/activemq/filter/PropertyExpression.java index 42178f6afb..8b6c8c468b 100755 --- a/activemq-core/src/main/java/org/apache/activemq/filter/PropertyExpression.java +++ b/activemq-core/src/main/java/org/apache/activemq/filter/PropertyExpression.java @@ -29,7 +29,7 @@ import org.apache.activemq.command.TransactionId; import org.apache.activemq.util.JMSExceptionSupport; /** - * Represents a property expression + * Represents a property expression * * @version $Revision: 1.5 $ */ @@ -38,149 +38,151 @@ public class PropertyExpression implements Expression { interface SubExpression { public Object evaluate(Message message); } - - static final private HashMap JMS_PROPERTY_EXPRESSIONS = new HashMap(); - static{ - JMS_PROPERTY_EXPRESSIONS.put("JMSDestination",new SubExpression(){ - public Object evaluate(Message message){ - ActiveMQDestination dest=message.getOriginalDestination(); - if(dest==null) - dest=message.getDestination(); - if(dest==null) + static final private HashMap JMS_PROPERTY_EXPRESSIONS = new HashMap(); + static { + JMS_PROPERTY_EXPRESSIONS.put("JMSDestination", new SubExpression() { + + public Object evaluate(Message message) { + ActiveMQDestination dest = message.getOriginalDestination(); + if (dest == null) + dest = message.getDestination(); + if (dest == null) return null; return dest.toString(); } }); - JMS_PROPERTY_EXPRESSIONS.put("JMSReplyTo",new SubExpression(){ + JMS_PROPERTY_EXPRESSIONS.put("JMSReplyTo", new SubExpression() { - public Object evaluate(Message message){ - if(message.getReplyTo()==null) + public Object evaluate(Message message) { + if (message.getReplyTo() == null) return null; return message.getReplyTo().toString(); } }); - JMS_PROPERTY_EXPRESSIONS.put("JMSType",new SubExpression(){ + JMS_PROPERTY_EXPRESSIONS.put("JMSType", new SubExpression() { - public Object evaluate(Message message){ + public Object evaluate(Message message) { return message.getType(); } }); - JMS_PROPERTY_EXPRESSIONS.put("JMSDeliveryMode",new SubExpression(){ + JMS_PROPERTY_EXPRESSIONS.put("JMSDeliveryMode", new SubExpression() { - public Object evaluate(Message message){ - return Integer.valueOf(message.isPersistent()?DeliveryMode.PERSISTENT:DeliveryMode.NON_PERSISTENT); + public Object evaluate(Message message) { + return Integer.valueOf(message.isPersistent() + ? DeliveryMode.PERSISTENT : DeliveryMode.NON_PERSISTENT); } }); - JMS_PROPERTY_EXPRESSIONS.put("JMSPriority",new SubExpression(){ + JMS_PROPERTY_EXPRESSIONS.put("JMSPriority", new SubExpression() { - public Object evaluate(Message message){ + public Object evaluate(Message message) { return Integer.valueOf(message.getPriority()); } }); - JMS_PROPERTY_EXPRESSIONS.put("JMSMessageID",new SubExpression(){ + JMS_PROPERTY_EXPRESSIONS.put("JMSMessageID", new SubExpression() { - public Object evaluate(Message message){ - if(message.getMessageId()==null) + public Object evaluate(Message message) { + if (message.getMessageId() == null) return null; return message.getMessageId().toString(); } }); - JMS_PROPERTY_EXPRESSIONS.put("JMSTimestamp",new SubExpression(){ + JMS_PROPERTY_EXPRESSIONS.put("JMSTimestamp", new SubExpression() { - public Object evaluate(Message message){ + public Object evaluate(Message message) { return Long.valueOf(message.getTimestamp()); } }); - JMS_PROPERTY_EXPRESSIONS.put("JMSCorrelationID",new SubExpression(){ + JMS_PROPERTY_EXPRESSIONS.put("JMSCorrelationID", new SubExpression() { - public Object evaluate(Message message){ + public Object evaluate(Message message) { return message.getCorrelationId(); } }); - JMS_PROPERTY_EXPRESSIONS.put("JMSExpiration",new SubExpression(){ + JMS_PROPERTY_EXPRESSIONS.put("JMSExpiration", new SubExpression() { - public Object evaluate(Message message){ + public Object evaluate(Message message) { return Long.valueOf(message.getExpiration()); } }); - JMS_PROPERTY_EXPRESSIONS.put("JMSRedelivered",new SubExpression(){ + JMS_PROPERTY_EXPRESSIONS.put("JMSRedelivered", new SubExpression() { - public Object evaluate(Message message){ + public Object evaluate(Message message) { return Boolean.valueOf(message.isRedelivered()); } }); - JMS_PROPERTY_EXPRESSIONS.put("JMSXDeliveryCount",new SubExpression(){ + JMS_PROPERTY_EXPRESSIONS.put("JMSXDeliveryCount", new SubExpression() { - public Object evaluate(Message message){ - return Integer.valueOf(message.getRedeliveryCounter()+1); + public Object evaluate(Message message) { + return Integer.valueOf(message.getRedeliveryCounter() + 1); } }); - JMS_PROPERTY_EXPRESSIONS.put("JMSXGroupID",new SubExpression(){ + JMS_PROPERTY_EXPRESSIONS.put("JMSXGroupID", new SubExpression() { - public Object evaluate(Message message){ + public Object evaluate(Message message) { return message.getGroupID(); } }); - JMS_PROPERTY_EXPRESSIONS.put("JMSXGroupSeq",new SubExpression(){ + JMS_PROPERTY_EXPRESSIONS.put("JMSXGroupSeq", new SubExpression() { - public Object evaluate(Message message){ + public Object evaluate(Message message) { return new Integer(message.getGroupSequence()); } }); - JMS_PROPERTY_EXPRESSIONS.put("JMSXProducerTXID",new SubExpression(){ + JMS_PROPERTY_EXPRESSIONS.put("JMSXProducerTXID", new SubExpression() { - public Object evaluate(Message message){ - TransactionId txId=message.getOriginalTransactionId(); - if(txId==null) - txId=message.getTransactionId(); - if(txId==null) + public Object evaluate(Message message) { + TransactionId txId = message.getOriginalTransactionId(); + if (txId == null) + txId = message.getTransactionId(); + if (txId == null) return null; return new Integer(txId.toString()); } }); - JMS_PROPERTY_EXPRESSIONS.put("JMSActiveMQBrokerInTime",new SubExpression(){ + JMS_PROPERTY_EXPRESSIONS.put("JMSActiveMQBrokerInTime", new SubExpression() { - public Object evaluate(Message message){ + public Object evaluate(Message message) { return Long.valueOf(message.getBrokerInTime()); } }); - JMS_PROPERTY_EXPRESSIONS.put("JMSActiveMQBrokerOutTime",new SubExpression(){ + JMS_PROPERTY_EXPRESSIONS.put("JMSActiveMQBrokerOutTime", new SubExpression() { - public Object evaluate(Message message){ + public Object evaluate(Message message) { return Long.valueOf(message.getBrokerOutTime()); } }); } - + private final String name; private final SubExpression jmsPropertyExpression; - + public PropertyExpression(String name) { this.name = name; - jmsPropertyExpression = (SubExpression) JMS_PROPERTY_EXPRESSIONS.get(name); + jmsPropertyExpression = (SubExpression)JMS_PROPERTY_EXPRESSIONS.get(name); } public Object evaluate(MessageEvaluationContext message) throws JMSException { try { - if( message.isDropped() ) + if (message.isDropped()) return null; - - if( jmsPropertyExpression!=null ) + + if (jmsPropertyExpression != null) return jmsPropertyExpression.evaluate(message.getMessage()); try { return message.getMessage().getProperty(name); } catch (IOException ioe) { - throw JMSExceptionSupport.create("Could not get property: "+name+" reason: "+ioe.getMessage(), ioe); + throw JMSExceptionSupport.create("Could not get property: " + name + " reason: " + + ioe.getMessage(), ioe); } } catch (IOException e) { throw JMSExceptionSupport.create(e); } } - + public Object evaluate(Message message) throws JMSException { - if( jmsPropertyExpression!=null ) + if (jmsPropertyExpression != null) return jmsPropertyExpression.evaluate(message); try { return message.getProperty(name); @@ -193,7 +195,6 @@ public class PropertyExpression implements Expression { return name; } - /** * @see java.lang.Object#toString() */ @@ -216,7 +217,7 @@ public class PropertyExpression implements Expression { if (o == null || !this.getClass().equals(o.getClass())) { return false; } - return name.equals(((PropertyExpression) o).name); + return name.equals(((PropertyExpression)o).name); } diff --git a/activemq-core/src/main/java/org/apache/activemq/filter/UnaryExpression.java b/activemq-core/src/main/java/org/apache/activemq/filter/UnaryExpression.java index a089c01386..2f6e9b672f 100755 --- a/activemq-core/src/main/java/org/apache/activemq/filter/UnaryExpression.java +++ b/activemq-core/src/main/java/org/apache/activemq/filter/UnaryExpression.java @@ -42,7 +42,7 @@ public abstract class UnaryExpression implements Expression { return null; } if (rvalue instanceof Number) { - return negate((Number) rvalue); + return negate((Number)rvalue); } return null; } @@ -53,83 +53,83 @@ public abstract class UnaryExpression implements Expression { }; } - public static BooleanExpression createInExpression(PropertyExpression right, List elements, final boolean not) { - - // Use a HashSet if there are many elements. - Collection t; - if( elements.size()==0 ) - t=null; - else if( elements.size() < 5 ) - t = elements; - else { - t = new HashSet(elements); - } - final Collection inList = t; - + public static BooleanExpression createInExpression(PropertyExpression right, List elements, + final boolean not) { + + // Use a HashSet if there are many elements. + Collection t; + if (elements.size() == 0) + t = null; + else if (elements.size() < 5) + t = elements; + else { + t = new HashSet(elements); + } + final Collection inList = t; + return new BooleanUnaryExpression(right) { public Object evaluate(MessageEvaluationContext message) throws JMSException { - + Object rvalue = right.evaluate(message); if (rvalue == null) { return null; } - if( rvalue.getClass()!=String.class ) - return null; - - if( (inList!=null && inList.contains(rvalue)) ^ not ) { - return Boolean.TRUE; + if (rvalue.getClass() != String.class) + return null; + + if ((inList != null && inList.contains(rvalue)) ^ not) { + return Boolean.TRUE; } else { - return Boolean.FALSE; + return Boolean.FALSE; } - + } public String toString() { - StringBuffer answer = new StringBuffer(); - answer.append(right); - answer.append(" "); - answer.append(getExpressionSymbol()); - answer.append(" ( "); + StringBuffer answer = new StringBuffer(); + answer.append(right); + answer.append(" "); + answer.append(getExpressionSymbol()); + answer.append(" ( "); - int count=0; - for (Iterator i = inList.iterator(); i.hasNext();) { - Object o = (Object) i.next(); - if( count!=0 ) { - answer.append(", "); - } - answer.append(o); - count++; - } - - answer.append(" )"); + int count = 0; + for (Iterator i = inList.iterator(); i.hasNext();) { + Object o = (Object)i.next(); + if (count != 0) { + answer.append(", "); + } + answer.append(o); + count++; + } + + answer.append(" )"); return answer.toString(); - } - + } + public String getExpressionSymbol() { - if( not ) - return "NOT IN"; - else - return "IN"; + if (not) + return "NOT IN"; + else + return "IN"; } }; } abstract static class BooleanUnaryExpression extends UnaryExpression implements BooleanExpression { - public BooleanUnaryExpression(Expression left) { + public BooleanUnaryExpression(Expression left) { super(left); } public boolean matches(MessageEvaluationContext message) throws JMSException { Object object = evaluate(message); - return object!=null && object==Boolean.TRUE; + return object != null && object == Boolean.TRUE; } }; - public static BooleanExpression createNOT(BooleanExpression left) { return new BooleanUnaryExpression(left) { public Object evaluate(MessageEvaluationContext message) throws JMSException { - Boolean lvalue = (Boolean) right.evaluate(message); + Boolean lvalue = (Boolean)right.evaluate(message); if (lvalue == null) { return null; } @@ -141,7 +141,7 @@ public abstract class UnaryExpression implements Expression { } }; } - + public static BooleanExpression createXPath(final String xpath) { return new XPathExpression(xpath); } @@ -154,9 +154,9 @@ public abstract class UnaryExpression implements Expression { return new BooleanUnaryExpression(left) { public Object evaluate(MessageEvaluationContext message) throws JMSException { Object rvalue = right.evaluate(message); - if (rvalue == null) + if (rvalue == null) return null; - if (!rvalue.getClass().equals(Boolean.class)) + if (!rvalue.getClass().equals(Boolean.class)) return Boolean.FALSE; return ((Boolean)rvalue).booleanValue() ? Boolean.TRUE : Boolean.FALSE; } @@ -172,34 +172,32 @@ public abstract class UnaryExpression implements Expression { } private static Number negate(Number left) { - Class clazz = left.getClass(); + Class clazz = left.getClass(); if (clazz == Integer.class) { return new Integer(-left.intValue()); - } - else if (clazz == Long.class) { + } else if (clazz == Long.class) { return new Long(-left.longValue()); - } - else if (clazz == Float.class) { + } else if (clazz == Float.class) { return new Float(-left.floatValue()); - } - else if (clazz == Double.class) { + } else if (clazz == Double.class) { return new Double(-left.doubleValue()); - } - else if (clazz == BigDecimal.class) { - // We ussually get a big deciamal when we have Long.MIN_VALUE constant in the - // Selector. Long.MIN_VALUE is too big to store in a Long as a positive so we store it - // as a Big decimal. But it gets Negated right away.. to here we try to covert it back - // to a Long. - BigDecimal bd = (BigDecimal)left; - bd = bd.negate(); - - if( BD_LONG_MIN_VALUE.compareTo(bd)==0 ) { - return Long.valueOf(Long.MIN_VALUE); - } + } else if (clazz == BigDecimal.class) { + // We ussually get a big deciamal when we have Long.MIN_VALUE + // constant in the + // Selector. Long.MIN_VALUE is too big to store in a Long as a + // positive so we store it + // as a Big decimal. But it gets Negated right away.. to here we try + // to covert it back + // to a Long. + BigDecimal bd = (BigDecimal)left; + bd = bd.negate(); + + if (BD_LONG_MIN_VALUE.compareTo(bd) == 0) { + return Long.valueOf(Long.MIN_VALUE); + } return bd; - } - else { - throw new RuntimeException("Don't know how to negate: "+left); + } else { + throw new RuntimeException("Don't know how to negate: " + left); } } @@ -224,7 +222,7 @@ public abstract class UnaryExpression implements Expression { /** * TODO: more efficient hashCode() - * + * * @see java.lang.Object#hashCode() */ public int hashCode() { @@ -233,7 +231,7 @@ public abstract class UnaryExpression implements Expression { /** * TODO: more efficient hashCode() - * + * * @see java.lang.Object#equals(java.lang.Object) */ public boolean equals(Object o) { @@ -246,9 +244,9 @@ public abstract class UnaryExpression implements Expression { } /** - * Returns the symbol that represents this binary expression. For example, addition is - * represented by "+" - * + * Returns the symbol that represents this binary expression. For example, + * addition is represented by "+" + * * @return */ abstract public String getExpressionSymbol(); diff --git a/activemq-core/src/main/java/org/apache/activemq/filter/XPathExpression.java b/activemq-core/src/main/java/org/apache/activemq/filter/XPathExpression.java index 62754c7146..2950ba6263 100755 --- a/activemq-core/src/main/java/org/apache/activemq/filter/XPathExpression.java +++ b/activemq-core/src/main/java/org/apache/activemq/filter/XPathExpression.java @@ -34,23 +34,24 @@ public final class XPathExpression implements BooleanExpression { private static final Log log = LogFactory.getLog(XPathExpression.class); private static final String EVALUATOR_SYSTEM_PROPERTY = "org.apache.activemq.XPathEvaluatorClassName"; - private static final String DEFAULT_EVALUATOR_CLASS_NAME=XalanXPathEvaluator.class.getName(); - + private static final String DEFAULT_EVALUATOR_CLASS_NAME = XalanXPathEvaluator.class.getName(); + private static final Constructor EVALUATOR_CONSTRUCTOR; - + static { - String cn = System.getProperty(EVALUATOR_SYSTEM_PROPERTY, DEFAULT_EVALUATOR_CLASS_NAME); + String cn = System.getProperty(EVALUATOR_SYSTEM_PROPERTY, DEFAULT_EVALUATOR_CLASS_NAME); Constructor m = null; try { try { m = getXPathEvaluatorConstructor(cn); } catch (Throwable e) { - log.warn("Invalid "+XPathEvaluator.class.getName()+" implementation: "+cn+", reason: "+e,e); + log.warn("Invalid " + XPathEvaluator.class.getName() + " implementation: " + cn + + ", reason: " + e, e); cn = DEFAULT_EVALUATOR_CLASS_NAME; try { m = getXPathEvaluatorConstructor(cn); } catch (Throwable e2) { - log.error("Default XPath evaluator could not be loaded",e); + log.error("Default XPath evaluator could not be loaded", e); } } } finally { @@ -58,21 +59,22 @@ public final class XPathExpression implements BooleanExpression { } } - private static Constructor getXPathEvaluatorConstructor(String cn) throws ClassNotFoundException, SecurityException, NoSuchMethodException { + private static Constructor getXPathEvaluatorConstructor(String cn) throws ClassNotFoundException, + SecurityException, NoSuchMethodException { Class c = XPathExpression.class.getClassLoader().loadClass(cn); - if( !XPathEvaluator.class.isAssignableFrom(c) ) { - throw new ClassCastException(""+c+" is not an instance of "+XPathEvaluator.class); + if (!XPathEvaluator.class.isAssignableFrom(c)) { + throw new ClassCastException("" + c + " is not an instance of " + XPathEvaluator.class); } - return c.getConstructor(new Class[]{String.class}); + return c.getConstructor(new Class[] {String.class}); } - + private final String xpath; private final XPathEvaluator evaluator; - + static public interface XPathEvaluator { public boolean evaluate(Message message) throws JMSException; - } - + } + XPathExpression(String xpath) { this.xpath = xpath; this.evaluator = createEvaluator(xpath); @@ -80,21 +82,21 @@ public final class XPathExpression implements BooleanExpression { private XPathEvaluator createEvaluator(String xpath2) { try { - return (XPathEvaluator)EVALUATOR_CONSTRUCTOR.newInstance(new Object[]{xpath}); + return (XPathEvaluator)EVALUATOR_CONSTRUCTOR.newInstance(new Object[] {xpath}); } catch (InvocationTargetException e) { Throwable cause = e.getCause(); - if( cause instanceof RuntimeException ) { + if (cause instanceof RuntimeException) { throw (RuntimeException)cause; } - throw new RuntimeException("Invalid XPath Expression: "+xpath+" reason: "+e.getMessage(), e); + throw new RuntimeException("Invalid XPath Expression: " + xpath + " reason: " + e.getMessage(), e); } catch (Throwable e) { - throw new RuntimeException("Invalid XPath Expression: "+xpath+" reason: "+e.getMessage(), e); + throw new RuntimeException("Invalid XPath Expression: " + xpath + " reason: " + e.getMessage(), e); } } public Object evaluate(MessageEvaluationContext message) throws JMSException { try { - if( message.isDropped() ) + if (message.isDropped()) return null; return evaluator.evaluate(message.getMessage()) ? Boolean.TRUE : Boolean.FALSE; } catch (IOException e) { @@ -104,9 +106,9 @@ public final class XPathExpression implements BooleanExpression { } public String toString() { - return "XPATH "+ConstantExpression.encodeString(xpath); + return "XPATH " + ConstantExpression.encodeString(xpath); } - + /** * @param message * @return true if the expression evaluates to Boolean.TRUE. @@ -114,7 +116,7 @@ public final class XPathExpression implements BooleanExpression { */ public boolean matches(MessageEvaluationContext message) throws JMSException { Object object = evaluate(message); - return object!=null && object==Boolean.TRUE; + return object != null && object == Boolean.TRUE; } } diff --git a/activemq-core/src/main/java/org/apache/activemq/filter/XQueryExpression.java b/activemq-core/src/main/java/org/apache/activemq/filter/XQueryExpression.java index 4f0f5ee0ac..5f18cbf2a5 100755 --- a/activemq-core/src/main/java/org/apache/activemq/filter/XQueryExpression.java +++ b/activemq-core/src/main/java/org/apache/activemq/filter/XQueryExpression.java @@ -34,9 +34,9 @@ public final class XQueryExpression implements BooleanExpression { } public String toString() { - return "XQUERY "+ConstantExpression.encodeString(xpath); + return "XQUERY " + ConstantExpression.encodeString(xpath); } - + /** * @param message * @return true if the expression evaluates to Boolean.TRUE. @@ -44,7 +44,7 @@ public final class XQueryExpression implements BooleanExpression { */ public boolean matches(MessageEvaluationContext message) throws JMSException { Object object = evaluate(message); - return object!=null && object==Boolean.TRUE; + return object != null && object == Boolean.TRUE; } } diff --git a/activemq-core/src/main/java/org/apache/activemq/filter/XalanXPathEvaluator.java b/activemq-core/src/main/java/org/apache/activemq/filter/XalanXPathEvaluator.java index e75ae597b5..f3caf311ff 100755 --- a/activemq-core/src/main/java/org/apache/activemq/filter/XalanXPathEvaluator.java +++ b/activemq-core/src/main/java/org/apache/activemq/filter/XalanXPathEvaluator.java @@ -33,40 +33,40 @@ import org.w3c.dom.traversal.NodeIterator; import org.xml.sax.InputSource; public class XalanXPathEvaluator implements XPathExpression.XPathEvaluator { - + private final String xpath; public XalanXPathEvaluator(String xpath) { this.xpath = xpath; } - + public boolean evaluate(Message m) throws JMSException { - if( m instanceof TextMessage ) { + if (m instanceof TextMessage) { String text = ((TextMessage)m).getText(); - return evaluate(text); - } else if ( m instanceof BytesMessage ) { - BytesMessage bm = (BytesMessage) m; - byte data[] = new byte[(int) bm.getBodyLength()]; + return evaluate(text); + } else if (m instanceof BytesMessage) { + BytesMessage bm = (BytesMessage)m; + byte data[] = new byte[(int)bm.getBodyLength()]; bm.readBytes(data); return evaluate(data); - } + } return false; } private boolean evaluate(byte[] data) { try { - + InputSource inputSource = new InputSource(new ByteArrayInputStream(data)); - + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); DocumentBuilder dbuilder = factory.newDocumentBuilder(); Document doc = dbuilder.parse(inputSource); - + CachedXPathAPI cachedXPathAPI = new CachedXPathAPI(); - NodeIterator iterator = cachedXPathAPI.selectNodeIterator(doc,xpath); - return iterator.nextNode()!=null; - + NodeIterator iterator = cachedXPathAPI.selectNodeIterator(doc, xpath); + return iterator.nextNode() != null; + } catch (Throwable e) { return false; } @@ -75,17 +75,18 @@ public class XalanXPathEvaluator implements XPathExpression.XPathEvaluator { private boolean evaluate(String text) { try { InputSource inputSource = new InputSource(new StringReader(text)); - + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); DocumentBuilder dbuilder = factory.newDocumentBuilder(); Document doc = dbuilder.parse(inputSource); - - // We should associated the cachedXPathAPI object with the message being evaluated + + // We should associated the cachedXPathAPI object with the message + // being evaluated // since that should speedup subsequent xpath expressions. CachedXPathAPI cachedXPathAPI = new CachedXPathAPI(); - NodeIterator iterator = cachedXPathAPI.selectNodeIterator(doc,xpath); - return iterator.nextNode()!=null; + NodeIterator iterator = cachedXPathAPI.selectNodeIterator(doc, xpath); + return iterator.nextNode() != null; } catch (Throwable e) { return false; } diff --git a/activemq-core/src/main/java/org/apache/activemq/jndi/ActiveMQInitialContextFactory.java b/activemq-core/src/main/java/org/apache/activemq/jndi/ActiveMQInitialContextFactory.java index e87d31c589..20c2f8bfe7 100755 --- a/activemq-core/src/main/java/org/apache/activemq/jndi/ActiveMQInitialContextFactory.java +++ b/activemq-core/src/main/java/org/apache/activemq/jndi/ActiveMQInitialContextFactory.java @@ -40,18 +40,19 @@ import org.apache.activemq.command.ActiveMQTopic; import java.util.concurrent.ConcurrentHashMap; /** - * A factory of the ActiveMQ InitialContext which contains {@link ConnectionFactory} - * instances as well as a child context called destinations which contain all of the - * current active destinations, in child context depending on the QoS such as - * transient or durable and queue or topic. - * + * A factory of the ActiveMQ InitialContext which contains + * {@link ConnectionFactory} instances as well as a child context called + * destinations which contain all of the current active destinations, in + * child context depending on the QoS such as transient or durable and queue or + * topic. + * * @version $Revision: 1.2 $ */ public class ActiveMQInitialContextFactory implements InitialContextFactory { - private static final String[] defaultConnectionFactoryNames = { - "ConnectionFactory", "QueueConnectionFactory", "TopicConnectionFactory" - }; + private static final String[] defaultConnectionFactoryNames = {"ConnectionFactory", + "QueueConnectionFactory", + "TopicConnectionFactory"}; private String connectionPrefix = "connection."; private String queuePrefix = "queue."; @@ -62,34 +63,29 @@ public class ActiveMQInitialContextFactory implements InitialContextFactory { Map data = new ConcurrentHashMap(); String[] names = getConnectionFactoryNames(environment); for (int i = 0; i < names.length; i++) { - ActiveMQConnectionFactory factory =null; + ActiveMQConnectionFactory factory = null; String name = names[i]; - try{ - factory = createConnectionFactory(name, environment); - }catch(Exception e){ + try { + factory = createConnectionFactory(name, environment); + } catch (Exception e) { throw new NamingException("Invalid broker URL"); } - /* if( broker==null ) { - try { - broker = factory.getEmbeddedBroker(); - } - catch (JMSException e) { - log.warn("Failed to get embedded broker", e); - } - } - */ - data.put(name,factory); + /* + * if( broker==null ) { try { broker = factory.getEmbeddedBroker(); } + * catch (JMSException e) { log.warn("Failed to get embedded + * broker", e); } } + */ + data.put(name, factory); } createQueues(data, environment); createTopics(data, environment); /* - if (broker != null) { - data.put("destinations", broker.getDestinationContext(environment)); - } - */ + * if (broker != null) { data.put("destinations", + * broker.getDestinationContext(environment)); } + */ data.put("dynamicQueues", new LazyCreateContext() { private static final long serialVersionUID = 6503881346214855588L; @@ -109,7 +105,7 @@ public class ActiveMQInitialContextFactory implements InitialContextFactory { } // Properties - //------------------------------------------------------------------------- + // ------------------------------------------------------------------------- public String getTopicPrefix() { return topicPrefix; } @@ -127,19 +123,20 @@ public class ActiveMQInitialContextFactory implements InitialContextFactory { } // Implementation methods - //------------------------------------------------------------------------- + // ------------------------------------------------------------------------- protected ReadOnlyContext createContext(Hashtable environment, Map data) { return new ReadOnlyContext(environment, data); } - protected ActiveMQConnectionFactory createConnectionFactory(String name, Hashtable environment) throws URISyntaxException { + protected ActiveMQConnectionFactory createConnectionFactory(String name, Hashtable environment) + throws URISyntaxException { Hashtable temp = new Hashtable(environment); - String prefix = connectionPrefix+name+"."; + String prefix = connectionPrefix + name + "."; for (Iterator iter = environment.entrySet().iterator(); iter.hasNext();) { - Map.Entry entry = (Map.Entry) iter.next(); - String key = (String) entry.getKey(); - if( key.startsWith(prefix) ) { + Map.Entry entry = (Map.Entry)iter.next(); + String key = (String)entry.getKey(); + if (key.startsWith(prefix)) { // Rename the key... temp.remove(key); key = key.substring(prefix.length()); @@ -150,10 +147,11 @@ public class ActiveMQInitialContextFactory implements InitialContextFactory { } protected String[] getConnectionFactoryNames(Map environment) { - String factoryNames = (String) environment.get("connectionFactoryNames"); + String factoryNames = (String)environment.get("connectionFactoryNames"); if (factoryNames != null) { List list = new ArrayList(); - for (StringTokenizer enumeration = new StringTokenizer(factoryNames, ","); enumeration.hasMoreTokens();) { + for (StringTokenizer enumeration = new StringTokenizer(factoryNames, ","); enumeration + .hasMoreTokens();) { list.add(enumeration.nextToken().trim()); } int size = list.size(); @@ -168,7 +166,7 @@ public class ActiveMQInitialContextFactory implements InitialContextFactory { protected void createQueues(Map data, Hashtable environment) { for (Iterator iter = environment.entrySet().iterator(); iter.hasNext();) { - Map.Entry entry = (Map.Entry) iter.next(); + Map.Entry entry = (Map.Entry)iter.next(); String key = entry.getKey().toString(); if (key.startsWith(queuePrefix)) { String jndiName = key.substring(queuePrefix.length()); @@ -179,7 +177,7 @@ public class ActiveMQInitialContextFactory implements InitialContextFactory { protected void createTopics(Map data, Hashtable environment) { for (Iterator iter = environment.entrySet().iterator(); iter.hasNext();) { - Map.Entry entry = (Map.Entry) iter.next(); + Map.Entry entry = (Map.Entry)iter.next(); String key = entry.getKey().toString(); if (key.startsWith(topicPrefix)) { String jndiName = key.substring(topicPrefix.length()); @@ -201,11 +199,13 @@ public class ActiveMQInitialContextFactory implements InitialContextFactory { protected Topic createTopic(String name) { return new ActiveMQTopic(name); } - + /** - * Factory method to create a new connection factory from the given environment + * Factory method to create a new connection factory from the given + * environment */ - protected ActiveMQConnectionFactory createConnectionFactory(Hashtable environment) throws URISyntaxException { + protected ActiveMQConnectionFactory createConnectionFactory(Hashtable environment) + throws URISyntaxException { ActiveMQConnectionFactory answer = new ActiveMQConnectionFactory(); Properties properties = new Properties(); properties.putAll(environment); @@ -216,10 +216,9 @@ public class ActiveMQInitialContextFactory implements InitialContextFactory { public String getConnectionPrefix() { return connectionPrefix; } - public void setConnectionPrefix(String connectionPrefix) { this.connectionPrefix = connectionPrefix; } - + } diff --git a/activemq-core/src/main/java/org/apache/activemq/kaha/BytesMarshaller.java b/activemq-core/src/main/java/org/apache/activemq/kaha/BytesMarshaller.java index f1337fc63f..885f8bb478 100644 --- a/activemq-core/src/main/java/org/apache/activemq/kaha/BytesMarshaller.java +++ b/activemq-core/src/main/java/org/apache/activemq/kaha/BytesMarshaller.java @@ -19,12 +19,13 @@ package org.apache.activemq.kaha; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; + /** * Implementation of a Marshaller for byte arrays * * @version $Revision: 1.2 $ */ -public class BytesMarshaller implements Marshaller{ +public class BytesMarshaller implements Marshaller { /** * Write the payload of this entry to the RawContainer * @@ -32,8 +33,8 @@ public class BytesMarshaller implements Marshaller{ * @param dataOut * @throws IOException */ - public void writePayload(Object object,DataOutput dataOut) throws IOException{ - byte[] data=(byte[]) object; + public void writePayload(Object object, DataOutput dataOut) throws IOException { + byte[] data = (byte[])object; dataOut.writeInt(data.length); dataOut.write(data); } @@ -45,9 +46,9 @@ public class BytesMarshaller implements Marshaller{ * @return unmarshalled object * @throws IOException */ - public Object readPayload(DataInput dataIn) throws IOException{ - int size=dataIn.readInt(); - byte[] data=new byte[size]; + public Object readPayload(DataInput dataIn) throws IOException { + int size = dataIn.readInt(); + byte[] data = new byte[size]; dataIn.readFully(data); return data; } diff --git a/activemq-core/src/main/java/org/apache/activemq/kaha/ContainerId.java b/activemq-core/src/main/java/org/apache/activemq/kaha/ContainerId.java index d8635c1394..e41ac54565 100644 --- a/activemq-core/src/main/java/org/apache/activemq/kaha/ContainerId.java +++ b/activemq-core/src/main/java/org/apache/activemq/kaha/ContainerId.java @@ -20,77 +20,77 @@ import java.io.Externalizable; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; + /** * Used by RootContainers * * @version $Revision: 1.1.1.1 $ */ -public class ContainerId implements Externalizable{ - private static final long serialVersionUID=-8883779541021821943L; +public class ContainerId implements Externalizable { + private static final long serialVersionUID = -8883779541021821943L; private Object key; private String dataContainerName; public ContainerId() { } - - public ContainerId(Object key,String dataContainerName) { - this.key=key; - this.dataContainerName=dataContainerName; + + public ContainerId(Object key, String dataContainerName) { + this.key = key; + this.dataContainerName = dataContainerName; } - - + /** * @return Returns the dataContainerPrefix. */ - public String getDataContainerName(){ + public String getDataContainerName() { return dataContainerName; } /** * @param dataContainerName The dataContainerPrefix to set. */ - public void setDataContainerName(String dataContainerName){ - this.dataContainerName=dataContainerName; + public void setDataContainerName(String dataContainerName) { + this.dataContainerName = dataContainerName; } /** * @return Returns the key. */ - public Object getKey(){ + public Object getKey() { return key; } /** * @param key The key to set. */ - public void setKey(Object key){ - this.key=key; + public void setKey(Object key) { + this.key = key; } - - public int hashCode(){ + + public int hashCode() { return key.hashCode(); } - - public boolean equals(Object obj){ + + public boolean equals(Object obj) { boolean result = false; - if (obj != null && obj instanceof ContainerId){ - ContainerId other = (ContainerId) obj; + if (obj != null && obj instanceof ContainerId) { + ContainerId other = (ContainerId)obj; result = other.key.equals(this.key); } return result; } - public void writeExternal(ObjectOutput out) throws IOException{ + public void writeExternal(ObjectOutput out) throws IOException { out.writeUTF(getDataContainerName()); out.writeObject(key); } - public void readExternal(ObjectInput in) throws IOException,ClassNotFoundException{ - dataContainerName=in.readUTF(); - key=in.readObject(); + public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { + dataContainerName = in.readUTF(); + key = in.readObject(); } - - public String toString(){ - return "CID{"+dataContainerName + ":" + key + "}"; + + public String toString() { + return "CID{" + dataContainerName + ":" + key + "}"; } } diff --git a/activemq-core/src/main/java/org/apache/activemq/kaha/ListContainer.java b/activemq-core/src/main/java/org/apache/activemq/kaha/ListContainer.java index 6ede5638c2..a82b2e43e3 100644 --- a/activemq-core/src/main/java/org/apache/activemq/kaha/ListContainer.java +++ b/activemq-core/src/main/java/org/apache/activemq/kaha/ListContainer.java @@ -18,16 +18,17 @@ import java.util.List; import java.util.NoSuchElementException; /** - * Represents a container of persistent objects in the store Acts as a map, but values can be retrieved in insertion - * order + * Represents a container of persistent objects in the store Acts as a map, but + * values can be retrieved in insertion order * * @version $Revision: 1.2 $ */ -public interface ListContainer extends List{ +public interface ListContainer extends List { /** - * The container is created or retrieved in an unloaded state. load populates the container will all the indexes - * used etc and should be called before any operations on the container + * The container is created or retrieved in an unloaded state. load + * populates the container will all the indexes used etc and should be + * called before any operations on the container */ public void load(); @@ -43,7 +44,8 @@ public interface ListContainer extends List{ public boolean isLoaded(); /** - * For homogenous containers can set a custom marshaller for loading values The default uses Object serialization + * For homogenous containers can set a custom marshaller for loading values + * The default uses Object serialization * * @param marshaller */ @@ -67,8 +69,8 @@ public interface ListContainer extends List{ public void addFirst(V o); /** - * Appends the given element to the end of this list. (Identical in function to the add method; included - * only for consistency.) + * Appends the given element to the end of this list. (Identical in function + * to the add method; included only for consistency.) * * @param o the element to be inserted at the end of this list. */ @@ -91,7 +93,8 @@ public interface ListContainer extends List{ public V removeLast(); /** - * remove an objecr from the list without retrieving the old value from the store + * remove an objecr from the list without retrieving the old value from the + * store * * @param position * @return true if successful @@ -107,7 +110,8 @@ public interface ListContainer extends List{ public StoreEntry placeLast(V object); /** - * insert an Object in first position int the list but get a StoreEntry of its position + * insert an Object in first position int the list but get a StoreEntry of + * its position * * @param object * @return the location in the Store @@ -115,12 +119,13 @@ public interface ListContainer extends List{ public StoreEntry placeFirst(V object); /** - * Advanced feature = must ensure the object written doesn't overwrite other objects in the container + * Advanced feature = must ensure the object written doesn't overwrite other + * objects in the container * * @param entry * @param object */ - public void update(StoreEntry entry,V object); + public void update(StoreEntry entry, V object); /** * Retrieve an Object from the Store by its location @@ -167,10 +172,11 @@ public interface ListContainer extends List{ * @return true if successful */ public boolean remove(StoreEntry entry); - + /** - * It's possible that a StoreEntry could be come stale - * this will return an upto date entry for the StoreEntry position + * It's possible that a StoreEntry could be come stale this will return an + * upto date entry for the StoreEntry position + * * @param entry old entry * @return a refreshed StoreEntry */ diff --git a/activemq-core/src/main/java/org/apache/activemq/kaha/MapContainer.java b/activemq-core/src/main/java/org/apache/activemq/kaha/MapContainer.java index 83d84c180e..ccee6589b2 100644 --- a/activemq-core/src/main/java/org/apache/activemq/kaha/MapContainer.java +++ b/activemq-core/src/main/java/org/apache/activemq/kaha/MapContainer.java @@ -21,47 +21,48 @@ import java.util.Map; import java.util.Set; /** - *Represents a container of persistent objects in the store - *Acts as a map, but values can be retrieved in insertion order + * Represents a container of persistent objects in the store Acts as a map, but + * values can be retrieved in insertion order * * @version $Revision: 1.2 $ */ -public interface MapContainer extends Map{ - - +public interface MapContainer extends Map { + /** - * The container is created or retrieved in - * an unloaded state. - * load populates the container will all the indexes used etc - * and should be called before any operations on the container + * The container is created or retrieved in an unloaded state. load + * populates the container will all the indexes used etc and should be + * called before any operations on the container */ public void load(); - + /** * unload indexes from the container - * + * */ public void unload(); - + /** * @return true if the indexes are loaded */ public boolean isLoaded(); - + /** * For homogenous containers can set a custom marshaller for loading keys * The default uses Object serialization + * * @param keyMarshaller */ public void setKeyMarshaller(Marshaller keyMarshaller); - + /** * For homogenous containers can set a custom marshaller for loading values * The default uses Object serialization - * @param valueMarshaller - + * + * @param valueMarshaller + * */ public void setValueMarshaller(Marshaller valueMarshaller); + /** * @return the id the MapContainer was create with */ @@ -78,30 +79,31 @@ public interface MapContainer extends Map{ public boolean isEmpty(); /** - * @param key + * @param key * @return true if the container contains the key */ public boolean containsKey(K key); /** * Get the value associated with the key - * @param key + * + * @param key * @return the value associated with the key from the store */ public V get(K key); - /** - * @param o + * @param o * @return true if the MapContainer contains the value o */ public boolean containsValue(K o); /** * Add add entries in the supplied Map + * * @param map */ - public void putAll(Map map); + public void putAll(Map map); /** * @return a Set of all the keys @@ -109,30 +111,30 @@ public interface MapContainer extends Map{ public Set keySet(); /** - * @return a collection of all the values - the values will be lazily pulled out of the - * store if iterated etc. + * @return a collection of all the values - the values will be lazily pulled + * out of the store if iterated etc. */ public Collection values(); /** - * @return a Set of all the Map.Entry instances - the values will be lazily pulled out of the - * store if iterated etc. + * @return a Set of all the Map.Entry instances - the values will be lazily + * pulled out of the store if iterated etc. */ - public Set> entrySet(); + public Set> entrySet(); - /** * Add an entry + * * @param key * @param value * @return the old value for the key */ - public V put(K key,V value); - + public V put(K key, V value); /** * remove an entry associated with the key - * @param key + * + * @param key * @return the old value assocaited with the key or null */ public V remove(K key); @@ -141,77 +143,83 @@ public interface MapContainer extends Map{ * empty the container */ public void clear(); - + /** * Add an entry to the Store Map + * * @param key * @param Value * @return the StoreEntry associated with the entry */ public StoreEntry place(K key, V Value); - + /** * Remove an Entry from ther Map + * * @param entry */ public void remove(StoreEntry entry); - + /** * Get the Key object from it's location + * * @param keyLocation * @return the key for the entry */ public K getKey(StoreEntry keyLocation); - + /** * Get the value from it's location + * * @param Valuelocation * @return the Object */ public V getValue(StoreEntry Valuelocation); - - /** Get the StoreEntry for the first value in the Map - * - * @return the first StoreEntry or null if the map is empty - */ - public StoreEntry getFirst(); - /** - * Get the StoreEntry for the last value item of the Map - * - * @return the last StoreEntry or null if the list is empty - */ - public StoreEntry getLast(); + /** + * Get the StoreEntry for the first value in the Map + * + * @return the first StoreEntry or null if the map is empty + */ + public StoreEntry getFirst(); - /** - * Get the next StoreEntry value from the map - * - * @param entry - * @return the next StoreEntry or null - */ - public StoreEntry getNext(StoreEntry entry); + /** + * Get the StoreEntry for the last value item of the Map + * + * @return the last StoreEntry or null if the list is empty + */ + public StoreEntry getLast(); - /** - * Get the previous StoreEntry from the map - * - * @param entry - * @return the previous store entry or null - */ - public StoreEntry getPrevious(StoreEntry entry); + /** + * Get the next StoreEntry value from the map + * + * @param entry + * @return the next StoreEntry or null + */ + public StoreEntry getNext(StoreEntry entry); - - /** - * It's possible that a StoreEntry could be come stale - * this will return an upto date entry for the StoreEntry position - * @param entry old entry - * @return a refreshed StoreEntry - */ - public StoreEntry refresh(StoreEntry entry); - - /** - * Get the StoreEntry associated with the key - * @param key - * @return the StoreEntry - */ - public StoreEntry getEntry(K key); + /** + * Get the previous StoreEntry from the map + * + * @param entry + * @return the previous store entry or null + */ + public StoreEntry getPrevious(StoreEntry entry); + + /** + * It's possible that a StoreEntry could be come stale this will return an + * upto date entry for the StoreEntry position + * + * @param entry old entry + * @return a refreshed StoreEntry + */ + public StoreEntry refresh(StoreEntry entry); + + /** + * Get the StoreEntry associated with the key + * + * @param key + * @return the StoreEntry + */ + public StoreEntry getEntry(K key); } diff --git a/activemq-core/src/main/java/org/apache/activemq/kaha/MessageIdMarshaller.java b/activemq-core/src/main/java/org/apache/activemq/kaha/MessageIdMarshaller.java index 51897f86a4..e40502d016 100644 --- a/activemq-core/src/main/java/org/apache/activemq/kaha/MessageIdMarshaller.java +++ b/activemq-core/src/main/java/org/apache/activemq/kaha/MessageIdMarshaller.java @@ -20,6 +20,7 @@ import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import org.apache.activemq.command.MessageId; + /** * Implementation of a Marshaller for MessageIds * @@ -33,7 +34,7 @@ public class MessageIdMarshaller implements Marshaller { * @param dataOut * @throws IOException */ - public void writePayload(MessageId object,DataOutput dataOut) throws IOException{ + public void writePayload(MessageId object, DataOutput dataOut) throws IOException { dataOut.writeUTF(object.toString()); } @@ -44,7 +45,7 @@ public class MessageIdMarshaller implements Marshaller { * @return unmarshalled object * @throws IOException */ - public MessageId readPayload(DataInput dataIn) throws IOException{ + public MessageId readPayload(DataInput dataIn) throws IOException { return new MessageId(dataIn.readUTF()); } } diff --git a/activemq-core/src/main/java/org/apache/activemq/kaha/ObjectMarshaller.java b/activemq-core/src/main/java/org/apache/activemq/kaha/ObjectMarshaller.java index 3c923ba617..2a6d102a50 100644 --- a/activemq-core/src/main/java/org/apache/activemq/kaha/ObjectMarshaller.java +++ b/activemq-core/src/main/java/org/apache/activemq/kaha/ObjectMarshaller.java @@ -27,7 +27,7 @@ import java.io.ObjectOutputStream; * * @version $Revision: 1.2 $ */ -public class ObjectMarshaller implements Marshaller{ +public class ObjectMarshaller implements Marshaller { /** * Write the payload of this entry to the RawContainer @@ -36,12 +36,12 @@ public class ObjectMarshaller implements Marshaller{ * @param dataOut * @throws IOException */ - public void writePayload(Object object,DataOutput dataOut) throws IOException{ - ByteArrayOutputStream bytesOut=new ByteArrayOutputStream(); - ObjectOutputStream objectOut=new ObjectOutputStream(bytesOut); + public void writePayload(Object object, DataOutput dataOut) throws IOException { + ByteArrayOutputStream bytesOut = new ByteArrayOutputStream(); + ObjectOutputStream objectOut = new ObjectOutputStream(bytesOut); objectOut.writeObject(object); objectOut.close(); - byte[] data=bytesOut.toByteArray(); + byte[] data = bytesOut.toByteArray(); dataOut.writeInt(data.length); dataOut.write(data); } @@ -53,15 +53,15 @@ public class ObjectMarshaller implements Marshaller{ * @return unmarshalled object * @throws IOException */ - public Object readPayload(DataInput dataIn) throws IOException{ - int size=dataIn.readInt(); - byte[] data=new byte[size]; + public Object readPayload(DataInput dataIn) throws IOException { + int size = dataIn.readInt(); + byte[] data = new byte[size]; dataIn.readFully(data); - ByteArrayInputStream bytesIn=new ByteArrayInputStream(data); - ObjectInputStream objectIn=new ObjectInputStream(bytesIn); - try{ + ByteArrayInputStream bytesIn = new ByteArrayInputStream(data); + ObjectInputStream objectIn = new ObjectInputStream(bytesIn); + try { return objectIn.readObject(); - }catch(ClassNotFoundException e){ + } catch (ClassNotFoundException e) { throw new IOException(e.getMessage()); } } diff --git a/activemq-core/src/main/java/org/apache/activemq/kaha/RuntimeStoreException.java b/activemq-core/src/main/java/org/apache/activemq/kaha/RuntimeStoreException.java index eaa6e4f9a7..b96dd2e098 100644 --- a/activemq-core/src/main/java/org/apache/activemq/kaha/RuntimeStoreException.java +++ b/activemq-core/src/main/java/org/apache/activemq/kaha/RuntimeStoreException.java @@ -16,47 +16,48 @@ */ package org.apache.activemq.kaha; - /** -*Runtime exception for the Store -* -* @version $Revision: 1.2 $ -*/ + * Runtime exception for the Store + * + * @version $Revision: 1.2 $ + */ -public class RuntimeStoreException extends RuntimeException{ - - - private static final long serialVersionUID=8807084681372365173L; +public class RuntimeStoreException extends RuntimeException { + + private static final long serialVersionUID = 8807084681372365173L; /** * Constructor */ - public RuntimeStoreException(){ + public RuntimeStoreException() { super(); } /** * Constructor + * * @param message */ - public RuntimeStoreException(String message){ + public RuntimeStoreException(String message) { super(message); } /** * Constructor + * * @param message * @param cause */ - public RuntimeStoreException(String message,Throwable cause){ - super(message,cause); + public RuntimeStoreException(String message, Throwable cause) { + super(message, cause); } /** * Constructor + * * @param cause */ - public RuntimeStoreException(Throwable cause){ + public RuntimeStoreException(Throwable cause) { super(cause); } } diff --git a/activemq-core/src/main/java/org/apache/activemq/kaha/Store.java b/activemq-core/src/main/java/org/apache/activemq/kaha/Store.java index 1066b59bf8..0c976a99ee 100644 --- a/activemq-core/src/main/java/org/apache/activemq/kaha/Store.java +++ b/activemq-core/src/main/java/org/apache/activemq/kaha/Store.java @@ -18,37 +18,38 @@ package org.apache.activemq.kaha; import java.io.IOException; import java.util.Set; + /** * A Store is holds persistent containers * * @version $Revision: 1.2 $ */ -public interface Store{ +public interface Store { /** * Defauly container name */ - public static final String DEFAULT_CONTAINER_NAME="kaha"; + public static final String DEFAULT_CONTAINER_NAME = "kaha"; /** * Byte Marshaller */ public final static Marshaller BytesMarshaller = new BytesMarshaller(); - + /** * Object Marshaller */ public final static Marshaller ObjectMarshaller = new ObjectMarshaller(); - + /** * String Marshaller */ public final static Marshaller StringMarshaller = new StringMarshaller(); - - + /** * Command Marshaller */ public final static Marshaller CommandMarshaller = new CommandMarshaller(); + /** * close the store * @@ -86,46 +87,50 @@ public interface Store{ * @throws IOException */ public boolean doesMapContainerExist(Object id) throws IOException; - + /** * Checks if a MapContainer exists in the named container * * @param id - * @param containerName + * @param containerName * @return new MapContainer * @throws IOException */ - public boolean doesMapContainerExist(Object id,String containerName) throws IOException; + public boolean doesMapContainerExist(Object id, String containerName) throws IOException; /** - * Get a MapContainer with the given id - the MapContainer is created if needed + * Get a MapContainer with the given id - the MapContainer is created if + * needed * * @param id * @return container for the associated id or null if it doesn't exist * @throws IOException */ - public MapContainer getMapContainer(Object id) throws IOException; + public MapContainer getMapContainer(Object id) throws IOException; /** - * Get a MapContainer with the given id - the MapContainer is created if needed + * Get a MapContainer with the given id - the MapContainer is created if + * needed * * @param id * @param containerName * @return container for the associated id or null if it doesn't exist * @throws IOException */ - public MapContainer getMapContainer(Object id,String containerName) throws IOException; - + public MapContainer getMapContainer(Object id, String containerName) throws IOException; + /** - * Get a MapContainer with the given id - the MapContainer is created if needed + * Get a MapContainer with the given id - the MapContainer is created if + * needed * * @param id * @param containerName - * @param persistentIndex + * @param persistentIndex * @return container for the associated id or null if it doesn't exist * @throws IOException */ - public MapContainer getMapContainer(Object id,String containerName,boolean persistentIndex) throws IOException; + public MapContainer getMapContainer(Object id, String containerName, boolean persistentIndex) + throws IOException; /** * delete a container from the default container @@ -134,18 +139,19 @@ public interface Store{ * @throws IOException */ public void deleteMapContainer(Object id) throws IOException; - + /** * delete a MapContainer from the name container * * @param id - * @param containerName + * @param containerName * @throws IOException */ - public void deleteMapContainer(Object id,String containerName) throws IOException; - + public void deleteMapContainer(Object id, String containerName) throws IOException; + /** * Delete Map container + * * @param id * @throws IOException */ @@ -167,16 +173,16 @@ public interface Store{ * @throws IOException */ public boolean doesListContainerExist(Object id) throws IOException; - + /** * Checks if a ListContainer exists in the named container * * @param id - * @param containerName + * @param containerName * @return new MapContainer * @throws IOException */ - public boolean doesListContainerExist(Object id,String containerName) throws IOException; + public boolean doesListContainerExist(Object id, String containerName) throws IOException; /** * Get a ListContainer with the given id and creates it if it doesn't exist @@ -185,7 +191,7 @@ public interface Store{ * @return container for the associated id or null if it doesn't exist * @throws IOException */ - public ListContainer getListContainer(Object id) throws IOException; + public ListContainer getListContainer(Object id) throws IOException; /** * Get a ListContainer with the given id and creates it if it doesn't exist @@ -195,18 +201,19 @@ public interface Store{ * @return container for the associated id or null if it doesn't exist * @throws IOException */ - public ListContainer getListContainer(Object id,String containerName) throws IOException; - + public ListContainer getListContainer(Object id, String containerName) throws IOException; + /** * Get a ListContainer with the given id and creates it if it doesn't exist * * @param id * @param containerName - * @param persistentIndex + * @param persistentIndex * @return container for the associated id or null if it doesn't exist * @throws IOException */ - public ListContainer getListContainer(Object id,String containerName,boolean persistentIndex) throws IOException; + public ListContainer getListContainer(Object id, String containerName, boolean persistentIndex) + throws IOException; /** * delete a ListContainer from the default container @@ -215,18 +222,19 @@ public interface Store{ * @throws IOException */ public void deleteListContainer(Object id) throws IOException; - + /** * delete a ListContainer from the named container * * @param id - * @param containerName + * @param containerName * @throws IOException */ - public void deleteListContainer(Object id,String containerName) throws IOException; + public void deleteListContainer(Object id, String containerName) throws IOException; /** * delete a list container + * * @param id * @throws IOException */ @@ -239,7 +247,7 @@ public interface Store{ * @throws IOException */ public Set getListContainerIds() throws IOException; - + /** * @return the maxDataFileLength */ @@ -249,20 +257,21 @@ public interface Store{ * @param maxDataFileLength the maxDataFileLength to set */ public void setMaxDataFileLength(long maxDataFileLength); - + /** * @see org.apache.activemq.kaha.IndexTypes * @return the default index type */ public String getIndexTypeAsString(); - + /** * Set the default index type + * * @param type * @see org.apache.activemq.kaha.IndexTypes */ public void setIndexTypeAsString(String type); - + /** * @return true if the store has been initialized */ diff --git a/activemq-core/src/main/java/org/apache/activemq/kaha/StoreFactory.java b/activemq-core/src/main/java/org/apache/activemq/kaha/StoreFactory.java index 4d8b286192..61f9a7c254 100755 --- a/activemq-core/src/main/java/org/apache/activemq/kaha/StoreFactory.java +++ b/activemq-core/src/main/java/org/apache/activemq/kaha/StoreFactory.java @@ -25,28 +25,29 @@ import org.apache.activemq.kaha.impl.KahaStore; * * @version $Revision: 1.2 $ */ -public class StoreFactory{ - +public class StoreFactory { /** * open or create a Store + * * @param name * @param mode * @return the opened/created store * @throws IOException */ - public static Store open(String name,String mode) throws IOException{ - return new KahaStore(name,mode); + public static Store open(String name, String mode) throws IOException { + return new KahaStore(name, mode); } - + /** * Delete a database + * * @param name of the database * @return true if successful - * @throws IOException + * @throws IOException */ - public static boolean delete(String name) throws IOException{ - KahaStore store = new KahaStore(name,"rw"); + public static boolean delete(String name) throws IOException { + KahaStore store = new KahaStore(name, "rw"); return store.delete(); } } diff --git a/activemq-core/src/main/java/org/apache/activemq/kaha/StringMarshaller.java b/activemq-core/src/main/java/org/apache/activemq/kaha/StringMarshaller.java index b3550c48a8..c3fc7d8167 100644 --- a/activemq-core/src/main/java/org/apache/activemq/kaha/StringMarshaller.java +++ b/activemq-core/src/main/java/org/apache/activemq/kaha/StringMarshaller.java @@ -19,6 +19,7 @@ package org.apache.activemq.kaha; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; + /** * Implementation of a Marshaller for Strings * @@ -32,7 +33,7 @@ public class StringMarshaller implements Marshaller { * @param dataOut * @throws IOException */ - public void writePayload(String object,DataOutput dataOut) throws IOException{ + public void writePayload(String object, DataOutput dataOut) throws IOException { dataOut.writeUTF(object); } @@ -43,7 +44,7 @@ public class StringMarshaller implements Marshaller { * @return unmarshalled object * @throws IOException */ - public String readPayload(DataInput dataIn) throws IOException{ + public String readPayload(DataInput dataIn) throws IOException { return dataIn.readUTF(); } } diff --git a/activemq-core/src/main/java/org/apache/activemq/kaha/impl/DataManager.java b/activemq-core/src/main/java/org/apache/activemq/kaha/impl/DataManager.java index 12d94436a8..0674f61967 100644 --- a/activemq-core/src/main/java/org/apache/activemq/kaha/impl/DataManager.java +++ b/activemq-core/src/main/java/org/apache/activemq/kaha/impl/DataManager.java @@ -8,35 +8,32 @@ import org.apache.activemq.kaha.impl.data.RedoListener; public interface DataManager { - String getName(); + String getName(); - Object readItem(Marshaller marshaller, StoreLocation item) - throws IOException; + Object readItem(Marshaller marshaller, StoreLocation item) throws IOException; - StoreLocation storeDataItem(Marshaller marshaller, Object payload) - throws IOException; + StoreLocation storeDataItem(Marshaller marshaller, Object payload) throws IOException; - StoreLocation storeRedoItem(Object payload) throws IOException; + StoreLocation storeRedoItem(Object payload) throws IOException; - void updateItem(StoreLocation location, Marshaller marshaller, - Object payload) throws IOException; + void updateItem(StoreLocation location, Marshaller marshaller, Object payload) throws IOException; - void recoverRedoItems(RedoListener listener) throws IOException; + void recoverRedoItems(RedoListener listener) throws IOException; - void close() throws IOException; + void close() throws IOException; - void force() throws IOException; + void force() throws IOException; - boolean delete() throws IOException; + boolean delete() throws IOException; - void addInterestInFile(int file) throws IOException; + void addInterestInFile(int file) throws IOException; - void removeInterestInFile(int file) throws IOException; + void removeInterestInFile(int file) throws IOException; - void consolidateDataFiles() throws IOException; + void consolidateDataFiles() throws IOException; - Marshaller getRedoMarshaller(); + Marshaller getRedoMarshaller(); - void setRedoMarshaller(Marshaller redoMarshaller); + void setRedoMarshaller(Marshaller redoMarshaller); -} \ No newline at end of file +} diff --git a/activemq-core/src/main/java/org/apache/activemq/kaha/impl/IndexRootContainer.java b/activemq-core/src/main/java/org/apache/activemq/kaha/impl/IndexRootContainer.java index 64f4435552..98643ccc68 100755 --- a/activemq-core/src/main/java/org/apache/activemq/kaha/impl/IndexRootContainer.java +++ b/activemq-core/src/main/java/org/apache/activemq/kaha/impl/IndexRootContainer.java @@ -35,58 +35,55 @@ import org.apache.commons.logging.LogFactory; import java.util.concurrent.ConcurrentHashMap; /** -* A container of roots for other Containers -* -* @version $Revision: 1.2 $ -*/ + * A container of roots for other Containers + * + * @version $Revision: 1.2 $ + */ class IndexRootContainer { - private static final Log log=LogFactory.getLog(IndexRootContainer.class); + private static final Log log = LogFactory.getLog(IndexRootContainer.class); protected static final Marshaller rootMarshaller = Store.ObjectMarshaller; protected IndexItem root; protected IndexManager indexManager; protected DataManager dataManager; protected Map map = new ConcurrentHashMap(); protected LinkedList list = new LinkedList(); - - - IndexRootContainer(IndexItem root,IndexManager im,DataManager dfm) throws IOException{ - this.root=root; - this.indexManager=im; - this.dataManager=dfm; - long nextItem=root.getNextItem(); - while(nextItem!=Item.POSITION_NOT_SET){ - StoreEntry item=indexManager.getIndex(nextItem); - StoreLocation data=item.getKeyDataItem(); - Object key = dataManager.readItem(rootMarshaller,data); - map.put(key,item); + + IndexRootContainer(IndexItem root, IndexManager im, DataManager dfm) throws IOException { + this.root = root; + this.indexManager = im; + this.dataManager = dfm; + long nextItem = root.getNextItem(); + while (nextItem != Item.POSITION_NOT_SET) { + StoreEntry item = indexManager.getIndex(nextItem); + StoreLocation data = item.getKeyDataItem(); + Object key = dataManager.readItem(rootMarshaller, data); + map.put(key, item); list.add(item); - nextItem=item.getNextItem(); + nextItem = item.getNextItem(); dataManager.addInterestInFile(item.getKeyFile()); } } - - Set getKeys(){ + + Set getKeys() { return map.keySet(); } - - - - IndexItem addRoot(IndexManager containerIndexManager,ContainerId key) throws IOException{ - if (map.containsKey(key)){ - removeRoot(containerIndexManager,key); + + IndexItem addRoot(IndexManager containerIndexManager, ContainerId key) throws IOException { + if (map.containsKey(key)) { + removeRoot(containerIndexManager, key); } - + StoreLocation data = dataManager.storeDataItem(rootMarshaller, key); IndexItem newRoot = indexManager.createNewIndex(); newRoot.setKeyData(data); IndexItem containerRoot = containerIndexManager.createNewIndex(); containerIndexManager.storeIndex(containerRoot); newRoot.setValueOffset(containerRoot.getOffset()); - - IndexItem last=list.isEmpty()?null:(IndexItem) list.getLast(); - last=last==null?root:last; - long prev=last.getOffset(); + + IndexItem last = list.isEmpty() ? null : (IndexItem)list.getLast(); + last = last == null ? root : last; + long prev = last.getOffset(); newRoot.setPreviousItem(prev); indexManager.storeIndex(newRoot); last.setNextItem(newRoot.getOffset()); @@ -95,25 +92,25 @@ class IndexRootContainer { list.add(newRoot); return containerRoot; } - - void removeRoot(IndexManager containerIndexManager,ContainerId key) throws IOException{ - StoreEntry oldRoot=(StoreEntry)map.remove(key); - if(oldRoot!=null){ + + void removeRoot(IndexManager containerIndexManager, ContainerId key) throws IOException { + StoreEntry oldRoot = (StoreEntry)map.remove(key); + if (oldRoot != null) { dataManager.removeInterestInFile(oldRoot.getKeyFile()); // get the container root - IndexItem containerRoot=containerIndexManager.getIndex(oldRoot.getValueOffset()); - if(containerRoot!=null){ + IndexItem containerRoot = containerIndexManager.getIndex(oldRoot.getValueOffset()); + if (containerRoot != null) { containerIndexManager.freeIndex(containerRoot); } - int index=list.indexOf(oldRoot); - IndexItem prev=index>0?(IndexItem)list.get(index-1):root; - prev=prev==null?root:prev; - IndexItem next=index<(list.size()-1)?(IndexItem)list.get(index+1):null; - if(next!=null){ + int index = list.indexOf(oldRoot); + IndexItem prev = index > 0 ? (IndexItem)list.get(index - 1) : root; + prev = prev == null ? root : prev; + IndexItem next = index < (list.size() - 1) ? (IndexItem)list.get(index + 1) : null; + if (next != null) { prev.setNextItem(next.getOffset()); next.setPreviousItem(prev.getOffset()); indexManager.updateIndexes(next); - }else{ + } else { prev.setNextItem(Item.POSITION_NOT_SET); } indexManager.updateIndexes(prev); @@ -121,19 +118,17 @@ class IndexRootContainer { indexManager.freeIndex((IndexItem)oldRoot); } } - - IndexItem getRoot(IndexManager containerIndexManager,ContainerId key) throws IOException{ - StoreEntry index = (StoreEntry) map.get(key); - if (index != null){ + + IndexItem getRoot(IndexManager containerIndexManager, ContainerId key) throws IOException { + StoreEntry index = (StoreEntry)map.get(key); + if (index != null) { return containerIndexManager.getIndex(index.getValueOffset()); } return null; } - - boolean doesRootExist(Object key){ + + boolean doesRootExist(Object key) { return map.containsKey(key); } - - } diff --git a/activemq-core/src/main/java/org/apache/activemq/kaha/impl/StoreLockedExcpetion.java b/activemq-core/src/main/java/org/apache/activemq/kaha/impl/StoreLockedExcpetion.java index 6beb2e1e4a..13e6306d9f 100644 --- a/activemq-core/src/main/java/org/apache/activemq/kaha/impl/StoreLockedExcpetion.java +++ b/activemq-core/src/main/java/org/apache/activemq/kaha/impl/StoreLockedExcpetion.java @@ -18,27 +18,25 @@ package org.apache.activemq.kaha.impl; import java.io.IOException; - - /** -* Exception thrown if the store is in use by another application -* -* @version $Revision: 1.1.1.1 $ -*/ -public class StoreLockedExcpetion extends IOException{ + * Exception thrown if the store is in use by another application + * + * @version $Revision: 1.1.1.1 $ + */ +public class StoreLockedExcpetion extends IOException { - private static final long serialVersionUID=3857646689671366926L; + private static final long serialVersionUID = 3857646689671366926L; /** * Default Constructor */ - public StoreLockedExcpetion(){ + public StoreLockedExcpetion() { } /** * @param s */ - public StoreLockedExcpetion(String s){ + public StoreLockedExcpetion(String s) { super(s); } } diff --git a/activemq-core/src/main/java/org/apache/activemq/kaha/impl/async/DataFileAccessor.java b/activemq-core/src/main/java/org/apache/activemq/kaha/impl/async/DataFileAccessor.java index e70bbd082f..a67e874755 100644 --- a/activemq-core/src/main/java/org/apache/activemq/kaha/impl/async/DataFileAccessor.java +++ b/activemq-core/src/main/java/org/apache/activemq/kaha/impl/async/DataFileAccessor.java @@ -23,129 +23,130 @@ import java.util.concurrent.ConcurrentHashMap; import org.apache.activemq.kaha.impl.async.DataFileAppender.WriteCommand; import org.apache.activemq.kaha.impl.async.DataFileAppender.WriteKey; import org.apache.activemq.util.ByteSequence; + /** - * Optimized Store reader and updater. Single threaded and synchronous. Use in conjunction - * with the DataFileAccessorPool of concurrent use. + * Optimized Store reader and updater. Single threaded and synchronous. Use in + * conjunction with the DataFileAccessorPool of concurrent use. * * @version $Revision: 1.1.1.1 $ */ final class DataFileAccessor { - - private final DataFile dataFile; - private final ConcurrentHashMap inflightWrites; - private final RandomAccessFile file; - private boolean disposed; - + + private final DataFile dataFile; + private final ConcurrentHashMap inflightWrites; + private final RandomAccessFile file; + private boolean disposed; + /** * Construct a Store reader * * @param fileId - * @throws IOException + * @throws IOException */ - public DataFileAccessor(AsyncDataManager dataManager, DataFile dataFile) throws IOException{ - this.dataFile = dataFile; - this.inflightWrites = dataManager.getInflightWrites(); - this.file = dataFile.openRandomAccessFile(false); + public DataFileAccessor(AsyncDataManager dataManager, DataFile dataFile) throws IOException { + this.dataFile = dataFile; + this.inflightWrites = dataManager.getInflightWrites(); + this.file = dataFile.openRandomAccessFile(false); } - public DataFile getDataFile() { - return dataFile; - } + public DataFile getDataFile() { + return dataFile; + } - public void dispose() { - if( disposed ) - return; - disposed=true; + public void dispose() { + if (disposed) + return; + disposed = true; try { - dataFile.closeRandomAccessFile(file); - } catch (IOException e) { - e.printStackTrace(); - } + dataFile.closeRandomAccessFile(file); + } catch (IOException e) { + e.printStackTrace(); + } } - + public ByteSequence readRecord(Location location) throws IOException { - - if( !location.isValid() ) - throw new IOException("Invalid location: "+location); - - WriteCommand asyncWrite = (WriteCommand) inflightWrites.get(new WriteKey(location)); - if( asyncWrite!= null ) { - return asyncWrite.data; - } - try { + if (!location.isValid()) + throw new IOException("Invalid location: " + location); - if( location.getSize()==Location.NOT_SET ) { - file.seek(location.getOffset()); - location.setSize(file.readInt()); - file.seek(location.getOffset()+AsyncDataManager.ITEM_HEAD_SPACE); - } else { - file.seek(location.getOffset()+AsyncDataManager.ITEM_HEAD_SPACE); - } - - byte[] data=new byte[location.getSize()-AsyncDataManager.ITEM_HEAD_FOOT_SPACE]; - file.readFully(data); - return new ByteSequence(data, 0, data.length); + WriteCommand asyncWrite = (WriteCommand)inflightWrites.get(new WriteKey(location)); + if (asyncWrite != null) { + return asyncWrite.data; + } - } catch (RuntimeException e) { - throw new IOException("Invalid location: "+location+", : "+e); - } + try { + + if (location.getSize() == Location.NOT_SET) { + file.seek(location.getOffset()); + location.setSize(file.readInt()); + file.seek(location.getOffset() + AsyncDataManager.ITEM_HEAD_SPACE); + } else { + file.seek(location.getOffset() + AsyncDataManager.ITEM_HEAD_SPACE); + } + + byte[] data = new byte[location.getSize() - AsyncDataManager.ITEM_HEAD_FOOT_SPACE]; + file.readFully(data); + return new ByteSequence(data, 0, data.length); + + } catch (RuntimeException e) { + throw new IOException("Invalid location: " + location + ", : " + e); + } } - + public void readLocationDetails(Location location) throws IOException { - WriteCommand asyncWrite = (WriteCommand) inflightWrites.get(new WriteKey(location)); - if( asyncWrite!= null ) { - location.setSize(asyncWrite.location.getSize()); - location.setType(asyncWrite.location.getType()); - } else { - file.seek(location.getOffset()); - location.setSize(file.readInt()); - location.setType(file.readByte()); - } + WriteCommand asyncWrite = (WriteCommand)inflightWrites.get(new WriteKey(location)); + if (asyncWrite != null) { + location.setSize(asyncWrite.location.getSize()); + location.setType(asyncWrite.location.getType()); + } else { + file.seek(location.getOffset()); + location.setSize(file.readInt()); + location.setType(file.readByte()); + } } - public boolean readLocationDetailsAndValidate(Location location) { - try { - WriteCommand asyncWrite = (WriteCommand) inflightWrites.get(new WriteKey(location)); - if( asyncWrite!= null ) { - location.setSize(asyncWrite.location.getSize()); - location.setType(asyncWrite.location.getType()); - } else { - file.seek(location.getOffset()); - location.setSize(file.readInt()); - location.setType(file.readByte()); - - byte data[] = new byte[3]; - file.seek(location.getOffset()+AsyncDataManager.ITEM_HEAD_OFFSET_TO_SOR); - file.readFully(data); - if( data[0] != AsyncDataManager.ITEM_HEAD_SOR[0] || - data[1] != AsyncDataManager.ITEM_HEAD_SOR[1] || - data[2] != AsyncDataManager.ITEM_HEAD_SOR[2] ) { - return false; - } - file.seek(location.getOffset()+location.getSize()-AsyncDataManager.ITEM_FOOT_SPACE); - file.readFully(data); - if( data[0] != AsyncDataManager.ITEM_HEAD_EOR[0] || - data[1] != AsyncDataManager.ITEM_HEAD_EOR[1] || - data[2] != AsyncDataManager.ITEM_HEAD_EOR[2] ) { - return false; - } - } - } catch (IOException e) { - return false; - } - return true; - } + public boolean readLocationDetailsAndValidate(Location location) { + try { + WriteCommand asyncWrite = (WriteCommand)inflightWrites.get(new WriteKey(location)); + if (asyncWrite != null) { + location.setSize(asyncWrite.location.getSize()); + location.setType(asyncWrite.location.getType()); + } else { + file.seek(location.getOffset()); + location.setSize(file.readInt()); + location.setType(file.readByte()); - public void updateRecord(Location location, ByteSequence data, boolean sync) throws IOException { - - file.seek(location.getOffset()+AsyncDataManager.ITEM_HEAD_SPACE); - int size = Math.min(data.getLength(), location.getSize()); - file.write(data.getData(), data.getOffset(), size); - if( sync ) { - file.getFD().sync(); - } - - } + byte data[] = new byte[3]; + file.seek(location.getOffset() + AsyncDataManager.ITEM_HEAD_OFFSET_TO_SOR); + file.readFully(data); + if (data[0] != AsyncDataManager.ITEM_HEAD_SOR[0] + || data[1] != AsyncDataManager.ITEM_HEAD_SOR[1] + || data[2] != AsyncDataManager.ITEM_HEAD_SOR[2]) { + return false; + } + file.seek(location.getOffset() + location.getSize() - AsyncDataManager.ITEM_FOOT_SPACE); + file.readFully(data); + if (data[0] != AsyncDataManager.ITEM_HEAD_EOR[0] + || data[1] != AsyncDataManager.ITEM_HEAD_EOR[1] + || data[2] != AsyncDataManager.ITEM_HEAD_EOR[2]) { + return false; + } + } + } catch (IOException e) { + return false; + } + return true; + } + + public void updateRecord(Location location, ByteSequence data, boolean sync) throws IOException { + + file.seek(location.getOffset() + AsyncDataManager.ITEM_HEAD_SPACE); + int size = Math.min(data.getLength(), location.getSize()); + file.write(data.getData(), data.getOffset(), size); + if (sync) { + file.getFD().sync(); + } + + } } diff --git a/activemq-core/src/main/java/org/apache/activemq/kaha/impl/async/DataFileAppender.java b/activemq-core/src/main/java/org/apache/activemq/kaha/impl/async/DataFileAppender.java index 91f6bfc11f..c68c37cec8 100644 --- a/activemq-core/src/main/java/org/apache/activemq/kaha/impl/async/DataFileAppender.java +++ b/activemq-core/src/main/java/org/apache/activemq/kaha/impl/async/DataFileAppender.java @@ -27,348 +27,351 @@ import org.apache.activemq.util.DataByteArrayOutputStream; import org.apache.activemq.util.LinkedNode; /** - * An optimized writer to do batch appends to a data file. This object is thread safe - * and gains throughput as you increase the number of concurrent writes it does. + * An optimized writer to do batch appends to a data file. This object is thread + * safe and gains throughput as you increase the number of concurrent writes it + * does. * * @version $Revision: 1.1.1.1 $ */ class DataFileAppender { - - protected static final byte []RESERVED_SPACE= new byte[AsyncDataManager.ITEM_HEAD_RESERVED_SPACE]; - protected static final String SHUTDOWN_COMMAND = "SHUTDOWN"; - int MAX_WRITE_BATCH_SIZE = 1024*1024*4; - - static public class WriteKey { - private final int file; - private final long offset; - private final int hash; - public WriteKey(Location item){ - file = item.getDataFileId(); - offset = item.getOffset(); - // TODO: see if we can build a better hash - hash = (int) (file ^ offset); - } - - public int hashCode() { - return hash; - } - - public boolean equals(Object obj){ - if(obj instanceof WriteKey){ - WriteKey di=(WriteKey)obj; - return di.file==file&&di.offset==offset; + protected static final byte[] RESERVED_SPACE = new byte[AsyncDataManager.ITEM_HEAD_RESERVED_SPACE]; + protected static final String SHUTDOWN_COMMAND = "SHUTDOWN"; + int MAX_WRITE_BATCH_SIZE = 1024 * 1024 * 4; + + static public class WriteKey { + private final int file; + private final long offset; + private final int hash; + + public WriteKey(Location item) { + file = item.getDataFileId(); + offset = item.getOffset(); + // TODO: see if we can build a better hash + hash = (int)(file ^ offset); + } + + public int hashCode() { + return hash; + } + + public boolean equals(Object obj) { + if (obj instanceof WriteKey) { + WriteKey di = (WriteKey)obj; + return di.file == file && di.offset == offset; } return false; } - } - - public class WriteBatch { - - public final DataFile dataFile; - public final WriteCommand first; - public final CountDownLatch latch = new CountDownLatch(1); - public int size; - - public WriteBatch(DataFile dataFile, WriteCommand write) throws IOException { - this.dataFile=dataFile; - this.first=write; - size+=write.location.getSize(); - } - - public boolean canAppend(DataFile dataFile, WriteCommand write) { - if( dataFile != this.dataFile ) - return false; - if( size+write.location.getSize() >= MAX_WRITE_BATCH_SIZE ) - return false; - return true; - } - - public void append(WriteCommand write) throws IOException { - this.first.getTailNode().linkAfter(write); - size+=write.location.getSize(); - } - } - - public static class WriteCommand extends LinkedNode { - public final Location location; - public final ByteSequence data; - final boolean sync; - - public WriteCommand(Location location, ByteSequence data, boolean sync) { - this.location = location; - this.data = data; - this.sync = sync; - } } - - protected final AsyncDataManager dataManager; - + + public class WriteBatch { + + public final DataFile dataFile; + public final WriteCommand first; + public final CountDownLatch latch = new CountDownLatch(1); + public int size; + + public WriteBatch(DataFile dataFile, WriteCommand write) throws IOException { + this.dataFile = dataFile; + this.first = write; + size += write.location.getSize(); + } + + public boolean canAppend(DataFile dataFile, WriteCommand write) { + if (dataFile != this.dataFile) + return false; + if (size + write.location.getSize() >= MAX_WRITE_BATCH_SIZE) + return false; + return true; + } + + public void append(WriteCommand write) throws IOException { + this.first.getTailNode().linkAfter(write); + size += write.location.getSize(); + } + } + + public static class WriteCommand extends LinkedNode { + public final Location location; + public final ByteSequence data; + final boolean sync; + + public WriteCommand(Location location, ByteSequence data, boolean sync) { + this.location = location; + this.data = data; + this.sync = sync; + } + } + + protected final AsyncDataManager dataManager; + protected final ConcurrentHashMap inflightWrites; - + protected final Object enqueueMutex = new Object(); - protected WriteBatch nextWriteBatch; - + protected WriteBatch nextWriteBatch; + private boolean running; protected boolean shutdown; protected IOException firstAsyncException; protected final CountDownLatch shutdownDone = new CountDownLatch(1); - private Thread thread; - + private Thread thread; + /** * Construct a Store writer * * @param fileId */ - public DataFileAppender(AsyncDataManager dataManager){ - this.dataManager=dataManager; + public DataFileAppender(AsyncDataManager dataManager) { + this.dataManager = dataManager; this.inflightWrites = this.dataManager.getInflightWrites(); } - + /** - * @param type + * @param type * @param marshaller * @param payload - * @param type - * @param sync + * @param type + * @param sync * @return * @throws IOException - * @throws - * @throws + * @throws + * @throws */ public Location storeItem(ByteSequence data, byte type, boolean sync) throws IOException { - - // Write the packet our internal buffer. - int size = data.getLength()+AsyncDataManager.ITEM_HEAD_FOOT_SPACE; - - final Location location=new Location(); - location.setSize(size); - location.setType(type); - - WriteBatch batch; - WriteCommand write = new WriteCommand(location, data, sync); - // Locate datafile and enqueue into the executor in sychronized block so that - // writes get equeued onto the executor in order that they were assigned by + // Write the packet our internal buffer. + int size = data.getLength() + AsyncDataManager.ITEM_HEAD_FOOT_SPACE; + + final Location location = new Location(); + location.setSize(size); + location.setType(type); + + WriteBatch batch; + WriteCommand write = new WriteCommand(location, data, sync); + + // Locate datafile and enqueue into the executor in sychronized block so + // that + // writes get equeued onto the executor in order that they were assigned + // by // the data manager (which is basically just appending) - - synchronized(this) { + + synchronized (this) { // Find the position where this item will land at. - DataFile dataFile=dataManager.allocateLocation(location); - batch = enqueue(dataFile, write); + DataFile dataFile = dataManager.allocateLocation(location); + batch = enqueue(dataFile, write); } location.setLatch(batch.latch); - if( sync ) { - try { - batch.latch.await(); - } catch (InterruptedException e) { - throw new InterruptedIOException(); - } - } else { + if (sync) { + try { + batch.latch.await(); + } catch (InterruptedException e) { + throw new InterruptedIOException(); + } + } else { inflightWrites.put(new WriteKey(location), write); - } - + } + return location; } private WriteBatch enqueue(DataFile dataFile, WriteCommand write) throws IOException { - synchronized(enqueueMutex) { - WriteBatch rc=null; - if( shutdown ) { - throw new IOException("Async Writter Thread Shutdown"); - } - if( firstAsyncException !=null ) - throw firstAsyncException; - - if( !running ) { - running=true; - thread = new Thread() { - public void run() { - processQueue(); - } - }; - thread.setPriority(Thread.MAX_PRIORITY); - thread.setDaemon(true); - thread.setName("ActiveMQ Data File Writer"); - thread.start(); - } - - if( nextWriteBatch == null ) { - nextWriteBatch = new WriteBatch(dataFile,write); - rc = nextWriteBatch; - enqueueMutex.notify(); - } else { - // Append to current batch if possible.. - if( nextWriteBatch.canAppend(dataFile, write) ) { - nextWriteBatch.append(write); - rc = nextWriteBatch; - } else { - // Otherwise wait for the queuedCommand to be null - try { - while( nextWriteBatch!=null ) { - enqueueMutex.wait(); - } - } catch (InterruptedException e) { - throw new InterruptedIOException(); - } - if( shutdown ) { - throw new IOException("Async Writter Thread Shutdown"); - } - - // Start a new batch. - nextWriteBatch = new WriteBatch(dataFile,write); - rc = nextWriteBatch; - enqueueMutex.notify(); - } - } - return rc; - } - } + synchronized (enqueueMutex) { + WriteBatch rc = null; + if (shutdown) { + throw new IOException("Async Writter Thread Shutdown"); + } + if (firstAsyncException != null) + throw firstAsyncException; + + if (!running) { + running = true; + thread = new Thread() { + public void run() { + processQueue(); + } + }; + thread.setPriority(Thread.MAX_PRIORITY); + thread.setDaemon(true); + thread.setName("ActiveMQ Data File Writer"); + thread.start(); + } + + if (nextWriteBatch == null) { + nextWriteBatch = new WriteBatch(dataFile, write); + rc = nextWriteBatch; + enqueueMutex.notify(); + } else { + // Append to current batch if possible.. + if (nextWriteBatch.canAppend(dataFile, write)) { + nextWriteBatch.append(write); + rc = nextWriteBatch; + } else { + // Otherwise wait for the queuedCommand to be null + try { + while (nextWriteBatch != null) { + enqueueMutex.wait(); + } + } catch (InterruptedException e) { + throw new InterruptedIOException(); + } + if (shutdown) { + throw new IOException("Async Writter Thread Shutdown"); + } + + // Start a new batch. + nextWriteBatch = new WriteBatch(dataFile, write); + rc = nextWriteBatch; + enqueueMutex.notify(); + } + } + return rc; + } + } public void close() throws IOException { - synchronized( enqueueMutex ) { - if( shutdown == false ) { - shutdown = true; - if( running ) { - enqueueMutex.notifyAll(); - } else { - shutdownDone.countDown(); - } - } - } - - try { - shutdownDone.await(); - } catch (InterruptedException e) { - throw new InterruptedIOException(); - } - + synchronized (enqueueMutex) { + if (shutdown == false) { + shutdown = true; + if (running) { + enqueueMutex.notifyAll(); + } else { + shutdownDone.countDown(); + } + } + } + + try { + shutdownDone.await(); + } catch (InterruptedException e) { + throw new InterruptedIOException(); + } + } /** - * The async processing loop that writes to the data files and - * does the force calls. + * The async processing loop that writes to the data files and does the + * force calls. * - * Since the file sync() call is the slowest of all the operations, - * this algorithm tries to 'batch' or group together several file sync() requests - * into a single file sync() call. The batching is accomplished attaching the - * same CountDownLatch instance to every force request in a group. + * Since the file sync() call is the slowest of all the operations, this + * algorithm tries to 'batch' or group together several file sync() requests + * into a single file sync() call. The batching is accomplished attaching + * the same CountDownLatch instance to every force request in a group. * */ protected void processQueue() { - DataFile dataFile=null; - RandomAccessFile file=null; - try { - - DataByteArrayOutputStream buff = new DataByteArrayOutputStream(MAX_WRITE_BATCH_SIZE); - while( true ) { - - Object o = null; + DataFile dataFile = null; + RandomAccessFile file = null; + try { - // Block till we get a command. - synchronized(enqueueMutex) { - while( true ) { - if( shutdown ) { - o = SHUTDOWN_COMMAND; - break; - } - if( nextWriteBatch!=null ) { - o = nextWriteBatch; - nextWriteBatch=null; - break; - } - enqueueMutex.wait(); - } - enqueueMutex.notify(); - } - - - if( o == SHUTDOWN_COMMAND ) { - break; - } - - WriteBatch wb = (WriteBatch) o; - if( dataFile != wb.dataFile ) { - if( file!=null ) { - dataFile.closeRandomAccessFile(file); - } - dataFile = wb.dataFile; - file = dataFile.openRandomAccessFile(true); - } - - WriteCommand write = wb.first; - - // Write all the data. - // Only need to seek to first location.. all others - // are in sequence. - file.seek(write.location.getOffset()); - - // - // is it just 1 big write? - if( wb.size == write.location.getSize() ) { - - // Just write it directly.. - file.writeInt(write.location.getSize()); - file.writeByte(write.location.getType()); - file.write(RESERVED_SPACE); - file.write(AsyncDataManager.ITEM_HEAD_SOR); - file.write(write.data.getData(),write.data.getOffset(), write.data.getLength()); - file.write(AsyncDataManager.ITEM_HEAD_EOR); - - } else { - - // Combine the smaller writes into 1 big buffer - while( write!=null ) { - - buff.writeInt(write.location.getSize()); - buff.writeByte(write.location.getType()); - buff.write(RESERVED_SPACE); - buff.write(AsyncDataManager.ITEM_HEAD_SOR); - buff.write(write.data.getData(),write.data.getOffset(), write.data.getLength()); - buff.write(AsyncDataManager.ITEM_HEAD_EOR); - - write = (WriteCommand) write.getNext(); - } - - // Now do the 1 big write. - ByteSequence sequence = buff.toByteSequence(); - file.write(sequence.getData(), sequence.getOffset(), sequence.getLength()); - buff.reset(); - } - - file.getFD().sync(); - - WriteCommand lastWrite = (WriteCommand) wb.first.getTailNode(); - dataManager.setLastAppendLocation( lastWrite.location ); - - // Signal any waiting threads that the write is on disk. - wb.latch.countDown(); - - // Now that the data is on disk, remove the writes from the in flight - // cache. - write = wb.first; - while( write!=null ) { - if( !write.sync ) { - inflightWrites.remove(new WriteKey(write.location)); - } - write = (WriteCommand) write.getNext(); - } - } - buff.close(); - } catch (IOException e) { - synchronized( enqueueMutex ) { - firstAsyncException = e; - } - } catch (InterruptedException e) { - } finally { - try { - if( file!=null ) { - dataFile.closeRandomAccessFile(file); - } - } catch (IOException e) { - } - shutdownDone.countDown(); - } + DataByteArrayOutputStream buff = new DataByteArrayOutputStream(MAX_WRITE_BATCH_SIZE); + while (true) { + + Object o = null; + + // Block till we get a command. + synchronized (enqueueMutex) { + while (true) { + if (shutdown) { + o = SHUTDOWN_COMMAND; + break; + } + if (nextWriteBatch != null) { + o = nextWriteBatch; + nextWriteBatch = null; + break; + } + enqueueMutex.wait(); + } + enqueueMutex.notify(); + } + + if (o == SHUTDOWN_COMMAND) { + break; + } + + WriteBatch wb = (WriteBatch)o; + if (dataFile != wb.dataFile) { + if (file != null) { + dataFile.closeRandomAccessFile(file); + } + dataFile = wb.dataFile; + file = dataFile.openRandomAccessFile(true); + } + + WriteCommand write = wb.first; + + // Write all the data. + // Only need to seek to first location.. all others + // are in sequence. + file.seek(write.location.getOffset()); + + // + // is it just 1 big write? + if (wb.size == write.location.getSize()) { + + // Just write it directly.. + file.writeInt(write.location.getSize()); + file.writeByte(write.location.getType()); + file.write(RESERVED_SPACE); + file.write(AsyncDataManager.ITEM_HEAD_SOR); + file.write(write.data.getData(), write.data.getOffset(), write.data.getLength()); + file.write(AsyncDataManager.ITEM_HEAD_EOR); + + } else { + + // Combine the smaller writes into 1 big buffer + while (write != null) { + + buff.writeInt(write.location.getSize()); + buff.writeByte(write.location.getType()); + buff.write(RESERVED_SPACE); + buff.write(AsyncDataManager.ITEM_HEAD_SOR); + buff.write(write.data.getData(), write.data.getOffset(), write.data.getLength()); + buff.write(AsyncDataManager.ITEM_HEAD_EOR); + + write = (WriteCommand)write.getNext(); + } + + // Now do the 1 big write. + ByteSequence sequence = buff.toByteSequence(); + file.write(sequence.getData(), sequence.getOffset(), sequence.getLength()); + buff.reset(); + } + + file.getFD().sync(); + + WriteCommand lastWrite = (WriteCommand)wb.first.getTailNode(); + dataManager.setLastAppendLocation(lastWrite.location); + + // Signal any waiting threads that the write is on disk. + wb.latch.countDown(); + + // Now that the data is on disk, remove the writes from the in + // flight + // cache. + write = wb.first; + while (write != null) { + if (!write.sync) { + inflightWrites.remove(new WriteKey(write.location)); + } + write = (WriteCommand)write.getNext(); + } + } + buff.close(); + } catch (IOException e) { + synchronized (enqueueMutex) { + firstAsyncException = e; + } + } catch (InterruptedException e) { + } finally { + try { + if (file != null) { + dataFile.closeRandomAccessFile(file); + } + } catch (IOException e) { + } + shutdownDone.countDown(); + } } - + } diff --git a/activemq-core/src/main/java/org/apache/activemq/kaha/impl/async/DataManagerFacade.java b/activemq-core/src/main/java/org/apache/activemq/kaha/impl/async/DataManagerFacade.java index d916757d9c..0107d7cd30 100644 --- a/activemq-core/src/main/java/org/apache/activemq/kaha/impl/async/DataManagerFacade.java +++ b/activemq-core/src/main/java/org/apache/activemq/kaha/impl/async/DataManagerFacade.java @@ -32,125 +32,124 @@ import org.apache.activemq.util.DataByteArrayOutputStream; */ public final class DataManagerFacade implements org.apache.activemq.kaha.impl.DataManager { - private static class StoreLocationFacade implements StoreLocation { - private final Location location; + private static class StoreLocationFacade implements StoreLocation { + private final Location location; - public StoreLocationFacade(Location location) { - this.location = location; - } + public StoreLocationFacade(Location location) { + this.location = location; + } - public int getFile() { - return location.getDataFileId(); - } + public int getFile() { + return location.getDataFileId(); + } - public long getOffset() { - return location.getOffset(); - } + public long getOffset() { + return location.getOffset(); + } - public int getSize() { - return location.getSize(); - } + public int getSize() { + return location.getSize(); + } - public Location getLocation() { - return location; - } - } + public Location getLocation() { + return location; + } + } - static private StoreLocation convertToStoreLocation(Location location) { - if(location==null) - return null; - return new StoreLocationFacade(location); - } - - static private Location convertFromStoreLocation(StoreLocation location) { - - if(location==null) - return null; - - if( location.getClass()== StoreLocationFacade.class ) - return ((StoreLocationFacade)location).getLocation(); - - Location l = new Location(); - l.setOffset((int) location.getOffset()); - l.setSize(location.getSize()); - l.setDataFileId(location.getFile()); - return l; - } + static private StoreLocation convertToStoreLocation(Location location) { + if (location == null) + return null; + return new StoreLocationFacade(location); + } - static final private ByteSequence FORCE_COMMAND = new ByteSequence(new byte[]{'F', 'O', 'R', 'C', 'E'}); - - AsyncDataManager dataManager; - private final String name; - private Marshaller redoMarshaller; - - - public DataManagerFacade(AsyncDataManager dataManager, String name) { - this.dataManager=dataManager; - this.name = name; - } - - public Object readItem(Marshaller marshaller, StoreLocation location) throws IOException { - ByteSequence sequence = dataManager.read(convertFromStoreLocation(location)); - DataByteArrayInputStream dataIn = new DataByteArrayInputStream(sequence); + static private Location convertFromStoreLocation(StoreLocation location) { + + if (location == null) + return null; + + if (location.getClass() == StoreLocationFacade.class) + return ((StoreLocationFacade)location).getLocation(); + + Location l = new Location(); + l.setOffset((int)location.getOffset()); + l.setSize(location.getSize()); + l.setDataFileId(location.getFile()); + return l; + } + + static final private ByteSequence FORCE_COMMAND = new ByteSequence(new byte[] {'F', 'O', 'R', 'C', 'E'}); + + AsyncDataManager dataManager; + private final String name; + private Marshaller redoMarshaller; + + public DataManagerFacade(AsyncDataManager dataManager, String name) { + this.dataManager = dataManager; + this.name = name; + } + + public Object readItem(Marshaller marshaller, StoreLocation location) throws IOException { + ByteSequence sequence = dataManager.read(convertFromStoreLocation(location)); + DataByteArrayInputStream dataIn = new DataByteArrayInputStream(sequence); return marshaller.readPayload(dataIn); - } + } + public StoreLocation storeDataItem(Marshaller marshaller, Object payload) throws IOException { + final DataByteArrayOutputStream buffer = new DataByteArrayOutputStream(); + marshaller.writePayload(payload, buffer); + ByteSequence data = buffer.toByteSequence(); + return convertToStoreLocation(dataManager.write(data, (byte)1, false)); + } - public StoreLocation storeDataItem(Marshaller marshaller, Object payload) throws IOException { - final DataByteArrayOutputStream buffer = new DataByteArrayOutputStream(); - marshaller.writePayload(payload,buffer); - ByteSequence data = buffer.toByteSequence(); - return convertToStoreLocation(dataManager.write(data, (byte)1, false)); - } + public void force() throws IOException { + dataManager.write(FORCE_COMMAND, (byte)2, true); + } + public void updateItem(StoreLocation location, Marshaller marshaller, Object payload) throws IOException { + final DataByteArrayOutputStream buffer = new DataByteArrayOutputStream(); + marshaller.writePayload(payload, buffer); + ByteSequence data = buffer.toByteSequence(); + dataManager.update(convertFromStoreLocation(location), data, false); + } - public void force() throws IOException { - dataManager.write(FORCE_COMMAND, (byte)2, true); - } + public void close() throws IOException { + dataManager.close(); + } - public void updateItem(StoreLocation location, Marshaller marshaller, Object payload) throws IOException { - final DataByteArrayOutputStream buffer = new DataByteArrayOutputStream(); - marshaller.writePayload(payload,buffer); - ByteSequence data = buffer.toByteSequence(); - dataManager.update(convertFromStoreLocation(location), data, false); - } - - public void close() throws IOException { - dataManager.close(); - } + public void consolidateDataFiles() throws IOException { + dataManager.consolidateDataFiles(); + } - public void consolidateDataFiles() throws IOException { - dataManager.consolidateDataFiles(); - } + public boolean delete() throws IOException { + return dataManager.delete(); + } - public boolean delete() throws IOException { - return dataManager.delete(); - } - - public void addInterestInFile(int file) throws IOException { - dataManager.addInterestInFile(file); - } - public void removeInterestInFile(int file) throws IOException { - dataManager.removeInterestInFile(file); - } + public void addInterestInFile(int file) throws IOException { + dataManager.addInterestInFile(file); + } - public void recoverRedoItems(RedoListener listener) throws IOException { - throw new RuntimeException("Not Implemented.."); - } - public StoreLocation storeRedoItem(Object payload) throws IOException { - throw new RuntimeException("Not Implemented.."); - } + public void removeInterestInFile(int file) throws IOException { + dataManager.removeInterestInFile(file); + } - public Marshaller getRedoMarshaller() { - return redoMarshaller; - } - public void setRedoMarshaller(Marshaller redoMarshaller) { - this.redoMarshaller = redoMarshaller; - } + public void recoverRedoItems(RedoListener listener) throws IOException { + throw new RuntimeException("Not Implemented.."); + } - public String getName() { - return name; - } + public StoreLocation storeRedoItem(Object payload) throws IOException { + throw new RuntimeException("Not Implemented.."); + } + + public Marshaller getRedoMarshaller() { + return redoMarshaller; + } + + public void setRedoMarshaller(Marshaller redoMarshaller) { + this.redoMarshaller = redoMarshaller; + } + + public String getName() { + return name; + } - } diff --git a/activemq-core/src/main/java/org/apache/activemq/kaha/impl/async/JournalFacade.java b/activemq-core/src/main/java/org/apache/activemq/kaha/impl/async/JournalFacade.java index 841f553cab..b93aa268ab 100644 --- a/activemq-core/src/main/java/org/apache/activemq/kaha/impl/async/JournalFacade.java +++ b/activemq-core/src/main/java/org/apache/activemq/kaha/impl/async/JournalFacade.java @@ -33,75 +33,77 @@ import org.apache.activemq.util.ByteSequence; */ public final class JournalFacade implements Journal { - - public static class RecordLocationFacade implements RecordLocation { - private final Location location; + public static class RecordLocationFacade implements RecordLocation { + private final Location location; - public RecordLocationFacade(Location location) { - this.location = location; - } + public RecordLocationFacade(Location location) { + this.location = location; + } - public Location getLocation() { - return location; - } + public Location getLocation() { + return location; + } - public int compareTo(Object o) { - RecordLocationFacade rlf = (RecordLocationFacade)o; - int rc = location.compareTo(rlf.location); - return rc; - } - } + public int compareTo(Object o) { + RecordLocationFacade rlf = (RecordLocationFacade)o; + int rc = location.compareTo(rlf.location); + return rc; + } + } - static private RecordLocation convertToRecordLocation(Location location) { - if(location==null) - return null; - return new RecordLocationFacade(location); - } - - static private Location convertFromRecordLocation(RecordLocation location) { - - if(location==null) - return null; - - return ((RecordLocationFacade)location).getLocation(); - } + static private RecordLocation convertToRecordLocation(Location location) { + if (location == null) + return null; + return new RecordLocationFacade(location); + } - AsyncDataManager dataManager; - - public JournalFacade(AsyncDataManager dataManager) { - this.dataManager = dataManager; - } + static private Location convertFromRecordLocation(RecordLocation location) { - public void close() throws IOException { - dataManager.close(); - } + if (location == null) + return null; - public RecordLocation getMark() throws IllegalStateException { - return convertToRecordLocation(dataManager.getMark()); - } + return ((RecordLocationFacade)location).getLocation(); + } - public RecordLocation getNextRecordLocation(RecordLocation location) throws InvalidRecordLocationException, IOException, IllegalStateException { - return convertToRecordLocation(dataManager.getNextLocation(convertFromRecordLocation(location))); - } + AsyncDataManager dataManager; - public Packet read(RecordLocation location) throws InvalidRecordLocationException, IOException, IllegalStateException { - ByteSequence rc = dataManager.read(convertFromRecordLocation(location)); - if( rc == null ) - return null; - return new ByteArrayPacket(rc.getData(), rc.getOffset(), rc.getLength()); - } + public JournalFacade(AsyncDataManager dataManager) { + this.dataManager = dataManager; + } - public void setJournalEventListener(JournalEventListener listener) throws IllegalStateException { - } + public void close() throws IOException { + dataManager.close(); + } - public void setMark(RecordLocation location, boolean sync) throws InvalidRecordLocationException, IOException, IllegalStateException { - dataManager.setMark(convertFromRecordLocation(location), sync); - } + public RecordLocation getMark() throws IllegalStateException { + return convertToRecordLocation(dataManager.getMark()); + } + + public RecordLocation getNextRecordLocation(RecordLocation location) + throws InvalidRecordLocationException, IOException, IllegalStateException { + return convertToRecordLocation(dataManager.getNextLocation(convertFromRecordLocation(location))); + } + + public Packet read(RecordLocation location) throws InvalidRecordLocationException, IOException, + IllegalStateException { + ByteSequence rc = dataManager.read(convertFromRecordLocation(location)); + if (rc == null) + return null; + return new ByteArrayPacket(rc.getData(), rc.getOffset(), rc.getLength()); + } + + public void setJournalEventListener(JournalEventListener listener) throws IllegalStateException { + } + + public void setMark(RecordLocation location, boolean sync) throws InvalidRecordLocationException, + IOException, IllegalStateException { + dataManager.setMark(convertFromRecordLocation(location), sync); + } + + public RecordLocation write(Packet packet, boolean sync) throws IOException, IllegalStateException { + org.apache.activeio.packet.ByteSequence data = packet.asByteSequence(); + ByteSequence sequence = new ByteSequence(data.getData(), data.getOffset(), data.getLength()); + return convertToRecordLocation(dataManager.write(sequence, sync)); + } - public RecordLocation write(Packet packet, boolean sync) throws IOException, IllegalStateException { - org.apache.activeio.packet.ByteSequence data = packet.asByteSequence(); - ByteSequence sequence = new ByteSequence(data.getData(), data.getOffset(), data.getLength()); - return convertToRecordLocation(dataManager.write(sequence, sync)); - } - } diff --git a/activemq-core/src/main/java/org/apache/activemq/kaha/impl/async/Location.java b/activemq-core/src/main/java/org/apache/activemq/kaha/impl/async/Location.java index 73ca704656..d024c1a297 100755 --- a/activemq-core/src/main/java/org/apache/activemq/kaha/impl/async/Location.java +++ b/activemq-core/src/main/java/org/apache/activemq/kaha/impl/async/Location.java @@ -27,121 +27,124 @@ import java.util.concurrent.CountDownLatch; * @version $Revision: 1.2 $ */ public final class Location implements Comparable { - - public static final byte MARK_TYPE=-1; - public static final byte USER_TYPE=1; - public static final byte NOT_SET_TYPE=0; - public static final int NOT_SET=-1; - private int dataFileId=NOT_SET; - private int offset=NOT_SET; - private int size=NOT_SET; - private byte type=NOT_SET_TYPE; + public static final byte MARK_TYPE = -1; + public static final byte USER_TYPE = 1; + public static final byte NOT_SET_TYPE = 0; + public static final int NOT_SET = -1; + + private int dataFileId = NOT_SET; + private int offset = NOT_SET; + private int size = NOT_SET; + private byte type = NOT_SET_TYPE; private CountDownLatch latch; - public Location(){} - + public Location() { + } + Location(Location item) { this.dataFileId = item.dataFileId; this.offset = item.offset; this.size = item.size; this.type = item.type; } - - boolean isValid(){ + + boolean isValid() { return dataFileId != NOT_SET; } /** * @return the size of the data record including the header. */ - public int getSize(){ + public int getSize() { return size; } /** * @param size the size of the data record including the header. */ - public void setSize(int size){ - this.size=size; + public void setSize(int size) { + this.size = size; } /** * @return the size of the payload of the record. */ public int getPaylodSize() { - return size-AsyncDataManager.ITEM_HEAD_FOOT_SPACE; - } - - public int getOffset(){ - return offset; - } - public void setOffset(int offset){ - this.offset=offset; + return size - AsyncDataManager.ITEM_HEAD_FOOT_SPACE; } - public int getDataFileId(){ + public int getOffset() { + return offset; + } + + public void setOffset(int offset) { + this.offset = offset; + } + + public int getDataFileId() { return dataFileId; } - public void setDataFileId(int file){ - this.dataFileId=file; + public void setDataFileId(int file) { + this.dataFileId = file; } - public byte getType() { - return type; - } + public byte getType() { + return type; + } - public void setType(byte type) { - this.type = type; - } + public void setType(byte type) { + this.type = type; + } - public String toString(){ - String result="offset = "+offset+", file = " + dataFileId + ", size = "+size + ", type = "+type; + public String toString() { + String result = "offset = " + offset + ", file = " + dataFileId + ", size = " + size + ", type = " + + type; return result; } - public void writeExternal(DataOutput dos) throws IOException { - dos.writeInt(dataFileId); - dos.writeInt(offset); - dos.writeInt(size); - dos.writeByte(type); - } + public void writeExternal(DataOutput dos) throws IOException { + dos.writeInt(dataFileId); + dos.writeInt(offset); + dos.writeInt(size); + dos.writeByte(type); + } - public void readExternal(DataInput dis) throws IOException { - dataFileId = dis.readInt(); - offset = dis.readInt(); - size = dis.readInt(); - type = dis.readByte(); - } + public void readExternal(DataInput dis) throws IOException { + dataFileId = dis.readInt(); + offset = dis.readInt(); + size = dis.readInt(); + type = dis.readByte(); + } - public CountDownLatch getLatch() { - return latch; - } - public void setLatch(CountDownLatch latch) { - this.latch = latch; - } + public CountDownLatch getLatch() { + return latch; + } + + public void setLatch(CountDownLatch latch) { + this.latch = latch; + } + + public int compareTo(Location o) { + Location l = (Location)o; + if (dataFileId == l.dataFileId) { + int rc = offset - l.offset; + return rc; + } + return dataFileId - l.dataFileId; + } - public int compareTo(Location o) { - Location l = (Location)o; - if( dataFileId == l.dataFileId ) { - int rc = offset-l.offset; - return rc; - } - return dataFileId - l.dataFileId; - } - public boolean equals(Object o) { boolean result = false; if (o instanceof Location) { - result = compareTo((Location)o)==0; + result = compareTo((Location)o) == 0; } return result; } - + public int hashCode() { return dataFileId ^ offset; } - } diff --git a/activemq-core/src/main/java/org/apache/activemq/kaha/impl/async/NIODataFileAppender.java b/activemq-core/src/main/java/org/apache/activemq/kaha/impl/async/NIODataFileAppender.java index b9a5069008..3fa96168f9 100644 --- a/activemq-core/src/main/java/org/apache/activemq/kaha/impl/async/NIODataFileAppender.java +++ b/activemq-core/src/main/java/org/apache/activemq/kaha/impl/async/NIODataFileAppender.java @@ -22,191 +22,194 @@ import java.nio.ByteBuffer; import java.nio.channels.FileChannel; /** - * An AsyncDataFileAppender that uses NIO ByteBuffers and File chanels to more efficently - * copy data to files. + * An AsyncDataFileAppender that uses NIO ByteBuffers and File chanels to more + * efficently copy data to files. * * @version $Revision: 1.1.1.1 $ */ class NIODataFileAppender extends DataFileAppender { - - public NIODataFileAppender(AsyncDataManager fileManager) { - super(fileManager); - } - /** - * The async processing loop that writes to the data files and - * does the force calls. + public NIODataFileAppender(AsyncDataManager fileManager) { + super(fileManager); + } + + /** + * The async processing loop that writes to the data files and does the + * force calls. * - * Since the file sync() call is the slowest of all the operations, - * this algorithm tries to 'batch' or group together several file sync() requests - * into a single file sync() call. The batching is accomplished attaching the - * same CountDownLatch instance to every force request in a group. + * Since the file sync() call is the slowest of all the operations, this + * algorithm tries to 'batch' or group together several file sync() requests + * into a single file sync() call. The batching is accomplished attaching + * the same CountDownLatch instance to every force request in a group. * */ protected void processQueue() { - DataFile dataFile=null; - RandomAccessFile file=null; - FileChannel channel=null; + DataFile dataFile = null; + RandomAccessFile file = null; + FileChannel channel = null; - try { - - ByteBuffer header = ByteBuffer.allocateDirect(AsyncDataManager.ITEM_HEAD_SPACE); - ByteBuffer footer = ByteBuffer.allocateDirect(AsyncDataManager.ITEM_FOOT_SPACE); - ByteBuffer buffer = ByteBuffer.allocateDirect(MAX_WRITE_BATCH_SIZE); - - // Populate the static parts of the headers and footers.. - header.putInt(0); // size - header.put((byte) 0); // type - header.put(RESERVED_SPACE); // reserved - header.put(AsyncDataManager.ITEM_HEAD_SOR); - footer.put(AsyncDataManager.ITEM_HEAD_EOR); - - while( true ) { - - Object o = null; + try { - // Block till we get a command. - synchronized(enqueueMutex) { - while( true ) { - if( shutdown ) { - o = SHUTDOWN_COMMAND; - break; - } - if( nextWriteBatch!=null ) { - o = nextWriteBatch; - nextWriteBatch=null; - break; - } - enqueueMutex.wait(); - } - enqueueMutex.notify(); - } - - - if( o == SHUTDOWN_COMMAND ) { - break; - } - - WriteBatch wb = (WriteBatch) o; - if( dataFile != wb.dataFile ) { - if( file!=null ) { - dataFile.closeRandomAccessFile(file); - } - dataFile = wb.dataFile; - file = dataFile.openRandomAccessFile(true); - channel = file.getChannel(); - } - - WriteCommand write = wb.first; - - // Write all the data. - // Only need to seek to first location.. all others - // are in sequence. - file.seek(write.location.getOffset()); - - // - // is it just 1 big write? - if( wb.size == write.location.getSize() ) { - - header.clear(); - header.putInt(write.location.getSize()); - header.put(write.location.getType()); - header.clear(); - transfer(header, channel); - ByteBuffer source = ByteBuffer.wrap(write.data.getData(), write.data.getOffset(), write.data.getLength()); - transfer(source, channel); - footer.clear(); - transfer(footer, channel); - - } else { - - // Combine the smaller writes into 1 big buffer - while( write!=null ) { - - header.clear(); - header.putInt(write.location.getSize()); - header.put(write.location.getType()); - header.clear(); - copy(header, buffer); - assert !header.hasRemaining(); - - ByteBuffer source = ByteBuffer.wrap(write.data.getData(), write.data.getOffset(), write.data.getLength()); - copy(source, buffer); - assert !source.hasRemaining(); + ByteBuffer header = ByteBuffer.allocateDirect(AsyncDataManager.ITEM_HEAD_SPACE); + ByteBuffer footer = ByteBuffer.allocateDirect(AsyncDataManager.ITEM_FOOT_SPACE); + ByteBuffer buffer = ByteBuffer.allocateDirect(MAX_WRITE_BATCH_SIZE); - footer.clear(); - copy(footer, buffer); - assert !footer.hasRemaining(); - - write = (WriteCommand) write.getNext(); - } - - // Fully write out the buffer.. - buffer.flip(); - transfer(buffer, channel); - buffer.clear(); - } - - file.getChannel().force(false); + // Populate the static parts of the headers and footers.. + header.putInt(0); // size + header.put((byte)0); // type + header.put(RESERVED_SPACE); // reserved + header.put(AsyncDataManager.ITEM_HEAD_SOR); + footer.put(AsyncDataManager.ITEM_HEAD_EOR); - WriteCommand lastWrite = (WriteCommand) wb.first.getTailNode(); - dataManager.setLastAppendLocation( lastWrite.location ); + while (true) { - // Signal any waiting threads that the write is on disk. - if( wb.latch!=null ) { - wb.latch.countDown(); - } - - // Now that the data is on disk, remove the writes from the in flight - // cache. - write = wb.first; - while( write!=null ) { - if( !write.sync ) { - inflightWrites.remove(new WriteKey(write.location)); - } - write = (WriteCommand) write.getNext(); - } - } - - } catch (IOException e) { - synchronized( enqueueMutex ) { - firstAsyncException = e; - } - } catch (InterruptedException e) { - } finally { - try { - if( file!=null ) { - dataFile.closeRandomAccessFile(file); - } - } catch (IOException e) { - } - shutdownDone.countDown(); - } + Object o = null; + + // Block till we get a command. + synchronized (enqueueMutex) { + while (true) { + if (shutdown) { + o = SHUTDOWN_COMMAND; + break; + } + if (nextWriteBatch != null) { + o = nextWriteBatch; + nextWriteBatch = null; + break; + } + enqueueMutex.wait(); + } + enqueueMutex.notify(); + } + + if (o == SHUTDOWN_COMMAND) { + break; + } + + WriteBatch wb = (WriteBatch)o; + if (dataFile != wb.dataFile) { + if (file != null) { + dataFile.closeRandomAccessFile(file); + } + dataFile = wb.dataFile; + file = dataFile.openRandomAccessFile(true); + channel = file.getChannel(); + } + + WriteCommand write = wb.first; + + // Write all the data. + // Only need to seek to first location.. all others + // are in sequence. + file.seek(write.location.getOffset()); + + // + // is it just 1 big write? + if (wb.size == write.location.getSize()) { + + header.clear(); + header.putInt(write.location.getSize()); + header.put(write.location.getType()); + header.clear(); + transfer(header, channel); + ByteBuffer source = ByteBuffer.wrap(write.data.getData(), write.data.getOffset(), + write.data.getLength()); + transfer(source, channel); + footer.clear(); + transfer(footer, channel); + + } else { + + // Combine the smaller writes into 1 big buffer + while (write != null) { + + header.clear(); + header.putInt(write.location.getSize()); + header.put(write.location.getType()); + header.clear(); + copy(header, buffer); + assert !header.hasRemaining(); + + ByteBuffer source = ByteBuffer.wrap(write.data.getData(), write.data.getOffset(), + write.data.getLength()); + copy(source, buffer); + assert !source.hasRemaining(); + + footer.clear(); + copy(footer, buffer); + assert !footer.hasRemaining(); + + write = (WriteCommand)write.getNext(); + } + + // Fully write out the buffer.. + buffer.flip(); + transfer(buffer, channel); + buffer.clear(); + } + + file.getChannel().force(false); + + WriteCommand lastWrite = (WriteCommand)wb.first.getTailNode(); + dataManager.setLastAppendLocation(lastWrite.location); + + // Signal any waiting threads that the write is on disk. + if (wb.latch != null) { + wb.latch.countDown(); + } + + // Now that the data is on disk, remove the writes from the in + // flight + // cache. + write = wb.first; + while (write != null) { + if (!write.sync) { + inflightWrites.remove(new WriteKey(write.location)); + } + write = (WriteCommand)write.getNext(); + } + } + + } catch (IOException e) { + synchronized (enqueueMutex) { + firstAsyncException = e; + } + } catch (InterruptedException e) { + } finally { + try { + if (file != null) { + dataFile.closeRandomAccessFile(file); + } + } catch (IOException e) { + } + shutdownDone.countDown(); + } } /** * Copy the bytes in header to the channel. + * * @param header - source of data * @param channel - destination where the data will be written. * @throws IOException */ - private void transfer(ByteBuffer header, FileChannel channel) throws IOException { - while (header.hasRemaining()) { - channel.write(header); - } - } + private void transfer(ByteBuffer header, FileChannel channel) throws IOException { + while (header.hasRemaining()) { + channel.write(header); + } + } - private int copy(ByteBuffer src, ByteBuffer dest) { - int rc = Math.min(dest.remaining(), src.remaining()); - if( rc > 0 ) { - // Adjust our limit so that we don't overflow the dest buffer. - int limit = src.limit(); - src.limit(src.position()+rc); + private int copy(ByteBuffer src, ByteBuffer dest) { + int rc = Math.min(dest.remaining(), src.remaining()); + if (rc > 0) { + // Adjust our limit so that we don't overflow the dest buffer. + int limit = src.limit(); + src.limit(src.position() + rc); dest.put(src); // restore the limit. - src.limit(limit); - } - return rc; - } - + src.limit(limit); + } + return rc; + } + } diff --git a/activemq-core/src/main/java/org/apache/activemq/kaha/impl/container/ContainerEntrySet.java b/activemq-core/src/main/java/org/apache/activemq/kaha/impl/container/ContainerEntrySet.java index 2227700b3a..67c1527a97 100644 --- a/activemq-core/src/main/java/org/apache/activemq/kaha/impl/container/ContainerEntrySet.java +++ b/activemq-core/src/main/java/org/apache/activemq/kaha/impl/container/ContainerEntrySet.java @@ -24,85 +24,85 @@ import java.util.List; import java.util.Set; /** -* Set of Map.Entry objects for a container -* -* @version $Revision: 1.2 $ -*/ -public class ContainerEntrySet extends ContainerCollectionSupport implements Set{ - ContainerEntrySet(MapContainerImpl container){ + * Set of Map.Entry objects for a container + * + * @version $Revision: 1.2 $ + */ +public class ContainerEntrySet extends ContainerCollectionSupport implements Set { + ContainerEntrySet(MapContainerImpl container) { super(container); } - public boolean contains(Object o){ + public boolean contains(Object o) { return container.entrySet().contains(o); } - public Iterator iterator(){ - return new ContainerEntrySetIterator(container,buildEntrySet().iterator()); + public Iterator iterator() { + return new ContainerEntrySetIterator(container, buildEntrySet().iterator()); } - public Object[] toArray(){ + public Object[] toArray() { return buildEntrySet().toArray(); } - public Object[] toArray(Object[] a){ + public Object[] toArray(Object[] a) { return buildEntrySet().toArray(a); } - public boolean add(Object o){ + public boolean add(Object o) { throw new UnsupportedOperationException("Cannot add here"); } - public boolean remove(Object o){ - boolean result=false; - if(buildEntrySet().remove(o)){ - ContainerMapEntry entry=(ContainerMapEntry) o; + public boolean remove(Object o) { + boolean result = false; + if (buildEntrySet().remove(o)) { + ContainerMapEntry entry = (ContainerMapEntry)o; container.remove(entry.getKey()); } return result; } - public boolean containsAll(Collection c){ + public boolean containsAll(Collection c) { return buildEntrySet().containsAll(c); } - public boolean addAll(Collection c){ + public boolean addAll(Collection c) { throw new UnsupportedOperationException("Cannot add here"); } - public boolean retainAll(Collection c){ - List tmpList=new ArrayList(); - for(Iterator i=c.iterator();i.hasNext();){ - Object o=i.next(); - if(!contains(o)){ + public boolean retainAll(Collection c) { + List tmpList = new ArrayList(); + for (Iterator i = c.iterator(); i.hasNext();) { + Object o = i.next(); + if (!contains(o)) { tmpList.add(o); } } - boolean result=false; - for(Iterator i=tmpList.iterator();i.hasNext();){ - result|=remove(i.next()); + boolean result = false; + for (Iterator i = tmpList.iterator(); i.hasNext();) { + result |= remove(i.next()); } return result; } - public boolean removeAll(Collection c){ - boolean result=true; - for(Iterator i=c.iterator();i.hasNext();){ - if(!remove(i.next())){ - result=false; + public boolean removeAll(Collection c) { + boolean result = true; + for (Iterator i = c.iterator(); i.hasNext();) { + if (!remove(i.next())) { + result = false; } } return result; } - public void clear(){ + public void clear() { container.clear(); } - protected Set buildEntrySet(){ - Set set=new HashSet(); - for(Iterator i=container.keySet().iterator();i.hasNext();){ - ContainerMapEntry entry=new ContainerMapEntry(container,i.next()); + protected Set buildEntrySet() { + Set set = new HashSet(); + for (Iterator i = container.keySet().iterator(); i.hasNext();) { + ContainerMapEntry entry = new ContainerMapEntry(container, i.next()); set.add(entry); } return set; diff --git a/activemq-core/src/main/java/org/apache/activemq/kaha/impl/container/ContainerEntrySetIterator.java b/activemq-core/src/main/java/org/apache/activemq/kaha/impl/container/ContainerEntrySetIterator.java index cb4ae97289..40a476393f 100644 --- a/activemq-core/src/main/java/org/apache/activemq/kaha/impl/container/ContainerEntrySetIterator.java +++ b/activemq-core/src/main/java/org/apache/activemq/kaha/impl/container/ContainerEntrySetIterator.java @@ -18,33 +18,33 @@ package org.apache.activemq.kaha.impl.container; import java.util.Iterator; - /** -* An Iterator for a container entry Set -* -* @version $Revision: 1.2 $ -*/ -public class ContainerEntrySetIterator implements Iterator{ + * An Iterator for a container entry Set + * + * @version $Revision: 1.2 $ + */ +public class ContainerEntrySetIterator implements Iterator { private MapContainerImpl container; - private Iterator iter; + private Iterator iter; private ContainerMapEntry currentEntry; - ContainerEntrySetIterator(MapContainerImpl container,Iterator iter){ + + ContainerEntrySetIterator(MapContainerImpl container, Iterator iter) { this.container = container; this.iter = iter; } - - public boolean hasNext(){ + + public boolean hasNext() { return iter.hasNext(); } - public Object next(){ - currentEntry = (ContainerMapEntry) iter.next(); + public Object next() { + currentEntry = (ContainerMapEntry)iter.next(); return currentEntry; } - public void remove(){ - if (currentEntry != null){ - container.remove(currentEntry.getKey()); - } + public void remove() { + if (currentEntry != null) { + container.remove(currentEntry.getKey()); + } } } diff --git a/activemq-core/src/main/java/org/apache/activemq/kaha/impl/container/ContainerKeySet.java b/activemq-core/src/main/java/org/apache/activemq/kaha/impl/container/ContainerKeySet.java index 9e97f95474..52b1750f86 100644 --- a/activemq-core/src/main/java/org/apache/activemq/kaha/impl/container/ContainerKeySet.java +++ b/activemq-core/src/main/java/org/apache/activemq/kaha/impl/container/ContainerKeySet.java @@ -25,27 +25,25 @@ import org.apache.activemq.kaha.impl.index.IndexItem; import org.apache.activemq.kaha.impl.index.IndexLinkedList; /** -* A Set of keys for the container -* -* @version $Revision: 1.2 $ -*/ -public class ContainerKeySet extends ContainerCollectionSupport implements Set{ - - - ContainerKeySet(MapContainerImpl container){ + * A Set of keys for the container + * + * @version $Revision: 1.2 $ + */ +public class ContainerKeySet extends ContainerCollectionSupport implements Set { + + ContainerKeySet(MapContainerImpl container) { super(container); } - - - public boolean contains(Object o){ + + public boolean contains(Object o) { return container.containsKey(o); } - public Iterator iterator(){ + public Iterator iterator() { return new ContainerKeySetIterator(container); } - public Object[] toArray(){ + public Object[] toArray() { List list = new ArrayList(); IndexItem item = container.getInternalList().getRoot(); while ((item = container.getInternalList().getNextEntry(item)) != null) { @@ -54,7 +52,7 @@ public class ContainerKeySet extends ContainerCollectionSupport implements Set{ return list.toArray(); } - public Object[] toArray(Object[] a){ + public Object[] toArray(Object[] a) { List list = new ArrayList(); IndexItem item = container.getInternalList().getRoot(); while ((item = container.getInternalList().getNextEntry(item)) != null) { @@ -63,58 +61,58 @@ public class ContainerKeySet extends ContainerCollectionSupport implements Set{ return list.toArray(a); } - public boolean add(Object o){ + public boolean add(Object o) { throw new UnsupportedOperationException("Cannot add here"); } - public boolean remove(Object o){ - return container.remove(o) != null; + public boolean remove(Object o) { + return container.remove(o) != null; } - public boolean containsAll(Collection c){ + public boolean containsAll(Collection c) { boolean result = true; - for (Object key:c) { - if (!(result&=container.containsKey(key))) { + for (Object key : c) { + if (!(result &= container.containsKey(key))) { break; } } - return result; + return result; } - public boolean addAll(Collection c){ + public boolean addAll(Collection c) { throw new UnsupportedOperationException("Cannot add here"); } - public boolean retainAll(Collection c){ + public boolean retainAll(Collection c) { List tmpList = new ArrayList(); - for (Iterator i = c.iterator(); i.hasNext(); ){ + for (Iterator i = c.iterator(); i.hasNext();) { Object o = i.next(); - if (!contains(o)){ + if (!contains(o)) { tmpList.add(o); - } + } } - for(Iterator i = tmpList.iterator(); i.hasNext();){ + for (Iterator i = tmpList.iterator(); i.hasNext();) { remove(i.next()); } return !tmpList.isEmpty(); } - public boolean removeAll(Collection c){ + public boolean removeAll(Collection c) { boolean result = true; - for (Iterator i = c.iterator(); i.hasNext(); ){ - if (!remove(i.next())){ + for (Iterator i = c.iterator(); i.hasNext();) { + if (!remove(i.next())) { result = false; } } return result; } - public void clear(){ - container.clear(); + public void clear() { + container.clear(); } - + public String toString() { - StringBuffer result =new StringBuffer(32); + StringBuffer result = new StringBuffer(32); result.append("ContainerKeySet["); IndexItem item = container.getInternalList().getRoot(); while ((item = container.getInternalList().getNextEntry(item)) != null) { diff --git a/activemq-core/src/main/java/org/apache/activemq/kaha/impl/container/ContainerKeySetIterator.java b/activemq-core/src/main/java/org/apache/activemq/kaha/impl/container/ContainerKeySetIterator.java index 5001331c69..7ddc09cc95 100644 --- a/activemq-core/src/main/java/org/apache/activemq/kaha/impl/container/ContainerKeySetIterator.java +++ b/activemq-core/src/main/java/org/apache/activemq/kaha/impl/container/ContainerKeySetIterator.java @@ -20,38 +20,37 @@ import java.util.Iterator; import org.apache.activemq.kaha.impl.index.IndexItem; import org.apache.activemq.kaha.impl.index.IndexLinkedList; - /** -*Iterator for the set of keys for a container -* -* @version $Revision: 1.2 $ -*/ -public class ContainerKeySetIterator implements Iterator{ + * Iterator for the set of keys for a container + * + * @version $Revision: 1.2 $ + */ +public class ContainerKeySetIterator implements Iterator { private MapContainerImpl container; private IndexLinkedList list; protected IndexItem nextItem; protected IndexItem currentItem; - - ContainerKeySetIterator(MapContainerImpl container){ + + ContainerKeySetIterator(MapContainerImpl container) { this.container = container; - this.list=container.getInternalList(); - this.currentItem=list.getRoot(); - this.nextItem=list.getNextEntry(currentItem); - } - - public boolean hasNext(){ - return nextItem!=null; + this.list = container.getInternalList(); + this.currentItem = list.getRoot(); + this.nextItem = list.getNextEntry(currentItem); } - public Object next(){ - currentItem=nextItem; - Object result=container.getKey(nextItem); - nextItem=list.getNextEntry(nextItem); + public boolean hasNext() { + return nextItem != null; + } + + public Object next() { + currentItem = nextItem; + Object result = container.getKey(nextItem); + nextItem = list.getNextEntry(nextItem); return result; } - public void remove(){ - if(currentItem!=null){ + public void remove() { + if (currentItem != null) { container.remove(currentItem); } } diff --git a/activemq-core/src/main/java/org/apache/activemq/kaha/impl/container/ContainerListIterator.java b/activemq-core/src/main/java/org/apache/activemq/kaha/impl/container/ContainerListIterator.java index 1946eedfaf..194b18afb7 100644 --- a/activemq-core/src/main/java/org/apache/activemq/kaha/impl/container/ContainerListIterator.java +++ b/activemq-core/src/main/java/org/apache/activemq/kaha/impl/container/ContainerListIterator.java @@ -22,10 +22,10 @@ import org.apache.activemq.kaha.impl.index.IndexLinkedList; /** * @version $Revision: 1.2 $ */ -public class ContainerListIterator extends ContainerValueCollectionIterator implements ListIterator{ +public class ContainerListIterator extends ContainerValueCollectionIterator implements ListIterator { - protected ContainerListIterator(ListContainerImpl container,IndexLinkedList list,IndexItem start){ - super(container,list,start); + protected ContainerListIterator(ListContainerImpl container, IndexLinkedList list, IndexItem start) { + super(container, list, start); } /* @@ -33,10 +33,10 @@ public class ContainerListIterator extends ContainerValueCollectionIterator impl * * @see java.util.ListIterator#hasPrevious() */ - public boolean hasPrevious(){ - synchronized(container){ - nextItem=(IndexItem)list.refreshEntry(nextItem); - return list.getPrevEntry(nextItem)!=null; + public boolean hasPrevious() { + synchronized (container) { + nextItem = (IndexItem)list.refreshEntry(nextItem); + return list.getPrevEntry(nextItem) != null; } } @@ -45,11 +45,11 @@ public class ContainerListIterator extends ContainerValueCollectionIterator impl * * @see java.util.ListIterator#previous() */ - public Object previous(){ - synchronized(container){ - nextItem=(IndexItem)list.refreshEntry(nextItem); - nextItem=list.getPrevEntry(nextItem); - return nextItem!=null?container.getValue(nextItem):null; + public Object previous() { + synchronized (container) { + nextItem = (IndexItem)list.refreshEntry(nextItem); + nextItem = list.getPrevEntry(nextItem); + return nextItem != null ? container.getValue(nextItem) : null; } } @@ -58,14 +58,14 @@ public class ContainerListIterator extends ContainerValueCollectionIterator impl * * @see java.util.ListIterator#nextIndex() */ - public int nextIndex(){ - int result=-1; - if(nextItem!=null){ - synchronized(container){ - nextItem=(IndexItem)list.refreshEntry(nextItem); - StoreEntry next=list.getNextEntry(nextItem); - if(next!=null){ - result=container.getInternalList().indexOf(next); + public int nextIndex() { + int result = -1; + if (nextItem != null) { + synchronized (container) { + nextItem = (IndexItem)list.refreshEntry(nextItem); + StoreEntry next = list.getNextEntry(nextItem); + if (next != null) { + result = container.getInternalList().indexOf(next); } } } @@ -77,14 +77,14 @@ public class ContainerListIterator extends ContainerValueCollectionIterator impl * * @see java.util.ListIterator#previousIndex() */ - public int previousIndex(){ - int result=-1; - if(nextItem!=null){ - synchronized(container){ - nextItem=(IndexItem)list.refreshEntry(nextItem); - StoreEntry prev=list.getPrevEntry(nextItem); - if(prev!=null){ - result=container.getInternalList().indexOf(prev); + public int previousIndex() { + int result = -1; + if (nextItem != null) { + synchronized (container) { + nextItem = (IndexItem)list.refreshEntry(nextItem); + StoreEntry prev = list.getPrevEntry(nextItem); + if (prev != null) { + result = container.getInternalList().indexOf(prev); } } } @@ -96,9 +96,9 @@ public class ContainerListIterator extends ContainerValueCollectionIterator impl * * @see java.util.ListIterator#set(E) */ - public void set(Object o){ - IndexItem item=((ListContainerImpl)container).internalSet(previousIndex()+1,o); - nextItem=item; + public void set(Object o) { + IndexItem item = ((ListContainerImpl)container).internalSet(previousIndex() + 1, o); + nextItem = item; } /* @@ -106,8 +106,8 @@ public class ContainerListIterator extends ContainerValueCollectionIterator impl * * @see java.util.ListIterator#add(E) */ - public void add(Object o){ - IndexItem item=((ListContainerImpl)container).internalAdd(previousIndex()+1,o); - nextItem=item; + public void add(Object o) { + IndexItem item = ((ListContainerImpl)container).internalAdd(previousIndex() + 1, o); + nextItem = item; } } diff --git a/activemq-core/src/main/java/org/apache/activemq/kaha/impl/container/ContainerMapEntry.java b/activemq-core/src/main/java/org/apache/activemq/kaha/impl/container/ContainerMapEntry.java index 8d1206aae4..a735999ef6 100755 --- a/activemq-core/src/main/java/org/apache/activemq/kaha/impl/container/ContainerMapEntry.java +++ b/activemq-core/src/main/java/org/apache/activemq/kaha/impl/container/ContainerMapEntry.java @@ -20,34 +20,30 @@ import java.util.Map; import org.apache.activemq.kaha.MapContainer; /** -* Map.Entry implementation for a container -* -* @version $Revision: 1.2 $ -*/ + * Map.Entry implementation for a container + * + * @version $Revision: 1.2 $ + */ class ContainerMapEntry implements Map.Entry { private MapContainer container; private Object key; - - ContainerMapEntry(MapContainer container,Object key){ + + ContainerMapEntry(MapContainer container, Object key) { this.container = container; this.key = key; - + } - - - public Object getKey(){ + + public Object getKey() { return key; } - public Object getValue(){ + public Object getValue() { return container.get(key); } - public Object setValue(Object value){ + public Object setValue(Object value) { return container.put(key, value); } } - - - diff --git a/activemq-core/src/main/java/org/apache/activemq/kaha/impl/container/ContainerValueCollection.java b/activemq-core/src/main/java/org/apache/activemq/kaha/impl/container/ContainerValueCollection.java index d8f01f6e1b..7e73e0ea2d 100644 --- a/activemq-core/src/main/java/org/apache/activemq/kaha/impl/container/ContainerValueCollection.java +++ b/activemq-core/src/main/java/org/apache/activemq/kaha/impl/container/ContainerValueCollection.java @@ -26,59 +26,53 @@ import org.apache.activemq.kaha.impl.index.IndexItem; import org.apache.activemq.kaha.impl.index.IndexLinkedList; /** -* Values collection for the MapContainer -* -* @version $Revision: 1.2 $ -*/ -class ContainerValueCollection extends ContainerCollectionSupport implements Collection{ - - - ContainerValueCollection(MapContainerImpl container){ + * Values collection for the MapContainer + * + * @version $Revision: 1.2 $ + */ +class ContainerValueCollection extends ContainerCollectionSupport implements Collection { + + ContainerValueCollection(MapContainerImpl container) { super(container); } - - - - public boolean contains(Object o){ + + public boolean contains(Object o) { return container.containsValue(o); } - - public Iterator iterator(){ - IndexLinkedList list=container.getItemList(); - return new ContainerValueCollectionIterator(container,list,list.getRoot()); + public Iterator iterator() { + IndexLinkedList list = container.getItemList(); + return new ContainerValueCollectionIterator(container, list, list.getRoot()); } - - public Object[] toArray(){ + public Object[] toArray() { Object[] result = null; IndexLinkedList list = container.getItemList(); - synchronized(list){ + synchronized (list) { result = new Object[list.size()]; IndexItem item = list.getFirst(); int count = 0; - while (item != null){ - Object value=container.getValue(item); + while (item != null) { + Object value = container.getValue(item); result[count++] = value; - + item = list.getNextEntry(item); } - - + } return result; } - public Object[] toArray(Object[] result){ - IndexLinkedList list=container.getItemList(); - synchronized(list){ - if(result.length<=list.size()){ + public Object[] toArray(Object[] result) { + IndexLinkedList list = container.getItemList(); + synchronized (list) { + if (result.length <= list.size()) { IndexItem item = list.getFirst(); int count = 0; - while (item != null){ - Object value=container.getValue(item); + while (item != null) { + Object value = container.getValue(item); result[count++] = value; - + item = list.getNextEntry(item); } } @@ -86,21 +80,18 @@ class ContainerValueCollection extends ContainerCollectionSupport implements Col return result; } - - public boolean add(Object o){ - throw new UnsupportedOperationException("Can't add an object here"); + public boolean add(Object o) { + throw new UnsupportedOperationException("Can't add an object here"); } - - public boolean remove(Object o){ + public boolean remove(Object o) { return container.removeValue(o); } - - public boolean containsAll(Collection c){ + public boolean containsAll(Collection c) { boolean result = !c.isEmpty(); - for (Iterator i = c.iterator(); i.hasNext(); ){ - if (!contains(i.next())){ + for (Iterator i = c.iterator(); i.hasNext();) { + if (!contains(i.next())) { result = false; break; } @@ -108,38 +99,34 @@ class ContainerValueCollection extends ContainerCollectionSupport implements Col return result; } - - public boolean addAll(Collection c){ - throw new UnsupportedOperationException("Can't add everything here!"); + public boolean addAll(Collection c) { + throw new UnsupportedOperationException("Can't add everything here!"); } - - public boolean removeAll(Collection c){ + public boolean removeAll(Collection c) { boolean result = true; - for (Iterator i = c.iterator(); i.hasNext(); ){ + for (Iterator i = c.iterator(); i.hasNext();) { Object obj = i.next(); - result&=remove(obj); + result &= remove(obj); } return result; } - - public boolean retainAll(Collection c){ - List tmpList = new ArrayList(); - for (Iterator i = c.iterator(); i.hasNext(); ){ - Object o = i.next(); - if (!contains(o)){ - tmpList.add(o); - } - } - for(Iterator i = tmpList.iterator(); i.hasNext();){ - remove(i.next()); - } - return !tmpList.isEmpty(); + public boolean retainAll(Collection c) { + List tmpList = new ArrayList(); + for (Iterator i = c.iterator(); i.hasNext();) { + Object o = i.next(); + if (!contains(o)) { + tmpList.add(o); + } + } + for (Iterator i = tmpList.iterator(); i.hasNext();) { + remove(i.next()); + } + return !tmpList.isEmpty(); } - - public void clear(){ - container.clear(); + public void clear() { + container.clear(); } } diff --git a/activemq-core/src/main/java/org/apache/activemq/kaha/impl/container/ContainerValueCollectionIterator.java b/activemq-core/src/main/java/org/apache/activemq/kaha/impl/container/ContainerValueCollectionIterator.java index e25f080d11..d3ba3660d0 100644 --- a/activemq-core/src/main/java/org/apache/activemq/kaha/impl/container/ContainerValueCollectionIterator.java +++ b/activemq-core/src/main/java/org/apache/activemq/kaha/impl/container/ContainerValueCollectionIterator.java @@ -23,38 +23,38 @@ import org.apache.activemq.kaha.impl.index.IndexLinkedList; * * @version $Revision: 1.2 $ */ -public class ContainerValueCollectionIterator implements Iterator{ +public class ContainerValueCollectionIterator implements Iterator { protected BaseContainerImpl container; protected IndexLinkedList list; protected IndexItem nextItem; protected IndexItem currentItem; - ContainerValueCollectionIterator(BaseContainerImpl container,IndexLinkedList list,IndexItem start){ - this.container=container; - this.list=list; - this.currentItem=start; - this.nextItem=list.getNextEntry((IndexItem)list.refreshEntry(start)); + ContainerValueCollectionIterator(BaseContainerImpl container, IndexLinkedList list, IndexItem start) { + this.container = container; + this.list = list; + this.currentItem = start; + this.nextItem = list.getNextEntry((IndexItem)list.refreshEntry(start)); } - public boolean hasNext(){ - return nextItem!=null; + public boolean hasNext() { + return nextItem != null; } - public Object next(){ - synchronized(container){ - nextItem=(IndexItem)list.refreshEntry(nextItem); - currentItem=nextItem; - Object result=container.getValue(nextItem); - nextItem=list.getNextEntry(nextItem); + public Object next() { + synchronized (container) { + nextItem = (IndexItem)list.refreshEntry(nextItem); + currentItem = nextItem; + Object result = container.getValue(nextItem); + nextItem = list.getNextEntry(nextItem); return result; } } - public void remove(){ - synchronized(container){ - if(currentItem!=null){ - currentItem=(IndexItem)list.refreshEntry(currentItem); + public void remove() { + synchronized (container) { + if (currentItem != null) { + currentItem = (IndexItem)list.refreshEntry(currentItem); container.remove(currentItem); } } diff --git a/activemq-core/src/main/java/org/apache/activemq/kaha/impl/container/ListContainerImpl.java b/activemq-core/src/main/java/org/apache/activemq/kaha/impl/container/ListContainerImpl.java index 465ebf24f5..4c132da684 100644 --- a/activemq-core/src/main/java/org/apache/activemq/kaha/impl/container/ListContainerImpl.java +++ b/activemq-core/src/main/java/org/apache/activemq/kaha/impl/container/ListContainerImpl.java @@ -40,15 +40,14 @@ import org.apache.commons.logging.LogFactory; * * @version $Revision: 1.2 $ */ -public class ListContainerImpl extends BaseContainerImpl implements ListContainer{ +public class ListContainerImpl extends BaseContainerImpl implements ListContainer { - private static final Log log=LogFactory.getLog(ListContainerImpl.class); - protected Marshaller marshaller=Store.ObjectMarshaller; - + private static final Log log = LogFactory.getLog(ListContainerImpl.class); + protected Marshaller marshaller = Store.ObjectMarshaller; - public ListContainerImpl(ContainerId id,IndexItem root,IndexManager indexManager,DataManager dataManager, - boolean persistentIndex) throws IOException{ - super(id,root,indexManager,dataManager,persistentIndex); + public ListContainerImpl(ContainerId id, IndexItem root, IndexManager indexManager, + DataManager dataManager, boolean persistentIndex) throws IOException { + super(id, root, indexManager, dataManager, persistentIndex); } /* @@ -56,22 +55,22 @@ public class ListContainerImpl extends BaseContainerImpl implements ListContaine * * @see org.apache.activemq.kaha.ListContainer#load() */ - public synchronized void load(){ + public synchronized void load() { checkClosed(); - if(!loaded){ - if(!loaded){ - loaded=true; - try{ + if (!loaded) { + if (!loaded) { + loaded = true; + try { init(); - long nextItem=root.getNextItem(); - while(nextItem!=Item.POSITION_NOT_SET){ - IndexItem item=indexManager.getIndex(nextItem); + long nextItem = root.getNextItem(); + while (nextItem != Item.POSITION_NOT_SET) { + IndexItem item = indexManager.getIndex(nextItem); indexList.add(item); - itemAdded(item,indexList.size()-1,getValue(item)); - nextItem=item.getNextItem(); + itemAdded(item, indexList.size() - 1, getValue(item)); + nextItem = item.getNextItem(); } - }catch(IOException e){ - log.error("Failed to load container "+getId(),e); + } catch (IOException e) { + log.error("Failed to load container " + getId(), e); throw new RuntimeStoreException(e); } } @@ -83,12 +82,12 @@ public class ListContainerImpl extends BaseContainerImpl implements ListContaine * * @see org.apache.activemq.kaha.ListContainer#unload() */ - public synchronized void unload(){ + public synchronized void unload() { checkClosed(); - if(loaded){ - loaded=false; + if (loaded) { + loaded = false; indexList.clear(); - + } } @@ -97,23 +96,23 @@ public class ListContainerImpl extends BaseContainerImpl implements ListContaine * * @see org.apache.activemq.kaha.ListContainer#setKeyMarshaller(org.apache.activemq.kaha.Marshaller) */ - public synchronized void setMarshaller(Marshaller marshaller){ + public synchronized void setMarshaller(Marshaller marshaller) { checkClosed(); - this.marshaller=marshaller; + this.marshaller = marshaller; } - public synchronized boolean equals(Object obj){ + public synchronized boolean equals(Object obj) { load(); - boolean result=false; - if(obj!=null&&obj instanceof List){ - List other=(List)obj; - result=other.size()==size(); - if(result){ - for(int i=0;i1?(IndexItem)indexList.get(1):null; + result = getValue(item); + IndexItem prev = root; + IndexItem next = indexList.size() > 1 ? (IndexItem)indexList.get(1) : null; indexList.removeFirst(); - - delete(item,prev,next); - item=null; + + delete(item, prev, next); + item = null; } return result; } @@ -181,17 +180,17 @@ public class ListContainerImpl extends BaseContainerImpl implements ListContaine * * @see org.apache.activemq.kaha.ListContainer#removeLast() */ - public synchronized Object removeLast(){ + public synchronized Object removeLast() { load(); - Object result=null; - IndexItem last=indexList.getLast(); - if(last!=null){ - itemRemoved(indexList.size()-1); - result=getValue(last); - IndexItem prev=indexList.getPrevEntry(last); - IndexItem next=null; + Object result = null; + IndexItem last = indexList.getLast(); + if (last != null) { + itemRemoved(indexList.size() - 1); + result = getValue(last); + IndexItem prev = indexList.getPrevEntry(last); + IndexItem next = null; indexList.removeLast(); - delete(last,prev,next); + delete(last, prev, next); } return result; } @@ -201,7 +200,7 @@ public class ListContainerImpl extends BaseContainerImpl implements ListContaine * * @see java.util.List#isEmpty() */ - public synchronized boolean isEmpty(){ + public synchronized boolean isEmpty() { load(); return indexList.isEmpty(); } @@ -211,18 +210,18 @@ public class ListContainerImpl extends BaseContainerImpl implements ListContaine * * @see java.util.List#contains(java.lang.Object) */ - public synchronized boolean contains(Object o){ + public synchronized boolean contains(Object o) { load(); - boolean result=false; - if(o!=null){ - IndexItem next=indexList.getFirst(); - while(next!=null){ - Object value=getValue(next); - if(value!=null&&value.equals(o)){ - result=true; + boolean result = false; + if (o != null) { + IndexItem next = indexList.getFirst(); + while (next != null) { + Object value = getValue(next); + if (value != null && value.equals(o)) { + result = true; break; } - next=indexList.getNextEntry(next); + next = indexList.getNextEntry(next); } } return result; @@ -233,7 +232,7 @@ public class ListContainerImpl extends BaseContainerImpl implements ListContaine * * @see java.util.List#iterator() */ - public synchronized Iterator iterator(){ + public synchronized Iterator iterator() { load(); return listIterator(); } @@ -243,14 +242,14 @@ public class ListContainerImpl extends BaseContainerImpl implements ListContaine * * @see java.util.List#toArray() */ - public synchronized Object[] toArray(){ + public synchronized Object[] toArray() { load(); - List tmp=new ArrayList(indexList.size()); - IndexItem next=indexList.getFirst(); - while(next!=null){ - Object value=getValue(next); + List tmp = new ArrayList(indexList.size()); + IndexItem next = indexList.getFirst(); + while (next != null) { + Object value = getValue(next); tmp.add(value); - next=indexList.getNextEntry(next); + next = indexList.getNextEntry(next); } return tmp.toArray(); } @@ -260,14 +259,14 @@ public class ListContainerImpl extends BaseContainerImpl implements ListContaine * * @see java.util.List#toArray(T[]) */ - public synchronized Object[] toArray(Object[] a){ + public synchronized Object[] toArray(Object[] a) { load(); - List tmp=new ArrayList(indexList.size()); - IndexItem next=indexList.getFirst(); - while(next!=null){ - Object value=getValue(next); + List tmp = new ArrayList(indexList.size()); + IndexItem next = indexList.getFirst(); + while (next != null) { + Object value = getValue(next); tmp.add(value); - next=indexList.getNextEntry(next); + next = indexList.getNextEntry(next); } return tmp.toArray(a); } @@ -277,7 +276,7 @@ public class ListContainerImpl extends BaseContainerImpl implements ListContaine * * @see java.util.List#add(E) */ - public synchronized boolean add(Object o){ + public synchronized boolean add(Object o) { load(); addLast(o); return true; @@ -288,31 +287,31 @@ public class ListContainerImpl extends BaseContainerImpl implements ListContaine * * @see java.util.List#remove(java.lang.Object) */ - public synchronized boolean remove(Object o){ + public synchronized boolean remove(Object o) { load(); - boolean result=false; - int pos=0; - IndexItem next=indexList.getFirst(); - while(next!=null){ - Object value=getValue(next); - if(value!=null&&value.equals(o)){ + boolean result = false; + int pos = 0; + IndexItem next = indexList.getFirst(); + while (next != null) { + Object value = getValue(next); + if (value != null && value.equals(o)) { remove(next); itemRemoved(pos); - result=true; + result = true; break; } - next=indexList.getNextEntry(next); + next = indexList.getNextEntry(next); pos++; } return result; } - protected synchronized void remove(IndexItem item){ - IndexItem prev=indexList.getPrevEntry(item); - IndexItem next=indexList.getNextEntry(item); + protected synchronized void remove(IndexItem item) { + IndexItem prev = indexList.getPrevEntry(item); + IndexItem next = indexList.getNextEntry(item); indexList.remove(item); - - delete(item,prev,next); + + delete(item, prev, next); } /* @@ -320,13 +319,13 @@ public class ListContainerImpl extends BaseContainerImpl implements ListContaine * * @see java.util.List#containsAll(java.util.Collection) */ - public synchronized boolean containsAll(Collection c){ + public synchronized boolean containsAll(Collection c) { load(); - boolean result=false; - for(Iterator i=c.iterator();i.hasNext();){ - Object obj=i.next(); - if(!(result=contains(obj))){ - result=false; + boolean result = false; + for (Iterator i = c.iterator(); i.hasNext();) { + Object obj = i.next(); + if (!(result = contains(obj))) { + result = false; break; } } @@ -338,9 +337,9 @@ public class ListContainerImpl extends BaseContainerImpl implements ListContaine * * @see java.util.List#addAll(java.util.Collection) */ - public synchronized boolean addAll(Collection c){ + public synchronized boolean addAll(Collection c) { load(); - for(Iterator i=c.iterator();i.hasNext();){ + for (Iterator i = c.iterator(); i.hasNext();) { add(i.next()); } return true; @@ -351,14 +350,14 @@ public class ListContainerImpl extends BaseContainerImpl implements ListContaine * * @see java.util.List#addAll(int, java.util.Collection) */ - public synchronized boolean addAll(int index,Collection c){ + public synchronized boolean addAll(int index, Collection c) { load(); - boolean result=false; - ListIterator e1=listIterator(index); - Iterator e2=c.iterator(); - while(e2.hasNext()){ + boolean result = false; + ListIterator e1 = listIterator(index); + Iterator e2 = c.iterator(); + while (e2.hasNext()) { e1.add(e2.next()); - result=true; + result = true; } return result; } @@ -368,12 +367,12 @@ public class ListContainerImpl extends BaseContainerImpl implements ListContaine * * @see java.util.List#removeAll(java.util.Collection) */ - public synchronized boolean removeAll(Collection c){ + public synchronized boolean removeAll(Collection c) { load(); - boolean result=true; - for(Iterator i=c.iterator();i.hasNext();){ - Object obj=i.next(); - result&=remove(obj); + boolean result = true; + for (Iterator i = c.iterator(); i.hasNext();) { + Object obj = i.next(); + result &= remove(obj); } return result; } @@ -383,18 +382,18 @@ public class ListContainerImpl extends BaseContainerImpl implements ListContaine * * @see java.util.List#retainAll(java.util.Collection) */ - public synchronized boolean retainAll(Collection c){ + public synchronized boolean retainAll(Collection c) { load(); - List tmpList=new ArrayList(); - IndexItem next=indexList.getFirst(); - while(next!=null){ - Object o=getValue(next); - if(!c.contains(o)){ + List tmpList = new ArrayList(); + IndexItem next = indexList.getFirst(); + while (next != null) { + Object o = getValue(next); + if (!c.contains(o)) { tmpList.add(o); } - next=indexList.getNextEntry(next); + next = indexList.getNextEntry(next); } - for(Iterator i=tmpList.iterator();i.hasNext();){ + for (Iterator i = tmpList.iterator(); i.hasNext();) { remove(i.next()); } return !tmpList.isEmpty(); @@ -405,11 +404,11 @@ public class ListContainerImpl extends BaseContainerImpl implements ListContaine * * @see java.util.List#clear() */ - public synchronized void clear(){ + public synchronized void clear() { checkClosed(); super.clear(); doClear(); - + } /* @@ -417,12 +416,12 @@ public class ListContainerImpl extends BaseContainerImpl implements ListContaine * * @see java.util.List#get(int) */ - public synchronized Object get(int index){ + public synchronized Object get(int index) { load(); Object result = null; - IndexItem item=indexList.get(index); - if(item!=null){ - result=getValue(item); + IndexItem item = indexList.get(index); + if (item != null) { + result = getValue(item); } return result; } @@ -432,28 +431,32 @@ public class ListContainerImpl extends BaseContainerImpl implements ListContaine * * @see java.util.List#set(int, E) */ - public synchronized Object set(int index,Object element){ + public synchronized Object set(int index, Object element) { load(); - Object result=null; - IndexItem replace=indexList.isEmpty()?null:(IndexItem)indexList.get(index); - IndexItem prev=(indexList.isEmpty()||(index-1)<0)?null:(IndexItem)indexList.get(index-1); - IndexItem next=(indexList.isEmpty()||(index+1)>=size())?null:(IndexItem)indexList.get(index+1); - result=getValue(replace); + Object result = null; + IndexItem replace = indexList.isEmpty() ? null : (IndexItem)indexList.get(index); + IndexItem prev = (indexList.isEmpty() || (index - 1) < 0) ? null : (IndexItem)indexList + .get(index - 1); + IndexItem next = (indexList.isEmpty() || (index + 1) >= size()) ? null : (IndexItem)indexList + .get(index + 1); + result = getValue(replace); indexList.remove(index); - delete(replace,prev,next); + delete(replace, prev, next); itemRemoved(index); - add(index,element); + add(index, element); return result; } - protected synchronized IndexItem internalSet(int index,Object element){ - IndexItem replace=indexList.isEmpty()?null:(IndexItem)indexList.get(index); - IndexItem prev=(indexList.isEmpty()||(index-1)<0)?null:(IndexItem)indexList.get(index-1); - IndexItem next=(indexList.isEmpty()||(index+1)>=size())?null:(IndexItem)indexList.get(index+1); + protected synchronized IndexItem internalSet(int index, Object element) { + IndexItem replace = indexList.isEmpty() ? null : (IndexItem)indexList.get(index); + IndexItem prev = (indexList.isEmpty() || (index - 1) < 0) ? null : (IndexItem)indexList + .get(index - 1); + IndexItem next = (indexList.isEmpty() || (index + 1) >= size()) ? null : (IndexItem)indexList + .get(index + 1); indexList.remove(index); - delete(replace,prev,next); + delete(replace, prev, next); itemRemoved(index); - return internalAdd(index,element); + return internalAdd(index, element); } /* @@ -461,40 +464,40 @@ public class ListContainerImpl extends BaseContainerImpl implements ListContaine * * @see java.util.List#add(int, E) */ - public synchronized void add(int index,Object element){ + public synchronized void add(int index, Object element) { load(); - IndexItem item=insert(index,element); - indexList.add(index,item); - itemAdded(item,index,element); + IndexItem item = insert(index, element); + indexList.add(index, item); + itemAdded(item, index, element); } - protected synchronized StoreEntry internalAddLast(Object o){ + protected synchronized StoreEntry internalAddLast(Object o) { load(); - IndexItem item=writeLast(o); + IndexItem item = writeLast(o); indexList.addLast(item); - itemAdded(item,indexList.size()-1,o); + itemAdded(item, indexList.size() - 1, o); return item; } - protected synchronized StoreEntry internalAddFirst(Object o){ + protected synchronized StoreEntry internalAddFirst(Object o) { load(); - IndexItem item=writeFirst(o); + IndexItem item = writeFirst(o); indexList.addFirst(item); - itemAdded(item,0,o); + itemAdded(item, 0, o); return item; } - protected synchronized IndexItem internalAdd(int index,Object element){ + protected synchronized IndexItem internalAdd(int index, Object element) { load(); - IndexItem item=insert(index,element); - indexList.add(index,item); - itemAdded(item,index,element); + IndexItem item = insert(index, element); + indexList.add(index, item); + itemAdded(item, index, element); return item; } - protected synchronized StoreEntry internalGet(int index){ + protected synchronized StoreEntry internalGet(int index) { load(); - if(index>=0&&index= 0 && index < indexList.size()) { return indexList.get(index); } return null; @@ -505,18 +508,18 @@ public class ListContainerImpl extends BaseContainerImpl implements ListContaine * * @see org.apache.activemq.kaha.ListContainer#doRemove(int) */ - public synchronized boolean doRemove(int index){ + public synchronized boolean doRemove(int index) { load(); - boolean result=false; - IndexItem item=indexList.get(index); - if(item!=null){ - result=true; - IndexItem prev=indexList.getPrevEntry(item); - prev=prev!=null?prev:root; - IndexItem next=indexList.getNextEntry(prev); + boolean result = false; + IndexItem item = indexList.get(index); + if (item != null) { + result = true; + IndexItem prev = indexList.getPrevEntry(item); + prev = prev != null ? prev : root; + IndexItem next = indexList.getNextEntry(prev); indexList.remove(index); itemRemoved(index); - delete(item,prev,next); + delete(item, prev, next); } return result; } @@ -526,18 +529,18 @@ public class ListContainerImpl extends BaseContainerImpl implements ListContaine * * @see java.util.List#remove(int) */ - public synchronized Object remove(int index){ + public synchronized Object remove(int index) { load(); - Object result=null; - IndexItem item=indexList.get(index); - if(item!=null){ + Object result = null; + IndexItem item = indexList.get(index); + if (item != null) { itemRemoved(index); - result=getValue(item); - IndexItem prev=indexList.getPrevEntry(item); - prev=prev!=null?prev:root; - IndexItem next=indexList.getNextEntry(item); + result = getValue(item); + IndexItem prev = indexList.getPrevEntry(item); + prev = prev != null ? prev : root; + IndexItem next = indexList.getNextEntry(item); indexList.remove(index); - delete(item,prev,next); + delete(item, prev, next); } return result; } @@ -547,20 +550,20 @@ public class ListContainerImpl extends BaseContainerImpl implements ListContaine * * @see java.util.List#indexOf(java.lang.Object) */ - public synchronized int indexOf(Object o){ + public synchronized int indexOf(Object o) { load(); - int result=-1; - if(o!=null){ - int count=0; - IndexItem next=indexList.getFirst(); - while(next!=null){ - Object value=getValue(next); - if(value!=null&&value.equals(o)){ - result=count; + int result = -1; + if (o != null) { + int count = 0; + IndexItem next = indexList.getFirst(); + while (next != null) { + Object value = getValue(next); + if (value != null && value.equals(o)) { + result = count; break; } count++; - next=indexList.getNextEntry(next); + next = indexList.getNextEntry(next); } } return result; @@ -571,20 +574,20 @@ public class ListContainerImpl extends BaseContainerImpl implements ListContaine * * @see java.util.List#lastIndexOf(java.lang.Object) */ - public synchronized int lastIndexOf(Object o){ + public synchronized int lastIndexOf(Object o) { load(); - int result=-1; - if(o!=null){ - int count=indexList.size()-1; - IndexItem next=indexList.getLast(); - while(next!=null){ - Object value=getValue(next); - if(value!=null&&value.equals(o)){ - result=count; + int result = -1; + if (o != null) { + int count = indexList.size() - 1; + IndexItem next = indexList.getLast(); + while (next != null) { + Object value = getValue(next); + if (value != null && value.equals(o)) { + result = count; break; } count--; - next=indexList.getPrevEntry(next); + next = indexList.getPrevEntry(next); } } return result; @@ -595,9 +598,9 @@ public class ListContainerImpl extends BaseContainerImpl implements ListContaine * * @see java.util.List#listIterator() */ - public synchronized ListIterator listIterator(){ + public synchronized ListIterator listIterator() { load(); - return new ContainerListIterator(this,indexList,indexList.getRoot()); + return new ContainerListIterator(this, indexList, indexList.getRoot()); } /* @@ -605,10 +608,10 @@ public class ListContainerImpl extends BaseContainerImpl implements ListContaine * * @see java.util.List#listIterator(int) */ - public synchronized ListIterator listIterator(int index){ + public synchronized ListIterator listIterator(int index) { load(); - IndexItem start = (index-1) >0 ?indexList.get(index-1):indexList.getRoot(); - return new ContainerListIterator(this,indexList,start); + IndexItem start = (index - 1) > 0 ? indexList.get(index - 1) : indexList.getRoot(); + return new ContainerListIterator(this, indexList, start); } /* @@ -616,14 +619,14 @@ public class ListContainerImpl extends BaseContainerImpl implements ListContaine * * @see java.util.List#subList(int, int) */ - public synchronized List subList(int fromIndex,int toIndex){ + public synchronized List subList(int fromIndex, int toIndex) { load(); - List result=new ArrayList(); - int count=fromIndex; - IndexItem next=indexList.get(fromIndex); - while(next!=null&&count++=indexList.size()){ - prev=indexList.getLast(); - next=null; - }else{ - prev=indexList.get(insertPos); - prev=prev!=null?prev:root; - next=indexList.getNextEntry(prev); + IndexItem prev = null; + IndexItem next = null; + if (insertPos <= 0) { + prev = root; + next = indexList.getNextEntry(root); + } else if (insertPos >= indexList.size()) { + prev = indexList.getLast(); + next = null; + } else { + prev = indexList.get(insertPos); + prev = prev != null ? prev : root; + next = indexList.getNextEntry(prev); } prev.setNextItem(index.getOffset()); index.setPreviousItem(prev.getOffset()); updateIndexes(prev); - if(next!=null){ + if (next != null) { next.setPreviousItem(index.getOffset()); index.setNextItem(next.getOffset()); updateIndexes(next); } storeIndex(index); } - }catch(IOException e){ - log.error("Failed to insert "+value,e); + } catch (IOException e) { + log.error("Failed to insert " + value, e); throw new RuntimeStoreException(e); } return index; } - protected synchronized Object getValue(StoreEntry item){ - Object result=null; - if(item!=null){ - try{ - StoreLocation data=item.getValueDataItem(); - result=dataManager.readItem(marshaller,data); - }catch(IOException e){ - log.error("Failed to get value for "+item,e); + protected synchronized Object getValue(StoreEntry item) { + Object result = null; + if (item != null) { + try { + StoreLocation data = item.getValueDataItem(); + result = dataManager.readItem(marshaller, data); + } catch (IOException e) { + log.error("Failed to get value for " + item, e); throw new RuntimeStoreException(e); } } @@ -855,27 +861,27 @@ public class ListContainerImpl extends BaseContainerImpl implements ListContaine /** * @return a string representation of this collection. */ - public synchronized String toString(){ - StringBuffer result=new StringBuffer(); + public synchronized String toString() { + StringBuffer result = new StringBuffer(); result.append("["); - Iterator i=iterator(); - boolean hasNext=i.hasNext(); - while(hasNext){ - Object o=i.next(); + Iterator i = iterator(); + boolean hasNext = i.hasNext(); + while (hasNext) { + Object o = i.next(); result.append(String.valueOf(o)); - hasNext=i.hasNext(); - if(hasNext) + hasNext = i.hasNext(); + if (hasNext) result.append(", "); } result.append("]"); return result.toString(); } - protected synchronized void itemAdded(IndexItem item,int pos,Object value){ - + protected synchronized void itemAdded(IndexItem item, int pos, Object value) { + } - protected synchronized void itemRemoved(int pos){ - + protected synchronized void itemRemoved(int pos) { + } } diff --git a/activemq-core/src/main/java/org/apache/activemq/kaha/impl/container/MapContainerImpl.java b/activemq-core/src/main/java/org/apache/activemq/kaha/impl/container/MapContainerImpl.java index d701593b58..acb2edb06e 100755 --- a/activemq-core/src/main/java/org/apache/activemq/kaha/impl/container/MapContainerImpl.java +++ b/activemq-core/src/main/java/org/apache/activemq/kaha/impl/container/MapContainerImpl.java @@ -43,34 +43,34 @@ import org.apache.commons.logging.LogFactory; * * @version $Revision: 1.2 $ */ -public final class MapContainerImpl extends BaseContainerImpl implements MapContainer{ +public final class MapContainerImpl extends BaseContainerImpl implements MapContainer { - private static final Log log=LogFactory.getLog(MapContainerImpl.class); + private static final Log log = LogFactory.getLog(MapContainerImpl.class); protected Index index; - protected Marshaller keyMarshaller=Store.ObjectMarshaller; - protected Marshaller valueMarshaller=Store.ObjectMarshaller; + protected Marshaller keyMarshaller = Store.ObjectMarshaller; + protected Marshaller valueMarshaller = Store.ObjectMarshaller; protected File directory; - public MapContainerImpl(File directory,ContainerId id,IndexItem root,IndexManager indexManager, - DataManager dataManager,boolean persistentIndex){ - super(id,root,indexManager,dataManager,persistentIndex); - this.directory=directory; + public MapContainerImpl(File directory, ContainerId id, IndexItem root, IndexManager indexManager, + DataManager dataManager, boolean persistentIndex) { + super(id, root, indexManager, dataManager, persistentIndex); + this.directory = directory; } - public synchronized void init(){ + public synchronized void init() { super.init(); - if(index==null){ - if(persistentIndex){ - String name=containerId.getDataContainerName()+"_"+containerId.getKey(); - name=name.replaceAll("[^a-zA-Z0-9\\.\\_\\-]", "_"); - try{ - this.index=new HashIndex(directory,name,indexManager); - }catch(IOException e){ - log.error("Failed to create HashIndex",e); + if (index == null) { + if (persistentIndex) { + String name = containerId.getDataContainerName() + "_" + containerId.getKey(); + name = name.replaceAll("[^a-zA-Z0-9\\.\\_\\-]", "_"); + try { + this.index = new HashIndex(directory, name, indexManager); + } catch (IOException e) { + log.error("Failed to create HashIndex", e); throw new RuntimeException(e); } - }else{ - this.index=new VMIndex(indexManager); + } else { + this.index = new VMIndex(indexManager); } } index.setKeyMarshaller(keyMarshaller); @@ -81,27 +81,27 @@ public final class MapContainerImpl extends BaseContainerImpl implements MapCont * * @see org.apache.activemq.kaha.MapContainer#load() */ - public synchronized void load(){ + public synchronized void load() { checkClosed(); - if(!loaded){ - if(!loaded){ - loaded=true; - try{ + if (!loaded) { + if (!loaded) { + loaded = true; + try { init(); index.load(); - long nextItem=root.getNextItem(); - while(nextItem!=Item.POSITION_NOT_SET){ - IndexItem item=indexManager.getIndex(nextItem); - StoreLocation data=item.getKeyDataItem(); - Object key=dataManager.readItem(keyMarshaller,data); - if(index.isTransient()){ - index.store(key,item); + long nextItem = root.getNextItem(); + while (nextItem != Item.POSITION_NOT_SET) { + IndexItem item = indexManager.getIndex(nextItem); + StoreLocation data = item.getKeyDataItem(); + Object key = dataManager.readItem(keyMarshaller, data); + if (index.isTransient()) { + index.store(key, item); } indexList.add(item); - nextItem=item.getNextItem(); + nextItem = item.getNextItem(); } - }catch(IOException e){ - log.error("Failed to load container "+getId(),e); + } catch (IOException e) { + log.error("Failed to load container " + getId(), e); throw new RuntimeStoreException(e); } } @@ -113,30 +113,30 @@ public final class MapContainerImpl extends BaseContainerImpl implements MapCont * * @see org.apache.activemq.kaha.MapContainer#unload() */ - public synchronized void unload(){ + public synchronized void unload() { checkClosed(); - if(loaded){ - loaded=false; - try{ + if (loaded) { + loaded = false; + try { index.unload(); - }catch(IOException e){ - log.warn("Failed to unload the index",e); + } catch (IOException e) { + log.warn("Failed to unload the index", e); } indexList.clear(); } } - public synchronized void setKeyMarshaller(Marshaller keyMarshaller){ + public synchronized void setKeyMarshaller(Marshaller keyMarshaller) { checkClosed(); - this.keyMarshaller=keyMarshaller; - if(index!=null){ + this.keyMarshaller = keyMarshaller; + if (index != null) { index.setKeyMarshaller(keyMarshaller); } } - public synchronized void setValueMarshaller(Marshaller valueMarshaller){ + public synchronized void setValueMarshaller(Marshaller valueMarshaller) { checkClosed(); - this.valueMarshaller=valueMarshaller; + this.valueMarshaller = valueMarshaller; } /* @@ -144,7 +144,7 @@ public final class MapContainerImpl extends BaseContainerImpl implements MapCont * * @see org.apache.activemq.kaha.MapContainer#size() */ - public synchronized int size(){ + public synchronized int size() { load(); return indexList.size(); } @@ -154,7 +154,7 @@ public final class MapContainerImpl extends BaseContainerImpl implements MapCont * * @see org.apache.activemq.kaha.MapContainer#isEmpty() */ - public synchronized boolean isEmpty(){ + public synchronized boolean isEmpty() { load(); return indexList.isEmpty(); } @@ -164,12 +164,12 @@ public final class MapContainerImpl extends BaseContainerImpl implements MapCont * * @see org.apache.activemq.kaha.MapContainer#containsKey(java.lang.Object) */ - public synchronized boolean containsKey(Object key){ + public synchronized boolean containsKey(Object key) { load(); - try{ + try { return index.containsKey(key); - }catch(IOException e){ - log.error("Failed trying to find key: "+key,e); + } catch (IOException e) { + log.error("Failed trying to find key: " + key, e); throw new RuntimeException(e); } } @@ -179,34 +179,35 @@ public final class MapContainerImpl extends BaseContainerImpl implements MapCont * * @see org.apache.activemq.kaha.MapContainer#get(java.lang.Object) */ - public synchronized Object get(Object key){ + public synchronized Object get(Object key) { load(); - Object result=null; - StoreEntry item=null; - try{ - item=index.get(key); - }catch(IOException e){ - log.error("Failed trying to get key: "+key,e); + Object result = null; + StoreEntry item = null; + try { + item = index.get(key); + } catch (IOException e) { + log.error("Failed trying to get key: " + key, e); throw new RuntimeException(e); } - if(item!=null){ - result=getValue(item); + if (item != null) { + result = getValue(item); } return result; } - + /** * Get the StoreEntry associated with the key + * * @param key * @return the StoreEntry */ public synchronized StoreEntry getEntry(Object key) { load(); - StoreEntry item=null; - try{ - item=index.get(key); - }catch(IOException e){ - log.error("Failed trying to get key: "+key,e); + StoreEntry item = null; + try { + item = index.get(key); + } catch (IOException e) { + log.error("Failed trying to get key: " + key, e); throw new RuntimeException(e); } return item; @@ -217,18 +218,18 @@ public final class MapContainerImpl extends BaseContainerImpl implements MapCont * * @see org.apache.activemq.kaha.MapContainer#containsValue(java.lang.Object) */ - public synchronized boolean containsValue(Object o){ + public synchronized boolean containsValue(Object o) { load(); - boolean result=false; - if(o!=null){ - IndexItem item=indexList.getFirst(); - while(item!=null){ - Object value=getValue(item); - if(value!=null&&value.equals(o)){ - result=true; + boolean result = false; + if (o != null) { + IndexItem item = indexList.getFirst(); + while (item != null) { + Object value = getValue(item); + if (value != null && value.equals(o)) { + result = true; break; } - item=indexList.getNextEntry(item); + item = indexList.getNextEntry(item); } } return result; @@ -239,12 +240,12 @@ public final class MapContainerImpl extends BaseContainerImpl implements MapCont * * @see org.apache.activemq.kaha.MapContainer#putAll(java.util.Map) */ - public synchronized void putAll(Map t){ + public synchronized void putAll(Map t) { load(); - if(t!=null){ - for(Iterator i=t.entrySet().iterator();i.hasNext();){ - Map.Entry entry=(Map.Entry)i.next(); - put(entry.getKey(),entry.getValue()); + if (t != null) { + for (Iterator i = t.entrySet().iterator(); i.hasNext();) { + Map.Entry entry = (Map.Entry)i.next(); + put(entry.getKey(), entry.getValue()); } } } @@ -254,7 +255,7 @@ public final class MapContainerImpl extends BaseContainerImpl implements MapCont * * @see org.apache.activemq.kaha.MapContainer#keySet() */ - public synchronized Set keySet(){ + public synchronized Set keySet() { load(); return new ContainerKeySet(this); } @@ -264,7 +265,7 @@ public final class MapContainerImpl extends BaseContainerImpl implements MapCont * * @see org.apache.activemq.kaha.MapContainer#values() */ - public synchronized Collection values(){ + public synchronized Collection values() { load(); return new ContainerValueCollection(this); } @@ -274,7 +275,7 @@ public final class MapContainerImpl extends BaseContainerImpl implements MapCont * * @see org.apache.activemq.kaha.MapContainer#entrySet() */ - public synchronized Set entrySet(){ + public synchronized Set entrySet() { load(); return new ContainerEntrySet(this); } @@ -282,16 +283,17 @@ public final class MapContainerImpl extends BaseContainerImpl implements MapCont /* * (non-Javadoc) * - * @see org.apache.activemq.kaha.MapContainer#put(java.lang.Object, java.lang.Object) + * @see org.apache.activemq.kaha.MapContainer#put(java.lang.Object, + * java.lang.Object) */ - public synchronized Object put(Object key,Object value){ + public synchronized Object put(Object key, Object value) { load(); - Object result=remove(key); - IndexItem item=write(key,value); - try{ - index.store(key,item); - }catch(IOException e){ - log.error("Failed trying to insert key: "+key,e); + Object result = remove(key); + IndexItem item = write(key, value); + try { + index.store(key, item); + } catch (IOException e) { + log.error("Failed trying to insert key: " + key, e); throw new RuntimeException(e); } indexList.add(item); @@ -303,52 +305,52 @@ public final class MapContainerImpl extends BaseContainerImpl implements MapCont * * @see org.apache.activemq.kaha.MapContainer#remove(java.lang.Object) */ - public synchronized Object remove(Object key){ + public synchronized Object remove(Object key) { load(); - try{ - Object result=null; - IndexItem item=(IndexItem)index.remove(key); - if(item!=null){ + try { + Object result = null; + IndexItem item = (IndexItem)index.remove(key); + if (item != null) { // refresh the index - item=(IndexItem)indexList.refreshEntry(item); - result=getValue(item); - IndexItem prev=indexList.getPrevEntry(item); - IndexItem next=indexList.getNextEntry(item); + item = (IndexItem)indexList.refreshEntry(item); + result = getValue(item); + IndexItem prev = indexList.getPrevEntry(item); + IndexItem next = indexList.getNextEntry(item); indexList.remove(item); - delete(item,prev,next); + delete(item, prev, next); } return result; - }catch(IOException e){ - log.error("Failed trying to remove key: "+key,e); + } catch (IOException e) { + log.error("Failed trying to remove key: " + key, e); throw new RuntimeException(e); } } - public synchronized boolean removeValue(Object o){ + public synchronized boolean removeValue(Object o) { load(); - boolean result=false; - if(o!=null){ - IndexItem item=indexList.getFirst(); - while(item!=null){ - Object value=getValue(item); - if(value!=null&&value.equals(o)){ - result=true; + boolean result = false; + if (o != null) { + IndexItem item = indexList.getFirst(); + while (item != null) { + Object value = getValue(item); + if (value != null && value.equals(o)) { + result = true; // find the key - Object key=getKey(item); - if(key!=null){ + Object key = getKey(item); + if (key != null) { remove(key); } break; } - item=indexList.getNextEntry(item); + item = indexList.getNextEntry(item); } } return result; } - protected synchronized void remove(IndexItem item){ - Object key=getKey(item); - if(key!=null){ + protected synchronized void remove(IndexItem item) { + Object key = getKey(item); + if (key != null) { remove(key); } } @@ -358,15 +360,15 @@ public final class MapContainerImpl extends BaseContainerImpl implements MapCont * * @see org.apache.activemq.kaha.MapContainer#clear() */ - public synchronized void clear(){ + public synchronized void clear() { checkClosed(); - loaded=true; + loaded = true; init(); - if(index!=null){ - try{ + if (index != null) { + try { index.clear(); - }catch(IOException e){ - log.error("Failed trying clear index",e); + } catch (IOException e) { + log.error("Failed trying clear index", e); throw new RuntimeException(e); } } @@ -381,16 +383,16 @@ public final class MapContainerImpl extends BaseContainerImpl implements MapCont * @param value * @return the StoreEntry associated with the entry */ - public synchronized StoreEntry place(Object key,Object value){ + public synchronized StoreEntry place(Object key, Object value) { load(); - try{ + try { remove(key); - IndexItem item=write(key,value); - index.store(key,item); + IndexItem item = write(key, value); + index.store(key, item); indexList.add(item); return item; - }catch(IOException e){ - log.error("Failed trying to place key: "+key,e); + } catch (IOException e) { + log.error("Failed trying to place key: " + key, e); throw new RuntimeException(e); } } @@ -401,47 +403,47 @@ public final class MapContainerImpl extends BaseContainerImpl implements MapCont * @param entry * @throws IOException */ - public synchronized void remove(StoreEntry entry){ + public synchronized void remove(StoreEntry entry) { load(); - IndexItem item=(IndexItem)entry; - if(item!=null){ - Object key=getKey(item); - try{ + IndexItem item = (IndexItem)entry; + if (item != null) { + Object key = getKey(item); + try { index.remove(key); - }catch(IOException e){ - log.error("Failed trying to remove entry: "+entry,e); + } catch (IOException e) { + log.error("Failed trying to remove entry: " + entry, e); throw new RuntimeException(e); } - IndexItem prev=indexList.getPrevEntry(item); - IndexItem next=indexList.getNextEntry(item); + IndexItem prev = indexList.getPrevEntry(item); + IndexItem next = indexList.getNextEntry(item); indexList.remove(item); - delete(item,prev,next); + delete(item, prev, next); } } - public synchronized StoreEntry getFirst(){ + public synchronized StoreEntry getFirst() { load(); return indexList.getFirst(); } - public synchronized StoreEntry getLast(){ + public synchronized StoreEntry getLast() { load(); return indexList.getLast(); } - public synchronized StoreEntry getNext(StoreEntry entry){ + public synchronized StoreEntry getNext(StoreEntry entry) { load(); - IndexItem item=(IndexItem)entry; + IndexItem item = (IndexItem)entry; return indexList.getNextEntry(item); } - public synchronized StoreEntry getPrevious(StoreEntry entry){ + public synchronized StoreEntry getPrevious(StoreEntry entry) { load(); - IndexItem item=(IndexItem)entry; + IndexItem item = (IndexItem)entry; return indexList.getPrevEntry(item); } - public synchronized StoreEntry refresh(StoreEntry entry){ + public synchronized StoreEntry refresh(StoreEntry entry) { load(); return indexList.getEntry(entry); } @@ -452,17 +454,17 @@ public final class MapContainerImpl extends BaseContainerImpl implements MapCont * @param item * @return the value associated with the store entry */ - public synchronized Object getValue(StoreEntry item){ + public synchronized Object getValue(StoreEntry item) { load(); - Object result=null; - if(item!=null){ - try{ + Object result = null; + if (item != null) { + try { // ensure this value is up to date // item=indexList.getEntry(item); - StoreLocation data=item.getValueDataItem(); - result=dataManager.readItem(valueMarshaller,data); - }catch(IOException e){ - log.error("Failed to get value for "+item,e); + StoreLocation data = item.getValueDataItem(); + result = dataManager.readItem(valueMarshaller, data); + } catch (IOException e) { + log.error("Failed to get value for " + item, e); throw new RuntimeStoreException(e); } } @@ -475,50 +477,50 @@ public final class MapContainerImpl extends BaseContainerImpl implements MapCont * @param item * @return the Key Object associated with the StoreEntry */ - public synchronized Object getKey(StoreEntry item){ + public synchronized Object getKey(StoreEntry item) { load(); - Object result=null; - if(item!=null){ - try{ - StoreLocation data=item.getKeyDataItem(); - result=dataManager.readItem(keyMarshaller,data); - }catch(IOException e){ - log.error("Failed to get key for "+item,e); + Object result = null; + if (item != null) { + try { + StoreLocation data = item.getKeyDataItem(); + result = dataManager.readItem(keyMarshaller, data); + } catch (IOException e) { + log.error("Failed to get key for " + item, e); throw new RuntimeStoreException(e); } } return result; } - protected IndexLinkedList getItemList(){ + protected IndexLinkedList getItemList() { return indexList; } - protected synchronized IndexItem write(Object key,Object value){ - IndexItem index=null; - try{ - index=indexManager.createNewIndex(); - StoreLocation data=dataManager.storeDataItem(keyMarshaller,key); + protected synchronized IndexItem write(Object key, Object value) { + IndexItem index = null; + try { + index = indexManager.createNewIndex(); + StoreLocation data = dataManager.storeDataItem(keyMarshaller, key); index.setKeyData(data); - - if(value!=null){ - data=dataManager.storeDataItem(valueMarshaller,value); + + if (value != null) { + data = dataManager.storeDataItem(valueMarshaller, value); index.setValueData(data); } - IndexItem prev=indexList.getLast(); - prev=prev!=null?prev:indexList.getRoot(); - IndexItem next=indexList.getNextEntry(prev); + IndexItem prev = indexList.getLast(); + prev = prev != null ? prev : indexList.getRoot(); + IndexItem next = indexList.getNextEntry(prev); prev.setNextItem(index.getOffset()); index.setPreviousItem(prev.getOffset()); updateIndexes(prev); - if(next!=null){ + if (next != null) { next.setPreviousItem(index.getOffset()); index.setNextItem(next.getOffset()); updateIndexes(next); } storeIndex(index); - }catch(IOException e){ - log.error("Failed to write "+key+" , "+value,e); + } catch (IOException e) { + log.error("Failed to write " + key + " , " + value, e); throw new RuntimeStoreException(e); } return index; diff --git a/activemq-core/src/main/java/org/apache/activemq/kaha/impl/data/DataItem.java b/activemq-core/src/main/java/org/apache/activemq/kaha/impl/data/DataItem.java index 8a2688b5cb..b5459e65a8 100755 --- a/activemq-core/src/main/java/org/apache/activemq/kaha/impl/data/DataItem.java +++ b/activemq-core/src/main/java/org/apache/activemq/kaha/impl/data/DataItem.java @@ -18,27 +18,27 @@ package org.apache.activemq.kaha.impl.data; import org.apache.activemq.kaha.StoreLocation; - /** * A a wrapper for a data in the store * * @version $Revision: 1.2 $ */ -public final class DataItem implements Item, StoreLocation{ - - private int file=(int) POSITION_NOT_SET; - private long offset=POSITION_NOT_SET; +public final class DataItem implements Item, StoreLocation { + + private int file = (int)POSITION_NOT_SET; + private long offset = POSITION_NOT_SET; private int size; - public DataItem(){} - + public DataItem() { + } + DataItem(DataItem item) { this.file = item.file; this.offset = item.offset; this.size = item.size; } - - boolean isValid(){ + + boolean isValid() { return file != POSITION_NOT_SET; } @@ -46,52 +46,52 @@ public final class DataItem implements Item, StoreLocation{ * @return * @see org.apache.activemq.kaha.StoreLocation#getSize() */ - public int getSize(){ + public int getSize() { return size; } /** * @param size The size to set. */ - public void setSize(int size){ - this.size=size; + public void setSize(int size) { + this.size = size; } /** * @return * @see org.apache.activemq.kaha.StoreLocation#getOffset() */ - public long getOffset(){ + public long getOffset() { return offset; } /** * @param offset The offset to set. */ - public void setOffset(long offset){ - this.offset=offset; + public void setOffset(long offset) { + this.offset = offset; } /** * @return * @see org.apache.activemq.kaha.StoreLocation#getFile() */ - public int getFile(){ + public int getFile() { return file; } /** * @param file The file to set. */ - public void setFile(int file){ - this.file=file; + public void setFile(int file) { + this.file = file; } /** * @return a pretty print */ - public String toString(){ - String result="offset = "+offset+", file = " + file + ", size = "+size; + public String toString() { + String result = "offset = " + offset + ", file = " + file + ", size = " + size; return result; } diff --git a/activemq-core/src/main/java/org/apache/activemq/kaha/impl/data/DataManagerImpl.java b/activemq-core/src/main/java/org/apache/activemq/kaha/impl/data/DataManagerImpl.java index 49e4232623..53df600d17 100644 --- a/activemq-core/src/main/java/org/apache/activemq/kaha/impl/data/DataManagerImpl.java +++ b/activemq-core/src/main/java/org/apache/activemq/kaha/impl/data/DataManagerImpl.java @@ -32,284 +32,316 @@ import org.apache.activemq.kaha.impl.index.RedoStoreIndexItem; import org.apache.activemq.util.IOExceptionSupport; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; + /** * Manages DataFiles * * @version $Revision: 1.1.1.1 $ */ public final class DataManagerImpl implements DataManager { - - private static final Log log=LogFactory.getLog(DataManagerImpl.class); - public static final long MAX_FILE_LENGTH=1024*1024*32; - private static final String NAME_PREFIX="data-"; + + private static final Log log = LogFactory.getLog(DataManagerImpl.class); + public static final long MAX_FILE_LENGTH = 1024 * 1024 * 32; + private static final String NAME_PREFIX = "data-"; private final File directory; private final String name; private SyncDataFileReader reader; private SyncDataFileWriter writer; private DataFile currentWriteFile; private long maxFileLength = MAX_FILE_LENGTH; - Map fileMap=new HashMap(); - - public static final int ITEM_HEAD_SIZE=5; // type + length - public static final byte DATA_ITEM_TYPE=1; - public static final byte REDO_ITEM_TYPE=2; - + Map fileMap = new HashMap(); + + public static final int ITEM_HEAD_SIZE = 5; // type + length + public static final byte DATA_ITEM_TYPE = 1; + public static final byte REDO_ITEM_TYPE = 2; + Marshaller redoMarshaller = RedoStoreIndexItem.MARSHALLER; private String dataFilePrefix; - - public DataManagerImpl(File dir, final String name){ - this.directory=dir; - this.name=name; - - dataFilePrefix = NAME_PREFIX+name+"-"; + + public DataManagerImpl(File dir, final String name) { + this.directory = dir; + this.name = name; + + dataFilePrefix = NAME_PREFIX + name + "-"; // build up list of current dataFiles - File[] files=dir.listFiles(new FilenameFilter(){ - public boolean accept(File dir,String n){ - return dir.equals(directory)&&n.startsWith(dataFilePrefix); + File[] files = dir.listFiles(new FilenameFilter() { + public boolean accept(File dir, String n) { + return dir.equals(directory) && n.startsWith(dataFilePrefix); } }); - if(files!=null){ - for(int i=0;imaxFileLength)){ - int nextNum=currentWriteFile!=null?currentWriteFile.getNumber().intValue()+1:1; - if(currentWriteFile!=null&¤tWriteFile.isUnused()){ + synchronized DataFile findSpaceForData(DataItem item) throws IOException { + if (currentWriteFile == null || ((currentWriteFile.getLength() + item.getSize()) > maxFileLength)) { + int nextNum = currentWriteFile != null ? currentWriteFile.getNumber().intValue() + 1 : 1; + if (currentWriteFile != null && currentWriteFile.isUnused()) { removeDataFile(currentWriteFile); } - currentWriteFile=createAndAddDataFile(nextNum); + currentWriteFile = createAndAddDataFile(nextNum); } item.setOffset(currentWriteFile.getLength()); - item.setFile(currentWriteFile.getNumber().intValue()); - currentWriteFile.incrementLength(item.getSize()+ITEM_HEAD_SIZE); + item.setFile(currentWriteFile.getNumber().intValue()); + currentWriteFile.incrementLength(item.getSize() + ITEM_HEAD_SIZE); return currentWriteFile; } - DataFile getDataFile(StoreLocation item) throws IOException{ - Integer key=Integer.valueOf(item.getFile()); - DataFile dataFile=(DataFile) fileMap.get(key); - if(dataFile==null){ + DataFile getDataFile(StoreLocation item) throws IOException { + Integer key = Integer.valueOf(item.getFile()); + DataFile dataFile = (DataFile)fileMap.get(key); + if (dataFile == null) { log.error("Looking for key " + key + " but not found in fileMap: " + fileMap); - throw new IOException("Could not locate data file "+NAME_PREFIX+name+"-"+item.getFile()); + throw new IOException("Could not locate data file " + NAME_PREFIX + name + "-" + item.getFile()); } return dataFile; } - - /* (non-Javadoc) - * @see org.apache.activemq.kaha.impl.data.IDataManager#readItem(org.apache.activemq.kaha.Marshaller, org.apache.activemq.kaha.StoreLocation) - */ - public synchronized Object readItem(Marshaller marshaller, StoreLocation item) throws IOException{ - return getReader().readItem(marshaller,item); + + /* + * (non-Javadoc) + * + * @see org.apache.activemq.kaha.impl.data.IDataManager#readItem(org.apache.activemq.kaha.Marshaller, + * org.apache.activemq.kaha.StoreLocation) + */ + public synchronized Object readItem(Marshaller marshaller, StoreLocation item) throws IOException { + return getReader().readItem(marshaller, item); } - /* (non-Javadoc) - * @see org.apache.activemq.kaha.impl.data.IDataManager#storeDataItem(org.apache.activemq.kaha.Marshaller, java.lang.Object) - */ - public synchronized StoreLocation storeDataItem(Marshaller marshaller, Object payload) throws IOException{ - return getWriter().storeItem(marshaller,payload, DATA_ITEM_TYPE); + /* + * (non-Javadoc) + * + * @see org.apache.activemq.kaha.impl.data.IDataManager#storeDataItem(org.apache.activemq.kaha.Marshaller, + * java.lang.Object) + */ + public synchronized StoreLocation storeDataItem(Marshaller marshaller, Object payload) throws IOException { + return getWriter().storeItem(marshaller, payload, DATA_ITEM_TYPE); } - - /* (non-Javadoc) - * @see org.apache.activemq.kaha.impl.data.IDataManager#storeRedoItem(java.lang.Object) - */ - public synchronized StoreLocation storeRedoItem(Object payload) throws IOException{ + + /* + * (non-Javadoc) + * + * @see org.apache.activemq.kaha.impl.data.IDataManager#storeRedoItem(java.lang.Object) + */ + public synchronized StoreLocation storeRedoItem(Object payload) throws IOException { return getWriter().storeItem(redoMarshaller, payload, REDO_ITEM_TYPE); } - - /* (non-Javadoc) - * @see org.apache.activemq.kaha.impl.data.IDataManager#updateItem(org.apache.activemq.kaha.StoreLocation, org.apache.activemq.kaha.Marshaller, java.lang.Object) - */ - public synchronized void updateItem(StoreLocation location,Marshaller marshaller, Object payload) throws IOException { - getWriter().updateItem((DataItem)location,marshaller,payload,DATA_ITEM_TYPE); + + /* + * (non-Javadoc) + * + * @see org.apache.activemq.kaha.impl.data.IDataManager#updateItem(org.apache.activemq.kaha.StoreLocation, + * org.apache.activemq.kaha.Marshaller, java.lang.Object) + */ + public synchronized void updateItem(StoreLocation location, Marshaller marshaller, Object payload) + throws IOException { + getWriter().updateItem((DataItem)location, marshaller, payload, DATA_ITEM_TYPE); } - /* (non-Javadoc) - * @see org.apache.activemq.kaha.impl.data.IDataManager#recoverRedoItems(org.apache.activemq.kaha.impl.data.RedoListener) - */ - public synchronized void recoverRedoItems(RedoListener listener) throws IOException{ - + /* + * (non-Javadoc) + * + * @see org.apache.activemq.kaha.impl.data.IDataManager#recoverRedoItems(org.apache.activemq.kaha.impl.data.RedoListener) + */ + public synchronized void recoverRedoItems(RedoListener listener) throws IOException { + // Nothing to recover if there is no current file. - if( currentWriteFile == null ) + if (currentWriteFile == null) return; - + DataItem item = new DataItem(); item.setFile(currentWriteFile.getNumber().intValue()); item.setOffset(0); - while( true ) { + while (true) { byte type; try { type = getReader().readDataItemSize(item); } catch (IOException ignore) { - log.trace("End of data file reached at (header was invalid): "+item); + log.trace("End of data file reached at (header was invalid): " + item); return; } - if( type == REDO_ITEM_TYPE ) { + if (type == REDO_ITEM_TYPE) { // Un-marshal the redo item Object object; try { object = readItem(redoMarshaller, item); } catch (IOException e1) { - log.trace("End of data file reached at (payload was invalid): "+item); + log.trace("End of data file reached at (payload was invalid): " + item); return; } try { - + listener.onRedoItem(item, object); - // in case the listener is holding on to item references, copy it + // in case the listener is holding on to item references, + // copy it // so we don't change it behind the listener's back. item = item.copy(); - + } catch (Exception e) { - throw IOExceptionSupport.create("Recovery handler failed: "+e,e); + throw IOExceptionSupport.create("Recovery handler failed: " + e, e); } } // Move to the next item. - item.setOffset(item.getOffset()+ITEM_HEAD_SIZE+item.getSize()); + item.setOffset(item.getOffset() + ITEM_HEAD_SIZE + item.getSize()); } } - - /* (non-Javadoc) - * @see org.apache.activemq.kaha.impl.data.IDataManager#close() - */ - public synchronized void close() throws IOException{ - getWriter().close(); - for(Iterator i=fileMap.values().iterator();i.hasNext();){ - DataFile dataFile=(DataFile) i.next(); + + /* + * (non-Javadoc) + * + * @see org.apache.activemq.kaha.impl.data.IDataManager#close() + */ + public synchronized void close() throws IOException { + getWriter().close(); + for (Iterator i = fileMap.values().iterator(); i.hasNext();) { + DataFile dataFile = (DataFile)i.next(); getWriter().force(dataFile); dataFile.close(); } fileMap.clear(); } - /* (non-Javadoc) - * @see org.apache.activemq.kaha.impl.data.IDataManager#force() - */ - public synchronized void force() throws IOException{ - for(Iterator i=fileMap.values().iterator();i.hasNext();){ - DataFile dataFile=(DataFile) i.next(); + /* + * (non-Javadoc) + * + * @see org.apache.activemq.kaha.impl.data.IDataManager#force() + */ + public synchronized void force() throws IOException { + for (Iterator i = fileMap.values().iterator(); i.hasNext();) { + DataFile dataFile = (DataFile)i.next(); getWriter().force(dataFile); } } - - /* (non-Javadoc) - * @see org.apache.activemq.kaha.impl.data.IDataManager#delete() - */ - public synchronized boolean delete() throws IOException{ - boolean result=true; - for(Iterator i=fileMap.values().iterator();i.hasNext();){ - DataFile dataFile=(DataFile) i.next(); - result&=dataFile.delete(); + /* + * (non-Javadoc) + * + * @see org.apache.activemq.kaha.impl.data.IDataManager#delete() + */ + public synchronized boolean delete() throws IOException { + boolean result = true; + for (Iterator i = fileMap.values().iterator(); i.hasNext();) { + DataFile dataFile = (DataFile)i.next(); + result &= dataFile.delete(); } fileMap.clear(); return result; } - - /* (non-Javadoc) - * @see org.apache.activemq.kaha.impl.data.IDataManager#addInterestInFile(int) - */ - public synchronized void addInterestInFile(int file) throws IOException{ - if(file>=0){ - Integer key=Integer.valueOf(file); - DataFile dataFile=(DataFile) fileMap.get(key); - if(dataFile==null){ - dataFile=createAndAddDataFile(file); + /* + * (non-Javadoc) + * + * @see org.apache.activemq.kaha.impl.data.IDataManager#addInterestInFile(int) + */ + public synchronized void addInterestInFile(int file) throws IOException { + if (file >= 0) { + Integer key = Integer.valueOf(file); + DataFile dataFile = (DataFile)fileMap.get(key); + if (dataFile == null) { + dataFile = createAndAddDataFile(file); } addInterestInFile(dataFile); } } - synchronized void addInterestInFile(DataFile dataFile){ - if(dataFile!=null){ + synchronized void addInterestInFile(DataFile dataFile) { + if (dataFile != null) { dataFile.increment(); } } - /* (non-Javadoc) - * @see org.apache.activemq.kaha.impl.data.IDataManager#removeInterestInFile(int) - */ - public synchronized void removeInterestInFile(int file) throws IOException{ - if(file>=0){ - Integer key=Integer.valueOf(file); - DataFile dataFile=(DataFile) fileMap.get(key); + /* + * (non-Javadoc) + * + * @see org.apache.activemq.kaha.impl.data.IDataManager#removeInterestInFile(int) + */ + public synchronized void removeInterestInFile(int file) throws IOException { + if (file >= 0) { + Integer key = Integer.valueOf(file); + DataFile dataFile = (DataFile)fileMap.get(key); removeInterestInFile(dataFile); } } - synchronized void removeInterestInFile(DataFile dataFile) throws IOException{ - if(dataFile!=null){ - if(dataFile.decrement()<=0){ - if(dataFile!=currentWriteFile){ + synchronized void removeInterestInFile(DataFile dataFile) throws IOException { + if (dataFile != null) { + if (dataFile.decrement() <= 0) { + if (dataFile != currentWriteFile) { removeDataFile(dataFile); } } } } - /* (non-Javadoc) - * @see org.apache.activemq.kaha.impl.data.IDataManager#consolidateDataFiles() - */ - public synchronized void consolidateDataFiles() throws IOException{ - List purgeList=new ArrayList(); - for(Iterator i=fileMap.values().iterator();i.hasNext();){ - DataFile dataFile=(DataFile) i.next(); - if(dataFile.isUnused() && dataFile != currentWriteFile){ + /* + * (non-Javadoc) + * + * @see org.apache.activemq.kaha.impl.data.IDataManager#consolidateDataFiles() + */ + public synchronized void consolidateDataFiles() throws IOException { + List purgeList = new ArrayList(); + for (Iterator i = fileMap.values().iterator(); i.hasNext();) { + DataFile dataFile = (DataFile)i.next(); + if (dataFile.isUnused() && dataFile != currentWriteFile) { purgeList.add(dataFile); } } - for(int i=0;iadd method; included - * only for consistency.) - * @param item + * Appends the given element to the end of this list. (Identical in function + * to the add method; included only for consistency.) + * + * @param item */ public void addLast(IndexItem item); @@ -87,9 +89,11 @@ public interface IndexLinkedList{ /** * Appends the specified element to the end of this list. - * @param item * - * @return true (as per the general contract of Collection.add). + * @param item + * + * @return true (as per the general contract of + * Collection.add). */ public boolean add(IndexItem item); @@ -105,24 +109,27 @@ public interface IndexLinkedList{ * @param index index of element to return. * @return the element at the specified position in this list. * - * @throws IndexOutOfBoundsException if the specified index is is out of range (index < 0 || index >= size()). + * @throws IndexOutOfBoundsException if the specified index is is out of + * range (index < 0 || index >= size()). */ public IndexItem get(int index); /** - * Inserts the specified element at the specified position in this list. Shifts the element currently at that - * position (if any) and any subsequent elements to the right (adds one to their indices). + * Inserts the specified element at the specified position in this list. + * Shifts the element currently at that position (if any) and any subsequent + * elements to the right (adds one to their indices). * * @param index index at which the specified element is to be inserted. * @param element element to be inserted. * * @throws IndexOutOfBoundsException if the specified index is out of range (index < 0 || index > size()). */ - public void add(int index,IndexItem element); + public void add(int index, IndexItem element); /** - * Removes the element at the specified position in this list. Shifts any subsequent elements to the left (subtracts - * one from their indices). Returns the element that was removed from the list. + * Removes the element at the specified position in this list. Shifts any + * subsequent elements to the left (subtracts one from their indices). + * Returns the element that was removed from the list. * * @param index the index of the element to removed. * @return the element previously at the specified position. @@ -133,13 +140,15 @@ public interface IndexLinkedList{ // Search Operations /** - * Returns the index in this list of the first occurrence of the specified element, or -1 if the List does not - * contain this element. More formally, returns the lowest index i such that - * (o==null ? get(i)==null : o.equals(get(i))), or -1 if there is no such index. + * Returns the index in this list of the first occurrence of the specified + * element, or -1 if the List does not contain this element. More formally, + * returns the lowest index i such that + * (o==null ? get(i)==null : o.equals(get(i))), or -1 if there + * is no such index. * * @param o element to search for. - * @return the index in this list of the first occurrence of the specified element, or -1 if the list does not - * contain this element. + * @return the index in this list of the first occurrence of the specified + * element, or -1 if the list does not contain this element. */ public int indexOf(StoreEntry o); @@ -159,22 +168,24 @@ public interface IndexLinkedList{ */ public IndexItem getPrevEntry(IndexItem entry); - /** * remove an entry + * * @param e */ public void remove(IndexItem e); - + /** * Ensure we have the up to date entry - * @param entry + * + * @param entry * @return the entry */ - public StoreEntry getEntry(StoreEntry entry); - + public StoreEntry getEntry(StoreEntry entry); + /** * Update the indexes of a StoreEntry + * * @param current * @return update StoreEntry */ diff --git a/activemq-core/src/main/java/org/apache/activemq/kaha/impl/index/RedoStoreIndexItem.java b/activemq-core/src/main/java/org/apache/activemq/kaha/impl/index/RedoStoreIndexItem.java index 1db43bc156..c1762fc840 100644 --- a/activemq-core/src/main/java/org/apache/activemq/kaha/impl/index/RedoStoreIndexItem.java +++ b/activemq-core/src/main/java/org/apache/activemq/kaha/impl/index/RedoStoreIndexItem.java @@ -35,11 +35,11 @@ public class RedoStoreIndexItem implements Externalizable { } public void writePayload(Object object, DataOutput out) throws IOException { - RedoStoreIndexItem item = (RedoStoreIndexItem) object; + RedoStoreIndexItem item = (RedoStoreIndexItem)object; item.writeExternal(out); } - }; - + }; + private static final long serialVersionUID = -4865508871719676655L; private String indexName; private IndexItem indexItem; @@ -47,47 +47,54 @@ public class RedoStoreIndexItem implements Externalizable { public RedoStoreIndexItem() { } + public RedoStoreIndexItem(String indexName, long offset, IndexItem item) { this.indexName = indexName; - this.offset=offset; + this.offset = offset; this.indexItem = item; } public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { readExternal((DataInput)in); } + public void readExternal(DataInput in) throws IOException { // indexName = in.readUTF(); offset = in.readLong(); indexItem = new IndexItem(); indexItem.read(in); } - + public void writeExternal(ObjectOutput out) throws IOException { writeExternal((DataOutput)out); } + public void writeExternal(DataOutput out) throws IOException { // out.writeUTF(indexName); out.writeLong(offset); indexItem.write(out); } - + public String getIndexName() { return indexName; } + public void setIndexName(String indexName) { this.indexName = indexName; } - + public IndexItem getIndexItem() { return indexItem; } + public void setIndexItem(IndexItem item) { this.indexItem = item; } + public long getOffset() { return offset; } + public void setOffset(long offset) { this.offset = offset; } diff --git a/activemq-core/src/main/java/org/apache/activemq/kaha/impl/index/StoreIndexReader.java b/activemq-core/src/main/java/org/apache/activemq/kaha/impl/index/StoreIndexReader.java index e850ade0ef..f8378a2ff7 100644 --- a/activemq-core/src/main/java/org/apache/activemq/kaha/impl/index/StoreIndexReader.java +++ b/activemq-core/src/main/java/org/apache/activemq/kaha/impl/index/StoreIndexReader.java @@ -20,40 +20,41 @@ import java.io.IOException; import java.io.RandomAccessFile; import org.apache.activemq.util.DataByteArrayInputStream; + /** * Optimized Store reader * * @version $Revision: 1.1.1.1 $ */ -class StoreIndexReader{ +class StoreIndexReader { protected RandomAccessFile file; protected DataByteArrayInputStream dataIn; - protected byte[] buffer=new byte[IndexItem.INDEX_SIZE]; + protected byte[] buffer = new byte[IndexItem.INDEX_SIZE]; /** * Construct a Store reader * * @param file */ - StoreIndexReader(RandomAccessFile file){ - this.file=file; - this.dataIn=new DataByteArrayInputStream(); + StoreIndexReader(RandomAccessFile file) { + this.file = file; + this.dataIn = new DataByteArrayInputStream(); } - protected IndexItem readItem(long offset) throws IOException{ + protected IndexItem readItem(long offset) throws IOException { file.seek(offset); file.readFully(buffer); dataIn.restart(buffer); - IndexItem result=new IndexItem(); + IndexItem result = new IndexItem(); result.setOffset(offset); result.read(dataIn); return result; } - - void updateIndexes(IndexItem indexItem) throws IOException{ - if (indexItem != null){ + + void updateIndexes(IndexItem indexItem) throws IOException { + if (indexItem != null) { file.seek(indexItem.getOffset()); - file.readFully(buffer,0,IndexItem.INDEXES_ONLY_SIZE); + file.readFully(buffer, 0, IndexItem.INDEXES_ONLY_SIZE); dataIn.restart(buffer); indexItem.readIndexes(dataIn); } diff --git a/activemq-core/src/main/java/org/apache/activemq/kaha/impl/index/StoreIndexWriter.java b/activemq-core/src/main/java/org/apache/activemq/kaha/impl/index/StoreIndexWriter.java index e8e6666bc6..5cb412a48b 100644 --- a/activemq-core/src/main/java/org/apache/activemq/kaha/impl/index/StoreIndexWriter.java +++ b/activemq-core/src/main/java/org/apache/activemq/kaha/impl/index/StoreIndexWriter.java @@ -21,13 +21,14 @@ import java.io.RandomAccessFile; import org.apache.activemq.kaha.impl.DataManager; import org.apache.activemq.util.DataByteArrayOutputStream; + /** * Optimized Store writer * * @version $Revision: 1.1.1.1 $ */ -class StoreIndexWriter{ - +class StoreIndexWriter { + protected final DataByteArrayOutputStream dataOut = new DataByteArrayOutputStream(); protected final RandomAccessFile file; protected final String name; @@ -38,46 +39,46 @@ class StoreIndexWriter{ * * @param file */ - StoreIndexWriter(RandomAccessFile file){ + StoreIndexWriter(RandomAccessFile file) { this(file, null, null); } public StoreIndexWriter(RandomAccessFile file, String indexName, DataManager redoLog) { - this.file=file; + this.file = file; this.name = indexName; this.redoLog = redoLog; } - void storeItem(IndexItem indexItem) throws IOException{ - - if( redoLog!=null ) { + void storeItem(IndexItem indexItem) throws IOException { + + if (redoLog != null) { RedoStoreIndexItem redo = new RedoStoreIndexItem(name, indexItem.getOffset(), indexItem); redoLog.storeRedoItem(redo); } - + dataOut.reset(); indexItem.write(dataOut); file.seek(indexItem.getOffset()); - file.write(dataOut.getData(),0,IndexItem.INDEX_SIZE); + file.write(dataOut.getData(), 0, IndexItem.INDEX_SIZE); } - - void updateIndexes(IndexItem indexItem) throws IOException{ - if( redoLog!=null ) { + + void updateIndexes(IndexItem indexItem) throws IOException { + if (redoLog != null) { RedoStoreIndexItem redo = new RedoStoreIndexItem(name, indexItem.getOffset(), indexItem); redoLog.storeRedoItem(redo); } - + dataOut.reset(); indexItem.updateIndexes(dataOut); file.seek(indexItem.getOffset()); - file.write(dataOut.getData(),0,IndexItem.INDEXES_ONLY_SIZE); + file.write(dataOut.getData(), 0, IndexItem.INDEXES_ONLY_SIZE); } public void redoStoreItem(RedoStoreIndexItem redo) throws IOException { dataOut.reset(); redo.getIndexItem().write(dataOut); file.seek(redo.getOffset()); - file.write(dataOut.getData(),0,IndexItem.INDEX_SIZE); + file.write(dataOut.getData(), 0, IndexItem.INDEX_SIZE); } - + } diff --git a/activemq-core/src/main/java/org/apache/activemq/kaha/impl/index/VMIndex.java b/activemq-core/src/main/java/org/apache/activemq/kaha/impl/index/VMIndex.java index a8ba9327b1..fed0ffc6f8 100644 --- a/activemq-core/src/main/java/org/apache/activemq/kaha/impl/index/VMIndex.java +++ b/activemq-core/src/main/java/org/apache/activemq/kaha/impl/index/VMIndex.java @@ -28,19 +28,20 @@ import org.apache.commons.logging.LogFactory; * * @version $Revision: 1.2 $ */ -public class VMIndex implements Index{ - private static final Log log=LogFactory.getLog(VMIndex.class); +public class VMIndex implements Index { + private static final Log log = LogFactory.getLog(VMIndex.class); private IndexManager indexManager; - private Map map=new HashMap(); + private Map map = new HashMap(); public VMIndex(IndexManager manager) { - this.indexManager= manager; + this.indexManager = manager; } + /** * * @see org.apache.activemq.kaha.impl.index.Index#clear() */ - public void clear(){ + public void clear() { map.clear(); } @@ -49,7 +50,7 @@ public class VMIndex implements Index{ * @return true if the index contains the key * @see org.apache.activemq.kaha.impl.index.Index#containsKey(java.lang.Object) */ - public boolean containsKey(Object key){ + public boolean containsKey(Object key) { return map.containsKey(key); } @@ -58,14 +59,14 @@ public class VMIndex implements Index{ * @return store entry * @see org.apache.activemq.kaha.impl.index.Index#removeKey(java.lang.Object) */ - public StoreEntry remove(Object key){ - StoreEntry result = map.remove(key); + public StoreEntry remove(Object key) { + StoreEntry result = map.remove(key); if (result != null) { - try{ - result=indexManager.refreshIndex((IndexItem)result); - }catch(IOException e){ - log.error("Failed to refresh entry",e); - throw new RuntimeException("Failed to refresh entry"); + try { + result = indexManager.refreshIndex((IndexItem)result); + } catch (IOException e) { + log.error("Failed to refresh entry", e); + throw new RuntimeException("Failed to refresh entry"); } } return result; @@ -77,22 +78,22 @@ public class VMIndex implements Index{ * @see org.apache.activemq.kaha.impl.index.Index#store(java.lang.Object, * org.apache.activemq.kaha.impl.index.IndexItem) */ - public void store(Object key,StoreEntry entry){ - map.put(key,entry); + public void store(Object key, StoreEntry entry) { + map.put(key, entry); } /** * @param key * @return the entry */ - public StoreEntry get(Object key){ - StoreEntry result = map.get(key); + public StoreEntry get(Object key) { + StoreEntry result = map.get(key); if (result != null) { - try{ - result=indexManager.refreshIndex((IndexItem)result); - }catch(IOException e){ - log.error("Failed to refresh entry",e); - throw new RuntimeException("Failed to refresh entry"); + try { + result = indexManager.refreshIndex((IndexItem)result); + } catch (IOException e) { + log.error("Failed to refresh entry", e); + throw new RuntimeException("Failed to refresh entry"); } } return result; @@ -101,24 +102,23 @@ public class VMIndex implements Index{ /** * @return true if the index is transient */ - public boolean isTransient(){ + public boolean isTransient() { return true; } /** * load indexes */ - public void load(){ + public void load() { } /** * unload indexes */ - public void unload(){ + public void unload() { map.clear(); } - - - public void setKeyMarshaller(Marshaller marshaller){ + + public void setKeyMarshaller(Marshaller marshaller) { } } diff --git a/activemq-core/src/main/java/org/apache/activemq/kaha/impl/index/hash/HashEntry.java b/activemq-core/src/main/java/org/apache/activemq/kaha/impl/index/hash/HashEntry.java index e759389998..2b90c6a50f 100644 --- a/activemq-core/src/main/java/org/apache/activemq/kaha/impl/index/hash/HashEntry.java +++ b/activemq-core/src/main/java/org/apache/activemq/kaha/impl/index/hash/HashEntry.java @@ -24,75 +24,75 @@ import org.apache.activemq.kaha.Marshaller; * * @version $Revision: 1.1.1.1 $ */ -class HashEntry implements Comparable{ +class HashEntry implements Comparable { - static final int NOT_SET=-1; + static final int NOT_SET = -1; private Comparable key; private long indexOffset; - public int compareTo(Object o){ - if(o instanceof HashEntry){ - HashEntry other=(HashEntry)o; + public int compareTo(Object o) { + if (o instanceof HashEntry) { + HashEntry other = (HashEntry)o; return key.compareTo(other.key); - }else{ + } else { return key.compareTo(o); } } - public boolean equals(Object o){ - return compareTo(o)==0; + public boolean equals(Object o) { + return compareTo(o) == 0; } - public int hashCode(){ + public int hashCode() { return key.hashCode(); } - public String toString(){ - return "HashEntry("+key+","+indexOffset+")"; + public String toString() { + return "HashEntry(" + key + "," + indexOffset + ")"; } - HashEntry copy(){ - HashEntry copy=new HashEntry(); - copy.key=this.key; - copy.indexOffset=this.indexOffset; + HashEntry copy() { + HashEntry copy = new HashEntry(); + copy.key = this.key; + copy.indexOffset = this.indexOffset; return copy; } /** * @return the key */ - Comparable getKey(){ + Comparable getKey() { return this.key; } /** * @param key the key to set */ - void setKey(Comparable key){ - this.key=key; + void setKey(Comparable key) { + this.key = key; } /** * @return the indexOffset */ - long getIndexOffset(){ + long getIndexOffset() { return this.indexOffset; } /** * @param indexOffset the indexOffset to set */ - void setIndexOffset(long indexOffset){ - this.indexOffset=indexOffset; + void setIndexOffset(long indexOffset) { + this.indexOffset = indexOffset; } - void write(Marshaller keyMarshaller,DataOutput dataOut) throws IOException{ + void write(Marshaller keyMarshaller, DataOutput dataOut) throws IOException { dataOut.writeLong(indexOffset); - keyMarshaller.writePayload(key,dataOut); + keyMarshaller.writePayload(key, dataOut); } - void read(Marshaller keyMarshaller,DataInput dataIn) throws IOException{ - indexOffset=dataIn.readLong(); - key=(Comparable)keyMarshaller.readPayload(dataIn); + void read(Marshaller keyMarshaller, DataInput dataIn) throws IOException { + indexOffset = dataIn.readLong(); + key = (Comparable)keyMarshaller.readPayload(dataIn); } } diff --git a/activemq-core/src/main/java/org/apache/activemq/kaha/impl/index/tree/TreeEntry.java b/activemq-core/src/main/java/org/apache/activemq/kaha/impl/index/tree/TreeEntry.java index 657e738962..e092927439 100644 --- a/activemq-core/src/main/java/org/apache/activemq/kaha/impl/index/tree/TreeEntry.java +++ b/activemq-core/src/main/java/org/apache/activemq/kaha/impl/index/tree/TreeEntry.java @@ -24,123 +24,120 @@ import org.apache.activemq.kaha.Marshaller; * * @version $Revision: 1.1.1.1 $ */ -class TreeEntry implements Comparable{ +class TreeEntry implements Comparable { - static final int NOT_SET=-1; + static final int NOT_SET = -1; private Comparable key; private long indexOffset; - private long prevPageId=NOT_SET; - private long nextPageId=NOT_SET; + private long prevPageId = NOT_SET; + private long nextPageId = NOT_SET; - public int compareTo(Object o){ - if(o instanceof TreeEntry){ - TreeEntry other=(TreeEntry)o; + public int compareTo(Object o) { + if (o instanceof TreeEntry) { + TreeEntry other = (TreeEntry)o; return key.compareTo(other.key); - }else{ + } else { return key.compareTo(o); } } - public boolean equals(Object o){ - return compareTo(o)==0; + public boolean equals(Object o) { + return compareTo(o) == 0; } - public int hashCode(){ + public int hashCode() { return key.hashCode(); } - public String toString(){ - return "TreeEntry("+key+","+indexOffset+")prev="+prevPageId+",next="+nextPageId; + public String toString() { + return "TreeEntry(" + key + "," + indexOffset + ")prev=" + prevPageId + ",next=" + nextPageId; } - void reset(){ - prevPageId=nextPageId=NOT_SET; + void reset() { + prevPageId = nextPageId = NOT_SET; } - TreeEntry copy(){ - TreeEntry copy=new TreeEntry(); - copy.key=this.key; - copy.indexOffset=this.indexOffset; - copy.prevPageId=this.prevPageId; - copy.nextPageId=this.nextPageId; + TreeEntry copy() { + TreeEntry copy = new TreeEntry(); + copy.key = this.key; + copy.indexOffset = this.indexOffset; + copy.prevPageId = this.prevPageId; + copy.nextPageId = this.nextPageId; return copy; } /** * @return the key */ - Comparable getKey(){ + Comparable getKey() { return this.key; } /** * @param key the key to set */ - void setKey(Comparable key){ - this.key=key; + void setKey(Comparable key) { + this.key = key; } /** * @return the nextPageId */ - long getNextPageId(){ + long getNextPageId() { return this.nextPageId; } /** * @param nextPageId the nextPageId to set */ - void setNextPageId(long nextPageId){ - this.nextPageId=nextPageId; + void setNextPageId(long nextPageId) { + this.nextPageId = nextPageId; } /** * @return the prevPageId */ - long getPrevPageId(){ + long getPrevPageId() { return this.prevPageId; } /** * @param prevPageId the prevPageId to set */ - void setPrevPageId(long prevPageId){ - this.prevPageId=prevPageId; + void setPrevPageId(long prevPageId) { + this.prevPageId = prevPageId; } - + /** * @return the indexOffset */ - long getIndexOffset(){ + long getIndexOffset() { return this.indexOffset; } - /** * @param indexOffset the indexOffset to set */ - void setIndexOffset(long indexOffset){ - this.indexOffset=indexOffset; + void setIndexOffset(long indexOffset) { + this.indexOffset = indexOffset; } - boolean hasChildPagesReferences(){ - return prevPageId!=NOT_SET||nextPageId!=NOT_SET; + boolean hasChildPagesReferences() { + return prevPageId != NOT_SET || nextPageId != NOT_SET; } - void write(Marshaller keyMarshaller,DataOutput dataOut) throws IOException{ - keyMarshaller.writePayload(key,dataOut); + void write(Marshaller keyMarshaller, DataOutput dataOut) throws IOException { + keyMarshaller.writePayload(key, dataOut); dataOut.writeLong(indexOffset); dataOut.writeLong(nextPageId); dataOut.writeLong(prevPageId); } - void read(Marshaller keyMarshaller,DataInput dataIn) throws IOException{ - key=(Comparable)keyMarshaller.readPayload(dataIn); - indexOffset=dataIn.readLong(); - nextPageId=dataIn.readLong(); - prevPageId=dataIn.readLong(); + void read(Marshaller keyMarshaller, DataInput dataIn) throws IOException { + key = (Comparable)keyMarshaller.readPayload(dataIn); + indexOffset = dataIn.readLong(); + nextPageId = dataIn.readLong(); + prevPageId = dataIn.readLong(); } - - } diff --git a/activemq-core/src/main/java/org/apache/activemq/kaha/impl/index/tree/TreePageEntry.java b/activemq-core/src/main/java/org/apache/activemq/kaha/impl/index/tree/TreePageEntry.java index 29a8f62763..4515c5f899 100644 --- a/activemq-core/src/main/java/org/apache/activemq/kaha/impl/index/tree/TreePageEntry.java +++ b/activemq-core/src/main/java/org/apache/activemq/kaha/impl/index/tree/TreePageEntry.java @@ -15,81 +15,77 @@ package org.apache.activemq.kaha.impl.index.tree; /** -* A conglomarate used for return results from a tree lookup -* -* @version $Revision: 1.1.1.1 $ -*/ -class TreePageEntry{ + * A conglomarate used for return results from a tree lookup + * + * @version $Revision: 1.1.1.1 $ + */ +class TreePageEntry { private TreeEntry treeEntry; private TreePage treePage; private TreePage.Flavour flavour; private int index = -1; - TreePageEntry(TreeEntry treeEntry,TreePage treePage,TreePage.Flavour flavour, int index){ + TreePageEntry(TreeEntry treeEntry, TreePage treePage, TreePage.Flavour flavour, int index) { this.treeEntry = treeEntry; - this.treePage=treePage; - this.flavour=flavour; + this.treePage = treePage; + this.flavour = flavour; this.index = index; } /** * @return the flavour */ - TreePage.Flavour getFlavour(){ + TreePage.Flavour getFlavour() { return this.flavour; } /** * @param flavour the flavour to set */ - void setFlavour(TreePage.Flavour flavour){ - this.flavour=flavour; + void setFlavour(TreePage.Flavour flavour) { + this.flavour = flavour; } /** * @return the treePage */ - TreePage getTreePage(){ + TreePage getTreePage() { return this.treePage; } /** * @param treePage the treePage to set */ - void setTreePage(TreePage treePage){ - this.treePage=treePage; + void setTreePage(TreePage treePage) { + this.treePage = treePage; } - /** * @return the index */ - public int getIndex(){ + public int getIndex() { return this.index; } - /** * @param index the index to set */ - public void setIndex(int index){ - this.index=index; + public void setIndex(int index) { + this.index = index; } - /** * @return the treeEntry */ - public TreeEntry getTreeEntry(){ + public TreeEntry getTreeEntry() { return this.treeEntry; } - /** * @param treeEntry the treeEntry to set */ - public void setTreeEntry(TreeEntry treeEntry){ - this.treeEntry=treeEntry; + public void setTreeEntry(TreeEntry treeEntry) { + this.treeEntry = treeEntry; } } diff --git a/activemq-core/src/main/java/org/apache/activemq/management/CountStatisticImpl.java b/activemq-core/src/main/java/org/apache/activemq/management/CountStatisticImpl.java index b30cfb2f43..abd743a89d 100755 --- a/activemq-core/src/main/java/org/apache/activemq/management/CountStatisticImpl.java +++ b/activemq-core/src/main/java/org/apache/activemq/management/CountStatisticImpl.java @@ -22,7 +22,7 @@ import java.util.concurrent.atomic.AtomicLong; /** * A count statistic implementation - * + * * @version $Revision: 1.3 $ */ public class CountStatisticImpl extends StatisticImpl implements CountStatistic { @@ -53,50 +53,50 @@ public class CountStatisticImpl extends StatisticImpl implements CountStatistic } public void setCount(long count) { - if(isEnabled()) { + if (isEnabled()) { counter.set(count); - } + } } public void add(long amount) { - if (isEnabled()) { - counter.addAndGet(amount); - updateSampleTime(); - if (parent != null) { - parent.add(amount); - } - } + if (isEnabled()) { + counter.addAndGet(amount); + updateSampleTime(); + if (parent != null) { + parent.add(amount); + } + } } public void increment() { - if (isEnabled()) { - counter.incrementAndGet(); - updateSampleTime(); - if (parent != null) { - parent.increment(); - } - } - } + if (isEnabled()) { + counter.incrementAndGet(); + updateSampleTime(); + if (parent != null) { + parent.increment(); + } + } + } - public void subtract(long amount) { - if (isEnabled()) { - counter.addAndGet(-amount); - updateSampleTime(); - if (parent != null) { - parent.subtract(amount); - } - } - } + public void subtract(long amount) { + if (isEnabled()) { + counter.addAndGet(-amount); + updateSampleTime(); + if (parent != null) { + parent.subtract(amount); + } + } + } - public void decrement() { - if (isEnabled()) { - counter.decrementAndGet(); - updateSampleTime(); - if (parent != null) { - parent.decrement(); - } - } - } + public void decrement() { + if (isEnabled()) { + counter.decrementAndGet(); + updateSampleTime(); + if (parent != null) { + parent.decrement(); + } + } + } public CountStatisticImpl getParent() { return parent; @@ -111,25 +111,27 @@ public class CountStatisticImpl extends StatisticImpl implements CountStatistic buffer.append(Long.toString(counter.get())); super.appendFieldDescription(buffer); } - + /** - * @return the average time period that elapses between counter increments since the last reset. + * @return the average time period that elapses between counter increments + * since the last reset. */ public double getPeriod() { double count = counter.get(); - if( count == 0 ) + if (count == 0) return 0; double time = (System.currentTimeMillis() - getStartTime()); - return (time/(count*1000.0)); + return (time / (count * 1000.0)); } - + /** - * @return the number of times per second that the counter is incrementing since the last reset. + * @return the number of times per second that the counter is incrementing + * since the last reset. */ public double getFrequency() { double count = counter.get(); double time = (System.currentTimeMillis() - getStartTime()); - return (count*1000.0/time); + return (count * 1000.0 / time); } } diff --git a/activemq-core/src/main/java/org/apache/activemq/management/PollCountStatisticImpl.java b/activemq-core/src/main/java/org/apache/activemq/management/PollCountStatisticImpl.java index 70f6395a53..9941dfa0ef 100755 --- a/activemq-core/src/main/java/org/apache/activemq/management/PollCountStatisticImpl.java +++ b/activemq-core/src/main/java/org/apache/activemq/management/PollCountStatisticImpl.java @@ -23,7 +23,7 @@ import javax.management.j2ee.statistics.CountStatistic; /** * A count statistic implementation - * + * * @version $Revision$ */ public class PollCountStatisticImpl extends StatisticImpl implements CountStatistic { @@ -49,61 +49,63 @@ public class PollCountStatisticImpl extends StatisticImpl implements CountStatis } public void setParent(PollCountStatisticImpl parent) { - if( this.parent !=null ) { + if (this.parent != null) { this.parent.removeChild(this); } this.parent = parent; - if( this.parent !=null ) { + if (this.parent != null) { this.parent.addChild(this); } } synchronized private void removeChild(PollCountStatisticImpl child) { - if( children!=null ) + if (children != null) children.remove(child); } synchronized private void addChild(PollCountStatisticImpl child) { - if( children==null ) + if (children == null) children = new ArrayList(); children.add(child); } synchronized public long getCount() { - if ( children == null ) + if (children == null) return 0; - long count=0; + long count = 0; for (Iterator iter = children.iterator(); iter.hasNext();) { - PollCountStatisticImpl child = (PollCountStatisticImpl) iter.next(); + PollCountStatisticImpl child = (PollCountStatisticImpl)iter.next(); count += child.getCount(); } return count; } - + protected void appendFieldDescription(StringBuffer buffer) { buffer.append(" count: "); buffer.append(Long.toString(getCount())); super.appendFieldDescription(buffer); } - + /** - * @return the average time period that elapses between counter increments since the last reset. + * @return the average time period that elapses between counter increments + * since the last reset. */ public double getPeriod() { double count = getCount(); - if( count == 0 ) + if (count == 0) return 0; double time = (System.currentTimeMillis() - getStartTime()); - return (time/(count*1000.0)); + return (time / (count * 1000.0)); } - + /** - * @return the number of times per second that the counter is incrementing since the last reset. + * @return the number of times per second that the counter is incrementing + * since the last reset. */ public double getFrequency() { double count = getCount(); double time = (System.currentTimeMillis() - getStartTime()); - return (count*1000.0/time); + return (count * 1000.0 / time); } } diff --git a/activemq-core/src/main/java/org/apache/activemq/memory/Cache.java b/activemq-core/src/main/java/org/apache/activemq/memory/Cache.java index 671687d21f..aec93f999a 100755 --- a/activemq-core/src/main/java/org/apache/activemq/memory/Cache.java +++ b/activemq-core/src/main/java/org/apache/activemq/memory/Cache.java @@ -16,48 +16,49 @@ */ package org.apache.activemq.memory; - /** * Defines the interface used to cache messages. - * + * * @version $Revision$ */ public interface Cache { - - /** - * Gets an object that was previously put into this object. - * - * @param msgid - * @return null if the object was not previously put or if the object has expired out of the cache. - */ - public Object get(Object key); - - /** - * Puts an object into the cache. - * - * @param messageID - * @param message - */ - public Object put(Object key, Object value); - - /** - * Removes an object from the cache. - * - * @param messageID - * @return the object associated with the key if it was still in the cache. - */ - public Object remove(Object key); /** - * Lets a cache know it will not be used any further and that it can release + * Gets an object that was previously put into this object. + * + * @param msgid + * @return null if the object was not previously put or if the object has + * expired out of the cache. + */ + public Object get(Object key); + + /** + * Puts an object into the cache. + * + * @param messageID + * @param message + */ + public Object put(Object key, Object value); + + /** + * Removes an object from the cache. + * + * @param messageID + * @return the object associated with the key if it was still in the cache. + */ + public Object remove(Object key); + + /** + * Lets a cache know it will not be used any further and that it can release * acquired resources */ public void close(); /** * How big is the cache right now? + * * @return */ public int size(); - + } diff --git a/activemq-core/src/main/java/org/apache/activemq/memory/CacheEntry.java b/activemq-core/src/main/java/org/apache/activemq/memory/CacheEntry.java index 2589ab27d2..0c085588a2 100755 --- a/activemq-core/src/main/java/org/apache/activemq/memory/CacheEntry.java +++ b/activemq-core/src/main/java/org/apache/activemq/memory/CacheEntry.java @@ -17,16 +17,16 @@ package org.apache.activemq.memory; public class CacheEntry { - - public final Object key; + + public final Object key; public final Object value; - + public CacheEntry next; public CacheEntry previous; public CacheEntryList owner; - + public CacheEntry(Object key, Object value) { - this.key=key; + this.key = key; this.value = value; } @@ -36,19 +36,19 @@ public class CacheEntry { * @return false if you are trying to remove the tail pointer. */ public boolean remove() { - + // Cannot remove if this is a tail pointer. // Or not linked. - if( owner==null || this.key==null || this.next==null ) + if (owner == null || this.key == null || this.next == null) return false; - - synchronized( owner.tail ) { + + synchronized (owner.tail) { this.next.previous = this.previous; this.previous.next = this.next; this.owner = null; this.next = this.previous = null; } - + return true; } diff --git a/activemq-core/src/main/java/org/apache/activemq/memory/CacheEntryList.java b/activemq-core/src/main/java/org/apache/activemq/memory/CacheEntryList.java index 2bf8f85657..7de526b9d9 100755 --- a/activemq-core/src/main/java/org/apache/activemq/memory/CacheEntryList.java +++ b/activemq-core/src/main/java/org/apache/activemq/memory/CacheEntryList.java @@ -17,37 +17,37 @@ package org.apache.activemq.memory; /** - * Maintains a simple linked list of CacheEntry objects. It is thread safe. + * Maintains a simple linked list of CacheEntry objects. It is thread safe. * * @version $Revision$ */ public class CacheEntryList { - + // Points at the tail of the CacheEntry list public final CacheEntry tail = new CacheEntry(null, null); - + public CacheEntryList() { tail.next = tail.previous = tail; } - + public void add(CacheEntry ce) { addEntryBefore(tail, ce); } - + private void addEntryBefore(CacheEntry position, CacheEntry ce) { - assert ce.key!=null && ce.next==null && ce.owner==null; - - synchronized( tail ) { - ce.owner=this; + assert ce.key != null && ce.next == null && ce.owner == null; + + synchronized (tail) { + ce.owner = this; ce.next = position; - ce.previous = position.previous; + ce.previous = position.previous; ce.previous.next = ce; ce.next.previous = ce; } } - + public void clear() { - synchronized( tail ) { + synchronized (tail) { tail.next = tail.previous = tail; } } @@ -56,19 +56,19 @@ public class CacheEntryList { return new CacheEvictor() { public CacheEntry evictCacheEntry() { CacheEntry rc; - synchronized( tail ) { + synchronized (tail) { rc = tail.next; } return rc.remove() ? rc : null; } }; } - + public CacheEvictor createLIFOCacheEvictor() { return new CacheEvictor() { public CacheEntry evictCacheEntry() { CacheEntry rc; - synchronized( tail ) { + synchronized (tail) { rc = tail.previous; } return rc.remove() ? rc : null; diff --git a/activemq-core/src/main/java/org/apache/activemq/memory/CacheEvictionUsageListener.java b/activemq-core/src/main/java/org/apache/activemq/memory/CacheEvictionUsageListener.java index 9979d66453..bfb2e9e38c 100755 --- a/activemq-core/src/main/java/org/apache/activemq/memory/CacheEvictionUsageListener.java +++ b/activemq-core/src/main/java/org/apache/activemq/memory/CacheEvictionUsageListener.java @@ -28,39 +28,40 @@ import org.apache.commons.logging.LogFactory; import java.util.concurrent.CopyOnWriteArrayList; public class CacheEvictionUsageListener implements UsageListener { - + private final static Log log = LogFactory.getLog(CacheEvictionUsageListener.class); - + private final CopyOnWriteArrayList evictors = new CopyOnWriteArrayList(); private final int usageHighMark; private final int usageLowMark; private final TaskRunner evictionTask; private final UsageManager usageManager; - - public CacheEvictionUsageListener(UsageManager usageManager, int usageHighMark, int usageLowMark, TaskRunnerFactory taskRunnerFactory) { + + public CacheEvictionUsageListener(UsageManager usageManager, int usageHighMark, int usageLowMark, + TaskRunnerFactory taskRunnerFactory) { this.usageManager = usageManager; this.usageHighMark = usageHighMark; this.usageLowMark = usageLowMark; - evictionTask = taskRunnerFactory.createTaskRunner(new Task(){ + evictionTask = taskRunnerFactory.createTaskRunner(new Task() { public boolean iterate() { return evictMessages(); } - }, "Cache Evictor: "+System.identityHashCode(this)); + }, "Cache Evictor: " + System.identityHashCode(this)); } - + boolean evictMessages() { // Try to take the memory usage down below the low mark. - try { - log.debug("Evicting cache memory usage: "+usageManager.getPercentUsage()); - + try { + log.debug("Evicting cache memory usage: " + usageManager.getPercentUsage()); + LinkedList list = new LinkedList(evictors); - while (list.size()>0 && usageManager.getPercentUsage() > usageLowMark) { - + while (list.size() > 0 && usageManager.getPercentUsage() > usageLowMark) { + // Evenly evict messages from all evictors for (Iterator iter = list.iterator(); iter.hasNext();) { - CacheEvictor evictor = (CacheEvictor) iter.next(); - if( evictor.evictCacheEntry() == null ) + CacheEvictor evictor = (CacheEvictor)iter.next(); + if (evictor.evictCacheEntry() == null) iter.remove(); } } @@ -68,11 +69,11 @@ public class CacheEvictionUsageListener implements UsageListener { } return false; } - + public void onMemoryUseChanged(UsageManager memoryManager, int oldPercentUsage, int newPercentUsage) { // Do we need to start evicting cache entries? Usage > than the // high mark - if (oldPercentUsage < newPercentUsage && memoryManager.getPercentUsage() >= usageHighMark) { + if (oldPercentUsage < newPercentUsage && memoryManager.getPercentUsage() >= usageHighMark) { try { evictionTask.wakeup(); } catch (InterruptedException e) { @@ -80,11 +81,11 @@ public class CacheEvictionUsageListener implements UsageListener { } } } - + public void add(CacheEvictor evictor) { evictors.add(evictor); } - + public void remove(CacheEvictor evictor) { evictors.remove(evictor); } diff --git a/activemq-core/src/main/java/org/apache/activemq/memory/UsageManager.java b/activemq-core/src/main/java/org/apache/activemq/memory/UsageManager.java index 0ce4d1e16d..8c50c529e9 100755 --- a/activemq-core/src/main/java/org/apache/activemq/memory/UsageManager.java +++ b/activemq-core/src/main/java/org/apache/activemq/memory/UsageManager.java @@ -26,10 +26,9 @@ import org.apache.activemq.Service; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; - /** - * Used to keep track of how much of something is being used so that - * a productive working set usage can be controlled. + * Used to keep track of how much of something is being used so that a + * productive working set usage can be controlled. * * Main use case is manage memory usage. * @@ -37,24 +36,27 @@ import org.apache.commons.logging.LogFactory; * * @version $Revision: 1.3 $ */ -public class UsageManager implements Service{ +public class UsageManager implements Service { private static final Log log = LogFactory.getLog(UsageManager.class); - + private final UsageManager parent; private long limit; private long usage; - + private int percentUsage; - private int percentUsageMinDelta=1; - + private int percentUsageMinDelta = 1; + private final Object usageMutex = new Object(); - + private final CopyOnWriteArrayList listeners = new CopyOnWriteArrayList(); - + private boolean sendFailIfNoSpace; - /** True if someone called setSendFailIfNoSpace() on this particular usage manager */ + /** + * True if someone called setSendFailIfNoSpace() on this particular usage + * manager + */ private boolean sendFailIfNoSpaceExplicitySet; private final boolean debug = log.isDebugEnabled(); private String name = ""; @@ -63,45 +65,46 @@ public class UsageManager implements Service{ private final LinkedList callbacks = new LinkedList(); public UsageManager() { - this(null,"default"); + this(null, "default"); } - + /** - * Create the memory manager linked to a parent. When the memory manager is linked to - * a parent then when usage increased or decreased, the parent's usage is also increased - * or decreased. + * Create the memory manager linked to a parent. When the memory manager is + * linked to a parent then when usage increased or decreased, the parent's + * usage is also increased or decreased. * * @param parent */ public UsageManager(UsageManager parent) { - this(parent,"default"); + this(parent, "default"); } - + public UsageManager(String name) { - this(null,name); + this(null, name); } - - public UsageManager(UsageManager parent,String name) { - this(parent,name,1.0f); + + public UsageManager(UsageManager parent, String name) { + this(parent, name, 1.0f); } - + public UsageManager(UsageManager parent, String name, float portion) { this.parent = parent; - this.usagePortion=portion; + this.usagePortion = portion; if (parent != null) { - this.limit=(long)(parent.limit * portion); - this.name= parent.name + ":"; + this.limit = (long)(parent.limit * portion); + this.name = parent.name + ":"; } this.name += name; } - + /** - * Tries to increase the usage by value amount but blocks if this object - * is currently full. - * @throws InterruptedException + * Tries to increase the usage by value amount but blocks if this object is + * currently full. + * + * @throws InterruptedException */ public void enqueueUsage(long value) throws InterruptedException { - waitForSpace(); + waitForSpace(); increaseUsage(value); } @@ -109,10 +112,10 @@ public class UsageManager implements Service{ * @throws InterruptedException */ public void waitForSpace() throws InterruptedException { - if(parent!=null) + if (parent != null) parent.waitForSpace(); synchronized (usageMutex) { - for( int i=0; percentUsage >= 100 ; i++) { + for (int i = 0; percentUsage >= 100; i++) { usageMutex.wait(); } } @@ -122,71 +125,72 @@ public class UsageManager implements Service{ * @throws InterruptedException * * @param timeout - */ + */ public boolean waitForSpace(long timeout) throws InterruptedException { - if(parent!=null) { - if( !parent.waitForSpace(timeout) ) - return false; + if (parent != null) { + if (!parent.waitForSpace(timeout)) + return false; } synchronized (usageMutex) { - if( percentUsage >= 100 ) { + if (percentUsage >= 100) { usageMutex.wait(timeout); } return percentUsage < 100; } - } - + } + /** - * Increases the usage by the value amount. + * Increases the usage by the value amount. * * @param value */ public void increaseUsage(long value) { - if( value == 0 ) + if (value == 0) return; - if(parent!=null) + if (parent != null) parent.increaseUsage(value); int percentUsage; - synchronized(usageMutex) { - usage+=value; - percentUsage = caclPercentUsage(); + synchronized (usageMutex) { + usage += value; + percentUsage = caclPercentUsage(); } setPercentUsage(percentUsage); } - + /** - * Decreases the usage by the value amount. + * Decreases the usage by the value amount. * * @param value */ public void decreaseUsage(long value) { - if( value == 0 ) + if (value == 0) return; - if(parent!=null) + if (parent != null) parent.decreaseUsage(value); int percentUsage; - synchronized(usageMutex) { - usage-=value; - percentUsage = caclPercentUsage(); + synchronized (usageMutex) { + usage -= value; + percentUsage = caclPercentUsage(); } setPercentUsage(percentUsage); } - + public boolean isFull() { - if(parent!=null && parent.isFull()) + if (parent != null && parent.isFull()) return true; synchronized (usageMutex) { return percentUsage >= 100; } } - + public void addUsageListener(UsageListener listener) { listeners.add(listener); } + public void removeUsageListener(UsageListener listener) { listeners.remove(listener); } - + public long getLimit() { synchronized (usageMutex) { return limit; @@ -194,64 +198,67 @@ public class UsageManager implements Service{ } /** - * Sets the memory limit in bytes. Setting the limit in bytes will set the usagePortion to 0 since - * the UsageManager is not going to be portion based off the parent. + * Sets the memory limit in bytes. Setting the limit in bytes will set the + * usagePortion to 0 since the UsageManager is not going to be portion based + * off the parent. * - * When set using XBean, you can use values such as: "20 mb", "1024 kb", or "1 gb" + * When set using XBean, you can use values such as: "20 mb", "1024 kb", or + * "1 gb" * * @org.apache.xbean.Property propertyEditor="org.apache.activemq.util.MemoryPropertyEditor" */ public void setLimit(long limit) { - if(percentUsageMinDelta < 0 ) { + if (percentUsageMinDelta < 0) { throw new IllegalArgumentException("percentUsageMinDelta must be greater or equal to 0"); } - synchronized(usageMutex){ - this.limit=limit; - this.usagePortion=0; + synchronized (usageMutex) { + this.limit = limit; + this.usagePortion = 0; } onLimitChange(); } - - private void onLimitChange() { - - // We may need to calculate the limit - if( usagePortion > 0 && parent!=null ) { - synchronized(usageMutex){ - limit = (long)(parent.getLimit()*usagePortion); - } - } - - // Reset the percent currently being used. + + private void onLimitChange() { + + // We may need to calculate the limit + if (usagePortion > 0 && parent != null) { + synchronized (usageMutex) { + limit = (long)(parent.getLimit() * usagePortion); + } + } + + // Reset the percent currently being used. int percentUsage; - synchronized(usageMutex){ - percentUsage=caclPercentUsage(); + synchronized (usageMutex) { + percentUsage = caclPercentUsage(); } setPercentUsage(percentUsage); - - // Let the children know that the limit has changed. They may need to set + + // Let the children know that the limit has changed. They may need to + // set // their limits based on ours. - for (UsageManager child:children) { + for (UsageManager child : children) { child.onLimitChange(); } - } + } - public float getUsagePortion() { - synchronized(usageMutex){ - return usagePortion; + public float getUsagePortion() { + synchronized (usageMutex) { + return usagePortion; } - } + } - public void setUsagePortion(float usagePortion) { - synchronized(usageMutex){ - this.usagePortion = usagePortion; + public void setUsagePortion(float usagePortion) { + synchronized (usageMutex) { + this.usagePortion = usagePortion; } onLimitChange(); - } + } /* - * Sets the minimum number of percentage points the usage has to change before a UsageListener - * event is fired by the manager. - */ + * Sets the minimum number of percentage points the usage has to change + * before a UsageListener event is fired by the manager. + */ public int getPercentUsage() { synchronized (usageMutex) { return percentUsage; @@ -265,20 +272,20 @@ public class UsageManager implements Service{ } /** - * Sets the minimum number of percentage points the usage has to change before a UsageListener - * event is fired by the manager. + * Sets the minimum number of percentage points the usage has to change + * before a UsageListener event is fired by the manager. * * @param percentUsageMinDelta */ public void setPercentUsageMinDelta(int percentUsageMinDelta) { - if(percentUsageMinDelta < 1) { + if (percentUsageMinDelta < 1) { throw new IllegalArgumentException("percentUsageMinDelta must be greater than 0"); } int percentUsage; synchronized (usageMutex) { this.percentUsageMinDelta = percentUsageMinDelta; - percentUsage = caclPercentUsage(); - } + percentUsage = caclPercentUsage(); + } setPercentUsage(percentUsage); } @@ -287,10 +294,11 @@ public class UsageManager implements Service{ return usage; } } - + /** - * Sets whether or not a send() should fail if there is no space free. The default - * value is false which means to block the send() method until space becomes available + * Sets whether or not a send() should fail if there is no space free. The + * default value is false which means to block the send() method until space + * becomes available */ public void setSendFailIfNoSpace(boolean failProducerIfNoSpace) { sendFailIfNoSpaceExplicitySet = true; @@ -304,106 +312,106 @@ public class UsageManager implements Service{ return parent.isSendFailIfNoSpace(); } } - + private void setPercentUsage(int value) { synchronized (usageMutex) { int oldValue = percentUsage; percentUsage = value; - if( oldValue!=value ) { + if (oldValue != value) { fireEvent(oldValue, value); } } } - + private int caclPercentUsage() { - if( limit==0 ) return 0; - return (int)((((usage*100)/limit)/percentUsageMinDelta)*percentUsageMinDelta); + if (limit == 0) + return 0; + return (int)((((usage * 100) / limit) / percentUsageMinDelta) * percentUsageMinDelta); } - - private void fireEvent(int oldPercentUsage,int newPercentUsage){ + + private void fireEvent(int oldPercentUsage, int newPercentUsage) { if (debug) { - log.debug("Memory usage change. from: "+oldPercentUsage+", to: "+newPercentUsage); + log.debug("Memory usage change. from: " + oldPercentUsage + ", to: " + newPercentUsage); } // Switching from being full to not being full.. - if(oldPercentUsage>=100&&newPercentUsage<100){ - synchronized(usageMutex){ + if (oldPercentUsage >= 100 && newPercentUsage < 100) { + synchronized (usageMutex) { usageMutex.notifyAll(); for (Iterator iter = new ArrayList(callbacks).iterator(); iter.hasNext();) { - Runnable callback = (Runnable) iter.next(); - callback.run(); - } + Runnable callback = (Runnable)iter.next(); + callback.run(); + } callbacks.clear(); } } // Let the listeners know - for(Iterator iter=listeners.iterator();iter.hasNext();){ - UsageListener l=(UsageListener)iter.next(); - l.onMemoryUseChanged(this,oldPercentUsage,newPercentUsage); + for (Iterator iter = listeners.iterator(); iter.hasNext();) { + UsageListener l = (UsageListener)iter.next(); + l.onMemoryUseChanged(this, oldPercentUsage, newPercentUsage); } } - + public String getName() { return name; } - public String toString(){ - - - return "UsageManager("+ getName() +") percentUsage="+percentUsage+"%, usage="+usage+" limit="+limit+" percentUsageMinDelta=" - +percentUsageMinDelta+"%"; + public String toString() { + + return "UsageManager(" + getName() + ") percentUsage=" + percentUsage + "%, usage=" + usage + + " limit=" + limit + " percentUsageMinDelta=" + percentUsageMinDelta + "%"; } - public void start(){ - if(parent!=null){ + public void start() { + if (parent != null) { parent.addChild(this); } } - public void stop(){ - if(parent!=null){ + public void stop() { + if (parent != null) { parent.removeChild(this); } } - private void addChild(UsageManager child){ + private void addChild(UsageManager child) { children.add(child); } - private void removeChild(UsageManager child){ + private void removeChild(UsageManager child) { children.remove(child); } - + /** * @param callback - * @return true if the UsageManager was full. The callback will only be called if this method returns true. + * @return true if the UsageManager was full. The callback will only be + * called if this method returns true. */ - public boolean notifyCallbackWhenNotFull( final Runnable callback ) { - - if(parent!=null) { - Runnable r = new Runnable(){ - public void run() { - synchronized (usageMutex) { - if( percentUsage >= 100 ) { - callbacks.add(callback); - } else { - callback.run(); - } - } - } + public boolean notifyCallbackWhenNotFull(final Runnable callback) { + + if (parent != null) { + Runnable r = new Runnable() { + public void run() { + synchronized (usageMutex) { + if (percentUsage >= 100) { + callbacks.add(callback); + } else { + callback.run(); + } + } + } }; - if( parent.notifyCallbackWhenNotFull(r) ) { - return true; - } - } + if (parent.notifyCallbackWhenNotFull(r)) { + return true; + } + } synchronized (usageMutex) { - if( percentUsage >= 100 ) { - callbacks.add(callback); - return true; + if (percentUsage >= 100) { + callbacks.add(callback); + return true; } else { - return false; + return false; } } } - } diff --git a/activemq-core/src/main/java/org/apache/activemq/memory/UsageManagerCacheFilter.java b/activemq-core/src/main/java/org/apache/activemq/memory/UsageManagerCacheFilter.java index 83ffa95140..b1493ed7ee 100755 --- a/activemq-core/src/main/java/org/apache/activemq/memory/UsageManagerCacheFilter.java +++ b/activemq-core/src/main/java/org/apache/activemq/memory/UsageManagerCacheFilter.java @@ -37,29 +37,28 @@ public class UsageManagerCacheFilter extends CacheFilter { public Object put(Object key, Object value) { long usage = getUsageOfAddedObject(value); Object rc = super.put(key, value); - if( rc !=null ) { + if (rc != null) { usage -= getUsageOfRemovedObject(rc); } totalUsage.addAndGet(usage); um.increaseUsage(usage); return rc; } - + public Object remove(Object key) { Object rc = super.remove(key); - if( rc !=null ) { + if (rc != null) { long usage = getUsageOfRemovedObject(rc); totalUsage.addAndGet(-usage); um.decreaseUsage(usage); } return rc; } - - + protected long getUsageOfAddedObject(Object value) { return 1; } - + protected long getUsageOfRemovedObject(Object value) { return 1; } diff --git a/activemq-core/src/main/java/org/apache/activemq/memory/list/SimpleMessageList.java b/activemq-core/src/main/java/org/apache/activemq/memory/list/SimpleMessageList.java index bd0f5ab332..3df9db1fff 100644 --- a/activemq-core/src/main/java/org/apache/activemq/memory/list/SimpleMessageList.java +++ b/activemq-core/src/main/java/org/apache/activemq/memory/list/SimpleMessageList.java @@ -30,14 +30,14 @@ import org.apache.commons.logging.LogFactory; /** * A simple fixed size {@link MessageList} where there is a single, fixed size - * list that all messages are added to for simplicity. Though this - * will lead to possibly slow recovery times as many more messages - * than is necessary will have to be iterated through for each subscription. + * list that all messages are added to for simplicity. Though this will lead to + * possibly slow recovery times as many more messages than is necessary will + * have to be iterated through for each subscription. * * @version $Revision: 1.1 $ */ public class SimpleMessageList implements MessageList { - static final private Log log=LogFactory.getLog(SimpleMessageList.class); + static final private Log log = LogFactory.getLog(SimpleMessageList.class); private LinkedList list = new LinkedList(); private int maximumSize = 100 * 64 * 1024; private int size; @@ -56,7 +56,7 @@ public class SimpleMessageList implements MessageList { list.add(node); size += delta; while (size > maximumSize) { - MessageReference evicted = (MessageReference) list.removeFirst(); + MessageReference evicted = (MessageReference)list.removeFirst(); size -= evicted.getMessageHardRef().getSize(); } } @@ -65,23 +65,23 @@ public class SimpleMessageList implements MessageList { public List getMessages(ActiveMQDestination destination) { return getList(); } - + public Message[] browse(ActiveMQDestination destination) { List result = new ArrayList(); - DestinationFilter filter=DestinationFilter.parseFilter(destination); - synchronized(lock){ - for (Iterator i = list.iterator(); i.hasNext();){ + DestinationFilter filter = DestinationFilter.parseFilter(destination); + synchronized (lock) { + for (Iterator i = list.iterator(); i.hasNext();) { MessageReference ref = (MessageReference)i.next(); Message msg; - try{ - msg=ref.getMessage(); - if (filter.matches(msg.getDestination())){ + try { + msg = ref.getMessage(); + if (filter.matches(msg.getDestination())) { result.add(msg); } - }catch(IOException e){ - log.error("Failed to get Message from MessageReference: " + ref,e); + } catch (IOException e) { + log.error("Failed to get Message from MessageReference: " + ref, e); } - + } } return (Message[])result.toArray(new Message[result.size()]); diff --git a/activemq-core/src/main/java/org/apache/activemq/network/CompositeDemandForwardingBridge.java b/activemq-core/src/main/java/org/apache/activemq/network/CompositeDemandForwardingBridge.java index 8a2d0274a5..176eaeba43 100644 --- a/activemq-core/src/main/java/org/apache/activemq/network/CompositeDemandForwardingBridge.java +++ b/activemq-core/src/main/java/org/apache/activemq/network/CompositeDemandForwardingBridge.java @@ -37,26 +37,27 @@ import java.io.IOException; */ public class CompositeDemandForwardingBridge extends DemandForwardingBridgeSupport { - protected final BrokerId remoteBrokerPath[] = new BrokerId[] { null }; + protected final BrokerId remoteBrokerPath[] = new BrokerId[] {null}; protected Object brokerInfoMutex = new Object(); - public CompositeDemandForwardingBridge(NetworkBridgeConfiguration configuration,Transport localBroker, Transport remoteBroker) { - super(configuration,localBroker, remoteBroker); + public CompositeDemandForwardingBridge(NetworkBridgeConfiguration configuration, Transport localBroker, + Transport remoteBroker) { + super(configuration, localBroker, remoteBroker); remoteBrokerName = remoteBroker.toString(); - remoteBrokerNameKnownLatch.countDown(); + remoteBrokerNameKnownLatch.countDown(); } protected void serviceRemoteBrokerInfo(Command command) throws IOException { synchronized (brokerInfoMutex) { - BrokerInfo remoteBrokerInfo = (BrokerInfo) command; + BrokerInfo remoteBrokerInfo = (BrokerInfo)command; BrokerId remoteBrokerId = remoteBrokerInfo.getBrokerId(); - - // lets associate the incoming endpoint with a broker ID so we can refer to it later + + // lets associate the incoming endpoint with a broker ID so we can + // refer to it later Endpoint from = command.getFrom(); if (from == null) { log.warn("Incoming command does not have a from endpoint: " + command); - } - else { + } else { from.setBrokerInfo(remoteBrokerInfo); } if (localBrokerId != null) { @@ -84,15 +85,14 @@ public class CompositeDemandForwardingBridge extends DemandForwardingBridgeSuppo Endpoint from = command.getFrom(); if (from == null) { log.warn("Incoming command does not have a from endpoint: " + command); - } - else { + } else { answer = from.getBrokerId(); } - if (answer != null) { + if (answer != null) { return answer; - } - else { - throw new IOException("No broker ID is available for endpoint: " + from + " from command: " + command); + } else { + throw new IOException("No broker ID is available for endpoint: " + from + " from command: " + + command); } } @@ -103,8 +103,8 @@ public class CompositeDemandForwardingBridge extends DemandForwardingBridgeSuppo protected NetworkBridgeFilter createNetworkBridgeFilter(ConsumerInfo info) throws IOException { return new NetworkBridgeFilter(getFromBrokerId(info), configuration.getNetworkTTL()); } - - protected BrokerId[] getRemoteBrokerPath(){ + + protected BrokerId[] getRemoteBrokerPath() { return remoteBrokerPath; } diff --git a/activemq-core/src/main/java/org/apache/activemq/network/ConduitBridge.java b/activemq-core/src/main/java/org/apache/activemq/network/ConduitBridge.java index f5e0e8c905..59fb97c187 100644 --- a/activemq-core/src/main/java/org/apache/activemq/network/ConduitBridge.java +++ b/activemq-core/src/main/java/org/apache/activemq/network/ConduitBridge.java @@ -28,70 +28,74 @@ import java.util.ArrayList; import java.util.Iterator; import java.util.List; - /** * Consolidates subscriptions * * @version $Revision: 1.1 $ */ -public class ConduitBridge extends DemandForwardingBridge{ - static final private Log log=LogFactory.getLog(ConduitBridge.class); +public class ConduitBridge extends DemandForwardingBridge { + static final private Log log = LogFactory.getLog(ConduitBridge.class); + /** * Constructor + * * @param localBroker * @param remoteBroker */ - public ConduitBridge(NetworkBridgeConfiguration configuration,Transport localBroker,Transport remoteBroker){ - super(configuration,localBroker,remoteBroker); + public ConduitBridge(NetworkBridgeConfiguration configuration, Transport localBroker, + Transport remoteBroker) { + super(configuration, localBroker, remoteBroker); } - - protected DemandSubscription createDemandSubscription(ConsumerInfo info) throws IOException{ - - if (addToAlreadyInterestedConsumers(info)){ - return null; //don't want this subscription added + + protected DemandSubscription createDemandSubscription(ConsumerInfo info) throws IOException { + + if (addToAlreadyInterestedConsumers(info)) { + return null; // don't want this subscription added } return doCreateDemandSubscription(info); } - - protected boolean addToAlreadyInterestedConsumers(ConsumerInfo info){ - - if( info.getSelector()!=null ) - return false; - - //search through existing subscriptions and see if we have a match + + protected boolean addToAlreadyInterestedConsumers(ConsumerInfo info) { + + if (info.getSelector() != null) + return false; + + // search through existing subscriptions and see if we have a match boolean matched = false; - DestinationFilter filter=DestinationFilter.parseFilter(info.getDestination()); - for (Iterator i = subscriptionMapByLocalId.values().iterator(); i.hasNext();){ + DestinationFilter filter = DestinationFilter.parseFilter(info.getDestination()); + for (Iterator i = subscriptionMapByLocalId.values().iterator(); i.hasNext();) { DemandSubscription ds = (DemandSubscription)i.next(); - if (filter.matches(ds.getLocalInfo().getDestination())){ - //add the interest in the subscription - //ds.add(ds.getRemoteInfo().getConsumerId()); + if (filter.matches(ds.getLocalInfo().getDestination())) { + // add the interest in the subscription + // ds.add(ds.getRemoteInfo().getConsumerId()); ds.add(info.getConsumerId()); matched = true; - //continue - we want interest to any existing DemandSubscriptions + // continue - we want interest to any existing + // DemandSubscriptions } } return matched; } - - protected void removeDemandSubscription(ConsumerId id) throws IOException{ + + protected void removeDemandSubscription(ConsumerId id) throws IOException { List tmpList = new ArrayList(); - - for (Iterator i = subscriptionMapByLocalId.values().iterator(); i.hasNext();){ + + for (Iterator i = subscriptionMapByLocalId.values().iterator(); i.hasNext();) { DemandSubscription ds = (DemandSubscription)i.next(); ds.remove(id); - if (ds.isEmpty()){ + if (ds.isEmpty()) { tmpList.add(ds); } } - for (Iterator i = tmpList.iterator(); i.hasNext();){ - DemandSubscription ds = (DemandSubscription) i.next(); + for (Iterator i = tmpList.iterator(); i.hasNext();) { + DemandSubscription ds = (DemandSubscription)i.next(); subscriptionMapByLocalId.remove(ds.getRemoteInfo().getConsumerId()); removeSubscription(ds); - if(log.isTraceEnabled()) - log.trace("removing sub on "+localBroker+" from "+remoteBrokerName+" : "+ds.getRemoteInfo()); + if (log.isTraceEnabled()) + log.trace("removing sub on " + localBroker + " from " + remoteBrokerName + " : " + + ds.getRemoteInfo()); } - + } } diff --git a/activemq-core/src/main/java/org/apache/activemq/network/DemandForwardingBridge.java b/activemq-core/src/main/java/org/apache/activemq/network/DemandForwardingBridge.java index cf71d6caaa..a664affd93 100755 --- a/activemq-core/src/main/java/org/apache/activemq/network/DemandForwardingBridge.java +++ b/activemq-core/src/main/java/org/apache/activemq/network/DemandForwardingBridge.java @@ -35,41 +35,42 @@ import java.io.IOException; */ public class DemandForwardingBridge extends DemandForwardingBridgeSupport { - protected final BrokerId remoteBrokerPath[] = new BrokerId[] { null }; + protected final BrokerId remoteBrokerPath[] = new BrokerId[] {null}; protected Object brokerInfoMutex = new Object(); protected BrokerId remoteBrokerId; - public DemandForwardingBridge(NetworkBridgeConfiguration configuration,Transport localBroker,Transport remoteBroker){ - super(configuration,localBroker, remoteBroker); + public DemandForwardingBridge(NetworkBridgeConfiguration configuration, Transport localBroker, + Transport remoteBroker) { + super(configuration, localBroker, remoteBroker); } protected void serviceRemoteBrokerInfo(Command command) throws IOException { - synchronized(brokerInfoMutex){ - BrokerInfo remoteBrokerInfo=(BrokerInfo) command; - remoteBrokerId=remoteBrokerInfo.getBrokerId(); - remoteBrokerPath[0]=remoteBrokerId; - remoteBrokerName=remoteBrokerInfo.getBrokerName(); - if(localBrokerId!=null){ - if(localBrokerId.equals(remoteBrokerId)){ + synchronized (brokerInfoMutex) { + BrokerInfo remoteBrokerInfo = (BrokerInfo)command; + remoteBrokerId = remoteBrokerInfo.getBrokerId(); + remoteBrokerPath[0] = remoteBrokerId; + remoteBrokerName = remoteBrokerInfo.getBrokerName(); + if (localBrokerId != null) { + if (localBrokerId.equals(remoteBrokerId)) { log.info("Disconnecting loop back connection."); - //waitStarted(); + // waitStarted(); ServiceSupport.dispose(this); } } - remoteBrokerNameKnownLatch.countDown(); + remoteBrokerNameKnownLatch.countDown(); } } protected void addRemoteBrokerToBrokerPath(ConsumerInfo info) { - info.setBrokerPath(appendToBrokerPath(info.getBrokerPath(),getRemoteBrokerPath())); + info.setBrokerPath(appendToBrokerPath(info.getBrokerPath(), getRemoteBrokerPath())); } protected void serviceLocalBrokerInfo(Command command) throws InterruptedException { - synchronized(brokerInfoMutex){ - localBrokerId=((BrokerInfo) command).getBrokerId(); - localBrokerPath[0]=localBrokerId; - if(remoteBrokerId!=null){ - if(remoteBrokerId.equals(localBrokerId)){ + synchronized (brokerInfoMutex) { + localBrokerId = ((BrokerInfo)command).getBrokerId(); + localBrokerPath[0] = localBrokerId; + if (remoteBrokerId != null) { + if (remoteBrokerId.equals(localBrokerId)) { log.info("Disconnecting loop back connection."); waitStarted(); ServiceSupport.dispose(this); @@ -77,12 +78,12 @@ public class DemandForwardingBridge extends DemandForwardingBridgeSupport { } } } - + protected NetworkBridgeFilter createNetworkBridgeFilter(ConsumerInfo info) throws IOException { return new NetworkBridgeFilter(remoteBrokerPath[0], configuration.getNetworkTTL()); } - - protected BrokerId[] getRemoteBrokerPath(){ + + protected BrokerId[] getRemoteBrokerPath() { return remoteBrokerPath; } } diff --git a/activemq-core/src/main/java/org/apache/activemq/network/DemandSubscription.java b/activemq-core/src/main/java/org/apache/activemq/network/DemandSubscription.java index 10e3edf9c7..495b5e45d7 100644 --- a/activemq-core/src/main/java/org/apache/activemq/network/DemandSubscription.java +++ b/activemq-core/src/main/java/org/apache/activemq/network/DemandSubscription.java @@ -29,92 +29,93 @@ import java.util.Set; * * @version $Revision: 1.1 $ */ -public class DemandSubscription{ +public class DemandSubscription { private ConsumerInfo remoteInfo; private ConsumerInfo localInfo; private Set remoteSubsIds = new CopyOnWriteArraySet(); private AtomicInteger dispatched = new AtomicInteger(0); - DemandSubscription(ConsumerInfo info){ - remoteInfo=info; - localInfo=info.copy(); + DemandSubscription(ConsumerInfo info) { + remoteInfo = info; + localInfo = info.copy(); localInfo.setBrokerPath(info.getBrokerPath()); remoteSubsIds.add(info.getConsumerId()); - } + } /** * Increment the consumers associated with this subscription + * * @param id * @return true if added */ - public boolean add(ConsumerId id){ + public boolean add(ConsumerId id) { return remoteSubsIds.add(id); } - + /** * Increment the consumers associated with this subscription + * * @param id * @return true if added */ - public boolean remove(ConsumerId id){ + public boolean remove(ConsumerId id) { return remoteSubsIds.remove(id); } - + /** * @return true if there are no interested consumers */ - public boolean isEmpty(){ + public boolean isEmpty() { return remoteSubsIds.isEmpty(); } - - + /** * @return Returns the dispatched. */ - public int getDispatched(){ + public int getDispatched() { return dispatched.get(); } /** * @param dispatched The dispatched to set. */ - public void setDispatched(int dispatched){ + public void setDispatched(int dispatched) { this.dispatched.set(dispatched); } - + /** * @return dispatched count after incremented */ - public int incrementDispatched(){ + public int incrementDispatched() { return dispatched.incrementAndGet(); } /** * @return Returns the localInfo. */ - public ConsumerInfo getLocalInfo(){ + public ConsumerInfo getLocalInfo() { return localInfo; } /** * @param localInfo The localInfo to set. */ - public void setLocalInfo(ConsumerInfo localInfo){ - this.localInfo=localInfo; + public void setLocalInfo(ConsumerInfo localInfo) { + this.localInfo = localInfo; } /** * @return Returns the remoteInfo. */ - public ConsumerInfo getRemoteInfo(){ + public ConsumerInfo getRemoteInfo() { return remoteInfo; } /** * @param remoteInfo The remoteInfo to set. */ - public void setRemoteInfo(ConsumerInfo remoteInfo){ - this.remoteInfo=remoteInfo; + public void setRemoteInfo(ConsumerInfo remoteInfo) { + this.remoteInfo = remoteInfo; } - + } diff --git a/activemq-core/src/main/java/org/apache/activemq/network/DiscoveryNetworkConnector.java b/activemq-core/src/main/java/org/apache/activemq/network/DiscoveryNetworkConnector.java index 473bc728bc..c1c6c662c6 100644 --- a/activemq-core/src/main/java/org/apache/activemq/network/DiscoveryNetworkConnector.java +++ b/activemq-core/src/main/java/org/apache/activemq/network/DiscoveryNetworkConnector.java @@ -44,7 +44,7 @@ public class DiscoveryNetworkConnector extends NetworkConnector implements Disco private DiscoveryAgent discoveryAgent; private ConcurrentHashMap bridges = new ConcurrentHashMap(); - + public DiscoveryNetworkConnector() { } @@ -56,74 +56,74 @@ public class DiscoveryNetworkConnector extends NetworkConnector implements Disco setDiscoveryAgent(DiscoveryAgentFactory.createDiscoveryAgent(discoveryURI)); } - public void onServiceAdd(DiscoveryEvent event){ - String localURIName=localURI.getScheme() + "://" + localURI.getHost(); + public void onServiceAdd(DiscoveryEvent event) { + String localURIName = localURI.getScheme() + "://" + localURI.getHost(); // Ignore events once we start stopping. - if(serviceSupport.isStopped()||serviceSupport.isStopping()) + if (serviceSupport.isStopped() || serviceSupport.isStopping()) return; - String url=event.getServiceName(); - if(url!=null){ + String url = event.getServiceName(); + if (url != null) { URI uri; - try{ - uri=new URI(url); - }catch(URISyntaxException e){ - log.warn("Could not connect to remote URI: "+url+" due to bad URI syntax: "+e,e); + try { + uri = new URI(url); + } catch (URISyntaxException e) { + log.warn("Could not connect to remote URI: " + url + " due to bad URI syntax: " + e, e); return; } // Should we try to connect to that URI? - if(bridges.containsKey(uri)||localURI.equals(uri) - ||(connectionFilter!=null&&!connectionFilter.connectTo(uri))) + if (bridges.containsKey(uri) || localURI.equals(uri) + || (connectionFilter != null && !connectionFilter.connectTo(uri))) return; - URI connectUri=uri; - log.info("Establishing network connection between from "+localURIName+" to "+connectUri); + URI connectUri = uri; + log.info("Establishing network connection between from " + localURIName + " to " + connectUri); Transport remoteTransport; - try{ - remoteTransport=TransportFactory.connect(connectUri); - }catch(Exception e){ - log.warn("Could not connect to remote URI: "+localURIName+": "+e.getMessage()); - log.debug("Connection failure exception: "+e,e); + try { + remoteTransport = TransportFactory.connect(connectUri); + } catch (Exception e) { + log.warn("Could not connect to remote URI: " + localURIName + ": " + e.getMessage()); + log.debug("Connection failure exception: " + e, e); return; } Transport localTransport; - try{ - localTransport=createLocalTransport(); - }catch(Exception e){ + try { + localTransport = createLocalTransport(); + } catch (Exception e) { ServiceSupport.dispose(remoteTransport); - log.warn("Could not connect to local URI: "+localURIName+": "+e.getMessage()); - log.debug("Connection failure exception: "+e,e); + log.warn("Could not connect to local URI: " + localURIName + ": " + e.getMessage()); + log.debug("Connection failure exception: " + e, e); return; } - NetworkBridge bridge=createBridge(localTransport,remoteTransport,event); - bridges.put(uri,bridge); - try{ + NetworkBridge bridge = createBridge(localTransport, remoteTransport, event); + bridges.put(uri, bridge); + try { bridge.start(); - }catch(Exception e){ + } catch (Exception e) { ServiceSupport.dispose(localTransport); ServiceSupport.dispose(remoteTransport); - log.warn("Could not start network bridge between: "+localURIName+" and: "+uri+" due to: "+e); - log.debug("Start failure exception: "+e,e); - try{ + log.warn("Could not start network bridge between: " + localURIName + " and: " + uri + + " due to: " + e); + log.debug("Start failure exception: " + e, e); + try { discoveryAgent.serviceFailed(event); - }catch(IOException e1){ + } catch (IOException e1) { } return; } } } - + public void onServiceRemove(DiscoveryEvent event) { String url = event.getServiceName(); if (url != null) { URI uri; try { uri = new URI(url); - } - catch (URISyntaxException e) { + } catch (URISyntaxException e) { log.warn("Could not connect to remote URI: " + url + " due to bad URI syntax: " + e, e); return; } - NetworkBridge bridge = (NetworkBridge) bridges.remove(uri); + NetworkBridge bridge = (NetworkBridge)bridges.remove(uri); if (bridge == null) return; @@ -153,48 +153,47 @@ public class DiscoveryNetworkConnector extends NetworkConnector implements Disco protected void handleStop(ServiceStopper stopper) throws Exception { for (Iterator i = bridges.values().iterator(); i.hasNext();) { - NetworkBridge bridge = (NetworkBridge) i.next(); + NetworkBridge bridge = (NetworkBridge)i.next(); try { bridge.stop(); - } - catch (Exception e) { + } catch (Exception e) { stopper.onException(this, e); } } try { this.discoveryAgent.stop(); - } - catch (Exception e) { + } catch (Exception e) { stopper.onException(this, e); } super.handleStop(stopper); } - protected NetworkBridge createBridge(Transport localTransport, Transport remoteTransport, final DiscoveryEvent event) { + protected NetworkBridge createBridge(Transport localTransport, Transport remoteTransport, + final DiscoveryEvent event) { NetworkBridgeListener listener = new NetworkBridgeListener() { - public void bridgeFailed(){ - if( !serviceSupport.isStopped() ) { + public void bridgeFailed() { + if (!serviceSupport.isStopped()) { try { discoveryAgent.serviceFailed(event); } catch (IOException e) { } } - + } - public void onStart(NetworkBridge bridge) { - registerNetworkBridgeMBean(bridge); - } + public void onStart(NetworkBridge bridge) { + registerNetworkBridgeMBean(bridge); + } - public void onStop(NetworkBridge bridge) { - unregisterNetworkBridgeMBean(bridge); - } + public void onStop(NetworkBridge bridge) { + unregisterNetworkBridgeMBean(bridge); + } - }; - DemandForwardingBridge result = NetworkBridgeFactory.createBridge(this,localTransport,remoteTransport,listener); + DemandForwardingBridge result = NetworkBridgeFactory.createBridge(this, localTransport, + remoteTransport, listener); return configureBridge(result); } @@ -202,6 +201,4 @@ public class DiscoveryNetworkConnector extends NetworkConnector implements Disco return discoveryAgent.toString(); } - - } diff --git a/activemq-core/src/main/java/org/apache/activemq/network/DurableConduitBridge.java b/activemq-core/src/main/java/org/apache/activemq/network/DurableConduitBridge.java index c988661b93..bd148f1590 100644 --- a/activemq-core/src/main/java/org/apache/activemq/network/DurableConduitBridge.java +++ b/activemq-core/src/main/java/org/apache/activemq/network/DurableConduitBridge.java @@ -26,81 +26,85 @@ import org.apache.commons.logging.LogFactory; import java.io.IOException; import java.util.Iterator; + /** * Consolidates subscriptions * * @version $Revision: 1.1 $ */ -public class DurableConduitBridge extends ConduitBridge{ - static final private Log log=LogFactory.getLog(DurableConduitBridge.class); +public class DurableConduitBridge extends ConduitBridge { + static final private Log log = LogFactory.getLog(DurableConduitBridge.class); /** * Constructor - * @param configuration + * + * @param configuration * * @param localBroker * @param remoteBroker */ - public DurableConduitBridge(NetworkBridgeConfiguration configuration,Transport localBroker,Transport remoteBroker){ - super(configuration,localBroker,remoteBroker); + public DurableConduitBridge(NetworkBridgeConfiguration configuration, Transport localBroker, + Transport remoteBroker) { + super(configuration, localBroker, remoteBroker); } /** * Subscriptions for these destinations are always created * */ - protected void setupStaticDestinations(){ + protected void setupStaticDestinations() { super.setupStaticDestinations(); - ActiveMQDestination[] dests=durableDestinations; - if(dests!=null){ - for(int i=0;i (queueConsumerInfo.getPrefetchSize()/2) ) { -// localBroker.oneway(new MessageAck(md, MessageAck.STANDARD_ACK_TYPE, queueDispatched)); -// queueDispatched=0; -// } -// } else { -// topicDispatched++; -// if( topicDispatched > (topicConsumerInfo.getPrefetchSize()/2) ) { -// localBroker.oneway(new MessageAck(md, MessageAck.STANDARD_ACK_TYPE, topicDispatched)); -// topicDispatched=0; -// } -// } - } else if(command.isBrokerInfo() ) { - synchronized( this ) { - localBrokerInfo = ((BrokerInfo)command); + // Ack on every message since we don't know if the broker is + // blocked due to memory + // usage and is waiting for an Ack to un-block him. + + // Acking a range is more efficient, but also more prone to + // locking up a server + // Perhaps doing something like the following should be policy + // based. + // if( + // md.getConsumerId().equals(queueConsumerInfo.getConsumerId()) + // ) { + // queueDispatched++; + // if( queueDispatched > (queueConsumerInfo.getPrefetchSize()/2) + // ) { + // localBroker.oneway(new MessageAck(md, + // MessageAck.STANDARD_ACK_TYPE, queueDispatched)); + // queueDispatched=0; + // } + // } else { + // topicDispatched++; + // if( topicDispatched > (topicConsumerInfo.getPrefetchSize()/2) + // ) { + // localBroker.oneway(new MessageAck(md, + // MessageAck.STANDARD_ACK_TYPE, topicDispatched)); + // topicDispatched=0; + // } + // } + } else if (command.isBrokerInfo()) { + synchronized (this) { + localBrokerInfo = ((BrokerInfo)command); localBrokerId = localBrokerInfo.getBrokerId(); - if( remoteBrokerId !=null) { - if( remoteBrokerId.equals(localBrokerId) ) { + if (remoteBrokerId != null) { + if (remoteBrokerId.equals(localBrokerId)) { log.info("Disconnecting loop back connection."); ServiceSupport.dispose(this); } else { - triggerStartBridge(); + triggerStartBridge(); } } } } else { - log.debug("Unexpected local command: "+command); + log.debug("Unexpected local command: " + command); } } catch (IOException e) { serviceLocalException(e); @@ -307,6 +321,7 @@ public class ForwardingBridge implements Service{ public String getClientId() { return clientId; } + public void setClientId(String clientId) { this.clientId = clientId; } @@ -314,6 +329,7 @@ public class ForwardingBridge implements Service{ public int getPrefetchSize() { return prefetchSize; } + public void setPrefetchSize(int prefetchSize) { this.prefetchSize = prefetchSize; } @@ -321,6 +337,7 @@ public class ForwardingBridge implements Service{ public boolean isDispatchAsync() { return dispatchAsync; } + public void setDispatchAsync(boolean dispatchAsync) { this.dispatchAsync = dispatchAsync; } @@ -328,44 +345,44 @@ public class ForwardingBridge implements Service{ public String getDestinationFilter() { return destinationFilter; } + public void setDestinationFilter(String destinationFilter) { this.destinationFilter = destinationFilter; } - - public void setNetworkBridgeFailedListener(NetworkBridgeListener listener){ - this.bridgeFailedListener=listener; + public void setNetworkBridgeFailedListener(NetworkBridgeListener listener) { + this.bridgeFailedListener = listener; } - + private void fireBridgeFailed() { NetworkBridgeListener l = this.bridgeFailedListener; - if (l!=null) { + if (l != null) { l.bridgeFailed(); } } - public String getRemoteAddress() { - return remoteBroker.getRemoteAddress(); - } + public String getRemoteAddress() { + return remoteBroker.getRemoteAddress(); + } - public String getLocalAddress() { - return localBroker.getRemoteAddress(); - } + public String getLocalAddress() { + return localBroker.getRemoteAddress(); + } - public String getLocalBrokerName() { - return localBrokerInfo == null ? null : localBrokerInfo.getBrokerName(); - } + public String getLocalBrokerName() { + return localBrokerInfo == null ? null : localBrokerInfo.getBrokerName(); + } - public String getRemoteBrokerName() { - return remoteBrokerInfo == null ? null : remoteBrokerInfo.getBrokerName(); - } - - public long getDequeueCounter() { - return dequeueCounter.get(); - } + public String getRemoteBrokerName() { + return remoteBrokerInfo == null ? null : remoteBrokerInfo.getBrokerName(); + } - public long getEnqueueCounter() { - return enqueueCounter.get(); - } + public long getDequeueCounter() { + return dequeueCounter.get(); + } + + public long getEnqueueCounter() { + return enqueueCounter.get(); + } } diff --git a/activemq-core/src/main/java/org/apache/activemq/network/MulticastNetworkConnector.java b/activemq-core/src/main/java/org/apache/activemq/network/MulticastNetworkConnector.java index 7e0c7d62cc..f4856e1fa1 100644 --- a/activemq-core/src/main/java/org/apache/activemq/network/MulticastNetworkConnector.java +++ b/activemq-core/src/main/java/org/apache/activemq/network/MulticastNetworkConnector.java @@ -121,24 +121,21 @@ public class MulticastNetworkConnector extends NetworkConnector { if (bridge != null) { try { bridge.stop(); - } - catch (Exception e) { + } catch (Exception e) { stopper.onException(this, e); } } if (remoteTransport != null) { try { remoteTransport.stop(); - } - catch (Exception e) { + } catch (Exception e) { stopper.onException(this, e); } } if (localTransport != null) { try { localTransport.stop(); - } - catch (Exception e) { + } catch (Exception e) { stopper.onException(this, e); } } @@ -149,7 +146,7 @@ public class MulticastNetworkConnector extends NetworkConnector { } protected DemandForwardingBridgeSupport createBridge(Transport local, Transport remote) { - return new CompositeDemandForwardingBridge(this,local, remote); + return new CompositeDemandForwardingBridge(this, local, remote); } } diff --git a/activemq-core/src/main/java/org/apache/activemq/network/NetworkBridgeFactory.java b/activemq-core/src/main/java/org/apache/activemq/network/NetworkBridgeFactory.java index d21d69f1ca..2dca2e1934 100644 --- a/activemq-core/src/main/java/org/apache/activemq/network/NetworkBridgeFactory.java +++ b/activemq-core/src/main/java/org/apache/activemq/network/NetworkBridgeFactory.java @@ -23,48 +23,44 @@ import org.apache.activemq.transport.Transport; */ public class NetworkBridgeFactory { - /** - * Create a network bridge - * - * @param config - * @param localTransport - * @param remoteTransport - * @return the NetworkBridge - */ - public static DemandForwardingBridge createBridge( - NetworkBridgeConfiguration config, Transport localTransport, - Transport remoteTransport) { - return createBridge(config, localTransport, remoteTransport, null); - } + /** + * Create a network bridge + * + * @param config + * @param localTransport + * @param remoteTransport + * @return the NetworkBridge + */ + public static DemandForwardingBridge createBridge(NetworkBridgeConfiguration config, + Transport localTransport, Transport remoteTransport) { + return createBridge(config, localTransport, remoteTransport, null); + } - /** - * create a network bridge - * - * @param configuration - * @param localTransport - * @param remoteTransport - * @param listener - * @return the NetworkBridge - */ - public static DemandForwardingBridge createBridge( - NetworkBridgeConfiguration configuration, Transport localTransport, - Transport remoteTransport, final NetworkBridgeListener listener) { - DemandForwardingBridge result = null; - if (configuration.isConduitSubscriptions()) { - if (configuration.isDynamicOnly()) { - result = new ConduitBridge(configuration, localTransport, - remoteTransport); - } else { - result = new DurableConduitBridge(configuration, - localTransport, remoteTransport); - } - } else { - result = new DemandForwardingBridge(configuration, localTransport, - remoteTransport); - } - if (listener != null) { - result.setNetworkBridgeListener(listener); - } - return result; - } + /** + * create a network bridge + * + * @param configuration + * @param localTransport + * @param remoteTransport + * @param listener + * @return the NetworkBridge + */ + public static DemandForwardingBridge createBridge(NetworkBridgeConfiguration configuration, + Transport localTransport, Transport remoteTransport, + final NetworkBridgeListener listener) { + DemandForwardingBridge result = null; + if (configuration.isConduitSubscriptions()) { + if (configuration.isDynamicOnly()) { + result = new ConduitBridge(configuration, localTransport, remoteTransport); + } else { + result = new DurableConduitBridge(configuration, localTransport, remoteTransport); + } + } else { + result = new DemandForwardingBridge(configuration, localTransport, remoteTransport); + } + if (listener != null) { + result.setNetworkBridgeListener(listener); + } + return result; + } } diff --git a/activemq-core/src/main/java/org/apache/activemq/network/NetworkBridgeListener.java b/activemq-core/src/main/java/org/apache/activemq/network/NetworkBridgeListener.java index 7c14e00c21..9a42d843e7 100644 --- a/activemq-core/src/main/java/org/apache/activemq/network/NetworkBridgeListener.java +++ b/activemq-core/src/main/java/org/apache/activemq/network/NetworkBridgeListener.java @@ -16,31 +16,26 @@ */ package org.apache.activemq.network; - - /** - *called when a bridge fails + * called when a bridge fails * * @version $Revision: 1.1 $ */ -public interface NetworkBridgeListener{ - +public interface NetworkBridgeListener { + /** * called when the transport fails - * */ public void bridgeFailed(); /** * called after the bridge is started. - * */ - public void onStart(NetworkBridge bridge); - + public void onStart(NetworkBridge bridge); + /** * called before the bridge is stopped. - * */ - public void onStop(NetworkBridge bridge); + public void onStop(NetworkBridge bridge); } diff --git a/activemq-core/src/main/java/org/apache/activemq/network/NetworkConnector.java b/activemq-core/src/main/java/org/apache/activemq/network/NetworkConnector.java index 4963465ddd..f68902341c 100644 --- a/activemq-core/src/main/java/org/apache/activemq/network/NetworkConnector.java +++ b/activemq-core/src/main/java/org/apache/activemq/network/NetworkConnector.java @@ -41,236 +41,231 @@ import org.apache.commons.logging.LogFactory; /** * @version $Revision$ */ -public abstract class NetworkConnector extends NetworkBridgeConfiguration implements Service{ +public abstract class NetworkConnector extends NetworkBridgeConfiguration implements Service { - protected static final Log log=LogFactory.getLog(NetworkConnector.class); + protected static final Log log = LogFactory.getLog(NetworkConnector.class); protected URI localURI; private Set durableDestinations; - private List excludedDestinations=new CopyOnWriteArrayList(); - private List dynamicallyIncludedDestinations=new CopyOnWriteArrayList(); - private List staticallyIncludedDestinations=new CopyOnWriteArrayList(); + private List excludedDestinations = new CopyOnWriteArrayList(); + private List dynamicallyIncludedDestinations = new CopyOnWriteArrayList(); + private List staticallyIncludedDestinations = new CopyOnWriteArrayList(); protected ConnectionFilter connectionFilter; private BrokerService brokerService; private ObjectName objectName; - - protected ServiceSupport serviceSupport=new ServiceSupport(){ - protected void doStart() throws Exception{ - handleStart(); + protected ServiceSupport serviceSupport = new ServiceSupport() { + + protected void doStart() throws Exception { + handleStart(); } - protected void doStop(ServiceStopper stopper) throws Exception{ + protected void doStop(ServiceStopper stopper) throws Exception { handleStop(stopper); } }; - public NetworkConnector(){ + public NetworkConnector() { } - public NetworkConnector(URI localURI){ - this.localURI=localURI; + public NetworkConnector(URI localURI) { + this.localURI = localURI; } - public URI getLocalUri() throws URISyntaxException{ + public URI getLocalUri() throws URISyntaxException { return localURI; } - public void setLocalUri(URI localURI){ - this.localURI=localURI; + public void setLocalUri(URI localURI) { + this.localURI = localURI; } - /** * @return Returns the durableDestinations. */ - public Set getDurableDestinations(){ + public Set getDurableDestinations() { return durableDestinations; } /** * @param durableDestinations The durableDestinations to set. */ - public void setDurableDestinations(Set durableDestinations){ - this.durableDestinations=durableDestinations; + public void setDurableDestinations(Set durableDestinations) { + this.durableDestinations = durableDestinations; } /** * @return Returns the excludedDestinations. */ - public List getExcludedDestinations(){ + public List getExcludedDestinations() { return excludedDestinations; } /** * @param excludedDestinations The excludedDestinations to set. */ - public void setExcludedDestinations(List excludedDestinations){ - this.excludedDestinations=excludedDestinations; + public void setExcludedDestinations(List excludedDestinations) { + this.excludedDestinations = excludedDestinations; } - public void addExcludedDestination(ActiveMQDestination destiantion){ + public void addExcludedDestination(ActiveMQDestination destiantion) { this.excludedDestinations.add(destiantion); } /** * @return Returns the staticallyIncludedDestinations. */ - public List getStaticallyIncludedDestinations(){ + public List getStaticallyIncludedDestinations() { return staticallyIncludedDestinations; } /** - * @param staticallyIncludedDestinations The staticallyIncludedDestinations to set. + * @param staticallyIncludedDestinations The staticallyIncludedDestinations + * to set. */ - public void setStaticallyIncludedDestinations(List staticallyIncludedDestinations){ - this.staticallyIncludedDestinations=staticallyIncludedDestinations; + public void setStaticallyIncludedDestinations(List staticallyIncludedDestinations) { + this.staticallyIncludedDestinations = staticallyIncludedDestinations; } - public void addStaticallyIncludedDestination(ActiveMQDestination destiantion){ + public void addStaticallyIncludedDestination(ActiveMQDestination destiantion) { this.staticallyIncludedDestinations.add(destiantion); } /** * @return Returns the dynamicallyIncludedDestinations. */ - public List getDynamicallyIncludedDestinations(){ + public List getDynamicallyIncludedDestinations() { return dynamicallyIncludedDestinations; } /** - * @param dynamicallyIncludedDestinations The dynamicallyIncludedDestinations to set. + * @param dynamicallyIncludedDestinations The + * dynamicallyIncludedDestinations to set. */ - public void setDynamicallyIncludedDestinations(List dynamicallyIncludedDestinations){ - this.dynamicallyIncludedDestinations=dynamicallyIncludedDestinations; + public void setDynamicallyIncludedDestinations(List dynamicallyIncludedDestinations) { + this.dynamicallyIncludedDestinations = dynamicallyIncludedDestinations; } - public void addDynamicallyIncludedDestination(ActiveMQDestination destiantion){ + public void addDynamicallyIncludedDestination(ActiveMQDestination destiantion) { this.dynamicallyIncludedDestinations.add(destiantion); } - - public ConnectionFilter getConnectionFilter(){ + + public ConnectionFilter getConnectionFilter() { return connectionFilter; } - public void setConnectionFilter(ConnectionFilter connectionFilter){ - this.connectionFilter=connectionFilter; + public void setConnectionFilter(ConnectionFilter connectionFilter) { + this.connectionFilter = connectionFilter; } - // Implementation methods // ------------------------------------------------------------------------- - protected NetworkBridge configureBridge(DemandForwardingBridgeSupport result){ - List destsList=getDynamicallyIncludedDestinations(); - ActiveMQDestination dests[]=(ActiveMQDestination[])destsList.toArray(new ActiveMQDestination[destsList.size()]); + protected NetworkBridge configureBridge(DemandForwardingBridgeSupport result) { + List destsList = getDynamicallyIncludedDestinations(); + ActiveMQDestination dests[] = (ActiveMQDestination[])destsList + .toArray(new ActiveMQDestination[destsList.size()]); result.setDynamicallyIncludedDestinations(dests); - destsList=getExcludedDestinations(); - dests=(ActiveMQDestination[])destsList.toArray(new ActiveMQDestination[destsList.size()]); + destsList = getExcludedDestinations(); + dests = (ActiveMQDestination[])destsList.toArray(new ActiveMQDestination[destsList.size()]); result.setExcludedDestinations(dests); - destsList=getStaticallyIncludedDestinations(); - dests=(ActiveMQDestination[])destsList.toArray(new ActiveMQDestination[destsList.size()]); + destsList = getStaticallyIncludedDestinations(); + dests = (ActiveMQDestination[])destsList.toArray(new ActiveMQDestination[destsList.size()]); result.setStaticallyIncludedDestinations(dests); - if(durableDestinations!=null){ - ActiveMQDestination[] dest=new ActiveMQDestination[durableDestinations.size()]; - dest=(ActiveMQDestination[])durableDestinations.toArray(dest); + if (durableDestinations != null) { + ActiveMQDestination[] dest = new ActiveMQDestination[durableDestinations.size()]; + dest = (ActiveMQDestination[])durableDestinations.toArray(dest); result.setDurableDestinations(dest); } return result; } - protected Transport createLocalTransport() throws Exception{ + protected Transport createLocalTransport() throws Exception { return TransportFactory.connect(localURI); } - public void start() throws Exception{ + public void start() throws Exception { serviceSupport.start(); } - public void stop() throws Exception{ + public void stop() throws Exception { serviceSupport.stop(); } - + public abstract String getName(); - - protected void handleStart() throws Exception{ - if(localURI==null){ + + protected void handleStart() throws Exception { + if (localURI == null) { throw new IllegalStateException("You must configure the 'localURI' property"); } - log.info("Network Connector "+getName()+" Started"); + log.info("Network Connector " + getName() + " Started"); } - protected void handleStop(ServiceStopper stopper) throws Exception{ - log.info("Network Connector "+getName()+" Stopped"); + protected void handleStop(ServiceStopper stopper) throws Exception { + log.info("Network Connector " + getName() + " Stopped"); } - + public ObjectName getObjectName() { - return objectName; - } + return objectName; + } - public void setObjectName(ObjectName objectName) { - this.objectName = objectName; - } + public void setObjectName(ObjectName objectName) { + this.objectName = objectName; + } - public BrokerService getBrokerService() { - return brokerService; - } + public BrokerService getBrokerService() { + return brokerService; + } - public void setBrokerService(BrokerService brokerService) { - this.brokerService = brokerService; - } + public void setBrokerService(BrokerService brokerService) { + this.brokerService = brokerService; + } - protected void registerNetworkBridgeMBean(NetworkBridge bridge) { - if (!getBrokerService().isUseJmx()) - return; + protected void registerNetworkBridgeMBean(NetworkBridge bridge) { + if (!getBrokerService().isUseJmx()) + return; - MBeanServer mbeanServer = getBrokerService().getManagementContext() - .getMBeanServer(); - if (mbeanServer != null) { - NetworkBridgeViewMBean view = new NetworkBridgeView(bridge); - try { - ObjectName objectName = createNetworkBridgeObjectName(bridge); - mbeanServer.registerMBean(view, objectName); - } catch (Throwable e) { - log.debug("Network bridge could not be registered in JMX: " - + e.getMessage(), e); - } - } - } + MBeanServer mbeanServer = getBrokerService().getManagementContext().getMBeanServer(); + if (mbeanServer != null) { + NetworkBridgeViewMBean view = new NetworkBridgeView(bridge); + try { + ObjectName objectName = createNetworkBridgeObjectName(bridge); + mbeanServer.registerMBean(view, objectName); + } catch (Throwable e) { + log.debug("Network bridge could not be registered in JMX: " + e.getMessage(), e); + } + } + } - protected void unregisterNetworkBridgeMBean(NetworkBridge bridge) { - if (!getBrokerService().isUseJmx()) - return; + protected void unregisterNetworkBridgeMBean(NetworkBridge bridge) { + if (!getBrokerService().isUseJmx()) + return; - MBeanServer mbeanServer = getBrokerService().getManagementContext() - .getMBeanServer(); - if (mbeanServer != null) { - try { - ObjectName objectName = createNetworkBridgeObjectName(bridge); - mbeanServer.unregisterMBean(objectName); - } catch (Throwable e) { - log.debug("Network bridge could not be unregistered in JMX: " - + e.getMessage(), e); - } - } - } + MBeanServer mbeanServer = getBrokerService().getManagementContext().getMBeanServer(); + if (mbeanServer != null) { + try { + ObjectName objectName = createNetworkBridgeObjectName(bridge); + mbeanServer.unregisterMBean(objectName); + } catch (Throwable e) { + log.debug("Network bridge could not be unregistered in JMX: " + e.getMessage(), e); + } + } + } - protected ObjectName createNetworkBridgeObjectName(NetworkBridge bridge) - throws MalformedObjectNameException { - ObjectName connectorName = getObjectName(); - Hashtable map = connectorName.getKeyPropertyList(); - return new ObjectName(connectorName.getDomain() - + ":" - + "BrokerName=" - + JMXSupport.encodeObjectNamePart((String) map - .get("BrokerName")) - + "," - + "Type=NetworkBridge," - + "NetworkConnectorName=" - + JMXSupport.encodeObjectNamePart((String) map - .get("NetworkConnectorName")) - + "," - + "Name=" - + JMXSupport.encodeObjectNamePart(JMXSupport - .encodeObjectNamePart(bridge.getRemoteAddress()))); - } + protected ObjectName createNetworkBridgeObjectName(NetworkBridge bridge) + throws MalformedObjectNameException { + ObjectName connectorName = getObjectName(); + Hashtable map = connectorName.getKeyPropertyList(); + return new ObjectName(connectorName.getDomain() + + ":" + + "BrokerName=" + + JMXSupport.encodeObjectNamePart((String)map.get("BrokerName")) + + "," + + "Type=NetworkBridge," + + "NetworkConnectorName=" + + JMXSupport.encodeObjectNamePart((String)map.get("NetworkConnectorName")) + + "," + + "Name=" + + JMXSupport.encodeObjectNamePart(JMXSupport.encodeObjectNamePart(bridge + .getRemoteAddress()))); + } } diff --git a/activemq-core/src/main/java/org/apache/activemq/network/jms/InboundQueueBridge.java b/activemq-core/src/main/java/org/apache/activemq/network/jms/InboundQueueBridge.java index dbdd5a2e52..cc1378fb54 100755 --- a/activemq-core/src/main/java/org/apache/activemq/network/jms/InboundQueueBridge.java +++ b/activemq-core/src/main/java/org/apache/activemq/network/jms/InboundQueueBridge.java @@ -16,7 +16,6 @@ */ package org.apache.activemq.network.jms; - /** * Create an Inbound Queue Bridge * @@ -24,38 +23,40 @@ package org.apache.activemq.network.jms; * * @version $Revision: 1.1.1.1 $ */ -public class InboundQueueBridge extends QueueBridge{ - +public class InboundQueueBridge extends QueueBridge { + String inboundQueueName; String localQueueName; + /** * Constructor that takes a foriegn destination as an argument + * * @param inboundQueueName */ - public InboundQueueBridge(String inboundQueueName){ - this.inboundQueueName = inboundQueueName; - this.localQueueName = inboundQueueName; + public InboundQueueBridge(String inboundQueueName) { + this.inboundQueueName = inboundQueueName; + this.localQueueName = inboundQueueName; } - + /** * Default Contructor */ - public InboundQueueBridge(){ + public InboundQueueBridge() { } /** * @return Returns the inboundQueueName. */ - public String getInboundQueueName(){ + public String getInboundQueueName() { return inboundQueueName; } /** * @param inboundQueueName The inboundQueueName to set. */ - public void setInboundQueueName(String inboundQueueName){ - this.inboundQueueName=inboundQueueName; - if (this.localQueueName == null){ + public void setInboundQueueName(String inboundQueueName) { + this.inboundQueueName = inboundQueueName; + if (this.localQueueName == null) { this.localQueueName = inboundQueueName; } } @@ -63,15 +64,15 @@ public class InboundQueueBridge extends QueueBridge{ /** * @return the localQueueName */ - public String getLocalQueueName(){ + public String getLocalQueueName() { return localQueueName; } /** * @param localQueueName the localQueueName to set */ - public void setLocalQueueName(String localQueueName){ - this.localQueueName=localQueueName; + public void setLocalQueueName(String localQueueName) { + this.localQueueName = localQueueName; } - + } diff --git a/activemq-core/src/main/java/org/apache/activemq/network/jms/InboundTopicBridge.java b/activemq-core/src/main/java/org/apache/activemq/network/jms/InboundTopicBridge.java index a8ce84023b..df3dd00398 100755 --- a/activemq-core/src/main/java/org/apache/activemq/network/jms/InboundTopicBridge.java +++ b/activemq-core/src/main/java/org/apache/activemq/network/jms/InboundTopicBridge.java @@ -16,7 +16,6 @@ */ package org.apache.activemq.network.jms; - /** * Create an Inbound Topic Bridge * @@ -24,38 +23,40 @@ package org.apache.activemq.network.jms; * * @version $Revision: 1.1.1.1 $ */ -public class InboundTopicBridge extends TopicBridge{ - +public class InboundTopicBridge extends TopicBridge { + String inboundTopicName; String localTopicName; + /** * Constructor that takes a foriegn destination as an argument + * * @param inboundTopicName */ - public InboundTopicBridge(String inboundTopicName){ + public InboundTopicBridge(String inboundTopicName) { this.inboundTopicName = inboundTopicName; this.localTopicName = inboundTopicName; } - + /** * Default Contructor */ - public InboundTopicBridge(){ + public InboundTopicBridge() { } /** * @return Returns the outboundTopicName. */ - public String getInboundTopicName(){ + public String getInboundTopicName() { return inboundTopicName; } /** - * @param inboundTopicName + * @param inboundTopicName */ - public void setInboundTopicName(String inboundTopicName){ - this.inboundTopicName=inboundTopicName; - if(this.localTopicName==null){ + public void setInboundTopicName(String inboundTopicName) { + this.inboundTopicName = inboundTopicName; + if (this.localTopicName == null) { this.localTopicName = inboundTopicName; } } @@ -63,15 +64,15 @@ public class InboundTopicBridge extends TopicBridge{ /** * @return the localTopicName */ - public String getLocalTopicName(){ + public String getLocalTopicName() { return localTopicName; } /** * @param localTopicName the localTopicName to set */ - public void setLocalTopicName(String localTopicName){ - this.localTopicName=localTopicName; + public void setLocalTopicName(String localTopicName) { + this.localTopicName = localTopicName; } - + } diff --git a/activemq-core/src/main/java/org/apache/activemq/network/jms/JmsQueueConnector.java b/activemq-core/src/main/java/org/apache/activemq/network/jms/JmsQueueConnector.java index db5131ccf8..69c2dbf520 100755 --- a/activemq-core/src/main/java/org/apache/activemq/network/jms/JmsQueueConnector.java +++ b/activemq-core/src/main/java/org/apache/activemq/network/jms/JmsQueueConnector.java @@ -28,15 +28,16 @@ import javax.jms.QueueConnectionFactory; import javax.jms.QueueSession; import javax.jms.Session; import javax.naming.NamingException; + /** * A Bridge to other JMS Queue providers * * @org.apache.xbean.XBean - * + * * @version $Revision: 1.1.1.1 $ */ -public class JmsQueueConnector extends JmsConnector{ - private static final Log log=LogFactory.getLog(JmsQueueConnector.class); +public class JmsQueueConnector extends JmsConnector { + private static final Log log = LogFactory.getLog(JmsQueueConnector.class); private String outboundQueueConnectionFactoryName; private String localConnectionFactoryName; private QueueConnectionFactory outboundQueueConnectionFactory; @@ -44,145 +45,138 @@ public class JmsQueueConnector extends JmsConnector{ private QueueConnection outboundQueueConnection; private QueueConnection localQueueConnection; private InboundQueueBridge[] inboundQueueBridges; - private OutboundQueueBridge[] outboundQueueBridges; + private OutboundQueueBridge[] outboundQueueBridges; - public boolean init(){ - boolean result=super.init(); - if(result){ - try{ + public boolean init() { + boolean result = super.init(); + if (result) { + try { initializeForeignQueueConnection(); initializeLocalQueueConnection(); initializeInboundJmsMessageConvertor(); initializeOutboundJmsMessageConvertor(); initializeInboundQueueBridges(); initializeOutboundQueueBridges(); - }catch(Exception e){ - log.error("Failed to initialize the JMSConnector",e); + } catch (Exception e) { + log.error("Failed to initialize the JMSConnector", e); } } return result; - } - + } - /** * @return Returns the inboundQueueBridges. */ - public InboundQueueBridge[] getInboundQueueBridges(){ + public InboundQueueBridge[] getInboundQueueBridges() { return inboundQueueBridges; } /** - * @param inboundQueueBridges - * The inboundQueueBridges to set. + * @param inboundQueueBridges The inboundQueueBridges to set. */ - public void setInboundQueueBridges(InboundQueueBridge[] inboundQueueBridges){ - this.inboundQueueBridges=inboundQueueBridges; + public void setInboundQueueBridges(InboundQueueBridge[] inboundQueueBridges) { + this.inboundQueueBridges = inboundQueueBridges; } /** * @return Returns the outboundQueueBridges. */ - public OutboundQueueBridge[] getOutboundQueueBridges(){ + public OutboundQueueBridge[] getOutboundQueueBridges() { return outboundQueueBridges; } /** - * @param outboundQueueBridges - * The outboundQueueBridges to set. + * @param outboundQueueBridges The outboundQueueBridges to set. */ - public void setOutboundQueueBridges(OutboundQueueBridge[] outboundQueueBridges){ - this.outboundQueueBridges=outboundQueueBridges; + public void setOutboundQueueBridges(OutboundQueueBridge[] outboundQueueBridges) { + this.outboundQueueBridges = outboundQueueBridges; } /** * @return Returns the localQueueConnectionFactory. */ - public QueueConnectionFactory getLocalQueueConnectionFactory(){ + public QueueConnectionFactory getLocalQueueConnectionFactory() { return localQueueConnectionFactory; } /** - * @param localQueueConnectionFactory - * The localQueueConnectionFactory to set. + * @param localQueueConnectionFactory The localQueueConnectionFactory to + * set. */ - public void setLocalQueueConnectionFactory(QueueConnectionFactory localConnectionFactory){ - this.localQueueConnectionFactory=localConnectionFactory; + public void setLocalQueueConnectionFactory(QueueConnectionFactory localConnectionFactory) { + this.localQueueConnectionFactory = localConnectionFactory; } /** * @return Returns the outboundQueueConnectionFactory. */ - public QueueConnectionFactory getOutboundQueueConnectionFactory(){ + public QueueConnectionFactory getOutboundQueueConnectionFactory() { return outboundQueueConnectionFactory; } /** * @return Returns the outboundQueueConnectionFactoryName. */ - public String getOutboundQueueConnectionFactoryName(){ + public String getOutboundQueueConnectionFactoryName() { return outboundQueueConnectionFactoryName; } /** - * @param outboundQueueConnectionFactoryName - * The outboundQueueConnectionFactoryName to set. + * @param outboundQueueConnectionFactoryName The + * outboundQueueConnectionFactoryName to set. */ - public void setOutboundQueueConnectionFactoryName(String foreignQueueConnectionFactoryName){ - this.outboundQueueConnectionFactoryName=foreignQueueConnectionFactoryName; + public void setOutboundQueueConnectionFactoryName(String foreignQueueConnectionFactoryName) { + this.outboundQueueConnectionFactoryName = foreignQueueConnectionFactoryName; } /** * @return Returns the localConnectionFactoryName. */ - public String getLocalConnectionFactoryName(){ + public String getLocalConnectionFactoryName() { return localConnectionFactoryName; } /** - * @param localConnectionFactoryName - * The localConnectionFactoryName to set. + * @param localConnectionFactoryName The localConnectionFactoryName to set. */ - public void setLocalConnectionFactoryName(String localConnectionFactoryName){ - this.localConnectionFactoryName=localConnectionFactoryName; + public void setLocalConnectionFactoryName(String localConnectionFactoryName) { + this.localConnectionFactoryName = localConnectionFactoryName; } /** * @return Returns the localQueueConnection. */ - public QueueConnection getLocalQueueConnection(){ + public QueueConnection getLocalQueueConnection() { return localQueueConnection; } /** - * @param localQueueConnection - * The localQueueConnection to set. + * @param localQueueConnection The localQueueConnection to set. */ - public void setLocalQueueConnection(QueueConnection localQueueConnection){ - this.localQueueConnection=localQueueConnection; + public void setLocalQueueConnection(QueueConnection localQueueConnection) { + this.localQueueConnection = localQueueConnection; } /** * @return Returns the outboundQueueConnection. */ - public QueueConnection getOutboundQueueConnection(){ + public QueueConnection getOutboundQueueConnection() { return outboundQueueConnection; } /** - * @param outboundQueueConnection - * The outboundQueueConnection to set. + * @param outboundQueueConnection The outboundQueueConnection to set. */ - public void setOutboundQueueConnection(QueueConnection foreignQueueConnection){ - this.outboundQueueConnection=foreignQueueConnection; + public void setOutboundQueueConnection(QueueConnection foreignQueueConnection) { + this.outboundQueueConnection = foreignQueueConnection; } /** - * @param outboundQueueConnectionFactory - * The outboundQueueConnectionFactory to set. + * @param outboundQueueConnectionFactory The outboundQueueConnectionFactory + * to set. */ - public void setOutboundQueueConnectionFactory(QueueConnectionFactory foreignQueueConnectionFactory){ - this.outboundQueueConnectionFactory=foreignQueueConnectionFactory; + public void setOutboundQueueConnectionFactory(QueueConnectionFactory foreignQueueConnectionFactory) { + this.outboundQueueConnectionFactory = foreignQueueConnectionFactory; } public void restartProducerConnection() throws NamingException, JMSException { @@ -190,91 +184,93 @@ public class JmsQueueConnector extends JmsConnector{ initializeForeignQueueConnection(); } - protected void initializeForeignQueueConnection() throws NamingException,JMSException{ - if(outboundQueueConnection==null){ + protected void initializeForeignQueueConnection() throws NamingException, JMSException { + if (outboundQueueConnection == null) { // get the connection factories - if(outboundQueueConnectionFactory==null){ + if (outboundQueueConnectionFactory == null) { // look it up from JNDI - if(outboundQueueConnectionFactoryName!=null){ - outboundQueueConnectionFactory=(QueueConnectionFactory) jndiOutboundTemplate.lookup( - outboundQueueConnectionFactoryName,QueueConnectionFactory.class); - if(outboundUsername!=null){ - outboundQueueConnection=outboundQueueConnectionFactory.createQueueConnection(outboundUsername, - outboundPassword); - }else{ - outboundQueueConnection=outboundQueueConnectionFactory.createQueueConnection(); + if (outboundQueueConnectionFactoryName != null) { + outboundQueueConnectionFactory = (QueueConnectionFactory)jndiOutboundTemplate + .lookup(outboundQueueConnectionFactoryName, QueueConnectionFactory.class); + if (outboundUsername != null) { + outboundQueueConnection = outboundQueueConnectionFactory + .createQueueConnection(outboundUsername, outboundPassword); + } else { + outboundQueueConnection = outboundQueueConnectionFactory.createQueueConnection(); } - }else { + } else { throw new JMSException("Cannot create localConnection - no information"); } - }else { - if(outboundUsername!=null){ - outboundQueueConnection=outboundQueueConnectionFactory.createQueueConnection(outboundUsername, - outboundPassword); - }else{ - outboundQueueConnection=outboundQueueConnectionFactory.createQueueConnection(); + } else { + if (outboundUsername != null) { + outboundQueueConnection = outboundQueueConnectionFactory + .createQueueConnection(outboundUsername, outboundPassword); + } else { + outboundQueueConnection = outboundQueueConnectionFactory.createQueueConnection(); } } } outboundQueueConnection.start(); } - protected void initializeLocalQueueConnection() throws NamingException,JMSException{ - if(localQueueConnection==null){ + protected void initializeLocalQueueConnection() throws NamingException, JMSException { + if (localQueueConnection == null) { // get the connection factories - if(localQueueConnectionFactory==null){ - if(embeddedConnectionFactory==null){ + if (localQueueConnectionFactory == null) { + if (embeddedConnectionFactory == null) { // look it up from JNDI - if(localConnectionFactoryName!=null){ - localQueueConnectionFactory=(QueueConnectionFactory) jndiLocalTemplate.lookup( - localConnectionFactoryName,QueueConnectionFactory.class); - if(localUsername!=null){ - localQueueConnection=localQueueConnectionFactory.createQueueConnection(localUsername, - localPassword); - }else{ - localQueueConnection=localQueueConnectionFactory.createQueueConnection(); + if (localConnectionFactoryName != null) { + localQueueConnectionFactory = (QueueConnectionFactory)jndiLocalTemplate + .lookup(localConnectionFactoryName, QueueConnectionFactory.class); + if (localUsername != null) { + localQueueConnection = localQueueConnectionFactory + .createQueueConnection(localUsername, localPassword); + } else { + localQueueConnection = localQueueConnectionFactory.createQueueConnection(); } - }else { + } else { throw new JMSException("Cannot create localConnection - no information"); } - }else{ + } else { localQueueConnection = embeddedConnectionFactory.createQueueConnection(); } - }else { - if(localUsername!=null){ - localQueueConnection=localQueueConnectionFactory.createQueueConnection(localUsername, - localPassword); - }else{ - localQueueConnection=localQueueConnectionFactory.createQueueConnection(); + } else { + if (localUsername != null) { + localQueueConnection = localQueueConnectionFactory.createQueueConnection(localUsername, + localPassword); + } else { + localQueueConnection = localQueueConnectionFactory.createQueueConnection(); } } } localQueueConnection.start(); } - - protected void initializeInboundJmsMessageConvertor(){ - inboundMessageConvertor.setConnection(localQueueConnection); - } - - protected void initializeOutboundJmsMessageConvertor(){ - outboundMessageConvertor.setConnection(outboundQueueConnection); + + protected void initializeInboundJmsMessageConvertor() { + inboundMessageConvertor.setConnection(localQueueConnection); } - protected void initializeInboundQueueBridges() throws JMSException{ - if(inboundQueueBridges!=null){ - QueueSession outboundSession = outboundQueueConnection.createQueueSession(false,Session.AUTO_ACKNOWLEDGE); - QueueSession localSession = localQueueConnection.createQueueSession(false,Session.AUTO_ACKNOWLEDGE); - for(int i=0;i0){ - consumer=consumerSession.createReceiver(consumerQueue,selector); - }else{ - consumer=consumerSession.createReceiver(consumerQueue); - } - + consumerSession = consumerConnection.createQueueSession(false, Session.CLIENT_ACKNOWLEDGE); + MessageConsumer consumer = null; + + if (selector != null && selector.length() > 0) { + consumer = consumerSession.createReceiver(consumerQueue, selector); + } else { + consumer = consumerSession.createReceiver(consumerQueue); + } + return consumer; } - - protected synchronized MessageProducer createProducer() throws JMSException{ - producerSession=producerConnection.createQueueSession(false,Session.AUTO_ACKNOWLEDGE); + + protected synchronized MessageProducer createProducer() throws JMSException { + producerSession = producerConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); producer = producerSession.createSender(null); return producer; } - - - - - protected synchronized void sendMessage(Message message) throws JMSException{ + + protected synchronized void sendMessage(Message message) throws JMSException { if (producer == null) { createProducer(); } - producer.send(producerQueue,message); + producer.send(producerQueue, message); } /** * @return Returns the consumerConnection. */ - public QueueConnection getConsumerConnection(){ + public QueueConnection getConsumerConnection() { return consumerConnection; } /** * @param consumerConnection The consumerConnection to set. */ - public void setConsumerConnection(QueueConnection consumerConnection){ - this.consumerConnection=consumerConnection; + public void setConsumerConnection(QueueConnection consumerConnection) { + this.consumerConnection = consumerConnection; } /** * @return Returns the consumerQueue. */ - public Queue getConsumerQueue(){ + public Queue getConsumerQueue() { return consumerQueue; } /** * @param consumerQueue The consumerQueue to set. */ - public void setConsumerQueue(Queue consumerQueue){ - this.consumerQueue=consumerQueue; + public void setConsumerQueue(Queue consumerQueue) { + this.consumerQueue = consumerQueue; } /** * @return Returns the producerConnection. */ - public QueueConnection getProducerConnection(){ + public QueueConnection getProducerConnection() { return producerConnection; } /** * @param producerConnection The producerConnection to set. */ - public void setProducerConnection(QueueConnection producerConnection){ - this.producerConnection=producerConnection; + public void setProducerConnection(QueueConnection producerConnection) { + this.producerConnection = producerConnection; } /** * @return Returns the producerQueue. */ - public Queue getProducerQueue(){ + public Queue getProducerQueue() { return producerQueue; } /** * @param producerQueue The producerQueue to set. */ - public void setProducerQueue(Queue producerQueue){ - this.producerQueue=producerQueue; + public void setProducerQueue(Queue producerQueue) { + this.producerQueue = producerQueue; } /** * @return Returns the selector. */ - public String getSelector(){ + public String getSelector() { return selector; } /** * @param selector The selector to set. */ - public void setSelector(String selector){ - this.selector=selector; + public void setSelector(String selector) { + this.selector = selector; } - - protected Connection getConnnectionForConsumer(){ + + protected Connection getConnnectionForConsumer() { return getConsumerConnection(); } - - protected Connection getConnectionForProducer(){ + + protected Connection getConnectionForProducer() { return getProducerConnection(); } - - + } diff --git a/activemq-core/src/main/java/org/apache/activemq/network/jms/SimpleJmsMessageConvertor.java b/activemq-core/src/main/java/org/apache/activemq/network/jms/SimpleJmsMessageConvertor.java index dc0ba3d296..32fa8aa400 100755 --- a/activemq-core/src/main/java/org/apache/activemq/network/jms/SimpleJmsMessageConvertor.java +++ b/activemq-core/src/main/java/org/apache/activemq/network/jms/SimpleJmsMessageConvertor.java @@ -28,32 +28,32 @@ import javax.jms.Message; * * @version $Revision: 1.1.1.1 $ */ -public class SimpleJmsMessageConvertor implements JmsMesageConvertor { - +public class SimpleJmsMessageConvertor implements JmsMesageConvertor { + /** - * Convert a foreign JMS Message to a native ActiveMQ Message - Inbound - * or visa-versa outbound + * Convert a foreign JMS Message to a native ActiveMQ Message - Inbound or + * visa-versa outbound + * * @param message * @return the converted message * @throws JMSException */ - public Message convert(Message message) throws JMSException{ + public Message convert(Message message) throws JMSException { return message; } - - public Message convert(Message message, Destination replyTo) throws JMSException{ - Message msg = convert(message); - if(replyTo != null) { - msg.setJMSReplyTo(replyTo); - }else{ - msg.setJMSReplyTo(null); - } - return msg; + + public Message convert(Message message, Destination replyTo) throws JMSException { + Message msg = convert(message); + if (replyTo != null) { + msg.setJMSReplyTo(replyTo); + } else { + msg.setJMSReplyTo(null); + } + return msg; } - - public void setConnection(Connection connection){ - //do nothing + + public void setConnection(Connection connection) { + // do nothing } - - + } diff --git a/activemq-core/src/main/java/org/apache/activemq/network/jms/TopicBridge.java b/activemq-core/src/main/java/org/apache/activemq/network/jms/TopicBridge.java index 5505bd4072..b7204254c7 100755 --- a/activemq-core/src/main/java/org/apache/activemq/network/jms/TopicBridge.java +++ b/activemq-core/src/main/java/org/apache/activemq/network/jms/TopicBridge.java @@ -27,12 +27,13 @@ import javax.jms.Topic; import javax.jms.TopicConnection; import javax.jms.TopicPublisher; import javax.jms.TopicSession; + /** * A Destination bridge is used to bridge between to different JMS systems * * @version $Revision: 1.1.1.1 $ */ -class TopicBridge extends DestinationBridge{ +class TopicBridge extends DestinationBridge { protected Topic consumerTopic; protected Topic producerTopic; protected TopicSession consumerSession; @@ -42,150 +43,140 @@ class TopicBridge extends DestinationBridge{ protected TopicPublisher producer; protected TopicConnection consumerConnection; protected TopicConnection producerConnection; - - public void stop() throws Exception{ + public void stop() throws Exception { super.stop(); - if(consumerSession!=null){ + if (consumerSession != null) { consumerSession.close(); } - if(producerSession!=null){ + if (producerSession != null) { producerSession.close(); } } - - - protected MessageConsumer createConsumer() throws JMSException{ + protected MessageConsumer createConsumer() throws JMSException { // set up the consumer - consumerSession=consumerConnection.createTopicSession(false,Session.CLIENT_ACKNOWLEDGE); - MessageConsumer consumer=null; - if(consumerName!=null&&consumerName.length()>0){ - if(selector!=null&&selector.length()>0){ - consumer=consumerSession.createDurableSubscriber(consumerTopic,consumerName,selector,false); - }else{ - consumer=consumerSession.createDurableSubscriber(consumerTopic,consumerName); + consumerSession = consumerConnection.createTopicSession(false, Session.CLIENT_ACKNOWLEDGE); + MessageConsumer consumer = null; + if (consumerName != null && consumerName.length() > 0) { + if (selector != null && selector.length() > 0) { + consumer = consumerSession.createDurableSubscriber(consumerTopic, consumerName, selector, + false); + } else { + consumer = consumerSession.createDurableSubscriber(consumerTopic, consumerName); } - }else{ - if(selector!=null&&selector.length()>0){ - consumer=consumerSession.createSubscriber(consumerTopic,selector,false); - }else{ - consumer=consumerSession.createSubscriber(consumerTopic); + } else { + if (selector != null && selector.length() > 0) { + consumer = consumerSession.createSubscriber(consumerTopic, selector, false); + } else { + consumer = consumerSession.createSubscriber(consumerTopic); } } return consumer; } - - - - protected synchronized MessageProducer createProducer() throws JMSException{ - producerSession=producerConnection.createTopicSession(false,Session.AUTO_ACKNOWLEDGE); + + protected synchronized MessageProducer createProducer() throws JMSException { + producerSession = producerConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE); producer = producerSession.createPublisher(null); return producer; } - - protected synchronized void sendMessage(Message message) throws JMSException{ + + protected synchronized void sendMessage(Message message) throws JMSException { if (producer == null) { createProducer(); } - producer.publish(producerTopic,message); + producer.publish(producerTopic, message); } /** * @return Returns the consumerConnection. */ - public TopicConnection getConsumerConnection(){ + public TopicConnection getConsumerConnection() { return consumerConnection; } /** - * @param consumerConnection - * The consumerConnection to set. + * @param consumerConnection The consumerConnection to set. */ - public void setConsumerConnection(TopicConnection consumerConnection){ - this.consumerConnection=consumerConnection; + public void setConsumerConnection(TopicConnection consumerConnection) { + this.consumerConnection = consumerConnection; } /** * @return Returns the subscriptionName. */ - public String getConsumerName(){ + public String getConsumerName() { return consumerName; } /** - * @param subscriptionName - * The subscriptionName to set. + * @param subscriptionName The subscriptionName to set. */ - public void setConsumerName(String consumerName){ - this.consumerName=consumerName; + public void setConsumerName(String consumerName) { + this.consumerName = consumerName; } /** * @return Returns the consumerTopic. */ - public Topic getConsumerTopic(){ + public Topic getConsumerTopic() { return consumerTopic; } /** - * @param consumerTopic - * The consumerTopic to set. + * @param consumerTopic The consumerTopic to set. */ - public void setConsumerTopic(Topic consumerTopic){ - this.consumerTopic=consumerTopic; + public void setConsumerTopic(Topic consumerTopic) { + this.consumerTopic = consumerTopic; } /** * @return Returns the producerConnection. */ - public TopicConnection getProducerConnection(){ + public TopicConnection getProducerConnection() { return producerConnection; } /** - * @param producerConnection - * The producerConnection to set. + * @param producerConnection The producerConnection to set. */ - public void setProducerConnection(TopicConnection producerConnection){ - this.producerConnection=producerConnection; + public void setProducerConnection(TopicConnection producerConnection) { + this.producerConnection = producerConnection; } /** * @return Returns the producerTopic. */ - public Topic getProducerTopic(){ + public Topic getProducerTopic() { return producerTopic; } /** - * @param producerTopic - * The producerTopic to set. + * @param producerTopic The producerTopic to set. */ - public void setProducerTopic(Topic producerTopic){ - this.producerTopic=producerTopic; + public void setProducerTopic(Topic producerTopic) { + this.producerTopic = producerTopic; } /** * @return Returns the selector. */ - public String getSelector(){ + public String getSelector() { return selector; } /** - * @param selector - * The selector to set. + * @param selector The selector to set. */ - public void setSelector(String selector){ - this.selector=selector; + public void setSelector(String selector) { + this.selector = selector; } - - protected Connection getConnnectionForConsumer(){ + + protected Connection getConnnectionForConsumer() { return getConsumerConnection(); } - - protected Connection getConnectionForProducer(){ + + protected Connection getConnectionForProducer() { return getProducerConnection(); } } diff --git a/activemq-core/src/main/java/org/apache/activemq/openwire/BooleanStream.java b/activemq-core/src/main/java/org/apache/activemq/openwire/BooleanStream.java index e39795a9d4..10931b72bf 100755 --- a/activemq-core/src/main/java/org/apache/activemq/openwire/BooleanStream.java +++ b/activemq-core/src/main/java/org/apache/activemq/openwire/BooleanStream.java @@ -26,101 +26,99 @@ import java.nio.ByteBuffer; final public class BooleanStream { byte data[] = new byte[48]; - short arrayLimit; - short arrayPos; + short arrayLimit; + short arrayPos; byte bytePos; - + public boolean readBoolean() throws IOException { assert arrayPos <= arrayLimit; byte b = data[arrayPos]; - boolean rc = ((b>>bytePos)&0x01)!=0; + boolean rc = ((b >> bytePos) & 0x01) != 0; bytePos++; - if( bytePos >= 8 ) { - bytePos=0; + if (bytePos >= 8) { + bytePos = 0; arrayPos++; } return rc; } - + public void writeBoolean(boolean value) throws IOException { - if( bytePos == 0 ) { + if (bytePos == 0) { arrayLimit++; - if( arrayLimit >= data.length ) { + if (arrayLimit >= data.length) { // re-grow the array. - byte d[] = new byte[data.length*2]; + byte d[] = new byte[data.length * 2]; System.arraycopy(data, 0, d, 0, data.length); data = d; } } - if( value ) { - data[arrayPos] |= (0x01 << bytePos); + if (value) { + data[arrayPos] |= (0x01 << bytePos); } bytePos++; - if( bytePos >= 8 ) { - bytePos=0; + if (bytePos >= 8) { + bytePos = 0; arrayPos++; } } - + public void marshal(DataOutput dataOut) throws IOException { - if( arrayLimit < 64 ) { + if (arrayLimit < 64) { dataOut.writeByte(arrayLimit); - } else if( arrayLimit < 256 ) { // max value of unsigned byte + } else if (arrayLimit < 256) { // max value of unsigned byte dataOut.writeByte(0xC0); - dataOut.writeByte(arrayLimit); + dataOut.writeByte(arrayLimit); } else { dataOut.writeByte(0x80); - dataOut.writeShort(arrayLimit); + dataOut.writeShort(arrayLimit); } - + dataOut.write(data, 0, arrayLimit); clear(); } - + public void marshal(ByteBuffer dataOut) { - if( arrayLimit < 64 ) { - dataOut.put((byte) arrayLimit); - } else if( arrayLimit < 256 ) { // max value of unsigned byte - dataOut.put((byte) 0xC0); - dataOut.put((byte) arrayLimit); + if (arrayLimit < 64) { + dataOut.put((byte)arrayLimit); + } else if (arrayLimit < 256) { // max value of unsigned byte + dataOut.put((byte)0xC0); + dataOut.put((byte)arrayLimit); } else { - dataOut.put((byte) 0x80); - dataOut.putShort(arrayLimit); + dataOut.put((byte)0x80); + dataOut.putShort(arrayLimit); } - + dataOut.put(data, 0, arrayLimit); } - public void unmarshal(DataInput dataIn) throws IOException { - - arrayLimit = (short) (dataIn.readByte() & 0xFF); - if ( arrayLimit == 0xC0 ) { + + arrayLimit = (short)(dataIn.readByte() & 0xFF); + if (arrayLimit == 0xC0) { arrayLimit = (short)(dataIn.readByte() & 0xFF); - } else if( arrayLimit == 0x80 ) { + } else if (arrayLimit == 0x80) { arrayLimit = dataIn.readShort(); - } - if( data.length < arrayLimit ) { + } + if (data.length < arrayLimit) { data = new byte[arrayLimit]; } dataIn.readFully(data, 0, arrayLimit); clear(); } - + public void clear() { - arrayPos=0; - bytePos=0; + arrayPos = 0; + bytePos = 0; } public int marshalledSize() { - if( arrayLimit < 64 ) { - return 1+arrayLimit; + if (arrayLimit < 64) { + return 1 + arrayLimit; } else if (arrayLimit < 256) { - return 2+arrayLimit; + return 2 + arrayLimit; } else { - return 3+arrayLimit; + return 3 + arrayLimit; } } - } diff --git a/activemq-core/src/main/java/org/apache/activemq/openwire/OpenWireFormatFactory.java b/activemq-core/src/main/java/org/apache/activemq/openwire/OpenWireFormatFactory.java index 0d915f9bd0..5edab743a3 100755 --- a/activemq-core/src/main/java/org/apache/activemq/openwire/OpenWireFormatFactory.java +++ b/activemq-core/src/main/java/org/apache/activemq/openwire/OpenWireFormatFactory.java @@ -25,37 +25,38 @@ import org.apache.activemq.wireformat.WireFormatFactory; */ public class OpenWireFormatFactory implements WireFormatFactory { - // - // The default values here are what the wire format changes to after a default negotiation. - // - - private int version=OpenWireFormat.DEFAULT_VERSION; - private boolean stackTraceEnabled=true; - private boolean tcpNoDelayEnabled=true; - private boolean cacheEnabled=true; - private boolean tightEncodingEnabled=true; - private boolean sizePrefixDisabled=false; - private long maxInactivityDuration=30*1000; - private int cacheSize=1024; - + // + // The default values here are what the wire format changes to after a + // default negotiation. + // + + private int version = OpenWireFormat.DEFAULT_VERSION; + private boolean stackTraceEnabled = true; + private boolean tcpNoDelayEnabled = true; + private boolean cacheEnabled = true; + private boolean tightEncodingEnabled = true; + private boolean sizePrefixDisabled = false; + private long maxInactivityDuration = 30 * 1000; + private int cacheSize = 1024; + public WireFormat createWireFormat() { - WireFormatInfo info = new WireFormatInfo(); - info.setVersion(version); - + WireFormatInfo info = new WireFormatInfo(); + info.setVersion(version); + try { - info.setStackTraceEnabled(stackTraceEnabled); - info.setCacheEnabled(cacheEnabled); - info.setTcpNoDelayEnabled(tcpNoDelayEnabled); - info.setTightEncodingEnabled(tightEncodingEnabled); - info.setSizePrefixDisabled(sizePrefixDisabled); + info.setStackTraceEnabled(stackTraceEnabled); + info.setCacheEnabled(cacheEnabled); + info.setTcpNoDelayEnabled(tcpNoDelayEnabled); + info.setTightEncodingEnabled(tightEncodingEnabled); + info.setSizePrefixDisabled(sizePrefixDisabled); info.seMaxInactivityDuration(maxInactivityDuration); info.setCacheSize(cacheSize); - } catch (Exception e) { - IllegalStateException ise = new IllegalStateException("Could not configure WireFormatInfo"); + } catch (Exception e) { + IllegalStateException ise = new IllegalStateException("Could not configure WireFormatInfo"); ise.initCause(e); throw ise; - } - + } + OpenWireFormat f = new OpenWireFormat(); f.setPreferedWireFormatInfo(info); return f; @@ -101,13 +102,13 @@ public class OpenWireFormatFactory implements WireFormatFactory { this.tightEncodingEnabled = tightEncodingEnabled; } - public boolean isSizePrefixDisabled() { - return sizePrefixDisabled; - } + public boolean isSizePrefixDisabled() { + return sizePrefixDisabled; + } - public void setSizePrefixDisabled(boolean sizePrefixDisabled) { - this.sizePrefixDisabled = sizePrefixDisabled; - } + public void setSizePrefixDisabled(boolean sizePrefixDisabled) { + this.sizePrefixDisabled = sizePrefixDisabled; + } public long getMaxInactivityDuration() { return maxInactivityDuration; @@ -117,11 +118,11 @@ public class OpenWireFormatFactory implements WireFormatFactory { this.maxInactivityDuration = maxInactivityDuration; } - public int getCacheSize() { - return cacheSize; - } + public int getCacheSize() { + return cacheSize; + } - public void setCacheSize(int cacheSize) { - this.cacheSize = cacheSize; - } + public void setCacheSize(int cacheSize) { + this.cacheSize = cacheSize; + } } diff --git a/activemq-core/src/main/java/org/apache/activemq/openwire/v1/BaseDataStreamMarshaller.java b/activemq-core/src/main/java/org/apache/activemq/openwire/v1/BaseDataStreamMarshaller.java index 5dd1e4c2e8..6f97e2da75 100755 --- a/activemq-core/src/main/java/org/apache/activemq/openwire/v1/BaseDataStreamMarshaller.java +++ b/activemq-core/src/main/java/org/apache/activemq/openwire/v1/BaseDataStreamMarshaller.java @@ -31,38 +31,43 @@ import org.apache.activemq.util.ClassLoading; abstract public class BaseDataStreamMarshaller implements DataStreamMarshaller { static final public Constructor STACK_TRACE_ELEMENT_CONSTRUCTOR; - + static { - Constructor constructor=null; + Constructor constructor = null; try { - constructor = StackTraceElement.class.getConstructor(new Class[]{String.class, String.class, String.class, int.class}); - } catch (Throwable e) { + constructor = StackTraceElement.class.getConstructor(new Class[] {String.class, String.class, + String.class, int.class}); + } catch (Throwable e) { } STACK_TRACE_ELEMENT_CONSTRUCTOR = constructor; } - abstract public byte getDataStructureType(); + abstract public DataStructure createObject(); - + public int tightMarshal1(OpenWireFormat wireFormat, Object o, BooleanStream bs) throws IOException { return 0; } - public void tightMarshal2(OpenWireFormat wireFormat, Object o, DataOutput dataOut, BooleanStream bs) throws IOException { + + public void tightMarshal2(OpenWireFormat wireFormat, Object o, DataOutput dataOut, BooleanStream bs) + throws IOException { } - public void tightUnmarshal(OpenWireFormat wireFormat, Object o, DataInput dataIn, BooleanStream bs) throws IOException { + + public void tightUnmarshal(OpenWireFormat wireFormat, Object o, DataInput dataIn, BooleanStream bs) + throws IOException { } - + public int tightMarshalLong1(OpenWireFormat wireFormat, long o, BooleanStream bs) throws IOException { - if( o == 0 ) { + if (o == 0) { bs.writeBoolean(false); bs.writeBoolean(false); return 0; - } else if ( (o & 0xFFFFFFFFFFFF0000l ) == 0 ) { + } else if ((o & 0xFFFFFFFFFFFF0000l) == 0) { bs.writeBoolean(false); - bs.writeBoolean(true); + bs.writeBoolean(true); return 2; - } else if ( (o & 0xFFFFFFFF00000000l ) == 0) { + } else if ((o & 0xFFFFFFFF00000000l) == 0) { bs.writeBoolean(true); bs.writeBoolean(false); return 4; @@ -72,61 +77,70 @@ abstract public class BaseDataStreamMarshaller implements DataStreamMarshaller { return 8; } } - public void tightMarshalLong2(OpenWireFormat wireFormat, long o, DataOutput dataOut, BooleanStream bs) throws IOException { - if( bs.readBoolean() ) { - if( bs.readBoolean() ) { + + public void tightMarshalLong2(OpenWireFormat wireFormat, long o, DataOutput dataOut, BooleanStream bs) + throws IOException { + if (bs.readBoolean()) { + if (bs.readBoolean()) { dataOut.writeLong(o); } else { - dataOut.writeInt((int) o); + dataOut.writeInt((int)o); } } else { - if( bs.readBoolean() ) { - dataOut.writeShort((int) o); + if (bs.readBoolean()) { + dataOut.writeShort((int)o); } } } - public long tightUnmarshalLong(OpenWireFormat wireFormat, DataInput dataIn, BooleanStream bs) throws IOException { - if( bs.readBoolean() ) { - if( bs.readBoolean() ) { + + public long tightUnmarshalLong(OpenWireFormat wireFormat, DataInput dataIn, BooleanStream bs) + throws IOException { + if (bs.readBoolean()) { + if (bs.readBoolean()) { return dataIn.readLong(); } else { return toLong(dataIn.readInt()); } } else { - if( bs.readBoolean() ) { + if (bs.readBoolean()) { return toLong(dataIn.readShort()); } else { return 0; } } } - + protected long toLong(short value) { // lets handle negative values long answer = value; return answer & 0xffffL; } - + protected long toLong(int value) { // lets handle negative values long answer = value; return answer & 0xffffffffL; } - - protected DataStructure tightUnmarsalNestedObject(OpenWireFormat wireFormat, DataInput dataIn, BooleanStream bs) throws IOException { + + protected DataStructure tightUnmarsalNestedObject(OpenWireFormat wireFormat, DataInput dataIn, + BooleanStream bs) throws IOException { return wireFormat.tightUnmarshalNestedObject(dataIn, bs); - } - protected int tightMarshalNestedObject1(OpenWireFormat wireFormat, DataStructure o, BooleanStream bs) throws IOException { + } + + protected int tightMarshalNestedObject1(OpenWireFormat wireFormat, DataStructure o, BooleanStream bs) + throws IOException { return wireFormat.tightMarshalNestedObject1(o, bs); } - - protected void tightMarshalNestedObject2(OpenWireFormat wireFormat, DataStructure o, DataOutput dataOut, BooleanStream bs) throws IOException { + + protected void tightMarshalNestedObject2(OpenWireFormat wireFormat, DataStructure o, DataOutput dataOut, + BooleanStream bs) throws IOException { wireFormat.tightMarshalNestedObject2(o, dataOut, bs); } - protected DataStructure tightUnmarsalCachedObject(OpenWireFormat wireFormat, DataInput dataIn, BooleanStream bs) throws IOException { - if( wireFormat.isCacheEnabled() ) { - if( bs.readBoolean() ) { + protected DataStructure tightUnmarsalCachedObject(OpenWireFormat wireFormat, DataInput dataIn, + BooleanStream bs) throws IOException { + if (wireFormat.isCacheEnabled()) { + if (bs.readBoolean()) { short index = dataIn.readShort(); DataStructure object = wireFormat.tightUnmarshalNestedObject(dataIn, bs); wireFormat.setInUnmarshallCache(index, object); @@ -138,26 +152,30 @@ abstract public class BaseDataStreamMarshaller implements DataStreamMarshaller { } else { return wireFormat.tightUnmarshalNestedObject(dataIn, bs); } - } - protected int tightMarshalCachedObject1(OpenWireFormat wireFormat, DataStructure o, BooleanStream bs) throws IOException { - if( wireFormat.isCacheEnabled() ) { + } + + protected int tightMarshalCachedObject1(OpenWireFormat wireFormat, DataStructure o, BooleanStream bs) + throws IOException { + if (wireFormat.isCacheEnabled()) { Short index = wireFormat.getMarshallCacheIndex(o); bs.writeBoolean(index == null); - if( index == null ) { + if (index == null) { int rc = wireFormat.tightMarshalNestedObject1(o, bs); wireFormat.addToMarshallCache(o); - return 2+rc; + return 2 + rc; } else { return 2; } } else { return wireFormat.tightMarshalNestedObject1(o, bs); } - } - protected void tightMarshalCachedObject2(OpenWireFormat wireFormat, DataStructure o, DataOutput dataOut, BooleanStream bs) throws IOException { - if( wireFormat.isCacheEnabled() ) { + } + + protected void tightMarshalCachedObject2(OpenWireFormat wireFormat, DataStructure o, DataOutput dataOut, + BooleanStream bs) throws IOException { + if (wireFormat.isCacheEnabled()) { Short index = wireFormat.getMarshallCacheIndex(o); - if( bs.readBoolean() ) { + if (bs.readBoolean()) { dataOut.writeShort(index.shortValue()); wireFormat.tightMarshalNestedObject2(o, dataOut, bs); } else { @@ -167,23 +185,23 @@ abstract public class BaseDataStreamMarshaller implements DataStreamMarshaller { wireFormat.tightMarshalNestedObject2(o, dataOut, bs); } } - - protected Throwable tightUnmarsalThrowable(OpenWireFormat wireFormat, DataInput dataIn, BooleanStream bs) throws IOException { - if( bs.readBoolean() ) { - String clazz = tightUnmarshalString(dataIn, bs); + + protected Throwable tightUnmarsalThrowable(OpenWireFormat wireFormat, DataInput dataIn, BooleanStream bs) + throws IOException { + if (bs.readBoolean()) { + String clazz = tightUnmarshalString(dataIn, bs); String message = tightUnmarshalString(dataIn, bs); Throwable o = createThrowable(clazz, message); - if( wireFormat.isStackTraceEnabled() ) { - if( STACK_TRACE_ELEMENT_CONSTRUCTOR!=null) { + if (wireFormat.isStackTraceEnabled()) { + if (STACK_TRACE_ELEMENT_CONSTRUCTOR != null) { StackTraceElement ss[] = new StackTraceElement[dataIn.readShort()]; for (int i = 0; i < ss.length; i++) { try { - ss[i] = (StackTraceElement) STACK_TRACE_ELEMENT_CONSTRUCTOR.newInstance(new Object[]{ - tightUnmarshalString(dataIn, bs), - tightUnmarshalString(dataIn, bs), - tightUnmarshalString(dataIn, bs), - new Integer(dataIn.readInt()) - }); + ss[i] = (StackTraceElement)STACK_TRACE_ELEMENT_CONSTRUCTOR + .newInstance(new Object[] {tightUnmarshalString(dataIn, bs), + tightUnmarshalString(dataIn, bs), + tightUnmarshalString(dataIn, bs), + new Integer(dataIn.readInt())}); } catch (IOException e) { throw e; } catch (Throwable e) { @@ -194,40 +212,41 @@ abstract public class BaseDataStreamMarshaller implements DataStreamMarshaller { short size = dataIn.readShort(); for (int i = 0; i < size; i++) { tightUnmarshalString(dataIn, bs); - tightUnmarshalString(dataIn, bs); - tightUnmarshalString(dataIn, bs); + tightUnmarshalString(dataIn, bs); + tightUnmarshalString(dataIn, bs); dataIn.readInt(); } } o.initCause(tightUnmarsalThrowable(wireFormat, dataIn, bs)); - + } return o; } else { return null; } } - + private Throwable createThrowable(String className, String message) { try { Class clazz = ClassLoading.loadClass(className, BaseDataStreamMarshaller.class.getClassLoader()); - Constructor constructor = clazz.getConstructor(new Class[]{String.class}); - return (Throwable) constructor.newInstance(new Object[]{message}); + Constructor constructor = clazz.getConstructor(new Class[] {String.class}); + return (Throwable)constructor.newInstance(new Object[] {message}); } catch (Throwable e) { - return new Throwable(className+": "+message); + return new Throwable(className + ": " + message); } } - - protected int tightMarshalThrowable1(OpenWireFormat wireFormat, Throwable o, BooleanStream bs) throws IOException { - if( o==null ) { + + protected int tightMarshalThrowable1(OpenWireFormat wireFormat, Throwable o, BooleanStream bs) + throws IOException { + if (o == null) { bs.writeBoolean(false); return 0; } else { - int rc=0; + int rc = 0; bs.writeBoolean(true); rc += tightMarshalString1(o.getClass().getName(), bs); rc += tightMarshalString1(o.getMessage(), bs); - if( wireFormat.isStackTraceEnabled() ) { + if (wireFormat.isStackTraceEnabled()) { rc += 2; StackTraceElement[] stackTrace = o.getStackTrace(); for (int i = 0; i < stackTrace.length; i++) { @@ -242,12 +261,13 @@ abstract public class BaseDataStreamMarshaller implements DataStreamMarshaller { return rc; } } - - protected void tightMarshalThrowable2(OpenWireFormat wireFormat, Throwable o, DataOutput dataOut, BooleanStream bs) throws IOException { - if( bs.readBoolean() ) { + + protected void tightMarshalThrowable2(OpenWireFormat wireFormat, Throwable o, DataOutput dataOut, + BooleanStream bs) throws IOException { + if (bs.readBoolean()) { tightMarshalString2(o.getClass().getName(), dataOut, bs); tightMarshalString2(o.getMessage(), dataOut, bs); - if( wireFormat.isStackTraceEnabled() ) { + if (wireFormat.isStackTraceEnabled()) { StackTraceElement[] stackTrace = o.getStackTrace(); dataOut.writeShort(stackTrace.length); for (int i = 0; i < stackTrace.length; i++) { @@ -261,31 +281,32 @@ abstract public class BaseDataStreamMarshaller implements DataStreamMarshaller { } } } - + protected String tightUnmarshalString(DataInput dataIn, BooleanStream bs) throws IOException { - if( bs.readBoolean() ) { - if( bs.readBoolean() ) { + if (bs.readBoolean()) { + if (bs.readBoolean()) { int size = dataIn.readShort(); byte data[] = new byte[size]; dataIn.readFully(data); - return new String(data,0); // Yes deprecated, but we know what we are doing. - } else { + return new String(data, 0); // Yes deprecated, but we know what + // we are doing. + } else { return dataIn.readUTF(); } } else { return null; } } - - protected int tightMarshalString1(String value, BooleanStream bs) throws IOException { - bs.writeBoolean(value!=null); - if( value!=null ) { - + + protected int tightMarshalString1(String value, BooleanStream bs) throws IOException { + bs.writeBoolean(value != null); + if (value != null) { + int strlen = value.length(); int utflen = 0; char[] charr = new char[strlen]; int c, count = 0; - boolean isOnlyAscii=true; + boolean isOnlyAscii = true; value.getChars(0, strlen, charr, 0); @@ -295,43 +316,44 @@ abstract public class BaseDataStreamMarshaller implements DataStreamMarshaller { utflen++; } else if (c > 0x07FF) { utflen += 3; - isOnlyAscii=false; + isOnlyAscii = false; } else { - isOnlyAscii=false; + isOnlyAscii = false; utflen += 2; } } - - if( utflen >= Short.MAX_VALUE ) + + if (utflen >= Short.MAX_VALUE) { throw new IOException("Encountered a String value that is too long to encode."); - - bs.writeBoolean(isOnlyAscii); - return utflen+2; - + } + bs.writeBoolean(isOnlyAscii); + return utflen + 2; + } else { return 0; } } - + protected void tightMarshalString2(String value, DataOutput dataOut, BooleanStream bs) throws IOException { - if( bs.readBoolean() ) { + if (bs.readBoolean()) { // If we verified it only holds ascii values - if( bs.readBoolean() ) { + if (bs.readBoolean()) { dataOut.writeShort(value.length()); dataOut.writeBytes(value); } else { - dataOut.writeUTF(value); + dataOut.writeUTF(value); } } - } - - protected int tightMarshalObjectArray1(OpenWireFormat wireFormat, DataStructure[] objects, BooleanStream bs) throws IOException { - if( objects != null ) { - int rc=0; + } + + protected int tightMarshalObjectArray1(OpenWireFormat wireFormat, DataStructure[] objects, + BooleanStream bs) throws IOException { + if (objects != null) { + int rc = 0; bs.writeBoolean(true); rc += 2; - for( int i=0; i < objects.length; i++ ) { - rc += tightMarshalNestedObject1(wireFormat,objects[i], bs); + for (int i = 0; i < objects.length; i++) { + rc += tightMarshalNestedObject1(wireFormat, objects[i], bs); } return rc; } else { @@ -339,12 +361,13 @@ abstract public class BaseDataStreamMarshaller implements DataStreamMarshaller { return 0; } } - - protected void tightMarshalObjectArray2(OpenWireFormat wireFormat, DataStructure[] objects, DataOutput dataOut, BooleanStream bs) throws IOException { - if( bs.readBoolean() ) { + + protected void tightMarshalObjectArray2(OpenWireFormat wireFormat, DataStructure[] objects, + DataOutput dataOut, BooleanStream bs) throws IOException { + if (bs.readBoolean()) { dataOut.writeShort(objects.length); - for( int i=0; i < objects.length; i++ ) { - tightMarshalNestedObject2(wireFormat,objects[i], dataOut, bs); + for (int i = 0; i < objects.length; i++) { + tightMarshalNestedObject2(wireFormat, objects[i], dataOut, bs); } } } @@ -352,61 +375,66 @@ abstract public class BaseDataStreamMarshaller implements DataStreamMarshaller { protected int tightMarshalConstByteArray1(byte[] data, BooleanStream bs, int i) throws IOException { return i; } - protected void tightMarshalConstByteArray2(byte[] data, DataOutput dataOut, BooleanStream bs, int i) throws IOException { + + protected void tightMarshalConstByteArray2(byte[] data, DataOutput dataOut, BooleanStream bs, int i) + throws IOException { dataOut.write(data, 0, i); } - protected byte[] tightUnmarshalConstByteArray(DataInput dataIn, BooleanStream bs, int i) throws IOException { + protected byte[] tightUnmarshalConstByteArray(DataInput dataIn, BooleanStream bs, int i) + throws IOException { byte data[] = new byte[i]; dataIn.readFully(data); return data; } protected int tightMarshalByteArray1(byte[] data, BooleanStream bs) throws IOException { - bs.writeBoolean(data!=null); - if( data!=null ){ - return data.length+4; + bs.writeBoolean(data != null); + if (data != null) { + return data.length + 4; } else { return 0; } } - - protected void tightMarshalByteArray2(byte[] data, DataOutput dataOut, BooleanStream bs) throws IOException { - if( bs.readBoolean() ){ + + protected void tightMarshalByteArray2(byte[] data, DataOutput dataOut, BooleanStream bs) + throws IOException { + if (bs.readBoolean()) { dataOut.writeInt(data.length); dataOut.write(data); } } protected byte[] tightUnmarshalByteArray(DataInput dataIn, BooleanStream bs) throws IOException { - byte rc[]=null; - if( bs.readBoolean() ) { + byte rc[] = null; + if (bs.readBoolean()) { int size = dataIn.readInt(); rc = new byte[size]; dataIn.readFully(rc); } return rc; } - + protected int tightMarshalByteSequence1(ByteSequence data, BooleanStream bs) throws IOException { - bs.writeBoolean(data!=null); - if( data!=null ){ - return data.getLength()+4; + bs.writeBoolean(data != null); + if (data != null) { + return data.getLength() + 4; } else { return 0; } } - - protected void tightMarshalByteSequence2(ByteSequence data, DataOutput dataOut, BooleanStream bs) throws IOException { - if( bs.readBoolean() ){ + + protected void tightMarshalByteSequence2(ByteSequence data, DataOutput dataOut, BooleanStream bs) + throws IOException { + if (bs.readBoolean()) { dataOut.writeInt(data.getLength()); dataOut.write(data.getData(), data.getOffset(), data.getLength()); } } protected ByteSequence tightUnmarshalByteSequence(DataInput dataIn, BooleanStream bs) throws IOException { - ByteSequence rc=null; - if( bs.readBoolean() ) { + ByteSequence rc = null; + if (bs.readBoolean()) { int size = dataIn.readInt(); byte[] t = new byte[size]; dataIn.readFully(t); @@ -418,29 +446,35 @@ abstract public class BaseDataStreamMarshaller implements DataStreamMarshaller { // // The loose marshaling logic // - - public void looseMarshal(OpenWireFormat wireFormat, Object o, DataOutput dataOut) throws IOException { + + public void looseMarshal(OpenWireFormat wireFormat, Object o, DataOutput dataOut) throws IOException { } - public void looseUnmarshal(OpenWireFormat wireFormat, Object o, DataInput dataIn) throws IOException { + + public void looseUnmarshal(OpenWireFormat wireFormat, Object o, DataInput dataIn) throws IOException { } - + public void looseMarshalLong(OpenWireFormat wireFormat, long o, DataOutput dataOut) throws IOException { dataOut.writeLong(o); } + public long looseUnmarshalLong(OpenWireFormat wireFormat, DataInput dataIn) throws IOException { return dataIn.readLong(); } - - protected DataStructure looseUnmarsalNestedObject(OpenWireFormat wireFormat, DataInput dataIn) throws IOException { + + protected DataStructure looseUnmarsalNestedObject(OpenWireFormat wireFormat, DataInput dataIn) + throws IOException { return wireFormat.looseUnmarshalNestedObject(dataIn); - } - protected void looseMarshalNestedObject(OpenWireFormat wireFormat, DataStructure o, DataOutput dataOut) throws IOException { + } + + protected void looseMarshalNestedObject(OpenWireFormat wireFormat, DataStructure o, DataOutput dataOut) + throws IOException { wireFormat.looseMarshalNestedObject(o, dataOut); } - protected DataStructure looseUnmarsalCachedObject(OpenWireFormat wireFormat, DataInput dataIn) throws IOException { - if( wireFormat.isCacheEnabled() ) { - if( dataIn.readBoolean() ) { + protected DataStructure looseUnmarsalCachedObject(OpenWireFormat wireFormat, DataInput dataIn) + throws IOException { + if (wireFormat.isCacheEnabled()) { + if (dataIn.readBoolean()) { short index = dataIn.readShort(); DataStructure object = wireFormat.looseUnmarshalNestedObject(dataIn); wireFormat.setInUnmarshallCache(index, object); @@ -452,12 +486,14 @@ abstract public class BaseDataStreamMarshaller implements DataStreamMarshaller { } else { return wireFormat.looseUnmarshalNestedObject(dataIn); } - } - protected void looseMarshalCachedObject(OpenWireFormat wireFormat, DataStructure o, DataOutput dataOut) throws IOException { - if( wireFormat.isCacheEnabled() ) { + } + + protected void looseMarshalCachedObject(OpenWireFormat wireFormat, DataStructure o, DataOutput dataOut) + throws IOException { + if (wireFormat.isCacheEnabled()) { Short index = wireFormat.getMarshallCacheIndex(o); dataOut.writeBoolean(index == null); - if( index == null ) { + if (index == null) { index = wireFormat.addToMarshallCache(o); dataOut.writeShort(index.shortValue()); wireFormat.looseMarshalNestedObject(o, dataOut); @@ -468,23 +504,23 @@ abstract public class BaseDataStreamMarshaller implements DataStreamMarshaller { wireFormat.looseMarshalNestedObject(o, dataOut); } } - - protected Throwable looseUnmarsalThrowable(OpenWireFormat wireFormat, DataInput dataIn) throws IOException { - if( dataIn.readBoolean() ) { - String clazz = looseUnmarshalString(dataIn); + + protected Throwable looseUnmarsalThrowable(OpenWireFormat wireFormat, DataInput dataIn) + throws IOException { + if (dataIn.readBoolean()) { + String clazz = looseUnmarshalString(dataIn); String message = looseUnmarshalString(dataIn); Throwable o = createThrowable(clazz, message); - if( wireFormat.isStackTraceEnabled() ) { - if( STACK_TRACE_ELEMENT_CONSTRUCTOR!=null) { + if (wireFormat.isStackTraceEnabled()) { + if (STACK_TRACE_ELEMENT_CONSTRUCTOR != null) { StackTraceElement ss[] = new StackTraceElement[dataIn.readShort()]; for (int i = 0; i < ss.length; i++) { try { - ss[i] = (StackTraceElement) STACK_TRACE_ELEMENT_CONSTRUCTOR.newInstance(new Object[]{ - looseUnmarshalString(dataIn), - looseUnmarshalString(dataIn), - looseUnmarshalString(dataIn), - new Integer(dataIn.readInt()) - }); + ss[i] = (StackTraceElement)STACK_TRACE_ELEMENT_CONSTRUCTOR + .newInstance(new Object[] {looseUnmarshalString(dataIn), + looseUnmarshalString(dataIn), + looseUnmarshalString(dataIn), + new Integer(dataIn.readInt())}); } catch (IOException e) { throw e; } catch (Throwable e) { @@ -495,27 +531,27 @@ abstract public class BaseDataStreamMarshaller implements DataStreamMarshaller { short size = dataIn.readShort(); for (int i = 0; i < size; i++) { looseUnmarshalString(dataIn); - looseUnmarshalString(dataIn); - looseUnmarshalString(dataIn); + looseUnmarshalString(dataIn); + looseUnmarshalString(dataIn); dataIn.readInt(); } } o.initCause(looseUnmarsalThrowable(wireFormat, dataIn)); - + } return o; } else { return null; } } - - - protected void looseMarshalThrowable(OpenWireFormat wireFormat, Throwable o, DataOutput dataOut) throws IOException { - dataOut.writeBoolean(o!=null); - if( o!=null ) { + + protected void looseMarshalThrowable(OpenWireFormat wireFormat, Throwable o, DataOutput dataOut) + throws IOException { + dataOut.writeBoolean(o != null); + if (o != null) { looseMarshalString(o.getClass().getName(), dataOut); looseMarshalString(o.getMessage(), dataOut); - if( wireFormat.isStackTraceEnabled() ) { + if (wireFormat.isStackTraceEnabled()) { StackTraceElement[] stackTrace = o.getStackTrace(); dataOut.writeShort(stackTrace.length); for (int i = 0; i < stackTrace.length; i++) { @@ -529,33 +565,35 @@ abstract public class BaseDataStreamMarshaller implements DataStreamMarshaller { } } } - + protected String looseUnmarshalString(DataInput dataIn) throws IOException { - if( dataIn.readBoolean() ) { + if (dataIn.readBoolean()) { return dataIn.readUTF(); } else { return null; } } - + protected void looseMarshalString(String value, DataOutput dataOut) throws IOException { - dataOut.writeBoolean(value!=null); - if( value!=null ) { - dataOut.writeUTF(value); + dataOut.writeBoolean(value != null); + if (value != null) { + dataOut.writeUTF(value); } - } - - protected void looseMarshalObjectArray(OpenWireFormat wireFormat, DataStructure[] objects, DataOutput dataOut) throws IOException { - dataOut.writeBoolean(objects!=null); - if( objects!=null ) { + } + + protected void looseMarshalObjectArray(OpenWireFormat wireFormat, DataStructure[] objects, + DataOutput dataOut) throws IOException { + dataOut.writeBoolean(objects != null); + if (objects != null) { dataOut.writeShort(objects.length); - for( int i=0; i < objects.length; i++ ) { - looseMarshalNestedObject(wireFormat,objects[i], dataOut); + for (int i = 0; i < objects.length; i++) { + looseMarshalNestedObject(wireFormat, objects[i], dataOut); } } } - - protected void looseMarshalConstByteArray(OpenWireFormat wireFormat, byte[] data, DataOutput dataOut, int i) throws IOException { + + protected void looseMarshalConstByteArray(OpenWireFormat wireFormat, byte[] data, DataOutput dataOut, + int i) throws IOException { dataOut.write(data, 0, i); } @@ -565,17 +603,18 @@ abstract public class BaseDataStreamMarshaller implements DataStreamMarshaller { return data; } - protected void looseMarshalByteArray(OpenWireFormat wireFormat, byte[] data, DataOutput dataOut) throws IOException { - dataOut.writeBoolean(data!=null); - if( data!=null ){ + protected void looseMarshalByteArray(OpenWireFormat wireFormat, byte[] data, DataOutput dataOut) + throws IOException { + dataOut.writeBoolean(data != null); + if (data != null) { dataOut.writeInt(data.length); dataOut.write(data); } } protected byte[] looseUnmarshalByteArray(DataInput dataIn) throws IOException { - byte rc[]=null; - if( dataIn.readBoolean() ) { + byte rc[] = null; + if (dataIn.readBoolean()) { int size = dataIn.readInt(); rc = new byte[size]; dataIn.readFully(rc); @@ -583,17 +622,18 @@ abstract public class BaseDataStreamMarshaller implements DataStreamMarshaller { return rc; } - protected void looseMarshalByteSequence(OpenWireFormat wireFormat, ByteSequence data, DataOutput dataOut) throws IOException { - dataOut.writeBoolean(data!=null); - if( data!=null ){ + protected void looseMarshalByteSequence(OpenWireFormat wireFormat, ByteSequence data, DataOutput dataOut) + throws IOException { + dataOut.writeBoolean(data != null); + if (data != null) { dataOut.writeInt(data.getLength()); dataOut.write(data.getData(), data.getOffset(), data.getLength()); } } protected ByteSequence looseUnmarshalByteSequence(DataInput dataIn) throws IOException { - ByteSequence rc=null; - if( dataIn.readBoolean() ) { + ByteSequence rc = null; + if (dataIn.readBoolean()) { int size = dataIn.readInt(); byte[] t = new byte[size]; dataIn.readFully(t); diff --git a/activemq-core/src/main/java/org/apache/activemq/openwire/v1/ConnectionInfoMarshaller.java b/activemq-core/src/main/java/org/apache/activemq/openwire/v1/ConnectionInfoMarshaller.java index 38596f9ee7..de07cbf05c 100755 --- a/activemq-core/src/main/java/org/apache/activemq/openwire/v1/ConnectionInfoMarshaller.java +++ b/activemq-core/src/main/java/org/apache/activemq/openwire/v1/ConnectionInfoMarshaller.java @@ -24,29 +24,27 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - - /** * Marshalling code for Open Wire Format for ConnectionInfoMarshaller - * - * - * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * + * + * + * NOTE!: This file is auto generated - do not modify! if you need to make a + * change, please see the modify the groovy scripts in the under src/gram/script + * and then use maven openwire:generate to regenerate this file. + * * @version $Revision$ */ public class ConnectionInfoMarshaller extends BaseCommandMarshaller { /** * Return the type of Data Structure we marshal + * * @return short representation of the type data structure */ public byte getDataStructureType() { return ConnectionInfo.DATA_STRUCTURE_TYPE; } - + /** * @return a new object instance */ @@ -56,16 +54,18 @@ public class ConnectionInfoMarshaller extends BaseCommandMarshaller { /** * Un-marshal an object instance from the data input stream - * + * * @param o the object to un-marshal * @param dataIn the data input stream to build the object from * @throws IOException */ - public void tightUnmarshal(OpenWireFormat wireFormat, Object o, DataInput dataIn, BooleanStream bs) throws IOException { + public void tightUnmarshal(OpenWireFormat wireFormat, Object o, DataInput dataIn, BooleanStream bs) + throws IOException { super.tightUnmarshal(wireFormat, o, dataIn, bs); ConnectionInfo info = (ConnectionInfo)o; - info.setConnectionId((org.apache.activemq.command.ConnectionId) tightUnmarsalCachedObject(wireFormat, dataIn, bs)); + info.setConnectionId((org.apache.activemq.command.ConnectionId)tightUnmarsalCachedObject(wireFormat, + dataIn, bs)); info.setClientId(tightUnmarshalString(dataIn, bs)); info.setPassword(tightUnmarshalString(dataIn, bs)); info.setUserName(tightUnmarshalString(dataIn, bs)); @@ -73,12 +73,12 @@ public class ConnectionInfoMarshaller extends BaseCommandMarshaller { if (bs.readBoolean()) { short size = dataIn.readShort(); org.apache.activemq.command.BrokerId value[] = new org.apache.activemq.command.BrokerId[size]; - for( int i=0; i < size; i++ ) { - value[i] = (org.apache.activemq.command.BrokerId) tightUnmarsalNestedObject(wireFormat,dataIn, bs); + for (int i = 0; i < size; i++) { + value[i] = (org.apache.activemq.command.BrokerId)tightUnmarsalNestedObject(wireFormat, + dataIn, bs); } info.setBrokerPath(value); - } - else { + } else { info.setBrokerPath(null); } info.setBrokerMasterConnector(bs.readBoolean()); @@ -86,7 +86,6 @@ public class ConnectionInfoMarshaller extends BaseCommandMarshaller { } - /** * Write the booleans that this object uses to a BooleanStream */ @@ -108,12 +107,13 @@ public class ConnectionInfoMarshaller extends BaseCommandMarshaller { /** * Write a object instance to data output stream - * + * * @param o the instance to be marshaled * @param dataOut the output stream * @throws IOException thrown if an error occurs */ - public void tightMarshal2(OpenWireFormat wireFormat, Object o, DataOutput dataOut, BooleanStream bs) throws IOException { + public void tightMarshal2(OpenWireFormat wireFormat, Object o, DataOutput dataOut, BooleanStream bs) + throws IOException { super.tightMarshal2(wireFormat, o, dataOut, bs); ConnectionInfo info = (ConnectionInfo)o; @@ -129,7 +129,7 @@ public class ConnectionInfoMarshaller extends BaseCommandMarshaller { /** * Un-marshal an object instance from the data input stream - * + * * @param o the object to un-marshal * @param dataIn the data input stream to build the object from * @throws IOException @@ -138,7 +138,8 @@ public class ConnectionInfoMarshaller extends BaseCommandMarshaller { super.looseUnmarshal(wireFormat, o, dataIn); ConnectionInfo info = (ConnectionInfo)o; - info.setConnectionId((org.apache.activemq.command.ConnectionId) looseUnmarsalCachedObject(wireFormat, dataIn)); + info.setConnectionId((org.apache.activemq.command.ConnectionId)looseUnmarsalCachedObject(wireFormat, + dataIn)); info.setClientId(looseUnmarshalString(dataIn)); info.setPassword(looseUnmarshalString(dataIn)); info.setUserName(looseUnmarshalString(dataIn)); @@ -146,12 +147,11 @@ public class ConnectionInfoMarshaller extends BaseCommandMarshaller { if (dataIn.readBoolean()) { short size = dataIn.readShort(); org.apache.activemq.command.BrokerId value[] = new org.apache.activemq.command.BrokerId[size]; - for( int i=0; i < size; i++ ) { - value[i] = (org.apache.activemq.command.BrokerId) looseUnmarsalNestedObject(wireFormat,dataIn); + for (int i = 0; i < size; i++) { + value[i] = (org.apache.activemq.command.BrokerId)looseUnmarsalNestedObject(wireFormat, dataIn); } info.setBrokerPath(value); - } - else { + } else { info.setBrokerPath(null); } info.setBrokerMasterConnector(dataIn.readBoolean()); @@ -159,7 +159,6 @@ public class ConnectionInfoMarshaller extends BaseCommandMarshaller { } - /** * Write the booleans that this object uses to a BooleanStream */ diff --git a/activemq-core/src/main/java/org/apache/activemq/openwire/v1/ConsumerIdMarshaller.java b/activemq-core/src/main/java/org/apache/activemq/openwire/v1/ConsumerIdMarshaller.java index 7899fef781..793ef86df7 100755 --- a/activemq-core/src/main/java/org/apache/activemq/openwire/v1/ConsumerIdMarshaller.java +++ b/activemq-core/src/main/java/org/apache/activemq/openwire/v1/ConsumerIdMarshaller.java @@ -24,29 +24,27 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - - /** * Marshalling code for Open Wire Format for ConsumerIdMarshaller - * - * - * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * + * + * + * NOTE!: This file is auto generated - do not modify! if you need to make a + * change, please see the modify the groovy scripts in the under src/gram/script + * and then use maven openwire:generate to regenerate this file. + * * @version $Revision$ */ public class ConsumerIdMarshaller extends BaseDataStreamMarshaller { /** * Return the type of Data Structure we marshal + * * @return short representation of the type data structure */ public byte getDataStructureType() { return ConsumerId.DATA_STRUCTURE_TYPE; } - + /** * @return a new object instance */ @@ -56,12 +54,13 @@ public class ConsumerIdMarshaller extends BaseDataStreamMarshaller { /** * Un-marshal an object instance from the data input stream - * + * * @param o the object to un-marshal * @param dataIn the data input stream to build the object from * @throws IOException */ - public void tightUnmarshal(OpenWireFormat wireFormat, Object o, DataInput dataIn, BooleanStream bs) throws IOException { + public void tightUnmarshal(OpenWireFormat wireFormat, Object o, DataInput dataIn, BooleanStream bs) + throws IOException { super.tightUnmarshal(wireFormat, o, dataIn, bs); ConsumerId info = (ConsumerId)o; @@ -71,7 +70,6 @@ public class ConsumerIdMarshaller extends BaseDataStreamMarshaller { } - /** * Write the booleans that this object uses to a BooleanStream */ @@ -81,20 +79,21 @@ public class ConsumerIdMarshaller extends BaseDataStreamMarshaller { int rc = super.tightMarshal1(wireFormat, o, bs); rc += tightMarshalString1(info.getConnectionId(), bs); - rc+=tightMarshalLong1(wireFormat, info.getSessionId(), bs); - rc+=tightMarshalLong1(wireFormat, info.getValue(), bs); + rc += tightMarshalLong1(wireFormat, info.getSessionId(), bs); + rc += tightMarshalLong1(wireFormat, info.getValue(), bs); return rc + 0; } /** * Write a object instance to data output stream - * + * * @param o the instance to be marshaled * @param dataOut the output stream * @throws IOException thrown if an error occurs */ - public void tightMarshal2(OpenWireFormat wireFormat, Object o, DataOutput dataOut, BooleanStream bs) throws IOException { + public void tightMarshal2(OpenWireFormat wireFormat, Object o, DataOutput dataOut, BooleanStream bs) + throws IOException { super.tightMarshal2(wireFormat, o, dataOut, bs); ConsumerId info = (ConsumerId)o; @@ -106,7 +105,7 @@ public class ConsumerIdMarshaller extends BaseDataStreamMarshaller { /** * Un-marshal an object instance from the data input stream - * + * * @param o the object to un-marshal * @param dataIn the data input stream to build the object from * @throws IOException @@ -121,7 +120,6 @@ public class ConsumerIdMarshaller extends BaseDataStreamMarshaller { } - /** * Write the booleans that this object uses to a BooleanStream */ diff --git a/activemq-core/src/main/java/org/apache/activemq/openwire/v1/ConsumerInfoMarshaller.java b/activemq-core/src/main/java/org/apache/activemq/openwire/v1/ConsumerInfoMarshaller.java index a5cddc756b..41d71c426a 100755 --- a/activemq-core/src/main/java/org/apache/activemq/openwire/v1/ConsumerInfoMarshaller.java +++ b/activemq-core/src/main/java/org/apache/activemq/openwire/v1/ConsumerInfoMarshaller.java @@ -24,29 +24,27 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - - /** * Marshalling code for Open Wire Format for ConsumerInfoMarshaller - * - * - * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * + * + * + * NOTE!: This file is auto generated - do not modify! if you need to make a + * change, please see the modify the groovy scripts in the under src/gram/script + * and then use maven openwire:generate to regenerate this file. + * * @version $Revision$ */ public class ConsumerInfoMarshaller extends BaseCommandMarshaller { /** * Return the type of Data Structure we marshal + * * @return short representation of the type data structure */ public byte getDataStructureType() { return ConsumerInfo.DATA_STRUCTURE_TYPE; } - + /** * @return a new object instance */ @@ -56,18 +54,24 @@ public class ConsumerInfoMarshaller extends BaseCommandMarshaller { /** * Un-marshal an object instance from the data input stream - * + * * @param o the object to un-marshal * @param dataIn the data input stream to build the object from * @throws IOException */ - public void tightUnmarshal(OpenWireFormat wireFormat, Object o, DataInput dataIn, BooleanStream bs) throws IOException { + public void tightUnmarshal(OpenWireFormat wireFormat, Object o, DataInput dataIn, BooleanStream bs) + throws IOException { super.tightUnmarshal(wireFormat, o, dataIn, bs); ConsumerInfo info = (ConsumerInfo)o; - info.setConsumerId((org.apache.activemq.command.ConsumerId) tightUnmarsalCachedObject(wireFormat, dataIn, bs)); + info.setConsumerId((org.apache.activemq.command.ConsumerId)tightUnmarsalCachedObject(wireFormat, + dataIn, bs)); info.setBrowser(bs.readBoolean()); - info.setDestination((org.apache.activemq.command.ActiveMQDestination) tightUnmarsalCachedObject(wireFormat, dataIn, bs)); + info + .setDestination((org.apache.activemq.command.ActiveMQDestination)tightUnmarsalCachedObject( + wireFormat, + dataIn, + bs)); info.setPrefetchSize(dataIn.readInt()); info.setMaximumPendingMessageLimit(dataIn.readInt()); info.setDispatchAsync(bs.readBoolean()); @@ -81,22 +85,25 @@ public class ConsumerInfoMarshaller extends BaseCommandMarshaller { if (bs.readBoolean()) { short size = dataIn.readShort(); org.apache.activemq.command.BrokerId value[] = new org.apache.activemq.command.BrokerId[size]; - for( int i=0; i < size; i++ ) { - value[i] = (org.apache.activemq.command.BrokerId) tightUnmarsalNestedObject(wireFormat,dataIn, bs); + for (int i = 0; i < size; i++) { + value[i] = (org.apache.activemq.command.BrokerId)tightUnmarsalNestedObject(wireFormat, + dataIn, bs); } info.setBrokerPath(value); - } - else { + } else { info.setBrokerPath(null); } - info.setAdditionalPredicate((org.apache.activemq.filter.BooleanExpression) tightUnmarsalNestedObject(wireFormat, dataIn, bs)); + info + .setAdditionalPredicate((org.apache.activemq.filter.BooleanExpression)tightUnmarsalNestedObject( + wireFormat, + dataIn, + bs)); info.setNetworkSubscription(bs.readBoolean()); info.setOptimizedAcknowledge(bs.readBoolean()); info.setNoRangeAcks(bs.readBoolean()); } - /** * Write the booleans that this object uses to a BooleanStream */ @@ -125,12 +132,13 @@ public class ConsumerInfoMarshaller extends BaseCommandMarshaller { /** * Write a object instance to data output stream - * + * * @param o the instance to be marshaled * @param dataOut the output stream * @throws IOException thrown if an error occurs */ - public void tightMarshal2(OpenWireFormat wireFormat, Object o, DataOutput dataOut, BooleanStream bs) throws IOException { + public void tightMarshal2(OpenWireFormat wireFormat, Object o, DataOutput dataOut, BooleanStream bs) + throws IOException { super.tightMarshal2(wireFormat, o, dataOut, bs); ConsumerInfo info = (ConsumerInfo)o; @@ -156,7 +164,7 @@ public class ConsumerInfoMarshaller extends BaseCommandMarshaller { /** * Un-marshal an object instance from the data input stream - * + * * @param o the object to un-marshal * @param dataIn the data input stream to build the object from * @throws IOException @@ -165,9 +173,13 @@ public class ConsumerInfoMarshaller extends BaseCommandMarshaller { super.looseUnmarshal(wireFormat, o, dataIn); ConsumerInfo info = (ConsumerInfo)o; - info.setConsumerId((org.apache.activemq.command.ConsumerId) looseUnmarsalCachedObject(wireFormat, dataIn)); + info.setConsumerId((org.apache.activemq.command.ConsumerId)looseUnmarsalCachedObject(wireFormat, + dataIn)); info.setBrowser(dataIn.readBoolean()); - info.setDestination((org.apache.activemq.command.ActiveMQDestination) looseUnmarsalCachedObject(wireFormat, dataIn)); + info + .setDestination((org.apache.activemq.command.ActiveMQDestination)looseUnmarsalCachedObject( + wireFormat, + dataIn)); info.setPrefetchSize(dataIn.readInt()); info.setMaximumPendingMessageLimit(dataIn.readInt()); info.setDispatchAsync(dataIn.readBoolean()); @@ -181,22 +193,23 @@ public class ConsumerInfoMarshaller extends BaseCommandMarshaller { if (dataIn.readBoolean()) { short size = dataIn.readShort(); org.apache.activemq.command.BrokerId value[] = new org.apache.activemq.command.BrokerId[size]; - for( int i=0; i < size; i++ ) { - value[i] = (org.apache.activemq.command.BrokerId) looseUnmarsalNestedObject(wireFormat,dataIn); + for (int i = 0; i < size; i++) { + value[i] = (org.apache.activemq.command.BrokerId)looseUnmarsalNestedObject(wireFormat, dataIn); } info.setBrokerPath(value); - } - else { + } else { info.setBrokerPath(null); } - info.setAdditionalPredicate((org.apache.activemq.filter.BooleanExpression) looseUnmarsalNestedObject(wireFormat, dataIn)); + info + .setAdditionalPredicate((org.apache.activemq.filter.BooleanExpression)looseUnmarsalNestedObject( + wireFormat, + dataIn)); info.setNetworkSubscription(dataIn.readBoolean()); info.setOptimizedAcknowledge(dataIn.readBoolean()); info.setNoRangeAcks(dataIn.readBoolean()); } - /** * Write the booleans that this object uses to a BooleanStream */ diff --git a/activemq-core/src/main/java/org/apache/activemq/openwire/v1/DataArrayResponseMarshaller.java b/activemq-core/src/main/java/org/apache/activemq/openwire/v1/DataArrayResponseMarshaller.java index ecfd27b91a..f0700b3635 100755 --- a/activemq-core/src/main/java/org/apache/activemq/openwire/v1/DataArrayResponseMarshaller.java +++ b/activemq-core/src/main/java/org/apache/activemq/openwire/v1/DataArrayResponseMarshaller.java @@ -24,29 +24,27 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - - /** * Marshalling code for Open Wire Format for DataArrayResponseMarshaller - * - * - * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * + * + * + * NOTE!: This file is auto generated - do not modify! if you need to make a + * change, please see the modify the groovy scripts in the under src/gram/script + * and then use maven openwire:generate to regenerate this file. + * * @version $Revision$ */ public class DataArrayResponseMarshaller extends ResponseMarshaller { /** * Return the type of Data Structure we marshal + * * @return short representation of the type data structure */ public byte getDataStructureType() { return DataArrayResponse.DATA_STRUCTURE_TYPE; } - + /** * @return a new object instance */ @@ -56,12 +54,13 @@ public class DataArrayResponseMarshaller extends ResponseMarshaller { /** * Un-marshal an object instance from the data input stream - * + * * @param o the object to un-marshal * @param dataIn the data input stream to build the object from * @throws IOException */ - public void tightUnmarshal(OpenWireFormat wireFormat, Object o, DataInput dataIn, BooleanStream bs) throws IOException { + public void tightUnmarshal(OpenWireFormat wireFormat, Object o, DataInput dataIn, BooleanStream bs) + throws IOException { super.tightUnmarshal(wireFormat, o, dataIn, bs); DataArrayResponse info = (DataArrayResponse)o; @@ -69,18 +68,17 @@ public class DataArrayResponseMarshaller extends ResponseMarshaller { if (bs.readBoolean()) { short size = dataIn.readShort(); org.apache.activemq.command.DataStructure value[] = new org.apache.activemq.command.DataStructure[size]; - for( int i=0; i < size; i++ ) { - value[i] = (org.apache.activemq.command.DataStructure) tightUnmarsalNestedObject(wireFormat,dataIn, bs); + for (int i = 0; i < size; i++) { + value[i] = (org.apache.activemq.command.DataStructure)tightUnmarsalNestedObject(wireFormat, + dataIn, bs); } info.setData(value); - } - else { + } else { info.setData(null); } } - /** * Write the booleans that this object uses to a BooleanStream */ @@ -96,12 +94,13 @@ public class DataArrayResponseMarshaller extends ResponseMarshaller { /** * Write a object instance to data output stream - * + * * @param o the instance to be marshaled * @param dataOut the output stream * @throws IOException thrown if an error occurs */ - public void tightMarshal2(OpenWireFormat wireFormat, Object o, DataOutput dataOut, BooleanStream bs) throws IOException { + public void tightMarshal2(OpenWireFormat wireFormat, Object o, DataOutput dataOut, BooleanStream bs) + throws IOException { super.tightMarshal2(wireFormat, o, dataOut, bs); DataArrayResponse info = (DataArrayResponse)o; @@ -111,7 +110,7 @@ public class DataArrayResponseMarshaller extends ResponseMarshaller { /** * Un-marshal an object instance from the data input stream - * + * * @param o the object to un-marshal * @param dataIn the data input stream to build the object from * @throws IOException @@ -124,18 +123,17 @@ public class DataArrayResponseMarshaller extends ResponseMarshaller { if (dataIn.readBoolean()) { short size = dataIn.readShort(); org.apache.activemq.command.DataStructure value[] = new org.apache.activemq.command.DataStructure[size]; - for( int i=0; i < size; i++ ) { - value[i] = (org.apache.activemq.command.DataStructure) looseUnmarsalNestedObject(wireFormat,dataIn); + for (int i = 0; i < size; i++) { + value[i] = (org.apache.activemq.command.DataStructure)looseUnmarsalNestedObject(wireFormat, + dataIn); } info.setData(value); - } - else { + } else { info.setData(null); } } - /** * Write the booleans that this object uses to a BooleanStream */ diff --git a/activemq-core/src/main/java/org/apache/activemq/openwire/v1/DestinationInfoMarshaller.java b/activemq-core/src/main/java/org/apache/activemq/openwire/v1/DestinationInfoMarshaller.java index cd4236c814..c341332c0e 100755 --- a/activemq-core/src/main/java/org/apache/activemq/openwire/v1/DestinationInfoMarshaller.java +++ b/activemq-core/src/main/java/org/apache/activemq/openwire/v1/DestinationInfoMarshaller.java @@ -24,29 +24,27 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - - /** * Marshalling code for Open Wire Format for DestinationInfoMarshaller - * - * - * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * + * + * + * NOTE!: This file is auto generated - do not modify! if you need to make a + * change, please see the modify the groovy scripts in the under src/gram/script + * and then use maven openwire:generate to regenerate this file. + * * @version $Revision$ */ public class DestinationInfoMarshaller extends BaseCommandMarshaller { /** * Return the type of Data Structure we marshal + * * @return short representation of the type data structure */ public byte getDataStructureType() { return DestinationInfo.DATA_STRUCTURE_TYPE; } - + /** * @return a new object instance */ @@ -56,35 +54,40 @@ public class DestinationInfoMarshaller extends BaseCommandMarshaller { /** * Un-marshal an object instance from the data input stream - * + * * @param o the object to un-marshal * @param dataIn the data input stream to build the object from * @throws IOException */ - public void tightUnmarshal(OpenWireFormat wireFormat, Object o, DataInput dataIn, BooleanStream bs) throws IOException { + public void tightUnmarshal(OpenWireFormat wireFormat, Object o, DataInput dataIn, BooleanStream bs) + throws IOException { super.tightUnmarshal(wireFormat, o, dataIn, bs); DestinationInfo info = (DestinationInfo)o; - info.setConnectionId((org.apache.activemq.command.ConnectionId) tightUnmarsalCachedObject(wireFormat, dataIn, bs)); - info.setDestination((org.apache.activemq.command.ActiveMQDestination) tightUnmarsalCachedObject(wireFormat, dataIn, bs)); + info.setConnectionId((org.apache.activemq.command.ConnectionId)tightUnmarsalCachedObject(wireFormat, + dataIn, bs)); + info + .setDestination((org.apache.activemq.command.ActiveMQDestination)tightUnmarsalCachedObject( + wireFormat, + dataIn, + bs)); info.setOperationType(dataIn.readByte()); info.setTimeout(tightUnmarshalLong(wireFormat, dataIn, bs)); if (bs.readBoolean()) { short size = dataIn.readShort(); org.apache.activemq.command.BrokerId value[] = new org.apache.activemq.command.BrokerId[size]; - for( int i=0; i < size; i++ ) { - value[i] = (org.apache.activemq.command.BrokerId) tightUnmarsalNestedObject(wireFormat,dataIn, bs); + for (int i = 0; i < size; i++) { + value[i] = (org.apache.activemq.command.BrokerId)tightUnmarsalNestedObject(wireFormat, + dataIn, bs); } info.setBrokerPath(value); - } - else { + } else { info.setBrokerPath(null); } } - /** * Write the booleans that this object uses to a BooleanStream */ @@ -95,7 +98,7 @@ public class DestinationInfoMarshaller extends BaseCommandMarshaller { int rc = super.tightMarshal1(wireFormat, o, bs); rc += tightMarshalCachedObject1(wireFormat, (DataStructure)info.getConnectionId(), bs); rc += tightMarshalCachedObject1(wireFormat, (DataStructure)info.getDestination(), bs); - rc+=tightMarshalLong1(wireFormat, info.getTimeout(), bs); + rc += tightMarshalLong1(wireFormat, info.getTimeout(), bs); rc += tightMarshalObjectArray1(wireFormat, info.getBrokerPath(), bs); return rc + 1; @@ -103,12 +106,13 @@ public class DestinationInfoMarshaller extends BaseCommandMarshaller { /** * Write a object instance to data output stream - * + * * @param o the instance to be marshaled * @param dataOut the output stream * @throws IOException thrown if an error occurs */ - public void tightMarshal2(OpenWireFormat wireFormat, Object o, DataOutput dataOut, BooleanStream bs) throws IOException { + public void tightMarshal2(OpenWireFormat wireFormat, Object o, DataOutput dataOut, BooleanStream bs) + throws IOException { super.tightMarshal2(wireFormat, o, dataOut, bs); DestinationInfo info = (DestinationInfo)o; @@ -122,7 +126,7 @@ public class DestinationInfoMarshaller extends BaseCommandMarshaller { /** * Un-marshal an object instance from the data input stream - * + * * @param o the object to un-marshal * @param dataIn the data input stream to build the object from * @throws IOException @@ -131,26 +135,28 @@ public class DestinationInfoMarshaller extends BaseCommandMarshaller { super.looseUnmarshal(wireFormat, o, dataIn); DestinationInfo info = (DestinationInfo)o; - info.setConnectionId((org.apache.activemq.command.ConnectionId) looseUnmarsalCachedObject(wireFormat, dataIn)); - info.setDestination((org.apache.activemq.command.ActiveMQDestination) looseUnmarsalCachedObject(wireFormat, dataIn)); + info.setConnectionId((org.apache.activemq.command.ConnectionId)looseUnmarsalCachedObject(wireFormat, + dataIn)); + info + .setDestination((org.apache.activemq.command.ActiveMQDestination)looseUnmarsalCachedObject( + wireFormat, + dataIn)); info.setOperationType(dataIn.readByte()); info.setTimeout(looseUnmarshalLong(wireFormat, dataIn)); if (dataIn.readBoolean()) { short size = dataIn.readShort(); org.apache.activemq.command.BrokerId value[] = new org.apache.activemq.command.BrokerId[size]; - for( int i=0; i < size; i++ ) { - value[i] = (org.apache.activemq.command.BrokerId) looseUnmarsalNestedObject(wireFormat,dataIn); + for (int i = 0; i < size; i++) { + value[i] = (org.apache.activemq.command.BrokerId)looseUnmarsalNestedObject(wireFormat, dataIn); } info.setBrokerPath(value); - } - else { + } else { info.setBrokerPath(null); } } - /** * Write the booleans that this object uses to a BooleanStream */ diff --git a/activemq-core/src/main/java/org/apache/activemq/openwire/v1/MarshallerFactory.java b/activemq-core/src/main/java/org/apache/activemq/openwire/v1/MarshallerFactory.java index 235e5b75ab..47ef76c6ef 100755 --- a/activemq-core/src/main/java/org/apache/activemq/openwire/v1/MarshallerFactory.java +++ b/activemq-core/src/main/java/org/apache/activemq/openwire/v1/MarshallerFactory.java @@ -21,14 +21,11 @@ import org.apache.activemq.openwire.DataStreamMarshaller; import org.apache.activemq.openwire.OpenWireFormat; /** - * MarshallerFactory for Open Wire Format. - * - * - * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * + * MarshallerFactory for Open Wire Format. NOTE!: This file is auto generated - + * do not modify! if you need to make a change, please see the modify the groovy + * scripts in the under src/gram/script and then use maven openwire:generate to + * regenerate this file. + * * @version $Revision$ */ public class MarshallerFactory { @@ -93,12 +90,12 @@ public class MarshallerFactory { add(new RemoveInfoMarshaller()); add(new ExceptionResponseMarshaller()); - } + } - static private void add(DataStreamMarshaller dsm) { + static private void add(DataStreamMarshaller dsm) { marshaller[dsm.getDataStructureType()] = dsm; } - + static public DataStreamMarshaller[] createMarshallerMap(OpenWireFormat wireFormat) { return marshaller; } diff --git a/activemq-core/src/main/java/org/apache/activemq/openwire/v1/MessageIdMarshaller.java b/activemq-core/src/main/java/org/apache/activemq/openwire/v1/MessageIdMarshaller.java index d171f1e53b..8e40c71c63 100755 --- a/activemq-core/src/main/java/org/apache/activemq/openwire/v1/MessageIdMarshaller.java +++ b/activemq-core/src/main/java/org/apache/activemq/openwire/v1/MessageIdMarshaller.java @@ -24,29 +24,27 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - - /** * Marshalling code for Open Wire Format for MessageIdMarshaller - * - * - * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * + * + * + * NOTE!: This file is auto generated - do not modify! if you need to make a + * change, please see the modify the groovy scripts in the under src/gram/script + * and then use maven openwire:generate to regenerate this file. + * * @version $Revision$ */ public class MessageIdMarshaller extends BaseDataStreamMarshaller { /** * Return the type of Data Structure we marshal + * * @return short representation of the type data structure */ public byte getDataStructureType() { return MessageId.DATA_STRUCTURE_TYPE; } - + /** * @return a new object instance */ @@ -56,22 +54,23 @@ public class MessageIdMarshaller extends BaseDataStreamMarshaller { /** * Un-marshal an object instance from the data input stream - * + * * @param o the object to un-marshal * @param dataIn the data input stream to build the object from * @throws IOException */ - public void tightUnmarshal(OpenWireFormat wireFormat, Object o, DataInput dataIn, BooleanStream bs) throws IOException { + public void tightUnmarshal(OpenWireFormat wireFormat, Object o, DataInput dataIn, BooleanStream bs) + throws IOException { super.tightUnmarshal(wireFormat, o, dataIn, bs); MessageId info = (MessageId)o; - info.setProducerId((org.apache.activemq.command.ProducerId) tightUnmarsalCachedObject(wireFormat, dataIn, bs)); + info.setProducerId((org.apache.activemq.command.ProducerId)tightUnmarsalCachedObject(wireFormat, + dataIn, bs)); info.setProducerSequenceId(tightUnmarshalLong(wireFormat, dataIn, bs)); info.setBrokerSequenceId(tightUnmarshalLong(wireFormat, dataIn, bs)); } - /** * Write the booleans that this object uses to a BooleanStream */ @@ -81,20 +80,21 @@ public class MessageIdMarshaller extends BaseDataStreamMarshaller { int rc = super.tightMarshal1(wireFormat, o, bs); rc += tightMarshalCachedObject1(wireFormat, (DataStructure)info.getProducerId(), bs); - rc+=tightMarshalLong1(wireFormat, info.getProducerSequenceId(), bs); - rc+=tightMarshalLong1(wireFormat, info.getBrokerSequenceId(), bs); + rc += tightMarshalLong1(wireFormat, info.getProducerSequenceId(), bs); + rc += tightMarshalLong1(wireFormat, info.getBrokerSequenceId(), bs); return rc + 0; } /** * Write a object instance to data output stream - * + * * @param o the instance to be marshaled * @param dataOut the output stream * @throws IOException thrown if an error occurs */ - public void tightMarshal2(OpenWireFormat wireFormat, Object o, DataOutput dataOut, BooleanStream bs) throws IOException { + public void tightMarshal2(OpenWireFormat wireFormat, Object o, DataOutput dataOut, BooleanStream bs) + throws IOException { super.tightMarshal2(wireFormat, o, dataOut, bs); MessageId info = (MessageId)o; @@ -106,7 +106,7 @@ public class MessageIdMarshaller extends BaseDataStreamMarshaller { /** * Un-marshal an object instance from the data input stream - * + * * @param o the object to un-marshal * @param dataIn the data input stream to build the object from * @throws IOException @@ -115,13 +115,13 @@ public class MessageIdMarshaller extends BaseDataStreamMarshaller { super.looseUnmarshal(wireFormat, o, dataIn); MessageId info = (MessageId)o; - info.setProducerId((org.apache.activemq.command.ProducerId) looseUnmarsalCachedObject(wireFormat, dataIn)); + info.setProducerId((org.apache.activemq.command.ProducerId)looseUnmarsalCachedObject(wireFormat, + dataIn)); info.setProducerSequenceId(looseUnmarshalLong(wireFormat, dataIn)); info.setBrokerSequenceId(looseUnmarshalLong(wireFormat, dataIn)); } - /** * Write the booleans that this object uses to a BooleanStream */ diff --git a/activemq-core/src/main/java/org/apache/activemq/openwire/v1/ProducerIdMarshaller.java b/activemq-core/src/main/java/org/apache/activemq/openwire/v1/ProducerIdMarshaller.java index 76e34fa9b4..8cc106ef13 100755 --- a/activemq-core/src/main/java/org/apache/activemq/openwire/v1/ProducerIdMarshaller.java +++ b/activemq-core/src/main/java/org/apache/activemq/openwire/v1/ProducerIdMarshaller.java @@ -24,29 +24,27 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - - /** * Marshalling code for Open Wire Format for ProducerIdMarshaller - * - * - * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * + * + * + * NOTE!: This file is auto generated - do not modify! if you need to make a + * change, please see the modify the groovy scripts in the under src/gram/script + * and then use maven openwire:generate to regenerate this file. + * * @version $Revision$ */ public class ProducerIdMarshaller extends BaseDataStreamMarshaller { /** * Return the type of Data Structure we marshal + * * @return short representation of the type data structure */ public byte getDataStructureType() { return ProducerId.DATA_STRUCTURE_TYPE; } - + /** * @return a new object instance */ @@ -56,12 +54,13 @@ public class ProducerIdMarshaller extends BaseDataStreamMarshaller { /** * Un-marshal an object instance from the data input stream - * + * * @param o the object to un-marshal * @param dataIn the data input stream to build the object from * @throws IOException */ - public void tightUnmarshal(OpenWireFormat wireFormat, Object o, DataInput dataIn, BooleanStream bs) throws IOException { + public void tightUnmarshal(OpenWireFormat wireFormat, Object o, DataInput dataIn, BooleanStream bs) + throws IOException { super.tightUnmarshal(wireFormat, o, dataIn, bs); ProducerId info = (ProducerId)o; @@ -71,7 +70,6 @@ public class ProducerIdMarshaller extends BaseDataStreamMarshaller { } - /** * Write the booleans that this object uses to a BooleanStream */ @@ -81,20 +79,21 @@ public class ProducerIdMarshaller extends BaseDataStreamMarshaller { int rc = super.tightMarshal1(wireFormat, o, bs); rc += tightMarshalString1(info.getConnectionId(), bs); - rc+=tightMarshalLong1(wireFormat, info.getValue(), bs); - rc+=tightMarshalLong1(wireFormat, info.getSessionId(), bs); + rc += tightMarshalLong1(wireFormat, info.getValue(), bs); + rc += tightMarshalLong1(wireFormat, info.getSessionId(), bs); return rc + 0; } /** * Write a object instance to data output stream - * + * * @param o the instance to be marshaled * @param dataOut the output stream * @throws IOException thrown if an error occurs */ - public void tightMarshal2(OpenWireFormat wireFormat, Object o, DataOutput dataOut, BooleanStream bs) throws IOException { + public void tightMarshal2(OpenWireFormat wireFormat, Object o, DataOutput dataOut, BooleanStream bs) + throws IOException { super.tightMarshal2(wireFormat, o, dataOut, bs); ProducerId info = (ProducerId)o; @@ -106,7 +105,7 @@ public class ProducerIdMarshaller extends BaseDataStreamMarshaller { /** * Un-marshal an object instance from the data input stream - * + * * @param o the object to un-marshal * @param dataIn the data input stream to build the object from * @throws IOException @@ -121,7 +120,6 @@ public class ProducerIdMarshaller extends BaseDataStreamMarshaller { } - /** * Write the booleans that this object uses to a BooleanStream */ diff --git a/activemq-core/src/main/java/org/apache/activemq/openwire/v1/SessionIdMarshaller.java b/activemq-core/src/main/java/org/apache/activemq/openwire/v1/SessionIdMarshaller.java index 2bf84cdddc..8627decb84 100755 --- a/activemq-core/src/main/java/org/apache/activemq/openwire/v1/SessionIdMarshaller.java +++ b/activemq-core/src/main/java/org/apache/activemq/openwire/v1/SessionIdMarshaller.java @@ -24,29 +24,27 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - - /** * Marshalling code for Open Wire Format for SessionIdMarshaller - * - * - * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * + * + * + * NOTE!: This file is auto generated - do not modify! if you need to make a + * change, please see the modify the groovy scripts in the under src/gram/script + * and then use maven openwire:generate to regenerate this file. + * * @version $Revision$ */ public class SessionIdMarshaller extends BaseDataStreamMarshaller { /** * Return the type of Data Structure we marshal + * * @return short representation of the type data structure */ public byte getDataStructureType() { return SessionId.DATA_STRUCTURE_TYPE; } - + /** * @return a new object instance */ @@ -56,12 +54,13 @@ public class SessionIdMarshaller extends BaseDataStreamMarshaller { /** * Un-marshal an object instance from the data input stream - * + * * @param o the object to un-marshal * @param dataIn the data input stream to build the object from * @throws IOException */ - public void tightUnmarshal(OpenWireFormat wireFormat, Object o, DataInput dataIn, BooleanStream bs) throws IOException { + public void tightUnmarshal(OpenWireFormat wireFormat, Object o, DataInput dataIn, BooleanStream bs) + throws IOException { super.tightUnmarshal(wireFormat, o, dataIn, bs); SessionId info = (SessionId)o; @@ -70,7 +69,6 @@ public class SessionIdMarshaller extends BaseDataStreamMarshaller { } - /** * Write the booleans that this object uses to a BooleanStream */ @@ -80,19 +78,20 @@ public class SessionIdMarshaller extends BaseDataStreamMarshaller { int rc = super.tightMarshal1(wireFormat, o, bs); rc += tightMarshalString1(info.getConnectionId(), bs); - rc+=tightMarshalLong1(wireFormat, info.getValue(), bs); + rc += tightMarshalLong1(wireFormat, info.getValue(), bs); return rc + 0; } /** * Write a object instance to data output stream - * + * * @param o the instance to be marshaled * @param dataOut the output stream * @throws IOException thrown if an error occurs */ - public void tightMarshal2(OpenWireFormat wireFormat, Object o, DataOutput dataOut, BooleanStream bs) throws IOException { + public void tightMarshal2(OpenWireFormat wireFormat, Object o, DataOutput dataOut, BooleanStream bs) + throws IOException { super.tightMarshal2(wireFormat, o, dataOut, bs); SessionId info = (SessionId)o; @@ -103,7 +102,7 @@ public class SessionIdMarshaller extends BaseDataStreamMarshaller { /** * Un-marshal an object instance from the data input stream - * + * * @param o the object to un-marshal * @param dataIn the data input stream to build the object from * @throws IOException @@ -117,7 +116,6 @@ public class SessionIdMarshaller extends BaseDataStreamMarshaller { } - /** * Write the booleans that this object uses to a BooleanStream */ diff --git a/activemq-core/src/main/java/org/apache/activemq/openwire/v2/BaseDataStreamMarshaller.java b/activemq-core/src/main/java/org/apache/activemq/openwire/v2/BaseDataStreamMarshaller.java index 217c49e539..573e06c16a 100755 --- a/activemq-core/src/main/java/org/apache/activemq/openwire/v2/BaseDataStreamMarshaller.java +++ b/activemq-core/src/main/java/org/apache/activemq/openwire/v2/BaseDataStreamMarshaller.java @@ -31,38 +31,43 @@ import org.apache.activemq.util.ClassLoading; abstract public class BaseDataStreamMarshaller implements DataStreamMarshaller { static final public Constructor STACK_TRACE_ELEMENT_CONSTRUCTOR; - + static { - Constructor constructor=null; + Constructor constructor = null; try { - constructor = StackTraceElement.class.getConstructor(new Class[]{String.class, String.class, String.class, int.class}); - } catch (Throwable e) { + constructor = StackTraceElement.class.getConstructor(new Class[] {String.class, String.class, + String.class, int.class}); + } catch (Throwable e) { } STACK_TRACE_ELEMENT_CONSTRUCTOR = constructor; } - abstract public byte getDataStructureType(); + abstract public DataStructure createObject(); - + public int tightMarshal1(OpenWireFormat wireFormat, Object o, BooleanStream bs) throws IOException { return 0; } - public void tightMarshal2(OpenWireFormat wireFormat, Object o, DataOutput dataOut, BooleanStream bs) throws IOException { + + public void tightMarshal2(OpenWireFormat wireFormat, Object o, DataOutput dataOut, BooleanStream bs) + throws IOException { } - public void tightUnmarshal(OpenWireFormat wireFormat, Object o, DataInput dataIn, BooleanStream bs) throws IOException { + + public void tightUnmarshal(OpenWireFormat wireFormat, Object o, DataInput dataIn, BooleanStream bs) + throws IOException { } - + public int tightMarshalLong1(OpenWireFormat wireFormat, long o, BooleanStream bs) throws IOException { - if( o == 0 ) { + if (o == 0) { bs.writeBoolean(false); bs.writeBoolean(false); return 0; - } else if ( (o & 0xFFFFFFFFFFFF0000l ) == 0 ) { + } else if ((o & 0xFFFFFFFFFFFF0000l) == 0) { bs.writeBoolean(false); - bs.writeBoolean(true); + bs.writeBoolean(true); return 2; - } else if ( (o & 0xFFFFFFFF00000000l ) == 0) { + } else if ((o & 0xFFFFFFFF00000000l) == 0) { bs.writeBoolean(true); bs.writeBoolean(false); return 4; @@ -72,61 +77,70 @@ abstract public class BaseDataStreamMarshaller implements DataStreamMarshaller { return 8; } } - public void tightMarshalLong2(OpenWireFormat wireFormat, long o, DataOutput dataOut, BooleanStream bs) throws IOException { - if( bs.readBoolean() ) { - if( bs.readBoolean() ) { + + public void tightMarshalLong2(OpenWireFormat wireFormat, long o, DataOutput dataOut, BooleanStream bs) + throws IOException { + if (bs.readBoolean()) { + if (bs.readBoolean()) { dataOut.writeLong(o); } else { - dataOut.writeInt((int) o); + dataOut.writeInt((int)o); } } else { - if( bs.readBoolean() ) { - dataOut.writeShort((int) o); + if (bs.readBoolean()) { + dataOut.writeShort((int)o); } } } - public long tightUnmarshalLong(OpenWireFormat wireFormat, DataInput dataIn, BooleanStream bs) throws IOException { - if( bs.readBoolean() ) { - if( bs.readBoolean() ) { + + public long tightUnmarshalLong(OpenWireFormat wireFormat, DataInput dataIn, BooleanStream bs) + throws IOException { + if (bs.readBoolean()) { + if (bs.readBoolean()) { return dataIn.readLong(); } else { return toLong(dataIn.readInt()); } } else { - if( bs.readBoolean() ) { + if (bs.readBoolean()) { return toLong(dataIn.readShort()); } else { return 0; } } } - + protected long toLong(short value) { // lets handle negative values long answer = value; return answer & 0xffffL; } - + protected long toLong(int value) { // lets handle negative values long answer = value; return answer & 0xffffffffL; } - - protected DataStructure tightUnmarsalNestedObject(OpenWireFormat wireFormat, DataInput dataIn, BooleanStream bs) throws IOException { + + protected DataStructure tightUnmarsalNestedObject(OpenWireFormat wireFormat, DataInput dataIn, + BooleanStream bs) throws IOException { return wireFormat.tightUnmarshalNestedObject(dataIn, bs); - } - protected int tightMarshalNestedObject1(OpenWireFormat wireFormat, DataStructure o, BooleanStream bs) throws IOException { + } + + protected int tightMarshalNestedObject1(OpenWireFormat wireFormat, DataStructure o, BooleanStream bs) + throws IOException { return wireFormat.tightMarshalNestedObject1(o, bs); } - - protected void tightMarshalNestedObject2(OpenWireFormat wireFormat, DataStructure o, DataOutput dataOut, BooleanStream bs) throws IOException { + + protected void tightMarshalNestedObject2(OpenWireFormat wireFormat, DataStructure o, DataOutput dataOut, + BooleanStream bs) throws IOException { wireFormat.tightMarshalNestedObject2(o, dataOut, bs); } - protected DataStructure tightUnmarsalCachedObject(OpenWireFormat wireFormat, DataInput dataIn, BooleanStream bs) throws IOException { - if( wireFormat.isCacheEnabled() ) { - if( bs.readBoolean() ) { + protected DataStructure tightUnmarsalCachedObject(OpenWireFormat wireFormat, DataInput dataIn, + BooleanStream bs) throws IOException { + if (wireFormat.isCacheEnabled()) { + if (bs.readBoolean()) { short index = dataIn.readShort(); DataStructure object = wireFormat.tightUnmarshalNestedObject(dataIn, bs); wireFormat.setInUnmarshallCache(index, object); @@ -138,26 +152,30 @@ abstract public class BaseDataStreamMarshaller implements DataStreamMarshaller { } else { return wireFormat.tightUnmarshalNestedObject(dataIn, bs); } - } - protected int tightMarshalCachedObject1(OpenWireFormat wireFormat, DataStructure o, BooleanStream bs) throws IOException { - if( wireFormat.isCacheEnabled() ) { + } + + protected int tightMarshalCachedObject1(OpenWireFormat wireFormat, DataStructure o, BooleanStream bs) + throws IOException { + if (wireFormat.isCacheEnabled()) { Short index = wireFormat.getMarshallCacheIndex(o); bs.writeBoolean(index == null); - if( index == null ) { + if (index == null) { int rc = wireFormat.tightMarshalNestedObject1(o, bs); wireFormat.addToMarshallCache(o); - return 2+rc; + return 2 + rc; } else { return 2; } } else { return wireFormat.tightMarshalNestedObject1(o, bs); } - } - protected void tightMarshalCachedObject2(OpenWireFormat wireFormat, DataStructure o, DataOutput dataOut, BooleanStream bs) throws IOException { - if( wireFormat.isCacheEnabled() ) { + } + + protected void tightMarshalCachedObject2(OpenWireFormat wireFormat, DataStructure o, DataOutput dataOut, + BooleanStream bs) throws IOException { + if (wireFormat.isCacheEnabled()) { Short index = wireFormat.getMarshallCacheIndex(o); - if( bs.readBoolean() ) { + if (bs.readBoolean()) { dataOut.writeShort(index.shortValue()); wireFormat.tightMarshalNestedObject2(o, dataOut, bs); } else { @@ -167,23 +185,23 @@ abstract public class BaseDataStreamMarshaller implements DataStreamMarshaller { wireFormat.tightMarshalNestedObject2(o, dataOut, bs); } } - - protected Throwable tightUnmarsalThrowable(OpenWireFormat wireFormat, DataInput dataIn, BooleanStream bs) throws IOException { - if( bs.readBoolean() ) { - String clazz = tightUnmarshalString(dataIn, bs); + + protected Throwable tightUnmarsalThrowable(OpenWireFormat wireFormat, DataInput dataIn, BooleanStream bs) + throws IOException { + if (bs.readBoolean()) { + String clazz = tightUnmarshalString(dataIn, bs); String message = tightUnmarshalString(dataIn, bs); Throwable o = createThrowable(clazz, message); - if( wireFormat.isStackTraceEnabled() ) { - if( STACK_TRACE_ELEMENT_CONSTRUCTOR!=null) { + if (wireFormat.isStackTraceEnabled()) { + if (STACK_TRACE_ELEMENT_CONSTRUCTOR != null) { StackTraceElement ss[] = new StackTraceElement[dataIn.readShort()]; for (int i = 0; i < ss.length; i++) { try { - ss[i] = (StackTraceElement) STACK_TRACE_ELEMENT_CONSTRUCTOR.newInstance(new Object[]{ - tightUnmarshalString(dataIn, bs), - tightUnmarshalString(dataIn, bs), - tightUnmarshalString(dataIn, bs), - Integer.valueOf(dataIn.readInt()) - }); + ss[i] = (StackTraceElement)STACK_TRACE_ELEMENT_CONSTRUCTOR + .newInstance(new Object[] {tightUnmarshalString(dataIn, bs), + tightUnmarshalString(dataIn, bs), + tightUnmarshalString(dataIn, bs), + Integer.valueOf(dataIn.readInt())}); } catch (IOException e) { throw e; } catch (Throwable e) { @@ -194,40 +212,41 @@ abstract public class BaseDataStreamMarshaller implements DataStreamMarshaller { short size = dataIn.readShort(); for (int i = 0; i < size; i++) { tightUnmarshalString(dataIn, bs); - tightUnmarshalString(dataIn, bs); - tightUnmarshalString(dataIn, bs); + tightUnmarshalString(dataIn, bs); + tightUnmarshalString(dataIn, bs); dataIn.readInt(); } } o.initCause(tightUnmarsalThrowable(wireFormat, dataIn, bs)); - + } return o; } else { return null; } } - + private Throwable createThrowable(String className, String message) { try { Class clazz = ClassLoading.loadClass(className, BaseDataStreamMarshaller.class.getClassLoader()); - Constructor constructor = clazz.getConstructor(new Class[]{String.class}); - return (Throwable) constructor.newInstance(new Object[]{message}); + Constructor constructor = clazz.getConstructor(new Class[] {String.class}); + return (Throwable)constructor.newInstance(new Object[] {message}); } catch (Throwable e) { - return new Throwable(className+": "+message); + return new Throwable(className + ": " + message); } } - - protected int tightMarshalThrowable1(OpenWireFormat wireFormat, Throwable o, BooleanStream bs) throws IOException { - if( o==null ) { + + protected int tightMarshalThrowable1(OpenWireFormat wireFormat, Throwable o, BooleanStream bs) + throws IOException { + if (o == null) { bs.writeBoolean(false); return 0; } else { - int rc=0; + int rc = 0; bs.writeBoolean(true); rc += tightMarshalString1(o.getClass().getName(), bs); rc += tightMarshalString1(o.getMessage(), bs); - if( wireFormat.isStackTraceEnabled() ) { + if (wireFormat.isStackTraceEnabled()) { rc += 2; StackTraceElement[] stackTrace = o.getStackTrace(); for (int i = 0; i < stackTrace.length; i++) { @@ -242,12 +261,13 @@ abstract public class BaseDataStreamMarshaller implements DataStreamMarshaller { return rc; } } - - protected void tightMarshalThrowable2(OpenWireFormat wireFormat, Throwable o, DataOutput dataOut, BooleanStream bs) throws IOException { - if( bs.readBoolean() ) { + + protected void tightMarshalThrowable2(OpenWireFormat wireFormat, Throwable o, DataOutput dataOut, + BooleanStream bs) throws IOException { + if (bs.readBoolean()) { tightMarshalString2(o.getClass().getName(), dataOut, bs); tightMarshalString2(o.getMessage(), dataOut, bs); - if( wireFormat.isStackTraceEnabled() ) { + if (wireFormat.isStackTraceEnabled()) { StackTraceElement[] stackTrace = o.getStackTrace(); dataOut.writeShort(stackTrace.length); for (int i = 0; i < stackTrace.length; i++) { @@ -261,31 +281,32 @@ abstract public class BaseDataStreamMarshaller implements DataStreamMarshaller { } } } - + protected String tightUnmarshalString(DataInput dataIn, BooleanStream bs) throws IOException { - if( bs.readBoolean() ) { - if( bs.readBoolean() ) { + if (bs.readBoolean()) { + if (bs.readBoolean()) { int size = dataIn.readShort(); byte data[] = new byte[size]; dataIn.readFully(data); - return new String(data,0); // Yes deprecated, but we know what we are doing. - } else { + return new String(data, 0); // Yes deprecated, but we know what + // we are doing. + } else { return dataIn.readUTF(); } } else { return null; } } - - protected int tightMarshalString1(String value, BooleanStream bs) throws IOException { - bs.writeBoolean(value!=null); - if( value!=null ) { - + + protected int tightMarshalString1(String value, BooleanStream bs) throws IOException { + bs.writeBoolean(value != null); + if (value != null) { + int strlen = value.length(); int utflen = 0; char[] charr = new char[strlen]; int c, count = 0; - boolean isOnlyAscii=true; + boolean isOnlyAscii = true; value.getChars(0, strlen, charr, 0); @@ -295,43 +316,44 @@ abstract public class BaseDataStreamMarshaller implements DataStreamMarshaller { utflen++; } else if (c > 0x07FF) { utflen += 3; - isOnlyAscii=false; + isOnlyAscii = false; } else { - isOnlyAscii=false; + isOnlyAscii = false; utflen += 2; } } - - if( utflen >= Short.MAX_VALUE ) + + if (utflen >= Short.MAX_VALUE) { throw new IOException("Encountered a String value that is too long to encode."); - - bs.writeBoolean(isOnlyAscii); - return utflen+2; - + } + bs.writeBoolean(isOnlyAscii); + return utflen + 2; + } else { return 0; } } - + protected void tightMarshalString2(String value, DataOutput dataOut, BooleanStream bs) throws IOException { - if( bs.readBoolean() ) { + if (bs.readBoolean()) { // If we verified it only holds ascii values - if( bs.readBoolean() ) { + if (bs.readBoolean()) { dataOut.writeShort(value.length()); dataOut.writeBytes(value); } else { - dataOut.writeUTF(value); + dataOut.writeUTF(value); } } - } - - protected int tightMarshalObjectArray1(OpenWireFormat wireFormat, DataStructure[] objects, BooleanStream bs) throws IOException { - if( objects != null ) { - int rc=0; + } + + protected int tightMarshalObjectArray1(OpenWireFormat wireFormat, DataStructure[] objects, + BooleanStream bs) throws IOException { + if (objects != null) { + int rc = 0; bs.writeBoolean(true); rc += 2; - for( int i=0; i < objects.length; i++ ) { - rc += tightMarshalNestedObject1(wireFormat,objects[i], bs); + for (int i = 0; i < objects.length; i++) { + rc += tightMarshalNestedObject1(wireFormat, objects[i], bs); } return rc; } else { @@ -339,12 +361,13 @@ abstract public class BaseDataStreamMarshaller implements DataStreamMarshaller { return 0; } } - - protected void tightMarshalObjectArray2(OpenWireFormat wireFormat, DataStructure[] objects, DataOutput dataOut, BooleanStream bs) throws IOException { - if( bs.readBoolean() ) { + + protected void tightMarshalObjectArray2(OpenWireFormat wireFormat, DataStructure[] objects, + DataOutput dataOut, BooleanStream bs) throws IOException { + if (bs.readBoolean()) { dataOut.writeShort(objects.length); - for( int i=0; i < objects.length; i++ ) { - tightMarshalNestedObject2(wireFormat,objects[i], dataOut, bs); + for (int i = 0; i < objects.length; i++) { + tightMarshalNestedObject2(wireFormat, objects[i], dataOut, bs); } } } @@ -352,61 +375,66 @@ abstract public class BaseDataStreamMarshaller implements DataStreamMarshaller { protected int tightMarshalConstByteArray1(byte[] data, BooleanStream bs, int i) throws IOException { return i; } - protected void tightMarshalConstByteArray2(byte[] data, DataOutput dataOut, BooleanStream bs, int i) throws IOException { + + protected void tightMarshalConstByteArray2(byte[] data, DataOutput dataOut, BooleanStream bs, int i) + throws IOException { dataOut.write(data, 0, i); } - protected byte[] tightUnmarshalConstByteArray(DataInput dataIn, BooleanStream bs, int i) throws IOException { + protected byte[] tightUnmarshalConstByteArray(DataInput dataIn, BooleanStream bs, int i) + throws IOException { byte data[] = new byte[i]; dataIn.readFully(data); return data; } protected int tightMarshalByteArray1(byte[] data, BooleanStream bs) throws IOException { - bs.writeBoolean(data!=null); - if( data!=null ){ - return data.length+4; + bs.writeBoolean(data != null); + if (data != null) { + return data.length + 4; } else { return 0; } } - - protected void tightMarshalByteArray2(byte[] data, DataOutput dataOut, BooleanStream bs) throws IOException { - if( bs.readBoolean() ){ + + protected void tightMarshalByteArray2(byte[] data, DataOutput dataOut, BooleanStream bs) + throws IOException { + if (bs.readBoolean()) { dataOut.writeInt(data.length); dataOut.write(data); } } protected byte[] tightUnmarshalByteArray(DataInput dataIn, BooleanStream bs) throws IOException { - byte rc[]=null; - if( bs.readBoolean() ) { + byte rc[] = null; + if (bs.readBoolean()) { int size = dataIn.readInt(); rc = new byte[size]; dataIn.readFully(rc); } return rc; } - + protected int tightMarshalByteSequence1(ByteSequence data, BooleanStream bs) throws IOException { - bs.writeBoolean(data!=null); - if( data!=null ){ - return data.getLength()+4; + bs.writeBoolean(data != null); + if (data != null) { + return data.getLength() + 4; } else { return 0; } } - - protected void tightMarshalByteSequence2(ByteSequence data, DataOutput dataOut, BooleanStream bs) throws IOException { - if( bs.readBoolean() ){ + + protected void tightMarshalByteSequence2(ByteSequence data, DataOutput dataOut, BooleanStream bs) + throws IOException { + if (bs.readBoolean()) { dataOut.writeInt(data.getLength()); dataOut.write(data.getData(), data.getOffset(), data.getLength()); } } protected ByteSequence tightUnmarshalByteSequence(DataInput dataIn, BooleanStream bs) throws IOException { - ByteSequence rc=null; - if( bs.readBoolean() ) { + ByteSequence rc = null; + if (bs.readBoolean()) { int size = dataIn.readInt(); byte[] t = new byte[size]; dataIn.readFully(t); @@ -418,29 +446,35 @@ abstract public class BaseDataStreamMarshaller implements DataStreamMarshaller { // // The loose marshaling logic // - - public void looseMarshal(OpenWireFormat wireFormat, Object o, DataOutput dataOut) throws IOException { + + public void looseMarshal(OpenWireFormat wireFormat, Object o, DataOutput dataOut) throws IOException { } - public void looseUnmarshal(OpenWireFormat wireFormat, Object o, DataInput dataIn) throws IOException { + + public void looseUnmarshal(OpenWireFormat wireFormat, Object o, DataInput dataIn) throws IOException { } - + public void looseMarshalLong(OpenWireFormat wireFormat, long o, DataOutput dataOut) throws IOException { dataOut.writeLong(o); } + public long looseUnmarshalLong(OpenWireFormat wireFormat, DataInput dataIn) throws IOException { return dataIn.readLong(); } - - protected DataStructure looseUnmarsalNestedObject(OpenWireFormat wireFormat, DataInput dataIn) throws IOException { + + protected DataStructure looseUnmarsalNestedObject(OpenWireFormat wireFormat, DataInput dataIn) + throws IOException { return wireFormat.looseUnmarshalNestedObject(dataIn); - } - protected void looseMarshalNestedObject(OpenWireFormat wireFormat, DataStructure o, DataOutput dataOut) throws IOException { + } + + protected void looseMarshalNestedObject(OpenWireFormat wireFormat, DataStructure o, DataOutput dataOut) + throws IOException { wireFormat.looseMarshalNestedObject(o, dataOut); } - protected DataStructure looseUnmarsalCachedObject(OpenWireFormat wireFormat, DataInput dataIn) throws IOException { - if( wireFormat.isCacheEnabled() ) { - if( dataIn.readBoolean() ) { + protected DataStructure looseUnmarsalCachedObject(OpenWireFormat wireFormat, DataInput dataIn) + throws IOException { + if (wireFormat.isCacheEnabled()) { + if (dataIn.readBoolean()) { short index = dataIn.readShort(); DataStructure object = wireFormat.looseUnmarshalNestedObject(dataIn); wireFormat.setInUnmarshallCache(index, object); @@ -452,12 +486,14 @@ abstract public class BaseDataStreamMarshaller implements DataStreamMarshaller { } else { return wireFormat.looseUnmarshalNestedObject(dataIn); } - } - protected void looseMarshalCachedObject(OpenWireFormat wireFormat, DataStructure o, DataOutput dataOut) throws IOException { - if( wireFormat.isCacheEnabled() ) { + } + + protected void looseMarshalCachedObject(OpenWireFormat wireFormat, DataStructure o, DataOutput dataOut) + throws IOException { + if (wireFormat.isCacheEnabled()) { Short index = wireFormat.getMarshallCacheIndex(o); dataOut.writeBoolean(index == null); - if( index == null ) { + if (index == null) { index = wireFormat.addToMarshallCache(o); dataOut.writeShort(index.shortValue()); wireFormat.looseMarshalNestedObject(o, dataOut); @@ -468,23 +504,23 @@ abstract public class BaseDataStreamMarshaller implements DataStreamMarshaller { wireFormat.looseMarshalNestedObject(o, dataOut); } } - - protected Throwable looseUnmarsalThrowable(OpenWireFormat wireFormat, DataInput dataIn) throws IOException { - if( dataIn.readBoolean() ) { - String clazz = looseUnmarshalString(dataIn); + + protected Throwable looseUnmarsalThrowable(OpenWireFormat wireFormat, DataInput dataIn) + throws IOException { + if (dataIn.readBoolean()) { + String clazz = looseUnmarshalString(dataIn); String message = looseUnmarshalString(dataIn); Throwable o = createThrowable(clazz, message); - if( wireFormat.isStackTraceEnabled() ) { - if( STACK_TRACE_ELEMENT_CONSTRUCTOR!=null) { + if (wireFormat.isStackTraceEnabled()) { + if (STACK_TRACE_ELEMENT_CONSTRUCTOR != null) { StackTraceElement ss[] = new StackTraceElement[dataIn.readShort()]; for (int i = 0; i < ss.length; i++) { try { - ss[i] = (StackTraceElement) STACK_TRACE_ELEMENT_CONSTRUCTOR.newInstance(new Object[]{ - looseUnmarshalString(dataIn), - looseUnmarshalString(dataIn), - looseUnmarshalString(dataIn), - Integer.valueOf(dataIn.readInt()) - }); + ss[i] = (StackTraceElement)STACK_TRACE_ELEMENT_CONSTRUCTOR + .newInstance(new Object[] {looseUnmarshalString(dataIn), + looseUnmarshalString(dataIn), + looseUnmarshalString(dataIn), + Integer.valueOf(dataIn.readInt())}); } catch (IOException e) { throw e; } catch (Throwable e) { @@ -495,27 +531,27 @@ abstract public class BaseDataStreamMarshaller implements DataStreamMarshaller { short size = dataIn.readShort(); for (int i = 0; i < size; i++) { looseUnmarshalString(dataIn); - looseUnmarshalString(dataIn); - looseUnmarshalString(dataIn); + looseUnmarshalString(dataIn); + looseUnmarshalString(dataIn); dataIn.readInt(); } } o.initCause(looseUnmarsalThrowable(wireFormat, dataIn)); - + } return o; } else { return null; } } - - - protected void looseMarshalThrowable(OpenWireFormat wireFormat, Throwable o, DataOutput dataOut) throws IOException { - dataOut.writeBoolean(o!=null); - if( o!=null ) { + + protected void looseMarshalThrowable(OpenWireFormat wireFormat, Throwable o, DataOutput dataOut) + throws IOException { + dataOut.writeBoolean(o != null); + if (o != null) { looseMarshalString(o.getClass().getName(), dataOut); looseMarshalString(o.getMessage(), dataOut); - if( wireFormat.isStackTraceEnabled() ) { + if (wireFormat.isStackTraceEnabled()) { StackTraceElement[] stackTrace = o.getStackTrace(); dataOut.writeShort(stackTrace.length); for (int i = 0; i < stackTrace.length; i++) { @@ -529,33 +565,35 @@ abstract public class BaseDataStreamMarshaller implements DataStreamMarshaller { } } } - + protected String looseUnmarshalString(DataInput dataIn) throws IOException { - if( dataIn.readBoolean() ) { + if (dataIn.readBoolean()) { return dataIn.readUTF(); } else { return null; } } - + protected void looseMarshalString(String value, DataOutput dataOut) throws IOException { - dataOut.writeBoolean(value!=null); - if( value!=null ) { - dataOut.writeUTF(value); + dataOut.writeBoolean(value != null); + if (value != null) { + dataOut.writeUTF(value); } - } - - protected void looseMarshalObjectArray(OpenWireFormat wireFormat, DataStructure[] objects, DataOutput dataOut) throws IOException { - dataOut.writeBoolean(objects!=null); - if( objects!=null ) { + } + + protected void looseMarshalObjectArray(OpenWireFormat wireFormat, DataStructure[] objects, + DataOutput dataOut) throws IOException { + dataOut.writeBoolean(objects != null); + if (objects != null) { dataOut.writeShort(objects.length); - for( int i=0; i < objects.length; i++ ) { - looseMarshalNestedObject(wireFormat,objects[i], dataOut); + for (int i = 0; i < objects.length; i++) { + looseMarshalNestedObject(wireFormat, objects[i], dataOut); } } } - - protected void looseMarshalConstByteArray(OpenWireFormat wireFormat, byte[] data, DataOutput dataOut, int i) throws IOException { + + protected void looseMarshalConstByteArray(OpenWireFormat wireFormat, byte[] data, DataOutput dataOut, + int i) throws IOException { dataOut.write(data, 0, i); } @@ -565,17 +603,18 @@ abstract public class BaseDataStreamMarshaller implements DataStreamMarshaller { return data; } - protected void looseMarshalByteArray(OpenWireFormat wireFormat, byte[] data, DataOutput dataOut) throws IOException { - dataOut.writeBoolean(data!=null); - if( data!=null ){ + protected void looseMarshalByteArray(OpenWireFormat wireFormat, byte[] data, DataOutput dataOut) + throws IOException { + dataOut.writeBoolean(data != null); + if (data != null) { dataOut.writeInt(data.length); dataOut.write(data); } } protected byte[] looseUnmarshalByteArray(DataInput dataIn) throws IOException { - byte rc[]=null; - if( dataIn.readBoolean() ) { + byte rc[] = null; + if (dataIn.readBoolean()) { int size = dataIn.readInt(); rc = new byte[size]; dataIn.readFully(rc); @@ -583,17 +622,18 @@ abstract public class BaseDataStreamMarshaller implements DataStreamMarshaller { return rc; } - protected void looseMarshalByteSequence(OpenWireFormat wireFormat, ByteSequence data, DataOutput dataOut) throws IOException { - dataOut.writeBoolean(data!=null); - if( data!=null ){ + protected void looseMarshalByteSequence(OpenWireFormat wireFormat, ByteSequence data, DataOutput dataOut) + throws IOException { + dataOut.writeBoolean(data != null); + if (data != null) { dataOut.writeInt(data.getLength()); dataOut.write(data.getData(), data.getOffset(), data.getLength()); } } protected ByteSequence looseUnmarshalByteSequence(DataInput dataIn) throws IOException { - ByteSequence rc=null; - if( dataIn.readBoolean() ) { + ByteSequence rc = null; + if (dataIn.readBoolean()) { int size = dataIn.readInt(); byte[] t = new byte[size]; dataIn.readFully(t); diff --git a/activemq-core/src/main/java/org/apache/activemq/openwire/v2/BrokerInfoMarshaller.java b/activemq-core/src/main/java/org/apache/activemq/openwire/v2/BrokerInfoMarshaller.java index f0c0b281cb..b4468256ac 100644 --- a/activemq-core/src/main/java/org/apache/activemq/openwire/v2/BrokerInfoMarshaller.java +++ b/activemq-core/src/main/java/org/apache/activemq/openwire/v2/BrokerInfoMarshaller.java @@ -24,29 +24,27 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - - /** * Marshalling code for Open Wire Format for BrokerInfoMarshaller - * - * - * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * + * + * + * NOTE!: This file is auto generated - do not modify! if you need to make a + * change, please see the modify the groovy scripts in the under src/gram/script + * and then use maven openwire:generate to regenerate this file. + * * @version $Revision$ */ public class BrokerInfoMarshaller extends BaseCommandMarshaller { /** * Return the type of Data Structure we marshal + * * @return short representation of the type data structure */ public byte getDataStructureType() { return BrokerInfo.DATA_STRUCTURE_TYPE; } - + /** * @return a new object instance */ @@ -56,27 +54,29 @@ public class BrokerInfoMarshaller extends BaseCommandMarshaller { /** * Un-marshal an object instance from the data input stream - * + * * @param o the object to un-marshal * @param dataIn the data input stream to build the object from * @throws IOException */ - public void tightUnmarshal(OpenWireFormat wireFormat, Object o, DataInput dataIn, BooleanStream bs) throws IOException { + public void tightUnmarshal(OpenWireFormat wireFormat, Object o, DataInput dataIn, BooleanStream bs) + throws IOException { super.tightUnmarshal(wireFormat, o, dataIn, bs); BrokerInfo info = (BrokerInfo)o; - info.setBrokerId((org.apache.activemq.command.BrokerId) tightUnmarsalCachedObject(wireFormat, dataIn, bs)); + info.setBrokerId((org.apache.activemq.command.BrokerId)tightUnmarsalCachedObject(wireFormat, dataIn, + bs)); info.setBrokerURL(tightUnmarshalString(dataIn, bs)); if (bs.readBoolean()) { short size = dataIn.readShort(); org.apache.activemq.command.BrokerInfo value[] = new org.apache.activemq.command.BrokerInfo[size]; - for( int i=0; i < size; i++ ) { - value[i] = (org.apache.activemq.command.BrokerInfo) tightUnmarsalNestedObject(wireFormat,dataIn, bs); + for (int i = 0; i < size; i++) { + value[i] = (org.apache.activemq.command.BrokerInfo)tightUnmarsalNestedObject(wireFormat, + dataIn, bs); } info.setPeerBrokerInfos(value); - } - else { + } else { info.setPeerBrokerInfos(null); } info.setBrokerName(tightUnmarshalString(dataIn, bs)); @@ -89,7 +89,6 @@ public class BrokerInfoMarshaller extends BaseCommandMarshaller { } - /** * Write the booleans that this object uses to a BooleanStream */ @@ -107,19 +106,20 @@ public class BrokerInfoMarshaller extends BaseCommandMarshaller { bs.writeBoolean(info.isFaultTolerantConfiguration()); bs.writeBoolean(info.isDuplexConnection()); bs.writeBoolean(info.isNetworkConnection()); - rc+=tightMarshalLong1(wireFormat, info.getConnectionId(), bs); + rc += tightMarshalLong1(wireFormat, info.getConnectionId(), bs); return rc + 0; } /** * Write a object instance to data output stream - * + * * @param o the instance to be marshaled * @param dataOut the output stream * @throws IOException thrown if an error occurs */ - public void tightMarshal2(OpenWireFormat wireFormat, Object o, DataOutput dataOut, BooleanStream bs) throws IOException { + public void tightMarshal2(OpenWireFormat wireFormat, Object o, DataOutput dataOut, BooleanStream bs) + throws IOException { super.tightMarshal2(wireFormat, o, dataOut, bs); BrokerInfo info = (BrokerInfo)o; @@ -138,7 +138,7 @@ public class BrokerInfoMarshaller extends BaseCommandMarshaller { /** * Un-marshal an object instance from the data input stream - * + * * @param o the object to un-marshal * @param dataIn the data input stream to build the object from * @throws IOException @@ -147,18 +147,18 @@ public class BrokerInfoMarshaller extends BaseCommandMarshaller { super.looseUnmarshal(wireFormat, o, dataIn); BrokerInfo info = (BrokerInfo)o; - info.setBrokerId((org.apache.activemq.command.BrokerId) looseUnmarsalCachedObject(wireFormat, dataIn)); + info.setBrokerId((org.apache.activemq.command.BrokerId)looseUnmarsalCachedObject(wireFormat, dataIn)); info.setBrokerURL(looseUnmarshalString(dataIn)); if (dataIn.readBoolean()) { short size = dataIn.readShort(); org.apache.activemq.command.BrokerInfo value[] = new org.apache.activemq.command.BrokerInfo[size]; - for( int i=0; i < size; i++ ) { - value[i] = (org.apache.activemq.command.BrokerInfo) looseUnmarsalNestedObject(wireFormat,dataIn); + for (int i = 0; i < size; i++) { + value[i] = (org.apache.activemq.command.BrokerInfo)looseUnmarsalNestedObject(wireFormat, + dataIn); } info.setPeerBrokerInfos(value); - } - else { + } else { info.setPeerBrokerInfos(null); } info.setBrokerName(looseUnmarshalString(dataIn)); @@ -171,7 +171,6 @@ public class BrokerInfoMarshaller extends BaseCommandMarshaller { } - /** * Write the booleans that this object uses to a BooleanStream */ diff --git a/activemq-core/src/main/java/org/apache/activemq/openwire/v2/ConnectionInfoMarshaller.java b/activemq-core/src/main/java/org/apache/activemq/openwire/v2/ConnectionInfoMarshaller.java index 8f827ba796..03d30945a0 100644 --- a/activemq-core/src/main/java/org/apache/activemq/openwire/v2/ConnectionInfoMarshaller.java +++ b/activemq-core/src/main/java/org/apache/activemq/openwire/v2/ConnectionInfoMarshaller.java @@ -24,29 +24,27 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - - /** * Marshalling code for Open Wire Format for ConnectionInfoMarshaller - * - * - * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * + * + * + * NOTE!: This file is auto generated - do not modify! if you need to make a + * change, please see the modify the groovy scripts in the under src/gram/script + * and then use maven openwire:generate to regenerate this file. + * * @version $Revision$ */ public class ConnectionInfoMarshaller extends BaseCommandMarshaller { /** * Return the type of Data Structure we marshal + * * @return short representation of the type data structure */ public byte getDataStructureType() { return ConnectionInfo.DATA_STRUCTURE_TYPE; } - + /** * @return a new object instance */ @@ -56,16 +54,18 @@ public class ConnectionInfoMarshaller extends BaseCommandMarshaller { /** * Un-marshal an object instance from the data input stream - * + * * @param o the object to un-marshal * @param dataIn the data input stream to build the object from * @throws IOException */ - public void tightUnmarshal(OpenWireFormat wireFormat, Object o, DataInput dataIn, BooleanStream bs) throws IOException { + public void tightUnmarshal(OpenWireFormat wireFormat, Object o, DataInput dataIn, BooleanStream bs) + throws IOException { super.tightUnmarshal(wireFormat, o, dataIn, bs); ConnectionInfo info = (ConnectionInfo)o; - info.setConnectionId((org.apache.activemq.command.ConnectionId) tightUnmarsalCachedObject(wireFormat, dataIn, bs)); + info.setConnectionId((org.apache.activemq.command.ConnectionId)tightUnmarsalCachedObject(wireFormat, + dataIn, bs)); info.setClientId(tightUnmarshalString(dataIn, bs)); info.setPassword(tightUnmarshalString(dataIn, bs)); info.setUserName(tightUnmarshalString(dataIn, bs)); @@ -73,12 +73,12 @@ public class ConnectionInfoMarshaller extends BaseCommandMarshaller { if (bs.readBoolean()) { short size = dataIn.readShort(); org.apache.activemq.command.BrokerId value[] = new org.apache.activemq.command.BrokerId[size]; - for( int i=0; i < size; i++ ) { - value[i] = (org.apache.activemq.command.BrokerId) tightUnmarsalNestedObject(wireFormat,dataIn, bs); + for (int i = 0; i < size; i++) { + value[i] = (org.apache.activemq.command.BrokerId)tightUnmarsalNestedObject(wireFormat, + dataIn, bs); } info.setBrokerPath(value); - } - else { + } else { info.setBrokerPath(null); } info.setBrokerMasterConnector(bs.readBoolean()); @@ -87,7 +87,6 @@ public class ConnectionInfoMarshaller extends BaseCommandMarshaller { } - /** * Write the booleans that this object uses to a BooleanStream */ @@ -110,12 +109,13 @@ public class ConnectionInfoMarshaller extends BaseCommandMarshaller { /** * Write a object instance to data output stream - * + * * @param o the instance to be marshaled * @param dataOut the output stream * @throws IOException thrown if an error occurs */ - public void tightMarshal2(OpenWireFormat wireFormat, Object o, DataOutput dataOut, BooleanStream bs) throws IOException { + public void tightMarshal2(OpenWireFormat wireFormat, Object o, DataOutput dataOut, BooleanStream bs) + throws IOException { super.tightMarshal2(wireFormat, o, dataOut, bs); ConnectionInfo info = (ConnectionInfo)o; @@ -132,7 +132,7 @@ public class ConnectionInfoMarshaller extends BaseCommandMarshaller { /** * Un-marshal an object instance from the data input stream - * + * * @param o the object to un-marshal * @param dataIn the data input stream to build the object from * @throws IOException @@ -141,7 +141,8 @@ public class ConnectionInfoMarshaller extends BaseCommandMarshaller { super.looseUnmarshal(wireFormat, o, dataIn); ConnectionInfo info = (ConnectionInfo)o; - info.setConnectionId((org.apache.activemq.command.ConnectionId) looseUnmarsalCachedObject(wireFormat, dataIn)); + info.setConnectionId((org.apache.activemq.command.ConnectionId)looseUnmarsalCachedObject(wireFormat, + dataIn)); info.setClientId(looseUnmarshalString(dataIn)); info.setPassword(looseUnmarshalString(dataIn)); info.setUserName(looseUnmarshalString(dataIn)); @@ -149,12 +150,11 @@ public class ConnectionInfoMarshaller extends BaseCommandMarshaller { if (dataIn.readBoolean()) { short size = dataIn.readShort(); org.apache.activemq.command.BrokerId value[] = new org.apache.activemq.command.BrokerId[size]; - for( int i=0; i < size; i++ ) { - value[i] = (org.apache.activemq.command.BrokerId) looseUnmarsalNestedObject(wireFormat,dataIn); + for (int i = 0; i < size; i++) { + value[i] = (org.apache.activemq.command.BrokerId)looseUnmarsalNestedObject(wireFormat, dataIn); } info.setBrokerPath(value); - } - else { + } else { info.setBrokerPath(null); } info.setBrokerMasterConnector(dataIn.readBoolean()); @@ -163,7 +163,6 @@ public class ConnectionInfoMarshaller extends BaseCommandMarshaller { } - /** * Write the booleans that this object uses to a BooleanStream */ diff --git a/activemq-core/src/main/java/org/apache/activemq/openwire/v2/ConsumerIdMarshaller.java b/activemq-core/src/main/java/org/apache/activemq/openwire/v2/ConsumerIdMarshaller.java index 89cdefc4e3..0f19ba2579 100644 --- a/activemq-core/src/main/java/org/apache/activemq/openwire/v2/ConsumerIdMarshaller.java +++ b/activemq-core/src/main/java/org/apache/activemq/openwire/v2/ConsumerIdMarshaller.java @@ -24,29 +24,27 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - - /** * Marshalling code for Open Wire Format for ConsumerIdMarshaller - * - * - * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * + * + * + * NOTE!: This file is auto generated - do not modify! if you need to make a + * change, please see the modify the groovy scripts in the under src/gram/script + * and then use maven openwire:generate to regenerate this file. + * * @version $Revision$ */ public class ConsumerIdMarshaller extends BaseDataStreamMarshaller { /** * Return the type of Data Structure we marshal + * * @return short representation of the type data structure */ public byte getDataStructureType() { return ConsumerId.DATA_STRUCTURE_TYPE; } - + /** * @return a new object instance */ @@ -56,12 +54,13 @@ public class ConsumerIdMarshaller extends BaseDataStreamMarshaller { /** * Un-marshal an object instance from the data input stream - * + * * @param o the object to un-marshal * @param dataIn the data input stream to build the object from * @throws IOException */ - public void tightUnmarshal(OpenWireFormat wireFormat, Object o, DataInput dataIn, BooleanStream bs) throws IOException { + public void tightUnmarshal(OpenWireFormat wireFormat, Object o, DataInput dataIn, BooleanStream bs) + throws IOException { super.tightUnmarshal(wireFormat, o, dataIn, bs); ConsumerId info = (ConsumerId)o; @@ -71,7 +70,6 @@ public class ConsumerIdMarshaller extends BaseDataStreamMarshaller { } - /** * Write the booleans that this object uses to a BooleanStream */ @@ -81,20 +79,21 @@ public class ConsumerIdMarshaller extends BaseDataStreamMarshaller { int rc = super.tightMarshal1(wireFormat, o, bs); rc += tightMarshalString1(info.getConnectionId(), bs); - rc+=tightMarshalLong1(wireFormat, info.getSessionId(), bs); - rc+=tightMarshalLong1(wireFormat, info.getValue(), bs); + rc += tightMarshalLong1(wireFormat, info.getSessionId(), bs); + rc += tightMarshalLong1(wireFormat, info.getValue(), bs); return rc + 0; } /** * Write a object instance to data output stream - * + * * @param o the instance to be marshaled * @param dataOut the output stream * @throws IOException thrown if an error occurs */ - public void tightMarshal2(OpenWireFormat wireFormat, Object o, DataOutput dataOut, BooleanStream bs) throws IOException { + public void tightMarshal2(OpenWireFormat wireFormat, Object o, DataOutput dataOut, BooleanStream bs) + throws IOException { super.tightMarshal2(wireFormat, o, dataOut, bs); ConsumerId info = (ConsumerId)o; @@ -106,7 +105,7 @@ public class ConsumerIdMarshaller extends BaseDataStreamMarshaller { /** * Un-marshal an object instance from the data input stream - * + * * @param o the object to un-marshal * @param dataIn the data input stream to build the object from * @throws IOException @@ -121,7 +120,6 @@ public class ConsumerIdMarshaller extends BaseDataStreamMarshaller { } - /** * Write the booleans that this object uses to a BooleanStream */ diff --git a/activemq-core/src/main/java/org/apache/activemq/openwire/v2/ConsumerInfoMarshaller.java b/activemq-core/src/main/java/org/apache/activemq/openwire/v2/ConsumerInfoMarshaller.java index c7debbfd97..7a40f53320 100644 --- a/activemq-core/src/main/java/org/apache/activemq/openwire/v2/ConsumerInfoMarshaller.java +++ b/activemq-core/src/main/java/org/apache/activemq/openwire/v2/ConsumerInfoMarshaller.java @@ -21,32 +21,32 @@ import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; -import org.apache.activemq.openwire.*; -import org.apache.activemq.command.*; - - +import org.apache.activemq.command.ConsumerInfo; +import org.apache.activemq.command.DataStructure; +import org.apache.activemq.openwire.BooleanStream; +import org.apache.activemq.openwire.OpenWireFormat; /** * Marshalling code for Open Wire Format for ConsumerInfoMarshaller - * - * - * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * + * + * + * NOTE!: This file is auto generated - do not modify! if you need to make a + * change, please see the modify the groovy scripts in the under src/gram/script + * and then use maven openwire:generate to regenerate this file. + * * @version $Revision$ */ public class ConsumerInfoMarshaller extends BaseCommandMarshaller { /** * Return the type of Data Structure we marshal + * * @return short representation of the type data structure */ public byte getDataStructureType() { return ConsumerInfo.DATA_STRUCTURE_TYPE; } - + /** * @return a new object instance */ @@ -56,18 +56,24 @@ public class ConsumerInfoMarshaller extends BaseCommandMarshaller { /** * Un-marshal an object instance from the data input stream - * + * * @param o the object to un-marshal * @param dataIn the data input stream to build the object from * @throws IOException */ - public void tightUnmarshal(OpenWireFormat wireFormat, Object o, DataInput dataIn, BooleanStream bs) throws IOException { + public void tightUnmarshal(OpenWireFormat wireFormat, Object o, DataInput dataIn, BooleanStream bs) + throws IOException { super.tightUnmarshal(wireFormat, o, dataIn, bs); ConsumerInfo info = (ConsumerInfo)o; - info.setConsumerId((org.apache.activemq.command.ConsumerId) tightUnmarsalCachedObject(wireFormat, dataIn, bs)); + info.setConsumerId((org.apache.activemq.command.ConsumerId)tightUnmarsalCachedObject(wireFormat, + dataIn, bs)); info.setBrowser(bs.readBoolean()); - info.setDestination((org.apache.activemq.command.ActiveMQDestination) tightUnmarsalCachedObject(wireFormat, dataIn, bs)); + info + .setDestination((org.apache.activemq.command.ActiveMQDestination)tightUnmarsalCachedObject( + wireFormat, + dataIn, + bs)); info.setPrefetchSize(dataIn.readInt()); info.setMaximumPendingMessageLimit(dataIn.readInt()); info.setDispatchAsync(bs.readBoolean()); @@ -81,22 +87,25 @@ public class ConsumerInfoMarshaller extends BaseCommandMarshaller { if (bs.readBoolean()) { short size = dataIn.readShort(); org.apache.activemq.command.BrokerId value[] = new org.apache.activemq.command.BrokerId[size]; - for( int i=0; i < size; i++ ) { - value[i] = (org.apache.activemq.command.BrokerId) tightUnmarsalNestedObject(wireFormat,dataIn, bs); + for (int i = 0; i < size; i++) { + value[i] = (org.apache.activemq.command.BrokerId)tightUnmarsalNestedObject(wireFormat, + dataIn, bs); } info.setBrokerPath(value); - } - else { + } else { info.setBrokerPath(null); } - info.setAdditionalPredicate((org.apache.activemq.filter.BooleanExpression) tightUnmarsalNestedObject(wireFormat, dataIn, bs)); + info + .setAdditionalPredicate((org.apache.activemq.filter.BooleanExpression)tightUnmarsalNestedObject( + wireFormat, + dataIn, + bs)); info.setNetworkSubscription(bs.readBoolean()); info.setOptimizedAcknowledge(bs.readBoolean()); info.setNoRangeAcks(bs.readBoolean()); } - /** * Write the booleans that this object uses to a BooleanStream */ @@ -125,12 +134,13 @@ public class ConsumerInfoMarshaller extends BaseCommandMarshaller { /** * Write a object instance to data output stream - * + * * @param o the instance to be marshaled * @param dataOut the output stream * @throws IOException thrown if an error occurs */ - public void tightMarshal2(OpenWireFormat wireFormat, Object o, DataOutput dataOut, BooleanStream bs) throws IOException { + public void tightMarshal2(OpenWireFormat wireFormat, Object o, DataOutput dataOut, BooleanStream bs) + throws IOException { super.tightMarshal2(wireFormat, o, dataOut, bs); ConsumerInfo info = (ConsumerInfo)o; @@ -156,7 +166,7 @@ public class ConsumerInfoMarshaller extends BaseCommandMarshaller { /** * Un-marshal an object instance from the data input stream - * + * * @param o the object to un-marshal * @param dataIn the data input stream to build the object from * @throws IOException @@ -165,9 +175,13 @@ public class ConsumerInfoMarshaller extends BaseCommandMarshaller { super.looseUnmarshal(wireFormat, o, dataIn); ConsumerInfo info = (ConsumerInfo)o; - info.setConsumerId((org.apache.activemq.command.ConsumerId) looseUnmarsalCachedObject(wireFormat, dataIn)); + info.setConsumerId((org.apache.activemq.command.ConsumerId)looseUnmarsalCachedObject(wireFormat, + dataIn)); info.setBrowser(dataIn.readBoolean()); - info.setDestination((org.apache.activemq.command.ActiveMQDestination) looseUnmarsalCachedObject(wireFormat, dataIn)); + info + .setDestination((org.apache.activemq.command.ActiveMQDestination)looseUnmarsalCachedObject( + wireFormat, + dataIn)); info.setPrefetchSize(dataIn.readInt()); info.setMaximumPendingMessageLimit(dataIn.readInt()); info.setDispatchAsync(dataIn.readBoolean()); @@ -181,22 +195,23 @@ public class ConsumerInfoMarshaller extends BaseCommandMarshaller { if (dataIn.readBoolean()) { short size = dataIn.readShort(); org.apache.activemq.command.BrokerId value[] = new org.apache.activemq.command.BrokerId[size]; - for( int i=0; i < size; i++ ) { - value[i] = (org.apache.activemq.command.BrokerId) looseUnmarsalNestedObject(wireFormat,dataIn); + for (int i = 0; i < size; i++) { + value[i] = (org.apache.activemq.command.BrokerId)looseUnmarsalNestedObject(wireFormat, dataIn); } info.setBrokerPath(value); - } - else { + } else { info.setBrokerPath(null); } - info.setAdditionalPredicate((org.apache.activemq.filter.BooleanExpression) looseUnmarsalNestedObject(wireFormat, dataIn)); + info + .setAdditionalPredicate((org.apache.activemq.filter.BooleanExpression)looseUnmarsalNestedObject( + wireFormat, + dataIn)); info.setNetworkSubscription(dataIn.readBoolean()); info.setOptimizedAcknowledge(dataIn.readBoolean()); info.setNoRangeAcks(dataIn.readBoolean()); } - /** * Write the booleans that this object uses to a BooleanStream */ diff --git a/activemq-core/src/main/java/org/apache/activemq/openwire/v2/DataArrayResponseMarshaller.java b/activemq-core/src/main/java/org/apache/activemq/openwire/v2/DataArrayResponseMarshaller.java index 2c5e46710e..6a753c0c5a 100644 --- a/activemq-core/src/main/java/org/apache/activemq/openwire/v2/DataArrayResponseMarshaller.java +++ b/activemq-core/src/main/java/org/apache/activemq/openwire/v2/DataArrayResponseMarshaller.java @@ -24,29 +24,27 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - - /** * Marshalling code for Open Wire Format for DataArrayResponseMarshaller - * - * - * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * + * + * + * NOTE!: This file is auto generated - do not modify! if you need to make a + * change, please see the modify the groovy scripts in the under src/gram/script + * and then use maven openwire:generate to regenerate this file. + * * @version $Revision$ */ public class DataArrayResponseMarshaller extends ResponseMarshaller { /** * Return the type of Data Structure we marshal + * * @return short representation of the type data structure */ public byte getDataStructureType() { return DataArrayResponse.DATA_STRUCTURE_TYPE; } - + /** * @return a new object instance */ @@ -56,12 +54,13 @@ public class DataArrayResponseMarshaller extends ResponseMarshaller { /** * Un-marshal an object instance from the data input stream - * + * * @param o the object to un-marshal * @param dataIn the data input stream to build the object from * @throws IOException */ - public void tightUnmarshal(OpenWireFormat wireFormat, Object o, DataInput dataIn, BooleanStream bs) throws IOException { + public void tightUnmarshal(OpenWireFormat wireFormat, Object o, DataInput dataIn, BooleanStream bs) + throws IOException { super.tightUnmarshal(wireFormat, o, dataIn, bs); DataArrayResponse info = (DataArrayResponse)o; @@ -69,18 +68,17 @@ public class DataArrayResponseMarshaller extends ResponseMarshaller { if (bs.readBoolean()) { short size = dataIn.readShort(); org.apache.activemq.command.DataStructure value[] = new org.apache.activemq.command.DataStructure[size]; - for( int i=0; i < size; i++ ) { - value[i] = (org.apache.activemq.command.DataStructure) tightUnmarsalNestedObject(wireFormat,dataIn, bs); + for (int i = 0; i < size; i++) { + value[i] = (org.apache.activemq.command.DataStructure)tightUnmarsalNestedObject(wireFormat, + dataIn, bs); } info.setData(value); - } - else { + } else { info.setData(null); } } - /** * Write the booleans that this object uses to a BooleanStream */ @@ -96,12 +94,13 @@ public class DataArrayResponseMarshaller extends ResponseMarshaller { /** * Write a object instance to data output stream - * + * * @param o the instance to be marshaled * @param dataOut the output stream * @throws IOException thrown if an error occurs */ - public void tightMarshal2(OpenWireFormat wireFormat, Object o, DataOutput dataOut, BooleanStream bs) throws IOException { + public void tightMarshal2(OpenWireFormat wireFormat, Object o, DataOutput dataOut, BooleanStream bs) + throws IOException { super.tightMarshal2(wireFormat, o, dataOut, bs); DataArrayResponse info = (DataArrayResponse)o; @@ -111,7 +110,7 @@ public class DataArrayResponseMarshaller extends ResponseMarshaller { /** * Un-marshal an object instance from the data input stream - * + * * @param o the object to un-marshal * @param dataIn the data input stream to build the object from * @throws IOException @@ -124,18 +123,17 @@ public class DataArrayResponseMarshaller extends ResponseMarshaller { if (dataIn.readBoolean()) { short size = dataIn.readShort(); org.apache.activemq.command.DataStructure value[] = new org.apache.activemq.command.DataStructure[size]; - for( int i=0; i < size; i++ ) { - value[i] = (org.apache.activemq.command.DataStructure) looseUnmarsalNestedObject(wireFormat,dataIn); + for (int i = 0; i < size; i++) { + value[i] = (org.apache.activemq.command.DataStructure)looseUnmarsalNestedObject(wireFormat, + dataIn); } info.setData(value); - } - else { + } else { info.setData(null); } } - /** * Write the booleans that this object uses to a BooleanStream */ diff --git a/activemq-core/src/main/java/org/apache/activemq/openwire/v2/DestinationInfoMarshaller.java b/activemq-core/src/main/java/org/apache/activemq/openwire/v2/DestinationInfoMarshaller.java index d85592334f..bdd73721f3 100644 --- a/activemq-core/src/main/java/org/apache/activemq/openwire/v2/DestinationInfoMarshaller.java +++ b/activemq-core/src/main/java/org/apache/activemq/openwire/v2/DestinationInfoMarshaller.java @@ -24,29 +24,27 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - - /** * Marshalling code for Open Wire Format for DestinationInfoMarshaller - * - * - * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * + * + * + * NOTE!: This file is auto generated - do not modify! if you need to make a + * change, please see the modify the groovy scripts in the under src/gram/script + * and then use maven openwire:generate to regenerate this file. + * * @version $Revision$ */ public class DestinationInfoMarshaller extends BaseCommandMarshaller { /** * Return the type of Data Structure we marshal + * * @return short representation of the type data structure */ public byte getDataStructureType() { return DestinationInfo.DATA_STRUCTURE_TYPE; } - + /** * @return a new object instance */ @@ -56,35 +54,40 @@ public class DestinationInfoMarshaller extends BaseCommandMarshaller { /** * Un-marshal an object instance from the data input stream - * + * * @param o the object to un-marshal * @param dataIn the data input stream to build the object from * @throws IOException */ - public void tightUnmarshal(OpenWireFormat wireFormat, Object o, DataInput dataIn, BooleanStream bs) throws IOException { + public void tightUnmarshal(OpenWireFormat wireFormat, Object o, DataInput dataIn, BooleanStream bs) + throws IOException { super.tightUnmarshal(wireFormat, o, dataIn, bs); DestinationInfo info = (DestinationInfo)o; - info.setConnectionId((org.apache.activemq.command.ConnectionId) tightUnmarsalCachedObject(wireFormat, dataIn, bs)); - info.setDestination((org.apache.activemq.command.ActiveMQDestination) tightUnmarsalCachedObject(wireFormat, dataIn, bs)); + info.setConnectionId((org.apache.activemq.command.ConnectionId)tightUnmarsalCachedObject(wireFormat, + dataIn, bs)); + info + .setDestination((org.apache.activemq.command.ActiveMQDestination)tightUnmarsalCachedObject( + wireFormat, + dataIn, + bs)); info.setOperationType(dataIn.readByte()); info.setTimeout(tightUnmarshalLong(wireFormat, dataIn, bs)); if (bs.readBoolean()) { short size = dataIn.readShort(); org.apache.activemq.command.BrokerId value[] = new org.apache.activemq.command.BrokerId[size]; - for( int i=0; i < size; i++ ) { - value[i] = (org.apache.activemq.command.BrokerId) tightUnmarsalNestedObject(wireFormat,dataIn, bs); + for (int i = 0; i < size; i++) { + value[i] = (org.apache.activemq.command.BrokerId)tightUnmarsalNestedObject(wireFormat, + dataIn, bs); } info.setBrokerPath(value); - } - else { + } else { info.setBrokerPath(null); } } - /** * Write the booleans that this object uses to a BooleanStream */ @@ -95,7 +98,7 @@ public class DestinationInfoMarshaller extends BaseCommandMarshaller { int rc = super.tightMarshal1(wireFormat, o, bs); rc += tightMarshalCachedObject1(wireFormat, (DataStructure)info.getConnectionId(), bs); rc += tightMarshalCachedObject1(wireFormat, (DataStructure)info.getDestination(), bs); - rc+=tightMarshalLong1(wireFormat, info.getTimeout(), bs); + rc += tightMarshalLong1(wireFormat, info.getTimeout(), bs); rc += tightMarshalObjectArray1(wireFormat, info.getBrokerPath(), bs); return rc + 1; @@ -103,12 +106,13 @@ public class DestinationInfoMarshaller extends BaseCommandMarshaller { /** * Write a object instance to data output stream - * + * * @param o the instance to be marshaled * @param dataOut the output stream * @throws IOException thrown if an error occurs */ - public void tightMarshal2(OpenWireFormat wireFormat, Object o, DataOutput dataOut, BooleanStream bs) throws IOException { + public void tightMarshal2(OpenWireFormat wireFormat, Object o, DataOutput dataOut, BooleanStream bs) + throws IOException { super.tightMarshal2(wireFormat, o, dataOut, bs); DestinationInfo info = (DestinationInfo)o; @@ -122,7 +126,7 @@ public class DestinationInfoMarshaller extends BaseCommandMarshaller { /** * Un-marshal an object instance from the data input stream - * + * * @param o the object to un-marshal * @param dataIn the data input stream to build the object from * @throws IOException @@ -131,26 +135,28 @@ public class DestinationInfoMarshaller extends BaseCommandMarshaller { super.looseUnmarshal(wireFormat, o, dataIn); DestinationInfo info = (DestinationInfo)o; - info.setConnectionId((org.apache.activemq.command.ConnectionId) looseUnmarsalCachedObject(wireFormat, dataIn)); - info.setDestination((org.apache.activemq.command.ActiveMQDestination) looseUnmarsalCachedObject(wireFormat, dataIn)); + info.setConnectionId((org.apache.activemq.command.ConnectionId)looseUnmarsalCachedObject(wireFormat, + dataIn)); + info + .setDestination((org.apache.activemq.command.ActiveMQDestination)looseUnmarsalCachedObject( + wireFormat, + dataIn)); info.setOperationType(dataIn.readByte()); info.setTimeout(looseUnmarshalLong(wireFormat, dataIn)); if (dataIn.readBoolean()) { short size = dataIn.readShort(); org.apache.activemq.command.BrokerId value[] = new org.apache.activemq.command.BrokerId[size]; - for( int i=0; i < size; i++ ) { - value[i] = (org.apache.activemq.command.BrokerId) looseUnmarsalNestedObject(wireFormat,dataIn); + for (int i = 0; i < size; i++) { + value[i] = (org.apache.activemq.command.BrokerId)looseUnmarsalNestedObject(wireFormat, dataIn); } info.setBrokerPath(value); - } - else { + } else { info.setBrokerPath(null); } } - /** * Write the booleans that this object uses to a BooleanStream */ diff --git a/activemq-core/src/main/java/org/apache/activemq/openwire/v2/MessageIdMarshaller.java b/activemq-core/src/main/java/org/apache/activemq/openwire/v2/MessageIdMarshaller.java index bf7e57e4c5..f2e8c265fd 100644 --- a/activemq-core/src/main/java/org/apache/activemq/openwire/v2/MessageIdMarshaller.java +++ b/activemq-core/src/main/java/org/apache/activemq/openwire/v2/MessageIdMarshaller.java @@ -24,29 +24,27 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - - /** * Marshalling code for Open Wire Format for MessageIdMarshaller - * - * - * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * + * + * + * NOTE!: This file is auto generated - do not modify! if you need to make a + * change, please see the modify the groovy scripts in the under src/gram/script + * and then use maven openwire:generate to regenerate this file. + * * @version $Revision$ */ public class MessageIdMarshaller extends BaseDataStreamMarshaller { /** * Return the type of Data Structure we marshal + * * @return short representation of the type data structure */ public byte getDataStructureType() { return MessageId.DATA_STRUCTURE_TYPE; } - + /** * @return a new object instance */ @@ -56,22 +54,23 @@ public class MessageIdMarshaller extends BaseDataStreamMarshaller { /** * Un-marshal an object instance from the data input stream - * + * * @param o the object to un-marshal * @param dataIn the data input stream to build the object from * @throws IOException */ - public void tightUnmarshal(OpenWireFormat wireFormat, Object o, DataInput dataIn, BooleanStream bs) throws IOException { + public void tightUnmarshal(OpenWireFormat wireFormat, Object o, DataInput dataIn, BooleanStream bs) + throws IOException { super.tightUnmarshal(wireFormat, o, dataIn, bs); MessageId info = (MessageId)o; - info.setProducerId((org.apache.activemq.command.ProducerId) tightUnmarsalCachedObject(wireFormat, dataIn, bs)); + info.setProducerId((org.apache.activemq.command.ProducerId)tightUnmarsalCachedObject(wireFormat, + dataIn, bs)); info.setProducerSequenceId(tightUnmarshalLong(wireFormat, dataIn, bs)); info.setBrokerSequenceId(tightUnmarshalLong(wireFormat, dataIn, bs)); } - /** * Write the booleans that this object uses to a BooleanStream */ @@ -81,20 +80,21 @@ public class MessageIdMarshaller extends BaseDataStreamMarshaller { int rc = super.tightMarshal1(wireFormat, o, bs); rc += tightMarshalCachedObject1(wireFormat, (DataStructure)info.getProducerId(), bs); - rc+=tightMarshalLong1(wireFormat, info.getProducerSequenceId(), bs); - rc+=tightMarshalLong1(wireFormat, info.getBrokerSequenceId(), bs); + rc += tightMarshalLong1(wireFormat, info.getProducerSequenceId(), bs); + rc += tightMarshalLong1(wireFormat, info.getBrokerSequenceId(), bs); return rc + 0; } /** * Write a object instance to data output stream - * + * * @param o the instance to be marshaled * @param dataOut the output stream * @throws IOException thrown if an error occurs */ - public void tightMarshal2(OpenWireFormat wireFormat, Object o, DataOutput dataOut, BooleanStream bs) throws IOException { + public void tightMarshal2(OpenWireFormat wireFormat, Object o, DataOutput dataOut, BooleanStream bs) + throws IOException { super.tightMarshal2(wireFormat, o, dataOut, bs); MessageId info = (MessageId)o; @@ -106,7 +106,7 @@ public class MessageIdMarshaller extends BaseDataStreamMarshaller { /** * Un-marshal an object instance from the data input stream - * + * * @param o the object to un-marshal * @param dataIn the data input stream to build the object from * @throws IOException @@ -115,13 +115,13 @@ public class MessageIdMarshaller extends BaseDataStreamMarshaller { super.looseUnmarshal(wireFormat, o, dataIn); MessageId info = (MessageId)o; - info.setProducerId((org.apache.activemq.command.ProducerId) looseUnmarsalCachedObject(wireFormat, dataIn)); + info.setProducerId((org.apache.activemq.command.ProducerId)looseUnmarsalCachedObject(wireFormat, + dataIn)); info.setProducerSequenceId(looseUnmarshalLong(wireFormat, dataIn)); info.setBrokerSequenceId(looseUnmarshalLong(wireFormat, dataIn)); } - /** * Write the booleans that this object uses to a BooleanStream */ diff --git a/activemq-core/src/main/java/org/apache/activemq/openwire/v2/ProducerIdMarshaller.java b/activemq-core/src/main/java/org/apache/activemq/openwire/v2/ProducerIdMarshaller.java index d93a9c9833..1f3f441e4f 100644 --- a/activemq-core/src/main/java/org/apache/activemq/openwire/v2/ProducerIdMarshaller.java +++ b/activemq-core/src/main/java/org/apache/activemq/openwire/v2/ProducerIdMarshaller.java @@ -24,29 +24,27 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - - /** * Marshalling code for Open Wire Format for ProducerIdMarshaller - * - * - * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * + * + * + * NOTE!: This file is auto generated - do not modify! if you need to make a + * change, please see the modify the groovy scripts in the under src/gram/script + * and then use maven openwire:generate to regenerate this file. + * * @version $Revision$ */ public class ProducerIdMarshaller extends BaseDataStreamMarshaller { /** * Return the type of Data Structure we marshal + * * @return short representation of the type data structure */ public byte getDataStructureType() { return ProducerId.DATA_STRUCTURE_TYPE; } - + /** * @return a new object instance */ @@ -56,12 +54,13 @@ public class ProducerIdMarshaller extends BaseDataStreamMarshaller { /** * Un-marshal an object instance from the data input stream - * + * * @param o the object to un-marshal * @param dataIn the data input stream to build the object from * @throws IOException */ - public void tightUnmarshal(OpenWireFormat wireFormat, Object o, DataInput dataIn, BooleanStream bs) throws IOException { + public void tightUnmarshal(OpenWireFormat wireFormat, Object o, DataInput dataIn, BooleanStream bs) + throws IOException { super.tightUnmarshal(wireFormat, o, dataIn, bs); ProducerId info = (ProducerId)o; @@ -71,7 +70,6 @@ public class ProducerIdMarshaller extends BaseDataStreamMarshaller { } - /** * Write the booleans that this object uses to a BooleanStream */ @@ -81,20 +79,21 @@ public class ProducerIdMarshaller extends BaseDataStreamMarshaller { int rc = super.tightMarshal1(wireFormat, o, bs); rc += tightMarshalString1(info.getConnectionId(), bs); - rc+=tightMarshalLong1(wireFormat, info.getValue(), bs); - rc+=tightMarshalLong1(wireFormat, info.getSessionId(), bs); + rc += tightMarshalLong1(wireFormat, info.getValue(), bs); + rc += tightMarshalLong1(wireFormat, info.getSessionId(), bs); return rc + 0; } /** * Write a object instance to data output stream - * + * * @param o the instance to be marshaled * @param dataOut the output stream * @throws IOException thrown if an error occurs */ - public void tightMarshal2(OpenWireFormat wireFormat, Object o, DataOutput dataOut, BooleanStream bs) throws IOException { + public void tightMarshal2(OpenWireFormat wireFormat, Object o, DataOutput dataOut, BooleanStream bs) + throws IOException { super.tightMarshal2(wireFormat, o, dataOut, bs); ProducerId info = (ProducerId)o; @@ -106,7 +105,7 @@ public class ProducerIdMarshaller extends BaseDataStreamMarshaller { /** * Un-marshal an object instance from the data input stream - * + * * @param o the object to un-marshal * @param dataIn the data input stream to build the object from * @throws IOException @@ -121,7 +120,6 @@ public class ProducerIdMarshaller extends BaseDataStreamMarshaller { } - /** * Write the booleans that this object uses to a BooleanStream */ diff --git a/activemq-core/src/main/java/org/apache/activemq/openwire/v2/SessionIdMarshaller.java b/activemq-core/src/main/java/org/apache/activemq/openwire/v2/SessionIdMarshaller.java index fc448e3183..007d2700f9 100644 --- a/activemq-core/src/main/java/org/apache/activemq/openwire/v2/SessionIdMarshaller.java +++ b/activemq-core/src/main/java/org/apache/activemq/openwire/v2/SessionIdMarshaller.java @@ -24,29 +24,27 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - - /** * Marshalling code for Open Wire Format for SessionIdMarshaller - * - * - * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * + * + * + * NOTE!: This file is auto generated - do not modify! if you need to make a + * change, please see the modify the groovy scripts in the under src/gram/script + * and then use maven openwire:generate to regenerate this file. + * * @version $Revision$ */ public class SessionIdMarshaller extends BaseDataStreamMarshaller { /** * Return the type of Data Structure we marshal + * * @return short representation of the type data structure */ public byte getDataStructureType() { return SessionId.DATA_STRUCTURE_TYPE; } - + /** * @return a new object instance */ @@ -56,12 +54,13 @@ public class SessionIdMarshaller extends BaseDataStreamMarshaller { /** * Un-marshal an object instance from the data input stream - * + * * @param o the object to un-marshal * @param dataIn the data input stream to build the object from * @throws IOException */ - public void tightUnmarshal(OpenWireFormat wireFormat, Object o, DataInput dataIn, BooleanStream bs) throws IOException { + public void tightUnmarshal(OpenWireFormat wireFormat, Object o, DataInput dataIn, BooleanStream bs) + throws IOException { super.tightUnmarshal(wireFormat, o, dataIn, bs); SessionId info = (SessionId)o; @@ -70,7 +69,6 @@ public class SessionIdMarshaller extends BaseDataStreamMarshaller { } - /** * Write the booleans that this object uses to a BooleanStream */ @@ -80,19 +78,20 @@ public class SessionIdMarshaller extends BaseDataStreamMarshaller { int rc = super.tightMarshal1(wireFormat, o, bs); rc += tightMarshalString1(info.getConnectionId(), bs); - rc+=tightMarshalLong1(wireFormat, info.getValue(), bs); + rc += tightMarshalLong1(wireFormat, info.getValue(), bs); return rc + 0; } /** * Write a object instance to data output stream - * + * * @param o the instance to be marshaled * @param dataOut the output stream * @throws IOException thrown if an error occurs */ - public void tightMarshal2(OpenWireFormat wireFormat, Object o, DataOutput dataOut, BooleanStream bs) throws IOException { + public void tightMarshal2(OpenWireFormat wireFormat, Object o, DataOutput dataOut, BooleanStream bs) + throws IOException { super.tightMarshal2(wireFormat, o, dataOut, bs); SessionId info = (SessionId)o; @@ -103,7 +102,7 @@ public class SessionIdMarshaller extends BaseDataStreamMarshaller { /** * Un-marshal an object instance from the data input stream - * + * * @param o the object to un-marshal * @param dataIn the data input stream to build the object from * @throws IOException @@ -117,7 +116,6 @@ public class SessionIdMarshaller extends BaseDataStreamMarshaller { } - /** * Write the booleans that this object uses to a BooleanStream */ diff --git a/activemq-core/src/main/java/org/apache/activemq/openwire/v3/BaseDataStreamMarshaller.java b/activemq-core/src/main/java/org/apache/activemq/openwire/v3/BaseDataStreamMarshaller.java index 54b82204a4..2dced88684 100644 --- a/activemq-core/src/main/java/org/apache/activemq/openwire/v3/BaseDataStreamMarshaller.java +++ b/activemq-core/src/main/java/org/apache/activemq/openwire/v3/BaseDataStreamMarshaller.java @@ -33,36 +33,38 @@ abstract public class BaseDataStreamMarshaller implements DataStreamMarshaller { static final public Constructor STACK_TRACE_ELEMENT_CONSTRUCTOR; static { - Constructor constructor=null; + Constructor constructor = null; try { - constructor = StackTraceElement.class.getConstructor(new Class[]{String.class, String.class, String.class, int.class}); + constructor = StackTraceElement.class.getConstructor(new Class[] {String.class, String.class, String.class, int.class}); } catch (Throwable e) { } STACK_TRACE_ELEMENT_CONSTRUCTOR = constructor; } - abstract public byte getDataStructureType(); + abstract public DataStructure createObject(); public int tightMarshal1(OpenWireFormat wireFormat, Object o, BooleanStream bs) throws IOException { return 0; } + public void tightMarshal2(OpenWireFormat wireFormat, Object o, DataOutput dataOut, BooleanStream bs) throws IOException { } + public void tightUnmarshal(OpenWireFormat wireFormat, Object o, DataInput dataIn, BooleanStream bs) throws IOException { } public int tightMarshalLong1(OpenWireFormat wireFormat, long o, BooleanStream bs) throws IOException { - if( o == 0 ) { + if (o == 0) { bs.writeBoolean(false); bs.writeBoolean(false); return 0; - } else if ( (o & 0xFFFFFFFFFFFF0000l ) == 0 ) { + } else if ((o & 0xFFFFFFFFFFFF0000l) == 0) { bs.writeBoolean(false); bs.writeBoolean(true); return 2; - } else if ( (o & 0xFFFFFFFF00000000l ) == 0) { + } else if ((o & 0xFFFFFFFF00000000l) == 0) { bs.writeBoolean(true); bs.writeBoolean(false); return 4; @@ -72,28 +74,30 @@ abstract public class BaseDataStreamMarshaller implements DataStreamMarshaller { return 8; } } + public void tightMarshalLong2(OpenWireFormat wireFormat, long o, DataOutput dataOut, BooleanStream bs) throws IOException { - if( bs.readBoolean() ) { - if( bs.readBoolean() ) { + if (bs.readBoolean()) { + if (bs.readBoolean()) { dataOut.writeLong(o); } else { - dataOut.writeInt((int) o); + dataOut.writeInt((int)o); } } else { - if( bs.readBoolean() ) { - dataOut.writeShort((int) o); + if (bs.readBoolean()) { + dataOut.writeShort((int)o); } } } + public long tightUnmarshalLong(OpenWireFormat wireFormat, DataInput dataIn, BooleanStream bs) throws IOException { - if( bs.readBoolean() ) { - if( bs.readBoolean() ) { + if (bs.readBoolean()) { + if (bs.readBoolean()) { return dataIn.readLong(); } else { return toLong(dataIn.readInt()); } } else { - if( bs.readBoolean() ) { + if (bs.readBoolean()) { return toLong(dataIn.readShort()); } else { return 0; @@ -116,6 +120,7 @@ abstract public class BaseDataStreamMarshaller implements DataStreamMarshaller { protected DataStructure tightUnmarsalNestedObject(OpenWireFormat wireFormat, DataInput dataIn, BooleanStream bs) throws IOException { return wireFormat.tightUnmarshalNestedObject(dataIn, bs); } + protected int tightMarshalNestedObject1(OpenWireFormat wireFormat, DataStructure o, BooleanStream bs) throws IOException { return wireFormat.tightMarshalNestedObject1(o, bs); } @@ -125,8 +130,8 @@ abstract public class BaseDataStreamMarshaller implements DataStreamMarshaller { } protected DataStructure tightUnmarsalCachedObject(OpenWireFormat wireFormat, DataInput dataIn, BooleanStream bs) throws IOException { - if( wireFormat.isCacheEnabled() ) { - if( bs.readBoolean() ) { + if (wireFormat.isCacheEnabled()) { + if (bs.readBoolean()) { short index = dataIn.readShort(); DataStructure object = wireFormat.tightUnmarshalNestedObject(dataIn, bs); wireFormat.setInUnmarshallCache(index, object); @@ -139,14 +144,15 @@ abstract public class BaseDataStreamMarshaller implements DataStreamMarshaller { return wireFormat.tightUnmarshalNestedObject(dataIn, bs); } } + protected int tightMarshalCachedObject1(OpenWireFormat wireFormat, DataStructure o, BooleanStream bs) throws IOException { - if( wireFormat.isCacheEnabled() ) { + if (wireFormat.isCacheEnabled()) { Short index = wireFormat.getMarshallCacheIndex(o); bs.writeBoolean(index == null); - if( index == null ) { + if (index == null) { int rc = wireFormat.tightMarshalNestedObject1(o, bs); wireFormat.addToMarshallCache(o); - return 2+rc; + return 2 + rc; } else { return 2; } @@ -154,10 +160,11 @@ abstract public class BaseDataStreamMarshaller implements DataStreamMarshaller { return wireFormat.tightMarshalNestedObject1(o, bs); } } + protected void tightMarshalCachedObject2(OpenWireFormat wireFormat, DataStructure o, DataOutput dataOut, BooleanStream bs) throws IOException { - if( wireFormat.isCacheEnabled() ) { + if (wireFormat.isCacheEnabled()) { Short index = wireFormat.getMarshallCacheIndex(o); - if( bs.readBoolean() ) { + if (bs.readBoolean()) { dataOut.writeShort(index.shortValue()); wireFormat.tightMarshalNestedObject2(o, dataOut, bs); } else { @@ -169,21 +176,19 @@ abstract public class BaseDataStreamMarshaller implements DataStreamMarshaller { } protected Throwable tightUnmarsalThrowable(OpenWireFormat wireFormat, DataInput dataIn, BooleanStream bs) throws IOException { - if( bs.readBoolean() ) { - String clazz = tightUnmarshalString(dataIn, bs); + if (bs.readBoolean()) { + String clazz = tightUnmarshalString(dataIn, bs); String message = tightUnmarshalString(dataIn, bs); Throwable o = createThrowable(clazz, message); - if( wireFormat.isStackTraceEnabled() ) { - if( STACK_TRACE_ELEMENT_CONSTRUCTOR !=null) { + if (wireFormat.isStackTraceEnabled()) { + if (STACK_TRACE_ELEMENT_CONSTRUCTOR != null) { StackTraceElement ss[] = new StackTraceElement[dataIn.readShort()]; for (int i = 0; i < ss.length; i++) { try { - ss[i] = (StackTraceElement) STACK_TRACE_ELEMENT_CONSTRUCTOR.newInstance(new Object[]{ - tightUnmarshalString(dataIn, bs), - tightUnmarshalString(dataIn, bs), - tightUnmarshalString(dataIn, bs), - Integer.valueOf(dataIn.readInt()) - }); + ss[i] = (StackTraceElement)STACK_TRACE_ELEMENT_CONSTRUCTOR.newInstance(new Object[] {tightUnmarshalString(dataIn, bs), + tightUnmarshalString(dataIn, bs), + tightUnmarshalString(dataIn, bs), + Integer.valueOf(dataIn.readInt())}); } catch (IOException e) { throw e; } catch (Throwable e) { @@ -211,23 +216,23 @@ abstract public class BaseDataStreamMarshaller implements DataStreamMarshaller { private Throwable createThrowable(String className, String message) { try { Class clazz = ClassLoading.loadClass(className, BaseDataStreamMarshaller.class.getClassLoader()); - Constructor constructor = clazz.getConstructor(new Class[]{String.class}); - return (Throwable) constructor.newInstance(new Object[]{message}); + Constructor constructor = clazz.getConstructor(new Class[] {String.class}); + return (Throwable)constructor.newInstance(new Object[] {message}); } catch (Throwable e) { - return new Throwable(className+": "+message); + return new Throwable(className + ": " + message); } } protected int tightMarshalThrowable1(OpenWireFormat wireFormat, Throwable o, BooleanStream bs) throws IOException { - if( o==null ) { + if (o == null) { bs.writeBoolean(false); return 0; } else { - int rc=0; + int rc = 0; bs.writeBoolean(true); rc += tightMarshalString1(o.getClass().getName(), bs); rc += tightMarshalString1(o.getMessage(), bs); - if( wireFormat.isStackTraceEnabled() ) { + if (wireFormat.isStackTraceEnabled()) { rc += 2; StackTraceElement[] stackTrace = o.getStackTrace(); for (int i = 0; i < stackTrace.length; i++) { @@ -244,10 +249,10 @@ abstract public class BaseDataStreamMarshaller implements DataStreamMarshaller { } protected void tightMarshalThrowable2(OpenWireFormat wireFormat, Throwable o, DataOutput dataOut, BooleanStream bs) throws IOException { - if( bs.readBoolean() ) { + if (bs.readBoolean()) { tightMarshalString2(o.getClass().getName(), dataOut, bs); tightMarshalString2(o.getMessage(), dataOut, bs); - if( wireFormat.isStackTraceEnabled() ) { + if (wireFormat.isStackTraceEnabled()) { StackTraceElement[] stackTrace = o.getStackTrace(); dataOut.writeShort(stackTrace.length); for (int i = 0; i < stackTrace.length; i++) { @@ -263,13 +268,14 @@ abstract public class BaseDataStreamMarshaller implements DataStreamMarshaller { } protected String tightUnmarshalString(DataInput dataIn, BooleanStream bs) throws IOException { - if( bs.readBoolean() ) { - if( bs.readBoolean() ) { + if (bs.readBoolean()) { + if (bs.readBoolean()) { int size = dataIn.readShort(); byte data[] = new byte[size]; dataIn.readFully(data); - return new String(data,0); // Yes deprecated, but we know what we are doing. - } else { + return new String(data, 0); // Yes deprecated, but we know what + // we are doing. + } else { return dataIn.readUTF(); } } else { @@ -278,14 +284,14 @@ abstract public class BaseDataStreamMarshaller implements DataStreamMarshaller { } protected int tightMarshalString1(String value, BooleanStream bs) throws IOException { - bs.writeBoolean(value!=null); - if( value!=null ) { + bs.writeBoolean(value != null); + if (value != null) { int strlen = value.length(); int utflen = 0; char[] charr = new char[strlen]; int c, count = 0; - boolean isOnlyAscii=true; + boolean isOnlyAscii = true; value.getChars(0, strlen, charr, 0); @@ -295,18 +301,18 @@ abstract public class BaseDataStreamMarshaller implements DataStreamMarshaller { utflen++; } else if (c > 0x07FF) { utflen += 3; - isOnlyAscii=false; + isOnlyAscii = false; } else { - isOnlyAscii=false; + isOnlyAscii = false; utflen += 2; } } - if( utflen >= Short.MAX_VALUE ) + if (utflen >= Short.MAX_VALUE) { throw new IOException("Encountered a String value that is too long to encode."); - + } bs.writeBoolean(isOnlyAscii); - return utflen+2; + return utflen + 2; } else { return 0; @@ -314,9 +320,9 @@ abstract public class BaseDataStreamMarshaller implements DataStreamMarshaller { } protected void tightMarshalString2(String value, DataOutput dataOut, BooleanStream bs) throws IOException { - if( bs.readBoolean() ) { + if (bs.readBoolean()) { // If we verified it only holds ascii values - if( bs.readBoolean() ) { + if (bs.readBoolean()) { dataOut.writeShort(value.length()); dataOut.writeBytes(value); } else { @@ -326,12 +332,12 @@ abstract public class BaseDataStreamMarshaller implements DataStreamMarshaller { } protected int tightMarshalObjectArray1(OpenWireFormat wireFormat, DataStructure[] objects, BooleanStream bs) throws IOException { - if( objects != null ) { - int rc=0; + if (objects != null) { + int rc = 0; bs.writeBoolean(true); rc += 2; - for( int i=0; i < objects.length; i++ ) { - rc += tightMarshalNestedObject1(wireFormat,objects[i], bs); + for (int i = 0; i < objects.length; i++) { + rc += tightMarshalNestedObject1(wireFormat, objects[i], bs); } return rc; } else { @@ -341,10 +347,10 @@ abstract public class BaseDataStreamMarshaller implements DataStreamMarshaller { } protected void tightMarshalObjectArray2(OpenWireFormat wireFormat, DataStructure[] objects, DataOutput dataOut, BooleanStream bs) throws IOException { - if( bs.readBoolean() ) { + if (bs.readBoolean()) { dataOut.writeShort(objects.length); - for( int i=0; i < objects.length; i++ ) { - tightMarshalNestedObject2(wireFormat,objects[i], dataOut, bs); + for (int i = 0; i < objects.length; i++) { + tightMarshalNestedObject2(wireFormat, objects[i], dataOut, bs); } } } @@ -352,6 +358,7 @@ abstract public class BaseDataStreamMarshaller implements DataStreamMarshaller { protected int tightMarshalConstByteArray1(byte[] data, BooleanStream bs, int i) throws IOException { return i; } + protected void tightMarshalConstByteArray2(byte[] data, DataOutput dataOut, BooleanStream bs, int i) throws IOException { dataOut.write(data, 0, i); } @@ -363,24 +370,24 @@ abstract public class BaseDataStreamMarshaller implements DataStreamMarshaller { } protected int tightMarshalByteArray1(byte[] data, BooleanStream bs) throws IOException { - bs.writeBoolean(data!=null); - if( data!=null ){ - return data.length+4; + bs.writeBoolean(data != null); + if (data != null) { + return data.length + 4; } else { return 0; } } protected void tightMarshalByteArray2(byte[] data, DataOutput dataOut, BooleanStream bs) throws IOException { - if( bs.readBoolean() ){ + if (bs.readBoolean()) { dataOut.writeInt(data.length); dataOut.write(data); } } protected byte[] tightUnmarshalByteArray(DataInput dataIn, BooleanStream bs) throws IOException { - byte rc[]=null; - if( bs.readBoolean() ) { + byte rc[] = null; + if (bs.readBoolean()) { int size = dataIn.readInt(); rc = new byte[size]; dataIn.readFully(rc); @@ -389,24 +396,24 @@ abstract public class BaseDataStreamMarshaller implements DataStreamMarshaller { } protected int tightMarshalByteSequence1(ByteSequence data, BooleanStream bs) throws IOException { - bs.writeBoolean(data!=null); - if( data!=null ){ - return data.getLength()+4; + bs.writeBoolean(data != null); + if (data != null) { + return data.getLength() + 4; } else { return 0; } } protected void tightMarshalByteSequence2(ByteSequence data, DataOutput dataOut, BooleanStream bs) throws IOException { - if( bs.readBoolean() ){ + if (bs.readBoolean()) { dataOut.writeInt(data.getLength()); dataOut.write(data.getData(), data.getOffset(), data.getLength()); } } protected ByteSequence tightUnmarshalByteSequence(DataInput dataIn, BooleanStream bs) throws IOException { - ByteSequence rc=null; - if( bs.readBoolean() ) { + ByteSequence rc = null; + if (bs.readBoolean()) { int size = dataIn.readInt(); byte[] t = new byte[size]; dataIn.readFully(t); @@ -421,12 +428,14 @@ abstract public class BaseDataStreamMarshaller implements DataStreamMarshaller { public void looseMarshal(OpenWireFormat wireFormat, Object o, DataOutput dataOut) throws IOException { } + public void looseUnmarshal(OpenWireFormat wireFormat, Object o, DataInput dataIn) throws IOException { } public void looseMarshalLong(OpenWireFormat wireFormat, long o, DataOutput dataOut) throws IOException { dataOut.writeLong(o); } + public long looseUnmarshalLong(OpenWireFormat wireFormat, DataInput dataIn) throws IOException { return dataIn.readLong(); } @@ -434,13 +443,14 @@ abstract public class BaseDataStreamMarshaller implements DataStreamMarshaller { protected DataStructure looseUnmarsalNestedObject(OpenWireFormat wireFormat, DataInput dataIn) throws IOException { return wireFormat.looseUnmarshalNestedObject(dataIn); } + protected void looseMarshalNestedObject(OpenWireFormat wireFormat, DataStructure o, DataOutput dataOut) throws IOException { wireFormat.looseMarshalNestedObject(o, dataOut); } protected DataStructure looseUnmarsalCachedObject(OpenWireFormat wireFormat, DataInput dataIn) throws IOException { - if( wireFormat.isCacheEnabled() ) { - if( dataIn.readBoolean() ) { + if (wireFormat.isCacheEnabled()) { + if (dataIn.readBoolean()) { short index = dataIn.readShort(); DataStructure object = wireFormat.looseUnmarshalNestedObject(dataIn); wireFormat.setInUnmarshallCache(index, object); @@ -453,11 +463,12 @@ abstract public class BaseDataStreamMarshaller implements DataStreamMarshaller { return wireFormat.looseUnmarshalNestedObject(dataIn); } } + protected void looseMarshalCachedObject(OpenWireFormat wireFormat, DataStructure o, DataOutput dataOut) throws IOException { - if( wireFormat.isCacheEnabled() ) { + if (wireFormat.isCacheEnabled()) { Short index = wireFormat.getMarshallCacheIndex(o); dataOut.writeBoolean(index == null); - if( index == null ) { + if (index == null) { index = wireFormat.addToMarshallCache(o); dataOut.writeShort(index.shortValue()); wireFormat.looseMarshalNestedObject(o, dataOut); @@ -470,21 +481,17 @@ abstract public class BaseDataStreamMarshaller implements DataStreamMarshaller { } protected Throwable looseUnmarsalThrowable(OpenWireFormat wireFormat, DataInput dataIn) throws IOException { - if( dataIn.readBoolean() ) { - String clazz = looseUnmarshalString(dataIn); + if (dataIn.readBoolean()) { + String clazz = looseUnmarshalString(dataIn); String message = looseUnmarshalString(dataIn); Throwable o = createThrowable(clazz, message); - if( wireFormat.isStackTraceEnabled() ) { - if( STACK_TRACE_ELEMENT_CONSTRUCTOR !=null) { + if (wireFormat.isStackTraceEnabled()) { + if (STACK_TRACE_ELEMENT_CONSTRUCTOR != null) { StackTraceElement ss[] = new StackTraceElement[dataIn.readShort()]; for (int i = 0; i < ss.length; i++) { try { - ss[i] = (StackTraceElement) STACK_TRACE_ELEMENT_CONSTRUCTOR.newInstance(new Object[]{ - looseUnmarshalString(dataIn), - looseUnmarshalString(dataIn), - looseUnmarshalString(dataIn), - Integer.valueOf(dataIn.readInt()) - }); + ss[i] = (StackTraceElement)STACK_TRACE_ELEMENT_CONSTRUCTOR.newInstance(new Object[] {looseUnmarshalString(dataIn), looseUnmarshalString(dataIn), + looseUnmarshalString(dataIn), Integer.valueOf(dataIn.readInt())}); } catch (IOException e) { throw e; } catch (Throwable e) { @@ -509,13 +516,12 @@ abstract public class BaseDataStreamMarshaller implements DataStreamMarshaller { } } - protected void looseMarshalThrowable(OpenWireFormat wireFormat, Throwable o, DataOutput dataOut) throws IOException { - dataOut.writeBoolean(o!=null); - if( o!=null ) { + dataOut.writeBoolean(o != null); + if (o != null) { looseMarshalString(o.getClass().getName(), dataOut); looseMarshalString(o.getMessage(), dataOut); - if( wireFormat.isStackTraceEnabled() ) { + if (wireFormat.isStackTraceEnabled()) { StackTraceElement[] stackTrace = o.getStackTrace(); dataOut.writeShort(stackTrace.length); for (int i = 0; i < stackTrace.length; i++) { @@ -531,7 +537,7 @@ abstract public class BaseDataStreamMarshaller implements DataStreamMarshaller { } protected String looseUnmarshalString(DataInput dataIn) throws IOException { - if( dataIn.readBoolean() ) { + if (dataIn.readBoolean()) { return dataIn.readUTF(); } else { return null; @@ -539,18 +545,18 @@ abstract public class BaseDataStreamMarshaller implements DataStreamMarshaller { } protected void looseMarshalString(String value, DataOutput dataOut) throws IOException { - dataOut.writeBoolean(value!=null); - if( value!=null ) { + dataOut.writeBoolean(value != null); + if (value != null) { dataOut.writeUTF(value); } } protected void looseMarshalObjectArray(OpenWireFormat wireFormat, DataStructure[] objects, DataOutput dataOut) throws IOException { - dataOut.writeBoolean(objects!=null); - if( objects!=null ) { + dataOut.writeBoolean(objects != null); + if (objects != null) { dataOut.writeShort(objects.length); - for( int i=0; i < objects.length; i++ ) { - looseMarshalNestedObject(wireFormat,objects[i], dataOut); + for (int i = 0; i < objects.length; i++) { + looseMarshalNestedObject(wireFormat, objects[i], dataOut); } } } @@ -566,16 +572,16 @@ abstract public class BaseDataStreamMarshaller implements DataStreamMarshaller { } protected void looseMarshalByteArray(OpenWireFormat wireFormat, byte[] data, DataOutput dataOut) throws IOException { - dataOut.writeBoolean(data!=null); - if( data!=null ){ + dataOut.writeBoolean(data != null); + if (data != null) { dataOut.writeInt(data.length); dataOut.write(data); } } protected byte[] looseUnmarshalByteArray(DataInput dataIn) throws IOException { - byte rc[]=null; - if( dataIn.readBoolean() ) { + byte rc[] = null; + if (dataIn.readBoolean()) { int size = dataIn.readInt(); rc = new byte[size]; dataIn.readFully(rc); @@ -584,16 +590,16 @@ abstract public class BaseDataStreamMarshaller implements DataStreamMarshaller { } protected void looseMarshalByteSequence(OpenWireFormat wireFormat, ByteSequence data, DataOutput dataOut) throws IOException { - dataOut.writeBoolean(data!=null); - if( data!=null ){ + dataOut.writeBoolean(data != null); + if (data != null) { dataOut.writeInt(data.getLength()); dataOut.write(data.getData(), data.getOffset(), data.getLength()); } } protected ByteSequence looseUnmarshalByteSequence(DataInput dataIn) throws IOException { - ByteSequence rc=null; - if( dataIn.readBoolean() ) { + ByteSequence rc = null; + if (dataIn.readBoolean()) { int size = dataIn.readInt(); byte[] t = new byte[size]; dataIn.readFully(t); diff --git a/activemq-core/src/main/java/org/apache/activemq/openwire/v3/BrokerInfoMarshaller.java b/activemq-core/src/main/java/org/apache/activemq/openwire/v3/BrokerInfoMarshaller.java index 437cddde95..31b3ac5954 100644 --- a/activemq-core/src/main/java/org/apache/activemq/openwire/v3/BrokerInfoMarshaller.java +++ b/activemq-core/src/main/java/org/apache/activemq/openwire/v3/BrokerInfoMarshaller.java @@ -24,29 +24,27 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - - /** * Marshalling code for Open Wire Format for BrokerInfoMarshaller - * - * - * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * + * + * + * NOTE!: This file is auto generated - do not modify! if you need to make a + * change, please see the modify the groovy scripts in the under src/gram/script + * and then use maven openwire:generate to regenerate this file. + * * @version $Revision$ */ public class BrokerInfoMarshaller extends BaseCommandMarshaller { /** * Return the type of Data Structure we marshal + * * @return short representation of the type data structure */ public byte getDataStructureType() { return BrokerInfo.DATA_STRUCTURE_TYPE; } - + /** * @return a new object instance */ @@ -56,27 +54,29 @@ public class BrokerInfoMarshaller extends BaseCommandMarshaller { /** * Un-marshal an object instance from the data input stream - * + * * @param o the object to un-marshal * @param dataIn the data input stream to build the object from * @throws IOException */ - public void tightUnmarshal(OpenWireFormat wireFormat, Object o, DataInput dataIn, BooleanStream bs) throws IOException { + public void tightUnmarshal(OpenWireFormat wireFormat, Object o, DataInput dataIn, BooleanStream bs) + throws IOException { super.tightUnmarshal(wireFormat, o, dataIn, bs); BrokerInfo info = (BrokerInfo)o; - info.setBrokerId((org.apache.activemq.command.BrokerId) tightUnmarsalCachedObject(wireFormat, dataIn, bs)); + info.setBrokerId((org.apache.activemq.command.BrokerId)tightUnmarsalCachedObject(wireFormat, dataIn, + bs)); info.setBrokerURL(tightUnmarshalString(dataIn, bs)); if (bs.readBoolean()) { short size = dataIn.readShort(); org.apache.activemq.command.BrokerInfo value[] = new org.apache.activemq.command.BrokerInfo[size]; - for( int i=0; i < size; i++ ) { - value[i] = (org.apache.activemq.command.BrokerInfo) tightUnmarsalNestedObject(wireFormat,dataIn, bs); + for (int i = 0; i < size; i++) { + value[i] = (org.apache.activemq.command.BrokerInfo)tightUnmarsalNestedObject(wireFormat, + dataIn, bs); } info.setPeerBrokerInfos(value); - } - else { + } else { info.setPeerBrokerInfos(null); } info.setBrokerName(tightUnmarshalString(dataIn, bs)); @@ -91,7 +91,6 @@ public class BrokerInfoMarshaller extends BaseCommandMarshaller { } - /** * Write the booleans that this object uses to a BooleanStream */ @@ -109,7 +108,7 @@ public class BrokerInfoMarshaller extends BaseCommandMarshaller { bs.writeBoolean(info.isFaultTolerantConfiguration()); bs.writeBoolean(info.isDuplexConnection()); bs.writeBoolean(info.isNetworkConnection()); - rc+=tightMarshalLong1(wireFormat, info.getConnectionId(), bs); + rc += tightMarshalLong1(wireFormat, info.getConnectionId(), bs); rc += tightMarshalString1(info.getBrokerUploadUrl(), bs); rc += tightMarshalString1(info.getNetworkProperties(), bs); @@ -118,12 +117,13 @@ public class BrokerInfoMarshaller extends BaseCommandMarshaller { /** * Write a object instance to data output stream - * + * * @param o the instance to be marshaled * @param dataOut the output stream * @throws IOException thrown if an error occurs */ - public void tightMarshal2(OpenWireFormat wireFormat, Object o, DataOutput dataOut, BooleanStream bs) throws IOException { + public void tightMarshal2(OpenWireFormat wireFormat, Object o, DataOutput dataOut, BooleanStream bs) + throws IOException { super.tightMarshal2(wireFormat, o, dataOut, bs); BrokerInfo info = (BrokerInfo)o; @@ -144,7 +144,7 @@ public class BrokerInfoMarshaller extends BaseCommandMarshaller { /** * Un-marshal an object instance from the data input stream - * + * * @param o the object to un-marshal * @param dataIn the data input stream to build the object from * @throws IOException @@ -153,18 +153,18 @@ public class BrokerInfoMarshaller extends BaseCommandMarshaller { super.looseUnmarshal(wireFormat, o, dataIn); BrokerInfo info = (BrokerInfo)o; - info.setBrokerId((org.apache.activemq.command.BrokerId) looseUnmarsalCachedObject(wireFormat, dataIn)); + info.setBrokerId((org.apache.activemq.command.BrokerId)looseUnmarsalCachedObject(wireFormat, dataIn)); info.setBrokerURL(looseUnmarshalString(dataIn)); if (dataIn.readBoolean()) { short size = dataIn.readShort(); org.apache.activemq.command.BrokerInfo value[] = new org.apache.activemq.command.BrokerInfo[size]; - for( int i=0; i < size; i++ ) { - value[i] = (org.apache.activemq.command.BrokerInfo) looseUnmarsalNestedObject(wireFormat,dataIn); + for (int i = 0; i < size; i++) { + value[i] = (org.apache.activemq.command.BrokerInfo)looseUnmarsalNestedObject(wireFormat, + dataIn); } info.setPeerBrokerInfos(value); - } - else { + } else { info.setPeerBrokerInfos(null); } info.setBrokerName(looseUnmarshalString(dataIn)); @@ -179,7 +179,6 @@ public class BrokerInfoMarshaller extends BaseCommandMarshaller { } - /** * Write the booleans that this object uses to a BooleanStream */ diff --git a/activemq-core/src/main/java/org/apache/activemq/openwire/v3/ConnectionInfoMarshaller.java b/activemq-core/src/main/java/org/apache/activemq/openwire/v3/ConnectionInfoMarshaller.java index 533245b40c..9449fce5f0 100644 --- a/activemq-core/src/main/java/org/apache/activemq/openwire/v3/ConnectionInfoMarshaller.java +++ b/activemq-core/src/main/java/org/apache/activemq/openwire/v3/ConnectionInfoMarshaller.java @@ -24,29 +24,27 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - - /** * Marshalling code for Open Wire Format for ConnectionInfoMarshaller - * - * - * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * + * + * + * NOTE!: This file is auto generated - do not modify! if you need to make a + * change, please see the modify the groovy scripts in the under src/gram/script + * and then use maven openwire:generate to regenerate this file. + * * @version $Revision$ */ public class ConnectionInfoMarshaller extends BaseCommandMarshaller { /** * Return the type of Data Structure we marshal + * * @return short representation of the type data structure */ public byte getDataStructureType() { return ConnectionInfo.DATA_STRUCTURE_TYPE; } - + /** * @return a new object instance */ @@ -56,16 +54,18 @@ public class ConnectionInfoMarshaller extends BaseCommandMarshaller { /** * Un-marshal an object instance from the data input stream - * + * * @param o the object to un-marshal * @param dataIn the data input stream to build the object from * @throws IOException */ - public void tightUnmarshal(OpenWireFormat wireFormat, Object o, DataInput dataIn, BooleanStream bs) throws IOException { + public void tightUnmarshal(OpenWireFormat wireFormat, Object o, DataInput dataIn, BooleanStream bs) + throws IOException { super.tightUnmarshal(wireFormat, o, dataIn, bs); ConnectionInfo info = (ConnectionInfo)o; - info.setConnectionId((org.apache.activemq.command.ConnectionId) tightUnmarsalCachedObject(wireFormat, dataIn, bs)); + info.setConnectionId((org.apache.activemq.command.ConnectionId)tightUnmarsalCachedObject(wireFormat, + dataIn, bs)); info.setClientId(tightUnmarshalString(dataIn, bs)); info.setPassword(tightUnmarshalString(dataIn, bs)); info.setUserName(tightUnmarshalString(dataIn, bs)); @@ -73,12 +73,12 @@ public class ConnectionInfoMarshaller extends BaseCommandMarshaller { if (bs.readBoolean()) { short size = dataIn.readShort(); org.apache.activemq.command.BrokerId value[] = new org.apache.activemq.command.BrokerId[size]; - for( int i=0; i < size; i++ ) { - value[i] = (org.apache.activemq.command.BrokerId) tightUnmarsalNestedObject(wireFormat,dataIn, bs); + for (int i = 0; i < size; i++) { + value[i] = (org.apache.activemq.command.BrokerId)tightUnmarsalNestedObject(wireFormat, + dataIn, bs); } info.setBrokerPath(value); - } - else { + } else { info.setBrokerPath(null); } info.setBrokerMasterConnector(bs.readBoolean()); @@ -87,7 +87,6 @@ public class ConnectionInfoMarshaller extends BaseCommandMarshaller { } - /** * Write the booleans that this object uses to a BooleanStream */ @@ -110,12 +109,13 @@ public class ConnectionInfoMarshaller extends BaseCommandMarshaller { /** * Write a object instance to data output stream - * + * * @param o the instance to be marshaled * @param dataOut the output stream * @throws IOException thrown if an error occurs */ - public void tightMarshal2(OpenWireFormat wireFormat, Object o, DataOutput dataOut, BooleanStream bs) throws IOException { + public void tightMarshal2(OpenWireFormat wireFormat, Object o, DataOutput dataOut, BooleanStream bs) + throws IOException { super.tightMarshal2(wireFormat, o, dataOut, bs); ConnectionInfo info = (ConnectionInfo)o; @@ -132,7 +132,7 @@ public class ConnectionInfoMarshaller extends BaseCommandMarshaller { /** * Un-marshal an object instance from the data input stream - * + * * @param o the object to un-marshal * @param dataIn the data input stream to build the object from * @throws IOException @@ -141,7 +141,8 @@ public class ConnectionInfoMarshaller extends BaseCommandMarshaller { super.looseUnmarshal(wireFormat, o, dataIn); ConnectionInfo info = (ConnectionInfo)o; - info.setConnectionId((org.apache.activemq.command.ConnectionId) looseUnmarsalCachedObject(wireFormat, dataIn)); + info.setConnectionId((org.apache.activemq.command.ConnectionId)looseUnmarsalCachedObject(wireFormat, + dataIn)); info.setClientId(looseUnmarshalString(dataIn)); info.setPassword(looseUnmarshalString(dataIn)); info.setUserName(looseUnmarshalString(dataIn)); @@ -149,12 +150,11 @@ public class ConnectionInfoMarshaller extends BaseCommandMarshaller { if (dataIn.readBoolean()) { short size = dataIn.readShort(); org.apache.activemq.command.BrokerId value[] = new org.apache.activemq.command.BrokerId[size]; - for( int i=0; i < size; i++ ) { - value[i] = (org.apache.activemq.command.BrokerId) looseUnmarsalNestedObject(wireFormat,dataIn); + for (int i = 0; i < size; i++) { + value[i] = (org.apache.activemq.command.BrokerId)looseUnmarsalNestedObject(wireFormat, dataIn); } info.setBrokerPath(value); - } - else { + } else { info.setBrokerPath(null); } info.setBrokerMasterConnector(dataIn.readBoolean()); @@ -163,7 +163,6 @@ public class ConnectionInfoMarshaller extends BaseCommandMarshaller { } - /** * Write the booleans that this object uses to a BooleanStream */ diff --git a/activemq-core/src/main/java/org/apache/activemq/openwire/v3/ConsumerIdMarshaller.java b/activemq-core/src/main/java/org/apache/activemq/openwire/v3/ConsumerIdMarshaller.java index 878f1c4ae2..847c339db6 100644 --- a/activemq-core/src/main/java/org/apache/activemq/openwire/v3/ConsumerIdMarshaller.java +++ b/activemq-core/src/main/java/org/apache/activemq/openwire/v3/ConsumerIdMarshaller.java @@ -24,29 +24,27 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - - /** * Marshalling code for Open Wire Format for ConsumerIdMarshaller - * - * - * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * + * + * + * NOTE!: This file is auto generated - do not modify! if you need to make a + * change, please see the modify the groovy scripts in the under src/gram/script + * and then use maven openwire:generate to regenerate this file. + * * @version $Revision$ */ public class ConsumerIdMarshaller extends BaseDataStreamMarshaller { /** * Return the type of Data Structure we marshal + * * @return short representation of the type data structure */ public byte getDataStructureType() { return ConsumerId.DATA_STRUCTURE_TYPE; } - + /** * @return a new object instance */ @@ -56,12 +54,13 @@ public class ConsumerIdMarshaller extends BaseDataStreamMarshaller { /** * Un-marshal an object instance from the data input stream - * + * * @param o the object to un-marshal * @param dataIn the data input stream to build the object from * @throws IOException */ - public void tightUnmarshal(OpenWireFormat wireFormat, Object o, DataInput dataIn, BooleanStream bs) throws IOException { + public void tightUnmarshal(OpenWireFormat wireFormat, Object o, DataInput dataIn, BooleanStream bs) + throws IOException { super.tightUnmarshal(wireFormat, o, dataIn, bs); ConsumerId info = (ConsumerId)o; @@ -71,7 +70,6 @@ public class ConsumerIdMarshaller extends BaseDataStreamMarshaller { } - /** * Write the booleans that this object uses to a BooleanStream */ @@ -81,20 +79,21 @@ public class ConsumerIdMarshaller extends BaseDataStreamMarshaller { int rc = super.tightMarshal1(wireFormat, o, bs); rc += tightMarshalString1(info.getConnectionId(), bs); - rc+=tightMarshalLong1(wireFormat, info.getSessionId(), bs); - rc+=tightMarshalLong1(wireFormat, info.getValue(), bs); + rc += tightMarshalLong1(wireFormat, info.getSessionId(), bs); + rc += tightMarshalLong1(wireFormat, info.getValue(), bs); return rc + 0; } /** * Write a object instance to data output stream - * + * * @param o the instance to be marshaled * @param dataOut the output stream * @throws IOException thrown if an error occurs */ - public void tightMarshal2(OpenWireFormat wireFormat, Object o, DataOutput dataOut, BooleanStream bs) throws IOException { + public void tightMarshal2(OpenWireFormat wireFormat, Object o, DataOutput dataOut, BooleanStream bs) + throws IOException { super.tightMarshal2(wireFormat, o, dataOut, bs); ConsumerId info = (ConsumerId)o; @@ -106,7 +105,7 @@ public class ConsumerIdMarshaller extends BaseDataStreamMarshaller { /** * Un-marshal an object instance from the data input stream - * + * * @param o the object to un-marshal * @param dataIn the data input stream to build the object from * @throws IOException @@ -121,7 +120,6 @@ public class ConsumerIdMarshaller extends BaseDataStreamMarshaller { } - /** * Write the booleans that this object uses to a BooleanStream */ diff --git a/activemq-core/src/main/java/org/apache/activemq/openwire/v3/ConsumerInfoMarshaller.java b/activemq-core/src/main/java/org/apache/activemq/openwire/v3/ConsumerInfoMarshaller.java index 955182ad6e..469189f850 100644 --- a/activemq-core/src/main/java/org/apache/activemq/openwire/v3/ConsumerInfoMarshaller.java +++ b/activemq-core/src/main/java/org/apache/activemq/openwire/v3/ConsumerInfoMarshaller.java @@ -24,29 +24,27 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - - /** * Marshalling code for Open Wire Format for ConsumerInfoMarshaller - * - * - * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * + * + * + * NOTE!: This file is auto generated - do not modify! if you need to make a + * change, please see the modify the groovy scripts in the under src/gram/script + * and then use maven openwire:generate to regenerate this file. + * * @version $Revision$ */ public class ConsumerInfoMarshaller extends BaseCommandMarshaller { /** * Return the type of Data Structure we marshal + * * @return short representation of the type data structure */ public byte getDataStructureType() { return ConsumerInfo.DATA_STRUCTURE_TYPE; } - + /** * @return a new object instance */ @@ -56,18 +54,24 @@ public class ConsumerInfoMarshaller extends BaseCommandMarshaller { /** * Un-marshal an object instance from the data input stream - * + * * @param o the object to un-marshal * @param dataIn the data input stream to build the object from * @throws IOException */ - public void tightUnmarshal(OpenWireFormat wireFormat, Object o, DataInput dataIn, BooleanStream bs) throws IOException { + public void tightUnmarshal(OpenWireFormat wireFormat, Object o, DataInput dataIn, BooleanStream bs) + throws IOException { super.tightUnmarshal(wireFormat, o, dataIn, bs); ConsumerInfo info = (ConsumerInfo)o; - info.setConsumerId((org.apache.activemq.command.ConsumerId) tightUnmarsalCachedObject(wireFormat, dataIn, bs)); + info.setConsumerId((org.apache.activemq.command.ConsumerId)tightUnmarsalCachedObject(wireFormat, + dataIn, bs)); info.setBrowser(bs.readBoolean()); - info.setDestination((org.apache.activemq.command.ActiveMQDestination) tightUnmarsalCachedObject(wireFormat, dataIn, bs)); + info + .setDestination((org.apache.activemq.command.ActiveMQDestination)tightUnmarsalCachedObject( + wireFormat, + dataIn, + bs)); info.setPrefetchSize(dataIn.readInt()); info.setMaximumPendingMessageLimit(dataIn.readInt()); info.setDispatchAsync(bs.readBoolean()); @@ -81,22 +85,25 @@ public class ConsumerInfoMarshaller extends BaseCommandMarshaller { if (bs.readBoolean()) { short size = dataIn.readShort(); org.apache.activemq.command.BrokerId value[] = new org.apache.activemq.command.BrokerId[size]; - for( int i=0; i < size; i++ ) { - value[i] = (org.apache.activemq.command.BrokerId) tightUnmarsalNestedObject(wireFormat,dataIn, bs); + for (int i = 0; i < size; i++) { + value[i] = (org.apache.activemq.command.BrokerId)tightUnmarsalNestedObject(wireFormat, + dataIn, bs); } info.setBrokerPath(value); - } - else { + } else { info.setBrokerPath(null); } - info.setAdditionalPredicate((org.apache.activemq.filter.BooleanExpression) tightUnmarsalNestedObject(wireFormat, dataIn, bs)); + info + .setAdditionalPredicate((org.apache.activemq.filter.BooleanExpression)tightUnmarsalNestedObject( + wireFormat, + dataIn, + bs)); info.setNetworkSubscription(bs.readBoolean()); info.setOptimizedAcknowledge(bs.readBoolean()); info.setNoRangeAcks(bs.readBoolean()); } - /** * Write the booleans that this object uses to a BooleanStream */ @@ -125,12 +132,13 @@ public class ConsumerInfoMarshaller extends BaseCommandMarshaller { /** * Write a object instance to data output stream - * + * * @param o the instance to be marshaled * @param dataOut the output stream * @throws IOException thrown if an error occurs */ - public void tightMarshal2(OpenWireFormat wireFormat, Object o, DataOutput dataOut, BooleanStream bs) throws IOException { + public void tightMarshal2(OpenWireFormat wireFormat, Object o, DataOutput dataOut, BooleanStream bs) + throws IOException { super.tightMarshal2(wireFormat, o, dataOut, bs); ConsumerInfo info = (ConsumerInfo)o; @@ -156,7 +164,7 @@ public class ConsumerInfoMarshaller extends BaseCommandMarshaller { /** * Un-marshal an object instance from the data input stream - * + * * @param o the object to un-marshal * @param dataIn the data input stream to build the object from * @throws IOException @@ -165,9 +173,13 @@ public class ConsumerInfoMarshaller extends BaseCommandMarshaller { super.looseUnmarshal(wireFormat, o, dataIn); ConsumerInfo info = (ConsumerInfo)o; - info.setConsumerId((org.apache.activemq.command.ConsumerId) looseUnmarsalCachedObject(wireFormat, dataIn)); + info.setConsumerId((org.apache.activemq.command.ConsumerId)looseUnmarsalCachedObject(wireFormat, + dataIn)); info.setBrowser(dataIn.readBoolean()); - info.setDestination((org.apache.activemq.command.ActiveMQDestination) looseUnmarsalCachedObject(wireFormat, dataIn)); + info + .setDestination((org.apache.activemq.command.ActiveMQDestination)looseUnmarsalCachedObject( + wireFormat, + dataIn)); info.setPrefetchSize(dataIn.readInt()); info.setMaximumPendingMessageLimit(dataIn.readInt()); info.setDispatchAsync(dataIn.readBoolean()); @@ -181,22 +193,23 @@ public class ConsumerInfoMarshaller extends BaseCommandMarshaller { if (dataIn.readBoolean()) { short size = dataIn.readShort(); org.apache.activemq.command.BrokerId value[] = new org.apache.activemq.command.BrokerId[size]; - for( int i=0; i < size; i++ ) { - value[i] = (org.apache.activemq.command.BrokerId) looseUnmarsalNestedObject(wireFormat,dataIn); + for (int i = 0; i < size; i++) { + value[i] = (org.apache.activemq.command.BrokerId)looseUnmarsalNestedObject(wireFormat, dataIn); } info.setBrokerPath(value); - } - else { + } else { info.setBrokerPath(null); } - info.setAdditionalPredicate((org.apache.activemq.filter.BooleanExpression) looseUnmarsalNestedObject(wireFormat, dataIn)); + info + .setAdditionalPredicate((org.apache.activemq.filter.BooleanExpression)looseUnmarsalNestedObject( + wireFormat, + dataIn)); info.setNetworkSubscription(dataIn.readBoolean()); info.setOptimizedAcknowledge(dataIn.readBoolean()); info.setNoRangeAcks(dataIn.readBoolean()); } - /** * Write the booleans that this object uses to a BooleanStream */ diff --git a/activemq-core/src/main/java/org/apache/activemq/openwire/v3/DataArrayResponseMarshaller.java b/activemq-core/src/main/java/org/apache/activemq/openwire/v3/DataArrayResponseMarshaller.java index b98c4968e0..35da0f1137 100644 --- a/activemq-core/src/main/java/org/apache/activemq/openwire/v3/DataArrayResponseMarshaller.java +++ b/activemq-core/src/main/java/org/apache/activemq/openwire/v3/DataArrayResponseMarshaller.java @@ -24,29 +24,27 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - - /** * Marshalling code for Open Wire Format for DataArrayResponseMarshaller - * - * - * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * + * + * + * NOTE!: This file is auto generated - do not modify! if you need to make a + * change, please see the modify the groovy scripts in the under src/gram/script + * and then use maven openwire:generate to regenerate this file. + * * @version $Revision$ */ public class DataArrayResponseMarshaller extends ResponseMarshaller { /** * Return the type of Data Structure we marshal + * * @return short representation of the type data structure */ public byte getDataStructureType() { return DataArrayResponse.DATA_STRUCTURE_TYPE; } - + /** * @return a new object instance */ @@ -56,12 +54,13 @@ public class DataArrayResponseMarshaller extends ResponseMarshaller { /** * Un-marshal an object instance from the data input stream - * + * * @param o the object to un-marshal * @param dataIn the data input stream to build the object from * @throws IOException */ - public void tightUnmarshal(OpenWireFormat wireFormat, Object o, DataInput dataIn, BooleanStream bs) throws IOException { + public void tightUnmarshal(OpenWireFormat wireFormat, Object o, DataInput dataIn, BooleanStream bs) + throws IOException { super.tightUnmarshal(wireFormat, o, dataIn, bs); DataArrayResponse info = (DataArrayResponse)o; @@ -69,18 +68,17 @@ public class DataArrayResponseMarshaller extends ResponseMarshaller { if (bs.readBoolean()) { short size = dataIn.readShort(); org.apache.activemq.command.DataStructure value[] = new org.apache.activemq.command.DataStructure[size]; - for( int i=0; i < size; i++ ) { - value[i] = (org.apache.activemq.command.DataStructure) tightUnmarsalNestedObject(wireFormat,dataIn, bs); + for (int i = 0; i < size; i++) { + value[i] = (org.apache.activemq.command.DataStructure)tightUnmarsalNestedObject(wireFormat, + dataIn, bs); } info.setData(value); - } - else { + } else { info.setData(null); } } - /** * Write the booleans that this object uses to a BooleanStream */ @@ -96,12 +94,13 @@ public class DataArrayResponseMarshaller extends ResponseMarshaller { /** * Write a object instance to data output stream - * + * * @param o the instance to be marshaled * @param dataOut the output stream * @throws IOException thrown if an error occurs */ - public void tightMarshal2(OpenWireFormat wireFormat, Object o, DataOutput dataOut, BooleanStream bs) throws IOException { + public void tightMarshal2(OpenWireFormat wireFormat, Object o, DataOutput dataOut, BooleanStream bs) + throws IOException { super.tightMarshal2(wireFormat, o, dataOut, bs); DataArrayResponse info = (DataArrayResponse)o; @@ -111,7 +110,7 @@ public class DataArrayResponseMarshaller extends ResponseMarshaller { /** * Un-marshal an object instance from the data input stream - * + * * @param o the object to un-marshal * @param dataIn the data input stream to build the object from * @throws IOException @@ -124,18 +123,17 @@ public class DataArrayResponseMarshaller extends ResponseMarshaller { if (dataIn.readBoolean()) { short size = dataIn.readShort(); org.apache.activemq.command.DataStructure value[] = new org.apache.activemq.command.DataStructure[size]; - for( int i=0; i < size; i++ ) { - value[i] = (org.apache.activemq.command.DataStructure) looseUnmarsalNestedObject(wireFormat,dataIn); + for (int i = 0; i < size; i++) { + value[i] = (org.apache.activemq.command.DataStructure)looseUnmarsalNestedObject(wireFormat, + dataIn); } info.setData(value); - } - else { + } else { info.setData(null); } } - /** * Write the booleans that this object uses to a BooleanStream */ diff --git a/activemq-core/src/main/java/org/apache/activemq/openwire/v3/DestinationInfoMarshaller.java b/activemq-core/src/main/java/org/apache/activemq/openwire/v3/DestinationInfoMarshaller.java index e8d7f865d2..f26e249365 100644 --- a/activemq-core/src/main/java/org/apache/activemq/openwire/v3/DestinationInfoMarshaller.java +++ b/activemq-core/src/main/java/org/apache/activemq/openwire/v3/DestinationInfoMarshaller.java @@ -24,29 +24,27 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - - /** * Marshalling code for Open Wire Format for DestinationInfoMarshaller - * - * - * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * + * + * + * NOTE!: This file is auto generated - do not modify! if you need to make a + * change, please see the modify the groovy scripts in the under src/gram/script + * and then use maven openwire:generate to regenerate this file. + * * @version $Revision$ */ public class DestinationInfoMarshaller extends BaseCommandMarshaller { /** * Return the type of Data Structure we marshal + * * @return short representation of the type data structure */ public byte getDataStructureType() { return DestinationInfo.DATA_STRUCTURE_TYPE; } - + /** * @return a new object instance */ @@ -56,35 +54,40 @@ public class DestinationInfoMarshaller extends BaseCommandMarshaller { /** * Un-marshal an object instance from the data input stream - * + * * @param o the object to un-marshal * @param dataIn the data input stream to build the object from * @throws IOException */ - public void tightUnmarshal(OpenWireFormat wireFormat, Object o, DataInput dataIn, BooleanStream bs) throws IOException { + public void tightUnmarshal(OpenWireFormat wireFormat, Object o, DataInput dataIn, BooleanStream bs) + throws IOException { super.tightUnmarshal(wireFormat, o, dataIn, bs); DestinationInfo info = (DestinationInfo)o; - info.setConnectionId((org.apache.activemq.command.ConnectionId) tightUnmarsalCachedObject(wireFormat, dataIn, bs)); - info.setDestination((org.apache.activemq.command.ActiveMQDestination) tightUnmarsalCachedObject(wireFormat, dataIn, bs)); + info.setConnectionId((org.apache.activemq.command.ConnectionId)tightUnmarsalCachedObject(wireFormat, + dataIn, bs)); + info + .setDestination((org.apache.activemq.command.ActiveMQDestination)tightUnmarsalCachedObject( + wireFormat, + dataIn, + bs)); info.setOperationType(dataIn.readByte()); info.setTimeout(tightUnmarshalLong(wireFormat, dataIn, bs)); if (bs.readBoolean()) { short size = dataIn.readShort(); org.apache.activemq.command.BrokerId value[] = new org.apache.activemq.command.BrokerId[size]; - for( int i=0; i < size; i++ ) { - value[i] = (org.apache.activemq.command.BrokerId) tightUnmarsalNestedObject(wireFormat,dataIn, bs); + for (int i = 0; i < size; i++) { + value[i] = (org.apache.activemq.command.BrokerId)tightUnmarsalNestedObject(wireFormat, + dataIn, bs); } info.setBrokerPath(value); - } - else { + } else { info.setBrokerPath(null); } } - /** * Write the booleans that this object uses to a BooleanStream */ @@ -95,7 +98,7 @@ public class DestinationInfoMarshaller extends BaseCommandMarshaller { int rc = super.tightMarshal1(wireFormat, o, bs); rc += tightMarshalCachedObject1(wireFormat, (DataStructure)info.getConnectionId(), bs); rc += tightMarshalCachedObject1(wireFormat, (DataStructure)info.getDestination(), bs); - rc+=tightMarshalLong1(wireFormat, info.getTimeout(), bs); + rc += tightMarshalLong1(wireFormat, info.getTimeout(), bs); rc += tightMarshalObjectArray1(wireFormat, info.getBrokerPath(), bs); return rc + 1; @@ -103,12 +106,13 @@ public class DestinationInfoMarshaller extends BaseCommandMarshaller { /** * Write a object instance to data output stream - * + * * @param o the instance to be marshaled * @param dataOut the output stream * @throws IOException thrown if an error occurs */ - public void tightMarshal2(OpenWireFormat wireFormat, Object o, DataOutput dataOut, BooleanStream bs) throws IOException { + public void tightMarshal2(OpenWireFormat wireFormat, Object o, DataOutput dataOut, BooleanStream bs) + throws IOException { super.tightMarshal2(wireFormat, o, dataOut, bs); DestinationInfo info = (DestinationInfo)o; @@ -122,7 +126,7 @@ public class DestinationInfoMarshaller extends BaseCommandMarshaller { /** * Un-marshal an object instance from the data input stream - * + * * @param o the object to un-marshal * @param dataIn the data input stream to build the object from * @throws IOException @@ -131,26 +135,28 @@ public class DestinationInfoMarshaller extends BaseCommandMarshaller { super.looseUnmarshal(wireFormat, o, dataIn); DestinationInfo info = (DestinationInfo)o; - info.setConnectionId((org.apache.activemq.command.ConnectionId) looseUnmarsalCachedObject(wireFormat, dataIn)); - info.setDestination((org.apache.activemq.command.ActiveMQDestination) looseUnmarsalCachedObject(wireFormat, dataIn)); + info.setConnectionId((org.apache.activemq.command.ConnectionId)looseUnmarsalCachedObject(wireFormat, + dataIn)); + info + .setDestination((org.apache.activemq.command.ActiveMQDestination)looseUnmarsalCachedObject( + wireFormat, + dataIn)); info.setOperationType(dataIn.readByte()); info.setTimeout(looseUnmarshalLong(wireFormat, dataIn)); if (dataIn.readBoolean()) { short size = dataIn.readShort(); org.apache.activemq.command.BrokerId value[] = new org.apache.activemq.command.BrokerId[size]; - for( int i=0; i < size; i++ ) { - value[i] = (org.apache.activemq.command.BrokerId) looseUnmarsalNestedObject(wireFormat,dataIn); + for (int i = 0; i < size; i++) { + value[i] = (org.apache.activemq.command.BrokerId)looseUnmarsalNestedObject(wireFormat, dataIn); } info.setBrokerPath(value); - } - else { + } else { info.setBrokerPath(null); } } - /** * Write the booleans that this object uses to a BooleanStream */ diff --git a/activemq-core/src/main/java/org/apache/activemq/openwire/v3/MessagePullMarshaller.java b/activemq-core/src/main/java/org/apache/activemq/openwire/v3/MessagePullMarshaller.java index 37c22cd515..d96f5f24a1 100644 --- a/activemq-core/src/main/java/org/apache/activemq/openwire/v3/MessagePullMarshaller.java +++ b/activemq-core/src/main/java/org/apache/activemq/openwire/v3/MessagePullMarshaller.java @@ -24,29 +24,27 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - - /** * Marshalling code for Open Wire Format for MessagePullMarshaller - * - * - * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * + * + * + * NOTE!: This file is auto generated - do not modify! if you need to make a + * change, please see the modify the groovy scripts in the under src/gram/script + * and then use maven openwire:generate to regenerate this file. + * * @version $Revision$ */ public class MessagePullMarshaller extends BaseCommandMarshaller { /** * Return the type of Data Structure we marshal + * * @return short representation of the type data structure */ public byte getDataStructureType() { return MessagePull.DATA_STRUCTURE_TYPE; } - + /** * @return a new object instance */ @@ -56,24 +54,30 @@ public class MessagePullMarshaller extends BaseCommandMarshaller { /** * Un-marshal an object instance from the data input stream - * + * * @param o the object to un-marshal * @param dataIn the data input stream to build the object from * @throws IOException */ - public void tightUnmarshal(OpenWireFormat wireFormat, Object o, DataInput dataIn, BooleanStream bs) throws IOException { + public void tightUnmarshal(OpenWireFormat wireFormat, Object o, DataInput dataIn, BooleanStream bs) + throws IOException { super.tightUnmarshal(wireFormat, o, dataIn, bs); MessagePull info = (MessagePull)o; - info.setConsumerId((org.apache.activemq.command.ConsumerId) tightUnmarsalCachedObject(wireFormat, dataIn, bs)); - info.setDestination((org.apache.activemq.command.ActiveMQDestination) tightUnmarsalCachedObject(wireFormat, dataIn, bs)); + info.setConsumerId((org.apache.activemq.command.ConsumerId)tightUnmarsalCachedObject(wireFormat, + dataIn, bs)); + info + .setDestination((org.apache.activemq.command.ActiveMQDestination)tightUnmarsalCachedObject( + wireFormat, + dataIn, + bs)); info.setTimeout(tightUnmarshalLong(wireFormat, dataIn, bs)); info.setCorrelationId(tightUnmarshalString(dataIn, bs)); - info.setMessageId((org.apache.activemq.command.MessageId) tightUnmarsalNestedObject(wireFormat, dataIn, bs)); + info.setMessageId((org.apache.activemq.command.MessageId)tightUnmarsalNestedObject(wireFormat, + dataIn, bs)); } - /** * Write the booleans that this object uses to a BooleanStream */ @@ -84,7 +88,7 @@ public class MessagePullMarshaller extends BaseCommandMarshaller { int rc = super.tightMarshal1(wireFormat, o, bs); rc += tightMarshalCachedObject1(wireFormat, (DataStructure)info.getConsumerId(), bs); rc += tightMarshalCachedObject1(wireFormat, (DataStructure)info.getDestination(), bs); - rc+=tightMarshalLong1(wireFormat, info.getTimeout(), bs); + rc += tightMarshalLong1(wireFormat, info.getTimeout(), bs); rc += tightMarshalString1(info.getCorrelationId(), bs); rc += tightMarshalNestedObject1(wireFormat, (DataStructure)info.getMessageId(), bs); @@ -93,12 +97,13 @@ public class MessagePullMarshaller extends BaseCommandMarshaller { /** * Write a object instance to data output stream - * + * * @param o the instance to be marshaled * @param dataOut the output stream * @throws IOException thrown if an error occurs */ - public void tightMarshal2(OpenWireFormat wireFormat, Object o, DataOutput dataOut, BooleanStream bs) throws IOException { + public void tightMarshal2(OpenWireFormat wireFormat, Object o, DataOutput dataOut, BooleanStream bs) + throws IOException { super.tightMarshal2(wireFormat, o, dataOut, bs); MessagePull info = (MessagePull)o; @@ -112,7 +117,7 @@ public class MessagePullMarshaller extends BaseCommandMarshaller { /** * Un-marshal an object instance from the data input stream - * + * * @param o the object to un-marshal * @param dataIn the data input stream to build the object from * @throws IOException @@ -121,15 +126,19 @@ public class MessagePullMarshaller extends BaseCommandMarshaller { super.looseUnmarshal(wireFormat, o, dataIn); MessagePull info = (MessagePull)o; - info.setConsumerId((org.apache.activemq.command.ConsumerId) looseUnmarsalCachedObject(wireFormat, dataIn)); - info.setDestination((org.apache.activemq.command.ActiveMQDestination) looseUnmarsalCachedObject(wireFormat, dataIn)); + info.setConsumerId((org.apache.activemq.command.ConsumerId)looseUnmarsalCachedObject(wireFormat, + dataIn)); + info + .setDestination((org.apache.activemq.command.ActiveMQDestination)looseUnmarsalCachedObject( + wireFormat, + dataIn)); info.setTimeout(looseUnmarshalLong(wireFormat, dataIn)); info.setCorrelationId(looseUnmarshalString(dataIn)); - info.setMessageId((org.apache.activemq.command.MessageId) looseUnmarsalNestedObject(wireFormat, dataIn)); + info + .setMessageId((org.apache.activemq.command.MessageId)looseUnmarsalNestedObject(wireFormat, dataIn)); } - /** * Write the booleans that this object uses to a BooleanStream */ diff --git a/activemq-core/src/main/java/org/apache/activemq/openwire/v3/ProducerInfoMarshaller.java b/activemq-core/src/main/java/org/apache/activemq/openwire/v3/ProducerInfoMarshaller.java index 943ec47a19..bc36bca199 100644 --- a/activemq-core/src/main/java/org/apache/activemq/openwire/v3/ProducerInfoMarshaller.java +++ b/activemq-core/src/main/java/org/apache/activemq/openwire/v3/ProducerInfoMarshaller.java @@ -24,29 +24,27 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - - /** * Marshalling code for Open Wire Format for ProducerInfoMarshaller - * - * - * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * + * + * + * NOTE!: This file is auto generated - do not modify! if you need to make a + * change, please see the modify the groovy scripts in the under src/gram/script + * and then use maven openwire:generate to regenerate this file. + * * @version $Revision$ */ public class ProducerInfoMarshaller extends BaseCommandMarshaller { /** * Return the type of Data Structure we marshal + * * @return short representation of the type data structure */ public byte getDataStructureType() { return ProducerInfo.DATA_STRUCTURE_TYPE; } - + /** * @return a new object instance */ @@ -56,27 +54,33 @@ public class ProducerInfoMarshaller extends BaseCommandMarshaller { /** * Un-marshal an object instance from the data input stream - * + * * @param o the object to un-marshal * @param dataIn the data input stream to build the object from * @throws IOException */ - public void tightUnmarshal(OpenWireFormat wireFormat, Object o, DataInput dataIn, BooleanStream bs) throws IOException { + public void tightUnmarshal(OpenWireFormat wireFormat, Object o, DataInput dataIn, BooleanStream bs) + throws IOException { super.tightUnmarshal(wireFormat, o, dataIn, bs); ProducerInfo info = (ProducerInfo)o; - info.setProducerId((org.apache.activemq.command.ProducerId) tightUnmarsalCachedObject(wireFormat, dataIn, bs)); - info.setDestination((org.apache.activemq.command.ActiveMQDestination) tightUnmarsalCachedObject(wireFormat, dataIn, bs)); + info.setProducerId((org.apache.activemq.command.ProducerId)tightUnmarsalCachedObject(wireFormat, + dataIn, bs)); + info + .setDestination((org.apache.activemq.command.ActiveMQDestination)tightUnmarsalCachedObject( + wireFormat, + dataIn, + bs)); if (bs.readBoolean()) { short size = dataIn.readShort(); org.apache.activemq.command.BrokerId value[] = new org.apache.activemq.command.BrokerId[size]; - for( int i=0; i < size; i++ ) { - value[i] = (org.apache.activemq.command.BrokerId) tightUnmarsalNestedObject(wireFormat,dataIn, bs); + for (int i = 0; i < size; i++) { + value[i] = (org.apache.activemq.command.BrokerId)tightUnmarsalNestedObject(wireFormat, + dataIn, bs); } info.setBrokerPath(value); - } - else { + } else { info.setBrokerPath(null); } info.setDispatchAsync(bs.readBoolean()); @@ -84,7 +88,6 @@ public class ProducerInfoMarshaller extends BaseCommandMarshaller { } - /** * Write the booleans that this object uses to a BooleanStream */ @@ -103,12 +106,13 @@ public class ProducerInfoMarshaller extends BaseCommandMarshaller { /** * Write a object instance to data output stream - * + * * @param o the instance to be marshaled * @param dataOut the output stream * @throws IOException thrown if an error occurs */ - public void tightMarshal2(OpenWireFormat wireFormat, Object o, DataOutput dataOut, BooleanStream bs) throws IOException { + public void tightMarshal2(OpenWireFormat wireFormat, Object o, DataOutput dataOut, BooleanStream bs) + throws IOException { super.tightMarshal2(wireFormat, o, dataOut, bs); ProducerInfo info = (ProducerInfo)o; @@ -122,7 +126,7 @@ public class ProducerInfoMarshaller extends BaseCommandMarshaller { /** * Un-marshal an object instance from the data input stream - * + * * @param o the object to un-marshal * @param dataIn the data input stream to build the object from * @throws IOException @@ -131,18 +135,21 @@ public class ProducerInfoMarshaller extends BaseCommandMarshaller { super.looseUnmarshal(wireFormat, o, dataIn); ProducerInfo info = (ProducerInfo)o; - info.setProducerId((org.apache.activemq.command.ProducerId) looseUnmarsalCachedObject(wireFormat, dataIn)); - info.setDestination((org.apache.activemq.command.ActiveMQDestination) looseUnmarsalCachedObject(wireFormat, dataIn)); + info.setProducerId((org.apache.activemq.command.ProducerId)looseUnmarsalCachedObject(wireFormat, + dataIn)); + info + .setDestination((org.apache.activemq.command.ActiveMQDestination)looseUnmarsalCachedObject( + wireFormat, + dataIn)); if (dataIn.readBoolean()) { short size = dataIn.readShort(); org.apache.activemq.command.BrokerId value[] = new org.apache.activemq.command.BrokerId[size]; - for( int i=0; i < size; i++ ) { - value[i] = (org.apache.activemq.command.BrokerId) looseUnmarsalNestedObject(wireFormat,dataIn); + for (int i = 0; i < size; i++) { + value[i] = (org.apache.activemq.command.BrokerId)looseUnmarsalNestedObject(wireFormat, dataIn); } info.setBrokerPath(value); - } - else { + } else { info.setBrokerPath(null); } info.setDispatchAsync(dataIn.readBoolean()); @@ -150,7 +157,6 @@ public class ProducerInfoMarshaller extends BaseCommandMarshaller { } - /** * Write the booleans that this object uses to a BooleanStream */ diff --git a/activemq-core/src/main/java/org/apache/activemq/openwire/v3/SessionIdMarshaller.java b/activemq-core/src/main/java/org/apache/activemq/openwire/v3/SessionIdMarshaller.java index ec69a7c7af..09ee6a1e4d 100644 --- a/activemq-core/src/main/java/org/apache/activemq/openwire/v3/SessionIdMarshaller.java +++ b/activemq-core/src/main/java/org/apache/activemq/openwire/v3/SessionIdMarshaller.java @@ -24,29 +24,27 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - - /** * Marshalling code for Open Wire Format for SessionIdMarshaller - * - * - * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * + * + * + * NOTE!: This file is auto generated - do not modify! if you need to make a + * change, please see the modify the groovy scripts in the under src/gram/script + * and then use maven openwire:generate to regenerate this file. + * * @version $Revision$ */ public class SessionIdMarshaller extends BaseDataStreamMarshaller { /** * Return the type of Data Structure we marshal + * * @return short representation of the type data structure */ public byte getDataStructureType() { return SessionId.DATA_STRUCTURE_TYPE; } - + /** * @return a new object instance */ @@ -56,12 +54,13 @@ public class SessionIdMarshaller extends BaseDataStreamMarshaller { /** * Un-marshal an object instance from the data input stream - * + * * @param o the object to un-marshal * @param dataIn the data input stream to build the object from * @throws IOException */ - public void tightUnmarshal(OpenWireFormat wireFormat, Object o, DataInput dataIn, BooleanStream bs) throws IOException { + public void tightUnmarshal(OpenWireFormat wireFormat, Object o, DataInput dataIn, BooleanStream bs) + throws IOException { super.tightUnmarshal(wireFormat, o, dataIn, bs); SessionId info = (SessionId)o; @@ -70,7 +69,6 @@ public class SessionIdMarshaller extends BaseDataStreamMarshaller { } - /** * Write the booleans that this object uses to a BooleanStream */ @@ -80,19 +78,20 @@ public class SessionIdMarshaller extends BaseDataStreamMarshaller { int rc = super.tightMarshal1(wireFormat, o, bs); rc += tightMarshalString1(info.getConnectionId(), bs); - rc+=tightMarshalLong1(wireFormat, info.getValue(), bs); + rc += tightMarshalLong1(wireFormat, info.getValue(), bs); return rc + 0; } /** * Write a object instance to data output stream - * + * * @param o the instance to be marshaled * @param dataOut the output stream * @throws IOException thrown if an error occurs */ - public void tightMarshal2(OpenWireFormat wireFormat, Object o, DataOutput dataOut, BooleanStream bs) throws IOException { + public void tightMarshal2(OpenWireFormat wireFormat, Object o, DataOutput dataOut, BooleanStream bs) + throws IOException { super.tightMarshal2(wireFormat, o, dataOut, bs); SessionId info = (SessionId)o; @@ -103,7 +102,7 @@ public class SessionIdMarshaller extends BaseDataStreamMarshaller { /** * Un-marshal an object instance from the data input stream - * + * * @param o the object to un-marshal * @param dataIn the data input stream to build the object from * @throws IOException @@ -117,7 +116,6 @@ public class SessionIdMarshaller extends BaseDataStreamMarshaller { } - /** * Write the booleans that this object uses to a BooleanStream */ diff --git a/activemq-core/src/main/java/org/apache/activemq/pool/ConnectionKey.java b/activemq-core/src/main/java/org/apache/activemq/pool/ConnectionKey.java index fda619dbff..f305dd4375 100644 --- a/activemq-core/src/main/java/org/apache/activemq/pool/ConnectionKey.java +++ b/activemq-core/src/main/java/org/apache/activemq/pool/ConnectionKey.java @@ -18,7 +18,7 @@ package org.apache.activemq.pool; /** * A cache key for the connection details - * + * * @version $Revision: 1.1 $ */ public class ConnectionKey { @@ -30,7 +30,7 @@ public class ConnectionKey { this.password = password; this.userName = userName; hash = 31; - if (userName != null) { + if (userName != null) { hash += userName.hashCode(); } hash *= 31; @@ -48,13 +48,13 @@ public class ConnectionKey { return true; } if (that instanceof ConnectionKey) { - return equals((ConnectionKey) that); + return equals((ConnectionKey)that); } return false; } public boolean equals(ConnectionKey that) { - return isEqual(this.userName, that.userName) && isEqual(this.password, that.password); + return isEqual(this.userName, that.userName) && isEqual(this.password, that.password); } public String getPassword() { @@ -72,5 +72,4 @@ public class ConnectionKey { return (o1 != null && o2 != null && o1.equals(o2)); } - } diff --git a/activemq-core/src/main/java/org/apache/activemq/pool/ConnectionPool.java b/activemq-core/src/main/java/org/apache/activemq/pool/ConnectionPool.java index 20a9ead12b..ab410c36fc 100644 --- a/activemq-core/src/main/java/org/apache/activemq/pool/ConnectionPool.java +++ b/activemq-core/src/main/java/org/apache/activemq/pool/ConnectionPool.java @@ -41,38 +41,44 @@ import java.util.concurrent.atomic.AtomicBoolean; * @version $Revision$ */ public class ConnectionPool { - + private TransactionManager transactionManager; private ActiveMQConnection connection; private Map cache; private AtomicBoolean started = new AtomicBoolean(false); private int referenceCount; private ObjectPoolFactory poolFactory; - private long lastUsed = System.currentTimeMillis(); - private boolean hasFailed; - private boolean hasExpired; - private int idleTimeout = 30*1000; + private long lastUsed = System.currentTimeMillis(); + private boolean hasFailed; + private boolean hasExpired; + private int idleTimeout = 30 * 1000; - public ConnectionPool(ActiveMQConnection connection, ObjectPoolFactory poolFactory, TransactionManager transactionManager) { + public ConnectionPool(ActiveMQConnection connection, ObjectPoolFactory poolFactory, + TransactionManager transactionManager) { this(connection, new HashMap(), poolFactory, transactionManager); - // Add a transport Listener so that we can notice if this connection should be expired due to + // Add a transport Listener so that we can notice if this connection + // should be expired due to // a connection failure. - connection.addTransportListener(new TransportListener(){ - public void onCommand(Object command) { - } - public void onException(IOException error) { - synchronized(ConnectionPool.this) { - hasFailed = true; - } - } - public void transportInterupted() { - } - public void transportResumed() { - } - }); + connection.addTransportListener(new TransportListener() { + public void onCommand(Object command) { + } + + public void onException(IOException error) { + synchronized (ConnectionPool.this) { + hasFailed = true; + } + } + + public void transportInterupted() { + } + + public void transportResumed() { + } + }); } - public ConnectionPool(ActiveMQConnection connection, Map cache, ObjectPoolFactory poolFactory, TransactionManager transactionManager) { + public ConnectionPool(ActiveMQConnection connection, Map cache, ObjectPoolFactory poolFactory, + TransactionManager transactionManager) { this.connection = connection; this.cache = cache; this.poolFactory = poolFactory; @@ -97,7 +103,7 @@ public class ConnectionPool { ackMode = Session.SESSION_TRANSACTED; } SessionKey key = new SessionKey(transacted, ackMode); - SessionPool pool = (SessionPool) cache.get(key); + SessionPool pool = (SessionPool)cache.get(key); if (pool == null) { pool = new SessionPool(this, key, poolFactory.createPool()); cache.put(key, pool); @@ -122,72 +128,72 @@ public class ConnectionPool { } synchronized public void close() { - if( connection!=null ) { - try { - Iterator i = cache.values().iterator(); - while (i.hasNext()) { - SessionPool pool = (SessionPool) i.next(); - i.remove(); - try { - pool.close(); - } catch (Exception e) { - } - } - } finally { + if (connection != null) { + try { + Iterator i = cache.values().iterator(); + while (i.hasNext()) { + SessionPool pool = (SessionPool)i.next(); + i.remove(); + try { + pool.close(); + } catch (Exception e) { + } + } + } finally { try { - connection.close(); + connection.close(); } catch (Exception e) { } finally { - connection = null; + connection = null; } - } - } + } + } } synchronized public void incrementReferenceCount() { - referenceCount++; - lastUsed = System.currentTimeMillis(); - } + referenceCount++; + lastUsed = System.currentTimeMillis(); + } - synchronized public void decrementReferenceCount() { - referenceCount--; - lastUsed = System.currentTimeMillis(); - if( referenceCount == 0 ) { - expiredCheck(); - } - } + synchronized public void decrementReferenceCount() { + referenceCount--; + lastUsed = System.currentTimeMillis(); + if (referenceCount == 0) { + expiredCheck(); + } + } - /** - * @return true if this connection has expired. - */ - synchronized public boolean expiredCheck() { - if( connection == null ) { - return true; - } - if( hasExpired ) { - if( referenceCount == 0 ) { - close(); - } - return true; - } - if( hasFailed || ( idleTimeout>0 && System.currentTimeMillis() > lastUsed+idleTimeout) ) { - hasExpired=true; - if( referenceCount == 0 ) { - close(); - } - return true; - } - return false; - } + /** + * @return true if this connection has expired. + */ + synchronized public boolean expiredCheck() { + if (connection == null) { + return true; + } + if (hasExpired) { + if (referenceCount == 0) { + close(); + } + return true; + } + if (hasFailed || (idleTimeout > 0 && System.currentTimeMillis() > lastUsed + idleTimeout)) { + hasExpired = true; + if (referenceCount == 0) { + close(); + } + return true; + } + return false; + } - public int getIdleTimeout() { - return idleTimeout; - } + public int getIdleTimeout() { + return idleTimeout; + } + + public void setIdleTimeout(int idleTimeout) { + this.idleTimeout = idleTimeout; + } - public void setIdleTimeout(int idleTimeout) { - this.idleTimeout = idleTimeout; - } - protected XAResource createXaResource(PooledSession session) throws JMSException { return session.getSession().getTransactionContext(); } @@ -201,7 +207,7 @@ public class ConnectionPool { public void beforeCompletion() { } - + public void afterCompletion(int status) { try { // This will return session to the pool. @@ -213,5 +219,5 @@ public class ConnectionPool { } } } - + } diff --git a/activemq-core/src/main/java/org/apache/activemq/pool/PooledConnection.java b/activemq-core/src/main/java/org/apache/activemq/pool/PooledConnection.java index cb10bff484..3136f17211 100755 --- a/activemq-core/src/main/java/org/apache/activemq/pool/PooledConnection.java +++ b/activemq-core/src/main/java/org/apache/activemq/pool/PooledConnection.java @@ -41,10 +41,9 @@ import javax.jms.TopicSession; * itself to the sessionPool. * * NOTE this implementation is only intended for use when sending - * messages. - * It does not deal with pooling of consumers; for that look at a library like - * Jencks such as in - * this example + * messages. It does not deal with pooling of consumers; for that look at a + * library like Jencks such as in this example * * @version $Revision: 1.1.1.1 $ */ @@ -66,10 +65,10 @@ public class PooledConnection implements TopicConnection, QueueConnection { } public void close() throws JMSException { - if( this.pool!=null ) { - this.pool.decrementReferenceCount(); - this.pool = null; - } + if (this.pool != null) { + this.pool.decrementReferenceCount(); + this.pool = null; + } } public void start() throws JMSException { @@ -81,17 +80,22 @@ public class PooledConnection implements TopicConnection, QueueConnection { stopped = true; } - public ConnectionConsumer createConnectionConsumer(Destination destination, String selector, ServerSessionPool serverSessionPool, int maxMessages) - throws JMSException { - return getConnection().createConnectionConsumer(destination, selector, serverSessionPool, maxMessages); + public ConnectionConsumer createConnectionConsumer(Destination destination, String selector, + ServerSessionPool serverSessionPool, int maxMessages) + throws JMSException { + return getConnection() + .createConnectionConsumer(destination, selector, serverSessionPool, maxMessages); } - public ConnectionConsumer createConnectionConsumer(Topic topic, String s, ServerSessionPool serverSessionPool, int maxMessages) throws JMSException { + public ConnectionConsumer createConnectionConsumer(Topic topic, String s, + ServerSessionPool serverSessionPool, int maxMessages) + throws JMSException { return getConnection().createConnectionConsumer(topic, s, serverSessionPool, maxMessages); } - public ConnectionConsumer createDurableConnectionConsumer(Topic topic, String selector, String s1, ServerSessionPool serverSessionPool, int i) - throws JMSException { + public ConnectionConsumer createDurableConnectionConsumer(Topic topic, String selector, String s1, + ServerSessionPool serverSessionPool, int i) + throws JMSException { return getConnection().createDurableConnectionConsumer(topic, selector, s1, serverSessionPool, i); } @@ -115,18 +119,20 @@ public class PooledConnection implements TopicConnection, QueueConnection { getConnection().setClientID(clientID); } - public ConnectionConsumer createConnectionConsumer(Queue queue, String selector, ServerSessionPool serverSessionPool, int maxMessages) throws JMSException { + public ConnectionConsumer createConnectionConsumer(Queue queue, String selector, + ServerSessionPool serverSessionPool, int maxMessages) + throws JMSException { return getConnection().createConnectionConsumer(queue, selector, serverSessionPool, maxMessages); } // Session factory methods // ------------------------------------------------------------------------- public QueueSession createQueueSession(boolean transacted, int ackMode) throws JMSException { - return (QueueSession) createSession(transacted, ackMode); + return (QueueSession)createSession(transacted, ackMode); } public TopicSession createTopicSession(boolean transacted, int ackMode) throws JMSException { - return (TopicSession) createSession(transacted, ackMode); + return (TopicSession)createSession(transacted, ackMode); } public Session createSession(boolean transacted, int ackMode) throws JMSException { @@ -148,11 +154,11 @@ public class PooledConnection implements TopicConnection, QueueConnection { } protected ActiveMQSession createSession(SessionKey key) throws JMSException { - return (ActiveMQSession) getConnection().createSession(key.isTransacted(), key.getAckMode()); + return (ActiveMQSession)getConnection().createSession(key.isTransacted(), key.getAckMode()); } - + public String toString() { - return "PooledConnection { "+pool+" }"; + return "PooledConnection { " + pool + " }"; } } diff --git a/activemq-core/src/main/java/org/apache/activemq/pool/PooledConnectionFactory.java b/activemq-core/src/main/java/org/apache/activemq/pool/PooledConnectionFactory.java index 6721ed1315..b29c2bf6bd 100644 --- a/activemq-core/src/main/java/org/apache/activemq/pool/PooledConnectionFactory.java +++ b/activemq-core/src/main/java/org/apache/activemq/pool/PooledConnectionFactory.java @@ -87,24 +87,24 @@ public class PooledConnectionFactory implements ConnectionFactory, Service { public synchronized Connection createConnection(String userName, String password) throws JMSException { ConnectionKey key = new ConnectionKey(userName, password); - LinkedList pools = (LinkedList) cache.get(key); - - if (pools == null) { + LinkedList pools = (LinkedList)cache.get(key); + + if (pools == null) { pools = new LinkedList(); cache.put(key, pools); } ConnectionPool connection = null; if (pools.size() == maxConnections) { - connection = (ConnectionPool) pools.removeFirst(); + connection = (ConnectionPool)pools.removeFirst(); } - - // Now.. we might get a connection, but it might be that we need to + + // Now.. we might get a connection, but it might be that we need to // dump it.. - if( connection!=null && connection.expiredCheck() ) { - connection=null; + if (connection != null && connection.expiredCheck()) { + connection = null; } - + if (connection == null) { ActiveMQConnection delegate = createConnection(key); connection = createConnectionPool(delegate); @@ -112,17 +112,17 @@ public class PooledConnectionFactory implements ConnectionFactory, Service { pools.add(connection); return new PooledConnection(connection); } - + protected ConnectionPool createConnectionPool(ActiveMQConnection connection) { return new ConnectionPool(connection, getPoolFactory(), transactionManager); } protected ActiveMQConnection createConnection(ConnectionKey key) throws JMSException { if (key.getUserName() == null && key.getPassword() == null) { - return (ActiveMQConnection) connectionFactory.createConnection(); - } - else { - return (ActiveMQConnection) connectionFactory.createConnection(key.getUserName(), key.getPassword()); + return (ActiveMQConnection)connectionFactory.createConnection(); + } else { + return (ActiveMQConnection)connectionFactory.createConnection(key.getUserName(), key + .getPassword()); } } @@ -132,17 +132,16 @@ public class PooledConnectionFactory implements ConnectionFactory, Service { public void start() { try { createConnection(); - } - catch (JMSException e) { + } catch (JMSException e) { IOExceptionSupport.create(e); } } - public void stop() throws Exception{ - for(Iterator iter=cache.values().iterator();iter.hasNext();){ - LinkedList list=(LinkedList)iter.next(); - for(Iterator i=list.iterator();i.hasNext();){ - ConnectionPool connection=(ConnectionPool)i.next(); + public void stop() throws Exception { + for (Iterator iter = cache.values().iterator(); iter.hasNext();) { + LinkedList list = (LinkedList)iter.next(); + for (Iterator i = list.iterator(); i.hasNext();) { + ConnectionPool connection = (ConnectionPool)i.next(); connection.close(); } } diff --git a/activemq-core/src/main/java/org/apache/activemq/proxy/ProxyConnector.java b/activemq-core/src/main/java/org/apache/activemq/proxy/ProxyConnector.java index 9eb06ea168..25b422f3f6 100644 --- a/activemq-core/src/main/java/org/apache/activemq/proxy/ProxyConnector.java +++ b/activemq-core/src/main/java/org/apache/activemq/proxy/ProxyConnector.java @@ -47,20 +47,19 @@ public class ProxyConnector implements Service { private URI remote; private URI localUri; private String name; - + CopyOnWriteArrayList connections = new CopyOnWriteArrayList(); - + public void start() throws Exception { - + this.getServer().setAcceptListener(new TransportAcceptListener() { public void onAccept(Transport localTransport) { try { Transport remoteTransport = createRemoteTransport(); ProxyConnection connection = new ProxyConnection(localTransport, remoteTransport); connections.add(connection); - connection.start(); - } - catch (Exception e) { + connection.start(); + } catch (Exception e) { onAcceptError(e); } } @@ -70,7 +69,7 @@ public class ProxyConnector implements Service { } }); getServer().start(); - log.info("Proxy Connector "+getName()+" Started"); + log.info("Proxy Connector " + getName() + " Started"); } @@ -81,15 +80,15 @@ public class ProxyConnector implements Service { } for (Iterator iter = connections.iterator(); iter.hasNext();) { log.info("Connector stopped: Stopping proxy."); - ss.stop((Service) iter.next()); + ss.stop((Service)iter.next()); } ss.throwFirstException(); log.info("Proxy Connector " + getName() + " Stopped"); } - + // Properties // ------------------------------------------------------------------------- - + public URI getLocalUri() { return localUri; } @@ -120,7 +119,7 @@ public class ProxyConnector implements Service { } return server; } - + public void setServer(TransportServer server) { this.server = server; } @@ -134,25 +133,25 @@ public class ProxyConnector implements Service { private Transport createRemoteTransport() throws Exception { Transport transport = TransportFactory.compositeConnect(remote); - CompositeTransport ct = (CompositeTransport) transport.narrow(CompositeTransport.class); - if( ct !=null && localUri!=null ) { - ct.add(new URI[]{localUri}); + CompositeTransport ct = (CompositeTransport)transport.narrow(CompositeTransport.class); + if (ct != null && localUri != null) { + ct.add(new URI[] {localUri}); } - + // Add a transport filter so that can track the transport life cycle transport = new TransportFilter(transport) { - public void stop() throws Exception { - log.info("Stopping proxy."); - super.stop(); - connections.remove(this); - } + public void stop() throws Exception { + log.info("Stopping proxy."); + super.stop(); + connections.remove(this); + } }; return transport; } public String getName() { - if( name == null ) { - if( server!=null ) { + if (name == null) { + if (server != null) { name = server.getConnectURI().toString(); } else { name = "proxy"; diff --git a/activemq-core/src/main/java/org/apache/activemq/security/AuthenticationUser.java b/activemq-core/src/main/java/org/apache/activemq/security/AuthenticationUser.java index c94ab32e2b..fd25de9cb3 100644 --- a/activemq-core/src/main/java/org/apache/activemq/security/AuthenticationUser.java +++ b/activemq-core/src/main/java/org/apache/activemq/security/AuthenticationUser.java @@ -16,48 +16,47 @@ */ package org.apache.activemq.security; - /** * A helper object used to configure simple authentiaction plugin - * + * * @org.apache.xbean.XBean * * @version $Revision */ public class AuthenticationUser { - String username; - String password; - String groups; - - - - public AuthenticationUser(String username, String password, String groups) { - this.username = username; - this.password = password; - this.groups = groups; - } - - - public String getGroups() { - return groups; - } - public void setGroups(String groups) { - this.groups = groups; - } - public String getPassword() { - return password; - } - public void setPassword(String password) { - this.password = password; - } - public String getUsername() { - return username; - } - public void setUsername(String username) { - this.username = username; - } - - - + String username; + String password; + String groups; + + public AuthenticationUser(String username, String password, String groups) { + this.username = username; + this.password = password; + this.groups = groups; + } + + public String getGroups() { + return groups; + } + + public void setGroups(String groups) { + this.groups = groups; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + } diff --git a/activemq-core/src/main/java/org/apache/activemq/security/AuthorizationBroker.java b/activemq-core/src/main/java/org/apache/activemq/security/AuthorizationBroker.java index c31032a8dc..01d78e878d 100644 --- a/activemq-core/src/main/java/org/apache/activemq/security/AuthorizationBroker.java +++ b/activemq-core/src/main/java/org/apache/activemq/security/AuthorizationBroker.java @@ -16,6 +16,8 @@ */ package org.apache.activemq.security; +import java.util.Set; + import org.apache.activemq.broker.Broker; import org.apache.activemq.broker.BrokerFilter; import org.apache.activemq.broker.ConnectionContext; @@ -24,170 +26,158 @@ import org.apache.activemq.broker.region.Destination; import org.apache.activemq.broker.region.Subscription; import org.apache.activemq.command.ActiveMQDestination; import org.apache.activemq.command.ActiveMQQueue; -import org.apache.activemq.command.ActiveMQTempDestination; import org.apache.activemq.command.ActiveMQTopic; import org.apache.activemq.command.ConsumerInfo; import org.apache.activemq.command.Message; import org.apache.activemq.command.ProducerInfo; -import org.apache.activemq.filter.BooleanExpression; -import org.apache.activemq.filter.MessageEvaluationContext; - -import javax.jms.JMSException; - -import java.util.Set; - /** - * Verifies if a authenticated user can do an operation against the broker using an authorization map. + * Verifies if a authenticated user can do an operation against the broker using + * an authorization map. * * @version $Revision$ */ public class AuthorizationBroker extends BrokerFilter implements SecurityAdminMBean { - + private final AuthorizationMap authorizationMap; public AuthorizationBroker(Broker next, AuthorizationMap authorizationMap) { super(next); this.authorizationMap = authorizationMap; } - + public Destination addDestination(ConnectionContext context, ActiveMQDestination destination) throws Exception { - final SecurityContext securityContext = (SecurityContext) context.getSecurityContext(); - if( securityContext == null ) + final SecurityContext securityContext = (SecurityContext)context.getSecurityContext(); + if (securityContext == null) { throw new SecurityException("User is not authenticated."); - - - //if(!((ActiveMQTempDestination)destination).getConnectionId().equals(context.getConnectionId().getValue()) ) { + } + // if(!((ActiveMQTempDestination)destination).getConnectionId().equals(context.getConnectionId().getValue()) + // ) { if (!securityContext.isBrokerContext()) { Set allowedACLs = null; - if(!destination.isTemporary()) { + if (!destination.isTemporary()) { allowedACLs = authorizationMap.getAdminACLs(destination); } else { allowedACLs = authorizationMap.getTempDestinationAdminACLs(); } - - if(allowedACLs!=null && !securityContext.isInOneOf(allowedACLs)) - throw new SecurityException("User "+securityContext.getUserName()+" is not authorized to create: "+destination); + + if (allowedACLs != null && !securityContext.isInOneOf(allowedACLs)) { + throw new SecurityException("User " + securityContext.getUserName() + " is not authorized to create: " + destination); + } } // } return super.addDestination(context, destination); } - - public void removeDestination(ConnectionContext context, ActiveMQDestination destination, long timeout) throws Exception { - - final SecurityContext securityContext = (SecurityContext) context.getSecurityContext(); - if( securityContext == null ) - throw new SecurityException("User is not authenticated."); + public void removeDestination(ConnectionContext context, ActiveMQDestination destination, long timeout) throws Exception { + + final SecurityContext securityContext = (SecurityContext)context.getSecurityContext(); + if (securityContext == null) { + throw new SecurityException("User is not authenticated."); + } Set allowedACLs = null; - if(!destination.isTemporary()) { + if (!destination.isTemporary()) { allowedACLs = authorizationMap.getAdminACLs(destination); } else { - allowedACLs = authorizationMap.getTempDestinationAdminACLs(); + allowedACLs = authorizationMap.getTempDestinationAdminACLs(); } - - if(allowedACLs!=null && !securityContext.isInOneOf(allowedACLs)) - throw new SecurityException("User "+securityContext.getUserName()+" is not authorized to remove: "+destination); + if (allowedACLs != null && !securityContext.isInOneOf(allowedACLs)) { + throw new SecurityException("User " + securityContext.getUserName() + " is not authorized to remove: " + destination); + } super.removeDestination(context, destination, timeout); } - + public Subscription addConsumer(ConnectionContext context, ConsumerInfo info) throws Exception { - - final SecurityContext subject = (SecurityContext) context.getSecurityContext(); - if( subject == null ) + + final SecurityContext subject = (SecurityContext)context.getSecurityContext(); + if (subject == null) { throw new SecurityException("User is not authenticated."); - + } Set allowedACLs = null; - if(!info.getDestination().isTemporary()) { + if (!info.getDestination().isTemporary()) { allowedACLs = authorizationMap.getReadACLs(info.getDestination()); - }else { - allowedACLs = authorizationMap.getTempDestinationReadACLs(); + } else { + allowedACLs = authorizationMap.getTempDestinationReadACLs(); } - if(allowedACLs!=null && !subject.isInOneOf(allowedACLs)) - throw new SecurityException("User "+subject.getUserName()+" is not authorized to read from: "+info.getDestination()); - + if (allowedACLs != null && !subject.isInOneOf(allowedACLs)) { + throw new SecurityException("User " + subject.getUserName() + " is not authorized to read from: " + info.getDestination()); + } subject.getAuthorizedReadDests().put(info.getDestination(), info.getDestination()); - - /* - * Need to think about this a little more. We could do per message security checking - * to implement finer grained security checking. For example a user can only see messages - * with price>1000 . Perhaps this should just be another additional broker filter that installs - * this type of feature. - * - * If we did want to do that, then we would install a predicate. We should be careful since - * there may be an existing predicate already assigned and the consumer info may be sent to a remote - * broker, so it also needs to support being marshaled. - * - info.setAdditionalPredicate(new BooleanExpression() { - public boolean matches(MessageEvaluationContext message) throws JMSException { - if( !subject.getAuthorizedReadDests().contains(message.getDestination()) ) { - Set allowedACLs = authorizationMap.getReadACLs(message.getDestination()); - if(allowedACLs!=null && !subject.isInOneOf(allowedACLs)) - return false; - subject.getAuthorizedReadDests().put(message.getDestination(), message.getDestination()); - } - return true; - } - public Object evaluate(MessageEvaluationContext message) throws JMSException { - return matches(message) ? Boolean.TRUE : Boolean.FALSE; - } - }); - */ - + + /* + * Need to think about this a little more. We could do per message + * security checking to implement finer grained security checking. For + * example a user can only see messages with price>1000 . Perhaps this + * should just be another additional broker filter that installs this + * type of feature. If we did want to do that, then we would install a + * predicate. We should be careful since there may be an existing + * predicate already assigned and the consumer info may be sent to a + * remote broker, so it also needs to support being marshaled. + * info.setAdditionalPredicate(new BooleanExpression() { public boolean + * matches(MessageEvaluationContext message) throws JMSException { if( + * !subject.getAuthorizedReadDests().contains(message.getDestination()) ) { + * Set allowedACLs = + * authorizationMap.getReadACLs(message.getDestination()); + * if(allowedACLs!=null && !subject.isInOneOf(allowedACLs)) return + * false; subject.getAuthorizedReadDests().put(message.getDestination(), + * message.getDestination()); } return true; } public Object + * evaluate(MessageEvaluationContext message) throws JMSException { + * return matches(message) ? Boolean.TRUE : Boolean.FALSE; } }); + */ + return super.addConsumer(context, info); } - + public void addProducer(ConnectionContext context, ProducerInfo info) throws Exception { - - SecurityContext subject = (SecurityContext) context.getSecurityContext(); - if( subject == null ) + + SecurityContext subject = (SecurityContext)context.getSecurityContext(); + if (subject == null) { throw new SecurityException("User is not authenticated."); - - if( info.getDestination()!=null ) { - - Set allowedACLs = null; - if(!info.getDestination().isTemporary()) { - allowedACLs = authorizationMap.getWriteACLs(info.getDestination()); - }else { - allowedACLs = authorizationMap.getTempDestinationWriteACLs(); - } - if(allowedACLs!=null && !subject.isInOneOf(allowedACLs)) - throw new SecurityException("User "+subject.getUserName()+" is not authorized to write to: "+info.getDestination()); - - + } + if (info.getDestination() != null) { + + Set allowedACLs = null; + if (!info.getDestination().isTemporary()) { + allowedACLs = authorizationMap.getWriteACLs(info.getDestination()); + } else { + allowedACLs = authorizationMap.getTempDestinationWriteACLs(); + } + if (allowedACLs != null && !subject.isInOneOf(allowedACLs)){ + throw new SecurityException("User " + subject.getUserName() + " is not authorized to write to: " + info.getDestination()); + } subject.getAuthorizedWriteDests().put(info.getDestination(), info.getDestination()); } - + super.addProducer(context, info); } - - public void send(ProducerBrokerExchange producerExchange, Message messageSend) throws Exception { - SecurityContext subject = (SecurityContext) producerExchange.getConnectionContext().getSecurityContext(); - if( subject == null ) - throw new SecurityException("User is not authenticated."); - if( !subject.getAuthorizedWriteDests().contains(messageSend.getDestination()) ) { - - Set allowedACLs = null; - if(!messageSend.getDestination().isTemporary()) { - allowedACLs = authorizationMap.getWriteACLs(messageSend.getDestination()); - }else { - allowedACLs = authorizationMap.getTempDestinationWriteACLs(); - } - - if(allowedACLs!=null && !subject.isInOneOf(allowedACLs)) - throw new SecurityException("User "+subject.getUserName()+" is not authorized to write to: "+messageSend.getDestination()); - + public void send(ProducerBrokerExchange producerExchange, Message messageSend) throws Exception { + SecurityContext subject = (SecurityContext)producerExchange.getConnectionContext().getSecurityContext(); + if (subject == null) { + throw new SecurityException("User is not authenticated."); + } + if (!subject.getAuthorizedWriteDests().contains(messageSend.getDestination())) { + + Set allowedACLs = null; + if (!messageSend.getDestination().isTemporary()) { + allowedACLs = authorizationMap.getWriteACLs(messageSend.getDestination()); + } else { + allowedACLs = authorizationMap.getTempDestinationWriteACLs(); + } + + if (allowedACLs != null && !subject.isInOneOf(allowedACLs)) { + throw new SecurityException("User " + subject.getUserName() + " is not authorized to write to: " + messageSend.getDestination()); + } subject.getAuthorizedWriteDests().put(messageSend.getDestination(), messageSend.getDestination()); } super.send(producerExchange, messageSend); } - + // SecurityAdminMBean interface // ------------------------------------------------------------------------- @@ -206,14 +196,13 @@ public class AuthorizationBroker extends BrokerFilter implements SecurityAdminMB public void removeTopicRole(String topic, String operation, String role) { removeDestinationRole(new ActiveMQTopic(topic), operation, role); } - + public void addDestinationRole(javax.jms.Destination destination, String operation, String role) { } - + public void removeDestinationRole(javax.jms.Destination destination, String operation, String role) { } - public void addRole(String role) { } diff --git a/activemq-core/src/main/java/org/apache/activemq/security/AuthorizationEntry.java b/activemq-core/src/main/java/org/apache/activemq/security/AuthorizationEntry.java index 44c1380715..39cd0039e0 100644 --- a/activemq-core/src/main/java/org/apache/activemq/security/AuthorizationEntry.java +++ b/activemq-core/src/main/java/org/apache/activemq/security/AuthorizationEntry.java @@ -16,8 +16,6 @@ */ package org.apache.activemq.security; -import org.apache.activemq.filter.DestinationMapEntry; - import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.util.Collections; @@ -25,13 +23,14 @@ import java.util.HashSet; import java.util.Set; import java.util.StringTokenizer; +import org.apache.activemq.filter.DestinationMapEntry; + /** * Represents an entry in a {@link DefaultAuthorizationMap} for assigning * different operations (read, write, admin) of user roles to a specific * destination or a hierarchical wildcard area of destinations. * * @org.apache.xbean.XBean - * * @version $Revision$ */ public class AuthorizationEntry extends DestinationMapEntry { @@ -39,20 +38,20 @@ public class AuthorizationEntry extends DestinationMapEntry { private Set readACLs = Collections.EMPTY_SET; private Set writeACLs = Collections.EMPTY_SET; private Set adminACLs = Collections.EMPTY_SET; - + private String adminRoles = null; private String readRoles = null; private String writeRoles = null; - + private String groupClass = "org.apache.activemq.jaas.GroupPrincipal"; - + public String getGroupClass() { - return groupClass; + return groupClass; } - + public void setGroupClass(String groupClass) { this.groupClass = groupClass; - } + } public Set getAdminACLs() { return adminACLs; @@ -79,23 +78,26 @@ public class AuthorizationEntry extends DestinationMapEntry { } // helper methods for easier configuration in Spring - // ACLs are already set in the afterPropertiesSet method to ensure that groupClass is set first before - // calling parceACLs() on any of the roles. We still need to add the call to parceACLs inside the helper - // methods for instances where we configure security programatically without using xbean + // ACLs are already set in the afterPropertiesSet method to ensure that + // groupClass is set first before + // calling parceACLs() on any of the roles. We still need to add the call to + // parceACLs inside the helper + // methods for instances where we configure security programatically without + // using xbean // ------------------------------------------------------------------------- public void setAdmin(String roles) throws Exception { - adminRoles = roles; - setAdminACLs(parseACLs(adminRoles)); + adminRoles = roles; + setAdminACLs(parseACLs(adminRoles)); } public void setRead(String roles) throws Exception { - readRoles = roles; - setReadACLs(parseACLs(readRoles)); + readRoles = roles; + setReadACLs(parseACLs(readRoles)); } public void setWrite(String roles) throws Exception { - writeRoles = roles; - setWriteACLs(parseACLs(writeRoles)); + writeRoles = roles; + setWriteACLs(parseACLs(writeRoles)); } protected Set parseACLs(String roles) throws Exception { @@ -105,58 +107,63 @@ public class AuthorizationEntry extends DestinationMapEntry { String name = iter.nextToken().trim(); Class[] paramClass = new Class[1]; paramClass[0] = String.class; - + Object[] param = new Object[1]; param[0] = name; try { - Class cls = Class.forName(groupClass); - - Constructor[] constructors = cls.getConstructors(); - int i; - for (i=0; i0; + return set.size() > 0; } abstract public Set getPrincipals(); - + public String getUserName() { return userName; } diff --git a/activemq-core/src/main/java/org/apache/activemq/security/SimpleAuthenticationBroker.java b/activemq-core/src/main/java/org/apache/activemq/security/SimpleAuthenticationBroker.java index a87729cb16..19dcf9978c 100644 --- a/activemq-core/src/main/java/org/apache/activemq/security/SimpleAuthenticationBroker.java +++ b/activemq-core/src/main/java/org/apache/activemq/security/SimpleAuthenticationBroker.java @@ -27,62 +27,62 @@ import org.apache.activemq.command.ConnectionInfo; import java.util.concurrent.CopyOnWriteArrayList; - /** * Handles authenticating a users against a simple user name/password map. * * @version $Revision$ */ public class SimpleAuthenticationBroker extends BrokerFilter { - + private final Map userPasswords; private final Map userGroups; private final CopyOnWriteArrayList securityContexts = new CopyOnWriteArrayList(); - + public SimpleAuthenticationBroker(Broker next, Map userPasswords, Map userGroups) { super(next); this.userPasswords = userPasswords; this.userGroups = userGroups; } - + public void addConnection(ConnectionContext context, ConnectionInfo info) throws Exception { - if( context.getSecurityContext()==null ) { + if (context.getSecurityContext() == null) { // Check the username and password. - String pw = (String) userPasswords.get(info.getUserName()); - if( pw == null || !pw.equals(info.getPassword()) ) + String pw = (String)userPasswords.get(info.getUserName()); + if (pw == null || !pw.equals(info.getPassword())) throw new SecurityException("User name or password is invalid."); - + final Set groups = (Set)userGroups.get(info.getUserName()); SecurityContext s = new SecurityContext(info.getUserName()) { public Set getPrincipals() { return groups; } }; - + context.setSecurityContext(s); securityContexts.add(s); } super.addConnection(context, info); } - - public void removeConnection(ConnectionContext context, ConnectionInfo info, Throwable error) throws Exception { + + public void removeConnection(ConnectionContext context, ConnectionInfo info, Throwable error) + throws Exception { super.removeConnection(context, info, error); - if( securityContexts.remove(context.getSecurityContext()) ) { + if (securityContexts.remove(context.getSecurityContext())) { context.setSecurityContext(null); } } - + /** - * Previously logged in users may no longer have the same access anymore. Refresh - * all the logged into users. + * Previously logged in users may no longer have the same access anymore. + * Refresh all the logged into users. */ public void refresh() { for (Iterator iter = securityContexts.iterator(); iter.hasNext();) { - SecurityContext sc = (SecurityContext) iter.next(); + SecurityContext sc = (SecurityContext)iter.next(); sc.getAuthorizedReadDests().clear(); sc.getAuthorizedWriteDests().clear(); } } - + } diff --git a/activemq-core/src/main/java/org/apache/activemq/security/SimpleAuthenticationPlugin.java b/activemq-core/src/main/java/org/apache/activemq/security/SimpleAuthenticationPlugin.java index 49906d51c1..31c6dd7444 100644 --- a/activemq-core/src/main/java/org/apache/activemq/security/SimpleAuthenticationPlugin.java +++ b/activemq-core/src/main/java/org/apache/activemq/security/SimpleAuthenticationPlugin.java @@ -33,9 +33,11 @@ import java.util.Map; /** * A simple authentication plugin - * - * @org.apache.xbean.XBean element="simpleAuthenticationPlugin" description="Provides a simple authentication - * plugin configured with a map of user-passwords and a map of user-groups or a list of authentication users" + * + * @org.apache.xbean.XBean element="simpleAuthenticationPlugin" + * description="Provides a simple authentication plugin + * configured with a map of user-passwords and a map of + * user-groups or a list of authentication users" * * @version $Revision$ */ @@ -43,10 +45,11 @@ public class SimpleAuthenticationPlugin implements BrokerPlugin { private Map userPasswords; private Map userGroups; - public SimpleAuthenticationPlugin() {} + public SimpleAuthenticationPlugin() { + } public SimpleAuthenticationPlugin(List users) { - setUsers(users); + setUsers(users); } public Broker installPlugin(Broker broker) { @@ -56,30 +59,31 @@ public class SimpleAuthenticationPlugin implements BrokerPlugin { public Map getUserGroups() { return userGroups; } - + /** * Sets individual users for authentication * * @org.apache.xbean.ElementType class="org.apache.activemq.security.AuthenticationUser" */ public void setUsers(List users) { - userPasswords = new HashMap(); - userGroups = new HashMap(); - for (Iterator it = users.iterator(); it.hasNext();) { - AuthenticationUser user = (AuthenticationUser)it.next(); - userPasswords.put(user.getUsername(), user.getPassword()); + userPasswords = new HashMap(); + userGroups = new HashMap(); + for (Iterator it = users.iterator(); it.hasNext();) { + AuthenticationUser user = (AuthenticationUser)it.next(); + userPasswords.put(user.getUsername(), user.getPassword()); Set groups = new HashSet(); StringTokenizer iter = new StringTokenizer(user.getGroups(), ","); while (iter.hasMoreTokens()) { String name = iter.nextToken().trim(); groups.add(new GroupPrincipal(name)); } - userGroups.put(user.getUsername(), groups); - } - } + userGroups.put(user.getUsername(), groups); + } + } /** - * Sets the groups a user is in. The key is the user name and the value is a Set of groups + * Sets the groups a user is in. The key is the user name and the value is a + * Set of groups */ public void setUserGroups(Map userGroups) { this.userGroups = userGroups; diff --git a/activemq-core/src/main/java/org/apache/activemq/security/SimpleAuthorizationMap.java b/activemq-core/src/main/java/org/apache/activemq/security/SimpleAuthorizationMap.java index bc88f9180d..5d1a2626c8 100644 --- a/activemq-core/src/main/java/org/apache/activemq/security/SimpleAuthorizationMap.java +++ b/activemq-core/src/main/java/org/apache/activemq/security/SimpleAuthorizationMap.java @@ -36,7 +36,7 @@ public class SimpleAuthorizationMap implements AuthorizationMap { private DestinationMap adminACLs; private TempDestinationAuthorizationEntry tempDestinationAuthorizationEntry; - + public SimpleAuthorizationMap() { } @@ -47,41 +47,43 @@ public class SimpleAuthorizationMap implements AuthorizationMap { } /* - * Need to think how to retrieve the ACLs for temporary destinations since they are not map - * to a specific destination. For now we'll just retrieve it from a TempDestinationAuthorizationEntry - * same way as the DefaultAuthorizationMap. The ACLs retrieved here will be map to all temp destinations + * Need to think how to retrieve the ACLs for temporary destinations since + * they are not map to a specific destination. For now we'll just retrieve + * it from a TempDestinationAuthorizationEntry same way as the + * DefaultAuthorizationMap. The ACLs retrieved here will be map to all temp + * destinations */ - - public void setTempDestinationAuthorizationEntry(TempDestinationAuthorizationEntry tempDestinationAuthorizationEntry) { + + public void setTempDestinationAuthorizationEntry( + TempDestinationAuthorizationEntry tempDestinationAuthorizationEntry) { this.tempDestinationAuthorizationEntry = tempDestinationAuthorizationEntry; - } - + } + public TempDestinationAuthorizationEntry getTempDestinationAuthorizationEntry() { return this.tempDestinationAuthorizationEntry; - } + } - public Set getTempDestinationAdminACLs() { - if(tempDestinationAuthorizationEntry != null) - return tempDestinationAuthorizationEntry.getAdminACLs(); + if (tempDestinationAuthorizationEntry != null) + return tempDestinationAuthorizationEntry.getAdminACLs(); else - return null; + return null; } - + public Set getTempDestinationReadACLs() { - if(tempDestinationAuthorizationEntry != null) - return tempDestinationAuthorizationEntry.getReadACLs(); - else - return null; + if (tempDestinationAuthorizationEntry != null) + return tempDestinationAuthorizationEntry.getReadACLs(); + else + return null; } - + public Set getTempDestinationWriteACLs() { - if(tempDestinationAuthorizationEntry != null) - return tempDestinationAuthorizationEntry.getWriteACLs(); - else - return null; - } - + if (tempDestinationAuthorizationEntry != null) + return tempDestinationAuthorizationEntry.getWriteACLs(); + else + return null; + } + public Set getAdminACLs(ActiveMQDestination destination) { return adminACLs.get(destination); } diff --git a/activemq-core/src/main/java/org/apache/activemq/state/CommandVisitor.java b/activemq-core/src/main/java/org/apache/activemq/state/CommandVisitor.java index 0fd68f2ceb..415154fcbd 100755 --- a/activemq-core/src/main/java/org/apache/activemq/state/CommandVisitor.java +++ b/activemq-core/src/main/java/org/apache/activemq/state/CommandVisitor.java @@ -47,45 +47,71 @@ import org.apache.activemq.command.WireFormatInfo; public interface CommandVisitor { Response processAddConnection(ConnectionInfo info) throws Exception; + Response processAddSession(SessionInfo info) throws Exception; + Response processAddProducer(ProducerInfo info) throws Exception; + Response processAddConsumer(ConsumerInfo info) throws Exception; - + Response processRemoveConnection(ConnectionId id) throws Exception; + Response processRemoveSession(SessionId id) throws Exception; + Response processRemoveProducer(ProducerId id) throws Exception; + Response processRemoveConsumer(ConsumerId id) throws Exception; - + Response processAddDestination(DestinationInfo info) throws Exception; + Response processRemoveDestination(DestinationInfo info) throws Exception; + Response processRemoveSubscription(RemoveSubscriptionInfo info) throws Exception; - + Response processMessage(Message send) throws Exception; + Response processMessageAck(MessageAck ack) throws Exception; + Response processMessagePull(MessagePull pull) throws Exception; Response processBeginTransaction(TransactionInfo info) throws Exception; + Response processPrepareTransaction(TransactionInfo info) throws Exception; + Response processCommitTransactionOnePhase(TransactionInfo info) throws Exception; + Response processCommitTransactionTwoPhase(TransactionInfo info) throws Exception; + Response processRollbackTransaction(TransactionInfo info) throws Exception; Response processWireFormat(WireFormatInfo info) throws Exception; + Response processKeepAlive(KeepAliveInfo info) throws Exception; + Response processShutdown(ShutdownInfo info) throws Exception; + Response processFlush(FlushCommand command) throws Exception; Response processBrokerInfo(BrokerInfo info) throws Exception; - Response processRecoverTransactions(TransactionInfo info) throws Exception; - Response processForgetTransaction(TransactionInfo info) throws Exception; - Response processEndTransaction(TransactionInfo info) throws Exception; - Response processMessageDispatchNotification(MessageDispatchNotification notification) throws Exception; - Response processProducerAck(ProducerAck ack) throws Exception; - Response processMessageDispatch(MessageDispatch dispatch) throws Exception; - Response processControlCommand(ControlCommand command) throws Exception; - Response processConnectionError(ConnectionError error) throws Exception; - Response processConnectionControl(ConnectionControl control) throws Exception; - Response processConsumerControl(ConsumerControl control) throws Exception; - -} + Response processRecoverTransactions(TransactionInfo info) throws Exception; + + Response processForgetTransaction(TransactionInfo info) throws Exception; + + Response processEndTransaction(TransactionInfo info) throws Exception; + + Response processMessageDispatchNotification(MessageDispatchNotification notification) throws Exception; + + Response processProducerAck(ProducerAck ack) throws Exception; + + Response processMessageDispatch(MessageDispatch dispatch) throws Exception; + + Response processControlCommand(ControlCommand command) throws Exception; + + Response processConnectionError(ConnectionError error) throws Exception; + + Response processConnectionControl(ConnectionControl control) throws Exception; + + Response processConsumerControl(ConsumerControl control) throws Exception; + +} diff --git a/activemq-core/src/main/java/org/apache/activemq/state/CommandVisitorAdapter.java b/activemq-core/src/main/java/org/apache/activemq/state/CommandVisitorAdapter.java index d2977c66ad..739cde7c11 100644 --- a/activemq-core/src/main/java/org/apache/activemq/state/CommandVisitorAdapter.java +++ b/activemq-core/src/main/java/org/apache/activemq/state/CommandVisitorAdapter.java @@ -46,140 +46,141 @@ import org.apache.activemq.command.WireFormatInfo; public class CommandVisitorAdapter implements CommandVisitor { - public Response processAddConnection(ConnectionInfo info) throws Exception { - return null; - } + public Response processAddConnection(ConnectionInfo info) throws Exception { + return null; + } - public Response processAddConsumer(ConsumerInfo info) throws Exception { - return null; - } + public Response processAddConsumer(ConsumerInfo info) throws Exception { + return null; + } - public Response processAddDestination(DestinationInfo info) throws Exception { - return null; - } + public Response processAddDestination(DestinationInfo info) throws Exception { + return null; + } - public Response processAddProducer(ProducerInfo info) throws Exception { - return null; - } + public Response processAddProducer(ProducerInfo info) throws Exception { + return null; + } - public Response processAddSession(SessionInfo info) throws Exception { - return null; - } + public Response processAddSession(SessionInfo info) throws Exception { + return null; + } - public Response processBeginTransaction(TransactionInfo info) throws Exception { - return null; - } + public Response processBeginTransaction(TransactionInfo info) throws Exception { + return null; + } - public Response processBrokerInfo(BrokerInfo info) throws Exception { - return null; - } + public Response processBrokerInfo(BrokerInfo info) throws Exception { + return null; + } - public Response processCommitTransactionOnePhase(TransactionInfo info) throws Exception { - return null; - } + public Response processCommitTransactionOnePhase(TransactionInfo info) throws Exception { + return null; + } - public Response processCommitTransactionTwoPhase(TransactionInfo info) throws Exception { - return null; - } + public Response processCommitTransactionTwoPhase(TransactionInfo info) throws Exception { + return null; + } - public Response processEndTransaction(TransactionInfo info) throws Exception { - return null; - } + public Response processEndTransaction(TransactionInfo info) throws Exception { + return null; + } - public Response processFlush(FlushCommand command) throws Exception { - return null; - } + public Response processFlush(FlushCommand command) throws Exception { + return null; + } - public Response processForgetTransaction(TransactionInfo info) throws Exception { - return null; - } + public Response processForgetTransaction(TransactionInfo info) throws Exception { + return null; + } - public Response processKeepAlive(KeepAliveInfo info) throws Exception { - return null; - } + public Response processKeepAlive(KeepAliveInfo info) throws Exception { + return null; + } - public Response processMessage(Message send) throws Exception { - return null; - } + public Response processMessage(Message send) throws Exception { + return null; + } - public Response processMessageAck(MessageAck ack) throws Exception { - return null; - } + public Response processMessageAck(MessageAck ack) throws Exception { + return null; + } - public Response processMessageDispatchNotification(MessageDispatchNotification notification) throws Exception { - return null; - } + public Response processMessageDispatchNotification(MessageDispatchNotification notification) + throws Exception { + return null; + } - public Response processMessagePull(MessagePull pull) throws Exception { - return null; - } + public Response processMessagePull(MessagePull pull) throws Exception { + return null; + } - public Response processPrepareTransaction(TransactionInfo info) throws Exception { - return null; - } + public Response processPrepareTransaction(TransactionInfo info) throws Exception { + return null; + } - public Response processProducerAck(ProducerAck ack) throws Exception { - return null; - } + public Response processProducerAck(ProducerAck ack) throws Exception { + return null; + } - public Response processRecoverTransactions(TransactionInfo info) throws Exception { - return null; - } + public Response processRecoverTransactions(TransactionInfo info) throws Exception { + return null; + } - public Response processRemoveConnection(ConnectionId id) throws Exception { - return null; - } + public Response processRemoveConnection(ConnectionId id) throws Exception { + return null; + } - public Response processRemoveConsumer(ConsumerId id) throws Exception { - return null; - } + public Response processRemoveConsumer(ConsumerId id) throws Exception { + return null; + } - public Response processRemoveDestination(DestinationInfo info) throws Exception { - return null; - } + public Response processRemoveDestination(DestinationInfo info) throws Exception { + return null; + } - public Response processRemoveProducer(ProducerId id) throws Exception { - return null; - } + public Response processRemoveProducer(ProducerId id) throws Exception { + return null; + } - public Response processRemoveSession(SessionId id) throws Exception { - return null; - } + public Response processRemoveSession(SessionId id) throws Exception { + return null; + } - public Response processRemoveSubscription(RemoveSubscriptionInfo info) throws Exception { - return null; - } + public Response processRemoveSubscription(RemoveSubscriptionInfo info) throws Exception { + return null; + } - public Response processRollbackTransaction(TransactionInfo info) throws Exception { - return null; - } + public Response processRollbackTransaction(TransactionInfo info) throws Exception { + return null; + } - public Response processShutdown(ShutdownInfo info) throws Exception { - return null; - } + public Response processShutdown(ShutdownInfo info) throws Exception { + return null; + } - public Response processWireFormat(WireFormatInfo info) throws Exception { - return null; - } + public Response processWireFormat(WireFormatInfo info) throws Exception { + return null; + } - public Response processMessageDispatch(MessageDispatch dispatch) throws Exception { - return null; - } + public Response processMessageDispatch(MessageDispatch dispatch) throws Exception { + return null; + } - public Response processControlCommand(ControlCommand command) throws Exception { - return null; - } + public Response processControlCommand(ControlCommand command) throws Exception { + return null; + } - public Response processConnectionControl(ConnectionControl control) throws Exception { - return null; - } + public Response processConnectionControl(ConnectionControl control) throws Exception { + return null; + } - public Response processConnectionError(ConnectionError error) throws Exception { - return null; - } + public Response processConnectionError(ConnectionError error) throws Exception { + return null; + } - public Response processConsumerControl(ConsumerControl control) throws Exception { - return null; - } + public Response processConsumerControl(ConsumerControl control) throws Exception { + return null; + } } diff --git a/activemq-core/src/main/java/org/apache/activemq/state/ConnectionState.java b/activemq-core/src/main/java/org/apache/activemq/state/ConnectionState.java index cdf2bf9bac..fa484757fb 100755 --- a/activemq-core/src/main/java/org/apache/activemq/state/ConnectionState.java +++ b/activemq-core/src/main/java/org/apache/activemq/state/ConnectionState.java @@ -34,71 +34,75 @@ import org.apache.activemq.command.SessionInfo; import org.apache.activemq.command.TransactionId; public class ConnectionState { - + ConnectionInfo info; private final ConcurrentHashMap transactions = new ConcurrentHashMap(); private final ConcurrentHashMap sessions = new ConcurrentHashMap(); private final List tempDestinations = Collections.synchronizedList(new ArrayList()); private final AtomicBoolean shutdown = new AtomicBoolean(false); - + public ConnectionState(ConnectionInfo info) { this.info = info; // Add the default session id. addSession(new SessionInfo(info, -1)); } - + public String toString() { return info.toString(); } - - public void reset(ConnectionInfo info) { - this.info=info; - transactions.clear(); - sessions.clear(); - tempDestinations.clear(); - shutdown.set(false); - } + public void reset(ConnectionInfo info) { + this.info = info; + transactions.clear(); + sessions.clear(); + tempDestinations.clear(); + shutdown.set(false); + } public void addTempDestination(DestinationInfo info) { - checkShutdown(); + checkShutdown(); tempDestinations.add(info); } - public void removeTempDestination(ActiveMQDestination destination) { + public void removeTempDestination(ActiveMQDestination destination) { for (Iterator iter = tempDestinations.iterator(); iter.hasNext();) { - DestinationInfo di = (DestinationInfo) iter.next(); - if( di.getDestination().equals(destination) ) { + DestinationInfo di = (DestinationInfo)iter.next(); + if (di.getDestination().equals(destination)) { iter.remove(); } } } - + public void addTransactionState(TransactionId id) { - checkShutdown(); - transactions.put(id, new TransactionState(id)); - } + checkShutdown(); + transactions.put(id, new TransactionState(id)); + } + public TransactionState getTransactionState(TransactionId id) { return (TransactionState)transactions.get(id); } + public Collection getTransactionStates() { return transactions.values(); } + public TransactionState removeTransactionState(TransactionId id) { - return (TransactionState) transactions.remove(id); + return (TransactionState)transactions.remove(id); } public void addSession(SessionInfo info) { - checkShutdown(); - sessions.put(info.getSessionId(), new SessionState(info)); - } + checkShutdown(); + sessions.put(info.getSessionId(), new SessionState(info)); + } + public SessionState removeSession(SessionId id) { return (SessionState)sessions.remove(id); } + public SessionState getSessionState(SessionId id) { return (SessionState)sessions.get(id); } - + public ConnectionInfo getInfo() { return info; } @@ -114,18 +118,18 @@ public class ConnectionState { public Collection getSessionStates() { return sessions.values(); } - + private void checkShutdown() { - if( shutdown.get() ) - throw new IllegalStateException("Disposed"); - } - + if (shutdown.get()) + throw new IllegalStateException("Disposed"); + } + public void shutdown() { - if( shutdown.compareAndSet(false, true) ) { - for (Iterator iter = sessions.values().iterator(); iter.hasNext();) { - SessionState ss = (SessionState) iter.next(); - ss.shutdown(); - } - } + if (shutdown.compareAndSet(false, true)) { + for (Iterator iter = sessions.values().iterator(); iter.hasNext();) { + SessionState ss = (SessionState)iter.next(); + ss.shutdown(); + } + } } } diff --git a/activemq-core/src/main/java/org/apache/activemq/state/ConnectionStateTracker.java b/activemq-core/src/main/java/org/apache/activemq/state/ConnectionStateTracker.java index 307ab428b1..7584221e39 100755 --- a/activemq-core/src/main/java/org/apache/activemq/state/ConnectionStateTracker.java +++ b/activemq-core/src/main/java/org/apache/activemq/state/ConnectionStateTracker.java @@ -38,34 +38,36 @@ import org.apache.activemq.transport.Transport; import org.apache.activemq.util.IOExceptionSupport; /** - * Tracks the state of a connection so a newly established transport can - * be re-initialized to the state that was tracked. + * Tracks the state of a connection so a newly established transport can be + * re-initialized to the state that was tracked. * * @version $Revision$ */ public class ConnectionStateTracker extends CommandVisitorAdapter { - private final static Tracked TRACKED_RESPONSE_MARKER = new Tracked(null); - - private boolean trackTransactions = false; - - private boolean restoreSessions=true; - private boolean restoreConsumers=true; - private boolean restoreProducers=true; - private boolean restoreTransaction=true; - + private final static Tracked TRACKED_RESPONSE_MARKER = new Tracked(null); + + private boolean trackTransactions = false; + + private boolean restoreSessions = true; + private boolean restoreConsumers = true; + private boolean restoreProducers = true; + private boolean restoreTransaction = true; + protected final ConcurrentHashMap connectionStates = new ConcurrentHashMap(); - + private class RemoveTransactionAction implements Runnable { - private final TransactionInfo info; - public RemoveTransactionAction(TransactionInfo info) { - this.info = info; - } - public void run() { - ConnectionId connectionId = info.getConnectionId(); - ConnectionState cs = (ConnectionState) connectionStates.get(connectionId); - cs.removeTransactionState(info.getTransactionId()); - } + private final TransactionInfo info; + + public RemoveTransactionAction(TransactionInfo info) { + this.info = info; + } + + public void run() { + ConnectionId connectionId = info.getConnectionId(); + ConnectionState cs = (ConnectionState)connectionStates.get(connectionId); + cs.removeTransactionState(info.getTransactionId()); + } } /** @@ -77,40 +79,40 @@ public class ConnectionStateTracker extends CommandVisitorAdapter { */ public Tracked track(Command command) throws IOException { try { - return (Tracked) command.visit(this); + return (Tracked)command.visit(this); } catch (IOException e) { throw e; } catch (Throwable e) { throw IOExceptionSupport.create(e); } - } - - public void restore( Transport transport ) throws IOException { + } + + public void restore(Transport transport) throws IOException { // Restore the connections. for (Iterator iter = connectionStates.values().iterator(); iter.hasNext();) { - ConnectionState connectionState = (ConnectionState) iter.next(); + ConnectionState connectionState = (ConnectionState)iter.next(); transport.oneway(connectionState.getInfo()); restoreTempDestinations(transport, connectionState); - - if( restoreSessions ) + + if (restoreSessions) restoreSessions(transport, connectionState); - - if( restoreTransaction ) - restoreTransactions(transport, connectionState); + + if (restoreTransaction) + restoreTransactions(transport, connectionState); } } private void restoreTransactions(Transport transport, ConnectionState connectionState) throws IOException { - for (Iterator iter = connectionState.getTransactionStates().iterator(); iter.hasNext();) { - TransactionState transactionState = (TransactionState) iter.next(); - for (Iterator iterator = transactionState.getCommands().iterator(); iterator.hasNext();) { - Command command = (Command) iterator.next(); - transport.oneway(command); - } - } - } + for (Iterator iter = connectionState.getTransactionStates().iterator(); iter.hasNext();) { + TransactionState transactionState = (TransactionState)iter.next(); + for (Iterator iterator = transactionState.getCommands().iterator(); iterator.hasNext();) { + Command command = (Command)iterator.next(); + transport.oneway(command); + } + } + } - /** + /** * @param transport * @param connectionState * @throws IOException @@ -118,13 +120,13 @@ public class ConnectionStateTracker extends CommandVisitorAdapter { protected void restoreSessions(Transport transport, ConnectionState connectionState) throws IOException { // Restore the connection's sessions for (Iterator iter2 = connectionState.getSessionStates().iterator(); iter2.hasNext();) { - SessionState sessionState = (SessionState) iter2.next(); + SessionState sessionState = (SessionState)iter2.next(); transport.oneway(sessionState.getInfo()); - if( restoreProducers ) + if (restoreProducers) restoreProducers(transport, sessionState); - - if( restoreConsumers ) + + if (restoreConsumers) restoreConsumers(transport, sessionState); } } @@ -137,7 +139,7 @@ public class ConnectionStateTracker extends CommandVisitorAdapter { protected void restoreConsumers(Transport transport, SessionState sessionState) throws IOException { // Restore the session's consumers for (Iterator iter3 = sessionState.getConsumerStates().iterator(); iter3.hasNext();) { - ConsumerState consumerState = (ConsumerState) iter3.next(); + ConsumerState consumerState = (ConsumerState)iter3.next(); transport.oneway(consumerState.getInfo()); } } @@ -150,7 +152,7 @@ public class ConnectionStateTracker extends CommandVisitorAdapter { protected void restoreProducers(Transport transport, SessionState sessionState) throws IOException { // Restore the session's producers for (Iterator iter3 = sessionState.getProducerStates().iterator(); iter3.hasNext();) { - ProducerState producerState = (ProducerState) iter3.next(); + ProducerState producerState = (ProducerState)iter3.next(); transport.oneway(producerState.getInfo()); } } @@ -160,44 +162,44 @@ public class ConnectionStateTracker extends CommandVisitorAdapter { * @param connectionState * @throws IOException */ - protected void restoreTempDestinations(Transport transport, ConnectionState connectionState) throws IOException { + protected void restoreTempDestinations(Transport transport, ConnectionState connectionState) + throws IOException { // Restore the connection's temp destinations. for (Iterator iter2 = connectionState.getTempDesinations().iterator(); iter2.hasNext();) { - transport.oneway((DestinationInfo) iter2.next()); + transport.oneway((DestinationInfo)iter2.next()); } } - public Response processAddDestination(DestinationInfo info){ - if(info!=null){ - ConnectionState cs=(ConnectionState)connectionStates.get(info.getConnectionId()); - if(cs!=null&&info.getDestination().isTemporary()){ + public Response processAddDestination(DestinationInfo info) { + if (info != null) { + ConnectionState cs = (ConnectionState)connectionStates.get(info.getConnectionId()); + if (cs != null && info.getDestination().isTemporary()) { cs.addTempDestination(info); } } return TRACKED_RESPONSE_MARKER; } - public Response processRemoveDestination(DestinationInfo info){ - if(info!=null){ - ConnectionState cs=(ConnectionState)connectionStates.get(info.getConnectionId()); - if(cs!=null&&info.getDestination().isTemporary()){ + public Response processRemoveDestination(DestinationInfo info) { + if (info != null) { + ConnectionState cs = (ConnectionState)connectionStates.get(info.getConnectionId()); + if (cs != null && info.getDestination().isTemporary()) { cs.removeTempDestination(info.getDestination()); } } return TRACKED_RESPONSE_MARKER; } - - public Response processAddProducer(ProducerInfo info){ - if(info!=null&&info.getProducerId()!=null){ - SessionId sessionId=info.getProducerId().getParentId(); - if(sessionId!=null){ - ConnectionId connectionId=sessionId.getParentId(); - if(connectionId!=null){ - ConnectionState cs=(ConnectionState)connectionStates.get(connectionId); - if(cs!=null){ - SessionState ss=cs.getSessionState(sessionId); - if(ss!=null){ + public Response processAddProducer(ProducerInfo info) { + if (info != null && info.getProducerId() != null) { + SessionId sessionId = info.getProducerId().getParentId(); + if (sessionId != null) { + ConnectionId connectionId = sessionId.getParentId(); + if (connectionId != null) { + ConnectionState cs = (ConnectionState)connectionStates.get(connectionId); + if (cs != null) { + SessionState ss = cs.getSessionState(sessionId); + if (ss != null) { ss.addProducer(info); } } @@ -206,17 +208,17 @@ public class ConnectionStateTracker extends CommandVisitorAdapter { } return TRACKED_RESPONSE_MARKER; } - - public Response processRemoveProducer(ProducerId id){ - if(id!=null){ - SessionId sessionId=id.getParentId(); - if(sessionId!=null){ - ConnectionId connectionId=sessionId.getParentId(); - if(connectionId!=null){ - ConnectionState cs=(ConnectionState)connectionStates.get(connectionId); - if(cs!=null){ - SessionState ss=cs.getSessionState(sessionId); - if(ss!=null){ + + public Response processRemoveProducer(ProducerId id) { + if (id != null) { + SessionId sessionId = id.getParentId(); + if (sessionId != null) { + ConnectionId connectionId = sessionId.getParentId(); + if (connectionId != null) { + ConnectionState cs = (ConnectionState)connectionStates.get(connectionId); + if (cs != null) { + SessionState ss = cs.getSessionState(sessionId); + if (ss != null) { ss.removeProducer(id); } } @@ -226,16 +228,16 @@ public class ConnectionStateTracker extends CommandVisitorAdapter { return TRACKED_RESPONSE_MARKER; } - public Response processAddConsumer(ConsumerInfo info){ - if(info!=null){ - SessionId sessionId=info.getConsumerId().getParentId(); - if(sessionId!=null){ - ConnectionId connectionId=sessionId.getParentId(); - if(connectionId!=null){ - ConnectionState cs=(ConnectionState)connectionStates.get(connectionId); - if(cs!=null){ - SessionState ss=cs.getSessionState(sessionId); - if(ss!=null){ + public Response processAddConsumer(ConsumerInfo info) { + if (info != null) { + SessionId sessionId = info.getConsumerId().getParentId(); + if (sessionId != null) { + ConnectionId connectionId = sessionId.getParentId(); + if (connectionId != null) { + ConnectionState cs = (ConnectionState)connectionStates.get(connectionId); + if (cs != null) { + SessionState ss = cs.getSessionState(sessionId); + if (ss != null) { ss.addConsumer(info); } } @@ -244,17 +246,17 @@ public class ConnectionStateTracker extends CommandVisitorAdapter { } return TRACKED_RESPONSE_MARKER; } - - public Response processRemoveConsumer(ConsumerId id){ - if(id!=null){ - SessionId sessionId=id.getParentId(); - if(sessionId!=null){ - ConnectionId connectionId=sessionId.getParentId(); - if(connectionId!=null){ - ConnectionState cs=(ConnectionState)connectionStates.get(connectionId); - if(cs!=null){ - SessionState ss=cs.getSessionState(sessionId); - if(ss!=null){ + + public Response processRemoveConsumer(ConsumerId id) { + if (id != null) { + SessionId sessionId = id.getParentId(); + if (sessionId != null) { + ConnectionId connectionId = sessionId.getParentId(); + if (connectionId != null) { + ConnectionState cs = (ConnectionState)connectionStates.get(connectionId); + if (cs != null) { + SessionState ss = cs.getSessionState(sessionId); + if (ss != null) { ss.removeConsumer(id); } } @@ -263,56 +265,55 @@ public class ConnectionStateTracker extends CommandVisitorAdapter { } return TRACKED_RESPONSE_MARKER; } - - public Response processAddSession(SessionInfo info){ - if(info!=null){ - ConnectionId connectionId=info.getSessionId().getParentId(); - if(connectionId!=null){ - ConnectionState cs=(ConnectionState)connectionStates.get(connectionId); - if(cs!=null){ + + public Response processAddSession(SessionInfo info) { + if (info != null) { + ConnectionId connectionId = info.getSessionId().getParentId(); + if (connectionId != null) { + ConnectionState cs = (ConnectionState)connectionStates.get(connectionId); + if (cs != null) { cs.addSession(info); } } } return TRACKED_RESPONSE_MARKER; } - - public Response processRemoveSession(SessionId id){ - if(id!=null){ - ConnectionId connectionId=id.getParentId(); - if(connectionId!=null){ - ConnectionState cs=(ConnectionState)connectionStates.get(connectionId); - if(cs!=null){ + + public Response processRemoveSession(SessionId id) { + if (id != null) { + ConnectionId connectionId = id.getParentId(); + if (connectionId != null) { + ConnectionState cs = (ConnectionState)connectionStates.get(connectionId); + if (cs != null) { cs.removeSession(id); } } } return TRACKED_RESPONSE_MARKER; } - - public Response processAddConnection(ConnectionInfo info){ + + public Response processAddConnection(ConnectionInfo info) { if (info != null) { - connectionStates.put(info.getConnectionId(), new ConnectionState(info)); - } - return TRACKED_RESPONSE_MARKER; - } - - public Response processRemoveConnection(ConnectionId id) throws Exception { - if (id != null) { - connectionStates.remove(id); + connectionStates.put(info.getConnectionId(), new ConnectionState(info)); } return TRACKED_RESPONSE_MARKER; } - - public Response processMessage(Message send) throws Exception{ - if(trackTransactions&&send!=null&&send.getTransactionId()!=null){ - ConnectionId connectionId=send.getProducerId().getParentId().getParentId(); - if(connectionId!=null){ - ConnectionState cs=(ConnectionState)connectionStates.get(connectionId); - if(cs!=null){ - TransactionState transactionState=cs.getTransactionState(send.getTransactionId()); - if(transactionState!=null){ + public Response processRemoveConnection(ConnectionId id) throws Exception { + if (id != null) { + connectionStates.remove(id); + } + return TRACKED_RESPONSE_MARKER; + } + + public Response processMessage(Message send) throws Exception { + if (trackTransactions && send != null && send.getTransactionId() != null) { + ConnectionId connectionId = send.getProducerId().getParentId().getParentId(); + if (connectionId != null) { + ConnectionState cs = (ConnectionState)connectionStates.get(connectionId); + if (cs != null) { + TransactionState transactionState = cs.getTransactionState(send.getTransactionId()); + if (transactionState != null) { transactionState.addCommand(send); } } @@ -320,16 +321,16 @@ public class ConnectionStateTracker extends CommandVisitorAdapter { return TRACKED_RESPONSE_MARKER; } return null; - } - - public Response processMessageAck(MessageAck ack){ - if(trackTransactions&&ack!=null&&ack.getTransactionId()!=null){ - ConnectionId connectionId=ack.getConsumerId().getParentId().getParentId(); - if(connectionId!=null){ - ConnectionState cs=(ConnectionState)connectionStates.get(connectionId); - if(cs!=null){ - TransactionState transactionState=cs.getTransactionState(ack.getTransactionId()); - if(transactionState!=null){ + } + + public Response processMessageAck(MessageAck ack) { + if (trackTransactions && ack != null && ack.getTransactionId() != null) { + ConnectionId connectionId = ack.getConsumerId().getParentId().getParentId(); + if (connectionId != null) { + ConnectionState cs = (ConnectionState)connectionStates.get(connectionId); + if (cs != null) { + TransactionState transactionState = cs.getTransactionState(ack.getTransactionId()); + if (transactionState != null) { transactionState.addCommand(ack); } } @@ -338,29 +339,29 @@ public class ConnectionStateTracker extends CommandVisitorAdapter { } return null; } - - public Response processBeginTransaction(TransactionInfo info){ - if(trackTransactions&&info!=null && info.getTransactionId() != null){ - ConnectionId connectionId=info.getConnectionId(); - if(connectionId!=null){ - ConnectionState cs=(ConnectionState)connectionStates.get(connectionId); - if(cs!=null){ + + public Response processBeginTransaction(TransactionInfo info) { + if (trackTransactions && info != null && info.getTransactionId() != null) { + ConnectionId connectionId = info.getConnectionId(); + if (connectionId != null) { + ConnectionState cs = (ConnectionState)connectionStates.get(connectionId); + if (cs != null) { cs.addTransactionState(info.getTransactionId()); } } return TRACKED_RESPONSE_MARKER; } return null; - } - - public Response processPrepareTransaction(TransactionInfo info) throws Exception{ - if(trackTransactions&&info!=null){ - ConnectionId connectionId=info.getConnectionId(); - if(connectionId!=null){ - ConnectionState cs=(ConnectionState)connectionStates.get(connectionId); - if(cs!=null){ - TransactionState transactionState=cs.getTransactionState(info.getTransactionId()); - if(transactionState!=null){ + } + + public Response processPrepareTransaction(TransactionInfo info) throws Exception { + if (trackTransactions && info != null) { + ConnectionId connectionId = info.getConnectionId(); + if (connectionId != null) { + ConnectionState cs = (ConnectionState)connectionStates.get(connectionId); + if (cs != null) { + TransactionState transactionState = cs.getTransactionState(info.getTransactionId()); + if (transactionState != null) { transactionState.addCommand(info); } } @@ -369,32 +370,15 @@ public class ConnectionStateTracker extends CommandVisitorAdapter { } return null; } - - public Response processCommitTransactionOnePhase(TransactionInfo info) throws Exception{ - if(trackTransactions&&info!=null){ - ConnectionId connectionId=info.getConnectionId(); - if(connectionId!=null){ - ConnectionState cs=(ConnectionState)connectionStates.get(connectionId); - if(cs!=null){ - TransactionState transactionState=cs.getTransactionState(info.getTransactionId()); - if(transactionState!=null){ - transactionState.addCommand(info); - return new Tracked(new RemoveTransactionAction(info)); - } - } - } - } - return null; - } - - public Response processCommitTransactionTwoPhase(TransactionInfo info) throws Exception{ - if(trackTransactions&&info!=null){ - ConnectionId connectionId=info.getConnectionId(); - if(connectionId!=null){ - ConnectionState cs=(ConnectionState)connectionStates.get(connectionId); - if(cs!=null){ - TransactionState transactionState=cs.getTransactionState(info.getTransactionId()); - if(transactionState!=null){ + + public Response processCommitTransactionOnePhase(TransactionInfo info) throws Exception { + if (trackTransactions && info != null) { + ConnectionId connectionId = info.getConnectionId(); + if (connectionId != null) { + ConnectionState cs = (ConnectionState)connectionStates.get(connectionId); + if (cs != null) { + TransactionState transactionState = cs.getTransactionState(info.getTransactionId()); + if (transactionState != null) { transactionState.addCommand(info); return new Tracked(new RemoveTransactionAction(info)); } @@ -403,15 +387,15 @@ public class ConnectionStateTracker extends CommandVisitorAdapter { } return null; } - - public Response processRollbackTransaction(TransactionInfo info) throws Exception{ - if(trackTransactions&&info!=null){ - ConnectionId connectionId=info.getConnectionId(); - if(connectionId!=null){ - ConnectionState cs=(ConnectionState)connectionStates.get(connectionId); - if(cs!=null){ - TransactionState transactionState=cs.getTransactionState(info.getTransactionId()); - if(transactionState!=null){ + + public Response processCommitTransactionTwoPhase(TransactionInfo info) throws Exception { + if (trackTransactions && info != null) { + ConnectionId connectionId = info.getConnectionId(); + if (connectionId != null) { + ConnectionState cs = (ConnectionState)connectionStates.get(connectionId); + if (cs != null) { + TransactionState transactionState = cs.getTransactionState(info.getTransactionId()); + if (transactionState != null) { transactionState.addCommand(info); return new Tracked(new RemoveTransactionAction(info)); } @@ -420,15 +404,32 @@ public class ConnectionStateTracker extends CommandVisitorAdapter { } return null; } - - public Response processEndTransaction(TransactionInfo info) throws Exception{ - if(trackTransactions&&info!=null){ - ConnectionId connectionId=info.getConnectionId(); - if(connectionId!=null){ - ConnectionState cs=(ConnectionState)connectionStates.get(connectionId); - if(cs!=null){ - TransactionState transactionState=cs.getTransactionState(info.getTransactionId()); - if(transactionState!=null){ + + public Response processRollbackTransaction(TransactionInfo info) throws Exception { + if (trackTransactions && info != null) { + ConnectionId connectionId = info.getConnectionId(); + if (connectionId != null) { + ConnectionState cs = (ConnectionState)connectionStates.get(connectionId); + if (cs != null) { + TransactionState transactionState = cs.getTransactionState(info.getTransactionId()); + if (transactionState != null) { + transactionState.addCommand(info); + return new Tracked(new RemoveTransactionAction(info)); + } + } + } + } + return null; + } + + public Response processEndTransaction(TransactionInfo info) throws Exception { + if (trackTransactions && info != null) { + ConnectionId connectionId = info.getConnectionId(); + if (connectionId != null) { + ConnectionState cs = (ConnectionState)connectionStates.get(connectionId); + if (cs != null) { + TransactionState transactionState = cs.getTransactionState(info.getTransactionId()); + if (transactionState != null) { transactionState.addCommand(info); } } @@ -437,7 +438,7 @@ public class ConnectionStateTracker extends CommandVisitorAdapter { } return null; } - + public boolean isRestoreConsumers() { return restoreConsumers; } @@ -462,20 +463,20 @@ public class ConnectionStateTracker extends CommandVisitorAdapter { this.restoreSessions = restoreSessions; } - public boolean isTrackTransactions() { - return trackTransactions; - } + public boolean isTrackTransactions() { + return trackTransactions; + } - public void setTrackTransactions(boolean trackTransactions) { - this.trackTransactions = trackTransactions; - } + public void setTrackTransactions(boolean trackTransactions) { + this.trackTransactions = trackTransactions; + } - public boolean isRestoreTransaction() { - return restoreTransaction; - } + public boolean isRestoreTransaction() { + return restoreTransaction; + } - public void setRestoreTransaction(boolean restoreTransaction) { - this.restoreTransaction = restoreTransaction; - } + public void setRestoreTransaction(boolean restoreTransaction) { + this.restoreTransaction = restoreTransaction; + } } diff --git a/activemq-core/src/main/java/org/apache/activemq/state/ProducerState.java b/activemq-core/src/main/java/org/apache/activemq/state/ProducerState.java index b7299a4099..07ee9fea82 100755 --- a/activemq-core/src/main/java/org/apache/activemq/state/ProducerState.java +++ b/activemq-core/src/main/java/org/apache/activemq/state/ProducerState.java @@ -19,18 +19,20 @@ package org.apache.activemq.state; import org.apache.activemq.command.ProducerInfo; -public class ProducerState { +public class ProducerState { final ProducerInfo info; - private long lastSequenceId=-1; - + private long lastSequenceId = -1; + public ProducerState(ProducerInfo info) { this.info = info; - } + } + public String toString() { return info.toString(); } + public ProducerInfo getInfo() { return info; } - + } diff --git a/activemq-core/src/main/java/org/apache/activemq/state/SessionState.java b/activemq-core/src/main/java/org/apache/activemq/state/SessionState.java index 1349609ce9..95deca8a05 100755 --- a/activemq-core/src/main/java/org/apache/activemq/state/SessionState.java +++ b/activemq-core/src/main/java/org/apache/activemq/state/SessionState.java @@ -29,68 +29,74 @@ import org.apache.activemq.command.SessionInfo; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicBoolean; -public class SessionState { +public class SessionState { final SessionInfo info; - + public final ConcurrentHashMap producers = new ConcurrentHashMap(); public final ConcurrentHashMap consumers = new ConcurrentHashMap(); private final AtomicBoolean shutdown = new AtomicBoolean(false); - + public SessionState(SessionInfo info) { this.info = info; - } + } + public String toString() { return info.toString(); } - + public void addProducer(ProducerInfo info) { - checkShutdown(); - producers.put(info.getProducerId(), new ProducerState(info)); - } + checkShutdown(); + producers.put(info.getProducerId(), new ProducerState(info)); + } + public ProducerState removeProducer(ProducerId id) { - return (ProducerState) producers.remove(id); + return (ProducerState)producers.remove(id); } - + public void addConsumer(ConsumerInfo info) { - checkShutdown(); - consumers.put(info.getConsumerId(), new ConsumerState(info)); - } - public ConsumerState removeConsumer(ConsumerId id) { - return (ConsumerState) consumers.remove(id); + checkShutdown(); + consumers.put(info.getConsumerId(), new ConsumerState(info)); } - + + public ConsumerState removeConsumer(ConsumerId id) { + return (ConsumerState)consumers.remove(id); + } + public SessionInfo getInfo() { return info; } - + public Set getConsumerIds() { return consumers.keySet(); - } + } + public Set getProducerIds() { return producers.keySet(); - } + } + public Collection getProducerStates() { return producers.values(); } - public ProducerState getProducerState(ProducerId producerId) { - return (ProducerState) producers.get(producerId); - } - + + public ProducerState getProducerState(ProducerId producerId) { + return (ProducerState)producers.get(producerId); + } + public Collection getConsumerStates() { return consumers.values(); } - + public ConsumerState getConsumerState(ConsumerId consumerId) { return (ConsumerState)consumers.get(consumerId); } - + private void checkShutdown() { - if( shutdown.get() ) - throw new IllegalStateException("Disposed"); - } - + if (shutdown.get()) + throw new IllegalStateException("Disposed"); + } + public void shutdown() { - shutdown.set(false); + shutdown.set(false); } } diff --git a/activemq-core/src/main/java/org/apache/activemq/state/Tracked.java b/activemq-core/src/main/java/org/apache/activemq/state/Tracked.java index 83059cd3d8..79b30603de 100644 --- a/activemq-core/src/main/java/org/apache/activemq/state/Tracked.java +++ b/activemq-core/src/main/java/org/apache/activemq/state/Tracked.java @@ -19,22 +19,22 @@ package org.apache.activemq.state; import org.apache.activemq.command.Response; public class Tracked extends Response { - - private Runnable runnable; - - public Tracked(Runnable runnable) { - this.runnable = runnable; - } - - public void onResponses() { - if( runnable != null ) { - runnable.run(); - runnable=null; - } - } - - public boolean isWaitingForResponse() { - return runnable!=null; - } - + + private Runnable runnable; + + public Tracked(Runnable runnable) { + this.runnable = runnable; + } + + public void onResponses() { + if (runnable != null) { + runnable.run(); + runnable = null; + } + } + + public boolean isWaitingForResponse() { + return runnable != null; + } + } diff --git a/activemq-core/src/main/java/org/apache/activemq/state/TransactionState.java b/activemq-core/src/main/java/org/apache/activemq/state/TransactionState.java index 8c88938c58..c1e1a8fa13 100644 --- a/activemq-core/src/main/java/org/apache/activemq/state/TransactionState.java +++ b/activemq-core/src/main/java/org/apache/activemq/state/TransactionState.java @@ -18,61 +18,65 @@ package org.apache.activemq.state; import java.util.ArrayList; import java.util.List; +import java.util.concurrent.atomic.AtomicBoolean; import org.apache.activemq.command.Command; import org.apache.activemq.command.TransactionId; -import java.util.concurrent.atomic.AtomicBoolean; - -public class TransactionState { +public class TransactionState { final TransactionId id; - + public final ArrayList commands = new ArrayList(); private final AtomicBoolean shutdown = new AtomicBoolean(false); - private boolean prepared; + private boolean prepared; + + private int preparedResult; - private int preparedResult; - public TransactionState(TransactionId id) { this.id = id; - } + } + public String toString() { return id.toString(); } - + public void addCommand(Command operation) { - checkShutdown(); - commands.add(operation); - } + checkShutdown(); + commands.add(operation); + } public List getCommands() { - return commands; - } - - private void checkShutdown() { - if( shutdown.get() ) - throw new IllegalStateException("Disposed"); - } - - public void shutdown() { - shutdown.set(false); + return commands; + } + + private void checkShutdown() { + if (shutdown.get()) + throw new IllegalStateException("Disposed"); + } + + public void shutdown() { + shutdown.set(false); + } + + public TransactionId getId() { + return id; + } + + public void setPrepared(boolean prepared) { + this.prepared = prepared; + } + + public boolean isPrepared() { + return prepared; + } + + public void setPreparedResult(int preparedResult) { + this.preparedResult = preparedResult; + } + + public int getPreparedResult() { + return preparedResult; } - public TransactionId getId() { - return id; - } - - public void setPrepared(boolean prepared) { - this.prepared = prepared; - } - public boolean isPrepared() { - return prepared; - } - public void setPreparedResult(int preparedResult) { - this.preparedResult = preparedResult; - } - public int getPreparedResult() { - return preparedResult; - } } diff --git a/activemq-core/src/main/java/org/apache/activemq/store/MessageStore.java b/activemq-core/src/main/java/org/apache/activemq/store/MessageStore.java index f980a6fb87..7fb89004a5 100755 --- a/activemq-core/src/main/java/org/apache/activemq/store/MessageStore.java +++ b/activemq-core/src/main/java/org/apache/activemq/store/MessageStore.java @@ -24,47 +24,48 @@ import org.apache.activemq.command.MessageId; import org.apache.activemq.memory.UsageManager; /** - * Represents a message store which is used by the persistent - * implementations + * Represents a message store which is used by the persistent implementations * * @version $Revision: 1.5 $ */ -public interface MessageStore extends Service{ +public interface MessageStore extends Service { /** * Adds a message to the message store * * @param context context - * @param message - * @throws IOException + * @param message + * @throws IOException */ - public void addMessage(ConnectionContext context,Message message) throws IOException; + public void addMessage(ConnectionContext context, Message message) throws IOException; /** - * Looks up a message using either the String messageID or the messageNumber. Implementations are encouraged to fill - * in the missing key if its easy to do so. + * Looks up a message using either the String messageID or the + * messageNumber. Implementations are encouraged to fill in the missing key + * if its easy to do so. * * @param identity which contains either the messageID or the messageNumber * @return the message or null if it does not exist - * @throws IOException + * @throws IOException */ public Message getMessage(MessageId identity) throws IOException; /** * Removes a message from the message store. * - * @param context - * @param ack the ack request that cause the message to be removed. It conatins the identity which contains the - * messageID of the message that needs to be removed. - * @throws IOException + * @param context + * @param ack the ack request that cause the message to be removed. It + * conatins the identity which contains the messageID of the + * message that needs to be removed. + * @throws IOException */ - public void removeMessage(ConnectionContext context,MessageAck ack) throws IOException; + public void removeMessage(ConnectionContext context, MessageAck ack) throws IOException; /** * Removes all the messages from the message store. * - * @param context - * @throws IOException + * @param context + * @throws IOException */ public void removeAllMessages(ConnectionContext context) throws IOException; @@ -84,25 +85,24 @@ public interface MessageStore extends Service{ public ActiveMQDestination getDestination(); /** - * @param usageManager The UsageManager that is controlling the destination's memory usage. + * @param usageManager The UsageManager that is controlling the + * destination's memory usage. */ public void setUsageManager(UsageManager usageManager); /** * @return the number of messages ready to deliver - * @throws IOException + * @throws IOException * */ public int getMessageCount() throws IOException; /** * A hint to the Store to reset any batching state for the Destination - * + * */ public void resetBatching(); - - public void recoverNextMessages(int maxReturned,MessageRecoveryListener listener) - throws Exception; - + public void recoverNextMessages(int maxReturned, MessageRecoveryListener listener) throws Exception; + } diff --git a/activemq-core/src/main/java/org/apache/activemq/store/ProxyMessageStore.java b/activemq-core/src/main/java/org/apache/activemq/store/ProxyMessageStore.java index 3e3102ef09..8e90983c39 100755 --- a/activemq-core/src/main/java/org/apache/activemq/store/ProxyMessageStore.java +++ b/activemq-core/src/main/java/org/apache/activemq/store/ProxyMessageStore.java @@ -31,11 +31,11 @@ import org.apache.activemq.memory.UsageManager; public class ProxyMessageStore implements MessageStore { final MessageStore delegate; - + public ProxyMessageStore(MessageStore delegate) { this.delegate = delegate; } - + public MessageStore getDelegate() { return delegate; } @@ -43,24 +43,31 @@ public class ProxyMessageStore implements MessageStore { public void addMessage(ConnectionContext context, Message message) throws IOException { delegate.addMessage(context, message); } + public Message getMessage(MessageId identity) throws IOException { return delegate.getMessage(identity); } + public void recover(MessageRecoveryListener listener) throws Exception { delegate.recover(listener); } + public void removeAllMessages(ConnectionContext context) throws IOException { delegate.removeAllMessages(context); } + public void removeMessage(ConnectionContext context, MessageAck ack) throws IOException { delegate.removeMessage(context, ack); } + public void start() throws Exception { delegate.start(); - } + } + public void stop() throws Exception { delegate.stop(); } + public ActiveMQDestination getDestination() { return delegate.getDestination(); } @@ -69,19 +76,17 @@ public class ProxyMessageStore implements MessageStore { delegate.setUsageManager(usageManager); } - - public int getMessageCount() throws IOException{ + public int getMessageCount() throws IOException { return delegate.getMessageCount(); } + public void recoverNextMessages(int maxReturned, MessageRecoveryListener listener) throws Exception { + delegate.recoverNextMessages(maxReturned, listener); - public void recoverNextMessages(int maxReturned,MessageRecoveryListener listener) throws Exception{ - delegate.recoverNextMessages(maxReturned,listener); - } - public void resetBatching(){ + public void resetBatching() { delegate.resetBatching(); - + } } diff --git a/activemq-core/src/main/java/org/apache/activemq/store/ProxyTopicMessageStore.java b/activemq-core/src/main/java/org/apache/activemq/store/ProxyTopicMessageStore.java index e9f3c585e2..f55c50a283 100755 --- a/activemq-core/src/main/java/org/apache/activemq/store/ProxyTopicMessageStore.java +++ b/activemq-core/src/main/java/org/apache/activemq/store/ProxyTopicMessageStore.java @@ -32,64 +32,74 @@ import org.apache.activemq.memory.UsageManager; public class ProxyTopicMessageStore implements TopicMessageStore { final TopicMessageStore delegate; - + public ProxyTopicMessageStore(TopicMessageStore delegate) { this.delegate = delegate; } - + public MessageStore getDelegate() { return delegate; } - + public void addMessage(ConnectionContext context, Message message) throws IOException { delegate.addMessage(context, message); } + public Message getMessage(MessageId identity) throws IOException { return delegate.getMessage(identity); } + public void recover(MessageRecoveryListener listener) throws Exception { delegate.recover(listener); } + public void removeAllMessages(ConnectionContext context) throws IOException { delegate.removeAllMessages(context); } + public void removeMessage(ConnectionContext context, MessageAck ack) throws IOException { delegate.removeMessage(context, ack); } + public void start() throws Exception { delegate.start(); } + public void stop() throws Exception { delegate.stop(); } - + public SubscriptionInfo lookupSubscription(String clientId, String subscriptionName) throws IOException { return delegate.lookupSubscription(clientId, subscriptionName); } - public void acknowledge(ConnectionContext context, String clientId, String subscriptionName, MessageId messageId) - throws IOException { + + public void acknowledge(ConnectionContext context, String clientId, String subscriptionName, + MessageId messageId) throws IOException { delegate.acknowledge(context, clientId, subscriptionName, messageId); } + public void addSubsciption(SubscriptionInfo subscriptionInfo, boolean retroactive) throws IOException { delegate.addSubsciption(subscriptionInfo, retroactive); } + public void deleteSubscription(String clientId, String subscriptionName) throws IOException { delegate.deleteSubscription(clientId, subscriptionName); } - public void recoverSubscription(String clientId, String subscriptionName, MessageRecoveryListener listener) throws Exception { + public void recoverSubscription(String clientId, String subscriptionName, MessageRecoveryListener listener) + throws Exception { delegate.recoverSubscription(clientId, subscriptionName, listener); } - - public void recoverNextMessages(String clientId,String subscriptionName,int maxReturned,MessageRecoveryListener listener) throws Exception{ - delegate.recoverNextMessages(clientId, subscriptionName, maxReturned,listener); + + public void recoverNextMessages(String clientId, String subscriptionName, int maxReturned, + MessageRecoveryListener listener) throws Exception { + delegate.recoverNextMessages(clientId, subscriptionName, maxReturned, listener); } - - public void resetBatching(String clientId,String subscriptionName) { - delegate.resetBatching(clientId,subscriptionName); + + public void resetBatching(String clientId, String subscriptionName) { + delegate.resetBatching(clientId, subscriptionName); } - - + public ActiveMQDestination getDestination() { return delegate.getDestination(); } @@ -97,27 +107,26 @@ public class ProxyTopicMessageStore implements TopicMessageStore { public SubscriptionInfo[] getAllSubscriptions() throws IOException { return delegate.getAllSubscriptions(); } - + public void setUsageManager(UsageManager usageManager) { delegate.setUsageManager(usageManager); } - public int getMessageCount(String clientId,String subscriberName) throws IOException{ - return delegate.getMessageCount(clientId,subscriberName); - } - - - public int getMessageCount() throws IOException{ + public int getMessageCount(String clientId, String subscriberName) throws IOException { + return delegate.getMessageCount(clientId, subscriberName); + } + + public int getMessageCount() throws IOException { return delegate.getMessageCount(); } - public void recoverNextMessages(int maxReturned,MessageRecoveryListener listener) throws Exception{ - delegate.recoverNextMessages(maxReturned,listener); - + public void recoverNextMessages(int maxReturned, MessageRecoveryListener listener) throws Exception { + delegate.recoverNextMessages(maxReturned, listener); + } - public void resetBatching(){ + public void resetBatching() { delegate.resetBatching(); - + } } diff --git a/activemq-core/src/main/java/org/apache/activemq/store/ReferenceStore.java b/activemq-core/src/main/java/org/apache/activemq/store/ReferenceStore.java index 85d0d690e2..7c34f62f22 100644 --- a/activemq-core/src/main/java/org/apache/activemq/store/ReferenceStore.java +++ b/activemq-core/src/main/java/org/apache/activemq/store/ReferenceStore.java @@ -23,59 +23,65 @@ import org.apache.activemq.broker.ConnectionContext; import org.apache.activemq.command.MessageId; /** - * Represents a message store which is used by the persistent - * implementations + * Represents a message store which is used by the persistent implementations * * @version $Revision: 1.5 $ */ public interface ReferenceStore extends MessageStore { - public class ReferenceData { - long expiration; - int fileId; - int offset; - - public long getExpiration() { - return expiration; - } - public void setExpiration(long expiration) { - this.expiration = expiration; - } - public int getFileId() { - return fileId; - } - public void setFileId(int file) { - this.fileId = file; - } - public int getOffset() { - return offset; - } - public void setOffset(int offset) { - this.offset = offset; - } - - @Override - public String toString() { - return "ReferenceData fileId="+fileId+", offset="+offset+", expiration="+expiration; - } - } - + public class ReferenceData { + long expiration; + int fileId; + int offset; + + public long getExpiration() { + return expiration; + } + + public void setExpiration(long expiration) { + this.expiration = expiration; + } + + public int getFileId() { + return fileId; + } + + public void setFileId(int file) { + this.fileId = file; + } + + public int getOffset() { + return offset; + } + + public void setOffset(int offset) { + this.offset = offset; + } + + @Override + public String toString() { + return "ReferenceData fileId=" + fileId + ", offset=" + offset + ", expiration=" + expiration; + } + } + /** * Adds a message reference to the message store */ - public void addMessageReference(ConnectionContext context, MessageId messageId, ReferenceData data) throws IOException; + public void addMessageReference(ConnectionContext context, MessageId messageId, ReferenceData data) + throws IOException; /** - * Looks up a message using either the String messageID or the messageNumber. Implementations are encouraged to fill - * in the missing key if its easy to do so. + * Looks up a message using either the String messageID or the + * messageNumber. Implementations are encouraged to fill in the missing key + * if its easy to do so. */ public ReferenceData getMessageReference(MessageId identity) throws IOException; - + /** * @return true if it supports external batch control */ public boolean supportsExternalBatchControl(); - + public void setBatch(MessageId startAfter); - + } diff --git a/activemq-core/src/main/java/org/apache/activemq/store/ReferenceStoreAdapter.java b/activemq-core/src/main/java/org/apache/activemq/store/ReferenceStoreAdapter.java index 5cf5d07947..513c8347c7 100644 --- a/activemq-core/src/main/java/org/apache/activemq/store/ReferenceStoreAdapter.java +++ b/activemq-core/src/main/java/org/apache/activemq/store/ReferenceStoreAdapter.java @@ -27,61 +27,67 @@ import org.apache.activemq.store.amq.AMQTx; /** * Adapter to the actual persistence mechanism used with ActiveMQ - * + * * @version $Revision: 1.3 $ */ public interface ReferenceStoreAdapter extends PersistenceAdapter { /** - * Factory method to create a new queue message store with the given destination name - * @param destination + * Factory method to create a new queue message store with the given + * destination name + * + * @param destination * @return the QueueReferenceStore - * @throws IOException + * @throws IOException */ public ReferenceStore createQueueReferenceStore(ActiveMQQueue destination) throws IOException; /** - * Factory method to create a new topic message store with the given destination name + * Factory method to create a new topic message store with the given + * destination name + * * @param destination - * @return the TopicRefererenceStore - * @throws IOException + * @return the TopicRefererenceStore + * @throws IOException */ public TopicReferenceStore createTopicReferenceStore(ActiveMQTopic destination) throws IOException; - /** - * @return Set of File ids in use - * @throws IOException - */ - public Set getReferenceFileIdsInUse() throws IOException; - + /** + * @return Set of File ids in use + * @throws IOException + */ + public Set getReferenceFileIdsInUse() throws IOException; + /** * If the store isn't valid, it can be recoverd at start-up + * * @return true if the reference store is in a consistent state */ public boolean isStoreValid(); - + /** * called by recover to clear out message references - * @throws IOException + * + * @throws IOException */ public void clearMessages() throws IOException; - + /** - * recover any state - * @throws IOException - * + * recover any state + * + * @throws IOException */ public void recoverState() throws IOException; - + /** * Save prepared transactions + * * @param map * @throws IOException */ - public void savePreparedState(Map map)throws IOException; - + public void savePreparedState(Map map) throws IOException; + /** - * * @return saved prepared transactions * @throws IOException */ diff --git a/activemq-core/src/main/java/org/apache/activemq/store/TopicMessageStore.java b/activemq-core/src/main/java/org/apache/activemq/store/TopicMessageStore.java index af5772ec5e..3daefae417 100755 --- a/activemq-core/src/main/java/org/apache/activemq/store/TopicMessageStore.java +++ b/activemq-core/src/main/java/org/apache/activemq/store/TopicMessageStore.java @@ -19,15 +19,16 @@ import org.apache.activemq.broker.ConnectionContext; import org.apache.activemq.command.Message; import org.apache.activemq.command.MessageId; import org.apache.activemq.command.SubscriptionInfo; + /** * A MessageStore for durable topic subscriptions * * @version $Revision: 1.4 $ */ -public interface TopicMessageStore extends MessageStore{ +public interface TopicMessageStore extends MessageStore { /** - * Stores the last acknowledged messgeID for the given subscription so that we can recover and commence dispatching - * messages from the last checkpoint + * Stores the last acknowledged messgeID for the given subscription so that + * we can recover and commence dispatching messages from the last checkpoint * * @param context * @param clientId @@ -36,8 +37,8 @@ public interface TopicMessageStore extends MessageStore{ * @param subscriptionPersistentId * @throws IOException */ - public void acknowledge(ConnectionContext context,String clientId,String subscriptionName,MessageId messageId) - throws IOException; + public void acknowledge(ConnectionContext context, String clientId, String subscriptionName, + MessageId messageId) throws IOException; /** * @param clientId @@ -46,12 +47,14 @@ public interface TopicMessageStore extends MessageStore{ * @throws IOException * @throws JMSException */ - public void deleteSubscription(String clientId,String subscriptionName) throws IOException; + public void deleteSubscription(String clientId, String subscriptionName) throws IOException; /** - * For the new subscription find the last acknowledged message ID and then find any new messages since then and - * dispatch them to the subscription.

e.g. if we dispatched some messages to a new durable topic subscriber, - * then went down before acknowledging any messages, we need to know the correct point from which to recover from. + * For the new subscription find the last acknowledged message ID and then + * find any new messages since then and dispatch them to the subscription. + *

e.g. if we dispatched some messages to a new durable topic + * subscriber, then went down before acknowledging any messages, we need to + * know the correct point from which to recover from. * * @param clientId * @param subscriptionName @@ -60,12 +63,12 @@ public interface TopicMessageStore extends MessageStore{ * * @throws Exception */ - public void recoverSubscription(String clientId,String subscriptionName,MessageRecoveryListener listener) - throws Exception; + public void recoverSubscription(String clientId, String subscriptionName, MessageRecoveryListener listener) + throws Exception; /** - * For an active subscription - retrieve messages from the store for the subscriber after the lastMessageId - * messageId

+ * For an active subscription - retrieve messages from the store for the + * subscriber after the lastMessageId messageId

* * @param clientId * @param subscriptionName @@ -74,27 +77,29 @@ public interface TopicMessageStore extends MessageStore{ * * @throws Exception */ - public void recoverNextMessages(String clientId,String subscriptionName,int maxReturned, - MessageRecoveryListener listener) throws Exception; + public void recoverNextMessages(String clientId, String subscriptionName, int maxReturned, + MessageRecoveryListener listener) throws Exception; /** * A hint to the Store to reset any batching state for a durable subsriber - * @param clientId - * @param subscriptionName - * + * + * @param clientId + * @param subscriptionName + * */ - public void resetBatching(String clientId,String subscriptionName); - - + public void resetBatching(String clientId, String subscriptionName); + /** - * Get the number of messages ready to deliver from the store to a durable subscriber + * Get the number of messages ready to deliver from the store to a durable + * subscriber + * * @param clientId * @param subscriberName * @return the outstanding message count * @throws IOException */ - public int getMessageCount(String clientId,String subscriberName) throws IOException; - + public int getMessageCount(String clientId, String subscriberName) throws IOException; + /** * Finds the subscriber entry for the given consumer info * @@ -103,7 +108,7 @@ public interface TopicMessageStore extends MessageStore{ * @return the SubscriptionInfo * @throws IOException */ - public SubscriptionInfo lookupSubscription(String clientId,String subscriptionName) throws IOException; + public SubscriptionInfo lookupSubscription(String clientId, String subscriptionName) throws IOException; /** * Lists all the durable subscriptions for a given destination. @@ -114,10 +119,12 @@ public interface TopicMessageStore extends MessageStore{ public SubscriptionInfo[] getAllSubscriptions() throws IOException; /** - * Inserts the subscriber info due to a subscription change

If this is a new subscription and the retroactive - * is false, then the last message sent to the topic should be set as the last message acknowledged by they new - * subscription. Otherwise, if retroactive is true, then create the subscription without it having an acknowledged - * message so that on recovery, all message recorded for the topic get replayed. + * Inserts the subscriber info due to a subscription change

If this is + * a new subscription and the retroactive is false, then the last message + * sent to the topic should be set as the last message acknowledged by they + * new subscription. Otherwise, if retroactive is true, then create the + * subscription without it having an acknowledged message so that on + * recovery, all message recorded for the topic get replayed. * * @param clientId * @param subscriptionName @@ -126,6 +133,5 @@ public interface TopicMessageStore extends MessageStore{ * @throws IOException * */ - public void addSubsciption(SubscriptionInfo subscriptionInfo, boolean retroactive) - throws IOException; + public void addSubsciption(SubscriptionInfo subscriptionInfo, boolean retroactive) throws IOException; } diff --git a/activemq-core/src/main/java/org/apache/activemq/store/TopicReferenceStore.java b/activemq-core/src/main/java/org/apache/activemq/store/TopicReferenceStore.java index b65c6edaf6..c820d426cb 100644 --- a/activemq-core/src/main/java/org/apache/activemq/store/TopicReferenceStore.java +++ b/activemq-core/src/main/java/org/apache/activemq/store/TopicReferenceStore.java @@ -31,8 +31,8 @@ import org.apache.activemq.command.SubscriptionInfo; */ public interface TopicReferenceStore extends ReferenceStore, TopicMessageStore { /** - * Stores the last acknowledged messgeID for the given subscription so that we can recover and commence dispatching - * messages from the last checkpoint + * Stores the last acknowledged messgeID for the given subscription so that + * we can recover and commence dispatching messages from the last checkpoint * * @param context * @param clientId @@ -41,8 +41,8 @@ public interface TopicReferenceStore extends ReferenceStore, TopicMessageStore { * @param subscriptionPersistentId * @throws IOException */ - public void acknowledge(ConnectionContext context,String clientId,String subscriptionName,MessageId messageId) - throws IOException; + public void acknowledge(ConnectionContext context, String clientId, String subscriptionName, + MessageId messageId) throws IOException; /** * @param clientId @@ -51,12 +51,14 @@ public interface TopicReferenceStore extends ReferenceStore, TopicMessageStore { * @throws IOException * @throws JMSException */ - public void deleteSubscription(String clientId,String subscriptionName) throws IOException; + public void deleteSubscription(String clientId, String subscriptionName) throws IOException; /** - * For the new subscription find the last acknowledged message ID and then find any new messages since then and - * dispatch them to the subscription.

e.g. if we dispatched some messages to a new durable topic subscriber, - * then went down before acknowledging any messages, we need to know the correct point from which to recover from. + * For the new subscription find the last acknowledged message ID and then + * find any new messages since then and dispatch them to the subscription. + *

e.g. if we dispatched some messages to a new durable topic + * subscriber, then went down before acknowledging any messages, we need to + * know the correct point from which to recover from. * * @param clientId * @param subscriptionName @@ -65,12 +67,12 @@ public interface TopicReferenceStore extends ReferenceStore, TopicMessageStore { * * @throws Exception */ - public void recoverSubscription(String clientId,String subscriptionName,MessageRecoveryListener listener) - throws Exception; + public void recoverSubscription(String clientId, String subscriptionName, MessageRecoveryListener listener) + throws Exception; /** - * For an active subscription - retrieve messages from the store for the subscriber after the lastMessageId - * messageId

+ * For an active subscription - retrieve messages from the store for the + * subscriber after the lastMessageId messageId

* * @param clientId * @param subscriptionName @@ -79,27 +81,29 @@ public interface TopicReferenceStore extends ReferenceStore, TopicMessageStore { * * @throws Exception */ - public void recoverNextMessages(String clientId,String subscriptionName,int maxReturned, - MessageRecoveryListener listener) throws Exception; + public void recoverNextMessages(String clientId, String subscriptionName, int maxReturned, + MessageRecoveryListener listener) throws Exception; /** * A hint to the Store to reset any batching state for a durable subsriber - * @param clientId - * @param subscriptionName - * + * + * @param clientId + * @param subscriptionName + * */ - public void resetBatching(String clientId,String subscriptionName); - - + public void resetBatching(String clientId, String subscriptionName); + /** - * Get the number of messages ready to deliver from the store to a durable subscriber + * Get the number of messages ready to deliver from the store to a durable + * subscriber + * * @param clientId * @param subscriberName * @return the outstanding message count * @throws IOException */ - public int getMessageCount(String clientId,String subscriberName) throws IOException; - + public int getMessageCount(String clientId, String subscriberName) throws IOException; + /** * Finds the subscriber entry for the given consumer info * @@ -108,7 +112,7 @@ public interface TopicReferenceStore extends ReferenceStore, TopicMessageStore { * @return the SubscriptionInfo * @throws IOException */ - public SubscriptionInfo lookupSubscription(String clientId,String subscriptionName) throws IOException; + public SubscriptionInfo lookupSubscription(String clientId, String subscriptionName) throws IOException; /** * Lists all the durable subscirptions for a given destination. @@ -119,10 +123,12 @@ public interface TopicReferenceStore extends ReferenceStore, TopicMessageStore { public SubscriptionInfo[] getAllSubscriptions() throws IOException; /** - * Inserts the subscriber info due to a subscription change

If this is a new subscription and the retroactive - * is false, then the last message sent to the topic should be set as the last message acknowledged by they new - * subscription. Otherwise, if retroactive is true, then create the subscription without it having an acknowledged - * message so that on recovery, all message recorded for the topic get replayed. + * Inserts the subscriber info due to a subscription change

If this is + * a new subscription and the retroactive is false, then the last message + * sent to the topic should be set as the last message acknowledged by they + * new subscription. Otherwise, if retroactive is true, then create the + * subscription without it having an acknowledged message so that on + * recovery, all message recorded for the topic get replayed. * * @param clientId * @param subscriptionName @@ -131,6 +137,5 @@ public interface TopicReferenceStore extends ReferenceStore, TopicMessageStore { * @throws IOException * */ - public void addSubsciption(SubscriptionInfo subscriptionInfo,boolean retroactive) - throws IOException; + public void addSubsciption(SubscriptionInfo subscriptionInfo, boolean retroactive) throws IOException; } diff --git a/activemq-core/src/main/java/org/apache/activemq/store/amq/AMQMessageStore.java b/activemq-core/src/main/java/org/apache/activemq/store/amq/AMQMessageStore.java index 04a1bd49c1..53bea9f035 100644 --- a/activemq-core/src/main/java/org/apache/activemq/store/amq/AMQMessageStore.java +++ b/activemq-core/src/main/java/org/apache/activemq/store/amq/AMQMessageStore.java @@ -24,6 +24,7 @@ import java.util.LinkedHashMap; import java.util.Map.Entry; import java.util.concurrent.CountDownLatch; import java.util.concurrent.atomic.AtomicReference; + import org.apache.activemq.broker.ConnectionContext; import org.apache.activemq.command.ActiveMQDestination; import org.apache.activemq.command.DataStructure; @@ -51,78 +52,82 @@ import org.apache.commons.logging.LogFactory; * * @version $Revision: 1.14 $ */ -public class AMQMessageStore implements MessageStore{ +public class AMQMessageStore implements MessageStore { - private static final Log log=LogFactory.getLog(AMQMessageStore.class); + private static final Log LOG = LogFactory.getLog(AMQMessageStore.class); protected final AMQPersistenceAdapter peristenceAdapter; protected final AMQTransactionStore transactionStore; protected final ReferenceStore referenceStore; protected final ActiveMQDestination destination; protected final TransactionTemplate transactionTemplate; - private LinkedHashMap messages=new LinkedHashMap(); - private ArrayList messageAcks=new ArrayList(); + private LinkedHashMap messages = new LinkedHashMap(); + private ArrayList messageAcks = new ArrayList(); /** A MessageStore that we can use to retrieve messages quickly. */ - private LinkedHashMap cpAddedMessageIds; + private LinkedHashMap cpAddedMessageIds; protected Location lastLocation; protected Location lastWrittenLocation; - protected HashSet inFlightTxLocations=new HashSet(); + protected HashSet inFlightTxLocations = new HashSet(); protected final TaskRunner asyncWriteTask; protected CountDownLatch flushLatch; - private final boolean debug=log.isDebugEnabled(); - private final AtomicReference mark=new AtomicReference(); - - public AMQMessageStore(AMQPersistenceAdapter adapter,ReferenceStore referenceStore,ActiveMQDestination destination){ - this.peristenceAdapter=adapter; - this.transactionStore=adapter.getTransactionStore(); - this.referenceStore=referenceStore; - this.destination=destination; - this.transactionTemplate=new TransactionTemplate(adapter,new ConnectionContext()); - asyncWriteTask=adapter.getTaskRunnerFactory().createTaskRunner(new Task(){ + private final boolean debug = LOG.isDebugEnabled(); + private final AtomicReference mark = new AtomicReference(); - public boolean iterate(){ + public AMQMessageStore(AMQPersistenceAdapter adapter, ReferenceStore referenceStore, ActiveMQDestination destination) { + this.peristenceAdapter = adapter; + this.transactionStore = adapter.getTransactionStore(); + this.referenceStore = referenceStore; + this.destination = destination; + this.transactionTemplate = new TransactionTemplate(adapter, new ConnectionContext()); + asyncWriteTask = adapter.getTaskRunnerFactory().createTaskRunner(new Task() { + + public boolean iterate() { asyncWrite(); return false; } - },"Checkpoint: "+destination); + }, "Checkpoint: " + destination); } - public void setUsageManager(UsageManager usageManager){ + public void setUsageManager(UsageManager usageManager) { referenceStore.setUsageManager(usageManager); } /** - * Not synchronized since the Journal has better throughput if you increase the number of concurrent writes that it - * is doing. + * Not synchronized since the Journal has better throughput if you increase + * the number of concurrent writes that it is doing. */ - public void addMessage(ConnectionContext context,final Message message) throws IOException{ - final MessageId id=message.getMessageId(); - final Location location=peristenceAdapter.writeCommand(message,message.isResponseRequired()); - if(!context.isInTransaction()){ - if(debug) - log.debug("Journalled message add for: "+id+", at: "+location); - addMessage(message,location); - }else{ - if(debug) - log.debug("Journalled transacted message add for: "+id+", at: "+location); - synchronized(this){ + public void addMessage(ConnectionContext context, final Message message) throws IOException { + final MessageId id = message.getMessageId(); + final Location location = peristenceAdapter.writeCommand(message, message.isResponseRequired()); + if (!context.isInTransaction()) { + if (debug) { + LOG.debug("Journalled message add for: " + id + ", at: " + location); + } + addMessage(message, location); + } else { + if (debug) { + LOG.debug("Journalled transacted message add for: " + id + ", at: " + location); + } + synchronized (this) { inFlightTxLocations.add(location); } - transactionStore.addMessage(this,message,location); - context.getTransaction().addSynchronization(new Synchronization(){ + transactionStore.addMessage(this, message, location); + context.getTransaction().addSynchronization(new Synchronization() { - public void afterCommit() throws Exception{ - if(debug) - log.debug("Transacted message add commit for: "+id+", at: "+location); - synchronized(AMQMessageStore.this){ + public void afterCommit() throws Exception { + if (debug) { + LOG.debug("Transacted message add commit for: " + id + ", at: " + location); + } + synchronized (AMQMessageStore.this) { inFlightTxLocations.remove(location); - addMessage(message,location); + addMessage(message, location); } } - public void afterRollback() throws Exception{ - if(debug) - log.debug("Transacted message add rollback for: "+id+", at: "+location); - synchronized(AMQMessageStore.this){ + public void afterRollback() throws Exception { + if (debug) { + LOG.debug("Transacted message add rollback for: " + id + ", at: " + location); + } + synchronized (AMQMessageStore.this) { inFlightTxLocations.remove(location); } } @@ -130,74 +135,78 @@ public class AMQMessageStore implements MessageStore{ } } - void addMessage(final Message message,final Location location) throws InterruptedIOException{ - ReferenceData data=new ReferenceData(); + void addMessage(final Message message, final Location location) throws InterruptedIOException { + ReferenceData data = new ReferenceData(); data.setExpiration(message.getExpiration()); data.setFileId(location.getDataFileId()); data.setOffset(location.getOffset()); - synchronized(this){ - lastLocation=location; - messages.put(message.getMessageId(),data); + synchronized (this) { + lastLocation = location; + messages.put(message.getMessageId(), data); } - try{ + try { asyncWriteTask.wakeup(); - }catch(InterruptedException e){ + } catch (InterruptedException e) { throw new InterruptedIOException(); } } - public boolean replayAddMessage(ConnectionContext context,Message message,Location location){ - MessageId id=message.getMessageId(); - try{ + public boolean replayAddMessage(ConnectionContext context, Message message, Location location) { + MessageId id = message.getMessageId(); + try { // Only add the message if it has not already been added. - ReferenceData data=referenceStore.getMessageReference(id); - if(data==null){ - data=new ReferenceData(); + ReferenceData data = referenceStore.getMessageReference(id); + if (data == null) { + data = new ReferenceData(); data.setExpiration(message.getExpiration()); data.setFileId(location.getDataFileId()); data.setOffset(location.getOffset()); - referenceStore.addMessageReference(context,id,data); + referenceStore.addMessageReference(context, id, data); return true; } - }catch(Throwable e){ - log.warn("Could not replay add for message '"+id+"'. Message may have already been added. reason: "+e,e); + } catch (Throwable e) { + LOG.warn("Could not replay add for message '" + id + "'. Message may have already been added. reason: " + e, e); } return false; } /** */ - public void removeMessage(ConnectionContext context,final MessageAck ack) throws IOException{ - JournalQueueAck remove=new JournalQueueAck(); + public void removeMessage(ConnectionContext context, final MessageAck ack) throws IOException { + JournalQueueAck remove = new JournalQueueAck(); remove.setDestination(destination); remove.setMessageAck(ack); - final Location location=peristenceAdapter.writeCommand(remove,ack.isResponseRequired()); - if(!context.isInTransaction()){ - if(debug) - log.debug("Journalled message remove for: "+ack.getLastMessageId()+", at: "+location); - removeMessage(ack,location); - }else{ - if(debug) - log.debug("Journalled transacted message remove for: "+ack.getLastMessageId()+", at: "+location); - synchronized(this){ + final Location location = peristenceAdapter.writeCommand(remove, ack.isResponseRequired()); + if (!context.isInTransaction()) { + if (debug) { + LOG.debug("Journalled message remove for: " + ack.getLastMessageId() + ", at: " + location); + } + removeMessage(ack, location); + } else { + if (debug) { + LOG.debug("Journalled transacted message remove for: " + ack.getLastMessageId() + ", at: " + location); + } + synchronized (this) { inFlightTxLocations.add(location); } - transactionStore.removeMessage(this,ack,location); - context.getTransaction().addSynchronization(new Synchronization(){ + transactionStore.removeMessage(this, ack, location); + context.getTransaction().addSynchronization(new Synchronization() { - public void afterCommit() throws Exception{ - if(debug) - log.debug("Transacted message remove commit for: "+ack.getLastMessageId()+", at: "+location); - synchronized(AMQMessageStore.this){ + public void afterCommit() throws Exception { + if (debug) { + LOG.debug("Transacted message remove commit for: " + ack.getLastMessageId() + ", at: " + location); + } + synchronized (AMQMessageStore.this) { inFlightTxLocations.remove(location); - removeMessage(ack,location); + removeMessage(ack, location); } } - public void afterRollback() throws Exception{ - if(debug) - log.debug("Transacted message remove rollback for: "+ack.getLastMessageId()+", at: "+location); - synchronized(AMQMessageStore.this){ + public void afterRollback() throws Exception { + if (debug) { + LOG.debug("Transacted message remove rollback for: " + ack.getLastMessageId() + ", at: " + location); + } + synchronized (AMQMessageStore.this) { inFlightTxLocations.remove(location); } } @@ -205,36 +214,35 @@ public class AMQMessageStore implements MessageStore{ } } - final void removeMessage(final MessageAck ack,final Location location) throws InterruptedIOException{ + final void removeMessage(final MessageAck ack, final Location location) throws InterruptedIOException { ReferenceData data; - synchronized(this){ - lastLocation=location; - MessageId id=ack.getLastMessageId(); - data=messages.remove(id); - if(data==null){ + synchronized (this) { + lastLocation = location; + MessageId id = ack.getLastMessageId(); + data = messages.remove(id); + if (data == null) { messageAcks.add(ack); } } - if(data==null){ - try{ + if (data == null) { + try { asyncWriteTask.wakeup(); - }catch(InterruptedException e){ + } catch (InterruptedException e) { throw new InterruptedIOException(); } } } - public boolean replayRemoveMessage(ConnectionContext context,MessageAck messageAck){ - try{ + public boolean replayRemoveMessage(ConnectionContext context, MessageAck messageAck) { + try { // Only remove the message if it has not already been removed. - ReferenceData t=referenceStore.getMessageReference(messageAck.getLastMessageId()); - if(t!=null){ - referenceStore.removeMessage(context,messageAck); + ReferenceData t = referenceStore.getMessageReference(messageAck.getLastMessageId()); + if (t != null) { + referenceStore.removeMessage(context, messageAck); return true; } - }catch(Throwable e){ - log.warn("Could not replay acknowledge for message '"+messageAck.getLastMessageId() - +"'. Message may have already been acknowledged. reason: "+e); + } catch (Throwable e) { + LOG.warn("Could not replay acknowledge for message '" + messageAck.getLastMessageId() + "'. Message may have already been acknowledged. reason: " + e); } return false; } @@ -244,28 +252,28 @@ public class AMQMessageStore implements MessageStore{ * * @throws InterruptedIOException */ - public void flush() throws InterruptedIOException{ - if(log.isDebugEnabled()){ - log.debug("flush starting ..."); + public void flush() throws InterruptedIOException { + if (LOG.isDebugEnabled()) { + LOG.debug("flush starting ..."); } CountDownLatch countDown; - synchronized(this){ - if(lastWrittenLocation==lastLocation){ + synchronized (this) { + if (lastWrittenLocation == lastLocation) { return; } - if(flushLatch==null){ - flushLatch=new CountDownLatch(1); + if (flushLatch == null) { + flushLatch = new CountDownLatch(1); } - countDown=flushLatch; + countDown = flushLatch; } - try{ + try { asyncWriteTask.wakeup(); countDown.await(); - }catch(InterruptedException e){ + } catch (InterruptedException e) { throw new InterruptedIOException(); } - if(log.isDebugEnabled()){ - log.debug("flush finished"); + if (LOG.isDebugEnabled()) { + LOG.debug("flush finished"); } } @@ -273,19 +281,19 @@ public class AMQMessageStore implements MessageStore{ * @return * @throws IOException */ - void asyncWrite(){ - try{ + void asyncWrite() { + try { CountDownLatch countDown; - synchronized(this){ - countDown=flushLatch; - flushLatch=null; + synchronized (this) { + countDown = flushLatch; + flushLatch = null; } mark.set(doAsyncWrite()); - if(countDown!=null){ + if (countDown != null) { countDown.countDown(); } - }catch(IOException e){ - log.error("Checkpoint failed: "+e,e); + } catch (IOException e) { + LOG.error("Checkpoint failed: " + e, e); } } @@ -293,67 +301,67 @@ public class AMQMessageStore implements MessageStore{ * @return * @throws IOException */ - protected Location doAsyncWrite() throws IOException{ + protected Location doAsyncWrite() throws IOException { final ArrayList cpRemovedMessageLocations; final ArrayList cpActiveJournalLocations; - final int maxCheckpointMessageAddSize=peristenceAdapter.getMaxCheckpointMessageAddSize(); + final int maxCheckpointMessageAddSize = peristenceAdapter.getMaxCheckpointMessageAddSize(); final Location lastLocation; // swap out the message hash maps.. - synchronized(this){ - cpAddedMessageIds=this.messages; - cpRemovedMessageLocations=this.messageAcks; - cpActiveJournalLocations=new ArrayList(inFlightTxLocations); - this.messages=new LinkedHashMap(); - this.messageAcks=new ArrayList(); - lastLocation=this.lastLocation; + synchronized (this) { + cpAddedMessageIds = this.messages; + cpRemovedMessageLocations = this.messageAcks; + cpActiveJournalLocations = new ArrayList(inFlightTxLocations); + this.messages = new LinkedHashMap(); + this.messageAcks = new ArrayList(); + lastLocation = this.lastLocation; } - if(log.isDebugEnabled()) - log.debug("Doing batch update... adding: "+cpAddedMessageIds.size()+" removing: " - +cpRemovedMessageLocations.size()+" "); - transactionTemplate.run(new Callback(){ + if (LOG.isDebugEnabled()) { + LOG.debug("Doing batch update... adding: " + cpAddedMessageIds.size() + " removing: " + cpRemovedMessageLocations.size() + " "); + } + transactionTemplate.run(new Callback() { - public void execute() throws Exception{ - int size=0; - PersistenceAdapter persitanceAdapter=transactionTemplate.getPersistenceAdapter(); - ConnectionContext context=transactionTemplate.getContext(); + public void execute() throws Exception { + int size = 0; + PersistenceAdapter persitanceAdapter = transactionTemplate.getPersistenceAdapter(); + ConnectionContext context = transactionTemplate.getContext(); // Checkpoint the added messages. - Iterator> iterator=cpAddedMessageIds.entrySet().iterator(); - while(iterator.hasNext()){ - Entry entry=iterator.next(); - try{ - referenceStore.addMessageReference(context,entry.getKey(),entry.getValue()); - }catch(Throwable e){ - log.warn("Message could not be added to long term store: "+e.getMessage(),e); + Iterator> iterator = cpAddedMessageIds.entrySet().iterator(); + while (iterator.hasNext()) { + Entry entry = iterator.next(); + try { + referenceStore.addMessageReference(context, entry.getKey(), entry.getValue()); + } catch (Throwable e) { + LOG.warn("Message could not be added to long term store: " + e.getMessage(), e); } size++; // Commit the batch if it's getting too big - if(size>=maxCheckpointMessageAddSize){ + if (size >= maxCheckpointMessageAddSize) { persitanceAdapter.commitTransaction(context); persitanceAdapter.beginTransaction(context); - size=0; + size = 0; } } persitanceAdapter.commitTransaction(context); persitanceAdapter.beginTransaction(context); // Checkpoint the removed messages. - for(MessageAck ack:cpRemovedMessageLocations){ - try{ - referenceStore.removeMessage(transactionTemplate.getContext(),ack); - }catch(Throwable e){ - log.warn("Message could not be removed from long term store: "+e.getMessage(),e); + for (MessageAck ack : cpRemovedMessageLocations) { + try { + referenceStore.removeMessage(transactionTemplate.getContext(), ack); + } catch (Throwable e) { + LOG.warn("Message could not be removed from long term store: " + e.getMessage(), e); } } } }); - log.debug("Batch update done."); - synchronized(this){ - cpAddedMessageIds=null; - lastWrittenLocation=lastLocation; + LOG.debug("Batch update done."); + synchronized (this) { + cpAddedMessageIds = null; + lastWrittenLocation = lastLocation; } - if(cpActiveJournalLocations.size()>0){ + if (cpActiveJournalLocations.size() > 0) { Collections.sort(cpActiveJournalLocations); return cpActiveJournalLocations.get(0); - }else{ + } else { return lastLocation; } } @@ -361,50 +369,50 @@ public class AMQMessageStore implements MessageStore{ /** * */ - public Message getMessage(MessageId identity) throws IOException{ - ReferenceData data=null; - synchronized(this){ + public Message getMessage(MessageId identity) throws IOException { + ReferenceData data = null; + synchronized (this) { // Is it still in flight??? - data=messages.get(identity); - if(data==null&&cpAddedMessageIds!=null){ - data=cpAddedMessageIds.get(identity); + data = messages.get(identity); + if (data == null && cpAddedMessageIds != null) { + data = cpAddedMessageIds.get(identity); } } - if(data==null){ - data=referenceStore.getMessageReference(identity); - if(data==null){ + if (data == null) { + data = referenceStore.getMessageReference(identity); + if (data == null) { return null; } } - Location location=new Location(); + Location location = new Location(); location.setDataFileId(data.getFileId()); location.setOffset(data.getOffset()); - DataStructure rc=peristenceAdapter.readCommand(location); - try{ + DataStructure rc = peristenceAdapter.readCommand(location); + try { return (Message)rc; - }catch(ClassCastException e){ - throw new IOException("Could not read message "+identity+" at location "+location - +", expected a message, but got: "+rc); + } catch (ClassCastException e) { + throw new IOException("Could not read message " + identity + " at location " + location + ", expected a message, but got: " + rc); } } /** - * Replays the referenceStore first as those messages are the oldest ones, then messages are replayed from the - * transaction log and then the cache is updated. + * Replays the referenceStore first as those messages are the oldest ones, + * then messages are replayed from the transaction log and then the cache is + * updated. * * @param listener * @throws Exception */ - public void recover(final MessageRecoveryListener listener) throws Exception{ + public void recover(final MessageRecoveryListener listener) throws Exception { flush(); - referenceStore.recover(new RecoveryListenerAdapter(this,listener)); + referenceStore.recover(new RecoveryListenerAdapter(this, listener)); } - public void start() throws Exception{ + public void start() throws Exception { referenceStore.start(); } - public void stop() throws Exception{ + public void stop() throws Exception { flush(); asyncWriteTask.shutdown(); referenceStore.stop(); @@ -413,28 +421,27 @@ public class AMQMessageStore implements MessageStore{ /** * @return Returns the longTermStore. */ - public ReferenceStore getReferenceStore(){ + public ReferenceStore getReferenceStore() { return referenceStore; } /** * @see org.apache.activemq.store.MessageStore#removeAllMessages(ConnectionContext) */ - public void removeAllMessages(ConnectionContext context) throws IOException{ + public void removeAllMessages(ConnectionContext context) throws IOException { flush(); referenceStore.removeAllMessages(context); } - public ActiveMQDestination getDestination(){ + public ActiveMQDestination getDestination() { return destination; } - public void addMessageReference(ConnectionContext context,MessageId messageId,long expirationTime,String messageRef) - throws IOException{ + public void addMessageReference(ConnectionContext context, MessageId messageId, long expirationTime, String messageRef) throws IOException { throw new IOException("The journal does not support message references."); } - public String getMessageReference(MessageId identity) throws IOException{ + public String getMessageReference(MessageId identity) throws IOException { throw new IOException("The journal does not support message references."); } @@ -443,61 +450,54 @@ public class AMQMessageStore implements MessageStore{ * @throws IOException * @see org.apache.activemq.store.MessageStore#getMessageCount() */ - public int getMessageCount() throws IOException{ + public int getMessageCount() throws IOException { flush(); return referenceStore.getMessageCount(); } - public void recoverNextMessages(int maxReturned,MessageRecoveryListener listener) throws Exception{ + public void recoverNextMessages(int maxReturned, MessageRecoveryListener listener) throws Exception { /* - RecoveryListenerAdapter recoveryListener=new RecoveryListenerAdapter(this,listener); - if(referenceStore.supportsExternalBatchControl()){ - synchronized(this){ - referenceStore.recoverNextMessages(maxReturned,recoveryListener); - if(recoveryListener.size()==0&&recoveryListener.hasSpace()){ - // check for inflight messages - int count=0; - Iterator> iterator=messages.entrySet().iterator(); - while(iterator.hasNext()&&count entry=iterator.next(); - ReferenceData data=entry.getValue(); - Message message=getMessage(data); - recoveryListener.recoverMessage(message); - count++; - } - referenceStore.setBatch(recoveryListener.getLastRecoveredMessageId()); - } - } - }else{ + * RecoveryListenerAdapter recoveryListener=new + * RecoveryListenerAdapter(this,listener); + * if(referenceStore.supportsExternalBatchControl()){ + * synchronized(this){ + * referenceStore.recoverNextMessages(maxReturned,recoveryListener); + * if(recoveryListener.size()==0&&recoveryListener.hasSpace()){ // check + * for inflight messages int count=0; Iterator> + * iterator=messages.entrySet().iterator(); + * while(iterator.hasNext()&&count entry=iterator.next(); ReferenceData + * data=entry.getValue(); Message message=getMessage(data); + * recoveryListener.recoverMessage(message); count++; } + * referenceStore.setBatch(recoveryListener.getLastRecoveredMessageId()); } } + * }else{ flush(); + * referenceStore.recoverNextMessages(maxReturned,recoveryListener); } + */ + RecoveryListenerAdapter recoveryListener = new RecoveryListenerAdapter(this, listener); + referenceStore.recoverNextMessages(maxReturned, recoveryListener); + if (recoveryListener.size() == 0 && recoveryListener.hasSpace()) { flush(); - referenceStore.recoverNextMessages(maxReturned,recoveryListener); - } - */ - RecoveryListenerAdapter recoveryListener=new RecoveryListenerAdapter(this,listener); - referenceStore.recoverNextMessages(maxReturned,recoveryListener); - if(recoveryListener.size()==0&&recoveryListener.hasSpace()){ - flush(); - referenceStore.recoverNextMessages(maxReturned,recoveryListener); + referenceStore.recoverNextMessages(maxReturned, recoveryListener); } } - Message getMessage(ReferenceData data) throws IOException{ - Location location=new Location(); + Message getMessage(ReferenceData data) throws IOException { + Location location = new Location(); location.setDataFileId(data.getFileId()); location.setOffset(data.getOffset()); - DataStructure rc=peristenceAdapter.readCommand(location); - try{ + DataStructure rc = peristenceAdapter.readCommand(location); + try { return (Message)rc; - }catch(ClassCastException e){ - throw new IOException("Could not read message at location "+location+", expected a message, but got: "+rc); + } catch (ClassCastException e) { + throw new IOException("Could not read message at location " + location + ", expected a message, but got: " + rc); } } - public void resetBatching(){ + public void resetBatching() { referenceStore.resetBatching(); } - public Location getMark(){ + public Location getMark() { return mark.get(); } -} \ No newline at end of file +} diff --git a/activemq-core/src/main/java/org/apache/activemq/store/amq/AMQPersistenceAdapter.java b/activemq-core/src/main/java/org/apache/activemq/store/amq/AMQPersistenceAdapter.java index b3d622c894..b8cee6d443 100644 --- a/activemq-core/src/main/java/org/apache/activemq/store/amq/AMQPersistenceAdapter.java +++ b/activemq-core/src/main/java/org/apache/activemq/store/amq/AMQPersistenceAdapter.java @@ -22,10 +22,11 @@ import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CountDownLatch; import java.util.concurrent.atomic.AtomicBoolean; + import org.apache.activeio.journal.Journal; -import org.apache.activemq.broker.ConnectionContext; -import org.apache.activemq.broker.BrokerServiceAware; import org.apache.activemq.broker.BrokerService; +import org.apache.activemq.broker.BrokerServiceAware; +import org.apache.activemq.broker.ConnectionContext; import org.apache.activemq.command.ActiveMQDestination; import org.apache.activemq.command.ActiveMQQueue; import org.apache.activemq.command.ActiveMQTopic; @@ -35,7 +36,6 @@ import org.apache.activemq.command.JournalTopicAck; import org.apache.activemq.command.JournalTrace; import org.apache.activemq.command.JournalTransaction; import org.apache.activemq.command.Message; -import org.apache.activemq.command.MessageAck; import org.apache.activemq.kaha.impl.async.AsyncDataManager; import org.apache.activemq.kaha.impl.async.Location; import org.apache.activemq.memory.UsageListener; @@ -62,46 +62,46 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** - * An implementation of {@link PersistenceAdapter} designed for use with a {@link Journal} and then check pointing - * asynchronously on a timeout with some other long term persistent storage. + * An implementation of {@link PersistenceAdapter} designed for use with a + * {@link Journal} and then check pointing asynchronously on a timeout with some + * other long term persistent storage. * * @org.apache.xbean.XBean element="amqPersistenceAdapter" - * * @version $Revision: 1.17 $ */ public class AMQPersistenceAdapter implements PersistenceAdapter, UsageListener, BrokerServiceAware { - private static final Log log=LogFactory.getLog(AMQPersistenceAdapter.class); - private final ConcurrentHashMap queues=new ConcurrentHashMap(); - private final ConcurrentHashMap topics=new ConcurrentHashMap(); + private static final Log log = LogFactory.getLog(AMQPersistenceAdapter.class); + private final ConcurrentHashMap queues = new ConcurrentHashMap(); + private final ConcurrentHashMap topics = new ConcurrentHashMap(); private AsyncDataManager asyncDataManager; private ReferenceStoreAdapter referenceStoreAdapter; private TaskRunnerFactory taskRunnerFactory; - private WireFormat wireFormat=new OpenWireFormat(); + private WireFormat wireFormat = new OpenWireFormat(); private UsageManager usageManager; - private long cleanupInterval=1000*60; - private long checkpointInterval=1000*10; - private int maxCheckpointWorkers=1; - private int maxCheckpointMessageAddSize=1024*4; - private AMQTransactionStore transactionStore=new AMQTransactionStore(this); + private long cleanupInterval = 1000 * 60; + private long checkpointInterval = 1000 * 10; + private int maxCheckpointWorkers = 1; + private int maxCheckpointMessageAddSize = 1024 * 4; + private AMQTransactionStore transactionStore = new AMQTransactionStore(this); private TaskRunner checkpointTask; - private CountDownLatch nextCheckpointCountDownLatch=new CountDownLatch(1); - private final AtomicBoolean started=new AtomicBoolean(false); + private CountDownLatch nextCheckpointCountDownLatch = new CountDownLatch(1); + private final AtomicBoolean started = new AtomicBoolean(false); private Runnable periodicCheckpointTask; private Runnable periodicCleanupTask; private boolean deleteAllMessages; private boolean syncOnWrite; - private String brokerName=""; + private String brokerName = ""; private File directory; private BrokerService brokerService; - public String getBrokerName(){ + public String getBrokerName() { return this.brokerName; } - public void setBrokerName(String brokerName){ - this.brokerName=brokerName; - if(this.referenceStoreAdapter!=null){ + public void setBrokerName(String brokerName) { + this.brokerName = brokerName; + if (this.referenceStoreAdapter != null) { this.referenceStoreAdapter.setBrokerName(brokerName); } } @@ -114,165 +114,170 @@ public class AMQPersistenceAdapter implements PersistenceAdapter, UsageListener, this.brokerService = brokerService; } - public synchronized void start() throws Exception{ - if(!started.compareAndSet(false,true)) + public synchronized void start() throws Exception { + if (!started.compareAndSet(false, true)) { return; - if(this.directory==null) { + } + if (this.directory == null) { if (brokerService != null) { this.directory = brokerService.getBrokerDataDirectory(); - } - else { - this.directory=new File(IOHelper.getDefaultDataDirectory(),brokerName); - this.directory=new File(directory,"amqstore"); + } else { + this.directory = new File(IOHelper.getDefaultDataDirectory(), brokerName); + this.directory = new File(directory, "amqstore"); } } log.info("AMQStore starting using directory: " + directory); this.directory.mkdirs(); - if(this.usageManager!=null){ + if (this.usageManager != null) { this.usageManager.addUsageListener(this); } - if(asyncDataManager==null){ - asyncDataManager=createAsyncDataManager(); + if (asyncDataManager == null) { + asyncDataManager = createAsyncDataManager(); } - if(referenceStoreAdapter==null){ - referenceStoreAdapter=createReferenceStoreAdapter(); + if (referenceStoreAdapter == null) { + referenceStoreAdapter = createReferenceStoreAdapter(); } - referenceStoreAdapter.setDirectory(new File(directory,"kr-store")); + referenceStoreAdapter.setDirectory(new File(directory, "kr-store")); referenceStoreAdapter.setBrokerName(getBrokerName()); referenceStoreAdapter.setUsageManager(usageManager); - if(taskRunnerFactory==null){ - taskRunnerFactory=createTaskRunnerFactory(); + if (taskRunnerFactory == null) { + taskRunnerFactory = createTaskRunnerFactory(); } asyncDataManager.start(); - if(deleteAllMessages){ + if (deleteAllMessages) { asyncDataManager.delete(); - try{ - JournalTrace trace=new JournalTrace(); - trace.setMessage("DELETED "+new Date()); - Location location=asyncDataManager.write(wireFormat.marshal(trace),false); - asyncDataManager.setMark(location,true); + try { + JournalTrace trace = new JournalTrace(); + trace.setMessage("DELETED " + new Date()); + Location location = asyncDataManager.write(wireFormat.marshal(trace), false); + asyncDataManager.setMark(location, true); log.info("Journal deleted: "); - deleteAllMessages=false; - }catch(IOException e){ + deleteAllMessages = false; + } catch (IOException e) { throw e; - }catch(Throwable e){ + } catch (Throwable e) { throw IOExceptionSupport.create(e); } referenceStoreAdapter.deleteAllMessages(); } referenceStoreAdapter.start(); - Set files=referenceStoreAdapter.getReferenceFileIdsInUse(); - log.info("Active data files: "+files); - checkpointTask=taskRunnerFactory.createTaskRunner(new Task(){ + Set files = referenceStoreAdapter.getReferenceFileIdsInUse(); + log.info("Active data files: " + files); + checkpointTask = taskRunnerFactory.createTaskRunner(new Task() { - public boolean iterate(){ + public boolean iterate() { doCheckpoint(); return false; } - },"ActiveMQ Journal Checkpoint Worker"); + }, "ActiveMQ Journal Checkpoint Worker"); createTransactionStore(); - -// -// The following was attempting to reduce startup times by avoiding the log -// file scanning that recovery performs. The problem with it is that XA transactions -// only live in transaction log and are not stored in the reference store, but they still -// need to be recovered when the broker starts up. - - if(referenceStoreAdapter.isStoreValid()==false){ + + // + // The following was attempting to reduce startup times by avoiding the + // log + // file scanning that recovery performs. The problem with it is that XA + // transactions + // only live in transaction log and are not stored in the reference + // store, but they still + // need to be recovered when the broker starts up. + + if (referenceStoreAdapter.isStoreValid() == false) { log.warn("The ReferenceStore is not valid - recovering ..."); recover(); log.info("Finished recovering the ReferenceStore"); - }else { - Location location=writeTraceMessage("RECOVERED "+new Date(),true); - asyncDataManager.setMark(location,true); - //recover transactions + } else { + Location location = writeTraceMessage("RECOVERED " + new Date(), true); + asyncDataManager.setMark(location, true); + // recover transactions getTransactionStore().setPreparedTransactions(referenceStoreAdapter.retrievePreparedState()); - } - - - // Do a checkpoint periodically. - periodicCheckpointTask=new Runnable(){ + } - public void run(){ + // Do a checkpoint periodically. + periodicCheckpointTask = new Runnable() { + + public void run() { checkpoint(false); } }; - Scheduler.executePeriodically(periodicCheckpointTask,checkpointInterval); - periodicCleanupTask=new Runnable(){ + Scheduler.executePeriodically(periodicCheckpointTask, checkpointInterval); + periodicCleanupTask = new Runnable() { - public void run(){ + public void run() { cleanup(); } }; - Scheduler.executePeriodically(periodicCleanupTask,cleanupInterval); + Scheduler.executePeriodically(periodicCleanupTask, cleanupInterval); } - public void stop() throws Exception{ - - if(!started.compareAndSet(true,false)) + public void stop() throws Exception { + + if (!started.compareAndSet(true, false)) { return; + } this.usageManager.removeUsageListener(this); - synchronized(this){ + synchronized (this) { Scheduler.cancel(periodicCheckpointTask); Scheduler.cancel(periodicCleanupTask); } - Iterator iterator=queues.values().iterator(); - while(iterator.hasNext()){ - AMQMessageStore ms=iterator.next(); + Iterator iterator = queues.values().iterator(); + while (iterator.hasNext()) { + AMQMessageStore ms = iterator.next(); ms.stop(); } - iterator=topics.values().iterator(); - while(iterator.hasNext()){ - final AMQTopicMessageStore ms=(AMQTopicMessageStore)iterator.next(); + iterator = topics.values().iterator(); + while (iterator.hasNext()) { + final AMQTopicMessageStore ms = (AMQTopicMessageStore)iterator.next(); ms.stop(); } // Take one final checkpoint and stop checkpoint processing. checkpoint(true); - synchronized(this){ + synchronized (this) { checkpointTask.shutdown(); } referenceStoreAdapter.savePreparedState(getTransactionStore().getPreparedTransactions()); queues.clear(); topics.clear(); - IOException firstException=null; + IOException firstException = null; referenceStoreAdapter.stop(); - try{ + try { log.debug("Journal close"); asyncDataManager.close(); - }catch(Exception e){ - firstException=IOExceptionSupport.create("Failed to close journals: "+e,e); + } catch (Exception e) { + firstException = IOExceptionSupport.create("Failed to close journals: " + e, e); } - if(firstException!=null){ + if (firstException != null) { throw firstException; } } /** * When we checkpoint we move all the journalled data to long term storage. - * @param sync + * + * @param sync */ - public void checkpoint(boolean sync){ - try{ - if(asyncDataManager==null) + public void checkpoint(boolean sync) { + try { + if (asyncDataManager == null) { throw new IllegalStateException("Journal is closed."); - CountDownLatch latch=null; - synchronized(this){ - latch=nextCheckpointCountDownLatch; + } + CountDownLatch latch = null; + synchronized (this) { + latch = nextCheckpointCountDownLatch; checkpointTask.wakeup(); } - if(sync){ - if(log.isDebugEnabled()){ + if (sync) { + if (log.isDebugEnabled()) { log.debug("Waitng for checkpoint to complete."); } latch.await(); } referenceStoreAdapter.checkpoint(sync); - }catch(InterruptedException e){ + } catch (InterruptedException e) { Thread.currentThread().interrupt(); - log.warn("Request to start checkpoint failed: "+e,e); - }catch(IOException e){ - log.error("checkpoint failed: "+e,e); + log.warn("Request to start checkpoint failed: " + e, e); + } catch (IOException e) { + log.error("checkpoint failed: " + e, e); } } @@ -281,49 +286,49 @@ public class AMQPersistenceAdapter implements PersistenceAdapter, UsageListener, * * @return true if successful */ - public boolean doCheckpoint(){ - CountDownLatch latch=null; - synchronized(this){ - latch=nextCheckpointCountDownLatch; - nextCheckpointCountDownLatch=new CountDownLatch(1); + public boolean doCheckpoint() { + CountDownLatch latch = null; + synchronized (this) { + latch = nextCheckpointCountDownLatch; + nextCheckpointCountDownLatch = new CountDownLatch(1); } - try{ - if(log.isDebugEnabled()){ + try { + if (log.isDebugEnabled()) { log.debug("Checkpoint started."); } - - Location newMark=null; - Iterator iterator=queues.values().iterator(); - while(iterator.hasNext()){ - final AMQMessageStore ms=iterator.next(); - Location mark=(Location)ms.getMark(); - if(mark!=null&&(newMark==null||newMark.compareTo(mark)<0)){ - newMark=mark; + + Location newMark = null; + Iterator iterator = queues.values().iterator(); + while (iterator.hasNext()) { + final AMQMessageStore ms = iterator.next(); + Location mark = (Location)ms.getMark(); + if (mark != null && (newMark == null || newMark.compareTo(mark) < 0)) { + newMark = mark; } } - iterator=topics.values().iterator(); - while(iterator.hasNext()){ - final AMQTopicMessageStore ms=(AMQTopicMessageStore)iterator.next(); - Location mark=(Location)ms.getMark(); - if(mark!=null&&(newMark==null||newMark.compareTo(mark)<0)){ - newMark=mark; + iterator = topics.values().iterator(); + while (iterator.hasNext()) { + final AMQTopicMessageStore ms = (AMQTopicMessageStore)iterator.next(); + Location mark = (Location)ms.getMark(); + if (mark != null && (newMark == null || newMark.compareTo(mark) < 0)) { + newMark = mark; } } - try{ - if(newMark!=null){ - if(log.isDebugEnabled()){ - log.debug("Marking journal at: "+newMark); + try { + if (newMark != null) { + if (log.isDebugEnabled()) { + log.debug("Marking journal at: " + newMark); } - asyncDataManager.setMark(newMark,false); - writeTraceMessage("CHECKPOINT "+new Date(),true); + asyncDataManager.setMark(newMark, false); + writeTraceMessage("CHECKPOINT " + new Date(), true); } - }catch(Exception e){ - log.error("Failed to mark the Journal: "+e,e); + } catch (Exception e) { + log.error("Failed to mark the Journal: " + e, e); } - if(log.isDebugEnabled()){ + if (log.isDebugEnabled()) { log.debug("Checkpoint done."); } - }finally{ + } finally { latch.countDown(); } return true; @@ -335,79 +340,77 @@ public class AMQPersistenceAdapter implements PersistenceAdapter, UsageListener, * @return * @throws IOException */ - public void cleanup(){ - try{ - Set inUse=referenceStoreAdapter.getReferenceFileIdsInUse(); + public void cleanup() { + try { + Set inUse = referenceStoreAdapter.getReferenceFileIdsInUse(); asyncDataManager.consolidateDataFilesNotIn(inUse); - }catch(IOException e){ - log.error("Could not cleanup data files: "+e,e); + } catch (IOException e) { + log.error("Could not cleanup data files: " + e, e); } } - public Set getDestinations(){ - Set destinations=new HashSet(referenceStoreAdapter.getDestinations()); + public Set getDestinations() { + Set destinations = new HashSet(referenceStoreAdapter.getDestinations()); destinations.addAll(queues.keySet()); destinations.addAll(topics.keySet()); return destinations; } - MessageStore createMessageStore(ActiveMQDestination destination) throws IOException{ - if(destination.isQueue()){ + MessageStore createMessageStore(ActiveMQDestination destination) throws IOException { + if (destination.isQueue()) { return createQueueMessageStore((ActiveMQQueue)destination); - }else{ + } else { return createTopicMessageStore((ActiveMQTopic)destination); } } - - - public MessageStore createQueueMessageStore(ActiveMQQueue destination) throws IOException{ - AMQMessageStore store=queues.get(destination); - if(store==null){ - ReferenceStore checkpointStore=referenceStoreAdapter.createQueueReferenceStore(destination); - store=new AMQMessageStore(this,checkpointStore,destination); - try{ + public MessageStore createQueueMessageStore(ActiveMQQueue destination) throws IOException { + AMQMessageStore store = queues.get(destination); + if (store == null) { + ReferenceStore checkpointStore = referenceStoreAdapter.createQueueReferenceStore(destination); + store = new AMQMessageStore(this, checkpointStore, destination); + try { store.start(); - }catch(Exception e){ + } catch (Exception e) { throw IOExceptionSupport.create(e); } - queues.put(destination,store); + queues.put(destination, store); } return store; } - public TopicMessageStore createTopicMessageStore(ActiveMQTopic destinationName) throws IOException{ - AMQTopicMessageStore store=(AMQTopicMessageStore)topics.get(destinationName); - if(store==null){ - TopicReferenceStore checkpointStore=referenceStoreAdapter.createTopicReferenceStore(destinationName); - store=new AMQTopicMessageStore(this,checkpointStore,destinationName); - try{ + public TopicMessageStore createTopicMessageStore(ActiveMQTopic destinationName) throws IOException { + AMQTopicMessageStore store = (AMQTopicMessageStore)topics.get(destinationName); + if (store == null) { + TopicReferenceStore checkpointStore = referenceStoreAdapter.createTopicReferenceStore(destinationName); + store = new AMQTopicMessageStore(this, checkpointStore, destinationName); + try { store.start(); - }catch(Exception e){ + } catch (Exception e) { throw IOExceptionSupport.create(e); } - topics.put(destinationName,store); + topics.put(destinationName, store); } return store; } - public TransactionStore createTransactionStore() throws IOException{ + public TransactionStore createTransactionStore() throws IOException { return transactionStore; } - public long getLastMessageBrokerSequenceId() throws IOException{ + public long getLastMessageBrokerSequenceId() throws IOException { return referenceStoreAdapter.getLastMessageBrokerSequenceId(); } - public void beginTransaction(ConnectionContext context) throws IOException{ + public void beginTransaction(ConnectionContext context) throws IOException { referenceStoreAdapter.beginTransaction(context); } - public void commitTransaction(ConnectionContext context) throws IOException{ + public void commitTransaction(ConnectionContext context) throws IOException { referenceStoreAdapter.commitTransaction(context); } - public void rollbackTransaction(ConnectionContext context) throws IOException{ + public void rollbackTransaction(ConnectionContext context) throws IOException { referenceStoreAdapter.rollbackTransaction(context); } @@ -416,91 +419,93 @@ public class AMQPersistenceAdapter implements PersistenceAdapter, UsageListener, * @return * @throws IOException */ - public DataStructure readCommand(Location location) throws IOException{ - try{ - ByteSequence packet=asyncDataManager.read(location); + public DataStructure readCommand(Location location) throws IOException { + try { + ByteSequence packet = asyncDataManager.read(location); return (DataStructure)wireFormat.unmarshal(packet); - }catch(IOException e){ - throw createReadException(location,e); + } catch (IOException e) { + throw createReadException(location, e); } } /** - * Move all the messages that were in the journal into long term storage. We just replay and do a checkpoint. + * Move all the messages that were in the journal into long term storage. We + * just replay and do a checkpoint. * * @throws IOException * @throws IOException * @throws InvalidLocationException * @throws IllegalStateException */ - private void recover() throws IllegalStateException,IOException{ + private void recover() throws IllegalStateException, IOException { referenceStoreAdapter.clearMessages(); referenceStoreAdapter.recoverState(); - Location pos=null; - int redoCounter=0; - log.info("Journal Recovery Started from: "+asyncDataManager); - long start=System.currentTimeMillis(); - ConnectionContext context=new ConnectionContext(); + Location pos = null; + int redoCounter = 0; + log.info("Journal Recovery Started from: " + asyncDataManager); + long start = System.currentTimeMillis(); + ConnectionContext context = new ConnectionContext(); // While we have records in the journal. - while((pos=asyncDataManager.getNextLocation(pos))!=null){ - ByteSequence data=asyncDataManager.read(pos); - DataStructure c=(DataStructure)wireFormat.unmarshal(data); - if(c instanceof Message){ - Message message=(Message)c; - AMQMessageStore store=(AMQMessageStore)createMessageStore(message.getDestination()); - if(message.isInTransaction()){ - transactionStore.addMessage(store,message,pos); - }else{ - if(store.replayAddMessage(context,message,pos)){ + while ((pos = asyncDataManager.getNextLocation(pos)) != null) { + ByteSequence data = asyncDataManager.read(pos); + DataStructure c = (DataStructure)wireFormat.unmarshal(data); + if (c instanceof Message) { + Message message = (Message)c; + AMQMessageStore store = (AMQMessageStore)createMessageStore(message.getDestination()); + if (message.isInTransaction()) { + transactionStore.addMessage(store, message, pos); + } else { + if (store.replayAddMessage(context, message, pos)) { redoCounter++; } } - }else{ - switch(c.getDataStructureType()){ + } else { + switch (c.getDataStructureType()) { case JournalQueueAck.DATA_STRUCTURE_TYPE: { - JournalQueueAck command=(JournalQueueAck)c; - AMQMessageStore store=(AMQMessageStore)createMessageStore(command.getDestination()); - if(command.getMessageAck().isInTransaction()){ - transactionStore.removeMessage(store,command.getMessageAck(),pos); - }else{ - if(store.replayRemoveMessage(context,command.getMessageAck())){ + JournalQueueAck command = (JournalQueueAck)c; + AMQMessageStore store = (AMQMessageStore)createMessageStore(command.getDestination()); + if (command.getMessageAck().isInTransaction()) { + transactionStore.removeMessage(store, command.getMessageAck(), pos); + } else { + if (store.replayRemoveMessage(context, command.getMessageAck())) { redoCounter++; } } } break; case JournalTopicAck.DATA_STRUCTURE_TYPE: { - JournalTopicAck command=(JournalTopicAck)c; - AMQTopicMessageStore store=(AMQTopicMessageStore)createMessageStore(command.getDestination()); - if(command.getTransactionId()!=null){ - transactionStore.acknowledge(store,command,pos); - }else{ - if(store.replayAcknowledge(context,command.getClientId(),command.getSubscritionName(),command - .getMessageId())){ + JournalTopicAck command = (JournalTopicAck)c; + AMQTopicMessageStore store = (AMQTopicMessageStore)createMessageStore(command.getDestination()); + if (command.getTransactionId() != null) { + transactionStore.acknowledge(store, command, pos); + } else { + if (store.replayAcknowledge(context, command.getClientId(), command.getSubscritionName(), command.getMessageId())) { redoCounter++; } } } break; case JournalTransaction.DATA_STRUCTURE_TYPE: { - JournalTransaction command=(JournalTransaction)c; - try{ + JournalTransaction command = (JournalTransaction)c; + try { // Try to replay the packet. - switch(command.getType()){ + switch (command.getType()) { case JournalTransaction.XA_PREPARE: transactionStore.replayPrepare(command.getTransactionId()); break; case JournalTransaction.XA_COMMIT: case JournalTransaction.LOCAL_COMMIT: - AMQTx tx=transactionStore.replayCommit(command.getTransactionId(),command.getWasPrepared()); - if(tx==null) - break; // We may be trying to replay a commit that + AMQTx tx = transactionStore.replayCommit(command.getTransactionId(), command.getWasPrepared()); + if (tx == null) { + break; // We may be trying to replay a commit + } + // that // was already committed. // Replay the committed operations. tx.getOperations(); - for(Iterator iter=tx.getOperations().iterator();iter.hasNext();){ - AMQTxOperation op=(AMQTxOperation)iter.next(); - if (op.replay(this,context)) { + for (Iterator iter = tx.getOperations().iterator(); iter.hasNext();) { + AMQTxOperation op = (AMQTxOperation)iter.next(); + if (op.replay(this, context)) { redoCounter++; } } @@ -510,176 +515,174 @@ public class AMQPersistenceAdapter implements PersistenceAdapter, UsageListener, transactionStore.replayRollback(command.getTransactionId()); break; } - }catch(IOException e){ - log.error("Recovery Failure: Could not replay: "+c+", reason: "+e,e); + } catch (IOException e) { + log.error("Recovery Failure: Could not replay: " + c + ", reason: " + e, e); } } break; case JournalTrace.DATA_STRUCTURE_TYPE: - JournalTrace trace=(JournalTrace)c; - log.debug("TRACE Entry: "+trace.getMessage()); + JournalTrace trace = (JournalTrace)c; + log.debug("TRACE Entry: " + trace.getMessage()); break; default: - log.error("Unknown type of record in transaction log which will be discarded: "+c); + log.error("Unknown type of record in transaction log which will be discarded: " + c); } } } - Location location=writeTraceMessage("RECOVERED "+new Date(),true); - asyncDataManager.setMark(location,true); - long end=System.currentTimeMillis(); - log.info("Recovered "+redoCounter+" operations from redo log in "+((end-start)/1000.0f)+" seconds."); + Location location = writeTraceMessage("RECOVERED " + new Date(), true); + asyncDataManager.setMark(location, true); + long end = System.currentTimeMillis(); + log.info("Recovered " + redoCounter + " operations from redo log in " + ((end - start) / 1000.0f) + " seconds."); } - private IOException createReadException(Location location,Exception e){ - return IOExceptionSupport.create("Failed to read to journal for: "+location+". Reason: "+e,e); + private IOException createReadException(Location location, Exception e) { + return IOExceptionSupport.create("Failed to read to journal for: " + location + ". Reason: " + e, e); } - protected IOException createWriteException(DataStructure packet,Exception e){ - return IOExceptionSupport.create("Failed to write to journal for: "+packet+". Reason: "+e,e); + protected IOException createWriteException(DataStructure packet, Exception e) { + return IOExceptionSupport.create("Failed to write to journal for: " + packet + ". Reason: " + e, e); } - protected IOException createWriteException(String command,Exception e){ - return IOExceptionSupport.create("Failed to write to journal for command: "+command+". Reason: "+e,e); + protected IOException createWriteException(String command, Exception e) { + return IOExceptionSupport.create("Failed to write to journal for command: " + command + ". Reason: " + e, e); } - protected IOException createRecoveryFailedException(Exception e){ - return IOExceptionSupport.create("Failed to recover from journal. Reason: "+e,e); + protected IOException createRecoveryFailedException(Exception e) { + return IOExceptionSupport.create("Failed to recover from journal. Reason: " + e, e); } /** - * * @param command * @param syncHint * @return * @throws IOException */ - public Location writeCommand(DataStructure command,boolean syncHint) throws IOException{ - return asyncDataManager.write(wireFormat.marshal(command),(syncHint&&syncOnWrite)); + public Location writeCommand(DataStructure command, boolean syncHint) throws IOException { + return asyncDataManager.write(wireFormat.marshal(command), (syncHint && syncOnWrite)); } - private Location writeTraceMessage(String message,boolean sync) throws IOException{ - JournalTrace trace=new JournalTrace(); + private Location writeTraceMessage(String message, boolean sync) throws IOException { + JournalTrace trace = new JournalTrace(); trace.setMessage(message); - return writeCommand(trace,sync); + return writeCommand(trace, sync); } - public void onMemoryUseChanged(UsageManager memoryManager,int oldPercentUsage,int newPercentUsage){ - newPercentUsage=((newPercentUsage)/10)*10; - oldPercentUsage=((oldPercentUsage)/10)*10; - if(newPercentUsage>=70&&oldPercentUsage= 70 && oldPercentUsage < newPercentUsage) { checkpoint(false); } } - public AMQTransactionStore getTransactionStore(){ + public AMQTransactionStore getTransactionStore() { return transactionStore; } - public synchronized void deleteAllMessages() throws IOException{ - deleteAllMessages=true; + public synchronized void deleteAllMessages() throws IOException { + deleteAllMessages = true; } - public String toString(){ - return "AMQPersistenceAdapter("+directory+")"; + public String toString() { + return "AMQPersistenceAdapter(" + directory + ")"; } // ///////////////////////////////////////////////////////////////// // Subclass overridables // ///////////////////////////////////////////////////////////////// - protected AsyncDataManager createAsyncDataManager(){ - AsyncDataManager manager=new AsyncDataManager(); - manager.setDirectory(new File(directory,"journal")); + protected AsyncDataManager createAsyncDataManager() { + AsyncDataManager manager = new AsyncDataManager(); + manager.setDirectory(new File(directory, "journal")); return manager; } - protected KahaReferenceStoreAdapter createReferenceStoreAdapter() throws IOException{ - KahaReferenceStoreAdapter adaptor=new KahaReferenceStoreAdapter(); + protected KahaReferenceStoreAdapter createReferenceStoreAdapter() throws IOException { + KahaReferenceStoreAdapter adaptor = new KahaReferenceStoreAdapter(); return adaptor; } - protected TaskRunnerFactory createTaskRunnerFactory(){ + protected TaskRunnerFactory createTaskRunnerFactory() { return DefaultThreadPools.getDefaultTaskRunnerFactory(); } // ///////////////////////////////////////////////////////////////// // Property Accessors // ///////////////////////////////////////////////////////////////// - public AsyncDataManager getAsyncDataManager(){ + public AsyncDataManager getAsyncDataManager() { return asyncDataManager; } - public void setAsyncDataManager(AsyncDataManager asyncDataManager){ - this.asyncDataManager=asyncDataManager; + public void setAsyncDataManager(AsyncDataManager asyncDataManager) { + this.asyncDataManager = asyncDataManager; } - public ReferenceStoreAdapter getReferenceStoreAdapter(){ + public ReferenceStoreAdapter getReferenceStoreAdapter() { return referenceStoreAdapter; } - public TaskRunnerFactory getTaskRunnerFactory(){ + public TaskRunnerFactory getTaskRunnerFactory() { return taskRunnerFactory; } - public void setTaskRunnerFactory(TaskRunnerFactory taskRunnerFactory){ - this.taskRunnerFactory=taskRunnerFactory; + public void setTaskRunnerFactory(TaskRunnerFactory taskRunnerFactory) { + this.taskRunnerFactory = taskRunnerFactory; } /** * @return Returns the wireFormat. */ - public WireFormat getWireFormat(){ + public WireFormat getWireFormat() { return wireFormat; } - public void setWireFormat(WireFormat wireFormat){ - this.wireFormat=wireFormat; + public void setWireFormat(WireFormat wireFormat) { + this.wireFormat = wireFormat; } - public UsageManager getUsageManager(){ + public UsageManager getUsageManager() { return usageManager; } - public void setUsageManager(UsageManager usageManager){ - this.usageManager=usageManager; + public void setUsageManager(UsageManager usageManager) { + this.usageManager = usageManager; } - public int getMaxCheckpointMessageAddSize(){ + public int getMaxCheckpointMessageAddSize() { return maxCheckpointMessageAddSize; } - public void setMaxCheckpointMessageAddSize(int maxCheckpointMessageAddSize){ - this.maxCheckpointMessageAddSize=maxCheckpointMessageAddSize; + public void setMaxCheckpointMessageAddSize(int maxCheckpointMessageAddSize) { + this.maxCheckpointMessageAddSize = maxCheckpointMessageAddSize; } - public int getMaxCheckpointWorkers(){ + public int getMaxCheckpointWorkers() { return maxCheckpointWorkers; } - public void setMaxCheckpointWorkers(int maxCheckpointWorkers){ - this.maxCheckpointWorkers=maxCheckpointWorkers; + public void setMaxCheckpointWorkers(int maxCheckpointWorkers) { + this.maxCheckpointWorkers = maxCheckpointWorkers; } - public synchronized File getDirectory(){ + public synchronized File getDirectory() { return directory; } - public synchronized void setDirectory(File directory){ - this.directory=directory; + public synchronized void setDirectory(File directory) { + this.directory = directory; } - public boolean isSyncOnWrite(){ + public boolean isSyncOnWrite() { return this.syncOnWrite; } - public void setSyncOnWrite(boolean syncOnWrite){ - this.syncOnWrite=syncOnWrite; + public void setSyncOnWrite(boolean syncOnWrite) { + this.syncOnWrite = syncOnWrite; } - /** * @param referenceStoreAdapter the referenceStoreAdapter to set */ - public void setReferenceStoreAdapter(ReferenceStoreAdapter referenceStoreAdapter){ - this.referenceStoreAdapter=referenceStoreAdapter; + public void setReferenceStoreAdapter(ReferenceStoreAdapter referenceStoreAdapter) { + this.referenceStoreAdapter = referenceStoreAdapter; } } diff --git a/activemq-core/src/main/java/org/apache/activemq/store/amq/AMQPersistenceAdapterFactory.java b/activemq-core/src/main/java/org/apache/activemq/store/amq/AMQPersistenceAdapterFactory.java index 1717ee300e..ff8b956fa6 100644 --- a/activemq-core/src/main/java/org/apache/activemq/store/amq/AMQPersistenceAdapterFactory.java +++ b/activemq-core/src/main/java/org/apache/activemq/store/amq/AMQPersistenceAdapterFactory.java @@ -28,106 +28,101 @@ import org.apache.activemq.util.IOHelper; * * @version $Revision: 1.17 $ */ -public class AMQPersistenceAdapterFactory implements PersistenceAdapterFactory{ +public class AMQPersistenceAdapterFactory implements PersistenceAdapterFactory { private TaskRunnerFactory taskRunnerFactory; private File dataDirectory; private int journalThreadPriority = Thread.MAX_PRIORITY; - private String brokerName="localhost"; + private String brokerName = "localhost"; private ReferenceStoreAdapter referenceStoreAdapter; - + /** * @return a AMQPersistenceAdapter * @see org.apache.activemq.store.PersistenceAdapterFactory#createPersistenceAdapter() */ - public PersistenceAdapter createPersistenceAdapter(){ - AMQPersistenceAdapter result = new AMQPersistenceAdapter(); + public PersistenceAdapter createPersistenceAdapter() { + AMQPersistenceAdapter result = new AMQPersistenceAdapter(); result.setDirectory(getDataDirectory()); result.setTaskRunnerFactory(getTaskRunnerFactory()); result.setBrokerName(getBrokerName()); result.setReferenceStoreAdapter(getReferenceStoreAdapter()); return result; } - + /** * @return the dataDirectory */ - public File getDataDirectory(){ - if(this.dataDirectory==null){ - this.dataDirectory=new File(IOHelper.getDefaultDataDirectory(),brokerName); + public File getDataDirectory() { + if (this.dataDirectory == null) { + this.dataDirectory = new File(IOHelper.getDefaultDataDirectory(), brokerName); } return this.dataDirectory; } - + /** * @param dataDirectory the dataDirectory to set */ - public void setDataDirectory(File dataDirectory){ - this.dataDirectory=dataDirectory; + public void setDataDirectory(File dataDirectory) { + this.dataDirectory = dataDirectory; } - + /** * @return the taskRunnerFactory */ - public TaskRunnerFactory getTaskRunnerFactory(){ - if( taskRunnerFactory == null ) { - taskRunnerFactory = new TaskRunnerFactory("AMQPersistenceAdaptor Task", journalThreadPriority, true, 1000); + public TaskRunnerFactory getTaskRunnerFactory() { + if (taskRunnerFactory == null) { + taskRunnerFactory = new TaskRunnerFactory("AMQPersistenceAdaptor Task", journalThreadPriority, + true, 1000); } return taskRunnerFactory; } - + /** * @param taskRunnerFactory the taskRunnerFactory to set */ - public void setTaskRunnerFactory(TaskRunnerFactory taskRunnerFactory){ - this.taskRunnerFactory=taskRunnerFactory; + public void setTaskRunnerFactory(TaskRunnerFactory taskRunnerFactory) { + this.taskRunnerFactory = taskRunnerFactory; } - /** * @return the journalThreadPriority */ - public int getJournalThreadPriority(){ + public int getJournalThreadPriority() { return this.journalThreadPriority; } - /** * @param journalThreadPriority the journalThreadPriority to set */ - public void setJournalThreadPriority(int journalThreadPriority){ - this.journalThreadPriority=journalThreadPriority; + public void setJournalThreadPriority(int journalThreadPriority) { + this.journalThreadPriority = journalThreadPriority; } - /** * @return the brokerName */ - public String getBrokerName(){ + public String getBrokerName() { return this.brokerName; } - /** * @param brokerName the brokerName to set */ - public void setBrokerName(String brokerName){ - this.brokerName=brokerName; + public void setBrokerName(String brokerName) { + this.brokerName = brokerName; } - /** * @return the referenceStoreAdapter */ - public ReferenceStoreAdapter getReferenceStoreAdapter(){ + public ReferenceStoreAdapter getReferenceStoreAdapter() { return this.referenceStoreAdapter; } - /** * @param referenceStoreAdapter the referenceStoreAdapter to set */ - public void setReferenceStoreAdapter(ReferenceStoreAdapter referenceStoreAdapter){ - this.referenceStoreAdapter=referenceStoreAdapter; + public void setReferenceStoreAdapter(ReferenceStoreAdapter referenceStoreAdapter) { + this.referenceStoreAdapter = referenceStoreAdapter; } } diff --git a/activemq-core/src/main/java/org/apache/activemq/store/amq/AMQTopicMessageStore.java b/activemq-core/src/main/java/org/apache/activemq/store/amq/AMQTopicMessageStore.java index 5997d15066..31a047a57c 100644 --- a/activemq-core/src/main/java/org/apache/activemq/store/amq/AMQTopicMessageStore.java +++ b/activemq-core/src/main/java/org/apache/activemq/store/amq/AMQTopicMessageStore.java @@ -18,6 +18,7 @@ import java.io.IOException; import java.io.InterruptedIOException; import java.util.HashMap; import java.util.Iterator; + import org.apache.activemq.broker.ConnectionContext; import org.apache.activemq.command.ActiveMQTopic; import org.apache.activemq.command.JournalTopicAck; @@ -38,83 +39,82 @@ import org.apache.commons.logging.LogFactory; * * @version $Revision: 1.13 $ */ -public class AMQTopicMessageStore extends AMQMessageStore implements TopicMessageStore{ +public class AMQTopicMessageStore extends AMQMessageStore implements TopicMessageStore { - private static final Log log=LogFactory.getLog(AMQTopicMessageStore.class); + private static final Log log = LogFactory.getLog(AMQTopicMessageStore.class); private TopicReferenceStore topicReferenceStore; - private HashMap ackedLastAckLocations=new HashMap(); + private HashMap ackedLastAckLocations = new HashMap(); - public AMQTopicMessageStore(AMQPersistenceAdapter adapter,TopicReferenceStore topicReferenceStore, - ActiveMQTopic destinationName){ - super(adapter,topicReferenceStore,destinationName); - this.topicReferenceStore=topicReferenceStore; + public AMQTopicMessageStore(AMQPersistenceAdapter adapter, TopicReferenceStore topicReferenceStore, ActiveMQTopic destinationName) { + super(adapter, topicReferenceStore, destinationName); + this.topicReferenceStore = topicReferenceStore; } - public void recoverSubscription(String clientId,String subscriptionName,MessageRecoveryListener listener) - throws Exception{ + public void recoverSubscription(String clientId, String subscriptionName, MessageRecoveryListener listener) throws Exception { flush(); - topicReferenceStore.recoverSubscription(clientId,subscriptionName,new RecoveryListenerAdapter(this,listener)); + topicReferenceStore.recoverSubscription(clientId, subscriptionName, new RecoveryListenerAdapter(this, listener)); } - public void recoverNextMessages(String clientId,String subscriptionName,int maxReturned, - final MessageRecoveryListener listener) throws Exception{ - RecoveryListenerAdapter recoveryListener=new RecoveryListenerAdapter(this,listener); - topicReferenceStore.recoverNextMessages(clientId,subscriptionName,maxReturned,recoveryListener); - if(recoveryListener.size()==0){ + public void recoverNextMessages(String clientId, String subscriptionName, int maxReturned, final MessageRecoveryListener listener) throws Exception { + RecoveryListenerAdapter recoveryListener = new RecoveryListenerAdapter(this, listener); + topicReferenceStore.recoverNextMessages(clientId, subscriptionName, maxReturned, recoveryListener); + if (recoveryListener.size() == 0) { flush(); - topicReferenceStore.recoverNextMessages(clientId,subscriptionName,maxReturned,recoveryListener); + topicReferenceStore.recoverNextMessages(clientId, subscriptionName, maxReturned, recoveryListener); } } - public SubscriptionInfo lookupSubscription(String clientId,String subscriptionName) throws IOException{ - return topicReferenceStore.lookupSubscription(clientId,subscriptionName); + public SubscriptionInfo lookupSubscription(String clientId, String subscriptionName) throws IOException { + return topicReferenceStore.lookupSubscription(clientId, subscriptionName); } - public void addSubsciption(SubscriptionInfo subscriptionInfo,boolean retroactive) - throws IOException{ - topicReferenceStore.addSubsciption(subscriptionInfo,retroactive); + public void addSubsciption(SubscriptionInfo subscriptionInfo, boolean retroactive) throws IOException { + topicReferenceStore.addSubsciption(subscriptionInfo, retroactive); } /** */ - public void acknowledge(ConnectionContext context,String clientId,String subscriptionName,final MessageId messageId) - throws IOException{ - final boolean debug=log.isDebugEnabled(); - JournalTopicAck ack=new JournalTopicAck(); + public void acknowledge(ConnectionContext context, String clientId, String subscriptionName, final MessageId messageId) throws IOException { + final boolean debug = log.isDebugEnabled(); + JournalTopicAck ack = new JournalTopicAck(); ack.setDestination(destination); ack.setMessageId(messageId); ack.setMessageSequenceId(messageId.getBrokerSequenceId()); ack.setSubscritionName(subscriptionName); ack.setClientId(clientId); - ack.setTransactionId(context.getTransaction()!=null?context.getTransaction().getTransactionId():null); - final Location location=peristenceAdapter.writeCommand(ack,false); - final SubscriptionKey key=new SubscriptionKey(clientId,subscriptionName); - if(!context.isInTransaction()){ - if(debug) - log.debug("Journalled acknowledge for: "+messageId+", at: "+location); - acknowledge(messageId,location,key); - }else{ - if(debug) - log.debug("Journalled transacted acknowledge for: "+messageId+", at: "+location); - synchronized(this){ + ack.setTransactionId(context.getTransaction() != null ? context.getTransaction().getTransactionId() : null); + final Location location = peristenceAdapter.writeCommand(ack, false); + final SubscriptionKey key = new SubscriptionKey(clientId, subscriptionName); + if (!context.isInTransaction()) { + if (debug) { + log.debug("Journalled acknowledge for: " + messageId + ", at: " + location); + } + acknowledge(messageId, location, key); + } else { + if (debug) { + log.debug("Journalled transacted acknowledge for: " + messageId + ", at: " + location); + } + synchronized (this) { inFlightTxLocations.add(location); } - transactionStore.acknowledge(this,ack,location); - context.getTransaction().addSynchronization(new Synchronization(){ + transactionStore.acknowledge(this, ack, location); + context.getTransaction().addSynchronization(new Synchronization() { - public void afterCommit() throws Exception{ - if(debug) - log.debug("Transacted acknowledge commit for: "+messageId+", at: "+location); - synchronized(AMQTopicMessageStore.this){ + public void afterCommit() throws Exception { + if (debug) { + log.debug("Transacted acknowledge commit for: " + messageId + ", at: " + location); + } + synchronized (AMQTopicMessageStore.this) { inFlightTxLocations.remove(location); - acknowledge(messageId,location,key); + acknowledge(messageId, location, key); } } - public void afterRollback() throws Exception{ - if(debug) - log.debug("Transacted acknowledge rollback for: "+messageId+", at: "+location); - synchronized(AMQTopicMessageStore.this){ + public void afterRollback() throws Exception { + if (debug) { + log.debug("Transacted acknowledge rollback for: " + messageId + ", at: " + location); + } + synchronized (AMQTopicMessageStore.this) { inFlightTxLocations.remove(location); } } @@ -122,17 +122,15 @@ public class AMQTopicMessageStore extends AMQMessageStore implements TopicMessag } } - public boolean replayAcknowledge(ConnectionContext context,String clientId,String subscritionName, - MessageId messageId){ - try{ - SubscriptionInfo sub=topicReferenceStore.lookupSubscription(clientId,subscritionName); - if(sub!=null){ - topicReferenceStore.acknowledge(context,clientId,subscritionName,messageId); + public boolean replayAcknowledge(ConnectionContext context, String clientId, String subscritionName, MessageId messageId) { + try { + SubscriptionInfo sub = topicReferenceStore.lookupSubscription(clientId, subscritionName); + if (sub != null) { + topicReferenceStore.acknowledge(context, clientId, subscritionName, messageId); return true; } - }catch(Throwable e){ - log.debug("Could not replay acknowledge for message '"+messageId - +"'. Message may have already been acknowledged. reason: "+e); + } catch (Throwable e) { + log.debug("Could not replay acknowledge for message '" + messageId + "'. Message may have already been acknowledged. reason: " + e); } return false; } @@ -143,26 +141,27 @@ public class AMQTopicMessageStore extends AMQMessageStore implements TopicMessag * @param key * @throws InterruptedIOException */ - protected void acknowledge(MessageId messageId,Location location,SubscriptionKey key) throws InterruptedIOException{ - synchronized(this){ - lastLocation=location; - ackedLastAckLocations.put(key,messageId); + protected void acknowledge(MessageId messageId, Location location, SubscriptionKey key) throws InterruptedIOException { + synchronized (this) { + lastLocation = location; + ackedLastAckLocations.put(key, messageId); } - try{ + try { asyncWriteTask.wakeup(); - }catch(InterruptedException e){ + } catch (InterruptedException e) { throw new InterruptedIOException(); } } - @Override protected Location doAsyncWrite() throws IOException{ - final HashMap cpAckedLastAckLocations; + @Override + protected Location doAsyncWrite() throws IOException { + final HashMap cpAckedLastAckLocations; // swap out the hash maps.. - synchronized(this){ - cpAckedLastAckLocations=this.ackedLastAckLocations; - this.ackedLastAckLocations=new HashMap(); + synchronized (this) { + cpAckedLastAckLocations = this.ackedLastAckLocations; + this.ackedLastAckLocations = new HashMap(); } - Location location=super.doAsyncWrite(); + Location location = super.doAsyncWrite(); if (cpAckedLastAckLocations != null) { transactionTemplate.run(new Callback() { @@ -172,8 +171,7 @@ public class AMQTopicMessageStore extends AMQMessageStore implements TopicMessag while (iterator.hasNext()) { SubscriptionKey subscriptionKey = iterator.next(); MessageId identity = cpAckedLastAckLocations.get(subscriptionKey); - topicReferenceStore.acknowledge(transactionTemplate.getContext(), subscriptionKey.clientId, - subscriptionKey.subscriptionName, identity); + topicReferenceStore.acknowledge(transactionTemplate.getContext(), subscriptionKey.clientId, subscriptionKey.subscriptionName, identity); } } }); @@ -184,24 +182,24 @@ public class AMQTopicMessageStore extends AMQMessageStore implements TopicMessag /** * @return Returns the longTermStore. */ - public TopicReferenceStore getTopicReferenceStore(){ + public TopicReferenceStore getTopicReferenceStore() { return topicReferenceStore; } - public void deleteSubscription(String clientId,String subscriptionName) throws IOException{ - topicReferenceStore.deleteSubscription(clientId,subscriptionName); + public void deleteSubscription(String clientId, String subscriptionName) throws IOException { + topicReferenceStore.deleteSubscription(clientId, subscriptionName); } - public SubscriptionInfo[] getAllSubscriptions() throws IOException{ + public SubscriptionInfo[] getAllSubscriptions() throws IOException { return topicReferenceStore.getAllSubscriptions(); } - public int getMessageCount(String clientId,String subscriberName) throws IOException{ + public int getMessageCount(String clientId, String subscriberName) throws IOException { flush(); - return topicReferenceStore.getMessageCount(clientId,subscriberName); + return topicReferenceStore.getMessageCount(clientId, subscriberName); } - public void resetBatching(String clientId,String subscriptionName){ - topicReferenceStore.resetBatching(clientId,subscriptionName); + public void resetBatching(String clientId, String subscriptionName) { + topicReferenceStore.resetBatching(clientId, subscriptionName); } -} \ No newline at end of file +} diff --git a/activemq-core/src/main/java/org/apache/activemq/store/amq/AMQTransactionStore.java b/activemq-core/src/main/java/org/apache/activemq/store/amq/AMQTransactionStore.java index af22011585..6e230ce849 100644 --- a/activemq-core/src/main/java/org/apache/activemq/store/amq/AMQTransactionStore.java +++ b/activemq-core/src/main/java/org/apache/activemq/store/amq/AMQTransactionStore.java @@ -21,7 +21,9 @@ import java.io.IOException; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; + import javax.transaction.xa.XAException; + import org.apache.activemq.command.JournalTopicAck; import org.apache.activemq.command.JournalTransaction; import org.apache.activemq.command.Message; @@ -32,34 +34,34 @@ import org.apache.activemq.kaha.impl.async.Location; import org.apache.activemq.store.TransactionRecoveryListener; import org.apache.activemq.store.TransactionStore; - /** */ -public class AMQTransactionStore implements TransactionStore{ +public class AMQTransactionStore implements TransactionStore { private final AMQPersistenceAdapter peristenceAdapter; - Map inflightTransactions=new LinkedHashMap(); - Map preparedTransactions=new LinkedHashMap(); + Map inflightTransactions = new LinkedHashMap(); + Map preparedTransactions = new LinkedHashMap(); private boolean doingRecover; - public AMQTransactionStore(AMQPersistenceAdapter adapter){ - this.peristenceAdapter=adapter; + public AMQTransactionStore(AMQPersistenceAdapter adapter) { + this.peristenceAdapter = adapter; } /** * @throws IOException * @see org.apache.activemq.store.TransactionStore#prepare(TransactionId) */ - public void prepare(TransactionId txid) throws IOException{ - AMQTx tx=null; - synchronized(inflightTransactions){ - tx=inflightTransactions.remove(txid); + public void prepare(TransactionId txid) throws IOException { + AMQTx tx = null; + synchronized (inflightTransactions) { + tx = inflightTransactions.remove(txid); } - if(tx==null) + if (tx == null) { return; - peristenceAdapter.writeCommand(new JournalTransaction(JournalTransaction.XA_PREPARE,txid,false),true); - synchronized(preparedTransactions){ - preparedTransactions.put(txid,tx); + } + peristenceAdapter.writeCommand(new JournalTransaction(JournalTransaction.XA_PREPARE, txid, false), true); + synchronized (preparedTransactions) { + preparedTransactions.put(txid, tx); } } @@ -67,26 +69,27 @@ public class AMQTransactionStore implements TransactionStore{ * @throws IOException * @see org.apache.activemq.store.TransactionStore#prepare(TransactionId) */ - public void replayPrepare(TransactionId txid) throws IOException{ - AMQTx tx=null; - synchronized(inflightTransactions){ - tx=inflightTransactions.remove(txid); + public void replayPrepare(TransactionId txid) throws IOException { + AMQTx tx = null; + synchronized (inflightTransactions) { + tx = inflightTransactions.remove(txid); } - if(tx==null) + if (tx == null) { return; - synchronized(preparedTransactions){ - preparedTransactions.put(txid,tx); + } + synchronized (preparedTransactions) { + preparedTransactions.put(txid, tx); } } - public AMQTx getTx(TransactionId txid,Location location){ - AMQTx tx=null; - synchronized(inflightTransactions){ - tx=inflightTransactions.get(txid); + public AMQTx getTx(TransactionId txid, Location location) { + AMQTx tx = null; + synchronized (inflightTransactions) { + tx = inflightTransactions.get(txid); } - if(tx==null){ - tx=new AMQTx(location); - inflightTransactions.put(txid,tx); + if (tx == null) { + tx = new AMQTx(location); + inflightTransactions.put(txid, tx); } return tx; } @@ -95,24 +98,24 @@ public class AMQTransactionStore implements TransactionStore{ * @throws XAException * @see org.apache.activemq.store.TransactionStore#commit(org.apache.activemq.service.Transaction) */ - public void commit(TransactionId txid,boolean wasPrepared) throws IOException{ + public void commit(TransactionId txid, boolean wasPrepared) throws IOException { AMQTx tx; - if(wasPrepared){ - synchronized(preparedTransactions){ - tx=preparedTransactions.remove(txid); + if (wasPrepared) { + synchronized (preparedTransactions) { + tx = preparedTransactions.remove(txid); } - }else{ - synchronized(inflightTransactions){ - tx=inflightTransactions.remove(txid); + } else { + synchronized (inflightTransactions) { + tx = inflightTransactions.remove(txid); } } - if(tx==null) + if (tx == null) { return; - if(txid.isXATransaction()){ - peristenceAdapter.writeCommand(new JournalTransaction(JournalTransaction.XA_COMMIT,txid,wasPrepared),true); - }else{ - peristenceAdapter.writeCommand(new JournalTransaction(JournalTransaction.LOCAL_COMMIT,txid,wasPrepared), - true); + } + if (txid.isXATransaction()) { + peristenceAdapter.writeCommand(new JournalTransaction(JournalTransaction.XA_COMMIT, txid, wasPrepared), true); + } else { + peristenceAdapter.writeCommand(new JournalTransaction(JournalTransaction.LOCAL_COMMIT, txid, wasPrepared), true); } } @@ -120,13 +123,13 @@ public class AMQTransactionStore implements TransactionStore{ * @throws XAException * @see org.apache.activemq.store.TransactionStore#commit(org.apache.activemq.service.Transaction) */ - public AMQTx replayCommit(TransactionId txid,boolean wasPrepared) throws IOException{ - if(wasPrepared){ - synchronized(preparedTransactions){ + public AMQTx replayCommit(TransactionId txid, boolean wasPrepared) throws IOException { + if (wasPrepared) { + synchronized (preparedTransactions) { return preparedTransactions.remove(txid); } - }else{ - synchronized(inflightTransactions){ + } else { + synchronized (inflightTransactions) { return inflightTransactions.remove(txid); } } @@ -136,21 +139,21 @@ public class AMQTransactionStore implements TransactionStore{ * @throws IOException * @see org.apache.activemq.store.TransactionStore#rollback(TransactionId) */ - public void rollback(TransactionId txid) throws IOException{ - AMQTx tx=null; - synchronized(inflightTransactions){ - tx=inflightTransactions.remove(txid); + public void rollback(TransactionId txid) throws IOException { + AMQTx tx = null; + synchronized (inflightTransactions) { + tx = inflightTransactions.remove(txid); } - if(tx!=null) - synchronized(preparedTransactions){ - tx=preparedTransactions.remove(txid); + if (tx != null) { + synchronized (preparedTransactions) { + tx = preparedTransactions.remove(txid); } - if(tx!=null){ - if(txid.isXATransaction()){ - peristenceAdapter.writeCommand(new JournalTransaction(JournalTransaction.XA_ROLLBACK,txid,false),true); - }else{ - peristenceAdapter.writeCommand(new JournalTransaction(JournalTransaction.LOCAL_ROLLBACK,txid,false), - true); + } + if (tx != null) { + if (txid.isXATransaction()) { + peristenceAdapter.writeCommand(new JournalTransaction(JournalTransaction.XA_ROLLBACK, txid, false), true); + } else { + peristenceAdapter.writeCommand(new JournalTransaction(JournalTransaction.LOCAL_ROLLBACK, txid, false), true); } } } @@ -159,42 +162,42 @@ public class AMQTransactionStore implements TransactionStore{ * @throws IOException * @see org.apache.activemq.store.TransactionStore#rollback(TransactionId) */ - public void replayRollback(TransactionId txid) throws IOException{ - boolean inflight=false; - synchronized(inflightTransactions){ - inflight=inflightTransactions.remove(txid)!=null; + public void replayRollback(TransactionId txid) throws IOException { + boolean inflight = false; + synchronized (inflightTransactions) { + inflight = inflightTransactions.remove(txid) != null; } - if(inflight){ - synchronized(preparedTransactions){ + if (inflight) { + synchronized (preparedTransactions) { preparedTransactions.remove(txid); } } } - public void start() throws Exception{ + public void start() throws Exception { } - public void stop() throws Exception{ + public void stop() throws Exception { } - synchronized public void recover(TransactionRecoveryListener listener) throws IOException{ + synchronized public void recover(TransactionRecoveryListener listener) throws IOException { // All the in-flight transactions get rolled back.. - synchronized(inflightTransactions){ + synchronized (inflightTransactions) { inflightTransactions.clear(); } - this.doingRecover=true; - try{ - Map txs=null; - synchronized(preparedTransactions){ - txs=new LinkedHashMap(preparedTransactions); + this.doingRecover = true; + try { + Map txs = null; + synchronized (preparedTransactions) { + txs = new LinkedHashMap(preparedTransactions); } - for(Iterator iter=txs.keySet().iterator();iter.hasNext();){ - Object txid=iter.next(); - AMQTx tx=txs.get(txid); - listener.recover((XATransactionId)txid,tx.getMessages(),tx.getAcks()); + for (Iterator iter = txs.keySet().iterator(); iter.hasNext();) { + Object txid = iter.next(); + AMQTx tx = txs.get(txid); + listener.recover((XATransactionId)txid, tx.getMessages(), tx.getAcks()); } - }finally{ - this.doingRecover=false; + } finally { + this.doingRecover = false; } } @@ -202,69 +205,70 @@ public class AMQTransactionStore implements TransactionStore{ * @param message * @throws IOException */ - void addMessage(AMQMessageStore store,Message message,Location location) throws IOException{ - AMQTx tx=getTx(message.getTransactionId(),location); - tx.add(store,message,location); + void addMessage(AMQMessageStore store, Message message, Location location) throws IOException { + AMQTx tx = getTx(message.getTransactionId(), location); + tx.add(store, message, location); } /** * @param ack * @throws IOException */ - public void removeMessage(AMQMessageStore store,MessageAck ack,Location location) throws IOException{ - AMQTx tx=getTx(ack.getTransactionId(),location); - tx.add(store,ack); + public void removeMessage(AMQMessageStore store, MessageAck ack, Location location) throws IOException { + AMQTx tx = getTx(ack.getTransactionId(), location); + tx.add(store, ack); } - public void acknowledge(AMQTopicMessageStore store,JournalTopicAck ack,Location location){ - AMQTx tx=getTx(ack.getTransactionId(),location); - tx.add(store,ack); + public void acknowledge(AMQTopicMessageStore store, JournalTopicAck ack, Location location) { + AMQTx tx = getTx(ack.getTransactionId(), location); + tx.add(store, ack); } - public Location checkpoint() throws IOException{ + public Location checkpoint() throws IOException { // Nothing really to checkpoint.. since, we don't - // checkpoint tx operations in to long term store until they are committed. + // checkpoint tx operations in to long term store until they are + // committed. // But we keep track of the first location of an operation // that was associated with an active tx. The journal can not // roll over active tx records. - Location rc=null; - synchronized(inflightTransactions){ - for(Iterator iter=inflightTransactions.values().iterator();iter.hasNext();){ - AMQTx tx=iter.next(); - Location location=tx.getLocation(); - if(rc==null||rc.compareTo(location)<0){ - rc=location; + Location rc = null; + synchronized (inflightTransactions) { + for (Iterator iter = inflightTransactions.values().iterator(); iter.hasNext();) { + AMQTx tx = iter.next(); + Location location = tx.getLocation(); + if (rc == null || rc.compareTo(location) < 0) { + rc = location; } } } - synchronized(preparedTransactions){ - for(Iterator iter=preparedTransactions.values().iterator();iter.hasNext();){ - AMQTx tx=iter.next(); - Location location=tx.getLocation(); - if(rc==null||rc.compareTo(location)<0){ - rc=location; + synchronized (preparedTransactions) { + for (Iterator iter = preparedTransactions.values().iterator(); iter.hasNext();) { + AMQTx tx = iter.next(); + Location location = tx.getLocation(); + if (rc == null || rc.compareTo(location) < 0) { + rc = location; } } return rc; } } - public boolean isDoingRecover(){ + public boolean isDoingRecover() { return doingRecover; } /** * @return the preparedTransactions */ - public Map getPreparedTransactions(){ + public Map getPreparedTransactions() { return this.preparedTransactions; } /** * @param preparedTransactions the preparedTransactions to set */ - public void setPreparedTransactions(Map preparedTransactions){ - if(preparedTransactions!=null){ + public void setPreparedTransactions(Map preparedTransactions) { + if (preparedTransactions != null) { this.preparedTransactions.clear(); this.preparedTransactions.putAll(preparedTransactions); } diff --git a/activemq-core/src/main/java/org/apache/activemq/store/amq/AMQTx.java b/activemq-core/src/main/java/org/apache/activemq/store/amq/AMQTx.java index 697ed3333b..dfb0e88855 100644 --- a/activemq-core/src/main/java/org/apache/activemq/store/amq/AMQTx.java +++ b/activemq-core/src/main/java/org/apache/activemq/store/amq/AMQTx.java @@ -24,56 +24,59 @@ import org.apache.activemq.command.Message; import org.apache.activemq.command.MessageAck; import org.apache.activemq.kaha.impl.async.Location; - /** */ /** * Operations + * * @version $Revision: 1.6 $ */ -public class AMQTx{ +public class AMQTx { private final Location location; - private ArrayList operations=new ArrayList(); + private ArrayList operations = new ArrayList(); - public AMQTx(Location location){ - this.location=location; + public AMQTx(Location location) { + this.location = location; } - public void add(AMQMessageStore store,Message msg,Location location){ - operations.add(new AMQTxOperation(AMQTxOperation.ADD_OPERATION_TYPE,store.getDestination(),msg,location)); + public void add(AMQMessageStore store, Message msg, Location location) { + operations.add(new AMQTxOperation(AMQTxOperation.ADD_OPERATION_TYPE, store.getDestination(), msg, + location)); } - public void add(AMQMessageStore store,MessageAck ack){ - operations.add(new AMQTxOperation(AMQTxOperation.REMOVE_OPERATION_TYPE,store.getDestination(),ack,null)); + public void add(AMQMessageStore store, MessageAck ack) { + operations.add(new AMQTxOperation(AMQTxOperation.REMOVE_OPERATION_TYPE, store.getDestination(), ack, + null)); } - public void add(AMQTopicMessageStore store,JournalTopicAck ack){ - operations.add(new AMQTxOperation(AMQTxOperation.ACK_OPERATION_TYPE,store.getDestination(),ack,null)); + public void add(AMQTopicMessageStore store, JournalTopicAck ack) { + operations.add(new AMQTxOperation(AMQTxOperation.ACK_OPERATION_TYPE, store.getDestination(), ack, + null)); } - public Message[] getMessages(){ - ArrayList list=new ArrayList(); - for(Iterator iter=operations.iterator();iter.hasNext();){ - AMQTxOperation op=iter.next(); - if(op.getOperationType()==AMQTxOperation.ADD_OPERATION_TYPE){ + public Message[] getMessages() { + ArrayList list = new ArrayList(); + for (Iterator iter = operations.iterator(); iter.hasNext();) { + AMQTxOperation op = iter.next(); + if (op.getOperationType() == AMQTxOperation.ADD_OPERATION_TYPE) { list.add(op.getData()); } } - Message rc[]=new Message[list.size()]; + Message rc[] = new Message[list.size()]; list.toArray(rc); return rc; } - public MessageAck[] getAcks(){ - ArrayList list=new ArrayList(); - for(Iterator iter=operations.iterator();iter.hasNext();){ - AMQTxOperation op=iter.next(); - if(op.getOperationType()==AMQTxOperation.REMOVE_OPERATION_TYPE){ + public MessageAck[] getAcks() { + ArrayList list = new ArrayList(); + for (Iterator iter = operations.iterator(); iter.hasNext();) { + AMQTxOperation op = iter.next(); + if (op.getOperationType() == AMQTxOperation.REMOVE_OPERATION_TYPE) { list.add(op.getData()); } } - MessageAck rc[]=new MessageAck[list.size()]; + MessageAck rc[] = new MessageAck[list.size()]; list.toArray(rc); return rc; } @@ -81,17 +84,15 @@ public class AMQTx{ /** * @return the location */ - public Location getLocation(){ + public Location getLocation() { return this.location; } - public ArrayList getOperations(){ + public ArrayList getOperations() { return operations; } - public void setOperations(ArrayList operations){ - this.operations=operations; + public void setOperations(ArrayList operations) { + this.operations = operations; } } - - \ No newline at end of file diff --git a/activemq-core/src/main/java/org/apache/activemq/store/amq/AMQTxOperation.java b/activemq-core/src/main/java/org/apache/activemq/store/amq/AMQTxOperation.java index dcb092dd72..b9f11a59d3 100644 --- a/activemq-core/src/main/java/org/apache/activemq/store/amq/AMQTxOperation.java +++ b/activemq-core/src/main/java/org/apache/activemq/store/amq/AMQTxOperation.java @@ -29,14 +29,13 @@ import org.apache.activemq.kaha.impl.async.Location; import org.apache.activemq.util.ByteSequence; import org.apache.activemq.wireformat.WireFormat; - /** */ public class AMQTxOperation { - public static final byte ADD_OPERATION_TYPE=0; - public static final byte REMOVE_OPERATION_TYPE=1; - public static final byte ACK_OPERATION_TYPE=3; + public static final byte ADD_OPERATION_TYPE = 0; + public static final byte REMOVE_OPERATION_TYPE = 1; + public static final byte ACK_OPERATION_TYPE = 3; private byte operationType; private ActiveMQDestination destination; private Object data; @@ -44,74 +43,73 @@ public class AMQTxOperation { public AMQTxOperation() { } - - public AMQTxOperation(byte operationType,ActiveMQDestination destination,Object data,Location location){ - this.operationType=operationType; - this.destination=destination; - this.data=data; - this.location=location; - + + public AMQTxOperation(byte operationType, ActiveMQDestination destination, Object data, Location location) { + this.operationType = operationType; + this.destination = destination; + this.data = data; + this.location = location; + } /** * @return the data */ - public Object getData(){ + public Object getData() { return this.data; } /** * @param data the data to set */ - public void setData(Object data){ - this.data=data; + public void setData(Object data) { + this.data = data; } /** * @return the location */ - public Location getLocation(){ + public Location getLocation() { return this.location; } /** * @param location the location to set */ - public void setLocation(Location location){ - this.location=location; + public void setLocation(Location location) { + this.location = location; } /** * @return the operationType */ - public byte getOperationType(){ + public byte getOperationType() { return this.operationType; } /** * @param operationType the operationType to set */ - public void setOperationType(byte operationType){ - this.operationType=operationType; + public void setOperationType(byte operationType) { + this.operationType = operationType; } - - public boolean replay(AMQPersistenceAdapter adapter,ConnectionContext context) throws IOException{ - boolean result=false; - AMQMessageStore store=(AMQMessageStore)adapter.createMessageStore(destination); - if(operationType==ADD_OPERATION_TYPE){ - result=store.replayAddMessage(context,(Message)data,location); - }else if(operationType==REMOVE_OPERATION_TYPE){ - result=store.replayRemoveMessage(context,(MessageAck)data); - }else{ - JournalTopicAck ack=(JournalTopicAck)data; - result=((AMQTopicMessageStore)store).replayAcknowledge(context,ack.getClientId(),ack.getSubscritionName(), - ack.getMessageId()); + public boolean replay(AMQPersistenceAdapter adapter, ConnectionContext context) throws IOException { + boolean result = false; + AMQMessageStore store = (AMQMessageStore)adapter.createMessageStore(destination); + if (operationType == ADD_OPERATION_TYPE) { + result = store.replayAddMessage(context, (Message)data, location); + } else if (operationType == REMOVE_OPERATION_TYPE) { + result = store.replayRemoveMessage(context, (MessageAck)data); + } else { + JournalTopicAck ack = (JournalTopicAck)data; + result = ((AMQTopicMessageStore)store).replayAcknowledge(context, ack.getClientId(), ack + .getSubscritionName(), ack.getMessageId()); } return result; } - - public void writeExternal(WireFormat wireFormat,DataOutput dos) throws IOException { + + public void writeExternal(WireFormat wireFormat, DataOutput dos) throws IOException { location.writeExternal(dos); ByteSequence packet = wireFormat.marshal(getData()); dos.writeInt(packet.length); @@ -121,16 +119,16 @@ public class AMQTxOperation { dos.write(packet.data, packet.offset, packet.length); } - public void readExternal(WireFormat wireFormat,DataInput dis) throws IOException { - this.location=new Location(); + public void readExternal(WireFormat wireFormat, DataInput dis) throws IOException { + this.location = new Location(); this.location.readExternal(dis); - int size=dis.readInt(); - byte[] data=new byte[size]; + int size = dis.readInt(); + byte[] data = new byte[size]; dis.readFully(data); setData(wireFormat.unmarshal(new ByteSequence(data))); - size=dis.readInt(); - data=new byte[size]; + size = dis.readInt(); + data = new byte[size]; dis.readFully(data); - this.destination=(ActiveMQDestination)wireFormat.unmarshal(new ByteSequence(data)); + this.destination = (ActiveMQDestination)wireFormat.unmarshal(new ByteSequence(data)); } } diff --git a/activemq-core/src/main/java/org/apache/activemq/store/amq/RecoveryListenerAdapter.java b/activemq-core/src/main/java/org/apache/activemq/store/amq/RecoveryListenerAdapter.java index 3ade719575..97a21168f1 100644 --- a/activemq-core/src/main/java/org/apache/activemq/store/amq/RecoveryListenerAdapter.java +++ b/activemq-core/src/main/java/org/apache/activemq/store/amq/RecoveryListenerAdapter.java @@ -21,53 +21,52 @@ import org.apache.activemq.store.MessageStore; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -final class RecoveryListenerAdapter implements MessageRecoveryListener{ +final class RecoveryListenerAdapter implements MessageRecoveryListener { - static final private Log log=LogFactory.getLog(RecoveryListenerAdapter.class); + static final private Log log = LogFactory.getLog(RecoveryListenerAdapter.class); private final MessageStore store; private final MessageRecoveryListener listener; - private int count=0; + private int count = 0; private MessageId lastRecovered; - RecoveryListenerAdapter(MessageStore store,MessageRecoveryListener listener){ - this.store=store; - this.listener=listener; + RecoveryListenerAdapter(MessageStore store, MessageRecoveryListener listener) { + this.store = store; + this.listener = listener; } - - public boolean hasSpace(){ + public boolean hasSpace() { return listener.hasSpace(); } - public boolean recoverMessage(Message message) throws Exception{ - if(listener.hasSpace()){ + public boolean recoverMessage(Message message) throws Exception { + if (listener.hasSpace()) { listener.recoverMessage(message); - lastRecovered=message.getMessageId(); + lastRecovered = message.getMessageId(); count++; return true; } return false; } - public boolean recoverMessageReference(MessageId ref) throws Exception{ - Message message=this.store.getMessage(ref); - if(message!=null){ - return recoverMessage(message); - }else{ - log.error("Message id "+ref+" could not be recovered from the data store!"); + public boolean recoverMessageReference(MessageId ref) throws Exception { + Message message = this.store.getMessage(ref); + if (message != null) { + return recoverMessage(message); + } else { + log.error("Message id " + ref + " could not be recovered from the data store!"); } return false; } - + MessageId getLastRecoveredMessageId() { return lastRecovered; } - int size(){ + int size() { return count; } - void reset(){ - count=0; + void reset() { + count = 0; } -} \ No newline at end of file +} diff --git a/activemq-core/src/main/java/org/apache/activemq/store/jdbc/DataSourceSupport.java b/activemq-core/src/main/java/org/apache/activemq/store/jdbc/DataSourceSupport.java index 7ffada36d4..b02ff0d380 100644 --- a/activemq-core/src/main/java/org/apache/activemq/store/jdbc/DataSourceSupport.java +++ b/activemq-core/src/main/java/org/apache/activemq/store/jdbc/DataSourceSupport.java @@ -65,7 +65,7 @@ public class DataSourceSupport { public DataSource getDataSource() throws IOException { if (dataSource == null) { dataSource = createDataSource(); - if (dataSource == null) { + if (dataSource == null) { throw new IllegalArgumentException("No dataSource property has been configured"); } } @@ -88,9 +88,9 @@ public class DataSourceSupport { ds.setCreateDatabase("create"); return ds; } - - public String toString(){ - return ""+dataSource; + + public String toString() { + return "" + dataSource; } } diff --git a/activemq-core/src/main/java/org/apache/activemq/store/jdbc/JDBCAdapter.java b/activemq-core/src/main/java/org/apache/activemq/store/jdbc/JDBCAdapter.java index 994e4625c2..f52764882f 100755 --- a/activemq-core/src/main/java/org/apache/activemq/store/jdbc/JDBCAdapter.java +++ b/activemq-core/src/main/java/org/apache/activemq/store/jdbc/JDBCAdapter.java @@ -24,69 +24,87 @@ import org.apache.activemq.command.SubscriptionInfo; /** * @version $Revision: 1.5 $ */ -public interface JDBCAdapter{ +public interface JDBCAdapter { public void setStatements(Statements statementProvider); - public abstract void doCreateTables(TransactionContext c) throws SQLException,IOException; + public abstract void doCreateTables(TransactionContext c) throws SQLException, IOException; - public abstract void doDropTables(TransactionContext c) throws SQLException,IOException; + public abstract void doDropTables(TransactionContext c) throws SQLException, IOException; - public abstract void doAddMessage(TransactionContext c,MessageId messageID,ActiveMQDestination destination, - byte[] data,long expiration) throws SQLException,IOException; + public abstract void doAddMessage(TransactionContext c, MessageId messageID, + ActiveMQDestination destination, byte[] data, long expiration) + throws SQLException, IOException; - public abstract void doAddMessageReference(TransactionContext c,MessageId messageId, - ActiveMQDestination destination,long expirationTime,String messageRef) throws SQLException,IOException; + public abstract void doAddMessageReference(TransactionContext c, MessageId messageId, + ActiveMQDestination destination, long expirationTime, + String messageRef) throws SQLException, IOException; - public abstract byte[] doGetMessage(TransactionContext c,long seq) throws SQLException,IOException; + public abstract byte[] doGetMessage(TransactionContext c, long seq) throws SQLException, IOException; - public abstract String doGetMessageReference(TransactionContext c,long id) throws SQLException,IOException; + public abstract String doGetMessageReference(TransactionContext c, long id) throws SQLException, + IOException; - public abstract void doRemoveMessage(TransactionContext c,long seq) throws SQLException,IOException; + public abstract void doRemoveMessage(TransactionContext c, long seq) throws SQLException, IOException; - public abstract void doRecover(TransactionContext c,ActiveMQDestination destination, - JDBCMessageRecoveryListener listener) throws Exception; + public abstract void doRecover(TransactionContext c, ActiveMQDestination destination, + JDBCMessageRecoveryListener listener) throws Exception; - public abstract void doSetLastAck(TransactionContext c,ActiveMQDestination destination,String clientId, - String subscriptionName,long seq) throws SQLException,IOException; + public abstract void doSetLastAck(TransactionContext c, ActiveMQDestination destination, String clientId, + String subscriptionName, long seq) throws SQLException, IOException; - public abstract void doRecoverSubscription(TransactionContext c,ActiveMQDestination destination,String clientId, - String subscriptionName,JDBCMessageRecoveryListener listener) throws Exception; + public abstract void doRecoverSubscription(TransactionContext c, ActiveMQDestination destination, + String clientId, String subscriptionName, + JDBCMessageRecoveryListener listener) throws Exception; - public abstract void doRecoverNextMessages(TransactionContext c,ActiveMQDestination destination,String clientId, - String subscriptionName,long seq,int maxReturned,JDBCMessageRecoveryListener listener) throws Exception; + public abstract void doRecoverNextMessages(TransactionContext c, ActiveMQDestination destination, + String clientId, String subscriptionName, long seq, + int maxReturned, JDBCMessageRecoveryListener listener) + throws Exception; - public abstract void doSetSubscriberEntry(TransactionContext c,SubscriptionInfo subscriptionInfo,boolean retroactive) throws SQLException,IOException; + public abstract void doSetSubscriberEntry(TransactionContext c, SubscriptionInfo subscriptionInfo, + boolean retroactive) throws SQLException, IOException; - public abstract SubscriptionInfo doGetSubscriberEntry(TransactionContext c,ActiveMQDestination destination, - String clientId,String subscriptionName) throws SQLException,IOException; + public abstract SubscriptionInfo doGetSubscriberEntry(TransactionContext c, + ActiveMQDestination destination, String clientId, + String subscriptionName) throws SQLException, + IOException; - public abstract long getBrokerSequenceId(TransactionContext c,MessageId messageID) throws SQLException,IOException; + public abstract long getBrokerSequenceId(TransactionContext c, MessageId messageID) throws SQLException, + IOException; - public abstract void doRemoveAllMessages(TransactionContext c,ActiveMQDestination destinationName) - throws SQLException,IOException; + public abstract void doRemoveAllMessages(TransactionContext c, ActiveMQDestination destinationName) + throws SQLException, IOException; - public abstract void doDeleteSubscription(TransactionContext c,ActiveMQDestination destinationName,String clientId, - String subscriptionName) throws SQLException,IOException; + public abstract void doDeleteSubscription(TransactionContext c, ActiveMQDestination destinationName, + String clientId, String subscriptionName) throws SQLException, + IOException; - public abstract void doDeleteOldMessages(TransactionContext c) throws SQLException,IOException; + public abstract void doDeleteOldMessages(TransactionContext c) throws SQLException, IOException; - public abstract long doGetLastMessageBrokerSequenceId(TransactionContext c) throws SQLException,IOException; + public abstract long doGetLastMessageBrokerSequenceId(TransactionContext c) throws SQLException, + IOException; - public abstract Set doGetDestinations(TransactionContext c) throws SQLException,IOException; + public abstract Set doGetDestinations(TransactionContext c) throws SQLException, IOException; public abstract void setUseExternalMessageReferences(boolean useExternalMessageReferences); - public abstract SubscriptionInfo[] doGetAllSubscriptions(TransactionContext c,ActiveMQDestination destination) - throws SQLException,IOException; + public abstract SubscriptionInfo[] doGetAllSubscriptions(TransactionContext c, + ActiveMQDestination destination) + throws SQLException, IOException; - public int doGetDurableSubscriberMessageCount(TransactionContext c,ActiveMQDestination destination,String clientId, - String subscriptionName) throws SQLException,IOException; + public int doGetDurableSubscriberMessageCount(TransactionContext c, ActiveMQDestination destination, + String clientId, String subscriptionName) + throws SQLException, IOException; - public int doGetMessageCount(TransactionContext c, ActiveMQDestination destination) throws SQLException, IOException; - - public void doRecoverNextMessages(TransactionContext c,ActiveMQDestination destination,long nextSeq,int maxReturned, - JDBCMessageRecoveryListener listener) throws Exception; - - public long doGetLastAckedDurableSubscriberMessageId(TransactionContext c,ActiveMQDestination destination,String clientId, String subscriberName) throws SQLException,IOException; -} \ No newline at end of file + public int doGetMessageCount(TransactionContext c, ActiveMQDestination destination) throws SQLException, + IOException; + + public void doRecoverNextMessages(TransactionContext c, ActiveMQDestination destination, long nextSeq, + int maxReturned, JDBCMessageRecoveryListener listener) throws Exception; + + public long doGetLastAckedDurableSubscriberMessageId(TransactionContext c, + ActiveMQDestination destination, String clientId, + String subscriberName) throws SQLException, + IOException; +} diff --git a/activemq-core/src/main/java/org/apache/activemq/store/jdbc/JDBCMessageStore.java b/activemq-core/src/main/java/org/apache/activemq/store/jdbc/JDBCMessageStore.java index 0e1b546479..910200cbb9 100755 --- a/activemq-core/src/main/java/org/apache/activemq/store/jdbc/JDBCMessageStore.java +++ b/activemq-core/src/main/java/org/apache/activemq/store/jdbc/JDBCMessageStore.java @@ -19,6 +19,7 @@ package org.apache.activemq.store.jdbc; import java.io.IOException; import java.sql.SQLException; import java.util.concurrent.atomic.AtomicLong; + import org.apache.activemq.broker.ConnectionContext; import org.apache.activemq.command.ActiveMQDestination; import org.apache.activemq.command.Message; @@ -32,7 +33,6 @@ import org.apache.activemq.util.ByteSequenceData; import org.apache.activemq.util.IOExceptionSupport; import org.apache.activemq.wireformat.WireFormat; - /** * @version $Revision: 1.10 $ */ @@ -44,8 +44,7 @@ public class JDBCMessageStore implements MessageStore { protected final JDBCPersistenceAdapter persistenceAdapter; protected AtomicLong lastMessageId = new AtomicLong(-1); - public JDBCMessageStore(JDBCPersistenceAdapter persistenceAdapter, JDBCAdapter adapter, WireFormat wireFormat, - ActiveMQDestination destination) { + public JDBCMessageStore(JDBCPersistenceAdapter persistenceAdapter, JDBCAdapter adapter, WireFormat wireFormat, ActiveMQDestination destination) { this.persistenceAdapter = persistenceAdapter; this.adapter = adapter; this.wireFormat = wireFormat; @@ -53,15 +52,14 @@ public class JDBCMessageStore implements MessageStore { } public void addMessage(ConnectionContext context, Message message) throws IOException { - + // Serialize the Message.. byte data[]; try { ByteSequence packet = wireFormat.marshal(message); data = ByteSequenceData.toByteArray(packet); } catch (IOException e) { - throw IOExceptionSupport.create("Failed to broker message: " + message.getMessageId() + " in container: " - + e, e); + throw IOExceptionSupport.create("Failed to broker message: " + message.getMessageId() + " in container: " + e, e); } // Get a connection and insert the message into the DB. @@ -69,9 +67,8 @@ public class JDBCMessageStore implements MessageStore { try { adapter.doAddMessage(c, message.getMessageId(), destination, data, message.getExpiration()); } catch (SQLException e) { - JDBCPersistenceAdapter.log("JDBC Failure: ",e); - throw IOExceptionSupport.create("Failed to broker message: " + message.getMessageId() + " in container: " - + e, e); + JDBCPersistenceAdapter.log("JDBC Failure: ", e); + throw IOExceptionSupport.create("Failed to broker message: " + message.getMessageId() + " in container: " + e, e); } finally { c.close(); } @@ -83,9 +80,8 @@ public class JDBCMessageStore implements MessageStore { try { adapter.doAddMessageReference(c, messageId, destination, expirationTime, messageRef); } catch (SQLException e) { - JDBCPersistenceAdapter.log("JDBC Failure: ",e); - throw IOExceptionSupport.create("Failed to broker message: " + messageId + " in container: " - + e, e); + JDBCPersistenceAdapter.log("JDBC Failure: ", e); + throw IOExceptionSupport.create("Failed to broker message: " + messageId + " in container: " + e, e); } finally { c.close(); } @@ -94,7 +90,7 @@ public class JDBCMessageStore implements MessageStore { public Message getMessage(MessageId messageId) throws IOException { long id = messageId.getBrokerSequenceId(); - + // Get a connection and pull the message out of the DB TransactionContext c = persistenceAdapter.getTransactionContext(); try { @@ -102,21 +98,21 @@ public class JDBCMessageStore implements MessageStore { if (data == null) return null; - Message answer = (Message) wireFormat.unmarshal(new ByteSequence(data)); + Message answer = (Message)wireFormat.unmarshal(new ByteSequence(data)); return answer; } catch (IOException e) { throw IOExceptionSupport.create("Failed to broker message: " + messageId + " in container: " + e, e); } catch (SQLException e) { - JDBCPersistenceAdapter.log("JDBC Failure: ",e); + JDBCPersistenceAdapter.log("JDBC Failure: ", e); throw IOExceptionSupport.create("Failed to broker message: " + messageId + " in container: " + e, e); } finally { c.close(); } } - + public String getMessageReference(MessageId messageId) throws IOException { long id = messageId.getBrokerSequenceId(); - + // Get a connection and pull the message out of the DB TransactionContext c = persistenceAdapter.getTransactionContext(); try { @@ -124,7 +120,7 @@ public class JDBCMessageStore implements MessageStore { } catch (IOException e) { throw IOExceptionSupport.create("Failed to broker message: " + messageId + " in container: " + e, e); } catch (SQLException e) { - JDBCPersistenceAdapter.log("JDBC Failure: ",e); + JDBCPersistenceAdapter.log("JDBC Failure: ", e); throw IOExceptionSupport.create("Failed to broker message: " + messageId + " in container: " + e, e); } finally { c.close(); @@ -139,7 +135,7 @@ public class JDBCMessageStore implements MessageStore { try { adapter.doRemoveMessage(c, seq); } catch (SQLException e) { - JDBCPersistenceAdapter.log("JDBC Failure: ",e); + JDBCPersistenceAdapter.log("JDBC Failure: ", e); throw IOExceptionSupport.create("Failed to broker message: " + ack.getLastMessageId() + " in container: " + e, e); } finally { c.close(); @@ -154,16 +150,17 @@ public class JDBCMessageStore implements MessageStore { c = persistenceAdapter.getTransactionContext(); adapter.doRecover(c, destination, new JDBCMessageRecoveryListener() { public boolean recoverMessage(long sequenceId, byte[] data) throws Exception { - Message msg = (Message) wireFormat.unmarshal(new ByteSequence(data)); + Message msg = (Message)wireFormat.unmarshal(new ByteSequence(data)); msg.getMessageId().setBrokerSequenceId(sequenceId); return listener.recoverMessage(msg); } + public boolean recoverMessageReference(String reference) throws Exception { return listener.recoverMessageReference(new MessageId(reference)); } }); } catch (SQLException e) { - JDBCPersistenceAdapter.log("JDBC Failure: ",e); + JDBCPersistenceAdapter.log("JDBC Failure: ", e); throw IOExceptionSupport.create("Failed to recover container. Reason: " + e, e); } finally { c.close(); @@ -185,13 +182,13 @@ public class JDBCMessageStore implements MessageStore { try { adapter.doRemoveAllMessages(c, destination); } catch (SQLException e) { - JDBCPersistenceAdapter.log("JDBC Failure: ",e); + JDBCPersistenceAdapter.log("JDBC Failure: ", e); throw IOExceptionSupport.create("Failed to broker remove all messages: " + e, e); } finally { c.close(); } } - + public ActiveMQDestination getDestination() { return destination; } @@ -200,16 +197,15 @@ public class JDBCMessageStore implements MessageStore { // we can ignore since we don't buffer up messages. } - - public int getMessageCount() throws IOException{ + public int getMessageCount() throws IOException { int result = 0; TransactionContext c = persistenceAdapter.getTransactionContext(); try { - + result = adapter.doGetMessageCount(c, destination); - + } catch (SQLException e) { - JDBCPersistenceAdapter.log("JDBC Failure: ",e); + JDBCPersistenceAdapter.log("JDBC Failure: ", e); throw IOExceptionSupport.create("Failed to get Message Count: " + destination + ". Reason: " + e, e); } finally { c.close(); @@ -221,50 +217,49 @@ public class JDBCMessageStore implements MessageStore { * @param maxReturned * @param listener * @throws Exception - * @see org.apache.activemq.store.MessageStore#recoverNextMessages(int, org.apache.activemq.store.MessageRecoveryListener) + * @see org.apache.activemq.store.MessageStore#recoverNextMessages(int, + * org.apache.activemq.store.MessageRecoveryListener) */ - public void recoverNextMessages(int maxReturned,final MessageRecoveryListener listener) throws Exception{ - TransactionContext c=persistenceAdapter.getTransactionContext(); - - try{ - adapter.doRecoverNextMessages(c,destination,lastMessageId.get(),maxReturned, - new JDBCMessageRecoveryListener(){ + public void recoverNextMessages(int maxReturned, final MessageRecoveryListener listener) throws Exception { + TransactionContext c = persistenceAdapter.getTransactionContext(); - public boolean recoverMessage(long sequenceId,byte[] data) throws Exception{ - if(listener.hasSpace()){ - Message msg=(Message)wireFormat.unmarshal(new ByteSequence(data)); - msg.getMessageId().setBrokerSequenceId(sequenceId); - listener.recoverMessage(msg); - lastMessageId.set(sequenceId); - return true; - } - return false; - } + try { + adapter.doRecoverNextMessages(c, destination, lastMessageId.get(), maxReturned, new JDBCMessageRecoveryListener() { - public boolean recoverMessageReference(String reference) throws Exception{ - if(listener.hasSpace()) { - listener.recoverMessageReference(new MessageId(reference)); - return true; - } - return false; - } + public boolean recoverMessage(long sequenceId, byte[] data) throws Exception { + if (listener.hasSpace()) { + Message msg = (Message)wireFormat.unmarshal(new ByteSequence(data)); + msg.getMessageId().setBrokerSequenceId(sequenceId); + listener.recoverMessage(msg); + lastMessageId.set(sequenceId); + return true; + } + return false; + } - }); - }catch(SQLException e){ - JDBCPersistenceAdapter.log("JDBC Failure: ",e); - }finally{ + public boolean recoverMessageReference(String reference) throws Exception { + if (listener.hasSpace()) { + listener.recoverMessageReference(new MessageId(reference)); + return true; + } + return false; + } + + }); + } catch (SQLException e) { + JDBCPersistenceAdapter.log("JDBC Failure: ", e); + } finally { c.close(); } - + } /** - * * @see org.apache.activemq.store.MessageStore#resetBatching() */ - public void resetBatching(){ + public void resetBatching() { lastMessageId.set(-1); - + } } diff --git a/activemq-core/src/main/java/org/apache/activemq/store/jdbc/JDBCPersistenceAdapter.java b/activemq-core/src/main/java/org/apache/activemq/store/jdbc/JDBCPersistenceAdapter.java index 8bfdccd7f3..c7facd05c9 100755 --- a/activemq-core/src/main/java/org/apache/activemq/store/jdbc/JDBCPersistenceAdapter.java +++ b/activemq-core/src/main/java/org/apache/activemq/store/jdbc/JDBCPersistenceAdapter.java @@ -60,10 +60,12 @@ import java.util.Set; * * @version $Revision: 1.9 $ */ -public class JDBCPersistenceAdapter extends DataSourceSupport implements PersistenceAdapter, BrokerServiceAware { +public class JDBCPersistenceAdapter extends DataSourceSupport implements PersistenceAdapter, + BrokerServiceAware { private static final Log log = LogFactory.getLog(JDBCPersistenceAdapter.class); - private static FactoryFinder factoryFinder = new FactoryFinder("META-INF/services/org/apache/activemq/store/jdbc/"); + private static FactoryFinder factoryFinder = new FactoryFinder( + "META-INF/services/org/apache/activemq/store/jdbc/"); private WireFormat wireFormat = new OpenWireFormat(); private BrokerService brokerService; @@ -93,20 +95,16 @@ public class JDBCPersistenceAdapter extends DataSourceSupport implements Persist try { c = getTransactionContext(); return getAdapter().doGetDestinations(c); - } - catch (IOException e) { + } catch (IOException e) { return Collections.EMPTY_SET; - } - catch (SQLException e) { + } catch (SQLException e) { JDBCPersistenceAdapter.log("JDBC Failure: ", e); return Collections.EMPTY_SET; - } - finally { + } finally { if (c != null) { try { c.close(); - } - catch (Throwable e) { + } catch (Throwable e) { } } } @@ -141,7 +139,7 @@ public class JDBCPersistenceAdapter extends DataSourceSupport implements Persist try { return getAdapter().doGetLastMessageBrokerSequenceId(c); } catch (SQLException e) { - JDBCPersistenceAdapter.log("JDBC Failure: ",e); + JDBCPersistenceAdapter.log("JDBC Failure: ", e); throw IOExceptionSupport.create("Failed to get last broker message id: " + e, e); } finally { c.close(); @@ -159,19 +157,18 @@ public class JDBCPersistenceAdapter extends DataSourceSupport implements Persist getAdapter().doCreateTables(transactionContext); } catch (SQLException e) { log.warn("Cannot create tables due to: " + e); - JDBCPersistenceAdapter.log("Failure Details: ",e); + JDBCPersistenceAdapter.log("Failure Details: ", e); } } finally { transactionContext.commit(); } } - + if (isUseDatabaseLock()) { DatabaseLocker service = getDatabaseLocker(); if (service == null) { log.warn("No databaseLocker configured for the JDBC Persistence Adapter"); - } - else { + } else { service.start(); } } @@ -209,20 +206,16 @@ public class JDBCPersistenceAdapter extends DataSourceSupport implements Persist log.debug("Cleaning up old messages."); c = getTransactionContext(); getAdapter().doDeleteOldMessages(c); - } - catch (IOException e) { + } catch (IOException e) { log.warn("Old message cleanup failed due to: " + e, e); - } - catch (SQLException e) { + } catch (SQLException e) { log.warn("Old message cleanup failed due to: " + e); JDBCPersistenceAdapter.log("Failure Details: ", e); - } - finally { + } finally { if (c != null) { try { c.close(); - } - catch (Throwable e) { + } catch (Throwable e) { } } log.debug("Cleanup done."); @@ -253,7 +246,6 @@ public class JDBCPersistenceAdapter extends DataSourceSupport implements Persist return adapter; } - public DatabaseLocker getDatabaseLocker() throws IOException { if (databaseLocker == null) { databaseLocker = createDatabaseLocker(); @@ -274,7 +266,7 @@ public class JDBCPersistenceAdapter extends DataSourceSupport implements Persist public void setDatabaseLocker(DatabaseLocker databaseLocker) { this.databaseLocker = databaseLocker; } - + public BrokerService getBrokerService() { return brokerService; } @@ -287,7 +279,7 @@ public class JDBCPersistenceAdapter extends DataSourceSupport implements Persist * @throws IOException */ protected JDBCAdapter createAdapter() throws IOException { - JDBCAdapter adapter=null; + JDBCAdapter adapter = null; TransactionContext c = getTransactionContext(); try { @@ -298,17 +290,18 @@ public class JDBCPersistenceAdapter extends DataSourceSupport implements Persist dirverName = dirverName.replaceAll("[^a-zA-Z0-9\\-]", "_").toLowerCase(); try { - adapter = (DefaultJDBCAdapter) factoryFinder.newInstance(dirverName); + adapter = (DefaultJDBCAdapter)factoryFinder.newInstance(dirverName); log.info("Database driver recognized: [" + dirverName + "]"); } catch (Throwable e) { log.warn("Database driver NOT recognized: [" + dirverName - + "]. Will use default JDBC implementation."); + + "]. Will use default JDBC implementation."); } } catch (SQLException e) { - log.warn("JDBC error occurred while trying to detect database type. Will use default JDBC implementation: " - + e.getMessage()); - JDBCPersistenceAdapter.log("Failure Details: ",e); + log + .warn("JDBC error occurred while trying to detect database type. Will use default JDBC implementation: " + + e.getMessage()); + JDBCPersistenceAdapter.log("Failure Details: ", e); } // Use the default JDBC adapter if the @@ -340,7 +333,7 @@ public class JDBCPersistenceAdapter extends DataSourceSupport implements Persist if (context == null) { return getTransactionContext(); } else { - TransactionContext answer = (TransactionContext) context.getLongTermStoreContext(); + TransactionContext answer = (TransactionContext)context.getLongTermStoreContext(); if (answer == null) { answer = new TransactionContext(getDataSource()); context.setLongTermStoreContext(answer); @@ -373,7 +366,8 @@ public class JDBCPersistenceAdapter extends DataSourceSupport implements Persist } /** - * Sets the number of milliseconds until the database is attempted to be cleaned up for durable topics + * Sets the number of milliseconds until the database is attempted to be + * cleaned up for durable topics */ public void setCleanupPeriod(int cleanupPeriod) { this.cleanupPeriod = cleanupPeriod; @@ -386,7 +380,7 @@ public class JDBCPersistenceAdapter extends DataSourceSupport implements Persist getAdapter().setUseExternalMessageReferences(isUseExternalMessageReferences()); getAdapter().doCreateTables(c); } catch (SQLException e) { - JDBCPersistenceAdapter.log("JDBC Failure: ",e); + JDBCPersistenceAdapter.log("JDBC Failure: ", e); throw IOExceptionSupport.create(e); } finally { c.close(); @@ -400,7 +394,7 @@ public class JDBCPersistenceAdapter extends DataSourceSupport implements Persist public void setUseExternalMessageReferences(boolean useExternalMessageReferences) { this.useExternalMessageReferences = useExternalMessageReferences; } - + public boolean isCreateTablesOnStartup() { return createTablesOnStartup; } @@ -417,23 +411,24 @@ public class JDBCPersistenceAdapter extends DataSourceSupport implements Persist } /** - * Sets whether or not an exclusive database lock should be used to enable JDBC Master/Slave. Enabled by default. + * Sets whether or not an exclusive database lock should be used to enable + * JDBC Master/Slave. Enabled by default. */ public void setUseDatabaseLock(boolean useDatabaseLock) { this.useDatabaseLock = useDatabaseLock; } static public void log(String msg, SQLException e) { - String s = msg+e.getMessage(); - while( e.getNextException() != null ) { + String s = msg + e.getMessage(); + while (e.getNextException() != null) { e = e.getNextException(); - s += ", due to: "+e.getMessage(); + s += ", due to: " + e.getMessage(); } log.debug(s, e); } public Statements getStatements() { - if( statements == null ) { + if (statements == null) { statements = new Statements(); } return statements; @@ -444,12 +439,12 @@ public class JDBCPersistenceAdapter extends DataSourceSupport implements Persist } /** - * @param usageManager The UsageManager that is controlling the destination's memory usage. + * @param usageManager The UsageManager that is controlling the + * destination's memory usage. */ public void setUsageManager(UsageManager usageManager) { } - protected void databaseLockKeepAlive() { boolean stop = false; try { @@ -459,8 +454,7 @@ public class JDBCPersistenceAdapter extends DataSourceSupport implements Persist stop = true; } } - } - catch (IOException e) { + } catch (IOException e) { log.error("Failed to get database when trying keepalive: " + e, e); } if (stop) { @@ -473,8 +467,7 @@ public class JDBCPersistenceAdapter extends DataSourceSupport implements Persist log.info("No longer able to keep the exclusive lock so giving up being a master"); try { brokerService.stop(); - } - catch (Exception e) { + } catch (Exception e) { log.warn("Failed to stop broker"); } } @@ -482,17 +475,17 @@ public class JDBCPersistenceAdapter extends DataSourceSupport implements Persist protected DatabaseLocker createDatabaseLocker() throws IOException { return new DefaultDatabaseLocker(getDataSource(), getStatements()); } - - public void setBrokerName(String brokerName){ - } - - public String toString(){ - return "JDBCPersistenceAdaptor("+super.toString()+")"; + + public void setBrokerName(String brokerName) { } - public void setDirectory(File dir){ + public String toString() { + return "JDBCPersistenceAdaptor(" + super.toString() + ")"; } - public void checkpoint(boolean sync) throws IOException{ + public void setDirectory(File dir) { + } + + public void checkpoint(boolean sync) throws IOException { } } diff --git a/activemq-core/src/main/java/org/apache/activemq/store/jdbc/JDBCTopicMessageStore.java b/activemq-core/src/main/java/org/apache/activemq/store/jdbc/JDBCTopicMessageStore.java index 12c4ffa013..34ba54be0d 100755 --- a/activemq-core/src/main/java/org/apache/activemq/store/jdbc/JDBCTopicMessageStore.java +++ b/activemq-core/src/main/java/org/apache/activemq/store/jdbc/JDBCTopicMessageStore.java @@ -21,6 +21,7 @@ import java.sql.SQLException; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicLong; + import org.apache.activemq.broker.ConnectionContext; import org.apache.activemq.command.ActiveMQTopic; import org.apache.activemq.command.Message; @@ -32,29 +33,26 @@ import org.apache.activemq.util.ByteSequence; import org.apache.activemq.util.IOExceptionSupport; import org.apache.activemq.wireformat.WireFormat; - /** * @version $Revision: 1.6 $ */ public class JDBCTopicMessageStore extends JDBCMessageStore implements TopicMessageStore { - private Map subscriberLastMessageMap=new ConcurrentHashMap(); - public JDBCTopicMessageStore(JDBCPersistenceAdapter persistenceAdapter, JDBCAdapter adapter, WireFormat wireFormat, - ActiveMQTopic topic) { + private Map subscriberLastMessageMap = new ConcurrentHashMap(); + + public JDBCTopicMessageStore(JDBCPersistenceAdapter persistenceAdapter, JDBCAdapter adapter, WireFormat wireFormat, ActiveMQTopic topic) { super(persistenceAdapter, adapter, wireFormat, topic); } - public void acknowledge(ConnectionContext context, String clientId, String subscriptionName, MessageId messageId) - throws IOException { + public void acknowledge(ConnectionContext context, String clientId, String subscriptionName, MessageId messageId) throws IOException { long seq = messageId.getBrokerSequenceId(); // Get a connection and insert the message into the DB. TransactionContext c = persistenceAdapter.getTransactionContext(context); try { adapter.doSetLastAck(c, destination, clientId, subscriptionName, seq); } catch (SQLException e) { - JDBCPersistenceAdapter.log("JDBC Failure: ",e); - throw IOExceptionSupport.create("Failed to store acknowledgment for: " + clientId + " on message " - + messageId + " in container: " + e, e); + JDBCPersistenceAdapter.log("JDBC Failure: ", e); + throw IOExceptionSupport.create("Failed to store acknowledgment for: " + clientId + " on message " + messageId + " in container: " + e, e); } finally { c.close(); } @@ -62,91 +60,86 @@ public class JDBCTopicMessageStore extends JDBCMessageStore implements TopicMess /** * @throws Exception - * */ - public void recoverSubscription(String clientId, String subscriptionName, final MessageRecoveryListener listener) - throws Exception { + public void recoverSubscription(String clientId, String subscriptionName, final MessageRecoveryListener listener) throws Exception { TransactionContext c = persistenceAdapter.getTransactionContext(); try { - adapter.doRecoverSubscription(c, destination, clientId, subscriptionName, - new JDBCMessageRecoveryListener() { - public boolean recoverMessage(long sequenceId, byte[] data) throws Exception { - Message msg = (Message) wireFormat.unmarshal(new ByteSequence(data)); - msg.getMessageId().setBrokerSequenceId(sequenceId); - return listener.recoverMessage(msg); - } - public boolean recoverMessageReference(String reference) throws Exception { - return listener.recoverMessageReference(new MessageId(reference)); - } - - }); + adapter.doRecoverSubscription(c, destination, clientId, subscriptionName, new JDBCMessageRecoveryListener() { + public boolean recoverMessage(long sequenceId, byte[] data) throws Exception { + Message msg = (Message)wireFormat.unmarshal(new ByteSequence(data)); + msg.getMessageId().setBrokerSequenceId(sequenceId); + return listener.recoverMessage(msg); + } + + public boolean recoverMessageReference(String reference) throws Exception { + return listener.recoverMessageReference(new MessageId(reference)); + } + + }); } catch (SQLException e) { - JDBCPersistenceAdapter.log("JDBC Failure: ",e); + JDBCPersistenceAdapter.log("JDBC Failure: ", e); throw IOExceptionSupport.create("Failed to recover subscription: " + clientId + ". Reason: " + e, e); } finally { c.close(); } } - public synchronized void recoverNextMessages(final String clientId,final String subscriptionName, - final int maxReturned,final MessageRecoveryListener listener) throws Exception{ - TransactionContext c=persistenceAdapter.getTransactionContext(); - String subcriberId=getSubscriptionKey(clientId,subscriptionName); - AtomicLong last=(AtomicLong)subscriberLastMessageMap.get(subcriberId); - if(last==null){ - long lastAcked = adapter.doGetLastAckedDurableSubscriberMessageId(c,destination,clientId,subscriptionName); - last=new AtomicLong(lastAcked); - subscriberLastMessageMap.put(subcriberId,last); + public synchronized void recoverNextMessages(final String clientId, final String subscriptionName, final int maxReturned, final MessageRecoveryListener listener) + throws Exception { + TransactionContext c = persistenceAdapter.getTransactionContext(); + String subcriberId = getSubscriptionKey(clientId, subscriptionName); + AtomicLong last = (AtomicLong)subscriberLastMessageMap.get(subcriberId); + if (last == null) { + long lastAcked = adapter.doGetLastAckedDurableSubscriberMessageId(c, destination, clientId, subscriptionName); + last = new AtomicLong(lastAcked); + subscriberLastMessageMap.put(subcriberId, last); } - final AtomicLong finalLast=last; - try{ - adapter.doRecoverNextMessages(c,destination,clientId,subscriptionName,last.get(),maxReturned, - new JDBCMessageRecoveryListener(){ + final AtomicLong finalLast = last; + try { + adapter.doRecoverNextMessages(c, destination, clientId, subscriptionName, last.get(), maxReturned, new JDBCMessageRecoveryListener() { - public boolean recoverMessage(long sequenceId,byte[] data) throws Exception{ - if(listener.hasSpace()){ - Message msg=(Message)wireFormat.unmarshal(new ByteSequence(data)); - msg.getMessageId().setBrokerSequenceId(sequenceId); - listener.recoverMessage(msg); - finalLast.set(sequenceId); - return true; - } - return false; - } + public boolean recoverMessage(long sequenceId, byte[] data) throws Exception { + if (listener.hasSpace()) { + Message msg = (Message)wireFormat.unmarshal(new ByteSequence(data)); + msg.getMessageId().setBrokerSequenceId(sequenceId); + listener.recoverMessage(msg); + finalLast.set(sequenceId); + return true; + } + return false; + } - public boolean recoverMessageReference(String reference) throws Exception{ - return listener.recoverMessageReference(new MessageId(reference)); - } + public boolean recoverMessageReference(String reference) throws Exception { + return listener.recoverMessageReference(new MessageId(reference)); + } - }); - }catch(SQLException e){ - JDBCPersistenceAdapter.log("JDBC Failure: ",e); - }finally{ + }); + } catch (SQLException e) { + JDBCPersistenceAdapter.log("JDBC Failure: ", e); + } finally { c.close(); last.set(finalLast.get()); } } - - public void resetBatching(String clientId,String subscriptionName) { - String subcriberId=getSubscriptionKey(clientId,subscriptionName); + + public void resetBatching(String clientId, String subscriptionName) { + String subcriberId = getSubscriptionKey(clientId, subscriptionName); subscriberLastMessageMap.remove(subcriberId); } - + /** * @see org.apache.activemq.store.TopicMessageStore#storeSubsciption(org.apache.activemq.service.SubscriptionInfo, * boolean) */ - public void addSubsciption(SubscriptionInfo subscriptionInfo, boolean retroactive) - throws IOException { + public void addSubsciption(SubscriptionInfo subscriptionInfo, boolean retroactive) throws IOException { TransactionContext c = persistenceAdapter.getTransactionContext(); try { c = persistenceAdapter.getTransactionContext(); adapter.doSetSubscriberEntry(c, subscriptionInfo, retroactive); } catch (SQLException e) { - JDBCPersistenceAdapter.log("JDBC Failure: ",e); - throw IOExceptionSupport - .create("Failed to lookup subscription for info: " + subscriptionInfo.getClientId() + ". Reason: " + e, e); + JDBCPersistenceAdapter.log("JDBC Failure: ", e); + throw IOExceptionSupport.create("Failed to lookup subscription for info: " + subscriptionInfo.getClientId() + ". Reason: " + e, e); } finally { c.close(); } @@ -161,7 +154,7 @@ public class JDBCTopicMessageStore extends JDBCMessageStore implements TopicMess try { return adapter.doGetSubscriberEntry(c, destination, clientId, subscriptionName); } catch (SQLException e) { - JDBCPersistenceAdapter.log("JDBC Failure: ",e); + JDBCPersistenceAdapter.log("JDBC Failure: ", e); throw IOExceptionSupport.create("Failed to lookup subscription for: " + clientId + ". Reason: " + e, e); } finally { c.close(); @@ -173,11 +166,11 @@ public class JDBCTopicMessageStore extends JDBCMessageStore implements TopicMess try { adapter.doDeleteSubscription(c, destination, clientId, subscriptionName); } catch (SQLException e) { - JDBCPersistenceAdapter.log("JDBC Failure: ",e); + JDBCPersistenceAdapter.log("JDBC Failure: ", e); throw IOExceptionSupport.create("Failed to remove subscription for: " + clientId + ". Reason: " + e, e); } finally { c.close(); - resetBatching(clientId,subscriptionName); + resetBatching(clientId, subscriptionName); } } @@ -186,40 +179,32 @@ public class JDBCTopicMessageStore extends JDBCMessageStore implements TopicMess try { return adapter.doGetAllSubscriptions(c, destination); } catch (SQLException e) { - JDBCPersistenceAdapter.log("JDBC Failure: ",e); + JDBCPersistenceAdapter.log("JDBC Failure: ", e); throw IOExceptionSupport.create("Failed to lookup subscriptions. Reason: " + e, e); } finally { c.close(); } } - - - - - public int getMessageCount(String clientId,String subscriberName) throws IOException{ + public int getMessageCount(String clientId, String subscriberName) throws IOException { int result = 0; TransactionContext c = persistenceAdapter.getTransactionContext(); try { result = adapter.doGetDurableSubscriberMessageCount(c, destination, clientId, subscriberName); - + } catch (SQLException e) { - JDBCPersistenceAdapter.log("JDBC Failure: ",e); + JDBCPersistenceAdapter.log("JDBC Failure: ", e); throw IOExceptionSupport.create("Failed to get Message Count: " + clientId + ". Reason: " + e, e); } finally { c.close(); } return result; } - - protected String getSubscriptionKey(String clientId,String subscriberName){ - String result=clientId+":"; - result+=subscriberName!=null?subscriberName:"NOT_SET"; + + protected String getSubscriptionKey(String clientId, String subscriberName) { + String result = clientId + ":"; + result += subscriberName != null ? subscriberName : "NOT_SET"; return result; } - - - - } diff --git a/activemq-core/src/main/java/org/apache/activemq/store/jdbc/Statements.java b/activemq-core/src/main/java/org/apache/activemq/store/jdbc/Statements.java index feb9e0c991..ba16997597 100755 --- a/activemq-core/src/main/java/org/apache/activemq/store/jdbc/Statements.java +++ b/activemq-core/src/main/java/org/apache/activemq/store/jdbc/Statements.java @@ -97,16 +97,17 @@ public class Statements { public String[] getDropSchemaStatements() { if (dropSchemaStatements == null) { - dropSchemaStatements = new String[] { "DROP TABLE " + getFullAckTableName() + "", - "DROP TABLE " + getFullMessageTableName() + "", }; + dropSchemaStatements = new String[] {"DROP TABLE " + getFullAckTableName() + "", + "DROP TABLE " + getFullMessageTableName() + "",}; } return dropSchemaStatements; } public String getAddMessageStatement() { if (addMessageStatement == null) { - addMessageStatement = "INSERT INTO " + getFullMessageTableName() - + "(ID, MSGID_PROD, MSGID_SEQ, CONTAINER, EXPIRATION, MSG) VALUES (?, ?, ?, ?, ?, ?)"; + addMessageStatement = "INSERT INTO " + + getFullMessageTableName() + + "(ID, MSGID_PROD, MSGID_SEQ, CONTAINER, EXPIRATION, MSG) VALUES (?, ?, ?, ?, ?, ?)"; } return addMessageStatement; } @@ -128,7 +129,7 @@ public class Statements { public String getFindMessageSequenceIdStatement() { if (findMessageSequenceIdStatement == null) { findMessageSequenceIdStatement = "SELECT ID FROM " + getFullMessageTableName() - + " WHERE MSGID_PROD=? AND MSGID_SEQ=?"; + + " WHERE MSGID_PROD=? AND MSGID_SEQ=?"; } return findMessageSequenceIdStatement; } @@ -143,7 +144,7 @@ public class Statements { public String getFindAllMessagesStatement() { if (findAllMessagesStatement == null) { findAllMessagesStatement = "SELECT ID, MSG FROM " + getFullMessageTableName() - + " WHERE CONTAINER=? ORDER BY ID"; + + " WHERE CONTAINER=? ORDER BY ID"; } return findAllMessagesStatement; } @@ -164,8 +165,10 @@ public class Statements { public String getCreateDurableSubStatement() { if (createDurableSubStatement == null) { - createDurableSubStatement = "INSERT INTO " + getFullAckTableName() - + "(CONTAINER, CLIENT_ID, SUB_NAME, SELECTOR, LAST_ACKED_ID, SUB_DEST) " + "VALUES (?, ?, ?, ?, ?, ?)"; + createDurableSubStatement = "INSERT INTO " + + getFullAckTableName() + + "(CONTAINER, CLIENT_ID, SUB_NAME, SELECTOR, LAST_ACKED_ID, SUB_DEST) " + + "VALUES (?, ?, ?, ?, ?, ?)"; } return createDurableSubStatement; } @@ -173,15 +176,15 @@ public class Statements { public String getFindDurableSubStatement() { if (findDurableSubStatement == null) { findDurableSubStatement = "SELECT SELECTOR, SUB_DEST " + "FROM " + getFullAckTableName() - + " WHERE CONTAINER=? AND CLIENT_ID=? AND SUB_NAME=?"; + + " WHERE CONTAINER=? AND CLIENT_ID=? AND SUB_NAME=?"; } return findDurableSubStatement; } public String getFindAllDurableSubsStatement() { if (findAllDurableSubsStatement == null) { - findAllDurableSubsStatement = "SELECT SELECTOR, SUB_NAME, CLIENT_ID, SUB_DEST" + " FROM " + getFullAckTableName() - + " WHERE CONTAINER=?"; + findAllDurableSubsStatement = "SELECT SELECTOR, SUB_NAME, CLIENT_ID, SUB_DEST" + " FROM " + + getFullAckTableName() + " WHERE CONTAINER=?"; } return findAllDurableSubsStatement; } @@ -189,7 +192,7 @@ public class Statements { public String getUpdateLastAckOfDurableSubStatement() { if (updateLastAckOfDurableSubStatement == null) { updateLastAckOfDurableSubStatement = "UPDATE " + getFullAckTableName() + " SET LAST_ACKED_ID=?" - + " WHERE CONTAINER=? AND CLIENT_ID=? AND SUB_NAME=?"; + + " WHERE CONTAINER=? AND CLIENT_ID=? AND SUB_NAME=?"; } return updateLastAckOfDurableSubStatement; } @@ -197,62 +200,76 @@ public class Statements { public String getDeleteSubscriptionStatement() { if (deleteSubscriptionStatement == null) { deleteSubscriptionStatement = "DELETE FROM " + getFullAckTableName() - + " WHERE CONTAINER=? AND CLIENT_ID=? AND SUB_NAME=?"; + + " WHERE CONTAINER=? AND CLIENT_ID=? AND SUB_NAME=?"; } return deleteSubscriptionStatement; } public String getFindAllDurableSubMessagesStatement() { if (findAllDurableSubMessagesStatement == null) { - findAllDurableSubMessagesStatement = "SELECT M.ID, M.MSG FROM " + getFullMessageTableName() + " M, " - + getFullAckTableName() + " D " + " WHERE D.CONTAINER=? AND D.CLIENT_ID=? AND D.SUB_NAME=?" - + " AND M.CONTAINER=D.CONTAINER AND M.ID > D.LAST_ACKED_ID" + " ORDER BY M.ID"; + findAllDurableSubMessagesStatement = "SELECT M.ID, M.MSG FROM " + getFullMessageTableName() + + " M, " + getFullAckTableName() + " D " + + " WHERE D.CONTAINER=? AND D.CLIENT_ID=? AND D.SUB_NAME=?" + + " AND M.CONTAINER=D.CONTAINER AND M.ID > D.LAST_ACKED_ID" + + " ORDER BY M.ID"; } return findAllDurableSubMessagesStatement; } - - public String getFindDurableSubMessagesStatement(){ - if(findDurableSubMessagesStatement==null){ - findDurableSubMessagesStatement="SELECT M.ID, M.MSG FROM " + getFullMessageTableName() + " M, " - + getFullAckTableName() + " D " + " WHERE D.CONTAINER=? AND D.CLIENT_ID=? AND D.SUB_NAME=?" - + " AND M.CONTAINER=D.CONTAINER AND M.ID > ?" + " ORDER BY M.ID"; + + public String getFindDurableSubMessagesStatement() { + if (findDurableSubMessagesStatement == null) { + findDurableSubMessagesStatement = "SELECT M.ID, M.MSG FROM " + getFullMessageTableName() + " M, " + + getFullAckTableName() + " D " + + " WHERE D.CONTAINER=? AND D.CLIENT_ID=? AND D.SUB_NAME=?" + + " AND M.CONTAINER=D.CONTAINER AND M.ID > ?" + + " ORDER BY M.ID"; } return findDurableSubMessagesStatement; } - + public String findAllDurableSubMessagesStatement() { if (findAllDurableSubMessagesStatement == null) { - findAllDurableSubMessagesStatement = "SELECT M.ID, M.MSG FROM " + getFullMessageTableName() + " M, " - + getFullAckTableName() + " D " + " WHERE D.CONTAINER=? AND D.CLIENT_ID=? AND D.SUB_NAME=?" - + " AND M.CONTAINER=D.CONTAINER AND M.ID > D.LAST_ACKED_ID" + " ORDER BY M.ID"; + findAllDurableSubMessagesStatement = "SELECT M.ID, M.MSG FROM " + getFullMessageTableName() + + " M, " + getFullAckTableName() + " D " + + " WHERE D.CONTAINER=? AND D.CLIENT_ID=? AND D.SUB_NAME=?" + + " AND M.CONTAINER=D.CONTAINER AND M.ID > D.LAST_ACKED_ID" + + " ORDER BY M.ID"; } return findAllDurableSubMessagesStatement; } - - public String getNextDurableSubscriberMessageStatement(){ - if (nextDurableSubscriberMessageStatement == null){ - nextDurableSubscriberMessageStatement = "SELECT M.ID, M.MSG FROM " + getFullMessageTableName() + " M, " - + getFullAckTableName() + " D " + " WHERE D.CONTAINER=? AND D.CLIENT_ID=? AND D.SUB_NAME=?" - + " AND M.CONTAINER=D.CONTAINER AND M.ID > ?" + " ORDER BY M.ID "; + + public String getNextDurableSubscriberMessageStatement() { + if (nextDurableSubscriberMessageStatement == null) { + nextDurableSubscriberMessageStatement = "SELECT M.ID, M.MSG FROM " + + getFullMessageTableName() + + " M, " + + getFullAckTableName() + + " D " + + " WHERE D.CONTAINER=? AND D.CLIENT_ID=? AND D.SUB_NAME=?" + + " AND M.CONTAINER=D.CONTAINER AND M.ID > ?" + + " ORDER BY M.ID "; } return nextDurableSubscriberMessageStatement; } - + /** * @return the durableSubscriberMessageCountStatement */ - - - public String getDurableSubscriberMessageCountStatement(){ - if (durableSubscriberMessageCountStatement==null){ - durableSubscriberMessageCountStatement = "SELECT COUNT(*) FROM " + getFullMessageTableName() + " M, " - + getFullAckTableName() + " D " + " WHERE D.CONTAINER=? AND D.CLIENT_ID=? AND D.SUB_NAME=?" - + " AND M.CONTAINER=D.CONTAINER AND M.ID > D.LAST_ACKED_ID"; + + public String getDurableSubscriberMessageCountStatement() { + if (durableSubscriberMessageCountStatement == null) { + durableSubscriberMessageCountStatement = "SELECT COUNT(*) FROM " + + getFullMessageTableName() + + " M, " + + getFullAckTableName() + + " D " + + " WHERE D.CONTAINER=? AND D.CLIENT_ID=? AND D.SUB_NAME=?" + + " AND M.CONTAINER=D.CONTAINER AND M.ID > D.LAST_ACKED_ID"; } return durableSubscriberMessageCountStatement; } - - public String getFindAllDestinationsStatement() { + + public String getFindAllDestinationsStatement() { if (findAllDestinationsStatement == null) { findAllDestinationsStatement = "SELECT DISTINCT CONTAINER FROM " + getFullMessageTableName(); } @@ -276,13 +293,15 @@ public class Statements { public String getDeleteOldMessagesStatement() { if (deleteOldMessagesStatement == null) { deleteOldMessagesStatement = "DELETE FROM " + getFullMessageTableName() - + " WHERE ( EXPIRATION<>0 AND EXPIRATION0 AND EXPIRATION ? ORDER BY ID"; + public String getFindNextMessagesStatement() { + if (findNextMessagesStatement == null) { + findNextMessagesStatement = "SELECT ID, MSG FROM " + getFullMessageTableName() + + " WHERE CONTAINER=? AND ID > ? ORDER BY ID"; } return findNextMessagesStatement; } - + /** * @return the lastAckedDurableSubscriberMessageStatement */ - public String getLastAckedDurableSubscriberMessageStatement(){ - if(lastAckedDurableSubscriberMessageStatement==null) { - lastAckedDurableSubscriberMessageStatement = "SELECT MAX(LAST_ACKED_ID) FROM " + getFullAckTableName() - + " WHERE CONTAINER=? AND CLIENT_ID=? AND SUB_NAME=?"; + public String getLastAckedDurableSubscriberMessageStatement() { + if (lastAckedDurableSubscriberMessageStatement == null) { + lastAckedDurableSubscriberMessageStatement = "SELECT MAX(LAST_ACKED_ID) FROM " + + getFullAckTableName() + + " WHERE CONTAINER=? AND CLIENT_ID=? AND SUB_NAME=?"; } return lastAckedDurableSubscriberMessageStatement; } - - public String getFullMessageTableName() { return getTablePrefix() + getMessageTableName(); } @@ -343,12 +361,11 @@ public class Statements { public String getFullAckTableName() { return getTablePrefix() + getDurableSubAcksTableName(); } - + public String getFullLockTableName() { return getTablePrefix() + getLockTableName(); } - /** * @return Returns the containerNameDataType. */ @@ -357,8 +374,7 @@ public class Statements { } /** - * @param containerNameDataType - * The containerNameDataType to set. + * @param containerNameDataType The containerNameDataType to set. */ public void setContainerNameDataType(String containerNameDataType) { this.containerNameDataType = containerNameDataType; @@ -372,8 +388,7 @@ public class Statements { } /** - * @param messageDataType - * The messageDataType to set. + * @param messageDataType The messageDataType to set. */ public void setBinaryDataType(String messageDataType) { this.binaryDataType = messageDataType; @@ -387,8 +402,7 @@ public class Statements { } /** - * @param messageTableName - * The messageTableName to set. + * @param messageTableName The messageTableName to set. */ public void setMessageTableName(String messageTableName) { this.messageTableName = messageTableName; @@ -402,8 +416,7 @@ public class Statements { } /** - * @param msgIdDataType - * The msgIdDataType to set. + * @param msgIdDataType The msgIdDataType to set. */ public void setMsgIdDataType(String msgIdDataType) { this.msgIdDataType = msgIdDataType; @@ -417,8 +430,7 @@ public class Statements { } /** - * @param sequenceDataType - * The sequenceDataType to set. + * @param sequenceDataType The sequenceDataType to set. */ public void setSequenceDataType(String sequenceDataType) { this.sequenceDataType = sequenceDataType; @@ -432,8 +444,7 @@ public class Statements { } /** - * @param tablePrefix - * The tablePrefix to set. + * @param tablePrefix The tablePrefix to set. */ public void setTablePrefix(String tablePrefix) { this.tablePrefix = tablePrefix; @@ -447,13 +458,12 @@ public class Statements { } /** - * @param durableSubAcksTableName - * The durableSubAcksTableName to set. + * @param durableSubAcksTableName The durableSubAcksTableName to set. */ public void setDurableSubAcksTableName(String durableSubAcksTableName) { this.durableSubAcksTableName = durableSubAcksTableName; } - + public String getLockTableName() { return lockTableName; } @@ -583,52 +593,47 @@ public class Statements { } /** - * @param findDurableSubMessagesStatement the findDurableSubMessagesStatement to set + * @param findDurableSubMessagesStatement the + * findDurableSubMessagesStatement to set */ - public void setFindDurableSubMessagesStatement(String findDurableSubMessagesStatement){ - this.findDurableSubMessagesStatement=findDurableSubMessagesStatement; + public void setFindDurableSubMessagesStatement(String findDurableSubMessagesStatement) { + this.findDurableSubMessagesStatement = findDurableSubMessagesStatement; } /** * @param nextDurableSubscriberMessageStatement the nextDurableSubscriberMessageStatement to set */ - public void setNextDurableSubscriberMessageStatement(String nextDurableSubscriberMessageStatement){ - this.nextDurableSubscriberMessageStatement=nextDurableSubscriberMessageStatement; + public void setNextDurableSubscriberMessageStatement(String nextDurableSubscriberMessageStatement) { + this.nextDurableSubscriberMessageStatement = nextDurableSubscriberMessageStatement; } - /** * @param durableSubscriberMessageCountStatement the durableSubscriberMessageCountStatement to set */ - public void setDurableSubscriberMessageCountStatement(String durableSubscriberMessageCountStatement){ - this.durableSubscriberMessageCountStatement=durableSubscriberMessageCountStatement; - } - + public void setDurableSubscriberMessageCountStatement(String durableSubscriberMessageCountStatement) { + this.durableSubscriberMessageCountStatement = durableSubscriberMessageCountStatement; + } + /** * @param findNextMessagesStatement the findNextMessagesStatement to set */ - public void setFindNextMessagesStatement(String findNextMessagesStatement){ - this.findNextMessagesStatement=findNextMessagesStatement; + public void setFindNextMessagesStatement(String findNextMessagesStatement) { + this.findNextMessagesStatement = findNextMessagesStatement; } /** * @param destinationMessageCountStatement the destinationMessageCountStatement to set */ - public void setDestinationMessageCountStatement(String destinationMessageCountStatement){ - this.destinationMessageCountStatement=destinationMessageCountStatement; + public void setDestinationMessageCountStatement(String destinationMessageCountStatement) { + this.destinationMessageCountStatement = destinationMessageCountStatement; } - - - /** * @param lastAckedDurableSubscriberMessageStatement the lastAckedDurableSubscriberMessageStatement to set */ - public void setLastAckedDurableSubscriberMessageStatement(String lastAckedDurableSubscriberMessageStatement){ - this.lastAckedDurableSubscriberMessageStatement=lastAckedDurableSubscriberMessageStatement; + public void setLastAckedDurableSubscriberMessageStatement( + String lastAckedDurableSubscriberMessageStatement) { + this.lastAckedDurableSubscriberMessageStatement = lastAckedDurableSubscriberMessageStatement; } - - - - + } \ No newline at end of file diff --git a/activemq-core/src/main/java/org/apache/activemq/store/jdbc/TransactionContext.java b/activemq-core/src/main/java/org/apache/activemq/store/jdbc/TransactionContext.java index 3d9b3047e7..cbe4d3dea7 100755 --- a/activemq-core/src/main/java/org/apache/activemq/store/jdbc/TransactionContext.java +++ b/activemq-core/src/main/java/org/apache/activemq/store/jdbc/TransactionContext.java @@ -36,7 +36,7 @@ import org.apache.commons.logging.LogFactory; public class TransactionContext { private static final Log log = LogFactory.getLog(TransactionContext.class); - + private final DataSource dataSource; private Connection connection; private boolean inTx; @@ -49,7 +49,7 @@ public class TransactionContext { } public Connection getConnection() throws IOException { - if( connection == null ) { + if (connection == null) { try { connection = dataSource.getConnection(); boolean autoCommit = !inTx; @@ -60,7 +60,7 @@ public class TransactionContext { JDBCPersistenceAdapter.log("Could not get JDBC connection: ", e); throw IOExceptionSupport.create(e); } - + try { connection.setTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED); } catch (Throwable e) { @@ -77,51 +77,54 @@ public class TransactionContext { try { executeBatch(removedMessageStatement, "Failed to remove a message"); } finally { - removedMessageStatement=null; + removedMessageStatement = null; try { executeBatch(updateLastAckStatement, "Failed to ack a message"); } finally { - updateLastAckStatement=null; + updateLastAckStatement = null; } } } } private void executeBatch(PreparedStatement p, String message) throws SQLException { - if( p == null ) + if (p == null) return; - + try { int[] rc = p.executeBatch(); for (int i = 0; i < rc.length; i++) { int code = rc[i]; - if ( code < 0 && code != Statement.SUCCESS_NO_INFO ) { + if (code < 0 && code != Statement.SUCCESS_NO_INFO) { throw new SQLException(message + ". Response code: " + code); } } } finally { - try { p.close(); } catch (Throwable e) { } + try { + p.close(); + } catch (Throwable e) { + } } } - + public void close() throws IOException { - if( !inTx ) { + if (!inTx) { try { - + /** * we are not in a transaction so should not be committing ?? - * This was previously commented out - but had - * adverse affects on testing - so it's back! + * This was previously commented out - but had adverse affects + * on testing - so it's back! * */ - try{ + try { executeBatch(); } finally { if (connection != null && !connection.getAutoCommit()) { connection.commit(); } } - + } catch (SQLException e) { JDBCPersistenceAdapter.log("Error while closing connection: ", e); throw IOExceptionSupport.create(e); @@ -131,60 +134,60 @@ public class TransactionContext { connection.close(); } } catch (Throwable e) { - log.warn("Close failed: "+e.getMessage(), e); + log.warn("Close failed: " + e.getMessage(), e); } finally { - connection=null; + connection = null; } } } } public void begin() throws IOException { - if( inTx ) + if (inTx) throw new IOException("Already started."); inTx = true; connection = getConnection(); } public void commit() throws IOException { - if( !inTx ) + if (!inTx) throw new IOException("Not started."); try { executeBatch(); - if( !connection.getAutoCommit() ) + if (!connection.getAutoCommit()) connection.commit(); } catch (SQLException e) { JDBCPersistenceAdapter.log("Commit failed: ", e); throw IOExceptionSupport.create(e); } finally { - inTx=false; + inTx = false; close(); } } - + public void rollback() throws IOException { - if( !inTx ) + if (!inTx) throw new IOException("Not started."); try { - if( addMessageStatement != null ) { + if (addMessageStatement != null) { addMessageStatement.close(); - addMessageStatement=null; + addMessageStatement = null; } - if( removedMessageStatement != null ) { + if (removedMessageStatement != null) { removedMessageStatement.close(); - removedMessageStatement=null; + removedMessageStatement = null; } - if( updateLastAckStatement != null ) { + if (updateLastAckStatement != null) { updateLastAckStatement.close(); - updateLastAckStatement=null; + updateLastAckStatement = null; } connection.rollback(); - + } catch (SQLException e) { JDBCPersistenceAdapter.log("Rollback failed: ", e); throw IOExceptionSupport.create(e); } finally { - inTx=false; + inTx = false; close(); } } @@ -192,6 +195,7 @@ public class TransactionContext { public PreparedStatement getAddMessageStatement() { return addMessageStatement; } + public void setAddMessageStatement(PreparedStatement addMessageStatement) { this.addMessageStatement = addMessageStatement; } @@ -199,6 +203,7 @@ public class TransactionContext { public PreparedStatement getUpdateLastAckStatement() { return updateLastAckStatement; } + public void setUpdateLastAckStatement(PreparedStatement ackMessageStatement) { this.updateLastAckStatement = ackMessageStatement; } @@ -206,6 +211,7 @@ public class TransactionContext { public PreparedStatement getRemovedMessageStatement() { return removedMessageStatement; } + public void setRemovedMessageStatement(PreparedStatement removedMessageStatement) { this.removedMessageStatement = removedMessageStatement; } diff --git a/activemq-core/src/main/java/org/apache/activemq/store/jdbc/adapter/BlobJDBCAdapter.java b/activemq-core/src/main/java/org/apache/activemq/store/jdbc/adapter/BlobJDBCAdapter.java index 561936853c..d9e4a50594 100755 --- a/activemq-core/src/main/java/org/apache/activemq/store/jdbc/adapter/BlobJDBCAdapter.java +++ b/activemq-core/src/main/java/org/apache/activemq/store/jdbc/adapter/BlobJDBCAdapter.java @@ -30,19 +30,17 @@ import javax.jms.JMSException; import org.apache.activemq.store.jdbc.TransactionContext; import org.apache.activemq.util.ByteArrayOutputStream; - /** - * This JDBCAdapter inserts and extracts BLOB data using the - * getBlob()/setBlob() operations. This is a little more involved - * since to insert a blob you have to: + * This JDBCAdapter inserts and extracts BLOB data using the getBlob()/setBlob() + * operations. This is a little more involved since to insert a blob you have + * to: * - * 1: insert empty blob. - * 2: select the blob - * 3: finally update the blob with data value. + * 1: insert empty blob. 2: select the blob 3: finally update the blob with data + * value. * * The databases/JDBC drivers that use this adapter are: *
    - *
  • + *
  • *
* * @org.apache.xbean.XBean element="blobJDBCAdapter" @@ -50,23 +48,22 @@ import org.apache.activemq.util.ByteArrayOutputStream; * @version $Revision: 1.2 $ */ public class BlobJDBCAdapter extends DefaultJDBCAdapter { - - public void doAddMessage(Connection c, long seq, String messageID, String destinationName, byte[] data) throws SQLException, - JMSException { + + public void doAddMessage(Connection c, long seq, String messageID, String destinationName, byte[] data) + throws SQLException, JMSException { PreparedStatement s = null; ResultSet rs = null; try { - + // Add the Blob record. s = c.prepareStatement(statements.getAddMessageStatement()); s.setLong(1, seq); s.setString(2, destinationName); s.setString(3, messageID); s.setString(4, " "); - + if (s.executeUpdate() != 1) - throw new JMSException("Failed to broker message: " + messageID - + " in container."); + throw new JMSException("Failed to broker message: " + messageID + " in container."); s.close(); // Select the blob record so that we can update it. @@ -74,8 +71,7 @@ public class BlobJDBCAdapter extends DefaultJDBCAdapter { s.setLong(1, seq); rs = s.executeQuery(); if (!rs.next()) - throw new JMSException("Failed to broker message: " + messageID - + " in container."); + throw new JMSException("Failed to broker message: " + messageID + " in container."); // Update the blob Blob blob = rs.getBlob(1); @@ -90,8 +86,7 @@ public class BlobJDBCAdapter extends DefaultJDBCAdapter { s.setLong(2, seq); } catch (IOException e) { - throw (SQLException) new SQLException("BLOB could not be updated: " - + e).initCause(e); + throw (SQLException)new SQLException("BLOB could not be updated: " + e).initCause(e); } finally { try { rs.close(); @@ -103,37 +98,44 @@ public class BlobJDBCAdapter extends DefaultJDBCAdapter { } } } - + public byte[] doGetMessage(TransactionContext c, long seq) throws SQLException { - PreparedStatement s=null; ResultSet rs=null; - try { - - s = c.getConnection().prepareStatement(statements.getFindMessageStatement()); - s.setLong(1, seq); - rs = s.executeQuery(); - - if( !rs.next() ) - return null; - Blob blob = rs.getBlob(1); - InputStream is = blob.getBinaryStream(); - - ByteArrayOutputStream os = new ByteArrayOutputStream((int)blob.length()); - int ch; - while( (ch=is.read())>= 0 ) { - os.write(ch); - } - is.close(); - os.close(); - - return os.toByteArray(); - - } catch (IOException e) { - throw (SQLException) new SQLException("BLOB could not be updated: " - + e).initCause(e); + PreparedStatement s = null; + ResultSet rs = null; + try { + + s = c.getConnection().prepareStatement(statements.getFindMessageStatement()); + s.setLong(1, seq); + rs = s.executeQuery(); + + if (!rs.next()) { + return null; + } + Blob blob = rs.getBlob(1); + InputStream is = blob.getBinaryStream(); + + ByteArrayOutputStream os = new ByteArrayOutputStream((int)blob.length()); + int ch; + while ((ch = is.read()) >= 0) { + os.write(ch); + } + is.close(); + os.close(); + + return os.toByteArray(); + + } catch (IOException e) { + throw (SQLException)new SQLException("BLOB could not be updated: " + e).initCause(e); } finally { - try { rs.close(); } catch (Throwable e) {} - try { s.close(); } catch (Throwable e) {} - } + try { + rs.close(); + } catch (Throwable ignore) { + } + try { + s.close(); + } catch (Throwable ignore) { + } + } } } diff --git a/activemq-core/src/main/java/org/apache/activemq/store/jdbc/adapter/DefaultJDBCAdapter.java b/activemq-core/src/main/java/org/apache/activemq/store/jdbc/adapter/DefaultJDBCAdapter.java index 3674a18b32..0b1726b8d6 100755 --- a/activemq-core/src/main/java/org/apache/activemq/store/jdbc/adapter/DefaultJDBCAdapter.java +++ b/activemq-core/src/main/java/org/apache/activemq/store/jdbc/adapter/DefaultJDBCAdapter.java @@ -34,10 +34,12 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** - * Implements all the default JDBC operations that are used by the JDBCPersistenceAdapter.

sub-classing is - * encouraged to override the default implementation of methods to account for differences in JDBC Driver - * implementations.

The JDBCAdapter inserts and extracts BLOB data using the getBytes()/setBytes() operations.

- * The databases/JDBC drivers that use this adapter are: + * Implements all the default JDBC operations that are used by the + * JDBCPersistenceAdapter.

sub-classing is encouraged to override the + * default implementation of methods to account for differences in JDBC Driver + * implementations.

The JDBCAdapter inserts and extracts BLOB data using + * the getBytes()/setBytes() operations.

The databases/JDBC drivers that + * use this adapter are: *

    *
  • *
@@ -46,381 +48,390 @@ import org.apache.commons.logging.LogFactory; * * @version $Revision: 1.10 $ */ -public class DefaultJDBCAdapter implements JDBCAdapter{ +public class DefaultJDBCAdapter implements JDBCAdapter { - private static final Log log=LogFactory.getLog(DefaultJDBCAdapter.class); + private static final Log log = LogFactory.getLog(DefaultJDBCAdapter.class); protected Statements statements; - protected boolean batchStatments=true; + protected boolean batchStatments = true; - protected void setBinaryData(PreparedStatement s,int index,byte data[]) throws SQLException{ - s.setBytes(index,data); + protected void setBinaryData(PreparedStatement s, int index, byte data[]) throws SQLException { + s.setBytes(index, data); } - protected byte[] getBinaryData(ResultSet rs,int index) throws SQLException{ + protected byte[] getBinaryData(ResultSet rs, int index) throws SQLException { return rs.getBytes(index); } - public void doCreateTables(TransactionContext c) throws SQLException,IOException{ - Statement s=null; - try{ - // Check to see if the table already exists. If it does, then don't log warnings during startup. - // Need to run the scripts anyways since they may contain ALTER statements that upgrade a previous version + public void doCreateTables(TransactionContext c) throws SQLException, IOException { + Statement s = null; + try { + // Check to see if the table already exists. If it does, then don't + // log warnings during startup. + // Need to run the scripts anyways since they may contain ALTER + // statements that upgrade a previous version // of the table - boolean alreadyExists=false; - ResultSet rs=null; - try{ - rs=c.getConnection().getMetaData().getTables(null,null,statements.getFullMessageTableName(), - new String[] { "TABLE" }); - alreadyExists=rs.next(); - }catch(Throwable ignore){ - }finally{ + boolean alreadyExists = false; + ResultSet rs = null; + try { + rs = c.getConnection().getMetaData().getTables(null, null, + statements.getFullMessageTableName(), + new String[] {"TABLE"}); + alreadyExists = rs.next(); + } catch (Throwable ignore) { + } finally { close(rs); } - s=c.getConnection().createStatement(); - String[] createStatments=statements.getCreateSchemaStatements(); - for(int i=0;i D.LAST_ACKED_ID" +" ORDER BY M.ID"); - * s.setString(1,destinationName); s.setString(2,clientId); s.setString(3,subscriptionName); + * Useful for debugging. public void dumpTables(Connection c, String + * destinationName, String clientId, String subscriptionName) throws + * SQLException { printQuery(c, "Select * from ACTIVEMQ_MSGS", System.out); + * printQuery(c, "Select * from ACTIVEMQ_ACKS", System.out); + * PreparedStatement s = c.prepareStatement("SELECT M.ID, D.LAST_ACKED_ID + * FROM " +"ACTIVEMQ_MSGS M, " +"ACTIVEMQ_ACKS D " +"WHERE D.CONTAINER=? AND + * D.CLIENT_ID=? AND D.SUB_NAME=?" +" AND M.CONTAINER=D.CONTAINER AND M.ID > + * D.LAST_ACKED_ID" +" ORDER BY M.ID"); s.setString(1,destinationName); + * s.setString(2,clientId); s.setString(3,subscriptionName); * printQuery(s,System.out); } * - * public void dumpTables(Connection c) throws SQLException { printQuery(c, "Select * from ACTIVEMQ_MSGS", - * System.out); printQuery(c, "Select * from ACTIVEMQ_ACKS", System.out); } + * public void dumpTables(Connection c) throws SQLException { printQuery(c, + * "Select * from ACTIVEMQ_MSGS", System.out); printQuery(c, "Select * from + * ACTIVEMQ_ACKS", System.out); } * - * private void printQuery(Connection c, String query, PrintStream out) throws SQLException { - * printQuery(c.prepareStatement(query), out); } + * private void printQuery(Connection c, String query, PrintStream out) + * throws SQLException { printQuery(c.prepareStatement(query), out); } * - * private void printQuery(PreparedStatement s, PrintStream out) throws SQLException { + * private void printQuery(PreparedStatement s, PrintStream out) throws + * SQLException { * - * ResultSet set=null; try { set = s.executeQuery(); ResultSetMetaData metaData = set.getMetaData(); for( int i=1; i<= - * metaData.getColumnCount(); i++ ) { if(i==1) out.print("||"); out.print(metaData.getColumnName(i)+"||"); } - * out.println(); while(set.next()) { for( int i=1; i<= metaData.getColumnCount(); i++ ) { if(i==1) out.print("|"); - * out.print(set.getString(i)+"|"); } out.println(); } } finally { try { set.close(); } catch (Throwable ignore) {} - * try { s.close(); } catch (Throwable ignore) {} } } + * ResultSet set=null; try { set = s.executeQuery(); ResultSetMetaData + * metaData = set.getMetaData(); for( int i=1; i<= + * metaData.getColumnCount(); i++ ) { if(i==1) out.print("||"); + * out.print(metaData.getColumnName(i)+"||"); } out.println(); + * while(set.next()) { for( int i=1; i<= metaData.getColumnCount(); i++ ) { + * if(i==1) out.print("|"); out.print(set.getString(i)+"|"); } + * out.println(); } } finally { try { set.close(); } catch (Throwable + * ignore) {} try { s.close(); } catch (Throwable ignore) {} } } */ - } diff --git a/activemq-core/src/main/java/org/apache/activemq/store/jdbc/adapter/StreamJDBCAdapter.java b/activemq-core/src/main/java/org/apache/activemq/store/jdbc/adapter/StreamJDBCAdapter.java index 603131abeb..c34ee63740 100755 --- a/activemq-core/src/main/java/org/apache/activemq/store/jdbc/adapter/StreamJDBCAdapter.java +++ b/activemq-core/src/main/java/org/apache/activemq/store/jdbc/adapter/StreamJDBCAdapter.java @@ -26,12 +26,12 @@ import java.sql.SQLException; import org.apache.activemq.util.ByteArrayInputStream; /** - * This JDBCAdapter inserts and extracts BLOB data using the + * This JDBCAdapter inserts and extracts BLOB data using the * setBinaryStream()/getBinaryStream() operations. * * The databases/JDBC drivers that use this adapter are: *
    - *
  • Axion
  • + *
  • Axion
  • *
* * @org.apache.xbean.XBean element="streamJDBCAdapter" @@ -39,12 +39,13 @@ import org.apache.activemq.util.ByteArrayInputStream; * @version $Revision: 1.2 $ */ public class StreamJDBCAdapter extends DefaultJDBCAdapter { - + /** - * @see org.apache.activemq.store.jdbc.adapter.DefaultJDBCAdapter#getBinaryData(java.sql.ResultSet, int) + * @see org.apache.activemq.store.jdbc.adapter.DefaultJDBCAdapter#getBinaryData(java.sql.ResultSet, + * int) */ protected byte[] getBinaryData(ResultSet rs, int index) throws SQLException { - + try { InputStream is = rs.getBinaryStream(index); ByteArrayOutputStream os = new ByteArrayOutputStream(1024 * 4); @@ -58,15 +59,16 @@ public class StreamJDBCAdapter extends DefaultJDBCAdapter { return os.toByteArray(); } catch (IOException e) { - throw (SQLException)new SQLException("Error reading binary parameter: "+index).initCause(e); + throw (SQLException)new SQLException("Error reading binary parameter: " + index).initCause(e); } } - + /** - * @see org.apache.activemq.store.jdbc.adapter.DefaultJDBCAdapter#setBinaryData(java.sql.PreparedStatement, int, byte[]) + * @see org.apache.activemq.store.jdbc.adapter.DefaultJDBCAdapter#setBinaryData(java.sql.PreparedStatement, + * int, byte[]) */ protected void setBinaryData(PreparedStatement s, int index, byte[] data) throws SQLException { s.setBinaryStream(index, new ByteArrayInputStream(data), data.length); } - + } diff --git a/activemq-core/src/main/java/org/apache/activemq/store/journal/JournalMessageStore.java b/activemq-core/src/main/java/org/apache/activemq/store/journal/JournalMessageStore.java index fd20868fe8..6d013520cc 100755 --- a/activemq-core/src/main/java/org/apache/activemq/store/journal/JournalMessageStore.java +++ b/activemq-core/src/main/java/org/apache/activemq/store/journal/JournalMessageStore.java @@ -60,62 +60,63 @@ public class JournalMessageStore implements MessageStore { /** A MessageStore that we can use to retrieve messages quickly. */ private LinkedHashMap cpAddedMessageIds; - + protected RecordLocation lastLocation; protected HashSet inFlightTxLocations = new HashSet(); private UsageManager usageManager; - - public JournalMessageStore(JournalPersistenceAdapter adapter, MessageStore checkpointStore, ActiveMQDestination destination) { + + public JournalMessageStore(JournalPersistenceAdapter adapter, MessageStore checkpointStore, + ActiveMQDestination destination) { this.peristenceAdapter = adapter; this.transactionStore = adapter.getTransactionStore(); this.longTermStore = checkpointStore; this.destination = destination; this.transactionTemplate = new TransactionTemplate(adapter, new ConnectionContext()); } - + public void setUsageManager(UsageManager usageManager) { this.usageManager = usageManager; longTermStore.setUsageManager(usageManager); } - /** * Not synchronized since the Journal has better throughput if you increase * the number of concurrent writes that it is doing. */ public void addMessage(ConnectionContext context, final Message message) throws IOException { - + final MessageId id = message.getMessageId(); - + final boolean debug = log.isDebugEnabled(); message.incrementReferenceCount(); - + final RecordLocation location = peristenceAdapter.writeCommand(message, message.isResponseRequired()); - if( !context.isInTransaction() ) { - if( debug ) - log.debug("Journalled message add for: "+id+", at: "+location); + if (!context.isInTransaction()) { + if (debug) + log.debug("Journalled message add for: " + id + ", at: " + location); addMessage(message, location); } else { - if( debug ) - log.debug("Journalled transacted message add for: "+id+", at: "+location); - synchronized( this ) { + if (debug) + log.debug("Journalled transacted message add for: " + id + ", at: " + location); + synchronized (this) { inFlightTxLocations.add(location); } transactionStore.addMessage(this, message, location); - context.getTransaction().addSynchronization(new Synchronization(){ - public void afterCommit() throws Exception { - if( debug ) - log.debug("Transacted message add commit for: "+id+", at: "+location); - synchronized( JournalMessageStore.this ) { + context.getTransaction().addSynchronization(new Synchronization() { + public void afterCommit() throws Exception { + if (debug) + log.debug("Transacted message add commit for: " + id + ", at: " + location); + synchronized (JournalMessageStore.this) { inFlightTxLocations.remove(location); addMessage(message, location); } } - public void afterRollback() throws Exception { - if( debug ) - log.debug("Transacted message add rollback for: "+id+", at: "+location); - synchronized( JournalMessageStore.this ) { + + public void afterRollback() throws Exception { + if (debug) + log.debug("Transacted message add rollback for: " + id + ", at: " + location); + synchronized (JournalMessageStore.this) { inFlightTxLocations.remove(location); } message.decrementReferenceCount(); @@ -131,17 +132,17 @@ public class JournalMessageStore implements MessageStore { messages.put(id, message); } } - + public void replayAddMessage(ConnectionContext context, Message message) { try { // Only add the message if it has not already been added. Message t = longTermStore.getMessage(message.getMessageId()); - if( t==null ) { + if (t == null) { longTermStore.addMessage(context, message); } - } - catch (Throwable e) { - log.warn("Could not replay add for message '" + message.getMessageId() + "'. Message may have already been added. reason: " + e); + } catch (Throwable e) { + log.warn("Could not replay add for message '" + message.getMessageId() + + "'. Message may have already been added. reason: " + e); } } @@ -152,32 +153,36 @@ public class JournalMessageStore implements MessageStore { JournalQueueAck remove = new JournalQueueAck(); remove.setDestination(destination); remove.setMessageAck(ack); - + final RecordLocation location = peristenceAdapter.writeCommand(remove, ack.isResponseRequired()); - if( !context.isInTransaction() ) { - if( debug ) - log.debug("Journalled message remove for: "+ack.getLastMessageId()+", at: "+location); + if (!context.isInTransaction()) { + if (debug) + log.debug("Journalled message remove for: " + ack.getLastMessageId() + ", at: " + location); removeMessage(ack, location); } else { - if( debug ) - log.debug("Journalled transacted message remove for: "+ack.getLastMessageId()+", at: "+location); - synchronized( this ) { + if (debug) + log.debug("Journalled transacted message remove for: " + ack.getLastMessageId() + ", at: " + + location); + synchronized (this) { inFlightTxLocations.add(location); } transactionStore.removeMessage(this, ack, location); - context.getTransaction().addSynchronization(new Synchronization(){ - public void afterCommit() throws Exception { - if( debug ) - log.debug("Transacted message remove commit for: "+ack.getLastMessageId()+", at: "+location); - synchronized( JournalMessageStore.this ) { + context.getTransaction().addSynchronization(new Synchronization() { + public void afterCommit() throws Exception { + if (debug) + log.debug("Transacted message remove commit for: " + ack.getLastMessageId() + + ", at: " + location); + synchronized (JournalMessageStore.this) { inFlightTxLocations.remove(location); removeMessage(ack, location); } } - public void afterRollback() throws Exception { - if( debug ) - log.debug("Transacted message remove rollback for: "+ack.getLastMessageId()+", at: "+location); - synchronized( JournalMessageStore.this ) { + + public void afterRollback() throws Exception { + if (debug) + log.debug("Transacted message remove rollback for: " + ack.getLastMessageId() + + ", at: " + location); + synchronized (JournalMessageStore.this) { inFlightTxLocations.remove(location); } } @@ -185,12 +190,12 @@ public class JournalMessageStore implements MessageStore { } } - + final void removeMessage(final MessageAck ack, final RecordLocation location) { synchronized (this) { lastLocation = location; MessageId id = ack.getLastMessageId(); - Message message = (Message) messages.remove(id); + Message message = (Message)messages.remove(id); if (message == null) { messageAcks.add(ack); } else { @@ -198,17 +203,17 @@ public class JournalMessageStore implements MessageStore { } } } - + public void replayRemoveMessage(ConnectionContext context, MessageAck messageAck) { try { // Only remove the message if it has not already been removed. Message t = longTermStore.getMessage(messageAck.getLastMessageId()); - if( t!=null ) { + if (t != null) { longTermStore.removeMessage(context, messageAck); } - } - catch (Throwable e) { - log.warn("Could not replay acknowledge for message '" + messageAck.getLastMessageId() + "'. Message may have already been acknowledged. reason: " + e); + } catch (Throwable e) { + log.warn("Could not replay acknowledge for message '" + messageAck.getLastMessageId() + + "'. Message may have already been acknowledged. reason: " + e); } } @@ -219,14 +224,13 @@ public class JournalMessageStore implements MessageStore { public RecordLocation checkpoint() throws IOException { return checkpoint(null); } - + /** * @return * @throws IOException */ public RecordLocation checkpoint(final Callback postCheckpointTest) throws IOException { - RecordLocation rc; final ArrayList cpRemovedMessageLocations; final ArrayList cpActiveJournalLocations; @@ -237,37 +241,37 @@ public class JournalMessageStore implements MessageStore { cpAddedMessageIds = this.messages; cpRemovedMessageLocations = this.messageAcks; - cpActiveJournalLocations=new ArrayList(inFlightTxLocations); - + cpActiveJournalLocations = new ArrayList(inFlightTxLocations); + this.messages = new LinkedHashMap(); - this.messageAcks = new ArrayList(); + this.messageAcks = new ArrayList(); } transactionTemplate.run(new Callback() { public void execute() throws Exception { int size = 0; - + PersistenceAdapter persitanceAdapter = transactionTemplate.getPersistenceAdapter(); ConnectionContext context = transactionTemplate.getContext(); - + // Checkpoint the added messages. - synchronized(JournalMessageStore.this){ - Iterator iterator=cpAddedMessageIds.values().iterator(); - while(iterator.hasNext()){ - Message message=(Message)iterator.next(); - try{ - longTermStore.addMessage(context,message); - }catch(Throwable e){ - log.warn("Message could not be added to long term store: "+e.getMessage(),e); + synchronized (JournalMessageStore.this) { + Iterator iterator = cpAddedMessageIds.values().iterator(); + while (iterator.hasNext()) { + Message message = (Message)iterator.next(); + try { + longTermStore.addMessage(context, message); + } catch (Throwable e) { + log.warn("Message could not be added to long term store: " + e.getMessage(), e); } - size+=message.getSize(); + size += message.getSize(); message.decrementReferenceCount(); // Commit the batch if it's getting too big - if(size>=maxCheckpointMessageAddSize){ + if (size >= maxCheckpointMessageAddSize) { persitanceAdapter.commitTransaction(context); persitanceAdapter.beginTransaction(context); - size=0; + size = 0; } } } @@ -279,14 +283,14 @@ public class JournalMessageStore implements MessageStore { Iterator iterator = cpRemovedMessageLocations.iterator(); while (iterator.hasNext()) { try { - MessageAck ack = (MessageAck) iterator.next(); + MessageAck ack = (MessageAck)iterator.next(); longTermStore.removeMessage(transactionTemplate.getContext(), ack); } catch (Throwable e) { log.debug("Message could not be removed from long term store: " + e.getMessage(), e); } } - - if( postCheckpointTest!= null ) { + + if (postCheckpointTest != null) { postCheckpointTest.execute(); } } @@ -296,12 +300,12 @@ public class JournalMessageStore implements MessageStore { synchronized (this) { cpAddedMessageIds = null; } - - if( cpActiveJournalLocations.size() > 0 ) { + + if (cpActiveJournalLocations.size() > 0) { Collections.sort(cpActiveJournalLocations); - return (RecordLocation) cpActiveJournalLocations.get(0); + return (RecordLocation)cpActiveJournalLocations.get(0); } - synchronized (this){ + synchronized (this) { return lastLocation; } } @@ -314,15 +318,15 @@ public class JournalMessageStore implements MessageStore { synchronized (this) { // Do we have a still have it in the journal? - answer = (Message) messages.get(identity); - if( answer==null && cpAddedMessageIds!=null ) - answer = (Message) cpAddedMessageIds.get(identity); + answer = (Message)messages.get(identity); + if (answer == null && cpAddedMessageIds != null) + answer = (Message)cpAddedMessageIds.get(identity); } - - if (answer != null ) { + + if (answer != null) { return answer; } - + // If all else fails try the long term message store. return longTermStore.getMessage(identity); } @@ -333,7 +337,7 @@ public class JournalMessageStore implements MessageStore { * updated. * * @param listener - * @throws Exception + * @throws Exception */ public void recover(final MessageRecoveryListener listener) throws Exception { peristenceAdapter.checkpoint(true, true); @@ -341,14 +345,14 @@ public class JournalMessageStore implements MessageStore { } public void start() throws Exception { - if( this.usageManager != null ) + if (this.usageManager != null) this.usageManager.addUsageListener(peristenceAdapter); longTermStore.start(); } public void stop() throws Exception { longTermStore.stop(); - if( this.usageManager != null ) + if (this.usageManager != null) this.usageManager.removeUsageListener(peristenceAdapter); } @@ -366,12 +370,13 @@ public class JournalMessageStore implements MessageStore { peristenceAdapter.checkpoint(true, true); longTermStore.removeAllMessages(context); } - + public ActiveMQDestination getDestination() { return destination; } - public void addMessageReference(ConnectionContext context, MessageId messageId, long expirationTime, String messageRef) throws IOException { + public void addMessageReference(ConnectionContext context, MessageId messageId, long expirationTime, + String messageRef) throws IOException { throw new IOException("The journal does not support message references."); } @@ -381,25 +386,23 @@ public class JournalMessageStore implements MessageStore { /** * @return - * @throws IOException + * @throws IOException * @see org.apache.activemq.store.MessageStore#getMessageCount() */ - public int getMessageCount() throws IOException{ + public int getMessageCount() throws IOException { peristenceAdapter.checkpoint(true, true); return longTermStore.getMessageCount(); } - - public void recoverNextMessages(int maxReturned,MessageRecoveryListener listener) throws Exception{ + public void recoverNextMessages(int maxReturned, MessageRecoveryListener listener) throws Exception { peristenceAdapter.checkpoint(true, true); - longTermStore.recoverNextMessages(maxReturned,listener); - + longTermStore.recoverNextMessages(maxReturned, listener); + } - - public void resetBatching(){ + public void resetBatching() { longTermStore.resetBatching(); - + } -} \ No newline at end of file +} diff --git a/activemq-core/src/main/java/org/apache/activemq/store/journal/JournalPersistenceAdapter.java b/activemq-core/src/main/java/org/apache/activemq/store/journal/JournalPersistenceAdapter.java index fda8016a1e..a8cc8e08ea 100755 --- a/activemq-core/src/main/java/org/apache/activemq/store/journal/JournalPersistenceAdapter.java +++ b/activemq-core/src/main/java/org/apache/activemq/store/journal/JournalPersistenceAdapter.java @@ -75,7 +75,6 @@ import org.apache.commons.logging.LogFactory; * other long term persistent storage. * * @org.apache.xbean.XBean - * * @version $Revision: 1.17 $ */ public class JournalPersistenceAdapter implements PersistenceAdapter, JournalEventListener, UsageListener { @@ -89,45 +88,45 @@ public class JournalPersistenceAdapter implements PersistenceAdapter, JournalEve private final ConcurrentHashMap queues = new ConcurrentHashMap(); private final ConcurrentHashMap topics = new ConcurrentHashMap(); - + private UsageManager usageManager; long checkpointInterval = 1000 * 60 * 5; long lastCheckpointRequest = System.currentTimeMillis(); private long lastCleanup = System.currentTimeMillis(); private int maxCheckpointWorkers = 10; - private int maxCheckpointMessageAddSize = 1024*1024; + private int maxCheckpointMessageAddSize = 1024 * 1024; private JournalTransactionStore transactionStore = new JournalTransactionStore(this); private ThreadPoolExecutor checkpointExecutor; - + private TaskRunner checkpointTask; private CountDownLatch nextCheckpointCountDownLatch = new CountDownLatch(1); private boolean fullCheckPoint; - + private AtomicBoolean started = new AtomicBoolean(false); - private final Runnable periodicCheckpointTask = createPeriodicCheckpointTask(); - + private final Runnable periodicCheckpointTask = createPeriodicCheckpointTask(); + final Runnable createPeriodicCheckpointTask() { - return new Runnable() { - public void run() { + return new Runnable() { + public void run() { long lastTime = 0; - synchronized(this) { + synchronized (this) { lastTime = lastCheckpointRequest; } - if( System.currentTimeMillis()>lastTime+checkpointInterval ) { - checkpoint(false, true); - } - } - }; + if (System.currentTimeMillis() > lastTime + checkpointInterval) { + checkpoint(false, true); + } + } + }; } - + public JournalPersistenceAdapter(Journal journal, PersistenceAdapter longTermPersistence, TaskRunnerFactory taskRunnerFactory) throws IOException { this.journal = journal; journal.setJournalEventListener(this); - - checkpointTask = taskRunnerFactory.createTaskRunner(new Task(){ + + checkpointTask = taskRunnerFactory.createTaskRunner(new Task() { public boolean iterate() { return doCheckpoint(); } @@ -137,7 +136,8 @@ public class JournalPersistenceAdapter implements PersistenceAdapter, JournalEve } /** - * @param usageManager The UsageManager that is controlling the destination's memory usage. + * @param usageManager The UsageManager that is controlling the + * destination's memory usage. */ public void setUsageManager(UsageManager usageManager) { this.usageManager = usageManager; @@ -153,15 +153,14 @@ public class JournalPersistenceAdapter implements PersistenceAdapter, JournalEve private MessageStore createMessageStore(ActiveMQDestination destination) throws IOException { if (destination.isQueue()) { - return createQueueMessageStore((ActiveMQQueue) destination); - } - else { - return createTopicMessageStore((ActiveMQTopic) destination); + return createQueueMessageStore((ActiveMQQueue)destination); + } else { + return createTopicMessageStore((ActiveMQTopic)destination); } } public MessageStore createQueueMessageStore(ActiveMQQueue destination) throws IOException { - JournalMessageStore store = (JournalMessageStore) queues.get(destination); + JournalMessageStore store = (JournalMessageStore)queues.get(destination); if (store == null) { MessageStore checkpointStore = longTermPersistence.createQueueMessageStore(destination); store = new JournalMessageStore(this, checkpointStore, destination); @@ -171,7 +170,7 @@ public class JournalPersistenceAdapter implements PersistenceAdapter, JournalEve } public TopicMessageStore createTopicMessageStore(ActiveMQTopic destinationName) throws IOException { - JournalTopicMessageStore store = (JournalTopicMessageStore) topics.get(destinationName); + JournalTopicMessageStore store = (JournalTopicMessageStore)topics.get(destinationName); if (store == null) { TopicMessageStore checkpointStore = longTermPersistence.createTopicMessageStore(destinationName); store = new JournalTopicMessageStore(this, checkpointStore, destinationName); @@ -201,24 +200,25 @@ public class JournalPersistenceAdapter implements PersistenceAdapter, JournalEve } public synchronized void start() throws Exception { - if( !started.compareAndSet(false, true) ) + if (!started.compareAndSet(false, true)) { return; - + } + checkpointExecutor = new ThreadPoolExecutor(maxCheckpointWorkers, maxCheckpointWorkers, 30, TimeUnit.SECONDS, new LinkedBlockingQueue(), new ThreadFactory() { public Thread newThread(Runnable runable) { Thread t = new Thread(runable, "Journal checkpoint worker"); t.setPriority(7); return t; - } + } }); - //checkpointExecutor.allowCoreThreadTimeOut(true); - + // checkpointExecutor.allowCoreThreadTimeOut(true); + this.usageManager.addUsageListener(this); if (longTermPersistence instanceof JDBCPersistenceAdapter) { // Disabled periodic clean up as it deadlocks with the checkpoint // operations. - ((JDBCPersistenceAdapter) longTermPersistence).setCleanupPeriod(0); + ((JDBCPersistenceAdapter)longTermPersistence).setCleanupPeriod(0); } longTermPersistence.start(); @@ -226,23 +226,23 @@ public class JournalPersistenceAdapter implements PersistenceAdapter, JournalEve recover(); // Do a checkpoint periodically. - Scheduler.executePeriodically(periodicCheckpointTask, checkpointInterval/10); + Scheduler.executePeriodically(periodicCheckpointTask, checkpointInterval / 10); } public void stop() throws Exception { - + this.usageManager.removeUsageListener(this); - if( !started.compareAndSet(true, false) ) + if (!started.compareAndSet(true, false)) return; - + Scheduler.cancel(periodicCheckpointTask); // Take one final checkpoint and stop checkpoint processing. checkpoint(true, true); - checkpointTask.shutdown(); + checkpointTask.shutdown(); checkpointExecutor.shutdown(); - + queues.clear(); topics.clear(); @@ -253,7 +253,7 @@ public class JournalPersistenceAdapter implements PersistenceAdapter, JournalEve firstException = IOExceptionSupport.create("Failed to close journals: " + e, e); } longTermPersistence.stop(); - + if (firstException != null) { throw firstException; } @@ -287,83 +287,86 @@ public class JournalPersistenceAdapter implements PersistenceAdapter, JournalEve /** * When we checkpoint we move all the journalled data to long term storage. - * @param stopping * + * @param stopping * @param b */ public void checkpoint(boolean sync, boolean fullCheckpoint) { try { - if (journal == null ) + if (journal == null) throw new IllegalStateException("Journal is closed."); - + long now = System.currentTimeMillis(); CountDownLatch latch = null; - synchronized(this) { + synchronized (this) { latch = nextCheckpointCountDownLatch; lastCheckpointRequest = now; - if( fullCheckpoint ) { - this.fullCheckPoint = true; + if (fullCheckpoint) { + this.fullCheckPoint = true; } } - + checkpointTask.wakeup(); - + if (sync) { log.debug("Waking for checkpoint to complete."); latch.await(); } - } - catch (InterruptedException e) { + } catch (InterruptedException e) { Thread.currentThread().interrupt(); log.warn("Request to start checkpoint failed: " + e, e); } } - + public void checkpoint(boolean sync) { - checkpoint(sync,sync); + checkpoint(sync, sync); } - + /** * This does the actual checkpoint. - * @return + * + * @return */ public boolean doCheckpoint() { CountDownLatch latch = null; boolean fullCheckpoint; - synchronized(this) { + synchronized (this) { latch = nextCheckpointCountDownLatch; nextCheckpointCountDownLatch = new CountDownLatch(1); fullCheckpoint = this.fullCheckPoint; - this.fullCheckPoint=false; - } + this.fullCheckPoint = false; + } try { log.debug("Checkpoint started."); RecordLocation newMark = null; - ArrayList futureTasks = new ArrayList(queues.size()+topics.size()); - + ArrayList futureTasks = new ArrayList(queues.size() + topics.size()); + // - // We do many partial checkpoints (fullCheckpoint==false) to move topic messages - // to long term store as soon as possible. + // We do many partial checkpoints (fullCheckpoint==false) to move + // topic messages + // to long term store as soon as possible. // - // We want to avoid doing that for queue messages since removes the come in the same - // checkpoint cycle will nullify the previous message add. Therefore, we only + // We want to avoid doing that for queue messages since removes the + // come in the same + // checkpoint cycle will nullify the previous message add. + // Therefore, we only // checkpoint queues on the fullCheckpoint cycles. // - if( fullCheckpoint ) { + if (fullCheckpoint) { Iterator iterator = queues.values().iterator(); while (iterator.hasNext()) { try { - final JournalMessageStore ms = (JournalMessageStore) iterator.next(); + final JournalMessageStore ms = (JournalMessageStore)iterator.next(); FutureTask task = new FutureTask(new Callable() { public Object call() throws Exception { return ms.checkpoint(); - }}); + } + }); futureTasks.add(task); - checkpointExecutor.execute(task); - } - catch (Exception e) { + checkpointExecutor.execute(task); + } catch (Exception e) { log.error("Failed to checkpoint a message store: " + e, e); } } @@ -372,25 +375,25 @@ public class JournalPersistenceAdapter implements PersistenceAdapter, JournalEve Iterator iterator = topics.values().iterator(); while (iterator.hasNext()) { try { - final JournalTopicMessageStore ms = (JournalTopicMessageStore) iterator.next(); + final JournalTopicMessageStore ms = (JournalTopicMessageStore)iterator.next(); FutureTask task = new FutureTask(new Callable() { public Object call() throws Exception { return ms.checkpoint(); - }}); + } + }); futureTasks.add(task); - checkpointExecutor.execute(task); - } - catch (Exception e) { + checkpointExecutor.execute(task); + } catch (Exception e) { log.error("Failed to checkpoint a message store: " + e, e); } } try { for (Iterator iter = futureTasks.iterator(); iter.hasNext();) { - FutureTask ft = (FutureTask) iter.next(); - RecordLocation mark = (RecordLocation) ft.get(); + FutureTask ft = (FutureTask)iter.next(); + RecordLocation mark = (RecordLocation)ft.get(); // We only set a newMark on full checkpoints. - if( fullCheckpoint ) { + if (fullCheckpoint) { if (mark != null && (newMark == null || newMark.compareTo(mark) < 0)) { newMark = mark; } @@ -399,38 +402,36 @@ public class JournalPersistenceAdapter implements PersistenceAdapter, JournalEve } catch (Throwable e) { log.error("Failed to checkpoint a message store: " + e, e); } - - if( fullCheckpoint ) { + if (fullCheckpoint) { try { if (newMark != null) { log.debug("Marking journal at: " + newMark); journal.setMark(newMark, true); } - } - catch (Exception e) { + } catch (Exception e) { log.error("Failed to mark the Journal: " + e, e); } - + if (longTermPersistence instanceof JDBCPersistenceAdapter) { - // We may be check pointing more often than the checkpointInterval if under high use + // We may be check pointing more often than the + // checkpointInterval if under high use // But we don't want to clean up the db that often. long now = System.currentTimeMillis(); - if( now > lastCleanup+checkpointInterval ) { + if (now > lastCleanup + checkpointInterval) { lastCleanup = now; - ((JDBCPersistenceAdapter) longTermPersistence).cleanup(); + ((JDBCPersistenceAdapter)longTermPersistence).cleanup(); } } } log.debug("Checkpoint done."); - } - finally { + } finally { latch.countDown(); } - synchronized(this) { + synchronized (this) { return this.fullCheckPoint; - } + } } @@ -441,13 +442,11 @@ public class JournalPersistenceAdapter implements PersistenceAdapter, JournalEve */ public DataStructure readCommand(RecordLocation location) throws IOException { try { - Packet packet = journal.read(location); - return (DataStructure) wireFormat.unmarshal(toByteSequence(packet)); - } - catch (InvalidRecordLocationException e) { + Packet packet = journal.read(location); + return (DataStructure)wireFormat.unmarshal(toByteSequence(packet)); + } catch (InvalidRecordLocationException e) { throw createReadException(location, e); - } - catch (IOException e) { + } catch (IOException e) { throw createReadException(location, e); } } @@ -472,49 +471,43 @@ public class JournalPersistenceAdapter implements PersistenceAdapter, JournalEve // While we have records in the journal. while ((pos = journal.getNextRecordLocation(pos)) != null) { Packet data = journal.read(pos); - DataStructure c = (DataStructure) wireFormat.unmarshal(toByteSequence(data)); + DataStructure c = (DataStructure)wireFormat.unmarshal(toByteSequence(data)); - if (c instanceof Message ) { - Message message = (Message) c; - JournalMessageStore store = (JournalMessageStore) createMessageStore(message.getDestination()); - if ( message.isInTransaction()) { + if (c instanceof Message) { + Message message = (Message)c; + JournalMessageStore store = (JournalMessageStore)createMessageStore(message.getDestination()); + if (message.isInTransaction()) { transactionStore.addMessage(store, message, pos); - } - else { + } else { store.replayAddMessage(context, message); transactionCounter++; } } else { switch (c.getDataStructureType()) { - case JournalQueueAck.DATA_STRUCTURE_TYPE: - { - JournalQueueAck command = (JournalQueueAck) c; - JournalMessageStore store = (JournalMessageStore) createMessageStore(command.getDestination()); + case JournalQueueAck.DATA_STRUCTURE_TYPE: { + JournalQueueAck command = (JournalQueueAck)c; + JournalMessageStore store = (JournalMessageStore)createMessageStore(command.getDestination()); if (command.getMessageAck().isInTransaction()) { transactionStore.removeMessage(store, command.getMessageAck(), pos); - } - else { + } else { store.replayRemoveMessage(context, command.getMessageAck()); transactionCounter++; } } - break; - case JournalTopicAck.DATA_STRUCTURE_TYPE: - { - JournalTopicAck command = (JournalTopicAck) c; - JournalTopicMessageStore store = (JournalTopicMessageStore) createMessageStore(command.getDestination()); + break; + case JournalTopicAck.DATA_STRUCTURE_TYPE: { + JournalTopicAck command = (JournalTopicAck)c; + JournalTopicMessageStore store = (JournalTopicMessageStore)createMessageStore(command.getDestination()); if (command.getTransactionId() != null) { transactionStore.acknowledge(store, command, pos); - } - else { + } else { store.replayAcknowledge(context, command.getClientId(), command.getSubscritionName(), command.getMessageId()); transactionCounter++; } } - break; - case JournalTransaction.DATA_STRUCTURE_TYPE: - { - JournalTransaction command = (JournalTransaction) c; + break; + case JournalTransaction.DATA_STRUCTURE_TYPE: { + JournalTransaction command = (JournalTransaction)c; try { // Try to replay the packet. switch (command.getType()) { @@ -525,23 +518,23 @@ public class JournalPersistenceAdapter implements PersistenceAdapter, JournalEve case JournalTransaction.LOCAL_COMMIT: Tx tx = transactionStore.replayCommit(command.getTransactionId(), command.getWasPrepared()); if (tx == null) - break; // We may be trying to replay a commit that - // was already committed. + break; // We may be trying to replay a commit + // that + // was already committed. // Replay the committed operations. tx.getOperations(); for (Iterator iter = tx.getOperations().iterator(); iter.hasNext();) { - TxOperation op = (TxOperation) iter.next(); + TxOperation op = (TxOperation)iter.next(); if (op.operationType == TxOperation.ADD_OPERATION_TYPE) { - op.store.replayAddMessage(context, (Message) op.data); + op.store.replayAddMessage(context, (Message)op.data); } if (op.operationType == TxOperation.REMOVE_OPERATION_TYPE) { - op.store.replayRemoveMessage(context, (MessageAck) op.data); + op.store.replayRemoveMessage(context, (MessageAck)op.data); } if (op.operationType == TxOperation.ACK_OPERATION_TYPE) { - JournalTopicAck ack = (JournalTopicAck) op.data; - ((JournalTopicMessageStore) op.store).replayAcknowledge(context, ack.getClientId(), ack.getSubscritionName(), ack - .getMessageId()); + JournalTopicAck ack = (JournalTopicAck)op.data; + ((JournalTopicMessageStore)op.store).replayAcknowledge(context, ack.getClientId(), ack.getSubscritionName(), ack.getMessageId()); } } transactionCounter++; @@ -551,14 +544,13 @@ public class JournalPersistenceAdapter implements PersistenceAdapter, JournalEve transactionStore.replayRollback(command.getTransactionId()); break; } - } - catch (IOException e) { + } catch (IOException e) { log.error("Recovery Failure: Could not replay: " + c + ", reason: " + e, e); } } - break; + break; case JournalTrace.DATA_STRUCTURE_TYPE: - JournalTrace trace = (JournalTrace) c; + JournalTrace trace = (JournalTrace)c; log.debug("TRACE Entry: " + trace.getMessage()); break; default: @@ -590,14 +582,13 @@ public class JournalPersistenceAdapter implements PersistenceAdapter, JournalEve } /** - * * @param command * @param sync * @return * @throws IOException */ public RecordLocation writeCommand(DataStructure command, boolean sync) throws IOException { - if( started.get() ) + if (started.get()) return journal.write(toPacket(wireFormat.marshal(command)), sync); throw new IOException("closed"); } @@ -609,19 +600,19 @@ public class JournalPersistenceAdapter implements PersistenceAdapter, JournalEve } public void onMemoryUseChanged(UsageManager memoryManager, int oldPercentUsage, int newPercentUsage) { - newPercentUsage = ((newPercentUsage)/10)*10; - oldPercentUsage = ((oldPercentUsage)/10)*10; + newPercentUsage = ((newPercentUsage) / 10) * 10; + oldPercentUsage = ((oldPercentUsage) / 10) * 10; if (newPercentUsage >= 70 && oldPercentUsage < newPercentUsage) { boolean sync = newPercentUsage >= 90; checkpoint(sync, true); } } - + public JournalTransactionStore getTransactionStore() { return transactionStore; } - public void deleteAllMessages() throws IOException { + public void deleteAllMessages() throws IOException { try { JournalTrace trace = new JournalTrace(); trace.setMessage("DELETED"); @@ -661,28 +652,28 @@ public class JournalPersistenceAdapter implements PersistenceAdapter, JournalEve } public void setUseExternalMessageReferences(boolean enable) { - if( enable ) + if (enable) throw new IllegalArgumentException("The journal does not support message references."); } - + public Packet toPacket(ByteSequence sequence) { - return new ByteArrayPacket(new org.apache.activeio.packet.ByteSequence(sequence.data, sequence.offset, sequence.length)); + return new ByteArrayPacket(new org.apache.activeio.packet.ByteSequence(sequence.data, sequence.offset, sequence.length)); } - + public ByteSequence toByteSequence(Packet packet) { - org.apache.activeio.packet.ByteSequence sequence = packet.asByteSequence(); - return new ByteSequence(sequence.getData(), sequence.getOffset(), sequence.getLength()); + org.apache.activeio.packet.ByteSequence sequence = packet.asByteSequence(); + return new ByteSequence(sequence.getData(), sequence.getOffset(), sequence.getLength()); } - - public void setBrokerName(String brokerName){ + + public void setBrokerName(String brokerName) { longTermPersistence.setBrokerName(brokerName); } - - public String toString(){ + + public String toString() { return "JournalPersistenceAdapator(" + longTermPersistence + ")"; } - public void setDirectory(File dir){ + public void setDirectory(File dir) { } } diff --git a/activemq-core/src/main/java/org/apache/activemq/store/journal/JournalPersistenceAdapterFactory.java b/activemq-core/src/main/java/org/apache/activemq/store/journal/JournalPersistenceAdapterFactory.java index 7a9497558b..f01ae6eba9 100755 --- a/activemq-core/src/main/java/org/apache/activemq/store/journal/JournalPersistenceAdapterFactory.java +++ b/activemq-core/src/main/java/org/apache/activemq/store/journal/JournalPersistenceAdapterFactory.java @@ -34,34 +34,34 @@ import org.apache.commons.logging.LogFactory; /** * Factory class that can create PersistenceAdapter objects. - * + * * @version $Revision: 1.4 $ */ public class JournalPersistenceAdapterFactory extends DataSourceSupport implements PersistenceAdapterFactory { - - private static final int JOURNAL_LOCKED_WAIT_DELAY = 10*1000; + + private static final int JOURNAL_LOCKED_WAIT_DELAY = 10 * 1000; private static final Log log = LogFactory.getLog(JournalPersistenceAdapterFactory.class); - - private int journalLogFileSize = 1024*1024*20; + + private int journalLogFileSize = 1024 * 1024 * 20; private int journalLogFiles = 2; private TaskRunnerFactory taskRunnerFactory; private Journal journal; - private boolean useJournal=true; - private boolean useQuickJournal=false; + private boolean useJournal = true; + private boolean useQuickJournal = false; private File journalArchiveDirectory; - private boolean failIfJournalIsLocked=false; + private boolean failIfJournalIsLocked = false; private int journalThreadPriority = Thread.MAX_PRIORITY; private JDBCPersistenceAdapter jdbcPersistenceAdapter = new JDBCPersistenceAdapter(); - + public PersistenceAdapter createPersistenceAdapter() throws IOException { jdbcPersistenceAdapter.setDataSource(getDataSource()); - - if( !useJournal ) { + + if (!useJournal) { return jdbcPersistenceAdapter; } return new JournalPersistenceAdapter(getJournal(), jdbcPersistenceAdapter, getTaskRunnerFactory()); - + } public int getJournalLogFiles() { @@ -81,13 +81,13 @@ public class JournalPersistenceAdapterFactory extends DataSourceSupport implemen /** * Sets the size of the journal log files - * + * * @org.apache.xbean.Property propertyEditor="org.apache.activemq.util.MemoryIntPropertyEditor" */ public void setJournalLogFileSize(int journalLogFileSize) { this.journalLogFileSize = journalLogFileSize; } - + public JDBCPersistenceAdapter getJdbcAdapter() { return jdbcPersistenceAdapter; } @@ -101,8 +101,9 @@ public class JournalPersistenceAdapterFactory extends DataSourceSupport implemen } /** - * Enables or disables the use of the journal. The default is to use the journal - * + * Enables or disables the use of the journal. The default is to use the + * journal + * * @param useJournal */ public void setUseJournal(boolean useJournal) { @@ -110,8 +111,9 @@ public class JournalPersistenceAdapterFactory extends DataSourceSupport implemen } public TaskRunnerFactory getTaskRunnerFactory() { - if( taskRunnerFactory == null ) { - taskRunnerFactory = new TaskRunnerFactory("Persistence Adaptor Task", journalThreadPriority, true, 1000); + if (taskRunnerFactory == null) { + taskRunnerFactory = new TaskRunnerFactory("Persistence Adaptor Task", journalThreadPriority, + true, 1000); } return taskRunnerFactory; } @@ -121,7 +123,7 @@ public class JournalPersistenceAdapterFactory extends DataSourceSupport implemen } public Journal getJournal() throws IOException { - if( journal == null ) { + if (journal == null) { createJournal(); } return journal; @@ -132,7 +134,7 @@ public class JournalPersistenceAdapterFactory extends DataSourceSupport implemen } public File getJournalArchiveDirectory() { - if( journalArchiveDirectory == null && useQuickJournal ) { + if (journalArchiveDirectory == null && useQuickJournal) { journalArchiveDirectory = new File(getDataDirectoryFile(), "journal"); } return journalArchiveDirectory; @@ -142,15 +144,14 @@ public class JournalPersistenceAdapterFactory extends DataSourceSupport implemen this.journalArchiveDirectory = journalArchiveDirectory; } - public boolean isUseQuickJournal() { return useQuickJournal; } /** - * Enables or disables the use of quick journal, which keeps messages in the journal and just - * stores a reference to the messages in JDBC. Defaults to false so that messages actually reside - * long term in the JDBC database. + * Enables or disables the use of quick journal, which keeps messages in the + * journal and just stores a reference to the messages in JDBC. Defaults to + * false so that messages actually reside long term in the JDBC database. */ public void setUseQuickJournal(boolean useQuickJournal) { this.useQuickJournal = useQuickJournal; @@ -167,6 +168,7 @@ public class JournalPersistenceAdapterFactory extends DataSourceSupport implemen public Statements getStatements() { return jdbcPersistenceAdapter.getStatements(); } + public void setStatements(Statements statements) { jdbcPersistenceAdapter.setStatements(statements); } @@ -176,7 +178,8 @@ public class JournalPersistenceAdapterFactory extends DataSourceSupport implemen } /** - * Sets whether or not an exclusive database lock should be used to enable JDBC Master/Slave. Enabled by default. + * Sets whether or not an exclusive database lock should be used to enable + * JDBC Master/Slave. Enabled by default. */ public void setUseDatabaseLock(boolean useDatabaseLock) { jdbcPersistenceAdapter.setUseDatabaseLock(useDatabaseLock); @@ -192,16 +195,16 @@ public class JournalPersistenceAdapterFactory extends DataSourceSupport implemen public void setCreateTablesOnStartup(boolean createTablesOnStartup) { jdbcPersistenceAdapter.setCreateTablesOnStartup(createTablesOnStartup); } - - public int getJournalThreadPriority(){ + + public int getJournalThreadPriority() { return journalThreadPriority; } /** * Sets the thread priority of the journal thread */ - public void setJournalThreadPriority(int journalThreadPriority){ - this.journalThreadPriority=journalThreadPriority; + public void setJournalThreadPriority(int journalThreadPriority) { + this.journalThreadPriority = journalThreadPriority; } /** @@ -209,15 +212,18 @@ public class JournalPersistenceAdapterFactory extends DataSourceSupport implemen */ protected void createJournal() throws IOException { File journalDir = new File(getDataDirectoryFile(), "journal").getCanonicalFile(); - if( failIfJournalIsLocked ) { - journal = new JournalImpl(journalDir, journalLogFiles, journalLogFileSize, getJournalArchiveDirectory()); + if (failIfJournalIsLocked) { + journal = new JournalImpl(journalDir, journalLogFiles, journalLogFileSize, + getJournalArchiveDirectory()); } else { - while( true ) { + while (true) { try { - journal = new JournalImpl(journalDir, journalLogFiles, journalLogFileSize, getJournalArchiveDirectory()); + journal = new JournalImpl(journalDir, journalLogFiles, journalLogFileSize, + getJournalArchiveDirectory()); break; } catch (JournalLockedException e) { - log.info("Journal is locked... waiting "+(JOURNAL_LOCKED_WAIT_DELAY/1000)+" seconds for the journal to be unlocked."); + log.info("Journal is locked... waiting " + (JOURNAL_LOCKED_WAIT_DELAY / 1000) + + " seconds for the journal to be unlocked."); try { Thread.sleep(JOURNAL_LOCKED_WAIT_DELAY); } catch (InterruptedException e1) { @@ -227,6 +233,4 @@ public class JournalPersistenceAdapterFactory extends DataSourceSupport implemen } } - - } diff --git a/activemq-core/src/main/java/org/apache/activemq/store/journal/JournalTopicMessageStore.java b/activemq-core/src/main/java/org/apache/activemq/store/journal/JournalTopicMessageStore.java index 1416970f23..426dd3cb08 100755 --- a/activemq-core/src/main/java/org/apache/activemq/store/journal/JournalTopicMessageStore.java +++ b/activemq-core/src/main/java/org/apache/activemq/store/journal/JournalTopicMessageStore.java @@ -41,26 +41,29 @@ import org.apache.commons.logging.LogFactory; * @version $Revision: 1.13 $ */ public class JournalTopicMessageStore extends JournalMessageStore implements TopicMessageStore { - + private static final Log log = LogFactory.getLog(JournalTopicMessageStore.class); private TopicMessageStore longTermStore; - private HashMap ackedLastAckLocations = new HashMap(); - - public JournalTopicMessageStore(JournalPersistenceAdapter adapter, TopicMessageStore checkpointStore, ActiveMQTopic destinationName) { + private HashMap ackedLastAckLocations = new HashMap(); + + public JournalTopicMessageStore(JournalPersistenceAdapter adapter, TopicMessageStore checkpointStore, + ActiveMQTopic destinationName) { super(adapter, checkpointStore, destinationName); this.longTermStore = checkpointStore; } - - public void recoverSubscription(String clientId, String subscriptionName, MessageRecoveryListener listener) throws Exception { + + public void recoverSubscription(String clientId, String subscriptionName, MessageRecoveryListener listener) + throws Exception { this.peristenceAdapter.checkpoint(true, true); longTermStore.recoverSubscription(clientId, subscriptionName, listener); } - - public void recoverNextMessages(String clientId,String subscriptionName,int maxReturned,MessageRecoveryListener listener) throws Exception{ + + public void recoverNextMessages(String clientId, String subscriptionName, int maxReturned, + MessageRecoveryListener listener) throws Exception { this.peristenceAdapter.checkpoint(true, true); - longTermStore.recoverNextMessages(clientId, subscriptionName, maxReturned,listener); - + longTermStore.recoverNextMessages(clientId, subscriptionName, maxReturned, listener); + } public SubscriptionInfo lookupSubscription(String clientId, String subscriptionName) throws IOException { @@ -75,66 +78,69 @@ public class JournalTopicMessageStore extends JournalMessageStore implements Top public void addMessage(ConnectionContext context, Message message) throws IOException { super.addMessage(context, message); } - + /** */ - public void acknowledge(ConnectionContext context, String clientId, String subscriptionName, final MessageId messageId) throws IOException { + public void acknowledge(ConnectionContext context, String clientId, String subscriptionName, + final MessageId messageId) throws IOException { final boolean debug = log.isDebugEnabled(); - + JournalTopicAck ack = new JournalTopicAck(); ack.setDestination(destination); ack.setMessageId(messageId); ack.setMessageSequenceId(messageId.getBrokerSequenceId()); ack.setSubscritionName(subscriptionName); ack.setClientId(clientId); - ack.setTransactionId( context.getTransaction()!=null ? context.getTransaction().getTransactionId():null); + ack.setTransactionId(context.getTransaction() != null + ? context.getTransaction().getTransactionId() : null); final RecordLocation location = peristenceAdapter.writeCommand(ack, false); - - final SubscriptionKey key = new SubscriptionKey(clientId, subscriptionName); - if( !context.isInTransaction() ) { - if( debug ) - log.debug("Journalled acknowledge for: "+messageId+", at: "+location); + + final SubscriptionKey key = new SubscriptionKey(clientId, subscriptionName); + if (!context.isInTransaction()) { + if (debug) + log.debug("Journalled acknowledge for: " + messageId + ", at: " + location); acknowledge(messageId, location, key); } else { - if( debug ) - log.debug("Journalled transacted acknowledge for: "+messageId+", at: "+location); + if (debug) + log.debug("Journalled transacted acknowledge for: " + messageId + ", at: " + location); synchronized (this) { inFlightTxLocations.add(location); } transactionStore.acknowledge(this, ack, location); - context.getTransaction().addSynchronization(new Synchronization(){ - public void afterCommit() throws Exception { - if( debug ) - log.debug("Transacted acknowledge commit for: "+messageId+", at: "+location); + context.getTransaction().addSynchronization(new Synchronization() { + public void afterCommit() throws Exception { + if (debug) + log.debug("Transacted acknowledge commit for: " + messageId + ", at: " + location); synchronized (JournalTopicMessageStore.this) { inFlightTxLocations.remove(location); acknowledge(messageId, location, key); } } - public void afterRollback() throws Exception { - if( debug ) - log.debug("Transacted acknowledge rollback for: "+messageId+", at: "+location); + + public void afterRollback() throws Exception { + if (debug) + log.debug("Transacted acknowledge rollback for: " + messageId + ", at: " + location); synchronized (JournalTopicMessageStore.this) { inFlightTxLocations.remove(location); } } }); } - + } - - public void replayAcknowledge(ConnectionContext context, String clientId, String subscritionName, MessageId messageId) { + + public void replayAcknowledge(ConnectionContext context, String clientId, String subscritionName, + MessageId messageId) { try { SubscriptionInfo sub = longTermStore.lookupSubscription(clientId, subscritionName); - if( sub != null ) { + if (sub != null) { longTermStore.acknowledge(context, clientId, subscritionName, messageId); } - } - catch (Throwable e) { - log.debug("Could not replay acknowledge for message '" + messageId + "'. Message may have already been acknowledged. reason: " + e); + } catch (Throwable e) { + log.debug("Could not replay acknowledge for message '" + messageId + + "'. Message may have already been acknowledged. reason: " + e); } } - /** * @param messageId @@ -142,15 +148,15 @@ public class JournalTopicMessageStore extends JournalMessageStore implements Top * @param key */ protected void acknowledge(MessageId messageId, RecordLocation location, SubscriptionKey key) { - synchronized(this) { - lastLocation = location; - ackedLastAckLocations.put(key, messageId); - } + synchronized (this) { + lastLocation = location; + ackedLastAckLocations.put(key, messageId); + } } - + public RecordLocation checkpoint() throws IOException { - - final HashMap cpAckedLastAckLocations; + + final HashMap cpAckedLastAckLocations; // swap out the hash maps.. synchronized (this) { @@ -158,15 +164,16 @@ public class JournalTopicMessageStore extends JournalMessageStore implements Top this.ackedLastAckLocations = new HashMap(); } - return super.checkpoint( new Callback() { + return super.checkpoint(new Callback() { public void execute() throws Exception { // Checkpoint the acknowledged messages. Iterator iterator = cpAckedLastAckLocations.keySet().iterator(); while (iterator.hasNext()) { - SubscriptionKey subscriptionKey = (SubscriptionKey) iterator.next(); - MessageId identity = (MessageId) cpAckedLastAckLocations.get(subscriptionKey); - longTermStore.acknowledge(transactionTemplate.getContext(), subscriptionKey.clientId, subscriptionKey.subscriptionName, identity); + SubscriptionKey subscriptionKey = (SubscriptionKey)iterator.next(); + MessageId identity = (MessageId)cpAckedLastAckLocations.get(subscriptionKey); + longTermStore.acknowledge(transactionTemplate.getContext(), subscriptionKey.clientId, + subscriptionKey.subscriptionName, identity); } } @@ -175,30 +182,27 @@ public class JournalTopicMessageStore extends JournalMessageStore implements Top } /** - * @return Returns the longTermStore. - */ - public TopicMessageStore getLongTermTopicMessageStore() { - return longTermStore; - } + * @return Returns the longTermStore. + */ + public TopicMessageStore getLongTermTopicMessageStore() { + return longTermStore; + } public void deleteSubscription(String clientId, String subscriptionName) throws IOException { longTermStore.deleteSubscription(clientId, subscriptionName); } - + public SubscriptionInfo[] getAllSubscriptions() throws IOException { return longTermStore.getAllSubscriptions(); } - - public int getMessageCount(String clientId,String subscriberName) throws IOException{ + public int getMessageCount(String clientId, String subscriberName) throws IOException { this.peristenceAdapter.checkpoint(true, true); - return longTermStore.getMessageCount(clientId,subscriberName); - } - - public void resetBatching(String clientId,String subscriptionName) { - longTermStore.resetBatching(clientId,subscriptionName); + return longTermStore.getMessageCount(clientId, subscriberName); } - + public void resetBatching(String clientId, String subscriptionName) { + longTermStore.resetBatching(clientId, subscriptionName); + } -} \ No newline at end of file +} diff --git a/activemq-core/src/main/java/org/apache/activemq/store/journal/JournalTransactionStore.java b/activemq-core/src/main/java/org/apache/activemq/store/journal/JournalTransactionStore.java index 48a8a4bf9b..b457b33e40 100755 --- a/activemq-core/src/main/java/org/apache/activemq/store/journal/JournalTransactionStore.java +++ b/activemq-core/src/main/java/org/apache/activemq/store/journal/JournalTransactionStore.java @@ -36,7 +36,6 @@ import org.apache.activemq.command.XATransactionId; import org.apache.activemq.store.TransactionRecoveryListener; import org.apache.activemq.store.TransactionStore; - /** */ public class JournalTransactionStore implements TransactionStore { @@ -46,26 +45,27 @@ public class JournalTransactionStore implements TransactionStore { Map preparedTransactions = new LinkedHashMap(); private boolean doingRecover; - public static class TxOperation { - - static final byte ADD_OPERATION_TYPE = 0; - static final byte REMOVE_OPERATION_TYPE = 1; - static final byte ACK_OPERATION_TYPE = 3; - + + static final byte ADD_OPERATION_TYPE = 0; + static final byte REMOVE_OPERATION_TYPE = 1; + static final byte ACK_OPERATION_TYPE = 3; + public byte operationType; public JournalMessageStore store; public Object data; - + public TxOperation(byte operationType, JournalMessageStore store, Object data) { - this.operationType=operationType; - this.store=store; - this.data=data; + this.operationType = operationType; + this.store = store; + this.data = data; } - + } + /** * Operations + * * @version $Revision: 1.6 $ */ public static class Tx { @@ -74,7 +74,7 @@ public class JournalTransactionStore implements TransactionStore { private ArrayList operations = new ArrayList(); public Tx(RecordLocation location) { - this.location=location; + this.location = location; } public void add(JournalMessageStore store, Message msg) { @@ -88,12 +88,12 @@ public class JournalTransactionStore implements TransactionStore { public void add(JournalTopicMessageStore store, JournalTopicAck ack) { operations.add(new TxOperation(TxOperation.ACK_OPERATION_TYPE, store, ack)); } - + public Message[] getMessages() { ArrayList list = new ArrayList(); for (Iterator iter = operations.iterator(); iter.hasNext();) { - TxOperation op = (TxOperation) iter.next(); - if( op.operationType==TxOperation.ADD_OPERATION_TYPE ) { + TxOperation op = (TxOperation)iter.next(); + if (op.operationType == TxOperation.ADD_OPERATION_TYPE) { list.add(op.data); } } @@ -105,8 +105,8 @@ public class JournalTransactionStore implements TransactionStore { public MessageAck[] getAcks() { ArrayList list = new ArrayList(); for (Iterator iter = operations.iterator(); iter.hasNext();) { - TxOperation op = (TxOperation) iter.next(); - if( op.operationType==TxOperation.REMOVE_OPERATION_TYPE ) { + TxOperation op = (TxOperation)iter.next(); + if (op.operationType == TxOperation.REMOVE_OPERATION_TYPE) { list.add(op.data); } } @@ -129,43 +129,44 @@ public class JournalTransactionStore implements TransactionStore { * @throws IOException * @see org.apache.activemq.store.TransactionStore#prepare(TransactionId) */ - public void prepare(TransactionId txid) throws IOException{ - Tx tx=null; - synchronized(inflightTransactions){ - tx=(Tx)inflightTransactions.remove(txid); + public void prepare(TransactionId txid) throws IOException { + Tx tx = null; + synchronized (inflightTransactions) { + tx = (Tx)inflightTransactions.remove(txid); } - if(tx==null) + if (tx == null) return; - peristenceAdapter.writeCommand(new JournalTransaction(JournalTransaction.XA_PREPARE,txid,false),true); - synchronized(preparedTransactions){ - preparedTransactions.put(txid,tx); + peristenceAdapter.writeCommand(new JournalTransaction(JournalTransaction.XA_PREPARE, txid, false), + true); + synchronized (preparedTransactions) { + preparedTransactions.put(txid, tx); } } - + /** * @throws IOException * @see org.apache.activemq.store.TransactionStore#prepare(TransactionId) */ - public void replayPrepare(TransactionId txid) throws IOException{ - Tx tx=null; - synchronized(inflightTransactions){ - tx=(Tx)inflightTransactions.remove(txid); + public void replayPrepare(TransactionId txid) throws IOException { + Tx tx = null; + synchronized (inflightTransactions) { + tx = (Tx)inflightTransactions.remove(txid); } - if(tx==null) + if (tx == null) return; - synchronized(preparedTransactions){ - preparedTransactions.put(txid,tx); + synchronized (preparedTransactions) { + preparedTransactions.put(txid, tx); } } - public Tx getTx(Object txid,RecordLocation location){ - Tx tx=null; - synchronized(inflightTransactions){ - tx=(Tx)inflightTransactions.get(txid); + public Tx getTx(Object txid, RecordLocation location) { + Tx tx = null; + synchronized (inflightTransactions) { + tx = (Tx)inflightTransactions.get(txid); } - if(tx==null){ - tx=new Tx(location); - inflightTransactions.put(txid,tx); + if (tx == null) { + tx = new Tx(location); + inflightTransactions.put(txid, tx); } return tx; } @@ -174,24 +175,25 @@ public class JournalTransactionStore implements TransactionStore { * @throws XAException * @see org.apache.activemq.store.TransactionStore#commit(org.apache.activemq.service.Transaction) */ - public void commit(TransactionId txid,boolean wasPrepared) throws IOException{ + public void commit(TransactionId txid, boolean wasPrepared) throws IOException { Tx tx; - if(wasPrepared){ - synchronized(preparedTransactions){ - tx=(Tx)preparedTransactions.remove(txid); + if (wasPrepared) { + synchronized (preparedTransactions) { + tx = (Tx)preparedTransactions.remove(txid); } - }else{ - synchronized(inflightTransactions){ - tx=(Tx)inflightTransactions.remove(txid); + } else { + synchronized (inflightTransactions) { + tx = (Tx)inflightTransactions.remove(txid); } } - if(tx==null) + if (tx == null) return; - if(txid.isXATransaction()){ - peristenceAdapter.writeCommand(new JournalTransaction(JournalTransaction.XA_COMMIT,txid,wasPrepared),true); - }else{ - peristenceAdapter.writeCommand(new JournalTransaction(JournalTransaction.LOCAL_COMMIT,txid,wasPrepared), - true); + if (txid.isXATransaction()) { + peristenceAdapter.writeCommand(new JournalTransaction(JournalTransaction.XA_COMMIT, txid, + wasPrepared), true); + } else { + peristenceAdapter.writeCommand(new JournalTransaction(JournalTransaction.LOCAL_COMMIT, txid, + wasPrepared), true); } } @@ -199,13 +201,13 @@ public class JournalTransactionStore implements TransactionStore { * @throws XAException * @see org.apache.activemq.store.TransactionStore#commit(org.apache.activemq.service.Transaction) */ - public Tx replayCommit(TransactionId txid,boolean wasPrepared) throws IOException{ - if(wasPrepared){ - synchronized(preparedTransactions){ + public Tx replayCommit(TransactionId txid, boolean wasPrepared) throws IOException { + if (wasPrepared) { + synchronized (preparedTransactions) { return (Tx)preparedTransactions.remove(txid); } - }else{ - synchronized(inflightTransactions){ + } else { + synchronized (inflightTransactions) { return (Tx)inflightTransactions.remove(txid); } } @@ -215,21 +217,22 @@ public class JournalTransactionStore implements TransactionStore { * @throws IOException * @see org.apache.activemq.store.TransactionStore#rollback(TransactionId) */ - public void rollback(TransactionId txid) throws IOException{ - Tx tx=null; - synchronized(inflightTransactions){ - tx=(Tx)inflightTransactions.remove(txid); + public void rollback(TransactionId txid) throws IOException { + Tx tx = null; + synchronized (inflightTransactions) { + tx = (Tx)inflightTransactions.remove(txid); } - if(tx!=null) - synchronized(preparedTransactions){ - tx=(Tx)preparedTransactions.remove(txid); + if (tx != null) + synchronized (preparedTransactions) { + tx = (Tx)preparedTransactions.remove(txid); } - if(tx!=null){ - if(txid.isXATransaction()){ - peristenceAdapter.writeCommand(new JournalTransaction(JournalTransaction.XA_ROLLBACK,txid,false),true); - }else{ - peristenceAdapter.writeCommand(new JournalTransaction(JournalTransaction.LOCAL_ROLLBACK,txid,false), - true); + if (tx != null) { + if (txid.isXATransaction()) { + peristenceAdapter.writeCommand(new JournalTransaction(JournalTransaction.XA_ROLLBACK, txid, + false), true); + } else { + peristenceAdapter.writeCommand(new JournalTransaction(JournalTransaction.LOCAL_ROLLBACK, + txid, false), true); } } } @@ -238,42 +241,42 @@ public class JournalTransactionStore implements TransactionStore { * @throws IOException * @see org.apache.activemq.store.TransactionStore#rollback(TransactionId) */ - public void replayRollback(TransactionId txid) throws IOException{ - boolean inflight=false; - synchronized(inflightTransactions){ - inflight=inflightTransactions.remove(txid)!=null; + public void replayRollback(TransactionId txid) throws IOException { + boolean inflight = false; + synchronized (inflightTransactions) { + inflight = inflightTransactions.remove(txid) != null; } - if(inflight){ - synchronized(preparedTransactions){ + if (inflight) { + synchronized (preparedTransactions) { preparedTransactions.remove(txid); } } } - + public void start() throws Exception { } public void stop() throws Exception { } - - synchronized public void recover(TransactionRecoveryListener listener) throws IOException{ + + synchronized public void recover(TransactionRecoveryListener listener) throws IOException { // All the in-flight transactions get rolled back.. - synchronized(inflightTransactions){ + synchronized (inflightTransactions) { inflightTransactions.clear(); } - this.doingRecover=true; - try{ - Map txs=null; - synchronized(preparedTransactions){ - txs=new LinkedHashMap(preparedTransactions); + this.doingRecover = true; + try { + Map txs = null; + synchronized (preparedTransactions) { + txs = new LinkedHashMap(preparedTransactions); } - for(Iterator iter=txs.keySet().iterator();iter.hasNext();){ - Object txid=(Object)iter.next(); - Tx tx=(Tx)txs.get(txid); - listener.recover((XATransactionId)txid,tx.getMessages(),tx.getAcks()); + for (Iterator iter = txs.keySet().iterator(); iter.hasNext();) { + Object txid = (Object)iter.next(); + Tx tx = (Tx)txs.get(txid); + listener.recover((XATransactionId)txid, tx.getMessages(), tx.getAcks()); } - }finally{ - this.doingRecover=false; + } finally { + this.doingRecover = false; } } @@ -290,40 +293,40 @@ public class JournalTransactionStore implements TransactionStore { * @param ack * @throws IOException */ - public void removeMessage(JournalMessageStore store, MessageAck ack, RecordLocation location) throws IOException { + public void removeMessage(JournalMessageStore store, MessageAck ack, RecordLocation location) + throws IOException { Tx tx = getTx(ack.getTransactionId(), location); tx.add(store, ack); } - - + public void acknowledge(JournalTopicMessageStore store, JournalTopicAck ack, RecordLocation location) { Tx tx = getTx(ack.getTransactionId(), location); tx.add(store, ack); } - - public RecordLocation checkpoint() throws IOException{ + public RecordLocation checkpoint() throws IOException { // Nothing really to checkpoint.. since, we don't - // checkpoint tx operations in to long term store until they are committed. + // checkpoint tx operations in to long term store until they are + // committed. // But we keep track of the first location of an operation // that was associated with an active tx. The journal can not // roll over active tx records. - RecordLocation rc=null; - synchronized(inflightTransactions){ - for(Iterator iter=inflightTransactions.values().iterator();iter.hasNext();){ - Tx tx=(Tx)iter.next(); - RecordLocation location=tx.location; - if(rc==null||rc.compareTo(location)<0){ - rc=location; + RecordLocation rc = null; + synchronized (inflightTransactions) { + for (Iterator iter = inflightTransactions.values().iterator(); iter.hasNext();) { + Tx tx = (Tx)iter.next(); + RecordLocation location = tx.location; + if (rc == null || rc.compareTo(location) < 0) { + rc = location; } } } - synchronized(preparedTransactions){ - for(Iterator iter=preparedTransactions.values().iterator();iter.hasNext();){ - Tx tx=(Tx)iter.next(); - RecordLocation location=tx.location; - if(rc==null||rc.compareTo(location)<0){ - rc=location; + synchronized (preparedTransactions) { + for (Iterator iter = preparedTransactions.values().iterator(); iter.hasNext();) { + Tx tx = (Tx)iter.next(); + RecordLocation location = tx.location; + if (rc == null || rc.compareTo(location) < 0) { + rc = location; } } return rc; @@ -334,5 +337,4 @@ public class JournalTransactionStore implements TransactionStore { return doingRecover; } - } diff --git a/activemq-core/src/main/java/org/apache/activemq/store/kahadaptor/AMQTxMarshaller.java b/activemq-core/src/main/java/org/apache/activemq/store/kahadaptor/AMQTxMarshaller.java index 79cb451944..eb3d4b3d02 100644 --- a/activemq-core/src/main/java/org/apache/activemq/store/kahadaptor/AMQTxMarshaller.java +++ b/activemq-core/src/main/java/org/apache/activemq/store/kahadaptor/AMQTxMarshaller.java @@ -28,35 +28,36 @@ import org.apache.activemq.wireformat.WireFormat; /** * Marshall an AMQTx + * * @version $Revision: 1.10 $ */ -public class AMQTxMarshaller implements Marshaller{ +public class AMQTxMarshaller implements Marshaller { private WireFormat wireFormat; - public AMQTxMarshaller(WireFormat wireFormat){ - this.wireFormat=wireFormat; + public AMQTxMarshaller(WireFormat wireFormat) { + this.wireFormat = wireFormat; } - public AMQTx readPayload(DataInput dataIn) throws IOException{ - Location location=new Location(); + public AMQTx readPayload(DataInput dataIn) throws IOException { + Location location = new Location(); location.readExternal(dataIn); - AMQTx result=new AMQTx(location); - int size=dataIn.readInt(); - for(int i=0;i list=amqtx.getOperations(); + List list = amqtx.getOperations(); dataOut.writeInt(list.size()); - for(AMQTxOperation op:list){ - op.writeExternal(wireFormat,dataOut); + for (AMQTxOperation op : list) { + op.writeExternal(wireFormat, dataOut); } } } diff --git a/activemq-core/src/main/java/org/apache/activemq/store/kahadaptor/AtomicIntegerMarshaller.java b/activemq-core/src/main/java/org/apache/activemq/store/kahadaptor/AtomicIntegerMarshaller.java index 1e42b57e70..cfda24fa55 100644 --- a/activemq-core/src/main/java/org/apache/activemq/store/kahadaptor/AtomicIntegerMarshaller.java +++ b/activemq-core/src/main/java/org/apache/activemq/store/kahadaptor/AtomicIntegerMarshaller.java @@ -22,20 +22,19 @@ import java.io.IOException; import org.apache.activemq.kaha.Marshaller; import java.util.concurrent.atomic.AtomicInteger; - /** * Marshall an AtomicInteger + * * @version $Revision: 1.10 $ */ -public class AtomicIntegerMarshaller implements Marshaller{ - +public class AtomicIntegerMarshaller implements Marshaller { + + public void writePayload(AtomicInteger ai, DataOutput dataOut) throws IOException { + dataOut.writeInt(ai.get()); - public void writePayload(AtomicInteger ai,DataOutput dataOut) throws IOException{ - dataOut.writeInt(ai.get()); - } - public AtomicInteger readPayload(DataInput dataIn) throws IOException{ + public AtomicInteger readPayload(DataInput dataIn) throws IOException { int value = dataIn.readInt(); return new AtomicInteger(value); } diff --git a/activemq-core/src/main/java/org/apache/activemq/store/kahadaptor/ConsumerMessageRef.java b/activemq-core/src/main/java/org/apache/activemq/store/kahadaptor/ConsumerMessageRef.java index 65e9735078..e2ba5b881a 100644 --- a/activemq-core/src/main/java/org/apache/activemq/store/kahadaptor/ConsumerMessageRef.java +++ b/activemq-core/src/main/java/org/apache/activemq/store/kahadaptor/ConsumerMessageRef.java @@ -22,59 +22,56 @@ import org.apache.activemq.kaha.StoreEntry; * * @version $Revision: 1.10 $ */ -public class ConsumerMessageRef{ +public class ConsumerMessageRef { private MessageId messageId; private StoreEntry messageEntry; private StoreEntry ackEntry; - + /** * @return the ackEntry */ - public StoreEntry getAckEntry(){ + public StoreEntry getAckEntry() { return this.ackEntry; } - + /** * @param ackEntry the ackEntry to set */ - public void setAckEntry(StoreEntry ackEntry){ - this.ackEntry=ackEntry; + public void setAckEntry(StoreEntry ackEntry) { + this.ackEntry = ackEntry; } - + /** * @return the messageEntry */ - public StoreEntry getMessageEntry(){ + public StoreEntry getMessageEntry() { return this.messageEntry; } - + /** * @param messageEntry the messageEntry to set */ - public void setMessageEntry(StoreEntry messageEntry){ - this.messageEntry=messageEntry; + public void setMessageEntry(StoreEntry messageEntry) { + this.messageEntry = messageEntry; } - /** * @return the messageId */ - public MessageId getMessageId(){ + public MessageId getMessageId() { return this.messageId; } - /** * @param messageId the messageId to set */ - public void setMessageId(MessageId messageId){ - this.messageId=messageId; - } - - public String toString() { - return "ConsumerMessageRef[" + messageId +"]"; + public void setMessageId(MessageId messageId) { + this.messageId = messageId; + } + + public String toString() { + return "ConsumerMessageRef[" + messageId + "]"; } - } diff --git a/activemq-core/src/main/java/org/apache/activemq/store/kahadaptor/ConsumerMessageRefMarshaller.java b/activemq-core/src/main/java/org/apache/activemq/store/kahadaptor/ConsumerMessageRefMarshaller.java index 3351982798..95de1af7a3 100644 --- a/activemq-core/src/main/java/org/apache/activemq/store/kahadaptor/ConsumerMessageRefMarshaller.java +++ b/activemq-core/src/main/java/org/apache/activemq/store/kahadaptor/ConsumerMessageRefMarshaller.java @@ -23,31 +23,30 @@ import org.apache.activemq.command.MessageId; import org.apache.activemq.kaha.Marshaller; import org.apache.activemq.kaha.impl.index.IndexItem; - /** * Marshall a TopicSubAck + * * @version $Revision: 1.10 $ */ -public class ConsumerMessageRefMarshaller implements Marshaller{ - +public class ConsumerMessageRefMarshaller implements Marshaller { /** * @param object * @param dataOut * @throws IOException - * @see org.apache.activemq.kaha.Marshaller#writePayload(java.lang.Object, java.io.DataOutput) + * @see org.apache.activemq.kaha.Marshaller#writePayload(java.lang.Object, + * java.io.DataOutput) */ - public void writePayload(Object object,DataOutput dataOut) throws IOException{ - ConsumerMessageRef ref = (ConsumerMessageRef) object; - dataOut.writeUTF(ref.getMessageId().toString()); - IndexItem item = (IndexItem)ref.getMessageEntry(); - dataOut.writeLong(item.getOffset()); - item.write(dataOut); - item = (IndexItem)ref.getAckEntry(); - dataOut.writeLong(item.getOffset()); - item.write(dataOut); - - + public void writePayload(Object object, DataOutput dataOut) throws IOException { + ConsumerMessageRef ref = (ConsumerMessageRef)object; + dataOut.writeUTF(ref.getMessageId().toString()); + IndexItem item = (IndexItem)ref.getMessageEntry(); + dataOut.writeLong(item.getOffset()); + item.write(dataOut); + item = (IndexItem)ref.getAckEntry(); + dataOut.writeLong(item.getOffset()); + item.write(dataOut); + } /** @@ -56,7 +55,7 @@ public class ConsumerMessageRefMarshaller implements Marshaller{ * @throws IOException * @see org.apache.activemq.kaha.Marshaller#readPayload(java.io.DataInput) */ - public Object readPayload(DataInput dataIn) throws IOException{ + public Object readPayload(DataInput dataIn) throws IOException { ConsumerMessageRef ref = new ConsumerMessageRef(); ref.setMessageId(new MessageId(dataIn.readUTF())); IndexItem item = new IndexItem(); diff --git a/activemq-core/src/main/java/org/apache/activemq/store/kahadaptor/IntegerMarshaller.java b/activemq-core/src/main/java/org/apache/activemq/store/kahadaptor/IntegerMarshaller.java index f275894123..6f35aba76e 100644 --- a/activemq-core/src/main/java/org/apache/activemq/store/kahadaptor/IntegerMarshaller.java +++ b/activemq-core/src/main/java/org/apache/activemq/store/kahadaptor/IntegerMarshaller.java @@ -22,18 +22,18 @@ import java.io.IOException; import org.apache.activemq.kaha.Marshaller; - /** * Marshall an Integer + * * @version $Revision: 1.10 $ */ public class IntegerMarshaller implements Marshaller { - - public void writePayload(Integer object,DataOutput dataOut) throws IOException{ - dataOut.writeInt(object.intValue()); + + public void writePayload(Integer object, DataOutput dataOut) throws IOException { + dataOut.writeInt(object.intValue()); } - public Integer readPayload(DataInput dataIn) throws IOException{ + public Integer readPayload(DataInput dataIn) throws IOException { return dataIn.readInt(); } } diff --git a/activemq-core/src/main/java/org/apache/activemq/store/kahadaptor/KahaMessageStore.java b/activemq-core/src/main/java/org/apache/activemq/store/kahadaptor/KahaMessageStore.java index d3cac05194..dca86cade9 100755 --- a/activemq-core/src/main/java/org/apache/activemq/store/kahadaptor/KahaMessageStore.java +++ b/activemq-core/src/main/java/org/apache/activemq/store/kahadaptor/KahaMessageStore.java @@ -27,107 +27,110 @@ import org.apache.activemq.store.MessageRecoveryListener; import org.apache.activemq.store.MessageStore; /** - * An implementation of {@link org.apache.activemq.store.MessageStore} which uses a JPS Container + * An implementation of {@link org.apache.activemq.store.MessageStore} which + * uses a JPS Container * * @version $Revision: 1.7 $ */ -public class KahaMessageStore implements MessageStore{ +public class KahaMessageStore implements MessageStore { protected final ActiveMQDestination destination; - protected final MapContainer messageContainer; - protected StoreEntry batchEntry=null; + protected final MapContainer messageContainer; + protected StoreEntry batchEntry = null; - public KahaMessageStore(MapContainer container,ActiveMQDestination destination) - throws IOException{ - this.messageContainer=container; - this.destination=destination; + public KahaMessageStore(MapContainer container, ActiveMQDestination destination) + throws IOException { + this.messageContainer = container; + this.destination = destination; } - protected MessageId getMessageId(Object object){ + protected MessageId getMessageId(Object object) { return ((Message)object).getMessageId(); } - public Object getId(){ + public Object getId() { return messageContainer.getId(); } - public synchronized void addMessage(ConnectionContext context,Message message) throws IOException{ - messageContainer.put(message.getMessageId(),message); - // TODO: we should do the following but it is not need if the message is being added within a persistence + public synchronized void addMessage(ConnectionContext context, Message message) throws IOException { + messageContainer.put(message.getMessageId(), message); + // TODO: we should do the following but it is not need if the message is + // being added within a persistence // transaction - // but since I can't tell if one is running right now.. I'll leave this out for now. + // but since I can't tell if one is running right now.. I'll leave this + // out for now. // if( message.isResponseRequired() ) { // messageContainer.force(); // } } - public synchronized Message getMessage(MessageId identity) throws IOException{ - Message result=messageContainer.get(identity); + public synchronized Message getMessage(MessageId identity) throws IOException { + Message result = messageContainer.get(identity); return result; } - protected boolean recoverMessage(MessageRecoveryListener listener,Message msg) throws Exception{ - if(listener.hasSpace()){ + protected boolean recoverMessage(MessageRecoveryListener listener, Message msg) throws Exception { + if (listener.hasSpace()) { listener.recoverMessage(msg); return true; } return false; } - public void removeMessage(ConnectionContext context,MessageAck ack) throws IOException{ + public void removeMessage(ConnectionContext context, MessageAck ack) throws IOException { removeMessage(ack.getLastMessageId()); } - - - public synchronized void removeMessage(MessageId msgId) throws IOException{ - StoreEntry entry=messageContainer.getEntry(msgId); - if(entry!=null){ + public synchronized void removeMessage(MessageId msgId) throws IOException { + StoreEntry entry = messageContainer.getEntry(msgId); + if (entry != null) { messageContainer.remove(entry); - if(messageContainer.isEmpty()||(batchEntry!=null&&batchEntry.equals(entry))){ + if (messageContainer.isEmpty() || (batchEntry != null && batchEntry.equals(entry))) { resetBatching(); } } } - public synchronized void recover(MessageRecoveryListener listener) throws Exception{ - for(StoreEntry entry=messageContainer.getFirst();entry!=null;entry=messageContainer.getNext(entry)){ - Message msg=(Message)messageContainer.getValue(entry); - if(!recoverMessage(listener,msg)) { + public synchronized void recover(MessageRecoveryListener listener) throws Exception { + for (StoreEntry entry = messageContainer.getFirst(); entry != null; entry = messageContainer + .getNext(entry)) { + Message msg = (Message)messageContainer.getValue(entry); + if (!recoverMessage(listener, msg)) { break; } } } - public void start(){ + public void start() { } - public void stop(){ + public void stop() { } - public synchronized void removeAllMessages(ConnectionContext context) throws IOException{ + public synchronized void removeAllMessages(ConnectionContext context) throws IOException { messageContainer.clear(); } - public ActiveMQDestination getDestination(){ + public ActiveMQDestination getDestination() { return destination; } - public synchronized void delete(){ + public synchronized void delete() { messageContainer.clear(); } /** - * @param usageManager The UsageManager that is controlling the destination's memory usage. + * @param usageManager The UsageManager that is controlling the + * destination's memory usage. */ - public void setUsageManager(UsageManager usageManager){ + public void setUsageManager(UsageManager usageManager) { } /** * @return the number of messages held by this destination * @see org.apache.activemq.store.MessageStore#getMessageCount() */ - public int getMessageCount(){ + public int getMessageCount() { return messageContainer.size(); } @@ -137,7 +140,7 @@ public class KahaMessageStore implements MessageStore{ * @throws Exception * @see org.apache.activemq.store.MessageStore#getPreviousMessageIdToDeliver(org.apache.activemq.command.MessageId) */ - public MessageId getPreviousMessageIdToDeliver(MessageId id) throws Exception{ + public MessageId getPreviousMessageIdToDeliver(MessageId id) throws Exception { return null; } @@ -146,31 +149,32 @@ public class KahaMessageStore implements MessageStore{ * @param maxReturned * @param listener * @throws Exception - * @see org.apache.activemq.store.MessageStore#recoverNextMessages(org.apache.activemq.command.MessageId, int, - * org.apache.activemq.store.MessageRecoveryListener) + * @see org.apache.activemq.store.MessageStore#recoverNextMessages(org.apache.activemq.command.MessageId, + * int, org.apache.activemq.store.MessageRecoveryListener) */ - public synchronized void recoverNextMessages(int maxReturned,MessageRecoveryListener listener) throws Exception{ - StoreEntry entry=batchEntry; - if(entry==null){ - entry=messageContainer.getFirst(); - }else{ - entry=messageContainer.refresh(entry); - entry=messageContainer.getNext(entry); - if(entry==null){ - batchEntry=null; + public synchronized void recoverNextMessages(int maxReturned, MessageRecoveryListener listener) + throws Exception { + StoreEntry entry = batchEntry; + if (entry == null) { + entry = messageContainer.getFirst(); + } else { + entry = messageContainer.refresh(entry); + entry = messageContainer.getNext(entry); + if (entry == null) { + batchEntry = null; } } - if(entry!=null){ - int count=0; - do{ - Message msg=messageContainer.getValue(entry); - if(msg!=null){ - recoverMessage(listener,msg); + if (entry != null) { + int count = 0; + do { + Message msg = messageContainer.getValue(entry); + if (msg != null) { + recoverMessage(listener, msg); count++; } - batchEntry=entry; - entry=messageContainer.getNext(entry); - }while(entry!=null&&count topics=new ConcurrentHashMap(); - ConcurrentHashMap queues=new ConcurrentHashMap(); - ConcurrentHashMap messageStores=new ConcurrentHashMap(); - protected OpenWireFormat wireFormat=new OpenWireFormat(); - private long maxDataFileLength=32*1024*1024; + ConcurrentHashMap topics = new ConcurrentHashMap(); + ConcurrentHashMap queues = new ConcurrentHashMap(); + ConcurrentHashMap messageStores = new ConcurrentHashMap(); + protected OpenWireFormat wireFormat = new OpenWireFormat(); + private long maxDataFileLength = 32 * 1024 * 1024; private File directory; private String brokerName; private Store theStore; private boolean initialized; - public Set getDestinations(){ - Set rc=new HashSet(); - try{ - Store store=getStore(); - for(Iterator i=store.getMapContainerIds().iterator();i.hasNext();){ - ContainerId id=(ContainerId) i.next(); + public Set getDestinations() { + Set rc = new HashSet(); + try { + Store store = getStore(); + for (Iterator i = store.getMapContainerIds().iterator(); i.hasNext();) { + ContainerId id = (ContainerId)i.next(); Object obj = id.getKey(); - if(obj instanceof ActiveMQDestination){ + if (obj instanceof ActiveMQDestination) { rc.add((ActiveMQDestination)obj); } } - }catch(IOException e){ - log.error("Failed to get destinations ",e); + } catch (IOException e) { + log.error("Failed to get destinations ", e); } return rc; } - public synchronized MessageStore createQueueMessageStore(ActiveMQQueue destination) throws IOException{ - MessageStore rc=queues.get(destination); - if(rc==null){ - rc=new KahaMessageStore(getMapContainer(destination,"queue-data"),destination); - messageStores.put(destination,rc); - if(transactionStore!=null){ - rc=transactionStore.proxy(rc); + public synchronized MessageStore createQueueMessageStore(ActiveMQQueue destination) throws IOException { + MessageStore rc = queues.get(destination); + if (rc == null) { + rc = new KahaMessageStore(getMapContainer(destination, "queue-data"), destination); + messageStores.put(destination, rc); + if (transactionStore != null) { + rc = transactionStore.proxy(rc); } - queues.put(destination,rc); + queues.put(destination, rc); } return rc; } - public synchronized TopicMessageStore createTopicMessageStore(ActiveMQTopic destination) throws IOException{ - TopicMessageStore rc=topics.get(destination); - if(rc==null){ - Store store=getStore(); - MapContainer messageContainer=getMapContainer(destination,"topic-data"); - MapContainer subsContainer=getSubsMapContainer(destination.toString()+"-Subscriptions","topic-subs"); - ListContainer ackContainer=store.getListContainer(destination.toString(),"topic-acks"); + public synchronized TopicMessageStore createTopicMessageStore(ActiveMQTopic destination) + throws IOException { + TopicMessageStore rc = topics.get(destination); + if (rc == null) { + Store store = getStore(); + MapContainer messageContainer = getMapContainer(destination, "topic-data"); + MapContainer subsContainer = getSubsMapContainer(destination.toString() + "-Subscriptions", + "topic-subs"); + ListContainer ackContainer = store.getListContainer(destination.toString(), + "topic-acks"); ackContainer.setMarshaller(new TopicSubAckMarshaller()); - rc=new KahaTopicMessageStore(store,messageContainer,ackContainer,subsContainer,destination); - messageStores.put(destination,rc); - if(transactionStore!=null){ - rc=transactionStore.proxy(rc); + rc = new KahaTopicMessageStore(store, messageContainer, ackContainer, subsContainer, destination); + messageStores.put(destination, rc); + if (transactionStore != null) { + rc = transactionStore.proxy(rc); } - topics.put(destination,rc); + topics.put(destination, rc); } return rc; } - protected MessageStore retrieveMessageStore(Object id){ - MessageStore result=messageStores.get(id); + protected MessageStore retrieveMessageStore(Object id) { + MessageStore result = messageStores.get(id); return result; } - public TransactionStore createTransactionStore() throws IOException{ - if(transactionStore==null){ - while(true){ - try{ - Store store=getStore(); - MapContainer container=store.getMapContainer(PREPARED_TRANSACTIONS_NAME,"transactions"); + public TransactionStore createTransactionStore() throws IOException { + if (transactionStore == null) { + while (true) { + try { + Store store = getStore(); + MapContainer container = store + .getMapContainer(PREPARED_TRANSACTIONS_NAME, "transactions"); container.setKeyMarshaller(new CommandMarshaller(wireFormat)); container.setValueMarshaller(new TransactionMarshaller(wireFormat)); container.load(); - transactionStore=new KahaTransactionStore(this,container); + transactionStore = new KahaTransactionStore(this, container); break; - }catch(StoreLockedExcpetion e){ - log.info("Store is locked... waiting "+(STORE_LOCKED_WAIT_DELAY/1000) - +" seconds for the Store to be unlocked."); - try{ + } catch (StoreLockedExcpetion e) { + log.info("Store is locked... waiting " + (STORE_LOCKED_WAIT_DELAY / 1000) + + " seconds for the Store to be unlocked."); + try { Thread.sleep(STORE_LOCKED_WAIT_DELAY); - }catch(InterruptedException e1){ + } catch (InterruptedException e1) { } } } @@ -144,84 +148,87 @@ public class KahaPersistenceAdapter implements PersistenceAdapter{ return transactionStore; } - public void beginTransaction(ConnectionContext context){ + public void beginTransaction(ConnectionContext context) { } - public void commitTransaction(ConnectionContext context) throws IOException{ - if(theStore!=null){ + public void commitTransaction(ConnectionContext context) throws IOException { + if (theStore != null) { theStore.force(); } } - public void rollbackTransaction(ConnectionContext context){ + public void rollbackTransaction(ConnectionContext context) { } - public void start() throws Exception{ + public void start() throws Exception { initialize(); } - public void stop() throws Exception{ - if(theStore!=null){ + public void stop() throws Exception { + if (theStore != null) { theStore.close(); } } - public long getLastMessageBrokerSequenceId() throws IOException{ + public long getLastMessageBrokerSequenceId() throws IOException { return 0; } - public void deleteAllMessages() throws IOException{ - if(theStore!=null){ - if(theStore.isInitialized()){ + public void deleteAllMessages() throws IOException { + if (theStore != null) { + if (theStore.isInitialized()) { theStore.clear(); - }else{ + } else { theStore.delete(); } - }else{ + } else { StoreFactory.delete(getStoreName()); } } - protected MapContainer getMapContainer(Object id,String containerName) throws IOException{ - Store store=getStore(); - MapContainer container=store.getMapContainer(id,containerName); + protected MapContainer getMapContainer(Object id, String containerName) + throws IOException { + Store store = getStore(); + MapContainer container = store.getMapContainer(id, containerName); container.setKeyMarshaller(new MessageIdMarshaller()); container.setValueMarshaller(new MessageMarshaller(wireFormat)); container.load(); return container; } - protected MapContainer getSubsMapContainer(Object id,String containerName) throws IOException{ - Store store=getStore(); - MapContainer container=store.getMapContainer(id,containerName); + protected MapContainer getSubsMapContainer(Object id, String containerName) + throws IOException { + Store store = getStore(); + MapContainer container = store.getMapContainer(id, containerName); container.setKeyMarshaller(Store.StringMarshaller); container.setValueMarshaller(createMessageMarshaller()); container.load(); return container; } - protected Marshaller createMessageMarshaller(){ + protected Marshaller createMessageMarshaller() { return new CommandMarshaller(wireFormat); } - protected ListContainer getListContainer(Object id,String containerName) throws IOException{ - Store store=getStore(); - ListContainer container=store.getListContainer(id,containerName); + protected ListContainer getListContainer(Object id, String containerName) throws IOException { + Store store = getStore(); + ListContainer container = store.getListContainer(id, containerName); container.setMarshaller(createMessageMarshaller()); container.load(); return container; } /** - * @param usageManager The UsageManager that is controlling the broker's memory usage. + * @param usageManager The UsageManager that is controlling the broker's + * memory usage. */ - public void setUsageManager(UsageManager usageManager){ + public void setUsageManager(UsageManager usageManager) { } /** * @return the maxDataFileLength */ - public long getMaxDataFileLength(){ + public long getMaxDataFileLength() { return maxDataFileLength; } @@ -230,62 +237,61 @@ public class KahaPersistenceAdapter implements PersistenceAdapter{ * * @org.apache.xbean.Property propertyEditor="org.apache.activemq.util.MemoryPropertyEditor" */ - public void setMaxDataFileLength(long maxDataFileLength){ - this.maxDataFileLength=maxDataFileLength; + public void setMaxDataFileLength(long maxDataFileLength) { + this.maxDataFileLength = maxDataFileLength; } - protected synchronized Store getStore() throws IOException{ - if(theStore==null){ - theStore=StoreFactory.open(getStoreName(),"rw"); + protected synchronized Store getStore() throws IOException { + if (theStore == null) { + theStore = StoreFactory.open(getStoreName(), "rw"); theStore.setMaxDataFileLength(maxDataFileLength); } return theStore; } - private String getStoreName(){ + private String getStoreName() { initialize(); return directory.getAbsolutePath(); } - public String toString(){ - return "KahaPersistenceAdapter("+getStoreName()+")"; + public String toString() { + return "KahaPersistenceAdapter(" + getStoreName() + ")"; } - public void setBrokerName(String brokerName){ - this.brokerName=brokerName; + public void setBrokerName(String brokerName) { + this.brokerName = brokerName; } - - public String getBrokerName(){ + + public String getBrokerName() { return brokerName; } - public File getDirectory(){ + public File getDirectory() { return this.directory; } - public void setDirectory(File directory){ - this.directory=directory; + public void setDirectory(File directory) { + this.directory = directory; } - - public void checkpoint(boolean sync) throws IOException{ - if(sync){ + + public void checkpoint(boolean sync) throws IOException { + if (sync) { getStore().force(); } } - private void initialize(){ - if(!initialized){ - initialized=true; - if(this.directory==null){ - File file =new File(IOHelper.getDefaultDataDirectory()); - file=new File(file,brokerName+"-kahastore"); + private void initialize() { + if (!initialized) { + initialized = true; + if (this.directory == null) { + File file = new File(IOHelper.getDefaultDataDirectory()); + file = new File(file, brokerName + "-kahastore"); setDirectory(file); - } + } this.directory.mkdirs(); wireFormat.setCacheEnabled(false); wireFormat.setTightEncodingEnabled(true); } } - } diff --git a/activemq-core/src/main/java/org/apache/activemq/store/kahadaptor/KahaReferenceStore.java b/activemq-core/src/main/java/org/apache/activemq/store/kahadaptor/KahaReferenceStore.java index 9c198f7030..12bc3eb834 100644 --- a/activemq-core/src/main/java/org/apache/activemq/store/kahadaptor/KahaReferenceStore.java +++ b/activemq-core/src/main/java/org/apache/activemq/store/kahadaptor/KahaReferenceStore.java @@ -26,39 +26,41 @@ import org.apache.activemq.memory.UsageManager; import org.apache.activemq.store.MessageRecoveryListener; import org.apache.activemq.store.ReferenceStore; -public class KahaReferenceStore implements ReferenceStore{ +public class KahaReferenceStore implements ReferenceStore { protected final ActiveMQDestination destination; - protected final MapContainer messageContainer; + protected final MapContainer messageContainer; protected KahaReferenceStoreAdapter adapter; - private StoreEntry batchEntry=null; - private String lastBatchId=null; + private StoreEntry batchEntry = null; + private String lastBatchId = null; - public KahaReferenceStore(KahaReferenceStoreAdapter adapter,MapContainer container,ActiveMQDestination destination) throws IOException{ + public KahaReferenceStore(KahaReferenceStoreAdapter adapter, MapContainer container, + ActiveMQDestination destination) throws IOException { this.adapter = adapter; - this.messageContainer=container; - this.destination=destination; + this.messageContainer = container; + this.destination = destination; } - public void start(){ + public void start() { } - public void stop(){ + public void stop() { } - protected MessageId getMessageId(Object object){ + protected MessageId getMessageId(Object object) { return new MessageId(((ReferenceRecord)object).getMessageId()); } - public synchronized void addMessage(ConnectionContext context,Message message) throws IOException{ + public synchronized void addMessage(ConnectionContext context, Message message) throws IOException { throw new RuntimeException("Use addMessageReference instead"); } - public synchronized Message getMessage(MessageId identity) throws IOException{ + public synchronized Message getMessage(MessageId identity) throws IOException { throw new RuntimeException("Use addMessageReference instead"); } - protected final boolean recoverReference(MessageRecoveryListener listener,ReferenceRecord record) throws Exception{ + protected final boolean recoverReference(MessageRecoveryListener listener, ReferenceRecord record) + throws Exception { if (listener.hasSpace()) { listener.recoverMessageReference(new MessageId(record.getMessageId())); return true; @@ -66,118 +68,121 @@ public class KahaReferenceStore implements ReferenceStore{ return false; } - public synchronized void recover(MessageRecoveryListener listener) throws Exception{ - for(StoreEntry entry=messageContainer.getFirst();entry!=null;entry=messageContainer.getNext(entry)){ - ReferenceRecord record=messageContainer.getValue(entry); - if (!recoverReference(listener,record)) { + public synchronized void recover(MessageRecoveryListener listener) throws Exception { + for (StoreEntry entry = messageContainer.getFirst(); entry != null; entry = messageContainer + .getNext(entry)) { + ReferenceRecord record = messageContainer.getValue(entry); + if (!recoverReference(listener, record)) { break; } } } - public synchronized void recoverNextMessages(int maxReturned,MessageRecoveryListener listener) throws Exception{ - StoreEntry entry=batchEntry; - if(entry==null){ - entry=messageContainer.getFirst(); - }else{ - entry=messageContainer.refresh(entry); - if(entry!=null){ - entry=messageContainer.getNext(entry); + public synchronized void recoverNextMessages(int maxReturned, MessageRecoveryListener listener) + throws Exception { + StoreEntry entry = batchEntry; + if (entry == null) { + entry = messageContainer.getFirst(); + } else { + entry = messageContainer.refresh(entry); + if (entry != null) { + entry = messageContainer.getNext(entry); } } - if(entry!=null){ - int count=0; - do{ - ReferenceRecord msg=messageContainer.getValue(entry); - if(msg!=null){ - recoverReference(listener,msg); + if (entry != null) { + int count = 0; + do { + ReferenceRecord msg = messageContainer.getValue(entry); + if (msg != null) { + recoverReference(listener, msg); count++; - lastBatchId=msg.getMessageId(); - }else{ - lastBatchId=null; + lastBatchId = msg.getMessageId(); + } else { + lastBatchId = null; } - batchEntry=entry; - entry=messageContainer.getNext(entry); - }while(entry!=null&&count recordReferences=new HashMap(); + private Map recordReferences = new HashMap(); private ListContainer durableSubscribers; private boolean storeValid; private Store stateStore; - public synchronized MessageStore createQueueMessageStore(ActiveMQQueue destination) throws IOException{ + public synchronized MessageStore createQueueMessageStore(ActiveMQQueue destination) throws IOException { throw new RuntimeException("Use createQueueReferenceStore instead"); } - public synchronized TopicMessageStore createTopicMessageStore(ActiveMQTopic destination) throws IOException{ + public synchronized TopicMessageStore createTopicMessageStore(ActiveMQTopic destination) + throws IOException { throw new RuntimeException("Use createTopicReferenceStore instead"); } - @Override public synchronized void start() throws Exception{ + @Override + public synchronized void start() throws Exception { super.start(); - Store store=getStateStore(); - boolean empty=store.getMapContainerIds().isEmpty(); - stateMap=store.getMapContainer("state",STORE_STATE); + Store store = getStateStore(); + boolean empty = store.getMapContainerIds().isEmpty(); + stateMap = store.getMapContainer("state", STORE_STATE); stateMap.load(); - if(!empty){ - AtomicBoolean status=(AtomicBoolean)stateMap.get(STORE_STATE); - if(status!=null){ - storeValid=status.get(); + if (!empty) { + AtomicBoolean status = (AtomicBoolean)stateMap.get(STORE_STATE); + if (status != null) { + storeValid = status.get(); } - if(storeValid){ - if(stateMap.containsKey(RECORD_REFERENCES)){ - recordReferences=(Map)stateMap.get(RECORD_REFERENCES); + if (storeValid) { + if (stateMap.containsKey(RECORD_REFERENCES)) { + recordReferences = (Map)stateMap.get(RECORD_REFERENCES); } } } - stateMap.put(STORE_STATE,new AtomicBoolean()); - durableSubscribers=store.getListContainer("durableSubscribers"); + stateMap.put(STORE_STATE, new AtomicBoolean()); + durableSubscribers = store.getListContainer("durableSubscribers"); durableSubscribers.setMarshaller(new CommandMarshaller()); - preparedTransactions=store.getMapContainer("transactions",TRANSACTIONS,false); - //need to set the Marshallers here + preparedTransactions = store.getMapContainer("transactions", TRANSACTIONS, false); + // need to set the Marshallers here preparedTransactions.setKeyMarshaller(Store.CommandMarshaller); preparedTransactions.setValueMarshaller(new AMQTxMarshaller(wireFormat)); } - @Override public synchronized void stop() throws Exception{ - stateMap.put(RECORD_REFERENCES,recordReferences); - stateMap.put(STORE_STATE,new AtomicBoolean(true)); - if(this.stateStore!=null){ + @Override + public synchronized void stop() throws Exception { + stateMap.put(RECORD_REFERENCES, recordReferences); + stateMap.put(STORE_STATE, new AtomicBoolean(true)); + if (this.stateStore != null) { this.stateStore.close(); - this.stateStore=null; - this.stateMap=null; + this.stateStore = null; + this.stateMap = null; } super.stop(); } - public boolean isStoreValid(){ + public boolean isStoreValid() { return storeValid; } - public ReferenceStore createQueueReferenceStore(ActiveMQQueue destination) throws IOException{ - ReferenceStore rc=(ReferenceStore)queues.get(destination); - if(rc==null){ - rc=new KahaReferenceStore(this,getMapReferenceContainer(destination,"queue-data"),destination); - messageStores.put(destination,rc); - // if(transactionStore!=null){ - // rc=transactionStore.proxy(rc); - // } - queues.put(destination,rc); + public ReferenceStore createQueueReferenceStore(ActiveMQQueue destination) throws IOException { + ReferenceStore rc = (ReferenceStore)queues.get(destination); + if (rc == null) { + rc = new KahaReferenceStore(this, getMapReferenceContainer(destination, "queue-data"), + destination); + messageStores.put(destination, rc); + // if(transactionStore!=null){ + // rc=transactionStore.proxy(rc); + // } + queues.put(destination, rc); } return rc; } - public TopicReferenceStore createTopicReferenceStore(ActiveMQTopic destination) throws IOException{ - TopicReferenceStore rc=(TopicReferenceStore)topics.get(destination); - if(rc==null){ - Store store=getStore(); - MapContainer messageContainer=getMapReferenceContainer(destination,"topic-data"); - MapContainer subsContainer=getSubsMapContainer(destination.toString()+"-Subscriptions","blob"); - ListContainer ackContainer=store.getListContainer(destination.toString(),"topic-acks"); + public TopicReferenceStore createTopicReferenceStore(ActiveMQTopic destination) throws IOException { + TopicReferenceStore rc = (TopicReferenceStore)topics.get(destination); + if (rc == null) { + Store store = getStore(); + MapContainer messageContainer = getMapReferenceContainer(destination, "topic-data"); + MapContainer subsContainer = getSubsMapContainer(destination.toString() + "-Subscriptions", + "blob"); + ListContainer ackContainer = store.getListContainer(destination.toString(), "topic-acks"); ackContainer.setMarshaller(new TopicSubAckMarshaller()); - rc=new KahaTopicReferenceStore(store,this,messageContainer,ackContainer,subsContainer,destination); - messageStores.put(destination,rc); - // if(transactionStore!=null){ - // rc=transactionStore.proxy(rc); - // } - topics.put(destination,rc); + rc = new KahaTopicReferenceStore(store, this, messageContainer, ackContainer, subsContainer, + destination); + messageStores.put(destination, rc); + // if(transactionStore!=null){ + // rc=transactionStore.proxy(rc); + // } + topics.put(destination, rc); } return rc; } - public void buildReferenceFileIdsInUse() throws IOException{ - recordReferences=new HashMap(); - Set destinations=getDestinations(); - for(ActiveMQDestination destination:destinations){ - if(destination.isQueue()){ - KahaReferenceStore store=(KahaReferenceStore)createQueueReferenceStore((ActiveMQQueue)destination); + public void buildReferenceFileIdsInUse() throws IOException { + recordReferences = new HashMap(); + Set destinations = getDestinations(); + for (ActiveMQDestination destination : destinations) { + if (destination.isQueue()) { + KahaReferenceStore store = (KahaReferenceStore)createQueueReferenceStore((ActiveMQQueue)destination); store.addReferenceFileIdsInUse(); - }else{ - KahaTopicReferenceStore store=(KahaTopicReferenceStore)createTopicReferenceStore((ActiveMQTopic)destination); + } else { + KahaTopicReferenceStore store = (KahaTopicReferenceStore)createTopicReferenceStore((ActiveMQTopic)destination); store.addReferenceFileIdsInUse(); } } } - protected MapContainer getMapReferenceContainer(Object id,String containerName) - throws IOException{ - Store store=getStore(); - MapContainer container=store.getMapContainer(id,containerName); + protected MapContainer getMapReferenceContainer(Object id, + String containerName) + throws IOException { + Store store = getStore(); + MapContainer container = store.getMapContainer(id, containerName); container.setKeyMarshaller(new MessageIdMarshaller()); container.setValueMarshaller(new ReferenceRecordMarshaller()); container.load(); return container; } - synchronized void addInterestInRecordFile(int recordNumber){ - Integer key=Integer.valueOf(recordNumber); - AtomicInteger rr=recordReferences.get(key); - if(rr==null){ - rr=new AtomicInteger(); - recordReferences.put(key,rr); + synchronized void addInterestInRecordFile(int recordNumber) { + Integer key = Integer.valueOf(recordNumber); + AtomicInteger rr = recordReferences.get(key); + if (rr == null) { + rr = new AtomicInteger(); + recordReferences.put(key, rr); } rr.incrementAndGet(); } - synchronized void removeInterestInRecordFile(int recordNumber){ - Integer key=Integer.valueOf(recordNumber); - AtomicInteger rr=recordReferences.get(key); - if(rr!=null&&rr.decrementAndGet()<=0){ + synchronized void removeInterestInRecordFile(int recordNumber) { + Integer key = Integer.valueOf(recordNumber); + AtomicInteger rr = recordReferences.get(key); + if (rr != null && rr.decrementAndGet() <= 0) { recordReferences.remove(key); } } @@ -188,99 +195,97 @@ public class KahaReferenceStoreAdapter extends KahaPersistenceAdapter implements * @throws IOException * @see org.apache.activemq.store.ReferenceStoreAdapter#getReferenceFileIdsInUse() */ - public Set getReferenceFileIdsInUse() throws IOException{ + public Set getReferenceFileIdsInUse() throws IOException { return recordReferences.keySet(); } /** * - * @throws IOException + * @throws IOException * @see org.apache.activemq.store.ReferenceStoreAdapter#clearMessages() */ - public void clearMessages() throws IOException{ + public void clearMessages() throws IOException { deleteAllMessages(); } /** * - * @throws IOException + * @throws IOException * @see org.apache.activemq.store.ReferenceStoreAdapter#recoverState() */ - public void recoverState() throws IOException{ - for(Iterator i=durableSubscribers.iterator();i.hasNext();){ - SubscriptionInfo info=(SubscriptionInfo)i.next(); - TopicReferenceStore ts=createTopicReferenceStore((ActiveMQTopic)info.getDestination()); - ts.addSubsciption(info,false); + public void recoverState() throws IOException { + for (Iterator i = durableSubscribers.iterator(); i.hasNext();) { + SubscriptionInfo info = (SubscriptionInfo)i.next(); + TopicReferenceStore ts = createTopicReferenceStore((ActiveMQTopic)info.getDestination()); + ts.addSubsciption(info, false); } } - public Map retrievePreparedState() throws IOException{ - Map result=new HashMap(); + public Map retrievePreparedState() throws IOException { + Map result = new HashMap(); preparedTransactions.load(); - for(Iterator i=preparedTransactions.keySet().iterator();i.hasNext();){ - TransactionId key=(TransactionId)i.next(); - AMQTx value=(AMQTx)preparedTransactions.get(key); - result.put(key,value); + for (Iterator i = preparedTransactions.keySet().iterator(); i.hasNext();) { + TransactionId key = (TransactionId)i.next(); + AMQTx value = (AMQTx)preparedTransactions.get(key); + result.put(key, value); } return result; } - public void savePreparedState(Map map) throws IOException{ + public void savePreparedState(Map map) throws IOException { preparedTransactions.clear(); - for(Iterator> iter=map.entrySet().iterator();iter.hasNext();){ - Map.Entry entry=iter.next(); - preparedTransactions.put(entry.getKey(),entry.getValue()); + for (Iterator> iter = map.entrySet().iterator(); iter.hasNext();) { + Map.Entry entry = iter.next(); + preparedTransactions.put(entry.getKey(), entry.getValue()); } } - @Override public synchronized void setDirectory(File directory){ - File file=new File(directory,"data"); + @Override + public synchronized void setDirectory(File directory) { + File file = new File(directory, "data"); super.setDirectory(file); - this.stateStore=createStateStore(directory); + this.stateStore = createStateStore(directory); } - protected synchronized Store getStateStore() throws IOException{ - if(this.stateStore==null){ - File stateDirectory=new File(getDirectory(),"kr-state"); + protected synchronized Store getStateStore() throws IOException { + if (this.stateStore == null) { + File stateDirectory = new File(getDirectory(), "kr-state"); stateDirectory.mkdirs(); - this.stateStore=createStateStore(getDirectory()); + this.stateStore = createStateStore(getDirectory()); } return this.stateStore; } - public void deleteAllMessages() throws IOException{ - super.deleteAllMessages(); - if(stateStore!=null){ - if(stateStore.isInitialized()){ - stateStore.clear(); - }else{ - stateStore.delete(); + public void deleteAllMessages() throws IOException { + super.deleteAllMessages(); + if (stateStore != null) { + if (stateStore.isInitialized()) { + stateStore.clear(); + } else { + stateStore.delete(); } - }else{ - File stateDirectory=new File(getDirectory(),"kr-state"); + } else { + File stateDirectory = new File(getDirectory(), "kr-state"); StoreFactory.delete(stateDirectory.getAbsolutePath()); } } - private Store createStateStore(File directory){ - File stateDirectory=new File(directory,"state"); + private Store createStateStore(File directory) { + File stateDirectory = new File(directory, "state"); stateDirectory.mkdirs(); - try{ - return StoreFactory.open(stateDirectory.getAbsolutePath(),"rw"); - }catch(IOException e){ - log.error("Failed to create the state store",e); + try { + return StoreFactory.open(stateDirectory.getAbsolutePath(), "rw"); + } catch (IOException e) { + log.error("Failed to create the state store", e); } return null; } - protected void addSubscriberState(SubscriptionInfo info) throws IOException{ + protected void addSubscriberState(SubscriptionInfo info) throws IOException { durableSubscribers.add(info); } - protected void removeSubscriberState(SubscriptionInfo info){ + protected void removeSubscriberState(SubscriptionInfo info) { durableSubscribers.remove(info); } } - - - diff --git a/activemq-core/src/main/java/org/apache/activemq/store/kahadaptor/KahaTopicMessageStore.java b/activemq-core/src/main/java/org/apache/activemq/store/kahadaptor/KahaTopicMessageStore.java index ec35ded772..a4fcdc2553 100755 --- a/activemq-core/src/main/java/org/apache/activemq/store/kahadaptor/KahaTopicMessageStore.java +++ b/activemq-core/src/main/java/org/apache/activemq/store/kahadaptor/KahaTopicMessageStore.java @@ -34,39 +34,40 @@ import org.apache.activemq.store.TopicMessageStore; /** * @version $Revision: 1.5 $ */ -public class KahaTopicMessageStore extends KahaMessageStore implements TopicMessageStore{ +public class KahaTopicMessageStore extends KahaMessageStore implements TopicMessageStore { protected ListContainer ackContainer; private Map subscriberContainer; private Store store; - protected Map subscriberMessages=new ConcurrentHashMap(); + protected Map subscriberMessages = new ConcurrentHashMap(); - public KahaTopicMessageStore(Store store,MapContainer messageContainer,ListContainer ackContainer, - MapContainer subsContainer,ActiveMQDestination destination) throws IOException{ - super(messageContainer,destination); - this.store=store; - this.ackContainer=ackContainer; - subscriberContainer=subsContainer; + public KahaTopicMessageStore(Store store, MapContainer messageContainer, + ListContainer ackContainer, MapContainer subsContainer, + ActiveMQDestination destination) throws IOException { + super(messageContainer, destination); + this.store = store; + this.ackContainer = ackContainer; + subscriberContainer = subsContainer; // load all the Ack containers - for(Iterator i=subscriberContainer.keySet().iterator();i.hasNext();){ - Object key=i.next(); + for (Iterator i = subscriberContainer.keySet().iterator(); i.hasNext();) { + Object key = i.next(); addSubscriberMessageContainer(key); } } @Override - public synchronized void addMessage(ConnectionContext context,Message message) throws IOException{ - int subscriberCount=subscriberMessages.size(); - if(subscriberCount>0){ + public synchronized void addMessage(ConnectionContext context, Message message) throws IOException { + int subscriberCount = subscriberMessages.size(); + if (subscriberCount > 0) { MessageId id = message.getMessageId(); - StoreEntry messageEntry=messageContainer.place(id,message); - TopicSubAck tsa=new TopicSubAck(); + StoreEntry messageEntry = messageContainer.place(id, message); + TopicSubAck tsa = new TopicSubAck(); tsa.setCount(subscriberCount); tsa.setMessageEntry(messageEntry); - StoreEntry ackEntry=ackContainer.placeLast(tsa); - for(Iterator i=subscriberMessages.values().iterator();i.hasNext();){ - TopicSubContainer container=(TopicSubContainer)i.next(); - ConsumerMessageRef ref=new ConsumerMessageRef(); + StoreEntry ackEntry = ackContainer.placeLast(tsa); + for (Iterator i = subscriberMessages.values().iterator(); i.hasNext();) { + TopicSubContainer container = (TopicSubContainer)i.next(); + ConsumerMessageRef ref = new ConsumerMessageRef(); ref.setAckEntry(ackEntry); ref.setMessageEntry(messageEntry); ref.setMessageId(id); @@ -75,75 +76,71 @@ public class KahaTopicMessageStore extends KahaMessageStore implements TopicMess } } - public synchronized void acknowledge(ConnectionContext context,String clientId,String subscriptionName, - MessageId messageId) throws IOException{ - String subcriberId=getSubscriptionKey(clientId,subscriptionName); - TopicSubContainer container=(TopicSubContainer)subscriberMessages.get(subcriberId); - if(container!=null){ - ConsumerMessageRef ref=container.remove(messageId); - if(container.isEmpty()){ + public synchronized void acknowledge(ConnectionContext context, String clientId, String subscriptionName, + MessageId messageId) throws IOException { + String subcriberId = getSubscriptionKey(clientId, subscriptionName); + TopicSubContainer container = (TopicSubContainer)subscriberMessages.get(subcriberId); + if (container != null) { + ConsumerMessageRef ref = container.remove(messageId); + if (container.isEmpty()) { container.reset(); } - if(ref!=null){ - TopicSubAck tsa=(TopicSubAck)ackContainer.get(ref.getAckEntry()); - if(tsa!=null){ - if(tsa.decrementCount()<=0){ + if (ref != null) { + TopicSubAck tsa = (TopicSubAck)ackContainer.get(ref.getAckEntry()); + if (tsa != null) { + if (tsa.decrementCount() <= 0) { StoreEntry entry = ref.getAckEntry(); entry = ackContainer.refresh(entry); ackContainer.remove(entry); entry = tsa.getMessageEntry(); - entry =messageContainer.refresh(entry); + entry = messageContainer.refresh(entry); messageContainer.remove(entry); - }else{ - ackContainer.update(ref.getAckEntry(),tsa); + } else { + ackContainer.update(ref.getAckEntry(), tsa); } } } } } - public SubscriptionInfo lookupSubscription(String clientId,String subscriptionName) throws IOException{ - return (SubscriptionInfo)subscriberContainer.get(getSubscriptionKey(clientId,subscriptionName)); + public SubscriptionInfo lookupSubscription(String clientId, String subscriptionName) throws IOException { + return (SubscriptionInfo)subscriberContainer.get(getSubscriptionKey(clientId, subscriptionName)); } - public synchronized void addSubsciption(SubscriptionInfo info,boolean retroactive) - throws IOException{ - String key=getSubscriptionKey(info.getClientId(),info.getSubscriptionName()); + public synchronized void addSubsciption(SubscriptionInfo info, boolean retroactive) throws IOException { + String key = getSubscriptionKey(info.getClientId(), info.getSubscriptionName()); // if already exists - won't add it again as it causes data files // to hang around - if(!subscriberContainer.containsKey(key)){ - subscriberContainer.put(key,info); + if (!subscriberContainer.containsKey(key)) { + subscriberContainer.put(key, info); } // add the subscriber - ListContainer container=addSubscriberMessageContainer(key); + ListContainer container = addSubscriberMessageContainer(key); /* - if(retroactive){ - for(StoreEntry entry=ackContainer.getFirst();entry!=null;entry=ackContainer.getNext(entry)){ - TopicSubAck tsa=(TopicSubAck)ackContainer.get(entry); - ConsumerMessageRef ref=new ConsumerMessageRef(); - ref.setAckEntry(entry); - ref.setMessageEntry(tsa.getMessageEntry()); - container.add(ref); - } - } - */ + * if(retroactive){ for(StoreEntry + * entry=ackContainer.getFirst();entry!=null;entry=ackContainer.getNext(entry)){ + * TopicSubAck tsa=(TopicSubAck)ackContainer.get(entry); + * ConsumerMessageRef ref=new ConsumerMessageRef(); + * ref.setAckEntry(entry); ref.setMessageEntry(tsa.getMessageEntry()); + * container.add(ref); } } + */ } - public synchronized void deleteSubscription(String clientId,String subscriptionName) throws IOException{ - String key=getSubscriptionKey(clientId,subscriptionName); + public synchronized void deleteSubscription(String clientId, String subscriptionName) throws IOException { + String key = getSubscriptionKey(clientId, subscriptionName); removeSubscriberMessageContainer(key); } - public void recoverSubscription(String clientId,String subscriptionName,MessageRecoveryListener listener) - throws Exception{ - String key=getSubscriptionKey(clientId,subscriptionName); - TopicSubContainer container=(TopicSubContainer)subscriberMessages.get(key); - if(container!=null){ - for(Iterator i=container.iterator();i.hasNext();){ - ConsumerMessageRef ref=(ConsumerMessageRef)i.next(); - Message msg=messageContainer.get(ref.getMessageEntry()); - if(msg!=null){ - if(!recoverMessage(listener,msg)){ + public void recoverSubscription(String clientId, String subscriptionName, MessageRecoveryListener listener) + throws Exception { + String key = getSubscriptionKey(clientId, subscriptionName); + TopicSubContainer container = (TopicSubContainer)subscriberMessages.get(key); + if (container != null) { + for (Iterator i = container.iterator(); i.hasNext();) { + ConsumerMessageRef ref = (ConsumerMessageRef)i.next(); + Message msg = messageContainer.get(ref.getMessageEntry()); + if (msg != null) { + if (!recoverMessage(listener, msg)) { break; } } @@ -151,88 +148,89 @@ public class KahaTopicMessageStore extends KahaMessageStore implements TopicMess } } - public void recoverNextMessages(String clientId,String subscriptionName,int maxReturned, - MessageRecoveryListener listener) throws Exception{ - String key=getSubscriptionKey(clientId,subscriptionName); - TopicSubContainer container=(TopicSubContainer)subscriberMessages.get(key); - if(container!=null){ - int count=0; - StoreEntry entry=container.getBatchEntry(); - if(entry==null){ - entry=container.getEntry(); - }else{ - entry=container.refreshEntry(entry); - if(entry!=null){ - entry=container.getNextEntry(entry); + public void recoverNextMessages(String clientId, String subscriptionName, int maxReturned, + MessageRecoveryListener listener) throws Exception { + String key = getSubscriptionKey(clientId, subscriptionName); + TopicSubContainer container = (TopicSubContainer)subscriberMessages.get(key); + if (container != null) { + int count = 0; + StoreEntry entry = container.getBatchEntry(); + if (entry == null) { + entry = container.getEntry(); + } else { + entry = container.refreshEntry(entry); + if (entry != null) { + entry = container.getNextEntry(entry); } } - if(entry!=null){ - do{ - ConsumerMessageRef consumerRef=container.get(entry); - Message msg=messageContainer.getValue(consumerRef.getMessageEntry()); - if(msg!=null){ - recoverMessage(listener, msg); + if (entry != null) { + do { + ConsumerMessageRef consumerRef = container.get(entry); + Message msg = messageContainer.getValue(consumerRef.getMessageEntry()); + if (msg != null) { + recoverMessage(listener, msg); count++; - container.setBatchEntry(msg.getMessageId().toString(),entry); - }else { + container.setBatchEntry(msg.getMessageId().toString(), entry); + } else { container.reset(); } - - entry=container.getNextEntry(entry); - }while(entry!=null&&count ackContainer; private Map subscriberContainer; private Store store; - protected Map subscriberMessages=new ConcurrentHashMap(); + protected Map subscriberMessages = new ConcurrentHashMap(); - public KahaTopicReferenceStore(Store store,KahaReferenceStoreAdapter adapter,MapContainer messageContainer,ListContainer ackContainer, - MapContainer subsContainer,ActiveMQDestination destination) throws IOException{ - super(adapter,messageContainer,destination); - this.store=store; - this.ackContainer=ackContainer; - subscriberContainer=subsContainer; + public KahaTopicReferenceStore(Store store, KahaReferenceStoreAdapter adapter, + MapContainer messageContainer, ListContainer ackContainer, + MapContainer subsContainer, ActiveMQDestination destination) + throws IOException { + super(adapter, messageContainer, destination); + this.store = store; + this.ackContainer = ackContainer; + subscriberContainer = subsContainer; // load all the Ack containers - for(Iterator i=subscriberContainer.keySet().iterator();i.hasNext();){ - String key=(String) i.next(); + for (Iterator i = subscriberContainer.keySet().iterator(); i.hasNext();) { + String key = (String)i.next(); addSubscriberMessageContainer(key); } } - protected MessageId getMessageId(Object object){ + protected MessageId getMessageId(Object object) { return new MessageId(((ReferenceRecord)object).getMessageId()); } - public synchronized void addMessage(ConnectionContext context,Message message) throws IOException{ + public synchronized void addMessage(ConnectionContext context, Message message) throws IOException { throw new RuntimeException("Use addMessageReference instead"); } - public synchronized Message getMessage(MessageId identity) throws IOException{ + public synchronized Message getMessage(MessageId identity) throws IOException { throw new RuntimeException("Use addMessageReference instead"); } - - public void addMessageReference(final ConnectionContext context,final MessageId messageId,final ReferenceData data){ - final ReferenceRecord record=new ReferenceRecord(messageId.toString(),data); - final int subscriberCount=subscriberMessages.size(); - if(subscriberCount>0){ - final StoreEntry messageEntry=messageContainer.place(messageId,record); + public void addMessageReference(final ConnectionContext context, final MessageId messageId, + final ReferenceData data) { + final ReferenceRecord record = new ReferenceRecord(messageId.toString(), data); + final int subscriberCount = subscriberMessages.size(); + if (subscriberCount > 0) { + final StoreEntry messageEntry = messageContainer.place(messageId, record); addInterest(record); - final TopicSubAck tsa=new TopicSubAck(); + final TopicSubAck tsa = new TopicSubAck(); tsa.setCount(subscriberCount); tsa.setMessageEntry(messageEntry); - final StoreEntry ackEntry=ackContainer.placeLast(tsa); - for(final Iterator i=subscriberMessages.values().iterator();i.hasNext();){ - final TopicSubContainer container=(TopicSubContainer)i.next(); - final ConsumerMessageRef ref=new ConsumerMessageRef(); + final StoreEntry ackEntry = ackContainer.placeLast(tsa); + for (final Iterator i = subscriberMessages.values().iterator(); i.hasNext();) { + final TopicSubContainer container = (TopicSubContainer)i.next(); + final ConsumerMessageRef ref = new ConsumerMessageRef(); ref.setAckEntry(ackEntry); ref.setMessageEntry(messageEntry); ref.setMessageId(messageId); @@ -86,154 +88,152 @@ public class KahaTopicReferenceStore extends KahaReferenceStore implements Topic } } - public ReferenceData getMessageReference(final MessageId identity) throws IOException{ - final ReferenceRecord result=messageContainer.get(identity); - if(result==null) + public ReferenceData getMessageReference(final MessageId identity) throws IOException { + final ReferenceRecord result = messageContainer.get(identity); + if (result == null) return null; return result.getData(); } - public void addReferenceFileIdsInUse(){ - for(StoreEntry entry=ackContainer.getFirst();entry!=null;entry=ackContainer.getNext(entry)){ - TopicSubAck subAck=(TopicSubAck)ackContainer.get(entry); - if(subAck.getCount()>0){ - ReferenceRecord rr=(ReferenceRecord)messageContainer.getValue(subAck.getMessageEntry()); + public void addReferenceFileIdsInUse() { + for (StoreEntry entry = ackContainer.getFirst(); entry != null; entry = ackContainer.getNext(entry)) { + TopicSubAck subAck = (TopicSubAck)ackContainer.get(entry); + if (subAck.getCount() > 0) { + ReferenceRecord rr = (ReferenceRecord)messageContainer.getValue(subAck.getMessageEntry()); addInterest(rr); } } } - protected ListContainer addSubscriberMessageContainer(String key) throws IOException{ - ListContainer container=store.getListContainer(destination,"topic-subs-references-"+key); - Marshaller marshaller=new ConsumerMessageRefMarshaller(); + protected ListContainer addSubscriberMessageContainer(String key) throws IOException { + ListContainer container = store.getListContainer(destination, "topic-subs-references-" + key); + Marshaller marshaller = new ConsumerMessageRefMarshaller(); container.setMarshaller(marshaller); - TopicSubContainer tsc=new TopicSubContainer(container); - subscriberMessages.put(key,tsc); + TopicSubContainer tsc = new TopicSubContainer(container); + subscriberMessages.put(key, tsc); return container; } - public synchronized void acknowledge(ConnectionContext context,String clientId,String subscriptionName, - MessageId messageId) throws IOException{ - String key=getSubscriptionKey(clientId,subscriptionName); - - TopicSubContainer container=(TopicSubContainer)subscriberMessages.get(key); - if(container!=null){ - ConsumerMessageRef ref=container.remove(messageId); - if(ref!=null){ - TopicSubAck tsa=(TopicSubAck)ackContainer.get(ref.getAckEntry()); - if(tsa!=null){ - if(tsa.decrementCount()<=0){ - StoreEntry entry=ref.getAckEntry(); - entry=ackContainer.refresh(entry); + public synchronized void acknowledge(ConnectionContext context, String clientId, String subscriptionName, + MessageId messageId) throws IOException { + String key = getSubscriptionKey(clientId, subscriptionName); + + TopicSubContainer container = (TopicSubContainer)subscriberMessages.get(key); + if (container != null) { + ConsumerMessageRef ref = container.remove(messageId); + if (ref != null) { + TopicSubAck tsa = (TopicSubAck)ackContainer.get(ref.getAckEntry()); + if (tsa != null) { + if (tsa.decrementCount() <= 0) { + StoreEntry entry = ref.getAckEntry(); + entry = ackContainer.refresh(entry); ackContainer.remove(entry); - ReferenceRecord rr=messageContainer.get(messageId); - if(rr!=null){ - entry=tsa.getMessageEntry(); - entry=messageContainer.refresh(entry); + ReferenceRecord rr = messageContainer.get(messageId); + if (rr != null) { + entry = tsa.getMessageEntry(); + entry = messageContainer.refresh(entry); messageContainer.remove(entry); removeInterest(rr); } - }else{ - - ackContainer.update(ref.getAckEntry(),tsa); + } else { + + ackContainer.update(ref.getAckEntry(), tsa); } } } } } - public synchronized void addSubsciption(SubscriptionInfo info,boolean retroactive) - throws IOException{ - String key=getSubscriptionKey(info.getClientId(), info.getSubscriptionName()); + public synchronized void addSubsciption(SubscriptionInfo info, boolean retroactive) throws IOException { + String key = getSubscriptionKey(info.getClientId(), info.getSubscriptionName()); // if already exists - won't add it again as it causes data files // to hang around - if(!subscriberContainer.containsKey(key)){ - subscriberContainer.put(key,info); + if (!subscriberContainer.containsKey(key)) { + subscriberContainer.put(key, info); adapter.addSubscriberState(info); } // add the subscriber - ListContainer container=addSubscriberMessageContainer(key); - if(retroactive){ + ListContainer container = addSubscriberMessageContainer(key); + if (retroactive) { /* - for(StoreEntry entry=ackContainer.getFirst();entry!=null;entry=ackContainer.getNext(entry)){ - TopicSubAck tsa=(TopicSubAck)ackContainer.get(entry); - ConsumerMessageRef ref=new ConsumerMessageRef(); - ref.setAckEntry(entry); - ref.setMessageEntry(tsa.getMessageEntry()); - container.add(ref); - } - */ + * for(StoreEntry + * entry=ackContainer.getFirst();entry!=null;entry=ackContainer.getNext(entry)){ + * TopicSubAck tsa=(TopicSubAck)ackContainer.get(entry); + * ConsumerMessageRef ref=new ConsumerMessageRef(); + * ref.setAckEntry(entry); + * ref.setMessageEntry(tsa.getMessageEntry()); container.add(ref); } + */ } } - public synchronized void deleteSubscription(String clientId,String subscriptionName) throws IOException{ - SubscriptionInfo info = lookupSubscription(clientId,subscriptionName); + public synchronized void deleteSubscription(String clientId, String subscriptionName) throws IOException { + SubscriptionInfo info = lookupSubscription(clientId, subscriptionName); if (info != null) { adapter.removeSubscriberState(info); } - String key=getSubscriptionKey(clientId,subscriptionName); + String key = getSubscriptionKey(clientId, subscriptionName); removeSubscriberMessageContainer(key); } - public SubscriptionInfo[] getAllSubscriptions() throws IOException{ - return (SubscriptionInfo[])subscriberContainer.values().toArray( - new SubscriptionInfo[subscriberContainer.size()]); + public SubscriptionInfo[] getAllSubscriptions() throws IOException { + return (SubscriptionInfo[])subscriberContainer.values() + .toArray(new SubscriptionInfo[subscriberContainer.size()]); } - public int getMessageCount(String clientId,String subscriberName) throws IOException{ - String key=getSubscriptionKey(clientId,subscriberName); - TopicSubContainer container=(TopicSubContainer)subscriberMessages.get(key); - return container != null ? container.size() : 0; + public int getMessageCount(String clientId, String subscriberName) throws IOException { + String key = getSubscriptionKey(clientId, subscriberName); + TopicSubContainer container = (TopicSubContainer)subscriberMessages.get(key); + return container != null ? container.size() : 0; } - public SubscriptionInfo lookupSubscription(String clientId,String subscriptionName) throws IOException{ - return (SubscriptionInfo)subscriberContainer.get(getSubscriptionKey(clientId,subscriptionName)); + public SubscriptionInfo lookupSubscription(String clientId, String subscriptionName) throws IOException { + return (SubscriptionInfo)subscriberContainer.get(getSubscriptionKey(clientId, subscriptionName)); } - public synchronized void recoverNextMessages(String clientId,String subscriptionName,int maxReturned, - MessageRecoveryListener listener) throws Exception{ - String key=getSubscriptionKey(clientId,subscriptionName); - TopicSubContainer container=(TopicSubContainer)subscriberMessages.get(key); - if(container!=null){ - int count=0; - StoreEntry entry=container.getBatchEntry(); - if(entry==null){ - entry=container.getEntry(); - }else{ - entry=container.refreshEntry(entry); - if(entry!=null){ - entry=container.getNextEntry(entry); + public synchronized void recoverNextMessages(String clientId, String subscriptionName, int maxReturned, + MessageRecoveryListener listener) throws Exception { + String key = getSubscriptionKey(clientId, subscriptionName); + TopicSubContainer container = (TopicSubContainer)subscriberMessages.get(key); + if (container != null) { + int count = 0; + StoreEntry entry = container.getBatchEntry(); + if (entry == null) { + entry = container.getEntry(); + } else { + entry = container.refreshEntry(entry); + if (entry != null) { + entry = container.getNextEntry(entry); } } - - if(entry!=null){ - do{ - ConsumerMessageRef consumerRef=container.get(entry); - ReferenceRecord msg=messageContainer.getValue(consumerRef.getMessageEntry()); - if(msg!=null){ - recoverReference(listener,msg); + + if (entry != null) { + do { + ConsumerMessageRef consumerRef = container.get(entry); + ReferenceRecord msg = messageContainer.getValue(consumerRef.getMessageEntry()); + if (msg != null) { + recoverReference(listener, msg); count++; - container.setBatchEntry(msg.getMessageId(),entry); - }else { + container.setBatchEntry(msg.getMessageId(), entry); + } else { container.reset(); } - - entry=container.getNextEntry(entry); - }while(entry!=null&&count{ +public class ReferenceRecordMarshaller implements Marshaller { - public ReferenceRecord readPayload(DataInput dataIn) throws IOException{ - ReferenceRecord rr=new ReferenceRecord(); + public ReferenceRecord readPayload(DataInput dataIn) throws IOException { + ReferenceRecord rr = new ReferenceRecord(); rr.setMessageId(dataIn.readUTF()); ReferenceData referenceData = new ReferenceData(); referenceData.setFileId(dataIn.readInt()); @@ -37,9 +37,10 @@ public class ReferenceRecordMarshaller implements Marshaller{ * @param object * @param dataOut * @throws IOException - * @see org.apache.activemq.kaha.Marshaller#writePayload(java.lang.Object, java.io.DataOutput) + * @see org.apache.activemq.kaha.Marshaller#writePayload(java.lang.Object, + * java.io.DataOutput) */ - public void writePayload(ReferenceRecord rr,DataOutput dataOut) throws IOException{ + public void writePayload(ReferenceRecord rr, DataOutput dataOut) throws IOException { dataOut.writeUTF(rr.getMessageId()); dataOut.writeInt(rr.getData().getFileId()); dataOut.writeInt(rr.getData().getOffset()); diff --git a/activemq-core/src/main/java/org/apache/activemq/store/kahadaptor/StoreEntryMarshaller.java b/activemq-core/src/main/java/org/apache/activemq/store/kahadaptor/StoreEntryMarshaller.java index 88ff1679d1..5cf929f5b2 100644 --- a/activemq-core/src/main/java/org/apache/activemq/store/kahadaptor/StoreEntryMarshaller.java +++ b/activemq-core/src/main/java/org/apache/activemq/store/kahadaptor/StoreEntryMarshaller.java @@ -22,22 +22,21 @@ import java.io.IOException; import org.apache.activemq.kaha.Marshaller; import org.apache.activemq.kaha.impl.index.IndexItem; - /** * Marshall a TopicSubAck + * * @version $Revision: 1.10 $ */ -public class StoreEntryMarshaller implements Marshaller{ - +public class StoreEntryMarshaller implements Marshaller { + + public void writePayload(Object object, DataOutput dataOut) throws IOException { + IndexItem item = (IndexItem)object; + dataOut.writeLong(item.getOffset()); + item.write(dataOut); - public void writePayload(Object object,DataOutput dataOut) throws IOException{ - IndexItem item = (IndexItem)object; - dataOut.writeLong(item.getOffset()); - item.write(dataOut); - } - public Object readPayload(DataInput dataIn) throws IOException{ + public Object readPayload(DataInput dataIn) throws IOException { IndexItem item = new IndexItem(); item.setOffset(dataIn.readLong()); item.read(dataIn); diff --git a/activemq-core/src/main/java/org/apache/activemq/store/kahadaptor/TopicSubAck.java b/activemq-core/src/main/java/org/apache/activemq/store/kahadaptor/TopicSubAck.java index def109a109..403e49b369 100644 --- a/activemq-core/src/main/java/org/apache/activemq/store/kahadaptor/TopicSubAck.java +++ b/activemq-core/src/main/java/org/apache/activemq/store/kahadaptor/TopicSubAck.java @@ -21,32 +21,32 @@ import org.apache.activemq.kaha.StoreEntry; * * @version $Revision: 1.10 $ */ -public class TopicSubAck{ +public class TopicSubAck { - private int count =0; + private int count = 0; private StoreEntry messageEntry; /** * @return the count */ - public int getCount(){ + public int getCount() { return this.count; } /** * @param count the count to set */ - public void setCount(int count){ - this.count=count; + public void setCount(int count) { + this.count = count; } - + /** * @return the value of the count after it's decremented */ public int decrementCount() { return --count; } - + /** * @return the value of the count after it's incremented */ @@ -54,21 +54,18 @@ public class TopicSubAck{ return ++count; } - /** * @return the messageEntry */ - public StoreEntry getMessageEntry(){ + public StoreEntry getMessageEntry() { return this.messageEntry; } - /** * @param messageEntry the messageEntry to set */ - public void setMessageEntry(StoreEntry storeEntry){ - this.messageEntry=storeEntry; + public void setMessageEntry(StoreEntry storeEntry) { + this.messageEntry = storeEntry; } - } diff --git a/activemq-core/src/main/java/org/apache/activemq/store/kahadaptor/TopicSubAckMarshaller.java b/activemq-core/src/main/java/org/apache/activemq/store/kahadaptor/TopicSubAckMarshaller.java index 30cbda243d..6a6f1444b4 100644 --- a/activemq-core/src/main/java/org/apache/activemq/store/kahadaptor/TopicSubAckMarshaller.java +++ b/activemq-core/src/main/java/org/apache/activemq/store/kahadaptor/TopicSubAckMarshaller.java @@ -22,24 +22,23 @@ import java.io.IOException; import org.apache.activemq.kaha.Marshaller; import org.apache.activemq.kaha.impl.index.IndexItem; - /** * Marshall a TopicSubAck + * * @version $Revision: 1.10 $ */ -public class TopicSubAckMarshaller implements Marshaller{ - +public class TopicSubAckMarshaller implements Marshaller { + + public void writePayload(Object object, DataOutput dataOut) throws IOException { + TopicSubAck tsa = (TopicSubAck)object; + dataOut.writeInt(tsa.getCount()); + IndexItem item = (IndexItem)tsa.getMessageEntry(); + dataOut.writeLong(item.getOffset()); + item.write(dataOut); - public void writePayload(Object object,DataOutput dataOut) throws IOException{ - TopicSubAck tsa = (TopicSubAck) object; - dataOut.writeInt(tsa.getCount()); - IndexItem item = (IndexItem)tsa.getMessageEntry(); - dataOut.writeLong(item.getOffset()); - item.write(dataOut); - } - public Object readPayload(DataInput dataIn) throws IOException{ + public Object readPayload(DataInput dataIn) throws IOException { TopicSubAck tsa = new TopicSubAck(); int count = dataIn.readInt(); tsa.setCount(count); diff --git a/activemq-core/src/main/java/org/apache/activemq/store/kahadaptor/TopicSubContainer.java b/activemq-core/src/main/java/org/apache/activemq/store/kahadaptor/TopicSubContainer.java index ae90b3061c..377272baa7 100644 --- a/activemq-core/src/main/java/org/apache/activemq/store/kahadaptor/TopicSubContainer.java +++ b/activemq-core/src/main/java/org/apache/activemq/store/kahadaptor/TopicSubContainer.java @@ -21,13 +21,13 @@ import java.util.Iterator; /** * Holds information for the subscriber - * + * * @version $Revision: 1.10 $ */ public class TopicSubContainer { private transient ListContainer listContainer; private transient StoreEntry batchEntry; - + public TopicSubContainer(ListContainer container) { this.listContainer = container; } @@ -40,10 +40,10 @@ public class TopicSubContainer { } /** - * @param id + * @param id * @param batchEntry the batchEntry to set */ - public void setBatchEntry(String id,StoreEntry batchEntry) { + public void setBatchEntry(String id, StoreEntry batchEntry) { this.batchEntry = batchEntry; } @@ -59,28 +59,28 @@ public class TopicSubContainer { return listContainer.placeLast(ref); } - public ConsumerMessageRef remove(MessageId id){ - ConsumerMessageRef result=null; - if(!listContainer.isEmpty()){ - StoreEntry entry=listContainer.getFirst(); - while(entry!=null){ - ConsumerMessageRef ref=(ConsumerMessageRef)listContainer.get(entry); + public ConsumerMessageRef remove(MessageId id) { + ConsumerMessageRef result = null; + if (!listContainer.isEmpty()) { + StoreEntry entry = listContainer.getFirst(); + while (entry != null) { + ConsumerMessageRef ref = (ConsumerMessageRef)listContainer.get(entry); listContainer.remove(entry); - if(listContainer!=null&&batchEntry!=null&&(listContainer.isEmpty()||batchEntry.equals(entry))){ + if (listContainer != null && batchEntry != null && (listContainer.isEmpty() || batchEntry.equals(entry))) { reset(); } - if(ref!=null&&ref.getMessageId().equals(id)){ - result=ref; + if (ref != null && ref.getMessageId().equals(id)) { + result = ref; break; } - entry=listContainer.getFirst(); + entry = listContainer.getFirst(); } } return result; } public ConsumerMessageRef get(StoreEntry entry) { - return (ConsumerMessageRef) listContainer.get(entry); + return (ConsumerMessageRef)listContainer.get(entry); } public StoreEntry getEntry() { diff --git a/activemq-core/src/main/java/org/apache/activemq/store/kahadaptor/TransactionMarshaller.java b/activemq-core/src/main/java/org/apache/activemq/store/kahadaptor/TransactionMarshaller.java index 3aea417c89..f75f151d92 100644 --- a/activemq-core/src/main/java/org/apache/activemq/store/kahadaptor/TransactionMarshaller.java +++ b/activemq-core/src/main/java/org/apache/activemq/store/kahadaptor/TransactionMarshaller.java @@ -29,22 +29,24 @@ import org.apache.activemq.wireformat.WireFormat; /** * Marshall a Transaction + * * @version $Revision: 1.10 $ */ -public class TransactionMarshaller implements Marshaller{ - +public class TransactionMarshaller implements Marshaller { + private WireFormat wireFormat; - public TransactionMarshaller(WireFormat wireFormat){ + + public TransactionMarshaller(WireFormat wireFormat) { this.wireFormat = wireFormat; - + } - - public void writePayload(Object object,DataOutput dataOut) throws IOException{ - KahaTransaction kt = (KahaTransaction) object; + + public void writePayload(Object object, DataOutput dataOut) throws IOException { + KahaTransaction kt = (KahaTransaction)object; List list = kt.getList(); dataOut.writeInt(list.size()); - for (int i = 0; i < list.size(); i++){ - TxCommand tx = (TxCommand) list.get(i); + for (int i = 0; i < list.size(); i++) { + TxCommand tx = (TxCommand)list.get(i); Object key = tx.getMessageStoreKey(); ByteSequence packet = wireFormat.marshal(key); dataOut.writeInt(packet.length); @@ -53,31 +55,30 @@ public class TransactionMarshaller implements Marshaller{ packet = wireFormat.marshal(command); dataOut.writeInt(packet.length); dataOut.write(packet.data, packet.offset, packet.length); - - } - } - - public Object readPayload(DataInput dataIn) throws IOException{ + } + } + + public Object readPayload(DataInput dataIn) throws IOException { KahaTransaction result = new KahaTransaction(); List list = new ArrayList(); result.setList(list); - int number=dataIn.readInt(); - for (int i = 0; i < number; i++){ + int number = dataIn.readInt(); + for (int i = 0; i < number; i++) { TxCommand command = new TxCommand(); int size = dataIn.readInt(); - byte[] data=new byte[size]; + byte[] data = new byte[size]; dataIn.readFully(data); - Object key = wireFormat.unmarshal(new ByteSequence(data)); + Object key = wireFormat.unmarshal(new ByteSequence(data)); command.setMessageStoreKey(key); size = dataIn.readInt(); - data=new byte[size]; + data = new byte[size]; dataIn.readFully(data); - BaseCommand bc = (BaseCommand) wireFormat.unmarshal(new ByteSequence(data)); + BaseCommand bc = (BaseCommand)wireFormat.unmarshal(new ByteSequence(data)); command.setCommand(bc); list.add(command); } return result; - + } } diff --git a/activemq-core/src/main/java/org/apache/activemq/store/kahadaptor/TxCommand.java b/activemq-core/src/main/java/org/apache/activemq/store/kahadaptor/TxCommand.java index ebeee9d3c9..b0b126137c 100755 --- a/activemq-core/src/main/java/org/apache/activemq/store/kahadaptor/TxCommand.java +++ b/activemq-core/src/main/java/org/apache/activemq/store/kahadaptor/TxCommand.java @@ -19,58 +19,55 @@ package org.apache.activemq.store.kahadaptor; import org.apache.activemq.command.BaseCommand; import org.apache.activemq.command.CommandTypes; - /** - * Base class for messages/acknowledgements for a transaction + * Base class for messages/acknowledgements for a transaction * * @version $Revision: 1.4 $ */ class TxCommand { - protected Object messageStoreKey; - protected BaseCommand command; + protected Object messageStoreKey; + protected BaseCommand command; - /** - * @return Returns the messageStoreKey. - */ - public Object getMessageStoreKey(){ - return messageStoreKey; - } + /** + * @return Returns the messageStoreKey. + */ + public Object getMessageStoreKey() { + return messageStoreKey; + } - /** - * @param messageStoreKey The messageStoreKey to set. - */ - public void setMessageStoreKey(Object messageStoreKey){ - this.messageStoreKey=messageStoreKey; - } + /** + * @param messageStoreKey The messageStoreKey to set. + */ + public void setMessageStoreKey(Object messageStoreKey) { + this.messageStoreKey = messageStoreKey; + } - /** - * @return Returns the command. - */ - public BaseCommand getCommand(){ - return command; - } + /** + * @return Returns the command. + */ + public BaseCommand getCommand() { + return command; + } - /** - * @param command The command to set. - */ - public void setCommand(BaseCommand command){ - this.command=command; - } - - /** - * @return true if a Message command - */ - public boolean isAdd(){ - return command != null && command.getDataStructureType() != CommandTypes.MESSAGE_ACK; - } - - /** - * @return true if a MessageAck command - */ - public boolean isRemove(){ - return command != null && command.getDataStructureType() == CommandTypes.MESSAGE_ACK; - } + /** + * @param command The command to set. + */ + public void setCommand(BaseCommand command) { + this.command = command; + } + + /** + * @return true if a Message command + */ + public boolean isAdd() { + return command != null && command.getDataStructureType() != CommandTypes.MESSAGE_ACK; + } + + /** + * @return true if a MessageAck command + */ + public boolean isRemove() { + return command != null && command.getDataStructureType() == CommandTypes.MESSAGE_ACK; + } - - } diff --git a/activemq-core/src/main/java/org/apache/activemq/store/memory/MemoryMessageStore.java b/activemq-core/src/main/java/org/apache/activemq/store/memory/MemoryMessageStore.java index a16bb698dd..2aa3cd2c59 100755 --- a/activemq-core/src/main/java/org/apache/activemq/store/memory/MemoryMessageStore.java +++ b/activemq-core/src/main/java/org/apache/activemq/store/memory/MemoryMessageStore.java @@ -31,128 +31,132 @@ import org.apache.activemq.store.MessageRecoveryListener; import org.apache.activemq.store.MessageStore; /** - * An implementation of {@link org.apache.activemq.store.MessageStore} which uses a + * An implementation of {@link org.apache.activemq.store.MessageStore} which + * uses a * * @version $Revision: 1.7 $ */ -public class MemoryMessageStore implements MessageStore{ +public class MemoryMessageStore implements MessageStore { protected final ActiveMQDestination destination; protected final Map messageTable; protected MessageId lastBatchId; - public MemoryMessageStore(ActiveMQDestination destination){ - this(destination,new LinkedHashMap()); + public MemoryMessageStore(ActiveMQDestination destination) { + this(destination, new LinkedHashMap()); } - public MemoryMessageStore(ActiveMQDestination destination,Map messageTable){ - this.destination=destination; - this.messageTable=Collections.synchronizedMap(messageTable); + public MemoryMessageStore(ActiveMQDestination destination, Map messageTable) { + this.destination = destination; + this.messageTable = Collections.synchronizedMap(messageTable); } - public synchronized void addMessage(ConnectionContext context,Message message) throws IOException{ - synchronized(messageTable){ - messageTable.put(message.getMessageId(),message); + public synchronized void addMessage(ConnectionContext context, Message message) throws IOException { + synchronized (messageTable) { + messageTable.put(message.getMessageId(), message); } } -// public void addMessageReference(ConnectionContext context,MessageId messageId,long expirationTime,String messageRef) -// throws IOException{ -// synchronized(messageTable){ -// messageTable.put(messageId,messageRef); -// } -// } + // public void addMessageReference(ConnectionContext context,MessageId + // messageId,long expirationTime,String messageRef) + // throws IOException{ + // synchronized(messageTable){ + // messageTable.put(messageId,messageRef); + // } + // } - public Message getMessage(MessageId identity) throws IOException{ + public Message getMessage(MessageId identity) throws IOException { return (Message)messageTable.get(identity); } -// public String getMessageReference(MessageId identity) throws IOException{ -// return (String)messageTable.get(identity); -// } + // public String getMessageReference(MessageId identity) throws IOException{ + // return (String)messageTable.get(identity); + // } - public void removeMessage(ConnectionContext context,MessageAck ack) throws IOException{ + public void removeMessage(ConnectionContext context, MessageAck ack) throws IOException { removeMessage(ack.getLastMessageId()); } - public void removeMessage(MessageId msgId) throws IOException{ - synchronized(messageTable){ + public void removeMessage(MessageId msgId) throws IOException { + synchronized (messageTable) { messageTable.remove(msgId); - if((lastBatchId!=null && lastBatchId.equals(msgId)) || messageTable.isEmpty()){ - lastBatchId=null; + if ((lastBatchId != null && lastBatchId.equals(msgId)) || messageTable.isEmpty()) { + lastBatchId = null; } } } - public void recover(MessageRecoveryListener listener) throws Exception{ - // the message table is a synchronizedMap - so just have to synchronize here - synchronized(messageTable){ - for(Iterator iter=messageTable.values().iterator();iter.hasNext();){ - Object msg=(Object)iter.next(); - if(msg.getClass()==MessageId.class){ + public void recover(MessageRecoveryListener listener) throws Exception { + // the message table is a synchronizedMap - so just have to synchronize + // here + synchronized (messageTable) { + for (Iterator iter = messageTable.values().iterator(); iter.hasNext();) { + Object msg = (Object)iter.next(); + if (msg.getClass() == MessageId.class) { listener.recoverMessageReference((MessageId)msg); - }else{ + } else { listener.recoverMessage((Message)msg); } } } } - public void start(){ + public void start() { } - public void stop(){ + public void stop() { } - public void removeAllMessages(ConnectionContext context) throws IOException{ - synchronized(messageTable){ + public void removeAllMessages(ConnectionContext context) throws IOException { + synchronized (messageTable) { messageTable.clear(); } } - public ActiveMQDestination getDestination(){ + public ActiveMQDestination getDestination() { return destination; } - public void delete(){ - synchronized(messageTable){ + public void delete() { + synchronized (messageTable) { messageTable.clear(); } } /** - * @param usageManager The UsageManager that is controlling the destination's memory usage. + * @param usageManager The UsageManager that is controlling the + * destination's memory usage. */ - public void setUsageManager(UsageManager usageManager){ + public void setUsageManager(UsageManager usageManager) { } - public int getMessageCount(){ + public int getMessageCount() { return messageTable.size(); } - public void recoverNextMessages(int maxReturned,MessageRecoveryListener listener) throws Exception{ - synchronized(messageTable){ - boolean pastLackBatch=lastBatchId==null; - int count=0; - for(Iterator iter=messageTable.entrySet().iterator();iter.hasNext();){ - Map.Entry entry=(Entry)iter.next(); - if(pastLackBatch){ + public void recoverNextMessages(int maxReturned, MessageRecoveryListener listener) throws Exception { + synchronized (messageTable) { + boolean pastLackBatch = lastBatchId == null; + int count = 0; + for (Iterator iter = messageTable.entrySet().iterator(); iter.hasNext();) { + Map.Entry entry = (Entry)iter.next(); + if (pastLackBatch) { count++; - Object msg=entry.getValue(); - lastBatchId=(MessageId)entry.getKey(); - if(msg.getClass()==MessageId.class){ + Object msg = entry.getValue(); + lastBatchId = (MessageId)entry.getKey(); + if (msg.getClass() == MessageId.class) { listener.recoverMessageReference((MessageId)msg); - }else{ + } else { listener.recoverMessage((Message)msg); } - }else{ - pastLackBatch=entry.getKey().equals(lastBatchId); + } else { + pastLackBatch = entry.getKey().equals(lastBatchId); } } } } - public void resetBatching(){ - lastBatchId=null; + public void resetBatching() { + lastBatchId = null; } } diff --git a/activemq-core/src/main/java/org/apache/activemq/store/memory/MemoryPersistenceAdapter.java b/activemq-core/src/main/java/org/apache/activemq/store/memory/MemoryPersistenceAdapter.java index bc42fe6caf..26112a3d4e 100755 --- a/activemq-core/src/main/java/org/apache/activemq/store/memory/MemoryPersistenceAdapter.java +++ b/activemq-core/src/main/java/org/apache/activemq/store/memory/MemoryPersistenceAdapter.java @@ -37,7 +37,6 @@ import java.util.concurrent.ConcurrentHashMap; /** * @org.apache.xbean.XBean - * * @version $Revision: 1.4 $ */ public class MemoryPersistenceAdapter implements PersistenceAdapter { @@ -47,14 +46,14 @@ public class MemoryPersistenceAdapter implements PersistenceAdapter { ConcurrentHashMap topics = new ConcurrentHashMap(); ConcurrentHashMap queues = new ConcurrentHashMap(); private boolean useExternalMessageReferences; - + public Set getDestinations() { - Set rc = new HashSet(queues.size()+topics.size()); + Set rc = new HashSet(queues.size() + topics.size()); for (Iterator iter = queues.keySet().iterator(); iter.hasNext();) { - rc.add( iter.next() ); + rc.add(iter.next()); } for (Iterator iter = topics.keySet().iterator(); iter.hasNext();) { - rc.add( iter.next() ); + rc.add(iter.next()); } return rc; } @@ -62,12 +61,12 @@ public class MemoryPersistenceAdapter implements PersistenceAdapter { public static MemoryPersistenceAdapter newInstance(File file) { return new MemoryPersistenceAdapter(); } - + public MessageStore createQueueMessageStore(ActiveMQQueue destination) throws IOException { MessageStore rc = (MessageStore)queues.get(destination); - if(rc==null) { + if (rc == null) { rc = new MemoryMessageStore(destination); - if( transactionStore !=null ) { + if (transactionStore != null) { rc = transactionStore.proxy(rc); } queues.put(destination, rc); @@ -77,9 +76,9 @@ public class MemoryPersistenceAdapter implements PersistenceAdapter { public TopicMessageStore createTopicMessageStore(ActiveMQTopic destination) throws IOException { TopicMessageStore rc = (TopicMessageStore)topics.get(destination); - if(rc==null) { + if (rc == null) { rc = new MemoryTopicMessageStore(destination); - if( transactionStore !=null ) { + if (transactionStore != null) { rc = transactionStore.proxy(rc); } topics.put(destination, rc); @@ -88,7 +87,7 @@ public class MemoryPersistenceAdapter implements PersistenceAdapter { } public TransactionStore createTransactionStore() throws IOException { - if( transactionStore==null ) { + if (transactionStore == null) { transactionStore = new MemoryTransactionStore(); } return transactionStore; @@ -108,7 +107,7 @@ public class MemoryPersistenceAdapter implements PersistenceAdapter { public void stop() throws Exception { } - + public long getLastMessageBrokerSequenceId() throws IOException { return 0; } @@ -142,28 +141,29 @@ public class MemoryPersistenceAdapter implements PersistenceAdapter { protected MemoryMessageStore asMemoryMessageStore(Object value) { if (value instanceof MemoryMessageStore) { - return (MemoryMessageStore) value; + return (MemoryMessageStore)value; } log.warn("Expected an instance of MemoryMessageStore but was: " + value); return null; } /** - * @param usageManager The UsageManager that is controlling the broker's memory usage. + * @param usageManager The UsageManager that is controlling the broker's + * memory usage. */ public void setUsageManager(UsageManager usageManager) { } - - public String toString(){ + + public String toString() { return "MemoryPersistenceAdapter"; } - public void setBrokerName(String brokerName){ + public void setBrokerName(String brokerName) { } - public void setDirectory(File dir){ + public void setDirectory(File dir) { } - public void checkpoint(boolean sync) throws IOException{ + public void checkpoint(boolean sync) throws IOException { } } diff --git a/activemq-core/src/main/java/org/apache/activemq/store/memory/MemoryTopicMessageStore.java b/activemq-core/src/main/java/org/apache/activemq/store/memory/MemoryTopicMessageStore.java index d4144697a4..9f9dd3680c 100755 --- a/activemq-core/src/main/java/org/apache/activemq/store/memory/MemoryTopicMessageStore.java +++ b/activemq-core/src/main/java/org/apache/activemq/store/memory/MemoryTopicMessageStore.java @@ -33,104 +33,100 @@ import org.apache.activemq.util.SubscriptionKey; /** * @version $Revision: 1.5 $ */ -public class MemoryTopicMessageStore extends MemoryMessageStore implements TopicMessageStore{ +public class MemoryTopicMessageStore extends MemoryMessageStore implements TopicMessageStore { private Map subscriberDatabase; private Map topicSubMap; - public MemoryTopicMessageStore(ActiveMQDestination destination){ - this(destination,new LRUCache(100,100,0.75f,false),makeMap()); + public MemoryTopicMessageStore(ActiveMQDestination destination) { + this(destination, new LRUCache(100, 100, 0.75f, false), makeMap()); } - protected static Map makeMap(){ + protected static Map makeMap() { return Collections.synchronizedMap(new HashMap()); } - public MemoryTopicMessageStore(ActiveMQDestination destination,Map messageTable,Map subscriberDatabase){ - super(destination,messageTable); - this.subscriberDatabase=subscriberDatabase; - this.topicSubMap=makeMap(); + public MemoryTopicMessageStore(ActiveMQDestination destination, Map messageTable, Map subscriberDatabase) { + super(destination, messageTable); + this.subscriberDatabase = subscriberDatabase; + this.topicSubMap = makeMap(); } - public synchronized void addMessage(ConnectionContext context,Message message) throws IOException{ - super.addMessage(context,message); - for(Iterator i=topicSubMap.values().iterator();i.hasNext();){ - MemoryTopicSub sub=(MemoryTopicSub)i.next(); - sub.addMessage(message.getMessageId(),message); + public synchronized void addMessage(ConnectionContext context, Message message) throws IOException { + super.addMessage(context, message); + for (Iterator i = topicSubMap.values().iterator(); i.hasNext();) { + MemoryTopicSub sub = (MemoryTopicSub)i.next(); + sub.addMessage(message.getMessageId(), message); } } - public synchronized void acknowledge(ConnectionContext context,String clientId,String subscriptionName, - MessageId messageId) throws IOException{ - SubscriptionKey key=new SubscriptionKey(clientId,subscriptionName); - MemoryTopicSub sub=(MemoryTopicSub)topicSubMap.get(key); - if(sub!=null){ + public synchronized void acknowledge(ConnectionContext context, String clientId, String subscriptionName, MessageId messageId) throws IOException { + SubscriptionKey key = new SubscriptionKey(clientId, subscriptionName); + MemoryTopicSub sub = (MemoryTopicSub)topicSubMap.get(key); + if (sub != null) { sub.removeMessage(messageId); } } - public SubscriptionInfo lookupSubscription(String clientId,String subscriptionName) throws IOException{ - return (SubscriptionInfo)subscriberDatabase.get(new SubscriptionKey(clientId,subscriptionName)); + public SubscriptionInfo lookupSubscription(String clientId, String subscriptionName) throws IOException { + return (SubscriptionInfo)subscriberDatabase.get(new SubscriptionKey(clientId, subscriptionName)); } - public synchronized void addSubsciption(SubscriptionInfo info,boolean retroactive) - throws IOException{ - SubscriptionKey key=new SubscriptionKey(info); - MemoryTopicSub sub=new MemoryTopicSub(); - topicSubMap.put(key,sub); - if(retroactive){ - for(Iterator i=messageTable.entrySet().iterator();i.hasNext();){ - Map.Entry entry=(Entry)i.next(); - sub.addMessage((MessageId)entry.getKey(),(Message)entry.getValue()); + public synchronized void addSubsciption(SubscriptionInfo info, boolean retroactive) throws IOException { + SubscriptionKey key = new SubscriptionKey(info); + MemoryTopicSub sub = new MemoryTopicSub(); + topicSubMap.put(key, sub); + if (retroactive) { + for (Iterator i = messageTable.entrySet().iterator(); i.hasNext();) { + Map.Entry entry = (Entry)i.next(); + sub.addMessage((MessageId)entry.getKey(), (Message)entry.getValue()); } } - subscriberDatabase.put(key,info); + subscriberDatabase.put(key, info); } - public void deleteSubscription(String clientId,String subscriptionName){ - org.apache.activemq.util.SubscriptionKey key=new SubscriptionKey(clientId,subscriptionName); + public void deleteSubscription(String clientId, String subscriptionName) { + org.apache.activemq.util.SubscriptionKey key = new SubscriptionKey(clientId, subscriptionName); subscriberDatabase.remove(key); topicSubMap.remove(key); } - public void recoverSubscription(String clientId,String subscriptionName,MessageRecoveryListener listener) - throws Exception{ - MemoryTopicSub sub=(MemoryTopicSub)topicSubMap.get(new SubscriptionKey(clientId,subscriptionName)); - if(sub!=null){ + public void recoverSubscription(String clientId, String subscriptionName, MessageRecoveryListener listener) throws Exception { + MemoryTopicSub sub = (MemoryTopicSub)topicSubMap.get(new SubscriptionKey(clientId, subscriptionName)); + if (sub != null) { sub.recoverSubscription(listener); } } - public void delete(){ + public void delete() { super.delete(); subscriberDatabase.clear(); topicSubMap.clear(); } - public SubscriptionInfo[] getAllSubscriptions() throws IOException{ + public SubscriptionInfo[] getAllSubscriptions() throws IOException { return (SubscriptionInfo[])subscriberDatabase.values().toArray(new SubscriptionInfo[subscriberDatabase.size()]); } - public synchronized int getMessageCount(String clientId,String subscriberName) throws IOException{ - int result=0; - MemoryTopicSub sub=(MemoryTopicSub)topicSubMap.get(new SubscriptionKey(clientId,subscriberName)); - if(sub!=null){ - result=sub.size(); + public synchronized int getMessageCount(String clientId, String subscriberName) throws IOException { + int result = 0; + MemoryTopicSub sub = (MemoryTopicSub)topicSubMap.get(new SubscriptionKey(clientId, subscriberName)); + if (sub != null) { + result = sub.size(); } return result; } - public void recoverNextMessages(String clientId,String subscriptionName,int maxReturned, - MessageRecoveryListener listener) throws Exception{ - MemoryTopicSub sub=(MemoryTopicSub)topicSubMap.get(new SubscriptionKey(clientId,subscriptionName)); - if(sub!=null){ - sub.recoverNextMessages(maxReturned,listener); + public void recoverNextMessages(String clientId, String subscriptionName, int maxReturned, MessageRecoveryListener listener) throws Exception { + MemoryTopicSub sub = (MemoryTopicSub)topicSubMap.get(new SubscriptionKey(clientId, subscriptionName)); + if (sub != null) { + sub.recoverNextMessages(maxReturned, listener); } } - public void resetBatching(String clientId,String subscriptionName){ - MemoryTopicSub sub=(MemoryTopicSub)topicSubMap.get(new SubscriptionKey(clientId,subscriptionName)); - if(sub!=null){ + public void resetBatching(String clientId, String subscriptionName) { + MemoryTopicSub sub = (MemoryTopicSub)topicSubMap.get(new SubscriptionKey(clientId, subscriptionName)); + if (sub != null) { sub.resetBatching(); } } diff --git a/activemq-core/src/main/java/org/apache/activemq/store/memory/MemoryTopicSub.java b/activemq-core/src/main/java/org/apache/activemq/store/memory/MemoryTopicSub.java index 1616eb4993..df5ba42583 100755 --- a/activemq-core/src/main/java/org/apache/activemq/store/memory/MemoryTopicSub.java +++ b/activemq-core/src/main/java/org/apache/activemq/store/memory/MemoryTopicSub.java @@ -27,65 +27,66 @@ import org.apache.activemq.store.MessageRecoveryListener; * * @version $Revision: 1.7 $ */ -class MemoryTopicSub{ +class MemoryTopicSub { - private Map map=new LinkedHashMap(); + private Map map = new LinkedHashMap(); private MessageId lastBatch; - void addMessage(MessageId id,Message message){ - map.put(id,message); + void addMessage(MessageId id, Message message) { + map.put(id, message); } - void removeMessage(MessageId id){ + void removeMessage(MessageId id) { map.remove(id); if (map.isEmpty()) { - lastBatch=null; + lastBatch = null; } } - int size(){ + int size() { return map.size(); } - void recoverSubscription(MessageRecoveryListener listener) throws Exception{ - for(Iterator iter=map.entrySet().iterator();iter.hasNext();){ - Map.Entry entry=(Entry)iter.next(); - Object msg=entry.getValue(); - if(msg.getClass()==MessageId.class){ + void recoverSubscription(MessageRecoveryListener listener) throws Exception { + for (Iterator iter = map.entrySet().iterator(); iter.hasNext();) { + Map.Entry entry = (Entry)iter.next(); + Object msg = entry.getValue(); + if (msg.getClass() == MessageId.class) { listener.recoverMessageReference((MessageId)msg); - }else{ + } else { listener.recoverMessage((Message)msg); } } } - void recoverNextMessages(int maxReturned,MessageRecoveryListener listener) throws Exception{ - boolean pastLackBatch=lastBatch==null; - MessageId lastId=null; - // the message table is a synchronizedMap - so just have to synchronize here - int count=0; - for(Iterator iter=map.entrySet().iterator();iter.hasNext()&&count 0 || !on) { - mutex.wait(); - } - on=false; - mutex.notifyAll(); - } finally { - --turningOff; - } - } + synchronized (mutex) { + try { + ++turningOff; + while (usage > 0 || !on) { + mutex.wait(); + } + on = false; + mutex.notifyAll(); + } finally { + --turningOff; + } + } } - + /** - * Increments the use counter of the valve. This method blocks if the valve is off, - * or is being turned off. + * Increments the use counter of the valve. This method blocks if the valve + * is off, or is being turned off. * * @throws InterruptedException */ public void increment() throws InterruptedException { - synchronized(mutex) { + synchronized (mutex) { // Do we have to wait for the value to be on? - while( turningOff>0 || !on ) { + while (turningOff > 0 || !on) { mutex.wait(); } usage++; - } + } } - + /** * Decrements the use counter of the valve. */ public void decrement() { - synchronized(mutex) { + synchronized (mutex) { usage--; - if( turningOff>0 && usage < 1 ) { + if (turningOff > 0 && usage < 1) { mutex.notifyAll(); } - } + } } - + } diff --git a/activemq-core/src/main/java/org/apache/activemq/transaction/Synchronization.java b/activemq-core/src/main/java/org/apache/activemq/transaction/Synchronization.java index 338fe43cc4..35a5b24dc2 100755 --- a/activemq-core/src/main/java/org/apache/activemq/transaction/Synchronization.java +++ b/activemq-core/src/main/java/org/apache/activemq/transaction/Synchronization.java @@ -17,13 +17,17 @@ package org.apache.activemq.transaction; /** - * * @version $Revision$ */ public class Synchronization { - public void beforeEnd() throws Exception{} - public void afterCommit() throws Exception{} - public void afterRollback() throws Exception{} - + public void beforeEnd() throws Exception { + } + + public void afterCommit() throws Exception { + } + + public void afterRollback() throws Exception { + } + } diff --git a/activemq-core/src/main/java/org/apache/activemq/transaction/Transaction.java b/activemq-core/src/main/java/org/apache/activemq/transaction/Transaction.java index fba4d46039..5460483061 100755 --- a/activemq-core/src/main/java/org/apache/activemq/transaction/Transaction.java +++ b/activemq-core/src/main/java/org/apache/activemq/transaction/Transaction.java @@ -25,16 +25,16 @@ import javax.transaction.xa.XAException; import org.apache.activemq.command.TransactionId; /** - * Keeps track of all the actions the need to be done when - * a transaction does a commit or rollback. - * + * Keeps track of all the actions the need to be done when a transaction does a + * commit or rollback. + * * @version $Revision: 1.5 $ */ public abstract class Transaction { - static final public byte START_STATE = 0; // can go to: 1,2,3 - static final public byte IN_USE_STATE = 1; // can go to: 2,3 - static final public byte PREPARED_STATE = 2; // can go to: 3 + static final public byte START_STATE = 0; // can go to: 1,2,3 + static final public byte IN_USE_STATE = 1; // can go to: 2,3 + static final public byte PREPARED_STATE = 2; // can go to: 3 static final public byte FINISHED_STATE = 3; private ArrayList synchronizations = new ArrayList(); @@ -54,7 +54,7 @@ public abstract class Transaction { state = IN_USE_STATE; } } - + public void removeSynchronization(Synchronization r) { synchronizations.remove(r); } @@ -64,47 +64,49 @@ public abstract class Transaction { // Is it ok to call prepare now given the state of the // transaction? switch (state) { - case START_STATE: - case IN_USE_STATE: - break; - default: - XAException xae = new XAException("Prepare cannot be called now."); - xae.errorCode = XAException.XAER_PROTO; - throw xae; + case START_STATE: + case IN_USE_STATE: + break; + default: + XAException xae = new XAException("Prepare cannot be called now."); + xae.errorCode = XAException.XAER_PROTO; + throw xae; } -// // Run the prePrepareTasks -// for (Iterator iter = prePrepareTasks.iterator(); iter.hasNext();) { -// Callback r = (Callback) iter.next(); -// r.execute(); -// } + // // Run the prePrepareTasks + // for (Iterator iter = prePrepareTasks.iterator(); iter.hasNext();) { + // Callback r = (Callback) iter.next(); + // r.execute(); + // } } protected void fireAfterCommit() throws Exception { for (Iterator iter = synchronizations.iterator(); iter.hasNext();) { - Synchronization s = (Synchronization) iter.next(); + Synchronization s = (Synchronization)iter.next(); s.afterCommit(); } } public void fireAfterRollback() throws Exception { for (Iterator iter = synchronizations.iterator(); iter.hasNext();) { - Synchronization s = (Synchronization) iter.next(); + Synchronization s = (Synchronization)iter.next(); s.afterRollback(); } } public String toString() { - return super.toString() + "[synchronizations=" + synchronizations +"]"; + return super.toString() + "[synchronizations=" + synchronizations + "]"; } abstract public void commit(boolean onePhase) throws XAException, IOException; + abstract public void rollback() throws XAException, IOException; + abstract public int prepare() throws XAException, IOException; - + abstract public TransactionId getTransactionId(); public boolean isPrepared() { - return getState()==PREPARED_STATE; + return getState() == PREPARED_STATE; } } diff --git a/activemq-core/src/main/java/org/apache/activemq/transaction/XATransaction.java b/activemq-core/src/main/java/org/apache/activemq/transaction/XATransaction.java index b0a5292b55..9ae0f0f889 100755 --- a/activemq-core/src/main/java/org/apache/activemq/transaction/XATransaction.java +++ b/activemq-core/src/main/java/org/apache/activemq/transaction/XATransaction.java @@ -32,9 +32,9 @@ import org.apache.commons.logging.LogFactory; * @version $Revision: 1.4 $ */ public class XATransaction extends Transaction { - + private static final Log log = LogFactory.getLog(XATransaction.class); - + private final TransactionStore transactionStore; private final XATransactionId xid; private final TransactionBroker broker; @@ -46,32 +46,32 @@ public class XATransaction extends Transaction { } public void commit(boolean onePhase) throws XAException, IOException { - if(log.isDebugEnabled()) - log.debug("XA Transaction commit: "+xid); + if (log.isDebugEnabled()) + log.debug("XA Transaction commit: " + xid); switch (getState()) { - case START_STATE: - // 1 phase commit, no work done. - checkForPreparedState(onePhase); - setStateFinished(); - break; - case IN_USE_STATE: - // 1 phase commit, work done. - checkForPreparedState(onePhase); - doPrePrepare(); - setStateFinished(); - transactionStore.commit(getTransactionId(), false); - doPostCommit(); - break; - case PREPARED_STATE: - // 2 phase commit, work done. - // We would record commit here. - setStateFinished(); - transactionStore.commit(getTransactionId(), true); - doPostCommit(); - break; - default: - illegalStateTransition("commit"); + case START_STATE: + // 1 phase commit, no work done. + checkForPreparedState(onePhase); + setStateFinished(); + break; + case IN_USE_STATE: + // 1 phase commit, work done. + checkForPreparedState(onePhase); + doPrePrepare(); + setStateFinished(); + transactionStore.commit(getTransactionId(), false); + doPostCommit(); + break; + case PREPARED_STATE: + // 2 phase commit, work done. + // We would record commit here. + setStateFinished(); + transactionStore.commit(getTransactionId(), true); + doPostCommit(); + break; + default: + illegalStateTransition("commit"); } } @@ -107,9 +107,8 @@ public class XATransaction extends Transaction { private void doPostCommit() throws XAException { try { fireAfterCommit(); - } - catch (Throwable e) { - // I guess this could happen. Post commit task failed + } catch (Throwable e) { + // I guess this could happen. Post commit task failed // to execute properly. log.warn("POST COMMIT FAILED: ", e); XAException xae = new XAException("POST COMMIT FAILED"); @@ -120,27 +119,27 @@ public class XATransaction extends Transaction { } public void rollback() throws XAException, IOException { - - if(log.isDebugEnabled()) - log.debug("XA Transaction rollback: "+xid); + + if (log.isDebugEnabled()) + log.debug("XA Transaction rollback: " + xid); switch (getState()) { - case START_STATE: - // 1 phase rollback no work done. - setStateFinished(); - break; - case IN_USE_STATE: - // 1 phase rollback work done. - setStateFinished(); - transactionStore.rollback(getTransactionId()); - doPostRollback(); - break; - case PREPARED_STATE: - // 2 phase rollback work done. - setStateFinished(); - transactionStore.rollback(getTransactionId()); - doPostRollback(); - break; + case START_STATE: + // 1 phase rollback no work done. + setStateFinished(); + break; + case IN_USE_STATE: + // 1 phase rollback work done. + setStateFinished(); + transactionStore.rollback(getTransactionId()); + doPostRollback(); + break; + case PREPARED_STATE: + // 2 phase rollback work done. + setStateFinished(); + transactionStore.rollback(getTransactionId()); + doPostRollback(); + break; } } @@ -148,9 +147,8 @@ public class XATransaction extends Transaction { private void doPostRollback() throws XAException { try { fireAfterRollback(); - } - catch (Throwable e) { - // I guess this could happen. Post commit task failed + } catch (Throwable e) { + // I guess this could happen. Post commit task failed // to execute properly. log.warn("POST ROLLBACK FAILED: ", e); XAException xae = new XAException("POST ROLLBACK FAILED"); @@ -161,23 +159,23 @@ public class XATransaction extends Transaction { } public int prepare() throws XAException, IOException { - if(log.isDebugEnabled()) - log.debug("XA Transaction prepare: "+xid); - + if (log.isDebugEnabled()) + log.debug("XA Transaction prepare: " + xid); + switch (getState()) { - case START_STATE: - // No work done.. no commit/rollback needed. - setStateFinished(); - return XAResource.XA_RDONLY; - case IN_USE_STATE: - // We would record prepare here. - doPrePrepare(); - setState(Transaction.PREPARED_STATE); - transactionStore.prepare(getTransactionId()); - return XAResource.XA_OK; - default : - illegalStateTransition("prepare"); - return XAResource.XA_RDONLY; + case START_STATE: + // No work done.. no commit/rollback needed. + setStateFinished(); + return XAResource.XA_RDONLY; + case IN_USE_STATE: + // We would record prepare here. + doPrePrepare(); + setState(Transaction.PREPARED_STATE); + transactionStore.prepare(getTransactionId()); + return XAResource.XA_OK; + default: + illegalStateTransition("prepare"); + return XAResource.XA_RDONLY; } } diff --git a/activemq-core/src/main/java/org/apache/activemq/transport/FutureResponse.java b/activemq-core/src/main/java/org/apache/activemq/transport/FutureResponse.java index 642427f061..413f842513 100755 --- a/activemq-core/src/main/java/org/apache/activemq/transport/FutureResponse.java +++ b/activemq-core/src/main/java/org/apache/activemq/transport/FutureResponse.java @@ -28,19 +28,18 @@ import java.util.concurrent.TimeUnit; public class FutureResponse { private static final Log log = LogFactory.getLog(FutureResponse.class); - + private final ResponseCallback responseCallback; private final ArrayBlockingQueue responseSlot = new ArrayBlockingQueue(1); - + public FutureResponse(ResponseCallback responseCallback) { this.responseCallback = responseCallback; } public Response getResult() throws IOException { try { - return (Response) responseSlot.take(); - } - catch (InterruptedException e) { + return (Response)responseSlot.take(); + } catch (InterruptedException e) { Thread.currentThread().interrupt(); if (log.isDebugEnabled()) { log.debug("Operation interupted: " + e, e); @@ -48,20 +47,20 @@ public class FutureResponse { throw new InterruptedIOException("Interrupted."); } } - + public Response getResult(int timeout) throws IOException { try { - return (Response) responseSlot.poll(timeout,TimeUnit.MILLISECONDS); + return (Response)responseSlot.poll(timeout, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { throw new InterruptedIOException("Interrupted."); } } - + public void set(Response result) { - if( responseSlot.offer(result) ) { - if( responseCallback !=null ) { + if (responseSlot.offer(result)) { + if (responseCallback != null) { responseCallback.onCompletion(this); - } + } } } } diff --git a/activemq-core/src/main/java/org/apache/activemq/transport/InactivityMonitor.java b/activemq-core/src/main/java/org/apache/activemq/transport/InactivityMonitor.java index 77bd817c4f..48bb7184af 100755 --- a/activemq-core/src/main/java/org/apache/activemq/transport/InactivityMonitor.java +++ b/activemq-core/src/main/java/org/apache/activemq/transport/InactivityMonitor.java @@ -26,23 +26,24 @@ import java.io.IOException; import java.util.concurrent.atomic.AtomicBoolean; /** - * Used to make sure that commands are arriving periodically from the peer of the transport. - * + * Used to make sure that commands are arriving periodically from the peer of + * the transport. + * * @version $Revision$ */ public class InactivityMonitor extends TransportFilter { - private final Log log = LogFactory.getLog(InactivityMonitor.class); + private final Log LOG = LogFactory.getLog(InactivityMonitor.class); private WireFormatInfo localWireFormatInfo; private WireFormatInfo remoteWireFormatInfo; - private final AtomicBoolean monitorStarted= new AtomicBoolean(false); + private final AtomicBoolean monitorStarted = new AtomicBoolean(false); - private final AtomicBoolean commandSent=new AtomicBoolean(false); - private final AtomicBoolean inSend=new AtomicBoolean(false); + private final AtomicBoolean commandSent = new AtomicBoolean(false); + private final AtomicBoolean inSend = new AtomicBoolean(false); - private final AtomicBoolean commandReceived=new AtomicBoolean(true); - private final AtomicBoolean inReceive=new AtomicBoolean(false); + private final AtomicBoolean commandReceived = new AtomicBoolean(true); + private final AtomicBoolean inReceive = new AtomicBoolean(false); private final Runnable readChecker = new Runnable() { public void run() { @@ -56,7 +57,6 @@ public class InactivityMonitor extends TransportFilter { } }; - public InactivityMonitor(Transport next) { super(next); } @@ -66,23 +66,22 @@ public class InactivityMonitor extends TransportFilter { next.stop(); } - final void writeCheck() { - synchronized(writeChecker) { - if( inSend.get() ) { - log.trace("A send is in progress"); + synchronized (writeChecker) { + if (inSend.get()) { + LOG.trace("A send is in progress"); return; } - if( !commandSent.get() ) { - log.trace("No message sent since last write check, sending a KeepAliveInfo"); + if (!commandSent.get()) { + LOG.trace("No message sent since last write check, sending a KeepAliveInfo"); try { next.oneway(new KeepAliveInfo()); } catch (IOException e) { onException(e); } } else { - log.trace("Message sent since last write check, resetting flag"); + LOG.trace("Message sent since last write check, resetting flag"); } commandSent.set(false); @@ -90,17 +89,17 @@ public class InactivityMonitor extends TransportFilter { } final void readCheck() { - synchronized(readChecker) { - if( inReceive.get() ) { - log.trace("A receive is in progress"); + synchronized (readChecker) { + if (inReceive.get()) { + LOG.trace("A receive is in progress"); return; } - if( !commandReceived.get() ) { - log.debug("No message received since last read check for " + toString() + "! Throwing InactivityIOException."); + if (!commandReceived.get()) { + LOG.debug("No message received since last read check for " + toString() + "! Throwing InactivityIOException."); onException(new InactivityIOException("Channel was inactive for too long.")); } else { - log.trace("Message received since last read check, resetting flag: "); + LOG.trace("Message received since last read check, resetting flag: "); } commandReceived.set(false); @@ -109,12 +108,12 @@ public class InactivityMonitor extends TransportFilter { } public void onCommand(Object command) { - synchronized(readChecker) { + synchronized (readChecker) { inReceive.set(true); try { - if( command.getClass() == WireFormatInfo.class ) { - synchronized( this ) { - remoteWireFormatInfo = (WireFormatInfo) command; + if (command.getClass() == WireFormatInfo.class) { + synchronized (this) { + remoteWireFormatInfo = (WireFormatInfo)command; try { startMonitorThreads(); } catch (IOException e) { @@ -130,16 +129,15 @@ public class InactivityMonitor extends TransportFilter { } } - public void oneway(Object o) throws IOException { - synchronized(writeChecker) { + synchronized (writeChecker) { // Disable inactivity monitoring while processing a command. inSend.set(true); commandSent.set(true); try { - if( o.getClass() == WireFormatInfo.class ) { - synchronized( this ) { - localWireFormatInfo = (WireFormatInfo) o; + if (o.getClass() == WireFormatInfo.class) { + synchronized (this) { + localWireFormatInfo = (WireFormatInfo)o; startMonitorThreads(); } } @@ -151,25 +149,24 @@ public class InactivityMonitor extends TransportFilter { } public void onException(IOException error) { - if( monitorStarted.get() ) { - stopMonitorThreads(); - } + if (monitorStarted.get()) { + stopMonitorThreads(); + } getTransportListener().onException(error); } - synchronized private void startMonitorThreads() throws IOException { - if( monitorStarted.get() ) + if (monitorStarted.get()) return; - if( localWireFormatInfo == null ) + if (localWireFormatInfo == null) return; - if( remoteWireFormatInfo == null ) + if (remoteWireFormatInfo == null) return; long l = Math.min(localWireFormatInfo.getMaxInactivityDuration(), remoteWireFormatInfo.getMaxInactivityDuration()); - if( l > 0 ) { + if (l > 0) { monitorStarted.set(true); - Scheduler.executePeriodically(writeChecker, l/2); + Scheduler.executePeriodically(writeChecker, l / 2); Scheduler.executePeriodically(readChecker, l); } } @@ -178,11 +175,10 @@ public class InactivityMonitor extends TransportFilter { * */ synchronized private void stopMonitorThreads() { - if( monitorStarted.compareAndSet(true, false) ) { + if (monitorStarted.compareAndSet(true, false)) { Scheduler.cancel(readChecker); Scheduler.cancel(writeChecker); } } - } diff --git a/activemq-core/src/main/java/org/apache/activemq/transport/MutexTransport.java b/activemq-core/src/main/java/org/apache/activemq/transport/MutexTransport.java index 09c2289f92..f3b1c2166f 100755 --- a/activemq-core/src/main/java/org/apache/activemq/transport/MutexTransport.java +++ b/activemq-core/src/main/java/org/apache/activemq/transport/MutexTransport.java @@ -19,45 +19,43 @@ package org.apache.activemq.transport; import java.io.IOException; import org.apache.activemq.command.ShutdownInfo; - - /** * @version $Revision$ */ public class MutexTransport extends TransportFilter { private final Object writeMutex = new Object(); - + public MutexTransport(Transport next) { super(next); } public FutureResponse asyncRequest(Object command, ResponseCallback responseCallback) throws IOException { - synchronized(writeMutex) { + synchronized (writeMutex) { return next.asyncRequest(command, null); } } - public void oneway(Object command) throws IOException{ - synchronized(writeMutex){ + public void oneway(Object command) throws IOException { + synchronized (writeMutex) { next.oneway(command); } } public Object request(Object command) throws IOException { - synchronized(writeMutex) { + synchronized (writeMutex) { return next.request(command); } } - - public Object request(Object command,int timeout) throws IOException { - synchronized(writeMutex){ - return next.request(command,timeout); + + public Object request(Object command, int timeout) throws IOException { + synchronized (writeMutex) { + return next.request(command, timeout); } } - + public String toString() { return next.toString(); } - + } diff --git a/activemq-core/src/main/java/org/apache/activemq/transport/ResponseCorrelator.java b/activemq-core/src/main/java/org/apache/activemq/transport/ResponseCorrelator.java index 6644ed08c8..6a15ad4c7a 100755 --- a/activemq-core/src/main/java/org/apache/activemq/transport/ResponseCorrelator.java +++ b/activemq-core/src/main/java/org/apache/activemq/transport/ResponseCorrelator.java @@ -28,95 +28,96 @@ import org.apache.commons.logging.LogFactory; import java.util.concurrent.ConcurrentHashMap; /** - * Adds the incrementing sequence number to commands along with performing the corelation of responses to requests to - * create a blocking request-response semantics. + * Adds the incrementing sequence number to commands along with performing the + * corelation of responses to requests to create a blocking request-response + * semantics. * * @version $Revision: 1.4 $ */ -public class ResponseCorrelator extends TransportFilter{ +public class ResponseCorrelator extends TransportFilter { - private static final Log log=LogFactory.getLog(ResponseCorrelator.class); - private final Map requestMap=new HashMap(); + private static final Log LOG = LogFactory.getLog(ResponseCorrelator.class); + private final Map requestMap = new HashMap(); private IntSequenceGenerator sequenceGenerator; - private final boolean debug=log.isDebugEnabled(); + private final boolean debug = LOG.isDebugEnabled(); - public ResponseCorrelator(Transport next){ - this(next,new IntSequenceGenerator()); + public ResponseCorrelator(Transport next) { + this(next, new IntSequenceGenerator()); } - public ResponseCorrelator(Transport next,IntSequenceGenerator sequenceGenerator){ + public ResponseCorrelator(Transport next, IntSequenceGenerator sequenceGenerator) { super(next); - this.sequenceGenerator=sequenceGenerator; + this.sequenceGenerator = sequenceGenerator; } - public void oneway(Object o) throws IOException{ - Command command=(Command)o; + public void oneway(Object o) throws IOException { + Command command = (Command)o; command.setCommandId(sequenceGenerator.getNextSequenceId()); command.setResponseRequired(false); next.oneway(command); } - public FutureResponse asyncRequest(Object o,ResponseCallback responseCallback) throws IOException{ - Command command=(Command)o; + public FutureResponse asyncRequest(Object o, ResponseCallback responseCallback) throws IOException { + Command command = (Command)o; command.setCommandId(sequenceGenerator.getNextSequenceId()); command.setResponseRequired(true); - FutureResponse future=new FutureResponse(responseCallback); - synchronized(requestMap){ - requestMap.put(new Integer(command.getCommandId()),future); + FutureResponse future = new FutureResponse(responseCallback); + synchronized (requestMap) { + requestMap.put(new Integer(command.getCommandId()), future); } next.oneway(command); return future; } - public Object request(Object command) throws IOException{ - FutureResponse response=asyncRequest(command,null); + public Object request(Object command) throws IOException { + FutureResponse response = asyncRequest(command, null); return response.getResult(); } - public Object request(Object command,int timeout) throws IOException{ - FutureResponse response=asyncRequest(command,null); + public Object request(Object command, int timeout) throws IOException { + FutureResponse response = asyncRequest(command, null); return response.getResult(timeout); } - public void onCommand(Object o){ - Command command=(Command)o; - if(command.isResponse()){ - Response response=(Response)command; - FutureResponse future=null; - synchronized(requestMap){ - future=(FutureResponse)requestMap.remove(Integer.valueOf(response.getCorrelationId())); + public void onCommand(Object o) { + Command command = (Command)o; + if (command.isResponse()) { + Response response = (Response)command; + FutureResponse future = null; + synchronized (requestMap) { + future = (FutureResponse)requestMap.remove(Integer.valueOf(response.getCorrelationId())); } - if(future!=null){ + if (future != null) { future.set(response); - }else{ - if(debug) - log.debug("Received unexpected response for command id: "+response.getCorrelationId()); + } else { + if (debug) + LOG.debug("Received unexpected response for command id: " + response.getCorrelationId()); } - }else{ + } else { getTransportListener().onCommand(command); } } /** - * If an async exception occurs, then assume no responses will arrive for any of current requests. Lets let them - * know of the problem. + * If an async exception occurs, then assume no responses will arrive for + * any of current requests. Lets let them know of the problem. */ - public void onException(IOException error){ + public void onException(IOException error) { // Copy and Clear the request Map - ArrayList requests=new ArrayList(requestMap.values()); + ArrayList requests = new ArrayList(requestMap.values()); requestMap.clear(); - for(Iterator iter=requests.iterator();iter.hasNext();){ - FutureResponse fr=(FutureResponse)iter.next(); + for (Iterator iter = requests.iterator(); iter.hasNext();) { + FutureResponse fr = (FutureResponse)iter.next(); fr.set(new ExceptionResponse(error)); } super.onException(error); } - public IntSequenceGenerator getSequenceGenerator(){ + public IntSequenceGenerator getSequenceGenerator() { return sequenceGenerator; } - public String toString(){ + public String toString() { return next.toString(); } } diff --git a/activemq-core/src/main/java/org/apache/activemq/transport/Transport.java b/activemq-core/src/main/java/org/apache/activemq/transport/Transport.java index 468378c0ce..eb62663723 100755 --- a/activemq-core/src/main/java/org/apache/activemq/transport/Transport.java +++ b/activemq-core/src/main/java/org/apache/activemq/transport/Transport.java @@ -16,103 +16,108 @@ */ package org.apache.activemq.transport; -import org.apache.activemq.Service; - import java.io.IOException; +import org.apache.activemq.Service; + /** - * Represents the client side of a transport allowing messages - * to be sent synchronously, asynchronously and consumed. - * + * Represents the client side of a transport allowing messages to be sent + * synchronously, asynchronously and consumed. + * * @version $Revision: 1.5 $ */ public interface Transport extends Service { /** * A one way asynchronous send - * @param command - * @throws IOException + * + * @param command + * @throws IOException */ public void oneway(Object command) throws IOException; /** - * An asynchronous request response where the Receipt will be returned - * in the future. If responseCallback is not null, then it will be called - * when the response has been completed. + * An asynchronous request response where the Receipt will be returned in + * the future. If responseCallback is not null, then it will be called when + * the response has been completed. * - * @param command + * @param command * @param responseCallback TODO * @return the FutureResponse - * @throws IOException + * @throws IOException */ public FutureResponse asyncRequest(Object command, ResponseCallback responseCallback) throws IOException; - + /** * A synchronous request response - * @param command + * + * @param command * @return the response - * @throws IOException + * @throws IOException */ public Object request(Object command) throws IOException; /** * A synchronous request response - * @param command - * @param timeout + * + * @param command + * @param timeout * @return the repsonse or null if timeout - * @throws IOException + * @throws IOException */ public Object request(Object command, int timeout) throws IOException; - -// /** -// * A one way asynchronous send -// * @param command -// * @throws IOException -// */ -// public void oneway(Command command) throws IOException; -// -// /** -// * An asynchronous request response where the Receipt will be returned -// * in the future. If responseCallback is not null, then it will be called -// * when the response has been completed. -// * -// * @param command -// * @param responseCallback TODO -// * @return the FutureResponse -// * @throws IOException -// */ -// public FutureResponse asyncRequest(Command command, ResponseCallback responseCallback) throws IOException; -// -// /** -// * A synchronous request response -// * @param command -// * @return the response -// * @throws IOException -// */ -// public Response request(Command command) throws IOException; -// -// /** -// * A synchronous request response -// * @param command -// * @param timeout -// * @return the repsonse or null if timeout -// * @throws IOException -// */ -// public Response request(Command command, int timeout) throws IOException; - + // /** + // * A one way asynchronous send + // * @param command + // * @throws IOException + // */ + // public void oneway(Command command) throws IOException; + // + // /** + // * An asynchronous request response where the Receipt will be returned + // * in the future. If responseCallback is not null, then it will be called + // * when the response has been completed. + // * + // * @param command + // * @param responseCallback TODO + // * @return the FutureResponse + // * @throws IOException + // */ + // public FutureResponse asyncRequest(Command command, ResponseCallback + // responseCallback) throws IOException; + // + // /** + // * A synchronous request response + // * @param command + // * @return the response + // * @throws IOException + // */ + // public Response request(Command command) throws IOException; + // + // /** + // * A synchronous request response + // * @param command + // * @param timeout + // * @return the repsonse or null if timeout + // * @throws IOException + // */ + // public Response request(Command command, int timeout) throws IOException; + /** * Returns the current transport listener - * @return + * + * @return */ public TransportListener getTransportListener(); /** * Registers an inbound command listener - * @param commandListener + * + * @param commandListener */ public void setTransportListener(TransportListener commandListener); - + /** * @param target * @return the target @@ -121,12 +126,12 @@ public interface Transport extends Service { /** * @return the remote address for this connection - * */ - public String getRemoteAddress(); - + public String getRemoteAddress(); + /** * Indicates if the transport can handle faults + * * @return tru if fault tolerant */ public boolean isFaultTolerant(); diff --git a/activemq-core/src/main/java/org/apache/activemq/transport/TransportDisposedIOException.java b/activemq-core/src/main/java/org/apache/activemq/transport/TransportDisposedIOException.java index f6171e63bd..15f8dea589 100644 --- a/activemq-core/src/main/java/org/apache/activemq/transport/TransportDisposedIOException.java +++ b/activemq-core/src/main/java/org/apache/activemq/transport/TransportDisposedIOException.java @@ -25,7 +25,7 @@ import java.io.IOException; */ public class TransportDisposedIOException extends IOException { - private static final long serialVersionUID=-7107323414439622596L; + private static final long serialVersionUID = -7107323414439622596L; public TransportDisposedIOException() { super(); @@ -38,5 +38,4 @@ public class TransportDisposedIOException extends IOException { super(message); } - } diff --git a/activemq-core/src/main/java/org/apache/activemq/transport/TransportFactory.java b/activemq-core/src/main/java/org/apache/activemq/transport/TransportFactory.java index 2d3e4eb489..8f4510b229 100755 --- a/activemq-core/src/main/java/org/apache/activemq/transport/TransportFactory.java +++ b/activemq-core/src/main/java/org/apache/activemq/transport/TransportFactory.java @@ -118,8 +118,7 @@ public abstract class TransportFactory { throw new IllegalArgumentException("Invalid connect parameters: " + options); } return rc; - } - catch (URISyntaxException e) { + } catch (URISyntaxException e) { throw IOExceptionSupport.create(e); } } @@ -135,16 +134,16 @@ public abstract class TransportFactory { } return rc; - } - catch (URISyntaxException e) { + } catch (URISyntaxException e) { throw IOExceptionSupport.create(e); } } /** * Factory method to create a new transport - * @throws IOException - * @throws UnknownHostException + * + * @throws IOException + * @throws UnknownHostException */ protected Transport createTransport(URI location, WireFormat wf) throws MalformedURLException, UnknownHostException, IOException { throw new IOException("createTransport() method not implemented!"); @@ -157,16 +156,15 @@ public abstract class TransportFactory { */ private static TransportFactory findTransportFactory(URI location) throws IOException { String scheme = location.getScheme(); - if( scheme == null ) + if (scheme == null) throw new IOException("Transport not scheme specified: [" + location + "]"); - TransportFactory tf = (TransportFactory) transportFactorys.get(scheme); + TransportFactory tf = (TransportFactory)transportFactorys.get(scheme); if (tf == null) { // Try to load if from a META-INF property. try { - tf = (TransportFactory) transportFactoryFinder.newInstance(scheme); + tf = (TransportFactory)transportFactoryFinder.newInstance(scheme); transportFactorys.put(scheme, tf); - } - catch (Throwable e) { + } catch (Throwable e) { throw IOExceptionSupport.create("Transport scheme NOT recognized: [" + scheme + "]", e); } } @@ -180,16 +178,15 @@ public abstract class TransportFactory { } protected WireFormatFactory createWireFormatFactory(Map options) throws IOException { - String wireFormat = (String) options.get("wireFormat"); + String wireFormat = (String)options.get("wireFormat"); if (wireFormat == null) wireFormat = getDefaultWireFormatType(); try { - WireFormatFactory wff = (WireFormatFactory) wireFormatFactoryFinder.newInstance(wireFormat); + WireFormatFactory wff = (WireFormatFactory)wireFormatFactoryFinder.newInstance(wireFormat); IntrospectionSupport.setProperties(wff, options, "wireFormat."); return wff; - } - catch (Throwable e) { + } catch (Throwable e) { throw IOExceptionSupport.create("Could not create wire format factory for: " + wireFormat + ", reason: " + e, e); } } @@ -199,8 +196,8 @@ public abstract class TransportFactory { } /** - * Fully configures and adds all need transport filters so that the transport - * can be used by the JMS client. + * Fully configures and adds all need transport filters so that the + * transport can be used by the JMS client. * * @param transport * @param wf @@ -209,19 +206,19 @@ public abstract class TransportFactory { * @throws Exception */ public Transport configure(Transport transport, WireFormat wf, Map options) throws Exception { - transport = compositeConfigure(transport, wf, options); - + transport = compositeConfigure(transport, wf, options); + transport = new MutexTransport(transport); transport = new ResponseCorrelator(transport); - + return transport; } /** - * Fully configures and adds all need transport filters so that the transport - * can be used by the ActiveMQ message broker. The main difference between this and the - * configure() method is that the broker does not issue requests to the client so the - * ResponseCorrelator is not needed. + * Fully configures and adds all need transport filters so that the + * transport can be used by the ActiveMQ message broker. The main difference + * between this and the configure() method is that the broker does not issue + * requests to the client so the ResponseCorrelator is not needed. * * @param transport * @param format @@ -229,15 +226,16 @@ public abstract class TransportFactory { * @return * @throws Exception */ - public Transport serverConfigure(Transport transport, WireFormat format, HashMap options) throws Exception { - transport = compositeConfigure(transport, format, options); + public Transport serverConfigure(Transport transport, WireFormat format, HashMap options) throws Exception { + transport = compositeConfigure(transport, format, options); transport = new MutexTransport(transport); return transport; - } - + } + /** - * Similar to configure(...) but this avoid adding in the MutexTransport and ResponseCorrelator transport layers - * so that the resulting transport can more efficiently be used as part of a composite transport. + * Similar to configure(...) but this avoid adding in the MutexTransport and + * ResponseCorrelator transport layers so that the resulting transport can + * more efficiently be used as part of a composite transport. * * @param transport * @param format diff --git a/activemq-core/src/main/java/org/apache/activemq/transport/TransportFilter.java b/activemq-core/src/main/java/org/apache/activemq/transport/TransportFilter.java index cee0970aad..444e8a9533 100755 --- a/activemq-core/src/main/java/org/apache/activemq/transport/TransportFilter.java +++ b/activemq-core/src/main/java/org/apache/activemq/transport/TransportFilter.java @@ -17,24 +17,25 @@ package org.apache.activemq.transport; import java.io.IOException; + /** * @version $Revision: 1.5 $ */ -public class TransportFilter implements TransportListener,Transport{ +public class TransportFilter implements TransportListener, Transport { final protected Transport next; protected TransportListener transportListener; - public TransportFilter(Transport next){ - this.next=next; + public TransportFilter(Transport next) { + this.next = next; } - public TransportListener getTransportListener(){ + public TransportListener getTransportListener() { return transportListener; } - public void setTransportListener(TransportListener channelListener){ - this.transportListener=channelListener; - if(channelListener==null) + public void setTransportListener(TransportListener channelListener) { + this.transportListener = channelListener; + if (channelListener == null) next.setTransportListener(null); else next.setTransportListener(this); @@ -42,13 +43,12 @@ public class TransportFilter implements TransportListener,Transport{ /** * @see org.apache.activemq.Service#start() - * @throws IOException - * if the next channel has not been set. + * @throws IOException if the next channel has not been set. */ - public void start() throws Exception{ - if(next==null) + public void start() throws Exception { + if (next == null) throw new IOException("The next channel has not been set."); - if(transportListener==null) + if (transportListener == null) throw new IOException("The command listener has not been set."); next.start(); } @@ -56,69 +56,69 @@ public class TransportFilter implements TransportListener,Transport{ /** * @see org.apache.activemq.Service#stop() */ - public void stop() throws Exception{ + public void stop() throws Exception { next.stop(); } - public void onCommand(Object command){ + public void onCommand(Object command) { transportListener.onCommand(command); } /** * @return Returns the next. */ - public Transport getNext(){ + public Transport getNext() { return next; } - public String toString(){ + public String toString() { return next.toString(); } - public void oneway(Object command) throws IOException{ + public void oneway(Object command) throws IOException { next.oneway(command); } - public FutureResponse asyncRequest(Object command,ResponseCallback responseCallback) throws IOException{ - return next.asyncRequest(command,null); + public FutureResponse asyncRequest(Object command, ResponseCallback responseCallback) throws IOException { + return next.asyncRequest(command, null); } - public Object request(Object command) throws IOException{ + public Object request(Object command) throws IOException { return next.request(command); } - public Object request(Object command,int timeout) throws IOException{ - return next.request(command,timeout); + public Object request(Object command, int timeout) throws IOException { + return next.request(command, timeout); } - public void onException(IOException error){ + public void onException(IOException error) { transportListener.onException(error); } - public void transportInterupted(){ + public void transportInterupted() { transportListener.transportInterupted(); } - public void transportResumed(){ + public void transportResumed() { transportListener.transportResumed(); } - public Object narrow(Class target){ - if(target.isAssignableFrom(getClass())){ + public Object narrow(Class target) { + if (target.isAssignableFrom(getClass())) { return this; } return next.narrow(target); } - public String getRemoteAddress() { - return next.getRemoteAddress(); - } + public String getRemoteAddress() { + return next.getRemoteAddress(); + } /** * @return * @see org.apache.activemq.transport.Transport#isFaultTolerant() */ - public boolean isFaultTolerant(){ + public boolean isFaultTolerant() { return next.isFaultTolerant(); } } diff --git a/activemq-core/src/main/java/org/apache/activemq/transport/TransportLogger.java b/activemq-core/src/main/java/org/apache/activemq/transport/TransportLogger.java index d7c0712c31..6fb243852b 100755 --- a/activemq-core/src/main/java/org/apache/activemq/transport/TransportLogger.java +++ b/activemq-core/src/main/java/org/apache/activemq/transport/TransportLogger.java @@ -21,19 +21,18 @@ import java.io.IOException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; - /** * @version $Revision$ */ public class TransportLogger extends TransportFilter { - private static int lastId=0; + private static int lastId; private final Log log; - + public TransportLogger(Transport next) { - this( next, LogFactory.getLog(TransportLogger.class.getName()+".Connection:"+getNextId())); + this(next, LogFactory.getLog(TransportLogger.class.getName() + ".Connection:" + getNextId())); } - + synchronized private static int getNextId() { return ++lastId; } @@ -44,46 +43,46 @@ public class TransportLogger extends TransportFilter { } public Object request(Object command) throws IOException { - log.debug("SENDING REQUEST: "+command); - Object rc = super.request(command); - log.debug("GOT RESPONSE: "+rc); - return rc; + log.debug("SENDING REQUEST: " + command); + Object rc = super.request(command); + log.debug("GOT RESPONSE: " + rc); + return rc; } - + public Object request(Object command, int timeout) throws IOException { - log.debug("SENDING REQUEST: "+command); + log.debug("SENDING REQUEST: " + command); Object rc = super.request(command, timeout); - log.debug("GOT RESPONSE: "+rc); - return rc; + log.debug("GOT RESPONSE: " + rc); + return rc; } - + public FutureResponse asyncRequest(Object command, ResponseCallback responseCallback) throws IOException { - log.debug("SENDING ASNYC REQUEST: "+command); - FutureResponse rc = next.asyncRequest(command, responseCallback); - return rc; + log.debug("SENDING ASNYC REQUEST: " + command); + FutureResponse rc = next.asyncRequest(command, responseCallback); + return rc; } - + public void oneway(Object command) throws IOException { - if( log.isDebugEnabled() ) { - log.debug("SENDING: "+command); + if (log.isDebugEnabled()) { + log.debug("SENDING: " + command); } next.oneway(command); } - + public void onCommand(Object command) { - if( log.isDebugEnabled() ) { + if (log.isDebugEnabled()) { log.debug("RECEIVED: " + command); } getTransportListener().onCommand(command); } - + public void onException(IOException error) { - if( log.isDebugEnabled() ) { - log.debug("RECEIVED Exception: "+error, error); + if (log.isDebugEnabled()) { + log.debug("RECEIVED Exception: " + error, error); } getTransportListener().onException(error); } - + public String toString() { return next.toString(); } diff --git a/activemq-core/src/main/java/org/apache/activemq/transport/TransportServerSupport.java b/activemq-core/src/main/java/org/apache/activemq/transport/TransportServerSupport.java index 4a0127842c..b7aa82d210 100644 --- a/activemq-core/src/main/java/org/apache/activemq/transport/TransportServerSupport.java +++ b/activemq-core/src/main/java/org/apache/activemq/transport/TransportServerSupport.java @@ -16,10 +16,10 @@ */ package org.apache.activemq.transport; -import org.apache.activemq.util.ServiceSupport; - import java.net.URI; +import org.apache.activemq.util.ServiceSupport; + /** * A useful base class for implementations of {@link TransportServer} * @@ -28,7 +28,7 @@ import java.net.URI; public abstract class TransportServerSupport extends ServiceSupport implements TransportServer { private URI connectURI; - private URI bindLocation; + private URI bindLocation; private TransportAcceptListener acceptListener; public TransportServerSupport() { @@ -63,8 +63,7 @@ public abstract class TransportServerSupport extends ServiceSupport implements T } /** - * @param location - * The location to set. + * @param location The location to set. */ public void setConnectURI(URI location) { this.connectURI = location; @@ -76,11 +75,11 @@ public abstract class TransportServerSupport extends ServiceSupport implements T } } - public URI getBindLocation() { - return bindLocation; - } + public URI getBindLocation() { + return bindLocation; + } - public void setBindLocation(URI bindLocation) { - this.bindLocation = bindLocation; - } + public void setBindLocation(URI bindLocation) { + this.bindLocation = bindLocation; + } } diff --git a/activemq-core/src/main/java/org/apache/activemq/transport/TransportServerThreadSupport.java b/activemq-core/src/main/java/org/apache/activemq/transport/TransportServerThreadSupport.java index 99a43d90cf..8d3868cb72 100644 --- a/activemq-core/src/main/java/org/apache/activemq/transport/TransportServerThreadSupport.java +++ b/activemq-core/src/main/java/org/apache/activemq/transport/TransportServerThreadSupport.java @@ -16,7 +16,6 @@ */ package org.apache.activemq.transport; - import org.apache.activemq.ThreadPriorities; import org.apache.activemq.util.ServiceStopper; import org.apache.commons.logging.Log; @@ -36,7 +35,8 @@ public abstract class TransportServerThreadSupport extends TransportServerSuppor private boolean daemon = true; private boolean joinOnStop = true; private Thread runner; - private long stackSize=0;//should be a multiple of 128k + // should be a multiple of 128k + private long stackSize = 0; public TransportServerThreadSupport() { } @@ -56,13 +56,13 @@ public abstract class TransportServerThreadSupport extends TransportServerSuppor this.daemon = daemon; } - public boolean isJoinOnStop() { return joinOnStop; } /** - * Sets whether the background read thread is joined with (waited for) on a stop + * Sets whether the background read thread is joined with (waited for) on a + * stop */ public void setJoinOnStop(boolean joinOnStop) { this.joinOnStop = joinOnStop; @@ -70,7 +70,7 @@ public abstract class TransportServerThreadSupport extends TransportServerSuppor protected void doStart() throws Exception { log.info("Listening for connections at: " + getConnectURI()); - runner = new Thread(null,this, "ActiveMQ Transport Server: "+toString(),stackSize); + runner = new Thread(null, this, "ActiveMQ Transport Server: " + toString(), stackSize); runner.setDaemon(daemon); runner.setPriority(ThreadPriorities.BROKER_MANAGEMENT); runner.start(); @@ -83,19 +83,17 @@ public abstract class TransportServerThreadSupport extends TransportServerSuppor } } - /** * @return the stackSize */ - public long getStackSize(){ + public long getStackSize() { return this.stackSize; } - /** * @param stackSize the stackSize to set */ - public void setStackSize(long stackSize){ - this.stackSize=stackSize; + public void setStackSize(long stackSize) { + this.stackSize = stackSize; } } diff --git a/activemq-core/src/main/java/org/apache/activemq/transport/TransportSupport.java b/activemq-core/src/main/java/org/apache/activemq/transport/TransportSupport.java index c9ff306b07..a21ddd324c 100644 --- a/activemq-core/src/main/java/org/apache/activemq/transport/TransportSupport.java +++ b/activemq-core/src/main/java/org/apache/activemq/transport/TransportSupport.java @@ -70,8 +70,8 @@ public abstract class TransportSupport extends ServiceSupport implements Transpo public Object request(Object command) throws IOException { throw new AssertionError("Unsupported Method"); } - - public Object request(Object command,int timeout) throws IOException { + + public Object request(Object command, int timeout) throws IOException { throw new AssertionError("Unsupported Method"); } @@ -82,8 +82,7 @@ public abstract class TransportSupport extends ServiceSupport implements Transpo if (command != null) { if (transportListener != null) { transportListener.onCommand(command); - } - else { + } else { log.error("No transportListener available to process inbound command: " + command); } } @@ -100,11 +99,11 @@ public abstract class TransportSupport extends ServiceSupport implements Transpo protected void checkStarted() throws IOException { if (!isStarted()) { - throw new IOException("The transport is not running."); + throw new IOException("The transport is not running."); } } - - public boolean isFaultTolerant(){ + + public boolean isFaultTolerant() { return false; } diff --git a/activemq-core/src/main/java/org/apache/activemq/transport/TransportThreadSupport.java b/activemq-core/src/main/java/org/apache/activemq/transport/TransportThreadSupport.java index e1fde97aca..411a82c7cd 100644 --- a/activemq-core/src/main/java/org/apache/activemq/transport/TransportThreadSupport.java +++ b/activemq-core/src/main/java/org/apache/activemq/transport/TransportThreadSupport.java @@ -16,8 +16,6 @@ */ package org.apache.activemq.transport; - - /** * A useful base class for a transport implementation which has a background * reading thread. @@ -28,7 +26,8 @@ public abstract class TransportThreadSupport extends TransportSupport implements private boolean daemon = false; private Thread runner; - private long stackSize=0;//should be a multiple of 128k + // should be a multiple of 128k + private long stackSize = 0; public boolean isDaemon() { return daemon; @@ -39,24 +38,22 @@ public abstract class TransportThreadSupport extends TransportSupport implements } protected void doStart() throws Exception { - runner = new Thread(null,this, "ActiveMQ Transport: "+toString(),stackSize); + runner = new Thread(null, this, "ActiveMQ Transport: " + toString(), stackSize); runner.setDaemon(daemon); runner.start(); } - /** * @return the stackSize */ - public long getStackSize(){ + public long getStackSize() { return this.stackSize; } - /** * @param stackSize the stackSize to set */ - public void setStackSize(long stackSize){ - this.stackSize=stackSize; + public void setStackSize(long stackSize) { + this.stackSize = stackSize; } } diff --git a/activemq-core/src/main/java/org/apache/activemq/transport/WireFormatNegotiator.java b/activemq-core/src/main/java/org/apache/activemq/transport/WireFormatNegotiator.java index a601626d71..a10afb2ea0 100755 --- a/activemq-core/src/main/java/org/apache/activemq/transport/WireFormatNegotiator.java +++ b/activemq-core/src/main/java/org/apache/activemq/transport/WireFormatNegotiator.java @@ -30,22 +30,21 @@ import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; - /** * Negotiates the wire format with a new connection */ public class WireFormatNegotiator extends TransportFilter { - private static final Log log = LogFactory.getLog(WireFormatNegotiator.class); - + private static final Log LOG = LogFactory.getLog(WireFormatNegotiator.class); + private OpenWireFormat wireFormat; private final int minimumVersion; - private long negotiateTimeout=15000; - - private final AtomicBoolean firstStart=new AtomicBoolean(true); + private long negotiateTimeout = 15000L; + + private final AtomicBoolean firstStart = new AtomicBoolean(true); private final CountDownLatch readyCountDownLatch = new CountDownLatch(1); private final CountDownLatch wireInfoSentDownLatch = new CountDownLatch(1); - + /** * Negotiator * @@ -60,31 +59,30 @@ public class WireFormatNegotiator extends TransportFilter { this.minimumVersion = minimumVersion; } - public void start() throws Exception { super.start(); - if( firstStart.compareAndSet(true, false) ) { - try { - WireFormatInfo info = wireFormat.getPreferedWireFormatInfo(); - if (log.isDebugEnabled()) { - log.debug("Sending: " + info); + if (firstStart.compareAndSet(true, false)) { + try { + WireFormatInfo info = wireFormat.getPreferedWireFormatInfo(); + if (LOG.isDebugEnabled()) { + LOG.debug("Sending: " + info); } - sendWireFormat(info); - } finally { - wireInfoSentDownLatch.countDown(); - } + sendWireFormat(info); + } finally { + wireInfoSentDownLatch.countDown(); + } } } - + public void stop() throws Exception { - super.stop(); + super.stop(); readyCountDownLatch.countDown(); } - + public void oneway(Object command) throws IOException { try { - if( !readyCountDownLatch.await(negotiateTimeout, TimeUnit.MILLISECONDS) ) - throw new IOException("Wire format negotiation timeout: peer did not send his wire format."); + if (!readyCountDownLatch.await(negotiateTimeout, TimeUnit.MILLISECONDS)) + throw new IOException("Wire format negotiation timeout: peer did not send his wire format."); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new InterruptedIOException(); @@ -92,60 +90,54 @@ public class WireFormatNegotiator extends TransportFilter { super.oneway(command); } - public void onCommand(Object o) { - Command command = (Command) o; - if( command.isWireFormatInfo() ) { - WireFormatInfo info = (WireFormatInfo) command; - if (log.isDebugEnabled()) { - log.debug("Received WireFormat: " + info); + Command command = (Command)o; + if (command.isWireFormatInfo()) { + WireFormatInfo info = (WireFormatInfo)command; + if (LOG.isDebugEnabled()) { + LOG.debug("Received WireFormat: " + info); } - + try { wireInfoSentDownLatch.await(); - - if (log.isDebugEnabled()) { - log.debug(this + " before negotiation: " + wireFormat); + + if (LOG.isDebugEnabled()) { + LOG.debug(this + " before negotiation: " + wireFormat); } - if( !info.isValid() ) { + if (!info.isValid()) { onException(new IOException("Remote wire format magic is invalid")); - } else if( info.getVersion() < minimumVersion ) { - onException(new IOException("Remote wire format ("+info.getVersion()+") is lower the minimum version required ("+minimumVersion+")")); + } else if (info.getVersion() < minimumVersion) { + onException(new IOException("Remote wire format (" + info.getVersion() + ") is lower the minimum version required (" + minimumVersion + ")")); } - + wireFormat.renegotiateWireFormat(info); - - if (log.isDebugEnabled()) { - log.debug(this + " after negotiation: " + wireFormat); + + if (LOG.isDebugEnabled()) { + LOG.debug(this + " after negotiation: " + wireFormat); } - + } catch (IOException e) { onException(e); } catch (InterruptedException e) { - onException((IOException) new InterruptedIOException().initCause(e)); + onException((IOException)new InterruptedIOException().initCause(e)); } catch (Exception e) { onException(IOExceptionSupport.create(e)); - } + } readyCountDownLatch.countDown(); onWireFormatNegotiated(info); } getTransportListener().onCommand(command); } - public void onException(IOException error) { readyCountDownLatch.countDown(); /* - try { - super.oneway(new ExceptionResponse(error)); - } - catch (IOException e) { - // ignore as we are already throwing an exception - } - */ + * try { super.oneway(new ExceptionResponse(error)); } catch + * (IOException e) { // ignore as we are already throwing an exception } + */ super.onException(error); } - + public String toString() { return next.toString(); } @@ -153,16 +145,15 @@ public class WireFormatNegotiator extends TransportFilter { protected void sendWireFormat(WireFormatInfo info) throws IOException { next.oneway(info); } - + protected void onWireFormatNegotiated(WireFormatInfo info) { } + public long getNegotiateTimeout() { + return negotiateTimeout; + } - public long getNegotiateTimeout() { - return negotiateTimeout; - } - - public void setNegotiateTimeout(long negotiateTimeout) { - this.negotiateTimeout = negotiateTimeout; - } + public void setNegotiateTimeout(long negotiateTimeout) { + this.negotiateTimeout = negotiateTimeout; + } } diff --git a/activemq-core/src/main/java/org/apache/activemq/transport/discovery/DiscoveryAgentFactory.java b/activemq-core/src/main/java/org/apache/activemq/transport/discovery/DiscoveryAgentFactory.java index 557259d8bf..5f6db1cf0a 100755 --- a/activemq-core/src/main/java/org/apache/activemq/transport/discovery/DiscoveryAgentFactory.java +++ b/activemq-core/src/main/java/org/apache/activemq/transport/discovery/DiscoveryAgentFactory.java @@ -26,7 +26,7 @@ import java.util.concurrent.ConcurrentHashMap; public abstract class DiscoveryAgentFactory { - static final private FactoryFinder discoveryAgentFinder = new FactoryFinder("META-INF/services/org/apache/activemq/transport/discoveryagent/"); + static final private FactoryFinder discoveryAgentFinder = new FactoryFinder("META-INF/services/org/apache/activemq/transport/discoveryagent/"); static final private ConcurrentHashMap discoveryAgentFactorys = new ConcurrentHashMap(); /** @@ -36,22 +36,21 @@ public abstract class DiscoveryAgentFactory { */ private static DiscoveryAgentFactory findDiscoveryAgentFactory(URI uri) throws IOException { String scheme = uri.getScheme(); - if( scheme == null ) + if (scheme == null) throw new IOException("DiscoveryAgent scheme not specified: [" + uri + "]"); - DiscoveryAgentFactory daf = (DiscoveryAgentFactory) discoveryAgentFactorys.get(scheme); + DiscoveryAgentFactory daf = (DiscoveryAgentFactory)discoveryAgentFactorys.get(scheme); if (daf == null) { // Try to load if from a META-INF property. try { - daf = (DiscoveryAgentFactory) discoveryAgentFinder.newInstance(scheme); + daf = (DiscoveryAgentFactory)discoveryAgentFinder.newInstance(scheme); discoveryAgentFactorys.put(scheme, daf); - } - catch (Throwable e) { + } catch (Throwable e) { throw IOExceptionSupport.create("DiscoveryAgent scheme NOT recognized: [" + scheme + "]", e); } } return daf; } - + public static DiscoveryAgent createDiscoveryAgent(URI uri) throws IOException { DiscoveryAgentFactory tf = findDiscoveryAgentFactory(uri); return tf.doCreateDiscoveryAgent(uri); @@ -59,19 +58,22 @@ public abstract class DiscoveryAgentFactory { } abstract protected DiscoveryAgent doCreateDiscoveryAgent(URI uri) throws IOException; -// { -// try { -// String type = ( uri.getScheme() == null ) ? uri.getPath() : uri.getScheme(); -// DiscoveryAgent rc = (DiscoveryAgent) discoveryAgentFinder.newInstance(type); -// Map options = URISupport.parseParamters(uri); -// IntrospectionSupport.setProperties(rc, options); -// if( rc.getClass() == SimpleDiscoveryAgent.class ) { -// CompositeData data = URISupport.parseComposite(uri); -// ((SimpleDiscoveryAgent)rc).setServices(data.getComponents()); -// } -// return rc; -// } catch (Throwable e) { -// throw IOExceptionSupport.create("Could not create discovery agent: "+uri, e); -// } -// } + // { + // try { + // String type = ( uri.getScheme() == null ) ? uri.getPath() : + // uri.getScheme(); + // DiscoveryAgent rc = (DiscoveryAgent) + // discoveryAgentFinder.newInstance(type); + // Map options = URISupport.parseParamters(uri); + // IntrospectionSupport.setProperties(rc, options); + // if( rc.getClass() == SimpleDiscoveryAgent.class ) { + // CompositeData data = URISupport.parseComposite(uri); + // ((SimpleDiscoveryAgent)rc).setServices(data.getComponents()); + // } + // return rc; + // } catch (Throwable e) { + // throw IOExceptionSupport.create("Could not create discovery agent: "+uri, + // e); + // } + // } } diff --git a/activemq-core/src/main/java/org/apache/activemq/transport/discovery/DiscoveryTransportFactory.java b/activemq-core/src/main/java/org/apache/activemq/transport/discovery/DiscoveryTransportFactory.java index 85676511b4..c1bc0e88f2 100755 --- a/activemq-core/src/main/java/org/apache/activemq/transport/discovery/DiscoveryTransportFactory.java +++ b/activemq-core/src/main/java/org/apache/activemq/transport/discovery/DiscoveryTransportFactory.java @@ -35,17 +35,17 @@ public class DiscoveryTransportFactory extends FailoverTransportFactory { public Transport createTransport(CompositeData compositData) throws IOException { Map parameters = new HashMap(compositData.getParameters()); DiscoveryTransport transport = new DiscoveryTransport(createTransport(parameters)); - + DiscoveryAgent discoveryAgent = DiscoveryAgentFactory.createDiscoveryAgent(compositData.getComponents()[0]); transport.setDiscoveryAgent(discoveryAgent); - IntrospectionSupport.setProperties(transport,parameters); + IntrospectionSupport.setProperties(transport, parameters); return transport; } - public TransportServer doBind(String brokerId,URI location) throws IOException{ - throw new IOException("Invalid server URI: "+location); -// try{ + public TransportServer doBind(String brokerId, URI location) throws IOException { + throw new IOException("Invalid server URI: " + location); +// try{ // CompositeData compositData=URISupport.parseComposite(location); // URI[] components=compositData.getComponents(); // if(components.length!=1){ diff --git a/activemq-core/src/main/java/org/apache/activemq/transport/discovery/rendezvous/JmDNSFactory.java b/activemq-core/src/main/java/org/apache/activemq/transport/discovery/rendezvous/JmDNSFactory.java index 69998fbed9..0d70e09a3d 100644 --- a/activemq-core/src/main/java/org/apache/activemq/transport/discovery/rendezvous/JmDNSFactory.java +++ b/activemq-core/src/main/java/org/apache/activemq/transport/discovery/rendezvous/JmDNSFactory.java @@ -24,34 +24,35 @@ import javax.jmdns.JmDNS; import java.util.concurrent.atomic.AtomicInteger; public class JmDNSFactory { - + static Map registry = new HashMap(); + static class UsageTracker { AtomicInteger count = new AtomicInteger(0); - JmDNS jmDNS; + JmDNS jmDNS; } - + static synchronized JmDNS create(final InetAddress address) throws IOException { UsageTracker tracker = (UsageTracker)registry.get(address); - if( tracker == null ) { + if (tracker == null) { tracker = new UsageTracker(); tracker.jmDNS = new JmDNS(address) { public void close() { - if( onClose(address) ) { + if (onClose(address)) { super.close(); } } }; registry.put(address, tracker); - } + } tracker.count.incrementAndGet(); return tracker.jmDNS; } - - static synchronized boolean onClose(InetAddress address){ - UsageTracker tracker=(UsageTracker) registry.get(address); - if(tracker!=null){ - if(tracker.count.decrementAndGet()==0){ + + static synchronized boolean onClose(InetAddress address) { + UsageTracker tracker = (UsageTracker)registry.get(address); + if (tracker != null) { + if (tracker.count.decrementAndGet() == 0) { registry.remove(address); return true; } diff --git a/activemq-core/src/main/java/org/apache/activemq/transport/discovery/rendezvous/RendezvousDiscoveryAgent.java b/activemq-core/src/main/java/org/apache/activemq/transport/discovery/rendezvous/RendezvousDiscoveryAgent.java index 1ee5ca5010..52129cfe84 100755 --- a/activemq-core/src/main/java/org/apache/activemq/transport/discovery/rendezvous/RendezvousDiscoveryAgent.java +++ b/activemq-core/src/main/java/org/apache/activemq/transport/discovery/rendezvous/RendezvousDiscoveryAgent.java @@ -41,7 +41,7 @@ import java.util.concurrent.CopyOnWriteArrayList; /** * A {@link DiscoveryAgent} using Zeroconf * via the jmDNS library - * + * * @version $Revision$ */ public class RendezvousDiscoveryAgent implements DiscoveryAgent, ServiceListener { @@ -60,7 +60,7 @@ public class RendezvousDiscoveryAgent implements DiscoveryAgent, ServiceListener private final CopyOnWriteArrayList serviceInfos = new CopyOnWriteArrayList(); // DiscoveryAgent interface - //------------------------------------------------------------------------- + // ------------------------------------------------------------------------- public void start() throws Exception { if (group == null) { throw new IOException("You must specify a group to discover"); @@ -73,23 +73,22 @@ public class RendezvousDiscoveryAgent implements DiscoveryAgent, ServiceListener try { // force lazy construction getJmdns(); - if (listener!=null) { - log.info("Discovering service of type: " +type); + if (listener != null) { + log.info("Discovering service of type: " + type); jmdns.addServiceListener(type, this); } - } - catch (IOException e) { + } catch (IOException e) { JMSExceptionSupport.create("Failed to start JmDNS service: " + e, e); } } public void stop() { - if( jmdns!=null ) { + if (jmdns != null) { for (Iterator iter = serviceInfos.iterator(); iter.hasNext();) { - ServiceInfo si = (ServiceInfo) iter.next(); + ServiceInfo si = (ServiceInfo)iter.next(); jmdns.unregisterService(si); } - + // Close it down async since this could block for a while. final JmDNS closeTarget = jmdns; Thread thread = new Thread() { @@ -97,28 +96,27 @@ public class RendezvousDiscoveryAgent implements DiscoveryAgent, ServiceListener closeTarget.close(); } }; - + thread.setDaemon(true); thread.start(); - - jmdns=null; + + jmdns = null; } } - + public void registerService(String name) throws IOException { ServiceInfo si = createServiceInfo(name, new HashMap()); serviceInfos.add(si); getJmdns().registerService(si); } - // ServiceListener interface - //------------------------------------------------------------------------- + // ------------------------------------------------------------------------- public void addService(JmDNS jmDNS, String type, String name) { if (log.isDebugEnabled()) { log.debug("addService with type: " + type + " name: " + name); } - if( listener!=null ) + if (listener != null) listener.onServiceAdd(new DiscoveryEvent(name)); jmDNS.requestServiceInfo(type, name); } @@ -127,18 +125,21 @@ public class RendezvousDiscoveryAgent implements DiscoveryAgent, ServiceListener if (log.isDebugEnabled()) { log.debug("removeService with type: " + type + " name: " + name); } - if( listener!=null ) + if (listener != null) listener.onServiceRemove(new DiscoveryEvent(name)); } - public void serviceAdded(ServiceEvent event) { - addService(event.getDNS(), event.getType(), event.getName()); - } - public void serviceRemoved(ServiceEvent event) { - removeService(event.getDNS(), event.getType(), event.getName()); - } + public void serviceAdded(ServiceEvent event) { + addService(event.getDNS(), event.getType(), event.getName()); + } + + public void serviceRemoved(ServiceEvent event) { + removeService(event.getDNS(), event.getType(), event.getName()); + } + public void serviceResolved(ServiceEvent event) { } + public void resolveService(JmDNS jmDNS, String type, String name, ServiceInfo serviceInfo) { } @@ -169,7 +170,6 @@ public class RendezvousDiscoveryAgent implements DiscoveryAgent, ServiceListener this.jmdns = jmdns; } - public InetAddress getLocalAddress() throws UnknownHostException { if (localAddress == null) { localAddress = createLocalAddress(); @@ -190,7 +190,7 @@ public class RendezvousDiscoveryAgent implements DiscoveryAgent, ServiceListener } // Implementation methods - //------------------------------------------------------------------------- + // ------------------------------------------------------------------------- protected ServiceInfo createServiceInfo(String name, Map map) { int port = MapHelper.getInt(map, "port", 0); @@ -199,7 +199,7 @@ public class RendezvousDiscoveryAgent implements DiscoveryAgent, ServiceListener if (log.isDebugEnabled()) { log.debug("Registering service type: " + type + " name: " + name + " details: " + map); } - return new ServiceInfo(type, name+"."+type, port, weight, priority, ""); + return new ServiceInfo(type, name + "." + type, port, weight, priority, ""); } protected JmDNS createJmDNS() throws IOException { @@ -222,11 +222,11 @@ public class RendezvousDiscoveryAgent implements DiscoveryAgent, ServiceListener } public void setGroup(String group) { - this.group=group; + this.group = group; } public String getType() { - return "_" + group+"."+TYPE_SUFFIX; + return "_" + group + "." + TYPE_SUFFIX; } public void serviceFailed(DiscoveryEvent event) throws IOException { @@ -237,8 +237,8 @@ public class RendezvousDiscoveryAgent implements DiscoveryAgent, ServiceListener * @param brokerName * @see org.apache.activemq.transport.discovery.DiscoveryAgent#setBrokerName(java.lang.String) */ - public void setBrokerName(String brokerName){ + public void setBrokerName(String brokerName) { // implementation of interface - + } } diff --git a/activemq-core/src/main/java/org/apache/activemq/transport/discovery/simple/SimpleDiscoveryAgent.java b/activemq-core/src/main/java/org/apache/activemq/transport/discovery/simple/SimpleDiscoveryAgent.java index d1684f79eb..aadf79c6df 100755 --- a/activemq-core/src/main/java/org/apache/activemq/transport/discovery/simple/SimpleDiscoveryAgent.java +++ b/activemq-core/src/main/java/org/apache/activemq/transport/discovery/simple/SimpleDiscoveryAgent.java @@ -26,12 +26,13 @@ import org.apache.activemq.transport.discovery.DiscoveryListener; import java.util.concurrent.atomic.AtomicBoolean; /** - * A simple DiscoveryAgent that allows static configuration of the discovered services. + * A simple DiscoveryAgent that allows static configuration of the discovered + * services. * * @version $Revision$ */ public class SimpleDiscoveryAgent implements DiscoveryAgent { - + private long initialReconnectDelay = 1000; private long maxReconnectDelay = 1000 * 30; private long backOffMultiplier = 2; @@ -44,41 +45,41 @@ public class SimpleDiscoveryAgent implements DiscoveryAgent { String services[] = new String[] {}; String group = "DEFAULT"; private final AtomicBoolean running = new AtomicBoolean(false); - + class SimpleDiscoveryEvent extends DiscoveryEvent { - - private int connectFailures; + + private int connectFailures; private long reconnectDelay = initialReconnectDelay; private long connectTime = System.currentTimeMillis(); private AtomicBoolean failed = new AtomicBoolean(false); public SimpleDiscoveryEvent(String service) { - super(service); - } - + super(service); + } + } - + public void setDiscoveryListener(DiscoveryListener listener) { this.listener = listener; } - + public void registerService(String name) throws IOException { } - + public void start() throws Exception { - running.set(true); + running.set(true); for (int i = 0; i < services.length; i++) { listener.onServiceAdd(new SimpleDiscoveryEvent(services[i])); } } - + public void stop() throws Exception { - running.set(false); - synchronized(sleepMutex) { - sleepMutex.notifyAll(); - } + running.set(false); + synchronized (sleepMutex) { + sleepMutex.notifyAll(); + } } - + public String[] getServices() { return services; } @@ -86,11 +87,11 @@ public class SimpleDiscoveryAgent implements DiscoveryAgent { public void setServices(String services) { this.services = services.split(","); } - + public void setServices(String services[]) { this.services = services; } - + public void setServices(URI services[]) { this.services = new String[services.length]; for (int i = 0; i < services.length; i++) { @@ -110,112 +111,112 @@ public class SimpleDiscoveryAgent implements DiscoveryAgent { } public void serviceFailed(DiscoveryEvent devent) throws IOException { - - final SimpleDiscoveryEvent event = (SimpleDiscoveryEvent) devent; - if( event.failed.compareAndSet(false, true) ) { - - listener.onServiceRemove(event); - Thread thread = new Thread() { - public void run() { - - - // We detect a failed connection attempt because the service fails right - // away. - if( event.connectTime + minConnectTime > System.currentTimeMillis() ) { - - event.connectFailures++; - - if( maxReconnectAttempts>0 && event.connectFailures >= maxReconnectAttempts ) { - // Don' try to re-connect - return; - } - - synchronized(sleepMutex){ - try{ - if( !running.get() ) - return; - - sleepMutex.wait(event.reconnectDelay); - }catch(InterruptedException ie){ + + final SimpleDiscoveryEvent event = (SimpleDiscoveryEvent)devent; + if (event.failed.compareAndSet(false, true)) { + + listener.onServiceRemove(event); + Thread thread = new Thread() { + public void run() { + + // We detect a failed connection attempt because the service + // fails right + // away. + if (event.connectTime + minConnectTime > System.currentTimeMillis()) { + + event.connectFailures++; + + if (maxReconnectAttempts > 0 && event.connectFailures >= maxReconnectAttempts) { + // Don' try to re-connect + return; + } + + synchronized (sleepMutex) { + try { + if (!running.get()) + return; + + sleepMutex.wait(event.reconnectDelay); + } catch (InterruptedException ie) { Thread.currentThread().interrupt(); - return; - } - } - - if (!useExponentialBackOff) { - event.reconnectDelay = initialReconnectDelay; - } else { - // Exponential increment of reconnect delay. - event.reconnectDelay*=backOffMultiplier; - if(event.reconnectDelay>maxReconnectDelay) - event.reconnectDelay=maxReconnectDelay; - } - - } else { - event.connectFailures = 0; - event.reconnectDelay = initialReconnectDelay; - } - - if( !running.get() ) - return; - - event.connectTime = System.currentTimeMillis(); - event.failed.set(false); - - listener.onServiceAdd(event); - } - }; - thread.setDaemon(true); - thread.start(); + return; + } + } + + if (!useExponentialBackOff) { + event.reconnectDelay = initialReconnectDelay; + } else { + // Exponential increment of reconnect delay. + event.reconnectDelay *= backOffMultiplier; + if (event.reconnectDelay > maxReconnectDelay) + event.reconnectDelay = maxReconnectDelay; + } + + } else { + event.connectFailures = 0; + event.reconnectDelay = initialReconnectDelay; + } + + if (!running.get()) + return; + + event.connectTime = System.currentTimeMillis(); + event.failed.set(false); + + listener.onServiceAdd(event); + } + }; + thread.setDaemon(true); + thread.start(); } } - public long getBackOffMultiplier() { - return backOffMultiplier; - } + public long getBackOffMultiplier() { + return backOffMultiplier; + } - public void setBackOffMultiplier(long backOffMultiplier) { - this.backOffMultiplier = backOffMultiplier; - } + public void setBackOffMultiplier(long backOffMultiplier) { + this.backOffMultiplier = backOffMultiplier; + } - public long getInitialReconnectDelay() { - return initialReconnectDelay; - } + public long getInitialReconnectDelay() { + return initialReconnectDelay; + } - public void setInitialReconnectDelay(long initialReconnectDelay) { - this.initialReconnectDelay = initialReconnectDelay; - } + public void setInitialReconnectDelay(long initialReconnectDelay) { + this.initialReconnectDelay = initialReconnectDelay; + } - public int getMaxReconnectAttempts() { - return maxReconnectAttempts; - } + public int getMaxReconnectAttempts() { + return maxReconnectAttempts; + } - public void setMaxReconnectAttempts(int maxReconnectAttempts) { - this.maxReconnectAttempts = maxReconnectAttempts; - } + public void setMaxReconnectAttempts(int maxReconnectAttempts) { + this.maxReconnectAttempts = maxReconnectAttempts; + } - public long getMaxReconnectDelay() { - return maxReconnectDelay; - } + public long getMaxReconnectDelay() { + return maxReconnectDelay; + } - public void setMaxReconnectDelay(long maxReconnectDelay) { - this.maxReconnectDelay = maxReconnectDelay; - } + public void setMaxReconnectDelay(long maxReconnectDelay) { + this.maxReconnectDelay = maxReconnectDelay; + } - public long getMinConnectTime() { - return minConnectTime; - } + public long getMinConnectTime() { + return minConnectTime; + } - public void setMinConnectTime(long minConnectTime) { - this.minConnectTime = minConnectTime; - } + public void setMinConnectTime(long minConnectTime) { + this.minConnectTime = minConnectTime; + } - public boolean isUseExponentialBackOff() { - return useExponentialBackOff; - } + public boolean isUseExponentialBackOff() { + return useExponentialBackOff; + } + + public void setUseExponentialBackOff(boolean useExponentialBackOff) { + this.useExponentialBackOff = useExponentialBackOff; + } - public void setUseExponentialBackOff(boolean useExponentialBackOff) { - this.useExponentialBackOff = useExponentialBackOff; - } - } diff --git a/activemq-core/src/main/java/org/apache/activemq/transport/failover/FailoverTransport.java b/activemq-core/src/main/java/org/apache/activemq/transport/failover/FailoverTransport.java index ded2a8cbf3..e4c573a5d8 100755 --- a/activemq-core/src/main/java/org/apache/activemq/transport/failover/FailoverTransport.java +++ b/activemq-core/src/main/java/org/apache/activemq/transport/failover/FailoverTransport.java @@ -81,122 +81,120 @@ public class FailoverTransport implements CompositeTransport { private Exception connectionFailure; private final TransportListener myTransportListener = createTransportListener(); - + TransportListener createTransportListener() { - return new TransportListener() { - public void onCommand(Object o) { - Command command = (Command) o; - if (command == null) { - return; - } - if (command.isResponse()) { - Object object = requestMap.remove(Integer.valueOf(((Response) command).getCorrelationId())); - if( object!=null && object.getClass() == Tracked.class ) { - ((Tracked)object).onResponses(); + return new TransportListener() { + public void onCommand(Object o) { + Command command = (Command)o; + if (command == null) { + return; + } + if (command.isResponse()) { + Object object = requestMap.remove(Integer.valueOf(((Response)command).getCorrelationId())); + if (object != null && object.getClass() == Tracked.class) { + ((Tracked)object).onResponses(); } - } - if (!initialized){ - if (command.isBrokerInfo()){ - BrokerInfo info = (BrokerInfo)command; - BrokerInfo[] peers = info.getPeerBrokerInfos(); - if (peers!= null){ - for (int i =0; i < peers.length;i++){ - String brokerString = peers[i].getBrokerURL(); - add(brokerString); - } - } - initialized = true; - } - - } - if (transportListener != null) { - transportListener.onCommand(command); - } - } - - public void onException(IOException error) { - try { - handleTransportFailure(error); - } - catch (InterruptedException e) { - Thread.currentThread().interrupt(); - transportListener.onException(new InterruptedIOException()); - } - } - - public void transportInterupted(){ - if (transportListener != null){ - transportListener.transportInterupted(); - } - } - - public void transportResumed(){ - if(transportListener != null){ - transportListener.transportResumed(); - } - } - }; + } + if (!initialized) { + if (command.isBrokerInfo()) { + BrokerInfo info = (BrokerInfo)command; + BrokerInfo[] peers = info.getPeerBrokerInfos(); + if (peers != null) { + for (int i = 0; i < peers.length; i++) { + String brokerString = peers[i].getBrokerURL(); + add(brokerString); + } + } + initialized = true; + } + + } + if (transportListener != null) { + transportListener.onCommand(command); + } + } + + public void onException(IOException error) { + try { + handleTransportFailure(error); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + transportListener.onException(new InterruptedIOException()); + } + } + + public void transportInterupted() { + if (transportListener != null) { + transportListener.transportInterupted(); + } + } + + public void transportResumed() { + if (transportListener != null) { + transportListener.transportResumed(); + } + } + }; } - + public FailoverTransport() throws InterruptedIOException { - stateTracker.setTrackTransactions(true); - + stateTracker.setTrackTransactions(true); + // Setup a task that is used to reconnect the a connection async. reconnectTask = DefaultThreadPools.getDefaultTaskRunnerFactory().createTaskRunner(new Task() { public boolean iterate() { - Exception failure=null; + Exception failure = null; synchronized (reconnectMutex) { - if (disposed || connectionFailure!=null) { + if (disposed || connectionFailure != null) { reconnectMutex.notifyAll(); } - if (connectedTransport != null || disposed || connectionFailure!=null) { + if (connectedTransport != null || disposed || connectionFailure != null) { return false; } else { ArrayList connectList = getConnectList(); - if( connectList.isEmpty() ) { + if (connectList.isEmpty()) { failure = new IOException("No uris available to connect to."); } else { - if (!useExponentialBackOff){ + if (!useExponentialBackOff) { reconnectDelay = initialReconnectDelay; } Iterator iter = connectList.iterator(); for (int i = 0; iter.hasNext() && connectedTransport == null && !disposed; i++) { - URI uri = (URI) iter.next(); + URI uri = (URI)iter.next(); try { log.debug("Attempting connect to: " + uri); Transport t = TransportFactory.compositeConnect(uri); t.setTransportListener(myTransportListener); t.start(); - + if (started) { restoreTransport(t); } - + log.debug("Connection established"); reconnectDelay = initialReconnectDelay; connectedTransportURI = uri; connectedTransport = t; reconnectMutex.notifyAll(); connectFailures = 0; - if (transportListener != null){ + if (transportListener != null) { transportListener.transportResumed(); } log.info("Successfully reconnected to " + uri); return false; - } - catch (Exception e) { + } catch (Exception e) { failure = e; log.debug("Connect fail to: " + uri + ", reason: " + e); } } } } - + if (maxReconnectAttempts > 0 && ++connectFailures >= maxReconnectAttempts) { log.error("Failed to connect to transport after: " + connectFailures + " attempt(s)"); connectionFailure = failure; @@ -205,33 +203,32 @@ public class FailoverTransport implements CompositeTransport { } } - if(!disposed){ - - log.debug("Waiting "+reconnectDelay+" ms before attempting connection. "); - synchronized(sleepMutex){ - try{ - sleepMutex.wait(reconnectDelay); - }catch(InterruptedException e){ - Thread.currentThread().interrupt(); - } + if (!disposed) { + + log.debug("Waiting " + reconnectDelay + " ms before attempting connection. "); + synchronized (sleepMutex) { + try { + sleepMutex.wait(reconnectDelay); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); } - - - if(useExponentialBackOff){ + } + + if (useExponentialBackOff) { // Exponential increment of reconnect delay. - reconnectDelay*=backOffMultiplier; - if(reconnectDelay>maxReconnectDelay) - reconnectDelay=maxReconnectDelay; + reconnectDelay *= backOffMultiplier; + if (reconnectDelay > maxReconnectDelay) + reconnectDelay = maxReconnectDelay; } } return !disposed; } - }, "ActiveMQ Failover Worker: "+System.identityHashCode(this)); + }, "ActiveMQ Failover Worker: " + System.identityHashCode(this)); } final void handleTransportFailure(IOException e) throws InterruptedException { - if (transportListener != null){ + if (transportListener != null) { transportListener.transportInterupted(); } synchronized (reconnectMutex) { @@ -268,11 +265,11 @@ public class FailoverTransport implements CompositeTransport { if (connectedTransport != null) { connectedTransport.stop(); - connectedTransport=null; + connectedTransport = null; } reconnectMutex.notifyAll(); } - synchronized(sleepMutex){ + synchronized (sleepMutex) { sleepMutex.notifyAll(); } reconnectTask.shutdown(); @@ -329,45 +326,44 @@ public class FailoverTransport implements CompositeTransport { /** * @return Returns the randomize. */ - public boolean isRandomize(){ + public boolean isRandomize() { return randomize; } /** * @param randomize The randomize to set. */ - public void setRandomize(boolean randomize){ - this.randomize=randomize; + public void setRandomize(boolean randomize) { + this.randomize = randomize; } public void oneway(Object o) throws IOException { - Command command = (Command) o; + Command command = (Command)o; Exception error = null; try { synchronized (reconnectMutex) { // Keep trying until the message is sent. - for (int i = 0;!disposed; i++) { + for (int i = 0; !disposed; i++) { try { // Wait for transport to be connected. - while (connectedTransport == null && !disposed && connectionFailure==null ) { + while (connectedTransport == null && !disposed && connectionFailure == null) { log.trace("Waiting for transport to reconnect."); try { reconnectMutex.wait(1000); - } - catch (InterruptedException e) { + } catch (InterruptedException e) { Thread.currentThread().interrupt(); log.debug("Interupted: " + e, e); } } - if( connectedTransport==null ) { + if (connectedTransport == null) { // Previous loop may have exited due to use being // disposed. if (disposed) { error = new IOException("Transport disposed."); - } else if (connectionFailure!=null) { + } else if (connectionFailure != null) { error = connectionFailure; } else { error = new IOException("Unexpected failure."); @@ -380,51 +376,53 @@ public class FailoverTransport implements CompositeTransport { // then hold it in the requestMap so that we can replay // it later. Tracked tracked = stateTracker.track(command); - if( tracked!=null && tracked.isWaitingForResponse() ) { + if (tracked != null && tracked.isWaitingForResponse()) { requestMap.put(Integer.valueOf(command.getCommandId()), tracked); - } else if ( tracked==null && command.isResponseRequired()) { + } else if (tracked == null && command.isResponseRequired()) { requestMap.put(Integer.valueOf(command.getCommandId()), command); } - + // Send the message. try { connectedTransport.oneway(command); } catch (IOException e) { - - // If the command was not tracked.. we will retry in this method - if( tracked==null ) { - - // since we will retry in this method.. take it out of the request - // map so that it is not sent 2 times on recovery - if( command.isResponseRequired() ) { - requestMap.remove(Integer.valueOf(command.getCommandId())); - } - - // Rethrow the exception so it will handled by the outer catch + + // If the command was not tracked.. we will retry in + // this method + if (tracked == null) { + + // since we will retry in this method.. take it + // out of the request + // map so that it is not sent 2 times on + // recovery + if (command.isResponseRequired()) { + requestMap.remove(Integer.valueOf(command.getCommandId())); + } + + // Rethrow the exception so it will handled by + // the outer catch throw e; - } - + } + } - + return; - } - catch (IOException e) { + } catch (IOException e) { log.debug("Send oneway attempt: " + i + " failed."); handleTransportFailure(e); } } } - } - catch (InterruptedException e) { + } catch (InterruptedException e) { // Some one may be trying to stop our thread. Thread.currentThread().interrupt(); throw new InterruptedIOException(); } - if(!disposed){ - if(error!=null){ - if(error instanceof IOException) - throw (IOException) error; + if (!disposed) { + if (error != null) { + if (error instanceof IOException) + throw (IOException)error; throw IOExceptionSupport.create(error); } } @@ -437,14 +435,14 @@ public class FailoverTransport implements CompositeTransport { public Object request(Object command) throws IOException { throw new AssertionError("Unsupported Method"); } - - public Object request(Object command,int timeout) throws IOException { + + public Object request(Object command, int timeout) throws IOException { throw new AssertionError("Unsupported Method"); } public void add(URI u[]) { for (int i = 0; i < u.length; i++) { - if( !uris.contains(u[i]) ) + if (!uris.contains(u[i])) uris.add(u[i]); } reconnect(); @@ -456,20 +454,19 @@ public class FailoverTransport implements CompositeTransport { } reconnect(); } - - public void add(String u){ - try { - URI uri = new URI(u); - if (!uris.contains(uri)) - uris.add(uri); - reconnect(); - }catch(Exception e){ + public void add(String u) { + try { + URI uri = new URI(u); + if (!uris.contains(uri)) + uris.add(uri); + + reconnect(); + } catch (Exception e) { log.error("Failed to parse URI: " + u); } } - public void reconnect() { log.debug("Waking up reconnect task"); try { @@ -479,17 +476,17 @@ public class FailoverTransport implements CompositeTransport { } } - private ArrayList getConnectList(){ - ArrayList l=new ArrayList(uris); - if (randomize){ + private ArrayList getConnectList() { + ArrayList l = new ArrayList(uris); + if (randomize) { // Randomly, reorder the list by random swapping - Random r=new Random(); + Random r = new Random(); r.setSeed(System.currentTimeMillis()); - for (int i=0;inow ) { - if( closestReconnectDate==0 || fanoutHandler.reconnectDate < closestReconnectDate ) { + if (fanoutHandler.reconnectDate != 0 && fanoutHandler.reconnectDate > now) { + if (closestReconnectDate == 0 || fanoutHandler.reconnectDate < closestReconnectDate) { closestReconnectDate = fanoutHandler.reconnectDate; } continue; } - + URI uri = fanoutHandler.uri; try { - log.debug("Stopped: "+this); + log.debug("Stopped: " + this); log.debug("Attempting connect to: " + uri); Transport t = TransportFactory.compositeConnect(uri); log.debug("Connection established"); fanoutHandler.transport = t; fanoutHandler.reconnectDelay = 10; fanoutHandler.connectFailures = 0; - if( primary == null ) { + if (primary == null) { primary = fanoutHandler; } t.setTransportListener(fanoutHandler); @@ -215,50 +214,48 @@ public class FanoutTransport implements CompositeTransport { if (started) { restoreTransport(fanoutHandler); } - } - catch (Exception e) { + } catch (Exception e) { log.debug("Connect fail to: " + uri + ", reason: " + e); - + if (maxReconnectAttempts > 0 && ++fanoutHandler.connectFailures >= maxReconnectAttempts) { log.error("Failed to connect to transport after: " + fanoutHandler.connectFailures + " attempt(s)"); connectionFailure = e; reconnectMutex.notifyAll(); return false; } else { - + if (useExponentialBackOff) { // Exponential increment of reconnect delay. fanoutHandler.reconnectDelay *= backOffMultiplier; if (fanoutHandler.reconnectDelay > maxReconnectDelay) fanoutHandler.reconnectDelay = maxReconnectDelay; } - + fanoutHandler.reconnectDate = now + fanoutHandler.reconnectDelay; - - if( closestReconnectDate==0 || fanoutHandler.reconnectDate < closestReconnectDate ) { + + if (closestReconnectDate == 0 || fanoutHandler.reconnectDate < closestReconnectDate) { closestReconnectDate = fanoutHandler.reconnectDate; } } } } - if (transports.size() == connectedCount || disposed ) { + if (transports.size() == connectedCount || disposed) { reconnectMutex.notifyAll(); return false; } - + } } - + } try { long reconnectDelay = closestReconnectDate - System.currentTimeMillis(); - if(reconnectDelay>0) { + if (reconnectDelay > 0) { log.debug("Waiting " + reconnectDelay + " ms before attempting connection. "); Thread.sleep(reconnectDelay); } - } - catch (InterruptedException e1) { + } catch (InterruptedException e1) { Thread.currentThread().interrupt(); } return true; @@ -271,8 +268,8 @@ public class FanoutTransport implements CompositeTransport { return; started = true; for (Iterator iter = transports.iterator(); iter.hasNext();) { - FanoutTransportHandler th = (FanoutTransportHandler) iter.next(); - if( th.transport != null ) { + FanoutTransportHandler th = (FanoutTransportHandler)iter.next(); + if (th.transport != null) { restoreTransport(th); } } @@ -281,21 +278,21 @@ public class FanoutTransport implements CompositeTransport { public void stop() throws Exception { synchronized (reconnectMutex) { - ServiceStopper ss = new ServiceStopper(); - + ServiceStopper ss = new ServiceStopper(); + if (!started) return; started = false; disposed = true; for (Iterator iter = transports.iterator(); iter.hasNext();) { - FanoutTransportHandler th = (FanoutTransportHandler) iter.next(); - if( th.transport != null ) { - ss.stop(th.transport); + FanoutTransportHandler th = (FanoutTransportHandler)iter.next(); + if (th.transport != null) { + ss.stop(th.transport); } } - - log.debug("Stopped: "+this); + + log.debug("Stopped: " + this); ss.throwFirstException(); } reconnectTask.shutdown(); @@ -334,50 +331,50 @@ public class FanoutTransport implements CompositeTransport { } public void oneway(Object o) throws IOException { - final Command command = (Command) o; + final Command command = (Command)o; try { synchronized (reconnectMutex) { - + // If it was a request and it was not being tracked by // the state tracker, // then hold it in the requestMap so that we can replay // it later. boolean fanout = isFanoutCommand(command); - if (stateTracker.track(command)==null && command.isResponseRequired() ) { + if (stateTracker.track(command) == null && command.isResponseRequired()) { int size = fanout ? minAckCount : 1; requestMap.put(new Integer(command.getCommandId()), new RequestCounter(command, size)); } // Wait for transport to be connected. - while (connectedCount != minAckCount && !disposed && connectionFailure==null ) { - log.debug("Waiting for at least "+minAckCount+" transports to be connected."); + while (connectedCount != minAckCount && !disposed && connectionFailure == null) { + log.debug("Waiting for at least " + minAckCount + " transports to be connected."); reconnectMutex.wait(1000); } // Still not fully connected. - if( connectedCount != minAckCount ) { + if (connectedCount != minAckCount) { Exception error; - + // Throw the right kind of error.. if (disposed) { error = new IOException("Transport disposed."); - } else if (connectionFailure!=null) { + } else if (connectionFailure != null) { error = connectionFailure; } else { error = new IOException("Unexpected failure."); } - - if( error instanceof IOException ) + + if (error instanceof IOException) throw (IOException)error; throw IOExceptionSupport.create(error); } - + // Send the message. - if( fanout ) { + if (fanout) { for (Iterator iter = transports.iterator(); iter.hasNext();) { - FanoutTransportHandler th = (FanoutTransportHandler) iter.next(); - if( th.transport!=null ) { + FanoutTransportHandler th = (FanoutTransportHandler)iter.next(); + if (th.transport != null) { try { th.transport.oneway(command); } catch (IOException e) { @@ -394,7 +391,7 @@ public class FanoutTransport implements CompositeTransport { primary.onException(e); } } - + } } catch (InterruptedException e) { // Some one may be trying to stop our thread. @@ -408,10 +405,10 @@ public class FanoutTransport implements CompositeTransport { * @return */ private boolean isFanoutCommand(Command command) { - if( command.isMessage() ) { + if (command.isMessage()) { return ((Message)command).getDestination().isTopic(); - } - if( command.getDataStructureType() == ConsumerInfo.DATA_STRUCTURE_TYPE ) { + } + if (command.getDataStructureType() == ConsumerInfo.DATA_STRUCTURE_TYPE) { return false; } return true; @@ -424,8 +421,8 @@ public class FanoutTransport implements CompositeTransport { public Object request(Object command) throws IOException { throw new AssertionError("Unsupported Method"); } - - public Object request(Object command,int timeout) throws IOException { + + public Object request(Object command, int timeout) throws IOException { throw new AssertionError("Unsupported Method"); } @@ -451,67 +448,67 @@ public class FanoutTransport implements CompositeTransport { if (target.isAssignableFrom(getClass())) { return this; } - + synchronized (reconnectMutex) { for (Iterator iter = transports.iterator(); iter.hasNext();) { - FanoutTransportHandler th = (FanoutTransportHandler) iter.next(); - if( th.transport!=null ) { + FanoutTransportHandler th = (FanoutTransportHandler)iter.next(); + if (th.transport != null) { Object rc = th.transport.narrow(target); - if( rc !=null ) + if (rc != null) return rc; } } } - + return null; } protected void restoreTransport(FanoutTransportHandler th) throws Exception, IOException { th.transport.start(); - stateTracker.setRestoreConsumers(th.transport==primary); + stateTracker.setRestoreConsumers(th.transport == primary); stateTracker.restore(th.transport); for (Iterator iter2 = requestMap.values().iterator(); iter2.hasNext();) { - RequestCounter rc = (RequestCounter) iter2.next(); + RequestCounter rc = (RequestCounter)iter2.next(); th.transport.oneway(rc.command); } } public void add(URI uris[]) { - + synchronized (reconnectMutex) { for (int i = 0; i < uris.length; i++) { URI uri = uris[i]; - - boolean match=false; + + boolean match = false; for (Iterator iter = transports.iterator(); iter.hasNext();) { - FanoutTransportHandler th = (FanoutTransportHandler) iter.next(); - if( th.uri.equals(uri)) { - match=true; + FanoutTransportHandler th = (FanoutTransportHandler)iter.next(); + if (th.uri.equals(uri)) { + match = true; break; } } - if( !match ) { + if (!match) { FanoutTransportHandler th = new FanoutTransportHandler(uri); transports.add(th); reconnect(); } } } - + } - + public void remove(URI uris[]) { - + synchronized (reconnectMutex) { for (int i = 0; i < uris.length; i++) { URI uri = uris[i]; - - boolean match=false; + + boolean match = false; for (Iterator iter = transports.iterator(); iter.hasNext();) { - FanoutTransportHandler th = (FanoutTransportHandler) iter.next(); - if( th.uri.equals(uri)) { - if( th.transport!=null ) { + FanoutTransportHandler th = (FanoutTransportHandler)iter.next(); + if (th.uri.equals(uri)) { + if (th.transport != null) { ServiceSupport.dispose(th.transport); connectedCount--; } @@ -521,17 +518,17 @@ public class FanoutTransport implements CompositeTransport { } } } - + } - public String getRemoteAddress() { - if(primary != null){ - if(primary.transport != null){ - return primary.transport.getRemoteAddress(); - } - } - return null; - } + public String getRemoteAddress() { + if (primary != null) { + if (primary.transport != null) { + return primary.transport.getRemoteAddress(); + } + } + return null; + } protected void transportListenerOnCommand(Command command) { if (transportListener != null) { @@ -539,8 +536,7 @@ public class FanoutTransport implements CompositeTransport { } } - - public boolean isFaultTolerant(){ + public boolean isFaultTolerant() { return true; } } diff --git a/activemq-core/src/main/java/org/apache/activemq/transport/fanout/FanoutTransportFactory.java b/activemq-core/src/main/java/org/apache/activemq/transport/fanout/FanoutTransportFactory.java index b1a277653f..56e832cf97 100755 --- a/activemq-core/src/main/java/org/apache/activemq/transport/fanout/FanoutTransportFactory.java +++ b/activemq-core/src/main/java/org/apache/activemq/transport/fanout/FanoutTransportFactory.java @@ -39,37 +39,37 @@ public class FanoutTransportFactory extends TransportFactory { public Transport doConnect(URI location) throws IOException { try { Transport transport = createTransport(location); - transport = new MutexTransport(transport); + transport = new MutexTransport(transport); transport = new ResponseCorrelator(transport); return transport; } catch (URISyntaxException e) { - throw new IOException("Invalid location: "+location); + throw new IOException("Invalid location: " + location); } } - + public Transport doCompositeConnect(URI location) throws IOException { try { return createTransport(location); } catch (URISyntaxException e) { - throw new IOException("Invalid location: "+location); + throw new IOException("Invalid location: " + location); } } /** * @param location - * @return + * @return * @throws IOException - * @throws URISyntaxException + * @throws URISyntaxException */ public Transport createTransport(URI location) throws IOException, URISyntaxException { - + CompositeData compositData = URISupport.parseComposite(location); Map parameters = new HashMap(compositData.getParameters()); DiscoveryTransport transport = new DiscoveryTransport(createTransport(parameters)); - + DiscoveryAgent discoveryAgent = DiscoveryAgentFactory.createDiscoveryAgent(compositData.getComponents()[0]); transport.setDiscoveryAgent(discoveryAgent); - + return transport; } @@ -80,8 +80,8 @@ public class FanoutTransportFactory extends TransportFactory { return transport; } - public TransportServer doBind(String brokerId,URI location) throws IOException { - throw new IOException("Invalid server URI: "+location); + public TransportServer doBind(String brokerId, URI location) throws IOException { + throw new IOException("Invalid server URI: " + location); } } diff --git a/activemq-core/src/main/java/org/apache/activemq/transport/mock/MockTransport.java b/activemq-core/src/main/java/org/apache/activemq/transport/mock/MockTransport.java index cf90d2dfc6..49e48d604b 100644 --- a/activemq-core/src/main/java/org/apache/activemq/transport/mock/MockTransport.java +++ b/activemq-core/src/main/java/org/apache/activemq/transport/mock/MockTransport.java @@ -25,7 +25,6 @@ import org.apache.activemq.transport.Transport; import org.apache.activemq.transport.TransportFilter; import org.apache.activemq.transport.TransportListener; - /** * @version $Revision: 1.5 $ */ @@ -48,15 +47,14 @@ public class MockTransport extends DefaultTransportListener implements Transport getNext().setTransportListener(this); } - /** * @see org.apache.activemq.Service#start() * @throws IOException if the next channel has not been set. */ public void start() throws Exception { - if( getNext() == null ) + if (getNext() == null) throw new IOException("The next channel has not been set."); - if( transportListener == null ) + if (transportListener == null) throw new IOException("The command listener has not been set."); getNext().start(); } @@ -66,7 +64,7 @@ public class MockTransport extends DefaultTransportListener implements Transport */ public void stop() throws Exception { getNext().stop(); - } + } public void onCommand(Object command) { getTransportListener().onCommand(command); @@ -85,7 +83,7 @@ public class MockTransport extends DefaultTransportListener implements Transport synchronized public TransportListener getTransportListener() { return transportListener; } - + public String toString() { return getNext().toString(); } @@ -101,8 +99,8 @@ public class MockTransport extends DefaultTransportListener implements Transport public Object request(Object command) throws IOException { return getNext().request(command); } - - public Object request(Object command,int timeout) throws IOException { + + public Object request(Object command, int timeout) throws IOException { return getNext().request(command, timeout); } @@ -111,7 +109,7 @@ public class MockTransport extends DefaultTransportListener implements Transport } public Object narrow(Class target) { - if( target.isAssignableFrom(getClass()) ) { + if (target.isAssignableFrom(getClass())) { return this; } return getNext().narrow(target); @@ -127,15 +125,15 @@ public class MockTransport extends DefaultTransportListener implements Transport setNext(filter); } - public String getRemoteAddress() { - return getNext().getRemoteAddress(); - } + public String getRemoteAddress() { + return getNext().getRemoteAddress(); + } /** * @see org.apache.activemq.transport.Transport#isFaultTolerant() */ - public boolean isFaultTolerant(){ - return getNext().isFaultTolerant(); - } - + public boolean isFaultTolerant() { + return getNext().isFaultTolerant(); + } + } diff --git a/activemq-core/src/main/java/org/apache/activemq/transport/mock/MockTransportFactory.java b/activemq-core/src/main/java/org/apache/activemq/transport/mock/MockTransportFactory.java index c389137858..34d5b14ee3 100755 --- a/activemq-core/src/main/java/org/apache/activemq/transport/mock/MockTransportFactory.java +++ b/activemq-core/src/main/java/org/apache/activemq/transport/mock/MockTransportFactory.java @@ -33,27 +33,27 @@ public class MockTransportFactory extends TransportFactory { public Transport doConnect(URI location) throws URISyntaxException, Exception { Transport transport = createTransport(URISupport.parseComposite(location)); - transport = new MutexTransport(transport); + transport = new MutexTransport(transport); transport = new ResponseCorrelator(transport); return transport; } - + public Transport doCompositeConnect(URI location) throws URISyntaxException, Exception { return createTransport(URISupport.parseComposite(location)); } - + /** * @param location - * @return - * @throws Exception + * @return + * @throws Exception */ public Transport createTransport(CompositeData compositData) throws Exception { - MockTransport transport = new MockTransport( TransportFactory.compositeConnect(compositData.getComponents()[0]) ); + MockTransport transport = new MockTransport(TransportFactory.compositeConnect(compositData.getComponents()[0])); IntrospectionSupport.setProperties(transport, compositData.getParameters()); return transport; } - public TransportServer doBind(String brokerId,URI location) throws IOException { + public TransportServer doBind(String brokerId, URI location) throws IOException { throw new IOException("This protocol does not support being bound."); } diff --git a/activemq-core/src/main/java/org/apache/activemq/transport/nio/NIOInputStream.java b/activemq-core/src/main/java/org/apache/activemq/transport/nio/NIOInputStream.java index f16742ff67..81ab1f43ab 100644 --- a/activemq-core/src/main/java/org/apache/activemq/transport/nio/NIOInputStream.java +++ b/activemq-core/src/main/java/org/apache/activemq/transport/nio/NIOInputStream.java @@ -20,54 +20,55 @@ import java.io.IOException; import java.io.InputStream; import java.nio.BufferUnderflowException; import java.nio.ByteBuffer; + /** * An optimized buffered input stream for Tcp * * @version $Revision: 1.1.1.1 $ */ public class NIOInputStream extends InputStream { - + protected int count; protected int position; - private final ByteBuffer in; + private final ByteBuffer in; - public NIOInputStream(ByteBuffer in){ - this.in = in; + public NIOInputStream(ByteBuffer in) { + this.in = in; } public int read() throws IOException { - try { - int rc = in.get()& 0xff; - return rc; - } catch ( BufferUnderflowException e ) { - return -1; - } + try { + int rc = in.get() & 0xff; + return rc; + } catch (BufferUnderflowException e) { + return -1; + } } - public int read(byte b[],int off,int len) throws IOException{ - if( in.hasRemaining() ) { - int rc = Math.min(len, in.remaining()); - in.get(b, off, rc); - return rc; - } else { - return len == 0 ? 0 : -1; - } + public int read(byte b[], int off, int len) throws IOException { + if (in.hasRemaining()) { + int rc = Math.min(len, in.remaining()); + in.get(b, off, rc); + return rc; + } else { + return len == 0 ? 0 : -1; + } } - public long skip(long n) throws IOException{ - int rc = Math.min((int)n, in.remaining()); - in.position(in.position()+rc); + public long skip(long n) throws IOException { + int rc = Math.min((int)n, in.remaining()); + in.position(in.position() + rc); return rc; } - public int available() throws IOException{ + public int available() throws IOException { return in.remaining(); } - public boolean markSupported(){ + public boolean markSupported() { return false; } - public void close() throws IOException{ + public void close() throws IOException { } } diff --git a/activemq-core/src/main/java/org/apache/activemq/transport/nio/NIOOutputStream.java b/activemq-core/src/main/java/org/apache/activemq/transport/nio/NIOOutputStream.java index 9e1a7fa91f..ce622a6a2c 100644 --- a/activemq-core/src/main/java/org/apache/activemq/transport/nio/NIOOutputStream.java +++ b/activemq-core/src/main/java/org/apache/activemq/transport/nio/NIOOutputStream.java @@ -25,24 +25,24 @@ import java.nio.channels.WritableByteChannel; /** * An optimized buffered outputstream for Tcp - * + * * @version $Revision: 1.1.1.1 $ */ public class NIOOutputStream extends OutputStream { - - private final static int BUFFER_SIZE = 8192; - private final WritableByteChannel out; + private final static int BUFFER_SIZE = 8192; + + private final WritableByteChannel out; private final byte[] buffer; - private final ByteBuffer byteBuffer; - + private final ByteBuffer byteBuffer; + private int count; private boolean closed; /** * Constructor - * + * * @param out */ public NIOOutputStream(WritableByteChannel out) { @@ -50,16 +50,16 @@ public class NIOOutputStream extends OutputStream { } /** - * Creates a new buffered output stream to write data to the specified underlying output stream with the specified - * buffer size. - * - * @param out the underlying output stream. + * Creates a new buffered output stream to write data to the specified + * underlying output stream with the specified buffer size. + * + * @param out the underlying output stream. * @param size the buffer size. * @throws IllegalArgumentException if size <= 0. */ public NIOOutputStream(WritableByteChannel out, int size) { this.out = out; - if (size <= 0) { + if (size <= 0) { throw new IllegalArgumentException("Buffer size <= 0"); } buffer = new byte[size]; @@ -68,7 +68,7 @@ public class NIOOutputStream extends OutputStream { /** * write a byte on to the stream - * + * * @param b - byte to write * @throws IOException */ @@ -77,14 +77,13 @@ public class NIOOutputStream extends OutputStream { if (availableBufferToWrite() < 1) { flush(); } - buffer[count++] = (byte) b; + buffer[count++] = (byte)b; } - /** * write a byte array to the stream - * - * @param b the byte buffer + * + * @param b the byte buffer * @param off the offset into the buffer * @param len the length of data to write * @throws IOException @@ -97,23 +96,22 @@ public class NIOOutputStream extends OutputStream { if (buffer.length >= len) { System.arraycopy(b, off, buffer, count, len); count += len; - } - else { - write( ByteBuffer.wrap(b, off, len)); + } else { + write(ByteBuffer.wrap(b, off, len)); } } - /** - * flush the data to the output stream - * This doesn't call flush on the underlying outputstream, because - * Tcp is particularly efficent at doing this itself .... - * + /** + * flush the data to the output stream This doesn't call flush on the + * underlying outputstream, because Tcp is particularly efficent at doing + * this itself .... + * * @throws IOException */ public void flush() throws IOException { if (count > 0 && out != null) { - byteBuffer.position(0); - byteBuffer.limit(count); + byteBuffer.position(0); + byteBuffer.limit(count); write(byteBuffer); count = 0; } @@ -121,7 +119,7 @@ public class NIOOutputStream extends OutputStream { /** * close this stream - * + * * @throws IOException */ public void close() throws IOException { @@ -129,10 +127,9 @@ public class NIOOutputStream extends OutputStream { closed = true; } - /** * Checks that the stream has not been closed - * + * * @throws IOException */ protected void checkClosed() throws IOException { @@ -147,35 +144,36 @@ public class NIOOutputStream extends OutputStream { private int availableBufferToWrite() { return buffer.length - count; } - + protected void write(ByteBuffer data) throws IOException { - int remaining = data.remaining(); - int lastRemaining = remaining-1; - long delay=1; - while( remaining > 0 ) { - - // We may need to do a little bit of sleeping to avoid a busy loop. - // Slow down if no data was written out.. - if( remaining == lastRemaining ) { - try { + int remaining = data.remaining(); + int lastRemaining = remaining - 1; + long delay = 1; + while (remaining > 0) { + + // We may need to do a little bit of sleeping to avoid a busy loop. + // Slow down if no data was written out.. + if (remaining == lastRemaining) { + try { // Use exponential rollback to increase sleep time. Thread.sleep(delay); delay *= 2; - if( delay > 1000 ) { + if (delay > 1000) { delay = 1000; } } catch (InterruptedException e) { throw new InterruptedIOException(); - } - } else { - delay = 1; - } - lastRemaining = remaining; - - // Since the write is non-blocking, all the data may not have been written. - out.write( data ); - remaining = data.remaining(); - } - } - + } + } else { + delay = 1; + } + lastRemaining = remaining; + + // Since the write is non-blocking, all the data may not have been + // written. + out.write(data); + remaining = data.remaining(); + } + } + } diff --git a/activemq-core/src/main/java/org/apache/activemq/transport/nio/NIOTransport.java b/activemq-core/src/main/java/org/apache/activemq/transport/nio/NIOTransport.java index 8aeb2c07a7..0fd67e23b6 100644 --- a/activemq-core/src/main/java/org/apache/activemq/transport/nio/NIOTransport.java +++ b/activemq-core/src/main/java/org/apache/activemq/transport/nio/NIOTransport.java @@ -43,113 +43,112 @@ import org.apache.activemq.util.ServiceStopper; */ public class NIOTransport extends TcpTransport { - //private static final Log log = LogFactory.getLog(NIOTransport.class); - private SocketChannel channel; - private SelectorSelection selection; - private ByteBuffer inputBuffer; - private ByteBuffer currentBuffer; - private int nextFrameSize; + // private static final Log log = LogFactory.getLog(NIOTransport.class); + private SocketChannel channel; + private SelectorSelection selection; + private ByteBuffer inputBuffer; + private ByteBuffer currentBuffer; + private int nextFrameSize; - public NIOTransport(WireFormat wireFormat, SocketFactory socketFactory, URI remoteLocation, URI localLocation) throws UnknownHostException, IOException { - super(wireFormat, socketFactory, remoteLocation, localLocation); - } + public NIOTransport(WireFormat wireFormat, SocketFactory socketFactory, URI remoteLocation, URI localLocation) throws UnknownHostException, IOException { + super(wireFormat, socketFactory, remoteLocation, localLocation); + } - public NIOTransport(WireFormat wireFormat, Socket socket) throws IOException { - super(wireFormat, socket); - } + public NIOTransport(WireFormat wireFormat, Socket socket) throws IOException { + super(wireFormat, socket); + } - protected void initializeStreams() throws IOException { - channel = socket.getChannel(); - channel.configureBlocking(false); - - // listen for events telling us when the socket is readable. - selection = SelectorManager.getInstance().register(channel, - new SelectorManager.Listener() { - public void onSelect(SelectorSelection selection) { - serviceRead(); - } - public void onError(SelectorSelection selection, Throwable error) { - if( error instanceof IOException ) { - onException((IOException) error); - } else { - onException(IOExceptionSupport.create(error)); - } - } - }); - - // Send the data via the channel -// inputBuffer = ByteBuffer.allocateDirect(8*1024); - inputBuffer = ByteBuffer.allocate(8*1024); + protected void initializeStreams() throws IOException { + channel = socket.getChannel(); + channel.configureBlocking(false); + + // listen for events telling us when the socket is readable. + selection = SelectorManager.getInstance().register(channel, new SelectorManager.Listener() { + public void onSelect(SelectorSelection selection) { + serviceRead(); + } + + public void onError(SelectorSelection selection, Throwable error) { + if (error instanceof IOException) { + onException((IOException)error); + } else { + onException(IOExceptionSupport.create(error)); + } + } + }); + + // Send the data via the channel + // inputBuffer = ByteBuffer.allocateDirect(8*1024); + inputBuffer = ByteBuffer.allocate(8 * 1024); currentBuffer = inputBuffer; - nextFrameSize=-1; + nextFrameSize = -1; currentBuffer.limit(4); - this.dataOut = new DataOutputStream(new NIOOutputStream(channel, 16*1024)); - - } - + this.dataOut = new DataOutputStream(new NIOOutputStream(channel, 16 * 1024)); + + } + private void serviceRead() { try { - while( true ) { - - - int readSize = channel.read(currentBuffer); - if( readSize == -1 ) { - onException(new EOFException()); - selection.close(); - break; - } - if( readSize==0 ) { - break; - } - - if( currentBuffer.hasRemaining() ) - continue; + while (true) { - // Are we trying to figure out the size of the next frame? - if( nextFrameSize==-1 ) { - assert inputBuffer == currentBuffer; + int readSize = channel.read(currentBuffer); + if (readSize == -1) { + onException(new EOFException()); + selection.close(); + break; + } + if (readSize == 0) { + break; + } + + if (currentBuffer.hasRemaining()) + continue; + + // Are we trying to figure out the size of the next frame? + if (nextFrameSize == -1) { + assert inputBuffer == currentBuffer; + + // If the frame is too big to fit in our direct byte buffer, + // Then allocate a non direct byte buffer of the right size + // for it. + inputBuffer.flip(); + nextFrameSize = inputBuffer.getInt() + 4; + if (nextFrameSize > inputBuffer.capacity()) { + currentBuffer = ByteBuffer.allocate(nextFrameSize); + currentBuffer.putInt(nextFrameSize); + } else { + inputBuffer.limit(nextFrameSize); + } + + } else { + currentBuffer.flip(); + + Object command = wireFormat.unmarshal(new DataInputStream(new NIOInputStream(currentBuffer))); + doConsume((Command)command); + + nextFrameSize = -1; + inputBuffer.clear(); + inputBuffer.limit(4); + currentBuffer = inputBuffer; + } - // If the frame is too big to fit in our direct byte buffer, - // Then allocate a non direct byte buffer of the right size for it. - inputBuffer.flip(); - nextFrameSize = inputBuffer.getInt()+4; - if( nextFrameSize > inputBuffer.capacity() ) { - currentBuffer = ByteBuffer.allocate(nextFrameSize); - currentBuffer.putInt(nextFrameSize); - } else { - inputBuffer.limit(nextFrameSize); - } - - } else { - currentBuffer.flip(); - - Object command = wireFormat.unmarshal(new DataInputStream(new NIOInputStream(currentBuffer))); - doConsume((Command) command); - - nextFrameSize=-1; - inputBuffer.clear(); - inputBuffer.limit(4); - currentBuffer = inputBuffer; - } - } - + } catch (IOException e) { onException(e); } catch (Throwable e) { - onException(IOExceptionSupport.create(e)); + onException(IOExceptionSupport.create(e)); } } - - protected void doStart() throws Exception { + protected void doStart() throws Exception { connect(); selection.setInterestOps(SelectionKey.OP_READ); selection.enable(); } - protected void doStop(ServiceStopper stopper) throws Exception { - selection.disable(); - super.doStop(stopper); - } + protected void doStop(ServiceStopper stopper) throws Exception { + selection.disable(); + super.doStop(stopper); + } } diff --git a/activemq-core/src/main/java/org/apache/activemq/transport/nio/NIOTransportFactory.java b/activemq-core/src/main/java/org/apache/activemq/transport/nio/NIOTransportFactory.java index 9f8f37a9d4..eac5d76df4 100644 --- a/activemq-core/src/main/java/org/apache/activemq/transport/nio/NIOTransportFactory.java +++ b/activemq-core/src/main/java/org/apache/activemq/transport/nio/NIOTransportFactory.java @@ -37,73 +37,74 @@ import org.apache.activemq.transport.tcp.TcpTransportFactory; import org.apache.activemq.transport.tcp.TcpTransportServer; public class NIOTransportFactory extends TcpTransportFactory { - - protected TcpTransportServer createTcpTransportServer(URI location, ServerSocketFactory serverSocketFactory) throws IOException, URISyntaxException { - return new TcpTransportServer(this, location, serverSocketFactory) { - protected Transport createTransport(Socket socket, WireFormat format) throws IOException { - return new NIOTransport(format,socket); - } - }; - } - - protected TcpTransport createTcpTransport(WireFormat wf, SocketFactory socketFactory, URI location, URI localLocation) throws UnknownHostException, IOException { - return new NIOTransport(wf, socketFactory, location, localLocation); - } - - protected ServerSocketFactory createServerSocketFactory() { - return new ServerSocketFactory() { - public ServerSocket createServerSocket(int port) throws IOException { - ServerSocketChannel serverSocketChannel = ServerSocketChannel.open(); - serverSocketChannel.socket().bind(new InetSocketAddress(port)); - return serverSocketChannel.socket(); - } - public ServerSocket createServerSocket(int port, int backlog) throws IOException { - ServerSocketChannel serverSocketChannel = ServerSocketChannel.open(); - serverSocketChannel.socket().bind(new InetSocketAddress(port), backlog); - return serverSocketChannel.socket(); - } - public ServerSocket createServerSocket(int port, int backlog, InetAddress ifAddress) throws IOException { - ServerSocketChannel serverSocketChannel = ServerSocketChannel.open(); - serverSocketChannel.socket().bind(new InetSocketAddress(ifAddress, port), backlog); - return serverSocketChannel.socket(); - } + protected TcpTransportServer createTcpTransportServer(URI location, ServerSocketFactory serverSocketFactory) throws IOException, URISyntaxException { + return new TcpTransportServer(this, location, serverSocketFactory) { + protected Transport createTransport(Socket socket, WireFormat format) throws IOException { + return new NIOTransport(format, socket); + } }; } - + + protected TcpTransport createTcpTransport(WireFormat wf, SocketFactory socketFactory, URI location, URI localLocation) throws UnknownHostException, IOException { + return new NIOTransport(wf, socketFactory, location, localLocation); + } + + protected ServerSocketFactory createServerSocketFactory() { + return new ServerSocketFactory() { + public ServerSocket createServerSocket(int port) throws IOException { + ServerSocketChannel serverSocketChannel = ServerSocketChannel.open(); + serverSocketChannel.socket().bind(new InetSocketAddress(port)); + return serverSocketChannel.socket(); + } + + public ServerSocket createServerSocket(int port, int backlog) throws IOException { + ServerSocketChannel serverSocketChannel = ServerSocketChannel.open(); + serverSocketChannel.socket().bind(new InetSocketAddress(port), backlog); + return serverSocketChannel.socket(); + } + + public ServerSocket createServerSocket(int port, int backlog, InetAddress ifAddress) throws IOException { + ServerSocketChannel serverSocketChannel = ServerSocketChannel.open(); + serverSocketChannel.socket().bind(new InetSocketAddress(ifAddress, port), backlog); + return serverSocketChannel.socket(); + } + }; + } + protected SocketFactory createSocketFactory() { return new SocketFactory() { - public Socket createSocket() throws IOException { - SocketChannel channel = SocketChannel.open(); - return channel.socket(); - } - - public Socket createSocket(String host, int port) throws IOException, UnknownHostException { - SocketChannel channel = SocketChannel.open(); - channel.connect(new InetSocketAddress(host, port)); - return channel.socket(); - } + public Socket createSocket() throws IOException { + SocketChannel channel = SocketChannel.open(); + return channel.socket(); + } - public Socket createSocket(InetAddress address, int port) throws IOException { - SocketChannel channel = SocketChannel.open(); - channel.connect(new InetSocketAddress(address, port)); - return channel.socket(); - } + public Socket createSocket(String host, int port) throws IOException, UnknownHostException { + SocketChannel channel = SocketChannel.open(); + channel.connect(new InetSocketAddress(host, port)); + return channel.socket(); + } - public Socket createSocket(String address, int port, InetAddress localAddresss, int localPort) throws IOException, UnknownHostException { - SocketChannel channel = SocketChannel.open(); - channel.socket().bind(new InetSocketAddress(localAddresss, localPort)); - channel.connect(new InetSocketAddress(address, port)); - return channel.socket(); - } + public Socket createSocket(InetAddress address, int port) throws IOException { + SocketChannel channel = SocketChannel.open(); + channel.connect(new InetSocketAddress(address, port)); + return channel.socket(); + } - public Socket createSocket(InetAddress address, int port, InetAddress localAddresss, int localPort) throws IOException { - SocketChannel channel = SocketChannel.open(); - channel.socket().bind(new InetSocketAddress(localAddresss, localPort)); - channel.connect(new InetSocketAddress(address, port)); - return channel.socket(); - } + public Socket createSocket(String address, int port, InetAddress localAddresss, int localPort) throws IOException, UnknownHostException { + SocketChannel channel = SocketChannel.open(); + channel.socket().bind(new InetSocketAddress(localAddresss, localPort)); + channel.connect(new InetSocketAddress(address, port)); + return channel.socket(); + } + + public Socket createSocket(InetAddress address, int port, InetAddress localAddresss, int localPort) throws IOException { + SocketChannel channel = SocketChannel.open(); + channel.socket().bind(new InetSocketAddress(localAddresss, localPort)); + channel.connect(new InetSocketAddress(address, port)); + return channel.socket(); + } }; } } diff --git a/activemq-core/src/main/java/org/apache/activemq/transport/nio/SelectorManager.java b/activemq-core/src/main/java/org/apache/activemq/transport/nio/SelectorManager.java index d965d3d817..4bae4586d5 100644 --- a/activemq-core/src/main/java/org/apache/activemq/transport/nio/SelectorManager.java +++ b/activemq-core/src/main/java/org/apache/activemq/transport/nio/SelectorManager.java @@ -34,75 +34,78 @@ import java.util.concurrent.ThreadFactory; */ final public class SelectorManager { - static final public SelectorManager singleton = new SelectorManager(); - static SelectorManager getInstance() { - return singleton; - } - - public interface Listener { - public void onSelect(SelectorSelection selector); - public void onError(SelectorSelection selection, Throwable error); - } - - private Executor selectorExecutor = Executors.newCachedThreadPool(new ThreadFactory(){ - public Thread newThread(Runnable r) { - Thread rc = new Thread(r); - rc.setName("NIO Transport Thread"); - return rc; - }}); - private Executor channelExecutor = selectorExecutor; - private LinkedList freeWorkers = new LinkedList(); - private int maxChannelsPerWorker = 64; - - public synchronized SelectorSelection register(SocketChannel socketChannel, Listener listener) - throws IOException { + static final public SelectorManager singleton = new SelectorManager(); - SelectorWorker worker = null; - if (freeWorkers.size() > 0) { - worker = freeWorkers.getFirst(); - } else { - worker = new SelectorWorker(this); - freeWorkers.addFirst(worker); - } + static SelectorManager getInstance() { + return singleton; + } - SelectorSelection selection = new SelectorSelection(worker, socketChannel, listener); - return selection; - } + public interface Listener { + public void onSelect(SelectorSelection selector); - synchronized void onWorkerFullEvent(SelectorWorker worker) { - freeWorkers.remove(worker); - } + public void onError(SelectorSelection selection, Throwable error); + } - synchronized public void onWorkerEmptyEvent(SelectorWorker worker) { - freeWorkers.remove(worker); - } + private Executor selectorExecutor = Executors.newCachedThreadPool(new ThreadFactory() { + public Thread newThread(Runnable r) { + Thread rc = new Thread(r); + rc.setName("NIO Transport Thread"); + return rc; + } + }); + private Executor channelExecutor = selectorExecutor; + private LinkedList freeWorkers = new LinkedList(); + private int maxChannelsPerWorker = 64; - synchronized public void onWorkerNotFullEvent(SelectorWorker worker) { - freeWorkers.add(worker); - } + public synchronized SelectorSelection register(SocketChannel socketChannel, Listener listener) + throws IOException { - public Executor getChannelExecutor() { - return channelExecutor; - } + SelectorWorker worker = null; + if (freeWorkers.size() > 0) { + worker = freeWorkers.getFirst(); + } else { + worker = new SelectorWorker(this); + freeWorkers.addFirst(worker); + } - public void setChannelExecutor(Executor channelExecutor) { - this.channelExecutor = channelExecutor; - } + SelectorSelection selection = new SelectorSelection(worker, socketChannel, listener); + return selection; + } - public int getMaxChannelsPerWorker() { - return maxChannelsPerWorker; - } + synchronized void onWorkerFullEvent(SelectorWorker worker) { + freeWorkers.remove(worker); + } - public void setMaxChannelsPerWorker(int maxChannelsPerWorker) { - this.maxChannelsPerWorker = maxChannelsPerWorker; - } + synchronized public void onWorkerEmptyEvent(SelectorWorker worker) { + freeWorkers.remove(worker); + } - public Executor getSelectorExecutor() { - return selectorExecutor; - } + synchronized public void onWorkerNotFullEvent(SelectorWorker worker) { + freeWorkers.add(worker); + } - public void setSelectorExecutor(Executor selectorExecutor) { - this.selectorExecutor = selectorExecutor; - } + public Executor getChannelExecutor() { + return channelExecutor; + } + + public void setChannelExecutor(Executor channelExecutor) { + this.channelExecutor = channelExecutor; + } + + public int getMaxChannelsPerWorker() { + return maxChannelsPerWorker; + } + + public void setMaxChannelsPerWorker(int maxChannelsPerWorker) { + this.maxChannelsPerWorker = maxChannelsPerWorker; + } + + public Executor getSelectorExecutor() { + return selectorExecutor; + } + + public void setSelectorExecutor(Executor selectorExecutor) { + this.selectorExecutor = selectorExecutor; + } } diff --git a/activemq-core/src/main/java/org/apache/activemq/transport/nio/SelectorWorker.java b/activemq-core/src/main/java/org/apache/activemq/transport/nio/SelectorWorker.java index d906fe5550..3741308756 100644 --- a/activemq-core/src/main/java/org/apache/activemq/transport/nio/SelectorWorker.java +++ b/activemq-core/src/main/java/org/apache/activemq/transport/nio/SelectorWorker.java @@ -23,107 +23,106 @@ import java.util.Iterator; import java.util.Set; import java.util.concurrent.atomic.AtomicInteger; - public class SelectorWorker implements Runnable { - private final static AtomicInteger NEXT_ID = new AtomicInteger(); + private final static AtomicInteger NEXT_ID = new AtomicInteger(); - final SelectorManager manager; - final Selector selector; - final int id = NEXT_ID.getAndIncrement(); - final AtomicInteger useCounter = new AtomicInteger(); - final private int maxChannelsPerWorker; + final SelectorManager manager; + final Selector selector; + final int id = NEXT_ID.getAndIncrement(); + final AtomicInteger useCounter = new AtomicInteger(); + final private int maxChannelsPerWorker; + public SelectorWorker(SelectorManager manager) throws IOException { + this.manager = manager; + selector = Selector.open(); + maxChannelsPerWorker = manager.getMaxChannelsPerWorker(); + } - public SelectorWorker(SelectorManager manager) throws IOException { - this.manager = manager; - selector = Selector.open(); - maxChannelsPerWorker = manager.getMaxChannelsPerWorker(); - } - - void incrementUseCounter() { - int use = useCounter.getAndIncrement(); - if( use == 0 ) { - manager.getSelectorExecutor().execute(this); - } else if( use+1 == maxChannelsPerWorker ) { - manager.onWorkerFullEvent(this); - } - } + void incrementUseCounter() { + int use = useCounter.getAndIncrement(); + if (use == 0) { + manager.getSelectorExecutor().execute(this); + } else if (use + 1 == maxChannelsPerWorker) { + manager.onWorkerFullEvent(this); + } + } - void decrementUseCounter() { - int use = useCounter.getAndDecrement(); - if (use == 1) { - manager.onWorkerEmptyEvent(this); - } else if (use == maxChannelsPerWorker ) { - manager.onWorkerNotFullEvent(this); - } - } + void decrementUseCounter() { + int use = useCounter.getAndDecrement(); + if (use == 1) { + manager.onWorkerEmptyEvent(this); + } else if (use == maxChannelsPerWorker) { + manager.onWorkerNotFullEvent(this); + } + } - boolean isRunning() { - return useCounter.get()!=0; - } + boolean isRunning() { + return useCounter.get() != 0; + } - public void run() { + public void run() { - String origName = Thread.currentThread().getName(); - try { - Thread.currentThread().setName("Selector Worker: " + id); - while (isRunning()) { + String origName = Thread.currentThread().getName(); + try { + Thread.currentThread().setName("Selector Worker: " + id); + while (isRunning()) { - int count = selector.select(10); - if (count == 0) - continue; - - if (!isRunning()) - return; + int count = selector.select(10); + if (count == 0) + continue; - // Get a java.util.Set containing the SelectionKey objects - // for all channels that are ready for I/O. - Set keys = selector.selectedKeys(); + if (!isRunning()) + return; - for (Iterator i = keys.iterator(); i.hasNext();) { - final SelectionKey key = (SelectionKey) i.next(); - i.remove(); + // Get a java.util.Set containing the SelectionKey objects + // for all channels that are ready for I/O. + Set keys = selector.selectedKeys(); - final SelectorSelection s = (SelectorSelection) key.attachment(); - try { - s.disable(); - - // Kick off another thread to find newly selected keys while we process the - // currently selected keys - manager.getChannelExecutor().execute(new Runnable() { - public void run() { - try { - s.onSelect(); - s.enable(); - } catch (Throwable e) { - s.onError(e); - } - } - }); - - } catch ( Throwable e ) { - s.onError(e); - } - - } + for (Iterator i = keys.iterator(); i.hasNext();) { + final SelectionKey key = (SelectionKey)i.next(); + i.remove(); - } - } catch (IOException e) { - - // Don't accept any more slections - manager.onWorkerEmptyEvent(this); + final SelectorSelection s = (SelectorSelection)key.attachment(); + try { + s.disable(); - // Notify all the selections that the error occurred. - Set keys = selector.keys(); - for (Iterator i = keys.iterator(); i.hasNext();) { - SelectionKey key = (SelectionKey) i.next(); - SelectorSelection s = (SelectorSelection) key.attachment(); - s.onError(e); - } - - } finally { - Thread.currentThread().setName(origName); - } - } -} \ No newline at end of file + // Kick off another thread to find newly selected keys + // while we process the + // currently selected keys + manager.getChannelExecutor().execute(new Runnable() { + public void run() { + try { + s.onSelect(); + s.enable(); + } catch (Throwable e) { + s.onError(e); + } + } + }); + + } catch (Throwable e) { + s.onError(e); + } + + } + + } + } catch (IOException e) { + + // Don't accept any more slections + manager.onWorkerEmptyEvent(this); + + // Notify all the selections that the error occurred. + Set keys = selector.keys(); + for (Iterator i = keys.iterator(); i.hasNext();) { + SelectionKey key = (SelectionKey)i.next(); + SelectorSelection s = (SelectorSelection)key.attachment(); + s.onError(e); + } + + } finally { + Thread.currentThread().setName(origName); + } + } +} diff --git a/activemq-core/src/main/java/org/apache/activemq/transport/peer/PeerTransportFactory.java b/activemq-core/src/main/java/org/apache/activemq/transport/peer/PeerTransportFactory.java index c4042e79da..46aff436b5 100755 --- a/activemq-core/src/main/java/org/apache/activemq/transport/peer/PeerTransportFactory.java +++ b/activemq-core/src/main/java/org/apache/activemq/transport/peer/PeerTransportFactory.java @@ -43,10 +43,9 @@ public class PeerTransportFactory extends TransportFactory { final public static ConcurrentHashMap connectors = new ConcurrentHashMap(); final public static ConcurrentHashMap servers = new ConcurrentHashMap(); - + private IdGenerator idGenerator = new IdGenerator("peer-"); - public Transport doConnect(URI location) throws Exception { VMTransportFactory vmTransportFactory = createTransportFactory(location); return vmTransportFactory.doConnect(location); @@ -66,50 +65,50 @@ public class PeerTransportFactory extends TransportFactory { try { String group = location.getHost(); String broker = URISupport.stripPrefix(location.getPath(), "/"); - - if( group == null ) { + + if (group == null) { group = "default"; } - if (broker == null || broker.length()==0){ + if (broker == null || broker.length() == 0) { broker = idGenerator.generateSanitizedId(); } - + final Map brokerOptions = new HashMap(URISupport.parseParamters(location)); - if (!brokerOptions.containsKey("persistent")){ + if (!brokerOptions.containsKey("persistent")) { brokerOptions.put("persistent", "false"); } - - final URI finalLocation = new URI("vm://"+broker); + + final URI finalLocation = new URI("vm://" + broker); final String finalBroker = broker; final String finalGroup = group; VMTransportFactory rc = new VMTransportFactory() { public Transport doConnect(URI ignore) throws Exception { return super.doConnect(finalLocation); }; + public Transport doCompositeConnect(URI ignore) throws Exception { return super.doCompositeConnect(finalLocation); }; }; - rc.setBrokerFactoryHandler(new BrokerFactoryHandler(){ + rc.setBrokerFactoryHandler(new BrokerFactoryHandler() { public BrokerService createBroker(URI brokerURI) throws Exception { BrokerService service = new BrokerService(); IntrospectionSupport.setProperties(service, brokerOptions); service.setBrokerName(finalBroker); TransportConnector c = service.addConnector("tcp://localhost:0"); - c.setDiscoveryUri(new URI("multicast://"+finalGroup)); - service.addNetworkConnector("multicast://"+finalGroup); + c.setDiscoveryUri(new URI("multicast://" + finalGroup)); + service.addNetworkConnector("multicast://" + finalGroup); return service; } }); return rc; - + } catch (URISyntaxException e) { throw IOExceptionSupport.create(e); } } - - public TransportServer doBind(String brokerId,URI location) throws IOException { + public TransportServer doBind(String brokerId, URI location) throws IOException { throw new IOException("This protocol does not support being bound."); } diff --git a/activemq-core/src/main/java/org/apache/activemq/transport/reliable/ReliableTransport.java b/activemq-core/src/main/java/org/apache/activemq/transport/reliable/ReliableTransport.java index be00559292..983ed5bba0 100644 --- a/activemq-core/src/main/java/org/apache/activemq/transport/reliable/ReliableTransport.java +++ b/activemq-core/src/main/java/org/apache/activemq/transport/reliable/ReliableTransport.java @@ -54,8 +54,7 @@ public class ReliableTransport extends ResponseCorrelator { this.replayStrategy = replayStrategy; } - public ReliableTransport(Transport next, UdpTransport udpTransport) - throws IOException { + public ReliableTransport(Transport next, UdpTransport udpTransport) throws IOException { super(next, udpTransport.getSequenceGenerator()); this.udpTransport = udpTransport; this.replayer = udpTransport.createReplayer(); @@ -70,14 +69,13 @@ public class ReliableTransport extends ResponseCorrelator { replay.setLastNakNumber(toCommandId); try { oneway(replay); - } - catch (IOException e) { + } catch (IOException e) { getTransportListener().onException(e); } } public Object request(Object o) throws IOException { - final Command command = (Command) o; + final Command command = (Command)o; FutureResponse response = asyncRequest(command, null); while (true) { Response result = response.getResult(requestTimeout); @@ -89,7 +87,7 @@ public class ReliableTransport extends ResponseCorrelator { } public Object request(Object o, int timeout) throws IOException { - final Command command = (Command) o; + final Command command = (Command)o; FutureResponse response = asyncRequest(command, null); while (timeout > 0) { int time = timeout; @@ -107,14 +105,13 @@ public class ReliableTransport extends ResponseCorrelator { } public void onCommand(Object o) { - Command command = (Command) o; + Command command = (Command)o; // lets pass wireformat through if (command.isWireFormatInfo()) { super.onCommand(command); return; - } - else if (command.getDataStructureType() == ReplayCommand.DATA_STRUCTURE_TYPE) { - replayCommands((ReplayCommand) command); + } else if (command.getDataStructureType() == ReplayCommand.DATA_STRUCTURE_TYPE) { + replayCommands((ReplayCommand)command); return; } @@ -126,10 +123,10 @@ public class ReliableTransport extends ResponseCorrelator { int nextCounter = actualCounter; boolean empty = commands.isEmpty(); if (!empty) { - Command nextAvailable = (Command) commands.first(); + Command nextAvailable = (Command)commands.first(); nextCounter = nextAvailable.getCommandId(); } - + try { boolean keep = replayStrategy.onDroppedPackets(this, expectedCounter, actualCounter, nextCounter); @@ -140,15 +137,14 @@ public class ReliableTransport extends ResponseCorrelator { } commands.add(command); } - } - catch (IOException e) { + } catch (IOException e) { onException(e); } if (!empty) { // lets see if the first item in the set is the next // expected - command = (Command) commands.first(); + command = (Command)commands.first(); valid = expectedCounter == command.getCommandId(); if (valid) { commands.remove(command); @@ -169,7 +165,7 @@ public class ReliableTransport extends ResponseCorrelator { if (valid) { // lets see if the first item in the set is the next // expected - command = (Command) commands.first(); + command = (Command)commands.first(); valid = expectedCounter == command.getCommandId(); if (valid) { commands.remove(command); @@ -288,8 +284,7 @@ public class ReliableTransport extends ResponseCorrelator { // TODO we could proactively remove ack'd stuff from the replay // buffer // if we only have a single client talking to us - } - catch (IOException e) { + } catch (IOException e) { onException(e); } } diff --git a/activemq-core/src/main/java/org/apache/activemq/transport/stomp/FrameTranslator.java b/activemq-core/src/main/java/org/apache/activemq/transport/stomp/FrameTranslator.java index e438538687..70c8d5841f 100644 --- a/activemq-core/src/main/java/org/apache/activemq/transport/stomp/FrameTranslator.java +++ b/activemq-core/src/main/java/org/apache/activemq/transport/stomp/FrameTranslator.java @@ -10,12 +10,12 @@ import java.util.Map; import java.util.HashMap; /** - * Implementations of this interface are used to map back and forth from Stomp to ActiveMQ. - * There are several standard mappings which are semantically the same, the inner class, - * Helper, provides functions to copy those properties from one to the other + * Implementations of this interface are used to map back and forth from Stomp + * to ActiveMQ. There are several standard mappings which are semantically the + * same, the inner class, Helper, provides functions to copy those properties + * from one to the other */ -public interface FrameTranslator -{ +public interface FrameTranslator { public ActiveMQMessage convertFrame(StompFrame frame) throws JMSException, ProtocolException; public StompFrame convertMessage(ActiveMQMessage message) throws IOException, JMSException; @@ -28,13 +28,8 @@ public interface FrameTranslator * Helper class which holds commonly needed functions used when implementing * FrameTranslators */ - public final static class Helper - { - public static void copyStandardHeadersFromMessageToFrame(ActiveMQMessage message, - StompFrame command, - FrameTranslator ft) - throws IOException - { + public final static class Helper { + public static void copyStandardHeadersFromMessageToFrame(ActiveMQMessage message, StompFrame command, FrameTranslator ft) throws IOException { final Map headers = command.getHeaders(); headers.put(Stomp.Headers.Message.DESTINATION, ft.convertDestination(message.getDestination())); headers.put(Stomp.Headers.Message.MESSAGE_ID, message.getJMSMessageID()); @@ -42,17 +37,17 @@ public interface FrameTranslator if (message.getJMSCorrelationID() != null) { headers.put(Stomp.Headers.Message.CORRELATION_ID, message.getJMSCorrelationID()); } - headers.put(Stomp.Headers.Message.EXPIRATION_TIME, ""+message.getJMSExpiration()); + headers.put(Stomp.Headers.Message.EXPIRATION_TIME, "" + message.getJMSExpiration()); if (message.getJMSRedelivered()) { headers.put(Stomp.Headers.Message.REDELIVERED, "true"); } - headers.put(Stomp.Headers.Message.PRORITY, ""+message.getJMSPriority()); + headers.put(Stomp.Headers.Message.PRORITY, "" + message.getJMSPriority()); if (message.getJMSReplyTo() != null) { headers.put(Stomp.Headers.Message.REPLY_TO, ft.convertDestination(message.getJMSReplyTo())); } - headers.put(Stomp.Headers.Message.TIMESTAMP, ""+message.getJMSTimestamp()); + headers.put(Stomp.Headers.Message.TIMESTAMP, "" + message.getJMSTimestamp()); if (message.getJMSType() != null) { headers.put(Stomp.Headers.Message.TYPE, message.getJMSType()); @@ -65,36 +60,32 @@ public interface FrameTranslator } } - public static void copyStandardHeadersFromFrameToMessage(StompFrame command, - ActiveMQMessage msg, - FrameTranslator ft) - throws ProtocolException, JMSException - { + public static void copyStandardHeadersFromFrameToMessage(StompFrame command, ActiveMQMessage msg, FrameTranslator ft) throws ProtocolException, JMSException { final Map headers = new HashMap(command.getHeaders()); - final String destination = (String) headers.remove(Stomp.Headers.Send.DESTINATION); - msg.setDestination( ft.convertDestination(destination)); + final String destination = (String)headers.remove(Stomp.Headers.Send.DESTINATION); + msg.setDestination(ft.convertDestination(destination)); // the standard JMS headers - msg.setJMSCorrelationID((String) headers.remove(Stomp.Headers.Send.CORRELATION_ID)); + msg.setJMSCorrelationID((String)headers.remove(Stomp.Headers.Send.CORRELATION_ID)); Object o = headers.remove(Stomp.Headers.Send.EXPIRATION_TIME); if (o != null) { - msg.setJMSExpiration(Long.parseLong((String) o)); + msg.setJMSExpiration(Long.parseLong((String)o)); } o = headers.remove(Stomp.Headers.Send.PRIORITY); if (o != null) { - msg.setJMSPriority(Integer.parseInt((String) o)); + msg.setJMSPriority(Integer.parseInt((String)o)); } o = headers.remove(Stomp.Headers.Send.TYPE); if (o != null) { - msg.setJMSType((String) o); + msg.setJMSType((String)o); } o = headers.remove(Stomp.Headers.Send.REPLY_TO); if (o != null) { - msg.setJMSReplyTo(ft.convertDestination((String) o)); + msg.setJMSReplyTo(ft.convertDestination((String)o)); } o = headers.remove(Stomp.Headers.Send.PERSISTENT); diff --git a/activemq-core/src/main/java/org/apache/activemq/transport/stomp/LegacyFrameTranslator.java b/activemq-core/src/main/java/org/apache/activemq/transport/stomp/LegacyFrameTranslator.java index 509cfb9954..a01754d0e9 100644 --- a/activemq-core/src/main/java/org/apache/activemq/transport/stomp/LegacyFrameTranslator.java +++ b/activemq-core/src/main/java/org/apache/activemq/transport/stomp/LegacyFrameTranslator.java @@ -14,8 +14,7 @@ import java.io.IOException; /** * Implements ActiveMQ 4.0 translations */ -public class LegacyFrameTranslator implements FrameTranslator -{ +public class LegacyFrameTranslator implements FrameTranslator { public ActiveMQMessage convertFrame(StompFrame command) throws JMSException, ProtocolException { final Map headers = command.getHeaders(); final ActiveMQMessage msg; @@ -28,8 +27,7 @@ public class LegacyFrameTranslator implements FrameTranslator ActiveMQTextMessage text = new ActiveMQTextMessage(); try { text.setText(new String(command.getContent(), "UTF-8")); - } - catch (Throwable e) { + } catch (Throwable e) { throw new ProtocolException("Text could not bet set: " + e, false, e); } msg = text; @@ -40,25 +38,25 @@ public class LegacyFrameTranslator implements FrameTranslator public StompFrame convertMessage(ActiveMQMessage message) throws IOException, JMSException { StompFrame command = new StompFrame(); - command.setAction(Stomp.Responses.MESSAGE); + command.setAction(Stomp.Responses.MESSAGE); Map headers = new HashMap(25); command.setHeaders(headers); FrameTranslator.Helper.copyStandardHeadersFromMessageToFrame(message, command, this); - if( message.getDataStructureType() == ActiveMQTextMessage.DATA_STRUCTURE_TYPE ) { + if (message.getDataStructureType() == ActiveMQTextMessage.DATA_STRUCTURE_TYPE) { ActiveMQTextMessage msg = (ActiveMQTextMessage)message.copy(); command.setContent(msg.getText().getBytes("UTF-8")); - } else if( message.getDataStructureType() == ActiveMQBytesMessage.DATA_STRUCTURE_TYPE ) { + } else if (message.getDataStructureType() == ActiveMQBytesMessage.DATA_STRUCTURE_TYPE) { - ActiveMQBytesMessage msg = (ActiveMQBytesMessage)message.copy(); - msg.setReadOnlyBody(true); + ActiveMQBytesMessage msg = (ActiveMQBytesMessage)message.copy(); + msg.setReadOnlyBody(true); byte[] data = new byte[(int)msg.getBodyLength()]; msg.readBytes(data); - headers.put(Stomp.Headers.CONTENT_LENGTH, ""+data.length); + headers.put(Stomp.Headers.CONTENT_LENGTH, "" + data.length); command.setContent(data); } return command; @@ -68,23 +66,20 @@ public class LegacyFrameTranslator implements FrameTranslator if (d == null) { return null; } - ActiveMQDestination amq_d = (ActiveMQDestination) d; + ActiveMQDestination amq_d = (ActiveMQDestination)d; String p_name = amq_d.getPhysicalName(); StringBuffer buffer = new StringBuffer(); if (amq_d.isQueue()) { if (amq_d.isTemporary()) { buffer.append("/temp-queue/"); - } - else { + } else { buffer.append("/queue/"); } - } - else { + } else { if (amq_d.isTemporary()) { buffer.append("/temp-topic/"); - } - else { + } else { buffer.append("/topic/"); } } @@ -95,26 +90,21 @@ public class LegacyFrameTranslator implements FrameTranslator public ActiveMQDestination convertDestination(String name) throws ProtocolException { if (name == null) { return null; - } - else if (name.startsWith("/queue/")) { + } else if (name.startsWith("/queue/")) { String q_name = name.substring("/queue/".length(), name.length()); return ActiveMQDestination.createDestination(q_name, ActiveMQDestination.QUEUE_TYPE); - } - else if (name.startsWith("/topic/")) { + } else if (name.startsWith("/topic/")) { String t_name = name.substring("/topic/".length(), name.length()); return ActiveMQDestination.createDestination(t_name, ActiveMQDestination.TOPIC_TYPE); - } - else if (name.startsWith("/temp-queue/")) { + } else if (name.startsWith("/temp-queue/")) { String t_name = name.substring("/temp-queue/".length(), name.length()); return ActiveMQDestination.createDestination(t_name, ActiveMQDestination.TEMP_QUEUE_TYPE); - } - else if (name.startsWith("/temp-topic/")) { + } else if (name.startsWith("/temp-topic/")) { String t_name = name.substring("/temp-topic/".length(), name.length()); return ActiveMQDestination.createDestination(t_name, ActiveMQDestination.TEMP_TOPIC_TYPE); - } - else { - throw new ProtocolException("Illegal destination name: [" + name + "] -- ActiveMQ STOMP destinations " + - "must begine with one of: /queue/ /topic/ /temp-queue/ /temp-topic/"); + } else { + throw new ProtocolException("Illegal destination name: [" + name + "] -- ActiveMQ STOMP destinations " + + "must begine with one of: /queue/ /topic/ /temp-queue/ /temp-topic/"); } } } diff --git a/activemq-core/src/main/java/org/apache/activemq/transport/stomp/ProtocolConverter.java b/activemq-core/src/main/java/org/apache/activemq/transport/stomp/ProtocolConverter.java index a447286a84..093633f0af 100644 --- a/activemq-core/src/main/java/org/apache/activemq/transport/stomp/ProtocolConverter.java +++ b/activemq-core/src/main/java/org/apache/activemq/transport/stomp/ProtocolConverter.java @@ -56,7 +56,6 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicBoolean; /** - * * @author chirino */ public class ProtocolConverter { @@ -73,117 +72,117 @@ public class ProtocolConverter { private final ConcurrentHashMap resposeHandlers = new ConcurrentHashMap(); private final ConcurrentHashMap subscriptionsByConsumerId = new ConcurrentHashMap(); private final Map transactions = new ConcurrentHashMap(); - private final StompTransportFilter transportFilter; + private final StompTransportFilter transportFilter; - private final Object commnadIdMutex = new Object(); - private int lastCommandId; + private final Object commnadIdMutex = new Object(); + private int lastCommandId; private final AtomicBoolean connected = new AtomicBoolean(false); private final FrameTranslator frameTranslator; - public ProtocolConverter(StompTransportFilter stompTransportFilter, FrameTranslator translator) - { + public ProtocolConverter(StompTransportFilter stompTransportFilter, FrameTranslator translator) { this.transportFilter = stompTransportFilter; this.frameTranslator = translator; } protected int generateCommandId() { - synchronized(commnadIdMutex){ - return lastCommandId++; - } + synchronized (commnadIdMutex) { + return lastCommandId++; + } } - protected ResponseHandler createResponseHandler(StompFrame command){ - final String receiptId = (String) command.getHeaders().get(Stomp.Headers.RECEIPT_REQUESTED); + protected ResponseHandler createResponseHandler(StompFrame command) { + final String receiptId = (String)command.getHeaders().get(Stomp.Headers.RECEIPT_REQUESTED); // A response may not be needed. - if( receiptId != null ) { - return new ResponseHandler() { - public void onResponse(ProtocolConverter converter, Response response) throws IOException { - StompFrame sc = new StompFrame(); - sc.setAction(Stomp.Responses.RECEIPT); - sc.setHeaders(new HashMap(1)); - sc.getHeaders().put(Stomp.Headers.Response.RECEIPT_ID, receiptId); - transportFilter.sendToStomp(sc); - } - }; - } - return null; + if (receiptId != null) { + return new ResponseHandler() { + public void onResponse(ProtocolConverter converter, Response response) throws IOException { + StompFrame sc = new StompFrame(); + sc.setAction(Stomp.Responses.RECEIPT); + sc.setHeaders(new HashMap(1)); + sc.getHeaders().put(Stomp.Headers.Response.RECEIPT_ID, receiptId); + transportFilter.sendToStomp(sc); + } + }; + } + return null; } - protected void sendToActiveMQ(Command command, ResponseHandler handler) { - command.setCommandId(generateCommandId()); - if(handler!=null) { - command.setResponseRequired(true); - resposeHandlers.put(Integer.valueOf(command.getCommandId()), handler); - } - transportFilter.sendToActiveMQ(command); - } + protected void sendToActiveMQ(Command command, ResponseHandler handler) { + command.setCommandId(generateCommandId()); + if (handler != null) { + command.setResponseRequired(true); + resposeHandlers.put(Integer.valueOf(command.getCommandId()), handler); + } + transportFilter.sendToActiveMQ(command); + } - protected void sendToStomp(StompFrame command) throws IOException { - transportFilter.sendToStomp(command); - } + protected void sendToStomp(StompFrame command) throws IOException { + transportFilter.sendToStomp(command); + } - /** + /** * Convert a stomp command + * * @param command */ - public void onStompCommad( StompFrame command ) throws IOException, JMSException { - try { + public void onStompCommad(StompFrame command) throws IOException, JMSException { + try { - if( command.getClass() == StompFrameError.class ) { - throw ((StompFrameError)command).getException(); - } + if (command.getClass() == StompFrameError.class) { + throw ((StompFrameError)command).getException(); + } - String action = command.getAction(); - if (action.startsWith(Stomp.Commands.SEND)) - onStompSend(command); - else if (action.startsWith(Stomp.Commands.ACK)) - onStompAck(command); - else if (action.startsWith(Stomp.Commands.BEGIN)) - onStompBegin(command); - else if (action.startsWith(Stomp.Commands.COMMIT)) - onStompCommit(command); - else if (action.startsWith(Stomp.Commands.ABORT)) - onStompAbort(command); - else if (action.startsWith(Stomp.Commands.SUBSCRIBE)) - onStompSubscribe(command); - else if (action.startsWith(Stomp.Commands.UNSUBSCRIBE)) - onStompUnsubscribe(command); - else if (action.startsWith(Stomp.Commands.CONNECT)) - onStompConnect(command); - else if (action.startsWith(Stomp.Commands.DISCONNECT)) - onStompDisconnect(command); - else - throw new ProtocolException("Unknown STOMP action: "+action); + String action = command.getAction(); + if (action.startsWith(Stomp.Commands.SEND)) + onStompSend(command); + else if (action.startsWith(Stomp.Commands.ACK)) + onStompAck(command); + else if (action.startsWith(Stomp.Commands.BEGIN)) + onStompBegin(command); + else if (action.startsWith(Stomp.Commands.COMMIT)) + onStompCommit(command); + else if (action.startsWith(Stomp.Commands.ABORT)) + onStompAbort(command); + else if (action.startsWith(Stomp.Commands.SUBSCRIBE)) + onStompSubscribe(command); + else if (action.startsWith(Stomp.Commands.UNSUBSCRIBE)) + onStompUnsubscribe(command); + else if (action.startsWith(Stomp.Commands.CONNECT)) + onStompConnect(command); + else if (action.startsWith(Stomp.Commands.DISCONNECT)) + onStompDisconnect(command); + else + throw new ProtocolException("Unknown STOMP action: " + action); } catch (ProtocolException e) { - // Let the stomp client know about any protocol errors. - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - PrintWriter stream = new PrintWriter(new OutputStreamWriter(baos,"UTF-8")); - e.printStackTrace(stream); - stream.close(); + // Let the stomp client know about any protocol errors. + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + PrintWriter stream = new PrintWriter(new OutputStreamWriter(baos, "UTF-8")); + e.printStackTrace(stream); + stream.close(); - HashMap headers = new HashMap(); - headers.put(Stomp.Headers.Error.MESSAGE, e.getMessage()); + HashMap headers = new HashMap(); + headers.put(Stomp.Headers.Error.MESSAGE, e.getMessage()); - final String receiptId = (String) command.getHeaders().get(Stomp.Headers.RECEIPT_REQUESTED); - if( receiptId != null ) { - headers.put(Stomp.Headers.Response.RECEIPT_ID, receiptId); + final String receiptId = (String)command.getHeaders().get(Stomp.Headers.RECEIPT_REQUESTED); + if (receiptId != null) { + headers.put(Stomp.Headers.Response.RECEIPT_ID, receiptId); } - StompFrame errorMessage = new StompFrame(Stomp.Responses.ERROR,headers,baos.toByteArray()); - sendToStomp(errorMessage); + StompFrame errorMessage = new StompFrame(Stomp.Responses.ERROR, headers, baos.toByteArray()); + sendToStomp(errorMessage); - if( e.isFatal() ) - getTransportFilter().onException(e); + if (e.isFatal()) + getTransportFilter().onException(e); } - } + } - protected void onStompSend(StompFrame command) throws IOException, JMSException { - checkConnected(); + protected void onStompSend(StompFrame command) throws IOException, JMSException { + checkConnected(); - Map headers = command.getHeaders(); - String stompTx = (String) headers.get(Stomp.Headers.TRANSACTION); + Map headers = command.getHeaders(); + String stompTx = (String)headers.get(Stomp.Headers.TRANSACTION); ActiveMQMessage message = convertMessage(command); @@ -192,61 +191,61 @@ public class ProtocolConverter { message.setMessageId(id); message.setJMSTimestamp(System.currentTimeMillis()); - if (stompTx!=null) { - TransactionId activemqTx = (TransactionId) transactions.get(stompTx); + if (stompTx != null) { + TransactionId activemqTx = (TransactionId)transactions.get(stompTx); if (activemqTx == null) - throw new ProtocolException("Invalid transaction id: "+stompTx); + throw new ProtocolException("Invalid transaction id: " + stompTx); message.setTransactionId(activemqTx); } message.onSend(); - sendToActiveMQ(message, createResponseHandler(command)); - - } + sendToActiveMQ(message, createResponseHandler(command)); + } protected void onStompAck(StompFrame command) throws ProtocolException { - checkConnected(); + checkConnected(); - // TODO: acking with just a message id is very bogus - // since the same message id could have been sent to 2 different subscriptions - // on the same stomp connection. For example, when 2 subs are created on the same topic. + // TODO: acking with just a message id is very bogus + // since the same message id could have been sent to 2 different + // subscriptions + // on the same stomp connection. For example, when 2 subs are created on + // the same topic. - Map headers = command.getHeaders(); - String messageId = (String) headers.get(Stomp.Headers.Ack.MESSAGE_ID); + Map headers = command.getHeaders(); + String messageId = (String)headers.get(Stomp.Headers.Ack.MESSAGE_ID); if (messageId == null) throw new ProtocolException("ACK received without a message-id to acknowledge!"); - TransactionId activemqTx=null; - String stompTx = (String) headers.get(Stomp.Headers.TRANSACTION); - if (stompTx!=null) { - activemqTx = (TransactionId) transactions.get(stompTx); + TransactionId activemqTx = null; + String stompTx = (String)headers.get(Stomp.Headers.TRANSACTION); + if (stompTx != null) { + activemqTx = (TransactionId)transactions.get(stompTx); if (activemqTx == null) - throw new ProtocolException("Invalid transaction id: "+stompTx); + throw new ProtocolException("Invalid transaction id: " + stompTx); } - boolean acked=false; + boolean acked = false; for (Iterator iter = subscriptionsByConsumerId.values().iterator(); iter.hasNext();) { - StompSubscription sub = (StompSubscription) iter.next(); - MessageAck ack = sub.onStompMessageAck(messageId); - if( ack!=null ) { - ack.setTransactionId(activemqTx); - sendToActiveMQ(ack,createResponseHandler(command)); - acked=true; - break; - } - } + StompSubscription sub = (StompSubscription)iter.next(); + MessageAck ack = sub.onStompMessageAck(messageId); + if (ack != null) { + ack.setTransactionId(activemqTx); + sendToActiveMQ(ack, createResponseHandler(command)); + acked = true; + break; + } + } - if( !acked ) - throw new ProtocolException("Unexpected ACK received for message-id [" + messageId + "]"); + if (!acked) + throw new ProtocolException("Unexpected ACK received for message-id [" + messageId + "]"); - } + } + protected void onStompBegin(StompFrame command) throws ProtocolException { + checkConnected(); - protected void onStompBegin(StompFrame command) throws ProtocolException { - checkConnected(); - - Map headers = command.getHeaders(); + Map headers = command.getHeaders(); String stompTx = (String)headers.get(Stomp.Headers.TRANSACTION); @@ -254,8 +253,8 @@ public class ProtocolConverter { throw new ProtocolException("Must specify the transaction you are beginning"); } - if( transactions.get(stompTx)!=null ) { - throw new ProtocolException("The transaction was allready started: "+stompTx); + if (transactions.get(stompTx) != null) { + throw new ProtocolException("The transaction was allready started: " + stompTx); } LocalTransactionId activemqTx = new LocalTransactionId(connectionId, transactionIdGenerator.getNextSequenceId()); @@ -266,23 +265,23 @@ public class ProtocolConverter { tx.setTransactionId(activemqTx); tx.setType(TransactionInfo.BEGIN); - sendToActiveMQ(tx, createResponseHandler(command)); + sendToActiveMQ(tx, createResponseHandler(command)); - } + } - protected void onStompCommit(StompFrame command) throws ProtocolException { - checkConnected(); + protected void onStompCommit(StompFrame command) throws ProtocolException { + checkConnected(); - Map headers = command.getHeaders(); + Map headers = command.getHeaders(); - String stompTx = (String) headers.get(Stomp.Headers.TRANSACTION); - if (stompTx==null) { + String stompTx = (String)headers.get(Stomp.Headers.TRANSACTION); + if (stompTx == null) { throw new ProtocolException("Must specify the transaction you are committing"); } - TransactionId activemqTx = (TransactionId) transactions.remove(stompTx); + TransactionId activemqTx = (TransactionId)transactions.remove(stompTx); if (activemqTx == null) { - throw new ProtocolException("Invalid transaction id: "+stompTx); + throw new ProtocolException("Invalid transaction id: " + stompTx); } TransactionInfo tx = new TransactionInfo(); @@ -290,21 +289,21 @@ public class ProtocolConverter { tx.setTransactionId(activemqTx); tx.setType(TransactionInfo.COMMIT_ONE_PHASE); - sendToActiveMQ(tx, createResponseHandler(command)); - } + sendToActiveMQ(tx, createResponseHandler(command)); + } - protected void onStompAbort(StompFrame command) throws ProtocolException { - checkConnected(); - Map headers = command.getHeaders(); + protected void onStompAbort(StompFrame command) throws ProtocolException { + checkConnected(); + Map headers = command.getHeaders(); - String stompTx = (String) headers.get(Stomp.Headers.TRANSACTION); - if (stompTx==null) { + String stompTx = (String)headers.get(Stomp.Headers.TRANSACTION); + if (stompTx == null) { throw new ProtocolException("Must specify the transaction you are committing"); } - TransactionId activemqTx = (TransactionId) transactions.remove(stompTx); + TransactionId activemqTx = (TransactionId)transactions.remove(stompTx); if (activemqTx == null) { - throw new ProtocolException("Invalid transaction id: "+stompTx); + throw new ProtocolException("Invalid transaction id: " + stompTx); } TransactionInfo tx = new TransactionInfo(); @@ -312,13 +311,13 @@ public class ProtocolConverter { tx.setTransactionId(activemqTx); tx.setType(TransactionInfo.ROLLBACK); - sendToActiveMQ(tx, createResponseHandler(command)); + sendToActiveMQ(tx, createResponseHandler(command)); - } + } - protected void onStompSubscribe(StompFrame command) throws ProtocolException { - checkConnected(); - Map headers = command.getHeaders(); + protected void onStompSubscribe(StompFrame command) throws ProtocolException { + checkConnected(); + Map headers = command.getHeaders(); String subscriptionId = (String)headers.get(Stomp.Headers.Subscribe.ID); String destination = (String)headers.get(Stomp.Headers.Subscribe.DESTINATION); @@ -329,7 +328,7 @@ public class ProtocolConverter { consumerInfo.setPrefetchSize(1000); consumerInfo.setDispatchAsync(true); - String selector = (String) headers.remove(Stomp.Headers.Subscribe.SELECTOR); + String selector = (String)headers.remove(Stomp.Headers.Subscribe.SELECTOR); consumerInfo.setSelector(selector); IntrospectionSupport.setProperties(consumerInfo, headers, "activemq."); @@ -347,50 +346,49 @@ public class ProtocolConverter { } subscriptionsByConsumerId.put(id, stompSubscription); - sendToActiveMQ(consumerInfo, createResponseHandler(command)); + sendToActiveMQ(consumerInfo, createResponseHandler(command)); - } + } - protected void onStompUnsubscribe(StompFrame command) throws ProtocolException { - checkConnected(); - Map headers = command.getHeaders(); + protected void onStompUnsubscribe(StompFrame command) throws ProtocolException { + checkConnected(); + Map headers = command.getHeaders(); - ActiveMQDestination destination=null; + ActiveMQDestination destination = null; Object o = headers.get(Stomp.Headers.Unsubscribe.DESTINATION); - if( o!=null ) - destination = frameTranslator.convertDestination((String) o); + if (o != null) + destination = frameTranslator.convertDestination((String)o); String subscriptionId = (String)headers.get(Stomp.Headers.Unsubscribe.ID); - if (subscriptionId==null && destination==null) { + if (subscriptionId == null && destination == null) { throw new ProtocolException("Must specify the subscriptionId or the destination you are unsubscribing from"); } - // TODO: Unsubscribing using a destination is a bit wierd if multiple subscriptions - // are created with the same destination. Perhaps this should be removed. + // TODO: Unsubscribing using a destination is a bit wierd if multiple + // subscriptions + // are created with the same destination. Perhaps this should be + // removed. // for (Iterator iter = subscriptionsByConsumerId.values().iterator(); iter.hasNext();) { - StompSubscription sub = (StompSubscription) iter.next(); - if ( - (subscriptionId!=null && subscriptionId.equals(sub.getSubscriptionId()) ) || - (destination!=null && destination.equals(sub.getDestination()) ) - ) { - sendToActiveMQ(sub.getConsumerInfo().createRemoveCommand(), createResponseHandler(command)); - iter.remove(); + StompSubscription sub = (StompSubscription)iter.next(); + if ((subscriptionId != null && subscriptionId.equals(sub.getSubscriptionId())) || (destination != null && destination.equals(sub.getDestination()))) { + sendToActiveMQ(sub.getConsumerInfo().createRemoveCommand(), createResponseHandler(command)); + iter.remove(); return; - } - } + } + } throw new ProtocolException("No subscription matched."); - } + } - protected void onStompConnect(StompFrame command) throws ProtocolException { + protected void onStompConnect(StompFrame command) throws ProtocolException { - if(connected.get()) { - throw new ProtocolException("Allready connected."); - } + if (connected.get()) { + throw new ProtocolException("Allready connected."); + } - final Map headers = command.getHeaders(); + final Map headers = command.getHeaders(); // allow anyone to login for now String login = (String)headers.get(Stomp.Headers.Connect.LOGIN); @@ -402,100 +400,99 @@ public class ProtocolConverter { IntrospectionSupport.setProperties(connectionInfo, headers, "activemq."); connectionInfo.setConnectionId(connectionId); - if( clientId!=null ) + if (clientId != null) connectionInfo.setClientId(clientId); else - connectionInfo.setClientId(""+connectionInfo.getConnectionId().toString()); + connectionInfo.setClientId("" + connectionInfo.getConnectionId().toString()); connectionInfo.setResponseRequired(true); connectionInfo.setUserName(login); connectionInfo.setPassword(passcode); - sendToActiveMQ(connectionInfo, new ResponseHandler(){ - public void onResponse(ProtocolConverter converter, Response response) throws IOException { + sendToActiveMQ(connectionInfo, new ResponseHandler() { + public void onResponse(ProtocolConverter converter, Response response) throws IOException { - final SessionInfo sessionInfo = new SessionInfo(sessionId); - sendToActiveMQ(sessionInfo,null); + final SessionInfo sessionInfo = new SessionInfo(sessionId); + sendToActiveMQ(sessionInfo, null); + final ProducerInfo producerInfo = new ProducerInfo(producerId); + sendToActiveMQ(producerInfo, new ResponseHandler() { + public void onResponse(ProtocolConverter converter, Response response) throws IOException { - final ProducerInfo producerInfo = new ProducerInfo(producerId); - sendToActiveMQ(producerInfo,new ResponseHandler(){ - public void onResponse(ProtocolConverter converter, Response response) throws IOException { + connected.set(true); + HashMap responseHeaders = new HashMap(); - connected.set(true); - HashMap responseHeaders = new HashMap(); - - responseHeaders.put(Stomp.Headers.Connected.SESSION, connectionInfo.getClientId()); - String requestId = (String) headers.get(Stomp.Headers.Connect.REQUEST_ID); + responseHeaders.put(Stomp.Headers.Connected.SESSION, connectionInfo.getClientId()); + String requestId = (String)headers.get(Stomp.Headers.Connect.REQUEST_ID); if (requestId == null) { // TODO legacy - requestId = (String) headers.get(Stomp.Headers.RECEIPT_REQUESTED); + requestId = (String)headers.get(Stomp.Headers.RECEIPT_REQUESTED); } - if( requestId !=null ){ + if (requestId != null) { // TODO legacy - responseHeaders.put(Stomp.Headers.Connected.RESPONSE_ID, requestId); + responseHeaders.put(Stomp.Headers.Connected.RESPONSE_ID, requestId); responseHeaders.put(Stomp.Headers.Response.RECEIPT_ID, requestId); - } + } - StompFrame sc = new StompFrame(); - sc.setAction(Stomp.Responses.CONNECTED); - sc.setHeaders(responseHeaders); - sendToStomp(sc); - } - }); + StompFrame sc = new StompFrame(); + sc.setAction(Stomp.Responses.CONNECTED); + sc.setHeaders(responseHeaders); + sendToStomp(sc); + } + }); - } - }); - } + } + }); + } - protected void onStompDisconnect(StompFrame command) throws ProtocolException { - checkConnected(); - sendToActiveMQ(new ShutdownInfo(), createResponseHandler(command)); - connected.set(false); - } + protected void onStompDisconnect(StompFrame command) throws ProtocolException { + checkConnected(); + sendToActiveMQ(new ShutdownInfo(), createResponseHandler(command)); + connected.set(false); + } + protected void checkConnected() throws ProtocolException { + if (!connected.get()) { + throw new ProtocolException("Not connected."); + } + } - protected void checkConnected() throws ProtocolException { - if(!connected.get()) { - throw new ProtocolException("Not connected."); - } - } - - /** + /** * Dispatch a ActiveMQ command + * * @param command * @throws IOException */ - public void onActiveMQCommad( Command command ) throws IOException, JMSException { + public void onActiveMQCommad(Command command) throws IOException, JMSException { - if ( command.isResponse() ) { + if (command.isResponse()) { - Response response = (Response) command; - ResponseHandler rh = (ResponseHandler) resposeHandlers.remove(Integer.valueOf(response.getCorrelationId())); - if( rh !=null ) { - rh.onResponse(this, response); - } + Response response = (Response)command; + ResponseHandler rh = (ResponseHandler)resposeHandlers.remove(Integer.valueOf(response.getCorrelationId())); + if (rh != null) { + rh.onResponse(this, response); + } - } else if( command.isMessageDispatch() ) { + } else if (command.isMessageDispatch()) { - MessageDispatch md = (MessageDispatch)command; - StompSubscription sub = (StompSubscription) subscriptionsByConsumerId.get(md.getConsumerId()); - if (sub != null) { - sub.onMessageDispatch(md); + MessageDispatch md = (MessageDispatch)command; + StompSubscription sub = (StompSubscription)subscriptionsByConsumerId.get(md.getConsumerId()); + if (sub != null) { + sub.onMessageDispatch(md); } } - } + } - public ActiveMQMessage convertMessage(StompFrame command) throws IOException, JMSException { + public ActiveMQMessage convertMessage(StompFrame command) throws IOException, JMSException { ActiveMQMessage msg = frameTranslator.convertFrame(command); return msg; } - public StompFrame convertMessage(ActiveMQMessage message) throws IOException, JMSException { - return frameTranslator.convertMessage(message); + public StompFrame convertMessage(ActiveMQMessage message) throws IOException, JMSException { + return frameTranslator.convertMessage(message); } - public StompTransportFilter getTransportFilter() { - return transportFilter; - } + public StompTransportFilter getTransportFilter() { + return transportFilter; + } } diff --git a/activemq-core/src/main/java/org/apache/activemq/transport/stomp/ProtocolException.java b/activemq-core/src/main/java/org/apache/activemq/transport/stomp/ProtocolException.java index 7d27e48d9c..2a923ca0f9 100644 --- a/activemq-core/src/main/java/org/apache/activemq/transport/stomp/ProtocolException.java +++ b/activemq-core/src/main/java/org/apache/activemq/transport/stomp/ProtocolException.java @@ -19,32 +19,34 @@ package org.apache.activemq.transport.stomp; import java.io.IOException; /** - * - * @author chirino + * @author chirino */ public class ProtocolException extends IOException { - private static final long serialVersionUID = -2869735532997332242L; - - private final boolean fatal; + private static final long serialVersionUID = -2869735532997332242L; - public ProtocolException() { - this(null); - } - public ProtocolException(String s) { - this(s, false); - } - public ProtocolException(String s, boolean fatal) { - this(s,fatal, null); - } - public ProtocolException(String s, boolean fatal, Throwable cause) { - super(s); - this.fatal = fatal; - initCause(cause); - } - - public boolean isFatal() { - return fatal; - } + private final boolean fatal; + + public ProtocolException() { + this(null); + } + + public ProtocolException(String s) { + this(s, false); + } + + public ProtocolException(String s, boolean fatal) { + this(s, fatal, null); + } + + public ProtocolException(String s, boolean fatal, Throwable cause) { + super(s); + this.fatal = fatal; + initCause(cause); + } + + public boolean isFatal() { + return fatal; + } } diff --git a/activemq-core/src/main/java/org/apache/activemq/transport/stomp/StompFrame.java b/activemq-core/src/main/java/org/apache/activemq/transport/stomp/StompFrame.java index c3152122ae..8a7fcf39eb 100644 --- a/activemq-core/src/main/java/org/apache/activemq/transport/stomp/StompFrame.java +++ b/activemq-core/src/main/java/org/apache/activemq/transport/stomp/StompFrame.java @@ -30,144 +30,144 @@ import org.apache.activemq.state.CommandVisitor; /** * Represents all the data in a STOMP frame. * - * @author chirino + * @author chirino */ public class StompFrame implements Command { - private static final byte[] NO_DATA = new byte[]{}; + private static final byte[] NO_DATA = new byte[] {}; - private String action; - private Map headers = Collections.EMPTY_MAP; - private byte[] content = NO_DATA; + private String action; + private Map headers = Collections.EMPTY_MAP; + private byte[] content = NO_DATA; - public StompFrame(String command, HashMap headers, byte[] data) { - this.action = command; - this.headers = headers; - this.content = data; - } + public StompFrame(String command, HashMap headers, byte[] data) { + this.action = command; + this.headers = headers; + this.content = data; + } - public StompFrame() { - } + public StompFrame() { + } - public String getAction() { - return action; - } + public String getAction() { + return action; + } - public void setAction(String command) { - this.action = command; - } + public void setAction(String command) { + this.action = command; + } - public byte[] getContent() { - return content; - } + public byte[] getContent() { + return content; + } - public void setContent(byte[] data) { - this.content = data; - } + public void setContent(byte[] data) { + this.content = data; + } - public Map getHeaders() { - return headers; - } + public Map getHeaders() { + return headers; + } - public void setHeaders(Map headers) { - this.headers = headers; - } + public void setHeaders(Map headers) { + this.headers = headers; + } - // - // Methods in the Command interface - // - public int getCommandId() { - return 0; - } + // + // Methods in the Command interface + // + public int getCommandId() { + return 0; + } - public Endpoint getFrom() { - return null; - } + public Endpoint getFrom() { + return null; + } - public Endpoint getTo() { - return null; - } + public Endpoint getTo() { + return null; + } - public boolean isBrokerInfo() { - return false; - } + public boolean isBrokerInfo() { + return false; + } - public boolean isMessage() { - return false; - } + public boolean isMessage() { + return false; + } - public boolean isMessageAck() { - return false; - } + public boolean isMessageAck() { + return false; + } - public boolean isMessageDispatch() { - return false; - } + public boolean isMessageDispatch() { + return false; + } - public boolean isMessageDispatchNotification() { - return false; - } + public boolean isMessageDispatchNotification() { + return false; + } - public boolean isResponse() { - return false; - } + public boolean isResponse() { + return false; + } - public boolean isResponseRequired() { - return false; - } + public boolean isResponseRequired() { + return false; + } - public boolean isShutdownInfo() { - return false; - } + public boolean isShutdownInfo() { + return false; + } - public boolean isWireFormatInfo() { - return false; - } + public boolean isWireFormatInfo() { + return false; + } - public void setCommandId(int value) { - } + public void setCommandId(int value) { + } - public void setFrom(Endpoint from) { - } + public void setFrom(Endpoint from) { + } - public void setResponseRequired(boolean responseRequired) { - } + public void setResponseRequired(boolean responseRequired) { + } - public void setTo(Endpoint to) { - } + public void setTo(Endpoint to) { + } - public Response visit(CommandVisitor visitor) throws Exception { - return null; - } + public Response visit(CommandVisitor visitor) throws Exception { + return null; + } - public byte getDataStructureType() { - return 0; - } + public byte getDataStructureType() { + return 0; + } - public boolean isMarshallAware() { - return false; - } + public boolean isMarshallAware() { + return false; + } - public String toString() { - StringBuffer buffer = new StringBuffer(); - buffer.append(getAction()); - buffer.append("\n"); - Map headers = getHeaders(); - for (Iterator iter = headers.entrySet().iterator(); iter.hasNext();) { - Map.Entry entry = (Map.Entry) iter.next(); - buffer.append(entry.getKey()); - buffer.append(":"); - buffer.append(entry.getValue()); - buffer.append("\n"); - } - buffer.append("\n"); - if( getContent()!=null ) { - try { - buffer.append(new String(getContent())); - } catch (Throwable e) { - buffer.append(Arrays.toString(getContent())); - } - } - return buffer.toString(); - } + public String toString() { + StringBuffer buffer = new StringBuffer(); + buffer.append(getAction()); + buffer.append("\n"); + Map headers = getHeaders(); + for (Iterator iter = headers.entrySet().iterator(); iter.hasNext();) { + Map.Entry entry = (Map.Entry)iter.next(); + buffer.append(entry.getKey()); + buffer.append(":"); + buffer.append(entry.getValue()); + buffer.append("\n"); + } + buffer.append("\n"); + if (getContent() != null) { + try { + buffer.append(new String(getContent())); + } catch (Throwable e) { + buffer.append(Arrays.toString(getContent())); + } + } + return buffer.toString(); + } } diff --git a/activemq-core/src/main/java/org/apache/activemq/transport/stomp/StompFrameError.java b/activemq-core/src/main/java/org/apache/activemq/transport/stomp/StompFrameError.java index 6d0ef4b67c..af62b3b329 100644 --- a/activemq-core/src/main/java/org/apache/activemq/transport/stomp/StompFrameError.java +++ b/activemq-core/src/main/java/org/apache/activemq/transport/stomp/StompFrameError.java @@ -19,20 +19,18 @@ package org.apache.activemq.transport.stomp; /** * Command indicating that an invalid Stomp Frame was received. * - * @author chirino + * @author chirino */ public class StompFrameError extends StompFrame { + private final ProtocolException exception; - private final ProtocolException exception; - - public StompFrameError(ProtocolException exception) { - this.exception = exception; - } - - public ProtocolException getException() { - return exception; - } + public StompFrameError(ProtocolException exception) { + this.exception = exception; + } + public ProtocolException getException() { + return exception; + } } diff --git a/activemq-core/src/main/java/org/apache/activemq/transport/stomp/StompSubscription.java b/activemq-core/src/main/java/org/apache/activemq/transport/stomp/StompSubscription.java index b9f155abb0..7e51a209f5 100644 --- a/activemq-core/src/main/java/org/apache/activemq/transport/stomp/StompSubscription.java +++ b/activemq-core/src/main/java/org/apache/activemq/transport/stomp/StompSubscription.java @@ -33,110 +33,109 @@ import org.apache.activemq.command.MessageId; /** * Keeps track of the STOMP susbscription so that acking is correctly done. - * - * @author chirino + * + * @author chirino */ public class StompSubscription { - + public static final String AUTO_ACK = Stomp.Headers.Subscribe.AckModeValues.AUTO; public static final String CLIENT_ACK = Stomp.Headers.Subscribe.AckModeValues.CLIENT; - private final ProtocolConverter protocolConverter; + private final ProtocolConverter protocolConverter; private final String subscriptionId; private final ConsumerInfo consumerInfo; - - private final LinkedHashMap dispatchedMessage = new LinkedHashMap(); - - private String ackMode = AUTO_ACK; - private ActiveMQDestination destination; - + private final LinkedHashMap dispatchedMessage = new LinkedHashMap(); + + private String ackMode = AUTO_ACK; + private ActiveMQDestination destination; + public StompSubscription(ProtocolConverter stompTransport, String subscriptionId, ConsumerInfo consumerInfo) { this.protocolConverter = stompTransport; - this.subscriptionId = subscriptionId; + this.subscriptionId = subscriptionId; this.consumerInfo = consumerInfo; } void onMessageDispatch(MessageDispatch md) throws IOException, JMSException { - ActiveMQMessage message = (ActiveMQMessage) md.getMessage(); - + ActiveMQMessage message = (ActiveMQMessage)md.getMessage(); + if (ackMode == CLIENT_ACK) { synchronized (this) { - dispatchedMessage.put(message.getJMSMessageID(), message.getMessageId()); + dispatchedMessage.put(message.getJMSMessageID(), message.getMessageId()); } } else if (ackMode == AUTO_ACK) { MessageAck ack = new MessageAck(md, MessageAck.STANDARD_ACK_TYPE, 1); protocolConverter.getTransportFilter().sendToActiveMQ(ack); } - + StompFrame command = protocolConverter.convertMessage(message); - - command.setAction(Stomp.Responses.MESSAGE); - if (subscriptionId!=null) { + + command.setAction(Stomp.Responses.MESSAGE); + if (subscriptionId != null) { command.getHeaders().put(Stomp.Headers.Message.SUBSCRIPTION, subscriptionId); } - + protocolConverter.getTransportFilter().sendToStomp(command); } - + synchronized MessageAck onStompMessageAck(String messageId) { - - if( !dispatchedMessage.containsKey(messageId) ) { - return null; - } - + + if (!dispatchedMessage.containsKey(messageId)) { + return null; + } + MessageAck ack = new MessageAck(); ack.setDestination(consumerInfo.getDestination()); ack.setAckType(MessageAck.STANDARD_ACK_TYPE); ack.setConsumerId(consumerInfo.getConsumerId()); - - int count=0; + + int count = 0; for (Iterator iter = dispatchedMessage.entrySet().iterator(); iter.hasNext();) { - - Map.Entry entry = (Entry) iter.next(); - String id = (String) entry.getKey(); - MessageId msgid = (MessageId) entry.getValue(); - - if( ack.getFirstMessageId()==null ) + + Map.Entry entry = (Entry)iter.next(); + String id = (String)entry.getKey(); + MessageId msgid = (MessageId)entry.getValue(); + + if (ack.getFirstMessageId() == null) ack.setFirstMessageId(msgid); iter.remove(); count++; - if( id.equals(messageId) ) { + if (id.equals(messageId)) { ack.setLastMessageId(msgid); break; } - + } - + ack.setMessageCount(count); return ack; } - public String getAckMode() { - return ackMode; - } + public String getAckMode() { + return ackMode; + } - public void setAckMode(String ackMode) { - this.ackMode = ackMode; - } + public void setAckMode(String ackMode) { + this.ackMode = ackMode; + } - public String getSubscriptionId() { - return subscriptionId; - } + public String getSubscriptionId() { + return subscriptionId; + } - public void setDestination(ActiveMQDestination destination) { - this.destination = destination; - } + public void setDestination(ActiveMQDestination destination) { + this.destination = destination; + } - public ActiveMQDestination getDestination() { - return destination; - } + public ActiveMQDestination getDestination() { + return destination; + } - public ConsumerInfo getConsumerInfo() { - return consumerInfo; - } + public ConsumerInfo getConsumerInfo() { + return consumerInfo; + } } diff --git a/activemq-core/src/main/java/org/apache/activemq/transport/stomp/StompTransportFilter.java b/activemq-core/src/main/java/org/apache/activemq/transport/stomp/StompTransportFilter.java index 5e1a6ff25b..b2912b2b1a 100644 --- a/activemq-core/src/main/java/org/apache/activemq/transport/stomp/StompTransportFilter.java +++ b/activemq-core/src/main/java/org/apache/activemq/transport/stomp/StompTransportFilter.java @@ -28,16 +28,15 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** - * The StompTransportFilter normally sits on top of a TcpTransport - * that has been configured with the StompWireFormat and is used to - * convert STOMP commands to ActiveMQ commands. - * - * All of the coversion work is done by delegating to the ProtocolConverter. - * + * The StompTransportFilter normally sits on top of a TcpTransport that has been + * configured with the StompWireFormat and is used to convert STOMP commands to + * ActiveMQ commands. All of the coversion work is done by delegating to the + * ProtocolConverter. + * * @author chirino */ public class StompTransportFilter extends TransportFilter { - static final private Log log = LogFactory.getLog(StompTransportFilter.class); + static final private Log log = LogFactory.getLog(StompTransportFilter.class); private final ProtocolConverter protocolConverter; private final Object sendToActiveMQMutex = new Object(); @@ -46,60 +45,59 @@ public class StompTransportFilter extends TransportFilter { private final FrameTranslator frameTranslator; private boolean trace; - + public StompTransportFilter(Transport next, FrameTranslator translator) { - super(next); + super(next); this.frameTranslator = translator; this.protocolConverter = new ProtocolConverter(this, translator); } - public void oneway(Object o) throws IOException { + public void oneway(Object o) throws IOException { try { - final Command command = (Command) o; - protocolConverter.onActiveMQCommad(command); - } catch (JMSException e) { - throw IOExceptionSupport.create(e); - } - } + final Command command = (Command)o; + protocolConverter.onActiveMQCommad(command); + } catch (JMSException e) { + throw IOExceptionSupport.create(e); + } + } - public void onCommand(Object command) { + public void onCommand(Object command) { try { - if( trace ) { - log.trace("Received: \n"+command); - } - protocolConverter.onStompCommad((StompFrame) command); - } catch (IOException e) { - onException(e); - } catch (JMSException e) { - onException(IOExceptionSupport.create(e)); - } - } + if (trace) { + log.trace("Received: \n" + command); + } + protocolConverter.onStompCommad((StompFrame)command); + } catch (IOException e) { + onException(e); + } catch (JMSException e) { + onException(IOExceptionSupport.create(e)); + } + } - public void sendToActiveMQ(Command command) { - synchronized(sendToActiveMQMutex) { - transportListener.onCommand(command); - } - } + public void sendToActiveMQ(Command command) { + synchronized (sendToActiveMQMutex) { + transportListener.onCommand(command); + } + } - public void sendToStomp(StompFrame command) throws IOException { - if( trace ) { - log.trace("Sending: \n"+command); - } - synchronized(sendToStompMutex) { - next.oneway(command); - } - } + public void sendToStomp(StompFrame command) throws IOException { + if (trace) { + log.trace("Sending: \n" + command); + } + synchronized (sendToStompMutex) { + next.oneway(command); + } + } - public FrameTranslator getFrameTranslator() - { + public FrameTranslator getFrameTranslator() { return frameTranslator; } - public boolean isTrace() { - return trace; - } + public boolean isTrace() { + return trace; + } - public void setTrace(boolean trace) { - this.trace = trace; - } + public void setTrace(boolean trace) { + this.trace = trace; + } } diff --git a/activemq-core/src/main/java/org/apache/activemq/transport/stomp/StompWireFormat.java b/activemq-core/src/main/java/org/apache/activemq/transport/stomp/StompWireFormat.java index 7047414275..a1d57383a3 100644 --- a/activemq-core/src/main/java/org/apache/activemq/transport/stomp/StompWireFormat.java +++ b/activemq-core/src/main/java/org/apache/activemq/transport/stomp/StompWireFormat.java @@ -31,21 +31,22 @@ import org.apache.activemq.util.ByteSequence; import org.apache.activemq.wireformat.WireFormat; /** - * Implements marshalling and unmarsalling the Stomp protocol. + * Implements marshalling and unmarsalling the Stomp protocol. */ public class StompWireFormat implements WireFormat { - private static final byte[] NO_DATA = new byte[]{}; - private static final byte[] END_OF_FRAME = new byte[]{0,'\n'}; - - private static final int MAX_COMMAND_LENGTH = 1024; - private static final int MAX_HEADER_LENGTH = 1024*10; - private static final int MAX_HEADERS = 1000; - private static final int MAX_DATA_LENGTH = 1024*1024*100; - - private int version=1; + private static final byte[] NO_DATA = new byte[] {}; + private static final byte[] END_OF_FRAME = new byte[] {0, '\n'}; - public ByteSequence marshal(Object command) throws IOException { + private static final int MAX_COMMAND_LENGTH = 1024; + private static final int MAX_HEADER_LENGTH = 1024 * 10; + private static final int MAX_HEADERS = 1000; + private static final int MAX_DATA_LENGTH = 1024 * 1024 * 100; + + private int version = 1; + + public ByteSequence marshal(Object command) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(baos); marshal(command, dos); @@ -60,140 +61,137 @@ public class StompWireFormat implements WireFormat { } public void marshal(Object command, DataOutput os) throws IOException { - StompFrame stomp = (org.apache.activemq.transport.stomp.StompFrame) command; + StompFrame stomp = (org.apache.activemq.transport.stomp.StompFrame)command; - StringBuffer buffer = new StringBuffer(); - buffer.append(stomp.getAction()); - buffer.append(Stomp.NEWLINE); + StringBuffer buffer = new StringBuffer(); + buffer.append(stomp.getAction()); + buffer.append(Stomp.NEWLINE); - // Output the headers. - for (Iterator iter = stomp.getHeaders().entrySet().iterator(); iter.hasNext();) { - Map.Entry entry = (Map.Entry) iter.next(); - buffer.append(entry.getKey()); - buffer.append(Stomp.Headers.SEPERATOR); - buffer.append(entry.getValue()); - buffer.append(Stomp.NEWLINE); - } + // Output the headers. + for (Iterator iter = stomp.getHeaders().entrySet().iterator(); iter.hasNext();) { + Map.Entry entry = (Map.Entry)iter.next(); + buffer.append(entry.getKey()); + buffer.append(Stomp.Headers.SEPERATOR); + buffer.append(entry.getValue()); + buffer.append(Stomp.NEWLINE); + } - // Add a newline to seperate the headers from the content. - buffer.append(Stomp.NEWLINE); + // Add a newline to seperate the headers from the content. + buffer.append(Stomp.NEWLINE); - os.write(buffer.toString().getBytes("UTF-8")); - os.write(stomp.getContent()); - os.write(END_OF_FRAME); - } - + os.write(buffer.toString().getBytes("UTF-8")); + os.write(stomp.getContent()); + os.write(END_OF_FRAME); + } public Object unmarshal(DataInput in) throws IOException { - + try { - String action = null; - - // skip white space to next real action line - while (true) { - action = readLine(in, MAX_COMMAND_LENGTH, "The maximum command length was exceeded"); - if (action == null) { - throw new IOException("connection was closed"); - } else { - action = action.trim(); - if (action.length() > 0) { - break; - } - } - } - - // Parse the headers - HashMap headers = new HashMap(25); - while (true) { - String line = readLine(in, MAX_HEADER_LENGTH, "The maximum header length was exceeded"); - if (line != null && line.trim().length() > 0) { - - if( headers.size() > MAX_HEADERS ) - throw new ProtocolException("The maximum number of headers was exceeded", true); - - try { - int seperator_index = line.indexOf(Stomp.Headers.SEPERATOR); - String name = line.substring(0, seperator_index).trim(); - String value = line.substring(seperator_index + 1, line.length()).trim(); - headers.put(name, value); - } - catch (Exception e) { - throw new ProtocolException("Unable to parser header line [" + line + "]", true); - } - } - else { - break; - } - } - - // Read in the data part. - byte[] data = NO_DATA; - String contentLength = (String)headers.get(Stomp.Headers.CONTENT_LENGTH); - if (contentLength!=null) { - - // Bless the client, he's telling us how much data to read in. - int length; - try { - length = Integer.parseInt(contentLength.trim()); - } catch (NumberFormatException e) { - throw new ProtocolException("Specified content-length is not a valid integer", true); - } + String action = null; - if( length > MAX_DATA_LENGTH ) - throw new ProtocolException("The maximum data length was exceeded", true); - - data = new byte[length]; - in.readFully(data); - - if (in.readByte() != 0) { - throw new ProtocolException(Stomp.Headers.CONTENT_LENGTH+" bytes were read and " + "there was no trailing null byte", true); - } - - } else { + // skip white space to next real action line + while (true) { + action = readLine(in, MAX_COMMAND_LENGTH, "The maximum command length was exceeded"); + if (action == null) { + throw new IOException("connection was closed"); + } else { + action = action.trim(); + if (action.length() > 0) { + break; + } + } + } - // We don't know how much to read.. data ends when we hit a 0 - byte b; - ByteArrayOutputStream baos=null; - while ((b = in.readByte()) != 0) { - - if( baos == null ) { - baos = new ByteArrayOutputStream(); - } else if( baos.size() > MAX_DATA_LENGTH ) { - throw new ProtocolException("The maximum data length was exceeded", true); - } - - baos.write(b); - } - - if( baos!=null ) { - baos.close(); - data = baos.toByteArray(); - } - - } - - return new StompFrame(action, headers, data); - - } catch (ProtocolException e) { - return new StompFrameError(e); - } + // Parse the headers + HashMap headers = new HashMap(25); + while (true) { + String line = readLine(in, MAX_HEADER_LENGTH, "The maximum header length was exceeded"); + if (line != null && line.trim().length() > 0) { + + if (headers.size() > MAX_HEADERS) + throw new ProtocolException("The maximum number of headers was exceeded", true); + + try { + int seperator_index = line.indexOf(Stomp.Headers.SEPERATOR); + String name = line.substring(0, seperator_index).trim(); + String value = line.substring(seperator_index + 1, line.length()).trim(); + headers.put(name, value); + } catch (Exception e) { + throw new ProtocolException("Unable to parser header line [" + line + "]", true); + } + } else { + break; + } + } + + // Read in the data part. + byte[] data = NO_DATA; + String contentLength = (String)headers.get(Stomp.Headers.CONTENT_LENGTH); + if (contentLength != null) { + + // Bless the client, he's telling us how much data to read in. + int length; + try { + length = Integer.parseInt(contentLength.trim()); + } catch (NumberFormatException e) { + throw new ProtocolException("Specified content-length is not a valid integer", true); + } + + if (length > MAX_DATA_LENGTH) + throw new ProtocolException("The maximum data length was exceeded", true); + + data = new byte[length]; + in.readFully(data); + + if (in.readByte() != 0) { + throw new ProtocolException(Stomp.Headers.CONTENT_LENGTH + " bytes were read and " + "there was no trailing null byte", true); + } + + } else { + + // We don't know how much to read.. data ends when we hit a 0 + byte b; + ByteArrayOutputStream baos = null; + while ((b = in.readByte()) != 0) { + + if (baos == null) { + baos = new ByteArrayOutputStream(); + } else if (baos.size() > MAX_DATA_LENGTH) { + throw new ProtocolException("The maximum data length was exceeded", true); + } + + baos.write(b); + } + + if (baos != null) { + baos.close(); + data = baos.toByteArray(); + } + + } + + return new StompFrame(action, headers, data); + + } catch (ProtocolException e) { + return new StompFrameError(e); + } } private String readLine(DataInput in, int maxLength, String errorMessage) throws IOException { byte b; - ByteArrayOutputStream baos=new ByteArrayOutputStream(maxLength); + ByteArrayOutputStream baos = new ByteArrayOutputStream(maxLength); while ((b = in.readByte()) != '\n') { - if( baos.size() > maxLength ) - throw new ProtocolException(errorMessage, true); + if (baos.size() > maxLength) + throw new ProtocolException(errorMessage, true); baos.write(b); } baos.close(); ByteSequence sequence = baos.toByteSequence(); - return new String(sequence.getData(),sequence.getOffset(),sequence.getLength(),"UTF-8"); - } + return new String(sequence.getData(), sequence.getOffset(), sequence.getLength(), "UTF-8"); + } - public int getVersion() { + public int getVersion() { return version; } diff --git a/activemq-core/src/main/java/org/apache/activemq/transport/tcp/SslTransport.java b/activemq-core/src/main/java/org/apache/activemq/transport/tcp/SslTransport.java index 87e20e9a21..2f8d643562 100644 --- a/activemq-core/src/main/java/org/apache/activemq/transport/tcp/SslTransport.java +++ b/activemq-core/src/main/java/org/apache/activemq/transport/tcp/SslTransport.java @@ -33,13 +33,13 @@ import javax.net.ssl.SSLSocketFactory; /** * A Transport class that uses SSL and client-side certificate authentication. - * - * Client-side certificate authentication must be enabled through the constructor. - * By default, this class will have the same client authentication behavior as the socket it is passed. - * This class will set ConnectionInfo's transportContext to the SSL certificates of the client. - * NOTE: Accessor method for needClientAuth was not provided on purpose. This is because needClientAuth's value must be - * set before the socket is connected. Otherwise, unexpected situations may occur. - * + * Client-side certificate authentication must be enabled through the + * constructor. By default, this class will have the same client authentication + * behavior as the socket it is passed. This class will set ConnectionInfo's + * transportContext to the SSL certificates of the client. NOTE: Accessor method + * for needClientAuth was not provided on purpose. This is because + * needClientAuth's value must be set before the socket is connected. Otherwise, + * unexpected situations may occur. */ public class SslTransport extends TcpTransport { /** @@ -47,11 +47,11 @@ public class SslTransport extends TcpTransport { * * @param wireFormat The WireFormat to be used. * @param socketFactory The socket factory to be used. Forcing SSLSockets - * for obvious reasons. + * for obvious reasons. * @param remoteLocation The remote location. * @param localLocation The local location. * @param needClientAuth If set to true, the underlying socket will need - * client certificate authentication. + * client certificate authentication. * @throws UnknownHostException If TcpTransport throws. * @throws IOException If TcpTransport throws. */ @@ -61,12 +61,10 @@ public class SslTransport extends TcpTransport { ((SSLSocket)this.socket).setNeedClientAuth(needClientAuth); } } - + /** - * Initialize from a ServerSocket. - * - * No access to needClientAuth is given since it is already set within the - * provided socket. + * Initialize from a ServerSocket. No access to needClientAuth is given + * since it is already set within the provided socket. * * @param wireFormat The WireFormat to be used. * @param socket The Socket to be used. Forcing SSL. @@ -75,31 +73,31 @@ public class SslTransport extends TcpTransport { public SslTransport(WireFormat wireFormat, SSLSocket socket) throws IOException { super(wireFormat, socket); } - + /** - * Overriding in order to add the client's certificates to ConnectionInfo Commmands. + * Overriding in order to add the client's certificates to ConnectionInfo + * Commmands. * * @param command The Command coming in. */ public void doConsume(Command command) { // The instanceof can be avoided, but that would require modifying the - // Command clas tree and that would require too much effort right - // now. - if ( command instanceof ConnectionInfo ) { + // Command clas tree and that would require too much effort right + // now. + if (command instanceof ConnectionInfo) { ConnectionInfo connectionInfo = (ConnectionInfo)command; - + SSLSocket sslSocket = (SSLSocket)this.socket; - + SSLSession sslSession = sslSocket.getSession(); - + X509Certificate[] clientCertChain; try { - clientCertChain = - (X509Certificate[]) sslSession.getPeerCertificates(); - } catch(SSLPeerUnverifiedException e) { + clientCertChain = (X509Certificate[])sslSession.getPeerCertificates(); + } catch (SSLPeerUnverifiedException e) { clientCertChain = null; } - + connectionInfo.setTransportContext(clientCertChain); } @@ -110,8 +108,7 @@ public class SslTransport extends TcpTransport { * @return pretty print of 'this' */ public String toString() { - return "ssl://"+socket.getInetAddress()+":"+socket.getPort(); + return "ssl://" + socket.getInetAddress() + ":" + socket.getPort(); } } - diff --git a/activemq-core/src/main/java/org/apache/activemq/transport/tcp/SslTransportFactory.java b/activemq-core/src/main/java/org/apache/activemq/transport/tcp/SslTransportFactory.java index 51910a9eeb..adb810c655 100644 --- a/activemq-core/src/main/java/org/apache/activemq/transport/tcp/SslTransportFactory.java +++ b/activemq-core/src/main/java/org/apache/activemq/transport/tcp/SslTransportFactory.java @@ -49,10 +49,10 @@ import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; /** - * An implementation of the TcpTransportFactory using SSL. - * - * The major contribution from this class is that it is aware of SslTransportServer and SslTransport classes. - * All Transports and TransportServers created from this factory will have their needClientAuth option set to false. + * An implementation of the TcpTransportFactory using SSL. The major + * contribution from this class is that it is aware of SslTransportServer and + * SslTransport classes. All Transports and TransportServers created from this + * factory will have their needClientAuth option set to false. * * @author sepandm@gmail.com (Sepand) * @version $Revision: $ @@ -60,17 +60,16 @@ import javax.net.ssl.TrustManager; public class SslTransportFactory extends TcpTransportFactory { // The context used to creat ssl sockets. private SSLContext sslContext = null; - + // The log this uses., private static final Log log = LogFactory.getLog(SslTransportFactory.class); - + /** * Constructor. Nothing special. - * */ public SslTransportFactory() { } - + /** * Overriding to use SslTransportServer and allow for proper reflection. */ @@ -79,31 +78,29 @@ public class SslTransportFactory extends TcpTransportFactory { Map options = new HashMap(URISupport.parseParamters(location)); ServerSocketFactory serverSocketFactory = createServerSocketFactory(); - SslTransportServer server = - new SslTransportServer(this, location, (SSLServerSocketFactory)serverSocketFactory); + SslTransportServer server = new SslTransportServer(this, location, (SSLServerSocketFactory)serverSocketFactory); server.setWireFormatFactory(createWireFormatFactory(options)); IntrospectionSupport.setProperties(server, options); Map transportOptions = IntrospectionSupport.extractProperties(options, "transport."); server.setTransportOption(transportOptions); server.bind(); - + return server; - } - catch (URISyntaxException e) { + } catch (URISyntaxException e) { throw IOExceptionSupport.create(e); } } - + /** * Overriding to allow for proper configuration through reflection. */ public Transport compositeConfigure(Transport transport, WireFormat format, Map options) { - - SslTransport sslTransport = (SslTransport) transport.narrow(SslTransport.class); + + SslTransport sslTransport = (SslTransport)transport.narrow(SslTransport.class); IntrospectionSupport.setProperties(sslTransport, options); - + Map socketOptions = IntrospectionSupport.extractProperties(options, "socket."); - + sslTransport.setSocketOptions(socketOptions); if (sslTransport.isTrace()) { @@ -116,14 +113,14 @@ public class SslTransportFactory extends TcpTransportFactory { if (format instanceof OpenWireFormat) { transport = new WireFormatNegotiator(transport, (OpenWireFormat)format, sslTransport.getMinmumWireFormatVersion()); } - + return transport; } - + /** * Overriding to use SslTransports. */ - protected Transport createTransport(URI location,WireFormat wf) throws UnknownHostException,IOException{ + protected Transport createTransport(URI location, WireFormat wf) throws UnknownHostException, IOException { URI localLocation = null; String path = location.getPath(); // see if the path is a local URI location @@ -133,18 +130,16 @@ public class SslTransportFactory extends TcpTransportFactory { Integer.parseInt(path.substring((localPortIndex + 1), path.length())); String localString = location.getScheme() + ":/" + path; localLocation = new URI(localString); - } - catch (Exception e) { + } catch (Exception e) { log.warn("path isn't a valid local location for SslTransport to use", e); } } SocketFactory socketFactory = createSocketFactory(); return new SslTransport(wf, (SSLSocketFactory)socketFactory, location, localLocation, false); } - + /** * Sets the key and trust managers used in constructed socket factories. - * * Passes given arguments to SSLContext.init(...). * * @param km The sources of authentication keys or null. @@ -161,36 +156,31 @@ public class SslTransportFactory extends TcpTransportFactory { } sslContext.init(km, tm, random); } - + /** - * Creates a new SSL ServerSocketFactory. - * - * The given factory will use user-provided key and trust managers (if the user provided them). + * Creates a new SSL ServerSocketFactory. The given factory will use + * user-provided key and trust managers (if the user provided them). * * @return Newly created (Ssl)ServerSocketFactory. */ protected ServerSocketFactory createServerSocketFactory() { if (sslContext == null) { return SSLServerSocketFactory.getDefault(); - } - else + } else return sslContext.getServerSocketFactory(); } /** - * Creates a new SSL SocketFactory. - * - * The given factory will use user-provided key and trust managers (if the user provided them). + * Creates a new SSL SocketFactory. The given factory will use user-provided + * key and trust managers (if the user provided them). * * @return Newly created (Ssl)SocketFactory. */ protected SocketFactory createSocketFactory() { - if ( sslContext == null ) { + if (sslContext == null) { return SSLSocketFactory.getDefault(); - } - else + } else return sslContext.getSocketFactory(); } - } diff --git a/activemq-core/src/main/java/org/apache/activemq/transport/tcp/TcpBufferedInputStream.java b/activemq-core/src/main/java/org/apache/activemq/transport/tcp/TcpBufferedInputStream.java index 9431a9959f..ebab7576c2 100755 --- a/activemq-core/src/main/java/org/apache/activemq/transport/tcp/TcpBufferedInputStream.java +++ b/activemq-core/src/main/java/org/apache/activemq/transport/tcp/TcpBufferedInputStream.java @@ -19,107 +19,108 @@ package org.apache.activemq.transport.tcp; import java.io.FilterInputStream; import java.io.IOException; import java.io.InputStream; + /** * An optimized buffered input stream for Tcp * * @version $Revision: 1.1.1.1 $ */ -public class TcpBufferedInputStream extends FilterInputStream{ - private static final int DEFAULT_BUFFER_SIZE=8192; +public class TcpBufferedInputStream extends FilterInputStream { + private static final int DEFAULT_BUFFER_SIZE = 8192; protected byte internalBuffer[]; protected int count; protected int position; - public TcpBufferedInputStream(InputStream in){ - this(in,DEFAULT_BUFFER_SIZE); + public TcpBufferedInputStream(InputStream in) { + this(in, DEFAULT_BUFFER_SIZE); } - public TcpBufferedInputStream(InputStream in,int size){ + public TcpBufferedInputStream(InputStream in, int size) { super(in); - if(size<=0){ + if (size <= 0) { throw new IllegalArgumentException("Buffer size <= 0"); } - internalBuffer=new byte[size]; + internalBuffer = new byte[size]; } - private void fill() throws IOException{ - byte[] buffer=internalBuffer; - count=position=0; - int n=in.read(buffer,position,buffer.length-position); - if(n>0) - count=n+position; + private void fill() throws IOException { + byte[] buffer = internalBuffer; + count = position = 0; + int n = in.read(buffer, position, buffer.length - position); + if (n > 0) + count = n + position; } - public int read() throws IOException{ - if(position>=count){ + public int read() throws IOException { + if (position >= count) { fill(); - if(position>=count) + if (position >= count) return -1; } - return internalBuffer[position++]&0xff; + return internalBuffer[position++] & 0xff; } - private int readStream(byte[] b,int off,int len) throws IOException{ - int avail=count-position; - if(avail<=0){ - if(len>=internalBuffer.length){ - return in.read(b,off,len); + private int readStream(byte[] b, int off, int len) throws IOException { + int avail = count - position; + if (avail <= 0) { + if (len >= internalBuffer.length) { + return in.read(b, off, len); } fill(); - avail=count-position; - if(avail<=0) + avail = count - position; + if (avail <= 0) return -1; } - int cnt=(avail=len) + int n = 0; + for (;;) { + int nread = readStream(b, off + n, len - n); + if (nread <= 0) + return (n == 0) ? nread : n; + n += nread; + if (n >= len) return n; // if not closed but no bytes available, return - InputStream input=in; - if(input!=null&&input.available()<=0) + InputStream input = in; + if (input != null && input.available() <= 0) return n; } } - public long skip(long n) throws IOException{ - if(n<=0){ + public long skip(long n) throws IOException { + if (n <= 0) { return 0; } - long avail=count-position; - if(avail<=0){ + long avail = count - position; + if (avail <= 0) { return in.skip(n); } - long skipped=(avail= len) { System.arraycopy(b, off, buffer, count, len); count += len; - } - else { + } else { out.write(b, off, len); } } /** - * flush the data to the output stream - * This doesn't call flush on the underlying outputstream, because - * Tcp is particularly efficent at doing this itself .... - * + * flush the data to the output stream This doesn't call flush on the + * underlying outputstream, because Tcp is particularly efficent at doing + * this itself .... + * * @throws IOException */ public void flush() throws IOException { @@ -112,7 +110,7 @@ public class TcpBufferedOutputStream extends FilterOutputStream { /** * close this stream - * + * * @throws IOException */ public void close() throws IOException { @@ -120,10 +118,9 @@ public class TcpBufferedOutputStream extends FilterOutputStream { closed = true; } - /** * Checks that the stream has not been closed - * + * * @throws IOException */ private final void checkClosed() throws IOException { diff --git a/activemq-core/src/main/java/org/apache/activemq/transport/tcp/TcpTransport.java b/activemq-core/src/main/java/org/apache/activemq/transport/tcp/TcpTransport.java index 0dbda3314b..5c1a7fe755 100755 --- a/activemq-core/src/main/java/org/apache/activemq/transport/tcp/TcpTransport.java +++ b/activemq-core/src/main/java/org/apache/activemq/transport/tcp/TcpTransport.java @@ -45,7 +45,7 @@ import org.apache.commons.logging.LogFactory; /** * An implementation of the {@link Transport} interface using raw tcp/ip - * + * * @version $Revision$ */ public class TcpTransport extends TransportThreadSupport implements Transport, Service, Runnable { @@ -74,12 +74,11 @@ public class TcpTransport extends TransportThreadSupport implements Transport, S /** * Connect to a remote Node - e.g. a Broker - * + * * @param wireFormat * @param socketFactory * @param remoteLocation - * @param localLocation - - * e.g. local InetAddress and local port + * @param localLocation - e.g. local InetAddress and local port * @throws IOException * @throws UnknownHostException */ @@ -88,8 +87,7 @@ public class TcpTransport extends TransportThreadSupport implements Transport, S this.socketFactory = socketFactory; try { this.socket = socketFactory.createSocket(); - } - catch (SocketException e) { + } catch (SocketException e) { this.socket = null; } this.remoteLocation = remoteLocation; @@ -97,10 +95,9 @@ public class TcpTransport extends TransportThreadSupport implements Transport, S setDaemon(false); } - /** * Initialize from a server Socket - * + * * @param wireFormat * @param socket * @throws IOException @@ -135,28 +132,25 @@ public class TcpTransport extends TransportThreadSupport implements Transport, S public void run() { log.trace("TCP consumer thread starting"); try { - while (!isStopped()) { - doRun(); - } + while (!isStopped()) { + doRun(); + } } catch (IOException e) { - stoppedLatch.get().countDown(); + stoppedLatch.get().countDown(); onException(e); } finally { - stoppedLatch.get().countDown(); + stoppedLatch.get().countDown(); } } - - protected void doRun() throws IOException { - try { - Object command = readCommand(); - doConsume(command); - } - catch (SocketTimeoutException e) { - } - catch (InterruptedIOException e) { - } - } + protected void doRun() throws IOException { + try { + Object command = readCommand(); + doConsume(command); + } catch (SocketTimeoutException e) { + } catch (InterruptedIOException e) { + } + } protected Object readCommand() throws IOException { return wireFormat.unmarshal(dataIn); @@ -248,22 +242,21 @@ public class TcpTransport extends TransportThreadSupport implements Transport, S public void setTcpNoDelay(Boolean tcpNoDelay) { this.tcpNoDelay = tcpNoDelay; } - + /** * @return the ioBufferSize */ - public int getIoBufferSize(){ + public int getIoBufferSize() { return this.ioBufferSize; } /** * @param ioBufferSize the ioBufferSize to set */ - public void setIoBufferSize(int ioBufferSize){ - this.ioBufferSize=ioBufferSize; + public void setIoBufferSize(int ioBufferSize) { + this.ioBufferSize = ioBufferSize; } - // Implementation methods // ------------------------------------------------------------------------- protected String resolveHostName(String host) throws UnknownHostException { @@ -278,7 +271,7 @@ public class TcpTransport extends TransportThreadSupport implements Transport, S /** * Configures the socket for use - * + * * @param sock * @throws SocketException */ @@ -290,8 +283,7 @@ public class TcpTransport extends TransportThreadSupport implements Transport, S try { sock.setReceiveBufferSize(socketBufferSize); sock.setSendBufferSize(socketBufferSize); - } - catch (SocketException se) { + } catch (SocketException se) { log.warn("Cannot set socket buffer size = " + socketBufferSize); log.debug("Cannot set socket buffer size. Reason: " + se, se); } @@ -340,20 +332,17 @@ public class TcpTransport extends TransportThreadSupport implements Transport, S if (remoteAddress != null) { if (connectionTimeout >= 0) { socket.connect(remoteAddress, connectionTimeout); - } - else { + } else { socket.connect(remoteAddress); } } - } - else { + } else { // For SSL sockets.. you can't create an unconnected socket :( // This means the timout option are not supported either. if (localAddress != null) { socket = socketFactory.createSocket(remoteAddress.getAddress(), remoteAddress.getPort(), localAddress.getAddress(), localAddress.getPort()); - } - else { + } else { socket = socketFactory.createSocket(remoteAddress.getAddress(), remoteAddress.getPort()); } } @@ -362,7 +351,6 @@ public class TcpTransport extends TransportThreadSupport implements Transport, S initializeStreams(); } - protected void doStop(ServiceStopper stopper) throws Exception { if (log.isDebugEnabled()) { log.debug("Stopping transport " + this); @@ -375,18 +363,17 @@ public class TcpTransport extends TransportThreadSupport implements Transport, S socket.close(); } } - - + /** * Override so that stop() blocks until the run thread is no longer running. */ @Override public void stop() throws Exception { - super.stop(); - CountDownLatch countDownLatch = stoppedLatch.get(); - if( countDownLatch!=null ) { - countDownLatch.await(); - } + super.stop(); + CountDownLatch countDownLatch = stoppedLatch.get(); + if (countDownLatch != null) { + countDownLatch.await(); + } } protected void initializeStreams() throws Exception { @@ -416,7 +403,4 @@ public class TcpTransport extends TransportThreadSupport implements Transport, S return null; } - - - } diff --git a/activemq-core/src/main/java/org/apache/activemq/transport/tcp/TcpTransportFactory.java b/activemq-core/src/main/java/org/apache/activemq/transport/tcp/TcpTransportFactory.java index a6fd7a742b..26b05eef71 100755 --- a/activemq-core/src/main/java/org/apache/activemq/transport/tcp/TcpTransportFactory.java +++ b/activemq-core/src/main/java/org/apache/activemq/transport/tcp/TcpTransportFactory.java @@ -42,6 +42,7 @@ import org.apache.commons.logging.LogFactory; public class TcpTransportFactory extends TransportFactory { private static final Log log = LogFactory.getLog(TcpTransportFactory.class); + public TransportServer doBind(String brokerId, final URI location) throws IOException { try { Map options = new HashMap(URISupport.parseParamters(location)); @@ -53,16 +54,16 @@ public class TcpTransportFactory extends TransportFactory { Map transportOptions = IntrospectionSupport.extractProperties(options, "transport."); server.setTransportOption(transportOptions); server.bind(); - + return server; - } - catch (URISyntaxException e) { + } catch (URISyntaxException e) { throw IOExceptionSupport.create(e); } } /** - * Allows subclasses of TcpTransportFactory to create custom instances of TcpTransportServer. + * Allows subclasses of TcpTransportFactory to create custom instances of + * TcpTransportServer. * * @param location * @param serverSocketFactory @@ -70,16 +71,16 @@ public class TcpTransportFactory extends TransportFactory { * @throws IOException * @throws URISyntaxException */ - protected TcpTransportServer createTcpTransportServer(final URI location, ServerSocketFactory serverSocketFactory) throws IOException, URISyntaxException { - return new TcpTransportServer(this, location, serverSocketFactory); - } + protected TcpTransportServer createTcpTransportServer(final URI location, ServerSocketFactory serverSocketFactory) throws IOException, URISyntaxException { + return new TcpTransportServer(this, location, serverSocketFactory); + } public Transport compositeConfigure(Transport transport, WireFormat format, Map options) { - - TcpTransport tcpTransport = (TcpTransport) transport.narrow(TcpTransport.class); + + TcpTransport tcpTransport = (TcpTransport)transport.narrow(TcpTransport.class); IntrospectionSupport.setProperties(tcpTransport, options); - - Map socketOptions = IntrospectionSupport.extractProperties(options, "socket."); + + Map socketOptions = IntrospectionSupport.extractProperties(options, "socket."); tcpTransport.setSocketOptions(socketOptions); if (tcpTransport.isTrace()) { @@ -91,10 +92,10 @@ public class TcpTransportFactory extends TransportFactory { } // Only need the WireFormatNegotiator if using openwire - if( format instanceof OpenWireFormat ) { - transport = new WireFormatNegotiator(transport, (OpenWireFormat)format, tcpTransport.getMinmumWireFormatVersion()); + if (format instanceof OpenWireFormat) { + transport = new WireFormatNegotiator(transport, (OpenWireFormat)format, tcpTransport.getMinmumWireFormatVersion()); } - + return transport; } @@ -105,9 +106,9 @@ public class TcpTransportFactory extends TransportFactory { return true; } - protected Transport createTransport(URI location,WireFormat wf) throws UnknownHostException,IOException{ - URI localLocation=null; - String path=location.getPath(); + protected Transport createTransport(URI location, WireFormat wf) throws UnknownHostException, IOException { + URI localLocation = null; + String path = location.getPath(); // see if the path is a local URI location if (path != null && path.length() > 0) { int localPortIndex = path.indexOf(':'); @@ -115,8 +116,7 @@ public class TcpTransportFactory extends TransportFactory { Integer.parseInt(path.substring((localPortIndex + 1), path.length())); String localString = location.getScheme() + ":/" + path; localLocation = new URI(localString); - } - catch (Exception e) { + } catch (Exception e) { log.warn("path isn't a valid local location for TcpTransport to use", e); } } @@ -125,19 +125,20 @@ public class TcpTransportFactory extends TransportFactory { } /** - * Allows subclasses of TcpTransportFactory to provide a create custom TcpTransport intances. + * Allows subclasses of TcpTransportFactory to provide a create custom + * TcpTransport intances. * * @param location * @param wf * @param socketFactory - * @param localLocation + * @param localLocation * @return * @throws UnknownHostException * @throws IOException */ - protected TcpTransport createTcpTransport(WireFormat wf, SocketFactory socketFactory, URI location, URI localLocation) throws UnknownHostException, IOException { - return new TcpTransport(wf, socketFactory, location, localLocation); - } + protected TcpTransport createTcpTransport(WireFormat wf, SocketFactory socketFactory, URI location, URI localLocation) throws UnknownHostException, IOException { + return new TcpTransport(wf, socketFactory, location, localLocation); + } protected ServerSocketFactory createServerSocketFactory() { return ServerSocketFactory.getDefault(); diff --git a/activemq-core/src/main/java/org/apache/activemq/transport/tcp/TcpTransportServer.java b/activemq-core/src/main/java/org/apache/activemq/transport/tcp/TcpTransportServer.java index 8788944cbf..871daff0b1 100755 --- a/activemq-core/src/main/java/org/apache/activemq/transport/tcp/TcpTransportServer.java +++ b/activemq-core/src/main/java/org/apache/activemq/transport/tcp/TcpTransportServer.java @@ -49,7 +49,7 @@ import javax.net.ServerSocketFactory; */ public class TcpTransportServer extends TransportServerThreadSupport { - + private static final Log log = LogFactory.getLog(TcpTransportServer.class); protected ServerSocket serverSocket; protected int backlog = 5000; @@ -60,16 +60,16 @@ public class TcpTransportServer extends TransportServerThreadSupport { protected boolean trace; protected Map transportOptions; protected final ServerSocketFactory serverSocketFactory; - + public TcpTransportServer(TcpTransportFactory transportFactory, URI location, ServerSocketFactory serverSocketFactory) throws IOException, URISyntaxException { super(location); - this.transportFactory=transportFactory; - this.serverSocketFactory = serverSocketFactory; + this.transportFactory = transportFactory; + this.serverSocketFactory = serverSocketFactory; } public void bind() throws IOException { - URI bind = getBindLocation(); - + URI bind = getBindLocation(); + String host = bind.getHost(); host = (host == null || host.length() == 0) ? "localhost" : host; InetAddress addr = InetAddress.getByName(host); @@ -77,31 +77,29 @@ public class TcpTransportServer extends TransportServerThreadSupport { try { if (host.trim().equals("localhost") || addr.equals(InetAddress.getLocalHost())) { this.serverSocket = serverSocketFactory.createServerSocket(bind.getPort(), backlog); - } - else { + } else { this.serverSocket = serverSocketFactory.createServerSocket(bind.getPort(), backlog, addr); } this.serverSocket.setSoTimeout(2000); - } - catch (IOException e) { + } catch (IOException e) { throw IOExceptionSupport.create("Failed to bind to server socket: " + bind + " due to: " + e, e); } try { - setConnectURI(new URI(bind.getScheme(), bind.getUserInfo(), resolveHostName(bind.getHost()), serverSocket.getLocalPort(), bind.getPath(), - bind.getQuery(), bind.getFragment())); - } catch (URISyntaxException e) { + setConnectURI(new URI(bind.getScheme(), bind.getUserInfo(), resolveHostName(bind.getHost()), serverSocket.getLocalPort(), bind.getPath(), bind.getQuery(), bind + .getFragment())); + } catch (URISyntaxException e) { - // it could be that the host name contains invalid characters such as _ on unix platforms + // it could be that the host name contains invalid characters such + // as _ on unix platforms // so lets try use the IP address instead try { - setConnectURI(new URI(bind.getScheme(), bind.getUserInfo(), addr.getHostAddress(), serverSocket.getLocalPort(), bind.getPath(), - bind.getQuery(), bind.getFragment())); + setConnectURI(new URI(bind.getScheme(), bind.getUserInfo(), addr.getHostAddress(), serverSocket.getLocalPort(), bind.getPath(), bind.getQuery(), bind.getFragment())); } catch (URISyntaxException e2) { throw IOExceptionSupport.create(e2); } } } - + /** * @return Returns the wireFormatFactory. */ @@ -110,8 +108,7 @@ public class TcpTransportServer extends TransportServerThreadSupport { } /** - * @param wireFormatFactory - * The wireFormatFactory to set. + * @param wireFormatFactory The wireFormatFactory to set. */ public void setWireFormatFactory(WireFormatFactory wireFormatFactory) { this.wireFormatFactory = wireFormatFactory; @@ -161,8 +158,7 @@ public class TcpTransportServer extends TransportServerThreadSupport { if (socket != null) { if (isStopped() || getAcceptListener() == null) { socket.close(); - } - else { + } else { HashMap options = new HashMap(); options.put("maxInactivityDuration", Long.valueOf(maxInactivityDuration)); options.put("minmumWireFormatVersion", Integer.valueOf(minmumWireFormatVersion)); @@ -174,13 +170,11 @@ public class TcpTransportServer extends TransportServerThreadSupport { getAcceptListener().onAccept(configuredTransport); } } - } - catch (SocketTimeoutException ste) { + } catch (SocketTimeoutException ste) { // expect this to happen - } - catch (Exception e) { + } catch (Exception e) { if (!isStopping()) { - onAcceptError(e); + onAcceptError(e); } else if (!isStopped()) { log.warn("run()", e); onAcceptError(e); @@ -190,25 +184,26 @@ public class TcpTransportServer extends TransportServerThreadSupport { } /** - * Allow derived classes to override the Transport implementation that this transport server creates. + * Allow derived classes to override the Transport implementation that this + * transport server creates. + * * @param socket * @param format * @return * @throws IOException */ - protected Transport createTransport(Socket socket, WireFormat format) throws IOException { - return new TcpTransport(format, socket); - } + protected Transport createTransport(Socket socket, WireFormat format) throws IOException { + return new TcpTransport(format, socket); + } /** * @return pretty print of this */ public String toString() { - return ""+getBindLocation(); + return "" + getBindLocation(); } /** - * * @param hostName * @return real hostName * @throws UnknownHostException diff --git a/activemq-core/src/main/java/org/apache/activemq/transport/udp/CommandDatagramChannel.java b/activemq-core/src/main/java/org/apache/activemq/transport/udp/CommandDatagramChannel.java index d44d2ded16..b56bcd5ea5 100644 --- a/activemq-core/src/main/java/org/apache/activemq/transport/udp/CommandDatagramChannel.java +++ b/activemq-core/src/main/java/org/apache/activemq/transport/udp/CommandDatagramChannel.java @@ -56,8 +56,8 @@ public class CommandDatagramChannel extends CommandChannelSupport { private int defaultMarshalBufferSize = 64 * 1024; public CommandDatagramChannel(UdpTransport transport, OpenWireFormat wireFormat, int datagramSize, - SocketAddress targetAddress, DatagramHeaderMarshaller headerMarshaller, DatagramChannel channel, - ByteBufferPool bufferPool) { + SocketAddress targetAddress, DatagramHeaderMarshaller headerMarshaller, + DatagramChannel channel, ByteBufferPool bufferPool) { super(transport, wireFormat, datagramSize, targetAddress, headerMarshaller); this.channel = channel; this.bufferPool = bufferPool; @@ -97,7 +97,7 @@ public class CommandDatagramChannel extends CommandChannelSupport { // the ByteBuffer to avoid object allocation and unnecessary // buffering? DataInputStream dataIn = new DataInputStream(new ByteArrayInputStream(data)); - answer = (Command) wireFormat.unmarshal(dataIn); + answer = (Command)wireFormat.unmarshal(dataIn); break; } } @@ -151,15 +151,14 @@ public class CommandDatagramChannel extends CommandChannelSupport { // lets remove the header of the partial command // which is the byte for the type and an int for the size of // the byte[] - chunkSize -= 1 // the data type - + 4 // the command ID - + 4; // the size of the partial data + + // data type + the command ID + size of the partial data + chunkSize -= 1 + 4 + 4; // the boolean flags if (bs != null) { chunkSize -= bs.marshalledSize(); - } - else { + } else { chunkSize -= 1; } @@ -176,8 +175,7 @@ public class CommandDatagramChannel extends CommandChannelSupport { if (lastFragment) { writeBuffer.put(LastPartialCommand.DATA_STRUCTURE_TYPE); - } - else { + } else { writeBuffer.put(PartialCommand.DATA_STRUCTURE_TYPE); } @@ -191,7 +189,7 @@ public class CommandDatagramChannel extends CommandChannelSupport { } writeBuffer.putInt(commandId); if (bs == null) { - writeBuffer.put((byte) 1); + writeBuffer.put((byte)1); } // size of byte array @@ -203,8 +201,7 @@ public class CommandDatagramChannel extends CommandChannelSupport { offset += chunkSize; sendWriteBuffer(commandId, address, writeBuffer, false); } - } - else { + } else { writeBuffer.put(data); sendWriteBuffer(command.getCommandId(), address, writeBuffer, false); } @@ -227,15 +224,15 @@ public class CommandDatagramChannel extends CommandChannelSupport { // Implementation methods // ------------------------------------------------------------------------- - protected void sendWriteBuffer(int commandId, SocketAddress address, ByteBuffer writeBuffer, boolean redelivery) - throws IOException { + protected void sendWriteBuffer(int commandId, SocketAddress address, ByteBuffer writeBuffer, + boolean redelivery) throws IOException { // lets put the datagram into the replay buffer first to prevent timing // issues ReplayBuffer bufferCache = getReplayBuffer(); if (bufferCache != null && !redelivery) { bufferCache.addBuffer(commandId, writeBuffer); } - + writeBuffer.flip(); if (log.isDebugEnabled()) { @@ -247,10 +244,9 @@ public class CommandDatagramChannel extends CommandChannelSupport { public void sendBuffer(int commandId, Object buffer) throws IOException { if (buffer != null) { - ByteBuffer writeBuffer = (ByteBuffer) buffer; + ByteBuffer writeBuffer = (ByteBuffer)buffer; sendWriteBuffer(commandId, getReplayAddress(), writeBuffer, true); - } - else { + } else { if (log.isWarnEnabled()) { log.warn("Request for buffer: " + commandId + " is no longer present"); } diff --git a/activemq-core/src/main/java/org/apache/activemq/transport/udp/CommandDatagramSocket.java b/activemq-core/src/main/java/org/apache/activemq/transport/udp/CommandDatagramSocket.java index c42ae1d8b5..84bd3d5761 100644 --- a/activemq-core/src/main/java/org/apache/activemq/transport/udp/CommandDatagramSocket.java +++ b/activemq-core/src/main/java/org/apache/activemq/transport/udp/CommandDatagramSocket.java @@ -48,8 +48,8 @@ public class CommandDatagramSocket extends CommandChannelSupport { private Object readLock = new Object(); private Object writeLock = new Object(); - public CommandDatagramSocket(UdpTransport transport, OpenWireFormat wireFormat, int datagramSize, - SocketAddress targetAddress, DatagramHeaderMarshaller headerMarshaller, DatagramSocket channel) { + public CommandDatagramSocket(UdpTransport transport, OpenWireFormat wireFormat, int datagramSize, SocketAddress targetAddress, DatagramHeaderMarshaller headerMarshaller, + DatagramSocket channel) { super(transport, wireFormat, datagramSize, targetAddress, headerMarshaller); this.channel = channel; } @@ -73,7 +73,7 @@ public class CommandDatagramSocket extends CommandChannelSupport { DataInputStream dataIn = new DataInputStream(new ByteArrayInputStream(datagram.getData())); from = headerMarshaller.createEndpoint(datagram, dataIn); - answer = (Command) wireFormat.unmarshal(dataIn); + answer = (Command)wireFormat.unmarshal(dataIn); break; } } @@ -100,8 +100,7 @@ public class CommandDatagramSocket extends CommandChannelSupport { if (remaining(writeBuffer) >= 0) { sendWriteBuffer(address, writeBuffer, command.getCommandId()); - } - else { + } else { // lets split the command up into chunks byte[] data = writeBuffer.toByteArray(); boolean lastFragment = false; @@ -125,15 +124,14 @@ public class CommandDatagramSocket extends CommandChannelSupport { // lets remove the header of the partial command // which is the byte for the type and an int for the size of // the byte[] - chunkSize -= 1 // the data type - + 4 // the command ID - + 4; // the size of the partial data + + // data type + the command ID + size of the partial data + chunkSize -= 1 + 4 + 4; // the boolean flags if (bs != null) { chunkSize -= bs.marshalledSize(); - } - else { + } else { chunkSize -= 1; } @@ -150,8 +148,7 @@ public class CommandDatagramSocket extends CommandChannelSupport { if (lastFragment) { dataOut.write(LastPartialCommand.DATA_STRUCTURE_TYPE); - } - else { + } else { dataOut.write(PartialCommand.DATA_STRUCTURE_TYPE); } @@ -165,7 +162,7 @@ public class CommandDatagramSocket extends CommandChannelSupport { } dataOut.writeInt(commandId); if (bs == null) { - dataOut.write((byte) 1); + dataOut.write((byte)1); } // size of byte array @@ -191,14 +188,12 @@ public class CommandDatagramSocket extends CommandChannelSupport { // Implementation methods // ------------------------------------------------------------------------- - protected void sendWriteBuffer(SocketAddress address, ByteArrayOutputStream writeBuffer, int commandId) - throws IOException { + protected void sendWriteBuffer(SocketAddress address, ByteArrayOutputStream writeBuffer, int commandId) throws IOException { byte[] data = writeBuffer.toByteArray(); sendWriteBuffer(commandId, address, data, false); } - protected void sendWriteBuffer(int commandId, SocketAddress address, byte[] data, boolean redelivery) - throws IOException { + protected void sendWriteBuffer(int commandId, SocketAddress address, byte[] data, boolean redelivery) throws IOException { // lets put the datagram into the replay buffer first to prevent timing // issues ReplayBuffer bufferCache = getReplayBuffer(); @@ -216,10 +211,9 @@ public class CommandDatagramSocket extends CommandChannelSupport { public void sendBuffer(int commandId, Object buffer) throws IOException { if (buffer != null) { - byte[] data = (byte[]) buffer; + byte[] data = (byte[])buffer; sendWriteBuffer(commandId, replayAddress, data, true); - } - else { + } else { if (log.isWarnEnabled()) { log.warn("Request for buffer: " + commandId + " is no longer present"); } diff --git a/activemq-core/src/main/java/org/apache/activemq/transport/udp/UdpTransport.java b/activemq-core/src/main/java/org/apache/activemq/transport/udp/UdpTransport.java index 6fb0a51edc..687620dc27 100755 --- a/activemq-core/src/main/java/org/apache/activemq/transport/udp/UdpTransport.java +++ b/activemq-core/src/main/java/org/apache/activemq/transport/udp/UdpTransport.java @@ -52,8 +52,8 @@ import java.nio.channels.DatagramChannel; public class UdpTransport extends TransportThreadSupport implements Transport, Service, Runnable { private static final Log log = LogFactory.getLog(UdpTransport.class); - private static final int MAX_BIND_ATTEMPTS = 50; - private static final long BIND_ATTEMPT_DELAY = 100; + private static final int MAX_BIND_ATTEMPTS = 50; + private static final long BIND_ATTEMPT_DELAY = 100; private CommandChannel commandChannel; private OpenWireFormat wireFormat; @@ -98,12 +98,11 @@ public class UdpTransport extends TransportThreadSupport implements Transport, S this.description = getProtocolName() + "Server@"; } - /** * Creates a replayer for working with the reliable transport */ public Replayer createReplayer() throws IOException { - if (replayEnabled ) { + if (replayEnabled) { return getCommandChannel(); } return null; @@ -124,7 +123,7 @@ public class UdpTransport extends TransportThreadSupport implements Transport, S log.debug("Sending oneway from: " + this + " to target: " + targetAddress + " command: " + command); } checkStarted(); - commandChannel.write((Command) command, address); + commandChannel.write((Command)command, address); } /** @@ -133,8 +132,7 @@ public class UdpTransport extends TransportThreadSupport implements Transport, S public String toString() { if (description != null) { return description + port; - } - else { + } else { return getProtocolUriScheme() + targetAddress + "@" + port; } } @@ -148,47 +146,38 @@ public class UdpTransport extends TransportThreadSupport implements Transport, S try { Command command = commandChannel.read(); doConsume(command); - } - catch (AsynchronousCloseException e) { + } catch (AsynchronousCloseException e) { // DatagramChannel closed try { stop(); - } - catch (Exception e2) { + } catch (Exception e2) { log.warn("Caught in: " + this + " while closing: " + e2 + ". Now Closed", e2); } - } - catch (SocketException e) { + } catch (SocketException e) { // DatagramSocket closed log.debug("Socket closed: " + e, e); try { stop(); - } - catch (Exception e2) { + } catch (Exception e2) { log.warn("Caught in: " + this + " while closing: " + e2 + ". Now Closed", e2); } - } - catch (EOFException e) { + } catch (EOFException e) { // DataInputStream closed log.debug("Socket closed: " + e, e); try { stop(); - } - catch (Exception e2) { + } catch (Exception e2) { log.warn("Caught in: " + this + " while closing: " + e2 + ". Now Closed", e2); } - } - catch (Exception e) { + } catch (Exception e) { try { stop(); - } - catch (Exception e2) { + } catch (Exception e2) { log.warn("Caught in: " + this + " while closing: " + e2 + ". Now Closed", e2); } if (e instanceof IOException) { - onException((IOException) e); - } - else { + onException((IOException)e); + } else { log.error("Caught: " + e, e); e.printStackTrace(); } @@ -204,7 +193,7 @@ public class UdpTransport extends TransportThreadSupport implements Transport, S */ public void setTargetEndpoint(Endpoint newTarget) { if (newTarget instanceof DatagramEndpoint) { - DatagramEndpoint endpoint = (DatagramEndpoint) newTarget; + DatagramEndpoint endpoint = (DatagramEndpoint)newTarget; SocketAddress address = endpoint.getAddress(); if (address != null) { if (originalTargetAddress == null) { @@ -305,14 +294,15 @@ public class UdpTransport extends TransportThreadSupport implements Transport, S public void setSequenceGenerator(IntSequenceGenerator sequenceGenerator) { this.sequenceGenerator = sequenceGenerator; } - + public boolean isReplayEnabled() { return replayEnabled; } /** - * Sets whether or not replay should be enabled when using the reliable transport. - * i.e. should we maintain a buffer of messages that can be replayed? + * Sets whether or not replay should be enabled when using the reliable + * transport. i.e. should we maintain a buffer of messages that can be + * replayed? */ public void setReplayEnabled(boolean replayEnabled) { this.replayEnabled = replayEnabled; @@ -328,7 +318,7 @@ public class UdpTransport extends TransportThreadSupport implements Transport, S public void setBufferPool(ByteBufferPool bufferPool) { this.bufferPool = bufferPool; } - + public ReplayBuffer getReplayBuffer() { return replayBuffer; } @@ -338,7 +328,6 @@ public class UdpTransport extends TransportThreadSupport implements Transport, S getCommandChannel().setReplayBuffer(replayBuffer); } - // Implementation methods // ------------------------------------------------------------------------- @@ -391,26 +380,28 @@ public class UdpTransport extends TransportThreadSupport implements Transport, S if (log.isDebugEnabled()) { log.debug("Binding to address: " + localAddress); } - + // - // We have noticed that on some platfoms like linux, after you close down - // a previously bound socket, it can take a little while before we can bind it again. + // We have noticed that on some platfoms like linux, after you close + // down + // a previously bound socket, it can take a little while before we can + // bind it again. // - for(int i=0; i < MAX_BIND_ATTEMPTS; i++){ - try { - socket.bind(localAddress); - return; - } catch (BindException e) { - if ( i+1 == MAX_BIND_ATTEMPTS ) - throw e; - try { - Thread.sleep(BIND_ATTEMPT_DELAY); - } catch (InterruptedException e1) { + for (int i = 0; i < MAX_BIND_ATTEMPTS; i++) { + try { + socket.bind(localAddress); + return; + } catch (BindException e) { + if (i + 1 == MAX_BIND_ATTEMPTS) + throw e; + try { + Thread.sleep(BIND_ATTEMPT_DELAY); + } catch (InterruptedException e1) { Thread.currentThread().interrupt(); - throw e; - } - } - } + throw e; + } + } + } } @@ -457,17 +448,17 @@ public class UdpTransport extends TransportThreadSupport implements Transport, S } public InetSocketAddress getLocalSocketAddress() { - if( channel==null ) { + if (channel == null) { return null; } else { return (InetSocketAddress)channel.socket().getLocalSocketAddress(); } } - public String getRemoteAddress() { - if(targetAddress != null){ - return "" + targetAddress; - } - return null; - } + public String getRemoteAddress() { + if (targetAddress != null) { + return "" + targetAddress; + } + return null; + } } diff --git a/activemq-core/src/main/java/org/apache/activemq/transport/vm/VMTransport.java b/activemq-core/src/main/java/org/apache/activemq/transport/vm/VMTransport.java index 0e1b678496..c35dbcebdc 100755 --- a/activemq-core/src/main/java/org/apache/activemq/transport/vm/VMTransport.java +++ b/activemq-core/src/main/java/org/apache/activemq/transport/vm/VMTransport.java @@ -41,178 +41,176 @@ import org.apache.commons.logging.LogFactory; * * @version $Revision$ */ -public class VMTransport implements Transport,Task{ +public class VMTransport implements Transport, Task { - private static final Log log=LogFactory.getLog(VMTransport.class); - private static final AtomicLong nextId=new AtomicLong(0); - private static final TaskRunnerFactory taskRunnerFactory=new TaskRunnerFactory("VMTransport",Thread.NORM_PRIORITY, - true,1000); + private static final Log log = LogFactory.getLog(VMTransport.class); + private static final AtomicLong nextId = new AtomicLong(0); + private static final TaskRunnerFactory taskRunnerFactory = new TaskRunnerFactory("VMTransport", Thread.NORM_PRIORITY, true, 1000); protected VMTransport peer; protected TransportListener transportListener; protected boolean disposed; protected boolean marshal; protected boolean network; - protected boolean async=true; - protected int asyncQueueDepth=2000; - protected LinkedBlockingQueue messageQueue=null; + protected boolean async = true; + protected int asyncQueueDepth = 2000; + protected LinkedBlockingQueue messageQueue = null; protected boolean started; protected final URI location; protected final long id; private TaskRunner taskRunner; - private final Object mutex=new Object(); + private final Object mutex = new Object(); - public VMTransport(URI location){ - this.location=location; - this.id=nextId.getAndIncrement(); + public VMTransport(URI location) { + this.location = location; + this.id = nextId.getAndIncrement(); } - public VMTransport getPeer(){ - synchronized(mutex){ + public VMTransport getPeer() { + synchronized (mutex) { return peer; } } - public void setPeer(VMTransport peer){ - synchronized(mutex){ - this.peer=peer; + public void setPeer(VMTransport peer) { + synchronized (mutex) { + this.peer = peer; } } - public void oneway(Object command) throws IOException{ - if(disposed){ + public void oneway(Object command) throws IOException { + if (disposed) { throw new TransportDisposedIOException("Transport disposed."); } - if(peer==null) + if (peer == null) throw new IOException("Peer not connected."); - TransportListener tl=null; - synchronized(peer.mutex) { - if( peer.disposed ) { - throw new TransportDisposedIOException("Peer ("+peer.toString()+") disposed."); - } - if( peer.started ) { - if(peer.async){ + TransportListener tl = null; + synchronized (peer.mutex) { + if (peer.disposed) { + throw new TransportDisposedIOException("Peer (" + peer.toString() + ") disposed."); + } + if (peer.started) { + if (peer.async) { peer.enqueue(command); - peer.wakeup(); + peer.wakeup(); } else { - tl = peer.transportListener; + tl = peer.transportListener; } - } else { - peer.enqueue(command); - } - } - - if( tl!=null ) { - tl.onCommand(command); - } - + } else { + peer.enqueue(command); + } + } + + if (tl != null) { + tl.onCommand(command); + } + } - private void enqueue(Object command) throws IOException { - try{ - getMessageQueue().put(command); - }catch(final InterruptedException e){ - throw IOExceptionSupport.create(e); - } - } + private void enqueue(Object command) throws IOException { + try { + getMessageQueue().put(command); + } catch (final InterruptedException e) { + throw IOExceptionSupport.create(e); + } + } - public FutureResponse asyncRequest(Object command,ResponseCallback responseCallback) throws IOException{ + public FutureResponse asyncRequest(Object command, ResponseCallback responseCallback) throws IOException { throw new AssertionError("Unsupported Method"); } - public Object request(Object command) throws IOException{ + public Object request(Object command) throws IOException { throw new AssertionError("Unsupported Method"); } - public Object request(Object command,int timeout) throws IOException{ + public Object request(Object command, int timeout) throws IOException { throw new AssertionError("Unsupported Method"); } - public TransportListener getTransportListener(){ - synchronized(mutex){ + public TransportListener getTransportListener() { + synchronized (mutex) { return transportListener; } } - public void setTransportListener(TransportListener commandListener){ - synchronized(mutex){ - this.transportListener=commandListener; + public void setTransportListener(TransportListener commandListener) { + synchronized (mutex) { + this.transportListener = commandListener; wakeup(); } } private LinkedBlockingQueue getMessageQueue() { - synchronized(mutex) { - if( messageQueue==null ) { - messageQueue=new LinkedBlockingQueue(this.asyncQueueDepth); - } - return messageQueue; - } + synchronized (mutex) { + if (messageQueue == null) { + messageQueue = new LinkedBlockingQueue(this.asyncQueueDepth); + } + return messageQueue; + } } - - - public void start() throws Exception{ - if(transportListener==null) + + public void start() throws Exception { + if (transportListener == null) throw new IOException("TransportListener not set."); - - synchronized(mutex) { - if( messageQueue!=null ) { - Object command; - while( (command = messageQueue.poll()) !=null ) { - transportListener.onCommand(command); - } - } - started = true; + + synchronized (mutex) { + if (messageQueue != null) { + Object command; + while ((command = messageQueue.poll()) != null) { + transportListener.onCommand(command); + } + } + started = true; wakeup(); } } - public void stop() throws Exception{ - TaskRunner tr=null; - synchronized(mutex) { - if(!disposed){ - started=false; - disposed=true; - if(taskRunner!=null){ - tr = taskRunner; - taskRunner=null; + public void stop() throws Exception { + TaskRunner tr = null; + synchronized (mutex) { + if (!disposed) { + started = false; + disposed = true; + if (taskRunner != null) { + tr = taskRunner; + taskRunner = null; } } } - if( tr !=null ) { - tr.shutdown(1000); - } + if (tr != null) { + tr.shutdown(1000); + } } - public Object narrow(Class target){ - if(target.isAssignableFrom(getClass())){ + public Object narrow(Class target) { + if (target.isAssignableFrom(getClass())) { return this; } return null; } - public boolean isMarshal(){ + public boolean isMarshal() { return marshal; } - public void setMarshal(boolean marshal){ - this.marshal=marshal; + public void setMarshal(boolean marshal) { + this.marshal = marshal; } - public boolean isNetwork(){ + public boolean isNetwork() { return network; } - public void setNetwork(boolean network){ - this.network=network; + public void setNetwork(boolean network) { + this.network = network; } - public String toString(){ - return location+"#"+id; + public String toString() { + return location + "#" + id; } - public String getRemoteAddress(){ - if(peer!=null){ + public String getRemoteAddress() { + if (peer != null) { return peer.toString(); } return null; @@ -221,68 +219,68 @@ public class VMTransport implements Transport,Task{ /** * @see org.apache.activemq.thread.Task#iterate() */ - public boolean iterate(){ + public boolean iterate() { final TransportListener tl; - synchronized(mutex){ - tl = transportListener; - if( !started || disposed || tl==null ) - return false; + synchronized (mutex) { + tl = transportListener; + if (!started || disposed || tl == null) + return false; } - + LinkedBlockingQueue mq = getMessageQueue(); - final Command command = (Command)mq.poll(); - if( command!=null ) { + final Command command = (Command)mq.poll(); + if (command != null) { tl.onCommand(command); return !mq.isEmpty(); } else { - return false; - } + return false; + } } /** * @return the async */ - public boolean isAsync(){ + public boolean isAsync() { return async; } /** * @param async the async to set */ - public void setAsync(boolean async){ - this.async=async; + public void setAsync(boolean async) { + this.async = async; } /** * @return the asyncQueueDepth */ - public int getAsyncQueueDepth(){ + public int getAsyncQueueDepth() { return asyncQueueDepth; } /** * @param asyncQueueDepth the asyncQueueDepth to set */ - public void setAsyncQueueDepth(int asyncQueueDepth){ - this.asyncQueueDepth=asyncQueueDepth; + public void setAsyncQueueDepth(int asyncQueueDepth) { + this.asyncQueueDepth = asyncQueueDepth; } - protected void wakeup(){ - if(async){ - synchronized(mutex){ - if(taskRunner==null){ - taskRunner=taskRunnerFactory.createTaskRunner(this,"VMTransport: "+toString()); + protected void wakeup() { + if (async) { + synchronized (mutex) { + if (taskRunner == null) { + taskRunner = taskRunnerFactory.createTaskRunner(this, "VMTransport: " + toString()); } } - try{ + try { taskRunner.wakeup(); - }catch(InterruptedException e){ + } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } } - public boolean isFaultTolerant(){ + public boolean isFaultTolerant() { return false; } } diff --git a/activemq-core/src/main/java/org/apache/activemq/transport/vm/VMTransportFactory.java b/activemq-core/src/main/java/org/apache/activemq/transport/vm/VMTransportFactory.java index 9b05476fc3..4668ddb391 100755 --- a/activemq-core/src/main/java/org/apache/activemq/transport/vm/VMTransportFactory.java +++ b/activemq-core/src/main/java/org/apache/activemq/transport/vm/VMTransportFactory.java @@ -39,111 +39,114 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import java.util.concurrent.ConcurrentHashMap; - -public class VMTransportFactory extends TransportFactory{ +public class VMTransportFactory extends TransportFactory { private static final Log log = LogFactory.getLog(VMTransportFactory.class); - final public static ConcurrentHashMap brokers=new ConcurrentHashMap(); - final public static ConcurrentHashMap connectors=new ConcurrentHashMap(); - final public static ConcurrentHashMap servers=new ConcurrentHashMap(); + final public static ConcurrentHashMap brokers = new ConcurrentHashMap(); + final public static ConcurrentHashMap connectors = new ConcurrentHashMap(); + final public static ConcurrentHashMap servers = new ConcurrentHashMap(); BrokerFactoryHandler brokerFactoryHandler; - public Transport doConnect(URI location) throws Exception{ + public Transport doConnect(URI location) throws Exception { return VMTransportServer.configure(doCompositeConnect(location)); } - public Transport doCompositeConnect(URI location) throws Exception{ + public Transport doCompositeConnect(URI location) throws Exception { URI brokerURI; String host; Map options; - boolean create=true; - CompositeData data=URISupport.parseComposite(location); - if(data.getComponents().length==1&&"broker".equals(data.getComponents()[0].getScheme())){ - brokerURI=data.getComponents()[0]; - CompositeData brokerData=URISupport.parseComposite(brokerURI); - host=(String) brokerData.getParameters().get("brokerName"); - if(host==null) - host="localhost"; - if(brokerData.getPath()!=null) - host=data.getPath(); - options=data.getParameters(); - location=new URI("vm://"+host); - }else{ - // If using the less complex vm://localhost?broker.persistent=true form - try{ - host=location.getHost(); - options=URISupport.parseParamters(location); - String config=(String) options.remove("brokerConfig"); - if(config!=null){ - brokerURI=new URI(config); - }else{ - Map brokerOptions=IntrospectionSupport.extractProperties(options,"broker."); - brokerURI=new URI("broker://()/"+host+"?"+URISupport.createQueryString(brokerOptions)); + boolean create = true; + CompositeData data = URISupport.parseComposite(location); + if (data.getComponents().length == 1 && "broker".equals(data.getComponents()[0].getScheme())) { + brokerURI = data.getComponents()[0]; + CompositeData brokerData = URISupport.parseComposite(brokerURI); + host = (String)brokerData.getParameters().get("brokerName"); + if (host == null) + host = "localhost"; + if (brokerData.getPath() != null) + host = data.getPath(); + options = data.getParameters(); + location = new URI("vm://" + host); + } else { + // If using the less complex vm://localhost?broker.persistent=true + // form + try { + host = location.getHost(); + options = URISupport.parseParamters(location); + String config = (String)options.remove("brokerConfig"); + if (config != null) { + brokerURI = new URI(config); + } else { + Map brokerOptions = IntrospectionSupport.extractProperties(options, "broker."); + brokerURI = new URI("broker://()/" + host + "?" + + URISupport.createQueryString(brokerOptions)); } - if( "false".equals(options.remove("create")) ) { - create=false; + if ("false".equals(options.remove("create"))) { + create = false; } - }catch(URISyntaxException e1){ + } catch (URISyntaxException e1) { throw IOExceptionSupport.create(e1); } - location=new URI("vm://"+host); + location = new URI("vm://" + host); } if (host == null) { host = "localhost"; } - VMTransportServer server=(VMTransportServer) servers.get(host); + VMTransportServer server = (VMTransportServer)servers.get(host); // validate the broker is still active - if(!validateBroker(host)||server==null){ - BrokerService broker=null; - // Synchronize on the registry so that multiple concurrent threads - // doing this do not think that the broker has not been created and cause multiple + if (!validateBroker(host) || server == null) { + BrokerService broker = null; + // Synchronize on the registry so that multiple concurrent threads + // doing this do not think that the broker has not been created and + // cause multiple // brokers to be started. - synchronized( BrokerRegistry.getInstance().getRegistryMutext() ) { - broker=BrokerRegistry.getInstance().lookup(host); - if(broker==null){ - if( !create ) { - throw new IOException("Broker named '"+host+"' does not exist."); - } - try{ - if(brokerFactoryHandler!=null){ - broker=brokerFactoryHandler.createBroker(brokerURI); - }else{ - broker=BrokerFactory.createBroker(brokerURI); + synchronized (BrokerRegistry.getInstance().getRegistryMutext()) { + broker = BrokerRegistry.getInstance().lookup(host); + if (broker == null) { + if (!create) { + throw new IOException("Broker named '" + host + "' does not exist."); + } + try { + if (brokerFactoryHandler != null) { + broker = brokerFactoryHandler.createBroker(brokerURI); + } else { + broker = BrokerFactory.createBroker(brokerURI); } broker.start(); - }catch(URISyntaxException e){ + } catch (URISyntaxException e) { throw IOExceptionSupport.create(e); } - brokers.put(host,broker); + brokers.put(host, broker); } - - server=(VMTransportServer) servers.get(host); - if(server==null){ - server=(VMTransportServer) bind(location,true); - TransportConnector connector=new TransportConnector(broker.getBroker(),server); + + server = (VMTransportServer)servers.get(host); + if (server == null) { + server = (VMTransportServer)bind(location, true); + TransportConnector connector = new TransportConnector(broker.getBroker(), server); connector.setUri(location); - connector.setTaskRunnerFactory( broker.getTaskRunnerFactory() ); + connector.setTaskRunnerFactory(broker.getTaskRunnerFactory()); connector.start(); - connectors.put(host,connector); + connectors.put(host, connector); } - + } } - - VMTransport vmtransport=server.connect(); - IntrospectionSupport.setProperties(vmtransport,options); - Transport transport=vmtransport; - if(vmtransport.isMarshal()){ - HashMap optionsCopy=new HashMap(options); - transport=new MarshallingTransportFilter(transport,createWireFormat(options),createWireFormat(optionsCopy)); + + VMTransport vmtransport = server.connect(); + IntrospectionSupport.setProperties(vmtransport, options); + Transport transport = vmtransport; + if (vmtransport.isMarshal()) { + HashMap optionsCopy = new HashMap(options); + transport = new MarshallingTransportFilter(transport, createWireFormat(options), + createWireFormat(optionsCopy)); } - if(!options.isEmpty()){ - throw new IllegalArgumentException("Invalid connect parameters: "+options); + if (!options.isEmpty()) { + throw new IllegalArgumentException("Invalid connect parameters: " + options); } return transport; } - public TransportServer doBind(String brokerId,URI location) throws IOException{ - return bind(location,false); + public TransportServer doBind(String brokerId, URI location) throws IOException { + return bind(location, false); } /** @@ -151,66 +154,67 @@ public class VMTransportFactory extends TransportFactory{ * @return the TransportServer * @throws IOException */ - private TransportServer bind(URI location,boolean dispose) throws IOException{ - String host=location.getHost(); + private TransportServer bind(URI location, boolean dispose) throws IOException { + String host = location.getHost(); log.debug("binding to broker: " + host); - VMTransportServer server=new VMTransportServer(location,dispose); - Object currentBoundValue=servers.get(host); - if(currentBoundValue!=null){ - throw new IOException("VMTransportServer already bound at: "+location); + VMTransportServer server = new VMTransportServer(location, dispose); + Object currentBoundValue = servers.get(host); + if (currentBoundValue != null) { + throw new IOException("VMTransportServer already bound at: " + location); } - servers.put(host,server); + servers.put(host, server); return server; } - public static void stopped(VMTransportServer server){ - String host=server.getBindURI().getHost(); + public static void stopped(VMTransportServer server) { + String host = server.getBindURI().getHost(); servers.remove(host); - TransportConnector connector=(TransportConnector) connectors.remove(host); - if(connector!=null){ - log.debug("Shutting down VM connectors for broker: " +host); + TransportConnector connector = (TransportConnector)connectors.remove(host); + if (connector != null) { + log.debug("Shutting down VM connectors for broker: " + host); ServiceSupport.dispose(connector); - BrokerService broker=(BrokerService) brokers.remove(host); - if(broker!=null){ + BrokerService broker = (BrokerService)brokers.remove(host); + if (broker != null) { ServiceSupport.dispose(broker); } } } - public static void stopped(String host){ + public static void stopped(String host) { servers.remove(host); - TransportConnector connector=(TransportConnector) connectors.remove(host); - if(connector!=null){ - log.debug("Shutting down VM connectors for broker: " +host); + TransportConnector connector = (TransportConnector)connectors.remove(host); + if (connector != null) { + log.debug("Shutting down VM connectors for broker: " + host); ServiceSupport.dispose(connector); - BrokerService broker=(BrokerService) brokers.remove(host); - if(broker!=null){ + BrokerService broker = (BrokerService)brokers.remove(host); + if (broker != null) { ServiceSupport.dispose(broker); } } } - public BrokerFactoryHandler getBrokerFactoryHandler(){ + public BrokerFactoryHandler getBrokerFactoryHandler() { return brokerFactoryHandler; } - public void setBrokerFactoryHandler(BrokerFactoryHandler brokerFactoryHandler){ - this.brokerFactoryHandler=brokerFactoryHandler; + public void setBrokerFactoryHandler(BrokerFactoryHandler brokerFactoryHandler) { + this.brokerFactoryHandler = brokerFactoryHandler; } - private boolean validateBroker(String host){ - boolean result=true; - if(brokers.containsKey(host)||servers.containsKey(host)||connectors.containsKey(host)){ + private boolean validateBroker(String host) { + boolean result = true; + if (brokers.containsKey(host) || servers.containsKey(host) || connectors.containsKey(host)) { // check the broker is still in the BrokerRegistry - TransportConnector connector=(TransportConnector) connectors.get(host); - if(BrokerRegistry.getInstance().lookup(host)==null||(connector!=null&&connector.getBroker().isStopped())){ - result=false; + TransportConnector connector = (TransportConnector)connectors.get(host); + if (BrokerRegistry.getInstance().lookup(host) == null + || (connector != null && connector.getBroker().isStopped())) { + result = false; // clean-up brokers.remove(host); servers.remove(host); - if(connector!=null){ + if (connector != null) { connectors.remove(host); - if(connector!=null){ + if (connector != null) { ServiceSupport.dispose(connector); } } diff --git a/activemq-core/src/main/java/org/apache/activemq/transport/vm/VMTransportServer.java b/activemq-core/src/main/java/org/apache/activemq/transport/vm/VMTransportServer.java index 31f5058dd1..eec705565e 100755 --- a/activemq-core/src/main/java/org/apache/activemq/transport/vm/VMTransportServer.java +++ b/activemq-core/src/main/java/org/apache/activemq/transport/vm/VMTransportServer.java @@ -31,33 +31,32 @@ import java.util.concurrent.atomic.AtomicInteger; /** * Broker side of the VMTransport - * */ public class VMTransportServer implements TransportServer { private TransportAcceptListener acceptListener; private final URI location; private boolean disposed; - + private final AtomicInteger connectionCount = new AtomicInteger(0); private final boolean disposeOnDisconnect; /** * @param location - * @param disposeOnDisconnect + * @param disposeOnDisconnect */ public VMTransportServer(URI location, boolean disposeOnDisconnect) { this.location = location; - this.disposeOnDisconnect=disposeOnDisconnect; + this.disposeOnDisconnect = disposeOnDisconnect; } - + /** - *@return a pretty print of this + * @return a pretty print of this */ - public String toString(){ - return "VMTransportServer(" + location +")"; + public String toString() { + return "VMTransportServer(" + location + ")"; } - + /** * @return new VMTransport * @throws IOException @@ -65,34 +64,35 @@ public class VMTransportServer implements TransportServer { public VMTransport connect() throws IOException { TransportAcceptListener al; synchronized (this) { - if( disposed ) + if (disposed) throw new IOException("Server has been disposed."); al = acceptListener; } - if( al == null) + if (al == null) throw new IOException("Server TransportAcceptListener is null."); - + connectionCount.incrementAndGet(); VMTransport client = new VMTransport(location) { public void stop() throws Exception { - if( disposed ) + if (disposed) return; super.stop(); - if( connectionCount.decrementAndGet()==0 && disposeOnDisconnect ) { + if (connectionCount.decrementAndGet() == 0 && disposeOnDisconnect) { VMTransportServer.this.stop(); } }; }; - + VMTransport server = new VMTransport(location); client.setPeer(server); server.setPeer(client); al.onAccept(configure(server)); return client; } - + /** * Configure transport + * * @param transport * @return the Transport */ @@ -102,14 +102,13 @@ public class VMTransportServer implements TransportServer { return transport; } - /** * Set the Transport accept listener for new Connections - * @param acceptListener * + * @param acceptListener */ synchronized public void setAcceptListener(TransportAcceptListener acceptListener) { - this.acceptListener = acceptListener; + this.acceptListener = acceptListener; } public void start() throws IOException { @@ -122,7 +121,7 @@ public class VMTransportServer implements TransportServer { public URI getConnectURI() { return location; } - + public URI getBindURI() { return location; } diff --git a/activemq-core/src/main/java/org/apache/activemq/util/BitArray.java b/activemq-core/src/main/java/org/apache/activemq/util/BitArray.java index f6b1b84984..d26f3078c2 100755 --- a/activemq-core/src/main/java/org/apache/activemq/util/BitArray.java +++ b/activemq-core/src/main/java/org/apache/activemq/util/BitArray.java @@ -21,8 +21,8 @@ import java.io.DataOutput; import java.io.IOException; /** - * Simple BitArray to enable setting multiple boolean values efficently Used instead of BitSet because BitSet does not - * allow for efficent serialization. + * Simple BitArray to enable setting multiple boolean values efficently Used + * instead of BitSet because BitSet does not allow for efficent serialization. * Will store up to 64 boolean values * * @version $Revision: 1.1.1.1 $ @@ -33,18 +33,26 @@ public class BitArray { static final int SHORT_SIZE = 16; static final int BYTE_SIZE = 8; private static final long[] BIT_VALUES = {0x0000000000000001L, 0x0000000000000002L, 0x0000000000000004L, - 0x0000000000000008L, 0x0000000000000010L, 0x0000000000000020L, 0x0000000000000040L, 0x0000000000000080L, - 0x0000000000000100L, 0x0000000000000200L, 0x0000000000000400L, 0x0000000000000800L, 0x0000000000001000L, - 0x0000000000002000L, 0x0000000000004000L, 0x0000000000008000L, 0x0000000000010000L, 0x0000000000020000L, - 0x0000000000040000L, 0x0000000000080000L, 0x0000000000100000L, 0x0000000000200000L, 0x0000000000400000L, - 0x0000000000800000L, 0x0000000001000000L, 0x0000000002000000L, 0x0000000004000000L, 0x0000000008000000L, - 0x0000000010000000L, 0x0000000020000000L, 0x0000000040000000L, 0x0000000080000000L, 0x0000000100000000L, - 0x0000000200000000L, 0x0000000400000000L, 0x0000000800000000L, 0x0000001000000000L, 0x0000002000000000L, - 0x0000004000000000L, 0x0000008000000000L, 0x0000010000000000L, 0x0000020000000000L, 0x0000040000000000L, - 0x0000080000000000L, 0x0000100000000000L, 0x0000200000000000L, 0x0000400000000000L, 0x0000800000000000L, - 0x0001000000000000L, 0x0002000000000000L, 0x0004000000000000L, 0x0008000000000000L, 0x0010000000000000L, - 0x0020000000000000L, 0x0040000000000000L, 0x0080000000000000L, 0x0100000000000000L, 0x0200000000000000L, - 0x0400000000000000L, 0x0800000000000000L, 0x1000000000000000L, 0x2000000000000000L, 0x4000000000000000L, + 0x0000000000000008L, 0x0000000000000010L, 0x0000000000000020L, + 0x0000000000000040L, 0x0000000000000080L, 0x0000000000000100L, + 0x0000000000000200L, 0x0000000000000400L, 0x0000000000000800L, + 0x0000000000001000L, 0x0000000000002000L, 0x0000000000004000L, + 0x0000000000008000L, 0x0000000000010000L, 0x0000000000020000L, + 0x0000000000040000L, 0x0000000000080000L, 0x0000000000100000L, + 0x0000000000200000L, 0x0000000000400000L, 0x0000000000800000L, + 0x0000000001000000L, 0x0000000002000000L, 0x0000000004000000L, + 0x0000000008000000L, 0x0000000010000000L, 0x0000000020000000L, + 0x0000000040000000L, 0x0000000080000000L, 0x0000000100000000L, + 0x0000000200000000L, 0x0000000400000000L, 0x0000000800000000L, + 0x0000001000000000L, 0x0000002000000000L, 0x0000004000000000L, + 0x0000008000000000L, 0x0000010000000000L, 0x0000020000000000L, + 0x0000040000000000L, 0x0000080000000000L, 0x0000100000000000L, + 0x0000200000000000L, 0x0000400000000000L, 0x0000800000000000L, + 0x0001000000000000L, 0x0002000000000000L, 0x0004000000000000L, + 0x0008000000000000L, 0x0010000000000000L, 0x0020000000000000L, + 0x0040000000000000L, 0x0080000000000000L, 0x0100000000000000L, + 0x0200000000000000L, 0x0400000000000000L, 0x0800000000000000L, + 0x1000000000000000L, 0x2000000000000000L, 0x4000000000000000L, 0x8000000000000000L}; private long bits; private int length; @@ -65,7 +73,7 @@ public class BitArray { /** * set the boolean value at the index - * + * * @param index * @param flag * @return the old value held at this index @@ -75,8 +83,7 @@ public class BitArray { boolean oldValue = (bits & BIT_VALUES[index]) != 0; if (flag) { bits |= BIT_VALUES[index]; - } - else if (oldValue) { + } else if (oldValue) { bits &= ~(BIT_VALUES[index]); } return oldValue; @@ -89,47 +96,45 @@ public class BitArray { public boolean get(int index) { return (bits & BIT_VALUES[index]) != 0; } - + /** * reset all the bit values to false */ - public void reset(){ + public void reset() { bits = 0; } - + /** * reset all the bits to the value supplied + * * @param bits */ - public void reset(long bits){ + public void reset(long bits) { this.bits = bits; } /** * write the bits to an output stream - * + * * @param dataOut * @throws IOException */ public void writeToStream(DataOutput dataOut) throws IOException { dataOut.writeByte(length); if (length <= BYTE_SIZE) { - dataOut.writeByte((int) bits); - } - else if (length <= SHORT_SIZE) { - dataOut.writeShort((short) bits); - } - else if (length <= INT_SIZE) { - dataOut.writeInt((int) bits); - } - else { + dataOut.writeByte((int)bits); + } else if (length <= SHORT_SIZE) { + dataOut.writeShort((short)bits); + } else if (length <= INT_SIZE) { + dataOut.writeInt((int)bits); + } else { dataOut.writeLong(bits); } } /** * read the bits from an input stream - * + * * @param dataIn * @throws IOException */ @@ -137,15 +142,12 @@ public class BitArray { length = dataIn.readByte(); if (length <= BYTE_SIZE) { bits = dataIn.readByte(); - } - else if (length <= SHORT_SIZE) { + } else if (length <= SHORT_SIZE) { bits = dataIn.readShort(); - } - else if (length <= INT_SIZE) { - bits=dataIn.readInt(); - } - else { + } else if (length <= INT_SIZE) { + bits = dataIn.readInt(); + } else { bits = dataIn.readLong(); } } -} \ No newline at end of file +} diff --git a/activemq-core/src/main/java/org/apache/activemq/util/BitArrayBin.java b/activemq-core/src/main/java/org/apache/activemq/util/BitArrayBin.java index b998222122..370a4249d2 100755 --- a/activemq-core/src/main/java/org/apache/activemq/util/BitArrayBin.java +++ b/activemq-core/src/main/java/org/apache/activemq/util/BitArrayBin.java @@ -21,23 +21,24 @@ import java.util.LinkedList; * * @version $Revision: 1.1.1.1 $ */ -public class BitArrayBin{ +public class BitArrayBin { private LinkedList list; private int maxNumberOfArrays; - private int firstIndex=-1; - private int firstBin=-1; + private int firstIndex = -1; + private int firstBin = -1; /** - * Create a BitArrayBin to a certain window size (number of messages to keep) + * Create a BitArrayBin to a certain window size (number of messages to + * keep) * * @param windowSize */ - public BitArrayBin(int windowSize){ - maxNumberOfArrays=((windowSize+1)/BitArray.LONG_SIZE)+1; - maxNumberOfArrays=Math.max(maxNumberOfArrays,1); - list=new LinkedList(); - for(int i=0;i(); + for (int i = 0; i < maxNumberOfArrays; i++) { list.add(new BitArray()); } } @@ -49,13 +50,13 @@ public class BitArrayBin{ * @param value * @return true if set */ - public boolean setBit(long index,boolean value){ - boolean answer=true; - BitArray ba=getBitArray(index); - if(ba!=null){ - int offset=getOffset(index); - if(offset>=0){ - answer=ba.set(offset,value); + public boolean setBit(long index, boolean value) { + boolean answer = true; + BitArray ba = getBitArray(index); + if (ba != null) { + int offset = getOffset(index); + if (offset >= 0) { + answer = ba.set(offset, value); } } return answer; @@ -67,18 +68,18 @@ public class BitArrayBin{ * @param index * @return true/false */ - public boolean getBit(long index){ - boolean answer=index>=firstIndex; - BitArray ba=getBitArray(index); - if(ba!=null){ - int offset=getOffset(index); - if(offset>=0){ - answer=ba.get(offset); + public boolean getBit(long index) { + boolean answer = index >= firstIndex; + BitArray ba = getBitArray(index); + if (ba != null) { + int offset = getOffset(index); + if (offset >= 0) { + answer = ba.get(offset); return answer; } - }else{ + } else { // gone passed range for previous bins so assume set - answer=true; + answer = true; } return answer; } @@ -89,20 +90,20 @@ public class BitArrayBin{ * @param index * @return BitArray */ - private BitArray getBitArray(long index){ - int bin=getBin(index); - BitArray answer=null; - if(bin>=0){ - if(firstIndex<0){ - firstIndex=0; + private BitArray getBitArray(long index) { + int bin = getBin(index); + BitArray answer = null; + if (bin >= 0) { + if (firstIndex < 0) { + firstIndex = 0; } - if(bin>=list.size()){ + if (bin >= list.size()) { list.removeFirst(); - firstIndex+=BitArray.LONG_SIZE; + firstIndex += BitArray.LONG_SIZE; list.add(new BitArray()); - bin=list.size()-1; + bin = list.size() - 1; } - answer=list.get(bin); + answer = list.get(bin); } return answer; } @@ -113,12 +114,12 @@ public class BitArrayBin{ * @param index * @return the index of the bin */ - private int getBin(long index){ - int answer=0; - if(firstBin<0){ - firstBin=0; - }else if(firstIndex>=0){ - answer=(int)((index-firstIndex)/BitArray.LONG_SIZE); + private int getBin(long index) { + int answer = 0; + if (firstBin < 0) { + firstBin = 0; + } else if (firstIndex >= 0) { + answer = (int)((index - firstIndex) / BitArray.LONG_SIZE); } return answer; } @@ -129,11 +130,11 @@ public class BitArrayBin{ * @param index * @return the relative offset into a bin */ - private int getOffset(long index){ - int answer=0; - if(firstIndex>=0){ - answer=(int)((index-firstIndex)-(BitArray.LONG_SIZE*getBin(index))); + private int getOffset(long index) { + int answer = 0; + if (firstIndex >= 0) { + answer = (int)((index - firstIndex) - (BitArray.LONG_SIZE * getBin(index))); } return answer; } -} \ No newline at end of file +} diff --git a/activemq-core/src/main/java/org/apache/activemq/util/BrokerSupport.java b/activemq-core/src/main/java/org/apache/activemq/util/BrokerSupport.java index 71f71597fe..98546bd850 100644 --- a/activemq-core/src/main/java/org/apache/activemq/util/BrokerSupport.java +++ b/activemq-core/src/main/java/org/apache/activemq/util/BrokerSupport.java @@ -24,7 +24,7 @@ import org.apache.activemq.command.ProducerInfo; import org.apache.activemq.state.ProducerState; public class BrokerSupport { - + /** * @param context * @param message @@ -32,14 +32,16 @@ public class BrokerSupport { * @throws Exception */ static public void resend(final ConnectionContext context, Message message, ActiveMQDestination deadLetterDestination) throws Exception { - if(message.getOriginalDestination()!=null) + if (message.getOriginalDestination() != null) { message.setOriginalDestination(message.getDestination()); - if(message.getOriginalTransactionId()!=null) - message.setOriginalTransactionId(message.getTransactionId()); + } + if (message.getOriginalTransactionId() != null) { + message.setOriginalTransactionId(message.getTransactionId()); + } message.setDestination(deadLetterDestination); message.setTransactionId(null); - boolean originalFlowControl=context.isProducerFlowControl(); - try{ + boolean originalFlowControl = context.isProducerFlowControl(); + try { context.setProducerFlowControl(false); ProducerInfo info = new ProducerInfo(); ProducerState state = new ProducerState(info); @@ -47,8 +49,8 @@ public class BrokerSupport { producerExchange.setProducerState(state); producerExchange.setMutable(true); producerExchange.setConnectionContext(context); - context.getBroker().send(producerExchange,message); - }finally{ + context.getBroker().send(producerExchange, message); + } finally { context.setProducerFlowControl(originalFlowControl); } } diff --git a/activemq-core/src/main/java/org/apache/activemq/util/ByteArrayInputStream.java b/activemq-core/src/main/java/org/apache/activemq/util/ByteArrayInputStream.java index 4dc6b5992a..ffc0fc1d4a 100644 --- a/activemq-core/src/main/java/org/apache/activemq/util/ByteArrayInputStream.java +++ b/activemq-core/src/main/java/org/apache/activemq/util/ByteArrayInputStream.java @@ -19,10 +19,9 @@ package org.apache.activemq.util; import java.io.IOException; import java.io.InputStream; - /** - * Very similar to the java.io.ByteArrayInputStream but this version - * is not thread safe. + * Very similar to the java.io.ByteArrayInputStream but this version is not + * thread safe. */ public class ByteArrayInputStream extends InputStream { @@ -34,19 +33,19 @@ public class ByteArrayInputStream extends InputStream { public ByteArrayInputStream(byte data[]) { this(data, 0, data.length); } - + public ByteArrayInputStream(ByteSequence sequence) { this(sequence.getData(), sequence.getOffset(), sequence.getLength()); } public ByteArrayInputStream(byte data[], int offset, int size) { this.buffer = data; - this.mark= this.pos = offset; - this.limit = offset+size; + this.mark = this.pos = offset; + this.limit = offset + size; } - + public int read() throws IOException { - if( pos < limit ) + if (pos < limit) return buffer[pos++] & 0xff; else return -1; @@ -55,10 +54,10 @@ public class ByteArrayInputStream extends InputStream { public int read(byte[] b) throws IOException { return read(b, 0, b.length); } - + public int read(byte b[], int off, int len) { if (pos < limit) { - len = Math.min(len, limit-pos); + len = Math.min(len, limit - pos); if (len > 0) { System.arraycopy(buffer, pos, b, off, len); pos += len; @@ -71,7 +70,7 @@ public class ByteArrayInputStream extends InputStream { public long skip(long len) throws IOException { if (pos < limit) { - len = Math.min(len, limit-pos); + len = Math.min(len, limit - pos); if (len > 0) { pos += len; } @@ -80,7 +79,7 @@ public class ByteArrayInputStream extends InputStream { return -1; } } - + public int available() { return limit - pos; } @@ -88,11 +87,11 @@ public class ByteArrayInputStream extends InputStream { public boolean markSupported() { return true; } - + public void mark(int markpos) { mark = pos; } - + public void reset() { pos = mark; } diff --git a/activemq-core/src/main/java/org/apache/activemq/util/ByteSequence.java b/activemq-core/src/main/java/org/apache/activemq/util/ByteSequence.java index 1d19bf99ab..41b6f8ca84 100644 --- a/activemq-core/src/main/java/org/apache/activemq/util/ByteSequence.java +++ b/activemq-core/src/main/java/org/apache/activemq/util/ByteSequence.java @@ -18,7 +18,7 @@ package org.apache.activemq.util; public class ByteSequence { - + public byte[] data; public int offset; public int length; @@ -26,41 +26,46 @@ public class ByteSequence { public ByteSequence(byte data[]) { this.data = data; this.offset = 0; - this.length = data.length; + this.length = data.length; } public ByteSequence(byte data[], int offset, int length) { this.data = data; this.offset = offset; - this.length = length; + this.length = length; } - + public byte[] getData() { return data; } + public int getLength() { return length; } + public int getOffset() { return offset; } - public void setData(byte[] data) { - this.data = data; - } - public void setLength(int length) { - this.length = length; - } - public void setOffset(int offset) { - this.offset = offset; - } - - public void compact() { - if( length != data.length ) { - byte t[] = new byte[length]; - System.arraycopy(data, offset, t, 0, length); - data=t; - offset=0; - } - } + + public void setData(byte[] data) { + this.data = data; + } + + public void setLength(int length) { + this.length = length; + } + + public void setOffset(int offset) { + this.offset = offset; + } + + public void compact() { + if (length != data.length) { + byte t[] = new byte[length]; + System.arraycopy(data, offset, t, 0, length); + data = t; + offset = 0; + } + } } diff --git a/activemq-core/src/main/java/org/apache/activemq/util/ByteSequenceData.java b/activemq-core/src/main/java/org/apache/activemq/util/ByteSequenceData.java index 868a5f76a8..a17b071aaa 100644 --- a/activemq-core/src/main/java/org/apache/activemq/util/ByteSequenceData.java +++ b/activemq-core/src/main/java/org/apache/activemq/util/ByteSequenceData.java @@ -18,41 +18,38 @@ package org.apache.activemq.util; import java.io.IOException; - /** * Used to write and read primitives to and from a ByteSequence. */ final public class ByteSequenceData { - - + public static byte[] toByteArray(ByteSequence packet) { - if( packet.offset==0 && packet.length == packet.data.length ) - return packet.data; - - byte rc[] = new byte[packet.length]; + if (packet.offset == 0 && packet.length == packet.data.length) + return packet.data; + + byte rc[] = new byte[packet.length]; System.arraycopy(packet.data, packet.offset, rc, 0, packet.length); return rc; - } + } private static void spaceNeeded(ByteSequence packet, int i) { - assert packet.offset+i <= packet.length; - } - - public static int remaining(ByteSequence packet) { - return packet.length - packet.offset; - } - - public static int read(ByteSequence packet) { - return packet.data[packet.offset++] & 0xff; - } + assert packet.offset + i <= packet.length; + } + public static int remaining(ByteSequence packet) { + return packet.length - packet.offset; + } + + public static int read(ByteSequence packet) { + return packet.data[packet.offset++] & 0xff; + } public static void readFully(ByteSequence packet, byte[] b) throws IOException { readFully(packet, b, 0, b.length); } - public static void readFully(ByteSequence packet, byte[] b, int off, int len) throws IOException { - spaceNeeded(packet, len); + public static void readFully(ByteSequence packet, byte[] b, int off, int len) throws IOException { + spaceNeeded(packet, len); System.arraycopy(packet.data, packet.offset, b, off, len); packet.offset += len; } @@ -63,14 +60,14 @@ final public class ByteSequenceData { return rc; } - public static boolean readBoolean(ByteSequence packet) throws IOException { + public static boolean readBoolean(ByteSequence packet) throws IOException { spaceNeeded(packet, 1); return read(packet) != 0; } - public static byte readByte(ByteSequence packet) throws IOException { + public static byte readByte(ByteSequence packet) throws IOException { spaceNeeded(packet, 1); - return (byte) read(packet); + return (byte)read(packet); } public static int readUnsignedByte(ByteSequence packet) throws IOException { @@ -80,72 +77,60 @@ final public class ByteSequenceData { public static short readShortBig(ByteSequence packet) throws IOException { spaceNeeded(packet, 2); - return (short) ((read(packet) << 8) + (read(packet) << 0)); + return (short)((read(packet) << 8) + (read(packet) << 0)); } + public static short readShortLittle(ByteSequence packet) throws IOException { spaceNeeded(packet, 2); - return (short) ((read(packet) << 0) + (read(packet) << 8) ); + return (short)((read(packet) << 0) + (read(packet) << 8)); } public static int readUnsignedShortBig(ByteSequence packet) throws IOException { spaceNeeded(packet, 2); return ((read(packet) << 8) + (read(packet) << 0)); } + public static int readUnsignedShortLittle(ByteSequence packet) throws IOException { spaceNeeded(packet, 2); - return ((read(packet) << 0) + (read(packet) << 8) ); + return ((read(packet) << 0) + (read(packet) << 8)); } public static char readCharBig(ByteSequence packet) throws IOException { spaceNeeded(packet, 2); - return (char) ((read(packet) << 8) + (read(packet) << 0)); + return (char)((read(packet) << 8) + (read(packet) << 0)); } + public static char readCharLittle(ByteSequence packet) throws IOException { spaceNeeded(packet, 2); - return (char) ((read(packet) << 0) + (read(packet) << 8) ); + return (char)((read(packet) << 0) + (read(packet) << 8)); } public static int readIntBig(ByteSequence packet) throws IOException { spaceNeeded(packet, 4); - return ((read(packet) << 24) + - (read(packet) << 16) + - (read(packet) << 8) + - (read(packet) << 0)); - } + return ((read(packet) << 24) + (read(packet) << 16) + (read(packet) << 8) + (read(packet) << 0)); + } + public static int readIntLittle(ByteSequence packet) throws IOException { spaceNeeded(packet, 4); - return ((read(packet) << 0) + - (read(packet) << 8) + - (read(packet) << 16) + - (read(packet) << 24)); - } - + return ((read(packet) << 0) + (read(packet) << 8) + (read(packet) << 16) + (read(packet) << 24)); + } + public static long readLongBig(ByteSequence packet) throws IOException { spaceNeeded(packet, 8); - return (((long) read(packet) << 56) + - ((long) read(packet) << 48) + - ((long) read(packet) << 40) + - ((long) read(packet) << 32) + - ((long) read(packet) << 24) + - ((read(packet)) << 16) + - ((read(packet)) << 8) + - ((read(packet)) << 0)); + return (((long)read(packet) << 56) + ((long)read(packet) << 48) + ((long)read(packet) << 40) + ((long)read(packet) << 32) + ((long)read(packet) << 24) + + ((read(packet)) << 16) + ((read(packet)) << 8) + ((read(packet)) << 0)); } + public static long readLongLittle(ByteSequence packet) throws IOException { spaceNeeded(packet, 8); - return ((read(packet) << 0) + - (read(packet) << 8) + - (read(packet) << 16) + - ((long) read(packet) << 24) + - ((long) read(packet) << 32) + - ((long) read(packet) << 40) + - ((long) read(packet) << 48) + - ((long) read(packet) << 56)); + return ((read(packet) << 0) + (read(packet) << 8) + (read(packet) << 16) + ((long)read(packet) << 24) + ((long)read(packet) << 32) + ((long)read(packet) << 40) + + ((long)read(packet) << 48) + ((long)read(packet) << 56)); } - + public static double readDoubleBig(ByteSequence packet) throws IOException { return Double.longBitsToDouble(readLongBig(packet)); } + public static double readDoubleLittle(ByteSequence packet) throws IOException { return Double.longBitsToDouble(readLongLittle(packet)); } @@ -153,91 +138,104 @@ final public class ByteSequenceData { public static float readFloatBig(ByteSequence packet) throws IOException { return Float.intBitsToFloat(readIntBig(packet)); } + public static float readFloatLittle(ByteSequence packet) throws IOException { return Float.intBitsToFloat(readIntLittle(packet)); } public static void write(ByteSequence packet, int b) throws IOException { spaceNeeded(packet, 1); - packet.data[packet.offset++] = (byte) b; + packet.data[packet.offset++] = (byte)b; } - + public static void write(ByteSequence packet, byte[] b) throws IOException { write(packet, b, 0, b.length); } + public static void write(ByteSequence packet, byte[] b, int off, int len) throws IOException { spaceNeeded(packet, len); System.arraycopy(b, off, packet.data, packet.offset, len); packet.offset += len; } + public static void writeBoolean(ByteSequence packet, boolean v) throws IOException { spaceNeeded(packet, 1); - write(packet,v ? 1 : 0); + write(packet, v ? 1 : 0); } + public static void writeByte(ByteSequence packet, int v) throws IOException { spaceNeeded(packet, 1); - write(packet,v); + write(packet, v); } + public static void writeShortBig(ByteSequence packet, int v) throws IOException { spaceNeeded(packet, 2); - write(packet,(v >>> 8) & 0xFF); - write(packet,(v >>> 0) & 0xFF); + write(packet, (v >>> 8) & 0xFF); + write(packet, (v >>> 0) & 0xFF); } + public static void writeShortLittle(ByteSequence packet, int v) throws IOException { spaceNeeded(packet, 2); - write(packet,(v >>> 0) & 0xFF); - write(packet,(v >>> 8) & 0xFF); + write(packet, (v >>> 0) & 0xFF); + write(packet, (v >>> 8) & 0xFF); } + public static void writeCharBig(ByteSequence packet, int v) throws IOException { spaceNeeded(packet, 2); - write(packet,(v >>> 8) & 0xFF); - write(packet,(v >>> 0) & 0xFF); + write(packet, (v >>> 8) & 0xFF); + write(packet, (v >>> 0) & 0xFF); } + public static void writeCharLittle(ByteSequence packet, int v) throws IOException { spaceNeeded(packet, 2); - write(packet,(v >>> 0) & 0xFF); - write(packet,(v >>> 8) & 0xFF); + write(packet, (v >>> 0) & 0xFF); + write(packet, (v >>> 8) & 0xFF); } + public static void writeIntBig(ByteSequence packet, int v) throws IOException { spaceNeeded(packet, 4); - write(packet,(v >>> 24) & 0xFF); - write(packet,(v >>> 16) & 0xFF); - write(packet,(v >>> 8) & 0xFF); - write(packet,(v >>> 0) & 0xFF); + write(packet, (v >>> 24) & 0xFF); + write(packet, (v >>> 16) & 0xFF); + write(packet, (v >>> 8) & 0xFF); + write(packet, (v >>> 0) & 0xFF); } + public static void writeIntLittle(ByteSequence packet, int v) throws IOException { spaceNeeded(packet, 4); - write(packet,(v >>> 0) & 0xFF); - write(packet,(v >>> 8) & 0xFF); - write(packet,(v >>> 16) & 0xFF); - write(packet,(v >>> 24) & 0xFF); + write(packet, (v >>> 0) & 0xFF); + write(packet, (v >>> 8) & 0xFF); + write(packet, (v >>> 16) & 0xFF); + write(packet, (v >>> 24) & 0xFF); } + public static void writeLongBig(ByteSequence packet, long v) throws IOException { spaceNeeded(packet, 8); - write(packet,(int) (v >>> 56) & 0xFF); - write(packet,(int) (v >>> 48) & 0xFF); - write(packet,(int) (v >>> 40) & 0xFF); - write(packet,(int) (v >>> 32) & 0xFF); - write(packet,(int) (v >>> 24) & 0xFF); - write(packet,(int) (v >>> 16) & 0xFF); - write(packet,(int) (v >>> 8) & 0xFF); - write(packet,(int) (v >>> 0) & 0xFF); + write(packet, (int)(v >>> 56) & 0xFF); + write(packet, (int)(v >>> 48) & 0xFF); + write(packet, (int)(v >>> 40) & 0xFF); + write(packet, (int)(v >>> 32) & 0xFF); + write(packet, (int)(v >>> 24) & 0xFF); + write(packet, (int)(v >>> 16) & 0xFF); + write(packet, (int)(v >>> 8) & 0xFF); + write(packet, (int)(v >>> 0) & 0xFF); } + public static void writeLongLittle(ByteSequence packet, long v) throws IOException { spaceNeeded(packet, 8); - write(packet,(int) (v >>> 0) & 0xFF); - write(packet,(int) (v >>> 8) & 0xFF); - write(packet,(int) (v >>> 16) & 0xFF); - write(packet,(int) (v >>> 24) & 0xFF); - write(packet,(int) (v >>> 32) & 0xFF); - write(packet,(int) (v >>> 40) & 0xFF); - write(packet,(int) (v >>> 48) & 0xFF); - write(packet,(int) (v >>> 56) & 0xFF); + write(packet, (int)(v >>> 0) & 0xFF); + write(packet, (int)(v >>> 8) & 0xFF); + write(packet, (int)(v >>> 16) & 0xFF); + write(packet, (int)(v >>> 24) & 0xFF); + write(packet, (int)(v >>> 32) & 0xFF); + write(packet, (int)(v >>> 40) & 0xFF); + write(packet, (int)(v >>> 48) & 0xFF); + write(packet, (int)(v >>> 56) & 0xFF); } - + public static void writeDoubleBig(ByteSequence packet, double v) throws IOException { writeLongBig(packet, Double.doubleToLongBits(v)); } + public static void writeDoubleLittle(ByteSequence packet, double v) throws IOException { writeLongLittle(packet, Double.doubleToLongBits(v)); } @@ -245,13 +243,15 @@ final public class ByteSequenceData { public static void writeFloatBig(ByteSequence packet, float v) throws IOException { writeIntBig(packet, Float.floatToIntBits(v)); } + public static void writeFloatLittle(ByteSequence packet, float v) throws IOException { writeIntLittle(packet, Float.floatToIntBits(v)); } - + public static void writeRawDoubleBig(ByteSequence packet, double v) throws IOException { writeLongBig(packet, Double.doubleToRawLongBits(v)); } + public static void writeRawDoubleLittle(ByteSequence packet, double v) throws IOException { writeLongLittle(packet, Double.doubleToRawLongBits(v)); } @@ -259,6 +259,7 @@ final public class ByteSequenceData { public static void writeRawFloatBig(ByteSequence packet, float v) throws IOException { writeIntBig(packet, Float.floatToRawIntBits(v)); } + public static void writeRawFloatLittle(ByteSequence packet, float v) throws IOException { writeIntLittle(packet, Float.floatToRawIntBits(v)); } diff --git a/activemq-core/src/main/java/org/apache/activemq/util/DataByteArrayInputStream.java b/activemq-core/src/main/java/org/apache/activemq/util/DataByteArrayInputStream.java index a6e9fb4f85..34fe8b7100 100755 --- a/activemq-core/src/main/java/org/apache/activemq/util/DataByteArrayInputStream.java +++ b/activemq-core/src/main/java/org/apache/activemq/util/DataByteArrayInputStream.java @@ -21,12 +21,13 @@ import java.io.IOException; import java.io.InputStream; import java.io.UTFDataFormatException; import org.apache.activemq.util.ByteSequence; + /** * Optimized ByteArrayInputStream that can be used more than once * * @version $Revision: 1.1.1.1 $ */ -public final class DataByteArrayInputStream extends InputStream implements DataInput{ +public final class DataByteArrayInputStream extends InputStream implements DataInput { private byte[] buf; private int pos; private int offset; @@ -36,62 +37,64 @@ public final class DataByteArrayInputStream extends InputStream implements DataI * * @param buf the input buffer. */ - public DataByteArrayInputStream(byte buf[]){ - this.buf=buf; - this.pos=0; + public DataByteArrayInputStream(byte buf[]) { + this.buf = buf; + this.pos = 0; this.offset = 0; } - + /** * Creates a StoreByteArrayInputStream. * * @param sequence the input buffer. */ - public DataByteArrayInputStream(ByteSequence sequence){ - this.buf=sequence.getData(); - this.offset=this.pos=sequence.getOffset(); + public DataByteArrayInputStream(ByteSequence sequence) { + this.buf = sequence.getData(); + this.offset = this.pos = sequence.getOffset(); } /** - * Creates WireByteArrayInputStream with a minmalist byte array + * Creates WireByteArrayInputStream with a minmalist byte + * array */ - public DataByteArrayInputStream(){ + public DataByteArrayInputStream() { this(new byte[0]); } /** - * * @return the size */ - public int size(){ - return pos-offset; + public int size() { + return pos - offset; } /** * @return the underlying data array */ - public byte[] getRawData(){ + public byte[] getRawData() { return buf; } /** - * reset the StoreByteArrayInputStream to use an new byte array + * reset the StoreByteArrayInputStream to use an new byte + * array * * @param newBuff */ - public void restart(byte[] newBuff){ - buf=newBuff; - pos=0; + public void restart(byte[] newBuff) { + buf = newBuff; + pos = 0; } - + /** - * reset the StoreByteArrayInputStream to use an new ByteSequence - * @param sequence - * + * reset the StoreByteArrayInputStream to use an new + * ByteSequence + * + * @param sequence */ - public void restart(ByteSequence sequence){ - this.buf=sequence.getData(); - this.pos=sequence.getOffset(); + public void restart(ByteSequence sequence) { + this.buf = sequence.getData(); + this.pos = sequence.getOffset(); } /** @@ -99,165 +102,169 @@ public final class DataByteArrayInputStream extends InputStream implements DataI * * @param size */ - public void restart(int size){ - if(buf==null||buf.lengthint in the - * range 0 to 255. If no byte is available because the end of the stream has been - * reached, the value -1 is returned. + * Reads the next byte of data from this input stream. The value byte is + * returned as an int in the range 0 to + * 255. If no byte is available because the end of the + * stream has been reached, the value -1 is returned. *

* This read method cannot block. * - * @return the next byte of data, or -1 if the end of the stream has been reached. + * @return the next byte of data, or -1 if the end of the + * stream has been reached. */ - public int read(){ - return (poslen bytes of data into an array of bytes from this input stream. + * Reads up to len bytes of data into an array of bytes from + * this input stream. * * @param b the buffer into which the data is read. * @param off the start offset of the data. * @param len the maximum number of bytes read. - * @return the total number of bytes read into the buffer, or -1 if there is no more data because the - * end of the stream has been reached. + * @return the total number of bytes read into the buffer, or + * -1 if there is no more data because the end of the + * stream has been reached. */ - public int read(byte b[],int off,int len){ - if(b==null){ + public int read(byte b[], int off, int len) { + if (b == null) { throw new NullPointerException(); } - if(pos>=buf.length){ + if (pos >= buf.length) { return -1; } - if(pos+len>buf.length){ - len=buf.length-pos; + if (pos + len > buf.length) { + len = buf.length - pos; } - if(len<=0){ + if (len <= 0) { return 0; } - System.arraycopy(buf,pos,b,off,len); - pos+=len; + System.arraycopy(buf, pos, b, off, len); + pos += len; return len; } /** - * @return the number of bytes that can be read from the input stream without blocking. + * @return the number of bytes that can be read from the input stream + * without blocking. */ - public int available(){ - return buf.length-pos; + public int available() { + return buf.length - pos; } - public void readFully(byte[] b){ - read(b,0,b.length); + public void readFully(byte[] b) { + read(b, 0, b.length); } - public void readFully(byte[] b,int off,int len){ - read(b,off,len); + public void readFully(byte[] b, int off, int len) { + read(b, off, len); } - public int skipBytes(int n){ - if(pos+n>buf.length){ - n=buf.length-pos; + public int skipBytes(int n) { + if (pos + n > buf.length) { + n = buf.length - pos; } - if(n<0){ + if (n < 0) { return 0; } - pos+=n; + pos += n; return n; } - public boolean readBoolean(){ - return read()!=0; + public boolean readBoolean() { + return read() != 0; } - public byte readByte(){ - return (byte) read(); + public byte readByte() { + return (byte)read(); } - public int readUnsignedByte(){ + public int readUnsignedByte() { return read(); } - public short readShort(){ - int ch1=read(); - int ch2=read(); - return (short) ((ch1<<8)+(ch2<<0)); + public short readShort() { + int ch1 = read(); + int ch2 = read(); + return (short)((ch1 << 8) + (ch2 << 0)); } - public int readUnsignedShort(){ - int ch1=read(); - int ch2=read(); - return ((ch1<<8)+(ch2<<0)); + public int readUnsignedShort() { + int ch1 = read(); + int ch2 = read(); + return ((ch1 << 8) + (ch2 << 0)); } - public char readChar(){ - int ch1=read(); - int ch2=read(); - return (char) ((ch1<<8)+(ch2<<0)); + public char readChar() { + int ch1 = read(); + int ch2 = read(); + return (char)((ch1 << 8) + (ch2 << 0)); } - public int readInt(){ - int ch1=read(); - int ch2=read(); - int ch3=read(); - int ch4=read(); - return ((ch1<<24)+(ch2<<16)+(ch3<<8)+(ch4<<0)); + public int readInt() { + int ch1 = read(); + int ch2 = read(); + int ch3 = read(); + int ch4 = read(); + return ((ch1 << 24) + (ch2 << 16) + (ch3 << 8) + (ch4 << 0)); } - public long readLong(){ - return (((long) buf[pos++]<<56)+((long) (buf[pos++]&255)<<48)+((long) (buf[pos++]&255)<<40) - +((long) (buf[pos++]&255)<<32)+((long) (buf[pos++]&255)<<24)+((buf[pos++]&255)<<16) - +((buf[pos++]&255)<<8)+((buf[pos++]&255)<<0)); + public long readLong() { + return (((long)buf[pos++] << 56) + ((long)(buf[pos++] & 255) << 48) + ((long)(buf[pos++] & 255) << 40) + ((long)(buf[pos++] & 255) << 32) + + ((long)(buf[pos++] & 255) << 24) + ((buf[pos++] & 255) << 16) + ((buf[pos++] & 255) << 8) + ((buf[pos++] & 255) << 0)); } - public float readFloat() throws IOException{ + public float readFloat() throws IOException { return Float.intBitsToFloat(readInt()); } - public double readDouble() throws IOException{ + public double readDouble() throws IOException { return Double.longBitsToDouble(readLong()); } - public String readLine(){ - int start=pos; - while(pos127) + public String readUTF() throws IOException { + int length = readUnsignedShort(); + char[] characters = new char[length]; + int c, c2, c3; + int count = 0; + int total = pos + length; + while (pos < total) { + c = (int)buf[pos] & 0xff; + if (c > 127) break; pos++; - characters[count++]=(char) c; + characters[count++] = (char)c; } - while(pos>4){ + while (pos < total) { + c = (int)buf[pos] & 0xff; + switch (c >> 4) { case 0: case 1: case 2: @@ -267,32 +274,32 @@ public final class DataByteArrayInputStream extends InputStream implements DataI case 6: case 7: pos++; - characters[count++]=(char) c; + characters[count++] = (char)c; break; case 12: case 13: - pos+=2; - if(pos>length) + pos += 2; + if (pos > length) throw new UTFDataFormatException("bad string"); - c2=(int) buf[pos-1]; - if((c2&0xC0)!=0x80) + c2 = (int)buf[pos - 1]; + if ((c2 & 0xC0) != 0x80) throw new UTFDataFormatException("bad string"); - characters[count++]=(char) (((c&0x1F)<<6)|(c2&0x3F)); + characters[count++] = (char)(((c & 0x1F) << 6) | (c2 & 0x3F)); break; case 14: - pos+=3; - if(pos>length) + pos += 3; + if (pos > length) throw new UTFDataFormatException("bad string"); - c2=(int) buf[pos-2]; - c3=(int) buf[pos-1]; - if(((c2&0xC0)!=0x80)||((c3&0xC0)!=0x80)) + c2 = (int)buf[pos - 2]; + c3 = (int)buf[pos - 1]; + if (((c2 & 0xC0) != 0x80) || ((c3 & 0xC0) != 0x80)) throw new UTFDataFormatException("bad string"); - characters[count++]=(char) (((c&0x0F)<<12)|((c2&0x3F)<<6)|((c3&0x3F)<<0)); + characters[count++] = (char)(((c & 0x0F) << 12) | ((c2 & 0x3F) << 6) | ((c3 & 0x3F) << 0)); break; default: throw new UTFDataFormatException("bad string"); } } - return new String(characters,0,count); + return new String(characters, 0, count); } } diff --git a/activemq-core/src/main/java/org/apache/activemq/util/FactoryFinder.java b/activemq-core/src/main/java/org/apache/activemq/util/FactoryFinder.java index d01d5ae4b5..f31cd59921 100644 --- a/activemq-core/src/main/java/org/apache/activemq/util/FactoryFinder.java +++ b/activemq-core/src/main/java/org/apache/activemq/util/FactoryFinder.java @@ -20,10 +20,8 @@ import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Properties; - import java.util.concurrent.ConcurrentHashMap; - public class FactoryFinder { private final String path; @@ -35,24 +33,21 @@ public class FactoryFinder { /** * Creates a new instance of the given key - * - * @param key is the key to add to the path to find a text file - * containing the factory name + * + * @param key is the key to add to the path to find a text file containing + * the factory name * @return a newly created instance */ - public Object newInstance(String key) - throws IllegalAccessException, InstantiationException, IOException, ClassNotFoundException - { + public Object newInstance(String key) throws IllegalAccessException, InstantiationException, IOException, ClassNotFoundException { return newInstance(key, null); } - public Object newInstance(String key, String propertyPrefix) - throws IllegalAccessException, InstantiationException, IOException, ClassNotFoundException - { - if (propertyPrefix == null) + public Object newInstance(String key, String propertyPrefix) throws IllegalAccessException, InstantiationException, IOException, ClassNotFoundException { + if (propertyPrefix == null) { propertyPrefix = ""; + } - Class clazz = (Class) classMap.get(propertyPrefix + key); + Class clazz = (Class)classMap.get(propertyPrefix + key); if (clazz == null) { clazz = newInstance(doFindFactoryProperies(key), propertyPrefix); classMap.put(propertyPrefix + key, clazz); @@ -71,8 +66,7 @@ public class FactoryFinder { if (loader != null) { try { clazz = loader.loadClass(className); - } - catch (ClassNotFoundException e) { + } catch (ClassNotFoundException e) { // ignore } } @@ -88,7 +82,8 @@ public class FactoryFinder { // lets try the thread context class loader first ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); - if (classLoader == null) classLoader = getClass().getClassLoader(); + if (classLoader == null) + classLoader = getClass().getClassLoader(); InputStream in = classLoader.getResourceAsStream(uri); if (in == null) { in = FactoryFinder.class.getClassLoader().getResourceAsStream(uri); diff --git a/activemq-core/src/main/java/org/apache/activemq/util/IdGenerator.java b/activemq-core/src/main/java/org/apache/activemq/util/IdGenerator.java index 9eed2c1b87..cd81f75f42 100755 --- a/activemq-core/src/main/java/org/apache/activemq/util/IdGenerator.java +++ b/activemq-core/src/main/java/org/apache/activemq/util/IdGenerator.java @@ -15,6 +15,7 @@ * limitations under the License. */ package org.apache.activemq.util; + import java.net.InetAddress; import java.net.ServerSocket; import java.util.logging.Level; @@ -24,93 +25,95 @@ import java.util.logging.Logger; * Generator for Globally unique Strings. */ -public class IdGenerator{ +public class IdGenerator { - private static final Logger log = Logger.getLogger(IdGenerator.class.getName()); - private static final String UNIQUE_STUB; - private static int instanceCount; + private static final Logger log = Logger.getLogger(IdGenerator.class.getName()); + private static final String UNIQUE_STUB; + private static int instanceCount; private static String hostName; - private String seed; - private long sequence; - - static { - String stub = ""; - boolean canAccessSystemProps = true; - try{ - SecurityManager sm = System.getSecurityManager(); - if(sm != null){ - sm.checkPropertiesAccess(); - } - }catch(SecurityException se){ - canAccessSystemProps = false; - } - - if ( canAccessSystemProps) { - try { - hostName = InetAddress.getLocalHost().getHostName(); - ServerSocket ss = new ServerSocket(0); - stub="-" + ss.getLocalPort() + "-" + System.currentTimeMillis() + "-"; - Thread.sleep(100); - ss.close(); - }catch(Exception ioe){ - log.log(Level.WARNING, "could not generate unique stub",ioe); - } - }else{ - hostName="localhost"; - stub = "-1-" +System.currentTimeMillis() +"-"; - } - UNIQUE_STUB = stub; - } - + private String seed; + private long sequence; + + static { + String stub = ""; + boolean canAccessSystemProps = true; + try { + SecurityManager sm = System.getSecurityManager(); + if (sm != null) { + sm.checkPropertiesAccess(); + } + } catch (SecurityException se) { + canAccessSystemProps = false; + } + + if (canAccessSystemProps) { + try { + hostName = InetAddress.getLocalHost().getHostName(); + ServerSocket ss = new ServerSocket(0); + stub = "-" + ss.getLocalPort() + "-" + System.currentTimeMillis() + "-"; + Thread.sleep(100); + ss.close(); + } catch (Exception ioe) { + log.log(Level.WARNING, "could not generate unique stub", ioe); + } + } else { + hostName = "localhost"; + stub = "-1-" + System.currentTimeMillis() + "-"; + } + UNIQUE_STUB = stub; + } + /** - * As we have to find the hostname as a side-affect of generating - * a unique stub, we allow it's easy retrevial here + * As we have to find the hostname as a side-affect of generating a unique + * stub, we allow it's easy retrevial here + * * @return the local host name */ - - public static String getHostName(){ + + public static String getHostName() { return hostName; } - - /** - * Construct an IdGenerator - * - */ - - public IdGenerator(String prefix){ - synchronized(UNIQUE_STUB){ - this.seed = prefix + UNIQUE_STUB +(instanceCount++) +":"; - } - } - - public IdGenerator(){ + + /** + * Construct an IdGenerator + */ + + public IdGenerator(String prefix) { + synchronized (UNIQUE_STUB) { + this.seed = prefix + UNIQUE_STUB + (instanceCount++) + ":"; + } + } + + public IdGenerator() { this("ID:" + hostName); } - - /** - * Generate a unqiue id - * @return a unique id - */ - - public synchronized String generateId(){ - return this.seed + (this.sequence++); - } - + /** - * Generate a unique ID - that is friendly for a URL or file system + * Generate a unqiue id + * * @return a unique id */ - public String generateSanitizedId(){ + + public synchronized String generateId() { + return this.seed + (this.sequence++); + } + + /** + * Generate a unique ID - that is friendly for a URL or file system + * + * @return a unique id + */ + public String generateSanitizedId() { String result = generateId(); result = result.replace(':', '-'); result = result.replace('_', '-'); result = result.replace('.', '-'); return result; } - + /** * From a generated id - return the seed (i.e. minus the count) - * + * * @param id the generated identifer * @return the seed */ @@ -127,7 +130,7 @@ public class IdGenerator{ /** * From a generated id - return the generator count - * + * * @param id * @return the count */ @@ -146,7 +149,7 @@ public class IdGenerator{ /** * Does a proper compare on the ids - * + * * @param id1 * @param id2 * @return 0 if equal else a positive if id1 is > id2 ... @@ -161,7 +164,7 @@ public class IdGenerator{ if (result == 0) { long count1 = IdGenerator.getSequenceFromId(id1); long count2 = IdGenerator.getSequenceFromId(id2); - result = (int) (count1 - count2); + result = (int)(count1 - count2); } } return result; diff --git a/activemq-core/src/main/java/org/apache/activemq/util/IntrospectionSupport.java b/activemq-core/src/main/java/org/apache/activemq/util/IntrospectionSupport.java index d4237d1c8b..ef4fd6261b 100755 --- a/activemq-core/src/main/java/org/apache/activemq/util/IntrospectionSupport.java +++ b/activemq-core/src/main/java/org/apache/activemq/util/IntrospectionSupport.java @@ -34,19 +34,18 @@ import java.util.Set; import java.util.Map.Entry; public class IntrospectionSupport { - - + static public boolean getProperties(Object target, Map props, String optionPrefix) { - + boolean rc = false; - if( target == null ) + if (target == null) throw new IllegalArgumentException("target was null."); - if( props == null ) + if (props == null) throw new IllegalArgumentException("props was null."); - - if( optionPrefix == null ) - optionPrefix=""; - + + if (optionPrefix == null) + optionPrefix = ""; + Class clazz = target.getClass(); Method[] methods = clazz.getMethods(); for (int i = 0; i < methods.length; i++) { @@ -54,47 +53,44 @@ public class IntrospectionSupport { String name = method.getName(); Class type = method.getReturnType(); Class params[] = method.getParameterTypes(); - if( name.startsWith("get") && params.length==0 && - type!=null && isSettableType(type)) { + if (name.startsWith("get") && params.length == 0 && type != null && isSettableType(type)) { - try { - - Object value = method.invoke(target, new Object[]{}); - if( value == null ) - continue; - - String strValue = convertToString(value, type); - if( strValue ==null ) - continue; - - name = name.substring(3,4).toLowerCase()+name.substring(4); - props.put(optionPrefix+name, strValue); + try { + + Object value = method.invoke(target, new Object[] {}); + if (value == null) + continue; + + String strValue = convertToString(value, type); + if (strValue == null) + continue; + + name = name.substring(3, 4).toLowerCase() + name.substring(4); + props.put(optionPrefix + name, strValue); rc = true; - - } catch ( Throwable ignore) { - } - + + } catch (Throwable ignore) { + } + } } - + return rc; } - - - + static public boolean setProperties(Object target, Map props, String optionPrefix) { boolean rc = false; - if( target == null ) + if (target == null) throw new IllegalArgumentException("target was null."); - if( props == null ) + if (props == null) throw new IllegalArgumentException("props was null."); - + for (Iterator iter = props.keySet().iterator(); iter.hasNext();) { - String name = (String) iter.next(); - if( name.startsWith(optionPrefix) ) { + String name = (String)iter.next(); + if (name.startsWith(optionPrefix)) { Object value = props.get(name); name = name.substring(optionPrefix.length()); - if( setProperty(target, name, value) ) { + if (setProperty(target, name, value)) { iter.remove(); rc = true; } @@ -102,42 +98,42 @@ public class IntrospectionSupport { } return rc; } - + public static Map extractProperties(Map props, String optionPrefix) { - if( props == null ) + if (props == null) throw new IllegalArgumentException("props was null."); HashMap rc = new HashMap(props.size()); - + for (Iterator iter = props.keySet().iterator(); iter.hasNext();) { - String name = (String) iter.next(); - if( name.startsWith(optionPrefix) ) { + String name = (String)iter.next(); + if (name.startsWith(optionPrefix)) { Object value = props.get(name); name = name.substring(optionPrefix.length()); rc.put(name, value); iter.remove(); } } - + return rc; } - + public static boolean setProperties(Object target, Map props) { - boolean rc = false; - - if( target == null ) + boolean rc = false; + + if (target == null) throw new IllegalArgumentException("target was null."); - if( props == null ) + if (props == null) throw new IllegalArgumentException("props was null."); - + for (Iterator iter = props.entrySet().iterator(); iter.hasNext();) { - Map.Entry entry = (Entry) iter.next(); - if( setProperty(target, (String) entry.getKey(), entry.getValue()) ) { + Map.Entry entry = (Entry)iter.next(); + if (setProperty(target, (String)entry.getKey(), entry.getValue())) { iter.remove(); - rc=true; + rc = true; } } - + return rc; } @@ -145,15 +141,16 @@ public class IntrospectionSupport { try { Class clazz = target.getClass(); Method setter = findSetterMethod(clazz, name); - if( setter == null ) + if (setter == null) return false; - - // If the type is null or it matches the needed type, just use the value directly - if( value == null || value.getClass()==setter.getParameterTypes()[0] ) { - setter.invoke(target, new Object[]{value}); + + // If the type is null or it matches the needed type, just use the + // value directly + if (value == null || value.getClass() == setter.getParameterTypes()[0]) { + setter.invoke(target, new Object[] {value}); } else { // We need to convert it - setter.invoke(target, new Object[]{ convert(value, setter.getParameterTypes()[0]) }); + setter.invoke(target, new Object[] {convert(value, setter.getParameterTypes()[0])}); } return true; } catch (Throwable ignore) { @@ -163,11 +160,11 @@ public class IntrospectionSupport { private static Object convert(Object value, Class type) throws URISyntaxException { PropertyEditor editor = PropertyEditorManager.findEditor(type); - if( editor != null ) { + if (editor != null) { editor.setAsText(value.toString()); return editor.getValue(); } - if( type == URI.class ) { + if (type == URI.class) { return new URI(value.toString()); } return null; @@ -175,11 +172,11 @@ public class IntrospectionSupport { private static String convertToString(Object value, Class type) throws URISyntaxException { PropertyEditor editor = PropertyEditorManager.findEditor(type); - if( editor != null ) { + if (editor != null) { editor.setValue(value); return editor.getAsText(); } - if( type == URI.class ) { + if (type == URI.class) { return ((URI)value).toString(); } return null; @@ -187,14 +184,12 @@ public class IntrospectionSupport { private static Method findSetterMethod(Class clazz, String name) { // Build the method name. - name = "set"+name.substring(0,1).toUpperCase()+name.substring(1); + name = "set" + name.substring(0, 1).toUpperCase() + name.substring(1); Method[] methods = clazz.getMethods(); for (int i = 0; i < methods.length; i++) { Method method = methods[i]; Class params[] = method.getParameterTypes(); - if( method.getName().equals(name) - && params.length==1 - && isSettableType(params[0])) { + if (method.getName().equals(name) && params.length == 1 && isSettableType(params[0])) { return method; } } @@ -202,11 +197,11 @@ public class IntrospectionSupport { } private static boolean isSettableType(Class clazz) { - if( PropertyEditorManager.findEditor(clazz)!=null ) + if (PropertyEditorManager.findEditor(clazz) != null) return true; - if( clazz == URI.class ) + if (clazz == URI.class) return true; - if( clazz == Boolean.class ) + if (clazz == Boolean.class) return true; return false; } @@ -223,11 +218,10 @@ public class IntrospectionSupport { Set entrySet = map.entrySet(); boolean first = true; for (Iterator iter = entrySet.iterator(); iter.hasNext();) { - Map.Entry entry = (Map.Entry) iter.next(); + Map.Entry entry = (Map.Entry)iter.next(); if (first) { first = false; - } - else { + } else { buffer.append(", "); } buffer.append(entry.getKey()); @@ -240,10 +234,9 @@ public class IntrospectionSupport { protected static void appendToString(StringBuffer buffer, Object value) { if (value instanceof ActiveMQDestination) { - ActiveMQDestination destination = (ActiveMQDestination) value; + ActiveMQDestination destination = (ActiveMQDestination)value; buffer.append(destination.getQualifiedName()); - } - else { + } else { buffer.append(value); } } @@ -251,33 +244,30 @@ public class IntrospectionSupport { static public String simpleName(Class clazz) { String name = clazz.getName(); int p = name.lastIndexOf("."); - if( p >= 0 ) { - name = name.substring(p+1); + if (p >= 0) { + name = name.substring(p + 1); } return name; } - static private void addFields(Object target, Class startClass, Class stopClass, LinkedHashMap map) { - - if( startClass!=stopClass ) - addFields( target, startClass.getSuperclass(), stopClass, map ); - + + if (startClass != stopClass) + addFields(target, startClass.getSuperclass(), stopClass, map); + Field[] fields = startClass.getDeclaredFields(); for (int i = 0; i < fields.length; i++) { Field field = fields[i]; - if( Modifier.isStatic(field.getModifiers()) || - Modifier.isTransient(field.getModifiers()) || - Modifier.isPrivate(field.getModifiers()) ) { + if (Modifier.isStatic(field.getModifiers()) || Modifier.isTransient(field.getModifiers()) || Modifier.isPrivate(field.getModifiers())) { continue; } - + try { field.setAccessible(true); Object o = field.get(target); - if( o!=null && o.getClass().isArray() ) { + if (o != null && o.getClass().isArray()) { try { - o = Arrays.asList((Object[]) o); + o = Arrays.asList((Object[])o); } catch (Throwable e) { } } @@ -286,8 +276,7 @@ public class IntrospectionSupport { e.printStackTrace(); } } - + } - } diff --git a/activemq-core/src/main/java/org/apache/activemq/util/JMSExceptionSupport.java b/activemq-core/src/main/java/org/apache/activemq/util/JMSExceptionSupport.java index cc10dca732..f13aea2c14 100755 --- a/activemq-core/src/main/java/org/apache/activemq/util/JMSExceptionSupport.java +++ b/activemq-core/src/main/java/org/apache/activemq/util/JMSExceptionSupport.java @@ -34,13 +34,13 @@ final public class JMSExceptionSupport { exception.initCause(cause); return exception; } - + public static JMSException create(Throwable cause) { if (cause instanceof JMSException) { - return (JMSException) cause; + return (JMSException)cause; } String msg = cause.getMessage(); - if( msg==null || msg.length()==0 ) + if (msg == null || msg.length() == 0) msg = cause.toString(); JMSException exception = new JMSException(msg); exception.initCause(cause); @@ -49,10 +49,10 @@ final public class JMSExceptionSupport { public static JMSException create(Exception cause) { if (cause instanceof JMSException) { - return (JMSException) cause; + return (JMSException)cause; } String msg = cause.getMessage(); - if( msg==null || msg.length()==0 ) + if (msg == null || msg.length() == 0) msg = cause.toString(); JMSException exception = new JMSException(msg); exception.setLinkedException(cause); @@ -62,17 +62,17 @@ final public class JMSExceptionSupport { public static MessageEOFException createMessageEOFException(Exception cause) { String msg = cause.getMessage(); - if( msg==null || msg.length()==0 ) + if (msg == null || msg.length() == 0) msg = cause.toString(); MessageEOFException exception = new MessageEOFException(msg); exception.setLinkedException(cause); exception.initCause(cause); return exception; } - + public static MessageFormatException createMessageFormatException(Exception cause) { String msg = cause.getMessage(); - if( msg==null || msg.length()==0 ) + if (msg == null || msg.length() == 0) msg = cause.toString(); MessageFormatException exception = new MessageFormatException(msg); exception.setLinkedException(cause); diff --git a/activemq-core/src/main/java/org/apache/activemq/util/LRUCache.java b/activemq-core/src/main/java/org/apache/activemq/util/LRUCache.java index 2ba1138cd9..be906fda94 100755 --- a/activemq-core/src/main/java/org/apache/activemq/util/LRUCache.java +++ b/activemq-core/src/main/java/org/apache/activemq/util/LRUCache.java @@ -18,71 +18,68 @@ package org.apache.activemq.util; import java.util.LinkedHashMap; import java.util.Map; + /** * A Simple LRU Cache * * @version $Revision$ - * @param - * @param + * @param + * @param */ public class LRUCache extends LinkedHashMap { - private static final long serialVersionUID=-342098639681884413L; - protected int maxCacheSize=10000; + private static final long serialVersionUID = -342098639681884413L; + protected int maxCacheSize = 10000; - /** - * Default constructorfor an LRU Cache - * The default capacity is 10000 - * + * Default constructorfor an LRU Cache The default capacity is 10000 */ - public LRUCache(){ - super(1000,0.75f,true); + public LRUCache() { + super(1000, 0.75f, true); } - + /** * Constructs a LRUCache with a maximum capacity + * * @param maximumCacheSize */ public LRUCache(int maximumCacheSize) { - this(maximumCacheSize,maximumCacheSize,0.75f,true); - } - /** - * Constructs an empty LRUCache instance with the - * specified initial capacity, maximumCacheSize,load factor and ordering mode. - * - * @param initialCapacity the initial capacity. - * @param maximumCacheSize - * @param loadFactor the load factor. - * @param accessOrder the ordering mode - true for - * access-order, false for insertion-order. - * @throws IllegalArgumentException if the initial capacity is negative - * or the load factor is nonpositive. - */ - - public LRUCache(int initialCapacity,int maximumCacheSize,float loadFactor, boolean accessOrder) { - super(initialCapacity,loadFactor,accessOrder); - this.maxCacheSize = maximumCacheSize; + this(maximumCacheSize, maximumCacheSize, 0.75f, true); } - + /** + * Constructs an empty LRUCache instance with the specified + * initial capacity, maximumCacheSize,load factor and ordering mode. + * + * @param initialCapacity the initial capacity. + * @param maximumCacheSize + * @param loadFactor the load factor. + * @param accessOrder the ordering mode - true for access-order, + * false for insertion-order. + * @throws IllegalArgumentException if the initial capacity is negative or + * the load factor is nonpositive. + */ + + public LRUCache(int initialCapacity, int maximumCacheSize, float loadFactor, boolean accessOrder) { + super(initialCapacity, loadFactor, accessOrder); + this.maxCacheSize = maximumCacheSize; + } /** * @return Returns the maxCacheSize. */ - public int getMaxCacheSize(){ + public int getMaxCacheSize() { return maxCacheSize; } /** - * @param maxCacheSize - * The maxCacheSize to set. + * @param maxCacheSize The maxCacheSize to set. */ - public void setMaxCacheSize(int maxCacheSize){ - this.maxCacheSize=maxCacheSize; + public void setMaxCacheSize(int maxCacheSize) { + this.maxCacheSize = maxCacheSize; } - - protected boolean removeEldestEntry(Map.Entry entry){ + + protected boolean removeEldestEntry(Map.Entry entry) { return size() > maxCacheSize; } } diff --git a/activemq-core/src/main/java/org/apache/activemq/util/LinkedNode.java b/activemq-core/src/main/java/org/apache/activemq/util/LinkedNode.java index a6fb1a2946..4d9a6a50a2 100644 --- a/activemq-core/src/main/java/org/apache/activemq/util/LinkedNode.java +++ b/activemq-core/src/main/java/org/apache/activemq/util/LinkedNode.java @@ -17,140 +17,137 @@ package org.apache.activemq.util; /** - * Provides a base class for you to extend when you want object to maintain - * a doubly linked list to other objects without using a collection class. + * Provides a base class for you to extend when you want object to maintain a + * doubly linked list to other objects without using a collection class. * * @author chirino */ public class LinkedNode { - - protected LinkedNode next=this; - protected LinkedNode prev=this; - protected boolean tail=true; - - public LinkedNode getHeadNode() { - if( isHeadNode() ) { - return this; - } - if( isTailNode() ) { - return next; - } - LinkedNode rc = prev; - while(!rc.isHeadNode()) { - rc = rc.prev; - } - return rc; - } - - public LinkedNode getTailNode() { - if( isTailNode() ) { - return this; - } - if( isHeadNode() ) { - return prev; - } - LinkedNode rc = next; - while(!rc.isTailNode()) { - rc = rc.next; - } - return rc; - } + protected LinkedNode next = this; + protected LinkedNode prev = this; + protected boolean tail = true; - public LinkedNode getNext() { - return tail ? null : next; - } + public LinkedNode getHeadNode() { + if (isHeadNode()) { + return this; + } + if (isTailNode()) { + return next; + } + LinkedNode rc = prev; + while (!rc.isHeadNode()) { + rc = rc.prev; + } + return rc; + } - public LinkedNode getPrevious() { - return prev.tail ? null : prev; - } + public LinkedNode getTailNode() { + if (isTailNode()) { + return this; + } + if (isHeadNode()) { + return prev; + } + LinkedNode rc = next; + while (!rc.isTailNode()) { + rc = rc.next; + } + return rc; + } - public boolean isHeadNode() { - return prev.isTailNode(); - } - - public boolean isTailNode() { - return tail; - } + public LinkedNode getNext() { + return tail ? null : next; + } - /** - * @param rightHead the node to link after this node. - * @return this - */ - public LinkedNode linkAfter(LinkedNode rightHead) { - - if( rightHead == this ) { - throw new IllegalArgumentException("You cannot link to yourself"); - } - if( !rightHead.isHeadNode() ) { - throw new IllegalArgumentException("You only insert nodes that are the first in a list"); - } + public LinkedNode getPrevious() { + return prev.tail ? null : prev; + } - LinkedNode rightTail = rightHead.prev; + public boolean isHeadNode() { + return prev.isTailNode(); + } - if( tail ) { - tail = false; - } else { - rightTail.tail=false; - } - - rightHead.prev = this; // link the head of the right side. - rightTail.next = next; // link the tail of the right side - next.prev = rightTail; // link the head of the left side - next = rightHead; // link the tail of the left side. - - return this; - } + public boolean isTailNode() { + return tail; + } - - /** - * @param leftHead the node to link after this node. - * @return - * @return this - */ - public LinkedNode linkBefore(LinkedNode leftHead) { - - - if( leftHead == this ) { - throw new IllegalArgumentException("You cannot link to yourself"); - } - if( !leftHead.isHeadNode() ) { - throw new IllegalArgumentException("You only insert nodes that are the first in a list"); - } + /** + * @param rightHead the node to link after this node. + * @return this + */ + public LinkedNode linkAfter(LinkedNode rightHead) { - // The left side is no longer going to be a tail.. - LinkedNode leftTail = leftHead.prev; - leftTail.tail = false; - - leftTail.next = this; // link the tail of the left side. - leftHead.prev = prev; // link the head of the left side. - prev.next = leftHead; // link the tail of the right side. - prev = leftTail; // link the head of the right side. - - return leftHead; - } + if (rightHead == this) { + throw new IllegalArgumentException("You cannot link to yourself"); + } + if (!rightHead.isHeadNode()) { + throw new IllegalArgumentException("You only insert nodes that are the first in a list"); + } + + LinkedNode rightTail = rightHead.prev; + + if (tail) { + tail = false; + } else { + rightTail.tail = false; + } + + rightHead.prev = this; // link the head of the right side. + rightTail.next = next; // link the tail of the right side + next.prev = rightTail; // link the head of the left side + next = rightHead; // link the tail of the left side. + + return this; + } + + /** + * @param leftHead the node to link after this node. + * @return + * @return this + */ + public LinkedNode linkBefore(LinkedNode leftHead) { + + if (leftHead == this) { + throw new IllegalArgumentException("You cannot link to yourself"); + } + if (!leftHead.isHeadNode()) { + throw new IllegalArgumentException("You only insert nodes that are the first in a list"); + } + + // The left side is no longer going to be a tail.. + LinkedNode leftTail = leftHead.prev; + leftTail.tail = false; + + leftTail.next = this; // link the tail of the left side. + leftHead.prev = prev; // link the head of the left side. + prev.next = leftHead; // link the tail of the right side. + prev = leftTail; // link the head of the right side. + + return leftHead; + } + + /** + * Removes this node out of the linked list it is chained in. + */ + public void unlink() { + // If we are allready unlinked... + if (prev == this) { + return; + } + + if (tail) { + prev.tail = true; + } + + // Update the peers links.. + next.prev = prev; + prev.next = next; + + // Update our links.. + next = this; + prev = this; + tail = true; + } - /** - * Removes this node out of the linked list it is chained in. - */ - public void unlink() { - // If we are allready unlinked... - if( prev==this ) { - return; - } - - if( tail ) { - prev.tail = true; - } - - // Update the peers links.. - next.prev = prev; - prev.next = next; - - // Update our links.. - next = this; - prev = this; - tail=true; - } - } diff --git a/activemq-core/src/main/java/org/apache/activemq/util/MarshallingSupport.java b/activemq-core/src/main/java/org/apache/activemq/util/MarshallingSupport.java index e27ee7102f..aff4686f8c 100755 --- a/activemq-core/src/main/java/org/apache/activemq/util/MarshallingSupport.java +++ b/activemq-core/src/main/java/org/apache/activemq/util/MarshallingSupport.java @@ -32,37 +32,35 @@ import java.util.Map; import java.util.Properties; /** - * - * - * The fixed version of the UTF8 encoding function. Some older JVM's UTF8 encoding function - * breaks when handling large strings. + * The fixed version of the UTF8 encoding function. Some older JVM's UTF8 + * encoding function breaks when handling large strings. * * @version $Revision$ */ public class MarshallingSupport { - - public static final byte NULL = 0; - public static final byte BOOLEAN_TYPE = 1; - public static final byte BYTE_TYPE = 2; - public static final byte CHAR_TYPE = 3; - public static final byte SHORT_TYPE = 4; - public static final byte INTEGER_TYPE = 5; - public static final byte LONG_TYPE = 6; - public static final byte DOUBLE_TYPE = 7; - public static final byte FLOAT_TYPE = 8; - public static final byte STRING_TYPE = 9; - public static final byte BYTE_ARRAY_TYPE = 10; - public static final byte MAP_TYPE = 11; - public static final byte LIST_TYPE = 12; - public static final byte BIG_STRING_TYPE = 13; - static public void marshalPrimitiveMap(Map map, DataOutputStream out) throws IOException { - if( map == null ) { + public static final byte NULL = 0; + public static final byte BOOLEAN_TYPE = 1; + public static final byte BYTE_TYPE = 2; + public static final byte CHAR_TYPE = 3; + public static final byte SHORT_TYPE = 4; + public static final byte INTEGER_TYPE = 5; + public static final byte LONG_TYPE = 6; + public static final byte DOUBLE_TYPE = 7; + public static final byte FLOAT_TYPE = 8; + public static final byte STRING_TYPE = 9; + public static final byte BYTE_ARRAY_TYPE = 10; + public static final byte MAP_TYPE = 11; + public static final byte LIST_TYPE = 12; + public static final byte BIG_STRING_TYPE = 13; + + static public void marshalPrimitiveMap(Map map, DataOutputStream out) throws IOException { + if (map == null) { out.writeInt(-1); } else { out.writeInt(map.size()); for (Iterator iter = map.keySet().iterator(); iter.hasNext();) { - String name = (String) iter.next(); + String name = (String)iter.next(); out.writeUTF(name); Object value = map.get(name); marshalPrimitive(out, value); @@ -71,37 +69,37 @@ public class MarshallingSupport { } static public Map unmarshalPrimitiveMap(DataInputStream in) throws IOException { - return unmarshalPrimitiveMap(in, Integer.MAX_VALUE); - } + return unmarshalPrimitiveMap(in, Integer.MAX_VALUE); + } /** * @param in * @return - * @throws IOException + * @throws IOException * @throws IOException */ - public static Map unmarshalPrimitiveMap(DataInputStream in, int max_property_size) throws IOException { + public static Map unmarshalPrimitiveMap(DataInputStream in, int max_property_size) throws IOException { int size = in.readInt(); - if( size > max_property_size ) { - throw new IOException("Primitive map is larger than the allowed size: "+size); + if (size > max_property_size) { + throw new IOException("Primitive map is larger than the allowed size: " + size); } - if( size < 0 ) { + if (size < 0) { return null; } else { HashMap rc = new HashMap(size); - for(int i=0; i < size; i++) { + for (int i = 0; i < size; i++) { String name = in.readUTF(); rc.put(name, unmarshalPrimitive(in)); } return rc; } - + } public static void marshalPrimitiveList(List list, DataOutputStream out) throws IOException { out.writeInt(list.size()); for (Iterator iter = list.iterator(); iter.hasNext();) { - Object element = (Object) iter.next(); + Object element = (Object)iter.next(); marshalPrimitive(out, element); } } @@ -116,43 +114,42 @@ public class MarshallingSupport { } static public void marshalPrimitive(DataOutputStream out, Object value) throws IOException { - if( value == null ) { + if (value == null) { marshalNull(out); - } else if( value.getClass() == Boolean.class ) { + } else if (value.getClass() == Boolean.class) { marshalBoolean(out, ((Boolean)value).booleanValue()); - } else if( value.getClass() == Byte.class ) { + } else if (value.getClass() == Byte.class) { marshalByte(out, ((Byte)value).byteValue()); - } else if( value.getClass() == Character.class ) { + } else if (value.getClass() == Character.class) { marshalChar(out, ((Character)value).charValue()); - } else if( value.getClass() == Short.class ) { + } else if (value.getClass() == Short.class) { marshalShort(out, ((Short)value).shortValue()); - } else if( value.getClass() == Integer.class ) { + } else if (value.getClass() == Integer.class) { marshalInt(out, ((Integer)value).intValue()); - } else if( value.getClass() == Long.class ) { + } else if (value.getClass() == Long.class) { marshalLong(out, ((Long)value).longValue()); - } else if( value.getClass() == Float.class ) { + } else if (value.getClass() == Float.class) { marshalFloat(out, ((Float)value).floatValue()); - } else if( value.getClass() == Double.class ) { + } else if (value.getClass() == Double.class) { marshalDouble(out, ((Double)value).doubleValue()); - } else if( value.getClass() == byte[].class ) { + } else if (value.getClass() == byte[].class) { marshalByteArray(out, ((byte[])value)); - } else if( value.getClass() == String.class ) { + } else if (value.getClass() == String.class) { marshalString(out, (String)value); - } else if( value instanceof Map) { + } else if (value instanceof Map) { out.writeByte(MAP_TYPE); - marshalPrimitiveMap((Map) value, out); - } else if( value instanceof List) { + marshalPrimitiveMap((Map)value, out); + } else if (value instanceof List) { out.writeByte(LIST_TYPE); - marshalPrimitiveList((List) value, out); + marshalPrimitiveList((List)value, out); } else { - throw new IOException("Object is not a primitive: "+value); + throw new IOException("Object is not a primitive: " + value); } } - static public Object unmarshalPrimitive(DataInputStream in) throws IOException { - Object value=null; - switch( in.readByte() ) { + Object value = null; + switch (in.readByte()) { case BYTE_TYPE: value = Byte.valueOf(in.readByte()); break; @@ -251,10 +248,9 @@ public class MarshallingSupport { out.write(value, offset, length); } - public static void marshalString(DataOutputStream out, String s) throws IOException { // If it's too big, out.writeUTF may not able able to write it out. - if( s.length() < Short.MAX_VALUE/4 ) { + if (s.length() < Short.MAX_VALUE / 4) { out.writeByte(STRING_TYPE); out.writeUTF(s); } else { @@ -282,23 +278,25 @@ public class MarshallingSupport { utflen += 2; } } - //TODO diff: Sun code - removed - byte[] bytearr = new byte[utflen + 4]; //TODO diff: Sun code - bytearr[count++] = (byte) ((utflen >>> 24) & 0xFF); //TODO diff: Sun code - bytearr[count++] = (byte) ((utflen >>> 16) & 0xFF); //TODO diff: Sun code - bytearr[count++] = (byte) ((utflen >>> 8) & 0xFF); - bytearr[count++] = (byte) ((utflen >>> 0) & 0xFF); + // TODO diff: Sun code - removed + byte[] bytearr = new byte[utflen + 4]; // TODO diff: Sun code + bytearr[count++] = (byte)((utflen >>> 24) & 0xFF); // TODO diff: + // Sun code + bytearr[count++] = (byte)((utflen >>> 16) & 0xFF); // TODO diff: + // Sun code + bytearr[count++] = (byte)((utflen >>> 8) & 0xFF); + bytearr[count++] = (byte)((utflen >>> 0) & 0xFF); for (int i = 0; i < strlen; i++) { c = charr[i]; if ((c >= 0x0001) && (c <= 0x007F)) { - bytearr[count++] = (byte) c; + bytearr[count++] = (byte)c; } else if (c > 0x07FF) { - bytearr[count++] = (byte) (0xE0 | ((c >> 12) & 0x0F)); - bytearr[count++] = (byte) (0x80 | ((c >> 6) & 0x3F)); - bytearr[count++] = (byte) (0x80 | ((c >> 0) & 0x3F)); + bytearr[count++] = (byte)(0xE0 | ((c >> 12) & 0x0F)); + bytearr[count++] = (byte)(0x80 | ((c >> 6) & 0x3F)); + bytearr[count++] = (byte)(0x80 | ((c >> 0) & 0x3F)); } else { - bytearr[count++] = (byte) (0xC0 | ((c >> 6) & 0x1F)); - bytearr[count++] = (byte) (0x80 | ((c >> 0) & 0x3F)); + bytearr[count++] = (byte)(0xC0 | ((c >> 6) & 0x1F)); + bytearr[count++] = (byte)(0x80 | ((c >> 0) & 0x3F)); } } dataOut.write(bytearr); @@ -309,7 +307,7 @@ public class MarshallingSupport { } static public String readUTF8(DataInput dataIn) throws IOException { - int utflen = dataIn.readInt(); //TODO diff: Sun code + int utflen = dataIn.readInt(); // TODO diff: Sun code if (utflen > -1) { StringBuffer str = new StringBuffer(utflen); byte bytearr[] = new byte[utflen]; @@ -321,47 +319,47 @@ public class MarshallingSupport { while (count < utflen) { c = bytearr[count] & 0xff; switch (c >> 4) { - case 0: - case 1: - case 2: - case 3: - case 4: - case 5: - case 6: - case 7: - /* 0xxxxxxx */ - count++; - str.append((char) c); - break; - case 12: - case 13: - /* 110x xxxx 10xx xxxx */ - count += 2; - if (count > utflen) { - throw new UTFDataFormatException(); - } - char2 = bytearr[count - 1]; - if ((char2 & 0xC0) != 0x80) { - throw new UTFDataFormatException(); - } - str.append((char) (((c & 0x1F) << 6) | (char2 & 0x3F))); - break; - case 14: - /* 1110 xxxx 10xx xxxx 10xx xxxx */ - count += 3; - if (count > utflen) { - throw new UTFDataFormatException(); - } - char2 = bytearr[count - 2]; //TODO diff: Sun code - char3 = bytearr[count - 1]; //TODO diff: Sun code - if (((char2 & 0xC0) != 0x80) || ((char3 & 0xC0) != 0x80)) { - throw new UTFDataFormatException(); - } - str.append((char) (((c & 0x0F) << 12) | ((char2 & 0x3F) << 6) | ((char3 & 0x3F) << 0))); - break; - default : - /* 10xx xxxx, 1111 xxxx */ + case 0: + case 1: + case 2: + case 3: + case 4: + case 5: + case 6: + case 7: + /* 0xxxxxxx */ + count++; + str.append((char)c); + break; + case 12: + case 13: + /* 110x xxxx 10xx xxxx */ + count += 2; + if (count > utflen) { throw new UTFDataFormatException(); + } + char2 = bytearr[count - 1]; + if ((char2 & 0xC0) != 0x80) { + throw new UTFDataFormatException(); + } + str.append((char)(((c & 0x1F) << 6) | (char2 & 0x3F))); + break; + case 14: + /* 1110 xxxx 10xx xxxx 10xx xxxx */ + count += 3; + if (count > utflen) { + throw new UTFDataFormatException(); + } + char2 = bytearr[count - 2]; // TODO diff: Sun code + char3 = bytearr[count - 1]; // TODO diff: Sun code + if (((char2 & 0xC0) != 0x80) || ((char3 & 0xC0) != 0x80)) { + throw new UTFDataFormatException(); + } + str.append((char)(((c & 0x0F) << 12) | ((char2 & 0x3F) << 6) | ((char3 & 0x3F) << 0))); + break; + default: + /* 10xx xxxx, 1111 xxxx */ + throw new UTFDataFormatException(); } } // The number of chars produced may be less than utflen @@ -370,21 +368,21 @@ public class MarshallingSupport { return null; } } - - public static String propertiesToString(Properties props) throws IOException{ - String result=""; - if(props!=null){ - DataByteArrayOutputStream dataOut=new DataByteArrayOutputStream(); - props.store(dataOut,""); - result=new String(dataOut.getData(),0,dataOut.size()); + + public static String propertiesToString(Properties props) throws IOException { + String result = ""; + if (props != null) { + DataByteArrayOutputStream dataOut = new DataByteArrayOutputStream(); + props.store(dataOut, ""); + result = new String(dataOut.getData(), 0, dataOut.size()); dataOut.close(); } return result; } - + public static Properties stringToProperties(String str) throws IOException { Properties result = new Properties(); - if (str != null && str.length() > 0 ) { + if (str != null && str.length() > 0) { DataByteArrayInputStream dataIn = new DataByteArrayInputStream(str.getBytes()); result.load(dataIn); dataIn.close(); @@ -392,5 +390,4 @@ public class MarshallingSupport { return result; } - } diff --git a/activemq-core/src/main/java/org/apache/activemq/util/MemoryIntPropertyEditor.java b/activemq-core/src/main/java/org/apache/activemq/util/MemoryIntPropertyEditor.java index debc936d68..c10006e9c0 100644 --- a/activemq-core/src/main/java/org/apache/activemq/util/MemoryIntPropertyEditor.java +++ b/activemq-core/src/main/java/org/apache/activemq/util/MemoryIntPropertyEditor.java @@ -20,49 +20,47 @@ import java.beans.PropertyEditorSupport; import java.util.regex.Matcher; import java.util.regex.Pattern; -/** - * Converts string values like "20 Mb", "1024kb", and "1g" - * to int values in bytes. - * +/** + * Converts string values like "20 Mb", "1024kb", and "1g" to int values in + * bytes. */ public class MemoryIntPropertyEditor extends PropertyEditorSupport { - public void setAsText(String text) throws IllegalArgumentException { + public void setAsText(String text) throws IllegalArgumentException { - Pattern p = Pattern.compile("^\\s*(\\d+)\\s*(b)?\\s*$",Pattern.CASE_INSENSITIVE); - Matcher m = p.matcher(text); - if (m.matches()) { - setValue(Integer.valueOf(Integer.parseInt(m.group(1)))); - return; - } + Pattern p = Pattern.compile("^\\s*(\\d+)\\s*(b)?\\s*$", Pattern.CASE_INSENSITIVE); + Matcher m = p.matcher(text); + if (m.matches()) { + setValue(Integer.valueOf(Integer.parseInt(m.group(1)))); + return; + } - p = Pattern.compile("^\\s*(\\d+)\\s*k(b)?\\s*$",Pattern.CASE_INSENSITIVE); - m = p.matcher(text); - if (m.matches()) { - setValue(Integer.valueOf(Integer.parseInt(m.group(1)) * 1024)); - return; - } + p = Pattern.compile("^\\s*(\\d+)\\s*k(b)?\\s*$", Pattern.CASE_INSENSITIVE); + m = p.matcher(text); + if (m.matches()) { + setValue(Integer.valueOf(Integer.parseInt(m.group(1)) * 1024)); + return; + } - p = Pattern.compile("^\\s*(\\d+)\\s*m(b)?\\s*$", Pattern.CASE_INSENSITIVE); - m = p.matcher(text); - if (m.matches()) { - setValue(Integer.valueOf(Integer.parseInt(m.group(1)) * 1024 * 1024 )); - return; - } + p = Pattern.compile("^\\s*(\\d+)\\s*m(b)?\\s*$", Pattern.CASE_INSENSITIVE); + m = p.matcher(text); + if (m.matches()) { + setValue(Integer.valueOf(Integer.parseInt(m.group(1)) * 1024 * 1024)); + return; + } - p = Pattern.compile("^\\s*(\\d+)\\s*g(b)?\\s*$", Pattern.CASE_INSENSITIVE); - m = p.matcher(text); - if (m.matches()) { - setValue(Integer.valueOf(Integer.parseInt(m.group(1)) * 1024 * 1024 * 1024 )); - return; - } + p = Pattern.compile("^\\s*(\\d+)\\s*g(b)?\\s*$", Pattern.CASE_INSENSITIVE); + m = p.matcher(text); + if (m.matches()) { + setValue(Integer.valueOf(Integer.parseInt(m.group(1)) * 1024 * 1024 * 1024)); + return; + } - throw new IllegalArgumentException( - "Could convert not to a memory size: " + text); - } + throw new IllegalArgumentException("Could convert not to a memory size: " + text); + } - public String getAsText() { - Integer value = (Integer) getValue(); - return (value != null ? value.toString() : ""); - } + public String getAsText() { + Integer value = (Integer)getValue(); + return (value != null ? value.toString() : ""); + } } diff --git a/activemq-core/src/main/java/org/apache/activemq/util/MemoryPropertyEditor.java b/activemq-core/src/main/java/org/apache/activemq/util/MemoryPropertyEditor.java index 1217e34241..3134a3aaee 100644 --- a/activemq-core/src/main/java/org/apache/activemq/util/MemoryPropertyEditor.java +++ b/activemq-core/src/main/java/org/apache/activemq/util/MemoryPropertyEditor.java @@ -20,49 +20,47 @@ import java.beans.PropertyEditorSupport; import java.util.regex.Matcher; import java.util.regex.Pattern; -/** - * Converts string values like "20 Mb", "1024kb", and "1g" - * to long values in bytes. - * +/** + * Converts string values like "20 Mb", "1024kb", and "1g" to long values in + * bytes. */ public class MemoryPropertyEditor extends PropertyEditorSupport { - public void setAsText(String text) throws IllegalArgumentException { + public void setAsText(String text) throws IllegalArgumentException { - Pattern p = Pattern.compile("^\\s*(\\d+)\\s*(b)?\\s*$",Pattern.CASE_INSENSITIVE); - Matcher m = p.matcher(text); - if (m.matches()) { - setValue(Long.valueOf(Long.parseLong(m.group(1)))); - return; - } + Pattern p = Pattern.compile("^\\s*(\\d+)\\s*(b)?\\s*$", Pattern.CASE_INSENSITIVE); + Matcher m = p.matcher(text); + if (m.matches()) { + setValue(Long.valueOf(Long.parseLong(m.group(1)))); + return; + } - p = Pattern.compile("^\\s*(\\d+)\\s*k(b)?\\s*$",Pattern.CASE_INSENSITIVE); - m = p.matcher(text); - if (m.matches()) { - setValue(Long.valueOf(Long.parseLong(m.group(1)) * 1024)); - return; - } + p = Pattern.compile("^\\s*(\\d+)\\s*k(b)?\\s*$", Pattern.CASE_INSENSITIVE); + m = p.matcher(text); + if (m.matches()) { + setValue(Long.valueOf(Long.parseLong(m.group(1)) * 1024)); + return; + } - p = Pattern.compile("^\\s*(\\d+)\\s*m(b)?\\s*$", Pattern.CASE_INSENSITIVE); - m = p.matcher(text); - if (m.matches()) { - setValue(Long.valueOf(Long.parseLong(m.group(1)) * 1024 * 1024 )); - return; - } + p = Pattern.compile("^\\s*(\\d+)\\s*m(b)?\\s*$", Pattern.CASE_INSENSITIVE); + m = p.matcher(text); + if (m.matches()) { + setValue(Long.valueOf(Long.parseLong(m.group(1)) * 1024 * 1024)); + return; + } - p = Pattern.compile("^\\s*(\\d+)\\s*g(b)?\\s*$", Pattern.CASE_INSENSITIVE); - m = p.matcher(text); - if (m.matches()) { - setValue(Long.valueOf(Long.parseLong(m.group(1)) * 1024 * 1024 * 1024 )); - return; - } + p = Pattern.compile("^\\s*(\\d+)\\s*g(b)?\\s*$", Pattern.CASE_INSENSITIVE); + m = p.matcher(text); + if (m.matches()) { + setValue(Long.valueOf(Long.parseLong(m.group(1)) * 1024 * 1024 * 1024)); + return; + } - throw new IllegalArgumentException( - "Could convert not to a memory size: " + text); - } + throw new IllegalArgumentException("Could convert not to a memory size: " + text); + } - public String getAsText() { - Long value = (Long) getValue(); - return (value != null ? value.toString() : ""); - } + public String getAsText() { + Long value = (Long)getValue(); + return (value != null ? value.toString() : ""); + } } diff --git a/activemq-core/src/main/java/org/apache/activemq/util/ServiceStopper.java b/activemq-core/src/main/java/org/apache/activemq/util/ServiceStopper.java index f2facb1cc0..fe54b615bc 100644 --- a/activemq-core/src/main/java/org/apache/activemq/util/ServiceStopper.java +++ b/activemq-core/src/main/java/org/apache/activemq/util/ServiceStopper.java @@ -37,11 +37,10 @@ public class ServiceStopper { */ public void stop(Service service) { try { - if( service!=null ) { + if (service != null) { service.stop(); } - } - catch (Exception e) { + } catch (Exception e) { onException(service, e); } } @@ -53,8 +52,7 @@ public class ServiceStopper { public void run(Callback stopClosure) { try { stopClosure.execute(); - } - catch (Throwable e) { + } catch (Throwable e) { onException(stopClosure, e); } } @@ -64,7 +62,7 @@ public class ServiceStopper { */ public void stopServices(List services) { for (Iterator iter = services.iterator(); iter.hasNext();) { - Service service = (Service) iter.next(); + Service service = (Service)iter.next(); stop(service); } } @@ -82,14 +80,12 @@ public class ServiceStopper { public void throwFirstException() throws Exception { if (firstException != null) { if (firstException instanceof Exception) { - Exception e = (Exception) firstException; + Exception e = (Exception)firstException; throw e; - } - else if (firstException instanceof RuntimeException) { - RuntimeException e = (RuntimeException) firstException; + } else if (firstException instanceof RuntimeException) { + RuntimeException e = (RuntimeException)firstException; throw e; - } - else { + } else { throw new RuntimeException("Unknown type of exception: " + firstException, firstException); } } diff --git a/activemq-core/src/main/java/org/apache/activemq/util/SubscriptionKey.java b/activemq-core/src/main/java/org/apache/activemq/util/SubscriptionKey.java index 53171ff751..0a87dfa87e 100755 --- a/activemq-core/src/main/java/org/apache/activemq/util/SubscriptionKey.java +++ b/activemq-core/src/main/java/org/apache/activemq/util/SubscriptionKey.java @@ -19,38 +19,36 @@ package org.apache.activemq.util; import org.apache.activemq.command.SubscriptionInfo; public class SubscriptionKey { - + public final String clientId; public final String subscriptionName; private final int hashValue; - public SubscriptionKey(SubscriptionInfo info) { this(info.getClientId(), info.getSubscriptionName()); } public SubscriptionKey(String clientId, String subscriptionName) { this.clientId = clientId; - this.subscriptionName = subscriptionName != null? subscriptionName : "NOT_SET"; - hashValue = clientId.hashCode()^this.subscriptionName.hashCode(); + this.subscriptionName = subscriptionName != null ? subscriptionName : "NOT_SET"; + hashValue = clientId.hashCode() ^ this.subscriptionName.hashCode(); } - public int hashCode() { return hashValue; } - + public boolean equals(Object o) { try { - SubscriptionKey key = (SubscriptionKey) o; + SubscriptionKey key = (SubscriptionKey)o; return key.clientId.equals(clientId) && key.subscriptionName.equals(subscriptionName); } catch (Throwable e) { return false; } } - + public String toString() { - return clientId+":"+subscriptionName; + return clientId + ":" + subscriptionName; } public String getClientId() { diff --git a/activemq-core/src/main/java/org/apache/activemq/util/TransactionTemplate.java b/activemq-core/src/main/java/org/apache/activemq/util/TransactionTemplate.java index 4012cfac89..965969d5dd 100755 --- a/activemq-core/src/main/java/org/apache/activemq/util/TransactionTemplate.java +++ b/activemq-core/src/main/java/org/apache/activemq/util/TransactionTemplate.java @@ -23,19 +23,18 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** - * A helper class for running code with a PersistenceAdapter - * in a transaction. - * + * A helper class for running code with a PersistenceAdapter in a transaction. + * * @version $Revision: 1.2 $ */ public class TransactionTemplate { - static private final Log log=LogFactory.getLog(TransactionTemplate.class); + static private final Log LOG = LogFactory.getLog(TransactionTemplate.class); private PersistenceAdapter persistenceAdapter; private ConnectionContext context; public TransactionTemplate(PersistenceAdapter persistenceAdapter, ConnectionContext context) { this.persistenceAdapter = persistenceAdapter; - this.context=context; + this.context = context; } public void run(Callback task) throws IOException { @@ -43,26 +42,22 @@ public class TransactionTemplate { Throwable throwable = null; try { task.execute(); - } - catch (IOException t) { + } catch (IOException t) { throwable = t; throw t; - } - catch (RuntimeException t) { + } catch (RuntimeException t) { throwable = t; throw t; - } - catch (Throwable t) { + } catch (Throwable t) { throwable = t; - throw IOExceptionSupport.create("Persistence task failed: "+t, t); + throw IOExceptionSupport.create("Persistence task failed: " + t, t); } finally { if (throwable == null) { persistenceAdapter.commitTransaction(context); - } - else { - log.error("Having to Rollback - caught an exception: " + throwable); + } else { + LOG.error("Having to Rollback - caught an exception: " + throwable); persistenceAdapter.rollbackTransaction(context); - } + } } } diff --git a/activemq-core/src/main/java/org/apache/activemq/util/URISupport.java b/activemq-core/src/main/java/org/apache/activemq/util/URISupport.java index c8b814235e..7dd469f95f 100755 --- a/activemq-core/src/main/java/org/apache/activemq/util/URISupport.java +++ b/activemq-core/src/main/java/org/apache/activemq/util/URISupport.java @@ -31,7 +31,7 @@ import java.util.Map; * @version $Revision$ */ public class URISupport { - + public static class CompositeData { String scheme; String path; @@ -39,54 +39,59 @@ public class URISupport { Map parameters; String fragment; public String host; - + public URI[] getComponents() { return components; } + public String getFragment() { return fragment; } + public Map getParameters() { return parameters; } + public String getScheme() { return scheme; } + public String getPath() { return path; } + public String getHost() { return host; } - + public URI toURI() throws URISyntaxException { StringBuffer sb = new StringBuffer(); - if( scheme!=null ) { + if (scheme != null) { sb.append(scheme); sb.append(':'); } - - if( host!=null && host.length()!=0 ) { + + if (host != null && host.length() != 0) { sb.append(host); } else { sb.append('('); for (int i = 0; i < components.length; i++) { - if( i!=0 ) + if (i != 0) sb.append(','); sb.append(components[i].toString()); } sb.append(')'); } - - if( path !=null ) { + + if (path != null) { sb.append('/'); sb.append(path); } - if(!parameters.isEmpty()) { + if (!parameters.isEmpty()) { sb.append("?"); sb.append(createQueryString(parameters)); } - if( fragment!=null ) { + if (fragment != null) { sb.append("#"); sb.append(fragment); } @@ -94,30 +99,30 @@ public class URISupport { } } - public static Map parseQuery(String uri) throws URISyntaxException{ - try{ - Map rc=new HashMap(); - if(uri!=null){ - String[] parameters=uri.split("&"); - for(int i=0;i=0){ - String name=URLDecoder.decode(parameters[i].substring(0,p),"UTF-8"); - String value=URLDecoder.decode(parameters[i].substring(p+1),"UTF-8"); - rc.put(name,value); - }else{ - rc.put(parameters[i],null); + public static Map parseQuery(String uri) throws URISyntaxException { + try { + Map rc = new HashMap(); + if (uri != null) { + String[] parameters = uri.split("&"); + for (int i = 0; i < parameters.length; i++) { + int p = parameters[i].indexOf("="); + if (p >= 0) { + String name = URLDecoder.decode(parameters[i].substring(0, p), "UTF-8"); + String value = URLDecoder.decode(parameters[i].substring(p + 1), "UTF-8"); + rc.put(name, value); + } else { + rc.put(parameters[i], null); } } } return rc; - }catch(UnsupportedEncodingException e){ - throw (URISyntaxException) new URISyntaxException(e.toString(),"Invalid encoding").initCause(e); + } catch (UnsupportedEncodingException e) { + throw (URISyntaxException)new URISyntaxException(e.toString(), "Invalid encoding").initCause(e); } } - + public static Map parseParamters(URI uri) throws URISyntaxException { - return uri.getQuery()==null ? Collections.EMPTY_MAP : parseQuery(stripPrefix(uri.getQuery(), "?")); + return uri.getQuery() == null ? Collections.EMPTY_MAP : parseQuery(stripPrefix(uri.getQuery(), "?")); } /** @@ -133,15 +138,15 @@ public class URISupport { public static URI createURIWithQuery(URI uri, String query) throws URISyntaxException { return new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(), uri.getPath(), query, uri.getFragment()); } - + public static CompositeData parseComposite(URI uri) throws URISyntaxException { - + CompositeData rc = new CompositeData(); rc.scheme = uri.getScheme(); String ssp = stripPrefix(uri.getSchemeSpecificPart().trim(), "//").trim(); parseComposite(uri, rc, ssp); - + rc.fragment = uri.getFragment(); return rc; } @@ -156,43 +161,43 @@ public class URISupport { private static void parseComposite(URI uri, CompositeData rc, String ssp) throws URISyntaxException { String componentString; String params; - - if(!checkParenthesis(ssp)){ + + if (!checkParenthesis(ssp)) { throw new URISyntaxException(uri.toString(), "Not a matching number of '(' and ')' parenthesis"); } - + int p; int intialParen = ssp.indexOf("("); - if( intialParen==0 ) { + if (intialParen == 0) { rc.host = ssp.substring(0, intialParen); p = rc.host.indexOf("/"); - if( p >= 0 ) { + if (p >= 0) { rc.path = rc.host.substring(p); - rc.host = rc.host.substring(0,p); + rc.host = rc.host.substring(0, p); } p = ssp.lastIndexOf(")"); - componentString = ssp.substring(intialParen+1,p); - params = ssp.substring(p+1).trim(); - + componentString = ssp.substring(intialParen + 1, p); + params = ssp.substring(p + 1).trim(); + } else { componentString = ssp; - params=""; + params = ""; } String components[] = splitComponents(componentString); - rc.components=new URI[components.length]; + rc.components = new URI[components.length]; for (int i = 0; i < components.length; i++) { rc.components[i] = new URI(components[i].trim()); } - + p = params.indexOf("?"); - if( p >= 0 ) { - if( p > 0) { + if (p >= 0) { + if (p > 0) { rc.path = stripPrefix(params.substring(0, p), "/"); } - rc.parameters = parseQuery(params.substring(p+1)); + rc.parameters = parseQuery(params.substring(p + 1)); } else { - if( params.length() > 0 ) + if (params.length() > 0) rc.path = stripPrefix(params, "/"); rc.parameters = Collections.EMPTY_MAP; } @@ -204,12 +209,12 @@ public class URISupport { */ private static String[] splitComponents(String str) { ArrayList l = new ArrayList(); - - int last=0; + + int last = 0; int depth = 0; char chars[] = str.toCharArray(); - for( int i=0; i < chars.length; i ++ ) { - switch( chars[i] ) { + for (int i = 0; i < chars.length; i++) { + switch (chars[i]) { case '(': depth++; break; @@ -217,45 +222,45 @@ public class URISupport { depth--; break; case ',': - if( depth == 0 ) { + if (depth == 0) { String s = str.substring(last, i); l.add(s); - last=i+1; + last = i + 1; } } } - + String s = str.substring(last); - if( s.length() !=0 ) - l.add(s); - + if (s.length() != 0) + l.add(s); + String rc[] = new String[l.size()]; l.toArray(rc); return rc; } - + public static String stripPrefix(String value, String prefix) { - if( value.startsWith(prefix) ) + if (value.startsWith(prefix)) return value.substring(prefix.length()); return value; } - + public static URI stripScheme(URI uri) throws URISyntaxException { - return new URI(stripPrefix(uri.getSchemeSpecificPart().trim(), "//")); + return new URI(stripPrefix(uri.getSchemeSpecificPart().trim(), "//")); } public static String createQueryString(Map options) throws URISyntaxException { try { - if(options.size()>0) { + if (options.size() > 0) { StringBuffer rc = new StringBuffer(); - boolean first=true; + boolean first = true; for (Iterator iter = options.keySet().iterator(); iter.hasNext();) { - if( first ) - first=false; + if (first) + first = false; else rc.append("&"); - - String key = (String) iter.next(); + + String key = (String)iter.next(); String value = (String)options.get(key); rc.append(URLEncoder.encode(key, "UTF-8")); rc.append("="); @@ -272,11 +277,12 @@ public class URISupport { /** * Creates a URI from the original URI and the remaining paramaters - * @throws URISyntaxException + * + * @throws URISyntaxException */ public static URI createRemainingURI(URI originalURI, Map params) throws URISyntaxException { String s = createQueryString(params); - if( s.length()==0 ) + if (s.length() == 0) s = null; return createURIWithQuery(originalURI, s); } @@ -284,20 +290,20 @@ public class URISupport { static public URI changeScheme(URI bindAddr, String scheme) throws URISyntaxException { return new URI(scheme, bindAddr.getUserInfo(), bindAddr.getHost(), bindAddr.getPort(), bindAddr.getPath(), bindAddr.getQuery(), bindAddr.getFragment()); } - - public static boolean checkParenthesis(String str){ - boolean result=true; - if(str!=null){ - int open=0; - int closed=0; - - int i=0; - while((i=str.indexOf('(',i)) >=0 ){ + + public static boolean checkParenthesis(String str) { + boolean result = true; + if (str != null) { + int open = 0; + int closed = 0; + + int i = 0; + while ((i = str.indexOf('(', i)) >= 0) { i++; open++; } - i=0; - while((i=str.indexOf(')',i)) >=0 ){ + i = 0; + while ((i = str.indexOf(')', i)) >= 0) { i++; closed++; } @@ -305,10 +311,10 @@ public class URISupport { } return result; } - - public int indexOfParenthesisMatch(String str){ + + public int indexOfParenthesisMatch(String str) { int result = -1; - + return result; } diff --git a/activemq-core/src/main/java/org/apache/activemq/wireformat/ObjectStreamWireFormat.java b/activemq-core/src/main/java/org/apache/activemq/wireformat/ObjectStreamWireFormat.java index b5b1144563..5628ac4168 100644 --- a/activemq-core/src/main/java/org/apache/activemq/wireformat/ObjectStreamWireFormat.java +++ b/activemq-core/src/main/java/org/apache/activemq/wireformat/ObjectStreamWireFormat.java @@ -32,13 +32,13 @@ import org.apache.activemq.util.ClassLoadingAwareObjectInputStream; /** * A simple implementation which uses Object Stream serialization. - * + * * @version $Revision: 1.1 $ */ public class ObjectStreamWireFormat implements WireFormat { public ByteSequence marshal(Object command) throws IOException { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + ByteArrayOutputStream baos = new ByteArrayOutputStream(); DataOutputStream ds = new DataOutputStream(baos); marshal(command, ds); ds.close(); @@ -64,7 +64,7 @@ public class ObjectStreamWireFormat implements WireFormat { in.close(); return command; } catch (ClassNotFoundException e) { - throw (IOException)new IOException("unmarshal failed: "+e).initCause(e); + throw (IOException)new IOException("unmarshal failed: " + e).initCause(e); } } diff --git a/activemq-core/src/main/java/org/apache/activemq/xbean/PooledBrokerFactoryBean.java b/activemq-core/src/main/java/org/apache/activemq/xbean/PooledBrokerFactoryBean.java index 15e019deb0..b0ef07ed5c 100644 --- a/activemq-core/src/main/java/org/apache/activemq/xbean/PooledBrokerFactoryBean.java +++ b/activemq-core/src/main/java/org/apache/activemq/xbean/PooledBrokerFactoryBean.java @@ -25,29 +25,29 @@ import org.springframework.beans.factory.InitializingBean; import org.springframework.core.io.Resource; /** - * Used to share a single broker even if you have multiple broker bean definitions. - * - * A use case is where you have multiple web applications that want to start an embedded broker - * but only the first one to deploy should actually start it. + * Used to share a single broker even if you have multiple broker bean + * definitions. A use case is where you have multiple web applications that want + * to start an embedded broker but only the first one to deploy should actually + * start it. * * @version $Revision$ */ public class PooledBrokerFactoryBean implements FactoryBean, InitializingBean, DisposableBean { static final HashMap sharedBrokerMap = new HashMap(); - + private boolean start; private Resource config; - + static class SharedBroker { BrokerFactoryBean factory; int refCount; } - + public void afterPropertiesSet() throws Exception { - synchronized( sharedBrokerMap ) { - SharedBroker sharedBroker = (SharedBroker) sharedBrokerMap.get(config.getFilename()); - if( sharedBroker == null ) { + synchronized (sharedBrokerMap) { + SharedBroker sharedBroker = (SharedBroker)sharedBrokerMap.get(config.getFilename()); + if (sharedBroker == null) { sharedBroker = new SharedBroker(); sharedBroker.factory = new BrokerFactoryBean(); sharedBroker.factory.setConfig(config); @@ -60,11 +60,11 @@ public class PooledBrokerFactoryBean implements FactoryBean, InitializingBean, D } public void destroy() throws Exception { - synchronized( sharedBrokerMap ) { - SharedBroker sharedBroker = (SharedBroker) sharedBrokerMap.get(config.getFilename()); - if( sharedBroker != null ) { + synchronized (sharedBrokerMap) { + SharedBroker sharedBroker = (SharedBroker)sharedBrokerMap.get(config.getFilename()); + if (sharedBroker != null) { sharedBroker.refCount--; - if( sharedBroker.refCount==0 ) { + if (sharedBroker.refCount == 0) { sharedBroker.factory.destroy(); sharedBrokerMap.remove(config.getFilename()); } @@ -77,9 +77,9 @@ public class PooledBrokerFactoryBean implements FactoryBean, InitializingBean, D } public Object getObject() throws Exception { - synchronized( sharedBrokerMap ) { - SharedBroker sharedBroker = (SharedBroker) sharedBrokerMap.get(config.getFilename()); - if( sharedBroker != null ) { + synchronized (sharedBrokerMap) { + SharedBroker sharedBroker = (SharedBroker)sharedBrokerMap.get(config.getFilename()); + if (sharedBroker != null) { return sharedBroker.factory.getObject(); } } @@ -103,7 +103,7 @@ public class PooledBrokerFactoryBean implements FactoryBean, InitializingBean, D } public void setStart(boolean start) { - this.start=start; + this.start = start; } - + } diff --git a/activemq-core/src/test/java/org/apache/activemq/AMQDeadlockTest3.java b/activemq-core/src/test/java/org/apache/activemq/AMQDeadlockTest3.java index 25ce61ce79..9597888beb 100644 --- a/activemq-core/src/test/java/org/apache/activemq/AMQDeadlockTest3.java +++ b/activemq-core/src/test/java/org/apache/activemq/AMQDeadlockTest3.java @@ -34,405 +34,383 @@ import org.springframework.jms.core.JmsTemplate; import org.springframework.jms.core.MessageCreator; import org.springframework.jms.listener.DefaultMessageListenerContainer; - public class AMQDeadlockTest3 extends TestCase { private static final transient Log log = LogFactory.getLog(AMQDeadlockTest3.class); private static final String URL1 = "tcp://localhost:61616"; - private static final String URL2 = "tcp://localhost:61617"; + private static final String URL2 = "tcp://localhost:61617"; - private static final String QUEUE1_NAME = "test.queue.1"; + private static final String QUEUE1_NAME = "test.queue.1"; - private static final String QUEUE2_NAME = "test.queue.2"; + private static final String QUEUE2_NAME = "test.queue.2"; - private static final int MAX_CONSUMERS = 1; + private static final int MAX_CONSUMERS = 1; - private static final int MAX_PRODUCERS = 1; + private static final int MAX_PRODUCERS = 1; - private static final int NUM_MESSAGE_TO_SEND = 10; + private static final int NUM_MESSAGE_TO_SEND = 10; - private AtomicInteger messageCount = new AtomicInteger(); - private CountDownLatch doneLatch; + private AtomicInteger messageCount = new AtomicInteger(); + private CountDownLatch doneLatch; - public void setUp() throws Exception { - } + public void setUp() throws Exception { + } - public void tearDown() throws Exception { - } + public void tearDown() throws Exception { + } - // This should fail with incubator-activemq-fuse-4.1.0.5 - public void testQueueLimitsWithOneBrokerSameConnection() throws Exception { + // This should fail with incubator-activemq-fuse-4.1.0.5 + public void testQueueLimitsWithOneBrokerSameConnection() throws Exception { - BrokerService brokerService1 = null; - ActiveMQConnectionFactory acf = null; - PooledConnectionFactory pcf = null; - DefaultMessageListenerContainer container1 = null; + BrokerService brokerService1 = null; + ActiveMQConnectionFactory acf = null; + PooledConnectionFactory pcf = null; + DefaultMessageListenerContainer container1 = null; - try { - brokerService1 = createBrokerService("broker1", URL1, null); - brokerService1.start(); + try { + brokerService1 = createBrokerService("broker1", URL1, null); + brokerService1.start(); - acf = createConnectionFactory(URL1); - pcf = new PooledConnectionFactory(acf); + acf = createConnectionFactory(URL1); + pcf = new PooledConnectionFactory(acf); - // Only listen on the first queue.. let the 2nd queue fill up. - doneLatch = new CountDownLatch(NUM_MESSAGE_TO_SEND); - container1 = createDefaultMessageListenerContainer(acf, new TestMessageListener1(500), QUEUE1_NAME); - container1.afterPropertiesSet(); - - Thread.sleep(2000); + // Only listen on the first queue.. let the 2nd queue fill up. + doneLatch = new CountDownLatch(NUM_MESSAGE_TO_SEND); + container1 = createDefaultMessageListenerContainer(acf, new TestMessageListener1(500), QUEUE1_NAME); + container1.afterPropertiesSet(); - final ExecutorService executor = Executors.newCachedThreadPool(); - for (int i = 0; i < MAX_PRODUCERS; i++) { - executor.submit(new PooledProducerTask(pcf, QUEUE2_NAME)); - Thread.sleep(1000); - executor.submit(new PooledProducerTask(pcf, QUEUE1_NAME)); - } - - // Wait for all message to arrive. - assertTrue(doneLatch.await(20, TimeUnit.SECONDS)); - executor.shutdownNow(); + Thread.sleep(2000); - Assert.assertEquals(NUM_MESSAGE_TO_SEND, messageCount.get()); + final ExecutorService executor = Executors.newCachedThreadPool(); + for (int i = 0; i < MAX_PRODUCERS; i++) { + executor.submit(new PooledProducerTask(pcf, QUEUE2_NAME)); + Thread.sleep(1000); + executor.submit(new PooledProducerTask(pcf, QUEUE1_NAME)); + } - } finally { + // Wait for all message to arrive. + assertTrue(doneLatch.await(20, TimeUnit.SECONDS)); + executor.shutdownNow(); - container1.stop(); - container1.destroy(); - container1 = null; - brokerService1.stop(); - brokerService1 = null; + Assert.assertEquals(NUM_MESSAGE_TO_SEND, messageCount.get()); - } + } finally { - } - + container1.stop(); + container1.destroy(); + container1 = null; + brokerService1.stop(); + brokerService1 = null; + } - - // This should fail with incubator-activemq-fuse-4.1.0.5 - public void testQueueLimitsWithTwoBrokerProduceandConsumeonDifferentBrokersWithOneConnectionForProducing() - throws Exception { + } - BrokerService brokerService1 = null; - BrokerService brokerService2 = null; - ActiveMQConnectionFactory acf1 = null; - ActiveMQConnectionFactory acf2 = null; - PooledConnectionFactory pcf = null; - DefaultMessageListenerContainer container1 = null; - - try { - brokerService1 = createBrokerService("broker1", URL1, URL2); - brokerService1.start(); - brokerService2 = createBrokerService("broker2", URL2, URL1); - brokerService2.start(); + // This should fail with incubator-activemq-fuse-4.1.0.5 + public void testQueueLimitsWithTwoBrokerProduceandConsumeonDifferentBrokersWithOneConnectionForProducing() throws Exception { - acf1 = createConnectionFactory(URL1); - acf2 = createConnectionFactory(URL2); + BrokerService brokerService1 = null; + BrokerService brokerService2 = null; + ActiveMQConnectionFactory acf1 = null; + ActiveMQConnectionFactory acf2 = null; + PooledConnectionFactory pcf = null; + DefaultMessageListenerContainer container1 = null; - pcf = new PooledConnectionFactory(acf1); + try { + brokerService1 = createBrokerService("broker1", URL1, URL2); + brokerService1.start(); + brokerService2 = createBrokerService("broker2", URL2, URL1); + brokerService2.start(); - Thread.sleep(1000); + acf1 = createConnectionFactory(URL1); + acf2 = createConnectionFactory(URL2); - doneLatch = new CountDownLatch(MAX_PRODUCERS * NUM_MESSAGE_TO_SEND); - container1 = createDefaultMessageListenerContainer(acf2, new TestMessageListener1(500), QUEUE1_NAME); - container1.afterPropertiesSet(); + pcf = new PooledConnectionFactory(acf1); - final ExecutorService executor = Executors.newCachedThreadPool(); - for (int i = 0; i < MAX_PRODUCERS; i++) { - executor.submit(new PooledProducerTask(pcf, QUEUE2_NAME)); - Thread.sleep(1000); - executor.submit(new PooledProducerTask(pcf, QUEUE1_NAME)); - } + Thread.sleep(1000); - assertTrue(doneLatch.await(20, TimeUnit.SECONDS)); - executor.shutdownNow(); - - Assert.assertEquals(MAX_PRODUCERS * NUM_MESSAGE_TO_SEND, - messageCount.get()); - } finally { - - container1.stop(); - container1.destroy(); - container1 = null; - - brokerService1.stop(); - brokerService1 = null; - brokerService2.stop(); - brokerService2 = null; - } - } - - - // This should fail with incubator-activemq-fuse-4.1.0.5 - public void testQueueLimitsWithTwoBrokerProduceandConsumeonDifferentBrokersWithSeperateConnectionsForProducing() - throws Exception { - - BrokerService brokerService1 = null; - BrokerService brokerService2 = null; - ActiveMQConnectionFactory acf1 = null; - ActiveMQConnectionFactory acf2 = null; - DefaultMessageListenerContainer container1 = null; - DefaultMessageListenerContainer container2 = null; - - try { - brokerService1 = createBrokerService("broker1", URL1, URL2); - brokerService1.start(); - brokerService2 = createBrokerService("broker2", URL2, URL1); - brokerService2.start(); - - acf1 = createConnectionFactory(URL1); - acf2 = createConnectionFactory(URL2); - - Thread.sleep(1000); - - doneLatch = new CountDownLatch(NUM_MESSAGE_TO_SEND*MAX_PRODUCERS); - - container1 = createDefaultMessageListenerContainer(acf2, new TestMessageListener1(500), QUEUE1_NAME); - container1.afterPropertiesSet(); - container2 = createDefaultMessageListenerContainer(acf2, new TestMessageListener1(30000), QUEUE2_NAME); - container2.afterPropertiesSet(); - - final ExecutorService executor = Executors.newCachedThreadPool(); - for (int i = 0; i < MAX_PRODUCERS; i++) { - executor.submit(new NonPooledProducerTask(acf1, QUEUE2_NAME)); - Thread.sleep(1000); - executor.submit(new NonPooledProducerTask(acf1, QUEUE1_NAME)); - } - - assertTrue(doneLatch.await(20, TimeUnit.SECONDS)); - executor.shutdownNow(); - - Assert.assertEquals(MAX_PRODUCERS * NUM_MESSAGE_TO_SEND, messageCount.get()); - } finally { - - container1.stop(); - container1.destroy(); - container1 = null; - - container2.stop(); - container2.destroy(); - container2 = null; - - 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 UsageManager memoryManager = new UsageManager(); - memoryManager.setLimit(5000000); - brokerService.setMemoryManager(memoryManager); - - final ArrayList policyEntries = new ArrayList(); - - final PolicyEntry entry = new PolicyEntry(); - entry.setQueue(">"); - // entry.setQueue(QUEUE1_NAME); - entry.setMemoryLimit(1000); - 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.setBrokerName(brokerName); - 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); - brokerService.addNetworkConnector(nc); - } - - return brokerService; - - } - - public DefaultMessageListenerContainer createDefaultMessageListenerContainer( - final ConnectionFactory acf, final MessageListener listener, - final String queue) { - final DefaultMessageListenerContainer container = new DefaultMessageListenerContainer(); - container.setConnectionFactory(acf); - container.setDestinationName(queue); - container.setMessageListener(listener); - container.setSessionTransacted(false); - container.setSessionAcknowledgeMode(Session.AUTO_ACKNOWLEDGE); - container.setConcurrentConsumers(MAX_CONSUMERS); - return container; - } - - public ActiveMQConnectionFactory createConnectionFactory(final String url) { - final ActiveMQConnectionFactory acf = new ActiveMQConnectionFactory(url); - acf.setCopyMessageOnSend(false); - acf.setUseAsyncSend(false); - acf.setDispatchAsync(true); - acf.setUseCompression(false); - acf.setOptimizeAcknowledge(false); - acf.setOptimizedMessageDispatch(true); - acf.setAlwaysSyncSend(true); - return acf; - } - - private class TestMessageListener1 implements MessageListener { - - private final long waitTime; - - public TestMessageListener1(long waitTime) { - this.waitTime = waitTime; - - } - - public void onMessage(Message msg) { - - try { - log.info("Listener1 Consumed message "+ msg.getIntProperty("count")); - - messageCount.incrementAndGet(); - doneLatch.countDown(); - - Thread.sleep(waitTime); - } catch (JMSException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (InterruptedException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } + doneLatch = new CountDownLatch(MAX_PRODUCERS * NUM_MESSAGE_TO_SEND); + container1 = createDefaultMessageListenerContainer(acf2, new TestMessageListener1(500), QUEUE1_NAME); + container1.afterPropertiesSet(); - } - } + final ExecutorService executor = Executors.newCachedThreadPool(); + for (int i = 0; i < MAX_PRODUCERS; i++) { + executor.submit(new PooledProducerTask(pcf, QUEUE2_NAME)); + Thread.sleep(1000); + executor.submit(new PooledProducerTask(pcf, QUEUE1_NAME)); + } + assertTrue(doneLatch.await(20, TimeUnit.SECONDS)); + executor.shutdownNow(); - private static class PooledProducerTask implements Runnable { - - private final String queueName; - - private final PooledConnectionFactory pcf; - - public PooledProducerTask(final PooledConnectionFactory pcf, - final String queueName) { - this.pcf = pcf; - this.queueName = queueName; - } - - public void run() { - - try { - - final JmsTemplate jmsTemplate = new JmsTemplate(pcf); - jmsTemplate.setDeliveryMode(DeliveryMode.NON_PERSISTENT); - jmsTemplate.setExplicitQosEnabled(true); - jmsTemplate.setMessageIdEnabled(false); - jmsTemplate.setMessageTimestampEnabled(false); - jmsTemplate.afterPropertiesSet(); - - final byte[] bytes = new byte[2048]; - final Random r = new Random(); - r.nextBytes(bytes); - - Thread.sleep(2000); - - final AtomicInteger count = new AtomicInteger(); - for (int i = 0; i < NUM_MESSAGE_TO_SEND; i++) { - jmsTemplate.send(queueName, new MessageCreator() { - - public Message createMessage(Session session) - throws JMSException { - - final BytesMessage message = session.createBytesMessage(); - - message.writeBytes(bytes); - message.setIntProperty("count", count.incrementAndGet()); - message.setStringProperty("producer", "pooled"); - return message; - } - }); - - log.info("PooledProducer sent message: "+ count.get()); - // Thread.sleep(1000); - } - - } catch (final Throwable e) { - log.error("Producer 1 is exiting", e); - } - } - } - - - private static class NonPooledProducerTask implements Runnable { + Assert.assertEquals(MAX_PRODUCERS * NUM_MESSAGE_TO_SEND, messageCount.get()); + } finally { - private final String queueName; + container1.stop(); + container1.destroy(); + container1 = null; - private final ConnectionFactory cf; + brokerService1.stop(); + brokerService1 = null; + brokerService2.stop(); + brokerService2 = null; + } + } + + // This should fail with incubator-activemq-fuse-4.1.0.5 + public void testQueueLimitsWithTwoBrokerProduceandConsumeonDifferentBrokersWithSeperateConnectionsForProducing() throws Exception { + + BrokerService brokerService1 = null; + BrokerService brokerService2 = null; + ActiveMQConnectionFactory acf1 = null; + ActiveMQConnectionFactory acf2 = null; + DefaultMessageListenerContainer container1 = null; + DefaultMessageListenerContainer container2 = null; + + try { + brokerService1 = createBrokerService("broker1", URL1, URL2); + brokerService1.start(); + brokerService2 = createBrokerService("broker2", URL2, URL1); + brokerService2.start(); + + acf1 = createConnectionFactory(URL1); + acf2 = createConnectionFactory(URL2); + + Thread.sleep(1000); + + doneLatch = new CountDownLatch(NUM_MESSAGE_TO_SEND * MAX_PRODUCERS); + + container1 = createDefaultMessageListenerContainer(acf2, new TestMessageListener1(500), QUEUE1_NAME); + container1.afterPropertiesSet(); + container2 = createDefaultMessageListenerContainer(acf2, new TestMessageListener1(30000), QUEUE2_NAME); + container2.afterPropertiesSet(); + + final ExecutorService executor = Executors.newCachedThreadPool(); + for (int i = 0; i < MAX_PRODUCERS; i++) { + executor.submit(new NonPooledProducerTask(acf1, QUEUE2_NAME)); + Thread.sleep(1000); + executor.submit(new NonPooledProducerTask(acf1, QUEUE1_NAME)); + } + + assertTrue(doneLatch.await(20, TimeUnit.SECONDS)); + executor.shutdownNow(); + + Assert.assertEquals(MAX_PRODUCERS * NUM_MESSAGE_TO_SEND, messageCount.get()); + } finally { + + container1.stop(); + container1.destroy(); + container1 = null; + + container2.stop(); + container2.destroy(); + container2 = null; + + 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); - public NonPooledProducerTask(final ConnectionFactory cf, - final String queueName) { - this.cf = cf; - this.queueName = queueName; - } + final UsageManager memoryManager = new UsageManager(); + memoryManager.setLimit(5000000); + brokerService.setMemoryManager(memoryManager); + + final ArrayList policyEntries = new ArrayList(); + + final PolicyEntry entry = new PolicyEntry(); + entry.setQueue(">"); + // entry.setQueue(QUEUE1_NAME); + entry.setMemoryLimit(1000); + 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.setBrokerName(brokerName); + tConnector.setName(brokerName + ".transportConnector"); + brokerService.addConnector(tConnector); - public void run() { + if (uri2 != null) { + final NetworkConnector nc = new DiscoveryNetworkConnector(new URI("static:" + uri2)); + nc.setBridgeTempDestinations(true); + nc.setBrokerName(brokerName); + brokerService.addNetworkConnector(nc); + } + + return brokerService; + + } + + public DefaultMessageListenerContainer createDefaultMessageListenerContainer(final ConnectionFactory acf, final MessageListener listener, final String queue) { + final DefaultMessageListenerContainer container = new DefaultMessageListenerContainer(); + container.setConnectionFactory(acf); + container.setDestinationName(queue); + container.setMessageListener(listener); + container.setSessionTransacted(false); + container.setSessionAcknowledgeMode(Session.AUTO_ACKNOWLEDGE); + container.setConcurrentConsumers(MAX_CONSUMERS); + return container; + } - try { + public ActiveMQConnectionFactory createConnectionFactory(final String url) { + final ActiveMQConnectionFactory acf = new ActiveMQConnectionFactory(url); + acf.setCopyMessageOnSend(false); + acf.setUseAsyncSend(false); + acf.setDispatchAsync(true); + acf.setUseCompression(false); + acf.setOptimizeAcknowledge(false); + acf.setOptimizedMessageDispatch(true); + acf.setAlwaysSyncSend(true); + return acf; + } - final JmsTemplate jmsTemplate = new JmsTemplate(cf); - jmsTemplate.setDeliveryMode(DeliveryMode.NON_PERSISTENT); - jmsTemplate.setExplicitQosEnabled(true); - jmsTemplate.setMessageIdEnabled(false); - jmsTemplate.setMessageTimestampEnabled(false); - jmsTemplate.afterPropertiesSet(); + private class TestMessageListener1 implements MessageListener { - final byte[] bytes = new byte[2048]; - final Random r = new Random(); - r.nextBytes(bytes); + private final long waitTime; - Thread.sleep(2000); + public TestMessageListener1(long waitTime) { + this.waitTime = waitTime; - final AtomicInteger count = new AtomicInteger(); - for (int i = 0; i < NUM_MESSAGE_TO_SEND; i++) { - jmsTemplate.send(queueName, new MessageCreator() { + } - public Message createMessage(Session session) - throws JMSException { + public void onMessage(Message msg) { - final BytesMessage message = session - .createBytesMessage(); + try { + log.info("Listener1 Consumed message " + msg.getIntProperty("count")); - message.writeBytes(bytes); - message.setIntProperty("count", count - .incrementAndGet()); - message.setStringProperty("producer", "non-pooled"); - return message; - } - }); + messageCount.incrementAndGet(); + doneLatch.countDown(); - log.info("Non-PooledProducer sent message: " + count.get()); + Thread.sleep(waitTime); + } catch (JMSException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (InterruptedException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } - // Thread.sleep(1000); - } + } + } - } catch (final Throwable e) { - log.error("Producer 1 is exiting", e); - } - } - } + private static class PooledProducerTask implements Runnable { + + private final String queueName; + + private final PooledConnectionFactory pcf; + + public PooledProducerTask(final PooledConnectionFactory pcf, final String queueName) { + this.pcf = pcf; + this.queueName = queueName; + } + + public void run() { + + try { + + final JmsTemplate jmsTemplate = new JmsTemplate(pcf); + jmsTemplate.setDeliveryMode(DeliveryMode.NON_PERSISTENT); + jmsTemplate.setExplicitQosEnabled(true); + jmsTemplate.setMessageIdEnabled(false); + jmsTemplate.setMessageTimestampEnabled(false); + jmsTemplate.afterPropertiesSet(); + + final byte[] bytes = new byte[2048]; + final Random r = new Random(); + r.nextBytes(bytes); + + Thread.sleep(2000); + + final AtomicInteger count = new AtomicInteger(); + for (int i = 0; i < NUM_MESSAGE_TO_SEND; i++) { + jmsTemplate.send(queueName, new MessageCreator() { + + public Message createMessage(Session session) throws JMSException { + + final BytesMessage message = session.createBytesMessage(); + + message.writeBytes(bytes); + message.setIntProperty("count", count.incrementAndGet()); + message.setStringProperty("producer", "pooled"); + return message; + } + }); + + log.info("PooledProducer sent message: " + count.get()); + // Thread.sleep(1000); + } + + } catch (final Throwable e) { + log.error("Producer 1 is exiting", e); + } + } + } + + private static class NonPooledProducerTask implements Runnable { + + private final String queueName; + + private final ConnectionFactory cf; + + public NonPooledProducerTask(final ConnectionFactory cf, final String queueName) { + this.cf = cf; + this.queueName = queueName; + } + + public void run() { + + try { + + final JmsTemplate jmsTemplate = new JmsTemplate(cf); + jmsTemplate.setDeliveryMode(DeliveryMode.NON_PERSISTENT); + jmsTemplate.setExplicitQosEnabled(true); + jmsTemplate.setMessageIdEnabled(false); + jmsTemplate.setMessageTimestampEnabled(false); + jmsTemplate.afterPropertiesSet(); + + final byte[] bytes = new byte[2048]; + final Random r = new Random(); + r.nextBytes(bytes); + + Thread.sleep(2000); + + final AtomicInteger count = new AtomicInteger(); + for (int i = 0; i < NUM_MESSAGE_TO_SEND; i++) { + jmsTemplate.send(queueName, new MessageCreator() { + + public Message createMessage(Session session) throws JMSException { + + final BytesMessage message = session.createBytesMessage(); + + message.writeBytes(bytes); + message.setIntProperty("count", count.incrementAndGet()); + message.setStringProperty("producer", "non-pooled"); + return message; + } + }); + + log.info("Non-PooledProducer sent message: " + count.get()); + + // Thread.sleep(1000); + } + + } catch (final Throwable e) { + log.error("Producer 1 is exiting", e); + } + } + } } diff --git a/activemq-core/src/test/java/org/apache/activemq/ActiveMQMessageAuditTest.java b/activemq-core/src/test/java/org/apache/activemq/ActiveMQMessageAuditTest.java index 5f25bf9ca0..31d3cdc3d9 100755 --- a/activemq-core/src/test/java/org/apache/activemq/ActiveMQMessageAuditTest.java +++ b/activemq-core/src/test/java/org/apache/activemq/ActiveMQMessageAuditTest.java @@ -28,16 +28,16 @@ import org.apache.activemq.util.IdGenerator; * * @version $Revision: 1.1.1.1 $ */ -public class ActiveMQMessageAuditTest extends TestCase{ +public class ActiveMQMessageAuditTest extends TestCase { - public static void main(String[] args){ + public static void main(String[] args) { } - protected void setUp() throws Exception{ + protected void setUp() throws Exception { super.setUp(); } - protected void tearDown() throws Exception{ + protected void tearDown() throws Exception { super.tearDown(); } @@ -46,48 +46,48 @@ public class ActiveMQMessageAuditTest extends TestCase{ * * @param arg0 */ - public ActiveMQMessageAuditTest(String arg0){ + public ActiveMQMessageAuditTest(String arg0) { super(arg0); } /** * test case for isDuplicate */ - public void testIsDuplicateString(){ - int count=10000; - ActiveMQMessageAudit audit=new ActiveMQMessageAudit(); - IdGenerator idGen=new IdGenerator(); + public void testIsDuplicateString() { + int count = 10000; + ActiveMQMessageAudit audit = new ActiveMQMessageAudit(); + IdGenerator idGen = new IdGenerator(); // add to a list - List list=new ArrayList(); - for(int i=0;i list = new ArrayList(); + for (int i = 0; i < count; i++) { + String id = idGen.generateId(); list.add(id); - assertTrue(audit.isDuplicate(id)==false); + assertTrue(audit.isDuplicate(id) == false); } - for(String id:list){ + for (String id : list) { assertTrue(audit.isDuplicate(id)); } } - public void testIsDuplicateMessageReference(){ - int count=10000; - ActiveMQMessageAudit audit=new ActiveMQMessageAudit(); + public void testIsDuplicateMessageReference() { + int count = 10000; + ActiveMQMessageAudit audit = new ActiveMQMessageAudit(); // add to a list - List list=new ArrayList(); - for(int i=0;i list = new ArrayList(); + for (int i = 0; i < count; i++) { + ProducerId pid = new ProducerId(); pid.setConnectionId("test"); pid.setSessionId(0); pid.setValue(1); - MessageId id=new MessageId(); + MessageId id = new MessageId(); id.setProducerId(pid); id.setProducerSequenceId(i); - ActiveMQMessage msg=new ActiveMQMessage(); + ActiveMQMessage msg = new ActiveMQMessage(); msg.setMessageId(id); list.add(msg); - assertTrue(audit.isDuplicateMessageReference(msg)==false); + assertTrue(audit.isDuplicateMessageReference(msg) == false); } - for(MessageReference msg:list){ + for (MessageReference msg : list) { assertTrue(audit.isDuplicateMessageReference(msg)); } } diff --git a/activemq-core/src/test/java/org/apache/activemq/CombinationTestSupport.java b/activemq-core/src/test/java/org/apache/activemq/CombinationTestSupport.java index ed28ce597b..122d18591b 100755 --- a/activemq-core/src/test/java/org/apache/activemq/CombinationTestSupport.java +++ b/activemq-core/src/test/java/org/apache/activemq/CombinationTestSupport.java @@ -37,27 +37,20 @@ import org.apache.commons.logging.LogFactory; /** * Poor mans way of getting JUnit to run a test case through a few different - * combinations of options. - * - * - * Usage: If you have a test case called testFoo what you want to run through a - * few combinations, of of values for the attributes age and color, you would - * something like: + * combinations of options. Usage: If you have a test case called testFoo what + * you want to run through a few combinations, of of values for the attributes + * age and color, you would something like: * public void initCombosForTestFoo() { * addCombinationValues( "age", new Object[]{ new Integer(21), new Integer(30) } ); * addCombinationValues( "color", new Object[]{"blue", "green"} ); * } * - * * The testFoo test case would be run for each possible combination of age and - * color that you setup in the initCombosForTestFoo method. Before each combination is - * run, the age and color fields of the test class are set to one of the values - * defined. This is done before the normal setUp method is called. - * + * color that you setup in the initCombosForTestFoo method. Before each + * combination is run, the age and color fields of the test class are set to one + * of the values defined. This is done before the normal setUp method is called. * If you want the test combinations to show up as separate test runs in the - * JUnit reports, add a suite method to your test case similar to: - * - * + * JUnit reports, add a suite method to your test case similar to: * public static Test suite() { * return suite(FooTest.class); * } @@ -68,7 +61,7 @@ import org.apache.commons.logging.LogFactory; public abstract class CombinationTestSupport extends AutoFailTestSupport { protected static final Log log = LogFactory.getLog(CombinationTestSupport.class); - + private HashMap comboOptions = new HashMap(); private boolean combosEvaluated; private Map options; @@ -84,7 +77,7 @@ public abstract class CombinationTestSupport extends AutoFailTestSupport { } public void addCombinationValues(String attribute, Object[] options) { - ComboOption co = (ComboOption) this.comboOptions.get(attribute); + ComboOption co = (ComboOption)this.comboOptions.get(attribute); if (co == null) { this.comboOptions.put(attribute, new ComboOption(attribute, Arrays.asList(options))); } else { @@ -99,8 +92,8 @@ public abstract class CombinationTestSupport extends AutoFailTestSupport { CombinationTestSupport[] combinations = getCombinations(); for (int i = 0; i < combinations.length; i++) { CombinationTestSupport test = combinations[i]; - if( getName()==null || getName().equals( test.getName()) ) { - test.runBare(); + if (getName() == null || getName().equals(test.getName())) { + test.runBare(); } } } @@ -109,14 +102,13 @@ public abstract class CombinationTestSupport extends AutoFailTestSupport { private void setOptions(Map options) throws NoSuchFieldException, IllegalAccessException { this.options = options; for (Iterator iterator = options.keySet().iterator(); iterator.hasNext();) { - String attribute = (String) iterator.next(); + String attribute = (String)iterator.next(); Object value = options.get(attribute); try { Field field = getClass().getField(attribute); field.set(this, value); } catch (Throwable e) { - log.info("Could not set field '" + attribute + "' to value '" + value - + "', make sure the field exists and is public."); + log.info("Could not set field '" + attribute + "' to value '" + value + "', make sure the field exists and is public."); } } } @@ -127,8 +119,8 @@ public abstract class CombinationTestSupport extends AutoFailTestSupport { method.invoke(this, null); } catch (Throwable e) { } - - String name = getName().split(" ")[0]; + + String name = getName().split(" ")[0]; String comboSetupMethodName = "initCombosFor" + Character.toUpperCase(name.charAt(0)) + name.substring(1); try { Method method = getClass().getMethod(comboSetupMethodName, null); @@ -139,28 +131,28 @@ public abstract class CombinationTestSupport extends AutoFailTestSupport { try { ArrayList expandedOptions = new ArrayList(); expandCombinations(new ArrayList(comboOptions.values()), expandedOptions); - + if (expandedOptions.isEmpty()) { combosEvaluated = true; - return new CombinationTestSupport[] { this }; + return new CombinationTestSupport[] {this}; } else { - + ArrayList result = new ArrayList(); // Run the test case for each possible combination for (Iterator iter = expandedOptions.iterator(); iter.hasNext();) { - CombinationTestSupport combo = (CombinationTestSupport) TestSuite.createTest(getClass(), name); + CombinationTestSupport combo = (CombinationTestSupport)TestSuite.createTest(getClass(), name); combo.combosEvaluated = true; - combo.setOptions((Map) iter.next()); + combo.setOptions((Map)iter.next()); result.add(combo); } - + CombinationTestSupport rc[] = new CombinationTestSupport[result.size()]; result.toArray(rc); return rc; } } catch (Throwable e) { combosEvaluated = true; - return new CombinationTestSupport[] { this }; + return new CombinationTestSupport[] {this}; } } @@ -172,14 +164,14 @@ public abstract class CombinationTestSupport extends AutoFailTestSupport { map = new HashMap(); expandedCombos.add(map); } else { - map = (HashMap) expandedCombos.get(expandedCombos.size() - 1); + map = (HashMap)expandedCombos.get(expandedCombos.size() - 1); } LinkedList l = new LinkedList(optionsLeft); - ComboOption comboOption = (ComboOption) l.removeLast(); + ComboOption comboOption = (ComboOption)l.removeLast(); int i = 0; for (Iterator iter = comboOption.values.iterator(); iter.hasNext();) { - Object value = (Object) iter.next(); + Object value = (Object)iter.next(); if (i != 0) { map = new HashMap(map); expandedCombos.add(map); @@ -203,7 +195,7 @@ public abstract class CombinationTestSupport extends AutoFailTestSupport { names.add(name); Test test = TestSuite.createTest(clazz, name); if (test instanceof CombinationTestSupport) { - CombinationTestSupport[] combinations = ((CombinationTestSupport) test).getCombinations(); + CombinationTestSupport[] combinations = ((CombinationTestSupport)test).getCombinations(); for (int j = 0; j < combinations.length; j++) { suite.addTest(combinations[j]); } diff --git a/activemq-core/src/test/java/org/apache/activemq/ConsumerReceiveWithTimeoutTest.java b/activemq-core/src/test/java/org/apache/activemq/ConsumerReceiveWithTimeoutTest.java index 1b98697773..8c087d030d 100644 --- a/activemq-core/src/test/java/org/apache/activemq/ConsumerReceiveWithTimeoutTest.java +++ b/activemq-core/src/test/java/org/apache/activemq/ConsumerReceiveWithTimeoutTest.java @@ -24,11 +24,10 @@ import javax.jms.MessageProducer; import javax.jms.Queue; import javax.jms.Session; - /** * @version $Revision: 1.1.1.1 $ */ -public class ConsumerReceiveWithTimeoutTest extends TestSupport { +public class ConsumerReceiveWithTimeoutTest extends TestSupport { private Connection connection; @@ -49,8 +48,9 @@ public class ConsumerReceiveWithTimeoutTest extends TestSupport { } /** - * Test to check if consumer thread wakes up inside a receive(timeout) after a message is dispatched to the consumer - * + * Test to check if consumer thread wakes up inside a receive(timeout) after + * a message is dispatched to the consumer + * * @throws javax.jms.JMSException */ public void testConsumerReceiveBeforeMessageDispatched() throws JMSException { @@ -61,15 +61,18 @@ public class ConsumerReceiveWithTimeoutTest extends TestSupport { final Queue queue = session.createQueue("test"); Thread t = new Thread() { - public void run(){ - try { - //wait for 10 seconds to allow consumer.receive to be run first - Thread.sleep(10000); - MessageProducer producer = session.createProducer(queue); - producer.send(session.createTextMessage("Hello")); - }catch(Exception e){e.printStackTrace();} - } - }; + public void run() { + try { + // wait for 10 seconds to allow consumer.receive to be run + // first + Thread.sleep(10000); + MessageProducer producer = session.createProducer(queue); + producer.send(session.createTextMessage("Hello")); + } catch (Exception e) { + e.printStackTrace(); + } + } + }; t.start(); @@ -81,8 +84,4 @@ public class ConsumerReceiveWithTimeoutTest extends TestSupport { } - - - - } diff --git a/activemq-core/src/test/java/org/apache/activemq/JMSConsumerTest.java b/activemq-core/src/test/java/org/apache/activemq/JMSConsumerTest.java index f8aa49bbdc..fe4bbde84f 100755 --- a/activemq-core/src/test/java/org/apache/activemq/JMSConsumerTest.java +++ b/activemq-core/src/test/java/org/apache/activemq/JMSConsumerTest.java @@ -272,7 +272,7 @@ public class JMSConsumerTest extends JmsTestSupport { addCombinationValues("ackMode", new Object[] {Integer.valueOf(Session.AUTO_ACKNOWLEDGE), Integer.valueOf(Session.DUPS_OK_ACKNOWLEDGE), Integer.valueOf(Session.CLIENT_ACKNOWLEDGE)}); - addCombinationValues("destinationType", new Object[] {Byte.valueOf(ActiveMQDestination.QUEUE_TYPE),}); + addCombinationValues("destinationType", new Object[] {Byte.valueOf(ActiveMQDestination.QUEUE_TYPE)}); } public void testMessageListenerUnackedWithPrefetch1StayInQueue() throws Exception { @@ -438,7 +438,7 @@ public class JMSConsumerTest extends JmsTestSupport { addCombinationValues("ackMode", new Object[] {Integer.valueOf(Session.AUTO_ACKNOWLEDGE), Integer.valueOf(Session.DUPS_OK_ACKNOWLEDGE), Integer.valueOf(Session.CLIENT_ACKNOWLEDGE)}); - addCombinationValues("destinationType", new Object[] {Byte.valueOf(ActiveMQDestination.QUEUE_TYPE),}); + addCombinationValues("destinationType", new Object[] {Byte.valueOf(ActiveMQDestination.QUEUE_TYPE)}); } public void testUnackedWithPrefetch1StayInQueue() throws Exception { @@ -528,9 +528,9 @@ public class JMSConsumerTest extends JmsTestSupport { } public void initCombosForTestDontStart() { - addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT),}); + addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT)}); addCombinationValues("destinationType", new Object[] {Byte.valueOf(ActiveMQDestination.QUEUE_TYPE), - Byte.valueOf(ActiveMQDestination.TOPIC_TYPE),}); + Byte.valueOf(ActiveMQDestination.TOPIC_TYPE)}); } public void testDontStart() throws Exception { @@ -547,9 +547,9 @@ public class JMSConsumerTest extends JmsTestSupport { } public void initCombosForTestStartAfterSend() { - addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT),}); + addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT)}); addCombinationValues("destinationType", new Object[] {Byte.valueOf(ActiveMQDestination.QUEUE_TYPE), - Byte.valueOf(ActiveMQDestination.TOPIC_TYPE),}); + Byte.valueOf(ActiveMQDestination.TOPIC_TYPE)}); } public void testStartAfterSend() throws Exception { diff --git a/activemq-core/src/test/java/org/apache/activemq/JMSDurableTopicRedeliverTest.java b/activemq-core/src/test/java/org/apache/activemq/JMSDurableTopicRedeliverTest.java index c0fdb3d8c2..ef1eddf187 100755 --- a/activemq-core/src/test/java/org/apache/activemq/JMSDurableTopicRedeliverTest.java +++ b/activemq-core/src/test/java/org/apache/activemq/JMSDurableTopicRedeliverTest.java @@ -24,22 +24,21 @@ import javax.jms.TextMessage; * @version $Revision: 1.4 $ */ public class JMSDurableTopicRedeliverTest extends JmsTopicRedeliverTest { - - private static final org.apache.commons.logging.Log log = org.apache.commons.logging.LogFactory - .getLog(JMSDurableTopicRedeliverTest.class); - + + private static final org.apache.commons.logging.Log log = org.apache.commons.logging.LogFactory.getLog(JMSDurableTopicRedeliverTest.class); + protected void setUp() throws Exception { durable = true; super.setUp(); } - + /** * Sends and consumes the messages. - * + * * @throws Exception */ public void testRedeliverNewSession() throws Exception { - String text = "TEST: "+System.currentTimeMillis(); + String text = "TEST: " + System.currentTimeMillis(); Message sendMessage = session.createTextMessage(text); if (verbose) { @@ -47,26 +46,26 @@ public class JMSDurableTopicRedeliverTest extends JmsTopicRedeliverTest { } producer.send(producerDestination, sendMessage); - //receive but don't acknowledge + // receive but don't acknowledge Message unackMessage = consumer.receive(1000); assertNotNull(unackMessage); String unackId = unackMessage.getJMSMessageID(); - assertEquals(((TextMessage) unackMessage).getText(), text); + assertEquals(((TextMessage)unackMessage).getText(), text); assertFalse(unackMessage.getJMSRedelivered()); - assertEquals(unackMessage.getIntProperty("JMSXDeliveryCount"),1); + assertEquals(unackMessage.getIntProperty("JMSXDeliveryCount"), 1); consumeSession.close(); consumer.close(); - //receive then acknowledge + // receive then acknowledge consumeSession = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); consumer = createConsumer(); Message ackMessage = consumer.receive(1000); assertNotNull(ackMessage); ackMessage.acknowledge(); String ackId = ackMessage.getJMSMessageID(); - assertEquals(((TextMessage) ackMessage).getText(), text); + assertEquals(((TextMessage)ackMessage).getText(), text); assertTrue(ackMessage.getJMSRedelivered()); - assertEquals(ackMessage.getIntProperty("JMSXDeliveryCount"),2); + assertEquals(ackMessage.getIntProperty("JMSXDeliveryCount"), 2); assertEquals(unackId, ackId); consumeSession.close(); consumer.close(); diff --git a/activemq-core/src/test/java/org/apache/activemq/JMSExclusiveConsumerTest.java b/activemq-core/src/test/java/org/apache/activemq/JMSExclusiveConsumerTest.java index 4a0498749f..f4ce875aa3 100644 --- a/activemq-core/src/test/java/org/apache/activemq/JMSExclusiveConsumerTest.java +++ b/activemq-core/src/test/java/org/apache/activemq/JMSExclusiveConsumerTest.java @@ -42,14 +42,14 @@ public class JMSExclusiveConsumerTest extends JmsTestSupport { } public int deliveryMode; - + public void initCombosForTestRoundRobinDispatchOnNonExclusive() { - addCombinationValues("deliveryMode", new Object[] { Integer.valueOf(DeliveryMode.NON_PERSISTENT), - Integer.valueOf(DeliveryMode.PERSISTENT) }); + addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); } /** - * Shows that by default messages are round robined across a set of consumers. + * Shows that by default messages are round robined across a set of + * consumers. * * @throws Exception */ @@ -61,18 +61,18 @@ public class JMSExclusiveConsumerTest extends JmsTestSupport { ActiveMQQueue destination = new ActiveMQQueue("TEST"); MessageProducer producer = session.createProducer(destination); producer.setDeliveryMode(deliveryMode); - + MessageConsumer consumer1 = session.createConsumer(destination); MessageConsumer consumer2 = session.createConsumer(destination); // Send the messages producer.send(session.createTextMessage("1st")); producer.send(session.createTextMessage("2nd")); - + Message m; m = consumer2.receive(1000); assertNotNull(m); - + m = consumer1.receive(1000); assertNotNull(m); @@ -81,13 +81,12 @@ public class JMSExclusiveConsumerTest extends JmsTestSupport { } public void initCombosForTestDispatchExclusive() { - addCombinationValues("deliveryMode", new Object[] { Integer.valueOf(DeliveryMode.NON_PERSISTENT), - Integer.valueOf(DeliveryMode.PERSISTENT) }); + addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); } /** - * Shows that if the "?consumer.exclusive=true" option is added to destination, - * then all messages are routed to 1 consumer. + * Shows that if the "?consumer.exclusive=true" option is added to + * destination, then all messages are routed to 1 consumer. * * @throws Exception */ @@ -99,7 +98,7 @@ public class JMSExclusiveConsumerTest extends JmsTestSupport { ActiveMQQueue destination = new ActiveMQQueue("TEST?consumer.exclusive=true"); MessageProducer producer = session.createProducer(destination); producer.setDeliveryMode(deliveryMode); - + MessageConsumer consumer1 = session.createConsumer(destination); MessageConsumer consumer2 = session.createConsumer(destination); @@ -107,10 +106,10 @@ public class JMSExclusiveConsumerTest extends JmsTestSupport { producer.send(session.createTextMessage("1st")); producer.send(session.createTextMessage("2nd")); producer.send(session.createTextMessage("3nd")); - + Message m; m = consumer2.receive(1000); - if( m!=null ) { + if (m != null) { // Consumer 2 should get all the messages. for (int i = 0; i < 2; i++) { m = consumer2.receive(1000); @@ -138,14 +137,13 @@ public class JMSExclusiveConsumerTest extends JmsTestSupport { MessageConsumer nonExCon = session.createConsumer(nonExclusiveQueue); MessageConsumer exCon = session.createConsumer(exclusiveQueue); - MessageProducer prod = session.createProducer(exclusiveQueue); prod.send(session.createMessage()); prod.send(session.createMessage()); prod.send(session.createMessage()); Message m; - for (int i=0; i<3; i++) { + for (int i = 0; i < 3; i++) { m = exCon.receive(1000); assertNotNull(m); m = nonExCon.receive(1000); diff --git a/activemq-core/src/test/java/org/apache/activemq/JMSUsecaseTest.java b/activemq-core/src/test/java/org/apache/activemq/JMSUsecaseTest.java index c90d8f61c3..e682d689aa 100755 --- a/activemq-core/src/test/java/org/apache/activemq/JMSUsecaseTest.java +++ b/activemq-core/src/test/java/org/apache/activemq/JMSUsecaseTest.java @@ -36,7 +36,8 @@ public class JMSUsecaseTest extends JmsTestSupport { public static Test suite() { return suite(JMSUsecaseTest.class); - } + } + public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } @@ -47,46 +48,37 @@ public class JMSUsecaseTest extends JmsTestSupport { public byte destinationType; public boolean durableConsumer; - public void initCombosForTestQueueBrowser() { - 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.TEMP_QUEUE_TYPE), - } ); - } + public void initCombosForTestQueueBrowser() { + 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.TEMP_QUEUE_TYPE)}); + } + public void testQueueBrowser() throws Exception { - + // Send a message to the broker. connection.start(); Session session = connection.createSession(false, Session.SESSION_TRANSACTED); destination = createDestination(session, destinationType); sendMessages(session, destination, 5); - - QueueBrowser browser = session.createBrowser((Queue) destination); + QueueBrowser browser = session.createBrowser((Queue)destination); Enumeration enumeration = browser.getEnumeration(); - for(int i=0; i < 5; i++) { + for (int i = 0; i < 5; i++) { Thread.sleep(100); assertTrue(enumeration.hasMoreElements()); Message m = (Message)enumeration.nextElement(); assertNotNull(m); - assertEquals(""+i, ((TextMessage)m).getText()); + assertEquals("" + i, ((TextMessage)m).getText()); } assertFalse(enumeration.hasMoreElements()); } - public void initCombosForTestSendReceive() { - 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 initCombosForTestSendReceive() { + 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 testSendReceive() throws Exception { // Send a message to the broker. connection.start(); @@ -96,22 +88,18 @@ public class JMSUsecaseTest extends JmsTestSupport { MessageConsumer consumer = session.createConsumer(destination); ActiveMQMessage message = new ActiveMQMessage(); producer.send(message); - + // Make sure only 1 message was delivered. assertNotNull(consumer.receive(1000)); - assertNull(consumer.receiveNoWait()); + assertNull(consumer.receiveNoWait()); + } + + public void initCombosForTestSendReceiveTransacted() { + 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 initCombosForTestSendReceiveTransacted() { - 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 testSendReceiveTransacted() throws Exception { // Send a message to the broker. connection.start(); @@ -120,28 +108,28 @@ public class JMSUsecaseTest extends JmsTestSupport { MessageProducer producer = session.createProducer(destination); MessageConsumer consumer = session.createConsumer(destination); producer.send(session.createTextMessage("test")); - + // Message should not be delivered until commit. - assertNull(consumer.receiveNoWait()); + assertNull(consumer.receiveNoWait()); session.commit(); - + // Make sure only 1 message was delivered. Message message = consumer.receive(1000); assertNotNull(message); assertFalse(message.getJMSRedelivered()); assertNull(consumer.receiveNoWait()); - + // Message should be redelivered is rollback is used. session.rollback(); - + // Make sure only 1 message was delivered. message = consumer.receive(2000); assertNotNull(message); assertTrue(message.getJMSRedelivered()); assertNull(consumer.receiveNoWait()); - + // If we commit now, the message should not be redelivered. - session.commit(); + session.commit(); assertNull(consumer.receiveNoWait()); } diff --git a/activemq-core/src/test/java/org/apache/activemq/JmsAutoAckListenerTest.java b/activemq-core/src/test/java/org/apache/activemq/JmsAutoAckListenerTest.java index d9f403a394..4467945848 100755 --- a/activemq-core/src/test/java/org/apache/activemq/JmsAutoAckListenerTest.java +++ b/activemq-core/src/test/java/org/apache/activemq/JmsAutoAckListenerTest.java @@ -27,7 +27,7 @@ import javax.jms.Session; /** * @version $Revision: 1.2 $ */ -public class JmsAutoAckListenerTest extends TestSupport implements MessageListener{ +public class JmsAutoAckListenerTest extends TestSupport implements MessageListener { private Connection connection; @@ -46,7 +46,7 @@ public class JmsAutoAckListenerTest extends TestSupport implements MessageListen } super.tearDown(); } - + /** * Tests if acknowleged messages are being consumed. * @@ -70,14 +70,11 @@ public class JmsAutoAckListenerTest extends TestSupport implements MessageListen Message msg = consumer.receive(1000); assertNull(msg); - session.close(); - } + } - - public void onMessage(Message message){ + public void onMessage(Message message) { assertNotNull(message); - - } + } } diff --git a/activemq-core/src/test/java/org/apache/activemq/JmsBenchmark.java b/activemq-core/src/test/java/org/apache/activemq/JmsBenchmark.java index d85c5ccd18..58296a0ee5 100755 --- a/activemq-core/src/test/java/org/apache/activemq/JmsBenchmark.java +++ b/activemq-core/src/test/java/org/apache/activemq/JmsBenchmark.java @@ -47,21 +47,18 @@ import org.apache.commons.logging.LogFactory; /** * Benchmarks the broker by starting many consumer and producers against the - * same destination. - * - * Make sure you run with jvm option -server (makes a big difference). The tests - * simulate storing 1000 1k jms messages to see the rate of processing msg/sec. + * same destination. Make sure you run with jvm option -server (makes a big + * difference). The tests simulate storing 1000 1k jms messages to see the rate + * of processing msg/sec. * * @version $Revision$ */ public class JmsBenchmark extends JmsTestSupport { private static final transient Log log = LogFactory.getLog(JmsBenchmark.class); - private static final long SAMPLE_DELAY = Integer.parseInt(System.getProperty("SAMPLE_DELAY", - "" + 1000 * 5)); + private static final long SAMPLE_DELAY = Integer.parseInt(System.getProperty("SAMPLE_DELAY", "" + 1000 * 5)); private static final long SAMPLES = Integer.parseInt(System.getProperty("SAMPLES", "10")); - private static final long SAMPLE_DURATION = Integer.parseInt(System.getProperty("SAMPLES_DURATION", - "" + 1000 * 60)); + private static final long SAMPLE_DURATION = Integer.parseInt(System.getProperty("SAMPLES_DURATION", "" + 1000 * 60)); private static final int PRODUCER_COUNT = Integer.parseInt(System.getProperty("PRODUCER_COUNT", "10")); private static final int CONSUMER_COUNT = Integer.parseInt(System.getProperty("CONSUMER_COUNT", "10")); @@ -76,9 +73,7 @@ public class JmsBenchmark extends JmsTestSupport { } public void initCombos() { - addCombinationValues("destination", new Object[] { - // new ActiveMQTopic("TEST"), - new ActiveMQQueue("TEST"),}); + addCombinationValues("destination", new Object[] {new ActiveMQQueue("TEST")}); } protected BrokerService createBroker() throws Exception { @@ -86,8 +81,7 @@ public class JmsBenchmark extends JmsTestSupport { } protected ConnectionFactory createConnectionFactory() throws URISyntaxException, IOException { - return new ActiveMQConnectionFactory(((TransportConnector)broker.getTransportConnectors().get(0)) - .getServer().getConnectURI()); + return new ActiveMQConnectionFactory(((TransportConnector)broker.getTransportConnectors().get(0)).getServer().getConnectURI()); } /** @@ -177,8 +171,7 @@ public class JmsBenchmark extends JmsTestSupport { log.info(getName() + ": Waiting for Producers and Consumers to startup."); connectionsEstablished.acquire(); - log.info("Producers and Consumers are now running. Waiting for system to reach steady state: " - + (SAMPLE_DELAY / 1000.0f) + " seconds"); + log.info("Producers and Consumers are now running. Waiting for system to reach steady state: " + (SAMPLE_DELAY / 1000.0f) + " seconds"); Thread.sleep(1000 * 10); log.info("Starting sample: " + SAMPLES + " each lasting " + (SAMPLE_DURATION / 1000.0f) + " seconds"); @@ -196,8 +189,7 @@ public class JmsBenchmark extends JmsTestSupport { int r = receivedMessages.get(); int 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"); + log.info("published: " + p + " msgs at " + (p * 1000f / (end - start)) + " msgs/sec, " + "consumed: " + r + " msgs at " + (r * 1000f / (end - start)) + " msgs/sec"); } log.info("Sample done."); diff --git a/activemq-core/src/test/java/org/apache/activemq/JmsDurableTopicSelectorTest.java b/activemq-core/src/test/java/org/apache/activemq/JmsDurableTopicSelectorTest.java index 82afe59802..bfa345226a 100755 --- a/activemq-core/src/test/java/org/apache/activemq/JmsDurableTopicSelectorTest.java +++ b/activemq-core/src/test/java/org/apache/activemq/JmsDurableTopicSelectorTest.java @@ -21,7 +21,7 @@ package org.apache.activemq; */ public class JmsDurableTopicSelectorTest extends JmsTopicSelectorTest { public void setUp() throws Exception { - durable=true; + durable = true; super.setUp(); } } diff --git a/activemq-core/src/test/java/org/apache/activemq/JmsDurableTopicSendReceiveTest.java b/activemq-core/src/test/java/org/apache/activemq/JmsDurableTopicSendReceiveTest.java index b401a17fdc..d83d57b20b 100755 --- a/activemq-core/src/test/java/org/apache/activemq/JmsDurableTopicSendReceiveTest.java +++ b/activemq-core/src/test/java/org/apache/activemq/JmsDurableTopicSendReceiveTest.java @@ -31,9 +31,8 @@ import org.apache.activemq.test.JmsTopicSendReceiveTest; * @version $Revision: 1.5 $ */ public class JmsDurableTopicSendReceiveTest extends JmsTopicSendReceiveTest { - private static final org.apache.commons.logging.Log log = org.apache.commons.logging.LogFactory - .getLog(JmsDurableTopicSendReceiveTest.class); - + private static final org.apache.commons.logging.Log log = org.apache.commons.logging.LogFactory.getLog(JmsDurableTopicSendReceiveTest.class); + protected Connection connection2; protected Session session2; protected Session consumeSession2; @@ -41,9 +40,10 @@ public class JmsDurableTopicSendReceiveTest extends JmsTopicSendReceiveTest { protected MessageProducer producer2; protected Destination consumerDestination2; protected Destination producerDestination2; + /** * Set up a durable suscriber test. - * + * * @see junit.framework.TestCase#setUp() */ protected void setUp() throws Exception { @@ -53,7 +53,7 @@ public class JmsDurableTopicSendReceiveTest extends JmsTopicSendReceiveTest { /** * Test if all the messages sent are being received. - * + * * @throws Exception */ public void testSendWhileClosed() throws Exception { @@ -63,23 +63,23 @@ public class JmsDurableTopicSendReceiveTest extends JmsTopicSendReceiveTest { session2 = connection2.createSession(false, Session.AUTO_ACKNOWLEDGE); producer2 = session2.createProducer(null); producer2.setDeliveryMode(deliveryMode); - producerDestination2 = session2.createTopic(getProducerSubject()+"2"); + producerDestination2 = session2.createTopic(getProducerSubject() + "2"); Thread.sleep(1000); consumeSession2 = connection2.createSession(false, Session.AUTO_ACKNOWLEDGE); - consumerDestination2 = session2.createTopic(getConsumerSubject()+"2"); + consumerDestination2 = session2.createTopic(getConsumerSubject() + "2"); consumer2 = consumeSession2.createDurableSubscriber((Topic)consumerDestination2, getName()); Thread.sleep(1000); consumer2.close(); TextMessage message = session2.createTextMessage("test"); - message.setStringProperty("test","test"); + message.setStringProperty("test", "test"); message.setJMSType("test"); producer2.send(producerDestination2, message); log.info("Creating durable consumer"); consumer2 = consumeSession2.createDurableSubscriber((Topic)consumerDestination2, getName()); Message msg = consumer2.receive(1000); assertNotNull(msg); - assertEquals(((TextMessage) msg).getText(), "test"); + assertEquals(((TextMessage)msg).getText(), "test"); assertEquals(msg.getJMSType(), "test"); assertEquals(msg.getStringProperty("test"), "test"); connection2.stop(); diff --git a/activemq-core/src/test/java/org/apache/activemq/JmsQueueSelectorTest.java b/activemq-core/src/test/java/org/apache/activemq/JmsQueueSelectorTest.java index 8a2a648f97..c2debdc3bd 100755 --- a/activemq-core/src/test/java/org/apache/activemq/JmsQueueSelectorTest.java +++ b/activemq-core/src/test/java/org/apache/activemq/JmsQueueSelectorTest.java @@ -22,7 +22,7 @@ package org.apache.activemq; */ public class JmsQueueSelectorTest extends JmsTopicSelectorTest { public void setUp() throws Exception { - topic=false; + topic = false; super.setUp(); } } diff --git a/activemq-core/src/test/java/org/apache/activemq/JmsQueueTransactionTest.java b/activemq-core/src/test/java/org/apache/activemq/JmsQueueTransactionTest.java index 3878697385..8797b2db93 100755 --- a/activemq-core/src/test/java/org/apache/activemq/JmsQueueTransactionTest.java +++ b/activemq-core/src/test/java/org/apache/activemq/JmsQueueTransactionTest.java @@ -29,34 +29,29 @@ import javax.jms.TextMessage; import org.apache.activemq.test.JmsResourceProvider; - /** * @version $Revision: 1.2 $ */ public class JmsQueueTransactionTest extends JmsTransactionTestSupport { - private static final org.apache.commons.logging.Log log = org.apache.commons.logging.LogFactory - .getLog(JmsQueueTransactionTest.class); - - /** - * - * @see org.apache.activemq.JmsTransactionTestSupport#getJmsResourceProvider() - */ - protected JmsResourceProvider getJmsResourceProvider() { - JmsResourceProvider p = new JmsResourceProvider(); - p.setTopic(false); - return p; - } + private static final org.apache.commons.logging.Log log = org.apache.commons.logging.LogFactory.getLog(JmsQueueTransactionTest.class); /** - * Tests if the the connection gets reset, the messages will still be received. - * + * @see org.apache.activemq.JmsTransactionTestSupport#getJmsResourceProvider() + */ + protected JmsResourceProvider getJmsResourceProvider() { + JmsResourceProvider p = new JmsResourceProvider(); + p.setTopic(false); + return p; + } + + /** + * Tests if the the connection gets reset, the messages will still be + * received. + * * @throws Exception */ public void testReceiveTwoThenCloseConnection() throws Exception { - Message[] outbound = new Message[]{ - session.createTextMessage("First Message"), - session.createTextMessage("Second Message") - }; + Message[] outbound = new Message[] {session.createTextMessage("First Message"), session.createTextMessage("Second Message")}; // lets consume any outstanding messages from previous test runs while (consumer.receive(1000) != null) { @@ -77,10 +72,10 @@ public class JmsQueueTransactionTest extends JmsTransactionTestSupport { message = consumer.receive(1000); assertNotNull(message); assertEquals(outbound[1], message); - + // Close and reopen connection. - reconnect(); - + reconnect(); + // Consume again.. the previous message should // get redelivered. message = consumer.receive(5000); @@ -99,52 +94,53 @@ public class JmsQueueTransactionTest extends JmsTransactionTestSupport { assertTextMessagesEqual("Rollback did not work", outbound, inbound); } - + /** - * Tests sending and receiving messages with two sessions(one for producing and another for consuming). + * Tests sending and receiving messages with two sessions(one for producing + * and another for consuming). * * @throws Exception */ public void testSendReceiveInSeperateSessionTest() throws Exception { - session.close(); + session.close(); int batchCount = 10; - for (int i=0; i < batchCount; i++) { - //Session that sends messages + for (int i = 0; i < batchCount; i++) { + // Session that sends messages { Session session = resourceProvider.createSession(connection); MessageProducer producer = resourceProvider.createProducer(session, destination); - //consumer = resourceProvider.createConsumer(session, destination); - producer.send(session.createTextMessage("Test Message: "+i)); + // consumer = resourceProvider.createConsumer(session, + // destination); + producer.send(session.createTextMessage("Test Message: " + i)); session.commit(); session.close(); } - - //Session that consumes messages + + // Session that consumes messages { Session session = resourceProvider.createSession(connection); MessageConsumer consumer = resourceProvider.createConsumer(session, destination); - TextMessage message = (TextMessage) consumer.receive(1000*5); - assertNotNull("Received only "+i+" messages in batch ", message); - assertEquals("Test Message: "+i, message.getText()); + TextMessage message = (TextMessage)consumer.receive(1000 * 5); + assertNotNull("Received only " + i + " messages in batch ", message); + assertEquals("Test Message: " + i, message.getText()); session.commit(); session.close(); } } } - + /** - * Tests the queue browser. Browses the messages then the consumer tries to receive them. - * The messages should still be in the queue even when it was browsed. + * Tests the queue browser. Browses the messages then the consumer tries to + * receive them. The messages should still be in the queue even when it was + * browsed. * * @throws Exception */ public void testReceiveBrowseReceive() throws Exception { - Message[] outbound = new Message[] { session.createTextMessage("First Message"), - session.createTextMessage("Second Message"), - session.createTextMessage("Third Message") }; + Message[] outbound = new Message[] {session.createTextMessage("First Message"), session.createTextMessage("Second Message"), session.createTextMessage("Third Message")}; // lets consume any outstanding messages from previous test runs while (consumer.receive(1000) != null) { @@ -160,21 +156,21 @@ public class JmsQueueTransactionTest extends JmsTransactionTestSupport { assertEquals(outbound[0], consumer.receive(1000)); consumer.close(); - QueueBrowser browser = session.createBrowser((Queue) destination); + QueueBrowser browser = session.createBrowser((Queue)destination); Enumeration enumeration = browser.getEnumeration(); // browse the second assertTrue("should have received the second message", enumeration.hasMoreElements()); - assertEquals(outbound[1], (Message) enumeration.nextElement()); + assertEquals(outbound[1], (Message)enumeration.nextElement()); // browse the third. assertTrue("Should have received the third message", enumeration.hasMoreElements()); - assertEquals(outbound[2], (Message) enumeration.nextElement()); + assertEquals(outbound[2], (Message)enumeration.nextElement()); // There should be no more. boolean tooMany = false; while (enumeration.hasMoreElements()) { - log.info("Got extra message: " + ((TextMessage) enumeration.nextElement()).getText()); + log.info("Got extra message: " + ((TextMessage)enumeration.nextElement()).getText()); tooMany = true; } assertFalse(tooMany); @@ -190,5 +186,5 @@ public class JmsQueueTransactionTest extends JmsTransactionTestSupport { session.commit(); } - + } diff --git a/activemq-core/src/test/java/org/apache/activemq/JmsQueueWildcardSendReceiveTest.java b/activemq-core/src/test/java/org/apache/activemq/JmsQueueWildcardSendReceiveTest.java index 44385f7af0..57ffe72c8a 100755 --- a/activemq-core/src/test/java/org/apache/activemq/JmsQueueWildcardSendReceiveTest.java +++ b/activemq-core/src/test/java/org/apache/activemq/JmsQueueWildcardSendReceiveTest.java @@ -28,19 +28,18 @@ import javax.jms.MessageProducer; import org.apache.activemq.command.ActiveMQDestination; import org.apache.activemq.test.JmsTopicSendReceiveTest; - /** * @version $Revision: 1.4 $ */ public class JmsQueueWildcardSendReceiveTest extends JmsTopicSendReceiveTest { - private String destination1String = "TEST.ONE.ONE" ; - private String destination2String = "TEST.ONE.ONE.ONE" ; - private String destination3String = "TEST.ONE.TWO" ; - private String destination4String = "TEST.TWO.ONE" ; + private String destination1String = "TEST.ONE.ONE"; + private String destination2String = "TEST.ONE.ONE.ONE"; + private String destination3String = "TEST.ONE.TWO"; + private String destination4String = "TEST.TWO.ONE"; /** - * Sets a test to have a queue destination and non-persistent delivery mode. + * Sets a test to have a queue destination and non-persistent delivery mode. * * @see junit.framework.TestCase#setUp() */ @@ -49,24 +48,24 @@ public class JmsQueueWildcardSendReceiveTest extends JmsTopicSendReceiveTest { deliveryMode = DeliveryMode.NON_PERSISTENT; super.setUp(); } - + /** * Returns the consumer subject. * * @return String - consumer subject * @see org.apache.activemq.test.TestSupport#getConsumerSubject() */ - protected String getConsumerSubject(){ + protected String getConsumerSubject() { return "FOO.>"; } - + /** * Returns the producer subject. * * @return String - producer subject * @see org.apache.activemq.test.TestSupport#getProducerSubject() */ - protected String getProducerSubject(){ + protected String getProducerSubject() { return "FOO.BAR.HUMBUG"; } @@ -74,27 +73,27 @@ public class JmsQueueWildcardSendReceiveTest extends JmsTopicSendReceiveTest { connection.start(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - ActiveMQDestination destination1 = (ActiveMQDestination) session.createQueue(destination1String); - ActiveMQDestination destination3 = (ActiveMQDestination) session.createQueue(destination3String); + ActiveMQDestination destination1 = (ActiveMQDestination)session.createQueue(destination1String); + ActiveMQDestination destination3 = (ActiveMQDestination)session.createQueue(destination3String); Message m = null; MessageConsumer consumer = null; String text = null; - sendMessage(session,destination1,destination1String); - sendMessage(session,destination3,destination3String); - ActiveMQDestination destination6 = (ActiveMQDestination) session.createQueue("TEST.ONE.*"); + sendMessage(session, destination1, destination1String); + sendMessage(session, destination3, destination3String); + ActiveMQDestination destination6 = (ActiveMQDestination)session.createQueue("TEST.ONE.*"); consumer = session.createConsumer(destination6); m = consumer.receive(1000); assertNotNull(m); text = ((TextMessage)m).getText(); - if(!(text.equals(destination1String) || text.equals(destination3String))) { + if (!(text.equals(destination1String) || text.equals(destination3String))) { fail("unexpected message:" + text); } m = consumer.receive(1000); assertNotNull(m); text = ((TextMessage)m).getText(); - if(!(text.equals(destination1String) || text.equals(destination3String))) { + if (!(text.equals(destination1String) || text.equals(destination3String))) { fail("unexpected message:" + text); } assertNull(consumer.receiveNoWait()); @@ -104,33 +103,33 @@ public class JmsQueueWildcardSendReceiveTest extends JmsTopicSendReceiveTest { connection.start(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - ActiveMQDestination destination1 = (ActiveMQDestination) session.createQueue(destination1String); - ActiveMQDestination destination2 = (ActiveMQDestination) session.createQueue(destination2String); - ActiveMQDestination destination3 = (ActiveMQDestination) session.createQueue(destination3String); + ActiveMQDestination destination1 = (ActiveMQDestination)session.createQueue(destination1String); + ActiveMQDestination destination2 = (ActiveMQDestination)session.createQueue(destination2String); + ActiveMQDestination destination3 = (ActiveMQDestination)session.createQueue(destination3String); Message m = null; MessageConsumer consumer = null; String text = null; - sendMessage(session,destination1,destination1String); - sendMessage(session,destination2,destination2String); - sendMessage(session,destination3,destination3String); - ActiveMQDestination destination7 = (ActiveMQDestination) session.createQueue("TEST.ONE.>"); + sendMessage(session, destination1, destination1String); + sendMessage(session, destination2, destination2String); + sendMessage(session, destination3, destination3String); + ActiveMQDestination destination7 = (ActiveMQDestination)session.createQueue("TEST.ONE.>"); consumer = session.createConsumer(destination7); m = consumer.receive(1000); assertNotNull(m); text = ((TextMessage)m).getText(); - if(!(text.equals(destination1String) || text.equals(destination2String) || text.equals(destination3String))) { + if (!(text.equals(destination1String) || text.equals(destination2String) || text.equals(destination3String))) { fail("unexpected message:" + text); } m = consumer.receive(1000); assertNotNull(m); - if(!(text.equals(destination1String) || text.equals(destination2String) || text.equals(destination3String))) { + if (!(text.equals(destination1String) || text.equals(destination2String) || text.equals(destination3String))) { fail("unexpected message:" + text); } m = consumer.receive(1000); assertNotNull(m); - if(!(text.equals(destination1String) || text.equals(destination2String) || text.equals(destination3String))) { + if (!(text.equals(destination1String) || text.equals(destination2String) || text.equals(destination3String))) { fail("unexpected message:" + text); } assertNull(consumer.receiveNoWait()); @@ -140,27 +139,27 @@ public class JmsQueueWildcardSendReceiveTest extends JmsTopicSendReceiveTest { connection.start(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - ActiveMQDestination destination1 = (ActiveMQDestination) session.createQueue(destination1String); - ActiveMQDestination destination4 = (ActiveMQDestination) session.createQueue(destination4String); + ActiveMQDestination destination1 = (ActiveMQDestination)session.createQueue(destination1String); + ActiveMQDestination destination4 = (ActiveMQDestination)session.createQueue(destination4String); Message m = null; MessageConsumer consumer = null; String text = null; - sendMessage(session,destination1,destination1String); - sendMessage(session,destination4,destination4String); - ActiveMQDestination destination8 = (ActiveMQDestination) session.createQueue("TEST.*.ONE"); + sendMessage(session, destination1, destination1String); + sendMessage(session, destination4, destination4String); + ActiveMQDestination destination8 = (ActiveMQDestination)session.createQueue("TEST.*.ONE"); consumer = session.createConsumer(destination8); m = consumer.receive(1000); assertNotNull(m); text = ((TextMessage)m).getText(); - if(!(text.equals(destination1String) || text.equals(destination4String))) { + if (!(text.equals(destination1String) || text.equals(destination4String))) { fail("unexpected message:" + text); } m = consumer.receive(1000); assertNotNull(m); text = ((TextMessage)m).getText(); - if(!(text.equals(destination1String) || text.equals(destination4String))) { + if (!(text.equals(destination1String) || text.equals(destination4String))) { fail("unexpected message:" + text); } assertNull(consumer.receiveNoWait()); diff --git a/activemq-core/src/test/java/org/apache/activemq/JmsTempDestinationTest.java b/activemq-core/src/test/java/org/apache/activemq/JmsTempDestinationTest.java index e06f8324f5..929f350238 100755 --- a/activemq-core/src/test/java/org/apache/activemq/JmsTempDestinationTest.java +++ b/activemq-core/src/test/java/org/apache/activemq/JmsTempDestinationTest.java @@ -56,10 +56,9 @@ public class JmsTempDestinationTest extends TestCase { } } - /** * Make sure Temp destination can only be consumed by local connection - * + * * @throws JMSException */ public void testTempDestOnlyConsumedByLocalConn() throws JMSException { @@ -72,7 +71,7 @@ public class JmsTempDestinationTest extends TestCase { TextMessage message = tempSession.createTextMessage("First"); producer.send(message); - //temp destination should not be consume when using another connection + // temp destination should not be consume when using another connection Connection otherConnection = factory.createConnection(); Session otherSession = otherConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); TemporaryQueue otherQueue = otherSession.createTemporaryQueue(); @@ -80,21 +79,20 @@ public class JmsTempDestinationTest extends TestCase { Message msg = consumer.receive(3000); assertNull(msg); - //should throw InvalidDestinationException when consuming a temp destination from another connection - try{ - consumer = otherSession.createConsumer(queue); - fail("Send should fail since temp destination should be used from another connection"); - }catch(InvalidDestinationException e){ - assertTrue("failed to throw an exception",true); + // should throw InvalidDestinationException when consuming a temp + // destination from another connection + try { + consumer = otherSession.createConsumer(queue); + fail("Send should fail since temp destination should be used from another connection"); + } catch (InvalidDestinationException e) { + assertTrue("failed to throw an exception", true); } - - //should be able to consume temp destination from the same connection + // should be able to consume temp destination from the same connection consumer = tempSession.createConsumer(queue); msg = consumer.receive(3000); assertNotNull(msg); - } /** @@ -117,8 +115,7 @@ public class JmsTempDestinationTest extends TestCase { Message message2 = consumer.receive(1000); assertNotNull(message2); assertTrue("Expected message to be a TextMessage", message2 instanceof TextMessage); - assertTrue("Expected message to be a '" + message.getText() + "'", - ((TextMessage) message2).getText().equals(message.getText())); + assertTrue("Expected message to be a '" + message.getText() + "'", ((TextMessage)message2).getText().equals(message.getText())); } /** @@ -141,95 +138,100 @@ public class JmsTempDestinationTest extends TestCase { Message message2 = consumer.receive(3000); assertNotNull(message2); assertTrue("Expected message to be a TextMessage", message2 instanceof TextMessage); - assertTrue("Expected message to be a '" + message.getText() + "'", - ((TextMessage) message2).getText().equals(message.getText())); + assertTrue("Expected message to be a '" + message.getText() + "'", ((TextMessage)message2).getText().equals(message.getText())); } - + /** * Test temp queue works under load + * * @throws JMSException */ public void testTmpQueueWorksUnderLoad() throws JMSException { int count = 500; int dataSize = 1024; - + ArrayList list = new ArrayList(count); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); Queue queue = session.createTemporaryQueue(); MessageProducer producer = session.createProducer(queue); producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); - + byte[] data = new byte[dataSize]; - for (int i =0; i < count; i++){ + for (int i = 0; i < count; i++) { BytesMessage message = session.createBytesMessage(); message.writeBytes(data); producer.send(message); list.add(message); } - connection.start(); MessageConsumer consumer = session.createConsumer(queue); - for (int i =0; i < count; i++){ + for (int i = 0; i < count; i++) { Message message2 = consumer.receive(2000); - + assertTrue(message2 != null); assertTrue(message2.equals(list.get(i))); } } - + /** - * Make sure you cannot publish to a temp destination that does not exist anymore. + * Make sure you cannot publish to a temp destination that does not exist + * anymore. * * @throws JMSException - * @throws InterruptedException + * @throws InterruptedException */ public void testPublishFailsForClosedConnection() throws JMSException, InterruptedException { - + Connection tempConnection = factory.createConnection(); - Session tempSession = tempConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); + Session tempSession = tempConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); TemporaryQueue queue = tempSession.createTemporaryQueue(); - + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - connection.start(); - - // This message delivery should work since the temp connection is still open. + connection.start(); + + // This message delivery should work since the temp connection is still + // open. MessageProducer producer = session.createProducer(queue); producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); TextMessage message = session.createTextMessage("First"); producer.send(message); - // Closing the connection should destroy the temp queue that was created. + // Closing the connection should destroy the temp queue that was + // created. tempConnection.close(); Thread.sleep(1000); // Wait a little bit to let the delete take effect. - - // This message delivery NOT should work since the temp connection is now closed. + + // This message delivery NOT should work since the temp connection is + // now closed. try { message = session.createTextMessage("Hello"); producer.send(message); fail("Send should fail since temp destination should not exist anymore."); - } catch ( JMSException e ) { - assertTrue("failed to throw an exception",true); + } catch (JMSException e) { + assertTrue("failed to throw an exception", true); } } - + /** - * Make sure you cannot publish to a temp destination that does not exist anymore. + * Make sure you cannot publish to a temp destination that does not exist + * anymore. * * @throws JMSException - * @throws InterruptedException + * @throws InterruptedException */ public void testPublishFailsForDestoryedTempDestination() throws JMSException, InterruptedException { - + Connection tempConnection = factory.createConnection(); - Session tempSession = tempConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); + Session tempSession = tempConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); TemporaryQueue queue = tempSession.createTemporaryQueue(); - - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - connection.start(); - - // This message delivery should work since the temp connection is still open. + + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + connection.start(); + + // This message delivery should work since the temp connection is still + // open. MessageProducer producer = session.createProducer(queue); producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); TextMessage message = session.createTextMessage("First"); @@ -238,36 +240,39 @@ public class JmsTempDestinationTest extends TestCase { // deleting the Queue will cause sends to fail queue.delete(); Thread.sleep(1000); // Wait a little bit to let the delete take effect. - - // This message delivery NOT should work since the temp connection is now closed. + + // This message delivery NOT should work since the temp connection is + // now closed. try { message = session.createTextMessage("Hello"); producer.send(message); fail("Send should fail since temp destination should not exist anymore."); - } catch ( JMSException e ) { - assertTrue("failed to throw an exception",true); + } catch (JMSException e) { + assertTrue("failed to throw an exception", true); } } - + /** * Test you can't delete a Destination with Active Subscribers + * * @throws JMSException */ public void testDeleteDestinationWithSubscribersFails() throws JMSException { Connection connection = factory.createConnection(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); TemporaryQueue queue = session.createTemporaryQueue(); - - connection.start(); - + + connection.start(); + session.createConsumer(queue); - - // This message delivery should NOT work since the temp connection is now closed. + + // This message delivery should NOT work since the temp connection is + // now closed. try { queue.delete(); fail("Should fail as Subscribers are active"); - } catch ( JMSException e ) { - assertTrue("failed to throw an exception",true); + } catch (JMSException e) { + assertTrue("failed to throw an exception", true); } } } diff --git a/activemq-core/src/test/java/org/apache/activemq/JmsTestSupport.java b/activemq-core/src/test/java/org/apache/activemq/JmsTestSupport.java index 8213177453..2d65c818be 100755 --- a/activemq-core/src/test/java/org/apache/activemq/JmsTestSupport.java +++ b/activemq-core/src/test/java/org/apache/activemq/JmsTestSupport.java @@ -49,7 +49,7 @@ public class JmsTestSupport extends CombinationTestSupport { protected ConnectionFactory factory; protected ActiveMQConnection connection; protected BrokerService broker; - + protected List connections = Collections.synchronizedList(new ArrayList()); // ///////////////////////////////////////////////////////////////// @@ -60,13 +60,13 @@ public class JmsTestSupport extends CombinationTestSupport { protected ActiveMQDestination createDestination(Session session, byte type) throws JMSException { switch (type) { case ActiveMQDestination.QUEUE_TYPE: - return (ActiveMQDestination) session.createQueue("TEST"); + return (ActiveMQDestination)session.createQueue("TEST"); case ActiveMQDestination.TOPIC_TYPE: - return (ActiveMQDestination) session.createTopic("TEST"); + return (ActiveMQDestination)session.createTopic("TEST"); case ActiveMQDestination.TEMP_QUEUE_TYPE: - return (ActiveMQDestination) session.createTemporaryQueue(); + return (ActiveMQDestination)session.createTemporaryQueue(); case ActiveMQDestination.TEMP_TOPIC_TYPE: - return (ActiveMQDestination) session.createTemporaryTopic(); + return (ActiveMQDestination)session.createTemporaryTopic(); } throw new IllegalArgumentException("type: " + type); } @@ -88,7 +88,7 @@ public class JmsTestSupport extends CombinationTestSupport { protected void sendMessages(Session session, Destination destination, int count) throws JMSException { MessageProducer producer = session.createProducer(destination); for (int i = 0; i < count; i++) { - producer.send(session.createTextMessage(""+i)); + producer.send(session.createTextMessage("" + i)); } producer.close(); } @@ -104,21 +104,21 @@ public class JmsTestSupport extends CombinationTestSupport { protected void setUp() throws Exception { super.setUp(); - if(System.getProperty("basedir")==null){ - File file=new File("."); - System.setProperty("basedir",file.getAbsolutePath()); + if (System.getProperty("basedir") == null) { + File file = new File("."); + System.setProperty("basedir", file.getAbsolutePath()); } broker = createBroker(); broker.start(); factory = createConnectionFactory(); - connection = (ActiveMQConnection) factory.createConnection(userName, password); + connection = (ActiveMQConnection)factory.createConnection(userName, password); connections.add(connection); } protected void tearDown() throws Exception { for (Iterator iter = connections.iterator(); iter.hasNext();) { - Connection conn= (Connection) iter.next(); + Connection conn = (Connection)iter.next(); try { conn.close(); } catch (Throwable e) { @@ -127,7 +127,7 @@ public class JmsTestSupport extends CombinationTestSupport { broker.stop(); super.tearDown(); } - + protected void safeClose(Connection c) { try { c.close(); @@ -155,17 +155,17 @@ public class JmsTestSupport extends CombinationTestSupport { } catch (Throwable e) { } } - + protected void profilerPause(String prompt) throws IOException { - if( System.getProperty("profiler")!=null ) { + if (System.getProperty("profiler") != null) { pause(prompt); } } - + protected void pause(String prompt) throws IOException { System.out.println(); - System.out.println(prompt+"> Press enter to continue: "); - while( System.in.read()!='\n' ) { + System.out.println(prompt + "> Press enter to continue: "); + while (System.in.read() != '\n') { } } diff --git a/activemq-core/src/test/java/org/apache/activemq/JmsTopicWildcardSendReceiveTest.java b/activemq-core/src/test/java/org/apache/activemq/JmsTopicWildcardSendReceiveTest.java index df4c2fd69c..b76f2f38de 100755 --- a/activemq-core/src/test/java/org/apache/activemq/JmsTopicWildcardSendReceiveTest.java +++ b/activemq-core/src/test/java/org/apache/activemq/JmsTopicWildcardSendReceiveTest.java @@ -28,16 +28,15 @@ import javax.jms.MessageProducer; import org.apache.activemq.command.ActiveMQDestination; import org.apache.activemq.test.JmsTopicSendReceiveTest; - /** * @version $Revision: 1.4 $ */ public class JmsTopicWildcardSendReceiveTest extends JmsTopicSendReceiveTest { - private String destination1String = "TEST.ONE.ONE" ; - private String destination2String = "TEST.ONE.ONE.ONE" ; - private String destination3String = "TEST.ONE.TWO" ; - private String destination4String = "TEST.TWO.ONE" ; + private String destination1String = "TEST.ONE.ONE"; + private String destination2String = "TEST.ONE.ONE.ONE"; + private String destination3String = "TEST.ONE.TWO"; + private String destination4String = "TEST.TWO.ONE"; protected void setUp() throws Exception { topic = true; @@ -45,12 +44,12 @@ public class JmsTopicWildcardSendReceiveTest extends JmsTopicSendReceiveTest { deliveryMode = DeliveryMode.NON_PERSISTENT; super.setUp(); } - - protected String getConsumerSubject(){ + + protected String getConsumerSubject() { return "FOO.>"; } - - protected String getProducerSubject(){ + + protected String getProducerSubject() { return "FOO.BAR.HUMBUG"; } @@ -58,27 +57,27 @@ public class JmsTopicWildcardSendReceiveTest extends JmsTopicSendReceiveTest { connection.start(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - ActiveMQDestination destination1 = (ActiveMQDestination) session.createTopic(destination1String); - ActiveMQDestination destination3 = (ActiveMQDestination) session.createTopic(destination3String); + ActiveMQDestination destination1 = (ActiveMQDestination)session.createTopic(destination1String); + ActiveMQDestination destination3 = (ActiveMQDestination)session.createTopic(destination3String); Message m = null; MessageConsumer consumer = null; String text = null; - ActiveMQDestination destination6 = (ActiveMQDestination) session.createTopic("TEST.ONE.*"); + ActiveMQDestination destination6 = (ActiveMQDestination)session.createTopic("TEST.ONE.*"); consumer = session.createConsumer(destination6); - sendMessage(session,destination1,destination1String); - sendMessage(session,destination3,destination3String); + sendMessage(session, destination1, destination1String); + sendMessage(session, destination3, destination3String); m = consumer.receive(1000); assertNotNull(m); text = ((TextMessage)m).getText(); - if(!(text.equals(destination1String) || text.equals(destination3String))) { + if (!(text.equals(destination1String) || text.equals(destination3String))) { fail("unexpected message:" + text); } m = consumer.receive(1000); assertNotNull(m); text = ((TextMessage)m).getText(); - if(!(text.equals(destination1String) || text.equals(destination3String))) { + if (!(text.equals(destination1String) || text.equals(destination3String))) { fail("unexpected message:" + text); } assertNull(consumer.receiveNoWait()); @@ -88,33 +87,33 @@ public class JmsTopicWildcardSendReceiveTest extends JmsTopicSendReceiveTest { connection.start(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - ActiveMQDestination destination1 = (ActiveMQDestination) session.createTopic(destination1String); - ActiveMQDestination destination2 = (ActiveMQDestination) session.createTopic(destination2String); - ActiveMQDestination destination3 = (ActiveMQDestination) session.createTopic(destination3String); + ActiveMQDestination destination1 = (ActiveMQDestination)session.createTopic(destination1String); + ActiveMQDestination destination2 = (ActiveMQDestination)session.createTopic(destination2String); + ActiveMQDestination destination3 = (ActiveMQDestination)session.createTopic(destination3String); Message m = null; MessageConsumer consumer = null; String text = null; - ActiveMQDestination destination7 = (ActiveMQDestination) session.createTopic("TEST.ONE.>"); + ActiveMQDestination destination7 = (ActiveMQDestination)session.createTopic("TEST.ONE.>"); consumer = session.createConsumer(destination7); - sendMessage(session,destination1,destination1String); - sendMessage(session,destination2,destination2String); - sendMessage(session,destination3,destination3String); + sendMessage(session, destination1, destination1String); + sendMessage(session, destination2, destination2String); + sendMessage(session, destination3, destination3String); m = consumer.receive(1000); assertNotNull(m); text = ((TextMessage)m).getText(); - if(!(text.equals(destination1String) || text.equals(destination2String) || text.equals(destination3String))) { + if (!(text.equals(destination1String) || text.equals(destination2String) || text.equals(destination3String))) { fail("unexpected message:" + text); } m = consumer.receive(1000); assertNotNull(m); - if(!(text.equals(destination1String) || text.equals(destination2String) || text.equals(destination3String))) { + if (!(text.equals(destination1String) || text.equals(destination2String) || text.equals(destination3String))) { fail("unexpected message:" + text); } m = consumer.receive(1000); assertNotNull(m); - if(!(text.equals(destination1String) || text.equals(destination2String) || text.equals(destination3String))) { + if (!(text.equals(destination1String) || text.equals(destination2String) || text.equals(destination3String))) { fail("unexpected message:" + text); } assertNull(consumer.receiveNoWait()); @@ -124,27 +123,27 @@ public class JmsTopicWildcardSendReceiveTest extends JmsTopicSendReceiveTest { connection.start(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - ActiveMQDestination destination1 = (ActiveMQDestination) session.createTopic(destination1String); - ActiveMQDestination destination4 = (ActiveMQDestination) session.createTopic(destination4String); + ActiveMQDestination destination1 = (ActiveMQDestination)session.createTopic(destination1String); + ActiveMQDestination destination4 = (ActiveMQDestination)session.createTopic(destination4String); Message m = null; MessageConsumer consumer = null; String text = null; - ActiveMQDestination destination8 = (ActiveMQDestination) session.createTopic("TEST.*.ONE"); + ActiveMQDestination destination8 = (ActiveMQDestination)session.createTopic("TEST.*.ONE"); consumer = session.createConsumer(destination8); - sendMessage(session,destination1,destination1String); - sendMessage(session,destination4,destination4String); + sendMessage(session, destination1, destination1String); + sendMessage(session, destination4, destination4String); m = consumer.receive(1000); assertNotNull(m); text = ((TextMessage)m).getText(); - if(!(text.equals(destination1String) || text.equals(destination4String))) { + if (!(text.equals(destination1String) || text.equals(destination4String))) { fail("unexpected message:" + text); } m = consumer.receive(1000); assertNotNull(m); text = ((TextMessage)m).getText(); - if(!(text.equals(destination1String) || text.equals(destination4String))) { + if (!(text.equals(destination1String) || text.equals(destination4String))) { fail("unexpected message:" + text); } assertNull(consumer.receiveNoWait()); diff --git a/activemq-core/src/test/java/org/apache/activemq/LargeMessageTestSupport.java b/activemq-core/src/test/java/org/apache/activemq/LargeMessageTestSupport.java index bc333aa5e7..76a68ec804 100755 --- a/activemq-core/src/test/java/org/apache/activemq/LargeMessageTestSupport.java +++ b/activemq-core/src/test/java/org/apache/activemq/LargeMessageTestSupport.java @@ -41,8 +41,7 @@ import org.apache.activemq.util.IdGenerator; */ public class LargeMessageTestSupport extends ClientTestSupport implements MessageListener { - private static final org.apache.commons.logging.Log log = org.apache.commons.logging.LogFactory - .getLog(LargeMessageTestSupport.class); + private static final org.apache.commons.logging.Log log = org.apache.commons.logging.LogFactory.getLog(LargeMessageTestSupport.class); protected static final int LARGE_MESSAGE_SIZE = 128 * 1024; protected static final int MESSAGE_COUNT = 100; @@ -97,7 +96,8 @@ public class LargeMessageTestSupport extends ClientTestSupport implements Messag } try { - Thread.sleep(1000);// allow the broker to start + // allow the broker to start + Thread.sleep(1000); } catch (InterruptedException e) { throw new JMSException(e.getMessage()); } @@ -185,8 +185,7 @@ public class LargeMessageTestSupport extends ClientTestSupport implements Messag } } log.info("Finished count = " + messageCount); - assertTrue("Not enough messages - expected " + MESSAGE_COUNT + " but got " + messageCount, - messageCount.get() == MESSAGE_COUNT); + assertTrue("Not enough messages - expected " + MESSAGE_COUNT + " but got " + messageCount, messageCount.get() == MESSAGE_COUNT); assertTrue("received messages are not valid", validMessageConsumption); Thread.sleep(1000); log.info("FINAL count = " + messageCount); diff --git a/activemq-core/src/test/java/org/apache/activemq/LargeStreamletTest.java b/activemq-core/src/test/java/org/apache/activemq/LargeStreamletTest.java index b879740727..3c1ca7586e 100644 --- a/activemq-core/src/test/java/org/apache/activemq/LargeStreamletTest.java +++ b/activemq-core/src/test/java/org/apache/activemq/LargeStreamletTest.java @@ -1,21 +1,22 @@ package org.apache.activemq; + /** -* -* Licensed to the Apache Software Foundation (ASF) under one or more -* contributor license agreements. See the NOTICE file distributed with -* this work for additional information regarding copyright ownership. -* The ASF licenses this file to You under the Apache License, Version 2.0 -* (the "License"); you may not use this file except in compliance with -* the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT 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. + */ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -38,13 +39,10 @@ import java.util.concurrent.atomic.AtomicInteger; public final class LargeStreamletTest extends TestCase { private static final Log log = LogFactory.getLog(LargeStreamletTest.class); - private static final String BROKER_URL = "vm://localhost?broker.persistent=false"; - private static final int BUFFER_SIZE = 1 * 1024; + private static final int MESSAGE_COUNT = 10 * 1024; - private static final int MESSAGE_COUNT = 10*1024; - private AtomicInteger totalRead = new AtomicInteger(); private AtomicInteger totalWritten = new AtomicInteger(); @@ -56,15 +54,12 @@ public final class LargeStreamletTest extends TestCase { protected Exception readerException; public void testStreamlets() throws Exception { - final ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory( - BROKER_URL); + final ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(BROKER_URL); - final ActiveMQConnection connection = (ActiveMQConnection) factory - .createConnection(); + final ActiveMQConnection connection = (ActiveMQConnection)factory.createConnection(); connection.start(); try { - final Session session = connection.createSession(false, - Session.AUTO_ACKNOWLEDGE); + final Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); try { final Destination destination = session.createQueue("wibble"); final Thread readerThread = new Thread(new Runnable() { @@ -72,20 +67,18 @@ public final class LargeStreamletTest extends TestCase { public void run() { totalRead.set(0); try { - final InputStream inputStream = connection - .createInputStream(destination); + final InputStream inputStream = connection.createInputStream(destination); try { int read; final byte[] buf = new byte[BUFFER_SIZE]; - while (!stopThreads.get() - && (read = inputStream.read(buf)) != -1) { + while (!stopThreads.get() && (read = inputStream.read(buf)) != -1) { totalRead.addAndGet(read); } } finally { inputStream.close(); } } catch (Exception e) { - readerException = e; + readerException = e; e.printStackTrace(); } finally { log.info(totalRead + " total bytes read."); @@ -94,13 +87,13 @@ public final class LargeStreamletTest extends TestCase { }); final Thread writerThread = new Thread(new Runnable() { - private final Random random = new Random(); + private final Random random = new Random(); + public void run() { totalWritten.set(0); int count = MESSAGE_COUNT; try { - final OutputStream outputStream = connection - .createOutputStream(destination); + final OutputStream outputStream = connection.createOutputStream(destination); try { final byte[] buf = new byte[BUFFER_SIZE]; random.nextBytes(buf); @@ -116,8 +109,7 @@ public final class LargeStreamletTest extends TestCase { writerException = e; e.printStackTrace(); } finally { - log.info(totalWritten - + " total bytes written."); + log.info(totalWritten + " total bytes written."); } } }); @@ -125,28 +117,27 @@ public final class LargeStreamletTest extends TestCase { readerThread.start(); writerThread.start(); - - // Wait till reader is has finished receiving all the messages or he has stopped + // Wait till reader is has finished receiving all the messages + // or he has stopped // receiving messages. Thread.sleep(1000); int lastRead = totalRead.get(); - while( readerThread.isAlive() ) { + while (readerThread.isAlive()) { readerThread.join(1000); // No progress?? then stop waiting.. - if( lastRead == totalRead.get() ) { + if (lastRead == totalRead.get()) { break; } lastRead = totalRead.get(); } - + stopThreads.set(true); assertTrue("Should not have received a reader exception", readerException == null); assertTrue("Should not have received a writer exception", writerException == null); - - Assert.assertEquals("Not all messages accounted for", - totalWritten.get(), totalRead.get()); - + + Assert.assertEquals("Not all messages accounted for", totalWritten.get(), totalRead.get()); + } finally { session.close(); } diff --git a/activemq-core/src/test/java/org/apache/activemq/LoadTestBurnIn.java b/activemq-core/src/test/java/org/apache/activemq/LoadTestBurnIn.java index 145c422b90..58d8ca5fcd 100644 --- a/activemq-core/src/test/java/org/apache/activemq/LoadTestBurnIn.java +++ b/activemq-core/src/test/java/org/apache/activemq/LoadTestBurnIn.java @@ -81,7 +81,8 @@ public class LoadTestBurnIn extends JmsTestSupport { } protected ConnectionFactory createConnectionFactory() throws URISyntaxException, IOException { - return new ActiveMQConnectionFactory(((TransportConnector)broker.getTransportConnectors().get(0)).getServer().getConnectURI()); + return new ActiveMQConnectionFactory(((TransportConnector)broker.getTransportConnectors().get(0)) + .getServer().getConnectURI()); } public ActiveMQDestination destination; @@ -93,18 +94,22 @@ public class LoadTestBurnIn extends JmsTestSupport { public int messageSize = 1024; 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),}); + 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) + if (durableConsumer && destinationType != ActiveMQDestination.TOPIC_TYPE) { return; + } connection.setClientID(getName()); connection.getPrefetchPolicy().setAll(1000); @@ -114,7 +119,8 @@ public class LoadTestBurnIn extends JmsTestSupport { destination = createDestination(session, destinationType); MessageConsumer consumer; if (durableConsumer) { - consumer = session.createDurableSubscriber((Topic)destination, "sub1:" + System.currentTimeMillis()); + consumer = session.createDurableSubscriber((Topic)destination, "sub1:" + + System.currentTimeMillis()); } else { consumer = session.createConsumer(destination); } diff --git a/activemq-core/src/test/java/org/apache/activemq/ProducerFlowControlTest.java b/activemq-core/src/test/java/org/apache/activemq/ProducerFlowControlTest.java index f0eb570bde..120d36ace4 100644 --- a/activemq-core/src/test/java/org/apache/activemq/ProducerFlowControlTest.java +++ b/activemq-core/src/test/java/org/apache/activemq/ProducerFlowControlTest.java @@ -163,8 +163,9 @@ public class ProducerFlowControlTest extends JmsTestSupport { while (true) { Thread.sleep(1000); // the producer is blocked once the done flag stays true. - if (done.get()) + if (done.get()) { break; + } done.set(true); } keepGoing.set(false); diff --git a/activemq-core/src/test/java/org/apache/activemq/ReconnectWithSameClientIDTest.java b/activemq-core/src/test/java/org/apache/activemq/ReconnectWithSameClientIDTest.java index 2c4b57067c..6b92ac8676 100644 --- a/activemq-core/src/test/java/org/apache/activemq/ReconnectWithSameClientIDTest.java +++ b/activemq-core/src/test/java/org/apache/activemq/ReconnectWithSameClientIDTest.java @@ -37,18 +37,18 @@ public class ReconnectWithSameClientIDTest extends EmbeddedBrokerTestSupport { // now lets create another which should fail for (int i = 1; i < 11; i++) { - Connection connection2 = connectionFactory.createConnection(); - try { - useConnection(connection2); - fail("Should have thrown InvalidClientIDException on attempt" + i); - } - catch (InvalidClientIDException e) { - connection2.close(); - LOG.info("Caught expected: " + e); - } + Connection connection2 = connectionFactory.createConnection(); + try { + useConnection(connection2); + fail("Should have thrown InvalidClientIDException on attempt" + i); + } catch (InvalidClientIDException e) { + connection2.close(); + LOG.info("Caught expected: " + e); + } } - // now lets try closing the original connection and creating a new connection with the same ID + // now lets try closing the original connection and creating a new + // connection with the same ID connection.close(); connection = connectionFactory.createConnection(); useConnection(connection); diff --git a/activemq-core/src/test/java/org/apache/activemq/broker/BrokerBenchmark.java b/activemq-core/src/test/java/org/apache/activemq/broker/BrokerBenchmark.java index 8f4b649d2a..c64746c59f 100755 --- a/activemq-core/src/test/java/org/apache/activemq/broker/BrokerBenchmark.java +++ b/activemq-core/src/test/java/org/apache/activemq/broker/BrokerBenchmark.java @@ -16,8 +16,10 @@ */ package org.apache.activemq.broker; -import junit.framework.Test; +import java.util.concurrent.Semaphore; +import java.util.concurrent.atomic.AtomicInteger; +import junit.framework.Test; import org.apache.activemq.command.ActiveMQDestination; import org.apache.activemq.command.ActiveMQQueue; import org.apache.activemq.command.ActiveMQTopic; @@ -30,9 +32,6 @@ import org.apache.activemq.command.SessionInfo; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import java.util.concurrent.Semaphore; -import java.util.concurrent.atomic.AtomicInteger; - /** * BrokerBenchmark is used to get an idea of the raw performance of a broker. * Since the broker data structures using in message dispatching are under high @@ -55,18 +54,18 @@ public class BrokerBenchmark extends BrokerTestSupport { public boolean deliveryMode; public void initCombosForTestPerformance() { - addCombinationValues("destination", new Object[] {new ActiveMQQueue("TEST"), new ActiveMQTopic("TEST")}); + addCombinationValues("destination", new Object[] {new ActiveMQQueue("TEST"), + new ActiveMQTopic("TEST")}); addCombinationValues("PRODUCER_COUNT", new Object[] {new Integer("1"), new Integer("10")}); addCombinationValues("CONSUMER_COUNT", new Object[] {new Integer("1"), new Integer("10")}); addCombinationValues("CONSUMER_COUNT", new Object[] {new Integer("1"), new Integer("10")}); - addCombinationValues("deliveryMode", new Object[] { - // Boolean.FALSE, - Boolean.TRUE}); + addCombinationValues("deliveryMode", new Object[] {Boolean.TRUE}); } public void testPerformance() throws Exception { - log.info("Running Benchmark for destination=" + destination + ", producers=" + PRODUCER_COUNT + ", consumers=" + CONSUMER_COUNT + ", deliveryMode=" + deliveryMode); + log.info("Running Benchmark for destination=" + destination + ", producers=" + PRODUCER_COUNT + + ", consumers=" + CONSUMER_COUNT + ", deliveryMode=" + deliveryMode); final int CONSUME_COUNT = destination.isTopic() ? CONSUMER_COUNT * PRODUCE_COUNT : PRODUCE_COUNT; final Semaphore consumersStarted = new Semaphore(1 - (CONSUMER_COUNT)); @@ -122,7 +121,8 @@ public class BrokerBenchmark extends BrokerTestSupport { } if (msg != null) { - connection.send(createAck(consumerInfo, msg, counter, MessageAck.STANDARD_ACK_TYPE)); + connection.send(createAck(consumerInfo, msg, counter, + MessageAck.STANDARD_ACK_TYPE)); } else if (receiveCounter.get() < CONSUME_COUNT) { log.info("Consumer stall, waiting for message #" + receiveCounter.get() + 1); } @@ -179,7 +179,8 @@ public class BrokerBenchmark extends BrokerTestSupport { consumersFinished.acquire(); long end2 = System.currentTimeMillis(); - log.info("Results for destination=" + destination + ", producers=" + PRODUCER_COUNT + ", consumers=" + CONSUMER_COUNT + ", deliveryMode=" + deliveryMode); + log.info("Results for destination=" + destination + ", producers=" + PRODUCER_COUNT + ", consumers=" + + CONSUMER_COUNT + ", deliveryMode=" + deliveryMode); log.info("Produced at messages/sec: " + (PRODUCE_COUNT * 1000.0 / (end1 - start))); log.info("Consumed at messages/sec: " + (CONSUME_COUNT * 1000.0 / (end2 - start))); profilerPause("Benchmark done. Stop profiler "); diff --git a/activemq-core/src/test/java/org/apache/activemq/broker/BrokerServiceTest.java b/activemq-core/src/test/java/org/apache/activemq/broker/BrokerServiceTest.java index 18c0a48d19..58cbe80852 100644 --- a/activemq-core/src/test/java/org/apache/activemq/broker/BrokerServiceTest.java +++ b/activemq-core/src/test/java/org/apache/activemq/broker/BrokerServiceTest.java @@ -16,61 +16,61 @@ */ package org.apache.activemq.broker; +import junit.framework.TestCase; import org.apache.activemq.network.NetworkConnector; -import junit.framework.TestCase; - /** - * Tests for the BrokerService class + * 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"); - 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"); - service.start(); - - service.removeNetworkConnector(connector); - connector.stop(); - service.stop(); - } + 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"); + 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"); + service.start(); + + service.removeNetworkConnector(connector); + connector.stop(); + service.stop(); + } } diff --git a/activemq-core/src/test/java/org/apache/activemq/broker/BrokerTest.java b/activemq-core/src/test/java/org/apache/activemq/broker/BrokerTest.java index 92f0c944c8..d29821cd49 100755 --- a/activemq-core/src/test/java/org/apache/activemq/broker/BrokerTest.java +++ b/activemq-core/src/test/java/org/apache/activemq/broker/BrokerTest.java @@ -45,7 +45,8 @@ public class BrokerTest extends BrokerTestSupport { public boolean durableConsumer; public void initCombosForTestQueueOnlyOnceDeliveryWith2Consumers() { - addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); + addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), + Integer.valueOf(DeliveryMode.PERSISTENT)}); } public void testQueueOnlyOnceDeliveryWith2Consumers() throws Exception { @@ -98,7 +99,8 @@ public class BrokerTest extends BrokerTestSupport { } public void initCombosForTestQueuBrowserWith2Consumers() { - addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); + addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), + Integer.valueOf(DeliveryMode.PERSISTENT)}); } /** @@ -167,8 +169,11 @@ public class BrokerTest extends BrokerTestSupport { 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)}); + 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 testConsumerPrefetchAndStandardAck() throws Exception { @@ -214,9 +219,13 @@ public class BrokerTest extends BrokerTestSupport { } public void initCombosForTestTransactedAckWithPrefetchOfOne() { - 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)}); + 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 testTransactedAckWithPrefetchOfOne() throws Exception { @@ -262,9 +271,13 @@ public class BrokerTest extends BrokerTestSupport { } public void initCombosForTestTransactedSend() { - 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)}); + 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 testTransactedSend() throws Exception { @@ -312,8 +325,11 @@ public class BrokerTest extends BrokerTestSupport { } public void initCombosForTestQueueTransactedAck() { - 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.TEMP_QUEUE_TYPE),}); + 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.TEMP_QUEUE_TYPE)}); } public void testQueueTransactedAck() throws Exception { @@ -360,7 +376,8 @@ public class BrokerTest extends BrokerTestSupport { } public void initCombosForTestConsumerCloseCausesRedelivery() { - addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); + addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), + Integer.valueOf(DeliveryMode.PERSISTENT)}); addCombinationValues("destination", new Object[] {new ActiveMQQueue("TEST")}); } @@ -470,7 +487,8 @@ public class BrokerTest extends BrokerTestSupport { } public void initCombosForTestGroupedMessagesDeliveredToOnlyOneConsumer() { - addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); + addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), + Integer.valueOf(DeliveryMode.PERSISTENT)}); } public void testGroupedMessagesDeliveredToOnlyOneConsumer() throws Exception { @@ -531,7 +549,8 @@ public class BrokerTest extends BrokerTestSupport { } public void initCombosForTestTopicConsumerOnlySeeMessagesAfterCreation() { - addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); + addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), + Integer.valueOf(DeliveryMode.PERSISTENT)}); addCombinationValues("durableConsumer", new Object[] {Boolean.TRUE, Boolean.FALSE}); } @@ -575,7 +594,8 @@ public class BrokerTest extends BrokerTestSupport { } public void initCombosForTestTopicRetroactiveConsumerSeeMessagesBeforeCreation() { - addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); + addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), + Integer.valueOf(DeliveryMode.PERSISTENT)}); addCombinationValues("durableConsumer", new Object[] {Boolean.TRUE, Boolean.FALSE}); } @@ -723,8 +743,11 @@ public class BrokerTest extends BrokerTestSupport { // } public void initCombosForTestTempDestinationsOnlyAllowsLocalConsumers() { - 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)}); + 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)}); } public void testTempDestinationsOnlyAllowsLocalConsumers() throws Exception { @@ -762,7 +785,8 @@ public class BrokerTest extends BrokerTestSupport { } public void initCombosForTestExclusiveQueueDeliversToOnlyOneConsumer() { - addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); + addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), + Integer.valueOf(DeliveryMode.PERSISTENT)}); } public void testExclusiveQueueDeliversToOnlyOneConsumer() throws Exception { @@ -826,8 +850,10 @@ public class BrokerTest extends BrokerTestSupport { } public void initCombosForTestWildcardConsume() { - 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)}); + 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 testWildcardConsume() throws Exception { @@ -842,14 +868,19 @@ public class BrokerTest extends BrokerTestSupport { connection1.send(producerInfo1); // setup the wildcard consumer. - ActiveMQDestination compositeDestination = ActiveMQDestination.createDestination("WILD.*.TEST", destinationType); + ActiveMQDestination compositeDestination = ActiveMQDestination.createDestination("WILD.*.TEST", + destinationType); ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, compositeDestination); consumerInfo1.setPrefetchSize(100); connection1.send(consumerInfo1); // These two message should NOT match the wild card. - connection1.send(createMessage(producerInfo1, ActiveMQDestination.createDestination("WILD.CARD", destinationType), deliveryMode)); - connection1.send(createMessage(producerInfo1, ActiveMQDestination.createDestination("WILD.TEST", destinationType), deliveryMode)); + connection1.send(createMessage(producerInfo1, ActiveMQDestination.createDestination("WILD.CARD", + destinationType), + deliveryMode)); + connection1.send(createMessage(producerInfo1, ActiveMQDestination.createDestination("WILD.TEST", + destinationType), + deliveryMode)); // These two message should match the wild card. ActiveMQDestination d1 = ActiveMQDestination.createDestination("WILD.CARD.TEST", destinationType); @@ -869,8 +900,10 @@ public class BrokerTest extends BrokerTestSupport { } public void initCombosForTestCompositeConsume() { - 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)}); + 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 testCompositeConsume() throws Exception { @@ -885,7 +918,8 @@ public class BrokerTest extends BrokerTestSupport { connection1.send(producerInfo1); // setup the composite consumer. - ActiveMQDestination compositeDestination = ActiveMQDestination.createDestination("A,B", destinationType); + ActiveMQDestination compositeDestination = ActiveMQDestination.createDestination("A,B", + destinationType); ConsumerInfo consumerInfo1 = createConsumerInfo(sessionInfo1, compositeDestination); consumerInfo1.setRetroactive(true); consumerInfo1.setPrefetchSize(100); @@ -910,8 +944,10 @@ public class BrokerTest extends BrokerTestSupport { } public void initCombosForTestCompositeSend() { - 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)}); + 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 testCompositeSend() throws Exception { @@ -945,7 +981,8 @@ public class BrokerTest extends BrokerTestSupport { connection2.send(consumerInfo2); // Send the messages to the composite destination. - ActiveMQDestination compositeDestination = ActiveMQDestination.createDestination("A,B", destinationType); + ActiveMQDestination compositeDestination = ActiveMQDestination.createDestination("A,B", + destinationType); for (int i = 0; i < 4; i++) { connection1.send(createMessage(producerInfo1, compositeDestination, deliveryMode)); } @@ -976,8 +1013,10 @@ public class BrokerTest extends BrokerTestSupport { } public void initCombosForTestConnectionCloseCascades() { - addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); - addCombinationValues("destination", new Object[] {new ActiveMQTopic("TEST"), new ActiveMQQueue("TEST")}); + addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), + Integer.valueOf(DeliveryMode.PERSISTENT)}); + addCombinationValues("destination", new Object[] {new ActiveMQTopic("TEST"), + new ActiveMQQueue("TEST")}); } public void testConnectionCloseCascades() throws Exception { @@ -1026,8 +1065,10 @@ public class BrokerTest extends BrokerTestSupport { } public void initCombosForTestSessionCloseCascades() { - addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); - addCombinationValues("destination", new Object[] {new ActiveMQTopic("TEST"), new ActiveMQQueue("TEST")}); + addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), + Integer.valueOf(DeliveryMode.PERSISTENT)}); + addCombinationValues("destination", new Object[] {new ActiveMQTopic("TEST"), + new ActiveMQQueue("TEST")}); } public void testSessionCloseCascades() throws Exception { @@ -1076,8 +1117,10 @@ public class BrokerTest extends BrokerTestSupport { } public void initCombosForTestConsumerClose() { - addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); - addCombinationValues("destination", new Object[] {new ActiveMQTopic("TEST"), new ActiveMQQueue("TEST")}); + addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), + Integer.valueOf(DeliveryMode.PERSISTENT)}); + addCombinationValues("destination", new Object[] {new ActiveMQTopic("TEST"), + new ActiveMQQueue("TEST")}); } public void testConsumerClose() throws Exception { @@ -1126,7 +1169,8 @@ public class BrokerTest extends BrokerTestSupport { } public void initCombosForTestTopicNoLocal() { - addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); + addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), + Integer.valueOf(DeliveryMode.PERSISTENT)}); } public void testTopicNoLocal() throws Exception { @@ -1191,7 +1235,8 @@ public class BrokerTest extends BrokerTestSupport { } public void initCombosForTopicDispatchIsBroadcast() { - addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), Integer.valueOf(DeliveryMode.PERSISTENT)}); + addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), + Integer.valueOf(DeliveryMode.PERSISTENT)}); } public void testTopicDispatchIsBroadcast() throws Exception { @@ -1239,8 +1284,11 @@ public class BrokerTest extends BrokerTestSupport { } public void initCombosForTestQueueDispatchedAreRedeliveredOnConsumerClose() { - 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.TEMP_QUEUE_TYPE),}); + 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.TEMP_QUEUE_TYPE)}); } public void testQueueDispatchedAreRedeliveredOnConsumerClose() throws Exception { @@ -1293,8 +1341,11 @@ public class BrokerTest extends BrokerTestSupport { } public void initCombosForTestQueueBrowseMessages() { - 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.TEMP_QUEUE_TYPE),}); + 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.TEMP_QUEUE_TYPE)}); } public void testQueueBrowseMessages() throws Exception { @@ -1330,8 +1381,11 @@ public class BrokerTest extends BrokerTestSupport { } public void initCombosForTestQueueSendThenAddConsumer() { - 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.TEMP_QUEUE_TYPE),}); + 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.TEMP_QUEUE_TYPE)}); } public void testQueueSendThenAddConsumer() throws Exception { @@ -1361,8 +1415,11 @@ public class BrokerTest extends BrokerTestSupport { } public void initCombosForTestQueueAckRemovesMessage() { - 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.TEMP_QUEUE_TYPE),}); + 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.TEMP_QUEUE_TYPE)}); } public void testQueueAckRemovesMessage() throws Exception { @@ -1399,9 +1456,13 @@ public class BrokerTest extends BrokerTestSupport { } public void initCombosForTestSelectorSkipsMessages() { - addCombinationValues("destination", new Object[] {new ActiveMQTopic("TEST_TOPIC"), new ActiveMQQueue("TEST_QUEUE")}); - 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)}); + addCombinationValues("destination", new Object[] {new ActiveMQTopic("TEST_TOPIC"), + new ActiveMQQueue("TEST_QUEUE")}); + 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 testSelectorSkipsMessages() throws Exception { @@ -1439,9 +1500,13 @@ public class BrokerTest extends BrokerTestSupport { } 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), - Byte.valueOf(ActiveMQDestination.TEMP_QUEUE_TYPE), Byte.valueOf(ActiveMQDestination.TEMP_TOPIC_TYPE)}); + 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 testAddConsumerThenSend() throws Exception { @@ -1468,9 +1533,13 @@ public class BrokerTest extends BrokerTestSupport { } public void initCombosForTestConsumerPrefetchAtOne() { - 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)}); + 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 testConsumerPrefetchAtOne() throws Exception { @@ -1502,9 +1571,13 @@ public class BrokerTest extends BrokerTestSupport { } public void initCombosForTestConsumerPrefetchAtTwo() { - 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)}); + 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 testConsumerPrefetchAtTwo() throws Exception { @@ -1539,9 +1612,13 @@ public class BrokerTest extends BrokerTestSupport { } public void initCombosForTestConsumerPrefetchAndDeliveredAck() { - 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)}); + 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 testConsumerPrefetchAndDeliveredAck() throws Exception { diff --git a/activemq-core/src/test/java/org/apache/activemq/broker/DoubleSubscriptionTest.java b/activemq-core/src/test/java/org/apache/activemq/broker/DoubleSubscriptionTest.java index 46472b57ce..8fd129256e 100644 --- a/activemq-core/src/test/java/org/apache/activemq/broker/DoubleSubscriptionTest.java +++ b/activemq-core/src/test/java/org/apache/activemq/broker/DoubleSubscriptionTest.java @@ -50,7 +50,7 @@ public class DoubleSubscriptionTest extends NetworkTestSupport { } public void initCombosForTestDoubleSubscription() { - addCombinationValues("destination", new Object[] {new ActiveMQQueue("TEST"), new ActiveMQQueue("TEST"),}); + addCombinationValues("destination", new Object[] {new ActiveMQQueue("TEST"), new ActiveMQQueue("TEST")}); } public void testDoubleSubscription() throws Exception { diff --git a/activemq-core/src/test/java/org/apache/activemq/broker/MessageExpirationTest.java b/activemq-core/src/test/java/org/apache/activemq/broker/MessageExpirationTest.java index 33549c800d..c6b9232759 100644 --- a/activemq-core/src/test/java/org/apache/activemq/broker/MessageExpirationTest.java +++ b/activemq-core/src/test/java/org/apache/activemq/broker/MessageExpirationTest.java @@ -19,7 +19,8 @@ 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; @@ -28,11 +29,6 @@ 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.broker.region.policy.FixedCountSubscriptionRecoveryPolicy; -import org.apache.activemq.broker.region.policy.PolicyMap; -import org.apache.activemq.broker.region.policy.PolicyEntry; -import org.apache.activemq.broker.region.policy.RoundRobinDispatchPolicy; -import org.apache.activemq.broker.region.policy.VMPendingSubscriberMessageStoragePolicy; public class MessageExpirationTest extends BrokerTestSupport { @@ -152,9 +148,7 @@ public class MessageExpirationTest extends BrokerTestSupport { * DeliveryMode.PERSISTENT test combination for now. */ public void initCombosForTestMessagesInLongTransactionExpire() { - addCombinationValues("deliveryMode", new Object[] {Integer.valueOf(DeliveryMode.NON_PERSISTENT), - // Integer.valueOf(DeliveryMode.PERSISTENT) - }); + addCombinationValues("deliveryMode", new Object[] {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)}); } diff --git a/activemq-core/src/test/java/org/apache/activemq/broker/region/cursors/CursorDurableTest.java b/activemq-core/src/test/java/org/apache/activemq/broker/region/cursors/CursorDurableTest.java index 81408a7add..e83ea435fa 100644 --- a/activemq-core/src/test/java/org/apache/activemq/broker/region/cursors/CursorDurableTest.java +++ b/activemq-core/src/test/java/org/apache/activemq/broker/region/cursors/CursorDurableTest.java @@ -26,28 +26,28 @@ import org.apache.activemq.broker.BrokerService; /** * @version $Revision: 1.3 $ */ -public class CursorDurableTest extends CursorSupport{ +public class CursorDurableTest extends CursorSupport { - protected Destination getDestination(Session session) throws JMSException{ + protected Destination getDestination(Session session) throws JMSException { String topicName = getClass().getName(); return session.createTopic(topicName); } - protected Connection getConsumerConnection(ConnectionFactory fac) throws JMSException{ - Connection connection=fac.createConnection(); + protected Connection getConsumerConnection(ConnectionFactory fac) throws JMSException { + Connection connection = fac.createConnection(); connection.setClientID("testConsumer"); connection.start(); return connection; } - 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"); + 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; } - - protected void configureBroker(BrokerService answer) throws Exception{ + + protected void configureBroker(BrokerService answer) throws Exception { answer.setDeleteAllMessagesOnStartup(true); answer.addConnector(bindAddress); answer.setDeleteAllMessagesOnStartup(true); diff --git a/activemq-core/src/test/java/org/apache/activemq/command/ActiveMQDestinationTest.java b/activemq-core/src/test/java/org/apache/activemq/command/ActiveMQDestinationTest.java index fe645a512e..6100ba5edd 100755 --- a/activemq-core/src/test/java/org/apache/activemq/command/ActiveMQDestinationTest.java +++ b/activemq-core/src/test/java/org/apache/activemq/command/ActiveMQDestinationTest.java @@ -29,58 +29,54 @@ import junit.framework.Test; public class ActiveMQDestinationTest extends DataStructureTestSupport { public ActiveMQDestination destination; - + public void initCombosForTestDesintaionMarshaling() { - addCombinationValues("destination", new Object[]{ - new ActiveMQQueue("TEST"), - new ActiveMQTopic("TEST"), - new ActiveMQTempQueue("TEST:1"), - new ActiveMQTempTopic("TEST:1"), - new ActiveMQTempQueue("TEST"), - new ActiveMQTempTopic("TEST"), - new ActiveMQQueue("TEST?option=value"), - new ActiveMQTopic("TEST?option=value"), - new ActiveMQTempQueue("TEST:1?option=value"), - new ActiveMQTempTopic("TEST:1?option=value"), - }); + addCombinationValues("destination", new Object[] {new ActiveMQQueue("TEST"), + new ActiveMQTopic("TEST"), + new ActiveMQTempQueue("TEST:1"), + new ActiveMQTempTopic("TEST:1"), + new ActiveMQTempQueue("TEST"), + new ActiveMQTempTopic("TEST"), + new ActiveMQQueue("TEST?option=value"), + new ActiveMQTopic("TEST?option=value"), + new ActiveMQTempQueue("TEST:1?option=value"), + new ActiveMQTempTopic("TEST:1?option=value")}); } - + public void testDesintaionMarshaling() throws IOException { assertBeanMarshalls(destination); } - + public void initCombosForTestDesintaionOptions() { - addCombinationValues("destination", new Object[]{ - new ActiveMQQueue("TEST?k1=v1&k2=v2"), - new ActiveMQTopic("TEST?k1=v1&k2=v2"), - new ActiveMQTempQueue("TEST:1?k1=v1&k2=v2"), - new ActiveMQTempTopic("TEST:1?k1=v1&k2=v2"), - }); + addCombinationValues("destination", new Object[] {new ActiveMQQueue("TEST?k1=v1&k2=v2"), + new ActiveMQTopic("TEST?k1=v1&k2=v2"), + new ActiveMQTempQueue("TEST:1?k1=v1&k2=v2"), + new ActiveMQTempTopic("TEST:1?k1=v1&k2=v2"),}); } - + public void testDesintaionOptions() throws IOException { Map options = destination.getOptions(); assertNotNull(options); assertEquals("v1", options.get("k1")); assertEquals("v2", options.get("k2")); } - + public void testSorting() throws Exception { SortedSet set = new TreeSet(); - ActiveMQDestination[] destinations = { new ActiveMQQueue("A"), new ActiveMQQueue("B"), new ActiveMQTopic("A"), new ActiveMQTopic("B") }; + ActiveMQDestination[] destinations = {new ActiveMQQueue("A"), new ActiveMQQueue("B"), + new ActiveMQTopic("A"), new ActiveMQTopic("B")}; List expected = Arrays.asList(destinations); set.addAll(expected); List actual = new ArrayList(set); assertEquals("Sorted order", expected, actual); } - - + public static Test suite() { return suite(ActiveMQDestinationTest.class); } - + public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } - + } diff --git a/activemq-core/src/test/java/org/apache/activemq/network/ForwardingBridgeTest.java b/activemq-core/src/test/java/org/apache/activemq/network/ForwardingBridgeTest.java index 9ec55014ed..694ddfce76 100755 --- a/activemq-core/src/test/java/org/apache/activemq/network/ForwardingBridgeTest.java +++ b/activemq-core/src/test/java/org/apache/activemq/network/ForwardingBridgeTest.java @@ -27,28 +27,25 @@ 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 initCombosForTestAddConsumerThenSend() { - addCombinationValues( "deliveryMode", new Object[]{ - new Integer(DeliveryMode.NON_PERSISTENT), - new Integer(DeliveryMode.PERSISTENT)} ); - addCombinationValues( "destinationType", new Object[]{ - new Byte(ActiveMQDestination.QUEUE_TYPE), - new Byte(ActiveMQDestination.TOPIC_TYPE), - } ); - } + public void initCombosForTestAddConsumerThenSend() { + addCombinationValues("deliveryMode", new Object[] {new Integer(DeliveryMode.NON_PERSISTENT), + new Integer(DeliveryMode.PERSISTENT)}); + addCombinationValues("destinationType", new Object[] {new Byte(ActiveMQDestination.QUEUE_TYPE), + new Byte(ActiveMQDestination.TOPIC_TYPE),}); + } + public void testAddConsumerThenSend() throws Exception { - // Start a producer on local broker + // Start a producer on local broker StubConnection connection1 = createConnection(); ConnectionInfo connectionInfo1 = createConnectionInfo(); - SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); + SessionInfo sessionInfo1 = createSessionInfo(connectionInfo1); ProducerInfo producerInfo = createProducerInfo(sessionInfo1); connection1.send(connectionInfo1); connection1.send(sessionInfo1); @@ -59,10 +56,10 @@ public class ForwardingBridgeTest extends NetworkTestSupport { // Start a consumer on a remote broker StubConnection connection2 = createRemoteConnection(); ConnectionInfo connectionInfo2 = createConnectionInfo(); - SessionInfo sessionInfo2 = createSessionInfo(connectionInfo2); + SessionInfo sessionInfo2 = createSessionInfo(connectionInfo2); connection2.send(connectionInfo2); connection2.send(sessionInfo2); - ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo2, destination); + ConsumerInfo consumerInfo = createConsumerInfo(sessionInfo2, destination); connection2.send(consumerInfo); Thread.sleep(1000); // Give forwarding bridge a chance to finish setting up @@ -71,33 +68,33 @@ public class ForwardingBridgeTest extends NetworkTestSupport { } 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); } - + protected void setUp() throws Exception { super.setUp(); bridge = new ForwardingBridge(createTransport(), createRemoteTransport()); bridge.setClientId("local-remote-bridge"); bridge.setDispatchAsync(false); - bridge.start(); + bridge.start(); } - + 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/activemq-core/src/test/java/org/apache/activemq/network/MulticastNetworkTest.java b/activemq-core/src/test/java/org/apache/activemq/network/MulticastNetworkTest.java index 0b7d8666ed..eb36cfe4eb 100644 --- a/activemq-core/src/test/java/org/apache/activemq/network/MulticastNetworkTest.java +++ b/activemq-core/src/test/java/org/apache/activemq/network/MulticastNetworkTest.java @@ -17,7 +17,6 @@ package org.apache.activemq.network; /** - * * @version $Revision$ */ public class MulticastNetworkTest extends SimpleNetworkTest { @@ -29,4 +28,4 @@ public class MulticastNetworkTest extends SimpleNetworkTest { protected String getLocalBrokerURI() { return "org/apache/activemq/network/multicast/localBroker.xml"; } - } +} diff --git a/activemq-core/src/test/java/org/apache/activemq/network/SSHTunnelNetworkReconnectTest.java b/activemq-core/src/test/java/org/apache/activemq/network/SSHTunnelNetworkReconnectTest.java index f861913cec..adb33100a3 100644 --- a/activemq-core/src/test/java/org/apache/activemq/network/SSHTunnelNetworkReconnectTest.java +++ b/activemq-core/src/test/java/org/apache/activemq/network/SSHTunnelNetworkReconnectTest.java @@ -40,11 +40,13 @@ public class SSHTunnelNetworkReconnectTest extends NetworkReconnectTest { ArrayList processes = new ArrayList(); protected BrokerService createFirstBroker() throws Exception { - return BrokerFactory.createBroker(new URI("xbean:org/apache/activemq/network/ssh-reconnect-broker1.xml")); + return BrokerFactory + .createBroker(new URI("xbean:org/apache/activemq/network/ssh-reconnect-broker1.xml")); } protected BrokerService createSecondBroker() throws Exception { - return BrokerFactory.createBroker(new URI("xbean:org/apache/activemq/network/ssh-reconnect-broker2.xml")); + return BrokerFactory + .createBroker(new URI("xbean:org/apache/activemq/network/ssh-reconnect-broker2.xml")); } protected void setUp() throws Exception { diff --git a/activemq-core/src/test/java/org/apache/activemq/openwire/NumberRangesWhileMarshallingTest.java b/activemq-core/src/test/java/org/apache/activemq/openwire/NumberRangesWhileMarshallingTest.java index 3194eb472a..f3421db6f8 100644 --- a/activemq-core/src/test/java/org/apache/activemq/openwire/NumberRangesWhileMarshallingTest.java +++ b/activemq-core/src/test/java/org/apache/activemq/openwire/NumberRangesWhileMarshallingTest.java @@ -16,10 +16,6 @@ */ package org.apache.activemq.openwire; -import org.apache.activemq.command.SessionId; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; @@ -27,96 +23,72 @@ import java.io.DataOutputStream; import java.io.IOException; import junit.framework.TestCase; +import org.apache.activemq.command.SessionId; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; /** - * * @version $Revision$ */ public class NumberRangesWhileMarshallingTest extends TestCase { private static final Log log = LogFactory.getLog(NumberRangesWhileMarshallingTest.class); - + protected String connectionId = "Cheese"; protected ByteArrayOutputStream buffer = new ByteArrayOutputStream(); protected DataOutputStream ds = new DataOutputStream(buffer); protected OpenWireFormat openWireformat; protected int endOfStreamMarker = 0x12345678; - public void testLongNumberRanges() throws Exception { - long[] numberValues = { - // bytes - 0, 1, 0x7e, 0x7f, 0x80, 0x81, 0xf0, 0xff, - // shorts - 0x7eff, 0x7fffL, 0x8001L, 0x8000L, 0xe000L, 0xe0001L, 0xff00L, 0xffffL, - // ints - 0x10000L, - 0x700000L, - 0x12345678L, - 0x72345678L, - 0x7fffffffL, - 0x80000000L, - 0x80000001L, - 0xE0000001L, - 0xFFFFFFFFL, - - // 3 byte longs - 0x123456781L, - 0x1234567812L, - 0x12345678123L, - 0x123456781234L, - 0x1234567812345L, - 0x12345678123456L, - 0x7e345678123456L, - 0x7fffffffffffffL, - 0x80000000000000L, - 0x80000000000001L, - 0xe0000000000001L, - 0xffffffffffffffL, - - // 4 byte longs - 0x1234567812345678L, - 0x7fffffffffffffffL, - 0x8000000000000000L, - 0x8000000000000001L, - 0xe000000000000001L, - 0xffffffffffffffffL, - 1 }; - + long[] numberValues = { + // bytes + 0, 1, 0x7e, 0x7f, 0x80, 0x81, 0xf0, 0xff, + // shorts + 0x7eff, 0x7fffL, 0x8001L, 0x8000L, 0xe000L, 0xe0001L, 0xff00L, 0xffffL, + // ints + 0x10000L, 0x700000L, 0x12345678L, 0x72345678L, 0x7fffffffL, 0x80000000L, 0x80000001L, 0xE0000001L, 0xFFFFFFFFL, + + // 3 byte longs + 0x123456781L, 0x1234567812L, 0x12345678123L, 0x123456781234L, 0x1234567812345L, 0x12345678123456L, 0x7e345678123456L, 0x7fffffffffffffL, + 0x80000000000000L, 0x80000000000001L, 0xe0000000000001L, 0xffffffffffffffL, + + // 4 byte longs + 0x1234567812345678L, 0x7fffffffffffffffL, 0x8000000000000000L, 0x8000000000000001L, 0xe000000000000001L, 0xffffffffffffffffL, 1}; + for (int i = 0; i < numberValues.length; i++) { long value = numberValues[i]; - + SessionId object = new SessionId(); object.setConnectionId(connectionId); object.setValue(value); writeObject(object); } ds.writeInt(endOfStreamMarker); - + // now lets read from the stream ds.close(); - + ByteArrayInputStream in = new ByteArrayInputStream(buffer.toByteArray()); DataInputStream dis = new DataInputStream(in); for (int i = 0; i < numberValues.length; i++) { long value = numberValues[i]; String expected = Long.toHexString(value); log.info("Unmarshaling value: " + i + " = " + expected); - - SessionId command = (SessionId) openWireformat.unmarshal(dis); - assertEquals("connection ID in object: "+ i, connectionId, command.getConnectionId()); + + SessionId command = (SessionId)openWireformat.unmarshal(dis); + assertEquals("connection ID in object: " + i, connectionId, command.getConnectionId()); String actual = Long.toHexString(command.getValue()); - assertEquals("value of object: "+ i + " was: " + actual, expected, actual); + assertEquals("value of object: " + i + " was: " + actual, expected, actual); } int marker = dis.readInt(); assertEquals("Marker int", Integer.toHexString(endOfStreamMarker), Integer.toHexString(marker)); - + // lets try read and we should get an exception try { byte value = dis.readByte(); fail("Should have reached the end of the stream"); - } - catch (IOException e) { + } catch (IOException e) { // worked! } } diff --git a/activemq-core/src/test/java/org/apache/activemq/openwire/v1/ActiveMQBytesMessageTest.java b/activemq-core/src/test/java/org/apache/activemq/openwire/v1/ActiveMQBytesMessageTest.java index 4dedc0cd08..f4465ca9ae 100644 --- a/activemq-core/src/test/java/org/apache/activemq/openwire/v1/ActiveMQBytesMessageTest.java +++ b/activemq-core/src/test/java/org/apache/activemq/openwire/v1/ActiveMQBytesMessageTest.java @@ -16,40 +16,31 @@ */ package org.apache.activemq.openwire.v1; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - -import org.apache.activemq.openwire.*; -import org.apache.activemq.command.*; - +import org.apache.activemq.command.ActiveMQBytesMessage; /** * Test case for the OpenWire marshalling for ActiveMQBytesMessage - * - * - * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * + * + * + * NOTE!: This file is auto generated - do not modify! if you need to make a + * change, please see the modify the groovy scripts in the under src/gram/script + * and then use maven openwire:generate to regenerate this file. + * * @version $Revision$ */ public class ActiveMQBytesMessageTest extends ActiveMQMessageTest { - public static ActiveMQBytesMessageTest SINGLETON = new ActiveMQBytesMessageTest(); public Object createObject() throws Exception { - ActiveMQBytesMessage info = new ActiveMQBytesMessage(); - populateObject(info); - return info; + ActiveMQBytesMessage info = new ActiveMQBytesMessage(); + populateObject(info); + return info; } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ActiveMQBytesMessage info = (ActiveMQBytesMessage) object; + super.populateObject(object); + ActiveMQBytesMessage info = (ActiveMQBytesMessage)object; - } - } + } +} diff --git a/activemq-core/src/test/java/org/apache/activemq/openwire/v1/ActiveMQDestinationTestSupport.java b/activemq-core/src/test/java/org/apache/activemq/openwire/v1/ActiveMQDestinationTestSupport.java index 30c3193929..66af0fc16b 100644 --- a/activemq-core/src/test/java/org/apache/activemq/openwire/v1/ActiveMQDestinationTestSupport.java +++ b/activemq-core/src/test/java/org/apache/activemq/openwire/v1/ActiveMQDestinationTestSupport.java @@ -16,32 +16,25 @@ */ package org.apache.activemq.openwire.v1; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - -import org.apache.activemq.openwire.*; -import org.apache.activemq.command.*; - +import org.apache.activemq.command.ActiveMQDestination; +import org.apache.activemq.openwire.DataFileGeneratorTestSupport; /** * Test case for the OpenWire marshalling for ActiveMQDestination - * - * - * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * + * + * + * NOTE!: This file is auto generated - do not modify! if you need to make a + * change, please see the modify the groovy scripts in the under src/gram/script + * and then use maven openwire:generate to regenerate this file. + * * @version $Revision$ */ public abstract class ActiveMQDestinationTestSupport extends DataFileGeneratorTestSupport { - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ActiveMQDestination info = (ActiveMQDestination) object; + super.populateObject(object); + ActiveMQDestination info = (ActiveMQDestination)object; info.setPhysicalName("PhysicalName:1"); - } - } + } +} diff --git a/activemq-core/src/test/java/org/apache/activemq/openwire/v1/ActiveMQMapMessageTest.java b/activemq-core/src/test/java/org/apache/activemq/openwire/v1/ActiveMQMapMessageTest.java index 5fde7de342..ee5ca2b2ea 100644 --- a/activemq-core/src/test/java/org/apache/activemq/openwire/v1/ActiveMQMapMessageTest.java +++ b/activemq-core/src/test/java/org/apache/activemq/openwire/v1/ActiveMQMapMessageTest.java @@ -16,40 +16,31 @@ */ package org.apache.activemq.openwire.v1; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - -import org.apache.activemq.openwire.*; -import org.apache.activemq.command.*; - +import org.apache.activemq.command.ActiveMQMapMessage; /** * Test case for the OpenWire marshalling for ActiveMQMapMessage - * - * - * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * + * + * + * NOTE!: This file is auto generated - do not modify! if you need to make a + * change, please see the modify the groovy scripts in the under src/gram/script + * and then use maven openwire:generate to regenerate this file. + * * @version $Revision$ */ public class ActiveMQMapMessageTest extends ActiveMQMessageTest { - public static ActiveMQMapMessageTest SINGLETON = new ActiveMQMapMessageTest(); public Object createObject() throws Exception { - ActiveMQMapMessage info = new ActiveMQMapMessage(); - populateObject(info); - return info; + ActiveMQMapMessage info = new ActiveMQMapMessage(); + populateObject(info); + return info; } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ActiveMQMapMessage info = (ActiveMQMapMessage) object; + super.populateObject(object); + ActiveMQMapMessage info = (ActiveMQMapMessage)object; - } - } + } +} diff --git a/activemq-core/src/test/java/org/apache/activemq/openwire/v1/ActiveMQMessageTest.java b/activemq-core/src/test/java/org/apache/activemq/openwire/v1/ActiveMQMessageTest.java index 74e091a317..52fcfd3781 100644 --- a/activemq-core/src/test/java/org/apache/activemq/openwire/v1/ActiveMQMessageTest.java +++ b/activemq-core/src/test/java/org/apache/activemq/openwire/v1/ActiveMQMessageTest.java @@ -16,40 +16,31 @@ */ package org.apache.activemq.openwire.v1; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - -import org.apache.activemq.openwire.*; -import org.apache.activemq.command.*; - +import org.apache.activemq.command.ActiveMQMessage; /** * Test case for the OpenWire marshalling for ActiveMQMessage - * - * - * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * + * + * + * NOTE!: This file is auto generated - do not modify! if you need to make a + * change, please see the modify the groovy scripts in the under src/gram/script + * and then use maven openwire:generate to regenerate this file. + * * @version $Revision$ */ public class ActiveMQMessageTest extends MessageTestSupport { - public static ActiveMQMessageTest SINGLETON = new ActiveMQMessageTest(); public Object createObject() throws Exception { - ActiveMQMessage info = new ActiveMQMessage(); - populateObject(info); - return info; + ActiveMQMessage info = new ActiveMQMessage(); + populateObject(info); + return info; } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ActiveMQMessage info = (ActiveMQMessage) object; + super.populateObject(object); + ActiveMQMessage info = (ActiveMQMessage)object; - } - } + } +} diff --git a/activemq-core/src/test/java/org/apache/activemq/openwire/v1/ActiveMQObjectMessageTest.java b/activemq-core/src/test/java/org/apache/activemq/openwire/v1/ActiveMQObjectMessageTest.java index afa37275a2..aa6905f81a 100644 --- a/activemq-core/src/test/java/org/apache/activemq/openwire/v1/ActiveMQObjectMessageTest.java +++ b/activemq-core/src/test/java/org/apache/activemq/openwire/v1/ActiveMQObjectMessageTest.java @@ -16,40 +16,31 @@ */ package org.apache.activemq.openwire.v1; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - -import org.apache.activemq.openwire.*; -import org.apache.activemq.command.*; - +import org.apache.activemq.command.ActiveMQObjectMessage; /** * Test case for the OpenWire marshalling for ActiveMQObjectMessage - * - * - * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * + * + * + * NOTE!: This file is auto generated - do not modify! if you need to make a + * change, please see the modify the groovy scripts in the under src/gram/script + * and then use maven openwire:generate to regenerate this file. + * * @version $Revision$ */ public class ActiveMQObjectMessageTest extends ActiveMQMessageTest { - public static ActiveMQObjectMessageTest SINGLETON = new ActiveMQObjectMessageTest(); public Object createObject() throws Exception { - ActiveMQObjectMessage info = new ActiveMQObjectMessage(); - populateObject(info); - return info; + ActiveMQObjectMessage info = new ActiveMQObjectMessage(); + populateObject(info); + return info; } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ActiveMQObjectMessage info = (ActiveMQObjectMessage) object; + super.populateObject(object); + ActiveMQObjectMessage info = (ActiveMQObjectMessage)object; - } - } + } +} diff --git a/activemq-core/src/test/java/org/apache/activemq/openwire/v1/ActiveMQQueueTest.java b/activemq-core/src/test/java/org/apache/activemq/openwire/v1/ActiveMQQueueTest.java index 0cb4d2def4..47a8f220d6 100644 --- a/activemq-core/src/test/java/org/apache/activemq/openwire/v1/ActiveMQQueueTest.java +++ b/activemq-core/src/test/java/org/apache/activemq/openwire/v1/ActiveMQQueueTest.java @@ -16,40 +16,29 @@ */ package org.apache.activemq.openwire.v1; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - -import org.apache.activemq.openwire.*; -import org.apache.activemq.command.*; - +import org.apache.activemq.command.ActiveMQQueue; /** - * Test case for the OpenWire marshalling for ActiveMQQueue - * - * - * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * + * Test case for the OpenWire marshalling for ActiveMQQueue NOTE!: This file is + * auto generated - do not modify! if you need to make a change, please see the + * modify the groovy scripts in the under src/gram/script and then use maven + * openwire:generate to regenerate this file. + * * @version $Revision$ */ public class ActiveMQQueueTest extends ActiveMQDestinationTestSupport { - public static ActiveMQQueueTest SINGLETON = new ActiveMQQueueTest(); public Object createObject() throws Exception { - ActiveMQQueue info = new ActiveMQQueue(); - populateObject(info); - return info; + ActiveMQQueue info = new ActiveMQQueue(); + populateObject(info); + return info; } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ActiveMQQueue info = (ActiveMQQueue) object; + super.populateObject(object); + ActiveMQQueue info = (ActiveMQQueue)object; - } - } + } +} diff --git a/activemq-core/src/test/java/org/apache/activemq/openwire/v1/ActiveMQStreamMessageTest.java b/activemq-core/src/test/java/org/apache/activemq/openwire/v1/ActiveMQStreamMessageTest.java index 7b56d47609..7dcbdbff62 100644 --- a/activemq-core/src/test/java/org/apache/activemq/openwire/v1/ActiveMQStreamMessageTest.java +++ b/activemq-core/src/test/java/org/apache/activemq/openwire/v1/ActiveMQStreamMessageTest.java @@ -16,40 +16,29 @@ */ package org.apache.activemq.openwire.v1; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - -import org.apache.activemq.openwire.*; -import org.apache.activemq.command.*; - +import org.apache.activemq.command.ActiveMQStreamMessage; /** - * Test case for the OpenWire marshalling for ActiveMQStreamMessage - * - * - * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * + * Test case for the OpenWire marshalling for ActiveMQStreamMessage NOTE!: This + * file is auto generated - do not modify! if you need to make a change, please + * see the modify the groovy scripts in the under src/gram/script and then use + * maven openwire:generate to regenerate this file. + * * @version $Revision$ */ public class ActiveMQStreamMessageTest extends ActiveMQMessageTest { - public static ActiveMQStreamMessageTest SINGLETON = new ActiveMQStreamMessageTest(); public Object createObject() throws Exception { - ActiveMQStreamMessage info = new ActiveMQStreamMessage(); - populateObject(info); - return info; + ActiveMQStreamMessage info = new ActiveMQStreamMessage(); + populateObject(info); + return info; } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ActiveMQStreamMessage info = (ActiveMQStreamMessage) object; + super.populateObject(object); + ActiveMQStreamMessage info = (ActiveMQStreamMessage)object; - } - } + } +} diff --git a/activemq-core/src/test/java/org/apache/activemq/openwire/v1/ActiveMQTempDestinationTestSupport.java b/activemq-core/src/test/java/org/apache/activemq/openwire/v1/ActiveMQTempDestinationTestSupport.java index def0d1607e..8ccc89256e 100644 --- a/activemq-core/src/test/java/org/apache/activemq/openwire/v1/ActiveMQTempDestinationTestSupport.java +++ b/activemq-core/src/test/java/org/apache/activemq/openwire/v1/ActiveMQTempDestinationTestSupport.java @@ -16,31 +16,21 @@ */ package org.apache.activemq.openwire.v1; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - -import org.apache.activemq.openwire.*; -import org.apache.activemq.command.*; - +import org.apache.activemq.command.ActiveMQTempDestination; /** - * Test case for the OpenWire marshalling for ActiveMQTempDestination - * - * - * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * + * Test case for the OpenWire marshalling for ActiveMQTempDestination NOTE!: + * This file is auto generated - do not modify! if you need to make a change, + * please see the modify the groovy scripts in the under src/gram/script and + * then use maven openwire:generate to regenerate this file. + * * @version $Revision$ */ public abstract class ActiveMQTempDestinationTestSupport extends ActiveMQDestinationTestSupport { - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ActiveMQTempDestination info = (ActiveMQTempDestination) object; + super.populateObject(object); + ActiveMQTempDestination info = (ActiveMQTempDestination)object; - } - } + } +} diff --git a/activemq-core/src/test/java/org/apache/activemq/openwire/v1/ActiveMQTempQueueTest.java b/activemq-core/src/test/java/org/apache/activemq/openwire/v1/ActiveMQTempQueueTest.java index 5a00b57067..0e1d885f4c 100644 --- a/activemq-core/src/test/java/org/apache/activemq/openwire/v1/ActiveMQTempQueueTest.java +++ b/activemq-core/src/test/java/org/apache/activemq/openwire/v1/ActiveMQTempQueueTest.java @@ -16,40 +16,29 @@ */ package org.apache.activemq.openwire.v1; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - -import org.apache.activemq.openwire.*; -import org.apache.activemq.command.*; - +import org.apache.activemq.command.ActiveMQTempQueue; /** - * Test case for the OpenWire marshalling for ActiveMQTempQueue - * - * - * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * + * Test case for the OpenWire marshalling for ActiveMQTempQueue NOTE!: This file + * is auto generated - do not modify! if you need to make a change, please see + * the modify the groovy scripts in the under src/gram/script and then use maven + * openwire:generate to regenerate this file. + * * @version $Revision$ */ public class ActiveMQTempQueueTest extends ActiveMQTempDestinationTestSupport { - public static ActiveMQTempQueueTest SINGLETON = new ActiveMQTempQueueTest(); public Object createObject() throws Exception { - ActiveMQTempQueue info = new ActiveMQTempQueue(); - populateObject(info); - return info; + ActiveMQTempQueue info = new ActiveMQTempQueue(); + populateObject(info); + return info; } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ActiveMQTempQueue info = (ActiveMQTempQueue) object; + super.populateObject(object); + ActiveMQTempQueue info = (ActiveMQTempQueue)object; - } - } + } +} diff --git a/activemq-core/src/test/java/org/apache/activemq/openwire/v1/ActiveMQTempTopicTest.java b/activemq-core/src/test/java/org/apache/activemq/openwire/v1/ActiveMQTempTopicTest.java index ca610241fe..8b3a43f542 100644 --- a/activemq-core/src/test/java/org/apache/activemq/openwire/v1/ActiveMQTempTopicTest.java +++ b/activemq-core/src/test/java/org/apache/activemq/openwire/v1/ActiveMQTempTopicTest.java @@ -16,40 +16,29 @@ */ package org.apache.activemq.openwire.v1; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - -import org.apache.activemq.openwire.*; -import org.apache.activemq.command.*; - +import org.apache.activemq.command.ActiveMQTempTopic; /** - * Test case for the OpenWire marshalling for ActiveMQTempTopic - * - * - * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * + * Test case for the OpenWire marshalling for ActiveMQTempTopic NOTE!: This file + * is auto generated - do not modify! if you need to make a change, please see + * the modify the groovy scripts in the under src/gram/script and then use maven + * openwire:generate to regenerate this file. + * * @version $Revision$ */ public class ActiveMQTempTopicTest extends ActiveMQTempDestinationTestSupport { - public static ActiveMQTempTopicTest SINGLETON = new ActiveMQTempTopicTest(); public Object createObject() throws Exception { - ActiveMQTempTopic info = new ActiveMQTempTopic(); - populateObject(info); - return info; + ActiveMQTempTopic info = new ActiveMQTempTopic(); + populateObject(info); + return info; } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ActiveMQTempTopic info = (ActiveMQTempTopic) object; + super.populateObject(object); + ActiveMQTempTopic info = (ActiveMQTempTopic)object; - } - } + } +} diff --git a/activemq-core/src/test/java/org/apache/activemq/openwire/v1/ActiveMQTextMessageTest.java b/activemq-core/src/test/java/org/apache/activemq/openwire/v1/ActiveMQTextMessageTest.java index 7bf71e460a..9120808c48 100644 --- a/activemq-core/src/test/java/org/apache/activemq/openwire/v1/ActiveMQTextMessageTest.java +++ b/activemq-core/src/test/java/org/apache/activemq/openwire/v1/ActiveMQTextMessageTest.java @@ -16,40 +16,29 @@ */ package org.apache.activemq.openwire.v1; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - -import org.apache.activemq.openwire.*; -import org.apache.activemq.command.*; - +import org.apache.activemq.command.ActiveMQTextMessage; /** - * Test case for the OpenWire marshalling for ActiveMQTextMessage - * - * - * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * + * Test case for the OpenWire marshalling for ActiveMQTextMessage NOTE!: This + * file is auto generated - do not modify! if you need to make a change, please + * see the modify the groovy scripts in the under src/gram/script and then use + * maven openwire:generate to regenerate this file. + * * @version $Revision$ */ public class ActiveMQTextMessageTest extends ActiveMQMessageTest { - public static final ActiveMQTextMessageTest SINGLETON = new ActiveMQTextMessageTest(); public Object createObject() throws Exception { - ActiveMQTextMessage info = new ActiveMQTextMessage(); - populateObject(info); - return info; + ActiveMQTextMessage info = new ActiveMQTextMessage(); + populateObject(info); + return info; } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ActiveMQTextMessage info = (ActiveMQTextMessage) object; + super.populateObject(object); + ActiveMQTextMessage info = (ActiveMQTextMessage)object; - } - } + } +} diff --git a/activemq-core/src/test/java/org/apache/activemq/openwire/v1/ActiveMQTopicTest.java b/activemq-core/src/test/java/org/apache/activemq/openwire/v1/ActiveMQTopicTest.java index a29c4d5ab0..d924ef07ce 100644 --- a/activemq-core/src/test/java/org/apache/activemq/openwire/v1/ActiveMQTopicTest.java +++ b/activemq-core/src/test/java/org/apache/activemq/openwire/v1/ActiveMQTopicTest.java @@ -16,40 +16,29 @@ */ package org.apache.activemq.openwire.v1; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - -import org.apache.activemq.openwire.*; -import org.apache.activemq.command.*; - +import org.apache.activemq.command.ActiveMQTopic; /** - * Test case for the OpenWire marshalling for ActiveMQTopic - * - * - * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * + * Test case for the OpenWire marshalling for ActiveMQTopic NOTE!: This file is + * auto generated - do not modify! if you need to make a change, please see the + * modify the groovy scripts in the under src/gram/script and then use maven + * openwire:generate to regenerate this file. + * * @version $Revision$ */ public class ActiveMQTopicTest extends ActiveMQDestinationTestSupport { - public static ActiveMQTopicTest SINGLETON = new ActiveMQTopicTest(); public Object createObject() throws Exception { - ActiveMQTopic info = new ActiveMQTopic(); - populateObject(info); - return info; + ActiveMQTopic info = new ActiveMQTopic(); + populateObject(info); + return info; } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ActiveMQTopic info = (ActiveMQTopic) object; + super.populateObject(object); + ActiveMQTopic info = (ActiveMQTopic)object; - } - } + } +} diff --git a/activemq-core/src/test/java/org/apache/activemq/openwire/v1/BaseCommandTestSupport.java b/activemq-core/src/test/java/org/apache/activemq/openwire/v1/BaseCommandTestSupport.java index 224e99a90e..087cdca8c9 100644 --- a/activemq-core/src/test/java/org/apache/activemq/openwire/v1/BaseCommandTestSupport.java +++ b/activemq-core/src/test/java/org/apache/activemq/openwire/v1/BaseCommandTestSupport.java @@ -16,33 +16,24 @@ */ package org.apache.activemq.openwire.v1; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - -import org.apache.activemq.openwire.*; -import org.apache.activemq.command.*; - +import org.apache.activemq.command.BaseCommand; +import org.apache.activemq.openwire.DataFileGeneratorTestSupport; /** - * Test case for the OpenWire marshalling for BaseCommand - * - * - * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * + * Test case for the OpenWire marshalling for BaseCommand NOTE!: This file is + * auto generated - do not modify! if you need to make a change, please see the + * modify the groovy scripts in the under src/gram/script and then use maven + * openwire:generate to regenerate this file. + * * @version $Revision$ */ public abstract class BaseCommandTestSupport extends DataFileGeneratorTestSupport { - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - BaseCommand info = (BaseCommand) object; + super.populateObject(object); + BaseCommand info = (BaseCommand)object; info.setCommandId(1); info.setResponseRequired(true); - } - } + } +} diff --git a/activemq-core/src/test/java/org/apache/activemq/openwire/v1/BrokerIdTest.java b/activemq-core/src/test/java/org/apache/activemq/openwire/v1/BrokerIdTest.java index 35e0382f08..27ae573b99 100644 --- a/activemq-core/src/test/java/org/apache/activemq/openwire/v1/BrokerIdTest.java +++ b/activemq-core/src/test/java/org/apache/activemq/openwire/v1/BrokerIdTest.java @@ -16,41 +16,33 @@ */ package org.apache.activemq.openwire.v1; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - -import org.apache.activemq.openwire.*; -import org.apache.activemq.command.*; - +import org.apache.activemq.command.BrokerId; +import org.apache.activemq.openwire.DataFileGeneratorTestSupport; /** * Test case for the OpenWire marshalling for BrokerId - * - * - * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * + * + * + * NOTE!: This file is auto generated - do not modify! if you need to make a + * change, please see the modify the groovy scripts in the under src/gram/script + * and then use maven openwire:generate to regenerate this file. + * * @version $Revision$ */ public class BrokerIdTest extends DataFileGeneratorTestSupport { - public static BrokerIdTest SINGLETON = new BrokerIdTest(); public Object createObject() throws Exception { - BrokerId info = new BrokerId(); - populateObject(info); - return info; + BrokerId info = new BrokerId(); + populateObject(info); + return info; } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - BrokerId info = (BrokerId) object; + super.populateObject(object); + BrokerId info = (BrokerId)object; info.setValue("Value:1"); - } - } + } +} diff --git a/activemq-core/src/test/java/org/apache/activemq/openwire/v1/ConnectionControlTest.java b/activemq-core/src/test/java/org/apache/activemq/openwire/v1/ConnectionControlTest.java index d346175308..018dfda531 100644 --- a/activemq-core/src/test/java/org/apache/activemq/openwire/v1/ConnectionControlTest.java +++ b/activemq-core/src/test/java/org/apache/activemq/openwire/v1/ConnectionControlTest.java @@ -16,45 +16,36 @@ */ package org.apache.activemq.openwire.v1; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - -import org.apache.activemq.openwire.*; -import org.apache.activemq.command.*; - +import org.apache.activemq.command.ConnectionControl; /** * Test case for the OpenWire marshalling for ConnectionControl - * - * - * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * + * + * + * NOTE!: This file is auto generated - do not modify! if you need to make a + * change, please see the modify the groovy scripts in the under src/gram/script + * and then use maven openwire:generate to regenerate this file. + * * @version $Revision: $ */ public class ConnectionControlTest extends BaseCommandTestSupport { - public static ConnectionControlTest SINGLETON = new ConnectionControlTest(); public Object createObject() throws Exception { - ConnectionControl info = new ConnectionControl(); - populateObject(info); - return info; + ConnectionControl info = new ConnectionControl(); + populateObject(info); + return info; } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ConnectionControl info = (ConnectionControl) object; + super.populateObject(object); + ConnectionControl info = (ConnectionControl)object; info.setClose(true); info.setExit(false); info.setFaultTolerant(true); info.setResume(false); info.setSuspend(true); - } - } + } +} diff --git a/activemq-core/src/test/java/org/apache/activemq/openwire/v1/ConnectionErrorTest.java b/activemq-core/src/test/java/org/apache/activemq/openwire/v1/ConnectionErrorTest.java index 822aedd15b..405f93297d 100644 --- a/activemq-core/src/test/java/org/apache/activemq/openwire/v1/ConnectionErrorTest.java +++ b/activemq-core/src/test/java/org/apache/activemq/openwire/v1/ConnectionErrorTest.java @@ -16,42 +16,33 @@ */ package org.apache.activemq.openwire.v1; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - -import org.apache.activemq.openwire.*; -import org.apache.activemq.command.*; - +import org.apache.activemq.command.ConnectionError; /** * Test case for the OpenWire marshalling for ConnectionError - * - * - * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * + * + * + * NOTE!: This file is auto generated - do not modify! if you need to make a + * change, please see the modify the groovy scripts in the under src/gram/script + * and then use maven openwire:generate to regenerate this file. + * * @version $Revision$ */ public class ConnectionErrorTest extends BaseCommandTestSupport { - public static ConnectionErrorTest SINGLETON = new ConnectionErrorTest(); public Object createObject() throws Exception { - ConnectionError info = new ConnectionError(); - populateObject(info); - return info; + ConnectionError info = new ConnectionError(); + populateObject(info); + return info; } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ConnectionError info = (ConnectionError) object; + super.populateObject(object); + ConnectionError info = (ConnectionError)object; info.setException(createThrowable("Exception:1")); info.setConnectionId(createConnectionId("ConnectionId:2")); - } - } + } +} diff --git a/activemq-core/src/test/java/org/apache/activemq/openwire/v1/ConnectionIdTest.java b/activemq-core/src/test/java/org/apache/activemq/openwire/v1/ConnectionIdTest.java index 01ce36ac4c..c72bcd9a17 100644 --- a/activemq-core/src/test/java/org/apache/activemq/openwire/v1/ConnectionIdTest.java +++ b/activemq-core/src/test/java/org/apache/activemq/openwire/v1/ConnectionIdTest.java @@ -16,41 +16,33 @@ */ package org.apache.activemq.openwire.v1; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - -import org.apache.activemq.openwire.*; -import org.apache.activemq.command.*; - +import org.apache.activemq.command.ConnectionId; +import org.apache.activemq.openwire.DataFileGeneratorTestSupport; /** * Test case for the OpenWire marshalling for ConnectionId - * - * - * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * + * + * + * NOTE!: This file is auto generated - do not modify! if you need to make a + * change, please see the modify the groovy scripts in the under src/gram/script + * and then use maven openwire:generate to regenerate this file. + * * @version $Revision$ */ public class ConnectionIdTest extends DataFileGeneratorTestSupport { - public static ConnectionIdTest SINGLETON = new ConnectionIdTest(); public Object createObject() throws Exception { - ConnectionId info = new ConnectionId(); - populateObject(info); - return info; + ConnectionId info = new ConnectionId(); + populateObject(info); + return info; } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ConnectionId info = (ConnectionId) object; + super.populateObject(object); + ConnectionId info = (ConnectionId)object; info.setValue("Value:1"); - } - } + } +} diff --git a/activemq-core/src/test/java/org/apache/activemq/openwire/v1/ConsumerControlTest.java b/activemq-core/src/test/java/org/apache/activemq/openwire/v1/ConsumerControlTest.java index ea302b6bbf..6f488b0c1c 100644 --- a/activemq-core/src/test/java/org/apache/activemq/openwire/v1/ConsumerControlTest.java +++ b/activemq-core/src/test/java/org/apache/activemq/openwire/v1/ConsumerControlTest.java @@ -16,43 +16,34 @@ */ package org.apache.activemq.openwire.v1; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - -import org.apache.activemq.openwire.*; -import org.apache.activemq.command.*; - +import org.apache.activemq.command.ConsumerControl; /** * Test case for the OpenWire marshalling for ConsumerControl - * - * - * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * + * + * + * NOTE!: This file is auto generated - do not modify! if you need to make a + * change, please see the modify the groovy scripts in the under src/gram/script + * and then use maven openwire:generate to regenerate this file. + * * @version $Revision: $ */ public class ConsumerControlTest extends BaseCommandTestSupport { - public static ConsumerControlTest SINGLETON = new ConsumerControlTest(); public Object createObject() throws Exception { - ConsumerControl info = new ConsumerControl(); - populateObject(info); - return info; + ConsumerControl info = new ConsumerControl(); + populateObject(info); + return info; } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ConsumerControl info = (ConsumerControl) object; + super.populateObject(object); + ConsumerControl info = (ConsumerControl)object; info.setClose(true); info.setConsumerId(createConsumerId("ConsumerId:1")); info.setPrefetch(1); - } - } + } +} diff --git a/activemq-core/src/test/java/org/apache/activemq/openwire/v1/ConsumerIdTest.java b/activemq-core/src/test/java/org/apache/activemq/openwire/v1/ConsumerIdTest.java index fb0fcdcf37..d4fa2965e4 100644 --- a/activemq-core/src/test/java/org/apache/activemq/openwire/v1/ConsumerIdTest.java +++ b/activemq-core/src/test/java/org/apache/activemq/openwire/v1/ConsumerIdTest.java @@ -16,43 +16,35 @@ */ package org.apache.activemq.openwire.v1; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - -import org.apache.activemq.openwire.*; -import org.apache.activemq.command.*; - +import org.apache.activemq.command.ConsumerId; +import org.apache.activemq.openwire.DataFileGeneratorTestSupport; /** * Test case for the OpenWire marshalling for ConsumerId - * - * - * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * + * + * + * NOTE!: This file is auto generated - do not modify! if you need to make a + * change, please see the modify the groovy scripts in the under src/gram/script + * and then use maven openwire:generate to regenerate this file. + * * @version $Revision$ */ public class ConsumerIdTest extends DataFileGeneratorTestSupport { - public static ConsumerIdTest SINGLETON = new ConsumerIdTest(); public Object createObject() throws Exception { - ConsumerId info = new ConsumerId(); - populateObject(info); - return info; + ConsumerId info = new ConsumerId(); + populateObject(info); + return info; } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ConsumerId info = (ConsumerId) object; + super.populateObject(object); + ConsumerId info = (ConsumerId)object; info.setConnectionId("ConnectionId:1"); info.setSessionId(1); info.setValue(2); - } - } + } +} diff --git a/activemq-core/src/test/java/org/apache/activemq/openwire/v1/ControlCommandTest.java b/activemq-core/src/test/java/org/apache/activemq/openwire/v1/ControlCommandTest.java index a9961531d9..841549b896 100644 --- a/activemq-core/src/test/java/org/apache/activemq/openwire/v1/ControlCommandTest.java +++ b/activemq-core/src/test/java/org/apache/activemq/openwire/v1/ControlCommandTest.java @@ -16,41 +16,32 @@ */ package org.apache.activemq.openwire.v1; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - -import org.apache.activemq.openwire.*; -import org.apache.activemq.command.*; - +import org.apache.activemq.command.ControlCommand; /** * Test case for the OpenWire marshalling for ControlCommand - * - * - * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * + * + * + * NOTE!: This file is auto generated - do not modify! if you need to make a + * change, please see the modify the groovy scripts in the under src/gram/script + * and then use maven openwire:generate to regenerate this file. + * * @version $Revision$ */ public class ControlCommandTest extends BaseCommandTestSupport { - public static ControlCommandTest SINGLETON = new ControlCommandTest(); public Object createObject() throws Exception { - ControlCommand info = new ControlCommand(); - populateObject(info); - return info; + ControlCommand info = new ControlCommand(); + populateObject(info); + return info; } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ControlCommand info = (ControlCommand) object; + super.populateObject(object); + ControlCommand info = (ControlCommand)object; info.setCommand("Command:1"); - } - } + } +} diff --git a/activemq-core/src/test/java/org/apache/activemq/openwire/v1/DataResponseTest.java b/activemq-core/src/test/java/org/apache/activemq/openwire/v1/DataResponseTest.java index 14396df609..19bc096c1d 100644 --- a/activemq-core/src/test/java/org/apache/activemq/openwire/v1/DataResponseTest.java +++ b/activemq-core/src/test/java/org/apache/activemq/openwire/v1/DataResponseTest.java @@ -16,41 +16,32 @@ */ package org.apache.activemq.openwire.v1; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - -import org.apache.activemq.openwire.*; -import org.apache.activemq.command.*; - +import org.apache.activemq.command.DataResponse; /** * Test case for the OpenWire marshalling for DataResponse - * - * - * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * + * + * + * NOTE!: This file is auto generated - do not modify! if you need to make a + * change, please see the modify the groovy scripts in the under src/gram/script + * and then use maven openwire:generate to regenerate this file. + * * @version $Revision$ */ public class DataResponseTest extends ResponseTest { - public static DataResponseTest SINGLETON = new DataResponseTest(); public Object createObject() throws Exception { - DataResponse info = new DataResponse(); - populateObject(info); - return info; + DataResponse info = new DataResponse(); + populateObject(info); + return info; } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - DataResponse info = (DataResponse) object; + super.populateObject(object); + DataResponse info = (DataResponse)object; info.setData(createDataStructure("Data:1")); - } - } + } +} diff --git a/activemq-core/src/test/java/org/apache/activemq/openwire/v1/DiscoveryEventTest.java b/activemq-core/src/test/java/org/apache/activemq/openwire/v1/DiscoveryEventTest.java index baec32c7b4..82925f1188 100644 --- a/activemq-core/src/test/java/org/apache/activemq/openwire/v1/DiscoveryEventTest.java +++ b/activemq-core/src/test/java/org/apache/activemq/openwire/v1/DiscoveryEventTest.java @@ -16,42 +16,34 @@ */ package org.apache.activemq.openwire.v1; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - -import org.apache.activemq.openwire.*; -import org.apache.activemq.command.*; - +import org.apache.activemq.command.DiscoveryEvent; +import org.apache.activemq.openwire.DataFileGeneratorTestSupport; /** * Test case for the OpenWire marshalling for DiscoveryEvent - * - * - * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * + * + * + * NOTE!: This file is auto generated - do not modify! if you need to make a + * change, please see the modify the groovy scripts in the under src/gram/script + * and then use maven openwire:generate to regenerate this file. + * * @version $Revision$ */ public class DiscoveryEventTest extends DataFileGeneratorTestSupport { - public static DiscoveryEventTest SINGLETON = new DiscoveryEventTest(); public Object createObject() throws Exception { - DiscoveryEvent info = new DiscoveryEvent(); - populateObject(info); - return info; + DiscoveryEvent info = new DiscoveryEvent(); + populateObject(info); + return info; } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - DiscoveryEvent info = (DiscoveryEvent) object; + super.populateObject(object); + DiscoveryEvent info = (DiscoveryEvent)object; info.setServiceName("ServiceName:1"); info.setBrokerName("BrokerName:2"); - } - } + } +} diff --git a/activemq-core/src/test/java/org/apache/activemq/openwire/v1/ExceptionResponseTest.java b/activemq-core/src/test/java/org/apache/activemq/openwire/v1/ExceptionResponseTest.java index 6375f6f4b1..c2ad8f1b70 100644 --- a/activemq-core/src/test/java/org/apache/activemq/openwire/v1/ExceptionResponseTest.java +++ b/activemq-core/src/test/java/org/apache/activemq/openwire/v1/ExceptionResponseTest.java @@ -16,41 +16,32 @@ */ package org.apache.activemq.openwire.v1; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - -import org.apache.activemq.openwire.*; -import org.apache.activemq.command.*; - +import org.apache.activemq.command.ExceptionResponse; /** * Test case for the OpenWire marshalling for ExceptionResponse - * - * - * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * + * + * + * NOTE!: This file is auto generated - do not modify! if you need to make a + * change, please see the modify the groovy scripts in the under src/gram/script + * and then use maven openwire:generate to regenerate this file. + * * @version $Revision$ */ public class ExceptionResponseTest extends ResponseTest { - public static ExceptionResponseTest SINGLETON = new ExceptionResponseTest(); public Object createObject() throws Exception { - ExceptionResponse info = new ExceptionResponse(); - populateObject(info); - return info; + ExceptionResponse info = new ExceptionResponse(); + populateObject(info); + return info; } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ExceptionResponse info = (ExceptionResponse) object; + super.populateObject(object); + ExceptionResponse info = (ExceptionResponse)object; info.setException(createThrowable("Exception:1")); - } - } + } +} diff --git a/activemq-core/src/test/java/org/apache/activemq/openwire/v1/FlushCommandTest.java b/activemq-core/src/test/java/org/apache/activemq/openwire/v1/FlushCommandTest.java index 2397043fcb..170a8fb61b 100644 --- a/activemq-core/src/test/java/org/apache/activemq/openwire/v1/FlushCommandTest.java +++ b/activemq-core/src/test/java/org/apache/activemq/openwire/v1/FlushCommandTest.java @@ -16,40 +16,31 @@ */ package org.apache.activemq.openwire.v1; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - -import org.apache.activemq.openwire.*; -import org.apache.activemq.command.*; - +import org.apache.activemq.command.FlushCommand; /** * Test case for the OpenWire marshalling for FlushCommand - * - * - * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * + * + * + * NOTE!: This file is auto generated - do not modify! if you need to make a + * change, please see the modify the groovy scripts in the under src/gram/script + * and then use maven openwire:generate to regenerate this file. + * * @version $Revision$ */ public class FlushCommandTest extends BaseCommandTestSupport { - public static FlushCommandTest SINGLETON = new FlushCommandTest(); public Object createObject() throws Exception { - FlushCommand info = new FlushCommand(); - populateObject(info); - return info; + FlushCommand info = new FlushCommand(); + populateObject(info); + return info; } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - FlushCommand info = (FlushCommand) object; + super.populateObject(object); + FlushCommand info = (FlushCommand)object; - } - } + } +} diff --git a/activemq-core/src/test/java/org/apache/activemq/openwire/v1/IntegerResponseTest.java b/activemq-core/src/test/java/org/apache/activemq/openwire/v1/IntegerResponseTest.java index 181708d185..5cbb40f1d9 100644 --- a/activemq-core/src/test/java/org/apache/activemq/openwire/v1/IntegerResponseTest.java +++ b/activemq-core/src/test/java/org/apache/activemq/openwire/v1/IntegerResponseTest.java @@ -16,41 +16,32 @@ */ package org.apache.activemq.openwire.v1; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - -import org.apache.activemq.openwire.*; -import org.apache.activemq.command.*; - +import org.apache.activemq.command.IntegerResponse; /** * Test case for the OpenWire marshalling for IntegerResponse - * - * - * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * + * + * + * NOTE!: This file is auto generated - do not modify! if you need to make a + * change, please see the modify the groovy scripts in the under src/gram/script + * and then use maven openwire:generate to regenerate this file. + * * @version $Revision$ */ public class IntegerResponseTest extends ResponseTest { - public static IntegerResponseTest SINGLETON = new IntegerResponseTest(); public Object createObject() throws Exception { - IntegerResponse info = new IntegerResponse(); - populateObject(info); - return info; + IntegerResponse info = new IntegerResponse(); + populateObject(info); + return info; } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - IntegerResponse info = (IntegerResponse) object; + super.populateObject(object); + IntegerResponse info = (IntegerResponse)object; info.setResult(1); - } - } + } +} diff --git a/activemq-core/src/test/java/org/apache/activemq/openwire/v1/JournalQueueAckTest.java b/activemq-core/src/test/java/org/apache/activemq/openwire/v1/JournalQueueAckTest.java index 25e50b7aa2..6a00edfadd 100644 --- a/activemq-core/src/test/java/org/apache/activemq/openwire/v1/JournalQueueAckTest.java +++ b/activemq-core/src/test/java/org/apache/activemq/openwire/v1/JournalQueueAckTest.java @@ -16,42 +16,34 @@ */ package org.apache.activemq.openwire.v1; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - -import org.apache.activemq.openwire.*; -import org.apache.activemq.command.*; - +import org.apache.activemq.command.JournalQueueAck; +import org.apache.activemq.openwire.DataFileGeneratorTestSupport; /** * Test case for the OpenWire marshalling for JournalQueueAck - * - * - * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * + * + * + * NOTE!: This file is auto generated - do not modify! if you need to make a + * change, please see the modify the groovy scripts in the under src/gram/script + * and then use maven openwire:generate to regenerate this file. + * * @version $Revision$ */ public class JournalQueueAckTest extends DataFileGeneratorTestSupport { - public static JournalQueueAckTest SINGLETON = new JournalQueueAckTest(); public Object createObject() throws Exception { - JournalQueueAck info = new JournalQueueAck(); - populateObject(info); - return info; + JournalQueueAck info = new JournalQueueAck(); + populateObject(info); + return info; } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - JournalQueueAck info = (JournalQueueAck) object; + super.populateObject(object); + JournalQueueAck info = (JournalQueueAck)object; info.setDestination(createActiveMQDestination("Destination:1")); info.setMessageAck(createMessageAck("MessageAck:2")); - } - } + } +} diff --git a/activemq-core/src/test/java/org/apache/activemq/openwire/v1/JournalTopicAckTest.java b/activemq-core/src/test/java/org/apache/activemq/openwire/v1/JournalTopicAckTest.java index a74eb2f082..3b025dd207 100644 --- a/activemq-core/src/test/java/org/apache/activemq/openwire/v1/JournalTopicAckTest.java +++ b/activemq-core/src/test/java/org/apache/activemq/openwire/v1/JournalTopicAckTest.java @@ -16,40 +16,32 @@ */ package org.apache.activemq.openwire.v1; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - -import org.apache.activemq.openwire.*; -import org.apache.activemq.command.*; - +import org.apache.activemq.command.JournalTopicAck; +import org.apache.activemq.openwire.DataFileGeneratorTestSupport; /** * Test case for the OpenWire marshalling for JournalTopicAck - * - * - * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * + * + * + * NOTE!: This file is auto generated - do not modify! if you need to make a + * change, please see the modify the groovy scripts in the under src/gram/script + * and then use maven openwire:generate to regenerate this file. + * * @version $Revision$ */ public class JournalTopicAckTest extends DataFileGeneratorTestSupport { - public static JournalTopicAckTest SINGLETON = new JournalTopicAckTest(); public Object createObject() throws Exception { - JournalTopicAck info = new JournalTopicAck(); - populateObject(info); - return info; + JournalTopicAck info = new JournalTopicAck(); + populateObject(info); + return info; } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - JournalTopicAck info = (JournalTopicAck) object; + super.populateObject(object); + JournalTopicAck info = (JournalTopicAck)object; info.setDestination(createActiveMQDestination("Destination:1")); info.setMessageId(createMessageId("MessageId:2")); info.setMessageSequenceId(1); @@ -57,5 +49,5 @@ public class JournalTopicAckTest extends DataFileGeneratorTestSupport { info.setClientId("ClientId:4"); info.setTransactionId(createTransactionId("TransactionId:5")); - } - } + } +} diff --git a/activemq-core/src/test/java/org/apache/activemq/openwire/v1/JournalTraceTest.java b/activemq-core/src/test/java/org/apache/activemq/openwire/v1/JournalTraceTest.java index bacba760a2..b849970752 100644 --- a/activemq-core/src/test/java/org/apache/activemq/openwire/v1/JournalTraceTest.java +++ b/activemq-core/src/test/java/org/apache/activemq/openwire/v1/JournalTraceTest.java @@ -16,41 +16,33 @@ */ package org.apache.activemq.openwire.v1; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - -import org.apache.activemq.openwire.*; -import org.apache.activemq.command.*; - +import org.apache.activemq.command.JournalTrace; +import org.apache.activemq.openwire.DataFileGeneratorTestSupport; /** * Test case for the OpenWire marshalling for JournalTrace - * - * - * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * + * + * + * NOTE!: This file is auto generated - do not modify! if you need to make a + * change, please see the modify the groovy scripts in the under src/gram/script + * and then use maven openwire:generate to regenerate this file. + * * @version $Revision$ */ public class JournalTraceTest extends DataFileGeneratorTestSupport { - public static JournalTraceTest SINGLETON = new JournalTraceTest(); public Object createObject() throws Exception { - JournalTrace info = new JournalTrace(); - populateObject(info); - return info; + JournalTrace info = new JournalTrace(); + populateObject(info); + return info; } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - JournalTrace info = (JournalTrace) object; + super.populateObject(object); + JournalTrace info = (JournalTrace)object; info.setMessage("Message:1"); - } - } + } +} diff --git a/activemq-core/src/test/java/org/apache/activemq/openwire/v1/JournalTransactionTest.java b/activemq-core/src/test/java/org/apache/activemq/openwire/v1/JournalTransactionTest.java index 70a5d99b16..7de2e39e69 100644 --- a/activemq-core/src/test/java/org/apache/activemq/openwire/v1/JournalTransactionTest.java +++ b/activemq-core/src/test/java/org/apache/activemq/openwire/v1/JournalTransactionTest.java @@ -16,43 +16,35 @@ */ package org.apache.activemq.openwire.v1; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - -import org.apache.activemq.openwire.*; -import org.apache.activemq.command.*; - +import org.apache.activemq.command.JournalTransaction; +import org.apache.activemq.openwire.DataFileGeneratorTestSupport; /** * Test case for the OpenWire marshalling for JournalTransaction - * - * - * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * + * + * + * NOTE!: This file is auto generated - do not modify! if you need to make a + * change, please see the modify the groovy scripts in the under src/gram/script + * and then use maven openwire:generate to regenerate this file. + * * @version $Revision$ */ public class JournalTransactionTest extends DataFileGeneratorTestSupport { - public static JournalTransactionTest SINGLETON = new JournalTransactionTest(); public Object createObject() throws Exception { - JournalTransaction info = new JournalTransaction(); - populateObject(info); - return info; + JournalTransaction info = new JournalTransaction(); + populateObject(info); + return info; } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - JournalTransaction info = (JournalTransaction) object; + super.populateObject(object); + JournalTransaction info = (JournalTransaction)object; info.setTransactionId(createTransactionId("TransactionId:1")); - info.setType((byte) 1); + info.setType((byte)1); info.setWasPrepared(true); - } - } + } +} diff --git a/activemq-core/src/test/java/org/apache/activemq/openwire/v1/KeepAliveInfoTest.java b/activemq-core/src/test/java/org/apache/activemq/openwire/v1/KeepAliveInfoTest.java index c84f326601..2763628bb9 100644 --- a/activemq-core/src/test/java/org/apache/activemq/openwire/v1/KeepAliveInfoTest.java +++ b/activemq-core/src/test/java/org/apache/activemq/openwire/v1/KeepAliveInfoTest.java @@ -16,40 +16,31 @@ */ package org.apache.activemq.openwire.v1; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - -import org.apache.activemq.openwire.*; -import org.apache.activemq.command.*; - +import org.apache.activemq.command.KeepAliveInfo; /** * Test case for the OpenWire marshalling for KeepAliveInfo - * - * - * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * + * + * + * NOTE!: This file is auto generated - do not modify! if you need to make a + * change, please see the modify the groovy scripts in the under src/gram/script + * and then use maven openwire:generate to regenerate this file. + * * @version $Revision$ */ public class KeepAliveInfoTest extends BaseCommandTestSupport { - public static KeepAliveInfoTest SINGLETON = new KeepAliveInfoTest(); public Object createObject() throws Exception { - KeepAliveInfo info = new KeepAliveInfo(); - populateObject(info); - return info; + KeepAliveInfo info = new KeepAliveInfo(); + populateObject(info); + return info; } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - KeepAliveInfo info = (KeepAliveInfo) object; + super.populateObject(object); + KeepAliveInfo info = (KeepAliveInfo)object; - } - } + } +} diff --git a/activemq-core/src/test/java/org/apache/activemq/openwire/v1/LastPartialCommandTest.java b/activemq-core/src/test/java/org/apache/activemq/openwire/v1/LastPartialCommandTest.java index f458cf4cc8..8c466104e1 100644 --- a/activemq-core/src/test/java/org/apache/activemq/openwire/v1/LastPartialCommandTest.java +++ b/activemq-core/src/test/java/org/apache/activemq/openwire/v1/LastPartialCommandTest.java @@ -16,40 +16,31 @@ */ package org.apache.activemq.openwire.v1; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - -import org.apache.activemq.openwire.*; -import org.apache.activemq.command.*; - +import org.apache.activemq.command.LastPartialCommand; /** * Test case for the OpenWire marshalling for LastPartialCommand - * - * - * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * + * + * + * NOTE!: This file is auto generated - do not modify! if you need to make a + * change, please see the modify the groovy scripts in the under src/gram/script + * and then use maven openwire:generate to regenerate this file. + * * @version $Revision$ */ public class LastPartialCommandTest extends PartialCommandTest { - public static LastPartialCommandTest SINGLETON = new LastPartialCommandTest(); public Object createObject() throws Exception { - LastPartialCommand info = new LastPartialCommand(); - populateObject(info); - return info; + LastPartialCommand info = new LastPartialCommand(); + populateObject(info); + return info; } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - LastPartialCommand info = (LastPartialCommand) object; + super.populateObject(object); + LastPartialCommand info = (LastPartialCommand)object; - } - } + } +} diff --git a/activemq-core/src/test/java/org/apache/activemq/openwire/v1/LocalTransactionIdTest.java b/activemq-core/src/test/java/org/apache/activemq/openwire/v1/LocalTransactionIdTest.java index 326754aa7e..4610de785c 100644 --- a/activemq-core/src/test/java/org/apache/activemq/openwire/v1/LocalTransactionIdTest.java +++ b/activemq-core/src/test/java/org/apache/activemq/openwire/v1/LocalTransactionIdTest.java @@ -16,42 +16,33 @@ */ package org.apache.activemq.openwire.v1; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - -import org.apache.activemq.openwire.*; -import org.apache.activemq.command.*; - +import org.apache.activemq.command.LocalTransactionId; /** * Test case for the OpenWire marshalling for LocalTransactionId - * - * - * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * + * + * + * NOTE!: This file is auto generated - do not modify! if you need to make a + * change, please see the modify the groovy scripts in the under src/gram/script + * and then use maven openwire:generate to regenerate this file. + * * @version $Revision$ */ public class LocalTransactionIdTest extends TransactionIdTestSupport { - public static LocalTransactionIdTest SINGLETON = new LocalTransactionIdTest(); public Object createObject() throws Exception { - LocalTransactionId info = new LocalTransactionId(); - populateObject(info); - return info; + LocalTransactionId info = new LocalTransactionId(); + populateObject(info); + return info; } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - LocalTransactionId info = (LocalTransactionId) object; + super.populateObject(object); + LocalTransactionId info = (LocalTransactionId)object; info.setValue(1); info.setConnectionId(createConnectionId("ConnectionId:1")); - } - } + } +} diff --git a/activemq-core/src/test/java/org/apache/activemq/openwire/v1/MessageAckTest.java b/activemq-core/src/test/java/org/apache/activemq/openwire/v1/MessageAckTest.java index f12bd116c9..2210d6d337 100644 --- a/activemq-core/src/test/java/org/apache/activemq/openwire/v1/MessageAckTest.java +++ b/activemq-core/src/test/java/org/apache/activemq/openwire/v1/MessageAckTest.java @@ -16,47 +16,38 @@ */ package org.apache.activemq.openwire.v1; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - -import org.apache.activemq.openwire.*; -import org.apache.activemq.command.*; - +import org.apache.activemq.command.MessageAck; /** * Test case for the OpenWire marshalling for MessageAck - * - * - * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * + * + * + * NOTE!: This file is auto generated - do not modify! if you need to make a + * change, please see the modify the groovy scripts in the under src/gram/script + * and then use maven openwire:generate to regenerate this file. + * * @version $Revision$ */ public class MessageAckTest extends BaseCommandTestSupport { - public static final MessageAckTest SINGLETON = new MessageAckTest(); public Object createObject() throws Exception { - MessageAck info = new MessageAck(); - populateObject(info); - return info; + MessageAck info = new MessageAck(); + populateObject(info); + return info; } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - MessageAck info = (MessageAck) object; + super.populateObject(object); + MessageAck info = (MessageAck)object; info.setDestination(createActiveMQDestination("Destination:1")); info.setTransactionId(createTransactionId("TransactionId:2")); info.setConsumerId(createConsumerId("ConsumerId:3")); - info.setAckType((byte) 1); + info.setAckType((byte)1); info.setFirstMessageId(createMessageId("FirstMessageId:4")); info.setLastMessageId(createMessageId("LastMessageId:5")); info.setMessageCount(1); - } - } + } +} diff --git a/activemq-core/src/test/java/org/apache/activemq/openwire/v1/MessageDispatchNotificationTest.java b/activemq-core/src/test/java/org/apache/activemq/openwire/v1/MessageDispatchNotificationTest.java index 7324c0594d..a3d27712e5 100644 --- a/activemq-core/src/test/java/org/apache/activemq/openwire/v1/MessageDispatchNotificationTest.java +++ b/activemq-core/src/test/java/org/apache/activemq/openwire/v1/MessageDispatchNotificationTest.java @@ -16,44 +16,35 @@ */ package org.apache.activemq.openwire.v1; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - -import org.apache.activemq.openwire.*; -import org.apache.activemq.command.*; - +import org.apache.activemq.command.MessageDispatchNotification; /** * Test case for the OpenWire marshalling for MessageDispatchNotification - * - * - * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * + * + * + * NOTE!: This file is auto generated - do not modify! if you need to make a + * change, please see the modify the groovy scripts in the under src/gram/script + * and then use maven openwire:generate to regenerate this file. + * * @version $Revision$ */ public class MessageDispatchNotificationTest extends BaseCommandTestSupport { - public static MessageDispatchNotificationTest SINGLETON = new MessageDispatchNotificationTest(); public Object createObject() throws Exception { - MessageDispatchNotification info = new MessageDispatchNotification(); - populateObject(info); - return info; + MessageDispatchNotification info = new MessageDispatchNotification(); + populateObject(info); + return info; } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - MessageDispatchNotification info = (MessageDispatchNotification) object; + super.populateObject(object); + MessageDispatchNotification info = (MessageDispatchNotification)object; info.setConsumerId(createConsumerId("ConsumerId:1")); info.setDestination(createActiveMQDestination("Destination:2")); info.setDeliverySequenceId(1); info.setMessageId(createMessageId("MessageId:3")); - } - } + } +} diff --git a/activemq-core/src/test/java/org/apache/activemq/openwire/v1/MessageDispatchTest.java b/activemq-core/src/test/java/org/apache/activemq/openwire/v1/MessageDispatchTest.java index d8df5239d7..ea6cb38d37 100644 --- a/activemq-core/src/test/java/org/apache/activemq/openwire/v1/MessageDispatchTest.java +++ b/activemq-core/src/test/java/org/apache/activemq/openwire/v1/MessageDispatchTest.java @@ -16,44 +16,35 @@ */ package org.apache.activemq.openwire.v1; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - -import org.apache.activemq.openwire.*; -import org.apache.activemq.command.*; - +import org.apache.activemq.command.MessageDispatch; /** * Test case for the OpenWire marshalling for MessageDispatch - * - * - * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * + * + * + * NOTE!: This file is auto generated - do not modify! if you need to make a + * change, please see the modify the groovy scripts in the under src/gram/script + * and then use maven openwire:generate to regenerate this file. + * * @version $Revision$ */ public class MessageDispatchTest extends BaseCommandTestSupport { - public static MessageDispatchTest SINGLETON = new MessageDispatchTest(); public Object createObject() throws Exception { - MessageDispatch info = new MessageDispatch(); - populateObject(info); - return info; + MessageDispatch info = new MessageDispatch(); + populateObject(info); + return info; } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - MessageDispatch info = (MessageDispatch) object; + super.populateObject(object); + MessageDispatch info = (MessageDispatch)object; info.setConsumerId(createConsumerId("ConsumerId:1")); info.setDestination(createActiveMQDestination("Destination:2")); info.setMessage(createMessage("Message:3")); info.setRedeliveryCounter(1); - } - } + } +} diff --git a/activemq-core/src/test/java/org/apache/activemq/openwire/v1/MessageIdTest.java b/activemq-core/src/test/java/org/apache/activemq/openwire/v1/MessageIdTest.java index e9b4072e93..6102316ec2 100644 --- a/activemq-core/src/test/java/org/apache/activemq/openwire/v1/MessageIdTest.java +++ b/activemq-core/src/test/java/org/apache/activemq/openwire/v1/MessageIdTest.java @@ -16,43 +16,35 @@ */ package org.apache.activemq.openwire.v1; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - -import org.apache.activemq.openwire.*; -import org.apache.activemq.command.*; - +import org.apache.activemq.command.MessageId; +import org.apache.activemq.openwire.DataFileGeneratorTestSupport; /** * Test case for the OpenWire marshalling for MessageId - * - * - * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * + * + * + * NOTE!: This file is auto generated - do not modify! if you need to make a + * change, please see the modify the groovy scripts in the under src/gram/script + * and then use maven openwire:generate to regenerate this file. + * * @version $Revision$ */ public class MessageIdTest extends DataFileGeneratorTestSupport { - public static MessageIdTest SINGLETON = new MessageIdTest(); public Object createObject() throws Exception { - MessageId info = new MessageId(); - populateObject(info); - return info; + MessageId info = new MessageId(); + populateObject(info); + return info; } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - MessageId info = (MessageId) object; + super.populateObject(object); + MessageId info = (MessageId)object; info.setProducerId(createProducerId("ProducerId:1")); info.setProducerSequenceId(1); info.setBrokerSequenceId(2); - } - } + } +} diff --git a/activemq-core/src/test/java/org/apache/activemq/openwire/v1/NetworkBridgeFilterTest.java b/activemq-core/src/test/java/org/apache/activemq/openwire/v1/NetworkBridgeFilterTest.java index f2faded08a..22d6bcb820 100644 --- a/activemq-core/src/test/java/org/apache/activemq/openwire/v1/NetworkBridgeFilterTest.java +++ b/activemq-core/src/test/java/org/apache/activemq/openwire/v1/NetworkBridgeFilterTest.java @@ -16,42 +16,34 @@ */ package org.apache.activemq.openwire.v1; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - -import org.apache.activemq.openwire.*; -import org.apache.activemq.command.*; - +import org.apache.activemq.command.NetworkBridgeFilter; +import org.apache.activemq.openwire.DataFileGeneratorTestSupport; /** * Test case for the OpenWire marshalling for NetworkBridgeFilter - * - * - * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * + * + * + * NOTE!: This file is auto generated - do not modify! if you need to make a + * change, please see the modify the groovy scripts in the under src/gram/script + * and then use maven openwire:generate to regenerate this file. + * * @version $Revision: $ */ public class NetworkBridgeFilterTest extends DataFileGeneratorTestSupport { - public static NetworkBridgeFilterTest SINGLETON = new NetworkBridgeFilterTest(); public Object createObject() throws Exception { - NetworkBridgeFilter info = new NetworkBridgeFilter(); - populateObject(info); - return info; + NetworkBridgeFilter info = new NetworkBridgeFilter(); + populateObject(info); + return info; } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - NetworkBridgeFilter info = (NetworkBridgeFilter) object; + super.populateObject(object); + NetworkBridgeFilter info = (NetworkBridgeFilter)object; info.setNetworkTTL(1); info.setNetworkBrokerId(createBrokerId("NetworkBrokerId:1")); - } - } + } +} diff --git a/activemq-core/src/test/java/org/apache/activemq/openwire/v1/PartialCommandTest.java b/activemq-core/src/test/java/org/apache/activemq/openwire/v1/PartialCommandTest.java index f5787ad65e..af6d114228 100644 --- a/activemq-core/src/test/java/org/apache/activemq/openwire/v1/PartialCommandTest.java +++ b/activemq-core/src/test/java/org/apache/activemq/openwire/v1/PartialCommandTest.java @@ -16,42 +16,34 @@ */ package org.apache.activemq.openwire.v1; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - -import org.apache.activemq.openwire.*; -import org.apache.activemq.command.*; - +import org.apache.activemq.command.PartialCommand; +import org.apache.activemq.openwire.DataFileGeneratorTestSupport; /** * Test case for the OpenWire marshalling for PartialCommand - * - * - * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * + * + * + * NOTE!: This file is auto generated - do not modify! if you need to make a + * change, please see the modify the groovy scripts in the under src/gram/script + * and then use maven openwire:generate to regenerate this file. + * * @version $Revision$ */ public class PartialCommandTest extends DataFileGeneratorTestSupport { - public static PartialCommandTest SINGLETON = new PartialCommandTest(); public Object createObject() throws Exception { - PartialCommand info = new PartialCommand(); - populateObject(info); - return info; + PartialCommand info = new PartialCommand(); + populateObject(info); + return info; } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - PartialCommand info = (PartialCommand) object; + super.populateObject(object); + PartialCommand info = (PartialCommand)object; info.setCommandId(1); info.setData("Data:1".getBytes()); - } - } + } +} diff --git a/activemq-core/src/test/java/org/apache/activemq/openwire/v1/ProducerIdTest.java b/activemq-core/src/test/java/org/apache/activemq/openwire/v1/ProducerIdTest.java index 7a869e6345..4659a9be92 100644 --- a/activemq-core/src/test/java/org/apache/activemq/openwire/v1/ProducerIdTest.java +++ b/activemq-core/src/test/java/org/apache/activemq/openwire/v1/ProducerIdTest.java @@ -16,43 +16,35 @@ */ package org.apache.activemq.openwire.v1; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - -import org.apache.activemq.openwire.*; -import org.apache.activemq.command.*; - +import org.apache.activemq.command.ProducerId; +import org.apache.activemq.openwire.DataFileGeneratorTestSupport; /** * Test case for the OpenWire marshalling for ProducerId - * - * - * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * + * + * + * NOTE!: This file is auto generated - do not modify! if you need to make a + * change, please see the modify the groovy scripts in the under src/gram/script + * and then use maven openwire:generate to regenerate this file. + * * @version $Revision$ */ public class ProducerIdTest extends DataFileGeneratorTestSupport { - public static ProducerIdTest SINGLETON = new ProducerIdTest(); public Object createObject() throws Exception { - ProducerId info = new ProducerId(); - populateObject(info); - return info; + ProducerId info = new ProducerId(); + populateObject(info); + return info; } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ProducerId info = (ProducerId) object; + super.populateObject(object); + ProducerId info = (ProducerId)object; info.setConnectionId("ConnectionId:1"); info.setValue(1); info.setSessionId(2); - } - } + } +} diff --git a/activemq-core/src/test/java/org/apache/activemq/openwire/v1/RemoveInfoTest.java b/activemq-core/src/test/java/org/apache/activemq/openwire/v1/RemoveInfoTest.java index 6f103cb52b..1333bbe271 100644 --- a/activemq-core/src/test/java/org/apache/activemq/openwire/v1/RemoveInfoTest.java +++ b/activemq-core/src/test/java/org/apache/activemq/openwire/v1/RemoveInfoTest.java @@ -16,41 +16,32 @@ */ package org.apache.activemq.openwire.v1; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - -import org.apache.activemq.openwire.*; -import org.apache.activemq.command.*; - +import org.apache.activemq.command.RemoveInfo; /** * Test case for the OpenWire marshalling for RemoveInfo - * - * - * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * + * + * + * NOTE!: This file is auto generated - do not modify! if you need to make a + * change, please see the modify the groovy scripts in the under src/gram/script + * and then use maven openwire:generate to regenerate this file. + * * @version $Revision$ */ public class RemoveInfoTest extends BaseCommandTestSupport { - public static RemoveInfoTest SINGLETON = new RemoveInfoTest(); public Object createObject() throws Exception { - RemoveInfo info = new RemoveInfo(); - populateObject(info); - return info; + RemoveInfo info = new RemoveInfo(); + populateObject(info); + return info; } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - RemoveInfo info = (RemoveInfo) object; + super.populateObject(object); + RemoveInfo info = (RemoveInfo)object; info.setObjectId(createDataStructure("ObjectId:1")); - } - } + } +} diff --git a/activemq-core/src/test/java/org/apache/activemq/openwire/v1/RemoveSubscriptionInfoTest.java b/activemq-core/src/test/java/org/apache/activemq/openwire/v1/RemoveSubscriptionInfoTest.java index a4c95b9b5a..8508c3594d 100644 --- a/activemq-core/src/test/java/org/apache/activemq/openwire/v1/RemoveSubscriptionInfoTest.java +++ b/activemq-core/src/test/java/org/apache/activemq/openwire/v1/RemoveSubscriptionInfoTest.java @@ -16,43 +16,34 @@ */ package org.apache.activemq.openwire.v1; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - -import org.apache.activemq.openwire.*; -import org.apache.activemq.command.*; - +import org.apache.activemq.command.RemoveSubscriptionInfo; /** * Test case for the OpenWire marshalling for RemoveSubscriptionInfo - * - * - * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * + * + * + * NOTE!: This file is auto generated - do not modify! if you need to make a + * change, please see the modify the groovy scripts in the under src/gram/script + * and then use maven openwire:generate to regenerate this file. + * * @version $Revision$ */ public class RemoveSubscriptionInfoTest extends BaseCommandTestSupport { - public static RemoveSubscriptionInfoTest SINGLETON = new RemoveSubscriptionInfoTest(); public Object createObject() throws Exception { - RemoveSubscriptionInfo info = new RemoveSubscriptionInfo(); - populateObject(info); - return info; + RemoveSubscriptionInfo info = new RemoveSubscriptionInfo(); + populateObject(info); + return info; } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - RemoveSubscriptionInfo info = (RemoveSubscriptionInfo) object; + super.populateObject(object); + RemoveSubscriptionInfo info = (RemoveSubscriptionInfo)object; info.setConnectionId(createConnectionId("ConnectionId:1")); info.setSubcriptionName("SubcriptionName:2"); info.setClientId("ClientId:3"); - } - } + } +} diff --git a/activemq-core/src/test/java/org/apache/activemq/openwire/v1/ReplayCommandTest.java b/activemq-core/src/test/java/org/apache/activemq/openwire/v1/ReplayCommandTest.java index c3fa291268..1b18738a9a 100644 --- a/activemq-core/src/test/java/org/apache/activemq/openwire/v1/ReplayCommandTest.java +++ b/activemq-core/src/test/java/org/apache/activemq/openwire/v1/ReplayCommandTest.java @@ -16,42 +16,33 @@ */ package org.apache.activemq.openwire.v1; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - -import org.apache.activemq.openwire.*; -import org.apache.activemq.command.*; - +import org.apache.activemq.command.ReplayCommand; /** * Test case for the OpenWire marshalling for ReplayCommand - * - * - * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * + * + * + * NOTE!: This file is auto generated - do not modify! if you need to make a + * change, please see the modify the groovy scripts in the under src/gram/script + * and then use maven openwire:generate to regenerate this file. + * * @version $Revision$ */ public class ReplayCommandTest extends BaseCommandTestSupport { - public static ReplayCommandTest SINGLETON = new ReplayCommandTest(); public Object createObject() throws Exception { - ReplayCommand info = new ReplayCommand(); - populateObject(info); - return info; + ReplayCommand info = new ReplayCommand(); + populateObject(info); + return info; } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ReplayCommand info = (ReplayCommand) object; + super.populateObject(object); + ReplayCommand info = (ReplayCommand)object; info.setFirstNakNumber(1); info.setLastNakNumber(2); - } - } + } +} diff --git a/activemq-core/src/test/java/org/apache/activemq/openwire/v1/ResponseTest.java b/activemq-core/src/test/java/org/apache/activemq/openwire/v1/ResponseTest.java index a2bfe98333..f165f07379 100644 --- a/activemq-core/src/test/java/org/apache/activemq/openwire/v1/ResponseTest.java +++ b/activemq-core/src/test/java/org/apache/activemq/openwire/v1/ResponseTest.java @@ -16,41 +16,32 @@ */ package org.apache.activemq.openwire.v1; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - -import org.apache.activemq.openwire.*; -import org.apache.activemq.command.*; - +import org.apache.activemq.command.Response; /** * Test case for the OpenWire marshalling for Response - * - * - * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * + * + * + * NOTE!: This file is auto generated - do not modify! if you need to make a + * change, please see the modify the groovy scripts in the under src/gram/script + * and then use maven openwire:generate to regenerate this file. + * * @version $Revision$ */ public class ResponseTest extends BaseCommandTestSupport { - public static ResponseTest SINGLETON = new ResponseTest(); public Object createObject() throws Exception { - Response info = new Response(); - populateObject(info); - return info; + Response info = new Response(); + populateObject(info); + return info; } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - Response info = (Response) object; + super.populateObject(object); + Response info = (Response)object; info.setCorrelationId(1); - } - } + } +} diff --git a/activemq-core/src/test/java/org/apache/activemq/openwire/v1/SessionIdTest.java b/activemq-core/src/test/java/org/apache/activemq/openwire/v1/SessionIdTest.java index 939e7cb223..813079f856 100644 --- a/activemq-core/src/test/java/org/apache/activemq/openwire/v1/SessionIdTest.java +++ b/activemq-core/src/test/java/org/apache/activemq/openwire/v1/SessionIdTest.java @@ -16,42 +16,34 @@ */ package org.apache.activemq.openwire.v1; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - -import org.apache.activemq.openwire.*; -import org.apache.activemq.command.*; - +import org.apache.activemq.command.SessionId; +import org.apache.activemq.openwire.DataFileGeneratorTestSupport; /** * Test case for the OpenWire marshalling for SessionId - * - * - * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * + * + * + * NOTE!: This file is auto generated - do not modify! if you need to make a + * change, please see the modify the groovy scripts in the under src/gram/script + * and then use maven openwire:generate to regenerate this file. + * * @version $Revision$ */ public class SessionIdTest extends DataFileGeneratorTestSupport { - public static SessionIdTest SINGLETON = new SessionIdTest(); public Object createObject() throws Exception { - SessionId info = new SessionId(); - populateObject(info); - return info; + SessionId info = new SessionId(); + populateObject(info); + return info; } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - SessionId info = (SessionId) object; + super.populateObject(object); + SessionId info = (SessionId)object; info.setConnectionId("ConnectionId:1"); info.setValue(1); - } - } + } +} diff --git a/activemq-core/src/test/java/org/apache/activemq/openwire/v1/SessionInfoTest.java b/activemq-core/src/test/java/org/apache/activemq/openwire/v1/SessionInfoTest.java index cc5f088ab4..33c6add7bf 100644 --- a/activemq-core/src/test/java/org/apache/activemq/openwire/v1/SessionInfoTest.java +++ b/activemq-core/src/test/java/org/apache/activemq/openwire/v1/SessionInfoTest.java @@ -16,41 +16,32 @@ */ package org.apache.activemq.openwire.v1; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - -import org.apache.activemq.openwire.*; -import org.apache.activemq.command.*; - +import org.apache.activemq.command.SessionInfo; /** * Test case for the OpenWire marshalling for SessionInfo - * - * - * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * + * + * + * NOTE!: This file is auto generated - do not modify! if you need to make a + * change, please see the modify the groovy scripts in the under src/gram/script + * and then use maven openwire:generate to regenerate this file. + * * @version $Revision$ */ public class SessionInfoTest extends BaseCommandTestSupport { - public static SessionInfoTest SINGLETON = new SessionInfoTest(); public Object createObject() throws Exception { - SessionInfo info = new SessionInfo(); - populateObject(info); - return info; + SessionInfo info = new SessionInfo(); + populateObject(info); + return info; } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - SessionInfo info = (SessionInfo) object; + super.populateObject(object); + SessionInfo info = (SessionInfo)object; info.setSessionId(createSessionId("SessionId:1")); - } - } + } +} diff --git a/activemq-core/src/test/java/org/apache/activemq/openwire/v1/ShutdownInfoTest.java b/activemq-core/src/test/java/org/apache/activemq/openwire/v1/ShutdownInfoTest.java index ec20edce01..8c4fc30750 100644 --- a/activemq-core/src/test/java/org/apache/activemq/openwire/v1/ShutdownInfoTest.java +++ b/activemq-core/src/test/java/org/apache/activemq/openwire/v1/ShutdownInfoTest.java @@ -16,40 +16,31 @@ */ package org.apache.activemq.openwire.v1; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - -import org.apache.activemq.openwire.*; -import org.apache.activemq.command.*; - +import org.apache.activemq.command.ShutdownInfo; /** * Test case for the OpenWire marshalling for ShutdownInfo - * - * - * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * + * + * + * NOTE!: This file is auto generated - do not modify! if you need to make a + * change, please see the modify the groovy scripts in the under src/gram/script + * and then use maven openwire:generate to regenerate this file. + * * @version $Revision$ */ public class ShutdownInfoTest extends BaseCommandTestSupport { - public static ShutdownInfoTest SINGLETON = new ShutdownInfoTest(); public Object createObject() throws Exception { - ShutdownInfo info = new ShutdownInfo(); - populateObject(info); - return info; + ShutdownInfo info = new ShutdownInfo(); + populateObject(info); + return info; } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ShutdownInfo info = (ShutdownInfo) object; + super.populateObject(object); + ShutdownInfo info = (ShutdownInfo)object; - } - } + } +} diff --git a/activemq-core/src/test/java/org/apache/activemq/openwire/v1/SubscriptionInfoTest.java b/activemq-core/src/test/java/org/apache/activemq/openwire/v1/SubscriptionInfoTest.java index c77d89b5c1..42af8ef225 100644 --- a/activemq-core/src/test/java/org/apache/activemq/openwire/v1/SubscriptionInfoTest.java +++ b/activemq-core/src/test/java/org/apache/activemq/openwire/v1/SubscriptionInfoTest.java @@ -16,44 +16,36 @@ */ package org.apache.activemq.openwire.v1; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - -import org.apache.activemq.openwire.*; -import org.apache.activemq.command.*; - +import org.apache.activemq.command.SubscriptionInfo; +import org.apache.activemq.openwire.DataFileGeneratorTestSupport; /** * Test case for the OpenWire marshalling for SubscriptionInfo - * - * - * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * + * + * + * NOTE!: This file is auto generated - do not modify! if you need to make a + * change, please see the modify the groovy scripts in the under src/gram/script + * and then use maven openwire:generate to regenerate this file. + * * @version $Revision$ */ public class SubscriptionInfoTest extends DataFileGeneratorTestSupport { - public static SubscriptionInfoTest SINGLETON = new SubscriptionInfoTest(); public Object createObject() throws Exception { - SubscriptionInfo info = new SubscriptionInfo(); - populateObject(info); - return info; + SubscriptionInfo info = new SubscriptionInfo(); + populateObject(info); + return info; } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - SubscriptionInfo info = (SubscriptionInfo) object; + super.populateObject(object); + SubscriptionInfo info = (SubscriptionInfo)object; info.setClientId("ClientId:1"); info.setDestination(createActiveMQDestination("Destination:2")); info.setSelector("Selector:3"); info.setSubcriptionName("SubcriptionName:4"); - } - } + } +} diff --git a/activemq-core/src/test/java/org/apache/activemq/openwire/v1/TransactionIdTestSupport.java b/activemq-core/src/test/java/org/apache/activemq/openwire/v1/TransactionIdTestSupport.java index 06fde7e4ab..488a17e366 100644 --- a/activemq-core/src/test/java/org/apache/activemq/openwire/v1/TransactionIdTestSupport.java +++ b/activemq-core/src/test/java/org/apache/activemq/openwire/v1/TransactionIdTestSupport.java @@ -16,31 +16,24 @@ */ package org.apache.activemq.openwire.v1; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - -import org.apache.activemq.openwire.*; -import org.apache.activemq.command.*; - +import org.apache.activemq.command.TransactionId; +import org.apache.activemq.openwire.DataFileGeneratorTestSupport; /** * Test case for the OpenWire marshalling for TransactionId - * - * - * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * + * + * + * NOTE!: This file is auto generated - do not modify! if you need to make a + * change, please see the modify the groovy scripts in the under src/gram/script + * and then use maven openwire:generate to regenerate this file. + * * @version $Revision$ */ public abstract class TransactionIdTestSupport extends DataFileGeneratorTestSupport { - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - TransactionId info = (TransactionId) object; + super.populateObject(object); + TransactionId info = (TransactionId)object; - } - } + } +} diff --git a/activemq-core/src/test/java/org/apache/activemq/openwire/v1/TransactionInfoTest.java b/activemq-core/src/test/java/org/apache/activemq/openwire/v1/TransactionInfoTest.java index 4c4376d915..f12ea889d6 100644 --- a/activemq-core/src/test/java/org/apache/activemq/openwire/v1/TransactionInfoTest.java +++ b/activemq-core/src/test/java/org/apache/activemq/openwire/v1/TransactionInfoTest.java @@ -16,43 +16,34 @@ */ package org.apache.activemq.openwire.v1; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - -import org.apache.activemq.openwire.*; -import org.apache.activemq.command.*; - +import org.apache.activemq.command.TransactionInfo; /** * Test case for the OpenWire marshalling for TransactionInfo - * - * - * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * + * + * + * NOTE!: This file is auto generated - do not modify! if you need to make a + * change, please see the modify the groovy scripts in the under src/gram/script + * and then use maven openwire:generate to regenerate this file. + * * @version $Revision$ */ public class TransactionInfoTest extends BaseCommandTestSupport { - public static TransactionInfoTest SINGLETON = new TransactionInfoTest(); public Object createObject() throws Exception { - TransactionInfo info = new TransactionInfo(); - populateObject(info); - return info; + TransactionInfo info = new TransactionInfo(); + populateObject(info); + return info; } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - TransactionInfo info = (TransactionInfo) object; + super.populateObject(object); + TransactionInfo info = (TransactionInfo)object; info.setConnectionId(createConnectionId("ConnectionId:1")); info.setTransactionId(createTransactionId("TransactionId:2")); - info.setType((byte) 1); + info.setType((byte)1); - } - } + } +} diff --git a/activemq-core/src/test/java/org/apache/activemq/openwire/v1/XATransactionIdTest.java b/activemq-core/src/test/java/org/apache/activemq/openwire/v1/XATransactionIdTest.java index 1304cd9d11..c00c8125c9 100644 --- a/activemq-core/src/test/java/org/apache/activemq/openwire/v1/XATransactionIdTest.java +++ b/activemq-core/src/test/java/org/apache/activemq/openwire/v1/XATransactionIdTest.java @@ -16,43 +16,34 @@ */ package org.apache.activemq.openwire.v1; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - -import org.apache.activemq.openwire.*; -import org.apache.activemq.command.*; - +import org.apache.activemq.command.XATransactionId; /** * Test case for the OpenWire marshalling for XATransactionId - * - * - * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * + * + * + * NOTE!: This file is auto generated - do not modify! if you need to make a + * change, please see the modify the groovy scripts in the under src/gram/script + * and then use maven openwire:generate to regenerate this file. + * * @version $Revision$ */ public class XATransactionIdTest extends TransactionIdTestSupport { - public static XATransactionIdTest SINGLETON = new XATransactionIdTest(); public Object createObject() throws Exception { - XATransactionId info = new XATransactionId(); - populateObject(info); - return info; + XATransactionId info = new XATransactionId(); + populateObject(info); + return info; } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - XATransactionId info = (XATransactionId) object; + super.populateObject(object); + XATransactionId info = (XATransactionId)object; info.setFormatId(1); info.setGlobalTransactionId("GlobalTransactionId:1".getBytes()); info.setBranchQualifier("BranchQualifier:2".getBytes()); - } - } + } +} diff --git a/activemq-core/src/test/java/org/apache/activemq/openwire/v2/ActiveMQBytesMessageTest.java b/activemq-core/src/test/java/org/apache/activemq/openwire/v2/ActiveMQBytesMessageTest.java index 7a095ed93c..5a4c6d67b9 100644 --- a/activemq-core/src/test/java/org/apache/activemq/openwire/v2/ActiveMQBytesMessageTest.java +++ b/activemq-core/src/test/java/org/apache/activemq/openwire/v2/ActiveMQBytesMessageTest.java @@ -23,33 +23,29 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for ActiveMQBytesMessage - * - * - * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * + * + * + * NOTE!: This file is auto generated - do not modify! if you need to make a + * change, please see the modify the groovy scripts in the under src/gram/script + * and then use maven openwire:generate to regenerate this file. + * * @version $Revision: $ */ public class ActiveMQBytesMessageTest extends ActiveMQMessageTest { - public static ActiveMQBytesMessageTest SINGLETON = new ActiveMQBytesMessageTest(); public Object createObject() throws Exception { - ActiveMQBytesMessage info = new ActiveMQBytesMessage(); - populateObject(info); - return info; + ActiveMQBytesMessage info = new ActiveMQBytesMessage(); + populateObject(info); + return info; } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ActiveMQBytesMessage info = (ActiveMQBytesMessage) object; + super.populateObject(object); + ActiveMQBytesMessage info = (ActiveMQBytesMessage)object; - } - } + } +} diff --git a/activemq-core/src/test/java/org/apache/activemq/openwire/v2/ActiveMQDestinationTestSupport.java b/activemq-core/src/test/java/org/apache/activemq/openwire/v2/ActiveMQDestinationTestSupport.java index 0d64bc7301..2b833f6aae 100644 --- a/activemq-core/src/test/java/org/apache/activemq/openwire/v2/ActiveMQDestinationTestSupport.java +++ b/activemq-core/src/test/java/org/apache/activemq/openwire/v2/ActiveMQDestinationTestSupport.java @@ -23,25 +23,22 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for ActiveMQDestination - * - * - * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * + * + * + * NOTE!: This file is auto generated - do not modify! if you need to make a + * change, please see the modify the groovy scripts in the under src/gram/script + * and then use maven openwire:generate to regenerate this file. + * * @version $Revision: $ */ public abstract class ActiveMQDestinationTestSupport extends DataFileGeneratorTestSupport { - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ActiveMQDestination info = (ActiveMQDestination) object; + super.populateObject(object); + ActiveMQDestination info = (ActiveMQDestination)object; info.setPhysicalName("PhysicalName:1"); - } - } + } +} diff --git a/activemq-core/src/test/java/org/apache/activemq/openwire/v2/ActiveMQMapMessageTest.java b/activemq-core/src/test/java/org/apache/activemq/openwire/v2/ActiveMQMapMessageTest.java index 8bea9f62d8..be52333fd3 100644 --- a/activemq-core/src/test/java/org/apache/activemq/openwire/v2/ActiveMQMapMessageTest.java +++ b/activemq-core/src/test/java/org/apache/activemq/openwire/v2/ActiveMQMapMessageTest.java @@ -23,33 +23,28 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for ActiveMQMapMessage - * - * - * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * + * + * + * NOTE!: This file is auto generated - do not modify! if you need to make a + * change, please see the modify the groovy scripts in the under src/gram/script + * and then use maven openwire:generate to regenerate this file. + * * @version $Revision: $ */ public class ActiveMQMapMessageTest extends ActiveMQMessageTest { - public static ActiveMQMapMessageTest SINGLETON = new ActiveMQMapMessageTest(); public Object createObject() throws Exception { - ActiveMQMapMessage info = new ActiveMQMapMessage(); - populateObject(info); - return info; + ActiveMQMapMessage info = new ActiveMQMapMessage(); + populateObject(info); + return info; } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ActiveMQMapMessage info = (ActiveMQMapMessage) object; - - } - } + super.populateObject(object); + ActiveMQMapMessage info = (ActiveMQMapMessage)object; + } +} diff --git a/activemq-core/src/test/java/org/apache/activemq/openwire/v2/ActiveMQMessageTest.java b/activemq-core/src/test/java/org/apache/activemq/openwire/v2/ActiveMQMessageTest.java index 7ddce86c05..a7d26f1846 100644 --- a/activemq-core/src/test/java/org/apache/activemq/openwire/v2/ActiveMQMessageTest.java +++ b/activemq-core/src/test/java/org/apache/activemq/openwire/v2/ActiveMQMessageTest.java @@ -23,33 +23,29 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for ActiveMQMessage - * - * - * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * + * + * + * NOTE!: This file is auto generated - do not modify! if you need to make a + * change, please see the modify the groovy scripts in the under src/gram/script + * and then use maven openwire:generate to regenerate this file. + * * @version $Revision: $ */ public class ActiveMQMessageTest extends MessageTestSupport { - public static ActiveMQMessageTest SINGLETON = new ActiveMQMessageTest(); public Object createObject() throws Exception { - ActiveMQMessage info = new ActiveMQMessage(); - populateObject(info); - return info; + ActiveMQMessage info = new ActiveMQMessage(); + populateObject(info); + return info; } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ActiveMQMessage info = (ActiveMQMessage) object; + super.populateObject(object); + ActiveMQMessage info = (ActiveMQMessage)object; - } - } + } +} diff --git a/activemq-core/src/test/java/org/apache/activemq/openwire/v2/ActiveMQObjectMessageTest.java b/activemq-core/src/test/java/org/apache/activemq/openwire/v2/ActiveMQObjectMessageTest.java index d077606239..539019f1ff 100644 --- a/activemq-core/src/test/java/org/apache/activemq/openwire/v2/ActiveMQObjectMessageTest.java +++ b/activemq-core/src/test/java/org/apache/activemq/openwire/v2/ActiveMQObjectMessageTest.java @@ -23,33 +23,29 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for ActiveMQObjectMessage - * - * - * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * + * + * + * NOTE!: This file is auto generated - do not modify! if you need to make a + * change, please see the modify the groovy scripts in the under src/gram/script + * and then use maven openwire:generate to regenerate this file. + * * @version $Revision: $ */ public class ActiveMQObjectMessageTest extends ActiveMQMessageTest { - public static ActiveMQObjectMessageTest SINGLETON = new ActiveMQObjectMessageTest(); public Object createObject() throws Exception { - ActiveMQObjectMessage info = new ActiveMQObjectMessage(); - populateObject(info); - return info; + ActiveMQObjectMessage info = new ActiveMQObjectMessage(); + populateObject(info); + return info; } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ActiveMQObjectMessage info = (ActiveMQObjectMessage) object; + super.populateObject(object); + ActiveMQObjectMessage info = (ActiveMQObjectMessage)object; - } - } + } +} diff --git a/activemq-core/src/test/java/org/apache/activemq/openwire/v2/ActiveMQQueueTest.java b/activemq-core/src/test/java/org/apache/activemq/openwire/v2/ActiveMQQueueTest.java index 7d9805124f..b4f2cb5af7 100644 --- a/activemq-core/src/test/java/org/apache/activemq/openwire/v2/ActiveMQQueueTest.java +++ b/activemq-core/src/test/java/org/apache/activemq/openwire/v2/ActiveMQQueueTest.java @@ -23,33 +23,29 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for ActiveMQQueue - * - * - * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * + * + * + * NOTE!: This file is auto generated - do not modify! if you need to make a + * change, please see the modify the groovy scripts in the under src/gram/script + * and then use maven openwire:generate to regenerate this file. + * * @version $Revision: $ */ public class ActiveMQQueueTest extends ActiveMQDestinationTestSupport { - public static ActiveMQQueueTest SINGLETON = new ActiveMQQueueTest(); public Object createObject() throws Exception { - ActiveMQQueue info = new ActiveMQQueue(); - populateObject(info); - return info; + ActiveMQQueue info = new ActiveMQQueue(); + populateObject(info); + return info; } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ActiveMQQueue info = (ActiveMQQueue) object; + super.populateObject(object); + ActiveMQQueue info = (ActiveMQQueue)object; - } - } + } +} diff --git a/activemq-core/src/test/java/org/apache/activemq/openwire/v2/ActiveMQStreamMessageTest.java b/activemq-core/src/test/java/org/apache/activemq/openwire/v2/ActiveMQStreamMessageTest.java index 66f201e4f2..58c06c00de 100644 --- a/activemq-core/src/test/java/org/apache/activemq/openwire/v2/ActiveMQStreamMessageTest.java +++ b/activemq-core/src/test/java/org/apache/activemq/openwire/v2/ActiveMQStreamMessageTest.java @@ -23,33 +23,29 @@ import java.io.IOException; import org.apache.activemq.openwire.*; import org.apache.activemq.command.*; - /** * Test case for the OpenWire marshalling for ActiveMQStreamMessage - * - * - * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * + * + * + * NOTE!: This file is auto generated - do not modify! if you need to make a + * change, please see the modify the groovy scripts in the under src/gram/script + * and then use maven openwire:generate to regenerate this file. + * * @version $Revision: $ */ public class ActiveMQStreamMessageTest extends ActiveMQMessageTest { - public static ActiveMQStreamMessageTest SINGLETON = new ActiveMQStreamMessageTest(); public Object createObject() throws Exception { - ActiveMQStreamMessage info = new ActiveMQStreamMessage(); - populateObject(info); - return info; + ActiveMQStreamMessage info = new ActiveMQStreamMessage(); + populateObject(info); + return info; } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ActiveMQStreamMessage info = (ActiveMQStreamMessage) object; + super.populateObject(object); + ActiveMQStreamMessage info = (ActiveMQStreamMessage)object; - } - } + } +} diff --git a/activemq-core/src/test/java/org/apache/activemq/openwire/v2/ActiveMQTempDestinationTestSupport.java b/activemq-core/src/test/java/org/apache/activemq/openwire/v2/ActiveMQTempDestinationTestSupport.java index c2d6ff85e6..fb23ab2a1b 100644 --- a/activemq-core/src/test/java/org/apache/activemq/openwire/v2/ActiveMQTempDestinationTestSupport.java +++ b/activemq-core/src/test/java/org/apache/activemq/openwire/v2/ActiveMQTempDestinationTestSupport.java @@ -16,31 +16,23 @@ */ package org.apache.activemq.openwire.v2; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - -import org.apache.activemq.openwire.*; -import org.apache.activemq.command.*; - +import org.apache.activemq.command.ActiveMQTempDestination; /** * Test case for the OpenWire marshalling for ActiveMQTempDestination - * - * - * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * + * + * + * NOTE!: This file is auto generated - do not modify! if you need to make a + * change, please see the modify the groovy scripts in the under src/gram/script + * and then use maven openwire:generate to regenerate this file. + * * @version $Revision: $ */ public abstract class ActiveMQTempDestinationTestSupport extends ActiveMQDestinationTestSupport { - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ActiveMQTempDestination info = (ActiveMQTempDestination) object; + super.populateObject(object); + ActiveMQTempDestination info = (ActiveMQTempDestination)object; - } - } + } +} diff --git a/activemq-core/src/test/java/org/apache/activemq/openwire/v2/ActiveMQTempQueueTest.java b/activemq-core/src/test/java/org/apache/activemq/openwire/v2/ActiveMQTempQueueTest.java index 37d0e61bdf..09b16a757f 100644 --- a/activemq-core/src/test/java/org/apache/activemq/openwire/v2/ActiveMQTempQueueTest.java +++ b/activemq-core/src/test/java/org/apache/activemq/openwire/v2/ActiveMQTempQueueTest.java @@ -16,40 +16,31 @@ */ package org.apache.activemq.openwire.v2; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - -import org.apache.activemq.openwire.*; -import org.apache.activemq.command.*; - +import org.apache.activemq.command.ActiveMQTempQueue; /** * Test case for the OpenWire marshalling for ActiveMQTempQueue - * - * - * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * + * + * + * NOTE!: This file is auto generated - do not modify! if you need to make a + * change, please see the modify the groovy scripts in the under src/gram/script + * and then use maven openwire:generate to regenerate this file. + * * @version $Revision: $ */ public class ActiveMQTempQueueTest extends ActiveMQTempDestinationTestSupport { - public static ActiveMQTempQueueTest SINGLETON = new ActiveMQTempQueueTest(); public Object createObject() throws Exception { - ActiveMQTempQueue info = new ActiveMQTempQueue(); - populateObject(info); - return info; + ActiveMQTempQueue info = new ActiveMQTempQueue(); + populateObject(info); + return info; } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ActiveMQTempQueue info = (ActiveMQTempQueue) object; + super.populateObject(object); + ActiveMQTempQueue info = (ActiveMQTempQueue)object; - } - } + } +} diff --git a/activemq-core/src/test/java/org/apache/activemq/openwire/v2/ActiveMQTempTopicTest.java b/activemq-core/src/test/java/org/apache/activemq/openwire/v2/ActiveMQTempTopicTest.java index feea74f353..0eee193365 100644 --- a/activemq-core/src/test/java/org/apache/activemq/openwire/v2/ActiveMQTempTopicTest.java +++ b/activemq-core/src/test/java/org/apache/activemq/openwire/v2/ActiveMQTempTopicTest.java @@ -16,40 +16,31 @@ */ package org.apache.activemq.openwire.v2; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - -import org.apache.activemq.openwire.*; -import org.apache.activemq.command.*; - +import org.apache.activemq.command.ActiveMQTempTopic; /** * Test case for the OpenWire marshalling for ActiveMQTempTopic - * - * - * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * + * + * + * NOTE!: This file is auto generated - do not modify! if you need to make a + * change, please see the modify the groovy scripts in the under src/gram/script + * and then use maven openwire:generate to regenerate this file. + * * @version $Revision: $ */ public class ActiveMQTempTopicTest extends ActiveMQTempDestinationTestSupport { - public static ActiveMQTempTopicTest SINGLETON = new ActiveMQTempTopicTest(); public Object createObject() throws Exception { - ActiveMQTempTopic info = new ActiveMQTempTopic(); - populateObject(info); - return info; + ActiveMQTempTopic info = new ActiveMQTempTopic(); + populateObject(info); + return info; } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ActiveMQTempTopic info = (ActiveMQTempTopic) object; + super.populateObject(object); + ActiveMQTempTopic info = (ActiveMQTempTopic)object; - } - } + } +} diff --git a/activemq-core/src/test/java/org/apache/activemq/openwire/v2/ActiveMQTextMessageTest.java b/activemq-core/src/test/java/org/apache/activemq/openwire/v2/ActiveMQTextMessageTest.java index 38afc1f751..40df54186c 100644 --- a/activemq-core/src/test/java/org/apache/activemq/openwire/v2/ActiveMQTextMessageTest.java +++ b/activemq-core/src/test/java/org/apache/activemq/openwire/v2/ActiveMQTextMessageTest.java @@ -16,40 +16,31 @@ */ package org.apache.activemq.openwire.v2; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - -import org.apache.activemq.openwire.*; -import org.apache.activemq.command.*; - +import org.apache.activemq.command.ActiveMQTextMessage; /** * Test case for the OpenWire marshalling for ActiveMQTextMessage - * - * - * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * + * + * + * NOTE!: This file is auto generated - do not modify! if you need to make a + * change, please see the modify the groovy scripts in the under src/gram/script + * and then use maven openwire:generate to regenerate this file. + * * @version $Revision: $ */ public class ActiveMQTextMessageTest extends ActiveMQMessageTest { - public static ActiveMQTextMessageTest SINGLETON = new ActiveMQTextMessageTest(); public Object createObject() throws Exception { - ActiveMQTextMessage info = new ActiveMQTextMessage(); - populateObject(info); - return info; + ActiveMQTextMessage info = new ActiveMQTextMessage(); + populateObject(info); + return info; } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ActiveMQTextMessage info = (ActiveMQTextMessage) object; + super.populateObject(object); + ActiveMQTextMessage info = (ActiveMQTextMessage)object; - } - } + } +} diff --git a/activemq-core/src/test/java/org/apache/activemq/openwire/v2/ActiveMQTopicTest.java b/activemq-core/src/test/java/org/apache/activemq/openwire/v2/ActiveMQTopicTest.java index 00ef685f53..eb42adf9ab 100644 --- a/activemq-core/src/test/java/org/apache/activemq/openwire/v2/ActiveMQTopicTest.java +++ b/activemq-core/src/test/java/org/apache/activemq/openwire/v2/ActiveMQTopicTest.java @@ -16,40 +16,31 @@ */ package org.apache.activemq.openwire.v2; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - -import org.apache.activemq.openwire.*; -import org.apache.activemq.command.*; - +import org.apache.activemq.command.ActiveMQTopic; /** * Test case for the OpenWire marshalling for ActiveMQTopic - * - * - * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * + * + * + * NOTE!: This file is auto generated - do not modify! if you need to make a + * change, please see the modify the groovy scripts in the under src/gram/script + * and then use maven openwire:generate to regenerate this file. + * * @version $Revision: $ */ public class ActiveMQTopicTest extends ActiveMQDestinationTestSupport { - public static ActiveMQTopicTest SINGLETON = new ActiveMQTopicTest(); public Object createObject() throws Exception { - ActiveMQTopic info = new ActiveMQTopic(); - populateObject(info); - return info; + ActiveMQTopic info = new ActiveMQTopic(); + populateObject(info); + return info; } - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - ActiveMQTopic info = (ActiveMQTopic) object; + super.populateObject(object); + ActiveMQTopic info = (ActiveMQTopic)object; - } - } + } +} diff --git a/activemq-core/src/test/java/org/apache/activemq/openwire/v2/BaseCommandTestSupport.java b/activemq-core/src/test/java/org/apache/activemq/openwire/v2/BaseCommandTestSupport.java index 5fe9c41615..fe53a70963 100644 --- a/activemq-core/src/test/java/org/apache/activemq/openwire/v2/BaseCommandTestSupport.java +++ b/activemq-core/src/test/java/org/apache/activemq/openwire/v2/BaseCommandTestSupport.java @@ -16,33 +16,24 @@ */ package org.apache.activemq.openwire.v2; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - -import org.apache.activemq.openwire.*; -import org.apache.activemq.command.*; - +import org.apache.activemq.command.BaseCommand; +import org.apache.activemq.openwire.DataFileGeneratorTestSupport; /** - * Test case for the OpenWire marshalling for BaseCommand - * - * - * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * + * Test case for the OpenWire marshalling for BaseCommand NOTE!: This file is + * auto generated - do not modify! if you need to make a change, please see the + * modify the groovy scripts in the under src/gram/script and then use maven + * openwire:generate to regenerate this file. + * * @version $Revision: $ */ public abstract class BaseCommandTestSupport extends DataFileGeneratorTestSupport { - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - BaseCommand info = (BaseCommand) object; + super.populateObject(object); + BaseCommand info = (BaseCommand)object; info.setCommandId(1); info.setResponseRequired(true); - } - } + } +} diff --git a/activemq-core/src/test/java/org/apache/activemq/openwire/v3/BaseCommandTestSupport.java b/activemq-core/src/test/java/org/apache/activemq/openwire/v3/BaseCommandTestSupport.java index 2e1e9152ff..6b07ff87fb 100644 --- a/activemq-core/src/test/java/org/apache/activemq/openwire/v3/BaseCommandTestSupport.java +++ b/activemq-core/src/test/java/org/apache/activemq/openwire/v3/BaseCommandTestSupport.java @@ -16,28 +16,26 @@ */ package org.apache.activemq.openwire.v3; -import org.apache.activemq.openwire.DataFileGeneratorTestSupport; import org.apache.activemq.command.BaseCommand; +import org.apache.activemq.openwire.DataFileGeneratorTestSupport; /** * Test case for the OpenWire marshalling for BaseCommand - * - * - * NOTE!: This file is auto generated - do not modify! - * if you need to make a change, please see the modify the groovy scripts in the - * under src/gram/script and then use maven openwire:generate to regenerate - * this file. - * + * + * + * NOTE!: This file is auto generated - do not modify! if you need to make a + * change, please see the modify the groovy scripts in the under src/gram/script + * and then use maven openwire:generate to regenerate this file. + * * @version $Revision: $ */ public abstract class BaseCommandTestSupport extends DataFileGeneratorTestSupport { - protected void populateObject(Object object) throws Exception { - super.populateObject(object); - BaseCommand info = (BaseCommand) object; + super.populateObject(object); + BaseCommand info = (BaseCommand)object; info.setCommandId(1); info.setResponseRequired(true); - } - } + } +} diff --git a/activemq-core/src/test/java/org/apache/activemq/proxy/ProxyConnectorTest.java b/activemq-core/src/test/java/org/apache/activemq/proxy/ProxyConnectorTest.java index 571400422e..131f671579 100755 --- a/activemq-core/src/test/java/org/apache/activemq/proxy/ProxyConnectorTest.java +++ b/activemq-core/src/test/java/org/apache/activemq/proxy/ProxyConnectorTest.java @@ -18,6 +18,7 @@ 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; @@ -26,15 +27,12 @@ import org.apache.activemq.command.Message; import org.apache.activemq.command.ProducerInfo; import org.apache.activemq.command.SessionInfo; -import junit.framework.Test; - - public class ProxyConnectorTest extends ProxyTestSupport { - + public static Test suite() { return suite(ProxyConnectorTest.class); } - + public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } @@ -49,39 +47,35 @@ public class ProxyConnectorTest extends ProxyTestSupport { } 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), - } ); + 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); + 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); + 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); + SessionInfo sessionInfo2 = createSessionInfo(connectionInfo2); connection2.send(connectionInfo2); connection2.send(sessionInfo2); - ConsumerInfo consumerInfo2 = createConsumerInfo(sessionInfo2, destination); + 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 { @@ -92,8 +86,9 @@ public class ProxyConnectorTest extends ProxyTestSupport { // 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. + + // Verify that the message Was sent to the remote broker and the local + // broker. Message m; m = receiveMessage(connection1); assertNotNull(m); @@ -105,5 +100,4 @@ public class ProxyConnectorTest extends ProxyTestSupport { } - } diff --git a/activemq-core/src/test/java/org/apache/activemq/security/AuthorizationMapTest.java b/activemq-core/src/test/java/org/apache/activemq/security/AuthorizationMapTest.java index 534c7af694..4670f1847d 100644 --- a/activemq-core/src/test/java/org/apache/activemq/security/AuthorizationMapTest.java +++ b/activemq-core/src/test/java/org/apache/activemq/security/AuthorizationMapTest.java @@ -16,13 +16,13 @@ */ package org.apache.activemq.security; -import org.apache.activemq.command.ActiveMQQueue; -import org.apache.activemq.command.ActiveMQTempQueue; -import org.apache.activemq.jaas.GroupPrincipal; - -import java.util.*; +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.jaas.GroupPrincipal; /** * @@ -41,7 +41,7 @@ public class AuthorizationMapTest extends TestCase { assertEquals("set size: " + readACLs, 2, readACLs.size()); assertTrue("Contains users group", readACLs.contains(admins)); assertTrue("Contains users group", readACLs.contains(users)); - + } public void testAuthorizationMapWithTempDest() { @@ -51,13 +51,13 @@ public class AuthorizationMapTest extends TestCase { 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(tempDestinationAdmins)); - - } - + + } + protected AuthorizationMap createAuthorizationMap() { DefaultAuthorizationMap answer = new DefaultAuthorizationMap(); @@ -67,20 +67,19 @@ public class AuthorizationMapTest extends TestCase { entry.setGroupClass("org.apache.activemq.jaas.GroupPrincipal"); entry.setQueue(">"); try { - entry.setRead("admins"); + entry.setRead("admins"); } catch (Exception e) { - fail(e.toString()); + fail(e.toString()); } - - + entries.add(entry); - // entry using default org.apache.activemq.jaas.GroupPrincipal class + // entry using default org.apache.activemq.jaas.GroupPrincipal class entry = new AuthorizationEntry(); entry.setQueue("USERS.>"); try { - entry.setRead("users"); + entry.setRead("users"); } catch (Exception e) { - fail(e.toString()); + fail(e.toString()); } entries.add(entry); @@ -88,7 +87,7 @@ public class AuthorizationMapTest extends TestCase { return answer; } - + protected AuthorizationMap createAuthorizationMapWithTempDest() { DefaultAuthorizationMap answer = new DefaultAuthorizationMap(); @@ -97,34 +96,34 @@ public class AuthorizationMapTest extends TestCase { AuthorizationEntry entry = new AuthorizationEntry(); entry.setQueue(">"); try { - entry.setRead("admins"); + entry.setRead("admins"); } catch (Exception e) { - fail(e.toString()); + fail(e.toString()); } entries.add(entry); entry = new AuthorizationEntry(); entry.setQueue("USERS.>"); try { - entry.setRead("users"); + entry.setRead("users"); } catch (Exception e) { - fail(e.toString()); + fail(e.toString()); } entries.add(entry); answer.setAuthorizationEntries(entries); - - //create entry for temporary queue + + // create entry for temporary queue TempDestinationAuthorizationEntry tEntry = new TempDestinationAuthorizationEntry(); try { - tEntry.setAdmin("tempDestAdmins"); + tEntry.setAdmin("tempDestAdmins"); } catch (Exception e) { - fail(e.toString()); - } - + fail(e.toString()); + } + answer.setTempDestinationAuthorizationEntry(tEntry); return answer; - } + } } diff --git a/activemq-core/src/test/java/org/apache/activemq/security/SecurityTestSupport.java b/activemq-core/src/test/java/org/apache/activemq/security/SecurityTestSupport.java index e26d4909d2..413b72ec95 100644 --- a/activemq-core/src/test/java/org/apache/activemq/security/SecurityTestSupport.java +++ b/activemq-core/src/test/java/org/apache/activemq/security/SecurityTestSupport.java @@ -16,6 +16,13 @@ */ 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; @@ -24,13 +31,6 @@ import org.apache.activemq.command.ActiveMQMessage; import org.apache.activemq.command.ActiveMQQueue; import org.apache.activemq.command.ActiveMQTopic; -import javax.jms.Connection; -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.Session; -import javax.jms.TextMessage; - /** * * @version $Revision$ @@ -59,8 +59,7 @@ public class SecurityTestSupport extends JmsTestSupport { connections.add(c); c.start(); fail("Expected exception."); - } - catch (JMSException e) { + } catch (JMSException e) { } try { @@ -69,8 +68,7 @@ public class SecurityTestSupport extends JmsTestSupport { connections.add(c); c.start(); fail("Expected exception."); - } - catch (JMSException e) { + } catch (JMSException e) { } try { @@ -79,8 +77,7 @@ public class SecurityTestSupport extends JmsTestSupport { connections.add(c); c.start(); fail("Expected exception."); - } - catch (JMSException e) { + } catch (JMSException e) { } } @@ -131,8 +128,7 @@ public class SecurityTestSupport extends JmsTestSupport { Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); try { sendMessages(session, destination, 1); - } - catch (JMSException e) { + } catch (JMSException e) { // If test is expected to fail, the cause must only be a // SecurityException // otherwise rethrow the exception @@ -146,7 +142,7 @@ public class SecurityTestSupport extends JmsTestSupport { assertNull(m); else { assertNotNull(m); - assertEquals("0", ((TextMessage) m).getText()); + assertEquals("0", ((TextMessage)m).getText()); assertNull(consumer.receiveNoWait()); } return m; @@ -164,8 +160,7 @@ public class SecurityTestSupport extends JmsTestSupport { consumer = session.createConsumer(destination); if (fail) fail("Expected failure due to security constraint."); - } - catch (JMSException e) { + } catch (JMSException e) { if (fail && e.getCause() instanceof SecurityException) return null; throw e; @@ -178,7 +173,7 @@ public class SecurityTestSupport extends JmsTestSupport { Message m = consumer.receive(1000); assertNotNull(m); - assertEquals("0", ((TextMessage) m).getText()); + assertEquals("0", ((TextMessage)m).getText()); assertNull(consumer.receiveNoWait()); return m; @@ -188,83 +183,95 @@ public class SecurityTestSupport extends JmsTestSupport { * @see {@link CombinationTestSupport} */ 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"), }); + 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} */ public void initCombosForTestInvalidAuthentication() { - addCombinationValues("userName", new Object[] { "user" }); - addCombinationValues("password", new Object[] { "password" }); + 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"), }); + 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"), }); + 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("TEST"), new ActiveMQTopic("TEST"), new ActiveMQQueue("USERS.FOO"), - new ActiveMQTopic("USERS.FOO"), }); + 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 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"), }); + 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("TEST"), new ActiveMQTopic("TEST"), }); + addCombinationValues("userName", new Object[] {"user"}); + addCombinationValues("password", new Object[] {"password"}); + addCombinationValues("destination", new Object[] {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("TEST"), new ActiveMQTopic("TEST"), new ActiveMQQueue("USERS.FOO"), - new ActiveMQTopic("USERS.FOO"), }); + 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 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"), }); + 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/activemq-core/src/test/java/org/apache/activemq/transport/QueueClusterTest.java b/activemq-core/src/test/java/org/apache/activemq/transport/QueueClusterTest.java index e2f62f763e..05f2295707 100755 --- a/activemq-core/src/test/java/org/apache/activemq/transport/QueueClusterTest.java +++ b/activemq-core/src/test/java/org/apache/activemq/transport/QueueClusterTest.java @@ -16,21 +16,18 @@ */ package org.apache.activemq.transport; - - /** * @version $Revision$ */ public class QueueClusterTest extends TopicClusterTest { - - - protected void setUp() throws Exception{ - topic = false; - super.setUp(); + + protected void setUp() throws Exception { + topic = false; + super.setUp(); } - - protected int expectedReceiveCount(){ + + protected int expectedReceiveCount() { return MESSAGE_COUNT * NUMBER_IN_CLUSTER; } - + } diff --git a/activemq-core/src/test/java/org/apache/activemq/transport/StubTransport.java b/activemq-core/src/test/java/org/apache/activemq/transport/StubTransport.java index e1eb3bad14..b1f07dd5c7 100644 --- a/activemq-core/src/test/java/org/apache/activemq/transport/StubTransport.java +++ b/activemq-core/src/test/java/org/apache/activemq/transport/StubTransport.java @@ -16,21 +16,20 @@ */ package org.apache.activemq.transport; +import java.io.IOException; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; import org.apache.activemq.util.ServiceStopper; -import java.io.IOException; - /** - * + * * @version $Revision$ */ public class StubTransport extends TransportSupport { private Queue queue = new ConcurrentLinkedQueue(); - + protected void doStop(ServiceStopper stopper) throws Exception { } @@ -45,9 +44,8 @@ public class StubTransport extends TransportSupport { return queue; } - public String getRemoteAddress() { - return null; - } + public String getRemoteAddress() { + return null; + } - } diff --git a/activemq-core/src/test/java/org/apache/activemq/transport/failover/FailoverConsumerTest.java b/activemq-core/src/test/java/org/apache/activemq/transport/failover/FailoverConsumerTest.java index 6842939068..f6ff0abf44 100644 --- a/activemq-core/src/test/java/org/apache/activemq/transport/failover/FailoverConsumerTest.java +++ b/activemq-core/src/test/java/org/apache/activemq/transport/failover/FailoverConsumerTest.java @@ -30,85 +30,88 @@ import org.apache.activemq.command.ActiveMQQueue; import org.apache.activemq.network.NetworkTestSupport; public class FailoverConsumerTest extends NetworkTestSupport { - + private static final org.apache.commons.logging.Log log = org.apache.commons.logging.LogFactory - .getLog(FailoverConsumerTest.class); - + .getLog(FailoverConsumerTest.class); + public static final int MSG_COUNT = 100; - + public void testPublisherFailsOver() throws Exception { - // Uncomment this if you want to use remote broker created by NetworkTestSupport. - // But it doesn't work. See comments below. -// URI failoverURI = new URI("failover://"+remoteConnector.getServer().getConnectURI()); + // Uncomment this if you want to use remote broker created by + // NetworkTestSupport. + // But it doesn't work. See comments below. + // URI failoverURI = new + // URI("failover://"+remoteConnector.getServer().getConnectURI()); URI failoverURI = new URI("failover://tcp://localhost:61616"); - ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(failoverURI); - ActiveMQPrefetchPolicy prefetchPolicy = new ActiveMQPrefetchPolicy(); - - // Prefetch size must be less than messages in the queue!! - prefetchPolicy.setQueuePrefetch(MSG_COUNT - 10); - factory.setPrefetchPolicy(prefetchPolicy); - Connection connection = factory.createConnection(); - Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - MessageProducer producer = session.createProducer(new ActiveMQQueue("Test")); - for (int idx = 0; idx < MSG_COUNT; ++idx) { - producer.send(session.createTextMessage("Test")); - } - producer.close(); - session.close(); - int count = 0; + ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(failoverURI); + ActiveMQPrefetchPolicy prefetchPolicy = new ActiveMQPrefetchPolicy(); - Session consumerSession = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); - MessageConsumer consumer = consumerSession.createConsumer(new ActiveMQQueue("Test")); - connection.start(); - Message msg = consumer.receive(3000); - - // restartRemoteBroker() doesn't work (you won't get received any messages - // after restart, javadoc says, that messages should be received though). - // So we must use external broker ant restart it manually. - log.info("You should restart remote broker now and press enter!"); - System.in.read(); -// Thread.sleep(20000); - restartRemoteBroker(); - msg.acknowledge(); - ++count; - - for (int idx = 1; idx < MSG_COUNT; ++idx) { - msg = consumer.receive(3000); - if (msg == null) { - log.error("No messages received! Received:" + count); - break; - } - msg.acknowledge(); - ++count; - } - assertEquals(count, MSG_COUNT); - consumer.close(); - consumerSession.close(); - connection.close(); - - connection = factory.createConnection(); - consumerSession = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); - consumer = consumerSession.createConsumer(new ActiveMQQueue("Test")); - connection.start(); + // Prefetch size must be less than messages in the queue!! + prefetchPolicy.setQueuePrefetch(MSG_COUNT - 10); + factory.setPrefetchPolicy(prefetchPolicy); + Connection connection = factory.createConnection(); + Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + MessageProducer producer = session.createProducer(new ActiveMQQueue("Test")); + for (int idx = 0; idx < MSG_COUNT; ++idx) { + producer.send(session.createTextMessage("Test")); + } + producer.close(); + session.close(); + int count = 0; - count = 0; - do { - msg = consumer.receive(1000); - if (msg != null) { - msg.acknowledge(); - ++count; - } - } - while (msg != null); - - assertEquals(count, 0); - - consumer.close(); - consumerSession.close(); - connection.close(); + Session consumerSession = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); + MessageConsumer consumer = consumerSession.createConsumer(new ActiveMQQueue("Test")); + connection.start(); + Message msg = consumer.receive(3000); + + // restartRemoteBroker() doesn't work (you won't get received any + // messages + // after restart, javadoc says, that messages should be received + // though). + // So we must use external broker ant restart it manually. + log.info("You should restart remote broker now and press enter!"); + System.in.read(); + // Thread.sleep(20000); + restartRemoteBroker(); + msg.acknowledge(); + ++count; + + for (int idx = 1; idx < MSG_COUNT; ++idx) { + msg = consumer.receive(3000); + if (msg == null) { + log.error("No messages received! Received:" + count); + break; + } + msg.acknowledge(); + ++count; + } + assertEquals(count, MSG_COUNT); + consumer.close(); + consumerSession.close(); + connection.close(); + + connection = factory.createConnection(); + consumerSession = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); + consumer = consumerSession.createConsumer(new ActiveMQQueue("Test")); + connection.start(); + + count = 0; + do { + msg = consumer.receive(1000); + if (msg != null) { + msg.acknowledge(); + ++count; + } + } while (msg != null); + + assertEquals(count, 0); + + consumer.close(); + consumerSession.close(); + connection.close(); } - + protected String getRemoteURI() { return "tcp://localhost:55555"; } diff --git a/activemq-core/src/test/java/org/apache/activemq/transport/reliable/ReliableTransportTest.java b/activemq-core/src/test/java/org/apache/activemq/transport/reliable/ReliableTransportTest.java index e2e20da53e..12ce0cd7c1 100644 --- a/activemq-core/src/test/java/org/apache/activemq/transport/reliable/ReliableTransportTest.java +++ b/activemq-core/src/test/java/org/apache/activemq/transport/reliable/ReliableTransportTest.java @@ -16,18 +16,16 @@ */ package org.apache.activemq.transport.reliable; -import junit.framework.TestCase; +import java.util.Queue; +import junit.framework.TestCase; import org.apache.activemq.command.ConsumerInfo; import org.apache.activemq.transport.StubTransport; import org.apache.activemq.transport.StubTransportListener; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import java.util.Queue; - /** - * * @version $Revision$ */ public class ReliableTransportTest extends TestCase { @@ -39,53 +37,53 @@ public class ReliableTransportTest extends TestCase { protected ReplayStrategy replayStrategy; public void testValidSequenceOfPackets() throws Exception { - int[] sequenceNumbers = { 1, 2, 3, 4, 5, 6, 7 }; - + int[] sequenceNumbers = {1, 2, 3, 4, 5, 6, 7}; + sendStreamOfCommands(sequenceNumbers, true); } - + public void testValidWrapAroundPackets() throws Exception { int[] sequenceNumbers = new int[10]; - + int value = Integer.MAX_VALUE - 3; transport.setExpectedCounter(value); - + for (int i = 0; i < 10; i++) { log.info("command: " + i + " = " + value); sequenceNumbers[i] = value++; } - + sendStreamOfCommands(sequenceNumbers, true); } - + public void testDuplicatePacketsDropped() throws Exception { - int[] sequenceNumbers = { 1, 2, 2, 3, 4, 5, 6, 7 }; - + int[] sequenceNumbers = {1, 2, 2, 3, 4, 5, 6, 7}; + sendStreamOfCommands(sequenceNumbers, true, 7); } - + public void testOldDuplicatePacketsDropped() throws Exception { - int[] sequenceNumbers = { 1, 2, 3, 4, 5, 2, 6, 7 }; - + int[] sequenceNumbers = {1, 2, 3, 4, 5, 2, 6, 7}; + sendStreamOfCommands(sequenceNumbers, true, 7); } - + public void testOldDuplicatePacketsDroppedUsingNegativeCounters() throws Exception { - int[] sequenceNumbers = { -3, -1, -3, -2, -1, 0, 1, -1, 3, 2, 0, 2, 4 }; - + int[] sequenceNumbers = {-3, -1, -3, -2, -1, 0, 1, -1, 3, 2, 0, 2, 4}; + transport.setExpectedCounter(-3); - + sendStreamOfCommands(sequenceNumbers, true, 8); } - + public void testWrongOrderOfPackets() throws Exception { - int[] sequenceNumbers = { 4, 3, 1, 5, 2, 7, 6, 8, 10, 9 }; + int[] sequenceNumbers = {4, 3, 1, 5, 2, 7, 6, 8, 10, 9}; sendStreamOfCommands(sequenceNumbers, true); } public void testMissingPacketsFails() throws Exception { - int[] sequenceNumbers = { 1, 2, /* 3, */ 4, 5, 6, 7, 8, 9, 10 }; + int[] sequenceNumbers = {1, 2, /* 3, */4, 5, 6, 7, 8, 9, 10}; sendStreamOfCommands(sequenceNumbers, false); } @@ -93,33 +91,32 @@ public class ReliableTransportTest extends TestCase { protected void sendStreamOfCommands(int[] sequenceNumbers, boolean expected) { sendStreamOfCommands(sequenceNumbers, expected, sequenceNumbers.length); } - + protected void sendStreamOfCommands(int[] sequenceNumbers, boolean expected, int expectedCount) { for (int i = 0; i < sequenceNumbers.length; i++) { int commandId = sequenceNumbers[i]; - + ConsumerInfo info = new ConsumerInfo(); info.setSelector("Cheese: " + commandId); info.setCommandId(commandId); transport.onCommand(info); } - + Queue exceptions = listener.getExceptions(); Queue commands = listener.getCommands(); if (expected) { if (!exceptions.isEmpty()) { - Exception e = (Exception) exceptions.remove(); + Exception e = (Exception)exceptions.remove(); e.printStackTrace(); fail("Caught exception: " + e); } assertEquals("number of messages received", expectedCount, commands.size()); - + assertEquals("Should have no buffered commands", 0, transport.getBufferedCommandCount()); - } - else { + } else { assertTrue("Should have received an exception!", exceptions.size() > 0); - Exception e = (Exception) exceptions.remove(); + Exception e = (Exception)exceptions.remove(); log.info("Caught expected response: " + e); } } diff --git a/activemq-core/src/test/java/org/apache/activemq/transport/reliable/UnreliableCommandDatagramSocket.java b/activemq-core/src/test/java/org/apache/activemq/transport/reliable/UnreliableCommandDatagramSocket.java index 4b86128d8b..4fecadd482 100644 --- a/activemq-core/src/test/java/org/apache/activemq/transport/reliable/UnreliableCommandDatagramSocket.java +++ b/activemq-core/src/test/java/org/apache/activemq/transport/reliable/UnreliableCommandDatagramSocket.java @@ -16,6 +16,10 @@ */ package org.apache.activemq.transport.reliable; +import java.io.IOException; +import java.net.DatagramSocket; +import java.net.SocketAddress; + import org.apache.activemq.openwire.OpenWireFormat; import org.apache.activemq.transport.udp.CommandDatagramSocket; import org.apache.activemq.transport.udp.DatagramHeaderMarshaller; @@ -23,12 +27,7 @@ import org.apache.activemq.transport.udp.UdpTransport; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import java.io.IOException; -import java.net.DatagramSocket; -import java.net.SocketAddress; - /** - * * @version $Revision: $ */ public class UnreliableCommandDatagramSocket extends CommandDatagramSocket { @@ -36,15 +35,13 @@ public class UnreliableCommandDatagramSocket extends CommandDatagramSocket { private DropCommandStrategy dropCommandStrategy; - public UnreliableCommandDatagramSocket(UdpTransport transport, OpenWireFormat wireFormat, int datagramSize, - SocketAddress targetAddress, DatagramHeaderMarshaller headerMarshaller, DatagramSocket channel, - DropCommandStrategy strategy) { + public UnreliableCommandDatagramSocket(UdpTransport transport, OpenWireFormat wireFormat, int datagramSize, SocketAddress targetAddress, + DatagramHeaderMarshaller headerMarshaller, DatagramSocket channel, DropCommandStrategy strategy) { super(transport, wireFormat, datagramSize, targetAddress, headerMarshaller, channel); this.dropCommandStrategy = strategy; } - protected void sendWriteBuffer(int commandId, SocketAddress address, byte[] data, boolean redelivery) - throws IOException { + protected void sendWriteBuffer(int commandId, SocketAddress address, byte[] data, boolean redelivery) throws IOException { if (dropCommandStrategy.shouldDropCommand(commandId, address, redelivery)) { log.info("Dropping datagram with command: " + commandId); @@ -53,8 +50,7 @@ public class UnreliableCommandDatagramSocket extends CommandDatagramSocket { if (bufferCache != null && !redelivery) { bufferCache.addBuffer(commandId, data); } - } - else { + } else { super.sendWriteBuffer(commandId, address, data, redelivery); } } diff --git a/activemq-core/src/test/java/org/apache/activemq/transport/stomp/StompConnection.java b/activemq-core/src/test/java/org/apache/activemq/transport/stomp/StompConnection.java index 856db1b9d4..d9ccc07f63 100644 --- a/activemq-core/src/test/java/org/apache/activemq/transport/stomp/StompConnection.java +++ b/activemq-core/src/test/java/org/apache/activemq/transport/stomp/StompConnection.java @@ -24,11 +24,10 @@ import java.io.OutputStream; import java.net.Socket; import java.net.UnknownHostException; - public class StompConnection { public static final long RECEIVE_TIMEOUT = 10000; - + private Socket stompSocket; private ByteArrayOutputStream inputBuffer = new ByteArrayOutputStream(); @@ -36,13 +35,13 @@ public class StompConnection { stompSocket = new Socket(host, port); } - public void close() throws IOException { - if (stompSocket != null) { - stompSocket.close(); - stompSocket = null; - } - } - + public void close() throws IOException { + if (stompSocket != null) { + stompSocket.close(); + stompSocket = null; + } + } + public void sendFrame(String data) throws Exception { byte[] bytes = data.getBytes("UTF-8"); OutputStream outputStream = stompSocket.getOutputStream(); @@ -52,28 +51,26 @@ public class StompConnection { } public String receiveFrame() throws Exception { - return receiveFrame(RECEIVE_TIMEOUT); + return receiveFrame(RECEIVE_TIMEOUT); } private String receiveFrame(long timeOut) throws Exception { - stompSocket.setSoTimeout((int) timeOut); + stompSocket.setSoTimeout((int)timeOut); InputStream is = stompSocket.getInputStream(); int c = 0; for (;;) { c = is.read(); if (c < 0) { throw new IOException("socket closed."); - } - else if (c == 0) { + } else if (c == 0) { c = is.read(); if (c != '\n') { - throw new IOException("Expecting stomp frame to terminate with \0\n"); + throw new IOException("Expecting stomp frame to terminate with \0\n"); } byte[] ba = inputBuffer.toByteArray(); inputBuffer.reset(); return new String(ba, "UTF-8"); - } - else { + } else { inputBuffer.write(c); } } diff --git a/activemq-core/src/test/java/org/apache/activemq/transport/stomp/StompSubscriptionRemoveTest.java b/activemq-core/src/test/java/org/apache/activemq/transport/stomp/StompSubscriptionRemoveTest.java index e207a41ca6..7c0a8c99d7 100644 --- a/activemq-core/src/test/java/org/apache/activemq/transport/stomp/StompSubscriptionRemoveTest.java +++ b/activemq-core/src/test/java/org/apache/activemq/transport/stomp/StompSubscriptionRemoveTest.java @@ -27,7 +27,6 @@ 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; @@ -35,7 +34,7 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** - * + * * @version $Revision$ */ public class StompSubscriptionRemoveTest extends TestCase { @@ -45,7 +44,7 @@ public class StompSubscriptionRemoveTest extends TestCase { private static final int STOMP_PORT = 61613; private StompConnection stompConnection = new StompConnection(); - + public void testRemoveSubscriber() throws Exception { BrokerService broker = new BrokerService(); broker.setPersistent(false); @@ -75,7 +74,7 @@ public class StompSubscriptionRemoveTest extends TestCase { stompConnection.receiveFrame(); String frame = "SUBSCRIBE\n" + "destination:/queue/" + getDestinationName() + "\n" + "ack:client\n\n"; stompConnection.sendFrame(frame); - + int messagesCount = 0; int count = 0; while (count < 2) { @@ -111,12 +110,11 @@ public class StompSubscriptionRemoveTest extends TestCase { String messageId = getHeaderValue(receiveFrame, HEADER_MESSAGE_ID); String ackmessage = "ACK\n" + HEADER_MESSAGE_ID + ":" + messageId.trim() + "\n\n"; stompConnection.sendFrame(ackmessage); - //Thread.sleep(1000); + // Thread.sleep(1000); ++messagesCount; ++count; } - } - catch (IOException ex) { + } catch (IOException ex) { ex.printStackTrace(); } @@ -127,7 +125,8 @@ public class StompSubscriptionRemoveTest extends TestCase { log.info("Total messages received: " + messagesCount); assertTrue("Messages received after connection loss: " + messagesCount, messagesCount >= 2000); - // The first ack messages has no chance complete, so we receiving more messages + // The first ack messages has no chance complete, so we receiving more + // messages // Don't know how to list subscriptions for the broker. Currently you // can check using JMX console. You'll see @@ -140,28 +139,28 @@ public class StompSubscriptionRemoveTest extends TestCase { // These two methods could move to a utility class protected String getCommand(String frame) { - return frame.substring(0, frame.indexOf('\n') + 1).trim(); + return frame.substring(0, frame.indexOf('\n') + 1).trim(); } - protected String getHeaderValue (String frame, String header) throws IOException { + protected String getHeaderValue(String frame, String header) throws IOException { DataInput input = new DataInputStream(new ByteArrayInputStream(frame.getBytes())); String line; - for (int idx = 0; /*forever, sort of*/; ++idx) { + for (int idx = 0; /* forever, sort of */; ++idx) { line = input.readLine(); if (line == null) { - // end of message, no headers - return null; - } + // end of message, no headers + return null; + } line = line.trim(); if (line.length() == 0) { - // start body, no headers from here on - return null; - } - if (idx > 0) { // Ignore command line - int pos = line.indexOf(':'); - if (header.equals(line.substring(0, pos))) { - return line.substring(pos + 1).trim(); - } + // start body, no headers from here on + return null; + } + if (idx > 0) { // Ignore command line + int pos = line.indexOf(':'); + if (header.equals(line.substring(0, pos))) { + return line.substring(pos + 1).trim(); + } } } } diff --git a/activemq-core/src/test/java/org/apache/activemq/transport/tcp/SslTransportFactoryTest.java b/activemq-core/src/test/java/org/apache/activemq/transport/tcp/SslTransportFactoryTest.java index 1da486640e..201accf221 100644 --- a/activemq-core/src/test/java/org/apache/activemq/transport/tcp/SslTransportFactoryTest.java +++ b/activemq-core/src/test/java/org/apache/activemq/transport/tcp/SslTransportFactoryTest.java @@ -17,16 +17,16 @@ package org.apache.activemq.transport.tcp; -import junit.framework.TestCase; -import org.apache.activemq.openwire.OpenWireFormat; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - import java.io.IOException; import java.net.URI; import java.util.HashMap; import java.util.Map; +import junit.framework.TestCase; +import org.apache.activemq.openwire.OpenWireFormat; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + public class SslTransportFactoryTest extends TestCase { private static final transient Log log = LogFactory.getLog(SslTransportFactoryTest.class); @@ -49,50 +49,46 @@ public class SslTransportFactoryTest extends TestCase { final boolean wantClientAuth = ((i & 0x1) == 1); final boolean needClientAuth = ((i & 0x2) == 1); - String options = "wantClientAuth=" + (wantClientAuth ? "true" : "false") + - "&needClientAuth=" + (needClientAuth ? "true" : "false"); + String options = "wantClientAuth=" + (wantClientAuth ? "true" : "false") + "&needClientAuth=" + + (needClientAuth ? "true" : "false"); try { - sslTransportServer = (SslTransportServer) - factory.doBind("brokerId", new URI("ssl://localhost:61616?" + options)); - } - catch (Exception e) { + sslTransportServer = (SslTransportServer)factory.doBind("brokerId", new URI( + "ssl://localhost:61616?" + + options)); + } catch (Exception e) { fail("Unable to bind to address: " + e.getMessage()); } assertEquals("Created ServerSocket did not have correct wantClientAuth status.", - sslTransportServer.getWantClientAuth(), wantClientAuth); + sslTransportServer.getWantClientAuth(), wantClientAuth); assertEquals("Created ServerSocket did not have correct needClientAuth status.", - sslTransportServer.getNeedClientAuth(), needClientAuth); + sslTransportServer.getNeedClientAuth(), needClientAuth); try { sslTransportServer.stop(); - } - catch (Exception e) { + } catch (Exception e) { fail("Unable to stop TransportServer: " + e.getMessage()); } } } private int getMthNaryDigit(int number, int digitIdx, int numBase) { - return (number / ((int) Math.pow(numBase, digitIdx))) % numBase; + return (number / ((int)Math.pow(numBase, digitIdx))) % numBase; } public void testCompositeConfigure() throws IOException { // The 5 options being tested. int optionSettings[] = new int[5]; - String optionNames[] = { - "wantClientAuth", - "needClientAuth", - "socket.wantClientAuth", - "socket.needClientAuth", - "socket.useClientMode" - }; + String optionNames[] = {"wantClientAuth", "needClientAuth", "socket.wantClientAuth", + "socket.needClientAuth", "socket.useClientMode"}; - // Using a trinary interpretation of i to set all possible values of stub options for socket and transport. - // 2 transport options, 3 socket options, 3 settings for each option => 3^5 = 243 combos. + // Using a trinary interpretation of i to set all possible values of + // stub options for socket and transport. + // 2 transport options, 3 socket options, 3 settings for each option => + // 3^5 = 243 combos. for (int i = 0; i < 243; ++i) { Map options = new HashMap(); @@ -110,8 +106,7 @@ public class SslTransportFactoryTest extends TestCase { try { transport = new StubSslTransport(null, socketStub); - } - catch (Exception e) { + } catch (Exception e) { fail("Unable to create StubSslTransport: " + e.getMessage()); } @@ -129,8 +124,7 @@ public class SslTransportFactoryTest extends TestCase { // lets start the transport to force the introspection try { transport.start(); - } - catch (Exception e) { + } catch (Exception e) { // ignore bad connection } @@ -138,16 +132,16 @@ public class SslTransportFactoryTest extends TestCase { log.info("sheiite"); } - assertEquals("wantClientAuth was not properly set for iteration: " + i, - optionSettings[0], transport.getWantClientAuthStatus()); - assertEquals("needClientAuth was not properly set for iteration: " + i, - optionSettings[1], transport.getNeedClientAuthStatus()); - assertEquals("socket.wantClientAuth was not properly set for iteration: " + i, - optionSettings[2], socketStub.getWantClientAuthStatus()); - assertEquals("socket.needClientAuth was not properly set for iteration: " + i, - optionSettings[3], socketStub.getNeedClientAuthStatus()); - assertEquals("socket.useClientMode was not properly set for iteration: " + i, - optionSettings[4], socketStub.getUseClientModeStatus()); + assertEquals("wantClientAuth was not properly set for iteration: " + i, optionSettings[0], + transport.getWantClientAuthStatus()); + assertEquals("needClientAuth was not properly set for iteration: " + i, optionSettings[1], + transport.getNeedClientAuthStatus()); + assertEquals("socket.wantClientAuth was not properly set for iteration: " + i, optionSettings[2], + socketStub.getWantClientAuthStatus()); + assertEquals("socket.needClientAuth was not properly set for iteration: " + i, optionSettings[3], + socketStub.getNeedClientAuthStatus()); + assertEquals("socket.useClientMode was not properly set for iteration: " + i, optionSettings[4], + socketStub.getUseClientModeStatus()); } } } diff --git a/activemq-core/src/test/java/org/apache/activemq/transport/tcp/StubSSLSocketFactory.java b/activemq-core/src/test/java/org/apache/activemq/transport/tcp/StubSSLSocketFactory.java index 5b4bac75fc..fa13cc30ff 100644 --- a/activemq-core/src/test/java/org/apache/activemq/transport/tcp/StubSSLSocketFactory.java +++ b/activemq-core/src/test/java/org/apache/activemq/transport/tcp/StubSSLSocketFactory.java @@ -20,33 +20,30 @@ package org.apache.activemq.transport.tcp; import java.io.IOException; import java.net.InetAddress; import java.net.ServerSocket; -import java.net.Socket; import javax.net.ssl.SSLServerSocketFactory; public class StubSSLSocketFactory extends SSLServerSocketFactory { - + private final ServerSocket retServerSocket; - + public StubSSLSocketFactory(ServerSocket returnServerSocket) { retServerSocket = returnServerSocket; } - + public ServerSocket createServerSocket(int arg0) throws IOException { return retServerSocket; } - public ServerSocket createServerSocket(int arg0, int arg1) - throws IOException { + public ServerSocket createServerSocket(int arg0, int arg1) throws IOException { return retServerSocket; } - - public ServerSocket createServerSocket(int arg0, int arg1, InetAddress arg2) - throws IOException { + + public ServerSocket createServerSocket(int arg0, int arg1, InetAddress arg2) throws IOException { return retServerSocket; } - - // --- Stubbed Methods --- + + // --- Stubbed Methods --- public String[] getDefaultCipherSuites() { return null; diff --git a/activemq-core/src/test/java/org/apache/activemq/transport/tcp/StubX509Certificate.java b/activemq-core/src/test/java/org/apache/activemq/transport/tcp/StubX509Certificate.java index ffbbbc9843..a41fad4dd4 100644 --- a/activemq-core/src/test/java/org/apache/activemq/transport/tcp/StubX509Certificate.java +++ b/activemq-core/src/test/java/org/apache/activemq/transport/tcp/StubX509Certificate.java @@ -20,146 +20,145 @@ package org.apache.activemq.transport.tcp; import java.math.BigInteger; import java.security.Principal; import java.security.PublicKey; +import java.security.cert.X509Certificate; import java.util.Date; import java.util.Set; -import java.security.cert.X509Certificate; - public class StubX509Certificate extends X509Certificate { public StubX509Certificate(Principal id) { this.id = id; } - + public Principal getSubjectDN() { return this.id; } - + private final Principal id; - + // --- Stubbed Methods --- public void checkValidity() { - // TODO Auto-generated method stub - + // TODO Auto-generated method stub + } - + public void checkValidity(Date arg0) { - // TODO Auto-generated method stub - + // TODO Auto-generated method stub + } - + public int getVersion() { - // TODO Auto-generated method stub - return 0; + // TODO Auto-generated method stub + return 0; } - + public BigInteger getSerialNumber() { - // TODO Auto-generated method stub - return null; + // TODO Auto-generated method stub + return null; } - + public Principal getIssuerDN() { - // TODO Auto-generated method stub - return null; + // TODO Auto-generated method stub + return null; } - + public Date getNotBefore() { - // TODO Auto-generated method stub - return null; + // TODO Auto-generated method stub + return null; } - + public Date getNotAfter() { - // TODO Auto-generated method stub - return null; + // TODO Auto-generated method stub + return null; } - + public byte[] getTBSCertificate() { - // TODO Auto-generated method stub - return null; + // TODO Auto-generated method stub + return null; } - + public byte[] getSignature() { - // TODO Auto-generated method stub - return null; + // TODO Auto-generated method stub + return null; } - + public String getSigAlgName() { - // TODO Auto-generated method stub - return null; + // TODO Auto-generated method stub + return null; } - + public String getSigAlgOID() { - // TODO Auto-generated method stub - return null; + // TODO Auto-generated method stub + return null; } - + public byte[] getSigAlgParams() { - // TODO Auto-generated method stub - return null; + // TODO Auto-generated method stub + return null; } - + public boolean[] getIssuerUniqueID() { - // TODO Auto-generated method stub - return null; + // TODO Auto-generated method stub + return null; } - + public boolean[] getSubjectUniqueID() { - // TODO Auto-generated method stub - return null; + // TODO Auto-generated method stub + return null; } - + public boolean[] getKeyUsage() { - // TODO Auto-generated method stub - return null; + // TODO Auto-generated method stub + return null; } - + public int getBasicConstraints() { - // TODO Auto-generated method stub - return 0; + // TODO Auto-generated method stub + return 0; } - + public byte[] getEncoded() { - // TODO Auto-generated method stub - return null; + // TODO Auto-generated method stub + return null; } - + public void verify(PublicKey arg0) { - // TODO Auto-generated method stub - + // TODO Auto-generated method stub + } - + public void verify(PublicKey arg0, String arg1) { - // TODO Auto-generated method stub - + // TODO Auto-generated method stub + } - + public String toString() { - // TODO Auto-generated method stub - return null; + // TODO Auto-generated method stub + return null; } - + public PublicKey getPublicKey() { - // TODO Auto-generated method stub - return null; + // TODO Auto-generated method stub + return null; } - + public boolean hasUnsupportedCriticalExtension() { - // TODO Auto-generated method stub - return false; + // TODO Auto-generated method stub + return false; } - + public Set getCriticalExtensionOIDs() { - // TODO Auto-generated method stub - return null; + // TODO Auto-generated method stub + return null; } - + public Set getNonCriticalExtensionOIDs() { - // TODO Auto-generated method stub - return null; + // TODO Auto-generated method stub + return null; } - + public byte[] getExtensionValue(String arg0) { - // TODO Auto-generated method stub - return null; + // TODO Auto-generated method stub + return null; } } diff --git a/activemq-core/src/test/java/org/apache/activemq/transport/udp/UdpTestSupport.java b/activemq-core/src/test/java/org/apache/activemq/transport/udp/UdpTestSupport.java index 04b4ffb949..36fac516f4 100644 --- a/activemq-core/src/test/java/org/apache/activemq/transport/udp/UdpTestSupport.java +++ b/activemq-core/src/test/java/org/apache/activemq/transport/udp/UdpTestSupport.java @@ -21,7 +21,6 @@ import java.io.IOException; import javax.jms.MessageNotWriteableException; import junit.framework.TestCase; - import org.apache.activemq.command.ActiveMQDestination; import org.apache.activemq.command.ActiveMQQueue; import org.apache.activemq.command.ActiveMQTextMessage; @@ -38,7 +37,6 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** - * * @version $Revision$ */ public abstract class UdpTestSupport extends TestCase implements TransportListener { @@ -69,12 +67,11 @@ public abstract class UdpTestSupport extends TestCase implements TransportListen Command received = assertCommandReceived(); assertTrue("Should have received a ConsumerInfo but was: " + received, received instanceof ConsumerInfo); - ConsumerInfo actual = (ConsumerInfo) received; + ConsumerInfo actual = (ConsumerInfo)received; assertEquals("Selector", expected.getSelector(), actual.getSelector()); assertEquals("isExclusive", expected.isExclusive(), actual.isExclusive()); assertEquals("getPrefetchSize", expected.getPrefetchSize(), actual.getPrefetchSize()); - } - catch (Exception e) { + } catch (Exception e) { log.info("Caught: " + e); e.printStackTrace(); fail("Failed to send to transport: " + e); @@ -93,8 +90,7 @@ public abstract class UdpTestSupport extends TestCase implements TransportListen assertSendTextMessage(destination, text); } - protected void assertSendTextMessage(ActiveMQDestination destination, String text) - throws MessageNotWriteableException { + protected void assertSendTextMessage(ActiveMQDestination destination, String text) throws MessageNotWriteableException { large = true; ActiveMQTextMessage expected = new ActiveMQTextMessage(); @@ -114,16 +110,14 @@ public abstract class UdpTestSupport extends TestCase implements TransportListen producer.oneway(new ProducerInfo()); Command received = assertCommandReceived(); - assertTrue("Should have received a ActiveMQTextMessage but was: " + received, - received instanceof ActiveMQTextMessage); - ActiveMQTextMessage actual = (ActiveMQTextMessage) received; + assertTrue("Should have received a ActiveMQTextMessage but was: " + received, received instanceof ActiveMQTextMessage); + ActiveMQTextMessage actual = (ActiveMQTextMessage)received; assertEquals("getDestination", expected.getDestination(), actual.getDestination()); assertEquals("getText", expected.getText(), actual.getText()); log.info("Received text message with: " + actual.getText().length() + " character(s)"); - } - catch (Exception e) { + } catch (Exception e) { log.info("Caught: " + e); e.printStackTrace(); fail("Failed to send to transport: " + e); @@ -148,8 +142,7 @@ public abstract class UdpTestSupport extends TestCase implements TransportListen consumer.setTransportListener(UdpTestSupport.this); try { consumer.start(); - } - catch (Exception e) { + } catch (Exception e) { throw new RuntimeException(e); } } @@ -200,29 +193,25 @@ public abstract class UdpTestSupport extends TestCase implements TransportListen } public void onCommand(Object o) { - final Command command = (Command) o; + final Command command = (Command)o; if (command instanceof WireFormatInfo) { log.info("Got WireFormatInfo: " + command); - } - else { + } else { if (command.isResponseRequired()) { // lets send a response back... sendResponse(command); } if (large) { - log.info("### Received command: " + command.getClass() + " with id: " - + command.getCommandId()); - } - else { + log.info("### Received command: " + command.getClass() + " with id: " + command.getCommandId()); + } else { log.info("### Received command: " + command); } synchronized (lock) { if (receivedCommand == null) { receivedCommand = command; - } - else { + } else { log.info("Ignoring superfluous command: " + command); } lock.notifyAll(); @@ -235,8 +224,7 @@ public abstract class UdpTestSupport extends TestCase implements TransportListen response.setCorrelationId(command.getCommandId()); try { consumer.oneway(response); - } - catch (IOException e) { + } catch (IOException e) { log.info("Caught: " + e); e.printStackTrace(); throw new RuntimeException(e); diff --git a/activemq-core/src/test/java/org/apache/activemq/usecases/AMQFailoverIssue.java b/activemq-core/src/test/java/org/apache/activemq/usecases/AMQFailoverIssue.java index 01751f4c77..260d1ac4c9 100644 --- a/activemq-core/src/test/java/org/apache/activemq/usecases/AMQFailoverIssue.java +++ b/activemq-core/src/test/java/org/apache/activemq/usecases/AMQFailoverIssue.java @@ -66,7 +66,7 @@ public class AMQFailoverIssue extends TestCase { // This should fail with incubator-activemq-fuse-4.1.0.5 public void testFailoverIssue() throws Exception { - BrokerService brokerService1=null; + BrokerService brokerService1 = null; ActiveMQConnectionFactory acf; PooledConnectionFactory pcf; DefaultMessageListenerContainer container1 = null; diff --git a/activemq-core/src/test/java/org/apache/activemq/usecases/AMQStackOverFlowTest.java b/activemq-core/src/test/java/org/apache/activemq/usecases/AMQStackOverFlowTest.java index c8d3fe1704..f60e5410b7 100644 --- a/activemq-core/src/test/java/org/apache/activemq/usecases/AMQStackOverFlowTest.java +++ b/activemq-core/src/test/java/org/apache/activemq/usecases/AMQStackOverFlowTest.java @@ -19,10 +19,12 @@ package org.apache.activemq.usecases; import java.net.URI; import java.util.ArrayList; + import javax.jms.JMSException; import javax.jms.Message; import javax.jms.Session; import javax.jms.TextMessage; + import junit.framework.Assert; import junit.framework.TestCase; import org.apache.activemq.ActiveMQConnectionFactory; @@ -38,117 +40,112 @@ import org.springframework.jms.core.MessageCreator; public class AMQStackOverFlowTest extends TestCase { - private static final String URL1 = "tcp://localhost:61616"; + private static final String URL1 = "tcp://localhost:61616"; - private static final String URL2 = "tcp://localhost:61617"; + private static final String URL2 = "tcp://localhost:61617"; - public void testStackOverflow() throws Exception { - BrokerService brokerService1 = null; - BrokerService brokerService2 = null; + 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(); + 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 cf1 = new ActiveMQConnectionFactory(URL1); + cf1.setUseAsyncSend(false); - final ActiveMQConnectionFactory cf2 = new ActiveMQConnectionFactory( - URL2); - cf2.setUseAsyncSend(false); + final ActiveMQConnectionFactory cf2 = new ActiveMQConnectionFactory(URL2); + cf2.setUseAsyncSend(false); - final JmsTemplate template1 = new JmsTemplate(cf1); - template1.setReceiveTimeout(10000); + final JmsTemplate template1 = new JmsTemplate(cf1); + template1.setReceiveTimeout(10000); - template1.send("test.q", new MessageCreator() { + template1.send("test.q", new MessageCreator() { - public Message createMessage(Session session) - throws JMSException { - return session.createTextMessage("test"); - } + public Message createMessage(Session session) throws JMSException { + return session.createTextMessage("test"); + } - }); + }); - final JmsTemplate template2 = new JmsTemplate(cf2); - template2.setReceiveTimeout(10000); + 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; + final Message m = template2.receive("test.q"); + assertTrue(m instanceof TextMessage); - Assert.assertEquals("test", tm.getText()); + final TextMessage tm = (TextMessage)m; - template2.send("test2.q", new MessageCreator() { + Assert.assertEquals("test", tm.getText()); - public Message createMessage(Session session) - throws JMSException { - return session.createTextMessage("test2"); - } + template2.send("test2.q", new MessageCreator() { - }); + public Message createMessage(Session session) throws JMSException { + return session.createTextMessage("test2"); + } - final Message m2 = template1.receive("test2.q"); + }); + + final Message m2 = template1.receive("test2.q"); assertTrue(m2 instanceof TextMessage); - final TextMessage tm2 = (TextMessage) m2; + final TextMessage tm2 = (TextMessage)m2; - Assert.assertEquals("test2", tm2.getText()); + Assert.assertEquals("test2", tm2.getText()); - } finally { + } finally { - brokerService1.stop(); - brokerService1 = null; - brokerService2.stop(); - brokerService2 = null; + 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(); + 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); + brokerService.setBrokerName(brokerName); + brokerService.setPersistent(false); + brokerService.setUseJmx(true); - final UsageManager memoryManager = new UsageManager(); - memoryManager.setLimit(10); - brokerService.setMemoryManager(memoryManager); + final UsageManager memoryManager = new UsageManager(); + memoryManager.setLimit(10); + brokerService.setMemoryManager(memoryManager); - final ArrayList policyEntries = new ArrayList(); + final ArrayList policyEntries = new ArrayList(); - final PolicyEntry entry = new PolicyEntry(); - entry.setQueue(">"); - entry.setMemoryLimit(1); - policyEntries.add(entry); + 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 PolicyMap policyMap = new PolicyMap(); + policyMap.setPolicyEntries(policyEntries); + brokerService.setDestinationPolicy(policyMap); - final TransportConnector tConnector = new TransportConnector(); - tConnector.setUri(new URI(uri1)); - tConnector.setBrokerName(brokerName); - tConnector.setName(brokerName + ".transportConnector"); - brokerService.addConnector(tConnector); + final TransportConnector tConnector = new TransportConnector(); + tConnector.setUri(new URI(uri1)); + tConnector.setBrokerName(brokerName); + 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); - } + 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; + return brokerService; - } + } } diff --git a/activemq-core/src/test/java/org/apache/activemq/usecases/TwoBrokerTopicSendReceiveTest.java b/activemq-core/src/test/java/org/apache/activemq/usecases/TwoBrokerTopicSendReceiveTest.java index 51d1656089..940dd16f81 100644 --- a/activemq-core/src/test/java/org/apache/activemq/usecases/TwoBrokerTopicSendReceiveTest.java +++ b/activemq-core/src/test/java/org/apache/activemq/usecases/TwoBrokerTopicSendReceiveTest.java @@ -47,12 +47,13 @@ public class TwoBrokerTopicSendReceiveTest extends JmsTopicSendReceiveWithTwoCon 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"); + return createConnectionFactory("org/apache/activemq/usecases/receiver.xml", "receiver", + "vm://receiver"); } protected ActiveMQConnectionFactory createSenderConnectionFactory() throws JMSException { @@ -61,11 +62,11 @@ public class TwoBrokerTopicSendReceiveTest extends JmsTopicSendReceiveWithTwoCon protected void tearDown() throws Exception { super.tearDown(); - for (Iterator iter = brokers.values().iterator(); iter.hasNext();) { - BrokerService broker = (BrokerService) iter.next(); - ServiceSupport.dispose(broker); - iter.remove(); - } + for (Iterator iter = brokers.values().iterator(); iter.hasNext();) { + BrokerService broker = (BrokerService)iter.next(); + ServiceSupport.dispose(broker); + iter.remove(); + } } protected Connection createReceiveConnection() throws JMSException { @@ -76,13 +77,14 @@ public class TwoBrokerTopicSendReceiveTest extends JmsTopicSendReceiveWithTwoCon return sendFactory.createConnection(); } - protected ActiveMQConnectionFactory createConnectionFactory(String config, String brokerName, String connectUrl) throws JMSException { + 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) {