[jbosscache-commits] JBoss Cache SVN: r7491 - in core/branches/flat/src: main/java/org/horizon/annotations and 63 other directories.
jbosscache-commits at lists.jboss.org
jbosscache-commits at lists.jboss.org
Fri Jan 16 10:41:04 EST 2009
Author: manik.surtani at jboss.com
Date: 2009-01-16 10:41:03 -0500 (Fri, 16 Jan 2009)
New Revision: 7491
Modified:
core/branches/flat/src/main/java/org/horizon/Cache.java
core/branches/flat/src/main/java/org/horizon/CacheDelegate.java
core/branches/flat/src/main/java/org/horizon/CacheException.java
core/branches/flat/src/main/java/org/horizon/CacheSPI.java
core/branches/flat/src/main/java/org/horizon/CacheStatus.java
core/branches/flat/src/main/java/org/horizon/EvictionManager.java
core/branches/flat/src/main/java/org/horizon/Version.java
core/branches/flat/src/main/java/org/horizon/annotations/MBean.java
core/branches/flat/src/main/java/org/horizon/annotations/ManagedAttribute.java
core/branches/flat/src/main/java/org/horizon/annotations/ManagedOperation.java
core/branches/flat/src/main/java/org/horizon/atomic/AtomicHashMap.java
core/branches/flat/src/main/java/org/horizon/atomic/AtomicHashMapDelta.java
core/branches/flat/src/main/java/org/horizon/atomic/AtomicHashMapProxy.java
core/branches/flat/src/main/java/org/horizon/atomic/AtomicMap.java
core/branches/flat/src/main/java/org/horizon/atomic/AtomicMapCache.java
core/branches/flat/src/main/java/org/horizon/atomic/ClearOperation.java
core/branches/flat/src/main/java/org/horizon/atomic/Delta.java
core/branches/flat/src/main/java/org/horizon/atomic/DeltaAware.java
core/branches/flat/src/main/java/org/horizon/atomic/NullDelta.java
core/branches/flat/src/main/java/org/horizon/atomic/Operation.java
core/branches/flat/src/main/java/org/horizon/atomic/PutOperation.java
core/branches/flat/src/main/java/org/horizon/atomic/RemoveOperation.java
core/branches/flat/src/main/java/org/horizon/batch/AutoBatchSupport.java
core/branches/flat/src/main/java/org/horizon/batch/BatchContainer.java
core/branches/flat/src/main/java/org/horizon/cluster/ReplicationQueue.java
core/branches/flat/src/main/java/org/horizon/commands/AbstractVisitor.java
core/branches/flat/src/main/java/org/horizon/commands/CommandsFactory.java
core/branches/flat/src/main/java/org/horizon/commands/CommandsFactoryImpl.java
core/branches/flat/src/main/java/org/horizon/commands/DataCommand.java
core/branches/flat/src/main/java/org/horizon/commands/ReplicableCommand.java
core/branches/flat/src/main/java/org/horizon/commands/TransactionBoundaryCommand.java
core/branches/flat/src/main/java/org/horizon/commands/VisitableCommand.java
core/branches/flat/src/main/java/org/horizon/commands/Visitor.java
core/branches/flat/src/main/java/org/horizon/commands/read/AbstractDataCommand.java
core/branches/flat/src/main/java/org/horizon/commands/read/GetKeyValueCommand.java
core/branches/flat/src/main/java/org/horizon/commands/read/SizeCommand.java
core/branches/flat/src/main/java/org/horizon/commands/remote/ClusteredGetCommand.java
core/branches/flat/src/main/java/org/horizon/commands/remote/ReplicateCommand.java
core/branches/flat/src/main/java/org/horizon/commands/tx/AbstractTransactionBoundaryCommand.java
core/branches/flat/src/main/java/org/horizon/commands/tx/CommitCommand.java
core/branches/flat/src/main/java/org/horizon/commands/tx/PrepareCommand.java
core/branches/flat/src/main/java/org/horizon/commands/tx/RollbackCommand.java
core/branches/flat/src/main/java/org/horizon/commands/write/ClearCommand.java
core/branches/flat/src/main/java/org/horizon/commands/write/EvictCommand.java
core/branches/flat/src/main/java/org/horizon/commands/write/InvalidateCommand.java
core/branches/flat/src/main/java/org/horizon/commands/write/PutKeyValueCommand.java
core/branches/flat/src/main/java/org/horizon/commands/write/PutMapCommand.java
core/branches/flat/src/main/java/org/horizon/commands/write/RemoveCommand.java
core/branches/flat/src/main/java/org/horizon/commands/write/ReplaceCommand.java
core/branches/flat/src/main/java/org/horizon/config/CacheLoaderConfig.java
core/branches/flat/src/main/java/org/horizon/config/CloneableConfigurationComponent.java
core/branches/flat/src/main/java/org/horizon/config/Configuration.java
core/branches/flat/src/main/java/org/horizon/config/ConfigurationComponent.java
core/branches/flat/src/main/java/org/horizon/config/ConfigurationException.java
core/branches/flat/src/main/java/org/horizon/config/ConfigurationRegistry.java
core/branches/flat/src/main/java/org/horizon/config/CustomInterceptorConfig.java
core/branches/flat/src/main/java/org/horizon/config/Dynamic.java
core/branches/flat/src/main/java/org/horizon/config/EvictionAlgorithmConfig.java
core/branches/flat/src/main/java/org/horizon/config/EvictionCacheConfig.java
core/branches/flat/src/main/java/org/horizon/config/EvictionConfig.java
core/branches/flat/src/main/java/org/horizon/config/GlobalConfiguration.java
core/branches/flat/src/main/java/org/horizon/config/MissingPolicyException.java
core/branches/flat/src/main/java/org/horizon/config/NonOverridable.java
core/branches/flat/src/main/java/org/horizon/config/OldFileFormatException.java
core/branches/flat/src/main/java/org/horizon/config/Option.java
core/branches/flat/src/main/java/org/horizon/config/PluggableConfigurationComponent.java
core/branches/flat/src/main/java/org/horizon/config/RuntimeConfig.java
core/branches/flat/src/main/java/org/horizon/config/UnsupportedEvictionImplException.java
core/branches/flat/src/main/java/org/horizon/config/XmlParsingConfigurationRegistry.java
core/branches/flat/src/main/java/org/horizon/config/parsing/CacheConfigsXmlParser.java
core/branches/flat/src/main/java/org/horizon/config/parsing/ConfigFilesConvertor.java
core/branches/flat/src/main/java/org/horizon/config/parsing/JGroupsStackParser.java
core/branches/flat/src/main/java/org/horizon/config/parsing/ParsedAttributes.java
core/branches/flat/src/main/java/org/horizon/config/parsing/RootElementBuilder.java
core/branches/flat/src/main/java/org/horizon/config/parsing/XmlConfigHelper.java
core/branches/flat/src/main/java/org/horizon/config/parsing/XmlConfigurationParser.java
core/branches/flat/src/main/java/org/horizon/config/parsing/XmlConfigurationParserImpl.java
core/branches/flat/src/main/java/org/horizon/config/parsing/XmlConfigurationParserJBC3.java
core/branches/flat/src/main/java/org/horizon/config/parsing/XmlParserBase.java
core/branches/flat/src/main/java/org/horizon/config/parsing/element/CustomInterceptorsElementParser.java
core/branches/flat/src/main/java/org/horizon/config/parsing/element/EvictionElementParser.java
core/branches/flat/src/main/java/org/horizon/config/parsing/element/LoadersElementParser.java
core/branches/flat/src/main/java/org/horizon/container/DataContainer.java
core/branches/flat/src/main/java/org/horizon/container/MVCCEntry.java
core/branches/flat/src/main/java/org/horizon/container/NullMarkerEntry.java
core/branches/flat/src/main/java/org/horizon/container/ReadCommittedEntry.java
core/branches/flat/src/main/java/org/horizon/container/RepeatableReadEntry.java
core/branches/flat/src/main/java/org/horizon/container/UnsortedDataContainer.java
core/branches/flat/src/main/java/org/horizon/context/EntryLookup.java
core/branches/flat/src/main/java/org/horizon/context/InvocationContext.java
core/branches/flat/src/main/java/org/horizon/context/InvocationContextImpl.java
core/branches/flat/src/main/java/org/horizon/context/TransactionContext.java
core/branches/flat/src/main/java/org/horizon/context/TransactionContextImpl.java
core/branches/flat/src/main/java/org/horizon/eviction/DefaultEvictionAction.java
core/branches/flat/src/main/java/org/horizon/eviction/ElementSizeAlgorithmConfig.java
core/branches/flat/src/main/java/org/horizon/eviction/ElementSizeQueue.java
core/branches/flat/src/main/java/org/horizon/eviction/EvictionAction.java
core/branches/flat/src/main/java/org/horizon/eviction/EvictionAlgorithm.java
core/branches/flat/src/main/java/org/horizon/eviction/EvictionAlgorithmConfigBase.java
core/branches/flat/src/main/java/org/horizon/eviction/EvictionCacheManager.java
core/branches/flat/src/main/java/org/horizon/eviction/EvictionCacheManagerImpl.java
core/branches/flat/src/main/java/org/horizon/eviction/EvictionEvent.java
core/branches/flat/src/main/java/org/horizon/eviction/EvictionException.java
core/branches/flat/src/main/java/org/horizon/eviction/EvictionManagerImpl.java
core/branches/flat/src/main/java/org/horizon/eviction/EvictionQueue.java
core/branches/flat/src/main/java/org/horizon/eviction/EvictionTimerTask.java
core/branches/flat/src/main/java/org/horizon/eviction/EvictionWatcher.java
core/branches/flat/src/main/java/org/horizon/eviction/ExpirationAlgorithmConfig.java
core/branches/flat/src/main/java/org/horizon/eviction/KeyEntry.java
core/branches/flat/src/main/java/org/horizon/eviction/RegionNameConflictException.java
core/branches/flat/src/main/java/org/horizon/eviction/RemoveOnEvictActionPolicy.java
core/branches/flat/src/main/java/org/horizon/eviction/algorithms/BaseEvictionAlgorithm.java
core/branches/flat/src/main/java/org/horizon/eviction/algorithms/BaseSortedEvictionAlgorithm.java
core/branches/flat/src/main/java/org/horizon/eviction/algorithms/ElementSizeAlgorithm.java
core/branches/flat/src/main/java/org/horizon/eviction/algorithms/ExpirationAlgorithm.java
core/branches/flat/src/main/java/org/horizon/eviction/algorithms/NULL/NullEvictionAlgorithm.java
core/branches/flat/src/main/java/org/horizon/eviction/algorithms/NULL/NullEvictionAlgorithmConfig.java
core/branches/flat/src/main/java/org/horizon/eviction/algorithms/NULL/NullEvictionQueue.java
core/branches/flat/src/main/java/org/horizon/eviction/algorithms/SortedEvictionQueue.java
core/branches/flat/src/main/java/org/horizon/eviction/algorithms/fifo/FIFOAlgorithm.java
core/branches/flat/src/main/java/org/horizon/eviction/algorithms/fifo/FIFOAlgorithmConfig.java
core/branches/flat/src/main/java/org/horizon/eviction/algorithms/fifo/FIFOQueue.java
core/branches/flat/src/main/java/org/horizon/eviction/algorithms/lfu/LFUAlgorithm.java
core/branches/flat/src/main/java/org/horizon/eviction/algorithms/lfu/LFUAlgorithmConfig.java
core/branches/flat/src/main/java/org/horizon/eviction/algorithms/lfu/LFUQueue.java
core/branches/flat/src/main/java/org/horizon/eviction/algorithms/lru/LRUAlgorithm.java
core/branches/flat/src/main/java/org/horizon/eviction/algorithms/lru/LRUAlgorithmConfig.java
core/branches/flat/src/main/java/org/horizon/eviction/algorithms/lru/LRUQueue.java
core/branches/flat/src/main/java/org/horizon/eviction/algorithms/mru/EvictionListEntry.java
core/branches/flat/src/main/java/org/horizon/eviction/algorithms/mru/EvictionQueueList.java
core/branches/flat/src/main/java/org/horizon/eviction/algorithms/mru/MRUAlgorithm.java
core/branches/flat/src/main/java/org/horizon/eviction/algorithms/mru/MRUAlgorithmConfig.java
core/branches/flat/src/main/java/org/horizon/eviction/algorithms/mru/MRUQueue.java
core/branches/flat/src/main/java/org/horizon/executors/DefaultExecutorFactory.java
core/branches/flat/src/main/java/org/horizon/executors/DefaultScheduledExecutorFactory.java
core/branches/flat/src/main/java/org/horizon/executors/ExecutorFactory.java
core/branches/flat/src/main/java/org/horizon/executors/ScheduledExecutorFactory.java
core/branches/flat/src/main/java/org/horizon/factories/AbstractComponentRegistry.java
core/branches/flat/src/main/java/org/horizon/factories/BootstrapFactory.java
core/branches/flat/src/main/java/org/horizon/factories/ComponentFactory.java
core/branches/flat/src/main/java/org/horizon/factories/ComponentRegistry.java
core/branches/flat/src/main/java/org/horizon/factories/DataContainerFactory.java
core/branches/flat/src/main/java/org/horizon/factories/DefaultCacheFactory.java
core/branches/flat/src/main/java/org/horizon/factories/EmptyConstructorFactory.java
core/branches/flat/src/main/java/org/horizon/factories/EntryFactory.java
core/branches/flat/src/main/java/org/horizon/factories/EntryFactoryImpl.java
core/branches/flat/src/main/java/org/horizon/factories/EvictionManagerFactory.java
core/branches/flat/src/main/java/org/horizon/factories/GlobalComponentRegistry.java
core/branches/flat/src/main/java/org/horizon/factories/InterceptorChainFactory.java
core/branches/flat/src/main/java/org/horizon/factories/LockManagerFactory.java
core/branches/flat/src/main/java/org/horizon/factories/ReplicationQueueFactory.java
core/branches/flat/src/main/java/org/horizon/factories/RuntimeConfigAwareFactory.java
core/branches/flat/src/main/java/org/horizon/factories/StateTransferFactory.java
core/branches/flat/src/main/java/org/horizon/factories/StateTransferManagerFactory.java
core/branches/flat/src/main/java/org/horizon/factories/TransactionManagerFactory.java
core/branches/flat/src/main/java/org/horizon/factories/annotations/DefaultFactoryFor.java
core/branches/flat/src/main/java/org/horizon/factories/annotations/Destroy.java
core/branches/flat/src/main/java/org/horizon/factories/annotations/Inject.java
core/branches/flat/src/main/java/org/horizon/factories/annotations/NonVolatile.java
core/branches/flat/src/main/java/org/horizon/factories/annotations/Start.java
core/branches/flat/src/main/java/org/horizon/factories/annotations/Stop.java
core/branches/flat/src/main/java/org/horizon/factories/context/ContextFactory.java
core/branches/flat/src/main/java/org/horizon/factories/scopes/Scope.java
core/branches/flat/src/main/java/org/horizon/factories/scopes/ScopeDetector.java
core/branches/flat/src/main/java/org/horizon/factories/scopes/Scopes.java
core/branches/flat/src/main/java/org/horizon/interceptors/BaseTransactionalContextInterceptor.java
core/branches/flat/src/main/java/org/horizon/interceptors/BatchingInterceptor.java
core/branches/flat/src/main/java/org/horizon/interceptors/CacheLoaderInterceptor.java
core/branches/flat/src/main/java/org/horizon/interceptors/CacheMgmtInterceptor.java
core/branches/flat/src/main/java/org/horizon/interceptors/CacheStoreInterceptor.java
core/branches/flat/src/main/java/org/horizon/interceptors/CallInterceptor.java
core/branches/flat/src/main/java/org/horizon/interceptors/EvictionInterceptor.java
core/branches/flat/src/main/java/org/horizon/interceptors/InterceptorChain.java
core/branches/flat/src/main/java/org/horizon/interceptors/InvalidationInterceptor.java
core/branches/flat/src/main/java/org/horizon/interceptors/InvocationContextInterceptor.java
core/branches/flat/src/main/java/org/horizon/interceptors/LockingInterceptor.java
core/branches/flat/src/main/java/org/horizon/interceptors/MarshalledValueInterceptor.java
core/branches/flat/src/main/java/org/horizon/interceptors/NotificationInterceptor.java
core/branches/flat/src/main/java/org/horizon/interceptors/ReplicationInterceptor.java
core/branches/flat/src/main/java/org/horizon/interceptors/TxInterceptor.java
core/branches/flat/src/main/java/org/horizon/interceptors/base/BaseRpcInterceptor.java
core/branches/flat/src/main/java/org/horizon/interceptors/base/CommandInterceptor.java
core/branches/flat/src/main/java/org/horizon/interceptors/base/JmxStatsCommandInterceptor.java
core/branches/flat/src/main/java/org/horizon/interceptors/base/PrePostProcessingCommandInterceptor.java
core/branches/flat/src/main/java/org/horizon/invocation/InvocationContextContainer.java
core/branches/flat/src/main/java/org/horizon/io/ByteBuffer.java
core/branches/flat/src/main/java/org/horizon/io/ExposedByteArrayOutputStream.java
core/branches/flat/src/main/java/org/horizon/jmx/JmxRegistrationManager.java
core/branches/flat/src/main/java/org/horizon/jmx/JmxStatisticsExposer.java
core/branches/flat/src/main/java/org/horizon/jmx/PlatformMBeanServerRegistration.java
core/branches/flat/src/main/java/org/horizon/jmx/ResourceDMBean.java
core/branches/flat/src/main/java/org/horizon/jmx/annotations/MBean.java
core/branches/flat/src/main/java/org/horizon/jmx/annotations/ManagedAttribute.java
core/branches/flat/src/main/java/org/horizon/jmx/annotations/ManagedOperation.java
core/branches/flat/src/main/java/org/horizon/lifecycle/Lifecycle.java
core/branches/flat/src/main/java/org/horizon/loader/AbstractCacheLoader.java
core/branches/flat/src/main/java/org/horizon/loader/AbstractDelegatingCacheLoader.java
core/branches/flat/src/main/java/org/horizon/loader/AsyncCacheLoader.java
core/branches/flat/src/main/java/org/horizon/loader/AsyncCacheLoaderConfig.java
core/branches/flat/src/main/java/org/horizon/loader/CacheLoader.java
core/branches/flat/src/main/java/org/horizon/loader/CacheLoaderManager.java
core/branches/flat/src/main/java/org/horizon/loader/ChainingCacheLoader.java
core/branches/flat/src/main/java/org/horizon/loader/ClusteredCacheLoader.java
core/branches/flat/src/main/java/org/horizon/loader/ClusteredCacheLoaderConfig.java
core/branches/flat/src/main/java/org/horizon/loader/FileCacheLoader.java
core/branches/flat/src/main/java/org/horizon/loader/FileCacheLoaderConfig.java
core/branches/flat/src/main/java/org/horizon/loader/Modification.java
core/branches/flat/src/main/java/org/horizon/loader/ReadOnlyDelegatingCacheLoader.java
core/branches/flat/src/main/java/org/horizon/loader/SingletonStoreCacheLoader.java
core/branches/flat/src/main/java/org/horizon/loader/SingletonStoreDefaultConfig.java
core/branches/flat/src/main/java/org/horizon/lock/IsolationLevel.java
core/branches/flat/src/main/java/org/horizon/lock/LockManager.java
core/branches/flat/src/main/java/org/horizon/lock/StripedLock.java
core/branches/flat/src/main/java/org/horizon/lock/StripedLockManager.java
core/branches/flat/src/main/java/org/horizon/lock/TimeoutException.java
core/branches/flat/src/main/java/org/horizon/manager/CacheManager.java
core/branches/flat/src/main/java/org/horizon/manager/CacheNameExistsException.java
core/branches/flat/src/main/java/org/horizon/manager/NamedCacheNotFoundException.java
core/branches/flat/src/main/java/org/horizon/marshall/CacheMarshallerStarobrno.java
core/branches/flat/src/main/java/org/horizon/marshall/CommandAwareRpcDispatcher.java
core/branches/flat/src/main/java/org/horizon/marshall/EntryData.java
core/branches/flat/src/main/java/org/horizon/marshall/EntryDataExceptionMarker.java
core/branches/flat/src/main/java/org/horizon/marshall/EntryDataMarker.java
core/branches/flat/src/main/java/org/horizon/marshall/MarshalledValue.java
core/branches/flat/src/main/java/org/horizon/marshall/MarshalledValueHelper.java
core/branches/flat/src/main/java/org/horizon/marshall/MarshalledValueMap.java
core/branches/flat/src/main/java/org/horizon/marshall/Marshaller.java
core/branches/flat/src/main/java/org/horizon/marshall/NodeData.java
core/branches/flat/src/main/java/org/horizon/marshall/NodeDataExceptionMarker.java
core/branches/flat/src/main/java/org/horizon/marshall/NodeDataMarker.java
core/branches/flat/src/main/java/org/horizon/marshall/UnmarshalledReferences.java
core/branches/flat/src/main/java/org/horizon/marshall/VersionAwareMarshaller.java
core/branches/flat/src/main/java/org/horizon/notifications/EventLog.java
core/branches/flat/src/main/java/org/horizon/notifications/IncorrectCacheListenerException.java
core/branches/flat/src/main/java/org/horizon/notifications/Notifier.java
core/branches/flat/src/main/java/org/horizon/notifications/NotifierImpl.java
core/branches/flat/src/main/java/org/horizon/notifications/annotation/CacheEntryActivated.java
core/branches/flat/src/main/java/org/horizon/notifications/annotation/CacheEntryCreated.java
core/branches/flat/src/main/java/org/horizon/notifications/annotation/CacheEntryEvicted.java
core/branches/flat/src/main/java/org/horizon/notifications/annotation/CacheEntryInvalidated.java
core/branches/flat/src/main/java/org/horizon/notifications/annotation/CacheEntryLoaded.java
core/branches/flat/src/main/java/org/horizon/notifications/annotation/CacheEntryModified.java
core/branches/flat/src/main/java/org/horizon/notifications/annotation/CacheEntryPassivated.java
core/branches/flat/src/main/java/org/horizon/notifications/annotation/CacheEntryRemoved.java
core/branches/flat/src/main/java/org/horizon/notifications/annotation/CacheEntryVisited.java
core/branches/flat/src/main/java/org/horizon/notifications/annotation/CacheListener.java
core/branches/flat/src/main/java/org/horizon/notifications/annotation/CacheStarted.java
core/branches/flat/src/main/java/org/horizon/notifications/annotation/CacheStopped.java
core/branches/flat/src/main/java/org/horizon/notifications/annotation/TransactionCompleted.java
core/branches/flat/src/main/java/org/horizon/notifications/annotation/TransactionRegistered.java
core/branches/flat/src/main/java/org/horizon/notifications/annotation/ViewChanged.java
core/branches/flat/src/main/java/org/horizon/notifications/event/CacheEntryActivatedEvent.java
core/branches/flat/src/main/java/org/horizon/notifications/event/CacheEntryCreatedEvent.java
core/branches/flat/src/main/java/org/horizon/notifications/event/CacheEntryEvent.java
core/branches/flat/src/main/java/org/horizon/notifications/event/CacheEntryEvictedEvent.java
core/branches/flat/src/main/java/org/horizon/notifications/event/CacheEntryInvalidatedEvent.java
core/branches/flat/src/main/java/org/horizon/notifications/event/CacheEntryLoadedEvent.java
core/branches/flat/src/main/java/org/horizon/notifications/event/CacheEntryModifiedEvent.java
core/branches/flat/src/main/java/org/horizon/notifications/event/CacheEntryPassivatedEvent.java
core/branches/flat/src/main/java/org/horizon/notifications/event/CacheEntryRemovedEvent.java
core/branches/flat/src/main/java/org/horizon/notifications/event/CacheEntryVisitedEvent.java
core/branches/flat/src/main/java/org/horizon/notifications/event/CacheStartedEvent.java
core/branches/flat/src/main/java/org/horizon/notifications/event/CacheStoppedEvent.java
core/branches/flat/src/main/java/org/horizon/notifications/event/Event.java
core/branches/flat/src/main/java/org/horizon/notifications/event/EventImpl.java
core/branches/flat/src/main/java/org/horizon/notifications/event/TransactionCompletedEvent.java
core/branches/flat/src/main/java/org/horizon/notifications/event/TransactionRegisteredEvent.java
core/branches/flat/src/main/java/org/horizon/notifications/event/TransactionalEvent.java
core/branches/flat/src/main/java/org/horizon/notifications/event/ViewChangedEvent.java
core/branches/flat/src/main/java/org/horizon/remoting/ChannelMessageListener.java
core/branches/flat/src/main/java/org/horizon/remoting/RPCManager.java
core/branches/flat/src/main/java/org/horizon/remoting/RPCManagerImpl.java
core/branches/flat/src/main/java/org/horizon/remoting/ReplicationException.java
core/branches/flat/src/main/java/org/horizon/remoting/SuspectException.java
core/branches/flat/src/main/java/org/horizon/remoting/transport/Address.java
core/branches/flat/src/main/java/org/horizon/remoting/transport/Transport.java
core/branches/flat/src/main/java/org/horizon/statetransfer/DefaultStateTransferManager.java
core/branches/flat/src/main/java/org/horizon/statetransfer/StateTransferManager.java
core/branches/flat/src/main/java/org/horizon/transaction/BatchModeTransactionManager.java
core/branches/flat/src/main/java/org/horizon/transaction/DummyBaseTransactionManager.java
core/branches/flat/src/main/java/org/horizon/transaction/DummyTransaction.java
core/branches/flat/src/main/java/org/horizon/transaction/DummyTransactionManager.java
core/branches/flat/src/main/java/org/horizon/transaction/DummyTransactionManagerLookup.java
core/branches/flat/src/main/java/org/horizon/transaction/DummyUserTransaction.java
core/branches/flat/src/main/java/org/horizon/transaction/GenericTransactionManagerLookup.java
core/branches/flat/src/main/java/org/horizon/transaction/GlobalTransaction.java
core/branches/flat/src/main/java/org/horizon/transaction/JBossStandaloneJTAManagerLookup.java
core/branches/flat/src/main/java/org/horizon/transaction/JBossTransactionManagerLookup.java
core/branches/flat/src/main/java/org/horizon/transaction/TransactionManagerLookup.java
core/branches/flat/src/main/java/org/horizon/transaction/TransactionTable.java
core/branches/flat/src/main/java/org/horizon/tree/Fqn.java
core/branches/flat/src/main/java/org/horizon/tree/FqnComparator.java
core/branches/flat/src/main/java/org/horizon/tree/Node.java
core/branches/flat/src/main/java/org/horizon/tree/NodeImpl.java
core/branches/flat/src/main/java/org/horizon/tree/NodeKey.java
core/branches/flat/src/main/java/org/horizon/tree/NodeNotExistsException.java
core/branches/flat/src/main/java/org/horizon/tree/NodeNotValidException.java
core/branches/flat/src/main/java/org/horizon/tree/TreeCache.java
core/branches/flat/src/main/java/org/horizon/tree/TreeCacheImpl.java
core/branches/flat/src/main/java/org/horizon/tree/TreeStructureSupport.java
core/branches/flat/src/main/java/org/horizon/util/BeanUtils.java
core/branches/flat/src/main/java/org/horizon/util/FastCopyHashMap.java
core/branches/flat/src/main/java/org/horizon/util/FileLookup.java
core/branches/flat/src/main/java/org/horizon/util/ImmutableListCopy.java
core/branches/flat/src/main/java/org/horizon/util/Immutables.java
core/branches/flat/src/main/java/org/horizon/util/ObjectDuplicator.java
core/branches/flat/src/main/java/org/horizon/util/ReflectionUtil.java
core/branches/flat/src/main/java/org/horizon/util/SimpleImmutableEntry.java
core/branches/flat/src/main/java/org/horizon/util/TestingUtil.java
core/branches/flat/src/main/java/org/horizon/util/TypedProperties.java
core/branches/flat/src/main/java/org/horizon/util/UnitTestTestNGListener.java
core/branches/flat/src/main/java/org/horizon/util/Util.java
core/branches/flat/src/main/java/org/horizon/util/concurrent/BoundedExecutors.java
core/branches/flat/src/main/java/org/horizon/util/concurrent/ConcurrentHashSet.java
core/branches/flat/src/main/java/org/horizon/util/concurrent/ReclosableLatch.java
core/branches/flat/src/main/java/org/horizon/util/concurrent/SelfInitializingConcurrentHashMap.java
core/branches/flat/src/main/java/org/horizon/util/concurrent/SynchronizedRestarter.java
core/branches/flat/src/main/java/org/horizon/util/concurrent/WithinThreadExecutor.java
core/branches/flat/src/main/java/org/horizon/util/concurrent/locks/LockContainer.java
core/branches/flat/src/main/java/org/horizon/util/concurrent/locks/OwnableReentrantLock.java
core/branches/flat/src/main/java/org/horizon/util/concurrent/locks/OwnableReentrantLockContainer.java
core/branches/flat/src/main/java/org/horizon/util/concurrent/locks/ReentrantLockContainer.java
core/branches/flat/src/main/java/org/horizon/util/internals/ReplicationListener.java
core/branches/flat/src/main/java/org/horizon/util/internals/ViewChangeListener.java
core/branches/flat/src/test/java/org/horizon/BasicTest.java
core/branches/flat/src/test/java/org/horizon/UnitTestCacheFactory.java
core/branches/flat/src/test/java/org/horizon/UnitTestCacheManager.java
core/branches/flat/src/test/java/org/horizon/api/CacheAPITest.java
core/branches/flat/src/test/java/org/horizon/api/CacheSPITest.java
core/branches/flat/src/test/java/org/horizon/api/batch/AbstractBatchTest.java
core/branches/flat/src/test/java/org/horizon/api/batch/BatchWithTM.java
core/branches/flat/src/test/java/org/horizon/api/batch/BatchWithoutTM.java
core/branches/flat/src/test/java/org/horizon/api/mvcc/LockAssert.java
core/branches/flat/src/test/java/org/horizon/api/mvcc/LockTestBase.java
core/branches/flat/src/test/java/org/horizon/api/mvcc/PutForExternalReadTest.java
core/branches/flat/src/test/java/org/horizon/api/mvcc/read_committed/CacheAPIMVCCTest.java
core/branches/flat/src/test/java/org/horizon/api/mvcc/read_committed/ReadCommittedLockTest.java
core/branches/flat/src/test/java/org/horizon/api/mvcc/repeatable_read/CacheAPIMVCCTest.java
core/branches/flat/src/test/java/org/horizon/api/mvcc/repeatable_read/RepeatableReadLockTest.java
core/branches/flat/src/test/java/org/horizon/api/mvcc/repeatable_read/WriteSkewTest.java
core/branches/flat/src/test/java/org/horizon/api/tree/NodeAPITest.java
core/branches/flat/src/test/java/org/horizon/api/tree/NodeLockSupport.java
core/branches/flat/src/test/java/org/horizon/api/tree/NodeMoveAPITest.java
core/branches/flat/src/test/java/org/horizon/api/tree/NodeReplicatedMoveTest.java
core/branches/flat/src/test/java/org/horizon/api/tree/SyncReplTest.java
core/branches/flat/src/test/java/org/horizon/api/tree/SyncReplTxTest.java
core/branches/flat/src/test/java/org/horizon/api/tree/TreeCacheAPITest.java
core/branches/flat/src/test/java/org/horizon/api/tree/TreeStructureHashCodeTest.java
core/branches/flat/src/test/java/org/horizon/atomic/APITest.java
core/branches/flat/src/test/java/org/horizon/atomic/AtomicHashMapTest.java
core/branches/flat/src/test/java/org/horizon/factories/scopes/ScopeDetectorTest.java
core/branches/flat/src/test/java/org/horizon/lock/LockContainerHashingTest.java
core/branches/flat/src/test/java/org/horizon/manager/CacheManagerComponentRegistryTest.java
core/branches/flat/src/test/java/org/horizon/manager/CacheManagerTest.java
core/branches/flat/src/test/java/org/horizon/manager/CacheManagerXmlConfigurationTest.java
core/branches/flat/src/test/java/org/horizon/profiling/AbstractProfileTest.java
core/branches/flat/src/test/java/org/horizon/profiling/MemConsumptionTest.java
core/branches/flat/src/test/java/org/horizon/profiling/ProfileTest.java
core/branches/flat/src/test/java/org/horizon/profiling/TreeProfileTest.java
core/branches/flat/src/test/java/org/horizon/profiling/testinternals/Generator.java
core/branches/flat/src/test/java/org/horizon/profiling/testinternals/TaskRunner.java
core/branches/flat/src/test/java/org/horizon/replication/AsyncReplTest.java
core/branches/flat/src/test/java/org/horizon/replication/ExceptionTest.java
core/branches/flat/src/test/java/org/horizon/replication/ReplicationExceptionTest.java
core/branches/flat/src/test/java/org/horizon/replication/SyncCacheListenerTest.java
core/branches/flat/src/test/java/org/horizon/replication/SyncReplTest.java
core/branches/flat/src/test/java/org/horizon/tx/LocalModeTxTest.java
Log:
code style update
Modified: core/branches/flat/src/main/java/org/horizon/Cache.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/Cache.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/Cache.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -35,25 +35,22 @@
* @author Mircea.Markus at jboss.com
* @since 1.0
*/
-public interface Cache<K, V> extends ConcurrentMap<K, V>, Lifecycle
-{
+public interface Cache<K, V> extends ConcurrentMap<K, V>, Lifecycle {
/**
- * Under special operating behavior, associates the value with the specified key.
- * <ul>
- * <li> Only goes through if the key specified does not exist; no-op otherwise (similar to {@link java.util.concurrent.ConcurrentMap#putIfAbsent(Object, Object)})</i>
- * <li> Force asynchronous mode for replication to prevent any blocking.</li>
- * <li> invalidation does not take place. </li>
- * <li> 0ms lock timeout to prevent any blocking here either. If the lock is not acquired, this method is a no-op, and swallows the timeout exception.</li>
- * <li> Ongoing transactions are suspended before this call, so failures here will not affect any ongoing transactions.</li>
- * <li> Errors and exceptions are 'silent' - logged at a much lower level than normal, and this method does not throw exceptions</li>
- * </ul>
- * This method is for caching data that has an external representation in storage, where, concurrent modification and
- * transactions are not a consideration, and failure to put the data in the cache should be treated as a 'suboptimal outcome'
- * rather than a 'failing outcome'.
+ * Under special operating behavior, associates the value with the specified key. <ul> <li> Only goes through if the
+ * key specified does not exist; no-op otherwise (similar to {@link java.util.concurrent.ConcurrentMap#putIfAbsent(Object,
+ * Object)})</i> <li> Force asynchronous mode for replication to prevent any blocking.</li> <li> invalidation does
+ * not take place. </li> <li> 0ms lock timeout to prevent any blocking here either. If the lock is not acquired, this
+ * method is a no-op, and swallows the timeout exception.</li> <li> Ongoing transactions are suspended before this
+ * call, so failures here will not affect any ongoing transactions.</li> <li> Errors and exceptions are 'silent' -
+ * logged at a much lower level than normal, and this method does not throw exceptions</li> </ul> This method is for
+ * caching data that has an external representation in storage, where, concurrent modification and transactions are
+ * not a consideration, and failure to put the data in the cache should be treated as a 'suboptimal outcome' rather
+ * than a 'failing outcome'.
* <p/>
- * An example of when this method is useful is when data is read from, for example, a legacy datastore, and is cached before
- * returning the data to the caller. Subsequent calls would prefer to get the data from the cache and if the data doesn't exist
- * in the cache, fetch again from the legacy datastore.
+ * An example of when this method is useful is when data is read from, for example, a legacy datastore, and is cached
+ * before returning the data to the caller. Subsequent calls would prefer to get the data from the cache and if the
+ * data doesn't exist in the cache, fetch again from the legacy datastore.
* <p/>
* See <a href="http://jira.jboss.com/jira/browse/JBCACHE-848">JBCACHE-848</a> for details around this feature.
* <p/>
Modified: core/branches/flat/src/main/java/org/horizon/CacheDelegate.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/CacheDelegate.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/CacheDelegate.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -68,8 +68,7 @@
* @since 1.0
*/
@NonVolatile
-public class CacheDelegate<K, V> implements CacheSPI<K, V>, AtomicMapCache<K, V>
-{
+public class CacheDelegate<K, V> implements CacheSPI<K, V>, AtomicMapCache<K, V> {
protected InvocationContextContainer invocationContextContainer;
protected CommandsFactory commandsFactory;
protected InterceptorChain invoker;
@@ -86,8 +85,7 @@
private LockManager lockManager;
private static final Log log = LogFactory.getLog(CacheDelegate.class);
- public CacheDelegate(String name)
- {
+ public CacheDelegate(String name) {
this.name = name;
}
@@ -103,8 +101,7 @@
BatchContainer batchContainer,
RPCManager rpcManager, DataContainer dataContainer,
Marshaller marshaller,
- LockManager lockManager)
- {
+ LockManager lockManager) {
this.invocationContextContainer = invocationContextContainer;
this.commandsFactory = commandsFactory;
this.invoker = interceptorChain;
@@ -120,110 +117,91 @@
this.lockManager = lockManager;
}
- public V putIfAbsent(K key, V value)
- {
+ public V putIfAbsent(K key, V value) {
PutKeyValueCommand command = commandsFactory.buildPutKeyValueCommand(key, value);
command.setPutIfAbsent(true);
return (V) invoker.invoke(buildCtx(), command);
}
- public boolean remove(Object key, Object value)
- {
+ public boolean remove(Object key, Object value) {
RemoveCommand command = commandsFactory.buildRemoveCommand(key, value);
return (Boolean) invoker.invoke(buildCtx(), command);
}
- public boolean replace(K key, V oldValue, V newValue)
- {
+ public boolean replace(K key, V oldValue, V newValue) {
ReplaceCommand command = commandsFactory.buildReplaceCommand(key, oldValue, newValue);
return (Boolean) invoker.invoke(buildCtx(), command);
}
- public V replace(K key, V value)
- {
+ public V replace(K key, V value) {
ReplaceCommand command = commandsFactory.buildReplaceCommand(key, null, value);
return (V) invoker.invoke(buildCtx(), command);
}
- public int size()
- {
+ public int size() {
SizeCommand command = commandsFactory.buildSizeCommand();
return (Integer) invoker.invoke(buildCtx(), command);
}
- public boolean isEmpty()
- {
+ public boolean isEmpty() {
SizeCommand command = commandsFactory.buildSizeCommand();
int size = (Integer) invoker.invoke(buildCtx(), command);
return size == 0;
}
- public boolean containsKey(Object key)
- {
+ public boolean containsKey(Object key) {
GetKeyValueCommand command = commandsFactory.buildGetKeyValueCommand(key);
Object response = invoker.invoke(buildCtx(), command);
return response != null;
}
- public boolean containsValue(Object value)
- {
+ public boolean containsValue(Object value) {
throw new UnsupportedOperationException("Go away");
}
- public V get(Object key)
- {
+ public V get(Object key) {
GetKeyValueCommand command = commandsFactory.buildGetKeyValueCommand(key);
return (V) invoker.invoke(buildCtx(), command);
}
- public V put(K key, V value)
- {
+ public V put(K key, V value) {
PutKeyValueCommand command = commandsFactory.buildPutKeyValueCommand(key, value);
return (V) invoker.invoke(buildCtx(), command);
}
- public V remove(Object key)
- {
+ public V remove(Object key) {
RemoveCommand command = commandsFactory.buildRemoveCommand(key, null);
V oldval = (V) invoker.invoke(buildCtx(), command);
return oldval;
}
- public void putAll(Map<? extends K, ? extends V> t)
- {
+ public void putAll(Map<? extends K, ? extends V> t) {
PutMapCommand command = commandsFactory.buildPutMapCommand(t);
invoker.invoke(buildCtx(), command);
}
- public void clear()
- {
+ public void clear() {
ClearCommand command = commandsFactory.buildClearCommand();
invoker.invoke(buildCtx(), command);
}
- public Set keySet()
- {
+ public Set keySet() {
throw new UnsupportedOperationException("Go away");
}
- public Collection values()
- {
+ public Collection values() {
throw new UnsupportedOperationException("Go away");
}
- public Set entrySet()
- {
+ public Set entrySet() {
throw new UnsupportedOperationException("Go away");
}
- public void putForExternalRead(K key, V value)
- {
+ public void putForExternalRead(K key, V value) {
InvocationContext ctx = invocationContextContainer.get();
Transaction ongoingTransaction = null;
- try
- {
- if (transactionManager != null && (ongoingTransaction = transactionManager.getTransaction()) != null)
- {
+ try {
+ if (transactionManager != null && (ongoingTransaction = transactionManager.getTransaction()) != null) {
transactionManager.suspend();
}
@@ -233,238 +211,192 @@
ctx.getOptionOverrides().setLockAcquisitionTimeout(0);
putIfAbsent(key, value);
}
- catch (Exception e)
- {
+ catch (Exception e) {
if (log.isDebugEnabled()) log.debug("Caught exception while doing putForExternalRead()", e);
}
- finally
- {
- try
- {
+ finally {
+ try {
if (ongoingTransaction != null) transactionManager.resume(ongoingTransaction);
}
- catch (Exception e)
- {
+ catch (Exception e) {
log.debug("Had problems trying to resume a transaction after putForExternalread()", e);
}
}
}
- public void evict(K key)
- {
+ public void evict(K key) {
EvictCommand command = commandsFactory.buildEvictCommand(key);
invoker.invoke(buildCtx(), command);
}
- public Configuration getConfiguration()
- {
+ public Configuration getConfiguration() {
return config;
}
- public void addCacheListener(Object listener)
- {
+ public void addCacheListener(Object listener) {
notifier.addCacheListener(listener);
}
- public void removeCacheListener(Object listener)
- {
+ public void removeCacheListener(Object listener) {
notifier.removeCacheListener(listener);
}
- public Set getCacheListeners()
- {
+ public Set getCacheListeners() {
return notifier.getCacheListeners();
}
- public InvocationContext getInvocationContext()
- {
+ public InvocationContext getInvocationContext() {
return invocationContextContainer.get();
}
- public void setInvocationContext(InvocationContext ctx)
- {
+ public void setInvocationContext(InvocationContext ctx) {
if (ctx == null) invocationContextContainer.remove();
else invocationContextContainer.set(ctx);
}
- public void start()
- {
+ public void start() {
componentRegistry.start();
}
- public void stop()
- {
+ public void stop() {
componentRegistry.stop();
- if (config.isUsingEviction())
- {
+ if (config.isUsingEviction()) {
evictionManager.cacheStopped(getName());
}
}
- private InvocationContext buildCtx()
- {
+ private InvocationContext buildCtx() {
return invocationContextContainer.get();
}
- public TransactionManager getTransactionManager()
- {
+ public TransactionManager getTransactionManager() {
return transactionManager;
}
- public List<CommandInterceptor> getInterceptorChain()
- {
+ public List<CommandInterceptor> getInterceptorChain() {
throw new IllegalStateException();//todo Implement me properly
}
- public Marshaller getMarshaller()
- {
+ public Marshaller getMarshaller() {
return marshaller;
}
- public void addInterceptor(CommandInterceptor i, int position)
- {
+ public void addInterceptor(CommandInterceptor i, int position) {
throw new IllegalStateException();//todo Implement me properly
}
- public void addInterceptor(CommandInterceptor i, Class<? extends CommandInterceptor> afterInterceptor)
- {
+ public void addInterceptor(CommandInterceptor i, Class<? extends CommandInterceptor> afterInterceptor) {
throw new IllegalStateException();//todo Implement me properly
}
- public void removeInterceptor(int position)
- {
+ public void removeInterceptor(int position) {
throw new IllegalStateException();//todo Implement me properly
}
- public void removeInterceptor(Class<? extends CommandInterceptor> interceptorType)
- {
+ public void removeInterceptor(Class<? extends CommandInterceptor> interceptorType) {
throw new IllegalStateException();//todo Implement me properly
}
- public CacheLoaderManager getCacheLoaderManager()
- {
+ public CacheLoaderManager getCacheLoaderManager() {
throw new IllegalStateException();//todo Implement me properly
}
- public TransactionTable getTransactionTable()
- {
+ public TransactionTable getTransactionTable() {
throw new IllegalStateException();//todo Implement me properly
}
- public EvictionManager getEvictionManager()
- {
+ public EvictionManager getEvictionManager() {
return evictionManager;
}
- public RPCManager getRPCManager()
- {
+ public RPCManager getRPCManager() {
return rpcManager;
}
- public StateTransferManager getStateTransferManager()
- {
+ public StateTransferManager getStateTransferManager() {
throw new IllegalStateException();//todo Implement me properly
}
- public Notifier getNotifier()
- {
+ public Notifier getNotifier() {
return notifier;
}
- public String getClusterName()
- {
+ public String getClusterName() {
return config.getClusterName();
}
- public GlobalTransaction getCurrentTransaction(Transaction tx, boolean createIfNotExists)
- {
+ public GlobalTransaction getCurrentTransaction(Transaction tx, boolean createIfNotExists) {
throw new IllegalStateException();//todo Implement me properly
}
- public GlobalTransaction getCurrentTransaction()
- {
+ public GlobalTransaction getCurrentTransaction() {
throw new IllegalStateException();//todo Implement me properly
}
- public ComponentRegistry getComponentRegistry()
- {
+ public ComponentRegistry getComponentRegistry() {
return componentRegistry;
}
- public CacheStatus getCacheStatus()
- {
+ public CacheStatus getCacheStatus() {
return componentRegistry.getState();
}
- public boolean startBatch()
- {
+ public boolean startBatch() {
if (!config.isInvocationBatchingEnabled())
throw new ConfigurationException("Invocation batching not enabled in current configuration! Please use the <invocationBatching /> element.");
return batchContainer.startBatch();
}
- public void endBatch(boolean successful)
- {
+ public void endBatch(boolean successful) {
if (!config.isInvocationBatchingEnabled())
throw new ConfigurationException("Invocation batching not enabled in current configuration! Please use the <invocationBatching /> element.");
batchContainer.endBatch(successful);
}
- public List<Address> getMembers()
- {
+ public List<Address> getMembers() {
return rpcManager.getMembers();
}
- public Object getDirect(Object key)
- {
+ public Object getDirect(Object key) {
throw new UnsupportedOperationException("Not implemented");//todo please implement!
}
- public LockManager getLockManager()
- {
+ public LockManager getLockManager() {
return lockManager;
}
- public String getName()
- {
+ public String getName() {
return name;
}
- public String getVersion()
- {
+ public String getVersion() {
return Version.decodeVersion(Version.getVersionShort());
}
- public Address getLocalAddress()
- {
+ public Address getLocalAddress() {
return rpcManager.getLocalAddress();
}
- public void setName(String name)
- {
+ public void setName(String name) {
this.name = name;
}
@Override
- public String toString()
- {
+ public String toString() {
return dataContainer == null ? super.toString() : dataContainer.toString();
}
- public AtomicMap getAtomicMap(K key) throws ClassCastException
- {
+ public AtomicMap getAtomicMap(K key) throws ClassCastException {
Object value = get(key);
if (value == null) value = AtomicHashMap.newInstance(this, key);
return ((AtomicHashMap) value).getProxy(this, key);
}
- public <AMK, AMV> AtomicMap<AMK, AMV> getAtomicMap(K key, Class<AMK> atomicMapKeyType, Class<AMV> atomicMapValueType) throws ClassCastException
- {
+ public <AMK, AMV> AtomicMap<AMK, AMV> getAtomicMap(K key, Class<AMK> atomicMapKeyType, Class<AMV> atomicMapValueType) throws ClassCastException {
return getAtomicMap(key);
}
- public BatchContainer getBatchContainer()
- {
+ public BatchContainer getBatchContainer() {
return batchContainer;
}
}
Modified: core/branches/flat/src/main/java/org/horizon/CacheException.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/CacheException.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/CacheException.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -24,35 +24,30 @@
/**
* Thrown when operations on {@link Cache} fail unexpectedly.
* <p/>
- * Specific subclasses such as {@link org.horizon.lock.TimeoutException} and {@link org.horizon.config.ConfigurationException}
- * have more specific uses.
+ * Specific subclasses such as {@link org.horizon.lock.TimeoutException} and {@link
+ * org.horizon.config.ConfigurationException} have more specific uses.
*
* @author <a href="mailto:bela at jboss.org">Bela Ban</a>
* @author <a href="mailto:manik at jboss.org">Manik Surtani</a>
* @since 1.0
*/
-public class CacheException extends RuntimeException
-{
+public class CacheException extends RuntimeException {
private static final long serialVersionUID = -4386393072593859164L;
- public CacheException()
- {
+ public CacheException() {
super();
}
- public CacheException(Throwable cause)
- {
+ public CacheException(Throwable cause) {
super(cause);
}
- public CacheException(String msg)
- {
+ public CacheException(String msg) {
super(msg);
}
- public CacheException(String msg, Throwable cause)
- {
+ public CacheException(String msg, Throwable cause) {
super(msg, cause);
}
}
\ No newline at end of file
Modified: core/branches/flat/src/main/java/org/horizon/CacheSPI.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/CacheSPI.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/CacheSPI.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -40,11 +40,12 @@
import java.util.List;
/**
- * A more detailed interface to {@link Cache}, which is used when writing plugins for or extending JBoss Cache. A reference
- * to this interface should only be obtained when it is passed in to your code, for example when you write an
+ * A more detailed interface to {@link Cache}, which is used when writing plugins for or extending JBoss Cache. A
+ * reference to this interface should only be obtained when it is passed in to your code, for example when you write an
* {@link org.horizon.interceptors.base.CommandInterceptor} or {@link CacheLoader}.
* <p/>
- * <B><I>You should NEVER attempt to directly cast a {@link Cache} instance to this interface. In future, the implementation may not allow it.</I></B>
+ * <B><I>You should NEVER attempt to directly cast a {@link Cache} instance to this interface. In future, the
+ * implementation may not allow it.</I></B>
* <p/>
*
* @author <a href="mailto:manik at jboss.org">Manik Surtani (manik at jboss.org)</a>
@@ -53,13 +54,12 @@
* @since 1.0
*/
@ThreadSafe
-public interface CacheSPI<K, V> extends Cache<K, V>
-{
+public interface CacheSPI<K, V> extends Cache<K, V> {
/**
* Retrieves a reference to a running {@link javax.transaction.TransactionManager}, if one is configured.
* <p/>
- * From 2.1.0, Interceptor authors should obtain this by injection rather than this method. See the
- * {@link org.horizon.factories.annotations.Inject} annotation.
+ * From 2.1.0, Interceptor authors should obtain this by injection rather than this method. See the {@link
+ * org.horizon.factories.annotations.Inject} annotation.
*
* @return a TransactionManager
*/
@@ -68,25 +68,24 @@
/**
* Retrieves the current Interceptor chain.
* <p/>
- * From 2.1.0, Interceptor authors should obtain this by injection rather than this method. See the
- * {@link org.horizon.factories.annotations.Inject} annotation.
+ * From 2.1.0, Interceptor authors should obtain this by injection rather than this method. See the {@link
+ * org.horizon.factories.annotations.Inject} annotation.
*
- * @return an immutable {@link List} of {@link org.horizon.interceptors.base.CommandInterceptor}s configured for
- * this cache
+ * @return an immutable {@link List} of {@link org.horizon.interceptors.base.CommandInterceptor}s configured for this
+ * cache
*/
List<CommandInterceptor> getInterceptorChain();
/**
- * Retrieves an instance of a {@link Marshaller}, which is capable of
- * converting Java objects to bytestreams and back in an efficient manner, which is
- * also interoperable with bytestreams produced/consumed by other versions of JBoss
+ * Retrieves an instance of a {@link Marshaller}, which is capable of converting Java objects to bytestreams and back
+ * in an efficient manner, which is also interoperable with bytestreams produced/consumed by other versions of JBoss
* Cache.
* <p/>
- * The use of this marshaller is the <b>recommended</b> way of creating efficient,
- * compatible, byte streams from objects.
+ * The use of this marshaller is the <b>recommended</b> way of creating efficient, compatible, byte streams from
+ * objects.
* <p/>
- * From 2.1.0, Interceptor authors should obtain this by injection rather than this method. See the
- * {@link org.horizon.factories.annotations.Inject} annotation.
+ * From 2.1.0, Interceptor authors should obtain this by injection rather than this method. See the {@link
+ * org.horizon.factories.annotations.Inject} annotation.
*
* @return an instance of {@link Marshaller}
*/
@@ -95,18 +94,19 @@
/**
* Retrieves the current CacheCacheLoaderManager instance associated with the current Cache instance.
* <p/>
- * From 2.1.0, Interceptor authors should obtain this by injection rather than this method. See the
- * {@link org.horizon.factories.annotations.Inject} annotation.
+ * From 2.1.0, Interceptor authors should obtain this by injection rather than this method. See the {@link
+ * org.horizon.factories.annotations.Inject} annotation.
*
- * @return Retrieves a reference to the currently configured {@link CacheLoaderManager} if one or more cache loaders are configured, null otherwise.
+ * @return Retrieves a reference to the currently configured {@link CacheLoaderManager} if one or more cache loaders
+ * are configured, null otherwise.
*/
CacheLoaderManager getCacheLoaderManager();
/**
* Retrieves the current TransactionTable instance associated with the current Cache instance.
* <p/>
- * From 2.1.0, Interceptor authors should obtain this by injection rather than this method. See the
- * {@link org.horizon.factories.annotations.Inject} annotation.
+ * From 2.1.0, Interceptor authors should obtain this by injection rather than this method. See the {@link
+ * org.horizon.factories.annotations.Inject} annotation.
*
* @return the current {@link TransactionTable}
*/
@@ -118,8 +118,8 @@
/**
* Gets a handle of the RPC manager.
* <p/>
- * From 2.1.0, Interceptor authors should obtain this by injection rather than this method. See the
- * {@link org.horizon.factories.annotations.Inject} annotation.
+ * From 2.1.0, Interceptor authors should obtain this by injection rather than this method. See the {@link
+ * org.horizon.factories.annotations.Inject} annotation.
*
* @return the {@link RPCManager} configured.
*/
@@ -128,8 +128,8 @@
/**
* Retrieves the current StateTransferManager instance associated with the current Cache instance.
* <p/>
- * From 2.1.0, Interceptor authors should obtain this by injection rather than this method. See the
- * {@link org.horizon.factories.annotations.Inject} annotation.
+ * From 2.1.0, Interceptor authors should obtain this by injection rather than this method. See the {@link
+ * org.horizon.factories.annotations.Inject} annotation.
*
* @return the current {@link org.horizon.statetransfer.StateTransferManager}
*/
@@ -138,11 +138,11 @@
/**
* Retrieves the current Notifier instance associated with the current Cache instance.
* <p/>
- * From 2.1.0, Interceptor authors should obtain this by injection rather than this method. See the
- * {@link org.horizon.factories.annotations.Inject} annotation.
+ * From 2.1.0, Interceptor authors should obtain this by injection rather than this method. See the {@link
+ * org.horizon.factories.annotations.Inject} annotation.
*
- * @return the notifier attached with this instance of the cache. See {@link org.horizon.notifications.Notifier}, a class
- * that is responsible for emitting notifications to registered CacheListeners.
+ * @return the notifier attached with this instance of the cache. See {@link org.horizon.notifications.Notifier}, a
+ * class that is responsible for emitting notifications to registered CacheListeners.
*/
Notifier getNotifier();
@@ -152,8 +152,8 @@
String getClusterName();
/**
- * Returns the global transaction for this local transaction.
- * Optionally creates a new global transaction if it does not exist.
+ * Returns the global transaction for this local transaction. Optionally creates a new global transaction if it does
+ * not exist.
*
* @param tx the current transaction
* @param createIfNotExists if true creates a new transaction if none exists
@@ -162,11 +162,9 @@
GlobalTransaction getCurrentTransaction(Transaction tx, boolean createIfNotExists);
/**
- * Returns the transaction associated with the current thread.
- * If a local transaction exists, but doesn't yet have a mapping to a
- * GlobalTransaction, a new GlobalTransaction will be created and mapped to
- * the local transaction. Note that if a local transaction exists, but is
- * not ACTIVE or PREPARING, null is returned.
+ * Returns the transaction associated with the current thread. If a local transaction exists, but doesn't yet have a
+ * mapping to a GlobalTransaction, a new GlobalTransaction will be created and mapped to the local transaction. Note
+ * that if a local transaction exists, but is not ACTIVE or PREPARING, null is returned.
*
* @return A GlobalTransaction, or null if no (local) transaction was associated with the current thread
*/
Modified: core/branches/flat/src/main/java/org/horizon/CacheStatus.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/CacheStatus.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/CacheStatus.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -25,16 +25,13 @@
import org.apache.commons.logging.LogFactory;
/**
- * Various states that an object that has a four stage lifecycle
- * (i.e. <code>create()</code>, <code>start()</code>, <code>stop()</code>
- * and <code>destroy()</code>) might be in.
+ * Various states that an object that has a four stage lifecycle (i.e. <code>create()</code>, <code>start()</code>,
+ * <code>stop()</code> and <code>destroy()</code>) might be in.
*
* @author <a href="brian.stansberry at jboss.com">Brian Stansberry</a>
- *
* @since 1.0
*/
-public enum CacheStatus
-{
+public enum CacheStatus {
/**
* Object has been instantiated, but create() has not been called.
*/
@@ -44,8 +41,7 @@
*/
CREATING,
/**
- * The <code>create()</code> method has been completed but
- * <code>start()</code> has not been called.
+ * The <code>create()</code> method has been completed but <code>start()</code> has not been called.
*/
CREATED,
/**
@@ -61,8 +57,8 @@
*/
STOPPING,
/**
- * The <code>stop()</code> method has completed but <code>destroy()</code>
- * has not yet been called. Conceptually equivalent to {@link #CREATED}.
+ * The <code>stop()</code> method has completed but <code>destroy()</code> has not yet been called. Conceptually
+ * equivalent to {@link #CREATED}.
*/
STOPPED,
/**
@@ -70,23 +66,19 @@
*/
DESTROYING,
/**
- * The <code>destroy()</code> method has completed.
- * Conceptually equivalent to {@link #INSTANTIATED}.
+ * The <code>destroy()</code> method has completed. Conceptually equivalent to {@link #INSTANTIATED}.
*/
DESTROYED,
/**
- * A failure occurred during the execution of <code>create()</code>,
- * <code>start()</code>, <code>stop()</code> or <code>destroy()</code>.
- * The next logical transition is to call <code>destroy()</code>.
+ * A failure occurred during the execution of <code>create()</code>, <code>start()</code>, <code>stop()</code> or
+ * <code>destroy()</code>. The next logical transition is to call <code>destroy()</code>.
*/
FAILED;
private static final Log log = LogFactory.getLog(CacheStatus.class);
- public boolean createAllowed()
- {
- switch (this)
- {
+ public boolean createAllowed() {
+ switch (this) {
case CREATING:
case CREATED:
case STARTING:
@@ -101,10 +93,8 @@
}
}
- public boolean needToDestroyFailedCache()
- {
- if (this == CacheStatus.FAILED)
- {
+ public boolean needToDestroyFailedCache() {
+ if (this == CacheStatus.FAILED) {
log.debug("need to call destroy() since current state is " +
this);
return true;
@@ -113,10 +103,8 @@
return false;
}
- public boolean startAllowed()
- {
- switch (this)
- {
+ public boolean startAllowed() {
+ switch (this) {
case INSTANTIATED:
case DESTROYED:
case STARTING:
@@ -130,10 +118,8 @@
}
}
- public boolean needCreateBeforeStart()
- {
- switch (this)
- {
+ public boolean needCreateBeforeStart() {
+ switch (this) {
case INSTANTIATED:
case DESTROYED:
log.debug("start() called while current state is " +
@@ -144,10 +130,8 @@
}
}
- public boolean stopAllowed()
- {
- switch (this)
- {
+ public boolean stopAllowed() {
+ switch (this) {
case INSTANTIATED:
case CREATED:
case STOPPED:
@@ -168,10 +152,8 @@
}
- public boolean destroyAllowed()
- {
- switch (this)
- {
+ public boolean destroyAllowed() {
+ switch (this) {
case INSTANTIATED:
case DESTROYED:
log.debug("Ignoring call to destroy() as current state is " + this);
@@ -193,10 +175,8 @@
}
}
- public boolean needStopBeforeDestroy()
- {
- if (this == CacheStatus.STARTED)
- {
+ public boolean needStopBeforeDestroy() {
+ if (this == CacheStatus.STARTED) {
log.warn("destroy() called while current state is " +
this + " -- call stop() first");
return true;
@@ -205,8 +185,7 @@
return false;
}
- public boolean allowInvocations()
- {
+ public boolean allowInvocations() {
return (this == CacheStatus.STARTED);
}
}
Modified: core/branches/flat/src/main/java/org/horizon/EvictionManager.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/EvictionManager.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/EvictionManager.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -13,13 +13,11 @@
@ThreadSafe
@NonVolatile
@Scope(Scopes.NAMED_CACHE)
-public interface EvictionManager
-{
+public interface EvictionManager {
/**
- * Whenever a new cache is created this method should be called.
- * If this cache does not have eviction enabled then this is a no-op.
- * If the cache has eviction enabled then it is reistered for receivinge eviction information.
- * If this is the first cache that requires eviction, the eviction theread will be started.
+ * Whenever a new cache is created this method should be called. If this cache does not have eviction enabled then
+ * this is a no-op. If the cache has eviction enabled then it is reistered for receivinge eviction information. If
+ * this is the first cache that requires eviction, the eviction theread will be started.
*
* @param cacheName
* @param cacheManager newly create cache.
@@ -28,9 +26,8 @@
/**
- * Whenever a cache will be stoped this method should be called.
- * If the given cache doesn't have eviction enabled this is an no-op.
- * If this is the only cache that has eviction enabled, then the eviction thread will be stopped.
+ * Whenever a cache will be stoped this method should be called. If the given cache doesn't have eviction enabled
+ * this is an no-op. If this is the only cache that has eviction enabled, then the eviction thread will be stopped.
* After calling this method the given cache will be unregistered from eviction events.
*
* @param cacheName
Modified: core/branches/flat/src/main/java/org/horizon/Version.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/Version.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/Version.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -27,12 +27,10 @@
* Contains version information about this release of JBoss Cache.
*
* @author Bela Ban
- *
* @since 1.0
*/
@Immutable
-public class Version
-{
+public class Version {
public static final String version = "1.0.0.SNAPSHOT";
public static final String codename = "Starobrno";
public static final String projectName = "Horizon";
@@ -46,8 +44,7 @@
/**
* Prints version information.
*/
- public static void main(String[] args)
- {
+ public static void main(String[] args) {
System.out.println(projectName);
System.out.println();
System.out.println("\nVersion: \t" + version);
@@ -59,16 +56,13 @@
/**
* Returns version information as a string.
*/
- public static String printVersion()
- {
+ public static String printVersion() {
return projectName + " '" + codename + "' " + version;
}
- public static String printVersionId(byte[] v, int len)
- {
+ public static String printVersionId(byte[] v, int len) {
StringBuilder sb = new StringBuilder();
- if (v != null)
- {
+ if (v != null) {
if (len <= 0)
len = v.length;
for (int i = 0; i < len; i++)
@@ -77,43 +71,36 @@
return sb.toString();
}
- public static String printVersionId(byte[] v)
- {
+ public static String printVersionId(byte[] v) {
StringBuilder sb = new StringBuilder();
- if (v != null)
- {
+ if (v != null) {
for (byte aV : v) sb.append((char) aV);
}
return sb.toString();
}
- public static boolean compareTo(byte[] v)
- {
+ public static boolean compareTo(byte[] v) {
if (v == null)
return false;
if (v.length < version_id.length)
return false;
- for (int i = 0; i < version_id.length; i++)
- {
+ for (int i = 0; i < version_id.length; i++) {
if (version_id[i] != v[i])
return false;
}
return true;
}
- public static int getLength()
- {
+ public static int getLength() {
return version_id.length;
}
- public static short getVersionShort()
- {
+ public static short getVersionShort() {
return getVersionShort(version);
}
- public static short getVersionShort(String versionString)
- {
+ public static short getVersionShort(String versionString) {
if (versionString == null)
throw new IllegalArgumentException("versionString is null");
@@ -136,15 +123,13 @@
return encodeVersion(a, b, c);
}
- public static short encodeVersion(int major, int minor, int patch)
- {
+ public static short encodeVersion(int major, int minor, int patch) {
return (short) ((major << MAJOR_SHIFT)
+ (minor << MINOR_SHIFT)
+ patch);
}
- public static String decodeVersion(short version)
- {
+ public static String decodeVersion(short version) {
int major = (version & MAJOR_MASK) >> MAJOR_SHIFT;
int minor = (version & MINOR_MASK) >> MINOR_SHIFT;
int patch = (version & PATCH_MASK);
Modified: core/branches/flat/src/main/java/org/horizon/annotations/MBean.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/annotations/MBean.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/annotations/MBean.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -28,9 +28,9 @@
import java.lang.annotation.Target;
/**
- * Classes anotaded with this will be exposed as MBeans.
- * If you are looking for more fined grained way of exposing jmx attributes/operations, take a look at
- * {@link org.horizon.jmx.annotations.ManagedAttribute} and {@link org.horizon.jmx.annotations.ManagedOperation}
+ * Classes anotaded with this will be exposed as MBeans. If you are looking for more fined grained way of exposing jmx
+ * attributes/operations, take a look at {@link org.horizon.jmx.annotations.ManagedAttribute} and {@link
+ * org.horizon.jmx.annotations.ManagedOperation}
*
* @author Mircea.Markus at jboss.com
* @since 1.0
@@ -38,8 +38,7 @@
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
@Inherited
-public @interface MBean
-{
+public @interface MBean {
public abstract String objectName() default "";
public abstract boolean exposeAll() default false;
Modified: core/branches/flat/src/main/java/org/horizon/annotations/ManagedAttribute.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/annotations/ManagedAttribute.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/annotations/ManagedAttribute.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -27,19 +27,16 @@
import java.lang.annotation.Target;
/**
- * Indicates that a public method or a field (any visibility) in
- * an MBean class defines an MBean attribute. This annotation can
- * be applied to either a field or a public setter and/or getter
- * method of a public class that is itself is optionally annotated
- * with an @MBean annotation, or inherits such an annotation from
- * a superclass.
- * @since 1.0
+ * Indicates that a public method or a field (any visibility) in an MBean class defines an MBean attribute. This
+ * annotation can be applied to either a field or a public setter and/or getter method of a public class that is itself
+ * is optionally annotated with an @MBean annotation, or inherits such an annotation from a superclass.
+ *
* @author (various)
+ * @since 1.0
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.FIELD})
-public @interface ManagedAttribute
-{
+public @interface ManagedAttribute {
public abstract String description() default "";
public abstract String name() default "";
Modified: core/branches/flat/src/main/java/org/horizon/annotations/ManagedOperation.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/annotations/ManagedOperation.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/annotations/ManagedOperation.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -27,17 +27,15 @@
import java.lang.annotation.Target;
/**
- * Indicates that a method in an MBean class defines an MBean
- * operation. @ManagedOperation annotation can be applied to a
- * public method of a public class that is itself optionally
- * annotated with an @MBean annotation, or inherits such an
+ * Indicates that a method in an MBean class defines an MBean operation. @ManagedOperation annotation can be applied to
+ * a public method of a public class that is itself optionally annotated with an @MBean annotation, or inherits such an
* annotation from a superclass.
- * @since 1.0
+ *
* @author (various)
+ * @since 1.0
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
-public @interface ManagedOperation
-{
+public @interface ManagedOperation {
public abstract String description() default "";
}
\ No newline at end of file
Modified: core/branches/flat/src/main/java/org/horizon/atomic/AtomicHashMap.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/atomic/AtomicHashMap.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/atomic/AtomicHashMap.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -34,14 +34,13 @@
* scope of an ongoing transaction or batch.
* <p/>
*
+ * @author (various)
* @param <K>
* @param <V>
* @since 1.0
- * @author (various)
*/
@NotThreadSafe
-public class AtomicHashMap<K, V> implements AtomicMap<K, V>, DeltaAware, Cloneable
-{
+public class AtomicHashMap<K, V> implements AtomicMap<K, V>, DeltaAware, Cloneable {
FastCopyHashMap<K, V> delegate;
AtomicHashMapDelta delta = null;
AtomicHashMapProxy proxy;
@@ -50,51 +49,42 @@
* Construction only allowed through this factory method. This factory is intended for use internally by the
* CacheDelegate. User code should use {@link AtomicMapCache#getAtomicMap(Object)}.
*/
- public static AtomicHashMap newInstance(Cache cache, Object cacheKey)
- {
+ public static AtomicHashMap newInstance(Cache cache, Object cacheKey) {
AtomicHashMap value = new AtomicHashMap();
Object oldValue = cache.putIfAbsent(cacheKey, value);
if (oldValue != null) value = (AtomicHashMap) oldValue;
return value;
}
- AtomicHashMap()
- {
+ AtomicHashMap() {
delegate = new FastCopyHashMap<K, V>();
}
- public void commit()
- {
+ public void commit() {
if (delta != null) delta = null;
}
- public int size()
- {
+ public int size() {
return delegate.size();
}
- public boolean isEmpty()
- {
+ public boolean isEmpty() {
return delegate.isEmpty();
}
- public boolean containsKey(Object key)
- {
+ public boolean containsKey(Object key) {
return delegate.containsKey(key);
}
- public boolean containsValue(Object value)
- {
+ public boolean containsValue(Object value) {
return delegate.containsValue(value);
}
- public V get(Object key)
- {
+ public V get(Object key) {
return delegate.get(key);
}
- public V put(K key, V value)
- {
+ public V put(K key, V value) {
PutOperation<K, V> op = new PutOperation<K, V>();
op.key = key;
op.newValue = value;
@@ -103,8 +93,7 @@
return op.oldValue;
}
- public V remove(Object key)
- {
+ public V remove(Object key) {
RemoveOperation<K, V> op = new RemoveOperation<K, V>();
op.key = (K) key;
op.oldValue = delegate.remove(key);
@@ -112,75 +101,63 @@
return op.oldValue;
}
- public void putAll(Map<? extends K, ? extends V> t)
- {
+ public void putAll(Map<? extends K, ? extends V> t) {
// this is crappy - need to do this more efficiently!
for (Entry<? extends K, ? extends V> e : t.entrySet()) put(e.getKey(), e.getValue());
}
- public void clear()
- {
+ public void clear() {
ClearOperation<K, V> op = new ClearOperation<K, V>();
op.originalEntries = (FastCopyHashMap<K, V>) delegate.clone();
delta.addOperation(op);
delegate.clear();
}
- public Set<K> keySet()
- {
+ public Set<K> keySet() {
return delegate.keySet();
}
- public Collection<V> values()
- {
+ public Collection<V> values() {
return delegate.values();
}
- public Set<Entry<K, V>> entrySet()
- {
+ public Set<Entry<K, V>> entrySet() {
return delegate.entrySet();
}
- public AtomicMap getProxy(Cache cache, Object mapKey)
- {
+ public AtomicMap getProxy(Cache cache, Object mapKey) {
// construct the proxy lazily
if (proxy == null) // DCL is OK here since proxy is volatile (and we live in a post-JDK 5 world)
{
- synchronized (this)
- {
+ synchronized (this) {
if (proxy == null) proxy = new AtomicHashMapProxy(cache, mapKey);
}
}
return proxy;
}
- public Delta delta()
- {
+ public Delta delta() {
Delta toReturn = delta == null ? NullDelta.INSTANCE : delta;
delta = null; // reset
return toReturn;
}
- public AtomicHashMap copyForWrite()
- {
- try
- {
+ public AtomicHashMap copyForWrite() {
+ try {
AtomicHashMap clone = (AtomicHashMap) super.clone();
clone.delegate = (FastCopyHashMap) delegate.clone();
clone.proxy = proxy;
return clone;
}
- catch (CloneNotSupportedException e)
- {
+ catch (CloneNotSupportedException e) {
// should never happen!!
throw new RuntimeException(e);
}
}
@Override
- public String toString()
- {
+ public String toString() {
return "AtomicHashMap{" +
"delegate=" + delegate +
'}';
@@ -189,8 +166,7 @@
/**
* Initializes the delta instance to start recording changes.
*/
- public void initForWriting()
- {
+ public void initForWriting() {
delta = new AtomicHashMapDelta();
}
}
Modified: core/branches/flat/src/main/java/org/horizon/atomic/AtomicHashMapDelta.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/atomic/AtomicHashMapDelta.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/atomic/AtomicHashMapDelta.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -36,14 +36,12 @@
* @author Manik Surtani (<a href="mailto:manik AT jboss DOT org">manik AT jboss DOT org</a>)
* @since 1.0
*/
-public class AtomicHashMapDelta implements Delta
-{
+public class AtomicHashMapDelta implements Delta {
private List<Operation> changelog;
private static final Log log = LogFactory.getLog(AtomicHashMapDelta.class);
private static final boolean trace = log.isTraceEnabled();
- public DeltaAware merge(DeltaAware d)
- {
+ public DeltaAware merge(DeltaAware d) {
AtomicHashMap other;
if (d != null && (d instanceof AtomicHashMap))
other = (AtomicHashMap) d;
@@ -55,38 +53,32 @@
return other;
}
- public void addOperation(Operation o)
- {
- if (changelog == null)
- {
+ public void addOperation(Operation o) {
+ if (changelog == null) {
// lazy init
changelog = new LinkedList<Operation>();
}
changelog.add(o);
}
- public void writeExternal(ObjectOutput out) throws IOException
- {
+ public void writeExternal(ObjectOutput out) throws IOException {
if (trace) log.trace("Serializing changelog " + changelog);
out.writeObject(changelog);
}
- public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException
- {
+ public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
changelog = (List<Operation>) in.readObject();
if (trace) log.trace("Deserialized changelog " + changelog);
}
@Override
- public String toString()
- {
+ public String toString() {
return "AtomicHashMapDelta{" +
"changelog=" + changelog +
'}';
}
- public int getChangeLogSize()
- {
+ public int getChangeLogSize() {
return changelog == null ? 0 : changelog.size();
}
}
\ No newline at end of file
Modified: core/branches/flat/src/main/java/org/horizon/atomic/AtomicHashMapProxy.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/atomic/AtomicHashMapProxy.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/atomic/AtomicHashMapProxy.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -35,36 +35,28 @@
* @author Manik Surtani (<a href="mailto:manik AT jboss DOT org">manik AT jboss DOT org</a>)
* @since 1.0
*/
-public class AtomicHashMapProxy<K, V> extends AutoBatchSupport implements AtomicMap<K, V>
-{
+public class AtomicHashMapProxy<K, V> extends AutoBatchSupport implements AtomicMap<K, V> {
Object deltaMapKey;
Cache cache;
- public AtomicHashMapProxy(Cache cache, Object deltaMapKey)
- {
+ public AtomicHashMapProxy(Cache cache, Object deltaMapKey) {
this.cache = cache;
this.deltaMapKey = deltaMapKey;
this.batchContainer = ((CacheSPI) cache).getBatchContainer();
}
// internal helper, reduces lots of casts.
- private AtomicHashMap<K, V> getDeltaMapForRead()
- {
+ private AtomicHashMap<K, V> getDeltaMapForRead() {
return (AtomicHashMap<K, V>) cache.get(deltaMapKey);
}
- private AtomicHashMap<K, V> getDeltaMapForWrite()
- {
- if (ownsLock())
- {
+ private AtomicHashMap<K, V> getDeltaMapForWrite() {
+ if (ownsLock()) {
return (AtomicHashMap<K, V>) cache.get(deltaMapKey);
- }
- else
- {
+ } else {
// acquire WL
boolean suppressLocks = cache.getInvocationContext().getOptionOverrides().isSuppressLocking();
- if (!suppressLocks)
- {
+ if (!suppressLocks) {
cache.getInvocationContext().getOptionOverrides().setForceWriteLock(true);
}
AtomicHashMap map = getDeltaMapForRead();
@@ -78,103 +70,82 @@
}
}
- private boolean ownsLock()
- {
+ private boolean ownsLock() {
return cache.getInvocationContext().hasLockedKey(deltaMapKey);
}
// readers
- public Set<K> keySet()
- {
+ public Set<K> keySet() {
return getDeltaMapForRead().keySet();
}
- public Collection<V> values()
- {
+ public Collection<V> values() {
return getDeltaMapForRead().values();
}
- public Set<Entry<K, V>> entrySet()
- {
+ public Set<Entry<K, V>> entrySet() {
return getDeltaMapForRead().entrySet();
}
- public int size()
- {
+ public int size() {
return getDeltaMapForRead().size();
}
- public boolean isEmpty()
- {
+ public boolean isEmpty() {
return getDeltaMapForRead().isEmpty();
}
- public boolean containsKey(Object key)
- {
+ public boolean containsKey(Object key) {
return getDeltaMapForRead().containsKey(key);
}
- public boolean containsValue(Object value)
- {
+ public boolean containsValue(Object value) {
return getDeltaMapForRead().containsValue(value);
}
- public V get(Object key)
- {
+ public V get(Object key) {
return getDeltaMapForRead().get(key);
}
// writers
- public V put(K key, V value)
- {
- try
- {
+ public V put(K key, V value) {
+ try {
startAtomic();
return getDeltaMapForWrite().put(key, value);
}
- finally
- {
+ finally {
endAtomic();
}
}
- public V remove(Object key)
- {
- try
- {
+ public V remove(Object key) {
+ try {
startAtomic();
return getDeltaMapForWrite().remove(key);
}
- finally
- {
+ finally {
endAtomic();
}
}
- public void putAll(Map<? extends K, ? extends V> m)
- {
- try
- {
+ public void putAll(Map<? extends K, ? extends V> m) {
+ try {
startAtomic();
getDeltaMapForWrite().putAll(m);
}
- finally
- {
+ finally {
endAtomic();
}
}
- public void clear()
- {
- try
- {
+ public void clear() {
+ try {
startAtomic();
getDeltaMapForWrite().clear();
}
- finally
- {
+ finally {
endAtomic();
}
}
Modified: core/branches/flat/src/main/java/org/horizon/atomic/AtomicMap.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/atomic/AtomicMap.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/atomic/AtomicMap.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -37,6 +37,5 @@
* @see AtomicHashMap
* @since 1.0
*/
-public interface AtomicMap<K, V> extends Map<K, V>
-{
+public interface AtomicMap<K, V> extends Map<K, V> {
}
Modified: core/branches/flat/src/main/java/org/horizon/atomic/AtomicMapCache.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/atomic/AtomicMapCache.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/atomic/AtomicMapCache.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -31,8 +31,7 @@
* @see AtomicMap
* @since 1.0
*/
-public interface AtomicMapCache<K, V> extends Cache<K, V>
-{
+public interface AtomicMapCache<K, V> extends Cache<K, V> {
/**
* Returns an atomic map. The classes passed in are used to parameterize the Map returned.
*
@@ -42,7 +41,8 @@
* @param <X> map keys
* @param <Y> map values
* @return a new or existing atomic map. Never null.
- * @throws ClassCastException if there already is a value stored under the given key and the type of value cannot be used as an AtomicMap.
+ * @throws ClassCastException if there already is a value stored under the given key and the type of value cannot be
+ * used as an AtomicMap.
*/
<AMK, AMV> AtomicMap<AMK, AMV> getAtomicMap(K key, Class<AMK> atomicMapKeyType, Class<AMV> atomicMapValueType) throws ClassCastException;
@@ -51,7 +51,8 @@
*
* @param key key under which to obtain and store this map in the cache
* @return a new or existing atomic map. Never null.
- * @throws ClassCastException if there already is a value stored under the given key and the type of value cannot be used as an AtomicMap.
+ * @throws ClassCastException if there already is a value stored under the given key and the type of value cannot be
+ * used as an AtomicMap.
*/
AtomicMap getAtomicMap(K key) throws ClassCastException;
}
Modified: core/branches/flat/src/main/java/org/horizon/atomic/ClearOperation.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/atomic/ClearOperation.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/atomic/ClearOperation.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -26,17 +26,14 @@
import java.util.Map;
-public class ClearOperation<K, V> extends Operation<K, V>
-{
+public class ClearOperation<K, V> extends Operation<K, V> {
FastCopyHashMap<K, V> originalEntries;
- public void rollback(Map<K, V> delegate)
- {
+ public void rollback(Map<K, V> delegate) {
if (!originalEntries.isEmpty()) delegate.putAll(originalEntries);
}
- public void replay(Map<K, V> delegate)
- {
+ public void replay(Map<K, V> delegate) {
delegate.clear();
}
}
\ No newline at end of file
Modified: core/branches/flat/src/main/java/org/horizon/atomic/Delta.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/atomic/Delta.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/atomic/Delta.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -29,14 +29,13 @@
* @author Manik Surtani (<a href="mailto:manik AT jboss DOT org">manik AT jboss DOT org</a>)
* @since 1.0
*/
-public interface Delta extends Externalizable
-{
+public interface Delta extends Externalizable {
/**
* Merge the current set of deltas with a given {@link DeltaAware} instance, and return a coherent and complete
* {@link DeltaAware} instance. Implementations should be able to deal with null values passed in, or values of a
* different type from the expected DeltaAware instance. Usually the approach would be to ignore what is passed in,
- * create a new instance of the DeltaAware implementation that the current Delta implementation is written for,
- * apply changes and pass it back.
+ * create a new instance of the DeltaAware implementation that the current Delta implementation is written for, apply
+ * changes and pass it back.
*
* @param d instance to merge with, or null if no merging is needed
* @return a fully coherent and usable instance of DeltaAware which may or may not be the same instance passed in
Modified: core/branches/flat/src/main/java/org/horizon/atomic/DeltaAware.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/atomic/DeltaAware.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/atomic/DeltaAware.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -24,16 +24,15 @@
/**
* This interface allows the extraction of deltas.
* <p/>
- * Implementations would be closely coupled to a corresponding {@link Delta} implementation, since {@link org.horizon.atomic.Delta#instantiate()}
- * would need to know how to recreate this instance of DeltaAware if needed.
+ * Implementations would be closely coupled to a corresponding {@link Delta} implementation, since {@link
+ * org.horizon.atomic.Delta#instantiate()} would need to know how to recreate this instance of DeltaAware if needed.
* <p/>
*
* @author Manik Surtani (<a href="mailto:manik AT jboss DOT org">manik AT jboss DOT org</a>)
* @see Delta
* @since 1.0
*/
-public interface DeltaAware
-{
+public interface DeltaAware {
/**
* Extracts changes made to implementations, in an efficient format that can easily and cheaply be serialized and
* deserialized. This method can only be called once for each changeset as it wipes its internal changelog when
@@ -44,7 +43,8 @@
Delta delta();
/**
- * Indicate that all deltas collected to date has been extracted (via a call to {@link #delta()}) and can be discarded.
+ * Indicate that all deltas collected to date has been extracted (via a call to {@link #delta()}) and can be
+ * discarded.
*/
void commit();
}
Modified: core/branches/flat/src/main/java/org/horizon/atomic/NullDelta.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/atomic/NullDelta.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/atomic/NullDelta.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -32,22 +32,18 @@
* @author Manik Surtani (<a href="mailto:manik AT jboss DOT org">manik AT jboss DOT org</a>)
* @since 1.0
*/
-public class NullDelta implements Externalizable, Delta
-{
+public class NullDelta implements Externalizable, Delta {
static final NullDelta INSTANCE = new NullDelta();
- public void writeExternal(ObjectOutput out) throws IOException
- {
+ public void writeExternal(ObjectOutput out) throws IOException {
// don't bother writing anything
}
- public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException
- {
+ public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
// nothing to read
}
- public DeltaAware merge(DeltaAware d)
- {
+ public DeltaAware merge(DeltaAware d) {
return (d != null && d instanceof AtomicHashMap) ? d : new AtomicHashMap();
}
}
\ No newline at end of file
Modified: core/branches/flat/src/main/java/org/horizon/atomic/Operation.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/atomic/Operation.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/atomic/Operation.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -27,19 +27,16 @@
import java.io.ObjectOutput;
import java.util.Map;
-public abstract class Operation<K, V> implements Externalizable
-{
+public abstract class Operation<K, V> implements Externalizable {
public abstract void replay(Map<K, V> delegate);
public abstract void rollback(Map<K, V> delegate);
- public void writeExternal(ObjectOutput out) throws IOException
- {
+ public void writeExternal(ObjectOutput out) throws IOException {
//no op
}
- public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException
- {
+ public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
//no op
}
}
Modified: core/branches/flat/src/main/java/org/horizon/atomic/PutOperation.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/atomic/PutOperation.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/atomic/PutOperation.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -27,36 +27,31 @@
import java.util.Map;
-public class PutOperation<K, V> extends Operation<K, V>
-{
+public class PutOperation<K, V> extends Operation<K, V> {
K key;
V oldValue;
V newValue;
- public void rollback(Map<K, V> delegate)
- {
+ public void rollback(Map<K, V> delegate) {
if (oldValue == null)
delegate.remove(key);
else
delegate.put(key, oldValue);
}
- public void replay(Map<K, V> delegate)
- {
+ public void replay(Map<K, V> delegate) {
delegate.put(key, newValue);
}
@Override
- public void writeExternal(ObjectOutput out) throws IOException
- {
+ public void writeExternal(ObjectOutput out) throws IOException {
// don't bother writing out the old value since it will never be rolled back
out.writeObject(key);
out.writeObject(newValue);
}
@Override
- public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException
- {
+ public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
key = (K) in.readObject();
newValue = (V) in.readObject();
}
Modified: core/branches/flat/src/main/java/org/horizon/atomic/RemoveOperation.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/atomic/RemoveOperation.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/atomic/RemoveOperation.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -27,30 +27,25 @@
import java.util.Map;
-public class RemoveOperation<K, V> extends Operation<K, V>
-{
+public class RemoveOperation<K, V> extends Operation<K, V> {
K key;
V oldValue;
- public void rollback(Map<K, V> delegate)
- {
+ public void rollback(Map<K, V> delegate) {
if (oldValue != null) delegate.put(key, oldValue);
}
- public void replay(Map<K, V> delegate)
- {
+ public void replay(Map<K, V> delegate) {
delegate.remove(key);
}
@Override
- public void writeExternal(ObjectOutput out) throws IOException
- {
+ public void writeExternal(ObjectOutput out) throws IOException {
out.writeObject(key);
}
@Override
- public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException
- {
+ public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
key = (K) in.readObject();
}
}
\ No newline at end of file
Modified: core/branches/flat/src/main/java/org/horizon/batch/AutoBatchSupport.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/batch/AutoBatchSupport.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/batch/AutoBatchSupport.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -32,23 +32,19 @@
* @since 1.0
*/
@NotThreadSafe
-public abstract class AutoBatchSupport
-{
+public abstract class AutoBatchSupport {
protected BatchContainer batchContainer;
- protected void assertBatchingSupported(Configuration c)
- {
+ protected void assertBatchingSupported(Configuration c) {
if (!c.isInvocationBatchingEnabled())
throw new ConfigurationException("Invocation batching not enabled in current configuration! Please use the <invocationBatching /> element.");
}
- protected void startAtomic()
- {
+ protected void startAtomic() {
batchContainer.startBatch(true);
}
- protected void endAtomic()
- {
+ protected void endAtomic() {
batchContainer.endBatch(true, true);
}
}
Modified: core/branches/flat/src/main/java/org/horizon/batch/BatchContainer.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/batch/BatchContainer.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/batch/BatchContainer.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -34,21 +34,17 @@
* @author Manik Surtani (<a href="mailto:manik at jboss.org">manik at jboss.org</a>)
* @since 1.0
*/
-public class BatchContainer
-{
+public class BatchContainer {
TransactionManager transactionManager;
- private ThreadLocal<BatchDetails> batchDetails = new ThreadLocal<BatchDetails>()
- {
+ private ThreadLocal<BatchDetails> batchDetails = new ThreadLocal<BatchDetails>() {
@Override
- protected BatchDetails initialValue()
- {
+ protected BatchDetails initialValue() {
return new BatchDetails();
}
};
@Inject
- void inject(TransactionManager transactionManager)
- {
+ void inject(TransactionManager transactionManager) {
this.transactionManager = transactionManager;
}
@@ -58,19 +54,15 @@
* @return true if a batch was started; false if one was already available.
* @throws CacheException
*/
- public boolean startBatch() throws CacheException
- {
+ public boolean startBatch() throws CacheException {
return startBatch(false);
}
- public boolean startBatch(boolean autoBatch) throws CacheException
- {
+ public boolean startBatch(boolean autoBatch) throws CacheException {
BatchDetails bd = batchDetails.get();
- try
- {
+ try {
bd.invocationCount++;
- if (transactionManager.getTransaction() == null && bd.tx == null)
- {
+ if (transactionManager.getTransaction() == null && bd.tx == null) {
transactionManager.begin();
bd.suspendTxAfterInvocation = !autoBatch;
@@ -84,31 +76,25 @@
}
return false;
}
- catch (Exception e)
- {
+ catch (Exception e) {
throw new CacheException("Unable to start batch", e);
}
- finally
- {
+ finally {
batchDetails.set(bd);
}
}
- public void endBatch(boolean success)
- {
+ public void endBatch(boolean success) {
endBatch(false, success);
}
- public void endBatch(boolean autoBatch, boolean success)
- {
+ public void endBatch(boolean autoBatch, boolean success) {
BatchDetails bd = batchDetails.get();
if (bd.tx == null) return;
if (autoBatch) bd.invocationCount--;
- if (!autoBatch || bd.invocationCount == 0)
- {
+ if (!autoBatch || bd.invocationCount == 0) {
Transaction existingTx = null;
- try
- {
+ try {
existingTx = transactionManager.getTransaction();
if ((existingTx == null && !autoBatch) || !bd.tx.equals(existingTx))
@@ -119,41 +105,32 @@
else
bd.tx.rollback();
}
- catch (Exception e)
- {
+ catch (Exception e) {
throw new CacheException("Unable to end batch", e);
}
- finally
- {
+ finally {
batchDetails.remove();
- try
- {
+ try {
if (!autoBatch && existingTx != null) transactionManager.resume(existingTx);
}
- catch (Exception e)
- {
+ catch (Exception e) {
throw new CacheException("Failed resuming existing transaction " + existingTx, e);
}
}
- }
- else
- {
+ } else {
batchDetails.set(bd);
}
}
- public Transaction getBatchTransaction()
- {
+ public Transaction getBatchTransaction() {
return batchDetails.get().tx;
}
- public boolean isSuspendTxAfterInvocation()
- {
+ public boolean isSuspendTxAfterInvocation() {
return batchDetails.get().suspendTxAfterInvocation;
}
- private static class BatchDetails
- {
+ private static class BatchDetails {
int invocationCount;
boolean suspendTxAfterInvocation;
Transaction tx;
Modified: core/branches/flat/src/main/java/org/horizon/cluster/ReplicationQueue.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/cluster/ReplicationQueue.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/cluster/ReplicationQueue.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -45,11 +45,9 @@
* Periodically (or when certain size is exceeded) takes elements and replicates them.
*
* @author <a href="mailto:bela at jboss.org">Bela Ban</a> May 24, 2003
- *
* @since 1.0
*/
-public class ReplicationQueue
-{
+public class ReplicationQueue {
private static final Log log = LogFactory.getLog(ReplicationQueue.class);
@@ -73,14 +71,12 @@
private CommandsFactory commandsFactory;
private static final AtomicInteger counter = new AtomicInteger(0);
- public boolean isEnabled()
- {
+ public boolean isEnabled() {
return enabled;
}
@Inject
- private void injectDependencies(RPCManager rpcManager, Configuration configuration, CommandsFactory commandsFactory)
- {
+ private void injectDependencies(RPCManager rpcManager, Configuration configuration, CommandsFactory commandsFactory) {
this.rpcManager = rpcManager;
this.configuration = configuration;
this.commandsFactory = commandsFactory;
@@ -93,29 +89,21 @@
* Starts the asynchronous flush queue.
*/
@Start
- public synchronized void start()
- {
+ public synchronized void start() {
long interval = configuration.getReplQueueInterval();
this.max_elements = configuration.getReplQueueMaxElements();
// check again
enabled = configuration.isUseReplQueue();
- if (enabled)
- {
- if (interval > 0)
- {
- if (scheduledExecutor == null)
- {
- scheduledExecutor = Executors.newSingleThreadScheduledExecutor(new ThreadFactory()
- {
- public Thread newThread(Runnable r)
- {
+ if (enabled) {
+ if (interval > 0) {
+ if (scheduledExecutor == null) {
+ scheduledExecutor = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() {
+ public Thread newThread(Runnable r) {
return new Thread(r, "ReplicationQueue-periodicProcessor-" + counter.getAndIncrement());
}
});
- scheduledExecutor.scheduleWithFixedDelay(new Runnable()
- {
- public void run()
- {
+ scheduledExecutor.scheduleWithFixedDelay(new Runnable() {
+ public void run() {
flush();
}
}, 500l, interval, TimeUnit.MILLISECONDS);
@@ -128,10 +116,8 @@
* Stops the asynchronous flush queue.
*/
@Stop
- public synchronized void stop()
- {
- if (scheduledExecutor != null)
- {
+ public synchronized void stop() {
+ if (scheduledExecutor != null) {
scheduledExecutor.shutdownNow();
}
scheduledExecutor = null;
@@ -141,12 +127,10 @@
/**
* Adds a new method call.
*/
- public void add(ReplicateCommand job)
- {
+ public void add(ReplicateCommand job) {
if (job == null)
throw new NullPointerException("job is null");
- synchronized (elements)
- {
+ synchronized (elements) {
elements.add(job);
if (elements.size() >= max_elements)
flush();
@@ -156,28 +140,23 @@
/**
* Flushes existing method calls.
*/
- public void flush()
- {
+ public void flush() {
List<ReplicableCommand> toReplicate;
- synchronized (elements)
- {
+ synchronized (elements) {
if (log.isTraceEnabled())
log.trace("flush(): flushing repl queue (num elements=" + elements.size() + ")");
toReplicate = new ArrayList<ReplicableCommand>(elements);
elements.clear();
}
- if (toReplicate.size() > 0)
- {
- try
- {
+ if (toReplicate.size() > 0) {
+ try {
ReplicateCommand replicateCommand = commandsFactory.buildReplicateCommand(toReplicate);
// send to all live nodes in the cluster
rpcManager.callRemoteMethods(null, replicateCommand, false, configuration.getSyncReplTimeout(), false);
}
- catch (Throwable t)
- {
+ catch (Throwable t) {
log.error("failed replicating " + toReplicate.size() + " elements in replication queue", t);
}
}
Modified: core/branches/flat/src/main/java/org/horizon/commands/AbstractVisitor.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/commands/AbstractVisitor.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/commands/AbstractVisitor.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -44,71 +44,58 @@
* @author Manik Surtani
* @since 1.0
*/
-public abstract class AbstractVisitor implements Visitor
-{
+public abstract class AbstractVisitor implements Visitor {
// write commands
- public Object visitPutKeyValueCommand(InvocationContext ctx, PutKeyValueCommand command) throws Throwable
- {
+ public Object visitPutKeyValueCommand(InvocationContext ctx, PutKeyValueCommand command) throws Throwable {
return handleDefault(ctx, command);
}
- public Object visitRemoveCommand(InvocationContext ctx, RemoveCommand command) throws Throwable
- {
+ public Object visitRemoveCommand(InvocationContext ctx, RemoveCommand command) throws Throwable {
return handleDefault(ctx, command);
}
- public Object visitReplaceCommand(InvocationContext ctx, ReplaceCommand command) throws Throwable
- {
+ public Object visitReplaceCommand(InvocationContext ctx, ReplaceCommand command) throws Throwable {
return handleDefault(ctx, command);
}
- public Object visitClearCommand(InvocationContext ctx, ClearCommand command) throws Throwable
- {
+ public Object visitClearCommand(InvocationContext ctx, ClearCommand command) throws Throwable {
return handleDefault(ctx, command);
}
- public Object visitPutMapCommand(InvocationContext ctx, PutMapCommand command) throws Throwable
- {
+ public Object visitPutMapCommand(InvocationContext ctx, PutMapCommand command) throws Throwable {
return handleDefault(ctx, command);
}
- public Object visitEvictCommand(InvocationContext ctx, EvictCommand command) throws Throwable
- {
+ public Object visitEvictCommand(InvocationContext ctx, EvictCommand command) throws Throwable {
return handleDefault(ctx, command);
}
// read commands
- public Object visitSizeCommand(InvocationContext ctx, SizeCommand command) throws Throwable
- {
+ public Object visitSizeCommand(InvocationContext ctx, SizeCommand command) throws Throwable {
return handleDefault(ctx, command);
}
- public Object visitGetKeyValueCommand(InvocationContext ctx, GetKeyValueCommand command) throws Throwable
- {
+ public Object visitGetKeyValueCommand(InvocationContext ctx, GetKeyValueCommand command) throws Throwable {
return handleDefault(ctx, command);
}
// tx commands
- public Object visitPrepareCommand(InvocationContext ctx, PrepareCommand command) throws Throwable
- {
+ public Object visitPrepareCommand(InvocationContext ctx, PrepareCommand command) throws Throwable {
return handleDefault(ctx, command);
}
- public Object visitRollbackCommand(InvocationContext ctx, RollbackCommand command) throws Throwable
- {
+ public Object visitRollbackCommand(InvocationContext ctx, RollbackCommand command) throws Throwable {
return handleDefault(ctx, command);
}
- public Object visitCommitCommand(InvocationContext ctx, CommitCommand command) throws Throwable
- {
+ public Object visitCommitCommand(InvocationContext ctx, CommitCommand command) throws Throwable {
return handleDefault(ctx, command);
}
- public Object visitInvalidateCommand(InvocationContext ctx, InvalidateCommand invalidateCommand) throws Throwable
- {
+ public Object visitInvalidateCommand(InvocationContext ctx, InvalidateCommand invalidateCommand) throws Throwable {
return handleDefault(ctx, invalidateCommand);
}
@@ -121,8 +108,7 @@
* @return return value
* @throws Throwable in the case of a problem
*/
- protected Object handleDefault(InvocationContext ctx, VisitableCommand command) throws Throwable
- {
+ protected Object handleDefault(InvocationContext ctx, VisitableCommand command) throws Throwable {
return null;
}
@@ -133,10 +119,8 @@
* @param toVisit collection of commands to visit
* @throws Throwable in the event of problems
*/
- public void visitCollection(InvocationContext ctx, Collection<? extends VisitableCommand> toVisit) throws Throwable
- {
- for (VisitableCommand command : toVisit)
- {
+ public void visitCollection(InvocationContext ctx, Collection<? extends VisitableCommand> toVisit) throws Throwable {
+ for (VisitableCommand command : toVisit) {
command.acceptVisitor(ctx, this);
}
}
Modified: core/branches/flat/src/main/java/org/horizon/commands/CommandsFactory.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/commands/CommandsFactory.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/commands/CommandsFactory.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -47,8 +47,7 @@
* @since 1.0
*/
@Scope(Scopes.NAMED_CACHE)
-public interface CommandsFactory
-{
+public interface CommandsFactory {
PutKeyValueCommand buildPutKeyValueCommand(Object key, Object value);
RemoveCommand buildRemoveCommand(Object key, Object value);
Modified: core/branches/flat/src/main/java/org/horizon/commands/CommandsFactoryImpl.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/commands/CommandsFactoryImpl.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/commands/CommandsFactoryImpl.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -28,7 +28,13 @@
import org.horizon.commands.tx.CommitCommand;
import org.horizon.commands.tx.PrepareCommand;
import org.horizon.commands.tx.RollbackCommand;
-import org.horizon.commands.write.*;
+import org.horizon.commands.write.ClearCommand;
+import org.horizon.commands.write.EvictCommand;
+import org.horizon.commands.write.InvalidateCommand;
+import org.horizon.commands.write.PutKeyValueCommand;
+import org.horizon.commands.write.PutMapCommand;
+import org.horizon.commands.write.RemoveCommand;
+import org.horizon.commands.write.ReplaceCommand;
import org.horizon.container.DataContainer;
import org.horizon.factories.annotations.Inject;
import org.horizon.interceptors.InterceptorChain;
@@ -43,152 +49,125 @@
* @author Mircea.Markus at jboss.com
* @since 1.0
*/
-public class CommandsFactoryImpl implements CommandsFactory
-{
+public class CommandsFactoryImpl implements CommandsFactory {
private DataContainer dataContainer;
private Notifier notifier;
private InterceptorChain interceptorChain;
@Inject
- public void setupDependencies(DataContainer container, Notifier notifier, InterceptorChain interceptorChain)
- {
+ public void setupDependencies(DataContainer container, Notifier notifier, InterceptorChain interceptorChain) {
this.dataContainer = container;
this.notifier = notifier;
this.interceptorChain = interceptorChain;
}
- public PutKeyValueCommand buildPutKeyValueCommand(Object key, Object value)
- {
+ public PutKeyValueCommand buildPutKeyValueCommand(Object key, Object value) {
return new PutKeyValueCommand(key, value, false, notifier);
}
- public RemoveCommand buildRemoveCommand(Object key, Object value)
- {
+ public RemoveCommand buildRemoveCommand(Object key, Object value) {
return new RemoveCommand(key, value, notifier);
}
- public ReplaceCommand buildReplaceCommand(Object key, Object oldValue, Object newValue)
- {
+ public ReplaceCommand buildReplaceCommand(Object key, Object oldValue, Object newValue) {
return new ReplaceCommand(key, oldValue, newValue);
}
- public SizeCommand buildSizeCommand()
- {
+ public SizeCommand buildSizeCommand() {
return new SizeCommand(dataContainer);
}
- public GetKeyValueCommand buildGetKeyValueCommand(Object key)
- {
+ public GetKeyValueCommand buildGetKeyValueCommand(Object key) {
return new GetKeyValueCommand(key, notifier);
}
- public PutMapCommand buildPutMapCommand(Map map)
- {
+ public PutMapCommand buildPutMapCommand(Map map) {
return new PutMapCommand(map, notifier);
}
- public ClearCommand buildClearCommand()
- {
+ public ClearCommand buildClearCommand() {
return new ClearCommand();
}
- public EvictCommand buildEvictCommand(Object key)
- {
+ public EvictCommand buildEvictCommand(Object key) {
EvictCommand command = new EvictCommand(key);
command.initialize(notifier);
return command;
}
- public PrepareCommand buildPrepareCommand(GlobalTransaction gtx, List modifications, Address localAddress, boolean onePhaseCommit)
- {
+ public PrepareCommand buildPrepareCommand(GlobalTransaction gtx, List modifications, Address localAddress, boolean onePhaseCommit) {
return new PrepareCommand(gtx, modifications, localAddress, onePhaseCommit);
}
- public CommitCommand buildCommitCommand(GlobalTransaction gtx)
- {
+ public CommitCommand buildCommitCommand(GlobalTransaction gtx) {
return new CommitCommand(gtx);
}
- public RollbackCommand buildRollbackCommand(GlobalTransaction gtx)
- {
+ public RollbackCommand buildRollbackCommand(GlobalTransaction gtx) {
return new RollbackCommand(gtx);
}
- public ReplicateCommand buildReplicateCommand(List<ReplicableCommand> toReplicate)
- {
+ public ReplicateCommand buildReplicateCommand(List<ReplicableCommand> toReplicate) {
return new ReplicateCommand(toReplicate);
}
- public ReplicateCommand buildReplicateCommand(ReplicableCommand call)
- {
+ public ReplicateCommand buildReplicateCommand(ReplicableCommand call) {
return new ReplicateCommand(call);
}
- public ReplicableCommand fromStream(byte id, Object[] parameters)
- {
+ public ReplicableCommand fromStream(byte id, Object[] parameters) {
ReplicableCommand command;
- switch (id)
- {
- case PutKeyValueCommand.METHOD_ID:
- {
+ switch (id) {
+ case PutKeyValueCommand.METHOD_ID: {
PutKeyValueCommand c = new PutKeyValueCommand();
c.init(notifier);
command = c;
break;
}
- case PutMapCommand.METHOD_ID:
- {
+ case PutMapCommand.METHOD_ID: {
PutMapCommand c = new PutMapCommand();
c.init(notifier);
command = c;
break;
}
- case RemoveCommand.METHOD_ID:
- {
+ case RemoveCommand.METHOD_ID: {
RemoveCommand c = new RemoveCommand();
c.init(notifier);
command = c;
break;
}
- case ReplaceCommand.METHOD_ID:
- {
+ case ReplaceCommand.METHOD_ID: {
ReplaceCommand c = new ReplaceCommand();
command = c;
break;
}
- case GetKeyValueCommand.METHOD_ID:
- {
+ case GetKeyValueCommand.METHOD_ID: {
GetKeyValueCommand c = new GetKeyValueCommand();
command = c;
break;
}
- case ClearCommand.METHOD_ID:
- {
+ case ClearCommand.METHOD_ID: {
ClearCommand c = new ClearCommand();
command = c;
break;
}
- case PrepareCommand.METHOD_ID:
- {
+ case PrepareCommand.METHOD_ID: {
PrepareCommand c = new PrepareCommand();
command = c;
break;
}
- case CommitCommand.METHOD_ID:
- {
+ case CommitCommand.METHOD_ID: {
CommitCommand c = new CommitCommand();
command = c;
break;
}
- case RollbackCommand.METHOD_ID:
- {
+ case RollbackCommand.METHOD_ID: {
RollbackCommand c = new RollbackCommand();
command = c;
break;
}
case ReplicateCommand.MULTIPLE_METHOD_ID:
- case ReplicateCommand.SINGLE_METHOD_ID:
- {
+ case ReplicateCommand.SINGLE_METHOD_ID: {
ReplicateCommand c = new ReplicateCommand();
c.initialize(interceptorChain);
command = c;
@@ -202,8 +181,7 @@
return command;
}
- public InvalidateCommand buildInvalidateCommand(Object fqn)
- {
+ public InvalidateCommand buildInvalidateCommand(Object fqn) {
throw new UnsupportedOperationException("Not implemented");//todo please implement!
}
}
Modified: core/branches/flat/src/main/java/org/horizon/commands/DataCommand.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/commands/DataCommand.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/commands/DataCommand.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -29,7 +29,6 @@
* @author Manik Surtani (<a href="mailto:manik at jboss.org">manik at jboss.org</a>)
* @since 1.0
*/
-public interface DataCommand extends VisitableCommand
-{
+public interface DataCommand extends VisitableCommand {
Object getKey();
}
\ No newline at end of file
Modified: core/branches/flat/src/main/java/org/horizon/commands/ReplicableCommand.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/commands/ReplicableCommand.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/commands/ReplicableCommand.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -31,13 +31,11 @@
* @author Manik Surtani
* @since 1.0
*/
-public interface ReplicableCommand
-{
+public interface ReplicableCommand {
/**
* Performs the primary function of the command. Please see specific implementation classes for details on what is
- * performed as well as return types.
- * <b>Important</b>: this method will be invoked at the end of interceptors chain. It should never be called directly from
- * a custom interceptor.
+ * performed as well as return types. <b>Important</b>: this method will be invoked at the end of interceptors chain.
+ * It should never be called directly from a custom interceptor.
*
* @param ctx invocation context
* @return arbitrary return value generated by performing this command
@@ -63,7 +61,7 @@
* Used by the {@link CommandsFactory} to create a command from raw data read off a stream.
*
* @param commandId command id to set. This is usually unused but *could* be used in the event of a command having
- * multiple IDs, such as {@link org.horizon.commands.write.PutKeyValueCommand}.
+ * multiple IDs, such as {@link org.horizon.commands.write.PutKeyValueCommand}.
* @param parameters object array of args
*/
void setParameters(int commandId, Object[] parameters);
Modified: core/branches/flat/src/main/java/org/horizon/commands/TransactionBoundaryCommand.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/commands/TransactionBoundaryCommand.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/commands/TransactionBoundaryCommand.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -29,8 +29,7 @@
* @author Manik Surtani (<a href="mailto:manik at jboss.org">manik at jboss.org</a>)
* @since 1.0
*/
-public interface TransactionBoundaryCommand extends VisitableCommand
-{
+public interface TransactionBoundaryCommand extends VisitableCommand {
GlobalTransaction getGlobalTransaction();
void setGlobalTransaction(GlobalTransaction gtx);
Modified: core/branches/flat/src/main/java/org/horizon/commands/VisitableCommand.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/commands/VisitableCommand.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/commands/VisitableCommand.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -30,8 +30,7 @@
* @author Manik Surtani (<a href="mailto:manik at jboss.org">manik at jboss.org</a>)
* @since 1.0
*/
-public interface VisitableCommand extends ReplicableCommand
-{
+public interface VisitableCommand extends ReplicableCommand {
/**
* Accept a visitor, and return the result of accepting this visitor.
*
Modified: core/branches/flat/src/main/java/org/horizon/commands/Visitor.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/commands/Visitor.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/commands/Visitor.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -35,8 +35,7 @@
import org.horizon.commands.write.ReplaceCommand;
import org.horizon.context.InvocationContext;
-public interface Visitor
-{
+public interface Visitor {
// write commands
Object visitPutKeyValueCommand(InvocationContext ctx, PutKeyValueCommand command) throws Throwable;
Modified: core/branches/flat/src/main/java/org/horizon/commands/read/AbstractDataCommand.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/commands/read/AbstractDataCommand.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/commands/read/AbstractDataCommand.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -27,42 +27,34 @@
* @author Mircea.Markus at jboss.com
* @since 1.0
*/
-public abstract class AbstractDataCommand implements DataCommand
-{
+public abstract class AbstractDataCommand implements DataCommand {
protected Object key;
- public Object getKey()
- {
+ public Object getKey() {
return key;
}
- public void setKey(Object key)
- {
+ public void setKey(Object key) {
this.key = key;
}
- protected AbstractDataCommand(Object key)
- {
+ protected AbstractDataCommand(Object key) {
this.key = key;
}
- protected AbstractDataCommand()
- {
+ protected AbstractDataCommand() {
}
- public void setParameters(int commandId, Object[] parameters)
- {
+ public void setParameters(int commandId, Object[] parameters) {
if (commandId != getCommandId()) throw new IllegalStateException("Invalid method id");
key = parameters[0];
}
- public Object[] getParameters()
- {
+ public Object[] getParameters() {
return new Object[]{key};
}
- public boolean equals(Object o)
- {
+ public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
@@ -73,14 +65,12 @@
return true;
}
- public int hashCode()
- {
+ public int hashCode() {
return (key != null ? key.hashCode() : 0);
}
- public String toString()
- {
+ public String toString() {
return getClass().getSimpleName() + "{" +
"key=" + key +
'}';
Modified: core/branches/flat/src/main/java/org/horizon/commands/read/GetKeyValueCommand.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/commands/read/GetKeyValueCommand.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/commands/read/GetKeyValueCommand.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -34,38 +34,31 @@
* @author Manik Surtani (<a href="mailto:manik at jboss.org">manik at jboss.org</a>)
* @since 1.0
*/
-public class GetKeyValueCommand extends AbstractDataCommand
-{
+public class GetKeyValueCommand extends AbstractDataCommand {
public static final byte METHOD_ID = 26;
private static final Log log = LogFactory.getLog(GetKeyValueCommand.class);
private static final boolean trace = log.isTraceEnabled();
private Notifier notifier;
- public GetKeyValueCommand(Object key, Notifier notifier)
- {
+ public GetKeyValueCommand(Object key, Notifier notifier) {
this.key = key;
this.notifier = notifier;
}
- public GetKeyValueCommand()
- {
+ public GetKeyValueCommand() {
}
- public Object acceptVisitor(InvocationContext ctx, Visitor visitor) throws Throwable
- {
+ public Object acceptVisitor(InvocationContext ctx, Visitor visitor) throws Throwable {
return visitor.visitGetKeyValueCommand(ctx, this);
}
- public Object perform(InvocationContext ctx) throws Throwable
- {
+ public Object perform(InvocationContext ctx) throws Throwable {
MVCCEntry entry = ctx.lookupEntry(key);
- if (entry == null || entry.isNullEntry())
- {
+ if (entry == null || entry.isNullEntry()) {
if (trace) log.trace("Entry not found");
return null;
}
- if (entry.isDeleted())
- {
+ if (entry.isDeleted()) {
if (trace) log.trace("Entry has been deleted and is of type " + entry.getClass().getSimpleName());
return null;
}
@@ -76,8 +69,7 @@
return result;
}
- public byte getCommandId()
- {
+ public byte getCommandId() {
return METHOD_ID;
}
}
Modified: core/branches/flat/src/main/java/org/horizon/commands/read/SizeCommand.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/commands/read/SizeCommand.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/commands/read/SizeCommand.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -32,37 +32,30 @@
* @author Manik Surtani (<a href="mailto:manik at jboss.org">manik at jboss.org</a>)
* @since 1.0
*/
-public class SizeCommand implements VisitableCommand
-{
+public class SizeCommand implements VisitableCommand {
private DataContainer container;
- public SizeCommand(DataContainer container)
- {
+ public SizeCommand(DataContainer container) {
this.container = container;
}
- public Object acceptVisitor(InvocationContext ctx, Visitor visitor) throws Throwable
- {
+ public Object acceptVisitor(InvocationContext ctx, Visitor visitor) throws Throwable {
return visitor.visitSizeCommand(ctx, this);
}
- public Integer perform(InvocationContext ctx) throws Throwable
- {
+ public Integer perform(InvocationContext ctx) throws Throwable {
return container.size();
}
- public byte getCommandId()
- {
+ public byte getCommandId() {
return 0; // no-op
}
- public Object[] getParameters()
- {
+ public Object[] getParameters() {
return new Object[0]; // no-op
}
- public void setParameters(int commandId, Object[] parameters)
- {
+ public void setParameters(int commandId, Object[] parameters) {
// no-op
}
}
Modified: core/branches/flat/src/main/java/org/horizon/commands/remote/ClusteredGetCommand.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/commands/remote/ClusteredGetCommand.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/commands/remote/ClusteredGetCommand.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -33,16 +33,15 @@
import java.util.List;
/**
- * Issues a clustered get call, for use primarily by the {@link ClusteredCacheLoader}. This is
- * not a {@link org.horizon.commands.VisitableCommand} and hence
- * not passed up the {@link org.horizon.interceptors.base.CommandInterceptor} chain.
+ * Issues a clustered get call, for use primarily by the {@link ClusteredCacheLoader}. This is not a {@link
+ * org.horizon.commands.VisitableCommand} and hence not passed up the {@link org.horizon.interceptors.base.CommandInterceptor}
+ * chain.
* <p/>
*
* @author Mircea.Markus at jboss.com
* @since 1.0
*/
-public class ClusteredGetCommand implements ReplicableCommand
-{
+public class ClusteredGetCommand implements ReplicableCommand {
public static final byte METHOD_ID = 22;
private DataCommand dataCommand;
@@ -53,18 +52,15 @@
private static final Log log = LogFactory.getLog(ClusteredGetCommand.class);
private static final boolean trace = log.isTraceEnabled();
- public ClusteredGetCommand(boolean searchBackupSubtrees, DataCommand dataCommand)
- {
+ public ClusteredGetCommand(boolean searchBackupSubtrees, DataCommand dataCommand) {
this.searchBackupSubtrees = searchBackupSubtrees;
this.dataCommand = dataCommand;
}
- public ClusteredGetCommand()
- {
+ public ClusteredGetCommand() {
}
- public void initialize(DataContainer dataContainer, InterceptorChain interceptorChain)
- {
+ public void initialize(DataContainer dataContainer, InterceptorChain interceptorChain) {
this.dataContainer = dataContainer;
this.interceptorChain = interceptorChain;
}
@@ -73,16 +69,16 @@
* Invokes a {@link DataCommand} on a remote cache and returns results.
*
* @param context invocation context, ignored.
- * @return a List containing 2 elements: a boolean, (true or false) and a value (Object) which is the result of invoking a remote get specified by {@link #getDataCommand()}. If buddy replication is used one further element is added - an Fqn of the backup subtree in which this node may be found.
+ * @return a List containing 2 elements: a boolean, (true or false) and a value (Object) which is the result of
+ * invoking a remote get specified by {@link #getDataCommand()}. If buddy replication is used one further
+ * element is added - an Fqn of the backup subtree in which this node may be found.
*/
- public Object perform(InvocationContext context) throws Throwable
- {
+ public Object perform(InvocationContext context) throws Throwable {
if (trace)
log.trace("Clustered Get called with params: " + dataCommand + ", " + searchBackupSubtrees);
Object callResults = null;
- try
- {
+ try {
InvocationContext ctx = interceptorChain.getInvocationContext();
ctx.setOriginLocal(false);
// very hacky to be calling this command directly.
@@ -91,62 +87,51 @@
if (trace) log.trace("Got result " + callResults + ", found=" + found);
if (found && callResults == null) callResults = createEmptyResults();
}
- catch (Exception e)
- {
+ catch (Exception e) {
log.warn("Problems processing clusteredGet call", e);
}
List<Object> results = new ArrayList<Object>(2);
- if (callResults != null)
- {
+ if (callResults != null) {
results.add(true);
results.add(callResults);
- }
- else
- {
+ } else {
results.add(false);
results.add(null);
}
return results;
}
- public byte getCommandId()
- {
+ public byte getCommandId() {
return METHOD_ID;
}
/**
* Creates an empty Collection class based on the return type of the method called.
*/
- private Object createEmptyResults()
- {
+ private Object createEmptyResults() {
return null;
}
- public Boolean getSearchBackupSubtrees()
- {
+ public Boolean getSearchBackupSubtrees() {
return searchBackupSubtrees;
}
- public DataCommand getDataCommand()
- {
+ public DataCommand getDataCommand() {
return dataCommand;
}
- public Object[] getParameters()
- {
+ public Object[] getParameters() {
return new Object[]{dataCommand, searchBackupSubtrees}; //To change body of implemented methods use File | Settings | File Templates.
}
- public void setParameters(int commandId, Object[] args)
- {
+ public void setParameters(int commandId, Object[] args) {
dataCommand = (DataCommand) args[0];
searchBackupSubtrees = (Boolean) args[1];
}
@Override
- public boolean equals(Object o)
- {
+ public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
@@ -158,8 +143,7 @@
}
@Override
- public int hashCode()
- {
+ public int hashCode() {
int result;
result = (dataCommand != null ? dataCommand.hashCode() : 0);
result = 31 * result + (searchBackupSubtrees ? 1 : 0);
@@ -167,8 +151,7 @@
}
@Override
- public String toString()
- {
+ public String toString() {
return "ClusteredGetCommand{" +
"dataCommand=" + dataCommand +
", searchBackupSubtrees=" + searchBackupSubtrees +
Modified: core/branches/flat/src/main/java/org/horizon/commands/remote/ReplicateCommand.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/commands/remote/ReplicateCommand.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/commands/remote/ReplicateCommand.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -32,18 +32,17 @@
import java.util.List;
/**
- * Command that implements cluster replication logic. Essentially mimics the replicate() and replicateAll() methods
- * in 2.1.x, we may need to revisit the usefulness of such a command.
+ * Command that implements cluster replication logic. Essentially mimics the replicate() and replicateAll() methods in
+ * 2.1.x, we may need to revisit the usefulness of such a command.
* <p/>
- * This is not a {@link VisitableCommand} and hence
- * not passed up the {@link org.horizon.interceptors.base.CommandInterceptor} chain.
+ * This is not a {@link VisitableCommand} and hence not passed up the {@link org.horizon.interceptors.base.CommandInterceptor}
+ * chain.
* <p/>
*
* @author Mircea.Markus at jboss.com
* @since 1.0
*/
-public class ReplicateCommand implements ReplicableCommand
-{
+public class ReplicateCommand implements ReplicableCommand {
public static final byte SINGLE_METHOD_ID = 13;
public static final byte MULTIPLE_METHOD_ID = 14;
@@ -53,45 +52,36 @@
private static final boolean trace = log.isTraceEnabled();
/**
- * optimisation - rather than constructing a new list each for scenarios where a single modification needs
- * to be replicated rather use this instance.
+ * optimisation - rather than constructing a new list each for scenarios where a single modification needs to be
+ * replicated rather use this instance.
*/
private ReplicableCommand singleModification;
private List<ReplicableCommand> modifications;
- public ReplicateCommand(List<ReplicableCommand> modifications)
- {
- if (modifications != null && modifications.size() == 1)
- {
+ public ReplicateCommand(List<ReplicableCommand> modifications) {
+ if (modifications != null && modifications.size() == 1) {
singleModification = modifications.get(0);
- }
- else
- {
+ } else {
this.modifications = modifications;
}
}
- public ReplicateCommand(ReplicableCommand command)
- {
+ public ReplicateCommand(ReplicableCommand command) {
this.singleModification = command;
}
- public ReplicateCommand()
- {
+ public ReplicateCommand() {
}
- public void initialize(InterceptorChain interceptorChain)
- {
+ public void initialize(InterceptorChain interceptorChain) {
this.invoker = interceptorChain;
}
- public void setSingleModification(ReplicableCommand singleModification)
- {
+ public void setSingleModification(ReplicableCommand singleModification) {
this.singleModification = singleModification;
}
- public void setModifications(List<ReplicableCommand> modifications)
- {
+ public void setModifications(List<ReplicableCommand> modifications) {
if (modifications != null && modifications.size() == 1)
singleModification = modifications.get(0);
else
@@ -105,47 +95,34 @@
* @return null
* @throws Throwable
*/
- public Object perform(InvocationContext ctx) throws Throwable
- {
- if (isSingleCommand())
- {
+ public Object perform(InvocationContext ctx) throws Throwable {
+ if (isSingleCommand()) {
return processSingleCommand(singleModification);
- }
- else
- {
+ } else {
for (ReplicableCommand command : modifications) processSingleCommand(command);
return null;
}
}
private Object processSingleCommand(ReplicableCommand cacheCommand)
- throws Throwable
- {
+ throws Throwable {
Object result;
- try
- {
+ try {
if (trace) log.trace("Invoking command " + cacheCommand + ", with originLocal flag set to false.");
- if (cacheCommand instanceof VisitableCommand)
- {
+ if (cacheCommand instanceof VisitableCommand) {
Object retVal = invoker.invokeRemote((VisitableCommand) cacheCommand);
// we only need to return values for a set of remote calls; not every call.
- if (returnValueForRemoteCall(cacheCommand))
- {
+ if (returnValueForRemoteCall(cacheCommand)) {
result = retVal;
- }
- else
- {
+ } else {
result = null;
}
- }
- else
- {
+ } else {
result = cacheCommand.perform(null);
}
}
- catch (Throwable ex)
- {
+ catch (Throwable ex) {
// TODO deal with PFER
// if (!(cacheCommand instanceof PutForExternalReadCommand))
// {
@@ -161,28 +138,23 @@
return result;
}
- private boolean returnValueForRemoteCall(ReplicableCommand cacheCommand)
- {
+ private boolean returnValueForRemoteCall(ReplicableCommand cacheCommand) {
return cacheCommand instanceof ClusteredGetCommand;
}
- public byte getCommandId()
- {
+ public byte getCommandId() {
return isSingleCommand() ? SINGLE_METHOD_ID : MULTIPLE_METHOD_ID;
}
- public List<ReplicableCommand> getModifications()
- {
+ public List<ReplicableCommand> getModifications() {
return modifications;
}
- public ReplicableCommand getSingleModification()
- {
+ public ReplicableCommand getSingleModification() {
return singleModification;
}
- public Object[] getParameters()
- {
+ public Object[] getParameters() {
if (isSingleCommand())
return new Object[]{singleModification};
else
@@ -190,26 +162,20 @@
}
@SuppressWarnings("unchecked")
- public void setParameters(int commandId, Object[] args)
- {
- if (commandId == SINGLE_METHOD_ID)
- {
+ public void setParameters(int commandId, Object[] args) {
+ if (commandId == SINGLE_METHOD_ID) {
singleModification = (ReplicableCommand) args[0];
- }
- else
- {
+ } else {
modifications = (List<ReplicableCommand>) args[0];
}
}
- public boolean isSingleCommand()
- {
+ public boolean isSingleCommand() {
return singleModification != null;
}
@Override
- public boolean equals(Object o)
- {
+ public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
@@ -223,8 +189,7 @@
}
@Override
- public int hashCode()
- {
+ public int hashCode() {
int result;
result = (singleModification != null ? singleModification.hashCode() : 0);
result = 31 * result + (modifications != null ? modifications.hashCode() : 0);
@@ -232,8 +197,7 @@
}
@Override
- public String toString()
- {
+ public String toString() {
return "ReplicateCommand{" +
"cmds=" + (isSingleCommand() ? singleModification : modifications) +
'}';
@@ -244,8 +208,7 @@
*
* @return a copy
*/
- public ReplicateCommand copy()
- {
+ public ReplicateCommand copy() {
ReplicateCommand clone;
clone = new ReplicateCommand();
clone.invoker = invoker;
@@ -254,16 +217,11 @@
return clone;
}
- public boolean containsCommandType(Class<? extends ReplicableCommand> aClass)
- {
- if (isSingleCommand())
- {
+ public boolean containsCommandType(Class<? extends ReplicableCommand> aClass) {
+ if (isSingleCommand()) {
return getSingleModification().getClass().equals(aClass);
- }
- else
- {
- for (ReplicableCommand command : getModifications())
- {
+ } else {
+ for (ReplicableCommand command : getModifications()) {
if (command.getClass().equals(aClass)) return true;
}
}
Modified: core/branches/flat/src/main/java/org/horizon/commands/tx/AbstractTransactionBoundaryCommand.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/commands/tx/AbstractTransactionBoundaryCommand.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/commands/tx/AbstractTransactionBoundaryCommand.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -31,37 +31,30 @@
* @author Manik Surtani (<a href="mailto:manik at jboss.org">manik at jboss.org</a>)
* @since 1.0
*/
-public abstract class AbstractTransactionBoundaryCommand implements TransactionBoundaryCommand
-{
+public abstract class AbstractTransactionBoundaryCommand implements TransactionBoundaryCommand {
GlobalTransaction gtx;
- public GlobalTransaction getGlobalTransaction()
- {
+ public GlobalTransaction getGlobalTransaction() {
return gtx;
}
- public void setGlobalTransaction(GlobalTransaction gtx)
- {
+ public void setGlobalTransaction(GlobalTransaction gtx) {
this.gtx = gtx;
}
- public Object perform(InvocationContext ctx) throws Throwable
- {
+ public Object perform(InvocationContext ctx) throws Throwable {
return null;
}
- public Object[] getParameters()
- {
+ public Object[] getParameters() {
return new Object[]{gtx};
}
- public void setParameters(int commandId, Object[] args)
- {
+ public void setParameters(int commandId, Object[] args) {
gtx = (GlobalTransaction) args[0];
}
- public boolean equals(Object o)
- {
+ public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
@@ -72,8 +65,7 @@
return true;
}
- public int hashCode()
- {
+ public int hashCode() {
return (gtx != null ? gtx.hashCode() : 0);
}
}
Modified: core/branches/flat/src/main/java/org/horizon/commands/tx/CommitCommand.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/commands/tx/CommitCommand.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/commands/tx/CommitCommand.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -31,31 +31,25 @@
* @author Manik Surtani (<a href="mailto:manik at jboss.org">manik at jboss.org</a>)
* @since 1.0
*/
-public class CommitCommand extends AbstractTransactionBoundaryCommand
-{
+public class CommitCommand extends AbstractTransactionBoundaryCommand {
public static final byte METHOD_ID = 11;
- public CommitCommand(GlobalTransaction gtx)
- {
+ public CommitCommand(GlobalTransaction gtx) {
this.gtx = gtx;
}
- public CommitCommand()
- {
+ public CommitCommand() {
}
- public Object acceptVisitor(InvocationContext ctx, Visitor visitor) throws Throwable
- {
+ public Object acceptVisitor(InvocationContext ctx, Visitor visitor) throws Throwable {
return visitor.visitCommitCommand(ctx, this);
}
- public byte getCommandId()
- {
+ public byte getCommandId() {
return METHOD_ID;
}
- public String toString()
- {
+ public String toString() {
return "CommitCommand {" +
"gtx=" + gtx +
'}';
Modified: core/branches/flat/src/main/java/org/horizon/commands/tx/PrepareCommand.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/commands/tx/PrepareCommand.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/commands/tx/PrepareCommand.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -39,76 +39,63 @@
* @author Manik Surtani (<a href="mailto:manik at jboss.org">manik at jboss.org</a>)
* @since 1.0
*/
-public class PrepareCommand extends AbstractTransactionBoundaryCommand
-{
+public class PrepareCommand extends AbstractTransactionBoundaryCommand {
public static final byte METHOD_ID = 10;
protected List<DataCommand> modifications;
protected Address localAddress;
protected boolean onePhaseCommit;
- public PrepareCommand(GlobalTransaction gtx, List<DataCommand> modifications, Address localAddress, boolean onePhaseCommit)
- {
+ public PrepareCommand(GlobalTransaction gtx, List<DataCommand> modifications, Address localAddress, boolean onePhaseCommit) {
this.gtx = gtx;
this.modifications = modifications;
this.localAddress = localAddress;
this.onePhaseCommit = onePhaseCommit;
}
- public void removeModifications(Collection<VisitableCommand> modificationsToRemove)
- {
+ public void removeModifications(Collection<VisitableCommand> modificationsToRemove) {
if (modifications != null) modifications.removeAll(modificationsToRemove);
}
- public PrepareCommand()
- {
+ public PrepareCommand() {
}
- public Object acceptVisitor(InvocationContext ctx, Visitor visitor) throws Throwable
- {
+ public Object acceptVisitor(InvocationContext ctx, Visitor visitor) throws Throwable {
return visitor.visitPrepareCommand(ctx, this);
}
- public List<DataCommand> getModifications()
- {
+ public List<DataCommand> getModifications() {
return modifications;
}
- public Address getLocalAddress()
- {
+ public Address getLocalAddress() {
return localAddress;
}
- public boolean isOnePhaseCommit()
- {
+ public boolean isOnePhaseCommit() {
return onePhaseCommit;
}
- public boolean existModifications()
- {
+ public boolean existModifications() {
return modifications != null && modifications.size() > 0;
}
- public int getModificationsCount()
- {
+ public int getModificationsCount() {
return modifications != null ? modifications.size() : 0;
}
- public byte getCommandId()
- {
+ public byte getCommandId() {
return METHOD_ID;
}
@Override
- public Object[] getParameters()
- {
+ public Object[] getParameters() {
return new Object[]{gtx, modifications, localAddress, onePhaseCommit};
}
@Override
@SuppressWarnings("unchecked")
- public void setParameters(int commandId, Object[] args)
- {
+ public void setParameters(int commandId, Object[] args) {
gtx = (GlobalTransaction) args[0];
modifications = (List<DataCommand>) args[1];
localAddress = (Address) args[2];
@@ -116,8 +103,7 @@
}
@Override
- public boolean equals(Object o)
- {
+ public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
if (!super.equals(o)) return false;
@@ -132,8 +118,7 @@
}
@Override
- public int hashCode()
- {
+ public int hashCode() {
int result = super.hashCode();
result = 31 * result + (modifications != null ? modifications.hashCode() : 0);
result = 31 * result + (localAddress != null ? localAddress.hashCode() : 0);
@@ -141,8 +126,7 @@
return result;
}
- public PrepareCommand copy()
- {
+ public PrepareCommand copy() {
PrepareCommand copy = new PrepareCommand();
copy.gtx = gtx;
copy.localAddress = localAddress;
@@ -152,8 +136,7 @@
}
@Override
- public String toString()
- {
+ public String toString() {
return "PrepareCommand{" +
"globalTransaction=" + gtx +
", modifications=" + modifications +
@@ -162,12 +145,9 @@
'}';
}
- public boolean containsModificationType(Class<? extends ReplicableCommand> replicableCommandClass)
- {
- for (DataCommand mod : getModifications())
- {
- if (mod.getClass().equals(replicableCommandClass))
- {
+ public boolean containsModificationType(Class<? extends ReplicableCommand> replicableCommandClass) {
+ for (DataCommand mod : getModifications()) {
+ if (mod.getClass().equals(replicableCommandClass)) {
return true;
}
}
Modified: core/branches/flat/src/main/java/org/horizon/commands/tx/RollbackCommand.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/commands/tx/RollbackCommand.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/commands/tx/RollbackCommand.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -31,31 +31,25 @@
* @author Manik Surtani (<a href="mailto:manik at jboss.org">manik at jboss.org</a>)
* @since 1.0
*/
-public class RollbackCommand extends AbstractTransactionBoundaryCommand
-{
+public class RollbackCommand extends AbstractTransactionBoundaryCommand {
public static final byte METHOD_ID = 12;
- public RollbackCommand(GlobalTransaction globalTransaction)
- {
+ public RollbackCommand(GlobalTransaction globalTransaction) {
this.gtx = globalTransaction;
}
- public RollbackCommand()
- {
+ public RollbackCommand() {
}
- public Object acceptVisitor(InvocationContext ctx, Visitor visitor) throws Throwable
- {
+ public Object acceptVisitor(InvocationContext ctx, Visitor visitor) throws Throwable {
return visitor.visitRollbackCommand(ctx, this);
}
- public byte getCommandId()
- {
+ public byte getCommandId() {
return METHOD_ID;
}
- public String toString()
- {
+ public String toString() {
return "RollbackCommand{" +
"gtx=" + gtx +
'}';
Modified: core/branches/flat/src/main/java/org/horizon/commands/write/ClearCommand.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/commands/write/ClearCommand.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/commands/write/ClearCommand.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -30,38 +30,31 @@
* @author Mircea.Markus at jboss.com
* @since 1.0
*/
-public class ClearCommand implements VisitableCommand
-{
+public class ClearCommand implements VisitableCommand {
private static final Object[] params = new Object[0];
public static final byte METHOD_ID = 17;
- public Object acceptVisitor(InvocationContext ctx, Visitor visitor) throws Throwable
- {
+ public Object acceptVisitor(InvocationContext ctx, Visitor visitor) throws Throwable {
return visitor.visitClearCommand(ctx, this);
}
- public Object perform(InvocationContext ctx) throws Throwable
- {
- for (MVCCEntry e : ctx.getLookedUpEntries().values())
- {
+ public Object perform(InvocationContext ctx) throws Throwable {
+ for (MVCCEntry e : ctx.getLookedUpEntries().values()) {
e.setDeleted(true);
e.setValid(false);
}
return null;
}
- public Object[] getParameters()
- {
+ public Object[] getParameters() {
return params;
}
- public byte getCommandId()
- {
+ public byte getCommandId() {
return METHOD_ID;
}
- public void setParameters(int commandId, Object[] parameters)
- {
+ public void setParameters(int commandId, Object[] parameters) {
if (commandId != METHOD_ID) throw new IllegalStateException("Invalid method id");
}
}
Modified: core/branches/flat/src/main/java/org/horizon/commands/write/EvictCommand.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/commands/write/EvictCommand.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/commands/write/EvictCommand.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -31,35 +31,29 @@
* @author Mircea.Markus at jboss.com
* @since 1.0
*/
-public class EvictCommand extends AbstractDataCommand
-{
+public class EvictCommand extends AbstractDataCommand {
public static final byte METHOD_ID = 120;
private Notifier notifier;
- public EvictCommand(Object key)
- {
+ public EvictCommand(Object key) {
this.key = key;
}
- public void initialize(Notifier notifier)
- {
+ public void initialize(Notifier notifier) {
this.notifier = notifier;
}
- public Object acceptVisitor(InvocationContext ctx, Visitor visitor) throws Throwable
- {
+ public Object acceptVisitor(InvocationContext ctx, Visitor visitor) throws Throwable {
return visitor.visitEvictCommand(ctx, this);
}
- public Object perform(InvocationContext ctx) throws Throwable
- {
+ public Object perform(InvocationContext ctx) throws Throwable {
if (key == null) throw new NullPointerException("Key is null!!");
MVCCEntry e = ctx.lookupEntry(key);
- if (e != null && !e.isNullEntry())
- {
+ if (e != null && !e.isNullEntry()) {
//todo - add a actual eviction from thr container
notifier.notifyCacheEntryEvicted(key, true, ctx);
e.setDeleted(true);
@@ -69,8 +63,7 @@
return null;
}
- public byte getCommandId()
- {
+ public byte getCommandId() {
return METHOD_ID;
}
}
Modified: core/branches/flat/src/main/java/org/horizon/commands/write/InvalidateCommand.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/commands/write/InvalidateCommand.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/commands/write/InvalidateCommand.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -33,14 +33,13 @@
/**
- * Removes a node's content from memory - never removes the node.
- * It also clenups data for resident nodes - which are not being touched by eviction.
+ * Removes a node's content from memory - never removes the node. It also clenups data for resident nodes - which are
+ * not being touched by eviction.
*
* @author Mircea.Markus at jboss.com
* @since 1.0
*/
-public class InvalidateCommand extends AbstractDataCommand
-{
+public class InvalidateCommand extends AbstractDataCommand {
public static final int METHOD_ID = 47;
private static final Log log = LogFactory.getLog(InvalidateCommand.class);
private static final boolean trace = log.isTraceEnabled();
@@ -50,17 +49,14 @@
protected Notifier notifier;
protected DataContainer dataContainer;
- public InvalidateCommand(Object key)
- {
+ public InvalidateCommand(Object key) {
this.key = key;
}
- public InvalidateCommand()
- {
+ public InvalidateCommand() {
}
- public void initialize(CacheSPI cacheSpi, DataContainer dataContainer, Notifier notifier)
- {
+ public void initialize(CacheSPI cacheSpi, DataContainer dataContainer, Notifier notifier) {
this.spi = cacheSpi;
this.dataContainer = dataContainer;
this.notifier = notifier;
@@ -72,12 +68,10 @@
* @param ctx invocation context
* @return null
*/
- public Object perform(InvocationContext ctx)
- {
+ public Object perform(InvocationContext ctx) {
Object value = enforceNodeLoading();
if (trace) log.trace("Invalidating key:" + key);
- if (value == null)
- {
+ if (value == null) {
return null;
}
evictNode(key, ctx);
@@ -85,33 +79,30 @@
return null;
}
- boolean evictNode(Object key, InvocationContext ctx)
- {
+ boolean evictNode(Object key, InvocationContext ctx) {
notifier.notifyNodeInvalidated(key, true, ctx);
- try
- {
+ try {
return dataContainer.evict(key);
}
- finally
- {
+ finally {
notifier.notifyNodeInvalidated(key, false, ctx);
}
}
/**
- * //TODO: 2.2.0: rather than using CacheSPI this should use peek(). The other interceptors should obtain locks and load nodes if necessary for this InvalidateCommand.
- * //Even better - this can be handles in the interceptors before call interceptor
+ * //TODO: 2.2.0: rather than using CacheSPI this should use peek(). The other interceptors should obtain locks and
+ * load nodes if necessary for this InvalidateCommand. //Even better - this can be handles in the interceptors before
+ * call interceptor
*/
- protected Object enforceNodeLoading()
- {
+ protected Object enforceNodeLoading() {
return spi.get(key);
}
/**
- * mark the node to be removed (and all children) as invalid so anyone holding a direct reference to it will
- * be aware that it is no longer valid.
+ * mark the node to be removed (and all children) as invalid so anyone holding a direct reference to it will be aware
+ * that it is no longer valid.
*/
protected void invalidateNode()//NodeSPI node)
{
@@ -123,38 +114,32 @@
}
- public Object acceptVisitor(InvocationContext ctx, Visitor visitor) throws Throwable
- {
+ public Object acceptVisitor(InvocationContext ctx, Visitor visitor) throws Throwable {
return visitor.visitInvalidateCommand(ctx, this);
}
- public byte getCommandId()
- {
+ public byte getCommandId() {
return METHOD_ID;
}
@Override
- public String toString()
- {
+ public String toString() {
return "InvalidateCommand{" +
"key=" + key +
'}';
}
@Override
- public Object[] getParameters()
- {
+ public Object[] getParameters() {
return new Object[]{key};
}
@Override
- public void setParameters(int commandId, Object[] args)
- {
+ public void setParameters(int commandId, Object[] args) {
key = args[0];
}
- void setFqn(Fqn newFqn)
- {
+ void setFqn(Fqn newFqn) {
this.key = newFqn;
}
}
\ No newline at end of file
Modified: core/branches/flat/src/main/java/org/horizon/commands/write/PutKeyValueCommand.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/commands/write/PutKeyValueCommand.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/commands/write/PutKeyValueCommand.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -30,61 +30,51 @@
import org.horizon.notifications.Notifier;
/**
- * Implements functionality defined by {@link org.horizon.Cache#put(Object, Object)}
+ * Implements functionality defined by {@link org.horizon.Cache#put(Object, Object)}
*
* @author Mircea.Markus at jboss.com
* @since 1.0
*/
-public class PutKeyValueCommand extends AbstractDataCommand
-{
+public class PutKeyValueCommand extends AbstractDataCommand {
public static final byte METHOD_ID = 3;
protected Object value;
protected boolean putIfAbsent;
private Notifier notifier;
- public PutKeyValueCommand(Object key, Object value, boolean putIfAbsent, Notifier notifier)
- {
+ public PutKeyValueCommand(Object key, Object value, boolean putIfAbsent, Notifier notifier) {
super(key);
this.value = value;
this.putIfAbsent = putIfAbsent;
this.notifier = notifier;
}
- public void init(Notifier notifier)
- {
+ public void init(Notifier notifier) {
this.notifier = notifier;
}
- public PutKeyValueCommand()
- {
+ public PutKeyValueCommand() {
}
- public Object getValue()
- {
+ public Object getValue() {
return value;
}
- public void setValue(Object value)
- {
+ public void setValue(Object value) {
this.value = value;
}
- public Object acceptVisitor(InvocationContext ctx, Visitor visitor) throws Throwable
- {
+ public Object acceptVisitor(InvocationContext ctx, Visitor visitor) throws Throwable {
return visitor.visitPutKeyValueCommand(ctx, this);
}
- public Object perform(InvocationContext ctx) throws Throwable
- {
+ public Object perform(InvocationContext ctx) throws Throwable {
Object o = null;
MVCCEntry e = ctx.lookupEntry(key);
- if (e.getValue() == null || !putIfAbsent)
- {
+ if (e.getValue() == null || !putIfAbsent) {
notifier.notifyCacheEntryModified(key, true, ctx);
- if (value instanceof Delta)
- {
+ if (value instanceof Delta) {
// magic
Delta dv = (Delta) value;
Object existing = e.getValue();
@@ -92,9 +82,7 @@
if (existing instanceof DeltaAware) toMergeWith = (DeltaAware) existing;
e.setValue(dv.merge(toMergeWith));
o = existing;
- }
- else
- {
+ } else {
o = e.setValue(value);
}
notifier.notifyCacheEntryModified(key, false, ctx);
@@ -102,35 +90,29 @@
return o;
}
- public byte getCommandId()
- {
+ public byte getCommandId() {
return METHOD_ID;
}
- public Object[] getParameters()
- {
+ public Object[] getParameters() {
return new Object[]{key, value};
}
- public void setParameters(int commandId, Object[] parameters)
- {
+ public void setParameters(int commandId, Object[] parameters) {
if (commandId != METHOD_ID) throw new IllegalStateException("Invalid method id");
key = parameters[0];
value = parameters[1];
}
- public boolean isPutIfAbsent()
- {
+ public boolean isPutIfAbsent() {
return putIfAbsent;
}
- public void setPutIfAbsent(boolean putIfAbsent)
- {
+ public void setPutIfAbsent(boolean putIfAbsent) {
this.putIfAbsent = putIfAbsent;
}
- public boolean equals(Object o)
- {
+ public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof PutKeyValueCommand)) return false;
if (!super.equals(o)) return false;
@@ -143,8 +125,7 @@
return true;
}
- public int hashCode()
- {
+ public int hashCode() {
int result = super.hashCode();
result = 31 * result + (value != null ? value.hashCode() : 0);
result = 31 * result + (putIfAbsent ? 1 : 0);
@@ -152,8 +133,7 @@
}
- public String toString()
- {
+ public String toString() {
return "PutKeyValueCommand{" +
"key= " + key +
", value=" + value +
Modified: core/branches/flat/src/main/java/org/horizon/commands/write/PutMapCommand.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/commands/write/PutMapCommand.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/commands/write/PutMapCommand.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -34,37 +34,30 @@
* @author Mircea.Markus at jboss.com
* @since 1.0
*/
-public class PutMapCommand implements VisitableCommand
-{
+public class PutMapCommand implements VisitableCommand {
public static final byte METHOD_ID = 121;
private Map<Object, Object> map;
private Notifier notifier;
- public PutMapCommand(Map map, Notifier notifier)
- {
+ public PutMapCommand(Map map, Notifier notifier) {
this.map = map;
this.notifier = notifier;
}
- public void init(Notifier notifier)
- {
+ public void init(Notifier notifier) {
this.notifier = notifier;
}
- public PutMapCommand()
- {
+ public PutMapCommand() {
}
- public Object acceptVisitor(InvocationContext ctx, Visitor visitor) throws Throwable
- {
+ public Object acceptVisitor(InvocationContext ctx, Visitor visitor) throws Throwable {
return visitor.visitPutMapCommand(ctx, this);
}
- public Object perform(InvocationContext ctx) throws Throwable
- {
- for (Entry<Object, Object> e : map.entrySet())
- {
+ public Object perform(InvocationContext ctx) throws Throwable {
+ for (Entry<Object, Object> e : map.entrySet()) {
Object key = e.getKey();
MVCCEntry me = ctx.lookupEntry(key);
notifier.notifyCacheEntryModified(key, true, ctx);
@@ -74,34 +67,28 @@
return null;
}
- public Map<Object, Object> getMap()
- {
+ public Map<Object, Object> getMap() {
return map;
}
- public void setMap(Map<Object, Object> map)
- {
+ public void setMap(Map<Object, Object> map) {
this.map = map;
}
- public byte getCommandId()
- {
+ public byte getCommandId() {
return METHOD_ID;
}
- public Object[] getParameters()
- {
+ public Object[] getParameters() {
return new Object[]{map};
}
- public void setParameters(int commandId, Object[] parameters)
- {
+ public void setParameters(int commandId, Object[] parameters) {
if (commandId != METHOD_ID) throw new IllegalStateException("Invalid method id");
map = (Map) parameters[0];
}
- public boolean equals(Object o)
- {
+ public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof PutMapCommand)) return false;
@@ -112,14 +99,12 @@
return true;
}
- public int hashCode()
- {
+ public int hashCode() {
return (map != null ? map.hashCode() : 0);
}
- public String toString()
- {
+ public String toString() {
return "PutMapCommand{" +
"map=" + map +
'}';
Modified: core/branches/flat/src/main/java/org/horizon/commands/write/RemoveCommand.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/commands/write/RemoveCommand.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/commands/write/RemoveCommand.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -32,36 +32,30 @@
* @author Mircea.Markus at jboss.com
* @since 1.0
*/
-public class RemoveCommand extends AbstractDataCommand
-{
+public class RemoveCommand extends AbstractDataCommand {
public static final byte METHOD_ID = 6;
private Notifier notifier;
protected Object value;
- public RemoveCommand(Object key, Object value, Notifier notifier)
- {
+ public RemoveCommand(Object key, Object value, Notifier notifier) {
super(key);
this.value = value;
this.notifier = notifier;
}
- public void init(Notifier notifier)
- {
+ public void init(Notifier notifier) {
this.notifier = notifier;
}
- public RemoveCommand()
- {
+ public RemoveCommand() {
}
- public Object acceptVisitor(InvocationContext ctx, Visitor visitor) throws Throwable
- {
+ public Object acceptVisitor(InvocationContext ctx, Visitor visitor) throws Throwable {
return visitor.visitRemoveCommand(ctx, this);
}
- public Object perform(InvocationContext ctx) throws Throwable
- {
+ public Object perform(InvocationContext ctx) throws Throwable {
MVCCEntry e = ctx.lookupEntry(key);
if (e == null || e.isNullEntry()) return null;
notifier.notifyCacheEntryRemoved(key, true, ctx);
@@ -72,13 +66,11 @@
}
- public byte getCommandId()
- {
+ public byte getCommandId() {
return METHOD_ID;
}
- public boolean equals(Object o)
- {
+ public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof RemoveCommand)) return false;
if (!super.equals(o)) return false;
@@ -90,16 +82,14 @@
return true;
}
- public int hashCode()
- {
+ public int hashCode() {
int result = super.hashCode();
result = 31 * result + (value != null ? value.hashCode() : 0);
return result;
}
- public String toString()
- {
+ public String toString() {
return "RemoveCommand{" +
"key=" + key +
", value=" + value +
Modified: core/branches/flat/src/main/java/org/horizon/commands/write/ReplaceCommand.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/commands/write/ReplaceCommand.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/commands/write/ReplaceCommand.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -31,61 +31,51 @@
* @author Mircea.Markus at jboss.com
* @since 1.0
*/
-public class ReplaceCommand extends AbstractDataCommand
-{
+public class ReplaceCommand extends AbstractDataCommand {
public static final byte METHOD_ID = 122;
protected Object oldValue;
protected Object newValue;
- public ReplaceCommand(Object key, Object oldValue, Object newValue)
- {
+ public ReplaceCommand(Object key, Object oldValue, Object newValue) {
super(key);
this.oldValue = oldValue;
this.newValue = newValue;
}
- public ReplaceCommand()
- {
+ public ReplaceCommand() {
}
- public Object acceptVisitor(InvocationContext ctx, Visitor visitor) throws Throwable
- {
+ public Object acceptVisitor(InvocationContext ctx, Visitor visitor) throws Throwable {
return visitor.visitReplaceCommand(ctx, this);
}
- public Boolean perform(InvocationContext ctx) throws Throwable
- {
+ public Boolean perform(InvocationContext ctx) throws Throwable {
MVCCEntry e = ctx.lookupEntry(key);
if (e == null || e.isNullEntry()) return false;
- if (oldValue == null || oldValue.equals(e.getValue()))
- {
+ if (oldValue == null || oldValue.equals(e.getValue())) {
e.setValue(newValue);
return true;
}
return false;
}
- public byte getCommandId()
- {
+ public byte getCommandId() {
return METHOD_ID;
}
- public Object[] getParameters()
- {
+ public Object[] getParameters() {
return new Object[]{key, oldValue, newValue};
}
- public void setParameters(int commandId, Object[] parameters)
- {
+ public void setParameters(int commandId, Object[] parameters) {
if (commandId != METHOD_ID) throw new IllegalArgumentException("Invalid method name");
key = parameters[0];
oldValue = parameters[1];
newValue = parameters[2];
}
- public boolean equals(Object o)
- {
+ public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof ReplaceCommand)) return false;
if (!super.equals(o)) return false;
@@ -98,16 +88,14 @@
return true;
}
- public int hashCode()
- {
+ public int hashCode() {
int result = super.hashCode();
result = 31 * result + (oldValue != null ? oldValue.hashCode() : 0);
result = 31 * result + (newValue != null ? newValue.hashCode() : 0);
return result;
}
- public String toString()
- {
+ public String toString() {
return "ReplaceCommand{" +
"key=" + key +
", oldValue=" + oldValue +
Modified: core/branches/flat/src/main/java/org/horizon/config/CacheLoaderConfig.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/config/CacheLoaderConfig.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/config/CacheLoaderConfig.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -22,8 +22,8 @@
package org.horizon.config;
import org.horizon.loader.CacheLoader;
-import org.horizon.util.Util;
import org.horizon.loader.SingletonStoreCacheLoader;
+import org.horizon.util.Util;
import java.util.ArrayList;
import java.util.List;
@@ -38,8 +38,7 @@
* @author <a href="mailto:galder.zamarreno at jboss.com">Galder Zamarreno</a>
* @since 1.0
*/
-public class CacheLoaderConfig extends ConfigurationComponent
-{
+public class CacheLoaderConfig extends ConfigurationComponent {
private static final long serialVersionUID = 2210349340378984424L;
private boolean passivation;
@@ -48,85 +47,71 @@
private boolean shared;
- public String getPreload()
- {
+ public String getPreload() {
return preload;
}
- public void setPreload(String preload)
- {
+ public void setPreload(String preload) {
testImmutability("preload");
this.preload = preload;
}
- public void setPassivation(boolean passivation)
- {
+ public void setPassivation(boolean passivation) {
testImmutability("passivation");
this.passivation = passivation;
}
- public boolean isPassivation()
- {
+ public boolean isPassivation() {
return passivation;
}
- public void addIndividualCacheLoaderConfig(IndividualCacheLoaderConfig clc)
- {
+ public void addIndividualCacheLoaderConfig(IndividualCacheLoaderConfig clc) {
testImmutability("cacheLoaderConfigs");
cacheLoaderConfigs.add(clc);
// Ensure this config gets our back ref to the cache
addChildConfig(clc);
}
- public List<IndividualCacheLoaderConfig> getIndividualCacheLoaderConfigs()
- {
+ public List<IndividualCacheLoaderConfig> getIndividualCacheLoaderConfigs() {
return cacheLoaderConfigs;
}
- public void setIndividualCacheLoaderConfigs(List<IndividualCacheLoaderConfig> configs)
- {
+ public void setIndividualCacheLoaderConfigs(List<IndividualCacheLoaderConfig> configs) {
testImmutability("cacheLoaderConfigs");
// Ensure these configs get our back ref to the cache
replaceChildConfigs(this.cacheLoaderConfigs, configs);
this.cacheLoaderConfigs = configs == null ? new ArrayList<IndividualCacheLoaderConfig>() : configs;
}
- public IndividualCacheLoaderConfig getFirstCacheLoaderConfig()
- {
+ public IndividualCacheLoaderConfig getFirstCacheLoaderConfig() {
if (cacheLoaderConfigs.size() == 0) return null;
return cacheLoaderConfigs.get(0);
}
- public boolean useChainingCacheLoader()
- {
+ public boolean useChainingCacheLoader() {
return !isPassivation() && cacheLoaderConfigs.size() > 1;
}
@Override
- public String toString()
- {
+ public String toString() {
return new StringBuilder().append("CacheLoaderConfig{").append("shared=").append(shared).append(", passivation=").append(passivation).append(", preload='").append(preload).append('\'').append(", cacheLoaderConfigs.size()=").append(cacheLoaderConfigs.size()).append('}').toString();
}
- public void setShared(boolean shared)
- {
+ public void setShared(boolean shared) {
testImmutability("shared");
this.shared = shared;
}
- public boolean isShared()
- {
+ public boolean isShared() {
return shared;
}
@Override
- public boolean equals(Object obj)
- {
+ public boolean equals(Object obj) {
if (this == obj)
return true;
- if (obj instanceof CacheLoaderConfig)
- {
+ if (obj instanceof CacheLoaderConfig) {
CacheLoaderConfig other = (CacheLoaderConfig) obj;
return (this.passivation == other.passivation)
&& (this.shared == other.shared)
@@ -137,8 +122,7 @@
}
@Override
- public int hashCode()
- {
+ public int hashCode() {
int result = 19;
result = 51 * result + (passivation ? 0 : 1);
result = 51 * result + (shared ? 0 : 1);
@@ -149,14 +133,11 @@
@Override
- public CacheLoaderConfig clone() throws CloneNotSupportedException
- {
+ public CacheLoaderConfig clone() throws CloneNotSupportedException {
CacheLoaderConfig clone = (CacheLoaderConfig) super.clone();
- if (cacheLoaderConfigs != null)
- {
+ if (cacheLoaderConfigs != null) {
List<IndividualCacheLoaderConfig> clcs = new ArrayList<IndividualCacheLoaderConfig>(cacheLoaderConfigs.size());
- for (IndividualCacheLoaderConfig clc : cacheLoaderConfigs)
- {
+ for (IndividualCacheLoaderConfig clc : cacheLoaderConfigs) {
clcs.add(clc.clone());
}
clone.setIndividualCacheLoaderConfigs(clcs);
@@ -167,10 +148,8 @@
/**
* Loops through all individual cache loader configs and checks if fetchPersistentState is set on any of them
*/
- public boolean isFetchPersistentState()
- {
- for (IndividualCacheLoaderConfig iclc : cacheLoaderConfigs)
- {
+ public boolean isFetchPersistentState() {
+ for (IndividualCacheLoaderConfig iclc : cacheLoaderConfigs) {
if (iclc.isFetchPersistentState()) return true;
}
return false;
@@ -183,8 +162,7 @@
* @author <a href="mailto:manik at jboss.org">Manik Surtani (manik at jboss.org)</a>
* @author <a href="mailto:galder.zamarreno at jboss.com">Galder Zamarreno</a>
*/
- public static class IndividualCacheLoaderConfig extends PluggableConfigurationComponent
- {
+ public static class IndividualCacheLoaderConfig extends PluggableConfigurationComponent {
private static final long serialVersionUID = -2282396799100828593L;
private boolean async;
@@ -196,10 +174,8 @@
private SingletonStoreConfig singletonStoreConfig;
private transient CacheLoader<Object, Object> cacheLoader;
- protected void populateFromBaseConfig(IndividualCacheLoaderConfig base)
- {
- if (base != null)
- {
+ protected void populateFromBaseConfig(IndividualCacheLoaderConfig base) {
+ if (base != null) {
setAsync(base.isAsync());
setIgnoreModifications(base.isIgnoreModifications());
setFetchPersistentState(base.isFetchPersistentState());
@@ -209,57 +185,47 @@
}
}
- public boolean isPurgeOnStartup()
- {
+ public boolean isPurgeOnStartup() {
return purgeOnStartup;
}
- public boolean isFetchPersistentState()
- {
+ public boolean isFetchPersistentState() {
return fetchPersistentState;
}
- public void setFetchPersistentState(boolean fetchPersistentState)
- {
+ public void setFetchPersistentState(boolean fetchPersistentState) {
testImmutability("fetchPersistentState");
this.fetchPersistentState = fetchPersistentState;
}
- public void setAsync(boolean async)
- {
+ public void setAsync(boolean async) {
testImmutability("async");
this.async = async;
}
- public boolean isAsync()
- {
+ public boolean isAsync() {
return async;
}
- public void setIgnoreModifications(boolean ignoreModifications)
- {
+ public void setIgnoreModifications(boolean ignoreModifications) {
testImmutability("ignoreModifications");
this.ignoreModifications = ignoreModifications;
}
- public boolean isIgnoreModifications()
- {
+ public boolean isIgnoreModifications() {
return ignoreModifications;
}
- public void setPurgeOnStartup(boolean purgeOnStartup)
- {
+ public void setPurgeOnStartup(boolean purgeOnStartup) {
testImmutability("purgeOnStartup");
this.purgeOnStartup = purgeOnStartup;
}
- public SingletonStoreConfig getSingletonStoreConfig()
- {
+ public SingletonStoreConfig getSingletonStoreConfig() {
return singletonStoreConfig;
}
- public void setSingletonStoreConfig(SingletonStoreConfig singletonStoreConfig)
- {
+ public void setSingletonStoreConfig(SingletonStoreConfig singletonStoreConfig) {
testImmutability("singletonStoreConfig");
replaceChildConfig(this.singletonStoreConfig, singletonStoreConfig);
this.singletonStoreConfig = singletonStoreConfig;
@@ -272,8 +238,7 @@
* @return cache loader, if one exists
* @since 1.0
*/
- public CacheLoader<Object,Object> getCacheLoader()
- {
+ public CacheLoader<Object, Object> getCacheLoader() {
return cacheLoader;
}
@@ -284,24 +249,20 @@
* @param cacheLoader cacheLoader to set
* @since 1.0
*/
- public void setCacheLoader(CacheLoader<Object,Object> cacheLoader)
- {
+ public void setCacheLoader(CacheLoader<Object, Object> cacheLoader) {
this.cacheLoader = cacheLoader;
}
@Override
- public boolean equals(Object obj)
- {
- if (super.equals(obj))
- {
+ public boolean equals(Object obj) {
+ if (super.equals(obj)) {
IndividualCacheLoaderConfig i = (IndividualCacheLoaderConfig) obj;
return equalsExcludingProperties(i);
}
return false;
}
- protected boolean equalsExcludingProperties(Object obj)
- {
+ protected boolean equalsExcludingProperties(Object obj) {
if (!(obj instanceof IndividualCacheLoaderConfig))
return false;
IndividualCacheLoaderConfig other = (IndividualCacheLoaderConfig) obj;
@@ -315,13 +276,11 @@
}
@Override
- public int hashCode()
- {
+ public int hashCode() {
return 31 * hashCodeExcludingProperties() + (properties == null ? 0 : properties.hashCode());
}
- protected int hashCodeExcludingProperties()
- {
+ protected int hashCodeExcludingProperties() {
int result = 17;
result = 31 * result + (className == null ? 0 : className.hashCode());
result = 31 * result + (async ? 0 : 1);
@@ -333,8 +292,7 @@
}
@Override
- public String toString()
- {
+ public String toString() {
return new StringBuilder().append("IndividualCacheLoaderConfig{").append("className='").append(className).append('\'')
.append(", async=").append(async)
.append(", ignoreModifications=").append(ignoreModifications)
@@ -346,8 +304,7 @@
}
@Override
- public IndividualCacheLoaderConfig clone() throws CloneNotSupportedException
- {
+ public IndividualCacheLoaderConfig clone() throws CloneNotSupportedException {
IndividualCacheLoaderConfig clone = (IndividualCacheLoaderConfig) super.clone();
if (singletonStoreConfig != null)
clone.setSingletonStoreConfig(singletonStoreConfig.clone());
@@ -358,8 +315,7 @@
/**
* Configuration for a SingletonStoreCacheLoader
*/
- public static class SingletonStoreConfig extends PluggableConfigurationComponent
- {
+ public static class SingletonStoreConfig extends PluggableConfigurationComponent {
private static final long serialVersionUID = 824251894176131850L;
/**
@@ -367,51 +323,42 @@
*/
private boolean singletonStoreEnabled;
- public SingletonStoreConfig()
- {
+ public SingletonStoreConfig() {
// default value
className = SingletonStoreCacheLoader.class.getName();
}
- public boolean isSingletonStoreEnabled()
- {
+ public boolean isSingletonStoreEnabled() {
return singletonStoreEnabled;
}
- public void setSingletonStoreEnabled(boolean singletonStoreEnabled)
- {
+ public void setSingletonStoreEnabled(boolean singletonStoreEnabled) {
testImmutability("singletonStoreEnabled");
this.singletonStoreEnabled = singletonStoreEnabled;
}
- public String getSingletonStoreClass()
- {
+ public String getSingletonStoreClass() {
return className;
}
- public void setSingletonStoreClass(String className)
- {
+ public void setSingletonStoreClass(String className) {
setClassName(className);
}
- public Properties getSingletonStoreproperties()
- {
+ public Properties getSingletonStoreproperties() {
return properties;
}
- public void setSingletonStoreproperties(Properties properties)
- {
+ public void setSingletonStoreproperties(Properties properties) {
setProperties(properties);
}
@Override
- public boolean equals(Object obj)
- {
+ public boolean equals(Object obj) {
if (this == obj)
return true;
- if (super.equals(obj))
- {
+ if (super.equals(obj)) {
SingletonStoreConfig other = (SingletonStoreConfig) obj;
return this.singletonStoreEnabled == other.singletonStoreEnabled;
}
@@ -419,8 +366,7 @@
}
@Override
- public int hashCode()
- {
+ public int hashCode() {
int result = 19;
result = 41 * result + super.hashCode();
result = 41 * result + (singletonStoreEnabled ? 0 : 1);
@@ -428,16 +374,14 @@
}
@Override
- public String toString()
- {
+ public String toString() {
return super.toString() + " enabled=" + singletonStoreEnabled +
" class=" + className +
" properties=" + properties;
}
@Override
- public SingletonStoreConfig clone() throws CloneNotSupportedException
- {
+ public SingletonStoreConfig clone() throws CloneNotSupportedException {
return (SingletonStoreConfig) super.clone();
}
}
Modified: core/branches/flat/src/main/java/org/horizon/config/CloneableConfigurationComponent.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/config/CloneableConfigurationComponent.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/config/CloneableConfigurationComponent.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -29,7 +29,6 @@
* @author Manik Surtani (<a href="mailto:manik at jboss.org">manik at jboss.org</a>)
* @since 1.0
*/
-public interface CloneableConfigurationComponent extends Serializable, Cloneable
-{
+public interface CloneableConfigurationComponent extends Serializable, Cloneable {
CloneableConfigurationComponent clone() throws CloneNotSupportedException;
}
Modified: core/branches/flat/src/main/java/org/horizon/config/Configuration.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/config/Configuration.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/config/Configuration.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -45,8 +45,7 @@
* @since 1.0
*/
@NonVolatile
-public class Configuration extends ConfigurationComponent
-{
+public class Configuration extends ConfigurationComponent {
private static final long serialVersionUID = 5553791890144997466L;
private Marshaller marshaller;
@@ -56,21 +55,18 @@
private Map<String, EvictionCacheConfig> evictionCacheConfigs = new HashMap<String, EvictionCacheConfig>(4);
- public EvictionCacheConfig getEvictionCacheConfig(String cacheName)
- {
+ public EvictionCacheConfig getEvictionCacheConfig(String cacheName) {
return evictionCacheConfigs.values().iterator().next();
}
- public void addEvictionCacheConfig(String cacheName, EvictionCacheConfig ecc)
- {
+ public void addEvictionCacheConfig(String cacheName, EvictionCacheConfig ecc) {
evictionCacheConfigs.put(cacheName, ecc);
}
/**
* Behavior of the JVM shutdown hook registered by the cache
*/
- public static enum ShutdownHookBehavior
- {
+ public static enum ShutdownHookBehavior {
/**
* By default a shutdown hook is registered if no MBean server (apart from the JDK default) is detected.
*/
@@ -88,8 +84,7 @@
/**
* Cache replication mode.
*/
- public static enum CacheMode
- {
+ public static enum CacheMode {
/**
* Data is not replicated.
*/
@@ -118,22 +113,18 @@
/**
* Returns true if the mode is invalidation, either sync or async.
*/
- public boolean isInvalidation()
- {
+ public boolean isInvalidation() {
return this == INVALIDATION_SYNC || this == INVALIDATION_ASYNC;
}
- public boolean isSynchronous()
- {
+ public boolean isSynchronous() {
return this == REPL_SYNC || this == INVALIDATION_SYNC || this == LOCAL;
}
}
- public static CacheMode legacyModeToCacheMode(int legacyMode)
- {
- switch (legacyMode)
- {
+ public static CacheMode legacyModeToCacheMode(int legacyMode) {
+ switch (legacyMode) {
case 1:
return CacheMode.LOCAL;
case 2:
@@ -212,11 +203,9 @@
private URL jgroupsConfigFile;
@Start(priority = 1)
- private void correctIsolationLevels()
- {
+ private void correctIsolationLevels() {
// ensure the correct isolation level upgrades and/or downgrades are performed.
- switch (isolationLevel)
- {
+ switch (isolationLevel) {
case NONE:
case READ_UNCOMMITTED:
isolationLevel = IsolationLevel.READ_COMMITTED;
@@ -231,35 +220,29 @@
// SETTERS - MAKE SURE ALL SETTERS PERFORM testImmutability()!!!
// ------------------------------------------------------------------------------------------------------------
- public void setCacheMarshaller(Marshaller instance)
- {
+ public void setCacheMarshaller(Marshaller instance) {
testImmutability("marshaller");
marshaller = instance;
}
- public Marshaller getMarshaller()
- {
+ public Marshaller getMarshaller() {
return marshaller;
}
- public boolean isWriteSkewCheck()
- {
+ public boolean isWriteSkewCheck() {
return writeSkewCheck;
}
- public void setWriteSkewCheck(boolean writeSkewCheck)
- {
+ public void setWriteSkewCheck(boolean writeSkewCheck) {
testImmutability("writeSkewCheck");
this.writeSkewCheck = writeSkewCheck;
}
- public int getConcurrencyLevel()
- {
+ public int getConcurrencyLevel() {
return concurrencyLevel;
}
- public void setConcurrencyLevel(int concurrencyLevel)
- {
+ public void setConcurrencyLevel(int concurrencyLevel) {
testImmutability("concurrencyLevel");
this.concurrencyLevel = concurrencyLevel;
}
@@ -267,37 +250,31 @@
/**
* Converts a list of elements to a Java Groups property string.
*/
- public void setClusterConfig(Element config)
- {
+ public void setClusterConfig(Element config) {
setClusterConfig(jGroupsStackParser.parseClusterConfigXml(config));
}
- public void setClusterName(String clusterName)
- {
+ public void setClusterName(String clusterName) {
testImmutability("clusterName");
this.clusterName = clusterName;
}
- public void setClusterConfig(String clusterConfig)
- {
+ public void setClusterConfig(String clusterConfig) {
testImmutability("clusterConfig");
this.clusterConfig = clusterConfig;
}
- public void setReplQueueMaxElements(int replQueueMaxElements)
- {
+ public void setReplQueueMaxElements(int replQueueMaxElements) {
testImmutability("replQueueMaxElements");
this.replQueueMaxElements = replQueueMaxElements;
}
- public void setReplQueueInterval(long replQueueInterval)
- {
+ public void setReplQueueInterval(long replQueueInterval) {
testImmutability("replQueueInterval");
this.replQueueInterval = replQueueInterval;
}
- public void setExposeManagementStatistics(boolean useMbean)
- {
+ public void setExposeManagementStatistics(boolean useMbean) {
testImmutability("exposeManagementStatistics");
this.exposeManagementStatistics = useMbean;
}
@@ -309,121 +286,102 @@
* @param enabled if true, batching is enabled.
* @since 1.0
*/
- public void setInvocationBatchingEnabled(boolean enabled)
- {
+ public void setInvocationBatchingEnabled(boolean enabled) {
testImmutability("invocationBatchingEnabled");
this.invocationBatchingEnabled = enabled;
}
- public void setFetchInMemoryState(boolean fetchInMemoryState)
- {
+ public void setFetchInMemoryState(boolean fetchInMemoryState) {
testImmutability("fetchInMemoryState");
this.fetchInMemoryState = fetchInMemoryState;
}
- public void setReplicationVersion(short replicationVersion)
- {
+ public void setReplicationVersion(short replicationVersion) {
testImmutability("replicationVersion");
this.replicationVersion = replicationVersion;
}
- public void setReplVersionString(String replVersionString)
- {
+ public void setReplVersionString(String replVersionString) {
setReplicationVersion(replVersionString == null ? 0 : Version.getVersionShort(replVersionString));
}
- public void setLockAcquisitionTimeout(long lockAcquisitionTimeout)
- {
+ public void setLockAcquisitionTimeout(long lockAcquisitionTimeout) {
testImmutability("lockAcquisitionTimeout");
this.lockAcquisitionTimeout = lockAcquisitionTimeout;
}
- public void setSyncReplTimeout(long syncReplTimeout)
- {
+ public void setSyncReplTimeout(long syncReplTimeout) {
testImmutability("syncReplTimeout");
this.syncReplTimeout = syncReplTimeout;
}
- public void setCacheMode(CacheMode cacheModeInt)
- {
+ public void setCacheMode(CacheMode cacheModeInt) {
testImmutability("cacheMode");
this.cacheMode = cacheModeInt;
}
- public void setCacheMode(String cacheMode)
- {
+ public void setCacheMode(String cacheMode) {
testImmutability("cacheMode");
if (cacheMode == null) throw new ConfigurationException("Cache mode cannot be null", "CacheMode");
this.cacheMode = CacheMode.valueOf(uc(cacheMode));
- if (this.cacheMode == null)
- {
+ if (this.cacheMode == null) {
log.warn("Unknown cache mode '" + cacheMode + "', using defaults.");
this.cacheMode = CacheMode.LOCAL;
}
}
- public String getCacheModeString()
- {
+ public String getCacheModeString() {
return cacheMode == null ? null : cacheMode.toString();
}
- public void setCacheModeString(String cacheMode)
- {
+ public void setCacheModeString(String cacheMode) {
setCacheMode(cacheMode);
}
- public void setInactiveOnStartup(boolean inactiveOnStartup)
- {
+ public void setInactiveOnStartup(boolean inactiveOnStartup) {
testImmutability("inactiveOnStartup");
this.inactiveOnStartup = inactiveOnStartup;
}
- public EvictionConfig getEvictionConfig()
- {
+ public EvictionConfig getEvictionConfig() {
return evictionConfig;
}
- public void setEvictionConfig(EvictionConfig config)
- {
+ public void setEvictionConfig(EvictionConfig config) {
testImmutability("evictionConfig");
this.evictionConfig = config;
}
/**
- * This is a deprecated configuration option. While it will be supported for the 2.x series for backward compatibility,
- * expect to see it disappear in 3.x.
+ * This is a deprecated configuration option. While it will be supported for the 2.x series for backward
+ * compatibility, expect to see it disappear in 3.x.
* <p/>
- * With {@link #isUseLazyDeserialization()}, which is enabled by default, custom class loaders are handled implicitly.
- * See the user guide for details on how this is handled.
+ * With {@link #isUseLazyDeserialization()}, which is enabled by default, custom class loaders are handled
+ * implicitly. See the user guide for details on how this is handled.
* <p/>
*/
- public void setUseRegionBasedMarshalling(boolean useRegionBasedMarshalling)
- {
+ public void setUseRegionBasedMarshalling(boolean useRegionBasedMarshalling) {
testImmutability("useRegionBasedMarshalling");
this.useRegionBasedMarshalling = useRegionBasedMarshalling;
}
- public void setTransactionManagerLookupClass(String transactionManagerLookupClass)
- {
+ public void setTransactionManagerLookupClass(String transactionManagerLookupClass) {
testImmutability("transactionManagerLookupClass");
this.transactionManagerLookupClass = transactionManagerLookupClass;
}
- public void setCacheLoaderConfig(CacheLoaderConfig config)
- {
+ public void setCacheLoaderConfig(CacheLoaderConfig config) {
testImmutability("cacheLoaderConfig");
replaceChildConfig(this.cacheLoaderConfig, config);
this.cacheLoaderConfig = config;
}
- public void setSyncCommitPhase(boolean syncCommitPhase)
- {
+ public void setSyncCommitPhase(boolean syncCommitPhase) {
testImmutability("syncCommitPhase");
this.syncCommitPhase = syncCommitPhase;
}
- public void setSyncRollbackPhase(boolean syncRollbackPhase)
- {
+ public void setSyncRollbackPhase(boolean syncRollbackPhase) {
testImmutability("syncRollbackPhase");
this.syncRollbackPhase = syncRollbackPhase;
}
@@ -436,107 +394,90 @@
* @param listenerAsyncPoolSize number of threads in pool
* @since 1.0
*/
- public void setListenerAsyncPoolSize(int listenerAsyncPoolSize)
- {
+ public void setListenerAsyncPoolSize(int listenerAsyncPoolSize) {
testImmutability("listenerAsyncPoolSize");
this.listenerAsyncPoolSize = listenerAsyncPoolSize;
}
- public void setUseReplQueue(boolean useReplQueue)
- {
+ public void setUseReplQueue(boolean useReplQueue) {
testImmutability("useReplQueue");
this.useReplQueue = useReplQueue;
}
- public void setIsolationLevel(IsolationLevel isolationLevel)
- {
+ public void setIsolationLevel(IsolationLevel isolationLevel) {
testImmutability("isolationLevel");
this.isolationLevel = isolationLevel;
}
- public void setStateRetrievalTimeout(long stateRetrievalTimeout)
- {
+ public void setStateRetrievalTimeout(long stateRetrievalTimeout) {
testImmutability("stateRetrievalTimeout");
this.stateRetrievalTimeout = stateRetrievalTimeout;
}
- private static String uc(String s)
- {
+ private static String uc(String s) {
return s.toUpperCase(Locale.ENGLISH);
}
- public void setIsolationLevel(String isolationLevel)
- {
+ public void setIsolationLevel(String isolationLevel) {
testImmutability("isolationLevel");
if (isolationLevel == null) throw new ConfigurationException("Isolation level cannot be null", "IsolationLevel");
this.isolationLevel = IsolationLevel.valueOf(uc(isolationLevel));
- if (this.isolationLevel == null)
- {
+ if (this.isolationLevel == null) {
log.warn("Unknown isolation level '" + isolationLevel + "', using defaults.");
this.isolationLevel = IsolationLevel.REPEATABLE_READ;
}
}
- public String getIsolationLevelString()
- {
+ public String getIsolationLevelString() {
return isolationLevel == null ? null : isolationLevel.toString();
}
- public void setIsolationLevelString(String isolationLevel)
- {
+ public void setIsolationLevelString(String isolationLevel) {
setIsolationLevel(isolationLevel);
}
/**
- * Sets whether inserting or removing a node requires a write lock
- * on the node's parent (when pessimistic locking is used.)
+ * Sets whether inserting or removing a node requires a write lock on the node's parent (when pessimistic locking is
+ * used.)
* <p/>
* The default value is <code>false</code>
*/
- public void setLockParentForChildInsertRemove(boolean lockParentForChildInsertRemove)
- {
+ public void setLockParentForChildInsertRemove(boolean lockParentForChildInsertRemove) {
testImmutability("lockParentForChildInsertRemove");
this.lockParentForChildInsertRemove = lockParentForChildInsertRemove;
}
- public void setMultiplexerStack(String stackName)
- {
+ public void setMultiplexerStack(String stackName) {
testImmutability("muxStackName");
this.muxStackName = stackName;
}
- public boolean isUsingMultiplexer()
- {
+ public boolean isUsingMultiplexer() {
return usingMultiplexer;
}
- public void setUsingMultiplexer(boolean usingMultiplexer)
- {
+ public void setUsingMultiplexer(boolean usingMultiplexer) {
testImmutability("usingMultiplexer");
this.usingMultiplexer = usingMultiplexer;
}
- public void setShutdownHookBehavior(ShutdownHookBehavior shutdownHookBehavior)
- {
+ public void setShutdownHookBehavior(ShutdownHookBehavior shutdownHookBehavior) {
testImmutability("shutdownHookBehavior");
this.shutdownHookBehavior = shutdownHookBehavior;
}
- public void setShutdownHookBehavior(String shutdownHookBehavior)
- {
+ public void setShutdownHookBehavior(String shutdownHookBehavior) {
testImmutability("shutdownHookBehavior");
if (shutdownHookBehavior == null)
throw new ConfigurationException("Shutdown hook behavior cannot be null", "ShutdownHookBehavior");
this.shutdownHookBehavior = ShutdownHookBehavior.valueOf(uc(shutdownHookBehavior));
- if (this.shutdownHookBehavior == null)
- {
+ if (this.shutdownHookBehavior == null) {
log.warn("Unknown shutdown hook behavior '" + shutdownHookBehavior + "', using defaults.");
this.shutdownHookBehavior = ShutdownHookBehavior.DEFAULT;
}
}
- public void setUseLazyDeserialization(boolean useLazyDeserialization)
- {
+ public void setUseLazyDeserialization(boolean useLazyDeserialization) {
testImmutability("useLazyDeserialization");
this.useLazyDeserialization = useLazyDeserialization;
}
@@ -547,8 +488,7 @@
* @param objectInputStreamPoolSize
* @since 1.0
*/
- public void setObjectInputStreamPoolSize(int objectInputStreamPoolSize)
- {
+ public void setObjectInputStreamPoolSize(int objectInputStreamPoolSize) {
testImmutability("objectInputStreamPoolSize");
this.objectInputStreamPoolSize = objectInputStreamPoolSize;
}
@@ -559,8 +499,7 @@
* @param objectOutputStreamPoolSize
* @since 1.0
*/
- public void setObjectOutputStreamPoolSize(int objectOutputStreamPoolSize)
- {
+ public void setObjectOutputStreamPoolSize(int objectOutputStreamPoolSize) {
testImmutability("objectOutputStreamPoolSize");
this.objectOutputStreamPoolSize = objectOutputStreamPoolSize;
}
@@ -571,26 +510,22 @@
*
* @param serializationExecutorPoolSize number of threads to use
*/
- public void setSerializationExecutorPoolSize(int serializationExecutorPoolSize)
- {
+ public void setSerializationExecutorPoolSize(int serializationExecutorPoolSize) {
testImmutability("serializationExecutorPoolSize");
this.serializationExecutorPoolSize = serializationExecutorPoolSize;
}
- public void setListenerAsyncQueueSize(int listenerAsyncQueueSize)
- {
+ public void setListenerAsyncQueueSize(int listenerAsyncQueueSize) {
testImmutability("listenerAsyncQueueSize");
this.listenerAsyncQueueSize = listenerAsyncQueueSize;
}
- public void setSerializationExecutorQueueSize(int serializationExecutorQueueSize)
- {
+ public void setSerializationExecutorQueueSize(int serializationExecutorQueueSize) {
testImmutability("serializationExecutorQueueSize");
this.serializationExecutorQueueSize = serializationExecutorQueueSize;
}
- public void setJgroupsConfigFile(URL jgroupsConfigFile)
- {
+ public void setJgroupsConfigFile(URL jgroupsConfigFile) {
testImmutability("jgroupsConfigFile");
this.jgroupsConfigFile = jgroupsConfigFile;
}
@@ -600,38 +535,31 @@
// ------------------------------------------------------------------------------------------------------------
- public ShutdownHookBehavior getShutdownHookBehavior()
- {
+ public ShutdownHookBehavior getShutdownHookBehavior() {
return this.shutdownHookBehavior;
}
- public boolean isUseReplQueue()
- {
+ public boolean isUseReplQueue() {
return useReplQueue;
}
- public String getClusterName()
- {
+ public String getClusterName() {
return clusterName;
}
- public String getClusterConfig()
- {
+ public String getClusterConfig() {
return clusterConfig;
}
- public int getReplQueueMaxElements()
- {
+ public int getReplQueueMaxElements() {
return replQueueMaxElements;
}
- public long getReplQueueInterval()
- {
+ public long getReplQueueInterval() {
return replQueueInterval;
}
- public boolean isExposeManagementStatistics()
- {
+ public boolean isExposeManagementStatistics() {
return exposeManagementStatistics;
}
@@ -639,84 +567,69 @@
* @return true if invocation batching is enabled.
* @since 1.0
*/
- public boolean isInvocationBatchingEnabled()
- {
+ public boolean isInvocationBatchingEnabled() {
return invocationBatchingEnabled;
}
- public boolean isFetchInMemoryState()
- {
+ public boolean isFetchInMemoryState() {
return fetchInMemoryState;
}
- public short getReplicationVersion()
- {
+ public short getReplicationVersion() {
return replicationVersion;
}
- public String getReplVersionString()
- {
+ public String getReplVersionString() {
return Version.decodeVersion(replicationVersion);
}
- public long getLockAcquisitionTimeout()
- {
+ public long getLockAcquisitionTimeout() {
return lockAcquisitionTimeout;
}
- public long getSyncReplTimeout()
- {
+ public long getSyncReplTimeout() {
return syncReplTimeout;
}
- public CacheMode getCacheMode()
- {
+ public CacheMode getCacheMode() {
return cacheMode;
}
- public boolean isInactiveOnStartup()
- {
+ public boolean isInactiveOnStartup() {
return inactiveOnStartup;
}
- public IsolationLevel getIsolationLevel()
- {
+ public IsolationLevel getIsolationLevel() {
return isolationLevel;
}
/**
- * Gets whether inserting or removing a node requires a write lock
- * on the node's parent (when pessimistic locking is used.)
+ * Gets whether inserting or removing a node requires a write lock on the node's parent (when pessimistic locking is
+ * used.)
* <p/>
* The default value is <code>false</code>
*/
- public boolean isLockParentForChildInsertRemove()
- {
+ public boolean isLockParentForChildInsertRemove() {
return lockParentForChildInsertRemove;
}
- public boolean isUseRegionBasedMarshalling()
- {
+ public boolean isUseRegionBasedMarshalling() {
return useRegionBasedMarshalling;
}
- public String getTransactionManagerLookupClass()
- {
+ public String getTransactionManagerLookupClass() {
return transactionManagerLookupClass;
}
- public CacheLoaderConfig getCacheLoaderConfig()
- {
+ public CacheLoaderConfig getCacheLoaderConfig() {
return cacheLoaderConfig;
}
- public boolean isSyncCommitPhase()
- {
+ public boolean isSyncCommitPhase() {
return syncCommitPhase;
}
- public boolean isSyncRollbackPhase()
- {
+ public boolean isSyncRollbackPhase() {
return syncRollbackPhase;
}
@@ -728,56 +641,45 @@
* @return thread pool size
* @since 1.0
*/
- public int getListenerAsyncPoolSize()
- {
+ public int getListenerAsyncPoolSize() {
return listenerAsyncPoolSize;
}
- public long getStateRetrievalTimeout()
- {
+ public long getStateRetrievalTimeout() {
return stateRetrievalTimeout;
}
- public String getMultiplexerStack()
- {
+ public String getMultiplexerStack() {
return muxStackName;
}
- public boolean isUseLazyDeserialization()
- {
+ public boolean isUseLazyDeserialization() {
return useLazyDeserialization;
}
- public synchronized RuntimeConfig getRuntimeConfig()
- {
- if (runtimeConfig == null)
- {
+ public synchronized RuntimeConfig getRuntimeConfig() {
+ if (runtimeConfig == null) {
setRuntimeConfig(new RuntimeConfig(), false);
}
return runtimeConfig;
}
- public void setRuntimeConfig(RuntimeConfig runtimeConfig)
- {
+ public void setRuntimeConfig(RuntimeConfig runtimeConfig) {
setRuntimeConfig(runtimeConfig, true);
}
- private void setRuntimeConfig(RuntimeConfig runtimeConfig, boolean testImmutability)
- {
- if (testImmutability)
- {
+ private void setRuntimeConfig(RuntimeConfig runtimeConfig, boolean testImmutability) {
+ if (testImmutability) {
testImmutability("runtimeConfig");
}
this.runtimeConfig = runtimeConfig;
}
- public String getMarshallerClass()
- {
+ public String getMarshallerClass() {
return marshallerClass;
}
- public void setMarshallerClass(String marshallerClass)
- {
+ public void setMarshallerClass(String marshallerClass) {
this.marshallerClass = marshallerClass;
}
@@ -785,8 +687,7 @@
* @return the size of he object input stream pool
* @since 1.0
*/
- public int getObjectInputStreamPoolSize()
- {
+ public int getObjectInputStreamPoolSize() {
return objectInputStreamPoolSize;
}
@@ -794,8 +695,7 @@
* @return the size of he object output stream pool
* @since 1.0
*/
- public int getObjectOutputStreamPoolSize()
- {
+ public int getObjectOutputStreamPoolSize() {
return objectOutputStreamPoolSize;
}
@@ -805,8 +705,7 @@
*
* @return a default JGroups config file
*/
- public URL getDefaultClusterConfig()
- {
+ public URL getDefaultClusterConfig() {
URL url = getClass().getClassLoader().getResource("flush-udp.xml");
if (log.isTraceEnabled()) log.trace("Using default JGroups configuration file " + url);
return url;
@@ -815,23 +714,19 @@
/**
* @return the serialization executor pool size.
*/
- public int getSerializationExecutorPoolSize()
- {
+ public int getSerializationExecutorPoolSize() {
return serializationExecutorPoolSize;
}
- public int getListenerAsyncQueueSize()
- {
+ public int getListenerAsyncQueueSize() {
return listenerAsyncQueueSize;
}
- public int getSerializationExecutorQueueSize()
- {
+ public int getSerializationExecutorQueueSize() {
return serializationExecutorQueueSize;
}
- public URL getJgroupsConfigFile()
- {
+ public URL getJgroupsConfigFile() {
return jgroupsConfigFile;
}
@@ -844,8 +739,7 @@
// ------------------------------------------------------------------------------------------------------------
@Override
- public boolean equals(Object o)
- {
+ public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
@@ -895,8 +789,7 @@
}
@Override
- public int hashCode()
- {
+ public int hashCode() {
int result;
result = (marshaller != null ? marshaller.hashCode() : 0);
result = 31 * result + (clusterName != null ? clusterName.hashCode() : 0);
@@ -938,93 +831,76 @@
}
@Override
- public Configuration clone()
- {
- try
- {
+ public Configuration clone() {
+ try {
Configuration c = (Configuration) super.clone();
- if (evictionConfig != null)
- {
+ if (evictionConfig != null) {
c.setEvictionConfig(evictionConfig.clone());
}
- if (cacheLoaderConfig != null)
- {
+ if (cacheLoaderConfig != null) {
c.setCacheLoaderConfig(cacheLoaderConfig.clone());
}
- if (runtimeConfig != null)
- {
+ if (runtimeConfig != null) {
c.setRuntimeConfig(runtimeConfig.clone());
// always make sure we reset the runtime when cloning.
c.getRuntimeConfig().reset();
}
return c;
}
- catch (CloneNotSupportedException e)
- {
+ catch (CloneNotSupportedException e) {
throw new RuntimeException(e);
}
}
- public boolean isUsingCacheLoaders()
- {
+ public boolean isUsingCacheLoaders() {
return getCacheLoaderConfig() != null && !getCacheLoaderConfig().getIndividualCacheLoaderConfigs().isEmpty();
}
- public String getMuxStackName()
- {
+ public String getMuxStackName() {
return muxStackName;
}
- public void setMuxStackName(String muxStackName)
- {
+ public void setMuxStackName(String muxStackName) {
this.muxStackName = muxStackName;
}
/**
- * Returns the {@link org.horizon.config.CustomInterceptorConfig}, if any, associated with this configuration
- * object. The custom interceptors will be added to the cache at startup in the sequence defined by this list.
+ * Returns the {@link org.horizon.config.CustomInterceptorConfig}, if any, associated with this configuration object.
+ * The custom interceptors will be added to the cache at startup in the sequence defined by this list.
*
* @return List of cutom interceptors, never null
*/
@SuppressWarnings("unchecked")
- public List<CustomInterceptorConfig> getCustomInterceptors()
- {
+ public List<CustomInterceptorConfig> getCustomInterceptors() {
return customInterceptors == null ? Collections.EMPTY_LIST : customInterceptors;
}
/**
* @see #getCustomInterceptors()
*/
- public void setCustomInterceptors(List<CustomInterceptorConfig> customInterceptors)
- {
+ public void setCustomInterceptors(List<CustomInterceptorConfig> customInterceptors) {
testImmutability("customInterceptors");
this.customInterceptors = customInterceptors;
}
- public boolean isUsingEviction()
- {
+ public boolean isUsingEviction() {
return getEvictionConfig() != null;
}
- public void applyOverrides(Configuration overrides)
- {
+ public void applyOverrides(Configuration overrides) {
// loop through all overridden elements in the incoming configuration and apply
- for (String overriddenField : overrides.overriddenConfigurationElements)
- {
+ for (String overriddenField : overrides.overriddenConfigurationElements) {
assertAllowedToOverride(overriddenField);
ReflectionUtil.setValue(this, overriddenField, ReflectionUtil.getValue(overrides, overriddenField));
}
}
- private void assertAllowedToOverride(String fieldname)
- {
- try
- {
+ private void assertAllowedToOverride(String fieldname) {
+ try {
if (getClass().getDeclaredField(fieldname).isAnnotationPresent(NonOverridable.class))
throw new ConfigurationException("Configuration field " + fieldname + " cannot be overridden!");
}
- catch (NoSuchFieldException e)
- {
+ catch (NoSuchFieldException e) {
throw new CacheException("Field " + fieldname + " does not exist on Configuration!");
}
}
Modified: core/branches/flat/src/main/java/org/horizon/config/ConfigurationComponent.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/config/ConfigurationComponent.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/config/ConfigurationComponent.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -23,8 +23,8 @@
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
-import org.horizon.CacheStatus;
import org.horizon.CacheSPI;
+import org.horizon.CacheStatus;
import org.horizon.factories.ComponentRegistry;
import org.horizon.factories.annotations.Inject;
import org.horizon.factories.annotations.Start;
@@ -39,17 +39,15 @@
import java.util.Set;
/**
- * Base superclass of Cache configuration classes that expose some properties
- * that can be changed after the cache is started.
+ * Base superclass of Cache configuration classes that expose some properties that can be changed after the cache is
+ * started.
*
* @author <a href="brian.stansberry at jboss.com">Brian Stansberry</a>
- *
* @see #testImmutability(String)
* @since 1.0
*/
@Scope(Scopes.NAMED_CACHE)
-public abstract class ConfigurationComponent implements CloneableConfigurationComponent
-{
+public abstract class ConfigurationComponent implements CloneableConfigurationComponent {
private static final long serialVersionUID = 4879873994727821938L;
protected transient Log log = LogFactory.getLog(getClass());
@@ -60,58 +58,46 @@
private boolean accessible;
protected List<String> overriddenConfigurationElements = new LinkedList<String>();
- protected ConfigurationComponent()
- {
+ protected ConfigurationComponent() {
}
- public void passCacheToChildConfig(ConfigurationComponent child)
- {
- if (child != null)
- {
+ public void passCacheToChildConfig(ConfigurationComponent child) {
+ if (child != null) {
child.setCache(cache);
}
}
- protected void addChildConfig(ConfigurationComponent child)
- {
+ protected void addChildConfig(ConfigurationComponent child) {
if (child != null && children.add(child))
child.setCache(cache);
}
- protected void addChildConfigs(Collection<? extends ConfigurationComponent> toAdd)
- {
- if (toAdd != null)
- {
+ protected void addChildConfigs(Collection<? extends ConfigurationComponent> toAdd) {
+ if (toAdd != null) {
for (ConfigurationComponent child : toAdd)
addChildConfig(child);
}
}
- protected void removeChildConfig(ConfigurationComponent child)
- {
+ protected void removeChildConfig(ConfigurationComponent child) {
children.remove(child);
}
- protected void removeChildConfigs(Collection<? extends ConfigurationComponent> toRemove)
- {
- if (toRemove != null)
- {
+ protected void removeChildConfigs(Collection<? extends ConfigurationComponent> toRemove) {
+ if (toRemove != null) {
for (ConfigurationComponent child : toRemove)
removeChildConfig(child);
}
}
- protected void replaceChildConfig(ConfigurationComponent oldConfig, ConfigurationComponent newConfig)
- {
+ protected void replaceChildConfig(ConfigurationComponent oldConfig, ConfigurationComponent newConfig) {
removeChildConfig(oldConfig);
addChildConfig(newConfig);
}
protected void replaceChildConfigs(Collection<? extends ConfigurationComponent> oldConfigs,
- Collection<? extends ConfigurationComponent> newConfigs)
- {
- synchronized (children)
- {
+ Collection<? extends ConfigurationComponent> newConfigs) {
+ synchronized (children) {
removeChildConfigs(oldConfigs);
addChildConfigs(newConfigs);
}
@@ -122,21 +108,16 @@
*
* @param fieldName
*/
- protected void testImmutability(String fieldName)
- {
- try
- {
- if (!accessible && cache != null && cache.getCacheStatus() != null && cache.getCacheStatus() == CacheStatus.STARTED && !getClass().getDeclaredField(fieldName).isAnnotationPresent(Dynamic.class))
- {
+ protected void testImmutability(String fieldName) {
+ try {
+ if (!accessible && cache != null && cache.getCacheStatus() != null && cache.getCacheStatus() == CacheStatus.STARTED && !getClass().getDeclaredField(fieldName).isAnnotationPresent(Dynamic.class)) {
throw new ConfigurationException("Attempted to modify a non-Dynamic configuration element [" + fieldName + "] after the cache has started!");
}
}
- catch (NoSuchFieldException e)
- {
+ catch (NoSuchFieldException e) {
log.warn("Field " + fieldName + " not found!!");
}
- finally
- {
+ finally {
accessible = false;
}
@@ -144,33 +125,27 @@
overriddenConfigurationElements.add(fieldName);
}
- public void setCache(CacheSPI cache)
- {
+ public void setCache(CacheSPI cache) {
this.cache = cache;
- synchronized (children)
- {
- for (ConfigurationComponent child : children)
- {
+ synchronized (children) {
+ for (ConfigurationComponent child : children) {
child.setCache(cache);
}
}
}
@Inject
- private void injectDependencies(ComponentRegistry cr)
- {
+ private void injectDependencies(ComponentRegistry cr) {
this.cr = cr;
}
@Start
- private void start()
- {
+ private void start() {
setCache(cr.getComponent(CacheSPI.class));
}
@Override
- public CloneableConfigurationComponent clone() throws CloneNotSupportedException
- {
+ public CloneableConfigurationComponent clone() throws CloneNotSupportedException {
ConfigurationComponent c = (ConfigurationComponent) super.clone();
c.setCache(null);
return c;
Modified: core/branches/flat/src/main/java/org/horizon/config/ConfigurationException.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/config/ConfigurationException.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/config/ConfigurationException.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -27,49 +27,42 @@
import java.util.List;
/**
- * An exception that represents an error in the configuration. This could be a parsing error or a logical error involving clashing
- * configuration options or missing mandatory configuration elements.
+ * An exception that represents an error in the configuration. This could be a parsing error or a logical error
+ * involving clashing configuration options or missing mandatory configuration elements.
*
* @author <a href="mailto:manik at jboss.org">Manik Surtani (manik at jboss.org)</a>
* @see Configuration
* @see org.horizon.manager.CacheManager
* @since 1.0
*/
-public class ConfigurationException extends CacheException
-{
+public class ConfigurationException extends CacheException {
private static final long serialVersionUID = -5576382839360927955L;
private List<String> erroneousAttributes = new ArrayList<String>();
- public ConfigurationException(Exception e)
- {
+ public ConfigurationException(Exception e) {
super(e);
}
- public ConfigurationException(String string)
- {
+ public ConfigurationException(String string) {
super(string);
}
- public ConfigurationException(String string, String erroneousAttribute)
- {
+ public ConfigurationException(String string, String erroneousAttribute) {
super(string);
erroneousAttributes.add(erroneousAttribute);
}
- public ConfigurationException(String string, Throwable throwable)
- {
+ public ConfigurationException(String string, Throwable throwable) {
super(string, throwable);
}
- public List<String> getErroneousAttributes()
- {
+ public List<String> getErroneousAttributes() {
return erroneousAttributes;
}
- public void addErroneousAttribute(String s)
- {
+ public void addErroneousAttribute(String s) {
erroneousAttributes.add(s);
}
}
Modified: core/branches/flat/src/main/java/org/horizon/config/ConfigurationRegistry.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/config/ConfigurationRegistry.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/config/ConfigurationRegistry.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -28,38 +28,31 @@
* A registry for {@link Configuration}s.
*
* @author Brian Stansberry
- *
* @since 1.0
*/
-public interface ConfigurationRegistry
-{
+public interface ConfigurationRegistry {
/**
- * Gets a {@link Configuration#clone() clone} of the {@link Configuration}
- * registered under the given name.
+ * Gets a {@link Configuration#clone() clone} of the {@link Configuration} registered under the given name.
* <p/>
- * The returned object is a clone of the internally held configuration,
- * so any changes made to it by the caller will not affect the internal
- * state of this registry.
+ * The returned object is a clone of the internally held configuration, so any changes made to it by the caller will
+ * not affect the internal state of this registry.
*
* @param configName the name of the configuration
* @return a <code>Configuration</code>. Will not be <code>null</code>.
- * @throws IllegalArgumentException if no configuration is registered
- * under <code>configName</code>
+ * @throws IllegalArgumentException if no configuration is registered under <code>configName</code>
*/
Configuration getConfiguration(String configName) throws Exception;
/**
* Register the given configuration under the given name.
* <p/>
- * The configuration will be cloned before being stored internally,
- * so the copy under the control of the registry will not be affected
- * by any external changes.
+ * The configuration will be cloned before being stored internally, so the copy under the control of the registry
+ * will not be affected by any external changes.
*
* @param configName the name of the configuration
* @param config the configuration
* @throws CloneNotSupportedException
- * @throws IllegalStateException if a configuration is already registered
- * under <code>configName</code>
+ * @throws IllegalStateException if a configuration is already registered under <code>configName</code>
*/
void registerConfiguration(String configName, Configuration config) throws CloneNotSupportedException;
@@ -67,8 +60,7 @@
* Unregisters the named configuration.
*
* @param configName the name of the configuration
- * @throws IllegalStateException if no configuration is registered
- * under <code>configName</code>
+ * @throws IllegalStateException if no configuration is registered under <code>configName</code>
*/
void unregisterConfiguration(String configName);
Modified: core/branches/flat/src/main/java/org/horizon/config/CustomInterceptorConfig.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/config/CustomInterceptorConfig.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/config/CustomInterceptorConfig.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -31,8 +31,7 @@
* @since 1.0
*/
@Immutable
-public class CustomInterceptorConfig extends ConfigurationComponent
-{
+public class CustomInterceptorConfig extends ConfigurationComponent {
private CommandInterceptor interceptor;
private boolean isFirst;
private boolean isLast;
@@ -51,8 +50,7 @@
* @param beforeClass immediately before the specified class in the chain
*/
public CustomInterceptorConfig(CommandInterceptor interceptor, boolean first, boolean last, int index,
- String afterClass, String beforeClass)
- {
+ String afterClass, String beforeClass) {
this.interceptor = interceptor;
isFirst = first;
isLast = last;
@@ -66,16 +64,14 @@
*
* @param interceptor
*/
- public CustomInterceptorConfig(CommandInterceptor interceptor)
- {
+ public CustomInterceptorConfig(CommandInterceptor interceptor) {
this.interceptor = interceptor;
}
/**
* Shall this interceptor be the first one in the chain?
*/
- public void setFirst(boolean first)
- {
+ public void setFirst(boolean first) {
testImmutability("first");
isFirst = first;
}
@@ -83,39 +79,34 @@
/**
* Shall this intercepto be the last one in the chain?
*/
- public void setLast(boolean last)
- {
+ public void setLast(boolean last) {
testImmutability("last");
isLast = last;
}
/**
- * Put this interceptor at the specified index, after the default chain is built.
- * If the index is not valid (negative or grater than the size of the chain)
- * an {@link ConfigurationException} is thrown at construction time.
+ * Put this interceptor at the specified index, after the default chain is built. If the index is not valid (negative
+ * or grater than the size of the chain) an {@link ConfigurationException} is thrown at construction time.
*/
- public void setIndex(int index)
- {
+ public void setIndex(int index) {
testImmutability("index");
this.index = index;
}
/**
- * Adds the interceptor immediately after the first occurance of an interceptor having the given class.
- * If the chain does not contain such an interceptor then this interceptor definition is ignored.
+ * Adds the interceptor immediately after the first occurance of an interceptor having the given class. If the chain
+ * does not contain such an interceptor then this interceptor definition is ignored.
*/
- public void setAfterClass(String afterClass)
- {
+ public void setAfterClass(String afterClass) {
testImmutability("afterClass");
this.afterClass = afterClass;
}
/**
- * Adds the interceptor immediately before the first occurance of an interceptor having the given class.
- * If the chain does not contain such an interceptor then this interceptor definition is ignored.
+ * Adds the interceptor immediately before the first occurance of an interceptor having the given class. If the chain
+ * does not contain such an interceptor then this interceptor definition is ignored.
*/
- public void setBeforeClass(String beforeClass)
- {
+ public void setBeforeClass(String beforeClass) {
testImmutability("beforeClass");
this.beforeClass = beforeClass;
}
@@ -123,53 +114,46 @@
/**
* Returns a the interceptor that we want to add to the chain.
*/
- public CommandInterceptor getInterceptor()
- {
+ public CommandInterceptor getInterceptor() {
return interceptor;
}
/**
* @see #setFirst(boolean)
*/
- public boolean isFirst()
- {
+ public boolean isFirst() {
return isFirst;
}
/**
* @see #setLast(boolean)
*/
- public boolean isLast()
- {
+ public boolean isLast() {
return isLast;
}
/**
* @see #getIndex()
*/
- public int getIndex()
- {
+ public int getIndex() {
return index;
}
/**
* @see #getAfterClass()
*/
- public String getAfterClass()
- {
+ public String getAfterClass() {
return afterClass;
}
/**
* @see #getBeforeClass()
*/
- public String getBeforeClass()
- {
+ public String getBeforeClass() {
return beforeClass;
}
- public String toString()
- {
+ public String toString() {
return "CustomInterceptorConfig{" +
"interceptor='" + interceptor + '\'' +
", isFirst=" + isFirst +
@@ -180,8 +164,7 @@
'}';
}
- public boolean equals(Object o)
- {
+ public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof CustomInterceptorConfig)) return false;
@@ -197,8 +180,7 @@
return true;
}
- public int hashCode()
- {
+ public int hashCode() {
int result;
result = (interceptor != null ? interceptor.hashCode() : 0);
result = 31 * result + (isFirst ? 1 : 0);
@@ -210,8 +192,7 @@
}
@Override
- public CustomInterceptorConfig clone() throws CloneNotSupportedException
- {
+ public CustomInterceptorConfig clone() throws CloneNotSupportedException {
CustomInterceptorConfig dolly = (CustomInterceptorConfig) super.clone();
dolly.interceptor = interceptor;
dolly.isFirst = isFirst;
Modified: core/branches/flat/src/main/java/org/horizon/config/Dynamic.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/config/Dynamic.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/config/Dynamic.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -43,6 +43,5 @@
// only applies to fields.
@Target(ElementType.FIELD)
-public @interface Dynamic
-{
+public @interface Dynamic {
}
Modified: core/branches/flat/src/main/java/org/horizon/config/EvictionAlgorithmConfig.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/config/EvictionAlgorithmConfig.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/config/EvictionAlgorithmConfig.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -24,29 +24,26 @@
/**
* An interface used to configure an eviction algorithm. Replaces the deprecated {@link EvictionCacheConfig}.
* <p/>
- * In its most basic form, it is implemented by {@link org.horizon.eviction.EvictionAlgorithmConfigBase}, but
- * more specific eviction policies may subclass {@link org.horizon.eviction.EvictionAlgorithmConfigBase} or re-implement
- * this interface to provide access to more config variables.
+ * In its most basic form, it is implemented by {@link org.horizon.eviction.EvictionAlgorithmConfigBase}, but more
+ * specific eviction policies may subclass {@link org.horizon.eviction.EvictionAlgorithmConfigBase} or re-implement this
+ * interface to provide access to more config variables.
*
* @author Manik Surtani (<a href="mailto:manik at jboss.org">manik at jboss.org</a>)
* @since 1.0
*/
-public interface EvictionAlgorithmConfig extends CloneableConfigurationComponent
-{
+public interface EvictionAlgorithmConfig extends CloneableConfigurationComponent {
/**
- * Gets the class name of the {@link org.horizon.eviction.EvictionAlgorithm} implementation
- * this object will configure.
+ * Gets the class name of the {@link org.horizon.eviction.EvictionAlgorithm} implementation this object will
+ * configure.
*
* @return fully qualified class name
*/
String getEvictionAlgorithmClassName();
/**
- * Validate the configuration. Will be called after any configuration
- * properties are set.
+ * Validate the configuration. Will be called after any configuration properties are set.
*
- * @throws ConfigurationException if any values for the configuration
- * properties are invalid
+ * @throws ConfigurationException if any values for the configuration properties are invalid
*/
void validate() throws ConfigurationException;
Modified: core/branches/flat/src/main/java/org/horizon/config/EvictionCacheConfig.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/config/EvictionCacheConfig.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/config/EvictionCacheConfig.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -23,8 +23,7 @@
import org.apache.commons.logging.LogFactory;
-public class EvictionCacheConfig extends ConfigurationComponent
-{
+public class EvictionCacheConfig extends ConfigurationComponent {
/**
* The serialVersionUID
*/
@@ -38,25 +37,21 @@
private EvictionAlgorithmConfig evictionAlgorithmConfig;
private String evictionActionClassName;
- public EvictionCacheConfig(EvictionAlgorithmConfig evictionAlgorithmConfig)
- {
+ public EvictionCacheConfig(EvictionAlgorithmConfig evictionAlgorithmConfig) {
eventQueueSize = EvictionConfig.EVENT_QUEUE_SIZE_DEFAULT;
evictionActionClassName = EvictionConfig.EVICTION_ACTION_CLASS_DEFAULT;
this.evictionAlgorithmConfig = evictionAlgorithmConfig;
}
- public EvictionCacheConfig(Integer eventQueueSize, EvictionAlgorithmConfig evictionAlgorithmConfig, String evictionActionClassName)
- {
+ public EvictionCacheConfig(Integer eventQueueSize, EvictionAlgorithmConfig evictionAlgorithmConfig, String evictionActionClassName) {
this.eventQueueSize = eventQueueSize;
this.evictionAlgorithmConfig = evictionAlgorithmConfig;
this.evictionActionClassName = evictionActionClassName;
}
- public void setEventQueueSize(int queueSize)
- {
+ public void setEventQueueSize(int queueSize) {
testImmutability("eventQueueSize");
- if (queueSize <= 0)
- {
+ if (queueSize <= 0) {
LogFactory.getLog(EvictionCacheConfig.class).warn("Ignoring invalid queue capacity " +
queueSize + " -- using " +
EvictionConfig.EVENT_QUEUE_SIZE_DEFAULT);
@@ -68,8 +63,7 @@
/**
* Ensure this is a valid eviction region configuration.
*/
- public void validate()
- {
+ public void validate() {
if (eventQueueSize < 1)
throw new ConfigurationException("Eviction event queue size cannot be less than 1!");
@@ -80,24 +74,20 @@
}
- public Integer getEventQueueSize()
- {
+ public Integer getEventQueueSize() {
return eventQueueSize;
}
- public EvictionAlgorithmConfig getEvictionAlgorithmConfig()
- {
+ public EvictionAlgorithmConfig getEvictionAlgorithmConfig() {
return evictionAlgorithmConfig;
}
- public String getEvictionActionClassName()
- {
+ public String getEvictionActionClassName() {
return evictionActionClassName;
}
@Override
- public boolean equals(Object o)
- {
+ public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
@@ -114,13 +104,12 @@
}
@Override
- public int hashCode()
- {
+ public int hashCode() {
int result;
result = (eventQueueSize != null ? eventQueueSize.hashCode() : 0);
result = 31 * result + (evictionAlgorithmConfig != null ? evictionAlgorithmConfig.hashCode() : 0);
result = 31 * result + (evictionActionClassName != null ? evictionActionClassName.hashCode() : 0);
return result;
}
-
+
}
\ No newline at end of file
Modified: core/branches/flat/src/main/java/org/horizon/config/EvictionConfig.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/config/EvictionConfig.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/config/EvictionConfig.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -27,8 +27,7 @@
import java.util.List;
import java.util.concurrent.TimeUnit;
-public class EvictionConfig extends ConfigurationComponent
-{
+public class EvictionConfig extends ConfigurationComponent {
/**
* The serialVersionUID
*/
@@ -51,16 +50,14 @@
private List<EvictionCacheConfig> evictionCacheConfigs;
private EvictionCacheConfig defaultEvictionCacheConfig;
- public EvictionConfig()
- {
+ public EvictionConfig() {
// evictionCacheConfigs = new LinkedList<EvictionCacheConfig>();
// defaultEvictionCacheConfig = new EvictionCacheConfig(Fqn.ROOT);
// defaultEvictionCacheConfig.setEventQueueSize(EVENT_QUEUE_SIZE_DEFAULT);
// defaultEvictionCacheConfig.setEvictionActionClassName(DefaultEvictionAction.class.getName());
}
- public EvictionConfig(EvictionCacheConfig defaultEvictionCacheConfig)
- {
+ public EvictionConfig(EvictionCacheConfig defaultEvictionCacheConfig) {
evictionCacheConfigs = new LinkedList<EvictionCacheConfig>();
// try
// {
@@ -75,40 +72,33 @@
// this.defaultEvictionCacheConfig.setEvictionActionClassName(DefaultEvictionAction.class.getName());
}
- public EvictionConfig(EvictionCacheConfig defaultEvictionCacheConfig, int wakeupInterval)
- {
+ public EvictionConfig(EvictionCacheConfig defaultEvictionCacheConfig, int wakeupInterval) {
this(defaultEvictionCacheConfig);
this.wakeupInterval = wakeupInterval;
}
- public boolean isValidConfig()
- {
+ public boolean isValidConfig() {
return (defaultEvictionCacheConfig != null && defaultEvictionCacheConfig.getEvictionActionClassName() != null && defaultEvictionCacheConfig.getEvictionAlgorithmConfig() != null)
|| (evictionCacheConfigs != null && evictionCacheConfigs.size() > 0);
}
- public EvictionCacheConfig getDefaultEvictionRegionConfig()
- {
+ public EvictionCacheConfig getDefaultEvictionRegionConfig() {
return defaultEvictionCacheConfig;
}
- public void setDefaultEvictionRegionConfig(EvictionCacheConfig defaultEvictionCacheConfig)
- {
+ public void setDefaultEvictionRegionConfig(EvictionCacheConfig defaultEvictionCacheConfig) {
this.defaultEvictionCacheConfig = defaultEvictionCacheConfig;
// this.defaultEvictionCacheConfig.setEventQueueSizeIfUnset(EVENT_QUEUE_SIZE_DEFAULT);
}
- public List<EvictionCacheConfig> getEvictionCacheConfigs()
- {
+ public List<EvictionCacheConfig> getEvictionCacheConfigs() {
return evictionCacheConfigs;
}
- public void setEvictionRegionConfigs(List<EvictionCacheConfig> evictionCacheConfigs)
- {
+ public void setEvictionRegionConfigs(List<EvictionCacheConfig> evictionCacheConfigs) {
testImmutability("evictionCacheConfigs");
EvictionCacheConfig toRemove = null;
- for (EvictionCacheConfig erc : evictionCacheConfigs)
- {
+ for (EvictionCacheConfig erc : evictionCacheConfigs) {
// if (erc.getCacheName().isRoot() || erc.getCacheName().equals(RegionManagerImpl.DEFAULT_REGION))
// {
// mergeWithDefault(erc);
@@ -122,16 +112,14 @@
this.evictionCacheConfigs = evictionCacheConfigs;
}
- private void mergeWithDefault(EvictionCacheConfig erc)
- {
+ private void mergeWithDefault(EvictionCacheConfig erc) {
// erc.setEventQueueSizeIfUnset(defaultEvictionCacheConfig.getEventQueueSize());
// if (erc.getEvictionAlgorithmConfig() == null)
// erc.setEvictionAlgorithmConfig(defaultEvictionCacheConfig.getEvictionAlgorithmConfig());
// defaultEvictionCacheConfig = erc;
}
- public void addEvictionRegionConfig(EvictionCacheConfig evictionCacheConfig)
- {
+ public void addEvictionRegionConfig(EvictionCacheConfig evictionCacheConfig) {
testImmutability("evictionCacheConfigs");
// if (evictionCacheConfig.getCacheName().isRoot() || evictionCacheConfig.getCacheName().equals(RegionManagerImpl.DEFAULT_REGION))
// {
@@ -146,8 +134,7 @@
/**
* @return the wake up interval of the eviction thread, in milliseconds.
*/
- public long getWakeupInterval()
- {
+ public long getWakeupInterval() {
return wakeupInterval;
}
@@ -156,8 +143,7 @@
*
* @param wakeupInterval interval, in milliseconds.
*/
- public void setWakeupInterval(long wakeupInterval)
- {
+ public void setWakeupInterval(long wakeupInterval) {
testImmutability("wakeupInterval");
this.wakeupInterval = wakeupInterval;
}
@@ -168,14 +154,12 @@
* @param wakeupInterval interval
* @param timeUnit for the interval provided
*/
- public void setWakeupInterval(long wakeupInterval, TimeUnit timeUnit)
- {
+ public void setWakeupInterval(long wakeupInterval, TimeUnit timeUnit) {
testImmutability("wakeupInterval");
this.wakeupInterval = timeUnit.toMillis(wakeupInterval);
}
- public boolean equals(Object o)
- {
+ public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof EvictionConfig)) return false;
@@ -191,8 +175,7 @@
return true;
}
- public int hashCode()
- {
+ public int hashCode() {
int result;
result = 31 + (int) (wakeupInterval ^ (wakeupInterval >>> 32));
result = 31 * result + defaultEventQueueSize;
@@ -201,11 +184,9 @@
}
@Override
- public EvictionConfig clone() throws CloneNotSupportedException
- {
+ public EvictionConfig clone() throws CloneNotSupportedException {
EvictionConfig clone = (EvictionConfig) super.clone();
- if (evictionCacheConfigs != null)
- {
+ if (evictionCacheConfigs != null) {
// needs to be a deep copy
clone.evictionCacheConfigs = new LinkedList<EvictionCacheConfig>();
// for (EvictionCacheConfig erc : evictionCacheConfigs)
@@ -216,11 +197,10 @@
/**
- * Returns the <code>EvictionRegionConfig</code> coresponding to given region fqn, or <code>null</code> if no
- * match is found.
+ * Returns the <code>EvictionRegionConfig</code> coresponding to given region fqn, or <code>null</code> if no match
+ * is found.
*/
- public EvictionCacheConfig getEvictionRegionConfig(String region)
- {
+ public EvictionCacheConfig getEvictionRegionConfig(String region) {
return null;
}
@@ -229,8 +209,7 @@
*
* @param config config to apply defaults to
*/
- public void applyDefaults(EvictionCacheConfig config)
- {
+ public void applyDefaults(EvictionCacheConfig config) {
// if (config == null) return; // no op
// config.setDefaults(defaultEvictionCacheConfig);
}
Modified: core/branches/flat/src/main/java/org/horizon/config/GlobalConfiguration.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/config/GlobalConfiguration.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/config/GlobalConfiguration.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -10,8 +10,7 @@
* @author Manik Surtani
* @since 1.0
*/
-public class GlobalConfiguration extends ConfigurationComponent
-{
+public class GlobalConfiguration extends ConfigurationComponent {
String asyncListenerExecutorFactoryClass;
String asyncSerializationExecutorFactoryClass;
String evictionScheduledExecutorFactoryClass;
@@ -24,130 +23,107 @@
Properties transportProperties;
Configuration defaultConfiguration;
- public String getAsyncListenerExecutorFactoryClass()
- {
+ public String getAsyncListenerExecutorFactoryClass() {
return asyncListenerExecutorFactoryClass;
}
- public void setAsyncListenerExecutorFactoryClass(String asyncListenerExecutorFactoryClass)
- {
+ public void setAsyncListenerExecutorFactoryClass(String asyncListenerExecutorFactoryClass) {
testImmutability("asyncListenerExecutorFactoryClass");
this.asyncListenerExecutorFactoryClass = asyncListenerExecutorFactoryClass;
}
- public String getAsyncSerializationExecutorFactoryClass()
- {
+ public String getAsyncSerializationExecutorFactoryClass() {
return asyncSerializationExecutorFactoryClass;
}
- public void setAsyncSerializationExecutorFactoryClass(String asyncSerializationExecutorFactoryClass)
- {
+ public void setAsyncSerializationExecutorFactoryClass(String asyncSerializationExecutorFactoryClass) {
testImmutability("asyncSerializationExecutorFactoryClass");
this.asyncSerializationExecutorFactoryClass = asyncSerializationExecutorFactoryClass;
}
- public String getEvictionScheduledExecutorFactoryClass()
- {
+ public String getEvictionScheduledExecutorFactoryClass() {
return evictionScheduledExecutorFactoryClass;
}
- public void setEvictionScheduledExecutorFactoryClass(String evictionScheduledExecutorFactoryClass)
- {
+ public void setEvictionScheduledExecutorFactoryClass(String evictionScheduledExecutorFactoryClass) {
testImmutability("evictionScheduledExecutorFactoryClass");
this.evictionScheduledExecutorFactoryClass = evictionScheduledExecutorFactoryClass;
}
- public String getReplicationQueueScheduledExecutorFactoryClass()
- {
+ public String getReplicationQueueScheduledExecutorFactoryClass() {
return replicationQueueScheduledExecutorFactoryClass;
}
- public void setReplicationQueueScheduledExecutorFactoryClass(String replicationQueueScheduledExecutorFactoryClass)
- {
+ public void setReplicationQueueScheduledExecutorFactoryClass(String replicationQueueScheduledExecutorFactoryClass) {
testImmutability("replicationQueueScheduledExecutorFactoryClass");
this.replicationQueueScheduledExecutorFactoryClass = replicationQueueScheduledExecutorFactoryClass;
}
- public String getMarshallerClass()
- {
+ public String getMarshallerClass() {
return marshallerClass;
}
- public void setMarshallerClass(String marshallerClass)
- {
+ public void setMarshallerClass(String marshallerClass) {
testImmutability("marshallerClass");
this.marshallerClass = marshallerClass;
}
- public String getMarshallVersion()
- {
+ public String getMarshallVersion() {
return marshallVersion;
}
- public void setMarshallVersion(String marshallVersion)
- {
+ public void setMarshallVersion(String marshallVersion) {
testImmutability("marshallVersion");
this.marshallVersion = marshallVersion;
}
- public int getObjectInputStreamPoolSize()
- {
+ public int getObjectInputStreamPoolSize() {
return objectInputStreamPoolSize;
}
- public void setObjectInputStreamPoolSize(int objectInputStreamPoolSize)
- {
+ public void setObjectInputStreamPoolSize(int objectInputStreamPoolSize) {
testImmutability("objectInputStreamPoolSize");
this.objectInputStreamPoolSize = objectInputStreamPoolSize;
}
- public int getObjectOutputStreamPoolSize()
- {
+ public int getObjectOutputStreamPoolSize() {
return objectOutputStreamPoolSize;
}
- public void setObjectOutputStreamPoolSize(int objectOutputStreamPoolSize)
- {
+ public void setObjectOutputStreamPoolSize(int objectOutputStreamPoolSize) {
testImmutability("objectOutputStreamPoolSize");
this.objectOutputStreamPoolSize = objectOutputStreamPoolSize;
}
- public String getTransportClass()
- {
+ public String getTransportClass() {
return transportClass;
}
- public void setTransportClass(String transportClass)
- {
+ public void setTransportClass(String transportClass) {
testImmutability("transportClass");
this.transportClass = transportClass;
}
- public Properties getTransportProperties()
- {
+ public Properties getTransportProperties() {
return transportProperties;
}
- public void setTransportProperties(Properties transportProperties)
- {
+ public void setTransportProperties(Properties transportProperties) {
testImmutability("transportProperties");
this.transportProperties = transportProperties;
}
- public Configuration getDefaultConfiguration()
- {
+ public Configuration getDefaultConfiguration() {
return defaultConfiguration;
}
- public void setDefaultConfiguration(Configuration defaultConfiguration)
- {
+ public void setDefaultConfiguration(Configuration defaultConfiguration) {
testImmutability("defaultConfiguration");
this.defaultConfiguration = defaultConfiguration;
}
@Override
- public boolean equals(Object o)
- {
+ public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
@@ -178,8 +154,7 @@
}
@Override
- public int hashCode()
- {
+ public int hashCode() {
int result = asyncListenerExecutorFactoryClass != null ? asyncListenerExecutorFactoryClass.hashCode() : 0;
result = 31 * result + (asyncSerializationExecutorFactoryClass != null ? asyncSerializationExecutorFactoryClass.hashCode() : 0);
result = 31 * result + (evictionScheduledExecutorFactoryClass != null ? evictionScheduledExecutorFactoryClass.hashCode() : 0);
@@ -195,14 +170,11 @@
}
@Override
- public GlobalConfiguration clone()
- {
- try
- {
+ public GlobalConfiguration clone() {
+ try {
return (GlobalConfiguration) super.clone();
}
- catch (CloneNotSupportedException e)
- {
+ catch (CloneNotSupportedException e) {
throw new CacheException("Problems cloning configuration component!", e);
}
}
Modified: core/branches/flat/src/main/java/org/horizon/config/MissingPolicyException.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/config/MissingPolicyException.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/config/MissingPolicyException.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -21,16 +21,14 @@
*/
package org.horizon.config;
-public class MissingPolicyException extends ConfigurationException
-{
+public class MissingPolicyException extends ConfigurationException {
/**
* The serialVersionUID
*/
private static final long serialVersionUID = 6107098975617303157L;
- public MissingPolicyException(String message)
- {
+ public MissingPolicyException(String message) {
super(message);
}
}
\ No newline at end of file
Modified: core/branches/flat/src/main/java/org/horizon/config/NonOverridable.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/config/NonOverridable.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/config/NonOverridable.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -1,6 +1,10 @@
package org.horizon.config;
-import java.lang.annotation.*;
+import java.lang.annotation.Documented;
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
/**
* This annotation marks configuration attributes as non-overridable by named caches.
@@ -17,7 +21,6 @@
// only applies to fields.
@Target(ElementType.FIELD)
-public @interface NonOverridable
-{
+public @interface NonOverridable {
}
Modified: core/branches/flat/src/main/java/org/horizon/config/OldFileFormatException.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/config/OldFileFormatException.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/config/OldFileFormatException.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -28,15 +28,12 @@
* @author Mircea.Markus at jboss.com
* @since 1.0
*/
-public class OldFileFormatException extends ConfigurationException
-{
- public OldFileFormatException(String string)
- {
+public class OldFileFormatException extends ConfigurationException {
+ public OldFileFormatException(String string) {
super(string);
}
- public OldFileFormatException()
- {
+ public OldFileFormatException() {
this("The configuration file has an old format.");
}
}
Modified: core/branches/flat/src/main/java/org/horizon/config/Option.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/config/Option.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/config/Option.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -23,13 +23,13 @@
/**
- * Used to override characteristics of specific calls to the cache. The javadocs of each of the setters below detail functionality and behaviour.
+ * Used to override characteristics of specific calls to the cache. The javadocs of each of the setters below detail
+ * functionality and behaviour.
*
* @author <a href="mailto:manik at jboss.org">Manik Surtani (manik at jboss.org)</a>
* @since 1.0
*/
-public class Option
-{
+public class Option {
private boolean failSilently;
private boolean cacheModeLocal;
private boolean suppressLocking;
@@ -47,18 +47,17 @@
/**
* @since 1.0
*/
- public boolean isSuppressLocking()
- {
+ public boolean isSuppressLocking() {
return suppressLocking;
}
/**
- * Suppresses acquiring locks for the given invocation. Used with pessimistic locking only. Use with extreme care, may lead to a breach in data integrity!
+ * Suppresses acquiring locks for the given invocation. Used with pessimistic locking only. Use with extreme care,
+ * may lead to a breach in data integrity!
*
* @since 1.0
*/
- public void setSuppressLocking(boolean suppressLocking)
- {
+ public void setSuppressLocking(boolean suppressLocking) {
this.suppressLocking = suppressLocking;
}
@@ -66,18 +65,19 @@
/**
* @since 1.0
*/
- public boolean isFailSilently()
- {
+ public boolean isFailSilently() {
return failSilently;
}
/**
- * suppress any failures in your cache operation, including version mismatches with optimistic locking, timeouts obtaining locks, transaction rollbacks. If this is option is set, the method invocation will __never fail or throw an exception__, although it may not succeed. With this option enabled the call will <b>not</b> participate in any ongoing transactions even if a transaction is running.
+ * suppress any failures in your cache operation, including version mismatches with optimistic locking, timeouts
+ * obtaining locks, transaction rollbacks. If this is option is set, the method invocation will __never fail or
+ * throw an exception__, although it may not succeed. With this option enabled the call will <b>not</b> participate
+ * in any ongoing transactions even if a transaction is running.
*
* @since 1.0
*/
- public void setFailSilently(boolean failSilently)
- {
+ public void setFailSilently(boolean failSilently) {
this.failSilently = failSilently;
}
@@ -86,108 +86,88 @@
*
* @since 1.0
*/
- public boolean isCacheModeLocal()
- {
+ public boolean isCacheModeLocal() {
return cacheModeLocal;
}
/**
- * overriding CacheMode from REPL_SYNC, REPL_ASYNC, INVALIDATION_SYNC, INVALIDATION_ASYNC to LOCAL. Only applies to put() and remove() methods on the cache.
+ * overriding CacheMode from REPL_SYNC, REPL_ASYNC, INVALIDATION_SYNC, INVALIDATION_ASYNC to LOCAL. Only applies to
+ * put() and remove() methods on the cache.
*
* @param cacheModeLocal
* @since 1.0
*/
- public void setCacheModeLocal(boolean cacheModeLocal)
- {
+ public void setCacheModeLocal(boolean cacheModeLocal) {
this.cacheModeLocal = cacheModeLocal;
}
/**
- * Gets whether replication or invalidation should be done asynchronously,
- * even if the cache is configured in a synchronous mode. Has no
- * effect if the call is occuring within a transactional context.
+ * Gets whether replication or invalidation should be done asynchronously, even if the cache is configured in a
+ * synchronous mode. Has no effect if the call is occuring within a transactional context.
*
- * @return <code>true</code> if replication/invalidation should be done
- * asynchronously; <code>false</code> if the default mode
- * configured for the cache should be used.
+ * @return <code>true</code> if replication/invalidation should be done asynchronously; <code>false</code> if the
+ * default mode configured for the cache should be used.
*/
- public boolean isForceAsynchronous()
- {
+ public boolean isForceAsynchronous() {
return forceAsynchronous;
}
/**
- * Sets whether replication or invalidation should be done asynchronously,
- * even if the cache is configured in a synchronous mode. Has no
- * effect if the call is occuring within a transactional context.
+ * Sets whether replication or invalidation should be done asynchronously, even if the cache is configured in a
+ * synchronous mode. Has no effect if the call is occuring within a transactional context.
*
- * @param forceAsynchronous <code>true</code> if replication/invalidation
- * should be done asynchronously; <code>false</code>
- * if the default mode configured for the cache
- * should be used.
+ * @param forceAsynchronous <code>true</code> if replication/invalidation should be done asynchronously;
+ * <code>false</code> if the default mode configured for the cache should be used.
*/
- public void setForceAsynchronous(boolean forceAsynchronous)
- {
+ public void setForceAsynchronous(boolean forceAsynchronous) {
this.forceAsynchronous = forceAsynchronous;
}
/**
- * Gets whether replication or invalidation should be done synchronously,
- * even if the cache is configured in an asynchronous mode. Has no
- * effect if the call is occuring within a transactional context.
+ * Gets whether replication or invalidation should be done synchronously, even if the cache is configured in an
+ * asynchronous mode. Has no effect if the call is occuring within a transactional context.
*
- * @return <code>true</code> if replication/invalidation should be done
- * synchronously; <code>false</code> if the default mode
- * configured for the cache should be used.
+ * @return <code>true</code> if replication/invalidation should be done synchronously; <code>false</code> if the
+ * default mode configured for the cache should be used.
*/
- public boolean isForceSynchronous()
- {
+ public boolean isForceSynchronous() {
return forceSynchronous;
}
/**
- * Sets whether replication or invalidation should be done synchronously,
- * even if the cache is configured in an asynchronous mode. Has no
- * effect if the call is occuring within a transactional context.
+ * Sets whether replication or invalidation should be done synchronously, even if the cache is configured in an
+ * asynchronous mode. Has no effect if the call is occuring within a transactional context.
*
- * @param forceSynchronous <code>true</code> if replication/invalidation
- * should be done synchronously; <code>false</code>
- * if the default mode configured for the cache
- * should be used.
+ * @param forceSynchronous <code>true</code> if replication/invalidation should be done synchronously;
+ * <code>false</code> if the default mode configured for the cache should be used.
*/
- public void setForceSynchronous(boolean forceSynchronous)
- {
+ public void setForceSynchronous(boolean forceSynchronous) {
this.forceSynchronous = forceSynchronous;
}
/**
* Gets any lock acquisition timeout configured for the call.
*
- * @return the time in ms that lock acquisition attempts should block
- * before failing with a TimeoutException. A value < 0 indicates
- * that the cache's default timeout should be used.
+ * @return the time in ms that lock acquisition attempts should block before failing with a TimeoutException. A
+ * value < 0 indicates that the cache's default timeout should be used.
*/
- public int getLockAcquisitionTimeout()
- {
+ public int getLockAcquisitionTimeout() {
return lockAcquisitionTimeout;
}
/**
* Sets any lock acquisition timeout configured for the call.
*
- * @param lockAcquisitionTimeout the time in ms that lock acquisition
- * attempts should block before failing with a
- * TimeoutException. A value < 0 indicates
- * that the cache's default timeout should be used.
+ * @param lockAcquisitionTimeout the time in ms that lock acquisition attempts should block before failing with a
+ * TimeoutException. A value < 0 indicates that the cache's default timeout should be
+ * used.
*/
- public void setLockAcquisitionTimeout(int lockAcquisitionTimeout)
- {
+ public void setLockAcquisitionTimeout(int lockAcquisitionTimeout) {
this.lockAcquisitionTimeout = lockAcquisitionTimeout;
}
@Override
- public String toString()
- {
+ public String toString() {
return "Option{" +
"failSilently=" + failSilently +
", cacheModeLocal=" + cacheModeLocal +
@@ -201,14 +181,11 @@
/**
* @return a new Option instance with all fields shallow-copied.
*/
- public Option copy()
- {
- try
- {
+ public Option copy() {
+ try {
return (Option) super.clone();
}
- catch (CloneNotSupportedException e)
- {
+ catch (CloneNotSupportedException e) {
// should never happen
throw new RuntimeException(e);
}
@@ -216,8 +193,7 @@
@Override
- public boolean equals(Object o)
- {
+ public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
@@ -235,8 +211,7 @@
}
@Override
- public int hashCode()
- {
+ public int hashCode() {
int result;
result = (failSilently ? 1 : 0);
result = 29 * result + (cacheModeLocal ? 1 : 0);
@@ -252,8 +227,7 @@
/**
* Resets this option to defaults.
*/
- public void reset()
- {
+ public void reset() {
this.cacheModeLocal = false;
this.failSilently = false;
this.suppressLocking = false;
@@ -270,8 +244,7 @@
* @param forceWriteLock
* @since 1.0
*/
- public void setForceWriteLock(boolean forceWriteLock)
- {
+ public void setForceWriteLock(boolean forceWriteLock) {
this.forceWriteLock = forceWriteLock;
}
@@ -281,8 +254,7 @@
*
* @since 1.0
*/
- public boolean isForceWriteLock()
- {
+ public boolean isForceWriteLock() {
return forceWriteLock;
}
@@ -291,8 +263,7 @@
*
* @since 1.0
*/
- public void setSkipCacheStatusCheck(boolean skipCacheStatusCheck)
- {
+ public void setSkipCacheStatusCheck(boolean skipCacheStatusCheck) {
this.skipCacheStatusCheck = skipCacheStatusCheck;
}
@@ -300,54 +271,52 @@
* @return true if skipCacheStatusCheck is true
* @since 1.0
*/
- public boolean isSkipCacheStatusCheck()
- {
+ public boolean isSkipCacheStatusCheck() {
return skipCacheStatusCheck;
}
/**
- * @return the value of the sync replication timeout (used when cache mode is either {@link org.horizon.config.Configuration.CacheMode#REPL_SYNC}
- * or {@link org.horizon.config.Configuration.CacheMode#INVALIDATION_SYNC}) to be used for this specific call, or -1 (default) if the
- * default value in {@link Configuration#getSyncReplTimeout()} is to be used instead.
+ * @return the value of the sync replication timeout (used when cache mode is either {@link
+ * org.horizon.config.Configuration.CacheMode#REPL_SYNC} or {@link org.horizon.config.Configuration.CacheMode#INVALIDATION_SYNC})
+ * to be used for this specific call, or -1 (default) if the default value in {@link
+ * Configuration#getSyncReplTimeout()} is to be used instead.
* @since 1.0
*/
- public long getSyncReplTimeout()
- {
+ public long getSyncReplTimeout() {
return syncReplTimeout;
}
/**
- * Used to override the value in {@link Configuration#getSyncReplTimeout()} (used when cache mode is either {@link org.horizon.config.Configuration.CacheMode#REPL_SYNC}
- * or {@link org.horizon.config.Configuration.CacheMode#INVALIDATION_SYNC}) for this specific invocation. Defaults to -1,
- * which means use the default in the configuration.
+ * Used to override the value in {@link Configuration#getSyncReplTimeout()} (used when cache mode is either {@link
+ * org.horizon.config.Configuration.CacheMode#REPL_SYNC} or {@link org.horizon.config.Configuration.CacheMode#INVALIDATION_SYNC})
+ * for this specific invocation. Defaults to -1, which means use the default in the configuration.
*
* @param syncReplTimeout new timeout value for this invocation.
* @since 1.0
*/
- public void setSyncReplTimeout(long syncReplTimeout)
- {
+ public void setSyncReplTimeout(long syncReplTimeout) {
this.syncReplTimeout = syncReplTimeout;
}
/**
- * If set to true, any persistence to a cache loader will be suppressed for the current invocation only. Does not apply to transactional calls.
+ * If set to true, any persistence to a cache loader will be suppressed for the current invocation only. Does not
+ * apply to transactional calls.
*
* @return true if persistence is suppressed.
* @since 1.0
*/
- public boolean isSuppressPersistence()
- {
+ public boolean isSuppressPersistence() {
return suppressPersistence;
}
/**
- * If set to true, any persistence to a cache loader will be suppressed for the current invocation only. Does not apply to transactional calls.
+ * If set to true, any persistence to a cache loader will be suppressed for the current invocation only. Does not
+ * apply to transactional calls.
*
* @param suppressPersistence if true, will suppress persistence.
* @since 1.0
*/
- public void setSuppressPersistence(boolean suppressPersistence)
- {
+ public void setSuppressPersistence(boolean suppressPersistence) {
this.suppressPersistence = suppressPersistence;
}
}
Modified: core/branches/flat/src/main/java/org/horizon/config/PluggableConfigurationComponent.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/config/PluggableConfigurationComponent.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/config/PluggableConfigurationComponent.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -33,36 +33,30 @@
* @author Manik Surtani (<a href="mailto:manik at jboss.org">manik at jboss.org</a>)
* @since 1.0
*/
-public abstract class PluggableConfigurationComponent extends ConfigurationComponent
-{
+public abstract class PluggableConfigurationComponent extends ConfigurationComponent {
protected String className;
protected Properties properties;
- public String getClassName()
- {
+ public String getClassName() {
return className;
}
- public void setClassName(String className)
- {
+ public void setClassName(String className) {
if (className == null || className.length() == 0) return;
testImmutability("className");
this.className = className;
}
- public Properties getProperties()
- {
+ public Properties getProperties() {
return properties;
}
- public void setProperties(Properties properties)
- {
+ public void setProperties(Properties properties) {
testImmutability("properties");
this.properties = properties;
}
- public void setProperties(String properties) throws IOException
- {
+ public void setProperties(String properties) throws IOException {
if (properties == null) return;
testImmutability("properties");
@@ -75,8 +69,7 @@
is.close();
}
- public boolean equals(Object o)
- {
+ public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
@@ -88,8 +81,7 @@
return true;
}
- public int hashCode()
- {
+ public int hashCode() {
int result;
result = (className != null ? className.hashCode() : 0);
result = 31 * result + (properties != null ? properties.hashCode() : 0);
@@ -97,15 +89,13 @@
}
@Override
- public String toString()
- {
+ public String toString() {
return getClass().getSimpleName() + " {className = " + className +
", properties=" + properties + "}";
}
@Override
- public PluggableConfigurationComponent clone() throws CloneNotSupportedException
- {
+ public PluggableConfigurationComponent clone() throws CloneNotSupportedException {
PluggableConfigurationComponent clone = (PluggableConfigurationComponent) super.clone();
if (properties != null) clone.properties = (Properties) properties.clone();
return clone;
Modified: core/branches/flat/src/main/java/org/horizon/config/RuntimeConfig.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/config/RuntimeConfig.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/config/RuntimeConfig.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -30,8 +30,7 @@
import javax.transaction.TransactionManager;
import java.util.concurrent.ExecutorService;
-public class RuntimeConfig extends ConfigurationComponent
-{
+public class RuntimeConfig extends ConfigurationComponent {
/**
* The serialVersionUID
*/
@@ -48,8 +47,7 @@
/**
* Resets the runtime to default values.
*/
- public void reset()
- {
+ public void reset() {
channel = null;
rpcManager = null;
}
@@ -60,175 +58,145 @@
*
* @return the channel, or <code>null</code> if not set
*/
- public ChannelFactory getMuxChannelFactory()
- {
+ public ChannelFactory getMuxChannelFactory() {
return muxChannelFactory;
}
/**
- * Sets the factory the cache should use to create a multiplexed channel.
- * Ignored if a Channel is directly configured via
- * {@link #setChannel(Channel)}. If the channel factory is set,
- * {@link Configuration#setMultiplexerStack(String)} must also be set, or
- * a <code>CacheException</code> will be thrown during cache startup.
+ * Sets the factory the cache should use to create a multiplexed channel. Ignored if a Channel is directly configured
+ * via {@link #setChannel(Channel)}. If the channel factory is set, {@link Configuration#setMultiplexerStack(String)}
+ * must also be set, or a <code>CacheException</code> will be thrown during cache startup.
*
* @param multiplexerChannelFactory channel factory
*/
- public void setMuxChannelFactory(ChannelFactory multiplexerChannelFactory)
- {
+ public void setMuxChannelFactory(ChannelFactory multiplexerChannelFactory) {
testImmutability("muxChannelFactory");
this.muxChannelFactory = multiplexerChannelFactory;
}
/**
- * Gets the channel the cache is using.
- * <p/>
- * External callers should use extreme care if they access the channel.
- * The cache expects it has exclusive access to the channel; external code
- * trying to send or receive messages via the channel will almost certainly
- * disrupt the operation of the cache.
- * </p>
+ * Gets the channel the cache is using. <p/> External callers should use extreme care if they access the channel. The
+ * cache expects it has exclusive access to the channel; external code trying to send or receive messages via the
+ * channel will almost certainly disrupt the operation of the cache. </p>
*
- * @return the channel. May return <code>null</code> if the channel was
- * not externally set via {@link #setChannel(Channel)} and the
- * cache has not yet been started.
+ * @return the channel. May return <code>null</code> if the channel was not externally set via {@link
+ * #setChannel(Channel)} and the cache has not yet been started.
* @see #setChannel(Channel)
*/
- public Channel getChannel()
- {
+ public Channel getChannel() {
return channel;
}
/**
- * Sets the channel the cache will use. The channel should not be
- * connected or closed.
- * <p/>
- * External callers should use extreme care if they access the channel.
- * The cache expects it has exclusive access to the channel; external code
- * trying to send or receive messages via the channel will almost certainly
- * disrupt the operation of the cache.
- * </p>
- * <p/>
- * If an application wishes to send and receive messages using the same
- * underlying channel as the <ocde>Cache</code>, a multiplexed channel should
- * be used. Two separate mux channels should be created from the same
- * <code>ChannelFactory</code> using the same <i>stack name</i> but different
- * <code>id</code>s.
- * See {@link ChannelFactory#createMultiplexerChannel(String,String,boolean,String)}.
- * These two mux channels will share the same underlying channel. One of the
- * two mux channels can be injected into the cache; the other can be used by
- * the application. The cache will not see the application messages and vice versa.
- * </p>
- * <p/>
- * Configuring the cache to use a mux channel can also be done by configuring
- * {@link #setMuxChannelFactory(ChannelFactory) the channel factory} and the
- * {@link Configuration#setMultiplexerStack(String) stack name}, in which case
- * the cache will create and use a mux channel.
- * </p>
+ * Sets the channel the cache will use. The channel should not be connected or closed. <p/> External callers should
+ * use extreme care if they access the channel. The cache expects it has exclusive access to the channel; external
+ * code trying to send or receive messages via the channel will almost certainly disrupt the operation of the cache.
+ * </p> <p/> If an application wishes to send and receive messages using the same underlying channel as the
+ * <ocde>Cache</code>, a multiplexed channel should be used. Two separate mux channels should be created from the
+ * same <code>ChannelFactory</code> using the same <i>stack name</i> but different <code>id</code>s. See {@link
+ * ChannelFactory#createMultiplexerChannel(String,String,boolean,String)}. These two mux channels will share the same
+ * underlying channel. One of the two mux channels can be injected into the cache; the other can be used by the
+ * application. The cache will not see the application messages and vice versa. </p> <p/> Configuring the cache to
+ * use a mux channel can also be done by configuring {@link #setMuxChannelFactory(ChannelFactory) the channel
+ * factory} and the {@link Configuration#setMultiplexerStack(String) stack name}, in which case the cache will create
+ * and use a mux channel. </p>
*
* @param channel channel to set
*/
- public void setChannel(Channel channel)
- {
+ public void setChannel(Channel channel) {
this.channel = channel;
}
- public TransactionManager getTransactionManager()
- {
+ public TransactionManager getTransactionManager() {
return transactionManager;
}
- public void setTransactionManager(TransactionManager transactionManager)
- {
+ public void setTransactionManager(TransactionManager transactionManager) {
testImmutability("transactionManager");
this.transactionManager = transactionManager;
}
/**
- * This is only relevant if an eviction timer thread factory has been set using {@link #setEvictionTimerThreadFactory(org.jgroups.util.ThreadFactory)}.
- * Will return a null if the eviction timer thread factory needs to be created internally.
+ * This is only relevant if an eviction timer thread factory has been set using {@link
+ * #setEvictionTimerThreadFactory(org.jgroups.util.ThreadFactory)}. Will return a null if the eviction timer thread
+ * factory needs to be created internally.
* <p/>
*
* @return the thread factory used by the eviction timer's scheduled executor.
* @since 1.0
*/
- public ThreadFactory getEvictionTimerThreadFactory()
- {
+ public ThreadFactory getEvictionTimerThreadFactory() {
return evictionTimerThreadFactory;
}
/**
- * Sets the eviction timer thread factory to use when creating a scheduled executor. If this is not set, the eviction
- * timer task will use a default thread factory.
+ * Sets the eviction timer thread factory to use when creating a scheduled executor. If this is not set, the
+ * eviction timer task will use a default thread factory.
*
* @param evictionTimerThreadFactory factory to use
* @since 1.0
*/
- public void setEvictionTimerThreadFactory(ThreadFactory evictionTimerThreadFactory)
- {
+ public void setEvictionTimerThreadFactory(ThreadFactory evictionTimerThreadFactory) {
this.evictionTimerThreadFactory = evictionTimerThreadFactory;
}
/**
- * This is only relevant if the async cache replication executor has been set using {@link #setAsyncSerializationExecutor(java.util.concurrent.ExecutorService)}.
- * If the executor is created internally, this method will return null.
+ * This is only relevant if the async cache replication executor has been set using {@link
+ * #setAsyncSerializationExecutor(java.util.concurrent.ExecutorService)}. If the executor is created internally, this
+ * method will return null.
* <p/>
*
* @return the executor used for async replication.
* @since 1.0
*/
- public ExecutorService getAsyncSerializationExecutor()
- {
+ public ExecutorService getAsyncSerializationExecutor() {
return asyncSerializationExecutor;
}
/**
- * This is used to set the executor to use for async cache replucation, and effectively overrides {@link Configuration#setSerializationExecutorPoolSize(int)}
+ * This is used to set the executor to use for async cache replucation, and effectively overrides {@link
+ * Configuration#setSerializationExecutorPoolSize(int)}
* <p/>
*
* @param asyncSerializationExecutor executor to set
* @since 1.0
*/
- public void setAsyncSerializationExecutor(ExecutorService asyncSerializationExecutor)
- {
+ public void setAsyncSerializationExecutor(ExecutorService asyncSerializationExecutor) {
this.asyncSerializationExecutor = asyncSerializationExecutor;
}
/**
- * This is only relevant if the async cache listener executor has been set using {@link #setAsyncCacheListenerExecutor(java.util.concurrent.ExecutorService)}.
- * If the executor is created internally, this method will return null.
+ * This is only relevant if the async cache listener executor has been set using {@link
+ * #setAsyncCacheListenerExecutor(java.util.concurrent.ExecutorService)}. If the executor is created internally, this
+ * method will return null.
* <p/>
*
* @return the executor to use for async cache listeners
* @since 1.0
*/
- public ExecutorService getAsyncCacheListenerExecutor()
- {
+ public ExecutorService getAsyncCacheListenerExecutor() {
return asyncCacheListenerExecutor;
}
/**
- * This is used to set the executor to use for async cache listeners, and effectively overrides {@link Configuration#setListenerAsyncPoolSize(int)}
+ * This is used to set the executor to use for async cache listeners, and effectively overrides {@link
+ * Configuration#setListenerAsyncPoolSize(int)}
* <p/>
*
* @param asyncCacheListenerExecutor the executor to use for async cache listeners
* @since 1.0
*/
- public void setAsyncCacheListenerExecutor(ExecutorService asyncCacheListenerExecutor)
- {
+ public void setAsyncCacheListenerExecutor(ExecutorService asyncCacheListenerExecutor) {
this.asyncCacheListenerExecutor = asyncCacheListenerExecutor;
}
@Override
- public boolean equals(Object obj)
- {
- if (this == obj)
- {
+ public boolean equals(Object obj) {
+ if (this == obj) {
return true;
}
- if (obj instanceof RuntimeConfig)
- {
+ if (obj instanceof RuntimeConfig) {
RuntimeConfig other = (RuntimeConfig) obj;
return Util.safeEquals(transactionManager, other.transactionManager)
&& Util.safeEquals(muxChannelFactory, other.muxChannelFactory)
@@ -243,8 +211,7 @@
}
@Override
- public int hashCode()
- {
+ public int hashCode() {
int result = 17;
result = result * 29 + (transactionManager == null ? 0 : transactionManager.hashCode());
result = result * 29 + (muxChannelFactory == null ? 0 : muxChannelFactory.hashCode());
@@ -256,19 +223,16 @@
return result;
}
- public void setRPCManager(RPCManager rpcManager)
- {
+ public void setRPCManager(RPCManager rpcManager) {
this.rpcManager = rpcManager;
}
- public RPCManager getRPCManager()
- {
+ public RPCManager getRPCManager() {
return rpcManager;
}
@Override
- public RuntimeConfig clone() throws CloneNotSupportedException
- {
+ public RuntimeConfig clone() throws CloneNotSupportedException {
return (RuntimeConfig) super.clone();
}
}
Modified: core/branches/flat/src/main/java/org/horizon/config/UnsupportedEvictionImplException.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/config/UnsupportedEvictionImplException.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/config/UnsupportedEvictionImplException.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -27,25 +27,20 @@
* @author Manik Surtani (<a href="mailto:manik at jboss.org">manik at jboss.org</a>)
* @since 1.0
*/
-public class UnsupportedEvictionImplException extends ConfigurationException
-{
- public UnsupportedEvictionImplException(Exception e)
- {
+public class UnsupportedEvictionImplException extends ConfigurationException {
+ public UnsupportedEvictionImplException(Exception e) {
super(e);
}
- public UnsupportedEvictionImplException(String string)
- {
+ public UnsupportedEvictionImplException(String string) {
super(string);
}
- public UnsupportedEvictionImplException(String string, String erroneousAttribute)
- {
+ public UnsupportedEvictionImplException(String string, String erroneousAttribute) {
super(string, erroneousAttribute);
}
- public UnsupportedEvictionImplException(String string, Throwable throwable)
- {
+ public UnsupportedEvictionImplException(String string, Throwable throwable) {
super(string, throwable);
}
}
Modified: core/branches/flat/src/main/java/org/horizon/config/XmlParsingConfigurationRegistry.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/config/XmlParsingConfigurationRegistry.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/config/XmlParsingConfigurationRegistry.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -29,82 +29,66 @@
import java.util.Set;
/**
- * {@link ConfigurationRegistry} that obtains its initial set of configurations
- * by parsing an XML document.
+ * {@link ConfigurationRegistry} that obtains its initial set of configurations by parsing an XML document.
*
* @author <a href="brian.stansberry at jboss.com">Brian Stansberry</a>
* @since 1.0
*/
-public class XmlParsingConfigurationRegistry implements ConfigurationRegistry
-{
+public class XmlParsingConfigurationRegistry implements ConfigurationRegistry {
private final CacheConfigsXmlParser parser;
private final String configResource;
private final Map<String, Configuration> configs = new Hashtable<String, Configuration>();
private boolean started;
- public XmlParsingConfigurationRegistry(String configResource)
- {
+ public XmlParsingConfigurationRegistry(String configResource) {
parser = new CacheConfigsXmlParser();
this.configResource = configResource;
}
- public void start() throws Exception
- {
- if (!started)
- {
+ public void start() throws Exception {
+ if (!started) {
if (configResource != null)
configs.putAll(parser.parseConfigs(configResource));
started = true;
}
}
- public void stop()
- {
- if (started)
- {
- synchronized (configs)
- {
+ public void stop() {
+ if (started) {
+ synchronized (configs) {
configs.clear();
}
started = false;
}
}
- public String getConfigResource()
- {
+ public String getConfigResource() {
return configResource;
}
- public Set<String> getConfigurationNames()
- {
+ public Set<String> getConfigurationNames() {
return new HashSet<String>(configs.keySet());
}
public void registerConfiguration(String configName, Configuration config)
- throws CloneNotSupportedException
- {
- synchronized (configs)
- {
+ throws CloneNotSupportedException {
+ synchronized (configs) {
if (configs.containsKey(configName))
throw new IllegalStateException(configName + " already registered");
configs.put(configName, config.clone());
}
}
- public void unregisterConfiguration(String configName)
- {
- synchronized (configs)
- {
+ public void unregisterConfiguration(String configName) {
+ synchronized (configs) {
if (configs.remove(configName) == null)
throw new IllegalStateException(configName + " not registered");
}
}
- public Configuration getConfiguration(String configName)
- {
+ public Configuration getConfiguration(String configName) {
Configuration config;
- synchronized (configs)
- {
+ synchronized (configs) {
config = configs.get(configName);
}
Modified: core/branches/flat/src/main/java/org/horizon/config/parsing/CacheConfigsXmlParser.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/config/parsing/CacheConfigsXmlParser.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/config/parsing/CacheConfigsXmlParser.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -35,8 +35,7 @@
import java.util.Map;
/**
- * Parser able to parse a series of cache configurations stored in an
- * XML document with the following structure:
+ * Parser able to parse a series of cache configurations stored in an XML document with the following structure:
* <pre>
* <cache-configs>
* <cache-config name="configA">
@@ -48,55 +47,47 @@
* </cache-configs>
* </pre>
* <p/>
- * The '....' represents the normal content of the mbean element in a
- * JBC -service.xml config file.
+ * The '....' represents the normal content of the mbean element in a JBC -service.xml config file.
*
* @author <a href="brian.stansberry at jboss.com">Brian Stansberry</a>
- *
* @since 1.0
*/
-public class CacheConfigsXmlParser
-{
+public class CacheConfigsXmlParser {
/**
* Name of the root element in a cache configs XML document
*/
public static final String DOCUMENT_ROOT = "cache-configs";
/**
- * Name of the element that represents an individual cache configuration
- * in a cache configs XML document.
+ * Name of the element that represents an individual cache configuration in a cache configs XML document.
*/
public static final String CONFIG_ROOT = "cache-config";
public static final String QUALIFIED_CONFIG_ROOT = "registry:cache-config";
/**
- * Name of the attribute in a {@link #CONFIG_ROOT cache-config} element that specifies
- * the name of the configuration.
+ * Name of the attribute in a {@link #CONFIG_ROOT cache-config} element that specifies the name of the
+ * configuration.
*/
public static final String CONFIG_NAME = "name";
private static final Log log = LogFactory.getLog(CacheConfigsXmlParser.class);
- public Map<String, Configuration> parseConfigs(String fileName) throws CloneNotSupportedException
- {
+ public Map<String, Configuration> parseConfigs(String fileName) throws CloneNotSupportedException {
FileLookup fileLookup = new FileLookup();
InputStream is = fileLookup.lookupFile(fileName);
- if (is == null)
- {
+ if (is == null) {
throw new ConfigurationException("Unable to find config file " + fileName + " either in classpath or on the filesystem!");
}
return parseConfigs(is);
}
- public Map<String, Configuration> parseConfigs(InputStream stream) throws CloneNotSupportedException
- {
+ public Map<String, Configuration> parseConfigs(InputStream stream) throws CloneNotSupportedException {
// loop through all elements in XML.
Element root = getDocumentRoot(stream);
NodeList list = root.getElementsByTagName(CONFIG_ROOT);
- if (list == null || list.getLength() == 0)
- {
+ if (list == null || list.getLength() == 0) {
// try looking for a QUALIFIED_CONFIG_ROOT
list = root.getElementsByTagName(QUALIFIED_CONFIG_ROOT);
if (list == null || list.getLength() == 0)
@@ -105,11 +96,9 @@
Map<String, Configuration> result = new HashMap<String, Configuration>();
- for (int i = 0; i < list.getLength(); i++)
- {
+ for (int i = 0; i < list.getLength(); i++) {
Node node = list.item(i);
- if (node.getNodeType() != Node.ELEMENT_NODE)
- {
+ if (node.getNodeType() != Node.ELEMENT_NODE) {
continue;
}
@@ -120,8 +109,7 @@
XmlConfigurationParserJBC3 parser = new XmlConfigurationParserJBC3();
Configuration c = null;
- if (parser.isValidElementRoot(element))
- {
+ if (parser.isValidElementRoot(element)) {
c = parser.parseElementIgnoringRoot(element);
}
@@ -133,8 +121,7 @@
return result;
}
- private Element getDocumentRoot(InputStream stream)
- {
+ private Element getDocumentRoot(InputStream stream) {
RootElementBuilder rootElementBuilder = new RootElementBuilder(false);
return rootElementBuilder.readRoot(stream);
}
Modified: core/branches/flat/src/main/java/org/horizon/config/parsing/ConfigFilesConvertor.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/config/parsing/ConfigFilesConvertor.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/config/parsing/ConfigFilesConvertor.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -34,7 +34,12 @@
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
-import java.io.*;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
/**
* Class used for converting a config file from from 2.x version to 3.x verison.
@@ -42,15 +47,13 @@
* @author Mircea.Markus at jboss.com
* @since 1.0
*/
-public class ConfigFilesConvertor
-{
+public class ConfigFilesConvertor {
/**
* Writes to the <b>os</b> the 3.x configuration file resulted by transforming the 2.x configuration file passed in
* as <b>is</b>. Transformation is performed according to the <b>xsltFile</b>. The xslt file is looked up using a
* {@link org.horizon.util.FileLookup}
*/
- public void parse(InputStream is, OutputStream os, String xsltFile) throws Exception
- {
+ public void parse(InputStream is, OutputStream os, String xsltFile) throws Exception {
InputStream xsltInStream = new FileLookup().lookupFile(xsltFile);
Document document = getInputDocument(is);
@@ -66,18 +69,15 @@
/**
* Writes to the <b>os</b> the 3.x configuration file resulted by transforming the 2.x configuration file passed in
- * as <b>inputFile</b>. Transformation is performed according to the <b>xsltFile</b>. Both <b>inputFile</b> and he xslt
- * file are looked up using a {@link org.horizon.util.FileLookup}
+ * as <b>inputFile</b>. Transformation is performed according to the <b>xsltFile</b>. Both <b>inputFile</b> and he
+ * xslt file are looked up using a {@link org.horizon.util.FileLookup}
*/
- public void parse(String inputFile, OutputStream os, String xsltFile) throws Exception
- {
+ public void parse(String inputFile, OutputStream os, String xsltFile) throws Exception {
InputStream stream = new FileLookup().lookupFile(inputFile);
- try
- {
+ try {
parse(stream, os, xsltFile);
}
- finally
- {
+ finally {
stream.close();
}
}
@@ -85,23 +85,19 @@
/**
* usage : java ConfigFilesConvertor -Dsource=config-2.x.xml -Ddestination=config-3.x.xnl
*/
- public static void main(String[] argv) throws Exception
- {
+ public static void main(String[] argv) throws Exception {
String sourceName = System.getProperty("source");
- if (sourceName == null)
- {
+ if (sourceName == null) {
System.err.println("Missing property 'source'.");
System.exit(1);
}
String destinationName = System.getProperty("destination");
- if (destinationName == null)
- {
+ if (destinationName == null) {
System.err.println("Missing property 'destination'.");
System.exit(1);
}
File oldConfig = new File(sourceName);
- if (!oldConfig.exists())
- {
+ if (!oldConfig.exists()) {
System.err.println("File specified as input ('" + sourceName + ") does not exist.");
System.exit(1);
}
@@ -117,16 +113,14 @@
}
private Transformer getTransformer(InputStream xsltInStream)
- throws TransformerConfigurationException
- {
+ throws TransformerConfigurationException {
TransformerFactory tFactory = TransformerFactory.newInstance();
StreamSource stylesource = new StreamSource(xsltInStream);
return tFactory.newTransformer(stylesource);
}
private Document getInputDocument(InputStream is)
- throws ParserConfigurationException, SAXException, IOException
- {
+ throws ParserConfigurationException, SAXException, IOException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
return builder.parse(is);
Modified: core/branches/flat/src/main/java/org/horizon/config/parsing/JGroupsStackParser.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/config/parsing/JGroupsStackParser.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/config/parsing/JGroupsStackParser.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -27,77 +27,65 @@
import org.w3c.dom.NodeList;
/**
- * The purpose of this class is to parse the jgroups configuration from the config file into an compact string
- * that can be passed as a config to the channel.
+ * The purpose of this class is to parse the jgroups configuration from the config file into an compact string that can
+ * be passed as a config to the channel.
*
* @author Mircea.Markus at jboss.com
* @since 1.0
*/
-public class JGroupsStackParser
-{
+public class JGroupsStackParser {
/**
* Parses the cluster config which is used to start a JGroups channel
*
* @param config an old-style JGroups protocol config String
*/
- public String parseClusterConfigXml(Element config)
- {
+ public String parseClusterConfigXml(Element config) {
StringBuilder buffer = new StringBuilder();
NodeList stack = config.getChildNodes();
int length = stack.getLength();
- for (int s = 0; s < length; s++)
- {
+ for (int s = 0; s < length; s++) {
org.w3c.dom.Node node = stack.item(s);
- if (node.getNodeType() != org.w3c.dom.Node.ELEMENT_NODE)
- {
+ if (node.getNodeType() != org.w3c.dom.Node.ELEMENT_NODE) {
continue;
}
// Ignore Namespace until JGroups defines one
Element tag = (Element) node;
String protocol = tag.getLocalName();
- if (protocol == null)
- {
+ if (protocol == null) {
protocol = tag.getNodeName(); // try a non-namespace aware version
}
buffer.append(protocol);
processAttributes(buffer, tag);
buffer.append(':');
}
- if (buffer.length() > 0)
- {
+ if (buffer.length() > 0) {
//Remove the trailing ':'
buffer.setLength(buffer.length() - 1);
}
return buffer.toString();
}
- private void processAttributes(StringBuilder buffer, Element tag)
- {
+ private void processAttributes(StringBuilder buffer, Element tag) {
NamedNodeMap attrs = tag.getAttributes();
int attrLength = attrs.getLength();
- if (attrLength > 0)
- {
+ if (attrLength > 0) {
buffer.append('(');
}
- for (int a = 0; a < attrLength; a++)
- {
+ for (int a = 0; a < attrLength; a++) {
Attr attr = (Attr) attrs.item(a);
processSingleAttribute(buffer, attr);
- if (a < attrLength - 1)
- {
+ if (a < attrLength - 1) {
buffer.append(';');
}
}
- if (attrLength > 0)
- {
+ if (attrLength > 0) {
buffer.append(')');
}
}
- private void processSingleAttribute(StringBuilder buffer, Attr attr)
- {
+ private void processSingleAttribute(StringBuilder buffer, Attr attr) {
String name = attr.getName();
String value = attr.getValue();
buffer.append(name);
Modified: core/branches/flat/src/main/java/org/horizon/config/parsing/ParsedAttributes.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/config/parsing/ParsedAttributes.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/config/parsing/ParsedAttributes.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -31,13 +31,11 @@
* @author Mircea.Markus at jboss.com
* @since 1.0
*/
-public class ParsedAttributes
-{
+public class ParsedAttributes {
public final Map<String, String> stringAttribs;
public final Map<String, Element> xmlAttribs;
- ParsedAttributes(Map strings, Map elements)
- {
+ ParsedAttributes(Map strings, Map elements) {
this.stringAttribs = strings;
this.xmlAttribs = elements;
}
Modified: core/branches/flat/src/main/java/org/horizon/config/parsing/RootElementBuilder.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/config/parsing/RootElementBuilder.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/config/parsing/RootElementBuilder.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -36,22 +36,20 @@
import java.io.InputStream;
/**
- * Parses an xml files and validates xml elements form {@link RootElementBuilder#JBOSSCACHE_CORE_NS} namespace
- * according to the configured schema.
+ * Parses an xml files and validates xml elements form {@link RootElementBuilder#JBOSSCACHE_CORE_NS} namespace according
+ * to the configured schema.
*
* @author Mircea.Markus at jboss.com
* @since 1.0
*/
-public class RootElementBuilder
-{
+public class RootElementBuilder {
private static final JBossEntityResolver resolver = new JBossEntityResolver();
public static final String JBOSSCACHE_CORE_NS = "urn:jboss:starobrno-core:config:1.0";
public static final String JBOSSCACHE_REPO_NS = "urn:jboss:starobrno-core:cache-repo:1.0";
- static
- {
+ static {
// Globally register this namespace
JBossEntityResolver.registerEntity(JBOSSCACHE_CORE_NS, "starobrno-config-1.0.xsd");
JBossEntityResolver.registerEntity(JBOSSCACHE_REPO_NS, "starobrno-registry-1.0.xsd");
@@ -62,36 +60,29 @@
private boolean isValidating;
public static final String VALIDATING_SYSTEM_PROPERTY = "jbosscache.config.validate";
- public RootElementBuilder(ErrorHandler errorHandler)
- {
+ public RootElementBuilder(ErrorHandler errorHandler) {
this.errorHandler = errorHandler;
isValidating = System.getProperty(VALIDATING_SYSTEM_PROPERTY) == null || Boolean.getBoolean(VALIDATING_SYSTEM_PROPERTY);
}
- public RootElementBuilder(ErrorHandler errorHandler, boolean validating)
- {
+ public RootElementBuilder(ErrorHandler errorHandler, boolean validating) {
this.errorHandler = errorHandler;
isValidating = validating;
}
- public RootElementBuilder()
- {
+ public RootElementBuilder() {
this(new FailureErrorHandler());
}
- public RootElementBuilder(boolean validating)
- {
+ public RootElementBuilder(boolean validating) {
this(new FailureErrorHandler(), validating);
}
- public Element readRoot(InputStream config)
- {
- try
- {
+ public Element readRoot(InputStream config) {
+ try {
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
docBuilderFactory.setNamespaceAware(true);
- if (isValidating)
- {
+ if (isValidating) {
docBuilderFactory.setValidating(true);
docBuilderFactory.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaLanguage", "http://www.w3.org/2001/XMLSchema");
String[] value = {JBOSSCACHE_CORE_NS, JBOSSCACHE_REPO_NS};
@@ -105,8 +96,7 @@
root.normalize();
return root;
}
- catch (Exception e)
- {
+ catch (Exception e) {
log.error(e);
throw new ConfigurationException("Could not parse the config file");
}
@@ -115,32 +105,26 @@
/**
* Default schema validation error handler, that throws an exception on validation errors.
*/
- private static class FailureErrorHandler implements ErrorHandler
- {
- public void warning(SAXParseException exception) throws SAXException
- {
+ private static class FailureErrorHandler implements ErrorHandler {
+ public void warning(SAXParseException exception) throws SAXException {
logAndThrowException(exception);
}
- public void error(SAXParseException exception) throws SAXException
- {
+ public void error(SAXParseException exception) throws SAXException {
logAndThrowException(exception);
}
- public void fatalError(SAXParseException exception) throws SAXException
- {
+ public void fatalError(SAXParseException exception) throws SAXException {
logAndThrowException(exception);
}
- private void logAndThrowException(SAXParseException exception)
- {
+ private void logAndThrowException(SAXParseException exception) {
log.error("Configuration warning: " + exception.getMessage());
throw new ConfigurationException("Incorrect configuration file. Use '-Djbosscache.config.validate=false' to disable validation.", exception);
}
}
- public boolean isValidating()
- {
+ public boolean isValidating() {
return isValidating;
}
}
Modified: core/branches/flat/src/main/java/org/horizon/config/parsing/XmlConfigHelper.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/config/parsing/XmlConfigHelper.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/config/parsing/XmlConfigHelper.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -26,7 +26,11 @@
import org.horizon.config.ConfigurationException;
import org.horizon.util.BeanUtils;
import org.jboss.util.StringPropertyReplacer;
-import org.w3c.dom.*;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.w3c.dom.Node;
+import org.w3c.dom.NodeList;
+import org.w3c.dom.Text;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
@@ -55,8 +59,7 @@
* @author <a href="mailto:manik at jboss.org">Manik Surtani (manik at jboss.org)</a>
* @since 1.0
*/
-public class XmlConfigHelper
-{
+public class XmlConfigHelper {
private static final Log log = LogFactory.getLog(XmlConfigHelper.class);
/**
@@ -82,8 +85,8 @@
/**
- * Returns the contents of a specific node of given element name, provided a certain attribute exists and is set to value.
- * E.g., if you have a {@link Element} which represents the following XML snippet:
+ * Returns the contents of a specific node of given element name, provided a certain attribute exists and is set to
+ * value. E.g., if you have a {@link Element} which represents the following XML snippet:
* <pre>
* <ItemQuantity Colour="Red">100</ItemQuantity>
* <ItemQuantity Colour="Blue">30</ItemQuantity>
@@ -109,20 +112,17 @@
* @param attributeName - attribute name of the element that would contain the expected value.
* @return the contents of the matched element, or null if not found/matched
*/
- public static String getTagContents(Element elem, String value, String elementName, String attributeName)
- {
+ public static String getTagContents(Element elem, String value, String elementName, String attributeName) {
NodeList list = elem.getElementsByTagName(elementName);
- for (int s = 0; s < list.getLength(); s++)
- {
+ for (int s = 0; s < list.getLength(); s++) {
org.w3c.dom.Node node = list.item(s);
if (node.getNodeType() != org.w3c.dom.Node.ELEMENT_NODE)
continue;
Element element = (Element) node;
String name = element.getAttribute(attributeName);
- if (name.equals(value))
- {
+ if (name.equals(value)) {
return getElementContent(element, true);
}
}
@@ -130,10 +130,8 @@
}
/**
- * Retrieves the value of a given attribute for the first encountered instance of a tag in an element.
- * <p/>
- * E.g., if you have a {@link Element} which represents the following XML snippet:
- * </p>
+ * Retrieves the value of a given attribute for the first encountered instance of a tag in an element. <p/> E.g., if
+ * you have a {@link Element} which represents the following XML snippet: </p>
* <pre>
* <ItemQuantity Colour="Red">100</ItemQuantity>
* <ItemQuantity Colour="Blue">30</ItemQuantity>
@@ -154,12 +152,10 @@
* @param attributeName - attribute name of the element that would contain the expected value.
* @return the contents of the matched attribute, or null if not found/matched
*/
- public static String getAttributeValue(Element elem, String elementName, String attributeName)
- {
+ public static String getAttributeValue(Element elem, String elementName, String attributeName) {
NodeList list = elem.getElementsByTagName(elementName);
- for (int s = 0; s < list.getLength(); s++)
- {
+ for (int s = 0; s < list.getLength(); s++) {
org.w3c.dom.Node node = list.item(s);
if (node.getNodeType() != org.w3c.dom.Node.ELEMENT_NODE)
continue;
@@ -181,14 +177,11 @@
* @param subElementName - the name of a sub element to look for
* @return the first matching sub element, if found, or null otherwise.
*/
- public static Element getSubElement(Element element, String subElementName)
- {
+ public static Element getSubElement(Element element, String subElementName) {
NodeList nl = element.getChildNodes();
- for (int i = 0; i < nl.getLength(); i++)
- {
+ for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
- if (node.getNodeType() == Node.ELEMENT_NODE && subElementName.equals(((Element) node).getTagName()))
- {
+ if (node.getNodeType() == Node.ELEMENT_NODE && subElementName.equals(((Element) node).getTagName())) {
return (Element) node;
}
}
@@ -206,15 +199,12 @@
* @param trim - if true, whitespace is trimmed before returning
* @return the contents of the element passed in. Will return an empty String if the element is empty.
*/
- public static String getElementContent(Element element, boolean trim)
- {
+ public static String getElementContent(Element element, boolean trim) {
NodeList nl = element.getChildNodes();
String attributeText = "";
- for (int i = 0; i < nl.getLength(); i++)
- {
+ for (int i = 0; i < nl.getLength(); i++) {
Node n = nl.item(i);
- if (n instanceof Text)
- {
+ if (n instanceof Text) {
attributeText += StringPropertyReplacer.replaceProperties(((Text) n).getData());
}
} // end of for ()
@@ -232,29 +222,22 @@
* @param elementName - name of the element to find within the element passed in
* @return may return an empty String of not found.
*/
- public static String readStringContents(Element element, String elementName)
- {
+ public static String readStringContents(Element element, String elementName) {
NodeList nodes = element.getElementsByTagName(elementName);
- if (nodes.getLength() > 0)
- {
+ if (nodes.getLength() > 0) {
Node node = nodes.item(0);
Element ne = (Element) node;
NodeList nl2 = ne.getChildNodes();
Node node2 = nl2.item(0);
- if (node2 != null)
- {
+ if (node2 != null) {
String value = node2.getNodeValue();
if (value == null)
return "";
return StringPropertyReplacer.replaceProperties(value.trim());
- }
- else
- {
+ } else {
return "";
}
- }
- else
- {
+ } else {
return "";
}
}
@@ -265,20 +248,16 @@
* @param value String to escape. Cannot be null.
* @return escaped String. Never is null.
*/
- public static String escapeBackslashes(String value)
- {
+ public static String escapeBackslashes(String value) {
StringBuilder buf = new StringBuilder(value);
- for (int looper = 0; looper < buf.length(); looper++)
- {
+ for (int looper = 0; looper < buf.length(); looper++) {
char curr = buf.charAt(looper);
char next = 0;
if (looper + 1 < buf.length())
next = buf.charAt(looper + 1);
- if (curr == '\\')
- {
- if (next != '\\')
- { // only if not already escaped
+ if (curr == '\\') {
+ if (next != '\\') { // only if not already escaped
buf.insert(looper, '\\'); // escape backslash
}
looper++; // skip past extra backslash (either the one we added or existing)
@@ -314,23 +293,20 @@
* @return a {@link Properties} object, never null.
* @throws IOException if unable to parse the contents of the element
*/
- public static Properties readPropertiesContents(Element element, String elementName)
- {
+ public static Properties readPropertiesContents(Element element, String elementName) {
String stringContents = readStringContents(element, elementName);
if (stringContents == null) return new Properties();
// JBCACHE-531: escape all backslash characters
stringContents = escapeBackslashes(stringContents);
ByteArrayInputStream is = null;
Properties properties = null;
- try
- {
+ try {
is = new ByteArrayInputStream(stringContents.trim().getBytes("ISO8859_1"));
properties = new Properties();
properties.load(is);
is.close();
}
- catch (IOException e)
- {
+ catch (IOException e) {
log.warn("Unexpected", e);
throw new ConfigurationException("Exception occured while reading properties from XML document", e);
}
@@ -344,8 +320,7 @@
* @param elementName - name of the element to find within the element passed in
* @return the contents of the element as a boolean, or false if not found.
*/
- public static boolean readBooleanContents(Element element, String elementName)
- {
+ public static boolean readBooleanContents(Element element, String elementName) {
return readBooleanContents(element, elementName, false);
}
@@ -357,11 +332,9 @@
* @param defaultValue - value to return if the element is not found or cannot be parsed.
* @return the contents of the element as a boolean
*/
- public static boolean readBooleanContents(Element element, String elementName, boolean defaultValue)
- {
+ public static boolean readBooleanContents(Element element, String elementName, boolean defaultValue) {
String val = readStringContents(element, elementName);
- if (val.equalsIgnoreCase("true") || val.equalsIgnoreCase("false"))
- {
+ if (val.equalsIgnoreCase("true") || val.equalsIgnoreCase("false")) {
// needs to be done this way because of JBBUILD-351
return Boolean.valueOf(val);
//return Boolean.parseBoolean(val);
@@ -376,8 +349,7 @@
* @return a DOM Element
* @throws Exception if unable to parse the String or if it doesn't contain valid XML.
*/
- public static Element stringToElementInCoreNS(String xml) throws Exception
- {
+ public static Element stringToElementInCoreNS(String xml) throws Exception {
xml = "<wrapper xmlns='" + RootElementBuilder.JBOSSCACHE_CORE_NS + "'>" + xml + "</wrapper>";
ByteArrayInputStream bais = new ByteArrayInputStream(xml.getBytes("utf8"));
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
@@ -395,8 +367,7 @@
* @return a DOM Element
* @throws Exception if unable to parse the String or if it doesn't contain valid XML.
*/
- public static Element stringToElement(String xml) throws Exception
- {
+ public static Element stringToElement(String xml) throws Exception {
ByteArrayInputStream bais = new ByteArrayInputStream(xml.getBytes("utf8"));
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
@@ -411,8 +382,7 @@
* @param element the parent
* @return the first child element or null if there isn't one
*/
- public static Element getFirstChildElement(Element element)
- {
+ public static Element getFirstChildElement(Element element) {
Node child = element.getFirstChild();
while (child != null && child.getNodeType() != Node.ELEMENT_NODE)
child = child.getNextSibling();
@@ -426,11 +396,9 @@
* @param is stream to parse
* @return XML DOM element, or null if unable to parse stream
*/
- public static Element getDocumentRoot(InputStream is)
- {
+ public static Element getDocumentRoot(InputStream is) {
Document doc;
- try
- {
+ try {
InputSource xmlInp = new InputSource(is);
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
@@ -441,16 +409,13 @@
root.normalize();
return root;
}
- catch (SAXParseException err)
- {
+ catch (SAXParseException err) {
log.error("Configurator SAXParse error", err);
}
- catch (SAXException e)
- {
+ catch (SAXException e) {
log.error("Configurator SAX error", e);
}
- catch (Exception pce)
- {
+ catch (Exception pce) {
log.error("Configurator general error", pce);
}
return null;
@@ -464,13 +429,10 @@
* @param attributeName - name of attribute to retrieve the value of
* @param defaultValue - default value to return if not found
*/
- public static boolean readBooleanAttribute(Element elem, String elementName, String attributeName, boolean defaultValue)
- {
+ public static boolean readBooleanAttribute(Element elem, String elementName, String attributeName, boolean defaultValue) {
String val = getAttributeValue(elem, elementName, attributeName);
- if (val != null)
- {
- if (val.equalsIgnoreCase("true") || val.equalsIgnoreCase("false"))
- {
+ if (val != null) {
+ if (val.equalsIgnoreCase("true") || val.equalsIgnoreCase("false")) {
//return Boolean.parseBoolean(val);
// needs to be done this way because of JBBUILD-351
return Boolean.valueOf(val);
@@ -480,52 +442,41 @@
return defaultValue;
}
- public static void setValues(Object target, Map<?, ?> attribs, boolean isXmlAttribs, boolean failOnMissingSetter)
- {
+ public static void setValues(Object target, Map<?, ?> attribs, boolean isXmlAttribs, boolean failOnMissingSetter) {
Class objectClass = target.getClass();
// go thru simple string setters first.
- for (Map.Entry entry : attribs.entrySet())
- {
+ for (Map.Entry entry : attribs.entrySet()) {
String propName = (String) entry.getKey();
String setter = BeanUtils.setterName(propName);
Method method;
- try
- {
- if (isXmlAttribs)
- {
+ try {
+ if (isXmlAttribs) {
method = objectClass.getMethod(setter, Element.class);
method.invoke(target, entry.getValue());
- }
- else
- {
+ } else {
method = objectClass.getMethod(setter, String.class);
method.invoke(target, entry.getValue());
}
continue;
}
- catch (NoSuchMethodException me)
- {
+ catch (NoSuchMethodException me) {
// this is ok, but certainly log this as a warning
// this is hugely noisy!
//if (log.isWarnEnabled()) log.warn("Unrecognised attribute " + propName + ". Please check your configuration. Ignoring!!");
}
- catch (Exception e)
- {
+ catch (Exception e) {
throw new ConfigurationException("Unable to invoke setter " + setter + " on " + objectClass, e);
}
boolean setterFound = false;
// if we get here, we could not find a String or Element setter.
- for (Method m : objectClass.getMethods())
- {
- if (setter.equals(m.getName()))
- {
+ for (Method m : objectClass.getMethods()) {
+ if (setter.equals(m.getName())) {
Class paramTypes[] = m.getParameterTypes();
- if (paramTypes.length != 1)
- {
+ if (paramTypes.length != 1) {
if (log.isTraceEnabled())
log.trace("Rejecting setter " + m + " on class " + objectClass + " due to incorrect number of parameters");
continue; // try another param with the same name.
@@ -533,8 +484,7 @@
Class parameterType = paramTypes[0];
PropertyEditor editor = PropertyEditorManager.findEditor(parameterType);
- if (editor == null)
- {
+ if (editor == null) {
throw new ConfigurationException("Couldn't find a property editor for parameter type " + parameterType);
}
@@ -543,14 +493,12 @@
Object parameter = editor.getValue();
//if (log.isDebugEnabled()) log.debug("Invoking setter method: " + setter + " with parameter \"" + parameter + "\" of type " + parameter.getClass());
- try
- {
+ try {
m.invoke(target, parameter);
setterFound = true;
break;
}
- catch (Exception e)
- {
+ catch (Exception e) {
throw new ConfigurationException("Unable to invoke setter " + setter + " on " + objectClass, e);
}
}
@@ -560,16 +508,14 @@
}
}
- public static ParsedAttributes extractAttributes(Element source)
- {
+ public static ParsedAttributes extractAttributes(Element source) {
Map<String, String> stringAttribs = new HashMap<String, String>();
Map<String, Element> xmlAttribs = new HashMap<String, Element>();
NodeList list = source.getElementsByTagName(ATTR);
if (log.isDebugEnabled()) log.debug("Attribute size: " + list.getLength());
// loop through attributes
- for (int loop = 0; loop < list.getLength(); loop++)
- {
+ for (int loop = 0; loop < list.getLength(); loop++) {
Node node = list.item(loop);
if (node.getNodeType() != Node.ELEMENT_NODE) continue;
@@ -579,28 +525,23 @@
String valueStr = getElementContent(element, true);
Element valueXml = null;
- if (valueStr.length() == 0)
- {
+ if (valueStr.length() == 0) {
// This may be an XML element ...
valueXml = getSubElement(element, CONFIG_ATTR);
if (valueXml != null) xmlAttribs.put(name, valueXml);
- }
- else
- {
+ } else {
if (valueStr.length() > 0) stringAttribs.put(name, valueStr);
}
}
return new ParsedAttributes(stringAttribs, xmlAttribs);
}
- public static Properties extractProperties(Element source)
- {
+ public static Properties extractProperties(Element source) {
Properties p = new Properties();
NodeList list = source.getElementsByTagName("property");
// loop through attributes
- for (int loop = 0; loop < list.getLength(); loop++)
- {
+ for (int loop = 0; loop < list.getLength(); loop++) {
Node node = list.item(loop);
if (node.getNodeType() != Node.ELEMENT_NODE) continue;
@@ -609,8 +550,7 @@
String name = element.getAttribute(NAME);
String valueStr = element.getAttribute("value");
- if (valueStr.length() > 0)
- {
+ if (valueStr.length() > 0) {
valueStr = valueStr.trim();
valueStr = StringPropertyReplacer.replaceProperties(valueStr);
p.put(name, valueStr);
@@ -619,10 +559,8 @@
return p;
}
- public static String toString(Element e)
- {
- try
- {
+ public static String toString(Element e) {
+ try {
TransformerFactory tfactory = TransformerFactory.newInstance();
Transformer xform = tfactory.newTransformer();
Source src = new DOMSource(e);
@@ -631,8 +569,7 @@
xform.transform(src, result);
return writer.toString();
}
- catch (Exception ex)
- {
+ catch (Exception ex) {
return "Unable to convert to string: " + ex.toString();
}
}
Modified: core/branches/flat/src/main/java/org/horizon/config/parsing/XmlConfigurationParser.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/config/parsing/XmlConfigurationParser.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/config/parsing/XmlConfigurationParser.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -14,8 +14,7 @@
* @author Manik Surtani
* @since 1.0
*/
-public interface XmlConfigurationParser
-{
+public interface XmlConfigurationParser {
/**
* Initializes the parser with a String that represents the name of the configuration file to parse. Parsers would
* attempt to find this file on the classpath first, and failing that, treat the String as an absolute path name on
@@ -43,7 +42,8 @@
Map<String, Configuration> parseNamedConfigurations() throws ConfigurationException;
/**
- * GlobalConfiguration would also have a reference to the template default configuration, accessible via {@link org.horizon.config.GlobalConfiguration#getDefaultConfiguration()}
+ * GlobalConfiguration would also have a reference to the template default configuration, accessible via {@link
+ * org.horizon.config.GlobalConfiguration#getDefaultConfiguration()}
* <p/>
* This is typically used to configure a {@link org.horizon.manager.CacheManager}
*
Modified: core/branches/flat/src/main/java/org/horizon/config/parsing/XmlConfigurationParserImpl.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/config/parsing/XmlConfigurationParserImpl.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/config/parsing/XmlConfigurationParserImpl.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -20,16 +20,14 @@
* @author Manik Surtani
* @since 1.0
*/
-public class XmlConfigurationParserImpl extends XmlParserBase implements XmlConfigurationParser
-{
+public class XmlConfigurationParserImpl extends XmlParserBase implements XmlConfigurationParser {
boolean initialized = false;
Element rootElement;
/**
* Constructs a new parser
*/
- public XmlConfigurationParserImpl()
- {
+ public XmlConfigurationParserImpl() {
}
/**
@@ -38,24 +36,22 @@
* @param fileName file name to initialize the parser with
* @throws IOException if there is a problem reading or locating the file.
*/
- public XmlConfigurationParserImpl(String fileName) throws IOException
- {
+ public XmlConfigurationParserImpl(String fileName) throws IOException {
initialize(fileName);
}
/**
- * Constructs a parser and initializes it with the input stream passed in, by calling {@link #initialize(InputStream)}.
+ * Constructs a parser and initializes it with the input stream passed in, by calling {@link
+ * #initialize(InputStream)}.
*
* @param inputStream input stream to initialize the parser with
* @throws IOException if there is a problem reading the stream
*/
- public XmlConfigurationParserImpl(InputStream inputStream) throws IOException
- {
+ public XmlConfigurationParserImpl(InputStream inputStream) throws IOException {
initialize(inputStream);
}
- public void initialize(String fileName) throws IOException
- {
+ public void initialize(String fileName) throws IOException {
if (fileName == null) throw new NullPointerException("File name cannot be null!");
FileLookup fileLookup = new FileLookup();
InputStream is = fileLookup.lookupFile(fileName);
@@ -64,28 +60,24 @@
initialize(is);
}
- public void initialize(InputStream inputStream) throws IOException
- {
+ public void initialize(InputStream inputStream) throws IOException {
if (inputStream == null) throw new NullPointerException("Input stream cannot be null!");
initialized = true;
rootElement = new RootElementBuilder().readRoot(inputStream);
}
- public Configuration parseDefaultConfiguration() throws ConfigurationException
- {
+ public Configuration parseDefaultConfiguration() throws ConfigurationException {
assertInitialized();
Element defaultConfiguration = getSingleElementInCoreNS("default", rootElement);
return new XmlConfigurationParserJBC3().parseElementIgnoringRoot(defaultConfiguration);
}
- public Map<String, Configuration> parseNamedConfigurations() throws ConfigurationException
- {
+ public Map<String, Configuration> parseNamedConfigurations() throws ConfigurationException {
assertInitialized();
Set<Element> elements = getAllElementsInCoreNS("namedCache", rootElement);
if (elements.isEmpty()) return Collections.emptyMap();
Map<String, Configuration> namedConfigurations = new HashMap<String, Configuration>(elements.size(), 1.0f);
- for (Element e : elements)
- {
+ for (Element e : elements) {
String configurationName = getAttributeValue(e, "name");
if (namedConfigurations.containsKey(configurationName))
throw new ConfigurationException("Named cache " + configurationName + " contains duplicate entries!");
@@ -95,13 +87,11 @@
return namedConfigurations;
}
- public GlobalConfiguration parseGlobalConfiguration()
- {
+ public GlobalConfiguration parseGlobalConfiguration() {
throw new RuntimeException("Implement me");
}
- private void assertInitialized()
- {
+ private void assertInitialized() {
if (!initialized)
throw new ConfigurationException("Parser not initialized. Please invoke initialize() first, or use a constructor that initializes the parser.");
}
Modified: core/branches/flat/src/main/java/org/horizon/config/parsing/XmlConfigurationParserJBC3.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/config/parsing/XmlConfigurationParserJBC3.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/config/parsing/XmlConfigurationParserJBC3.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -21,12 +21,15 @@
*/
package org.horizon.config.parsing;
-import org.horizon.lock.IsolationLevel;
-import org.horizon.config.*;
+import org.horizon.config.CacheLoaderConfig;
+import org.horizon.config.Configuration;
import org.horizon.config.Configuration.CacheMode;
+import org.horizon.config.ConfigurationException;
+import org.horizon.config.CustomInterceptorConfig;
import org.horizon.config.parsing.element.CustomInterceptorsElementParser;
import org.horizon.config.parsing.element.EvictionElementParser;
import org.horizon.config.parsing.element.LoadersElementParser;
+import org.horizon.lock.IsolationLevel;
import org.horizon.util.FileLookup;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
@@ -37,22 +40,20 @@
import java.util.List;
/**
- * Reads in XMLconfiguration files and spits out a {@link Configuration} object.
- * By default this class uses a validating parser (configurable).
+ * Reads in XMLconfiguration files and spits out a {@link Configuration} object. By default this class uses a validating
+ * parser (configurable).
* <p/>
- * Following system properties can be used for customizing parser behavior:
- * <ul>
- * <li> <b>-Djbosscache.config.validate=false</b> will make the parser non-validating </li>
- * <li> <b>-Djbosscache.config.schemaLocation=url</b> allows one to specify a validation schema that would override the one specified in the the xml document </li>
- * </ul>
- * This class is stateful and one instance should be used for parsing a single configuration file.
+ * Following system properties can be used for customizing parser behavior: <ul> <li>
+ * <b>-Djbosscache.config.validate=false</b> will make the parser non-validating </li> <li>
+ * <b>-Djbosscache.config.schemaLocation=url</b> allows one to specify a validation schema that would override the one
+ * specified in the the xml document </li> </ul> This class is stateful and one instance should be used for parsing a
+ * single configuration file.
*
* @author Mircea.Markus at jboss.com
* @see RootElementBuilder
* @since 1.0
*/
-public class XmlConfigurationParserJBC3 extends XmlParserBase
-{
+public class XmlConfigurationParserJBC3 extends XmlParserBase {
private RootElementBuilder rootElementBuilder;
/**
@@ -62,11 +63,10 @@
private Element root;
/**
- * If validation is on (default) one can specify an error handler for handling validation errors.
- * The default error handler just logs parsing errors received.
+ * If validation is on (default) one can specify an error handler for handling validation errors. The default error
+ * handler just logs parsing errors received.
*/
- public XmlConfigurationParserJBC3(ErrorHandler errorHandler)
- {
+ public XmlConfigurationParserJBC3(ErrorHandler errorHandler) {
rootElementBuilder = new RootElementBuilder(errorHandler);
}
@@ -75,30 +75,26 @@
*
* @param validating should the underlaying parser disable the validation?
*/
- public XmlConfigurationParserJBC3(boolean validating, ErrorHandler errorHandler)
- {
+ public XmlConfigurationParserJBC3(boolean validating, ErrorHandler errorHandler) {
rootElementBuilder = new RootElementBuilder(errorHandler, validating);
}
/**
* Constructs a parser having validation enabled with a ErrorHandler that only logs the parser errors.
*/
- public XmlConfigurationParserJBC3()
- {
+ public XmlConfigurationParserJBC3() {
rootElementBuilder = new RootElementBuilder();
}
/**
- * Parses an XML file and returns a new configuration.
- * For looking up the file, {@link org.horizon.util.FileLookup} is used.
+ * Parses an XML file and returns a new configuration. For looking up the file, {@link org.horizon.util.FileLookup}
+ * is used.
*
* @see org.horizon.util.FileLookup
*/
- public Configuration parseFile(String filename)
- {
+ public Configuration parseFile(String filename) {
InputStream is = new FileLookup().lookupFile(filename);
- if (is == null)
- {
+ if (is == null) {
throw new ConfigurationException("Unable to find config file " + filename + " either in classpath or on the filesystem!");
}
return parseStream(is);
@@ -107,8 +103,7 @@
/**
* Similar to {@link #parseFile(String)}, just that it does not create the input stream.
*/
- public Configuration parseStream(InputStream configStream)
- {
+ public Configuration parseStream(InputStream configStream) {
readRoot(configStream);
return processElements(false);
}
@@ -116,35 +111,29 @@
/**
* Root should be the <b>jbosscache</b> element in the configuration file.
*/
- public Configuration parseElement(Element root)
- {
+ public Configuration parseElement(Element root) {
this.root = root;
this.root.normalize();
return processElements(false);
}
- public Configuration parseElementIgnoringRoot(Element root)
- {
+ public Configuration parseElementIgnoringRoot(Element root) {
this.root = root;
this.root.normalize();
return processElements(true);
}
- public boolean isValidating()
- {
+ public boolean isValidating() {
return rootElementBuilder.isValidating();
}
- private Configuration processElements(boolean ignoreRoot)
- {
+ private Configuration processElements(boolean ignoreRoot) {
if (!ignoreRoot &&
- (!"jbosscache".equals(root.getLocalName()) || !RootElementBuilder.JBOSSCACHE_CORE_NS.equals(root.getNamespaceURI())))
- {
+ (!"jbosscache".equals(root.getLocalName()) || !RootElementBuilder.JBOSSCACHE_CORE_NS.equals(root.getNamespaceURI()))) {
throw new ConfigurationException("Expected root element {" + RootElementBuilder.JBOSSCACHE_CORE_NS + "}" + "jbosscache");
}
- try
- {
+ try {
configureLocking(getSingleElement("locking"));
configureTransaction(getSingleElement("transaction"));
configureClustering(getSingleElement("clustering"));
@@ -159,15 +148,13 @@
configureListeners(getSingleElement("listeners"));
configureInvocationBatching(getSingleElement("invocationBatching"));
}
- catch (Exception e)
- {
+ catch (Exception e) {
throw new ConfigurationException("Unexpected exception while parsing the configuration file", e);
}
return config;
}
- private void configureClustering(Element e)
- {
+ private void configureClustering(Element e) {
if (e == null) return; //we might not have this configured
// there are 2 attribs - mode and clusterName
boolean repl = true;
@@ -182,13 +169,10 @@
if (syncEl != null && asyncEl != null)
throw new ConfigurationException("Cannot have sync and async elements within the same cluster element!");
boolean sync = asyncEl == null; // even if both are null, we default to sync
- if (sync)
- {
+ if (sync) {
config.setCacheMode(repl ? CacheMode.REPL_SYNC : CacheMode.INVALIDATION_SYNC);
configureSyncMode(syncEl);
- }
- else
- {
+ } else {
config.setCacheMode(repl ? CacheMode.REPL_ASYNC : CacheMode.INVALIDATION_ASYNC);
configureAsyncMode(asyncEl);
}
@@ -198,8 +182,7 @@
configureTransport(getSingleElementInCoreNS("jgroupsConfig", e));
}
- private void configureStateRetrieval(Element element)
- {
+ private void configureStateRetrieval(Element element) {
if (element == null) return; //we might not have this configured
String fetchInMemoryState = getAttributeValue(element, "fetchInMemoryState");
if (existsAttribute(fetchInMemoryState)) config.setFetchInMemoryState(getBoolean(fetchInMemoryState));
@@ -208,8 +191,7 @@
}
- private void configureTransaction(Element element)
- {
+ private void configureTransaction(Element element) {
if (element == null) return;
String attrName = "transactionManagerLookupClass";
String txMngLookupClass = getAttributeValue(element, attrName);
@@ -220,8 +202,7 @@
if (existsAttribute(syncCommitPhase)) config.setSyncCommitPhase(getBoolean(syncCommitPhase));
}
- private void configureSerialization(Element element)
- {
+ private void configureSerialization(Element element) {
if (element == null) return;
String objectInputStreamPoolSize = getAttributeValue(element, "objectInputStreamPoolSize");
if (existsAttribute(objectInputStreamPoolSize))
@@ -240,16 +221,14 @@
config.setUseRegionBasedMarshalling(getBoolean(useRegionBasedMarshalling));
}
- private void configureCustomInterceptors(Element element)
- {
+ private void configureCustomInterceptors(Element element) {
if (element == null) return; //this element might be missing
CustomInterceptorsElementParser parser = new CustomInterceptorsElementParser();
List<CustomInterceptorConfig> interceptorConfigList = parser.parseCustomInterceptors(element);
config.setCustomInterceptors(interceptorConfigList);
}
- private void configureListeners(Element element)
- {
+ private void configureListeners(Element element) {
if (element == null) return; //this element is optional
String asyncPoolSizeStr = getAttributeValue(element, "asyncPoolSize");
if (existsAttribute(asyncPoolSizeStr)) config.setListenerAsyncPoolSize(getInt(asyncPoolSizeStr));
@@ -258,63 +237,51 @@
if (existsAttribute(asyncQueueSizeStr)) config.setListenerAsyncQueueSize(getInt(asyncQueueSizeStr));
}
- private void configureInvocationBatching(Element element)
- {
+ private void configureInvocationBatching(Element element) {
if (element == null) return; //this element is optional
boolean enabled = getBoolean(getAttributeValue(element, "enabled"));
config.setInvocationBatchingEnabled(enabled);
}
- private void configureCacheLoaders(Element element)
- {
+ private void configureCacheLoaders(Element element) {
if (element == null) return; //null cache loaders are allowed
LoadersElementParser clElementParser = new LoadersElementParser();
CacheLoaderConfig cacheLoaderConfig = clElementParser.parseLoadersElement(element);
config.setCacheLoaderConfig(cacheLoaderConfig);
}
- private void configureEviction(Element element)
- {
+ private void configureEviction(Element element) {
if (element == null) return; //no eviction might be configured
EvictionElementParser evictionElementParser = new EvictionElementParser();
//config.setEvictionConfig(evictionElementParser.parseEvictionElement(element));
}
- private void configureJmxStatistics(Element element)
- {
+ private void configureJmxStatistics(Element element) {
if (element == null) return; //might not be specified
String enabled = getAttributeValue(element, "enabled");
config.setExposeManagementStatistics(getBoolean(enabled));
}
- private void configureShutdown(Element element)
- {
+ private void configureShutdown(Element element) {
if (element == null) return;
String hookBehavior = getAttributeValue(element, "hookBehavior");
if (existsAttribute(hookBehavior)) config.setShutdownHookBehavior(hookBehavior);
}
- private void configureTransport(Element element)
- {
+ private void configureTransport(Element element) {
if (element == null) return; //transport might be missing
// first see if a configFile is provided
String cfgFile = getAttributeValue(element, "configFile");
- if (existsAttribute(cfgFile))
- {
+ if (existsAttribute(cfgFile)) {
// try and load this file
URL u = new FileLookup().lookupFileLocation(cfgFile);
config.setJgroupsConfigFile(u);
- }
- else
- {
+ } else {
String multiplexerStack = getAttributeValue(element, "multiplexerStack");
- if (existsAttribute(multiplexerStack))
- {
+ if (existsAttribute(multiplexerStack)) {
config.setMultiplexerStack(multiplexerStack);
- }
- else
- {
+ } else {
JGroupsStackParser stackParser = new JGroupsStackParser();
String clusterConfigStr = stackParser.parseClusterConfigXml(element);
if (clusterConfigStr != null && clusterConfigStr.trim().length() > 0)
@@ -323,38 +290,32 @@
}
}
- private void configureStartup(Element element)
- {
+ private void configureStartup(Element element) {
if (element == null) return; //we might not have this configured
String inactiveOnStartup = getAttributeValue(element, "regionsInactiveOnStartup");
if (existsAttribute(inactiveOnStartup)) config.setInactiveOnStartup(getBoolean(inactiveOnStartup));
}
- private void configureInvalidation(Element element)
- {
+ private void configureInvalidation(Element element) {
if (element == null) return; //might be replication
Element async = getSingleElement("async");
- if (async != null)
- {
+ if (async != null) {
config.setCacheMode(Configuration.CacheMode.INVALIDATION_ASYNC);
configureAsyncMode(getSingleElementInCoreNS("async", element));
}
Element sync = getSingleElement("sync");
- if (sync != null)
- {
+ if (sync != null) {
config.setCacheMode(Configuration.CacheMode.INVALIDATION_SYNC);
configureSyncMode(getSingleElementInCoreNS("sync", element));
}
}
- private void configureSyncMode(Element element)
- {
+ private void configureSyncMode(Element element) {
String replTimeout = getAttributeValue(element, "replTimeout");
if (existsAttribute(replTimeout)) config.setSyncReplTimeout(getLong(replTimeout));
}
- private void configureAsyncMode(Element element)
- {
+ private void configureAsyncMode(Element element) {
String useReplQueue = getAttributeValue(element, "useReplQueue");
if (existsAttribute(useReplQueue)) config.setUseReplQueue(getBoolean(useReplQueue));
String replQueueInterval = getAttributeValue(element, "replQueueInterval");
@@ -371,8 +332,7 @@
config.setSerializationExecutorQueueSize(getInt(serializationExecutorQueueSize));
}
- private void configureLocking(Element element)
- {
+ private void configureLocking(Element element) {
String isolationLevel = getAttributeValue(element, "isolationLevel");
if (existsAttribute(isolationLevel)) config.setIsolationLevel(IsolationLevel.valueOf(isolationLevel));
String lockParentForChildInsertRemove = getAttributeValue(element, "lockParentForChildInsertRemove");
@@ -386,13 +346,11 @@
if (existsAttribute(concurrencyLevel)) config.setConcurrencyLevel(getInt(concurrencyLevel));
}
- private Element getSingleElement(String elementName)
- {
+ private Element getSingleElement(String elementName) {
return getSingleElementInCoreNS(elementName, root);
}
- private void readRoot(InputStream config)
- {
+ private void readRoot(InputStream config) {
root = rootElementBuilder.readRoot(config);
}
@@ -402,8 +360,7 @@
* @param element element to test
* @return true of the element is a modern one and can be parsed using the current parser.
*/
- public boolean isValidElementRoot(Element element)
- {
+ public boolean isValidElementRoot(Element element) {
// simply test for the "jbosscache" element.
NodeList elements = element.getElementsByTagName("jbosscache");
return elements != null && elements.getLength() > 0;
Modified: core/branches/flat/src/main/java/org/horizon/config/parsing/XmlParserBase.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/config/parsing/XmlParserBase.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/config/parsing/XmlParserBase.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -36,46 +36,40 @@
* @author Mircea.Markus at jboss.com
* @since 1.0
*/
-public abstract class XmlParserBase
-{
+public abstract class XmlParserBase {
/**
* @see Integer#parseInt(String)
*/
- protected int getInt(String intStr)
- {
+ protected int getInt(String intStr) {
return Integer.parseInt(intStr);
}
/**
* @see Long#parseLong(String)
*/
- protected long getLong(String longStr)
- {
+ protected long getLong(String longStr) {
return Long.parseLong(longStr);
}
/**
* @see Boolean#valueOf(String)
*/
- protected boolean getBoolean(String str)
- {
+ protected boolean getBoolean(String str) {
return str == null ? false : Boolean.valueOf(str);
}
/**
* @return true if the given value is not empty.
*/
- protected boolean existsAttribute(String attrValue)
- {
+ protected boolean existsAttribute(String attrValue) {
return attrValue != null && attrValue.length() > 0;
}
/**
* Convenient method for retrieving a single element with the give name.
*/
- protected Element getSingleElement(String namespace, String elementName, Element parent)
- {
+ protected Element getSingleElement(String namespace, String elementName, Element parent) {
NodeList nodeList = parent.getElementsByTagNameNS(namespace, elementName);
if (nodeList.getLength() == 0) return null;
return (Element) nodeList.item(0);
@@ -84,13 +78,11 @@
/**
* Convenience method for retrieving all child elements bearing the same element name
*/
- protected Set<Element> getAllElements(String namespace, String elementName, Element parent)
- {
+ protected Set<Element> getAllElements(String namespace, String elementName, Element parent) {
NodeList nodeList = parent.getElementsByTagNameNS(namespace, elementName);
if (nodeList.getLength() == 0) return Collections.emptySet();
Set<Element> elements = new HashSet<Element>();
- for (int i = 0; i < nodeList.getLength(); i++)
- {
+ for (int i = 0; i < nodeList.getLength(); i++) {
Node n = nodeList.item(i);
if (n instanceof Element) elements.add((Element) n);
}
@@ -100,27 +92,24 @@
/**
* Convenient method for retrieving a single element with the give name, in the core namespace
*/
- protected Element getSingleElementInCoreNS(String elementName, Element parent)
- {
+ protected Element getSingleElementInCoreNS(String elementName, Element parent) {
return getSingleElement(RootElementBuilder.JBOSSCACHE_CORE_NS, elementName, parent);
}
/**
* Convenience method for retrieving all child elements bearing the same element name, in the core namespace
*/
- protected Set<Element> getAllElementsInCoreNS(String elementName, Element parent)
- {
+ protected Set<Element> getAllElementsInCoreNS(String elementName, Element parent) {
return getAllElements(RootElementBuilder.JBOSSCACHE_CORE_NS, elementName, parent);
}
/**
- * Beside querying the element for its attribute value, it will look into the value, if any, and replace the
- * jboss properties(e.g. ${someValue:defaultValue}.
+ * Beside querying the element for its attribute value, it will look into the value, if any, and replace the jboss
+ * properties(e.g. ${someValue:defaultValue}.
* <p/>
* {@link org.jboss.util.StringPropertyReplacer#replaceProperties(String)}
*/
- protected String getAttributeValue(Element element, String attrName)
- {
+ protected String getAttributeValue(Element element, String attrName) {
if (element == null || attrName == null) return null;
String value = element.getAttribute(attrName);
return value == null ? null : StringPropertyReplacer.replaceProperties(value);
Modified: core/branches/flat/src/main/java/org/horizon/config/parsing/element/CustomInterceptorsElementParser.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/config/parsing/element/CustomInterceptorsElementParser.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/config/parsing/element/CustomInterceptorsElementParser.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -45,20 +45,17 @@
* @author Mircea.Markus at jboss.com
* @since 1.0
*/
-public class CustomInterceptorsElementParser extends XmlParserBase
-{
+public class CustomInterceptorsElementParser extends XmlParserBase {
/**
* Iterates within the given element looking for custom interceptors.
*
* @param element should not be null
* @return a list which might be empty, never null
*/
- public List<CustomInterceptorConfig> parseCustomInterceptors(Element element)
- {
+ public List<CustomInterceptorConfig> parseCustomInterceptors(Element element) {
NodeList interceptorNodes = element.getElementsByTagName("interceptor");
List<CustomInterceptorConfig> interceptorConfigs = new ArrayList<CustomInterceptorConfig>(interceptorNodes.getLength());
- for (int i = 0; i < interceptorNodes.getLength(); i++)
- {
+ for (int i = 0; i < interceptorNodes.getLength(); i++) {
boolean first = false;
boolean last = false;
int index = -1;
@@ -67,12 +64,10 @@
Element interceptorElement = (Element) interceptorNodes.item(i);
String position = getAttributeValue(interceptorElement, "position");
- if (existsAttribute(position) && "first".equalsIgnoreCase(position))
- {
+ if (existsAttribute(position) && "first".equalsIgnoreCase(position)) {
first = true;
}
- if (existsAttribute(position) && "last".equalsIgnoreCase(position))
- {
+ if (existsAttribute(position) && "last".equalsIgnoreCase(position)) {
last = true;
}
String indexStr = getAttributeValue(interceptorElement, "index");
@@ -94,17 +89,14 @@
/**
* Builds the interceptor based on the interceptor class and also sets all its attributes.
*/
- private CommandInterceptor buildCommandInterceptor(Element element)
- {
+ private CommandInterceptor buildCommandInterceptor(Element element) {
String interceptorClass = getAttributeValue(element, "class");
if (!existsAttribute(interceptorClass)) throw new ConfigurationException("Interceptor class cannot be empty!");
CommandInterceptor result;
- try
- {
+ try {
result = (CommandInterceptor) Util.loadClass(interceptorClass).newInstance();
}
- catch (Exception e)
- {
+ catch (Exception e) {
throw new ConfigurationException("CommandInterceptor class is not properly loaded in classloader", e);
}
Properties p = XmlConfigHelper.extractProperties(element);
Modified: core/branches/flat/src/main/java/org/horizon/config/parsing/element/EvictionElementParser.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/config/parsing/element/EvictionElementParser.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/config/parsing/element/EvictionElementParser.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -45,26 +45,20 @@
* @author Mircea.Markus at jboss.com
* @since 1.0
*/
-public class EvictionElementParser extends XmlParserBase
-{
- public EvictionConfig parseEvictionElement(Element evictionElement)
- {
+public class EvictionElementParser extends XmlParserBase {
+ public EvictionConfig parseEvictionElement(Element evictionElement) {
EvictionConfig evictionConfig = new EvictionConfig();
String wakeUpInterval = getAttributeValue(evictionElement, "wakeUpInterval");
- if (existsAttribute(wakeUpInterval))
- {
+ if (existsAttribute(wakeUpInterval)) {
evictionConfig.setWakeupInterval(getInt(wakeUpInterval));
- }
- else
- {
+ } else {
throw new ConfigurationException("Missing mandatory attribute wakeUpInterval");
}
List<EvictionCacheConfig> evictionCacheConfigs = new LinkedList<EvictionCacheConfig>();
Element defaultRegion = getSingleElementInCoreNS("default", evictionElement);
- if (defaultRegion != null)
- {
+ if (defaultRegion != null) {
EvictionCacheConfig defaultCacheConfig = getEvictionRegionConfig(defaultRegion, null, true);
if (defaultCacheConfig.getEvictionAlgorithmConfig() == null)
throw new MissingPolicyException("Default eviction region should have an evictionAlgorithmClass defined.");
@@ -72,8 +66,7 @@
}
NodeList regions = evictionElement.getElementsByTagName("region");
- for (int i = 0; i < regions.getLength(); i++)
- {
+ for (int i = 0; i < regions.getLength(); i++) {
Element regionConfig = (Element) regions.item(i);
EvictionCacheConfig erc = getEvictionRegionConfig(regionConfig, evictionConfig.getDefaultEvictionRegionConfig(), false);
evictionConfig.applyDefaults(erc);
@@ -84,8 +77,7 @@
}
@SuppressWarnings("unchecked")
- private EvictionCacheConfig getEvictionRegionConfig(Element element, EvictionCacheConfig defaultCache, boolean isDefault)
- {
+ private EvictionCacheConfig getEvictionRegionConfig(Element element, EvictionCacheConfig defaultCache, boolean isDefault) {
// EvictionCacheConfig erc = new EvictionCacheConfig();
// erc.setRegionName(getAttributeValue(element, "name"));
// String queueSize = getAttributeValue(element, "eventQueueSize");
@@ -181,8 +173,7 @@
return null;
}
- public static void parseEvictionPolicyConfig(Element element, EvictionAlgorithmConfig target)
- {
+ public static void parseEvictionPolicyConfig(Element element, EvictionAlgorithmConfig target) {
// target.reset();
Properties p = XmlConfigHelper.extractProperties(element);
XmlConfigHelper.setValues(target, p, false, true);
Modified: core/branches/flat/src/main/java/org/horizon/config/parsing/element/LoadersElementParser.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/config/parsing/element/LoadersElementParser.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/config/parsing/element/LoadersElementParser.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -40,10 +40,8 @@
* @author Mircea.Markus at jboss.com
* @since 1.0
*/
-public class LoadersElementParser extends XmlParserBase
-{
- public CacheLoaderConfig parseLoadersElement(Element element)
- {
+public class LoadersElementParser extends XmlParserBase {
+ public CacheLoaderConfig parseLoadersElement(Element element) {
CacheLoaderConfig cacheLoaderConfig = new CacheLoaderConfig();
String passivation = getAttributeValue(element, "passivation");
if (existsAttribute(passivation)) cacheLoaderConfig.setPassivation(getBoolean(passivation));
@@ -53,8 +51,7 @@
if (preload != null) cacheLoaderConfig.setPreload(preload);
NodeList cacheLoaderNodes = element.getElementsByTagName("loader");
- for (int i = 0; i < cacheLoaderNodes.getLength(); i++)
- {
+ for (int i = 0; i < cacheLoaderNodes.getLength(); i++) {
Element indivElement = (Element) cacheLoaderNodes.item(i);
CacheLoaderConfig.IndividualCacheLoaderConfig iclc = parseIndividualCacheLoaderConfig(indivElement);
cacheLoaderConfig.addIndividualCacheLoaderConfig(iclc);
@@ -62,8 +59,7 @@
return cacheLoaderConfig;
}
- private CacheLoaderConfig.IndividualCacheLoaderConfig parseIndividualCacheLoaderConfig(Element indivElement)
- {
+ private CacheLoaderConfig.IndividualCacheLoaderConfig parseIndividualCacheLoaderConfig(Element indivElement) {
CacheLoaderConfig.IndividualCacheLoaderConfig iclc = new CacheLoaderConfig.IndividualCacheLoaderConfig();
String async = getAttributeValue(indivElement, "async");
@@ -80,20 +76,17 @@
iclc.setClassName(clClass);
iclc.setProperties(XmlConfigHelper.readPropertiesContents(indivElement, "properties"));
CacheLoaderConfig.IndividualCacheLoaderConfig.SingletonStoreConfig ssc = parseSingletonStoreConfig(getSingleElementInCoreNS("singletonStore", indivElement));
- if (ssc != null)
- {
+ if (ssc != null) {
iclc.setSingletonStoreConfig(ssc);
}
return iclc;
}
- private String getPreloadString(Element preloadElement)
- {
+ private String getPreloadString(Element preloadElement) {
if (preloadElement == null) return null; //might be no preload
NodeList nodesToPreload = preloadElement.getElementsByTagName("node");
StringBuilder result = new StringBuilder();
- for (int i = 0; i < nodesToPreload.getLength(); i++)
- {
+ for (int i = 0; i < nodesToPreload.getLength(); i++) {
Element node = (Element) nodesToPreload.item(i);
String fqn2preload = getAttributeValue(node, "fqn");
if (!existsAttribute(fqn2preload))
@@ -102,15 +95,13 @@
result.append(fqn2preload);
}
//no elements defined for preload so by default load the root
- if (nodesToPreload.getLength() == 0)
- {
+ if (nodesToPreload.getLength() == 0) {
result.append("/");
}
return result.toString();
}
- public CacheLoaderConfig.IndividualCacheLoaderConfig.SingletonStoreConfig parseSingletonStoreConfig(Element element)
- {
+ public CacheLoaderConfig.IndividualCacheLoaderConfig.SingletonStoreConfig parseSingletonStoreConfig(Element element) {
if (element == null) return null; //might happen, this config option is not mandatory
boolean singletonStoreEnabled = getBoolean(getAttributeValue(element, "enabled"));
String singletonStoreClass = getAttributeValue(element, "class");
Modified: core/branches/flat/src/main/java/org/horizon/container/DataContainer.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/container/DataContainer.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/container/DataContainer.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -33,8 +33,7 @@
* @since 1.0
*/
@Scope(Scopes.NAMED_CACHE)
-public interface DataContainer<K, V>
-{
+public interface DataContainer<K, V> {
V get(K k);
void put(K k, V v);
Modified: core/branches/flat/src/main/java/org/horizon/container/MVCCEntry.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/container/MVCCEntry.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/container/MVCCEntry.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -31,8 +31,7 @@
* @author Manik Surtani (<a href="mailto:manik at jboss.org">manik at jboss.org</a>)
* @since 1.0
*/
-public interface MVCCEntry extends Entry
-{
+public interface MVCCEntry extends Entry {
boolean isNullEntry();
void copyForUpdate(DataContainer container, boolean writeSkewCheck);
Modified: core/branches/flat/src/main/java/org/horizon/container/NullMarkerEntry.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/container/NullMarkerEntry.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/container/NullMarkerEntry.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -28,32 +28,30 @@
* @author Manik Surtani (<a href="mailto:manik at jboss.org">manik at jboss.org</a>)
* @since 1.0
*/
-public class NullMarkerEntry extends ReadCommittedEntry
-{
+public class NullMarkerEntry extends ReadCommittedEntry {
/**
* @return always returns true
*/
@Override
- public boolean isNullEntry()
- {
+ public boolean isNullEntry() {
return true;
}
/**
- * @return always returns true so that any get commands, upon getting this node, will ignore the node as though it were removed.
+ * @return always returns true so that any get commands, upon getting this node, will ignore the node as though it
+ * were removed.
*/
@Override
- public boolean isDeleted()
- {
+ public boolean isDeleted() {
return true;
}
/**
- * @return always returns true so that any get commands, upon getting this node, will ignore the node as though it were invalid.
+ * @return always returns true so that any get commands, upon getting this node, will ignore the node as though it
+ * were invalid.
*/
@Override
- public boolean isValid()
- {
+ public boolean isValid() {
return false;
}
@@ -61,8 +59,7 @@
* A no-op.
*/
@Override
- public void copyForUpdate(DataContainer d, boolean b)
- {
+ public void copyForUpdate(DataContainer d, boolean b) {
// no op
}
}
\ No newline at end of file
Modified: core/branches/flat/src/main/java/org/horizon/container/ReadCommittedEntry.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/container/ReadCommittedEntry.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/container/ReadCommittedEntry.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -32,8 +32,7 @@
* @author Manik Surtani (<a href="mailto:manik at jboss.org">manik at jboss.org</a>)
* @since 1.0
*/
-public class ReadCommittedEntry implements MVCCEntry
-{
+public class ReadCommittedEntry implements MVCCEntry {
private static final Log log = LogFactory.getLog(ReadCommittedEntry.class);
private static final boolean trace = log.isTraceEnabled();
@@ -41,40 +40,33 @@
protected byte flags = 0;
- protected ReadCommittedEntry()
- {
+ protected ReadCommittedEntry() {
setValid(true);
}
- public ReadCommittedEntry(Object key, Object value)
- {
+ public ReadCommittedEntry(Object key, Object value) {
setValid(true);
this.key = key;
this.value = value;
}
- public Object getKey()
- {
+ public Object getKey() {
return key;
}
- public Object getValue()
- {
+ public Object getValue() {
return value;
}
- public Object setValue(Object value)
- {
+ public Object setValue(Object value) {
return this.value = value;
}
- protected static enum Flags
- {
+ protected static enum Flags {
CHANGED(0x1), CREATED(0x2), DELETED(0x4), VALID(0x8);
final byte mask;
- Flags(int mask)
- {
+ Flags(int mask) {
this.mask = (byte) mask;
}
}
@@ -85,8 +77,7 @@
* @param flag flag to test
* @return true if set, false otherwise.
*/
- protected final boolean isFlagSet(Flags flag)
- {
+ protected final boolean isFlagSet(Flags flag) {
return (flags & flag.mask) != 0;
}
@@ -95,8 +86,7 @@
*
* @param flag flag to set
*/
- protected final void setFlag(Flags flag)
- {
+ protected final void setFlag(Flags flag) {
flags |= flag.mask;
}
@@ -105,18 +95,15 @@
*
* @param flag flag to unset
*/
- protected final void unsetFlag(Flags flag)
- {
+ protected final void unsetFlag(Flags flag) {
flags &= ~flag.mask;
}
- public boolean isNullEntry()
- {
+ public boolean isNullEntry() {
return false;
}
- public void copyForUpdate(DataContainer container, boolean writeSkewCheck)
- {
+ public void copyForUpdate(DataContainer container, boolean writeSkewCheck) {
if (isFlagSet(CHANGED)) return; // already copied
setFlag(CHANGED); // mark as changed
@@ -126,85 +113,70 @@
}
@SuppressWarnings("unchecked")
- public void commitUpdate(InvocationContext ctx, DataContainer container)
- {
+ public void commitUpdate(InvocationContext ctx, DataContainer container) {
// only do stuff if there are changes.
- if (isFlagSet(CHANGED))
- {
+ if (isFlagSet(CHANGED)) {
if (trace)
log.trace("Updating entry [" + getKey() + "]. deleted=" + isDeleted() + " valid=" + isValid() + " changed=" + isChanged() + " created=" + isFlagSet(CREATED));
- if (isFlagSet(DELETED))
- {
+ if (isFlagSet(DELETED)) {
container.remove(key);
- }
- else
- {
+ } else {
container.put(key, value);
}
reset();
}
}
- private void reset()
- {
+ private void reset() {
oldValue = null;
flags = 0;
setValid(true);
}
- public void rollbackUpdate()
- {
+ public void rollbackUpdate() {
value = oldValue;
reset();
}
- public boolean isChanged()
- {
+ public boolean isChanged() {
return isFlagSet(CHANGED);
}
- public boolean isValid()
- {
+ public boolean isValid() {
return isFlagSet(VALID);
}
- public void setValid(boolean valid)
- {
+ public void setValid(boolean valid) {
if (valid)
setFlag(VALID);
else
unsetFlag(VALID);
}
- public boolean isCreated()
- {
+ public boolean isCreated() {
return isFlagSet(CREATED);
}
- public void setCreated(boolean created)
- {
+ public void setCreated(boolean created) {
if (created)
setFlag(CREATED);
else
unsetFlag(CREATED);
}
- public boolean isDeleted()
- {
+ public boolean isDeleted() {
return isFlagSet(DELETED);
}
- public void setDeleted(boolean deleted)
- {
+ public void setDeleted(boolean deleted) {
if (deleted)
setFlag(DELETED);
else
unsetFlag(DELETED);
}
- public String toString()
- {
+ public String toString() {
return getClass().getSimpleName() + "(" + System.identityHashCode(this) + "){" +
"key=" + key +
", value=" + value +
Modified: core/branches/flat/src/main/java/org/horizon/container/RepeatableReadEntry.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/container/RepeatableReadEntry.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/container/RepeatableReadEntry.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -32,30 +32,25 @@
* @author Manik Surtani (<a href="mailto:manik at jboss.org">manik at jboss.org</a>)
* @since 1.0
*/
-public class RepeatableReadEntry extends ReadCommittedEntry
-{
+public class RepeatableReadEntry extends ReadCommittedEntry {
private static final Log log = LogFactory.getLog(RepeatableReadEntry.class);
- public RepeatableReadEntry(Object key, Object value)
- {
+ public RepeatableReadEntry(Object key, Object value) {
super(key, value);
}
@Override
- public void copyForUpdate(DataContainer container, boolean writeSkewCheck)
- {
+ public void copyForUpdate(DataContainer container, boolean writeSkewCheck) {
if (isFlagSet(CHANGED)) return; // already copied
// mark node as changed.
setFlag(CHANGED);
- if (writeSkewCheck)
- {
+ if (writeSkewCheck) {
// check for write skew.
Object actualValue = container.get(key);
- if (actualValue != null && actualValue != value)
- {
+ if (actualValue != null && actualValue != value) {
String errormsg = new StringBuilder().append("Detected write skew on key [").append(getKey()).append("]. Another process has changed the entry since we last read it!").toString();
if (log.isWarnEnabled()) log.warn(errormsg + ". Unable to copy entry for update.");
throw new CacheException(errormsg);
Modified: core/branches/flat/src/main/java/org/horizon/container/UnsortedDataContainer.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/container/UnsortedDataContainer.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/container/UnsortedDataContainer.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -31,52 +31,42 @@
* @author Manik Surtani (<a href="mailto:manik at jboss.org">manik at jboss.org</a>)
* @since 1.0
*/
-public class UnsortedDataContainer<K, V> implements DataContainer<K, V>
-{
+public class UnsortedDataContainer<K, V> implements DataContainer<K, V> {
private final ConcurrentMap<K, V> data = new ConcurrentHashMap<K, V>();
- public V get(K k)
- {
+ public V get(K k) {
return data.get(k);
}
- public void put(K k, V v)
- {
+ public void put(K k, V v) {
data.put(k, v);
}
- public boolean containsKey(K k)
- {
+ public boolean containsKey(K k) {
return data.containsKey(k);
}
- public V remove(K k)
- {
+ public V remove(K k) {
return data.remove(k);
}
- public int size()
- {
+ public int size() {
return data.size();
}
- public void clear()
- {
+ public void clear() {
data.clear();
}
- public Set<K> keySet()
- {
+ public Set<K> keySet() {
return data.keySet();
}
- public boolean evict(Object key)
- {
+ public boolean evict(Object key) {
throw new UnsupportedOperationException("Not implemented");//todo please implement!
}
- public String toString()
- {
+ public String toString() {
return data.toString();
}
}
Modified: core/branches/flat/src/main/java/org/horizon/context/EntryLookup.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/context/EntryLookup.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/context/EntryLookup.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -31,8 +31,7 @@
* @author Manik Surtani (<a href="mailto:manik at jboss.org">manik at jboss.org</a>)
* @since 1.0
*/
-public interface EntryLookup
-{
+public interface EntryLookup {
MVCCEntry lookupEntry(Object key);
Map<Object, MVCCEntry> getLookedUpEntries();
Modified: core/branches/flat/src/main/java/org/horizon/context/InvocationContext.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/context/InvocationContext.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/context/InvocationContext.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -33,8 +33,7 @@
* @author Manik Surtani (<a href="mailto:manik at jboss.org">manik at jboss.org</a>)
* @since 1.0
*/
-public interface InvocationContext extends EntryLookup
-{
+public interface InvocationContext extends EntryLookup {
void setLocalRollbackOnly(boolean localRollbackOnly);
Transaction getTransaction();
Modified: core/branches/flat/src/main/java/org/horizon/context/InvocationContextImpl.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/context/InvocationContextImpl.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/context/InvocationContextImpl.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -42,8 +42,7 @@
* @author Manik Surtani (<a href="mailto:manik at jboss.org">manik at jboss.org</a>)
* @since 1.0
*/
-public class InvocationContextImpl implements InvocationContext
-{
+public class InvocationContextImpl implements InvocationContext {
private static final Log log = LogFactory.getLog(InvocationContext.class);
private static final boolean trace = log.isTraceEnabled();
@@ -59,8 +58,8 @@
* LinkedHashSet of locks acquired by the invocation. We use a LinkedHashSet because we need efficient Set semantics
* but also need guaranteed ordering for use by lock release code (see JBCCACHE-874).
* <p/>
- * This needs to be unchecked since we support both MVCC (Fqns held here) or legacy Opt/Pess locking (NodeLocks held here).
- * once we drop support for opt/pess locks we can genericise this to contain Fqns. - Manik Surtani, June 2008
+ * This needs to be unchecked since we support both MVCC (Fqns held here) or legacy Opt/Pess locking (NodeLocks held
+ * here). once we drop support for opt/pess locks we can genericise this to contain Fqns. - Manik Surtani, June 2008
*/
protected LinkedHashSet<Object> invocationLocks;
private FastCopyHashMap<Object, MVCCEntry> lookedUpEntries = null;
@@ -74,26 +73,18 @@
* @param k key to look up
* @return a node, or null if it cannot be found.
*/
- public MVCCEntry lookupEntry(Object k)
- {
- if (transactionContext != null)
- {
+ public MVCCEntry lookupEntry(Object k) {
+ if (transactionContext != null) {
return transactionContext.lookupEntry(k);
- }
- else
- {
+ } else {
return lookedUpEntries == null ? null : lookedUpEntries.get(k);
}
}
- public void removeLookedUpEntry(Object key)
- {
- if (transactionContext != null)
- {
+ public void removeLookedUpEntry(Object key) {
+ if (transactionContext != null) {
transactionContext.removeLookedUpEntry(key);
- }
- else
- {
+ } else {
if (lookedUpEntries != null) lookedUpEntries.remove(key);
}
}
@@ -101,28 +92,25 @@
/**
* Puts an entry in the registry of looked up nodes in the current scope.
* <p/>
- * If a transaction is in progress, implementations should delegate to {@link TransactionContext#putLookedUpEntry(Object, org.horizon.container.MVCCEntry)}
+ * If a transaction is in progress, implementations should delegate to {@link TransactionContext#putLookedUpEntry(Object,
+ * org.horizon.container.MVCCEntry)}
* <p/>
*
* @param key
*/
- public void putLookedUpEntry(Object key, MVCCEntry e)
- {
+ public void putLookedUpEntry(Object key, MVCCEntry e) {
if (transactionContext != null)
transactionContext.putLookedUpEntry(key, e);
- else
- {
+ else {
if (lookedUpEntries == null) lookedUpEntries = new FastCopyHashMap<Object, MVCCEntry>(4);
lookedUpEntries.put(key, e);
}
}
- public void putLookedUpEntries(Map<Object, MVCCEntry> lookedUpEntries)
- {
+ public void putLookedUpEntries(Map<Object, MVCCEntry> lookedUpEntries) {
if (transactionContext != null)
transactionContext.putLookedUpEntries(lookedUpEntries);
- else
- {
+ else {
if (this.lookedUpEntries == null)
this.lookedUpEntries = new FastCopyHashMap<Object, MVCCEntry>();
@@ -133,8 +121,7 @@
/**
* Clears the registry of looked up nodes.
*/
- public void clearLookedUpEntries()
- {
+ public void clearLookedUpEntries() {
if (lookedUpEntries != null) lookedUpEntries.clear();
}
@@ -147,15 +134,13 @@
* @return a map of looked up nodes.
*/
@SuppressWarnings("unchecked")
- public Map<Object, MVCCEntry> getLookedUpEntries()
- {
+ public Map<Object, MVCCEntry> getLookedUpEntries() {
if (transactionContext != null) return transactionContext.getLookedUpEntries();
return (Map<Object, MVCCEntry>) (lookedUpEntries == null ? Collections.emptyMap() : lookedUpEntries);
}
@SuppressWarnings("unchecked")
- public InvocationContext copy()
- {
+ public InvocationContext copy() {
InvocationContextImpl copy = new InvocationContextImpl();
doCopy(copy);
if (lookedUpEntries != null) copy.lookedUpEntries = (FastCopyHashMap<Object, MVCCEntry>) lookedUpEntries.clone();
@@ -168,8 +153,7 @@
*
* @param localRollbackOnly if true, the context is only rolling back.
*/
- public void setLocalRollbackOnly(boolean localRollbackOnly)
- {
+ public void setLocalRollbackOnly(boolean localRollbackOnly) {
this.localRollbackOnly = localRollbackOnly;
}
@@ -178,8 +162,7 @@
*
* @return The transaction associated with this invocation
*/
- public Transaction getTransaction()
- {
+ public Transaction getTransaction() {
return transaction;
}
@@ -188,17 +171,16 @@
*
* @param transaction transaction to set
*/
- public void setTransaction(Transaction transaction)
- {
+ public void setTransaction(Transaction transaction) {
this.transaction = transaction;
}
/**
- * @return the transaction entry associated with the current transaction, or null if the current thread is not associated with a transaction.
+ * @return the transaction entry associated with the current transaction, or null if the current thread is not
+ * associated with a transaction.
* @since 1.0
*/
- public TransactionContext getTransactionContext()
- {
+ public TransactionContext getTransactionContext() {
return transactionContext;
}
@@ -208,8 +190,7 @@
* @param transactionContext transaction context to set
* @since 1.0
*/
- public void setTransactionContext(TransactionContext transactionContext)
- {
+ public void setTransactionContext(TransactionContext transactionContext) {
this.transactionContext = transactionContext;
}
@@ -218,8 +199,7 @@
*
* @return the global transaction associated with this invocation
*/
- public GlobalTransaction getGlobalTransaction()
- {
+ public GlobalTransaction getGlobalTransaction() {
return globalTransaction;
}
@@ -228,8 +208,7 @@
*
* @param globalTransaction global transaction to set
*/
- public void setGlobalTransaction(GlobalTransaction globalTransaction)
- {
+ public void setGlobalTransaction(GlobalTransaction globalTransaction) {
this.globalTransaction = globalTransaction;
}
@@ -239,10 +218,8 @@
*
* @return the option overrides associated with this invocation
*/
- public Option getOptionOverrides()
- {
- if (optionOverrides == null)
- {
+ public Option getOptionOverrides() {
+ if (optionOverrides == null) {
optionOverrides = new Option();
}
return optionOverrides;
@@ -251,8 +228,7 @@
/**
* @return true of no options have been set on this context, false otherwise.
*/
- public boolean isOptionsUninitialised()
- {
+ public boolean isOptionsUninitialised() {
return optionOverrides == null;
}
@@ -261,8 +237,7 @@
*
* @param optionOverrides options to set
*/
- public void setOptionOverrides(Option optionOverrides)
- {
+ public void setOptionOverrides(Option optionOverrides) {
this.optionOverrides = optionOverrides;
}
@@ -271,22 +246,21 @@
*
* @return true if the invocation originated locally.
*/
- public boolean isOriginLocal()
- {
+ public boolean isOriginLocal() {
return originLocal;
}
/**
* Returns an immutable, defensive copy of the List of locks currently maintained for the current scope.
* <p/>
- * Note that if a transaction is in scope, implementations should retrieve these locks from the {@link TransactionContext}.
- * Retrieving locks from this method should always ensure they are retrieved from the appropriate scope.
+ * Note that if a transaction is in scope, implementations should retrieve these locks from the {@link
+ * TransactionContext}. Retrieving locks from this method should always ensure they are retrieved from the
+ * appropriate scope.
*
* @return locks held in current scope.
*/
@SuppressWarnings("unchecked")
- public List<Object> getKeysLocked()
- {
+ public List<Object> getKeysLocked() {
// first check transactional scope
if (transactionContext != null) return transactionContext.getKeysLocked();
return invocationLocks == null || invocationLocks.isEmpty() ? Collections.emptyList() : Immutables.immutableListConvert(invocationLocks);
@@ -298,18 +272,15 @@
* Note that if a transaction is in scope, implementations should record locks on the {@link TransactionContext}.
* Adding locks using this method should always ensure they are applied to the appropriate scope.
* <p/>
+ *
* @param locks locks to add
*/
@SuppressWarnings("unchecked")
- public void addAllKeysLocked(List<Object> locks)
- {
+ public void addAllKeysLocked(List<Object> locks) {
// first check transactional scope
- if (transactionContext != null)
- {
+ if (transactionContext != null) {
transactionContext.addAllKeysLocked(locks);
- }
- else
- {
+ } else {
// no need to worry about concurrency here - a context is only valid for a single thread.
if (invocationLocks == null) invocationLocks = new LinkedHashSet(4);
invocationLocks.addAll(locks);
@@ -326,15 +297,11 @@
* @param lock lock to add
*/
@SuppressWarnings("unchecked")
- public void addKeyLocked(Object lock)
- {
+ public void addKeyLocked(Object lock) {
// first check transactional scope
- if (transactionContext != null)
- {
+ if (transactionContext != null) {
transactionContext.addKeyLocked(lock);
- }
- else
- {
+ } else {
// no need to worry about concurrency here - a context is only valid for a single thread.
if (invocationLocks == null) invocationLocks = new LinkedHashSet(4);
invocationLocks.add(lock);
@@ -344,22 +311,18 @@
/**
* Removes a lock from the currently maintained collection of locks acquired.
* <p/>
- * Note that if a transaction is in scope, implementations should remove this lock from the {@link TransactionContext}.
- * Using this method should always ensure that the lock is removed from the appropriate scope.
+ * Note that if a transaction is in scope, implementations should remove this lock from the {@link
+ * TransactionContext}. Using this method should always ensure that the lock is removed from the appropriate scope.
* <p/>
*
* @param lock lock to remove
*/
@SuppressWarnings("unchecked")
- public void removeKeyLocked(Object lock)
- {
+ public void removeKeyLocked(Object lock) {
// first check transactional scope
- if (transactionContext != null)
- {
+ if (transactionContext != null) {
transactionContext.removeKeyLocked(lock);
- }
- else
- {
+ } else {
// no need to worry about concurrency here - a context is only valid for a single thread.
if (invocationLocks != null) invocationLocks.remove(lock);
}
@@ -372,15 +335,11 @@
* Using this method should always ensure locks are cleared in the appropriate scope.
* <p/>
*/
- public void clearKeysLocked()
- {
+ public void clearKeysLocked() {
// first check transactional scope
- if (transactionContext != null)
- {
+ if (transactionContext != null) {
transactionContext.clearKeysLocked();
- }
- else
- {
+ } else {
// no need to worry about concurrency here - a context is only valid for a single thread.
if (invocationLocks != null) invocationLocks.clear();
}
@@ -393,15 +352,11 @@
* @param lock lock to test
* @return true if the lock being tested is already held in the current scope, false otherwise.
*/
- public boolean hasLockedKey(Object lock)
- {
+ public boolean hasLockedKey(Object lock) {
// first check transactional scope
- if (transactionContext != null)
- {
+ if (transactionContext != null) {
return transactionContext.hasLockedKey(lock);
- }
- else
- {
+ } else {
return invocationLocks != null && invocationLocks.contains(lock);
}
}
@@ -409,42 +364,37 @@
/**
* @return true if options exist to suppress locking - false otherwise.
*/
- public boolean isLockingSuppressed()
- {
+ public boolean isLockingSuppressed() {
return getOptionOverrides() != null && getOptionOverrides().isSuppressLocking();
}
/**
- * If set to true, the invocation is assumed to have originated locally. If set to false,
- * assumed to have originated from a remote cache.
+ * If set to true, the invocation is assumed to have originated locally. If set to false, assumed to have originated
+ * from a remote cache.
*
* @param originLocal flag to set
*/
- public void setOriginLocal(boolean originLocal)
- {
+ public void setOriginLocal(boolean originLocal) {
this.originLocal = originLocal;
}
/**
* @return true if the current transaction is set to rollback only.
*/
- public boolean isLocalRollbackOnly()
- {
+ public boolean isLocalRollbackOnly() {
return localRollbackOnly;
}
/**
* Resets the context, freeing up any references.
*/
- public void reset()
- {
+ public void reset() {
transaction = null;
globalTransaction = null;
optionOverrides = null;
originLocal = true;
invocationLocks = null;
- if (lookedUpEntries != null)
- {
+ if (lookedUpEntries != null) {
lookedUpEntries.clear();
lookedUpEntries = null;
}
@@ -455,10 +405,8 @@
*
* @param template template to copy from
*/
- public void setState(InvocationContext template)
- {
- if (template == null)
- {
+ public void setState(InvocationContext template) {
+ if (template == null) {
throw new NullPointerException("Template InvocationContext passed in to InvocationContext.setState() passed in is null");
}
@@ -470,28 +418,26 @@
}
/**
- * If the lock acquisition timeout is overridden for current call using an option, then return that one.
- * If not overridden, return default value.
+ * If the lock acquisition timeout is overridden for current call using an option, then return that one. If not
+ * overridden, return default value.
*
* @param timeout timeout to fall back to
* @return timeout to use
*/
- public long getLockAcquisitionTimeout(long timeout)
- {
+ public long getLockAcquisitionTimeout(long timeout) {
// TODO: this stuff really doesn't belong here. Put it somewhere else.
if (getOptionOverrides() != null
- && getOptionOverrides().getLockAcquisitionTimeout() >= 0)
- {
+ && getOptionOverrides().getLockAcquisitionTimeout() >= 0) {
timeout = getOptionOverrides().getLockAcquisitionTimeout();
}
return timeout;
}
/**
- * @return true if there is current transaction associated with the invocation, and this transaction is in a valid state.
+ * @return true if there is current transaction associated with the invocation, and this transaction is in a valid
+ * state.
*/
- public boolean isValidTransaction()
- {
+ public boolean isValidTransaction() {
// ought to move to the transaction context
return transaction != null && TransactionTable.isValid(transaction);
}
@@ -502,13 +448,11 @@
* @param e throwable to throw
* @throws Throwable if allowed to throw one.
*/
- public void throwIfNeeded(Throwable e) throws Throwable
- {
+ public void throwIfNeeded(Throwable e) throws Throwable {
// TODO: this stuff really doesn't belong here. Put it somewhere else.
Option optionOverride = getOptionOverrides();
boolean shouldRethtrow = optionOverride == null || !optionOverride.isFailSilently();
- if (!shouldRethtrow)
- {
+ if (!shouldRethtrow) {
if (trace)
log.trace("There was a problem handling this request, but failSilently was set, so suppressing exception", e);
return;
@@ -517,8 +461,7 @@
}
@SuppressWarnings("unchecked")
- protected void doCopy(InvocationContext c)
- {
+ protected void doCopy(InvocationContext c) {
InvocationContextImpl copy = (InvocationContextImpl) c;
copy.globalTransaction = globalTransaction;
copy.invocationLocks = invocationLocks == null ? null : new LinkedHashSet(invocationLocks);
@@ -530,8 +473,7 @@
}
@Override
- public boolean equals(Object o)
- {
+ public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
@@ -555,8 +497,7 @@
}
@Override
- public int hashCode()
- {
+ public int hashCode() {
int result = transaction != null ? transaction.hashCode() : 0;
result = 31 * result + (globalTransaction != null ? globalTransaction.hashCode() : 0);
result = 31 * result + (transactionContext != null ? transactionContext.hashCode() : 0);
@@ -569,8 +510,7 @@
}
@Override
- public String toString()
- {
+ public String toString() {
return "InvocationContextImpl{" +
"transaction=" + transaction +
", globalTransaction=" + globalTransaction +
Modified: core/branches/flat/src/main/java/org/horizon/context/TransactionContext.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/context/TransactionContext.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/context/TransactionContext.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -38,8 +38,7 @@
* @see InvocationContext
* @since 1.0
*/
-public interface TransactionContext extends EntryLookup
-{
+public interface TransactionContext extends EntryLookup {
/**
* Adds a modification to the modification list.
*
@@ -48,7 +47,8 @@
void addModification(VisitableCommand command);
/**
- * Returns all modifications. If there are no modifications in this transaction this method will return an empty list.
+ * Returns all modifications. If there are no modifications in this transaction this method will return an empty
+ * list.
*
* @return list of modifications.
*/
@@ -63,7 +63,8 @@
void addLocalModification(VisitableCommand command);
/**
- * Returns all modifications that have been invoked with the LOCAL cache mode option. These will also be in the standard modification list.
+ * Returns all modifications that have been invoked with the LOCAL cache mode option. These will also be in the
+ * standard modification list.
*
* @return list of LOCAL modifications, or an empty list.
*/
@@ -80,7 +81,8 @@
/**
* Gets the list of removed nodes.
*
- * @return list of nodes removed in the current transaction scope. Note that this method will return an empty list if nothing has been removed. The list returned is defensively copied.
+ * @return list of nodes removed in the current transaction scope. Note that this method will return an empty list
+ * if nothing has been removed. The list returned is defensively copied.
*/
List<Object> getRemovedEntries();
@@ -125,16 +127,17 @@
/**
* Clears all locks from the currently maintained collection of locks acquired.
* <p/>
- * Most code could not use this method directly, but use {@link InvocationContext#clearKeysLocked()} instead,
- * which would delegate to this method if a transaction is in scope or otherwise use invocation-specific locks.
+ * Most code could not use this method directly, but use {@link InvocationContext#clearKeysLocked()} instead, which
+ * would delegate to this method if a transaction is in scope or otherwise use invocation-specific locks.
*/
void clearKeysLocked();
/**
* Adds a List of locks to the currently maintained collection of locks acquired.
* <p/>
- * Most code could not use this method directly, but use {@link InvocationContext#addAllKeysLocked(java.util.List)} instead,
- * which would delegate to this method if a transaction is in scope or otherwise use invocation-specific locks.
+ * Most code could not use this method directly, but use {@link InvocationContext#addAllKeysLocked(java.util.List)}
+ * instead, which would delegate to this method if a transaction is in scope or otherwise use invocation-specific
+ * locks.
*
* @param newLocks locks to add
*/
@@ -145,7 +148,8 @@
* Returns an immutable, defensive copy of the List of locks currently maintained for the transaction.
* <p/>
* Most code could not use this method directly, but use {@link org.horizon.context.InvocationContext#getKeysLocked()}
- * instead, which would delegate to this method if a transaction is in scope or otherwise use invocation-specific locks.
+ * instead, which would delegate to this method if a transaction is in scope or otherwise use invocation-specific
+ * locks.
*
* @return locks held in current scope.
*/
@@ -163,7 +167,7 @@
/**
* Gets the value of the forceAsyncReplication flag.
- *
+ *
* @return true if the forceAsyncReplication flag is set to true.
*/
boolean isForceAsyncReplication();
Modified: core/branches/flat/src/main/java/org/horizon/context/TransactionContextImpl.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/context/TransactionContextImpl.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/context/TransactionContextImpl.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -44,8 +44,7 @@
* @author Manik Surtani (<a href="mailto:manik at jboss.org">manik at jboss.org</a>)
* @since 1.0
*/
-public class TransactionContextImpl implements TransactionContext
-{
+public class TransactionContextImpl implements TransactionContext {
/**
* Local transaction
*/
@@ -59,7 +58,8 @@
*/
private List<VisitableCommand> modificationList;
/**
- * A list of modifications that have been encountered with a LOCAL mode option. These will be removed from the modification list during replication.
+ * A list of modifications that have been encountered with a LOCAL mode option. These will be removed from the
+ * modification list during replication.
*/
private List<VisitableCommand> localModifications;
@@ -67,14 +67,14 @@
* LinkedHashSet of locks acquired by the transaction. We use a LinkedHashSet because we need efficient Set semantics
* but also need guaranteed ordering for use by lock release code (see JBCCACHE-874).
* <p/>
- * This needs to be unchecked since we support both MVCC (Fqns held here) or legacy Opt/Pess locking (NodeLocks held here).
- * once we drop support for opt/pess locks we can genericise this to contain Fqns. - Manik Surtani, June 2008
+ * This needs to be unchecked since we support both MVCC (Fqns held here) or legacy Opt/Pess locking (NodeLocks held
+ * here). once we drop support for opt/pess locks we can genericise this to contain Fqns. - Manik Surtani, June 2008
*/
private LinkedHashSet<Object> transactionLocks;
/**
- * A list of dummy uninitialised nodes created by the cache loader interceptor to load data for a
- * given node in this tx.
+ * A list of dummy uninitialised nodes created by the cache loader interceptor to load data for a given node in this
+ * tx.
*/
private List<Object> dummyNodesCreatedByCacheLoader;
@@ -86,38 +86,31 @@
private final FastCopyHashMap<Object, MVCCEntry> lookedUpEntries = new FastCopyHashMap<Object, MVCCEntry>(8);
private GlobalTransaction gtx;
- public TransactionContextImpl(Transaction tx) throws SystemException, RollbackException
- {
+ public TransactionContextImpl(Transaction tx) throws SystemException, RollbackException {
ltx = tx;
}
- public MVCCEntry lookupEntry(Object key)
- {
+ public MVCCEntry lookupEntry(Object key) {
return lookedUpEntries.get(key);
}
- public void removeLookedUpEntry(Object key)
- {
+ public void removeLookedUpEntry(Object key) {
lookedUpEntries.remove(key);
}
- public void putLookedUpEntry(Object key, MVCCEntry entry)
- {
+ public void putLookedUpEntry(Object key, MVCCEntry entry) {
lookedUpEntries.put(key, entry);
}
- public void clearLookedUpEntries()
- {
+ public void clearLookedUpEntries() {
lookedUpEntries.clear();
}
- public Map<Object, MVCCEntry> getLookedUpEntries()
- {
+ public Map<Object, MVCCEntry> getLookedUpEntries() {
return lookedUpEntries;
}
- public void reset()
- {
+ public void reset() {
modificationList = null;
localModifications = null;
option = null;
@@ -127,134 +120,111 @@
lookedUpEntries.clear();
}
- public GlobalTransaction getGobalTransaction()
- {
+ public GlobalTransaction getGobalTransaction() {
return gtx;
}
- public void putLookedUpEntries(Map<Object, MVCCEntry> entries)
- {
+ public void putLookedUpEntries(Map<Object, MVCCEntry> entries) {
lookedUpEntries.putAll(entries);
}
- public void addModification(VisitableCommand command)
- {
+ public void addModification(VisitableCommand command) {
if (command == null) return;
if (modificationList == null) modificationList = new LinkedList<VisitableCommand>();
modificationList.add(command);
}
- public List<VisitableCommand> getModifications()
- {
+ public List<VisitableCommand> getModifications() {
if (modificationList == null) return Collections.emptyList();
return modificationList;
}
- public void addLocalModification(VisitableCommand command)
- {
+ public void addLocalModification(VisitableCommand command) {
if (command == null) throw new NullPointerException("Command is null!");
if (localModifications == null) localModifications = new LinkedList<VisitableCommand>();
localModifications.add(command);
}
- public List<VisitableCommand> getLocalModifications()
- {
+ public List<VisitableCommand> getLocalModifications() {
if (localModifications == null) return Collections.emptyList();
return localModifications;
}
- public void addRemovedEntry(Object key)
- {
+ public void addRemovedEntry(Object key) {
if (key == null) throw new NullPointerException("Key is null!");
if (removedNodes == null) removedNodes = new LinkedList<Object>();
removedNodes.add(key);
}
- public List<Object> getRemovedEntries()
- {
+ public List<Object> getRemovedEntries() {
if (removedNodes == null) return Collections.emptyList();
return new ArrayList<Object>(removedNodes);
}
- public void setTransaction(Transaction tx)
- {
+ public void setTransaction(Transaction tx) {
ltx = tx;
}
- public void setGlobalTransaction(GlobalTransaction gtx)
- {
+ public void setGlobalTransaction(GlobalTransaction gtx) {
this.gtx = gtx;
}
- public Transaction getTransaction()
- {
+ public Transaction getTransaction() {
return ltx;
}
@SuppressWarnings("unchecked")
- public void addKeyLocked(Object lock)
- {
+ public void addKeyLocked(Object lock) {
// no need to worry about concurrency here - a context is only valid for a single thread.
if (transactionLocks == null) transactionLocks = new LinkedHashSet(5);
transactionLocks.add(lock);
}
@SuppressWarnings("unchecked")
- public void removeKeyLocked(Object lock)
- {
+ public void removeKeyLocked(Object lock) {
// no need to worry about concurrency here - a context is only valid for a single thread.
if (transactionLocks != null) transactionLocks.remove(lock);
}
- public void clearKeysLocked()
- {
+ public void clearKeysLocked() {
if (transactionLocks != null) transactionLocks.clear();
}
@SuppressWarnings("unchecked")
- public void addAllKeysLocked(List<Object> newLocks)
- {
+ public void addAllKeysLocked(List<Object> newLocks) {
// no need to worry about concurrency here - a context is only valid for a single thread.
if (transactionLocks == null) transactionLocks = new LinkedHashSet(5);
transactionLocks.addAll(newLocks);
}
@SuppressWarnings("unchecked")
- public List<Object> getKeysLocked()
- {
+ public List<Object> getKeysLocked() {
return transactionLocks == null || transactionLocks.isEmpty() ? Collections.emptyList() : Immutables.immutableListConvert(transactionLocks);
}
- public boolean hasLockedKey(Object lock)
- {
+ public boolean hasLockedKey(Object lock) {
return transactionLocks != null && transactionLocks.contains(lock);
}
- public boolean isForceAsyncReplication()
- {
+ public boolean isForceAsyncReplication() {
return forceAsyncReplication;
}
- public void setForceAsyncReplication(boolean forceAsyncReplication)
- {
+ public void setForceAsyncReplication(boolean forceAsyncReplication) {
this.forceAsyncReplication = forceAsyncReplication;
- if (forceAsyncReplication)
- {
+ if (forceAsyncReplication) {
forceSyncReplication = false;
}
}
- public boolean isForceSyncReplication()
- {
+ public boolean isForceSyncReplication() {
return forceSyncReplication;
}
- public void setForceSyncReplication(boolean forceSyncReplication)
- {
+ public void setForceSyncReplication(boolean forceSyncReplication) {
this.forceSyncReplication = forceSyncReplication;
- if (forceSyncReplication)
- {
+ if (forceSyncReplication) {
forceAsyncReplication = false;
}
}
@@ -263,48 +233,40 @@
* Returns debug information about this transaction.
*/
@Override
- public String toString()
- {
+ public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("TransactionContext (").append(System.identityHashCode(this)).append(") nmodificationList: ").append(modificationList);
return sb.toString();
}
- public void addDummyEntryCreatedByCacheLoader(Object key)
- {
+ public void addDummyEntryCreatedByCacheLoader(Object key) {
if (dummyNodesCreatedByCacheLoader == null)
dummyNodesCreatedByCacheLoader = new LinkedList<Object>();
dummyNodesCreatedByCacheLoader.add(key);
}
- public List<Object> getDummyEntriesCreatedByCacheLoader()
- {
+ public List<Object> getDummyEntriesCreatedByCacheLoader() {
if (dummyNodesCreatedByCacheLoader == null) return Collections.emptyList();
return dummyNodesCreatedByCacheLoader;
}
- public void setOption(Option o)
- {
+ public void setOption(Option o) {
this.option = o;
}
- public Option getOption()
- {
+ public Option getOption() {
return this.option;
}
- public boolean hasModifications()
- {
+ public boolean hasModifications() {
return modificationList != null && !modificationList.isEmpty();
}
- public boolean hasLocalModifications()
- {
+ public boolean hasLocalModifications() {
return localModifications != null && !localModifications.isEmpty();
}
- public boolean hasAnyModifications()
- {
+ public boolean hasAnyModifications() {
return hasModifications() || hasLocalModifications();
}
}
Modified: core/branches/flat/src/main/java/org/horizon/eviction/DefaultEvictionAction.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/eviction/DefaultEvictionAction.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/eviction/DefaultEvictionAction.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -31,29 +31,24 @@
* @author Manik Surtani (<a href="mailto:manik at jboss.org">manik at jboss.org</a>)
* @since 1.0
*/
-public class DefaultEvictionAction<K> implements EvictionAction<K>
-{
+public class DefaultEvictionAction<K> implements EvictionAction<K> {
private static final Log log = LogFactory.getLog(DefaultEvictionAction.class);
private static boolean trace = log.isTraceEnabled();
private Cache<K, ?> cache;
- public void setCache(Cache<K, ?> cache)
- {
+ public void setCache(Cache<K, ?> cache) {
this.cache = cache;
}
- public boolean evict(K key)
- {
+ public boolean evict(K key) {
if (trace) log.trace("Attempting to evict cache node with key of " + key);
- try
- {
+ try {
cache.evict(key);
log.trace("Eviction of cache node with key of " + key + " successful");
return true;
}
- catch (Exception e)
- {
+ catch (Exception e) {
if (log.isDebugEnabled()) log.debug("Unable to evict " + key, e);
return false;
}
Modified: core/branches/flat/src/main/java/org/horizon/eviction/ElementSizeAlgorithmConfig.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/eviction/ElementSizeAlgorithmConfig.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/eviction/ElementSizeAlgorithmConfig.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -33,8 +33,7 @@
* @author Manik Surtani
* @since 1.0
*/
-public class ElementSizeAlgorithmConfig extends EvictionAlgorithmConfigBase
-{
+public class ElementSizeAlgorithmConfig extends EvictionAlgorithmConfigBase {
/**
* The serialVersionUID
*/
@@ -43,49 +42,41 @@
@Dynamic
private int maxElementsPerNode;
- public ElementSizeAlgorithmConfig()
- {
+ public ElementSizeAlgorithmConfig() {
evictionAlgorithmClassName = ElementSizeAlgorithm.class.getName();
// Force configuration of maxElementsPerNode
setMaxElementsPerNode(-1);
}
- public ElementSizeAlgorithmConfig(int maxNodes, int maxElementsPerNode)
- {
+ public ElementSizeAlgorithmConfig(int maxNodes, int maxElementsPerNode) {
this();
setMaxNodes(maxNodes);
setMaxElementsPerNode(maxElementsPerNode);
}
- public int getMaxElementsPerNode()
- {
+ public int getMaxElementsPerNode() {
return maxElementsPerNode;
}
- public void setMaxElementsPerNode(int maxElementsPerNode)
- {
+ public void setMaxElementsPerNode(int maxElementsPerNode) {
testImmutability("maxElementsPerNode");
this.maxElementsPerNode = maxElementsPerNode;
}
/**
- * Requires a positive maxElementsPerNode value or ConfigurationException
- * is thrown.
+ * Requires a positive maxElementsPerNode value or ConfigurationException is thrown.
*/
@Override
- public void validate() throws ConfigurationException
- {
+ public void validate() throws ConfigurationException {
super.validate();
- if (maxElementsPerNode < 0)
- {
+ if (maxElementsPerNode < 0) {
throw new ConfigurationException("maxElementsPerNode must be must be " +
"configured to a value greater than or equal to 0");
}
}
@Override
- public String toString()
- {
+ public String toString() {
StringBuilder str = new StringBuilder();
str.append("ElementSizeConfiguration: maxElementsPerNode =");
str.append(getMaxElementsPerNode()).append(" maxNodes =").append(getMaxNodes());
@@ -93,36 +84,31 @@
}
@Override
- public boolean equals(Object obj)
- {
+ public boolean equals(Object obj) {
if (this == obj)
return true;
- if (obj instanceof ElementSizeAlgorithmConfig && super.equals(obj))
- {
+ if (obj instanceof ElementSizeAlgorithmConfig && super.equals(obj)) {
return this.maxElementsPerNode == ((ElementSizeAlgorithmConfig) obj).maxElementsPerNode;
}
return false;
}
@Override
- public int hashCode()
- {
+ public int hashCode() {
int result = super.hashCode();
result = 31 * result + maxElementsPerNode;
return result;
}
@Override
- public void reset()
- {
+ public void reset() {
super.reset();
setMaxElementsPerNode(-1);
evictionAlgorithmClassName = ElementSizeAlgorithm.class.getName();
}
@Override
- public ElementSizeAlgorithmConfig clone() throws CloneNotSupportedException
- {
+ public ElementSizeAlgorithmConfig clone() throws CloneNotSupportedException {
return (ElementSizeAlgorithmConfig) super.clone();
}
}
\ No newline at end of file
Modified: core/branches/flat/src/main/java/org/horizon/eviction/ElementSizeQueue.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/eviction/ElementSizeQueue.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/eviction/ElementSizeQueue.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -29,8 +29,7 @@
* @author Daniel Huang
* @since 1.0
*/
-public class ElementSizeQueue<K> implements SortedEvictionQueue<K>
-{
+public class ElementSizeQueue<K> implements SortedEvictionQueue<K> {
private Map<K, KeyEntry<K>> nodeMap;
private LinkedList<KeyEntry<K>> evictionList;
private Comparator<KeyEntry> comparator;
@@ -38,60 +37,48 @@
private Set<KeyEntry> removalQueue;
private int numElements = 0;
- public ElementSizeQueue()
- {
+ public ElementSizeQueue() {
nodeMap = new HashMap<K, KeyEntry<K>>();
evictionList = new LinkedList<KeyEntry<K>>();
comparator = new MaxElementComparator();
removalQueue = new HashSet<KeyEntry>();
}
- public void resortEvictionQueue()
- {
+ public void resortEvictionQueue() {
Collections.sort(evictionList, comparator);
}
- public KeyEntry<K> getFirstNodeEntry()
- {
- try
- {
+ public KeyEntry<K> getFirstNodeEntry() {
+ try {
KeyEntry<K> ne;
- while ((ne = evictionList.getFirst()) != null)
- {
- if (removalQueue.contains(ne))
- {
+ while ((ne = evictionList.getFirst()) != null) {
+ if (removalQueue.contains(ne)) {
evictionList.removeFirst();
removalQueue.remove(ne);
- } else
- {
+ } else {
break;
}
}
return ne;
}
- catch (NoSuchElementException e)
- {
+ catch (NoSuchElementException e) {
//
}
return null;
}
- public KeyEntry<K> getNodeEntry(K key)
- {
+ public KeyEntry<K> getNodeEntry(K key) {
return nodeMap.get(key);
}
- public boolean containsNodeEntry(KeyEntry<K> entry)
- {
+ public boolean containsNodeEntry(KeyEntry<K> entry) {
K key = entry.getKey();
return this.getNodeEntry(key) != null;
}
- public void removeNodeEntry(KeyEntry<K> entry)
- {
+ public void removeNodeEntry(KeyEntry<K> entry) {
KeyEntry ne = nodeMap.remove(entry.getKey());
- if (ne != null)
- {
+ if (ne != null) {
// don't remove directly from the LinkedList otherwise we will incur a O(n) = n
// performance penalty for every removal! In the prune method for LFU, we will iterate the LinkedList through ONCE
// doing a single O(n) = n operation and removal. This is much preferred over running O(n) = n every single time
@@ -105,10 +92,8 @@
}
}
- public void addNodeEntry(KeyEntry<K> entry)
- {
- if (!this.containsNodeEntry(entry))
- {
+ public void addNodeEntry(KeyEntry<K> entry) {
+ if (!this.containsNodeEntry(entry)) {
K key = entry.getKey();
nodeMap.put(key, entry);
evictionList.add(entry);
@@ -116,87 +101,71 @@
}
}
- public int getNumberOfNodes()
- {
+ public int getNumberOfNodes() {
return nodeMap.size();
}
- public int getNumberOfElements()
- {
+ public int getNumberOfElements() {
return this.numElements;
}
- public void modifyElementCount(int difference)
- {
+ public void modifyElementCount(int difference) {
this.numElements += difference;
}
- public void clear()
- {
+ public void clear() {
nodeMap.clear();
evictionList.clear();
removalQueue.clear();
this.numElements = 0;
}
-
- protected final List<KeyEntry<K>> getEvictionList()
- {
+
+ protected final List<KeyEntry<K>> getEvictionList() {
return evictionList;
}
- protected final Set<KeyEntry> getRemovalQueue()
- {
+ protected final Set<KeyEntry> getRemovalQueue() {
return removalQueue;
}
- public final void prune()
- {
+ public final void prune() {
Iterator<KeyEntry<K>> it = evictionList.iterator();
- while (it.hasNext() && removalQueue.size() > 0)
- {
- if (removalQueue.remove(it.next()))
- {
+ while (it.hasNext() && removalQueue.size() > 0) {
+ if (removalQueue.remove(it.next())) {
it.remove();
}
}
}
- public Iterator<KeyEntry<K>> iterator()
- {
+ public Iterator<KeyEntry<K>> iterator() {
return evictionList.iterator();
}
/**
* Comparator class for Max Elements.
* <p/>
- * This class will sort the eviction queue in the correct eviction order.
- * The top of the list should evict before the bottom of the list.
+ * This class will sort the eviction queue in the correct eviction order. The top of the list should evict before the
+ * bottom of the list.
* <p/>
* The sort is based on descending order of numElements.
* <p/>
* Note: this class has a natural ordering that is inconsistent with equals as defined by the java.lang.Comparator
* contract.
*/
- protected static class MaxElementComparator implements Comparator<KeyEntry>
- {
+ protected static class MaxElementComparator implements Comparator<KeyEntry> {
- public int compare(KeyEntry ne1, KeyEntry ne2)
- {
- if (ne1.equals(ne2))
- {
+ public int compare(KeyEntry ne1, KeyEntry ne2) {
+ if (ne1.equals(ne2)) {
return 0;
}
int neNumElements = ne1.getNumberOfElements();
int neNumElements2 = ne2.getNumberOfElements();
- if (neNumElements > neNumElements2)
- {
+ if (neNumElements > neNumElements2) {
return -1;
- } else if (neNumElements < neNumElements2)
- {
+ } else if (neNumElements < neNumElements2) {
return 1;
- } else if (neNumElements == neNumElements2)
- {
+ } else if (neNumElements == neNumElements2) {
return 0;
}
throw new RuntimeException("Should never reach this condition");
Modified: core/branches/flat/src/main/java/org/horizon/eviction/EvictionAction.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/eviction/EvictionAction.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/eviction/EvictionAction.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -29,8 +29,7 @@
* @author Manik Surtani (<a href="mailto:manik at jboss.org">manik at jboss.org</a>)
* @since 1.0
*/
-public interface EvictionAction<K>
-{
+public interface EvictionAction<K> {
/**
* Sets a reference to the cache.
*
Modified: core/branches/flat/src/main/java/org/horizon/eviction/EvictionAlgorithm.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/eviction/EvictionAlgorithm.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/eviction/EvictionAlgorithm.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -37,11 +37,10 @@
* @author Daniel Huang - dhuang at jboss.org - 10/2005
* @since 1.0
*/
-public interface EvictionAlgorithm<K>
-{
+public interface EvictionAlgorithm<K> {
/**
- * Entry point for eviction algorithm. Invoking this will cause the algorithm to process the queue of {@link EvictionEvent}
- * passed in.
+ * Entry point for eviction algorithm. Invoking this will cause the algorithm to process the queue of {@link
+ * EvictionEvent} passed in.
*/
void process(BlockingQueue<EvictionEvent<K>> queue) throws EvictionException;
Modified: core/branches/flat/src/main/java/org/horizon/eviction/EvictionAlgorithmConfigBase.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/eviction/EvictionAlgorithmConfigBase.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/eviction/EvictionAlgorithmConfigBase.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -34,8 +34,7 @@
* @author Manik Surtani (<a href="mailto:manik at jboss.org">manik at jboss.org</a>)
* @since 1.0
*/
-public abstract class EvictionAlgorithmConfigBase extends ConfigurationComponent implements EvictionAlgorithmConfig
-{
+public abstract class EvictionAlgorithmConfigBase extends ConfigurationComponent implements EvictionAlgorithmConfig {
private static final long serialVersionUID = 4591691674370188932L;
protected String evictionAlgorithmClassName;
@@ -47,22 +46,18 @@
/**
* Can only be instantiated by a subclass.
*/
- protected EvictionAlgorithmConfigBase()
- {
+ protected EvictionAlgorithmConfigBase() {
}
- public String getEvictionAlgorithmClassName()
- {
+ public String getEvictionAlgorithmClassName() {
return evictionAlgorithmClassName;
}
- public int getMaxNodes()
- {
+ public int getMaxNodes() {
return maxNodes;
}
- public void setMaxNodes(int maxNodes)
- {
+ public void setMaxNodes(int maxNodes) {
testImmutability("maxNodes");
this.maxNodes = maxNodes;
}
@@ -70,34 +65,29 @@
/**
* @return The minimum time to live, in milliseconds.
*/
- public long getMinTimeToLive()
- {
+ public long getMinTimeToLive() {
return minTimeToLive;
}
/**
* @param minTimeToLive time to live, in milliseconds
*/
- public void setMinTimeToLive(long minTimeToLive)
- {
+ public void setMinTimeToLive(long minTimeToLive) {
testImmutability("minTimeToLive");
this.minTimeToLive = minTimeToLive;
}
- public void setMinTimeToLive(long time, TimeUnit timeUnit)
- {
+ public void setMinTimeToLive(long time, TimeUnit timeUnit) {
testImmutability("minTimeToLive");
minTimeToLive = timeUnit.toMillis(time);
}
- public void validate() throws ConfigurationException
- {
+ public void validate() throws ConfigurationException {
if (evictionAlgorithmClassName == null)
throw new ConfigurationException("Eviction algorithm class name cannot be null!");
}
- public boolean equals(Object o)
- {
+ public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof EvictionAlgorithmConfigBase)) return false;
@@ -111,8 +101,7 @@
return true;
}
- public int hashCode()
- {
+ public int hashCode() {
int result;
result = (evictionAlgorithmClassName != null ? evictionAlgorithmClassName.hashCode() : 0);
result = 31 * result + maxNodes;
@@ -121,14 +110,12 @@
return result;
}
- public void reset()
- {
+ public void reset() {
maxNodes = 0;
minTimeToLive = 0;
}
- public EvictionAlgorithmConfig clone() throws CloneNotSupportedException
- {
+ public EvictionAlgorithmConfig clone() throws CloneNotSupportedException {
return (EvictionAlgorithmConfig) super.clone();
}
}
Modified: core/branches/flat/src/main/java/org/horizon/eviction/EvictionCacheManager.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/eviction/EvictionCacheManager.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/eviction/EvictionCacheManager.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -8,8 +8,7 @@
* @author Mircea.Markus at jboss.com
* @since 1.0
*/
-public interface EvictionCacheManager<K>
-{
+public interface EvictionCacheManager<K> {
/**
* Processes the eviction queues (primary and recycle queues) associated with this cache.
*/
@@ -28,14 +27,14 @@
void configure(EvictionCacheConfig evictionCacheConfig);
/**
- * Registers an eviction event on the cache's eviction event queue for later processing by
- * {@link #processEvictionQueues()}.
+ * Registers an eviction event on the cache's eviction event queue for later processing by {@link
+ * #processEvictionQueues()}.
*/
EvictionEvent registerEvictionEvent(K key, EvictionEvent.Type eventType, int elementDifference);
/**
- * An overloaded version of {@link #registerEvictionEvent(Object, org.horizon.eviction.EvictionEvent.Type, int)} which
- * uses a default elementDifference value.
+ * An overloaded version of {@link #registerEvictionEvent(Object, org.horizon.eviction.EvictionEvent.Type, int)}
+ * which uses a default elementDifference value.
*
* @param eventType passed in to the constructor of {@link org.horizon.eviction.EvictionEvent}
* @return an EvictedEventNode that has been created for this queue
Modified: core/branches/flat/src/main/java/org/horizon/eviction/EvictionCacheManagerImpl.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/eviction/EvictionCacheManagerImpl.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/eviction/EvictionCacheManagerImpl.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -1,11 +1,11 @@
package org.horizon.eviction;
-import org.horizon.config.EvictionCacheConfig;
-import org.horizon.config.EvictionAlgorithmConfig;
-import org.horizon.util.Util;
-import org.horizon.CacheSPI;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
+import org.horizon.CacheSPI;
+import org.horizon.config.EvictionAlgorithmConfig;
+import org.horizon.config.EvictionCacheConfig;
+import org.horizon.util.Util;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
@@ -14,8 +14,7 @@
* @author Mircea.Markus at jboss.com
* @since 1.0
*/
-public class EvictionCacheManagerImpl<K> implements EvictionCacheManager<K>
-{
+public class EvictionCacheManagerImpl<K> implements EvictionCacheManager<K> {
private static Log log = LogFactory.getLog(EvictionCacheManagerImpl.class);
private static boolean trace = log.isTraceEnabled();
@@ -23,103 +22,85 @@
private int capacityWarnThreshold = 0;
private EvictionCacheConfig evictionCacheConfig;
private EvictionAlgorithm<K> evictionAlgorithm;
- private CacheSPI<K,?> cache;
+ private CacheSPI<K, ?> cache;
- public EvictionCacheManagerImpl(CacheSPI<K, ?> cache)
- {
+ public EvictionCacheManagerImpl(CacheSPI<K, ?> cache) {
this.cache = cache;
}
- public void processEvictionQueues()
- {
+ public void processEvictionQueues() {
evictionAlgorithm.process(evictionEventQueue);
}
- public void resetEvictionQueues()
- {
+ public void resetEvictionQueues() {
evictionEventQueue.clear();
}
- public EvictionEvent registerEvictionEvent(K key, EvictionEvent.Type eventType, int elementDifference)
- {
+ public EvictionEvent registerEvictionEvent(K key, EvictionEvent.Type eventType, int elementDifference) {
if (evictionAlgorithm.canIgnoreEvent(eventType)) return null;
EvictionEvent<K> event = new EvictionEvent<K>(key, eventType, elementDifference);
registerEvictionEvent(event);
return event;
}
- public EvictionEvent registerEvictionEvent(K key, EvictionEvent.Type eventType)
- {
+ public EvictionEvent registerEvictionEvent(K key, EvictionEvent.Type eventType) {
return registerEvictionEvent(key, eventType, 0);
}
- public void markNodeCurrentlyInUse(K key, long timeout)
- {
+ public void markNodeCurrentlyInUse(K key, long timeout) {
registerEvictionEvent(key, EvictionEvent.Type.MARK_IN_USE_EVENT, 0).setInUseTimeout(timeout);
}
- public void unmarkNodeCurrentlyInUse(K key)
- {
+ public void unmarkNodeCurrentlyInUse(K key) {
registerEvictionEvent(key, EvictionEvent.Type.UNMARK_USE_EVENT, 0);
}
- public void configure(EvictionCacheConfig evictionCacheConfig)
- {
+ public void configure(EvictionCacheConfig evictionCacheConfig) {
this.evictionCacheConfig = evictionCacheConfig;
evictionAlgorithm = createEvictionAlgorithm(evictionCacheConfig.getEvictionAlgorithmConfig(), evictionCacheConfig.getEvictionActionClassName());
if (evictionEventQueue == null) createQueue();
evictionAlgorithm.initialize();
}
- private void registerEvictionEvent(EvictionEvent<K> ee)
- {
- try
- {
+ private void registerEvictionEvent(EvictionEvent<K> ee) {
+ try {
createQueue();// in case the queue does not exist yet.
- if (evictionEventQueue.size() > capacityWarnThreshold)
- {
+ if (evictionEventQueue.size() > capacityWarnThreshold) {
if (log.isWarnEnabled())
log.warn("putNodeEvent(): eviction node event queue size is at 98% threshold value of capacity: " + evictionCacheConfig.getEventQueueSize() +
" Cache name: " + cache.getName() + " You will need to reduce the wakeUpIntervalSeconds parameter.");
}
evictionEventQueue.put(ee);
}
- catch (InterruptedException e)
- {
+ catch (InterruptedException e) {
if (log.isDebugEnabled()) log.debug("Interrupted on adding event", e);
// reinstate interrupt flag
Thread.currentThread().interrupt();
}
}
- private void createQueue()
- {
- if (evictionEventQueue == null)
- {
- if (evictionCacheConfig == null)
- {
+ private void createQueue() {
+ if (evictionEventQueue == null) {
+ if (evictionCacheConfig == null) {
throw new IllegalArgumentException("null eviction configuration");
}
int size = evictionCacheConfig.getEventQueueSize();
capacityWarnThreshold = (98 * size) / 100 - 100;
- if (capacityWarnThreshold <= 0)
- {
+ if (capacityWarnThreshold <= 0) {
if (log.isWarnEnabled()) log.warn("Capacity warn threshold used in eviction is smaller than 1.");
}
evictionEventQueue = new LinkedBlockingQueue<EvictionEvent<K>>(size);
}
}
- private EvictionAlgorithm<K> createEvictionAlgorithm(EvictionAlgorithmConfig algoConfig, String evictionActionClass)
- {
+ private EvictionAlgorithm<K> createEvictionAlgorithm(EvictionAlgorithmConfig algoConfig, String evictionActionClass) {
if (algoConfig == null)
throw new IllegalArgumentException("Eviction algorithm class must not be null!");
if (evictionActionClass == null)
throw new IllegalArgumentException("Eviction action policy class must not be null!");
- try
- {
+ try {
if (trace) log.trace("Instantiating " + evictionActionClass);
EvictionAction<K> evictionAction = (EvictionAction<K>) Util.getInstance(evictionActionClass);
evictionAction.setCache(cache);
@@ -130,15 +111,13 @@
algorithm.assignToCache(cache, algoConfig);
return algorithm;
}
- catch (Exception e)
- {
+ catch (Exception e) {
log.fatal("Unable to instantiate eviction algorithm " + algoConfig.getEvictionAlgorithmClassName(), e);
throw new IllegalStateException(e);
}
}
- public String getCacheName()
- {
+ public String getCacheName() {
return cache.getName();
}
}
Modified: core/branches/flat/src/main/java/org/horizon/eviction/EvictionEvent.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/eviction/EvictionEvent.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/eviction/EvictionEvent.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -22,13 +22,12 @@
package org.horizon.eviction;
/**
- * An eviction event records activity on nodes in the cache. These are recorded for processing
- * later.
- * @since 1.0
+ * An eviction event records activity on nodes in the cache. These are recorded for processing later.
+ *
* @author (various)
+ * @since 1.0
*/
-public class EvictionEvent<K>
-{
+public class EvictionEvent<K> {
private K key;
private Type type;
private int elementDifference;
@@ -36,12 +35,10 @@
private long inUseTimeout;
private long creationTimestamp;
- public EvictionEvent()
- {
+ public EvictionEvent() {
}
- public static enum Type
- {
+ public static enum Type {
ADD_NODE_EVENT,
REMOVE_NODE_EVENT,
VISIT_NODE_EVENT,
@@ -51,62 +48,51 @@
UNMARK_USE_EVENT
}
- public EvictionEvent(K key, Type type, int elementDifference)
- {
+ public EvictionEvent(K key, Type type, int elementDifference) {
this.key = key;
this.type = type;
this.elementDifference = elementDifference;
this.creationTimestamp = System.currentTimeMillis();
}
- public long getCreationTimestamp()
- {
+ public long getCreationTimestamp() {
return creationTimestamp;
}
- public long getInUseTimeout()
- {
+ public long getInUseTimeout() {
return inUseTimeout;
}
- public void setInUseTimeout(long inUseTimeout)
- {
+ public void setInUseTimeout(long inUseTimeout) {
this.inUseTimeout = inUseTimeout;
}
- public int getElementDifference()
- {
+ public int getElementDifference() {
return elementDifference;
}
- public void setElementDifference(int elementDifference)
- {
+ public void setElementDifference(int elementDifference) {
this.elementDifference = elementDifference;
}
- public K getKey()
- {
+ public K getKey() {
return key;
}
- public void setKey(K key)
- {
+ public void setKey(K key) {
this.key = key;
}
- public void setEventType(Type event)
- {
+ public void setEventType(Type event) {
type = event;
}
- public Type getEventType()
- {
+ public Type getEventType() {
return type;
}
@Override
- public String toString()
- {
+ public String toString() {
return "EvictedEventNode[key=" + key + " event=" + type + " diff=" + elementDifference + "]";
}
@@ -116,8 +102,7 @@
* @param key new Fqn root to use
* @return a new EvictedEventNode instance
*/
- public EvictionEvent copy(K key)
- {
+ public EvictionEvent copy(K key) {
return new EvictionEvent<K>(key, type, elementDifference);
}
}
Modified: core/branches/flat/src/main/java/org/horizon/eviction/EvictionException.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/eviction/EvictionException.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/eviction/EvictionException.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -27,23 +27,19 @@
* @author Ben Wang, Feb 11, 2004
* @since 1.0
*/
-public class EvictionException extends CacheException
-{
+public class EvictionException extends CacheException {
private static final long serialVersionUID = 4006783737166646935L;
- public EvictionException()
- {
+ public EvictionException() {
super();
}
- public EvictionException(String msg)
- {
+ public EvictionException(String msg) {
super(msg);
}
- public EvictionException(String msg, Throwable cause)
- {
+ public EvictionException(String msg, Throwable cause) {
super(msg, cause);
}
Modified: core/branches/flat/src/main/java/org/horizon/eviction/EvictionManagerImpl.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/eviction/EvictionManagerImpl.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/eviction/EvictionManagerImpl.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -14,8 +14,7 @@
* @since 1.0
*/
@ThreadSafe
-public class EvictionManagerImpl implements EvictionManager
-{
+public class EvictionManagerImpl implements EvictionManager {
private static Log log = LogFactory.getLog(EvictionManagerImpl.class);
private boolean externalEvictionThread;
private EvictionTimerTask evictionTimerTask;
@@ -23,10 +22,8 @@
private ThreadFactory threadFactory;
private long wakeUpInterval;
- public synchronized void configureEvictionThread(long wakeUpInterval, ThreadFactory threadFactory)
- {
- if (wakeUpInterval <= 0)
- {
+ public synchronized void configureEvictionThread(long wakeUpInterval, ThreadFactory threadFactory) {
+ if (wakeUpInterval <= 0) {
log.info("wakeUpInterval is <= 0, not starting eviction thread");
externalEvictionThread = true;
return;
@@ -36,8 +33,7 @@
evictionTimerTask = new EvictionTimerTask(this);
}
- public synchronized void cacheCreated(String cacheName, EvictionCacheManager cacheManager)
- {
+ public synchronized void cacheCreated(String cacheName, EvictionCacheManager cacheManager) {
if (!externalEvictionThread && evictionCacheManagers.isEmpty())//this is the first cache to be added, also start ev thread here
{
evictionTimerTask.init(wakeUpInterval, threadFactory);
@@ -45,30 +41,22 @@
evictionCacheManagers.put(cacheName, cacheManager);
}
- public synchronized void cacheStopped(String cacheName)
- {
- if (evictionCacheManagers.remove(cacheName) == null)
- {
+ public synchronized void cacheStopped(String cacheName) {
+ if (evictionCacheManagers.remove(cacheName) == null) {
throw new IllegalStateException("Attempting to stop an unregistred cache: " + cacheName);
}
- if (!externalEvictionThread && evictionCacheManagers.isEmpty())
- {
+ if (!externalEvictionThread && evictionCacheManagers.isEmpty()) {
evictionTimerTask.stop();
}
}
- public void runEviction()
- {
- synchronized (evictionCacheManagers)
- {
- for (EvictionCacheManager evictionCacheManager : evictionCacheManagers.values())
- {
- try
- {
+ public void runEviction() {
+ synchronized (evictionCacheManagers) {
+ for (EvictionCacheManager evictionCacheManager : evictionCacheManagers.values()) {
+ try {
evictionCacheManager.processEvictionQueues();
}
- catch (EvictionException e)
- {
+ catch (EvictionException e) {
//we cannot die in peace here, as this is not the main thread and the user won't get informed...
log.error("run(): error processing eviction with exception: " + e.toString()
+ " will reset the eviction queue list.", e);
Modified: core/branches/flat/src/main/java/org/horizon/eviction/EvictionQueue.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/eviction/EvictionQueue.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/eviction/EvictionQueue.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -28,11 +28,9 @@
* EvictionAlgorithm/EvictionQueue/EvictionConfiguration are only operated on by one thread at any given time.
*
* @author Daniel Huang (dhuang at jboss.org)
- *
* @since 1.0
*/
-public interface EvictionQueue<K> extends Iterable<KeyEntry<K>>
-{
+public interface EvictionQueue<K> extends Iterable<KeyEntry<K>> {
/**
* Get the first entry in the queue.
* <p/>
Modified: core/branches/flat/src/main/java/org/horizon/eviction/EvictionTimerTask.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/eviction/EvictionTimerTask.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/eviction/EvictionTimerTask.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -38,8 +38,7 @@
* @author Daniel Huang (dhuang at jboss.org)
* @since 1.0
*/
-public class EvictionTimerTask
-{
+public class EvictionTimerTask {
private Log log = LogFactory.getLog(EvictionTimerTask.class);
private static AtomicInteger tcount = new AtomicInteger();
@@ -49,14 +48,12 @@
private EvictionManager evictionManager;
- public EvictionTimerTask(EvictionManager evManager)
- {
+ public EvictionTimerTask(EvictionManager evManager) {
this.evictionManager = evManager;
task = new Task();
}
- public void init(long wakeupInterval, ThreadFactory evictionThreadFactory)
- {
+ public void init(long wakeupInterval, ThreadFactory evictionThreadFactory) {
if (log.isTraceEnabled())
log.trace("Creating a new eviction timer task with wakeupInterval millis set at " + wakeupInterval);
this.wakeupInterval = wakeupInterval;
@@ -64,22 +61,17 @@
}
- public void stop()
- {
+ public void stop() {
if (log.isDebugEnabled()) log.debug("Stopping eviction timer");
- if (scheduledExecutor != null)
- {
+ if (scheduledExecutor != null) {
scheduledExecutor.shutdownNow();
}
scheduledExecutor = null;
}
- private void start(ThreadFactory tf)
- {
- if (tf == null) tf = new ThreadFactory()
- {
- public Thread newThread(Runnable r)
- {
+ private void start(ThreadFactory tf) {
+ if (tf == null) tf = new ThreadFactory() {
+ public Thread newThread(Runnable r) {
Thread t = new Thread(r, "EvictionTimer-" + tcount.getAndIncrement());
t.setDaemon(true);
return t;
@@ -89,10 +81,8 @@
scheduledExecutor.scheduleWithFixedDelay(task, wakeupInterval, wakeupInterval, TimeUnit.MILLISECONDS);
}
- public class Task implements Runnable
- {
- public void run()
- {
+ public class Task implements Runnable {
+ public void run() {
evictionManager.runEviction();
}
}
Modified: core/branches/flat/src/main/java/org/horizon/eviction/EvictionWatcher.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/eviction/EvictionWatcher.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/eviction/EvictionWatcher.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -16,29 +16,24 @@
* @since 1.0
*/
@CacheListener
-public class EvictionWatcher
-{
+public class EvictionWatcher {
Cache<?, ?> cache;
List<Object> keysToWaitFor;
- public EvictionWatcher(Cache<?, ?> cache, Fqn... keysToWaitFor)
- {
+ public EvictionWatcher(Cache<?, ?> cache, Fqn... keysToWaitFor) {
// this(cache, Arrays.asList(keysToWaitFor));
}
- public EvictionWatcher(Cache<?, ?> cache, List<Object> keysToWaitFor)
- {
+ public EvictionWatcher(Cache<?, ?> cache, List<Object> keysToWaitFor) {
this.cache = cache;
this.keysToWaitFor = new ArrayList<Object>(keysToWaitFor);
cache.addCacheListener(this);
}
@CacheEntryEvicted
- public void receive(CacheEntryEvictedEvent ee)
- {
+ public void receive(CacheEntryEvictedEvent ee) {
boolean xpect = false;
- if (ee.isPre() && keysToWaitFor.contains(ee.getKey()))
- {
+ if (ee.isPre() && keysToWaitFor.contains(ee.getKey())) {
xpect = true;
keysToWaitFor.remove(ee.getKey());
}
@@ -46,8 +41,7 @@
if (ee.isPre()) System.out.println("Saw " + ee.getKey() + " was expecting? " + xpect);
}
- public boolean allNodesEvicted()
- {
+ public boolean allNodesEvicted() {
return keysToWaitFor.isEmpty();
}
}
\ No newline at end of file
Modified: core/branches/flat/src/main/java/org/horizon/eviction/ExpirationAlgorithmConfig.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/eviction/ExpirationAlgorithmConfig.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/eviction/ExpirationAlgorithmConfig.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -28,11 +28,11 @@
/**
* Configuration for indicating the Node key for setting a specific eviction time.
- * @since 1.0
+ *
* @author (various)
+ * @since 1.0
*/
-public class ExpirationAlgorithmConfig extends EvictionAlgorithmConfigBase
-{
+public class ExpirationAlgorithmConfig extends EvictionAlgorithmConfigBase {
private static final long serialVersionUID = 47338798734219507L;
@@ -53,49 +53,42 @@
@Dynamic
private long timeToLive = 0;
- public ExpirationAlgorithmConfig()
- {
+ public ExpirationAlgorithmConfig() {
evictionAlgorithmClassName = ExpirationAlgorithm.class.getName();
}
/**
- * Returns the expirationKeyName.
- * This key should point to a java.lang.Long value in the Node data.
+ * Returns the expirationKeyName. This key should point to a java.lang.Long value in the Node data.
*/
- public String getExpirationKeyName()
- {
+ public String getExpirationKeyName() {
return expirationKeyName;
}
/**
* Sets the expirationKeyName.
*/
- public void setExpirationKeyName(String expirationKeyName)
- {
+ public void setExpirationKeyName(String expirationKeyName) {
this.expirationKeyName = expirationKeyName;
}
/**
* Returns true if the algorithm should warn if a expiration key is missing for a node.
*/
- public boolean isWarnNoExpirationKey()
- {
+ public boolean isWarnNoExpirationKey() {
return warnNoExpirationKey;
}
/**
* Sets if the algorithm should warn if a expiration key is missing for a node.
*/
- public void setWarnNoExpirationKey(boolean warnNoExpirationKey)
- {
+ public void setWarnNoExpirationKey(boolean warnNoExpirationKey) {
this.warnNoExpirationKey = warnNoExpirationKey;
}
/**
* @return time to live, in milliseconds
*/
- public long getTimeToLive()
- {
+ public long getTimeToLive() {
return timeToLive;
}
@@ -104,24 +97,20 @@
*
* @param timeToLive value in milliseconds
*/
- public void setTimeToLive(long timeToLive)
- {
+ public void setTimeToLive(long timeToLive) {
this.timeToLive = timeToLive;
}
- public void setTimeToLive(long timeToLive, TimeUnit timeUnit)
- {
+ public void setTimeToLive(long timeToLive, TimeUnit timeUnit) {
this.timeToLive = timeUnit.toMillis(timeToLive);
}
@Override
- public ExpirationAlgorithmConfig clone() throws CloneNotSupportedException
- {
+ public ExpirationAlgorithmConfig clone() throws CloneNotSupportedException {
return (ExpirationAlgorithmConfig) super.clone();
}
- public boolean equals(Object o)
- {
+ public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
if (!super.equals(o)) return false;
@@ -136,8 +125,7 @@
return true;
}
- public int hashCode()
- {
+ public int hashCode() {
int result = super.hashCode();
result = 31 * result + (expirationKeyName != null ? expirationKeyName.hashCode() : 0);
result = 31 * result + (warnNoExpirationKey ? 1 : 0);
@@ -146,8 +134,7 @@
}
@Override
- public void reset()
- {
+ public void reset() {
super.reset();
evictionAlgorithmClassName = ExpirationAlgorithm.class.getName();
warnNoExpirationKey = true;
Modified: core/branches/flat/src/main/java/org/horizon/eviction/KeyEntry.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/eviction/KeyEntry.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/eviction/KeyEntry.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -28,8 +28,7 @@
* @author Daniel Huang - dhuang at jboss.org
* @since 1.0
*/
-public class KeyEntry<K>
-{
+public class KeyEntry<K> {
private long modifiedTimeStamp;
private long creationTimeStamp;
private int numberOfNodeVisits;
@@ -44,19 +43,16 @@
/**
* Private constructor that automatically sets the creation time stamp of the node entry.
*/
- private KeyEntry()
- {
+ private KeyEntry() {
this.creationTimeStamp = System.currentTimeMillis();
}
- public KeyEntry(K key)
- {
+ public KeyEntry(K key) {
this();
setKey(key);
}
- public KeyEntry(int numberOfNodeVisits, long modifiedTimeStamp, int numberOfElements, K key)
- {
+ public KeyEntry(int numberOfNodeVisits, long modifiedTimeStamp, int numberOfElements, K key) {
this(key);
this.numberOfNodeVisits = numberOfNodeVisits;
this.modifiedTimeStamp = modifiedTimeStamp;
@@ -68,38 +64,32 @@
*
* @return True/false if the node is currently marked as in use.
*/
- public boolean isCurrentlyInUse()
- {
+ public boolean isCurrentlyInUse() {
return currentlyInUse;
}
- public void setCurrentlyInUse(boolean currentlyInUse, long inUseTimeout)
- {
+ public void setCurrentlyInUse(boolean currentlyInUse, long inUseTimeout) {
this.currentlyInUse = currentlyInUse;
- if (inUseTimeout > 0)
- {
+ if (inUseTimeout > 0) {
this.inUseTimeoutTimestamp = System.currentTimeMillis() + inUseTimeout;
}
}
- public long getInUseTimeoutTimestamp()
- {
+ public long getInUseTimeoutTimestamp() {
return this.inUseTimeoutTimestamp;
}
/**
- * Get modified time stamp. This stamp is created during the node is
- * processed so it has some fuzy tolerance in there.
+ * Get modified time stamp. This stamp is created during the node is processed so it has some fuzy tolerance in
+ * there.
*
* @return The last modified time stamp
*/
- public long getModifiedTimeStamp()
- {
+ public long getModifiedTimeStamp() {
return modifiedTimeStamp;
}
- public void setModifiedTimeStamp(long modifiedTimeStamp)
- {
+ public void setModifiedTimeStamp(long modifiedTimeStamp) {
// log.error("Being modified to " + modifiedTimeStamp, new Throwable());
this.modifiedTimeStamp = modifiedTimeStamp;
}
@@ -109,73 +99,58 @@
*
* @return The node entry creation time stamp
*/
- public long getCreationTimeStamp()
- {
+ public long getCreationTimeStamp() {
return creationTimeStamp;
}
- public void setCreationTimeStamp(long creationTimeStamp)
- {
+ public void setCreationTimeStamp(long creationTimeStamp) {
this.creationTimeStamp = creationTimeStamp;
}
- public int getNumberOfNodeVisits()
- {
+ public int getNumberOfNodeVisits() {
return numberOfNodeVisits;
}
- public void setNumberOfNodeVisits(int numberOfNodeVisits)
- {
+ public void setNumberOfNodeVisits(int numberOfNodeVisits) {
this.numberOfNodeVisits = numberOfNodeVisits;
}
- public void incerementNumberOfNodeVisits()
- {
- this.numberOfNodeVisits ++;
+ public void incerementNumberOfNodeVisits() {
+ this.numberOfNodeVisits++;
}
- public int getNumberOfElements()
- {
+ public int getNumberOfElements() {
return numberOfElements;
}
- public void setNumberOfElements(int numberOfElements)
- {
- if (queue != null)
- {
+ public void setNumberOfElements(int numberOfElements) {
+ if (queue != null) {
int difference = numberOfElements - this.numberOfElements;
queue.modifyElementCount(difference);
}
this.numberOfElements = numberOfElements;
}
- public K getKey()
- {
+ public K getKey() {
return key;
}
- void setKey(K key)
- {
+ void setKey(K key) {
this.key = key;
}
@Override
- public int hashCode()
- {
+ public int hashCode() {
return key.hashCode();
}
- public boolean isNodeInUseAndNotTimedOut()
- {
- if (isCurrentlyInUse())
- {
- if (getInUseTimeoutTimestamp() == 0)
- {
+ public boolean isNodeInUseAndNotTimedOut() {
+ if (isCurrentlyInUse()) {
+ if (getInUseTimeoutTimestamp() == 0) {
return true;
}
- if (System.currentTimeMillis() < getInUseTimeoutTimestamp())
- {
+ if (System.currentTimeMillis() < getInUseTimeoutTimestamp()) {
return true;
}
}
@@ -185,17 +160,16 @@
/**
* Tests whether a node entry is younger than the minimum time to live - if one is configured.
*
- * @return true if the node is younger than - or exactly equal to - the minimum time to live, if one is configured for the given region. False otherwise.
+ * @return true if the node is younger than - or exactly equal to - the minimum time to live, if one is configured
+ * for the given region. False otherwise.
*/
- public boolean isYoungerThanMinimumTimeToLive(long minTTL)
- {
+ public boolean isYoungerThanMinimumTimeToLive(long minTTL) {
return minTTL >= 1 && (getModifiedTimeStamp() + minTTL > System.currentTimeMillis());
}
@Override
- public boolean equals(Object o)
- {
+ public boolean equals(Object o) {
if (!(o instanceof KeyEntry))
return false;
KeyEntry ne = (KeyEntry) o;
@@ -203,16 +177,12 @@
}
@Override
- public String toString()
- {
+ public String toString() {
StringBuilder output = new StringBuilder();
output.append("Fqn: ");
- if (key != null)
- {
+ if (key != null) {
output.append(key);
- }
- else
- {
+ } else {
output.append(" null");
}
@@ -224,8 +194,7 @@
return output.toString();
}
- public void setQueue(EvictionQueue queue)
- {
+ public void setQueue(EvictionQueue queue) {
this.queue = queue;
}
}
Modified: core/branches/flat/src/main/java/org/horizon/eviction/RegionNameConflictException.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/eviction/RegionNameConflictException.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/eviction/RegionNameConflictException.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -27,23 +27,19 @@
* @author Ben Wang 2-2004
* @since 1.0
*/
-public class RegionNameConflictException extends Exception
-{
+public class RegionNameConflictException extends Exception {
private static final long serialVersionUID = -6796150029431162837L;
- public RegionNameConflictException()
- {
+ public RegionNameConflictException() {
super();
}
- public RegionNameConflictException(String msg)
- {
+ public RegionNameConflictException(String msg) {
super(msg);
}
- public RegionNameConflictException(String msg, Throwable cause)
- {
+ public RegionNameConflictException(String msg, Throwable cause) {
super(msg, cause);
}
}
Modified: core/branches/flat/src/main/java/org/horizon/eviction/RemoveOnEvictActionPolicy.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/eviction/RemoveOnEvictActionPolicy.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/eviction/RemoveOnEvictActionPolicy.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -31,25 +31,20 @@
* @author Manik Surtani (<a href="mailto:manik at jboss.org">manik at jboss.org</a>)
* @since 1.0
*/
-public class RemoveOnEvictActionPolicy<K> implements EvictionAction<K>
-{
+public class RemoveOnEvictActionPolicy<K> implements EvictionAction<K> {
private Cache<K, ?> cache;
private static final Log log = LogFactory.getLog(DefaultEvictionAction.class);
- public void setCache(Cache<K, ?> cache)
- {
+ public void setCache(Cache<K, ?> cache) {
this.cache = cache;
}
- public boolean evict(K key)
- {
- try
- {
+ public boolean evict(K key) {
+ try {
cache.remove(key);
return true;
}
- catch (Exception e)
- {
+ catch (Exception e) {
if (log.isDebugEnabled()) log.debug("Unable to evict " + key, e);
return false;
}
Modified: core/branches/flat/src/main/java/org/horizon/eviction/algorithms/BaseEvictionAlgorithm.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/eviction/algorithms/BaseEvictionAlgorithm.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/eviction/algorithms/BaseEvictionAlgorithm.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -25,25 +25,28 @@
import org.apache.commons.logging.LogFactory;
import org.horizon.CacheSPI;
import org.horizon.config.EvictionAlgorithmConfig;
-import org.horizon.eviction.*;
+import org.horizon.eviction.EvictionAction;
+import org.horizon.eviction.EvictionAlgorithm;
+import org.horizon.eviction.EvictionEvent;
import org.horizon.eviction.EvictionEvent.Type;
+import org.horizon.eviction.EvictionException;
+import org.horizon.eviction.EvictionQueue;
+import org.horizon.eviction.KeyEntry;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
/**
- * Abstract Event Processing Eviction Algorithm.
- * This class is used to implement basic event processing for Eviction Algorithms.
- * To extend this abstract class to make an Eviction Algorithm, implement the
- * abstract methods and a policy.
+ * Abstract Event Processing Eviction Algorithm. This class is used to implement basic event processing for Eviction
+ * Algorithms. To extend this abstract class to make an Eviction Algorithm, implement the abstract methods and a
+ * policy.
*
* @author Daniel Huang - dhuang at jboss.org 10/2005
* @author <a href="mailto:galder.zamarreno at jboss.com">Galder Zamarreno</a>
* @since 1.0
*/
-public abstract class BaseEvictionAlgorithm<K> implements EvictionAlgorithm<K>
-{
+public abstract class BaseEvictionAlgorithm<K> implements EvictionAlgorithm<K> {
private static final Log log = LogFactory.getLog(BaseEvictionAlgorithm.class);
private static final boolean trace = log.isTraceEnabled();
protected EvictionAction<K> evictionAction;
@@ -68,58 +71,48 @@
*/
protected abstract boolean shouldEvictNode(KeyEntry<K> ne);
- protected BaseEvictionAlgorithm()
- {
+ protected BaseEvictionAlgorithm() {
recycleQueue = new LinkedBlockingQueue<K>(500000);
}
- public synchronized void initialize()
- {
- if (evictionQueue == null)
- {
+ public synchronized void initialize() {
+ if (evictionQueue == null) {
evictionQueue = setupEvictionQueue();
}
}
- public EvictionAction getEvictionActionPolicy()
- {
+ public EvictionAction getEvictionActionPolicy() {
return evictionAction;
}
- public void setEvictionAction(EvictionAction<K> evictionAction)
- {
+ public void setEvictionAction(EvictionAction<K> evictionAction) {
this.evictionAction = evictionAction;
}
- public EvictionAlgorithmConfig getEvictionAlgorithmConfig()
- {
+ public EvictionAlgorithmConfig getEvictionAlgorithmConfig() {
return evictionAlgorithmConfig;
}
- public void assignToCache(CacheSPI<K, ?> cache, EvictionAlgorithmConfig evictionAlgorithmConfig)
- {
+ public void assignToCache(CacheSPI<K, ?> cache, EvictionAlgorithmConfig evictionAlgorithmConfig) {
this.cache = cache;
this.evictionAlgorithmConfig = evictionAlgorithmConfig;
}
- public boolean canIgnoreEvent(Type eventType)
- {
+ public boolean canIgnoreEvent(Type eventType) {
return false; // don't ignore anything!
}
/**
* Process the given eviction event queue. Eviction Processing encompasses the following:
* <p/>
- * - Add/Remove/Visit Nodes
- * - Prune according to Eviction Algorithm
- * - Empty/Retry the recycle queue of previously evicted but locked (during actual cache eviction) nodes.
+ * - Add/Remove/Visit Nodes - Prune according to Eviction Algorithm - Empty/Retry the recycle queue of previously
+ * evicted but locked (during actual cache eviction) nodes.
*
* @param eventQueue queue containing eviction events
* @throws org.horizon.eviction.EvictionException
*
*/
- public void process(BlockingQueue<EvictionEvent<K>> eventQueue) throws org.horizon.eviction.EvictionException
- {
+ public void process(BlockingQueue<EvictionEvent<K>> eventQueue) throws org.horizon.eviction.EvictionException {
if (trace) log.trace("process(): cache: " + cache);
initialize();
this.processQueues(eventQueue);
@@ -127,8 +120,7 @@
this.prune();
}
- public void resetEvictionQueue()
- {
+ public void resetEvictionQueue() {
// a no-op
}
@@ -138,19 +130,15 @@
* @return the EvictionQueue used by this algorithm
* @see org.horizon.eviction.EvictionQueue
*/
- public EvictionQueue getEvictionQueue()
- {
+ public EvictionQueue getEvictionQueue() {
return this.evictionQueue;
}
- protected EvictionEvent<K> getNextInQueue(BlockingQueue<EvictionEvent<K>> queue)
- {
- try
- {
+ protected EvictionEvent<K> getNextInQueue(BlockingQueue<EvictionEvent<K>> queue) {
+ try {
return queue.poll(0, TimeUnit.SECONDS);
}
- catch (InterruptedException e)
- {
+ catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
return null;
@@ -159,23 +147,20 @@
/**
* Event processing for Evict/Add/Visiting of nodes.
* <p/>
- * - On AddEvents a new element is added into the eviction queue
- * - On RemoveEvents, the removed element is removed from the eviction queue.
- * - On VisitEvents, the visited node has its eviction statistics updated (idleTime, numberOfNodeVisists, etc..)
+ * - On AddEvents a new element is added into the eviction queue - On RemoveEvents, the removed element is removed
+ * from the eviction queue. - On VisitEvents, the visited node has its eviction statistics updated (idleTime,
+ * numberOfNodeVisists, etc..)
*
* @param queue queue to inspect
* @throws org.horizon.eviction.EvictionException
* in the event of problems
*/
- protected void processQueues(BlockingQueue<EvictionEvent<K>> queue) throws org.horizon.eviction.EvictionException
- {
+ protected void processQueues(BlockingQueue<EvictionEvent<K>> queue) throws org.horizon.eviction.EvictionException {
EvictionEvent<K> node;
int count = 0;
- while ((node = getNextInQueue(queue)) != null)
- {
+ while ((node = getNextInQueue(queue)) != null) {
count++;
- switch (node.getEventType())
- {
+ switch (node.getEventType()) {
case ADD_NODE_EVENT:
this.processAddedNodes(node);
break;
@@ -204,56 +189,44 @@
if (trace) log.trace("processed " + count + " node events");
}
- protected void evict(KeyEntry<K> ne)
- {
- if (ne != null)
- {
+ protected void evict(KeyEntry<K> ne) {
+ if (ne != null) {
evictionQueue.removeNodeEntry(ne);
- if (!evictionAction.evict(ne.getKey()))
- {
- try
- {
+ if (!evictionAction.evict(ne.getKey())) {
+ try {
boolean result = recycleQueue.offer(ne.getKey(), 5, TimeUnit.SECONDS);
- if (!result)
- {
+ if (!result) {
log.warn("Unable to add Fqn[" + ne.getKey() + "] to recycle " +
"queue because it's full. This is often sign that " +
"evictions are not occurring and nodes that should be " +
"evicted are piling up waiting to be evicted.");
}
}
- catch (InterruptedException e)
- {
+ catch (InterruptedException e) {
log.debug("InterruptedException", e);
}
}
}
}
- protected void processMarkInUseNodes(K key, long inUseTimeout) throws EvictionException
- {
- if (trace)
- {
+ protected void processMarkInUseNodes(K key, long inUseTimeout) throws EvictionException {
+ if (trace) {
log.trace("Marking " + key + " as in use with a usage timeout of " + inUseTimeout);
}
KeyEntry ne = evictionQueue.getNodeEntry(key);
- if (ne != null)
- {
+ if (ne != null) {
ne.setCurrentlyInUse(true, inUseTimeout);
}
}
- protected void processUnmarkInUseNodes(K key) throws EvictionException
- {
- if (trace)
- {
+ protected void processUnmarkInUseNodes(K key) throws EvictionException {
+ if (trace) {
log.trace("Unmarking node " + key + " as in use");
}
KeyEntry ne = evictionQueue.getNodeEntry(key);
- if (ne != null)
- {
+ if (ne != null) {
ne.setCurrentlyInUse(false, 0);
}
}
@@ -265,18 +238,15 @@
* @param evictedEventNode an evictedEventNode to process
* @throws EvictionException on problems
*/
- protected void processAddedNodes(EvictionEvent<K> evictedEventNode) throws EvictionException
- {
+ protected void processAddedNodes(EvictionEvent<K> evictedEventNode) throws EvictionException {
processAddedNodes(evictedEventNode, evictedEventNode.getElementDifference());
}
- protected void processAddedNodes(EvictionEvent<K> evictedEventNode, int numAddedElements) throws EvictionException
- {
+ protected void processAddedNodes(EvictionEvent<K> evictedEventNode, int numAddedElements) throws EvictionException {
K key = evictedEventNode.getKey();
if (trace) log.trace("Adding node " + key + " with " + numAddedElements + " elements to eviction queue");
KeyEntry<K> ne = evictionQueue.getNodeEntry(key);
- if (ne != null)
- {
+ if (ne != null) {
ne.setModifiedTimeStamp(evictedEventNode.getCreationTimestamp());
ne.incerementNumberOfNodeVisits();
ne.setNumberOfElements(ne.getNumberOfElements() + numAddedElements);
@@ -293,41 +263,35 @@
/**
* Remove a node from cache.
* <p/>
- * This method will remove the node from the eviction queue as well as
- * evict the node from cache.
+ * This method will remove the node from the eviction queue as well as evict the node from cache.
* <p/>
- * If a node cannot be removed from cache, this method will remove it from the eviction queue
- * and place the element into the recycleQueue. Each node in the recycle queue will get retried until
- * proper cache eviction has taken place.
+ * If a node cannot be removed from cache, this method will remove it from the eviction queue and place the element
+ * into the recycleQueue. Each node in the recycle queue will get retried until proper cache eviction has taken
+ * place.
* <p/>
- * Because EvictionQueues are collections, when iterating them from an iterator, use iterator.remove()
- * to avoid ConcurrentModificationExceptions. Use the boolean parameter to indicate the calling context.
+ * Because EvictionQueues are collections, when iterating them from an iterator, use iterator.remove() to avoid
+ * ConcurrentModificationExceptions. Use the boolean parameter to indicate the calling context.
*
* @throws EvictionException
*/
- protected void processRemovedNodes(EvictionEvent<K> evictedEventNode) throws EvictionException
- {
+ protected void processRemovedNodes(EvictionEvent<K> evictedEventNode) throws EvictionException {
K key = evictedEventNode.getKey();
- if (trace)
- {
+ if (trace) {
log.trace("Removing key " + key + " from eviction queue and attempting eviction");
}
KeyEntry<K> ne = evictionQueue.getNodeEntry(key);
- if (ne != null)
- {
+ if (ne != null) {
evictionQueue.removeNodeEntry(ne);
- } else
- {
+ } else {
if (trace)
log.trace("processRemoveNodes(): Can't find node associated with key: " + key
+ "Could have been evicted earlier. Will just continue.");
return;
}
- if (trace)
- {
+ if (trace) {
log.trace(key + " removed from eviction queue");
}
}
@@ -335,21 +299,18 @@
/**
* Visit a node in cache.
* <p/>
- * This method will update the numVisits and modifiedTimestamp properties of the Node.
- * These properties are used as statistics to determine eviction (LRU, LFU, MRU, etc..)
+ * This method will update the numVisits and modifiedTimestamp properties of the Node. These properties are used as
+ * statistics to determine eviction (LRU, LFU, MRU, etc..)
* <p/>
- * *Note* that this method updates Node Entries by reference and does not put them back
- * into the queue. For some sorted collections, a remove, and a re-add is required to
- * maintain the sorted order of the elements.
+ * *Note* that this method updates Node Entries by reference and does not put them back into the queue. For some
+ * sorted collections, a remove, and a re-add is required to maintain the sorted order of the elements.
*
* @throws EvictionException
*/
- protected void processVisitedNodes(EvictionEvent<K> evictedEventNode) throws EvictionException
- {
+ protected void processVisitedNodes(EvictionEvent<K> evictedEventNode) throws EvictionException {
K key = evictedEventNode.getKey();
KeyEntry<K> ne = evictionQueue.getNodeEntry(key);
- if (ne == null)
- {
+ if (ne == null) {
if (trace) log.trace("Visiting node that was not added to eviction queues. Assuming that it has 1 element.");
this.processAddedNodes(evictedEventNode, 1);
return;
@@ -361,13 +322,11 @@
ne.setModifiedTimeStamp(evictedEventNode.getCreationTimestamp());
}
- protected void processRemovedElement(EvictionEvent<K> evictedEventNode) throws EvictionException
- {
+ protected void processRemovedElement(EvictionEvent<K> evictedEventNode) throws EvictionException {
K key = evictedEventNode.getKey();
KeyEntry<K> ne = evictionQueue.getNodeEntry(key);
- if (ne == null)
- {
+ if (ne == null) {
if (trace)
log.trace("Removing element from " + key + " but eviction queue does not contain this node. " +
"Ignoring removeElement event.");
@@ -380,12 +339,10 @@
ne.setModifiedTimeStamp(evictedEventNode.getCreationTimestamp());
}
- protected void processAddedElement(EvictionEvent<K> evictedEventNode) throws EvictionException
- {
+ protected void processAddedElement(EvictionEvent<K> evictedEventNode) throws EvictionException {
K key = evictedEventNode.getKey();
KeyEntry<K> ne = evictionQueue.getNodeEntry(key);
- if (ne == null)
- {
+ if (ne == null) {
if (trace) log.trace("Adding element " + key + " for a node that doesn't exist yet. Process as an add.");
this.processAddedNodes(evictedEventNode, 1);
return;
@@ -403,23 +360,18 @@
*
* @throws EvictionException
*/
- protected void emptyRecycleQueue() throws EvictionException
- {
- while (true)
- {
+ protected void emptyRecycleQueue() throws EvictionException {
+ while (true) {
K key;
- try
- {
+ try {
key = recycleQueue.poll(0, TimeUnit.SECONDS);
}
- catch (InterruptedException e)
- {
+ catch (InterruptedException e) {
log.debug(e, e);
break;
}
- if (key == null)
- {
+ if (key == null) {
if (trace) log.trace("Recycle queue is empty");
break;
}
@@ -427,14 +379,11 @@
if (trace) log.trace("emptying recycle bin. Evict key " + key);
// Still doesn't work
- if (!evictionAction.evict(key))
- {
- try
- {
+ if (!evictionAction.evict(key)) {
+ try {
recycleQueue.put(key);
}
- catch (InterruptedException e)
- {
+ catch (InterruptedException e) {
if (trace) log.trace(e, e);
}
break;
@@ -442,16 +391,12 @@
}
}
- protected void prune() throws EvictionException
- {
+ protected void prune() throws EvictionException {
KeyEntry<K> entry;
- while ((entry = evictionQueue.getFirstNodeEntry()) != null)
- {
- if (this.shouldEvictNode(entry))
- {
+ while ((entry = evictionQueue.getFirstNodeEntry()) != null) {
+ if (this.shouldEvictNode(entry)) {
this.evict(entry);
- } else
- {
+ } else {
break;
}
}
@@ -461,8 +406,7 @@
* Returns debug information.
*/
@Override
- public String toString()
- {
+ public String toString() {
return super.toString() + " recycle=" + recycleQueue.size() + " evict=" + evictionQueue.getNumberOfNodes();
}
}
Modified: core/branches/flat/src/main/java/org/horizon/eviction/algorithms/BaseSortedEvictionAlgorithm.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/eviction/algorithms/BaseSortedEvictionAlgorithm.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/eviction/algorithms/BaseSortedEvictionAlgorithm.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -25,7 +25,6 @@
import org.apache.commons.logging.LogFactory;
import org.horizon.eviction.EvictionEvent;
import org.horizon.eviction.EvictionException;
-import org.horizon.eviction.algorithms.SortedEvictionQueue;
import java.util.concurrent.BlockingQueue;
@@ -33,32 +32,27 @@
/**
* An abstract SortedEvictionAlgorithm.
* <p/>
- * This class supports early termination of the eviction queue processing. Because the eviction
- * queue is sorted by first to evict to last to evict, when iterating the eviction queue, the first time
- * a node is encountered that does not require eviction will terminate the loop early. This way we don't incur
- * the full breadth of the O(n) = n operation everytime we need to check for eviction (defined by eviction poll time
- * interval).
+ * This class supports early termination of the eviction queue processing. Because the eviction queue is sorted by first
+ * to evict to last to evict, when iterating the eviction queue, the first time a node is encountered that does not
+ * require eviction will terminate the loop early. This way we don't incur the full breadth of the O(n) = n operation
+ * everytime we need to check for eviction (defined by eviction poll time interval).
*
* @author Daniel Huang - dhuang at jboss.org - 10/2005
* @since 1.0
*/
-public abstract class BaseSortedEvictionAlgorithm<K> extends BaseEvictionAlgorithm<K>
-{
+public abstract class BaseSortedEvictionAlgorithm<K> extends BaseEvictionAlgorithm<K> {
private static final Log log = LogFactory.getLog(BaseSortedEvictionAlgorithm.class);
private static final boolean trace = log.isTraceEnabled();
@Override
- protected void processQueues(BlockingQueue<EvictionEvent<K>> queue) throws EvictionException
- {
+ protected void processQueues(BlockingQueue<EvictionEvent<K>> queue) throws EvictionException {
boolean evictionNodesModified = false;
EvictionEvent<K> node;
int count = 0;
- while ((node = getNextInQueue(queue)) != null)
- {
+ while ((node = getNextInQueue(queue)) != null) {
count++;
- switch (node.getEventType())
- {
+ switch (node.getEventType()) {
case ADD_NODE_EVENT:
this.processAddedNodes(node);
evictionNodesModified = true;
@@ -91,23 +85,19 @@
/**
* This method is called to resort the queue after add or visit events have occurred.
* <p/>
- * If the parameter is true, the queue needs to be resorted. If it is false, the queue does not
- * need resorting.
+ * If the parameter is true, the queue needs to be resorted. If it is false, the queue does not need resorting.
*
* @param evictionQueueModified True if the queue was added to or visisted during event processing.
*/
- protected void resortEvictionQueue(boolean evictionQueueModified)
- {
- if (!evictionQueueModified)
- {
+ protected void resortEvictionQueue(boolean evictionQueueModified) {
+ if (!evictionQueueModified) {
if (trace) log.debug("Eviction queue not modified. Resort unnecessary.");
return;
}
long begin = System.currentTimeMillis();
((SortedEvictionQueue) evictionQueue).resortEvictionQueue();
- if (trace)
- {
+ if (trace) {
long end = System.currentTimeMillis();
long diff = end - begin;
log.trace("Took " + diff + "ms to sort queue with " + getEvictionQueue().getNumberOfNodes() + " elements");
Modified: core/branches/flat/src/main/java/org/horizon/eviction/algorithms/ElementSizeAlgorithm.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/eviction/algorithms/ElementSizeAlgorithm.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/eviction/algorithms/ElementSizeAlgorithm.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -22,24 +22,24 @@
package org.horizon.eviction.algorithms;
import org.horizon.config.EvictionAlgorithmConfig;
-import org.horizon.eviction.*;
+import org.horizon.eviction.ElementSizeAlgorithmConfig;
+import org.horizon.eviction.ElementSizeQueue;
+import org.horizon.eviction.EvictionException;
+import org.horizon.eviction.EvictionQueue;
+import org.horizon.eviction.KeyEntry;
/**
* @author Daniel Huang
- *
* @since 1.0
*/
-public class ElementSizeAlgorithm<K> extends BaseSortedEvictionAlgorithm<K>
-{
+public class ElementSizeAlgorithm<K> extends BaseSortedEvictionAlgorithm<K> {
@Override
- protected EvictionQueue<K> setupEvictionQueue() throws EvictionException
- {
+ protected EvictionQueue<K> setupEvictionQueue() throws EvictionException {
return new ElementSizeQueue<K>();
}
@Override
- protected boolean shouldEvictNode(KeyEntry<K> ne)
- {
+ protected boolean shouldEvictNode(KeyEntry<K> ne) {
// check the minimum time to live and see if we should not evict the node. This check will
// ensure that, if configured, nodes are kept alive for at least a minimum period of time.
if (ne.isYoungerThanMinimumTimeToLive(evictionAlgorithmConfig.getMinTimeToLive())) return false;
@@ -49,16 +49,14 @@
}
@Override
- protected void prune() throws EvictionException
- {
+ protected void prune() throws EvictionException {
super.prune();
// clean up the Queue's eviction removals
((ElementSizeQueue) this.evictionQueue).prune();
}
- public Class<? extends EvictionAlgorithmConfig> getConfigurationClass()
- {
+ public Class<? extends EvictionAlgorithmConfig> getConfigurationClass() {
return ElementSizeAlgorithmConfig.class;
}
}
Modified: core/branches/flat/src/main/java/org/horizon/eviction/algorithms/ExpirationAlgorithm.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/eviction/algorithms/ExpirationAlgorithm.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/eviction/algorithms/ExpirationAlgorithm.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -24,8 +24,12 @@
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.horizon.config.EvictionAlgorithmConfig;
-import org.horizon.eviction.*;
+import org.horizon.eviction.EvictionEvent;
import org.horizon.eviction.EvictionEvent.Type;
+import org.horizon.eviction.EvictionException;
+import org.horizon.eviction.EvictionQueue;
+import org.horizon.eviction.ExpirationAlgorithmConfig;
+import org.horizon.eviction.KeyEntry;
import java.util.Iterator;
import java.util.SortedSet;
@@ -33,26 +37,21 @@
import java.util.concurrent.BlockingQueue;
/**
- * Eviction algorithm that uses a key in the Node data that indicates the time
- * the node should be evicted. The key must be a java.lang.Long object, with
- * the time to expire as milliseconds past midnight January 1st, 1970 UTC (the
- * same relative time as provided by {@link
- * java.lang.System#currentTimeMillis()}).
+ * Eviction algorithm that uses a key in the Node data that indicates the time the node should be evicted. The key must
+ * be a java.lang.Long object, with the time to expire as milliseconds past midnight January 1st, 1970 UTC (the same
+ * relative time as provided by {@link java.lang.System#currentTimeMillis()}).
* <p/>
- * This algorithm also obeys the configuration key {@link
- * org.horizon.eviction.ExpirationAlgorithmConfig#getMaxNodes()}, and will evict the soonest to
- * expire entires first to reduce the region size. If there are not enough
- * nodes with expiration keys set, a warning is logged.
+ * This algorithm also obeys the configuration key {@link org.horizon.eviction.ExpirationAlgorithmConfig#getMaxNodes()},
+ * and will evict the soonest to expire entires first to reduce the region size. If there are not enough nodes with
+ * expiration keys set, a warning is logged.
* <p/>
- * If a node in the eviction region does not have an expiration value, then
- * {@link org.horizon.eviction.ExpirationAlgorithmConfig#getTimeToLive()} (if set) will be used.
- * The expiration is updated when a node is added or updated.
+ * If a node in the eviction region does not have an expiration value, then {@link
+ * org.horizon.eviction.ExpirationAlgorithmConfig#getTimeToLive()} (if set) will be used. The expiration is updated when
+ * a node is added or updated.
* <p/>
- * If there is no time-to-live set, and a node in the eviction region does not
- * have an expiration value, then that node will never be evicted. As
- * forgetting to indicate an expiration value is likely a mistake, a warning
- * message is logged by this class. This warning, however, can be disabled
- * through {@link org.horizon.eviction.ExpirationAlgorithmConfig#setWarnNoExpirationKey(boolean)}.
+ * If there is no time-to-live set, and a node in the eviction region does not have an expiration value, then that node
+ * will never be evicted. As forgetting to indicate an expiration value is likely a mistake, a warning message is
+ * logged by this class. This warning, however, can be disabled through {@link org.horizon.eviction.ExpirationAlgorithmConfig#setWarnNoExpirationKey(boolean)}.
* <p/>
* A node's expiration time can be changed by setting a new value in the node.
* <p/>
@@ -69,11 +68,11 @@
* assertTrue(cache.get(fqn1) == null);
* <p/>
* </pre>
- * @since 1.0
+ *
* @author (various)
+ * @since 1.0
*/
-public class ExpirationAlgorithm<K> extends BaseEvictionAlgorithm<K>
-{
+public class ExpirationAlgorithm<K> extends BaseEvictionAlgorithm<K> {
private static final Log log = LogFactory.getLog(ExpirationAlgorithm.class);
private static final boolean trace = log.isTraceEnabled();
@@ -85,54 +84,44 @@
/**
* Constructs a new algorithm with a policy.
*/
- public ExpirationAlgorithm()
- {
+ public ExpirationAlgorithm() {
this.set = new TreeSet<ExpirationEntry<K>>();
}
- private void addEvictionEntry(EvictionEvent<K> node)
- {
+ private void addEvictionEntry(EvictionEvent<K> node) {
K key = node.getKey();
addEvictionEntry(key);
}
- private void addEvictionEntry(K key)
- {
+ private void addEvictionEntry(K key) {
Long l = getExpiration();
- if (l == null)
- {
+ if (l == null) {
if (config.isWarnNoExpirationKey() && log.isWarnEnabled())
log.warn("No expiration key '" + config.getExpirationKeyName() + "' for Node: " + key);
else if (log.isDebugEnabled())
log.debug("No expiration key for Node: " + key);
- } else
- {
+ } else {
setExpiration(key, l);
}
}
- private void setExpiration(K key, Long l)
- {
+ private void setExpiration(K key, Long l) {
ExpirationEntry<K> ee = new ExpirationEntry<K>(key, l);
if (trace) log.trace("adding eviction entry: " + ee);
set.add(ee);
}
- private Long getExpiration()
- {
+ private Long getExpiration() {
return (Long) cache.getDirect(config.getExpirationKeyName());
}
@Override
- protected void processQueues(BlockingQueue<EvictionEvent<K>> queue) throws EvictionException
- {
+ protected void processQueues(BlockingQueue<EvictionEvent<K>> queue) throws EvictionException {
EvictionEvent<K> node;
int count = 0;
- while ((node = getNextInQueue(queue)) != null)
- {
+ while ((node = getNextInQueue(queue)) != null) {
count++;
- switch (node.getEventType())
- {
+ switch (node.getEventType()) {
case ADD_NODE_EVENT:
case ADD_ELEMENT_EVENT:
addEvictionEntry(node);
@@ -157,35 +146,29 @@
if (trace) log.trace("processed " + count + " node events in cache: " + cache.getName());
}
- private void markInUse(EvictionEvent<K> node)
- {
+ private void markInUse(EvictionEvent<K> node) {
long expiration = node.getInUseTimeout() + System.currentTimeMillis();
setExpiration(node.getKey(), expiration);
}
@Override
- protected void prune() throws EvictionException
- {
+ protected void prune() throws EvictionException {
if (set.isEmpty())
return;
long now = System.currentTimeMillis();
int max = config.getMaxNodes();
- for (Iterator<ExpirationEntry<K>> i = set.iterator(); i.hasNext();)
- {
+ for (Iterator<ExpirationEntry<K>> i = set.iterator(); i.hasNext();) {
ExpirationEntry<K> ee = i.next();
Long ce = getExpiration();
- if (ce == null || ce > ee.getExpiration())
- {
+ if (ce == null || ce > ee.getExpiration()) {
// Expiration now older
i.remove();
continue;
}
- if (ee.getExpiration() < now || (max != 0 && set.size() > max))
- {
+ if (ee.getExpiration() < now || (max != 0 && set.size() > max)) {
i.remove();
evictionAction.evict(ee.getKey());
- } else
- {
+ } else {
break;
}
}
@@ -196,56 +179,46 @@
}
@Override
- public void resetEvictionQueue()
- {
- for (ExpirationEntry<K> ee : set)
- {
+ public void resetEvictionQueue() {
+ for (ExpirationEntry<K> ee : set) {
addEvictionEntry(ee.getKey());
}
}
@Override
@SuppressWarnings(value = "unchecked")
- protected EvictionQueue<K> setupEvictionQueue() throws EvictionException
- {
+ protected EvictionQueue<K> setupEvictionQueue() throws EvictionException {
this.config = (ExpirationAlgorithmConfig) evictionAlgorithmConfig;
return new DummyEvictionQueue<K>();
}
@Override
- protected boolean shouldEvictNode(KeyEntry<K> ne)
- {
+ protected boolean shouldEvictNode(KeyEntry<K> ne) {
throw new UnsupportedOperationException();
}
@Override
- public boolean canIgnoreEvent(Type eventType)
- {
+ public boolean canIgnoreEvent(Type eventType) {
return (eventType == EvictionEvent.Type.VISIT_NODE_EVENT);
}
- public Class<? extends EvictionAlgorithmConfig> getConfigurationClass()
- {
+ public Class<? extends EvictionAlgorithmConfig> getConfigurationClass() {
return ExpirationAlgorithmConfig.class;
}
/**
- * Ordered list of FQN, with the expiration taken from the Map at the time
- * of processing.
+ * Ordered list of FQN, with the expiration taken from the Map at the time of processing.
*/
- static class ExpirationEntry<K> implements Comparable<ExpirationEntry>
- {
+ static class ExpirationEntry<K> implements Comparable<ExpirationEntry> {
private long expiration;
private K key;
- public ExpirationEntry(K key)
- {
+ public ExpirationEntry(K key) {
this.key = key;
}
- public ExpirationEntry(K key, long expiration)
- {
+ public ExpirationEntry(K key, long expiration) {
this.key = key;
this.expiration = expiration;
}
@@ -253,8 +226,7 @@
/**
* Compares expiration, then FQN order.
*/
- public int compareTo(ExpirationEntry ee)
- {
+ public int compareTo(ExpirationEntry ee) {
long n = expiration - ee.expiration;
if (n < 0)
return -1;
@@ -266,22 +238,19 @@
/**
* @return the expiration
*/
- public long getExpiration()
- {
+ public long getExpiration() {
return expiration;
}
/**
* @return the fqn
*/
- public K getKey()
- {
+ public K getKey() {
return key;
}
@Override
- public boolean equals(Object o)
- {
+ public boolean equals(Object o) {
if (!(o instanceof ExpirationEntry))
return false;
ExpirationEntry ee = (ExpirationEntry) o;
@@ -289,14 +258,12 @@
}
@Override
- public int hashCode()
- {
+ public int hashCode() {
return (int) expiration ^ key.hashCode();
}
@Override
- public String toString()
- {
+ public String toString() {
long now = System.currentTimeMillis();
long ttl = expiration - now;
String sttl;
@@ -310,55 +277,44 @@
}
}
- class DummyEvictionQueue<K> implements EvictionQueue<K>
- {
+ class DummyEvictionQueue<K> implements EvictionQueue<K> {
- public void addNodeEntry(KeyEntry entry)
- {
+ public void addNodeEntry(KeyEntry entry) {
throw new UnsupportedOperationException();
}
- public void clear()
- {
+ public void clear() {
set.clear();
}
- public boolean containsNodeEntry(KeyEntry entry)
- {
+ public boolean containsNodeEntry(KeyEntry entry) {
return false;
}
- public KeyEntry<K> getFirstNodeEntry()
- {
+ public KeyEntry<K> getFirstNodeEntry() {
return null;
}
- public KeyEntry<K> getNodeEntry(K k)
- {
+ public KeyEntry<K> getNodeEntry(K k) {
return null;
}
- public int getNumberOfElements()
- {
+ public int getNumberOfElements() {
return set.size();
}
- public int getNumberOfNodes()
- {
+ public int getNumberOfNodes() {
return set.size();
}
- public Iterator<KeyEntry<K>> iterator()
- {
+ public Iterator<KeyEntry<K>> iterator() {
return null;
}
- public void modifyElementCount(int difference)
- {
+ public void modifyElementCount(int difference) {
}
- public void removeNodeEntry(KeyEntry entry)
- {
+ public void removeNodeEntry(KeyEntry entry) {
throw new UnsupportedOperationException();
}
}
Modified: core/branches/flat/src/main/java/org/horizon/eviction/algorithms/NULL/NullEvictionAlgorithm.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/eviction/algorithms/NULL/NullEvictionAlgorithm.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/eviction/algorithms/NULL/NullEvictionAlgorithm.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -37,8 +37,7 @@
* @author Brian Stansberry
* @since 1.0
*/
-public class NullEvictionAlgorithm implements EvictionAlgorithm
-{
+public class NullEvictionAlgorithm implements EvictionAlgorithm {
/**
* Singleton instance of this class.
*/
@@ -47,55 +46,45 @@
/**
* Constructs a new NullEvictionAlgorithm.
*/
- private NullEvictionAlgorithm()
- {
+ private NullEvictionAlgorithm() {
}
- public static NullEvictionAlgorithm getInstance()
- {
+ public static NullEvictionAlgorithm getInstance() {
return INSTANCE;
}
/**
* Returns {@link NullEvictionQueue#INSTANCE}.
*/
- public EvictionQueue getEvictionQueue()
- {
+ public EvictionQueue getEvictionQueue() {
return NullEvictionQueue.INSTANCE;
}
- public void setEvictionAction(EvictionAction evictionAction)
- {
+ public void setEvictionAction(EvictionAction evictionAction) {
// no-op
}
- public void assignToCache(CacheSPI cache, EvictionAlgorithmConfig evictionAlgorithmConfig)
- {
+ public void assignToCache(CacheSPI cache, EvictionAlgorithmConfig evictionAlgorithmConfig) {
// no-op
}
- public void process(BlockingQueue queue) throws EvictionException
- {
+ public void process(BlockingQueue queue) throws EvictionException {
// no-op
}
- public void resetEvictionQueue()
- {
+ public void resetEvictionQueue() {
// no-op
}
- public boolean canIgnoreEvent(Type eventType)
- {
+ public boolean canIgnoreEvent(Type eventType) {
return true; // always ignore everything!
}
- public void initialize()
- {
+ public void initialize() {
// no-op
}
- public Class<? extends EvictionAlgorithmConfig> getConfigurationClass()
- {
+ public Class<? extends EvictionAlgorithmConfig> getConfigurationClass() {
return NullEvictionAlgorithmConfig.class;
}
}
Modified: core/branches/flat/src/main/java/org/horizon/eviction/algorithms/NULL/NullEvictionAlgorithmConfig.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/eviction/algorithms/NULL/NullEvictionAlgorithmConfig.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/eviction/algorithms/NULL/NullEvictionAlgorithmConfig.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -31,38 +31,32 @@
* @author Manik Surtani
* @since 1.0
*/
-public class NullEvictionAlgorithmConfig extends ConfigurationComponent implements EvictionAlgorithmConfig
-{
+public class NullEvictionAlgorithmConfig extends ConfigurationComponent implements EvictionAlgorithmConfig {
private static final long serialVersionUID = -6591180473728241737L;
/**
* No-op
*/
- public void reset()
- {
+ public void reset() {
// no-op
}
- public String getEvictionAlgorithmClassName()
- {
+ public String getEvictionAlgorithmClassName() {
return NullEvictionAlgorithm.class.getName();
}
/**
* No-op
*/
- public void validate() throws ConfigurationException
- {
+ public void validate() throws ConfigurationException {
// no-op
}
- public NullEvictionAlgorithmConfig clone() throws CloneNotSupportedException
- {
+ public NullEvictionAlgorithmConfig clone() throws CloneNotSupportedException {
return (NullEvictionAlgorithmConfig) super.clone();
}
- public long getMinTimeToLive()
- {
+ public long getMinTimeToLive() {
throw new UnsupportedOperationException("Not implemented");//todo please implement!
}
}
\ No newline at end of file
Modified: core/branches/flat/src/main/java/org/horizon/eviction/algorithms/NULL/NullEvictionQueue.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/eviction/algorithms/NULL/NullEvictionQueue.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/eviction/algorithms/NULL/NullEvictionQueue.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -33,8 +33,7 @@
* @author Brian Stansberry
* @since 1.0
*/
-public class NullEvictionQueue implements EvictionQueue
-{
+public class NullEvictionQueue implements EvictionQueue {
/**
* Singleton instance of this class.
*/
@@ -43,80 +42,69 @@
/**
* Constructs a new NullEvictionQueue.
*/
- private NullEvictionQueue()
- {
+ private NullEvictionQueue() {
}
/**
* No-op
*/
- public void addNodeEntry(KeyEntry entry)
- {
+ public void addNodeEntry(KeyEntry entry) {
// no-op
}
/**
* No-op
*/
- public void clear()
- {
+ public void clear() {
// no-op
}
/**
* Returns <code>false</code>
*/
- public boolean containsNodeEntry(KeyEntry entry)
- {
+ public boolean containsNodeEntry(KeyEntry entry) {
return false;
}
/**
* Returns <code>null</code>
*/
- public KeyEntry getFirstNodeEntry()
- {
+ public KeyEntry getFirstNodeEntry() {
return null;
}
/**
* Returns <code>null</code>
*/
- public KeyEntry getNodeEntry(Object fqn)
- {
+ public KeyEntry getNodeEntry(Object fqn) {
return null;
}
/**
* Returns <code>null</code>
*/
- public KeyEntry getNodeEntry(String fqn)
- {
+ public KeyEntry getNodeEntry(String fqn) {
return null;
}
/**
* Returns <code>0</code>
*/
- public int getNumberOfElements()
- {
+ public int getNumberOfElements() {
return 0;
}
/**
* Returns <code>0</code>
*/
- public int getNumberOfNodes()
- {
+ public int getNumberOfNodes() {
return 0;
}
/**
- * Returns an <code>Iterator</code> whose
- * <code>hasNext()</code> returns <code>false</code>.
+ * Returns an <code>Iterator</code> whose <code>hasNext()</code> returns <code>false</code>.
*/
- public Iterator iterator()
- {
+ public Iterator iterator() {
return NullQueueIterator.INSTANCE;
}
@@ -124,39 +112,32 @@
/**
* No-op
*/
- public void modifyElementCount(int difference)
- {
+ public void modifyElementCount(int difference) {
// no-op
}
/**
* No-op
*/
- public void removeNodeEntry(KeyEntry entry)
- {
+ public void removeNodeEntry(KeyEntry entry) {
// no-op
}
- static class NullQueueIterator implements Iterator<KeyEntry>
- {
+ static class NullQueueIterator implements Iterator<KeyEntry> {
private static final NullQueueIterator INSTANCE = new NullQueueIterator();
- private NullQueueIterator()
- {
+ private NullQueueIterator() {
}
- public boolean hasNext()
- {
+ public boolean hasNext() {
return false;
}
- public KeyEntry next()
- {
+ public KeyEntry next() {
throw new NoSuchElementException("No more elements");
}
- public void remove()
- {
+ public void remove() {
throw new IllegalStateException("Must call next() before remove()");
}
}
Modified: core/branches/flat/src/main/java/org/horizon/eviction/algorithms/SortedEvictionQueue.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/eviction/algorithms/SortedEvictionQueue.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/eviction/algorithms/SortedEvictionQueue.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -27,11 +27,9 @@
* Sorted Eviction Queue implementation.
*
* @author Daniel Huang (dhuang at jboss.org)
- *
* @since 1.0
*/
-public interface SortedEvictionQueue<K> extends EvictionQueue<K>
-{
+public interface SortedEvictionQueue<K> extends EvictionQueue<K> {
/**
* Provide contract to resort a sorted queue.
*/
Modified: core/branches/flat/src/main/java/org/horizon/eviction/algorithms/fifo/FIFOAlgorithm.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/eviction/algorithms/fifo/FIFOAlgorithm.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/eviction/algorithms/fifo/FIFOAlgorithm.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -24,27 +24,24 @@
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.horizon.config.EvictionAlgorithmConfig;
-import org.horizon.eviction.algorithms.BaseEvictionAlgorithm;
-import org.horizon.eviction.EvictionQueue;
import org.horizon.eviction.EvictionException;
+import org.horizon.eviction.EvictionQueue;
import org.horizon.eviction.KeyEntry;
+import org.horizon.eviction.algorithms.BaseEvictionAlgorithm;
/**
* First-in-first-out algorithm used to evict nodes.
*
* @author Daniel Huang - dhuang at jboss.org
* @author Morten Kvistgaard
- *
* @since 1.0
*/
-public class FIFOAlgorithm<K> extends BaseEvictionAlgorithm<K>
-{
+public class FIFOAlgorithm<K> extends BaseEvictionAlgorithm<K> {
private static final Log log = LogFactory.getLog(FIFOAlgorithm.class);
private static final boolean trace = log.isTraceEnabled();
-
+
@Override
- protected EvictionQueue<K> setupEvictionQueue() throws EvictionException
- {
+ protected EvictionQueue<K> setupEvictionQueue() throws EvictionException {
return new FIFOQueue<K>();
}
@@ -52,8 +49,7 @@
* For FIFO, a node should be evicted if the queue size is >= to the configured maxNodes size.
*/
@Override
- protected boolean shouldEvictNode(KeyEntry ne)
- {
+ protected boolean shouldEvictNode(KeyEntry ne) {
// check the minimum time to live and see if we should not evict the node. This check will
// ensure that, if configured, nodes are kept alive for at least a minimum period of time.
if (ne.isYoungerThanMinimumTimeToLive(evictionAlgorithmConfig.getMinTimeToLive())) return false;
@@ -65,8 +61,7 @@
return config.getMaxNodes() != 0 && size > config.getMaxNodes();
}
- public Class<? extends EvictionAlgorithmConfig> getConfigurationClass()
- {
+ public Class<? extends EvictionAlgorithmConfig> getConfigurationClass() {
return FIFOAlgorithmConfig.class;
}
}
Modified: core/branches/flat/src/main/java/org/horizon/eviction/algorithms/fifo/FIFOAlgorithmConfig.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/eviction/algorithms/fifo/FIFOAlgorithmConfig.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/eviction/algorithms/fifo/FIFOAlgorithmConfig.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -32,67 +32,57 @@
* @author Manik Surtani
* @since 1.0
*/
-public class FIFOAlgorithmConfig extends EvictionAlgorithmConfigBase
-{
+public class FIFOAlgorithmConfig extends EvictionAlgorithmConfigBase {
/**
* The serialVersionUID
*/
private static final long serialVersionUID = -7229715009546277313L;
- public FIFOAlgorithmConfig()
- {
+ public FIFOAlgorithmConfig() {
evictionAlgorithmClassName = FIFOAlgorithm.class.getName();
// We require that maxNodes is set
setMaxNodes(-1);
}
- public FIFOAlgorithmConfig(int maxNodes)
- {
+ public FIFOAlgorithmConfig(int maxNodes) {
evictionAlgorithmClassName = FIFOAlgorithm.class.getName();
// We require that maxNodes is set
setMaxNodes(maxNodes);
}
/**
- * Requires a positive maxNodes value or ConfigurationException
- * is thrown.
+ * Requires a positive maxNodes value or ConfigurationException is thrown.
*/
@Override
- public void validate() throws ConfigurationException
- {
+ public void validate() throws ConfigurationException {
super.validate();
- if (getMaxNodes() < 0)
- {
+ if (getMaxNodes() < 0) {
throw new ConfigurationException("maxNodes must be must be " +
"configured to a value greater than or equal to 0");
}
}
@Override
- public String toString()
- {
+ public String toString() {
StringBuilder ret = new StringBuilder();
ret.append("FIFOAlgorithmConfig: maxNodes = ").append(getMaxNodes());
return ret.toString();
}
@Override
- public boolean equals(Object obj)
- {
+ public boolean equals(Object obj) {
return (obj instanceof FIFOAlgorithmConfig && super.equals(obj));
}
@Override
- public void reset()
- {
+ public void reset() {
super.reset();
setMaxNodes(-1);
evictionAlgorithmClassName = FIFOAlgorithm.class.getName();
}
@Override
- public FIFOAlgorithmConfig clone() throws CloneNotSupportedException
- {
+ public FIFOAlgorithmConfig clone() throws CloneNotSupportedException {
return (FIFOAlgorithmConfig) super.clone();
}
}
\ No newline at end of file
Modified: core/branches/flat/src/main/java/org/horizon/eviction/algorithms/fifo/FIFOQueue.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/eviction/algorithms/fifo/FIFOQueue.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/eviction/algorithms/fifo/FIFOQueue.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -32,79 +32,64 @@
* FIFO Eviction Queue implementation for FIFO Policy.
*
* @author Daniel Huang (dhuang at jboss.org)
- *
* @since 1.0
*/
-public class FIFOQueue<K> implements EvictionQueue<K>
-{
+public class FIFOQueue<K> implements EvictionQueue<K> {
private Map<K, KeyEntry<K>> keyMap;
private int numElements = 0;
- protected FIFOQueue()
- {
+ protected FIFOQueue() {
keyMap = new LinkedHashMap<K, KeyEntry<K>>();
// We use a LinkedHashMap here because we want to maintain FIFO ordering and still get the benefits of
// O(n) = 1 for add/remove/search.
}
- public KeyEntry<K> getFirstNodeEntry()
- {
- if (keyMap.size() > 0)
- {
+ public KeyEntry<K> getFirstNodeEntry() {
+ if (keyMap.size() > 0) {
return keyMap.values().iterator().next();
}
return null;
}
- public KeyEntry<K> getNodeEntry(K key)
- {
+ public KeyEntry<K> getNodeEntry(K key) {
return keyMap.get(key);
}
- public boolean containsNodeEntry(KeyEntry<K> entry)
- {
+ public boolean containsNodeEntry(KeyEntry<K> entry) {
K key = entry.getKey();
return this.getNodeEntry(key) != null;
}
- public void removeNodeEntry(KeyEntry<K> entry)
- {
+ public void removeNodeEntry(KeyEntry<K> entry) {
KeyEntry<K> e = keyMap.remove(entry.getKey());
this.numElements -= e.getNumberOfElements();
}
- public void addNodeEntry(KeyEntry<K> entry)
- {
- if (!this.containsNodeEntry(entry))
- {
+ public void addNodeEntry(KeyEntry<K> entry) {
+ if (!this.containsNodeEntry(entry)) {
keyMap.put(entry.getKey(), entry);
this.numElements += entry.getNumberOfElements();
}
}
- public int getNumberOfNodes()
- {
+ public int getNumberOfNodes() {
return keyMap.size();
}
- public int getNumberOfElements()
- {
+ public int getNumberOfElements() {
return this.numElements;
}
- public void modifyElementCount(int difference)
- {
+ public void modifyElementCount(int difference) {
this.numElements += difference;
}
- public void clear()
- {
+ public void clear() {
keyMap.clear();
this.numElements = 0;
}
- public Iterator<KeyEntry<K>> iterator()
- {
+ public Iterator<KeyEntry<K>> iterator() {
return keyMap.values().iterator();
}
}
Modified: core/branches/flat/src/main/java/org/horizon/eviction/algorithms/lfu/LFUAlgorithm.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/eviction/algorithms/lfu/LFUAlgorithm.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/eviction/algorithms/lfu/LFUAlgorithm.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -24,44 +24,35 @@
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.horizon.config.EvictionAlgorithmConfig;
-import org.horizon.eviction.algorithms.BaseSortedEvictionAlgorithm;
+import org.horizon.eviction.EvictionException;
import org.horizon.eviction.EvictionQueue;
import org.horizon.eviction.KeyEntry;
-import org.horizon.eviction.EvictionException;
+import org.horizon.eviction.algorithms.BaseSortedEvictionAlgorithm;
/**
- * Least Frequently Used algorithm for cache eviction.
- * Note that this algorithm is not thread-safe.
+ * Least Frequently Used algorithm for cache eviction. Note that this algorithm is not thread-safe.
* <p/>
- * This algorithm relies on maxNodes and minNodes to operate correctly.
- * Eviction takes place using Least Frequently Used algorithm. A node A
- * that is used less than a node B is evicted sooner.
+ * This algorithm relies on maxNodes and minNodes to operate correctly. Eviction takes place using Least Frequently Used
+ * algorithm. A node A that is used less than a node B is evicted sooner.
* <p/>
- * The minNodes property defines a threshold for eviction. If minNodes = 100,
- * the LFUAlgorithm will not evict the cache to anything less than 100 elements
- * still left in cache. The maxNodes property defines the maximum number of nodes
- * the cache will accept before eviction. maxNodes = 0 means that this region is
- * unbounded. minNodes = 0 means that the eviction queue will attempt to bring
- * the cache of this region to 0 elements (evict all elements) whenever it is run.
+ * The minNodes property defines a threshold for eviction. If minNodes = 100, the LFUAlgorithm will not evict the cache
+ * to anything less than 100 elements still left in cache. The maxNodes property defines the maximum number of nodes the
+ * cache will accept before eviction. maxNodes = 0 means that this region is unbounded. minNodes = 0 means that the
+ * eviction queue will attempt to bring the cache of this region to 0 elements (evict all elements) whenever it is run.
* <p/>
- * This algorithm uses a sorted eviction queue. The eviction queue is sorted in
- * ascending order based on the number of times a node is visited. The more frequently
- * a node is visited, the less likely it will be evicted.
+ * This algorithm uses a sorted eviction queue. The eviction queue is sorted in ascending order based on the number of
+ * times a node is visited. The more frequently a node is visited, the less likely it will be evicted.
*
* @author Daniel Huang - dhuang at jboss.org 10/2005
- *
* @since 1.0
*/
-public class LFUAlgorithm extends BaseSortedEvictionAlgorithm
-{
+public class LFUAlgorithm extends BaseSortedEvictionAlgorithm {
private static final Log log = LogFactory.getLog(LFUAlgorithm.class);
private static final boolean trace = log.isTraceEnabled();
@Override
- protected boolean shouldEvictNode( KeyEntry ne)
- {
- if (trace)
- {
+ protected boolean shouldEvictNode(KeyEntry ne) {
+ if (trace) {
log.trace("Deciding whether node in queue " + ne.getKey() + " requires eviction.");
}
@@ -71,12 +62,9 @@
LFUAlgorithmConfig config = (LFUAlgorithmConfig) evictionAlgorithmConfig;
int size = this.getEvictionQueue().getNumberOfNodes();
- if (config.getMaxNodes() > -1 && size > config.getMaxNodes())
- {
+ if (config.getMaxNodes() > -1 && size > config.getMaxNodes()) {
return true;
- }
- else if (size > config.getMinNodes())
- {
+ } else if (size > config.getMinNodes()) {
return true;
}
@@ -91,22 +79,19 @@
*
*/
@Override
- protected EvictionQueue setupEvictionQueue() throws EvictionException
- {
+ protected EvictionQueue setupEvictionQueue() throws EvictionException {
return new LFUQueue();
}
@Override
- protected void prune() throws EvictionException
- {
+ protected void prune() throws EvictionException {
super.prune();
// clean up the Queue's eviction removals
((LFUQueue) this.evictionQueue).prune();
}
- public Class<? extends EvictionAlgorithmConfig> getConfigurationClass()
- {
+ public Class<? extends EvictionAlgorithmConfig> getConfigurationClass() {
return LFUAlgorithmConfig.class;
}
}
Modified: core/branches/flat/src/main/java/org/horizon/eviction/algorithms/lfu/LFUAlgorithmConfig.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/eviction/algorithms/lfu/LFUAlgorithmConfig.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/eviction/algorithms/lfu/LFUAlgorithmConfig.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -30,8 +30,7 @@
* @author Manik Surtani
* @since 1.0
*/
-public class LFUAlgorithmConfig extends EvictionAlgorithmConfigBase
-{
+public class LFUAlgorithmConfig extends EvictionAlgorithmConfigBase {
/**
* The serialVersionUID
*/
@@ -40,64 +39,54 @@
@Dynamic
private int minNodes;
- public LFUAlgorithmConfig()
- {
+ public LFUAlgorithmConfig() {
evictionAlgorithmClassName = LFUAlgorithm.class.getName();
}
- public LFUAlgorithmConfig(int maxNodes, int minNodes)
- {
+ public LFUAlgorithmConfig(int maxNodes, int minNodes) {
this();
setMaxNodes(maxNodes);
setMinNodes(minNodes);
}
- public int getMinNodes()
- {
+ public int getMinNodes() {
return minNodes;
}
- public void setMinNodes(int minNodes)
- {
+ public void setMinNodes(int minNodes) {
testImmutability("minNodes");
this.minNodes = minNodes;
}
@Override
- public String toString()
- {
+ public String toString() {
StringBuilder ret = new StringBuilder();
ret.append("LFUAlgorithmConfig: maxNodes = ").append(getMaxNodes()).append(" minNodes = ").append(getMinNodes());
return ret.toString();
}
@Override
- public boolean equals(Object obj)
- {
- if (obj instanceof LFUAlgorithmConfig && super.equals(obj))
- {
+ public boolean equals(Object obj) {
+ if (obj instanceof LFUAlgorithmConfig && super.equals(obj)) {
return (this.minNodes == ((LFUAlgorithmConfig) obj).minNodes);
}
return false;
}
@Override
- public int hashCode()
- {
+ public int hashCode() {
int result = super.hashCode();
result = 31 * result + minNodes;
return result;
}
@Override
- public LFUAlgorithmConfig clone() throws CloneNotSupportedException
- {
+ public LFUAlgorithmConfig clone() throws CloneNotSupportedException {
return (LFUAlgorithmConfig) super.clone();
}
@Override
- public void reset()
- {
+ public void reset() {
super.reset();
minNodes = -1;
evictionAlgorithmClassName = LFUAlgorithm.class.getName();
Modified: core/branches/flat/src/main/java/org/horizon/eviction/algorithms/lfu/LFUQueue.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/eviction/algorithms/lfu/LFUQueue.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/eviction/algorithms/lfu/LFUQueue.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -32,11 +32,9 @@
* The queue is sorted in least frequently used order.
*
* @author Daniel Huang (dhuang at jboss.org)
- *
* @since 1.0
*/
-public class LFUQueue<K> implements SortedEvictionQueue<K>
-{
+public class LFUQueue<K> implements SortedEvictionQueue<K> {
private Map<K, KeyEntry<K>> keyMap;
private LinkedList<KeyEntry<K>> evictionList;
private Set<KeyEntry<K>> removalQueue;
@@ -44,8 +42,7 @@
private int numElements = 0;
- protected LFUQueue()
- {
+ protected LFUQueue() {
keyMap = new HashMap<K, KeyEntry<K>>();
comparator = new LFUComparator<K>();
evictionList = new LinkedList<KeyEntry<K>>();
@@ -57,48 +54,37 @@
* <p/>
* This method will return the least frequently used entry in the queue.
*/
- public KeyEntry<K> getFirstNodeEntry()
- {
- try
- {
+ public KeyEntry<K> getFirstNodeEntry() {
+ try {
KeyEntry<K> ne;
- while ((ne = evictionList.getFirst()) != null)
- {
- if (removalQueue.contains(ne))
- {
+ while ((ne = evictionList.getFirst()) != null) {
+ if (removalQueue.contains(ne)) {
evictionList.removeFirst();
removalQueue.remove(ne);
- }
- else
- {
+ } else {
break;
}
}
return ne;
}
- catch (NoSuchElementException e)
- {
+ catch (NoSuchElementException e) {
//
}
return null;
}
- public KeyEntry<K> getNodeEntry(K key)
- {
+ public KeyEntry<K> getNodeEntry(K key) {
return keyMap.get(key);
}
- public boolean containsNodeEntry(KeyEntry<K> entry)
- {
+ public boolean containsNodeEntry(KeyEntry<K> entry) {
K key = entry.getKey();
return this.getNodeEntry(key) != null;
}
- public void removeNodeEntry(KeyEntry<K> entry)
- {
+ public void removeNodeEntry(KeyEntry<K> entry) {
KeyEntry<K> ne = keyMap.remove(entry.getKey());
- if (ne != null)
- {
+ if (ne != null) {
// don't remove directly from the LinkedList otherwise we will incur a O(n) = n
// performance penalty for every removal! In the prune method for LFU, we will iterate the LinkedList through ONCE
// doing a single O(n) = n operation and removal. This is much preferred over running O(n) = n every single time
@@ -109,10 +95,8 @@
}
}
- public void addNodeEntry(KeyEntry<K> entry)
- {
- if (!this.containsNodeEntry(entry))
- {
+ public void addNodeEntry(KeyEntry<K> entry) {
+ if (!this.containsNodeEntry(entry)) {
K key = entry.getKey();
keyMap.put(key, entry);
evictionList.add(entry);
@@ -120,95 +104,76 @@
}
}
- public int getNumberOfNodes()
- {
+ public int getNumberOfNodes() {
return keyMap.size();
}
- public int getNumberOfElements()
- {
+ public int getNumberOfElements() {
return this.numElements;
}
- public void clear()
- {
+ public void clear() {
keyMap.clear();
evictionList.clear();
removalQueue.clear();
this.numElements = 0;
}
- public void resortEvictionQueue()
- {
+ public void resortEvictionQueue() {
Collections.sort(evictionList, comparator);
}
- public void modifyElementCount(int difference)
- {
+ public void modifyElementCount(int difference) {
this.numElements += difference;
}
- protected void prune()
- {
+ protected void prune() {
Iterator<KeyEntry<K>> it = this.iterator();
- while (it.hasNext() && removalQueue.size() > 0)
- {
- if (removalQueue.remove(it.next()))
- {
+ while (it.hasNext() && removalQueue.size() > 0) {
+ if (removalQueue.remove(it.next())) {
it.remove();
}
}
}
- protected final List<KeyEntry<K>> getEvictionList()
- {
+ protected final List<KeyEntry<K>> getEvictionList() {
return this.evictionList;
}
- protected final Set<KeyEntry<K>> getRemovalQueue()
- {
+ protected final Set<KeyEntry<K>> getRemovalQueue() {
return this.removalQueue;
}
- public Iterator<KeyEntry<K>> iterator()
- {
+ public Iterator<KeyEntry<K>> iterator() {
return evictionList.iterator();
}
/**
* Comparator class for LFU.
* <p/>
- * This class will sort the eviction queue in the correct eviction order.
- * The top of the list should evict before the bottom of the list.
+ * This class will sort the eviction queue in the correct eviction order. The top of the list should evict before the
+ * bottom of the list.
* <p/>
* The sort is based on ascending order of nodeVisits.
* <p/>
* Note: this class has a natural ordering that is inconsistent with equals as defined by the java.lang.Comparator
* contract.
*/
- protected static class LFUComparator<K> implements Comparator<KeyEntry<K>>
- {
+ protected static class LFUComparator<K> implements Comparator<KeyEntry<K>> {
- public int compare(KeyEntry<K> ne1, KeyEntry<K> ne2)
- {
- if (ne1.equals(ne2))
- {
+ public int compare(KeyEntry<K> ne1, KeyEntry<K> ne2) {
+ if (ne1.equals(ne2)) {
return 0;
}
int neNodeHits = ne1.getNumberOfNodeVisits();
int ne2NodeHits = ne2.getNumberOfNodeVisits();
- if (neNodeHits > ne2NodeHits)
- {
+ if (neNodeHits > ne2NodeHits) {
return 1;
- }
- else if (neNodeHits < ne2NodeHits)
- {
+ } else if (neNodeHits < ne2NodeHits) {
return -1;
- }
- else if (neNodeHits == ne2NodeHits)
- {
+ } else if (neNodeHits == ne2NodeHits) {
return 0;
}
throw new RuntimeException("Should never reach this condition");
Modified: core/branches/flat/src/main/java/org/horizon/eviction/algorithms/lru/LRUAlgorithm.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/eviction/algorithms/lru/LRUAlgorithm.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/eviction/algorithms/lru/LRUAlgorithm.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -24,35 +24,31 @@
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.horizon.config.EvictionAlgorithmConfig;
-import org.horizon.eviction.algorithms.BaseEvictionAlgorithm;
-import org.horizon.eviction.KeyEntry;
-import org.horizon.eviction.EvictionQueue;
import org.horizon.eviction.EvictionException;
+import org.horizon.eviction.EvictionQueue;
+import org.horizon.eviction.KeyEntry;
+import org.horizon.eviction.algorithms.BaseEvictionAlgorithm;
import java.util.Iterator;
/**
- * Least recently Used algorithm to purge old data.
- * Note that this algorithm is not thread-safe.
+ * Least recently Used algorithm to purge old data. Note that this algorithm is not thread-safe.
*
* @author Ben Wang 02-2004
* @author Daniel Huang - dhuang at jboss.org
* @since 1.0
*/
-public class LRUAlgorithm<K> extends BaseEvictionAlgorithm<K>
-{
+public class LRUAlgorithm<K> extends BaseEvictionAlgorithm<K> {
private static final Log log = LogFactory.getLog(LRUAlgorithm.class);
private static final boolean trace = log.isTraceEnabled();
@Override
- protected EvictionQueue<K> setupEvictionQueue() throws EvictionException
- {
+ protected EvictionQueue<K> setupEvictionQueue() throws EvictionException {
return new LRUQueue<K>();
}
@Override
- protected boolean shouldEvictNode(KeyEntry<K> entry)
- {
+ protected boolean shouldEvictNode(KeyEntry<K> entry) {
// check the minimum time to live and see if we should not evict the node. This check will
// ensure that, if configured, nodes are kept alive for at least a minimum period of time.
if (entry.isYoungerThanMinimumTimeToLive(evictionAlgorithmConfig.getMinTimeToLive())) return false;
@@ -62,17 +58,13 @@
if (config.getTimeToLive() < 0 && config.getMaxAge() < 0) return false;
long currentTime = System.currentTimeMillis();
- if (config.getTimeToLive() > -1)
- {
+ if (config.getTimeToLive() > -1) {
long idleTime = currentTime - entry.getModifiedTimeStamp();
- if (trace)
- {
+ if (trace) {
log.trace("Node " + entry.getKey() + " has been idle for " + idleTime + "ms");
}
- if ((idleTime >= (config.getTimeToLive())))
- {
- if (trace)
- {
+ if ((idleTime >= (config.getTimeToLive()))) {
+ if (trace) {
log.trace("Node " + entry.getKey() + " should be evicted because of idle time");
log.trace("Time to live in millies is: " + (config.getTimeToLive()));
log.trace("Config instance is: " + System.identityHashCode(config));
@@ -81,43 +73,33 @@
}
}
- if (config.getMaxAge() > -1)
- {
+ if (config.getMaxAge() > -1) {
long objectLifeTime = currentTime - entry.getCreationTimeStamp();
- if (trace)
- {
+ if (trace) {
log.trace("Node " + entry.getKey() + " has been alive for " + objectLifeTime + "ms");
}
- if ((objectLifeTime >= config.getMaxAge()))
- {
- if (trace)
- {
+ if ((objectLifeTime >= config.getMaxAge())) {
+ if (trace) {
log.trace("Node " + entry.getKey() + " should be evicted because of max age");
}
return true;
}
}
- if (trace)
- {
+ if (trace) {
log.trace("Node " + entry.getKey() + " should not be evicted");
}
return false;
}
@Override
- protected void evict(KeyEntry<K> ne)
- {
- if (ne != null)
- {
- if (!evictionAction.evict(ne.getKey()))
- {
- try
- {
+ protected void evict(KeyEntry<K> ne) {
+ if (ne != null) {
+ if (!evictionAction.evict(ne.getKey())) {
+ try {
recycleQueue.put(ne.getKey());
}
- catch (InterruptedException e)
- {
+ catch (InterruptedException e) {
log.debug("InterruptedException", e);
}
}
@@ -125,60 +107,49 @@
}
@Override
- protected void prune() throws EvictionException
- {
+ protected void prune() throws EvictionException {
LRUQueue<K> lruQueue = (LRUQueue<K>) evictionQueue;
KeyEntry<K> ne;
Iterator<KeyEntry<K>> it = lruQueue.iterateLRUQueue();
- while (it.hasNext())
- {
+ while (it.hasNext()) {
ne = it.next();
if (ne.isNodeInUseAndNotTimedOut()) continue;
- if (this.shouldEvictNode(ne))
- {
+ if (this.shouldEvictNode(ne)) {
it.remove();
lruQueue.removeNodeEntryFromMaxAge(ne);
this.evict(ne);
- } else
- {
+ } else {
break;
}
}
it = lruQueue.iterateMaxAgeQueue();
- while (it.hasNext())
- {
+ while (it.hasNext()) {
ne = it.next();
if (ne.isNodeInUseAndNotTimedOut()) continue;
- if (this.shouldEvictNode(ne))
- {
+ if (this.shouldEvictNode(ne)) {
it.remove();
lruQueue.removeNodeEntryFromLRU(ne);
this.evict(ne);
- } else
- {
+ } else {
break;
}
}
int maxNodes = ((LRUAlgorithmConfig) evictionAlgorithmConfig).getMaxNodes();
- if (maxNodes <= 0)
- {
+ if (maxNodes <= 0) {
return;
}
it = lruQueue.iterateLRUQueue();
- while (evictionQueue.getNumberOfNodes() > maxNodes)
- {
+ while (evictionQueue.getNumberOfNodes() > maxNodes) {
ne = it.next();
- if (trace)
- {
+ if (trace) {
log.trace("Node " + ne.getKey() + " will be evicted because of exceeding the maxNode limit." +
" maxNode: " + maxNodes + " but current queue size is: " + evictionQueue.getNumberOfNodes());
}
- if (!ne.isNodeInUseAndNotTimedOut())
- {
+ if (!ne.isNodeInUseAndNotTimedOut()) {
it.remove();
lruQueue.removeNodeEntryFromMaxAge(ne);
this.evict(ne);
@@ -186,8 +157,7 @@
}
}
- public Class<? extends EvictionAlgorithmConfig> getConfigurationClass()
- {
+ public Class<? extends EvictionAlgorithmConfig> getConfigurationClass() {
return LRUAlgorithmConfig.class;
}
}
Modified: core/branches/flat/src/main/java/org/horizon/eviction/algorithms/lru/LRUAlgorithmConfig.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/eviction/algorithms/lru/LRUAlgorithmConfig.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/eviction/algorithms/lru/LRUAlgorithmConfig.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -34,8 +34,7 @@
* @author Manik Surtani
* @since 1.0
*/
-public class LRUAlgorithmConfig extends EvictionAlgorithmConfigBase
-{
+public class LRUAlgorithmConfig extends EvictionAlgorithmConfigBase {
/**
* The serialVersionUID
*/
@@ -53,23 +52,20 @@
@Dynamic
private long maxAge;
- public LRUAlgorithmConfig()
- {
+ public LRUAlgorithmConfig() {
evictionAlgorithmClassName = LRUAlgorithm.class.getName();
// Force config of ttls
setTimeToLive(-1);
setMaxAge(-1);
}
- public LRUAlgorithmConfig(long timeToLive, long maxAge)
- {
+ public LRUAlgorithmConfig(long timeToLive, long maxAge) {
this();
this.timeToLive = timeToLive;
this.maxAge = maxAge;
}
- public LRUAlgorithmConfig(long timeToLive, int maxAge, int maxNodes)
- {
+ public LRUAlgorithmConfig(long timeToLive, int maxAge, int maxNodes) {
this(timeToLive, maxAge);
this.maxNodes = maxNodes;
}
@@ -77,8 +73,7 @@
/**
* @return the time to live, in milliseconds
*/
- public long getTimeToLive()
- {
+ public long getTimeToLive() {
return timeToLive;
}
@@ -87,14 +82,12 @@
*
* @param timeToLive the time to live, in milliseconds
*/
- public void setTimeToLive(long timeToLive)
- {
+ public void setTimeToLive(long timeToLive) {
testImmutability("timeToLive");
this.timeToLive = timeToLive;
}
- public void setTimeToLive(long timeToLive, TimeUnit timeUnit)
- {
+ public void setTimeToLive(long timeToLive, TimeUnit timeUnit) {
testImmutability("timeToLive");
this.timeToLive = timeUnit.toMillis(timeToLive);
}
@@ -102,8 +95,7 @@
/**
* @return the max age per element, in milliseconds
*/
- public long getMaxAge()
- {
+ public long getMaxAge() {
return maxAge;
}
@@ -112,35 +104,29 @@
*
* @param maxAge value in milliseconds
*/
- public void setMaxAge(long maxAge)
- {
+ public void setMaxAge(long maxAge) {
testImmutability("maxAge");
this.maxAge = maxAge;
}
- public void setMaxAge(long maxAge, TimeUnit timeUnit)
- {
+ public void setMaxAge(long maxAge, TimeUnit timeUnit) {
testImmutability("maxAge");
this.maxAge = timeUnit.toMillis(maxAge);
}
/**
- * Requires a positive timeToLive value or ConfigurationException
- * is thrown.
+ * Requires a positive timeToLive value or ConfigurationException is thrown.
*/
@Override
- public void validate() throws ConfigurationException
- {
+ public void validate() throws ConfigurationException {
super.validate();
- if (timeToLive < -1)
- {
+ if (timeToLive < -1) {
throw new ConfigurationException("timeToLive must be " +
"configured to a value greater than or equal to 0 (or -1 for unlimited time to live) for " + getEvictionAlgorithmClassName());
}
}
- public String toString()
- {
+ public String toString() {
return "LRUAlgorithmConfig {" +
"algorithmClassName=" + evictionAlgorithmClassName +
", timeToLive=" + timeToLive +
@@ -148,8 +134,7 @@
'}';
}
- public boolean equals(Object o)
- {
+ public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof LRUAlgorithmConfig)) return false;
if (!super.equals(o)) return false;
@@ -162,8 +147,7 @@
return true;
}
- public int hashCode()
- {
+ public int hashCode() {
int result = super.hashCode();
result = 31 * result + (int) (timeToLive ^ (timeToLive >>> 32));
result = 31 * result + (int) (maxAge ^ (maxAge >>> 32));
@@ -171,8 +155,7 @@
}
@Override
- public void reset()
- {
+ public void reset() {
super.reset();
setTimeToLive(-1);
setMaxAge(-1);
@@ -180,8 +163,7 @@
}
@Override
- public LRUAlgorithmConfig clone() throws CloneNotSupportedException
- {
+ public LRUAlgorithmConfig clone() throws CloneNotSupportedException {
return (LRUAlgorithmConfig) super.clone();
}
}
\ No newline at end of file
Modified: core/branches/flat/src/main/java/org/horizon/eviction/algorithms/lru/LRUQueue.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/eviction/algorithms/lru/LRUQueue.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/eviction/algorithms/lru/LRUQueue.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -31,47 +31,38 @@
/**
* LRU Eviction Queue implementation.
* <p/>
- * This eviction queue will iterate properly through two sorted lists.
- * One sorted by maxAge and the other sorted by idleTime.
+ * This eviction queue will iterate properly through two sorted lists. One sorted by maxAge and the other sorted by
+ * idleTime.
*
* @author Daniel Huang (dhuang at jboss.org)
- *
* @since 1.0
*/
-public class LRUQueue<K> implements EvictionQueue<K>
-{
+public class LRUQueue<K> implements EvictionQueue<K> {
private Map<K, KeyEntry<K>> maxAgeQueue;
private Map<K, KeyEntry<K>> lruQueue;
private long alternatingCount = 0;
private int numElements = 0;
- protected LRUQueue()
- {
+ protected LRUQueue() {
maxAgeQueue = new LinkedHashMap<K, KeyEntry<K>>();
lruQueue = new LinkedHashMap<K, KeyEntry<K>>(16, 0.75f, true);
}
/**
- * because the underlying queue is in two differently sorted queues, we alternate between them when calling
- * a generic getFirstNodeEntry.
- * we must alternate to keep things balanced when evicting nodes based on the maxNodes attribute. We don't
- * want to just prune from one queue but rather we want to be able to prune from both.
+ * because the underlying queue is in two differently sorted queues, we alternate between them when calling a generic
+ * getFirstNodeEntry. we must alternate to keep things balanced when evicting nodes based on the maxNodes attribute.
+ * We don't want to just prune from one queue but rather we want to be able to prune from both.
*/
- public KeyEntry<K> getFirstNodeEntry()
- {
+ public KeyEntry<K> getFirstNodeEntry() {
KeyEntry<K> ne;
- if (alternatingCount % 2 == 0)
- {
+ if (alternatingCount % 2 == 0) {
ne = this.getFirstLRUNodeEntry();
- if (ne == null)
- {
+ if (ne == null) {
ne = this.getFirstMaxAgeNodeEntry();
}
- } else
- {
+ } else {
ne = this.getFirstMaxAgeNodeEntry();
- if (ne == null)
- {
+ if (ne == null) {
ne = this.getFirstLRUNodeEntry();
}
}
@@ -79,66 +70,53 @@
return ne;
}
- public KeyEntry<K> getFirstLRUNodeEntry()
- {
- if (lruQueue.size() > 0)
- {
+ public KeyEntry<K> getFirstLRUNodeEntry() {
+ if (lruQueue.size() > 0) {
return lruQueue.values().iterator().next();
}
return null;
}
- public KeyEntry<K> getFirstMaxAgeNodeEntry()
- {
- if (maxAgeQueue.size() > 0)
- {
+ public KeyEntry<K> getFirstMaxAgeNodeEntry() {
+ if (maxAgeQueue.size() > 0) {
return maxAgeQueue.values().iterator().next();
}
return null;
}
- public KeyEntry<K> getNodeEntry(K key)
- {
+ public KeyEntry<K> getNodeEntry(K key) {
return lruQueue.get(key);
}
- public boolean containsNodeEntry(KeyEntry<K> entry)
- {
+ public boolean containsNodeEntry(KeyEntry<K> entry) {
return this.maxAgeQueue.containsKey(entry.getKey());
}
- protected void removeNodeEntryFromLRU(KeyEntry<K> entry)
- {
+ protected void removeNodeEntryFromLRU(KeyEntry<K> entry) {
K key = entry.getKey();
lruQueue.remove(key);
}
- protected void removeNodeEntryFromMaxAge(KeyEntry<K> entry)
- {
+ protected void removeNodeEntryFromMaxAge(KeyEntry<K> entry) {
K key = entry.getKey();
maxAgeQueue.remove(key);
}
- public void removeNodeEntry(KeyEntry<K> entry)
- {
- if (!this.containsNodeEntry(entry))
- {
+ public void removeNodeEntry(KeyEntry<K> entry) {
+ if (!this.containsNodeEntry(entry)) {
return;
}
K key = entry.getKey();
KeyEntry ne1 = lruQueue.remove(key);
KeyEntry ne2 = maxAgeQueue.remove(key);
- if (ne1 == null || ne2 == null)
- {
+ if (ne1 == null || ne2 == null) {
throw new RuntimeException("The queues are out of sync.");
}
this.numElements -= ne1.getNumberOfElements();
}
- public void addNodeEntry(KeyEntry<K> entry)
- {
- if (!this.containsNodeEntry(entry))
- {
+ public void addNodeEntry(KeyEntry<K> entry) {
+ if (!this.containsNodeEntry(entry)) {
K key = entry.getKey();
maxAgeQueue.put(key, entry);
lruQueue.put(key, entry);
@@ -146,40 +124,33 @@
}
}
- public int getNumberOfNodes()
- {
+ public int getNumberOfNodes() {
return maxAgeQueue.size();
}
- public int getNumberOfElements()
- {
+ public int getNumberOfElements() {
return this.numElements;
}
- public void clear()
- {
+ public void clear() {
maxAgeQueue.clear();
lruQueue.clear();
this.numElements = 0;
}
- public void modifyElementCount(int difference)
- {
+ public void modifyElementCount(int difference) {
this.numElements += difference;
}
- public Iterator<KeyEntry<K>> iterator()
- {
+ public Iterator<KeyEntry<K>> iterator() {
return lruQueue.values().iterator();
}
- protected final Iterator<KeyEntry<K>> iterateMaxAgeQueue()
- {
+ protected final Iterator<KeyEntry<K>> iterateMaxAgeQueue() {
return maxAgeQueue.values().iterator();
}
- protected final Iterator<KeyEntry<K>> iterateLRUQueue()
- {
+ protected final Iterator<KeyEntry<K>> iterateLRUQueue() {
return lruQueue.values().iterator();
}
Modified: core/branches/flat/src/main/java/org/horizon/eviction/algorithms/mru/EvictionListEntry.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/eviction/algorithms/mru/EvictionListEntry.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/eviction/algorithms/mru/EvictionListEntry.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -29,24 +29,20 @@
* @author Manik Surtani (<a href="mailto:manik at jboss.org">manik at jboss.org</a>)
* @since 1.0
*/
-public class EvictionListEntry<K>
-{
+public class EvictionListEntry<K> {
EvictionListEntry<K> next;
KeyEntry<K> keyEntry;
EvictionListEntry<K> previous;
- EvictionListEntry()
- {
+ EvictionListEntry() {
}
- EvictionListEntry(KeyEntry<K> keyEntry)
- {
+ EvictionListEntry(KeyEntry<K> keyEntry) {
this.keyEntry = keyEntry;
}
@Override
- public boolean equals(Object o)
- {
+ public boolean equals(Object o) {
if (!(o instanceof EvictionListEntry))
return false;
EvictionListEntry entry = (EvictionListEntry) o;
@@ -54,14 +50,12 @@
}
@Override
- public int hashCode()
- {
+ public int hashCode() {
return this.keyEntry.getKey().hashCode();
}
@Override
- public String toString()
- {
+ public String toString() {
return "EvictionListEntry=" + keyEntry;
}
Modified: core/branches/flat/src/main/java/org/horizon/eviction/algorithms/mru/EvictionQueueList.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/eviction/algorithms/mru/EvictionQueueList.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/eviction/algorithms/mru/EvictionQueueList.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -23,91 +23,76 @@
import org.horizon.eviction.KeyEntry;
-import java.util.*;
+import java.util.Arrays;
+import java.util.Comparator;
+import java.util.ConcurrentModificationException;
+import java.util.Iterator;
+import java.util.ListIterator;
+import java.util.NoSuchElementException;
/**
* @author Daniel Huang (dhuang at jboss.org)
- *
* @since 1.0
*/
-public class EvictionQueueList<K>
-{
+public class EvictionQueueList<K> {
private EvictionListEntry<K> head;
private EvictionListEntry<K> tail;
private int modCount;
private int size;
- EvictionQueueList()
- {
+ EvictionQueueList() {
head = null;
tail = null;
size = 0;
modCount = 0;
}
- void addToTop(EvictionListEntry<K> entry)
- {
+ void addToTop(EvictionListEntry<K> entry) {
EvictionListEntry<K> formerHead = head;
head = entry;
// if there was no previous head then this list was empty.
- if (formerHead != null)
- {
+ if (formerHead != null) {
formerHead.previous = head;
head.next = formerHead;
head.previous = null;
- }
- else
- {
+ } else {
tail = entry;
}
size++;
modCount++;
}
- void addToBottom(EvictionListEntry<K> entry)
- {
+ void addToBottom(EvictionListEntry<K> entry) {
EvictionListEntry<K> formerTail = tail;
tail = entry;
// if there was no previous head then this list was empty.
- if (formerTail != null)
- {
+ if (formerTail != null) {
tail.previous = formerTail;
formerTail.next = tail;
tail.next = null;
- }
- else
- {
+ } else {
head = entry;
}
size++;
modCount++;
}
- void remove(EvictionListEntry<K> entry)
- {
- if (this.isEmpty())
- {
+ void remove(EvictionListEntry<K> entry) {
+ if (this.isEmpty()) {
return;
}
- if (isSingleNode(entry))
- {
+ if (isSingleNode(entry)) {
head = null;
tail = null;
- }
- else if (isTail(entry))
- {
+ } else if (isTail(entry)) {
tail = entry.previous;
// unlink the last node.
entry.previous.next = null;
- }
- else if (isHead(entry))
- {
+ } else if (isHead(entry)) {
head = entry.next;
head.previous = null;
- }
- else
- {
+ } else {
// node is in between two other nodes.
entry.next.previous = entry.previous;
entry.previous.next = entry.next;
@@ -116,55 +101,45 @@
modCount++;
}
- int size()
- {
+ int size() {
return this.size;
}
- void clear()
- {
+ void clear() {
head = null;
tail = null;
size = 0;
modCount++;
}
- EvictionListEntry<K> getFirst()
- {
- if (head == null)
- {
+ EvictionListEntry<K> getFirst() {
+ if (head == null) {
throw new NoSuchElementException("List is empty");
}
return head;
}
- EvictionListEntry getLast()
- {
- if (tail == null)
- {
+ EvictionListEntry getLast() {
+ if (tail == null) {
throw new NoSuchElementException("List is empty");
}
return tail;
}
@SuppressWarnings(value = "unchecked")
- Iterator<KeyEntry<K>> iterator()
- {
+ Iterator<KeyEntry<K>> iterator() {
return new EvictionListIterator();
}
- KeyEntry[] toNodeEntryArray()
- {
- if (isEmpty())
- {
+ KeyEntry[] toNodeEntryArray() {
+ if (isEmpty()) {
return null;
}
KeyEntry[] ret = new KeyEntry[size];
int i = 0;
EvictionListEntry temp = head;
- do
- {
+ do {
ret[i] = temp.keyEntry;
temp = temp.next;
i++;
@@ -174,18 +149,15 @@
return ret;
}
- EvictionListEntry[] toArray()
- {
- if (isEmpty())
- {
+ EvictionListEntry[] toArray() {
+ if (isEmpty()) {
return null;
}
EvictionListEntry[] ret = new EvictionListEntry[size];
int i = 0;
EvictionListEntry temp = head;
- do
- {
+ do {
ret[i] = temp;
temp = temp.next;
i++;
@@ -195,105 +167,86 @@
return ret;
}
- void fromArray(EvictionListEntry<K>[] evictionListEntries)
- {
+ void fromArray(EvictionListEntry<K>[] evictionListEntries) {
- for (EvictionListEntry<K> evictionListEntry : evictionListEntries)
- {
+ for (EvictionListEntry<K> evictionListEntry : evictionListEntries) {
this.addToBottom(evictionListEntry);
}
}
- private boolean isEmpty()
- {
+ private boolean isEmpty() {
return head == null && tail == null;
}
- private boolean isSingleNode(EvictionListEntry entry)
- {
+ private boolean isSingleNode(EvictionListEntry entry) {
return isTail(entry) && isHead(entry);
}
- private boolean isTail(EvictionListEntry entry)
- {
+ private boolean isTail(EvictionListEntry entry) {
return entry.next == null;
}
- private boolean isHead(EvictionListEntry entry)
- {
+ private boolean isHead(EvictionListEntry entry) {
return entry.previous == null;
}
@Override
- public String toString()
- {
+ public String toString() {
return Arrays.asList(toArray()).toString();
}
- static class EvictionListComparator implements Comparator<EvictionListEntry>
- {
+ static class EvictionListComparator implements Comparator<EvictionListEntry> {
Comparator<KeyEntry> nodeEntryComparator;
- EvictionListComparator(Comparator<KeyEntry> nodeEntryComparator)
- {
+ EvictionListComparator(Comparator<KeyEntry> nodeEntryComparator) {
this.nodeEntryComparator = nodeEntryComparator;
}
- public int compare(EvictionListEntry e1, EvictionListEntry e2)
- {
+ public int compare(EvictionListEntry e1, EvictionListEntry e2) {
return nodeEntryComparator.compare(e1.keyEntry, e2.keyEntry);
}
}
- class EvictionListIterator implements ListIterator
- {
+ class EvictionListIterator implements ListIterator {
EvictionListEntry<K> next = head;
EvictionListEntry<K> previous;
EvictionListEntry<K> cursor;
int initialModCount = EvictionQueueList.this.modCount;
- public boolean hasNext()
- {
+ public boolean hasNext() {
this.doConcurrentModCheck();
return next != null;
}
- public KeyEntry<K> next()
- {
+ public KeyEntry<K> next() {
this.doConcurrentModCheck();
this.forwardCursor();
return cursor.keyEntry;
}
- public boolean hasPrevious()
- {
+ public boolean hasPrevious() {
this.doConcurrentModCheck();
return previous != null;
}
- public KeyEntry<K> previous()
- {
+ public KeyEntry<K> previous() {
this.doConcurrentModCheck();
this.rewindCursor();
return cursor.keyEntry;
}
- public int nextIndex()
- {
+ public int nextIndex() {
throw new UnsupportedOperationException();
}
- public int previousIndex()
- {
+ public int previousIndex() {
throw new UnsupportedOperationException();
}
- public void remove()
- {
+ public void remove() {
this.doConcurrentModCheck();
- if (cursor == null)
- {
+ if (cursor == null) {
throw new IllegalStateException("Cannot remove from iterator when there is nothing at the current iteration point");
}
EvictionQueueList.this.remove(cursor);
@@ -302,30 +255,24 @@
}
@SuppressWarnings(value = "unchecked")
- public void set(Object o)
- {
+ public void set(Object o) {
this.doConcurrentModCheck();
cursor.keyEntry = (KeyEntry<K>) o;
}
- public void add(Object o)
- {
+ public void add(Object o) {
this.doConcurrentModCheck();
initialModCount++;
}
- private void doConcurrentModCheck()
- {
- if (EvictionQueueList.this.modCount != initialModCount)
- {
+ private void doConcurrentModCheck() {
+ if (EvictionQueueList.this.modCount != initialModCount) {
throw new ConcurrentModificationException();
}
}
- private void forwardCursor()
- {
- if (next == null)
- {
+ private void forwardCursor() {
+ if (next == null) {
throw new NoSuchElementException("No more objects to iterate.");
}
previous = cursor;
@@ -333,10 +280,8 @@
next = cursor.next;
}
- private void rewindCursor()
- {
- if (previous == null)
- {
+ private void rewindCursor() {
+ if (previous == null) {
throw new NoSuchElementException();
}
next = cursor;
Modified: core/branches/flat/src/main/java/org/horizon/eviction/algorithms/mru/MRUAlgorithm.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/eviction/algorithms/mru/MRUAlgorithm.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/eviction/algorithms/mru/MRUAlgorithm.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -22,11 +22,11 @@
package org.horizon.eviction.algorithms.mru;
import org.horizon.config.EvictionAlgorithmConfig;
-import org.horizon.eviction.algorithms.BaseEvictionAlgorithm;
-import org.horizon.eviction.KeyEntry;
-import org.horizon.eviction.EvictionException;
import org.horizon.eviction.EvictionEvent;
+import org.horizon.eviction.EvictionException;
import org.horizon.eviction.EvictionQueue;
+import org.horizon.eviction.KeyEntry;
+import org.horizon.eviction.algorithms.BaseEvictionAlgorithm;
/**
* Most Recently Used Algorithm.
@@ -37,20 +37,16 @@
* EvictionAlgorithm/EvictionQueue/EvictionConfiguration are only operated on by one thread at any given time.
*
* @author Daniel Huang (dhuang at jboss.org)
- *
* @since 1.0
*/
-public class MRUAlgorithm<K> extends BaseEvictionAlgorithm<K>
-{
+public class MRUAlgorithm<K> extends BaseEvictionAlgorithm<K> {
@Override
- protected EvictionQueue<K> setupEvictionQueue() throws EvictionException
- {
+ protected EvictionQueue<K> setupEvictionQueue() throws EvictionException {
return new MRUQueue<K>();
}
@Override
- protected boolean shouldEvictNode(KeyEntry ne)
- {
+ protected boolean shouldEvictNode(KeyEntry ne) {
// check the minimum time to live and see if we should not evict the node. This check will
// ensure that, if configured, nodes are kept alive for at least a minimum period of time.
if (ne.isYoungerThanMinimumTimeToLive(evictionAlgorithmConfig.getMinTimeToLive())) return false;
@@ -60,14 +56,12 @@
}
@Override
- protected void processVisitedNodes(EvictionEvent<K> evictedEventNode) throws EvictionException
- {
+ protected void processVisitedNodes(EvictionEvent<K> evictedEventNode) throws EvictionException {
super.processVisitedNodes(evictedEventNode);
((MRUQueue<K>) evictionQueue).moveToTopOfStack(evictedEventNode.getKey());
}
- public Class<? extends EvictionAlgorithmConfig> getConfigurationClass()
- {
+ public Class<? extends EvictionAlgorithmConfig> getConfigurationClass() {
return MRUAlgorithmConfig.class;
}
}
Modified: core/branches/flat/src/main/java/org/horizon/eviction/algorithms/mru/MRUAlgorithmConfig.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/eviction/algorithms/mru/MRUAlgorithmConfig.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/eviction/algorithms/mru/MRUAlgorithmConfig.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -32,41 +32,35 @@
* @author Manik Surtani
* @since 1.0
*/
-public class MRUAlgorithmConfig extends EvictionAlgorithmConfigBase
-{
+public class MRUAlgorithmConfig extends EvictionAlgorithmConfigBase {
/**
* The serialVersionUID
*/
private static final long serialVersionUID = -8734577898966155218L;
- public MRUAlgorithmConfig()
- {
+ public MRUAlgorithmConfig() {
evictionAlgorithmClassName = MRUAlgorithm.class.getName();
// We require that maxNodes is set
setMaxNodes(-1);
}
- public MRUAlgorithmConfig(int maxNodes)
- {
+ public MRUAlgorithmConfig(int maxNodes) {
evictionAlgorithmClassName = MRUAlgorithm.class.getName();
setMaxNodes(maxNodes);
}
/**
- * Requires a positive maxNodes value or ConfigurationException
- * is thrown.
+ * Requires a positive maxNodes value or ConfigurationException is thrown.
*/
@Override
- public void validate() throws ConfigurationException
- {
+ public void validate() throws ConfigurationException {
super.validate();
if (getMaxNodes() < 0)
throw new ConfigurationException("maxNodes not configured");
}
@Override
- public String toString()
- {
+ public String toString() {
StringBuilder str = new StringBuilder();
str.append("MRUAlgorithmConfig: ").
append(" maxNodes =").append(getMaxNodes());
@@ -74,22 +68,19 @@
}
@Override
- public boolean equals(Object obj)
- {
+ public boolean equals(Object obj) {
return (obj instanceof MRUAlgorithmConfig && super.equals(obj));
}
@Override
- public void reset()
- {
+ public void reset() {
super.reset();
setMaxNodes(-1);
evictionAlgorithmClassName = MRUAlgorithm.class.getName();
}
@Override
- public MRUAlgorithmConfig clone() throws CloneNotSupportedException
- {
+ public MRUAlgorithmConfig clone() throws CloneNotSupportedException {
return (MRUAlgorithmConfig) super.clone();
}
Modified: core/branches/flat/src/main/java/org/horizon/eviction/algorithms/mru/MRUQueue.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/eviction/algorithms/mru/MRUQueue.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/eviction/algorithms/mru/MRUQueue.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -32,17 +32,14 @@
/**
* MRU Eviction Queue implementation.
* <p/>
- * This nodeMap is sorted by MRU. The first entry in the nodeMap
- * will also be the most recently used entry. The sort is implicit
- * based on a Stack that we can implicitly sort to the top by moving
- * a node that is used to the top of the eviction stack.
+ * This nodeMap is sorted by MRU. The first entry in the nodeMap will also be the most recently used entry. The sort is
+ * implicit based on a Stack that we can implicitly sort to the top by moving a node that is used to the top of the
+ * eviction stack.
*
* @author Daniel Huang (dhuang at jboss.org)
- *
* @since 1.0
*/
-public class MRUQueue<K> implements EvictionQueue<K>
-{
+public class MRUQueue<K> implements EvictionQueue<K> {
// we use our own Stack/Linked List implementation here because it guarantees O(n) = 1 for add, remove, get and
// we can sort it in order of MRU implicitly while still getting O(n) = 1 access time
// throughout.
@@ -50,8 +47,7 @@
private EvictionQueueList<K> list;
private int numElements = 0;
- protected MRUQueue()
- {
+ protected MRUQueue() {
keyMap = new HashMap<K, EvictionListEntry<K>>();
list = new EvictionQueueList<K>();
}
@@ -63,11 +59,9 @@
*
* @param key Fqn of the nodeEntry to move to the top of the stack.
*/
- protected void moveToTopOfStack(K key)
- {
+ protected void moveToTopOfStack(K key) {
EvictionListEntry<K> le = keyMap.remove(key);
- if (le != null)
- {
+ if (le != null) {
list.remove(le);
list.addToTop(le);
keyMap.put(le.keyEntry.getKey(), le);
@@ -81,46 +75,37 @@
*
* @return The first node entry in nodeMap.
*/
- public KeyEntry<K> getFirstNodeEntry()
- {
- try
- {
+ public KeyEntry<K> getFirstNodeEntry() {
+ try {
return list.getFirst().keyEntry;
}
- catch (NoSuchElementException e)
- {
+ catch (NoSuchElementException e) {
//
}
return null;
}
- public KeyEntry<K> getNodeEntry(K key)
- {
+ public KeyEntry<K> getNodeEntry(K key) {
EvictionListEntry<K> le = keyMap.get(key);
if (le != null)
return le.keyEntry;
return null;
}
- public boolean containsNodeEntry(KeyEntry<K> entry)
- {
+ public boolean containsNodeEntry(KeyEntry<K> entry) {
return keyMap.containsKey(entry.getKey());
}
- public void removeNodeEntry(KeyEntry<K> entry)
- {
+ public void removeNodeEntry(KeyEntry<K> entry) {
EvictionListEntry<K> le = keyMap.remove(entry.getKey());
- if (le != null)
- {
+ if (le != null) {
list.remove(le);
this.numElements -= le.keyEntry.getNumberOfElements();
}
}
- public void addNodeEntry(KeyEntry<K> entry)
- {
- if (!this.containsNodeEntry(entry))
- {
+ public void addNodeEntry(KeyEntry<K> entry) {
+ if (!this.containsNodeEntry(entry)) {
EvictionListEntry<K> le = new EvictionListEntry<K>(entry);
list.addToBottom(le);
keyMap.put(entry.getKey(), le);
@@ -128,36 +113,30 @@
}
}
- public int getNumberOfNodes()
- {
+ public int getNumberOfNodes() {
return list.size();
}
- public int getNumberOfElements()
- {
+ public int getNumberOfElements() {
return this.numElements;
}
- public void modifyElementCount(int difference)
- {
+ public void modifyElementCount(int difference) {
this.numElements += difference;
}
- public void clear()
- {
+ public void clear() {
keyMap.clear();
list.clear();
this.numElements = 0;
}
- public Iterator<KeyEntry<K>> iterator()
- {
+ public Iterator<KeyEntry<K>> iterator() {
return list.iterator();
}
@Override
- public String toString()
- {
+ public String toString() {
return list.toString();
}
}
Modified: core/branches/flat/src/main/java/org/horizon/executors/DefaultExecutorFactory.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/executors/DefaultExecutorFactory.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/executors/DefaultExecutorFactory.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -14,18 +14,14 @@
* @author Manik Surtani
* @since 1.0
*/
-public class DefaultExecutorFactory implements ExecutorFactory
-{
- public ExecutorService getExecutor(Properties p)
- {
+public class DefaultExecutorFactory implements ExecutorFactory {
+ public ExecutorService getExecutor(Properties p) {
TypedProperties tp = new TypedProperties(p);
int maxThreads = tp.getIntProperty("maxThreads", 1);
final String threadNamePrefix = tp.getProperty("threadNamePrefix", "Thread");
final AtomicInteger counter = new AtomicInteger(0);
- return Executors.newFixedThreadPool(maxThreads, new ThreadFactory()
- {
- public Thread newThread(Runnable r)
- {
+ return Executors.newFixedThreadPool(maxThreads, new ThreadFactory() {
+ public Thread newThread(Runnable r) {
return new Thread(threadNamePrefix + "-" + counter.getAndIncrement());
}
});
Modified: core/branches/flat/src/main/java/org/horizon/executors/DefaultScheduledExecutorFactory.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/executors/DefaultScheduledExecutorFactory.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/executors/DefaultScheduledExecutorFactory.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -14,17 +14,13 @@
* @author Manik Surtani
* @since 1.0
*/
-public class DefaultScheduledExecutorFactory implements ScheduledExecutorFactory
-{
- public ScheduledExecutorService getScheduledExecutor(Properties p)
- {
+public class DefaultScheduledExecutorFactory implements ScheduledExecutorFactory {
+ public ScheduledExecutorService getScheduledExecutor(Properties p) {
TypedProperties tp = new TypedProperties(p);
final String threadNamePrefix = tp.getProperty("threadNamePrefix", "ScheduledThread");
final AtomicInteger counter = new AtomicInteger(0);
- return Executors.newSingleThreadScheduledExecutor(new ThreadFactory()
- {
- public Thread newThread(Runnable r)
- {
+ return Executors.newSingleThreadScheduledExecutor(new ThreadFactory() {
+ public Thread newThread(Runnable r) {
return new Thread(threadNamePrefix + "-" + counter.getAndIncrement());
}
});
Modified: core/branches/flat/src/main/java/org/horizon/executors/ExecutorFactory.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/executors/ExecutorFactory.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/executors/ExecutorFactory.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -9,7 +9,6 @@
* @author Manik Surtani
* @since 1.0
*/
-public interface ExecutorFactory
-{
+public interface ExecutorFactory {
ExecutorService getExecutor(Properties p);
}
Modified: core/branches/flat/src/main/java/org/horizon/executors/ScheduledExecutorFactory.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/executors/ScheduledExecutorFactory.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/executors/ScheduledExecutorFactory.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -9,7 +9,6 @@
* @author Manik Surtani
* @since 1.0
*/
-public interface ScheduledExecutorFactory
-{
+public interface ScheduledExecutorFactory {
ScheduledExecutorService getScheduledExecutor(Properties p);
}
Modified: core/branches/flat/src/main/java/org/horizon/factories/AbstractComponentRegistry.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/factories/AbstractComponentRegistry.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/factories/AbstractComponentRegistry.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -23,9 +23,9 @@
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
+import org.horizon.CacheException;
import org.horizon.CacheStatus;
import org.horizon.Version;
-import org.horizon.CacheException;
import org.horizon.config.Configuration;
import org.horizon.config.ConfigurationException;
import org.horizon.config.RuntimeConfig;
@@ -52,35 +52,32 @@
import java.util.Set;
/**
- * A registry where components which have been created are stored. Components are stored as singletons, registered under
- * a specific name.
+ * A registry where components which have been created are stored. Components are stored as singletons, registered
+ * under a specific name.
* <p/>
* Components can be retrieved from the registry using {@link #getComponent(Class)}.
* <p/>
* Components can be registered using {@link #registerComponent(Object, Class)}, which will cause any dependencies to be
- * wired in as well. Components that need to be created as a result of wiring will be done using {@link #getOrCreateComponent(Class)},
- * which will look up the default factory for the component type (factories annotated with the appropriate {@link DefaultFactoryFor} annotation.
+ * wired in as well. Components that need to be created as a result of wiring will be done using {@link
+ * #getOrCreateComponent(Class)}, which will look up the default factory for the component type (factories annotated
+ * with the appropriate {@link DefaultFactoryFor} annotation.
* <p/>
* Default factories are treated as components too and will need to be wired before being used.
* <p/>
- * The registry can exist in one of several states, as defined by the {@link CacheStatus} enumeration. In terms of the cache,
- * state changes in the following manner:
- * <ul>
- * <li>INSTANTIATED - when first constructed</li>
- * <li>CONSTRUCTED - when created using the DefaultCacheFactory</li>
- * <li>STARTED - when {@link org.horizon.Cache#start()} is called</li>
- * <li>STOPPED - when {@link org.horizon.Cache#stop()} is called</li>
- * </ul>
+ * The registry can exist in one of several states, as defined by the {@link CacheStatus} enumeration. In terms of the
+ * cache, state changes in the following manner: <ul> <li>INSTANTIATED - when first constructed</li> <li>CONSTRUCTED -
+ * when created using the DefaultCacheFactory</li> <li>STARTED - when {@link org.horizon.Cache#start()} is called</li>
+ * <li>STOPPED - when {@link org.horizon.Cache#stop()} is called</li> </ul>
* <p/>
- * Cache configuration can only be changed and will only be reinjected if the cache is not in the {@link org.horizon.CacheStatus#STARTED} state.
+ * Cache configuration can only be changed and will only be reinjected if the cache is not in the {@link
+ * org.horizon.CacheStatus#STARTED} state.
*
* @author Manik Surtani (<a href="mailto:manik at jboss.org">manik at jboss.org</a>)
* @since 1.0
*/
@NonVolatile
@Scope(Scopes.NAMED_CACHE)
-public abstract class AbstractComponentRegistry implements Lifecycle
-{
+public abstract class AbstractComponentRegistry implements Lifecycle {
/**
* Contains class definitions of component factories that can be used to construct certain components
*/
@@ -110,23 +107,21 @@
*
* @return state of the registry
*/
- public CacheStatus getState()
- {
+ public CacheStatus getState() {
return state;
}
/**
* Wires an object instance with dependencies annotated with the {@link Inject} annotation, creating more components
- * as needed based on the Configuration passed in if these additional components don't exist in the
- * {@link ComponentRegistry}. Strictly for components that don't otherwise live in the registry and have a lifecycle, such as Nodes.
+ * as needed based on the Configuration passed in if these additional components don't exist in the {@link
+ * ComponentRegistry}. Strictly for components that don't otherwise live in the registry and have a lifecycle, such
+ * as Nodes.
*
* @param target object to wire
* @throws ConfigurationException if there is a problem wiring the instance
*/
- public void wireDependencies(Object target) throws ConfigurationException
- {
- try
- {
+ public void wireDependencies(Object target) throws ConfigurationException {
+ try {
// don't use the reflection cache for wireDependencies calls since these are not managed by the ComponentRegistry
// and may be invoked at any time, even after the cache starts.
List<Method> methods = ReflectionUtil.getAllMethods(target.getClass(), Inject.class);
@@ -134,8 +129,7 @@
// search for anything we need to inject
for (Method method : methods) invokeInjectionMethod(target, method);
}
- catch (Exception e)
- {
+ catch (Exception e) {
throw new ConfigurationException("Unable to configure component (type: " + target.getClass() + ", instance " + target + ")", e);
}
}
@@ -149,8 +143,7 @@
*
* @return set of known factory types.
*/
- private Set<Class<? extends ComponentFactory>> getHardcodedFactories()
- {
+ private Set<Class<? extends ComponentFactory>> getHardcodedFactories() {
Set<Class<? extends ComponentFactory>> s = new HashSet<Class<? extends ComponentFactory>>();
s.add(BootstrapFactory.class);
s.add(EmptyConstructorFactory.class);
@@ -173,17 +166,14 @@
* @param component component to register
* @param type type of component
*/
- public void registerComponent(Object component, Class type)
- {
+ public void registerComponent(Object component, Class type) {
String name = type.getName();
Component old = componentLookup.get(name);
- if (old != null)
- {
+ if (old != null) {
// if they are equal don't bother
- if (old.instance.equals(component))
- {
+ if (old.instance.equals(component)) {
if (trace)
log.trace("Attempting to register a component equal to one that already exists under the same name (" + name + "). Not doing anything.");
return;
@@ -191,17 +181,14 @@
}
Component c;
- if (old != null)
- {
+ if (old != null) {
if (trace) log.trace("Replacing old component " + old + " with new instance " + component);
old.instance = component;
old.methodsScanned = false;
c = old;
if (state == CacheStatus.STARTED) populateLifecycleMethods();
- }
- else
- {
+ } else {
c = new Component();
c.name = name;
c.instance = component;
@@ -219,8 +206,7 @@
*
* @param c component to add dependencies to
*/
- protected void addComponentDependencies(Component c)
- {
+ protected void addComponentDependencies(Component c) {
Class type = c.instance.getClass();
List<Method> methods = ReflectionUtil.getAllMethods(type, Inject.class);
c.injectionMethods.clear();
@@ -228,13 +214,11 @@
}
@SuppressWarnings("unchecked")
- protected void invokeInjectionMethod(Object o, Method m)
- {
+ protected void invokeInjectionMethod(Object o, Method m) {
Class[] dependencies = m.getParameterTypes();
Object[] params = new Object[dependencies.length];
- for (int i = 0; i < dependencies.length; i++)
- {
+ for (int i = 0; i < dependencies.length; i++) {
params[i] = getOrCreateComponent(dependencies[i]);
}
@@ -243,35 +227,33 @@
/**
* Retrieves a component if one exists, and if not, attempts to find a factory capable of constructing the component
- * (factories annotated with the {@link DefaultFactoryFor} annotation that is capable of creating the component class).
+ * (factories annotated with the {@link DefaultFactoryFor} annotation that is capable of creating the component
+ * class).
* <p/>
- * If an instance needs to be constructed, dependencies are then automatically wired into the instance, based on methods
- * on the component type annotated with {@link Inject}.
+ * If an instance needs to be constructed, dependencies are then automatically wired into the instance, based on
+ * methods on the component type annotated with {@link Inject}.
* <p/>
- * Summing it up, component retrieval happens in the following order:<br />
- * 1. Look for a component that has already been created and registered.
- * 2. Look for an appropriate component that exists in the {@link Configuration} that may be injected from an external system.
- * 3. Look for a class definition passed in to the {@link Configuration} - such as an EvictionPolicy implementation
- * 4. Attempt to create it by looking for an appropriate factory (annotated with {@link DefaultFactoryFor})
+ * Summing it up, component retrieval happens in the following order:<br /> 1. Look for a component that has already
+ * been created and registered. 2. Look for an appropriate component that exists in the {@link Configuration} that
+ * may be injected from an external system. 3. Look for a class definition passed in to the {@link Configuration} -
+ * such as an EvictionPolicy implementation 4. Attempt to create it by looking for an appropriate factory (annotated
+ * with {@link DefaultFactoryFor})
* <p/>
*
* @param componentClass type of component to be retrieved. Should not be null.
* @return a fully wired component instance, or null if one cannot be found or constructed.
* @throws ConfigurationException if there is a problem with consructing or wiring the instance.
*/
- protected <T> T getOrCreateComponent(Class<T> componentClass)
- {
+ protected <T> T getOrCreateComponent(Class<T> componentClass) {
T component = getComponent(componentClass);
- if (component == null)
- {
+ if (component == null) {
// first see if this has been injected externally.
component = getFromConfiguration(componentClass);
boolean attemptedFactoryConstruction = false;
- if (component == null)
- {
+ if (component == null) {
// create this component and add it to the registry
ComponentFactory factory = getFactory(componentClass);
component = factory.construct(componentClass);
@@ -279,12 +261,9 @@
}
- if (component != null)
- {
+ if (component != null) {
registerComponent(component, componentClass);
- }
- else if (attemptedFactoryConstruction)
- {
+ } else if (attemptedFactoryConstruction) {
if (trace) log.trace("Registering a null for component " + componentClass.getSimpleName());
registerNullComponent(componentClass);
}
@@ -294,22 +273,20 @@
}
/**
- * Retrieves a component factory instance capable of constructing components of a specified type. If the factory doesn't
- * exist in the registry, one is created.
+ * Retrieves a component factory instance capable of constructing components of a specified type. If the factory
+ * doesn't exist in the registry, one is created.
*
* @param componentClass type of component to construct
* @return component factory capable of constructing such components
*/
- protected ComponentFactory getFactory(Class componentClass)
- {
+ protected ComponentFactory getFactory(Class componentClass) {
Map<Class, Class<? extends ComponentFactory>> defaultFactoryMap = getDefaultFactoryMap();
Class<? extends ComponentFactory> cfClass = defaultFactoryMap.get(componentClass);
if (cfClass == null)
throw new ConfigurationException("No registered default factory for component " + componentClass + " found!");
// a component factory is a component too! See if one has been created and exists in the registry
ComponentFactory cf = getComponent(cfClass);
- if (cf == null)
- {
+ if (cf == null) {
// hasn't yet been created. Create and put in registry
cf = instantiateFactory(cfClass);
if (cf == null)
@@ -325,44 +302,38 @@
return cf;
}
- protected Map<Class, Class<? extends ComponentFactory>> getDefaultFactoryMap()
- {
+ protected Map<Class, Class<? extends ComponentFactory>> getDefaultFactoryMap() {
if (defaultFactories == null) scanDefaultFactories();
return defaultFactories;
}
/**
- * Scans the class path for classes annotated with {@link DefaultFactoryFor}, and
- * analyses which components can be created by such factories.
+ * Scans the class path for classes annotated with {@link DefaultFactoryFor}, and analyses which components can be
+ * created by such factories.
*/
- void scanDefaultFactories()
- {
+ void scanDefaultFactories() {
defaultFactories = new HashMap<Class, Class<? extends ComponentFactory>>();
Set<Class<? extends ComponentFactory>> factories = getHardcodedFactories();
- for (Class<? extends ComponentFactory> factory : factories)
- {
+ for (Class<? extends ComponentFactory> factory : factories) {
DefaultFactoryFor dFFAnnotation = factory.getAnnotation(DefaultFactoryFor.class);
for (Class targetClass : dFFAnnotation.classes()) defaultFactories.put(targetClass, factory);
}
}
/**
- * No such thing as a meta factory yet. Factories are created using this method which attempts to use an empty public
- * constructor.
+ * No such thing as a meta factory yet. Factories are created using this method which attempts to use an empty
+ * public constructor.
*
* @param factory class of factory to be created
* @return factory instance
*/
- ComponentFactory instantiateFactory(Class<? extends ComponentFactory> factory)
- {
- try
- {
+ ComponentFactory instantiateFactory(Class<? extends ComponentFactory> factory) {
+ try {
return factory.newInstance();
}
- catch (Exception e)
- {
+ catch (Exception e) {
// unable to get a hold of an instance!!
throw new ConfigurationException("Unable to instantiate factory " + factory, e);
}
@@ -373,8 +344,7 @@
*
* @param type type of component to register as a null
*/
- void registerNullComponent(Class type)
- {
+ void registerNullComponent(Class type) {
registerComponent(NULL_COMPONENT, type);
}
@@ -385,37 +355,29 @@
* @return component, or null if it cannot be found
*/
@SuppressWarnings("unchecked")
- protected <T> T getFromConfiguration(Class<T> componentClass)
- {
+ protected <T> T getFromConfiguration(Class<T> componentClass) {
if (log.isDebugEnabled())
log.debug("Looking in configuration for an instance of " + componentClass + " that may have been injected from an external source.");
Method getter = BeanUtils.getterMethod(Configuration.class, componentClass);
T returnValue = null;
- if (getter != null)
- {
- try
- {
+ if (getter != null) {
+ try {
returnValue = (T) getter.invoke(getConfiguration());
}
- catch (Exception e)
- {
+ catch (Exception e) {
log.warn("Unable to invoke getter " + getter + " on Configuration.class!", e);
}
}
// now try the RuntimeConfig - a legacy "registry" of sorts.
- if (returnValue == null)
- {
+ if (returnValue == null) {
getter = BeanUtils.getterMethod(RuntimeConfig.class, componentClass);
- if (getter != null)
- {
- try
- {
+ if (getter != null) {
+ try {
returnValue = (T) getter.invoke(getConfiguration().getRuntimeConfig());
}
- catch (Exception e)
- {
+ catch (Exception e) {
log.warn("Unable to invoke getter " + getter + " on RuntimeConfig.class!", e);
}
}
@@ -428,8 +390,7 @@
*
* @return a Configuration object
*/
- protected Configuration getConfiguration()
- {
+ protected Configuration getConfiguration() {
// this is assumed to always be present as a part of the bootstrap/construction of a ComponentRegistry.
return getComponent(Configuration.class);
}
@@ -441,8 +402,7 @@
* @return component, or null
*/
@SuppressWarnings("unchecked")
- public <T> T getComponent(Class<T> type)
- {
+ public <T> T getComponent(Class<T> type) {
Component wrapper = componentLookup.get(type.getName());
if (wrapper == null) return null;
@@ -452,11 +412,9 @@
/**
* Rewires components. Can only be called if the current state is WIRED or STARTED.
*/
- public void rewire()
- {
+ public void rewire() {
// need to re-inject everything again.
- for (Component c : new HashSet<Component>(componentLookup.values()))
- {
+ for (Component c : new HashSet<Component>(componentLookup.values())) {
// inject dependencies for this component
c.injectDependencies();
}
@@ -466,20 +424,16 @@
* Scans each registered component for lifecycle methods, and adds them to the appropriate lists, and then sorts them
* by priority.
*/
- private void populateLifecycleMethods()
- {
- for (Component c : componentLookup.values())
- {
- if (!c.methodsScanned)
- {
+ private void populateLifecycleMethods() {
+ for (Component c : componentLookup.values()) {
+ if (!c.methodsScanned) {
c.methodsScanned = true;
c.startMethods.clear();
c.stopMethods.clear();
c.destroyMethods.clear();
List<Method> methods = ReflectionUtil.getAllMethods(c.instance.getClass(), Start.class);
- for (Method m : methods)
- {
+ for (Method m : methods) {
PrioritizedMethod em = new PrioritizedMethod();
em.component = c;
em.method = m;
@@ -488,8 +442,7 @@
}
methods = ReflectionUtil.getAllMethods(c.instance.getClass(), Stop.class);
- for (Method m : methods)
- {
+ for (Method m : methods) {
PrioritizedMethod em = new PrioritizedMethod();
em.component = c;
em.method = m;
@@ -498,8 +451,7 @@
}
methods = ReflectionUtil.getAllMethods(c.instance.getClass(), Destroy.class);
- for (Method m : methods)
- {
+ for (Method m : methods) {
PrioritizedMethod em = new PrioritizedMethod();
em.component = c;
em.method = m;
@@ -513,14 +465,11 @@
/**
* Removes any components not annotated as @NonVolatile.
*/
- public void resetNonVolatile()
- {
+ public void resetNonVolatile() {
// destroy all components to clean up resources
- for (Component c : new HashSet<Component>(componentLookup.values()))
- {
+ for (Component c : new HashSet<Component>(componentLookup.values())) {
// the component is volatile!!
- if (!c.nonVolatile)
- {
+ if (!c.nonVolatile) {
componentLookup.remove(c.name);
}
}
@@ -532,25 +481,21 @@
// These methods perform a check for appropriate transition and then delegate to similarly named internal methods.
/**
- * Creates the components needed by a cache instance and sets the cache status to {@link org.horizon.CacheStatus#CREATED}
- * when it is done.
+ * Creates the components needed by a cache instance and sets the cache status to {@link
+ * org.horizon.CacheStatus#CREATED} when it is done.
*/
- public void create()
- {
- if (!state.createAllowed())
- {
+ public void create() {
+ if (!state.createAllowed()) {
if (state.needToDestroyFailedCache())
destroy();
else
return;
}
- try
- {
+ try {
internalCreate();
}
- catch (Throwable t)
- {
+ catch (Throwable t) {
handleLifecycleTransitionFailure(t);
}
}
@@ -559,97 +504,78 @@
* This starts the components in the cache, connecting to channels, starting service threads, etc. If the cache is
* not in the {@link org.horizon.CacheStatus#CREATED} state, {@link #create()} will be invoked first.
*/
- public void start()
- {
+ public void start() {
boolean createdInStart = false;
- if (!state.startAllowed())
- {
+ if (!state.startAllowed()) {
if (state.needToDestroyFailedCache())
destroy(); // this will take us back to DESTROYED
- if (state.needCreateBeforeStart())
- {
+ if (state.needCreateBeforeStart()) {
create();
createdInStart = true;
- }
- else
+ } else
return;
}
- try
- {
+ try {
internalStart(createdInStart);
}
- catch (Throwable t)
- {
+ catch (Throwable t) {
handleLifecycleTransitionFailure(t);
}
}
/**
- * Stops the cache and sets the cache status to {@link org.horizon.CacheStatus#STOPPED} once it is done. If the cache is not in
- * the {@link org.horizon.CacheStatus#STARTED} state, this is a no-op.
+ * Stops the cache and sets the cache status to {@link org.horizon.CacheStatus#STOPPED} once it is done. If the
+ * cache is not in the {@link org.horizon.CacheStatus#STARTED} state, this is a no-op.
*/
- public void stop()
- {
- if (!state.stopAllowed())
- {
+ public void stop() {
+ if (!state.stopAllowed()) {
return;
}
// Trying to stop() from FAILED is valid, but may not work
boolean failed = state == CacheStatus.FAILED;
- try
- {
+ try {
internalStop();
}
- catch (Throwable t)
- {
- if (failed)
- {
+ catch (Throwable t) {
+ if (failed) {
log.warn("Attempted to stop() from FAILED state, but caught exception; try calling destroy()", t);
}
failed = true;
handleLifecycleTransitionFailure(t);
}
- finally
- {
+ finally {
if (!failed) state = CacheStatus.STOPPED;
}
}
/**
- * Destroys the cache and frees up any resources. Sets the cache status to {@link CacheStatus#DESTROYED} when it is done.
+ * Destroys the cache and frees up any resources. Sets the cache status to {@link CacheStatus#DESTROYED} when it is
+ * done.
* <p/>
- * If the cache is in {@link org.horizon.CacheStatus#STARTED} when this method is called, it will first call {@link #stop()}
- * to stop the cache.
+ * If the cache is in {@link org.horizon.CacheStatus#STARTED} when this method is called, it will first call {@link
+ * #stop()} to stop the cache.
*/
- public void destroy()
- {
- if (!state.destroyAllowed())
- {
- if (state.needStopBeforeDestroy())
- {
- try
- {
+ public void destroy() {
+ if (!state.destroyAllowed()) {
+ if (state.needStopBeforeDestroy()) {
+ try {
stop();
}
- catch (CacheException e)
- {
+ catch (CacheException e) {
log.warn("Needed to call stop() before destroying but stop() threw exception. Proceeding to destroy", e);
}
- }
- else
+ } else
return;
}
- try
- {
+ try {
internalDestroy();
}
- finally
- {
+ finally {
// We always progress to destroyed
state = CacheStatus.DESTROYED;
}
@@ -659,14 +585,12 @@
// ------------------------------ START: Actual internal lifecycle methods --------------------------------
/**
- * Sets the cacheStatus to FAILED and rethrows the problem as one
- * of the declared types. Converts any non-RuntimeException Exception
- * to CacheException.
+ * Sets the cacheStatus to FAILED and rethrows the problem as one of the declared types. Converts any
+ * non-RuntimeException Exception to CacheException.
*
* @param t throwable thrown during failure
*/
- private void handleLifecycleTransitionFailure(Throwable t)
- {
+ private void handleLifecycleTransitionFailure(Throwable t) {
state = CacheStatus.FAILED;
if (t instanceof CacheException)
throw (CacheException) t;
@@ -681,18 +605,15 @@
/**
* The actual create implementation.
*/
- private void internalCreate()
- {
+ private void internalCreate() {
state = CacheStatus.CREATING;
resetNonVolatile();
rewire();
state = CacheStatus.CREATED;
}
- private void internalStart(boolean createdInStart) throws CacheException, IllegalArgumentException
- {
- if (!createdInStart)
- {
+ private void internalStart(boolean createdInStart) throws CacheException, IllegalArgumentException {
+ if (!createdInStart) {
// re-wire all dependencies in case stuff has changed since the cache was created
// remove any components whose construction may have depended upon a configuration that may have changed.
resetNonVolatile();
@@ -722,37 +643,29 @@
state = CacheStatus.STARTED;
}
- private void addShutdownHook()
- {
+ private void addShutdownHook() {
ArrayList al = MBeanServerFactory.findMBeanServer(null);
boolean registerShutdownHook = (getConfiguration().getShutdownHookBehavior() == Configuration.ShutdownHookBehavior.DEFAULT && al.size() == 0)
|| getConfiguration().getShutdownHookBehavior() == Configuration.ShutdownHookBehavior.REGISTER;
- if (registerShutdownHook)
- {
+ if (registerShutdownHook) {
if (log.isTraceEnabled())
log.trace("Registering a shutdown hook. Configured behavior = " + getConfiguration().getShutdownHookBehavior());
- shutdownHook = new Thread()
- {
+ shutdownHook = new Thread() {
@Override
- public void run()
- {
- try
- {
+ public void run() {
+ try {
invokedFromShutdownHook = true;
AbstractComponentRegistry.this.stop();
}
- finally
- {
+ finally {
invokedFromShutdownHook = false;
}
}
};
Runtime.getRuntime().addShutdownHook(shutdownHook);
- }
- else
- {
+ } else {
if (log.isTraceEnabled())
log.trace("Not registering a shutdown hook. Configured behavior = " + getConfiguration().getShutdownHookBehavior());
}
@@ -761,8 +674,7 @@
/**
* Actual stop
*/
- private void internalStop()
- {
+ private void internalStop() {
state = CacheStatus.STOPPING;
// if this is called from a source other than the shutdown hook, deregister the shutdown hook.
if (!invokedFromShutdownHook && shutdownHook != null) Runtime.getRuntime().removeShutdownHook(shutdownHook);
@@ -781,8 +693,7 @@
/**
* Actual destroy
*/
- private void internalDestroy()
- {
+ private void internalDestroy() {
state = CacheStatus.DESTROYING;
@@ -802,16 +713,16 @@
// ------------------------------ END: Actual internal lifecycle methods --------------------------------
/**
- * Asserts whether invocations are allowed on the cache or not. Returns <tt>true</tt> if invocations are to be allowed,
- * <tt>false</tt> otherwise. If the origin of the call is remote and the cache status is {@link org.horizon.CacheStatus#STARTING},
- * this method will block for up to {@link Configuration#getStateRetrievalTimeout()} millis, checking
- * for a valid state.
+ * Asserts whether invocations are allowed on the cache or not. Returns <tt>true</tt> if invocations are to be
+ * allowed, <tt>false</tt> otherwise. If the origin of the call is remote and the cache status is {@link
+ * org.horizon.CacheStatus#STARTING}, this method will block for up to {@link Configuration#getStateRetrievalTimeout()}
+ * millis, checking for a valid state.
*
- * @param originLocal true if the call originates locally (i.e., from the {@link org.horizon.CacheDelegate} or false if it originates remotely, i.e., from the {@link org.horizon.marshall.CommandAwareRpcDispatcher}.
+ * @param originLocal true if the call originates locally (i.e., from the {@link org.horizon.CacheDelegate} or false
+ * if it originates remotely, i.e., from the {@link org.horizon.marshall.CommandAwareRpcDispatcher}.
* @return true if invocations are allowed, false otherwise.
*/
- public boolean invocationsAllowed(boolean originLocal)
- {
+ public boolean invocationsAllowed(boolean originLocal) {
log.trace("Testing if invocations are allowed.");
if (state.allowInvocations()) return true;
@@ -821,21 +732,16 @@
log.trace("Is remotely originating.");
// else if this is a remote call and the status is STARTING, wait until the cache starts.
- if (state == CacheStatus.STARTING)
- {
+ if (state == CacheStatus.STARTING) {
log.trace("Cache is starting; block.");
- try
- {
+ try {
blockUntilCacheStarts();
return true;
}
- catch (InterruptedException e)
- {
+ catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
- }
- else
- {
+ } else {
log.warn("Received a remote call but the cache is not in STARTED state - ignoring call.");
}
return false;
@@ -843,20 +749,18 @@
/**
* Blocks until the current cache instance is in its {@link org.horizon.CacheStatus#STARTED started} phase. Blocks
- * for up to {@link Configuration#getStateRetrievalTimeout()} milliseconds, throwing an IllegalStateException
- * if the cache doesn't reach this state even after this maximum wait time.
+ * for up to {@link Configuration#getStateRetrievalTimeout()} milliseconds, throwing an IllegalStateException if the
+ * cache doesn't reach this state even after this maximum wait time.
*
* @throws InterruptedException if interrupted while waiting
* @throws IllegalStateException if even after waiting the cache has not started.
*/
- private void blockUntilCacheStarts() throws InterruptedException, IllegalStateException
- {
+ private void blockUntilCacheStarts() throws InterruptedException, IllegalStateException {
int pollFrequencyMS = 100;
long startupWaitTime = getConfiguration().getStateRetrievalTimeout();
long giveUpTime = System.currentTimeMillis() + startupWaitTime;
- while (System.currentTimeMillis() < giveUpTime)
- {
+ while (System.currentTimeMillis() < giveUpTime) {
if (state.allowInvocations()) break;
Thread.sleep(pollFrequencyMS);
}
@@ -869,8 +773,7 @@
/**
* A wrapper representing a component in the registry
*/
- public class Component
- {
+ public class Component {
/**
* A reference to the object instance for this component.
*/
@@ -893,8 +796,7 @@
boolean nonVolatile;
@Override
- public String toString()
- {
+ public String toString() {
return "Component{" +
"instance=" + instance +
", name=" + name +
@@ -905,18 +807,15 @@
/**
* Injects dependencies into this component.
*/
- public void injectDependencies()
- {
+ public void injectDependencies() {
for (Method m : injectionMethods) invokeInjectionMethod(instance, m);
}
- public Object getInstance()
- {
+ public Object getInstance() {
return instance;
}
- public String getName()
- {
+ public String getName() {
return name;
}
}
@@ -925,25 +824,21 @@
/**
* Wrapper to encapsulate a method along with a priority
*/
- static class PrioritizedMethod implements Comparable<PrioritizedMethod>
- {
+ static class PrioritizedMethod implements Comparable<PrioritizedMethod> {
Method method;
Component component;
int priority;
- public int compareTo(PrioritizedMethod o)
- {
+ public int compareTo(PrioritizedMethod o) {
return (priority < o.priority ? -1 : (priority == o.priority ? 0 : 1));
}
- void invoke()
- {
+ void invoke() {
ReflectionUtil.invokeAccessibly(component.instance, method, null);
}
@Override
- public String toString()
- {
+ public String toString() {
return "PrioritizedMethod{" +
"method=" + method +
", priority=" + priority +
@@ -953,10 +848,10 @@
/**
* Returns an immutable set contating all the components that exists in the reporsitory at this moment.
+ *
* @return a set of components
*/
- public Set<Component> getRegiteredComponents()
- {
+ public Set<Component> getRegiteredComponents() {
HashSet<Component> defensiveCopy = new HashSet<Component>(componentLookup.values());
return Collections.unmodifiableSet(defensiveCopy);
}
Modified: core/branches/flat/src/main/java/org/horizon/factories/BootstrapFactory.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/factories/BootstrapFactory.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/factories/BootstrapFactory.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -35,23 +35,19 @@
*/
@DefaultFactoryFor(classes = {CacheSPI.class, Configuration.class, ComponentRegistry.class})
@NonVolatile
-public class BootstrapFactory extends ComponentFactory
-{
+public class BootstrapFactory extends ComponentFactory {
CacheSPI cacheSPI;
- public BootstrapFactory(CacheSPI cacheSPI, Configuration configuration, ComponentRegistry componentRegistry)
- {
+ public BootstrapFactory(CacheSPI cacheSPI, Configuration configuration, ComponentRegistry componentRegistry) {
super(componentRegistry, configuration);
this.cacheSPI = cacheSPI;
}
@Override
- protected <T> T construct(Class<T> componentType)
- {
+ protected <T> T construct(Class<T> componentType) {
if (componentType.isAssignableFrom(CacheSPI.class) ||
componentType.isAssignableFrom(Configuration.class) ||
- componentType.isAssignableFrom(ComponentRegistry.class))
- {
+ componentType.isAssignableFrom(ComponentRegistry.class)) {
return componentType.cast(cacheSPI);
}
Modified: core/branches/flat/src/main/java/org/horizon/factories/ComponentFactory.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/factories/ComponentFactory.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/factories/ComponentFactory.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -32,9 +32,9 @@
/**
* Factory that creates components used internally within JBoss Cache, and also wires dependencies into the components.
* <p/>
- * The {@link DefaultCacheFactory} is a special subclass of this, which bootstraps the construction of
- * other components. When this class is loaded, it maintains a static list of known default factories for known
- * components, which it then delegates to, when actually performing the construction.
+ * The {@link DefaultCacheFactory} is a special subclass of this, which bootstraps the construction of other components.
+ * When this class is loaded, it maintains a static list of known default factories for known components, which it then
+ * delegates to, when actually performing the construction.
* <p/>
*
* @author Manik Surtani (<a href="mailto:manik at jboss.org">manik at jboss.org</a>)
@@ -43,8 +43,7 @@
* @since 1.0
*/
@Scope(Scopes.NAMED_CACHE)
-public abstract class ComponentFactory
-{
+public abstract class ComponentFactory {
protected final Log log = LogFactory.getLog(getClass());
protected ComponentRegistry componentRegistry;
protected Configuration configuration;
@@ -52,8 +51,7 @@
/**
* Constructs a new ComponentFactory.
*/
- public ComponentFactory(ComponentRegistry componentRegistry, Configuration configuration)
- {
+ public ComponentFactory(ComponentRegistry componentRegistry, Configuration configuration) {
this.componentRegistry = componentRegistry;
this.configuration = configuration;
}
@@ -61,13 +59,11 @@
/**
* Constructs a new ComponentFactory.
*/
- public ComponentFactory()
- {
+ public ComponentFactory() {
}
@Inject
- private void injectDependencies(Configuration configuration, ComponentRegistry componentRegistry)
- {
+ private void injectDependencies(Configuration configuration, ComponentRegistry componentRegistry) {
this.configuration = configuration;
this.componentRegistry = componentRegistry;
}
@@ -80,11 +76,9 @@
*/
protected abstract <T> T construct(Class<T> componentType);
- protected void assertTypeConstructable(Class requestedType, Class... ableToConstruct)
- {
+ protected void assertTypeConstructable(Class requestedType, Class... ableToConstruct) {
boolean canConstruct = false;
- for (Class c : ableToConstruct)
- {
+ for (Class c : ableToConstruct) {
canConstruct = canConstruct || requestedType.isAssignableFrom(c);
}
if (!canConstruct) throw new ConfigurationException("Don't know how to construct " + requestedType);
Modified: core/branches/flat/src/main/java/org/horizon/factories/ComponentRegistry.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/factories/ComponentRegistry.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/factories/ComponentRegistry.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -14,8 +14,7 @@
* @author Manik Surtani
* @since 1.0
*/
-public class ComponentRegistry extends AbstractComponentRegistry
-{
+public class ComponentRegistry extends AbstractComponentRegistry {
GlobalComponentRegistry globalComponents;
/**
@@ -25,11 +24,9 @@
* @param cache cache
* @param globalComponents Shared Component Registry to delegate to
*/
- public ComponentRegistry(Configuration configuration, CacheSPI cache, GlobalComponentRegistry globalComponents)
- {
+ public ComponentRegistry(Configuration configuration, CacheSPI cache, GlobalComponentRegistry globalComponents) {
- try
- {
+ try {
registerDefaultClassLoader(null);
registerComponent(this, ComponentRegistry.class);
registerComponent(configuration, Configuration.class);
@@ -37,8 +34,7 @@
this.globalComponents = globalComponents;
}
- catch (Exception e)
- {
+ catch (Exception e) {
throw new CacheException("Unable to construct a ComponentRegistry!", e);
}
}
@@ -48,10 +44,10 @@
* typically called by bootstrap code. Defensively, it is called in the constructor of ComponentRegistry with a null
* parameter.
*
- * @param loader a class loader to use by default. If this is null, the class loader used to load this instance of ComponentRegistry is used.
+ * @param loader a class loader to use by default. If this is null, the class loader used to load this instance of
+ * ComponentRegistry is used.
*/
- public void registerDefaultClassLoader(ClassLoader loader)
- {
+ public void registerDefaultClassLoader(ClassLoader loader) {
registerComponent(loader == null ? getClass().getClassLoader() : loader, ClassLoader.class);
// make sure the class loader is non-volatile, so it survives restarts.
componentLookup.get(ClassLoader.class.getName()).nonVolatile = true;
@@ -59,12 +55,10 @@
@Override
- public <T> T getComponent(Class<T> componentType)
- {
+ public <T> T getComponent(Class<T> componentType) {
// first try in the local registry
Scopes componentScope = ScopeDetector.detectScope(componentType);
- switch (componentScope)
- {
+ switch (componentScope) {
case GLOBAL:
return globalComponents.getComponent(componentType);
case NAMED_CACHE:
@@ -75,20 +69,17 @@
}
@Override
- protected Map<Class, Class<? extends ComponentFactory>> getDefaultFactoryMap()
- {
+ protected Map<Class, Class<? extends ComponentFactory>> getDefaultFactoryMap() {
// delegate to parent. No sense maintaining multiple copies of this map.
return globalComponents.getDefaultFactoryMap();
}
@Override
- protected ComponentFactory getFactory(Class componentClass)
- {
+ protected ComponentFactory getFactory(Class componentClass) {
return super.getFactory(componentClass);
}
- public GlobalComponentRegistry getSharedComponentRegistry()
- {
+ public GlobalComponentRegistry getSharedComponentRegistry() {
return globalComponents;
}
}
Modified: core/branches/flat/src/main/java/org/horizon/factories/DataContainerFactory.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/factories/DataContainerFactory.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/factories/DataContainerFactory.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -32,10 +32,8 @@
* @since 1.0
*/
@DefaultFactoryFor(classes = DataContainer.class)
-public class DataContainerFactory extends ComponentFactory
-{
- protected <T> T construct(Class<T> componentType)
- {
+public class DataContainerFactory extends ComponentFactory {
+ protected <T> T construct(Class<T> componentType) {
return (T) new UnsortedDataContainer();
}
}
Modified: core/branches/flat/src/main/java/org/horizon/factories/DefaultCacheFactory.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/factories/DefaultCacheFactory.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/factories/DefaultCacheFactory.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -21,19 +21,19 @@
*/
package org.horizon.factories;
-import org.horizon.jmx.PlatformMBeanServerRegistration;
import org.horizon.Cache;
import org.horizon.CacheDelegate;
import org.horizon.CacheSPI;
import org.horizon.config.Configuration;
import org.horizon.config.ConfigurationException;
+import org.horizon.jmx.PlatformMBeanServerRegistration;
import org.horizon.manager.CacheManager;
/**
* Default implementation of the {@link CacheFactory} interface.
* <p/>
- * This is a special instance of a {@link ComponentFactory} which contains bootstrap information for the
- * {@link ComponentRegistry}.
+ * This is a special instance of a {@link ComponentFactory} which contains bootstrap information for the {@link
+ * ComponentRegistry}.
* <p/>
*
* @author <a href="mailto:manik at jboss.org">Manik Surtani (manik at jboss.org)</a>
@@ -52,35 +52,28 @@
* @return a cache
* @throws ConfigurationException if there are problems with the cfg
*/
- public Cache<K, V> createCache(Configuration configuration, GlobalComponentRegistry globalComponentRegistry, String cacheName) throws ConfigurationException
- {
- try
- {
+ public Cache<K, V> createCache(Configuration configuration, GlobalComponentRegistry globalComponentRegistry, String cacheName) throws ConfigurationException {
+ try {
CacheSPI<K, V> cache = createAndWire(configuration, globalComponentRegistry, cacheName);
cache.start();
return cache;
}
- catch (ConfigurationException ce)
- {
+ catch (ConfigurationException ce) {
throw ce;
}
- catch (RuntimeException re)
- {
+ catch (RuntimeException re) {
throw re;
}
- catch (Exception e)
- {
+ catch (Exception e) {
throw new RuntimeException(e);
}
}
- public Cache<K, V> createDefaultCache(Configuration configuration) throws ConfigurationException
- {
+ public Cache<K, V> createDefaultCache(Configuration configuration) throws ConfigurationException {
return createCache(configuration, null, CacheManager.DEFAULT_CACHE_NAME);
}
- protected CacheSPI<K, V> createAndWire(Configuration configuration, GlobalComponentRegistry globalComponentRegistry, String cacheName) throws Exception
- {
+ protected CacheSPI<K, V> createAndWire(Configuration configuration, GlobalComponentRegistry globalComponentRegistry, String cacheName) throws Exception {
CacheSPI<K, V> spi = new CacheDelegate<K, V>(cacheName);
bootstrap(spi, configuration, globalComponentRegistry);
return spi;
@@ -89,8 +82,7 @@
/**
* Bootstraps this factory with a Configuration and a ComponentRegistry.
*/
- private void bootstrap(CacheSPI spi, Configuration configuration, GlobalComponentRegistry globalComponentRegistry)
- {
+ private void bootstrap(CacheSPI spi, Configuration configuration, GlobalComponentRegistry globalComponentRegistry) {
this.configuration = configuration;
// injection bootstrap stuff
@@ -105,14 +97,12 @@
*
* @param loader class loader to use as a default.
*/
- public void setDefaultClassLoader(ClassLoader loader)
- {
+ public void setDefaultClassLoader(ClassLoader loader) {
this.defaultClassLoader = loader;
}
@Override
- protected <T> T construct(Class<T> componentType)
- {
+ protected <T> T construct(Class<T> componentType) {
throw new UnsupportedOperationException("Should never be invoked - this is a bootstrap factory.");
}
}
Modified: core/branches/flat/src/main/java/org/horizon/factories/EmptyConstructorFactory.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/factories/EmptyConstructorFactory.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/factories/EmptyConstructorFactory.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -44,40 +44,28 @@
* @since 1.0
*/
@DefaultFactoryFor(classes = {Notifier.class,
- ChannelMessageListener.class, CacheLoaderManager.class, Marshaller.class, InvocationContextContainer.class,
- TransactionTable.class, BatchContainer.class, ContextFactory.class, EntryFactory.class, CommandsFactory.class})
-public class EmptyConstructorFactory extends ComponentFactory
-{
+ ChannelMessageListener.class, CacheLoaderManager.class, Marshaller.class, InvocationContextContainer.class,
+ TransactionTable.class, BatchContainer.class, ContextFactory.class, EntryFactory.class, CommandsFactory.class})
+public class EmptyConstructorFactory extends ComponentFactory {
@Override
- protected <T> T construct(Class<T> componentType)
- {
- try
- {
- if (componentType.isInterface())
- {
+ protected <T> T construct(Class<T> componentType) {
+ try {
+ if (componentType.isInterface()) {
Class componentImpl;
- if (componentType.equals(Marshaller.class))
- {
+ if (componentType.equals(Marshaller.class)) {
componentImpl = VersionAwareMarshaller.class;
- }
- else if (componentType.equals(RPCManager.class))
- {
+ } else if (componentType.equals(RPCManager.class)) {
componentImpl = RPCManagerImpl.class;
- }
- else
- {
+ } else {
// add an "Impl" to the end of the class name and try again
componentImpl = getClass().getClassLoader().loadClass(componentType.getName() + "Impl");
}
return componentType.cast(componentImpl.newInstance());
- }
- else
- {
+ } else {
return componentType.newInstance();
}
}
- catch (Exception e)
- {
+ catch (Exception e) {
throw new ConfigurationException("Unable to create component " + componentType, e);
}
}
Modified: core/branches/flat/src/main/java/org/horizon/factories/EntryFactory.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/factories/EntryFactory.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/factories/EntryFactory.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -31,8 +31,7 @@
* @author Manik Surtani (<a href="mailto:manik at jboss.org">manik at jboss.org</a>)
* @since 1.0
*/
-public interface EntryFactory
-{
+public interface EntryFactory {
void releaseLock(Object key);
/**
@@ -40,7 +39,8 @@
*
* @param ctx context
* @param key Key to lock
- * @return true if a lock was needed and acquired, false if it didn't need to acquire the lock (i.e., lock was already held)
+ * @return true if a lock was needed and acquired, false if it didn't need to acquire the lock (i.e., lock was
+ * already held)
* @throws InterruptedException if interrupted
* @throws org.horizon.lock.TimeoutException
* if we are unable to acquire the lock after a specified timeout.
Modified: core/branches/flat/src/main/java/org/horizon/factories/EntryFactoryImpl.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/factories/EntryFactoryImpl.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/factories/EntryFactoryImpl.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -23,7 +23,6 @@
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
-import org.horizon.lock.IsolationLevel;
import org.horizon.config.Configuration;
import org.horizon.container.DataContainer;
import org.horizon.container.MVCCEntry;
@@ -33,6 +32,7 @@
import org.horizon.context.InvocationContext;
import org.horizon.factories.annotations.Inject;
import org.horizon.factories.annotations.Start;
+import org.horizon.lock.IsolationLevel;
import org.horizon.lock.LockManager;
import org.horizon.lock.TimeoutException;
import org.horizon.notifications.Notifier;
@@ -43,8 +43,7 @@
* @author Manik Surtani (<a href="mailto:manik at jboss.org">manik at jboss.org</a>)
* @since 1.0
*/
-public class EntryFactoryImpl implements EntryFactory
-{
+public class EntryFactoryImpl implements EntryFactory {
private boolean useRepeatableRead;
private static final NullMarkerEntry NULL_MARKER = new NullMarkerEntry();
DataContainer container;
@@ -58,8 +57,7 @@
private static final boolean trace = log.isTraceEnabled();
@Inject
- public void injectDependencies(DataContainer dataContainer, LockManager lockManager, Configuration configuration, Notifier notifier)
- {
+ public void injectDependencies(DataContainer dataContainer, LockManager lockManager, Configuration configuration, Notifier notifier) {
this.container = dataContainer;
this.configuration = configuration;
this.lockManager = lockManager;
@@ -67,79 +65,64 @@
}
@Start
- public void init()
- {
+ public void init() {
useRepeatableRead = configuration.getIsolationLevel() == IsolationLevel.REPEATABLE_READ;
defaultLockAcquisitionTimeout = configuration.getLockAcquisitionTimeout();
writeSkewCheck = configuration.isWriteSkewCheck();
}
- public MVCCEntry createWrappedEntry(Object key, Object value, boolean isForInsert)
- {
+ public MVCCEntry createWrappedEntry(Object key, Object value, boolean isForInsert) {
if (value == null && !isForInsert) return useRepeatableRead ? NULL_MARKER : null;
MVCCEntry mvccEntry = useRepeatableRead ? new RepeatableReadEntry(key, value) : new ReadCommittedEntry(key, value);
return mvccEntry;
}
- public MVCCEntry wrapEntryForReading(InvocationContext ctx, Object key, boolean putInContext) throws InterruptedException
- {
+ public MVCCEntry wrapEntryForReading(InvocationContext ctx, Object key, boolean putInContext) throws InterruptedException {
return wrapEntryForReading(ctx, key, putInContext, false);
}
- public MVCCEntry wrapEntryForReading(InvocationContext ctx, Object key, boolean putInContext, boolean forceWriteLock) throws InterruptedException
- {
+ public MVCCEntry wrapEntryForReading(InvocationContext ctx, Object key, boolean putInContext, boolean forceWriteLock) throws InterruptedException {
// TODO: Do we need to wrap for reading if we are not in a TX?
// TODO: Also, do we need to wrap for reading even IN a TX if we are using read-committed?
MVCCEntry mvccEntry;
- if (forceWriteLock)
- {
+ if (forceWriteLock) {
if (trace) log.trace("Forcing lock on reading");
return wrapEntryForWriting(ctx, key, false, false);
- }
- else if ((mvccEntry = ctx.lookupEntry(key)) == null)
- {
+ } else if ((mvccEntry = ctx.lookupEntry(key)) == null) {
if (trace) log.trace("Key " + key + " is not in context, fetching from container.");
// simple implementation. Peek the node, wrap it, put wrapped node in the context.
Object value = container.get(key);
mvccEntry = createWrappedEntry(key, value, false);
if (mvccEntry != null && putInContext) ctx.putLookedUpEntry(key, mvccEntry);
return mvccEntry;
- }
- else
- {
+ } else {
if (trace) log.trace("Key is already in context");
return mvccEntry;
}
}
- public MVCCEntry wrapEntryForWriting(InvocationContext ctx, Object key, boolean createIfAbsent, boolean forceLockIfAbsent) throws InterruptedException
- {
+ public MVCCEntry wrapEntryForWriting(InvocationContext ctx, Object key, boolean createIfAbsent, boolean forceLockIfAbsent) throws InterruptedException {
MVCCEntry mvccEntry = ctx.lookupEntry(key);
if (createIfAbsent && mvccEntry != null && mvccEntry.isNullEntry()) mvccEntry = null;
if (mvccEntry != null) // exists in context! Just acquire lock if needed, and wrap.
{
// acquire lock if needed
- if (acquireLock(ctx, key))
- {
+ if (acquireLock(ctx, key)) {
// create a copy of the underlying node
mvccEntry.copyForUpdate(container, writeSkewCheck);
}
if (trace) log.trace("Exists in context.");
- if (mvccEntry.isDeleted() && createIfAbsent)
- {
+ if (mvccEntry.isDeleted() && createIfAbsent) {
if (trace) log.trace("Node is deleted in current scope. Need to un-delete.");
mvccEntry.setDeleted(false);
mvccEntry.setValid(true);
}
- }
- else
- {
+ } else {
// else, fetch from dataContainer.
Object value = container.get(key);
- if (value != null)
- {
+ if (value != null) {
if (trace) log.trace("Retrieved from container.");
// exists in cache! Just acquire lock if needed, and wrap.
// do we need a lock?
@@ -148,8 +131,7 @@
mvccEntry = createWrappedEntry(key, value, false);
ctx.putLookedUpEntry(key, mvccEntry);
if (needToCopy) mvccEntry.copyForUpdate(container, writeSkewCheck);
- }
- else if (createIfAbsent) // else, do we need to create one?
+ } else if (createIfAbsent) // else, do we need to create one?
{
// this is the *only* point where new entries can be created!!
if (trace) log.trace("Creating new entry.");
@@ -175,26 +157,22 @@
*
* @param ctx context
* @param key Key to lock
- * @return true if a lock was needed and acquired, false if it didn't need to acquire the lock (i.e., lock was already held)
+ * @return true if a lock was needed and acquired, false if it didn't need to acquire the lock (i.e., lock was
+ * already held)
* @throws InterruptedException if interrupted
* @throws org.horizon.lock.TimeoutException
* if we are unable to acquire the lock after a specified timeout.
*/
- public boolean acquireLock(InvocationContext ctx, Object key) throws InterruptedException, TimeoutException
- {
+ public boolean acquireLock(InvocationContext ctx, Object key) throws InterruptedException, TimeoutException {
// don't EVER use lockManager.isLocked() since with lock striping it may be the case that we hold the relevant
// lock which may be shared with another Fqn that we have a lock for already.
// nothing wrong, just means that we fail to record the lock. And that is a problem.
// Better to check our records and lock again if necessary.
- if (!ctx.hasLockedKey(key))
- {
- if (ctx.getOptionOverrides().isSuppressLocking())
- {
+ if (!ctx.hasLockedKey(key)) {
+ if (ctx.getOptionOverrides().isSuppressLocking()) {
// just record this in the ctx and rtn
ctx.addKeyLocked(key);
- }
- else if (!lockManager.lockAndRecord(key, ctx))
- {
+ } else if (!lockManager.lockAndRecord(key, ctx)) {
Object owner = lockManager.getOwner(key);
throw new TimeoutException("Unable to acquire lock on key [" + key + "] after [" + ctx.getLockAcquisitionTimeout(defaultLockAcquisitionTimeout) + "] milliseconds for requestor [" + lockManager.getLockOwner(ctx) + "]! Lock held by [" + owner + "]");
}
@@ -203,8 +181,7 @@
return false;
}
- public void releaseLock(Object key)
- {
+ public void releaseLock(Object key) {
lockManager.unlock(key, lockManager.getOwner(key));
}
}
Modified: core/branches/flat/src/main/java/org/horizon/factories/EvictionManagerFactory.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/factories/EvictionManagerFactory.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/factories/EvictionManagerFactory.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -9,21 +9,16 @@
* @since 1.0
*/
@DefaultFactoryFor(classes = {EvictionManager.class})
-public class EvictionManagerFactory extends ComponentFactory
-{
- protected <T> T construct(Class<T> componentType)
- {
- if (componentType != EvictionManager.class)
- {
+public class EvictionManagerFactory extends ComponentFactory {
+ protected <T> T construct(Class<T> componentType) {
+ if (componentType != EvictionManager.class) {
throw new IllegalStateException();
}
EvictionManagerImpl evManager = new EvictionManagerImpl();
- if (configuration.getEvictionConfig() != null)
- {
+ if (configuration.getEvictionConfig() != null) {
long wakeupInterval = configuration.getEvictionConfig().getWakeupInterval();
evManager.configureEvictionThread(wakeupInterval, configuration.getRuntimeConfig().getEvictionTimerThreadFactory());
return (T) evManager;
- }
- else return null;
+ } else return null;
}
}
Modified: core/branches/flat/src/main/java/org/horizon/factories/GlobalComponentRegistry.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/factories/GlobalComponentRegistry.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/factories/GlobalComponentRegistry.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -9,22 +9,18 @@
* @author Manik Surtani
* @since 1.0
*/
-public class GlobalComponentRegistry extends AbstractComponentRegistry
-{
+public class GlobalComponentRegistry extends AbstractComponentRegistry {
/**
* Creates an instance of the component registry. The configuration passed in is automatically registered.
*
* @param configuration configuration with which this is created
*/
- public GlobalComponentRegistry(GlobalConfiguration configuration)
- {
- try
- {
+ public GlobalComponentRegistry(GlobalConfiguration configuration) {
+ try {
registerComponent(configuration, GlobalConfiguration.class);
registerComponent(this, GlobalComponentRegistry.class);
}
- catch (Exception e)
- {
+ catch (Exception e) {
throw new CacheException("Unable to construct a GlobalComponentRegistry!", e);
}
}
Modified: core/branches/flat/src/main/java/org/horizon/factories/InterceptorChainFactory.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/factories/InterceptorChainFactory.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/factories/InterceptorChainFactory.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -22,17 +22,17 @@
package org.horizon.factories;
+import org.horizon.CacheSPI;
+import org.horizon.EvictionManager;
import org.horizon.config.Configuration;
import org.horizon.config.ConfigurationException;
import org.horizon.config.CustomInterceptorConfig;
import org.horizon.config.EvictionCacheConfig;
+import org.horizon.eviction.EvictionCacheManager;
+import org.horizon.eviction.EvictionCacheManagerImpl;
import org.horizon.factories.annotations.DefaultFactoryFor;
import org.horizon.interceptors.*;
import org.horizon.interceptors.base.CommandInterceptor;
-import org.horizon.eviction.EvictionCacheManager;
-import org.horizon.eviction.EvictionCacheManagerImpl;
-import org.horizon.CacheSPI;
-import org.horizon.EvictionManager;
import java.util.List;
@@ -43,34 +43,26 @@
* @since 1.0
*/
@DefaultFactoryFor(classes = InterceptorChain.class)
-public class InterceptorChainFactory extends ComponentFactory
-{
- private CommandInterceptor createInterceptor(Class<? extends CommandInterceptor> clazz) throws IllegalAccessException, InstantiationException
- {
+public class InterceptorChainFactory extends ComponentFactory {
+ private CommandInterceptor createInterceptor(Class<? extends CommandInterceptor> clazz) throws IllegalAccessException, InstantiationException {
CommandInterceptor chainedInterceptor = componentRegistry.getComponent(clazz);
- if (chainedInterceptor == null)
- {
+ if (chainedInterceptor == null) {
chainedInterceptor = clazz.newInstance();
- try
- {
+ try {
componentRegistry.registerComponent(chainedInterceptor, clazz);
}
- catch (RuntimeException e)
- {
+ catch (RuntimeException e) {
log.warn("Problems creating interceptor " + clazz);
throw e;
}
- }
- else
- {
+ } else {
// wipe next/last chaining!!
chainedInterceptor.setNext(null);
}
return chainedInterceptor;
}
- public InterceptorChain buildInterceptorChain() throws IllegalAccessException, InstantiationException, ClassNotFoundException
- {
+ public InterceptorChain buildInterceptorChain() throws IllegalAccessException, InstantiationException, ClassNotFoundException {
boolean invocationBatching = configuration.isInvocationBatchingEnabled();
// load the icInterceptor first
@@ -98,8 +90,7 @@
interceptorChain.appendIntereceptor(createInterceptor(NotificationInterceptor.class));
// TODO: Uncomment once the Repl and Inval interceptors has been moved to Starobrno
- switch (configuration.getCacheMode())
- {
+ switch (configuration.getCacheMode()) {
case REPL_SYNC:
case REPL_ASYNC:
interceptorChain.appendIntereceptor(createInterceptor(ReplicationInterceptor.class));
@@ -113,8 +104,7 @@
}
// TODO: Uncomment once the CacheLoader has been moved to Starobrno
- if (configuration.isUsingCacheLoaders())
- {
+ if (configuration.isUsingCacheLoaders()) {
// if (configuration.getCacheLoaderConfig().isPassivation())
// {
// interceptorChain.appendIntereceptor(createInterceptor(ActivationInterceptor.class));
@@ -127,8 +117,7 @@
interceptorChain.appendIntereceptor(createInterceptor(LockingInterceptor.class));
// TODO: Uncomment once the CacheLoader has been moved to Starobrno
- if (configuration.isUsingCacheLoaders())
- {
+ if (configuration.isUsingCacheLoaders()) {
// if (configuration.getCacheLoaderConfig().isPassivation())
// {
//
@@ -150,8 +139,7 @@
//
// }
- if (configuration.isUsingEviction())
- {
+ if (configuration.isUsingEviction()) {
EvictionInterceptor evictionInterceptor = (EvictionInterceptor) createInterceptor(EvictionInterceptor.class);
interceptorChain.appendIntereceptor(evictionInterceptor);
EvictionCacheConfig ecc = configuration.getEvictionCacheConfig("bla");
@@ -169,32 +157,25 @@
return interceptorChain;
}
- private void buildCustomInterceptors(InterceptorChain interceptorChain, List<CustomInterceptorConfig> customInterceptors)
- {
- for (CustomInterceptorConfig config : customInterceptors)
- {
+ private void buildCustomInterceptors(InterceptorChain interceptorChain, List<CustomInterceptorConfig> customInterceptors) {
+ for (CustomInterceptorConfig config : customInterceptors) {
if (interceptorChain.containsInstance(config.getInterceptor())) continue;
- if (config.isFirst())
- {
+ if (config.isFirst()) {
interceptorChain.addInterceptor(config.getInterceptor(), 0);
}
if (config.isLast()) interceptorChain.appendIntereceptor(config.getInterceptor());
if (config.getIndex() >= 0) interceptorChain.addInterceptor(config.getInterceptor(), config.getIndex());
- if (config.getAfterClass() != null)
- {
+ if (config.getAfterClass() != null) {
List<CommandInterceptor> withClassName = interceptorChain.getInterceptorsWithClassName(config.getAfterClass());
- if (withClassName.isEmpty())
- {
+ if (withClassName.isEmpty()) {
throw new ConfigurationException("Cannot add after class: " + config.getAfterClass()
+ " as no such iterceptor exists in the default chain");
}
interceptorChain.addAfterInterceptor(config.getInterceptor(), withClassName.get(0).getClass());
}
- if (config.getBeforeClass() != null)
- {
+ if (config.getBeforeClass() != null) {
List<CommandInterceptor> withClassName = interceptorChain.getInterceptorsWithClassName(config.getBeforeClass());
- if (withClassName.isEmpty())
- {
+ if (withClassName.isEmpty()) {
throw new ConfigurationException("Cannot add before class: " + config.getAfterClass()
+ " as no such iterceptor exists in the default chain");
}
@@ -204,20 +185,16 @@
}
@Override
- protected <T> T construct(Class<T> componentType)
- {
- try
- {
+ protected <T> T construct(Class<T> componentType) {
+ try {
return componentType.cast(buildInterceptorChain());
}
- catch (Exception e)
- {
+ catch (Exception e) {
throw new ConfigurationException("Unable to build interceptor chain", e);
}
}
- public static InterceptorChainFactory getInstance(ComponentRegistry componentRegistry, Configuration configuration)
- {
+ public static InterceptorChainFactory getInstance(ComponentRegistry componentRegistry, Configuration configuration) {
InterceptorChainFactory icf = new InterceptorChainFactory();
icf.componentRegistry = componentRegistry;
icf.configuration = configuration;
Modified: core/branches/flat/src/main/java/org/horizon/factories/LockManagerFactory.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/factories/LockManagerFactory.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/factories/LockManagerFactory.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -32,10 +32,8 @@
* @since 1.0
*/
@DefaultFactoryFor(classes = LockManager.class)
-public class LockManagerFactory extends ComponentFactory
-{
- protected <T> T construct(Class<T> componentType)
- {
+public class LockManagerFactory extends ComponentFactory {
+ protected <T> T construct(Class<T> componentType) {
return (T) new StripedLockManager();
}
}
Modified: core/branches/flat/src/main/java/org/horizon/factories/ReplicationQueueFactory.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/factories/ReplicationQueueFactory.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/factories/ReplicationQueueFactory.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -32,18 +32,13 @@
* @since 1.0
*/
@DefaultFactoryFor(classes = ReplicationQueue.class)
-public class ReplicationQueueFactory extends EmptyConstructorFactory
-{
+public class ReplicationQueueFactory extends EmptyConstructorFactory {
@Override
- public <T> T construct(Class<T> componentType)
- {
+ public <T> T construct(Class<T> componentType) {
if ((configuration.getCacheMode() == Configuration.CacheMode.REPL_ASYNC || configuration.getCacheMode() == Configuration.CacheMode.INVALIDATION_ASYNC)
- && configuration.isUseReplQueue())
- {
+ && configuration.isUseReplQueue()) {
return super.construct(componentType);
- }
- else
- {
+ } else {
return null;
}
}
Modified: core/branches/flat/src/main/java/org/horizon/factories/RuntimeConfigAwareFactory.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/factories/RuntimeConfigAwareFactory.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/factories/RuntimeConfigAwareFactory.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -36,22 +36,17 @@
* @since 1.0
*/
@DefaultFactoryFor(classes = RPCManager.class)
-public class RuntimeConfigAwareFactory extends EmptyConstructorFactory
-{
+public class RuntimeConfigAwareFactory extends EmptyConstructorFactory {
@Override
- protected <T> T construct(Class<T> componentType)
- {
+ protected <T> T construct(Class<T> componentType) {
T component = super.construct(componentType);
Method setter = BeanUtils.setterMethod(RuntimeConfig.class, componentType);
- if (setter != null)
- {
- try
- {
+ if (setter != null) {
+ try {
setter.invoke(configuration.getRuntimeConfig(), component);
}
- catch (Exception e)
- {
+ catch (Exception e) {
throw new ConfigurationException("Unable to put newly constructed component of type " + componentType + " in the RuntimeConfig", e);
}
}
Modified: core/branches/flat/src/main/java/org/horizon/factories/StateTransferFactory.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/factories/StateTransferFactory.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/factories/StateTransferFactory.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -22,24 +22,20 @@
package org.horizon.factories;
/**
- * Factory class able to create {@link StateTransferGenerator} and
- * {@link StateTransferIntegrator} instances.
+ * Factory class able to create {@link StateTransferGenerator} and {@link StateTransferIntegrator} instances.
* <p/>
* Updated in 3.0.0 to extend ComponentFactory, etc.
* <p/>
*
* @author <a href="brian.stansberry at jboss.com">Brian Stansberry</a>
* @author Manik Surtani
- *
* @since 1.0
*/
// TODO: Implement me
//@DefaultFactoryFor(classes = {StateTransferGenerator.class, StateTransferIntegrator.class})
-public class StateTransferFactory extends ComponentFactory
-{
+public class StateTransferFactory extends ComponentFactory {
@SuppressWarnings("deprecation")
- protected <T> T construct(Class<T> componentType)
- {
+ protected <T> T construct(Class<T> componentType) {
return null;
// if (componentType.equals(StateTransferIntegrator.class))
// {
Modified: core/branches/flat/src/main/java/org/horizon/factories/StateTransferManagerFactory.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/factories/StateTransferManagerFactory.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/factories/StateTransferManagerFactory.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -21,9 +21,9 @@
*/
package org.horizon.factories;
+import org.horizon.factories.annotations.DefaultFactoryFor;
import org.horizon.statetransfer.DefaultStateTransferManager;
import org.horizon.statetransfer.StateTransferManager;
-import org.horizon.factories.annotations.DefaultFactoryFor;
/**
* Constructs {@link org.horizon.statetransfer.StateTransferManager} instances.
@@ -32,11 +32,9 @@
* @since 1.0
*/
@DefaultFactoryFor(classes = StateTransferManager.class)
-public class StateTransferManagerFactory extends ComponentFactory
-{
+public class StateTransferManagerFactory extends ComponentFactory {
@SuppressWarnings("deprecation")
- protected <T> T construct(Class<T> componentType)
- {
+ protected <T> T construct(Class<T> componentType) {
return componentType.cast(new DefaultStateTransferManager());
}
}
Modified: core/branches/flat/src/main/java/org/horizon/factories/TransactionManagerFactory.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/factories/TransactionManagerFactory.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/factories/TransactionManagerFactory.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -35,48 +35,38 @@
* @since 1.0
*/
@DefaultFactoryFor(classes = {TransactionManager.class})
-public class TransactionManagerFactory extends ComponentFactory
-{
- protected <T> T construct(Class<T> componentType)
- {
+public class TransactionManagerFactory extends ComponentFactory {
+ protected <T> T construct(Class<T> componentType) {
// See if we had a TransactionManager injected into our config
TransactionManager transactionManager = configuration.getRuntimeConfig().getTransactionManager();
TransactionManagerLookup lookup = null;
- if (transactionManager == null)
- {
+ if (transactionManager == null) {
// Nope. See if we can look it up from JNDI
- if (configuration.getTransactionManagerLookupClass() != null)
- {
- try
- {
+ if (configuration.getTransactionManagerLookupClass() != null) {
+ try {
ClassLoader cl = Thread.currentThread().getContextClassLoader();
if (cl == null) cl = getClass().getClassLoader();
Class clazz = cl.loadClass(configuration.getTransactionManagerLookupClass());
lookup = (TransactionManagerLookup) clazz.newInstance();
}
- catch (Exception e)
- {
+ catch (Exception e) {
throw new ConfigurationException("Problems looking up transaction manager", e);
}
}
- try
- {
- if (lookup != null)
- {
+ try {
+ if (lookup != null) {
transactionManager = lookup.getTransactionManager();
configuration.getRuntimeConfig().setTransactionManager(transactionManager);
}
}
- catch (Exception e)
- {
+ catch (Exception e) {
log.info("failed looking up TransactionManager, will not use transactions", e);
}
}
- if (transactionManager == null && configuration.isInvocationBatchingEnabled())
- {
+ if (transactionManager == null && configuration.isInvocationBatchingEnabled()) {
log.info("Using a batchMode transaction manager");
transactionManager = BatchModeTransactionManager.getInstance();
}
Modified: core/branches/flat/src/main/java/org/horizon/factories/annotations/DefaultFactoryFor.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/factories/annotations/DefaultFactoryFor.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/factories/annotations/DefaultFactoryFor.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -35,8 +35,7 @@
*/
@Target(TYPE)
@Retention(RetentionPolicy.RUNTIME)
-public @interface DefaultFactoryFor
-{
+public @interface DefaultFactoryFor {
/**
* Components that may be constructed by a factory annotated with this annotation.
*
Modified: core/branches/flat/src/main/java/org/horizon/factories/annotations/Destroy.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/factories/annotations/Destroy.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/factories/annotations/Destroy.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -27,8 +27,8 @@
import java.lang.annotation.Target;
/**
- * Method level annotation that indicates a (no-param) method to be called on a component registered in the ComponentRegistry
- * when the cache is destroyed.
+ * Method level annotation that indicates a (no-param) method to be called on a component registered in the
+ * ComponentRegistry when the cache is destroyed.
* <p/>
*
* @author Manik Surtani (<a href="mailto:manik at jboss.org">manik at jboss.org</a>)
@@ -36,11 +36,10 @@
*/
@Target(METHOD)
@Retention(RetentionPolicy.RUNTIME)
-public @interface Destroy
-{
+public @interface Destroy {
/**
- * Optional parameter which defines the order in which this method will be called when the ComponentRegistry moves
- * to the STARTED state. Defaults to 10.
+ * Optional parameter which defines the order in which this method will be called when the ComponentRegistry moves to
+ * the STARTED state. Defaults to 10.
*
* @return execution priority
* @since 1.0
Modified: core/branches/flat/src/main/java/org/horizon/factories/annotations/Inject.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/factories/annotations/Inject.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/factories/annotations/Inject.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -28,9 +28,9 @@
/**
* Used to annotate a method as one that is used to inject a registered component into another component. The component
- * to be constructed must be built using the {@link ComponentFactory#construct(Class)} method, or if your object that needs
- * components injected into it already exists, it can be built using the {@link ComponentRegistry#wireDependencies(Object)}
- * method.
+ * to be constructed must be built using the {@link ComponentFactory#construct(Class)} method, or if your object that
+ * needs components injected into it already exists, it can be built using the {@link
+ * ComponentRegistry#wireDependencies(Object)} method.
* <p/>
* Usage example:
* <pre>
@@ -68,6 +68,5 @@
// only applies to fields.
@Target(ElementType.METHOD)
-public @interface Inject
-{
+public @interface Inject {
}
\ No newline at end of file
Modified: core/branches/flat/src/main/java/org/horizon/factories/annotations/NonVolatile.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/factories/annotations/NonVolatile.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/factories/annotations/NonVolatile.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -28,10 +28,11 @@
/**
* This annotation is used for components that will be registered in the {@link org.horizon.factories.ComponentRegistry},
- * that are resilient to changes in configuration. Examples are the {@link org.horizon.CacheSPI} implementation used, which does
- * not change regardless of the configuration. Components such as the {@link org.horizon.lock.LockManager}, though, should
- * <b>never</b> be marked as <tt>@NonVolatile</tt> since based on the configuration, different lock manager implementations
- * may be selected. LockManager is, hence, <b>not</b> resilient to changes in the configuration.
+ * that are resilient to changes in configuration. Examples are the {@link org.horizon.CacheSPI} implementation used,
+ * which does not change regardless of the configuration. Components such as the {@link org.horizon.lock.LockManager},
+ * though, should <b>never</b> be marked as <tt>@NonVolatile</tt> since based on the configuration, different lock
+ * manager implementations may be selected. LockManager is, hence, <b>not</b> resilient to changes in the
+ * configuration.
*
* @author Manik Surtani (<a href="mailto:manik at jboss.org">manik at jboss.org</a>)
* @since 1.0
@@ -41,6 +42,5 @@
// only applies to classes.
@Target(ElementType.TYPE)
-public @interface NonVolatile
-{
+public @interface NonVolatile {
}
\ No newline at end of file
Modified: core/branches/flat/src/main/java/org/horizon/factories/annotations/Start.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/factories/annotations/Start.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/factories/annotations/Start.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -27,8 +27,8 @@
import java.lang.annotation.Target;
/**
- * Method level annotation that indicates a (no-param) method to be called on a component registered in the ComponentRegistry
- * when the cache starts.
+ * Method level annotation that indicates a (no-param) method to be called on a component registered in the
+ * ComponentRegistry when the cache starts.
* <p/>
*
* @author Manik Surtani (<a href="mailto:manik at jboss.org">manik at jboss.org</a>)
@@ -36,11 +36,10 @@
*/
@Target(METHOD)
@Retention(RetentionPolicy.RUNTIME)
-public @interface Start
-{
+public @interface Start {
/**
- * Optional parameter which defines the order in which this method will be called when the ComponentRegistry moves
- * to the STARTED state. Defaults to 10.
+ * Optional parameter which defines the order in which this method will be called when the ComponentRegistry moves to
+ * the STARTED state. Defaults to 10.
*
* @return execution priority
* @since 1.0
Modified: core/branches/flat/src/main/java/org/horizon/factories/annotations/Stop.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/factories/annotations/Stop.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/factories/annotations/Stop.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -27,8 +27,8 @@
import java.lang.annotation.Target;
/**
- * Method level annotation that indicates a (no-param) method to be called on a component registered in the ComponentRegistry
- * when the cache stops.
+ * Method level annotation that indicates a (no-param) method to be called on a component registered in the
+ * ComponentRegistry when the cache stops.
* <p/>
*
* @author Manik Surtani (<a href="mailto:manik at jboss.org">manik at jboss.org</a>)
@@ -36,11 +36,10 @@
*/
@Target(METHOD)
@Retention(RetentionPolicy.RUNTIME)
-public @interface Stop
-{
+public @interface Stop {
/**
- * Optional parameter which defines the order in which this method will be called when the ComponentRegistry moves
- * to the STARTED state. Defaults to 10.
+ * Optional parameter which defines the order in which this method will be called when the ComponentRegistry moves to
+ * the STARTED state. Defaults to 10.
*
* @return execution priority
* @since 1.0
Modified: core/branches/flat/src/main/java/org/horizon/factories/context/ContextFactory.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/factories/context/ContextFactory.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/factories/context/ContextFactory.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -31,19 +31,17 @@
import javax.transaction.Transaction;
/**
- * This is the factory responsible for creating {@link InvocationContext}s and {@link TransactionContext}s
- * for requests, based on the configuration used.
+ * This is the factory responsible for creating {@link InvocationContext}s and {@link TransactionContext}s for requests,
+ * based on the configuration used.
*
* @author Manik Surtani (<a href="mailto:manik at jboss.org">manik at jboss.org</a>)
* @since 1.0
*/
-public class ContextFactory
-{
+public class ContextFactory {
/**
* @return a new invocation context
*/
- public InvocationContext createInvocationContext()
- {
+ public InvocationContext createInvocationContext() {
return new InvocationContextImpl();
}
@@ -55,8 +53,7 @@
* @throws javax.transaction.SystemException
* in the event of an invalid transaction
*/
- public TransactionContext createTransactionContext(Transaction tx) throws SystemException, RollbackException
- {
+ public TransactionContext createTransactionContext(Transaction tx) throws SystemException, RollbackException {
return new TransactionContextImpl(tx);
}
}
\ No newline at end of file
Modified: core/branches/flat/src/main/java/org/horizon/factories/scopes/Scope.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/factories/scopes/Scope.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/factories/scopes/Scope.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -4,14 +4,14 @@
import java.lang.annotation.RetentionPolicy;
/**
- * Defines the scope of a component in a cache system. If not specified, components default to the {@link Scopes#EITHER} scope.
+ * Defines the scope of a component in a cache system. If not specified, components default to the {@link
+ * Scopes#EITHER} scope.
*
* @author Manik Surtani
* @see Scopes
* @since 1.0
*/
@Retention(RetentionPolicy.RUNTIME)
-public @interface Scope
-{
+public @interface Scope {
Scopes value();
}
Modified: core/branches/flat/src/main/java/org/horizon/factories/scopes/ScopeDetector.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/factories/scopes/ScopeDetector.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/factories/scopes/ScopeDetector.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -8,10 +8,8 @@
* @author Manik Surtani
* @since 1.0
*/
-public class ScopeDetector
-{
- public static Scopes detectScope(Class clazz)
- {
+public class ScopeDetector {
+ public static Scopes detectScope(Class clazz) {
Scope s = ReflectionUtil.getAnnotation(clazz, Scope.class);
if (s == null)
return Scopes.getDefaultScope();
Modified: core/branches/flat/src/main/java/org/horizon/factories/scopes/Scopes.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/factories/scopes/Scopes.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/factories/scopes/Scopes.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -8,22 +8,20 @@
* @see Scope
* @since 1.0
*/
-public enum Scopes
-{
+public enum Scopes {
/**
- * Components bounded to this scope can only be created by a {@link org.horizon.manager.CacheManager} and exist in the
- * {@link org.horizon.manager.CacheManager}'s {@link org.horizon.factories.ComponentRegistry}.
+ * Components bounded to this scope can only be created by a {@link org.horizon.manager.CacheManager} and exist in
+ * the {@link org.horizon.manager.CacheManager}'s {@link org.horizon.factories.ComponentRegistry}.
*/
GLOBAL,
/**
- * Components bounded to this scope can only be created by a {@link org.horizon.Cache} and exist in the
- * {@link org.horizon.Cache}'s {@link org.horizon.factories.ComponentRegistry}.
+ * Components bounded to this scope can only be created by a {@link org.horizon.Cache} and exist in the {@link
+ * org.horizon.Cache}'s {@link org.horizon.factories.ComponentRegistry}.
*/
NAMED_CACHE;
- public static Scopes getDefaultScope()
- {
+ public static Scopes getDefaultScope() {
return NAMED_CACHE;
}
}
Modified: core/branches/flat/src/main/java/org/horizon/interceptors/BaseTransactionalContextInterceptor.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/interceptors/BaseTransactionalContextInterceptor.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/interceptors/BaseTransactionalContextInterceptor.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -34,46 +34,37 @@
import javax.transaction.TransactionManager;
/**
- * Class providing some base functionality around manipulating transactions and global transactions withing invocation contexts.
+ * Class providing some base functionality around manipulating transactions and global transactions withing invocation
+ * contexts.
*
* @author <a href="mailto:manik at jboss.org">Manik Surtani</a>
* @since 1.0
*/
-public abstract class BaseTransactionalContextInterceptor extends CommandInterceptor
-{
+public abstract class BaseTransactionalContextInterceptor extends CommandInterceptor {
protected TransactionTable txTable;
protected TransactionManager txManager;
@Inject
- public void injectDependencies(TransactionTable txTable, TransactionManager txManager)
- {
+ public void injectDependencies(TransactionTable txTable, TransactionManager txManager) {
this.txManager = txManager;
this.txTable = txTable;
}
- protected void setTransactionalContext(Transaction tx, GlobalTransaction gtx, TransactionContext tCtx, InvocationContext ctx)
- {
- if (trace)
- {
+ protected void setTransactionalContext(Transaction tx, GlobalTransaction gtx, TransactionContext tCtx, InvocationContext ctx) {
+ if (trace) {
log.trace("Setting up transactional context.");
log.trace("Setting tx as " + tx + " and gtx as " + gtx);
}
ctx.setTransaction(tx);
ctx.setGlobalTransaction(gtx);
- if (tCtx == null)
- {
- if (gtx != null)
- {
+ if (tCtx == null) {
+ if (gtx != null) {
ctx.setTransactionContext(txTable.getTransactionContext(gtx));
- }
- else if (tx == null)
- {
+ } else if (tx == null) {
// then nullify the transaction tCtx as well
ctx.setTransactionContext(null);
}
- }
- else
- {
+ } else {
ctx.setTransactionContext(tCtx);
}
}
@@ -81,17 +72,14 @@
/**
* Returns true if transaction is rolling back, false otherwise
*/
- protected boolean isRollingBack(Transaction tx)
- {
+ protected boolean isRollingBack(Transaction tx) {
if (tx == null) return false;
int status;
- try
- {
+ try {
status = tx.getStatus();
return status == Status.STATUS_ROLLING_BACK || status == Status.STATUS_ROLLEDBACK;
}
- catch (SystemException e)
- {
+ catch (SystemException e) {
log.error("failed getting transaction status", e);
return false;
}
Modified: core/branches/flat/src/main/java/org/horizon/interceptors/BatchingInterceptor.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/interceptors/BatchingInterceptor.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/interceptors/BatchingInterceptor.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -36,42 +36,33 @@
* @author Manik Surtani (<a href="mailto:manik at jboss.org">manik at jboss.org</a>)
* @since 1.0
*/
-public class BatchingInterceptor extends CommandInterceptor
-{
+public class BatchingInterceptor extends CommandInterceptor {
BatchContainer batchContainer;
TransactionManager transactionManager;
@Inject
- private void inject(BatchContainer batchContainer, TransactionManager transactionManager)
- {
+ private void inject(BatchContainer batchContainer, TransactionManager transactionManager) {
this.batchContainer = batchContainer;
this.transactionManager = transactionManager;
}
/**
- * Simply check if there is an ongoing tx.
- * <ul>
- * <li>If there is one, this is a no-op and just passes the call up the chain.</li>
- * <li>If there isn't one and there is a batch in progress, resume the batch's tx, pass up, and finally suspend the batch's tx.</li>
- * <li>If there is no batch in progress, just pass the call up the chain.</li>
- * </ul>
+ * Simply check if there is an ongoing tx. <ul> <li>If there is one, this is a no-op and just passes the call up the
+ * chain.</li> <li>If there isn't one and there is a batch in progress, resume the batch's tx, pass up, and finally
+ * suspend the batch's tx.</li> <li>If there is no batch in progress, just pass the call up the chain.</li> </ul>
*/
@Override
- protected Object handleDefault(InvocationContext ctx, VisitableCommand command) throws Throwable
- {
+ protected Object handleDefault(InvocationContext ctx, VisitableCommand command) throws Throwable {
Transaction tx = null;
- try
- {
+ try {
// if in a batch, attach tx
if (transactionManager.getTransaction() == null &&
- (tx = batchContainer.getBatchTransaction()) != null)
- {
+ (tx = batchContainer.getBatchTransaction()) != null) {
transactionManager.resume(tx);
}
return super.handleDefault(ctx, command);
}
- finally
- {
+ finally {
if (tx != null && transactionManager.getTransaction() != null && batchContainer.isSuspendTxAfterInvocation())
transactionManager.suspend();
}
Modified: core/branches/flat/src/main/java/org/horizon/interceptors/CacheLoaderInterceptor.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/interceptors/CacheLoaderInterceptor.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/interceptors/CacheLoaderInterceptor.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -21,6 +21,8 @@
*/
package org.horizon.interceptors;
+import org.horizon.annotations.ManagedAttribute;
+import org.horizon.annotations.ManagedOperation;
import org.horizon.commands.read.GetKeyValueCommand;
import org.horizon.commands.write.PutKeyValueCommand;
import org.horizon.commands.write.RemoveCommand;
@@ -32,8 +34,6 @@
import org.horizon.factories.annotations.Inject;
import org.horizon.factories.annotations.Start;
import org.horizon.interceptors.base.JmxStatsCommandInterceptor;
-import org.horizon.annotations.ManagedAttribute;
-import org.horizon.annotations.ManagedOperation;
import org.horizon.loader.CacheLoader;
import org.horizon.loader.CacheLoaderManager;
import org.horizon.notifications.Notifier;
@@ -46,11 +46,9 @@
* Loads nodes that don't exist at the time of the call into memory from the CacheLoader
*
* @author Bela Ban
- *
* @since 1.0
*/
-public class CacheLoaderInterceptor extends JmxStatsCommandInterceptor
-{
+public class CacheLoaderInterceptor extends JmxStatsCommandInterceptor {
private long cacheLoads = 0;
private long cacheMisses = 0;
private CacheLoaderManager clm;
@@ -66,16 +64,14 @@
/**
- * True if CacheStoreInterceptor is in place.
- * This allows us to skip loading keys for remove(Fqn, key) and put(Fqn, key).
- * It also affects removal of node data and listing children.
+ * True if CacheStoreInterceptor is in place. This allows us to skip loading keys for remove(Fqn, key) and put(Fqn,
+ * key). It also affects removal of node data and listing children.
*/
protected boolean useCacheStore = true;
@Inject
protected void injectDependencies(TransactionTable txTable, CacheLoaderManager clm,
- DataContainer<Object, Object> dataContainer, EntryFactory entryFactory, Notifier notifier)
- {
+ DataContainer<Object, Object> dataContainer, EntryFactory entryFactory, Notifier notifier) {
this.txTable = txTable;
this.clm = clm;
// CacheMode mode = configuration.getCacheMode();
@@ -86,16 +82,13 @@
}
@Start
- protected void startInterceptor()
- {
+ protected void startInterceptor() {
loader = clm.getCacheLoader();
}
@Override
- public Object visitPutKeyValueCommand(InvocationContext ctx, PutKeyValueCommand command) throws Throwable
- {
- if (command.getKey() != null)
- {
+ public Object visitPutKeyValueCommand(InvocationContext ctx, PutKeyValueCommand command) throws Throwable {
+ if (command.getKey() != null) {
loadIfNeeded(ctx, command.getKey());
}
return invokeNextInterceptor(ctx, command);
@@ -103,44 +96,36 @@
@Override
- public Object visitGetKeyValueCommand(InvocationContext ctx, GetKeyValueCommand command) throws Throwable
- {
- if (command.getKey() != null)
- {
+ public Object visitGetKeyValueCommand(InvocationContext ctx, GetKeyValueCommand command) throws Throwable {
+ if (command.getKey() != null) {
loadIfNeeded(ctx, command.getKey());
}
return invokeNextInterceptor(ctx, command);
}
@Override
- public Object visitRemoveCommand(InvocationContext ctx, RemoveCommand command) throws Throwable
- {
- if (command.getKey() != null)
- {
+ public Object visitRemoveCommand(InvocationContext ctx, RemoveCommand command) throws Throwable {
+ if (command.getKey() != null) {
loadIfNeeded(ctx, command.getKey());
}
return invokeNextInterceptor(ctx, command);
}
@Override
- public Object visitReplaceCommand(InvocationContext ctx, ReplaceCommand command) throws Throwable
- {
- if (command.getKey() != null)
- {
+ public Object visitReplaceCommand(InvocationContext ctx, ReplaceCommand command) throws Throwable {
+ if (command.getKey() != null) {
loadIfNeeded(ctx, command.getKey());
}
return invokeNextInterceptor(ctx, command);
}
- private void loadIfNeeded(InvocationContext ctx, Object key) throws Throwable
- {
+ private void loadIfNeeded(InvocationContext ctx, Object key) throws Throwable {
if (dataContainer.containsKey(key) || !loader.exists(key))
return;
// Obtain a temporary lock to verify the key is not being concurrently added
boolean release = entryFactory.acquireLock(ctx, key);
- if (dataContainer.containsKey(key))
- {
+ if (dataContainer.containsKey(key)) {
if (release)
entryFactory.releaseLock(key);
return;
@@ -152,32 +137,25 @@
}
/**
- * Loads a node from disk; if it exists creates parent TreeNodes.
- * If it doesn't exist on disk but in memory, clears the
- * uninitialized flag, otherwise returns null.
+ * Loads a node from disk; if it exists creates parent TreeNodes. If it doesn't exist on disk but in memory, clears
+ * the uninitialized flag, otherwise returns null.
*/
- private MVCCEntry loadEntry(InvocationContext ctx, Object key, MVCCEntry entry) throws Exception
- {
+ private MVCCEntry loadEntry(InvocationContext ctx, Object key, MVCCEntry entry) throws Exception {
if (trace) log.trace("loading entry " + key + " entry is " + entry);
Object value = loader.get(key);
boolean nodeExists = (value != null);
if (trace) log.trace("nodeExists " + nodeExists);
- if (getStatisticsEnabled())
- {
- if (nodeExists)
- {
+ if (getStatisticsEnabled()) {
+ if (nodeExists) {
cacheLoads++;
- }
- else
- {
+ } else {
cacheMisses++;
}
}
- if (value != null)
- {
+ if (value != null) {
if (trace) log.trace("Entry is not null, loading");
// notifier.notifyNodeLoaded(fqn, true, Collections.emptyMap(), ctx);
// if (isActivation)
@@ -199,27 +177,23 @@
}
@ManagedAttribute(description = "number of cache loader node loads")
- public long getCacheLoaderLoads()
- {
+ public long getCacheLoaderLoads() {
return cacheLoads;
}
@ManagedAttribute(description = "number of cache loader node misses")
- public long getCacheLoaderMisses()
- {
+ public long getCacheLoaderMisses() {
return cacheMisses;
}
@ManagedOperation
- public void resetStatistics()
- {
+ public void resetStatistics() {
cacheLoads = 0;
cacheMisses = 0;
}
@ManagedOperation
- public Map<String, Object> dumpStatistics()
- {
+ public Map<String, Object> dumpStatistics() {
Map<String, Object> retval = new HashMap<String, Object>();
retval.put("CacheLoaderLoads", cacheLoads);
retval.put("CacheLoaderMisses", cacheMisses);
Modified: core/branches/flat/src/main/java/org/horizon/interceptors/CacheMgmtInterceptor.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/interceptors/CacheMgmtInterceptor.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/interceptors/CacheMgmtInterceptor.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -21,6 +21,8 @@
*/
package org.horizon.interceptors;
+import org.horizon.annotations.ManagedAttribute;
+import org.horizon.annotations.ManagedOperation;
import org.horizon.commands.read.GetKeyValueCommand;
import org.horizon.commands.write.EvictCommand;
import org.horizon.commands.write.PutKeyValueCommand;
@@ -29,8 +31,6 @@
import org.horizon.context.InvocationContext;
import org.horizon.factories.annotations.Inject;
import org.horizon.interceptors.base.JmxStatsCommandInterceptor;
-import org.horizon.annotations.ManagedAttribute;
-import org.horizon.annotations.ManagedOperation;
import java.util.HashMap;
import java.util.Map;
@@ -39,11 +39,9 @@
* Captures cache management statistics
*
* @author Jerry Gauthier
- *
* @since 1.0
*/
-public class CacheMgmtInterceptor extends JmxStatsCommandInterceptor
-{
+public class CacheMgmtInterceptor extends JmxStatsCommandInterceptor {
private long hitTimes = 0;
private long missTimes = 0;
private long storeTimes = 0;
@@ -57,32 +55,26 @@
private DataContainer dataContainer;
@Inject
- public void setDependencies(DataContainer dataContainer)
- {
+ public void setDependencies(DataContainer dataContainer) {
this.dataContainer = dataContainer;
}
@Override
- public Object visitEvictCommand(InvocationContext ctx, EvictCommand command) throws Throwable
- {
+ public Object visitEvictCommand(InvocationContext ctx, EvictCommand command) throws Throwable {
Object returnValue = invokeNextInterceptor(ctx, command);
evictions++;
return returnValue;
}
@Override
- public Object visitGetKeyValueCommand(InvocationContext ctx, GetKeyValueCommand command) throws Throwable
- {
+ public Object visitGetKeyValueCommand(InvocationContext ctx, GetKeyValueCommand command) throws Throwable {
long t1 = System.currentTimeMillis();
Object retval = invokeNextInterceptor(ctx, command);
long t2 = System.currentTimeMillis();
- if (retval == null)
- {
+ if (retval == null) {
missTimes = missTimes + (t2 - t1);
misses++;
- }
- else
- {
+ } else {
hitTimes = hitTimes + (t2 - t1);
hits++;
}
@@ -90,15 +82,13 @@
}
@Override
- public Object visitPutMapCommand(InvocationContext ctx, PutMapCommand command) throws Throwable
- {
+ public Object visitPutMapCommand(InvocationContext ctx, PutMapCommand command) throws Throwable {
Map data = command.getMap();
long t1 = System.currentTimeMillis();
Object retval = invokeNextInterceptor(ctx, command);
long t2 = System.currentTimeMillis();
- if (data != null && data.size() > 0)
- {
+ if (data != null && data.size() > 0) {
storeTimes = storeTimes + (t2 - t1);
stores = stores + data.size();
}
@@ -106,8 +96,7 @@
}
@Override
- public Object visitPutKeyValueCommand(InvocationContext ctx, PutKeyValueCommand command) throws Throwable
- {
+ public Object visitPutKeyValueCommand(InvocationContext ctx, PutKeyValueCommand command) throws Throwable {
long t1 = System.currentTimeMillis();
Object retval = invokeNextInterceptor(ctx, command);
long t2 = System.currentTimeMillis();
@@ -117,32 +106,27 @@
}
@ManagedAttribute(description = "number of cache attribute hits")
- public long getHits()
- {
+ public long getHits() {
return hits;
}
@ManagedAttribute(description = "number of cache attribute misses")
- public long getMisses()
- {
+ public long getMisses() {
return misses;
}
@ManagedAttribute(description = "number of cache attribute put operations")
- public long getStores()
- {
+ public long getStores() {
return stores;
}
@ManagedAttribute(description = "number of cache eviction operations")
- public long getEvictions()
- {
+ public long getEvictions() {
return evictions;
}
@ManagedAttribute(description = "hit/miss ratio for the cache")
- public double getHitMissRatio()
- {
+ public double getHitMissRatio() {
double total = hits + misses;
if (total == 0)
return 0;
@@ -150,16 +134,14 @@
}
@ManagedAttribute(description = "read/writes ratio for the cache")
- public double getReadWriteRatio()
- {
+ public double getReadWriteRatio() {
if (stores == 0)
return 0;
return (((double) (hits + misses) / (double) stores));
}
@ManagedAttribute(description = "average number of milliseconds for a read operation")
- public long getAverageReadTime()
- {
+ public long getAverageReadTime() {
long total = hits + misses;
if (total == 0)
return 0;
@@ -167,34 +149,29 @@
}
@ManagedAttribute(description = "average number of milliseconds for a write operation")
- public long getAverageWriteTime()
- {
+ public long getAverageWriteTime() {
if (stores == 0)
return 0;
return (storeTimes) / stores;
}
@ManagedAttribute(description = "number of entries in the cache")
- public int getNumberOfEntries()
- {
+ public int getNumberOfEntries() {
return dataContainer.size();
}
@ManagedAttribute(description = "seconds since cache started")
- public long getElapsedTime()
- {
+ public long getElapsedTime() {
return (System.currentTimeMillis() - start) / 1000;
}
@ManagedAttribute(description = "number of seconds since the cache statistics were last reset")
- public long getTimeSinceReset()
- {
+ public long getTimeSinceReset() {
return (System.currentTimeMillis() - reset) / 1000;
}
@ManagedOperation
- public Map<String, Object> dumpStatistics()
- {
+ public Map<String, Object> dumpStatistics() {
Map<String, Object> retval = new HashMap<String, Object>();
retval.put("Hits", hits);
retval.put("Misses", misses);
@@ -211,8 +188,7 @@
}
@ManagedOperation
- public void resetStatistics()
- {
+ public void resetStatistics() {
hits = 0;
misses = 0;
stores = 0;
Modified: core/branches/flat/src/main/java/org/horizon/interceptors/CacheStoreInterceptor.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/interceptors/CacheStoreInterceptor.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/interceptors/CacheStoreInterceptor.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -56,15 +56,13 @@
import java.util.concurrent.ConcurrentHashMap;
/**
- * Writes modifications back to the store on the way out: stores modifications back
- * through the CacheLoader, either after each method call (no TXs), or at TX commit.
+ * Writes modifications back to the store on the way out: stores modifications back through the CacheLoader, either
+ * after each method call (no TXs), or at TX commit.
*
* @author Bela Ban
- *
* @since 1.0
*/
-public class CacheStoreInterceptor extends JmxStatsCommandInterceptor
-{
+public class CacheStoreInterceptor extends JmxStatsCommandInterceptor {
private CacheLoaderConfig loaderConfig = null;
private TransactionManager txMgr = null;
private HashMap<GlobalTransaction, Integer> txStores = new HashMap<GlobalTransaction, Integer>();
@@ -74,15 +72,13 @@
private CacheLoaderManager loaderManager;
private boolean statsEnabled;
- public CacheStoreInterceptor()
- {
+ public CacheStoreInterceptor() {
log = LogFactory.getLog(getClass());
trace = log.isTraceEnabled();
}
@Inject
- protected void init(CacheLoaderManager loaderManager, TransactionManager txManager, CacheLoaderConfig clConfig)
- {
+ protected void init(CacheLoaderManager loaderManager, TransactionManager txManager, CacheLoaderConfig clConfig) {
// never inject a CacheLoader at this stage - only a CacheLoaderManager, since the CacheLoaderManager only creates a CacheLoader instance when it @Starts.
this.loaderManager = loaderManager;
this.loaderConfig = clConfig;
@@ -90,8 +86,7 @@
}
@Start
- protected void start()
- {
+ protected void start() {
// this should only happen after the CacheLoaderManager has started, since the CacheLoaderManager only creates the CacheLoader instance in its @Start method.
loader = loaderManager.getCacheLoader();
this.setStatisticsEnabled(configuration.isExposeManagementStatistics());
@@ -100,10 +95,8 @@
/**
* if this is a shared cache loader and the call is of remote origin, pass up the chain
*/
- public final boolean skip(InvocationContext ctx, VisitableCommand command)
- {
- if ((!ctx.isOriginLocal() && loaderConfig.isShared()) || ctx.getOptionOverrides().isSuppressPersistence())
- {
+ public final boolean skip(InvocationContext ctx, VisitableCommand command) {
+ if ((!ctx.isOriginLocal() && loaderConfig.isShared()) || ctx.getOptionOverrides().isSuppressPersistence()) {
if (trace)
log.trace("Passing up method call and bypassing this interceptor since the cache loader is shared and this call originated remotely.");
return true;
@@ -112,40 +105,31 @@
}
@Override
- public Object visitCommitCommand(InvocationContext ctx, CommitCommand command) throws Throwable
- {
- if (!skip(ctx, command) && inTransaction())
- {
- if (ctx.getTransactionContext().hasAnyModifications())
- {
+ public Object visitCommitCommand(InvocationContext ctx, CommitCommand command) throws Throwable {
+ if (!skip(ctx, command) && inTransaction()) {
+ if (ctx.getTransactionContext().hasAnyModifications()) {
// this is a commit call.
GlobalTransaction gtx = command.getGlobalTransaction();
if (trace) log.trace("Calling loader.commit() for gtx " + gtx);
// sync call (a write) on the loader
// ignore modified FQNs
// List fqnsModified = getFqnsFromModificationList(txTable.get(globalTransaction).getCacheLoaderModifications());
- try
- {
+ try {
loader.commit(gtx);
}
- catch (Throwable t)
- {
+ catch (Throwable t) {
preparingTxs.remove(gtx);
throw t;
}
- if (getStatisticsEnabled())
- {
+ if (getStatisticsEnabled()) {
Integer puts = (Integer) txStores.get(gtx);
- if (puts != null)
- {
+ if (puts != null) {
cacheStores = cacheStores + puts;
}
txStores.remove(gtx);
}
return invokeNextInterceptor(ctx, command);
- }
- else
- {
+ } else {
if (trace) log.trace("Commit called with no modifications; ignoring.");
}
}
@@ -153,24 +137,18 @@
}
@Override
- public Object visitRollbackCommand(InvocationContext ctx, RollbackCommand command) throws Throwable
- {
- if (!skip(ctx, command) && inTransaction())
- {
+ public Object visitRollbackCommand(InvocationContext ctx, RollbackCommand command) throws Throwable {
+ if (!skip(ctx, command) && inTransaction()) {
if (trace) log.trace("transactional so don't put stuff in the cloader yet.");
- if (ctx.getTransactionContext().hasAnyModifications())
- {
+ if (ctx.getTransactionContext().hasAnyModifications()) {
GlobalTransaction gtx = command.getGlobalTransaction();
// this is a rollback method
- if (preparingTxs.containsKey(gtx))
- {
+ if (preparingTxs.containsKey(gtx)) {
preparingTxs.remove(gtx);
loader.rollback(gtx);
}
if (getStatisticsEnabled()) txStores.remove(gtx);
- }
- else
- {
+ } else {
if (trace) log.trace("Rollback called with no modifications; ignoring.");
}
}
@@ -178,10 +156,8 @@
}
@Override
- public Object visitPrepareCommand(InvocationContext ctx, PrepareCommand command) throws Throwable
- {
- if (!skip(ctx, command) && inTransaction())
- {
+ public Object visitPrepareCommand(InvocationContext ctx, PrepareCommand command) throws Throwable {
+ if (!skip(ctx, command) && inTransaction()) {
if (trace) log.trace("transactional so don't put stuff in the cloader yet.");
prepareCacheLoader(command.getGlobalTransaction(), ctx.getTransactionContext(), command.isOnePhaseCommit());
}
@@ -189,10 +165,8 @@
}
@Override
- public Object visitRemoveCommand(InvocationContext ctx, RemoveCommand command) throws Throwable
- {
- if (!skip(ctx, command) && !inTransaction())
- {
+ public Object visitRemoveCommand(InvocationContext ctx, RemoveCommand command) throws Throwable {
+ if (!skip(ctx, command) && !inTransaction()) {
Object returnValue = loader.remove(command.getKey());
invokeNextInterceptor(ctx, command);
return returnValue;
@@ -201,8 +175,7 @@
}
@Override
- public Object visitPutKeyValueCommand(InvocationContext ctx, PutKeyValueCommand command) throws Throwable
- {
+ public Object visitPutKeyValueCommand(InvocationContext ctx, PutKeyValueCommand command) throws Throwable {
Object returnValue = invokeNextInterceptor(ctx, command);
if (skip(ctx, command) || inTransaction())
return returnValue;
@@ -214,8 +187,7 @@
}
@Override
- public Object visitPutMapCommand(InvocationContext ctx, PutMapCommand command) throws Throwable
- {
+ public Object visitPutMapCommand(InvocationContext ctx, PutMapCommand command) throws Throwable {
Object returnValue = invokeNextInterceptor(ctx, command);
if (skip(ctx, command) || inTransaction())
return returnValue;
@@ -230,55 +202,45 @@
return returnValue;
}
- private static List<Modification> toModifications(Map<Object, Object> map)
- {
+ private static List<Modification> toModifications(Map<Object, Object> map) {
List<Modification> modifications = new ArrayList<Modification>(map.size());
for (Map.Entry<Object, Object> entry : map.entrySet())
modifications.add(new Modification(ModificationType.PUT, entry.getKey(), entry.getValue()));
return modifications;
}
- private boolean inTransaction() throws SystemException
- {
+ private boolean inTransaction() throws SystemException {
return txMgr != null && txMgr.getTransaction() != null;
}
- private void prepareCacheLoader(GlobalTransaction gtx, TransactionContext transactionContext, boolean onePhase) throws Throwable
- {
- if (transactionContext == null)
- {
+ private void prepareCacheLoader(GlobalTransaction gtx, TransactionContext transactionContext, boolean onePhase) throws Throwable {
+ if (transactionContext == null) {
throw new Exception("transactionContext for transaction " + gtx + " not found in transaction table");
}
List<VisitableCommand> modifications = transactionContext.getModifications();
- if (modifications.size() == 0)
- {
+ if (modifications.size() == 0) {
if (trace) log.trace("Transaction has not logged any modifications!");
return;
}
if (trace) log.trace("Cache loader modification list: " + modifications);
StoreModificationsBuilder modsBuilder = new StoreModificationsBuilder(getStatisticsEnabled());
- for (VisitableCommand cacheCommand : modifications)
- {
+ for (VisitableCommand cacheCommand : modifications) {
cacheCommand.acceptVisitor(null, modsBuilder);
}
- if (trace)
- {
+ if (trace) {
log.trace("Converted method calls to cache loader modifications. List size: " + modsBuilder.modifications.size());
}
- if (modsBuilder.modifications.size() > 0)
- {
+ if (modsBuilder.modifications.size() > 0) {
loader.prepare(gtx, modsBuilder.modifications, onePhase);
preparingTxs.put(gtx, modsBuilder.affectedKeys);
- if (getStatisticsEnabled() && modsBuilder.putCount > 0)
- {
+ if (getStatisticsEnabled() && modsBuilder.putCount > 0) {
txStores.put(gtx, modsBuilder.putCount);
}
}
}
- public static class StoreModificationsBuilder extends AbstractVisitor
- {
+ public static class StoreModificationsBuilder extends AbstractVisitor {
boolean generateStatistics;
@@ -288,14 +250,12 @@
List<Modification> modifications = new ArrayList<Modification>();
- public StoreModificationsBuilder(boolean generateStatistics)
- {
+ public StoreModificationsBuilder(boolean generateStatistics) {
this.generateStatistics = generateStatistics;
}
@Override
- public Object visitPutKeyValueCommand(InvocationContext ctx, PutKeyValueCommand command) throws Throwable
- {
+ public Object visitPutKeyValueCommand(InvocationContext ctx, PutKeyValueCommand command) throws Throwable {
if (generateStatistics) putCount++;
modifications.add(new Modification(Modification.ModificationType.PUT, command.getKey(), command.getValue()));
affectedKeys.add(command.getKey());
@@ -303,8 +263,7 @@
}
@Override
- public Object visitPutMapCommand(InvocationContext ctx, PutMapCommand command) throws Throwable
- {
+ public Object visitPutMapCommand(InvocationContext ctx, PutMapCommand command) throws Throwable {
Map<Object, Object> map = command.getMap();
if (generateStatistics) putCount += map.size();
affectedKeys.addAll(map.keySet());
@@ -313,50 +272,43 @@
}
@Override
- public Object visitRemoveCommand(InvocationContext ctx, RemoveCommand command) throws Throwable
- {
+ public Object visitRemoveCommand(InvocationContext ctx, RemoveCommand command) throws Throwable {
modifications.add(new Modification(Modification.ModificationType.REMOVE, command.getKey(), null));
affectedKeys.add(command.getKey());
return null;
}
@Override
- public Object visitClearCommand(InvocationContext ctx, ClearCommand command) throws Throwable
- {
+ public Object visitClearCommand(InvocationContext ctx, ClearCommand command) throws Throwable {
modifications.add(new Modification(Modification.ModificationType.CLEAR, null, null));
return null;
}
}
@ManagedOperation
- public void resetStatistics()
- {
+ public void resetStatistics() {
cacheStores = 0;
}
@ManagedOperation
- public Map<String, Object> dumpStatistics()
- {
+ public Map<String, Object> dumpStatistics() {
Map<String, Object> retval = new HashMap<String, Object>();
retval.put("CacheLoaderStores", cacheStores);
return retval;
}
@ManagedAttribute
- public boolean getStatisticsEnabled()
- {
+ public boolean getStatisticsEnabled() {
return statsEnabled;
}
@ManagedAttribute
- public void setStatisticsEnabled(boolean enabled)
- {
+ public void setStatisticsEnabled(boolean enabled) {
this.statsEnabled = enabled;
}
@ManagedAttribute(description = "number of cache loader stores")
- public long getCacheLoaderStores()
- {
+ public long getCacheLoaderStores() {
return cacheStores;
}
Modified: core/branches/flat/src/main/java/org/horizon/interceptors/CallInterceptor.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/interceptors/CallInterceptor.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/interceptors/CallInterceptor.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -37,59 +37,49 @@
import javax.transaction.Transaction;
/**
- * Always at the end of the chain, directly in front of the cache. Simply calls into the cache using reflection.
- * If the call resulted in a modification, add the Modification to the end of the modification list
- * keyed by the current transaction.
+ * Always at the end of the chain, directly in front of the cache. Simply calls into the cache using reflection. If the
+ * call resulted in a modification, add the Modification to the end of the modification list keyed by the current
+ * transaction.
* <p/>
- * Although always added to the end of an optimistically locked chain as well, calls should not make it down to
- * this interceptor unless it is a call the OptimisticNodeInterceptor knows nothing about.
+ * Although always added to the end of an optimistically locked chain as well, calls should not make it down to this
+ * interceptor unless it is a call the OptimisticNodeInterceptor knows nothing about.
*
* @author Bela Ban
- *
* @since 1.0
*/
-public class CallInterceptor extends CommandInterceptor
-{
+public class CallInterceptor extends CommandInterceptor {
@Override
- public Object visitPrepareCommand(InvocationContext ctx, PrepareCommand command) throws Throwable
- {
+ public Object visitPrepareCommand(InvocationContext ctx, PrepareCommand command) throws Throwable {
if (trace) log.trace("Suppressing invocation of method handlePrepareCommand.");
return null;
}
@Override
- public Object visitCommitCommand(InvocationContext ctx, CommitCommand command) throws Throwable
- {
+ public Object visitCommitCommand(InvocationContext ctx, CommitCommand command) throws Throwable {
if (trace) log.trace("Suppressing invocation of method handleCommitCommand.");
return null;
}
@Override
- public Object visitRollbackCommand(InvocationContext ctx, RollbackCommand command) throws Throwable
- {
+ public Object visitRollbackCommand(InvocationContext ctx, RollbackCommand command) throws Throwable {
if (trace) log.trace("Suppressing invocation of method handleRollbackCommand.");
return null;
}
@Override
- public Object handleDefault(InvocationContext ctx, VisitableCommand command) throws Throwable
- {
+ public Object handleDefault(InvocationContext ctx, VisitableCommand command) throws Throwable {
if (trace) log.trace("Executing command: " + command + ".");
return invokeCommand(ctx, command);
}
- private Object invokeCommand(InvocationContext ctx, ReplicableCommand command) throws Throwable
- {
+ private Object invokeCommand(InvocationContext ctx, ReplicableCommand command) throws Throwable {
Object retval;
- try
- {
+ try {
retval = command.perform(ctx);
}
- catch (Throwable t)
- {
+ catch (Throwable t) {
Transaction tx = ctx.getTransaction();
- if (ctx.isValidTransaction())
- {
+ if (ctx.isValidTransaction()) {
tx.setRollbackOnly();
}
throw t;
@@ -98,47 +88,36 @@
}
@Override
- public Object visitPutKeyValueCommand(InvocationContext ctx, PutKeyValueCommand command) throws Throwable
- {
+ public Object visitPutKeyValueCommand(InvocationContext ctx, PutKeyValueCommand command) throws Throwable {
return handleAlterCacheMethod(ctx, command);
}
@Override
- public Object visitClearCommand(InvocationContext ctx, ClearCommand command) throws Throwable
- {
+ public Object visitClearCommand(InvocationContext ctx, ClearCommand command) throws Throwable {
return handleAlterCacheMethod(ctx, command);
}
@Override
- public Object visitRemoveCommand(InvocationContext ctx, RemoveCommand command) throws Throwable
- {
+ public Object visitRemoveCommand(InvocationContext ctx, RemoveCommand command) throws Throwable {
return handleAlterCacheMethod(ctx, command);
}
-
/**
- * only add the modification to the modification list if we are using pessimistic locking.
- * Optimistic locking calls *should* not make it this far down the interceptor chain, but just
- * in case a method has been invoked that the OptimisticNodeInterceptor knows nothing about, it will
- * filter down here.
+ * only add the modification to the modification list if we are using pessimistic locking. Optimistic locking calls
+ * *should* not make it this far down the interceptor chain, but just in case a method has been invoked that the
+ * OptimisticNodeInterceptor knows nothing about, it will filter down here.
*/
private Object handleAlterCacheMethod(InvocationContext ctx, VisitableCommand command)
- throws Throwable
- {
+ throws Throwable {
Object result = invokeCommand(ctx, command);
- if (ctx.isValidTransaction())
- {
+ if (ctx.isValidTransaction()) {
GlobalTransaction gtx = ctx.getGlobalTransaction();
- if (gtx == null)
- {
- if (log.isDebugEnabled())
- {
+ if (gtx == null) {
+ if (log.isDebugEnabled()) {
log.debug("didn't find GlobalTransaction for " + ctx.getTransaction() + "; won't add modification to transaction list");
}
- }
- else
- {
+ } else {
ctx.getTransactionContext().addModification(command);
}
}
Modified: core/branches/flat/src/main/java/org/horizon/interceptors/EvictionInterceptor.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/interceptors/EvictionInterceptor.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/interceptors/EvictionInterceptor.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -22,7 +22,11 @@
package org.horizon.interceptors;
import org.horizon.commands.read.GetKeyValueCommand;
-import org.horizon.commands.write.*;
+import org.horizon.commands.write.ClearCommand;
+import org.horizon.commands.write.PutKeyValueCommand;
+import org.horizon.commands.write.PutMapCommand;
+import org.horizon.commands.write.RemoveCommand;
+import org.horizon.commands.write.ReplaceCommand;
import org.horizon.context.InvocationContext;
import org.horizon.eviction.EvictionCacheManager;
import org.horizon.eviction.EvictionEvent;
@@ -37,8 +41,7 @@
* @author Mircea.Markus at jboss.com
* @since 1.0
*/
-public class EvictionInterceptor extends CommandInterceptor
-{
+public class EvictionInterceptor extends CommandInterceptor {
protected EvictionCacheManager evictionCacheManager;
/**
@@ -46,35 +49,28 @@
* <p/>
* Not to be attempted to be used anywhere else.
*/
- public void setEvictionCacheManager(EvictionCacheManager evictionCacheManager)
- {
+ public void setEvictionCacheManager(EvictionCacheManager evictionCacheManager) {
this.evictionCacheManager = evictionCacheManager;
}
@Override
- public Object visitPutKeyValueCommand(InvocationContext ctx, PutKeyValueCommand command) throws Throwable
- {
+ public Object visitPutKeyValueCommand(InvocationContext ctx, PutKeyValueCommand command) throws Throwable {
Object retVal = invokeNextInterceptor(ctx, command);
- if (command.getKey() != null)
- {
+ if (command.getKey() != null) {
registerEvictionEvent(command.getKey(), ADD_ELEMENT_EVENT, 1);
}
return retVal;
}
@Override
- public Object visitPutMapCommand(InvocationContext ctx, PutMapCommand command) throws Throwable
- {
+ public Object visitPutMapCommand(InvocationContext ctx, PutMapCommand command) throws Throwable {
Object retVal = invokeNextInterceptor(ctx, command);
- if (command.getMap() == null)
- {
+ if (command.getMap() == null) {
if (trace) log.trace("Putting null data.");
- } else
- {
+ } else {
int size;
- synchronized (command.getMap())
- {
+ synchronized (command.getMap()) {
size = command.getMap().size();
}
registerEvictionEvent(null, ADD_NODE_EVENT, size);
@@ -83,16 +79,12 @@
}
@Override
- public Object visitRemoveCommand(InvocationContext ctx, RemoveCommand command) throws Throwable
- {
+ public Object visitRemoveCommand(InvocationContext ctx, RemoveCommand command) throws Throwable {
Object retVal = invokeNextInterceptor(ctx, command);
- if (retVal == null)
- {
+ if (retVal == null) {
if (trace) log.trace("No event added. Element does not exist");
- } else
- {
- if (command.getKey() != null)
- {
+ } else {
+ if (command.getKey() != null) {
registerEvictionEvent(command.getKey(), REMOVE_ELEMENT_EVENT, 1);
}
}
@@ -100,38 +92,32 @@
}
@Override
- public Object visitGetKeyValueCommand(InvocationContext ctx, GetKeyValueCommand command) throws Throwable
- {
+ public Object visitGetKeyValueCommand(InvocationContext ctx, GetKeyValueCommand command) throws Throwable {
Object retVal = invokeNextInterceptor(ctx, command);
- if (retVal == null)
- {
+ if (retVal == null) {
if (trace) log.trace("No event added. Element does not exist");
- } else if (command.getKey() != null)
- {
+ } else if (command.getKey() != null) {
registerEvictionEvent(command.getKey(), VISIT_NODE_EVENT, 0);
}
return retVal;
}
- public Object visitReplaceCommand(InvocationContext ctx, ReplaceCommand command) throws Throwable
- {
+ public Object visitReplaceCommand(InvocationContext ctx, ReplaceCommand command) throws Throwable {
Boolean replaced = (Boolean) invokeNextInterceptor(ctx, command);
if (replaced) registerEvictionEvent(command.getKey(), ADD_NODE_EVENT, 1);
- else registerEvictionEvent(command.getKey(), VISIT_NODE_EVENT, 0);
+ else registerEvictionEvent(command.getKey(), VISIT_NODE_EVENT, 0);
return replaced;
}
@Override
- public Object visitClearCommand(InvocationContext ctx, ClearCommand command) throws Throwable
- {
+ public Object visitClearCommand(InvocationContext ctx, ClearCommand command) throws Throwable {
Object retVal = invokeNextInterceptor(ctx, command);
registerEvictionEvent(null, REMOVE_NODE_EVENT, 0);
return retVal;
}
@SuppressWarnings(value = "unchecked")
- private void registerEvictionEvent(Object key, EvictionEvent.Type type, int elementDifference)
- {
+ private void registerEvictionEvent(Object key, EvictionEvent.Type type, int elementDifference) {
evictionCacheManager.registerEvictionEvent(key, type, elementDifference);
if (trace) log.trace("Registering event " + type + " on node " + key);
}
Modified: core/branches/flat/src/main/java/org/horizon/interceptors/InterceptorChain.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/interceptors/InterceptorChain.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/interceptors/InterceptorChain.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -42,13 +42,11 @@
* Knows how to build and manage an chain of interceptors. Also in charge with invoking methods on the chain.
*
* @author Mircea.Markus at jboss.com
- * @since 1.0
- * todo - if you add the same interceptor instance twice, things get really dirty.
- * -- this should be treated as an missuse and an exception should be thrown
+ * @since 1.0 todo - if you add the same interceptor instance twice, things get really dirty. -- this should be treated
+ * as an missuse and an exception should be thrown
*/
@Scope(Scopes.NAMED_CACHE)
-public class InterceptorChain
-{
+public class InterceptorChain {
/**
* reference to the first interceptor in the chain
*/
@@ -63,20 +61,17 @@
/**
* Constructs an interceptor chain having the supplied interceptor as first.
*/
- public InterceptorChain(CommandInterceptor first)
- {
+ public InterceptorChain(CommandInterceptor first) {
this.firstInChain = first;
}
@Inject
- public void initialize(InvocationContextContainer invocationContextContainer)
- {
+ public void initialize(InvocationContextContainer invocationContextContainer) {
this.invocationContextContainer = invocationContextContainer;
}
@Start
- private void printChainInfo()
- {
+ private void printChainInfo() {
if (log.isDebugEnabled()) log.debug("Interceptor chain size: " + size());
if (log.isDebugEnabled()) log.debug("Interceptor chain is: " + toString());
}
@@ -84,12 +79,11 @@
/**
* Inserts the given interceptor at the specified position in the chain (o based indexing).
*
- * @throws IllegalArgumentException if the position is invalid (e.g. 5 and there are only 2 interceptors in the chain)
+ * @throws IllegalArgumentException if the position is invalid (e.g. 5 and there are only 2 interceptors in the
+ * chain)
*/
- public synchronized void addInterceptor(CommandInterceptor interceptor, int position)
- {
- if (position == 0)
- {
+ public synchronized void addInterceptor(CommandInterceptor interceptor, int position) {
+ if (position == 0) {
interceptor.setNext(firstInChain);
firstInChain = interceptor;
return;
@@ -97,10 +91,8 @@
if (firstInChain == null) return;
CommandInterceptor it = firstInChain;
int index = 0;
- while (it != null)
- {
- if (++index == position)
- {
+ while (it != null) {
+ if (++index == position) {
interceptor.setNext(it.getNext());
it.setNext(interceptor);
return;
@@ -113,22 +105,19 @@
/**
* Removes the interceptor at the given postion.
*
- * @throws IllegalArgumentException if the position is invalid (e.g. 5 and there are only 2 interceptors in the chain)
+ * @throws IllegalArgumentException if the position is invalid (e.g. 5 and there are only 2 interceptors in the
+ * chain)
*/
- public synchronized void removeInterceptor(int position)
- {
+ public synchronized void removeInterceptor(int position) {
if (firstInChain == null) return;
- if (position == 0)
- {
+ if (position == 0) {
firstInChain = firstInChain.getNext();
return;
}
CommandInterceptor it = firstInChain;
int index = 0;
- while (it != null)
- {
- if (++index == position)
- {
+ while (it != null) {
+ if (++index == position) {
if (it.getNext() == null) return; //nothing to remove
it.setNext(it.getNext().getNext());
return;
@@ -141,12 +130,10 @@
/**
* Returns the number of interceptors in the chain.
*/
- public int size()
- {
+ public int size() {
int size = 0;
CommandInterceptor it = firstInChain;
- while (it != null)
- {
+ while (it != null) {
size++;
it = it.getNext();
}
@@ -155,17 +142,15 @@
}
/**
- * Returns an unmofiable list with all the interceptors in sequence.
- * If first in chain is null an empty list is returned.
+ * Returns an unmofiable list with all the interceptors in sequence. If first in chain is null an empty list is
+ * returned.
*/
- public List<CommandInterceptor> asList()
- {
+ public List<CommandInterceptor> asList() {
if (firstInChain == null) return Collections.emptyList();
List<CommandInterceptor> retval = new LinkedList<CommandInterceptor>();
CommandInterceptor tmp = firstInChain;
- do
- {
+ do {
retval.add(tmp);
tmp = tmp.getNext();
}
@@ -177,18 +162,14 @@
/**
* Removes all the occurences of supplied interceptor type from the chain.
*/
- public synchronized void removeInterceptor(Class<? extends CommandInterceptor> clazz)
- {
- if (firstInChain.getClass() == clazz)
- {
+ public synchronized void removeInterceptor(Class<? extends CommandInterceptor> clazz) {
+ if (firstInChain.getClass() == clazz) {
firstInChain = firstInChain.getNext();
}
CommandInterceptor it = firstInChain.getNext();
CommandInterceptor prevIt = firstInChain;
- while (it != null)
- {
- if (it.getClass() == clazz)
- {
+ while (it != null) {
+ if (it.getClass() == clazz) {
prevIt.setNext(it.getNext());
}
prevIt = it;
@@ -201,13 +182,10 @@
*
* @return true if the interceptor was added; i.e. the afterInterceptor exists
*/
- public synchronized boolean addAfterInterceptor(CommandInterceptor toAdd, Class<? extends CommandInterceptor> afterInterceptor)
- {
+ public synchronized boolean addAfterInterceptor(CommandInterceptor toAdd, Class<? extends CommandInterceptor> afterInterceptor) {
CommandInterceptor it = firstInChain;
- while (it != null)
- {
- if (it.getClass().equals(afterInterceptor))
- {
+ while (it != null) {
+ if (it.getClass().equals(afterInterceptor)) {
toAdd.setNext(it.getNext());
it.setNext(toAdd);
return true;
@@ -222,19 +200,15 @@
*
* @return true if the interceptor was added; i.e. the afterInterceptor exists
*/
- public synchronized boolean addBeforeInterceptor(CommandInterceptor toAdd, Class<? extends CommandInterceptor> beforeInterceptor)
- {
- if (firstInChain.getClass().equals(beforeInterceptor))
- {
+ public synchronized boolean addBeforeInterceptor(CommandInterceptor toAdd, Class<? extends CommandInterceptor> beforeInterceptor) {
+ if (firstInChain.getClass().equals(beforeInterceptor)) {
toAdd.setNext(firstInChain);
firstInChain = toAdd;
return true;
}
CommandInterceptor it = firstInChain;
- while (it.getNext() != null)
- {
- if (it.getNext().getClass().equals(beforeInterceptor))
- {
+ while (it.getNext() != null) {
+ if (it.getNext().getClass().equals(beforeInterceptor)) {
toAdd.setNext(it.getNext());
it.setNext(toAdd);
return true;
@@ -247,8 +221,7 @@
/**
* Appends at the end.
*/
- public void appendIntereceptor(CommandInterceptor ci)
- {
+ public void appendIntereceptor(CommandInterceptor ci) {
CommandInterceptor it = firstInChain;
while (it.hasNext()) it = it.getNext();
it.setNext(ci);
@@ -260,44 +233,36 @@
* Walks the command through the interceptor chain. The received ctx is being passed in.
*/
@SuppressWarnings("deprecation")
- public Object invoke(InvocationContext ctx, VisitableCommand command)
- {
- try
- {
+ public Object invoke(InvocationContext ctx, VisitableCommand command) {
+ try {
return command.acceptVisitor(ctx, firstInChain);
}
- catch (CacheException e)
- {
+ catch (CacheException e) {
throw e;
}
- catch (RuntimeException e)
- {
+ catch (RuntimeException e) {
throw e;
}
- catch (Throwable t)
- {
+ catch (Throwable t) {
throw new CacheException(t);
}
}
/**
- * Similar to {@link #invoke(InvocationContext , VisitableCommand)}, but
- * constructs a invocation context on the fly, using {@link InvocationContextContainer#get()}
+ * Similar to {@link #invoke(InvocationContext , VisitableCommand)}, but constructs a invocation context on the fly,
+ * using {@link InvocationContextContainer#get()}
*/
- public Object invokeRemote(VisitableCommand cacheCommand) throws Throwable
- {
+ public Object invokeRemote(VisitableCommand cacheCommand) throws Throwable {
InvocationContext ctxt = invocationContextContainer.get();
ctxt.setOriginLocal(false);
return cacheCommand.acceptVisitor(ctxt, firstInChain);
}
/**
- * Similar to {@link #invoke(InvocationContext , VisitableCommand)}, but
- * constructs a invocation context on the fly, using {@link InvocationContextContainer#get()} and setting the origin
- * local flag to its default value.
+ * Similar to {@link #invoke(InvocationContext , VisitableCommand)}, but constructs a invocation context on the fly,
+ * using {@link InvocationContextContainer#get()} and setting the origin local flag to its default value.
*/
- public Object invoke(VisitableCommand cacheCommand) throws Throwable
- {
+ public Object invoke(VisitableCommand cacheCommand) throws Throwable {
InvocationContext ctxt = invocationContextContainer.get();
return cacheCommand.acceptVisitor(ctxt, firstInChain);
}
@@ -305,8 +270,7 @@
/**
* @return the first interceptor in the chain.
*/
- public CommandInterceptor getFirstInChain()
- {
+ public CommandInterceptor getFirstInChain() {
return firstInChain;
}
@@ -315,27 +279,22 @@
*
* @param interceptor interceptor to be used as the first interceptor in the chain.
*/
- public void setFirstInChain(CommandInterceptor interceptor)
- {
+ public void setFirstInChain(CommandInterceptor interceptor) {
this.firstInChain = interceptor;
}
- public InvocationContext getInvocationContext()
- {
+ public InvocationContext getInvocationContext() {
return invocationContextContainer.get();
}
/**
* Returns all interceptors which extend the given command interceptor.
*/
- public List<CommandInterceptor> getInterceptorsWhichExtend(Class<? extends CommandInterceptor> interceptorClass)
- {
+ public List<CommandInterceptor> getInterceptorsWhichExtend(Class<? extends CommandInterceptor> interceptorClass) {
List<CommandInterceptor> result = new ArrayList<CommandInterceptor>();
- for (CommandInterceptor interceptor : asList())
- {
+ for (CommandInterceptor interceptor : asList()) {
boolean isSubclass = interceptorClass.isAssignableFrom(interceptor.getClass());
- if (isSubclass)
- {
+ if (isSubclass) {
result.add(interceptor);
}
}
@@ -343,26 +302,23 @@
}
/**
- * Returns all the interceptors that have the fully qualified name of their class equal with the supplied class name.
+ * Returns all the interceptors that have the fully qualified name of their class equal with the supplied class
+ * name.
*/
- public List<CommandInterceptor> getInterceptorsWithClassName(String fqName)
- {
+ public List<CommandInterceptor> getInterceptorsWithClassName(String fqName) {
CommandInterceptor iterator = firstInChain;
List<CommandInterceptor> result = new ArrayList<CommandInterceptor>(2);
- while (iterator != null)
- {
+ while (iterator != null) {
if (iterator.getClass().getName().equals(fqName)) result.add(iterator);
iterator = iterator.getNext();
}
return result;
}
- public String toString()
- {
+ public String toString() {
StringBuilder sb = new StringBuilder();
CommandInterceptor i = firstInChain;
- while (i != null)
- {
+ while (i != null) {
sb.append("\n\t>> ");
sb.append(i.getClass().getName());
i = i.getNext();
@@ -373,22 +329,18 @@
/**
* Checks whether the chain contains the supplied interceptor instance.
*/
- public boolean containsInstance(CommandInterceptor interceptor)
- {
+ public boolean containsInstance(CommandInterceptor interceptor) {
CommandInterceptor it = firstInChain;
- while (it != null)
- {
+ while (it != null) {
if (it == interceptor) return true;
it = it.getNext();
}
return false;
}
- public boolean containsInterceptorType(Class<? extends CommandInterceptor> interceptorType)
- {
+ public boolean containsInterceptorType(Class<? extends CommandInterceptor> interceptorType) {
CommandInterceptor it = firstInChain;
- while (it != null)
- {
+ while (it != null) {
if (it.getClass().equals(interceptorType)) return true;
it = it.getNext();
}
Modified: core/branches/flat/src/main/java/org/horizon/interceptors/InvalidationInterceptor.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/interceptors/InvalidationInterceptor.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/interceptors/InvalidationInterceptor.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -21,6 +21,8 @@
*/
package org.horizon.interceptors;
+import org.horizon.annotations.ManagedAttribute;
+import org.horizon.annotations.ManagedOperation;
import org.horizon.commands.AbstractVisitor;
import org.horizon.commands.CommandsFactory;
import org.horizon.commands.DataCommand;
@@ -36,75 +38,68 @@
import org.horizon.factories.annotations.Inject;
import org.horizon.factories.annotations.Start;
import org.horizon.interceptors.base.BaseRpcInterceptor;
-import org.horizon.annotations.ManagedAttribute;
-import org.horizon.annotations.ManagedOperation;
import org.horizon.transaction.GlobalTransaction;
import org.horizon.transaction.TransactionTable;
import javax.transaction.SystemException;
import javax.transaction.Transaction;
-import java.util.*;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
/**
- * This interceptor acts as a replacement to the replication interceptor when
- * the CacheImpl is configured with ClusteredSyncMode as INVALIDATE.
+ * This interceptor acts as a replacement to the replication interceptor when the CacheImpl is configured with
+ * ClusteredSyncMode as INVALIDATE.
* <p/>
- * The idea is that rather than replicating changes to all caches in a cluster
- * when CRUD (Create, Remove, Update, Delete) methods are called, simply call
- * evict(Fqn) on the remote caches for each changed node. This allows the
- * remote node to look up the value in a shared cache loader which would have
- * been updated with the changes.
+ * The idea is that rather than replicating changes to all caches in a cluster when CRUD (Create, Remove, Update,
+ * Delete) methods are called, simply call evict(Fqn) on the remote caches for each changed node. This allows the
+ * remote node to look up the value in a shared cache loader which would have been updated with the changes.
*
* @author <a href="mailto:manik at jboss.org">Manik Surtani (manik at jboss.org)</a>
* @since 1.0
*/
-public class InvalidationInterceptor extends BaseRpcInterceptor
-{
+public class InvalidationInterceptor extends BaseRpcInterceptor {
private long invalidations = 0;
protected Map<GlobalTransaction, List<VisitableCommand>> txMods;
private CommandsFactory commandsFactory;
private boolean statsEnabled;
@Inject
- public void injectDependencies(CommandsFactory commandsFactory)
- {
+ public void injectDependencies(CommandsFactory commandsFactory) {
this.commandsFactory = commandsFactory;
}
@Start
- private void initTxMap()
- {
+ private void initTxMap() {
this.setStatisticsEnabled(configuration.isExposeManagementStatistics());
}
@Override
- public Object visitPutKeyValueCommand(InvocationContext ctx, PutKeyValueCommand command) throws Throwable
- {
+ public Object visitPutKeyValueCommand(InvocationContext ctx, PutKeyValueCommand command) throws Throwable {
return handleWriteMethod(ctx, command, command);
}
@Override
- public Object visitRemoveCommand(InvocationContext ctx, RemoveCommand command) throws Throwable
- {
+ public Object visitRemoveCommand(InvocationContext ctx, RemoveCommand command) throws Throwable {
return handleWriteMethod(ctx, command.getKey(), command);
}
@Override
- public Object visitClearCommand(InvocationContext ctx, ClearCommand command) throws Throwable
- {
+ public Object visitClearCommand(InvocationContext ctx, ClearCommand command) throws Throwable {
// return handleWriteMethod(ctx, command.getKey(), command);
//todo handle this - should perfor a remote invalidation aswell!!!
return null;
}
@Override
- public Object visitPrepareCommand(InvocationContext ctx, PrepareCommand command) throws Throwable
- {
+ public Object visitPrepareCommand(InvocationContext ctx, PrepareCommand command) throws Throwable {
Object retval = invokeNextInterceptor(ctx, command);
Transaction tx = ctx.getTransaction();
- if (tx != null)
- {
+ if (tx != null) {
if (trace) log.trace("Entering InvalidationInterceptor_Legacy's prepare phase");
// fetch the modifications before the transaction is committed (and thus removed from the txTable)
GlobalTransaction gtx = ctx.getGlobalTransaction();
@@ -112,22 +107,16 @@
if (transactionContext == null)
throw new IllegalStateException("cannot find transaction transactionContext for " + gtx);
- if (transactionContext.hasModifications())
- {
+ if (transactionContext.hasModifications()) {
List<DataCommand> mods;
- if (transactionContext.hasLocalModifications())
- {
+ if (transactionContext.hasLocalModifications()) {
mods = new ArrayList<DataCommand>(command.getModifications());
mods.removeAll(transactionContext.getLocalModifications());
- }
- else
- {
+ } else {
mods = command.getModifications();
}
broadcastInvalidate(mods, tx, ctx);
- }
- else
- {
+ } else {
if (trace) log.trace("Nothing to invalidate - no modifications in the transaction.");
}
}
@@ -135,56 +124,42 @@
}
private Object handleWriteMethod(InvocationContext ctx, Object key, VisitableCommand command)
- throws Throwable
- {
+ throws Throwable {
Object retval = invokeNextInterceptor(ctx, command);
Transaction tx = ctx.getTransaction();
Option optionOverride = ctx.getOptionOverrides();
if (log.isDebugEnabled()) log.debug("Is a CRUD method");
- if (key != null)
- {
+ if (key != null) {
// could be potentially TRANSACTIONAL. Ignore if it is, until we see a prepare().
- if (tx == null || !TransactionTable.isValid(tx))
- {
+ if (tx == null || !TransactionTable.isValid(tx)) {
// the no-tx case:
//replicate an evict call.
invalidateAcrossCluster(key, null, isSynchronous(optionOverride), ctx);
- }
- else
- {
+ } else {
if (isLocalModeForced(ctx)) ctx.getTransactionContext().addLocalModification(command);
}
}
return retval;
}
- private void broadcastInvalidate(List<DataCommand> modifications, Transaction tx, InvocationContext ctx) throws Throwable
- {
- if (ctx.getTransaction() != null && !isLocalModeForced(ctx))
- {
+ private void broadcastInvalidate(List<DataCommand> modifications, Transaction tx, InvocationContext ctx) throws Throwable {
+ if (ctx.getTransaction() != null && !isLocalModeForced(ctx)) {
if (modifications == null || modifications.isEmpty()) return;
InvalidationFilterVisitor filterVisitor = new InvalidationFilterVisitor(modifications.size());
filterVisitor.visitCollection(null, modifications);
- if (filterVisitor.containsPutForExternalRead)
- {
+ if (filterVisitor.containsPutForExternalRead) {
log.debug("Modification list contains a putForExternalRead operation. Not invalidating.");
- }
- else
- {
- try
- {
+ } else {
+ try {
for (Object key : filterVisitor.result) invalidateAcrossCluster(key, null, defaultSynchronous, ctx);
}
- catch (Throwable t)
- {
+ catch (Throwable t) {
log.warn("Unable to broadcast evicts as a part of the prepare phase. Rolling back.", t);
- try
- {
+ try {
tx.setRollbackOnly();
}
- catch (SystemException se)
- {
+ catch (SystemException se) {
throw new RuntimeException("setting tx rollback failed ", se);
}
if (t instanceof RuntimeException)
@@ -196,36 +171,30 @@
}
}
- public static class InvalidationFilterVisitor extends AbstractVisitor
- {
+ public static class InvalidationFilterVisitor extends AbstractVisitor {
Set<Object> result;
public boolean containsPutForExternalRead;
- public InvalidationFilterVisitor(int maxSetSize)
- {
+ public InvalidationFilterVisitor(int maxSetSize) {
result = new HashSet<Object>(maxSetSize);
}
@Override
- public Object visitPutKeyValueCommand(InvocationContext ctx, PutKeyValueCommand command) throws Throwable
- {
+ public Object visitPutKeyValueCommand(InvocationContext ctx, PutKeyValueCommand command) throws Throwable {
result.add(command.getKey());
return null;
}
@Override
- public Object visitRemoveCommand(InvocationContext ctx, RemoveCommand command) throws Throwable
- {
+ public Object visitRemoveCommand(InvocationContext ctx, RemoveCommand command) throws Throwable {
result.add(command.getKey());
return null;
}
}
- protected void invalidateAcrossCluster(Object fqn, Object workspace, boolean synchronous, InvocationContext ctx) throws Throwable
- {
- if (!isLocalModeForced(ctx))
- {
+ protected void invalidateAcrossCluster(Object fqn, Object workspace, boolean synchronous, InvocationContext ctx) throws Throwable {
+ if (!isLocalModeForced(ctx)) {
// increment invalidations counter if statistics maintained
incrementInvalidations();
InvalidateCommand command = commandsFactory.buildInvalidateCommand(fqn);
@@ -235,40 +204,34 @@
}
}
- private void incrementInvalidations()
- {
+ private void incrementInvalidations() {
if (getStatisticsEnabled()) invalidations++;
}
@ManagedOperation
- public void resetStatistics()
- {
+ public void resetStatistics() {
invalidations = 0;
}
@ManagedOperation
- public Map<String, Object> dumpStatistics()
- {
+ public Map<String, Object> dumpStatistics() {
Map<String, Object> retval = new HashMap<String, Object>();
retval.put("Invalidations", invalidations);
return retval;
}
@ManagedAttribute
- public boolean getStatisticsEnabled()
- {
+ public boolean getStatisticsEnabled() {
return this.statsEnabled;
}
@ManagedAttribute
- public void setStatisticsEnabled(boolean enabled)
- {
+ public void setStatisticsEnabled(boolean enabled) {
this.statsEnabled = enabled;
}
@ManagedAttribute(description = "number of invalidations")
- public long getInvalidations()
- {
+ public long getInvalidations() {
return invalidations;
}
}
\ No newline at end of file
Modified: core/branches/flat/src/main/java/org/horizon/interceptors/InvocationContextInterceptor.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/interceptors/InvocationContextInterceptor.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/interceptors/InvocationContextInterceptor.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -26,7 +26,11 @@
import org.horizon.commands.tx.CommitCommand;
import org.horizon.commands.tx.PrepareCommand;
import org.horizon.commands.tx.RollbackCommand;
-import org.horizon.commands.write.*;
+import org.horizon.commands.write.ClearCommand;
+import org.horizon.commands.write.PutKeyValueCommand;
+import org.horizon.commands.write.PutMapCommand;
+import org.horizon.commands.write.RemoveCommand;
+import org.horizon.commands.write.ReplaceCommand;
import org.horizon.config.Option;
import org.horizon.context.InvocationContext;
import org.horizon.context.TransactionContext;
@@ -38,73 +42,61 @@
import javax.transaction.SystemException;
import javax.transaction.Transaction;
-public class InvocationContextInterceptor extends BaseTransactionalContextInterceptor
-{
+public class InvocationContextInterceptor extends BaseTransactionalContextInterceptor {
private RPCManager rpcManager;
@Inject
- public void setDependencies(RPCManager rpcManager)
- {
+ public void setDependencies(RPCManager rpcManager) {
this.rpcManager = rpcManager;
}
@Override
- public Object visitPutMapCommand(InvocationContext ctx, PutMapCommand command) throws Throwable
- {
+ public Object visitPutMapCommand(InvocationContext ctx, PutMapCommand command) throws Throwable {
return handleAll(ctx, command, ctx.getGlobalTransaction(), false);
}
@Override
- public Object visitPutKeyValueCommand(InvocationContext ctx, PutKeyValueCommand command) throws Throwable
- {
+ public Object visitPutKeyValueCommand(InvocationContext ctx, PutKeyValueCommand command) throws Throwable {
return handleAll(ctx, command, ctx.getGlobalTransaction(), true);
}
@Override
- public Object visitClearCommand(InvocationContext ctx, ClearCommand command) throws Throwable
- {
+ public Object visitClearCommand(InvocationContext ctx, ClearCommand command) throws Throwable {
return handleAll(ctx, command, ctx.getGlobalTransaction(), false);
}
@Override
- public Object visitRemoveCommand(InvocationContext ctx, RemoveCommand command) throws Throwable
- {
+ public Object visitRemoveCommand(InvocationContext ctx, RemoveCommand command) throws Throwable {
return handleAll(ctx, command, ctx.getGlobalTransaction(), false);
}
@Override
- public Object visitReplaceCommand(InvocationContext ctx, ReplaceCommand command) throws Throwable
- {
+ public Object visitReplaceCommand(InvocationContext ctx, ReplaceCommand command) throws Throwable {
return handleAll(ctx, command, ctx.getGlobalTransaction(), false);
}
@Override
- public Object visitPrepareCommand(InvocationContext ctx, PrepareCommand command) throws Throwable
- {
+ public Object visitPrepareCommand(InvocationContext ctx, PrepareCommand command) throws Throwable {
return handleAll(ctx, command, command.getGlobalTransaction(), true);
}
@Override
- public Object visitRollbackCommand(InvocationContext ctx, RollbackCommand command) throws Throwable
- {
+ public Object visitRollbackCommand(InvocationContext ctx, RollbackCommand command) throws Throwable {
return handleAll(ctx, command, command.getGlobalTransaction(), true);
}
@Override
- public Object visitCommitCommand(InvocationContext ctx, CommitCommand command) throws Throwable
- {
+ public Object visitCommitCommand(InvocationContext ctx, CommitCommand command) throws Throwable {
return handleAll(ctx, command, command.getGlobalTransaction(), true);
}
@Override
- public Object handleDefault(InvocationContext ctx, VisitableCommand command) throws Throwable
- {
+ public Object handleDefault(InvocationContext ctx, VisitableCommand command) throws Throwable {
return handleAll(ctx, command, null, true);
}
@SuppressWarnings("deprecation")
- private Object handleAll(InvocationContext ctx, VisitableCommand command, GlobalTransaction gtx, boolean scrubContextOnCompletion) throws Throwable
- {
+ private Object handleAll(InvocationContext ctx, VisitableCommand command, GlobalTransaction gtx, boolean scrubContextOnCompletion) throws Throwable {
Option optionOverride = ctx.getOptionOverrides();
boolean suppressExceptions = false;
Transaction suspendedTransaction = null;
@@ -112,64 +104,49 @@
if (trace) log.trace("Invoked with command " + command + " and InvocationContext [" + ctx + "]");
- try
- {
- if (txManager != null)
- {
+ try {
+ if (txManager != null) {
Transaction tx = getTransaction();
GlobalTransaction realGtx = getGlobalTransaction(tx, gtx);
if (tx == null && realGtx != null && realGtx.isRemote()) tx = txTable.getLocalTransaction(gtx);
setTransactionalContext(tx, realGtx, null, ctx);
- }
- else
- {
+ } else {
setTransactionalContext(null, null, null, ctx);
}
- if (optionOverride != null)
- {
- if (optionOverride.isFailSilently())
- {
+ if (optionOverride != null) {
+ if (optionOverride.isFailSilently()) {
log.debug("FAIL_SILENTLY Option is present - suspending any ongoing transaction.");
suppressExceptions = true;
- if (ctx.getTransaction() != null)
- {
+ if (ctx.getTransaction() != null) {
suspendedTransaction = txManager.suspend();
setTransactionalContext(null, null, null, ctx);
if (trace) log.trace("Suspending transaction " + suspendedTransaction);
resumeSuspended = true;
- }
- else
- {
+ } else {
if (trace) log.trace("No ongoing transaction to suspend");
}
}
}
Object retval;
- try
- {
+ try {
return invokeNextInterceptor(ctx, command);
}
- catch (Throwable th)
- {
+ catch (Throwable th) {
retval = th;
// if fail silently return a null
if (suppressExceptions) return null;
Throwable t = (Throwable) retval;
- if (t instanceof RuntimeException && t.getCause() != null)
- {
+ if (t instanceof RuntimeException && t.getCause() != null) {
throw t.getCause();
- }
- else
- {
+ } else {
throw t;
}
}
// assume we're the first interceptor in the chain. Handle the exception-throwing.
}
- finally
- {
+ finally {
// TODO: scope upgrading should happen transparently
/*
* we should scrub txs after every call to prevent race conditions
@@ -184,14 +161,10 @@
// if this is a prepare, opt prepare or
- if (resumeSuspended)
- {
+ if (resumeSuspended) {
txManager.resume(suspendedTransaction);
- }
- else
- {
- if (ctx.getTransaction() != null && (TransactionTable.isValid(ctx.getTransaction())))
- {
+ } else {
+ if (ctx.getTransaction() != null && (TransactionTable.isValid(ctx.getTransaction()))) {
copyInvocationScopeOptionsToTxScope(ctx);
}
}
@@ -203,23 +176,18 @@
}
}
- private GlobalTransaction getGlobalTransaction(Transaction tx, GlobalTransaction gtx)
- {
+ private GlobalTransaction getGlobalTransaction(Transaction tx, GlobalTransaction gtx) {
if (gtx == null) gtx = txTable.getCurrentTransaction(tx, false);
if (gtx != null) gtx.setRemote(isRemoteGlobalTx(gtx));
return gtx;
}
- private Transaction getTransaction() throws SystemException
- {
+ private Transaction getTransaction() throws SystemException {
// this creates a context if one did not exist.
- if (txManager == null)
- {
+ if (txManager == null) {
if (trace) log.trace("no transaction manager configured, setting tx as null.");
return null;
- }
- else
- {
+ } else {
return txManager.getTransaction();
}
}
@@ -230,17 +198,14 @@
* @param gtx
* @return true if the gtx is remote, false if it originated locally.
*/
- private boolean isRemoteGlobalTx(GlobalTransaction gtx)
- {
+ private boolean isRemoteGlobalTx(GlobalTransaction gtx) {
return gtx != null && (gtx.getAddress() != null) && (!gtx.getAddress().equals(rpcManager.getLocalAddress()));
}
- private void copyInvocationScopeOptionsToTxScope(InvocationContext ctx)
- {
+ private void copyInvocationScopeOptionsToTxScope(InvocationContext ctx) {
// notify the transaction tCtx that this override is in place.
TransactionContext tCtx = ctx.getTransactionContext();
- if (tCtx != null)
- {
+ if (tCtx != null) {
Option txScopeOption = new Option();
txScopeOption.setCacheModeLocal(ctx.getOptionOverrides() != null && ctx.getOptionOverrides().isCacheModeLocal());
txScopeOption.setSkipCacheStatusCheck(ctx.getOptionOverrides() != null && ctx.getOptionOverrides().isSkipCacheStatusCheck());
Modified: core/branches/flat/src/main/java/org/horizon/interceptors/LockingInterceptor.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/interceptors/LockingInterceptor.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/interceptors/LockingInterceptor.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -21,7 +21,6 @@
*/
package org.horizon.interceptors;
-import org.horizon.lock.IsolationLevel;
import org.horizon.commands.read.GetKeyValueCommand;
import org.horizon.commands.read.SizeCommand;
import org.horizon.commands.tx.CommitCommand;
@@ -40,6 +39,7 @@
import org.horizon.factories.annotations.Inject;
import org.horizon.factories.annotations.Start;
import org.horizon.interceptors.base.CommandInterceptor;
+import org.horizon.lock.IsolationLevel;
import org.horizon.lock.LockManager;
import java.util.ArrayList;
@@ -54,62 +54,50 @@
* @see <a href="http://wiki.jboss.org/wiki/JBossCacheMVCC">MVCC designs</a>
* @since 1.0
*/
-public class LockingInterceptor extends CommandInterceptor
-{
+public class LockingInterceptor extends CommandInterceptor {
LockManager lockManager;
DataContainer dataContainer;
EntryFactory entryFactory;
boolean useReadCommitted;
@Inject
- public void setDependencies(LockManager lockManager, DataContainer dataContainer, EntryFactory entryFactory)
- {
+ public void setDependencies(LockManager lockManager, DataContainer dataContainer, EntryFactory entryFactory) {
this.lockManager = lockManager;
this.dataContainer = dataContainer;
this.entryFactory = entryFactory;
}
@Start
- private void determineIsolationLevel()
- {
+ private void determineIsolationLevel() {
useReadCommitted = configuration.getIsolationLevel() == IsolationLevel.READ_COMMITTED;
}
@Override
- public Object visitCommitCommand(InvocationContext ctx, CommitCommand command) throws Throwable
- {
- try
- {
+ public Object visitCommitCommand(InvocationContext ctx, CommitCommand command) throws Throwable {
+ try {
return invokeNextInterceptor(ctx, command);
}
- finally
- {
+ finally {
transactionalCleanup(true, ctx);
}
}
@Override
- public Object visitRollbackCommand(InvocationContext ctx, RollbackCommand command) throws Throwable
- {
- try
- {
+ public Object visitRollbackCommand(InvocationContext ctx, RollbackCommand command) throws Throwable {
+ try {
return invokeNextInterceptor(ctx, command);
}
- finally
- {
+ finally {
transactionalCleanup(false, ctx);
}
}
@Override
- public Object visitPrepareCommand(InvocationContext ctx, PrepareCommand command) throws Throwable
- {
- try
- {
+ public Object visitPrepareCommand(InvocationContext ctx, PrepareCommand command) throws Throwable {
+ try {
return invokeNextInterceptor(ctx, command);
}
- finally
- {
+ finally {
if (command.isOnePhaseCommit()) transactionalCleanup(true, ctx);
}
}
@@ -117,29 +105,23 @@
// read commands
@Override
- public Object visitGetKeyValueCommand(InvocationContext ctx, GetKeyValueCommand command) throws Throwable
- {
- try
- {
+ public Object visitGetKeyValueCommand(InvocationContext ctx, GetKeyValueCommand command) throws Throwable {
+ try {
entryFactory.wrapEntryForReading(ctx, command.getKey(), true);
return invokeNextInterceptor(ctx, command);
}
- finally
- {
+ finally {
doAfterCall(ctx);
}
}
@Override
- public Object visitSizeCommand(InvocationContext ctx, SizeCommand command) throws Throwable
- {
- try
- {
+ public Object visitSizeCommand(InvocationContext ctx, SizeCommand command) throws Throwable {
+ try {
if (log.isDebugEnabled()) log.debug("No locking performed for SizeCommands");
return invokeNextInterceptor(ctx, command);
}
- finally
- {
+ finally {
doAfterCall(ctx);
}
}
@@ -147,129 +129,99 @@
// write commands
@Override
- public Object visitClearCommand(InvocationContext ctx, ClearCommand command) throws Throwable
- {
- try
- {
+ public Object visitClearCommand(InvocationContext ctx, ClearCommand command) throws Throwable {
+ try {
// get a snapshot of all keys in the data container
for (Object key : dataContainer.keySet()) entryFactory.wrapEntryForWriting(ctx, key, false, false);
return invokeNextInterceptor(ctx, command);
}
- finally
- {
+ finally {
doAfterCall(ctx);
}
}
@Override
- public Object visitEvictCommand(InvocationContext ctx, EvictCommand command) throws Throwable
- {
- try
- {
+ public Object visitEvictCommand(InvocationContext ctx, EvictCommand command) throws Throwable {
+ try {
entryFactory.wrapEntryForWriting(ctx, command.getKey(), false, true);
return invokeNextInterceptor(ctx, command);
}
- finally
- {
+ finally {
doAfterCall(ctx);
}
}
@Override
- public Object visitPutKeyValueCommand(InvocationContext ctx, PutKeyValueCommand command) throws Throwable
- {
- try
- {
+ public Object visitPutKeyValueCommand(InvocationContext ctx, PutKeyValueCommand command) throws Throwable {
+ try {
entryFactory.wrapEntryForWriting(ctx, command.getKey(), true, false);
Object o = invokeNextInterceptor(ctx, command);
return o;
}
- finally
- {
+ finally {
doAfterCall(ctx);
}
}
@Override
- public Object visitPutMapCommand(InvocationContext ctx, PutMapCommand command) throws Throwable
- {
- try
- {
- for (Object key : command.getMap().keySet())
- {
+ public Object visitPutMapCommand(InvocationContext ctx, PutMapCommand command) throws Throwable {
+ try {
+ for (Object key : command.getMap().keySet()) {
entryFactory.wrapEntryForWriting(ctx, key, true, false);
}
return invokeNextInterceptor(ctx, command);
}
- finally
- {
+ finally {
doAfterCall(ctx);
}
}
@Override
- public Object visitRemoveCommand(InvocationContext ctx, RemoveCommand command) throws Throwable
- {
- try
- {
+ public Object visitRemoveCommand(InvocationContext ctx, RemoveCommand command) throws Throwable {
+ try {
entryFactory.wrapEntryForWriting(ctx, command.getKey(), false, true);
return invokeNextInterceptor(ctx, command);
}
- finally
- {
+ finally {
doAfterCall(ctx);
}
}
@Override
- public Object visitReplaceCommand(InvocationContext ctx, ReplaceCommand command) throws Throwable
- {
- try
- {
+ public Object visitReplaceCommand(InvocationContext ctx, ReplaceCommand command) throws Throwable {
+ try {
entryFactory.wrapEntryForWriting(ctx, command.getKey(), false, true);
return invokeNextInterceptor(ctx, command);
}
- finally
- {
+ finally {
doAfterCall(ctx);
}
}
@SuppressWarnings("unchecked")
- private void doAfterCall(InvocationContext ctx)
- {
+ private void doAfterCall(InvocationContext ctx) {
// for non-transactional stuff.
- if (ctx.getTransactionContext() == null)
- {
+ if (ctx.getTransactionContext() == null) {
List<Object> locks;
- if (!(locks = ctx.getKeysLocked()).isEmpty())
- {
+ if (!(locks = ctx.getKeysLocked()).isEmpty()) {
cleanupLocks(locks, ctx, Thread.currentThread(), true);
- }
- else
- {
+ } else {
if (trace) log.trace("Nothing to do since there are no modifications in scope.");
}
- }
- else
- {
- if (useReadCommitted)
- {
+ } else {
+ if (useReadCommitted) {
Map<Object, MVCCEntry> lookedUpEntries = ctx.getLookedUpEntries();
- if (!lookedUpEntries.isEmpty())
- {
+ if (!lookedUpEntries.isEmpty()) {
// This should be a Set but we can use an ArrayList instead for efficiency since we know that the elements
// will always be unique as they are keys from a Map. Also, we know the maximum size so this ArrayList
// should never resize.
List<Object> keysToRemove = new ArrayList<Object>(lookedUpEntries.size());
- for (Map.Entry<Object, MVCCEntry> e : lookedUpEntries.entrySet())
- {
+ for (Map.Entry<Object, MVCCEntry> e : lookedUpEntries.entrySet()) {
if (!e.getValue().isChanged()) keysToRemove.add(e.getKey());
}
- if (!keysToRemove.isEmpty())
- {
+ if (!keysToRemove.isEmpty()) {
for (Object key : keysToRemove) ctx.removeLookedUpEntry(key);
}
}
@@ -277,16 +229,13 @@
}
}
- private void cleanupLocks(List<Object> keysLocked, InvocationContext ctx, Object owner, boolean commit)
- {
+ private void cleanupLocks(List<Object> keysLocked, InvocationContext ctx, Object owner, boolean commit) {
// clean up.
// unlocking needs to be done in reverse order.
ListIterator<Object> it = keysLocked.listIterator(keysLocked.size());
- if (commit)
- {
- while (it.hasPrevious())
- {
+ if (commit) {
+ while (it.hasPrevious()) {
Object key = it.previous();
MVCCEntry entry = ctx.lookupEntry(key);
// could be null with read-committed
@@ -295,11 +244,8 @@
if (trace) log.trace("Releasing lock on [" + key + "] for owner " + owner);
lockManager.unlock(key, owner);
}
- }
- else
- {
- while (it.hasPrevious())
- {
+ } else {
+ while (it.hasPrevious()) {
Object key = it.previous();
MVCCEntry entry = ctx.lookupEntry(key);
// could be null with read-committed
@@ -313,18 +259,14 @@
}
@SuppressWarnings("unchecked")
- private void transactionalCleanup(boolean commit, InvocationContext ctx)
- {
- if (ctx.getTransactionContext() != null)
- {
+ private void transactionalCleanup(boolean commit, InvocationContext ctx) {
+ if (ctx.getTransactionContext() != null) {
List<Object> locks = ctx.getTransactionContext().getKeysLocked();
if (!locks.isEmpty())
cleanupLocks(locks, ctx, ctx.getGlobalTransaction(), commit);
else if (trace)
log.trace("At transaction boundary (" + (commit ? "commit" : "rollback") + "), and we have no locks in context!");
- }
- else
- {
+ } else {
throw new IllegalStateException("Attempting to do a commit or rollback but there is no transactional context in scope. " + ctx);
}
}
Modified: core/branches/flat/src/main/java/org/horizon/interceptors/MarshalledValueInterceptor.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/interceptors/MarshalledValueInterceptor.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/interceptors/MarshalledValueInterceptor.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -29,7 +29,6 @@
import org.horizon.interceptors.base.CommandInterceptor;
import org.horizon.marshall.MarshalledValue;
import org.horizon.marshall.MarshalledValueHelper;
-//import org.jboss.starobrno.marshall.MarshalledValueHelper;
import java.io.IOException;
import java.io.NotSerializableException;
@@ -40,21 +39,20 @@
import java.util.Set;
/**
- * Interceptor that handles the wrapping and unwrapping of cached data using {@link org.horizon.marshall.MarshalledValue}s.
- * Known "excluded" types are not wrapped/unwrapped, which at this time include {@link String}, Java primitives
- * and their Object wrappers, as well as arrays of excluded types.
+ * Interceptor that handles the wrapping and unwrapping of cached data using {@link
+ * org.horizon.marshall.MarshalledValue}s. Known "excluded" types are not wrapped/unwrapped, which at this time include
+ * {@link String}, Java primitives and their Object wrappers, as well as arrays of excluded types.
* <p/>
- * The {@link org.horizon.marshall.MarshalledValue} wrapper handles lazy deserialization from byte array representations.
+ * The {@link org.horizon.marshall.MarshalledValue} wrapper handles lazy deserialization from byte array
+ * representations.
*
* @author Manik Surtani (<a href="mailto:manik at jboss.org">manik at jboss.org</a>)
* @see org.horizon.marshall.MarshalledValue
* @since 1.0
*/
-public class MarshalledValueInterceptor extends CommandInterceptor
-{
+public class MarshalledValueInterceptor extends CommandInterceptor {
@Override
- public Object visitPutMapCommand(InvocationContext ctx, PutMapCommand command) throws Throwable
- {
+ public Object visitPutMapCommand(InvocationContext ctx, PutMapCommand command) throws Throwable {
Set<MarshalledValue> marshalledValues = new HashSet<MarshalledValue>();
command.setMap(wrapMap(command.getMap(), marshalledValues, ctx));
@@ -63,16 +61,13 @@
}
@Override
- public Object visitPutKeyValueCommand(InvocationContext ctx, PutKeyValueCommand command) throws Throwable
- {
+ public Object visitPutKeyValueCommand(InvocationContext ctx, PutKeyValueCommand command) throws Throwable {
Set<MarshalledValue> marshalledValues = new HashSet<MarshalledValue>();
- if (!MarshalledValueHelper.isTypeExcluded(command.getKey().getClass()))
- {
+ if (!MarshalledValueHelper.isTypeExcluded(command.getKey().getClass())) {
Object newKey = createAndAddMarshalledValue(command.getKey(), marshalledValues, ctx);
command.setKey(newKey);
}
- if (!MarshalledValueHelper.isTypeExcluded(command.getValue().getClass()))
- {
+ if (!MarshalledValueHelper.isTypeExcluded(command.getValue().getClass())) {
Object value = createAndAddMarshalledValue(command.getValue(), marshalledValues, ctx);
command.setValue(value);
}
@@ -81,11 +76,9 @@
}
@Override
- public Object visitRemoveCommand(InvocationContext ctx, RemoveCommand command) throws Throwable
- {
+ public Object visitRemoveCommand(InvocationContext ctx, RemoveCommand command) throws Throwable {
Set<MarshalledValue> marshalledValues = new HashSet<MarshalledValue>();
- if (!MarshalledValueHelper.isTypeExcluded(command.getKey().getClass()))
- {
+ if (!MarshalledValueHelper.isTypeExcluded(command.getKey().getClass())) {
Object value = createAndAddMarshalledValue(command.getKey(), marshalledValues, ctx);
command.setKey(value);
}
@@ -94,11 +87,9 @@
}
@Override
- public Object visitGetKeyValueCommand(InvocationContext ctx, GetKeyValueCommand command) throws Throwable
- {
+ public Object visitGetKeyValueCommand(InvocationContext ctx, GetKeyValueCommand command) throws Throwable {
Set<MarshalledValue> marshalledValues = new HashSet<MarshalledValue>();
- if (!MarshalledValueHelper.isTypeExcluded(command.getKey().getClass()))
- {
+ if (!MarshalledValueHelper.isTypeExcluded(command.getKey().getClass())) {
Object value = createAndAddMarshalledValue(command.getKey(), marshalledValues, ctx);
command.setKey(value);
}
@@ -107,8 +98,7 @@
}
private Object compactAndProcessRetVal(Set<MarshalledValue> marshalledValues, Object retVal)
- throws IOException, ClassNotFoundException
- {
+ throws IOException, ClassNotFoundException {
if (trace) log.trace("Compacting MarshalledValues created");
for (MarshalledValue mv : marshalledValues) mv.compact(false, false);
@@ -116,10 +106,8 @@
}
private Object processRetVal(Object retVal)
- throws IOException, ClassNotFoundException
- {
- if (retVal instanceof MarshalledValue)
- {
+ throws IOException, ClassNotFoundException {
+ if (retVal instanceof MarshalledValue) {
if (trace) log.trace("Return value is a MarshalledValue. Unwrapping.");
retVal = ((MarshalledValue) retVal).get();
}
@@ -127,27 +115,23 @@
}
@SuppressWarnings("unchecked")
- protected Map wrapMap(Map<Object, Object> m, Set<MarshalledValue> marshalledValues, InvocationContext ctx) throws NotSerializableException
- {
- if (m == null)
- {
+ protected Map wrapMap(Map<Object, Object> m, Set<MarshalledValue> marshalledValues, InvocationContext ctx) throws NotSerializableException {
+ if (m == null) {
if (trace) log.trace("Map is nul; returning an empty map.");
return Collections.emptyMap();
}
if (trace) log.trace("Wrapping map contents of argument " + m);
Map copy = new HashMap();
- for (Map.Entry me : m.entrySet())
- {
+ for (Map.Entry me : m.entrySet()) {
Object key = me.getKey();
Object value = me.getValue();
copy.put((key == null || MarshalledValueHelper.isTypeExcluded(key.getClass())) ? key : createAndAddMarshalledValue(key, marshalledValues, ctx),
- (value == null || MarshalledValueHelper.isTypeExcluded(value.getClass())) ? value : createAndAddMarshalledValue(value, marshalledValues, ctx));
+ (value == null || MarshalledValueHelper.isTypeExcluded(value.getClass())) ? value : createAndAddMarshalledValue(value, marshalledValues, ctx));
}
return copy;
}
- protected MarshalledValue createAndAddMarshalledValue(Object toWrap, Set<MarshalledValue> marshalledValues, InvocationContext ctx) throws NotSerializableException
- {
+ protected MarshalledValue createAndAddMarshalledValue(Object toWrap, Set<MarshalledValue> marshalledValues, InvocationContext ctx) throws NotSerializableException {
MarshalledValue mv = new MarshalledValue(toWrap);
marshalledValues.add(mv);
if (!ctx.isOriginLocal()) mv.setEqualityPreferenceForInstance(false);
Modified: core/branches/flat/src/main/java/org/horizon/interceptors/NotificationInterceptor.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/interceptors/NotificationInterceptor.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/interceptors/NotificationInterceptor.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -34,19 +34,16 @@
* @author <a href="mailto:manik at jboss.org">Manik Surtani</a>
* @since 1.0
*/
-public class NotificationInterceptor extends BaseTransactionalContextInterceptor
-{
+public class NotificationInterceptor extends BaseTransactionalContextInterceptor {
private Notifier notifier;
@Inject
- public void injectDependencies(Notifier notifier)
- {
+ public void injectDependencies(Notifier notifier) {
this.notifier = notifier;
}
@Override
- public Object visitPrepareCommand(InvocationContext ctx, PrepareCommand command) throws Throwable
- {
+ public Object visitPrepareCommand(InvocationContext ctx, PrepareCommand command) throws Throwable {
Object retval = invokeNextInterceptor(ctx, command);
if (command.isOnePhaseCommit()) notifier.notifyTransactionCompleted(ctx.getTransaction(), true, ctx);
@@ -54,16 +51,14 @@
}
@Override
- public Object visitCommitCommand(InvocationContext ctx, CommitCommand command) throws Throwable
- {
+ public Object visitCommitCommand(InvocationContext ctx, CommitCommand command) throws Throwable {
Object retval = invokeNextInterceptor(ctx, command);
notifier.notifyTransactionCompleted(ctx.getTransaction(), true, ctx);
return retval;
}
@Override
- public Object visitRollbackCommand(InvocationContext ctx, RollbackCommand command) throws Throwable
- {
+ public Object visitRollbackCommand(InvocationContext ctx, RollbackCommand command) throws Throwable {
Object retval = invokeNextInterceptor(ctx, command);
notifier.notifyTransactionCompleted(ctx.getTransaction(), false, ctx);
return retval;
Modified: core/branches/flat/src/main/java/org/horizon/interceptors/ReplicationInterceptor.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/interceptors/ReplicationInterceptor.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/interceptors/ReplicationInterceptor.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -25,7 +25,11 @@
import org.horizon.commands.tx.CommitCommand;
import org.horizon.commands.tx.PrepareCommand;
import org.horizon.commands.tx.RollbackCommand;
-import org.horizon.commands.write.*;
+import org.horizon.commands.write.ClearCommand;
+import org.horizon.commands.write.PutKeyValueCommand;
+import org.horizon.commands.write.PutMapCommand;
+import org.horizon.commands.write.RemoveCommand;
+import org.horizon.commands.write.ReplaceCommand;
import org.horizon.config.Configuration;
import org.horizon.context.InvocationContext;
import org.horizon.context.TransactionContext;
@@ -33,32 +37,26 @@
import org.horizon.transaction.GlobalTransaction;
/**
- * Takes care of replicating modifications to other nodes in a cluster. Also
- * listens for prepare(), commit() and rollback() messages which are received
- * 'side-ways' (see docs/design/Refactoring.txt).
+ * Takes care of replicating modifications to other nodes in a cluster. Also listens for prepare(), commit() and
+ * rollback() messages which are received 'side-ways' (see docs/design/Refactoring.txt).
*
* @author Bela Ban
- *
* @since 1.0
*/
-public class ReplicationInterceptor extends BaseRpcInterceptor
-{
+public class ReplicationInterceptor extends BaseRpcInterceptor {
@Override
- public Object visitCommitCommand(InvocationContext ctx, CommitCommand command) throws Throwable
- {
+ public Object visitCommitCommand(InvocationContext ctx, CommitCommand command) throws Throwable {
if (!skipReplicationOfTransactionMethod(ctx))
replicateCall(ctx, command, configuration.isSyncCommitPhase(), ctx.getOptionOverrides(), true);
return invokeNextInterceptor(ctx, command);
}
@Override
- public Object visitPrepareCommand(InvocationContext ctx, PrepareCommand command) throws Throwable
- {
+ public Object visitPrepareCommand(InvocationContext ctx, PrepareCommand command) throws Throwable {
Object retVal = invokeNextInterceptor(ctx, command);
TransactionContext transactionContext = ctx.getTransactionContext();
- if (transactionContext.hasLocalModifications())
- {
+ if (transactionContext.hasLocalModifications()) {
PrepareCommand replicablePrepareCommand = command.copy(); // makre sure we remove any "local" transactions
replicablePrepareCommand.removeModifications(transactionContext.getLocalModifications());
command = replicablePrepareCommand;
@@ -69,93 +67,75 @@
}
@Override
- public Object visitRollbackCommand(InvocationContext ctx, RollbackCommand command) throws Throwable
- {
- if (!skipReplicationOfTransactionMethod(ctx) && !ctx.isLocalRollbackOnly())
- {
+ public Object visitRollbackCommand(InvocationContext ctx, RollbackCommand command) throws Throwable {
+ if (!skipReplicationOfTransactionMethod(ctx) && !ctx.isLocalRollbackOnly()) {
replicateCall(ctx, command, configuration.isSyncRollbackPhase(), ctx.getOptionOverrides());
}
return invokeNextInterceptor(ctx, command);
}
@Override
- public Object visitPutKeyValueCommand(InvocationContext ctx, PutKeyValueCommand command) throws Throwable
- {
+ public Object visitPutKeyValueCommand(InvocationContext ctx, PutKeyValueCommand command) throws Throwable {
return handleCrudMethod(ctx, command);
}
@Override
- public Object visitPutMapCommand(InvocationContext ctx, PutMapCommand command) throws Throwable
- {
+ public Object visitPutMapCommand(InvocationContext ctx, PutMapCommand command) throws Throwable {
return handleCrudMethod(ctx, command);
}
@Override
- public Object visitRemoveCommand(InvocationContext ctx, RemoveCommand command) throws Throwable
- {
+ public Object visitRemoveCommand(InvocationContext ctx, RemoveCommand command) throws Throwable {
return handleCrudMethod(ctx, command);
}
@Override
- public Object visitClearCommand(InvocationContext ctx, ClearCommand command) throws Throwable
- {
+ public Object visitClearCommand(InvocationContext ctx, ClearCommand command) throws Throwable {
return handleCrudMethod(ctx, command);
}
@Override
- public Object visitReplaceCommand(InvocationContext ctx, ReplaceCommand command) throws Throwable
- {
+ public Object visitReplaceCommand(InvocationContext ctx, ReplaceCommand command) throws Throwable {
return handleCrudMethod(ctx, command);
}
/**
- * If we are within one transaction we won't do any replication as replication would only be performed at commit time.
- * If the operation didn't originate locally we won't do any replication either.
+ * If we are within one transaction we won't do any replication as replication would only be performed at commit
+ * time. If the operation didn't originate locally we won't do any replication either.
*/
private Object handleCrudMethod(InvocationContext ctx, VisitableCommand command)
- throws Throwable
- {
+ throws Throwable {
boolean local = isLocalModeForced(ctx);
if (local && ctx.getTransaction() == null) return invokeNextInterceptor(ctx, command);
// FIRST pass this call up the chain. Only if it succeeds (no exceptions) locally do we attempt to replicate.
Object returnValue = invokeNextInterceptor(ctx, command);
- if (ctx.getTransaction() == null && ctx.isOriginLocal())
- {
- if (trace)
- {
+ if (ctx.getTransaction() == null && ctx.isOriginLocal()) {
+ if (trace) {
log.trace("invoking method " + command.getClass().getSimpleName() + ", members=" + rpcManager.getMembers() + ", mode=" +
configuration.getCacheMode() + ", exclude_self=" + true + ", timeout=" +
configuration.getSyncReplTimeout());
}
replicateCall(ctx, command, isSynchronous(ctx.getOptionOverrides()), ctx.getOptionOverrides());
- }
- else
- {
+ } else {
if (local) ctx.getTransactionContext().addLocalModification(command);
}
return returnValue;
}
/**
- * Calls prepare(GlobalTransaction,List,org.jgroups.Address,boolean)) in all members except self.
- * Waits for all responses. If one of the members failed to prepare, its return value
- * will be an exception. If there is one exception we rethrow it. This will mark the
- * current transaction as rolled back, which will cause the
- * afterCompletion(int) callback to have a status
- * of <tt>MARKED_ROLLBACK</tt>. When we get that call, we simply roll back the
- * transaction.<br/>
- * If everything runs okay, the afterCompletion(int)
- * callback will trigger the @link #runCommitPhase(GlobalTransaction)).
- * <br/>
+ * Calls prepare(GlobalTransaction,List,org.jgroups.Address,boolean)) in all members except self. Waits for all
+ * responses. If one of the members failed to prepare, its return value will be an exception. If there is one
+ * exception we rethrow it. This will mark the current transaction as rolled back, which will cause the
+ * afterCompletion(int) callback to have a status of <tt>MARKED_ROLLBACK</tt>. When we get that call, we simply roll
+ * back the transaction.<br/> If everything runs okay, the afterCompletion(int) callback will trigger the @link
+ * #runCommitPhase(GlobalTransaction)). <br/>
*
* @throws Exception
*/
- protected void runPreparePhase(PrepareCommand prepareMethod, GlobalTransaction gtx, InvocationContext ctx) throws Throwable
- {
+ protected void runPreparePhase(PrepareCommand prepareMethod, GlobalTransaction gtx, InvocationContext ctx) throws Throwable {
boolean async = configuration.getCacheMode() == Configuration.CacheMode.REPL_ASYNC;
- if (trace)
- {
+ if (trace) {
log.trace("(" + rpcManager.getLocalAddress() + "): running remote prepare for global tx " + gtx + " with async mode=" + async);
}
Modified: core/branches/flat/src/main/java/org/horizon/interceptors/TxInterceptor.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/interceptors/TxInterceptor.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/interceptors/TxInterceptor.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -22,6 +22,8 @@
package org.horizon.interceptors;
import org.horizon.CacheException;
+import org.horizon.annotations.ManagedAttribute;
+import org.horizon.annotations.ManagedOperation;
import org.horizon.commands.CommandsFactory;
import org.horizon.commands.ReplicableCommand;
import org.horizon.commands.VisitableCommand;
@@ -35,8 +37,6 @@
import org.horizon.factories.annotations.Inject;
import org.horizon.factories.context.ContextFactory;
import org.horizon.invocation.InvocationContextContainer;
-import org.horizon.annotations.ManagedAttribute;
-import org.horizon.annotations.ManagedOperation;
import org.horizon.lock.LockManager;
import org.horizon.notifications.Notifier;
import org.horizon.remoting.RPCManager;
@@ -45,22 +45,28 @@
import org.horizon.transaction.TransactionTable;
import org.horizon.util.concurrent.ConcurrentHashSet;
-import javax.transaction.*;
-import java.util.*;
+import javax.transaction.InvalidTransactionException;
+import javax.transaction.Status;
+import javax.transaction.Synchronization;
+import javax.transaction.SystemException;
+import javax.transaction.Transaction;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
/**
- * This interceptor is the new default at the head of all interceptor chains,
- * and makes transactional attributes available to all interceptors in the chain.
- * This interceptor is also responsible for registering for synchronisation on
- * transaction completion.
+ * This interceptor is the new default at the head of all interceptor chains, and makes transactional attributes
+ * available to all interceptors in the chain. This interceptor is also responsible for registering for synchronisation
+ * on transaction completion.
*
* @author <a href="mailto:manik at jboss.org">Manik Surtani (manik at jboss.org)</a>
* @author <a href="mailto:stevew at jofti.com">Steve Woodcock (stevew at jofti.com)</a>
* @since 1.0
*/
-public class TxInterceptor extends BaseTransactionalContextInterceptor
-{
+public class TxInterceptor extends BaseTransactionalContextInterceptor {
protected CommandsFactory commandsFactory;
protected RPCManager rpcManager;
private Notifier notifier;
@@ -83,8 +89,7 @@
@Inject
public void intialize(RPCManager rpcManager, ContextFactory contextFactory,
Notifier notifier, InvocationContextContainer icc,
- CommandsFactory factory, ComponentRegistry componentRegistry, LockManager lockManager)
- {
+ CommandsFactory factory, ComponentRegistry componentRegistry, LockManager lockManager) {
this.contextFactory = contextFactory;
this.commandsFactory = factory;
this.rpcManager = rpcManager;
@@ -96,27 +101,21 @@
}
@Override
- public Object visitPrepareCommand(InvocationContext ctx, PrepareCommand command) throws Throwable
- {
+ public Object visitPrepareCommand(InvocationContext ctx, PrepareCommand command) throws Throwable {
Object result = null;
// this is a prepare, commit, or rollback.
if (log.isDebugEnabled()) log.debug("Got gtx from invocation context " + ctx.getGlobalTransaction());
- try
- {
- if (ctx.getGlobalTransaction().isRemote())
- {
+ try {
+ if (ctx.getGlobalTransaction().isRemote()) {
result = handleRemotePrepare(ctx, command);
if (getStatisticsEnabled()) prepares++;
- }
- else
- {
+ } else {
if (trace) log.trace("received my own message (discarding it)");
result = null;
}
}
- catch (Throwable e)
- {
+ catch (Throwable e) {
ctx.throwIfNeeded(e);
}
@@ -124,25 +123,20 @@
}
@Override
- public Object visitCommitCommand(InvocationContext ctx, CommitCommand command) throws Throwable
- {
- if (!ctx.getGlobalTransaction().isRemote())
- {
+ public Object visitCommitCommand(InvocationContext ctx, CommitCommand command) throws Throwable {
+ if (!ctx.getGlobalTransaction().isRemote()) {
if (trace) log.trace("received my own message (discarding it)");
return null;
}
- try
- {
+ try {
if (trace) log.trace("(" + rpcManager.getLocalAddress() + ") call on command [" + command + "]");
GlobalTransaction gtx = ctx.getGlobalTransaction();
Transaction ltx = txTable.getLocalTransaction(gtx, true);
// disconnect if we have a current tx associated
Transaction currentTx = txManager.getTransaction();
boolean resumeCurrentTxOnCompletion = false;
- try
- {
- if (!ltx.equals(currentTx))
- {
+ try {
+ if (!ltx.equals(currentTx)) {
currentTx = txManager.suspend();
resumeCurrentTxOnCompletion = true;
txManager.resume(ltx);
@@ -153,11 +147,9 @@
txManager.commit();
if (getStatisticsEnabled()) commits++;
}
- finally
- {
+ finally {
//resume the old transaction if we suspended it
- if (resumeCurrentTxOnCompletion)
- {
+ if (resumeCurrentTxOnCompletion) {
resumeTransactionOnCompletion(ctx, currentTx);
}
// remove from local lists.
@@ -167,28 +159,23 @@
}
if (log.isDebugEnabled()) log.debug("Finished remote rollback method for " + gtx);
}
- catch (Throwable throwable)
- {
+ catch (Throwable throwable) {
ctx.throwIfNeeded(throwable);
}
return null;
}
@Override
- public Object visitRollbackCommand(InvocationContext ctx, RollbackCommand command) throws Throwable
- {
- if (!ctx.getGlobalTransaction().isRemote())
- {
+ public Object visitRollbackCommand(InvocationContext ctx, RollbackCommand command) throws Throwable {
+ if (!ctx.getGlobalTransaction().isRemote()) {
if (trace) log.trace("received my own message (discarding it)");
return null;
}
- try
- {
+ try {
if (trace) log.trace("(" + rpcManager.getLocalAddress() + ") call on command [" + command + "]");
GlobalTransaction gtx = ctx.getGlobalTransaction();
Transaction ltx = txTable.getLocalTransaction(gtx);
- if (ltx == null)
- {
+ if (ltx == null) {
log.warn("No local transaction for this remotely originating rollback. Possibly rolling back before a prepare call was broadcast?");
txTable.cleanup(gtx);
return null;
@@ -196,10 +183,8 @@
// disconnect if we have a current tx associated
Transaction currentTx = txManager.getTransaction();
boolean resumeCurrentTxOnCompletion = false;
- try
- {
- if (!ltx.equals(currentTx))
- {
+ try {
+ if (!ltx.equals(currentTx)) {
currentTx = txManager.suspend();
resumeCurrentTxOnCompletion = true;
txManager.resume(ltx);
@@ -210,11 +195,9 @@
txManager.rollback();
if (getStatisticsEnabled()) rollbacks++;
}
- finally
- {
+ finally {
//resume the old transaction if we suspended it
- if (resumeCurrentTxOnCompletion)
- {
+ if (resumeCurrentTxOnCompletion) {
resumeTransactionOnCompletion(ctx, currentTx);
}
@@ -226,8 +209,7 @@
}
if (log.isDebugEnabled()) log.debug("Finished remote commit/rollback method for " + gtx);
}
- catch (Throwable throwable)
- {
+ catch (Throwable throwable) {
ctx.throwIfNeeded(throwable);
}
@@ -235,21 +217,17 @@
}
@Override
- public Object handleDefault(InvocationContext ctx, VisitableCommand command) throws Throwable
- {
- try
- {
+ public Object handleDefault(InvocationContext ctx, VisitableCommand command) throws Throwable {
+ try {
return attachGtxAndPassUpChain(ctx, command);
}
- catch (Throwable throwable)
- {
+ catch (Throwable throwable) {
ctx.throwIfNeeded(throwable);
return null;
}
}
- protected Object attachGtxAndPassUpChain(InvocationContext ctx, VisitableCommand command) throws Throwable
- {
+ protected Object attachGtxAndPassUpChain(InvocationContext ctx, VisitableCommand command) throws Throwable {
Transaction tx = ctx.getTransaction();
if (tx != null) attachGlobalTransaction(ctx, tx, command);
return invokeNextInterceptor(ctx, command);
@@ -262,16 +240,15 @@
// --------------------------------------------------------------
/**
- * Handles a remotely originating prepare call, by creating a local transaction for the remote global transaction
- * and replaying modifications in this new local transaction.
+ * Handles a remotely originating prepare call, by creating a local transaction for the remote global transaction and
+ * replaying modifications in this new local transaction.
*
* @param ctx invocation context
* @param command prepare command
* @return result of the prepare, typically a null.
* @throws Throwable in the event of problems.
*/
- private Object handleRemotePrepare(InvocationContext ctx, PrepareCommand command) throws Throwable
- {
+ private Object handleRemotePrepare(InvocationContext ctx, PrepareCommand command) throws Throwable {
// the InvocationContextInterceptor would have set this for us
GlobalTransaction gtx = ctx.getGlobalTransaction();
@@ -282,10 +259,8 @@
TransactionContext transactionContext;
Object retval = null;
boolean success = false;
- try
- {
- if (ltx == null)
- {
+ try {
+ if (ltx == null) {
if (currentTx != null) txManager.suspend();
// create a new local transaction
ltx = createLocalTx();
@@ -297,16 +272,13 @@
if (log.isDebugEnabled())
log.debug("Started new local tx as result of remote prepare: local tx=" + ltx + " (status=" + ltx.getStatus() + "), gtx=" + gtx);
- }
- else
- {
+ } else {
//this should be valid
if (!TransactionTable.isValid(ltx))
throw new CacheException("Transaction " + ltx + " not in correct state to be prepared");
//associate this thread with the local transaction associated with the global transaction, IF the localTx is NOT the current tx.
- if (currentTx == null || !ltx.equals(currentTx))
- {
+ if (currentTx == null || !ltx.equals(currentTx)) {
if (trace) log.trace("Suspending current tx " + currentTx);
txManager.suspend();
txManager.resume(ltx);
@@ -317,8 +289,7 @@
// below will need this transactionContext to add their modifications
// under the GlobalTx key
transactionContext = txTable.getTransactionContext(gtx);
- if (transactionContext == null)
- {
+ if (transactionContext == null) {
// create a new transaction transactionContext
if (log.isDebugEnabled()) log.debug("creating new tx transactionContext");
transactionContext = contextFactory.createTransactionContext(ltx);
@@ -344,57 +315,43 @@
success = true; // no exceptions were thrown above!!
// now pass the prepare command up the chain as well.
- if (command.isOnePhaseCommit())
- {
+ if (command.isOnePhaseCommit()) {
if (trace)
log.trace("Using one-phase prepare. Not propagating the prepare call up the stack until called to do so by the sync handler.");
- }
- else
- {
+ } else {
// now pass up the prepare method itself.
invokeNextInterceptor(ctx, command);
}
// JBCACHE-361 Confirm that the transaction is ACTIVE
assertTxIsStillValid(ltx);
}
- finally
- {
+ finally {
// if we are running a one-phase commit, perform a commit or rollback now.
if (trace) log.trace("Are we running a 1-phase commit? " + command.isOnePhaseCommit());
- if (command.isOnePhaseCommit())
- {
- try
- {
- if (success)
- {
+ if (command.isOnePhaseCommit()) {
+ try {
+ if (success) {
ltx.commit();
- }
- else
- {
+ } else {
ltx.rollback();
}
}
- catch (Throwable t)
- {
+ catch (Throwable t) {
log.error("Commit/rollback failed.", t);
- if (success)
- {
+ if (success) {
// try another rollback...
- try
- {
+ try {
log.info("Attempting anotehr rollback");
//invokeOnePhaseCommitMethod(globalTransaction, modifications.size() > 0, false);
ltx.rollback();
}
- catch (Throwable t2)
- {
+ catch (Throwable t2) {
log.error("Unable to rollback", t2);
}
}
}
- finally
- {
+ finally {
transactions.remove(ltx);// JBAS-298
}
}
@@ -408,22 +365,18 @@
return retval;
}
- private ReplicableCommand attachGlobalTransaction(InvocationContext ctx, Transaction tx, VisitableCommand command) throws Throwable
- {
- if (trace)
- {
+ private ReplicableCommand attachGlobalTransaction(InvocationContext ctx, Transaction tx, VisitableCommand command) throws Throwable {
+ if (trace) {
log.trace(" local transaction exists - registering global tx if not present for " + Thread.currentThread());
}
- if (trace)
- {
+ if (trace) {
GlobalTransaction tempGtx = txTable.get(tx);
log.trace("Associated gtx in txTable is " + tempGtx);
}
// register a sync handler for this tx - only if the globalTransaction is not remotely initiated.
GlobalTransaction gtx = registerTransaction(tx, ctx);
- if (gtx == null)
- {
+ if (gtx == null) {
// get the current globalTransaction from the txTable.
gtx = txTable.get(tx);
}
@@ -437,31 +390,25 @@
/**
* Replays modifications
*/
- protected void replayModifications(InvocationContext ctx, Transaction ltx, PrepareCommand command) throws Throwable
- {
- try
- {
+ protected void replayModifications(InvocationContext ctx, Transaction ltx, PrepareCommand command) throws Throwable {
+ try {
// replay modifications
- for (VisitableCommand modification : command.getModifications())
- {
+ for (VisitableCommand modification : command.getModifications()) {
invokeNextInterceptor(ctx, modification);
assertTxIsStillValid(ltx);
}
}
- catch (Throwable th)
- {
+ catch (Throwable th) {
log.error("prepare failed!", th);
throw th;
}
}
private void resumeTransactionOnCompletion(InvocationContext ctx, Transaction currentTx)
- throws SystemException, InvalidTransactionException
- {
+ throws SystemException, InvalidTransactionException {
if (trace) log.trace("Resuming suspended transaction " + currentTx);
txManager.suspend();
- if (currentTx != null)
- {
+ if (currentTx != null) {
txManager.resume(currentTx);
ctx.setTransaction(currentTx);
}
@@ -474,8 +421,7 @@
* @throws Throwable
*/
@SuppressWarnings("deprecation")
- private Object handleCommitRollback(InvocationContext ctx, VisitableCommand command) throws Throwable
- {
+ private Object handleCommitRollback(InvocationContext ctx, VisitableCommand command) throws Throwable {
GlobalTransaction gtx = ctx.getGlobalTransaction();
Object result;
result = invokeNextInterceptor(ctx, command);
@@ -487,38 +433,31 @@
// Transaction phase runners
// --------------------------------------------------------------
- protected PrepareCommand buildPrepareCommand(GlobalTransaction gtx, List modifications, boolean onePhaseCommit)
- {
+ protected PrepareCommand buildPrepareCommand(GlobalTransaction gtx, List modifications, boolean onePhaseCommit) {
return commandsFactory.buildPrepareCommand(gtx, modifications, rpcManager.getLocalAddress(), onePhaseCommit);
}
/**
* creates a commit()
*/
- protected void runCommitPhase(InvocationContext ctx, GlobalTransaction gtx, List modifications, boolean onePhaseCommit)
- {
- try
- {
+ protected void runCommitPhase(InvocationContext ctx, GlobalTransaction gtx, List modifications, boolean onePhaseCommit) {
+ try {
VisitableCommand commitCommand = onePhaseCommit ? buildPrepareCommand(gtx, modifications, true) : commandsFactory.buildCommitCommand(gtx);
if (trace) log.trace("Running commit for " + gtx);
handleCommitRollback(ctx, commitCommand);
}
- catch (Throwable e)
- {
+ catch (Throwable e) {
log.warn("Commit failed. Clearing stale locks.");
- try
- {
+ try {
cleanupStaleLocks(ctx);
}
- catch (RuntimeException re)
- {
+ catch (RuntimeException re) {
log.error("Unable to clear stale locks", re);
throw re;
}
- catch (Throwable e2)
- {
+ catch (Throwable e2) {
log.error("Unable to clear stale locks", e2);
throw new RuntimeException(e2);
}
@@ -529,8 +468,7 @@
}
}
- protected void cleanupStaleLocks(InvocationContext ctx) throws Throwable
- {
+ protected void cleanupStaleLocks(InvocationContext ctx) throws Throwable {
TransactionContext transactionContext = ctx.getTransactionContext();
if (transactionContext != null) lockManager.unlock(ctx);
}
@@ -538,10 +476,8 @@
/**
* creates a rollback()
*/
- protected void runRollbackPhase(InvocationContext ctx, GlobalTransaction gtx, Transaction tx)
- {
- try
- {
+ protected void runRollbackPhase(InvocationContext ctx, GlobalTransaction gtx, Transaction tx) {
+ try {
// JBCACHE-457
VisitableCommand rollbackCommand = commandsFactory.buildRollbackCommand(gtx);
if (trace) log.trace(" running rollback for " + gtx);
@@ -552,20 +488,16 @@
handleCommitRollback(ctx, rollbackCommand);
}
- catch (Throwable e)
- {
+ catch (Throwable e) {
log.warn("Rollback had a problem", e);
}
- finally
- {
+ finally {
rollbackTransactions.remove(tx);
}
}
- private boolean isOnePhaseCommit()
- {
- if (!configuration.getCacheMode().isSynchronous())
- {
+ private boolean isOnePhaseCommit() {
+ if (!configuration.getCacheMode().isSynchronous()) {
// this is a REPL_ASYNC call - do 1-phase commit. break!
if (trace) log.trace("This is a REPL_ASYNC call (1 phase commit) - do nothing for beforeCompletion()");
return true;
@@ -578,8 +510,7 @@
* method call and passes the prepare() call up the chain.
*/
@SuppressWarnings("deprecation")
- public Object runPreparePhase(InvocationContext ctx, GlobalTransaction gtx, List<VisitableCommand> modifications) throws Throwable
- {
+ public Object runPreparePhase(InvocationContext ctx, GlobalTransaction gtx, List<VisitableCommand> modifications) throws Throwable {
// running a 2-phase commit.
VisitableCommand prepareCommand = buildPrepareCommand(gtx, modifications, false);
@@ -590,12 +521,9 @@
//if ltx is not null and it is already running
Transaction currentTransaction = txManager.getTransaction();
- if (currentTransaction != null && ltx != null && currentTransaction.equals(ltx))
- {
+ if (currentTransaction != null && ltx != null && currentTransaction.equals(ltx)) {
result = invokeNextInterceptor(ctx, prepareCommand);
- }
- else
- {
+ } else {
log.warn("Local transaction does not exist or does not match expected transaction " + gtx);
throw new CacheException(" local transaction " + ltx + " does not exist or does not match expected transaction " + gtx);
}
@@ -606,16 +534,12 @@
// Private helper methods
// --------------------------------------------------------------
- protected void assertTxIsStillValid(Transaction tx)
- {
- if (!TransactionTable.isActive(tx))
- {
- try
- {
+ protected void assertTxIsStillValid(Transaction tx) {
+ if (!TransactionTable.isActive(tx)) {
+ try {
throw new ReplicationException("prepare() failed -- local transaction status is not STATUS_ACTIVE; is " + tx.getStatus());
}
- catch (SystemException e)
- {
+ catch (SystemException e) {
throw new ReplicationException("prepare() failed -- local transaction status is not STATUS_ACTIVE; Unable to retrieve transaction status.");
}
}
@@ -624,44 +548,32 @@
/**
* Creates a gtx (if one doesnt exist), a sync handler, and registers the tx.
*/
- private GlobalTransaction registerTransaction(Transaction tx, InvocationContext ctx) throws Exception
- {
+ private GlobalTransaction registerTransaction(Transaction tx, InvocationContext ctx) throws Exception {
GlobalTransaction gtx;
- if (TransactionTable.isValid(tx) && transactions.add(tx))
- {
+ if (TransactionTable.isValid(tx) && transactions.add(tx)) {
gtx = txTable.getCurrentTransaction(tx, true);
TransactionContext transactionContext;
- if (ctx.getGlobalTransaction() == null)
- {
+ if (ctx.getGlobalTransaction() == null) {
ctx.setGlobalTransaction(gtx);
transactionContext = txTable.getTransactionContext(gtx);
ctx.setTransactionContext(transactionContext);
- }
- else
- {
+ } else {
transactionContext = ctx.getTransactionContext();
}
- if (gtx.isRemote())
- {
+ if (gtx.isRemote()) {
// should be no need to register a handler since this a remotely initiated globalTransaction
if (trace) log.trace("is a remotely initiated gtx so no need to register a tx for it");
- }
- else
- {
+ } else {
if (trace) log.trace("Registering sync handler for tx " + tx + ", gtx " + gtx);
// see the comment in the LocalSyncHandler for the last isOriginLocal param.
LocalSynchronizationHandler myHandler = new LocalSynchronizationHandler(gtx, tx, transactionContext, !ctx.isOriginLocal());
registerHandler(tx, myHandler, ctx);
}
- }
- else if ((gtx = rollbackTransactions.get(tx)) != null)
- {
+ } else if ((gtx = rollbackTransactions.get(tx)) != null) {
if (trace) log.trace("Transaction " + tx + " is already registered and is rolling back.");
- }
- else
- {
+ } else {
if (trace) log.trace("Transaction " + tx + " is already registered.");
}
return gtx;
@@ -670,8 +582,7 @@
/**
* Registers a sync hander against a tx.
*/
- private void registerHandler(Transaction tx, Synchronization sync, InvocationContext ctx) throws Exception
- {
+ private void registerHandler(Transaction tx, Synchronization sync, InvocationContext ctx) throws Exception {
if (trace) log.trace("registering for TX completion: Synchronization (" + sync + ")");
tx.registerSynchronization(sync);
notifier.notifyTransactionRegistered(tx, ctx);
@@ -682,10 +593,8 @@
*
* @throws Exception
*/
- protected Transaction createLocalTx() throws Exception
- {
- if (trace)
- {
+ protected Transaction createLocalTx() throws Exception {
+ if (trace) {
log.trace("Creating transaction for thread " + Thread.currentThread());
}
Transaction localTx;
@@ -701,27 +610,23 @@
// this controls the whole transaction
- private class RemoteSynchronizationHandler implements Synchronization
- {
+ private class RemoteSynchronizationHandler implements Synchronization {
Transaction tx = null;
GlobalTransaction gtx = null;
List<VisitableCommand> modifications = null;
TransactionContext transactionContext = null;
protected InvocationContext ctx; // the context for this call.
- RemoteSynchronizationHandler(GlobalTransaction gtx, Transaction tx, TransactionContext entry)
- {
+ RemoteSynchronizationHandler(GlobalTransaction gtx, Transaction tx, TransactionContext entry) {
this.gtx = gtx;
this.tx = tx;
this.transactionContext = entry;
}
- public void beforeCompletion()
- {
+ public void beforeCompletion() {
if (trace) log.trace("Running beforeCompletion on gtx " + gtx);
- if (transactionContext == null)
- {
+ if (transactionContext == null) {
log.error("Transaction has a null transaction entry - beforeCompletion() will fail.");
throw new IllegalStateException("cannot find transaction entry for " + gtx);
}
@@ -740,47 +645,39 @@
// this should really not be done here -
// it is supposed to be post commit not actually run the commit
- public void afterCompletion(int status)
- {
+ public void afterCompletion(int status) {
// could happen if a rollback is called and beforeCompletion() doesn't get called.
- if (ctx == null)
- {
+ if (ctx == null) {
ctx = invocationContextContainer.get();
setTransactionalContext(tx, gtx, transactionContext, ctx);
- if (ctx.isOptionsUninitialised() && transactionContext != null && transactionContext.getOption() != null)
- {
+ if (ctx.isOptionsUninitialised() && transactionContext != null && transactionContext.getOption() != null) {
// use the options from the transaction entry instead
ctx.setOptionOverrides(transactionContext.getOption());
}
}
- try
- {
+ try {
assertCanContinue();
- try
- {
+ try {
if (txManager.getTransaction() != null && !txManager.getTransaction().equals(tx)) txManager.resume(tx);
}
- catch (Exception e)
- {
+ catch (Exception e) {
log.error("afterCompletion error: " + status, e);
}
if (trace) log.trace("calling aftercompletion for " + gtx);
// set any transaction wide options as current for this thread.
- if (transactionContext != null)
- {
+ if (transactionContext != null) {
// this should ideally be set in beforeCompletion(), after compacting the list.
if (modifications == null) modifications = transactionContext.getModifications();
ctx.setOptionOverrides(transactionContext.getOption());
}
if (tx != null) transactions.remove(tx);
- switch (status)
- {
+ switch (status) {
case Status.STATUS_COMMITTED:
boolean onePhaseCommit = isOnePhaseCommit();
if (log.isDebugEnabled()) log.debug("Running commit phase. One phase? " + onePhaseCommit);
@@ -800,13 +697,11 @@
throw new IllegalStateException("illegal status: " + status);
}
}
- catch (Exception th)
- {
+ catch (Exception th) {
log.trace("Caught exception ", th);
}
- finally
- {
+ finally {
// clean up the tx table
txTable.cleanup(gtx);
setTransactionalContext(null, null, null, ctx);
@@ -814,19 +709,17 @@
}
}
- private void assertCanContinue()
- {
+ private void assertCanContinue() {
if (!componentRegistry.invocationsAllowed(true) && (ctx.getOptionOverrides() == null || !ctx.getOptionOverrides().isSkipCacheStatusCheck()))
throw new IllegalStateException("Cache not in STARTED state!");
}
/**
- * Cleans out (nullifies) member variables held by the sync object for easier gc. Could be (falsely) seen as a mem
- * leak if the TM implementation hangs on to the synchronizations for an unnecessarily long time even after the tx
- * completes. See JBCACHE-1007.
+ * Cleans out (nullifies) member variables held by the sync object for easier gc. Could be (falsely) seen as a
+ * mem leak if the TM implementation hangs on to the synchronizations for an unnecessarily long time even after
+ * the tx completes. See JBCACHE-1007.
*/
- private void cleanupInternalState()
- {
+ private void cleanupInternalState() {
tx = null;
gtx = null;
modifications = null;
@@ -835,13 +728,11 @@
}
@Override
- public String toString()
- {
+ public String toString() {
return "TxInterceptor.RemoteSynchronizationHandler(gtx=" + gtx + ", tx=" + getTxAsString() + ")";
}
- protected String getTxAsString()
- {
+ protected String getTxAsString() {
// JBCACHE-1114 -- don't call toString() on tx or it can lead to stack overflow
if (tx == null)
return null;
@@ -850,8 +741,7 @@
}
}
- private class LocalSynchronizationHandler extends RemoteSynchronizationHandler
- {
+ private class LocalSynchronizationHandler extends RemoteSynchronizationHandler {
private boolean localRollbackOnly = true;
// a VERY strange situation where a tx has remote origins, but since certain buddy group org methods perform local
// cleanups even when remotely triggered, and optimistic locking is used, you end up with an implicit local tx.
@@ -865,35 +755,30 @@
* <p/>
* a VERY strange situation where a tx has remote origins, but since certain buddy group org methods perform local
* cleanups even when remotely triggered, and optimistic locking is used, you end up with an implicit local tx.
- * This is STILL remotely originating though and this needs to be made explicit here.
- * this can be checked by inspecting the InvocationContext.isOriginLocal() at the time of registering the sync.
+ * This is STILL remotely originating though and this needs to be made explicit here. this can be checked by
+ * inspecting the InvocationContext.isOriginLocal() at the time of registering the sync.
*
* @param gtx
* @param tx
* @param remoteLocal
*/
- LocalSynchronizationHandler(GlobalTransaction gtx, Transaction tx, TransactionContext transactionContext, boolean remoteLocal)
- {
+ LocalSynchronizationHandler(GlobalTransaction gtx, Transaction tx, TransactionContext transactionContext, boolean remoteLocal) {
super(gtx, tx, transactionContext);
this.remoteLocal = remoteLocal;
}
@Override
- public void beforeCompletion()
- {
+ public void beforeCompletion() {
super.beforeCompletion();
ctx.setOriginLocal(!remoteLocal); // this is the LOCAL sync handler after all!
// fetch the modifications before the transaction is committed
// (and thus removed from the txTable)
setTransactionalContext(tx, gtx, transactionContext, ctx);
- if (!transactionContext.hasModifications())
- {
+ if (!transactionContext.hasModifications()) {
if (trace) log.trace("No modifications in this tx. Skipping beforeCompletion()");
modifications = Collections.emptyList();
return;
- }
- else
- {
+ } else {
modifications = transactionContext.getModifications();
}
@@ -902,10 +787,8 @@
transactionalOptions = transactionContext.getOption();
ctx.setOptionOverrides(transactionalOptions);
- try
- {
- switch (tx.getStatus())
- {
+ try {
+ switch (tx.getStatus()) {
// if we are active or preparing then we can go ahead
case Status.STATUS_ACTIVE:
case Status.STATUS_PREPARING:
@@ -913,8 +796,7 @@
Object result = isOnePhaseCommit() ? null : runPreparePhase(ctx, gtx, modifications);
- if (result instanceof Throwable)
- {
+ if (result instanceof Throwable) {
if (log.isDebugEnabled())
log.debug("Transaction needs to be rolled back - the cache returned an instance of Throwable for this prepare call (tx=" + tx + " and gtx=" + gtx + ")", (Throwable) result);
tx.setRollbackOnly();
@@ -925,15 +807,12 @@
throw new CacheException("transaction " + tx + " in status " + tx.getStatus() + " unable to start transaction");
}
}
- catch (Throwable t)
- {
+ catch (Throwable t) {
if (log.isWarnEnabled()) log.warn("Caught exception, will now set transaction to roll back", t);
- try
- {
+ try {
tx.setRollbackOnly();
}
- catch (SystemException se)
- {
+ catch (SystemException se) {
throw new RuntimeException("setting tx rollback failed ", se);
}
if (t instanceof RuntimeException)
@@ -941,8 +820,7 @@
else
throw new RuntimeException("", t);
}
- finally
- {
+ finally {
localRollbackOnly = false;
setTransactionalContext(null, null, null, ctx);
ctx.setOptionOverrides(originalOptions);
@@ -950,41 +828,35 @@
}
@Override
- public void afterCompletion(int status)
- {
+ public void afterCompletion(int status) {
// could happen if a rollback is called and beforeCompletion() doesn't get called.
if (ctx == null) ctx = invocationContextContainer.get();
ctx.setLocalRollbackOnly(localRollbackOnly);
setTransactionalContext(tx, gtx, transactionContext, ctx);
if (transactionalOptions != null) ctx.setOptionOverrides(transactionalOptions);
- try
- {
+ try {
super.afterCompletion(status);
}
- finally
- {
+ finally {
ctx.setOptionOverrides(originalOptions);
}
}
@Override
- public String toString()
- {
+ public String toString() {
return "TxInterceptor.LocalSynchronizationHandler(gtx=" + gtx + ", tx=" + getTxAsString() + ")";
}
}
@ManagedOperation
- public void resetStatistics()
- {
+ public void resetStatistics() {
prepares = 0;
commits = 0;
rollbacks = 0;
}
@ManagedOperation
- public Map<String, Object> dumpStatistics()
- {
+ public Map<String, Object> dumpStatistics() {
Map<String, Object> retval = new HashMap<String, Object>(3);
retval.put("Prepares", prepares);
retval.put("Commits", commits);
@@ -993,32 +865,27 @@
}
@ManagedAttribute
- public boolean getStatisticsEnabled()
- {
+ public boolean getStatisticsEnabled() {
return this.statsEnabled;
}
@ManagedAttribute
- public void setStatisticsEnabled(boolean enabled)
- {
+ public void setStatisticsEnabled(boolean enabled) {
this.statsEnabled = enabled;
}
@ManagedAttribute(description = "number of transaction prepares")
- public long getPrepares()
- {
+ public long getPrepares() {
return prepares;
}
@ManagedAttribute(description = "number of transaction commits")
- public long getCommits()
- {
+ public long getCommits() {
return commits;
}
@ManagedAttribute(description = "number of transaction rollbacks")
- public long getRollbacks()
- {
+ public long getRollbacks() {
return rollbacks;
}
}
\ No newline at end of file
Modified: core/branches/flat/src/main/java/org/horizon/interceptors/base/BaseRpcInterceptor.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/interceptors/base/BaseRpcInterceptor.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/interceptors/base/BaseRpcInterceptor.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -44,8 +44,7 @@
* @author <a href="mailto:manik at jboss.org">Manik Surtani (manik at jboss.org)</a>
* @since 1.0
*/
-public abstract class BaseRpcInterceptor extends CommandInterceptor
-{
+public abstract class BaseRpcInterceptor extends CommandInterceptor {
private ReplicationQueue replicationQueue;
protected TransactionTable txTable;
private CommandsFactory commandsFactory;
@@ -55,8 +54,7 @@
@Inject
public void injectComponents(RPCManager rpcManager, ReplicationQueue replicationQueue,
- TransactionTable txTable, CommandsFactory commandsFactory)
- {
+ TransactionTable txTable, CommandsFactory commandsFactory) {
this.rpcManager = rpcManager;
this.replicationQueue = replicationQueue;
this.txTable = txTable;
@@ -64,23 +62,17 @@
}
@Start
- public void init()
- {
+ public void init() {
defaultSynchronous = configuration.getCacheMode().isSynchronous();
}
/**
- * Checks whether any of the responses are exceptions. If yes, re-throws
- * them (as exceptions or runtime exceptions).
+ * Checks whether any of the responses are exceptions. If yes, re-throws them (as exceptions or runtime exceptions).
*/
- protected void checkResponses(List rsps) throws Throwable
- {
- if (rsps != null)
- {
- for (Object rsp : rsps)
- {
- if (rsp != null && rsp instanceof Throwable)
- {
+ protected void checkResponses(List rsps) throws Throwable {
+ if (rsps != null) {
+ for (Object rsp : rsps) {
+ if (rsp != null && rsp instanceof Throwable) {
// lets print a stack trace first.
if (log.isDebugEnabled())
log.debug("Received Throwable from remote node", (Throwable) rsp);
@@ -90,23 +82,19 @@
}
}
- protected void replicateCall(InvocationContext ctx, ReplicableCommand call, boolean sync, Option o, boolean useOutOfBandMessage) throws Throwable
- {
+ protected void replicateCall(InvocationContext ctx, ReplicableCommand call, boolean sync, Option o, boolean useOutOfBandMessage) throws Throwable {
replicateCall(ctx, null, call, sync, o, useOutOfBandMessage);
}
- protected void replicateCall(InvocationContext ctx, ReplicableCommand call, boolean sync, Option o) throws Throwable
- {
+ protected void replicateCall(InvocationContext ctx, ReplicableCommand call, boolean sync, Option o) throws Throwable {
replicateCall(ctx, null, call, sync, o, false);
}
- protected void replicateCall(InvocationContext ctx, Vector<Address> recipients, ReplicableCommand c, boolean sync, Option o, boolean useOutOfBandMessage) throws Throwable
- {
+ protected void replicateCall(InvocationContext ctx, Vector<Address> recipients, ReplicableCommand c, boolean sync, Option o, boolean useOutOfBandMessage) throws Throwable {
long syncReplTimeout = configuration.getSyncReplTimeout();
// test for option overrides
- if (o != null)
- {
+ if (o != null) {
if (o.isForceAsynchronous()) sync = false;
else if (o.isForceSynchronous()) sync = true;
@@ -115,11 +103,9 @@
// tx-level overrides are more important
Transaction tx = ctx.getTransaction();
- if (tx != null)
- {
+ if (tx != null) {
TransactionContext transactionContext = ctx.getTransactionContext();
- if (transactionContext != null)
- {
+ if (transactionContext != null) {
if (transactionContext.isForceAsyncReplication()) sync = false;
else if (transactionContext.isForceSyncReplication()) sync = true;
}
@@ -128,20 +114,15 @@
replicateCall(recipients, c, sync, true, useOutOfBandMessage, false, syncReplTimeout);
}
- protected void replicateCall(Vector<Address> recipients, ReplicableCommand call, boolean sync, boolean wrapCacheCommandInReplicateMethod, boolean useOutOfBandMessage, boolean isBroadcast, long timeout) throws Throwable
- {
+ protected void replicateCall(Vector<Address> recipients, ReplicableCommand call, boolean sync, boolean wrapCacheCommandInReplicateMethod, boolean useOutOfBandMessage, boolean isBroadcast, long timeout) throws Throwable {
if (trace) log.trace("Broadcasting call " + call + " to recipient list " + recipients);
- if (!sync && replicationQueue != null)
- {
+ if (!sync && replicationQueue != null) {
if (log.isDebugEnabled()) log.debug("Putting call " + call + " on the replication queue.");
replicationQueue.add(commandsFactory.buildReplicateCommand(call));
- }
- else
- {
+ } else {
Vector<Address> callRecipients = recipients;
- if (callRecipients == null)
- {
+ if (callRecipients == null) {
callRecipients = null;
if (trace)
log.trace("Setting call recipients to " + callRecipients + " since the original list of recipients passed in is null.");
@@ -150,10 +131,10 @@
ReplicableCommand toCall = wrapCacheCommandInReplicateMethod ? commandsFactory.buildReplicateCommand(call) : call;
List rsps = rpcManager.callRemoteMethods(callRecipients,
- toCall,
- sync, // is synchronised?
- timeout,
- useOutOfBandMessage
+ toCall,
+ sync, // is synchronised?
+ timeout,
+ useOutOfBandMessage
);
if (trace) log.trace("responses=" + rsps);
if (sync) checkResponses(rsps);
@@ -161,15 +142,15 @@
}
/**
- * It does not make sense replicating a transaction method(commit, rollback, prepare) if one of the following is true:
+ * It does not make sense replicating a transaction method(commit, rollback, prepare) if one of the following is
+ * true:
* <pre>
* - call was not initiated here, but on other member of the cluster
* - there is no transaction. Why broadcast a commit or rollback if there is no transaction going on?
* - the current transaction did not modify any data
* </pre>
*/
- protected boolean skipReplicationOfTransactionMethod(InvocationContext ctx)
- {
+ protected boolean skipReplicationOfTransactionMethod(InvocationContext ctx) {
GlobalTransaction gtx = ctx.getGlobalTransaction();
return ctx.getTransaction() == null || gtx == null || gtx.isRemote() || ctx.getOptionOverrides().isCacheModeLocal() || !ctx.getTransactionContext().hasModifications();
}
@@ -177,17 +158,14 @@
/**
* The call runs in a transaction and it was initiated on this node of the cluster.
*/
- protected boolean isTransactionalAndLocal(InvocationContext ctx)
- {
+ protected boolean isTransactionalAndLocal(InvocationContext ctx) {
GlobalTransaction gtx = ctx.getGlobalTransaction();
boolean isInitiatedHere = gtx != null && !gtx.isRemote();
return isInitiatedHere && (ctx.getTransaction() != null);
}
- protected boolean isSynchronous(Option option)
- {
- if (option != null)
- {
+ protected boolean isSynchronous(Option option) {
+ if (option != null) {
if (option.isForceSynchronous())
return true;
else if (option.isForceAsynchronous())
@@ -196,10 +174,8 @@
return defaultSynchronous;
}
- protected boolean isLocalModeForced(InvocationContext ctx)
- {
- if (ctx.getOptionOverrides() != null && ctx.getOptionOverrides().isCacheModeLocal())
- {
+ protected boolean isLocalModeForced(InvocationContext ctx) {
+ if (ctx.getOptionOverrides() != null && ctx.getOptionOverrides().isCacheModeLocal()) {
if (log.isDebugEnabled()) log.debug("LOCAL mode forced on invocation. Suppressing clustered events.");
return true;
}
Modified: core/branches/flat/src/main/java/org/horizon/interceptors/base/CommandInterceptor.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/interceptors/base/CommandInterceptor.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/interceptors/base/CommandInterceptor.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -32,19 +32,23 @@
import org.horizon.factories.scopes.Scopes;
/**
- * This is the base class for all interceptors to extend, and implements the {@link org.horizon.commands.Visitor} interface
- * allowing it to intercept invocations on {@link org.horizon.commands.VisitableCommand}s.
+ * This is the base class for all interceptors to extend, and implements the {@link org.horizon.commands.Visitor}
+ * interface allowing it to intercept invocations on {@link org.horizon.commands.VisitableCommand}s.
* <p/>
- * Commands are either created by the {@link org.horizon.CacheDelegate} (for invocations on the {@link org.horizon.Cache}
- * public interface), or by the {@link org.horizon.marshall.CommandAwareRpcDispatcher} for remotely originating invocations, and
- * are passed up the interceptor chain by using the {@link org.horizon.interceptors.InterceptorChain} helper class.
+ * Commands are either created by the {@link org.horizon.CacheDelegate} (for invocations on the {@link
+ * org.horizon.Cache} public interface), or by the {@link org.horizon.marshall.CommandAwareRpcDispatcher} for remotely
+ * originating invocations, and are passed up the interceptor chain by using the {@link
+ * org.horizon.interceptors.InterceptorChain} helper class.
* <p/>
- * When writing interceptors, authors can either override a specific visitXXX() method (such as {@link #visitGetKeyValueCommand(org.horizon.context.InvocationContext, org.horizon.commands.read.GetKeyValueCommand)})
- * or the more generic {@link #handleDefault(org.horizon.context.InvocationContext, org.horizon.commands.VisitableCommand)} which is the default behaviour of
- * any visit method, as defined in {@link AbstractVisitor#handleDefault(org.horizon.context.InvocationContext, org.horizon.commands.VisitableCommand)}.
+ * When writing interceptors, authors can either override a specific visitXXX() method (such as {@link
+ * #visitGetKeyValueCommand(org.horizon.context.InvocationContext, org.horizon.commands.read.GetKeyValueCommand)}) or
+ * the more generic {@link #handleDefault(org.horizon.context.InvocationContext, org.horizon.commands.VisitableCommand)}
+ * which is the default behaviour of any visit method, as defined in {@link AbstractVisitor#handleDefault(org.horizon.context.InvocationContext,
+ * org.horizon.commands.VisitableCommand)}.
* <p/>
- * The preferred approach is to override the specific visitXXX() methods that are of interest rather than to override {@link #handleDefault(org.horizon.context.InvocationContext, org.horizon.commands.VisitableCommand)}
- * and then write a series of if statements or a switch block, if command-specific behaviour is needed.
+ * The preferred approach is to override the specific visitXXX() methods that are of interest rather than to override
+ * {@link #handleDefault(org.horizon.context.InvocationContext, org.horizon.commands.VisitableCommand)} and then write a
+ * series of if statements or a switch block, if command-specific behaviour is needed.
* <p/>
*
* @author Mircea.Markus at jboss.com
@@ -54,8 +58,7 @@
* @since 1.0
*/
@Scope(Scopes.NAMED_CACHE)
-public class CommandInterceptor extends AbstractVisitor
-{
+public class CommandInterceptor extends AbstractVisitor {
private CommandInterceptor next;
protected Log log;
@@ -63,15 +66,13 @@
protected Configuration configuration;
- public CommandInterceptor()
- {
+ public CommandInterceptor() {
log = LogFactory.getLog(getClass());
trace = log.isTraceEnabled();
}
@Inject
- private void injectConfiguration(Configuration configuration)
- {
+ private void injectConfiguration(Configuration configuration) {
this.configuration = configuration;
}
@@ -80,16 +81,14 @@
*
* @return the next interceptor in the chain.
*/
- public CommandInterceptor getNext()
- {
+ public CommandInterceptor getNext() {
return next;
}
/**
* @return true if there is another interceptor in the chain after this; false otherwise.
*/
- public boolean hasNext()
- {
+ public boolean hasNext() {
return getNext() != null;
}
@@ -98,14 +97,13 @@
*
* @param next next interceptor in the chain.
*/
- public void setNext(CommandInterceptor next)
- {
+ public void setNext(CommandInterceptor next) {
this.next = next;
}
/**
- * Invokes the next interceptor in the chain. This is how interceptor implementations should pass a call up the chain
- * to the next interceptor. In previous (pre-2.2.0) implementations of JBoss Cache, this was done by calling
+ * Invokes the next interceptor in the chain. This is how interceptor implementations should pass a call up the
+ * chain to the next interceptor. In previous (pre-2.2.0) implementations of JBoss Cache, this was done by calling
* <pre>super.invoke()</pre>.
*
* @param ctx invocation context
@@ -113,8 +111,7 @@
* @return return value of the invocation
* @throws Throwable in the event of problems
*/
- public Object invokeNextInterceptor(InvocationContext ctx, VisitableCommand command) throws Throwable
- {
+ public Object invokeNextInterceptor(InvocationContext ctx, VisitableCommand command) throws Throwable {
return command.acceptVisitor(ctx, next);
}
@@ -128,8 +125,7 @@
* @throws Throwable in the event of problems
*/
@Override
- protected Object handleDefault(InvocationContext ctx, VisitableCommand command) throws Throwable
- {
+ protected Object handleDefault(InvocationContext ctx, VisitableCommand command) throws Throwable {
return invokeNextInterceptor(ctx, command);
}
}
\ No newline at end of file
Modified: core/branches/flat/src/main/java/org/horizon/interceptors/base/JmxStatsCommandInterceptor.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/interceptors/base/JmxStatsCommandInterceptor.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/interceptors/base/JmxStatsCommandInterceptor.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -21,9 +21,9 @@
*/
package org.horizon.interceptors.base;
-import org.horizon.jmx.JmxStatisticsExposer;
-import org.horizon.factories.annotations.Start;
import org.horizon.annotations.ManagedAttribute;
+import org.horizon.factories.annotations.Start;
+import org.horizon.jmx.JmxStatisticsExposer;
import java.util.Collections;
import java.util.Map;
@@ -34,25 +34,21 @@
* @author Mircea.Markus at jboss.com
* @since 1.0
*/
-public class JmxStatsCommandInterceptor extends CommandInterceptor implements JmxStatisticsExposer
-{
+public class JmxStatsCommandInterceptor extends CommandInterceptor implements JmxStatisticsExposer {
private boolean statsEnabled = false;
@Start
- public void checkStatisticsUsed()
- {
+ public void checkStatisticsUsed() {
setStatisticsEnabled(configuration.isExposeManagementStatistics());
}
/**
- * Returns whether an interceptor's statistics are
- * being captured.
+ * Returns whether an interceptor's statistics are being captured.
*
* @return true if statistics are captured
*/
@ManagedAttribute
- public boolean getStatisticsEnabled()
- {
+ public boolean getStatisticsEnabled() {
return statsEnabled;
}
@@ -60,8 +56,7 @@
* @param enabled whether gathering statistics for JMX are enabled.
*/
@ManagedAttribute
- public void setStatisticsEnabled(boolean enabled)
- {
+ public void setStatisticsEnabled(boolean enabled) {
statsEnabled = enabled;
}
@@ -71,16 +66,14 @@
*
* @return an empty map
*/
- public Map<String, Object> dumpStatistics()
- {
+ public Map<String, Object> dumpStatistics() {
return Collections.emptyMap();
}
/**
* Resets statistics gathered. Is a no-op, and should be overridden if it is to be meaningful.
*/
- public void resetStatistics()
- {
+ public void resetStatistics() {
}
Modified: core/branches/flat/src/main/java/org/horizon/interceptors/base/PrePostProcessingCommandInterceptor.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/interceptors/base/PrePostProcessingCommandInterceptor.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/interceptors/base/PrePostProcessingCommandInterceptor.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -38,219 +38,175 @@
/**
* This interceptor adds pre and post processing to each <tt>visitXXX()</tt> method.
* <p/>
- * For each <tt>visitXXX()</tt> method invoked, it will first call {@link #doBeforeCall(InvocationContext, VisitableCommand)}
- * and if this method returns true, it will proceed to invoking a <tt>handleXXX()</tt> method and lastly, {@link #doAfterCall(InvocationContext, VisitableCommand)}
- * in a <tt>finally</tt> block. Note that the <tt>doAfterCall()</tt> method is still invoked even if <tt>doBeforeCall()</tt> returns <tt>false</tt>.
+ * For each <tt>visitXXX()</tt> method invoked, it will first call {@link #doBeforeCall(InvocationContext,
+ * VisitableCommand)} and if this method returns true, it will proceed to invoking a <tt>handleXXX()</tt> method and
+ * lastly, {@link #doAfterCall(InvocationContext, VisitableCommand)} in a <tt>finally</tt> block. Note that the
+ * <tt>doAfterCall()</tt> method is still invoked even if <tt>doBeforeCall()</tt> returns <tt>false</tt>.
* <p/>
- * Instead of overriding <tt>visitXXX()</tt> methods, implementations should override their <tt>handleXXX()</tt> counterparts defined in this class
- * instead, as well as the {@link #doAfterCall(InvocationContext ,VisitableCommand)} method and
- * optionally {@link #doBeforeCall(InvocationContext, VisitableCommand)}.
+ * Instead of overriding <tt>visitXXX()</tt> methods, implementations should override their <tt>handleXXX()</tt>
+ * counterparts defined in this class instead, as well as the {@link #doAfterCall(InvocationContext ,VisitableCommand)}
+ * method and optionally {@link #doBeforeCall(InvocationContext, VisitableCommand)}.
* <p/>
*
* @author Mircea.Markus at jboss.com
* @since 1.0
*/
-public abstract class PrePostProcessingCommandInterceptor extends CommandInterceptor
-{
+public abstract class PrePostProcessingCommandInterceptor extends CommandInterceptor {
@Override
- public Object visitPutKeyValueCommand(InvocationContext ctx, PutKeyValueCommand command) throws Throwable
- {
- try
- {
+ public Object visitPutKeyValueCommand(InvocationContext ctx, PutKeyValueCommand command) throws Throwable {
+ try {
return (doBeforeCall(ctx, command)) ? handlePutKeyValueCommand(ctx, command) : null;
}
- finally
- {
+ finally {
doAfterCall(ctx, command);
}
}
- protected Object handlePutKeyValueCommand(InvocationContext ctx, PutKeyValueCommand command) throws Throwable
- {
+ protected Object handlePutKeyValueCommand(InvocationContext ctx, PutKeyValueCommand command) throws Throwable {
return handleDefault(ctx, command);
}
@Override
- public Object visitRemoveCommand(InvocationContext ctx, RemoveCommand command) throws Throwable
- {
- try
- {
+ public Object visitRemoveCommand(InvocationContext ctx, RemoveCommand command) throws Throwable {
+ try {
return (doBeforeCall(ctx, command)) ? handleRemoveCommand(ctx, command) : null;
}
- finally
- {
+ finally {
doAfterCall(ctx, command);
}
}
- protected Object handleRemoveCommand(InvocationContext ctx, RemoveCommand command) throws Throwable
- {
+ protected Object handleRemoveCommand(InvocationContext ctx, RemoveCommand command) throws Throwable {
return handleDefault(ctx, command);
}
@Override
- public Object visitReplaceCommand(InvocationContext ctx, ReplaceCommand command) throws Throwable
- {
- try
- {
+ public Object visitReplaceCommand(InvocationContext ctx, ReplaceCommand command) throws Throwable {
+ try {
return (doBeforeCall(ctx, command)) ? handleReplaceCommand(ctx, command) : null;
}
- finally
- {
+ finally {
doAfterCall(ctx, command);
}
}
- protected Object handleReplaceCommand(InvocationContext ctx, ReplaceCommand command) throws Throwable
- {
+ protected Object handleReplaceCommand(InvocationContext ctx, ReplaceCommand command) throws Throwable {
return handleDefault(ctx, command);
}
@Override
- public Object visitClearCommand(InvocationContext ctx, ClearCommand command) throws Throwable
- {
- try
- {
+ public Object visitClearCommand(InvocationContext ctx, ClearCommand command) throws Throwable {
+ try {
return (doBeforeCall(ctx, command)) ? handleClearCommand(ctx, command) : null;
}
- finally
- {
+ finally {
doAfterCall(ctx, command);
}
}
- protected Object handleClearCommand(InvocationContext ctx, ClearCommand command) throws Throwable
- {
+ protected Object handleClearCommand(InvocationContext ctx, ClearCommand command) throws Throwable {
return handleDefault(ctx, command);
}
@Override
- public Object visitPutMapCommand(InvocationContext ctx, PutMapCommand command) throws Throwable
- {
- try
- {
+ public Object visitPutMapCommand(InvocationContext ctx, PutMapCommand command) throws Throwable {
+ try {
return (doBeforeCall(ctx, command)) ? handlePutMapCommand(ctx, command) : null;
}
- finally
- {
+ finally {
doAfterCall(ctx, command);
}
}
- protected Object handlePutMapCommand(InvocationContext ctx, PutMapCommand command) throws Throwable
- {
+ protected Object handlePutMapCommand(InvocationContext ctx, PutMapCommand command) throws Throwable {
return handleDefault(ctx, command);
}
@Override
- public Object visitEvictCommand(InvocationContext ctx, EvictCommand command) throws Throwable
- {
- try
- {
+ public Object visitEvictCommand(InvocationContext ctx, EvictCommand command) throws Throwable {
+ try {
return (doBeforeCall(ctx, command)) ? handleEvictCommand(ctx, command) : null;
}
- finally
- {
+ finally {
doAfterCall(ctx, command);
}
}
- protected Object handleEvictCommand(InvocationContext ctx, EvictCommand command) throws Throwable
- {
+ protected Object handleEvictCommand(InvocationContext ctx, EvictCommand command) throws Throwable {
return handleDefault(ctx, command);
}
// read commands
@Override
- public Object visitSizeCommand(InvocationContext ctx, SizeCommand command) throws Throwable
- {
- try
- {
+ public Object visitSizeCommand(InvocationContext ctx, SizeCommand command) throws Throwable {
+ try {
return (doBeforeCall(ctx, command)) ? handleSizeCommand(ctx, command) : null;
}
- finally
- {
+ finally {
doAfterCall(ctx, command);
}
}
- protected Object handleSizeCommand(InvocationContext ctx, SizeCommand command) throws Throwable
- {
+ protected Object handleSizeCommand(InvocationContext ctx, SizeCommand command) throws Throwable {
return handleDefault(ctx, command);
}
@Override
- public Object visitGetKeyValueCommand(InvocationContext ctx, GetKeyValueCommand command) throws Throwable
- {
- try
- {
+ public Object visitGetKeyValueCommand(InvocationContext ctx, GetKeyValueCommand command) throws Throwable {
+ try {
return (doBeforeCall(ctx, command)) ? handleGetKeyValueCommand(ctx, command) : null;
}
- finally
- {
+ finally {
doAfterCall(ctx, command);
}
}
- protected Object handleGetKeyValueCommand(InvocationContext ctx, GetKeyValueCommand command) throws Throwable
- {
+ protected Object handleGetKeyValueCommand(InvocationContext ctx, GetKeyValueCommand command) throws Throwable {
return handleDefault(ctx, command);
}
// tx commands
@Override
- public Object visitPrepareCommand(InvocationContext ctx, PrepareCommand command) throws Throwable
- {
- try
- {
+ public Object visitPrepareCommand(InvocationContext ctx, PrepareCommand command) throws Throwable {
+ try {
return (doBeforeCall(ctx, command)) ? handlePrepareCommand(ctx, command) : null;
}
- finally
- {
+ finally {
doAfterCall(ctx, command);
}
}
- protected Object handlePrepareCommand(InvocationContext ctx, PrepareCommand command) throws Throwable
- {
+ protected Object handlePrepareCommand(InvocationContext ctx, PrepareCommand command) throws Throwable {
return handleDefault(ctx, command);
}
@Override
- public Object visitRollbackCommand(InvocationContext ctx, RollbackCommand command) throws Throwable
- {
- try
- {
+ public Object visitRollbackCommand(InvocationContext ctx, RollbackCommand command) throws Throwable {
+ try {
return (doBeforeCall(ctx, command)) ? handleRollbackCommand(ctx, command) : null;
}
- finally
- {
+ finally {
doAfterCall(ctx, command);
}
}
- protected Object handleRollbackCommand(InvocationContext ctx, RollbackCommand command) throws Throwable
- {
+ protected Object handleRollbackCommand(InvocationContext ctx, RollbackCommand command) throws Throwable {
return handleDefault(ctx, command);
}
@Override
- public Object visitCommitCommand(InvocationContext ctx, CommitCommand command) throws Throwable
- {
- try
- {
+ public Object visitCommitCommand(InvocationContext ctx, CommitCommand command) throws Throwable {
+ try {
return (doBeforeCall(ctx, command)) ? handleCommitCommand(ctx, command) : null;
}
- finally
- {
+ finally {
doAfterCall(ctx, command);
}
}
- protected Object handleCommitCommand(InvocationContext ctx, CommitCommand command) throws Throwable
- {
+ protected Object handleCommitCommand(InvocationContext ctx, CommitCommand command) throws Throwable {
return handleDefault(ctx, command);
}
@@ -262,8 +218,7 @@
*/
protected abstract void doAfterCall(InvocationContext ctx, VisitableCommand command);
- protected boolean doBeforeCall(InvocationContext ctx, VisitableCommand command)
- {
+ protected boolean doBeforeCall(InvocationContext ctx, VisitableCommand command) {
return true;
}
}
\ No newline at end of file
Modified: core/branches/flat/src/main/java/org/horizon/invocation/InvocationContextContainer.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/invocation/InvocationContextContainer.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/invocation/InvocationContextContainer.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -37,19 +37,16 @@
*/
@NonVolatile
@Scope(Scopes.NAMED_CACHE)
-public class InvocationContextContainer extends ThreadLocal<InvocationContext>
-{
+public class InvocationContextContainer extends ThreadLocal<InvocationContext> {
ContextFactory contextFactory;
@Inject
- public void injectContextFactory(ContextFactory contextFactory)
- {
+ public void injectContextFactory(ContextFactory contextFactory) {
this.contextFactory = contextFactory;
}
@Override
- protected InvocationContext initialValue()
- {
+ protected InvocationContext initialValue() {
// create if this is initially unset
return contextFactory.createInvocationContext();
}
Modified: core/branches/flat/src/main/java/org/horizon/io/ByteBuffer.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/io/ByteBuffer.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/io/ByteBuffer.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -28,21 +28,19 @@
/**
* A subclass of a JGroups Buffer
- * @since 1.0
+ *
* @author (various)
+ * @since 1.0
*/
-public class ByteBuffer extends Buffer
-{
- public ByteBuffer(byte[] bytes, int offset, int length)
- {
+public class ByteBuffer extends Buffer {
+ public ByteBuffer(byte[] bytes, int offset, int length) {
super(bytes, offset, length);
}
/**
* @return an input stream for the bytes in the buffer
*/
- public InputStream getStream()
- {
+ public InputStream getStream() {
return new ByteArrayInputStream(getBuf(), getOffset(), getLength());
}
}
Modified: core/branches/flat/src/main/java/org/horizon/io/ExposedByteArrayOutputStream.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/io/ExposedByteArrayOutputStream.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/io/ExposedByteArrayOutputStream.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -26,91 +26,67 @@
import java.io.ByteArrayOutputStream;
/**
- * Extends ByteArrayOutputStream, but exposes the internal buffer.
- * Using this, callers don't need to call toByteArray() which copies the
- * internal buffer.
- * <p>
- * Also overrides the superclass' behavior of always doubling the size of the
- * internal buffer any time more capacity is needed. This class doubles the
- * size until the internal buffer reaches a configurable max size (default is
- * 4MB), after which it begins growing the buffer in 25% increments. This is
- * intended to help prevent an OutOfMemoryError during a resize of a large
- * buffer.
- * </p>
- * <p>
- * A version of this class was originally created by Bela Ban as part of the
- * JGroups library.
- * </p>
- * This class is not threadsafe as it will not support concurrent readers and writers.
+ * Extends ByteArrayOutputStream, but exposes the internal buffer. Using this, callers don't need to call toByteArray()
+ * which copies the internal buffer. <p> Also overrides the superclass' behavior of always doubling the size of the
+ * internal buffer any time more capacity is needed. This class doubles the size until the internal buffer reaches a
+ * configurable max size (default is 4MB), after which it begins growing the buffer in 25% increments. This is intended
+ * to help prevent an OutOfMemoryError during a resize of a large buffer. </p> <p> A version of this class was
+ * originally created by Bela Ban as part of the JGroups library. </p> This class is not threadsafe as it will not
+ * support concurrent readers and writers.
* <p/>
*
* @author <a href="mailto://brian.stansberry@jboss.com">Brian Stansberry</a>
- *
* @since 1.0
*/
@NotThreadSafe
-public class ExposedByteArrayOutputStream extends ByteArrayOutputStream
-{
+public class ExposedByteArrayOutputStream extends ByteArrayOutputStream {
/**
- * Default buffer size after which if more buffer capacity
- * is needed the buffer will grow by 25% rather than 100%
+ * Default buffer size after which if more buffer capacity is needed the buffer will grow by 25% rather than 100%
*/
public static final int DEFAULT_DOUBLING_SIZE = 4 * 1024 * 1024; // 4MB
private int maxDoublingSize = DEFAULT_DOUBLING_SIZE;
- public ExposedByteArrayOutputStream()
- {
+ public ExposedByteArrayOutputStream() {
super();
}
- public ExposedByteArrayOutputStream(int size)
- {
+ public ExposedByteArrayOutputStream(int size) {
super(size);
}
/**
- * Creates a new byte array output stream, with a buffer capacity of
- * the specified size, in bytes.
+ * Creates a new byte array output stream, with a buffer capacity of the specified size, in bytes.
*
* @param size the initial size.
- * @param maxDoublingSize the buffer size, after which if more capacity
- * is needed the buffer will grow by 25%
- * rather than 100%
+ * @param maxDoublingSize the buffer size, after which if more capacity is needed the buffer will grow by 25% rather
+ * than 100%
* @throws IllegalArgumentException if size is negative.
*/
- public ExposedByteArrayOutputStream(int size, int maxDoublingSize)
- {
+ public ExposedByteArrayOutputStream(int size, int maxDoublingSize) {
super(size);
this.maxDoublingSize = maxDoublingSize;
}
/**
- * Gets the internal buffer array. Note that the length of this array
- * will almost certainly be longer than the data written to it; call
- * <code>size()</code> to get the number of bytes of actual data.
+ * Gets the internal buffer array. Note that the length of this array will almost certainly be longer than the data
+ * written to it; call <code>size()</code> to get the number of bytes of actual data.
*/
- public final byte[] getRawBuffer()
- {
+ public final byte[] getRawBuffer() {
return buf;
}
@Override
- public void write(byte[] b, int off, int len)
- {
+ public void write(byte[] b, int off, int len) {
if ((off < 0) || (off > b.length) || (len < 0) ||
- ((off + len) > b.length) || ((off + len) < 0))
- {
+ ((off + len) > b.length) || ((off + len) < 0)) {
throw new IndexOutOfBoundsException();
- }
- else if (len == 0)
- {
+ } else if (len == 0) {
return;
}
int newcount = count + len;
- if (newcount > buf.length)
- {
+ if (newcount > buf.length) {
byte newbuf[] = new byte[getNewBufferSize(buf.length, newcount)];
System.arraycopy(buf, 0, newbuf, 0, count);
buf = newbuf;
@@ -121,11 +97,9 @@
}
@Override
- public void write(int b)
- {
+ public void write(int b) {
int newcount = count + 1;
- if (newcount > buf.length)
- {
+ if (newcount > buf.length) {
byte newbuf[] = new byte[getNewBufferSize(buf.length, newcount)];
System.arraycopy(buf, 0, newbuf, 0, count);
buf = newbuf;
@@ -135,11 +109,10 @@
}
/**
- * Gets the highest internal buffer size after which if more capacity
- * is needed the buffer will grow in 25% increments rather than 100%.
+ * Gets the highest internal buffer size after which if more capacity is needed the buffer will grow in 25%
+ * increments rather than 100%.
*/
- public final int getMaxDoublingSize()
- {
+ public final int getMaxDoublingSize() {
return maxDoublingSize;
}
@@ -150,8 +123,7 @@
* @param minNewSize the minimum number of bytes required
* @return the size to which the internal buffer should be resized
*/
- public final int getNewBufferSize(int curSize, int minNewSize)
- {
+ public final int getNewBufferSize(int curSize, int minNewSize) {
if (curSize <= maxDoublingSize)
return Math.max(curSize << 1, minNewSize);
else
Modified: core/branches/flat/src/main/java/org/horizon/jmx/JmxRegistrationManager.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/jmx/JmxRegistrationManager.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/jmx/JmxRegistrationManager.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -37,163 +37,157 @@
import java.util.List;
/**
- * Registers all the <b>MBean</b>s from an <b>Cache</b> instance to a <b>MBeanServer</b>.
- * It iterates over all the components within <b>ComponentRegistry</b> and registers all the components
- * annotated with <b>ManagedAttribute</b>, <b>ManagedOperation</b> or/and <b>MBean</b>.
- * If no <b>MBean</b> server is provided, then the {@link java.lang.management.ManagementFactory#getPlatformMBeanServer()}
- * is being used.
- * <p/>
- * It is immutable: both cache instance and MBeanServer are being passed as arguments to the constructor.
- * <p />
- * <p>
- * Note that by default object names used are prefixed with <tt>jboss.cache:service=JBossCache</tt>. While this format
- * works for and is consistent with JBoss AS and the JMX console, it has been known to cause problems with other JMX
- * servers such as Websphere. To work around this, you can provide the following VM system property to override this
- * prefix with a prefix of your choice:
- * <tt><b>-Djbosscache.jmx.prefix=JBossCache</b></tt>
- * </p>
+ * Registers all the <b>MBean</b>s from an <b>Cache</b> instance to a <b>MBeanServer</b>. It iterates over all the
+ * components within <b>ComponentRegistry</b> and registers all the components annotated with <b>ManagedAttribute</b>,
+ * <b>ManagedOperation</b> or/and <b>MBean</b>. If no <b>MBean</b> server is provided, then the {@link
+ * java.lang.management.ManagementFactory#getPlatformMBeanServer()} is being used. <p/> It is immutable: both cache
+ * instance and MBeanServer are being passed as arguments to the constructor. <p /> <p> Note that by default object
+ * names used are prefixed with <tt>jboss.cache:service=JBossCache</tt>. While this format works for and is consistent
+ * with JBoss AS and the JMX console, it has been known to cause problems with other JMX servers such as Websphere. To
+ * work around this, you can provide the following VM system property to override this prefix with a prefix of your
+ * choice: <tt><b>-Djbosscache.jmx.prefix=JBossCache</b></tt> </p>
*
* @author Mircea.Markus at jboss.com
* @since 1.0
*/
public class JmxRegistrationManager {
- private static final Log log = LogFactory.getLog(JmxRegistrationManager.class);
+ private static final Log log = LogFactory.getLog(JmxRegistrationManager.class);
- private static final String GENERAL_PREFIX = System.getProperty("jbosscache.jmx.prefix", "jboss.cache:service=JBossCache");
+ private static final String GENERAL_PREFIX = System.getProperty("jbosscache.jmx.prefix", "jboss.cache:service=JBossCache");
- /**
- * default ObjectName for clusterd caches. Cluster name should pe appended.
- */
- public static final String REPLICATED_CACHE_PREFIX = GENERAL_PREFIX + ",cluster=";
+ /**
+ * default ObjectName for clusterd caches. Cluster name should pe appended.
+ */
+ public static final String REPLICATED_CACHE_PREFIX = GENERAL_PREFIX + ",cluster=";
- /**
- * default ObjectName for non clustered caches. An unique identifier should be appended.
- */
- public static final String LOCAL_CACHE_PREFIX = GENERAL_PREFIX + ",uniqueId=";
+ /**
+ * default ObjectName for non clustered caches. An unique identifier should be appended.
+ */
+ public static final String LOCAL_CACHE_PREFIX = GENERAL_PREFIX + ",uniqueId=";
- /**
- * Key for every Dynamic mbean added.
- */
- public static final String JMX_RESOURCE_KEY = ",jmx-resource=";
+ /**
+ * Key for every Dynamic mbean added.
+ */
+ public static final String JMX_RESOURCE_KEY = ",jmx-resource=";
- private MBeanServer mBeanServer;
+ private MBeanServer mBeanServer;
- private String objectNameBase;
+ private String objectNameBase;
- private CacheSPI cacheSpi;
+ private CacheSPI cacheSpi;
- /**
- * C-tor.
- *
- * @param mBeanServer the server where mbeans are being registered
- * @param cache cache that needs to be monitored
- * @param objectNameBase path in the MBeanServer where to register cache MBeans
- */
- public JmxRegistrationManager(MBeanServer mBeanServer, Cache cache, ObjectName objectNameBase) {
- this.mBeanServer = mBeanServer;
- this.cacheSpi = (CacheSPI) cache;
- processBaseName(objectNameBase);
- }
+ /**
+ * C-tor.
+ *
+ * @param mBeanServer the server where mbeans are being registered
+ * @param cache cache that needs to be monitored
+ * @param objectNameBase path in the MBeanServer where to register cache MBeans
+ */
+ public JmxRegistrationManager(MBeanServer mBeanServer, Cache cache, ObjectName objectNameBase) {
+ this.mBeanServer = mBeanServer;
+ this.cacheSpi = (CacheSPI) cache;
+ processBaseName(objectNameBase);
+ }
- /**
- * @throws IllegalArgumentException if the supplied objectNameBase name isn't valid
- */
- public JmxRegistrationManager(MBeanServer mBeanServer, Cache cache, String objectNameBase) {
- this.mBeanServer = mBeanServer;
- this.cacheSpi = (CacheSPI) cache;
- try {
- processBaseName(new ObjectName(objectNameBase));
- }
- catch (MalformedObjectNameException e) {
- throw new IllegalArgumentException("Invalid Object Name : " + objectNameBase, e);
- }
- }
+ /**
+ * @throws IllegalArgumentException if the supplied objectNameBase name isn't valid
+ */
+ public JmxRegistrationManager(MBeanServer mBeanServer, Cache cache, String objectNameBase) {
+ this.mBeanServer = mBeanServer;
+ this.cacheSpi = (CacheSPI) cache;
+ try {
+ processBaseName(new ObjectName(objectNameBase));
+ }
+ catch (MalformedObjectNameException e) {
+ throw new IllegalArgumentException("Invalid Object Name : " + objectNameBase, e);
+ }
+ }
- /**
- * Defaults to platform to platform MBeanServer.
- *
- * @see java.lang.management.ManagementFactory#getPlatformMBeanServer()
- * @see <a href="http://java.sun.com/j2se/1.5.0/docs/guide/management/mxbeans.html#mbean_server">platform MBeanServer</a>
- */
- public JmxRegistrationManager(Cache cache, ObjectName objectNameBase) {
- this(ManagementFactory.getPlatformMBeanServer(), cache, objectNameBase);
- }
+ /**
+ * Defaults to platform to platform MBeanServer.
+ *
+ * @see java.lang.management.ManagementFactory#getPlatformMBeanServer()
+ * @see <a href="http://java.sun.com/j2se/1.5.0/docs/guide/management/mxbeans.html#mbean_server">platform
+ * MBeanServer</a>
+ */
+ public JmxRegistrationManager(Cache cache, ObjectName objectNameBase) {
+ this(ManagementFactory.getPlatformMBeanServer(), cache, objectNameBase);
+ }
- public JmxRegistrationManager(Cache cache) {
- this(cache, null);
- }
+ public JmxRegistrationManager(Cache cache) {
+ this(cache, null);
+ }
- /**
- * Performs the MBean registration.
- */
- public void registerAllMBeans() throws CacheException
- {
- try {
- List<ResourceDMBean> resourceDMBeans = getResourceDMBeans();
- for (ResourceDMBean resource : resourceDMBeans) {
- String resourceName = resource.getObjectName();
- ObjectName objectName = new ObjectName(getObjectName(resourceName));
- if (!mBeanServer.isRegistered(objectName)) {
- mBeanServer.registerMBean(resource, objectName);
- }
+ /**
+ * Performs the MBean registration.
+ */
+ public void registerAllMBeans() throws CacheException {
+ try {
+ List<ResourceDMBean> resourceDMBeans = getResourceDMBeans();
+ for (ResourceDMBean resource : resourceDMBeans) {
+ String resourceName = resource.getObjectName();
+ ObjectName objectName = new ObjectName(getObjectName(resourceName));
+ if (!mBeanServer.isRegistered(objectName)) {
+ mBeanServer.registerMBean(resource, objectName);
}
- }
- catch (Exception e) {
- throw new CacheException("Failure while registering mbeans", e);
- }
- }
+ }
+ }
+ catch (Exception e) {
+ throw new CacheException("Failure while registering mbeans", e);
+ }
+ }
- /**
- * Unregisters all the MBeans registered through {@link #registerAllMBeans()}.
- */
- public void unregisterAllMBeans() throws CacheException {
- log.trace("Unregistering jmx resources..");
- try {
- List<ResourceDMBean> resourceDMBeans = getResourceDMBeans();
- for (ResourceDMBean resource : resourceDMBeans) {
- String resourceName = resource.getObject().getClass().getSimpleName();
- ObjectName objectName = new ObjectName(getObjectName(resourceName));
- if (mBeanServer.isRegistered(objectName)) {
- mBeanServer.unregisterMBean(objectName);
- }
+ /**
+ * Unregisters all the MBeans registered through {@link #registerAllMBeans()}.
+ */
+ public void unregisterAllMBeans() throws CacheException {
+ log.trace("Unregistering jmx resources..");
+ try {
+ List<ResourceDMBean> resourceDMBeans = getResourceDMBeans();
+ for (ResourceDMBean resource : resourceDMBeans) {
+ String resourceName = resource.getObject().getClass().getSimpleName();
+ ObjectName objectName = new ObjectName(getObjectName(resourceName));
+ if (mBeanServer.isRegistered(objectName)) {
+ mBeanServer.unregisterMBean(objectName);
}
- }
- catch (Exception e) {
- throw new CacheException("Failure while unregistering mbeans", e);
- }
- }
+ }
+ }
+ catch (Exception e) {
+ throw new CacheException("Failure while unregistering mbeans", e);
+ }
+ }
- private List<ResourceDMBean> getResourceDMBeans() {
- List<ResourceDMBean> resourceDMBeans = new ArrayList<ResourceDMBean>();
- for (ComponentRegistry.Component component : cacheSpi.getComponentRegistry().getRegiteredComponents()) {
- ResourceDMBean resourceDMBean = new ResourceDMBean(component.getInstance());
- if (resourceDMBean.isManagedResource()) {
- resourceDMBeans.add(resourceDMBean);
- }
- }
- return resourceDMBeans;
- }
+ private List<ResourceDMBean> getResourceDMBeans() {
+ List<ResourceDMBean> resourceDMBeans = new ArrayList<ResourceDMBean>();
+ for (ComponentRegistry.Component component : cacheSpi.getComponentRegistry().getRegiteredComponents()) {
+ ResourceDMBean resourceDMBean = new ResourceDMBean(component.getInstance());
+ if (resourceDMBean.isManagedResource()) {
+ resourceDMBeans.add(resourceDMBean);
+ }
+ }
+ return resourceDMBeans;
+ }
- private void processBaseName(ObjectName baseName) {
- if (baseName != null) {
- this.objectNameBase = baseName.getCanonicalName();
- return;
- }
- if (cacheSpi.getConfiguration().getCacheMode().equals(Configuration.CacheMode.LOCAL)) {
- objectNameBase = LOCAL_CACHE_PREFIX + System.currentTimeMillis();
- } else //the cache is clustered
- {
- objectNameBase = REPLICATED_CACHE_PREFIX + cacheSpi.getConfiguration().getClusterName();
- }
- }
+ private void processBaseName(ObjectName baseName) {
+ if (baseName != null) {
+ this.objectNameBase = baseName.getCanonicalName();
+ return;
+ }
+ if (cacheSpi.getConfiguration().getCacheMode().equals(Configuration.CacheMode.LOCAL)) {
+ objectNameBase = LOCAL_CACHE_PREFIX + System.currentTimeMillis();
+ } else //the cache is clustered
+ {
+ objectNameBase = REPLICATED_CACHE_PREFIX + cacheSpi.getConfiguration().getClusterName();
+ }
+ }
- public String getObjectName(String resourceName) {
- return objectNameBase + JMX_RESOURCE_KEY + resourceName;
- }
+ public String getObjectName(String resourceName) {
+ return objectNameBase + JMX_RESOURCE_KEY + resourceName;
+ }
- public String getObjectNameBase() {
- return objectNameBase;
- }
+ public String getObjectNameBase() {
+ return objectNameBase;
+ }
}
Modified: core/branches/flat/src/main/java/org/horizon/jmx/JmxStatisticsExposer.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/jmx/JmxStatisticsExposer.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/jmx/JmxStatisticsExposer.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -27,31 +27,27 @@
* Interface containing common cache management operations
*
* @author Jerry Gauthier
- *
* @since 1.0
*/
-public interface JmxStatisticsExposer
-{
+public interface JmxStatisticsExposer {
/**
- * Returns whether an interceptor's statistics are
- * being captured.
+ * Returns whether an interceptor's statistics are being captured.
*
* @return true if statistics are captured
*/
boolean getStatisticsEnabled();
/**
- * Enables an interceptor's cache statistics
- * If true, the interceptor will capture statistics
- * and make them available through the mbean.
+ * Enables an interceptor's cache statistics If true, the interceptor will capture statistics and make them available
+ * through the mbean.
*
* @param enabled true if statistics should be captured
*/
void setStatisticsEnabled(boolean enabled);
/**
- * Returns a map of the cache interceptor's statistics
- * Map is keyed on statistic names (which are Strings) and values are Objects.
+ * Returns a map of the cache interceptor's statistics Map is keyed on statistic names (which are Strings) and values
+ * are Objects.
*
* @return a map containing statistics
*/
Modified: core/branches/flat/src/main/java/org/horizon/jmx/PlatformMBeanServerRegistration.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/jmx/PlatformMBeanServerRegistration.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/jmx/PlatformMBeanServerRegistration.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -31,8 +31,8 @@
import org.horizon.factories.annotations.Stop;
/**
- * If {@link Configuration#getExposeManagementStatistics()} is true, then class will register
- * all the MBeans from the ConfigurationRegistry to the pltform MBean server.
+ * If {@link Configuration#getExposeManagementStatistics()} is true, then class will register all the MBeans from the
+ * ConfigurationRegistry to the pltform MBean server.
* <p/>
* Note: to enable platform MBeanServer the following system property should be passet to the JVM:
* <b>-Dcom.sun.management.jmxremote</b>.
@@ -42,15 +42,13 @@
* @since 1.0
*/
@NonVolatile
-public class PlatformMBeanServerRegistration
-{
+public class PlatformMBeanServerRegistration {
private static final Log log = LogFactory.getLog(PlatformMBeanServerRegistration.class);
private CacheSPI cache;
@Inject
- public void initialize(CacheSPI cache)
- {
+ public void initialize(CacheSPI cache) {
this.cache = cache;
}
@@ -58,13 +56,11 @@
* Here is where the registration is being performed.
*/
@Start(priority = 14)
- public void registerToPlatformMBeanServer()
- {
+ public void registerToPlatformMBeanServer() {
if (cache == null)
throw new IllegalStateException("The cache should had been injected before a call to this method");
Configuration config = cache.getConfiguration();
- if (config.isExposeManagementStatistics())
- {
+ if (config.isExposeManagementStatistics()) {
JmxRegistrationManager jmxRegistrationManager = new JmxRegistrationManager(cache);
jmxRegistrationManager.registerAllMBeans();
log.info("JBossCache MBeans were successfully registered to the platform mbean server.");
@@ -75,14 +71,12 @@
* Unregister when the cache is being stoped.
*/
@Stop
- public void unregisterMBeans()
- {
+ public void unregisterMBeans() {
//this method might get called several times.
// After the first call the cache will become null, so we guard this
if (cache == null) return;
Configuration config = cache.getConfiguration();
- if (config.isExposeManagementStatistics())
- {
+ if (config.isExposeManagementStatistics()) {
JmxRegistrationManager jmxRegistrationManager = new JmxRegistrationManager(cache);
jmxRegistrationManager.unregisterAllMBeans();
log.trace("JBossCache MBeans were successfully unregistered from the platform mbean server.");
Modified: core/branches/flat/src/main/java/org/horizon/jmx/ResourceDMBean.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/jmx/ResourceDMBean.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/jmx/ResourceDMBean.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -46,15 +46,14 @@
import java.util.regex.Pattern;
/**
- * This class was entirely copied from jgroups 2.7 (same name there).
- * Couldn't simply reuse it because jgroups does not ship with MBean, ManagedAttribute and ManagedOperation.
- * Once jgroups will ship these classes, the code can be dinalmically reused from there.
+ * This class was entirely copied from jgroups 2.7 (same name there). Couldn't simply reuse it because jgroups does not
+ * ship with MBean, ManagedAttribute and ManagedOperation. Once jgroups will ship these classes, the code can be
+ * dinalmically reused from there.
*
* @author Mircea.Markus at jboss.com
* @since 1.0
*/
-public class ResourceDMBean implements DynamicMBean
-{
+public class ResourceDMBean implements DynamicMBean {
private static final Class<?>[] primitives = {int.class,
byte.class,
short.class,
@@ -76,8 +75,7 @@
private final HashMap<String, AttributeEntry> atts = new HashMap<String, AttributeEntry>();
private final List<MBeanOperationInfo> ops = new ArrayList<MBeanOperationInfo>();
- public ResourceDMBean(Object instance)
- {
+ public ResourceDMBean(Object instance) {
if (instance == null)
throw new NullPointerException("Cannot make an MBean wrapper for null instance");
@@ -91,12 +89,10 @@
int i = 0;
MBeanAttributeInfo info;
- for (AttributeEntry entry : atts.values())
- {
+ for (AttributeEntry entry : atts.values()) {
info = entry.getInfo();
attrInfo[i++] = info;
- if (log.isInfoEnabled())
- {
+ if (log.isInfoEnabled()) {
log.trace("Attribute " + info.getName()
+ "[r="
+ info.isReadable()
@@ -113,64 +109,54 @@
opInfo = new MBeanOperationInfo[ops.size()];
ops.toArray(opInfo);
- if (log.isInfoEnabled())
- {
+ if (log.isInfoEnabled()) {
if (ops.size() > 0)
log.trace("Operations are:");
- for (MBeanOperationInfo op : opInfo)
- {
+ for (MBeanOperationInfo op : opInfo) {
log.trace("Operation " + op.getReturnType() + " " + op.getName());
}
}
}
- Object getObject()
- {
+ Object getObject() {
return obj;
}
- private void findDescription()
- {
+ private void findDescription() {
MBean mbean = getObject().getClass().getAnnotation(MBean.class);
- if (mbean != null && mbean.description() != null && mbean.description().trim().length() > 0)
- {
+ if (mbean != null && mbean.description() != null && mbean.description().trim().length() > 0) {
description = mbean.description();
- if (log.isDebugEnabled())
- {
+ if (log.isDebugEnabled()) {
log.debug("@MBean description set - " + mbean.description());
}
MBeanAttributeInfo info = new MBeanAttributeInfo(MBEAN_DESCRITION,
- "java.lang.String",
- "@MBean description",
- true,
- false,
- false);
- try
- {
+ "java.lang.String",
+ "@MBean description",
+ true,
+ false,
+ false);
+ try {
atts.put(MBEAN_DESCRITION,
- new FieldAttributeEntry(info, getClass().getDeclaredField("description")));
+ new FieldAttributeEntry(info, getClass().getDeclaredField("description")));
}
- catch (NoSuchFieldException e)
- {
+ catch (NoSuchFieldException e) {
//this should not happen unless somebody removes description field
log.warn("Could not reflect field description of this class. Was it removed?");
}
}
}
- public synchronized MBeanInfo getMBeanInfo()
- {
+ public synchronized MBeanInfo getMBeanInfo() {
return new MBeanInfo(getObject().getClass().getCanonicalName(),
- description,
- attrInfo,
- null,
- opInfo,
- null);
+ description,
+ attrInfo,
+ null,
+ opInfo,
+ null);
}
- public synchronized Object getAttribute(String name)
- {
+ public synchronized Object getAttribute(String name) {
if (name == null || name.length() == 0)
throw new NullPointerException("Invalid attribute requested " + name);
@@ -178,47 +164,35 @@
return attr.getValue();
}
- public synchronized void setAttribute(Attribute attribute)
- {
+ public synchronized void setAttribute(Attribute attribute) {
if (attribute == null || attribute.getName() == null)
throw new NullPointerException("Invalid attribute requested " + attribute);
setNamedAttribute(attribute);
}
- public synchronized AttributeList getAttributes(String[] names)
- {
+ public synchronized AttributeList getAttributes(String[] names) {
AttributeList al = new AttributeList();
- for (String name : names)
- {
+ for (String name : names) {
Attribute attr = getNamedAttribute(name);
- if (attr != null)
- {
+ if (attr != null) {
al.add(attr);
- }
- else
- {
+ } else {
log.warn("Did not find attribute " + name);
}
}
return al;
}
- public synchronized AttributeList setAttributes(AttributeList list)
- {
+ public synchronized AttributeList setAttributes(AttributeList list) {
AttributeList results = new AttributeList();
- for (int i = 0; i < list.size(); i++)
- {
+ for (int i = 0; i < list.size(); i++) {
Attribute attr = (Attribute) list.get(i);
- if (setNamedAttribute(attr))
- {
+ if (setNamedAttribute(attr)) {
results.add(attr);
- }
- else
- {
- if (log.isWarnEnabled())
- {
+ } else {
+ if (log.isWarnEnabled()) {
log.warn("Failed to update attribute name " + attr.getName()
+ " with value "
+ attr.getValue());
@@ -229,42 +203,32 @@
}
public Object invoke(String name, Object[] args, String[] sig) throws MBeanException,
- ReflectionException
- {
- try
- {
- if (log.isDebugEnabled())
- {
+ ReflectionException {
+ try {
+ if (log.isDebugEnabled()) {
log.debug("Invoke method called on " + name);
}
Class<?>[] classes = new Class[sig.length];
- for (int i = 0; i < classes.length; i++)
- {
+ for (int i = 0; i < classes.length; i++) {
classes[i] = getClassForName(sig[i]);
}
Method method = getObject().getClass().getMethod(name, classes);
return method.invoke(getObject(), args);
}
- catch (Exception e)
- {
+ catch (Exception e) {
throw new MBeanException(e);
}
}
- public static Class<?> getClassForName(String name) throws ClassNotFoundException
- {
- try
- {
+ public static Class<?> getClassForName(String name) throws ClassNotFoundException {
+ try {
Class<?> c = Class.forName(name);
return c;
}
- catch (ClassNotFoundException cnfe)
- {
+ catch (ClassNotFoundException cnfe) {
//Could be a primitive - let's check
- for (int i = 0; i < primitives.length; i++)
- {
- if (name.equals(primitives[i].getName()))
- {
+ for (int i = 0; i < primitives.length; i++) {
+ if (name.equals(primitives[i].getName())) {
return primitives[i];
}
}
@@ -272,77 +236,61 @@
throw new ClassNotFoundException("Class " + name + " cannot be found");
}
- private void findMethods()
- {
+ private void findMethods() {
//find all methods but don't include methods from Object class
List<Method> methods = new ArrayList<Method>(Arrays.asList(getObject().getClass().getMethods()));
List<Method> objectMethods = new ArrayList<Method>(Arrays.asList(Object.class.getMethods()));
methods.removeAll(objectMethods);
- for (Method method : methods)
- {
+ for (Method method : methods) {
//does method have @ManagedAttribute annotation?
ManagedAttribute attr = method.getAnnotation(ManagedAttribute.class);
- if (attr != null)
- {
+ if (attr != null) {
String methodName = method.getName();
if (!methodName.startsWith("get") && !methodName.startsWith("set")
- && !methodName.startsWith("is"))
- {
+ && !methodName.startsWith("is")) {
if (log.isWarnEnabled())
log.warn("method name " + methodName
+ " doesn't start with \"get\", \"set\", or \"is\""
+ ", but is annotated with @ManagedAttribute: will be ignored");
- }
- else
- {
+ } else {
MBeanAttributeInfo info = null;
//Is name field of @ManagedAttributed used?
String attributeName = attr.name().length() > 0 ? attr.name().trim() : null;
boolean writeAttribute = false;
- if (isSetMethod(method))
- { // setter
+ if (isSetMethod(method)) { // setter
attributeName = (attributeName == null) ? methodName.substring(3) : attributeName;
info = new MBeanAttributeInfo(attributeName,
- method.getParameterTypes()[0].getCanonicalName(),
- attr.description(),
- true,
- true,
- false);
+ method.getParameterTypes()[0].getCanonicalName(),
+ attr.description(),
+ true,
+ true,
+ false);
writeAttribute = true;
- }
- else
- { // getter
- if (method.getParameterTypes().length == 0 && method.getReturnType() != java.lang.Void.TYPE)
- {
+ } else { // getter
+ if (method.getParameterTypes().length == 0 && method.getReturnType() != java.lang.Void.TYPE) {
boolean hasSetter = atts.containsKey(attributeName);
//we found is method
- if (methodName.startsWith("is"))
- {
+ if (methodName.startsWith("is")) {
attributeName = (attributeName == null) ? methodName.substring(2) : attributeName;
info = new MBeanAttributeInfo(attributeName,
- method.getReturnType().getCanonicalName(),
- attr.description(),
- true,
- hasSetter,
- true);
- }
- else
- {
+ method.getReturnType().getCanonicalName(),
+ attr.description(),
+ true,
+ hasSetter,
+ true);
+ } else {
//this has to be get
attributeName = (attributeName == null) ? methodName.substring(3) : attributeName;
info = new MBeanAttributeInfo(attributeName,
- method.getReturnType().getCanonicalName(),
- attr.description(),
- true,
- hasSetter,
- false);
+ method.getReturnType().getCanonicalName(),
+ attr.description(),
+ true,
+ hasSetter,
+ false);
}
- }
- else
- {
- if (log.isWarnEnabled())
- {
+ } else {
+ if (log.isWarnEnabled()) {
log.warn("Method " + method.getName()
+ " must have a valid return type and zero parameters");
}
@@ -352,134 +300,108 @@
AttributeEntry ae = atts.get(attributeName);
//is it a read method?
- if (!writeAttribute)
- {
+ if (!writeAttribute) {
//we already have annotated field as read
- if (ae instanceof FieldAttributeEntry && ae.getInfo().isReadable())
- {
+ if (ae instanceof FieldAttributeEntry && ae.getInfo().isReadable()) {
log.warn("not adding annotated method " + method
+ " since we already have read attribute");
}
//we already have annotated set method
- else if (ae instanceof MethodAttributeEntry)
- {
+ else if (ae instanceof MethodAttributeEntry) {
MethodAttributeEntry mae = (MethodAttributeEntry) ae;
- if (mae.hasSetMethod())
- {
+ if (mae.hasSetMethod()) {
atts.put(attributeName,
- new MethodAttributeEntry(mae.getInfo(), mae.getSetMethod(), method));
+ new MethodAttributeEntry(mae.getInfo(), mae.getSetMethod(), method));
}
} //we don't have such entry
- else
- {
+ else {
atts.put(attributeName, new MethodAttributeEntry(info, null, method));
}
}//is it a set method?
- else
- {
- if (ae instanceof FieldAttributeEntry)
- {
+ else {
+ if (ae instanceof FieldAttributeEntry) {
//we already have annotated field as write
- if (ae.getInfo().isWritable())
- {
+ if (ae.getInfo().isWritable()) {
log.warn("Not adding annotated method " + methodName
+ " since we already have writable attribute");
- }
- else
- {
+ } else {
//we already have annotated field as read
//lets make the field writable
Field f = ((FieldAttributeEntry) ae).getField();
MBeanAttributeInfo i = new MBeanAttributeInfo(ae.getInfo().getName(),
- f.getType().getCanonicalName(),
- attr.description(),
- true,
- Modifier.isFinal(f.getModifiers()) ? false : true,
- false);
+ f.getType().getCanonicalName(),
+ attr.description(),
+ true,
+ Modifier.isFinal(f.getModifiers()) ? false : true,
+ false);
atts.put(attributeName, new FieldAttributeEntry(i, f));
}
}
//we already have annotated getOrIs method
- else if (ae instanceof MethodAttributeEntry)
- {
+ else if (ae instanceof MethodAttributeEntry) {
MethodAttributeEntry mae = (MethodAttributeEntry) ae;
- if (mae.hasIsOrGetMethod())
- {
+ if (mae.hasIsOrGetMethod()) {
atts.put(attributeName,
- new MethodAttributeEntry(info,
- method,
- mae.getIsOrGetMethod()));
+ new MethodAttributeEntry(info,
+ method,
+ mae.getIsOrGetMethod()));
}
} //we don't have such entry
- else
- {
+ else {
atts.put(attributeName, new MethodAttributeEntry(info, method, null));
}
}
}
- }
- else if (method.isAnnotationPresent(ManagedOperation.class) || isMBeanAnnotationPresentWithExposeAll())
- {
+ } else if (method.isAnnotationPresent(ManagedOperation.class) || isMBeanAnnotationPresentWithExposeAll()) {
ManagedOperation op = method.getAnnotation(ManagedOperation.class);
String attName = method.getName();
- if (isSetMethod(method) || isGetMethod(method))
- {
+ if (isSetMethod(method) || isGetMethod(method)) {
attName = attName.substring(3);
- }
- else if (isIsMethod(method))
- {
+ } else if (isIsMethod(method)) {
attName = attName.substring(2);
}
//expose unless we already exposed matching attribute field
boolean isAlreadyExposed = atts.containsKey(attName);
- if (!isAlreadyExposed)
- {
+ if (!isAlreadyExposed) {
ops.add(new MBeanOperationInfo(op != null ? op.description() : "", method));
}
}
}
}
- private boolean isSetMethod(Method method)
- {
+ private boolean isSetMethod(Method method) {
return (method.getName().startsWith("set") &&
method.getParameterTypes().length == 1 &&
method.getReturnType() == java.lang.Void.TYPE);
}
- private boolean isGetMethod(Method method)
- {
+ private boolean isGetMethod(Method method) {
return (method.getParameterTypes().length == 0 &&
method.getReturnType() != java.lang.Void.TYPE &&
method.getName().startsWith("get"));
}
- private boolean isIsMethod(Method method)
- {
+ private boolean isIsMethod(Method method) {
return (method.getParameterTypes().length == 0 &&
(method.getReturnType() == boolean.class || method.getReturnType() == Boolean.class) &&
method.getName().startsWith("is"));
}
- private void findFields()
- {
+ private void findFields() {
//traverse class hierarchy and find all annotated fields
- for (Class<?> clazz = getObject().getClass(); clazz != null; clazz = clazz.getSuperclass())
- {
+ for (Class<?> clazz = getObject().getClass(); clazz != null; clazz = clazz.getSuperclass()) {
Field[] fields = clazz.getDeclaredFields();
- for (Field field : fields)
- {
+ for (Field field : fields) {
ManagedAttribute attr = field.getAnnotation(ManagedAttribute.class);
- if (attr != null)
- {
+ if (attr != null) {
String fieldName = renameToJavaCodingConvention(field.getName());
MBeanAttributeInfo info = new MBeanAttributeInfo(fieldName,
- field.getType().getCanonicalName(),
- attr.description(),
- true,
- Modifier.isFinal(field.getModifiers()) ? false : attr.writable(),
- false);
+ field.getType().getCanonicalName(),
+ attr.description(),
+ true,
+ Modifier.isFinal(field.getModifiers()) ? false : attr.writable(),
+ false);
atts.put(fieldName, new FieldAttributeEntry(info, field));
}
@@ -487,21 +409,15 @@
}
}
- private Attribute getNamedAttribute(String name)
- {
+ private Attribute getNamedAttribute(String name) {
Attribute result = null;
- if (name.equals(MBEAN_DESCRITION))
- {
+ if (name.equals(MBEAN_DESCRITION)) {
result = new Attribute(MBEAN_DESCRITION, this.description);
- }
- else
- {
+ } else {
AttributeEntry entry = atts.get(name);
- if (entry != null)
- {
+ if (entry != null) {
MBeanAttributeInfo i = entry.getInfo();
- try
- {
+ try {
result = new Attribute(name, entry.invoke(null));
if (log.isDebugEnabled())
log.debug("Attribute " + name
@@ -514,21 +430,17 @@
+ " and value "
+ result.getValue());
}
- catch (Exception e)
- {
+ catch (Exception e) {
log.debug("Exception while reading value of attribute " + name, e);
}
- }
- else
- {
+ } else {
log.warn("Did not find queried attribute with name " + name);
}
}
return result;
}
- private boolean setNamedAttribute(Attribute attribute)
- {
+ private boolean setNamedAttribute(Attribute attribute) {
boolean result = false;
if (log.isDebugEnabled())
log.debug("Invoking set on attribute " + attribute.getName()
@@ -536,20 +448,15 @@
+ attribute.getValue());
AttributeEntry entry = atts.get(attribute.getName());
- if (entry != null)
- {
- try
- {
+ if (entry != null) {
+ try {
entry.invoke(attribute);
result = true;
}
- catch (Exception e)
- {
+ catch (Exception e) {
log.warn("Exception while writing value for attribute " + attribute.getName(), e);
}
- }
- else
- {
+ } else {
log.warn("Could not invoke set on attribute " + attribute.getName()
+ " with value "
+ attribute.getValue());
@@ -558,46 +465,35 @@
}
- private String renameToJavaCodingConvention(String fieldName)
- {
- if (fieldName.contains("_"))
- {
+ private String renameToJavaCodingConvention(String fieldName) {
+ if (fieldName.contains("_")) {
Pattern p = Pattern.compile("_.");
Matcher m = p.matcher(fieldName);
StringBuffer sb = new StringBuffer();
- while (m.find())
- {
+ while (m.find()) {
m.appendReplacement(sb, fieldName.substring(m.end() - 1, m.end()).toUpperCase());
}
m.appendTail(sb);
char first = sb.charAt(0);
- if (Character.isLowerCase(first))
- {
+ if (Character.isLowerCase(first)) {
sb.setCharAt(0, Character.toUpperCase(first));
}
return sb.toString();
- }
- else
- {
- if (Character.isLowerCase(fieldName.charAt(0)))
- {
+ } else {
+ if (Character.isLowerCase(fieldName.charAt(0))) {
return fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
- }
- else
- {
+ } else {
return fieldName;
}
}
}
- private boolean isMBeanAnnotationPresentWithExposeAll()
- {
+ private boolean isMBeanAnnotationPresentWithExposeAll() {
Class<?> c = getObject().getClass();
return c.isAnnotationPresent(MBean.class) && c.getAnnotation(MBean.class).exposeAll();
}
- private class MethodAttributeEntry implements AttributeEntry
- {
+ private class MethodAttributeEntry implements AttributeEntry {
final MBeanAttributeInfo info;
@@ -607,16 +503,14 @@
public MethodAttributeEntry(final MBeanAttributeInfo info,
final Method setMethod,
- final Method isOrGetMethod)
- {
+ final Method isOrGetMethod) {
super();
this.info = info;
this.setMethod = setMethod;
this.isOrGetmethod = isOrGetMethod;
}
- public Object invoke(Attribute a) throws Exception
- {
+ public Object invoke(Attribute a) throws Exception {
if (a == null && isOrGetmethod != null)
return isOrGetmethod.invoke(getObject(), new Object[]{});
else if (a != null && setMethod != null)
@@ -625,102 +519,81 @@
return null;
}
- public MBeanAttributeInfo getInfo()
- {
+ public MBeanAttributeInfo getInfo() {
return info;
}
- public boolean hasIsOrGetMethod()
- {
+ public boolean hasIsOrGetMethod() {
return isOrGetmethod != null;
}
- public boolean hasSetMethod()
- {
+ public boolean hasSetMethod() {
return setMethod != null;
}
- public Method getIsOrGetMethod()
- {
+ public Method getIsOrGetMethod() {
return isOrGetmethod;
}
- public Method getSetMethod()
- {
+ public Method getSetMethod() {
return setMethod;
}
}
- private class FieldAttributeEntry implements AttributeEntry
- {
+ private class FieldAttributeEntry implements AttributeEntry {
private final MBeanAttributeInfo info;
private final Field field;
- public FieldAttributeEntry(final MBeanAttributeInfo info, final Field field)
- {
+ public FieldAttributeEntry(final MBeanAttributeInfo info, final Field field) {
super();
this.info = info;
this.field = field;
- if (!field.isAccessible())
- {
+ if (!field.isAccessible()) {
field.setAccessible(true);
}
}
- public Field getField()
- {
+ public Field getField() {
return field;
}
- public Object invoke(Attribute a) throws Exception
- {
- if (a == null)
- {
+ public Object invoke(Attribute a) throws Exception {
+ if (a == null) {
return field.get(getObject());
- }
- else
- {
+ } else {
field.set(getObject(), a.getValue());
return null;
}
}
- public MBeanAttributeInfo getInfo()
- {
+ public MBeanAttributeInfo getInfo() {
return info;
}
}
- private interface AttributeEntry
- {
+ private interface AttributeEntry {
public Object invoke(Attribute a) throws Exception;
public MBeanAttributeInfo getInfo();
}
- public boolean isManagedResource()
- {
+ public boolean isManagedResource() {
return !atts.isEmpty() || !ops.isEmpty();
}
- public String getObjectName()
- {
+ public String getObjectName() {
MBean mBean = obj.getClass().getAnnotation(MBean.class);
- if (mBean != null && mBean.objectName() != null && mBean.objectName().trim().length() > 0)
- {
+ if (mBean != null && mBean.objectName() != null && mBean.objectName().trim().length() > 0) {
return mBean.objectName();
}
return obj.getClass().getSimpleName();
}
- public boolean isOperationRegistred(String operationName)
- {
- for (MBeanOperationInfo opInfo : this.ops)
- {
- if (opInfo.getName().equals(operationName))
- {
+ public boolean isOperationRegistred(String operationName) {
+ for (MBeanOperationInfo opInfo : this.ops) {
+ if (opInfo.getName().equals(operationName)) {
return true;
}
}
Modified: core/branches/flat/src/main/java/org/horizon/jmx/annotations/MBean.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/jmx/annotations/MBean.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/jmx/annotations/MBean.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -28,9 +28,9 @@
import java.lang.annotation.Target;
/**
- * Classes anotaded with this will be exposed as MBeans.
- * If you are looking for more fined grained way of exposing jmx attributes/operations, take a look at
- * {@link org.horizon.jmx.annotations.ManagedAttribute} and {@link org.horizon.jmx.annotations.ManagedOperation}
+ * Classes anotaded with this will be exposed as MBeans. If you are looking for more fined grained way of exposing jmx
+ * attributes/operations, take a look at {@link org.horizon.jmx.annotations.ManagedAttribute} and {@link
+ * org.horizon.jmx.annotations.ManagedOperation}
*
* @author Mircea.Markus at jboss.com
* @since 1.0
@@ -38,8 +38,7 @@
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
@Inherited
-public @interface MBean
-{
+public @interface MBean {
String objectName() default "";
boolean exposeAll() default false;
Modified: core/branches/flat/src/main/java/org/horizon/jmx/annotations/ManagedAttribute.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/jmx/annotations/ManagedAttribute.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/jmx/annotations/ManagedAttribute.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -27,19 +27,16 @@
import java.lang.annotation.Target;
/**
- * Indicates that a public method or a field (any visibility) in
- * an MBean class defines an MBean attribute. This annotation can
- * be applied to either a field or a public setter and/or getter
- * method of a public class that is itself is optionally annotated
- * with an @MBean annotation, or inherits such an annotation from
- * a superclass.
- * @since 1.0
+ * Indicates that a public method or a field (any visibility) in an MBean class defines an MBean attribute. This
+ * annotation can be applied to either a field or a public setter and/or getter method of a public class that is itself
+ * is optionally annotated with an @MBean annotation, or inherits such an annotation from a superclass.
+ *
* @author (various)
+ * @since 1.0
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.FIELD})
-public @interface ManagedAttribute
-{
+public @interface ManagedAttribute {
String description() default "";
String name() default "";
Modified: core/branches/flat/src/main/java/org/horizon/jmx/annotations/ManagedOperation.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/jmx/annotations/ManagedOperation.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/jmx/annotations/ManagedOperation.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -27,17 +27,15 @@
import java.lang.annotation.Target;
/**
- * Indicates that a method in an MBean class defines an MBean
- * operation. @ManagedOperation annotation can be applied to a
- * public method of a public class that is itself optionally
- * annotated with an @MBean annotation, or inherits such an
+ * Indicates that a method in an MBean class defines an MBean operation. @ManagedOperation annotation can be applied to
+ * a public method of a public class that is itself optionally annotated with an @MBean annotation, or inherits such an
* annotation from a superclass.
- * @since 1.0
+ *
* @author (various)
+ * @since 1.0
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
-public @interface ManagedOperation
-{
+public @interface ManagedOperation {
String description() default "";
}
Modified: core/branches/flat/src/main/java/org/horizon/lifecycle/Lifecycle.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/lifecycle/Lifecycle.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/lifecycle/Lifecycle.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -27,8 +27,7 @@
* @author Manik Surtani (<a href="mailto:manik at jboss.org">manik at jboss.org</a>)
* @since 1.0
*/
-public interface Lifecycle
-{
+public interface Lifecycle {
void start();
void stop();
Modified: core/branches/flat/src/main/java/org/horizon/loader/AbstractCacheLoader.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/loader/AbstractCacheLoader.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/loader/AbstractCacheLoader.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -37,90 +37,77 @@
import java.util.concurrent.ConcurrentHashMap;
/**
- * A convenience abstract implementation of a {@link CacheLoader}. Specific methods to note are methods like
- * {@link #storeState(Fqn,java.io.ObjectInputStream)}, {@link #loadState(Fqn,java.io.ObjectOutputStream)},
- * {@link #storeEntireState(java.io.ObjectInputStream)} and {@link #loadEntireState(java.io.ObjectOutputStream)} which have convenience
- * implementations here.
+ * A convenience abstract implementation of a {@link CacheLoader}. Specific methods to note are methods like {@link
+ * #storeState(Fqn,java.io.ObjectInputStream)}, {@link #loadState(Fqn,java.io.ObjectOutputStream)}, {@link
+ * #storeEntireState(java.io.ObjectInputStream)} and {@link #loadEntireState(java.io.ObjectOutputStream)} which have
+ * convenience implementations here.
* <p/>
- * Also useful to note is the implementation of {@link #put(java.util.List)}, used during the prepare phase of a transaction.
+ * Also useful to note is the implementation of {@link #put(java.util.List)}, used during the prepare phase of a
+ * transaction.
* <p/>
*
* @author <a href="mailto:manik at jboss.org">Manik Surtani (manik at jboss.org)</a>
* @author <a href="mailto:galder.zamarreno at jboss.com">Galder Zamarreno</a>
* @since 1.0
*/
-public abstract class AbstractCacheLoader<K, V> implements CacheLoader<K,V>
-{
- protected CacheSPI<K,V> cache;
+public abstract class AbstractCacheLoader<K, V> implements CacheLoader<K, V> {
+ protected CacheSPI<K, V> cache;
private static final Log log = LogFactory.getLog(AbstractCacheLoader.class);
private static final boolean trace = log.isTraceEnabled();
/**
- * HashMap<Object,List<Modification>>. List of open transactions. Note that this is purely transient, as
- * we don't use a log, recovery is not available
+ * HashMap<Object,List<Modification>>. List of open transactions. Note that this is purely transient, as we don't use
+ * a log, recovery is not available
*/
protected Map<Object, List<Modification>> transactions = new ConcurrentHashMap<Object, List<Modification>>();
- public void storeEntireState(ObjectInputStream in)
- {
+ public void storeEntireState(ObjectInputStream in) {
// store new state
Object objectFromStream;
- try
- {
+ try {
objectFromStream = cache.getMarshaller().objectFromObjectStream(in);
}
- catch (Exception e)
- {
+ catch (Exception e) {
throw new CacheException(e.getMessage(), e);
}
- if (objectFromStream instanceof EntryDataMarker)
- {
+ if (objectFromStream instanceof EntryDataMarker) {
// no persistent state sent across; return?
if (trace) log.trace("Empty persistent stream?");
return;
}
- if (objectFromStream instanceof EntryDataExceptionMarker)
- {
+ if (objectFromStream instanceof EntryDataExceptionMarker) {
EntryDataExceptionMarker ndem = (EntryDataExceptionMarker) objectFromStream;
throw new CacheException("State provider cacheloader at node " + ndem.getCacheNodeIdentity()
+ " threw exception during loadState (see Caused by)", ndem.getCause());
}
List<EntryData<K, V>> data = (List<EntryData<K, V>>) objectFromStream;
- for (EntryData<K, V> datem : data)
- {
+ for (EntryData<K, V> datem : data) {
put(datem.getKey(), datem.getValue());
}
}
- public void loadEntireState(ObjectOutputStream os)
- {
- List<EntryData<K,V>> list = getAllEntries();
+ public void loadEntireState(ObjectOutputStream os) {
+ List<EntryData<K, V>> list = getAllEntries();
if (trace) log.trace("Loading state of " + list.size() + " nodes into stream");
- try
- {
+ try {
cache.getMarshaller().objectToObjectStream(list, os);
}
- catch (Exception e)
- {
+ catch (Exception e) {
throw new CacheException(e.getMessage(), e);
}
}
- public void setCache(CacheSPI<K,V> c)
- {
+ public void setCache(CacheSPI<K, V> c) {
this.cache = c;
}
- public void put(List<Modification> modifications)
- {
- for (Modification m : modifications)
- {
- switch (m.getType())
- {
+ public void put(List<Modification> modifications) {
+ for (Modification m : modifications) {
+ switch (m.getType()) {
case PUT:
- put((K)m.getKey(), (V)m.getValue());
+ put((K) m.getKey(), (V) m.getValue());
break;
case REMOVE:
remove(m.getKey());
@@ -134,55 +121,43 @@
}
}
- protected Marshaller getMarshaller()
- {
+ protected Marshaller getMarshaller() {
return cache.getMarshaller();
}
// empty implementations for loaders that do not wish to implement lifecycle.
- public void create()
- {
+ public void create() {
}
- public void start()
- {
+ public void start() {
}
- public void stop()
- {
+ public void stop() {
}
- public void destroy()
- {
+ public void destroy() {
}
// Adds simple transactional capabilities to cache loaders that are inherently non-transactional. If your cache loader implementation
// is tansactional though, then override these.
- public void prepare(Object tx, List<Modification> modifications, boolean one_phase)
- {
- if (one_phase)
- {
+ public void prepare(Object tx, List<Modification> modifications, boolean one_phase) {
+ if (one_phase) {
put(modifications);
- }
- else
- {
+ } else {
transactions.put(tx, modifications);
}
}
- public void commit(Object tx)
- {
+ public void commit(Object tx) {
List<Modification> modifications = transactions.remove(tx);
- if (modifications == null)
- {
+ if (modifications == null) {
throw new CacheException("transaction " + tx + " not found in transaction table");
}
put(modifications);
}
- public void rollback(Object tx)
- {
+ public void rollback(Object tx) {
transactions.remove(tx);
}
}
Modified: core/branches/flat/src/main/java/org/horizon/loader/AbstractDelegatingCacheLoader.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/loader/AbstractDelegatingCacheLoader.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/loader/AbstractDelegatingCacheLoader.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -30,127 +30,104 @@
import java.util.List;
/**
- * AbstractDelegatingCacheLoader provides standard functionality for a cache loader that simply delegates each
- * operation defined in the cache loader interface to the underlying cache loader, basically acting as a proxy to the
- * real cache loader.
+ * AbstractDelegatingCacheLoader provides standard functionality for a cache loader that simply delegates each operation
+ * defined in the cache loader interface to the underlying cache loader, basically acting as a proxy to the real cache
+ * loader.
* <p/>
- * Any cache loader implementation that extends this class would be required to override any of the methods in
- * order to provide a different or added behaviour.
+ * Any cache loader implementation that extends this class would be required to override any of the methods in order to
+ * provide a different or added behaviour.
*
* @author <a href="mailto:galder.zamarreno at jboss.com">Galder Zamarreno</a>
* @since 1.0
*/
-public abstract class AbstractDelegatingCacheLoader<K,V> extends AbstractCacheLoader<K,V>
-{
- private CacheLoader<K,V> cacheLoader;
+public abstract class AbstractDelegatingCacheLoader<K, V> extends AbstractCacheLoader<K, V> {
+ private CacheLoader<K, V> cacheLoader;
- public AbstractDelegatingCacheLoader(CacheLoader<K,V> cacheLoader)
- {
+ public AbstractDelegatingCacheLoader(CacheLoader<K, V> cacheLoader) {
this.cacheLoader = cacheLoader;
}
- public void clear()
- {
+ public void clear() {
cacheLoader.clear();
}
- public void commit(Object tx)
- {
+ public void commit(Object tx) {
cacheLoader.commit(tx);
}
- public void create()
- {
+ public void create() {
cacheLoader.create();
}
- public void destroy()
- {
+ public void destroy() {
cacheLoader.destroy();
}
- public boolean exists(Object key)
- {
+ public boolean exists(Object key) {
return cacheLoader.exists(key);
}
- public V get(Object key)
- {
+ public V get(Object key) {
return cacheLoader.get(key);
}
- public List<EntryData<K, V>> getAllEntries()
- {
+ public List<EntryData<K, V>> getAllEntries() {
return cacheLoader.getAllEntries();
}
- public IndividualCacheLoaderConfig getConfig()
- {
+ public IndividualCacheLoaderConfig getConfig() {
return cacheLoader.getConfig();
}
- public void loadEntireState(ObjectOutputStream os)
- {
+ public void loadEntireState(ObjectOutputStream os) {
cacheLoader.loadEntireState(os);
}
- public void prepare(Object tx, List<Modification> modifications, boolean one_phase)
- {
+ public void prepare(Object tx, List<Modification> modifications, boolean one_phase) {
cacheLoader.prepare(tx, modifications, one_phase);
}
- public V put(K key, V value)
- {
+ public V put(K key, V value) {
return cacheLoader.put(key, value);
}
- public void put(List<Modification> modifications)
- {
+ public void put(List<Modification> modifications) {
cacheLoader.put(modifications);
}
- public V remove(Object key)
- {
+ public V remove(Object key) {
return cacheLoader.remove(key);
}
- public void rollback(Object tx)
- {
+ public void rollback(Object tx) {
cacheLoader.rollback(tx);
}
- public void setCache(CacheSPI<K, V> c)
- {
+ public void setCache(CacheSPI<K, V> c) {
cacheLoader.setCache(c);
}
- public void setConfig(IndividualCacheLoaderConfig config)
- {
+ public void setConfig(IndividualCacheLoaderConfig config) {
cacheLoader.setConfig(config);
}
- public void start()
- {
+ public void start() {
cacheLoader.start();
}
- public void stop()
- {
+ public void stop() {
cacheLoader.stop();
}
- public void storeEntireState(ObjectInputStream is)
- {
+ public void storeEntireState(ObjectInputStream is) {
cacheLoader.storeEntireState(is);
}
- public CacheLoader<K,V> getCacheLoader()
- {
+ public CacheLoader<K, V> getCacheLoader() {
return cacheLoader;
}
- public void setCacheLoader(CacheLoader<K,V> cacheLoader)
- {
+ public void setCacheLoader(CacheLoader<K, V> cacheLoader) {
this.cacheLoader = cacheLoader;
}
}
Modified: core/branches/flat/src/main/java/org/horizon/loader/AsyncCacheLoader.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/loader/AsyncCacheLoader.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/loader/AsyncCacheLoader.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -28,71 +28,53 @@
import java.util.ArrayList;
import java.util.List;
-import java.util.concurrent.*;
+import java.util.concurrent.ArrayBlockingQueue;
+import java.util.concurrent.BlockingQueue;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.ThreadFactory;
+import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
/**
- * The AsyncCacheLoader is a delegating cache loader that extends
- * AbstractDelegatingCacheLoader overriding methods to that should not
- * just delegate the operation to the underlying cache loader.
+ * The AsyncCacheLoader is a delegating cache loader that extends AbstractDelegatingCacheLoader overriding methods to
+ * that should not just delegate the operation to the underlying cache loader.
* <p/>
- * Read operations are done synchronously, while write (CRUD - Create, Remove,
- * Update, Delete) operations are done asynchronously. There is no provision
- * for exception handling at the moment for problems encountered with the
- * underlying CacheLoader during a CRUD operation, and the exception is just
- * logged.
+ * Read operations are done synchronously, while write (CRUD - Create, Remove, Update, Delete) operations are done
+ * asynchronously. There is no provision for exception handling at the moment for problems encountered with the
+ * underlying CacheLoader during a CRUD operation, and the exception is just logged.
* <p/>
* When configuring the CacheLoader, use the following attribute:
* <p/>
- * <code>
- * <attribute name="CacheLoaderAsynchronous">true</attribute>
- * </code>
+ * <code> <attribute name="CacheLoaderAsynchronous">true</attribute> </code>
* <p/>
- * to define whether cache loader operations are to be asynchronous. If not
- * specified, a cache loader operation is assumed synchronous.
+ * to define whether cache loader operations are to be asynchronous. If not specified, a cache loader operation is
+ * assumed synchronous.
* <p/>
* <p/>
- * The following additional parameters are available:
- * <dl>
- * <dt>cache.async.batchSize</dt>
- * <dd>Number of modifications to commit in one transaction, default is
- * 100. The minimum batch size is 1.</dd>
- * <dt>cache.async.pollWait</dt>
- * <dd>How long to wait before processing an incomplete batch, in
- * milliseconds. Default is 100. Set this to 0 to not wait before processing
- * available records.</dd>
- * <dt>cache.async.returnOld</dt>
- * <dd>If <code>true</code>, this loader returns the old values from {@link
- * #put} and {@link #remove} methods. Otherwise, these methods always return
- * null. Default is true. <code>false</code> improves the performance of these
- * operations.</dd>
- * <dt>cache.async.queueSize</dt>
- * <dd>Maximum number of entries to enqueue for asynchronous processing.
- * Lowering this size may help prevent out-of-memory conditions. It also may
- * help to prevent less records lost in the case of JVM failure. Default is
- * 10,000 operations.</dd>
- * <dt>cache.async.put</dt>
- * <dd>If set to false, all {@link #put} operations will be processed
- * synchronously, and then only the {@link #remove} operations will be
- * processed asynchronously. This mode may be useful for processing
- * expiration of messages within a separate thread and keeping other
- * operations synchronous for reliability.
- * </dd>
- * <dt>cache.async.threadPoolSize</dt>
- * <dd>The size of the async processor thread pool. Defaults to <tt>1</tt>. This
- * property is new in JBoss Cache 3.0.</dd>
- * </dl>
- * For increased performance for many smaller transactions, use higher values
- * for <code>cache.async.batchSize</code> and
- * <code>cache.async.pollWait</code>. For larger sized records, use a smaller
- * value for <code>cache.async.queueSize</code>.
+ * The following additional parameters are available: <dl> <dt>cache.async.batchSize</dt> <dd>Number of modifications to
+ * commit in one transaction, default is 100. The minimum batch size is 1.</dd> <dt>cache.async.pollWait</dt> <dd>How
+ * long to wait before processing an incomplete batch, in milliseconds. Default is 100. Set this to 0 to not wait
+ * before processing available records.</dd> <dt>cache.async.returnOld</dt> <dd>If <code>true</code>, this loader
+ * returns the old values from {@link #put} and {@link #remove} methods. Otherwise, these methods always return null.
+ * Default is true. <code>false</code> improves the performance of these operations.</dd>
+ * <dt>cache.async.queueSize</dt> <dd>Maximum number of entries to enqueue for asynchronous processing. Lowering this
+ * size may help prevent out-of-memory conditions. It also may help to prevent less records lost in the case of JVM
+ * failure. Default is 10,000 operations.</dd> <dt>cache.async.put</dt> <dd>If set to false, all {@link #put}
+ * operations will be processed synchronously, and then only the {@link #remove} operations will be processed
+ * asynchronously. This mode may be useful for processing expiration of messages within a separate thread and keeping
+ * other operations synchronous for reliability. </dd> <dt>cache.async.threadPoolSize</dt> <dd>The size of the async
+ * processor thread pool. Defaults to <tt>1</tt>. This property is new in JBoss Cache 3.0.</dd> </dl> For increased
+ * performance for many smaller transactions, use higher values for <code>cache.async.batchSize</code> and
+ * <code>cache.async.pollWait</code>. For larger sized records, use a smaller value for
+ * <code>cache.async.queueSize</code>.
*
* @author Manik Surtani (manik.surtani at jboss.com)
* @since 1.0
*/
-public class AsyncCacheLoader<K, V> extends AbstractDelegatingCacheLoader<K, V>
-{
+public class AsyncCacheLoader<K, V> extends AbstractDelegatingCacheLoader<K, V> {
private static final Log log = LogFactory.getLog(AsyncCacheLoader.class);
private static final boolean trace = log.isTraceEnabled();
@@ -110,30 +92,23 @@
private BlockingQueue<Modification> queue = new ArrayBlockingQueue<Modification>(DEFAULT_QUEUE_SIZE);
private List<Future> processorFutures;
- public AsyncCacheLoader()
- {
+ public AsyncCacheLoader() {
super(null);
}
- public AsyncCacheLoader(CacheLoader<K, V> cacheLoader)
- {
+ public AsyncCacheLoader(CacheLoader<K, V> cacheLoader) {
super(cacheLoader);
}
@Override
- public void setConfig(IndividualCacheLoaderConfig base)
- {
- if (base instanceof AsyncCacheLoaderConfig)
- {
+ public void setConfig(IndividualCacheLoaderConfig base) {
+ if (base instanceof AsyncCacheLoaderConfig) {
config = (AsyncCacheLoaderConfig) base;
- }
- else
- {
+ } else {
config = new AsyncCacheLoaderConfig(base);
}
- if (config.getQueueSize() > 0)
- {
+ if (config.getQueueSize() > 0) {
queue = new ArrayBlockingQueue<Modification>(config.getQueueSize());
}
@@ -141,40 +116,30 @@
}
@Override
- public V put(K key, V value)
- {
- if (config.getUseAsyncPut())
- {
+ public V put(K key, V value) {
+ if (config.getUseAsyncPut()) {
V oldValue = get(key);
Modification mod = new Modification(Modification.ModificationType.PUT, key, value);
enqueue(mod);
return oldValue;
- }
- else
- {
+ } else {
return super.put(key, value);
}
}
@Override
- public void put(List<Modification> modifications)
- {
- if (config.getUseAsyncPut())
- {
- for (Modification modification : modifications)
- {
+ public void put(List<Modification> modifications) {
+ if (config.getUseAsyncPut()) {
+ for (Modification modification : modifications) {
enqueue(modification);
}
- }
- else
- {
+ } else {
super.put(modifications);
}
}
@Override
- public V remove(Object key)
- {
+ public V remove(Object key) {
V oldValue = get(key);
Modification mod = new Modification(Modification.ModificationType.REMOVE, key, null);
enqueue(mod);
@@ -182,15 +147,12 @@
}
@Override
- public void start()
- {
+ public void start() {
if (log.isInfoEnabled()) log.info("Async cache loader starting: " + this);
stopped.set(false);
super.start();
- executor = Executors.newFixedThreadPool(config.getThreadPoolSize(), new ThreadFactory()
- {
- public Thread newThread(Runnable r)
- {
+ executor = Executors.newFixedThreadPool(config.getThreadPoolSize(), new ThreadFactory() {
+ public Thread newThread(Runnable r) {
Thread t = new Thread(r, "AsyncCacheLoader-" + threadId.getAndIncrement());
t.setDaemon(true);
return t;
@@ -201,23 +163,18 @@
}
@Override
- public void stop()
- {
+ public void stop() {
stopped.set(true);
- if (executor != null)
- {
+ if (executor != null) {
for (Future f : processorFutures) f.cancel(true);
executor.shutdown();
- try
- {
+ try {
boolean terminated = executor.isTerminated();
- while (!terminated)
- {
+ while (!terminated) {
terminated = executor.awaitTermination(60, TimeUnit.SECONDS);
}
}
- catch (InterruptedException e)
- {
+ catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
@@ -225,19 +182,15 @@
super.stop();
}
- private void enqueue(final Modification mod)
- {
- if (stopped.get())
- {
+ private void enqueue(final Modification mod) {
+ if (stopped.get()) {
throw new CacheException("AsyncCacheLoader stopped; no longer accepting more entries.");
}
if (trace) log.trace("Enqueuing modification " + mod);
- try
- {
+ try {
queue.put(mod);
}
- catch (InterruptedException e)
- {
+ catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
@@ -247,67 +200,53 @@
*
* @author manik surtani
*/
- private class AsyncProcessor implements Runnable
- {
+ private class AsyncProcessor implements Runnable {
// Modifications to invoke as a single put
private final List<Modification> mods = new ArrayList<Modification>(config.getBatchSize());
- public void run()
- {
- while (!Thread.interrupted())
- {
- try
- {
+ public void run() {
+ while (!Thread.interrupted()) {
+ try {
run0();
}
- catch (InterruptedException e)
- {
+ catch (InterruptedException e) {
break;
}
}
- try
- {
+ try {
if (trace) log.trace("process remaining batch " + mods.size());
put(mods);
if (trace) log.trace("process remaining queued " + queue.size());
- while (!queue.isEmpty())
- {
+ while (!queue.isEmpty()) {
run0();
}
}
- catch (InterruptedException e)
- {
+ catch (InterruptedException e) {
log.trace("remaining interrupted");
}
}
- private void run0() throws InterruptedException
- {
+ private void run0() throws InterruptedException {
log.trace("Checking for modifications");
int i = queue.drainTo(mods, config.getBatchSize());
- if (i == 0)
- {
+ if (i == 0) {
Modification m = queue.take();
mods.add(m);
}
- if (trace)
- {
+ if (trace) {
log.trace("Calling put(List) with " + mods.size() + " modifications");
}
put(mods);
mods.clear();
}
- private void put(List<Modification> mods)
- {
- try
- {
+ private void put(List<Modification> mods) {
+ try {
AsyncCacheLoader.super.put(mods);
}
- catch (Exception e)
- {
+ catch (Exception e) {
if (log.isWarnEnabled()) log.warn("Failed to process async modifications: " + e);
if (log.isDebugEnabled()) log.debug("Exception: ", e);
}
@@ -315,8 +254,7 @@
}
@Override
- public String toString()
- {
+ public String toString() {
return super.toString() +
" delegate=[" + super.getCacheLoader() + "]" +
" stopped=" + stopped +
Modified: core/branches/flat/src/main/java/org/horizon/loader/AsyncCacheLoaderConfig.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/loader/AsyncCacheLoaderConfig.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/loader/AsyncCacheLoaderConfig.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -25,8 +25,7 @@
import java.util.Properties;
-public class AsyncCacheLoaderConfig extends IndividualCacheLoaderConfig
-{
+public class AsyncCacheLoaderConfig extends IndividualCacheLoaderConfig {
/**
* The serialVersionUID
*/
@@ -41,8 +40,7 @@
/**
* Default constructor.
*/
- public AsyncCacheLoaderConfig()
- {
+ public AsyncCacheLoaderConfig() {
setClassName(AsyncCacheLoader.class.getName());
}
@@ -51,70 +49,58 @@
*
* @param base generic config object created by XML parsing.
*/
- AsyncCacheLoaderConfig(IndividualCacheLoaderConfig base)
- {
+ AsyncCacheLoaderConfig(IndividualCacheLoaderConfig base) {
setClassName(AsyncCacheLoader.class.getName());
populateFromBaseConfig(base);
}
- public int getThreadPoolSize()
- {
+ public int getThreadPoolSize() {
return threadPoolSize;
}
- public void setThreadPoolSize(int threadPoolSize)
- {
+ public void setThreadPoolSize(int threadPoolSize) {
testImmutability("threadPoolSize");
this.threadPoolSize = threadPoolSize;
}
- public int getBatchSize()
- {
+ public int getBatchSize() {
return batchSize;
}
- public void setBatchSize(int batchSize)
- {
+ public void setBatchSize(int batchSize) {
testImmutability("batchSize");
this.batchSize = batchSize;
}
- public int getQueueSize()
- {
+ public int getQueueSize() {
return queueSize;
}
- public void setQueueSize(int queueSize)
- {
+ public void setQueueSize(int queueSize) {
testImmutability("queueSize");
this.queueSize = queueSize;
}
- public boolean getReturnOld()
- {
+ public boolean getReturnOld() {
return returnOld;
}
- public void setReturnOld(boolean returnOld)
- {
+ public void setReturnOld(boolean returnOld) {
testImmutability("returnOld");
this.returnOld = returnOld;
}
- public boolean getUseAsyncPut()
- {
+ public boolean getUseAsyncPut() {
return useAsyncPut;
}
- public void setUseAsyncPut(boolean useAsyncPut)
- {
+ public void setUseAsyncPut(boolean useAsyncPut) {
testImmutability("useAsyncPut");
this.useAsyncPut = useAsyncPut;
}
@Override
- public void setProperties(Properties props)
- {
+ public void setProperties(Properties props) {
super.setProperties(props);
String s;
@@ -140,10 +126,8 @@
}
@Override
- public boolean equals(Object obj)
- {
- if (obj instanceof AsyncCacheLoaderConfig && equalsExcludingProperties(obj))
- {
+ public boolean equals(Object obj) {
+ if (obj instanceof AsyncCacheLoaderConfig && equalsExcludingProperties(obj)) {
AsyncCacheLoaderConfig other = (AsyncCacheLoaderConfig) obj;
return (batchSize == other.batchSize)
&& (queueSize == other.queueSize)
@@ -154,8 +138,7 @@
}
@Override
- public int hashCode()
- {
+ public int hashCode() {
int result = hashCodeExcludingProperties();
result = 31 * result + batchSize;
result = 31 * result + queueSize;
@@ -165,8 +148,7 @@
}
@Override
- public AsyncCacheLoaderConfig clone() throws CloneNotSupportedException
- {
+ public AsyncCacheLoaderConfig clone() throws CloneNotSupportedException {
return (AsyncCacheLoaderConfig) super.clone();
}
Modified: core/branches/flat/src/main/java/org/horizon/loader/CacheLoader.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/loader/CacheLoader.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/loader/CacheLoader.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -34,21 +34,18 @@
import java.util.Map;
/**
- * A {@link CacheLoader} implementation persists and load keys to and from
- * secondary storage, such as a database or filesystem. Typically,
- * implementations store a series of keys and values (an entire {@link Map})
- * under a single {@link Fqn}. Loading and saving properties of an entire
- * {@link Map} should be atomic.
+ * A {@link CacheLoader} implementation persists and load keys to and from secondary storage, such as a database or
+ * filesystem. Typically, implementations store a series of keys and values (an entire {@link Map}) under a single
+ * {@link Fqn}. Loading and saving properties of an entire {@link Map} should be atomic.
* <p/>
- * Lifecycle: First an instance of the loader is created, then the
- * configuration ({@link #setConfig(CacheLoaderConfig.IndividualCacheLoaderConfig)}) and cache ({@link
- * #setCache(CacheSPI)}) are set. After this, {@link #create()} is called.
- * Then {@link #start()} is called. When re-deployed, {@link #stop()} will be
- * called, followed by another {@link #start()}. Finally, when shut down,
- * {@link #destroy()} is called, after which the loader is unusable.
+ * Lifecycle: First an instance of the loader is created, then the configuration ({@link
+ * #setConfig(CacheLoaderConfig.IndividualCacheLoaderConfig)}) and cache ({@link #setCache(CacheSPI)}) are set. After
+ * this, {@link #create()} is called. Then {@link #start()} is called. When re-deployed, {@link #stop()} will be called,
+ * followed by another {@link #start()}. Finally, when shut down, {@link #destroy()} is called, after which the loader
+ * is unusable.
* <p/>
- * An {@link AbstractCacheLoader} is provided as a convenient starting place
- * when implementing your own {@link CacheLoader}.
+ * An {@link AbstractCacheLoader} is provided as a convenient starting place when implementing your own {@link
+ * CacheLoader}.
* <p/>
* It is important to note that all implementations are thread safe, as concurrent reads and writes, potentially even to
* the same {@link Fqn}, are possible.
@@ -59,17 +56,14 @@
*/
@ThreadSafe
@Scope(Scopes.NAMED_CACHE)
-public interface CacheLoader<K, V>
-{
+public interface CacheLoader<K, V> {
/**
* Sets the configuration. This is called before {@link #create()} and {@link #start()}.
*
- * @param config May be an instance of the {@link CacheLoaderConfig.IndividualCacheLoaderConfig} base
- * class, in which case the cache loader should use the
- * {@link CacheLoaderConfig.IndividualCacheLoaderConfig#getProperties()}
- * method to find configuration information. Alternatively,
- * may be a type-specific subclass of {@link CacheLoaderConfig.IndividualCacheLoaderConfig},
- * if there is one.
+ * @param config May be an instance of the {@link CacheLoaderConfig.IndividualCacheLoaderConfig} base class, in which
+ * case the cache loader should use the {@link CacheLoaderConfig.IndividualCacheLoaderConfig#getProperties()}
+ * method to find configuration information. Alternatively, may be a type-specific subclass of {@link
+ * CacheLoaderConfig.IndividualCacheLoaderConfig}, if there is one.
*/
void setConfig(IndividualCacheLoaderConfig config);
@@ -81,9 +75,9 @@
IndividualCacheLoaderConfig getConfig();
/**
- * Sets the {@link CacheSPI} that is maintaining this CacheLoader.
- * This method allows this CacheLoader to set a reference to the {@link CacheSPI}.
- * This method is called be called after the CacheLoader instance has been constructed.
+ * Sets the {@link CacheSPI} that is maintaining this CacheLoader. This method allows this CacheLoader to set a
+ * reference to the {@link CacheSPI}. This method is called be called after the CacheLoader instance has been
+ * constructed.
*
* @param c The cache on which this loader works
*/
@@ -93,9 +87,8 @@
* Returns all keys and values from the persistent store, given a {@link Fqn}
*
* @param name the {@link Fqn} to search for.
- * @return Map<Object,Object> keys and values for the given node. Returns
- * null if the node is not found. If the node is found but has no
- * attributes, this method returns an empty Map.
+ * @return Map<Object,Object> keys and values for the given node. Returns null if the node is not found. If the node
+ * is found but has no attributes, this method returns an empty Map.
*/
V get(Object key);
@@ -108,9 +101,8 @@
boolean exists(Object key);
/**
- * Puts a key and value into the attribute map of a given node. If the
- * node does not exist, all parent nodes from the root down are created
- * automatically. Returns the old value.
+ * Puts a key and value into the attribute map of a given node. If the node does not exist, all parent nodes from
+ * the root down are created automatically. Returns the old value.
*/
V put(K key, V value);
@@ -136,25 +128,23 @@
/**
- * Applies all modifications to the backend store.
- * Changes may be applied in a single operation.
+ * Applies all modifications to the backend store. Changes may be applied in a single operation.
*
* @param modifications A List<Modification> of modifications
*/
void put(List<Modification> modifications);
/**
- * Prepares a list of modifications. For example, for a DB-based CacheLoader:
- * <ol>
- * <li>Create a local (JDBC) transaction
- * <li>Associate the local transaction with <code>tx</code> (tx is the key)
- * <li>Execute the corresponding SQL statements against the DB (statements derived from modifications)
- * </ol>
- * For non-transactional CacheLoader (e.g. file-based), the implementation could attempt to implement its own transactional
- * logic, attempting to write data to a temp location (or memory) and writing it to the proper location upon commit.
+ * Prepares a list of modifications. For example, for a DB-based CacheLoader: <ol> <li>Create a local (JDBC)
+ * transaction <li>Associate the local transaction with <code>tx</code> (tx is the key) <li>Execute the corresponding
+ * SQL statements against the DB (statements derived from modifications) </ol> For non-transactional CacheLoader
+ * (e.g. file-based), the implementation could attempt to implement its own transactional logic, attempting to write
+ * data to a temp location (or memory) and writing it to the proper location upon commit.
*
- * @param tx The transaction, indended to be used by implementations as an identifier of the transaction (and not necessarily a JTA {@link javax.transaction.Transaction} object)
- * @param modifications A {@link List} containing {@link org.horizon.loader.Modification}s, for the given transaction
+ * @param tx The transaction, indended to be used by implementations as an identifier of the transaction
+ * (and not necessarily a JTA {@link javax.transaction.Transaction} object)
+ * @param modifications A {@link List} containing {@link org.horizon.loader.Modification}s, for the given
+ * transaction
* @param one_phase Persist immediately and (for example) commit the local JDBC transaction as well. When true,
* we won't get a {@link #commit(Object)} or {@link #rollback(Object)} method call later
* @throws Exception
@@ -162,11 +152,9 @@
void prepare(Object tx, List<Modification> modifications, boolean one_phase);
/**
- * Commits the transaction. A DB-based CacheLoader would look up the local
- * JDBC transaction asociated with <code>tx</code> and commit that
- * transaction. Non-transactional CacheLoaders could simply write the data
- * that was previously saved transiently under the given <code>tx</code>
- * key, to (for example) a file system.
+ * Commits the transaction. A DB-based CacheLoader would look up the local JDBC transaction asociated with
+ * <code>tx</code> and commit that transaction. Non-transactional CacheLoaders could simply write the data that was
+ * previously saved transiently under the given <code>tx</code> key, to (for example) a file system.
* <p/>
* <b>Note</b> this only holds if the previous prepare() did not define <pre>one_phase=true</pre>
*
@@ -175,29 +163,26 @@
void commit(Object tx);
/**
- * Rolls the transaction back. A DB-based CacheLoader would look up the
- * local JDBC transaction asociated with <code>tx</code> and roll back that
- * transaction.
+ * Rolls the transaction back. A DB-based CacheLoader would look up the local JDBC transaction asociated with
+ * <code>tx</code> and roll back that transaction.
*
* @param tx transaction to roll back
*/
void rollback(Object tx);
/**
- * Fetches the entire state for this cache from secondary storage (disk, database)
- * and writes it to a provided ObjectOutputStream. State written to the provided
- * ObjectOutputStream parameter is used for initialization of a new CacheImpl instance.
- * When the state gets transferred to the new cache instance its cacheloader calls
- * {@link #storeEntireState(ObjectInputStream)}
+ * Fetches the entire state for this cache from secondary storage (disk, database) and writes it to a provided
+ * ObjectOutputStream. State written to the provided ObjectOutputStream parameter is used for initialization of a new
+ * CacheImpl instance. When the state gets transferred to the new cache instance its cacheloader calls {@link
+ * #storeEntireState(ObjectInputStream)}
* <p/>
- * Implementations of this method should not catch any exception or close the
- * given ObjectOutputStream parameter. In order to ensure cacheloader interoperability
- * contents of the cache are written to the ObjectOutputStream as a sequence of
- * NodeData objects.
+ * Implementations of this method should not catch any exception or close the given ObjectOutputStream parameter. In
+ * order to ensure cacheloader interoperability contents of the cache are written to the ObjectOutputStream as a
+ * sequence of NodeData objects.
* <p/>
- * Default implementation is provided by {@link AbstractCacheLoader} and ensures cacheloader
- * interoperability. Implementors are encouraged to consider extending AbstractCacheLoader
- * prior to implementing completely custom cacheloader.
+ * Default implementation is provided by {@link AbstractCacheLoader} and ensures cacheloader interoperability.
+ * Implementors are encouraged to consider extending AbstractCacheLoader prior to implementing completely custom
+ * cacheloader.
*
* @param os ObjectOutputStream to write state
* @see AbstractCacheLoader#loadEntireState(ObjectOutputStream)
@@ -206,18 +191,17 @@
void loadEntireState(ObjectOutputStream os);
/**
- * Stores the entire state for this cache by reading it from a provided ObjectInputStream.
- * The state was provided to this cache by calling {@link #loadEntireState(ObjectOutputStream)}}
- * on some other cache instance. State currently in storage gets overwritten.
+ * Stores the entire state for this cache by reading it from a provided ObjectInputStream. The state was provided to
+ * this cache by calling {@link #loadEntireState(ObjectOutputStream)}} on some other cache instance. State currently
+ * in storage gets overwritten.
* <p/>
- * Implementations of this method should not catch any exception or close the
- * given ObjectInputStream parameter. In order to ensure cacheloader interoperability
- * contents of the cache are read from the ObjectInputStream as a sequence of
- * NodeData objects.
+ * Implementations of this method should not catch any exception or close the given ObjectInputStream parameter. In
+ * order to ensure cacheloader interoperability contents of the cache are read from the ObjectInputStream as a
+ * sequence of NodeData objects.
* <p/>
- * Default implementation is provided by {@link AbstractCacheLoader} and ensures cacheloader
- * interoperability. Implementors are encouraged to consider extending AbstractCacheLoader
- * prior to implementing completely custom cacheloader.
+ * Default implementation is provided by {@link AbstractCacheLoader} and ensures cacheloader interoperability.
+ * Implementors are encouraged to consider extending AbstractCacheLoader prior to implementing completely custom
+ * cacheloader.
*
* @param is ObjectInputStream to read state
* @see AbstractCacheLoader#storeEntireState(ObjectInputStream)
Modified: core/branches/flat/src/main/java/org/horizon/loader/CacheLoaderManager.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/loader/CacheLoaderManager.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/loader/CacheLoaderManager.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -21,36 +21,33 @@
*/
package org.horizon.loader;
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.StringTokenizer;
-
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.horizon.CacheException;
import org.horizon.CacheSPI;
import org.horizon.config.CacheLoaderConfig;
-import org.horizon.config.Configuration;
-import org.horizon.config.ConfigurationException;
import org.horizon.config.CacheLoaderConfig.IndividualCacheLoaderConfig;
import org.horizon.config.CacheLoaderConfig.IndividualCacheLoaderConfig.SingletonStoreConfig;
+import org.horizon.config.Configuration;
+import org.horizon.config.ConfigurationException;
import org.horizon.factories.ComponentRegistry;
import org.horizon.factories.annotations.Inject;
import org.horizon.factories.annotations.Start;
import org.horizon.factories.annotations.Stop;
import org.horizon.util.ReflectionUtil;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.StringTokenizer;
+
/**
- * Manages all cache loader functionality. This class is typically initialised with an XML DOM Element,
- * represeting a cache loader configuration, or a {@link CacheLoaderConfig} object.
+ * Manages all cache loader functionality. This class is typically initialised with an XML DOM Element, represeting a
+ * cache loader configuration, or a {@link CacheLoaderConfig} object.
* <p/>
* Usage:
* <p/>
- * <code>
- * CacheLoaderManager manager = new CacheLoaderManager();
- * manager.setConfig(myXmlSnippet, myTreeCache);
- * CacheLoader loader = manager.getCacheLoader();
- * </code>
+ * <code> CacheLoaderManager manager = new CacheLoaderManager(); manager.setConfig(myXmlSnippet, myTreeCache);
+ * CacheLoader loader = manager.getCacheLoader(); </code>
* <p/>
* See the User Guide or sample configuration files for the equivalent XML configuration elements.
*
@@ -58,33 +55,28 @@
* @author <a href="mailto:galder.zamarreno at jboss.com">Galder Zamarreno</a>
* @since 1.0
*/
-public class CacheLoaderManager
-{
+public class CacheLoaderManager {
private static final Log log = LogFactory.getLog(CacheLoaderManager.class);
private CacheLoaderConfig config;
- private CacheSPI<Object,Object> cache;
- private CacheLoader<Object,Object> loader;
+ private CacheSPI<Object, Object> cache;
+ private CacheLoader<Object, Object> loader;
private boolean fetchPersistentState;
private Configuration configuration;
private ComponentRegistry registry;
@Inject
- public void injectDependencies(CacheSPI<Object, Object> cache, Configuration configuration, ComponentRegistry registry)
- {
+ public void injectDependencies(CacheSPI<Object, Object> cache, Configuration configuration, ComponentRegistry registry) {
// TODO: Inject CacheSPI once we have the cache loaders not relying on a tree structure
this.config = configuration.getCacheLoaderConfig();
this.cache = cache;
this.configuration = configuration;
this.registry = registry;
- if (config != null)
- {
- try
- {
+ if (config != null) {
+ try {
loader = createCacheLoader();
}
- catch (Exception e)
- {
+ catch (Exception e) {
throw new CacheException("Unable to create cache loaders", e);
}
}
@@ -97,20 +89,16 @@
* @param cache
* @throws CacheException
*/
- public void setConfig(CacheLoaderConfig config, CacheSPI<Object,Object> cache, Configuration configuration) throws CacheException
- {
+ public void setConfig(CacheLoaderConfig config, CacheSPI<Object, Object> cache, Configuration configuration) throws CacheException {
this.config = config == null ? configuration.getCacheLoaderConfig() : config;
this.cache = cache;
this.configuration = configuration;
- if (config != null)
- {
- try
- {
+ if (config != null) {
+ try {
loader = createCacheLoader();
}
- catch (Exception e)
- {
+ catch (Exception e) {
throw new CacheException("Unable to create cache loaders", e);
}
}
@@ -124,9 +112,8 @@
* @throws InstantiationException
* @throws ClassNotFoundException
*/
- private CacheLoader<Object, Object> createCacheLoader() throws Exception
- {
- CacheLoader<Object,Object> tmpLoader;
+ private CacheLoader<Object, Object> createCacheLoader() throws Exception {
+ CacheLoader<Object, Object> tmpLoader;
// if we only have a single cache loader configured in the chaining cacheloader then
// don't use a chaining cache loader at all.
@@ -134,31 +121,27 @@
new ArrayList<IndividualCacheLoaderConfig>();
// also if we are using passivation then just directly use the first cache loader.
- if (config.useChainingCacheLoader())
- {
+ if (config.useChainingCacheLoader()) {
// create chaining cache loader.
- ChainingCacheLoader<Object,Object> ccl = new ChainingCacheLoader<Object,Object>();
+ ChainingCacheLoader<Object, Object> ccl = new ChainingCacheLoader<Object, Object>();
tmpLoader = ccl;
Iterator<IndividualCacheLoaderConfig> it = config.getIndividualCacheLoaderConfigs().iterator();
// only one cache loader may have fetchPersistentState to true.
int numLoadersWithFetchPersistentState = 0;
- while (it.hasNext())
- {
+ while (it.hasNext()) {
CacheLoaderConfig.IndividualCacheLoaderConfig cfg = (CacheLoaderConfig.IndividualCacheLoaderConfig) it.next();
- if (cfg.isFetchPersistentState())
- {
+ if (cfg.isFetchPersistentState()) {
numLoadersWithFetchPersistentState++;
fetchPersistentState = true;
}
- if (numLoadersWithFetchPersistentState > 1)
- {
+ if (numLoadersWithFetchPersistentState > 1) {
throw new Exception("Invalid cache loader configuration!! Only ONE cache loader may have fetchPersistentState set to true. Cache will not start!");
}
assertNotSingletonAndShared(cfg);
- CacheLoader<Object,Object> l = createCacheLoader(cfg, cache);
+ CacheLoader<Object, Object> l = createCacheLoader(cfg, cache);
cfg = l.getConfig();
finalConfigs.add(cfg);
// Only loaders that deal w/ state transfer factor into
@@ -166,9 +149,7 @@
ccl.addCacheLoader(l, cfg);
}
- }
- else
- {
+ } else {
CacheLoaderConfig.IndividualCacheLoaderConfig cfg = config.getIndividualCacheLoaderConfigs().get(0);
tmpLoader = createCacheLoader(cfg, cache);
finalConfigs.add(tmpLoader.getConfig() == null ? cfg : tmpLoader.getConfig());
@@ -183,8 +164,7 @@
return tmpLoader;
}
- private void assertNotSingletonAndShared(IndividualCacheLoaderConfig cfg)
- {
+ private void assertNotSingletonAndShared(IndividualCacheLoaderConfig cfg) {
SingletonStoreConfig ssc = cfg.getSingletonStoreConfig();
if (ssc != null && ssc.isSingletonStoreEnabled() && config.isShared())
throw new ConfigurationException("Invalid cache loader configuration!! If a cache loader is configured as a singleton, the cache loader cannot be shared in a cluster!");
@@ -199,23 +179,19 @@
* @throws Exception
*/
@SuppressWarnings("deprecation")
- private CacheLoader<Object, Object> createCacheLoader(CacheLoaderConfig.IndividualCacheLoaderConfig cfg, CacheSPI<Object, Object> cache) throws Exception
- {
+ private CacheLoader<Object, Object> createCacheLoader(CacheLoaderConfig.IndividualCacheLoaderConfig cfg, CacheSPI<Object, Object> cache) throws Exception {
// create loader
CacheLoader<Object, Object> tmpLoader = cfg.getCacheLoader() == null ? createInstance(cfg.getClassName()) : cfg.getCacheLoader();
- if (tmpLoader != null)
- {
+ if (tmpLoader != null) {
// async?
- if (cfg.isAsync())
- {
+ if (cfg.isAsync()) {
CacheLoader<Object, Object> asyncDecorator;
asyncDecorator = new AsyncCacheLoader<Object, Object>(tmpLoader);
tmpLoader = asyncDecorator;
}
- if (cfg.isIgnoreModifications())
- {
+ if (cfg.isIgnoreModifications()) {
AbstractDelegatingCacheLoader<Object, Object> readOnlyDecorator;
readOnlyDecorator = new ReadOnlyDelegatingCacheLoader<Object, Object>(tmpLoader);
tmpLoader = readOnlyDecorator;
@@ -223,23 +199,19 @@
// singleton?
SingletonStoreConfig ssc = cfg.getSingletonStoreConfig();
- if (ssc != null && ssc.isSingletonStoreEnabled())
- {
+ if (ssc != null && ssc.isSingletonStoreEnabled()) {
Object decorator = createInstance(ssc.getSingletonStoreClass());
/* class providing singleton store functionality must extend AbstractDelegatingCacheLoader so that
* underlying cacheloader can be set. */
- if (decorator instanceof AbstractDelegatingCacheLoader)
- {
+ if (decorator instanceof AbstractDelegatingCacheLoader) {
@SuppressWarnings("unchecked")
AbstractDelegatingCacheLoader<Object, Object> singletonDecorator = (AbstractDelegatingCacheLoader<Object, Object>) decorator;
/* set the cache loader to where calls will be delegated by the class providing the singleton
* store functionality. */
singletonDecorator.setCacheLoader(tmpLoader);
tmpLoader = singletonDecorator;
- }
- else
- {
+ } else {
throw new Exception("Invalid cache loader configuration!! Singleton store implementation class must extend org.horizon.loader.AbstractDelegatingCacheLoader");
}
}
@@ -257,20 +229,18 @@
}
/**
- * Sets the cache instance associated with the given cache loader. This method was created for testing purpouses
- * so that it can be overriden in the mock version of the CacheLoaderManager.
+ * Sets the cache instance associated with the given cache loader. This method was created for testing purpouses so
+ * that it can be overriden in the mock version of the CacheLoaderManager.
*
* @param c instance of cache to be set in cache loader
* @param loader cache loader to which assign the cache instance
*/
- protected void setCacheInLoader(CacheSPI<Object,Object> c, CacheLoader<Object,Object> loader)
- {
+ protected void setCacheInLoader(CacheSPI<Object, Object> c, CacheLoader<Object, Object> loader) {
loader.setCache(c);
}
@SuppressWarnings("unchecked")
- private CacheLoader<Object, Object> createInstance(String className) throws ClassNotFoundException, IllegalAccessException, InstantiationException
- {
+ private CacheLoader<Object, Object> createInstance(String className) throws ClassNotFoundException, IllegalAccessException, InstantiationException {
if (log.isTraceEnabled()) log.trace("instantiating class " + className);
Class<?> cl = Thread.currentThread().getContextClassLoader().loadClass(className);
return (CacheLoader<Object, Object>) cl.newInstance();
@@ -282,17 +252,14 @@
* @throws Exception
*/
@Start(priority = 50)
- public void preloadCache() throws CacheException
- {
- if (loader != null)
- {
+ public void preloadCache() throws CacheException {
+ if (loader != null) {
if (config.getPreload() == null || config.getPreload().equals("")) return;
if (log.isDebugEnabled()) log.debug("preloading transient state from cache loader " + loader);
StringTokenizer st = new StringTokenizer(config.getPreload(), ",");
long start, stop, total;
start = System.currentTimeMillis();
- while (st.hasMoreTokens())
- {
+ while (st.hasMoreTokens()) {
String tok = st.nextToken().trim();
if (log.isTraceEnabled()) log.trace("preloading " + tok);
preload(tok);
@@ -300,8 +267,7 @@
stop = System.currentTimeMillis();
total = stop - start;
- if (log.isDebugEnabled())
- {
+ if (log.isDebugEnabled()) {
log.debug("preloading transient state from cache loader was successful (in " + total + " milliseconds)");
}
}
@@ -315,8 +281,7 @@
* @param preloadChildren whether we preload children
* @throws CacheException if we are unable to preload
*/
- public void preload(String key) throws CacheException
- {
+ public void preload(String key) throws CacheException {
cache.getInvocationContext().getOptionOverrides().setSkipCacheStatusCheck(true);
// 1. Load the attributes first
@@ -327,40 +292,34 @@
/**
* Returns the configuration element of the cache loaders
*/
- public CacheLoaderConfig getCacheLoaderConfig()
- {
+ public CacheLoaderConfig getCacheLoaderConfig() {
return config;
}
/**
* Returns the cache loader
*/
- public CacheLoader<Object, Object> getCacheLoader()
- {
+ public CacheLoader<Object, Object> getCacheLoader() {
return loader;
}
/**
* Tests if we're using passivation
*/
- public boolean isPassivation()
- {
+ public boolean isPassivation() {
return config.isPassivation();
}
/**
* Returns true if at least one of the configured cache loaders has set fetchPersistentState to true.
*/
- public boolean isFetchPersistentState()
- {
+ public boolean isFetchPersistentState() {
return fetchPersistentState;
}
@Stop
- public void stopCacheLoader()
- {
- if (loader != null)
- {
+ public void stopCacheLoader() {
+ if (loader != null) {
// stop the cache loader
loader.stop();
// destroy the cache loader
@@ -369,27 +328,21 @@
}
@Start
- public void startCacheLoader() throws CacheException
- {
+ public void startCacheLoader() throws CacheException {
if (config == null) config = configuration.getCacheLoaderConfig();
- if (config != null && loader == null)
- {
- try
- {
+ if (config != null && loader == null) {
+ try {
loader = createCacheLoader();
}
- catch (Exception e)
- {
+ catch (Exception e) {
throw new CacheException("Unable to create cache loaders", e);
}
}
- if (loader != null)
- {
- try
- {
+ if (loader != null) {
+ try {
// wire any deps.
registry.wireDependencies(loader);
@@ -400,8 +353,7 @@
purgeLoaders(false);
}
- catch (Exception e)
- {
+ catch (Exception e) {
throw new CacheException("Unable to start cache loaders", e);
}
fetchPersistentState = fetchPersistentState || (loader.getConfig() != null && loader.getConfig().isFetchPersistentState());
@@ -409,18 +361,13 @@
}
}
- public void purgeLoaders(boolean force) throws Exception
- {
- if ((loader instanceof ChainingCacheLoader) && !force)
- {
- ((ChainingCacheLoader<?,?>) loader).purgeIfNecessary();
- }
- else
- {
+ public void purgeLoaders(boolean force) throws Exception {
+ if ((loader instanceof ChainingCacheLoader) && !force) {
+ ((ChainingCacheLoader<?, ?>) loader).purgeIfNecessary();
+ } else {
CacheLoaderConfig.IndividualCacheLoaderConfig first = getCacheLoaderConfig().getFirstCacheLoaderConfig();
if (force ||
- (first != null && first.isPurgeOnStartup()))
- {
+ (first != null && first.isPurgeOnStartup())) {
loader.clear();
}
}
Modified: core/branches/flat/src/main/java/org/horizon/loader/ChainingCacheLoader.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/loader/ChainingCacheLoader.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/loader/ChainingCacheLoader.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -21,6 +21,12 @@
*/
package org.horizon.loader;
+import org.horizon.config.CacheLoaderConfig;
+import org.horizon.config.CacheLoaderConfig.IndividualCacheLoaderConfig;
+import org.horizon.factories.ComponentRegistry;
+import org.horizon.factories.annotations.Inject;
+import org.horizon.marshall.EntryData;
+
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
@@ -28,27 +34,20 @@
import java.util.Iterator;
import java.util.List;
-import org.horizon.config.CacheLoaderConfig;
-import org.horizon.config.CacheLoaderConfig.IndividualCacheLoaderConfig;
-import org.horizon.factories.ComponentRegistry;
-import org.horizon.factories.annotations.Inject;
-import org.horizon.marshall.EntryData;
-
/**
- * This decorator is used whenever more than one cache loader is configured. READ operations are directed to
- * each of the cache loaders (in the order which they were configured) until a non-null (or non-empty in the case
- * of retrieving collection objects) result is achieved.
+ * This decorator is used whenever more than one cache loader is configured. READ operations are directed to each of
+ * the cache loaders (in the order which they were configured) until a non-null (or non-empty in the case of retrieving
+ * collection objects) result is achieved.
* <p/>
* WRITE operations are propagated to ALL registered cacheloaders that specified set ignoreModifications to false.
*
* @author <a href="mailto:manik at jboss.org">Manik Surtani (manik at jboss.org)</a>
* @since 1.0
*/
-public class ChainingCacheLoader<K,V> extends AbstractCacheLoader<K,V>
-{
+public class ChainingCacheLoader<K, V> extends AbstractCacheLoader<K, V> {
- private final List<CacheLoader<K,V>> cacheLoaders = new ArrayList<CacheLoader<K,V>>(2);
- private final List<CacheLoader<K,V>> writeCacheLoaders = new ArrayList<CacheLoader<K,V>>(2);
+ private final List<CacheLoader<K, V>> cacheLoaders = new ArrayList<CacheLoader<K, V>>(2);
+ private final List<CacheLoader<K, V>> writeCacheLoaders = new ArrayList<CacheLoader<K, V>>(2);
private final List<CacheLoaderConfig.IndividualCacheLoaderConfig> cacheLoaderConfigs = new ArrayList<CacheLoaderConfig.IndividualCacheLoaderConfig>(2);
private ComponentRegistry registry;
@@ -57,28 +56,23 @@
*
* @param config ignored
*/
- public void setConfig(IndividualCacheLoaderConfig config)
- {
+ public void setConfig(IndividualCacheLoaderConfig config) {
// don't do much here?
}
- public IndividualCacheLoaderConfig getConfig()
- {
+ public IndividualCacheLoaderConfig getConfig() {
return null;
}
@Inject
- public void injectDependencies(ComponentRegistry registry)
- {
+ public void injectDependencies(ComponentRegistry registry) {
this.registry = registry;
}
- public V get(Object key)
- {
+ public V get(Object key) {
V answer = null;
- for (CacheLoader<K,V> l : cacheLoaders)
- {
+ for (CacheLoader<K, V> l : cacheLoaders) {
answer = l.get(key);
if (answer != null) break;
}
@@ -91,11 +85,9 @@
* @param name
* @return True if node exists, false otherwise
*/
- public boolean exists(Object key)
- {
+ public boolean exists(Object key) {
boolean answer = false;
- for (CacheLoader<K,V> l : cacheLoaders)
- {
+ for (CacheLoader<K, V> l : cacheLoaders) {
answer = l.exists(key);
if (answer) break;
}
@@ -103,18 +95,15 @@
}
/**
- * Inserts key and value into the attributes hashmap of the given node. If the node does not exist, all
- * parent nodes from the root down are created automatically. Returns the old value
+ * Inserts key and value into the attributes hashmap of the given node. If the node does not exist, all parent nodes
+ * from the root down are created automatically. Returns the old value
*/
- public V put(K key, V value)
- {
+ public V put(K key, V value) {
V answer = null;
boolean isFirst = true;
- for (CacheLoader<K,V> l : writeCacheLoaders)
- {
+ for (CacheLoader<K, V> l : writeCacheLoaders) {
V tAnswer = l.put(key, value);
- if (isFirst)
- {
+ if (isFirst) {
answer = tAnswer;
isFirst = false;
}
@@ -124,34 +113,27 @@
}
/**
- * Inserts all modifications to the backend store. Overwrite whatever is already in
- * the datastore.
+ * Inserts all modifications to the backend store. Overwrite whatever is already in the datastore.
*
* @param modifications A List<Modification> of modifications
* @throws Exception
*/
@Override
- public void put(List<Modification> modifications)
- {
- for (CacheLoader<K,V> l : writeCacheLoaders)
- {
+ public void put(List<Modification> modifications) {
+ for (CacheLoader<K, V> l : writeCacheLoaders) {
l.put(modifications);
}
}
/**
- * Removes the given key and value. No-op if key doesn't exist.
- * Returns the first response from the loader chain.
+ * Removes the given key and value. No-op if key doesn't exist. Returns the first response from the loader chain.
*/
- public V remove(Object key)
- {
+ public V remove(Object key) {
V answer = null;
boolean isFirst = true;
- for (CacheLoader<K,V> l : writeCacheLoaders)
- {
+ for (CacheLoader<K, V> l : writeCacheLoaders) {
V tAnswer = l.remove(key);
- if (isFirst)
- {
+ if (isFirst) {
answer = tAnswer;
isFirst = false;
}
@@ -160,13 +142,10 @@
}
/**
- * Prepare the modifications. For example, for a DB-based CacheLoader:
- * <ol>
- * <li>Create a local (JDBC) transaction
- * <li>Associate the local transaction with <code>tx</code> (tx is the key)
- * <li>Execute the coresponding SQL statements against the DB (statements derived from modifications)
- * </ol>
- * For non-transactional CacheLoader (e.g. file-based), this could be a null operation
+ * Prepare the modifications. For example, for a DB-based CacheLoader: <ol> <li>Create a local (JDBC) transaction
+ * <li>Associate the local transaction with <code>tx</code> (tx is the key) <li>Execute the coresponding SQL
+ * statements against the DB (statements derived from modifications) </ol> For non-transactional CacheLoader (e.g.
+ * file-based), this could be a null operation
*
* @param tx The transaction, just used as a hashmap key
* @param modifications List<Modification>, a list of all modifications within the given transaction
@@ -175,43 +154,36 @@
* @throws Exception
*/
@Override
- public void prepare(Object tx, List<Modification> modifications, boolean one_phase)
- {
- for (CacheLoader<K,V> l : writeCacheLoaders)
- {
+ public void prepare(Object tx, List<Modification> modifications, boolean one_phase) {
+ for (CacheLoader<K, V> l : writeCacheLoaders) {
l.prepare(tx, modifications, one_phase);
}
}
/**
- * Commit the transaction. A DB-based CacheLoader would look up the local JDBC transaction asociated
- * with <code>tx</code> and commit that transaction<br/>
- * Non-transactional CacheLoaders could simply write the data that was previously saved transiently under the
- * given <code>tx</code> key, to (for example) a file system (note this only holds if the previous prepare() did
- * not define one_phase=true
+ * Commit the transaction. A DB-based CacheLoader would look up the local JDBC transaction asociated with
+ * <code>tx</code> and commit that transaction<br/> Non-transactional CacheLoaders could simply write the data that
+ * was previously saved transiently under the given <code>tx</code> key, to (for example) a file system (note this
+ * only holds if the previous prepare() did not define one_phase=true
*
* @param tx
*/
@Override
- public void commit(Object tx)
- {
- for (CacheLoader<K,V> l : writeCacheLoaders)
- {
+ public void commit(Object tx) {
+ for (CacheLoader<K, V> l : writeCacheLoaders) {
l.commit(tx);
}
}
/**
- * Roll the transaction back. A DB-based CacheLoader would look up the local JDBC transaction asociated
- * with <code>tx</code> and roll back that transaction
+ * Roll the transaction back. A DB-based CacheLoader would look up the local JDBC transaction asociated with
+ * <code>tx</code> and roll back that transaction
*
* @param tx
*/
@Override
- public void rollback(Object tx)
- {
- for (CacheLoader<K,V> l : writeCacheLoaders)
- {
+ public void rollback(Object tx) {
+ for (CacheLoader<K, V> l : writeCacheLoaders) {
l.rollback(tx);
}
}
@@ -223,13 +195,11 @@
* @throws Exception
*/
@Override
- public void create()
- {
+ public void create() {
Iterator<CacheLoader<K, V>> it = cacheLoaders.iterator();
Iterator<CacheLoaderConfig.IndividualCacheLoaderConfig> cfgIt = cacheLoaderConfigs.iterator();
- while (it.hasNext() && cfgIt.hasNext())
- {
- CacheLoader<K,V> cl = it.next();
+ while (it.hasNext() && cfgIt.hasNext()) {
+ CacheLoader<K, V> cl = it.next();
CacheLoaderConfig.IndividualCacheLoaderConfig cfg = cfgIt.next();
cl.setConfig(cfg);
registry.wireDependencies(cl);
@@ -238,42 +208,34 @@
}
@Override
- public void start()
- {
- for (CacheLoader<K,V> cacheLoader : cacheLoaders)
- {
+ public void start() {
+ for (CacheLoader<K, V> cacheLoader : cacheLoaders) {
cacheLoader.start();
}
}
@Override
- public void stop()
- {
- for (CacheLoader<K,V> cacheLoader : cacheLoaders)
- {
+ public void stop() {
+ for (CacheLoader<K, V> cacheLoader : cacheLoaders) {
cacheLoader.stop();
}
}
@Override
- public void destroy()
- {
- for (CacheLoader<K,V> cacheLoader : cacheLoaders)
- {
+ public void destroy() {
+ for (CacheLoader<K, V> cacheLoader : cacheLoaders) {
cacheLoader.destroy();
}
}
+
@Override
- public void loadEntireState(ObjectOutputStream os)
- {
+ public void loadEntireState(ObjectOutputStream os) {
Iterator<CacheLoader<K, V>> i = cacheLoaders.iterator();
Iterator<CacheLoaderConfig.IndividualCacheLoaderConfig> cfgs = cacheLoaderConfigs.iterator();
- while (i.hasNext() && cfgs.hasNext())
- {
- CacheLoader<K,V> l = i.next();
+ while (i.hasNext() && cfgs.hasNext()) {
+ CacheLoader<K, V> l = i.next();
CacheLoaderConfig.IndividualCacheLoaderConfig cfg = cfgs.next();
- if (cfg.isFetchPersistentState())
- {
+ if (cfg.isFetchPersistentState()) {
l.loadEntireState(os);
break;
}
@@ -281,16 +243,13 @@
}
@Override
- public void storeEntireState(ObjectInputStream is)
- {
+ public void storeEntireState(ObjectInputStream is) {
Iterator<CacheLoader<K, V>> i = writeCacheLoaders.iterator();
Iterator<CacheLoaderConfig.IndividualCacheLoaderConfig> cfgs = cacheLoaderConfigs.iterator();
- while (i.hasNext())
- {
- CacheLoader<K,V> l = i.next();
+ while (i.hasNext()) {
+ CacheLoader<K, V> l = i.next();
CacheLoaderConfig.IndividualCacheLoaderConfig cfg = cfgs.next();
- if (cfg.isFetchPersistentState())
- {
+ if (cfg.isFetchPersistentState()) {
l.storeEntireState(is);
break;
}
@@ -301,16 +260,14 @@
/**
* Returns the number of cache loaders in the chain.
*/
- public int getSize()
- {
+ public int getSize() {
return cacheLoaders.size();
}
/**
* Returns a List<CacheLoader> of individual cache loaders configured.
*/
- public List<CacheLoader<K,V>> getCacheLoaders()
- {
+ public List<CacheLoader<K, V>> getCacheLoaders() {
return Collections.unmodifiableList(cacheLoaders);
}
@@ -320,30 +277,25 @@
* @param l the cache loader to add
* @param cfg and its configuration
*/
- public void addCacheLoader(CacheLoader<K, V> l, CacheLoaderConfig.IndividualCacheLoaderConfig cfg)
- {
- synchronized (this)
- {
+ public void addCacheLoader(CacheLoader<K, V> l, CacheLoaderConfig.IndividualCacheLoaderConfig cfg) {
+ synchronized (this) {
cacheLoaderConfigs.add(cfg);
cacheLoaders.add(l);
- if (!cfg.isIgnoreModifications())
- {
+ if (!cfg.isIgnoreModifications()) {
writeCacheLoaders.add(l);
}
}
}
@Override
- public String toString()
- {
+ public String toString() {
StringBuilder buf = new StringBuilder("ChainingCacheLoader{");
Iterator<CacheLoader<K, V>> i = cacheLoaders.iterator();
Iterator<CacheLoaderConfig.IndividualCacheLoaderConfig> c = cacheLoaderConfigs.iterator();
int count = 0;
- while (i.hasNext() && c.hasNext())
- {
- CacheLoader<K,V> loader = i.next();
+ while (i.hasNext() && c.hasNext()) {
+ CacheLoader<K, V> loader = i.next();
CacheLoaderConfig.IndividualCacheLoaderConfig cfg = c.next();
buf.append(++count);
@@ -357,31 +309,27 @@
return buf.toString();
}
- public void purgeIfNecessary() throws Exception
- {
+ public void purgeIfNecessary() throws Exception {
Iterator<CacheLoader<K, V>> loaders = cacheLoaders.iterator();
Iterator<CacheLoaderConfig.IndividualCacheLoaderConfig> configs = cacheLoaderConfigs.iterator();
- while (loaders.hasNext() && configs.hasNext())
- {
- CacheLoader<K,V> myLoader = loaders.next();
+ while (loaders.hasNext() && configs.hasNext()) {
+ CacheLoader<K, V> myLoader = loaders.next();
CacheLoaderConfig.IndividualCacheLoaderConfig myConfig = configs.next();
if (!myConfig.isIgnoreModifications() && myConfig.isPurgeOnStartup()) myLoader.clear();
}
}
- public void clear()
- {
- for (CacheLoader<K,V> l : writeCacheLoaders)
+ public void clear() {
+ for (CacheLoader<K, V> l : writeCacheLoaders)
l.clear();
}
- public List<EntryData<K, V>> getAllEntries()
- {
- ArrayList<EntryData<K,V>> full = new ArrayList<EntryData<K,V>>();
+ public List<EntryData<K, V>> getAllEntries() {
+ ArrayList<EntryData<K, V>> full = new ArrayList<EntryData<K, V>>();
- for (CacheLoader<K,V> l : writeCacheLoaders)
+ for (CacheLoader<K, V> l : writeCacheLoaders)
full.addAll(l.getAllEntries());
return full;
Modified: core/branches/flat/src/main/java/org/horizon/loader/ClusteredCacheLoader.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/loader/ClusteredCacheLoader.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/loader/ClusteredCacheLoader.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -43,19 +43,15 @@
import java.util.Set;
/**
- * A cache loader that consults other members in the cluster for values. Does
- * not propagate update methods since replication should take care of this. A
- * <code>timeout</code> property is required, a <code>long</code> that
- * specifies in milliseconds how long to wait for results before returning a
- * null.
+ * A cache loader that consults other members in the cluster for values. Does not propagate update methods since
+ * replication should take care of this. A <code>timeout</code> property is required, a <code>long</code> that
+ * specifies in milliseconds how long to wait for results before returning a null.
*
- * @author <a href="mailto:manik at jboss.org">Manik Surtani (manik at jboss.org)</a>
- * // TODO implement me!!
+ * @author <a href="mailto:manik at jboss.org">Manik Surtani (manik at jboss.org)</a> // TODO implement me!!
* @since 1.0
*/
@ThreadSafe
-public class ClusteredCacheLoader extends AbstractCacheLoader
-{
+public class ClusteredCacheLoader extends AbstractCacheLoader {
private static final Log log = LogFactory.getLog(ClusteredCacheLoader.class);
private static final boolean trace = log.isTraceEnabled();
private StripedLock lock = new StripedLock();
@@ -68,23 +64,19 @@
*
* @return true if the cache is in its STARTED state.
*/
- protected boolean isCacheReady()
- {
+ protected boolean isCacheReady() {
return cache.getCacheStatus() == CacheStatus.STARTED;
}
@Inject
- public void setCommandsFactory(CommandsFactory commandsFactory)
- {
+ public void setCommandsFactory(CommandsFactory commandsFactory) {
this.commandsFactory = commandsFactory;
}
/**
- * Sets the configuration.
- * A property <code>timeout</code> is used as the timeout value.
+ * Sets the configuration. A property <code>timeout</code> is used as the timeout value.
*/
- public void setConfig(IndividualCacheLoaderConfig base)
- {
+ public void setConfig(IndividualCacheLoaderConfig base) {
// if (base instanceof ClusteredCacheLoaderConfig)
// {
// this.config = (ClusteredCacheLoaderConfig) base;
@@ -95,43 +87,35 @@
// }
}
- public IndividualCacheLoaderConfig getConfig()
- {
+ public IndividualCacheLoaderConfig getConfig() {
return config;
}
- public Object get(Object key)
- {
+ public Object get(Object key) {
return null; // TODO: Manik: Customise this generated block
}
- public boolean exists(Object key)
- {
+ public boolean exists(Object key) {
return false; // TODO: Manik: Customise this generated block
}
- public Object put(Object key, Object value)
- {
+ public Object put(Object key, Object value) {
return null; // TODO: Manik: Customise this generated block
}
- public void clear()
- {
+ public void clear() {
// TODO: Manik: Customise this generated block
}
- public Object remove(Object key)
- {
+ public Object remove(Object key) {
return null; // TODO: Manik: Customise this generated block
}
- public List getAllEntries()
- {
+ public List getAllEntries() {
return null; // TODO: Manik: Customise this generated block
}
- public Set getChildrenNames(Fqn fqn) throws Exception
- {
+ public Set getChildrenNames(Fqn fqn) throws Exception {
if (!isCacheReady() || !cache.getInvocationContext().isOriginLocal()) return Collections.emptySet();
lock.acquireLock(fqn, true);
// try
@@ -148,8 +132,7 @@
}
@SuppressWarnings("deprecation")
- private Object callRemote(DataCommand dataCommand) throws Exception
- {
+ private Object callRemote(DataCommand dataCommand) throws Exception {
if (trace) log.trace("cache=" + cache.getLocalAddress() + "; calling with " + dataCommand);
// ClusteredGetCommand clusteredGet = commandsFactory.buildClusteredGetCommand(false, dataCommand);
List resps;
@@ -200,13 +183,11 @@
throw new RuntimeException("Implement me");
}
- public Map get(Fqn name) throws Exception
- {
+ public Map get(Fqn name) throws Exception {
return get0(name);
}
- protected Map get0(Fqn name) throws Exception
- {
+ protected Map get0(Fqn name) throws Exception {
// DON'T make a remote call if this is a remote call in the first place - leads to deadlocks - JBCACHE-1103
if (!isCacheReady() || !cache.getInvocationContext().isOriginLocal()) return Collections.emptyMap();
lock.acquireLock(name, true);
@@ -223,8 +204,7 @@
throw new RuntimeException("Implement me");
}
- public boolean exists(Fqn name) throws Exception
- {
+ public boolean exists(Fqn name) throws Exception {
// DON'T make a remote call if this is a remote call in the first place - leads to deadlocks - JBCACHE-1103
if (!isCacheReady() || !cache.getInvocationContext().isOriginLocal()) return false;
@@ -242,13 +222,11 @@
throw new RuntimeException("Implement me");
}
- public Object put(Fqn name, Object key, Object value) throws Exception
- {
+ public Object put(Fqn name, Object key, Object value) throws Exception {
// DON'T make a remote call if this is a remote call in the first place - leads to deadlocks - JBCACHE-1103
if (!isCacheReady() || !cache.getInvocationContext().isOriginLocal()) return null;
lock.acquireLock(name, true);
- try
- {
+ try {
// NodeSPI n = cache.peek(name, false);
// if (n == null)
// {
@@ -261,8 +239,7 @@
// return n.getDirect(key);
// }
}
- finally
- {
+ finally {
lock.releaseLock(name);
}
throw new RuntimeException("Implement me");
@@ -271,8 +248,7 @@
/**
* Does nothing; replication handles put.
*/
- public void put(Fqn name, Map attributes) throws Exception
- {
+ public void put(Fqn name, Map attributes) throws Exception {
}
/**
@@ -284,16 +260,13 @@
// }
/**
- * Fetches the remove value, does not remove. Replication handles
- * removal.
+ * Fetches the remove value, does not remove. Replication handles removal.
*/
- public Object remove(Fqn name, Object key) throws Exception
- {
+ public Object remove(Fqn name, Object key) throws Exception {
// DON'T make a remote call if this is a remote call in the first place - leads to deadlocks - JBCACHE-1103
if (!isCacheReady() || !cache.getInvocationContext().isOriginLocal()) return false;
lock.acquireLock(name, true);
- try
- {
+ try {
// NodeSPI n = cache.peek(name, true);
// if (n == null)
// {
@@ -306,8 +279,7 @@
// return n.getDirect(key);
// }
}
- finally
- {
+ finally {
lock.releaseLock(name);
}
throw new RuntimeException("Implement me");
@@ -316,16 +288,14 @@
/**
* Does nothing; replication handles removal.
*/
- public void remove(Fqn name) throws Exception
- {
+ public void remove(Fqn name) throws Exception {
// do nothing
}
/**
* Does nothing; replication handles removal.
*/
- public void removeData(Fqn name) throws Exception
- {
+ public void removeData(Fqn name) throws Exception {
}
/**
@@ -348,8 +318,7 @@
* Does nothing.
*/
@Override
- public void rollback(Object tx)
- {
+ public void rollback(Object tx) {
}
// @Override
@@ -358,9 +327,9 @@
// //intentional no-op
// }
-// @Override
- public void loadState(Fqn subtree, ObjectOutputStream os) throws Exception
- {
+ // @Override
+
+ public void loadState(Fqn subtree, ObjectOutputStream os) throws Exception {
// intentional no-op
}
@@ -370,30 +339,26 @@
// // intentional no-op
// }
-// @Override
- public void storeState(Fqn subtree, ObjectInputStream is) throws Exception
- {
+ // @Override
+
+ public void storeState(Fqn subtree, ObjectInputStream is) throws Exception {
// intentional no-op
}
- public static class ResponseValidityFilter implements RspFilter
- {
+ public static class ResponseValidityFilter implements RspFilter {
private int numValidResponses = 0;
private List<Address> pendingResponders;
- public ResponseValidityFilter(List<Address> expected, Address localAddress)
- {
+ public ResponseValidityFilter(List<Address> expected, Address localAddress) {
this.pendingResponders = new ArrayList<Address>(expected);
// We'll never get a response from ourself
this.pendingResponders.remove(localAddress);
}
- public boolean isAcceptable(Object object, Address address)
- {
+ public boolean isAcceptable(Object object, Address address) {
pendingResponders.remove(address);
- if (object instanceof List)
- {
+ if (object instanceof List) {
List response = (List) object;
Boolean foundResult = (Boolean) response.get(0);
if (foundResult) numValidResponses++;
@@ -402,8 +367,7 @@
return true;
}
- public boolean needMoreResponses()
- {
+ public boolean needMoreResponses() {
return numValidResponses < 1 && pendingResponders.size() > 0;
}
Modified: core/branches/flat/src/main/java/org/horizon/loader/ClusteredCacheLoaderConfig.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/loader/ClusteredCacheLoaderConfig.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/loader/ClusteredCacheLoaderConfig.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -27,8 +27,7 @@
import java.util.Properties;
-public class ClusteredCacheLoaderConfig extends IndividualCacheLoaderConfig
-{
+public class ClusteredCacheLoaderConfig extends IndividualCacheLoaderConfig {
/**
* The serialVersionUID
*/
@@ -37,8 +36,7 @@
@Dynamic
private long timeout = 10000;
- public ClusteredCacheLoaderConfig()
- {
+ public ClusteredCacheLoaderConfig() {
setClassName(ClusteredCacheLoader.class.getName());
}
@@ -47,42 +45,34 @@
*
* @param base generic config object created by XML parsing.
*/
- ClusteredCacheLoaderConfig(IndividualCacheLoaderConfig base)
- {
+ ClusteredCacheLoaderConfig(IndividualCacheLoaderConfig base) {
setClassName(ClusteredCacheLoader.class.getName());
populateFromBaseConfig(base);
}
- public long getTimeout()
- {
+ public long getTimeout() {
return timeout;
}
- public void setTimeout(long timeout)
- {
+ public void setTimeout(long timeout) {
testImmutability("timeout");
this.timeout = timeout;
}
@Override
- public void setProperties(Properties props)
- {
+ public void setProperties(Properties props) {
super.setProperties(props);
- try
- {
+ try {
timeout = Long.valueOf(props.getProperty("timeout"));
}
- catch (Exception e)
- {
+ catch (Exception e) {
log.info("Using default value for config property 'timeout' - " + timeout);
}
}
@Override
- public boolean equals(Object obj)
- {
- if (obj instanceof ClusteredCacheLoaderConfig && equalsExcludingProperties(obj))
- {
+ public boolean equals(Object obj) {
+ if (obj instanceof ClusteredCacheLoaderConfig && equalsExcludingProperties(obj)) {
ClusteredCacheLoaderConfig other = (ClusteredCacheLoaderConfig) obj;
return (this.timeout == other.timeout);
}
@@ -90,14 +80,12 @@
}
@Override
- public int hashCode()
- {
+ public int hashCode() {
return 31 * hashCodeExcludingProperties() + (int) timeout;
}
@Override
- public ClusteredCacheLoaderConfig clone() throws CloneNotSupportedException
- {
+ public ClusteredCacheLoaderConfig clone() throws CloneNotSupportedException {
return (ClusteredCacheLoaderConfig) super.clone();
}
Modified: core/branches/flat/src/main/java/org/horizon/loader/FileCacheLoader.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/loader/FileCacheLoader.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/loader/FileCacheLoader.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -46,31 +46,29 @@
/**
* Simple file-based CacheLoader implementation. Nodes are directories, attributes of a node is a file in the directory
* <p/>
- * The FileCacheLoader has some severe limitations which restrict its use in a production
- * environment, or if used in such an environment, it should be used with due care and sufficient
- * understanding of these limitations.
- * <ul>
- * <li>Due to the way the FileCacheLoader represents a tree structure on disk (directories and files) traversal is inefficient for deep trees.</li>
- * <li>Usage on shared filesystems like NFS, Windows shares, etc. should be avoided as these do not implement proper file locking and can cause data corruption.</li>
- * <li>Usage with an isolation level of NONE can cause corrupt writes as multiple threads attempt to write to the same file.</li>
- * <li>File systems are inherently not transactional, so when attempting to use your cache in a transactional context, failures when writing to the file (which happens during the commit phase) cannot be recovered.</li>
- * </ul>
+ * The FileCacheLoader has some severe limitations which restrict its use in a production environment, or if used in
+ * such an environment, it should be used with due care and sufficient understanding of these limitations. <ul> <li>Due
+ * to the way the FileCacheLoader represents a tree structure on disk (directories and files) traversal is inefficient
+ * for deep trees.</li> <li>Usage on shared filesystems like NFS, Windows shares, etc. should be avoided as these do not
+ * implement proper file locking and can cause data corruption.</li> <li>Usage with an isolation level of NONE can cause
+ * corrupt writes as multiple threads attempt to write to the same file.</li> <li>File systems are inherently not
+ * transactional, so when attempting to use your cache in a transactional context, failures when writing to the file
+ * (which happens during the commit phase) cannot be recovered.</li> </ul>
* <p/>
- * As a rule of thumb, it is recommended that the FileCacheLoader not be used in a highly concurrent,
- * transactional or stressful environment, and its use is restricted to testing.
+ * As a rule of thumb, it is recommended that the FileCacheLoader not be used in a highly concurrent, transactional or
+ * stressful environment, and its use is restricted to testing.
* <p/>
- * In terms of concurrency, file systems are notoriously inconsistent in their implementations of concurrent locks. To get around
- * this and to meet the <b>thread safety</b> contracts set out in {@link CacheLoader}, this implementation uses a {@link StripedLock}
+ * In terms of concurrency, file systems are notoriously inconsistent in their implementations of concurrent locks. To
+ * get around this and to meet the <b>thread safety</b> contracts set out in {@link CacheLoader}, this implementation
+ * uses a {@link StripedLock}
*
* @author Bela Ban
* @author <a href="mailto:galder.zamarreno at jboss.com">Galder Zamarreno</a>
* @author <a href="mailto:manik at jboss.org">Manik Surtani</a>
- *
* @since 1.0
*/
@ThreadSafe
-public class FileCacheLoader<K, V> extends AbstractCacheLoader<K, V>
-{
+public class FileCacheLoader<K, V> extends AbstractCacheLoader<K, V> {
File root = null;
String rootPath = null;
Log log = LogFactory.getLog(getClass());
@@ -90,149 +88,116 @@
public static final Pattern KEY_PATTERN = Pattern.compile("[\\\\\\/:*<>|\"?]");
private static boolean isOldWindows;
- static
- {
+ static {
float osVersion = -1;
- try
- {
+ try {
osVersion = Float.parseFloat(System.getProperty("os.version").trim());
}
- catch (Exception e)
- {
+ catch (Exception e) {
// ignore
}
// 4.x is windows NT/2000 and 5.x is XP.
isOldWindows = System.getProperty("os.name").toLowerCase().startsWith("windows") && osVersion < 4;
}
- public void setConfig(IndividualCacheLoaderConfig base)
- {
- if (base instanceof FileCacheLoaderConfig)
- {
+ public void setConfig(IndividualCacheLoaderConfig base) {
+ if (base instanceof FileCacheLoaderConfig) {
this.config = (FileCacheLoaderConfig) base;
- }
- else if (base != null)
- {
+ } else if (base != null) {
this.config = new FileCacheLoaderConfig(base);
}
String location = this.config != null ? this.config.getLocation() : null;
- if (location != null && location.length() > 0)
- {
+ if (location != null && location.length() > 0) {
root = new File(location);
rootPath = root.getAbsolutePath() + File.separator;
}
}
- public IndividualCacheLoaderConfig getConfig()
- {
+ public IndividualCacheLoaderConfig getConfig() {
return config;
}
@Override
- public void create()
- {
- if (root == null)
- {
+ public void create() {
+ if (root == null) {
String tmpLocation = System.getProperty("java.io.tmpdir", "C:\\tmp");
root = new File(tmpLocation);
rootPath = root.getAbsolutePath() + File.separator;
}
- if (!root.exists())
- {
- if (log.isTraceEnabled())
- {
+ if (!root.exists()) {
+ if (log.isTraceEnabled()) {
log.trace("Creating cache loader location " + root);
}
- if (config.isCheckCharacterPortability())
- {
+ if (config.isCheckCharacterPortability()) {
/* Before creating the root, check whether the path is character portable. Anything that comes after is part
of the fqn which is inspected later. */
isCharacterPortableLocation(root.getAbsolutePath());
}
boolean created = root.mkdirs();
- if (!created)
- {
+ if (!created) {
throw new CacheException("Unable to create cache loader location " + root);
}
}
- if (!root.isDirectory())
- {
+ if (!root.isDirectory()) {
throw new CacheException("Cache loader location [" + root + "] is not a directory!");
}
}
- public V get(Object key)
- {
+ public V get(Object key) {
lock(key);
- try
- {
- try
- {
+ try {
+ try {
return loadValue(key);
}
- catch (Exception e)
- {
+ catch (Exception e) {
throw new CacheException(e);
}
}
- finally
- {
+ finally {
unlock(key);
}
}
- public boolean exists(Object key)
- {
+ public boolean exists(Object key) {
lock(key);
- try
- {
+ try {
return getFile(key, false).exists();
}
- catch (IOException e)
- {
+ catch (IOException e) {
throw new CacheException(e);
}
- finally
- {
+ finally {
unlock(key);
}
}
- public V put(K key, V value)
- {
+ public V put(K key, V value) {
lock(key);
- try
- {
+ try {
V retval;
- try
- {
+ try {
retval = loadValue(key);
storeValue(key, value);
return retval;
}
- catch (Exception e)
- {
+ catch (Exception e) {
throw new CacheException(e);
}
}
- finally
- {
+ finally {
unlock(key);
}
}
- public V remove(Object key)
- {
+ public V remove(Object key) {
lock(key);
- try
- {
+ try {
V retval;
- try
- {
+ try {
File file = getFile(key, false);
if (!file.exists())
return null;
@@ -241,34 +206,27 @@
file.delete();
return retval;
}
- catch (Exception e)
- {
+ catch (Exception e) {
throw new CacheException(e);
}
}
- finally
- {
+ finally {
unlock(key);
}
}
- private void unlock(Object key)
- {
+ private void unlock(Object key) {
lock.releaseLock(key.toString());
}
- private void lock(Object key)
- {
+ private void lock(Object key) {
lock.acquireLock(key.toString(), true);
}
- private File getDirectory(Object key, boolean create) throws IOException
- {
+ private File getDirectory(Object key, boolean create) throws IOException {
File f = new File(getFullPath(key));
- if (!f.exists())
- {
- if (create)
- {
+ if (!f.exists()) {
+ if (create) {
boolean make = f.mkdirs();
if (!make)
throw new IOException("Unable to mkdirs " + f);
@@ -277,27 +235,22 @@
return f;
}
- private String getFullPath(Object key)
- {
+ private String getFullPath(Object key) {
return rootPath;
}
- private void safeClose(Closeable closeable)
- {
+ private void safeClose(Closeable closeable) {
if (closeable == null)
return;
- try
- {
+ try {
closeable.close();
}
- catch (IOException e)
- {
+ catch (IOException e) {
}
}
- private V loadValue(Object key) throws Exception
- {
+ private V loadValue(Object key) throws Exception {
File child = getFile(key, false);
if (!child.exists())
return null;
@@ -305,68 +258,56 @@
return loadValue(child);
}
- private V loadValue(File file) throws Exception
- {
+ private V loadValue(File file) throws Exception {
FileInputStream fileIn = null;
ObjectInputStream input = null;
- try
- {
+ try {
fileIn = new FileInputStream(file);
input = new MarshalledValueInputStream(fileIn);
return (V) getMarshaller().objectFromObjectStream(input);
}
- catch (FileNotFoundException fnfe)
- {
+ catch (FileNotFoundException fnfe) {
return null;
}
- finally
- {
+ finally {
safeClose(input);
safeClose(fileIn);
}
}
- private EntryData<K, V> loadEntry(File file) throws Exception
- {
+ private EntryData<K, V> loadEntry(File file) throws Exception {
FileInputStream fileIn = null;
ObjectInputStream input = null;
- try
- {
+ try {
fileIn = new FileInputStream(file);
input = new MarshalledValueInputStream(fileIn);
V value = (V) getMarshaller().objectFromObjectStream(input);
K key = (K) getMarshaller().objectFromObjectStream(input);
return new EntryData<K, V>(key, value);
}
- catch (FileNotFoundException fnfe)
- {
+ catch (FileNotFoundException fnfe) {
return null;
}
- finally
- {
+ finally {
safeClose(input);
safeClose(fileIn);
}
}
- private File getFile(Object key, boolean create) throws IOException
- {
+ private File getFile(Object key, boolean create) throws IOException {
File directory = getDirectory(key, create);
File child = new File(directory, key.toString());
- if (create && !child.exists())
- {
- if (config.isCheckCharacterPortability())
- {
+ if (create && !child.exists()) {
+ if (config.isCheckCharacterPortability()) {
/* Check whether the entire file path (root + fqn + data file name), is length portable */
isLengthPortablePath(child.getAbsolutePath());
/* Check whether the fqn tree we're trying to store could contain non portable characters */
isCharacterPortableKey(key);
}
- if (!child.createNewFile())
- {
+ if (!child.createNewFile()) {
throw new IOException("Unable to create file: " + child);
}
}
@@ -374,31 +315,26 @@
return child;
}
- protected void storeValue(Object key, Object value) throws Exception
- {
+ protected void storeValue(Object key, Object value) throws Exception {
File child = getFile(key, true);
FileOutputStream fileOut = null;
ObjectOutputStream output = null;
- try
- {
+ try {
fileOut = new FileOutputStream(child);
output = new ObjectOutputStream(fileOut);
getMarshaller().objectToObjectStream(value, output);
getMarshaller().objectToObjectStream(key, output); // For getAllEntries
}
- finally
- {
+ finally {
safeClose(output);
safeClose(fileOut);
}
}
- protected boolean isCharacterPortableLocation(String fileAbsolutePath)
- {
+ protected boolean isCharacterPortableLocation(String fileAbsolutePath) {
Matcher matcher = PATH_PATTERN.matcher(fileAbsolutePath);
- if (matcher.find())
- {
+ if (matcher.find()) {
log.warn("Cache loader location ( " + fileAbsolutePath + " ) contains one of these characters: '*' '<' '>' '|' '\"' '?'");
log.warn("Directories containing these characters are illegal in some operative systems and could lead to portability issues");
return false;
@@ -407,12 +343,10 @@
return true;
}
- protected boolean isCharacterPortableKey(Object key)
- {
+ protected boolean isCharacterPortableKey(Object key) {
// getFullPath converts Object to String via toString(), so we do too
Matcher matcher = KEY_PATTERN.matcher(key.toString());
- if (matcher.find())
- {
+ if (matcher.find()) {
log.warn("The key.toString() contains one of these characters: '*' '<' '>' '|' '\"' '?' '\\' '/' ':' ");
log.warn("Directories containing these characters are illegal in some operating systems and could lead to portability issues");
return false;
@@ -421,11 +355,9 @@
return true;
}
- protected boolean isLengthPortablePath(String absoluteFqnPath)
- {
+ protected boolean isLengthPortablePath(String absoluteFqnPath) {
- if (isOldWindows && absoluteFqnPath.length() > 255)
- {
+ if (isOldWindows && absoluteFqnPath.length() > 255) {
log.warn("The full absolute path to the fqn that you are trying to store is bigger than 255 characters, this could lead to problems on certain Windows systems: " + absoluteFqnPath);
return false;
}
@@ -433,58 +365,46 @@
return true;
}
- public void clear()
- {
+ public void clear() {
File directory = new File(rootPath);
if (!directory.exists())
return;
File[] files = directory.listFiles();
- if (files != null)
- {
- for (File file : files)
- {
- try
- {
+ if (files != null) {
+ for (File file : files) {
+ try {
lock(file.getName());
if (file.exists())
file.delete();
}
- finally
- {
+ finally {
unlock(file.getName());
}
}
}
}
- public List<EntryData<K, V>> getAllEntries()
- {
+ public List<EntryData<K, V>> getAllEntries() {
List<EntryData<K, V>> entries = new LinkedList<EntryData<K, V>>();
File directory = new File(rootPath);
if (!directory.exists())
return entries;
File[] files = directory.listFiles();
- if (files != null)
- {
- for (File file : files)
- {
- try
- {
+ if (files != null) {
+ for (File file : files) {
+ try {
lock(file.getName());
- if (file.exists())
- {
+ if (file.exists()) {
EntryData<K, V> entry = loadEntry(file);
if (entry != null)
entries.add(entry);
}
}
- catch (Exception e)
- {
+ catch (Exception e) {
}
- finally
- {
+ finally {
unlock(file.getName());
}
}
Modified: core/branches/flat/src/main/java/org/horizon/loader/FileCacheLoaderConfig.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/loader/FileCacheLoaderConfig.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/loader/FileCacheLoaderConfig.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -23,20 +23,18 @@
import org.horizon.config.CacheLoaderConfig.IndividualCacheLoaderConfig;
import org.horizon.config.Dynamic;
+import org.horizon.util.Util;
import java.util.Properties;
-import org.horizon.util.Util;
-public class FileCacheLoaderConfig extends IndividualCacheLoaderConfig
-{
+public class FileCacheLoaderConfig extends IndividualCacheLoaderConfig {
private static final long serialVersionUID = 4626734068542420865L;
private String location;
@Dynamic
private boolean checkCharacterPortability = true;
- public FileCacheLoaderConfig()
- {
+ public FileCacheLoaderConfig() {
setClassName(FileCacheLoader.class.getName());
}
@@ -45,41 +43,34 @@
*
* @param base generic config object created by XML parsing.
*/
- FileCacheLoaderConfig(IndividualCacheLoaderConfig base)
- {
+ FileCacheLoaderConfig(IndividualCacheLoaderConfig base) {
setClassName(FileCacheLoader.class.getName());
populateFromBaseConfig(base);
}
- public String getLocation()
- {
+ public String getLocation() {
return location;
}
- public void setLocation(String location)
- {
+ public void setLocation(String location) {
testImmutability("location");
this.location = location;
}
- public boolean isCheckCharacterPortability()
- {
+ public boolean isCheckCharacterPortability() {
return checkCharacterPortability;
}
- public void setCheckCharacterPortability(boolean checkCharacterPortability)
- {
+ public void setCheckCharacterPortability(boolean checkCharacterPortability) {
testImmutability("check.character.portability");
this.checkCharacterPortability = checkCharacterPortability;
}
@Override
- public void setProperties(Properties props)
- {
+ public void setProperties(Properties props) {
super.setProperties(props);
- if (props != null)
- {
+ if (props != null) {
setLocation(props.getProperty("location"));
String prop = props.getProperty("check.character.portability");
setCheckCharacterPortability((prop == null || Boolean.valueOf(prop)));
@@ -87,24 +78,20 @@
}
@Override
- public boolean equals(Object obj)
- {
- if (obj instanceof FileCacheLoaderConfig && equalsExcludingProperties(obj))
- {
+ public boolean equals(Object obj) {
+ if (obj instanceof FileCacheLoaderConfig && equalsExcludingProperties(obj)) {
return Util.safeEquals(location, ((FileCacheLoaderConfig) obj).location);
}
return false;
}
@Override
- public int hashCode()
- {
+ public int hashCode() {
return 31 * hashCodeExcludingProperties() + (location == null ? 0 : location.hashCode());
}
@Override
- public FileCacheLoaderConfig clone() throws CloneNotSupportedException
- {
+ public FileCacheLoaderConfig clone() throws CloneNotSupportedException {
return (FileCacheLoaderConfig) super.clone();
}
Modified: core/branches/flat/src/main/java/org/horizon/loader/Modification.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/loader/Modification.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/loader/Modification.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -26,24 +26,20 @@
/**
- * Represents a modification in the cache. Contains the nature of the modification
- * (e.g. PUT, REMOVE), the fqn of the node, the new value and the previous value.
- * A list of modifications will be sent to all nodes in a cluster when a transaction
- * has been committed (PREPARE phase). A Modification is also used to roll back changes,
- * e.g. since we know the previous value, we can reconstruct the previous state by
- * applying the changes in a modification listin reverse order.
+ * Represents a modification in the cache. Contains the nature of the modification (e.g. PUT, REMOVE), the fqn of the
+ * node, the new value and the previous value. A list of modifications will be sent to all nodes in a cluster when a
+ * transaction has been committed (PREPARE phase). A Modification is also used to roll back changes, e.g. since we know
+ * the previous value, we can reconstruct the previous state by applying the changes in a modification listin reverse
+ * order.
*
* @author <a href="mailto:bela at jboss.org">Bela Ban</a> Apr 12, 2003
- *
* @since 1.0
*/
-public final class Modification implements Serializable
-{
+public final class Modification implements Serializable {
private static final long serialVersionUID = 7463314130283897197L;
- public static enum ModificationType
- {
+ public static enum ModificationType {
PUT,
REMOVE,
CLEAR
@@ -56,8 +52,7 @@
/**
* Constructs a new modification with details.
*/
- public Modification(ModificationType type, Object key, Object value)
- {
+ public Modification(ModificationType type, Object key, Object value) {
if (type == null)
throw new IllegalArgumentException();
this.type = type;
@@ -69,24 +64,21 @@
/**
* Returns the type of modification.
*/
- public ModificationType getType()
- {
+ public ModificationType getType() {
return type;
}
/**
* Returns the modification key.
*/
- public Object getKey()
- {
+ public Object getKey() {
return key;
}
/**
* Returns the modification value.
*/
- public Object getValue()
- {
+ public Object getValue() {
return value;
}
@@ -95,16 +87,13 @@
* Returns debug information about this modification.
*/
@Override
- public String toString()
- {
+ public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(type.toString()).append("{");
- if (key != null)
- {
+ if (key != null) {
sb.append("\nkey=").append(key);
}
- if (value != null)
- {
+ if (value != null) {
sb.append("\nvalue=").append(value);
}
return sb.append("}").toString();
Modified: core/branches/flat/src/main/java/org/horizon/loader/ReadOnlyDelegatingCacheLoader.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/loader/ReadOnlyDelegatingCacheLoader.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/loader/ReadOnlyDelegatingCacheLoader.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -21,74 +21,64 @@
*/
package org.horizon.loader;
-import java.io.ObjectInputStream;
-import java.util.List;
-
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
+import java.io.ObjectInputStream;
+import java.util.List;
+
/**
* Provides ignoreModifications features to all cache loaders.
*
* @author <a href="mailto:manik at jboss.org">Manik Surtani</a>
* @since 1.0
*/
-public class ReadOnlyDelegatingCacheLoader<K,V> extends AbstractDelegatingCacheLoader<K,V>
-{
+public class ReadOnlyDelegatingCacheLoader<K, V> extends AbstractDelegatingCacheLoader<K, V> {
private static final Log log = LogFactory.getLog(ReadOnlyDelegatingCacheLoader.class);
- public ReadOnlyDelegatingCacheLoader(CacheLoader cl)
- {
+ public ReadOnlyDelegatingCacheLoader(CacheLoader cl) {
super(cl);
}
@Override
- public V put(K key, V value)
- {
+ public V put(K key, V value) {
log.trace("Not delegating write operation to underlying cache loader");
return get(key);
}
@Override
- public void put(List<Modification> modifications)
- {
+ public void put(List<Modification> modifications) {
log.trace("Not delegating write operation to underlying cache loader");
}
@Override
- public V remove(Object key)
- {
+ public V remove(Object key) {
log.trace("Not delegating write operation to underlying cache loader");
return get(key);
}
@Override
- public void prepare(Object tx, List<Modification> modifications, boolean one_phase)
- {
+ public void prepare(Object tx, List<Modification> modifications, boolean one_phase) {
log.trace("Not delegating write operation to underlying cache loader");
}
@Override
- public void commit(Object tx)
- {
+ public void commit(Object tx) {
log.trace("Not delegating write operation to underlying cache loader");
}
@Override
- public void rollback(Object tx)
- {
+ public void rollback(Object tx) {
log.trace("Not delegating write operation to underlying cache loader");
}
@Override
- public void storeEntireState(ObjectInputStream is)
- {
+ public void storeEntireState(ObjectInputStream is) {
log.trace("Not delegating write operation to underlying cache loader");
}
@Override
- public void clear()
- {
+ public void clear() {
log.trace("Not delegating write operation to underlying cache loader");
}
}
Modified: core/branches/flat/src/main/java/org/horizon/loader/SingletonStoreCacheLoader.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/loader/SingletonStoreCacheLoader.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/loader/SingletonStoreCacheLoader.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -54,9 +54,9 @@
* real CacheLoader.
* <p/>
* Writes are forwarded only if this SingletonStoreCacheLoader is currently the cordinator. This avoid having all
- * CacheLoaders in a cluster writing the same data to the same underlying store. Although not incorrect (e.g. a DB
- * will just discard additional INSERTs for the same key, and throw an exception), this will avoid a lot of
- * redundant work.<br/>
+ * CacheLoaders in a cluster writing the same data to the same underlying store. Although not incorrect (e.g. a DB will
+ * just discard additional INSERTs for the same key, and throw an exception), this will avoid a lot of redundant
+ * work.<br/>
* <p/>
* Whenever the current coordinator dies (or leaves), the second in line will take over. That SingletonStoreCacheLoader
* will then pass writes through to its underlying CacheLoader. Optionally, when a new coordinator takes over the
@@ -66,8 +66,7 @@
* @author <a href="mailto:galder.zamarreno at jboss.com">Galder Zamarreno</a>
* @since 1.0
*/
-public class SingletonStoreCacheLoader extends AbstractDelegatingCacheLoader
-{
+public class SingletonStoreCacheLoader extends AbstractDelegatingCacheLoader {
/**
* Log instance.
*/
@@ -110,14 +109,11 @@
/**
* Empty constructor so that it can instantiated using reflection.
*/
- public SingletonStoreCacheLoader()
- {
+ public SingletonStoreCacheLoader() {
super(null);
- executor = Executors.newSingleThreadExecutor(new ThreadFactory()
- {
- public Thread newThread(Runnable r)
- {
+ executor = Executors.newSingleThreadExecutor(new ThreadFactory() {
+ public Thread newThread(Runnable r) {
return new Thread(r, THREAD_NAME);
}
});
@@ -127,21 +123,15 @@
* Sets the config for SingletonStoreCacheLoader and for the delegating cache loader.
*/
@Override
- public void setConfig(CacheLoaderConfig.IndividualCacheLoaderConfig config)
- {
+ public void setConfig(CacheLoaderConfig.IndividualCacheLoaderConfig config) {
super.setConfig(config);
SingletonStoreConfig ssc = config.getSingletonStoreConfig();
- if (ssc instanceof SingletonStoreDefaultConfig)
- {
+ if (ssc instanceof SingletonStoreDefaultConfig) {
this.config = (SingletonStoreDefaultConfig) ssc;
- }
- else if (ssc != null)
- {
+ } else if (ssc != null) {
this.config = new SingletonStoreDefaultConfig(ssc);
- }
- else
- {
+ } else {
this.config = new SingletonStoreDefaultConfig();
}
}
@@ -160,8 +150,7 @@
*
* @param config configuration instance for SingletonStoreCacheLoader
*/
- protected SingletonStoreCacheLoader(SingletonStoreDefaultConfig config)
- {
+ protected SingletonStoreCacheLoader(SingletonStoreDefaultConfig config) {
this();
this.config = config;
@@ -173,8 +162,7 @@
*
* @return instance of SingletonStoreDefaultConfig
*/
- protected SingletonStoreDefaultConfig getSingletonStoreDefaultConfig()
- {
+ protected SingletonStoreDefaultConfig getSingletonStoreDefaultConfig() {
return config;
}
@@ -184,8 +172,7 @@
*
* @return an instance of Future
*/
- protected Future<?> getPushStateFuture()
- {
+ protected Future<?> getPushStateFuture() {
return pushStateFuture;
}
@@ -193,14 +180,13 @@
* Method called when the node either becomes the coordinator or stops being the coordinator. If it becomes the
* coordinator, it can optionally start the in-memory state transfer to the underlying cache store.
*
- * @param newActiveState true if the node just became the coordinator, false if the nodes stopped being the coordinator.
+ * @param newActiveState true if the node just became the coordinator, false if the nodes stopped being the
+ * coordinator.
*/
- protected void activeStatusChanged(boolean newActiveState) throws PushStateException
- {
+ protected void activeStatusChanged(boolean newActiveState) throws PushStateException {
active = newActiveState;
log.debug("changed mode: " + this);
- if (active && config.isPushStateWhenCoordinator())
- {
+ if (active && config.isPushStateWhenCoordinator()) {
doPushState();
}
}
@@ -208,15 +194,12 @@
/**
* Factory method for the creation of a Callable task in charge of pushing in-memory state to cache loader.
*
- * @return new instance of Callable<?> whose call() method either throws an exception or returns null if the task
- * was successfull.
+ * @return new instance of Callable<?> whose call() method either throws an exception or returns null if the task was
+ * successfull.
*/
- protected Callable<?> createPushStateTask()
- {
- return new Callable()
- {
- public Object call() throws Exception
- {
+ protected Callable<?> createPushStateTask() {
+ return new Callable() {
+ public Object call() throws Exception {
final boolean debugEnabled = log.isDebugEnabled();
if (debugEnabled) log.debug("start pushing in-memory state to cache cacheLoader");
@@ -259,31 +242,26 @@
// }
/**
- * Method that waits for the in-memory to cache loader state to finish. This method's called in case a push state
- * is already in progress and we need to wait for it to finish.
+ * Method that waits for the in-memory to cache loader state to finish. This method's called in case a push state is
+ * already in progress and we need to wait for it to finish.
*
* @param future instance of Future representing the on going push task
* @param timeout time to wait for the push task to finish
* @param unit instance of TimeUnit representing the unit of timeout
*/
- protected void awaitForPushToFinish(Future future, int timeout, TimeUnit unit)
- {
+ protected void awaitForPushToFinish(Future future, int timeout, TimeUnit unit) {
final boolean debugEnabled = log.isDebugEnabled();
- try
- {
+ try {
if (debugEnabled) log.debug("wait for state push to cache loader to finish");
future.get(timeout, unit);
}
- catch (TimeoutException e)
- {
+ catch (TimeoutException e) {
if (debugEnabled) log.debug("timed out waiting for state push to cache loader to finish");
}
- catch (ExecutionException e)
- {
+ catch (ExecutionException e) {
if (debugEnabled) log.debug("exception reported waiting for state push to cache loader to finish");
}
- catch (InterruptedException ie)
- {
+ catch (InterruptedException ie) {
/* Re-assert the thread's interrupted status */
Thread.currentThread().interrupt();
if (trace) log.trace("wait for state push to cache loader to finish was interrupted");
@@ -297,23 +275,17 @@
*
* @throws PushStateException when the push state task reports an issue.
*/
- private void doPushState() throws PushStateException
- {
- if (pushStateFuture == null || pushStateFuture.isDone())
- {
+ private void doPushState() throws PushStateException {
+ if (pushStateFuture == null || pushStateFuture.isDone()) {
Callable<?> task = createPushStateTask();
pushStateFuture = executor.submit(task);
- try
- {
+ try {
waitForTaskToFinish(pushStateFuture, config.getPushStateWhenCoordinatorTimeout(), TimeUnit.MILLISECONDS);
}
- catch (Exception e)
- {
+ catch (Exception e) {
throw new PushStateException("unable to complete in memory state push to cache loader", e);
}
- }
- else
- {
+ } else {
/* at the most, we wait for push state timeout value. if it push task finishes earlier, this call
* will stop when the push task finishes, otherwise a timeout exception will be reported */
awaitForPushToFinish(pushStateFuture, config.getPushStateWhenCoordinatorTimeout(), TimeUnit.MILLISECONDS);
@@ -328,24 +300,19 @@
* @param unit instance of TimeUnit representing the unit of timeout
* @throws Exception if any issues are reported while waiting for the task to finish
*/
- private void waitForTaskToFinish(Future future, int timeout, TimeUnit unit) throws Exception
- {
- try
- {
+ private void waitForTaskToFinish(Future future, int timeout, TimeUnit unit) throws Exception {
+ try {
future.get(timeout, unit);
}
- catch (TimeoutException e)
- {
+ catch (TimeoutException e) {
throw new Exception("task timed out", e);
}
- catch (InterruptedException e)
- {
+ catch (InterruptedException e) {
/* Re-assert the thread's interrupted status */
Thread.currentThread().interrupt();
if (trace) log.trace("task was interrupted");
}
- finally
- {
+ finally {
/* no-op if task is completed */
future.cancel(true); /* interrupt if running */
}
@@ -357,15 +324,11 @@
* @param newView View instance containing the new view of the cluster
* @return whether the current node is the coordinator or not.
*/
- private boolean isCoordinator(View newView)
- {
- if (newView != null && localAddress != null)
- {
+ private boolean isCoordinator(View newView) {
+ if (newView != null && localAddress != null) {
Vector mbrs = newView.getMembers();
- if (mbrs != null)
- {
- if (mbrs.size() > 0 && localAddress.equals(mbrs.firstElement()))
- {
+ if (mbrs != null) {
+ if (mbrs.size() > 0 && localAddress.equals(mbrs.firstElement())) {
/* This node is the coordinator */
return true;
}
@@ -382,10 +345,8 @@
* Calls the underlying cache loader's operation if the current node is the coordinator.
*/
// @Override
- public Object put(Fqn name, Object key, Object value) throws Exception
- {
- if (active)
- {
+ public Object put(Fqn name, Object key, Object value) throws Exception {
+ if (active) {
// return super.put(name, key, value);
}
@@ -396,8 +357,7 @@
* Calls the underlying cache loader's operation if the current node is the coordinator.
*/
// @Override
- public void put(Fqn name, Map attributes) throws Exception
- {
+ public void put(Fqn name, Map attributes) throws Exception {
// TODO implement me
// if (active)
// {
@@ -411,7 +371,7 @@
// @Override
// public void put(List<Modification> modifications) throws Exception
// {
- // TODO implement me
+ // TODO implement me
// if (active)
// {
// super.put(modifications);
@@ -422,10 +382,8 @@
* Calls the underlying cache loader's operation if the current node is the coordinator.
*/
// @Override
- public Object remove(Fqn fqn, Object key) throws Exception
- {
- if (active)
- {
+ public Object remove(Fqn fqn, Object key) throws Exception {
+ if (active) {
// return super.remove(fqn, key);
}
@@ -436,10 +394,8 @@
* Calls the underlying cache loader's operation if the current node is the coordinator.
*/
// @Override
- public void remove(Fqn fqn) throws Exception
- {
- if (active)
- {
+ public void remove(Fqn fqn) throws Exception {
+ if (active) {
super.remove(fqn);
}
}
@@ -448,10 +404,8 @@
* Calls the underlying cache loader's operation if the current node is the coordinator.
*/
// @Override
- public void removeData(Fqn fqn) throws Exception
- {
- if (active)
- {
+ public void removeData(Fqn fqn) throws Exception {
+ if (active) {
// super.removeData(fqn);
}
}
@@ -474,8 +428,7 @@
@Override
public void commit(Object tx) // throws Exception
{
- if (active)
- {
+ if (active) {
super.commit(tx);
}
}
@@ -484,10 +437,8 @@
* Calls the underlying cache loader's operation if the current node is the coordinator.
*/
@Override
- public void rollback(Object tx)
- {
- if (active)
- {
+ public void rollback(Object tx) {
+ if (active) {
super.rollback(tx);
}
}
@@ -498,8 +449,7 @@
@Override
public void storeEntireState(ObjectInputStream is) //throws Exception
{
- if (active)
- {
+ if (active) {
super.storeEntireState(is);
}
}
@@ -508,11 +458,9 @@
* Calls the underlying cache loader's operation if the current node is the coordinator.
*/
// @Override
- public void storeState(Fqn subtree, ObjectInputStream is) throws Exception
- {
- if (active)
- {
- // super.storeState(subtree, is);
+ public void storeState(Fqn subtree, ObjectInputStream is) throws Exception {
+ if (active) {
+ // super.storeState(subtree, is);
}
}
@@ -520,8 +468,7 @@
* Calls the underlying cache loader's operation if the current node is the coordinator.
*/
@Override
- public String toString()
- {
+ public String toString() {
return "loc_addr=" + localAddress + ", active=" + active;
}
@@ -531,23 +478,20 @@
* underlying cache store.
*/
@CacheListener
- public class SingletonStoreListener
- {
+ public class SingletonStoreListener {
/**
* Cache started, check whether the node is the coordinator and set the singleton store cache loader's active
* status.
*/
@CacheStarted
- public void cacheStarted(Event e)
- {
+ public void cacheStarted(Event e) {
localAddress = cache.getLocalAddress();
active = cache.getRPCManager().isCoordinator();
if (log.isDebugEnabled()) log.debug("cache started: " + this);
}
@CacheStopped
- public void cacheStopped(Event e)
- {
+ public void cacheStopped(Event e) {
if (log.isDebugEnabled()) log.debug("cache stopped: " + this);
}
@@ -557,18 +501,14 @@
* became the coordinator. This method will report any issues that could potentially arise from this push.
*/
@ViewChanged
- public void viewChange(ViewChangedEvent event)
- {
+ public void viewChange(ViewChangedEvent event) {
boolean tmp = isCoordinator(event.getNewView());
- if (active != tmp)
- {
- try
- {
+ if (active != tmp) {
+ try {
activeStatusChanged(tmp);
}
- catch (PushStateException e)
- {
+ catch (PushStateException e) {
log.error("exception reported changing nodes active status", e);
}
@@ -579,17 +519,14 @@
/**
* Exception representing any issues that arise from pushing the in-memory state to the cache loader.
*/
- public static class PushStateException extends Exception
- {
+ public static class PushStateException extends Exception {
private static final long serialVersionUID = 5542893943730200886L;
- public PushStateException(String message, Throwable cause)
- {
+ public PushStateException(String message, Throwable cause) {
super(message, cause);
}
- public PushStateException(Throwable cause)
- {
+ public PushStateException(Throwable cause) {
super(cause);
}
}
Modified: core/branches/flat/src/main/java/org/horizon/loader/SingletonStoreDefaultConfig.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/loader/SingletonStoreDefaultConfig.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/loader/SingletonStoreDefaultConfig.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -35,8 +35,7 @@
* @author <a href="mailto:galder.zamarreno at jboss.com">Galder Zamarreno</a>
* @since 1.0
*/
-public class SingletonStoreDefaultConfig extends SingletonStoreConfig
-{
+public class SingletonStoreDefaultConfig extends SingletonStoreConfig {
private static final long serialVersionUID = -5828927920142613537L;
/**
@@ -52,11 +51,10 @@
private int pushStateWhenCoordinatorTimeout;
/**
- * Default constructor that sets default values for singleton store cache loader configuration taking in account
- * that this configuration belongs to the default singleton store cache loader implementation.
+ * Default constructor that sets default values for singleton store cache loader configuration taking in account that
+ * this configuration belongs to the default singleton store cache loader implementation.
*/
- public SingletonStoreDefaultConfig()
- {
+ public SingletonStoreDefaultConfig() {
/* pushStateWhenCoordinator enabled by default with 20 seconds as default timeout*/
pushStateWhenCoordinator = true;
pushStateWhenCoordinatorTimeout = 20000;
@@ -68,38 +66,33 @@
}
/**
- * Constructor that sets the assumed values for the default singleton store cache loader implementation and also
- * the properties, as per the properties section defined in the XML configuration.
+ * Constructor that sets the assumed values for the default singleton store cache loader implementation and also the
+ * properties, as per the properties section defined in the XML configuration.
*
* @param base contains properties set in XML configuration
*/
- public SingletonStoreDefaultConfig(SingletonStoreConfig base)
- {
+ public SingletonStoreDefaultConfig(SingletonStoreConfig base) {
this();
setSingletonStoreproperties(base.getSingletonStoreproperties());
}
@Override
- public boolean isSingletonStoreEnabled()
- {
+ public boolean isSingletonStoreEnabled() {
return true;
}
@Override
- public void setSingletonStoreEnabled(boolean singletonStoreEnabled)
- {
+ public void setSingletonStoreEnabled(boolean singletonStoreEnabled) {
/* ignore it */
}
@Override
- public String getSingletonStoreClass()
- {
+ public String getSingletonStoreClass() {
return SingletonStoreCacheLoader.class.getName();
}
@Override
- public void setSingletonStoreClass(String singletonStoreClass)
- {
+ public void setSingletonStoreClass(String singletonStoreClass) {
/* ignore it */
}
@@ -110,53 +103,44 @@
* @param props is an instance of Properties containing these values.
*/
@Override
- public void setSingletonStoreproperties(Properties props)
- {
+ public void setSingletonStoreproperties(Properties props) {
super.setSingletonStoreproperties(props);
String pushStateWhenCoordinatorStr = props.getProperty("pushStateWhenCoordinator");
- if (pushStateWhenCoordinatorStr != null)
- {
+ if (pushStateWhenCoordinatorStr != null) {
/* if not null, we use the defined value, otherwise we leave it to the default value, true */
/* note: default value for a null property is false, hence the check */
setPushStateWhenCoordinator(Boolean.valueOf(pushStateWhenCoordinatorStr));
}
String pushStateWhenCoordinatorTimeoutStr = props.getProperty("pushStateWhenCoordinatorTimeout");
- if (pushStateWhenCoordinatorTimeoutStr != null)
- {
+ if (pushStateWhenCoordinatorTimeoutStr != null) {
setPushStateWhenCoordinatorTimeout(Integer.parseInt(pushStateWhenCoordinatorTimeoutStr));
}
}
- public boolean isPushStateWhenCoordinator()
- {
+ public boolean isPushStateWhenCoordinator() {
return pushStateWhenCoordinator;
}
- public void setPushStateWhenCoordinator(boolean pushStateWhenCoordinator)
- {
+ public void setPushStateWhenCoordinator(boolean pushStateWhenCoordinator) {
testImmutability("pushStateWhenCoordinator");
this.pushStateWhenCoordinator = pushStateWhenCoordinator;
}
- public int getPushStateWhenCoordinatorTimeout()
- {
+ public int getPushStateWhenCoordinatorTimeout() {
return pushStateWhenCoordinatorTimeout;
}
- public void setPushStateWhenCoordinatorTimeout(int pushStateWhenCoordinatorTimeout)
- {
+ public void setPushStateWhenCoordinatorTimeout(int pushStateWhenCoordinatorTimeout) {
testImmutability("pushStateWhenCoordinatorTimeout");
this.pushStateWhenCoordinatorTimeout = pushStateWhenCoordinatorTimeout;
}
@Override
- public boolean equals(Object obj)
- {
+ public boolean equals(Object obj) {
if (this == obj)
return true;
- if (obj instanceof SingletonStoreDefaultConfig)
- {
+ if (obj instanceof SingletonStoreDefaultConfig) {
SingletonStoreDefaultConfig other = (SingletonStoreDefaultConfig) obj;
return (other.pushStateWhenCoordinator == this.pushStateWhenCoordinator)
&& (other.pushStateWhenCoordinatorTimeout == this.pushStateWhenCoordinatorTimeout);
@@ -166,8 +150,7 @@
@Override
- public int hashCode()
- {
+ public int hashCode() {
int result = 13;
result = 23 * result + (pushStateWhenCoordinator ? 0 : 1);
result = 23 * result + pushStateWhenCoordinatorTimeout;
Modified: core/branches/flat/src/main/java/org/horizon/lock/IsolationLevel.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/lock/IsolationLevel.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/lock/IsolationLevel.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -23,17 +23,17 @@
/**
* Various transaction isolation levels as an enumerated class. Note that <a href="http://wiki.jboss.org/wiki/JBossCacheMVCC">MVCC</a>
- * in JBoss Cache 3.0.0 and above only supports {@link #READ_COMMITTED} and {@link #REPEATABLE_READ}, upgrading where possible.
+ * in JBoss Cache 3.0.0 and above only supports {@link #READ_COMMITTED} and {@link #REPEATABLE_READ}, upgrading where
+ * possible.
* <p/>
* Also note that JBoss Cache defaults to {@link #REPEATABLE_READ}.
* <p/>
*
+ * @author (various)
* @see <a href="http://en.wikipedia.org/wiki/Isolation_%28computer_science%29">Isolation levels</a>
* @since 1.0
- * @author (various)
*/
-public enum IsolationLevel
-{
+public enum IsolationLevel {
/**
* No isolation.
*/
Modified: core/branches/flat/src/main/java/org/horizon/lock/LockManager.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/lock/LockManager.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/lock/LockManager.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -29,11 +29,11 @@
* @author Manik Surtani (<a href="mailto:manik at jboss.org">manik at jboss.org</a>)
* @since 1.0
*/
-public interface LockManager
-{
+public interface LockManager {
/**
- * Determines the owner to be used when obtaining locks, given an invocation context. This is typically a {@link org.horizon.transaction.GlobalTransaction} if one
- * is present in the context, or {@link Thread#currentThread()} if one is not present.
+ * Determines the owner to be used when obtaining locks, given an invocation context. This is typically a {@link
+ * org.horizon.transaction.GlobalTransaction} if one is present in the context, or {@link Thread#currentThread()} if
+ * one is not present.
*
* @param ctx invocation context
* @return owner to be used for acquiring locks.
@@ -41,8 +41,9 @@
Object getLockOwner(InvocationContext ctx);
/**
- * Acquires a lock of type lockType, for a given owner, on a specific Node in the cache, denoted by fqn. This
- * method will try for {@link org.horizon.config.Configuration#getLockAcquisitionTimeout()} milliseconds and give up if it is unable to acquire the required lock.
+ * Acquires a lock of type lockType, for a given owner, on a specific Node in the cache, denoted by fqn. This method
+ * will try for {@link org.horizon.config.Configuration#getLockAcquisitionTimeout()} milliseconds and give up if it
+ * is unable to acquire the required lock.
*
* @param key key to lock
* @param owner owner to acquire the lock for
@@ -52,8 +53,8 @@
boolean lock(Object key, Object owner) throws InterruptedException;
/**
- * Acquires a lock of type lockType, for a given owner, on a specific Node in the cache, denoted by fqn. This
- * method will try for timeout milliseconds and give up if it is unable to acquire the required lock.
+ * Acquires a lock of type lockType, for a given owner, on a specific Node in the cache, denoted by fqn. This method
+ * will try for timeout milliseconds and give up if it is unable to acquire the required lock.
*
* @param key key to lock
* @param owner owner to acquire the lock for
@@ -64,14 +65,16 @@
boolean lock(Object key, Object owner, long timeout) throws InterruptedException;
/**
- * Acquires a lock of type lockType, on a specific Node in the cache, denoted by fqn. This
- * method will try for a period of time and give up if it is unable to acquire the required lock. The period of time
- * is specified in {@link org.horizon.config.Option#getLockAcquisitionTimeout()} and, if this is unset, the default timeout
- * set in {@link org.horizon.config.Configuration#getLockAcquisitionTimeout()} is used.
+ * Acquires a lock of type lockType, on a specific Node in the cache, denoted by fqn. This method will try for a
+ * period of time and give up if it is unable to acquire the required lock. The period of time is specified in
+ * {@link org.horizon.config.Option#getLockAcquisitionTimeout()} and, if this is unset, the default timeout set in
+ * {@link org.horizon.config.Configuration#getLockAcquisitionTimeout()} is used.
* <p/>
- * In addition, any locks acquired are added to the context OR transaction entry using {@link InvocationContext#addLock(Object)}.
+ * In addition, any locks acquired are added to the context OR transaction entry using {@link
+ * InvocationContext#addLock(Object)}.
* <p/>
- * The owner for the lock is determined by passing the invocation context to {@link #getLockOwner(InvocationContext)}.
+ * The owner for the lock is determined by passing the invocation context to {@link
+ * #getLockOwner(InvocationContext)}.
* <p/>
*
* @param key key to lock
Modified: core/branches/flat/src/main/java/org/horizon/lock/StripedLock.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/lock/StripedLock.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/lock/StripedLock.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -27,11 +27,11 @@
import java.util.concurrent.locks.ReentrantReadWriteLock;
/**
- * A simple implementation of lock striping, using Fqns as the keys to lock on, primarily used to help make
- * {@link org.horizon.loader.CacheLoader} implemtations thread safe.
+ * A simple implementation of lock striping, using Fqns as the keys to lock on, primarily used to help make {@link
+ * org.horizon.loader.CacheLoader} implemtations thread safe.
* <p/>
- * Backed by a set of {@link java.util.concurrent.locks.ReentrantReadWriteLock} instances, and using the key
- * hashcodes to determine buckets.
+ * Backed by a set of {@link java.util.concurrent.locks.ReentrantReadWriteLock} instances, and using the key hashcodes
+ * to determine buckets.
* <p/>
* Since buckets are used, it doesn't matter that the Fqn in question is not removed from the lock map when no longer in
* use, since the Fqn is not referenced in this class. Rather, the hash code is used.
@@ -41,8 +41,7 @@
* @since 1.0
*/
@ThreadSafe
-public class StripedLock
-{
+public class StripedLock {
private static final int DEFAULT_CONCURRENCY = 20;
private final int lockSegmentMask;
private final int lockSegmentShift;
@@ -52,8 +51,7 @@
/**
* This constructor just calls {@link #StripedLock(int)} with a default concurrency value of 20.
*/
- public StripedLock()
- {
+ public StripedLock() {
this(DEFAULT_CONCURRENCY);
}
@@ -62,12 +60,10 @@
*
* @param concurrency number of threads expected to use this class concurrently.
*/
- public StripedLock(int concurrency)
- {
+ public StripedLock(int concurrency) {
int tempLockSegShift = 0;
int numLocks = 1;
- while (numLocks < concurrency)
- {
+ while (numLocks < concurrency) {
++tempLockSegShift;
numLocks <<= 1;
}
@@ -84,78 +80,63 @@
*
* @param exclusive if true, a write (exclusive) lock is attempted, otherwise a read (shared) lock is used.
*/
- public void acquireLock(Object key, boolean exclusive)
- {
+ public void acquireLock(Object key, boolean exclusive) {
ReentrantReadWriteLock lock = getLock(key);
- if (exclusive)
- {
+ if (exclusive) {
lock.writeLock().lock();
- }
- else
- {
+ } else {
lock.readLock().lock();
}
}
/**
* Releases a lock the caller may be holding. This method is idempotent.
- *
*/
- public void releaseLock(Object key)
- {
+ public void releaseLock(Object key) {
ReentrantReadWriteLock lock = getLock(key);
- if (lock.isWriteLockedByCurrentThread())
- {
+ if (lock.isWriteLockedByCurrentThread()) {
lock.writeLock().unlock();
- }
- else
- {
+ } else {
lock.readLock().unlock();
}
}
- final ReentrantReadWriteLock getLock(Object o)
- {
+ final ReentrantReadWriteLock getLock(Object o) {
return sharedLocks[hashToIndex(o)];
}
- final int hashToIndex(Object o)
- {
+ final int hashToIndex(Object o) {
return (hash(o) >>> lockSegmentShift) & lockSegmentMask;
}
/**
- * Returns a hash code for non-null Object x.
- * Uses the same hash code spreader as most other java.util hash tables, except that this uses the string representation
- * of the object passed in.
+ * Returns a hash code for non-null Object x. Uses the same hash code spreader as most other java.util hash tables,
+ * except that this uses the string representation of the object passed in.
*
* @param x the object serving as a key
* @return the hash code
*/
- final int hash(Object x)
- {
+ final int hash(Object x) {
int h = x.hashCode();
h ^= (h >>> 20) ^ (h >>> 12);
return h ^ (h >>> 7) ^ (h >>> 4);
}
/**
- * Releases locks on all fqns passed in. Makes multiple calls to {@link #releaseLock(Object)}. This method is idempotent.
- *
+ * Releases locks on all fqns passed in. Makes multiple calls to {@link #releaseLock(Object)}. This method is
+ * idempotent.
*/
- public void releaseAllLocks(List<Object> keys)
- {
+ public void releaseAllLocks(List<Object> keys) {
for (Object k : keys) releaseLock(k);
}
/**
- * Acquires locks on all fqns passed in. Makes multiple calls to {@link #acquireLock(Object, boolean)}
+ * Acquires locks on all fqns passed in. Makes multiple calls to {@link #acquireLock(Object, boolean)}
*
* @param exclusive whether locks are exclusive.
*/
- public void acquireAllLocks(List<Object> keys, boolean exclusive)
- {
+ public void acquireAllLocks(List<Object> keys, boolean exclusive) {
for (Object k : keys) acquireLock(k, exclusive);
}
}
Modified: core/branches/flat/src/main/java/org/horizon/lock/StripedLockManager.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/lock/StripedLockManager.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/lock/StripedLockManager.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -23,15 +23,15 @@
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
-import org.horizon.util.concurrent.locks.LockContainer;
-import org.horizon.util.concurrent.locks.OwnableReentrantLock;
-import org.horizon.util.concurrent.locks.OwnableReentrantLockContainer;
-import org.horizon.util.concurrent.locks.ReentrantLockContainer;
import org.horizon.config.Configuration;
import org.horizon.context.InvocationContext;
import org.horizon.factories.annotations.Inject;
import org.horizon.factories.annotations.Start;
import org.horizon.invocation.InvocationContextContainer;
+import org.horizon.util.concurrent.locks.LockContainer;
+import org.horizon.util.concurrent.locks.OwnableReentrantLock;
+import org.horizon.util.concurrent.locks.OwnableReentrantLockContainer;
+import org.horizon.util.concurrent.locks.ReentrantLockContainer;
import javax.transaction.TransactionManager;
import java.util.List;
@@ -45,8 +45,7 @@
* @author Manik Surtani (<a href="mailto:manik at jboss.org">manik at jboss.org</a>)
* @since 1.0
*/
-public class StripedLockManager implements LockManager
-{
+public class StripedLockManager implements LockManager {
protected Configuration configuration;
protected long lockAcquisitionTimeout;
LockContainer<Object> lockContainer;
@@ -56,45 +55,38 @@
private static final boolean trace = log.isTraceEnabled();
@Inject
- public void injectDependencies(Configuration configuration, TransactionManager transactionManager, InvocationContextContainer invocationContextContainer)
- {
+ public void injectDependencies(Configuration configuration, TransactionManager transactionManager, InvocationContextContainer invocationContextContainer) {
this.configuration = configuration;
this.transactionManager = transactionManager;
this.invocationContextContainer = invocationContextContainer;
}
@Start
- public void startLockManager()
- {
+ public void startLockManager() {
this.lockAcquisitionTimeout = configuration.getLockAcquisitionTimeout();
lockContainer = transactionManager == null ? new ReentrantLockContainer<Object>(configuration.getConcurrencyLevel()) : new OwnableReentrantLockContainer<Object>(configuration.getConcurrencyLevel(), invocationContextContainer);
}
- public Object getLockOwner(InvocationContext ctx)
- {
+ public Object getLockOwner(InvocationContext ctx) {
return ctx.getGlobalTransaction() != null ? ctx.getGlobalTransaction() : Thread.currentThread();
}
- public boolean lock(Object key, Object owner) throws InterruptedException
- {
+ public boolean lock(Object key, Object owner) throws InterruptedException {
if (trace) log.trace("Attempting to lock " + key);
Lock lock = lockContainer.getLock(key);
return lock.tryLock(lockAcquisitionTimeout, MILLISECONDS);
}
- public boolean lock(Object key, Object owner, long timeoutMillis) throws InterruptedException
- {
+ public boolean lock(Object key, Object owner, long timeoutMillis) throws InterruptedException {
if (trace) log.trace("Attempting to lock " + key);
Lock lock = lockContainer.getLock(key);
return lock.tryLock(timeoutMillis, MILLISECONDS);
}
- public boolean lockAndRecord(Object key, InvocationContext ctx) throws InterruptedException
- {
+ public boolean lockAndRecord(Object key, InvocationContext ctx) throws InterruptedException {
if (trace) log.trace("Attempting to lock " + key);
Lock lock = lockContainer.getLock(key);
- if (lock.tryLock(ctx.getLockAcquisitionTimeout(lockAcquisitionTimeout), MILLISECONDS))
- {
+ if (lock.tryLock(ctx.getLockAcquisitionTimeout(lockAcquisitionTimeout), MILLISECONDS)) {
ctx.addKeyLocked(key);
return true;
}
@@ -103,23 +95,19 @@
return false;
}
- public void unlock(Object key, Object owner)
- {
+ public void unlock(Object key, Object owner) {
if (trace) log.trace("Attempting to unlock " + key);
Lock lock = lockContainer.getLock(key);
lock.unlock();
}
@SuppressWarnings("unchecked")
- public void unlock(InvocationContext ctx)
- {
+ public void unlock(InvocationContext ctx) {
List<Object> locks = ctx.getKeysLocked();
- if (!locks.isEmpty())
- {
+ if (!locks.isEmpty()) {
// unlocking needs to be done in reverse order.
ListIterator<Object> it = locks.listIterator(locks.size());
- while (it.hasPrevious())
- {
+ while (it.hasPrevious()) {
Object k = it.previous();
if (trace) log.trace("Attempting to unlock " + k);
lockContainer.getLock(k).unlock();
@@ -127,37 +115,28 @@
}
}
- public boolean ownsLock(Object key, Object owner)
- {
+ public boolean ownsLock(Object key, Object owner) {
return lockContainer.ownsLock(key, owner);
}
- public boolean isLocked(Object key)
- {
+ public boolean isLocked(Object key) {
return lockContainer.isLocked(key);
}
- public Object getOwner(Object key)
- {
- if (lockContainer.isLocked(key))
- {
+ public Object getOwner(Object key) {
+ if (lockContainer.isLocked(key)) {
Lock l = lockContainer.getLock(key);
- if (l instanceof OwnableReentrantLock)
- {
+ if (l instanceof OwnableReentrantLock) {
return ((OwnableReentrantLock) l).getOwner();
- }
- else
- {
+ } else {
// cannot determine owner.
return null;
}
- }
- else return null;
+ } else return null;
}
- public String printLockInfo()
- {
+ public String printLockInfo() {
return lockContainer.toString();
}
}
Modified: core/branches/flat/src/main/java/org/horizon/lock/TimeoutException.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/lock/TimeoutException.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/lock/TimeoutException.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -25,43 +25,38 @@
/**
- * Thrown when a timeout occurred. used by operations with timeouts, e.g. lock
- * acquisition, or waiting for responses from all members.
+ * Thrown when a timeout occurred. used by operations with timeouts, e.g. lock acquisition, or waiting for responses
+ * from all members.
*
* @author <a href="mailto:bela at jboss.org">Bela Ban</a>.
- *
- * <p/>
- * <p><b>Revisions:</b>
- * <p/>
- * <p>Dec 28 2002 Bela Ban: first implementation
+ * <p/>
+ * <p/>
+ * <p><b>Revisions:</b>
+ * <p/>
+ * <p>Dec 28 2002 Bela Ban: first implementation
* @since 1.0
*/
-public class TimeoutException extends CacheException
-{
+public class TimeoutException extends CacheException {
/**
* The serialVersionUID
*/
private static final long serialVersionUID = -8096787619908687038L;
- public TimeoutException()
- {
+ public TimeoutException() {
super();
}
- public TimeoutException(String msg)
- {
+ public TimeoutException(String msg) {
super(msg);
}
- public TimeoutException(String msg, Throwable cause)
- {
+ public TimeoutException(String msg, Throwable cause) {
super(msg, cause);
}
@Override
- public String toString()
- {
+ public String toString() {
return super.toString();
}
}
Modified: core/branches/flat/src/main/java/org/horizon/manager/CacheManager.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/manager/CacheManager.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/manager/CacheManager.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -46,42 +46,36 @@
* JVM (unless specific configuration requirements require more than one; but either way, this would be a minimal and
* finite number of instances).
* <p/>
- * Constructing a <tt>CacheManager</tt> is done via one of its constructors, which optionally take in a
- * {@link org.horizon.config.Configuration} or a path or URL to a configuration XML file.
+ * Constructing a <tt>CacheManager</tt> is done via one of its constructors, which optionally take in a {@link
+ * org.horizon.config.Configuration} or a path or URL to a configuration XML file.
* <p/>
- * Lifecycle - <tt>CacheManager</tt>s have a lifecycle (it implements {@link Lifecycle}) and the default constructors also
- * call {@link #start()}. Overloaded versions of the constructors are available, that do not start the <tt>CacheManager</tt>,
- * although it must be kept in mind that <tt>CacheManager</tt>s need to be started before they can be used to create <tt>Cache</tt>
- * instances.
+ * Lifecycle - <tt>CacheManager</tt>s have a lifecycle (it implements {@link Lifecycle}) and the default constructors
+ * also call {@link #start()}. Overloaded versions of the constructors are available, that do not start the
+ * <tt>CacheManager</tt>, although it must be kept in mind that <tt>CacheManager</tt>s need to be started before they
+ * can be used to create <tt>Cache</tt> instances.
* <p/>
* Once constructed, <tt>CacheManager</tt>s should be made available to any component that requires a <tt>Cache</tt>,
* via JNDI or via some other mechanism such as an IoC container.
* <p/>
- * You obtain <tt>Cache</tt> instances from the <tt>CacheManager</tt> by using one of the overloaded <tt>getCache()</tt>,
- * methods. Note that with <tt>getCache()</tt>, there is no guarantee that the instance you get is brand-new and empty,
- * since caches are named and shared. Because of this, the <tt>CacheManager</tt> also acts as a repository of <tt>Cache</tt>s,
- * and is an effective mechanism of looking up or creating <tt>Cache</tt>s on demand.
+ * You obtain <tt>Cache</tt> instances from the <tt>CacheManager</tt> by using one of the overloaded
+ * <tt>getCache()</tt>, methods. Note that with <tt>getCache()</tt>, there is no guarantee that the instance you get is
+ * brand-new and empty, since caches are named and shared. Because of this, the <tt>CacheManager</tt> also acts as a
+ * repository of <tt>Cache</tt>s, and is an effective mechanism of looking up or creating <tt>Cache</tt>s on demand.
* <p/>
* When the system shuts down, it should call {@link #stop()} on the <tt>CacheManager</tt>. This will ensure all caches
* within its scope are properly stopped as well.
* <p/>
- * Sample usage:
- * <code>
- * CacheManager manager = CacheManager.getInstance("my-config-file.xml");
- * Cache entityCache = manager.getCache("myEntityCache");
- * entityCache.put("aPerson", new Person());
+ * Sample usage: <code> CacheManager manager = CacheManager.getInstance("my-config-file.xml"); Cache entityCache =
+ * manager.getCache("myEntityCache"); entityCache.put("aPerson", new Person());
* <p/>
- * Configuration myNewConfiguration = new Configuration();
- * myNewConfiguration.setCacheMode(Configuration.CacheMode.LOCAL);
- * manager.defineCache("myLocalCache", myNewConfiguration);
- * Cache localCache = manager.getCache("myLocalCache");
+ * Configuration myNewConfiguration = new Configuration(); myNewConfiguration.setCacheMode(Configuration.CacheMode.LOCAL);
+ * manager.defineCache("myLocalCache", myNewConfiguration); Cache localCache = manager.getCache("myLocalCache");
* </code>
*
* @author Manik Surtani (<a href="mailto:manik at jboss.org">manik at jboss.org</a>)
* @since 1.0
*/
-public class CacheManager implements Lifecycle
-{
+public class CacheManager implements Lifecycle {
public static final String DEFAULT_CACHE_NAME = "org.jboss.starobrno.manager.CacheManager.DEFAULT_CACHE_NAME";
protected GlobalConfiguration globalConfiguration;
private final ConcurrentMap<String, Cache> caches = new ConcurrentHashMap<String, Cache>();
@@ -92,8 +86,7 @@
/**
* Constructs and starts a default instance of the CacheManager, using configuration defaults.
*/
- public CacheManager()
- {
+ public CacheManager() {
this(null, null, true);
}
@@ -102,8 +95,7 @@
*
* @param start if true, the cache manager is started
*/
- public CacheManager(boolean start)
- {
+ public CacheManager(boolean start) {
this(null, null, start);
}
@@ -113,43 +105,39 @@
*
* @param defaultConfiguration configuration to use as a template for all caches created
*/
- public CacheManager(Configuration defaultConfiguration)
- {
+ public CacheManager(Configuration defaultConfiguration) {
this(null, defaultConfiguration, true);
}
/**
- * Constructs a new instance of the CacheManager, using the default configuration passed in. Uses
- * defaults for a {@link org.horizon.config.GlobalConfiguration}.
+ * Constructs a new instance of the CacheManager, using the default configuration passed in. Uses defaults for a
+ * {@link org.horizon.config.GlobalConfiguration}.
*
* @param defaultConfiguration configuration file to use as a template for all caches created
* @param start if true, the cache manager is started
*/
- public CacheManager(Configuration defaultConfiguration, boolean start)
- {
+ public CacheManager(Configuration defaultConfiguration, boolean start) {
this(null, defaultConfiguration, start);
}
/**
- * Constructs and starts a new instance of the CacheManager, using the global configuration passed in, and
- * system defaults for the default named cache configuration.
+ * Constructs and starts a new instance of the CacheManager, using the global configuration passed in, and system
+ * defaults for the default named cache configuration.
*
* @param globalConfiguration GlobalConfiguration to use for all caches created
*/
- public CacheManager(GlobalConfiguration globalConfiguration)
- {
+ public CacheManager(GlobalConfiguration globalConfiguration) {
this(globalConfiguration, null, true);
}
/**
- * Constructs a new instance of the CacheManager, using the global configuration passed in, and
- * system defaults for the default named cache configuration.
+ * Constructs a new instance of the CacheManager, using the global configuration passed in, and system defaults for
+ * the default named cache configuration.
*
* @param globalConfiguration GlobalConfiguration to use for all caches created
* @param start if true, the cache manager is started.
*/
- public CacheManager(GlobalConfiguration globalConfiguration, boolean start)
- {
+ public CacheManager(GlobalConfiguration globalConfiguration, boolean start) {
this(globalConfiguration, null, start);
}
@@ -161,8 +149,7 @@
* @param defaultConfiguration default configuration to use. If null, a default instance is created.
* @param start if true, the cache manager is started
*/
- public CacheManager(GlobalConfiguration globalConfiguration, Configuration defaultConfiguration, boolean start)
- {
+ public CacheManager(GlobalConfiguration globalConfiguration, Configuration defaultConfiguration, boolean start) {
this.globalConfiguration = globalConfiguration == null ? new GlobalConfiguration() : globalConfiguration.clone();
this.globalConfiguration.setDefaultConfiguration(defaultConfiguration == null ? new Configuration() : defaultConfiguration.clone());
globalComponentRegistry = new GlobalComponentRegistry(globalConfiguration);
@@ -171,80 +158,74 @@
/**
- * Constructs and starts a new instance of the CacheManager, using the configuration file name passed in. This constructor
- * first searches for the named file on the classpath, and failing that, treats the file name as an absolute
- * path.
+ * Constructs and starts a new instance of the CacheManager, using the configuration file name passed in. This
+ * constructor first searches for the named file on the classpath, and failing that, treats the file name as an
+ * absolute path.
*
* @param configurationFile name of configuration file to use as a template for all caches created
* @throws java.io.IOException if there is a problem with the configuration file.
*/
- public CacheManager(String configurationFile) throws IOException
- {
+ public CacheManager(String configurationFile) throws IOException {
this(configurationFile, true);
}
/**
* Constructs a new instance of the CacheManager, using the configuration file name passed in. This constructor
- * first searches for the named file on the classpath, and failing that, treats the file name as an absolute
- * path.
+ * first searches for the named file on the classpath, and failing that, treats the file name as an absolute path.
*
* @param configurationFile name of configuration file to use as a template for all caches created
* @param start if true, the cache manager is started
* @throws java.io.IOException if there is a problem with the configuration file.
*/
- public CacheManager(String configurationFile, boolean start) throws IOException
- {
- try
- {
+ public CacheManager(String configurationFile, boolean start) throws IOException {
+ try {
initialize(new XmlConfigurationParserImpl(configurationFile));
}
- catch (RuntimeException re)
- {
+ catch (RuntimeException re) {
throw new ConfigurationException(re);
}
if (start) start();
}
/**
- * Constructs and starts a new instance of the CacheManager, using the input stream passed in to read configuration file contents.
+ * Constructs and starts a new instance of the CacheManager, using the input stream passed in to read configuration
+ * file contents.
*
- * @param configurationStream stream containing configuration file contents, to use as a template for all caches created
+ * @param configurationStream stream containing configuration file contents, to use as a template for all caches
+ * created
* @throws java.io.IOException if there is a problem with the configuration stream.
*/
- public CacheManager(InputStream configurationStream) throws IOException
- {
+ public CacheManager(InputStream configurationStream) throws IOException {
this(configurationStream, true);
}
/**
- * Constructs a new instance of the CacheManager, using the input stream passed in to read configuration file contents.
+ * Constructs a new instance of the CacheManager, using the input stream passed in to read configuration file
+ * contents.
*
- * @param configurationStream stream containing configuration file contents, to use as a template for all caches created
+ * @param configurationStream stream containing configuration file contents, to use as a template for all caches
+ * created
* @param start if true, the cache manager is started
* @throws java.io.IOException if there is a problem reading the configuration stream
*/
- public CacheManager(InputStream configurationStream, boolean start) throws IOException
- {
- try
- {
+ public CacheManager(InputStream configurationStream, boolean start) throws IOException {
+ try {
initialize(new XmlConfigurationParserImpl(configurationStream));
}
- catch (RuntimeException re)
- {
+ catch (RuntimeException re) {
throw new ConfigurationException(re);
}
if (start) start();
}
- private void initialize(XmlConfigurationParser initializedParser)
- {
+ private void initialize(XmlConfigurationParser initializedParser) {
this.globalConfiguration = initializedParser.parseGlobalConfiguration();
configurationOverrides.putAll(initializedParser.parseNamedConfigurations());
}
/**
- * Defines a named cache. Named caches can be defined by using this method, in which case the configuration
- * passed in is used to override the default configuration used when this cache manager instance was created.
+ * Defines a named cache. Named caches can be defined by using this method, in which case the configuration passed
+ * in is used to override the default configuration used when this cache manager instance was created.
* <p/>
* The other way to define named caches is declaratively, in the XML file passed in to the cache manager.
* <p/>
@@ -254,8 +235,7 @@
* @param configurationOverride configuration overrides to use
* @throws CacheNameExistsException if the name is already in use.
*/
- public void defineCache(String cacheName, Configuration configurationOverride) throws CacheNameExistsException
- {
+ public void defineCache(String cacheName, Configuration configurationOverride) throws CacheNameExistsException {
if (cacheName == null || configurationOverrides == null)
throw new NullPointerException("Null arguments not allowed");
if (cacheName.equals(DEFAULT_CACHE_NAME))
@@ -273,8 +253,7 @@
*
* @return the default cache.
*/
- public Cache getCache()
- {
+ public Cache getCache() {
return getCache(DEFAULT_CACHE_NAME);
}
@@ -283,14 +262,13 @@
* cache instance is returned. Otherwise, this method attempts to create the cache first.
* <p/>
* When creating a new cache, this method will use the configuration passed in to the CacheManager on construction,
- * as a template, and then optionally apply any overrides previously defined for the named cache using the
- * {@link #defineCache(String, org.horizon.config.Configuration)} method, or declared in the configuration file.
+ * as a template, and then optionally apply any overrides previously defined for the named cache using the {@link
+ * #defineCache(String, org.horizon.config.Configuration)} method, or declared in the configuration file.
*
* @param cacheName name of cache to retrieve
* @return a cache instance identified by cacheName
*/
- public Cache getCache(String cacheName)
- {
+ public Cache getCache(String cacheName) {
if (cacheName == null)
throw new NullPointerException("Null arguments not allowed");
@@ -300,47 +278,36 @@
return createCache(cacheName);
}
- private Cache createCache(String cacheName)
- {
+ private Cache createCache(String cacheName) {
Configuration c = globalConfiguration.getDefaultConfiguration().clone();
- if (!cacheName.equals(DEFAULT_CACHE_NAME))
- {
+ if (!cacheName.equals(DEFAULT_CACHE_NAME)) {
Configuration overrides = configurationOverrides.get(cacheName);
if (overrides != null) c.applyOverrides(overrides);
}
Cache cache = new DefaultCacheFactory().createCache(c, globalComponentRegistry, cacheName);
Cache other = caches.putIfAbsent(cacheName, cache);
- if (other == null)
- {
+ if (other == null) {
cache.start();
return cache;
- }
- else
- {
+ } else {
return other;
}
}
- public void start()
- {
+ public void start() {
// get a hold of the "default" cache to start this?
CacheSPI defaultCache = (CacheSPI) getCache();
globalComponentRegistry = defaultCache.getComponentRegistry().getSharedComponentRegistry();
}
- public void stop()
- {
+ public void stop() {
// make sure we stop the default cache LAST!
Cache defaultCache = null;
- for (Map.Entry<String, Cache> entry : caches.entrySet())
- {
- if (entry.getKey().equals(DEFAULT_CACHE_NAME))
- {
+ for (Map.Entry<String, Cache> entry : caches.entrySet()) {
+ if (entry.getKey().equals(DEFAULT_CACHE_NAME)) {
defaultCache = entry.getValue();
- }
- else
- {
+ } else {
entry.getValue().stop();
}
}
Modified: core/branches/flat/src/main/java/org/horizon/manager/CacheNameExistsException.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/manager/CacheNameExistsException.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/manager/CacheNameExistsException.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -2,27 +2,23 @@
/**
* Thrown if a cache creation is attempted but the name already exists
- * @since 1.0
+ *
* @author (various)
+ * @since 1.0
*/
-public class CacheNameExistsException extends Exception
-{
- public CacheNameExistsException()
- {
+public class CacheNameExistsException extends Exception {
+ public CacheNameExistsException() {
}
- public CacheNameExistsException(String message)
- {
+ public CacheNameExistsException(String message) {
super(message);
}
- public CacheNameExistsException(String message, Throwable cause)
- {
+ public CacheNameExistsException(String message, Throwable cause) {
super(message, cause);
}
- public CacheNameExistsException(Throwable cause)
- {
+ public CacheNameExistsException(Throwable cause) {
super(cause);
}
}
Modified: core/branches/flat/src/main/java/org/horizon/manager/NamedCacheNotFoundException.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/manager/NamedCacheNotFoundException.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/manager/NamedCacheNotFoundException.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -2,27 +2,23 @@
/**
* Thrown when a named cache cannot be found.
- * @since 1.0
+ *
* @author (various)
+ * @since 1.0
*/
-public class NamedCacheNotFoundException extends Exception
-{
- public NamedCacheNotFoundException()
- {
+public class NamedCacheNotFoundException extends Exception {
+ public NamedCacheNotFoundException() {
}
- public NamedCacheNotFoundException(String message)
- {
+ public NamedCacheNotFoundException(String message) {
super(message);
}
- public NamedCacheNotFoundException(String message, Throwable cause)
- {
+ public NamedCacheNotFoundException(String message, Throwable cause) {
super(message, cause);
}
- public NamedCacheNotFoundException(Throwable cause)
- {
+ public NamedCacheNotFoundException(Throwable cause) {
super(cause);
}
}
Modified: core/branches/flat/src/main/java/org/horizon/marshall/CacheMarshallerStarobrno.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/marshall/CacheMarshallerStarobrno.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/marshall/CacheMarshallerStarobrno.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -55,8 +55,7 @@
* @author <a href="mailto:manik at jboss.org">Manik Surtani (manik at jboss.org)</a>
* @since 1.0
*/
-public class CacheMarshallerStarobrno implements Marshaller
-{
+public class CacheMarshallerStarobrno implements Marshaller {
// magic numbers
protected static final int MAGICNUMBER_METHODCALL = 1;
protected static final int MAGICNUMBER_FQN = 2;
@@ -92,8 +91,7 @@
protected static final int MAGICNUMBER_REF = 101;
- public CacheMarshallerStarobrno()
- {
+ public CacheMarshallerStarobrno() {
initLogger();
// enabled, since this is always enabled in JBC 2.0.0.
useRefs = false;
@@ -106,22 +104,19 @@
protected ClassLoader defaultClassLoader;
protected boolean useRefs = false;
- public void init(Configuration configuration, ClassLoader defaultClassLoader, CommandsFactory commandsFactory)
- {
+ public void init(Configuration configuration, ClassLoader defaultClassLoader, CommandsFactory commandsFactory) {
this.defaultClassLoader = defaultClassLoader;
this.configuration = configuration;
this.commandsFactory = commandsFactory;
}
- protected void initLogger()
- {
+ protected void initLogger() {
log = LogFactory.getLog(getClass());
trace = log.isTraceEnabled();
}
// implement the basic contract set in RPCDispatcher.AbstractMarshaller
- public byte[] objectToByteBuffer(Object obj) throws Exception
- {
+ public byte[] objectToByteBuffer(Object obj) throws Exception {
Buffer b = objectToBuffer(obj);
byte[] bytes = new byte[b.getLength()];
System.arraycopy(b.getBuf(), b.getOffset(), bytes, 0, b.getLength());
@@ -130,219 +125,151 @@
protected CommandsFactory commandsFactory;
- protected void marshallObject(Object o, ObjectOutputStream out, Map<Object, Integer> refMap) throws Exception
- {
- if (o != null && o.getClass().isArray() && isKnownType(o.getClass().getComponentType()))
- {
+ protected void marshallObject(Object o, ObjectOutputStream out, Map<Object, Integer> refMap) throws Exception {
+ if (o != null && o.getClass().isArray() && isKnownType(o.getClass().getComponentType())) {
marshallArray(o, out, refMap);
- }
- else
- {
- if (o == null)
- {
+ } else {
+ if (o == null) {
out.writeByte(MAGICNUMBER_NULL);
- }
- else if (useRefs && refMap.containsKey(o))// see if this object has been marshalled before.
+ } else if (useRefs && refMap.containsKey(o))// see if this object has been marshalled before.
{
out.writeByte(MAGICNUMBER_REF);
writeReference(out, refMap.get(o));
- }
- else if (o instanceof ReplicableCommand)
- {
+ } else if (o instanceof ReplicableCommand) {
ReplicableCommand command = (ReplicableCommand) o;
- if (command.getCommandId() > -1)
- {
+ if (command.getCommandId() > -1) {
out.writeByte(MAGICNUMBER_METHODCALL);
marshallCommand(command, out, refMap);
- }
- else
- {
+ } else {
throw new IllegalArgumentException("MethodCall does not have a valid method id. Was this method call created with MethodCallFactory?");
}
- }
- else if (o instanceof org.jgroups.blocks.MethodCall)
- {
+ } else if (o instanceof org.jgroups.blocks.MethodCall) {
throw new IllegalArgumentException("Usage of a legacy MethodCall object!!");
- }
- else if (o instanceof MarshalledValue)
- {
+ } else if (o instanceof MarshalledValue) {
out.writeByte(MAGICNUMBER_MARSHALLEDVALUE);
((MarshalledValue) o).writeExternal(out);
- }
- else if (o instanceof DeltaAware)
- {
+ } else if (o instanceof DeltaAware) {
// reading in should be nothing special.
out.writeByte(MAGICNUMBER_SERIALIZABLE);
// only write the delta for these maps.
out.writeObject(((DeltaAware) o).delta());
- }
- else if (o instanceof GlobalTransaction)
- {
+ } else if (o instanceof GlobalTransaction) {
out.writeByte(MAGICNUMBER_GTX);
if (useRefs) writeReference(out, createReference(o, refMap));
marshallGlobalTransaction((GlobalTransaction) o, out, refMap);
- }
- else if (o instanceof IpAddress)
- {
+ } else if (o instanceof IpAddress) {
out.writeByte(MAGICNUMBER_IPADDRESS);
marshallIpAddress((IpAddress) o, out);
- }
- else if (o.getClass().equals(ArrayList.class))
- {
+ } else if (o.getClass().equals(ArrayList.class)) {
out.writeByte(MAGICNUMBER_ARRAY_LIST);
marshallCollection((Collection) o, out, refMap);
- }
- else if (o instanceof LinkedList)
- {
+ } else if (o instanceof LinkedList) {
out.writeByte(MAGICNUMBER_LINKED_LIST);
marshallCollection((Collection) o, out, refMap);
- }
- else if (o.getClass().equals(HashMap.class))
- {
+ } else if (o.getClass().equals(HashMap.class)) {
out.writeByte(MAGICNUMBER_HASH_MAP);
marshallMap((Map) o, out, refMap);
- }
- else if (o.getClass().equals(TreeMap.class))
- {
+ } else if (o.getClass().equals(TreeMap.class)) {
out.writeByte(MAGICNUMBER_TREE_MAP);
marshallMap((Map) o, out, refMap);
- }
- else if (o.getClass().equals(FastCopyHashMap.class))
- {
+ } else if (o.getClass().equals(FastCopyHashMap.class)) {
out.writeByte(MAGICNUMBER_FASTCOPY_HASHMAP);
marshallMap((Map) o, out, refMap);
- }
- else if (o instanceof Map && Immutables.isImmutable(o))
- {
+ } else if (o instanceof Map && Immutables.isImmutable(o)) {
out.writeByte(MAGICNUMBER_IMMUTABLE_MAPCOPY);
marshallMap((Map) o, out, refMap);
- }
- else if (o.getClass().equals(HashSet.class))
- {
+ } else if (o.getClass().equals(HashSet.class)) {
out.writeByte(MAGICNUMBER_HASH_SET);
marshallCollection((Collection) o, out, refMap);
- }
- else if (o.getClass().equals(TreeSet.class))
- {
+ } else if (o.getClass().equals(TreeSet.class)) {
out.writeByte(MAGICNUMBER_TREE_SET);
marshallCollection((Collection) o, out, refMap);
- }
- else if (o instanceof Boolean)
- {
+ } else if (o instanceof Boolean) {
out.writeByte(MAGICNUMBER_BOOLEAN);
out.writeBoolean(((Boolean) o).booleanValue());
- }
- else if (o instanceof Integer)
- {
+ } else if (o instanceof Integer) {
out.writeByte(MAGICNUMBER_INTEGER);
out.writeInt(((Integer) o).intValue());
- }
- else if (o instanceof Long)
- {
+ } else if (o instanceof Long) {
out.writeByte(MAGICNUMBER_LONG);
out.writeLong(((Long) o).longValue());
- }
- else if (o instanceof Short)
- {
+ } else if (o instanceof Short) {
out.writeByte(MAGICNUMBER_SHORT);
out.writeShort(((Short) o).shortValue());
- }
- else if (o instanceof String)
- {
+ } else if (o instanceof String) {
out.writeByte(MAGICNUMBER_STRING);
if (useRefs) writeReference(out, createReference(o, refMap));
marshallString((String) o, out);
- }
- else if (o instanceof NodeDataMarker)
- {
+ } else if (o instanceof NodeDataMarker) {
out.writeByte(MAGICNUMBER_NODEDATA_MARKER);
((Externalizable) o).writeExternal(out);
- }
- else if (o instanceof NodeDataExceptionMarker)
- {
+ } else if (o instanceof NodeDataExceptionMarker) {
out.writeByte(MAGICNUMBER_NODEDATA_EXCEPTION_MARKER);
((Externalizable) o).writeExternal(out);
- }
- else if (o instanceof NodeData)
- {
+ } else if (o instanceof NodeData) {
out.writeByte(MAGICNUMBER_NODEDATA);
((Externalizable) o).writeExternal(out);
- }
- else if (o instanceof Serializable)
- {
- if (trace)
- {
+ } else if (o instanceof Serializable) {
+ if (trace) {
log.trace("Warning: using object serialization for " + o.getClass());
}
out.writeByte(MAGICNUMBER_SERIALIZABLE);
if (useRefs) writeReference(out, createReference(o, refMap));
out.writeObject(o);
- }
- else
- {
+ } else {
throw new Exception("Don't know how to marshall object of type " + o.getClass());
}
}
}
- protected void marshallString(String s, ObjectOutputStream out) throws Exception
- {
+ protected void marshallString(String s, ObjectOutputStream out) throws Exception {
//StringUtil.saveString(out, s);
out.writeObject(s);
}
- private void marshallCommand(ReplicableCommand command, ObjectOutputStream out, Map<Object, Integer> refMap) throws Exception
- {
+ private void marshallCommand(ReplicableCommand command, ObjectOutputStream out, Map<Object, Integer> refMap) throws Exception {
out.writeShort(command.getCommandId());
Object[] args = command.getParameters();
byte numArgs = (byte) (args == null ? 0 : args.length);
out.writeByte(numArgs);
- for (int i = 0; i < numArgs; i++)
- {
+ for (int i = 0; i < numArgs; i++) {
marshallObject(args[i], out, refMap);
}
}
- private int createReference(Object o, Map<Object, Integer> refMap)
- {
+ private int createReference(Object o, Map<Object, Integer> refMap) {
int reference = refMap.size();
refMap.put(o, reference);
return reference;
}
- private void marshallGlobalTransaction(GlobalTransaction globalTransaction, ObjectOutputStream out, Map<Object, Integer> refMap) throws Exception
- {
+ private void marshallGlobalTransaction(GlobalTransaction globalTransaction, ObjectOutputStream out, Map<Object, Integer> refMap) throws Exception {
out.writeLong(globalTransaction.getId());
marshallObject(globalTransaction.getAddress(), out, refMap);
}
- private void marshallIpAddress(IpAddress ipAddress, ObjectOutputStream out) throws Exception
- {
+ private void marshallIpAddress(IpAddress ipAddress, ObjectOutputStream out) throws Exception {
ipAddress.writeExternal(out);
}
@SuppressWarnings("unchecked")
- private void marshallCollection(Collection c, ObjectOutputStream out, Map refMap) throws Exception
- {
+ private void marshallCollection(Collection c, ObjectOutputStream out, Map refMap) throws Exception {
writeUnsignedInt(out, c.size());
- for (Object o : c)
- {
+ for (Object o : c) {
marshallObject(o, out, refMap);
}
}
@SuppressWarnings("unchecked")
- private void marshallMap(Map map, ObjectOutputStream out, Map<Object, Integer> refMap) throws Exception
- {
+ private void marshallMap(Map map, ObjectOutputStream out, Map<Object, Integer> refMap) throws Exception {
int mapSize = map.size();
writeUnsignedInt(out, mapSize);
if (mapSize == 0) return;
- for (Map.Entry me : (Set<Map.Entry>) map.entrySet())
- {
+ for (Map.Entry me : (Set<Map.Entry>) map.entrySet()) {
marshallObject(me.getKey(), out, refMap);
marshallObject(me.getValue(), out, refMap);
}
@@ -350,45 +277,35 @@
// --------- Unmarshalling methods
- protected Object unmarshallObject(ObjectInputStream in, ClassLoader loader, UnmarshalledReferences refMap, boolean overrideContextClassloaderOnThread) throws Exception
- {
- if (loader == null)
- {
+ protected Object unmarshallObject(ObjectInputStream in, ClassLoader loader, UnmarshalledReferences refMap, boolean overrideContextClassloaderOnThread) throws Exception {
+ if (loader == null) {
return unmarshallObject(in, refMap);
- }
- else
- {
+ } else {
Thread currentThread = Thread.currentThread();
ClassLoader old = currentThread.getContextClassLoader();
- try
- {
+ try {
// only do this if we haven't already set a context class loader elsewhere.
if (overrideContextClassloaderOnThread || old == null) currentThread.setContextClassLoader(loader);
return unmarshallObject(in, refMap);
}
- finally
- {
+ finally {
if (overrideContextClassloaderOnThread || old == null) currentThread.setContextClassLoader(old);
}
}
}
- protected Object unmarshallObject(ObjectInputStream in, UnmarshalledReferences refMap) throws Exception
- {
+ protected Object unmarshallObject(ObjectInputStream in, UnmarshalledReferences refMap) throws Exception {
byte magicNumber = in.readByte();
int reference = 0;
Object retVal;
- switch (magicNumber)
- {
+ switch (magicNumber) {
case MAGICNUMBER_NULL:
return null;
case MAGICNUMBER_REF:
- if (useRefs)
- {
+ if (useRefs) {
reference = readReference(in);
return refMap.getReferencedObject(reference);
- }
- else break;
+ } else break;
case MAGICNUMBER_SERIALIZABLE:
if (useRefs) reference = readReference(in);
retVal = in.readObject();
@@ -453,8 +370,7 @@
((NodeData) retVal).readExternal(in);
return retVal;
default:
- if (log.isErrorEnabled())
- {
+ if (log.isErrorEnabled()) {
log.error("Unknown Magic Number " + magicNumber);
}
throw new Exception("Unknown magic number " + magicNumber);
@@ -462,26 +378,22 @@
throw new Exception("Unknown magic number " + magicNumber);
}
- private FastCopyHashMap unmarshallFastCopyHashMap(ObjectInputStream in, UnmarshalledReferences refMap) throws Exception
- {
+ private FastCopyHashMap unmarshallFastCopyHashMap(ObjectInputStream in, UnmarshalledReferences refMap) throws Exception {
FastCopyHashMap map = new FastCopyHashMap();
populateFromStream(in, refMap, map);
return map;
}
- protected String unmarshallString(ObjectInputStream in) throws Exception
- {
+ protected String unmarshallString(ObjectInputStream in) throws Exception {
return (String) in.readObject();
}
- private ReplicableCommand unmarshallCommand(ObjectInputStream in, UnmarshalledReferences refMap) throws Exception
- {
+ private ReplicableCommand unmarshallCommand(ObjectInputStream in, UnmarshalledReferences refMap) throws Exception {
short methodId = in.readShort();
byte numArgs = in.readByte();
Object[] args = null;
- if (numArgs > 0)
- {
+ if (numArgs > 0) {
args = new Object[numArgs];
for (int i = 0; i < numArgs; i++) args[i] = unmarshallObject(in, refMap);
}
@@ -490,8 +402,7 @@
}
- private GlobalTransaction unmarshallGlobalTransaction(ObjectInputStream in, UnmarshalledReferences refMap) throws Exception
- {
+ private GlobalTransaction unmarshallGlobalTransaction(ObjectInputStream in, UnmarshalledReferences refMap) throws Exception {
GlobalTransaction gtx = new GlobalTransaction();
long id = in.readLong();
Object address = unmarshallObject(in, refMap);
@@ -500,121 +411,107 @@
return gtx;
}
- private IpAddress unmarshallIpAddress(ObjectInputStream in) throws Exception
- {
+ private IpAddress unmarshallIpAddress(ObjectInputStream in) throws Exception {
IpAddress ipAddress = new IpAddress();
ipAddress.readExternal(in);
return ipAddress;
}
- private List unmarshallArrayList(ObjectInputStream in, UnmarshalledReferences refMap) throws Exception
- {
+ private List unmarshallArrayList(ObjectInputStream in, UnmarshalledReferences refMap) throws Exception {
int listSize = readUnsignedInt(in);
List list = new ArrayList(listSize);
populateFromStream(in, refMap, list, listSize);
return list;
}
- private List unmarshallLinkedList(ObjectInputStream in, UnmarshalledReferences refMap) throws Exception
- {
+ private List unmarshallLinkedList(ObjectInputStream in, UnmarshalledReferences refMap) throws Exception {
List list = new LinkedList();
populateFromStream(in, refMap, list, readUnsignedInt(in));
return list;
}
- private Map unmarshallHashMap(ObjectInputStream in, UnmarshalledReferences refMap) throws Exception
- {
+ private Map unmarshallHashMap(ObjectInputStream in, UnmarshalledReferences refMap) throws Exception {
Map map = new HashMap();
populateFromStream(in, refMap, map);
return map;
}
@SuppressWarnings("unchecked")
- private Map unmarshallMapCopy(ObjectInputStream in, UnmarshalledReferences refMap) throws Exception
- {
+ private Map unmarshallMapCopy(ObjectInputStream in, UnmarshalledReferences refMap) throws Exception {
// read in as a HashMap first
Map m = unmarshallHashMap(in, refMap);
return Immutables.immutableMapWrap(m);
}
- private Map unmarshallTreeMap(ObjectInputStream in, UnmarshalledReferences refMap) throws Exception
- {
+ private Map unmarshallTreeMap(ObjectInputStream in, UnmarshalledReferences refMap) throws Exception {
Map map = new TreeMap();
populateFromStream(in, refMap, map);
return map;
}
- private Set unmarshallHashSet(ObjectInputStream in, UnmarshalledReferences refMap) throws Exception
- {
+ private Set unmarshallHashSet(ObjectInputStream in, UnmarshalledReferences refMap) throws Exception {
Set set = new HashSet();
populateFromStream(in, refMap, set);
return set;
}
- private Set unmarshallTreeSet(ObjectInputStream in, UnmarshalledReferences refMap) throws Exception
- {
+ private Set unmarshallTreeSet(ObjectInputStream in, UnmarshalledReferences refMap) throws Exception {
Set set = new TreeSet();
populateFromStream(in, refMap, set);
return set;
}
@SuppressWarnings("unchecked")
- private void populateFromStream(ObjectInputStream in, UnmarshalledReferences refMap, Map mapToPopulate) throws Exception
- {
+ private void populateFromStream(ObjectInputStream in, UnmarshalledReferences refMap, Map mapToPopulate) throws Exception {
int size = readUnsignedInt(in);
for (int i = 0; i < size; i++) mapToPopulate.put(unmarshallObject(in, refMap), unmarshallObject(in, refMap));
}
@SuppressWarnings("unchecked")
- private void populateFromStream(ObjectInputStream in, UnmarshalledReferences refMap, Set setToPopulate) throws Exception
- {
+ private void populateFromStream(ObjectInputStream in, UnmarshalledReferences refMap, Set setToPopulate) throws Exception {
int size = readUnsignedInt(in);
for (int i = 0; i < size; i++) setToPopulate.add(unmarshallObject(in, refMap));
}
@SuppressWarnings("unchecked")
- private void populateFromStream(ObjectInputStream in, UnmarshalledReferences refMap, List listToPopulate, int listSize) throws Exception
- {
+ private void populateFromStream(ObjectInputStream in, UnmarshalledReferences refMap, List listToPopulate, int listSize) throws Exception {
for (int i = 0; i < listSize; i++) listToPopulate.add(unmarshallObject(in, refMap));
}
/**
- * This version of writeReference is written to solve JBCACHE-1211, where references are encoded as ints rather than shorts.
+ * This version of writeReference is written to solve JBCACHE-1211, where references are encoded as ints rather than
+ * shorts.
*
* @param out stream to write to
* @param reference reference to write
* @throws java.io.IOException propagated from OOS
* @see <a href="http://jira.jboss.org/jira/browse/JBCACHE-1211">JBCACHE-1211</a>
*/
- protected void writeReference(ObjectOutputStream out, int reference) throws IOException
- {
+ protected void writeReference(ObjectOutputStream out, int reference) throws IOException {
writeUnsignedInt(out, reference);
}
/**
- * This version of readReference is written to solve JBCACHE-1211, where references are encoded as ints rather than shorts.
+ * This version of readReference is written to solve JBCACHE-1211, where references are encoded as ints rather than
+ * shorts.
*
* @param in stream to read from
* @return reference
* @throws java.io.IOException propagated from OUS
* @see <a href="http://jira.jboss.org/jira/browse/JBCACHE-1211">JBCACHE-1211</a>
*/
- protected int readReference(ObjectInputStream in) throws IOException
- {
+ protected int readReference(ObjectInputStream in) throws IOException {
return readUnsignedInt(in);
}
/**
- * Reads an int stored in variable-length format. Reads between one and
- * five bytes. Smaller values take fewer bytes. Negative numbers are not
- * supported.
+ * Reads an int stored in variable-length format. Reads between one and five bytes. Smaller values take fewer
+ * bytes. Negative numbers are not supported.
*/
- protected int readUnsignedInt(ObjectInputStream in) throws IOException
- {
+ protected int readUnsignedInt(ObjectInputStream in) throws IOException {
byte b = in.readByte();
int i = b & 0x7F;
- for (int shift = 7; (b & 0x80) != 0; shift += 7)
- {
+ for (int shift = 7; (b & 0x80) != 0; shift += 7) {
b = in.readByte();
i |= (b & 0x7FL) << shift;
}
@@ -622,16 +519,13 @@
}
/**
- * Writes an int in a variable-length format. Writes between one and
- * five bytes. Smaller values take fewer bytes. Negative numbers are not
- * supported.
+ * Writes an int in a variable-length format. Writes between one and five bytes. Smaller values take fewer bytes.
+ * Negative numbers are not supported.
*
* @param i int to write
*/
- protected void writeUnsignedInt(ObjectOutputStream out, int i) throws IOException
- {
- while ((i & ~0x7F) != 0)
- {
+ protected void writeUnsignedInt(ObjectOutputStream out, int i) throws IOException {
+ while ((i & ~0x7F) != 0) {
out.writeByte((byte) ((i & 0x7f) | 0x80));
i >>>= 7;
}
@@ -640,16 +534,13 @@
/**
- * Reads an int stored in variable-length format. Reads between one and
- * nine bytes. Smaller values take fewer bytes. Negative numbers are not
- * supported.
+ * Reads an int stored in variable-length format. Reads between one and nine bytes. Smaller values take fewer
+ * bytes. Negative numbers are not supported.
*/
- protected long readUnsignedLong(ObjectInputStream in) throws IOException
- {
+ protected long readUnsignedLong(ObjectInputStream in) throws IOException {
byte b = in.readByte();
long i = b & 0x7F;
- for (int shift = 7; (b & 0x80) != 0; shift += 7)
- {
+ for (int shift = 7; (b & 0x80) != 0; shift += 7) {
b = in.readByte();
i |= (b & 0x7FL) << shift;
}
@@ -657,166 +548,127 @@
}
/**
- * Writes an int in a variable-length format. Writes between one and
- * nine bytes. Smaller values take fewer bytes. Negative numbers are not
- * supported.
+ * Writes an int in a variable-length format. Writes between one and nine bytes. Smaller values take fewer bytes.
+ * Negative numbers are not supported.
*
* @param i int to write
*/
- protected void writeUnsignedLong(ObjectOutputStream out, long i) throws IOException
- {
- while ((i & ~0x7F) != 0)
- {
+ protected void writeUnsignedLong(ObjectOutputStream out, long i) throws IOException {
+ while ((i & ~0x7F) != 0) {
out.writeByte((byte) ((i & 0x7f) | 0x80));
i >>>= 7;
}
out.writeByte((byte) i);
}
- protected Object unmarshallArray(ObjectInputStream in, UnmarshalledReferences refs) throws Exception
- {
+ protected Object unmarshallArray(ObjectInputStream in, UnmarshalledReferences refs) throws Exception {
int sz = readUnsignedInt(in);
byte type = in.readByte();
- switch (type)
- {
- case MAGICNUMBER_BOOLEAN:
- {
+ switch (type) {
+ case MAGICNUMBER_BOOLEAN: {
boolean isPrim = in.readBoolean();
- if (isPrim)
- {
+ if (isPrim) {
boolean[] a = new boolean[sz];
for (int i = 0; i < sz; i++) a[i] = in.readBoolean();
return a;
- }
- else
- {
+ } else {
Boolean[] a = new Boolean[sz];
for (int i = 0; i < sz; i++) a[i] = in.readBoolean();
return a;
}
}
- case MAGICNUMBER_INTEGER:
- {
+ case MAGICNUMBER_INTEGER: {
boolean isPrim = in.readBoolean();
- if (isPrim)
- {
+ if (isPrim) {
int[] a = new int[sz];
for (int i = 0; i < sz; i++) a[i] = in.readInt();
return a;
- }
- else
- {
+ } else {
Integer[] a = new Integer[sz];
for (int i = 0; i < sz; i++) a[i] = in.readInt();
return a;
}
}
- case MAGICNUMBER_LONG:
- {
+ case MAGICNUMBER_LONG: {
boolean isPrim = in.readBoolean();
- if (isPrim)
- {
+ if (isPrim) {
long[] a = new long[sz];
for (int i = 0; i < sz; i++) a[i] = in.readLong();
return a;
- }
- else
- {
+ } else {
Long[] a = new Long[sz];
for (int i = 0; i < sz; i++) a[i] = in.readLong();
return a;
}
}
- case MAGICNUMBER_CHAR:
- {
+ case MAGICNUMBER_CHAR: {
boolean isPrim = in.readBoolean();
- if (isPrim)
- {
+ if (isPrim) {
char[] a = new char[sz];
for (int i = 0; i < sz; i++) a[i] = in.readChar();
return a;
- }
- else
- {
+ } else {
Character[] a = new Character[sz];
for (int i = 0; i < sz; i++) a[i] = in.readChar();
return a;
}
}
- case MAGICNUMBER_BYTE:
- {
+ case MAGICNUMBER_BYTE: {
boolean isPrim = in.readBoolean();
- if (isPrim)
- {
+ if (isPrim) {
byte[] a = new byte[sz];
int bsize = 10240;
int offset = 0;
int bytesLeft = sz;
- while (bytesLeft > 0)
- {
+ while (bytesLeft > 0) {
int read = in.read(a, offset, Math.min(bsize, bytesLeft));
offset += read;
bytesLeft -= read;
}
return a;
- }
- else
- {
+ } else {
Byte[] a = new Byte[sz];
for (int i = 0; i < sz; i++) a[i] = in.readByte();
return a;
}
}
- case MAGICNUMBER_SHORT:
- {
+ case MAGICNUMBER_SHORT: {
boolean isPrim = in.readBoolean();
- if (isPrim)
- {
+ if (isPrim) {
short[] a = new short[sz];
for (int i = 0; i < sz; i++) a[i] = in.readShort();
return a;
- }
- else
- {
+ } else {
Short[] a = new Short[sz];
for (int i = 0; i < sz; i++) a[i] = in.readShort();
return a;
}
}
- case MAGICNUMBER_FLOAT:
- {
+ case MAGICNUMBER_FLOAT: {
boolean isPrim = in.readBoolean();
- if (isPrim)
- {
+ if (isPrim) {
float[] a = new float[sz];
for (int i = 0; i < sz; i++) a[i] = in.readFloat();
return a;
- }
- else
- {
+ } else {
Float[] a = new Float[sz];
for (int i = 0; i < sz; i++) a[i] = in.readFloat();
return a;
}
}
- case MAGICNUMBER_DOUBLE:
- {
+ case MAGICNUMBER_DOUBLE: {
boolean isPrim = in.readBoolean();
- if (isPrim)
- {
+ if (isPrim) {
double[] a = new double[sz];
for (int i = 0; i < sz; i++) a[i] = in.readDouble();
return a;
- }
- else
- {
+ } else {
Double[] a = new Double[sz];
for (int i = 0; i < sz; i++) a[i] = in.readDouble();
return a;
}
}
- case MAGICNUMBER_OBJECT:
- {
+ case MAGICNUMBER_OBJECT: {
Object[] a = new Object[sz];
for (int i = 0; i < sz; i++) a[i] = unmarshallObject(in, refs);
return a;
@@ -826,136 +678,110 @@
}
}
- protected void marshallArray(Object o, ObjectOutputStream out, Map<Object, Integer> refMap) throws Exception
- {
+ protected void marshallArray(Object o, ObjectOutputStream out, Map<Object, Integer> refMap) throws Exception {
out.writeByte(MAGICNUMBER_ARRAY);
Class arrayTypeClass = o.getClass().getComponentType();
int sz = Array.getLength(o);
writeUnsignedInt(out, sz);
boolean isPrim = arrayTypeClass.isPrimitive();
- if (!isPrim && arrayTypeClass.equals(Object.class))
- {
+ if (!isPrim && arrayTypeClass.equals(Object.class)) {
out.writeByte(MAGICNUMBER_OBJECT);
for (int i = 0; i < sz; i++) marshallObject(Array.get(o, i), out, refMap);
- }
- else if (arrayTypeClass.equals(byte.class) || arrayTypeClass.equals(Byte.class))
- {
+ } else if (arrayTypeClass.equals(byte.class) || arrayTypeClass.equals(Byte.class)) {
out.writeByte(MAGICNUMBER_BYTE);
out.writeBoolean(isPrim);
if (isPrim)
out.write((byte[]) o);
else
for (int i = 0; i < sz; i++) out.writeByte((Byte) Array.get(o, i));
- }
- else if (arrayTypeClass.equals(int.class) || arrayTypeClass.equals(Integer.class))
- {
+ } else if (arrayTypeClass.equals(int.class) || arrayTypeClass.equals(Integer.class)) {
out.writeByte(MAGICNUMBER_INTEGER);
out.writeBoolean(isPrim);
if (isPrim)
for (int i = 0; i < sz; i++) out.writeInt(Array.getInt(o, i));
else
for (int i = 0; i < sz; i++) out.writeInt((Integer) Array.get(o, i));
- }
- else if (arrayTypeClass.equals(long.class) || arrayTypeClass.equals(Long.class))
- {
+ } else if (arrayTypeClass.equals(long.class) || arrayTypeClass.equals(Long.class)) {
out.writeByte(MAGICNUMBER_LONG);
out.writeBoolean(isPrim);
if (isPrim)
for (int i = 0; i < sz; i++) out.writeLong(Array.getLong(o, i));
else
for (int i = 0; i < sz; i++) out.writeLong((Long) Array.get(o, i));
- }
- else if (arrayTypeClass.equals(boolean.class) || arrayTypeClass.equals(Boolean.class))
- {
+ } else if (arrayTypeClass.equals(boolean.class) || arrayTypeClass.equals(Boolean.class)) {
out.writeByte(MAGICNUMBER_BOOLEAN);
out.writeBoolean(isPrim);
if (isPrim)
for (int i = 0; i < sz; i++) out.writeBoolean(Array.getBoolean(o, i));
else
for (int i = 0; i < sz; i++) out.writeBoolean((Boolean) Array.get(o, i));
- }
- else if (arrayTypeClass.equals(char.class) || arrayTypeClass.equals(Character.class))
- {
+ } else if (arrayTypeClass.equals(char.class) || arrayTypeClass.equals(Character.class)) {
out.writeByte(MAGICNUMBER_CHAR);
out.writeBoolean(isPrim);
if (isPrim)
for (int i = 0; i < sz; i++) out.writeChar(Array.getChar(o, i));
else
for (int i = 0; i < sz; i++) out.writeChar((Character) Array.get(o, i));
- }
- else if (arrayTypeClass.equals(short.class) || arrayTypeClass.equals(Short.class))
- {
+ } else if (arrayTypeClass.equals(short.class) || arrayTypeClass.equals(Short.class)) {
out.writeByte(MAGICNUMBER_SHORT);
out.writeBoolean(isPrim);
if (isPrim)
for (int i = 0; i < sz; i++) out.writeShort(Array.getShort(o, i));
else
for (int i = 0; i < sz; i++) out.writeShort((Short) Array.get(o, i));
- }
- else if (arrayTypeClass.equals(float.class) || arrayTypeClass.equals(Float.class))
- {
+ } else if (arrayTypeClass.equals(float.class) || arrayTypeClass.equals(Float.class)) {
out.writeByte(MAGICNUMBER_FLOAT);
out.writeBoolean(isPrim);
if (isPrim)
for (int i = 0; i < sz; i++) out.writeFloat(Array.getFloat(o, i));
else
for (int i = 0; i < sz; i++) out.writeFloat((Float) Array.get(o, i));
- }
- else if (arrayTypeClass.equals(double.class) || arrayTypeClass.equals(Double.class))
- {
+ } else if (arrayTypeClass.equals(double.class) || arrayTypeClass.equals(Double.class)) {
out.writeByte(MAGICNUMBER_DOUBLE);
out.writeBoolean(isPrim);
if (isPrim)
for (int i = 0; i < sz; i++) out.writeDouble(Array.getDouble(o, i));
else
for (int i = 0; i < sz; i++) out.writeDouble((Double) Array.get(o, i));
- }
- else throw new CacheException("Unknown array type!");
+ } else throw new CacheException("Unknown array type!");
}
- protected boolean isKnownType(Class c)
- {
+ protected boolean isKnownType(Class c) {
return (c.equals(Object.class) ||
c.isPrimitive() || c.equals(Character.class) || c.equals(Integer.class) || c.equals(Long.class) ||
c.equals(Byte.class) || c.equals(Boolean.class) || c.equals(Short.class) || c.equals(Float.class) ||
c.equals(Double.class));
}
- public void objectToObjectStream(Object o, ObjectOutputStream out) throws Exception
- {
+ public void objectToObjectStream(Object o, ObjectOutputStream out) throws Exception {
Map<Object, Integer> refMap = useRefs ? new IdentityHashMap<Object, Integer>() : null;
ClassLoader toUse = defaultClassLoader;
Thread current = Thread.currentThread();
ClassLoader old = current.getContextClassLoader();
if (old != null) toUse = old;
- try
- {
+ try {
current.setContextClassLoader(toUse);
marshallObject(o, out, refMap);
}
- finally
- {
+ finally {
current.setContextClassLoader(old);
}
}
- public Object objectFromObjectStream(ObjectInputStream in) throws Exception
- {
+ public Object objectFromObjectStream(ObjectInputStream in) throws Exception {
UnmarshalledReferences refMap = useRefs ? new UnmarshalledReferences() : null;
Object retValue = unmarshallObject(in, defaultClassLoader, refMap, false);
if (trace) log.trace("Unmarshalled object " + retValue);
return retValue;
}
- public Object objectFromStream(InputStream is) throws Exception
- {
+ public Object objectFromStream(InputStream is) throws Exception {
throw new NotImplementedException("not implemented");
}
- public ByteBuffer objectToBuffer(Object o) throws Exception
- {
+ public ByteBuffer objectToBuffer(Object o) throws Exception {
ExposedByteArrayOutputStream baos = new ExposedByteArrayOutputStream(128);
ObjectOutputStream out = new ObjectOutputStream(baos);
@@ -966,14 +792,12 @@
return new ByteBuffer(baos.getRawBuffer(), 0, baos.size());
}
- public Object objectFromByteBuffer(byte[] buf, int offset, int length) throws Exception
- {
+ public Object objectFromByteBuffer(byte[] buf, int offset, int length) throws Exception {
ObjectInputStream in = new MarshalledValueInputStream(new ByteArrayInputStream(buf, offset, length));
return objectFromObjectStream(in);
}
- public Object objectFromByteBuffer(byte[] bytes) throws Exception
- {
+ public Object objectFromByteBuffer(byte[] bytes) throws Exception {
return objectFromByteBuffer(bytes, 0, bytes.length);
}
}
\ No newline at end of file
Modified: core/branches/flat/src/main/java/org/horizon/marshall/CommandAwareRpcDispatcher.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/marshall/CommandAwareRpcDispatcher.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/marshall/CommandAwareRpcDispatcher.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -30,7 +30,11 @@
import org.horizon.invocation.InvocationContextContainer;
import org.horizon.util.concurrent.BoundedExecutors;
import org.horizon.util.concurrent.WithinThreadExecutor;
-import org.jgroups.*;
+import org.jgroups.Address;
+import org.jgroups.Channel;
+import org.jgroups.MembershipListener;
+import org.jgroups.Message;
+import org.jgroups.MessageListener;
import org.jgroups.blocks.RpcDispatcher;
import org.jgroups.blocks.RspFilter;
import org.jgroups.util.Buffer;
@@ -39,7 +43,12 @@
import java.io.NotSerializableException;
import java.util.Vector;
-import java.util.concurrent.*;
+import java.util.concurrent.Callable;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Future;
+import java.util.concurrent.ThreadFactory;
+import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
/**
@@ -48,8 +57,7 @@
* @author Manik Surtani (<a href="mailto:manik at jboss.org">manik at jboss.org</a>)
* @since 1.0
*/
-public class CommandAwareRpcDispatcher extends RpcDispatcher
-{
+public class CommandAwareRpcDispatcher extends RpcDispatcher {
protected InvocationContextContainer invocationContextContainer;
protected InterceptorChain interceptorChain;
protected ComponentRegistry componentRegistry;
@@ -58,14 +66,12 @@
private AtomicInteger replicationProcessorCount;
private boolean asyncSerial;
- public CommandAwareRpcDispatcher()
- {
+ public CommandAwareRpcDispatcher() {
}
public CommandAwareRpcDispatcher(Channel channel, MessageListener l, MembershipListener l2, Object serverObj,
InvocationContextContainer container, InterceptorChain interceptorChain,
- ComponentRegistry componentRegistry)
- {
+ ComponentRegistry componentRegistry) {
super(channel, l, l2, serverObj);
this.invocationContextContainer = container;
this.componentRegistry = componentRegistry;
@@ -81,45 +87,35 @@
// in-process thread. Not async.
replicationProcessor = new WithinThreadExecutor();
asyncSerial = false;
- }
- else
- {
+ } else {
asyncSerial = true;
- if (replicationProcessor == null)
- {
+ if (replicationProcessor == null) {
replicationProcessorCount = new AtomicInteger(0);
replicationProcessor = BoundedExecutors.newFixedThreadPool(c.isUseReplQueue() ? 1 : c.getSerializationExecutorPoolSize(),
- new ThreadFactory()
- {
- public Thread newThread(Runnable r)
- {
- return new Thread(r, "AsyncReplicationProcessor-" + replicationProcessorCount.incrementAndGet());
- }
- }, c.getSerializationExecutorQueueSize()
+ new ThreadFactory() {
+ public Thread newThread(Runnable r) {
+ return new Thread(r, "AsyncReplicationProcessor-" + replicationProcessorCount.incrementAndGet());
+ }
+ }, c.getSerializationExecutorQueueSize()
);
}
}
}
@Override
- public void stop()
- {
+ public void stop() {
replicationProcessor.shutdownNow();
- try
- {
+ try {
replicationProcessor.awaitTermination(60, TimeUnit.SECONDS);
}
- catch (InterruptedException e)
- {
+ catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
super.stop();
}
- protected boolean isValid(Message req)
- {
- if (req == null || req.getLength() == 0)
- {
+ protected boolean isValid(Message req) {
+ if (req == null || req.getLength() == 0) {
log.error("message or message buffer is null");
return false;
}
@@ -128,14 +124,12 @@
}
/**
- * Similar to {@link #callRemoteMethods(java.util.Vector, org.jgroups.blocks.MethodCall, int, long, boolean, boolean, org.jgroups.blocks.RspFilter)} except that this version
- * is aware of {@link ReplicableCommand} objects.
+ * Similar to {@link #callRemoteMethods(java.util.Vector, org.jgroups.blocks.MethodCall, int, long, boolean, boolean,
+ * org.jgroups.blocks.RspFilter)} except that this version is aware of {@link ReplicableCommand} objects.
*/
public RspList invokeRemoteCommands(Vector<Address> dests, ReplicableCommand command, int mode, long timeout,
- boolean oob, RspFilter filter) throws NotSerializableException, ExecutionException, InterruptedException
- {
- if (dests != null && dests.isEmpty())
- {
+ boolean oob, RspFilter filter) throws NotSerializableException, ExecutionException, InterruptedException {
+ if (dests != null && dests.isEmpty()) {
// don't send if dest list is empty
if (trace) log.trace("Destination list is empty: no need to send message");
return new RspList();
@@ -147,13 +141,10 @@
ReplicationTask replicationTask = new ReplicationTask(command, oob, dests, mode, timeout, false, filter);
Future<RspList> response = replicationProcessor.submit(replicationTask);
- if (asyncSerial)
- {
+ if (asyncSerial) {
// don't care about the response. return.
return null;
- }
- else
- {
+ } else {
RspList retval = response.get();
if (retval.isEmpty() || containsOnlyNulls(retval))
return null;
@@ -162,10 +153,8 @@
}
}
- private boolean containsOnlyNulls(RspList l)
- {
- for (Rsp r : l.values())
- {
+ private boolean containsOnlyNulls(RspList l) {
+ for (Rsp r : l.values()) {
if (r.getValue() != null || !r.wasReceived() || r.wasSuspected()) return false;
}
return true;
@@ -175,43 +164,32 @@
* Message contains a Command. Execute it against *this* object and return result.
*/
@Override
- public Object handle(Message req)
- {
- if (isValid(req))
- {
- try
- {
+ public Object handle(Message req) {
+ if (isValid(req)) {
+ try {
return executeCommand((ReplicableCommand) req_marshaller.objectFromByteBuffer(req.getBuffer(), req.getOffset(), req.getLength()), req);
}
- catch (Throwable x)
- {
+ catch (Throwable x) {
if (trace) log.trace("Problems invoking command.", x);
return x;
}
- }
- else
- {
+ } else {
return null;
}
}
- protected Object executeCommand(ReplicableCommand cmd, Message req) throws Throwable
- {
+ protected Object executeCommand(ReplicableCommand cmd, Message req) throws Throwable {
if (cmd == null) throw new NullPointerException("Unable to execute a null command! Message was " + req);
if (trace) log.trace("Executing command: " + cmd + " [sender=" + req.getSrc() + "]");
- if (cmd instanceof VisitableCommand)
- {
+ if (cmd instanceof VisitableCommand) {
InvocationContext ctx = invocationContextContainer.get();
ctx.setOriginLocal(false);
- if (!componentRegistry.invocationsAllowed(false))
- {
+ if (!componentRegistry.invocationsAllowed(false)) {
return null;
}
return interceptorChain.invoke(ctx, (VisitableCommand) cmd);
- }
- else
- {
+ } else {
if (trace) log.trace("This is a non-visitable command - so performing directly and not via the invoker.");
// need to check cache status for all except buddy replication commands.
@@ -222,13 +200,11 @@
}
@Override
- public String toString()
- {
+ public String toString() {
return getClass().getSimpleName() + "[Outgoing marshaller: " + req_marshaller + "; incoming marshaller: " + rsp_marshaller + "]";
}
- private class ReplicationTask implements Callable<RspList>
- {
+ private class ReplicationTask implements Callable<RspList> {
private ReplicableCommand command;
private boolean oob;
private Vector<Address> dests;
@@ -237,8 +213,7 @@
private boolean anycasting;
private RspFilter filter;
- private ReplicationTask(ReplicableCommand command, boolean oob, Vector<Address> dests, int mode, long timeout, boolean anycasting, RspFilter filter)
- {
+ private ReplicationTask(ReplicableCommand command, boolean oob, Vector<Address> dests, int mode, long timeout, boolean anycasting, RspFilter filter) {
this.command = command;
this.oob = oob;
this.dests = dests;
@@ -248,15 +223,12 @@
this.filter = filter;
}
- public RspList call() throws Exception
- {
+ public RspList call() throws Exception {
Buffer buf;
- try
- {
+ try {
buf = req_marshaller.objectToBuffer(command);
}
- catch (Exception e)
- {
+ catch (Exception e) {
throw new RuntimeException("Failure to marshal argument(s)", e);
}
Modified: core/branches/flat/src/main/java/org/horizon/marshall/EntryData.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/marshall/EntryData.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/marshall/EntryData.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -31,82 +31,70 @@
* Serializable representation of the data of a node (FQN and attributes)
*
* @author Bela Ban
- *
* @since 1.0
*/
// TODO: 3.0.0: remove Externalizable and rely on the CacheMarshaller.
-public class EntryData<K, V> implements Externalizable, Map.Entry<K, V>
-{
+public class EntryData<K, V> implements Externalizable, Map.Entry<K, V> {
private K key;
private V value;
static final long serialVersionUID = -7571995794010294485L;
- public EntryData(K key, V value)
- {
+ public EntryData(K key, V value) {
this.key = key;
this.value = value;
}
- public K getKey()
- {
+ public K getKey() {
return key;
}
- public V getValue()
- {
+ public V getValue() {
return value;
}
// TODO: 3.0.0: Remove and replace with marshallNodeData/unmarshallNodeData methods in the CacheMarshaller so that we can use the same marshalling framework for Fqns.
- public void writeExternal(ObjectOutput out) throws IOException
- {
+ public void writeExternal(ObjectOutput out) throws IOException {
out.writeObject(key);
out.writeObject(value);
}
// TODO: 3.0.0: Remove in and replace with marshallNodeData/unmarshallNodeData methods in the CacheMarshaller so that we can use the same marshalling framework for Fqns.
@SuppressWarnings("unchecked")
- public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException
- {
+ public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
key = (K) in.readObject();
value = (V) in.readObject();
}
@Override
- public String toString()
- {
+ public String toString() {
return "{" + key + "=" + value + "}";
}
- private static boolean eq(Object a, Object b)
- {
+ private static boolean eq(Object a, Object b) {
return a == b || (a != null && a.equals(b));
}
@Override
- public boolean equals(Object o)
- {
+ public boolean equals(Object o) {
if (this == o) return true;
- if (! (o instanceof EntryData))
+ if (!(o instanceof EntryData))
return false;
- EntryData<?,?> other = (EntryData<?,?>)o;
+ EntryData<?, ?> other = (EntryData<?, ?>) o;
return eq(key, other.key) && eq(value, other.value);
}
@Override
- public int hashCode()
- {
+ public int hashCode() {
int result;
result = (key != null ? key.hashCode() : 0);
result = 31 * result + (value != null ? value.hashCode() : 0);
return result;
}
- public V setValue(V value)
- {
+ public V setValue(V value) {
throw new UnsupportedOperationException();
}
}
Modified: core/branches/flat/src/main/java/org/horizon/marshall/EntryDataExceptionMarker.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/marshall/EntryDataExceptionMarker.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/marshall/EntryDataExceptionMarker.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -26,36 +26,30 @@
import java.io.ObjectInput;
import java.io.ObjectOutput;
-public class EntryDataExceptionMarker implements Externalizable
-{
+public class EntryDataExceptionMarker implements Externalizable {
private static final long serialVersionUID = 240199474174502551L;
private Throwable cause;
private Object cacheNodeIdentity;
- public EntryDataExceptionMarker(Throwable t, Object node)
- {
+ public EntryDataExceptionMarker(Throwable t, Object node) {
cause = t;
cacheNodeIdentity = node;
}
- public Throwable getCause()
- {
+ public Throwable getCause() {
return cause;
}
- public Object getCacheNodeIdentity()
- {
+ public Object getCacheNodeIdentity() {
return cacheNodeIdentity;
}
- public void writeExternal(ObjectOutput out) throws IOException
- {
+ public void writeExternal(ObjectOutput out) throws IOException {
out.writeObject(cause);
out.writeObject(cacheNodeIdentity);
}
- public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException
- {
+ public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
cause = (Throwable) in.readObject();
cacheNodeIdentity = in.readObject();
}
Modified: core/branches/flat/src/main/java/org/horizon/marshall/EntryDataMarker.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/marshall/EntryDataMarker.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/marshall/EntryDataMarker.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -23,7 +23,6 @@
import java.io.Serializable;
-public class EntryDataMarker implements Serializable
-{
+public class EntryDataMarker implements Serializable {
private static final long serialVersionUID = 4851793846346021014L;
}
Modified: core/branches/flat/src/main/java/org/horizon/marshall/MarshalledValue.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/marshall/MarshalledValue.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/marshall/MarshalledValue.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -24,39 +24,28 @@
import org.horizon.CacheException;
import org.jboss.util.stream.MarshalledValueInputStream;
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.Externalizable;
-import java.io.IOException;
-import java.io.NotSerializableException;
-import java.io.ObjectInput;
-import java.io.ObjectInputStream;
-import java.io.ObjectOutput;
-import java.io.ObjectOutputStream;
-import java.io.Serializable;
+import java.io.*;
import java.util.Arrays;
/**
* Wrapper that wraps cached data, providing lazy deserialization using the calling thread's context class loader.
* <p/>
- * The {@link org.horizon.interceptors.MarshalledValueInterceptor} handles transparent
- * wrapping/unwrapping of cached data.
+ * The {@link org.horizon.interceptors.MarshalledValueInterceptor} handles transparent wrapping/unwrapping of cached
+ * data.
* <p/>
*
* @author Manik Surtani (<a href="mailto:manik at jboss.org">manik at jboss.org</a>)
* @see org.horizon.interceptors.MarshalledValueInterceptor
* @since 1.0
*/
-public class MarshalledValue implements Externalizable
-{
+public class MarshalledValue implements Externalizable {
protected Object instance;
protected byte[] raw;
private int cachedHashCode = 0;
// by default equals() will test on the istance rather than the byte array if conversion is required.
private transient boolean equalityPreferenceForInstance = true;
- public MarshalledValue(Object instance) throws NotSerializableException
- {
+ public MarshalledValue(Object instance) throws NotSerializableException {
if (instance == null) throw new NullPointerException("Null values cannot be wrapped as MarshalledValues!");
if (instance instanceof Serializable)
@@ -65,22 +54,17 @@
throw new NotSerializableException("Marshalled values can only wrap Objects that are serializable! Instance of " + instance.getClass() + " won't Serialize.");
}
- public MarshalledValue()
- {
+ public MarshalledValue() {
// empty ctor for serialization
}
- public void setEqualityPreferenceForInstance(boolean equalityPreferenceForInstance)
- {
+ public void setEqualityPreferenceForInstance(boolean equalityPreferenceForInstance) {
this.equalityPreferenceForInstance = equalityPreferenceForInstance;
}
- public synchronized void serialize()
- {
- if (raw == null)
- {
- try
- {
+ public synchronized void serialize() {
+ if (raw == null) {
+ try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(instance);
@@ -91,19 +75,15 @@
// instance = null;
raw = baos.toByteArray();
}
- catch (Exception e)
- {
+ catch (Exception e) {
throw new CacheException("Unable to marshall value " + instance, e);
}
}
}
- public synchronized void deserialize()
- {
- if (instance == null)
- {
- try
- {
+ public synchronized void deserialize() {
+ if (instance == null) {
+ try {
ByteArrayInputStream bais = new ByteArrayInputStream(raw);
// use a MarshalledValueInputStream since it needs to be aware of any context class loaders on the current thread.
ObjectInputStream ois = new MarshalledValueInputStream(bais);
@@ -112,8 +92,7 @@
bais.close();
// raw = null;
}
- catch (Exception e)
- {
+ catch (Exception e) {
throw new CacheException("Unable to unmarshall value", e);
}
}
@@ -127,44 +106,38 @@
* Either way, a call to compact() will ensure that only one representation is held.
* <p/>
*
- * @param preferSerializedRepresentation if true and both representations exist, the serialized representation is favoured. If false, the deserialized representation is preferred.
- * @param force ensures the preferred representation is maintained and the other released, even if this means serializing or deserializing.
+ * @param preferSerializedRepresentation if true and both representations exist, the serialized representation is
+ * favoured. If false, the deserialized representation is preferred.
+ * @param force ensures the preferred representation is maintained and the other released,
+ * even if this means serializing or deserializing.
*/
- public void compact(boolean preferSerializedRepresentation, boolean force)
- {
+ public void compact(boolean preferSerializedRepresentation, boolean force) {
// reset the equalityPreference
equalityPreferenceForInstance = true;
- if (force)
- {
+ if (force) {
if (preferSerializedRepresentation && raw == null) serialize();
else if (!preferSerializedRepresentation && instance == null) deserialize();
}
- if (instance != null && raw != null)
- {
+ if (instance != null && raw != null) {
// need to lose one representation!
- if (preferSerializedRepresentation)
- {
+ if (preferSerializedRepresentation) {
instance = null;
- }
- else
- {
+ } else {
raw = null;
}
}
}
- public void writeExternal(ObjectOutput out) throws IOException
- {
+ public void writeExternal(ObjectOutput out) throws IOException {
if (raw == null) serialize();
out.writeInt(raw.length);
out.write(raw);
out.writeInt(hashCode());
}
- public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException
- {
+ public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
int size = in.readInt();
raw = new byte[size];
cachedHashCode = 0;
@@ -172,15 +145,13 @@
cachedHashCode = in.readInt();
}
- public Object get() throws IOException, ClassNotFoundException
- {
+ public Object get() throws IOException, ClassNotFoundException {
if (instance == null) deserialize();
return instance;
}
@Override
- public boolean equals(Object o)
- {
+ public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
@@ -191,14 +162,11 @@
if (instance != null && that.instance != null) return instance.equals(that.instance);
// if conversion of one representation to the other is necessary, then see which we prefer converting.
- if (equalityPreferenceForInstance)
- {
+ if (equalityPreferenceForInstance) {
if (instance == null) deserialize();
if (that.instance == null) that.deserialize();
return instance.equals(that.instance);
- }
- else
- {
+ } else {
if (raw == null) serialize();
if (that.raw == null) that.serialize();
return Arrays.equals(raw, that.raw);
@@ -206,10 +174,8 @@
}
@Override
- public int hashCode()
- {
- if (cachedHashCode == 0)
- {
+ public int hashCode() {
+ if (cachedHashCode == 0) {
// always calculate the hashcode based on the instance since this is where we're getting the equals()
if (instance == null) deserialize();
cachedHashCode = instance.hashCode();
@@ -222,8 +188,7 @@
}
@Override
- public String toString()
- {
+ public String toString() {
return "MarshalledValue(cachedHashCode=" + cachedHashCode + "; serialized=" + (raw != null) + ")";
}
}
Modified: core/branches/flat/src/main/java/org/horizon/marshall/MarshalledValueHelper.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/marshall/MarshalledValueHelper.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/marshall/MarshalledValueHelper.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -26,7 +26,8 @@
import org.jgroups.Address;
/**
- * Common functionality used by the {@link org.horizon.interceptors.MarshalledValueInterceptor} and the {@link MarshalledValueMap}.
+ * Common functionality used by the {@link org.horizon.interceptors.MarshalledValueInterceptor} and the {@link
+ * MarshalledValueMap}.
*
* @author Manik Surtani (<a href="mailto:manik at jboss.org">manik at jboss.org</a>)
* @see MarshalledValue
@@ -34,16 +35,14 @@
* @see MarshalledValueMap
* @since 1.0
*/
-public class MarshalledValueHelper
-{
+public class MarshalledValueHelper {
/**
* Tests whether the type should be excluded from MarshalledValue wrapping.
*
* @param type type to test. Should not be null.
* @return true if it should be excluded from MarshalledValue wrapping.
*/
- public static boolean isTypeExcluded(Class type)
- {
+ public static boolean isTypeExcluded(Class type) {
return type.equals(String.class) || type.isPrimitive() ||
type.equals(Void.class) || type.equals(Boolean.class) || type.equals(Character.class) ||
type.equals(Byte.class) || type.equals(Short.class) || type.equals(Integer.class) ||
Modified: core/branches/flat/src/main/java/org/horizon/marshall/MarshalledValueMap.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/marshall/MarshalledValueMap.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/marshall/MarshalledValueMap.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -35,8 +35,8 @@
import java.util.Set;
/**
- * A Map that is able to wrap/unwrap MarshalledValues in keys or values. Note that calling keySet(), entrySet() or values()
- * could be expensive if this map is large!!
+ * A Map that is able to wrap/unwrap MarshalledValues in keys or values. Note that calling keySet(), entrySet() or
+ * values() could be expensive if this map is large!!
* <p/>
* Also note that this is an immutable Map.
* <p/>
@@ -46,136 +46,110 @@
* @since 1.0
*/
@Immutable
-public class MarshalledValueMap implements Map, Externalizable
-{
+public class MarshalledValueMap implements Map, Externalizable {
Map delegate;
Map<Object, Object> unmarshalled;
- public MarshalledValueMap()
- {
+ public MarshalledValueMap() {
// for externalization
}
- public MarshalledValueMap(Map delegate)
- {
+ public MarshalledValueMap(Map delegate) {
this.delegate = delegate;
}
@SuppressWarnings("unchecked")
- protected synchronized Map getUnmarshalledMap()
- {
+ protected synchronized Map getUnmarshalledMap() {
if (unmarshalled == null) unmarshalled = unmarshalledMap(delegate.entrySet());
return unmarshalled;
}
- public int size()
- {
+ public int size() {
return delegate.size();
}
- public boolean isEmpty()
- {
+ public boolean isEmpty() {
return delegate.isEmpty();
}
- public boolean containsKey(Object key)
- {
+ public boolean containsKey(Object key) {
return getUnmarshalledMap().containsKey(key);
}
- public boolean containsValue(Object value)
- {
+ public boolean containsValue(Object value) {
return getUnmarshalledMap().containsValue(value);
}
- public Object get(Object key)
- {
+ public Object get(Object key) {
return getUnmarshalledMap().get(key);
}
- public Object put(Object key, Object value)
- {
+ public Object put(Object key, Object value) {
throw new UnsupportedOperationException("This is an immutable map!");
}
- public Object remove(Object key)
- {
+ public Object remove(Object key) {
throw new UnsupportedOperationException("This is an immutable map!");
}
- public void putAll(Map t)
- {
+ public void putAll(Map t) {
throw new UnsupportedOperationException("This is an immutable map!");
}
- public void clear()
- {
+ public void clear() {
throw new UnsupportedOperationException("This is an immutable map!");
}
- public Set keySet()
- {
+ public Set keySet() {
return getUnmarshalledMap().keySet();
}
- public Collection values()
- {
+ public Collection values() {
return getUnmarshalledMap().values();
}
- public Set entrySet()
- {
+ public Set entrySet() {
return getUnmarshalledMap().entrySet();
}
@SuppressWarnings("unchecked")
- protected Map unmarshalledMap(Set entries)
- {
+ protected Map unmarshalledMap(Set entries) {
if (entries == null || entries.isEmpty()) return Collections.emptyMap();
Map map = new HashMap(entries.size());
- for (Object e : entries)
- {
+ for (Object e : entries) {
Map.Entry entry = (Map.Entry) e;
map.put(getUnmarshalledValue(entry.getKey()), getUnmarshalledValue(entry.getValue()));
}
return map;
}
- private Object getUnmarshalledValue(Object o)
- {
- try
- {
+ private Object getUnmarshalledValue(Object o) {
+ try {
return o instanceof MarshalledValue ? ((MarshalledValue) o).get() : o;
}
- catch (Exception e)
- {
+ catch (Exception e) {
throw new CacheException("Unable to unmarshall value", e);
}
}
@Override
- public boolean equals(Object other)
- {
- if (other instanceof Map)
- {
+ public boolean equals(Object other) {
+ if (other instanceof Map) {
return getUnmarshalledMap().equals(other);
}
return false;
}
@Override
- public int hashCode()
- {
+ public int hashCode() {
return getUnmarshalledMap().hashCode();
}
- public void writeExternal(ObjectOutput out) throws IOException
- {
+ public void writeExternal(ObjectOutput out) throws IOException {
out.writeObject(delegate);
}
- public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException
- {
+ public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
delegate = (Map) in.readObject();
}
}
Modified: core/branches/flat/src/main/java/org/horizon/marshall/Marshaller.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/marshall/Marshaller.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/marshall/Marshaller.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -31,29 +31,30 @@
/**
* A marshaller is a class that is able to marshall and unmarshall objects efficiently.
* <p/>
- * The reason why this is implemented specially in JBoss Cache rather than resorting to
- * Java serialization or even the more efficient JBoss serialization is that a lot of efficiency
- * can be gained when a majority of the serialization that occurs has to do with a small set
- * of known types such as {@link org.horizon.transaction.GlobalTransaction} or {@link org.horizon.commands.ReplicableCommand},
- * and class type information can be replaced with simple magic numbers.
+ * The reason why this is implemented specially in JBoss Cache rather than resorting to Java serialization or even the
+ * more efficient JBoss serialization is that a lot of efficiency can be gained when a majority of the serialization
+ * that occurs has to do with a small set of known types such as {@link org.horizon.transaction.GlobalTransaction} or
+ * {@link org.horizon.commands.ReplicableCommand}, and class type information can be replaced with simple magic
+ * numbers.
* <p/>
* Unknown types (typically user data) falls back to JBoss serialization.
* <p/>
- * In addition, using a marshaller allows adding additional data to the byte stream, such as context
- * class loader information on which class loader to use to deserialize the object stream, or versioning
- * information to allow streams to interoperate between different versions of JBoss Cache (see {@link VersionAwareMarshaller}
+ * In addition, using a marshaller allows adding additional data to the byte stream, such as context class loader
+ * information on which class loader to use to deserialize the object stream, or versioning information to allow streams
+ * to interoperate between different versions of JBoss Cache (see {@link VersionAwareMarshaller}
* <p/>
- * This interface implements the JGroups building-block interface {@link org.jgroups.blocks.RpcDispatcher.Marshaller} which
- * is used to marshall {@link org.horizon.commands.ReplicableCommand}s, their parameters and their response values.
+ * This interface implements the JGroups building-block interface {@link org.jgroups.blocks.RpcDispatcher.Marshaller}
+ * which is used to marshall {@link org.horizon.commands.ReplicableCommand}s, their parameters and their response
+ * values.
* <p/>
- * The interface is also used by the {@link org.horizon.loader.CacheLoader} framework to efficiently serialize data to be persisted, as well as
- * the {@link org.horizon.statetransfer.StateTransferManager} when serializing the cache for transferring state en-masse.
+ * The interface is also used by the {@link org.horizon.loader.CacheLoader} framework to efficiently serialize data to
+ * be persisted, as well as the {@link org.horizon.statetransfer.StateTransferManager} when serializing the cache for
+ * transferring state en-masse.
*
* @author <a href="mailto://manik@jboss.org">Manik Surtani</a>
* @since 1.0
*/
-public interface Marshaller extends RpcDispatcher.Marshaller2
-{
+public interface Marshaller extends RpcDispatcher.Marshaller2 {
/**
* Marshalls an object to a given {@link java.io.ObjectOutputStream}
*
@@ -78,8 +79,8 @@
Object objectFromStream(InputStream is) throws Exception;
/**
- * A specialized form of {@link org.jgroups.blocks.RpcDispatcher.Marshaller2#objectToBuffer(Object)} that returns an instance
- * of {@link org.horizon.io.ByteBuffer} instead of {@link org.jgroups.util.Buffer}.
+ * A specialized form of {@link org.jgroups.blocks.RpcDispatcher.Marshaller2#objectToBuffer(Object)} that returns an
+ * instance of {@link org.horizon.io.ByteBuffer} instead of {@link org.jgroups.util.Buffer}.
*
* @param o object to marshall
* @return a ByteBuffer
Modified: core/branches/flat/src/main/java/org/horizon/marshall/NodeData.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/marshall/NodeData.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/marshall/NodeData.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -34,28 +34,23 @@
* Serializable representation of the data of a node (FQN and attributes)
*
* @author Bela Ban
- *
* @since 1.0
*/
// TODO: 3.0.0: remove Externalizable and rely on the CacheMarshaller.
-public class NodeData<K, V> implements Externalizable
-{
+public class NodeData<K, V> implements Externalizable {
private Fqn fqn = null;
private Map<K, V> attrs = null;
static final long serialVersionUID = -7571995794010294485L;
- public NodeData()
- {
+ public NodeData() {
}
- public NodeData(Fqn fqn)
- {
+ public NodeData(Fqn fqn) {
this.fqn = fqn;
}
- public NodeData(Fqn fqn, Map<K, V> attrs, boolean mapSafe)
- {
+ public NodeData(Fqn fqn, Map<K, V> attrs, boolean mapSafe) {
this.fqn = fqn;
if (mapSafe || attrs == null)
this.attrs = attrs;
@@ -63,67 +58,54 @@
this.attrs = new HashMap<K, V>(attrs);
}
- public NodeData(String fqn, Map<K, V> attrs, boolean mapSafe)
- {
+ public NodeData(String fqn, Map<K, V> attrs, boolean mapSafe) {
this(Fqn.fromString(fqn), attrs, mapSafe);
}
- public Map<K, V> getAttributes()
- {
+ public Map<K, V> getAttributes() {
return attrs;
}
- public Fqn getFqn()
- {
+ public Fqn getFqn() {
return fqn;
}
- public boolean isMarker()
- {
+ public boolean isMarker() {
return false;
}
- public boolean isExceptionMarker()
- {
+ public boolean isExceptionMarker() {
return false;
}
// TODO: 3.0.0: Remove and replace with marshallNodeData/unmarshallNodeData methods in the CacheMarshaller so that we can use the same marshalling framework for Fqns.
- public void writeExternal(ObjectOutput out) throws IOException
- {
+ public void writeExternal(ObjectOutput out) throws IOException {
out.writeObject(fqn);
- if (attrs != null)
- {
+ if (attrs != null) {
out.writeBoolean(true);
out.writeObject(attrs);
- }
- else
- {
+ } else {
out.writeBoolean(false);
}
}
// TODO: 3.0.0: Remove in and replace with marshallNodeData/unmarshallNodeData methods in the CacheMarshaller so that we can use the same marshalling framework for Fqns.
@SuppressWarnings("unchecked")
- public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException
- {
+ public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
fqn = (Fqn) in.readObject();
- if (in.readBoolean())
- {
+ if (in.readBoolean()) {
attrs = (Map<K, V>) in.readObject();
}
}
@Override
- public String toString()
- {
+ public String toString() {
return "NodeData {fqn: " + fqn + ", attrs=" + attrs + "}";
}
@Override
- public boolean equals(Object o)
- {
+ public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
@@ -136,8 +118,7 @@
}
@Override
- public int hashCode()
- {
+ public int hashCode() {
int result;
result = (fqn != null ? fqn.hashCode() : 0);
result = 31 * result + (attrs != null ? attrs.hashCode() : 0);
Modified: core/branches/flat/src/main/java/org/horizon/marshall/NodeDataExceptionMarker.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/marshall/NodeDataExceptionMarker.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/marshall/NodeDataExceptionMarker.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -21,65 +21,54 @@
*/
package org.horizon.marshall;
-import org.horizon.marshall.NodeData;
-
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
-public class NodeDataExceptionMarker extends NodeData
-{
+public class NodeDataExceptionMarker extends NodeData {
private static final long serialVersionUID = 240199474174502551L;
private Throwable cause;
private Object cacheNodeIdentity;
- public NodeDataExceptionMarker()
- {
+ public NodeDataExceptionMarker() {
super();
}
- public NodeDataExceptionMarker(Throwable t, Object node)
- {
+ public NodeDataExceptionMarker(Throwable t, Object node) {
cause = t;
cacheNodeIdentity = node;
}
- public Throwable getCause()
- {
+ public Throwable getCause() {
return cause;
}
- public Object getCacheNodeIdentity()
- {
+ public Object getCacheNodeIdentity() {
return cacheNodeIdentity;
}
@Override
- public boolean isExceptionMarker()
- {
+ public boolean isExceptionMarker() {
return true;
}
@Override
- public void writeExternal(ObjectOutput out) throws IOException
- {
+ public void writeExternal(ObjectOutput out) throws IOException {
super.writeExternal(out);
out.writeObject(cause);
out.writeObject(cacheNodeIdentity);
}
@Override
- public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException
- {
+ public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
super.readExternal(in);
cause = (Throwable) in.readObject();
cacheNodeIdentity = in.readObject();
}
@Override
- public String toString()
- {
+ public String toString() {
return "NodeDataExceptionMarker";
}
}
Modified: core/branches/flat/src/main/java/org/horizon/marshall/NodeDataMarker.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/marshall/NodeDataMarker.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/marshall/NodeDataMarker.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -21,22 +21,17 @@
*/
package org.horizon.marshall;
-import org.horizon.marshall.NodeData;
+public class NodeDataMarker extends NodeData {
-public class NodeDataMarker extends NodeData
-{
-
private static final long serialVersionUID = 4851793846346021014L;
@Override
- public boolean isMarker()
- {
+ public boolean isMarker() {
return true;
}
@Override
- public String toString()
- {
+ public String toString() {
return "NodeDataMarker";
}
}
Modified: core/branches/flat/src/main/java/org/horizon/marshall/UnmarshalledReferences.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/marshall/UnmarshalledReferences.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/marshall/UnmarshalledReferences.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -31,8 +31,7 @@
* @author <a href="mailto:manik at jboss.org">Manik Surtani (manik at jboss.org)</a>
* @since 1.0
*/
-public class UnmarshalledReferences
-{
+public class UnmarshalledReferences {
private final ArrayList<Object> referencedObjects = new ArrayList<Object>();
/**
@@ -41,8 +40,7 @@
* @param ref reference
* @return object
*/
- public Object getReferencedObject(int ref)
- {
+ public Object getReferencedObject(int ref) {
if (ref >= referencedObjects.size())
throw new CacheException("Attempting to look up a ref that hasn't been inserted yet");
return referencedObjects.get(ref);
@@ -54,17 +52,13 @@
* @param ref reference id
* @param o object
*/
- public void putReferencedObject(int ref, Object o)
- {
+ public void putReferencedObject(int ref, Object o) {
int sz = referencedObjects.size();
// if we are not adding the object to the end of the list, make sure we use a specific position
- if (ref < sz)
- {
+ if (ref < sz) {
referencedObjects.set(ref, o);
return;
- }
- else if (ref > sz)
- {
+ } else if (ref > sz) {
// if we are adding the reference to a position beyond the end of the list, make sure we expand the list first.
// this can happen, weirdly enough, since marshallObject() can be called recursively, such as from marshallFqn().
for (int i = sz; i < ref; i++) referencedObjects.add(null);
Modified: core/branches/flat/src/main/java/org/horizon/marshall/VersionAwareMarshaller.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/marshall/VersionAwareMarshaller.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/marshall/VersionAwareMarshaller.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -23,11 +23,11 @@
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
+import org.horizon.commands.CommandsFactory;
+import org.horizon.config.Configuration;
+import org.horizon.factories.annotations.Inject;
import org.horizon.io.ByteBuffer;
import org.horizon.io.ExposedByteArrayOutputStream;
-import org.horizon.factories.annotations.Inject;
-import org.horizon.config.Configuration;
-import org.horizon.commands.CommandsFactory;
import org.jboss.util.stream.MarshalledValueInputStream;
import java.io.ByteArrayInputStream;
@@ -36,17 +36,15 @@
import java.io.ObjectOutputStream;
/**
- * A delegate to various other marshallers like {@link CacheMarshallerStarobrno}.
- * This delegating marshaller adds versioning information to the stream when marshalling objects and
- * is able to pick the appropriate marshaller to delegate to based on the versioning information when
- * unmarshalling objects.
+ * A delegate to various other marshallers like {@link CacheMarshallerStarobrno}. This delegating marshaller adds
+ * versioning information to the stream when marshalling objects and is able to pick the appropriate marshaller to
+ * delegate to based on the versioning information when unmarshalling objects.
*
* @author <a href="mailto:manik at jboss.org">Manik Surtani (manik at jboss.org)</a>
* @author <a href="mailto:galder.zamarreno at jboss.com">Galder Zamarreno</a>
* @since 1.0
*/
-public class VersionAwareMarshaller implements Marshaller
-{
+public class VersionAwareMarshaller implements Marshaller {
private static final Log log = LogFactory.getLog(VersionAwareMarshaller.class);
private boolean trace = log.isTraceEnabled();
@@ -59,19 +57,16 @@
private Configuration configuration;
@Inject
- public void init(ClassLoader loader, Configuration configuration, CommandsFactory factory)
- {
+ public void init(ClassLoader loader, Configuration configuration, CommandsFactory factory) {
defaultMarshaller = new CacheMarshallerStarobrno();
defaultMarshaller.init(configuration, loader, factory);
}
- protected int getCustomMarshallerVersionInt()
- {
+ protected int getCustomMarshallerVersionInt() {
return CUSTOM_MARSHALLER;
}
- public ByteBuffer objectToBuffer(Object obj) throws Exception
- {
+ public ByteBuffer objectToBuffer(Object obj) throws Exception {
ExposedByteArrayOutputStream baos = new ExposedByteArrayOutputStream(128);
ObjectOutputStream out = new ObjectOutputStream(baos);
@@ -86,70 +81,58 @@
return new ByteBuffer(baos.getRawBuffer(), 0, baos.size());
}
- public Object objectFromByteBuffer(byte[] bytes, int offset, int len) throws Exception
- {
+ public Object objectFromByteBuffer(byte[] bytes, int offset, int len) throws Exception {
int versionId;
ObjectInputStream in = new MarshalledValueInputStream(new ByteArrayInputStream(bytes, offset, len));
- try
- {
+ try {
versionId = in.readShort();
if (trace) log.trace("Read version " + versionId);
}
- catch (Exception e)
- {
+ catch (Exception e) {
log.error("Unable to read version id from first two bytes of stream, barfing.");
throw e;
}
return defaultMarshaller.objectFromObjectStream(in);
}
- public Object objectFromStream(InputStream is) throws Exception
- {
+ public Object objectFromStream(InputStream is) throws Exception {
short versionId;
ObjectInputStream in = new MarshalledValueInputStream(is);
- try
- {
+ try {
versionId = in.readShort();
if (trace) log.trace("Read version " + versionId);
}
- catch (Exception e)
- {
+ catch (Exception e) {
log.error("Unable to read version id from first two bytes of stream, barfing.");
throw e;
}
return defaultMarshaller.objectFromObjectStream(in);
}
- public void objectToObjectStream(Object obj, ObjectOutputStream out) throws Exception
- {
+ public void objectToObjectStream(Object obj, ObjectOutputStream out) throws Exception {
out.writeShort(VERSION_400);
if (trace) log.trace("Wrote version " + VERSION_400);
defaultMarshaller.objectToObjectStream(obj, out);
}
- public Object objectFromObjectStream(ObjectInputStream in) throws Exception
- {
+ public Object objectFromObjectStream(ObjectInputStream in) throws Exception {
int versionId;
- try
- {
+ try {
versionId = in.readShort();
if (trace) log.trace("Read version " + versionId);
}
- catch (Exception e)
- {
+ catch (Exception e) {
log.error("Unable to read version id from first two bytes of stream, barfing.");
throw e;
}
return defaultMarshaller.objectFromObjectStream(in);
}
- public byte[] objectToByteBuffer(Object obj) throws Exception
- {
+ public byte[] objectToByteBuffer(Object obj) throws Exception {
return defaultMarshaller.objectToByteBuffer(obj);
}
- public Object objectFromByteBuffer(byte[] buf) throws Exception
- {
+ public Object objectFromByteBuffer(byte[] buf) throws Exception {
return defaultMarshaller.objectFromByteBuffer(buf);
}
}
\ No newline at end of file
Modified: core/branches/flat/src/main/java/org/horizon/notifications/EventLog.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/notifications/EventLog.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/notifications/EventLog.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -1,16 +1,6 @@
package org.horizon.notifications;
-import org.horizon.notifications.annotation.CacheEntryActivated;
-import org.horizon.notifications.annotation.CacheEntryCreated;
-import org.horizon.notifications.annotation.CacheEntryEvicted;
-import org.horizon.notifications.annotation.CacheEntryInvalidated;
-import org.horizon.notifications.annotation.CacheEntryModified;
-import org.horizon.notifications.annotation.CacheEntryPassivated;
-import org.horizon.notifications.annotation.CacheEntryRemoved;
-import org.horizon.notifications.annotation.CacheEntryVisited;
-import org.horizon.notifications.annotation.CacheListener;
-import org.horizon.notifications.annotation.TransactionCompleted;
-import org.horizon.notifications.annotation.TransactionRegistered;
+import org.horizon.notifications.annotation.*;
import org.horizon.notifications.event.Event;
import org.horizon.notifications.event.EventImpl;
@@ -19,8 +9,7 @@
@CacheListener
-public class EventLog
-{
+public class EventLog {
public final List<Event> events = new ArrayList<Event>();
@CacheEntryCreated
@@ -33,24 +22,21 @@
@CacheEntryPassivated
@CacheEntryActivated
@CacheEntryInvalidated
- public void callback(Event e)
- {
+ public void callback(Event e) {
events.add(e);
}
- public String toString()
- {
+ public String toString() {
return "EventLog{" +
"events=" + events +
'}';
}
/**
- * Done when we don't have a Transaction reference to compare with, e.g., when using implicit transactions in
- * opt locking.
+ * Done when we don't have a Transaction reference to compare with, e.g., when using implicit transactions in opt
+ * locking.
*/
- public void scrubImplicitTransactions()
- {
+ public void scrubImplicitTransactions() {
for (Event e : events) ((EventImpl) e).setTransaction(null);
}
}
\ No newline at end of file
Modified: core/branches/flat/src/main/java/org/horizon/notifications/IncorrectCacheListenerException.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/notifications/IncorrectCacheListenerException.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/notifications/IncorrectCacheListenerException.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -24,18 +24,17 @@
import org.horizon.CacheException;
/**
- * Thrown when an incorrectly annotated class is added as a cache listener using the {@link org.horizon.Cache#addCacheListener(Object)} API.
+ * Thrown when an incorrectly annotated class is added as a cache listener using the {@link
+ * org.horizon.Cache#addCacheListener(Object)} API.
*
* @author <a href="mailto:manik at jboss.org">Manik Surtani</a>
* @since 1.0
*/
-public class IncorrectCacheListenerException extends CacheException
-{
+public class IncorrectCacheListenerException extends CacheException {
private static final long serialVersionUID = 3847404572671886703L;
- public IncorrectCacheListenerException(String s)
- {
+ public IncorrectCacheListenerException(String s) {
super(s);
}
}
Modified: core/branches/flat/src/main/java/org/horizon/notifications/Notifier.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/notifications/Notifier.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/notifications/Notifier.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -33,8 +33,7 @@
* @author Mircea.Markus at jboss.com
* @since 1.0
*/
-public interface Notifier
-{
+public interface Notifier {
/**
* Notifies all registered listeners of a nodeCreated event.
*/
Modified: core/branches/flat/src/main/java/org/horizon/notifications/NotifierImpl.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/notifications/NotifierImpl.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/notifications/NotifierImpl.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -66,8 +66,7 @@
*/
@NonVolatile
@Scope(Scopes.NAMED_CACHE)
-public class NotifierImpl implements Notifier
-{
+public class NotifierImpl implements Notifier {
private static final Log log = LogFactory.getLog(NotifierImpl.class);
private static final Class emptyMap = Collections.emptyMap().getClass();
@@ -111,8 +110,7 @@
private ExecutorService asyncProcessor;
private static final AtomicInteger asyncNotifierThreadNumber = new AtomicInteger(0);
- public NotifierImpl()
- {
+ public NotifierImpl() {
listenersMap.put(CacheStarted.class, cacheStartedListeners);
listenersMap.put(CacheStopped.class, cacheStoppedListeners);
listenersMap.put(CacheEntryCreated.class, nodeCreatedListeners);
@@ -130,47 +128,37 @@
}
@Inject
- void injectDependencies(CacheSPI cache, Configuration config)
- {
+ void injectDependencies(CacheSPI cache, Configuration config) {
this.cache = cache;
this.config = config;
}
@Stop
- void stop()
- {
+ void stop() {
syncProcessor.shutdownNow();
asyncProcessor.shutdownNow();
}
@Destroy
- void destroy()
- {
+ void destroy() {
removeAllCacheListeners();
}
@Start
- void start()
- {
+ void start() {
useMarshalledValueMaps = config.isUseLazyDeserialization();
syncProcessor = new WithinThreadExecutor();
// first try and use an injected executor for async listeners
- if ((asyncProcessor = config.getRuntimeConfig().getAsyncCacheListenerExecutor()) == null)
- {
+ if ((asyncProcessor = config.getRuntimeConfig().getAsyncCacheListenerExecutor()) == null) {
// create one if needed
- if (config.getListenerAsyncPoolSize() > 0)
- {
- asyncProcessor = BoundedExecutors.newFixedThreadPool(config.getListenerAsyncPoolSize(), new ThreadFactory()
- {
- public Thread newThread(Runnable r)
- {
+ if (config.getListenerAsyncPoolSize() > 0) {
+ asyncProcessor = BoundedExecutors.newFixedThreadPool(config.getListenerAsyncPoolSize(), new ThreadFactory() {
+ public Thread newThread(Runnable r) {
return new Thread(r, "AsyncNotifier-" + asyncNotifierThreadNumber.getAndIncrement());
}
}, config.getListenerAsyncQueueSize());
- }
- else
- {
+ } else {
// use the same sync executor
asyncProcessor = syncProcessor;
}
@@ -178,25 +166,21 @@
}
/**
- * Loops through all valid methods on the object passed in, and caches the relevant methods as {@link NotifierImpl.ListenerInvocation}
- * for invocation by reflection.
+ * Loops through all valid methods on the object passed in, and caches the relevant methods as {@link
+ * NotifierImpl.ListenerInvocation} for invocation by reflection.
*
* @param listener object to be considered as a listener.
*/
@SuppressWarnings("unchecked")
- private void validateAndAddListenerInvocation(Object listener)
- {
+ private void validateAndAddListenerInvocation(Object listener) {
boolean sync = testListenerClassValidity(listener.getClass());
boolean foundMethods = false;
// now try all methods on the listener for anything that we like. Note that only PUBLIC methods are scanned.
- for (Method m : listener.getClass().getMethods())
- {
+ for (Method m : listener.getClass().getMethods()) {
// loop through all valid method annotations
- for (int i = 0; i < allowedMethodAnnotations.length; i++)
- {
- if (m.isAnnotationPresent(allowedMethodAnnotations[i]))
- {
+ for (int i = 0; i < allowedMethodAnnotations.length; i++) {
+ if (m.isAnnotationPresent(allowedMethodAnnotations[i])) {
testListenerMethodValidity(m, parameterTypes[i], allowedMethodAnnotations[i].getName());
addListenerInvocation(allowedMethodAnnotations[i], new ListenerInvocation(listener, m, sync));
foundMethods = true;
@@ -209,14 +193,13 @@
}
/**
- * Tests if a class is properly annotated as a CacheListener and returns whether callbacks on this class should be invoked
- * synchronously or asynchronously.
+ * Tests if a class is properly annotated as a CacheListener and returns whether callbacks on this class should be
+ * invoked synchronously or asynchronously.
*
* @param listenerClass class to inspect
* @return true if callbacks on this class should use the syncProcessor; false if it should use the asyncProcessor.
*/
- private static boolean testListenerClassValidity(Class<?> listenerClass)
- {
+ private static boolean testListenerClassValidity(Class<?> listenerClass) {
CacheListener cl = listenerClass.getAnnotation(CacheListener.class);
if (cl == null)
throw new IncorrectCacheListenerException("Cache listener class MUST be annotated with org.horizon.notifications.annotation.CacheListener");
@@ -226,37 +209,31 @@
}
- private static void testListenerMethodValidity(Method m, Class allowedParameter, String annotationName)
- {
+ private static void testListenerMethodValidity(Method m, Class allowedParameter, String annotationName) {
if (m.getParameterTypes().length != 1 || !m.getParameterTypes()[0].isAssignableFrom(allowedParameter))
throw new IncorrectCacheListenerException("Methods annotated with " + annotationName + " must accept exactly one parameter, of assignable from type " + allowedParameter.getName());
if (!m.getReturnType().equals(void.class))
throw new IncorrectCacheListenerException("Methods annotated with " + annotationName + " should have a return type of void.");
}
- private void addListenerInvocation(Class annotation, ListenerInvocation li)
- {
+ private void addListenerInvocation(Class annotation, ListenerInvocation li) {
List<ListenerInvocation> result = getListenerCollectionForAnnotation(annotation);
result.add(li);
}
- public void addCacheListener(Object listener)
- {
+ public void addCacheListener(Object listener) {
validateAndAddListenerInvocation(listener);
}
- public void removeCacheListener(Object listener)
- {
+ public void removeCacheListener(Object listener) {
for (Class annotation : allowedMethodAnnotations) removeListenerInvocation(annotation, listener);
}
- private void removeListenerInvocation(Class annotation, Object listener)
- {
+ private void removeListenerInvocation(Class annotation, Object listener) {
if (listener == null) return;
List<ListenerInvocation> l = getListenerCollectionForAnnotation(annotation);
Set<Object> markedForRemoval = new HashSet<Object>();
- for (ListenerInvocation li : l)
- {
+ for (ListenerInvocation li : l) {
if (listener.equals(li.target)) markedForRemoval.add(li);
}
l.removeAll(markedForRemoval);
@@ -266,8 +243,7 @@
* Removes all listeners from the notifier, including the evictionPolicyListener.
*/
@Stop(priority = 99)
- public void removeAllCacheListeners()
- {
+ public void removeAllCacheListeners() {
cacheStartedListeners.clear();
cacheStoppedListeners.clear();
nodeCreatedListeners.clear();
@@ -283,20 +259,16 @@
viewChangedListeners.clear();
}
- public Set<Object> getCacheListeners()
- {
+ public Set<Object> getCacheListeners() {
Set<Object> result = new HashSet<Object>();
- for (List<ListenerInvocation> list : listenersMap.values())
- {
+ for (List<ListenerInvocation> list : listenersMap.values()) {
for (ListenerInvocation li : list) result.add(li.target);
}
return Collections.unmodifiableSet(result);
}
- public void notifyCacheEntryCreated(Object key, boolean pre, InvocationContext ctx)
- {
- if (!nodeCreatedListeners.isEmpty())
- {
+ public void notifyCacheEntryCreated(Object key, boolean pre, InvocationContext ctx) {
+ if (!nodeCreatedListeners.isEmpty()) {
boolean originLocal = ctx.isOriginLocal();
Transaction tx = ctx.getTransaction();
InvocationContext backup = resetInvocationContext(ctx);
@@ -312,10 +284,8 @@
}
}
- public void notifyCacheEntryModified(Object key, boolean pre, InvocationContext ctx)
- {
- if (!nodeModifiedListeners.isEmpty())
- {
+ public void notifyCacheEntryModified(Object key, boolean pre, InvocationContext ctx) {
+ if (!nodeModifiedListeners.isEmpty()) {
boolean originLocal = ctx.isOriginLocal();
Transaction tx = ctx.getTransaction();
InvocationContext backup = resetInvocationContext(ctx);
@@ -331,15 +301,12 @@
}
}
- public boolean shouldNotifyOnNodeModified()
- {
+ public boolean shouldNotifyOnNodeModified() {
return !nodeModifiedListeners.isEmpty();
}
- public void notifyCacheEntryRemoved(Object key, boolean pre, InvocationContext ctx)
- {
- if (!nodeRemovedListeners.isEmpty())
- {
+ public void notifyCacheEntryRemoved(Object key, boolean pre, InvocationContext ctx) {
+ if (!nodeRemovedListeners.isEmpty()) {
boolean originLocal = ctx.isOriginLocal();
Transaction tx = ctx.getTransaction();
InvocationContext backup = resetInvocationContext(ctx);
@@ -355,10 +322,8 @@
}
}
- public void notifyCacheEntryVisited(Object key, boolean pre, InvocationContext ctx)
- {
- if (!nodeVisitedListeners.isEmpty())
- {
+ public void notifyCacheEntryVisited(Object key, boolean pre, InvocationContext ctx) {
+ if (!nodeVisitedListeners.isEmpty()) {
Transaction tx = ctx.getTransaction();
InvocationContext backup = resetInvocationContext(ctx);
EventImpl e = new EventImpl();
@@ -372,10 +337,8 @@
}
}
- public void notifyCacheEntryEvicted(final Object key, final boolean pre, InvocationContext ctx)
- {
- if (!nodeEvictedListeners.isEmpty())
- {
+ public void notifyCacheEntryEvicted(final Object key, final boolean pre, InvocationContext ctx) {
+ if (!nodeEvictedListeners.isEmpty()) {
final boolean originLocal = ctx.isOriginLocal();
Transaction tx = ctx.getTransaction();
InvocationContext backup = resetInvocationContext(ctx);
@@ -391,10 +354,8 @@
}
}
- public void notifyCacheEntryInvalidated(final Object key, final boolean pre, InvocationContext ctx)
- {
- if (!nodeInvalidatedListeners.isEmpty())
- {
+ public void notifyCacheEntryInvalidated(final Object key, final boolean pre, InvocationContext ctx) {
+ if (!nodeInvalidatedListeners.isEmpty()) {
final boolean originLocal = ctx.isOriginLocal();
Transaction tx = ctx.getTransaction();
InvocationContext backup = resetInvocationContext(ctx);
@@ -410,10 +371,8 @@
}
}
- public void notifyCacheEntryLoaded(Object key, boolean pre, InvocationContext ctx)
- {
- if (!nodeLoadedListeners.isEmpty())
- {
+ public void notifyCacheEntryLoaded(Object key, boolean pre, InvocationContext ctx) {
+ if (!nodeLoadedListeners.isEmpty()) {
boolean originLocal = ctx.isOriginLocal();
Transaction tx = ctx.getTransaction();
InvocationContext backup = resetInvocationContext(ctx);
@@ -429,10 +388,8 @@
}
}
- public void notifyCacheEntryActivated(Object key, boolean pre, InvocationContext ctx)
- {
- if (!nodeActivatedListeners.isEmpty())
- {
+ public void notifyCacheEntryActivated(Object key, boolean pre, InvocationContext ctx) {
+ if (!nodeActivatedListeners.isEmpty()) {
boolean originLocal = ctx.isOriginLocal();
Transaction tx = ctx.getTransaction();
InvocationContext backup = resetInvocationContext(ctx);
@@ -448,10 +405,8 @@
}
}
- public void notifyCacheEntryPassivated(Object key, boolean pre, InvocationContext ctx)
- {
- if (!nodePassivatedListeners.isEmpty())
- {
+ public void notifyCacheEntryPassivated(Object key, boolean pre, InvocationContext ctx) {
+ if (!nodePassivatedListeners.isEmpty()) {
Transaction tx = ctx.getTransaction();
InvocationContext backup = resetInvocationContext(ctx);
EventImpl e = new EventImpl();
@@ -469,10 +424,8 @@
* Notifies all registered listeners of a cacheStarted event.
*/
@Start(priority = 99)
- public void notifyCacheStarted()
- {
- if (!cacheStartedListeners.isEmpty())
- {
+ public void notifyCacheStarted() {
+ if (!cacheStartedListeners.isEmpty()) {
EventImpl e = new EventImpl();
e.setCache(cache);
e.setType(CACHE_STARTED);
@@ -484,10 +437,8 @@
* Notifies all registered listeners of a cacheStopped event.
*/
@Stop(priority = 98)
- public void notifyCacheStopped()
- {
- if (!cacheStoppedListeners.isEmpty())
- {
+ public void notifyCacheStopped() {
+ if (!cacheStoppedListeners.isEmpty()) {
EventImpl e = new EventImpl();
e.setCache(cache);
e.setType(CACHE_STOPPED);
@@ -495,10 +446,8 @@
}
}
- public void notifyViewChange(final View newView, InvocationContext ctx)
- {
- if (!viewChangedListeners.isEmpty())
- {
+ public void notifyViewChange(final View newView, InvocationContext ctx) {
+ if (!viewChangedListeners.isEmpty()) {
InvocationContext backup = resetInvocationContext(ctx);
EventImpl e = new EventImpl();
e.setCache(cache);
@@ -509,10 +458,8 @@
}
}
- public void notifyTransactionCompleted(Transaction transaction, boolean successful, InvocationContext ctx)
- {
- if (!transactionCompletedListeners.isEmpty())
- {
+ public void notifyTransactionCompleted(Transaction transaction, boolean successful, InvocationContext ctx) {
+ if (!transactionCompletedListeners.isEmpty()) {
boolean isOriginLocal = ctx.isOriginLocal();
InvocationContext backup = resetInvocationContext(ctx);
EventImpl e = new EventImpl();
@@ -526,10 +473,8 @@
}
}
- public void notifyTransactionRegistered(Transaction transaction, InvocationContext ctx)
- {
- if (!transactionRegisteredListeners.isEmpty())
- {
+ public void notifyTransactionRegistered(Transaction transaction, InvocationContext ctx) {
+ if (!transactionRegisteredListeners.isEmpty()) {
boolean isOriginLocal = ctx.isOriginLocal();
InvocationContext backup = resetInvocationContext(ctx);
EventImpl e = new EventImpl();
@@ -542,8 +487,7 @@
}
}
- private void restoreInvocationContext(InvocationContext backup)
- {
+ private void restoreInvocationContext(InvocationContext backup) {
InvocationContext currentIC = cache.getInvocationContext();
backup.clearLookedUpEntries();
backup.putLookedUpEntries(currentIC.getLookedUpEntries());
@@ -551,14 +495,13 @@
}
/**
- * Resets the current (passed-in) invocation, and returns a temp InvocationContext containing its state so it can
- * be restored later using {@link #restoreInvocationContext(InvocationContext)}
+ * Resets the current (passed-in) invocation, and returns a temp InvocationContext containing its state so it can be
+ * restored later using {@link #restoreInvocationContext(InvocationContext)}
*
* @param ctx the current context to be reset
* @return a clone of ctx, before it was reset
*/
- private InvocationContext resetInvocationContext(InvocationContext ctx)
- {
+ private InvocationContext resetInvocationContext(InvocationContext ctx) {
// wipe current context.
cache.setInvocationContext(null);
// get a new Invocation Context
@@ -568,43 +511,35 @@
}
/**
- * Class that encapsulates a valid invocation for a given registered listener - containing a reference to the
- * method to be invoked as well as the target object.
+ * Class that encapsulates a valid invocation for a given registered listener - containing a reference to the method
+ * to be invoked as well as the target object.
*/
- class ListenerInvocation
- {
+ class ListenerInvocation {
private final Object target;
private final Method method;
private final boolean sync;
- public ListenerInvocation(Object target, Method method, boolean sync)
- {
+ public ListenerInvocation(Object target, Method method, boolean sync) {
this.target = target;
this.method = method;
this.sync = sync;
}
- public void invoke(final Event e)
- {
- Runnable r = new Runnable()
- {
+ public void invoke(final Event e) {
+ Runnable r = new Runnable() {
- public void run()
- {
- try
- {
+ public void run() {
+ try {
method.invoke(target, e);
}
- catch (InvocationTargetException exception)
- {
+ catch (InvocationTargetException exception) {
Throwable cause = exception.getCause();
if (cause != null)
throw new CacheException("Caught exception invoking method " + method + " on listener instance " + target, cause);
else
throw new CacheException("Caught exception invoking method " + method + " on listener instance " + target, exception);
}
- catch (IllegalAccessException exception)
- {
+ catch (IllegalAccessException exception) {
log.warn("Unable to invoke method " + method + " on Object instance " + target + " - removing this target object from list of listeners!", exception);
removeCacheListener(target);
}
@@ -620,15 +555,13 @@
}
- private List<ListenerInvocation> getListenerCollectionForAnnotation(Class<? extends Annotation> annotation)
- {
+ private List<ListenerInvocation> getListenerCollectionForAnnotation(Class<? extends Annotation> annotation) {
List<ListenerInvocation> list = listenersMap.get(annotation);
if (list == null) throw new CacheException("Unknown listener annotation: " + annotation);
return list;
}
- public void notifyNodeInvalidated(Object key, boolean pre, InvocationContext ctx)
- {
+ public void notifyNodeInvalidated(Object key, boolean pre, InvocationContext ctx) {
throw new UnsupportedOperationException("Not implemented");//todo please implement!
}
}
Modified: core/branches/flat/src/main/java/org/horizon/notifications/annotation/CacheEntryActivated.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/notifications/annotation/CacheEntryActivated.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/notifications/annotation/CacheEntryActivated.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -29,9 +29,9 @@
/**
* This annotation should be used on methods that need to be notified when a node is activated.
* <p/>
- * Methods annotated with this annotation should be public and take in a single parameter, a {@link org.horizon.notifications.event.NodeActivatedEvent}
- * otherwise an {@link org.horizon.notifications.IncorrectCacheListenerException} will be thrown when registering
- * your cache listener.
+ * Methods annotated with this annotation should be public and take in a single parameter, a {@link
+ * org.horizon.notifications.event.NodeActivatedEvent} otherwise an {@link org.horizon.notifications.IncorrectCacheListenerException}
+ * will be thrown when registering your cache listener.
*
* @author <a href="mailto:manik at jboss.org">Manik Surtani</a>
* @see CacheListener
@@ -40,6 +40,5 @@
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
-public @interface CacheEntryActivated
-{
+public @interface CacheEntryActivated {
}
Modified: core/branches/flat/src/main/java/org/horizon/notifications/annotation/CacheEntryCreated.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/notifications/annotation/CacheEntryCreated.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/notifications/annotation/CacheEntryCreated.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -29,9 +29,9 @@
/**
* This annotation should be used on methods that need to be notified when a node is created.
* <p/>
- * Methods annotated with this annotation should be public and take in a single parameter, a {@link org.horizon.notifications.event.NodeCreatedEvent}
- * otherwise an {@link org.horizon.notifications.IncorrectCacheListenerException} will be thrown when registering
- * your cache listener.
+ * Methods annotated with this annotation should be public and take in a single parameter, a {@link
+ * org.horizon.notifications.event.NodeCreatedEvent} otherwise an {@link org.horizon.notifications.IncorrectCacheListenerException}
+ * will be thrown when registering your cache listener.
*
* @author <a href="mailto:manik at jboss.org">Manik Surtani</a>
* @see CacheListener
@@ -39,6 +39,5 @@
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
-public @interface CacheEntryCreated
-{
+public @interface CacheEntryCreated {
}
Modified: core/branches/flat/src/main/java/org/horizon/notifications/annotation/CacheEntryEvicted.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/notifications/annotation/CacheEntryEvicted.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/notifications/annotation/CacheEntryEvicted.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -29,9 +29,9 @@
/**
* This annotation should be used on methods that need to be notified when a node is evicted.
* <p/>
- * Methods annotated with this annotation should be public and take in a single parameter, a {@link org.horizon.notifications.event.NodeEvictedEvent}
- * otherwise an {@link org.horizon.notifications.IncorrectCacheListenerException} will be thrown when registering
- * your cache listener.
+ * Methods annotated with this annotation should be public and take in a single parameter, a {@link
+ * org.horizon.notifications.event.NodeEvictedEvent} otherwise an {@link org.horizon.notifications.IncorrectCacheListenerException}
+ * will be thrown when registering your cache listener.
*
* @author <a href="mailto:manik at jboss.org">Manik Surtani</a>
* @see CacheListener
@@ -40,6 +40,5 @@
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
-public @interface CacheEntryEvicted
-{
+public @interface CacheEntryEvicted {
}
Modified: core/branches/flat/src/main/java/org/horizon/notifications/annotation/CacheEntryInvalidated.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/notifications/annotation/CacheEntryInvalidated.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/notifications/annotation/CacheEntryInvalidated.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -29,9 +29,9 @@
/**
* This annotation should be used on methods that need to be notified when a node is invalidated.
* <p/>
- * Methods annotated with this annotation should be public and take in a single parameter, a {@link org.horizon.notifications.event.NodeInvalidatedEvent}
- * otherwise an {@link org.horizon.notifications.IncorrectCacheListenerException} will be thrown when registering
- * your cache listener.
+ * Methods annotated with this annotation should be public and take in a single parameter, a {@link
+ * org.horizon.notifications.event.NodeInvalidatedEvent} otherwise an {@link org.horizon.notifications.IncorrectCacheListenerException}
+ * will be thrown when registering your cache listener.
*
* @author <a href="mailto:manik at jboss.org">Manik Surtani</a>
* @see org.horizon.notifications.annotation.CacheListener
@@ -39,6 +39,5 @@
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
-public @interface CacheEntryInvalidated
-{
+public @interface CacheEntryInvalidated {
}
\ No newline at end of file
Modified: core/branches/flat/src/main/java/org/horizon/notifications/annotation/CacheEntryLoaded.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/notifications/annotation/CacheEntryLoaded.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/notifications/annotation/CacheEntryLoaded.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -27,11 +27,12 @@
import java.lang.annotation.Target;
/**
- * This annotation should be used on methods that need to be notified when a node is loaded from a {@link org.horizon.loader.CacheLoader}.
+ * This annotation should be used on methods that need to be notified when a node is loaded from a {@link
+ * org.horizon.loader.CacheLoader}.
* <p/>
- * Methods annotated with this annotation should be public and take in a single parameter, a {@link org.horizon.notifications.event.NodeEvictedEvent}
- * otherwise an {@link org.horizon.notifications.IncorrectCacheListenerException} will be thrown when registering
- * your cache listener.
+ * Methods annotated with this annotation should be public and take in a single parameter, a {@link
+ * org.horizon.notifications.event.NodeEvictedEvent} otherwise an {@link org.horizon.notifications.IncorrectCacheListenerException}
+ * will be thrown when registering your cache listener.
*
* @author <a href="mailto:manik at jboss.org">Manik Surtani</a>
* @see CacheListener
@@ -39,6 +40,5 @@
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
-public @interface CacheEntryLoaded
-{
+public @interface CacheEntryLoaded {
}
Modified: core/branches/flat/src/main/java/org/horizon/notifications/annotation/CacheEntryModified.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/notifications/annotation/CacheEntryModified.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/notifications/annotation/CacheEntryModified.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -29,9 +29,9 @@
/**
* This annotation should be used on methods that need to be notified when a node has been modified.
* <p/>
- * Methods annotated with this annotation should be public and take in a single parameter, a {@link org.horizon.notifications.event.NodeModifiedEvent}
- * otherwise an {@link org.horizon.notifications.IncorrectCacheListenerException} will be thrown when registering
- * your cache listener.
+ * Methods annotated with this annotation should be public and take in a single parameter, a {@link
+ * org.horizon.notifications.event.NodeModifiedEvent} otherwise an {@link org.horizon.notifications.IncorrectCacheListenerException}
+ * will be thrown when registering your cache listener.
* <p/>
*
* @author <a href="mailto:manik at jboss.org">Manik Surtani</a>
@@ -40,6 +40,5 @@
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
-public @interface CacheEntryModified
-{
+public @interface CacheEntryModified {
}
Modified: core/branches/flat/src/main/java/org/horizon/notifications/annotation/CacheEntryPassivated.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/notifications/annotation/CacheEntryPassivated.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/notifications/annotation/CacheEntryPassivated.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -29,8 +29,8 @@
/**
* This annotation should be used on methods that need to be notified when a node is passivated.
* <p/>
- * Methods annotated with this annotation should accept a single
- * parameter, a {@link org.horizon.notifications.event.NodePassivatedEvent} otherwise a {@link org.horizon.notifications.IncorrectCacheListenerException}
+ * Methods annotated with this annotation should accept a single parameter, a {@link
+ * org.horizon.notifications.event.NodePassivatedEvent} otherwise a {@link org.horizon.notifications.IncorrectCacheListenerException}
* will be thrown when registering your listener.
*
* @author <a href="mailto:manik at jboss.org">Manik Surtani</a>
@@ -41,6 +41,5 @@
@Retention(RetentionPolicy.RUNTIME)
// ensure that this annotation is applied to classes.
@Target(ElementType.METHOD)
-public @interface CacheEntryPassivated
-{
+public @interface CacheEntryPassivated {
}
Modified: core/branches/flat/src/main/java/org/horizon/notifications/annotation/CacheEntryRemoved.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/notifications/annotation/CacheEntryRemoved.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/notifications/annotation/CacheEntryRemoved.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -29,8 +29,8 @@
/**
* This annotation should be used on methods that need to be notified when a node is removed from the cache.
* <p/>
- * Methods annotated with this annotation should accept a single
- * parameter, a {@link org.horizon.notifications.event.TransactionRegisteredEvent} otherwise a {@link org.horizon.notifications.IncorrectCacheListenerException}
+ * Methods annotated with this annotation should accept a single parameter, a {@link
+ * org.horizon.notifications.event.TransactionRegisteredEvent} otherwise a {@link org.horizon.notifications.IncorrectCacheListenerException}
* will be thrown when registering your listener.
*
* @author <a href="mailto:manik at jboss.org">Manik Surtani</a>
@@ -41,6 +41,5 @@
@Retention(RetentionPolicy.RUNTIME)
// ensure that this annotation is applied to classes.
@Target(ElementType.METHOD)
-public @interface CacheEntryRemoved
-{
+public @interface CacheEntryRemoved {
}
Modified: core/branches/flat/src/main/java/org/horizon/notifications/annotation/CacheEntryVisited.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/notifications/annotation/CacheEntryVisited.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/notifications/annotation/CacheEntryVisited.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -29,8 +29,8 @@
/**
* This annotation should be used on methods that need to be notified when a node is visited.
* <p/>
- * Methods annotated with this annotation should accept a single
- * parameter, a {@link org.horizon.notifications.event.NodeVisitedEvent} otherwise a {@link org.horizon.notifications.IncorrectCacheListenerException}
+ * Methods annotated with this annotation should accept a single parameter, a {@link
+ * org.horizon.notifications.event.NodeVisitedEvent} otherwise a {@link org.horizon.notifications.IncorrectCacheListenerException}
* will be thrown when registering your listener.
*
* @author <a href="mailto:manik at jboss.org">Manik Surtani</a>
@@ -41,6 +41,5 @@
@Retention(RetentionPolicy.RUNTIME)
// ensure that this annotation is applied to classes.
@Target(ElementType.METHOD)
-public @interface CacheEntryVisited
-{
+public @interface CacheEntryVisited {
}
Modified: core/branches/flat/src/main/java/org/horizon/notifications/annotation/CacheListener.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/notifications/annotation/CacheListener.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/notifications/annotation/CacheListener.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -27,161 +27,73 @@
import java.lang.annotation.Target;
/**
- * Class-level annotation used to annotate an object as being a valid cache listener. Used with the
- * {@link org.horizon.Cache_Legacy#addCacheListener(Object)} and related APIs.
+ * Class-level annotation used to annotate an object as being a valid cache listener. Used with the {@link
+ * org.horizon.Cache_Legacy#addCacheListener(Object)} and related APIs. <p/> Note that even if a class is annotated with
+ * this annotation, it still needs method-level annotation (such as {@link org.horizon.notifications.annotation.CacheStarted})
+ * to actually receive notifications. <p/> Objects annotated with this annotation - listeners - can be attached to a
+ * running {@link org.horizon.Cache_Legacy} so users can be notified of {@link org.horizon.Cache_Legacy} events. <p/>
+ * <p/> There can be multiple methods that are annotated to receive the same event, and a method may receive multiple
+ * events by using a super type. </p> <p/> <h4>Delivery Semantics</h4> <p/> An event is delivered immediately after the
+ * respective operation, but before the underlying cache call returns. For this reason it is important to keep listener
+ * processing logic short-lived. If a long running task needs to be performed, it's recommended to use another thread.
+ * </p> <p/> <h4>Transactional Semantics</h4> <p/> Since the event is delivered during the actual cache call, the
+ * transactional outcome is not yet known. For this reason, <i>events are always delivered, even if the changes they
+ * represent are discarded by their containing transaction</i>. For applications that must only process events that
+ * represent changes in a completed transaction, {@link org.horizon.notifications.event.TransactionalEvent#getTransaction()}
+ * can be used, along with {@link org.horizon.notifications.event.TransactionCompletedEvent#isSuccessful()} to record
+ * events and later process them once the transaction has been successfully committed. Example 4 demonstrates this. </p>
+ * <p/> <h4>Threading Semantics</h4> <p/> A listener implementation must be capable of handling concurrent invocations.
+ * Local notifications reuse the calling thread; remote notifications reuse the network thread. </p> <p/> Since
+ * notifications reuse the calling or network thread, it is important to realise that if your listener implementation
+ * blocks or performs a long-running task, the original caller which triggered the cache event may block until the
+ * listener callback completes. It is therefore a good idea to use the listener to be notified of an event but to
+ * perform any long running tasks in a separate thread so as not to block the original caller. </p> <p/> In addition,
+ * any locks acquired for the operation being performed will still be held for the callback. This needs to be kept in
+ * mind as locks may be held longer than necessary or intended to and may cause deadlocking in certain situations. See
+ * above paragraph on long-running tasks that should be run in a separate thread. </p> <b>Note</b>: Since 3.0, a new
+ * parameter, <tt>sync</tt>, has been introduced on this annotation. This defaults to <tt>true</tt> which provides the
+ * above semantics. Alternatively, if you set <tt>sync</tt> to <tt>false</tt>, then invocations are made in a
+ * <i>separate</i> thread, which will not cause any blocking on the caller or network thread. The separate thread is
+ * taken from a pool, which can be configured using {@link org.horizon.config.Configuration#setListenerAsyncPoolSize(int)}.
* <p/>
- * Note that even if a class is annotated with this annotation, it still needs method-level annotation (such as
- * {@link org.horizon.notifications.annotation.CacheStarted}) to actually receive notifications.
+ * <b>Summary of Notification Annotations</b> <table border="1" cellpadding="1" cellspacing="1" summary="Summary of
+ * notification annotations"> <tr> <th bgcolor="#CCCCFF" align="left">Annotation</th> <th bgcolor="#CCCCFF"
+ * align="left">Event</th> <th bgcolor="#CCCCFF" align="left">Description</th> </tr> <tr> <td valign="top">{@link
+ * CacheStarted}</td> <td valign="top">{@link org.horizon.notifications.event.CacheStartedEvent}</td> <td valign="top">A
+ * cache was started</td> </tr> <tr> <td valign="top">{@link CacheStopped}</td> <td valign="top">{@link
+ * org.horizon.notifications.event.CacheStoppedEvent}</td> <td valign="top">A cache was stopped</td> </tr> <tr> <td
+ * valign="top">{@link CacheEntryModified}</td> <td valign="top">{@link org.horizon.notifications.event.NodeModifiedEvent}</td>
+ * <td valign="top">A node was modified</td> </tr> <tr> <td valign="top">{@link NodeMoved}</td> <td valign="top">{@link
+ * org.horizon.notifications.event.NodeMovedEvent}</td> <td valign="top">A node was moved</td> </tr> <tr> <td
+ * valign="top">{@link CacheEntryCreated}</td> <td valign="top">{@link org.horizon.notifications.event.NodeCreatedEvent}</td>
+ * <td valign="top">A node was created</td> </tr> <tr> <td valign="top">{@link CacheEntryRemoved}</td> <td
+ * valign="top">{@link org.horizon.notifications.event.NodeRemovedEvent}</td> <td valign="top">A node was removed</td>
+ * </tr> <tr> <td valign="top">{@link CacheEntryVisited}</td> <td valign="top">{@link
+ * org.horizon.notifications.event.NodeVisitedEvent}</td> <td valign="top">A node was visited</td> </tr> <tr> <td
+ * valign="top">{@link CacheEntryLoaded}</td> <td valign="top">{@link org.horizon.notifications.event.NodeLoadedEvent}</td>
+ * <td valign="top">A node was loaded</td> </tr> <tr> <td valign="top">{@link org.horizon.notifications.annotation.NodeEvicted}</td>
+ * <td valign="top">{@link org.horizon.notifications.event.NodeEvictedEvent}</td> <td valign="top">A node was
+ * evicted</td> </tr> <tr> <td valign="top">{@link org.horizon.notifications.annotation.NodeActivated}</td> <td
+ * valign="top">{@link org.horizon.notifications.event.NodeActivatedEvent}</td> <td valign="top">A node was
+ * activated</td> </tr> <tr> <td valign="top">{@link org.horizon.notifications.annotation.NodePassivated}</td> <td
+ * valign="top">{@link org.horizon.notifications.event.NodePassivatedEvent}</td> <td valign="top">A node was
+ * passivated</td> </tr> <tr> <td valign="top">{@link org.horizon.notifications.annotation.ViewChanged}</td> <td
+ * valign="top">{@link org.horizon.notifications.event.ViewChangedEvent}</td> <td valign="top">A view change event was
+ * detected</td> </tr> <tr> <td valign="top">{@link org.horizon.notifications.annotation.CacheBlocked}</td> <td
+ * valign="top">{@link org.horizon.notifications.event.CacheBlockedEvent}</td> <td valign="top">A cache block event was
+ * detected</td> </tr> <tr> <td valign="top">{@link CacheUnblocked}</td> <td valign="top">{@link
+ * org.horizon.notifications.event.CacheUnblockedEvent}</td> <td valign="top">A cache unblock event was detected</td>
+ * </tr> <tr> <td valign="top">{@link TransactionRegistered}</td> <td valign@="top">{@link
+ * org.horizon.notifications.event.TransactionRegisteredEvent}</td> <td valign="top">The cache has started to
+ * participate in a transaction</td> </tr> <tr> <td valign="top">{@link TransactionCompleted}</td> <td
+ * valign=@"top">{@link org.horizon.notifications.event.TransactionCompletedEvent}</td> <td valign="top">The cache has
+ * completed its participation in a transaction</td> </tr> <tr> <td valign="top">{@link BuddyGroupChanged}</td> <td
+ * valign=@"top">{@link org.horizon.notifications.event.BuddyGroupChangedEvent}</td> <td valign="top">Buddy replication
+ * is enabled and one of the buddy groups that the instance is a member of has changed its membership.</td> </tr> <tr>
+ * <td valign="top">{@link CacheEntryInvalidated}</td> <td valign=@"top">{@link org.horizon.notifications.event.NodeInvalidatedEvent}</td>
+ * <td valign="top">A node was invalidated by a remote cache. Only if cache mode is INVALIDATION_SYNC or
+ * INVALIDATION_ASYNC.</td> </tr>
* <p/>
- * Objects annotated with this annotation - listeners - can be attached to a running {@link org.horizon.Cache_Legacy} so
- * users can be notified of {@link org.horizon.Cache_Legacy} events.
- * <p/>
- * <p/>
- * There can be multiple methods that are annotated to receive the same event,
- * and a method may receive multiple events by using a super type.
- * </p>
- * <p/>
- * <h4>Delivery Semantics</h4>
- * <p/>
- * An event is delivered immediately after the
- * respective operation, but before the underlying cache call returns. For this
- * reason it is important to keep listener processing logic short-lived. If a
- * long running task needs to be performed, it's recommended to use another
- * thread.
- * </p>
- * <p/>
- * <h4>Transactional Semantics</h4>
- * <p/>
- * Since the event is delivered during the actual cache call, the transactional
- * outcome is not yet known. For this reason, <i>events are always delivered, even
- * if the changes they represent are discarded by their containing transaction</i>.
- * For applications that must only process events that represent changes in a
- * completed transaction, {@link org.horizon.notifications.event.TransactionalEvent#getTransaction()} can be used,
- * along with {@link org.horizon.notifications.event.TransactionCompletedEvent#isSuccessful()} to record events and
- * later process them once the transaction has been successfully committed.
- * Example 4 demonstrates this.
- * </p>
- * <p/>
- * <h4>Threading Semantics</h4>
- * <p/>
- * A listener implementation must be capable of handling concurrent invocations. Local
- * notifications reuse the calling thread; remote notifications reuse the network thread.
- * </p>
- * <p/>
- * Since notifications reuse the calling or network thread, it is important to realise that
- * if your listener implementation blocks or performs a long-running task, the original caller which
- * triggered the cache event may block until the listener callback completes. It is therefore a good idea to use
- * the listener to be notified of an event but to perform any
- * long running tasks in a separate thread so as not to block the original caller.
- * </p>
- * <p/>
- * In addition, any locks acquired for the operation being performed will still be held for the callback. This needs to be kept in mind
- * as locks may be held longer than necessary or intended to and may cause deadlocking in certain situations. See above paragraph
- * on long-running tasks that should be run in a separate thread.
- * </p>
- * <b>Note</b>: Since 3.0, a new parameter, <tt>sync</tt>, has been introduced on this annotation. This defaults to <tt>true</tt>
- * which provides the above semantics. Alternatively, if you set <tt>sync</tt> to <tt>false</tt>, then invocations are made in a
- * <i>separate</i> thread, which will not cause any blocking on the caller or network thread. The separate thread is taken
- * from a pool, which can be configured using {@link org.horizon.config.Configuration#setListenerAsyncPoolSize(int)}.
- * <p/>
- * <b>Summary of Notification Annotations</b>
- * <table border="1" cellpadding="1" cellspacing="1" summary="Summary of notification annotations">
- * <tr>
- * <th bgcolor="#CCCCFF" align="left">Annotation</th>
- * <th bgcolor="#CCCCFF" align="left">Event</th>
- * <th bgcolor="#CCCCFF" align="left">Description</th>
- * </tr>
- * <tr>
- * <td valign="top">{@link CacheStarted}</td>
- * <td valign="top">{@link org.horizon.notifications.event.CacheStartedEvent}</td>
- * <td valign="top">A cache was started</td>
- * </tr>
- * <tr>
- * <td valign="top">{@link CacheStopped}</td>
- * <td valign="top">{@link org.horizon.notifications.event.CacheStoppedEvent}</td>
- * <td valign="top">A cache was stopped</td>
- * </tr>
- * <tr>
- * <td valign="top">{@link CacheEntryModified}</td>
- * <td valign="top">{@link org.horizon.notifications.event.NodeModifiedEvent}</td>
- * <td valign="top">A node was modified</td>
- * </tr>
- * <tr>
- * <td valign="top">{@link NodeMoved}</td>
- * <td valign="top">{@link org.horizon.notifications.event.NodeMovedEvent}</td>
- * <td valign="top">A node was moved</td>
- * </tr>
- * <tr>
- * <td valign="top">{@link CacheEntryCreated}</td>
- * <td valign="top">{@link org.horizon.notifications.event.NodeCreatedEvent}</td>
- * <td valign="top">A node was created</td>
- * </tr>
- * <tr>
- * <td valign="top">{@link CacheEntryRemoved}</td>
- * <td valign="top">{@link org.horizon.notifications.event.NodeRemovedEvent}</td>
- * <td valign="top">A node was removed</td>
- * </tr>
- * <tr>
- * <td valign="top">{@link CacheEntryVisited}</td>
- * <td valign="top">{@link org.horizon.notifications.event.NodeVisitedEvent}</td>
- * <td valign="top">A node was visited</td>
- * </tr>
- * <tr>
- * <td valign="top">{@link CacheEntryLoaded}</td>
- * <td valign="top">{@link org.horizon.notifications.event.NodeLoadedEvent}</td>
- * <td valign="top">A node was loaded</td>
- * </tr>
- * <tr>
- * <td valign="top">{@link org.horizon.notifications.annotation.NodeEvicted}</td>
- * <td valign="top">{@link org.horizon.notifications.event.NodeEvictedEvent}</td>
- * <td valign="top">A node was evicted</td>
- * </tr>
- * <tr>
- * <td valign="top">{@link org.horizon.notifications.annotation.NodeActivated}</td>
- * <td valign="top">{@link org.horizon.notifications.event.NodeActivatedEvent}</td>
- * <td valign="top">A node was activated</td>
- * </tr>
- * <tr>
- * <td valign="top">{@link org.horizon.notifications.annotation.NodePassivated}</td>
- * <td valign="top">{@link org.horizon.notifications.event.NodePassivatedEvent}</td>
- * <td valign="top">A node was passivated</td>
- * </tr>
- * <tr>
- * <td valign="top">{@link org.horizon.notifications.annotation.ViewChanged}</td>
- * <td valign="top">{@link org.horizon.notifications.event.ViewChangedEvent}</td>
- * <td valign="top">A view change event was detected</td>
- * </tr>
- * <tr>
- * <td valign="top">{@link org.horizon.notifications.annotation.CacheBlocked}</td>
- * <td valign="top">{@link org.horizon.notifications.event.CacheBlockedEvent}</td>
- * <td valign="top">A cache block event was detected</td>
- * </tr>
- * <tr>
- * <td valign="top">{@link CacheUnblocked}</td>
- * <td valign="top">{@link org.horizon.notifications.event.CacheUnblockedEvent}</td>
- * <td valign="top">A cache unblock event was detected</td>
- * </tr>
- * <tr>
- * <td valign="top">{@link TransactionRegistered}</td>
- * <td valign@="top">{@link org.horizon.notifications.event.TransactionRegisteredEvent}</td>
- * <td valign="top">The cache has started to participate in a transaction</td>
- * </tr>
- * <tr>
- * <td valign="top">{@link TransactionCompleted}</td>
- * <td valign=@"top">{@link org.horizon.notifications.event.TransactionCompletedEvent}</td>
- * <td valign="top">The cache has completed its participation in a transaction</td>
- * </tr>
- * <tr>
- * <td valign="top">{@link BuddyGroupChanged}</td>
- * <td valign=@"top">{@link org.horizon.notifications.event.BuddyGroupChangedEvent}</td>
- * <td valign="top">Buddy replication is enabled and one of the buddy groups that the instance is a member of has changed its membership.</td>
- * </tr>
- * <tr>
- * <td valign="top">{@link CacheEntryInvalidated}</td>
- * <td valign=@"top">{@link org.horizon.notifications.event.NodeInvalidatedEvent}</td>
- * <td valign="top">A node was invalidated by a remote cache. Only if cache mode is INVALIDATION_SYNC or INVALIDATION_ASYNC.</td>
- * </tr>
- * <p/>
* </table>
* <p/>
* <h4>Example 1 - Method receiving a single event</h4>
@@ -246,7 +158,8 @@
* {
* private class TxEventQueue
* {
- * private ConcurrentMap<Transaction, Queue<Event>> map = new ConcurrentHashMap<Transaction, Queue<Event>>();
+ * private ConcurrentMap<Transaction, Queue<Event>> map = new ConcurrentHashMap<Transaction,
+ * Queue<Event>>();
* <p/>
* public void offer(Event event)
* {
@@ -320,13 +233,13 @@
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
-public @interface CacheListener
-{
+public @interface CacheListener {
/**
- * Specifies whether callbacks on any class annotated with this annotation happens synchronously (in the caller's thread)
- * or asynchronously (using a separate thread). Defaults to <tt>true</tt>.
+ * Specifies whether callbacks on any class annotated with this annotation happens synchronously (in the caller's
+ * thread) or asynchronously (using a separate thread). Defaults to <tt>true</tt>.
*
- * @return true if the expectation is that callbacks are called using the caller's thread; false if they are to be made in a separate thread.
+ * @return true if the expectation is that callbacks are called using the caller's thread; false if they are to be
+ * made in a separate thread.
* @since 1.0
*/
boolean sync() default true;
Modified: core/branches/flat/src/main/java/org/horizon/notifications/annotation/CacheStarted.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/notifications/annotation/CacheStarted.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/notifications/annotation/CacheStarted.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -29,8 +29,8 @@
/**
* This annotation should be used on methods that need to be notified when a cache is started.
* <p/>
- * Methods annotated with this annotation should accept a single
- * parameter, a {@link org.horizon.notifications.event.CacheStartedEvent} otherwise a {@link org.horizon.notifications.IncorrectCacheListenerException}
+ * Methods annotated with this annotation should accept a single parameter, a {@link
+ * org.horizon.notifications.event.CacheStartedEvent} otherwise a {@link org.horizon.notifications.IncorrectCacheListenerException}
* will be thrown when registering your listener.
*
* @author <a href="mailto:manik at jboss.org">Manik Surtani</a>
@@ -39,6 +39,5 @@
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
-public @interface CacheStarted
-{
+public @interface CacheStarted {
}
Modified: core/branches/flat/src/main/java/org/horizon/notifications/annotation/CacheStopped.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/notifications/annotation/CacheStopped.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/notifications/annotation/CacheStopped.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -29,8 +29,8 @@
/**
* This annotation should be used on methods that need to be notified when a cache is stopped.
* <p/>
- * Methods annotated with this annotation should accept a single
- * parameter, a {@link org.horizon.notifications.event.CacheStoppedEvent} otherwise a {@link org.horizon.notifications.IncorrectCacheListenerException}
+ * Methods annotated with this annotation should accept a single parameter, a {@link
+ * org.horizon.notifications.event.CacheStoppedEvent} otherwise a {@link org.horizon.notifications.IncorrectCacheListenerException}
* will be thrown when registering your listener.
*
* @author <a href="mailto:manik at jboss.org">Manik Surtani</a>
@@ -39,6 +39,5 @@
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
-public @interface CacheStopped
-{
+public @interface CacheStopped {
}
Modified: core/branches/flat/src/main/java/org/horizon/notifications/annotation/TransactionCompleted.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/notifications/annotation/TransactionCompleted.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/notifications/annotation/TransactionCompleted.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -27,15 +27,15 @@
import java.lang.annotation.Target;
/**
- * This annotation should be used on methods that need to be notified when the cache is called to participate in a transaction and
- * the transaction completes, either with a commit or a rollback.
+ * This annotation should be used on methods that need to be notified when the cache is called to participate in a
+ * transaction and the transaction completes, either with a commit or a rollback.
* <p/>
- * Methods annotated with this annotation should accept a single
- * parameter, a {@link org.horizon.notifications.event.TransactionCompletedEvent} otherwise a {@link org.horizon.notifications.IncorrectCacheListenerException}
+ * Methods annotated with this annotation should accept a single parameter, a {@link
+ * org.horizon.notifications.event.TransactionCompletedEvent} otherwise a {@link org.horizon.notifications.IncorrectCacheListenerException}
* will be thrown when registering your listener.
* <p/>
- * Note that methods marked with this annotation will only be fired <i>after the fact</i>, i.e., your method will never be
- * called with {@link org.horizon.notifications.event.Event#isPre()} being set to <tt>true</tt>.
+ * Note that methods marked with this annotation will only be fired <i>after the fact</i>, i.e., your method will never
+ * be called with {@link org.horizon.notifications.event.Event#isPre()} being set to <tt>true</tt>.
*
* @author <a href="mailto:manik at jboss.org">Manik Surtani</a>
* @see CacheListener
@@ -45,6 +45,5 @@
@Retention(RetentionPolicy.RUNTIME)
// ensure that this annotation is applied to classes.
@Target(ElementType.METHOD)
-public @interface TransactionCompleted
-{
+public @interface TransactionCompleted {
}
Modified: core/branches/flat/src/main/java/org/horizon/notifications/annotation/TransactionRegistered.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/notifications/annotation/TransactionRegistered.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/notifications/annotation/TransactionRegistered.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -27,15 +27,16 @@
import java.lang.annotation.Target;
/**
- * This annotation should be used on methods that need to be notified when the cache is called to participate in a transaction and
- * registers a {@link javax.transaction.Synchronization} with a registered {@link javax.transaction.TransactionManager}.
+ * This annotation should be used on methods that need to be notified when the cache is called to participate in a
+ * transaction and registers a {@link javax.transaction.Synchronization} with a registered {@link
+ * javax.transaction.TransactionManager}.
* <p/>
- * Methods annotated with this annotation should accept a single
- * parameter, a {@link org.horizon.notifications.event.TransactionRegisteredEvent} otherwise a {@link org.horizon.notifications.IncorrectCacheListenerException}
+ * Methods annotated with this annotation should accept a single parameter, a {@link
+ * org.horizon.notifications.event.TransactionRegisteredEvent} otherwise a {@link org.horizon.notifications.IncorrectCacheListenerException}
* will be thrown when registering your listener.
* <p/>
- * Note that methods marked with this annotation will only be fired <i>after the fact</i>, i.e., your method will never be
- * called with {@link org.horizon.notifications.event.Event#isPre()} being set to <tt>true</tt>.
+ * Note that methods marked with this annotation will only be fired <i>after the fact</i>, i.e., your method will never
+ * be called with {@link org.horizon.notifications.event.Event#isPre()} being set to <tt>true</tt>.
*
* @author <a href="mailto:manik at jboss.org">Manik Surtani</a>
* @see CacheListener
@@ -45,6 +46,5 @@
@Retention(RetentionPolicy.RUNTIME)
// ensure that this annotation is applied to classes.
@Target(ElementType.METHOD)
-public @interface TransactionRegistered
-{
+public @interface TransactionRegistered {
}
Modified: core/branches/flat/src/main/java/org/horizon/notifications/annotation/ViewChanged.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/notifications/annotation/ViewChanged.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/notifications/annotation/ViewChanged.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -27,11 +27,11 @@
import java.lang.annotation.Target;
/**
- * This annotation should be used on methods that need to be notified when the cache is used in a cluster and the cluster topology
- * changes (i.e., a member joins or leaves the cluster).
+ * This annotation should be used on methods that need to be notified when the cache is used in a cluster and the
+ * cluster topology changes (i.e., a member joins or leaves the cluster).
* <p/>
- * Methods annotated with this annotation should accept a single parameter,
- * a {@link org.horizon.notifications.event.ViewChangedEvent} otherwise a {@link org.horizon.notifications.IncorrectCacheListenerException}
+ * Methods annotated with this annotation should accept a single parameter, a {@link
+ * org.horizon.notifications.event.ViewChangedEvent} otherwise a {@link org.horizon.notifications.IncorrectCacheListenerException}
* will be thrown when registering your listener.
*
* @author <a href="mailto:manik at jboss.org">Manik Surtani</a>
@@ -42,6 +42,5 @@
@Retention(RetentionPolicy.RUNTIME)
// ensure that this annotation is applied to classes.
@Target(ElementType.METHOD)
-public @interface ViewChanged
-{
+public @interface ViewChanged {
}
Modified: core/branches/flat/src/main/java/org/horizon/notifications/event/CacheEntryActivatedEvent.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/notifications/event/CacheEntryActivatedEvent.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/notifications/event/CacheEntryActivatedEvent.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -27,6 +27,5 @@
* @author <a href="mailto:manik at jboss.org">Manik Surtani</a>
* @since 1.0
*/
-public interface CacheEntryActivatedEvent extends CacheEntryEvent
-{
+public interface CacheEntryActivatedEvent extends CacheEntryEvent {
}
Modified: core/branches/flat/src/main/java/org/horizon/notifications/event/CacheEntryCreatedEvent.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/notifications/event/CacheEntryCreatedEvent.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/notifications/event/CacheEntryCreatedEvent.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -27,6 +27,5 @@
* @author <a href="mailto:manik at jboss.org">Manik Surtani</a>
* @since 1.0
*/
-public interface CacheEntryCreatedEvent extends CacheEntryEvent
-{
+public interface CacheEntryCreatedEvent extends CacheEntryEvent {
}
Modified: core/branches/flat/src/main/java/org/horizon/notifications/event/CacheEntryEvent.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/notifications/event/CacheEntryEvent.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/notifications/event/CacheEntryEvent.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -27,8 +27,7 @@
* @author <a href="mailto:manik at jboss.org">Manik Surtani</a>
* @since 1.0
*/
-public interface CacheEntryEvent extends TransactionalEvent
-{
+public interface CacheEntryEvent extends TransactionalEvent {
/**
* @return the Fqn pointing to the node that is affected.
*/
Modified: core/branches/flat/src/main/java/org/horizon/notifications/event/CacheEntryEvictedEvent.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/notifications/event/CacheEntryEvictedEvent.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/notifications/event/CacheEntryEvictedEvent.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -27,6 +27,5 @@
* @author <a href="mailto:manik at jboss.org">Manik Surtani</a>
* @since 1.0
*/
-public interface CacheEntryEvictedEvent extends CacheEntryEvent
-{
+public interface CacheEntryEvictedEvent extends CacheEntryEvent {
}
Modified: core/branches/flat/src/main/java/org/horizon/notifications/event/CacheEntryInvalidatedEvent.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/notifications/event/CacheEntryInvalidatedEvent.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/notifications/event/CacheEntryInvalidatedEvent.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -27,6 +27,5 @@
* @author Manik Surtani (<a href="mailto:manik at jboss.org">manik at jboss.org</a>)
* @since 1.0
*/
-public interface CacheEntryInvalidatedEvent extends CacheEntryEvent
-{
+public interface CacheEntryInvalidatedEvent extends CacheEntryEvent {
}
Modified: core/branches/flat/src/main/java/org/horizon/notifications/event/CacheEntryLoadedEvent.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/notifications/event/CacheEntryLoadedEvent.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/notifications/event/CacheEntryLoadedEvent.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -27,6 +27,5 @@
* @author <a href="mailto:manik at jboss.org">Manik Surtani</a>
* @since 1.0
*/
-public interface CacheEntryLoadedEvent extends CacheEntryEvent
-{
+public interface CacheEntryLoadedEvent extends CacheEntryEvent {
}
Modified: core/branches/flat/src/main/java/org/horizon/notifications/event/CacheEntryModifiedEvent.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/notifications/event/CacheEntryModifiedEvent.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/notifications/event/CacheEntryModifiedEvent.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -27,6 +27,5 @@
* @author <a href="mailto:manik at jboss.org">Manik Surtani</a>
* @since 1.0
*/
-public interface CacheEntryModifiedEvent extends CacheEntryEvent
-{
+public interface CacheEntryModifiedEvent extends CacheEntryEvent {
}
Modified: core/branches/flat/src/main/java/org/horizon/notifications/event/CacheEntryPassivatedEvent.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/notifications/event/CacheEntryPassivatedEvent.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/notifications/event/CacheEntryPassivatedEvent.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -27,6 +27,5 @@
* @author <a href="mailto:manik at jboss.org">Manik Surtani</a>
* @since 1.0
*/
-public interface CacheEntryPassivatedEvent extends CacheEntryEvent
-{
+public interface CacheEntryPassivatedEvent extends CacheEntryEvent {
}
Modified: core/branches/flat/src/main/java/org/horizon/notifications/event/CacheEntryRemovedEvent.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/notifications/event/CacheEntryRemovedEvent.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/notifications/event/CacheEntryRemovedEvent.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -27,6 +27,5 @@
* @author <a href="mailto:manik at jboss.org">Manik Surtani</a>
* @since 1.0
*/
-public interface CacheEntryRemovedEvent extends CacheEntryEvent
-{
+public interface CacheEntryRemovedEvent extends CacheEntryEvent {
}
Modified: core/branches/flat/src/main/java/org/horizon/notifications/event/CacheEntryVisitedEvent.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/notifications/event/CacheEntryVisitedEvent.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/notifications/event/CacheEntryVisitedEvent.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -27,6 +27,5 @@
* @author <a href="mailto:manik at jboss.org">Manik Surtani</a>
* @since 1.0
*/
-public interface CacheEntryVisitedEvent extends CacheEntryEvent
-{
+public interface CacheEntryVisitedEvent extends CacheEntryEvent {
}
Modified: core/branches/flat/src/main/java/org/horizon/notifications/event/CacheStartedEvent.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/notifications/event/CacheStartedEvent.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/notifications/event/CacheStartedEvent.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -27,6 +27,5 @@
* @author <a href="mailto:manik at jboss.org">Manik Surtani</a>
* @since 1.0
*/
-public interface CacheStartedEvent extends Event
-{
+public interface CacheStartedEvent extends Event {
}
Modified: core/branches/flat/src/main/java/org/horizon/notifications/event/CacheStoppedEvent.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/notifications/event/CacheStoppedEvent.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/notifications/event/CacheStoppedEvent.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -27,6 +27,5 @@
* @author <a href="mailto:manik at jboss.org">Manik Surtani</a>
* @since 1.0
*/
-public interface CacheStoppedEvent extends Event
-{
+public interface CacheStoppedEvent extends Event {
}
Modified: core/branches/flat/src/main/java/org/horizon/notifications/event/Event.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/notifications/event/Event.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/notifications/event/Event.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -29,10 +29,8 @@
* @author <a href="mailto:manik at jboss.org">Manik Surtani</a>
* @since 1.0
*/
-public interface Event
-{
- static enum Type
- {
+public interface Event {
+ static enum Type {
CACHE_STARTED, CACHE_STOPPED, CACHE_ENTRY_ACTIVATED, CACHE_ENTRY_PASSIVATED, CACHE_ENTRY_VISITED,
CACHE_ENTRY_LOADED, CACHE_ENTRY_EVICTED, CACHE_ENTRY_CREATED, CACHE_ENTRY_REMOVED, CACHE_ENTRY_MODIFIED,
TRANSACTION_COMPLETED, TRANSACTION_REGISTERED, VIEW_CHANGED, BUDDY_GROUP_CHANGED, CACHE_ENTRY_INVALIDATED
Modified: core/branches/flat/src/main/java/org/horizon/notifications/event/EventImpl.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/notifications/event/EventImpl.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/notifications/event/EventImpl.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -34,10 +34,9 @@
* @since 1.0
*/
public class EventImpl implements CacheStartedEvent, CacheStoppedEvent,
- CacheEntryActivatedEvent, CacheEntryCreatedEvent, CacheEntryEvictedEvent, CacheEntryLoadedEvent, CacheEntryModifiedEvent,
- CacheEntryPassivatedEvent, CacheEntryRemovedEvent, CacheEntryVisitedEvent, TransactionCompletedEvent, TransactionRegisteredEvent,
- ViewChangedEvent, CacheEntryInvalidatedEvent
-{
+ CacheEntryActivatedEvent, CacheEntryCreatedEvent, CacheEntryEvictedEvent, CacheEntryLoadedEvent, CacheEntryModifiedEvent,
+ CacheEntryPassivatedEvent, CacheEntryRemovedEvent, CacheEntryVisitedEvent, TransactionCompletedEvent, TransactionRegisteredEvent,
+ ViewChangedEvent, CacheEntryInvalidatedEvent {
private boolean pre = false; // by default events are after the fact
private Cache cache;
private Object key;
@@ -48,8 +47,7 @@
private View newView;
private Type type;
- public EventImpl(boolean pre, Cache cache, Object key, Transaction transaction, boolean originLocal, Fqn targetFqn, boolean successful, View newView, Type type)
- {
+ public EventImpl(boolean pre, Cache cache, Object key, Transaction transaction, boolean originLocal, Fqn targetFqn, boolean successful, View newView, Type type) {
this.pre = pre;
this.cache = cache;
this.key = key;
@@ -61,105 +59,85 @@
this.type = type;
}
- public EventImpl()
- {
+ public EventImpl() {
}
- public Type getType()
- {
+ public Type getType() {
return type;
}
- public boolean isPre()
- {
+ public boolean isPre() {
return pre;
}
- public Cache getCache()
- {
+ public Cache getCache() {
return cache;
}
- public Object getKey()
- {
+ public Object getKey() {
return key;
}
- public Transaction getTransaction()
- {
+ public Transaction getTransaction() {
return transaction;
}
- public boolean isOriginLocal()
- {
+ public boolean isOriginLocal() {
return originLocal;
}
- public Fqn getTargetFqn()
- {
+ public Fqn getTargetFqn() {
return targetFqn;
}
- public boolean isSuccessful()
- {
+ public boolean isSuccessful() {
return successful;
}
- public View getNewView()
- {
+ public View getNewView() {
return newView;
}
// ------------------------------ setters -----------------------------
- public void setPre(boolean pre)
- {
+ public void setPre(boolean pre) {
this.pre = pre;
}
- public void setCache(Cache cache)
- {
+ public void setCache(Cache cache) {
this.cache = cache;
}
- public void setKey(Object key)
- {
+ public void setKey(Object key) {
this.key = key;
}
- public void setTransaction(Transaction transaction)
- {
+ public void setTransaction(Transaction transaction) {
this.transaction = transaction;
}
- public void setOriginLocal(boolean originLocal)
- {
+ public void setOriginLocal(boolean originLocal) {
this.originLocal = originLocal;
}
- public void setTargetFqn(Fqn targetFqn)
- {
+ public void setTargetFqn(Fqn targetFqn) {
this.targetFqn = targetFqn;
}
- public void setSuccessful(boolean successful)
- {
+ public void setSuccessful(boolean successful) {
this.successful = successful;
}
- public void setNewView(View newView)
- {
+ public void setNewView(View newView) {
this.newView = newView;
}
- public void setType(Type type)
- {
+ public void setType(Type type) {
this.type = type;
}
@Override
- public boolean equals(Object o)
- {
+ public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
@@ -179,8 +157,7 @@
}
@Override
- public int hashCode()
- {
+ public int hashCode() {
int result;
result = (pre ? 1 : 0);
result = 31 * result + (cache != null ? cache.hashCode() : 0);
@@ -196,8 +173,7 @@
@Override
- public String toString()
- {
+ public String toString() {
return "EventImpl{" +
"type=" + type +
",pre=" + pre +
Modified: core/branches/flat/src/main/java/org/horizon/notifications/event/TransactionCompletedEvent.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/notifications/event/TransactionCompletedEvent.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/notifications/event/TransactionCompletedEvent.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -24,17 +24,16 @@
/**
* This event is passed in to any method annotated with {@link org.horizon.notifications.annotation.TransactionCompleted}.
* <p/>
- * Note that this event is only delivered <i>after the fact</i>, i.e., you will never see an instance of this event
- * with {@link #isPre()} being set to <tt>true</tt>.
+ * Note that this event is only delivered <i>after the fact</i>, i.e., you will never see an instance of this event with
+ * {@link #isPre()} being set to <tt>true</tt>.
*
* @author <a href="mailto:manik at jboss.org">Manik Surtani</a>
* @since 1.0
*/
-public interface TransactionCompletedEvent extends TransactionalEvent
-{
+public interface TransactionCompletedEvent extends TransactionalEvent {
/**
- * @return if <tt>true</tt>, the transaction completed by committing successfully. If <tt>false</tt>, the transaction
- * completed with a rollback.
+ * @return if <tt>true</tt>, the transaction completed by committing successfully. If <tt>false</tt>, the
+ * transaction completed with a rollback.
*/
boolean isSuccessful();
}
Modified: core/branches/flat/src/main/java/org/horizon/notifications/event/TransactionRegisteredEvent.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/notifications/event/TransactionRegisteredEvent.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/notifications/event/TransactionRegisteredEvent.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -24,12 +24,11 @@
/**
* This event is passed in to any method annotated with {@link org.horizon.notifications.annotation.TransactionRegistered}.
* <p/>
- * Note that this event is only delivered <i>after the fact</i>, i.e., you will never see an instance of this event
- * with {@link #isPre()} being set to <tt>true</tt>.
+ * Note that this event is only delivered <i>after the fact</i>, i.e., you will never see an instance of this event with
+ * {@link #isPre()} being set to <tt>true</tt>.
*
* @author <a href="mailto:manik at jboss.org">Manik Surtani</a>
* @since 1.0
*/
-public interface TransactionRegisteredEvent extends TransactionalEvent
-{
+public interface TransactionRegisteredEvent extends TransactionalEvent {
}
Modified: core/branches/flat/src/main/java/org/horizon/notifications/event/TransactionalEvent.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/notifications/event/TransactionalEvent.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/notifications/event/TransactionalEvent.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -30,11 +30,10 @@
* @author <a href="mailto:manik at jboss.org">Manik Surtani</a>
* @since 1.0
*/
-public interface TransactionalEvent extends Event
-{
+public interface TransactionalEvent extends Event {
/**
- * @return the Transaction associated with the current call. May be null if the current call is outside the
- * scope of a transaction.
+ * @return the Transaction associated with the current call. May be null if the current call is outside the scope of
+ * a transaction.
*/
Transaction getTransaction();
Modified: core/branches/flat/src/main/java/org/horizon/notifications/event/ViewChangedEvent.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/notifications/event/ViewChangedEvent.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/notifications/event/ViewChangedEvent.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -29,8 +29,7 @@
* @author <a href="mailto:manik at jboss.org">Manik Surtani</a>
* @since 1.0
*/
-public interface ViewChangedEvent extends Event
-{
+public interface ViewChangedEvent extends Event {
/**
* @return the new view associated with this view change.
*/
Modified: core/branches/flat/src/main/java/org/horizon/remoting/ChannelMessageListener.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/remoting/ChannelMessageListener.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/remoting/ChannelMessageListener.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -48,11 +48,9 @@
* @since 1.0
*/
@NonVolatile
-public class ChannelMessageListener implements ExtendedMessageListener
-{
+public class ChannelMessageListener implements ExtendedMessageListener {
/**
- * Reference to an exception that was raised during
- * state installation on this node.
+ * Reference to an exception that was raised during state installation on this node.
*/
protected volatile Exception setStateException;
private final Object stateLock = new Object();
@@ -67,78 +65,57 @@
@Inject
- private void injectDependencies(StateTransferManager stateTransferManager, Configuration configuration)
- {
+ private void injectDependencies(StateTransferManager stateTransferManager, Configuration configuration) {
this.stateTransferManager = stateTransferManager;
this.configuration = configuration;
}
- public boolean isStateSet()
- {
+ public boolean isStateSet() {
return isStateSet;
}
- public void setStateSet(boolean stateSet)
- {
+ public void setStateSet(boolean stateSet) {
isStateSet = stateSet;
}
- public void waitForState() throws Exception
- {
- synchronized (stateLock)
- {
- while (!isStateSet)
- {
- if (setStateException != null)
- {
+ public void waitForState() throws Exception {
+ synchronized (stateLock) {
+ while (!isStateSet) {
+ if (setStateException != null) {
throw setStateException;
}
- try
- {
+ try {
stateLock.wait();
}
- catch (InterruptedException iex)
- {
+ catch (InterruptedException iex) {
}
}
}
}
- protected void stateReceivedSuccess()
- {
+ protected void stateReceivedSuccess() {
isStateSet = true;
setStateException = null;
}
- protected void stateReceivingFailed(Throwable t)
- {
- if (t instanceof CacheException)
- {
+ protected void stateReceivingFailed(Throwable t) {
+ if (t instanceof CacheException) {
log.debug(t);
- }
- else
- {
+ } else {
log.error("failed setting state", t);
}
- if (t instanceof Exception)
- {
+ if (t instanceof Exception) {
setStateException = (Exception) t;
- }
- else
- {
+ } else {
setStateException = new Exception(t);
}
}
- protected void stateProducingFailed(Throwable t)
- {
- if (t instanceof CacheException)
- {
+ protected void stateProducingFailed(Throwable t) {
+ if (t instanceof CacheException) {
log.debug(t);
- }
- else
- {
+ } else {
log.error("Caught " + t.getClass().getName()
+ " while responding to state transfer request", t);
}
@@ -147,173 +124,140 @@
/**
* Callback, does nothing.
*/
- public void receive(Message msg)
- {
+ public void receive(Message msg) {
}
- public byte[] getState()
- {
+ public byte[] getState() {
MarshalledValueOutputStream out = null;
byte[] result;
ExposedByteArrayOutputStream baos = new ExposedByteArrayOutputStream(16 * 1024);
- try
- {
+ try {
out = new MarshalledValueOutputStream(baos);
stateTransferManager.getState(out, Fqn.ROOT, configuration.getStateRetrievalTimeout(), true, true);
}
- catch (Throwable t)
- {
+ catch (Throwable t) {
stateProducingFailed(t);
}
- finally
- {
+ finally {
result = baos.getRawBuffer();
Util.close(out);
}
return result;
}
- public void setState(byte[] new_state)
- {
- if (new_state == null)
- {
+ public void setState(byte[] new_state) {
+ if (new_state == null) {
log.debug("transferred state is null (may be first member in cluster)");
return;
}
ByteArrayInputStream bais = new ByteArrayInputStream(new_state);
MarshalledValueInputStream in = null;
- try
- {
+ try {
in = new MarshalledValueInputStream(bais);
stateTransferManager.setState(in, Fqn.ROOT);
stateReceivedSuccess();
}
- catch (Throwable t)
- {
+ catch (Throwable t) {
stateReceivingFailed(t);
}
- finally
- {
+ finally {
Util.close(in);
- synchronized (stateLock)
- {
+ synchronized (stateLock) {
// Notify wait that state has been set.
stateLock.notifyAll();
}
}
}
- public byte[] getState(String state_id)
- {
+ public byte[] getState(String state_id) {
if (trace) log.trace("Getting state for state id " + state_id);
MarshalledValueOutputStream out = null;
String sourceRoot = state_id;
byte[] result;
boolean hasDifferentSourceAndIntegrationRoots = state_id.indexOf(DefaultStateTransferManager.PARTIAL_STATE_DELIMITER) > 0;
- if (hasDifferentSourceAndIntegrationRoots)
- {
+ if (hasDifferentSourceAndIntegrationRoots) {
sourceRoot = state_id.split(DefaultStateTransferManager.PARTIAL_STATE_DELIMITER)[0];
}
ExposedByteArrayOutputStream baos = new ExposedByteArrayOutputStream(16 * 1024);
- try
- {
+ try {
out = new MarshalledValueOutputStream(baos);
stateTransferManager.getState(out, Fqn.fromString(sourceRoot),
- configuration.getStateRetrievalTimeout(), true, true);
+ configuration.getStateRetrievalTimeout(), true, true);
}
- catch (Throwable t)
- {
+ catch (Throwable t) {
stateProducingFailed(t);
}
- finally
- {
+ finally {
result = baos.getRawBuffer();
Util.close(out);
}
return result;
}
- public void getState(OutputStream ostream)
- {
+ public void getState(OutputStream ostream) {
MarshalledValueOutputStream out = null;
- try
- {
+ try {
out = new MarshalledValueOutputStream(ostream);
stateTransferManager.getState(out, Fqn.ROOT, configuration.getStateRetrievalTimeout(), true, true);
}
- catch (Throwable t)
- {
+ catch (Throwable t) {
stateProducingFailed(t);
}
- finally
- {
+ finally {
Util.close(out);
}
}
- public void getState(String state_id, OutputStream ostream)
- {
+ public void getState(String state_id, OutputStream ostream) {
if (trace) log.trace("Getting state for state id " + state_id);
String sourceRoot = state_id;
MarshalledValueOutputStream out = null;
boolean hasDifferentSourceAndIntegrationRoots = state_id.indexOf(DefaultStateTransferManager.PARTIAL_STATE_DELIMITER) > 0;
- if (hasDifferentSourceAndIntegrationRoots)
- {
+ if (hasDifferentSourceAndIntegrationRoots) {
sourceRoot = state_id.split(DefaultStateTransferManager.PARTIAL_STATE_DELIMITER)[0];
}
- try
- {
+ try {
out = new MarshalledValueOutputStream(ostream);
stateTransferManager.getState(out, Fqn.fromString(sourceRoot), configuration.getStateRetrievalTimeout(), true, true);
}
- catch (Throwable t)
- {
+ catch (Throwable t) {
stateProducingFailed(t);
}
- finally
- {
+ finally {
Util.close(out);
}
}
- public void setState(InputStream istream)
- {
- if (istream == null)
- {
+ public void setState(InputStream istream) {
+ if (istream == null) {
log.debug("stream is null (may be first member in cluster)");
return;
}
MarshalledValueInputStream in = null;
- try
- {
+ try {
in = new MarshalledValueInputStream(istream);
stateTransferManager.setState(in, Fqn.ROOT);
stateReceivedSuccess();
}
- catch (Throwable t)
- {
+ catch (Throwable t) {
stateReceivingFailed(t);
}
- finally
- {
+ finally {
Util.close(in);
- synchronized (stateLock)
- {
+ synchronized (stateLock) {
// Notify wait that state has been set.
stateLock.notifyAll();
}
}
}
- public void setState(String state_id, byte[] state)
- {
+ public void setState(String state_id, byte[] state) {
if (trace) log.trace("Receiving state for " + state_id);
- if (state == null)
- {
+ if (state == null) {
log.debug("partial transferred state is null");
return;
}
@@ -321,12 +265,10 @@
MarshalledValueInputStream in = null;
String targetRoot = state_id;
boolean hasDifferentSourceAndIntegrationRoots = state_id.indexOf(DefaultStateTransferManager.PARTIAL_STATE_DELIMITER) > 0;
- if (hasDifferentSourceAndIntegrationRoots)
- {
+ if (hasDifferentSourceAndIntegrationRoots) {
targetRoot = state_id.split(DefaultStateTransferManager.PARTIAL_STATE_DELIMITER)[1];
}
- try
- {
+ try {
log.debug("Setting received partial state for subroot " + state_id);
Fqn subroot = Fqn.fromString(targetRoot);
// Region region = evictionCacheManager.getRegion(subroot, false);
@@ -342,39 +284,32 @@
stateTransferManager.setState(in, subroot);
stateReceivedSuccess();
}
- catch (Throwable t)
- {
+ catch (Throwable t) {
stateReceivingFailed(t);
}
- finally
- {
+ finally {
Util.close(in);
- synchronized (stateLock)
- {
+ synchronized (stateLock) {
// Notify wait that state has been set.
stateLock.notifyAll();
}
}
}
- public void setState(String stateId, InputStream istream)
- {
+ public void setState(String stateId, InputStream istream) {
if (trace) log.trace("Receiving state for " + stateId);
String targetRoot = stateId;
MarshalledValueInputStream in = null;
boolean hasDifferentSourceAndIntegrationRoots = stateId.indexOf(DefaultStateTransferManager.PARTIAL_STATE_DELIMITER) > 0;
- if (hasDifferentSourceAndIntegrationRoots)
- {
+ if (hasDifferentSourceAndIntegrationRoots) {
targetRoot = stateId.split(DefaultStateTransferManager.PARTIAL_STATE_DELIMITER)[1];
}
- if (istream == null)
- {
+ if (istream == null) {
log.debug("stream is null (may be first member in cluster). State is not set");
return;
}
- try
- {
+ try {
log.debug("Setting received partial state for subroot " + stateId);
in = new MarshalledValueInputStream(istream);
Fqn subroot = Fqn.fromString(targetRoot);
@@ -389,16 +324,13 @@
stateTransferManager.setState(in, subroot);
stateReceivedSuccess();
}
- catch (Throwable t)
- {
+ catch (Throwable t) {
if (log.isTraceEnabled()) log.trace("Unknown error while integrating state", t);
stateReceivingFailed(t);
}
- finally
- {
+ finally {
Util.close(in);
- synchronized (stateLock)
- {
+ synchronized (stateLock) {
// Notify wait that state has been set.
stateLock.notifyAll();
}
Modified: core/branches/flat/src/main/java/org/horizon/remoting/RPCManager.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/remoting/RPCManager.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/remoting/RPCManager.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -32,22 +32,18 @@
import java.util.Vector;
/**
- * Provides a mechanism for communicating with other caches in the cluster. For now this is based on JGroups as an underlying
- * transport, and in future more transport options may become available.
+ * Provides a mechanism for communicating with other caches in the cluster. For now this is based on JGroups as an
+ * underlying transport, and in future more transport options may become available.
* <p/>
- * Implementations have a simple lifecycle:
- * <ul>
- * <li>start() - starts the underlying channel based on configuration options injected, and connects the channel</li>
- * <li>disconnect() - disconnects the channel</li>
- * <li>stop() - stops the dispatcher and releases resources</li>
- * </ul>
+ * Implementations have a simple lifecycle: <ul> <li>start() - starts the underlying channel based on configuration
+ * options injected, and connects the channel</li> <li>disconnect() - disconnects the channel</li> <li>stop() - stops
+ * the dispatcher and releases resources</li> </ul>
*
* @author Manik Surtani
* @since 1.0
*/
@Scope(Scopes.GLOBAL)
-public interface RPCManager
-{
+public interface RPCManager {
/**
* Disconnects and closes the underlying JGroups channel.
*/
@@ -69,7 +65,8 @@
/**
* Invokes an RPC call on other caches in the cluster.
*
- * @param recipients a list of Addresses to invoke the call on. If this is null, the call is broadcast to the entire cluster.
+ * @param recipients a list of Addresses to invoke the call on. If this is null, the call is broadcast to
+ * the entire cluster.
* @param cacheCommand the cache command to invoke
* @param mode the group request mode to use. See {@link org.jgroups.blocks.GroupRequest}.
* @param timeout a timeout after which to throw a replication exception.
@@ -83,7 +80,8 @@
/**
* Invokes an RPC call on other caches in the cluster.
*
- * @param recipients a list of Addresses to invoke the call on. If this is null, the call is broadcast to the entire cluster.
+ * @param recipients a list of Addresses to invoke the call on. If this is null, the call is broadcast to
+ * the entire cluster.
* @param cacheCommand the cache command to invoke
* @param mode the group request mode to use. See {@link org.jgroups.blocks.GroupRequest}.
* @param timeout a timeout after which to throw a replication exception.
@@ -96,9 +94,11 @@
/**
* Invokes an RPC call on other caches in the cluster.
*
- * @param recipients a list of Addresses to invoke the call on. If this is null, the call is broadcast to the entire cluster.
+ * @param recipients a list of Addresses to invoke the call on. If this is null, the call is broadcast to
+ * the entire cluster.
* @param cacheCommand the cache command to invoke
- * @param synchronous if true, sets group request mode to {@link org.jgroups.blocks.GroupRequest#GET_ALL}, and if false sets it to {@link org.jgroups.blocks.GroupRequest#GET_NONE}.
+ * @param synchronous if true, sets group request mode to {@link org.jgroups.blocks.GroupRequest#GET_ALL},
+ * and if false sets it to {@link org.jgroups.blocks.GroupRequest#GET_NONE}.
* @param timeout a timeout after which to throw a replication exception.
* @param useOutOfBandMessage if true, the message is put on JGroups' OOB queue. See JGroups docs for more info.
* @return a list of responses from each member contacted.
Modified: core/branches/flat/src/main/java/org/horizon/remoting/RPCManagerImpl.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/remoting/RPCManagerImpl.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/remoting/RPCManagerImpl.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -25,6 +25,9 @@
import org.apache.commons.logging.LogFactory;
import org.horizon.CacheException;
import org.horizon.CacheSPI;
+import org.horizon.annotations.MBean;
+import org.horizon.annotations.ManagedAttribute;
+import org.horizon.annotations.ManagedOperation;
import org.horizon.commands.ReplicableCommand;
import org.horizon.config.Configuration;
import org.horizon.config.RuntimeConfig;
@@ -35,9 +38,6 @@
import org.horizon.factories.annotations.Stop;
import org.horizon.interceptors.InterceptorChain;
import org.horizon.invocation.InvocationContextContainer;
-import org.horizon.annotations.MBean;
-import org.horizon.annotations.ManagedAttribute;
-import org.horizon.annotations.ManagedOperation;
import org.horizon.lock.LockManager;
import org.horizon.lock.TimeoutException;
import org.horizon.marshall.CommandAwareRpcDispatcher;
@@ -46,7 +46,13 @@
import org.horizon.transaction.TransactionTable;
import org.horizon.util.ReflectionUtil;
import org.horizon.util.concurrent.ReclosableLatch;
-import org.jgroups.*;
+import org.jgroups.Address;
+import org.jgroups.Channel;
+import org.jgroups.ChannelException;
+import org.jgroups.ChannelFactory;
+import org.jgroups.ExtendedMembershipListener;
+import org.jgroups.JChannel;
+import org.jgroups.View;
import org.jgroups.blocks.GroupRequest;
import org.jgroups.blocks.RspFilter;
import org.jgroups.protocols.TP;
@@ -69,8 +75,7 @@
* @since 1.0
*/
@MBean(objectName = "RPCManager")
-public class RPCManagerImpl implements RPCManager
-{
+public class RPCManagerImpl implements RPCManager {
private Channel channel;
private final Log log = LogFactory.getLog(RPCManagerImpl.class);
private List<Address> members;
@@ -114,8 +119,7 @@
public void setupDependencies(ChannelMessageListener messageListener, Configuration configuration, Notifier notifier,
Marshaller extendedMarshaller, TransactionTable txTable,
TransactionManager txManager, InvocationContextContainer container, InterceptorChain interceptorChain,
- ComponentRegistry componentRegistry, LockManager lockManager, CacheSPI spi)
- {
+ ComponentRegistry componentRegistry, LockManager lockManager, CacheSPI spi) {
this.messageListener = messageListener;
this.configuration = configuration;
this.notifier = notifier;
@@ -132,10 +136,8 @@
// ------------ START: Lifecycle methods ------------
@Start(priority = 15)
- public void start()
- {
- if (configuration.getCacheMode().equals(Configuration.CacheMode.LOCAL))
- {
+ public void start() {
+ if (configuration.getCacheMode().equals(Configuration.CacheMode.LOCAL)) {
log.debug("cache mode is local, will not create the channel");
isInLocalMode = true;
return;
@@ -146,21 +148,17 @@
initialiseChannelAndRpcDispatcher();
//otherwise just connect
- try
- {
+ try {
channel.connect(configuration.getClusterName());
}
- catch (ChannelException e)
- {
+ catch (ChannelException e) {
throw new CacheException("Unable to connect to JGroups channel", e);
}
if (log.isInfoEnabled()) log.info("Cache local address is " + getLocalAddress());
}
- public void disconnect()
- {
- if (channel != null && channel.isOpen())
- {
+ public void disconnect() {
+ if (channel != null && channel.isOpen()) {
log.info("Disconnecting and closing the Channel");
channel.disconnect();
channel.close();
@@ -168,21 +166,17 @@
}
@Stop(priority = 8)
- public void stop()
- {
- try
- {
+ public void stop() {
+ try {
disconnect();
}
- catch (Exception toLog)
- {
+ catch (Exception toLog) {
log.error("Problem closing channel; setting it to null", toLog);
}
channel = null;
configuration.getRuntimeConfig().setChannel(null);
- if (rpcDispatcher != null)
- {
+ if (rpcDispatcher != null) {
log.info("Stopping the RpcDispatcher");
rpcDispatcher.stop();
}
@@ -195,8 +189,7 @@
}
@SuppressWarnings("deprecation")
- private void initialiseChannelAndRpcDispatcher() throws CacheException
- {
+ private void initialiseChannelAndRpcDispatcher() throws CacheException {
buildChannel();
// Channel.LOCAL *must* be set to false so we don't see our own messages - otherwise invalidations targeted at
// remote instances will be received by self.
@@ -205,47 +198,36 @@
channel.setOpt(Channel.AUTO_GETSTATE, false);
channel.setOpt(Channel.BLOCK, true);
rpcDispatcher = new CommandAwareRpcDispatcher(channel, messageListener, new MembershipListenerAdaptor(),
- invocationContextContainer, invocationContextContainer, interceptorChain, componentRegistry);
+ invocationContextContainer, invocationContextContainer, interceptorChain, componentRegistry);
checkAppropriateConfig();
rpcDispatcher.setRequestMarshaller(marshaller);
rpcDispatcher.setResponseMarshaller(marshaller);
}
- private void buildChannel()
- {
+ private void buildChannel() {
channel = configuration.getRuntimeConfig().getChannel();
- if (channel == null)
- {
+ if (channel == null) {
// Try to create a multiplexer channel
channel = getMultiplexerChannel();
- if (channel != null)
- {
+ if (channel != null) {
ReflectionUtil.setValue(configuration, "accessible", true);
configuration.setUsingMultiplexer(true);
if (log.isDebugEnabled())
log.debug("Created Multiplexer Channel for cache cluster " + configuration.getClusterName() + " using stack " + configuration.getMultiplexerStack());
- }
- else
- {
- try
- {
- if (configuration.getClusterConfig() == null)
- {
+ } else {
+ try {
+ if (configuration.getClusterConfig() == null) {
log.debug("setting cluster properties to default value");
channel = new JChannel(configuration.getDefaultClusterConfig());
- }
- else
- {
- if (trace)
- {
+ } else {
+ if (trace) {
log.trace("Cache cluster properties: " + configuration.getClusterConfig());
}
channel = new JChannel(configuration.getClusterConfig());
}
}
- catch (ChannelException e)
- {
+ catch (ChannelException e) {
throw new CacheException(e);
}
}
@@ -254,28 +236,23 @@
}
}
- public Channel getChannel()
- {
+ public Channel getChannel() {
return channel;
}
- private JChannel getMultiplexerChannel() throws CacheException
- {
+ private JChannel getMultiplexerChannel() throws CacheException {
String stackName = configuration.getMultiplexerStack();
RuntimeConfig rtc = configuration.getRuntimeConfig();
ChannelFactory channelFactory = rtc.getMuxChannelFactory();
JChannel muxchannel = null;
- if (channelFactory != null)
- {
- try
- {
+ if (channelFactory != null) {
+ try {
muxchannel = (JChannel) channelFactory.createMultiplexerChannel(stackName, configuration.getClusterName());
}
- catch (Exception e)
- {
+ catch (Exception e) {
throw new CacheException("Failed to create multiplexed channel using stack " + stackName, e);
}
}
@@ -325,28 +302,23 @@
// ------------ END: Lifecycle methods ------------
// ------------ START: RPC call methods ------------
- public List<Object> callRemoteMethods(Vector<Address> recipients, ReplicableCommand command, int mode, long timeout, boolean useOutOfBandMessage) throws Exception
- {
+ public List<Object> callRemoteMethods(Vector<Address> recipients, ReplicableCommand command, int mode, long timeout, boolean useOutOfBandMessage) throws Exception {
return callRemoteMethods(recipients, command, mode, timeout, null, useOutOfBandMessage);
}
- public List<Object> callRemoteMethods(Vector<Address> recipients, ReplicableCommand command, boolean synchronous, long timeout, boolean useOutOfBandMessage) throws Exception
- {
+ public List<Object> callRemoteMethods(Vector<Address> recipients, ReplicableCommand command, boolean synchronous, long timeout, boolean useOutOfBandMessage) throws Exception {
return callRemoteMethods(recipients, command, synchronous ? GroupRequest.GET_ALL : GroupRequest.GET_NONE, timeout, useOutOfBandMessage);
}
- public List<Object> callRemoteMethods(Vector<Address> recipients, ReplicableCommand command, int mode, long timeout, RspFilter responseFilter, boolean useOutOfBandMessage) throws Exception
- {
+ public List<Object> callRemoteMethods(Vector<Address> recipients, ReplicableCommand command, int mode, long timeout, RspFilter responseFilter, boolean useOutOfBandMessage) throws Exception {
boolean success = true;
- try
- {
+ try {
// short circuit if we don't have an RpcDispatcher!
if (rpcDispatcher == null) return null;
int modeToUse = mode;
if (trace)
log.trace("callRemoteMethods(): valid members are " + recipients + " methods: " + command + " Using OOB? " + useOutOfBandMessage);
- if (channel.flushSupported())
- {
+ if (channel.flushSupported()) {
if (!flushBlockGate.await(configuration.getStateRetrievalTimeout(), TimeUnit.MILLISECONDS))
throw new TimeoutException("State retrieval timed out waiting for flush unblock.");
}
@@ -358,27 +330,19 @@
// short-circuit no-return-value calls.
if (rsps == null) return Collections.emptyList();
List<Object> retval = new ArrayList<Object>(rsps.size());
- for (Rsp rsp : rsps.values())
- {
- if (rsp.wasSuspected() || !rsp.wasReceived())
- {
+ for (Rsp rsp : rsps.values()) {
+ if (rsp.wasSuspected() || !rsp.wasReceived()) {
CacheException ex;
- if (rsp.wasSuspected())
- {
+ if (rsp.wasSuspected()) {
ex = new SuspectException("Suspected member: " + rsp.getSender());
- }
- else
- {
+ } else {
ex = new TimeoutException("Replication timeout for " + rsp.getSender());
}
retval.add(new ReplicationException("rsp=" + rsp, ex));
success = false;
- }
- else
- {
+ } else {
Object value = rsp.getValue();
- if (value instanceof Exception && !(value instanceof ReplicationException))
- {
+ if (value instanceof Exception && !(value instanceof ReplicationException)) {
// if we have any application-level exceptions make sure we throw them!!
if (trace) log.trace("Recieved exception'" + value + "' from " + rsp.getSender());
throw (Exception) value;
@@ -389,13 +353,11 @@
}
return retval;
}
- catch (Exception e)
- {
+ catch (Exception e) {
success = false;
throw e;
}
- finally
- {
+ finally {
computeStats(success);
}
}
@@ -404,13 +366,11 @@
// ------------ START: Informational methods ------------
- public Address getLocalAddress()
- {
+ public Address getLocalAddress() {
return channel != null ? channel.getLocalAddress() : null;
}
- public List<Address> getMembers()
- {
+ public List<Address> getMembers() {
if (isInLocalMode) return null;
if (members == null)
return Collections.emptyList();
@@ -418,29 +378,22 @@
return members;
}
- public boolean isCoordinator()
- {
+ public boolean isCoordinator() {
return coordinator;
}
- public Address getCoordinator()
- {
- if (channel == null)
- {
+ public Address getCoordinator() {
+ if (channel == null) {
return null;
}
- synchronized (coordinatorLock)
- {
- while (members == null || members.isEmpty())
- {
+ synchronized (coordinatorLock) {
+ while (members == null || members.isEmpty()) {
log.debug("getCoordinator(): waiting on viewAccepted()");
- try
- {
+ try {
coordinatorLock.wait();
}
- catch (InterruptedException e)
- {
+ catch (InterruptedException e) {
log.error("getCoordinator(): Interrupted while waiting for members to be set", e);
break;
}
@@ -453,20 +406,15 @@
/*----------------------- MembershipListener ------------------------*/
- protected class MembershipListenerAdaptor implements ExtendedMembershipListener
- {
+ protected class MembershipListenerAdaptor implements ExtendedMembershipListener {
- public void viewAccepted(View newView)
- {
+ public void viewAccepted(View newView) {
Vector<Address> newMembers = newView.getMembers();
if (log.isInfoEnabled()) log.info("Received new cluster view: " + newView);
- synchronized (coordinatorLock)
- {
+ synchronized (coordinatorLock) {
boolean needNotification = false;
- if (newMembers != null)
- {
- if (members != null)
- {
+ if (newMembers != null) {
+ if (members != null) {
// we had a membership list before this event. Check to make sure we haven't lost any members,
// and if so, determine what members have been removed
// and roll back any tx and break any locks
@@ -491,8 +439,7 @@
coordinator = (members != null && members.size() != 0 && members.get(0).equals(getLocalAddress()));
// now notify listeners - *after* updating the coordinator. - JBCACHE-662
- if (needNotification && notifier != null)
- {
+ if (needNotification && notifier != null) {
InvocationContext ctx = invocationContextContainer.get();
notifier.notifyViewChange(newView, ctx);
}
@@ -505,15 +452,13 @@
/**
* Called when a member is suspected.
*/
- public void suspect(Address suspected_mbr)
- {
+ public void suspect(Address suspected_mbr) {
}
/**
* Indicates that a channel has received a BLOCK event from FLUSH protocol.
*/
- public void block()
- {
+ public void block() {
flushBlockGate.close();
if (log.isDebugEnabled()) log.debug("Block received at " + getLocalAddress());
@@ -523,8 +468,7 @@
/**
* Indicates that a channel has received a UNBLOCK event from FLUSH protocol.
*/
- public void unblock()
- {
+ public void unblock() {
if (log.isDebugEnabled()) log.debug("UnBlock received at " + getLocalAddress());
if (log.isDebugEnabled()) log.debug("UnBlock processed at " + getLocalAddress());
flushBlockGate.open();
@@ -533,57 +477,45 @@
}
//jmx operations
- private void computeStats(boolean success)
- {
- if (statisticsEnabled && rpcDispatcher != null)
- {
- if (success)
- {
+ private void computeStats(boolean success) {
+ if (statisticsEnabled && rpcDispatcher != null) {
+ if (success) {
replicationCount++;
- }
- else
- {
+ } else {
replicationFailures++;
}
}
}
@ManagedOperation
- public void resetStatistics()
- {
+ public void resetStatistics() {
this.replicationCount = 0;
this.replicationFailures = 0;
}
@ManagedAttribute(description = "number of successful replications")
- public long getReplicationCount()
- {
+ public long getReplicationCount() {
return replicationCount;
}
@ManagedAttribute(description = "number of failed replications")
- public long getReplicationFailures()
- {
+ public long getReplicationFailures() {
return replicationFailures;
}
@ManagedAttribute(description = "whether or not jmx statistics are enabled")
- public boolean isStatisticsEnabled()
- {
+ public boolean isStatisticsEnabled() {
return statisticsEnabled;
}
@ManagedAttribute
- public void setStatisticsEnabled(boolean statisticsEnabled)
- {
+ public void setStatisticsEnabled(boolean statisticsEnabled) {
this.statisticsEnabled = statisticsEnabled;
}
@ManagedAttribute
- public String getSuccessRatio()
- {
- if (replicationCount == 0 || !statisticsEnabled)
- {
+ public String getSuccessRatio() {
+ if (replicationCount == 0 || !statisticsEnabled) {
return "N/A";
}
double totalCount = replicationCount + replicationFailures;
@@ -594,30 +526,25 @@
/**
* Checks to see whether the cache is using an appropriate JGroups config.
*/
- private void checkAppropriateConfig()
- {
+ private void checkAppropriateConfig() {
//if we use a shared transport do not log any warn message
if (configuration.getMultiplexerStack() != null)
return;
//bundling is not good for sync caches
Configuration.CacheMode cacheMode = configuration.getCacheMode();
- if (!cacheMode.equals(Configuration.CacheMode.LOCAL) && configuration.getCacheMode().isSynchronous())
- {
+ if (!cacheMode.equals(Configuration.CacheMode.LOCAL) && configuration.getCacheMode().isSynchronous()) {
ProtocolStack stack = ((JChannel) channel).getProtocolStack();
TP transport = stack.getTransport();
- if (transport.isEnableBundling())
- {
+ if (transport.isEnableBundling()) {
log.warn("You have enabled jgroups's message bundling, which is not recommended for sync replication. If there is no particular " +
"reason for this we strongly recommend to disable message bundling in JGroups config (enable_bundling=\"false\").");
}
}
//bundling is good for async caches
- if (!cacheMode.isSynchronous())
- {
+ if (!cacheMode.isSynchronous()) {
ProtocolStack stack = ((JChannel) channel).getProtocolStack();
TP transport = stack.getTransport();
- if (!transport.isEnableBundling())
- {
+ if (!transport.isEnableBundling()) {
log.warn("You have disabled jgroups's message bundling, which is not recommended for async replication. If there is no particular " +
"reason for this we strongly recommend to enable message bundling in JGroups config (enable_bundling=\"true\").");
}
Modified: core/branches/flat/src/main/java/org/horizon/remoting/ReplicationException.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/remoting/ReplicationException.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/remoting/ReplicationException.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -25,37 +25,32 @@
/**
* Thrown when a replication problem occurred
- * @since 1.0
+ *
* @author (various)
+ * @since 1.0
*/
-public class ReplicationException extends CacheException
-{
+public class ReplicationException extends CacheException {
private static final long serialVersionUID = 33172388691879866L;
- public ReplicationException()
- {
+ public ReplicationException() {
super();
}
- public ReplicationException(Throwable cause)
- {
+ public ReplicationException(Throwable cause) {
super(cause);
}
- public ReplicationException(String msg)
- {
+ public ReplicationException(String msg) {
super(msg);
}
- public ReplicationException(String msg, Throwable cause)
- {
+ public ReplicationException(String msg, Throwable cause) {
super(msg, cause);
}
@Override
- public String toString()
- {
+ public String toString() {
return super.toString();
}
}
\ No newline at end of file
Modified: core/branches/flat/src/main/java/org/horizon/remoting/SuspectException.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/remoting/SuspectException.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/remoting/SuspectException.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -27,26 +27,21 @@
* Thrown when a member is suspected during remote method invocation
*
* @author Bela Ban
- *
* @since 1.0
*/
-public class SuspectException extends CacheException
-{
+public class SuspectException extends CacheException {
private static final long serialVersionUID = -2965599037371850141L;
- public SuspectException()
- {
+ public SuspectException() {
super();
}
- public SuspectException(String msg)
- {
+ public SuspectException(String msg) {
super(msg);
}
- public SuspectException(String msg, Throwable cause)
- {
+ public SuspectException(String msg, Throwable cause) {
super(msg, cause);
}
}
Modified: core/branches/flat/src/main/java/org/horizon/remoting/transport/Address.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/remoting/transport/Address.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/remoting/transport/Address.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -6,6 +6,5 @@
* @author Manik Surtani
* @since 1.0
*/
-public interface Address
-{
+public interface Address {
}
Modified: core/branches/flat/src/main/java/org/horizon/remoting/transport/Transport.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/remoting/transport/Transport.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/remoting/transport/Transport.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -11,8 +11,7 @@
* @author Manik Surtani
* @since 1.0
*/
-public interface Transport extends Lifecycle
-{
+public interface Transport extends Lifecycle {
void setProperties(Properties p);
Address getAddress();
Modified: core/branches/flat/src/main/java/org/horizon/statetransfer/DefaultStateTransferManager.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/statetransfer/DefaultStateTransferManager.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/statetransfer/DefaultStateTransferManager.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -37,13 +37,12 @@
import java.io.ObjectOutputStream;
/**
- * The default state transfer manager to be used when using MVCC locking.
- * // TODO: implement me
- * @since 1.0
+ * The default state transfer manager to be used when using MVCC locking. // TODO: implement me
+ *
* @author (various)
+ * @since 1.0
*/
-public class DefaultStateTransferManager implements StateTransferManager
-{
+public class DefaultStateTransferManager implements StateTransferManager {
protected final static Log log = LogFactory.getLog(DefaultStateTransferManager.class);
protected static final boolean trace = log.isTraceEnabled();
@@ -53,7 +52,7 @@
protected CacheSPI cache;
protected Marshaller marshaller;
-// protected RegionManager regionManager;
+ // protected RegionManager regionManager;
protected Configuration configuration;
private CacheLoaderManager cacheLoaderManager;
boolean fetchTransientState;
@@ -64,8 +63,7 @@
@Inject
- public void injectDependencies()
- {
+ public void injectDependencies() {
this.cache = cache;
// this.regionManager = regionManager;
this.marshaller = marshaller;
@@ -76,15 +74,13 @@
}
@Start(priority = 14)
- public void start()
- {
+ public void start() {
// fetchTransientState = configuration.isFetchInMemoryState();
// fetchPersistentState = cacheLoaderManager != null && cacheLoaderManager.isFetchPersistentState();
// stateRetrievalTimeout = configuration.getStateRetrievalTimeout();
}
- public void getState(ObjectOutputStream out, Fqn fqn, long timeout, boolean force, boolean suppressErrors) throws Exception
- {
+ public void getState(ObjectOutputStream out, Fqn fqn, long timeout, boolean force, boolean suppressErrors) throws Exception {
throw new UnsupportedOperationException("Implement me properly!");
/*
@@ -135,8 +131,7 @@
*/
}
- public void setState(ObjectInputStream in, Fqn targetRoot) throws Exception
- {
+ public void setState(ObjectInputStream in, Fqn targetRoot) throws Exception {
throw new UnsupportedOperationException("fix me!");
/*
cache.getInvocationContext().getOptionOverrides().setSkipCacheStatusCheck(true);
@@ -167,17 +162,14 @@
}
/**
- * Set the portion of the cache rooted in <code>targetRoot</code>
- * to match the given state. Updates the contents of <code>targetRoot</code>
- * to reflect those in <code>new_state</code>.
+ * Set the portion of the cache rooted in <code>targetRoot</code> to match the given state. Updates the contents of
+ * <code>targetRoot</code> to reflect those in <code>new_state</code>.
* <p/>
- * <strong>NOTE:</strong> This method performs no locking of nodes; it
- * is up to the caller to lock <code>targetRoot</code> before calling
- * this method.
+ * <strong>NOTE:</strong> This method performs no locking of nodes; it is up to the caller to lock
+ * <code>targetRoot</code> before calling this method.
*
- * @param state a serialized byte[][] array where element 0 is the
- * transient state (or null) , and element 1 is the
- * persistent state (or null)
+ * @param state a serialized byte[][] array where element 0 is the transient state (or null) , and element 1 is
+ * the persistent state (or null)
* @param targetRoot node into which the state should be integrated
*/
// TODO: implement me
Modified: core/branches/flat/src/main/java/org/horizon/statetransfer/StateTransferManager.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/statetransfer/StateTransferManager.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/statetransfer/StateTransferManager.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -29,43 +29,38 @@
/**
* This interface handles requests to generate or integrate state from neighbouring caches in a cluster.
* <p/>
- * This has existed prior to 3.0.0 as a concrete class. An interface was introduced in 3.0.0 to provide more flexibility
- * in state transfer implementations.
+ * This has existed prior to 3.0.0 as a concrete class. An interface was introduced in 3.0.0 to provide more
+ * flexibility in state transfer implementations.
* <p/>
*
* @author Manik Surtani (<a href="mailto:manik at jboss.org">manik at jboss.org</a>)
* @since 1.0
*/
-public interface StateTransferManager
-{
+public interface StateTransferManager {
/**
- * Writes the state for the portion of the tree named by <code>fqn</code> to
- * the provided OutputStream.
+ * Writes the state for the portion of the tree named by <code>fqn</code> to the provided OutputStream.
* <p/>
* <p/>
*
* @param out stream to write state to
- * @param fqn Fqn indicating the uppermost node in the
- * portion of the tree whose state should be returned.
- * @param timeout max number of millis this method should wait to acquire
- * any locks, if necessary, on the nodes being transferred
- * @param force if locks are needed and cannot be acquired after
- * <code>timeout</code> millis, should the lock acquisition
- * be forced, and any existing transactions holding locks
- * on the nodes be rolled back?
+ * @param fqn Fqn indicating the uppermost node in the portion of the tree whose state should be
+ * returned.
+ * @param timeout max number of millis this method should wait to acquire any locks, if necessary, on the
+ * nodes being transferred
+ * @param force if locks are needed and cannot be acquired after <code>timeout</code> millis, should the
+ * lock acquisition be forced, and any existing transactions holding locks on the nodes be
+ * rolled back?
* @param suppressErrors if true, all exceptions are logged but not propagated.
* @throws Exception in event of error
*/
void getState(ObjectOutputStream out, Fqn fqn, long timeout, boolean force, boolean suppressErrors) throws Exception;
/**
- * Set the portion of the cache rooted in <code>targetRoot</code>
- * to match the given state. Updates the contents of <code>targetRoot</code>
- * to reflect those in <code>new_state</code>.
+ * Set the portion of the cache rooted in <code>targetRoot</code> to match the given state. Updates the contents of
+ * <code>targetRoot</code> to reflect those in <code>new_state</code>.
* <p/>
- * <strong>NOTE:</strong> This method performs no locking of nodes; it
- * is up to the caller to lock <code>targetRoot</code> before calling
- * this method.
+ * <strong>NOTE:</strong> This method performs no locking of nodes; it is up to the caller to lock
+ * <code>targetRoot</code> before calling this method.
* <p/>
*
* @param in an input stream containing the state
Modified: core/branches/flat/src/main/java/org/horizon/transaction/BatchModeTransactionManager.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/transaction/BatchModeTransactionManager.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/transaction/BatchModeTransactionManager.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -29,28 +29,23 @@
* transactional symantics of rollbacks and recovery are NOT used here. This is used by PojoCache.
*
* @author bela
- *
- * Date: May 15, 2003
- * Time: 4:11:37 PM
+ * <p/>
+ * Date: May 15, 2003 Time: 4:11:37 PM
* @since 1.0
*/
-public class BatchModeTransactionManager extends DummyBaseTransactionManager
-{
+public class BatchModeTransactionManager extends DummyBaseTransactionManager {
static BatchModeTransactionManager instance = null;
static Log log = LogFactory.getLog(BatchModeTransactionManager.class);
private static final long serialVersionUID = 5656602677430350961L;
- public static BatchModeTransactionManager getInstance()
- {
- if (instance == null)
- {
+ public static BatchModeTransactionManager getInstance() {
+ if (instance == null) {
instance = new BatchModeTransactionManager();
}
return instance;
}
- public static void destroy()
- {
+ public static void destroy() {
if (instance == null) return;
instance.setTransaction(null);
instance = null;
Modified: core/branches/flat/src/main/java/org/horizon/transaction/DummyBaseTransactionManager.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/transaction/DummyBaseTransactionManager.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/transaction/DummyBaseTransactionManager.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -24,17 +24,23 @@
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
-import javax.transaction.*;
+import javax.transaction.HeuristicMixedException;
+import javax.transaction.HeuristicRollbackException;
+import javax.transaction.InvalidTransactionException;
+import javax.transaction.NotSupportedException;
+import javax.transaction.RollbackException;
+import javax.transaction.Status;
+import javax.transaction.SystemException;
+import javax.transaction.Transaction;
+import javax.transaction.TransactionManager;
/**
* @author bela
- *
- * Date: May 15, 2003
- * Time: 4:11:37 PM
+ * <p/>
+ * Date: May 15, 2003 Time: 4:11:37 PM
* @since 1.0
*/
-public class DummyBaseTransactionManager implements TransactionManager, java.io.Serializable
-{
+public class DummyBaseTransactionManager implements TransactionManager, java.io.Serializable {
static ThreadLocal<Transaction> thread_local = new ThreadLocal<Transaction>();
private static final long serialVersionUID = -6716097342564237376l;
private static final Log log = LogFactory.getLog(DummyBaseTransactionManager.class);
@@ -44,15 +50,12 @@
* Starts a new transaction, and associate it with the calling thread.
*
* @throws javax.transaction.NotSupportedException
- * If the calling thread is already
- * associated with a transaction, and nested transactions are
- * not supported.
+ * If the calling thread is already associated with a transaction, and nested transactions are not
+ * supported.
* @throws javax.transaction.SystemException
- * If the transaction service fails in an
- * unexpected way.
+ * If the transaction service fails in an unexpected way.
*/
- public void begin() throws NotSupportedException, SystemException
- {
+ public void begin() throws NotSupportedException, SystemException {
Transaction currentTx;
if ((currentTx = getTransaction()) != null)
throw new NotSupportedException(Thread.currentThread() +
@@ -65,28 +68,21 @@
* Commit the transaction associated with the calling thread.
*
* @throws javax.transaction.RollbackException
- * If the transaction was marked for rollback
- * only, the transaction is rolled back and this exception is
- * thrown.
- * @throws IllegalStateException If the calling thread is not associated
- * with a transaction.
+ * If the transaction was marked for rollback only, the transaction is rolled back and
+ * this exception is thrown.
+ * @throws IllegalStateException If the calling thread is not associated with a transaction.
* @throws javax.transaction.SystemException
- * If the transaction service fails in an
- * unexpected way.
+ * If the transaction service fails in an unexpected way.
* @throws javax.transaction.HeuristicMixedException
- * If a heuristic decision was made and
- * some some parts of the transaction have been committed while
- * other parts have been rolled back.
+ * If a heuristic decision was made and some some parts of the transaction have been
+ * committed while other parts have been rolled back.
* @throws javax.transaction.HeuristicRollbackException
- * If a heuristic decision to roll
- * back the transaction was made.
- * @throws SecurityException If the caller is not allowed to commit this
- * transaction.
+ * If a heuristic decision to roll back the transaction was made.
+ * @throws SecurityException If the caller is not allowed to commit this transaction.
*/
public void commit() throws RollbackException, HeuristicMixedException,
- HeuristicRollbackException, SecurityException,
- IllegalStateException, SystemException
- {
+ HeuristicRollbackException, SecurityException,
+ IllegalStateException, SystemException {
int status;
Transaction tx = getTransaction();
if (tx == null)
@@ -103,20 +99,15 @@
/**
* Rolls back the transaction associated with the calling thread.
*
- * @throws IllegalStateException If the transaction is in a state
- * where it cannot be rolled back. This could be because the
- * calling thread is not associated with a transaction, or
- * because it is in the
- * {@link javax.transaction.Status#STATUS_PREPARED prepared state}.
- * @throws SecurityException If the caller is not allowed to roll back
- * this transaction.
+ * @throws IllegalStateException If the transaction is in a state where it cannot be rolled back. This could be
+ * because the calling thread is not associated with a transaction, or because it is in
+ * the {@link javax.transaction.Status#STATUS_PREPARED prepared state}.
+ * @throws SecurityException If the caller is not allowed to roll back this transaction.
* @throws javax.transaction.SystemException
- * If the transaction service fails in an
- * unexpected way.
+ * If the transaction service fails in an unexpected way.
*/
public void rollback() throws IllegalStateException, SecurityException,
- SystemException
- {
+ SystemException {
Transaction tx = getTransaction();
if (tx == null)
throw new IllegalStateException("no transaction associated with thread");
@@ -127,20 +118,15 @@
}
/**
- * Mark the transaction associated with the calling thread for rollback
- * only.
+ * Mark the transaction associated with the calling thread for rollback only.
*
- * @throws IllegalStateException If the transaction is in a state
- * where it cannot be rolled back. This could be because the
- * calling thread is not associated with a transaction, or
- * because it is in the
- * {@link javax.transaction.Status#STATUS_PREPARED prepared state}.
+ * @throws IllegalStateException If the transaction is in a state where it cannot be rolled back. This could be
+ * because the calling thread is not associated with a transaction, or because it is in
+ * the {@link javax.transaction.Status#STATUS_PREPARED prepared state}.
* @throws javax.transaction.SystemException
- * If the transaction service fails in an
- * unexpected way.
+ * If the transaction service fails in an unexpected way.
*/
- public void setRollbackOnly() throws IllegalStateException, SystemException
- {
+ public void setRollbackOnly() throws IllegalStateException, SystemException {
Transaction tx = getTransaction();
if (tx == null)
throw new IllegalStateException("no transaction associated with calling thread");
@@ -150,16 +136,13 @@
/**
* Get the status of the transaction associated with the calling thread.
*
- * @return The status of the transaction. This is one of the
- * {@link javax.transaction.Status} constants. If no transaction is associated
- * with the calling thread,
- * {@link javax.transaction.Status#STATUS_NO_TRANSACTION} is returned.
+ * @return The status of the transaction. This is one of the {@link javax.transaction.Status} constants. If no
+ * transaction is associated with the calling thread, {@link javax.transaction.Status#STATUS_NO_TRANSACTION}
+ * is returned.
* @throws javax.transaction.SystemException
- * If the transaction service fails in an
- * unexpected way.
+ * If the transaction service fails in an unexpected way.
*/
- public int getStatus() throws SystemException
- {
+ public int getStatus() throws SystemException {
Transaction tx = getTransaction();
return tx != null ? tx.getStatus() : Status.STATUS_NO_TRANSACTION;
}
@@ -167,49 +150,37 @@
/**
* Get the transaction associated with the calling thread.
*
- * @return The transaction associated with the calling thread, or
- * <code>null</code> if the calling thread is not associated
- * with a transaction.
+ * @return The transaction associated with the calling thread, or <code>null</code> if the calling thread is not
+ * associated with a transaction.
* @throws javax.transaction.SystemException
- * If the transaction service fails in an
- * unexpected way.
+ * If the transaction service fails in an unexpected way.
*/
- public Transaction getTransaction() throws SystemException
- {
+ public Transaction getTransaction() throws SystemException {
return thread_local.get();
}
/**
- * Change the transaction timeout for transactions started by the calling
- * thread with the {@link #begin()} method.
+ * Change the transaction timeout for transactions started by the calling thread with the {@link #begin()} method.
*
- * @param seconds The new timeout value, in seconds. If this parameter
- * is <code>0</code>, the timeout value is reset to the default
- * value.
+ * @param seconds The new timeout value, in seconds. If this parameter is <code>0</code>, the timeout value is reset
+ * to the default value.
* @throws javax.transaction.SystemException
- * If the transaction service fails in an
- * unexpected way.
+ * If the transaction service fails in an unexpected way.
*/
- public void setTransactionTimeout(int seconds) throws SystemException
- {
+ public void setTransactionTimeout(int seconds) throws SystemException {
throw new SystemException("not supported");
}
/**
- * Suspend the association the calling thread has to a transaction,
- * and return the suspended transaction.
- * When returning from this method, the calling thread is no longer
- * associated with a transaction.
+ * Suspend the association the calling thread has to a transaction, and return the suspended transaction. When
+ * returning from this method, the calling thread is no longer associated with a transaction.
*
- * @return The transaction that the calling thread was associated with,
- * or <code>null</code> if the calling thread was not associated
- * with a transaction.
+ * @return The transaction that the calling thread was associated with, or <code>null</code> if the calling thread
+ * was not associated with a transaction.
* @throws javax.transaction.SystemException
- * If the transaction service fails in an
- * unexpected way.
+ * If the transaction service fails in an unexpected way.
*/
- public Transaction suspend() throws SystemException
- {
+ public Transaction suspend() throws SystemException {
Transaction retval = getTransaction();
setTransaction(null);
if (trace) log.trace("Suspending tx " + retval);
@@ -217,21 +188,16 @@
}
/**
- * Resume the association of the calling thread with the given
- * transaction.
+ * Resume the association of the calling thread with the given transaction.
*
* @param tx The transaction to be associated with the calling thread.
* @throws javax.transaction.InvalidTransactionException
- * If the argument does not represent
- * a valid transaction.
- * @throws IllegalStateException If the calling thread is already
- * associated with a transaction.
+ * If the argument does not represent a valid transaction.
+ * @throws IllegalStateException If the calling thread is already associated with a transaction.
* @throws javax.transaction.SystemException
- * If the transaction service fails in an
- * unexpected way.
+ * If the transaction service fails in an unexpected way.
*/
- public void resume(Transaction tx) throws InvalidTransactionException, IllegalStateException, SystemException
- {
+ public void resume(Transaction tx) throws InvalidTransactionException, IllegalStateException, SystemException {
if (trace) log.trace("Resuming tx " + tx);
setTransaction(tx);
}
@@ -241,8 +207,7 @@
*
* @param tx
*/
- public void setTransaction(Transaction tx)
- {
+ public void setTransaction(Transaction tx) {
thread_local.set(tx);
}
Modified: core/branches/flat/src/main/java/org/horizon/transaction/DummyTransaction.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/transaction/DummyTransaction.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/transaction/DummyTransaction.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -24,28 +24,31 @@
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
-import javax.transaction.*;
+import javax.transaction.HeuristicMixedException;
+import javax.transaction.HeuristicRollbackException;
+import javax.transaction.RollbackException;
+import javax.transaction.Status;
+import javax.transaction.Synchronization;
+import javax.transaction.SystemException;
+import javax.transaction.Transaction;
import javax.transaction.xa.XAResource;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
/**
* @author bela
- *
- * Date: May 15, 2003
- * Time: 4:20:17 PM
+ * <p/>
+ * Date: May 15, 2003 Time: 4:20:17 PM
* @since 1.0
*/
-public class DummyTransaction implements Transaction
-{
+public class DummyTransaction implements Transaction {
private int status = Status.STATUS_UNKNOWN;
private static final Log log = LogFactory.getLog(DummyTransaction.class);
protected DummyBaseTransactionManager tm_;
protected final Set<Synchronization> participants = new CopyOnWriteArraySet<Synchronization>();
- public DummyTransaction(DummyBaseTransactionManager tm)
- {
+ public DummyTransaction(DummyBaseTransactionManager tm) {
tm_ = tm;
status = Status.STATUS_ACTIVE;
}
@@ -53,36 +56,26 @@
/**
* Attempt to commit this transaction.
*
- * @throws RollbackException If the transaction was marked for rollback
- * only, the transaction is rolled back and this exception is
- * thrown.
- * @throws SystemException If the transaction service fails in an
- * unexpected way.
- * @throws HeuristicMixedException If a heuristic decision was made and
- * some some parts of the transaction have been committed while
- * other parts have been rolled back.
- * @throws HeuristicRollbackException If a heuristic decision to roll
- * back the transaction was made.
- * @throws SecurityException If the caller is not allowed to commit this
- * transaction.
+ * @throws RollbackException If the transaction was marked for rollback only, the transaction is rolled back
+ * and this exception is thrown.
+ * @throws SystemException If the transaction service fails in an unexpected way.
+ * @throws HeuristicMixedException If a heuristic decision was made and some some parts of the transaction have
+ * been committed while other parts have been rolled back.
+ * @throws HeuristicRollbackException If a heuristic decision to roll back the transaction was made.
+ * @throws SecurityException If the caller is not allowed to commit this transaction.
*/
public void commit()
throws RollbackException, HeuristicMixedException, HeuristicRollbackException,
- SecurityException, SystemException
- {
+ SecurityException, SystemException {
boolean doCommit;
status = Status.STATUS_PREPARING;
- try
- {
+ try {
boolean outcome = notifyBeforeCompletion();
// status=Status.STATUS_PREPARED;
- if (outcome && status != Status.STATUS_MARKED_ROLLBACK)
- {
+ if (outcome && status != Status.STATUS_MARKED_ROLLBACK) {
status = Status.STATUS_COMMITTING;
doCommit = true;
- }
- else
- {
+ } else {
status = Status.STATUS_ROLLING_BACK;
doCommit = false;
}
@@ -90,8 +83,7 @@
status = doCommit ? Status.STATUS_COMMITTED : Status.STATUS_MARKED_ROLLBACK;
if (!doCommit) throw new RollbackException("outcome is " + outcome + " status: " + status);
}
- finally
- {
+ finally {
// Disassociate tx from thread.
tm_.setTransaction(null);
}
@@ -100,17 +92,13 @@
/**
* Rolls back this transaction.
*
- * @throws IllegalStateException If the transaction is in a state
- * where it cannot be rolled back. This could be because the
- * transaction is no longer active, or because it is in the
- * {@link Status#STATUS_PREPARED prepared state}.
- * @throws SystemException If the transaction service fails in an
- * unexpected way.
+ * @throws IllegalStateException If the transaction is in a state where it cannot be rolled back. This could be
+ * because the transaction is no longer active, or because it is in the {@link
+ * Status#STATUS_PREPARED prepared state}.
+ * @throws SystemException If the transaction service fails in an unexpected way.
*/
- public void rollback() throws IllegalStateException, SystemException
- {
- try
- {
+ public void rollback() throws IllegalStateException, SystemException {
+ try {
// JBCACHE-360 -- to match JBossTM (and presumable the spec) a
// rollback transaction should have status ROLLEDBACK before
// calling afterCompletion().
@@ -118,8 +106,7 @@
status = Status.STATUS_ROLLEDBACK;
notifyAfterCompletion(Status.STATUS_ROLLEDBACK);
}
- catch (Throwable t)
- {
+ catch (Throwable t) {
}
status = Status.STATUS_ROLLEDBACK;
@@ -130,102 +117,78 @@
/**
* Mark the transaction so that the only possible outcome is a rollback.
*
- * @throws IllegalStateException If the transaction is not in an active
- * state.
- * @throws SystemException If the transaction service fails in an
- * unexpected way.
+ * @throws IllegalStateException If the transaction is not in an active state.
+ * @throws SystemException If the transaction service fails in an unexpected way.
*/
- public void setRollbackOnly() throws IllegalStateException, SystemException
- {
+ public void setRollbackOnly() throws IllegalStateException, SystemException {
status = Status.STATUS_MARKED_ROLLBACK;
}
/**
* Get the status of the transaction.
*
- * @return The status of the transaction. This is one of the
- * {@link Status} constants.
- * @throws SystemException If the transaction service fails in an
- * unexpected way.
+ * @return The status of the transaction. This is one of the {@link Status} constants.
+ * @throws SystemException If the transaction service fails in an unexpected way.
*/
- public int getStatus() throws SystemException
- {
+ public int getStatus() throws SystemException {
return status;
}
/**
- * Change the transaction timeout for transactions started by the calling
- * thread with the {@link DummyTransactionManager#begin()} method.
+ * Change the transaction timeout for transactions started by the calling thread with the {@link
+ * DummyTransactionManager#begin()} method.
*
- * @param seconds The new timeout value, in seconds. If this parameter
- * is <code>0</code>, the timeout value is reset to the default
- * value.
- * @throws SystemException If the transaction service fails in an
- * unexpected way.
+ * @param seconds The new timeout value, in seconds. If this parameter is <code>0</code>, the timeout value is reset
+ * to the default value.
+ * @throws SystemException If the transaction service fails in an unexpected way.
*/
- public void setTransactionTimeout(int seconds) throws SystemException
- {
+ public void setTransactionTimeout(int seconds) throws SystemException {
throw new SystemException("not supported");
}
/**
* Enlist an XA resource with this transaction.
*
- * @return <code>true</code> if the resource could be enlisted with
- * this transaction, otherwise <code>false</code>.
- * @throws RollbackException If the transaction is marked for rollback
- * only.
- * @throws IllegalStateException If the transaction is in a state
- * where resources cannot be enlisted. This could be because the
- * transaction is no longer active, or because it is in the
- * {@link Status#STATUS_PREPARED prepared state}.
- * @throws SystemException If the transaction service fails in an
- * unexpected way.
+ * @return <code>true</code> if the resource could be enlisted with this transaction, otherwise <code>false</code>.
+ * @throws RollbackException If the transaction is marked for rollback only.
+ * @throws IllegalStateException If the transaction is in a state where resources cannot be enlisted. This could be
+ * because the transaction is no longer active, or because it is in the {@link
+ * Status#STATUS_PREPARED prepared state}.
+ * @throws SystemException If the transaction service fails in an unexpected way.
*/
public boolean enlistResource(XAResource xaRes)
- throws RollbackException, IllegalStateException, SystemException
- {
+ throws RollbackException, IllegalStateException, SystemException {
throw new SystemException("not supported");
}
/**
* Delist an XA resource from this transaction.
*
- * @return <code>true</code> if the resource could be delisted from
- * this transaction, otherwise <code>false</code>.
- * @throws IllegalStateException If the transaction is in a state
- * where resources cannot be delisted. This could be because the
- * transaction is no longer active.
- * @throws SystemException If the transaction service fails in an
- * unexpected way.
+ * @return <code>true</code> if the resource could be delisted from this transaction, otherwise <code>false</code>.
+ * @throws IllegalStateException If the transaction is in a state where resources cannot be delisted. This could be
+ * because the transaction is no longer active.
+ * @throws SystemException If the transaction service fails in an unexpected way.
*/
public boolean delistResource(XAResource xaRes, int flag)
- throws IllegalStateException, SystemException
- {
+ throws IllegalStateException, SystemException {
throw new SystemException("not supported");
}
/**
* Register a {@link Synchronization} callback with this transaction.
*
- * @throws RollbackException If the transaction is marked for rollback
- * only.
- * @throws IllegalStateException If the transaction is in a state
- * where {@link Synchronization} callbacks cannot be registered.
- * This could be because the transaction is no longer active,
- * or because it is in the
- * {@link Status#STATUS_PREPARED prepared state}.
- * @throws SystemException If the transaction service fails in an
- * unexpected way.
+ * @throws RollbackException If the transaction is marked for rollback only.
+ * @throws IllegalStateException If the transaction is in a state where {@link Synchronization} callbacks cannot be
+ * registered. This could be because the transaction is no longer active, or because it
+ * is in the {@link Status#STATUS_PREPARED prepared state}.
+ * @throws SystemException If the transaction service fails in an unexpected way.
*/
public void registerSynchronization(Synchronization sync)
- throws RollbackException, IllegalStateException, SystemException
- {
+ throws RollbackException, IllegalStateException, SystemException {
if (sync == null)
throw new IllegalArgumentException("null synchronization " + this);
- switch (status)
- {
+ switch (status) {
case Status.STATUS_ACTIVE:
case Status.STATUS_PREPARING:
break;
@@ -249,35 +212,28 @@
throw new IllegalStateException("illegal status: " + status + " tx=" + this);
}
- if (log.isDebugEnabled())
- {
+ if (log.isDebugEnabled()) {
log.debug("registering synchronization handler " + sync);
}
participants.add(sync);
}
- void setStatus(int new_status)
- {
+ void setStatus(int new_status) {
status = new_status;
}
- protected boolean notifyBeforeCompletion()
- {
+ protected boolean notifyBeforeCompletion() {
boolean retval = true;
- for (Synchronization s : participants)
- {
- if (log.isDebugEnabled())
- {
+ for (Synchronization s : participants) {
+ if (log.isDebugEnabled()) {
log.debug("processing beforeCompletion for " + s);
}
- try
- {
+ try {
s.beforeCompletion();
}
- catch (Throwable t)
- {
+ catch (Throwable t) {
retval = false;
log.error("beforeCompletion() failed for " + s, t);
}
@@ -285,20 +241,15 @@
return retval;
}
- protected void notifyAfterCompletion(int status)
- {
- for (Synchronization s : participants)
- {
- if (log.isDebugEnabled())
- {
+ protected void notifyAfterCompletion(int status) {
+ for (Synchronization s : participants) {
+ if (log.isDebugEnabled()) {
log.debug("processing afterCompletion for " + s);
}
- try
- {
+ try {
s.afterCompletion(status);
}
- catch (Throwable t)
- {
+ catch (Throwable t) {
log.error("afterCompletion() failed for " + s, t);
}
}
Modified: core/branches/flat/src/main/java/org/horizon/transaction/DummyTransactionManager.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/transaction/DummyTransactionManager.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/transaction/DummyTransactionManager.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -30,17 +30,14 @@
import java.util.Properties;
/**
- * Simple transaction manager implementation that maintains transaction state
- * in memory only.
+ * Simple transaction manager implementation that maintains transaction state in memory only.
*
* @author bela
- *
- * Date: May 15, 2003
- * Time: 4:11:37 PM
+ * <p/>
+ * Date: May 15, 2003 Time: 4:11:37 PM
* @since 1.0
*/
-public class DummyTransactionManager extends DummyBaseTransactionManager
-{
+public class DummyTransactionManager extends DummyBaseTransactionManager {
protected static DummyTransactionManager instance = null;
protected static DummyUserTransaction utx = null;
@@ -48,46 +45,38 @@
private static final long serialVersionUID = 4396695354693176535L;
- public static DummyTransactionManager getInstance()
- {
- if (instance == null)
- {
+ public static DummyTransactionManager getInstance() {
+ if (instance == null) {
instance = new DummyTransactionManager();
utx = new DummyUserTransaction(instance);
- try
- {
+ try {
Properties p = new Properties();
Context ctx = new InitialContext(p);
ctx.bind("java:/TransactionManager", instance);
ctx.bind("UserTransaction", utx);
}
- catch (NamingException e)
- {
+ catch (NamingException e) {
log.debug("binding of DummyTransactionManager failed", e);
}
}
return instance;
}
- public static DummyUserTransaction getUserTransaction()
- {
+ public static DummyUserTransaction getUserTransaction() {
getInstance();
return utx;
}
- public static void destroy()
- {
+ public static void destroy() {
if (instance == null)
return;
- try
- {
+ try {
Properties p = new Properties();
Context ctx = new InitialContext(p);
ctx.unbind("java:/TransactionManager");
ctx.unbind("UserTransaction");
}
- catch (NamingException e)
- {
+ catch (NamingException e) {
log.error("unbinding of DummyTransactionManager failed", e);
}
instance.setTransaction(null);
Modified: core/branches/flat/src/main/java/org/horizon/transaction/DummyTransactionManagerLookup.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/transaction/DummyTransactionManagerLookup.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/transaction/DummyTransactionManagerLookup.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -30,24 +30,19 @@
* Returns an instance of {@link org.horizon.transaction.DummyTransactionManager}.
*
* @author Bela Ban Sept 5 2003
- *
* @since 1.0
*/
-public class DummyTransactionManagerLookup implements TransactionManagerLookup
-{
+public class DummyTransactionManagerLookup implements TransactionManagerLookup {
- public TransactionManager getTransactionManager() throws Exception
- {
+ public TransactionManager getTransactionManager() throws Exception {
return DummyTransactionManager.getInstance();
}
- public UserTransaction getUserTransaction()
- {
+ public UserTransaction getUserTransaction() {
return DummyTransactionManager.getUserTransaction();
}
- public void cleanup()
- {
+ public void cleanup() {
DummyTransactionManager.destroy();
}
}
Modified: core/branches/flat/src/main/java/org/horizon/transaction/DummyUserTransaction.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/transaction/DummyUserTransaction.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/transaction/DummyUserTransaction.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -24,19 +24,24 @@
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
-import javax.transaction.*;
+import javax.transaction.HeuristicMixedException;
+import javax.transaction.HeuristicRollbackException;
+import javax.transaction.NotSupportedException;
+import javax.transaction.RollbackException;
+import javax.transaction.Status;
+import javax.transaction.Synchronization;
+import javax.transaction.SystemException;
+import javax.transaction.UserTransaction;
import java.util.ArrayList;
import java.util.List;
/**
* @author bela
- *
- * Date: May 15, 2003
- * Time: 4:20:17 PM
+ * <p/>
+ * Date: May 15, 2003 Time: 4:20:17 PM
* @since 1.0
*/
-public class DummyUserTransaction implements UserTransaction, java.io.Serializable
-{
+public class DummyUserTransaction implements UserTransaction, java.io.Serializable {
static final Log logger_ = LogFactory.getLog(DummyUserTransaction.class);
DummyTransactionManager tm_;
private static final long serialVersionUID = -6568400755677046127L;
@@ -46,8 +51,7 @@
*/
List<Synchronization> l = new ArrayList<Synchronization>();
- public DummyUserTransaction(DummyTransactionManager tm)
- {
+ public DummyUserTransaction(DummyTransactionManager tm) {
tm_ = tm;
}
@@ -55,37 +59,28 @@
/**
* Starts a new transaction, and associate it with the calling thread.
*
- * @throws NotSupportedException If the calling thread is already
- * associated with a transaction, and nested transactions are
- * not supported.
- * @throws SystemException If the transaction service fails in an
- * unexpected way.
+ * @throws NotSupportedException If the calling thread is already associated with a transaction, and nested
+ * transactions are not supported.
+ * @throws SystemException If the transaction service fails in an unexpected way.
*/
- public void begin() throws NotSupportedException, SystemException
- {
+ public void begin() throws NotSupportedException, SystemException {
tm_.begin();
}
/**
* Attempt to commit this transaction.
*
- * @throws RollbackException If the transaction was marked for rollback
- * only, the transaction is rolled back and this exception is
- * thrown.
- * @throws SystemException If the transaction service fails in an
- * unexpected way.
- * @throws HeuristicMixedException If a heuristic decision was made and
- * some some parts of the transaction have been committed while
- * other parts have been rolled back.
- * @throws HeuristicRollbackException If a heuristic decision to roll
- * back the transaction was made.
- * @throws SecurityException If the caller is not allowed to commit this
- * transaction.
+ * @throws RollbackException If the transaction was marked for rollback only, the transaction is rolled back
+ * and this exception is thrown.
+ * @throws SystemException If the transaction service fails in an unexpected way.
+ * @throws HeuristicMixedException If a heuristic decision was made and some some parts of the transaction have
+ * been committed while other parts have been rolled back.
+ * @throws HeuristicRollbackException If a heuristic decision to roll back the transaction was made.
+ * @throws SecurityException If the caller is not allowed to commit this transaction.
*/
public void commit()
throws RollbackException, HeuristicMixedException,
- HeuristicRollbackException, SecurityException, SystemException
- {
+ HeuristicRollbackException, SecurityException, SystemException {
tm_.commit();
}
@@ -93,56 +88,43 @@
/**
* Rolls back this transaction.
*
- * @throws IllegalStateException If the transaction is in a state
- * where it cannot be rolled back. This could be because the
- * transaction is no longer active, or because it is in the
- * {@link Status#STATUS_PREPARED prepared state}.
- * @throws SystemException If the transaction service fails in an
- * unexpected way.
+ * @throws IllegalStateException If the transaction is in a state where it cannot be rolled back. This could be
+ * because the transaction is no longer active, or because it is in the {@link
+ * Status#STATUS_PREPARED prepared state}.
+ * @throws SystemException If the transaction service fails in an unexpected way.
*/
- public void rollback() throws IllegalStateException, SystemException
- {
+ public void rollback() throws IllegalStateException, SystemException {
tm_.rollback();
}
/**
* Mark the transaction so that the only possible outcome is a rollback.
*
- * @throws IllegalStateException If the transaction is not in an active
- * state.
- * @throws SystemException If the transaction service fails in an
- * unexpected way.
+ * @throws IllegalStateException If the transaction is not in an active state.
+ * @throws SystemException If the transaction service fails in an unexpected way.
*/
- public void setRollbackOnly() throws IllegalStateException, SystemException
- {
+ public void setRollbackOnly() throws IllegalStateException, SystemException {
tm_.setRollbackOnly();
}
/**
* Get the status of the transaction.
*
- * @return The status of the transaction. This is one of the
- * {@link Status} constants.
- * @throws SystemException If the transaction service fails in an
- * unexpected way.
+ * @return The status of the transaction. This is one of the {@link Status} constants.
+ * @throws SystemException If the transaction service fails in an unexpected way.
*/
- public int getStatus() throws SystemException
- {
+ public int getStatus() throws SystemException {
return tm_.getStatus();
}
/**
- * Change the transaction timeout for transactions started by the calling
- * thread with the {@link #begin()} method.
+ * Change the transaction timeout for transactions started by the calling thread with the {@link #begin()} method.
*
- * @param seconds The new timeout value, in seconds. If this parameter
- * is <code>0</code>, the timeout value is reset to the default
- * value.
- * @throws SystemException If the transaction service fails in an
- * unexpected way.
+ * @param seconds The new timeout value, in seconds. If this parameter is <code>0</code>, the timeout value is reset
+ * to the default value.
+ * @throws SystemException If the transaction service fails in an unexpected way.
*/
- public void setTransactionTimeout(int seconds) throws SystemException
- {
+ public void setTransactionTimeout(int seconds) throws SystemException {
throw new SystemException("not supported");
}
Modified: core/branches/flat/src/main/java/org/horizon/transaction/GenericTransactionManagerLookup.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/transaction/GenericTransactionManagerLookup.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/transaction/GenericTransactionManagerLookup.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -30,27 +30,15 @@
import java.lang.reflect.Method;
/**
- * A transaction manager lookup class that attempts to locate a TransactionManager.
- * A variety of different classes and JNDI locations are tried, for servers
- * such as:
- * <ul>
- * <li> JBoss
- * <li> JRun4
- * <li> Resin
- * <li> Orion
- * <li> JOnAS
- * <li> BEA Weblogic
- * <li> Websphere 4.0, 5.0, 5.1, 6.0
- * <li> Sun, Glassfish
- * </ul>
- * If a transaction manager is not found, returns a {@link org.horizon.transaction.DummyTransactionManager}.
+ * A transaction manager lookup class that attempts to locate a TransactionManager. A variety of different classes and
+ * JNDI locations are tried, for servers such as: <ul> <li> JBoss <li> JRun4 <li> Resin <li> Orion <li> JOnAS <li> BEA
+ * Weblogic <li> Websphere 4.0, 5.0, 5.1, 6.0 <li> Sun, Glassfish </ul> If a transaction manager is not found, returns a
+ * {@link org.horizon.transaction.DummyTransactionManager}.
*
* @author Markus Plesser
- *
* @since 1.0
*/
-public class GenericTransactionManagerLookup implements TransactionManagerLookup
-{
+public class GenericTransactionManagerLookup implements TransactionManagerLookup {
private static final Log log = LogFactory.getLog(GenericTransactionManagerLookup.class);
@@ -102,14 +90,12 @@
*
* @return TransactionManager
*/
- public TransactionManager getTransactionManager()
- {
+ public TransactionManager getTransactionManager() {
if (!lookupDone)
doLookups();
if (tm != null)
return tm;
- if (lookupFailed)
- {
+ if (lookupFailed) {
//fall back to a dummy from JBossCache
tm = DummyTransactionManager.getInstance();
log.warn("Falling back to DummyTransactionManager from JBossCache");
@@ -120,39 +106,32 @@
/**
* Try to figure out which TransactionManager to use
*/
- private static void doLookups()
- {
+ private static void doLookups() {
if (lookupFailed)
return;
InitialContext ctx;
- try
- {
+ try {
ctx = new InitialContext();
}
- catch (NamingException e)
- {
+ catch (NamingException e) {
log.error("Failed creating initial JNDI context", e);
lookupFailed = true;
return;
}
//probe jndi lookups first
- for (String[] knownJNDIManager : knownJNDIManagers)
- {
+ for (String[] knownJNDIManager : knownJNDIManagers) {
Object jndiObject;
- try
- {
+ try {
if (log.isDebugEnabled())
log.debug("Trying to lookup TransactionManager for " + knownJNDIManager[1]);
jndiObject = ctx.lookup(knownJNDIManager[0]);
}
- catch (NamingException e)
- {
+ catch (NamingException e) {
log.debug("Failed to perform a lookup for [" + knownJNDIManager[0] + " (" + knownJNDIManager[1]
+ ")]");
continue;
}
- if (jndiObject instanceof TransactionManager)
- {
+ if (jndiObject instanceof TransactionManager) {
tm = (TransactionManager) jndiObject;
log.debug("Found TransactionManager for " + knownJNDIManager[1]);
return;
@@ -160,45 +139,37 @@
}
//try to find websphere lookups since we came here
Class clazz;
- try
- {
+ try {
log.debug("Trying WebSphere 5.1: " + WS_FACTORY_CLASS_5_1);
clazz = Class.forName(WS_FACTORY_CLASS_5_1);
log.debug("Found WebSphere 5.1: " + WS_FACTORY_CLASS_5_1);
}
- catch (ClassNotFoundException ex)
- {
- try
- {
+ catch (ClassNotFoundException ex) {
+ try {
log.debug("Trying WebSphere 5.0: " + WS_FACTORY_CLASS_5_0);
clazz = Class.forName(WS_FACTORY_CLASS_5_0);
log.debug("Found WebSphere 5.0: " + WS_FACTORY_CLASS_5_0);
}
- catch (ClassNotFoundException ex2)
- {
- try
- {
+ catch (ClassNotFoundException ex2) {
+ try {
log.debug("Trying WebSphere 4: " + WS_FACTORY_CLASS_4);
clazz = Class.forName(WS_FACTORY_CLASS_4);
log.debug("Found WebSphere 4: " + WS_FACTORY_CLASS_4);
}
- catch (ClassNotFoundException ex3)
- {
+ catch (ClassNotFoundException ex3) {
log.debug("Couldn't find any WebSphere TransactionManager factory class, neither for WebSphere version 5.1 nor 5.0 nor 4");
lookupFailed = true;
return;
}
}
}
- try
- {
+ try {
Class[] signature = null;
Object[] args = null;
Method method = clazz.getMethod("getTransactionManager", signature);
tm = (TransactionManager) method.invoke(null, args);
}
- catch (Exception ex)
- {
+ catch (Exception ex) {
log.error("Found WebSphere TransactionManager factory class [" + clazz.getName()
+ "], but couldn't invoke its static 'getTransactionManager' method", ex);
}
Modified: core/branches/flat/src/main/java/org/horizon/transaction/GlobalTransaction.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/transaction/GlobalTransaction.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/transaction/GlobalTransaction.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -31,17 +31,15 @@
/**
- * Uniquely identifies a transaction that spans all nodes in a cluster. This is used when
- * replicating all modifications in a transaction; the PREPARE and COMMIT (or ROLLBACK)
- * messages have to have a unique identifier to associate the changes with<br>
+ * Uniquely identifies a transaction that spans all nodes in a cluster. This is used when replicating all modifications
+ * in a transaction; the PREPARE and COMMIT (or ROLLBACK) messages have to have a unique identifier to associate the
+ * changes with<br>
*
* @author <a href="mailto:bela at jboss.org">Bela Ban</a> Apr 12, 2003
* @author <a href="mailto:manik at jboss.org">Manik Surtani (manik at jboss.org)</a>
- *
* @since 1.0
*/
-public class GlobalTransaction implements Externalizable
-{
+public class GlobalTransaction implements Externalizable {
private static final long serialVersionUID = 8011434781266976149L;
@@ -57,54 +55,44 @@
/**
* empty ctor used by externalization
*/
- public GlobalTransaction()
- {
+ public GlobalTransaction() {
}
- private GlobalTransaction(Address addr)
- {
+ private GlobalTransaction(Address addr) {
this.addr = addr;
id = newId();
}
- private static synchronized long newId()
- {
+ private static synchronized long newId() {
return ++sid;
}
- public static GlobalTransaction create(Address addr)
- {
+ public static GlobalTransaction create(Address addr) {
return new GlobalTransaction(addr);
}
- public Object getAddress()
- {
+ public Object getAddress() {
return addr;
}
- public void setAddress(Address address)
- {
+ public void setAddress(Address address) {
addr = address;
}
- public long getId()
- {
+ public long getId() {
return id;
}
@Override
- public int hashCode()
- {
- if (hash_code == -1)
- {
+ public int hashCode() {
+ if (hash_code == -1) {
hash_code = (addr != null ? addr.hashCode() : 0) + (int) id;
}
return hash_code;
}
@Override
- public boolean equals(Object other)
- {
+ public boolean equals(Object other) {
if (this == other)
return true;
if (!(other instanceof GlobalTransaction))
@@ -116,22 +104,19 @@
}
@Override
- public String toString()
- {
+ public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("GlobalTransaction:<").append(addr).append(">:").append(id);
return sb.toString();
}
- public void writeExternal(ObjectOutput out) throws IOException
- {
+ public void writeExternal(ObjectOutput out) throws IOException {
out.writeObject(addr);
out.writeLong(id);
// out.writeInt(hash_code);
}
- public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException
- {
+ public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
addr = (Address) in.readObject();
id = in.readLong();
hash_code = -1;
@@ -140,22 +125,19 @@
/**
* @return Returns the remote.
*/
- public boolean isRemote()
- {
+ public boolean isRemote() {
return remote;
}
/**
* @param remote The remote to set.
*/
- public void setRemote(boolean remote)
- {
+ public void setRemote(boolean remote) {
this.remote = remote;
}
- public void setId(long id)
- {
+ public void setId(long id) {
this.id = id;
}
}
\ No newline at end of file
Modified: core/branches/flat/src/main/java/org/horizon/transaction/JBossStandaloneJTAManagerLookup.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/transaction/JBossStandaloneJTAManagerLookup.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/transaction/JBossStandaloneJTAManagerLookup.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -32,30 +32,24 @@
* @author Jason T. Greene
* @since 1.0
*/
-public class JBossStandaloneJTAManagerLookup implements TransactionManagerLookup
-{
+public class JBossStandaloneJTAManagerLookup implements TransactionManagerLookup {
private Method manager, user;
- public JBossStandaloneJTAManagerLookup()
- {
- try
- {
+ public JBossStandaloneJTAManagerLookup() {
+ try {
manager = Class.forName("com.arjuna.ats.jta.TransactionManager").getMethod("transactionManager");
user = Class.forName("com.arjuna.ats.jta.UserTransaction").getMethod("userTransaction");
}
- catch (Exception e)
- {
+ catch (Exception e) {
throw new RuntimeException(e);
}
}
- public TransactionManager getTransactionManager() throws Exception
- {
+ public TransactionManager getTransactionManager() throws Exception {
return (TransactionManager) manager.invoke(null);
}
- public UserTransaction getUserTransaction() throws Exception
- {
+ public UserTransaction getUserTransaction() throws Exception {
return (UserTransaction) user.invoke(null);
}
}
\ No newline at end of file
Modified: core/branches/flat/src/main/java/org/horizon/transaction/JBossTransactionManagerLookup.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/transaction/JBossTransactionManagerLookup.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/transaction/JBossTransactionManagerLookup.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -26,18 +26,14 @@
/**
- * Uses JNDI to look-up the
- * {@link TransactionManager} instance from "java:/TransactionManager".
+ * Uses JNDI to look-up the {@link TransactionManager} instance from "java:/TransactionManager".
*
* @author Bela Ban, Aug 26 2003
- *
* @since 1.0
*/
-public class JBossTransactionManagerLookup implements TransactionManagerLookup
-{
+public class JBossTransactionManagerLookup implements TransactionManagerLookup {
- public TransactionManager getTransactionManager() throws Exception
- {
+ public TransactionManager getTransactionManager() throws Exception {
return (TransactionManager) new InitialContext().lookup("java:/TransactionManager");
}
Modified: core/branches/flat/src/main/java/org/horizon/transaction/TransactionManagerLookup.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/transaction/TransactionManagerLookup.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/transaction/TransactionManagerLookup.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -24,16 +24,13 @@
import javax.transaction.TransactionManager;
/**
- * Factory interface, allows {@link org.horizon.Cache} to use different transactional systems.
- * Names of implementors of this class can be configured using
- * {@link Configuration#setTransactionManagerLookupClass}.
+ * Factory interface, allows {@link org.horizon.Cache} to use different transactional systems. Names of implementors of
+ * this class can be configured using {@link Configuration#setTransactionManagerLookupClass}.
*
* @author Bela Ban, Aug 26 2003
- *
* @since 1.0
*/
-public interface TransactionManagerLookup
-{
+public interface TransactionManagerLookup {
/**
* Returns a new TransactionManager.
Modified: core/branches/flat/src/main/java/org/horizon/transaction/TransactionTable.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/transaction/TransactionTable.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/transaction/TransactionTable.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -40,16 +40,14 @@
import java.util.concurrent.ConcurrentHashMap;
/**
- * Maintains the mapping between a local {@link Transaction} and a {@link GlobalTransaction}.
- * Also stores {@link TransactionContext} instances under a given transaction.
+ * Maintains the mapping between a local {@link Transaction} and a {@link GlobalTransaction}. Also stores {@link
+ * TransactionContext} instances under a given transaction.
*
* @author <a href="mailto:bela at jboss.org">Bela Ban</a> Apr 14, 2003
- *
* @since 1.0
*/
@NonVolatile
-public class TransactionTable
-{
+public class TransactionTable {
private static final Log log = LogFactory.getLog(TransactionTable.class);
private static final boolean trace = log.isTraceEnabled();
@@ -70,8 +68,7 @@
private ContextFactory contextFactory;
@Inject
- public void initialize(TransactionManager transactionManager, RPCManager rpcManager, ContextFactory contextFactory)
- {
+ public void initialize(TransactionManager transactionManager, RPCManager rpcManager, ContextFactory contextFactory) {
this.transactionManager = transactionManager;
this.rpcManager = rpcManager;
this.contextFactory = contextFactory;
@@ -80,25 +77,22 @@
/**
* Returns the number of local transactions.
*/
- public int getNumLocalTransactions()
- {
+ public int getNumLocalTransactions() {
return txMapping.size();
}
/**
* Returns the number of global transactions.
*/
- public int getNumGlobalTransactions()
- {
+ public int getNumGlobalTransactions() {
return txMapping.size();
}
/**
- * Returns the global transaction associated with the local transaction.
- * Returns null if tx is null or it was not found.
+ * Returns the global transaction associated with the local transaction. Returns null if tx is null or it was not
+ * found.
*/
- public GlobalTransaction get(Transaction tx)
- {
+ public GlobalTransaction get(Transaction tx) {
if (tx == null) return null;
TransactionContext ctx = txMapping.get(tx);
return ctx == null ? null : ctx.getGobalTransaction();
@@ -107,34 +101,28 @@
/**
* If assers exists is true and the coresponding local transaction is null an IllegalStateExcetpion is being thrown.
*/
- public Transaction getLocalTransaction(GlobalTransaction gtx, boolean assertExists)
- {
+ public Transaction getLocalTransaction(GlobalTransaction gtx, boolean assertExists) {
Transaction ltx = getLocalTransaction(gtx);
- if (!assertExists)
- {
+ if (!assertExists) {
return ltx;
}
- if (ltx != null)
- {
+ if (ltx != null) {
if (log.isDebugEnabled()) log.debug("Found local TX=" + ltx + ", global TX=" + gtx);
return ltx;
- }
- else
- {
+ } else {
throw new IllegalStateException(" found no local TX for global TX " + gtx);
}
}
/**
- * Associates 3 elements of a transaction - a local Transaction, a GlobalTransaction and a TransactionContext -
- * with each other.
+ * Associates 3 elements of a transaction - a local Transaction, a GlobalTransaction and a TransactionContext - with
+ * each other.
*
* @param tx transaction to associate
* @param gtx global transaction to associate
* @param ctx transaction context to associate
*/
- public void associateTransaction(Transaction tx, GlobalTransaction gtx, TransactionContext ctx)
- {
+ public void associateTransaction(Transaction tx, GlobalTransaction gtx, TransactionContext ctx) {
if (ctx.getTransaction() == null) ctx.setTransaction(tx);
if (ctx.getGobalTransaction() == null) ctx.setGlobalTransaction(gtx);
@@ -142,8 +130,7 @@
gtxMapping.put(gtx, ctx);
}
- public Transaction getLocalTransaction(GlobalTransaction gtx)
- {
+ public Transaction getLocalTransaction(GlobalTransaction gtx) {
TransactionContext ctx = gtxMapping.get(gtx);
return ctx == null ? null : ctx.getTransaction();
}
@@ -152,8 +139,7 @@
* Returns summary debug information.
*/
@Override
- public String toString()
- {
+ public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(txMapping.size()).append(" transactions");
return sb.toString();
@@ -162,66 +148,52 @@
/**
* Returns detailed debug information.
*/
- public String toString(boolean printDetails)
- {
+ public String toString(boolean printDetails) {
if (!printDetails)
return toString();
StringBuilder sb = new StringBuilder();
sb.append("Transactions: ").append(txMapping.size()).append("\n");
sb.append("mappings:\n");
- for (Map.Entry<Transaction, TransactionContext> entry : txMapping.entrySet())
- {
+ for (Map.Entry<Transaction, TransactionContext> entry : txMapping.entrySet()) {
sb.append(entry.getKey()).append(": ").append(entry.getValue()).append("\n");
}
return sb.toString();
}
/**
- * Returns the transaction associated with the current thread.
- * If a local transaction exists, but doesn't yet have a mapping to a
- * GlobalTransaction, a new GlobalTransaction will be created and mapped to
- * the local transaction. Note that if a local transaction exists, but is
- * not ACTIVE or PREPARING, null is returned.
+ * Returns the transaction associated with the current thread. If a local transaction exists, but doesn't yet have a
+ * mapping to a GlobalTransaction, a new GlobalTransaction will be created and mapped to the local transaction. Note
+ * that if a local transaction exists, but is not ACTIVE or PREPARING, null is returned.
*
* @return A GlobalTransaction, or null if no (local) transaction was associated with the current thread
*/
- public GlobalTransaction getCurrentTransaction()
- {
+ public GlobalTransaction getCurrentTransaction() {
return getCurrentTransaction(true);
}
/**
- * Returns the transaction associated with the thread; optionally creating
- * it if is does not exist.
+ * Returns the transaction associated with the thread; optionally creating it if is does not exist.
*/
- public GlobalTransaction getCurrentTransaction(boolean createIfNotExists)
- {
+ public GlobalTransaction getCurrentTransaction(boolean createIfNotExists) {
Transaction tx;
- if ((tx = getLocalTransaction()) == null)
- {// no transaction is associated with the current thread
+ if ((tx = getLocalTransaction()) == null) {// no transaction is associated with the current thread
return null;
}
- if (!isValid(tx))
- {// we got a non-null transaction, but it is not active anymore
+ if (!isValid(tx)) {// we got a non-null transaction, but it is not active anymore
int status = -1;
- try
- {
+ try {
status = tx.getStatus();
}
- catch (SystemException e)
- {
+ catch (SystemException e) {
}
// JBCACHE-982 -- don't complain if COMMITTED
- if (status != Status.STATUS_COMMITTED)
- {
+ if (status != Status.STATUS_COMMITTED) {
log.warn("status is " + status + " (not ACTIVE or PREPARING); returning null)");
- }
- else
- {
+ } else {
log.trace("status is COMMITTED; returning null");
}
@@ -232,22 +204,17 @@
}
/**
- * Returns the transaction associated with the current thread. We get the
- * initial context and a reference to the TransactionManager to get the
- * transaction. This method is used by {@link #getCurrentTransaction()}
+ * Returns the transaction associated with the current thread. We get the initial context and a reference to the
+ * TransactionManager to get the transaction. This method is used by {@link #getCurrentTransaction()}
*/
- protected Transaction getLocalTransaction()
- {
- if (transactionManager == null)
- {
+ protected Transaction getLocalTransaction() {
+ if (transactionManager == null) {
return null;
}
- try
- {
+ try {
return transactionManager.getTransaction();
}
- catch (Throwable t)
- {
+ catch (Throwable t) {
return null;
}
}
@@ -255,17 +222,14 @@
/**
* Returns true if transaction is ACTIVE, false otherwise
*/
- public static boolean isActive(Transaction tx)
- {
+ public static boolean isActive(Transaction tx) {
if (tx == null) return false;
int status;
- try
- {
+ try {
status = tx.getStatus();
return status == Status.STATUS_ACTIVE;
}
- catch (SystemException e)
- {
+ catch (SystemException e) {
return false;
}
}
@@ -273,17 +237,14 @@
/**
* Returns true if transaction is PREPARING, false otherwise
*/
- public static boolean isPreparing(Transaction tx)
- {
+ public static boolean isPreparing(Transaction tx) {
if (tx == null) return false;
int status;
- try
- {
+ try {
status = tx.getStatus();
return status == Status.STATUS_PREPARING;
}
- catch (SystemException e)
- {
+ catch (SystemException e) {
return false;
}
}
@@ -294,23 +255,19 @@
* @param tx
* @return true if the tx is active or preparing
*/
- public static boolean isValid(Transaction tx)
- {
+ public static boolean isValid(Transaction tx) {
return isActive(tx) || isPreparing(tx);
}
/**
* Tests whether the caller is in a valid transaction. If not, will throw a CacheException.
*/
- public static void assertTransactionValid(InvocationContext ctx)
- {
+ public static void assertTransactionValid(InvocationContext ctx) {
Transaction tx = ctx.getTransaction();
- if (!isValid(tx)) try
- {
+ if (!isValid(tx)) try {
throw new CacheException("Invalid transaction " + tx + ", status = " + (tx == null ? null : tx.getStatus()));
}
- catch (SystemException e)
- {
+ catch (SystemException e) {
throw new CacheException("Exception trying to analyse status of transaction " + tx, e);
}
}
@@ -319,8 +276,7 @@
/**
* Returns the global transaction for this local transaction.
*/
- public GlobalTransaction getCurrentTransaction(Transaction tx)
- {
+ public GlobalTransaction getCurrentTransaction(Transaction tx) {
return getCurrentTransaction(tx, true);
}
@@ -329,44 +285,37 @@
*
* @param createIfNotExists if true, if a global transaction is not found; one is created
*/
- public GlobalTransaction getCurrentTransaction(Transaction tx, boolean createIfNotExists)
- {
+ public GlobalTransaction getCurrentTransaction(Transaction tx, boolean createIfNotExists) {
// removed synchronization on txTable because underlying implementation is thread safe
// and JTA spec (section 3.4.3 Thread of Control, par 2) says that only one thread may
// operate on the transaction at one time so no concern about 2 threads trying to call
// this method for the same Transaction instance at the same time
//
GlobalTransaction gtx = get(tx);
- if (gtx == null && createIfNotExists)
- {
+ if (gtx == null && createIfNotExists) {
Address addr = rpcManager.getLocalAddress();
gtx = GlobalTransaction.create(addr);
if (trace) log.trace("Creating new GlobalTransaction " + gtx);
TransactionContext transactionContext;
- try
- {
+ try {
transactionContext = contextFactory.createTransactionContext(tx);
}
- catch (Exception e)
- {
+ catch (Exception e) {
throw new CacheException("Unable to create a transaction entry!", e);
}
associateTransaction(tx, gtx, transactionContext);
- if (trace)
- {
+ if (trace) {
log.trace("created new GTX: " + gtx + ", local TX=" + tx);
}
}
return gtx;
}
- public TransactionContext getTransactionContext(GlobalTransaction gtx)
- {
+ public TransactionContext getTransactionContext(GlobalTransaction gtx) {
return gtxMapping.get(gtx);
}
- public void cleanup(GlobalTransaction gtx)
- {
+ public void cleanup(GlobalTransaction gtx) {
TransactionContext ctx = gtxMapping.remove(gtx);
if (ctx != null) txMapping.remove(ctx.getTransaction());
}
Modified: core/branches/flat/src/main/java/org/horizon/tree/Fqn.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/tree/Fqn.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/tree/Fqn.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -35,16 +35,15 @@
import java.util.List;
/**
- * A Fully Qualified Name (Fqn) is a list of names (typically Strings but can be any Object),
- * which represent a path to a particular {@link Node} in a {@link TreeCache}.
+ * A Fully Qualified Name (Fqn) is a list of names (typically Strings but can be any Object), which represent a path to
+ * a particular {@link Node} in a {@link TreeCache}.
* <p/>
- * This name can be absolute (i.e., relative from the root node - {@link #ROOT}), or relative to any node in the cache. Reading the
- * documentation on each API call that makes use of {@link Fqn}s will tell you whether the API expects a
+ * This name can be absolute (i.e., relative from the root node - {@link #ROOT}), or relative to any node in the cache.
+ * Reading the documentation on each API call that makes use of {@link Fqn}s will tell you whether the API expects a
* relative or absolute Fqn.
* <p/>
- * For instance, using this class to fetch a particular node might look like
- * this. (Here data on "Joe" is kept under the "Smith" surname node, under
- * the "people" tree.)
+ * For instance, using this class to fetch a particular node might look like this. (Here data on "Joe" is kept under
+ * the "Smith" surname node, under the "people" tree.)
* <pre>
* Fqn<String> abc = Fqn.fromString("/people/Smith/Joe/");
* Node joesmith = Cache.getRoot().getChild(abc);
@@ -65,37 +64,23 @@
* <p/>
* The former will result in a single Fqn, called "/a/b/c" which hangs directly under Fqn.ROOT.
* <p/>
- * The latter will result in 3 Fqns, called "a", "b" and "c", where "c" is a child of "b", "b" is a child of "a", and "a" hangs off Fqn.ROOT.
+ * The latter will result in 3 Fqns, called "a", "b" and "c", where "c" is a child of "b", "b" is a child of "a", and
+ * "a" hangs off Fqn.ROOT.
* <p/>
- * Another way to look at it is that the "/" separarator is only parsed when it forms
- * part of a String passed in to Fqn.fromString() and not otherwise.
+ * Another way to look at it is that the "/" separarator is only parsed when it forms part of a String passed in to
+ * Fqn.fromString() and not otherwise.
* <p/>
- * <B>Best practices</B>: Always creating Fqns - even when using some factory methods - can be expensive in the long run,
- * and as far as possible we recommend that client code holds on to their Fqn references and reuse them. E.g.:
- * <code>
- * // BAD!!
- * for (int i=0; i<someBigNumber; i++)
- * {
- * cache.get(Fqn.fromString("/a/b/c"), "key" + i);
- * }
- * </code>
- * instead, do:
- * <code>
- * // Much better
- * Fqn f = Fqn.fromString("/a/b/c");
- * for (int i=0; i<someBigNumber; i++)
- * {
- * cache.get(f, "key" + i);
- * }
- * </code>
+ * <B>Best practices</B>: Always creating Fqns - even when using some factory methods - can be expensive in the long
+ * run, and as far as possible we recommend that client code holds on to their Fqn references and reuse them. E.g.:
+ * <code> // BAD!! for (int i=0; i<someBigNumber; i++) { cache.get(Fqn.fromString("/a/b/c"), "key" + i); } </code>
+ * instead, do: <code> // Much better Fqn f = Fqn.fromString("/a/b/c"); for (int i=0; i<someBigNumber; i++) {
+ * cache.get(f, "key" + i); } </code>
*
- *
- * @since 1.0
* @author (various)
+ * @since 1.0
*/
@Immutable
-public class Fqn implements Comparable<Fqn>, Externalizable
-{
+public class Fqn implements Comparable<Fqn>, Externalizable {
/**
* Separator between FQN elements.
*/
@@ -120,38 +105,32 @@
/**
* Public to satisfy Externalization. // TODO: Remove this ctor as well as Externalization!!
*/
- public Fqn()
- {
+ public Fqn() {
elements = Collections.emptyList();
size = 0;
}
/**
* If safe is false, Collections.unmodifiableList() is used to wrap the list passed in. This is an optimisation so
- * Fqn.fromString(), probably the most frequently used factory method, doesn't end up needing to use the unmodifiableList()
- * since it creates the list internally.
+ * Fqn.fromString(), probably the most frequently used factory method, doesn't end up needing to use the
+ * unmodifiableList() since it creates the list internally.
*
* @param names List of names
* @param safe whether this list is referenced externally (safe = false) or not (safe = true).
*/
@SuppressWarnings("unchecked")
- private Fqn(List names, boolean safe)
- {
- if (names != null)
- {
+ private Fqn(List names, boolean safe) {
+ if (names != null) {
// if not safe make a defensive copy
elements = safe ? names : Immutables.immutableListCopy(names);
size = elements.size();
- }
- else
- {
+ } else {
elements = Collections.emptyList();
size = 0;
}
}
- private Fqn(Fqn base, List relative)
- {
+ private Fqn(Fqn base, List relative) {
elements = Immutables.immutableListMerge(base.elements, relative);
size = elements.size();
}
@@ -166,8 +145,7 @@
* @since 1.0
*/
@SuppressWarnings("unchecked")
- public static Fqn fromList(List names)
- {
+ public static Fqn fromList(List names) {
return new Fqn(names, false);
}
@@ -175,15 +153,15 @@
* Retrieves an Fqn that represents the list of elements passed in.
*
* @param names list of elements that comprise the Fqn
- * @param safe if true, the list passed in is not defensively copied but used directly. <b>Use with care.</b> Make sure
- * you know what you are doing before you pass in a <tt>true</tt> value to <tt>safe</tt>, as it can have adverse effects on
- * performance or correctness. The defensive copy of list elements is not just for safety but also for performance as
- * an appropriare List implementation is used, which works well with Fqn operations.
+ * @param safe if true, the list passed in is not defensively copied but used directly. <b>Use with care.</b> Make
+ * sure you know what you are doing before you pass in a <tt>true</tt> value to <tt>safe</tt>, as it can
+ * have adverse effects on performance or correctness. The defensive copy of list elements is not just
+ * for safety but also for performance as an appropriare List implementation is used, which works well
+ * with Fqn operations.
* @return an Fqn
*/
@SuppressWarnings("unchecked")
- public static Fqn fromList(List names, boolean safe)
- {
+ public static Fqn fromList(List names, boolean safe) {
return new Fqn(names, safe);
}
@@ -194,8 +172,7 @@
* @return an Fqn
* @since 1.0
*/
- public static Fqn fromElements(Object... elements)
- {
+ public static Fqn fromElements(Object... elements) {
return new Fqn(Arrays.asList(elements), true);
}
@@ -207,8 +184,7 @@
* @return an Fqn
* @since 1.0
*/
- public static Fqn fromRelativeFqn(Fqn base, Fqn relative)
- {
+ public static Fqn fromRelativeFqn(Fqn base, Fqn relative) {
return new Fqn(base, relative.elements);
}
@@ -220,8 +196,7 @@
* @return an Fqn
* @since 1.0
*/
- public static Fqn fromRelativeList(Fqn base, List relativeElements)
- {
+ public static Fqn fromRelativeList(Fqn base, List relativeElements) {
return new Fqn(base, relativeElements);
}
@@ -233,15 +208,13 @@
* @return an Fqn
* @since 1.0
*/
- public static Fqn fromRelativeElements(Fqn base, Object... relativeElements)
- {
+ public static Fqn fromRelativeElements(Fqn base, Object... relativeElements) {
return new Fqn(base, Arrays.asList(relativeElements));
}
/**
- * Returns a new Fqn from a string, where the elements are deliminated by
- * one or more separator ({@link #SEPARATOR}) characters.<br><br>
- * Example use:<br>
+ * Returns a new Fqn from a string, where the elements are deliminated by one or more separator ({@link #SEPARATOR})
+ * characters.<br><br> Example use:<br>
* <pre>
* Fqn.fromString("/a/b/c/");
* </pre><br>
@@ -254,8 +227,7 @@
* @return an Fqn<String> constructed from the string representation passed in
*/
@SuppressWarnings("unchecked")
- public static Fqn fromString(String stringRepresentation)
- {
+ public static Fqn fromString(String stringRepresentation) {
if (stringRepresentation == null || stringRepresentation.equals(SEPARATOR) || stringRepresentation.equals(""))
return root();
@@ -265,7 +237,8 @@
}
/**
- * Retrieves an Fqn read from an object input stream, typically written to using {@link #writeExternal(java.io.ObjectOutput)}.
+ * Retrieves an Fqn read from an object input stream, typically written to using {@link
+ * #writeExternal(java.io.ObjectOutput)}.
*
* @param in input stream
* @return an Fqn
@@ -273,8 +246,7 @@
* @throws ClassNotFoundException in the event of classes that comprise the element list of this Fqn not being found
* @since 1.0
*/
- public static Fqn fromExternalStream(ObjectInput in) throws IOException, ClassNotFoundException
- {
+ public static Fqn fromExternalStream(ObjectInput in) throws IOException, ClassNotFoundException {
Fqn f = new Fqn();
f.readExternal(in);
return f;
@@ -282,30 +254,15 @@
/**
- * Obtains an ancestor of the current Fqn. Literally performs <code>elements.subList(0, generation)</code>
- * such that if
- * <code>
- * generation == Fqn.size()
- * </code>
- * then the return value is the Fqn itself (current generation), and if
- * <code>
- * generation == Fqn.size() - 1
- * </code>
- * then the return value is the same as
- * <code>
- * Fqn.getParent()
- * </code>
- * i.e., just one generation behind the current generation.
- * <code>
- * generation == 0
- * </code>
- * would return Fqn.ROOT.
+ * Obtains an ancestor of the current Fqn. Literally performs <code>elements.subList(0, generation)</code> such that
+ * if <code> generation == Fqn.size() </code> then the return value is the Fqn itself (current generation), and if
+ * <code> generation == Fqn.size() - 1 </code> then the return value is the same as <code> Fqn.getParent() </code>
+ * i.e., just one generation behind the current generation. <code> generation == 0 </code> would return Fqn.ROOT.
*
* @param generation the generation of the ancestor to retrieve
* @return an ancestor of the current Fqn
*/
- public Fqn getAncestor(int generation)
- {
+ public Fqn getAncestor(int generation) {
if (generation == 0) return root();
return getSubFqn(0, generation);
}
@@ -317,8 +274,7 @@
* @param endIndex end index
* @return a subFqn
*/
- public Fqn getSubFqn(int startIndex, int endIndex)
- {
+ public Fqn getSubFqn(int startIndex, int endIndex) {
List el = elements.subList(startIndex, endIndex);
return new Fqn(el, true);
}
@@ -326,8 +282,7 @@
/**
* @return the number of elements in the Fqn. The root node contains zero.
*/
- public int size()
- {
+ public int size() {
return size;
}
@@ -335,8 +290,7 @@
* @param n index of the element to return
* @return Returns the nth element in the Fqn.
*/
- public Object get(int n)
- {
+ public Object get(int n) {
return elements.get(n);
}
@@ -344,8 +298,7 @@
* @return the last element in the Fqn.
* @see #getLastElementAsString
*/
- public Object getLastElement()
- {
+ public Object getLastElement() {
if (isRoot()) return null;
return elements.get(size - 1);
}
@@ -354,8 +307,7 @@
* @param element element to find
* @return true if the Fqn contains this element, false otherwise.
*/
- public boolean hasElement(Object element)
- {
+ public boolean hasElement(Object element) {
return elements.indexOf(element) != -1;
}
@@ -363,14 +315,11 @@
* Returns true if obj is a Fqn with the same elements.
*/
@Override
- public boolean equals(Object obj)
- {
- if (this == obj)
- {
+ public boolean equals(Object obj) {
+ if (this == obj) {
return true;
}
- if (!(obj instanceof Fqn))
- {
+ if (!(obj instanceof Fqn)) {
return false;
}
Fqn other = (Fqn) obj;
@@ -381,46 +330,37 @@
* Returns a hash code with Fqn elements.
*/
@Override
- public int hashCode()
- {
- if (hash_code == 0)
- {
+ public int hashCode() {
+ if (hash_code == 0) {
hash_code = calculateHashCode();
}
return hash_code;
}
/**
- * Returns this Fqn as a string, prefixing the first element with a {@link Fqn#SEPARATOR} and
- * joining each subsequent element with a {@link Fqn#SEPARATOR}.
- * If this is the root Fqn, returns {@link Fqn#SEPARATOR}.
- * Example:
+ * Returns this Fqn as a string, prefixing the first element with a {@link Fqn#SEPARATOR} and joining each subsequent
+ * element with a {@link Fqn#SEPARATOR}. If this is the root Fqn, returns {@link Fqn#SEPARATOR}. Example:
* <pre>
* new Fqn(new Object[] { "a", "b", "c" }).toString(); // "/a/b/c"
* Fqn.ROOT.toString(); // "/"
* </pre>
*/
@Override
- public String toString()
- {
- if (stringRepresentation == null)
- {
+ public String toString() {
+ if (stringRepresentation == null) {
stringRepresentation = getStringRepresentation(elements);
}
return stringRepresentation;
}
- public void writeExternal(ObjectOutput out) throws IOException
- {
+ public void writeExternal(ObjectOutput out) throws IOException {
out.writeShort(size);
- for (Object element : elements)
- {
+ for (Object element : elements) {
out.writeObject(element);
}
}
- public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException
- {
+ public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
size = in.readShort();
this.elements = new ArrayList(size);
for (int i = 0; i < size; i++) elements.add(in.readObject());
@@ -428,8 +368,7 @@
/**
- * Returns true if this Fqn is child of parentFqn.
- * Example usage:
+ * Returns true if this Fqn is child of parentFqn. Example usage:
* <pre>
* Fqn<String> f1 = Fqn.fromString("/a/b");
* Fqn<String> f2 = Fqn.fromString("/a/b/c");
@@ -441,8 +380,7 @@
* @param parentFqn candidate parent to test against
* @return true if the target is a child of parentFqn
*/
- public boolean isChildOf(Fqn parentFqn)
- {
+ public boolean isChildOf(Fqn parentFqn) {
return parentFqn.size() != size && isChildOrEquals(parentFqn);
}
@@ -453,14 +391,12 @@
* @param parentFqn parentFqn to compare with
* @return true if this is a direct child, false otherwise.
*/
- public boolean isDirectChildOf(Fqn parentFqn)
- {
+ public boolean isDirectChildOf(Fqn parentFqn) {
return size == parentFqn.size() + 1 && isChildOf(parentFqn);
}
/**
- * Returns true if this Fqn is equals or the child of parentFqn.
- * Example usage:
+ * Returns true if this Fqn is equals or the child of parentFqn. Example usage:
* <pre>
* Fqn<String> f1 = Fqn.fromString("/a/b");
* Fqn<String> f2 = Fqn.fromString("/a/b/c");
@@ -472,17 +408,13 @@
* @param parentFqn candidate parent to test against
* @return true if this Fqn is equals or the child of parentFqn.
*/
- public boolean isChildOrEquals(Fqn parentFqn)
- {
+ public boolean isChildOrEquals(Fqn parentFqn) {
List parentList = parentFqn.elements;
- if (parentList.size() > size)
- {
+ if (parentList.size() > size) {
return false;
}
- for (int i = parentList.size() - 1; i >= 0; i--)
- {
- if (!parentList.get(i).equals(elements.get(i)))
- {
+ for (int i = parentList.size() - 1; i >= 0; i--) {
+ if (!parentList.get(i).equals(elements.get(i))) {
return false;
}
}
@@ -494,22 +426,18 @@
*
* @return a calculated hashcode
*/
- protected int calculateHashCode()
- {
+ protected int calculateHashCode() {
int hashCode = 19;
for (Object o : elements) hashCode = 31 * hashCode + (o == null ? 0 : o.hashCode());
if (hashCode == 0) hashCode = 0xDEADBEEF; // degenerate case
return hashCode;
}
- protected String getStringRepresentation(List elements)
- {
+ protected String getStringRepresentation(List elements) {
StringBuilder builder = new StringBuilder();
- for (Object e : elements)
- {
+ for (Object e : elements) {
// incase user element 'e' does not implement equals() properly, don't rely on their implementation.
- if (!SEPARATOR.equals(e) && !"".equals(e))
- {
+ if (!SEPARATOR.equals(e) && !"".equals(e)) {
builder.append(SEPARATOR);
builder.append(e);
}
@@ -519,9 +447,7 @@
/**
- * Returns the parent of this Fqn.
- * The parent of the root node is {@link #ROOT}.
- * Examples:
+ * Returns the parent of this Fqn. The parent of the root node is {@link #ROOT}. Examples:
* <pre>
* Fqn<String> f1 = Fqn.fromString("/a");
* Fqn<String> f2 = Fqn.fromString("/a/b");
@@ -532,10 +458,8 @@
*
* @return the parent Fqn
*/
- public Fqn getParent()
- {
- switch (size)
- {
+ public Fqn getParent() {
+ switch (size) {
case 0:
case 1:
return root();
@@ -554,8 +478,7 @@
*
* @return true if the Fqn is Fqn.ROOT.
*/
- public boolean isRoot()
- {
+ public boolean isRoot() {
return size == 0;
}
@@ -564,14 +487,10 @@
*
* @return a String representation of the last element that makes up this Fqn.
*/
- public String getLastElementAsString()
- {
- if (isRoot())
- {
+ public String getLastElementAsString() {
+ if (isRoot()) {
return SEPARATOR;
- }
- else
- {
+ } else {
Object last = getLastElement();
if (last instanceof String)
return (String) last;
@@ -581,21 +500,19 @@
}
/**
- * Peeks into the elements that build up this Fqn. The list returned is
- * read-only, to maintain the immutable nature of Fqn.
+ * Peeks into the elements that build up this Fqn. The list returned is read-only, to maintain the immutable nature
+ * of Fqn.
*
* @return an unmodifiable list
*/
- public List peekElements()
- {
+ public List peekElements() {
return elements;
}
/**
* Compares this Fqn to another using {@link FqnComparator}.
*/
- public int compareTo(Fqn fqn)
- {
+ public int compareTo(Fqn fqn) {
return FqnComparator.INSTANCE.compare(this, fqn);
}
@@ -606,8 +523,7 @@
* @param newAncestor nw ancestor to replace with
* @return a new Fqn with ancestors replaced.
*/
- public Fqn replaceAncestor(Fqn oldAncestor, Fqn newAncestor)
- {
+ public Fqn replaceAncestor(Fqn oldAncestor, Fqn newAncestor) {
if (!isChildOf(oldAncestor))
throw new IllegalArgumentException("Old ancestor must be an ancestor of the current Fqn!");
Fqn subFqn = this.getSubFqn(oldAncestor.size(), size());
Modified: core/branches/flat/src/main/java/org/horizon/tree/FqnComparator.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/tree/FqnComparator.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/tree/FqnComparator.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -27,8 +27,7 @@
import java.util.Comparator;
/**
- * Compares the order of two FQN.
- * Sorts by name, then by depth, e.g.
+ * Compares the order of two FQN. Sorts by name, then by depth, e.g.
* <pre>
* aaa/bbb
* xxx
@@ -40,26 +39,22 @@
* @since 1.0
*/
@Immutable
-public class FqnComparator implements Comparator<Fqn>, Serializable
-{
+public class FqnComparator implements Comparator<Fqn>, Serializable {
public static final FqnComparator INSTANCE = new FqnComparator();
/**
- * Returns -1 if the first comes before; 0 if they are the same; 1 if the
- * second Fqn comes before. <code>null</code> always comes first.
+ * Returns -1 if the first comes before; 0 if they are the same; 1 if the second Fqn comes before. <code>null</code>
+ * always comes first.
*/
- public int compare(Fqn fqn1, Fqn fqn2)
- {
+ public int compare(Fqn fqn1, Fqn fqn2) {
int s1 = fqn1.size();
int s2 = fqn2.size();
- if (s1 == 0)
- {
+ if (s1 == 0) {
return (s2 == 0) ? 0 : -1;
}
- if (s2 == 0)
- {
+ if (s2 == 0) {
return 1;
}
@@ -71,27 +66,21 @@
// }
int size = Math.min(s1, s2);
- for (int i = 0; i < size; i++)
- {
+ for (int i = 0; i < size; i++) {
Object e1 = fqn1.get(i);
Object e2 = fqn2.get(i);
- if (e1 == e2)
- {
+ if (e1 == e2) {
continue;
}
- if (e1 == null)
- {
+ if (e1 == null) {
return 0;
}
- if (e2 == null)
- {
+ if (e2 == null) {
return 1;
}
- if (!e1.equals(e2))
- {
+ if (!e1.equals(e2)) {
int c = compareElements(e1, e2);
- if (c != 0)
- {
+ if (c != 0) {
return c;
}
}
@@ -101,19 +90,13 @@
}
/**
- * Compares two Fqn elements.
- * If e1 and e2 are the same class and e1 implements Comparable,
- * returns e1.compareTo(e2).
+ * Compares two Fqn elements. If e1 and e2 are the same class and e1 implements Comparable, returns e1.compareTo(e2).
* Otherwise, returns e1.toString().compareTo(e2.toString()).
*/
- private int compareElements(Object e1, Object e2)
- {
- if (e1.getClass() == e2.getClass() && e1 instanceof Comparable)
- {
+ private int compareElements(Object e1, Object e2) {
+ if (e1.getClass() == e2.getClass() && e1 instanceof Comparable) {
return ((Comparable<Object>) e1).compareTo(e2);
- }
- else
- {
+ } else {
return e1.toString().compareTo(e2.toString());
}
}
Modified: core/branches/flat/src/main/java/org/horizon/tree/Node.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/tree/Node.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/tree/Node.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -27,18 +27,17 @@
import java.util.Set;
/**
- * A Node is a {@link Fqn named} logical grouping of data in the {@link TreeCache} API of JBoss {@link Cache}.
- * A node should be used to contain data for a single data record, for example
- * information about a particular person or account.
+ * A Node is a {@link Fqn named} logical grouping of data in the {@link TreeCache} API of JBoss {@link Cache}. A node
+ * should be used to contain data for a single data record, for example information about a particular person or
+ * account.
* <p/>
- * One purpose of grouping cache data into separate nodes is to minimize transaction
- * locking interference, and increase concurrency. So for example, when multiple threads or
- * possibly distributed caches are acccessing different accounts simultaneously.
+ * One purpose of grouping cache data into separate nodes is to minimize transaction locking interference, and increase
+ * concurrency. So for example, when multiple threads or possibly distributed caches are acccessing different accounts
+ * simultaneously.
* <p/>
- * A node has references to its children, parent (each node except the root - defined by {@link Fqn#ROOT} - has
- * a single parent) and data contained within the node (as key/value pairs). The
- * data access methods are similar to the collections {@link Map} interface,
- * but some are read-only or return copies of the underlying the data.
+ * A node has references to its children, parent (each node except the root - defined by {@link Fqn#ROOT} - has a single
+ * parent) and data contained within the node (as key/value pairs). The data access methods are similar to the
+ * collections {@link Map} interface, but some are read-only or return copies of the underlying the data.
* <p/>
*
* @author <a href="mailto:manik AT jboss DOT org">Manik Surtani (manik AT jboss DOT org)</a>
@@ -46,11 +45,9 @@
* @since 1.0
*/
@ThreadSafe
-public interface Node<K, V>
-{
+public interface Node<K, V> {
/**
- * Returns the parent node.
- * If this is the root node, this method returns <code>null</code>.
+ * Returns the parent node. If this is the root node, this method returns <code>null</code>.
*
* @return the parent node, or null if this is the root node
*/
@@ -73,21 +70,25 @@
/**
* Returns a map containing the data in this {@link Node}.
*
- * @return a {@link Map} containing the data in this {@link Node}. If there is no data, an empty {@link Map} is returned. The {@link Map} returned is always immutable.
+ * @return a {@link Map} containing the data in this {@link Node}. If there is no data, an empty {@link Map} is
+ * returned. The {@link Map} returned is always immutable.
*/
Map<K, V> getData();
/**
* Returns a {@link Set} containing the data in this {@link Node}.
*
- * @return a {@link Set} containing the data in this {@link Node}. If there is no data, an empty {@link Set} is returned. The {@link Set} returned is always immutable.
+ * @return a {@link Set} containing the data in this {@link Node}. If there is no data, an empty {@link Set} is
+ * returned. The {@link Set} returned is always immutable.
*/
Set<K> getKeys();
/**
- * Returns the {@link Fqn} which represents the location of this {@link Node} in the cache structure. The {@link Fqn} returned is absolute.
+ * Returns the {@link Fqn} which represents the location of this {@link Node} in the cache structure. The {@link
+ * Fqn} returned is absolute.
*
- * @return The {@link Fqn} which represents the location of this {@link Node} in the cache structure. The {@link Fqn} returned is absolute.
+ * @return The {@link Fqn} which represents the location of this {@link Node} in the cache structure. The {@link
+ * Fqn} returned is absolute.
*/
Fqn getFqn();
@@ -138,8 +139,8 @@
Node<K, V> getChild(Object name);
/**
- * Associates the specified value with the specified key for this node.
- * If this node previously contained a mapping for this key, the old value is replaced by the specified value.
+ * Associates the specified value with the specified key for this node. If this node previously contained a mapping
+ * for this key, the old value is replaced by the specified value.
*
* @param key key with which the specified value is to be associated.
* @param value value to be associated with the specified key.
@@ -168,8 +169,7 @@
V putIfAbsent(K key, V value);
/**
- * Replace entry for key only if currently mapped to some value.
- * Acts as
+ * Replace entry for key only if currently mapped to some value. Acts as
* <pre>
* if ((node.getKeys().contains(key))
* {
@@ -183,14 +183,12 @@
*
* @param key key with which the specified value is associated.
* @param value value to be associated with the specified key.
- * @return previous value associated with specified key, or <tt>null</tt>
- * if there was no mapping for key.
+ * @return previous value associated with specified key, or <tt>null</tt> if there was no mapping for key.
*/
V replace(K key, V value);
/**
- * Replace entry for key only if currently mapped to given value.
- * Acts as
+ * Replace entry for key only if currently mapped to given value. Acts as
* <pre>
* if (node.get(key).equals(oldValue))
* {
@@ -212,9 +210,8 @@
/**
- * Copies all of the mappings from the specified map to this node's map.
- * If any data exists, existing keys are overwritten with the keys in the new map.
- * The behavior is equivalent to:
+ * Copies all of the mappings from the specified map to this node's map. If any data exists, existing keys are
+ * overwritten with the keys in the new map. The behavior is equivalent to:
* <pre>
* Node node;
* for (Map.Entry me : map.entrySet())
@@ -226,9 +223,9 @@
void putAll(Map<? extends K, ? extends V> map);
/**
- * Similar to {@link #putAll(java.util.Map)} except that it removes any entries that exists in
- * the data map first. Note that this happens atomically, under a single lock. This is the analogous
- * to doing a {@link #clearData()} followed by a {@link #putAll(java.util.Map)} in the same transaction.
+ * Similar to {@link #putAll(java.util.Map)} except that it removes any entries that exists in the data map first.
+ * Note that this happens atomically, under a single lock. This is the analogous to doing a {@link #clearData()}
+ * followed by a {@link #putAll(java.util.Map)} in the same transaction.
*
* @param map map to copy from
*/
@@ -236,22 +233,21 @@
/**
- * Returns the value to which this node maps the specified key.
- * Returns <code>null</code> if the node contains no mapping for this key.
+ * Returns the value to which this node maps the specified key. Returns <code>null</code> if the node contains no
+ * mapping for this key.
*
* @param key key of the data to return
- * @return the value to which this node maps the specified key, or <code>null</code> if the map contains no mapping for this key
+ * @return the value to which this node maps the specified key, or <code>null</code> if the map contains no mapping
+ * for this key
*/
V get(K key);
/**
- * Removes the mapping for this key from this node if it is present.
- * Returns the value to which the node previously associated the key,
- * or <code>null</code> if the node contained no mapping for this key
+ * Removes the mapping for this key from this node if it is present. Returns the value to which the node previously
+ * associated the key, or <code>null</code> if the node contained no mapping for this key
*
* @param key key whose mapping is to be removed
- * @return previous value associated with specified key, or <code>null</code>
- * if there was no mapping for key
+ * @return previous value associated with specified key, or <code>null</code> if there was no mapping for key
*/
V remove(K key);
Modified: core/branches/flat/src/main/java/org/horizon/tree/NodeImpl.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/tree/NodeImpl.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/tree/NodeImpl.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -26,7 +26,11 @@
import org.horizon.util.Immutables;
import org.horizon.util.Util;
-import java.util.*;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
/**
* Implementation backed by an {@link AtomicMap}
@@ -34,79 +38,64 @@
* @author Manik Surtani (<a href="mailto:manik AT jboss DOT org">manik AT jboss DOT org</a>)
* @since 1.0
*/
-public class NodeImpl<K, V> extends TreeStructureSupport implements Node<K, V>
-{
+public class NodeImpl<K, V> extends TreeStructureSupport implements Node<K, V> {
Fqn fqn;
NodeKey dataKey, structureKey;
- public NodeImpl(Fqn fqn, Cache cache)
- {
+ public NodeImpl(Fqn fqn, Cache cache) {
super(cache);
this.fqn = fqn;
dataKey = new NodeKey(fqn, NodeKey.Type.DATA);
structureKey = new NodeKey(fqn, NodeKey.Type.STRUCTURE);
}
- public Node<K, V> getParent()
- {
+ public Node<K, V> getParent() {
if (fqn.isRoot()) return this;
return new NodeImpl(fqn.getParent(), cache);
}
- public Set<Node<K, V>> getChildren()
- {
+ public Set<Node<K, V>> getChildren() {
startAtomic();
- try
- {
+ try {
Set set = new HashSet();
- for (Fqn f : getStructure().values())
- {
+ for (Fqn f : getStructure().values()) {
NodeImpl n = new NodeImpl(f, cache);
set.add(n);
}
return Immutables.immutableSetWrap(set);
}
- finally
- {
+ finally {
endAtomic();
}
}
- public Set<Object> getChildrenNames()
- {
+ public Set<Object> getChildrenNames() {
return Immutables.immutableSetCopy(getStructure().keySet());
}
@SuppressWarnings("unchecked")
- public Map<K, V> getData()
- {
+ public Map<K, V> getData() {
return Collections.unmodifiableMap(new HashMap(getDataInternal()));
// return Immutables.immutableMapCopy(getDataInternal());
}
- public Set<K> getKeys()
- {
+ public Set<K> getKeys() {
startAtomic();
- try
- {
+ try {
return getData().keySet();
}
- finally
- {
+ finally {
endAtomic();
}
}
- public Fqn getFqn()
- {
+ public Fqn getFqn() {
return fqn;
}
- public Node<K, V> addChild(Fqn f)
- {
+ public Node<K, V> addChild(Fqn f) {
startAtomic();
- try
- {
+ try {
Fqn absoluteChildFqn = Fqn.fromRelativeFqn(fqn, f);
NodeImpl child = new NodeImpl(absoluteChildFqn, cache);
AtomicMap<Object, Fqn> s = getStructure();
@@ -115,26 +104,21 @@
createNodeInCache(absoluteChildFqn);
return child;
}
- finally
- {
+ finally {
endAtomic();
}
}
- public boolean removeChild(Fqn f)
- {
+ public boolean removeChild(Fqn f) {
return removeChild(f.getLastElement());
}
- public boolean removeChild(Object childName)
- {
+ public boolean removeChild(Object childName) {
startAtomic();
- try
- {
+ try {
AtomicMap<Object, Fqn> s = getStructure();
Fqn childFqn = s.remove(childName);
- if (childFqn != null)
- {
+ if (childFqn != null) {
Node child = new NodeImpl(childFqn, cache);
child.removeChildren();
cache.remove(new NodeKey(childFqn, NodeKey.Type.DATA));
@@ -145,220 +129,175 @@
return false;
}
- finally
- {
+ finally {
endAtomic();
}
}
- public Node<K, V> getChild(Fqn f)
- {
+ public Node<K, V> getChild(Fqn f) {
startAtomic();
- try
- {
+ try {
if (hasChild(f))
return new NodeImpl(Fqn.fromRelativeFqn(fqn, f), cache);
else
return null;
}
- finally
- {
+ finally {
endAtomic();
}
}
- public Node<K, V> getChild(Object name)
- {
+ public Node<K, V> getChild(Object name) {
startAtomic();
- try
- {
+ try {
if (hasChild(name))
return new NodeImpl(Fqn.fromRelativeElements(fqn, name), cache);
else
return null;
}
- finally
- {
+ finally {
endAtomic();
}
}
- public V put(K key, V value)
- {
+ public V put(K key, V value) {
startAtomic();
- try
- {
+ try {
return getDataInternal().put(key, value);
}
- finally
- {
+ finally {
endAtomic();
}
}
- public V putIfAbsent(K key, V value)
- {
+ public V putIfAbsent(K key, V value) {
startAtomic();
- try
- {
+ try {
AtomicMap<K, V> data = getDataInternal();
if (!data.containsKey(key)) return data.put(key, value);
return null;
}
- finally
- {
+ finally {
endAtomic();
}
}
- public V replace(K key, V value)
- {
+ public V replace(K key, V value) {
startAtomic();
- try
- {
+ try {
AtomicMap<K, V> map = getDataInternal();
if (map.containsKey(key))
return map.put(key, value);
else
return null;
}
- finally
- {
+ finally {
endAtomic();
}
}
- public boolean replace(K key, V oldValue, V newValue)
- {
+ public boolean replace(K key, V oldValue, V newValue) {
startAtomic();
- try
- {
+ try {
AtomicMap<K, V> data = getDataInternal();
V old = data.get(key);
- if (Util.safeEquals(oldValue, old))
- {
+ if (Util.safeEquals(oldValue, old)) {
data.put(key, newValue);
return true;
}
return false;
}
- finally
- {
+ finally {
endAtomic();
}
}
- public void putAll(Map<? extends K, ? extends V> map)
- {
+ public void putAll(Map<? extends K, ? extends V> map) {
startAtomic();
- try
- {
+ try {
getDataInternal().putAll(map);
}
- finally
- {
+ finally {
endAtomic();
}
}
- public void replaceAll(Map<? extends K, ? extends V> map)
- {
+ public void replaceAll(Map<? extends K, ? extends V> map) {
startAtomic();
- try
- {
+ try {
AtomicMap<K, V> data = getDataInternal();
data.clear();
data.putAll(map);
}
- finally
- {
+ finally {
endAtomic();
}
}
- public V get(K key)
- {
+ public V get(K key) {
return getData().get(key);
}
- public V remove(K key)
- {
+ public V remove(K key) {
startAtomic();
- try
- {
+ try {
return getDataInternal().remove(key);
}
- finally
- {
+ finally {
endAtomic();
}
}
- public void clearData()
- {
+ public void clearData() {
getDataInternal().clear();
}
- public int dataSize()
- {
+ public int dataSize() {
return getData().size();
}
- public boolean hasChild(Fqn f)
- {
- if (f.size() > 1)
- {
+ public boolean hasChild(Fqn f) {
+ if (f.size() > 1) {
// indirect child.
Fqn absoluteFqn = Fqn.fromRelativeFqn(fqn, f);
return exists(absoluteFqn);
- }
- else
- {
+ } else {
return hasChild(f.getLastElement());
}
}
- public boolean hasChild(Object o)
- {
+ public boolean hasChild(Object o) {
return getStructure().containsKey(o);
}
- public boolean isValid()
- {
+ public boolean isValid() {
return cache.containsKey(dataKey);
}
- public void removeChildren()
- {
+ public void removeChildren() {
startAtomic();
- try
- {
+ try {
Map<Object, Fqn> s = getStructure();
for (Object o : Immutables.immutableSetCopy(s.keySet())) removeChild(o);
}
- finally
- {
+ finally {
endAtomic();
}
}
- public void evict()
- {
+ public void evict() {
startAtomic();
- try
- {
+ try {
cache.evict(structureKey);
cache.evict(dataKey);
}
- finally
- {
+ finally {
endAtomic();
}
}
- AtomicMap<K, V> getDataInternal()
- {
+ AtomicMap<K, V> getDataInternal() {
return (AtomicMap<K, V>) cache.getAtomicMap(dataKey);
}
@@ -367,13 +306,11 @@
// cache.put(structureKey, s.clone());
// }
- AtomicMap<Object, Fqn> getStructure()
- {
+ AtomicMap<Object, Fqn> getStructure() {
return cache.getAtomicMap(structureKey, Object.class, Fqn.class);
}
- public boolean equals(Object o)
- {
+ public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
@@ -384,14 +321,12 @@
return true;
}
- public int hashCode()
- {
+ public int hashCode() {
return (fqn != null ? fqn.hashCode() : 0);
}
@Override
- public String toString()
- {
+ public String toString() {
return "NodeImpl{" +
"fqn=" + fqn +
'}';
Modified: core/branches/flat/src/main/java/org/horizon/tree/NodeKey.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/tree/NodeKey.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/tree/NodeKey.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -33,24 +33,20 @@
* @author Manik Surtani
* @since 1.0
*/
-public class NodeKey implements Serializable
-{
+public class NodeKey implements Serializable {
Fqn fqn;
Type contents;
- public static enum Type
- {
+ public static enum Type {
DATA, STRUCTURE
}
- public NodeKey(Fqn fqn, Type contents)
- {
+ public NodeKey(Fqn fqn, Type contents) {
this.contents = contents;
this.fqn = fqn;
}
- public boolean equals(Object o)
- {
+ public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
@@ -62,8 +58,7 @@
return true;
}
- public int hashCode()
- {
+ public int hashCode() {
int h = fqn != null ? fqn.hashCode() : 1;
h += ~(h << 9);
h ^= (h >>> 14);
@@ -72,8 +67,7 @@
return h;
}
- public String toString()
- {
+ public String toString() {
return "NodeKey{" +
"contents=" + contents +
", fqn=" + fqn +
Modified: core/branches/flat/src/main/java/org/horizon/tree/NodeNotExistsException.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/tree/NodeNotExistsException.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/tree/NodeNotExistsException.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -28,29 +28,24 @@
* Thrown when an operation is attempted on a non-existing node in the cache
*
* @author <a href="mailto:bela at jboss.com">Bela Ban</a>.
- *
* @since 1.0
*/
-public class NodeNotExistsException extends CacheException
-{
+public class NodeNotExistsException extends CacheException {
private static final long serialVersionUID = 779376138690777440L;
- public NodeNotExistsException()
- {
+ public NodeNotExistsException() {
super();
}
- public NodeNotExistsException(String msg)
- {
+ public NodeNotExistsException(String msg) {
super(msg);
}
- public NodeNotExistsException(String msg, Throwable cause)
- {
+ public NodeNotExistsException(String msg, Throwable cause) {
super(msg, cause);
}
Modified: core/branches/flat/src/main/java/org/horizon/tree/NodeNotValidException.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/tree/NodeNotValidException.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/tree/NodeNotValidException.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -24,30 +24,24 @@
import org.horizon.CacheException;
/**
- * Thrown whenever operations are attempted on a node that is no longer valid. See {@link Node#isValid()}
- * for details.
+ * Thrown whenever operations are attempted on a node that is no longer valid. See {@link Node#isValid()} for details.
*
* @author <a href="mailto:manik at jboss.org">Manik Surtani</a>
* @since 1.0
*/
-public class NodeNotValidException extends CacheException
-{
- public NodeNotValidException()
- {
+public class NodeNotValidException extends CacheException {
+ public NodeNotValidException() {
}
- public NodeNotValidException(Throwable cause)
- {
+ public NodeNotValidException(Throwable cause) {
super(cause);
}
- public NodeNotValidException(String msg)
- {
+ public NodeNotValidException(String msg) {
super(msg);
}
- public NodeNotValidException(String msg, Throwable cause)
- {
+ public NodeNotValidException(String msg, Throwable cause) {
super(msg, cause);
}
}
Modified: core/branches/flat/src/main/java/org/horizon/tree/TreeCache.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/tree/TreeCache.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/tree/TreeCache.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -54,8 +54,7 @@
* @see Node
* @since 1.0
*/
-public interface TreeCache<K, V> extends Lifecycle
-{
+public interface TreeCache<K, V> extends Lifecycle {
/**
* Returns the root node of this cache.
*
@@ -64,71 +63,76 @@
Node<K, V> getRoot();
/**
- * Adds a {@link org.horizon.notifications.annotation.CacheListener}-annotated object to the entire cache. The object passed in needs to be properly annotated with the
- * {@link org.horizon.notifications.annotation.CacheListener} annotation otherwise an {@link org.horizon.notifications.IncorrectCacheListenerException} will be thrown.
+ * Adds a {@link org.horizon.notifications.annotation.CacheListener}-annotated object to the entire cache. The
+ * object passed in needs to be properly annotated with the {@link org.horizon.notifications.annotation.CacheListener}
+ * annotation otherwise an {@link org.horizon.notifications.IncorrectCacheListenerException} will be thrown.
*
* @param listener listener to add
*/
void addCacheListener(Object listener);
/**
- * Removes a {@link org.horizon.notifications.annotation.CacheListener}-annotated object from the cache. The object passed in needs to be properly annotated with the
- * {@link org.horizon.notifications.annotation.CacheListener} annotation otherwise an {@link org.horizon.notifications.IncorrectCacheListenerException} will be thrown.
+ * Removes a {@link org.horizon.notifications.annotation.CacheListener}-annotated object from the cache. The object
+ * passed in needs to be properly annotated with the {@link org.horizon.notifications.annotation.CacheListener}
+ * annotation otherwise an {@link org.horizon.notifications.IncorrectCacheListenerException} will be thrown.
*
* @param listener listener to remove
*/
void removeCacheListener(Object listener);
/**
- * Retrieves an immutable {@link List} of objects annotated as {@link org.horizon.notifications.annotation.CacheListener}s attached to the cache.
+ * Retrieves an immutable {@link List} of objects annotated as {@link org.horizon.notifications.annotation.CacheListener}s
+ * attached to the cache.
*
- * @return an immutable {@link List} of objects annotated as {@link org.horizon.notifications.annotation.CacheListener}s attached to the cache.
+ * @return an immutable {@link List} of objects annotated as {@link org.horizon.notifications.annotation.CacheListener}s
+ * attached to the cache.
*/
Set<Object> getCacheListeners();
/**
- * Associates the specified value with the specified key for a {@link Node} in this cache.
- * If the {@link Node} previously contained a mapping for this key, the old value is replaced by the specified value.
+ * Associates the specified value with the specified key for a {@link Node} in this cache. If the {@link Node}
+ * previously contained a mapping for this key, the old value is replaced by the specified value.
*
* @param fqn <b><i>absolute</i></b> {@link Fqn} to the {@link Node} to be accessed.
* @param key key with which the specified value is to be associated.
* @param value value to be associated with the specified key.
- * @return previous value associated with specified key, or <code>null</code> if there was no mapping for key.
- * A <code>null</code> return can also indicate that the Node previously associated <code>null</code> with the specified key, if the implementation supports null values.
+ * @return previous value associated with specified key, or <code>null</code> if there was no mapping for key. A
+ * <code>null</code> return can also indicate that the Node previously associated <code>null</code> with the
+ * specified key, if the implementation supports null values.
* @throws IllegalStateException if the cache is not in a started state.
*/
V put(Fqn fqn, K key, V value);
/**
- * Convenience method that takes a string representation of an Fqn. Otherwise identical to {@link #put(Fqn, Object, Object)}
+ * Convenience method that takes a string representation of an Fqn. Otherwise identical to {@link #put(Fqn, Object,
+ * Object)}
*
* @param fqn String representation of the Fqn
* @param key key with which the specified value is to be associated.
* @param value value to be associated with the specified key.
- * @return previous value associated with specified key, or <code>null</code> if there was no mapping for key.
- * A <code>null</code> return can also indicate that the Node previously associated <code>null</code> with the specified key, if the implementation supports null values.
+ * @return previous value associated with specified key, or <code>null</code> if there was no mapping for key. A
+ * <code>null</code> return can also indicate that the Node previously associated <code>null</code> with the
+ * specified key, if the implementation supports null values.
* @throws IllegalStateException if the cache is not in a started state
*/
V put(String fqn, K key, V value);
/**
- * Under special operating behavior, associates the value with the specified key for a node identified by the Fqn passed in.
- * <ul>
- * <li> Only goes through if the node specified does not exist; no-op otherwise.</i>
- * <li> Force asynchronous mode for replication to prevent any blocking.</li>
- * <li> invalidation does not take place. </li>
- * <li> 0ms lock timeout to prevent any blocking here either. If the lock is not acquired, this method is a no-op, and swallows the timeout exception.</li>
- * <li> Ongoing transactions are suspended before this call, so failures here will not affect any ongoing transactions.</li>
- * <li> Errors and exceptions are 'silent' - logged at a much lower level than normal, and this method does not throw exceptions</li>
- * </ul>
- * This method is for caching data that has an external representation in storage, where, concurrent modification and
- * transactions are not a consideration, and failure to put the data in the cache should be treated as a 'suboptimal outcome'
- * rather than a 'failing outcome'.
+ * Under special operating behavior, associates the value with the specified key for a node identified by the Fqn
+ * passed in. <ul> <li> Only goes through if the node specified does not exist; no-op otherwise.</i> <li> Force
+ * asynchronous mode for replication to prevent any blocking.</li> <li> invalidation does not take place. </li> <li>
+ * 0ms lock timeout to prevent any blocking here either. If the lock is not acquired, this method is a no-op, and
+ * swallows the timeout exception.</li> <li> Ongoing transactions are suspended before this call, so failures here
+ * will not affect any ongoing transactions.</li> <li> Errors and exceptions are 'silent' - logged at a much lower
+ * level than normal, and this method does not throw exceptions</li> </ul> This method is for caching data that has
+ * an external representation in storage, where, concurrent modification and transactions are not a consideration,
+ * and failure to put the data in the cache should be treated as a 'suboptimal outcome' rather than a 'failing
+ * outcome'.
* <p/>
- * An example of when this method is useful is when data is read from, for example, a legacy datastore, and is cached before
- * returning the data to the caller. Subsequent calls would prefer to get the data from the cache and if the data doesn't exist
- * in the cache, fetch again from the legacy datastore.
+ * An example of when this method is useful is when data is read from, for example, a legacy datastore, and is cached
+ * before returning the data to the caller. Subsequent calls would prefer to get the data from the cache and if the
+ * data doesn't exist in the cache, fetch again from the legacy datastore.
* <p/>
* See <a href="http://jira.jboss.com/jira/browse/JBCACHE-848">JBCACHE-848</a> for details around this feature.
* <p/>
@@ -150,7 +154,8 @@
void put(Fqn fqn, Map<? extends K, ? extends V> data);
/**
- * Convenience method that takes a string representation of an Fqn. Otherwise identical to {@link #put(Fqn, java.util.Map)}
+ * Convenience method that takes a string representation of an Fqn. Otherwise identical to {@link #put(Fqn,
+ * java.util.Map)}
*
* @param fqn String representation of the Fqn
* @param data data map to insert
@@ -159,9 +164,8 @@
void put(String fqn, Map<? extends K, ? extends V> data);
/**
- * Removes the mapping for this key from a Node.
- * Returns the value to which the Node previously associated the key, or
- * <code>null</code> if the Node contained no mapping for this key.
+ * Removes the mapping for this key from a Node. Returns the value to which the Node previously associated the key,
+ * or <code>null</code> if the Node contained no mapping for this key.
*
* @param fqn <b><i>absolute</i></b> {@link Fqn} to the {@link Node} to be accessed.
* @param key key whose mapping is to be removed from the Node
@@ -171,7 +175,8 @@
V remove(Fqn fqn, K key);
/**
- * Convenience method that takes a string representation of an Fqn. Otherwise identical to {@link #remove(Fqn, Object)}
+ * Convenience method that takes a string representation of an Fqn. Otherwise identical to {@link #remove(Fqn,
+ * Object)}
*
* @param fqn string representation of the Fqn to retrieve
* @param key key to remove
@@ -199,7 +204,8 @@
boolean removeNode(String fqn);
/**
- * A convenience method to retrieve a node directly from the cache. Equivalent to calling cache.getRoot().getChild(fqn).
+ * A convenience method to retrieve a node directly from the cache. Equivalent to calling
+ * cache.getRoot().getChild(fqn).
*
* @param fqn fqn of the node to retrieve
* @return a Node object, or a null if the node does not exist.
@@ -228,7 +234,8 @@
V get(Fqn fqn, K key);
/**
- * Convenience method that takes a string representation of an Fqn. Otherwise identical to {@link #get(Fqn, Object)}
+ * Convenience method that takes a string representation of an Fqn. Otherwise identical to {@link #get(Fqn,
+ * Object)}
*
* @param fqn string representation of the Fqn to retrieve
* @param key key to fetch
@@ -276,20 +283,16 @@
void setInvocationContext(InvocationContext ctx);
/**
- * Returns the local address of this cache in a cluster, or <code>null</code>
- * if running in local mode.
+ * Returns the local address of this cache in a cluster, or <code>null</code> if running in local mode.
*
- * @return the local address of this cache in a cluster, or <code>null</code>
- * if running in local mode.
+ * @return the local address of this cache in a cluster, or <code>null</code> if running in local mode.
*/
Address getLocalAddress();
/**
- * Returns a list of members in the cluster, or <code>null</code>
- * if running in local mode.
+ * Returns a list of members in the cluster, or <code>null</code> if running in local mode.
*
- * @return a {@link List} of members in the cluster, or <code>null</code>
- * if running in local mode.
+ * @return a {@link List} of members in the cluster, or <code>null</code> if running in local mode.
*/
List<Address> getMembers();
@@ -335,16 +338,16 @@
* </pre>
* No-op if the node to be moved is the root node.
* <p/>
- * <b>Note</b>: As of 3.0.0 and when using MVCC locking, more specific behaviour is defined as follows:
- * <ul>
- * <li>A no-op if the node is moved unto itself. E.g., <tt>move(fqn, fqn.getParent())</tt> will not do anything.</li>
- * <li>If a target node does not exist it will be created silently, to be more consistent with other APIs such as <tt>put()</tt> on a nonexistent node.</li>
- * <li>If the source node does not exist this is a no-op, to be more consistent with other APIs such as <tt>get()</tt> on a nonexistent node.</li>
- * </ul>
+ * <b>Note</b>: As of 3.0.0 and when using MVCC locking, more specific behaviour is defined as follows: <ul> <li>A
+ * no-op if the node is moved unto itself. E.g., <tt>move(fqn, fqn.getParent())</tt> will not do anything.</li>
+ * <li>If a target node does not exist it will be created silently, to be more consistent with other APIs such as
+ * <tt>put()</tt> on a nonexistent node.</li> <li>If the source node does not exist this is a no-op, to be more
+ * consistent with other APIs such as <tt>get()</tt> on a nonexistent node.</li> </ul>
*
* @param nodeToMove the Fqn of the node to move.
* @param newParent new location under which to attach the node being moved.
- * @throws NodeNotExistsException may throw one of these if the target node does not exist or if a different thread has moved this node elsewhere already.
+ * @throws NodeNotExistsException may throw one of these if the target node does not exist or if a different thread
+ * has moved this node elsewhere already.
* @throws IllegalStateException if {@link #getCacheStatus()} would not return {@link org.horizon.CacheStatus#STARTED}.
*/
void move(Fqn nodeToMove, Fqn newParent) throws NodeNotExistsException;
@@ -368,17 +371,16 @@
Map<K, V> getData(Fqn fqn);
/**
- * Convenience method that takes in a String represenation of the Fqn. Otherwise identical to {@link #getKeys(Fqn)}.
+ * Convenience method that takes in a String represenation of the Fqn. Otherwise identical to {@link
+ * #getKeys(Fqn)}.
*/
Set<K> getKeys(String fqn);
/**
- * Returns a set of attribute keys for the Fqn.
- * Returns null if the node is not found, otherwise a Set.
- * The set is a copy of the actual keys for this node.
+ * Returns a set of attribute keys for the Fqn. Returns null if the node is not found, otherwise a Set. The set is a
+ * copy of the actual keys for this node.
* <p/>
- * A convenience method to retrieving a node and
- * getting keys from the node directly.
+ * A convenience method to retrieving a node and getting keys from the node directly.
*
* @param fqn name of the node
* @throws IllegalStateException if {@link #getCacheStatus()} would not return {@link org.horizon.CacheStatus#STARTED}.
@@ -386,7 +388,8 @@
Set<K> getKeys(Fqn fqn);
/**
- * Convenience method that takes in a String represenation of the Fqn. Otherwise identical to {@link #clearData(Fqn)}.
+ * Convenience method that takes in a String represenation of the Fqn. Otherwise identical to {@link
+ * #clearData(Fqn)}.
*
* @throws IllegalStateException if {@link #getCacheStatus()} would not return {@link CacheStatus#STARTED}.
*/
@@ -395,8 +398,7 @@
/**
* Removes the keys and properties from a named node.
* <p/>
- * A convenience method to retrieving a node and
- * getting keys from the node directly.
+ * A convenience method to retrieving a node and getting keys from the node directly.
*
* @param fqn name of the node
* @throws IllegalStateException if {@link #getCacheStatus()} would not return {@link org.horizon.CacheStatus#STARTED}.
@@ -404,12 +406,13 @@
void clearData(Fqn fqn);
/**
- * Starts a batch. This is a lightweight batching mechanism that groups cache writes together and finally performs the
- * write, persistence and/or replication when {@link #endBatch(boolean)} is called rather than for each invocation on the
- * cache.
+ * Starts a batch. This is a lightweight batching mechanism that groups cache writes together and finally performs
+ * the write, persistence and/or replication when {@link #endBatch(boolean)} is called rather than for each
+ * invocation on the cache.
* <p/>
* Note that if there is an existing transaction in scope and the cache has been configured to use a JTA compliant
- * transaction manager, calls to {@link #startBatch()} and {@link #endBatch(boolean)} are ignored and treated as no-ops.
+ * transaction manager, calls to {@link #startBatch()} and {@link #endBatch(boolean)} are ignored and treated as
+ * no-ops.
* <p/>
*
* @see #endBatch(boolean)
@@ -421,18 +424,20 @@
* Ends an existing ongoing batch. A no-op if a batch has not been started yet.
* <p/>
* Note that if there is an existing transaction in scope and the cache has been configured to use a JTA compliant
- * transaction manager, calls to {@link #startBatch()} and {@link #endBatch(boolean)} are ignored and treated as no-ops.
+ * transaction manager, calls to {@link #startBatch()} and {@link #endBatch(boolean)} are ignored and treated as
+ * no-ops.
* <p/>
*
- * @param successful if <tt>true</tt>, changes made in the batch are committed. If <tt>false</tt>, they are discarded.
+ * @param successful if <tt>true</tt>, changes made in the batch are committed. If <tt>false</tt>, they are
+ * discarded.
* @see #startBatch()
* @since 1.0
*/
void endBatch(boolean successful);
/**
- * Adds a custom interceptor to the interceptor chain, at specified position, where the first interceptor in the chain
- * is at position 0 and the last one at getInterceptorChain().size() - 1.
+ * Adds a custom interceptor to the interceptor chain, at specified position, where the first interceptor in the
+ * chain is at position 0 and the last one at getInterceptorChain().size() - 1.
*
* @param i the interceptor to add
* @param position the position to add the interceptor
@@ -451,8 +456,8 @@
void addInterceptor(CommandInterceptor i, Class<? extends CommandInterceptor> afterInterceptor);
/**
- * Removes the interceptor at a specified position, where the first interceptor in the chain
- * is at position 0 and the last one at getInterceptorChain().size() - 1.
+ * Removes the interceptor at a specified position, where the first interceptor in the chain is at position 0 and the
+ * last one at getInterceptorChain().size() - 1.
*
* @param position the position at which to remove an interceptor
* @since 1.0
Modified: core/branches/flat/src/main/java/org/horizon/tree/TreeCacheImpl.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/tree/TreeCacheImpl.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/tree/TreeCacheImpl.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -40,156 +40,124 @@
* @author Manik Surtani (<a href="mailto:manik AT jboss DOT org">manik AT jboss DOT org</a>)
* @since 1.0
*/
-public class TreeCacheImpl<K, V> extends TreeStructureSupport implements TreeCache<K, V>
-{
+public class TreeCacheImpl<K, V> extends TreeStructureSupport implements TreeCache<K, V> {
private static final Log log = LogFactory.getLog(TreeCacheImpl.class);
private static final boolean trace = log.isTraceEnabled();
- public TreeCacheImpl(Cache<K, V> cache)
- {
+ public TreeCacheImpl(Cache<K, V> cache) {
super(cache);
assertBatchingSupported(cache.getConfiguration());
createRoot();
}
- public Node<K, V> getRoot()
- {
+ public Node<K, V> getRoot() {
return new NodeImpl(Fqn.ROOT, cache);
}
- public V put(String fqn, K key, V value)
- {
+ public V put(String fqn, K key, V value) {
return put(Fqn.fromString(fqn), key, value);
}
- public void putForExternalRead(Fqn fqn, K key, V value)
- {
+ public void putForExternalRead(Fqn fqn, K key, V value) {
put(fqn, key, value); // TODO implement this properly
}
- public void put(Fqn fqn, Map<? extends K, ? extends V> data)
- {
+ public void put(Fqn fqn, Map<? extends K, ? extends V> data) {
startAtomic();
- try
- {
+ try {
getNode(fqn).putAll(data);
}
- finally
- {
+ finally {
endAtomic();
}
}
- public void put(String fqn, Map<? extends K, ? extends V> data)
- {
+ public void put(String fqn, Map<? extends K, ? extends V> data) {
put(Fqn.fromString(fqn), data);
}
@SuppressWarnings("unchecked")
- public V remove(Fqn fqn, K key)
- {
+ public V remove(Fqn fqn, K key) {
startAtomic();
- try
- {
+ try {
AtomicMap map = cache.getAtomicMap(new NodeKey(fqn, NodeKey.Type.DATA));
return map == null ? null : (V) map.remove(key);
}
- finally
- {
+ finally {
endAtomic();
}
}
- public V remove(String fqn, K key)
- {
+ public V remove(String fqn, K key) {
return remove(Fqn.fromString(fqn), key);
}
- public boolean removeNode(Fqn fqn)
- {
+ public boolean removeNode(Fqn fqn) {
if (fqn.isRoot()) return false;
startAtomic();
- try
- {
+ try {
Node<K, V> n = getNode(fqn.getParent());
return n != null && n.removeChild(fqn.getLastElement());
}
- finally
- {
+ finally {
endAtomic();
}
}
- public boolean removeNode(String fqn)
- {
+ public boolean removeNode(String fqn) {
return removeNode(Fqn.fromString(fqn));
}
- public Node<K, V> getNode(Fqn fqn)
- {
+ public Node<K, V> getNode(Fqn fqn) {
startAtomic();
- try
- {
+ try {
if (exists(fqn))
return new NodeImpl(fqn, cache);
else return null;
}
- finally
- {
+ finally {
endAtomic();
}
}
- public Node<K, V> getNode(String fqn)
- {
+ public Node<K, V> getNode(String fqn) {
return getNode(Fqn.fromString(fqn));
}
@SuppressWarnings("unchecked")
- public V get(Fqn fqn, K key)
- {
+ public V get(Fqn fqn, K key) {
Map m = cache.getAtomicMap(new NodeKey(fqn, NodeKey.Type.DATA));
if (m == null) return null;
return (V) m.get(key);
}
- public boolean exists(String f)
- {
+ public boolean exists(String f) {
return exists(Fqn.fromString(f));
}
- public V get(String fqn, K key)
- {
+ public V get(String fqn, K key) {
return get(Fqn.fromString(fqn), key);
}
- public void evict(Fqn fqn, boolean recursive)
- {
+ public void evict(Fqn fqn, boolean recursive) {
boolean removeFromParent;
- if (recursive)
- {
+ if (recursive) {
childFirstEvict(fqn);
removeFromParent = true;
- }
- else
- {
+ } else {
removeFromParent = evictNode((NodeImpl) getNode(fqn), false);
}
- if (!fqn.isRoot() && removeFromParent)
- {
+ if (!fqn.isRoot() && removeFromParent) {
Node parent = getNode(fqn.getParent());
parent.removeChild(fqn.getLastElement());
}
}
- private void childFirstEvict(Fqn fqn)
- {
+ private void childFirstEvict(Fqn fqn) {
Node n = getNode(fqn);
- if (n != null)
- {
- for (Object childName : n.getChildrenNames())
- {
+ if (n != null) {
+ for (Object childName : n.getChildrenNames()) {
childFirstEvict(Fqn.fromRelativeElements(fqn, childName));
}
}
@@ -203,13 +171,10 @@
* @param recursive
* @return
*/
- private boolean evictNode(NodeImpl node, boolean recursive)
- {
+ private boolean evictNode(NodeImpl node, boolean recursive) {
boolean retval = false;
- if (node != null)
- {
- if (recursive || node.getChildrenNames().isEmpty())
- {
+ if (node != null) {
+ if (recursive || node.getChildrenNames().isEmpty()) {
cache.evict(node.structureKey);
retval = true;
}
@@ -218,37 +183,30 @@
return retval;
}
- public void evict(Fqn fqn)
- {
+ public void evict(Fqn fqn) {
startAtomic();
- try
- {
+ try {
getNode(fqn).evict();
}
- finally
- {
+ finally {
endAtomic();
}
}
- public void move(Fqn nodeToMove, Fqn newParent) throws NodeNotExistsException
- {
+ public void move(Fqn nodeToMove, Fqn newParent) throws NodeNotExistsException {
if (nodeToMove == null || newParent == null) throw new NullPointerException("Cannot accept null parameters!");
- if (nodeToMove.getParent().equals(newParent))
- {
+ if (nodeToMove.getParent().equals(newParent)) {
// moving onto self! Do nothing!
return;
}
// Depth first. Lets start with getting the node we want.
startAtomic();
- try
- {
+ try {
Node node = getNode(nodeToMove);
if (node == null) return; // nothing to do here!
- if (!exists(newParent))
- {
+ if (!exists(newParent)) {
// then we need to silently create the new parent
createNodeInCache(newParent);
}
@@ -259,8 +217,7 @@
Node newNode = getNode(newFqn);
Map oldData = node.getData();
if (oldData != null && !oldData.isEmpty()) newNode.putAll(oldData);
- for (Object child : node.getChildrenNames())
- {
+ for (Object child : node.getChildrenNames()) {
// move kids
Fqn oldChildFqn = Fqn.fromRelativeElements(nodeToMove, child);
move(oldChildFqn, newFqn);
@@ -268,182 +225,146 @@
removeNode(nodeToMove);
}
- finally
- {
+ finally {
endAtomic();
}
}
- public void move(String nodeToMove, String newParent) throws NodeNotExistsException
- {
+ public void move(String nodeToMove, String newParent) throws NodeNotExistsException {
move(Fqn.fromString(nodeToMove), Fqn.fromString(newParent));
}
- public Map<K, V> getData(Fqn fqn)
- {
+ public Map<K, V> getData(Fqn fqn) {
startAtomic();
- try
- {
+ try {
return getNode(fqn).getData();
}
- finally
- {
+ finally {
endAtomic();
}
}
- public Set<K> getKeys(String fqn)
- {
+ public Set<K> getKeys(String fqn) {
return getKeys(Fqn.fromString(fqn));
}
- public Set<K> getKeys(Fqn fqn)
- {
+ public Set<K> getKeys(Fqn fqn) {
startAtomic();
- try
- {
+ try {
return getNode(fqn).getKeys();
}
- finally
- {
+ finally {
endAtomic();
}
}
- public void clearData(String fqn)
- {
+ public void clearData(String fqn) {
clearData(Fqn.fromString(fqn));
}
- public void clearData(Fqn fqn)
- {
+ public void clearData(Fqn fqn) {
startAtomic();
- try
- {
+ try {
getNode(fqn).clearData();
}
- finally
- {
+ finally {
endAtomic();
}
}
@SuppressWarnings("unchecked")
- public V put(Fqn fqn, K key, V value)
- {
+ public V put(Fqn fqn, K key, V value) {
if (trace) log.trace("Start: Putting value under key [" + key + "] for node [" + fqn + "]");
startAtomic();
- try
- {
+ try {
createNodeInCache(fqn);
return (V) cache.getAtomicMap(new NodeKey(fqn, NodeKey.Type.DATA)).put(key, value);
}
- finally
- {
+ finally {
endAtomic();
if (trace) log.trace("End: Putting value under key [" + key + "] for node [" + fqn + "]");
}
}
// ------------------ nothing different; just delegate to the cache
- public void addCacheListener(Object listener)
- {
+ public void addCacheListener(Object listener) {
cache.addCacheListener(listener);
}
- public void removeCacheListener(Object listener)
- {
+ public void removeCacheListener(Object listener) {
cache.removeCacheListener(listener);
}
- public Set<Object> getCacheListeners()
- {
+ public Set<Object> getCacheListeners() {
return cache.getCacheListeners();
}
- public void startBatch()
- {
+ public void startBatch() {
cache.startBatch();
}
- public void endBatch(boolean successful)
- {
+ public void endBatch(boolean successful) {
cache.endBatch(successful);
}
- public void addInterceptor(CommandInterceptor i, int position)
- {
+ public void addInterceptor(CommandInterceptor i, int position) {
cache.addInterceptor(i, position);
}
- public void addInterceptor(CommandInterceptor i, Class<? extends CommandInterceptor> afterInterceptor)
- {
+ public void addInterceptor(CommandInterceptor i, Class<? extends CommandInterceptor> afterInterceptor) {
cache.addInterceptor(i, afterInterceptor);
}
- public void removeInterceptor(int position)
- {
+ public void removeInterceptor(int position) {
cache.removeInterceptor(position);
}
- public void removeInterceptor(Class<? extends CommandInterceptor> interceptorType)
- {
+ public void removeInterceptor(Class<? extends CommandInterceptor> interceptorType) {
cache.removeInterceptor(interceptorType);
}
- public Configuration getConfiguration()
- {
+ public Configuration getConfiguration() {
return cache.getConfiguration();
}
- public Cache getCache()
- {
+ public Cache getCache() {
return cache;
}
- public CacheStatus getCacheStatus()
- {
+ public CacheStatus getCacheStatus() {
return cache.getCacheStatus();
}
- public InvocationContext getInvocationContext()
- {
+ public InvocationContext getInvocationContext() {
return cache.getInvocationContext();
}
- public void setInvocationContext(InvocationContext ctx)
- {
+ public void setInvocationContext(InvocationContext ctx) {
cache.setInvocationContext(ctx);
}
- public Address getLocalAddress()
- {
+ public Address getLocalAddress() {
return cache.getLocalAddress();
}
- public List<Address> getMembers()
- {
+ public List<Address> getMembers() {
return cache.getMembers();
}
- public void start() throws CacheException
- {
+ public void start() throws CacheException {
cache.start();
createRoot();
}
- public void stop()
- {
+ public void stop() {
cache.stop();
}
- private void createRoot()
- {
+ private void createRoot() {
if (!exists(Fqn.ROOT)) createNodeInCache(Fqn.ROOT);
}
- public String toString()
- {
+ public String toString() {
return cache.toString();
}
}
Modified: core/branches/flat/src/main/java/org/horizon/tree/TreeStructureSupport.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/tree/TreeStructureSupport.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/tree/TreeStructureSupport.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -27,25 +27,20 @@
import org.horizon.atomic.AtomicMapCache;
import org.horizon.batch.AutoBatchSupport;
-public class TreeStructureSupport extends AutoBatchSupport
-{
+public class TreeStructureSupport extends AutoBatchSupport {
AtomicMapCache cache;
- public TreeStructureSupport(Cache cache)
- {
+ public TreeStructureSupport(Cache cache) {
this.cache = (AtomicMapCache) cache;
batchContainer = ((CacheSPI) cache).getBatchContainer();
}
- public boolean exists(Fqn f)
- {
+ public boolean exists(Fqn f) {
startAtomic();
- try
- {
+ try {
return cache.containsKey(new NodeKey(f, NodeKey.Type.DATA)) && cache.containsKey(new NodeKey(f, NodeKey.Type.STRUCTURE));
}
- finally
- {
+ finally {
endAtomic();
}
}
@@ -54,21 +49,17 @@
* @param fqn
* @return true if created, false if this was not necessary
*/
- boolean createNodeInCache(Fqn fqn)
- {
+ boolean createNodeInCache(Fqn fqn) {
startAtomic();
- try
- {
+ try {
NodeKey dataKey = new NodeKey(fqn, NodeKey.Type.DATA);
NodeKey structureKey = new NodeKey(fqn, NodeKey.Type.STRUCTURE);
if (cache.containsKey(dataKey) && cache.containsKey(structureKey)) return false;
Fqn parent = fqn.getParent();
- if (!fqn.isRoot())
- {
+ if (!fqn.isRoot()) {
if (!exists(parent)) createNodeInCache(parent);
AtomicMap<Object, Fqn> parentStructure = getStructure(parent);
- if (!cache.getConfiguration().isLockParentForChildInsertRemove())
- {
+ if (!cache.getConfiguration().isLockParentForChildInsertRemove()) {
cache.getInvocationContext().getOptionOverrides().setSuppressLocking(true);
}
parentStructure.put(fqn.getLastElement(), fqn);
@@ -80,14 +71,12 @@
cache.getAtomicMap(dataKey);
return true;
}
- finally
- {
+ finally {
endAtomic();
}
}
- AtomicMap<Object, Fqn> getStructure(Fqn fqn)
- {
+ AtomicMap<Object, Fqn> getStructure(Fqn fqn) {
return cache.getAtomicMap(new NodeKey(fqn, NodeKey.Type.STRUCTURE), Object.class, Fqn.class);
}
@@ -96,8 +85,7 @@
// cache.put(new NodeKey(fqn, NodeKey.Type.STRUCTURE), structure.clone());
// }
- public static boolean isLocked(Cache c, Fqn fqn)
- {
+ public static boolean isLocked(Cache c, Fqn fqn) {
org.horizon.lock.LockManager lockManager = ((CacheSPI) c).getLockManager();
return lockManager.isLocked(new NodeKey(fqn, NodeKey.Type.STRUCTURE)) &&
lockManager.isLocked(new NodeKey(fqn, NodeKey.Type.DATA));
@@ -109,8 +97,7 @@
* @param cache cache to dump
* @return String rep
*/
- public static String printTree(TreeCache<?, ?> cache, boolean details)
- {
+ public static String printTree(TreeCache<?, ?> cache, boolean details) {
StringBuilder sb = new StringBuilder();
// sb.append("Raw keys: " + cache.getCache().keySet());
sb.append("\n\n");
@@ -123,10 +110,8 @@
return sb.toString();
}
- private static void addChildren(Node<?, ?> node, int depth, StringBuilder sb, boolean details)
- {
- for (Node<?, ?> child : node.getChildren())
- {
+ private static void addChildren(Node<?, ?> node, int depth, StringBuilder sb, boolean details) {
+ for (Node<?, ?> child : node.getChildren()) {
for (int i = 0; i < depth; i++) sb.append(" "); // indentations
sb.append("+ ");
sb.append(child.getFqn().getLastElementAsString()).append(Fqn.SEPARATOR);
Modified: core/branches/flat/src/main/java/org/horizon/util/BeanUtils.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/util/BeanUtils.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/util/BeanUtils.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -30,22 +30,18 @@
* @author Manik Surtani (<a href="mailto:manik at jboss.org">manik at jboss.org</a>)
* @since 1.0
*/
-public class BeanUtils
-{
+public class BeanUtils {
/**
* Retrieves a setter name based on a field name passed in
*
* @param fieldName field name to find setter for
* @return name of setter method
*/
- public static String setterName(String fieldName)
- {
+ public static String setterName(String fieldName) {
StringBuilder sb = new StringBuilder("set");
- if (fieldName != null && fieldName.length() > 0)
- {
+ if (fieldName != null && fieldName.length() > 0) {
sb.append(fieldName.substring(0, 1).toUpperCase(Locale.ENGLISH));
- if (fieldName.length() > 1)
- {
+ if (fieldName.length() > 1) {
sb.append(fieldName.substring(1));
}
}
@@ -58,8 +54,7 @@
* @param componentClass class to find getter for
* @return name of getter method
*/
- public static String getterName(Class componentClass)
- {
+ public static String getterName(Class componentClass) {
if (componentClass == null) return null;
StringBuilder sb = new StringBuilder("get");
sb.append(componentClass.getSimpleName());
@@ -72,8 +67,7 @@
* @param componentClass class to find setter for
* @return name of getter method
*/
- public static String setterName(Class componentClass)
- {
+ public static String setterName(Class componentClass) {
if (componentClass == null) return null;
StringBuilder sb = new StringBuilder("set");
sb.append(componentClass.getSimpleName());
@@ -88,19 +82,15 @@
* @param componentClass component to get
* @return Method object, or null of one does not exist
*/
- public static Method getterMethod(Class target, Class componentClass)
- {
- try
- {
+ public static Method getterMethod(Class target, Class componentClass) {
+ try {
return target.getMethod(getterName(componentClass));
}
- catch (NoSuchMethodException e)
- {
+ catch (NoSuchMethodException e) {
//if (log.isTraceEnabled()) log.trace("Unable to find method " + getterName(componentClass) + " in class " + target);
return null;
}
- catch (NullPointerException e)
- {
+ catch (NullPointerException e) {
return null;
}
}
@@ -112,19 +102,15 @@
* @param componentClass component to set
* @return Method object, or null of one does not exist
*/
- public static Method setterMethod(Class target, Class componentClass)
- {
- try
- {
+ public static Method setterMethod(Class target, Class componentClass) {
+ try {
return target.getMethod(setterName(componentClass), componentClass);
}
- catch (NoSuchMethodException e)
- {
+ catch (NoSuchMethodException e) {
//if (log.isTraceEnabled()) log.trace("Unable to find method " + setterName(componentClass) + " in class " + target);
return null;
}
- catch (NullPointerException e)
- {
+ catch (NullPointerException e) {
return null;
}
}
Modified: core/branches/flat/src/main/java/org/horizon/util/FastCopyHashMap.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/util/FastCopyHashMap.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/util/FastCopyHashMap.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -39,8 +39,7 @@
* @author Jason T. Greene
* @since 1.0
*/
-public class FastCopyHashMap<K, V> extends AbstractMap<K, V> implements Map<K, V>, Cloneable, Serializable
-{
+public class FastCopyHashMap<K, V> extends AbstractMap<K, V> implements Map<K, V>, Cloneable, Serializable {
/**
* Marks null keys.
*/
@@ -96,8 +95,7 @@
private transient Values values;
private transient EntrySet entrySet;
- public FastCopyHashMap(int initialCapacity, float loadFactor)
- {
+ public FastCopyHashMap(int initialCapacity, float loadFactor) {
if (initialCapacity < 0)
throw new IllegalArgumentException("Can not have a negative size table!");
@@ -112,18 +110,14 @@
}
@SuppressWarnings("unchecked")
- public FastCopyHashMap(Map<? extends K, ? extends V> map)
- {
- if (map instanceof FastCopyHashMap)
- {
+ public FastCopyHashMap(Map<? extends K, ? extends V> map) {
+ if (map instanceof FastCopyHashMap) {
FastCopyHashMap<? extends K, ? extends V> fast = (FastCopyHashMap<? extends K, ? extends V>) map;
this.table = (Entry<K, V>[]) fast.table.clone();
this.loadFactor = fast.loadFactor;
this.size = fast.size;
this.threshold = fast.threshold;
- }
- else
- {
+ } else {
this.loadFactor = DEFAULT_LOAD_FACTOR;
init(map.size(), this.loadFactor);
putAll(map);
@@ -131,8 +125,7 @@
}
@SuppressWarnings("unchecked")
- private void init(int initialCapacity, float loadFactor)
- {
+ private void init(int initialCapacity, float loadFactor) {
int c = 1;
for (; c < initialCapacity; c <<= 1) ;
@@ -141,71 +134,59 @@
threshold = (int) (c * loadFactor);
}
- public FastCopyHashMap(int initialCapacity)
- {
+ public FastCopyHashMap(int initialCapacity) {
this(initialCapacity, DEFAULT_LOAD_FACTOR);
}
- public FastCopyHashMap()
- {
+ public FastCopyHashMap() {
this(DEFAULT_CAPACITY);
}
// The normal bit spreader...
- private static final int hash(Object key)
- {
+ private static final int hash(Object key) {
int h = key.hashCode();
h ^= (h >>> 20) ^ (h >>> 12);
return h ^ (h >>> 7) ^ (h >>> 4);
}
@SuppressWarnings("unchecked")
- private static final <K> K maskNull(K key)
- {
+ private static final <K> K maskNull(K key) {
return key == null ? (K) NULL : key;
}
- private static final <K> K unmaskNull(K key)
- {
+ private static final <K> K unmaskNull(K key) {
return key == NULL ? null : key;
}
- private int nextIndex(int index, int length)
- {
+ private int nextIndex(int index, int length) {
index = (index >= length - 1) ? 0 : index + 1;
return index;
}
- private static final boolean eq(Object o1, Object o2)
- {
+ private static final boolean eq(Object o1, Object o2) {
return o1 == o2 || (o1 != null && o1.equals(o2));
}
- private static final int index(int hashCode, int length)
- {
+ private static final int index(int hashCode, int length) {
return hashCode & (length - 1);
}
- public int size()
- {
+ public int size() {
return size;
}
- public boolean isEmpty()
- {
+ public boolean isEmpty() {
return size == 0;
}
- public V get(Object key)
- {
+ public V get(Object key) {
key = maskNull(key);
int hash = hash(key);
int length = table.length;
int index = index(hash, length);
- for (; ;)
- {
+ for (; ;) {
Entry<K, V> e = table[index];
if (e == null)
return null;
@@ -217,16 +198,14 @@
}
}
- public boolean containsKey(Object key)
- {
+ public boolean containsKey(Object key) {
key = maskNull(key);
int hash = hash(key);
int length = table.length;
int index = index(hash, length);
- for (; ;)
- {
+ for (; ;) {
Entry<K, V> e = table[index];
if (e == null)
return false;
@@ -238,8 +217,7 @@
}
}
- public boolean containsValue(Object value)
- {
+ public boolean containsValue(Object value) {
for (Entry<K, V> e : table)
if (e != null && eq(value, e.value))
return true;
@@ -247,8 +225,7 @@
return false;
}
- public V put(K key, V value)
- {
+ public V put(K key, V value) {
key = maskNull(key);
Entry<K, V>[] table = this.table;
@@ -258,14 +235,12 @@
int index = start;
- for (; ;)
- {
+ for (; ;) {
Entry<K, V> e = table[index];
if (e == null)
break;
- if (e.hash == hash && eq(key, e.key))
- {
+ if (e.hash == hash && eq(key, e.key)) {
table[index] = new Entry<K, V>(e.key, e.hash, value);
return e.value;
}
@@ -285,8 +260,7 @@
@SuppressWarnings("unchecked")
- private void resize(int from)
- {
+ private void resize(int from) {
int newLength = from << 1;
// Can't get any bigger
@@ -296,8 +270,7 @@
Entry<K, V>[] newTable = new Entry[newLength];
Entry<K, V>[] old = table;
- for (Entry<K, V> e : old)
- {
+ for (Entry<K, V> e : old) {
if (e == null)
continue;
@@ -312,14 +285,12 @@
table = newTable;
}
- public void putAll(Map<? extends K, ? extends V> map)
- {
+ public void putAll(Map<? extends K, ? extends V> map) {
int size = map.size();
if (size == 0)
return;
- if (size > threshold)
- {
+ if (size > threshold) {
if (size > MAXIMUM_CAPACITY)
size = MAXIMUM_CAPACITY;
@@ -333,8 +304,7 @@
put(e.getKey(), e.getValue());
}
- public V remove(Object key)
- {
+ public V remove(Object key) {
key = maskNull(key);
Entry<K, V>[] table = this.table;
@@ -342,14 +312,12 @@
int hash = hash(key);
int start = index(hash, length);
- for (int index = start; ;)
- {
+ for (int index = start; ;) {
Entry<K, V> e = table[index];
if (e == null)
return null;
- if (e.hash == hash && eq(key, e.key))
- {
+ if (e.hash == hash && eq(key, e.key)) {
table[index] = null;
relocate(index);
modCount++;
@@ -365,14 +333,12 @@
}
- private void relocate(int start)
- {
+ private void relocate(int start) {
Entry<K, V>[] table = this.table;
int length = table.length;
int current = nextIndex(start, length);
- for (; ;)
- {
+ for (; ;) {
Entry<K, V> e = table[current];
if (e == null)
return;
@@ -382,8 +348,7 @@
// entries to their optimal positions once a gap is created.
int prefer = index(e.hash, length);
if ((current < prefer && (prefer <= start || start <= current))
- || (prefer <= start && start <= current))
- {
+ || (prefer <= start && start <= current)) {
table[start] = e;
table[current] = null;
start = current;
@@ -393,8 +358,7 @@
}
}
- public void clear()
- {
+ public void clear() {
modCount++;
Entry<K, V>[] table = this.table;
for (int i = 0; i < table.length; i++)
@@ -404,10 +368,8 @@
}
@SuppressWarnings("unchecked")
- public Object clone()
- {
- try
- {
+ public Object clone() {
+ try {
FastCopyHashMap<K, V> clone = (FastCopyHashMap<K, V>) super.clone();
clone.table = table.clone();
clone.entrySet = null;
@@ -415,31 +377,26 @@
clone.keySet = null;
return clone;
}
- catch (CloneNotSupportedException e)
- {
+ catch (CloneNotSupportedException e) {
// should never happen
throw new IllegalStateException(e);
}
}
- public void printDebugStats()
- {
+ public void printDebugStats() {
int optimal = 0;
int total = 0;
int totalSkew = 0;
int maxSkew = 0;
- for (int i = 0; i < table.length; i++)
- {
+ for (int i = 0; i < table.length; i++) {
Entry<K, V> e = table[i];
- if (e != null)
- {
+ if (e != null) {
total++;
int target = index(e.hash, table.length);
if (i == target)
optimal++;
- else
- {
+ else {
int skew = Math.abs(i - target);
if (skew > maxSkew) maxSkew = skew;
totalSkew += skew;
@@ -455,24 +412,21 @@
System.out.println(" Max Distance: " + maxSkew);
}
- public Set<Map.Entry<K, V>> entrySet()
- {
+ public Set<Map.Entry<K, V>> entrySet() {
if (entrySet == null)
entrySet = new EntrySet();
return entrySet;
}
- public Set<K> keySet()
- {
+ public Set<K> keySet() {
if (keySet == null)
keySet = new KeySet();
return keySet;
}
- public Collection<V> values()
- {
+ public Collection<V> values() {
if (values == null)
values = new Values();
@@ -480,16 +434,14 @@
}
@SuppressWarnings("unchecked")
- private void readObject(java.io.ObjectInputStream s) throws IOException, ClassNotFoundException
- {
+ private void readObject(java.io.ObjectInputStream s) throws IOException, ClassNotFoundException {
s.defaultReadObject();
int size = s.readInt();
init(size, loadFactor);
- for (int i = 0; i < size; i++)
- {
+ for (int i = 0; i < size; i++) {
K key = (K) s.readObject();
V value = (V) s.readObject();
putForCreate(key, value);
@@ -497,8 +449,7 @@
}
@SuppressWarnings("unchecked")
- private void putForCreate(K key, V value)
- {
+ private void putForCreate(K key, V value) {
key = maskNull(key);
Entry<K, V>[] table = this.table;
@@ -507,8 +458,7 @@
int index = index(hash, length);
Entry<K, V> e = table[index];
- while (e != null)
- {
+ while (e != null) {
index = nextIndex(index, length);
e = table[index];
}
@@ -516,53 +466,44 @@
table[index] = new Entry<K, V>(key, hash, value);
}
- private void writeObject(java.io.ObjectOutputStream s) throws IOException
- {
+ private void writeObject(java.io.ObjectOutputStream s) throws IOException {
s.defaultWriteObject();
s.writeInt(size);
- for (Entry<K, V> e : table)
- {
- if (e != null)
- {
+ for (Entry<K, V> e : table) {
+ if (e != null) {
s.writeObject(unmaskNull(e.key));
s.writeObject(e.value);
}
}
}
- private static final class Entry<K, V>
- {
+ private static final class Entry<K, V> {
final K key;
final int hash;
final V value;
- Entry(K key, int hash, V value)
- {
+ Entry(K key, int hash, V value) {
this.key = key;
this.hash = hash;
this.value = value;
}
}
- private abstract class FasyCopyHashMapIterator<E> implements Iterator<E>
- {
+ private abstract class FasyCopyHashMapIterator<E> implements Iterator<E> {
private int next = 0;
private int expectedCount = modCount;
private int current = -1;
private boolean hasNext;
Entry<K, V> table[] = FastCopyHashMap.this.table;
- public boolean hasNext()
- {
+ public boolean hasNext() {
if (hasNext == true)
return true;
Entry<K, V> table[] = this.table;
- for (int i = next; i < table.length; i++)
- {
- if (table[i] != null)
- {
+ for (int i = next; i < table.length; i++) {
+ if (table[i] != null) {
next = i;
return hasNext = true;
}
@@ -572,8 +513,7 @@
return false;
}
- protected Entry<K, V> nextEntry()
- {
+ protected Entry<K, V> nextEntry() {
if (modCount != expectedCount)
throw new ConcurrentModificationException();
@@ -587,8 +527,7 @@
}
@SuppressWarnings("unchecked")
- public void remove()
- {
+ public void remove() {
if (modCount != expectedCount)
throw new ConcurrentModificationException();
@@ -605,8 +544,7 @@
next = delete;
Entry<K, V>[] table = this.table;
- if (table != FastCopyHashMap.this.table)
- {
+ if (table != FastCopyHashMap.this.table) {
FastCopyHashMap.this.remove(table[delete].key);
table[delete] = null;
expectedCount = modCount;
@@ -620,8 +558,7 @@
table[delete] = null;
size--;
- for (; ;)
- {
+ for (; ;) {
i = nextIndex(i, length);
Entry<K, V> e = table[i];
if (e == null)
@@ -629,12 +566,10 @@
int prefer = index(e.hash, length);
if ((i < prefer && (prefer <= delete || delete <= i))
- || (prefer <= delete && delete <= i))
- {
+ || (prefer <= delete && delete <= i)) {
// Snapshot the unseen portion of the table if we have
// to relocate an entry that was already seen by this iterator
- if (i < current && current <= delete && table == FastCopyHashMap.this.table)
- {
+ if (i < current && current <= delete && table == FastCopyHashMap.this.table) {
int remaining = length - current;
Entry<K, V>[] newTable = (Entry<K, V>[]) new Entry[remaining];
System.arraycopy(table, current, newTable, 0, remaining);
@@ -655,33 +590,25 @@
}
- private class KeyIterator extends FasyCopyHashMapIterator<K>
- {
- public K next()
- {
+ private class KeyIterator extends FasyCopyHashMapIterator<K> {
+ public K next() {
return unmaskNull(nextEntry().key);
}
}
- private class ValueIterator extends FasyCopyHashMapIterator<V>
- {
- public V next()
- {
+ private class ValueIterator extends FasyCopyHashMapIterator<V> {
+ public V next() {
return nextEntry().value;
}
}
- private class EntryIterator extends FasyCopyHashMapIterator<Map.Entry<K, V>>
- {
- private class WriteThroughEntry extends SimpleEntry<K, V>
- {
- WriteThroughEntry(K key, V value)
- {
+ private class EntryIterator extends FasyCopyHashMapIterator<Map.Entry<K, V>> {
+ private class WriteThroughEntry extends SimpleEntry<K, V> {
+ WriteThroughEntry(K key, V value) {
super(key, value);
}
- public V setValue(V value)
- {
+ public V setValue(V value) {
if (table != FastCopyHashMap.this.table)
FastCopyHashMap.this.put(getKey(), value);
@@ -689,71 +616,57 @@
}
}
- public Map.Entry<K, V> next()
- {
+ public Map.Entry<K, V> next() {
Entry<K, V> e = nextEntry();
return new WriteThroughEntry(unmaskNull(e.key), e.value);
}
}
- private class KeySet extends AbstractSet<K>
- {
- public Iterator<K> iterator()
- {
+ private class KeySet extends AbstractSet<K> {
+ public Iterator<K> iterator() {
return new KeyIterator();
}
- public void clear()
- {
+ public void clear() {
FastCopyHashMap.this.clear();
}
- public boolean contains(Object o)
- {
+ public boolean contains(Object o) {
return containsKey(o);
}
- public boolean remove(Object o)
- {
+ public boolean remove(Object o) {
int size = size();
FastCopyHashMap.this.remove(o);
return size() < size;
}
- public int size()
- {
+ public int size() {
return FastCopyHashMap.this.size();
}
}
- private class Values extends AbstractCollection<V>
- {
- public Iterator<V> iterator()
- {
+ private class Values extends AbstractCollection<V> {
+ public Iterator<V> iterator() {
return new ValueIterator();
}
- public void clear()
- {
+ public void clear() {
FastCopyHashMap.this.clear();
}
- public int size()
- {
+ public int size() {
return FastCopyHashMap.this.size();
}
}
- private class EntrySet extends AbstractSet<Map.Entry<K, V>>
- {
- public Iterator<Map.Entry<K, V>> iterator()
- {
+ private class EntrySet extends AbstractSet<Map.Entry<K, V>> {
+ public Iterator<Map.Entry<K, V>> iterator() {
return new EntryIterator();
}
- public boolean contains(Object o)
- {
+ public boolean contains(Object o) {
if (!(o instanceof Map.Entry))
return false;
@@ -762,58 +675,48 @@
return eq(entry.getValue(), value);
}
- public void clear()
- {
+ public void clear() {
FastCopyHashMap.this.clear();
}
- public boolean isEmpty()
- {
+ public boolean isEmpty() {
return FastCopyHashMap.this.isEmpty();
}
- public int size()
- {
+ public int size() {
return FastCopyHashMap.this.size();
}
}
- protected static class SimpleEntry<K, V> implements Map.Entry<K, V>
- {
+ protected static class SimpleEntry<K, V> implements Map.Entry<K, V> {
private K key;
private V value;
- SimpleEntry(K key, V value)
- {
+ SimpleEntry(K key, V value) {
this.key = key;
this.value = value;
}
- SimpleEntry(Map.Entry<K, V> entry)
- {
+ SimpleEntry(Map.Entry<K, V> entry) {
this.key = entry.getKey();
this.value = entry.getValue();
}
- public K getKey()
- {
+ public K getKey() {
return key;
}
- public V getValue()
- {
+ public V getValue() {
return value;
}
- public V setValue(V value)
- {
+ public V setValue(V value) {
V old = this.value;
this.value = value;
return old;
}
- public boolean equals(Object o)
- {
+ public boolean equals(Object o) {
if (this == o)
return true;
@@ -823,14 +726,12 @@
return eq(key, e.getKey()) && eq(value, e.getValue());
}
- public int hashCode()
- {
+ public int hashCode() {
return hash(key) ^
(value == null ? 0 : hash(value));
}
- public String toString()
- {
+ public String toString() {
return getKey() + "=" + getValue();
}
}
Modified: core/branches/flat/src/main/java/org/horizon/util/FileLookup.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/util/FileLookup.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/util/FileLookup.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -32,18 +32,14 @@
import java.net.URL;
/**
- * Holds the logic of looking up a file, in the following sequence:
- * <ol>
- * <li> try to load it with the curent thread's context ClassLoader</li>
- * <li> if fails, the system ClassLoader</li>
- * <li> if fails, try to load it as a file from the disck </li>
- * </ol>
+ * Holds the logic of looking up a file, in the following sequence: <ol> <li> try to load it with the curent thread's
+ * context ClassLoader</li> <li> if fails, the system ClassLoader</li> <li> if fails, try to load it as a file from the
+ * disck </li> </ol>
*
* @author Mircea.Markus at jboss.com
* @since 1.0
*/
-public class FileLookup
-{
+public class FileLookup {
private static final Log log = LogFactory.getLog(FileLookup.class);
/**
@@ -52,55 +48,44 @@
* @param filename might be the name of the file (too look it up in the class path) or an url to a file.
* @return an input stream to the file or null if nothing found through all lookup steps.
*/
- public InputStream lookupFile(String filename)
- {
+ public InputStream lookupFile(String filename) {
InputStream is = getAsInputStreamFromClassLoader(filename);
- if (is == null)
- {
+ if (is == null) {
if (log.isDebugEnabled())
log.debug("Unable to find configuration file " + filename + " in classpath; searching for this file on the filesystem instead.");
- try
- {
+ try {
is = new FileInputStream(filename);
}
- catch (FileNotFoundException e)
- {
+ catch (FileNotFoundException e) {
return null;
}
}
return is;
}
- protected InputStream getAsInputStreamFromClassLoader(String filename)
- {
+ protected InputStream getAsInputStreamFromClassLoader(String filename) {
ClassLoader cl = Thread.currentThread().getContextClassLoader();
InputStream is = cl == null ? null : cl.getResourceAsStream(filename);
- if (is == null)
- {
+ if (is == null) {
// check system class loader
is = getClass().getClassLoader().getResourceAsStream(filename);
}
return is;
}
- public URL lookupFileLocation(String filename)
- {
+ public URL lookupFileLocation(String filename) {
ClassLoader cl = Thread.currentThread().getContextClassLoader();
URL u = cl == null ? null : cl.getResource(filename);
- if (u == null)
- {
+ if (u == null) {
// check system class loader
u = getClass().getClassLoader().getResource(filename);
}
- if (u == null)
- {
+ if (u == null) {
File f = new File(filename);
- if (f.exists()) try
- {
+ if (f.exists()) try {
u = f.toURL();
}
- catch (MalformedURLException e)
- {
+ catch (MalformedURLException e) {
// what do we do here?
}
}
Modified: core/branches/flat/src/main/java/org/horizon/util/ImmutableListCopy.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/util/ImmutableListCopy.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/util/ImmutableListCopy.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -28,13 +28,16 @@
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.lang.reflect.Array;
-import java.util.*;
+import java.util.AbstractList;
+import java.util.Collection;
+import java.util.Iterator;
+import java.util.List;
+import java.util.ListIterator;
+import java.util.NoSuchElementException;
/**
- * A lightweight, read-only copy of a List. Typically used in place of the common idiom:
- * <code>
- * return Collections.unmodifiableList(new ArrayList( myInternalList ));
- * </code>
+ * A lightweight, read-only copy of a List. Typically used in place of the common idiom: <code> return
+ * Collections.unmodifiableList(new ArrayList( myInternalList )); </code>
* <p/>
* a it is far more efficient than making a defensive copy and then wrapping the defensive copy in a read-only wrapper.
* <p/>
@@ -45,18 +48,15 @@
* @since 1.0
*/
@Immutable
-public class ImmutableListCopy<E> extends AbstractList<E> implements Externalizable, Immutables.Immutable
-{
+public class ImmutableListCopy<E> extends AbstractList<E> implements Externalizable, Immutables.Immutable {
private static final long serialVersionUID = 10929568968966L;
private E[] elements;
private int size;
/**
- * Constructs a new ImmutableListCopy.
- * Required by Serialization.
+ * Constructs a new ImmutableListCopy. Required by Serialization.
*/
- public ImmutableListCopy()
- {
+ public ImmutableListCopy() {
}
/**
@@ -65,8 +65,7 @@
* @param c collection to copy from
*/
@SuppressWarnings("unchecked")
- public ImmutableListCopy(Collection<? extends E> c)
- {
+ public ImmutableListCopy(Collection<? extends E> c) {
size = c.size();
Object[] el = new Object[size]; // no room for growth;
el = c.toArray(el);
@@ -78,8 +77,7 @@
*
* @param array to reference
*/
- public ImmutableListCopy(E[] array)
- {
+ public ImmutableListCopy(E[] array) {
size = array.length;
elements = array;
}
@@ -91,8 +89,7 @@
* @param collection2 collection to copy from
*/
@SuppressWarnings("unchecked")
- public ImmutableListCopy(Collection<? extends E> collection1, Collection<? extends E> collection2)
- {
+ public ImmutableListCopy(Collection<? extends E> collection1, Collection<? extends E> collection2) {
size = collection1.size() + collection2.size();
elements = (E[]) new Object[size]; // no room for growth;
Object[] c1 = new Object[collection1.size()];
@@ -104,32 +101,27 @@
}
@Override
- public final int size()
- {
+ public final int size() {
return size;
}
@Override
- public final boolean isEmpty()
- {
+ public final boolean isEmpty() {
return size == 0;
}
@Override
- public final boolean contains(Object o)
- {
+ public final boolean contains(Object o) {
return indexOf(o) >= 0;
}
@Override
- public final Iterator<E> iterator()
- {
+ public final Iterator<E> iterator() {
return new ImmutableIterator();
}
@Override
- public final Object[] toArray()
- {
+ public final Object[] toArray() {
Object[] result = new Object[size];
System.arraycopy(elements, 0, result, 0, size);
return result;
@@ -137,10 +129,8 @@
@Override
@SuppressWarnings("unchecked")
- public final <T> T[] toArray(T[] a)
- {
- if (a.length < size)
- {
+ public final <T> T[] toArray(T[] a) {
+ if (a.length < size) {
a = (T[]) Array.newInstance(a.getClass().getComponentType(), size);
}
System.arraycopy(elements, 0, a, 0, size);
@@ -149,61 +139,48 @@
}
@Override
- public final boolean add(E o)
- {
+ public final boolean add(E o) {
throw new UnsupportedOperationException();
}
@Override
- public final boolean remove(Object o)
- {
+ public final boolean remove(Object o) {
throw new UnsupportedOperationException();
}
@Override
- public final boolean addAll(Collection<? extends E> c)
- {
+ public final boolean addAll(Collection<? extends E> c) {
throw new UnsupportedOperationException();
}
@Override
- public final boolean addAll(int index, Collection<? extends E> c)
- {
+ public final boolean addAll(int index, Collection<? extends E> c) {
throw new UnsupportedOperationException();
}
@Override
- public final boolean removeAll(Collection<?> c)
- {
+ public final boolean removeAll(Collection<?> c) {
throw new UnsupportedOperationException();
}
@Override
- public final boolean retainAll(Collection<?> c)
- {
+ public final boolean retainAll(Collection<?> c) {
throw new UnsupportedOperationException();
}
- public final E get(int index)
- {
+ public final E get(int index) {
if (index >= size || index < 0) throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
return elements[index];
}
@Override
- public final int indexOf(Object o)
- {
- if (o == null)
- {
- for (int i = 0; i < size; i++)
- {
+ public final int indexOf(Object o) {
+ if (o == null) {
+ for (int i = 0; i < size; i++) {
if (elements[i] == null) return i;
}
- }
- else
- {
- for (int i = 0; i < size; i++)
- {
+ } else {
+ for (int i = 0; i < size; i++) {
if (o.equals(elements[i])) return i;
}
}
@@ -211,19 +188,13 @@
}
@Override
- public final int lastIndexOf(Object o)
- {
- if (o == null)
- {
- for (int i = size - 1; i >= 0; i--)
- {
+ public final int lastIndexOf(Object o) {
+ if (o == null) {
+ for (int i = size - 1; i >= 0; i--) {
if (elements[i] == null) return i;
}
- }
- else
- {
- for (int i = size - 1; i >= 0; i--)
- {
+ } else {
+ for (int i = size - 1; i >= 0; i--) {
if (o.equals(elements[i])) return i;
}
}
@@ -231,33 +202,27 @@
}
@Override
- public final ListIterator<E> listIterator()
- {
+ public final ListIterator<E> listIterator() {
return new ImmutableIterator();
}
@Override
- public final ListIterator<E> listIterator(int index)
- {
+ public final ListIterator<E> listIterator(int index) {
return new ImmutableIterator(index);
}
@Override
- public final List<E> subList(int fromIndex, int toIndex)
- {
+ public final List<E> subList(int fromIndex, int toIndex) {
return new ImmutableSubList<E>(fromIndex, toIndex);
}
/**
- * Format:
- * - entry array size (int)
- * - elements (Object)
+ * Format: - entry array size (int) - elements (Object)
*
* @param out stream to write to
* @throws IOException
*/
- public void writeExternal(ObjectOutput out) throws IOException
- {
+ public void writeExternal(ObjectOutput out) throws IOException {
out.writeInt(size);
for (E e : elements) out.writeObject(e);
}
@@ -270,94 +235,75 @@
* @throws ClassNotFoundException
*/
@SuppressWarnings("unchecked")
- public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException
- {
+ public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
size = in.readInt();
elements = (E[]) new Object[size];
for (int i = 0; i < size; i++) elements[i] = (E) in.readObject();
}
- private class ImmutableIterator implements ListIterator<E>
- {
+ private class ImmutableIterator implements ListIterator<E> {
int cursor = 0;
- ImmutableIterator(int index)
- {
+ ImmutableIterator(int index) {
if (index < 0 || index > size()) throw new IndexOutOfBoundsException("Index: " + index);
cursor = index;
}
- ImmutableIterator()
- {
+ ImmutableIterator() {
}
- public boolean hasNext()
- {
+ public boolean hasNext() {
return cursor != size;
}
- public E next()
- {
- try
- {
+ public E next() {
+ try {
return get(cursor++);
}
- catch (IndexOutOfBoundsException e)
- {
+ catch (IndexOutOfBoundsException e) {
throw new NoSuchElementException();
}
}
- public void remove()
- {
+ public void remove() {
throw new UnsupportedOperationException();
}
- public boolean hasPrevious()
- {
+ public boolean hasPrevious() {
return cursor != 0;
}
- public E previous()
- {
- try
- {
+ public E previous() {
+ try {
return get(--cursor);
}
- catch (IndexOutOfBoundsException e)
- {
+ catch (IndexOutOfBoundsException e) {
throw new NoSuchElementException();
}
}
- public int nextIndex()
- {
+ public int nextIndex() {
return cursor;
}
- public int previousIndex()
- {
+ public int previousIndex() {
return cursor - 1;
}
- public void set(E o)
- {
+ public void set(E o) {
throw new UnsupportedOperationException();
}
- public void add(E o)
- {
+ public void add(E o) {
throw new UnsupportedOperationException();
}
}
- private class ImmutableSubList<E> extends AbstractList<E>
- {
+ private class ImmutableSubList<E> extends AbstractList<E> {
private int offset;
private int size;
- ImmutableSubList(int fromIndex, int toIndex)
- {
+ ImmutableSubList(int fromIndex, int toIndex) {
if (fromIndex < 0 || toIndex > ImmutableListCopy.this.size || fromIndex > toIndex)
throw new IllegalArgumentException("fromIndex(" + fromIndex + "), toIndex(" + toIndex + "), size (" + ImmutableListCopy.this.size + "), List=" + ImmutableListCopy.this.toString());
offset = fromIndex;
@@ -365,109 +311,91 @@
}
@SuppressWarnings("unchecked")
- public final E get(int index)
- {
+ public final E get(int index) {
if (index < 0 || index >= size) throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
return (E) ImmutableListCopy.this.get(index + offset);
}
- public final int size()
- {
+ public final int size() {
return size;
}
@Override
- protected final void removeRange(int fromIndex, int toIndex)
- {
+ protected final void removeRange(int fromIndex, int toIndex) {
throw new UnsupportedOperationException();
}
@Override
- public final boolean addAll(Collection<? extends E> c)
- {
+ public final boolean addAll(Collection<? extends E> c) {
throw new UnsupportedOperationException();
}
@Override
- public final boolean addAll(int index, Collection<? extends E> c)
- {
+ public final boolean addAll(int index, Collection<? extends E> c) {
throw new UnsupportedOperationException();
}
@Override
- public final Iterator<E> iterator()
- {
+ public final Iterator<E> iterator() {
return listIterator();
}
@Override
- public final ListIterator<E> listIterator(final int index)
- {
+ public final ListIterator<E> listIterator(final int index) {
if (index < 0 || (index != 0 && index >= size))
throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
- return new ListIterator<E>()
- {
+ return new ListIterator<E>() {
private ListIterator i = ImmutableListCopy.this.listIterator(index + offset);
- public boolean hasNext()
- {
+ public boolean hasNext() {
return nextIndex() < size;
}
@SuppressWarnings("unchecked")
- public E next()
- {
+ public E next() {
if (hasNext())
return (E) i.next();
else
throw new NoSuchElementException();
}
- public boolean hasPrevious()
- {
+ public boolean hasPrevious() {
return previousIndex() >= 0;
}
@SuppressWarnings("unchecked")
- public E previous()
- {
+ public E previous() {
if (hasPrevious())
return (E) i.previous();
else
throw new NoSuchElementException();
}
- public int nextIndex()
- {
+ public int nextIndex() {
return i.nextIndex() - offset;
}
- public int previousIndex()
- {
+ public int previousIndex() {
return i.previousIndex() - offset;
}
- public void remove()
- {
+ public void remove() {
throw new UnsupportedOperationException();
}
- public void set(E o)
- {
+ public void set(E o) {
throw new UnsupportedOperationException();
}
- public void add(E o)
- {
+ public void add(E o) {
throw new UnsupportedOperationException();
}
};
}
@Override
- public final List<E> subList(int fromIndex, int toIndex)
- {
+ public final List<E> subList(int fromIndex, int toIndex) {
return new ImmutableSubList<E>(offset + fromIndex, offset + toIndex);
}
}
Modified: core/branches/flat/src/main/java/org/horizon/util/Immutables.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/util/Immutables.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/util/Immutables.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -23,8 +23,15 @@
import java.io.Serializable;
import java.lang.reflect.Array;
-import java.util.*;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
import java.util.Map.Entry;
+import java.util.Set;
/**
* Factory for generating immutable type wrappers.
@@ -32,16 +39,14 @@
* @author Jason T. Greene
* @since 1.0
*/
-public class Immutables
-{
+public class Immutables {
/**
* Whether or not this collection type is immutable
*
* @param o a Collection, Set, List, or Map
* @return true if immutable, false if not
*/
- public static boolean isImmutable(Object o)
- {
+ public static boolean isImmutable(Object o) {
return o instanceof Immutable;
}
@@ -51,8 +56,7 @@
* @param source the collection to convert
* @return a copied/converted immutable list
*/
- public static <T> List<T> immutableListConvert(Collection<? extends T> source)
- {
+ public static <T> List<T> immutableListConvert(Collection<? extends T> source) {
return new ImmutableListCopy<T>(source);
}
@@ -62,8 +66,7 @@
* @param list the list to copy
* @return the immutable copy
*/
- public static <T> List<T> immutableListCopy(List<? extends T> list)
- {
+ public static <T> List<T> immutableListCopy(List<? extends T> list) {
return new ImmutableListCopy<T>(list);
}
@@ -74,8 +77,7 @@
* @param array the array to wrap
* @return a list containing the array
*/
- public static <T> List<T> immutableListWrap(T... array)
- {
+ public static <T> List<T> immutableListWrap(T... array) {
return new ImmutableListCopy<T>(array);
}
@@ -86,8 +88,7 @@
* @param list2 contains the successor elements of the new list
* @return a new immutable merged copy of list1 and list2
*/
- public static <T> List<T> immutableListMerge(List<? extends T> list1, List<? extends T> list2)
- {
+ public static <T> List<T> immutableListMerge(List<? extends T> list1, List<? extends T> list2) {
return new ImmutableListCopy<T>(list1, list2);
}
@@ -97,8 +98,7 @@
* @param collection the collection to convert/copy
* @return a new immutable set containing the elements in collection
*/
- public static <T> Set<T> immutableSetConvert(Collection<? extends T> collection)
- {
+ public static <T> Set<T> immutableSetConvert(Collection<? extends T> collection) {
return immutableSetWrap(new HashSet<T>(collection));
}
@@ -108,8 +108,7 @@
* @param set the set to wrap
* @return an immutable set wrapper that delegates to the original set
*/
- public static <T> Set<T> immutableSetWrap(Set<? extends T> set)
- {
+ public static <T> Set<T> immutableSetWrap(Set<? extends T> set) {
return new ImmutableSetWrapper<T>(set);
}
@@ -119,8 +118,7 @@
* @param set the set to copy from
* @return an immutable set copy
*/
- public static <T> Set<T> immutableSetCopy(Set<? extends T> set)
- {
+ public static <T> Set<T> immutableSetCopy(Set<? extends T> set) {
Set<? extends T> copy = ObjectDuplicator.duplicateSet(set);
if (copy == null)
// Set uses Collection copy-ctor
@@ -138,8 +136,7 @@
* @param map the map to wrap
* @return an immutable map wrapper that delegates to the original map
*/
- public static <K, V> Map<K, V> immutableMapWrap(Map<? extends K, ? extends V> map)
- {
+ public static <K, V> Map<K, V> immutableMapWrap(Map<? extends K, ? extends V> map) {
return new ImmutableMapWrapper<K, V>(map);
}
@@ -149,8 +146,7 @@
* @param map the map to copy from
* @return an immutable map copy
*/
- public static <K, V> Map<K, V> immutableMapCopy(Map<? extends K, ? extends V> map)
- {
+ public static <K, V> Map<K, V> immutableMapCopy(Map<? extends K, ? extends V> map) {
Map<? extends K, ? extends V> copy = ObjectDuplicator.duplicateMap(map);
if (copy == null)
@@ -167,8 +163,7 @@
* @param collection the collection to copy
* @return an immutable copy
*/
- public static <T> Collection<T> immutableCollectionCopy(Collection<? extends T> collection)
- {
+ public static <T> Collection<T> immutableCollectionCopy(Collection<? extends T> collection) {
Collection<? extends T> copy = ObjectDuplicator.duplicateCollection(collection);
if (copy == null)
copy = attemptCopyConstructor(collection, Collection.class);
@@ -179,22 +174,18 @@
}
@SuppressWarnings("unchecked")
- private static <T> T attemptCopyConstructor(T source, Class<? super T> clazz)
- {
- try
- {
+ private static <T> T attemptCopyConstructor(T source, Class<? super T> clazz) {
+ try {
return (T) source.getClass().getConstructor(clazz).newInstance(source);
}
- catch (Exception e)
- {
+ catch (Exception e) {
}
return null;
}
- public interface Immutable
- {
+ public interface Immutable {
}
/*
@@ -204,171 +195,139 @@
* simple to detect them (the class names are JDK dependent).
*/
- private static class ImmutableIteratorWrapper<E> implements Iterator<E>
- {
+ private static class ImmutableIteratorWrapper<E> implements Iterator<E> {
private Iterator<? extends E> iterator;
- public ImmutableIteratorWrapper(Iterator<? extends E> iterator)
- {
+ public ImmutableIteratorWrapper(Iterator<? extends E> iterator) {
this.iterator = iterator;
}
- public boolean hasNext()
- {
+ public boolean hasNext() {
return iterator.hasNext();
}
- public E next()
- {
+ public E next() {
return iterator.next();
}
- public void remove()
- {
+ public void remove() {
throw new UnsupportedOperationException();
}
}
- private static class ImmutableCollectionWrapper<E> implements Collection<E>, Serializable, Immutable
- {
+ private static class ImmutableCollectionWrapper<E> implements Collection<E>, Serializable, Immutable {
private static final long serialVersionUID = 6777564328198393535L;
Collection<? extends E> collection;
- public ImmutableCollectionWrapper(Collection<? extends E> collection)
- {
+ public ImmutableCollectionWrapper(Collection<? extends E> collection) {
this.collection = collection;
}
- public boolean add(E o)
- {
+ public boolean add(E o) {
throw new UnsupportedOperationException();
}
- public boolean addAll(Collection<? extends E> c)
- {
+ public boolean addAll(Collection<? extends E> c) {
throw new UnsupportedOperationException();
}
- public void clear()
- {
+ public void clear() {
throw new UnsupportedOperationException();
}
- public boolean contains(Object o)
- {
+ public boolean contains(Object o) {
return collection.contains(o);
}
- public boolean containsAll(Collection<?> c)
- {
+ public boolean containsAll(Collection<?> c) {
return collection.containsAll(c);
}
- public boolean equals(Object o)
- {
+ public boolean equals(Object o) {
return collection.equals(o);
}
- public int hashCode()
- {
+ public int hashCode() {
return collection.hashCode();
}
- public boolean isEmpty()
- {
+ public boolean isEmpty() {
return collection.isEmpty();
}
- public Iterator<E> iterator()
- {
+ public Iterator<E> iterator() {
return new ImmutableIteratorWrapper<E>(collection.iterator());
}
- public boolean remove(Object o)
- {
+ public boolean remove(Object o) {
throw new UnsupportedOperationException();
}
- public boolean removeAll(Collection<?> c)
- {
+ public boolean removeAll(Collection<?> c) {
throw new UnsupportedOperationException();
}
- public boolean retainAll(Collection<?> c)
- {
+ public boolean retainAll(Collection<?> c) {
throw new UnsupportedOperationException();
}
- public int size()
- {
+ public int size() {
return collection.size();
}
- public Object[] toArray()
- {
+ public Object[] toArray() {
return collection.toArray();
}
- public <T> T[] toArray(T[] a)
- {
+ public <T> T[] toArray(T[] a) {
return collection.toArray(a);
}
- public String toString()
- {
+ public String toString() {
return collection.toString();
}
}
- private static class ImmutableSetWrapper<E> extends ImmutableCollectionWrapper<E> implements Set<E>, Serializable, Immutable
- {
+ private static class ImmutableSetWrapper<E> extends ImmutableCollectionWrapper<E> implements Set<E>, Serializable, Immutable {
private static final long serialVersionUID = 7991492805176142615L;
- public ImmutableSetWrapper(Set<? extends E> set)
- {
+ public ImmutableSetWrapper(Set<? extends E> set) {
super(set);
}
}
- static class ImmutableEntry<K, V> implements Entry<K, V>
- {
+ static class ImmutableEntry<K, V> implements Entry<K, V> {
private K key;
private V value;
private int hash;
- ImmutableEntry(Entry<? extends K, ? extends V> entry)
- {
+ ImmutableEntry(Entry<? extends K, ? extends V> entry) {
this.key = entry.getKey();
this.value = entry.getValue();
this.hash = entry.hashCode();
}
- public K getKey()
- {
+ public K getKey() {
return key;
}
- public V getValue()
- {
+ public V getValue() {
return value;
}
- public V setValue(V value)
- {
+ public V setValue(V value) {
throw new UnsupportedOperationException();
}
- private static boolean eq(Object o1, Object o2)
- {
+ private static boolean eq(Object o1, Object o2) {
return o1 == o2 || (o1 != null && o1.equals(o2));
}
@SuppressWarnings("unchecked")
- public boolean equals(Object o)
- {
+ public boolean equals(Object o) {
if (!(o instanceof Entry))
return false;
@@ -376,29 +335,24 @@
return eq(entry.getKey(), key) && eq(entry.getValue(), value);
}
- public int hashCode()
- {
+ public int hashCode() {
return hash;
}
- public String toString()
- {
+ public String toString() {
return getKey() + "=" + getValue();
}
}
- private static class ImmutableEntrySetWrapper<K, V> extends ImmutableSetWrapper<Entry<K, V>>
- {
+ private static class ImmutableEntrySetWrapper<K, V> extends ImmutableSetWrapper<Entry<K, V>> {
private static final long serialVersionUID = 6378667653889667692L;
@SuppressWarnings("unchecked")
- public ImmutableEntrySetWrapper(Set<? extends Entry<? extends K, ? extends V>> set)
- {
+ public ImmutableEntrySetWrapper(Set<? extends Entry<? extends K, ? extends V>> set) {
super((Set<Entry<K, V>>) set);
}
- public Object[] toArray()
- {
+ public Object[] toArray() {
Object[] array = new Object[collection.size()];
int i = 0;
for (Entry<K, V> entry : this)
@@ -407,8 +361,7 @@
}
@SuppressWarnings("unchecked")
- public <T> T[] toArray(T[] array)
- {
+ public <T> T[] toArray(T[] array) {
int size = collection.size();
if (array.length < size)
array = (T[]) Array.newInstance(array.getClass().getComponentType(), size);
@@ -421,101 +374,81 @@
return array;
}
- public Iterator<Entry<K, V>> iterator()
- {
- return new ImmutableIteratorWrapper<Entry<K, V>>(collection.iterator())
- {
- public Entry<K, V> next()
- {
+ public Iterator<Entry<K, V>> iterator() {
+ return new ImmutableIteratorWrapper<Entry<K, V>>(collection.iterator()) {
+ public Entry<K, V> next() {
return new ImmutableEntry<K, V>(super.next());
}
};
}
}
- private static class ImmutableMapWrapper<K, V> implements Map<K, V>, Serializable, Immutable
- {
+ private static class ImmutableMapWrapper<K, V> implements Map<K, V>, Serializable, Immutable {
private static final long serialVersionUID = 708144227046742221L;
private Map<? extends K, ? extends V> map;
- public ImmutableMapWrapper(Map<? extends K, ? extends V> map)
- {
+ public ImmutableMapWrapper(Map<? extends K, ? extends V> map) {
this.map = map;
}
- public void clear()
- {
+ public void clear() {
throw new UnsupportedOperationException();
}
- public boolean containsKey(Object key)
- {
+ public boolean containsKey(Object key) {
return map.containsKey(key);
}
- public boolean containsValue(Object value)
- {
+ public boolean containsValue(Object value) {
return map.containsValue(value);
}
- public Set<Entry<K, V>> entrySet()
- {
+ public Set<Entry<K, V>> entrySet() {
return new ImmutableEntrySetWrapper<K, V>(map.entrySet());
}
- public boolean equals(Object o)
- {
+ public boolean equals(Object o) {
return map.equals(o);
}
- public V get(Object key)
- {
+ public V get(Object key) {
return map.get(key);
}
- public int hashCode()
- {
+ public int hashCode() {
return map.hashCode();
}
- public boolean isEmpty()
- {
+ public boolean isEmpty() {
return map.isEmpty();
}
- public Set<K> keySet()
- {
+ public Set<K> keySet() {
return new ImmutableSetWrapper<K>(map.keySet());
}
- public V put(K key, V value)
- {
+ public V put(K key, V value) {
throw new UnsupportedOperationException();
}
- public void putAll(Map<? extends K, ? extends V> t)
- {
+ public void putAll(Map<? extends K, ? extends V> t) {
throw new UnsupportedOperationException();
}
- public V remove(Object key)
- {
+ public V remove(Object key) {
throw new UnsupportedOperationException();
}
- public int size()
- {
+ public int size() {
return map.size();
}
- public Collection<V> values()
- {
+ public Collection<V> values() {
return new ImmutableCollectionWrapper<V>(map.values());
}
- public String toString()
- {
+ public String toString() {
return map.toString();
}
}
Modified: core/branches/flat/src/main/java/org/horizon/util/ObjectDuplicator.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/util/ObjectDuplicator.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/util/ObjectDuplicator.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -1,17 +1,22 @@
package org.horizon.util;
-import java.util.*;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+import java.util.TreeMap;
+import java.util.TreeSet;
/**
* A helper that efficiently duplicates known object types.
- * @since 1.0
+ *
* @author (various)
+ * @since 1.0
*/
-public class ObjectDuplicator
-{
+public class ObjectDuplicator {
@SuppressWarnings("unchecked")
- public static <K, V> Map<K, V> duplicateMap(Map<K, V> original)
- {
+ public static <K, V> Map<K, V> duplicateMap(Map<K, V> original) {
if (original instanceof FastCopyHashMap)
return (Map<K, V>) ((FastCopyHashMap) original).clone();
if (original instanceof HashMap)
@@ -22,8 +27,7 @@
}
@SuppressWarnings("unchecked")
- public static <E> Set<E> duplicateSet(Set<E> original)
- {
+ public static <E> Set<E> duplicateSet(Set<E> original) {
if (original instanceof HashSet)
return (Set<E>) ((HashSet) original).clone();
if (original instanceof TreeSet)
@@ -33,8 +37,7 @@
}
@SuppressWarnings("unchecked")
- public static <E> Collection<E> duplicateCollection(Collection<E> original)
- {
+ public static <E> Collection<E> duplicateCollection(Collection<E> original) {
if (original instanceof HashSet)
return (Set<E>) ((HashSet) original).clone();
if (original instanceof TreeSet)
@@ -44,16 +47,12 @@
}
@SuppressWarnings("unchecked")
- private static <T> T attemptClone(T source)
- {
- if (source instanceof Cloneable)
- {
- try
- {
+ private static <T> T attemptClone(T source) {
+ if (source instanceof Cloneable) {
+ try {
return (T) source.getClass().getMethod("clone").invoke(source);
}
- catch (Exception e)
- {
+ catch (Exception e) {
}
}
Modified: core/branches/flat/src/main/java/org/horizon/util/ReflectionUtil.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/util/ReflectionUtil.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/util/ReflectionUtil.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -39,43 +39,38 @@
* @author Manik Surtani (<a href="mailto:manik at jboss.org">manik at jboss.org</a>)
* @since 1.0
*/
-public class ReflectionUtil
-{
+public class ReflectionUtil {
private static final Log log = LogFactory.getLog(ReflectionUtil.class);
/**
- * Returns a set of Methods that contain the given method annotation. This includes all public, protected, package and private
- * methods, as well as those of superclasses. Note that this does *not* include overridden methods.
+ * Returns a set of Methods that contain the given method annotation. This includes all public, protected, package
+ * and private methods, as well as those of superclasses. Note that this does *not* include overridden methods.
*
* @param c class to inspect
* @param annotationType the type of annotation to look for
* @return List of Method objects that require injection.
*/
- public static List<Method> getAllMethods(Class c, Class<? extends Annotation> annotationType)
- {
+ public static List<Method> getAllMethods(Class c, Class<? extends Annotation> annotationType) {
List<Method> annotated = new LinkedList<Method>();
inspectRecursively(c, annotated, annotationType);
return annotated;
}
/**
- * Inspects a class and its superclasses (all the way to {@link Object} for method instances that contain a given annotation.
- * This even identifies private, package and protected methods, not just public ones.
+ * Inspects a class and its superclasses (all the way to {@link Object} for method instances that contain a given
+ * annotation. This even identifies private, package and protected methods, not just public ones.
*
* @param c
* @param s
* @param annotationType
*/
- private static void inspectRecursively(Class c, List<Method> s, Class<? extends Annotation> annotationType)
- {
+ private static void inspectRecursively(Class c, List<Method> s, Class<? extends Annotation> annotationType) {
// Superclass first
if (!c.equals(Object.class)) inspectRecursively(c.getSuperclass(), s, annotationType);
- for (Method m : c.getDeclaredMethods())
- {
+ for (Method m : c.getDeclaredMethods()) {
// don't bother if this method has already been overridden by a subclass
- if (!alreadyFound(m, s) && m.isAnnotationPresent(annotationType))
- {
+ if (!alreadyFound(m, s) && m.isAnnotationPresent(annotationType)) {
s.add(m);
}
}
@@ -88,10 +83,8 @@
* @param s collection of methods found
* @return true a method with the same signature already exists.
*/
- private static boolean alreadyFound(Method m, Collection<Method> s)
- {
- for (Method found : s)
- {
+ private static boolean alreadyFound(Method m, Collection<Method> s) {
+ for (Method found : s) {
if (m.getName().equals(found.getName()) &&
Arrays.equals(m.getParameterTypes(), found.getParameterTypes()))
return true;
@@ -99,31 +92,25 @@
return false;
}
- public static void setValue(Object instance, String fieldName, Object value)
- {
- try
- {
+ public static void setValue(Object instance, String fieldName, Object value) {
+ try {
Field f = findFieldRecursively(instance.getClass(), fieldName);
if (f == null)
throw new NoSuchMethodException("Cannot find field " + fieldName + " on " + instance.getClass() + " or superclasses");
f.setAccessible(true);
f.set(instance, value);
}
- catch (Exception e)
- {
+ catch (Exception e) {
log.error("Unable to set value!", e);
}
}
- private static Field findFieldRecursively(Class c, String fieldName)
- {
+ private static Field findFieldRecursively(Class c, String fieldName) {
Field f = null;
- try
- {
+ try {
f = c.getDeclaredField(fieldName);
}
- catch (NoSuchFieldException e)
- {
+ catch (NoSuchFieldException e) {
if (!c.equals(Object.class)) f = findFieldRecursively(c.getSuperclass(), fieldName);
}
return f;
@@ -136,15 +123,12 @@
* @param method method to execute
* @param parameters parameters
*/
- public static void invokeAccessibly(Object instance, Method method, Object[] parameters)
- {
- try
- {
+ public static void invokeAccessibly(Object instance, Method method, Object[] parameters) {
+ try {
method.setAccessible(true);
method.invoke(instance, parameters);
}
- catch (Exception e)
- {
+ catch (Exception e) {
throw new CacheException("Unable to invoke method " + method + " on object " + //instance +
(parameters != null ? " with parameters " + Arrays.asList(parameters) : ""), e);
}
@@ -157,16 +141,13 @@
* @param fieldName name of field to retrieve
* @return a value
*/
- public static Object getValue(Object instance, String fieldName)
- {
+ public static Object getValue(Object instance, String fieldName) {
Field f = findFieldRecursively(instance.getClass(), fieldName);
- try
- {
+ try {
f.setAccessible(true);
return f.get(instance);
}
- catch (IllegalAccessException iae)
- {
+ catch (IllegalAccessException iae) {
throw new CacheException("Cannot access field " + f, iae);
}
}
@@ -182,18 +163,15 @@
* @return the annotation instance, or null
*/
@SuppressWarnings("unchecked")
- public static <T extends Annotation> T getAnnotation(Class clazz, Class<T> ann)
- {
+ public static <T extends Annotation> T getAnnotation(Class clazz, Class<T> ann) {
// first check class
T a = (T) clazz.getAnnotation(ann);
if (a != null) return a;
// check interfaces
- if (!clazz.isInterface())
- {
+ if (!clazz.isInterface()) {
Class[] interfaces = clazz.getInterfaces();
- for (Class inter : interfaces)
- {
+ for (Class inter : interfaces) {
a = getAnnotation(inter, ann);
if (a != null) return a;
}
Modified: core/branches/flat/src/main/java/org/horizon/util/SimpleImmutableEntry.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/util/SimpleImmutableEntry.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/util/SimpleImmutableEntry.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -27,47 +27,41 @@
/**
* Where is Java 1.6?
- * @since 1.0
+ *
* @author (various)
+ * @since 1.0
*/
-public class SimpleImmutableEntry<K, V> implements Map.Entry<K, V>, Serializable
-{
+public class SimpleImmutableEntry<K, V> implements Map.Entry<K, V>, Serializable {
private static final long serialVersionUID = -6092752114794052323L;
private final K key;
private final V value;
- public SimpleImmutableEntry(Entry<K, V> me)
- {
+ public SimpleImmutableEntry(Entry<K, V> me) {
key = me.getKey();
value = me.getValue();
}
- public SimpleImmutableEntry(K key, V value)
- {
+ public SimpleImmutableEntry(K key, V value) {
this.key = key;
this.value = value;
}
- public K getKey()
- {
+ public K getKey() {
return key;
}
- public V getValue()
- {
+ public V getValue() {
return value;
}
- public V setValue(V arg0)
- {
+ public V setValue(V arg0) {
throw new UnsupportedOperationException();
}
@Override
- public boolean equals(Object o)
- {
+ public boolean equals(Object o) {
if (!(o instanceof Map.Entry))
return false;
Map.Entry e2 = (Map.Entry) o;
@@ -76,15 +70,13 @@
}
@Override
- public int hashCode()
- {
+ public int hashCode() {
return (getKey() == null ? 0 : getKey().hashCode()) ^
(getValue() == null ? 0 : getValue().hashCode());
}
@Override
- public String toString()
- {
+ public String toString() {
return key + "=" + value;
}
}
\ No newline at end of file
Modified: core/branches/flat/src/main/java/org/horizon/util/TestingUtil.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/util/TestingUtil.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/util/TestingUtil.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -32,69 +32,56 @@
* Utilities for unit testing JBossCache.
*
* @author <a href="mailto://brian.stansberry@jboss.com">Brian Stansberry</a>
- *
* @since 1.0
*/
-public class TestingUtil
-{
+public class TestingUtil {
private static Random random = new Random();
/**
- * Extracts the value of a field in a given target instance using reflection, able to extract private fields as well.
+ * Extracts the value of a field in a given target instance using reflection, able to extract private fields as
+ * well.
*
* @param target object to extract field from
* @param fieldName name of field to extract
* @return field value
*/
- public static Object extractField(Object target, String fieldName)
- {
+ public static Object extractField(Object target, String fieldName) {
return extractField(target.getClass(), target, fieldName);
}
- public static void replaceField(Object newValue, String fieldName, Object owner, Class baseType)
- {
+ public static void replaceField(Object newValue, String fieldName, Object owner, Class baseType) {
Field field;
- try
- {
+ try {
field = baseType.getDeclaredField(fieldName);
field.setAccessible(true);
field.set(owner, newValue);
}
- catch (Exception e)
- {
+ catch (Exception e) {
throw new RuntimeException(e);//just to simplify exception handeling
}
}
- public static Object extractField(Class type, Object target, String fieldName)
- {
+ public static Object extractField(Class type, Object target, String fieldName) {
Field field;
- try
- {
+ try {
field = type.getDeclaredField(fieldName);
field.setAccessible(true);
return field.get(target);
}
- catch (Exception e)
- {
- if (type.equals(Object.class))
- {
+ catch (Exception e) {
+ if (type.equals(Object.class)) {
e.printStackTrace();
return null;
- }
- else
- {
+ } else {
// try with superclass!!
return extractField(type.getSuperclass(), target, fieldName);
}
}
}
- public static <T extends CommandInterceptor> T findInterceptor(CacheSPI<?, ?> cache, Class<T> interceptorToFind)
- {
- for (CommandInterceptor i : cache.getInterceptorChain())
- {
+ public static <T extends CommandInterceptor> T findInterceptor(CacheSPI<?, ?> cache, Class<T> interceptorToFind) {
+ for (CommandInterceptor i : cache.getInterceptorChain()) {
if (interceptorToFind.isInstance(i)) return interceptorToFind.cast(i);
}
return null;
@@ -107,31 +94,28 @@
*
* @param cache running cache instance
* @param interceptorToInject interceptor instance to inject.
- * @param interceptorAfterWhichToInject class of interceptor to search for in the chain and after which to add your interceptor
+ * @param interceptorAfterWhichToInject class of interceptor to search for in the chain and after which to add your
+ * interceptor
*/
- public static void injectInterceptor(CacheSPI<?, ?> cache, CommandInterceptor interceptorToInject, Class<? extends CommandInterceptor> interceptorAfterWhichToInject)
- {
+ public static void injectInterceptor(CacheSPI<?, ?> cache, CommandInterceptor interceptorToInject, Class<? extends CommandInterceptor> interceptorAfterWhichToInject) {
cache.addInterceptor(interceptorToInject, interceptorAfterWhichToInject);
}
/**
- * Loops, continually calling {@link #areCacheViewsComplete(Cache[])}
- * until it either returns true or <code>timeout</code> ms have elapsed.
+ * Loops, continually calling {@link #areCacheViewsComplete(Cache[])} until it either returns true or
+ * <code>timeout</code> ms have elapsed.
*
* @param caches caches which must all have consistent views
* @param timeout max number of ms to loop
- * @throws RuntimeException if <code>timeout</code> ms have elapse without
- * all caches having the same number of members.
+ * @throws RuntimeException if <code>timeout</code> ms have elapse without all caches having the same number of
+ * members.
*/
- public static void blockUntilViewsReceived(Cache[] caches, long timeout)
- {
+ public static void blockUntilViewsReceived(Cache[] caches, long timeout) {
long failTime = System.currentTimeMillis() + timeout;
- while (System.currentTimeMillis() < failTime)
- {
+ while (System.currentTimeMillis() < failTime) {
sleepThread(100);
- if (areCacheViewsComplete(caches))
- {
+ if (areCacheViewsComplete(caches)) {
return;
}
}
@@ -142,29 +126,25 @@
/**
* Version of blockUntilViewsReceived that uses varargs
*/
- public static void blockUntilViewsReceived(long timeout, Cache... caches)
- {
+ public static void blockUntilViewsReceived(long timeout, Cache... caches) {
blockUntilViewsReceived(caches, timeout);
}
/**
- * Loops, continually calling {@link #areCacheViewsComplete(CacheSPI[])}
- * until it either returns true or <code>timeout</code> ms have elapsed.
+ * Loops, continually calling {@link #areCacheViewsComplete(CacheSPI[])} until it either returns true or
+ * <code>timeout</code> ms have elapsed.
*
* @param caches caches which must all have consistent views
* @param timeout max number of ms to loop
- * @throws RuntimeException if <code>timeout</code> ms have elapse without
- * all caches having the same number of members.
+ * @throws RuntimeException if <code>timeout</code> ms have elapse without all caches having the same number of
+ * members.
*/
- public static void blockUntilViewsReceived(CacheSPI[] caches, long timeout)
- {
+ public static void blockUntilViewsReceived(CacheSPI[] caches, long timeout) {
long failTime = System.currentTimeMillis() + timeout;
- while (System.currentTimeMillis() < failTime)
- {
+ while (System.currentTimeMillis() < failTime) {
sleepThread(100);
- if (areCacheViewsComplete(caches))
- {
+ if (areCacheViewsComplete(caches)) {
return;
}
}
@@ -175,23 +155,20 @@
/**
* An overloaded version of {@link #blockUntilViewsReceived(long,Cache[])} that allows for 'shrinking' clusters.
- * I.e., the usual method barfs if there are more members than expected. This one takes a param (barfIfTooManyMembers) which,
- * if false, will NOT barf but will wait until the cluster 'shrinks' to the desired size. Useful if in tests, you kill
- * a member and want to wait until this fact is known across the cluster.
+ * I.e., the usual method barfs if there are more members than expected. This one takes a param
+ * (barfIfTooManyMembers) which, if false, will NOT barf but will wait until the cluster 'shrinks' to the desired
+ * size. Useful if in tests, you kill a member and want to wait until this fact is known across the cluster.
*
* @param timeout
* @param barfIfTooManyMembers
* @param caches
*/
- public static void blockUntilViewsReceived(long timeout, boolean barfIfTooManyMembers, Cache... caches)
- {
+ public static void blockUntilViewsReceived(long timeout, boolean barfIfTooManyMembers, Cache... caches) {
long failTime = System.currentTimeMillis() + timeout;
- while (System.currentTimeMillis() < failTime)
- {
+ while (System.currentTimeMillis() < failTime) {
sleepThread(100);
- if (areCacheViewsComplete(caches, barfIfTooManyMembers))
- {
+ if (areCacheViewsComplete(caches, barfIfTooManyMembers)) {
return;
}
}
@@ -200,28 +177,24 @@
}
/**
- * Loops, continually calling {@link #areCacheViewsComplete(CacheSPI[])}
- * until it either returns true or <code>timeout</code> ms have elapsed.
+ * Loops, continually calling {@link #areCacheViewsComplete(CacheSPI[])} until it either returns true or
+ * <code>timeout</code> ms have elapsed.
*
* @param groupSize number of caches expected in the group
* @param timeout max number of ms to loop
- * @throws RuntimeException if <code>timeout</code> ms have elapse without
- * all caches having the same number of members.
+ * @throws RuntimeException if <code>timeout</code> ms have elapse without all caches having the same number of
+ * members.
*/
- public static void blockUntilViewReceived(CacheSPI cache, int groupSize, long timeout)
- {
+ public static void blockUntilViewReceived(CacheSPI cache, int groupSize, long timeout) {
blockUntilViewReceived(cache, groupSize, timeout, true);
}
- public static void blockUntilViewReceived(CacheSPI cache, int groupSize, long timeout, boolean barfIfTooManyMembersInView)
- {
+ public static void blockUntilViewReceived(CacheSPI cache, int groupSize, long timeout, boolean barfIfTooManyMembersInView) {
long failTime = System.currentTimeMillis() + timeout;
- while (System.currentTimeMillis() < failTime)
- {
+ while (System.currentTimeMillis() < failTime) {
sleepThread(100);
- if (isCacheViewComplete(cache, groupSize, barfIfTooManyMembersInView))
- {
+ if (isCacheViewComplete(cache, groupSize, barfIfTooManyMembersInView)) {
return;
}
}
@@ -230,29 +203,22 @@
}
/**
- * Checks each cache to see if the number of elements in the array
- * returned by {@link CacheSPI#getMembers()} matches the size of
- * the <code>caches</code> parameter.
+ * Checks each cache to see if the number of elements in the array returned by {@link CacheSPI#getMembers()} matches
+ * the size of the <code>caches</code> parameter.
*
* @param caches caches that should form a View
- * @return <code>true</code> if all caches have
- * <code>caches.length</code> members; false otherwise
- * @throws IllegalStateException if any of the caches have MORE view
- * members than caches.length
+ * @return <code>true</code> if all caches have <code>caches.length</code> members; false otherwise
+ * @throws IllegalStateException if any of the caches have MORE view members than caches.length
*/
- public static boolean areCacheViewsComplete(Cache[] caches)
- {
+ public static boolean areCacheViewsComplete(Cache[] caches) {
return areCacheViewsComplete(caches, true);
}
- public static boolean areCacheViewsComplete(Cache[] caches, boolean barfIfTooManyMembers)
- {
+ public static boolean areCacheViewsComplete(Cache[] caches, boolean barfIfTooManyMembers) {
int memberCount = caches.length;
- for (int i = 0; i < memberCount; i++)
- {
- if (!isCacheViewComplete(caches[i], memberCount, barfIfTooManyMembers))
- {
+ for (int i = 0; i < memberCount; i++) {
+ if (!isCacheViewComplete(caches[i], memberCount, barfIfTooManyMembers)) {
return false;
}
}
@@ -261,18 +227,14 @@
}
/**
- * Checks each cache to see if the number of elements in the array
- * returned by {@link RPCManager#getMembers()} matches the size of
- * the <code>caches</code> parameter.
+ * Checks each cache to see if the number of elements in the array returned by {@link RPCManager#getMembers()}
+ * matches the size of the <code>caches</code> parameter.
*
* @param caches caches that should form a View
- * @return <code>true</code> if all caches have
- * <code>caches.length</code> members; false otherwise
- * @throws IllegalStateException if any of the caches have MORE view
- * members than caches.length
+ * @return <code>true</code> if all caches have <code>caches.length</code> members; false otherwise
+ * @throws IllegalStateException if any of the caches have MORE view members than caches.length
*/
- public static boolean areCacheViewsComplete(CacheSPI[] caches)
- {
+ public static boolean areCacheViewsComplete(CacheSPI[] caches) {
if (caches == null) throw new NullPointerException("Cache impl array is null");
Cache[] c = new Cache[caches.length];
for (int i = 0; i < caches.length; i++) c[i] = caches[i];
@@ -283,15 +245,11 @@
* @param cache
* @param memberCount
*/
- public static boolean isCacheViewComplete(CacheSPI cache, int memberCount)
- {
+ public static boolean isCacheViewComplete(CacheSPI cache, int memberCount) {
List members = cache.getRPCManager().getMembers();
- if (members == null || memberCount > members.size())
- {
+ if (members == null || memberCount > members.size()) {
return false;
- }
- else if (memberCount < members.size())
- {
+ } else if (memberCount < members.size()) {
// This is an exceptional condition
StringBuilder sb = new StringBuilder("Cache at address ");
sb.append(cache.getRPCManager().getLocalAddress());
@@ -300,10 +258,8 @@
sb.append(" members; expecting ");
sb.append(memberCount);
sb.append(". Members were (");
- for (int j = 0; j < members.size(); j++)
- {
- if (j > 0)
- {
+ for (int j = 0; j < members.size(); j++) {
+ if (j > 0) {
sb.append(", ");
}
sb.append(members.get(j));
@@ -320,23 +276,17 @@
* @param c
* @param memberCount
*/
- public static boolean isCacheViewComplete(Cache c, int memberCount)
- {
+ public static boolean isCacheViewComplete(Cache c, int memberCount) {
return isCacheViewComplete(c, memberCount, true);
}
- public static boolean isCacheViewComplete(Cache c, int memberCount, boolean barfIfTooManyMembers)
- {
+ public static boolean isCacheViewComplete(Cache c, int memberCount, boolean barfIfTooManyMembers) {
CacheSPI cache = (CacheSPI) c;
List members = cache.getMembers();
- if (members == null || memberCount > members.size())
- {
+ if (members == null || memberCount > members.size()) {
return false;
- }
- else if (memberCount < members.size())
- {
- if (barfIfTooManyMembers)
- {
+ } else if (memberCount < members.size()) {
+ if (barfIfTooManyMembers) {
// This is an exceptional condition
StringBuilder sb = new StringBuilder("Cache at address ");
sb.append(cache.getRPCManager().getLocalAddress());
@@ -345,10 +295,8 @@
sb.append(" members; expecting ");
sb.append(memberCount);
sb.append(". Members were (");
- for (int j = 0; j < members.size(); j++)
- {
- if (j > 0)
- {
+ for (int j = 0; j < members.size(); j++) {
+ if (j > 0) {
sb.append(", ");
}
sb.append(members.get(j));
@@ -356,8 +304,7 @@
sb.append(')');
throw new IllegalStateException(sb.toString());
- }
- else return false;
+ } else return false;
}
return true;
@@ -365,49 +312,38 @@
/**
- * Puts the current thread to sleep for the desired number of ms, suppressing
- * any exceptions.
+ * Puts the current thread to sleep for the desired number of ms, suppressing any exceptions.
*
* @param sleeptime number of ms to sleep
*/
- public static void sleepThread(long sleeptime)
- {
- try
- {
+ public static void sleepThread(long sleeptime) {
+ try {
Thread.sleep(sleeptime);
}
- catch (InterruptedException ie)
- {
+ catch (InterruptedException ie) {
}
}
- public static void sleepRandom(int maxTime)
- {
+ public static void sleepRandom(int maxTime) {
sleepThread(random.nextInt(maxTime));
}
- public static void recursiveFileRemove(String directoryName)
- {
+ public static void recursiveFileRemove(String directoryName) {
File file = new File(directoryName);
recursiveFileRemove(file);
}
- public static void recursiveFileRemove(File file)
- {
- if (file.exists())
- {
+ public static void recursiveFileRemove(File file) {
+ if (file.exists()) {
System.out.println("Deleting file " + file);
recursivedelete(file);
}
}
- private static void recursivedelete(File f)
- {
- if (f.isDirectory())
- {
+ private static void recursivedelete(File f) {
+ if (f.isDirectory()) {
File[] files = f.listFiles();
- for (File file : files)
- {
+ for (File file : files) {
recursivedelete(file);
}
}
@@ -415,20 +351,16 @@
f.delete();
}
- public static void killTreeCaches(Collection treeCaches)
- {
+ public static void killTreeCaches(Collection treeCaches) {
if (treeCaches != null) killTreeCaches((TreeCache[]) treeCaches.toArray(new TreeCache[]{}));
}
- public static void killCaches(Collection caches)
- {
+ public static void killCaches(Collection caches) {
if (caches != null) killCaches((Cache[]) caches.toArray(new Cache[]{}));
}
- public static void killTreeCaches(TreeCache... treeCaches)
- {
- for (TreeCache tc : treeCaches)
- {
+ public static void killTreeCaches(TreeCache... treeCaches) {
+ for (TreeCache tc : treeCaches) {
if (tc != null) killCaches(tc.getCache());
}
}
@@ -436,23 +368,16 @@
/**
* Kills a cache - stops it, clears any data in any cache loaders, and rolls back any associated txs
*/
- public static void killCaches(Cache... caches)
- {
- for (Cache c : caches)
- {
- try
- {
- if (c != null && c.getCacheStatus() == CacheStatus.STARTED)
- {
+ public static void killCaches(Cache... caches) {
+ for (Cache c : caches) {
+ try {
+ if (c != null && c.getCacheStatus() == CacheStatus.STARTED) {
CacheSPI spi = (CacheSPI) c;
- if (spi.getTransactionManager() != null)
- {
- try
- {
+ if (spi.getTransactionManager() != null) {
+ try {
spi.getTransactionManager().rollback();
}
- catch (Exception e)
- {
+ catch (Exception e) {
// don't care
}
}
@@ -477,8 +402,7 @@
spi.stop();
}
}
- catch (Throwable t)
- {
+ catch (Throwable t) {
}
}
@@ -489,16 +413,12 @@
*
* @param txManager a TransactionManager to be cleared
*/
- public static void killTransaction(TransactionManager txManager)
- {
- if (txManager != null)
- {
- try
- {
+ public static void killTransaction(TransactionManager txManager) {
+ if (txManager != null) {
+ try {
txManager.rollback();
}
- catch (Exception e)
- {
+ catch (Exception e) {
// don't care
}
}
@@ -508,21 +428,15 @@
/**
* Clears any associated transactions with the current thread in the caches' transaction managers.
*/
- public static void killTransactions(Cache... caches)
- {
- for (Cache c : caches)
- {
- if (c != null && c.getCacheStatus() == CacheStatus.STARTED)
- {
+ public static void killTransactions(Cache... caches) {
+ for (Cache c : caches) {
+ if (c != null && c.getCacheStatus() == CacheStatus.STARTED) {
CacheSPI ci = (CacheSPI) c;
- if (ci.getTransactionManager() != null)
- {
- try
- {
+ if (ci.getTransactionManager() != null) {
+ try {
ci.getTransactionManager().rollback();
}
- catch (Exception e)
- {
+ catch (Exception e) {
// don't care
}
}
@@ -536,13 +450,11 @@
* @param cache cache to introspect
* @return component registry
*/
- public static ComponentRegistry extractComponentRegistry(Cache cache)
- {
+ public static ComponentRegistry extractComponentRegistry(Cache cache) {
return (ComponentRegistry) extractField(cache, "componentRegistry");
}
- public static LockManager extractLockManager(Cache cache)
- {
+ public static LockManager extractLockManager(Cache cache) {
return extractComponentRegistry(cache).getComponent(LockManager.class);
}
@@ -552,8 +464,7 @@
* @param ci interceptor chain to introspect
* @return component registry
*/
- public static ComponentRegistry extractComponentRegistry(InterceptorChain ci)
- {
+ public static ComponentRegistry extractComponentRegistry(InterceptorChain ci) {
return (ComponentRegistry) extractField(ci, "componentRegistry");
}
@@ -565,13 +476,11 @@
* @param cache cache that needs to be altered
* @param interceptor the first interceptor in the new chain.
*/
- public static void replaceInterceptorChain(CacheSPI<?, ?> cache, CommandInterceptor interceptor)
- {
+ public static void replaceInterceptorChain(CacheSPI<?, ?> cache, CommandInterceptor interceptor) {
ComponentRegistry cr = extractComponentRegistry(cache);
// make sure all interceptors here are wired.
CommandInterceptor i = interceptor;
- do
- {
+ do {
cr.wireDependencies(i);
}
while ((i = i.getNext()) != null);
@@ -587,8 +496,7 @@
* @param cache cache instance for which a remote delegate is to be retrieved
* @return remote delegate, or null if the cacge is not configured for replication.
*/
- public static CacheDelegate getInvocationDelegate(CacheSPI cache)
- {
+ public static CacheDelegate getInvocationDelegate(CacheSPI cache) {
ComponentRegistry cr = extractComponentRegistry(cache);
return cr.getComponent(CacheDelegate.class);
}
@@ -600,43 +508,36 @@
* @param cacheStatus status to wait for
* @param timeout timeout to wait for
*/
- public static void blockUntilCacheStatusAchieved(Cache cache, CacheStatus cacheStatus, long timeout)
- {
+ public static void blockUntilCacheStatusAchieved(Cache cache, CacheStatus cacheStatus, long timeout) {
CacheSPI spi = (CacheSPI) cache;
long killTime = System.currentTimeMillis() + timeout;
- while (System.currentTimeMillis() < killTime)
- {
+ while (System.currentTimeMillis() < killTime) {
if (spi.getCacheStatus() == cacheStatus) return;
sleepThread(50);
}
throw new RuntimeException("Timed out waiting for condition");
}
- public static void replicateCommand(CacheSPI cache, VisitableCommand command) throws Throwable
- {
+ public static void replicateCommand(CacheSPI cache, VisitableCommand command) throws Throwable {
ComponentRegistry cr = extractComponentRegistry(cache);
InterceptorChain ic = cr.getComponent(InterceptorChain.class);
ic.invoke(command);
}
- public static void blockUntilViewsReceived(int timeout, List caches)
- {
+ public static void blockUntilViewsReceived(int timeout, List caches) {
blockUntilViewsReceived((Cache[]) caches.toArray(new Cache[]{}), timeout);
}
- public static CommandsFactory extractCommandsFactory(CacheSPI<Object, Object> cache)
- {
+ public static CommandsFactory extractCommandsFactory(CacheSPI<Object, Object> cache) {
return (CommandsFactory) extractField(cache, "commandsFactory");
}
- public static String getJGroupsAttribute(Cache cache, String protocol, String attribute)
- {
+ public static String getJGroupsAttribute(Cache cache, String protocol, String attribute) {
String s = ((JChannel) ((CacheSPI) cache).getRPCManager().getChannel()).getProperties();
String[] protocols = s.split(":");
String attribs = null;
- for (String p : protocols)
- {
+ for (String p : protocols) {
boolean hasAttribs = p.contains("(");
String name = hasAttribs ? p.substring(0, p.indexOf('(')) : p;
attribs = hasAttribs ? p.substring(p.indexOf('(') + 1, p.length() - 1) : null;
@@ -644,11 +545,9 @@
if (name.equalsIgnoreCase(protocol)) break;
}
- if (attribs != null)
- {
+ if (attribs != null) {
String[] attrArray = attribs.split(";");
- for (String a : attrArray)
- {
+ for (String a : attrArray) {
String[] kvPairs = a.split("=");
if (kvPairs[0].equalsIgnoreCase(attribute)) return kvPairs[1];
}
@@ -656,19 +555,14 @@
return null;
}
- public static void dumpCacheContents(List caches)
- {
+ public static void dumpCacheContents(List caches) {
System.out.println("**** START: Cache Contents ****");
int count = 1;
- for (Object o : caches)
- {
+ for (Object o : caches) {
CacheSPI c = (CacheSPI) o;
- if (c == null)
- {
+ if (c == null) {
System.out.println(" ** Cache " + count + " is null!");
- }
- else
- {
+ } else {
System.out.println(" ** Cache " + count + " is " + c.getRPCManager().getLocalAddress());
// System.out.println(" " + CachePrinter.printCacheDetails(c));
}
@@ -677,8 +571,7 @@
System.out.println("**** END: Cache Contents ****");
}
- public static void dumpCacheContents(Cache... caches)
- {
+ public static void dumpCacheContents(Cache... caches) {
dumpCacheContents(Arrays.asList(caches));
}
@@ -690,8 +583,7 @@
* @param <T>
* @return
*/
- public static <T> T extractComponent(Cache cache, Class<T> componentType)
- {
+ public static <T> T extractComponent(Cache cache, Class<T> componentType) {
ComponentRegistry cr = extractComponentRegistry(cache);
return cr.getComponent(componentType);
}
Modified: core/branches/flat/src/main/java/org/horizon/util/TypedProperties.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/util/TypedProperties.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/util/TypedProperties.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -12,64 +12,53 @@
* @author Manik Surtani
* @since 1.0
*/
-public class TypedProperties extends Properties
-{
+public class TypedProperties extends Properties {
private static final Log log = LogFactory.getLog(TypedProperties.class);
- public TypedProperties(Properties p)
- {
+ public TypedProperties(Properties p) {
if (p != null) putAll(p);
}
- public int getIntProperty(String key, int defaultValue)
- {
+ public int getIntProperty(String key, int defaultValue) {
String value = getProperty(key);
if (value == null) return defaultValue;
value = value.trim();
if (value.length() == 0) return defaultValue;
- try
- {
+ try {
return Integer.parseInt(value);
}
- catch (NumberFormatException nfe)
- {
+ catch (NumberFormatException nfe) {
log.warn("Unable to convert string property [" + value + "] to an int! Using default value of " + defaultValue);
return defaultValue;
}
}
- public long getLongProperty(String key, long defaultValue)
- {
+ public long getLongProperty(String key, long defaultValue) {
String value = getProperty(key);
if (value == null) return defaultValue;
value = value.trim();
if (value.length() == 0) return defaultValue;
- try
- {
+ try {
return Long.parseLong(value);
}
- catch (NumberFormatException nfe)
- {
+ catch (NumberFormatException nfe) {
log.warn("Unable to convert string property [" + value + "] to a long! Using default value of " + defaultValue);
return defaultValue;
}
}
- public boolean getBooleanProperty(String key, boolean defaultValue)
- {
+ public boolean getBooleanProperty(String key, boolean defaultValue) {
String value = getProperty(key);
if (value == null) return defaultValue;
value = value.trim();
if (value.length() == 0) return defaultValue;
- try
- {
+ try {
return Boolean.parseBoolean(value);
}
- catch (Exception e)
- {
+ catch (Exception e) {
log.warn("Unable to convert string property [" + value + "] to a boolean! Using default value of " + defaultValue);
return defaultValue;
}
Modified: core/branches/flat/src/main/java/org/horizon/util/UnitTestTestNGListener.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/util/UnitTestTestNGListener.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/util/UnitTestTestNGListener.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -11,24 +11,23 @@
import org.testng.ITestResult;
/**
- *
* @author dpospisi
* @since 1.0
*/
public class UnitTestTestNGListener implements ITestListener {
-
+
/**
* Holds test classes actually running in all threads.
*/
private ThreadLocal<IClass> threadTestClass = new ThreadLocal<IClass>();
-
+
private int failed = 0;
private int succeded = 0;
private int skipped = 0;
-
+
public void onTestStart(ITestResult res) {
- System.out.println(getThreadId() + " Starting test " + getTestDesc(res));
-
+ System.out.println(getThreadId() + " Starting test " + getTestDesc(res));
+
/*
IClass testClass = threadTestClass.get();
if ((testClass != null) && (! res.getTestClass().equals(testClass))) {
@@ -47,8 +46,8 @@
System.out.println(getThreadId() +" WARNING !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
}
}
- */
-
+ */
+
threadTestClass.set(res.getTestClass());
}
@@ -61,7 +60,7 @@
synchronized public void onTestFailure(ITestResult arg0) {
System.out.println(getThreadId() + " Test " + getTestDesc(arg0) + " failed.");
failed++;
- printStatus();
+ printStatus();
}
synchronized public void onTestSkipped(ITestResult arg0) {
@@ -73,20 +72,20 @@
public void onTestFailedButWithinSuccessPercentage(ITestResult arg0) {
}
- public void onStart(ITestContext arg0) {
+ public void onStart(ITestContext arg0) {
}
public void onFinish(ITestContext arg0) {
}
-
+
private String getThreadId() {
- return "["+ Thread.currentThread().getName() + "]";
+ return "[" + Thread.currentThread().getName() + "]";
}
-
+
private String getTestDesc(ITestResult res) {
return res.getMethod().getMethodName() + "(" + res.getTestClass().getName() + ")";
}
-
+
private void printStatus() {
System.out.println("Testsuite execution progress: tests succeded " + succeded + ", failed " + failed + ", skipped " + skipped + ".");
}
Modified: core/branches/flat/src/main/java/org/horizon/util/Util.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/util/Util.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/util/Util.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -29,25 +29,19 @@
* General utility methods used throughout the JBC code base.
*
* @author <a href="brian.stansberry at jboss.com">Brian Stansberry</a>
- *
* @since 1.0
*/
-public final class Util
-{
+public final class Util {
/**
- * Loads the specified class using this class's classloader, or, if it is <code>null</code>
- * (i.e. this class was loaded by the bootstrap classloader), the system classloader.
- * <p/>
- * If loadtime instrumentation via GenerateInstrumentedClassLoader is used, this
- * class may be loaded by the bootstrap classloader.
- * </p>
+ * Loads the specified class using this class's classloader, or, if it is <code>null</code> (i.e. this class was
+ * loaded by the bootstrap classloader), the system classloader. <p/> If loadtime instrumentation via
+ * GenerateInstrumentedClassLoader is used, this class may be loaded by the bootstrap classloader. </p>
*
* @param classname name of the class to load
* @return the class
* @throws ClassNotFoundException
*/
- public static Class loadClass(String classname) throws ClassNotFoundException
- {
+ public static Class loadClass(String classname) throws ClassNotFoundException {
ClassLoader cl = Thread.currentThread().getContextClassLoader();
if (cl == null)
cl = ClassLoader.getSystemClassLoader();
@@ -55,17 +49,14 @@
}
@SuppressWarnings("unchecked")
- public static <T> T getInstance(Class<T> clazz) throws Exception
- {
+ public static <T> T getInstance(Class<T> clazz) throws Exception {
// first look for a getInstance() constructor
T instance;
- try
- {
+ try {
Method factoryMethod = clazz.getMethod("getInstance", new Class[]{});
instance = (T) factoryMethod.invoke(null);
}
- catch (Exception e)
- {
+ catch (Exception e) {
// no factory method or factory method failed. Try a constructor.
instance = clazz.newInstance();
}
@@ -73,8 +64,7 @@
}
@SuppressWarnings("unchecked")
- public static Object getInstance(String classname) throws Exception
- {
+ public static Object getInstance(String classname) throws Exception {
if (classname == null) throw new IllegalArgumentException("Cannot load null class!");
Class clazz = loadClass(classname);
return getInstance(clazz);
@@ -83,8 +73,7 @@
/**
* Prevent instantiation
*/
- private Util()
- {
+ private Util() {
}
/**
@@ -94,24 +83,21 @@
* @param b second object to compare
* @return true if the objects are equals or both null, false otherwise.
*/
- public static boolean safeEquals(Object a, Object b)
- {
+ public static boolean safeEquals(Object a, Object b) {
return (a == b) || (a != null && a.equals(b));
}
/**
* Static inner class that holds 3 maps - for data added, removed and modified.
*/
- public static class MapModifications
- {
+ public static class MapModifications {
public final Map<Object, Object> addedEntries = new HashMap<Object, Object>();
public final Map<Object, Object> removedEntries = new HashMap<Object, Object>();
public final Map<Object, Object> modifiedEntries = new HashMap<Object, Object>();
@Override
- public boolean equals(Object o)
- {
+ public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
@@ -127,8 +113,7 @@
}
@Override
- public int hashCode()
- {
+ public int hashCode() {
int result;
result = (addedEntries != null ? addedEntries.hashCode() : 0);
result = 31 * result + (removedEntries != null ? removedEntries.hashCode() : 0);
@@ -137,8 +122,7 @@
}
@Override
- public String toString()
- {
+ public String toString() {
return "Added Entries " + addedEntries + " Removeed Entries " + removedEntries + " Modified Entries " + modifiedEntries;
}
}
Modified: core/branches/flat/src/main/java/org/horizon/util/concurrent/BoundedExecutors.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/util/concurrent/BoundedExecutors.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/util/concurrent/BoundedExecutors.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -21,7 +21,11 @@
*/
package org.horizon.util.concurrent;
-import java.util.concurrent.*;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.LinkedBlockingQueue;
+import java.util.concurrent.ThreadFactory;
+import java.util.concurrent.ThreadPoolExecutor;
+import java.util.concurrent.TimeUnit;
/**
* Similar to JDK {@link java.util.concurrent.Executors} except that the factory methods here allow you to specify the
@@ -30,29 +34,24 @@
* @author Manik Surtani (<a href="mailto:manik AT jboss DOT org">manik AT jboss DOT org</a>)
* @since 1.0
*/
-public class BoundedExecutors
-{
+public class BoundedExecutors {
/**
- * Creates a thread pool that reuses a fixed set of threads
- * operating off a shared bounded queue. If any thread
- * terminates due to a failure during execution prior to shutdown,
- * a new one will take its place if needed to execute subsequent
- * tasks.
+ * Creates a thread pool that reuses a fixed set of threads operating off a shared bounded queue. If any thread
+ * terminates due to a failure during execution prior to shutdown, a new one will take its place if needed to execute
+ * subsequent tasks.
*
* @param nThreads the number of threads in the pool
* @param boundedQueueSize size of the bounded queue
* @return the newly created thread pool
*/
- public static ExecutorService newFixedThreadPool(int nThreads, int boundedQueueSize)
- {
+ public static ExecutorService newFixedThreadPool(int nThreads, int boundedQueueSize) {
return new ThreadPoolExecutor(nThreads, nThreads,
- 0L, TimeUnit.MILLISECONDS,
- new LinkedBlockingQueue<Runnable>(boundedQueueSize));
+ 0L, TimeUnit.MILLISECONDS,
+ new LinkedBlockingQueue<Runnable>(boundedQueueSize));
}
/**
- * Creates a thread pool that reuses a fixed set of threads
- * operating off a shared bounded queue, using the provided
+ * Creates a thread pool that reuses a fixed set of threads operating off a shared bounded queue, using the provided
* ThreadFactory to create new threads when needed.
*
* @param nThreads the number of threads in the pool
@@ -60,11 +59,10 @@
* @param boundedQueueSize size of the bounded queue
* @return the newly created thread pool
*/
- public static ExecutorService newFixedThreadPool(int nThreads, ThreadFactory threadFactory, int boundedQueueSize)
- {
+ public static ExecutorService newFixedThreadPool(int nThreads, ThreadFactory threadFactory, int boundedQueueSize) {
return new ThreadPoolExecutor(nThreads, nThreads,
- 0L, TimeUnit.MILLISECONDS,
- new LinkedBlockingQueue<Runnable>(boundedQueueSize),
- threadFactory);
+ 0L, TimeUnit.MILLISECONDS,
+ new LinkedBlockingQueue<Runnable>(boundedQueueSize),
+ threadFactory);
}
}
Modified: core/branches/flat/src/main/java/org/horizon/util/concurrent/ConcurrentHashSet.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/util/concurrent/ConcurrentHashSet.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/util/concurrent/ConcurrentHashSet.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -35,110 +35,95 @@
* @author <a href="mailto:manik at jboss.org">Manik Surtani</a>
* @since 1.0
*/
-public class ConcurrentHashSet<E> extends AbstractSet<E>
-{
+public class ConcurrentHashSet<E> extends AbstractSet<E> {
protected ConcurrentHashMap<E, Object> map;
private static final Object DUMMY = new Object();
- public ConcurrentHashSet()
- {
+ public ConcurrentHashSet() {
map = new ConcurrentHashMap<E, Object>();
}
/**
- * @param concurrencyLevel passed in to the underlying CHM. See {@link java.util.concurrent.ConcurrentHashMap#ConcurrentHashMap(int, float, int)} javadocs for details.
+ * @param concurrencyLevel passed in to the underlying CHM. See {@link java.util.concurrent.ConcurrentHashMap#ConcurrentHashMap(int,
+ * float, int)} javadocs for details.
*/
- public ConcurrentHashSet(int concurrencyLevel)
- {
+ public ConcurrentHashSet(int concurrencyLevel) {
map = new ConcurrentHashMap<E, Object>(16, 0.75f, concurrencyLevel);
}
/**
- * Params passed in to the underlying CHM. See {@link java.util.concurrent.ConcurrentHashMap#ConcurrentHashMap(int, float, int)} javadocs for details.
+ * Params passed in to the underlying CHM. See {@link java.util.concurrent.ConcurrentHashMap#ConcurrentHashMap(int,
+ * float, int)} javadocs for details.
*/
- public ConcurrentHashSet(int initSize, float loadFactor, int concurrencyLevel)
- {
+ public ConcurrentHashSet(int initSize, float loadFactor, int concurrencyLevel) {
map = new ConcurrentHashMap<E, Object>(initSize, loadFactor, concurrencyLevel);
}
@Override
- public int size()
- {
+ public int size() {
return map.size();
}
@Override
- public boolean isEmpty()
- {
+ public boolean isEmpty() {
return map.isEmpty();
}
@Override
- public boolean contains(Object o)
- {
+ public boolean contains(Object o) {
return map.containsKey(o);
}
@Override
- public Iterator<E> iterator()
- {
+ public Iterator<E> iterator() {
return map.keySet().iterator();
}
@Override
- public Object[] toArray()
- {
+ public Object[] toArray() {
return map.keySet().toArray();
}
@Override
- public <T> T[] toArray(T[] a)
- {
+ public <T> T[] toArray(T[] a) {
return map.keySet().toArray(a);
}
@Override
- public boolean add(E o)
- {
+ public boolean add(E o) {
Object v = map.put(o, DUMMY);
return v == null;
}
@Override
- public boolean remove(Object o)
- {
+ public boolean remove(Object o) {
Object v = map.remove(o);
return v != null;
}
@Override
- public boolean containsAll(Collection<?> c)
- {
+ public boolean containsAll(Collection<?> c) {
return map.keySet().containsAll(c);
}
@Override
- public boolean addAll(Collection<? extends E> c)
- {
+ public boolean addAll(Collection<? extends E> c) {
throw new UnsupportedOperationException("Not supported in this implementation since additional locking is required and cannot directly be delegated to multiple calls to ConcurrentHashMap");
}
@Override
- public boolean retainAll(Collection<?> c)
- {
+ public boolean retainAll(Collection<?> c) {
throw new UnsupportedOperationException("Not supported in this implementation since additional locking is required and cannot directly be delegated to multiple calls to ConcurrentHashMap");
}
@Override
- public boolean removeAll(Collection<?> c)
- {
+ public boolean removeAll(Collection<?> c) {
throw new UnsupportedOperationException("Not supported in this implementation since additional locking is required and cannot directly be delegated to multiple calls to ConcurrentHashMap");
}
@Override
- public void clear()
- {
+ public void clear() {
map.clear();
}
}
Modified: core/branches/flat/src/main/java/org/horizon/util/concurrent/ReclosableLatch.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/util/concurrent/ReclosableLatch.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/util/concurrent/ReclosableLatch.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -33,55 +33,46 @@
* @author Manik Surtani (<a href="mailto:manik at jboss.org">manik at jboss.org</a>)
* @since 1.0
*/
-public class ReclosableLatch extends AbstractQueuedSynchronizer
-{
+public class ReclosableLatch extends AbstractQueuedSynchronizer {
// the following states are used in the AQS.
private static final int OPEN_STATE = 0, CLOSED_STATE = 1;
- public ReclosableLatch()
- {
+ public ReclosableLatch() {
setState(CLOSED_STATE);
}
- public ReclosableLatch(boolean defaultOpen)
- {
+ public ReclosableLatch(boolean defaultOpen) {
setState(defaultOpen ? OPEN_STATE : CLOSED_STATE);
}
@Override
- public final int tryAcquireShared(int ignored)
- {
+ public final int tryAcquireShared(int ignored) {
// return 1 if we allow the requestor to proceed, -1 if we want the requestor to block.
return getState() == OPEN_STATE ? 1 : -1;
}
@Override
- public final boolean tryReleaseShared(int state)
- {
+ public final boolean tryReleaseShared(int state) {
// used as a mechanism to set the state of the Sync.
setState(state);
return true;
}
- public final void open()
- {
+ public final void open() {
// do not use setState() directly since this won't notify parked threads.
releaseShared(OPEN_STATE);
}
- public final void close()
- {
+ public final void close() {
// do not use setState() directly since this won't notify parked threads.
releaseShared(CLOSED_STATE);
}
- public final void await() throws InterruptedException
- {
+ public final void await() throws InterruptedException {
acquireSharedInterruptibly(1); // the 1 is a dummy value that is not used.
}
- public final boolean await(long time, TimeUnit unit) throws InterruptedException
- {
+ public final boolean await(long time, TimeUnit unit) throws InterruptedException {
return tryAcquireSharedNanos(1, unit.toNanos(time)); // the 1 is a dummy value that is not used.
}
}
Modified: core/branches/flat/src/main/java/org/horizon/util/concurrent/SelfInitializingConcurrentHashMap.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/util/concurrent/SelfInitializingConcurrentHashMap.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/util/concurrent/SelfInitializingConcurrentHashMap.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -29,127 +29,106 @@
import java.util.concurrent.ConcurrentMap;
/**
- * Primarily used to hold child maps for nodes. Underlying CHM is null initially, and once threads start
- * writing to this map, the CHM is initialized.
+ * Primarily used to hold child maps for nodes. Underlying CHM is null initially, and once threads start writing to
+ * this map, the CHM is initialized.
*
* @author Manik Surtani (<a href="mailto:manik at jboss.org">manik at jboss.org</a>)
* @since 1.0
*/
-public class SelfInitializingConcurrentHashMap<K, V> implements ConcurrentMap<K, V>
-{
+public class SelfInitializingConcurrentHashMap<K, V> implements ConcurrentMap<K, V> {
private volatile ConcurrentMap<K, V> delegate;
// -------------- initialization methods and helpers ----------------------
- private ConcurrentMap<K, V> getDelegate()
- {
+ private ConcurrentMap<K, V> getDelegate() {
if (delegate == null) init();
return delegate;
}
- private synchronized void init()
- {
+ private synchronized void init() {
// Reminiscent of DCL but the delegate here is volatile so construction reordering should not affect.
if (delegate == null) delegate = new ConcurrentHashMap<K, V>(1, 0.75f, 4);
}
// -------------- Public API methods that will trigger initialization ----------------------
- public final V put(K key, V value)
- {
+ public final V put(K key, V value) {
return getDelegate().put(key, value);
}
- public final V remove(Object key)
- {
+ public final V remove(Object key) {
return getDelegate().remove(key);
}
- public final void putAll(Map<? extends K, ? extends V> m)
- {
+ public final void putAll(Map<? extends K, ? extends V> m) {
getDelegate().putAll(m);
}
- public final V putIfAbsent(K key, V value)
- {
+ public final V putIfAbsent(K key, V value) {
return getDelegate().putIfAbsent(key, value);
}
- public final boolean replace(K key, V oldValue, V newValue)
- {
+ public final boolean replace(K key, V oldValue, V newValue) {
return getDelegate().replace(key, oldValue, newValue);
}
- public final V replace(K key, V value)
- {
+ public final V replace(K key, V value) {
return getDelegate().replace(key, value);
}
// -------------- Public API methods that won't trigger initialization ----------------------
- public final boolean remove(Object key, Object value)
- {
+ public final boolean remove(Object key, Object value) {
return delegate != null && delegate.remove(key, value);
}
- public final int size()
- {
+ public final int size() {
return delegate == null ? 0 : delegate.size();
}
- public final boolean isEmpty()
- {
+ public final boolean isEmpty() {
return delegate == null || delegate.isEmpty();
}
- public final boolean containsKey(Object key)
- {
+ public final boolean containsKey(Object key) {
return delegate != null && delegate.containsKey(key);
}
- public final boolean containsValue(Object value)
- {
+ public final boolean containsValue(Object value) {
return delegate != null && delegate.containsValue(value);
}
- public final V get(Object key)
- {
+ public final V get(Object key) {
return delegate == null ? null : delegate.get(key);
}
- public final void clear()
- {
+ public final void clear() {
if (delegate != null) delegate.clear();
}
- public final Set<K> keySet()
- {
+ public final Set<K> keySet() {
if (delegate == null || delegate.isEmpty()) return Collections.emptySet();
return delegate.keySet();
}
- public final Collection<V> values()
- {
+ public final Collection<V> values() {
if (delegate == null || delegate.isEmpty()) return Collections.emptySet();
return delegate.values();
}
- public final Set<Entry<K, V>> entrySet()
- {
+ public final Set<Entry<K, V>> entrySet() {
if (delegate == null || delegate.isEmpty()) return Collections.emptySet();
return delegate.entrySet();
}
@Override
- public String toString()
- {
+ public String toString() {
return "SelfInitializingConcurrentHashMap{" +
"delegate=" + delegate +
'}';
}
@Override
- public boolean equals(Object o)
- {
+ public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
SelfInitializingConcurrentHashMap that = (SelfInitializingConcurrentHashMap) o;
@@ -157,8 +136,7 @@
}
@Override
- public int hashCode()
- {
+ public int hashCode() {
int result;
result = (delegate != null ? delegate.hashCode() : 0);
return result;
Modified: core/branches/flat/src/main/java/org/horizon/util/concurrent/SynchronizedRestarter.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/util/concurrent/SynchronizedRestarter.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/util/concurrent/SynchronizedRestarter.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -7,60 +7,47 @@
/**
* A class that handles restarts of components via multiple threads. Specifically, if a component needs to be restarted
- * and several threads may demand a restart but only one thread should be allowed to restart the component, then use this
- * class.
+ * and several threads may demand a restart but only one thread should be allowed to restart the component, then use
+ * this class.
* <p/>
* What this class guarantees is that several threads may come in while a component is being restarted, but they will
* block until the restart is complete.
* <p/>
- * This is different from other techniques in that:
- * <ul>
- * <li>A simple compare-and-swap to check whether another thread is already performing a restart will result in the
- * requesting thread returning immediately and potentially attempting to use the resource being restarted.</li>
- * <li>A synchronized method or use of a lock would result in the thread waiting for the restart to complete, but on
- * completion will attempt to restart the component again.</li>
- * </ul>
- * This implementation combines a compare-and-swap to detect a concurrent restart, as well as registering for notification
+ * This is different from other techniques in that: <ul> <li>A simple compare-and-swap to check whether another thread
+ * is already performing a restart will result in the requesting thread returning immediately and potentially attempting
+ * to use the resource being restarted.</li> <li>A synchronized method or use of a lock would result in the thread
+ * waiting for the restart to complete, but on completion will attempt to restart the component again.</li> </ul> This
+ * implementation combines a compare-and-swap to detect a concurrent restart, as well as registering for notification
* for when the restart completes and then parking the thread if the CAS variable still indicates a restart in progress,
* and finally deregistering itself in the end.
*
* @author Manik Surtani
* @since 1.0
*/
-public class SynchronizedRestarter
-{
+public class SynchronizedRestarter {
private AtomicBoolean restartInProgress = new AtomicBoolean(false);
private ConcurrentHashSet<Thread> restartWaiters = new ConcurrentHashSet<Thread>();
- public void restartComponent(Lifecycle component) throws Exception
- {
+ public void restartComponent(Lifecycle component) throws Exception {
// will only enter this block if no one else is restarting the socket
// and will atomically set the flag so others won't enter
- if (restartInProgress.compareAndSet(false, true))
- {
- try
- {
+ if (restartInProgress.compareAndSet(false, true)) {
+ try {
component.stop();
component.start();
}
- finally
- {
+ finally {
restartInProgress.set(false);
- for (Thread waiter : restartWaiters)
- {
- try
- {
+ for (Thread waiter : restartWaiters) {
+ try {
LockSupport.unpark(waiter);
}
- catch (Throwable t)
- {
+ catch (Throwable t) {
// do nothing; continue notifying the rest
}
}
}
- }
- else
- {
+ } else {
// register interest in being notified after the restart
restartWaiters.add(Thread.currentThread());
// check again to ensure the restarting thread hasn't finished, then wait for that thread to finish
Modified: core/branches/flat/src/main/java/org/horizon/util/concurrent/WithinThreadExecutor.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/util/concurrent/WithinThreadExecutor.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/util/concurrent/WithinThreadExecutor.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -26,7 +26,12 @@
import java.util.Collection;
import java.util.Collections;
import java.util.List;
-import java.util.concurrent.*;
+import java.util.concurrent.Callable;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
/**
* An executor that works within the current thread.
@@ -35,116 +40,94 @@
* @see <a href="http://jcip.net/">Java Concurrency In Practice</a>
* @since 1.0
*/
-public class WithinThreadExecutor implements ExecutorService
-{
+public class WithinThreadExecutor implements ExecutorService {
boolean shutDown = false;
- public void execute(Runnable command)
- {
+ public void execute(Runnable command) {
command.run();
}
- public void shutdown()
- {
+ public void shutdown() {
shutDown = true;
}
- public List<Runnable> shutdownNow()
- {
+ public List<Runnable> shutdownNow() {
shutDown = true;
return Collections.emptyList();
}
- public boolean isShutdown()
- {
+ public boolean isShutdown() {
return shutDown;
}
- public boolean isTerminated()
- {
+ public boolean isTerminated() {
return shutDown;
}
- public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException
- {
+ public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException {
return shutDown;
}
- public <T> Future<T> submit(Callable<T> task)
- {
- try
- {
+ public <T> Future<T> submit(Callable<T> task) {
+ try {
final T resp = task.call();
- return new Future<T>()
- {
+ return new Future<T>() {
- public boolean cancel(boolean mayInterruptIfRunning)
- {
+ public boolean cancel(boolean mayInterruptIfRunning) {
return false;
}
- public boolean isCancelled()
- {
+ public boolean isCancelled() {
return false;
}
- public boolean isDone()
- {
+ public boolean isDone() {
return true;
}
- public T get() throws InterruptedException, ExecutionException
- {
+ public T get() throws InterruptedException, ExecutionException {
return resp;
}
- public T get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException
- {
+ public T get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
return resp;
}
};
}
- catch (Exception e)
- {
+ catch (Exception e) {
throw new CacheException(e);
}
}
- public <T> Future<T> submit(Runnable task, T result)
- {
+ public <T> Future<T> submit(Runnable task, T result) {
throw new UnsupportedOperationException();
}
- public Future<?> submit(Runnable task)
- {
+ public Future<?> submit(Runnable task) {
throw new UnsupportedOperationException();
}
@SuppressWarnings("unchecked")
// unchecked on purpose due to http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6267833
- public List invokeAll(Collection tasks) throws InterruptedException
- {
+ public List invokeAll(Collection tasks) throws InterruptedException {
throw new UnsupportedOperationException();
}
@SuppressWarnings("unchecked")
// unchecked on purpose due to http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6267833
- public List invokeAll(Collection tasks, long timeout, TimeUnit unit) throws InterruptedException
- {
+ public List invokeAll(Collection tasks, long timeout, TimeUnit unit) throws InterruptedException {
throw new UnsupportedOperationException();
}
@SuppressWarnings("unchecked")
// unchecked on purpose due to http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6267833
- public Object invokeAny(Collection tasks) throws InterruptedException, ExecutionException
- {
+ public Object invokeAny(Collection tasks) throws InterruptedException, ExecutionException {
throw new UnsupportedOperationException();
}
@SuppressWarnings("unchecked")
// unchecked on purpose due to http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6267833
- public Object invokeAny(Collection tasks, long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException
- {
+ public Object invokeAny(Collection tasks, long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
throw new UnsupportedOperationException();
}
}
Modified: core/branches/flat/src/main/java/org/horizon/util/concurrent/locks/LockContainer.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/util/concurrent/locks/LockContainer.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/util/concurrent/locks/LockContainer.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -32,18 +32,15 @@
* @since 1.0
*/
@ThreadSafe
-public abstract class LockContainer<E>
-{
+public abstract class LockContainer<E> {
private int lockSegmentMask;
private int lockSegmentShift;
- protected int calculateNumberOfSegments(int concurrencyLevel)
- {
+ protected int calculateNumberOfSegments(int concurrencyLevel) {
int tempLockSegShift = 0;
int numLocks = 1;
- while (numLocks < concurrencyLevel)
- {
+ while (numLocks < concurrencyLevel) {
++tempLockSegShift;
numLocks <<= 1;
}
@@ -52,21 +49,18 @@
return numLocks;
}
- public final int hashToIndex(E object)
- {
+ public final int hashToIndex(E object) {
return (hash(object) >>> lockSegmentShift) & lockSegmentMask;
}
/**
- * Returns a hash code for non-null Object x.
- * Uses the same hash code spreader as most other java.util hash tables, except that this uses the string representation
- * of the object passed in.
+ * Returns a hash code for non-null Object x. Uses the same hash code spreader as most other java.util hash tables,
+ * except that this uses the string representation of the object passed in.
*
* @param object the object serving as a key
* @return the hash code
*/
- final int hash(E object)
- {
+ final int hash(E object) {
int h = object.hashCode();
// h ^= (h >>> 20) ^ (h >>> 12);
// return h ^ (h >>> 7) ^ (h >>> 4);
Modified: core/branches/flat/src/main/java/org/horizon/util/concurrent/locks/OwnableReentrantLock.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/util/concurrent/locks/OwnableReentrantLock.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/util/concurrent/locks/OwnableReentrantLock.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -31,12 +31,11 @@
/**
* A lock that supports reentrancy based on owner (and not on current thread). For this to work, the lock needs to be
- * constructed with a reference to the {@link InvocationContextContainer}, so it is able
- * to determine whether the caller's "owner" reference is the current thread or a {@link GlobalTransaction}
- * instance.
+ * constructed with a reference to the {@link InvocationContextContainer}, so it is able to determine whether the
+ * caller's "owner" reference is the current thread or a {@link GlobalTransaction} instance.
* <p/>
- * This makes this lock implementation very closely tied to JBoss Cache internals, but it provides for a very clean, efficient
- * and moreover familiar interface to work with, since it implements {@link java.util.concurrent.locks.Lock}.
+ * This makes this lock implementation very closely tied to JBoss Cache internals, but it provides for a very clean,
+ * efficient and moreover familiar interface to work with, since it implements {@link java.util.concurrent.locks.Lock}.
* <p/>
* For the sake of performance, this lock only supports nonfair queueing.
* <p/>
@@ -45,8 +44,7 @@
* @since 1.0
*/
@ThreadSafe
-public class OwnableReentrantLock extends AbstractQueuedSynchronizer implements Lock
-{
+public class OwnableReentrantLock extends AbstractQueuedSynchronizer implements Lock {
/**
* Current owner
*/
@@ -59,79 +57,66 @@
/**
* Creates a new lock instance.
*
- * @param invocationContextContainer InvocationContextContainer instance to consult for the invocation context of the call.
+ * @param invocationContextContainer InvocationContextContainer instance to consult for the invocation context of the
+ * call.
*/
- public OwnableReentrantLock(InvocationContextContainer invocationContextContainer)
- {
+ public OwnableReentrantLock(InvocationContextContainer invocationContextContainer) {
if (invocationContextContainer == null)
throw new IllegalArgumentException("Invocation context container cannot be null!");
this.invocationContextContainer = invocationContextContainer;
}
/**
- * @return a GlobalTransaction instance if the current call is participating in a transaction, or the current thread otherwise.
+ * @return a GlobalTransaction instance if the current call is participating in a transaction, or the current thread
+ * otherwise.
*/
- protected final Object currentRequestor()
- {
+ protected final Object currentRequestor() {
GlobalTransaction gtx;
return (gtx = invocationContextContainer.get().getGlobalTransaction()) == null ? Thread.currentThread() : gtx;
}
- public void lock()
- {
+ public void lock() {
if (compareAndSetState(0, 1))
owner = currentRequestor();
else
acquire(1);
}
- public void lockInterruptibly() throws InterruptedException
- {
+ public void lockInterruptibly() throws InterruptedException {
acquireInterruptibly(1);
}
- public boolean tryLock()
- {
+ public boolean tryLock() {
return tryAcquire(1);
}
- public boolean tryLock(long time, TimeUnit unit) throws InterruptedException
- {
+ public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
return tryAcquireNanos(1, unit.toNanos(time));
}
- public void unlock()
- {
- try
- {
+ public void unlock() {
+ try {
release(1);
}
- catch (IllegalMonitorStateException imse)
- {
+ catch (IllegalMonitorStateException imse) {
// ignore?
}
}
- public ConditionObject newCondition()
- {
+ public ConditionObject newCondition() {
throw new UnsupportedOperationException("Not supported in this implementation!");
}
@Override
- protected final boolean tryAcquire(int acquires)
- {
+ protected final boolean tryAcquire(int acquires) {
final Object current = currentRequestor();
int c = getState();
- if (c == 0)
- {
- if (compareAndSetState(0, acquires))
- {
+ if (c == 0) {
+ if (compareAndSetState(0, acquires)) {
owner = current;
return true;
}
- }
- else if (current.equals(owner))
- {
+ } else if (current.equals(owner)) {
setState(c + acquires);
return true;
}
@@ -139,18 +124,15 @@
}
@Override
- protected final boolean tryRelease(int releases)
- {
+ protected final boolean tryRelease(int releases) {
int c = getState() - releases;
- if (!currentRequestor().equals(owner))
- {
+ if (!currentRequestor().equals(owner)) {
//throw new IllegalMonitorStateException(this.toString());
// lets be quiet about this
return false;
}
boolean free = false;
- if (c == 0)
- {
+ if (c == 0) {
free = true;
owner = null;
}
@@ -159,16 +141,14 @@
}
@Override
- protected final boolean isHeldExclusively()
- {
+ protected final boolean isHeldExclusively() {
return getState() != 0 && currentRequestor().equals(owner);
}
/**
* @return the owner of the lock, or null if it is currently unlocked.
*/
- public final Object getOwner()
- {
+ public final Object getOwner() {
int c = getState();
Object o = owner;
return (c == 0) ? null : o;
@@ -177,8 +157,7 @@
/**
* @return the hold count of the current lock, or 0 if it is not locked.
*/
- public final int getHoldCount()
- {
+ public final int getHoldCount() {
int c = getState();
Object o = owner;
return (currentRequestor().equals(o)) ? c : 0;
@@ -187,8 +166,7 @@
/**
* @return true if the lock is locked, false otherwise
*/
- public final boolean isLocked()
- {
+ public final boolean isLocked() {
return getState() != 0;
}
@@ -198,22 +176,19 @@
* @param s the stream
*/
private void readObject(java.io.ObjectInputStream s)
- throws java.io.IOException, ClassNotFoundException
- {
+ throws java.io.IOException, ClassNotFoundException {
s.defaultReadObject();
setState(0); // reset to unlocked state
}
/**
- * Returns a string identifying this lock, as well as its lock
- * state. The state, in brackets, includes either the String
- * "Unlocked" or the String "Locked by"
- * followed by the String representation of the lock owner.
+ * Returns a string identifying this lock, as well as its lock state. The state, in brackets, includes either the
+ * String "Unlocked" or the String "Locked by" followed by the String representation of the lock
+ * owner.
*
* @return a string identifying this lock, as well as its lock state.
*/
- public String toString()
- {
+ public String toString() {
Object owner = getOwner();
return super.toString() + ((owner == null) ?
"[Unlocked]" :
Modified: core/branches/flat/src/main/java/org/horizon/util/concurrent/locks/OwnableReentrantLockContainer.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/util/concurrent/locks/OwnableReentrantLockContainer.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/util/concurrent/locks/OwnableReentrantLockContainer.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -35,72 +35,63 @@
* @since 1.0
*/
@ThreadSafe
-public class OwnableReentrantLockContainer<E> extends LockContainer<E>
-{
+public class OwnableReentrantLockContainer<E> extends LockContainer<E> {
OwnableReentrantLock[] sharedLocks;
InvocationContextContainer icc;
- public OwnableReentrantLockContainer(int concurrencyLevel, Object dummy)
- {
+ public OwnableReentrantLockContainer(int concurrencyLevel, Object dummy) {
throw new UnsupportedOperationException("Barf"); // todo remove this
}
/**
- * Creates a new LockContainer which uses a certain number of shared locks across all elements that need to be locked.
+ * Creates a new LockContainer which uses a certain number of shared locks across all elements that need to be
+ * locked.
*
- * @param concurrencyLevel concurrency level for number of stripes to create. Stripes are created in powers of two, with a minimum of concurrencyLevel created.
+ * @param concurrencyLevel concurrency level for number of stripes to create. Stripes are created in powers of two,
+ * with a minimum of concurrencyLevel created.
* @param icc invocation context container to use
*/
- public OwnableReentrantLockContainer(int concurrencyLevel, InvocationContextContainer icc)
- {
+ public OwnableReentrantLockContainer(int concurrencyLevel, InvocationContextContainer icc) {
this.icc = icc;
initLocks(calculateNumberOfSegments(concurrencyLevel));
}
- protected void initLocks(int numLocks)
- {
+ protected void initLocks(int numLocks) {
sharedLocks = new OwnableReentrantLock[numLocks];
for (int i = 0; i < numLocks; i++) sharedLocks[i] = new OwnableReentrantLock(icc);
}
- public final OwnableReentrantLock getLock(E object)
- {
+ public final OwnableReentrantLock getLock(E object) {
return sharedLocks[hashToIndex(object)];
}
- public final boolean ownsLock(E object, Object owner)
- {
+ public final boolean ownsLock(E object, Object owner) {
OwnableReentrantLock lock = getLock(object);
return owner.equals(lock.getOwner());
}
- public final boolean isLocked(E object)
- {
+ public final boolean isLocked(E object) {
OwnableReentrantLock lock = getLock(object);
return lock.isLocked();
}
- public final int getNumLocksHeld()
- {
+ public final int getNumLocksHeld() {
int i = 0;
for (OwnableReentrantLock l : sharedLocks) if (l.isLocked()) i++;
return i;
}
- public String toString()
- {
+ public String toString() {
return "OwnableReentrantLockContainer{" +
"sharedLocks=" + (sharedLocks == null ? null : Arrays.asList(sharedLocks)) +
'}';
}
- public void reset()
- {
+ public void reset() {
initLocks(sharedLocks.length);
}
- public int size()
- {
+ public int size() {
return sharedLocks.length;
}
}
Modified: core/branches/flat/src/main/java/org/horizon/util/concurrent/locks/ReentrantLockContainer.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/util/concurrent/locks/ReentrantLockContainer.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/util/concurrent/locks/ReentrantLockContainer.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -34,64 +34,56 @@
* @since 1.0
*/
@ThreadSafe
-public class ReentrantLockContainer<E> extends LockContainer<E>
-{
+public class ReentrantLockContainer<E> extends LockContainer<E> {
ReentrantLock[] sharedLocks;
/**
- * Creates a new LockContainer which uses a certain number of shared locks across all elements that need to be locked.
+ * Creates a new LockContainer which uses a certain number of shared locks across all elements that need to be
+ * locked.
*
- * @param concurrencyLevel concurrency level for number of stripes to create. Stripes are created in powers of two, with a minimum of concurrencyLevel created.
+ * @param concurrencyLevel concurrency level for number of stripes to create. Stripes are created in powers of two,
+ * with a minimum of concurrencyLevel created.
*/
- public ReentrantLockContainer(int concurrencyLevel)
- {
+ public ReentrantLockContainer(int concurrencyLevel) {
initLocks(calculateNumberOfSegments(concurrencyLevel));
}
- protected void initLocks(int numLocks)
- {
+ protected void initLocks(int numLocks) {
sharedLocks = new ReentrantLock[numLocks];
for (int i = 0; i < numLocks; i++) sharedLocks[i] = new ReentrantLock();
}
- public final ReentrantLock getLock(E object)
- {
+ public final ReentrantLock getLock(E object) {
return sharedLocks[hashToIndex(object)];
}
- public final int getNumLocksHeld()
- {
+ public final int getNumLocksHeld() {
int i = 0;
for (ReentrantLock l : sharedLocks) if (l.isLocked()) i++;
return i;
}
- public int size()
- {
+ public int size() {
return sharedLocks.length;
}
- public final boolean ownsLock(E object, Object owner)
- {
+ public final boolean ownsLock(E object, Object owner) {
ReentrantLock lock = getLock(object);
return lock.isHeldByCurrentThread();
}
- public final boolean isLocked(E object)
- {
+ public final boolean isLocked(E object) {
ReentrantLock lock = getLock(object);
return lock.isLocked();
}
- public String toString()
- {
+ public String toString() {
return "ReentrantLockContainer{" +
"sharedLocks=" + (sharedLocks == null ? null : Arrays.asList(sharedLocks)) +
'}';
}
- public void reset()
- {
+ public void reset() {
initLocks(sharedLocks.length);
}
}
Modified: core/branches/flat/src/main/java/org/horizon/util/internals/ReplicationListener.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/util/internals/ReplicationListener.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/util/internals/ReplicationListener.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -50,8 +50,7 @@
* @author Mircea.Markus at jboss.com
* @since 1.0
*/
-public class ReplicationListener
-{
+public class ReplicationListener {
private CountDownLatch latch = new CountDownLatch(1);
private Set<Class<? extends ReplicableCommand>> expectedCommands;
Configuration configuration;
@@ -60,8 +59,7 @@
/**
* Builds a listener that will observe the given cache for recieving replication commands.
*/
- public ReplicationListener(Cache cache)
- {
+ public ReplicationListener(Cache cache) {
ComponentRegistry componentRegistry = TestingUtil.extractComponentRegistry(cache);
RPCManager rpcManager = componentRegistry.getComponent(RPCManager.class);
CommandAwareRpcDispatcher realDispatcher = (CommandAwareRpcDispatcher) TestingUtil.extractField(rpcManager, "rpcDispatcher");
@@ -74,41 +72,33 @@
configuration = cache.getConfiguration();
}
- private class MarshallerDelegate implements RpcDispatcher.Marshaller2
- {
+ private class MarshallerDelegate implements RpcDispatcher.Marshaller2 {
RpcDispatcher.Marshaller2 marshaller;
- private MarshallerDelegate(RpcDispatcher.Marshaller2 marshaller)
- {
+ private MarshallerDelegate(RpcDispatcher.Marshaller2 marshaller) {
this.marshaller = marshaller;
}
- public byte[] objectToByteBuffer(Object obj) throws Exception
- {
+ public byte[] objectToByteBuffer(Object obj) throws Exception {
return marshaller.objectToByteBuffer(obj);
}
- public Object objectFromByteBuffer(byte bytes[]) throws Exception
- {
+ public Object objectFromByteBuffer(byte bytes[]) throws Exception {
Object result = marshaller.objectFromByteBuffer(bytes);
- if (result instanceof ReplicateCommand && expectedCommands != null)
- {
+ if (result instanceof ReplicateCommand && expectedCommands != null) {
ReplicateCommand replicateCommand = (ReplicateCommand) result;
return new ReplicateCommandDelegate(replicateCommand);
}
return result;
}
- public Buffer objectToBuffer(Object o) throws Exception
- {
+ public Buffer objectToBuffer(Object o) throws Exception {
return marshaller.objectToBuffer(o);
}
- public Object objectFromByteBuffer(byte[] bytes, int i, int i1) throws Exception
- {
+ public Object objectFromByteBuffer(byte[] bytes, int i, int i1) throws Exception {
Object result = marshaller.objectFromByteBuffer(bytes, i, i1);
- if (result instanceof ReplicateCommand && expectedCommands != null)
- {
+ if (result instanceof ReplicateCommand && expectedCommands != null) {
ReplicateCommand replicateCommand = (ReplicateCommand) result;
return new ReplicateCommandDelegate(replicateCommand);
}
@@ -119,44 +109,34 @@
/**
* We want the notification to be performed only *after* the remote command is executed.
*/
- private class ReplicateCommandDelegate extends ReplicateCommand
- {
+ private class ReplicateCommandDelegate extends ReplicateCommand {
ReplicateCommand realOne;
- private ReplicateCommandDelegate(ReplicateCommand realOne)
- {
+ private ReplicateCommandDelegate(ReplicateCommand realOne) {
this.realOne = realOne;
}
@Override
- public Object perform(InvocationContext ctx) throws Throwable
- {
- try
- {
+ public Object perform(InvocationContext ctx) throws Throwable {
+ try {
return realOne.perform(ctx);
}
- finally
- {
+ finally {
log.trace("Processed command: " + realOne);
Iterator<Class<? extends ReplicableCommand>> it = expectedCommands.iterator();
- while (it.hasNext())
- {
+ while (it.hasNext()) {
Class<? extends ReplicableCommand> replicableCommandClass = it.next();
- if (realOne.containsCommandType(replicableCommandClass))
- {
+ if (realOne.containsCommandType(replicableCommandClass)) {
it.remove();
- }
- else if (realOne.getSingleModification() instanceof PrepareCommand) //explicit transaction
+ } else if (realOne.getSingleModification() instanceof PrepareCommand) //explicit transaction
{
PrepareCommand prepareCommand = (PrepareCommand) realOne.getSingleModification();
- if (prepareCommand.containsModificationType(replicableCommandClass))
- {
+ if (prepareCommand.containsModificationType(replicableCommandClass)) {
it.remove();
}
}
}
- if (expectedCommands.isEmpty())
- {
+ if (expectedCommands.isEmpty()) {
latch.countDown();
}
}
@@ -166,49 +146,40 @@
/**
* Needed for region based marshalling.
*/
- private class RegionMarshallerDelegate extends CacheMarshallerStarobrno
- {
+ private class RegionMarshallerDelegate extends CacheMarshallerStarobrno {
private Marshaller realOne;
- private RegionMarshallerDelegate(Marshaller realOne)
- {
+ private RegionMarshallerDelegate(Marshaller realOne) {
this.realOne = realOne;
}
@Override
- public void objectToObjectStream(Object obj, ObjectOutputStream out) throws Exception
- {
+ public void objectToObjectStream(Object obj, ObjectOutputStream out) throws Exception {
realOne.objectToObjectStream(obj, out);
}
@Override
- public Object objectFromObjectStream(ObjectInputStream in) throws Exception
- {
+ public Object objectFromObjectStream(ObjectInputStream in) throws Exception {
return realOne.objectFromObjectStream(in);
}
@Override
- public Object objectFromStream(InputStream is) throws Exception
- {
+ public Object objectFromStream(InputStream is) throws Exception {
return realOne.objectFromStream(is);
}
- public Object objectFromByteBuffer(byte[] bytes) throws Exception
- {
+ public Object objectFromByteBuffer(byte[] bytes) throws Exception {
return this.objectFromByteBuffer(bytes, 0, bytes.length);
}
- public ByteBuffer objectToBuffer(Object o) throws Exception
- {
+ public ByteBuffer objectToBuffer(Object o) throws Exception {
return realOne.objectToBuffer(o);
}
- public Object objectFromByteBuffer(byte[] buffer, int i, int i1) throws Exception
- {
+ public Object objectFromByteBuffer(byte[] buffer, int i, int i1) throws Exception {
Object result = realOne.objectFromByteBuffer(buffer, i, i1);
- if (result instanceof ReplicateCommand && expectedCommands != null)
- {
+ if (result instanceof ReplicateCommand && expectedCommands != null) {
ReplicateCommand replicateCommand = (ReplicateCommand) result;
result = new ReplicateCommandDelegate(replicateCommand);
}
@@ -219,57 +190,49 @@
/**
* Waits for 1 minute
*/
- public void waitForReplicationToOccur()
- {
+ public void waitForReplicationToOccur() {
waitForReplicationToOccur(60000);
}
/**
- * Blocks for the elements specified through {@link #expect(Class[])} invocations to be replicated in this cache.
- * if replication does not occur in the give timeout then an exception is being thrown.
+ * Blocks for the elements specified through {@link #expect(Class[])} invocations to be replicated in this cache. if
+ * replication does not occur in the give timeout then an exception is being thrown.
*/
- public void waitForReplicationToOccur(long timeoutMillis)
- {
+ public void waitForReplicationToOccur(long timeoutMillis) {
log.trace("enter... ReplicationListener.waitForReplicationToOccur");
waitForReplicationToOccur(timeoutMillis, TimeUnit.MILLISECONDS);
log.trace("exit... ReplicationListener.waitForReplicationToOccur");
}
/**
- * Similar to {@link #waitForReplicationToOccur(long)} except that this method provides more flexibility in time units.
+ * Similar to {@link #waitForReplicationToOccur(long)} except that this method provides more flexibility in time
+ * units.
*
* @param timeout the maximum time to wait
* @param timeUnit the time unit of the <tt>timeout</tt> argument.
*/
- public void waitForReplicationToOccur(long timeout, TimeUnit timeUnit)
- {
+ public void waitForReplicationToOccur(long timeout, TimeUnit timeUnit) {
assert expectedCommands != null : "there are no replication expectations; please use AsyncReplicationListener.expect(...) before calling this method";
- try
- {
- if (!latch.await(timeout, timeUnit))
- {
+ try {
+ if (!latch.await(timeout, timeUnit)) {
assert false : "waiting for more than " + timeout + " " + timeUnit + " and following commands did not replicate: " + expectedCommands;
}
}
- catch (InterruptedException e)
- {
+ catch (InterruptedException e) {
throw new IllegalStateException("unexpected", e);
}
- finally
- {
+ finally {
expectedCommands = null;
latch = new CountDownLatch(1);
}
}
/**
- * {@link #waitForReplicationToOccur(long)} will block untill all the commands specified here are being replicated
- * to this cache. The method can be called several times with various arguments.
+ * {@link #waitForReplicationToOccur(long)} will block untill all the commands specified here are being replicated to
+ * this cache. The method can be called several times with various arguments.
*/
- public void expect(Class<? extends ReplicableCommand>... expectedCommands)
- {
- if (this.expectedCommands == null)
- {
+ public void expect(Class<? extends ReplicableCommand>... expectedCommands) {
+ if (this.expectedCommands == null) {
this.expectedCommands = new HashSet<Class<? extends ReplicableCommand>>();
}
this.expectedCommands.addAll(Arrays.asList(expectedCommands));
@@ -278,13 +241,11 @@
/**
* Waits untill first command is replicated.
*/
- public void expectAny()
- {
+ public void expectAny() {
expect();
}
- public void expectWithTx(Class<? extends ReplicableCommand>... writeCommands)
- {
+ public void expectWithTx(Class<? extends ReplicableCommand>... writeCommands) {
expect(PrepareCommand.class);
//this is because for async replication we have an 1pc transaction
if (configuration.getCacheMode().isSynchronous()) expect(CommitCommand.class);
Modified: core/branches/flat/src/main/java/org/horizon/util/internals/ViewChangeListener.java
===================================================================
--- core/branches/flat/src/main/java/org/horizon/util/internals/ViewChangeListener.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/main/java/org/horizon/util/internals/ViewChangeListener.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -15,14 +15,15 @@
* <pre>
* Cache c = getCache();
* ViewChangeListener vcl = new ViewChangeListener(c);
- * assert vcl.waitForViewChange(60, TimeUnit.SECONDS); // will block for up to 60 seconds for a view change on cache c
+ * assert vcl.waitForViewChange(60, TimeUnit.SECONDS); // will block for up to 60 seconds for a view change on cache
+ * c
* </pre>
- * @since 1.0
+ *
* @author (various)
+ * @since 1.0
*/
@CacheListener
-public class ViewChangeListener
-{
+public class ViewChangeListener {
CountDownLatch latch;
/**
@@ -30,15 +31,13 @@
*
* @param cache cache to listen on for view change events
*/
- public ViewChangeListener(Cache cache)
- {
+ public ViewChangeListener(Cache cache) {
this.latch = new CountDownLatch(1);
cache.addCacheListener(this);
}
@ViewChanged
- public void handleViewChange(ViewChangedEvent e)
- {
+ public void handleViewChange(ViewChangedEvent e) {
if (!e.isPre()) latch.countDown();
}
@@ -50,8 +49,7 @@
* @return true if a view change is received, false otherwise.
* @throws InterruptedException
*/
- public boolean waitForViewChange(long timeout, TimeUnit unit) throws InterruptedException
- {
+ public boolean waitForViewChange(long timeout, TimeUnit unit) throws InterruptedException {
return latch.await(timeout, unit);
}
}
\ No newline at end of file
Modified: core/branches/flat/src/test/java/org/horizon/BasicTest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/BasicTest.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/test/java/org/horizon/BasicTest.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -27,21 +27,16 @@
import org.horizon.manager.CacheManager;
import org.horizon.manager.NamedCacheNotFoundException;
import org.horizon.util.TestingUtil;
-import org.horizon.Cache;
-import org.horizon.CacheSPI;
import org.testng.annotations.Test;
@Test(groups = "functional")
-public class BasicTest
-{
- public void basicTest() throws Exception
- {
+public class BasicTest {
+ public void basicTest() throws Exception {
// create a cache manager
Configuration c = new Configuration(); // LOCAL mode
c.setFetchInMemoryState(false);
CacheManager cm = new CacheManager(c);
- try
- {
+ try {
cm.start();
Cache cache = cm.getCache("test");
String key = "key", value = "value";
@@ -61,24 +56,21 @@
assert cache.size() == 0;
assert !cache.containsKey(key);
}
- finally
- {
+ finally {
cm.stop();
}
}
public static final Log log = LogFactory.getLog(BasicTest.class);
- public void testBasicReplication() throws NamedCacheNotFoundException
- {
+ public void testBasicReplication() throws NamedCacheNotFoundException {
Configuration configuration = new Configuration();
configuration.setCacheMode(Configuration.CacheMode.REPL_SYNC);
CacheManager firstManager = new CacheManager(configuration);
CacheManager secondManager = new CacheManager(configuration);
- try
- {
+ try {
firstManager.start();
secondManager.start();
@@ -97,20 +89,17 @@
firstCache.remove("key");
assert secondCache.get("key") == null;
}
- finally
- {
+ finally {
firstManager.stop();
secondManager.stop();
}
}
- public void concurrentMapMethodTest()
- {
+ public void concurrentMapMethodTest() {
}
- public void transactionalTest()
- {
+ public void transactionalTest() {
}
}
Modified: core/branches/flat/src/test/java/org/horizon/UnitTestCacheFactory.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/UnitTestCacheFactory.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/test/java/org/horizon/UnitTestCacheFactory.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -35,13 +35,11 @@
/**
* Holds unique mcast_addr for each thread used for JGroups channel construction.
*/
- private static final ThreadLocal<String> threadMcastIP = new ThreadLocal<String>()
- {
+ private static final ThreadLocal<String> threadMcastIP = new ThreadLocal<String>() {
private final AtomicInteger uniqueAddr = new AtomicInteger(11);
@Override
- protected String initialValue()
- {
+ protected String initialValue() {
return "228.10.10." + uniqueAddr.getAndIncrement();
}
};
@@ -49,13 +47,11 @@
/**
* Holds unique mcast_port for each thread used for JGroups channel construction.
*/
- private static final ThreadLocal<Integer> threadMcastPort = new ThreadLocal<Integer>()
- {
+ private static final ThreadLocal<Integer> threadMcastPort = new ThreadLocal<Integer>() {
private final AtomicInteger uniquePort = new AtomicInteger(45589);
@Override
- protected Integer initialValue()
- {
+ protected Integer initialValue() {
return uniquePort.getAndIncrement();
}
};
@@ -64,11 +60,9 @@
* For each thread holds list of caches created using this factory.
*/
private static final ThreadLocal<List<Cache>> threadCaches =
- new ThreadLocal<List<Cache>>()
- {
+ new ThreadLocal<List<Cache>>() {
@Override
- protected List<Cache> initialValue()
- {
+ protected List<Cache> initialValue() {
return new ArrayList<Cache>();
}
};
@@ -82,48 +76,40 @@
// factory methods
- public Cache<K, V> createCache() throws ConfigurationException
- {
+ public Cache<K, V> createCache() throws ConfigurationException {
return createCache(true);
}
- public Cache<K, V> createCache(boolean start) throws ConfigurationException
- {
+ public Cache<K, V> createCache(boolean start) throws ConfigurationException {
return createCache(new Configuration(), start);
}
- public Cache<K, V> createCache(String configFileName) throws ConfigurationException
- {
+ public Cache<K, V> createCache(String configFileName) throws ConfigurationException {
return createCache(configFileName, true);
}
- public Cache<K, V> createCache(String configFileName, boolean start) throws ConfigurationException
- {
+ public Cache<K, V> createCache(String configFileName, boolean start) throws ConfigurationException {
XmlConfigurationParserJBC3 parser = new XmlConfigurationParserJBC3();
Configuration c;
c = parser.parseFile(configFileName);
return createCache(c, start);
}
- public Cache<K, V> createCache(Configuration configuration) throws ConfigurationException
- {
+ public Cache<K, V> createCache(Configuration configuration) throws ConfigurationException {
return createCache(configuration, true);
}
- public Cache<K, V> createCache(InputStream is) throws ConfigurationException
- {
+ public Cache<K, V> createCache(InputStream is) throws ConfigurationException {
return createCache(is, true);
}
- public Cache<K, V> createCache(InputStream is, boolean start) throws ConfigurationException
- {
+ public Cache<K, V> createCache(InputStream is, boolean start) throws ConfigurationException {
XmlConfigurationParserJBC3 parser = new XmlConfigurationParserJBC3();
Configuration c = parser.parseStream(is);
return createCache(c, start);
}
- public Cache<K, V> createCache(Configuration configuration, boolean start) throws ConfigurationException
- {
+ public Cache<K, V> createCache(Configuration configuration, boolean start) throws ConfigurationException {
// - Do not print out this exception - since tests are ALSO run from IDEs on the main thread. - MANIK
// if (!Thread.currentThread().getName().contains("pool"))
// {
@@ -132,8 +118,7 @@
checkCaches();
- switch (configuration.getCacheMode())
- {
+ switch (configuration.getCacheMode()) {
case LOCAL:
// local cache, no channel used
break;
@@ -155,8 +140,7 @@
List<Cache> caches = threadCaches.get();
caches.add(cache);
- synchronized (allCaches)
- {
+ synchronized (allCaches) {
allCaches.add(cache);
}
return cache;
@@ -168,21 +152,18 @@
*
* @return true if some cleanup was actually performed
*/
- public boolean cleanUp()
- {
+ public boolean cleanUp() {
List<Cache> caches = new ArrayList<Cache>(threadCaches.get());
boolean ret = false;
- for (Cache cache : caches)
- {
+ for (Cache cache : caches) {
TestingUtil.killCaches(cache);
ret = true;
}
return ret;
}
- public void removeCache(Cache c)
- {
+ public void removeCache(Cache c) {
// - Do not print out this exception - since tests are ALSO run from IDEs on the main thread. - MANIK
// if (!Thread.currentThread().getName().contains("pool"))
@@ -191,15 +172,11 @@
// }
List<Cache> caches = threadCaches.get();
- synchronized (allCaches)
- {
- if (caches.contains(c))
- {
+ synchronized (allCaches) {
+ if (caches.contains(c)) {
caches.remove(c);
allCaches.remove(c);
- }
- else if (allCaches.contains(c))
- {
+ } else if (allCaches.contains(c)) {
System.out.println("[" + Thread.currentThread().getName() + "] WARNING!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Remove cache called from different thread.");
Thread.dumpStack();
}
@@ -211,8 +188,7 @@
*
* @param configuration Configuration to update.
*/
- public void mangleConfiguration(Configuration configuration)
- {
+ public void mangleConfiguration(Configuration configuration) {
configuration.setClusterConfig(mangleClusterConfiguration(configuration.getClusterConfig()));
// Check if the cluster name contains thread id. If not, append.
@@ -222,8 +198,7 @@
String clusterName = configuration.getClusterName();
// append thread id
- if (clusterName.indexOf(Thread.currentThread().getName()) == -1)
- {
+ if (clusterName.indexOf(Thread.currentThread().getName()) == -1) {
clusterName = clusterName + "-" + Thread.currentThread().getName();
// System.out.println(getThreadId() + " Setting cluster name " + newClusterName);
}
@@ -244,10 +219,8 @@
/**
* Updates cluster configuration to ensure mutual thread isolation.
*/
- public String mangleClusterConfiguration(String clusterConfig)
- {
- if (clusterConfig == null)
- {
+ public String mangleClusterConfiguration(String clusterConfig) {
+ if (clusterConfig == null) {
// No explicit cluster configuration found. we need to resolve the default config
// now in orded to be able to update it before the cache (and the channel) starts.
@@ -257,15 +230,12 @@
// replace mcast_addr
Pattern pattern = Pattern.compile("mcast_addr=[^;]*");
Matcher m = pattern.matcher(clusterConfig);
- if (m.find())
- {
+ if (m.find()) {
String origAddr = m.group().substring(m.group().indexOf("=") + 1);
String newAddr = threadMcastIP.get();
// System.out.println(getThreadId() + " Replacing mcast_addr " + origAddr + " with " + newAddr);
clusterConfig = m.replaceFirst("mcast_addr=" + newAddr);
- }
- else
- {
+ } else {
Thread.dumpStack();
System.exit(1);
}
@@ -273,8 +243,7 @@
// replace mcast_port
pattern = Pattern.compile("mcast_port=[^;]*");
m = pattern.matcher(clusterConfig);
- if (m.find())
- {
+ if (m.find()) {
// String origPort = m.group().substring(m.group().indexOf("=") + 1);
String newPort = threadMcastPort.get().toString();
// System.out.println(getThreadId() + " Replacing mcast_port " + origPort + " with " + newPort);
@@ -289,21 +258,18 @@
// return "[" + Thread.currentThread().getName() + "]";
// }
- private void checkCaches()
- {
+ private void checkCaches() {
String lastTestName = threadTestName.get();
String currentTestName = extractTestName();
- if ((lastTestName != null) && (!lastTestName.equals(currentTestName)))
- {
+ if ((lastTestName != null) && (!lastTestName.equals(currentTestName))) {
String threadId = "[" + Thread.currentThread().getName() + "] ";
// we are running new test class
// check if there is a cache(s) instance left & kill it if possitive
- if (cleanUp())
- {
+ if (cleanUp()) {
System.out.print(threadId + "WARNING!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ");
System.out.print(threadId + " A test method in " + lastTestName + " did not clean all cache instances properly. ");
System.out.println(threadId + " Use UnitTestCacheFactory.cleanUp() or TestngUtil.killCaches(...) ");
@@ -313,12 +279,10 @@
threadTestName.set(currentTestName);
}
- private String extractTestName()
- {
+ private String extractTestName() {
StackTraceElement[] stack = Thread.currentThread().getStackTrace();
if (stack.length == 0) return null;
- for (int i = stack.length - 1; i > 0; i--)
- {
+ for (int i = stack.length - 1; i > 0; i--) {
StackTraceElement e = stack[i];
String className = e.getClassName();
if (className.indexOf("org.horizon") != -1) return className; //+ "." + e.getMethodName();
@@ -326,23 +290,20 @@
return null;
}
- private String getDefaultClusterConfiguration()
- {
+ private String getDefaultClusterConfiguration() {
return getClusterConfigFromFile(new Configuration().getDefaultClusterConfig());
}
/**
- * Helper method that takes a <b>JGroups</b> configuration file and creates an old-style JGroups config {@link String} that can be used
- * in {@link Configuration#setClusterConfig(String)}. Note that expressions
- * in the file - such as <tt>${jgroups.udp.mcast_port:45588}</tt> are expanded out accordingly.
+ * Helper method that takes a <b>JGroups</b> configuration file and creates an old-style JGroups config {@link
+ * String} that can be used in {@link Configuration#setClusterConfig(String)}. Note that expressions in the file -
+ * such as <tt>${jgroups.udp.mcast_port:45588}</tt> are expanded out accordingly.
*
* @param url url to the cfg file
* @return a String
*/
- public static String getClusterConfigFromFile(URL url)
- {
- try
- {
+ public static String getClusterConfigFromFile(URL url) {
+ try {
XmlConfigurator conf = XmlConfigurator.getInstance(url);
String tmp = conf.getProtocolStackString();
// parse this string for ${} substitutions
@@ -353,8 +314,7 @@
// System.out.println("config string: " + tmp);
return tmp;
}
- catch (Exception e)
- {
+ catch (Exception e) {
throw new RuntimeException("Problems with url " + url, e);
}
}
Modified: core/branches/flat/src/test/java/org/horizon/UnitTestCacheManager.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/UnitTestCacheManager.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/test/java/org/horizon/UnitTestCacheManager.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -10,23 +10,19 @@
/**
* @author dpospisi
*/
-public class UnitTestCacheManager
-{
+public class UnitTestCacheManager {
Configuration c;
- public UnitTestCacheManager(Configuration c)
- {
+ public UnitTestCacheManager(Configuration c) {
this.c = c.clone();
}
- protected Cache createNewCache()
- {
+ protected Cache createNewCache() {
UnitTestCacheFactory dcf = new UnitTestCacheFactory();
return dcf.createCache(c);
}
- public Cache createCache(String name)
- {
+ public Cache createCache(String name) {
return createNewCache();
}
}
Modified: core/branches/flat/src/test/java/org/horizon/api/CacheAPITest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/api/CacheAPITest.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/test/java/org/horizon/api/CacheAPITest.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -1,10 +1,10 @@
package org.horizon.api;
-import org.horizon.lock.IsolationLevel;
import org.horizon.CacheSPI;
import org.horizon.UnitTestCacheFactory;
import org.horizon.config.Configuration;
import org.horizon.config.ConfigurationException;
+import org.horizon.lock.IsolationLevel;
import org.horizon.transaction.DummyTransactionManager;
import org.horizon.transaction.DummyTransactionManagerLookup;
import org.horizon.util.TestingUtil;
@@ -24,13 +24,11 @@
*/
@Test(groups = {"functional", "pessimistic"})
-public abstract class CacheAPITest
-{
+public abstract class CacheAPITest {
private ThreadLocal<CacheSPI<String, String>> cacheTL = new ThreadLocal<CacheSPI<String, String>>();
@BeforeMethod(alwaysRun = true)
- public void setUp() throws Exception
- {
+ public void setUp() throws Exception {
// start a single cache instance
Configuration c = new Configuration();
c.setIsolationLevel(getIsolationLevel());
@@ -43,8 +41,7 @@
protected abstract IsolationLevel getIsolationLevel();
@AfterMethod(alwaysRun = true)
- public void tearDown()
- {
+ public void tearDown() {
CacheSPI<String, String> cache = cacheTL.get();
TestingUtil.killCaches(cache);
cacheTL.set(null);
@@ -53,21 +50,18 @@
/**
* Tests that the configuration contains the values expected, as well as immutability of certain elements
*/
- public void testConfiguration()
- {
+ public void testConfiguration() {
CacheSPI<String, String> cache = cacheTL.get();
Configuration c = cache.getConfiguration();
assertEquals(Configuration.CacheMode.LOCAL, c.getCacheMode());
assertEquals(DummyTransactionManagerLookup.class.getName(), c.getTransactionManagerLookupClass());
// note that certain values should be immutable. E.g., CacheMode cannot be changed on the fly.
- try
- {
+ try {
c.setCacheMode(Configuration.CacheMode.REPL_SYNC);
assert false : "Should have thrown an Exception";
}
- catch (ConfigurationException e)
- {
+ catch (ConfigurationException e) {
// expected
}
@@ -75,14 +69,12 @@
c.setLockAcquisitionTimeout(100);
}
- public void testGetMembersInLocalMode()
- {
+ public void testGetMembersInLocalMode() {
CacheSPI<String, String> cache = cacheTL.get();
assert cache.getRPCManager().getLocalAddress() == null : "Cache members should be null if running in LOCAL mode";
}
- public void testConvenienceMethods()
- {
+ public void testConvenienceMethods() {
CacheSPI<String, String> cache = cacheTL.get();
String key = "key", value = "value";
Map<String, String> data = new HashMap<String, String>();
@@ -106,8 +98,7 @@
/**
* Tests basic eviction
*/
- public void testEvict()
- {
+ public void testEvict() {
CacheSPI<String, String> cache = cacheTL.get();
String key1 = "keyOne", key2 = "keyTwo", value = "value";
@@ -132,8 +123,7 @@
assert cache.size() == 0;
}
- public void testStopClearsData() throws Exception
- {
+ public void testStopClearsData() throws Exception {
CacheSPI<String, String> cache = cacheTL.get();
String key = "key", value = "value";
cache.put(key, value);
@@ -147,8 +137,7 @@
assert cache.isEmpty();
}
- public void testRollbackAfterPut() throws Exception
- {
+ public void testRollbackAfterPut() throws Exception {
CacheSPI<String, String> cache = cacheTL.get();
String key = "key", value = "value";
cache.put(key, value);
@@ -164,8 +153,7 @@
assert 1 == cache.size();
}
- public void testRollbackAfterOverwrite() throws Exception
- {
+ public void testRollbackAfterOverwrite() throws Exception {
CacheSPI<String, String> cache = cacheTL.get();
String key = "key", value = "value";
cache.put(key, value);
@@ -182,8 +170,7 @@
assert 1 == cache.size();
}
- public void testRollbackAfterRemove() throws Exception
- {
+ public void testRollbackAfterRemove() throws Exception {
CacheSPI<String, String> cache = cacheTL.get();
String key = "key", value = "value";
cache.put(key, value);
@@ -199,8 +186,7 @@
assert 1 == cache.size();
}
- public void testRollbackAfterClear() throws Exception
- {
+ public void testRollbackAfterClear() throws Exception {
CacheSPI<String, String> cache = cacheTL.get();
String key = "key", value = "value";
cache.put(key, value);
Modified: core/branches/flat/src/test/java/org/horizon/api/CacheSPITest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/api/CacheSPITest.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/test/java/org/horizon/api/CacheSPITest.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -1,6 +1,7 @@
package org.horizon.api;
import org.horizon.CacheSPI;
+import org.horizon.UnitTestCacheFactory;
import org.horizon.config.Configuration;
import org.horizon.config.Configuration.CacheMode;
import org.horizon.util.TestingUtil;
@@ -11,17 +12,14 @@
import java.util.List;
import java.util.concurrent.TimeUnit;
-import org.horizon.UnitTestCacheFactory;
@Test(groups = {"functional", "pessimistic"})
-public class CacheSPITest
-{
+public class CacheSPITest {
private ThreadLocal<CacheSPI<Object, Object>> cache1TL = new ThreadLocal<CacheSPI<Object, Object>>();
private ThreadLocal<CacheSPI<Object, Object>> cache2TL = new ThreadLocal<CacheSPI<Object, Object>>();
@BeforeMethod(alwaysRun = true)
- public void setUp() throws Exception
- {
+ public void setUp() throws Exception {
Configuration conf1 = new Configuration();
conf1.setCacheMode(CacheMode.REPL_SYNC);
@@ -35,20 +33,18 @@
}
@AfterMethod(alwaysRun = true)
- public void tearDown() throws Exception
- {
+ public void tearDown() throws Exception {
CacheSPI<Object, Object> cache1 = cache1TL.get();
CacheSPI<Object, Object> cache2 = cache2TL.get();
TestingUtil.killCaches(cache1, cache2);
-
+
cache1TL.set(null);
cache2TL.set(null);
-
+
}
- public void testGetMembers() throws Exception
- {
+ public void testGetMembers() throws Exception {
CacheSPI<Object, Object> cache1 = cache1TL.get();
CacheSPI<Object, Object> cache2 = cache2TL.get();
@@ -72,8 +68,7 @@
assert !coord.equals(memb2.get(0));
}
- public void testIsCoordinator() throws Exception
- {
+ public void testIsCoordinator() throws Exception {
CacheSPI<Object, Object> cache1 = cache1TL.get();
CacheSPI<Object, Object> cache2 = cache2TL.get();
Modified: core/branches/flat/src/test/java/org/horizon/api/batch/AbstractBatchTest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/api/batch/AbstractBatchTest.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/test/java/org/horizon/api/batch/AbstractBatchTest.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -4,15 +4,11 @@
import java.util.concurrent.atomic.AtomicReference;
-public abstract class AbstractBatchTest
-{
- protected String getOnDifferentThread(final Cache<String, String> cache, final String key) throws InterruptedException
- {
+public abstract class AbstractBatchTest {
+ protected String getOnDifferentThread(final Cache<String, String> cache, final String key) throws InterruptedException {
final AtomicReference<String> ref = new AtomicReference<String>();
- Thread t = new Thread()
- {
- public void run()
- {
+ Thread t = new Thread() {
+ public void run() {
ref.set(cache.get(key));
}
};
Modified: core/branches/flat/src/test/java/org/horizon/api/batch/BatchWithTM.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/api/batch/BatchWithTM.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/test/java/org/horizon/api/batch/BatchWithTM.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -11,13 +11,10 @@
@Test(groups = {"functional", "transaction"})
-public class BatchWithTM extends AbstractBatchTest
-{
- public void testBatchWithOngoingTM() throws Exception
- {
+public class BatchWithTM extends AbstractBatchTest {
+ public void testBatchWithOngoingTM() throws Exception {
Cache<String, String> cache = null;
- try
- {
+ try {
cache = createCache();
TransactionManager tm = getTransactionManager(cache);
tm.begin();
@@ -33,17 +30,14 @@
assert "v".equals(cache.get("k"));
assert "v2".equals(cache.get("k2"));
}
- finally
- {
+ finally {
TestingUtil.killCaches(cache);
}
}
- public void testBatchWithoutOngoingTMSuspension() throws Exception
- {
+ public void testBatchWithoutOngoingTMSuspension() throws Exception {
Cache<String, String> cache = null;
- try
- {
+ try {
cache = createCache();
TransactionManager tm = getTransactionManager(cache);
assert tm.getTransaction() == null : "Should have no ongoing txs";
@@ -55,12 +49,10 @@
assert getOnDifferentThread(cache, "k") == null;
assert getOnDifferentThread(cache, "k2") == null;
- try
- {
+ try {
tm.commit(); // should have no effect
}
- catch (Exception e)
- {
+ catch (Exception e) {
// the TM may barf here ... this is OK.
}
@@ -74,17 +66,14 @@
assert "v".equals(getOnDifferentThread(cache, "k"));
assert "v2".equals(getOnDifferentThread(cache, "k2"));
}
- finally
- {
+ finally {
TestingUtil.killCaches(cache);
}
}
- public void testBatchRollback() throws Exception
- {
+ public void testBatchRollback() throws Exception {
Cache<String, String> cache = null;
- try
- {
+ try {
cache = createCache();
TransactionManager tm = getTransactionManager(cache);
cache.startBatch();
@@ -99,19 +88,16 @@
assert getOnDifferentThread(cache, "k") == null;
assert getOnDifferentThread(cache, "k2") == null;
}
- finally
- {
+ finally {
TestingUtil.killCaches(cache);
}
}
- private TransactionManager getTransactionManager(Cache<String, String> c)
- {
+ private TransactionManager getTransactionManager(Cache<String, String> c) {
return c.getConfiguration().getRuntimeConfig().getTransactionManager();
}
- private Cache<String, String> createCache()
- {
+ private Cache<String, String> createCache() {
UnitTestCacheFactory<String, String> cf = new UnitTestCacheFactory<String, String>();
Configuration c = new Configuration();
c.setTransactionManagerLookupClass(DummyTransactionManagerLookup.class.getName());
Modified: core/branches/flat/src/test/java/org/horizon/api/batch/BatchWithoutTM.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/api/batch/BatchWithoutTM.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/test/java/org/horizon/api/batch/BatchWithoutTM.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -8,71 +8,56 @@
import org.testng.annotations.Test;
@Test(groups = "functional")
-public class BatchWithoutTM extends AbstractBatchTest
-{
- public void testBatchWithoutCfg()
- {
+public class BatchWithoutTM extends AbstractBatchTest {
+ public void testBatchWithoutCfg() {
Cache<String, String> cache = null;
- try
- {
+ try {
cache = createCache(false);
- try
- {
+ try {
cache.startBatch();
assert false : "Should have failed";
}
- catch (ConfigurationException good)
- {
+ catch (ConfigurationException good) {
// do nothing
}
- try
- {
+ try {
cache.endBatch(true);
assert false : "Should have failed";
}
- catch (ConfigurationException good)
- {
+ catch (ConfigurationException good) {
// do nothing
}
- try
- {
+ try {
cache.endBatch(false);
assert false : "Should have failed";
}
- catch (ConfigurationException good)
- {
+ catch (ConfigurationException good) {
// do nothing
}
}
- finally
- {
+ finally {
TestingUtil.killCaches(cache);
}
}
- public void testEndBatchWithoutStartBatch()
- {
+ public void testEndBatchWithoutStartBatch() {
Cache<String, String> cache = null;
- try
- {
+ try {
cache = createCache(true);
cache.endBatch(true);
cache.endBatch(false);
// should not fail.
}
- finally
- {
+ finally {
TestingUtil.killCaches(cache);
}
}
- public void testStartBatchIdempotency()
- {
+ public void testStartBatchIdempotency() {
Cache<String, String> cache = null;
- try
- {
+ try {
cache = createCache(true);
cache.startBatch();
cache.put("k", "v");
@@ -83,17 +68,14 @@
assert "v".equals(cache.get("k"));
assert "v2".equals(cache.get("k2"));
}
- finally
- {
+ finally {
TestingUtil.killCaches(cache);
}
}
- public void testBatchVisibility() throws InterruptedException
- {
+ public void testBatchVisibility() throws InterruptedException {
Cache<String, String> cache = null;
- try
- {
+ try {
cache = createCache(true);
cache.startBatch();
cache.put("k", "v");
@@ -103,17 +85,14 @@
assert "v".equals(getOnDifferentThread(cache, "k"));
}
- finally
- {
+ finally {
TestingUtil.killCaches(cache);
}
}
- public void testBatchRollback() throws Exception
- {
+ public void testBatchRollback() throws Exception {
Cache<String, String> cache = null;
- try
- {
+ try {
cache = createCache(true);
cache.startBatch();
cache.put("k", "v");
@@ -127,14 +106,12 @@
assert getOnDifferentThread(cache, "k") == null;
assert getOnDifferentThread(cache, "k2") == null;
}
- finally
- {
+ finally {
TestingUtil.killCaches(cache);
}
}
- private Cache<String, String> createCache(boolean enableBatch)
- {
+ private Cache<String, String> createCache(boolean enableBatch) {
UnitTestCacheFactory<String, String> cf = new UnitTestCacheFactory<String, String>();
Configuration c = new Configuration();
c.setInvocationBatchingEnabled(enableBatch);
Modified: core/branches/flat/src/test/java/org/horizon/api/mvcc/LockAssert.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/api/mvcc/LockAssert.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/test/java/org/horizon/api/mvcc/LockAssert.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -10,23 +10,19 @@
*
* @author Manik Surtani (<a href="mailto:manik at jboss.org">manik at jboss.org</a>)
*/
-public class LockAssert
-{
- public static void assertLocked(Object key, LockManager lockManager, InvocationContextContainer icc)
- {
+public class LockAssert {
+ public static void assertLocked(Object key, LockManager lockManager, InvocationContextContainer icc) {
assert lockManager.isLocked(key) : key + " not locked!";
// assert icc.get().getKeysLocked().contains(key) : "Lock not recorded for " + key;
}
- public static void assertNotLocked(Object key, InvocationContextContainer icc)
- {
+ public static void assertNotLocked(Object key, InvocationContextContainer icc) {
// can't rely on the negative test since other nodes may share the same lock with lock striping.
// assert !lockManager.isLocked(fqn) : fqn + " is locked!";
assert !icc.get().getKeysLocked().contains(key) : key + " lock recorded!";
}
- public static void assertNoLocks(LockManager lockManager, InvocationContextContainer icc)
- {
+ public static void assertNoLocks(LockManager lockManager, InvocationContextContainer icc) {
LockContainer lc = (LockContainer) TestingUtil.extractField(lockManager, "lockContainer");
assert lc.getNumLocksHeld() == 0 : "Stale locks exist! NumLocksHeld is " + lc.getNumLocksHeld() + " and lock info is " + lockManager.printLockInfo();
assert icc.get().getKeysLocked().isEmpty() : "Stale (?) locks recorded! " + icc.get().getKeysLocked();
Modified: core/branches/flat/src/test/java/org/horizon/api/mvcc/LockTestBase.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/api/mvcc/LockTestBase.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/test/java/org/horizon/api/mvcc/LockTestBase.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -2,11 +2,11 @@
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
-import org.horizon.lock.IsolationLevel;
import org.horizon.Cache;
import org.horizon.UnitTestCacheFactory;
import org.horizon.config.Configuration;
import org.horizon.invocation.InvocationContextContainer;
+import org.horizon.lock.IsolationLevel;
import org.horizon.lock.LockManager;
import org.horizon.lock.TimeoutException;
import org.horizon.transaction.DummyTransactionManagerLookup;
@@ -23,14 +23,12 @@
* @author Manik Surtani (<a href="mailto:manik at jboss.org">manik at jboss.org</a>)
*/
@Test(groups = {"functional", "mvcc"})
-public abstract class LockTestBase
-{
+public abstract class LockTestBase {
protected boolean repeatableRead = true;
protected boolean lockParentForChildInsertRemove = false;
private Log log = LogFactory.getLog(LockTestBase.class);
- protected class LockTestBaseTL
- {
+ protected class LockTestBaseTL {
public Cache<String, String> cache;
public TransactionManager tm;
public LockManager lockManager;
@@ -41,8 +39,7 @@
@BeforeMethod
- public void setUp()
- {
+ public void setUp() {
LockTestBaseTL tl = new LockTestBaseTL();
tl.cache = new UnitTestCacheFactory<String, String>().createCache(new Configuration(), false);
tl.cache.getConfiguration().setTransactionManagerLookupClass(DummyTransactionManagerLookup.class.getName());
@@ -58,34 +55,29 @@
}
@AfterMethod
- public void tearDown()
- {
+ public void tearDown() {
LockTestBaseTL tl = threadLocal.get();
log.debug("**** - STARTING TEARDOWN - ****");
TestingUtil.killCaches(tl.cache);
threadLocal.set(null);
}
- protected void assertLocked(Object key)
- {
+ protected void assertLocked(Object key) {
LockTestBaseTL tl = threadLocal.get();
LockAssert.assertLocked(key, tl.lockManager, tl.icc);
}
- protected void assertNotLocked(Object key)
- {
+ protected void assertNotLocked(Object key) {
LockTestBaseTL tl = threadLocal.get();
LockAssert.assertNotLocked(key, tl.icc);
}
- protected void assertNoLocks()
- {
+ protected void assertNoLocks() {
LockTestBaseTL tl = threadLocal.get();
LockAssert.assertNoLocks(tl.lockManager, tl.icc);
}
- public void testLocksOnPutKeyVal() throws Exception
- {
+ public void testLocksOnPutKeyVal() throws Exception {
LockTestBaseTL tl = threadLocal.get();
Cache<String, String> cache = tl.cache;
TransactionManager tm = tl.tm;
@@ -111,8 +103,7 @@
assertNoLocks();
}
- public void testLocksOnPutData() throws Exception
- {
+ public void testLocksOnPutData() throws Exception {
LockTestBaseTL tl = threadLocal.get();
Cache<String, String> cache = tl.cache;
TransactionManager tm = tl.tm;
@@ -132,8 +123,7 @@
assertNoLocks();
}
- public void testLocksOnEvictNode() throws Exception
- {
+ public void testLocksOnEvictNode() throws Exception {
LockTestBaseTL tl = threadLocal.get();
Cache<String, String> cache = tl.cache;
TransactionManager tm = tl.tm;
@@ -150,8 +140,7 @@
assertNoLocks();
}
- public void testLocksOnRemoveNonexistentNode() throws Exception
- {
+ public void testLocksOnRemoveNonexistentNode() throws Exception {
LockTestBaseTL tl = threadLocal.get();
Cache<String, String> cache = tl.cache;
TransactionManager tm = tl.tm;
@@ -165,8 +154,7 @@
assertNoLocks();
}
- public void testLocksOnEvictNonexistentNode() throws Exception
- {
+ public void testLocksOnEvictNonexistentNode() throws Exception {
LockTestBaseTL tl = threadLocal.get();
Cache<String, String> cache = tl.cache;
TransactionManager tm = tl.tm;
@@ -180,8 +168,7 @@
assertNoLocks();
}
- public void testLocksOnRemoveData() throws Exception
- {
+ public void testLocksOnRemoveData() throws Exception {
LockTestBaseTL tl = threadLocal.get();
Cache<String, String> cache = tl.cache;
TransactionManager tm = tl.tm;
@@ -203,8 +190,7 @@
assertNoLocks();
}
- public void testWriteDoesntBlockRead() throws Exception
- {
+ public void testWriteDoesntBlockRead() throws Exception {
LockTestBaseTL tl = threadLocal.get();
Cache<String, String> cache = tl.cache;
TransactionManager tm = tl.tm;
@@ -237,8 +223,7 @@
assertNoLocks();
}
- public void testWriteDoesntBlockReadNonexistent() throws Exception
- {
+ public void testWriteDoesntBlockReadNonexistent() throws Exception {
LockTestBaseTL tl = threadLocal.get();
Cache<String, String> cache = tl.cache;
TransactionManager tm = tl.tm;
@@ -260,20 +245,16 @@
assertNoLocks();
tm.resume(read);
- if (repeatableRead)
- {
+ if (repeatableRead) {
assert null == cache.get("k") : "Should have repeatable read";
- }
- else
- {
+ } else {
assert "v".equals(cache.get("k")) : "Read committed should see committed changes";
}
tm.commit();
assertNoLocks();
}
- public void testConcurrentWriters() throws Exception
- {
+ public void testConcurrentWriters() throws Exception {
LockTestBaseTL tl = threadLocal.get();
Cache<String, String> cache = tl.cache;
TransactionManager tm = tl.tm;
@@ -282,13 +263,11 @@
Transaction t1 = tm.suspend();
tm.begin();
- try
- {
+ try {
cache.put("k", "v");
assert false : "Should fail lock acquisition";
}
- catch (TimeoutException expected)
- {
+ catch (TimeoutException expected) {
// expected.printStackTrace(); // for debugging
}
tm.commit();
@@ -297,8 +276,7 @@
assertNoLocks();
}
- public void testRollbacks() throws Exception
- {
+ public void testRollbacks() throws Exception {
LockTestBaseTL tl = threadLocal.get();
Cache<String, String> cache = tl.cache;
TransactionManager tm = tl.tm;
@@ -321,8 +299,7 @@
assertNoLocks();
}
- public void testRollbacksOnNullNode() throws Exception
- {
+ public void testRollbacksOnNullNode() throws Exception {
LockTestBaseTL tl = threadLocal.get();
Cache<String, String> cache = tl.cache;
TransactionManager tm = tl.tm;
Modified: core/branches/flat/src/test/java/org/horizon/api/mvcc/PutForExternalReadTest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/api/mvcc/PutForExternalReadTest.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/test/java/org/horizon/api/mvcc/PutForExternalReadTest.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -11,8 +11,8 @@
import org.horizon.config.Configuration;
import org.horizon.factories.ComponentRegistry;
import org.horizon.remoting.RPCManager;
-import org.horizon.transaction.TransactionTable;
import org.horizon.transaction.DummyTransactionManagerLookup;
+import org.horizon.transaction.TransactionTable;
import org.horizon.util.TestingUtil;
import org.horizon.util.internals.ReplicationListener;
import org.jgroups.Address;
@@ -27,8 +27,7 @@
import java.util.Vector;
@Test(groups = {"functional", "jgroups", "transaction"})
-public class PutForExternalReadTest
-{
+public class PutForExternalReadTest {
protected final String key = "k", value = "v", value2 = "v2";
protected CacheSPI<String, String> cache1, cache2;
@@ -42,8 +41,7 @@
@BeforeMethod(alwaysRun = true)
- public void setUp()
- {
+ public void setUp() {
UnitTestCacheFactory<String, String> cf = new UnitTestCacheFactory<String, String>();
Configuration c = new Configuration();
@@ -65,13 +63,11 @@
}
@AfterMethod(alwaysRun = true)
- public void tearDown()
- {
+ public void tearDown() {
TestingUtil.killCaches(cache1, cache2);
}
- public void testNoOpWhenKeyPresent()
- {
+ public void testNoOpWhenKeyPresent() {
replListener2.expect(PutKeyValueCommand.class);
cache1.putForExternalRead(key, value);
replListener2.waitForReplicationToOccur();
@@ -99,14 +95,12 @@
assertEquals("PFER should have been a no-op", value, cache2.get(key));
}
- private Vector<Address> anyAddresses()
- {
+ private Vector<Address> anyAddresses() {
anyObject();
return null;
}
- public void testAsyncForce() throws Exception
- {
+ public void testAsyncForce() throws Exception {
RPCManager rpcManager = EasyMock.createNiceMock(RPCManager.class);
RPCManager originalRpcManager = cache1.getConfiguration().getRuntimeConfig().getRPCManager();
List<Address> memberList = originalRpcManager.getMembers();
@@ -131,8 +125,7 @@
cache1.remove(key);
}
- public void testTxSuspension() throws Exception
- {
+ public void testTxSuspension() throws Exception {
// create parent node first
replListener2.expect(PutKeyValueCommand.class);
cache1.put(key + "0", value);
@@ -156,12 +149,10 @@
assertEquals("parent fqn tx should have completed", value, cache2.get(key + "0"));
}
- public void testExceptionSuppression() throws Exception
- {
+ public void testExceptionSuppression() throws Exception {
RPCManager barfingRpcManager = EasyMock.createNiceMock(RPCManager.class);
RPCManager originalRpcManager = cache1.getConfiguration().getRuntimeConfig().getRPCManager();
- try
- {
+ try {
List<Address> memberList = originalRpcManager.getMembers();
expect(barfingRpcManager.getMembers()).andReturn(memberList).anyTimes();
expect(barfingRpcManager.getLocalAddress()).andReturn(originalRpcManager.getLocalAddress()).anyTimes();
@@ -172,23 +163,19 @@
cache1.getConfiguration().getRuntimeConfig().setRPCManager(barfingRpcManager);
TestingUtil.extractComponentRegistry(cache1).rewire();
- try
- {
+ try {
cache1.put(key, value);
fail("Should have barfed");
}
- catch (RuntimeException re)
- {
+ catch (RuntimeException re) {
}
// clean up any indeterminate state left over
- try
- {
+ try {
cache1.remove(key);
fail("Should have barfed");
}
- catch (RuntimeException re)
- {
+ catch (RuntimeException re) {
}
assertNull("Should have cleaned up", cache1.get(key));
@@ -196,14 +183,12 @@
// should not barf
cache1.putForExternalRead(key, value);
}
- finally
- {
+ finally {
TestingUtil.extractComponentRegistry(cache1).registerComponent(originalRpcManager, RPCManager.class);
}
}
- public void testBasicPropagation() throws Exception
- {
+ public void testBasicPropagation() throws Exception {
assert !cache1.containsKey(key);
assert !cache2.containsKey(key);
@@ -222,37 +207,32 @@
}
/**
- * Tests that setting a cacheModeLocal=true Option prevents propagation
- * of the putForExternalRead().
+ * Tests that setting a cacheModeLocal=true Option prevents propagation of the putForExternalRead().
*
* @throws Exception
*/
- public void testSimpleCacheModeLocal() throws Exception
- {
+ public void testSimpleCacheModeLocal() throws Exception {
cacheModeLocalTest(false);
}
/**
- * Tests that setting a cacheModeLocal=true Option prevents propagation
- * of the putForExternalRead() when the call occurs inside a transaction.
+ * Tests that setting a cacheModeLocal=true Option prevents propagation of the putForExternalRead() when the call
+ * occurs inside a transaction.
*
* @throws Exception
*/
- public void testCacheModeLocalInTx() throws Exception
- {
+ public void testCacheModeLocalInTx() throws Exception {
cacheModeLocalTest(true);
}
- private TransactionTable getTransactionTable(Cache cache)
- {
+ private TransactionTable getTransactionTable(Cache cache) {
return TestingUtil.extractComponent(cache, TransactionTable.class);
}
/**
* Tests that suspended transactions do not leak. See JBCACHE-1246.
*/
- public void testMemLeakOnSuspendedTransactions() throws Exception
- {
+ public void testMemLeakOnSuspendedTransactions() throws Exception {
replListener2.expect(PutKeyValueCommand.class);
tm1.begin();
cache1.putForExternalRead(key, value);
@@ -309,13 +289,11 @@
}
/**
- * Tests that setting a cacheModeLocal=true Option prevents propagation
- * of the putForExternalRead().
+ * Tests that setting a cacheModeLocal=true Option prevents propagation of the putForExternalRead().
*
* @throws Exception
*/
- private void cacheModeLocalTest(boolean transactional) throws Exception
- {
+ private void cacheModeLocalTest(boolean transactional) throws Exception {
RPCManager rpcManager = EasyMock.createMock(RPCManager.class);
RPCManager originalRpcManager = cache1.getConfiguration().getRuntimeConfig().getRPCManager();
Modified: core/branches/flat/src/test/java/org/horizon/api/mvcc/read_committed/CacheAPIMVCCTest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/api/mvcc/read_committed/CacheAPIMVCCTest.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/test/java/org/horizon/api/mvcc/read_committed/CacheAPIMVCCTest.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -1,15 +1,13 @@
package org.horizon.api.mvcc.read_committed;
-import org.horizon.lock.IsolationLevel;
import org.horizon.api.CacheAPITest;
+import org.horizon.lock.IsolationLevel;
import org.testng.annotations.Test;
@Test(groups = "functional")
-public class CacheAPIMVCCTest extends CacheAPITest
-{
+public class CacheAPIMVCCTest extends CacheAPITest {
@Override
- protected IsolationLevel getIsolationLevel()
- {
+ protected IsolationLevel getIsolationLevel() {
return IsolationLevel.READ_COMMITTED;
}
}
\ No newline at end of file
Modified: core/branches/flat/src/test/java/org/horizon/api/mvcc/read_committed/ReadCommittedLockTest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/api/mvcc/read_committed/ReadCommittedLockTest.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/test/java/org/horizon/api/mvcc/read_committed/ReadCommittedLockTest.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -7,15 +7,12 @@
import javax.transaction.Transaction;
@Test(groups = {"functional", "mvcc"})
-public class ReadCommittedLockTest extends LockTestBase
-{
- public ReadCommittedLockTest()
- {
+public class ReadCommittedLockTest extends LockTestBase {
+ public ReadCommittedLockTest() {
repeatableRead = false;
}
- public void testVisibilityOfCommittedDataPut() throws Exception
- {
+ public void testVisibilityOfCommittedDataPut() throws Exception {
Cache c = threadLocal.get().cache;
c.put("k", "v");
@@ -43,8 +40,7 @@
threadLocal.get().tm.commit();
}
- public void testVisibilityOfCommittedDataReplace() throws Exception
- {
+ public void testVisibilityOfCommittedDataReplace() throws Exception {
Cache c = threadLocal.get().cache;
c.put("k", "v");
Modified: core/branches/flat/src/test/java/org/horizon/api/mvcc/repeatable_read/CacheAPIMVCCTest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/api/mvcc/repeatable_read/CacheAPIMVCCTest.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/test/java/org/horizon/api/mvcc/repeatable_read/CacheAPIMVCCTest.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -1,15 +1,13 @@
package org.horizon.api.mvcc.repeatable_read;
-import org.horizon.lock.IsolationLevel;
import org.horizon.api.CacheAPITest;
+import org.horizon.lock.IsolationLevel;
import org.testng.annotations.Test;
@Test(groups = "functional")
-public class CacheAPIMVCCTest extends CacheAPITest
-{
+public class CacheAPIMVCCTest extends CacheAPITest {
@Override
- protected IsolationLevel getIsolationLevel()
- {
+ protected IsolationLevel getIsolationLevel() {
return IsolationLevel.REPEATABLE_READ;
}
}
\ No newline at end of file
Modified: core/branches/flat/src/test/java/org/horizon/api/mvcc/repeatable_read/RepeatableReadLockTest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/api/mvcc/repeatable_read/RepeatableReadLockTest.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/test/java/org/horizon/api/mvcc/repeatable_read/RepeatableReadLockTest.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -1,22 +1,19 @@
package org.horizon.api.mvcc.repeatable_read;
+import org.horizon.Cache;
import org.horizon.api.mvcc.LockTestBase;
import org.testng.annotations.Test;
import javax.transaction.Transaction;
import javax.transaction.TransactionManager;
-import org.horizon.Cache;
@Test(groups = {"functional", "mvcc"})
-public class RepeatableReadLockTest extends LockTestBase
-{
- public RepeatableReadLockTest()
- {
+public class RepeatableReadLockTest extends LockTestBase {
+ public RepeatableReadLockTest() {
repeatableRead = true;
}
- public void testRepeatableReadWithRemove() throws Exception
- {
+ public void testRepeatableReadWithRemove() throws Exception {
LockTestBaseTL tl = threadLocal.get();
Cache<String, String> cache = tl.cache;
TransactionManager tm = tl.tm;
@@ -42,8 +39,7 @@
assertNoLocks();
}
- public void testRepeatableReadWithEvict() throws Exception
- {
+ public void testRepeatableReadWithEvict() throws Exception {
LockTestBaseTL tl = threadLocal.get();
Cache<String, String> cache = tl.cache;
TransactionManager tm = tl.tm;
@@ -70,8 +66,7 @@
assertNoLocks();
}
- public void testRepeatableReadWithNull() throws Exception
- {
+ public void testRepeatableReadWithNull() throws Exception {
LockTestBaseTL tl = threadLocal.get();
Cache<String, String> cache = tl.cache;
TransactionManager tm = tl.tm;
Modified: core/branches/flat/src/test/java/org/horizon/api/mvcc/repeatable_read/WriteSkewTest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/api/mvcc/repeatable_read/WriteSkewTest.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/test/java/org/horizon/api/mvcc/repeatable_read/WriteSkewTest.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -1,11 +1,11 @@
package org.horizon.api.mvcc.repeatable_read;
-import org.horizon.lock.IsolationLevel;
import org.horizon.Cache;
import org.horizon.UnitTestCacheFactory;
import org.horizon.api.mvcc.LockAssert;
import org.horizon.config.Configuration;
import org.horizon.invocation.InvocationContextContainer;
+import org.horizon.lock.IsolationLevel;
import org.horizon.lock.LockManager;
import org.horizon.transaction.DummyTransactionManagerLookup;
import org.horizon.util.TestingUtil;
@@ -21,8 +21,7 @@
import java.util.concurrent.CountDownLatch;
@Test(groups = {"functional", "mvcc"}, sequential = true)
-public class WriteSkewTest
-{
+public class WriteSkewTest {
protected Cache<String, String> cache;
protected TransactionManager tm;
protected LockManager lockManager;
@@ -30,8 +29,7 @@
protected boolean repeatableRead = true;
@BeforeMethod
- public void setUp()
- {
+ public void setUp() {
cache = new UnitTestCacheFactory<String, String>().createCache(new Configuration(), false);
cache.getConfiguration().setTransactionManagerLookupClass(DummyTransactionManagerLookup.class.getName());
cache.getConfiguration().setIsolationLevel(repeatableRead ? IsolationLevel.REPEATABLE_READ : IsolationLevel.READ_COMMITTED);
@@ -40,43 +38,36 @@
}
@AfterMethod
- public void tearDown()
- {
+ public void tearDown() {
TestingUtil.killCaches(cache);
}
- private void postStart()
- {
+ private void postStart() {
lockManager = TestingUtil.extractComponentRegistry(cache).getComponent(LockManager.class);
icc = TestingUtil.extractComponentRegistry(cache).getComponent(InvocationContextContainer.class);
tm = TestingUtil.extractComponentRegistry(cache).getComponent(TransactionManager.class);
}
- protected void assertNoLocks()
- {
+ protected void assertNoLocks() {
LockAssert.assertNoLocks(lockManager, icc);
}
- public void testDontCheckWriteSkew() throws Exception
- {
+ public void testDontCheckWriteSkew() throws Exception {
cache.getConfiguration().setWriteSkewCheck(false);
cache.start();
postStart();
doTest(true);
}
- public void testCheckWriteSkew() throws Exception
- {
+ public void testCheckWriteSkew() throws Exception {
cache.getConfiguration().setWriteSkewCheck(true);
cache.start();
postStart();
doTest(false);
}
- private void doTest(final boolean allowWriteSkew) throws Exception
- {
- if (repeatableRead)
- {
+ private void doTest(final boolean allowWriteSkew) throws Exception {
+ if (repeatableRead) {
cache.put("k", "v");
final Set<Exception> w1exceptions = new HashSet<Exception>();
final Set<Exception> w2exceptions = new HashSet<Exception>();
@@ -84,13 +75,10 @@
final CountDownLatch w2Signal = new CountDownLatch(1);
final CountDownLatch threadSignal = new CountDownLatch(2);
- Thread w1 = new Thread("Writer-1")
- {
- public void run()
- {
+ Thread w1 = new Thread("Writer-1") {
+ public void run() {
boolean didCoundDown = false;
- try
- {
+ try {
tm.begin();
assert "v".equals(cache.get("k"));
threadSignal.countDown();
@@ -99,24 +87,19 @@
cache.put("k", "v2");
tm.commit();
}
- catch (Exception e)
- {
+ catch (Exception e) {
w1exceptions.add(e);
}
- finally
- {
+ finally {
if (!didCoundDown) threadSignal.countDown();
}
}
};
- Thread w2 = new Thread("Writer-2")
- {
- public void run()
- {
+ Thread w2 = new Thread("Writer-2") {
+ public void run() {
boolean didCoundDown = false;
- try
- {
+ try {
tm.begin();
assert "v".equals(cache.get("k"));
threadSignal.countDown();
@@ -125,24 +108,19 @@
cache.put("k", "v3");
tm.commit();
}
- catch (Exception e)
- {
+ catch (Exception e) {
w2exceptions.add(e);
// the exception will be thrown when doing a cache.put(). We should make sure we roll back the tx to release locks.
- if (!allowWriteSkew)
- {
- try
- {
+ if (!allowWriteSkew) {
+ try {
tm.rollback();
}
- catch (SystemException e1)
- {
+ catch (SystemException e1) {
// do nothing.
}
}
}
- finally
- {
+ finally {
if (!didCoundDown) threadSignal.countDown();
}
}
@@ -160,16 +138,13 @@
w2Signal.countDown();
w2.join();
- if (allowWriteSkew)
- {
+ if (allowWriteSkew) {
// should have no exceptions!!
throwExceptions(w1exceptions, w2exceptions);
assert w2exceptions.size() == 0;
assert w1exceptions.size() == 0;
assert "v3".equals(cache.get("k")) : "W2 should have overwritten W1's work!";
- }
- else
- {
+ } else {
// there should be a single exception from w2.
assert w2exceptions.size() == 1;
throwExceptions(w1exceptions);
@@ -181,10 +156,8 @@
}
}
- private void throwExceptions(Collection<Exception>... exceptions) throws Exception
- {
- for (Collection<Exception> ce : exceptions)
- {
+ private void throwExceptions(Collection<Exception>... exceptions) throws Exception {
+ for (Collection<Exception> ce : exceptions) {
for (Exception e : ce) throw e;
}
}
Modified: core/branches/flat/src/test/java/org/horizon/api/tree/NodeAPITest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/api/tree/NodeAPITest.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/test/java/org/horizon/api/tree/NodeAPITest.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -27,8 +27,7 @@
* @author <a href="mailto:manik AT jboss DOT org">Manik Surtani</a>
*/
@Test(groups = "functional")
-public class NodeAPITest
-{
+public class NodeAPITest {
protected ThreadLocal<TreeCache<Object, Object>> cacheTL = new ThreadLocal<TreeCache<Object, Object>>();
protected static final Fqn A = Fqn.fromString("/a"), B = Fqn.fromString("/b"), C = Fqn.fromString("/c"), D = Fqn.fromString("/d");
protected Fqn A_B = Fqn.fromRelativeFqn(A, B);
@@ -36,8 +35,7 @@
protected TransactionManager tm;
@BeforeMethod(alwaysRun = true)
- public void setUp() throws Exception
- {
+ public void setUp() throws Exception {
// start a single cache instance
Configuration c = new Configuration();
c.setTransactionManagerLookupClass(DummyTransactionManagerLookup.class.getName());
@@ -49,15 +47,13 @@
}
@AfterMethod(alwaysRun = true)
- public void tearDown()
- {
+ public void tearDown() {
TreeCache<Object, Object> cache = cacheTL.get();
TestingUtil.killTreeCaches(cache);
cacheTL.set(null);
}
- public void testAddingData()
- {
+ public void testAddingData() {
TreeCache<Object, Object> cache = cacheTL.get();
Node<Object, Object> rootNode = cache.getRoot();
Node<Object, Object> nodeA = rootNode.addChild(A);
@@ -66,8 +62,7 @@
assertEquals("value", nodeA.get("key"));
}
- public void testAddingDataTx() throws Exception
- {
+ public void testAddingDataTx() throws Exception {
TreeCache<Object, Object> cache = cacheTL.get();
Node<Object, Object> rootNode = cache.getRoot();
tm.begin();
@@ -78,8 +73,7 @@
tm.commit();
}
- public void testOverwritingDataTx() throws Exception
- {
+ public void testOverwritingDataTx() throws Exception {
TreeCache<Object, Object> cache = cacheTL.get();
Node<Object, Object> rootNode = cache.getRoot();
@@ -98,8 +92,7 @@
/**
* Remember, Fqns are relative!!
*/
- public void testParentsAndChildren()
- {
+ public void testParentsAndChildren() {
TreeCache<Object, Object> cache = cacheTL.get();
Node<Object, Object> rootNode = cache.getRoot();
@@ -144,36 +137,30 @@
}
- public void testImmutabilityOfData()
- {
+ public void testImmutabilityOfData() {
TreeCache<Object, Object> cache = cacheTL.get();
Node<Object, Object> rootNode = cache.getRoot();
rootNode.put("key", "value");
Map<Object, Object> m = rootNode.getData();
- try
- {
+ try {
m.put("x", "y");
fail("Map should be immutable!!");
}
- catch (Exception e)
- {
+ catch (Exception e) {
// expected
}
- try
- {
+ try {
rootNode.getKeys().add(new Object());
fail("Key set should be immutable");
}
- catch (Exception e)
- {
+ catch (Exception e) {
// expected
}
}
- public void testDefensiveCopyOfData()
- {
+ public void testDefensiveCopyOfData() {
TreeCache<Object, Object> cache = cacheTL.get();
Node<Object, Object> rootNode = cache.getRoot();
@@ -199,8 +186,7 @@
assert data.containsKey("key");
}
- public void testDefensiveCopyOfChildren()
- {
+ public void testDefensiveCopyOfChildren() {
TreeCache<Object, Object> cache = cacheTL.get();
Node<Object, Object> rootNode = cache.getRoot();
@@ -228,26 +214,22 @@
}
- public void testImmutabilityOfChildren()
- {
+ public void testImmutabilityOfChildren() {
TreeCache<Object, Object> cache = cacheTL.get();
Node<Object, Object> rootNode = cache.getRoot();
rootNode.addChild(A);
- try
- {
+ try {
rootNode.getChildren().clear();
fail("Collection of child nodes returned in getChildren() should be immutable");
}
- catch (Exception e)
- {
+ catch (Exception e) {
// expected
}
}
- public void testGetChildAPI()
- {
+ public void testGetChildAPI() {
TreeCache<Object, Object> cache = cacheTL.get();
Node<Object, Object> rootNode = cache.getRoot();
@@ -266,8 +248,7 @@
assertNull(rootNode.getChild(Fqn.fromElements("nonexistent")));
}
- public void testClearingData()
- {
+ public void testClearingData() {
TreeCache<Object, Object> cache = cacheTL.get();
Node<Object, Object> rootNode = cache.getRoot();
@@ -279,8 +260,7 @@
assertTrue(rootNode.getData().isEmpty());
}
- public void testClearingDataTx() throws Exception
- {
+ public void testClearingDataTx() throws Exception {
TreeCache<Object, Object> cache = cacheTL.get();
Node<Object, Object> rootNode = cache.getRoot();
@@ -295,8 +275,7 @@
assertTrue(rootNode.getData().isEmpty());
}
- public void testPutData()
- {
+ public void testPutData() {
TreeCache<Object, Object> cache = cacheTL.get();
Node<Object, Object> rootNode = cache.getRoot();
@@ -331,8 +310,7 @@
assertEquals("v5", rootNode.get("k5"));
}
- public void testGetChildrenNames() throws Exception
- {
+ public void testGetChildrenNames() throws Exception {
TreeCache<Object, Object> cache = cacheTL.get();
Node<Object, Object> rootNode = cache.getRoot();
@@ -355,8 +333,7 @@
assertEquals(childrenNames, rootNode.getChildrenNames());
}
- public void testDoubleRemovalOfData() throws Exception
- {
+ public void testDoubleRemovalOfData() throws Exception {
TreeCache<Object, Object> cache = cacheTL.get();
assert DummyTransactionManager.getInstance().getTransaction() == null;
@@ -378,8 +355,7 @@
assertNull(cache.get("/foo/1", "item"));
}
- public void testDoubleRemovalOfData2() throws Exception
- {
+ public void testDoubleRemovalOfData2() throws Exception {
TreeCache<Object, Object> cache = cacheTL.get();
cache.put("/foo/1/2", "item", 1);
Modified: core/branches/flat/src/test/java/org/horizon/api/tree/NodeLockSupport.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/api/tree/NodeLockSupport.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/test/java/org/horizon/api/tree/NodeLockSupport.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -32,8 +32,7 @@
import javax.transaction.TransactionManager;
-public abstract class NodeLockSupport
-{
+public abstract class NodeLockSupport {
static final Fqn A = Fqn.fromString("/a"), B = Fqn.fromString("/b"), C = Fqn.fromString("/c"), D = Fqn.fromString("/d"), E = Fqn.fromString("/e");
static final Object k = "key", vA = "valueA", vB = "valueB", vC = "valueC", vD = "valueD", vE = "valueE";
static final Fqn A_B = Fqn.fromRelativeFqn(A, B);
@@ -48,8 +47,7 @@
protected ThreadLocal<TransactionManager> tmTL = new ThreadLocal<TransactionManager>();
protected ThreadLocal<TreeCache> treeCacheTL = new ThreadLocal<TreeCache>();
- protected void checkLocks()
- {
+ protected void checkLocks() {
Cache<Object, Object> cache = cacheTL.get();
assert !TreeStructureSupport.isLocked(cache, A);
@@ -59,8 +57,7 @@
assert TreeStructureSupport.isLocked(cache, A_B_C);
}
- protected void checkLocksDeep()
- {
+ protected void checkLocksDeep() {
Cache<Object, Object> cache = cacheTL.get();
assert !TreeStructureSupport.isLocked(cache, A);
@@ -74,8 +71,7 @@
assert TreeStructureSupport.isLocked(cache, A_B_C_E);
}
- protected void assertNoLocks()
- {
+ protected void assertNoLocks() {
Cache<Object, Object> cache = cacheTL.get();
LockManager lm = ((CacheSPI) cache).getLockManager();
for (Object key : cache.keySet()) assert !lm.isLocked(key);
Modified: core/branches/flat/src/test/java/org/horizon/api/tree/NodeMoveAPITest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/api/tree/NodeMoveAPITest.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/test/java/org/horizon/api/tree/NodeMoveAPITest.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -2,7 +2,6 @@
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
-import org.horizon.tree.NodeNotExistsException;
import org.horizon.Cache;
import org.horizon.CacheSPI;
import org.horizon.UnitTestCacheFactory;
@@ -14,7 +13,12 @@
import org.horizon.factories.ComponentRegistry;
import org.horizon.invocation.InvocationContextContainer;
import org.horizon.lock.LockManager;
-import org.horizon.tree.*;
+import org.horizon.tree.Fqn;
+import org.horizon.tree.Node;
+import org.horizon.tree.NodeNotExistsException;
+import org.horizon.tree.TreeCache;
+import org.horizon.tree.TreeCacheImpl;
+import org.horizon.tree.TreeStructureSupport;
import org.horizon.util.TestingUtil;
import static org.testng.AssertJUnit.*;
import org.testng.annotations.AfterMethod;
@@ -32,8 +36,7 @@
* @author <a href="mailto:manik AT jboss DOT org">Manik Surtani</a>
*/
@Test(groups = {"functional", "pessimistic"}, testName = "api.NodeMoveAPITest")
-public class NodeMoveAPITest
-{
+public class NodeMoveAPITest {
protected final Log log = LogFactory.getLog(getClass());
protected static final Fqn A = Fqn.fromString("/a"), B = Fqn.fromString("/b"), C = Fqn.fromString("/c"), D = Fqn.fromString("/d"), E = Fqn.fromString("/e");
@@ -50,8 +53,7 @@
protected ThreadLocal<TransactionManager> tmTL = new ThreadLocal<TransactionManager>();
@BeforeMethod(alwaysRun = true)
- public void setUp() throws Exception
- {
+ public void setUp() throws Exception {
// start a single cache instance
Configuration c = new Configuration();
c.setFetchInMemoryState(false);
@@ -63,14 +65,12 @@
}
@AfterMethod(alwaysRun = true)
- public void tearDown()
- {
+ public void tearDown() {
TestingUtil.killTreeCaches(cacheTL.get());
cacheTL.set(null);
}
- public void testBasicMove()
- {
+ public void testBasicMove() {
TreeCache<Object, Object> cache = cacheTL.get();
TransactionManager tm = tmTL.get();
Node<Object, Object> rootNode = cache.getRoot();
@@ -132,13 +132,11 @@
}
@SuppressWarnings("unchecked")
- private Node<Object, Object> genericize(Node node)
- {
+ private Node<Object, Object> genericize(Node node) {
return (Node<Object, Object>) node;
}
- public void testMoveWithChildren()
- {
+ public void testMoveWithChildren() {
TreeCache<Object, Object> cache = cacheTL.get();
TransactionManager tm = tmTL.get();
Node<Object, Object> rootNode = cache.getRoot();
@@ -209,8 +207,7 @@
assertEquals(nodeD, nodeE.getParent());
}
- public void testTxCommit() throws Exception
- {
+ public void testTxCommit() throws Exception {
TreeCache<Object, Object> cache = cacheTL.get();
TransactionManager tm = tmTL.get();
Node<Object, Object> rootNode = cache.getRoot();
@@ -240,8 +237,7 @@
assertTrue(nodeA.getChildren().isEmpty());
}
- public void testTxRollback() throws Exception
- {
+ public void testTxRollback() throws Exception {
TreeCache<Object, Object> cache = cacheTL.get();
TransactionManager tm = tmTL.get();
Node<Object, Object> rootNode = cache.getRoot();
@@ -378,8 +374,7 @@
}
*/
- public void testLocksDeepMove() throws Exception
- {
+ public void testLocksDeepMove() throws Exception {
TreeCache<Object, Object> cache = cacheTL.get();
TransactionManager tm = tmTL.get();
Node<Object, Object> rootNode = cache.getRoot();
@@ -402,8 +397,7 @@
assertNoLocks();
}
- public void testLocks() throws Exception
- {
+ public void testLocks() throws Exception {
TreeCache<Object, Object> cache = cacheTL.get();
TransactionManager tm = tmTL.get();
Node<Object, Object> rootNode = cache.getRoot();
@@ -422,8 +416,7 @@
assertNoLocks();
}
- public void testConcurrency() throws InterruptedException
- {
+ public void testConcurrency() throws InterruptedException {
final TreeCache<Object, Object> cache = cacheTL.get();
Node<Object, Object> rootNode = cache.getRoot();
@@ -455,39 +448,29 @@
final CountDownLatch latch = new CountDownLatch(1);
final Random r = new Random();
- for (int i = 0; i < N; i++)
- {
- movers[i] = new Thread("Mover-" + i)
- {
- public void run()
- {
- try
- {
+ for (int i = 0; i < N; i++) {
+ movers[i] = new Thread("Mover-" + i) {
+ public void run() {
+ try {
latch.await();
}
- catch (InterruptedException e)
- {
+ catch (InterruptedException e) {
}
- for (int counter = 0; counter < loops; counter++)
- {
+ for (int counter = 0; counter < loops; counter++) {
System.out.println(getName() + ": Attempt " + counter);
- try
- {
+ try {
cache.move(NODE_X.getFqn(), NODES[r.nextInt(NODES.length)].getFqn());
}
- catch (NodeNotExistsException e)
- {
+ catch (NodeNotExistsException e) {
// this may happen ...
}
TestingUtil.sleepRandom(250);
- try
- {
+ try {
cache.move(NODE_Y.getFqn(), NODES[r.nextInt(NODES.length)].getFqn());
}
- catch (NodeNotExistsException e)
- {
+ catch (NodeNotExistsException e) {
// this may happen ...
}
TestingUtil.sleepRandom(250);
@@ -499,35 +482,26 @@
latch.countDown();
- for (Thread t : movers)
- {
+ for (Thread t : movers) {
t.join();
}
assertNoLocks();
boolean found_x = false, found_x_again = false;
- for (Node erased : NODES)
- {
+ for (Node erased : NODES) {
Node<Object, Object> n = genericize(erased);
- if (!found_x)
- {
+ if (!found_x) {
found_x = n.hasChild(FQN_X);
- }
- else
- {
+ } else {
found_x_again = found_x_again || n.hasChild(FQN_X);
}
}
boolean found_y = false, found_y_again = false;
- for (Node erased : NODES)
- {
+ for (Node erased : NODES) {
Node<Object, Object> n = genericize(erased);
- if (!found_y)
- {
+ if (!found_y) {
found_y = n.hasChild(FQN_Y);
- }
- else
- {
+ } else {
found_y_again = found_y_again || n.hasChild(FQN_Y);
}
}
@@ -538,8 +512,7 @@
assertFalse("Should have only found y once", found_y_again);
}
- public void testMoveInSamePlace()
- {
+ public void testMoveInSamePlace() {
TreeCache<Object, Object> cache = cacheTL.get();
Node<Object, Object> rootNode = cache.getRoot();
@@ -560,8 +533,7 @@
assertNoLocks();
}
- protected CacheLoaderConfig getSingleCacheLoaderConfig(boolean passivation, String preload, String cacheloaderClass, String properties, boolean async, boolean fetchPersistentState, boolean shared, boolean purgeOnStartup) throws Exception
- {
+ protected CacheLoaderConfig getSingleCacheLoaderConfig(boolean passivation, String preload, String cacheloaderClass, String properties, boolean async, boolean fetchPersistentState, boolean shared, boolean purgeOnStartup) throws Exception {
String xml =
" <loaders passivation=\"" + passivation + "\" shared=\"" + shared + "\">\n" +
" <preload>\n" +
@@ -579,8 +551,7 @@
return elementParser.parseLoadersElement(element);
}
- protected void checkLocks()
- {
+ protected void checkLocks() {
TreeCache<Object, Object> tree = cacheTL.get();
Cache<Object, Object> cache = tree.getCache();
@@ -589,8 +560,7 @@
assert TreeStructureSupport.isLocked(cache, A_B_C);
}
- protected void checkLocksDeep()
- {
+ protected void checkLocksDeep() {
TreeCache<Object, Object> tree = cacheTL.get();
Cache<Object, Object> cache = tree.getCache();
@@ -602,8 +572,7 @@
assert TreeStructureSupport.isLocked(cache, A_B_C_E);
}
- protected void assertNoLocks()
- {
+ protected void assertNoLocks() {
TreeCache<Object, Object> cache = cacheTL.get();
ComponentRegistry cr = TestingUtil.extractComponentRegistry(cache.getCache());
LockManager lm = cr.getComponent(LockManager.class);
@@ -611,8 +580,7 @@
LockAssert.assertNoLocks(lm, icc);
}
- public void testNonexistentSource()
- {
+ public void testNonexistentSource() {
TreeCache<Object, Object> cache = cacheTL.get();
cache.put(A_B_C, "k", "v");
assert "v".equals(cache.get(A_B_C, "k"));
@@ -628,8 +596,7 @@
assert !cache.getNode(A_B).getChildrenNames().contains(D.getLastElement());
}
- public void testNonexistentTarget()
- {
+ public void testNonexistentTarget() {
TreeCache<Object, Object> cache = cacheTL.get();
cache.put(A_B_C, "k", "v");
assert "v".equals(cache.get(A_B_C, "k"));
Modified: core/branches/flat/src/test/java/org/horizon/api/tree/NodeReplicatedMoveTest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/api/tree/NodeReplicatedMoveTest.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/test/java/org/horizon/api/tree/NodeReplicatedMoveTest.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -23,10 +23,8 @@
import javax.transaction.TransactionManager;
@Test(groups = {"functional", "jgroups", "pessimistic"}, testName = "api.NodeReplicatedMoveTest")
-public class NodeReplicatedMoveTest
-{
- private class NodeReplicatedMoveTestTL
- {
+public class NodeReplicatedMoveTest {
+ private class NodeReplicatedMoveTestTL {
protected TreeCache<Object, Object> cache1;
protected TreeCache<Object, Object> cache2;
protected TransactionManager tm;
@@ -38,8 +36,7 @@
protected static final Object k = "key", vA = "valueA", vB = "valueB", vC = "valueC", vD = "valueD", vE = "valueE";
@BeforeMethod(alwaysRun = true)
- public void setUp() throws Exception
- {
+ public void setUp() throws Exception {
NodeReplicatedMoveTestTL tl = new NodeReplicatedMoveTestTL();
threadLocal.set(tl);
Configuration c = new Configuration();
@@ -57,19 +54,16 @@
}
@AfterMethod(alwaysRun = true)
- public void tearDown()
- {
+ public void tearDown() {
NodeReplicatedMoveTestTL tl = threadLocal.get();
- if (tl != null)
- {
+ if (tl != null) {
TestingUtil.killTreeCaches(tl.cache1, tl.cache2);
threadLocal.set(null);
}
}
- public void testReplicatability()
- {
+ public void testReplicatability() {
NodeReplicatedMoveTestTL tl = threadLocal.get();
Node<Object, Object> rootNode = tl.cache1.getRoot();
@@ -95,8 +89,7 @@
assertEquals(vB, tl.cache2.getRoot().getChild(B).get(k));
}
- public void testReplTxCommit() throws Exception
- {
+ public void testReplTxCommit() throws Exception {
NodeReplicatedMoveTestTL tl = threadLocal.get();
Node<Object, Object> rootNode = tl.cache1.getRoot();
Fqn A_B = Fqn.fromRelativeFqn(A, B);
@@ -128,8 +121,7 @@
}
- public void testReplTxRollback() throws Exception
- {
+ public void testReplTxRollback() throws Exception {
NodeReplicatedMoveTestTL tl = threadLocal.get();
Node<Object, Object> rootNode = tl.cache1.getRoot();
Node<Object, Object> nodeA = rootNode.addChild(A);
Modified: core/branches/flat/src/test/java/org/horizon/api/tree/SyncReplTest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/api/tree/SyncReplTest.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/test/java/org/horizon/api/tree/SyncReplTest.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -28,14 +28,12 @@
* @author <a href="mailto:manik AT jboss DOT org">Manik Surtani (manik AT jboss DOT org)</a>
*/
@Test(groups = {"functional", "jgroups", "pessimistic"}, sequential = true, testName = "api.SyncReplTest")
-public class SyncReplTest
-{
+public class SyncReplTest {
private CacheSPI<Object, Object> c1, c2;
private TreeCache<Object, Object> cache1, cache2;
@BeforeMethod(alwaysRun = true)
- public void setUp()
- {
+ public void setUp() {
System.out.println("*** In setUp()");
Configuration c = new Configuration();
c.setCacheMode(Configuration.CacheMode.REPL_SYNC);
@@ -54,15 +52,13 @@
}
@AfterMethod(alwaysRun = true)
- public void tearDown()
- {
+ public void tearDown() {
TestingUtil.killCaches(c1, c2);
cache1 = null;
cache2 = null;
}
- public void testBasicOperation()
- {
+ public void testBasicOperation() {
assertClusterSize("Should only be 2 caches in the cluster!!!", 2);
Fqn f = Fqn.fromString("/test/data");
@@ -82,8 +78,7 @@
assert v.equals(cache2.get(f, k));
}
- public void testSyncRepl()
- {
+ public void testSyncRepl() {
assertClusterSize("Should only be 2 caches in the cluster!!!", 2);
Fqn fqn = Fqn.fromString("/JSESSIONID/1010.10.5:3000/1234567890/1");
@@ -96,8 +91,7 @@
assertEquals("Value should have replicated", 38, cache2.get(fqn, "age"));
}
- public void testPutMap()
- {
+ public void testPutMap() {
assertClusterSize("Should only be 2 caches in the cluster!!!", 2);
Fqn fqn = Fqn.fromString("/JSESSIONID/10.10.10.5:3000/1234567890/1");
@@ -122,14 +116,12 @@
}
- private void assertClusterSize(String message, int size)
- {
+ private void assertClusterSize(String message, int size) {
assertClusterSize(message, size, cache1);
assertClusterSize(message, size, cache2);
}
- private void assertClusterSize(String message, int size, TreeCache c)
- {
+ private void assertClusterSize(String message, int size, TreeCache c) {
assertEquals(message, size, c.getMembers().size());
}
}
Modified: core/branches/flat/src/test/java/org/horizon/api/tree/SyncReplTxTest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/api/tree/SyncReplTxTest.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/test/java/org/horizon/api/tree/SyncReplTxTest.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -22,7 +22,12 @@
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
-import javax.transaction.*;
+import javax.transaction.HeuristicMixedException;
+import javax.transaction.HeuristicRollbackException;
+import javax.transaction.NotSupportedException;
+import javax.transaction.RollbackException;
+import javax.transaction.SystemException;
+import javax.transaction.TransactionManager;
import java.util.ArrayList;
import java.util.List;
@@ -30,14 +35,12 @@
* @author <a href="mailto:manik AT jboss DOT org">Manik Surtani (manik AT jboss DOT org)</a>
*/
@Test(groups = {"functional", "jgroups", "transaction", "pessimistic"}, sequential = true, testName = "api.SyncReplTxTest")
-public class SyncReplTxTest
-{
+public class SyncReplTxTest {
private List<CacheSPI<Object, Object>> flatCaches;
private List<TreeCache<Object, Object>> caches;
@BeforeMethod(alwaysRun = true)
- public void setUp() throws CloneNotSupportedException
- {
+ public void setUp() throws CloneNotSupportedException {
System.out.println("*** In setUp()");
caches = new ArrayList<TreeCache<Object, Object>>();
flatCaches = new ArrayList<CacheSPI<Object, Object>>();
@@ -64,23 +67,20 @@
}
@AfterMethod(alwaysRun = true)
- public void tearDown()
- {
+ public void tearDown() {
System.out.println("*** In tearDown()");
TestingUtil.killTreeCaches(caches);
caches = null;
System.out.println("*** Finished tearDown()");
}
- private TransactionManager beginTransaction(Cache<Object, Object> cache) throws NotSupportedException, SystemException
- {
+ private TransactionManager beginTransaction(Cache<Object, Object> cache) throws NotSupportedException, SystemException {
TransactionManager mgr = cache.getConfiguration().getRuntimeConfig().getTransactionManager();
mgr.begin();
return mgr;
}
- public void testBasicOperation() throws SystemException, NotSupportedException, HeuristicMixedException, HeuristicRollbackException, RollbackException
- {
+ public void testBasicOperation() throws SystemException, NotSupportedException, HeuristicMixedException, HeuristicRollbackException, RollbackException {
assertClusterSize("Should only be 2 caches in the cluster!!!", 2);
Fqn f = Fqn.fromString("/test/data");
@@ -102,16 +102,13 @@
assertEquals("Should have replicated", v, caches.get(1).get(f, k));
}
- private void assertClusterSize(String message, int size)
- {
- for (Cache<Object, Object> c : flatCaches)
- {
+ private void assertClusterSize(String message, int size) {
+ for (Cache<Object, Object> c : flatCaches) {
assertClusterSize(message, size, c);
}
}
- private void assertClusterSize(String message, int size, Cache<Object, Object> c)
- {
+ private void assertClusterSize(String message, int size, Cache<Object, Object> c) {
assertEquals(message, size, c.getMembers().size());
}
}
\ No newline at end of file
Modified: core/branches/flat/src/test/java/org/horizon/api/tree/TreeCacheAPITest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/api/tree/TreeCacheAPITest.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/test/java/org/horizon/api/tree/TreeCacheAPITest.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -26,14 +26,12 @@
*/
@Test(groups = "functional", sequential = true)
-public class TreeCacheAPITest
-{
+public class TreeCacheAPITest {
private TreeCache<String, String> cache;
private TransactionManager tm;
@BeforeMethod(alwaysRun = true)
- public void setUp() throws Exception
- {
+ public void setUp() throws Exception {
// start a single cache instance
Configuration c = new Configuration();
c.setTransactionManagerLookupClass(DummyTransactionManagerLookup.class.getName());
@@ -47,21 +45,19 @@
}
@AfterMethod(alwaysRun = true)
- public void tearDown()
- {
+ public void tearDown() {
TestingUtil.killTreeCaches(cache);
cache = null;
}
/**
- * All cache operations should happen on a {@link Node} - I.e., you look up a {@link Node} and perform data operations
- * on this {@link Node}. For convenience and familiarity with JBoss Cache 1.x, we provide some helpers in {@link Cache}
- * which dives you direct data access to nodes.
+ * All cache operations should happen on a {@link Node} - I.e., you look up a {@link Node} and perform data
+ * operations on this {@link Node}. For convenience and familiarity with JBoss Cache 1.x, we provide some helpers in
+ * {@link Cache} which dives you direct data access to nodes.
* <p/>
* This test exercises these.
*/
- public void testConvenienceMethods()
- {
+ public void testConvenienceMethods() {
Fqn fqn = Fqn.fromString("/test/fqn");
String key = "key", value = "value";
Map<String, String> data = new HashMap<String, String>();
@@ -86,8 +82,7 @@
/**
* Another convenience method that tests node removal
*/
- public void testNodeConvenienceNodeRemoval()
- {
+ public void testNodeConvenienceNodeRemoval() {
// this fqn is relative, but since it is from the root it may as well be absolute
Fqn fqn = Fqn.fromString("/test/fqn");
cache.getRoot().addChild(fqn);
@@ -118,8 +113,7 @@
/**
* Tests basic eviction
*/
- public void testEvict()
- {
+ public void testEvict() {
Fqn one = Fqn.fromString("/one");
Fqn two = Fqn.fromString("/one/two");
String key = "key", value = "value";
@@ -158,8 +152,7 @@
/**
* Tests recursive eviction
*/
- public void testEvictRecursive()
- {
+ public void testEvictRecursive() {
Fqn one = Fqn.fromString("/one");
Fqn two = Fqn.fromString("/one/two");
String key = "key", value = "value";
@@ -189,8 +182,7 @@
assertFalse(cache.getRoot().hasChild(two));
}
- public void testStopClearsData() throws Exception
- {
+ public void testStopClearsData() throws Exception {
Fqn a = Fqn.fromString("/a");
Fqn b = Fqn.fromString("/a/b");
String key = "key", value = "value";
@@ -211,8 +203,7 @@
assertTrue(cache.getRoot().getChildren().isEmpty());
}
- public void testPhantomStructuralNodesOnRemove()
- {
+ public void testPhantomStructuralNodesOnRemove() {
assert cache.getNode(Fqn.fromString("/a/b/c")) == null;
assert !cache.removeNode("/a/b/c");
assert cache.getNode(Fqn.fromString("/a/b/c")) == null;
@@ -220,8 +211,7 @@
assert cache.getNode(Fqn.fromString("/a")) == null;
}
- public void testPhantomStructuralNodesOnRemoveTransactional() throws Exception
- {
+ public void testPhantomStructuralNodesOnRemoveTransactional() throws Exception {
assert cache.getNode(Fqn.fromString("/a/b/c")) == null;
tm.begin();
assert !cache.removeNode("/a/b/c");
@@ -231,8 +221,7 @@
assert cache.getNode(Fqn.fromString("/a")) == null;
}
- public void testRpcManagerElements()
- {
+ public void testRpcManagerElements() {
assertEquals("CacheMode.LOCAL cache has no address", null, cache.getLocalAddress());
assertEquals("CacheMode.LOCAL cache has no members list", null, cache.getMembers());
}
Modified: core/branches/flat/src/test/java/org/horizon/api/tree/TreeStructureHashCodeTest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/api/tree/TreeStructureHashCodeTest.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/test/java/org/horizon/api/tree/TreeStructureHashCodeTest.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -16,30 +16,25 @@
* Tests the degree to which hash codes get spread
*/
@Test
-public class TreeStructureHashCodeTest
-{
- public void testHashCodesAppendedCount()
- {
+public class TreeStructureHashCodeTest {
+ public void testHashCodesAppendedCount() {
List<Fqn> fqns = new ArrayList<Fqn>();
fqns.add(Fqn.ROOT);
for (int i = 0; i < 256; i++) fqns.add(Fqn.fromString("/fqn" + i));
doTest(fqns);
}
- public void testHashCodesAlpha()
- {
+ public void testHashCodesAlpha() {
List<Fqn> fqns = new ArrayList<Fqn>();
fqns.add(Fqn.ROOT);
for (int i = 0; i < 256; i++) fqns.add(Fqn.fromString("/" + Integer.toString(i, 36)));
doTest(fqns);
}
- private void doTest(List<Fqn> fqns)
- {
+ private void doTest(List<Fqn> fqns) {
LockContainer<NodeKey> container = new ReentrantLockContainer<NodeKey>(512);
Map<Lock, Integer> distribution = new HashMap<Lock, Integer>();
- for (Fqn f : fqns)
- {
+ for (Fqn f : fqns) {
NodeKey dataKey = new NodeKey(f, NodeKey.Type.DATA);
NodeKey structureKey = new NodeKey(f, NodeKey.Type.STRUCTURE);
addToDistribution(container.getLock(dataKey), distribution);
@@ -55,8 +50,7 @@
}
- private void addToDistribution(Lock lock, Map<Lock, Integer> map)
- {
+ private void addToDistribution(Lock lock, Map<Lock, Integer> map) {
int count = 1;
if (map.containsKey(lock)) count = map.get(lock) + 1;
map.put(lock, count);
Modified: core/branches/flat/src/test/java/org/horizon/atomic/APITest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/atomic/APITest.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/test/java/org/horizon/atomic/APITest.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -33,28 +33,23 @@
import java.util.Map;
@Test(groups = "functional")
-public class APITest
-{
+public class APITest {
- private void assertIsEmpty(Map map)
- {
+ private void assertIsEmpty(Map map) {
assert map.size() == 0;
assert map.get("blah") == null;
assert !map.containsKey("blah");
}
- private void assertIsEmptyMap(AtomicMapCache cache, Object key)
- {
+ private void assertIsEmptyMap(AtomicMapCache cache, Object key) {
assertIsEmpty(cache.getAtomicMap(key));
}
- public void testAtomicMap()
- {
+ public void testAtomicMap() {
Configuration c = new Configuration();
c.setInvocationBatchingEnabled(true);
AtomicMapCache cache = (AtomicMapCache) new CacheManager(c).getCache();
- try
- {
+ try {
AtomicMap map = cache.getAtomicMap("map");
assertIsEmpty(map);
@@ -70,21 +65,18 @@
assertIsEmpty(map);
assertIsEmptyMap(cache, "map");
}
- finally
- {
+ finally {
cache.stop();
}
}
- public void testReadSafetyEmptyCache() throws Exception
- {
+ public void testReadSafetyEmptyCache() throws Exception {
Configuration c = new Configuration();
c.setTransactionManagerLookupClass(DummyTransactionManagerLookup.class.getName());
c.setInvocationBatchingEnabled(true);
AtomicMapCache cache = (AtomicMapCache) new CacheManager(c).getCache();
- try
- {
+ try {
AtomicMap map = cache.getAtomicMap("map");
assertIsEmpty(map);
@@ -112,20 +104,17 @@
assertIsEmpty(map);
assertIsEmptyMap(cache, "map");
}
- finally
- {
+ finally {
cache.stop();
}
}
- public void testReadSafetyNotEmptyCache() throws Exception
- {
+ public void testReadSafetyNotEmptyCache() throws Exception {
Configuration c = new Configuration();
c.setTransactionManagerLookupClass(DummyTransactionManagerLookup.class.getName());
c.setInvocationBatchingEnabled(true);
AtomicMapCache cache = (AtomicMapCache) new CacheManager(c).getCache();
- try
- {
+ try {
AtomicMap map = cache.getAtomicMap("map");
DummyTransactionManager.getInstance().begin();
@@ -150,20 +139,17 @@
assertIsEmpty(map);
assertIsEmptyMap(cache, "map");
}
- finally
- {
+ finally {
cache.stop();
}
}
- public void testReadSafetyRollback() throws Exception
- {
+ public void testReadSafetyRollback() throws Exception {
Configuration c = new Configuration();
c.setTransactionManagerLookupClass(DummyTransactionManagerLookup.class.getName());
c.setInvocationBatchingEnabled(true);
AtomicMapCache cache = (AtomicMapCache) new CacheManager(c).getCache();
- try
- {
+ try {
AtomicMap map = cache.getAtomicMap("map");
DummyTransactionManager.getInstance().begin();
@@ -182,14 +168,12 @@
assertIsEmpty(map);
assertIsEmptyMap(cache, "map");
}
- finally
- {
+ finally {
cache.stop();
}
}
- public void testReplicationCommit() throws Exception
- {
+ public void testReplicationCommit() throws Exception {
Configuration c = new Configuration();
c.setTransactionManagerLookupClass(DummyTransactionManagerLookup.class.getName());
c.setCacheMode(CacheMode.REPL_SYNC);
@@ -197,8 +181,7 @@
AtomicMapCache cache1 = (AtomicMapCache) new CacheManager(c).getCache();
AtomicMapCache cache2 = (AtomicMapCache) new CacheManager(c).getCache();
- try
- {
+ try {
TestingUtil.blockUntilViewsReceived(20000, cache1, cache2);
AtomicMap map = cache1.getAtomicMap("map");
@@ -217,14 +200,12 @@
assert cache2.getAtomicMap("map").get("blah").equals("blah");
assert cache2.getAtomicMap("map").containsKey("blah");
}
- finally
- {
+ finally {
TestingUtil.killCaches(cache1, cache2);
}
}
- public void testReplicationRollback() throws Exception
- {
+ public void testReplicationRollback() throws Exception {
Configuration c = new Configuration();
c.setTransactionManagerLookupClass(DummyTransactionManagerLookup.class.getName());
c.setCacheMode(CacheMode.REPL_SYNC);
@@ -232,8 +213,7 @@
AtomicMapCache cache1 = (AtomicMapCache) new CacheManager(c).getCache();
AtomicMapCache cache2 = (AtomicMapCache) new CacheManager(c).getCache();
- try
- {
+ try {
TestingUtil.blockUntilViewsReceived(20000, cache1, cache2);
AtomicMap map = cache1.getAtomicMap("map");
@@ -246,8 +226,7 @@
assertIsEmptyMap(cache1, "map");
assertIsEmptyMap(cache2, "map");
}
- finally
- {
+ finally {
TestingUtil.killCaches(cache1, cache2);
}
}
Modified: core/branches/flat/src/test/java/org/horizon/atomic/AtomicHashMapTest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/atomic/AtomicHashMapTest.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/test/java/org/horizon/atomic/AtomicHashMapTest.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -30,10 +30,8 @@
import java.io.ObjectOutput;
@Test(groups = "unit")
-public class AtomicHashMapTest
-{
- public void testDeltasWithEmptyMap() throws IOException
- {
+public class AtomicHashMapTest {
+ public void testDeltasWithEmptyMap() throws IOException {
AtomicHashMap m = new AtomicHashMap();
Delta d = m.delta();
assert d instanceof NullDelta;
@@ -53,8 +51,7 @@
assert newMap.isEmpty();
}
- public void testDeltasWithNoChanges() throws IOException
- {
+ public void testDeltasWithNoChanges() throws IOException {
AtomicHashMap m = new AtomicHashMap();
m.initForWriting();
m.put("k1", "v1");
@@ -78,8 +75,7 @@
assert newMap.isEmpty();
}
- public void testDeltasWithRepeatedChanges()
- {
+ public void testDeltasWithRepeatedChanges() {
AtomicHashMap m = new AtomicHashMap();
m.initForWriting();
m.put("k1", "v1");
Modified: core/branches/flat/src/test/java/org/horizon/factories/scopes/ScopeDetectorTest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/factories/scopes/ScopeDetectorTest.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/test/java/org/horizon/factories/scopes/ScopeDetectorTest.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -7,85 +7,69 @@
* @since 1.0
*/
@Test(groups = "unit")
-public class ScopeDetectorTest
-{
- public void testScopeOnClass()
- {
+public class ScopeDetectorTest {
+ public void testScopeOnClass() {
testScopes(Test1.class, Scopes.GLOBAL);
}
- public void testScopeOnInterface()
- {
+ public void testScopeOnInterface() {
testScopes(Test2.class, Scopes.GLOBAL);
}
- public void testScopeOnSuperClass()
- {
+ public void testScopeOnSuperClass() {
testScopes(Test3.class, Scopes.GLOBAL);
}
- public void testScopeOnSuperInterface()
- {
+ public void testScopeOnSuperInterface() {
testScopes(Test4.class, Scopes.GLOBAL);
}
- public void testNoScopes()
- {
+ public void testNoScopes() {
testScopes(Test6.class, Scopes.NAMED_CACHE);
}
- private void testScopes(Class clazz, Scopes expected)
- {
+ private void testScopes(Class clazz, Scopes expected) {
Scopes detected = ScopeDetector.detectScope(clazz);
assert detected == expected : "Expected " + expected + " but was " + detected;
}
- public static interface Unscoped
- {
+ public static interface Unscoped {
}
@Scope(Scopes.GLOBAL)
- public static interface Scoped
- {
+ public static interface Scoped {
}
@Scope(Scopes.GLOBAL)
- public static class SuperScoped
- {
+ public static class SuperScoped {
}
- public static class SuperUnScoped
- {
+ public static class SuperUnScoped {
}
@Scope(Scopes.GLOBAL)
- public static class Test1
- {
+ public static class Test1 {
}
- public static class Test2 implements Scoped
- {
+ public static class Test2 implements Scoped {
}
- public static class Test3 extends SuperScoped
- {
+ public static class Test3 extends SuperScoped {
}
- public static class Test4 extends Test2
- {
+ public static class Test4 extends Test2 {
}
- public static class Test6 extends SuperUnScoped implements Unscoped
- {
+ public static class Test6 extends SuperUnScoped implements Unscoped {
}
}
Modified: core/branches/flat/src/test/java/org/horizon/lock/LockContainerHashingTest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/lock/LockContainerHashingTest.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/test/java/org/horizon/lock/LockContainerHashingTest.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -26,37 +26,34 @@
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
-import java.util.*;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Random;
import java.util.concurrent.locks.Lock;
@Test(groups = "unit")
-public class LockContainerHashingTest
-{
+public class LockContainerHashingTest {
private LockContainer<String> stripedLock;
@BeforeMethod(alwaysRun = true)
- public void setUp()
- {
+ public void setUp() {
stripedLock = new ReentrantLockContainer<String>(500);
}
- public void testHashingDistribution()
- {
+ public void testHashingDistribution() {
// ensure even bucket distribution of lock stripes
List<String> keys = createRandomKeys(1000);
Map<Lock, Integer> distribution = new HashMap<Lock, Integer>();
- for (String s : keys)
- {
+ for (String s : keys) {
Lock lock = stripedLock.getLock(s);
- if (distribution.containsKey(lock))
- {
+ if (distribution.containsKey(lock)) {
int count = distribution.get(lock) + 1;
distribution.put(lock, count);
- }
- else
- {
+ } else {
distribution.put(lock, 1);
}
}
@@ -71,14 +68,12 @@
assert distribution.size() * 1.5 >= stripedLock.size();
}
- private List<String> createRandomKeys(int number)
- {
+ private List<String> createRandomKeys(int number) {
List<String> f = new ArrayList<String>(number);
Random r = new Random();
int i = number;
- while (f.size() < number)
- {
+ while (f.size() < number) {
String s = i + "baseKey" + (10000 + i++);
f.add(s);
}
Modified: core/branches/flat/src/test/java/org/horizon/manager/CacheManagerComponentRegistryTest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/manager/CacheManagerComponentRegistryTest.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/test/java/org/horizon/manager/CacheManagerComponentRegistryTest.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -21,18 +21,15 @@
* @since 1.0
*/
@Test(groups = "functional", sequential = true)
-public class CacheManagerComponentRegistryTest
-{
+public class CacheManagerComponentRegistryTest {
CacheManager cm;
@AfterMethod
- public void tearDown()
- {
+ public void tearDown() {
if (cm != null) cm.stop();
}
- public void testForceSharedComponents() throws CacheNameExistsException, NamedCacheNotFoundException
- {
+ public void testForceSharedComponents() throws CacheNameExistsException, NamedCacheNotFoundException {
Configuration defaultCfg = new Configuration();
defaultCfg.setCacheMode(Configuration.CacheMode.REPL_SYNC);
// cache manager with default configuration
@@ -56,8 +53,7 @@
assert TestingUtil.extractComponent(c, RPCManager.class) == TestingUtil.extractComponent(transactional, RPCManager.class);
}
- public void testForceUnsharedComponents() throws CacheNameExistsException, NamedCacheNotFoundException
- {
+ public void testForceUnsharedComponents() throws CacheNameExistsException, NamedCacheNotFoundException {
CacheLoaderConfig clc = new CacheLoaderConfig();
FileCacheLoaderConfig fc = new FileCacheLoaderConfig();
fc.setLocation("/tmp");
@@ -83,8 +79,7 @@
assert TestingUtil.extractComponent(c, CacheLoaderManager.class) != TestingUtil.extractComponent(transactional, CacheLoaderManager.class);
}
- public void testOverridingComponents() throws CacheNameExistsException, NamedCacheNotFoundException
- {
+ public void testOverridingComponents() throws CacheNameExistsException, NamedCacheNotFoundException {
Configuration defaultCfg = new Configuration();
cm = new CacheManager(defaultCfg);
Modified: core/branches/flat/src/test/java/org/horizon/manager/CacheManagerTest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/manager/CacheManagerTest.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/test/java/org/horizon/manager/CacheManagerTest.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -1,7 +1,7 @@
package org.horizon.manager;
-import org.horizon.CacheStatus;
import org.horizon.Cache;
+import org.horizon.CacheStatus;
import org.horizon.config.Configuration;
import org.testng.annotations.Test;
@@ -10,47 +10,39 @@
* @since 1.0
*/
@Test(groups = "functional")
-public class CacheManagerTest
-{
- public void testDefaultCache() throws CacheNameExistsException
- {
+public class CacheManagerTest {
+ public void testDefaultCache() throws CacheNameExistsException {
CacheManager cm = new CacheManager();
assert cm.getCache().getCacheStatus() == CacheStatus.STARTED;
assert cm.getCache().getName().equals(CacheManager.DEFAULT_CACHE_NAME);
- try
- {
+ try {
cm.defineCache(CacheManager.DEFAULT_CACHE_NAME, new Configuration());
assert false : "Should fail";
}
- catch (IllegalArgumentException e)
- {
+ catch (IllegalArgumentException e) {
// ok
assert true : "Allowed";
}
}
- public void testClashingNames() throws CacheNameExistsException
- {
+ public void testClashingNames() throws CacheNameExistsException {
CacheManager cm = new CacheManager();
Configuration c = new Configuration();
cm.defineCache("aCache", c);
- try
- {
+ try {
cm.defineCache("aCache", c);
assert false : "Should fail";
}
- catch (CacheNameExistsException cnee)
- {
+ catch (CacheNameExistsException cnee) {
// expected
assert true : "Expected";
}
}
- public void testStartAndStop()
- {
+ public void testStartAndStop() {
CacheManager cm = new CacheManager();
Cache c1 = cm.getCache("cache1");
Cache c2 = cm.getCache("cache2");
Modified: core/branches/flat/src/test/java/org/horizon/manager/CacheManagerXmlConfigurationTest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/manager/CacheManagerXmlConfigurationTest.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/test/java/org/horizon/manager/CacheManagerXmlConfigurationTest.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -14,18 +14,15 @@
* @since 1.0
*/
@Test(groups = "functional", sequential = true)
-public class CacheManagerXmlConfigurationTest
-{
+public class CacheManagerXmlConfigurationTest {
CacheManager cm;
@AfterMethod
- public void tearDown()
- {
+ public void tearDown() {
if (cm != null) cm.stop();
}
- public void testNamedCacheXML() throws IOException
- {
+ public void testNamedCacheXML() throws IOException {
String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<jbosscache xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns=\"urn:jboss:starobrno-core:config:1.0\">\n" +
"\n" +
@@ -88,8 +85,7 @@
assert c.getConfiguration().getRuntimeConfig().getRPCManager() != null;
}
- public void testNamedCacheXMLClashingNames() throws IOException
- {
+ public void testNamedCacheXMLClashingNames() throws IOException {
String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<jbosscache xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns=\"urn:jboss:starobrno-core:config:1.0\">\n" +
"\n" +
@@ -112,19 +108,16 @@
"</jbosscache>";
ByteArrayInputStream bais = new ByteArrayInputStream(xml.getBytes());
- try
- {
+ try {
cm = new CacheManager(bais);
assert false : "Should fail";
}
- catch (ConfigurationException expected)
- {
+ catch (ConfigurationException expected) {
}
}
- public void testNamedCacheXMLClashingNamesProgrammatic() throws IOException
- {
+ public void testNamedCacheXMLClashingNamesProgrammatic() throws IOException {
String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<jbosscache xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns=\"urn:jboss:starobrno-core:config:1.0\">\n" +
"\n" +
@@ -143,13 +136,11 @@
assert cm.getCache() != null;
assert cm.getCache("c1") != null;
- try
- {
+ try {
cm.defineCache("c1", new Configuration());
assert false : "Should fail";
}
- catch (CacheNameExistsException expected)
- {
+ catch (CacheNameExistsException expected) {
}
}
Modified: core/branches/flat/src/test/java/org/horizon/profiling/AbstractProfileTest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/profiling/AbstractProfileTest.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/test/java/org/horizon/profiling/AbstractProfileTest.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -1,6 +1,7 @@
package org.horizon.profiling;
import org.horizon.Cache;
+import org.horizon.UnitTestCacheFactory;
import org.horizon.config.Configuration;
import org.horizon.util.TestingUtil;
import org.testng.annotations.AfterTest;
@@ -8,23 +9,19 @@
import org.testng.annotations.Test;
import java.util.Map;
-import org.horizon.UnitTestCacheFactory;
@Test(groups = "profiling")
-public abstract class AbstractProfileTest
-{
+public abstract class AbstractProfileTest {
protected Map cache;
@BeforeTest
- public void setUp()
- {
+ public void setUp() {
Configuration cfg = new Configuration();
cache = new UnitTestCacheFactory().createCache(cfg, false);
}
@AfterTest
- public void tearDown()
- {
+ public void tearDown() {
TestingUtil.killCaches((Cache) cache);
cache = null;
}
Modified: core/branches/flat/src/test/java/org/horizon/profiling/MemConsumptionTest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/profiling/MemConsumptionTest.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/test/java/org/horizon/profiling/MemConsumptionTest.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -33,16 +33,14 @@
import java.util.Random;
@Test(groups = "profiling", enabled = false)
-public class MemConsumptionTest
-{
+public class MemConsumptionTest {
// adjust the next 4 values
int numEntries = 1000000;
int payloadSize = 60; // bytes
int keySize = 10; // bytes
PayloadType payloadType = PayloadType.STRINGS;
- enum PayloadType
- {
+ enum PayloadType {
STRINGS, BYTE_ARRAYS
}
@@ -50,16 +48,13 @@
Random r = new Random();
- public void testMemConsumption() throws IOException
- {
+ public void testMemConsumption() throws IOException {
int kBytesCached = (bytesPerCharacter * numEntries * (payloadSize + keySize)) / 1024;
System.out.println("Bytes to be cached: " + NumberFormat.getIntegerInstance().format(kBytesCached) + " kb");
Cache c = new CacheManager().getCache();
- for (int i = 0; i < numEntries; i++)
- {
- switch (payloadType)
- {
+ for (int i = 0; i < numEntries; i++) {
+ switch (payloadType) {
case STRINGS:
c.put(generateUniqueString(i, keySize), generateRandomString(payloadSize));
break;
@@ -84,8 +79,7 @@
System.in.read();
}
- private String generateUniqueString(int runNumber, int keySize)
- {
+ private String generateUniqueString(int runNumber, int keySize) {
// string size should be exactly equal to key size but also be unique.
// start by creating a string from the run number
StringBuilder sb = new StringBuilder();
@@ -95,8 +89,7 @@
return sb.toString();
}
- private byte[] generateUniqueKey(int runNumber, int keySize)
- {
+ private byte[] generateUniqueKey(int runNumber, int keySize) {
byte[] b = new byte[keySize];
b[0] = (byte) (runNumber >>> 0);
b[1] = (byte) (runNumber >>> 8);
@@ -107,18 +100,15 @@
return b;
}
- private byte[] generateBytePayload(int payloadSize)
- {
+ private byte[] generateBytePayload(int payloadSize) {
byte[] b = new byte[payloadSize];
Arrays.fill(b, (byte) 0);
return b;
}
- private String generateRandomString(int stringSize)
- {
+ private String generateRandomString(int stringSize) {
StringBuilder sb = new StringBuilder();
- for (int i = 0; i < stringSize; i++)
- {
+ for (int i = 0; i < stringSize; i++) {
sb.append(r.nextInt(9)); // single digit
}
assert sb.length() == stringSize;
Modified: core/branches/flat/src/test/java/org/horizon/profiling/ProfileTest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/profiling/ProfileTest.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/test/java/org/horizon/profiling/ProfileTest.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -2,9 +2,9 @@
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
-import org.horizon.lock.IsolationLevel;
import org.horizon.Cache;
import org.horizon.config.Configuration;
+import org.horizon.lock.IsolationLevel;
import org.horizon.profiling.testinternals.Generator;
import org.horizon.profiling.testinternals.TaskRunner;
import org.horizon.util.TestingUtil;
@@ -20,16 +20,14 @@
* <p/>
* Typical usage pattern:
* <p/>
- * 1. Start a single test method in ProfileSlaveTest. This will block until you kill it.
- * 2. Start the corresponding test in this class, with the same name, in a different JVM, and attached to a profiler.
- * 3. Profile away!
+ * 1. Start a single test method in ProfileSlaveTest. This will block until you kill it. 2. Start the corresponding
+ * test in this class, with the same name, in a different JVM, and attached to a profiler. 3. Profile away!
* <p/>
*
* @author Manik Surtani (<a href="mailto:manik at jboss.org">manik at jboss.org</a>)
*/
@Test(groups = "profiling", sequential = true, enabled = false)
-public class ProfileTest extends AbstractProfileTest
-{
+public class ProfileTest extends AbstractProfileTest {
/*
Test configuration options
*/
@@ -45,8 +43,7 @@
Log log = LogFactory.getLog(ProfileTest.class);
@Test(enabled = true)
- public void testLocalMode() throws Exception
- {
+ public void testLocalMode() throws Exception {
Cache c = (Cache) cache;
c.getConfiguration().setCacheMode(Configuration.CacheMode.LOCAL);
c.getConfiguration().setConcurrencyLevel(2000);
@@ -54,8 +51,7 @@
runCompleteTest();
}
- private void runCompleteTest() throws Exception
- {
+ private void runCompleteTest() throws Exception {
init();
startup();
warmup();
@@ -69,22 +65,18 @@
* Thr following test phases can be profiled individually using triggers in JProfiler.
*/
- protected void init()
- {
+ protected void init() {
long startTime = System.currentTimeMillis();
log.warn("Starting init() phase");
keys.clear();
- for (int i = 0; i < MAX_OVERALL_KEYS; i++)
- {
+ for (int i = 0; i < MAX_OVERALL_KEYS; i++) {
Object key;
- do
- {
+ do {
key = Generator.createRandomKey();
}
while (keys.contains(key));
- if (i % 10 == 0)
- {
+ if (i % 10 == 0) {
log.warn("Generated " + i + " keys");
}
keys.add(key);
@@ -95,8 +87,7 @@
}
- protected void startup()
- {
+ protected void startup() {
long startTime = System.currentTimeMillis();
log.warn("Starting cache");
((Cache) cache).start();
@@ -104,18 +95,14 @@
log.warn("Started cache. " + printDuration(duration));
}
- private void warmup() throws InterruptedException
- {
+ private void warmup() throws InterruptedException {
long startTime = System.currentTimeMillis();
TaskRunner exec = new TaskRunner(NUM_THREADS);
log.warn("Starting warmup");
// creates all the Fqns since this can be expensive and we don't really want to measure this (for now)
- for (final Object key : keys)
- {
- exec.execute(new Runnable()
- {
- public void run()
- {
+ for (final Object key : keys) {
+ exec.execute(new Runnable() {
+ public void run() {
// this will create the necessary nodes.
cache.put(key, Collections.emptyMap());
}
@@ -123,12 +110,9 @@
}
// loop through WARMUP_LOOPS gets and puts for JVM optimisation
- for (int i = 0; i < WARMUP_LOOPS; i++)
- {
- exec.execute(new Runnable()
- {
- public void run()
- {
+ for (int i = 0; i < WARMUP_LOOPS; i++) {
+ exec.execute(new Runnable() {
+ public void run() {
Object key = Generator.getRandomElement(keys);
cache.get(key);
cache.put(key, "Value");
@@ -147,8 +131,7 @@
startup();
}
- private void doTest() throws Exception
- {
+ private void doTest() throws Exception {
TaskRunner exec = new TaskRunner(NUM_THREADS);
log.warn("Starting test");
int i;
@@ -159,11 +142,9 @@
AtomicLong durationRemoves = new AtomicLong();
long stElapsed = System.nanoTime();
- for (i = 0; i < NUM_OPERATIONS; i++)
- {
+ for (i = 0; i < NUM_OPERATIONS; i++) {
MyRunnable r = null;
- switch (i % 3)
- {
+ switch (i % 3) {
case 0:
r = new Putter(i, durationPuts);
break;
@@ -194,36 +175,30 @@
log.warn("Average REMOVE time: " + printAvg(durationRemoves.get()));
}
- private String printAvg(long totalNanos)
- {
+ private String printAvg(long totalNanos) {
double nOps = (double) (NUM_OPERATIONS / 3);
double avg = ((double) totalNanos) / nOps;
double avgMicros = avg / 1000;
return avgMicros + " µs";
}
- private double toMillis(long nanos)
- {
+ private double toMillis(long nanos) {
return ((double) nanos / (double) 1000000);
}
- enum Mode
- {
+ enum Mode {
PUT, GET, REMOVE
}
- private abstract class MyRunnable implements Runnable
- {
+ private abstract class MyRunnable implements Runnable {
int id;
Mode mode;
AtomicLong duration;
- public void run()
- {
+ public void run() {
Object key = Generator.getRandomElement(keys);
long d = 0, st = 0;
- switch (mode)
- {
+ switch (mode) {
case PUT:
Object value = Generator.getRandomString();
st = System.nanoTime();
@@ -245,45 +220,35 @@
}
}
- private class Putter extends MyRunnable
- {
- private Putter(int id, AtomicLong duration)
- {
+ private class Putter extends MyRunnable {
+ private Putter(int id, AtomicLong duration) {
this.id = id;
this.duration = duration;
mode = Mode.PUT;
}
}
- private class Getter extends MyRunnable
- {
- private Getter(int id, AtomicLong duration)
- {
+ private class Getter extends MyRunnable {
+ private Getter(int id, AtomicLong duration) {
this.id = id;
this.duration = duration;
mode = Mode.GET;
}
}
- private class Remover extends MyRunnable
- {
- private Remover(int id, AtomicLong duration)
- {
+ private class Remover extends MyRunnable {
+ private Remover(int id, AtomicLong duration) {
this.id = id;
this.duration = duration;
mode = Mode.REMOVE;
}
}
- protected String printDuration(long duration)
- {
- if (duration > 2000)
- {
+ protected String printDuration(long duration) {
+ if (duration > 2000) {
double dSecs = ((double) duration / (double) 1000);
return "Duration: " + dSecs + " seconds";
- }
- else
- {
+ } else {
return "Duration: " + duration + " millis";
}
}
Modified: core/branches/flat/src/test/java/org/horizon/profiling/TreeProfileTest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/profiling/TreeProfileTest.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/test/java/org/horizon/profiling/TreeProfileTest.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -2,10 +2,10 @@
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
-import org.horizon.lock.IsolationLevel;
import org.horizon.Cache;
import org.horizon.UnitTestCacheFactory;
import org.horizon.config.Configuration;
+import org.horizon.lock.IsolationLevel;
import org.horizon.profiling.testinternals.Generator;
import org.horizon.profiling.testinternals.TaskRunner;
import org.horizon.transaction.DummyTransactionManager;
@@ -27,16 +27,14 @@
* <p/>
* Typical usage pattern:
* <p/>
- * 1. Start a single test method in ProfileSlaveTest. This will block until you kill it.
- * 2. Start the corresponding test in this class, with the same name, in a different JVM, and attached to a profiler.
- * 3. Profile away!
+ * 1. Start a single test method in ProfileSlaveTest. This will block until you kill it. 2. Start the corresponding
+ * test in this class, with the same name, in a different JVM, and attached to a profiler. 3. Profile away!
* <p/>
*
* @author Manik Surtani (<a href="mailto:manik at jboss.org">manik at jboss.org</a>)
*/
@Test(groups = "profiling", sequential = true, enabled = false)
-public class TreeProfileTest
-{
+public class TreeProfileTest {
/*
Test configuration options
*/
@@ -51,8 +49,7 @@
protected TreeCache cache;
@BeforeTest
- public void setUp()
- {
+ public void setUp() {
Configuration cfg = new Configuration();
cfg.setInvocationBatchingEnabled(true);
cfg.setCacheMode(Configuration.CacheMode.LOCAL);
@@ -65,8 +62,7 @@
}
@AfterTest
- public void tearDown()
- {
+ public void tearDown() {
TestingUtil.killTreeCaches(cache);
cache = null;
}
@@ -75,13 +71,11 @@
Log log = LogFactory.getLog(TreeProfileTest.class);
- public void testLocalMode() throws Exception
- {
+ public void testLocalMode() throws Exception {
runCompleteTest();
}
- private void runCompleteTest() throws Exception
- {
+ private void runCompleteTest() throws Exception {
init();
startup();
warmup();
@@ -95,16 +89,13 @@
* Thr following test phases can be profiled individually using triggers in JProfiler.
*/
- protected void init()
- {
+ protected void init() {
long startTime = System.currentTimeMillis();
log.warn("Starting init() phase");
fqns.clear();
- for (int i = 0; i < MAX_OVERALL_NODES; i++)
- {
+ for (int i = 0; i < MAX_OVERALL_NODES; i++) {
Fqn fqn;
- do
- {
+ do {
fqn = Generator.createRandomFqn(MAX_DEPTH);
}
while (fqns.contains(fqn));
@@ -117,8 +108,7 @@
log.warn("Finished init() phase. " + printDuration(duration));
}
- protected void startup()
- {
+ protected void startup() {
long startTime = System.currentTimeMillis();
log.warn("Starting cache");
cache.start();
@@ -126,25 +116,19 @@
log.warn("Started cache. " + printDuration(duration));
}
- private void warmup() throws InterruptedException
- {
+ private void warmup() throws InterruptedException {
long startTime = System.currentTimeMillis();
TaskRunner runner = new TaskRunner(NUM_THREADS);
log.warn("Starting warmup");
// creates all the Fqns since this can be expensive and we don't really want to measure this (for now)
- for (final Fqn fqn : fqns)
- {
- runner.execute(new Runnable()
- {
- public void run()
- {
- try
- {
+ for (final Fqn fqn : fqns) {
+ runner.execute(new Runnable() {
+ public void run() {
+ try {
// this will create the necessary nodes.
cache.put(fqn, "key", Collections.emptyMap());
}
- catch (Exception e)
- {
+ catch (Exception e) {
log.warn("Caught Exception", e);
}
}
@@ -152,14 +136,10 @@
}
// loop through WARMUP_LOOPS gets and puts for JVM optimisation
- for (int i = 0; i < WARMUP_LOOPS; i++)
- {
- runner.execute(new Runnable()
- {
- public void run()
- {
- try
- {
+ for (int i = 0; i < WARMUP_LOOPS; i++) {
+ runner.execute(new Runnable() {
+ public void run() {
+ try {
Fqn fqn = Generator.getRandomElement(fqns);
DummyTransactionManager.getInstance().begin();
cache.get(fqn, "key");
@@ -171,8 +151,7 @@
cache.remove(fqn, "key");
DummyTransactionManager.getInstance().commit();
}
- catch (Exception e)
- {
+ catch (Exception e) {
log.warn("Caught Exception", e);
}
}
@@ -189,8 +168,7 @@
startup();
}
- private void doTest() throws Exception
- {
+ private void doTest() throws Exception {
TaskRunner runner = new TaskRunner(NUM_THREADS);
log.warn("Starting test");
@@ -202,11 +180,9 @@
AtomicLong durationRemoves = new AtomicLong();
long stElapsed = System.nanoTime();
- for (i = 0; i < NUM_OPERATIONS; i++)
- {
+ for (i = 0; i < NUM_OPERATIONS; i++) {
MyRunnable r = null;
- switch (i % 3)
- {
+ switch (i % 3) {
case 0:
r = new Putter(i, durationPuts);
break;
@@ -237,38 +213,31 @@
log.warn("Average REMOVE time: " + printAvg(durationRemoves.get()));
}
- private String printAvg(long totalNanos)
- {
+ private String printAvg(long totalNanos) {
double nOps = (double) (NUM_OPERATIONS / 3);
double avg = ((double) totalNanos) / nOps;
double avgMicros = avg / 1000;
return avgMicros + " µs";
}
- private double toMillis(long nanos)
- {
+ private double toMillis(long nanos) {
return ((double) nanos / (double) 1000000);
}
- enum Mode
- {
+ enum Mode {
PUT, GET, REMOVE
}
- private abstract class MyRunnable implements Runnable
- {
+ private abstract class MyRunnable implements Runnable {
int id;
Mode mode;
AtomicLong duration;
- public void run()
- {
+ public void run() {
Fqn fqn = Generator.getRandomElement(fqns);
long d = 0, st = 0;
- try
- {
- switch (mode)
- {
+ try {
+ switch (mode) {
case PUT:
Object value = Generator.getRandomString();
@@ -288,53 +257,42 @@
break;
}
}
- catch (Exception e)
- {
+ catch (Exception e) {
d = 0;
}
duration.getAndAdd(d);
}
}
- private class Putter extends MyRunnable
- {
- private Putter(int id, AtomicLong duration)
- {
+ private class Putter extends MyRunnable {
+ private Putter(int id, AtomicLong duration) {
this.id = id;
this.duration = duration;
mode = Mode.PUT;
}
}
- private class Getter extends MyRunnable
- {
- private Getter(int id, AtomicLong duration)
- {
+ private class Getter extends MyRunnable {
+ private Getter(int id, AtomicLong duration) {
this.id = id;
this.duration = duration;
mode = Mode.GET;
}
}
- private class Remover extends MyRunnable
- {
- private Remover(int id, AtomicLong duration)
- {
+ private class Remover extends MyRunnable {
+ private Remover(int id, AtomicLong duration) {
this.id = id;
this.duration = duration;
mode = Mode.REMOVE;
}
}
- protected String printDuration(long duration)
- {
- if (duration > 2000)
- {
+ protected String printDuration(long duration) {
+ if (duration > 2000) {
double dSecs = ((double) duration / (double) 1000);
return "Duration: " + dSecs + " seconds";
- }
- else
- {
+ } else {
return "Duration: " + duration + " millis";
}
}
Modified: core/branches/flat/src/test/java/org/horizon/profiling/testinternals/Generator.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/profiling/testinternals/Generator.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/test/java/org/horizon/profiling/testinternals/Generator.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -6,36 +6,30 @@
import java.util.List;
import java.util.Random;
-public class Generator
-{
+public class Generator {
private static final Random r = new Random();
- public static String getRandomString()
- {
+ public static String getRandomString() {
StringBuilder sb = new StringBuilder();
int len = r.nextInt(10);
- for (int i = 0; i < len; i++)
- {
+ for (int i = 0; i < len; i++) {
sb.append((char) (63 + r.nextInt(26)));
}
return sb.toString();
}
- public static <T> T getRandomElement(List<T> list)
- {
+ public static <T> T getRandomElement(List<T> list) {
return list.get(r.nextInt(list.size()));
}
- public static Fqn createRandomFqn(int depth)
- {
+ public static Fqn createRandomFqn(int depth) {
List<String> fqnElements = new ArrayList<String>(depth);
for (int i = 0; i < depth; i++) fqnElements.add(Integer.toHexString(r.nextInt(Integer.MAX_VALUE)));
return Fqn.fromList(fqnElements, true);
}
- public static Object createRandomKey()
- {
+ public static Object createRandomKey() {
return Integer.toHexString(r.nextInt(Integer.MAX_VALUE));
}
}
Modified: core/branches/flat/src/test/java/org/horizon/profiling/testinternals/TaskRunner.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/profiling/testinternals/TaskRunner.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/test/java/org/horizon/profiling/testinternals/TaskRunner.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -8,22 +8,18 @@
* Essentially a delegate to an ExecutorService, but a special one that is only used by perf tests so it can be ignored
* when profiling.
*/
-public class TaskRunner
-{
+public class TaskRunner {
ExecutorService exec;
- public TaskRunner(int numThreads)
- {
+ public TaskRunner(int numThreads) {
this.exec = Executors.newFixedThreadPool(numThreads);
}
- public void execute(Runnable r)
- {
+ public void execute(Runnable r) {
exec.execute(r);
}
- public void stop() throws InterruptedException
- {
+ public void stop() throws InterruptedException {
exec.shutdown();
while (!exec.awaitTermination(30, TimeUnit.SECONDS)) Thread.sleep(30);
}
Modified: core/branches/flat/src/test/java/org/horizon/replication/AsyncReplTest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/replication/AsyncReplTest.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/test/java/org/horizon/replication/AsyncReplTest.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -23,15 +23,12 @@
import javax.transaction.TransactionManager;
/**
- * Unit test for replicated async CacheSPI. Use locking and multiple threads to test
- * concurrent access to the tree.
+ * Unit test for replicated async CacheSPI. Use locking and multiple threads to test concurrent access to the tree.
*/
@Test(groups = {"functional", "jgroups"})
-public class AsyncReplTest
-{
+public class AsyncReplTest {
- private class AsyncReplTestTL
- {
+ private class AsyncReplTestTL {
private Configuration configuration;
private CacheSPI<Object, Object> cache1, cache2;
private UnitTestCacheManager cacheManager1, cacheManager2;
@@ -41,8 +38,7 @@
private ThreadLocal<AsyncReplTestTL> threadLocal = new ThreadLocal<AsyncReplTestTL>();
@BeforeMethod(alwaysRun = true)
- public void setUp() throws Exception
- {
+ public void setUp() throws Exception {
AsyncReplTestTL tl = new AsyncReplTestTL();
threadLocal.set(tl);
@@ -62,39 +58,33 @@
}
/**
- * Provides a hook for multiplexer integration. This default implementation
- * is a no-op; subclasses that test mux integration would override
- * to integrate the given cache with a multiplexer.
+ * Provides a hook for multiplexer integration. This default implementation is a no-op; subclasses that test mux
+ * integration would override to integrate the given cache with a multiplexer.
* <p/>
* param cache a cache that has been configured but not yet created.
*/
- protected void configureMultiplexer(Cache cache) throws Exception
- {
+ protected void configureMultiplexer(Cache cache) throws Exception {
// default does nothing
}
/**
- * Provides a hook to check that the cache's channel came from the
- * multiplexer, or not, as expected. This default impl asserts that
- * the channel did not come from the multiplexer.
+ * Provides a hook to check that the cache's channel came from the multiplexer, or not, as expected. This default
+ * impl asserts that the channel did not come from the multiplexer.
*
* @param cache a cache that has already been started
*/
- protected void validateMultiplexer(Cache cache)
- {
+ protected void validateMultiplexer(Cache cache) {
assertFalse("Cache is not using multiplexer", cache.getConfiguration().isUsingMultiplexer());
}
@AfterMethod(alwaysRun = true)
- public void tearDown() throws Exception
- {
+ public void tearDown() throws Exception {
AsyncReplTestTL tl = threadLocal.get();
TestingUtil.killCaches(tl.cache1, tl.cache2);
threadLocal.set(null);
}
- public void testTxCompletion() throws Exception
- {
+ public void testTxCompletion() throws Exception {
AsyncReplTestTL tl = threadLocal.get();
CacheSPI<Object, Object> cache1 = tl.cache1;
CacheSPI<Object, Object> cache2 = tl.cache2;
@@ -136,8 +126,7 @@
assertEquals("value2", cache2.get(key));
}
- public void testPutShouldNotReplicateToDifferentCluster()
- {
+ public void testPutShouldNotReplicateToDifferentCluster() {
AsyncReplTestTL tl = threadLocal.get();
CacheSPI<Object, Object> cache1 = tl.cache1;
CacheSPI<Object, Object> cache2 = tl.cache2;
@@ -145,8 +134,7 @@
ReplicationListener replListener2 = tl.replListener2;
CacheSPI<Object, Object> cache3 = null, cache4 = null;
- try
- {
+ try {
tl.configuration.setClusterName("otherTest");
cache3 = (CacheSPI<Object, Object>) new UnitTestCacheManager(tl.configuration).createCache("testCache");
cache4 = (CacheSPI<Object, Object>) new UnitTestCacheManager(tl.configuration).createCache("testCache");
@@ -157,25 +145,20 @@
replListener2.waitForReplicationToOccur(500);
assertNull("Should not have replicated", cache3.get("age"));
}
- catch (Exception e)
- {
+ catch (Exception e) {
fail(e.toString());
}
- finally
- {
- if (cache3 != null)
- {
+ finally {
+ if (cache3 != null) {
cache3.stop();
}
- if (cache4 != null)
- {
+ if (cache4 != null) {
cache4.stop();
}
}
}
- public void testAsyncReplDelay()
- {
+ public void testAsyncReplDelay() {
Integer age;
AsyncReplTestTL tl = threadLocal.get();
CacheSPI<Object, Object> cache1 = tl.cache1;
@@ -183,8 +166,7 @@
ReplicationListener replListener1 = tl.replListener1;
ReplicationListener replListener2 = tl.replListener2;
- try
- {
+ try {
cache1.put("age", 38);
// value on cache2 may be 38 or not yet replicated
@@ -192,14 +174,12 @@
log("attr \"age\" of \"/a/b/c\" on cache2=" + age);
assertTrue("should be either null or 38", age == null || age == 38);
}
- catch (Exception e)
- {
+ catch (Exception e) {
fail(e.toString());
}
}
- public void testAsyncReplTxDelay()
- {
+ public void testAsyncReplTxDelay() {
Integer age;
AsyncReplTestTL tl = threadLocal.get();
CacheSPI<Object, Object> cache1 = tl.cache1;
@@ -207,8 +187,7 @@
ReplicationListener replListener1 = tl.replListener1;
ReplicationListener replListener2 = tl.replListener2;
- try
- {
+ try {
TransactionManager tm = cache1.getTransactionManager();
tm.begin();
cache1.put("age", 38);
@@ -219,14 +198,12 @@
log("attr \"age\" of \"/a/b/c\" on cache2=" + age);
assertTrue("should be either null or 38", age == null || age == 38);
}
- catch (Exception e)
- {
+ catch (Exception e) {
fail(e.toString());
}
}
- private void log(String msg)
- {
+ private void log(String msg) {
System.out.println("-- [" + Thread.currentThread() + "]: " + msg);
}
}
Modified: core/branches/flat/src/test/java/org/horizon/replication/ExceptionTest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/replication/ExceptionTest.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/test/java/org/horizon/replication/ExceptionTest.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -18,8 +18,7 @@
* @author <a href="mailto:manik at jboss.org">Manik Surtani</a>
*/
@Test(groups = {"functional"}, sequential = true)
-public class ExceptionTest
-{
+public class ExceptionTest {
private Cache cache1;
private Cache cache2;
@@ -39,8 +38,7 @@
"pbcast.STATE_TRANSFER:" +
"DELAY(in_delay=100;out_delay=100)";
- private Cache createCache(String jgroupsConfig)
- {
+ private Cache createCache(String jgroupsConfig) {
Configuration c = new Configuration();
c.setSyncCommitPhase(true);
c.setSyncRollbackPhase(true);
@@ -52,16 +50,14 @@
}
@AfterMethod
- public void tearDown()
- {
+ public void tearDown() {
TestingUtil.killCaches(cache1, cache2);
cache1 = null;
cache2 = null;
}
@Test(groups = {"functional"}, expectedExceptions = {TimeoutException.class})
- public void testSyncReplTimeout()
- {
+ public void testSyncReplTimeout() {
cache1 = createCache(DELAYED_CLUSTER_CONFIG);
cache2 = createCache(DELAYED_CLUSTER_CONFIG);
@@ -77,8 +73,7 @@
}
@Test(groups = {"functional"}, expectedExceptions = {TimeoutException.class})
- public void testLockAcquisitionTimeout() throws Exception
- {
+ public void testLockAcquisitionTimeout() throws Exception {
cache1 = createCache(null);
cache2 = createCache(null);
cache2.getConfiguration().setLockAcquisitionTimeout(1);
Modified: core/branches/flat/src/test/java/org/horizon/replication/ReplicationExceptionTest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/replication/ReplicationExceptionTest.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/test/java/org/horizon/replication/ReplicationExceptionTest.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -32,13 +32,11 @@
* @author Ben Wang
*/
@Test(groups = {"functional"}, sequential = true)
-public class ReplicationExceptionTest
-{
+public class ReplicationExceptionTest {
private CacheSPI<String, ContainerData> cache1, cache2;
@AfterMethod(alwaysRun = true)
- public void tearDown() throws Exception
- {
+ public void tearDown() throws Exception {
// We just can't kill DummyTransactionManager. We are sharing single instance in more tests.
TestingUtil.killTransaction(DummyTransactionManager.getInstance());
destroyCaches();
@@ -51,15 +49,13 @@
*/
}
- private TransactionManager beginTransaction() throws SystemException, NotSupportedException
- {
+ private TransactionManager beginTransaction() throws SystemException, NotSupportedException {
TransactionManager mgr = cache1.getConfiguration().getRuntimeConfig().getTransactionManager();
mgr.begin();
return mgr;
}
- private void initCaches(Configuration.CacheMode cachingMode)
- {
+ private void initCaches(Configuration.CacheMode cachingMode) {
Configuration conf1 = new Configuration();
Configuration conf2 = new Configuration();
@@ -81,17 +77,14 @@
cache2.start();
}
- void destroyCaches() throws Exception
- {
+ void destroyCaches() throws Exception {
TestingUtil.killCaches(cache1, cache2);
cache1 = null;
cache2 = null;
}
- public void testNonSerializableRepl() throws Exception
- {
- try
- {
+ public void testNonSerializableRepl() throws Exception {
+ try {
initCaches(Configuration.CacheMode.REPL_SYNC);
cache1.put("test", new ContainerData());
@@ -99,26 +92,20 @@
// We should not come here.
assertNotNull("NonSerializableData should not be null on cache2", cache2.get("test"));
}
- catch (RuntimeException runtime)
- {
+ catch (RuntimeException runtime) {
Throwable t = runtime.getCause();
- if (t instanceof NotSerializableException)
- {
+ if (t instanceof NotSerializableException) {
System.out.println("received NotSerializableException - as expected");
- }
- else
- {
+ } else {
throw runtime;
}
}
}
- public void testNonSerializableReplWithTx() throws Exception
- {
+ public void testNonSerializableReplWithTx() throws Exception {
TransactionManager tm;
- try
- {
+ try {
initCaches(Configuration.CacheMode.REPL_SYNC);
tm = beginTransaction();
@@ -128,30 +115,25 @@
// We should not come here.
assertNotNull("NonSerializableData should not be null on cache2", cache2.get("test"));
}
- catch (RollbackException rollback)
- {
+ catch (RollbackException rollback) {
System.out.println("received RollbackException - as expected");
}
- catch (Exception e)
- {
+ catch (Exception e) {
// We should also examine that it is indeed throwing a NonSerilaizable exception.
fail(e.toString());
}
}
- static class NonSerializabeData
- {
+ static class NonSerializabeData {
int i;
}
- static class ContainerData implements Serializable
- {
+ static class ContainerData implements Serializable {
int i;
NonSerializabeData non_serializable_data;
private static final long serialVersionUID = -8322197791060897247L;
- public ContainerData()
- {
+ public ContainerData() {
i = 99;
non_serializable_data = new NonSerializabeData();
}
Modified: core/branches/flat/src/test/java/org/horizon/replication/SyncCacheListenerTest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/replication/SyncCacheListenerTest.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/test/java/org/horizon/replication/SyncCacheListenerTest.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -36,22 +36,19 @@
* Test out the TreeCacheListener
*/
@Test(groups = {"functional"}, sequential = true)
-public class SyncCacheListenerTest
-{
+public class SyncCacheListenerTest {
private CacheSPI<Object, Object> cache1, cache2;
private final static Log log_ = LogFactory.getLog(SyncCacheListenerTest.class);
@BeforeMethod(alwaysRun = true)
- public void setUp() throws Exception
- {
+ public void setUp() throws Exception {
System.out.println("*** starting setUp()");
initCaches();
System.out.println("*** finished setUp()");
}
@AfterMethod(alwaysRun = true)
- public void tearDown() throws Exception
- {
+ public void tearDown() throws Exception {
System.out.println("*** starting tearDown()");
// We just can't kill DummyTransactionManager. We are sharing single instance in more tests.
TestingUtil.killTransaction(DummyTransactionManager.getInstance());
@@ -66,8 +63,7 @@
System.out.println("*** finished tearDown()");
}
- private void initCaches()
- {
+ private void initCaches() {
Configuration conf = new Configuration();
conf.setSyncCommitPhase(true);
conf.setCacheMode(Configuration.CacheMode.REPL_SYNC);
@@ -80,15 +76,13 @@
TestingUtil.blockUntilViewReceived(cache2, 2, 1000);
}
- private void destroyCaches()
- {
+ private void destroyCaches() {
TestingUtil.killCaches(cache1, cache2);
cache1 = null;
cache2 = null;
}
- public void testSyncTxRepl() throws Exception
- {
+ public void testSyncTxRepl() throws Exception {
Integer age;
TransactionManager tm = cache1.getTransactionManager();
@@ -109,8 +103,7 @@
assertTrue("\"age\" must be 38", age == 38);
}
- public void testRemoteCacheListener() throws Exception
- {
+ public void testRemoteCacheListener() throws Exception {
Integer age;
RemoteListener lis = new RemoteListener();
cache2.getNotifier().addCacheListener(lis);
@@ -123,8 +116,7 @@
cache1.remove("age");
}
- public void testSyncRepl() throws Exception
- {
+ public void testSyncRepl() throws Exception {
Integer age;
Listener lis = new Listener();
cache1.addCacheListener(lis);
@@ -137,8 +129,7 @@
}
- public void simpleReplicationTest() throws Exception
- {
+ public void simpleReplicationTest() throws Exception {
TransactionManager tm = cache1.getConfiguration().getRuntimeConfig().getTransactionManager();
tm.begin();
cache1.put("key", "value");
@@ -148,8 +139,7 @@
}
- public void testSyncTxReplMap() throws Exception
- {
+ public void testSyncTxReplMap() throws Exception {
Integer age;
TransactionManager tm = cache1.getConfiguration().getRuntimeConfig().getTransactionManager();
tm.begin();
@@ -175,8 +165,7 @@
assertTrue("\"age\" must be 38", age == 38);
}
- public void testSyncReplMap() throws Exception
- {
+ public void testSyncReplMap() throws Exception {
Integer age;
Listener lis = new Listener();
@@ -191,18 +180,15 @@
}
@CacheListener
- public class Listener
- {
+ public class Listener {
Object key = null;
- public void put(Object key, Object val)
- {
+ public void put(Object key, Object val) {
this.key = key;
cache1.put(key, val);
}
- public void put(String fqn, Map map)
- {
+ public void put(String fqn, Map map) {
if (map.size() == 0)
fail("put(): map size can't be 0");
Set<String> set = map.keySet();
@@ -211,18 +197,14 @@
}
@CacheEntryModified
- public void nodeModified(Event ne)
- {
- if (!ne.isPre())
- {
+ public void nodeModified(Event ne) {
+ if (!ne.isPre()) {
log_.debug("nodeModified visited with fqn: " + key);
- try
- {
+ try {
// test out if we can get the read lock since there is a write lock going as well.
cache1.get(key);
}
- catch (CacheException e)
- {
+ catch (CacheException e) {
e.printStackTrace();//To change body of catch statement use File | Settings | File Templates.
fail("nodeModified: test failed with exception: " + e);
}
@@ -232,13 +214,11 @@
}
@CacheListener
- public class RemoteListener
- {
+ public class RemoteListener {
@CacheEntryRemoved
@CacheEntryModified
- public void callback(TransactionalEvent e)
- {
+ public void callback(TransactionalEvent e) {
System.out.println("Callback got event " + e);
log_.debug("Callback got event " + e);
assertFalse("node was removed on remote cache so isLocal should be false", e.isOriginLocal());
Modified: core/branches/flat/src/test/java/org/horizon/replication/SyncReplTest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/replication/SyncReplTest.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/test/java/org/horizon/replication/SyncReplTest.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -6,26 +6,25 @@
*/
package org.horizon.replication;
-import static org.testng.AssertJUnit.*;
-import org.testng.annotations.AfterMethod;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
import org.horizon.Cache;
import org.horizon.UnitTestCacheManager;
-import org.horizon.util.TestingUtil;
import org.horizon.config.Configuration;
+import org.horizon.util.TestingUtil;
+import static org.testng.AssertJUnit.assertEquals;
+import static org.testng.AssertJUnit.assertNull;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
/**
* @author <a href="mailto:manik at jboss.org">Manik Surtani (manik at jboss.org)</a>
*/
@Test(groups = {"functional", "jgroups"})
-public class SyncReplTest
-{
+public class SyncReplTest {
private ThreadLocal<Cache<Object, Object>[]> cachesTL = new ThreadLocal<Cache<Object, Object>[]>();
@BeforeMethod(alwaysRun = true)
- public void setUp()
- {
+ public void setUp() {
System.out.println("*** In setUp()");
Cache<Object, Object>[] caches = new Cache[2];
Configuration configuration = new Configuration();
@@ -38,15 +37,13 @@
}
@AfterMethod(alwaysRun = true)
- public void tearDown()
- {
+ public void tearDown() {
Cache<Object, Object>[] caches = cachesTL.get();
if (caches != null) TestingUtil.killCaches(caches);
cachesTL.set(null);
}
- public void testBasicOperation()
- {
+ public void testBasicOperation() {
Cache<Object, Object>[] caches = cachesTL.get();
assertClusterSize("Should only be 2 caches in the cluster!!!", 2);
@@ -62,8 +59,7 @@
}
@SuppressWarnings("unchecked")
- public void testSyncRepl()
- {
+ public void testSyncRepl() {
Cache<Object, Object>[] caches = cachesTL.get();
assertClusterSize("Should only be 2 caches in the cluster!!!", 2);
@@ -75,17 +71,14 @@
assertEquals("Value should have replicated", 38, caches[1].get("age"));
}
- private void assertClusterSize(String message, int size)
- {
+ private void assertClusterSize(String message, int size) {
Cache<Object, Object>[] caches = cachesTL.get();
- for (Cache c : caches)
- {
+ for (Cache c : caches) {
assertClusterSize(message, size, c);
}
}
- private void assertClusterSize(String message, int size, Cache c)
- {
+ private void assertClusterSize(String message, int size, Cache c) {
assertEquals(message, size, c.getMembers().size());
}
}
Modified: core/branches/flat/src/test/java/org/horizon/tx/LocalModeTxTest.java
===================================================================
--- core/branches/flat/src/test/java/org/horizon/tx/LocalModeTxTest.java 2009-01-16 15:25:15 UTC (rev 7490)
+++ core/branches/flat/src/test/java/org/horizon/tx/LocalModeTxTest.java 2009-01-16 15:41:03 UTC (rev 7491)
@@ -32,21 +32,17 @@
import javax.transaction.TransactionManager;
@Test(groups = "functional")
-public class LocalModeTxTest
-{
- private CacheSPI<String, String> createCache()
- {
+public class LocalModeTxTest {
+ private CacheSPI<String, String> createCache() {
Configuration cfg = new Configuration();
cfg.setTransactionManagerLookupClass(DummyTransactionManagerLookup.class.getName());
UnitTestCacheManager cm = new UnitTestCacheManager(cfg);
return (CacheSPI<String, String>) cm.createCache("test");
}
- public void testTxCommit1() throws Exception
- {
+ public void testTxCommit1() throws Exception {
CacheSPI c = null;
- try
- {
+ try {
c = createCache();
TransactionManager tm = c.getTransactionManager();
tm.begin();
@@ -57,17 +53,14 @@
tm.commit();
assert !c.isEmpty();
}
- finally
- {
+ finally {
TestingUtil.killCaches(c);
}
}
- public void testTxCommit2() throws Exception
- {
+ public void testTxCommit2() throws Exception {
CacheSPI c = null;
- try
- {
+ try {
c = createCache();
TransactionManager tm = c.getTransactionManager();
c.put("key", "old");
@@ -82,8 +75,7 @@
assert c.get("key").equals("value");
assert !c.isEmpty();
}
- finally
- {
+ finally {
TestingUtil.killCaches(c);
}
}
More information about the jbosscache-commits
mailing list