You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@curator.apache.org by ti...@apache.org on 2023/06/02 08:11:12 UTC
[curator] branch master updated: CURATOR-674. Apply code style with spotless (#463)
This is an automated email from the ASF dual-hosted git repository.
tison pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/curator.git
The following commit(s) were added to refs/heads/master by this push:
new 484ede9a CURATOR-674. Apply code style with spotless (#463)
484ede9a is described below
commit 484ede9a33abb1427ba58c77e5792814aac889f0
Author: tison <wa...@gmail.com>
AuthorDate: Fri Jun 2 16:11:05 2023 +0800
CURATOR-674. Apply code style with spotless (#463)
Signed-off-by: tison <wa...@gmail.com>
---
.github/workflows/ci.yml | 15 +
.../java/org/apache/curator/ConnectionState.java | 213 ++-
.../curator/CuratorConnectionLossException.java | 5 +-
.../org/apache/curator/CuratorZookeeperClient.java | 189 +--
.../main/java/org/apache/curator/HandleHolder.java | 89 +-
.../src/main/java/org/apache/curator/Helper.java | 21 +-
.../main/java/org/apache/curator/RetryLoop.java | 28 +-
.../java/org/apache/curator/RetryLoopImpl.java | 43 +-
.../main/java/org/apache/curator/RetryPolicy.java | 17 +-
.../main/java/org/apache/curator/RetrySleeper.java | 5 +-
.../org/apache/curator/SessionFailRetryLoop.java | 109 +-
.../apache/curator/SessionFailedRetryPolicy.java | 19 +-
.../main/java/org/apache/curator/TimeTrace.java | 13 +-
.../curator/connection/ThreadLocalRetryLoop.java | 53 +-
.../curator/drivers/AdvancedTracerDriver.java | 11 +-
.../org/apache/curator/drivers/EventTrace.java | 50 +-
.../org/apache/curator/drivers/OperationTrace.java | 107 +-
.../org/apache/curator/drivers/TracerDriver.java | 7 +-
.../apache/curator/ensemble/EnsembleProvider.java | 19 +-
.../ensemble/fixed/FixedEnsembleProvider.java | 31 +-
.../retry/BoundedExponentialBackoffRetry.java | 14 +-
.../curator/retry/ExponentialBackoffRetry.java | 28 +-
.../org/apache/curator/retry/RetryForever.java | 22 +-
.../java/org/apache/curator/retry/RetryNTimes.java | 9 +-
.../org/apache/curator/retry/RetryOneTime.java | 6 +-
.../apache/curator/retry/RetryUntilElapsed.java | 13 +-
.../org/apache/curator/retry/SleepingRetry.java | 26 +-
.../curator/utils/CloseableExecutorService.java | 66 +-
.../utils/CloseableScheduledExecutorService.java | 19 +-
.../org/apache/curator/utils/CloseableUtils.java | 17 +-
.../org/apache/curator/utils/Compatibility.java | 70 +-
.../utils/ConfigurableZookeeperFactory.java | 17 +-
.../java/org/apache/curator/utils/DebugUtils.java | 14 +-
.../apache/curator/utils/DefaultTracerDriver.java | 17 +-
.../curator/utils/DefaultZookeeperFactory.java | 7 +-
.../java/org/apache/curator/utils/EnsurePath.java | 74 +-
.../apache/curator/utils/ExceptionAccumulator.java | 25 +-
.../apache/curator/utils/InternalACLProvider.java | 7 +-
.../curator/utils/NonAdminZookeeperFactory.java | 7 +-
.../java/org/apache/curator/utils/PathUtils.java | 22 +-
.../java/org/apache/curator/utils/ThreadUtils.java | 51 +-
.../java/org/apache/curator/utils/ZKPaths.java | 264 ++--
.../org/apache/curator/utils/ZookeeperFactory.java | 24 +-
.../test/java/org/apache/curator/BasicTests.java | 127 +-
.../java/org/apache/curator/TestEnsurePath.java | 86 +-
.../src/test/java/org/apache/curator/TestIs37.java | 9 +-
.../java/org/apache/curator/TestRetryLoop.java | 148 +-
.../apache/curator/TestSessionFailRetryLoop.java | 334 ++---
.../utils/TestCloseableExecutorService.java | 201 +--
.../TestCloseableScheduledExecutorService.java | 55 +-
.../java/org/apache/curator/utils/TestZKPaths.java | 11 +-
.../src/main/java/async/AsyncExamples.java | 67 +-
.../src/main/java/cache/CuratorCacheExample.java | 55 +-
.../src/main/java/cache/PathCacheExample.java | 181 +--
.../src/main/java/cache/TreeCacheExample.java | 20 +-
.../src/main/java/discovery/DiscoveryExample.java | 237 ++--
.../src/main/java/discovery/ExampleServer.java | 47 +-
.../src/main/java/discovery/InstanceDetails.java | 17 +-
.../main/java/framework/CreateClientExamples.java | 22 +-
.../src/main/java/framework/CrudExamples.java | 109 +-
.../main/java/framework/TransactionExamples.java | 17 +-
.../src/main/java/leader/ExampleClient.java | 34 +-
.../main/java/leader/LeaderSelectorExample.java | 52 +-
.../main/java/locking/ExampleClientThatLocks.java | 22 +-
.../src/main/java/locking/FakeLimitedResource.java | 20 +-
.../src/main/java/locking/LockingExample.java | 70 +-
.../src/main/java/modeled/ContainerType.java | 29 +-
.../main/java/modeled/ModeledCuratorExamples.java | 26 +-
.../java/modeled/ModeledCuratorExamplesAlt.java | 21 +-
.../src/main/java/modeled/PersonId.java | 29 +-
.../src/main/java/modeled/PersonModel.java | 56 +-
.../src/main/java/modeled/PersonModelSpec.java | 9 +-
curator-examples/src/main/java/pubsub/Clients.java | 42 +-
.../src/main/java/pubsub/Publisher.java | 56 +-
.../src/main/java/pubsub/SubPubTest.java | 150 +-
.../src/main/java/pubsub/Subscriber.java | 25 +-
.../java/pubsub/messages/LocationAvailable.java | 22 +-
.../src/main/java/pubsub/messages/UserCreated.java | 25 +-
.../src/main/java/pubsub/models/Group.java | 15 +-
.../src/main/java/pubsub/models/Instance.java | 32 +-
.../src/main/java/pubsub/models/InstanceType.java | 3 +-
.../src/main/java/pubsub/models/Message.java | 26 +-
.../src/main/java/pubsub/models/Priority.java | 3 +-
.../org/apache/curator/framework/AuthInfo.java | 18 +-
.../apache/curator/framework/CuratorFramework.java | 16 +-
.../curator/framework/CuratorFrameworkFactory.java | 269 ++--
.../curator/framework/CuratorTempFramework.java | 7 +-
.../apache/curator/framework/EnsureContainers.java | 21 +-
.../framework/WatcherRemoveCuratorFramework.java | 5 +-
.../api/ACLBackgroundPathAndBytesable.java | 7 +-
.../ACLCreateModeBackgroundPathAndBytesable.java | 10 +-
.../api/ACLCreateModePathAndBytesable.java | 7 +-
...CLCreateModeStatBackgroundPathAndBytesable.java | 7 +-
.../curator/framework/api/ACLPathAndBytesable.java | 6 +-
.../apache/curator/framework/api/ACLProvider.java | 9 +-
.../org/apache/curator/framework/api/ACLable.java | 5 +-
.../framework/api/ACLableExistBuilderMain.java | 6 +-
.../framework/api/AddStatConfigEnsembleable.java | 9 +-
.../curator/framework/api/AddWatchBuilder.java | 5 +-
.../curator/framework/api/AddWatchBuilder2.java | 8 +-
.../org/apache/curator/framework/api/Addable.java | 3 +-
.../curator/framework/api/AsyncReconfigurable.java | 2 +-
.../curator/framework/api/BackgroundCallback.java | 3 +-
.../framework/api/BackgroundEnsembleable.java | 6 +-
.../framework/api/BackgroundPathAndBytesable.java | 7 +-
.../curator/framework/api/BackgroundPathable.java | 6 +-
.../api/BackgroundPathableQuietlyable.java | 4 +-
.../framework/api/BackgroundVersionable.java | 6 +-
.../curator/framework/api/Backgroundable.java | 3 +-
.../curator/framework/api/ChildrenDeletable.java | 3 +-
.../apache/curator/framework/api/Compressible.java | 3 +-
.../curator/framework/api/CompressionProvider.java | 7 +-
.../framework/api/ConfigureEnsembleable.java | 4 +-
.../framework/api/CreateBackgroundModeACLable.java | 13 +-
.../api/CreateBackgroundModeStatACLable.java | 15 +-
.../curator/framework/api/CreateBuilder.java | 3 +-
.../curator/framework/api/CreateBuilder2.java | 3 +-
.../curator/framework/api/CreateBuilderMain.java | 18 +-
.../curator/framework/api/CreateModable.java | 3 +-
...CreateProtectACLCreateModePathAndBytesable.java | 6 +-
.../apache/curator/framework/api/CuratorEvent.java | 6 +-
.../curator/framework/api/CuratorEventType.java | 3 +-
.../curator/framework/api/CuratorListener.java | 5 +-
.../curator/framework/api/CuratorWatcher.java | 3 +-
.../curator/framework/api/Decompressible.java | 5 +-
.../curator/framework/api/DeleteBuilder.java | 8 +-
.../curator/framework/api/DeleteBuilderMain.java | 4 +-
.../framework/api/ErrorListenerEnsembleable.java | 3 +-
.../api/ErrorListenerMultiTransactionMain.java | 3 +-
.../api/ErrorListenerPathAndBytesable.java | 3 +-
.../framework/api/ErrorListenerPathable.java | 3 +-
.../api/ErrorListenerReconfigBuilderMain.java | 3 +-
.../curator/framework/api/ExistsBuilder.java | 4 +-
.../curator/framework/api/ExistsBuilderMain.java | 6 +-
.../curator/framework/api/GetACLBuilder.java | 8 +-
.../curator/framework/api/GetChildrenBuilder.java | 10 +-
.../curator/framework/api/GetConfigBuilder.java | 12 +-
.../curator/framework/api/GetDataBuilder.java | 12 +-
.../api/GetDataWatchBackgroundStatable.java | 8 +-
.../curator/framework/api/Guaranteeable.java | 9 +-
.../framework/api/GuaranteeableDeletable.java | 6 +-
.../curator/framework/api/Idempotentable.java | 3 +-
.../framework/api/JoinStatConfigEnsembleable.java | 9 +-
.../org/apache/curator/framework/api/Joinable.java | 3 +-
.../framework/api/LeaveStatConfigEnsembleable.java | 9 +-
.../apache/curator/framework/api/Leaveable.java | 3 +-
.../apache/curator/framework/api/Membersable.java | 3 +-
.../curator/framework/api/ParentACLable.java | 4 +-
.../curator/framework/api/PathAndBytesable.java | 7 +-
.../org/apache/curator/framework/api/Pathable.java | 5 +-
.../api/ProtectACLCreateModePathAndBytesable.java | 8 +-
.../ProtectACLCreateModeStatPathAndBytesable.java | 7 +-
.../org/apache/curator/framework/api/Quietly.java | 3 +-
.../curator/framework/api/ReconfigBuilder.java | 6 +-
.../curator/framework/api/ReconfigBuilderMain.java | 10 +-
.../framework/api/RemoveWatchesBuilder.java | 57 +-
.../curator/framework/api/RemoveWatchesLocal.java | 32 +-
.../curator/framework/api/RemoveWatchesType.java | 36 +-
.../curator/framework/api/SetACLBuilder.java | 7 +-
.../api/SetDataBackgroundVersionable.java | 7 +-
.../curator/framework/api/SetDataBuilder.java | 12 +-
.../framework/api/StatConfigureEnsembleable.java | 6 +-
.../apache/curator/framework/api/StatPathable.java | 6 +-
.../org/apache/curator/framework/api/Statable.java | 3 +-
.../apache/curator/framework/api/SyncBuilder.java | 5 +-
.../curator/framework/api/TempGetDataBuilder.java | 8 +-
.../framework/api/UnhandledErrorListener.java | 8 +-
.../framework/api/VersionPathAndBytesable.java | 6 +-
.../apache/curator/framework/api/Versionable.java | 5 +-
.../framework/api/WatchBackgroundEnsembleable.java | 7 +-
.../curator/framework/api/WatchPathable.java | 6 +-
.../apache/curator/framework/api/Watchable.java | 3 +-
.../curator/framework/api/WatchableBase.java | 3 +-
.../curator/framework/api/WatchesBuilder.java | 7 +-
.../api/transaction/CuratorMultiTransaction.java | 7 +-
.../transaction/CuratorMultiTransactionMain.java | 5 +-
.../framework/api/transaction/CuratorOp.java | 3 +-
.../api/transaction/CuratorTransaction.java | 3 +-
.../api/transaction/CuratorTransactionBridge.java | 3 +-
.../api/transaction/CuratorTransactionFinal.java | 3 +-
.../api/transaction/CuratorTransactionResult.java | 33 +-
.../framework/api/transaction/OperationType.java | 3 +-
.../api/transaction/TransactionCheckBuilder.java | 6 +-
.../api/transaction/TransactionCreateBuilder.java | 3 +-
.../api/transaction/TransactionCreateBuilder2.java | 14 +-
.../api/transaction/TransactionDeleteBuilder.java | 6 +-
.../framework/api/transaction/TransactionOp.java | 3 +-
.../api/transaction/TransactionSetDataBuilder.java | 12 +-
.../framework/api/transaction/TypeAndPath.java | 12 +-
.../org/apache/curator/framework/imps/ACLing.java | 34 +-
.../framework/imps/AddWatchBuilderImpl.java | 174 +--
.../framework/imps/BackgroundOperation.java | 3 +-
.../curator/framework/imps/BackgroundSyncImpl.java | 50 +-
.../curator/framework/imps/Backgrounding.java | 106 +-
.../curator/framework/imps/CreateBuilderImpl.java | 972 ++++++-------
.../curator/framework/imps/CuratorEventImpl.java | 83 +-
.../framework/imps/CuratorFrameworkImpl.java | 678 ++++-----
.../framework/imps/CuratorFrameworkState.java | 3 +-
.../imps/CuratorMultiTransactionImpl.java | 156 +-
.../imps/CuratorMultiTransactionRecord.java | 30 +-
.../framework/imps/CuratorTempFrameworkImpl.java | 82 +-
.../framework/imps/CuratorTransactionImpl.java | 108 +-
.../curator/framework/imps/DefaultACLProvider.java | 11 +-
.../curator/framework/imps/DeleteBuilderImpl.java | 305 ++--
.../curator/framework/imps/EnsembleTracker.java | 135 +-
.../curator/framework/imps/ExistsBuilderImpl.java | 228 ++-
.../framework/imps/ExtractingCuratorOp.java | 20 +-
.../framework/imps/FailedDeleteManager.java | 10 +-
.../framework/imps/FailedOperationManager.java | 39 +-
.../framework/imps/FailedRemoveWatchManager.java | 27 +-
.../FindAndDeleteProtectedNodeInBackground.java | 76 +-
.../curator/framework/imps/GetACLBuilderImpl.java | 107 +-
.../framework/imps/GetChildrenBuilderImpl.java | 185 ++-
.../framework/imps/GetConfigBuilderImpl.java | 197 ++-
.../curator/framework/imps/GetDataBuilderImpl.java | 235 ++--
.../framework/imps/GzipCompressionProvider.java | 139 +-
.../curator/framework/imps/IdempotentUtils.java | 10 +-
.../framework/imps/InternalConnectionHandler.java | 3 +-
.../curator/framework/imps/NamespaceFacade.java | 66 +-
.../framework/imps/NamespaceFacadeCache.java | 32 +-
.../curator/framework/imps/NamespaceImpl.java | 75 +-
.../framework/imps/NamespaceWatchedEvent.java | 6 +-
.../curator/framework/imps/NamespaceWatcher.java | 61 +-
.../curator/framework/imps/OperationAndData.java | 85 +-
.../curator/framework/imps/PathAndBytes.java | 16 +-
.../curator/framework/imps/ProtectedMode.java | 40 +-
.../curator/framework/imps/ProtectedUtils.java | 58 +-
.../framework/imps/ReconfigBuilderImpl.java | 186 ++-
.../framework/imps/RemoveWatchesBuilderImpl.java | 637 ++++-----
.../curator/framework/imps/SetACLBuilderImpl.java | 152 +-
.../curator/framework/imps/SetDataBuilderImpl.java | 393 +++---
.../imps/StandardInternalConnectionHandler.java | 9 +-
.../curator/framework/imps/SyncBuilderImpl.java | 59 +-
.../framework/imps/TempGetDataBuilderImpl.java | 48 +-
.../curator/framework/imps/TransactionOpImpl.java | 19 +-
.../framework/imps/WatcherRemovalFacade.java | 83 +-
.../framework/imps/WatcherRemovalManager.java | 35 +-
.../curator/framework/imps/WatchesBuilderImpl.java | 22 +-
.../apache/curator/framework/imps/Watching.java | 47 +-
.../curator/framework/listen/Listenable.java | 9 +-
.../curator/framework/listen/ListenerEntry.java | 8 +-
.../curator/framework/listen/ListenerManager.java | 6 +-
.../framework/listen/MappingListenerManager.java | 46 +-
.../framework/listen/StandardListenerManager.java | 30 +-
.../framework/listen/UnaryListenerManager.java | 4 +-
.../framework/schema/DefaultSchemaValidator.java | 8 +-
.../apache/curator/framework/schema/Schema.java | 190 +--
.../curator/framework/schema/SchemaBuilder.java | 45 +-
.../apache/curator/framework/schema/SchemaSet.java | 127 +-
.../curator/framework/schema/SchemaSetLoader.java | 97 +-
.../curator/framework/schema/SchemaValidator.java | 5 +-
.../curator/framework/schema/SchemaViolation.java | 47 +-
.../curator/framework/state/CircuitBreaker.java | 50 +-
.../CircuitBreakingConnectionStateListener.java | 94 +-
.../framework/state/CircuitBreakingManager.java | 48 +-
.../curator/framework/state/ConnectionState.java | 37 +-
.../state/ConnectionStateErrorPolicy.java | 3 +-
.../framework/state/ConnectionStateListener.java | 6 +-
.../ConnectionStateListenerManagerFactory.java | 12 +-
.../framework/state/ConnectionStateManager.java | 223 ++-
.../state/SessionConnectionStateErrorPolicy.java | 6 +-
.../state/StandardConnectionStateErrorPolicy.java | 6 +-
.../framework/ensemble/TestEnsembleProvider.java | 84 +-
.../framework/imps/TestBlockUntilConnected.java | 187 +--
.../curator/framework/imps/TestCleanState.java | 95 +-
.../curator/framework/imps/TestCompression.java | 80 +-
.../imps/TestCompressionInTransactionNew.java | 101 +-
.../imps/TestCompressionInTransactionOld.java | 160 ++-
.../apache/curator/framework/imps/TestCreate.java | 276 ++--
.../framework/imps/TestCreateReturningStat.java | 433 +++---
.../apache/curator/framework/imps/TestDelete.java | 241 ++--
.../imps/TestEnabledSessionExpiredState.java | 83 +-
.../framework/imps/TestEnsureContainers.java | 24 +-
.../curator/framework/imps/TestExistsBuilder.java | 63 +-
.../framework/imps/TestFailedDeleteManager.java | 292 ++--
.../curator/framework/imps/TestFramework.java | 772 ++++------
.../framework/imps/TestFrameworkBackground.java | 225 ++-
.../curator/framework/imps/TestFrameworkEdges.java | 595 ++++----
.../imps/TestGzipCompressionProvider.java | 27 +-
.../curator/framework/imps/TestMultiClient.java | 69 +-
.../framework/imps/TestNamespaceFacade.java | 160 +--
.../curator/framework/imps/TestNeverConnected.java | 25 +-
.../curator/framework/imps/TestReadOnly.java | 80 +-
.../framework/imps/TestReconfiguration.java | 393 +++---
.../apache/curator/framework/imps/TestSetData.java | 273 ++--
.../curator/framework/imps/TestTempFramework.java | 65 +-
.../framework/imps/TestTransactionsNew.java | 153 +-
.../framework/imps/TestTransactionsOld.java | 168 ++-
.../curator/framework/imps/TestTtlNodes.java | 50 +-
.../framework/imps/TestWatcherIdentity.java | 265 ++--
.../framework/imps/TestWatcherRemovalManager.java | 330 ++---
.../curator/framework/imps/TestWatchesBuilder.java | 1484 ++++++++++----------
.../curator/framework/imps/TestWithCluster.java | 100 +-
.../curator/framework/schema/TestSchema.java | 224 ++-
.../framework/state/TestCircuitBreaker.java | 38 +-
...TestCircuitBreakingConnectionStateListener.java | 84 +-
.../state/TestConnectionStateManager.java | 69 +-
.../recipes/AfterConnectionEstablished.java | 38 +-
.../framework/recipes/atomic/AtomicStats.java | 35 +-
.../framework/recipes/atomic/AtomicValue.java | 11 +-
.../recipes/atomic/CachedAtomicInteger.java | 26 +-
.../framework/recipes/atomic/CachedAtomicLong.java | 24 +-
.../recipes/atomic/DistributedAtomicInteger.java | 100 +-
.../recipes/atomic/DistributedAtomicLong.java | 100 +-
.../recipes/atomic/DistributedAtomicNumber.java | 3 +-
.../recipes/atomic/DistributedAtomicValue.java | 245 ++--
.../framework/recipes/atomic/MakeValue.java | 5 +-
.../recipes/atomic/MutableAtomicValue.java | 21 +-
.../framework/recipes/atomic/PromotedToLock.java | 58 +-
.../recipes/barriers/DistributedBarrier.java | 70 +-
.../recipes/barriers/DistributedDoubleBarrier.java | 228 ++-
.../curator/framework/recipes/cache/ChildData.java | 58 +-
.../cache/CompatibleCuratorCacheBridge.java | 75 +-
.../framework/recipes/cache/CuratorCache.java | 19 +-
.../recipes/cache/CuratorCacheAccessor.java | 8 +-
.../recipes/cache/CuratorCacheBridge.java | 3 +-
.../recipes/cache/CuratorCacheBridgeBuilder.java | 5 +-
.../cache/CuratorCacheBridgeBuilderImpl.java | 31 +-
.../recipes/cache/CuratorCacheBuilder.java | 5 +-
.../recipes/cache/CuratorCacheBuilderImpl.java | 22 +-
.../framework/recipes/cache/CuratorCacheImpl.java | 197 +--
.../recipes/cache/CuratorCacheListener.java | 14 +-
.../recipes/cache/CuratorCacheListenerBuilder.java | 13 +-
.../cache/CuratorCacheListenerBuilderImpl.java | 74 +-
.../recipes/cache/CuratorCacheStorage.java | 9 +-
.../recipes/cache/DefaultTreeCacheSelector.java | 9 +-
.../framework/recipes/cache/EventOperation.java | 16 +-
.../framework/recipes/cache/GetDataOperation.java | 33 +-
.../curator/framework/recipes/cache/NodeCache.java | 196 +--
.../framework/recipes/cache/NodeCacheListener.java | 5 +-
.../recipes/cache/NodeCacheListenerWrapper.java | 21 +-
.../curator/framework/recipes/cache/Operation.java | 5 +-
.../framework/recipes/cache/PathChildrenCache.java | 557 ++++----
.../recipes/cache/PathChildrenCacheEvent.java | 28 +-
.../recipes/cache/PathChildrenCacheListener.java | 5 +-
.../cache/PathChildrenCacheListenerWrapper.java | 38 +-
.../recipes/cache/PathChildrenCacheMode.java | 5 +-
.../framework/recipes/cache/RefreshOperation.java | 29 +-
.../recipes/cache/StandardCuratorCacheStorage.java | 26 +-
.../curator/framework/recipes/cache/TreeCache.java | 644 ++++-----
.../framework/recipes/cache/TreeCacheEvent.java | 29 +-
.../framework/recipes/cache/TreeCacheIterator.java | 62 +-
.../framework/recipes/cache/TreeCacheListener.java | 3 +-
.../recipes/cache/TreeCacheListenerWrapper.java | 36 +-
.../framework/recipes/cache/TreeCacheSelector.java | 3 +-
.../recipes/leader/CancelLeadershipException.java | 16 +-
.../framework/recipes/leader/LeaderLatch.java | 353 ++---
.../recipes/leader/LeaderLatchListener.java | 31 +-
.../framework/recipes/leader/LeaderSelector.java | 279 ++--
.../recipes/leader/LeaderSelectorListener.java | 5 +-
.../leader/LeaderSelectorListenerAdapter.java | 9 +-
.../framework/recipes/leader/Participant.java | 47 +-
.../framework/recipes/locks/InterProcessLock.java | 3 +-
.../recipes/locks/InterProcessMultiLock.java | 116 +-
.../framework/recipes/locks/InterProcessMutex.java | 104 +-
.../recipes/locks/InterProcessReadWriteLock.java | 90 +-
.../recipes/locks/InterProcessSemaphore.java | 145 +-
.../recipes/locks/InterProcessSemaphoreMutex.java | 25 +-
.../recipes/locks/InterProcessSemaphoreV2.java | 253 ++--
.../curator/framework/recipes/locks/Lease.java | 5 +-
.../framework/recipes/locks/LockInternals.java | 298 ++--
.../recipes/locks/LockInternalsDriver.java | 10 +-
.../recipes/locks/LockInternalsSorter.java | 5 +-
.../curator/framework/recipes/locks/Locker.java | 27 +-
.../framework/recipes/locks/PredicateResults.java | 16 +-
.../curator/framework/recipes/locks/Revocable.java | 7 +-
.../recipes/locks/RevocationListener.java | 5 +-
.../framework/recipes/locks/RevocationSpec.java | 16 +-
.../curator/framework/recipes/locks/Revoker.java | 17 +-
.../recipes/locks/StandardLockInternalsDriver.java | 55 +-
.../framework/recipes/nodes/GroupMember.java | 61 +-
.../recipes/nodes/PersistentEphemeralNode.java | 101 +-
.../framework/recipes/nodes/PersistentNode.java | 374 ++---
.../framework/recipes/nodes/PersistentTtlNode.java | 142 +-
.../recipes/queue/BlockingQueueConsumer.java | 43 +-
.../framework/recipes/queue/ChildrenCache.java | 103 +-
.../recipes/queue/DistributedDelayQueue.java | 149 +-
.../recipes/queue/DistributedIdQueue.java | 194 ++-
.../recipes/queue/DistributedPriorityQueue.java | 86 +-
.../framework/recipes/queue/DistributedQueue.java | 514 +++----
.../curator/framework/recipes/queue/ErrorMode.java | 3 +-
.../framework/recipes/queue/ItemSerializer.java | 76 +-
.../curator/framework/recipes/queue/MultiItem.java | 5 +-
.../framework/recipes/queue/QueueAllocator.java | 5 +-
.../curator/framework/recipes/queue/QueueBase.java | 9 +-
.../framework/recipes/queue/QueueBuilder.java | 157 +--
.../framework/recipes/queue/QueueConsumer.java | 5 +-
.../framework/recipes/queue/QueuePutListener.java | 7 +-
.../framework/recipes/queue/QueueSafety.java | 18 +-
.../framework/recipes/queue/QueueSerializer.java | 7 +-
.../framework/recipes/queue/QueueSharder.java | 201 ++-
.../recipes/queue/QueueSharderPolicies.java | 64 +-
.../recipes/queue/SimpleDistributedQueue.java | 145 +-
.../framework/recipes/shared/SharedCount.java | 69 +-
.../recipes/shared/SharedCountListener.java | 5 +-
.../recipes/shared/SharedCountReader.java | 5 +-
.../framework/recipes/shared/SharedValue.java | 139 +-
.../recipes/shared/SharedValueListener.java | 3 +-
.../recipes/shared/SharedValueReader.java | 5 +-
.../framework/recipes/shared/VersionedValue.java | 12 +-
.../framework/recipes/watch/PersistentWatcher.java | 69 +-
.../connection/TestThreadLocalRetryLoop.java | 96 +-
.../framework/client/TestBackgroundStates.java | 77 +-
.../TestResetConnectionWithBackgroundFailure.java | 48 +-
.../recipes/atomic/TestCachedAtomicCounter.java | 74 +-
.../recipes/atomic/TestDistributedAtomicLong.java | 236 ++--
.../recipes/barriers/TestDistributedBarrier.java | 202 ++-
.../barriers/TestDistributedDoubleBarrier.java | 262 ++--
.../framework/recipes/cache/BaseTestTreeCache.java | 119 +-
.../framework/recipes/cache/TestCuratorCache.java | 91 +-
.../recipes/cache/TestCuratorCacheBridge.java | 35 +-
.../recipes/cache/TestCuratorCacheConsistency.java | 243 ++--
.../recipes/cache/TestCuratorCacheEdges.java | 74 +-
.../cache/TestCuratorCacheEventOrdering.java | 18 +-
.../recipes/cache/TestCuratorCacheWrappers.java | 139 +-
.../framework/recipes/cache/TestEventOrdering.java | 123 +-
.../framework/recipes/cache/TestNodeCache.java | 218 ++-
.../recipes/cache/TestPathChildrenCache.java | 921 +++++-------
.../cache/TestPathChildrenCacheEventOrdering.java | 24 +-
.../cache/TestPathChildrenCacheInCluster.java | 122 +-
.../framework/recipes/cache/TestTreeCache.java | 125 +-
.../recipes/cache/TestTreeCacheEventOrdering.java | 27 +-
.../cache/TestTreeCacheIteratorAndSize.java | 83 +-
.../recipes/cache/TestTreeCacheRandomTree.java | 182 ++-
.../recipes/cache/TestWrappedNodeCache.java | 61 +-
.../recipes/leader/ChaosMonkeyCnxnFactory.java | 49 +-
.../framework/recipes/leader/TestLeaderAcls.java | 69 +-
.../framework/recipes/leader/TestLeaderLatch.java | 881 ++++++------
.../recipes/leader/TestLeaderLatchCluster.java | 71 +-
.../recipes/leader/TestLeaderSelector.java | 503 +++----
.../recipes/leader/TestLeaderSelectorCluster.java | 140 +-
.../recipes/leader/TestLeaderSelectorEdges.java | 155 +-
.../leader/TestLeaderSelectorParticipants.java | 115 +-
.../leader/TestLeaderSelectorWithExecutor.java | 69 +-
.../curator/framework/recipes/locks/Counter.java | 7 +-
.../framework/recipes/locks/SemaphoreClient.java | 87 +-
.../curator/framework/recipes/locks/Stepper.java | 14 +-
.../recipes/locks/TestInterProcessMultiMutex.java | 99 +-
.../recipes/locks/TestInterProcessMutex.java | 163 +--
.../recipes/locks/TestInterProcessMutexBase.java | 503 +++----
.../locks/TestInterProcessReadWriteLock.java | 318 ++---
.../recipes/locks/TestInterProcessSemaphore.java | 672 ++++-----
.../locks/TestInterProcessSemaphoreCluster.java | 275 ++--
.../locks/TestInterProcessSemaphoreMutex.java | 18 +-
.../framework/recipes/locks/TestLockACLs.java | 95 +-
.../locks/TestLockCleanlinessWithFaults.java | 32 +-
.../framework/recipes/nodes/TestGroupMember.java | 28 +-
.../recipes/nodes/TestPersistentEphemeralNode.java | 475 +++----
.../nodes/TestPersistentEphemeralNodeListener.java | 41 +-
.../recipes/nodes/TestPersistentNode.java | 99 +-
.../recipes/nodes/TestPersistentTtlNode.java | 91 +-
.../recipes/queue/QueueItemSerializer.java | 9 +-
.../framework/recipes/queue/QueueTestProducer.java | 14 +-
.../recipes/queue/TestBoundedDistributedQueue.java | 263 ++--
.../recipes/queue/TestDistributedDelayQueue.java | 188 ++-
.../recipes/queue/TestDistributedIdQueue.java | 120 +-
.../queue/TestDistributedPriorityQueue.java | 235 ++--
.../recipes/queue/TestDistributedQueue.java | 740 +++++-----
.../recipes/queue/TestLongNetworkPartition.java | 76 +-
.../framework/recipes/queue/TestQueueItem.java | 35 +-
.../framework/recipes/queue/TestQueueSharder.java | 181 ++-
.../recipes/queue/TestSimpleDistributedQueue.java | 279 ++--
.../framework/recipes/shared/TestSharedCount.java | 301 ++--
.../recipes/watch/TestPersistentWatcher.java | 50 +-
.../curator/framework/TestCompatibility.java | 20 +-
.../java/org/apache/curator/zk35/TestIs35.java | 10 +-
.../java/org/apache/curator/zk36/TestIs36.java | 13 +-
.../org/apache/curator/test/BaseClassForTests.java | 108 +-
.../org/apache/curator/test/Compatibility.java | 62 +-
.../curator/test/DelegatingExecutorService.java | 51 +-
.../org/apache/curator/test/DirectoryUtils.java | 16 +-
.../test/ExecuteCalledWatchingExecutorService.java | 15 +-
.../curator/test/FailedServerStartException.java | 9 +-
.../java/org/apache/curator/test/InstanceSpec.java | 189 +--
.../java/org/apache/curator/test/KillSession.java | 12 +-
.../apache/curator/test/QuorumConfigBuilder.java | 83 +-
.../curator/test/QuorumPeerConfigBuilder.java | 3 +-
.../java/org/apache/curator/test/ServerHelper.java | 120 +-
.../org/apache/curator/test/TestingCluster.java | 122 +-
.../apache/curator/test/TestingQuorumPeerMain.java | 63 +-
.../org/apache/curator/test/TestingServer.java | 47 +-
.../apache/curator/test/TestingZooKeeperMain.java | 207 +--
.../curator/test/TestingZooKeeperServer.java | 62 +-
.../main/java/org/apache/curator/test/Timing.java | 82 +-
.../org/apache/curator/test/WatchersDebug.java | 47 +-
.../org/apache/curator/test/ZooKeeperMainFace.java | 3 +-
.../test/ZooKeeperServerEmbeddedAdapter.java | 1 -
.../test/compatibility/CuratorTestBase.java | 3 +-
.../apache/curator/test/compatibility/Timing2.java | 118 +-
.../curator/test/TestQuorumConfigBuilder.java | 10 +-
.../org/apache/curator/test/TestTestingServer.java | 47 +-
.../curator/x/async/AsyncCuratorFramework.java | 19 +-
.../curator/x/async/AsyncEventException.java | 5 +-
.../org/apache/curator/x/async/AsyncResult.java | 18 +-
.../org/apache/curator/x/async/AsyncStage.java | 5 +-
.../org/apache/curator/x/async/AsyncWrappers.java | 174 +--
.../java/org/apache/curator/x/async/WatchMode.java | 3 +-
.../curator/x/async/api/AsyncCreateBuilder.java | 24 +-
.../x/async/api/AsyncCuratorFrameworkDsl.java | 3 +-
.../curator/x/async/api/AsyncDeleteBuilder.java | 5 +-
.../curator/x/async/api/AsyncEnsemblable.java | 3 +-
.../curator/x/async/api/AsyncExistsBuilder.java | 5 +-
.../curator/x/async/api/AsyncGetACLBuilder.java | 5 +-
.../x/async/api/AsyncGetChildrenBuilder.java | 5 +-
.../curator/x/async/api/AsyncGetConfigBuilder.java | 3 +-
.../curator/x/async/api/AsyncGetDataBuilder.java | 3 +-
.../curator/x/async/api/AsyncMultiTransaction.java | 5 +-
.../curator/x/async/api/AsyncPathAndBytesable.java | 3 +-
.../apache/curator/x/async/api/AsyncPathable.java | 3 +-
.../curator/x/async/api/AsyncReconfigBuilder.java | 11 +-
.../x/async/api/AsyncRemoveWatchesBuilder.java | 11 +-
.../curator/x/async/api/AsyncSetACLBuilder.java | 5 +-
.../curator/x/async/api/AsyncSetDataBuilder.java | 3 +-
.../curator/x/async/api/AsyncSyncBuilder.java | 5 +-
.../x/async/api/AsyncTransactionCheckBuilder.java | 3 +-
.../x/async/api/AsyncTransactionCreateBuilder.java | 8 +-
.../x/async/api/AsyncTransactionDeleteBuilder.java | 3 +-
.../curator/x/async/api/AsyncTransactionOp.java | 3 +-
.../async/api/AsyncTransactionSetDataBuilder.java | 3 +-
.../curator/x/async/api/AsyncWatchBuilder.java | 8 +-
.../curator/x/async/api/AsyncWatchBuilder2.java | 7 +-
.../apache/curator/x/async/api/CreateOption.java | 3 +-
.../apache/curator/x/async/api/DeleteOption.java | 3 +-
.../apache/curator/x/async/api/ExistsOption.java | 3 +-
.../curator/x/async/api/RemoveWatcherOption.java | 3 +-
.../async/api/WatchableAsyncCuratorFramework.java | 3 +-
.../x/async/details/AsyncCreateBuilderImpl.java | 98 +-
.../x/async/details/AsyncCuratorFrameworkImpl.java | 146 +-
.../x/async/details/AsyncDeleteBuilderImpl.java | 37 +-
.../x/async/details/AsyncExistsBuilderImpl.java | 35 +-
.../async/details/AsyncGetChildrenBuilderImpl.java | 19 +-
.../x/async/details/AsyncGetConfigBuilderImpl.java | 17 +-
.../x/async/details/AsyncGetDataBuilderImpl.java | 26 +-
.../x/async/details/AsyncReconfigBuilderImpl.java | 46 +-
.../details/AsyncRemoveWatchesBuilderImpl.java | 77 +-
.../curator/x/async/details/AsyncResultImpl.java | 72 +-
.../x/async/details/AsyncSetACLBuilderImpl.java | 22 +-
.../x/async/details/AsyncSetDataBuilderImpl.java | 29 +-
.../x/async/details/AsyncTransactionOpImpl.java | 139 +-
.../x/async/details/AsyncWatchBuilderImpl.java | 29 +-
.../curator/x/async/details/BackgroundProc.java | 6 +-
.../curator/x/async/details/BackgroundProcs.java | 46 +-
.../curator/x/async/details/BuilderCommon.java | 11 +-
.../apache/curator/x/async/details/Filters.java | 20 +-
.../curator/x/async/details/InternalCallback.java | 19 +-
.../curator/x/async/details/InternalWatcher.java | 47 +-
.../curator/x/async/migrations/Migration.java | 5 +-
.../x/async/migrations/MigrationException.java | 9 +-
.../x/async/migrations/MigrationManager.java | 121 +-
.../curator/x/async/migrations/MigrationSet.java | 15 +-
.../x/async/modeled/JacksonModelSerializer.java | 54 +-
.../curator/x/async/modeled/ModelSerializer.java | 12 +-
.../apache/curator/x/async/modeled/ModelSpec.java | 24 +-
.../curator/x/async/modeled/ModelSpecBuilder.java | 38 +-
.../curator/x/async/modeled/ModeledFramework.java | 16 +-
.../x/async/modeled/ModeledFrameworkBuilder.java | 53 +-
.../curator/x/async/modeled/ModeledOptions.java | 3 +-
.../apache/curator/x/async/modeled/NodeName.java | 11 +-
.../apache/curator/x/async/modeled/Resolvable.java | 6 +-
.../org/apache/curator/x/async/modeled/ZNode.java | 13 +-
.../org/apache/curator/x/async/modeled/ZPath.java | 41 +-
.../modeled/cached/CachedModeledFramework.java | 7 +-
.../x/async/modeled/cached/ModeledCache.java | 7 +-
.../async/modeled/cached/ModeledCacheListener.java | 27 +-
.../details/CachedModeledFrameworkImpl.java | 199 +--
.../x/async/modeled/details/ModelSpecImpl.java | 144 +-
.../x/async/modeled/details/ModelStage.java | 80 +-
.../x/async/modeled/details/ModeledCacheImpl.java | 189 ++-
.../modeled/details/ModeledFrameworkImpl.java | 377 +++--
.../details/VersionedModeledFrameworkImpl.java | 37 +-
.../curator/x/async/modeled/details/ZNodeImpl.java | 17 +-
.../curator/x/async/modeled/details/ZPathImpl.java | 186 +--
.../x/async/modeled/typed/TypedModelSpec.java | 9 +-
.../x/async/modeled/typed/TypedModelSpec0.java | 9 +-
.../x/async/modeled/typed/TypedModelSpec10.java | 21 +-
.../x/async/modeled/typed/TypedModelSpec2.java | 9 +-
.../x/async/modeled/typed/TypedModelSpec3.java | 10 +-
.../x/async/modeled/typed/TypedModelSpec4.java | 17 +-
.../x/async/modeled/typed/TypedModelSpec5.java | 17 +-
.../x/async/modeled/typed/TypedModelSpec6.java | 17 +-
.../x/async/modeled/typed/TypedModelSpec7.java | 17 +-
.../x/async/modeled/typed/TypedModelSpec8.java | 17 +-
.../x/async/modeled/typed/TypedModelSpec9.java | 19 +-
.../async/modeled/typed/TypedModeledFramework.java | 21 +-
.../modeled/typed/TypedModeledFramework0.java | 21 +-
.../modeled/typed/TypedModeledFramework10.java | 32 +-
.../modeled/typed/TypedModeledFramework2.java | 21 +-
.../modeled/typed/TypedModeledFramework3.java | 21 +-
.../modeled/typed/TypedModeledFramework4.java | 21 +-
.../modeled/typed/TypedModeledFramework5.java | 21 +-
.../modeled/typed/TypedModeledFramework6.java | 21 +-
.../modeled/typed/TypedModeledFramework7.java | 24 +-
.../modeled/typed/TypedModeledFramework8.java | 24 +-
.../modeled/typed/TypedModeledFramework9.java | 28 +-
.../curator/x/async/modeled/typed/TypedZPath.java | 9 +-
.../curator/x/async/modeled/typed/TypedZPath0.java | 9 +-
.../x/async/modeled/typed/TypedZPath10.java | 11 +-
.../curator/x/async/modeled/typed/TypedZPath2.java | 9 +-
.../curator/x/async/modeled/typed/TypedZPath3.java | 9 +-
.../curator/x/async/modeled/typed/TypedZPath4.java | 9 +-
.../curator/x/async/modeled/typed/TypedZPath5.java | 9 +-
.../curator/x/async/modeled/typed/TypedZPath6.java | 9 +-
.../curator/x/async/modeled/typed/TypedZPath7.java | 9 +-
.../curator/x/async/modeled/typed/TypedZPath8.java | 9 +-
.../curator/x/async/modeled/typed/TypedZPath9.java | 10 +-
.../x/async/modeled/versioned/Versioned.java | 18 +-
.../versioned/VersionedModeledFramework.java | 3 +-
.../curator/framework/imps/TestAddWatch.java | 33 +-
.../curator/framework/imps/TestFramework.java | 629 +++++----
.../framework/imps/TestFrameworkBackground.java | 169 +--
.../x/async/CompletableBaseClassForTests.java | 44 +-
.../apache/curator/x/async/TestAsyncWrappers.java | 39 +-
.../curator/x/async/TestBasicOperations.java | 83 +-
.../x/async/migrations/TestMigrationManager.java | 162 +--
.../curator/x/async/migrations/models/ModelV1.java | 12 +-
.../curator/x/async/migrations/models/ModelV2.java | 15 +-
.../curator/x/async/migrations/models/ModelV3.java | 18 +-
.../async/modeled/TestCachedModeledFramework.java | 135 +-
.../x/async/modeled/TestModeledFramework.java | 144 +-
.../x/async/modeled/TestModeledFrameworkBase.java | 12 +-
.../apache/curator/x/async/modeled/TestZPath.java | 37 +-
.../curator/x/async/modeled/models/TestModel.java | 50 +-
.../x/async/modeled/models/TestNewerModel.java | 71 +-
.../x/async/modeled/models/TestSimpleModel.java | 35 +-
.../server/contexts/GenericDiscoveryContext.java | 50 +-
.../server/contexts/IntegerDiscoveryContext.java | 37 +-
.../server/contexts/MapDiscoveryContext.java | 18 +-
.../server/contexts/StringDiscoveryContext.java | 34 +-
.../entity/JsonServiceInstanceMarshaller.java | 105 +-
.../entity/JsonServiceInstancesMarshaller.java | 81 +-
.../server/entity/JsonServiceNamesMarshaller.java | 53 +-
.../discovery/server/entity/ServiceInstances.java | 14 +-
.../x/discovery/server/entity/ServiceNames.java | 12 +-
.../x/discovery/server/rest/DiscoveryContext.java | 13 +-
.../x/discovery/server/rest/DiscoveryResource.java | 148 +-
.../x/discovery/server/rest/InstanceCleanup.java | 91 +-
.../server/jetty_jersey/MapDiscoveryResource.java | 12 +-
.../server/jetty_jersey/ServiceDetails.java | 98 +-
.../ServiceDetailsDiscoveryContext.java | 14 +-
.../ServiceDetailsDiscoveryResource.java | 7 +-
.../jetty_jersey/StringDiscoveryResource.java | 10 +-
.../server/jetty_jersey/TestMapsWithJersey.java | 77 +-
.../jetty_jersey/TestObjectPayloadWithJersey.java | 74 +-
.../server/jetty_jersey/TestStringsWithJersey.java | 79 +-
.../server/jetty_resteasy/RestEasyApplication.java | 18 +-
.../server/jetty_resteasy/RestEasySingletons.java | 14 +-
.../jetty_resteasy/StringDiscoveryResource.java | 16 +-
.../jetty_resteasy/TestStringsWithRestEasy.java | 101 +-
.../server/mocks/MockServiceDiscovery.java | 61 +-
.../curator/x/discovery/DownInstancePolicy.java | 15 +-
.../apache/curator/x/discovery/InstanceFilter.java | 4 +-
.../apache/curator/x/discovery/LocalIpFilter.java | 5 +-
.../curator/x/discovery/ProviderStrategy.java | 5 +-
.../apache/curator/x/discovery/ServiceCache.java | 9 +-
.../curator/x/discovery/ServiceCacheBuilder.java | 3 +-
.../curator/x/discovery/ServiceDiscovery.java | 13 +-
.../x/discovery/ServiceDiscoveryBuilder.java | 30 +-
.../curator/x/discovery/ServiceInstance.java | 173 ++-
.../x/discovery/ServiceInstanceBuilder.java | 81 +-
.../curator/x/discovery/ServiceProvider.java | 5 +-
.../x/discovery/ServiceProviderBuilder.java | 5 +-
.../apache/curator/x/discovery/ServiceType.java | 11 +-
.../org/apache/curator/x/discovery/UriSpec.java | 176 +--
.../x/discovery/details/DownInstanceManager.java | 38 +-
.../details/FilteredInstanceProvider.java | 11 +-
.../x/discovery/details/InstanceProvider.java | 7 +-
.../x/discovery/details/InstanceSerializer.java | 5 +-
.../discovery/details/JsonInstanceSerializer.java | 35 +-
.../apache/curator/x/discovery/details/Latch.java | 14 +-
.../x/discovery/details/OldServiceInstance.java | 95 +-
.../discovery/details/ServiceCacheBuilderImpl.java | 29 +-
.../x/discovery/details/ServiceCacheImpl.java | 132 +-
.../x/discovery/details/ServiceCacheListener.java | 3 +-
.../x/discovery/details/ServiceDiscoveryImpl.java | 334 ++---
.../details/ServiceProviderBuilderImpl.java | 36 +-
.../x/discovery/details/ServiceProviderImpl.java | 55 +-
.../x/discovery/strategies/RandomStrategy.java | 21 +-
.../x/discovery/strategies/RoundRobinStrategy.java | 21 +-
.../x/discovery/strategies/StickyStrategy.java | 54 +-
.../x/discovery/ServiceCacheLeakTester.java | 50 +-
.../x/discovery/TestJsonInstanceSerializer.java | 128 +-
.../curator/x/discovery/TestLocalIpFilter.java | 32 +-
.../curator/x/discovery/TestServiceCache.java | 251 ++--
.../apache/curator/x/discovery/TestStrategies.java | 94 +-
.../apache/curator/x/discovery/TestUriSpec.java | 45 +-
.../discovery/details/TestDownInstanceManager.java | 35 +-
.../TestJsonInstanceSerializerCompatibility.java | 103 +-
.../discovery/details/TestNewServiceInstance.java | 69 +-
.../x/discovery/details/TestServiceCacheRace.java | 89 +-
.../x/discovery/details/TestServiceDiscovery.java | 256 ++--
.../details/TestServiceDiscoveryBuilder.java | 31 +-
.../x/discovery/details/TestServiceProvider.java | 69 +-
.../x/discovery/details/TestWatchedInstances.java | 58 +-
pom.xml | 30 +
694 files changed, 21271 insertions(+), 29270 deletions(-)
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index e7678802..7806dfd1 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -34,6 +34,21 @@ jobs:
- name: Check license header
run: docker run --rm -v $(pwd):/github/workspace -u $(id -u):$(id -g) ghcr.io/korandoru/hawkeye-native:v1 check
+ - name: Cache Local Maven Repository
+ uses: actions/cache@v3
+ with:
+ path: ~/.m2/repository
+ key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }}
+ restore-keys: |
+ ${{ runner.os }}-maven-
+ - name: Set up JDK
+ uses: actions/setup-java@v3
+ with:
+ java-version: 17
+ distribution: 'temurin'
+ - name: Check code style
+ run: ./mvnw spotless:check
+
unittest:
name: Unit tests
runs-on: ubuntu-latest
diff --git a/curator-client/src/main/java/org/apache/curator/ConnectionState.java b/curator-client/src/main/java/org/apache/curator/ConnectionState.java
index 88325f22..d367d50d 100644
--- a/curator-client/src/main/java/org/apache/curator/ConnectionState.java
+++ b/curator-client/src/main/java/org/apache/curator/ConnectionState.java
@@ -19,6 +19,14 @@
package org.apache.curator;
+import java.io.Closeable;
+import java.io.IOException;
+import java.util.Queue;
+import java.util.concurrent.ConcurrentLinkedQueue;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicLong;
+import java.util.concurrent.atomic.AtomicReference;
import org.apache.curator.drivers.EventTrace;
import org.apache.curator.drivers.OperationTrace;
import org.apache.curator.drivers.TracerDriver;
@@ -32,17 +40,8 @@ import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.io.Closeable;
-import java.io.IOException;
-import java.util.Queue;
-import java.util.concurrent.ConcurrentLinkedQueue;
-import java.util.concurrent.atomic.AtomicBoolean;
-import java.util.concurrent.atomic.AtomicInteger;
-import java.util.concurrent.atomic.AtomicLong;
-import java.util.concurrent.atomic.AtomicReference;
-class ConnectionState implements Watcher, Closeable
-{
+class ConnectionState implements Watcher, Closeable {
private static final int MAX_BACKGROUND_EXCEPTIONS = 10;
private static final boolean LOG_EVENTS = Boolean.getBoolean(DebugUtils.PROPERTY_LOG_EVENTS);
private static final Logger log = LoggerFactory.getLogger(ConnectionState.class);
@@ -56,48 +55,46 @@ class ConnectionState implements Watcher, Closeable
private final AtomicLong instanceIndex = new AtomicLong();
private volatile long connectionStartMs = 0;
- ConnectionState(ZookeeperFactory zookeeperFactory, EnsembleProvider ensembleProvider, int sessionTimeoutMs, Watcher parentWatcher, AtomicReference<TracerDriver> tracer, boolean canBeReadOnly)
- {
+ ConnectionState(
+ ZookeeperFactory zookeeperFactory,
+ EnsembleProvider ensembleProvider,
+ int sessionTimeoutMs,
+ Watcher parentWatcher,
+ AtomicReference<TracerDriver> tracer,
+ boolean canBeReadOnly) {
this.ensembleProvider = ensembleProvider;
this.tracer = tracer;
- if ( parentWatcher != null )
- {
+ if (parentWatcher != null) {
parentWatchers.offer(parentWatcher);
}
handleHolder = new HandleHolder(zookeeperFactory, this, ensembleProvider, sessionTimeoutMs, canBeReadOnly);
}
- ZooKeeper getZooKeeper() throws Exception
- {
- if ( SessionFailRetryLoop.sessionForThreadHasFailed() )
- {
+ ZooKeeper getZooKeeper() throws Exception {
+ if (SessionFailRetryLoop.sessionForThreadHasFailed()) {
throw new SessionFailRetryLoop.SessionFailedException();
}
Exception exception = backgroundExceptions.poll();
- if ( exception != null )
- {
+ if (exception != null) {
new EventTrace("background-exceptions", tracer.get()).commit();
throw exception;
}
boolean localIsConnected = isConnected.get();
- if ( !localIsConnected )
- {
+ if (!localIsConnected) {
checkNewConnectionString();
}
return handleHolder.getZooKeeper();
}
- boolean isConnected()
- {
+ boolean isConnected() {
return isConnected.get();
}
- void start() throws Exception
- {
+ void start() throws Exception {
log.debug("Starting");
ensembleProvider.start();
reset();
@@ -107,85 +104,68 @@ class ConnectionState implements Watcher, Closeable
public void close() throws IOException {
close(0);
}
-
+
public void close(int waitForShutdownTimeoutMs) throws IOException {
log.debug("Closing");
CloseableUtils.closeQuietly(ensembleProvider);
- try
- {
+ try {
handleHolder.closeAndClear(waitForShutdownTimeoutMs);
- }
- catch ( Exception e )
- {
+ } catch (Exception e) {
ThreadUtils.checkInterrupted(e);
throw new IOException(e);
- }
- finally
- {
+ } finally {
isConnected.set(false);
}
}
- void addParentWatcher(Watcher watcher)
- {
+ void addParentWatcher(Watcher watcher) {
parentWatchers.offer(watcher);
}
- void removeParentWatcher(Watcher watcher)
- {
+ void removeParentWatcher(Watcher watcher) {
parentWatchers.remove(watcher);
}
- long getInstanceIndex()
- {
+ long getInstanceIndex() {
return instanceIndex.get();
}
- int getLastNegotiatedSessionTimeoutMs()
- {
+ int getLastNegotiatedSessionTimeoutMs() {
return lastNegotiatedSessionTimeoutMs.get();
}
@Override
- public void process(WatchedEvent event)
- {
- if ( LOG_EVENTS )
- {
+ public void process(WatchedEvent event) {
+ if (LOG_EVENTS) {
log.debug("ConnectState watcher: " + event);
}
- if ( event.getType() == Watcher.Event.EventType.None )
- {
+ if (event.getType() == Watcher.Event.EventType.None) {
boolean wasConnected = isConnected.get();
boolean newIsConnected = checkState(event.getState(), wasConnected);
- if ( newIsConnected != wasConnected )
- {
+ if (newIsConnected != wasConnected) {
isConnected.set(newIsConnected);
connectionStartMs = System.currentTimeMillis();
- if ( newIsConnected )
- {
+ if (newIsConnected) {
lastNegotiatedSessionTimeoutMs.set(handleHolder.getNegotiatedSessionTimeoutMs());
log.debug("Negotiated session timeout: " + lastNegotiatedSessionTimeoutMs.get());
}
}
}
- for ( Watcher parentWatcher : parentWatchers )
- {
+ for (Watcher parentWatcher : parentWatchers) {
OperationTrace trace = new OperationTrace("connection-state-parent-process", tracer.get(), getSessionId());
parentWatcher.process(event);
trace.commit();
}
}
- EnsembleProvider getEnsembleProvider()
- {
+ EnsembleProvider getEnsembleProvider() {
return ensembleProvider;
}
- synchronized void reset() throws Exception
- {
+ synchronized void reset() throws Exception {
log.debug("reset");
instanceIndex.incrementAndGet();
@@ -193,15 +173,13 @@ class ConnectionState implements Watcher, Closeable
isConnected.set(false);
connectionStartMs = System.currentTimeMillis();
handleHolder.closeAndReset();
- handleHolder.getZooKeeper(); // initiate connection
+ handleHolder.getZooKeeper(); // initiate connection
}
- private synchronized void checkNewConnectionString()
- {
+ private synchronized void checkNewConnectionString() {
final String newConnectionString = handleHolder.getNewConnectionString();
- if (newConnectionString != null)
- {
+ if (newConnectionString != null) {
handleNewConnectionString(newConnectionString);
}
}
@@ -222,57 +200,48 @@ class ConnectionState implements Watcher, Closeable
return sessionId;
}
- private boolean checkState(Event.KeeperState state, boolean wasConnected)
- {
+ private boolean checkState(Event.KeeperState state, boolean wasConnected) {
boolean isConnected = wasConnected;
boolean checkNewConnectionString = true;
- switch ( state )
- {
- default:
- case Disconnected:
- {
- isConnected = false;
- break;
- }
+ switch (state) {
+ default:
+ case Disconnected: {
+ isConnected = false;
+ break;
+ }
- case SyncConnected:
- case ConnectedReadOnly:
- {
- isConnected = true;
- break;
- }
+ case SyncConnected:
+ case ConnectedReadOnly: {
+ isConnected = true;
+ break;
+ }
- case AuthFailed:
- {
- isConnected = false;
- log.error("Authentication failed");
- break;
- }
+ case AuthFailed: {
+ isConnected = false;
+ log.error("Authentication failed");
+ break;
+ }
- case Expired:
- {
- isConnected = false;
- checkNewConnectionString = false;
- handleExpiredSession();
- break;
- }
+ case Expired: {
+ isConnected = false;
+ checkNewConnectionString = false;
+ handleExpiredSession();
+ break;
+ }
- case SaslAuthenticated:
- {
- // NOP
- break;
- }
+ case SaslAuthenticated: {
+ // NOP
+ break;
+ }
}
// the session expired is logged in handleExpiredSession, so not log here
if (state != Event.KeeperState.Expired) {
new EventTrace(state.toString(), tracer.get(), getSessionId()).commit();
}
- if ( checkNewConnectionString )
- {
+ if (checkNewConnectionString) {
String newConnectionString = handleHolder.getNewConnectionString();
- if ( newConnectionString != null )
- {
+ if (newConnectionString != null) {
handleNewConnectionString(newConnectionString);
}
}
@@ -280,59 +249,43 @@ class ConnectionState implements Watcher, Closeable
return isConnected;
}
- private void handleNewConnectionString(String newConnectionString)
- {
+ private void handleNewConnectionString(String newConnectionString) {
log.info("Connection string changed to: " + newConnectionString);
new EventTrace("connection-string-changed", tracer.get(), getSessionId()).commit();
- try
- {
+ try {
ZooKeeper zooKeeper = handleHolder.getZooKeeper();
- if ( zooKeeper == null )
- {
+ if (zooKeeper == null) {
log.warn("Could not update the connection string because getZooKeeper() returned null.");
- }
- else
- {
- if ( ensembleProvider.updateServerListEnabled() )
- {
+ } else {
+ if (ensembleProvider.updateServerListEnabled()) {
zooKeeper.updateServerList(newConnectionString);
handleHolder.resetConnectionString(newConnectionString);
- }
- else
- {
+ } else {
reset();
}
}
- }
- catch ( Exception e )
- {
+ } catch (Exception e) {
ThreadUtils.checkInterrupted(e);
queueBackgroundException(e);
}
}
- private void handleExpiredSession()
- {
+ private void handleExpiredSession() {
log.warn("Session expired event received");
new EventTrace("session-expired", tracer.get(), getSessionId()).commit();
- try
- {
+ try {
reset();
- }
- catch ( Exception e )
- {
+ } catch (Exception e) {
ThreadUtils.checkInterrupted(e);
queueBackgroundException(e);
}
}
@SuppressWarnings({"ThrowableResultOfMethodCallIgnored"})
- private void queueBackgroundException(Exception e)
- {
- while ( backgroundExceptions.size() >= MAX_BACKGROUND_EXCEPTIONS )
- {
+ private void queueBackgroundException(Exception e) {
+ while (backgroundExceptions.size() >= MAX_BACKGROUND_EXCEPTIONS) {
backgroundExceptions.poll();
}
backgroundExceptions.offer(e);
diff --git a/curator-client/src/main/java/org/apache/curator/CuratorConnectionLossException.java b/curator-client/src/main/java/org/apache/curator/CuratorConnectionLossException.java
index 2df63f42..91d7626c 100644
--- a/curator-client/src/main/java/org/apache/curator/CuratorConnectionLossException.java
+++ b/curator-client/src/main/java/org/apache/curator/CuratorConnectionLossException.java
@@ -21,7 +21,6 @@ package org.apache.curator;
import org.apache.zookeeper.KeeperException;
-public class CuratorConnectionLossException extends KeeperException.ConnectionLossException
-{
- private static final long serialVersionUID = 1L;
+public class CuratorConnectionLossException extends KeeperException.ConnectionLossException {
+ private static final long serialVersionUID = 1L;
}
diff --git a/curator-client/src/main/java/org/apache/curator/CuratorZookeeperClient.java b/curator-client/src/main/java/org/apache/curator/CuratorZookeeperClient.java
index 51cad402..ecb072f6 100644
--- a/curator-client/src/main/java/org/apache/curator/CuratorZookeeperClient.java
+++ b/curator-client/src/main/java/org/apache/curator/CuratorZookeeperClient.java
@@ -20,6 +20,12 @@
package org.apache.curator;
import com.google.common.base.Preconditions;
+import java.io.Closeable;
+import java.io.IOException;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicReference;
import org.apache.curator.drivers.OperationTrace;
import org.apache.curator.drivers.TracerDriver;
import org.apache.curator.ensemble.EnsembleProvider;
@@ -33,19 +39,12 @@ import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.io.Closeable;
-import java.io.IOException;
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.atomic.AtomicBoolean;
-import java.util.concurrent.atomic.AtomicReference;
/**
* A wrapper around Zookeeper that takes care of some low-level housekeeping
*/
@SuppressWarnings("UnusedDeclaration")
-public class CuratorZookeeperClient implements Closeable
-{
+public class CuratorZookeeperClient implements Closeable {
private final Logger log = LoggerFactory.getLogger(getClass());
private final ConnectionState state;
private final AtomicReference<RetryPolicy> retryPolicy = new AtomicReference<RetryPolicy>();
@@ -62,9 +61,20 @@ public class CuratorZookeeperClient implements Closeable
* @param watcher default watcher or null
* @param retryPolicy the retry policy to use
*/
- public CuratorZookeeperClient(String connectString, int sessionTimeoutMs, int connectionTimeoutMs, Watcher watcher, RetryPolicy retryPolicy)
- {
- this(new DefaultZookeeperFactory(), new FixedEnsembleProvider(connectString), sessionTimeoutMs, connectionTimeoutMs, watcher, retryPolicy, false);
+ public CuratorZookeeperClient(
+ String connectString,
+ int sessionTimeoutMs,
+ int connectionTimeoutMs,
+ Watcher watcher,
+ RetryPolicy retryPolicy) {
+ this(
+ new DefaultZookeeperFactory(),
+ new FixedEnsembleProvider(connectString),
+ sessionTimeoutMs,
+ connectionTimeoutMs,
+ watcher,
+ retryPolicy,
+ false);
}
/**
@@ -74,9 +84,20 @@ public class CuratorZookeeperClient implements Closeable
* @param watcher default watcher or null
* @param retryPolicy the retry policy to use
*/
- public CuratorZookeeperClient(EnsembleProvider ensembleProvider, int sessionTimeoutMs, int connectionTimeoutMs, Watcher watcher, RetryPolicy retryPolicy)
- {
- this(new DefaultZookeeperFactory(), ensembleProvider, sessionTimeoutMs, connectionTimeoutMs, watcher, retryPolicy, false);
+ public CuratorZookeeperClient(
+ EnsembleProvider ensembleProvider,
+ int sessionTimeoutMs,
+ int connectionTimeoutMs,
+ Watcher watcher,
+ RetryPolicy retryPolicy) {
+ this(
+ new DefaultZookeeperFactory(),
+ ensembleProvider,
+ sessionTimeoutMs,
+ connectionTimeoutMs,
+ watcher,
+ retryPolicy,
+ false);
}
/**
@@ -91,9 +112,23 @@ public class CuratorZookeeperClient implements Closeable
* {@link ZooKeeper#ZooKeeper(String, int, Watcher, long, byte[], boolean)}
* for details
*/
- public CuratorZookeeperClient(ZookeeperFactory zookeeperFactory, EnsembleProvider ensembleProvider, int sessionTimeoutMs, int connectionTimeoutMs, Watcher watcher, RetryPolicy retryPolicy, boolean canBeReadOnly)
- {
- this(zookeeperFactory, ensembleProvider, sessionTimeoutMs, connectionTimeoutMs, 0, watcher, retryPolicy, canBeReadOnly);
+ public CuratorZookeeperClient(
+ ZookeeperFactory zookeeperFactory,
+ EnsembleProvider ensembleProvider,
+ int sessionTimeoutMs,
+ int connectionTimeoutMs,
+ Watcher watcher,
+ RetryPolicy retryPolicy,
+ boolean canBeReadOnly) {
+ this(
+ zookeeperFactory,
+ ensembleProvider,
+ sessionTimeoutMs,
+ connectionTimeoutMs,
+ 0,
+ watcher,
+ retryPolicy,
+ canBeReadOnly);
}
/**
@@ -110,13 +145,19 @@ public class CuratorZookeeperClient implements Closeable
* for details
* @since 4.0.2
*/
- public CuratorZookeeperClient(ZookeeperFactory zookeeperFactory, EnsembleProvider ensembleProvider,
- int sessionTimeoutMs, int connectionTimeoutMs, int waitForShutdownTimeoutMs, Watcher watcher,
- RetryPolicy retryPolicy, boolean canBeReadOnly)
- {
- if ( sessionTimeoutMs < connectionTimeoutMs )
- {
- log.warn(String.format("session timeout [%d] is less than connection timeout [%d]", sessionTimeoutMs, connectionTimeoutMs));
+ public CuratorZookeeperClient(
+ ZookeeperFactory zookeeperFactory,
+ EnsembleProvider ensembleProvider,
+ int sessionTimeoutMs,
+ int connectionTimeoutMs,
+ int waitForShutdownTimeoutMs,
+ Watcher watcher,
+ RetryPolicy retryPolicy,
+ boolean canBeReadOnly) {
+ if (sessionTimeoutMs < connectionTimeoutMs) {
+ log.warn(String.format(
+ "session timeout [%d] is less than connection timeout [%d]",
+ sessionTimeoutMs, connectionTimeoutMs));
}
retryPolicy = Preconditions.checkNotNull(retryPolicy, "retryPolicy cannot be null");
@@ -124,7 +165,8 @@ public class CuratorZookeeperClient implements Closeable
this.connectionTimeoutMs = connectionTimeoutMs;
this.waitForShutdownTimeoutMs = waitForShutdownTimeoutMs;
- state = new ConnectionState(zookeeperFactory, ensembleProvider, sessionTimeoutMs, watcher, tracer, canBeReadOnly);
+ state = new ConnectionState(
+ zookeeperFactory, ensembleProvider, sessionTimeoutMs, watcher, tracer, canBeReadOnly);
setRetryPolicy(retryPolicy);
}
@@ -134,8 +176,7 @@ public class CuratorZookeeperClient implements Closeable
* @return client the client
* @throws Exception if the connection timeout has elapsed or an exception occurs in a background process
*/
- public ZooKeeper getZooKeeper() throws Exception
- {
+ public ZooKeeper getZooKeeper() throws Exception {
Preconditions.checkState(started.get(), "Client is not started");
return state.getZooKeeper();
@@ -146,8 +187,7 @@ public class CuratorZookeeperClient implements Closeable
*
* @return new retry loop
*/
- public RetryLoop newRetryLoop()
- {
+ public RetryLoop newRetryLoop() {
return new RetryLoopImpl(retryPolicy.get(), tracer);
}
@@ -158,8 +198,7 @@ public class CuratorZookeeperClient implements Closeable
* @param mode failure mode
* @return new retry loop
*/
- public SessionFailRetryLoop newSessionFailRetryLoop(SessionFailRetryLoop.Mode mode)
- {
+ public SessionFailRetryLoop newSessionFailRetryLoop(SessionFailRetryLoop.Mode mode) {
return new SessionFailRetryLoop(this, mode);
}
@@ -168,8 +207,7 @@ public class CuratorZookeeperClient implements Closeable
*
* @return true/false
*/
- public boolean isConnected()
- {
+ public boolean isConnected() {
return state.isConnected();
}
@@ -180,12 +218,11 @@ public class CuratorZookeeperClient implements Closeable
* @return true if the connection succeeded, false if not
* @throws InterruptedException interrupted while waiting
*/
- public boolean blockUntilConnectedOrTimedOut() throws InterruptedException
- {
+ public boolean blockUntilConnectedOrTimedOut() throws InterruptedException {
Preconditions.checkState(started.get(), "Client is not started");
log.debug("blockUntilConnectedOrTimedOut() start");
- OperationTrace trace = startAdvancedTracer("blockUntilConnectedOrTimedOut");
+ OperationTrace trace = startAdvancedTracer("blockUntilConnectedOrTimedOut");
internalBlockUntilConnectedOrTimedOut();
@@ -202,18 +239,16 @@ public class CuratorZookeeperClient implements Closeable
*
* @throws IOException errors
*/
- public void start() throws Exception
- {
+ public void start() throws Exception {
log.debug("Starting");
- if ( !started.compareAndSet(false, true) )
- {
+ if (!started.compareAndSet(false, true)) {
throw new IllegalStateException("Already started");
}
state.start();
}
-
+
/**
* Close the client.
*
@@ -225,25 +260,21 @@ public class CuratorZookeeperClient implements Closeable
public void close() {
close(waitForShutdownTimeoutMs);
}
-
+
/**
* Close this client object as the {@link #close() } method.
* This method will wait for internal resources to be released.
- *
+ *
* @param waitForShutdownTimeoutMs timeout (in milliseconds) to wait for resources to be released.
* Use zero or a negative value to skip the wait.
*/
- public void close(int waitForShutdownTimeoutMs)
- {
+ public void close(int waitForShutdownTimeoutMs) {
log.debug("Closing, waitForShutdownTimeoutMs {}", waitForShutdownTimeoutMs);
started.set(false);
- try
- {
+ try {
state.close(waitForShutdownTimeoutMs);
- }
- catch ( IOException e )
- {
+ } catch (IOException e) {
ThreadUtils.checkInterrupted(e);
log.error("", e);
}
@@ -254,8 +285,7 @@ public class CuratorZookeeperClient implements Closeable
*
* @param policy new policy
*/
- public void setRetryPolicy(RetryPolicy policy)
- {
+ public void setRetryPolicy(RetryPolicy policy) {
Preconditions.checkNotNull(policy, "policy cannot be null");
retryPolicy.set(policy);
@@ -266,8 +296,7 @@ public class CuratorZookeeperClient implements Closeable
*
* @return policy
*/
- public RetryPolicy getRetryPolicy()
- {
+ public RetryPolicy getRetryPolicy() {
return retryPolicy.get();
}
@@ -276,8 +305,7 @@ public class CuratorZookeeperClient implements Closeable
* @param name name of the event
* @return the new tracer ({@link TimeTrace#commit()} must be called)
*/
- public TimeTrace startTracer(String name)
- {
+ public TimeTrace startTracer(String name) {
return new TimeTrace(name, tracer.get());
}
@@ -286,8 +314,7 @@ public class CuratorZookeeperClient implements Closeable
* @param name name of the event
* @return the new tracer ({@link OperationTrace#commit()} must be called)
*/
- public OperationTrace startAdvancedTracer(String name)
- {
+ public OperationTrace startAdvancedTracer(String name) {
return new OperationTrace(name, tracer.get(), state.getSessionId());
}
@@ -296,8 +323,7 @@ public class CuratorZookeeperClient implements Closeable
*
* @return tracing driver
*/
- public TracerDriver getTracerDriver()
- {
+ public TracerDriver getTracerDriver() {
return tracer.get();
}
@@ -306,8 +332,7 @@ public class CuratorZookeeperClient implements Closeable
*
* @param tracer new tracing driver
*/
- public void setTracerDriver(TracerDriver tracer)
- {
+ public void setTracerDriver(TracerDriver tracer) {
this.tracer.set(tracer);
}
@@ -317,8 +342,7 @@ public class CuratorZookeeperClient implements Closeable
*
* @return connection string
*/
- public String getCurrentConnectionString()
- {
+ public String getCurrentConnectionString() {
return state.getEnsembleProvider().getConnectionString();
}
@@ -327,8 +351,7 @@ public class CuratorZookeeperClient implements Closeable
*
* @return timeout
*/
- public int getConnectionTimeoutMs()
- {
+ public int getConnectionTimeoutMs() {
return connectionTimeoutMs;
}
@@ -337,8 +360,7 @@ public class CuratorZookeeperClient implements Closeable
*
* @throws Exception errors
*/
- public void reset() throws Exception
- {
+ public void reset() throws Exception {
state.reset();
}
@@ -348,8 +370,7 @@ public class CuratorZookeeperClient implements Closeable
*
* @return the current instance index
*/
- public long getInstanceIndex()
- {
+ public long getInstanceIndex() {
return state.getInstanceIndex();
}
@@ -358,18 +379,15 @@ public class CuratorZookeeperClient implements Closeable
*
* @return session timeout or 0
*/
- public int getLastNegotiatedSessionTimeoutMs()
- {
+ public int getLastNegotiatedSessionTimeoutMs() {
return state.getLastNegotiatedSessionTimeoutMs();
}
- void addParentWatcher(Watcher watcher)
- {
+ void addParentWatcher(Watcher watcher) {
state.addParentWatcher(watcher);
}
- void removeParentWatcher(Watcher watcher)
- {
+ void removeParentWatcher(Watcher watcher) {
state.removeParentWatcher(watcher);
}
@@ -378,17 +396,13 @@ public class CuratorZookeeperClient implements Closeable
*
* @throws InterruptedException interruptions
*/
- public void internalBlockUntilConnectedOrTimedOut() throws InterruptedException
- {
+ public void internalBlockUntilConnectedOrTimedOut() throws InterruptedException {
long waitTimeMs = connectionTimeoutMs;
- while ( !state.isConnected() && (waitTimeMs > 0) )
- {
+ while (!state.isConnected() && (waitTimeMs > 0)) {
final CountDownLatch latch = new CountDownLatch(1);
- Watcher tempWatcher = new Watcher()
- {
+ Watcher tempWatcher = new Watcher() {
@Override
- public void process(WatchedEvent event)
- {
+ public void process(WatchedEvent event) {
latch.countDown();
}
};
@@ -396,12 +410,9 @@ public class CuratorZookeeperClient implements Closeable
state.addParentWatcher(tempWatcher);
long startTimeMs = System.currentTimeMillis();
long timeoutMs = Math.min(waitTimeMs, 1000);
- try
- {
+ try {
latch.await(timeoutMs, TimeUnit.MILLISECONDS);
- }
- finally
- {
+ } finally {
state.removeParentWatcher(tempWatcher);
}
long elapsed = Math.max(1, System.currentTimeMillis() - startTimeMs);
diff --git a/curator-client/src/main/java/org/apache/curator/HandleHolder.java b/curator-client/src/main/java/org/apache/curator/HandleHolder.java
index a8c6d53d..e178177c 100644
--- a/curator-client/src/main/java/org/apache/curator/HandleHolder.java
+++ b/curator-client/src/main/java/org/apache/curator/HandleHolder.java
@@ -25,8 +25,7 @@ import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
-class HandleHolder
-{
+class HandleHolder {
private final ZookeeperFactory zookeeperFactory;
private final Watcher watcher;
private final EnsembleProvider ensembleProvider;
@@ -35,8 +34,12 @@ class HandleHolder
private volatile Helper helper;
- HandleHolder(ZookeeperFactory zookeeperFactory, Watcher watcher, EnsembleProvider ensembleProvider, int sessionTimeout, boolean canBeReadOnly)
- {
+ HandleHolder(
+ ZookeeperFactory zookeeperFactory,
+ Watcher watcher,
+ EnsembleProvider ensembleProvider,
+ int sessionTimeout,
+ boolean canBeReadOnly) {
this.zookeeperFactory = zookeeperFactory;
this.watcher = watcher;
this.ensembleProvider = ensembleProvider;
@@ -44,61 +47,52 @@ class HandleHolder
this.canBeReadOnly = canBeReadOnly;
}
- ZooKeeper getZooKeeper() throws Exception
- {
+ ZooKeeper getZooKeeper() throws Exception {
return (helper != null) ? helper.getZooKeeper() : null;
}
- int getNegotiatedSessionTimeoutMs()
- {
+ int getNegotiatedSessionTimeoutMs() {
return (helper != null) ? helper.getNegotiatedSessionTimeoutMs() : 0;
}
- String getConnectionString()
- {
+ String getConnectionString() {
return (helper != null) ? helper.getConnectionString() : null;
}
- String getNewConnectionString()
- {
+ String getNewConnectionString() {
String helperConnectionString = (helper != null) ? helper.getConnectionString() : null;
String ensembleProviderConnectionString = ensembleProvider.getConnectionString();
- return ((helperConnectionString != null) && !ensembleProviderConnectionString.equals(helperConnectionString)) ? ensembleProviderConnectionString : null;
+ return ((helperConnectionString != null) && !ensembleProviderConnectionString.equals(helperConnectionString))
+ ? ensembleProviderConnectionString
+ : null;
}
- void resetConnectionString(String connectionString)
- {
- if ( helper != null )
- {
+ void resetConnectionString(String connectionString) {
+ if (helper != null) {
helper.resetConnectionString(connectionString);
}
}
- void closeAndClear(int waitForShutdownTimeoutMs) throws Exception
- {
+ void closeAndClear(int waitForShutdownTimeoutMs) throws Exception {
internalClose(waitForShutdownTimeoutMs);
helper = null;
}
- void closeAndReset() throws Exception
- {
+ void closeAndReset() throws Exception {
internalClose(0);
- Helper.Data data = new Helper.Data(); // data shared between initial Helper and the un-synchronized Helper
+ Helper.Data data = new Helper.Data(); // data shared between initial Helper and the un-synchronized Helper
// first helper is synchronized when getZooKeeper is called. Subsequent calls
// are not synchronized.
//noinspection NonAtomicOperationOnVolatileField
- helper = new Helper(data)
- {
+ helper = new Helper(data) {
@Override
- ZooKeeper getZooKeeper() throws Exception
- {
- synchronized(this)
- {
- if ( data.zooKeeperHandle == null )
- {
+ ZooKeeper getZooKeeper() throws Exception {
+ synchronized (this) {
+ if (data.zooKeeperHandle == null) {
resetConnectionString(ensembleProvider.getConnectionString());
- data.zooKeeperHandle = zookeeperFactory.newZooKeeper(data.connectionString, sessionTimeout, watcher, canBeReadOnly);
+ data.zooKeeperHandle = zookeeperFactory.newZooKeeper(
+ data.connectionString, sessionTimeout, watcher, canBeReadOnly);
}
helper = new Helper(data);
@@ -109,33 +103,24 @@ class HandleHolder
};
}
- private void internalClose(int waitForShutdownTimeoutMs) throws Exception
- {
- try
- {
+ private void internalClose(int waitForShutdownTimeoutMs) throws Exception {
+ try {
ZooKeeper zooKeeper = (helper != null) ? helper.getZooKeeper() : null;
- if ( zooKeeper != null )
- {
- Watcher dummyWatcher = new Watcher()
- {
+ if (zooKeeper != null) {
+ Watcher dummyWatcher = new Watcher() {
@Override
- public void process(WatchedEvent event)
- {
- }
+ public void process(WatchedEvent event) {}
};
- zooKeeper.register(dummyWatcher); // clear the default watcher so that no new events get processed by mistake
- if ( waitForShutdownTimeoutMs == 0 )
- {
- zooKeeper.close(); // coming from closeAndReset() which is executed in ZK's event thread. Cannot use zooKeeper.close(n) otherwise we'd get a dead lock
- }
- else
- {
+ zooKeeper.register(
+ dummyWatcher); // clear the default watcher so that no new events get processed by mistake
+ if (waitForShutdownTimeoutMs == 0) {
+ zooKeeper.close(); // coming from closeAndReset() which is executed in ZK's event thread. Cannot use
+ // zooKeeper.close(n) otherwise we'd get a dead lock
+ } else {
zooKeeper.close(waitForShutdownTimeoutMs);
}
}
- }
- catch ( InterruptedException dummy )
- {
+ } catch (InterruptedException dummy) {
Thread.currentThread().interrupt();
}
}
diff --git a/curator-client/src/main/java/org/apache/curator/Helper.java b/curator-client/src/main/java/org/apache/curator/Helper.java
index 31b4aa64..b6c5cff0 100644
--- a/curator-client/src/main/java/org/apache/curator/Helper.java
+++ b/curator-client/src/main/java/org/apache/curator/Helper.java
@@ -21,38 +21,31 @@ package org.apache.curator;
import org.apache.zookeeper.ZooKeeper;
-class Helper
-{
+class Helper {
private final Data data;
- static class Data
- {
+ static class Data {
volatile ZooKeeper zooKeeperHandle = null;
volatile String connectionString = null;
}
- Helper(Data data)
- {
+ Helper(Data data) {
this.data = data;
}
- ZooKeeper getZooKeeper() throws Exception
- {
+ ZooKeeper getZooKeeper() throws Exception {
return data.zooKeeperHandle;
}
- String getConnectionString()
- {
+ String getConnectionString() {
return data.connectionString;
}
- int getNegotiatedSessionTimeoutMs()
- {
+ int getNegotiatedSessionTimeoutMs() {
return (data.zooKeeperHandle != null) ? data.zooKeeperHandle.getSessionTimeout() : 0;
}
- void resetConnectionString(String connectionString)
- {
+ void resetConnectionString(String connectionString) {
data.connectionString = connectionString;
}
}
diff --git a/curator-client/src/main/java/org/apache/curator/RetryLoop.java b/curator-client/src/main/java/org/apache/curator/RetryLoop.java
index 85a79cae..f6c160a9 100644
--- a/curator-client/src/main/java/org/apache/curator/RetryLoop.java
+++ b/curator-client/src/main/java/org/apache/curator/RetryLoop.java
@@ -19,9 +19,9 @@
package org.apache.curator;
+import java.util.concurrent.Callable;
import org.apache.curator.connection.ThreadLocalRetryLoop;
import org.apache.curator.utils.ThreadUtils;
-import java.util.concurrent.Callable;
/**
* <p>Mechanism to perform an operation on Zookeeper that is safe against
@@ -57,15 +57,13 @@ import java.util.concurrent.Callable;
* and if it becomes an interface we risk {@link java.lang.IncompatibleClassChangeError}s with clients.
* </p>
*/
-public abstract class RetryLoop
-{
+public abstract class RetryLoop {
/**
* Returns the default retry sleeper
*
* @return sleeper
*/
- public static RetrySleeper getDefaultRetrySleeper()
- {
+ public static RetrySleeper getDefaultRetrySleeper() {
return RetryLoopImpl.getRetrySleeper();
}
@@ -78,31 +76,23 @@ public abstract class RetryLoop
* @return procedure result
* @throws Exception any non-retriable errors
*/
- public static <T> T callWithRetry(CuratorZookeeperClient client, Callable<T> proc) throws Exception
- {
+ public static <T> T callWithRetry(CuratorZookeeperClient client, Callable<T> proc) throws Exception {
client.internalBlockUntilConnectedOrTimedOut();
T result = null;
ThreadLocalRetryLoop threadLocalRetryLoop = new ThreadLocalRetryLoop();
RetryLoop retryLoop = threadLocalRetryLoop.getRetryLoop(client::newRetryLoop);
- try
- {
- while ( retryLoop.shouldContinue() )
- {
- try
- {
+ try {
+ while (retryLoop.shouldContinue()) {
+ try {
result = proc.call();
retryLoop.markComplete();
- }
- catch ( Exception e )
- {
+ } catch (Exception e) {
ThreadUtils.checkInterrupted(e);
retryLoop.takeException(e);
}
}
- }
- finally
- {
+ } finally {
threadLocalRetryLoop.release();
}
diff --git a/curator-client/src/main/java/org/apache/curator/RetryLoopImpl.java b/curator-client/src/main/java/org/apache/curator/RetryLoopImpl.java
index 85991274..318a76b9 100644
--- a/curator-client/src/main/java/org/apache/curator/RetryLoopImpl.java
+++ b/curator-client/src/main/java/org/apache/curator/RetryLoopImpl.java
@@ -19,15 +19,14 @@
package org.apache.curator;
+import java.util.concurrent.atomic.AtomicReference;
import org.apache.curator.drivers.EventTrace;
import org.apache.curator.drivers.TracerDriver;
import org.apache.curator.utils.DebugUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.util.concurrent.atomic.AtomicReference;
-class RetryLoopImpl extends RetryLoop
-{
+class RetryLoopImpl extends RetryLoop {
private boolean isDone = false;
private int retryCount = 0;
@@ -38,62 +37,48 @@ class RetryLoopImpl extends RetryLoop
private static final RetrySleeper sleeper = (time, unit) -> unit.sleep(time);
- RetryLoopImpl(RetryPolicy retryPolicy, AtomicReference<TracerDriver> tracer)
- {
+ RetryLoopImpl(RetryPolicy retryPolicy, AtomicReference<TracerDriver> tracer) {
this.retryPolicy = retryPolicy;
this.tracer = tracer;
}
- static RetrySleeper getRetrySleeper()
- {
+ static RetrySleeper getRetrySleeper() {
return sleeper;
}
-
@Override
- public boolean shouldContinue()
- {
+ public boolean shouldContinue() {
return !isDone;
}
@Override
- public void markComplete()
- {
+ public void markComplete() {
isDone = true;
}
@Override
- public void takeException(Exception exception) throws Exception
- {
+ public void takeException(Exception exception) throws Exception {
boolean rethrow = true;
- if ( retryPolicy.allowRetry(exception) )
- {
- if ( !Boolean.getBoolean(DebugUtils.PROPERTY_DONT_LOG_CONNECTION_ISSUES) )
- {
+ if (retryPolicy.allowRetry(exception)) {
+ if (!Boolean.getBoolean(DebugUtils.PROPERTY_DONT_LOG_CONNECTION_ISSUES)) {
log.debug("Retry-able exception received", exception);
}
- if ( retryPolicy.allowRetry(retryCount++, System.currentTimeMillis() - startTimeMs, sleeper) )
- {
+ if (retryPolicy.allowRetry(retryCount++, System.currentTimeMillis() - startTimeMs, sleeper)) {
new EventTrace("retries-allowed", tracer.get()).commit();
- if ( !Boolean.getBoolean(DebugUtils.PROPERTY_DONT_LOG_CONNECTION_ISSUES) )
- {
+ if (!Boolean.getBoolean(DebugUtils.PROPERTY_DONT_LOG_CONNECTION_ISSUES)) {
log.debug("Retrying operation");
}
rethrow = false;
- }
- else
- {
+ } else {
new EventTrace("retries-disallowed", tracer.get()).commit();
- if ( !Boolean.getBoolean(DebugUtils.PROPERTY_DONT_LOG_CONNECTION_ISSUES) )
- {
+ if (!Boolean.getBoolean(DebugUtils.PROPERTY_DONT_LOG_CONNECTION_ISSUES)) {
log.debug("Retry policy not allowing retry");
}
}
}
- if ( rethrow )
- {
+ if (rethrow) {
throw exception;
}
}
diff --git a/curator-client/src/main/java/org/apache/curator/RetryPolicy.java b/curator-client/src/main/java/org/apache/curator/RetryPolicy.java
index 2f0a79ab..b433e505 100644
--- a/curator-client/src/main/java/org/apache/curator/RetryPolicy.java
+++ b/curator-client/src/main/java/org/apache/curator/RetryPolicy.java
@@ -24,8 +24,7 @@ import org.apache.zookeeper.KeeperException;
/**
* Abstracts the policy to use when retrying connections
*/
-public interface RetryPolicy
-{
+public interface RetryPolicy {
/**
* Called when an operation has failed for some reason. This method should return
* true to make another attempt.
@@ -45,15 +44,13 @@ public interface RetryPolicy
* @param exception the cause that this operation failed
* @return true/false
*/
- default boolean allowRetry(Throwable exception)
- {
- if ( exception instanceof KeeperException)
- {
+ default boolean allowRetry(Throwable exception) {
+ if (exception instanceof KeeperException) {
final int rc = ((KeeperException) exception).code().intValue();
- return (rc == KeeperException.Code.CONNECTIONLOSS.intValue()) ||
- (rc == KeeperException.Code.OPERATIONTIMEOUT.intValue()) ||
- (rc == KeeperException.Code.SESSIONMOVED.intValue()) ||
- (rc == KeeperException.Code.SESSIONEXPIRED.intValue());
+ return (rc == KeeperException.Code.CONNECTIONLOSS.intValue())
+ || (rc == KeeperException.Code.OPERATIONTIMEOUT.intValue())
+ || (rc == KeeperException.Code.SESSIONMOVED.intValue())
+ || (rc == KeeperException.Code.SESSIONEXPIRED.intValue());
}
return false;
}
diff --git a/curator-client/src/main/java/org/apache/curator/RetrySleeper.java b/curator-client/src/main/java/org/apache/curator/RetrySleeper.java
index 034563cd..ccc90700 100644
--- a/curator-client/src/main/java/org/apache/curator/RetrySleeper.java
+++ b/curator-client/src/main/java/org/apache/curator/RetrySleeper.java
@@ -24,8 +24,7 @@ import java.util.concurrent.TimeUnit;
/**
* Abstraction for retry policies to sleep
*/
-public interface RetrySleeper
-{
+public interface RetrySleeper {
/**
* Sleep for the given time
*
@@ -33,5 +32,5 @@ public interface RetrySleeper
* @param unit time unit
* @throws InterruptedException if the sleep is interrupted
*/
- public void sleepFor(long time, TimeUnit unit) throws InterruptedException;
+ public void sleepFor(long time, TimeUnit unit) throws InterruptedException;
}
diff --git a/curator-client/src/main/java/org/apache/curator/SessionFailRetryLoop.java b/curator-client/src/main/java/org/apache/curator/SessionFailRetryLoop.java
index e81c275e..34e14e40 100644
--- a/curator-client/src/main/java/org/apache/curator/SessionFailRetryLoop.java
+++ b/curator-client/src/main/java/org/apache/curator/SessionFailRetryLoop.java
@@ -22,14 +22,14 @@ package org.apache.curator;
import com.google.common.base.Preconditions;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
-import org.apache.curator.utils.ThreadUtils;
-import org.apache.zookeeper.KeeperException;
-import org.apache.zookeeper.WatchedEvent;
-import org.apache.zookeeper.Watcher;
import java.io.Closeable;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.atomic.AtomicBoolean;
+import org.apache.curator.utils.ThreadUtils;
+import org.apache.zookeeper.KeeperException;
+import org.apache.zookeeper.WatchedEvent;
+import org.apache.zookeeper.Watcher;
/**
* <p>
@@ -92,37 +92,32 @@ import java.util.concurrent.atomic.AtomicBoolean;
* }
* </pre>
*/
-public class SessionFailRetryLoop implements Closeable
-{
- private final CuratorZookeeperClient client;
- private final Mode mode;
- private final Thread ourThread = Thread.currentThread();
- private final AtomicBoolean sessionHasFailed = new AtomicBoolean(false);
- private final AtomicBoolean isDone = new AtomicBoolean(false);
- private final RetryLoop retryLoop;
-
- private final Watcher watcher = new Watcher()
- {
+public class SessionFailRetryLoop implements Closeable {
+ private final CuratorZookeeperClient client;
+ private final Mode mode;
+ private final Thread ourThread = Thread.currentThread();
+ private final AtomicBoolean sessionHasFailed = new AtomicBoolean(false);
+ private final AtomicBoolean isDone = new AtomicBoolean(false);
+ private final RetryLoop retryLoop;
+
+ private final Watcher watcher = new Watcher() {
@Override
- public void process(WatchedEvent event)
- {
- if ( event.getState() == Event.KeeperState.Expired )
- {
+ public void process(WatchedEvent event) {
+ if (event.getState() == Event.KeeperState.Expired) {
sessionHasFailed.set(true);
failedSessionThreads.add(ourThread);
}
}
};
- private static final Set<Thread> failedSessionThreads = Sets.newSetFromMap(Maps.<Thread, Boolean>newConcurrentMap());
+ private static final Set<Thread> failedSessionThreads =
+ Sets.newSetFromMap(Maps.<Thread, Boolean>newConcurrentMap());
- public static class SessionFailedException extends Exception
- {
- private static final long serialVersionUID = 1L;
+ public static class SessionFailedException extends Exception {
+ private static final long serialVersionUID = 1L;
}
- public enum Mode
- {
+ public enum Mode {
/**
* If the session fails, retry the entire set of operations when {@link SessionFailRetryLoop#shouldContinue()}
* is called
@@ -146,50 +141,39 @@ public class SessionFailRetryLoop implements Closeable
* @return procedure result
* @throws Exception any non-retriable errors
*/
- public static<T> T callWithRetry(CuratorZookeeperClient client, Mode mode, Callable<T> proc) throws Exception
- {
- T result = null;
- SessionFailRetryLoop retryLoop = client.newSessionFailRetryLoop(mode);
+ public static <T> T callWithRetry(CuratorZookeeperClient client, Mode mode, Callable<T> proc) throws Exception {
+ T result = null;
+ SessionFailRetryLoop retryLoop = client.newSessionFailRetryLoop(mode);
retryLoop.start();
- try
- {
- while ( retryLoop.shouldContinue() )
- {
- try
- {
+ try {
+ while (retryLoop.shouldContinue()) {
+ try {
result = proc.call();
- }
- catch ( Exception e )
- {
+ } catch (Exception e) {
ThreadUtils.checkInterrupted(e);
retryLoop.takeException(e);
}
}
- }
- finally
- {
+ } finally {
retryLoop.close();
}
return result;
}
- SessionFailRetryLoop(CuratorZookeeperClient client, Mode mode)
- {
+ SessionFailRetryLoop(CuratorZookeeperClient client, Mode mode) {
this.client = client;
this.mode = mode;
retryLoop = client.newRetryLoop();
}
- static boolean sessionForThreadHasFailed()
- {
+ static boolean sessionForThreadHasFailed() {
return failedSessionThreads.contains(Thread.currentThread());
}
/**
* SessionFailRetryLoop must be started
*/
- public void start()
- {
+ public void start() {
Preconditions.checkState(Thread.currentThread().equals(ourThread), "Not in the correct thread");
client.addParentWatcher(watcher);
@@ -200,9 +184,8 @@ public class SessionFailRetryLoop implements Closeable
*
* @return true/false
*/
- public boolean shouldContinue()
- {
- boolean localIsDone = isDone.getAndSet(true);
+ public boolean shouldContinue() {
+ boolean localIsDone = isDone.getAndSet(true);
return !localIsDone;
}
@@ -210,8 +193,7 @@ public class SessionFailRetryLoop implements Closeable
* Must be called in a finally handler when done with the loop
*/
@Override
- public void close()
- {
+ public void close() {
Preconditions.checkState(Thread.currentThread().equals(ourThread), "Not in the correct thread");
failedSessionThreads.remove(ourThread);
@@ -224,36 +206,29 @@ public class SessionFailRetryLoop implements Closeable
* @param exception the exception
* @throws Exception if not retry-able or the retry policy returned negative
*/
- public void takeException(Exception exception) throws Exception
- {
+ public void takeException(Exception exception) throws Exception {
Preconditions.checkState(Thread.currentThread().equals(ourThread), "Not in the correct thread");
- boolean passUp = true;
- if ( sessionHasFailed.get() )
- {
- switch ( mode )
- {
- case RETRY:
- {
+ boolean passUp = true;
+ if (sessionHasFailed.get()) {
+ switch (mode) {
+ case RETRY: {
sessionHasFailed.set(false);
failedSessionThreads.remove(ourThread);
- if ( exception instanceof SessionFailedException )
- {
+ if (exception instanceof SessionFailedException) {
isDone.set(false);
passUp = false;
}
break;
}
- case FAIL:
- {
+ case FAIL: {
break;
}
}
}
- if ( passUp )
- {
+ if (passUp) {
retryLoop.takeException(exception);
}
}
diff --git a/curator-client/src/main/java/org/apache/curator/SessionFailedRetryPolicy.java b/curator-client/src/main/java/org/apache/curator/SessionFailedRetryPolicy.java
index d645e36c..9927e0b5 100644
--- a/curator-client/src/main/java/org/apache/curator/SessionFailedRetryPolicy.java
+++ b/curator-client/src/main/java/org/apache/curator/SessionFailedRetryPolicy.java
@@ -24,31 +24,24 @@ import org.apache.zookeeper.KeeperException;
/**
* {@link RetryPolicy} implementation that failed on session expired.
*/
-public class SessionFailedRetryPolicy implements RetryPolicy
-{
+public class SessionFailedRetryPolicy implements RetryPolicy {
private final RetryPolicy delegatePolicy;
- public SessionFailedRetryPolicy(RetryPolicy delegatePolicy)
- {
+ public SessionFailedRetryPolicy(RetryPolicy delegatePolicy) {
this.delegatePolicy = delegatePolicy;
}
@Override
- public boolean allowRetry(int retryCount, long elapsedTimeMs, RetrySleeper sleeper)
- {
+ public boolean allowRetry(int retryCount, long elapsedTimeMs, RetrySleeper sleeper) {
return delegatePolicy.allowRetry(retryCount, elapsedTimeMs, sleeper);
}
@Override
- public boolean allowRetry(Throwable exception)
- {
- if ( exception instanceof KeeperException.SessionExpiredException )
- {
+ public boolean allowRetry(Throwable exception) {
+ if (exception instanceof KeeperException.SessionExpiredException) {
return false;
- }
- else
- {
+ } else {
return delegatePolicy.allowRetry(exception);
}
}
diff --git a/curator-client/src/main/java/org/apache/curator/TimeTrace.java b/curator-client/src/main/java/org/apache/curator/TimeTrace.java
index 723f59db..289db2e2 100644
--- a/curator-client/src/main/java/org/apache/curator/TimeTrace.java
+++ b/curator-client/src/main/java/org/apache/curator/TimeTrace.java
@@ -19,14 +19,13 @@
package org.apache.curator;
-import org.apache.curator.drivers.TracerDriver;
import java.util.concurrent.TimeUnit;
+import org.apache.curator.drivers.TracerDriver;
/**
* Utility to time a method or portion of code
*/
-public class TimeTrace
-{
+public class TimeTrace {
private final String name;
private final TracerDriver driver;
private final long startTimeNanos = System.nanoTime();
@@ -37,8 +36,7 @@ public class TimeTrace
* @param name name of the event
* @param driver driver
*/
- public TimeTrace(String name, TracerDriver driver)
- {
+ public TimeTrace(String name, TracerDriver driver) {
this.name = name;
this.driver = driver;
}
@@ -46,9 +44,8 @@ public class TimeTrace
/**
* Record the elapsed time
*/
- public void commit()
- {
- long elapsed = System.nanoTime() - startTimeNanos;
+ public void commit() {
+ long elapsed = System.nanoTime() - startTimeNanos;
driver.addTrace(name, elapsed, TimeUnit.NANOSECONDS);
}
}
diff --git a/curator-client/src/main/java/org/apache/curator/connection/ThreadLocalRetryLoop.java b/curator-client/src/main/java/org/apache/curator/connection/ThreadLocalRetryLoop.java
index 40e14bb5..96673422 100644
--- a/curator-client/src/main/java/org/apache/curator/connection/ThreadLocalRetryLoop.java
+++ b/curator-client/src/main/java/org/apache/curator/connection/ThreadLocalRetryLoop.java
@@ -19,11 +19,11 @@
package org.apache.curator.connection;
+import java.util.Objects;
+import java.util.function.Supplier;
import org.apache.curator.RetryLoop;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.util.Objects;
-import java.util.function.Supplier;
/**
* <p>
@@ -62,61 +62,48 @@ import java.util.function.Supplier;
* </pre></code>
* </p>
*/
-public class ThreadLocalRetryLoop
-{
+public class ThreadLocalRetryLoop {
private static final Logger log = LoggerFactory.getLogger(ThreadLocalRetryLoop.class);
private static final ThreadLocal<Entry> threadLocal = new ThreadLocal<>();
- private static class Entry
- {
+ private static class Entry {
private final RetryLoop retryLoop;
private int counter;
- Entry(RetryLoop retryLoop)
- {
+ Entry(RetryLoop retryLoop) {
this.retryLoop = retryLoop;
}
}
- private static class WrappedRetryLoop extends RetryLoop
- {
+ private static class WrappedRetryLoop extends RetryLoop {
private final RetryLoop retryLoop;
private Exception takenException;
- public WrappedRetryLoop(RetryLoop retryLoop)
- {
+ public WrappedRetryLoop(RetryLoop retryLoop) {
this.retryLoop = retryLoop;
}
@Override
- public boolean shouldContinue()
- {
+ public boolean shouldContinue() {
return retryLoop.shouldContinue() && (takenException == null);
}
@Override
- public void markComplete()
- {
+ public void markComplete() {
retryLoop.markComplete();
}
@Override
- public void takeException(Exception exception) throws Exception
- {
- if ( takenException != null )
- {
- if ( exception.getClass() != takenException.getClass() )
- {
+ public void takeException(Exception exception) throws Exception {
+ if (takenException != null) {
+ if (exception.getClass() != takenException.getClass()) {
log.error("Multiple exceptions in retry loop", exception);
}
throw takenException;
}
- try
- {
+ try {
retryLoop.takeException(exception);
- }
- catch ( Exception e )
- {
+ } catch (Exception e) {
takenException = e;
throw e;
}
@@ -130,11 +117,9 @@ public class ThreadLocalRetryLoop
* @param newRetryLoopSupplier supply a new retry loop when needed. Normally you should use {@link org.apache.curator.CuratorZookeeperClient#newRetryLoop()}
* @return retry loop to use
*/
- public RetryLoop getRetryLoop(Supplier<RetryLoop> newRetryLoopSupplier)
- {
+ public RetryLoop getRetryLoop(Supplier<RetryLoop> newRetryLoopSupplier) {
Entry entry = threadLocal.get();
- if ( entry == null )
- {
+ if (entry == null) {
entry = new Entry(new WrappedRetryLoop(newRetryLoopSupplier.get()));
threadLocal.set(entry);
}
@@ -146,11 +131,9 @@ public class ThreadLocalRetryLoop
* Must be called to release the retry loop. See {@link RetryLoop#callWithRetry(org.apache.curator.CuratorZookeeperClient, java.util.concurrent.Callable)}
* for an example usage.
*/
- public void release()
- {
+ public void release() {
Entry entry = Objects.requireNonNull(threadLocal.get(), "No retry loop was set - unbalanced call to release()");
- if ( --entry.counter <= 0 )
- {
+ if (--entry.counter <= 0) {
threadLocal.remove();
}
}
diff --git a/curator-client/src/main/java/org/apache/curator/drivers/AdvancedTracerDriver.java b/curator-client/src/main/java/org/apache/curator/drivers/AdvancedTracerDriver.java
index 2644f2fa..800dd0ce 100644
--- a/curator-client/src/main/java/org/apache/curator/drivers/AdvancedTracerDriver.java
+++ b/curator-client/src/main/java/org/apache/curator/drivers/AdvancedTracerDriver.java
@@ -24,14 +24,13 @@ import java.util.concurrent.TimeUnit;
/**
* Expose more metrics for the operations and events
*/
-public abstract class AdvancedTracerDriver implements TracerDriver
-{
+public abstract class AdvancedTracerDriver implements TracerDriver {
/**
* Record the given trace event
*
* @param trace the metrics of the operation
*/
- public abstract void addTrace(OperationTrace trace);
+ public abstract void addTrace(OperationTrace trace);
/**
* Add to a named counter
@@ -39,13 +38,13 @@ public abstract class AdvancedTracerDriver implements TracerDriver
* @param name name of the counter
* @param increment amount to increment
*/
- public abstract void addEvent(EventTrace trace);
+ public abstract void addEvent(EventTrace trace);
@Deprecated
@Override
- public final void addTrace(String name, long time, TimeUnit unit) {}
+ public final void addTrace(String name, long time, TimeUnit unit) {}
@Deprecated
@Override
- public final void addCount(String name, int increment) {}
+ public final void addCount(String name, int increment) {}
}
diff --git a/curator-client/src/main/java/org/apache/curator/drivers/EventTrace.java b/curator-client/src/main/java/org/apache/curator/drivers/EventTrace.java
index 6d1f6ac4..1484b8e0 100644
--- a/curator-client/src/main/java/org/apache/curator/drivers/EventTrace.java
+++ b/curator-client/src/main/java/org/apache/curator/drivers/EventTrace.java
@@ -19,36 +19,34 @@
package org.apache.curator.drivers;
-public class EventTrace
-{
- private final String name;
- private final TracerDriver driver;
- private final long sessionId;
+public class EventTrace {
+ private final String name;
+ private final TracerDriver driver;
+ private final long sessionId;
- public EventTrace(String name, TracerDriver driver) {
- this(name, driver, -1);
- }
+ public EventTrace(String name, TracerDriver driver) {
+ this(name, driver, -1);
+ }
- public EventTrace(String name, TracerDriver driver, long sessionId) {
- this.name = name;
- this.driver = driver;
- this.sessionId = sessionId;
- }
+ public EventTrace(String name, TracerDriver driver, long sessionId) {
+ this.name = name;
+ this.driver = driver;
+ this.sessionId = sessionId;
+ }
- public String getName() {
- return this.name;
- }
+ public String getName() {
+ return this.name;
+ }
- public long getSessionId() {
- return this.sessionId;
- }
+ public long getSessionId() {
+ return this.sessionId;
+ }
- public void commit() {
- if (this.driver instanceof AdvancedTracerDriver) {
- ((AdvancedTracerDriver) this.driver).addEvent(this);
- } else {
- this.driver.addCount(this.name, 1);
+ public void commit() {
+ if (this.driver instanceof AdvancedTracerDriver) {
+ ((AdvancedTracerDriver) this.driver).addEvent(this);
+ } else {
+ this.driver.addCount(this.name, 1);
+ }
}
- }
}
-
diff --git a/curator-client/src/main/java/org/apache/curator/drivers/OperationTrace.java b/curator-client/src/main/java/org/apache/curator/drivers/OperationTrace.java
index f84c1c56..8ef3de09 100644
--- a/curator-client/src/main/java/org/apache/curator/drivers/OperationTrace.java
+++ b/curator-client/src/main/java/org/apache/curator/drivers/OperationTrace.java
@@ -19,18 +19,15 @@
package org.apache.curator.drivers;
-import org.apache.curator.drivers.TracerDriver;
-import org.apache.zookeeper.KeeperException;
-import org.apache.zookeeper.data.Stat;
-
import java.io.UnsupportedEncodingException;
import java.util.concurrent.TimeUnit;
+import org.apache.zookeeper.KeeperException;
+import org.apache.zookeeper.data.Stat;
/**
* Used to trace the metrics of a certain Zookeeper operation.
*/
-public class OperationTrace
-{
+public class OperationTrace {
private final String name;
private final TracerDriver driver;
@@ -46,118 +43,118 @@ public class OperationTrace
private final long startTimeNanos = System.nanoTime();
public OperationTrace(String name, TracerDriver driver) {
- this(name, driver, -1);
+ this(name, driver, -1);
}
public OperationTrace(String name, TracerDriver driver, long sessionId) {
- this.name = name;
- this.driver = driver;
- this.sessionId = sessionId;
+ this.name = name;
+ this.driver = driver;
+ this.sessionId = sessionId;
}
public OperationTrace setReturnCode(int returnCode) {
- this.returnCode = returnCode;
- return this;
+ this.returnCode = returnCode;
+ return this;
}
public OperationTrace setRequestBytesLength(long length) {
- this.requestBytesLength = length;
- return this;
+ this.requestBytesLength = length;
+ return this;
}
public OperationTrace setRequestBytesLength(String data) {
- if (data == null) {
- return this;
- }
+ if (data == null) {
+ return this;
+ }
- try {
- this.setRequestBytesLength(data.getBytes("UTF-8").length);
- } catch (UnsupportedEncodingException e) {
- // Ignore the exception.
- }
+ try {
+ this.setRequestBytesLength(data.getBytes("UTF-8").length);
+ } catch (UnsupportedEncodingException e) {
+ // Ignore the exception.
+ }
- return this;
+ return this;
}
public OperationTrace setRequestBytesLength(byte[] data) {
- if (data == null) {
- return this;
- }
+ if (data == null) {
+ return this;
+ }
- return this.setRequestBytesLength(data.length);
+ return this.setRequestBytesLength(data.length);
}
public OperationTrace setResponseBytesLength(long length) {
- this.responseBytesLength = length;
- return this;
+ this.responseBytesLength = length;
+ return this;
}
public OperationTrace setResponseBytesLength(byte[] data) {
- if (data == null) {
- return this;
- }
+ if (data == null) {
+ return this;
+ }
- return this.setResponseBytesLength(data.length);
+ return this.setResponseBytesLength(data.length);
}
public OperationTrace setPath(String path) {
- this.path = path;
- return this;
+ this.path = path;
+ return this;
}
public OperationTrace setWithWatcher(boolean withWatcher) {
- this.withWatcher = withWatcher;
- return this;
+ this.withWatcher = withWatcher;
+ return this;
}
public OperationTrace setStat(Stat stat) {
- this.stat = stat;
- return this;
+ this.stat = stat;
+ return this;
}
public String getName() {
- return this.name;
+ return this.name;
}
public int getReturnCode() {
- return this.returnCode;
+ return this.returnCode;
}
public long getLatencyMs() {
- return this.latencyMs;
+ return this.latencyMs;
}
public long getRequestBytesLength() {
- return this.requestBytesLength;
+ return this.requestBytesLength;
}
public long getResponseBytesLength() {
- return this.responseBytesLength;
+ return this.responseBytesLength;
}
public long getSessionId() {
- return this.sessionId;
+ return this.sessionId;
}
public String getPath() {
- return this.path;
+ return this.path;
}
public boolean isWithWatcher() {
- return this.withWatcher;
+ return this.withWatcher;
}
public Stat getStat() {
- return this.stat;
+ return this.stat;
}
public void commit() {
- long elapsed = System.nanoTime() - startTimeNanos;
- this.latencyMs = TimeUnit.MILLISECONDS.convert(elapsed, TimeUnit.NANOSECONDS);
- if (this.driver instanceof AdvancedTracerDriver) {
- ((AdvancedTracerDriver) this.driver).addTrace(this);
- } else {
- this.driver.addTrace(this.name, elapsed, TimeUnit.NANOSECONDS);
- }
+ long elapsed = System.nanoTime() - startTimeNanos;
+ this.latencyMs = TimeUnit.MILLISECONDS.convert(elapsed, TimeUnit.NANOSECONDS);
+ if (this.driver instanceof AdvancedTracerDriver) {
+ ((AdvancedTracerDriver) this.driver).addTrace(this);
+ } else {
+ this.driver.addTrace(this.name, elapsed, TimeUnit.NANOSECONDS);
+ }
}
}
diff --git a/curator-client/src/main/java/org/apache/curator/drivers/TracerDriver.java b/curator-client/src/main/java/org/apache/curator/drivers/TracerDriver.java
index 69021ed2..89fad26b 100644
--- a/curator-client/src/main/java/org/apache/curator/drivers/TracerDriver.java
+++ b/curator-client/src/main/java/org/apache/curator/drivers/TracerDriver.java
@@ -24,8 +24,7 @@ import java.util.concurrent.TimeUnit;
/**
* Mechanism for timing methods and recording counters
*/
-public interface TracerDriver
-{
+public interface TracerDriver {
/**
* Record the given trace event
*
@@ -33,7 +32,7 @@ public interface TracerDriver
* @param time time event took
* @param unit time unit
*/
- public void addTrace(String name, long time, TimeUnit unit);
+ public void addTrace(String name, long time, TimeUnit unit);
/**
* Add to a named counter
@@ -41,5 +40,5 @@ public interface TracerDriver
* @param name name of the counter
* @param increment amount to increment
*/
- public void addCount(String name, int increment);
+ public void addCount(String name, int increment);
}
diff --git a/curator-client/src/main/java/org/apache/curator/ensemble/EnsembleProvider.java b/curator-client/src/main/java/org/apache/curator/ensemble/EnsembleProvider.java
index 24f32f06..f52456d4 100644
--- a/curator-client/src/main/java/org/apache/curator/ensemble/EnsembleProvider.java
+++ b/curator-client/src/main/java/org/apache/curator/ensemble/EnsembleProvider.java
@@ -19,39 +19,38 @@
package org.apache.curator.ensemble;
+import java.io.Closeable;
+import java.io.IOException;
import org.apache.curator.CuratorZookeeperClient;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
-import java.io.Closeable;
-import java.io.IOException;
/**
* Abstraction that provides the ZooKeeper connection string
*/
-public interface EnsembleProvider extends Closeable
-{
+public interface EnsembleProvider extends Closeable {
/**
* Curator will call this method when {@link CuratorZookeeperClient#start()} is
* called
- *
+ *
* @throws Exception errors
*/
- public void start() throws Exception;
+ public void start() throws Exception;
/**
* Return the current connection string to use. Curator will call this each
* time it needs to create a ZooKeeper instance
- *
+ *
* @return connection string (per {@link ZooKeeper#ZooKeeper(String, int, Watcher)} etc.)
*/
- public String getConnectionString();
+ public String getConnectionString();
/**
* Curator will call this method when {@link CuratorZookeeperClient#close()} is called
- *
+ *
* @throws IOException errors
*/
- public void close() throws IOException;
+ public void close() throws IOException;
/**
* A new connection string event was received
diff --git a/curator-client/src/main/java/org/apache/curator/ensemble/fixed/FixedEnsembleProvider.java b/curator-client/src/main/java/org/apache/curator/ensemble/fixed/FixedEnsembleProvider.java
index 95a0511a..c8ca4e64 100644
--- a/curator-client/src/main/java/org/apache/curator/ensemble/fixed/FixedEnsembleProvider.java
+++ b/curator-client/src/main/java/org/apache/curator/ensemble/fixed/FixedEnsembleProvider.java
@@ -21,16 +21,15 @@ package org.apache.curator.ensemble.fixed;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
-import org.apache.curator.ensemble.EnsembleProvider;
-import org.apache.zookeeper.ZooKeeper;
import java.io.IOException;
import java.util.concurrent.atomic.AtomicReference;
+import org.apache.curator.ensemble.EnsembleProvider;
+import org.apache.zookeeper.ZooKeeper;
/**
* Standard ensemble provider that wraps a fixed connection string
*/
-public class FixedEnsembleProvider implements EnsembleProvider
-{
+public class FixedEnsembleProvider implements EnsembleProvider {
private final AtomicReference<String> connectionString = new AtomicReference<>();
private final boolean updateServerListEnabled;
@@ -39,8 +38,7 @@ public class FixedEnsembleProvider implements EnsembleProvider
*
* @param connectionString connection string
*/
- public FixedEnsembleProvider(String connectionString)
- {
+ public FixedEnsembleProvider(String connectionString) {
this(connectionString, true);
}
@@ -50,40 +48,35 @@ public class FixedEnsembleProvider implements EnsembleProvider
* @param connectionString connection string
* @param updateServerListEnabled if true, allow Curator to call {@link ZooKeeper#updateServerList(String)}
*/
- public FixedEnsembleProvider(String connectionString, boolean updateServerListEnabled)
- {
+ public FixedEnsembleProvider(String connectionString, boolean updateServerListEnabled) {
this.updateServerListEnabled = updateServerListEnabled;
- Preconditions.checkArgument(!Strings.isNullOrEmpty(connectionString), "connectionString cannot be null or empty");
+ Preconditions.checkArgument(
+ !Strings.isNullOrEmpty(connectionString), "connectionString cannot be null or empty");
this.connectionString.set(connectionString);
}
@Override
- public void start() throws Exception
- {
+ public void start() throws Exception {
// NOP
}
@Override
- public void close() throws IOException
- {
+ public void close() throws IOException {
// NOP
}
@Override
- public void setConnectionString(String connectionString)
- {
+ public void setConnectionString(String connectionString) {
this.connectionString.set(connectionString);
}
@Override
- public String getConnectionString()
- {
+ public String getConnectionString() {
return connectionString.get();
}
@Override
- public boolean updateServerListEnabled()
- {
+ public boolean updateServerListEnabled() {
return updateServerListEnabled;
}
}
diff --git a/curator-client/src/main/java/org/apache/curator/retry/BoundedExponentialBackoffRetry.java b/curator-client/src/main/java/org/apache/curator/retry/BoundedExponentialBackoffRetry.java
index b85588c6..a53884a0 100644
--- a/curator-client/src/main/java/org/apache/curator/retry/BoundedExponentialBackoffRetry.java
+++ b/curator-client/src/main/java/org/apache/curator/retry/BoundedExponentialBackoffRetry.java
@@ -24,8 +24,7 @@ import com.google.common.annotations.VisibleForTesting;
/**
* Retry policy that retries a set number of times with an increasing (up to a maximum bound) sleep time between retries
*/
-public class BoundedExponentialBackoffRetry extends ExponentialBackoffRetry
-{
+public class BoundedExponentialBackoffRetry extends ExponentialBackoffRetry {
private final int maxSleepTimeMs;
/**
@@ -33,21 +32,18 @@ public class BoundedExponentialBackoffRetry extends ExponentialBackoffRetry
* @param maxSleepTimeMs maximum amount of time to wait between retries
* @param maxRetries maximum number of times to retry
*/
- public BoundedExponentialBackoffRetry(int baseSleepTimeMs, int maxSleepTimeMs, int maxRetries)
- {
+ public BoundedExponentialBackoffRetry(int baseSleepTimeMs, int maxSleepTimeMs, int maxRetries) {
super(baseSleepTimeMs, maxRetries);
this.maxSleepTimeMs = maxSleepTimeMs;
}
@VisibleForTesting
- public int getMaxSleepTimeMs()
- {
+ public int getMaxSleepTimeMs() {
return maxSleepTimeMs;
}
@Override
- protected long getSleepTimeMs(int retryCount, long elapsedTimeMs)
- {
+ protected long getSleepTimeMs(int retryCount, long elapsedTimeMs) {
return Math.min(maxSleepTimeMs, super.getSleepTimeMs(retryCount, elapsedTimeMs));
}
-}
\ No newline at end of file
+}
diff --git a/curator-client/src/main/java/org/apache/curator/retry/ExponentialBackoffRetry.java b/curator-client/src/main/java/org/apache/curator/retry/ExponentialBackoffRetry.java
index e9f56f30..929b3b37 100644
--- a/curator-client/src/main/java/org/apache/curator/retry/ExponentialBackoffRetry.java
+++ b/curator-client/src/main/java/org/apache/curator/retry/ExponentialBackoffRetry.java
@@ -20,16 +20,15 @@
package org.apache.curator.retry;
import com.google.common.annotations.VisibleForTesting;
+import java.util.Random;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.util.Random;
/**
* Retry policy that retries a set number of times with increasing sleep time between retries
*/
-public class ExponentialBackoffRetry extends SleepingRetry
-{
- private static final Logger log = LoggerFactory.getLogger(ExponentialBackoffRetry.class);
+public class ExponentialBackoffRetry extends SleepingRetry {
+ private static final Logger log = LoggerFactory.getLogger(ExponentialBackoffRetry.class);
private static final int MAX_RETRIES_LIMIT = 29;
private static final int DEFAULT_MAX_SLEEP_MS = Integer.MAX_VALUE;
@@ -42,8 +41,7 @@ public class ExponentialBackoffRetry extends SleepingRetry
* @param baseSleepTimeMs initial amount of time to wait between retries
* @param maxRetries max number of times to retry
*/
- public ExponentialBackoffRetry(int baseSleepTimeMs, int maxRetries)
- {
+ public ExponentialBackoffRetry(int baseSleepTimeMs, int maxRetries) {
this(baseSleepTimeMs, maxRetries, DEFAULT_MAX_SLEEP_MS);
}
@@ -52,36 +50,30 @@ public class ExponentialBackoffRetry extends SleepingRetry
* @param maxRetries max number of times to retry
* @param maxSleepMs max time in ms to sleep on each retry
*/
- public ExponentialBackoffRetry(int baseSleepTimeMs, int maxRetries, int maxSleepMs)
- {
+ public ExponentialBackoffRetry(int baseSleepTimeMs, int maxRetries, int maxSleepMs) {
super(validateMaxRetries(maxRetries));
this.baseSleepTimeMs = baseSleepTimeMs;
this.maxSleepMs = maxSleepMs;
}
@VisibleForTesting
- public int getBaseSleepTimeMs()
- {
+ public int getBaseSleepTimeMs() {
return baseSleepTimeMs;
}
@Override
- protected long getSleepTimeMs(int retryCount, long elapsedTimeMs)
- {
+ protected long getSleepTimeMs(int retryCount, long elapsedTimeMs) {
// copied from Hadoop's RetryPolicies.java
long sleepMs = baseSleepTimeMs * Math.max(1, random.nextInt(1 << (retryCount + 1)));
- if ( sleepMs > maxSleepMs )
- {
+ if (sleepMs > maxSleepMs) {
log.warn(String.format("Sleep extension too large (%d). Pinning to %d", sleepMs, maxSleepMs));
sleepMs = maxSleepMs;
}
return sleepMs;
}
- private static int validateMaxRetries(int maxRetries)
- {
- if ( maxRetries > MAX_RETRIES_LIMIT )
- {
+ private static int validateMaxRetries(int maxRetries) {
+ if (maxRetries > MAX_RETRIES_LIMIT) {
log.warn(String.format("maxRetries too large (%d). Pinning to %d", maxRetries, MAX_RETRIES_LIMIT));
maxRetries = MAX_RETRIES_LIMIT;
}
diff --git a/curator-client/src/main/java/org/apache/curator/retry/RetryForever.java b/curator-client/src/main/java/org/apache/curator/retry/RetryForever.java
index c8431383..a4d148fe 100644
--- a/curator-client/src/main/java/org/apache/curator/retry/RetryForever.java
+++ b/curator-client/src/main/java/org/apache/curator/retry/RetryForever.java
@@ -19,39 +19,31 @@
package org.apache.curator.retry;
+import static com.google.common.base.Preconditions.checkArgument;
+import java.util.concurrent.TimeUnit;
import org.apache.curator.RetryPolicy;
import org.apache.curator.RetrySleeper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.util.concurrent.TimeUnit;
-
-import static com.google.common.base.Preconditions.checkArgument;
-
/**
* {@link RetryPolicy} implementation that always <i>allowsRetry</i>.
*/
-public class RetryForever implements RetryPolicy
-{
+public class RetryForever implements RetryPolicy {
private static final Logger log = LoggerFactory.getLogger(RetryForever.class);
private final int retryIntervalMs;
- public RetryForever(int retryIntervalMs)
- {
+ public RetryForever(int retryIntervalMs) {
checkArgument(retryIntervalMs > 0);
this.retryIntervalMs = retryIntervalMs;
}
@Override
- public boolean allowRetry(int retryCount, long elapsedTimeMs, RetrySleeper sleeper)
- {
- try
- {
+ public boolean allowRetry(int retryCount, long elapsedTimeMs, RetrySleeper sleeper) {
+ try {
sleeper.sleepFor(retryIntervalMs, TimeUnit.MILLISECONDS);
- }
- catch (InterruptedException e)
- {
+ } catch (InterruptedException e) {
Thread.currentThread().interrupt();
log.warn("Error occurred while sleeping", e);
return false;
diff --git a/curator-client/src/main/java/org/apache/curator/retry/RetryNTimes.java b/curator-client/src/main/java/org/apache/curator/retry/RetryNTimes.java
index 71b5ed78..1ff49c34 100644
--- a/curator-client/src/main/java/org/apache/curator/retry/RetryNTimes.java
+++ b/curator-client/src/main/java/org/apache/curator/retry/RetryNTimes.java
@@ -22,19 +22,16 @@ package org.apache.curator.retry;
/**
* Retry policy that retries a max number of times
*/
-public class RetryNTimes extends SleepingRetry
-{
+public class RetryNTimes extends SleepingRetry {
private final int sleepMsBetweenRetries;
- public RetryNTimes(int n, int sleepMsBetweenRetries)
- {
+ public RetryNTimes(int n, int sleepMsBetweenRetries) {
super(n);
this.sleepMsBetweenRetries = sleepMsBetweenRetries;
}
@Override
- protected long getSleepTimeMs(int retryCount, long elapsedTimeMs)
- {
+ protected long getSleepTimeMs(int retryCount, long elapsedTimeMs) {
return sleepMsBetweenRetries;
}
}
diff --git a/curator-client/src/main/java/org/apache/curator/retry/RetryOneTime.java b/curator-client/src/main/java/org/apache/curator/retry/RetryOneTime.java
index cac6e0a5..89b6bfad 100644
--- a/curator-client/src/main/java/org/apache/curator/retry/RetryOneTime.java
+++ b/curator-client/src/main/java/org/apache/curator/retry/RetryOneTime.java
@@ -22,10 +22,8 @@ package org.apache.curator.retry;
/**
* A retry policy that retries only once
*/
-public class RetryOneTime extends RetryNTimes
-{
- public RetryOneTime(int sleepMsBetweenRetry)
- {
+public class RetryOneTime extends RetryNTimes {
+ public RetryOneTime(int sleepMsBetweenRetry) {
super(1, sleepMsBetweenRetry);
}
}
diff --git a/curator-client/src/main/java/org/apache/curator/retry/RetryUntilElapsed.java b/curator-client/src/main/java/org/apache/curator/retry/RetryUntilElapsed.java
index 3ce006e0..24fb94ee 100644
--- a/curator-client/src/main/java/org/apache/curator/retry/RetryUntilElapsed.java
+++ b/curator-client/src/main/java/org/apache/curator/retry/RetryUntilElapsed.java
@@ -24,28 +24,23 @@ import org.apache.curator.RetrySleeper;
/**
* A retry policy that retries until a given amount of time elapses
*/
-public class RetryUntilElapsed extends SleepingRetry
-{
+public class RetryUntilElapsed extends SleepingRetry {
private final int maxElapsedTimeMs;
private final int sleepMsBetweenRetries;
- public RetryUntilElapsed(int maxElapsedTimeMs, int sleepMsBetweenRetries)
- {
+ public RetryUntilElapsed(int maxElapsedTimeMs, int sleepMsBetweenRetries) {
super(Integer.MAX_VALUE);
this.maxElapsedTimeMs = maxElapsedTimeMs;
this.sleepMsBetweenRetries = sleepMsBetweenRetries;
}
@Override
- public boolean allowRetry(int retryCount, long elapsedTimeMs, RetrySleeper sleeper)
- {
+ public boolean allowRetry(int retryCount, long elapsedTimeMs, RetrySleeper sleeper) {
return super.allowRetry(retryCount, elapsedTimeMs, sleeper) && (elapsedTimeMs < maxElapsedTimeMs);
}
@Override
- protected long getSleepTimeMs(int retryCount, long elapsedTimeMs)
- {
+ protected long getSleepTimeMs(int retryCount, long elapsedTimeMs) {
return sleepMsBetweenRetries;
}
}
-
diff --git a/curator-client/src/main/java/org/apache/curator/retry/SleepingRetry.java b/curator-client/src/main/java/org/apache/curator/retry/SleepingRetry.java
index 8b729f53..a5d25684 100644
--- a/curator-client/src/main/java/org/apache/curator/retry/SleepingRetry.java
+++ b/curator-client/src/main/java/org/apache/curator/retry/SleepingRetry.java
@@ -19,35 +19,27 @@
package org.apache.curator.retry;
+import java.util.concurrent.TimeUnit;
import org.apache.curator.RetryPolicy;
import org.apache.curator.RetrySleeper;
-import java.util.concurrent.TimeUnit;
-abstract class SleepingRetry implements RetryPolicy
-{
+abstract class SleepingRetry implements RetryPolicy {
private final int n;
- protected SleepingRetry(int n)
- {
+ protected SleepingRetry(int n) {
this.n = n;
}
// made public for testing
- public int getN()
- {
+ public int getN() {
return n;
}
- public boolean allowRetry(int retryCount, long elapsedTimeMs, RetrySleeper sleeper)
- {
- if ( retryCount < n )
- {
- try
- {
+ public boolean allowRetry(int retryCount, long elapsedTimeMs, RetrySleeper sleeper) {
+ if (retryCount < n) {
+ try {
sleeper.sleepFor(getSleepTimeMs(retryCount, elapsedTimeMs), TimeUnit.MILLISECONDS);
- }
- catch ( InterruptedException e )
- {
+ } catch (InterruptedException e) {
Thread.currentThread().interrupt();
return false;
}
@@ -56,5 +48,5 @@ abstract class SleepingRetry implements RetryPolicy
return false;
}
- protected abstract long getSleepTimeMs(int retryCount, long elapsedTimeMs);
+ protected abstract long getSleepTimeMs(int retryCount, long elapsedTimeMs);
}
diff --git a/curator-client/src/main/java/org/apache/curator/utils/CloseableExecutorService.java b/curator-client/src/main/java/org/apache/curator/utils/CloseableExecutorService.java
index 29089637..f388305a 100644
--- a/curator-client/src/main/java/org/apache/curator/utils/CloseableExecutorService.java
+++ b/curator-client/src/main/java/org/apache/curator/utils/CloseableExecutorService.java
@@ -23,81 +23,70 @@ import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
import java.io.Closeable;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/**
* Decoration on an ExecutorService that tracks created futures and provides
* a method to close futures created via this class
*/
-public class CloseableExecutorService implements Closeable
-{
+public class CloseableExecutorService implements Closeable {
private final Logger log = LoggerFactory.getLogger(CloseableExecutorService.class);
private final Set<Future<?>> futures = Sets.newSetFromMap(Maps.<Future<?>, Boolean>newConcurrentMap());
private final ExecutorService executorService;
private final boolean shutdownOnClose;
protected final AtomicBoolean isOpen = new AtomicBoolean(true);
- protected class InternalScheduledFutureTask implements Future<Void>
- {
+ protected class InternalScheduledFutureTask implements Future<Void> {
private final ScheduledFuture<?> scheduledFuture;
- public InternalScheduledFutureTask(ScheduledFuture<?> scheduledFuture)
- {
+ public InternalScheduledFutureTask(ScheduledFuture<?> scheduledFuture) {
this.scheduledFuture = scheduledFuture;
futures.add(scheduledFuture);
}
@Override
- public boolean cancel(boolean mayInterruptIfRunning)
- {
+ public boolean cancel(boolean mayInterruptIfRunning) {
futures.remove(scheduledFuture);
return scheduledFuture.cancel(mayInterruptIfRunning);
}
@Override
- public boolean isCancelled()
- {
+ public boolean isCancelled() {
return scheduledFuture.isCancelled();
}
@Override
- public boolean isDone()
- {
+ public boolean isDone() {
return scheduledFuture.isDone();
}
@Override
- public Void get() throws InterruptedException, ExecutionException
- {
+ public Void get() throws InterruptedException, ExecutionException {
return null;
}
@Override
- public Void get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException
- {
+ public Void get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
return null;
}
}
- protected class InternalFutureTask<T> extends FutureTask<T>
- {
+ protected class InternalFutureTask<T> extends FutureTask<T> {
private final RunnableFuture<T> task;
- InternalFutureTask(RunnableFuture<T> task)
- {
+ InternalFutureTask(RunnableFuture<T> task) {
super(task, null);
this.task = task;
futures.add(task);
}
- protected void done()
- {
+ protected void done() {
futures.remove(task);
}
}
@@ -105,17 +94,15 @@ public class CloseableExecutorService implements Closeable
/**
* @param executorService the service to decorate
*/
- public CloseableExecutorService(ExecutorService executorService)
- {
- this(executorService, false);
+ public CloseableExecutorService(ExecutorService executorService) {
+ this(executorService, false);
}
/**
* @param executorService the service to decorate
* @param shutdownOnClose if true, shutdown the executor service when this is closed
*/
- public CloseableExecutorService(ExecutorService executorService, boolean shutdownOnClose)
- {
+ public CloseableExecutorService(ExecutorService executorService, boolean shutdownOnClose) {
this.executorService = Preconditions.checkNotNull(executorService, "executorService cannot be null");
this.shutdownOnClose = shutdownOnClose;
}
@@ -125,14 +112,12 @@ public class CloseableExecutorService implements Closeable
*
* @return <tt>true</tt> if this executor has been shut down
*/
- public boolean isShutdown()
- {
+ public boolean isShutdown() {
return !isOpen.get();
}
@VisibleForTesting
- int size()
- {
+ int size() {
return futures.size();
}
@@ -140,16 +125,13 @@ public class CloseableExecutorService implements Closeable
* Closes any tasks currently in progress
*/
@Override
- public void close()
- {
+ public void close() {
isOpen.set(false);
Iterator<Future<?>> iterator = futures.iterator();
- while ( iterator.hasNext() )
- {
+ while (iterator.hasNext()) {
Future<?> future = iterator.next();
iterator.remove();
- if ( !future.isDone() && !future.isCancelled() && !future.cancel(true) )
- {
+ if (!future.isDone() && !future.isCancelled() && !future.cancel(true)) {
log.warn("Could not cancel " + future);
}
}
@@ -166,8 +148,7 @@ public class CloseableExecutorService implements Closeable
* @param task the task to submit
* @return a future to watch the task
*/
- public<V> Future<V> submit(Callable<V> task)
- {
+ public <V> Future<V> submit(Callable<V> task) {
Preconditions.checkState(isOpen.get(), "CloseableExecutorService is closed");
InternalFutureTask<V> futureTask = new InternalFutureTask<V>(new FutureTask<V>(task));
@@ -183,8 +164,7 @@ public class CloseableExecutorService implements Closeable
* @param task the task to submit
* @return a future to watch the task
*/
- public Future<?> submit(Runnable task)
- {
+ public Future<?> submit(Runnable task) {
Preconditions.checkState(isOpen.get(), "CloseableExecutorService is closed");
InternalFutureTask<Void> futureTask = new InternalFutureTask<Void>(new FutureTask<Void>(task, null));
diff --git a/curator-client/src/main/java/org/apache/curator/utils/CloseableScheduledExecutorService.java b/curator-client/src/main/java/org/apache/curator/utils/CloseableScheduledExecutorService.java
index 5b832b74..8fbc420e 100644
--- a/curator-client/src/main/java/org/apache/curator/utils/CloseableScheduledExecutorService.java
+++ b/curator-client/src/main/java/org/apache/curator/utils/CloseableScheduledExecutorService.java
@@ -30,15 +30,13 @@ import java.util.concurrent.TimeUnit;
* Decoration on an ScheduledExecutorService that tracks created futures and provides
* a method to close futures created via this class
*/
-public class CloseableScheduledExecutorService extends CloseableExecutorService
-{
+public class CloseableScheduledExecutorService extends CloseableExecutorService {
private final ScheduledExecutorService scheduledExecutorService;
/**
* @param scheduledExecutorService the service to decorate
*/
- public CloseableScheduledExecutorService(ScheduledExecutorService scheduledExecutorService)
- {
+ public CloseableScheduledExecutorService(ScheduledExecutorService scheduledExecutorService) {
super(scheduledExecutorService, false);
this.scheduledExecutorService = scheduledExecutorService;
}
@@ -47,8 +45,8 @@ public class CloseableScheduledExecutorService extends CloseableExecutorService
* @param scheduledExecutorService the service to decorate
* @param shutdownOnClose if true, shutdown the executor service when this is closed
*/
- public CloseableScheduledExecutorService(ScheduledExecutorService scheduledExecutorService, boolean shutdownOnClose)
- {
+ public CloseableScheduledExecutorService(
+ ScheduledExecutorService scheduledExecutorService, boolean shutdownOnClose) {
super(scheduledExecutorService, shutdownOnClose);
this.scheduledExecutorService = scheduledExecutorService;
}
@@ -64,8 +62,7 @@ public class CloseableScheduledExecutorService extends CloseableExecutorService
* the task and whose <tt>get()</tt> method will return
* <tt>null</tt> upon completion
*/
- public Future<?> schedule(Runnable task, long delay, TimeUnit unit)
- {
+ public Future<?> schedule(Runnable task, long delay, TimeUnit unit) {
Preconditions.checkState(isOpen.get(), "CloseableExecutorService is closed");
InternalFutureTask<Void> futureTask = new InternalFutureTask<Void>(new FutureTask<Void>(task, null));
@@ -91,11 +88,11 @@ public class CloseableScheduledExecutorService extends CloseableExecutorService
* the task, and whose <tt>get()</tt> method will throw an
* exception upon cancellation
*/
- public Future<?> scheduleWithFixedDelay(Runnable task, long initialDelay, long delay, TimeUnit unit)
- {
+ public Future<?> scheduleWithFixedDelay(Runnable task, long initialDelay, long delay, TimeUnit unit) {
Preconditions.checkState(isOpen.get(), "CloseableExecutorService is closed");
- ScheduledFuture<?> scheduledFuture = scheduledExecutorService.scheduleWithFixedDelay(task, initialDelay, delay, unit);
+ ScheduledFuture<?> scheduledFuture =
+ scheduledExecutorService.scheduleWithFixedDelay(task, initialDelay, delay, unit);
return new InternalScheduledFutureTask(scheduledFuture);
}
}
diff --git a/curator-client/src/main/java/org/apache/curator/utils/CloseableUtils.java b/curator-client/src/main/java/org/apache/curator/utils/CloseableUtils.java
index fd0a84f9..63fc0fe7 100644
--- a/curator-client/src/main/java/org/apache/curator/utils/CloseableUtils.java
+++ b/curator-client/src/main/java/org/apache/curator/utils/CloseableUtils.java
@@ -20,16 +20,15 @@
package org.apache.curator.utils;
import com.google.common.io.Closeables;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
import java.io.Closeable;
import java.io.IOException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/**
* This class adds back functionality that was removed in Guava v16.0.
*/
-public class CloseableUtils
-{
+public class CloseableUtils {
private static final Logger log = LoggerFactory.getLogger(CloseableUtils.class);
/**
@@ -51,15 +50,11 @@ public class CloseableUtils
* See <a href="https://issues.apache.org/jira/browse/CURATOR-85">https://issues.apache.org/jira/browse/CURATOR-85</a>
* </p>
*/
- public static void closeQuietly(Closeable closeable)
- {
- try
- {
+ public static void closeQuietly(Closeable closeable) {
+ try {
// Here we've instructed Guava to swallow the IOException
Closeables.close(closeable, true);
- }
- catch ( IOException e )
- {
+ } catch (IOException e) {
// We instructed Guava to swallow the IOException, so this should
// never happen. Since it did, log it.
log.error("IOException should not have been thrown.", e);
diff --git a/curator-client/src/main/java/org/apache/curator/utils/Compatibility.java b/curator-client/src/main/java/org/apache/curator/utils/Compatibility.java
index 5e5f2987..03545cde 100644
--- a/curator-client/src/main/java/org/apache/curator/utils/Compatibility.java
+++ b/curator-client/src/main/java/org/apache/curator/utils/Compatibility.java
@@ -19,105 +19,81 @@
package org.apache.curator.utils;
-import org.apache.zookeeper.server.quorum.QuorumPeer;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.InetSocketAddress;
+import org.apache.zookeeper.server.quorum.QuorumPeer;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/**
* Utils to help with ZK version compatibility
*/
-public class Compatibility
-{
+public class Compatibility {
private static final Logger log = LoggerFactory.getLogger(Compatibility.class);
private static final Method getReachableOrOneMethod;
private static final Field addrField;
private static final boolean hasPersistentWatchers;
- static
- {
+ static {
Method localGetReachableOrOneMethod;
- try
- {
+ try {
Class<?> multipleAddressesClass = Class.forName("org.apache.zookeeper.server.quorum.MultipleAddresses");
localGetReachableOrOneMethod = multipleAddressesClass.getMethod("getReachableOrOne");
log.info("Using org.apache.zookeeper.server.quorum.MultipleAddresses");
- }
- catch ( ReflectiveOperationException ignore )
- {
+ } catch (ReflectiveOperationException ignore) {
localGetReachableOrOneMethod = null;
}
getReachableOrOneMethod = localGetReachableOrOneMethod;
Field localAddrField;
- try
- {
+ try {
localAddrField = QuorumPeer.QuorumServer.class.getField("addr");
- }
- catch ( NoSuchFieldException e )
- {
+ } catch (NoSuchFieldException e) {
localAddrField = null;
log.error("Could not get addr field! Reconfiguration fail!");
}
addrField = localAddrField;
boolean localHasPersistentWatchers;
- try
- {
+ try {
Class.forName("org.apache.zookeeper.AddWatchMode");
localHasPersistentWatchers = true;
- }
- catch ( ClassNotFoundException e )
- {
+ } catch (ClassNotFoundException e) {
localHasPersistentWatchers = false;
log.info("Persistent Watchers are not available in the version of the ZooKeeper library being used");
}
hasPersistentWatchers = localHasPersistentWatchers;
}
- public static boolean hasGetReachableOrOneMethod()
- {
+ public static boolean hasGetReachableOrOneMethod() {
return (getReachableOrOneMethod != null);
}
- public static boolean hasAddrField()
- {
+ public static boolean hasAddrField() {
return (addrField != null);
}
- public static String getHostString(QuorumPeer.QuorumServer server)
- {
+ public static String getHostString(QuorumPeer.QuorumServer server) {
InetSocketAddress address = null;
- if ( getReachableOrOneMethod != null )
- {
- try
- {
- address = (InetSocketAddress)getReachableOrOneMethod.invoke(server.addr);
- }
- catch ( Exception e )
- {
+ if (getReachableOrOneMethod != null) {
+ try {
+ address = (InetSocketAddress) getReachableOrOneMethod.invoke(server.addr);
+ } catch (Exception e) {
log.error("Could not call getReachableOrOneMethod.invoke({})", server.addr, e);
}
- }
- else if (addrField != null)
- {
- try
- {
- address = (InetSocketAddress)addrField.get(server);
- }
- catch ( Exception e )
- {
+ } else if (addrField != null) {
+ try {
+ address = (InetSocketAddress) addrField.get(server);
+ } catch (Exception e) {
log.error("Could not call addrField.get({})", server, e);
}
}
return address != null ? address.getHostString() : "unknown";
}
- public static boolean hasPersistentWatchers()
- {
+ public static boolean hasPersistentWatchers() {
return hasPersistentWatchers;
}
}
diff --git a/curator-client/src/main/java/org/apache/curator/utils/ConfigurableZookeeperFactory.java b/curator-client/src/main/java/org/apache/curator/utils/ConfigurableZookeeperFactory.java
index 6a8d6e83..10821cfe 100644
--- a/curator-client/src/main/java/org/apache/curator/utils/ConfigurableZookeeperFactory.java
+++ b/curator-client/src/main/java/org/apache/curator/utils/ConfigurableZookeeperFactory.java
@@ -28,12 +28,15 @@ import org.apache.zookeeper.client.ZKClientConfig;
* Configurable ZookeeperFactory, by using org.apache.zookeeper.client.ZKClientConfig.
*
*/
-public class ConfigurableZookeeperFactory extends DefaultZookeeperFactory
-{
-
- public ZooKeeper newZooKeeper(String connectString, int sessionTimeout, Watcher watcher,
- boolean canBeReadOnly, ZKClientConfig zkClientConfig) throws Exception
- {
- return new ZooKeeperAdmin(connectString, sessionTimeout, watcher, canBeReadOnly, zkClientConfig);
+public class ConfigurableZookeeperFactory extends DefaultZookeeperFactory {
+
+ public ZooKeeper newZooKeeper(
+ String connectString,
+ int sessionTimeout,
+ Watcher watcher,
+ boolean canBeReadOnly,
+ ZKClientConfig zkClientConfig)
+ throws Exception {
+ return new ZooKeeperAdmin(connectString, sessionTimeout, watcher, canBeReadOnly, zkClientConfig);
}
}
diff --git a/curator-client/src/main/java/org/apache/curator/utils/DebugUtils.java b/curator-client/src/main/java/org/apache/curator/utils/DebugUtils.java
index 0cc4227a..a99348cc 100644
--- a/curator-client/src/main/java/org/apache/curator/utils/DebugUtils.java
+++ b/curator-client/src/main/java/org/apache/curator/utils/DebugUtils.java
@@ -19,17 +19,15 @@
package org.apache.curator.utils;
-public class DebugUtils
-{
+public class DebugUtils {
public static final String PROPERTY_LOG_EVENTS = "curator-log-events";
public static final String PROPERTY_DONT_LOG_CONNECTION_ISSUES = "curator-dont-log-connection-problems";
- public static final String PROPERTY_LOG_ONLY_FIRST_CONNECTION_ISSUE_AS_ERROR_LEVEL = "curator-log-only-first-connection-issue-as-error-level";
+ public static final String PROPERTY_LOG_ONLY_FIRST_CONNECTION_ISSUE_AS_ERROR_LEVEL =
+ "curator-log-only-first-connection-issue-as-error-level";
public static final String PROPERTY_REMOVE_WATCHERS_IN_FOREGROUND = "curator-remove-watchers-in-foreground";
- public static final String PROPERTY_VALIDATE_NAMESPACE_WATCHER_MAP_EMPTY = "curator-validate-namespace-watcher-map-empty";
+ public static final String PROPERTY_VALIDATE_NAMESPACE_WATCHER_MAP_EMPTY =
+ "curator-validate-namespace-watcher-map-empty";
public static final String PROPERTY_VALIDATE_NO_REMAINING_WATCHERS = "curator-validate-no-remaining-watchers";
-
- private DebugUtils()
- {
- }
+ private DebugUtils() {}
}
diff --git a/curator-client/src/main/java/org/apache/curator/utils/DefaultTracerDriver.java b/curator-client/src/main/java/org/apache/curator/utils/DefaultTracerDriver.java
index 5439421a..22dd1f65 100644
--- a/curator-client/src/main/java/org/apache/curator/utils/DefaultTracerDriver.java
+++ b/curator-client/src/main/java/org/apache/curator/utils/DefaultTracerDriver.java
@@ -19,32 +19,27 @@
package org.apache.curator.utils;
+import java.util.concurrent.TimeUnit;
import org.apache.curator.drivers.TracerDriver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.util.concurrent.TimeUnit;
/**
* Default tracer driver
*/
-public class DefaultTracerDriver implements TracerDriver
-{
+public class DefaultTracerDriver implements TracerDriver {
private final Logger log = LoggerFactory.getLogger(getClass());
@Override
- public void addTrace(String name, long time, TimeUnit unit)
- {
- if ( log.isTraceEnabled() )
- {
+ public void addTrace(String name, long time, TimeUnit unit) {
+ if (log.isTraceEnabled()) {
log.trace("Trace: " + name + " - " + TimeUnit.MILLISECONDS.convert(time, unit) + " ms");
}
}
@Override
- public void addCount(String name, int increment)
- {
- if ( log.isTraceEnabled() )
- {
+ public void addCount(String name, int increment) {
+ if (log.isTraceEnabled()) {
log.trace("Counter " + name + ": " + increment);
}
}
diff --git a/curator-client/src/main/java/org/apache/curator/utils/DefaultZookeeperFactory.java b/curator-client/src/main/java/org/apache/curator/utils/DefaultZookeeperFactory.java
index c9bf1971..af3e4b26 100644
--- a/curator-client/src/main/java/org/apache/curator/utils/DefaultZookeeperFactory.java
+++ b/curator-client/src/main/java/org/apache/curator/utils/DefaultZookeeperFactory.java
@@ -23,11 +23,10 @@ import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.admin.ZooKeeperAdmin;
-public class DefaultZookeeperFactory implements ZookeeperFactory
-{
+public class DefaultZookeeperFactory implements ZookeeperFactory {
@Override
- public ZooKeeper newZooKeeper(String connectString, int sessionTimeout, Watcher watcher, boolean canBeReadOnly) throws Exception
- {
+ public ZooKeeper newZooKeeper(String connectString, int sessionTimeout, Watcher watcher, boolean canBeReadOnly)
+ throws Exception {
return new ZooKeeperAdmin(connectString, sessionTimeout, watcher, canBeReadOnly);
}
}
diff --git a/curator-client/src/main/java/org/apache/curator/utils/EnsurePath.java b/curator-client/src/main/java/org/apache/curator/utils/EnsurePath.java
index 2843f344..ce23cbd8 100644
--- a/curator-client/src/main/java/org/apache/curator/utils/EnsurePath.java
+++ b/curator-client/src/main/java/org/apache/curator/utils/EnsurePath.java
@@ -19,11 +19,11 @@
package org.apache.curator.utils;
+import java.util.concurrent.Callable;
+import java.util.concurrent.atomic.AtomicReference;
import org.apache.curator.CuratorZookeeperClient;
import org.apache.curator.RetryLoop;
import org.apache.zookeeper.ZooKeeper;
-import java.util.concurrent.Callable;
-import java.util.concurrent.atomic.AtomicReference;
/**
* <p>
@@ -51,32 +51,27 @@ import java.util.concurrent.atomic.AtomicReference;
* @deprecated Since 2.9.0 - Prefer CuratorFramework.create().creatingParentContainersIfNeeded() or CuratorFramework.exists().creatingParentContainersIfNeeded()
*/
@Deprecated
-public class EnsurePath
-{
+public class EnsurePath {
private final String path;
private final boolean makeLastNode;
private final InternalACLProvider aclProvider;
private final AtomicReference<Helper> helper;
- private static final Helper doNothingHelper = new Helper()
- {
+ private static final Helper doNothingHelper = new Helper() {
@Override
- public void ensure(CuratorZookeeperClient client, String path, final boolean makeLastNode) throws Exception
- {
+ public void ensure(CuratorZookeeperClient client, String path, final boolean makeLastNode) throws Exception {
// NOP
}
};
- interface Helper
- {
+ interface Helper {
public void ensure(CuratorZookeeperClient client, String path, final boolean makeLastNode) throws Exception;
}
/**
* @param path the full path to ensure
*/
- public EnsurePath(String path)
- {
+ public EnsurePath(String path) {
this(path, null, true, null);
}
@@ -84,8 +79,7 @@ public class EnsurePath
* @param path the full path to ensure
* @param aclProvider if not null, the ACL provider to use when creating parent nodes
*/
- public EnsurePath(String path, InternalACLProvider aclProvider)
- {
+ public EnsurePath(String path, InternalACLProvider aclProvider) {
this(path, null, true, aclProvider);
}
@@ -96,8 +90,7 @@ public class EnsurePath
* @param client ZK client
* @throws Exception ZK errors
*/
- public void ensure(CuratorZookeeperClient client) throws Exception
- {
+ public void ensure(CuratorZookeeperClient client) throws Exception {
Helper localHelper = helper.get();
localHelper.ensure(client, path, makeLastNode);
}
@@ -108,13 +101,12 @@ public class EnsurePath
*
* @return view
*/
- public EnsurePath excludingLast()
- {
+ public EnsurePath excludingLast() {
return new EnsurePath(path, helper, false, aclProvider);
}
- protected EnsurePath(String path, AtomicReference<Helper> helper, boolean makeLastNode, InternalACLProvider aclProvider)
- {
+ protected EnsurePath(
+ String path, AtomicReference<Helper> helper, boolean makeLastNode, InternalACLProvider aclProvider) {
this.path = path;
this.makeLastNode = makeLastNode;
this.aclProvider = aclProvider;
@@ -126,40 +118,30 @@ public class EnsurePath
*
* @return the path being ensured
*/
- public String getPath()
- {
+ public String getPath() {
return this.path;
}
- protected boolean asContainers()
- {
+ protected boolean asContainers() {
return false;
}
- private class InitialHelper implements Helper
- {
- private boolean isSet = false; // guarded by synchronization
+ private class InitialHelper implements Helper {
+ private boolean isSet = false; // guarded by synchronization
@Override
- public synchronized void ensure(final CuratorZookeeperClient client, final String path, final boolean makeLastNode) throws Exception
- {
- if ( !isSet )
- {
- RetryLoop.callWithRetry
- (
- client,
- new Callable<Object>()
- {
- @Override
- public Object call() throws Exception
- {
- ZKPaths.mkdirs(client.getZooKeeper(), path, makeLastNode, aclProvider, asContainers());
- helper.set(doNothingHelper);
- isSet = true;
- return null;
- }
- }
- );
+ public synchronized void ensure(
+ final CuratorZookeeperClient client, final String path, final boolean makeLastNode) throws Exception {
+ if (!isSet) {
+ RetryLoop.callWithRetry(client, new Callable<Object>() {
+ @Override
+ public Object call() throws Exception {
+ ZKPaths.mkdirs(client.getZooKeeper(), path, makeLastNode, aclProvider, asContainers());
+ helper.set(doNothingHelper);
+ isSet = true;
+ return null;
+ }
+ });
}
}
}
diff --git a/curator-client/src/main/java/org/apache/curator/utils/ExceptionAccumulator.java b/curator-client/src/main/java/org/apache/curator/utils/ExceptionAccumulator.java
index 932c2274..64e81318 100644
--- a/curator-client/src/main/java/org/apache/curator/utils/ExceptionAccumulator.java
+++ b/curator-client/src/main/java/org/apache/curator/utils/ExceptionAccumulator.java
@@ -25,17 +25,14 @@ import com.google.common.base.Throwables;
* Utility to accumulate multiple potential exceptions into one that
* is thrown at the end
*/
-public class ExceptionAccumulator
-{
+public class ExceptionAccumulator {
private volatile Throwable mainEx = null;
/**
* If there is an accumulated exception, throw it
*/
- public void propagate()
- {
- if ( mainEx != null )
- {
+ public void propagate() {
+ if (mainEx != null) {
Throwables.propagate(mainEx);
}
}
@@ -47,23 +44,17 @@ public class ExceptionAccumulator
*
* @param e the exception
*/
- public void add(Throwable e)
- {
- if ( e instanceof InterruptedException )
- {
- if ( mainEx != null )
- {
+ public void add(Throwable e) {
+ if (e instanceof InterruptedException) {
+ if (mainEx != null) {
e.addSuppressed(mainEx);
}
Thread.currentThread().interrupt();
}
- if ( mainEx == null )
- {
+ if (mainEx == null) {
mainEx = e;
- }
- else
- {
+ } else {
mainEx.addSuppressed(e);
}
}
diff --git a/curator-client/src/main/java/org/apache/curator/utils/InternalACLProvider.java b/curator-client/src/main/java/org/apache/curator/utils/InternalACLProvider.java
index 13e79e54..caba991b 100644
--- a/curator-client/src/main/java/org/apache/curator/utils/InternalACLProvider.java
+++ b/curator-client/src/main/java/org/apache/curator/utils/InternalACLProvider.java
@@ -19,12 +19,11 @@
package org.apache.curator.utils;
+import java.util.List;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.data.ACL;
-import java.util.List;
-public interface InternalACLProvider
-{
+public interface InternalACLProvider {
/**
* Return the ACL list to use by default (usually {@link ZooDefs.Ids#OPEN_ACL_UNSAFE}).
*
@@ -38,5 +37,5 @@ public interface InternalACLProvider
* @param path path (NOTE: might be null)
* @return ACL list
*/
- public List<ACL> getAclForPath(String path);
+ public List<ACL> getAclForPath(String path);
}
diff --git a/curator-client/src/main/java/org/apache/curator/utils/NonAdminZookeeperFactory.java b/curator-client/src/main/java/org/apache/curator/utils/NonAdminZookeeperFactory.java
index cb36a729..22be8ba6 100644
--- a/curator-client/src/main/java/org/apache/curator/utils/NonAdminZookeeperFactory.java
+++ b/curator-client/src/main/java/org/apache/curator/utils/NonAdminZookeeperFactory.java
@@ -22,11 +22,10 @@ package org.apache.curator.utils;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
-public class NonAdminZookeeperFactory implements ZookeeperFactory
-{
+public class NonAdminZookeeperFactory implements ZookeeperFactory {
@Override
- public ZooKeeper newZooKeeper(String connectString, int sessionTimeout, Watcher watcher, boolean canBeReadOnly) throws Exception
- {
+ public ZooKeeper newZooKeeper(String connectString, int sessionTimeout, Watcher watcher, boolean canBeReadOnly)
+ throws Exception {
return new ZooKeeper(connectString, sessionTimeout, watcher, canBeReadOnly);
}
}
diff --git a/curator-client/src/main/java/org/apache/curator/utils/PathUtils.java b/curator-client/src/main/java/org/apache/curator/utils/PathUtils.java
index 110f3b0e..d8c7af4d 100644
--- a/curator-client/src/main/java/org/apache/curator/utils/PathUtils.java
+++ b/curator-client/src/main/java/org/apache/curator/utils/PathUtils.java
@@ -33,9 +33,8 @@ public class PathUtils {
* with a sequential flag
* @throws IllegalArgumentException if the path is invalid
*/
- public static void validatePath(String path, boolean isSequential)
- throws IllegalArgumentException {
- validatePath(isSequential? path + "1": path);
+ public static void validatePath(String path, boolean isSequential) throws IllegalArgumentException {
+ validatePath(isSequential ? path + "1" : path);
}
/**
@@ -52,15 +51,13 @@ public class PathUtils {
throw new IllegalArgumentException("Path length must be > 0");
}
if (path.charAt(0) != '/') {
- throw new IllegalArgumentException(
- "Path must start with / character");
+ throw new IllegalArgumentException("Path must start with / character");
}
if (path.length() == 1) { // done checking - it's the root
return path;
}
if (path.charAt(path.length() - 1) == '/') {
- throw new IllegalArgumentException(
- "Path must not end with / character");
+ throw new IllegalArgumentException("Path must not end with / character");
}
String reason = null;
@@ -77,16 +74,12 @@ public class PathUtils {
reason = "empty node name specified @" + i;
break;
} else if (c == '.' && lastc == '.') {
- if (chars[i-2] == '/' &&
- ((i + 1 == chars.length)
- || chars[i+1] == '/')) {
+ if (chars[i - 2] == '/' && ((i + 1 == chars.length) || chars[i + 1] == '/')) {
reason = "relative paths not allowed @" + i;
break;
}
} else if (c == '.') {
- if (chars[i-1] == '/' &&
- ((i + 1 == chars.length)
- || chars[i+1] == '/')) {
+ if (chars[i - 1] == '/' && ((i + 1 == chars.length) || chars[i + 1] == '/')) {
reason = "relative paths not allowed @" + i;
break;
}
@@ -100,8 +93,7 @@ public class PathUtils {
}
if (reason != null) {
- throw new IllegalArgumentException(
- "Invalid path string \"" + path + "\" caused by " + reason);
+ throw new IllegalArgumentException("Invalid path string \"" + path + "\" caused by " + reason);
}
return path;
diff --git a/curator-client/src/main/java/org/apache/curator/utils/ThreadUtils.java b/curator-client/src/main/java/org/apache/curator/utils/ThreadUtils.java
index a89963e1..7c2a8010 100644
--- a/curator-client/src/main/java/org/apache/curator/utils/ThreadUtils.java
+++ b/curator-client/src/main/java/org/apache/curator/utils/ThreadUtils.java
@@ -21,74 +21,61 @@ package org.apache.curator.utils;
import com.google.common.base.Throwables;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
-public class ThreadUtils
-{
+public class ThreadUtils {
private static final Logger log = LoggerFactory.getLogger(ThreadUtils.class);
- public static boolean checkInterrupted(Throwable e)
- {
- if ( e instanceof InterruptedException )
- {
+ public static boolean checkInterrupted(Throwable e) {
+ if (e instanceof InterruptedException) {
Thread.currentThread().interrupt();
return true;
}
return false;
}
- public static ExecutorService newSingleThreadExecutor(String processName)
- {
+ public static ExecutorService newSingleThreadExecutor(String processName) {
return Executors.newSingleThreadExecutor(newThreadFactory(processName));
}
- public static ExecutorService newFixedThreadPool(int qty, String processName)
- {
+ public static ExecutorService newFixedThreadPool(int qty, String processName) {
return Executors.newFixedThreadPool(qty, newThreadFactory(processName));
}
- public static ScheduledExecutorService newSingleThreadScheduledExecutor(String processName)
- {
+ public static ScheduledExecutorService newSingleThreadScheduledExecutor(String processName) {
return Executors.newSingleThreadScheduledExecutor(newThreadFactory(processName));
}
- public static ScheduledExecutorService newFixedThreadScheduledPool(int qty, String processName)
- {
+ public static ScheduledExecutorService newFixedThreadScheduledPool(int qty, String processName) {
return Executors.newScheduledThreadPool(qty, newThreadFactory(processName));
}
- public static ThreadFactory newThreadFactory(String processName)
- {
+ public static ThreadFactory newThreadFactory(String processName) {
return newGenericThreadFactory("Curator-" + processName);
}
- public static ThreadFactory newGenericThreadFactory(String processName)
- {
- Thread.UncaughtExceptionHandler uncaughtExceptionHandler = new Thread.UncaughtExceptionHandler()
- {
+ public static ThreadFactory newGenericThreadFactory(String processName) {
+ Thread.UncaughtExceptionHandler uncaughtExceptionHandler = new Thread.UncaughtExceptionHandler() {
@Override
- public void uncaughtException(Thread t, Throwable e)
- {
+ public void uncaughtException(Thread t, Throwable e) {
log.error("Unexpected exception in thread: " + t, e);
Throwables.propagate(e);
}
};
return new ThreadFactoryBuilder()
- .setNameFormat(processName + "-%d")
- .setDaemon(true)
- .setUncaughtExceptionHandler(uncaughtExceptionHandler)
- .build();
+ .setNameFormat(processName + "-%d")
+ .setDaemon(true)
+ .setUncaughtExceptionHandler(uncaughtExceptionHandler)
+ .build();
}
- public static String getProcessName(Class<?> clazz)
- {
- if ( clazz.isAnonymousClass() )
- {
+ public static String getProcessName(Class<?> clazz) {
+ if (clazz.isAnonymousClass()) {
return getProcessName(clazz.getEnclosingClass());
}
return clazz.getSimpleName();
diff --git a/curator-client/src/main/java/org/apache/curator/utils/ZKPaths.java b/curator-client/src/main/java/org/apache/curator/utils/ZKPaths.java
index 9ac88e16..5364ab5c 100644
--- a/curator-client/src/main/java/org/apache/curator/utils/ZKPaths.java
+++ b/curator-client/src/main/java/org/apache/curator/utils/ZKPaths.java
@@ -31,8 +31,7 @@ import org.apache.zookeeper.data.ACL;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-public class ZKPaths
-{
+public class ZKPaths {
/**
* Zookeeper's path separator character.
*/
@@ -45,8 +44,7 @@ public class ZKPaths
/**
* @return {@link CreateMode#CONTAINER} if the ZK JAR supports it. Otherwise {@link CreateMode#PERSISTENT}
*/
- public static CreateMode getContainerCreateMode()
- {
+ public static CreateMode getContainerCreateMode() {
return CreateModeHolder.containerCreateMode;
}
@@ -55,27 +53,22 @@ public class ZKPaths
*
* @return true/false
*/
- public static boolean hasContainerSupport()
- {
+ public static boolean hasContainerSupport() {
return getContainerCreateMode() != NON_CONTAINER_MODE;
}
- private static class CreateModeHolder
- {
+ private static class CreateModeHolder {
private static final Logger log = LoggerFactory.getLogger(ZKPaths.class);
private static final CreateMode containerCreateMode;
- static
- {
+ static {
CreateMode localCreateMode;
- try
- {
+ try {
localCreateMode = CreateMode.valueOf("CONTAINER");
- }
- catch ( IllegalArgumentException ignore )
- {
+ } catch (IllegalArgumentException ignore) {
localCreateMode = NON_CONTAINER_MODE;
- log.warn("The version of ZooKeeper being used doesn't support Container nodes. CreateMode.PERSISTENT will be used instead.");
+ log.warn(
+ "The version of ZooKeeper being used doesn't support Container nodes. CreateMode.PERSISTENT will be used instead.");
}
containerCreateMode = localCreateMode;
}
@@ -88,8 +81,7 @@ public class ZKPaths
* @param path path
* @return adjusted path
*/
- public static String fixForNamespace(String namespace, String path)
- {
+ public static String fixForNamespace(String namespace, String path) {
return fixForNamespace(namespace, path, false);
}
@@ -101,13 +93,11 @@ public class ZKPaths
* @param isSequential if the path is being created with a sequential flag
* @return adjusted path
*/
- public static String fixForNamespace(String namespace, String path, boolean isSequential)
- {
+ public static String fixForNamespace(String namespace, String path, boolean isSequential) {
// Child path must be valid in and of itself.
PathUtils.validatePath(path, isSequential);
- if ( namespace != null )
- {
+ if (namespace != null) {
return makePath(namespace, path);
}
return path;
@@ -119,45 +109,37 @@ public class ZKPaths
* @param path the path
* @return the node
*/
- public static String getNodeFromPath(String path)
- {
+ public static String getNodeFromPath(String path) {
PathUtils.validatePath(path);
int i = path.lastIndexOf(PATH_SEPARATOR_CHAR);
- if ( i < 0 )
- {
+ if (i < 0) {
return path;
}
- if ( (i + 1) >= path.length() )
- {
+ if ((i + 1) >= path.length()) {
return "";
}
return path.substring(i + 1);
}
- public static class PathAndNode
- {
+ public static class PathAndNode {
private final String path;
private final String node;
- public PathAndNode(String path, String node)
- {
+ public PathAndNode(String path, String node) {
this.path = path;
this.node = node;
}
- public String getPath()
- {
+ public String getPath() {
return path;
}
- public String getNode()
- {
+ public String getNode() {
return node;
}
@Override
- public int hashCode()
- {
+ public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + node.hashCode();
@@ -166,35 +148,28 @@ public class ZKPaths
}
@Override
- public boolean equals(Object obj)
- {
- if (this == obj)
- {
- return true;
+ public boolean equals(Object obj) {
+ if (this == obj) {
+ return true;
}
- if (obj == null)
- {
- return false;
+ if (obj == null) {
+ return false;
}
- if (getClass() != obj.getClass())
- {
- return false;
+ if (getClass() != obj.getClass()) {
+ return false;
}
PathAndNode other = (PathAndNode) obj;
- if (!node.equals(other.node))
- {
- return false;
+ if (!node.equals(other.node)) {
+ return false;
}
- if (!path.equals(other.path))
- {
- return false;
+ if (!path.equals(other.path)) {
+ return false;
}
return true;
}
@Override
- public String toString()
- {
+ public String toString() {
return "PathAndNode [path=" + path + ", node=" + node + "]";
}
}
@@ -205,16 +180,13 @@ public class ZKPaths
* @param path the path
* @return the node
*/
- public static PathAndNode getPathAndNode(String path)
- {
+ public static PathAndNode getPathAndNode(String path) {
PathUtils.validatePath(path);
int i = path.lastIndexOf(PATH_SEPARATOR_CHAR);
- if ( i < 0 )
- {
+ if (i < 0) {
return new PathAndNode(path, "");
}
- if ( (i + 1) >= path.length() )
- {
+ if ((i + 1) >= path.length()) {
return new PathAndNode(PATH_SEPARATOR, "");
}
String node = path.substring(i + 1);
@@ -237,7 +209,8 @@ public class ZKPaths
return length > SEQUENTIAL_SUFFIX_DIGITS ? path.substring(length - SEQUENTIAL_SUFFIX_DIGITS) : path;
}
- private static final Splitter PATH_SPLITTER = Splitter.on(PATH_SEPARATOR_CHAR).omitEmptyStrings();
+ private static final Splitter PATH_SPLITTER =
+ Splitter.on(PATH_SEPARATOR_CHAR).omitEmptyStrings();
/**
* Given a full path, return the the individual parts, without slashes.
@@ -246,8 +219,7 @@ public class ZKPaths
* @param path the path
* @return an array of parts
*/
- public static List<String> split(String path)
- {
+ public static List<String> split(String path) {
PathUtils.validatePath(path);
return PATH_SPLITTER.splitToList(path);
}
@@ -261,8 +233,7 @@ public class ZKPaths
* @throws InterruptedException thread interruption
* @throws org.apache.zookeeper.KeeperException Zookeeper errors
*/
- public static void mkdirs(ZooKeeper zookeeper, String path) throws InterruptedException, KeeperException
- {
+ public static void mkdirs(ZooKeeper zookeeper, String path) throws InterruptedException, KeeperException {
mkdirs(zookeeper, path, true, null, false);
}
@@ -276,8 +247,8 @@ public class ZKPaths
* @throws InterruptedException thread interruption
* @throws org.apache.zookeeper.KeeperException Zookeeper errors
*/
- public static void mkdirs(ZooKeeper zookeeper, String path, boolean makeLastNode) throws InterruptedException, KeeperException
- {
+ public static void mkdirs(ZooKeeper zookeeper, String path, boolean makeLastNode)
+ throws InterruptedException, KeeperException {
mkdirs(zookeeper, path, makeLastNode, null, false);
}
@@ -292,8 +263,8 @@ public class ZKPaths
* @throws InterruptedException thread interruption
* @throws org.apache.zookeeper.KeeperException Zookeeper errors
*/
- public static void mkdirs(ZooKeeper zookeeper, String path, boolean makeLastNode, InternalACLProvider aclProvider) throws InterruptedException, KeeperException
- {
+ public static void mkdirs(ZooKeeper zookeeper, String path, boolean makeLastNode, InternalACLProvider aclProvider)
+ throws InterruptedException, KeeperException {
mkdirs(zookeeper, path, makeLastNode, aclProvider, false);
}
@@ -309,55 +280,47 @@ public class ZKPaths
* @throws InterruptedException thread interruption
* @throws org.apache.zookeeper.KeeperException Zookeeper errors
*/
- public static void mkdirs(ZooKeeper zookeeper, String path, boolean makeLastNode, InternalACLProvider aclProvider, boolean asContainers) throws InterruptedException, KeeperException
- {
+ public static void mkdirs(
+ ZooKeeper zookeeper,
+ String path,
+ boolean makeLastNode,
+ InternalACLProvider aclProvider,
+ boolean asContainers)
+ throws InterruptedException, KeeperException {
PathUtils.validatePath(path);
int pos = 1; // skip first slash, root is guaranteed to exist
- do
- {
+ do {
pos = path.indexOf(PATH_SEPARATOR_CHAR, pos + 1);
- if ( pos == -1 )
- {
- if ( makeLastNode )
- {
+ if (pos == -1) {
+ if (makeLastNode) {
pos = path.length();
- }
- else
- {
+ } else {
break;
}
}
String subPath = path.substring(0, pos);
- if ( zookeeper.exists(subPath, false) == null )
- {
- try
- {
+ if (zookeeper.exists(subPath, false) == null) {
+ try {
List<ACL> acl = null;
- if ( aclProvider != null )
- {
+ if (aclProvider != null) {
acl = aclProvider.getAclForPath(subPath);
- if ( acl == null )
- {
+ if (acl == null) {
acl = aclProvider.getDefaultAcl();
}
}
- if ( acl == null )
- {
+ if (acl == null) {
acl = ZooDefs.Ids.OPEN_ACL_UNSAFE;
}
zookeeper.create(subPath, new byte[0], acl, getCreateMode(asContainers));
- }
- catch (KeeperException.NodeExistsException ignore)
- {
+ } catch (KeeperException.NodeExistsException ignore) {
// ignore... someone else has created it since we checked
}
}
- }
- while ( pos < path.length() );
+ } while (pos < path.length());
}
/**
@@ -369,39 +332,29 @@ public class ZKPaths
* @throws InterruptedException
* @throws KeeperException
*/
- public static void deleteChildren(ZooKeeper zookeeper, String path, boolean deleteSelf) throws InterruptedException, KeeperException
- {
+ public static void deleteChildren(ZooKeeper zookeeper, String path, boolean deleteSelf)
+ throws InterruptedException, KeeperException {
PathUtils.validatePath(path);
List<String> children;
- try
- {
+ try {
children = zookeeper.getChildren(path, null);
- }
- catch (KeeperException.NoNodeException e)
- {
+ } catch (KeeperException.NoNodeException e) {
// someone else has deleted the node since we checked
return;
}
- for ( String child : children )
- {
+ for (String child : children) {
String fullPath = makePath(path, child);
deleteChildren(zookeeper, fullPath, true);
}
- if ( deleteSelf )
- {
- try
- {
+ if (deleteSelf) {
+ try {
zookeeper.delete(path, -1);
- }
- catch ( KeeperException.NotEmptyException e )
- {
- //someone has created a new child since we checked ... delete again.
+ } catch (KeeperException.NotEmptyException e) {
+ // someone has created a new child since we checked ... delete again.
deleteChildren(zookeeper, path, true);
- }
- catch ( KeeperException.NoNodeException e )
- {
+ } catch (KeeperException.NoNodeException e) {
// ignore... someone else has deleted the node since we checked
}
}
@@ -416,8 +369,8 @@ public class ZKPaths
* @throws InterruptedException thread interruption
* @throws org.apache.zookeeper.KeeperException zookeeper errors
*/
- public static List<String> getSortedChildren(ZooKeeper zookeeper, String path) throws InterruptedException, KeeperException
- {
+ public static List<String> getSortedChildren(ZooKeeper zookeeper, String path)
+ throws InterruptedException, KeeperException {
List<String> children = zookeeper.getChildren(path, false);
List<String> sortedList = Lists.newArrayList(children);
Collections.sort(sortedList);
@@ -431,8 +384,7 @@ public class ZKPaths
* @param child the child
* @return full path
*/
- public static String makePath(String parent, String child)
- {
+ public static String makePath(String parent, String child) {
// 2 is the maximum number of additional path separators inserted
int maxPathLength = nullableStringLength(parent) + nullableStringLength(child) + 2;
// Avoid internal StringBuilder's buffer reallocation by specifying the max path length
@@ -451,14 +403,11 @@ public class ZKPaths
* @param restChildren the rest of the children in the path
* @return full path
*/
- public static String makePath(String parent, String firstChild, String... restChildren)
- {
+ public static String makePath(String parent, String firstChild, String... restChildren) {
// 2 is the maximum number of additional path separators inserted
int maxPathLength = nullableStringLength(parent) + nullableStringLength(firstChild) + 2;
- if ( restChildren != null )
- {
- for ( String child : restChildren )
- {
+ if (restChildren != null) {
+ for (String child : restChildren) {
// 1 is for possible additional separator
maxPathLength += nullableStringLength(child) + 1;
}
@@ -468,14 +417,10 @@ public class ZKPaths
joinPath(path, parent, firstChild);
- if ( restChildren == null )
- {
+ if (restChildren == null) {
return path.toString();
- }
- else
- {
- for ( String child : restChildren )
- {
+ } else {
+ for (String child : restChildren) {
joinPath(path, "", child);
}
@@ -483,8 +428,7 @@ public class ZKPaths
}
}
- private static int nullableStringLength(String s)
- {
+ private static int nullableStringLength(String s) {
return s != null ? s.length() : 0;
}
@@ -495,31 +439,24 @@ public class ZKPaths
* @param parent the parent
* @param child the child
*/
- private static void joinPath(StringBuilder path, String parent, String child)
- {
+ private static void joinPath(StringBuilder path, String parent, String child) {
// Add parent piece, with no trailing slash.
- if ( (parent != null) && (parent.length() > 0) )
- {
- if ( parent.charAt(0) != PATH_SEPARATOR_CHAR )
- {
+ if ((parent != null) && (parent.length() > 0)) {
+ if (parent.charAt(0) != PATH_SEPARATOR_CHAR) {
path.append(PATH_SEPARATOR_CHAR);
}
- if ( parent.charAt(parent.length() - 1) == PATH_SEPARATOR_CHAR )
- {
+ if (parent.charAt(parent.length() - 1) == PATH_SEPARATOR_CHAR) {
path.append(parent, 0, parent.length() - 1);
- }
- else
- {
+ } else {
path.append(parent);
}
}
- if ( (child == null) || (child.length() == 0) ||
- (child.length() == 1 && child.charAt(0) == PATH_SEPARATOR_CHAR) )
- {
+ if ((child == null)
+ || (child.length() == 0)
+ || (child.length() == 1 && child.charAt(0) == PATH_SEPARATOR_CHAR)) {
// Special case, empty parent and child
- if ( path.length() == 0 )
- {
+ if (path.length() == 0) {
path.append(PATH_SEPARATOR_CHAR);
}
return;
@@ -529,22 +466,16 @@ public class ZKPaths
path.append(PATH_SEPARATOR_CHAR);
int childAppendBeginIndex;
- if ( child.charAt(0) == PATH_SEPARATOR_CHAR )
- {
+ if (child.charAt(0) == PATH_SEPARATOR_CHAR) {
childAppendBeginIndex = 1;
- }
- else
- {
+ } else {
childAppendBeginIndex = 0;
}
int childAppendEndIndex;
- if ( child.charAt(child.length() - 1) == PATH_SEPARATOR_CHAR )
- {
+ if (child.charAt(child.length() - 1) == PATH_SEPARATOR_CHAR) {
childAppendEndIndex = child.length() - 1;
- }
- else
- {
+ } else {
childAppendEndIndex = child.length();
}
@@ -552,12 +483,9 @@ public class ZKPaths
path.append(child, childAppendBeginIndex, childAppendEndIndex);
}
- private ZKPaths()
- {
- }
+ private ZKPaths() {}
- private static CreateMode getCreateMode(boolean asContainers)
- {
+ private static CreateMode getCreateMode(boolean asContainers) {
return asContainers ? getContainerCreateMode() : CreateMode.PERSISTENT;
}
}
diff --git a/curator-client/src/main/java/org/apache/curator/utils/ZookeeperFactory.java b/curator-client/src/main/java/org/apache/curator/utils/ZookeeperFactory.java
index eaa80ebb..f15aaccb 100644
--- a/curator-client/src/main/java/org/apache/curator/utils/ZookeeperFactory.java
+++ b/curator-client/src/main/java/org/apache/curator/utils/ZookeeperFactory.java
@@ -24,8 +24,7 @@ import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.admin.ZooKeeperAdmin;
import org.apache.zookeeper.client.ZKClientConfig;
-public interface ZookeeperFactory
-{
+public interface ZookeeperFactory {
/**
* Allocate a new ZooKeeper instance
*
@@ -40,8 +39,9 @@ public interface ZookeeperFactory
* @return the instance
* @throws Exception errors
*/
- public ZooKeeper newZooKeeper(String connectString, int sessionTimeout, Watcher watcher, boolean canBeReadOnly) throws Exception;
-
+ public ZooKeeper newZooKeeper(String connectString, int sessionTimeout, Watcher watcher, boolean canBeReadOnly)
+ throws Exception;
+
/**
* Allocate a new ZooKeeper instance
*
@@ -57,10 +57,16 @@ public interface ZookeeperFactory
* @return the instance
* @throws Exception errors
*/
- public default ZooKeeper newZooKeeper(String connectString, int sessionTimeout, Watcher watcher, boolean canBeReadOnly, ZKClientConfig zkClientConfig) throws Exception {
- if (zkClientConfig == null) {
- return newZooKeeper(connectString, sessionTimeout, watcher, canBeReadOnly);
- }
- return new ZooKeeperAdmin(connectString, sessionTimeout, watcher, canBeReadOnly, zkClientConfig);
+ public default ZooKeeper newZooKeeper(
+ String connectString,
+ int sessionTimeout,
+ Watcher watcher,
+ boolean canBeReadOnly,
+ ZKClientConfig zkClientConfig)
+ throws Exception {
+ if (zkClientConfig == null) {
+ return newZooKeeper(connectString, sessionTimeout, watcher, canBeReadOnly);
+ }
+ return new ZooKeeperAdmin(connectString, sessionTimeout, watcher, canBeReadOnly, zkClientConfig);
}
}
diff --git a/curator-client/src/test/java/org/apache/curator/BasicTests.java b/curator-client/src/test/java/org/apache/curator/BasicTests.java
index a81dbcbe..58946934 100644
--- a/curator-client/src/test/java/org/apache/curator/BasicTests.java
+++ b/curator-client/src/test/java/org/apache/curator/BasicTests.java
@@ -25,6 +25,8 @@ import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.time.Duration;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.atomic.AtomicBoolean;
import org.apache.curator.ensemble.fixed.FixedEnsembleProvider;
import org.apache.curator.retry.RetryOneTime;
import org.apache.curator.test.BaseClassForTests;
@@ -39,84 +41,74 @@ import org.awaitility.Awaitility;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.atomic.AtomicBoolean;
-public class BasicTests extends BaseClassForTests
-{
+public class BasicTests extends BaseClassForTests {
@Test
- public void testFactory() throws Exception
- {
- final ZooKeeper mockZookeeper = Mockito.mock(ZooKeeper.class);
- ZookeeperFactory zookeeperFactory =
- (connectString, sessionTimeout, watcher, canBeReadOnly) -> mockZookeeper;
- CuratorZookeeperClient client = new CuratorZookeeperClient(zookeeperFactory, new FixedEnsembleProvider(server.getConnectString()), 10000, 10000, null, new RetryOneTime(1), false);
+ public void testFactory() throws Exception {
+ final ZooKeeper mockZookeeper = Mockito.mock(ZooKeeper.class);
+ ZookeeperFactory zookeeperFactory = (connectString, sessionTimeout, watcher, canBeReadOnly) -> mockZookeeper;
+ CuratorZookeeperClient client = new CuratorZookeeperClient(
+ zookeeperFactory,
+ new FixedEnsembleProvider(server.getConnectString()),
+ 10000,
+ 10000,
+ null,
+ new RetryOneTime(1),
+ false);
client.start();
assertEquals(client.getZooKeeper(), mockZookeeper);
}
@Test
- public void testExpiredSession() throws Exception
- {
+ public void testExpiredSession() throws Exception {
// see http://wiki.apache.org/hadoop/ZooKeeper/FAQ#A4
- final Timing timing = new Timing();
+ final Timing timing = new Timing();
- final CountDownLatch latch = new CountDownLatch(1);
- Watcher watcher = event -> {
- if ( event.getState() == Watcher.Event.KeeperState.Expired )
- {
+ final CountDownLatch latch = new CountDownLatch(1);
+ Watcher watcher = event -> {
+ if (event.getState() == Watcher.Event.KeeperState.Expired) {
latch.countDown();
}
};
- final CuratorZookeeperClient client = new CuratorZookeeperClient(server.getConnectString(), timing.session(), timing.connection(), watcher, new RetryOneTime(2));
+ final CuratorZookeeperClient client = new CuratorZookeeperClient(
+ server.getConnectString(), timing.session(), timing.connection(), watcher, new RetryOneTime(2));
client.start();
- try
- {
- final AtomicBoolean firstTime = new AtomicBoolean(true);
- RetryLoop.callWithRetry
- (
- client,
- () -> {
- if ( firstTime.compareAndSet(true, false) )
- {
- try
- {
- client.getZooKeeper().create("/foo", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
- }
- catch ( KeeperException.NodeExistsException ignore )
- {
- // ignore
- }
+ try {
+ final AtomicBoolean firstTime = new AtomicBoolean(true);
+ RetryLoop.callWithRetry(client, () -> {
+ if (firstTime.compareAndSet(true, false)) {
+ try {
+ client.getZooKeeper()
+ .create("/foo", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
+ } catch (KeeperException.NodeExistsException ignore) {
+ // ignore
+ }
- client.getZooKeeper().getTestable().injectSessionExpiration();
+ client.getZooKeeper().getTestable().injectSessionExpiration();
- assertTrue(timing.awaitLatch(latch));
- }
- ZooKeeper zooKeeper = client.getZooKeeper();
- client.blockUntilConnectedOrTimedOut();
- assertNotNull(zooKeeper.exists("/foo", false));
- return null;
- }
- );
- }
- finally
- {
+ assertTrue(timing.awaitLatch(latch));
+ }
+ ZooKeeper zooKeeper = client.getZooKeeper();
+ client.blockUntilConnectedOrTimedOut();
+ assertNotNull(zooKeeper.exists("/foo", false));
+ return null;
+ });
+ } finally {
client.close();
}
}
@Test
- public void testReconnect() throws Exception
- {
- CuratorZookeeperClient client = new CuratorZookeeperClient(server.getConnectString(), 10000, 10000, null, new RetryOneTime(1));
+ public void testReconnect() throws Exception {
+ CuratorZookeeperClient client =
+ new CuratorZookeeperClient(server.getConnectString(), 10000, 10000, null, new RetryOneTime(1));
client.start();
- try
- {
+ try {
client.blockUntilConnectedOrTimedOut();
- byte[] writtenData = {1, 2, 3};
+ byte[] writtenData = {1, 2, 3};
client.getZooKeeper().create("/test", writtenData, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
Thread.sleep(1000);
server.stop();
@@ -124,38 +116,33 @@ public class BasicTests extends BaseClassForTests
server.restart();
assertTrue(client.blockUntilConnectedOrTimedOut());
- byte[] readData = client.getZooKeeper().getData("/test", false, null);
+ byte[] readData = client.getZooKeeper().getData("/test", false, null);
assertArrayEquals(readData, writtenData);
- }
- finally
- {
+ } finally {
client.close();
}
}
@Test
- public void testSimple() throws Exception
- {
- CuratorZookeeperClient client = new CuratorZookeeperClient(server.getConnectString(), 10000, 10000, null, new RetryOneTime(1));
+ public void testSimple() throws Exception {
+ CuratorZookeeperClient client =
+ new CuratorZookeeperClient(server.getConnectString(), 10000, 10000, null, new RetryOneTime(1));
client.start();
- try
- {
+ try {
client.blockUntilConnectedOrTimedOut();
- String path = client.getZooKeeper().create("/test", new byte[]{1,2,3}, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
+ String path = client.getZooKeeper()
+ .create("/test", new byte[] {1, 2, 3}, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
assertEquals(path, "/test");
- }
- finally
- {
+ } finally {
client.close();
}
}
@Test
- public void testBackgroundConnect() throws Exception
- {
+ public void testBackgroundConnect() throws Exception {
final int CONNECTION_TIMEOUT_MS = 4000;
- try (CuratorZookeeperClient client = new CuratorZookeeperClient(server.getConnectString(), 10000,
- CONNECTION_TIMEOUT_MS, null, new RetryOneTime(1))) {
+ try (CuratorZookeeperClient client = new CuratorZookeeperClient(
+ server.getConnectString(), 10000, CONNECTION_TIMEOUT_MS, null, new RetryOneTime(1))) {
assertFalse(client.isConnected());
client.start();
Awaitility.await()
diff --git a/curator-client/src/test/java/org/apache/curator/TestEnsurePath.java b/curator-client/src/test/java/org/apache/curator/TestEnsurePath.java
index dffc7b63..11e7de7b 100644
--- a/curator-client/src/test/java/org/apache/curator/TestEnsurePath.java
+++ b/curator-client/src/test/java/org/apache/curator/TestEnsurePath.java
@@ -26,14 +26,12 @@ import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
-
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
-
import org.apache.curator.retry.RetryOneTime;
import org.apache.curator.utils.EnsurePath;
import org.apache.zookeeper.ZooKeeper;
@@ -43,23 +41,21 @@ import org.mockito.Mockito;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
-public class TestEnsurePath
-{
+public class TestEnsurePath {
@Test
- public void testBasic() throws Exception
- {
- ZooKeeper client = mock(ZooKeeper.class, Mockito.RETURNS_MOCKS);
- CuratorZookeeperClient curator = mock(CuratorZookeeperClient.class);
- RetryPolicy retryPolicy = new RetryOneTime(1);
- RetryLoop retryLoop = new RetryLoopImpl(retryPolicy, null);
+ public void testBasic() throws Exception {
+ ZooKeeper client = mock(ZooKeeper.class, Mockito.RETURNS_MOCKS);
+ CuratorZookeeperClient curator = mock(CuratorZookeeperClient.class);
+ RetryPolicy retryPolicy = new RetryOneTime(1);
+ RetryLoop retryLoop = new RetryLoopImpl(retryPolicy, null);
when(curator.getZooKeeper()).thenReturn(client);
when(curator.getRetryPolicy()).thenReturn(retryPolicy);
when(curator.newRetryLoop()).thenReturn(retryLoop);
- Stat fakeStat = mock(Stat.class);
+ Stat fakeStat = mock(Stat.class);
when(client.exists(Mockito.<String>any(), anyBoolean())).thenReturn(fakeStat);
-
- EnsurePath ensurePath = new EnsurePath("/one/two/three");
+
+ EnsurePath ensurePath = new EnsurePath("/one/two/three");
ensurePath.ensure(curator);
verify(client, times(3)).exists(Mockito.<String>any(), anyBoolean());
@@ -71,51 +67,39 @@ public class TestEnsurePath
}
@Test
- public void testSimultaneous() throws Exception
- {
- ZooKeeper client = mock(ZooKeeper.class, Mockito.RETURNS_MOCKS);
- RetryPolicy retryPolicy = new RetryOneTime(1);
- RetryLoop retryLoop = new RetryLoopImpl(retryPolicy, null);
- final CuratorZookeeperClient curator = mock(CuratorZookeeperClient.class);
+ public void testSimultaneous() throws Exception {
+ ZooKeeper client = mock(ZooKeeper.class, Mockito.RETURNS_MOCKS);
+ RetryPolicy retryPolicy = new RetryOneTime(1);
+ RetryLoop retryLoop = new RetryLoopImpl(retryPolicy, null);
+ final CuratorZookeeperClient curator = mock(CuratorZookeeperClient.class);
when(curator.getZooKeeper()).thenReturn(client);
when(curator.getRetryPolicy()).thenReturn(retryPolicy);
when(curator.newRetryLoop()).thenReturn(retryLoop);
- final Stat fakeStat = mock(Stat.class);
- final CountDownLatch startedLatch = new CountDownLatch(2);
- final CountDownLatch finishedLatch = new CountDownLatch(2);
- final Semaphore semaphore = new Semaphore(0);
- when(client.exists(Mockito.<String>any(), anyBoolean())).thenAnswer
- (
- new Answer<Stat>()
- {
- @Override
- public Stat answer(InvocationOnMock invocation) throws Throwable
- {
- semaphore.acquire();
- return fakeStat;
- }
+ final Stat fakeStat = mock(Stat.class);
+ final CountDownLatch startedLatch = new CountDownLatch(2);
+ final CountDownLatch finishedLatch = new CountDownLatch(2);
+ final Semaphore semaphore = new Semaphore(0);
+ when(client.exists(Mockito.<String>any(), anyBoolean())).thenAnswer(new Answer<Stat>() {
+ @Override
+ public Stat answer(InvocationOnMock invocation) throws Throwable {
+ semaphore.acquire();
+ return fakeStat;
}
- );
+ });
- final EnsurePath ensurePath = new EnsurePath("/one/two/three");
- ExecutorService service = Executors.newCachedThreadPool();
- for ( int i = 0; i < 2; ++i )
- {
- service.submit
- (
- new Callable<Void>()
- {
- @Override
- public Void call() throws Exception
- {
- startedLatch.countDown();
- ensurePath.ensure(curator);
- finishedLatch.countDown();
- return null;
- }
+ final EnsurePath ensurePath = new EnsurePath("/one/two/three");
+ ExecutorService service = Executors.newCachedThreadPool();
+ for (int i = 0; i < 2; ++i) {
+ service.submit(new Callable<Void>() {
+ @Override
+ public Void call() throws Exception {
+ startedLatch.countDown();
+ ensurePath.ensure(curator);
+ finishedLatch.countDown();
+ return null;
}
- );
+ });
}
assertTrue(startedLatch.await(10, TimeUnit.SECONDS));
diff --git a/curator-client/src/test/java/org/apache/curator/TestIs37.java b/curator-client/src/test/java/org/apache/curator/TestIs37.java
index 73020ede..87217875 100644
--- a/curator-client/src/test/java/org/apache/curator/TestIs37.java
+++ b/curator-client/src/test/java/org/apache/curator/TestIs37.java
@@ -19,15 +19,13 @@
package org.apache.curator;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
import org.apache.curator.test.compatibility.CuratorTestBase;
-import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.proto.WhoAmIResponse;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
-import static org.junit.jupiter.api.Assertions.assertNotNull;
-public class TestIs37 extends CuratorTestBase
-{
+public class TestIs37 extends CuratorTestBase {
/**
* Ensure that ZooKeeper is 3.7 or above.
*
@@ -42,8 +40,7 @@ public class TestIs37 extends CuratorTestBase
}
@Override
- protected void createServer()
- {
+ protected void createServer() {
// NOP
}
}
diff --git a/curator-client/src/test/java/org/apache/curator/TestRetryLoop.java b/curator-client/src/test/java/org/apache/curator/TestRetryLoop.java
index 69ebbae0..ff2491b4 100644
--- a/curator-client/src/test/java/org/apache/curator/TestRetryLoop.java
+++ b/curator-client/src/test/java/org/apache/curator/TestRetryLoop.java
@@ -23,6 +23,8 @@ import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
+import static org.mockito.Mockito.times;
+import java.util.concurrent.TimeUnit;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.curator.retry.RetryForever;
import org.apache.curator.retry.RetryOneTime;
@@ -34,135 +36,107 @@ import org.apache.zookeeper.ZooDefs;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
-import java.util.concurrent.TimeUnit;
-
-import static org.mockito.Mockito.times;
-
-public class TestRetryLoop extends BaseClassForTests
-{
+public class TestRetryLoop extends BaseClassForTests {
@Test
- public void testExponentialBackoffRetryLimit()
- {
- RetrySleeper sleeper = new RetrySleeper()
- {
+ public void testExponentialBackoffRetryLimit() {
+ RetrySleeper sleeper = new RetrySleeper() {
@Override
- public void sleepFor(long time, TimeUnit unit) throws InterruptedException
- {
+ public void sleepFor(long time, TimeUnit unit) throws InterruptedException {
assertTrue(unit.toMillis(time) <= 100);
}
};
- ExponentialBackoffRetry retry = new ExponentialBackoffRetry(1, Integer.MAX_VALUE, 100);
- for ( int i = 0; i >= 0; ++i )
- {
+ ExponentialBackoffRetry retry = new ExponentialBackoffRetry(1, Integer.MAX_VALUE, 100);
+ for (int i = 0; i >= 0; ++i) {
retry.allowRetry(i, 0, sleeper);
}
}
@Test
- public void testRetryLoopWithFailure() throws Exception
- {
- CuratorZookeeperClient client = new CuratorZookeeperClient(server.getConnectString(), 5000, 5000, null, new RetryOneTime(1));
+ public void testRetryLoopWithFailure() throws Exception {
+ CuratorZookeeperClient client =
+ new CuratorZookeeperClient(server.getConnectString(), 5000, 5000, null, new RetryOneTime(1));
client.start();
- try
- {
- int loopCount = 0;
- RetryLoop retryLoop = client.newRetryLoop();
- outer: while ( retryLoop.shouldContinue() )
- {
+ try {
+ int loopCount = 0;
+ RetryLoop retryLoop = client.newRetryLoop();
+ outer:
+ while (retryLoop.shouldContinue()) {
++loopCount;
- switch ( loopCount )
- {
- case 1:
- {
+ switch (loopCount) {
+ case 1: {
server.stop();
break;
}
- case 2:
- {
+ case 2: {
server.restart();
break;
}
case 3:
- case 4:
- {
+ case 4: {
// ignore
break;
}
- default:
- {
+ default: {
fail();
break outer;
}
}
- try
- {
+ try {
client.blockUntilConnectedOrTimedOut();
- client.getZooKeeper().create("/test", new byte[]{1,2,3}, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
+ client.getZooKeeper()
+ .create("/test", new byte[] {1, 2, 3}, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
retryLoop.markComplete();
- }
- catch ( Exception e )
- {
+ } catch (Exception e) {
retryLoop.takeException(e);
}
}
assertThat(loopCount).isGreaterThanOrEqualTo(2);
- }
- finally
- {
+ } finally {
client.close();
}
}
@Test
- public void testRetryLoop() throws Exception
- {
- CuratorZookeeperClient client = new CuratorZookeeperClient(server.getConnectString(), 10000, 10000, null, new RetryOneTime(1));
+ public void testRetryLoop() throws Exception {
+ CuratorZookeeperClient client =
+ new CuratorZookeeperClient(server.getConnectString(), 10000, 10000, null, new RetryOneTime(1));
client.start();
- try
- {
- int loopCount = 0;
- RetryLoop retryLoop = client.newRetryLoop();
- while ( retryLoop.shouldContinue() )
- {
- if ( ++loopCount > 2 )
- {
+ try {
+ int loopCount = 0;
+ RetryLoop retryLoop = client.newRetryLoop();
+ while (retryLoop.shouldContinue()) {
+ if (++loopCount > 2) {
fail();
break;
}
- try
- {
- client.getZooKeeper().create("/test", new byte[]{1,2,3}, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
+ try {
+ client.getZooKeeper()
+ .create("/test", new byte[] {1, 2, 3}, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
retryLoop.markComplete();
- }
- catch ( Exception e )
- {
+ } catch (Exception e) {
retryLoop.takeException(e);
}
}
assertTrue(loopCount > 0);
- }
- finally
- {
+ } finally {
client.close();
}
}
@Test
- public void testRetryForever() throws Exception
- {
+ public void testRetryForever() throws Exception {
int retryIntervalMs = 1;
RetrySleeper sleeper = Mockito.mock(RetrySleeper.class);
RetryForever retryForever = new RetryForever(retryIntervalMs);
- for (int i = 0; i < 10; i++)
- {
+ for (int i = 0; i < 10; i++) {
boolean allowed = retryForever.allowRetry(i, 0, sleeper);
assertTrue(allowed);
Mockito.verify(sleeper, times(i + 1)).sleepFor(retryIntervalMs, TimeUnit.MILLISECONDS);
@@ -170,52 +144,40 @@ public class TestRetryLoop extends BaseClassForTests
}
@Test
- public void testRetryForeverWithSessionFailed() throws Exception
- {
+ public void testRetryForeverWithSessionFailed() throws Exception {
final Timing timing = new Timing();
final RetryPolicy retryPolicy = new SessionFailedRetryPolicy(new RetryForever(1000));
- final CuratorZookeeperClient client = new CuratorZookeeperClient(server.getConnectString(), timing.session(), timing.connection(), null, retryPolicy);
+ final CuratorZookeeperClient client = new CuratorZookeeperClient(
+ server.getConnectString(), timing.session(), timing.connection(), null, retryPolicy);
client.start();
- try
- {
+ try {
int loopCount = 0;
final RetryLoop retryLoop = client.newRetryLoop();
- while ( retryLoop.shouldContinue() )
- {
- if ( ++loopCount > 1 )
- {
+ while (retryLoop.shouldContinue()) {
+ if (++loopCount > 1) {
break;
}
- try
- {
+ try {
client.getZooKeeper().getTestable().injectSessionExpiration();
- client.getZooKeeper().create("/test", new byte[]{1,2,3}, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
+ client.getZooKeeper()
+ .create("/test", new byte[] {1, 2, 3}, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
retryLoop.markComplete();
- }
- catch ( Exception e )
- {
+ } catch (Exception e) {
retryLoop.takeException(e);
}
}
fail("Should failed with SessionExpiredException.");
- }
- catch ( Exception e )
- {
- if ( e instanceof KeeperException )
- {
+ } catch (Exception e) {
+ if (e instanceof KeeperException) {
int rc = ((KeeperException) e).code().intValue();
assertEquals(rc, KeeperException.Code.SESSIONEXPIRED.intValue());
- }
- else
- {
+ } else {
throw e;
}
- }
- finally
- {
+ } finally {
client.close();
}
}
diff --git a/curator-client/src/test/java/org/apache/curator/TestSessionFailRetryLoop.java b/curator-client/src/test/java/org/apache/curator/TestSessionFailRetryLoop.java
index 7459c1e7..0b509e84 100644
--- a/curator-client/src/test/java/org/apache/curator/TestSessionFailRetryLoop.java
+++ b/curator-client/src/test/java/org/apache/curator/TestSessionFailRetryLoop.java
@@ -23,266 +23,202 @@ import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
+import java.util.concurrent.Callable;
+import java.util.concurrent.atomic.AtomicBoolean;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.curator.test.BaseClassForTests;
-import org.apache.curator.utils.CloseableUtils;
import org.apache.curator.test.Timing;
+import org.apache.curator.utils.CloseableUtils;
import org.junit.jupiter.api.Test;
-import java.util.concurrent.Callable;
-import java.util.concurrent.atomic.AtomicBoolean;
-
-public class TestSessionFailRetryLoop extends BaseClassForTests
-{
+public class TestSessionFailRetryLoop extends BaseClassForTests {
@Test
- public void testRetry() throws Exception
- {
- Timing timing = new Timing();
- final CuratorZookeeperClient client = new CuratorZookeeperClient(server.getConnectString(), timing.session(), timing.connection(), null, new ExponentialBackoffRetry(100, 3));
- SessionFailRetryLoop retryLoop = client.newSessionFailRetryLoop(SessionFailRetryLoop.Mode.RETRY);
+ public void testRetry() throws Exception {
+ Timing timing = new Timing();
+ final CuratorZookeeperClient client = new CuratorZookeeperClient(
+ server.getConnectString(),
+ timing.session(),
+ timing.connection(),
+ null,
+ new ExponentialBackoffRetry(100, 3));
+ SessionFailRetryLoop retryLoop = client.newSessionFailRetryLoop(SessionFailRetryLoop.Mode.RETRY);
retryLoop.start();
- try
- {
+ try {
client.start();
- final AtomicBoolean secondWasDone = new AtomicBoolean(false);
- final AtomicBoolean firstTime = new AtomicBoolean(true);
- while ( retryLoop.shouldContinue() )
- {
- try
- {
- RetryLoop.callWithRetry
- (
- client,
- new Callable<Void>()
- {
- @Override
- public Void call() throws Exception
- {
- if ( firstTime.compareAndSet(true, false) )
- {
- assertNull(client.getZooKeeper().exists("/foo/bar", false));
- client.getZooKeeper().getTestable().injectSessionExpiration();
- client.getZooKeeper();
- client.blockUntilConnectedOrTimedOut();
- }
-
+ final AtomicBoolean secondWasDone = new AtomicBoolean(false);
+ final AtomicBoolean firstTime = new AtomicBoolean(true);
+ while (retryLoop.shouldContinue()) {
+ try {
+ RetryLoop.callWithRetry(client, new Callable<Void>() {
+ @Override
+ public Void call() throws Exception {
+ if (firstTime.compareAndSet(true, false)) {
assertNull(client.getZooKeeper().exists("/foo/bar", false));
- return null;
+ client.getZooKeeper().getTestable().injectSessionExpiration();
+ client.getZooKeeper();
+ client.blockUntilConnectedOrTimedOut();
}
+
+ assertNull(client.getZooKeeper().exists("/foo/bar", false));
+ return null;
}
- );
+ });
- RetryLoop.callWithRetry
- (
- client,
- new Callable<Void>()
- {
- @Override
- public Void call() throws Exception
- {
- assertFalse(firstTime.get());
- assertNull(client.getZooKeeper().exists("/foo/bar", false));
- secondWasDone.set(true);
- return null;
- }
+ RetryLoop.callWithRetry(client, new Callable<Void>() {
+ @Override
+ public Void call() throws Exception {
+ assertFalse(firstTime.get());
+ assertNull(client.getZooKeeper().exists("/foo/bar", false));
+ secondWasDone.set(true);
+ return null;
}
- );
- }
- catch ( Exception e )
- {
+ });
+ } catch (Exception e) {
retryLoop.takeException(e);
}
}
assertTrue(secondWasDone.get());
- }
- finally
- {
+ } finally {
retryLoop.close();
CloseableUtils.closeQuietly(client);
}
}
@Test
- public void testRetryStatic() throws Exception
- {
- Timing timing = new Timing();
- final CuratorZookeeperClient client = new CuratorZookeeperClient(server.getConnectString(), timing.session(), timing.connection(), null, new ExponentialBackoffRetry(100, 3));
- SessionFailRetryLoop retryLoop = client.newSessionFailRetryLoop(SessionFailRetryLoop.Mode.RETRY);
+ public void testRetryStatic() throws Exception {
+ Timing timing = new Timing();
+ final CuratorZookeeperClient client = new CuratorZookeeperClient(
+ server.getConnectString(),
+ timing.session(),
+ timing.connection(),
+ null,
+ new ExponentialBackoffRetry(100, 3));
+ SessionFailRetryLoop retryLoop = client.newSessionFailRetryLoop(SessionFailRetryLoop.Mode.RETRY);
retryLoop.start();
- try
- {
+ try {
client.start();
- final AtomicBoolean secondWasDone = new AtomicBoolean(false);
- final AtomicBoolean firstTime = new AtomicBoolean(true);
- SessionFailRetryLoop.callWithRetry
- (
- client,
- SessionFailRetryLoop.Mode.RETRY,
- new Callable<Object>()
- {
- @Override
- public Object call() throws Exception
- {
- RetryLoop.callWithRetry
- (
- client,
- new Callable<Void>()
- {
- @Override
- public Void call() throws Exception
- {
- if ( firstTime.compareAndSet(true, false) )
- {
- assertNull(client.getZooKeeper().exists("/foo/bar", false));
- client.getZooKeeper().getTestable().injectSessionExpiration();
- client.getZooKeeper();
- client.blockUntilConnectedOrTimedOut();
- }
-
- assertNull(client.getZooKeeper().exists("/foo/bar", false));
- return null;
- }
+ final AtomicBoolean secondWasDone = new AtomicBoolean(false);
+ final AtomicBoolean firstTime = new AtomicBoolean(true);
+ SessionFailRetryLoop.callWithRetry(client, SessionFailRetryLoop.Mode.RETRY, new Callable<Object>() {
+ @Override
+ public Object call() throws Exception {
+ RetryLoop.callWithRetry(client, new Callable<Void>() {
+ @Override
+ public Void call() throws Exception {
+ if (firstTime.compareAndSet(true, false)) {
+ assertNull(client.getZooKeeper().exists("/foo/bar", false));
+ client.getZooKeeper().getTestable().injectSessionExpiration();
+ client.getZooKeeper();
+ client.blockUntilConnectedOrTimedOut();
}
- );
- RetryLoop.callWithRetry
- (
- client,
- new Callable<Void>()
- {
- @Override
- public Void call() throws Exception
- {
- assertFalse(firstTime.get());
- assertNull(client.getZooKeeper().exists("/foo/bar", false));
- secondWasDone.set(true);
- return null;
- }
- }
- );
- return null;
- }
+ assertNull(client.getZooKeeper().exists("/foo/bar", false));
+ return null;
+ }
+ });
+
+ RetryLoop.callWithRetry(client, new Callable<Void>() {
+ @Override
+ public Void call() throws Exception {
+ assertFalse(firstTime.get());
+ assertNull(client.getZooKeeper().exists("/foo/bar", false));
+ secondWasDone.set(true);
+ return null;
+ }
+ });
+ return null;
}
- );
+ });
assertTrue(secondWasDone.get());
- }
- finally
- {
+ } finally {
retryLoop.close();
CloseableUtils.closeQuietly(client);
}
}
@Test
- public void testBasic() throws Exception
- {
- final Timing timing = new Timing();
- final CuratorZookeeperClient client = new CuratorZookeeperClient(server.getConnectString(), timing.session(), timing.connection(), null, new ExponentialBackoffRetry(100, 3));
- SessionFailRetryLoop retryLoop = client.newSessionFailRetryLoop(SessionFailRetryLoop.Mode.FAIL);
+ public void testBasic() throws Exception {
+ final Timing timing = new Timing();
+ final CuratorZookeeperClient client = new CuratorZookeeperClient(
+ server.getConnectString(),
+ timing.session(),
+ timing.connection(),
+ null,
+ new ExponentialBackoffRetry(100, 3));
+ SessionFailRetryLoop retryLoop = client.newSessionFailRetryLoop(SessionFailRetryLoop.Mode.FAIL);
retryLoop.start();
- try
- {
+ try {
client.start();
- try
- {
- while ( retryLoop.shouldContinue() )
- {
- try
- {
- RetryLoop.callWithRetry
- (
- client,
- new Callable<Void>()
- {
- @Override
- public Void call() throws Exception
- {
- assertNull(client.getZooKeeper().exists("/foo/bar", false));
- client.getZooKeeper().getTestable().injectSessionExpiration();
+ try {
+ while (retryLoop.shouldContinue()) {
+ try {
+ RetryLoop.callWithRetry(client, new Callable<Void>() {
+ @Override
+ public Void call() throws Exception {
+ assertNull(client.getZooKeeper().exists("/foo/bar", false));
+ client.getZooKeeper().getTestable().injectSessionExpiration();
- timing.sleepABit();
+ timing.sleepABit();
- client.getZooKeeper();
- client.blockUntilConnectedOrTimedOut();
- assertNull(client.getZooKeeper().exists("/foo/bar", false));
- return null;
- }
+ client.getZooKeeper();
+ client.blockUntilConnectedOrTimedOut();
+ assertNull(client.getZooKeeper().exists("/foo/bar", false));
+ return null;
}
- );
- }
- catch ( Exception e )
- {
+ });
+ } catch (Exception e) {
retryLoop.takeException(e);
}
}
fail();
- }
- catch ( SessionFailRetryLoop.SessionFailedException dummy )
- {
+ } catch (SessionFailRetryLoop.SessionFailedException dummy) {
// correct
}
- }
- finally
- {
+ } finally {
retryLoop.close();
CloseableUtils.closeQuietly(client);
}
}
@Test
- public void testBasicStatic() throws Exception
- {
- Timing timing = new Timing();
- final CuratorZookeeperClient client = new CuratorZookeeperClient(server.getConnectString(), timing.session(), timing.connection(), null, new ExponentialBackoffRetry(100, 3));
- SessionFailRetryLoop retryLoop = client.newSessionFailRetryLoop(SessionFailRetryLoop.Mode.FAIL);
+ public void testBasicStatic() throws Exception {
+ Timing timing = new Timing();
+ final CuratorZookeeperClient client = new CuratorZookeeperClient(
+ server.getConnectString(),
+ timing.session(),
+ timing.connection(),
+ null,
+ new ExponentialBackoffRetry(100, 3));
+ SessionFailRetryLoop retryLoop = client.newSessionFailRetryLoop(SessionFailRetryLoop.Mode.FAIL);
retryLoop.start();
- try
- {
+ try {
client.start();
- try
- {
- SessionFailRetryLoop.callWithRetry
- (
- client,
- SessionFailRetryLoop.Mode.FAIL,
- new Callable<Object>()
- {
- @Override
- public Object call() throws Exception
- {
- RetryLoop.callWithRetry
- (
- client,
- new Callable<Void>()
- {
- @Override
- public Void call() throws Exception
- {
- assertNull(client.getZooKeeper().exists("/foo/bar", false));
- client.getZooKeeper().getTestable().injectSessionExpiration();
+ try {
+ SessionFailRetryLoop.callWithRetry(client, SessionFailRetryLoop.Mode.FAIL, new Callable<Object>() {
+ @Override
+ public Object call() throws Exception {
+ RetryLoop.callWithRetry(client, new Callable<Void>() {
+ @Override
+ public Void call() throws Exception {
+ assertNull(client.getZooKeeper().exists("/foo/bar", false));
+ client.getZooKeeper().getTestable().injectSessionExpiration();
- client.getZooKeeper();
- client.blockUntilConnectedOrTimedOut();
- assertNull(client.getZooKeeper().exists("/foo/bar", false));
- return null;
- }
- }
- );
- return null;
- }
+ client.getZooKeeper();
+ client.blockUntilConnectedOrTimedOut();
+ assertNull(client.getZooKeeper().exists("/foo/bar", false));
+ return null;
+ }
+ });
+ return null;
}
- );
- }
- catch ( SessionFailRetryLoop.SessionFailedException dummy )
- {
+ });
+ } catch (SessionFailRetryLoop.SessionFailedException dummy) {
// correct
}
- }
- finally
- {
+ } finally {
retryLoop.close();
CloseableUtils.closeQuietly(client);
}
diff --git a/curator-client/src/test/java/org/apache/curator/utils/TestCloseableExecutorService.java b/curator-client/src/test/java/org/apache/curator/utils/TestCloseableExecutorService.java
index 1a3fa72f..8760607e 100644
--- a/curator-client/src/test/java/org/apache/curator/utils/TestCloseableExecutorService.java
+++ b/curator-client/src/test/java/org/apache/curator/utils/TestCloseableExecutorService.java
@@ -22,11 +22,6 @@ package org.apache.curator.utils;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import com.google.common.collect.Lists;
-import org.awaitility.Awaitility;
-import org.junit.jupiter.api.AfterEach;
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
@@ -34,79 +29,63 @@ import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
+import org.awaitility.Awaitility;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
-public class TestCloseableExecutorService
-{
+public class TestCloseableExecutorService {
private static final int QTY = 10;
private volatile ExecutorService executorService;
@BeforeEach
- public void setup()
- {
+ public void setup() {
executorService = Executors.newFixedThreadPool(QTY * 2);
}
@AfterEach
- public void tearDown()
- {
+ public void tearDown() {
executorService.shutdownNow();
}
@Test
- public void testBasicRunnable() throws InterruptedException
- {
- try
- {
+ public void testBasicRunnable() throws InterruptedException {
+ try {
CloseableExecutorService service = new CloseableExecutorService(executorService);
CountDownLatch startLatch = new CountDownLatch(QTY);
CountDownLatch latch = new CountDownLatch(QTY);
- for ( int i = 0; i < QTY; ++i )
- {
+ for (int i = 0; i < QTY; ++i) {
submitRunnable(service, startLatch, latch);
}
assertTrue(startLatch.await(3, TimeUnit.SECONDS));
service.close();
assertTrue(latch.await(3, TimeUnit.SECONDS));
- }
- catch ( AssertionError e )
- {
+ } catch (AssertionError e) {
throw e;
- }
- catch ( Throwable e )
- {
+ } catch (Throwable e) {
e.printStackTrace();
}
}
@Test
- public void testBasicCallable() throws InterruptedException
- {
+ public void testBasicCallable() throws InterruptedException {
CloseableExecutorService service = new CloseableExecutorService(executorService);
final CountDownLatch startLatch = new CountDownLatch(QTY);
final CountDownLatch latch = new CountDownLatch(QTY);
- for ( int i = 0; i < QTY; ++i )
- {
- service.submit
- (
- (Callable<Void>) () -> {
- try
- {
- startLatch.countDown();
- Thread.currentThread().join();
- }
- catch ( InterruptedException e )
- {
- Thread.currentThread().interrupt();
- }
- finally
- {
- latch.countDown();
- }
- return null;
- }
- );
+ for (int i = 0; i < QTY; ++i) {
+ service.submit((Callable<Void>) () -> {
+ try {
+ startLatch.countDown();
+ Thread.currentThread().join();
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ } finally {
+ latch.countDown();
+ }
+ return null;
+ });
}
assertTrue(startLatch.await(3, TimeUnit.SECONDS));
@@ -115,34 +94,25 @@ public class TestCloseableExecutorService
}
@Test
- public void testListeningRunnable() throws InterruptedException
- {
+ public void testListeningRunnable() throws InterruptedException {
CloseableExecutorService service = new CloseableExecutorService(executorService);
List<Future<?>> futures = Lists.newArrayList();
final CountDownLatch startLatch = new CountDownLatch(QTY);
- for ( int i = 0; i < QTY; ++i )
- {
- Future<?> future = service.submit
- (
- () -> {
- try
- {
- startLatch.countDown();
- Thread.currentThread().join();
- }
- catch ( InterruptedException e )
- {
- Thread.currentThread().interrupt();
- }
- }
- );
+ for (int i = 0; i < QTY; ++i) {
+ Future<?> future = service.submit(() -> {
+ try {
+ startLatch.countDown();
+ Thread.currentThread().join();
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ }
+ });
futures.add(future);
}
assertTrue(startLatch.await(3, TimeUnit.SECONDS));
- for ( Future<?> future : futures )
- {
+ for (Future<?> future : futures) {
future.cancel(true);
}
@@ -150,34 +120,25 @@ public class TestCloseableExecutorService
}
@Test
- public void testListeningCallable() throws InterruptedException
- {
+ public void testListeningCallable() throws InterruptedException {
CloseableExecutorService service = new CloseableExecutorService(executorService);
final CountDownLatch startLatch = new CountDownLatch(QTY);
List<Future<?>> futures = Lists.newArrayList();
- for ( int i = 0; i < QTY; ++i )
- {
- Future<?> future = service.submit
- (
- (Callable<Void>) () -> {
- try
- {
- startLatch.countDown();
- Thread.currentThread().join();
- }
- catch ( InterruptedException e )
- {
- Thread.currentThread().interrupt();
- }
- return null;
- }
- );
+ for (int i = 0; i < QTY; ++i) {
+ Future<?> future = service.submit((Callable<Void>) () -> {
+ try {
+ startLatch.countDown();
+ Thread.currentThread().join();
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ }
+ return null;
+ });
futures.add(future);
}
assertTrue(startLatch.await(3, TimeUnit.SECONDS));
- for ( Future<?> future : futures )
- {
+ for (Future<?> future : futures) {
future.cancel(true);
}
@@ -185,36 +146,26 @@ public class TestCloseableExecutorService
}
@Test
- public void testPartialRunnable() throws InterruptedException
- {
+ public void testPartialRunnable() throws InterruptedException {
final CountDownLatch outsideLatch = new CountDownLatch(1);
- executorService.submit
- (
- () -> {
- try
- {
- Thread.currentThread().join();
- }
- catch ( InterruptedException e )
- {
- Thread.currentThread().interrupt();
- }
- finally
- {
- outsideLatch.countDown();
- }
- }
- );
+ executorService.submit(() -> {
+ try {
+ Thread.currentThread().join();
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ } finally {
+ outsideLatch.countDown();
+ }
+ });
CloseableExecutorService service = new CloseableExecutorService(executorService);
CountDownLatch startLatch = new CountDownLatch(QTY);
CountDownLatch latch = new CountDownLatch(QTY);
- for ( int i = 0; i < QTY; ++i )
- {
+ for (int i = 0; i < QTY; ++i) {
submitRunnable(service, startLatch, latch);
}
- Awaitility.await().until(()-> service.size() >= QTY);
+ Awaitility.await().until(() -> service.size() >= QTY);
assertTrue(startLatch.await(3, TimeUnit.SECONDS));
service.close();
@@ -222,25 +173,17 @@ public class TestCloseableExecutorService
assertEquals(outsideLatch.getCount(), 1);
}
- private void submitRunnable(CloseableExecutorService service, final CountDownLatch startLatch, final CountDownLatch latch)
- {
- service.submit
- (
- () -> {
- try
- {
- startLatch.countDown();
- Thread.sleep(100000);
- }
- catch ( InterruptedException e )
- {
- Thread.currentThread().interrupt();
- }
- finally
- {
- latch.countDown();
- }
- }
- );
+ private void submitRunnable(
+ CloseableExecutorService service, final CountDownLatch startLatch, final CountDownLatch latch) {
+ service.submit(() -> {
+ try {
+ startLatch.countDown();
+ Thread.sleep(100000);
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ } finally {
+ latch.countDown();
+ }
+ });
}
}
diff --git a/curator-client/src/test/java/org/apache/curator/utils/TestCloseableScheduledExecutorService.java b/curator-client/src/test/java/org/apache/curator/utils/TestCloseableScheduledExecutorService.java
index e854a9f0..42ad7a6b 100644
--- a/curator-client/src/test/java/org/apache/curator/utils/TestCloseableScheduledExecutorService.java
+++ b/curator-client/src/test/java/org/apache/curator/utils/TestCloseableScheduledExecutorService.java
@@ -21,67 +21,56 @@ package org.apache.curator.utils;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
-import org.junit.jupiter.api.AfterEach;
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
-public class TestCloseableScheduledExecutorService
-{
+public class TestCloseableScheduledExecutorService {
private static final int QTY = 10;
private static final int DELAY_MS = 100;
private volatile ScheduledExecutorService executorService;
@BeforeEach
- public void setup()
- {
+ public void setup() {
executorService = Executors.newScheduledThreadPool(QTY * 2);
}
@AfterEach
- public void tearDown()
- {
+ public void tearDown() {
executorService.shutdownNow();
}
@Test
- public void testCloseableScheduleWithFixedDelay() throws InterruptedException
- {
+ public void testCloseableScheduleWithFixedDelay() throws InterruptedException {
CloseableScheduledExecutorService service = new CloseableScheduledExecutorService(executorService);
final CountDownLatch latch = new CountDownLatch(QTY);
service.scheduleWithFixedDelay(
- new Runnable()
- {
+ new Runnable() {
@Override
- public void run()
- {
+ public void run() {
latch.countDown();
}
},
DELAY_MS,
DELAY_MS,
- TimeUnit.MILLISECONDS
- );
+ TimeUnit.MILLISECONDS);
assertTrue(latch.await((QTY * 2) * DELAY_MS, TimeUnit.MILLISECONDS));
}
@Test
- public void testCloseableScheduleWithFixedDelayAndAdditionalTasks() throws InterruptedException
- {
+ public void testCloseableScheduleWithFixedDelayAndAdditionalTasks() throws InterruptedException {
final AtomicInteger outerCounter = new AtomicInteger(0);
- Runnable command = new Runnable()
- {
+ Runnable command = new Runnable() {
@Override
- public void run()
- {
+ public void run() {
outerCounter.incrementAndGet();
}
};
@@ -90,14 +79,16 @@ public class TestCloseableScheduledExecutorService
CloseableScheduledExecutorService service = new CloseableScheduledExecutorService(executorService);
final AtomicInteger innerCounter = new AtomicInteger(0);
- service.scheduleWithFixedDelay(new Runnable()
- {
- @Override
- public void run()
- {
- innerCounter.incrementAndGet();
- }
- }, DELAY_MS, DELAY_MS, TimeUnit.MILLISECONDS);
+ service.scheduleWithFixedDelay(
+ new Runnable() {
+ @Override
+ public void run() {
+ innerCounter.incrementAndGet();
+ }
+ },
+ DELAY_MS,
+ DELAY_MS,
+ TimeUnit.MILLISECONDS);
Thread.sleep(DELAY_MS * 4);
diff --git a/curator-client/src/test/java/org/apache/curator/utils/TestZKPaths.java b/curator-client/src/test/java/org/apache/curator/utils/TestZKPaths.java
index 05f46a88..2b20d882 100644
--- a/curator-client/src/test/java/org/apache/curator/utils/TestZKPaths.java
+++ b/curator-client/src/test/java/org/apache/curator/utils/TestZKPaths.java
@@ -20,16 +20,14 @@
package org.apache.curator.utils;
import static org.junit.jupiter.api.Assertions.assertEquals;
-import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.Collections;
+import org.junit.jupiter.api.Test;
-public class TestZKPaths
-{
+public class TestZKPaths {
@SuppressWarnings("NullArgumentToVariableArgMethod")
@Test
- public void testMakePath()
- {
+ public void testMakePath() {
assertEquals(ZKPaths.makePath(null, "/"), "/");
assertEquals(ZKPaths.makePath("", null), "/");
assertEquals(ZKPaths.makePath("/", null), "/");
@@ -77,8 +75,7 @@ public class TestZKPaths
}
@Test
- public void testSplit()
- {
+ public void testSplit() {
assertEquals(ZKPaths.split("/"), Collections.emptyList());
assertEquals(ZKPaths.split("/test"), Collections.singletonList("test"));
assertEquals(ZKPaths.split("/test/one"), Arrays.asList("test", "one"));
diff --git a/curator-examples/src/main/java/async/AsyncExamples.java b/curator-examples/src/main/java/async/AsyncExamples.java
index 4b67a8c4..89dc844e 100644
--- a/curator-examples/src/main/java/async/AsyncExamples.java
+++ b/curator-examples/src/main/java/async/AsyncExamples.java
@@ -19,46 +19,41 @@
package async;
+import java.util.concurrent.CompletionStage;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.x.async.AsyncCuratorFramework;
import org.apache.curator.x.async.AsyncEventException;
import org.apache.curator.x.async.WatchMode;
import org.apache.zookeeper.WatchedEvent;
-import java.util.concurrent.CompletionStage;
/**
* Examples using the asynchronous DSL
*/
-public class AsyncExamples
-{
- public static AsyncCuratorFramework wrap(CuratorFramework client)
- {
+public class AsyncExamples {
+ public static AsyncCuratorFramework wrap(CuratorFramework client) {
// wrap a CuratorFramework instance so that it can be used async.
// do this once and re-use the returned AsyncCuratorFramework instance
return AsyncCuratorFramework.wrap(client);
}
- public static void create(CuratorFramework client, String path, byte[] payload)
- {
- AsyncCuratorFramework async = AsyncCuratorFramework.wrap(client); // normally you'd wrap early in your app and reuse the instance
+ public static void create(CuratorFramework client, String path, byte[] payload) {
+ AsyncCuratorFramework async =
+ AsyncCuratorFramework.wrap(client); // normally you'd wrap early in your app and reuse the instance
// create a node at the given path with the given payload asynchronously
async.create().forPath(path, payload).whenComplete((name, exception) -> {
- if ( exception != null )
- {
+ if (exception != null) {
// there was a problem
exception.printStackTrace();
- }
- else
- {
+ } else {
System.out.println("Created node name is: " + name);
}
});
}
- public static void createThenWatch(CuratorFramework client, String path)
- {
- AsyncCuratorFramework async = AsyncCuratorFramework.wrap(client); // normally you'd wrap early in your app and reuse the instance
+ public static void createThenWatch(CuratorFramework client, String path) {
+ AsyncCuratorFramework async =
+ AsyncCuratorFramework.wrap(client); // normally you'd wrap early in your app and reuse the instance
// this example shows to asynchronously use watchers for both event
// triggering and connection problems. If you don't need to be notified
@@ -67,44 +62,42 @@ public class AsyncExamples
// create a node at the given path with the given payload asynchronously
// then watch the created node
async.create().forPath(path).whenComplete((name, exception) -> {
- if ( exception != null )
- {
+ if (exception != null) {
// there was a problem creating the node
exception.printStackTrace();
- }
- else
- {
+ } else {
handleWatchedStage(async.watched().checkExists().forPath(path).event());
}
});
}
- public static void createThenWatchSimple(CuratorFramework client, String path)
- {
- AsyncCuratorFramework async = AsyncCuratorFramework.wrap(client); // normally you'd wrap early in your app and reuse the instance
+ public static void createThenWatchSimple(CuratorFramework client, String path) {
+ AsyncCuratorFramework async =
+ AsyncCuratorFramework.wrap(client); // normally you'd wrap early in your app and reuse the instance
// create a node at the given path with the given payload asynchronously
// then watch the created node
async.create().forPath(path).whenComplete((name, exception) -> {
- if ( exception != null )
- {
+ if (exception != null) {
// there was a problem creating the node
exception.printStackTrace();
- }
- else
- {
+ } else {
// because "WatchMode.successOnly" is used the watch stage is only triggered when
// the EventType is a node event
- async.with(WatchMode.successOnly).watched().checkExists().forPath(path).event().thenAccept(event -> {
- System.out.println(event.getType());
- System.out.println(event);
- });
+ async.with(WatchMode.successOnly)
+ .watched()
+ .checkExists()
+ .forPath(path)
+ .event()
+ .thenAccept(event -> {
+ System.out.println(event.getType());
+ System.out.println(event);
+ });
}
});
}
- private static void handleWatchedStage(CompletionStage<WatchedEvent> watchedStage)
- {
+ private static void handleWatchedStage(CompletionStage<WatchedEvent> watchedStage) {
// async handling of Watchers is complicated because watchers can trigger multiple times
// and CompletionStage don't support this behavior
@@ -119,8 +112,8 @@ public class AsyncExamples
// watchers trigger to signal the connection problem. "reset()" must be called
// to reset the watched stage
watchedStage.exceptionally(exception -> {
- AsyncEventException asyncEx = (AsyncEventException)exception;
- asyncEx.printStackTrace(); // handle the error as needed
+ AsyncEventException asyncEx = (AsyncEventException) exception;
+ asyncEx.printStackTrace(); // handle the error as needed
handleWatchedStage(asyncEx.reset());
return null;
});
diff --git a/curator-examples/src/main/java/cache/CuratorCacheExample.java b/curator-examples/src/main/java/cache/CuratorCacheExample.java
index 11da6ba4..bb9aa911 100644
--- a/curator-examples/src/main/java/cache/CuratorCacheExample.java
+++ b/curator-examples/src/main/java/cache/CuratorCacheExample.java
@@ -19,40 +19,38 @@
package cache;
+import java.util.concurrent.ThreadLocalRandom;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.cache.CuratorCache;
import org.apache.curator.framework.recipes.cache.CuratorCacheListener;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.curator.test.TestingServer;
-import java.util.concurrent.ThreadLocalRandom;
/**
* Very simple example of creating a CuratorCache that listens to events and logs the changes
* to standard out. A loop of random changes is run to exercise the cache.
*/
-public class CuratorCacheExample
-{
+public class CuratorCacheExample {
private static final String PATH = "/example/cache";
- public static void main(String[] args) throws Exception
- {
+ public static void main(String[] args) throws Exception {
ThreadLocalRandom random = ThreadLocalRandom.current();
- try (TestingServer server = new TestingServer())
- {
- try (CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new ExponentialBackoffRetry(1000, 3)))
- {
+ try (TestingServer server = new TestingServer()) {
+ try (CuratorFramework client = CuratorFrameworkFactory.newClient(
+ server.getConnectString(), new ExponentialBackoffRetry(1000, 3))) {
client.start();
- try (CuratorCache cache = CuratorCache.build(client, PATH))
- {
+ try (CuratorCache cache = CuratorCache.build(client, PATH)) {
// there are several ways to set a listener on a CuratorCache. You can watch for individual events
// or for all events. Here, we'll use the builder to log individual cache actions
CuratorCacheListener listener = CuratorCacheListener.builder()
- .forCreates(node -> System.out.println(String.format("Node created: [%s]", node)))
- .forChanges((oldNode, node) -> System.out.println(String.format("Node changed. Old: [%s] New: [%s]", oldNode, node)))
- .forDeletes(oldNode -> System.out.println(String.format("Node deleted. Old value: [%s]", oldNode)))
- .forInitialized(() -> System.out.println("Cache initialized"))
- .build();
+ .forCreates(node -> System.out.println(String.format("Node created: [%s]", node)))
+ .forChanges((oldNode, node) -> System.out.println(
+ String.format("Node changed. Old: [%s] New: [%s]", oldNode, node)))
+ .forDeletes(oldNode ->
+ System.out.println(String.format("Node deleted. Old value: [%s]", oldNode)))
+ .forInitialized(() -> System.out.println("Cache initialized"))
+ .build();
// register the listener
cache.listenable().addListener(listener);
@@ -61,16 +59,17 @@ public class CuratorCacheExample
cache.start();
// now randomly create/change/delete nodes
- for ( int i = 0; i < 1000; ++i )
- {
+ for (int i = 0; i < 1000; ++i) {
int depth = random.nextInt(1, 4);
String path = makeRandomPath(random, depth);
- if ( random.nextBoolean() )
- {
- client.create().orSetData().creatingParentsIfNeeded().forPath(path, Long.toString(random.nextLong()).getBytes());
- }
- else
- {
+ if (random.nextBoolean()) {
+ client.create()
+ .orSetData()
+ .creatingParentsIfNeeded()
+ .forPath(
+ path,
+ Long.toString(random.nextLong()).getBytes());
+ } else {
client.delete().quietly().deletingChildrenIfNeeded().forPath(path);
}
@@ -81,12 +80,10 @@ public class CuratorCacheExample
}
}
- private static String makeRandomPath(ThreadLocalRandom random, int depth)
- {
- if ( depth == 0 )
- {
+ private static String makeRandomPath(ThreadLocalRandom random, int depth) {
+ if (depth == 0) {
return PATH;
}
return makeRandomPath(random, depth - 1) + "/" + random.nextInt(3);
}
-}
\ No newline at end of file
+}
diff --git a/curator-examples/src/main/java/cache/PathCacheExample.java b/curator-examples/src/main/java/cache/PathCacheExample.java
index cbfcc7a8..1e947d52 100644
--- a/curator-examples/src/main/java/cache/PathCacheExample.java
+++ b/curator-examples/src/main/java/cache/PathCacheExample.java
@@ -20,7 +20,11 @@
package cache;
import com.google.common.collect.Lists;
-import org.apache.curator.utils.CloseableUtils;
+import discovery.ExampleServer;
+import java.io.BufferedReader;
+import java.io.InputStreamReader;
+import java.util.Arrays;
+import java.util.List;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.cache.ChildData;
@@ -29,30 +33,23 @@ import org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheListener;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.curator.test.TestingServer;
+import org.apache.curator.utils.CloseableUtils;
import org.apache.curator.utils.ZKPaths;
-import discovery.ExampleServer;
import org.apache.zookeeper.KeeperException;
-import java.io.BufferedReader;
-import java.io.InputStreamReader;
-import java.util.Arrays;
-import java.util.List;
/**
* An example of the PathChildrenCache. The example "harness" is a command processor
* that allows adding/updating/removed nodes in a path. A PathChildrenCache keeps a
* cache of these changes and outputs when updates occurs.
*/
-public class PathCacheExample
-{
- private static final String PATH = "/example/cache";
-
- public static void main(String[] args) throws Exception
- {
- TestingServer server = new TestingServer();
- CuratorFramework client = null;
- PathChildrenCache cache = null;
- try
- {
+public class PathCacheExample {
+ private static final String PATH = "/example/cache";
+
+ public static void main(String[] args) throws Exception {
+ TestingServer server = new TestingServer();
+ CuratorFramework client = null;
+ PathChildrenCache cache = null;
+ try {
client = CuratorFrameworkFactory.newClient(server.getConnectString(), new ExponentialBackoffRetry(1000, 3));
client.start();
@@ -61,40 +58,34 @@ public class PathCacheExample
cache.start();
processCommands(client, cache);
- }
- finally
- {
+ } finally {
CloseableUtils.closeQuietly(cache);
CloseableUtils.closeQuietly(client);
CloseableUtils.closeQuietly(server);
}
}
- private static void addListener(PathChildrenCache cache)
- {
+ private static void addListener(PathChildrenCache cache) {
// a PathChildrenCacheListener is optional. Here, it's used just to log changes
- PathChildrenCacheListener listener = new PathChildrenCacheListener()
- {
+ PathChildrenCacheListener listener = new PathChildrenCacheListener() {
@Override
- public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception
- {
- switch ( event.getType() )
- {
- case CHILD_ADDED:
- {
- System.out.println("Node added: " + ZKPaths.getNodeFromPath(event.getData().getPath()));
+ public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception {
+ switch (event.getType()) {
+ case CHILD_ADDED: {
+ System.out.println("Node added: "
+ + ZKPaths.getNodeFromPath(event.getData().getPath()));
break;
}
- case CHILD_UPDATED:
- {
- System.out.println("Node changed: " + ZKPaths.getNodeFromPath(event.getData().getPath()));
+ case CHILD_UPDATED: {
+ System.out.println("Node changed: "
+ + ZKPaths.getNodeFromPath(event.getData().getPath()));
break;
}
- case CHILD_REMOVED:
- {
- System.out.println("Node removed: " + ZKPaths.getNodeFromPath(event.getData().getPath()));
+ case CHILD_REMOVED: {
+ System.out.println("Node removed: "
+ + ZKPaths.getNodeFromPath(event.getData().getPath()));
break;
}
}
@@ -103,142 +94,108 @@ public class PathCacheExample
cache.getListenable().addListener(listener);
}
- private static void processCommands(CuratorFramework client, PathChildrenCache cache) throws Exception
- {
+ private static void processCommands(CuratorFramework client, PathChildrenCache cache) throws Exception {
// More scaffolding that does a simple command line processor
printHelp();
List<ExampleServer> servers = Lists.newArrayList();
- try
- {
+ try {
addListener(cache);
- BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
- boolean done = false;
- while ( !done )
- {
+ BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
+ boolean done = false;
+ while (!done) {
System.out.print("> ");
- String line = in.readLine();
- if ( line == null )
- {
+ String line = in.readLine();
+ if (line == null) {
break;
}
- String command = line.trim();
- String[] parts = command.split("\\s");
- if ( parts.length == 0 )
- {
+ String command = line.trim();
+ String[] parts = command.split("\\s");
+ if (parts.length == 0) {
continue;
}
- String operation = parts[0];
- String args[] = Arrays.copyOfRange(parts, 1, parts.length);
+ String operation = parts[0];
+ String args[] = Arrays.copyOfRange(parts, 1, parts.length);
- if ( operation.equalsIgnoreCase("help") || operation.equalsIgnoreCase("?") )
- {
+ if (operation.equalsIgnoreCase("help") || operation.equalsIgnoreCase("?")) {
printHelp();
- }
- else if ( operation.equalsIgnoreCase("q") || operation.equalsIgnoreCase("quit") )
- {
+ } else if (operation.equalsIgnoreCase("q") || operation.equalsIgnoreCase("quit")) {
done = true;
- }
- else if ( operation.equals("set") )
- {
+ } else if (operation.equals("set")) {
setValue(client, command, args);
- }
- else if ( operation.equals("remove") )
- {
+ } else if (operation.equals("remove")) {
remove(client, command, args);
- }
- else if ( operation.equals("list") )
- {
+ } else if (operation.equals("list")) {
list(cache);
}
Thread.sleep(1000); // just to allow the console output to catch up
}
- }
- finally
- {
- for ( ExampleServer server : servers )
- {
+ } finally {
+ for (ExampleServer server : servers) {
CloseableUtils.closeQuietly(server);
}
}
}
- private static void list(PathChildrenCache cache)
- {
- if ( cache.getCurrentData().size() == 0 )
- {
+ private static void list(PathChildrenCache cache) {
+ if (cache.getCurrentData().size() == 0) {
System.out.println("* empty *");
- }
- else
- {
- for ( ChildData data : cache.getCurrentData() )
- {
+ } else {
+ for (ChildData data : cache.getCurrentData()) {
System.out.println(data.getPath() + " = " + new String(data.getData()));
}
}
}
- private static void remove(CuratorFramework client, String command, String[] args) throws Exception
- {
- if ( args.length != 1 )
- {
+ private static void remove(CuratorFramework client, String command, String[] args) throws Exception {
+ if (args.length != 1) {
System.err.println("syntax error (expected remove <path>): " + command);
return;
}
- String name = args[0];
- if ( name.contains("/") )
- {
+ String name = args[0];
+ if (name.contains("/")) {
System.err.println("Invalid node name" + name);
return;
}
- String path = ZKPaths.makePath(PATH, name);
+ String path = ZKPaths.makePath(PATH, name);
- try
- {
+ try {
client.delete().forPath(path);
- }
- catch ( KeeperException.NoNodeException e )
- {
+ } catch (KeeperException.NoNodeException e) {
// ignore
}
}
- private static void setValue(CuratorFramework client, String command, String[] args) throws Exception
- {
- if ( args.length != 2 )
- {
+ private static void setValue(CuratorFramework client, String command, String[] args) throws Exception {
+ if (args.length != 2) {
System.err.println("syntax error (expected set <path> <value>): " + command);
return;
}
- String name = args[0];
- if ( name.contains("/") )
- {
+ String name = args[0];
+ if (name.contains("/")) {
System.err.println("Invalid node name" + name);
return;
}
- String path = ZKPaths.makePath(PATH, name);
+ String path = ZKPaths.makePath(PATH, name);
- byte[] bytes = args[1].getBytes();
- try
- {
+ byte[] bytes = args[1].getBytes();
+ try {
client.setData().forPath(path, bytes);
- }
- catch ( KeeperException.NoNodeException e )
- {
+ } catch (KeeperException.NoNodeException e) {
client.create().creatingParentContainersIfNeeded().forPath(path, bytes);
}
}
- private static void printHelp()
- {
- System.out.println("An example of using PathChildrenCache. This example is driven by entering commands at the prompt:\n");
+ private static void printHelp() {
+ System.out.println(
+ "An example of using PathChildrenCache. This example is driven by entering commands at the prompt:\n");
System.out.println("set <name> <value>: Adds or updates a node with the given name");
System.out.println("remove <name>: Deletes the node with the given name");
System.out.println("list: List the nodes/values in the cache");
diff --git a/curator-examples/src/main/java/cache/TreeCacheExample.java b/curator-examples/src/main/java/cache/TreeCacheExample.java
index 5c49e078..dbb0b211 100644
--- a/curator-examples/src/main/java/cache/TreeCacheExample.java
+++ b/curator-examples/src/main/java/cache/TreeCacheExample.java
@@ -20,15 +20,13 @@
package cache;
import framework.CreateClientExamples;
-import org.apache.curator.framework.CuratorFramework;
-import org.apache.curator.framework.recipes.cache.TreeCache;
import java.io.BufferedReader;
import java.io.InputStreamReader;
+import org.apache.curator.framework.CuratorFramework;
+import org.apache.curator.framework.recipes.cache.TreeCache;
-public class TreeCacheExample
-{
- public static void main(String[] args) throws Exception
- {
+public class TreeCacheExample {
+ public static void main(String[] args) throws Exception {
CuratorFramework client = CreateClientExamples.createSimple("127.0.0.1:2181");
client.getUnhandledErrorListenable().addListener((message, e) -> {
System.err.println("error=" + message);
@@ -41,12 +39,10 @@ public class TreeCacheExample
TreeCache cache = TreeCache.newBuilder(client, "/").setCacheData(false).build();
cache.getListenable().addListener((c, event) -> {
- if ( event.getData() != null )
- {
- System.out.println("type=" + event.getType() + " path=" + event.getData().getPath());
- }
- else
- {
+ if (event.getData() != null) {
+ System.out.println(
+ "type=" + event.getType() + " path=" + event.getData().getPath());
+ } else {
System.out.println("type=" + event.getType());
}
});
diff --git a/curator-examples/src/main/java/discovery/DiscoveryExample.java b/curator-examples/src/main/java/discovery/DiscoveryExample.java
index e932fa5e..3949b8b0 100644
--- a/curator-examples/src/main/java/discovery/DiscoveryExample.java
+++ b/curator-examples/src/main/java/discovery/DiscoveryExample.java
@@ -23,11 +23,17 @@ import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
-import org.apache.curator.utils.CloseableUtils;
+import java.io.BufferedReader;
+import java.io.InputStreamReader;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.List;
+import java.util.Map;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.curator.test.TestingServer;
+import org.apache.curator.utils.CloseableUtils;
import org.apache.curator.x.discovery.ServiceDiscovery;
import org.apache.curator.x.discovery.ServiceDiscoveryBuilder;
import org.apache.curator.x.discovery.ServiceInstance;
@@ -36,40 +42,32 @@ import org.apache.curator.x.discovery.details.JsonInstanceSerializer;
import org.apache.curator.x.discovery.strategies.RandomStrategy;
import org.apache.zookeeper.KeeperException;
-import java.io.BufferedReader;
-import java.io.InputStreamReader;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.List;
-import java.util.Map;
-
-public class DiscoveryExample
-{
- private static final String PATH = "/discovery/example";
+public class DiscoveryExample {
+ private static final String PATH = "/discovery/example";
- public static void main(String[] args) throws Exception
- {
+ public static void main(String[] args) throws Exception {
// This method is scaffolding to get the example up and running
- TestingServer server = new TestingServer();
- CuratorFramework client = null;
- ServiceDiscovery<InstanceDetails> serviceDiscovery = null;
- Map<String, ServiceProvider<InstanceDetails>> providers = Maps.newHashMap();
- try
- {
+ TestingServer server = new TestingServer();
+ CuratorFramework client = null;
+ ServiceDiscovery<InstanceDetails> serviceDiscovery = null;
+ Map<String, ServiceProvider<InstanceDetails>> providers = Maps.newHashMap();
+ try {
client = CuratorFrameworkFactory.newClient(server.getConnectString(), new ExponentialBackoffRetry(1000, 3));
client.start();
- JsonInstanceSerializer<InstanceDetails> serializer = new JsonInstanceSerializer<InstanceDetails>(InstanceDetails.class);
- serviceDiscovery = ServiceDiscoveryBuilder.builder(InstanceDetails.class).client(client).basePath(PATH).serializer(serializer).build();
+ JsonInstanceSerializer<InstanceDetails> serializer =
+ new JsonInstanceSerializer<InstanceDetails>(InstanceDetails.class);
+ serviceDiscovery = ServiceDiscoveryBuilder.builder(InstanceDetails.class)
+ .client(client)
+ .basePath(PATH)
+ .serializer(serializer)
+ .build();
serviceDiscovery.start();
processCommands(serviceDiscovery, providers, client);
- }
- finally
- {
- for ( ServiceProvider<InstanceDetails> cache : providers.values() )
- {
+ } finally {
+ for (ServiceProvider<InstanceDetails> cache : providers.values()) {
CloseableUtils.closeQuietly(cache);
}
@@ -79,165 +77,139 @@ public class DiscoveryExample
}
}
- private static void processCommands(ServiceDiscovery<InstanceDetails> serviceDiscovery, Map<String, ServiceProvider<InstanceDetails>> providers, CuratorFramework client) throws Exception
- {
+ private static void processCommands(
+ ServiceDiscovery<InstanceDetails> serviceDiscovery,
+ Map<String, ServiceProvider<InstanceDetails>> providers,
+ CuratorFramework client)
+ throws Exception {
// More scaffolding that does a simple command line processor
printHelp();
- List<ExampleServer> servers = Lists.newArrayList();
- try
- {
- BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
- boolean done = false;
- while ( !done )
- {
+ List<ExampleServer> servers = Lists.newArrayList();
+ try {
+ BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
+ boolean done = false;
+ while (!done) {
System.out.print("> ");
- String line = in.readLine();
- if ( line == null )
- {
+ String line = in.readLine();
+ if (line == null) {
break;
}
- String command = line.trim();
- String[] parts = command.split("\\s");
- if ( parts.length == 0 )
- {
+ String command = line.trim();
+ String[] parts = command.split("\\s");
+ if (parts.length == 0) {
continue;
}
- String operation = parts[0];
- String args[] = Arrays.copyOfRange(parts, 1, parts.length);
+ String operation = parts[0];
+ String args[] = Arrays.copyOfRange(parts, 1, parts.length);
- if ( operation.equalsIgnoreCase("help") || operation.equalsIgnoreCase("?") )
- {
+ if (operation.equalsIgnoreCase("help") || operation.equalsIgnoreCase("?")) {
printHelp();
- }
- else if ( operation.equalsIgnoreCase("q") || operation.equalsIgnoreCase("quit") )
- {
+ } else if (operation.equalsIgnoreCase("q") || operation.equalsIgnoreCase("quit")) {
done = true;
- }
- else if ( operation.equals("add") )
- {
+ } else if (operation.equals("add")) {
addInstance(args, client, command, servers);
- }
- else if ( operation.equals("delete") )
- {
+ } else if (operation.equals("delete")) {
deleteInstance(args, command, servers);
- }
- else if ( operation.equals("random") )
- {
+ } else if (operation.equals("random")) {
listRandomInstance(args, serviceDiscovery, providers, command);
- }
- else if ( operation.equals("list") )
- {
+ } else if (operation.equals("list")) {
listInstances(serviceDiscovery);
}
}
- }
- finally
- {
- for ( ExampleServer server : servers )
- {
+ } finally {
+ for (ExampleServer server : servers) {
CloseableUtils.closeQuietly(server);
}
}
}
- private static void listRandomInstance(String[] args, ServiceDiscovery<InstanceDetails> serviceDiscovery, Map<String, ServiceProvider<InstanceDetails>> providers, String command) throws Exception
- {
+ private static void listRandomInstance(
+ String[] args,
+ ServiceDiscovery<InstanceDetails> serviceDiscovery,
+ Map<String, ServiceProvider<InstanceDetails>> providers,
+ String command)
+ throws Exception {
// this shows how to use a ServiceProvider
// in a real application you'd create the ServiceProvider early for the service(s) you're interested in
- if ( args.length != 1 )
- {
+ if (args.length != 1) {
System.err.println("syntax error (expected random <name>): " + command);
return;
}
- String serviceName = args[0];
- ServiceProvider<InstanceDetails> provider = providers.get(serviceName);
- if ( provider == null )
- {
- provider = serviceDiscovery.serviceProviderBuilder().serviceName(serviceName).providerStrategy(new RandomStrategy<InstanceDetails>()).build();
+ String serviceName = args[0];
+ ServiceProvider<InstanceDetails> provider = providers.get(serviceName);
+ if (provider == null) {
+ provider = serviceDiscovery
+ .serviceProviderBuilder()
+ .serviceName(serviceName)
+ .providerStrategy(new RandomStrategy<InstanceDetails>())
+ .build();
providers.put(serviceName, provider);
provider.start();
- Thread.sleep(2500); // give the provider time to warm up - in a real application you wouldn't need to do this
+ Thread.sleep(
+ 2500); // give the provider time to warm up - in a real application you wouldn't need to do this
}
- ServiceInstance<InstanceDetails> instance = provider.getInstance();
- if ( instance == null )
- {
+ ServiceInstance<InstanceDetails> instance = provider.getInstance();
+ if (instance == null) {
System.err.println("No instances named: " + serviceName);
- }
- else
- {
+ } else {
outputInstance(instance);
}
}
- private static void listInstances(ServiceDiscovery<InstanceDetails> serviceDiscovery) throws Exception
- {
+ private static void listInstances(ServiceDiscovery<InstanceDetails> serviceDiscovery) throws Exception {
// This shows how to query all the instances in service discovery
- try
- {
- Collection<String> serviceNames = serviceDiscovery.queryForNames();
+ try {
+ Collection<String> serviceNames = serviceDiscovery.queryForNames();
System.out.println(serviceNames.size() + " type(s)");
- for ( String serviceName : serviceNames )
- {
- Collection<ServiceInstance<InstanceDetails>> instances = serviceDiscovery.queryForInstances(serviceName);
+ for (String serviceName : serviceNames) {
+ Collection<ServiceInstance<InstanceDetails>> instances =
+ serviceDiscovery.queryForInstances(serviceName);
System.out.println(serviceName);
- for ( ServiceInstance<InstanceDetails> instance : instances )
- {
+ for (ServiceInstance<InstanceDetails> instance : instances) {
outputInstance(instance);
}
}
- }
- catch ( KeeperException.NoNodeException e )
- {
+ } catch (KeeperException.NoNodeException e) {
System.err.println("There are no registered instances.");
- }
- finally
- {
+ } finally {
CloseableUtils.closeQuietly(serviceDiscovery);
}
}
- private static void outputInstance(ServiceInstance<InstanceDetails> instance)
- {
+ private static void outputInstance(ServiceInstance<InstanceDetails> instance) {
System.out.println("\t" + instance.getPayload().getDescription() + ": " + instance.buildUriSpec());
}
- private static void deleteInstance(String[] args, String command, List<ExampleServer> servers)
- {
+ private static void deleteInstance(String[] args, String command, List<ExampleServer> servers) {
// simulate a random instance going down
// in a real application, this would occur due to normal operation, a crash, maintenance, etc.
- if ( args.length != 1 )
- {
+ if (args.length != 1) {
System.err.println("syntax error (expected delete <name>): " + command);
return;
}
- final String serviceName = args[0];
- ExampleServer server = Iterables.find
- (
- servers,
- new Predicate<ExampleServer>()
- {
- @Override
- public boolean apply(ExampleServer server)
- {
- return server.getThisInstance().getName().endsWith(serviceName);
- }
- },
- null
- );
- if ( server == null )
- {
+ final String serviceName = args[0];
+ ExampleServer server = Iterables.find(
+ servers,
+ new Predicate<ExampleServer>() {
+ @Override
+ public boolean apply(ExampleServer server) {
+ return server.getThisInstance().getName().endsWith(serviceName);
+ }
+ },
+ null);
+ if (server == null) {
System.err.println("No servers found named: " + serviceName);
return;
}
@@ -247,38 +219,35 @@ public class DiscoveryExample
System.out.println("Removed a random instance of: " + serviceName);
}
- private static void addInstance(String[] args, CuratorFramework client, String command, List<ExampleServer> servers) throws Exception
- {
+ private static void addInstance(String[] args, CuratorFramework client, String command, List<ExampleServer> servers)
+ throws Exception {
// simulate a new instance coming up
// in a real application, this would be a separate process
- if ( args.length < 2 )
- {
+ if (args.length < 2) {
System.err.println("syntax error (expected add <name> <description>): " + command);
return;
}
- StringBuilder description = new StringBuilder();
- for ( int i = 1; i < args.length; ++i )
- {
- if ( i > 1 )
- {
+ StringBuilder description = new StringBuilder();
+ for (int i = 1; i < args.length; ++i) {
+ if (i > 1) {
description.append(' ');
}
description.append(args[i]);
}
- String serviceName = args[0];
- ExampleServer server = new ExampleServer(client, PATH, serviceName, description.toString());
+ String serviceName = args[0];
+ ExampleServer server = new ExampleServer(client, PATH, serviceName, description.toString());
servers.add(server);
server.start();
System.out.println(serviceName + " added");
}
- private static void printHelp()
- {
- System.out.println("An example of using the ServiceDiscovery APIs. This example is driven by entering commands at the prompt:\n");
+ private static void printHelp() {
+ System.out.println(
+ "An example of using the ServiceDiscovery APIs. This example is driven by entering commands at the prompt:\n");
System.out.println("add <name> <description>: Adds a mock service with the given name and description");
System.out.println("delete <name>: Deletes one of the mock services with the given name");
System.out.println("list: Lists all the currently registered services");
diff --git a/curator-examples/src/main/java/discovery/ExampleServer.java b/curator-examples/src/main/java/discovery/ExampleServer.java
index 9b461ee8..aabeecca 100644
--- a/curator-examples/src/main/java/discovery/ExampleServer.java
+++ b/curator-examples/src/main/java/discovery/ExampleServer.java
@@ -19,62 +19,59 @@
package discovery;
-import org.apache.curator.utils.CloseableUtils;
+import java.io.Closeable;
+import java.io.IOException;
import org.apache.curator.framework.CuratorFramework;
+import org.apache.curator.utils.CloseableUtils;
import org.apache.curator.x.discovery.ServiceDiscovery;
import org.apache.curator.x.discovery.ServiceDiscoveryBuilder;
import org.apache.curator.x.discovery.ServiceInstance;
import org.apache.curator.x.discovery.UriSpec;
import org.apache.curator.x.discovery.details.JsonInstanceSerializer;
-import java.io.Closeable;
-import java.io.IOException;
/**
* This shows a very simplified method of registering an instance with the service discovery. Each individual
* instance in your distributed set of applications would create an instance of something similar to ExampleServer,
* start it when the application comes up and close it when the application shuts down.
*/
-public class ExampleServer implements Closeable
-{
+public class ExampleServer implements Closeable {
private final ServiceDiscovery<InstanceDetails> serviceDiscovery;
private final ServiceInstance<InstanceDetails> thisInstance;
- public ExampleServer(CuratorFramework client, String path, String serviceName, String description) throws Exception
- {
+ public ExampleServer(CuratorFramework client, String path, String serviceName, String description)
+ throws Exception {
// in a real application, you'd have a convention of some kind for the URI layout
- UriSpec uriSpec = new UriSpec("{scheme}://foo.com:{port}");
+ UriSpec uriSpec = new UriSpec("{scheme}://foo.com:{port}");
thisInstance = ServiceInstance.<InstanceDetails>builder()
- .name(serviceName)
- .payload(new InstanceDetails(description))
- .port((int)(65535 * Math.random())) // in a real application, you'd use a common port
- .uriSpec(uriSpec)
- .build();
+ .name(serviceName)
+ .payload(new InstanceDetails(description))
+ .port((int) (65535 * Math.random())) // in a real application, you'd use a common port
+ .uriSpec(uriSpec)
+ .build();
// if you mark your payload class with @JsonRootName the provided JsonInstanceSerializer will work
- JsonInstanceSerializer<InstanceDetails> serializer = new JsonInstanceSerializer<InstanceDetails>(InstanceDetails.class);
+ JsonInstanceSerializer<InstanceDetails> serializer =
+ new JsonInstanceSerializer<InstanceDetails>(InstanceDetails.class);
serviceDiscovery = ServiceDiscoveryBuilder.builder(InstanceDetails.class)
- .client(client)
- .basePath(path)
- .serializer(serializer)
- .thisInstance(thisInstance)
- .build();
+ .client(client)
+ .basePath(path)
+ .serializer(serializer)
+ .thisInstance(thisInstance)
+ .build();
}
- public ServiceInstance<InstanceDetails> getThisInstance()
- {
+ public ServiceInstance<InstanceDetails> getThisInstance() {
return thisInstance;
}
- public void start() throws Exception
- {
+ public void start() throws Exception {
serviceDiscovery.start();
}
@Override
- public void close() throws IOException
- {
+ public void close() throws IOException {
CloseableUtils.closeQuietly(serviceDiscovery);
}
}
diff --git a/curator-examples/src/main/java/discovery/InstanceDetails.java b/curator-examples/src/main/java/discovery/InstanceDetails.java
index 8c40a979..8124cf62 100644
--- a/curator-examples/src/main/java/discovery/InstanceDetails.java
+++ b/curator-examples/src/main/java/discovery/InstanceDetails.java
@@ -26,27 +26,22 @@ import com.fasterxml.jackson.annotation.JsonRootName;
* be more detailed than this. But, this gives a good example.
*/
@JsonRootName("details")
-public class InstanceDetails
-{
- private String description;
+public class InstanceDetails {
+ private String description;
- public InstanceDetails()
- {
+ public InstanceDetails() {
this("");
}
- public InstanceDetails(String description)
- {
+ public InstanceDetails(String description) {
this.description = description;
}
- public void setDescription(String description)
- {
+ public void setDescription(String description) {
this.description = description;
}
- public String getDescription()
- {
+ public String getDescription() {
return description;
}
}
diff --git a/curator-examples/src/main/java/framework/CreateClientExamples.java b/curator-examples/src/main/java/framework/CreateClientExamples.java
index 31c799c3..aba6fac1 100644
--- a/curator-examples/src/main/java/framework/CreateClientExamples.java
+++ b/curator-examples/src/main/java/framework/CreateClientExamples.java
@@ -24,10 +24,8 @@ import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
-public class CreateClientExamples
-{
- public static CuratorFramework createSimple(String connectionString)
- {
+public class CreateClientExamples {
+ public static CuratorFramework createSimple(String connectionString) {
// these are reasonable arguments for the ExponentialBackoffRetry. The first
// retry will wait 1 second - the second will wait up to 2 seconds - the
// third will wait up to 4 seconds.
@@ -38,17 +36,17 @@ public class CreateClientExamples
return CuratorFrameworkFactory.newClient(connectionString, retryPolicy);
}
- public static CuratorFramework createWithOptions(String connectionString, RetryPolicy retryPolicy, int connectionTimeoutMs, int sessionTimeoutMs)
- {
+ public static CuratorFramework createWithOptions(
+ String connectionString, RetryPolicy retryPolicy, int connectionTimeoutMs, int sessionTimeoutMs) {
// using the CuratorFrameworkFactory.builder() gives fine grained control
// over creation options. See the CuratorFrameworkFactory.Builder javadoc
// details
return CuratorFrameworkFactory.builder()
- .connectString(connectionString)
- .retryPolicy(retryPolicy)
- .connectionTimeoutMs(connectionTimeoutMs)
- .sessionTimeoutMs(sessionTimeoutMs)
- // etc. etc.
- .build();
+ .connectString(connectionString)
+ .retryPolicy(retryPolicy)
+ .connectionTimeoutMs(connectionTimeoutMs)
+ .sessionTimeoutMs(sessionTimeoutMs)
+ // etc. etc.
+ .build();
}
}
diff --git a/curator-examples/src/main/java/framework/CrudExamples.java b/curator-examples/src/main/java/framework/CrudExamples.java
index 8ac76098..9cde6287 100644
--- a/curator-examples/src/main/java/framework/CrudExamples.java
+++ b/curator-examples/src/main/java/framework/CrudExamples.java
@@ -19,52 +19,51 @@
package framework;
+import java.util.List;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.api.BackgroundCallback;
import org.apache.curator.framework.api.CuratorEvent;
import org.apache.curator.framework.api.CuratorListener;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.Watcher;
-import java.util.List;
-public class CrudExamples
-{
- public static void create(CuratorFramework client, String path, byte[] payload) throws Exception
- {
+public class CrudExamples {
+ public static void create(CuratorFramework client, String path, byte[] payload) throws Exception {
// this will create the given ZNode with the given data
client.create().forPath(path, payload);
}
- public static void createEphemeral(CuratorFramework client, String path, byte[] payload) throws Exception
- {
+ public static void createEphemeral(CuratorFramework client, String path, byte[] payload) throws Exception {
// this will create the given EPHEMERAL ZNode with the given data
client.create().withMode(CreateMode.EPHEMERAL).forPath(path, payload);
}
- public static String createEphemeralSequential(CuratorFramework client, String path, byte[] payload) throws Exception
- {
+ public static String createEphemeralSequential(CuratorFramework client, String path, byte[] payload)
+ throws Exception {
// this will create the given EPHEMERAL-SEQUENTIAL ZNode with the given data using Curator protection.
/*
- Protection Mode:
-
- It turns out there is an edge case that exists when creating sequential-ephemeral nodes. The creation
- can succeed on the server, but the server can crash before the created node name is returned to the
- client. However, the ZK session is still valid so the ephemeral node is not deleted. Thus, there is no
- way for the client to determine what node was created for them.
-
- Even without sequential-ephemeral, however, the create can succeed on the sever but the client (for various
- reasons) will not know it. Putting the create builder into protection mode works around this. The name of
- the node that is created is prefixed with a GUID. If node creation fails the normal retry mechanism will
- occur. On the retry, the parent path is first searched for a node that has the GUID in it. If that node is
- found, it is assumed to be the lost node that was successfully created on the first try and is returned to
- the caller.
- */
- return client.create().withProtection().withMode(CreateMode.EPHEMERAL_SEQUENTIAL).forPath(path, payload);
+ Protection Mode:
+
+ It turns out there is an edge case that exists when creating sequential-ephemeral nodes. The creation
+ can succeed on the server, but the server can crash before the created node name is returned to the
+ client. However, the ZK session is still valid so the ephemeral node is not deleted. Thus, there is no
+ way for the client to determine what node was created for them.
+
+ Even without sequential-ephemeral, however, the create can succeed on the sever but the client (for various
+ reasons) will not know it. Putting the create builder into protection mode works around this. The name of
+ the node that is created is prefixed with a GUID. If node creation fails the normal retry mechanism will
+ occur. On the retry, the parent path is first searched for a node that has the GUID in it. If that node is
+ found, it is assumed to be the lost node that was successfully created on the first try and is returned to
+ the caller.
+ */
+ return client.create()
+ .withProtection()
+ .withMode(CreateMode.EPHEMERAL_SEQUENTIAL)
+ .forPath(path, payload);
}
- public static void createIdempotent(CuratorFramework client, String path, byte[] payload) throws Exception
- {
+ public static void createIdempotent(CuratorFramework client, String path, byte[] payload) throws Exception {
/*
* This will create the given ZNode with the given data idempotently, meaning that if the initial create
* failed transiently, it will be retried and behave as if the first create never happened, even if the
@@ -73,20 +72,16 @@ public class CrudExamples
client.create().idempotent().forPath(path, payload);
}
- public static void setData(CuratorFramework client, String path, byte[] payload) throws Exception
- {
+ public static void setData(CuratorFramework client, String path, byte[] payload) throws Exception {
// set data for the given node
client.setData().forPath(path, payload);
}
- public static void setDataAsync(CuratorFramework client, String path, byte[] payload) throws Exception
- {
+ public static void setDataAsync(CuratorFramework client, String path, byte[] payload) throws Exception {
// this is one method of getting event/async notifications
- CuratorListener listener = new CuratorListener()
- {
+ CuratorListener listener = new CuratorListener() {
@Override
- public void eventReceived(CuratorFramework client, CuratorEvent event) throws Exception
- {
+ public void eventReceived(CuratorFramework client, CuratorEvent event) throws Exception {
// examine event for details
}
};
@@ -97,14 +92,14 @@ public class CrudExamples
client.setData().inBackground().forPath(path, payload);
}
- public static void setDataAsyncWithCallback(CuratorFramework client, BackgroundCallback callback, String path, byte[] payload) throws Exception
- {
+ public static void setDataAsyncWithCallback(
+ CuratorFramework client, BackgroundCallback callback, String path, byte[] payload) throws Exception {
// this is another method of getting notification of an async completion
client.setData().inBackground(callback).forPath(path, payload);
}
- public static void setDataIdempotent(CuratorFramework client, String path, byte[] payload, int currentVersion) throws Exception
- {
+ public static void setDataIdempotent(CuratorFramework client, String path, byte[] payload, int currentVersion)
+ throws Exception {
/*
* This will set the given ZNode with the given data idempotently, meaning that if the initial setData
* failed transiently, it will be retried and behave as if the first setData never happened, even if the
@@ -117,38 +112,33 @@ public class CrudExamples
client.setData().idempotent().forPath(path, payload);
}
-
-
- public static void delete(CuratorFramework client, String path) throws Exception
- {
+ public static void delete(CuratorFramework client, String path) throws Exception {
// delete the given node
client.delete().forPath(path);
}
- public static void guaranteedDelete(CuratorFramework client, String path) throws Exception
- {
+ public static void guaranteedDelete(CuratorFramework client, String path) throws Exception {
// delete the given node and guarantee that it completes
/*
- Guaranteed Delete
+ Guaranteed Delete
- Solves this edge case: deleting a node can fail due to connection issues. Further, if the node was
- ephemeral, the node will not get auto-deleted as the session is still valid. This can wreak havoc
- with lock implementations.
+ Solves this edge case: deleting a node can fail due to connection issues. Further, if the node was
+ ephemeral, the node will not get auto-deleted as the session is still valid. This can wreak havoc
+ with lock implementations.
- When guaranteed is set, Curator will record failed node deletions and attempt to delete them in the
- background until successful. NOTE: you will still get an exception when the deletion fails. But, you
- can be assured that as long as the CuratorFramework instance is open attempts will be made to delete
- the node.
- */
+ When guaranteed is set, Curator will record failed node deletions and attempt to delete them in the
+ background until successful. NOTE: you will still get an exception when the deletion fails. But, you
+ can be assured that as long as the CuratorFramework instance is open attempts will be made to delete
+ the node.
+ */
client.delete().guaranteed().forPath(path);
}
- public static void deleteIdempotent(CuratorFramework client, String path, int currentVersion) throws Exception
- {
- /*
+ public static void deleteIdempotent(CuratorFramework client, String path, int currentVersion) throws Exception {
+ /*
* This will delete the given ZNode with the given data idempotently, meaning that if the initial delete
* failed transiently, it will be retried and behave as if the first delete never happened, even if the
* first delete actually succeeded on the server but the client didn't know it.
@@ -164,8 +154,7 @@ public class CrudExamples
client.delete().quietly().forPath(path);
}
- public static List<String> watchedGetChildren(CuratorFramework client, String path) throws Exception
- {
+ public static List<String> watchedGetChildren(CuratorFramework client, String path) throws Exception {
/**
* Get children and set a watcher on the node. The watcher notification will come through the
* CuratorListener (see setDataAsync() above).
@@ -173,8 +162,8 @@ public class CrudExamples
return client.getChildren().watched().forPath(path);
}
- public static List<String> watchedGetChildren(CuratorFramework client, String path, Watcher watcher) throws Exception
- {
+ public static List<String> watchedGetChildren(CuratorFramework client, String path, Watcher watcher)
+ throws Exception {
/**
* Get children and set the given watcher on the node.
*/
diff --git a/curator-examples/src/main/java/framework/TransactionExamples.java b/curator-examples/src/main/java/framework/TransactionExamples.java
index 49d7920e..8e6fa5db 100644
--- a/curator-examples/src/main/java/framework/TransactionExamples.java
+++ b/curator-examples/src/main/java/framework/TransactionExamples.java
@@ -19,28 +19,23 @@
package framework;
+import java.util.Collection;
import org.apache.curator.framework.CuratorFramework;
-import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.api.transaction.CuratorOp;
import org.apache.curator.framework.api.transaction.CuratorTransactionResult;
-import org.apache.curator.retry.RetryOneTime;
-import org.apache.curator.test.TestingServer;
-import java.util.Collection;
-public class TransactionExamples
-{
- public static Collection<CuratorTransactionResult> transaction(CuratorFramework client) throws Exception
- {
+public class TransactionExamples {
+ public static Collection<CuratorTransactionResult> transaction(CuratorFramework client) throws Exception {
// this example shows how to use ZooKeeper's transactions
CuratorOp createOp = client.transactionOp().create().forPath("/a/path", "some data".getBytes());
CuratorOp setDataOp = client.transactionOp().setData().forPath("/another/path", "other data".getBytes());
CuratorOp deleteOp = client.transactionOp().delete().forPath("/yet/another/path");
- Collection<CuratorTransactionResult> results = client.transaction().forOperations(createOp, setDataOp, deleteOp);
+ Collection<CuratorTransactionResult> results =
+ client.transaction().forOperations(createOp, setDataOp, deleteOp);
- for ( CuratorTransactionResult result : results )
- {
+ for (CuratorTransactionResult result : results) {
System.out.println(result.getForPath() + " - " + result.getType());
}
diff --git a/curator-examples/src/main/java/leader/ExampleClient.java b/curator-examples/src/main/java/leader/ExampleClient.java
index 3b9f22b7..50965ff7 100644
--- a/curator-examples/src/main/java/leader/ExampleClient.java
+++ b/curator-examples/src/main/java/leader/ExampleClient.java
@@ -19,26 +19,24 @@
package leader;
-import org.apache.curator.framework.CuratorFramework;
-import org.apache.curator.framework.recipes.leader.LeaderSelectorListenerAdapter;
-import org.apache.curator.framework.recipes.leader.LeaderSelector;
import java.io.Closeable;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
+import org.apache.curator.framework.CuratorFramework;
+import org.apache.curator.framework.recipes.leader.LeaderSelector;
+import org.apache.curator.framework.recipes.leader.LeaderSelectorListenerAdapter;
/**
* An example leader selector client. Note that {@link LeaderSelectorListenerAdapter} which
* has the recommended handling for connection state issues
*/
-public class ExampleClient extends LeaderSelectorListenerAdapter implements Closeable
-{
+public class ExampleClient extends LeaderSelectorListenerAdapter implements Closeable {
private final String name;
private final LeaderSelector leaderSelector;
private final AtomicInteger leaderCount = new AtomicInteger();
- public ExampleClient(CuratorFramework client, String path, String name)
- {
+ public ExampleClient(CuratorFramework client, String path, String name) {
this.name = name;
// create a leader selector using the given path for management
@@ -50,39 +48,31 @@ public class ExampleClient extends LeaderSelectorListenerAdapter implements Clos
leaderSelector.autoRequeue();
}
- public void start() throws IOException
- {
+ public void start() throws IOException {
// the selection for this instance doesn't start until the leader selector is started
// leader selection is done in the background so this call to leaderSelector.start() returns immediately
leaderSelector.start();
}
@Override
- public void close() throws IOException
- {
+ public void close() throws IOException {
leaderSelector.close();
}
@Override
- public void takeLeadership(CuratorFramework client) throws Exception
- {
+ public void takeLeadership(CuratorFramework client) throws Exception {
// we are now the leader. This method should not return until we want to relinquish leadership
- final int waitSeconds = (int)(5 * Math.random()) + 1;
+ final int waitSeconds = (int) (5 * Math.random()) + 1;
System.out.println(name + " is now the leader. Waiting " + waitSeconds + " seconds...");
System.out.println(name + " has been leader " + leaderCount.getAndIncrement() + " time(s) before.");
- try
- {
+ try {
Thread.sleep(TimeUnit.SECONDS.toMillis(waitSeconds));
- }
- catch ( InterruptedException e )
- {
+ } catch (InterruptedException e) {
System.err.println(name + " was interrupted.");
Thread.currentThread().interrupt();
- }
- finally
- {
+ } finally {
System.out.println(name + " relinquishing leadership.\n");
}
}
diff --git a/curator-examples/src/main/java/leader/LeaderSelectorExample.java b/curator-examples/src/main/java/leader/LeaderSelectorExample.java
index 1c3de744..c8e9fd8c 100644
--- a/curator-examples/src/main/java/leader/LeaderSelectorExample.java
+++ b/curator-examples/src/main/java/leader/LeaderSelectorExample.java
@@ -20,39 +20,39 @@
package leader;
import com.google.common.collect.Lists;
-import org.apache.curator.utils.CloseableUtils;
+import java.io.BufferedReader;
+import java.io.InputStreamReader;
+import java.util.List;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.curator.test.TestingServer;
-import java.io.BufferedReader;
-import java.io.InputStreamReader;
-import java.util.List;
+import org.apache.curator.utils.CloseableUtils;
-public class LeaderSelectorExample
-{
- private static final int CLIENT_QTY = 10;
+public class LeaderSelectorExample {
+ private static final int CLIENT_QTY = 10;
- private static final String PATH = "/examples/leader";
+ private static final String PATH = "/examples/leader";
- public static void main(String[] args) throws Exception
- {
+ public static void main(String[] args) throws Exception {
// all of the useful sample code is in ExampleClient.java
- System.out.println("Create " + CLIENT_QTY + " clients, have each negotiate for leadership and then wait a random number of seconds before letting another leader election occur.");
- System.out.println("Notice that leader election is fair: all clients will become leader and will do so the same number of times.");
+ System.out.println(
+ "Create " + CLIENT_QTY
+ + " clients, have each negotiate for leadership and then wait a random number of seconds before letting another leader election occur.");
+ System.out.println(
+ "Notice that leader election is fair: all clients will become leader and will do so the same number of times.");
- List<CuratorFramework> clients = Lists.newArrayList();
- List<ExampleClient> examples = Lists.newArrayList();
- TestingServer server = new TestingServer();
- try
- {
- for ( int i = 0; i < CLIENT_QTY; ++i )
- {
- CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new ExponentialBackoffRetry(1000, 3));
+ List<CuratorFramework> clients = Lists.newArrayList();
+ List<ExampleClient> examples = Lists.newArrayList();
+ TestingServer server = new TestingServer();
+ try {
+ for (int i = 0; i < CLIENT_QTY; ++i) {
+ CuratorFramework client = CuratorFrameworkFactory.newClient(
+ server.getConnectString(), new ExponentialBackoffRetry(1000, 3));
clients.add(client);
- ExampleClient example = new ExampleClient(client, PATH, "Client #" + i);
+ ExampleClient example = new ExampleClient(client, PATH, "Client #" + i);
examples.add(example);
client.start();
@@ -61,17 +61,13 @@ public class LeaderSelectorExample
System.out.println("Press enter/return to quit\n");
new BufferedReader(new InputStreamReader(System.in)).readLine();
- }
- finally
- {
+ } finally {
System.out.println("Shutting down...");
- for ( ExampleClient exampleClient : examples )
- {
+ for (ExampleClient exampleClient : examples) {
CloseableUtils.closeQuietly(exampleClient);
}
- for ( CuratorFramework client : clients )
- {
+ for (CuratorFramework client : clients) {
CloseableUtils.closeQuietly(client);
}
diff --git a/curator-examples/src/main/java/locking/ExampleClientThatLocks.java b/curator-examples/src/main/java/locking/ExampleClientThatLocks.java
index 5c7cd1d9..52fe9ae0 100644
--- a/curator-examples/src/main/java/locking/ExampleClientThatLocks.java
+++ b/curator-examples/src/main/java/locking/ExampleClientThatLocks.java
@@ -19,36 +19,30 @@
package locking;
+import java.util.concurrent.TimeUnit;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
-import java.util.concurrent.TimeUnit;
-public class ExampleClientThatLocks
-{
+public class ExampleClientThatLocks {
private final InterProcessMutex lock;
private final FakeLimitedResource resource;
private final String clientName;
- public ExampleClientThatLocks(CuratorFramework client, String lockPath, FakeLimitedResource resource, String clientName)
- {
+ public ExampleClientThatLocks(
+ CuratorFramework client, String lockPath, FakeLimitedResource resource, String clientName) {
this.resource = resource;
this.clientName = clientName;
lock = new InterProcessMutex(client, lockPath);
}
- public void doWork(long time, TimeUnit unit) throws Exception
- {
- if ( !lock.acquire(time, unit) )
- {
+ public void doWork(long time, TimeUnit unit) throws Exception {
+ if (!lock.acquire(time, unit)) {
throw new IllegalStateException(clientName + " could not acquire the lock");
}
- try
- {
+ try {
System.out.println(clientName + " has the lock");
resource.use();
- }
- finally
- {
+ } finally {
System.out.println(clientName + " releasing the lock");
lock.release(); // always release the lock in a finally block
}
diff --git a/curator-examples/src/main/java/locking/FakeLimitedResource.java b/curator-examples/src/main/java/locking/FakeLimitedResource.java
index ac578e9b..58650d6a 100644
--- a/curator-examples/src/main/java/locking/FakeLimitedResource.java
+++ b/curator-examples/src/main/java/locking/FakeLimitedResource.java
@@ -24,25 +24,19 @@ import java.util.concurrent.atomic.AtomicBoolean;
/**
* Simulates some external resource that can only be access by one process at a time
*/
-public class FakeLimitedResource
-{
- private final AtomicBoolean inUse = new AtomicBoolean(false);
+public class FakeLimitedResource {
+ private final AtomicBoolean inUse = new AtomicBoolean(false);
- public void use() throws InterruptedException
- {
+ public void use() throws InterruptedException {
// in a real application this would be accessing/manipulating a shared resource
- if ( !inUse.compareAndSet(false, true) )
- {
+ if (!inUse.compareAndSet(false, true)) {
throw new IllegalStateException("Needs to be used by one client at a time");
}
- try
- {
- Thread.sleep((long)(3 * Math.random()));
- }
- finally
- {
+ try {
+ Thread.sleep((long) (3 * Math.random()));
+ } finally {
inUse.set(false);
}
}
diff --git a/curator-examples/src/main/java/locking/LockingExample.java b/curator-examples/src/main/java/locking/LockingExample.java
index bd2026e4..ec6a9321 100644
--- a/curator-examples/src/main/java/locking/LockingExample.java
+++ b/curator-examples/src/main/java/locking/LockingExample.java
@@ -19,64 +19,52 @@
package locking;
-import org.apache.curator.utils.CloseableUtils;
-import org.apache.curator.framework.CuratorFramework;
-import org.apache.curator.framework.CuratorFrameworkFactory;
-import org.apache.curator.retry.ExponentialBackoffRetry;
-import org.apache.curator.test.TestingServer;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
+import org.apache.curator.framework.CuratorFramework;
+import org.apache.curator.framework.CuratorFrameworkFactory;
+import org.apache.curator.retry.ExponentialBackoffRetry;
+import org.apache.curator.test.TestingServer;
+import org.apache.curator.utils.CloseableUtils;
-public class LockingExample
-{
- private static final int QTY = 5;
- private static final int REPETITIONS = QTY * 10;
+public class LockingExample {
+ private static final int QTY = 5;
+ private static final int REPETITIONS = QTY * 10;
- private static final String PATH = "/examples/locks";
+ private static final String PATH = "/examples/locks";
- public static void main(String[] args) throws Exception
- {
+ public static void main(String[] args) throws Exception {
// all of the useful sample code is in ExampleClientThatLocks.java
// FakeLimitedResource simulates some external resource that can only be access by one process at a time
- final FakeLimitedResource resource = new FakeLimitedResource();
+ final FakeLimitedResource resource = new FakeLimitedResource();
- ExecutorService service = Executors.newFixedThreadPool(QTY);
- final TestingServer server = new TestingServer();
- try
- {
- for ( int i = 0; i < QTY; ++i )
- {
- final int index = i;
- Callable<Void> task = new Callable<Void>()
- {
+ ExecutorService service = Executors.newFixedThreadPool(QTY);
+ final TestingServer server = new TestingServer();
+ try {
+ for (int i = 0; i < QTY; ++i) {
+ final int index = i;
+ Callable<Void> task = new Callable<Void>() {
@Override
- public Void call() throws Exception
- {
- CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new ExponentialBackoffRetry(1000, 3));
- try
- {
+ public Void call() throws Exception {
+ CuratorFramework client = CuratorFrameworkFactory.newClient(
+ server.getConnectString(), new ExponentialBackoffRetry(1000, 3));
+ try {
client.start();
- ExampleClientThatLocks example = new ExampleClientThatLocks(client, PATH, resource, "Client " + index);
- for ( int j = 0; j < REPETITIONS; ++j )
- {
+ ExampleClientThatLocks example =
+ new ExampleClientThatLocks(client, PATH, resource, "Client " + index);
+ for (int j = 0; j < REPETITIONS; ++j) {
example.doWork(10, TimeUnit.SECONDS);
}
- }
- catch ( InterruptedException e )
- {
+ } catch (InterruptedException e) {
Thread.currentThread().interrupt();
- }
- catch ( Exception e )
- {
+ } catch (Exception e) {
e.printStackTrace();
// log or do something
- }
- finally
- {
+ } finally {
CloseableUtils.closeQuietly(client);
}
return null;
@@ -87,9 +75,7 @@ public class LockingExample
service.shutdown();
service.awaitTermination(10, TimeUnit.MINUTES);
- }
- finally
- {
+ } finally {
CloseableUtils.closeQuietly(server);
}
}
diff --git a/curator-examples/src/main/java/modeled/ContainerType.java b/curator-examples/src/main/java/modeled/ContainerType.java
index c78a39bd..5207c8fc 100644
--- a/curator-examples/src/main/java/modeled/ContainerType.java
+++ b/curator-examples/src/main/java/modeled/ContainerType.java
@@ -19,51 +19,42 @@
package modeled;
-public class ContainerType
-{
+public class ContainerType {
private final int typeId;
- public ContainerType()
- {
+ public ContainerType() {
this(0);
}
- public ContainerType(int typeId)
- {
+ public ContainerType(int typeId) {
this.typeId = typeId;
}
- public int getTypeId()
- {
+ public int getTypeId() {
return typeId;
}
@Override
- public boolean equals(Object o)
- {
- if ( this == o )
- {
+ public boolean equals(Object o) {
+ if (this == o) {
return true;
}
- if ( o == null || getClass() != o.getClass() )
- {
+ if (o == null || getClass() != o.getClass()) {
return false;
}
- ContainerType that = (ContainerType)o;
+ ContainerType that = (ContainerType) o;
return typeId == that.typeId;
}
@Override
- public int hashCode()
- {
+ public int hashCode() {
return typeId;
}
@Override
- public String toString()
- {
+ public String toString() {
return "ContainerType{" + "typeId=" + typeId + '}';
}
}
diff --git a/curator-examples/src/main/java/modeled/ModeledCuratorExamples.java b/curator-examples/src/main/java/modeled/ModeledCuratorExamples.java
index 5806ecbc..064d00fd 100644
--- a/curator-examples/src/main/java/modeled/ModeledCuratorExamples.java
+++ b/curator-examples/src/main/java/modeled/ModeledCuratorExamples.java
@@ -19,21 +19,20 @@
package modeled;
+import java.util.function.Consumer;
import org.apache.curator.x.async.AsyncCuratorFramework;
import org.apache.curator.x.async.modeled.JacksonModelSerializer;
import org.apache.curator.x.async.modeled.ModelSpec;
import org.apache.curator.x.async.modeled.ModeledFramework;
import org.apache.curator.x.async.modeled.ZPath;
-import java.util.function.Consumer;
-public class ModeledCuratorExamples
-{
- public static ModeledFramework<PersonModel> wrap(AsyncCuratorFramework client)
- {
+public class ModeledCuratorExamples {
+ public static ModeledFramework<PersonModel> wrap(AsyncCuratorFramework client) {
JacksonModelSerializer<PersonModel> serializer = JacksonModelSerializer.build(PersonModel.class);
// build a model specification - you can pre-build all the model specifications for your app at startup
- ModelSpec<PersonModel> modelSpec = ModelSpec.builder(ZPath.parse("/example/path"), serializer).build();
+ ModelSpec<PersonModel> modelSpec =
+ ModelSpec.builder(ZPath.parse("/example/path"), serializer).build();
// wrap a CuratorFramework instance so that it can be used "modeled".
// do this once and re-use the returned ModeledFramework instance.
@@ -41,8 +40,7 @@ public class ModeledCuratorExamples
return ModeledFramework.wrap(client, modelSpec);
}
- public static void createOrUpdate(ModeledFramework<PersonModel> modeled, PersonModel model)
- {
+ public static void createOrUpdate(ModeledFramework<PersonModel> modeled, PersonModel model) {
// change the affected path to be modeled's base path plus id: i.e. "/example/path/{id}"
ModeledFramework<PersonModel> atId = modeled.child(model.getId().getId());
@@ -51,16 +49,12 @@ public class ModeledCuratorExamples
atId.set(model); // note - this is async
}
- public static void readPerson(ModeledFramework<PersonModel> modeled, String id, Consumer<PersonModel> receiver)
- {
+ public static void readPerson(ModeledFramework<PersonModel> modeled, String id, Consumer<PersonModel> receiver) {
// read the person with the given ID and asynchronously call the receiver after it is read
modeled.child(id).read().whenComplete((person, exception) -> {
- if ( exception != null )
- {
- exception.printStackTrace(); // handle the error
- }
- else
- {
+ if (exception != null) {
+ exception.printStackTrace(); // handle the error
+ } else {
receiver.accept(person);
}
});
diff --git a/curator-examples/src/main/java/modeled/ModeledCuratorExamplesAlt.java b/curator-examples/src/main/java/modeled/ModeledCuratorExamplesAlt.java
index f747bf8f..d07364dd 100644
--- a/curator-examples/src/main/java/modeled/ModeledCuratorExamplesAlt.java
+++ b/curator-examples/src/main/java/modeled/ModeledCuratorExamplesAlt.java
@@ -19,13 +19,11 @@
package modeled;
-import org.apache.curator.x.async.modeled.ModeledFramework;
import java.util.function.Consumer;
+import org.apache.curator.x.async.modeled.ModeledFramework;
-public class ModeledCuratorExamplesAlt
-{
- public static void createOrUpdate(PersonModelSpec modelSpec, PersonModel model)
- {
+public class ModeledCuratorExamplesAlt {
+ public static void createOrUpdate(PersonModelSpec modelSpec, PersonModel model) {
// change the affected path to be modeled's base path plus id: i.e. "/example/path/{id}"
ModeledFramework<PersonModel> resolved = modelSpec.resolved(model.getContainerType(), model.getId());
@@ -34,18 +32,15 @@ public class ModeledCuratorExamplesAlt
resolved.set(model); // note - this is async
}
- public static void readPerson(PersonModelSpec modelSpec, ContainerType containerType, PersonId id, Consumer<PersonModel> receiver)
- {
+ public static void readPerson(
+ PersonModelSpec modelSpec, ContainerType containerType, PersonId id, Consumer<PersonModel> receiver) {
ModeledFramework<PersonModel> resolved = modelSpec.resolved(containerType, id);
// read the person with the given ID and asynchronously call the receiver after it is read
resolved.read().whenComplete((person, exception) -> {
- if ( exception != null )
- {
- exception.printStackTrace(); // handle the error
- }
- else
- {
+ if (exception != null) {
+ exception.printStackTrace(); // handle the error
+ } else {
receiver.accept(person);
}
});
diff --git a/curator-examples/src/main/java/modeled/PersonId.java b/curator-examples/src/main/java/modeled/PersonId.java
index 143c8a46..3c5700ce 100644
--- a/curator-examples/src/main/java/modeled/PersonId.java
+++ b/curator-examples/src/main/java/modeled/PersonId.java
@@ -21,51 +21,42 @@ package modeled;
import java.util.Objects;
-public class PersonId
-{
+public class PersonId {
private final String id;
- public PersonId()
- {
+ public PersonId() {
this("");
}
- public PersonId(String id)
- {
+ public PersonId(String id) {
this.id = Objects.requireNonNull(id, "id cannot be null");
}
- public String getId()
- {
+ public String getId() {
return id;
}
@Override
- public boolean equals(Object o)
- {
- if ( this == o )
- {
+ public boolean equals(Object o) {
+ if (this == o) {
return true;
}
- if ( o == null || getClass() != o.getClass() )
- {
+ if (o == null || getClass() != o.getClass()) {
return false;
}
- PersonId personId = (PersonId)o;
+ PersonId personId = (PersonId) o;
return id.equals(personId.id);
}
@Override
- public int hashCode()
- {
+ public int hashCode() {
return id.hashCode();
}
@Override
- public String toString()
- {
+ public String toString() {
return "PersonId{" + "id='" + id + '\'' + '}';
}
}
diff --git a/curator-examples/src/main/java/modeled/PersonModel.java b/curator-examples/src/main/java/modeled/PersonModel.java
index 52be5d94..c3960412 100644
--- a/curator-examples/src/main/java/modeled/PersonModel.java
+++ b/curator-examples/src/main/java/modeled/PersonModel.java
@@ -21,21 +21,18 @@ package modeled;
import java.util.Objects;
-public class PersonModel
-{
+public class PersonModel {
private final PersonId id;
private final ContainerType containerType;
private final String firstName;
private final String lastName;
private final int age;
- public PersonModel()
- {
+ public PersonModel() {
this(new PersonId(), new ContainerType(), null, null, 0);
}
- public PersonModel(PersonId id, ContainerType containerType, String firstName, String lastName, int age)
- {
+ public PersonModel(PersonId id, ContainerType containerType, String firstName, String lastName, int age) {
this.id = Objects.requireNonNull(id, "id cannot be null");
this.containerType = Objects.requireNonNull(containerType, "containerType cannot be null");
this.firstName = Objects.requireNonNull(firstName, "firstName cannot be null");
@@ -43,68 +40,55 @@ public class PersonModel
this.age = age;
}
- public PersonId getId()
- {
+ public PersonId getId() {
return id;
}
- public ContainerType getContainerType()
- {
+ public ContainerType getContainerType() {
return containerType;
}
- public String getFirstName()
- {
+ public String getFirstName() {
return firstName;
}
- public String getLastName()
- {
+ public String getLastName() {
return lastName;
}
- public int getAge()
- {
+ public int getAge() {
return age;
}
@Override
- public boolean equals(Object o)
- {
- if ( this == o )
- {
+ public boolean equals(Object o) {
+ if (this == o) {
return true;
}
- if ( o == null || getClass() != o.getClass() )
- {
+ if (o == null || getClass() != o.getClass()) {
return false;
}
- PersonModel that = (PersonModel)o;
+ PersonModel that = (PersonModel) o;
- if ( age != that.age )
- {
+ if (age != that.age) {
return false;
}
- if ( !id.equals(that.id) )
- {
+ if (!id.equals(that.id)) {
return false;
}
- if ( !containerType.equals(that.containerType) )
- {
+ if (!containerType.equals(that.containerType)) {
return false;
}
//noinspection SimplifiableIfStatement
- if ( !firstName.equals(that.firstName) )
- {
+ if (!firstName.equals(that.firstName)) {
return false;
}
return lastName.equals(that.lastName);
}
@Override
- public int hashCode()
- {
+ public int hashCode() {
int result = id.hashCode();
result = 31 * result + containerType.hashCode();
result = 31 * result + firstName.hashCode();
@@ -114,8 +98,8 @@ public class PersonModel
}
@Override
- public String toString()
- {
- return "PersonModel{" + "id=" + id + ", containerType=" + containerType + ", firstName='" + firstName + '\'' + ", lastName='" + lastName + '\'' + ", age=" + age + '}';
+ public String toString() {
+ return "PersonModel{" + "id=" + id + ", containerType=" + containerType + ", firstName='" + firstName + '\''
+ + ", lastName='" + lastName + '\'' + ", age=" + age + '}';
}
}
diff --git a/curator-examples/src/main/java/modeled/PersonModelSpec.java b/curator-examples/src/main/java/modeled/PersonModelSpec.java
index 79286ebb..5251b279 100644
--- a/curator-examples/src/main/java/modeled/PersonModelSpec.java
+++ b/curator-examples/src/main/java/modeled/PersonModelSpec.java
@@ -25,13 +25,11 @@ import org.apache.curator.x.async.modeled.ModelSpec;
import org.apache.curator.x.async.modeled.ModeledFramework;
import org.apache.curator.x.async.modeled.ZPath;
-public class PersonModelSpec
-{
+public class PersonModelSpec {
private final AsyncCuratorFramework client;
private final ModelSpec<PersonModel> modelSpec;
- public PersonModelSpec(AsyncCuratorFramework client)
- {
+ public PersonModelSpec(AsyncCuratorFramework client) {
this.client = client;
JacksonModelSerializer<PersonModel> serializer = JacksonModelSerializer.build(PersonModel.class);
@@ -39,8 +37,7 @@ public class PersonModelSpec
modelSpec = ModelSpec.builder(path, serializer).build();
}
- public ModeledFramework<PersonModel> resolved(ContainerType containerType, PersonId personId)
- {
+ public ModeledFramework<PersonModel> resolved(ContainerType containerType, PersonId personId) {
ModelSpec<PersonModel> resolved = modelSpec.resolved(containerType.getTypeId(), personId.getId());
return ModeledFramework.wrap(client, resolved);
}
diff --git a/curator-examples/src/main/java/pubsub/Clients.java b/curator-examples/src/main/java/pubsub/Clients.java
index 82212bf1..c46b08c8 100644
--- a/curator-examples/src/main/java/pubsub/Clients.java
+++ b/curator-examples/src/main/java/pubsub/Clients.java
@@ -19,6 +19,7 @@
package pubsub;
+import java.util.concurrent.TimeUnit;
import org.apache.curator.x.async.modeled.JacksonModelSerializer;
import org.apache.curator.x.async.modeled.ModelSpec;
import org.apache.curator.x.async.modeled.ModelSpecBuilder;
@@ -32,46 +33,37 @@ import pubsub.models.Group;
import pubsub.models.Instance;
import pubsub.models.InstanceType;
import pubsub.models.Priority;
-import java.util.concurrent.TimeUnit;
-public class Clients
-{
+public class Clients {
/**
* A client template for LocationAvailable instances
*/
- public static final TypedModeledFramework2<LocationAvailable, Group, Priority> locationAvailableClient = TypedModeledFramework2.from(
- ModeledFramework.builder(),
- builder(LocationAvailable.class),
- "/root/pubsub/messages/locations/{group}/{priority}/{id}"
- );
+ public static final TypedModeledFramework2<LocationAvailable, Group, Priority> locationAvailableClient =
+ TypedModeledFramework2.from(
+ ModeledFramework.builder(),
+ builder(LocationAvailable.class),
+ "/root/pubsub/messages/locations/{group}/{priority}/{id}");
/**
* A client template for UserCreated instances
*/
- public static final TypedModeledFramework2<UserCreated, Group, Priority> userCreatedClient = TypedModeledFramework2.from(
- ModeledFramework.builder(),
- builder(UserCreated.class),
- "/root/pubsub/messages/users/{group}/{priority}/{id}"
- );
+ public static final TypedModeledFramework2<UserCreated, Group, Priority> userCreatedClient =
+ TypedModeledFramework2.from(
+ ModeledFramework.builder(),
+ builder(UserCreated.class),
+ "/root/pubsub/messages/users/{group}/{priority}/{id}");
/**
* A client template for Instance instances
*/
public static final TypedModeledFramework<Instance, InstanceType> instanceClient = TypedModeledFramework.from(
- ModeledFramework.builder(),
- builder(Instance.class),
- "/root/pubsub/instances/{instance-type}/{id}"
- );
+ ModeledFramework.builder(), builder(Instance.class), "/root/pubsub/instances/{instance-type}/{id}");
- private static <T> ModelSpecBuilder<T> builder(Class<T> clazz)
- {
+ private static <T> ModelSpecBuilder<T> builder(Class<T> clazz) {
return ModelSpec.builder(JacksonModelSerializer.build(clazz))
- .withTtl(TimeUnit.MINUTES.toMillis(10)) // for our pub-sub example, messages are valid for 10 minutes
- .withCreateMode(CreateMode.PERSISTENT_WITH_TTL)
- ;
+ .withTtl(TimeUnit.MINUTES.toMillis(10)) // for our pub-sub example, messages are valid for 10 minutes
+ .withCreateMode(CreateMode.PERSISTENT_WITH_TTL);
}
- private Clients()
- {
- }
+ private Clients() {}
}
diff --git a/curator-examples/src/main/java/pubsub/Publisher.java b/curator-examples/src/main/java/pubsub/Publisher.java
index 73267e7b..4c33322d 100644
--- a/curator-examples/src/main/java/pubsub/Publisher.java
+++ b/curator-examples/src/main/java/pubsub/Publisher.java
@@ -19,6 +19,9 @@
package pubsub;
+import java.util.List;
+import java.util.Objects;
+import java.util.stream.Collectors;
import org.apache.curator.framework.api.transaction.CuratorOp;
import org.apache.curator.x.async.AsyncCuratorFramework;
import org.apache.curator.x.async.modeled.ModeledFramework;
@@ -31,17 +34,12 @@ import pubsub.models.Group;
import pubsub.models.Instance;
import pubsub.models.Message;
import pubsub.models.Priority;
-import java.util.List;
-import java.util.Objects;
-import java.util.stream.Collectors;
-public class Publisher
-{
+public class Publisher {
private final Logger log = LoggerFactory.getLogger(getClass());
private final AsyncCuratorFramework client;
- public Publisher(AsyncCuratorFramework client)
- {
+ public Publisher(AsyncCuratorFramework client) {
this.client = Objects.requireNonNull(client, "client cannot be null");
}
@@ -50,8 +48,7 @@ public class Publisher
*
* @param instance instance to publish
*/
- public void publishInstance(Instance instance)
- {
+ public void publishInstance(Instance instance) {
ModeledFramework<Instance> resolvedClient = Clients.instanceClient.resolved(client, instance.getType());
resolvedClient.set(instance).exceptionally(e -> {
log.error("Could not publish instance: " + instance, e);
@@ -64,14 +61,12 @@ public class Publisher
*
* @param instances instances to publish
*/
- public void publishInstances(List<Instance> instances)
- {
+ public void publishInstances(List<Instance> instances) {
List<CuratorOp> operations = instances.stream()
- .map(instance -> Clients.instanceClient
- .resolved(client, instance.getType())
- .createOp(instance)
- )
- .collect(Collectors.toList());
+ .map(instance -> Clients.instanceClient
+ .resolved(client, instance.getType())
+ .createOp(instance))
+ .collect(Collectors.toList());
client.transaction().forOperations(operations).exceptionally(e -> {
log.error("Could not publish instances: " + instances, e);
return null;
@@ -84,8 +79,7 @@ public class Publisher
* @param group group
* @param locationAvailable message to publish
*/
- public void publishLocationAvailable(Group group, LocationAvailable locationAvailable)
- {
+ public void publishLocationAvailable(Group group, LocationAvailable locationAvailable) {
publishMessage(Clients.locationAvailableClient, group, locationAvailable);
}
@@ -95,8 +89,7 @@ public class Publisher
* @param group group
* @param userCreated message to publish
*/
- public void publishUserCreated(Group group, UserCreated userCreated)
- {
+ public void publishUserCreated(Group group, UserCreated userCreated) {
publishMessage(Clients.userCreatedClient, group, userCreated);
}
@@ -106,8 +99,7 @@ public class Publisher
* @param group group
* @param locationsAvailable messages to publish
*/
- public void publishLocationsAvailable(Group group, List<LocationAvailable> locationsAvailable)
- {
+ public void publishLocationsAvailable(Group group, List<LocationAvailable> locationsAvailable) {
publishMessages(Clients.locationAvailableClient, group, locationsAvailable);
}
@@ -117,13 +109,12 @@ public class Publisher
* @param group group
* @param usersCreated messages to publish
*/
- public void publishUsersCreated(Group group, List<UserCreated> usersCreated)
- {
+ public void publishUsersCreated(Group group, List<UserCreated> usersCreated) {
publishMessages(Clients.userCreatedClient, group, usersCreated);
}
- private <T extends Message> void publishMessage(TypedModeledFramework2<T, Group, Priority> typedClient, Group group, T message)
- {
+ private <T extends Message> void publishMessage(
+ TypedModeledFramework2<T, Group, Priority> typedClient, Group group, T message) {
ModeledFramework<T> resolvedClient = typedClient.resolved(client, group, message.getPriority());
resolvedClient.set(message).exceptionally(e -> {
log.error("Could not publish message: " + message, e);
@@ -131,14 +122,13 @@ public class Publisher
});
}
- private <T extends Message> void publishMessages(TypedModeledFramework2<T, Group, Priority> typedClient, Group group, List<T> messages)
- {
+ private <T extends Message> void publishMessages(
+ TypedModeledFramework2<T, Group, Priority> typedClient, Group group, List<T> messages) {
List<CuratorOp> operations = messages.stream()
- .map(message -> typedClient
- .resolved(client, group, message.getPriority())
- .createOp(message)
- )
- .collect(Collectors.toList());
+ .map(message -> typedClient
+ .resolved(client, group, message.getPriority())
+ .createOp(message))
+ .collect(Collectors.toList());
client.transaction().forOperations(operations).exceptionally(e -> {
log.error("Could not publish messages: " + messages, e);
return null;
diff --git a/curator-examples/src/main/java/pubsub/SubPubTest.java b/curator-examples/src/main/java/pubsub/SubPubTest.java
index 861059f8..727b76b2 100644
--- a/curator-examples/src/main/java/pubsub/SubPubTest.java
+++ b/curator-examples/src/main/java/pubsub/SubPubTest.java
@@ -19,18 +19,6 @@
package pubsub;
-import org.apache.curator.framework.CuratorFrameworkFactory;
-import org.apache.curator.retry.RetryOneTime;
-import org.apache.curator.test.TestingServer;
-import org.apache.curator.x.async.AsyncCuratorFramework;
-import org.apache.curator.x.async.modeled.cached.CachedModeledFramework;
-import org.apache.curator.x.async.modeled.cached.ModeledCacheListener;
-import pubsub.messages.LocationAvailable;
-import pubsub.messages.UserCreated;
-import pubsub.models.Group;
-import pubsub.models.Instance;
-import pubsub.models.InstanceType;
-import pubsub.models.Priority;
import java.io.Closeable;
import java.io.IOException;
import java.time.Duration;
@@ -44,9 +32,20 @@ import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
+import org.apache.curator.framework.CuratorFrameworkFactory;
+import org.apache.curator.retry.RetryOneTime;
+import org.apache.curator.test.TestingServer;
+import org.apache.curator.x.async.AsyncCuratorFramework;
+import org.apache.curator.x.async.modeled.cached.CachedModeledFramework;
+import org.apache.curator.x.async.modeled.cached.ModeledCacheListener;
+import pubsub.messages.LocationAvailable;
+import pubsub.messages.UserCreated;
+import pubsub.models.Group;
+import pubsub.models.Instance;
+import pubsub.models.InstanceType;
+import pubsub.models.Priority;
-public class SubPubTest implements Closeable
-{
+public class SubPubTest implements Closeable {
private final TestingServer testingServer;
private final AsyncCuratorFramework client;
private final ScheduledExecutorService executorService;
@@ -64,53 +63,44 @@ public class SubPubTest implements Closeable
private static final Duration[] durations = {Duration.ofSeconds(1), Duration.ofMinutes(1), Duration.ofHours(1)};
private static final String[] positions = {"worker", "manager", "executive"};
- public static void main(String[] args)
- {
- try ( SubPubTest subPubTest = new SubPubTest() )
- {
+ public static void main(String[] args) {
+ try (SubPubTest subPubTest = new SubPubTest()) {
subPubTest.start();
- TimeUnit.MINUTES.sleep(1); // run the test for a minute then exit
- }
- catch ( Exception e )
- {
+ TimeUnit.MINUTES.sleep(1); // run the test for a minute then exit
+ } catch (Exception e) {
e.printStackTrace();
}
}
- public SubPubTest() throws Exception
- {
+ public SubPubTest() throws Exception {
this.testingServer = new TestingServer();
- client = AsyncCuratorFramework.wrap(CuratorFrameworkFactory.newClient(testingServer.getConnectString(), new RetryOneTime(1)));
+ client = AsyncCuratorFramework.wrap(
+ CuratorFrameworkFactory.newClient(testingServer.getConnectString(), new RetryOneTime(1)));
executorService = Executors.newSingleThreadScheduledExecutor();
}
- public void start()
- {
+ public void start() {
client.unwrap().start();
Publisher publisher = new Publisher(client);
Subscriber subscriber = new Subscriber(client);
// start a subscriber/cache for Instances of each InstanceType
- instanceSubscribers.addAll(
- Arrays.stream(InstanceType.values())
- .map(subscriber::startInstanceSubscriber)
- .collect(Collectors.toList())
- );
+ instanceSubscribers.addAll(Arrays.stream(InstanceType.values())
+ .map(subscriber::startInstanceSubscriber)
+ .collect(Collectors.toList()));
// start a subscriber/cache for LocationAvailables of each combination of Group and Priority
- locationAvailableSubscribers.addAll(
- Arrays.stream(Priority.values())
- .flatMap(priority -> Arrays.stream(groups).map(group -> subscriber.startLocationAvailableSubscriber(group, priority)))
- .collect(Collectors.toList())
- );
+ locationAvailableSubscribers.addAll(Arrays.stream(Priority.values())
+ .flatMap(priority -> Arrays.stream(groups)
+ .map(group -> subscriber.startLocationAvailableSubscriber(group, priority)))
+ .collect(Collectors.toList()));
// start a subscriber/cache for UserCreateds of each combination of Group and Priority
- userCreatedSubscribers.addAll(
- Arrays.stream(Priority.values())
- .flatMap(priority -> Arrays.stream(groups).map(group -> subscriber.startUserCreatedSubscriber(group, priority)))
- .collect(Collectors.toList())
- );
+ userCreatedSubscribers.addAll(Arrays.stream(Priority.values())
+ .flatMap(priority ->
+ Arrays.stream(groups).map(group -> subscriber.startUserCreatedSubscriber(group, priority)))
+ .collect(Collectors.toList()));
// add listeners for each of the caches
instanceSubscribers.forEach(s -> s.listenable().addListener(generalListener()));
@@ -122,15 +112,11 @@ public class SubPubTest implements Closeable
}
@Override
- public void close() throws IOException
- {
+ public void close() throws IOException {
executorService.shutdownNow();
- try
- {
+ try {
executorService.awaitTermination(5, TimeUnit.SECONDS);
- }
- catch ( InterruptedException ignore )
- {
+ } catch (InterruptedException ignore) {
Thread.currentThread().interrupt();
}
@@ -141,60 +127,58 @@ public class SubPubTest implements Closeable
testingServer.close();
}
- private void publishSomething(Publisher publisher)
- {
+ private void publishSomething(Publisher publisher) {
// randomly do some publishing - either single items or lists of items in a transaction
- switch ( ThreadLocalRandom.current().nextInt(6) )
- {
- case 0:
- {
- Instance instance = new Instance(nextId(), random(InstanceType.values()), random(hostnames), random(ports));
+ switch (ThreadLocalRandom.current().nextInt(6)) {
+ case 0: {
+ Instance instance =
+ new Instance(nextId(), random(InstanceType.values()), random(hostnames), random(ports));
System.out.println("Publishing 1 instance");
publisher.publishInstance(instance);
break;
}
- case 1:
- {
- List<Instance> instances = IntStream.range(1, 10)
- .mapToObj(__ -> new Instance(nextId(), random(InstanceType.values()), random(hostnames), random(ports)))
- .collect(Collectors.toList());
+ case 1: {
+ List<Instance> instances = IntStream.range(1, 10)
+ .mapToObj(__ ->
+ new Instance(nextId(), random(InstanceType.values()), random(hostnames), random(ports)))
+ .collect(Collectors.toList());
System.out.println(String.format("Publishing %d instances", instances.size()));
publisher.publishInstances(instances);
break;
}
- case 2:
- {
- LocationAvailable locationAvailable = new LocationAvailable(nextId(), random(Priority.values()), random(locations), random(durations));
+ case 2: {
+ LocationAvailable locationAvailable = new LocationAvailable(
+ nextId(), random(Priority.values()), random(locations), random(durations));
System.out.println("Publishing 1 locationAvailable");
publisher.publishLocationAvailable(random(groups), locationAvailable);
break;
}
- case 3:
- {
- List<LocationAvailable> locationsAvailable = IntStream.range(1, 10)
- .mapToObj(__ -> new LocationAvailable(nextId(), random(Priority.values()), random(locations), random(durations)))
- .collect(Collectors.toList());
+ case 3: {
+ List<LocationAvailable> locationsAvailable = IntStream.range(1, 10)
+ .mapToObj(__ -> new LocationAvailable(
+ nextId(), random(Priority.values()), random(locations), random(durations)))
+ .collect(Collectors.toList());
System.out.println(String.format("Publishing %d locationsAvailable", locationsAvailable.size()));
publisher.publishLocationsAvailable(random(groups), locationsAvailable);
break;
}
- case 4:
- {
- UserCreated userCreated = new UserCreated(nextId(), random(Priority.values()), random(locations), random(positions));
+ case 4: {
+ UserCreated userCreated =
+ new UserCreated(nextId(), random(Priority.values()), random(locations), random(positions));
System.out.println("Publishing 1 userCreated");
publisher.publishUserCreated(random(groups), userCreated);
break;
}
- case 5:
- {
- List<UserCreated> usersCreated = IntStream.range(1, 10)
- .mapToObj(__ -> new UserCreated(nextId(), random(Priority.values()), random(locations), random(positions)))
- .collect(Collectors.toList());
+ case 5: {
+ List<UserCreated> usersCreated = IntStream.range(1, 10)
+ .mapToObj(__ -> new UserCreated(
+ nextId(), random(Priority.values()), random(locations), random(positions)))
+ .collect(Collectors.toList());
System.out.println(String.format("Publishing %d usersCreated", usersCreated.size()));
publisher.publishUsersCreated(random(groups), usersCreated);
break;
@@ -202,20 +186,18 @@ public class SubPubTest implements Closeable
}
}
- private <T> ModeledCacheListener<T> generalListener()
- {
- return (type, path, stat, model) -> System.out.println(String.format("Subscribed %s @ %s", model.getClass().getSimpleName(), path));
+ private <T> ModeledCacheListener<T> generalListener() {
+ return (type, path, stat, model) -> System.out.println(
+ String.format("Subscribed %s @ %s", model.getClass().getSimpleName(), path));
}
@SafeVarargs
- private final <T> T random(T... tab)
- {
+ private final <T> T random(T... tab) {
int index = ThreadLocalRandom.current().nextInt(tab.length);
return tab[index];
}
- private String nextId()
- {
+ private String nextId() {
return Long.toString(nextId.getAndIncrement());
}
}
diff --git a/curator-examples/src/main/java/pubsub/Subscriber.java b/curator-examples/src/main/java/pubsub/Subscriber.java
index ec2561a0..aa8d09fb 100644
--- a/curator-examples/src/main/java/pubsub/Subscriber.java
+++ b/curator-examples/src/main/java/pubsub/Subscriber.java
@@ -30,12 +30,10 @@ import pubsub.models.InstanceType;
import pubsub.models.Message;
import pubsub.models.Priority;
-public class Subscriber
-{
+public class Subscriber {
private final AsyncCuratorFramework client;
- public Subscriber(AsyncCuratorFramework client)
- {
+ public Subscriber(AsyncCuratorFramework client) {
this.client = client;
}
@@ -46,8 +44,7 @@ public class Subscriber
* @param priority priority to listen for
* @return CachedModeledFramework instance (already started)
*/
- public CachedModeledFramework<LocationAvailable> startLocationAvailableSubscriber(Group group, Priority priority)
- {
+ public CachedModeledFramework<LocationAvailable> startLocationAvailableSubscriber(Group group, Priority priority) {
return startSubscriber(Clients.locationAvailableClient, group, priority);
}
@@ -58,8 +55,7 @@ public class Subscriber
* @param priority priority to listen for
* @return CachedModeledFramework instance (already started)
*/
- public CachedModeledFramework<UserCreated> startUserCreatedSubscriber(Group group, Priority priority)
- {
+ public CachedModeledFramework<UserCreated> startUserCreatedSubscriber(Group group, Priority priority) {
return startSubscriber(Clients.userCreatedClient, group, priority);
}
@@ -69,16 +65,17 @@ public class Subscriber
* @param instanceType type to listen for
* @return CachedModeledFramework instance (already started)
*/
- public CachedModeledFramework<Instance> startInstanceSubscriber(InstanceType instanceType)
- {
- CachedModeledFramework<Instance> resolved = Clients.instanceClient.resolved(client, instanceType).cached();
+ public CachedModeledFramework<Instance> startInstanceSubscriber(InstanceType instanceType) {
+ CachedModeledFramework<Instance> resolved =
+ Clients.instanceClient.resolved(client, instanceType).cached();
resolved.start();
return resolved;
}
- private <T extends Message> CachedModeledFramework<T> startSubscriber(TypedModeledFramework2<T, Group, Priority> typedClient, Group group, Priority priority)
- {
- CachedModeledFramework<T> resolved = typedClient.resolved(client, group, priority).cached();
+ private <T extends Message> CachedModeledFramework<T> startSubscriber(
+ TypedModeledFramework2<T, Group, Priority> typedClient, Group group, Priority priority) {
+ CachedModeledFramework<T> resolved =
+ typedClient.resolved(client, group, priority).cached();
resolved.start();
return resolved;
}
diff --git a/curator-examples/src/main/java/pubsub/messages/LocationAvailable.java b/curator-examples/src/main/java/pubsub/messages/LocationAvailable.java
index d762373b..375a79a8 100644
--- a/curator-examples/src/main/java/pubsub/messages/LocationAvailable.java
+++ b/curator-examples/src/main/java/pubsub/messages/LocationAvailable.java
@@ -19,38 +19,34 @@
package pubsub.messages;
-import pubsub.models.Message;
-import pubsub.models.Priority;
import java.time.Duration;
import java.util.Objects;
+import pubsub.models.Message;
+import pubsub.models.Priority;
-public class LocationAvailable extends Message
-{
+public class LocationAvailable extends Message {
private final String name;
private final Duration availableUntil;
- public LocationAvailable()
- {
+ public LocationAvailable() {
this(Priority.low, "", Duration.ZERO);
}
- public LocationAvailable(Priority priority, String name, Duration availableUntil)
- {
+ public LocationAvailable(Priority priority, String name, Duration availableUntil) {
super(priority);
this.name = Objects.requireNonNull(name, "name cannot be null");
this.availableUntil = Objects.requireNonNull(availableUntil, "availableUntil cannot be null");
}
- public LocationAvailable(String id, Priority priority, String name, Duration availableUntil)
- {
+ public LocationAvailable(String id, Priority priority, String name, Duration availableUntil) {
super(id, priority);
this.name = Objects.requireNonNull(name, "name cannot be null");
this.availableUntil = Objects.requireNonNull(availableUntil, "availableUntil cannot be null");
}
@Override
- public String toString()
- {
- return "LocationAvailable{" + "name='" + name + '\'' + ", availableUntil=" + availableUntil + "} " + super.toString();
+ public String toString() {
+ return "LocationAvailable{" + "name='" + name + '\'' + ", availableUntil=" + availableUntil + "} "
+ + super.toString();
}
}
diff --git a/curator-examples/src/main/java/pubsub/messages/UserCreated.java b/curator-examples/src/main/java/pubsub/messages/UserCreated.java
index 90fcb21f..aa790987 100644
--- a/curator-examples/src/main/java/pubsub/messages/UserCreated.java
+++ b/curator-examples/src/main/java/pubsub/messages/UserCreated.java
@@ -19,47 +19,40 @@
package pubsub.messages;
+import java.util.Objects;
import pubsub.models.Message;
import pubsub.models.Priority;
-import java.util.Objects;
-public class UserCreated extends Message
-{
+public class UserCreated extends Message {
private final String name;
private final String position;
- public UserCreated()
- {
- this(Priority.low, "","");
+ public UserCreated() {
+ this(Priority.low, "", "");
}
- public UserCreated(Priority priority, String name, String position)
- {
+ public UserCreated(Priority priority, String name, String position) {
super(priority);
this.name = Objects.requireNonNull(name, "name cannot be null");
this.position = Objects.requireNonNull(position, "position cannot be null");
}
- public UserCreated(String id, Priority priority, String name, String position)
- {
+ public UserCreated(String id, Priority priority, String name, String position) {
super(id, priority);
this.name = Objects.requireNonNull(name, "name cannot be null");
this.position = Objects.requireNonNull(position, "position cannot be null");
}
- public String getName()
- {
+ public String getName() {
return name;
}
- public String getPosition()
- {
+ public String getPosition() {
return position;
}
@Override
- public String toString()
- {
+ public String toString() {
return "UserCreated{" + "name='" + name + '\'' + ", position='" + position + '\'' + "} " + super.toString();
}
}
diff --git a/curator-examples/src/main/java/pubsub/models/Group.java b/curator-examples/src/main/java/pubsub/models/Group.java
index 0baa6171..1436b1df 100644
--- a/curator-examples/src/main/java/pubsub/models/Group.java
+++ b/curator-examples/src/main/java/pubsub/models/Group.java
@@ -21,28 +21,23 @@ package pubsub.models;
import org.apache.curator.x.async.modeled.NodeName;
-public class Group implements NodeName
-{
+public class Group implements NodeName {
private final String groupName;
- public Group()
- {
+ public Group() {
this("");
}
- public Group(String groupName)
- {
+ public Group(String groupName) {
this.groupName = groupName;
}
- public String getGroupName()
- {
+ public String getGroupName() {
return groupName;
}
@Override
- public String nodeName()
- {
+ public String nodeName() {
return groupName;
}
}
diff --git a/curator-examples/src/main/java/pubsub/models/Instance.java b/curator-examples/src/main/java/pubsub/models/Instance.java
index 68180f9d..77195bff 100644
--- a/curator-examples/src/main/java/pubsub/models/Instance.java
+++ b/curator-examples/src/main/java/pubsub/models/Instance.java
@@ -19,59 +19,51 @@
package pubsub.models;
-import org.apache.curator.x.async.modeled.NodeName;
import java.util.Objects;
import java.util.UUID;
+import org.apache.curator.x.async.modeled.NodeName;
-public class Instance implements NodeName
-{
+public class Instance implements NodeName {
private final String id;
private final InstanceType type;
private final String hostname;
private final int port;
- public Instance()
- {
+ public Instance() {
this(UUID.randomUUID().toString(), InstanceType.proxy, "", 0);
}
- public Instance(String id, InstanceType type, String hostname, int port)
- {
+ public Instance(String id, InstanceType type, String hostname, int port) {
this.id = Objects.requireNonNull(id, "id cannot be null");
this.type = Objects.requireNonNull(type, "type cannot be null");
this.hostname = Objects.requireNonNull(hostname, "hostname cannot be null");
this.port = port;
}
- public String getId()
- {
+ public String getId() {
return id;
}
- public InstanceType getType()
- {
+ public InstanceType getType() {
return type;
}
- public String getHostname()
- {
+ public String getHostname() {
return hostname;
}
- public int getPort()
- {
+ public int getPort() {
return port;
}
@Override
- public String nodeName()
- {
+ public String nodeName() {
return id;
}
@Override
- public String toString()
- {
- return "Instance{" + "id='" + id + '\'' + ", type=" + type + ", hostname='" + hostname + '\'' + ", port=" + port + '}';
+ public String toString() {
+ return "Instance{" + "id='" + id + '\'' + ", type=" + type + ", hostname='" + hostname + '\'' + ", port=" + port
+ + '}';
}
}
diff --git a/curator-examples/src/main/java/pubsub/models/InstanceType.java b/curator-examples/src/main/java/pubsub/models/InstanceType.java
index 1253779e..a590205a 100644
--- a/curator-examples/src/main/java/pubsub/models/InstanceType.java
+++ b/curator-examples/src/main/java/pubsub/models/InstanceType.java
@@ -19,8 +19,7 @@
package pubsub.models;
-public enum InstanceType
-{
+public enum InstanceType {
database,
cache,
web,
diff --git a/curator-examples/src/main/java/pubsub/models/Message.java b/curator-examples/src/main/java/pubsub/models/Message.java
index 81e36250..340aced9 100644
--- a/curator-examples/src/main/java/pubsub/models/Message.java
+++ b/curator-examples/src/main/java/pubsub/models/Message.java
@@ -19,50 +19,42 @@
package pubsub.models;
-import org.apache.curator.x.async.modeled.NodeName;
import java.util.Objects;
import java.util.UUID;
+import org.apache.curator.x.async.modeled.NodeName;
-public abstract class Message implements NodeName
-{
+public abstract class Message implements NodeName {
private final String id;
private final Priority priority;
- protected Message()
- {
+ protected Message() {
this(UUID.randomUUID().toString(), Priority.low);
}
- protected Message(Priority priority)
- {
+ protected Message(Priority priority) {
this(UUID.randomUUID().toString(), priority);
}
- protected Message(String id, Priority priority)
- {
+ protected Message(String id, Priority priority) {
this.id = Objects.requireNonNull(id, "id cannot be null");
this.priority = Objects.requireNonNull(priority, "messageType cannot be null");
}
- public String getId()
- {
+ public String getId() {
return id;
}
- public Priority getPriority()
- {
+ public Priority getPriority() {
return priority;
}
@Override
- public String nodeName()
- {
+ public String nodeName() {
return id;
}
@Override
- public String toString()
- {
+ public String toString() {
return "Message{" + "id='" + id + '\'' + ", priority=" + priority + '}';
}
}
diff --git a/curator-examples/src/main/java/pubsub/models/Priority.java b/curator-examples/src/main/java/pubsub/models/Priority.java
index c0448306..ca026e56 100644
--- a/curator-examples/src/main/java/pubsub/models/Priority.java
+++ b/curator-examples/src/main/java/pubsub/models/Priority.java
@@ -19,8 +19,7 @@
package pubsub.models;
-public enum Priority
-{
+public enum Priority {
low,
medium,
high
diff --git a/curator-framework/src/main/java/org/apache/curator/framework/AuthInfo.java b/curator-framework/src/main/java/org/apache/curator/framework/AuthInfo.java
index 7a7a564f..7279a0c9 100644
--- a/curator-framework/src/main/java/org/apache/curator/framework/AuthInfo.java
+++ b/curator-framework/src/main/java/org/apache/curator/framework/AuthInfo.java
@@ -21,13 +21,11 @@ package org.apache.curator.framework;
import java.util.Arrays;
-public class AuthInfo
-{
- final String scheme;
- final byte[] auth;
+public class AuthInfo {
+ final String scheme;
+ final byte[] auth;
- public AuthInfo(String scheme, byte[] auth)
- {
+ public AuthInfo(String scheme, byte[] auth) {
this.scheme = scheme;
this.auth = auth;
}
@@ -41,11 +39,7 @@ public class AuthInfo
}
@Override
- public String toString()
- {
- return "AuthInfo{" +
- "scheme='" + scheme + '\'' +
- ", auth=" + Arrays.toString(auth) +
- '}';
+ public String toString() {
+ return "AuthInfo{" + "scheme='" + scheme + '\'' + ", auth=" + Arrays.toString(auth) + '}';
}
}
diff --git a/curator-framework/src/main/java/org/apache/curator/framework/CuratorFramework.java b/curator-framework/src/main/java/org/apache/curator/framework/CuratorFramework.java
index bbcd3cfc..25b701ca 100644
--- a/curator-framework/src/main/java/org/apache/curator/framework/CuratorFramework.java
+++ b/curator-framework/src/main/java/org/apache/curator/framework/CuratorFramework.java
@@ -19,6 +19,9 @@
package org.apache.curator.framework;
+import java.io.Closeable;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.TimeUnit;
import org.apache.curator.CuratorZookeeperClient;
import org.apache.curator.framework.api.*;
import org.apache.curator.framework.api.transaction.CuratorMultiTransaction;
@@ -33,15 +36,11 @@ import org.apache.curator.framework.state.ConnectionStateListener;
import org.apache.curator.utils.EnsurePath;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.server.quorum.flexible.QuorumVerifier;
-import java.io.Closeable;
-import java.util.concurrent.CompletableFuture;
-import java.util.concurrent.TimeUnit;
/**
* Zookeeper framework-style client
*/
-public interface CuratorFramework extends Closeable
-{
+public interface CuratorFramework extends Closeable {
/**
* Start the client. Most mutator methods will not work until the client is started
*/
@@ -346,10 +345,9 @@ public interface CuratorFramework extends Closeable
* @return a CompletableFuture that can be used to monitor when the call is complete
* @since 4.1.0
*/
- default CompletableFuture<Void> postSafeNotify(Object monitorHolder)
- {
+ default CompletableFuture<Void> postSafeNotify(Object monitorHolder) {
return runSafe(() -> {
- synchronized(monitorHolder) {
+ synchronized (monitorHolder) {
monitorHolder.notifyAll();
}
});
@@ -358,7 +356,7 @@ public interface CuratorFramework extends Closeable
/**
* Curator (and user) recipes can use this to run notifyAll
* and other blocking calls that might normally block ZooKeeper's event thread.
-
+ *
* @param runnable proc to call from a safe internal thread
* @return a CompletableFuture that can be used to monitor when the call is complete
* @since 4.1.0
diff --git a/curator-framework/src/main/java/org/apache/curator/framework/CuratorFrameworkFactory.java b/curator-framework/src/main/java/org/apache/curator/framework/CuratorFrameworkFactory.java
index 54ace509..59ffb428 100644
--- a/curator-framework/src/main/java/org/apache/curator/framework/CuratorFrameworkFactory.java
+++ b/curator-framework/src/main/java/org/apache/curator/framework/CuratorFrameworkFactory.java
@@ -19,6 +19,8 @@
package org.apache.curator.framework;
+import com.google.common.base.Preconditions;
+import com.google.common.collect.ImmutableList;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Arrays;
@@ -27,7 +29,6 @@ import java.util.Objects;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
-
import org.apache.curator.CuratorZookeeperClient;
import org.apache.curator.RetryPolicy;
import org.apache.curator.ensemble.EnsembleProvider;
@@ -51,24 +52,22 @@ import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.client.ZKClientConfig;
-import com.google.common.base.Preconditions;
-import com.google.common.collect.ImmutableList;
-
/**
* Factory methods for creating framework-style clients
*/
-public class CuratorFrameworkFactory
-{
- private static final int DEFAULT_SESSION_TIMEOUT_MS = Integer.getInteger("curator-default-session-timeout", 60 * 1000);
- private static final int DEFAULT_CONNECTION_TIMEOUT_MS = Integer.getInteger("curator-default-connection-timeout", 15 * 1000);
+public class CuratorFrameworkFactory {
+ private static final int DEFAULT_SESSION_TIMEOUT_MS =
+ Integer.getInteger("curator-default-session-timeout", 60 * 1000);
+ private static final int DEFAULT_CONNECTION_TIMEOUT_MS =
+ Integer.getInteger("curator-default-connection-timeout", 15 * 1000);
private static final byte[] LOCAL_ADDRESS = getLocalAddress();
private static final CompressionProvider DEFAULT_COMPRESSION_PROVIDER = new GzipCompressionProvider();
private static final DefaultZookeeperFactory DEFAULT_ZOOKEEPER_FACTORY = new DefaultZookeeperFactory();
private static final DefaultACLProvider DEFAULT_ACL_PROVIDER = new DefaultACLProvider();
- private static final long DEFAULT_INACTIVE_THRESHOLD_MS = (int)TimeUnit.MINUTES.toMillis(3);
- private static final int DEFAULT_CLOSE_WAIT_MS = (int)TimeUnit.SECONDS.toMillis(1);
+ private static final long DEFAULT_INACTIVE_THRESHOLD_MS = (int) TimeUnit.MINUTES.toMillis(3);
+ private static final int DEFAULT_CLOSE_WAIT_MS = (int) TimeUnit.SECONDS.toMillis(1);
private static final boolean DEFAULT_WITH_ENSEMBLE_TRACKER = true;
/**
@@ -76,8 +75,7 @@ public class CuratorFrameworkFactory
*
* @return new builder
*/
- public static Builder builder()
- {
+ public static Builder builder() {
return new Builder();
}
@@ -88,8 +86,7 @@ public class CuratorFrameworkFactory
* @param retryPolicy retry policy to use
* @return client
*/
- public static CuratorFramework newClient(String connectString, RetryPolicy retryPolicy)
- {
+ public static CuratorFramework newClient(String connectString, RetryPolicy retryPolicy) {
return newClient(connectString, DEFAULT_SESSION_TIMEOUT_MS, DEFAULT_CONNECTION_TIMEOUT_MS, retryPolicy);
}
@@ -102,16 +99,16 @@ public class CuratorFrameworkFactory
* @param retryPolicy retry policy to use
* @return client
*/
- public static CuratorFramework newClient(String connectString, int sessionTimeoutMs, int connectionTimeoutMs, RetryPolicy retryPolicy)
- {
- return builder().
- connectString(connectString).
- sessionTimeoutMs(sessionTimeoutMs).
- connectionTimeoutMs(connectionTimeoutMs).
- retryPolicy(retryPolicy).
- build();
+ public static CuratorFramework newClient(
+ String connectString, int sessionTimeoutMs, int connectionTimeoutMs, RetryPolicy retryPolicy) {
+ return builder()
+ .connectString(connectString)
+ .sessionTimeoutMs(sessionTimeoutMs)
+ .connectionTimeoutMs(connectionTimeoutMs)
+ .retryPolicy(retryPolicy)
+ .build();
}
-
+
/**
* Create a new client
*
@@ -121,18 +118,22 @@ public class CuratorFrameworkFactory
* @param retryPolicy retry policy to use
* @param zkClientConfig ZKClientConfig
* @return client
- *
+ *
* @since 5.1.1, supported from ZooKeeper 3.6.1 and above.
*/
- public static CuratorFramework newClient(String connectString, int sessionTimeoutMs, int connectionTimeoutMs, RetryPolicy retryPolicy, ZKClientConfig zkClientConfig)
- {
- return builder().
- connectString(connectString).
- sessionTimeoutMs(sessionTimeoutMs).
- connectionTimeoutMs(connectionTimeoutMs).
- retryPolicy(retryPolicy).
- zkClientConfig(zkClientConfig).
- build();
+ public static CuratorFramework newClient(
+ String connectString,
+ int sessionTimeoutMs,
+ int connectionTimeoutMs,
+ RetryPolicy retryPolicy,
+ ZKClientConfig zkClientConfig) {
+ return builder()
+ .connectString(connectString)
+ .sessionTimeoutMs(sessionTimeoutMs)
+ .connectionTimeoutMs(connectionTimeoutMs)
+ .retryPolicy(retryPolicy)
+ .zkClientConfig(zkClientConfig)
+ .build();
}
/**
@@ -140,21 +141,16 @@ public class CuratorFrameworkFactory
*
* @return local address bytes
*/
- public static byte[] getLocalAddress()
- {
- try
- {
+ public static byte[] getLocalAddress() {
+ try {
return InetAddress.getLocalHost().getHostAddress().getBytes();
- }
- catch ( UnknownHostException ignore )
- {
+ } catch (UnknownHostException ignore) {
// ignore
}
return new byte[0];
}
- public static class Builder
- {
+ public static class Builder {
private EnsembleProvider ensembleProvider;
private boolean withEnsembleTracker = DEFAULT_WITH_ENSEMBLE_TRACKER;
private int sessionTimeoutMs = DEFAULT_SESSION_TIMEOUT_MS;
@@ -174,7 +170,8 @@ public class CuratorFrameworkFactory
private SchemaSet schemaSet = SchemaSet.getDefaultSchemaSet();
private int waitForShutdownTimeoutMs = 0;
private Executor runSafeService = null;
- private ConnectionStateListenerManagerFactory connectionStateListenerManagerFactory = ConnectionStateListenerManagerFactory.standard;
+ private ConnectionStateListenerManagerFactory connectionStateListenerManagerFactory =
+ ConnectionStateListenerManagerFactory.standard;
private int simulatedSessionExpirationPercent = 100;
private ZKClientConfig zkClientConfig;
@@ -183,8 +180,7 @@ public class CuratorFrameworkFactory
*
* @return new CuratorFramework
*/
- public CuratorFramework build()
- {
+ public CuratorFramework build() {
return new CuratorFrameworkImpl(this);
}
@@ -196,8 +192,7 @@ public class CuratorFrameworkFactory
*
* @return temp instance
*/
- public CuratorTempFramework buildTemp()
- {
+ public CuratorTempFramework buildTemp() {
return buildTemp(DEFAULT_INACTIVE_THRESHOLD_MS, TimeUnit.MILLISECONDS);
}
@@ -211,8 +206,7 @@ public class CuratorFrameworkFactory
* @param unit threshold unit
* @return temp instance
*/
- public CuratorTempFramework buildTemp(long inactiveThreshold, TimeUnit unit)
- {
+ public CuratorTempFramework buildTemp(long inactiveThreshold, TimeUnit unit) {
return new CuratorTempFrameworkImpl(this, unit.toMillis(inactiveThreshold));
}
@@ -225,9 +219,9 @@ public class CuratorFrameworkFactory
* @param auth the auth bytes
* @return this
*/
- public Builder authorization(String scheme, byte[] auth)
- {
- return authorization(ImmutableList.of(new AuthInfo(scheme, (auth != null) ? Arrays.copyOf(auth, auth.length) : null)));
+ public Builder authorization(String scheme, byte[] auth) {
+ return authorization(
+ ImmutableList.of(new AuthInfo(scheme, (auth != null) ? Arrays.copyOf(auth, auth.length) : null)));
}
/**
@@ -239,8 +233,7 @@ public class CuratorFrameworkFactory
* @param authInfos list of {@link AuthInfo} objects with scheme and auth
* @return this
*/
- public Builder authorization(List<AuthInfo> authInfos)
- {
+ public Builder authorization(List<AuthInfo> authInfos) {
this.authInfos = ImmutableList.copyOf(authInfos);
return this;
}
@@ -252,8 +245,7 @@ public class CuratorFrameworkFactory
* @param connectString list of servers to connect to
* @return this
*/
- public Builder connectString(String connectString)
- {
+ public Builder connectString(String connectString) {
ensembleProvider = new FixedEnsembleProvider(connectString);
return this;
}
@@ -265,8 +257,7 @@ public class CuratorFrameworkFactory
* @param ensembleProvider the ensemble provider to use
* @return this
*/
- public Builder ensembleProvider(EnsembleProvider ensembleProvider)
- {
+ public Builder ensembleProvider(EnsembleProvider ensembleProvider) {
this.ensembleProvider = ensembleProvider;
return this;
}
@@ -274,11 +265,11 @@ public class CuratorFrameworkFactory
/**
* Allows to configure if the ensemble configuration changes will be watched.
* The default value is {@code true}.<br>
- *
+ *
* IMPORTANT: Use this method in combination with {@link #ensembleProvider(EnsembleProvider)} to provide
* an instance that returns {@code false} on {@link EnsembleProvider#updateServerListEnabled()} in order
* to fully achieve that ensemble server list changes are ignored<br>
- *
+ *
* @param withEnsembleTracker use {@code false} if you want to avoid following ensemble configuration changes
* @return this
*/
@@ -302,8 +293,7 @@ public class CuratorFrameworkFactory
* @param defaultData new default data to use
* @return this
*/
- public Builder defaultData(byte[] defaultData)
- {
+ public Builder defaultData(byte[] defaultData) {
this.defaultData = (defaultData != null) ? Arrays.copyOf(defaultData, defaultData.length) : null;
return this;
}
@@ -316,8 +306,7 @@ public class CuratorFrameworkFactory
* @param namespace the namespace
* @return this
*/
- public Builder namespace(String namespace)
- {
+ public Builder namespace(String namespace) {
this.namespace = namespace;
return this;
}
@@ -326,8 +315,7 @@ public class CuratorFrameworkFactory
* @param sessionTimeoutMs session timeout
* @return this
*/
- public Builder sessionTimeoutMs(int sessionTimeoutMs)
- {
+ public Builder sessionTimeoutMs(int sessionTimeoutMs) {
this.sessionTimeoutMs = sessionTimeoutMs;
return this;
}
@@ -336,8 +324,7 @@ public class CuratorFrameworkFactory
* @param connectionTimeoutMs connection timeout
* @return this
*/
- public Builder connectionTimeoutMs(int connectionTimeoutMs)
- {
+ public Builder connectionTimeoutMs(int connectionTimeoutMs) {
this.connectionTimeoutMs = connectionTimeoutMs;
return this;
}
@@ -346,8 +333,7 @@ public class CuratorFrameworkFactory
* @param maxCloseWaitMs time to wait during close to join background threads
* @return this
*/
- public Builder maxCloseWaitMs(int maxCloseWaitMs)
- {
+ public Builder maxCloseWaitMs(int maxCloseWaitMs) {
this.maxCloseWaitMs = maxCloseWaitMs;
return this;
}
@@ -356,8 +342,7 @@ public class CuratorFrameworkFactory
* @param retryPolicy retry policy to use
* @return this
*/
- public Builder retryPolicy(RetryPolicy retryPolicy)
- {
+ public Builder retryPolicy(RetryPolicy retryPolicy) {
this.retryPolicy = retryPolicy;
return this;
}
@@ -366,8 +351,7 @@ public class CuratorFrameworkFactory
* @param threadFactory thread factory used to create Executor Services
* @return this
*/
- public Builder threadFactory(ThreadFactory threadFactory)
- {
+ public Builder threadFactory(ThreadFactory threadFactory) {
this.threadFactory = threadFactory;
return this;
}
@@ -376,8 +360,7 @@ public class CuratorFrameworkFactory
* @param compressionProvider the compression provider
* @return this
*/
- public Builder compressionProvider(CompressionProvider compressionProvider)
- {
+ public Builder compressionProvider(CompressionProvider compressionProvider) {
this.compressionProvider = compressionProvider;
return this;
}
@@ -386,8 +369,7 @@ public class CuratorFrameworkFactory
* @param zookeeperFactory the zookeeper factory to use
* @return this
*/
- public Builder zookeeperFactory(ZookeeperFactory zookeeperFactory)
- {
+ public Builder zookeeperFactory(ZookeeperFactory zookeeperFactory) {
this.zookeeperFactory = zookeeperFactory;
return this;
}
@@ -396,8 +378,7 @@ public class CuratorFrameworkFactory
* @param aclProvider a provider for ACLs
* @return this
*/
- public Builder aclProvider(ACLProvider aclProvider)
- {
+ public Builder aclProvider(ACLProvider aclProvider) {
this.aclProvider = aclProvider;
return this;
}
@@ -409,8 +390,7 @@ public class CuratorFrameworkFactory
* for details
* @return this
*/
- public Builder canBeReadOnly(boolean canBeReadOnly)
- {
+ public Builder canBeReadOnly(boolean canBeReadOnly) {
this.canBeReadOnly = canBeReadOnly;
return this;
}
@@ -421,8 +401,7 @@ public class CuratorFrameworkFactory
*
* @return this
*/
- public Builder dontUseContainerParents()
- {
+ public Builder dontUseContainerParents() {
this.useContainerParentsIfAvailable = false;
return this;
}
@@ -434,8 +413,7 @@ public class CuratorFrameworkFactory
* @param connectionStateErrorPolicy new error policy
* @return this
*/
- public Builder connectionStateErrorPolicy(ConnectionStateErrorPolicy connectionStateErrorPolicy)
- {
+ public Builder connectionStateErrorPolicy(ConnectionStateErrorPolicy connectionStateErrorPolicy) {
this.connectionStateErrorPolicy = connectionStateErrorPolicy;
return this;
}
@@ -448,8 +426,7 @@ public class CuratorFrameworkFactory
* @param waitForShutdownTimeoutMs default timeout
* @return this
*/
- public Builder waitForShutdownTimeoutMs(int waitForShutdownTimeoutMs)
- {
+ public Builder waitForShutdownTimeoutMs(int waitForShutdownTimeoutMs) {
this.waitForShutdownTimeoutMs = waitForShutdownTimeoutMs;
return this;
}
@@ -493,10 +470,10 @@ public class CuratorFrameworkFactory
this.simulatedSessionExpirationPercent = simulatedSessionExpirationPercent;
return this;
}
-
+
public Builder zkClientConfig(ZKClientConfig zkClientConfig) {
- this.zkClientConfig = zkClientConfig;
- return this;
+ this.zkClientConfig = zkClientConfig;
+ return this;
}
/**
@@ -506,8 +483,7 @@ public class CuratorFrameworkFactory
* @return this
* @since 3.2.0
*/
- public Builder schemaSet(SchemaSet schemaSet)
- {
+ public Builder schemaSet(SchemaSet schemaSet) {
this.schemaSet = schemaSet;
return this;
}
@@ -523,8 +499,7 @@ public class CuratorFrameworkFactory
* @return this
* @since 4.1.0
*/
- public Builder runSafeService(Executor runSafeService)
- {
+ public Builder runSafeService(Executor runSafeService) {
this.runSafeService = runSafeService;
return this;
}
@@ -537,168 +512,136 @@ public class CuratorFrameworkFactory
* @return this
* @since 4.2.0
*/
- public Builder connectionStateListenerManagerFactory(ConnectionStateListenerManagerFactory connectionStateListenerManagerFactory)
- {
- this.connectionStateListenerManagerFactory = Objects.requireNonNull(connectionStateListenerManagerFactory, "connectionStateListenerManagerFactory cannot be null");
+ public Builder connectionStateListenerManagerFactory(
+ ConnectionStateListenerManagerFactory connectionStateListenerManagerFactory) {
+ this.connectionStateListenerManagerFactory = Objects.requireNonNull(
+ connectionStateListenerManagerFactory, "connectionStateListenerManagerFactory cannot be null");
return this;
}
- public Executor getRunSafeService()
- {
+ public Executor getRunSafeService() {
return runSafeService;
}
- public ACLProvider getAclProvider()
- {
+ public ACLProvider getAclProvider() {
return aclProvider;
}
- public ZookeeperFactory getZookeeperFactory()
- {
+ public ZookeeperFactory getZookeeperFactory() {
return zookeeperFactory;
}
- public CompressionProvider getCompressionProvider()
- {
+ public CompressionProvider getCompressionProvider() {
return compressionProvider;
}
- public ThreadFactory getThreadFactory()
- {
+ public ThreadFactory getThreadFactory() {
return threadFactory;
}
- public EnsembleProvider getEnsembleProvider()
- {
+ public EnsembleProvider getEnsembleProvider() {
return ensembleProvider;
}
- public int getSessionTimeoutMs()
- {
+ public int getSessionTimeoutMs() {
return sessionTimeoutMs;
}
- public int getConnectionTimeoutMs()
- {
+ public int getConnectionTimeoutMs() {
return connectionTimeoutMs;
}
- public int getWaitForShutdownTimeoutMs()
- {
+ public int getWaitForShutdownTimeoutMs() {
return waitForShutdownTimeoutMs;
}
- public int getMaxCloseWaitMs()
- {
+ public int getMaxCloseWaitMs() {
return maxCloseWaitMs;
}
- public RetryPolicy getRetryPolicy()
- {
+ public RetryPolicy getRetryPolicy() {
return retryPolicy;
}
- public String getNamespace()
- {
+ public String getNamespace() {
return namespace;
}
- public boolean useContainerParentsIfAvailable()
- {
+ public boolean useContainerParentsIfAvailable() {
return useContainerParentsIfAvailable;
}
- public ConnectionStateErrorPolicy getConnectionStateErrorPolicy()
- {
+ public ConnectionStateErrorPolicy getConnectionStateErrorPolicy() {
return connectionStateErrorPolicy;
}
public int getSimulatedSessionExpirationPercent() {
return simulatedSessionExpirationPercent;
}
-
+
public ZKClientConfig getZkClientConfig() {
return zkClientConfig;
}
- public SchemaSet getSchemaSet()
- {
+ public SchemaSet getSchemaSet() {
return schemaSet;
}
@Deprecated
- public String getAuthScheme()
- {
+ public String getAuthScheme() {
int qty = (authInfos != null) ? authInfos.size() : 0;
- switch ( qty )
- {
- case 0:
- {
+ switch (qty) {
+ case 0: {
return null;
}
- case 1:
- {
+ case 1: {
return authInfos.get(0).scheme;
}
- default:
- {
+ default: {
throw new IllegalStateException("More than 1 auth has been added");
}
}
}
@Deprecated
- public byte[] getAuthValue()
- {
+ public byte[] getAuthValue() {
int qty = (authInfos != null) ? authInfos.size() : 0;
- switch ( qty )
- {
- case 0:
- {
+ switch (qty) {
+ case 0: {
return null;
}
- case 1:
- {
+ case 1: {
byte[] bytes = authInfos.get(0).getAuth();
return (bytes != null) ? Arrays.copyOf(bytes, bytes.length) : null;
}
- default:
- {
+ default: {
throw new IllegalStateException("More than 1 auth has been added");
}
}
}
- public List<AuthInfo> getAuthInfos()
- {
+ public List<AuthInfo> getAuthInfos() {
return authInfos;
}
- public byte[] getDefaultData()
- {
+ public byte[] getDefaultData() {
return defaultData;
}
- public boolean canBeReadOnly()
- {
+ public boolean canBeReadOnly() {
return canBeReadOnly;
}
- public ConnectionStateListenerManagerFactory getConnectionStateListenerManagerFactory()
- {
+ public ConnectionStateListenerManagerFactory getConnectionStateListenerManagerFactory() {
return connectionStateListenerManagerFactory;
}
- private Builder()
- {
- }
+ private Builder() {}
}
- private CuratorFrameworkFactory()
- {
- }
+ private CuratorFrameworkFactory() {}
}
diff --git a/curator-framework/src/main/java/org/apache/curator/framework/CuratorTempFramework.java b/curator-framework/src/main/java/org/apache/curator/framework/CuratorTempFramework.java
index b4af0e3a..72bc0ce8 100644
--- a/curator-framework/src/main/java/org/apache/curator/framework/CuratorTempFramework.java
+++ b/curator-framework/src/main/java/org/apache/curator/framework/CuratorTempFramework.java
@@ -19,9 +19,9 @@
package org.apache.curator.framework;
+import java.io.Closeable;
import org.apache.curator.framework.api.TempGetDataBuilder;
import org.apache.curator.framework.api.transaction.CuratorTransaction;
-import java.io.Closeable;
/**
* <p>
@@ -35,12 +35,11 @@ import java.io.Closeable;
* <a href="http://whilefalse.blogspot.com/2012/12/building-global-highly-available.html">http://whilefalse.blogspot.com/2012/12/building-global-highly-available.html</a>
* </p>
*/
-public interface CuratorTempFramework extends Closeable
-{
+public interface CuratorTempFramework extends Closeable {
/**
* Stop the client
*/
- public void close();
+ public void close();
/**
* Start a transaction builder
diff --git a/curator-framework/src/main/java/org/apache/curator/framework/EnsureContainers.java b/curator-framework/src/main/java/org/apache/curator/framework/EnsureContainers.java
index f3637ac8..5d07982b 100644
--- a/curator-framework/src/main/java/org/apache/curator/framework/EnsureContainers.java
+++ b/curator-framework/src/main/java/org/apache/curator/framework/EnsureContainers.java
@@ -25,8 +25,7 @@ import java.util.concurrent.atomic.AtomicBoolean;
* Similar to {@link org.apache.curator.utils.EnsurePath} but creates containers.
*
*/
-public class EnsureContainers
-{
+public class EnsureContainers {
private final CuratorFramework client;
private final String path;
private final AtomicBoolean ensureNeeded = new AtomicBoolean(true);
@@ -35,8 +34,7 @@ public class EnsureContainers
* @param client the client
* @param path path to ensure is containers
*/
- public EnsureContainers(CuratorFramework client, String path)
- {
+ public EnsureContainers(CuratorFramework client, String path) {
this.client = client;
this.path = path;
}
@@ -47,10 +45,8 @@ public class EnsureContainers
*
* @throws Exception errors
*/
- public void ensure() throws Exception
- {
- if ( ensureNeeded.get() )
- {
+ public void ensure() throws Exception {
+ if (ensureNeeded.get()) {
internalEnsure();
}
}
@@ -58,15 +54,12 @@ public class EnsureContainers
/**
* Reset so that the next call to {@link #ensure()} will attempt to create containers
*/
- public void reset()
- {
+ public void reset() {
ensureNeeded.set(true);
}
- private synchronized void internalEnsure() throws Exception
- {
- if ( ensureNeeded.compareAndSet(true, false) )
- {
+ private synchronized void internalEnsure() throws Exception {
+ if (ensureNeeded.compareAndSet(true, false)) {
client.createContainers(path);
}
}
diff --git a/curator-framework/src/main/java/org/apache/curator/framework/WatcherRemoveCuratorFramework.java b/curator-framework/src/main/java/org/apache/curator/framework/WatcherRemoveCuratorFramework.java
index fb923541..c6f1b8f3 100644
--- a/curator-framework/src/main/java/org/apache/curator/framework/WatcherRemoveCuratorFramework.java
+++ b/curator-framework/src/main/java/org/apache/curator/framework/WatcherRemoveCuratorFramework.java
@@ -19,13 +19,10 @@
package org.apache.curator.framework;
-import org.apache.zookeeper.Watcher;
-
/**
* A CuratorFramework facade that tracks watchers created and allows a one-shot removal of all watchers
*/
-public interface WatcherRemoveCuratorFramework extends CuratorFramework
-{
+public interface WatcherRemoveCuratorFramework extends CuratorFramework {
/**
* Remove all outstanding watchers that have been set
*/
diff --git a/curator-framework/src/main/java/org/apache/curator/framework/api/ACLBackgroundPathAndBytesable.java b/curator-framework/src/main/java/org/apache/curator/framework/api/ACLBackgroundPathAndBytesable.java
index 3e3c9528..950aeec7 100644
--- a/curator-framework/src/main/java/org/apache/curator/framework/api/ACLBackgroundPathAndBytesable.java
+++ b/curator-framework/src/main/java/org/apache/curator/framework/api/ACLBackgroundPathAndBytesable.java
@@ -19,8 +19,5 @@
package org.apache.curator.framework.api;
-public interface ACLBackgroundPathAndBytesable<T> extends
- ParentACLable<BackgroundPathAndBytesable<T>>,
- BackgroundPathAndBytesable<T>
-{
-}
+public interface ACLBackgroundPathAndBytesable<T>
+ extends ParentACLable<BackgroundPathAndBytesable<T>>, BackgroundPathAndBytesable<T> {}
diff --git a/curator-framework/src/main/java/org/apache/curator/framework/api/ACLCreateModeBackgroundPathAndBytesable.java b/curator-framework/src/main/java/org/apache/curator/framework/api/ACLCreateModeBackgroundPathAndBytesable.java
index cefd44fb..3c83149a 100644
--- a/curator-framework/src/main/java/org/apache/curator/framework/api/ACLCreateModeBackgroundPathAndBytesable.java
+++ b/curator-framework/src/main/java/org/apache/curator/framework/api/ACLCreateModeBackgroundPathAndBytesable.java
@@ -19,9 +19,7 @@
package org.apache.curator.framework.api;
-public interface ACLCreateModeBackgroundPathAndBytesable<T> extends
- ACLBackgroundPathAndBytesable<T>,
- BackgroundPathAndBytesable<T>,
- CreateModable<ACLBackgroundPathAndBytesable<T>>
-{
-}
+public interface ACLCreateModeBackgroundPathAndBytesable<T>
+ extends ACLBackgroundPathAndBytesable<T>,
+ BackgroundPathAndBytesable<T>,
+ CreateModable<ACLBackgroundPathAndBytesable<T>> {}
diff --git a/curator-framework/src/main/java/org/apache/curator/framework/api/ACLCreateModePathAndBytesable.java b/curator-framework/src/main/java/org/apache/curator/framework/api/ACLCreateModePathAndBytesable.java
index 43f09515..23a52322 100644
--- a/curator-framework/src/main/java/org/apache/curator/framework/api/ACLCreateModePathAndBytesable.java
+++ b/curator-framework/src/main/java/org/apache/curator/framework/api/ACLCreateModePathAndBytesable.java
@@ -19,8 +19,5 @@
package org.apache.curator.framework.api;
-public interface ACLCreateModePathAndBytesable<T> extends
- ACLPathAndBytesable<T>,
- CreateModable<ACLPathAndBytesable<T>>
-{
-}
+public interface ACLCreateModePathAndBytesable<T>
+ extends ACLPathAndBytesable<T>, CreateModable<ACLPathAndBytesable<T>> {}
diff --git a/curator-framework/src/main/java/org/apache/curator/framework/api/ACLCreateModeStatBackgroundPathAndBytesable.java b/curator-framework/src/main/java/org/apache/curator/framework/api/ACLCreateModeStatBackgroundPathAndBytesable.java
index ec3ea961..8d81abc5 100755
--- a/curator-framework/src/main/java/org/apache/curator/framework/api/ACLCreateModeStatBackgroundPathAndBytesable.java
+++ b/curator-framework/src/main/java/org/apache/curator/framework/api/ACLCreateModeStatBackgroundPathAndBytesable.java
@@ -19,8 +19,5 @@
package org.apache.curator.framework.api;
-public interface ACLCreateModeStatBackgroundPathAndBytesable<T> extends
- ACLCreateModeBackgroundPathAndBytesable<T>,
- Statable<ACLCreateModeBackgroundPathAndBytesable<T>>
-{
-}
+public interface ACLCreateModeStatBackgroundPathAndBytesable<T>
+ extends ACLCreateModeBackgroundPathAndBytesable<T>, Statable<ACLCreateModeBackgroundPathAndBytesable<T>> {}
diff --git a/curator-framework/src/main/java/org/apache/curator/framework/api/ACLPathAndBytesable.java b/curator-framework/src/main/java/org/apache/curator/framework/api/ACLPathAndBytesable.java
index 39047b1d..5da9b019 100644
--- a/curator-framework/src/main/java/org/apache/curator/framework/api/ACLPathAndBytesable.java
+++ b/curator-framework/src/main/java/org/apache/curator/framework/api/ACLPathAndBytesable.java
@@ -19,8 +19,4 @@
package org.apache.curator.framework.api;
-public interface ACLPathAndBytesable<T> extends
- ParentACLable<PathAndBytesable<T>>,
- PathAndBytesable<T>
-{
-}
+public interface ACLPathAndBytesable<T> extends ParentACLable<PathAndBytesable<T>>, PathAndBytesable<T> {}
diff --git a/curator-framework/src/main/java/org/apache/curator/framework/api/ACLProvider.java b/curator-framework/src/main/java/org/apache/curator/framework/api/ACLProvider.java
index 3d5d04d4..89a1c96f 100644
--- a/curator-framework/src/main/java/org/apache/curator/framework/api/ACLProvider.java
+++ b/curator-framework/src/main/java/org/apache/curator/framework/api/ACLProvider.java
@@ -19,19 +19,18 @@
package org.apache.curator.framework.api;
+import java.util.List;
import org.apache.curator.utils.InternalACLProvider;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.data.ACL;
-import java.util.List;
-public interface ACLProvider extends InternalACLProvider
-{
+public interface ACLProvider extends InternalACLProvider {
/**
* Return the ACL list to use by default (usually {@link ZooDefs.Ids#OPEN_ACL_UNSAFE}).
... 83338 lines suppressed ...