From d8c8bc38c682fa674617907f8fe3112947e8bdf0 Mon Sep 17 00:00:00 2001 From: tison Date: Thu, 18 May 2023 09:52:17 +0800 Subject: [PATCH 1/2] CURATOR-XXX. Apply code style with spotless Signed-off-by: tison --- .github/workflows/ci.yml | 15 +++++++++++++++ pom.xml | 30 ++++++++++++++++++++++++++++++ 2 files changed, 45 insertions(+) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e7678802b..7806dfd1a 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/pom.xml b/pom.xml index 2fb910088..4ddcaf781 100644 --- a/pom.xml +++ b/pom.xml @@ -79,6 +79,7 @@ 3.0.0 3.3.2 3.0.0-M5 + 2.36.0 1.11.1 3.24.1-GA 2.2 @@ -736,6 +737,12 @@ maven-dependency-plugin ${maven-dependency-plugin-version} + + + com.diffplug.spotless + spotless-maven-plugin + ${spotless.version} + @@ -985,6 +992,29 @@ maven-dependency-plugin ${maven-dependency-plugin-version} + + + com.diffplug.spotless + spotless-maven-plugin + + + + 2.30.0 + + + + \#| + + + + + + true + 4 + + + + From 236d49fc888c6897164419115b69a4bf4f57688d Mon Sep 17 00:00:00 2001 From: tison Date: Thu, 1 Jun 2023 22:57:50 +0800 Subject: [PATCH 2/2] run ./mvnw spotless:apply Signed-off-by: tison --- .../org/apache/curator/ConnectionState.java | 213 +-- .../CuratorConnectionLossException.java | 5 +- .../curator/CuratorZookeeperClient.java | 189 ++- .../java/org/apache/curator/HandleHolder.java | 89 +- .../main/java/org/apache/curator/Helper.java | 21 +- .../java/org/apache/curator/RetryLoop.java | 28 +- .../org/apache/curator/RetryLoopImpl.java | 43 +- .../java/org/apache/curator/RetryPolicy.java | 17 +- .../java/org/apache/curator/RetrySleeper.java | 5 +- .../apache/curator/SessionFailRetryLoop.java | 109 +- .../curator/SessionFailedRetryPolicy.java | 19 +- .../java/org/apache/curator/TimeTrace.java | 13 +- .../connection/ThreadLocalRetryLoop.java | 53 +- .../curator/drivers/AdvancedTracerDriver.java | 11 +- .../apache/curator/drivers/EventTrace.java | 50 +- .../curator/drivers/OperationTrace.java | 107 +- .../apache/curator/drivers/TracerDriver.java | 7 +- .../curator/ensemble/EnsembleProvider.java | 19 +- .../ensemble/fixed/FixedEnsembleProvider.java | 31 +- .../retry/BoundedExponentialBackoffRetry.java | 14 +- .../retry/ExponentialBackoffRetry.java | 28 +- .../apache/curator/retry/RetryForever.java | 22 +- .../org/apache/curator/retry/RetryNTimes.java | 9 +- .../apache/curator/retry/RetryOneTime.java | 6 +- .../curator/retry/RetryUntilElapsed.java | 13 +- .../apache/curator/retry/SleepingRetry.java | 26 +- .../utils/CloseableExecutorService.java | 66 +- .../CloseableScheduledExecutorService.java | 19 +- .../apache/curator/utils/CloseableUtils.java | 17 +- .../apache/curator/utils/Compatibility.java | 70 +- .../utils/ConfigurableZookeeperFactory.java | 17 +- .../org/apache/curator/utils/DebugUtils.java | 14 +- .../curator/utils/DefaultTracerDriver.java | 17 +- .../utils/DefaultZookeeperFactory.java | 7 +- .../org/apache/curator/utils/EnsurePath.java | 74 +- .../curator/utils/ExceptionAccumulator.java | 25 +- .../curator/utils/InternalACLProvider.java | 7 +- .../utils/NonAdminZookeeperFactory.java | 7 +- .../org/apache/curator/utils/PathUtils.java | 22 +- .../org/apache/curator/utils/ThreadUtils.java | 51 +- .../org/apache/curator/utils/ZKPaths.java | 264 ++- .../curator/utils/ZookeeperFactory.java | 24 +- .../java/org/apache/curator/BasicTests.java | 127 +- .../org/apache/curator/TestEnsurePath.java | 86 +- .../java/org/apache/curator/TestIs37.java | 9 +- .../org/apache/curator/TestRetryLoop.java | 148 +- .../curator/TestSessionFailRetryLoop.java | 334 ++-- .../utils/TestCloseableExecutorService.java | 201 +-- ...TestCloseableScheduledExecutorService.java | 55 +- .../org/apache/curator/utils/TestZKPaths.java | 11 +- .../src/main/java/async/AsyncExamples.java | 67 +- .../main/java/cache/CuratorCacheExample.java | 55 +- .../src/main/java/cache/PathCacheExample.java | 181 +- .../src/main/java/cache/TreeCacheExample.java | 20 +- .../main/java/discovery/DiscoveryExample.java | 237 ++- .../main/java/discovery/ExampleServer.java | 47 +- .../main/java/discovery/InstanceDetails.java | 17 +- .../java/framework/CreateClientExamples.java | 22 +- .../src/main/java/framework/CrudExamples.java | 109 +- .../java/framework/TransactionExamples.java | 17 +- .../src/main/java/leader/ExampleClient.java | 34 +- .../java/leader/LeaderSelectorExample.java | 52 +- .../java/locking/ExampleClientThatLocks.java | 22 +- .../java/locking/FakeLimitedResource.java | 20 +- .../src/main/java/locking/LockingExample.java | 70 +- .../src/main/java/modeled/ContainerType.java | 29 +- .../java/modeled/ModeledCuratorExamples.java | 26 +- .../modeled/ModeledCuratorExamplesAlt.java | 21 +- .../src/main/java/modeled/PersonId.java | 29 +- .../src/main/java/modeled/PersonModel.java | 56 +- .../main/java/modeled/PersonModelSpec.java | 9 +- .../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 +- .../pubsub/messages/LocationAvailable.java | 22 +- .../java/pubsub/messages/UserCreated.java | 25 +- .../src/main/java/pubsub/models/Group.java | 15 +- .../src/main/java/pubsub/models/Instance.java | 32 +- .../main/java/pubsub/models/InstanceType.java | 3 +- .../src/main/java/pubsub/models/Message.java | 26 +- .../src/main/java/pubsub/models/Priority.java | 3 +- .../apache/curator/framework/AuthInfo.java | 18 +- .../curator/framework/CuratorFramework.java | 16 +- .../framework/CuratorFrameworkFactory.java | 269 ++- .../framework/CuratorTempFramework.java | 7 +- .../curator/framework/EnsureContainers.java | 21 +- .../WatcherRemoveCuratorFramework.java | 5 +- .../api/ACLBackgroundPathAndBytesable.java | 7 +- ...LCreateModeBackgroundPathAndBytesable.java | 10 +- .../api/ACLCreateModePathAndBytesable.java | 7 +- ...ateModeStatBackgroundPathAndBytesable.java | 7 +- .../framework/api/ACLPathAndBytesable.java | 6 +- .../curator/framework/api/ACLProvider.java | 9 +- .../apache/curator/framework/api/ACLable.java | 5 +- .../api/ACLableExistBuilderMain.java | 6 +- .../api/AddStatConfigEnsembleable.java | 9 +- .../framework/api/AddWatchBuilder.java | 5 +- .../framework/api/AddWatchBuilder2.java | 8 +- .../apache/curator/framework/api/Addable.java | 3 +- .../framework/api/AsyncReconfigurable.java | 2 +- .../framework/api/BackgroundCallback.java | 3 +- .../framework/api/BackgroundEnsembleable.java | 6 +- .../api/BackgroundPathAndBytesable.java | 7 +- .../framework/api/BackgroundPathable.java | 6 +- .../api/BackgroundPathableQuietlyable.java | 4 +- .../framework/api/BackgroundVersionable.java | 6 +- .../curator/framework/api/Backgroundable.java | 3 +- .../framework/api/ChildrenDeletable.java | 3 +- .../curator/framework/api/Compressible.java | 3 +- .../framework/api/CompressionProvider.java | 7 +- .../framework/api/ConfigureEnsembleable.java | 4 +- .../api/CreateBackgroundModeACLable.java | 13 +- .../api/CreateBackgroundModeStatACLable.java | 15 +- .../curator/framework/api/CreateBuilder.java | 3 +- .../curator/framework/api/CreateBuilder2.java | 3 +- .../framework/api/CreateBuilderMain.java | 18 +- .../curator/framework/api/CreateModable.java | 3 +- ...eProtectACLCreateModePathAndBytesable.java | 6 +- .../curator/framework/api/CuratorEvent.java | 6 +- .../framework/api/CuratorEventType.java | 3 +- .../framework/api/CuratorListener.java | 5 +- .../curator/framework/api/CuratorWatcher.java | 3 +- .../curator/framework/api/Decompressible.java | 5 +- .../curator/framework/api/DeleteBuilder.java | 8 +- .../framework/api/DeleteBuilderMain.java | 4 +- .../api/ErrorListenerEnsembleable.java | 3 +- .../ErrorListenerMultiTransactionMain.java | 3 +- .../api/ErrorListenerPathAndBytesable.java | 3 +- .../framework/api/ErrorListenerPathable.java | 3 +- .../api/ErrorListenerReconfigBuilderMain.java | 3 +- .../curator/framework/api/ExistsBuilder.java | 4 +- .../framework/api/ExistsBuilderMain.java | 6 +- .../curator/framework/api/GetACLBuilder.java | 8 +- .../framework/api/GetChildrenBuilder.java | 10 +- .../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 +- .../api/JoinStatConfigEnsembleable.java | 9 +- .../curator/framework/api/Joinable.java | 3 +- .../api/LeaveStatConfigEnsembleable.java | 9 +- .../curator/framework/api/Leaveable.java | 3 +- .../curator/framework/api/Membersable.java | 3 +- .../curator/framework/api/ParentACLable.java | 4 +- .../framework/api/PathAndBytesable.java | 7 +- .../curator/framework/api/Pathable.java | 5 +- .../ProtectACLCreateModePathAndBytesable.java | 8 +- ...tectACLCreateModeStatPathAndBytesable.java | 7 +- .../apache/curator/framework/api/Quietly.java | 3 +- .../framework/api/ReconfigBuilder.java | 6 +- .../framework/api/ReconfigBuilderMain.java | 10 +- .../framework/api/RemoveWatchesBuilder.java | 57 +- .../framework/api/RemoveWatchesLocal.java | 32 +- .../framework/api/RemoveWatchesType.java | 36 +- .../curator/framework/api/SetACLBuilder.java | 7 +- .../api/SetDataBackgroundVersionable.java | 7 +- .../curator/framework/api/SetDataBuilder.java | 12 +- .../api/StatConfigureEnsembleable.java | 6 +- .../curator/framework/api/StatPathable.java | 6 +- .../curator/framework/api/Statable.java | 3 +- .../curator/framework/api/SyncBuilder.java | 5 +- .../framework/api/TempGetDataBuilder.java | 8 +- .../framework/api/UnhandledErrorListener.java | 8 +- .../api/VersionPathAndBytesable.java | 6 +- .../curator/framework/api/Versionable.java | 5 +- .../api/WatchBackgroundEnsembleable.java | 7 +- .../curator/framework/api/WatchPathable.java | 6 +- .../curator/framework/api/Watchable.java | 3 +- .../curator/framework/api/WatchableBase.java | 3 +- .../curator/framework/api/WatchesBuilder.java | 7 +- .../transaction/CuratorMultiTransaction.java | 7 +- .../CuratorMultiTransactionMain.java | 5 +- .../framework/api/transaction/CuratorOp.java | 3 +- .../api/transaction/CuratorTransaction.java | 3 +- .../transaction/CuratorTransactionBridge.java | 3 +- .../transaction/CuratorTransactionFinal.java | 3 +- .../transaction/CuratorTransactionResult.java | 33 +- .../api/transaction/OperationType.java | 3 +- .../transaction/TransactionCheckBuilder.java | 6 +- .../transaction/TransactionCreateBuilder.java | 3 +- .../TransactionCreateBuilder2.java | 14 +- .../transaction/TransactionDeleteBuilder.java | 6 +- .../api/transaction/TransactionOp.java | 3 +- .../TransactionSetDataBuilder.java | 12 +- .../api/transaction/TypeAndPath.java | 12 +- .../apache/curator/framework/imps/ACLing.java | 34 +- .../framework/imps/AddWatchBuilderImpl.java | 174 +- .../framework/imps/BackgroundOperation.java | 3 +- .../framework/imps/BackgroundSyncImpl.java | 50 +- .../curator/framework/imps/Backgrounding.java | 106 +- .../framework/imps/CreateBuilderImpl.java | 972 +++++------ .../framework/imps/CuratorEventImpl.java | 83 +- .../framework/imps/CuratorFrameworkImpl.java | 678 ++++---- .../framework/imps/CuratorFrameworkState.java | 3 +- .../imps/CuratorMultiTransactionImpl.java | 156 +- .../imps/CuratorMultiTransactionRecord.java | 30 +- .../imps/CuratorTempFrameworkImpl.java | 82 +- .../imps/CuratorTransactionImpl.java | 108 +- .../framework/imps/DefaultACLProvider.java | 11 +- .../framework/imps/DeleteBuilderImpl.java | 305 ++-- .../framework/imps/EnsembleTracker.java | 135 +- .../framework/imps/ExistsBuilderImpl.java | 228 ++- .../framework/imps/ExtractingCuratorOp.java | 20 +- .../framework/imps/FailedDeleteManager.java | 10 +- .../imps/FailedOperationManager.java | 39 +- .../imps/FailedRemoveWatchManager.java | 27 +- ...indAndDeleteProtectedNodeInBackground.java | 76 +- .../framework/imps/GetACLBuilderImpl.java | 107 +- .../imps/GetChildrenBuilderImpl.java | 185 +- .../framework/imps/GetConfigBuilderImpl.java | 197 +-- .../framework/imps/GetDataBuilderImpl.java | 235 ++- .../imps/GzipCompressionProvider.java | 139 +- .../framework/imps/IdempotentUtils.java | 10 +- .../imps/InternalConnectionHandler.java | 3 +- .../framework/imps/NamespaceFacade.java | 66 +- .../framework/imps/NamespaceFacadeCache.java | 32 +- .../curator/framework/imps/NamespaceImpl.java | 75 +- .../framework/imps/NamespaceWatchedEvent.java | 6 +- .../framework/imps/NamespaceWatcher.java | 61 +- .../framework/imps/OperationAndData.java | 85 +- .../curator/framework/imps/PathAndBytes.java | 16 +- .../curator/framework/imps/ProtectedMode.java | 40 +- .../framework/imps/ProtectedUtils.java | 58 +- .../framework/imps/ReconfigBuilderImpl.java | 186 +-- .../imps/RemoveWatchesBuilderImpl.java | 637 ++++--- .../framework/imps/SetACLBuilderImpl.java | 152 +- .../framework/imps/SetDataBuilderImpl.java | 393 ++--- .../StandardInternalConnectionHandler.java | 9 +- .../framework/imps/SyncBuilderImpl.java | 59 +- .../imps/TempGetDataBuilderImpl.java | 48 +- .../framework/imps/TransactionOpImpl.java | 19 +- .../framework/imps/WatcherRemovalFacade.java | 83 +- .../framework/imps/WatcherRemovalManager.java | 35 +- .../framework/imps/WatchesBuilderImpl.java | 22 +- .../curator/framework/imps/Watching.java | 47 +- .../curator/framework/listen/Listenable.java | 9 +- .../framework/listen/ListenerEntry.java | 8 +- .../framework/listen/ListenerManager.java | 6 +- .../listen/MappingListenerManager.java | 46 +- .../listen/StandardListenerManager.java | 30 +- .../listen/UnaryListenerManager.java | 4 +- .../schema/DefaultSchemaValidator.java | 8 +- .../curator/framework/schema/Schema.java | 190 +-- .../framework/schema/SchemaBuilder.java | 45 +- .../curator/framework/schema/SchemaSet.java | 127 +- .../framework/schema/SchemaSetLoader.java | 97 +- .../framework/schema/SchemaValidator.java | 5 +- .../framework/schema/SchemaViolation.java | 47 +- .../framework/state/CircuitBreaker.java | 50 +- ...ircuitBreakingConnectionStateListener.java | 94 +- .../state/CircuitBreakingManager.java | 48 +- .../framework/state/ConnectionState.java | 37 +- .../state/ConnectionStateErrorPolicy.java | 3 +- .../state/ConnectionStateListener.java | 6 +- ...ConnectionStateListenerManagerFactory.java | 12 +- .../state/ConnectionStateManager.java | 223 ++- .../SessionConnectionStateErrorPolicy.java | 6 +- .../StandardConnectionStateErrorPolicy.java | 6 +- .../ensemble/TestEnsembleProvider.java | 84 +- .../imps/TestBlockUntilConnected.java | 187 +-- .../framework/imps/TestCleanState.java | 95 +- .../framework/imps/TestCompression.java | 80 +- .../imps/TestCompressionInTransactionNew.java | 101 +- .../imps/TestCompressionInTransactionOld.java | 160 +- .../curator/framework/imps/TestCreate.java | 276 ++- .../imps/TestCreateReturningStat.java | 433 +++-- .../curator/framework/imps/TestDelete.java | 241 +-- .../imps/TestEnabledSessionExpiredState.java | 83 +- .../framework/imps/TestEnsureContainers.java | 24 +- .../framework/imps/TestExistsBuilder.java | 63 +- .../imps/TestFailedDeleteManager.java | 292 ++-- .../curator/framework/imps/TestFramework.java | 772 ++++----- .../imps/TestFrameworkBackground.java | 225 +-- .../framework/imps/TestFrameworkEdges.java | 595 +++---- .../imps/TestGzipCompressionProvider.java | 27 +- .../framework/imps/TestMultiClient.java | 69 +- .../framework/imps/TestNamespaceFacade.java | 160 +- .../framework/imps/TestNeverConnected.java | 25 +- .../curator/framework/imps/TestReadOnly.java | 80 +- .../framework/imps/TestReconfiguration.java | 393 ++--- .../curator/framework/imps/TestSetData.java | 273 ++- .../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 ++- .../imps/TestWatcherRemovalManager.java | 330 ++-- .../framework/imps/TestWatchesBuilder.java | 1484 ++++++++--------- .../framework/imps/TestWithCluster.java | 100 +- .../curator/framework/schema/TestSchema.java | 224 ++- .../framework/state/TestCircuitBreaker.java | 38 +- ...ircuitBreakingConnectionStateListener.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 +- .../recipes/atomic/CachedAtomicLong.java | 24 +- .../atomic/DistributedAtomicInteger.java | 100 +- .../recipes/atomic/DistributedAtomicLong.java | 100 +- .../atomic/DistributedAtomicNumber.java | 3 +- .../atomic/DistributedAtomicValue.java | 245 ++- .../framework/recipes/atomic/MakeValue.java | 5 +- .../recipes/atomic/MutableAtomicValue.java | 21 +- .../recipes/atomic/PromotedToLock.java | 58 +- .../recipes/barriers/DistributedBarrier.java | 70 +- .../barriers/DistributedDoubleBarrier.java | 228 +-- .../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 +- .../cache/CuratorCacheBridgeBuilder.java | 5 +- .../cache/CuratorCacheBridgeBuilderImpl.java | 31 +- .../recipes/cache/CuratorCacheBuilder.java | 5 +- .../cache/CuratorCacheBuilderImpl.java | 22 +- .../recipes/cache/CuratorCacheImpl.java | 197 +-- .../recipes/cache/CuratorCacheListener.java | 14 +- .../cache/CuratorCacheListenerBuilder.java | 13 +- .../CuratorCacheListenerBuilderImpl.java | 74 +- .../recipes/cache/CuratorCacheStorage.java | 9 +- .../cache/DefaultTreeCacheSelector.java | 9 +- .../recipes/cache/EventOperation.java | 16 +- .../recipes/cache/GetDataOperation.java | 33 +- .../framework/recipes/cache/NodeCache.java | 196 +-- .../recipes/cache/NodeCacheListener.java | 5 +- .../cache/NodeCacheListenerWrapper.java | 21 +- .../framework/recipes/cache/Operation.java | 5 +- .../recipes/cache/PathChildrenCache.java | 557 +++---- .../recipes/cache/PathChildrenCacheEvent.java | 28 +- .../cache/PathChildrenCacheListener.java | 5 +- .../PathChildrenCacheListenerWrapper.java | 38 +- .../recipes/cache/PathChildrenCacheMode.java | 5 +- .../recipes/cache/RefreshOperation.java | 29 +- .../cache/StandardCuratorCacheStorage.java | 26 +- .../framework/recipes/cache/TreeCache.java | 644 +++---- .../recipes/cache/TreeCacheEvent.java | 29 +- .../recipes/cache/TreeCacheIterator.java | 62 +- .../recipes/cache/TreeCacheListener.java | 3 +- .../cache/TreeCacheListenerWrapper.java | 36 +- .../recipes/cache/TreeCacheSelector.java | 3 +- .../leader/CancelLeadershipException.java | 16 +- .../framework/recipes/leader/LeaderLatch.java | 353 ++-- .../recipes/leader/LeaderLatchListener.java | 31 +- .../recipes/leader/LeaderSelector.java | 279 ++-- .../leader/LeaderSelectorListener.java | 5 +- .../leader/LeaderSelectorListenerAdapter.java | 9 +- .../framework/recipes/leader/Participant.java | 47 +- .../recipes/locks/InterProcessLock.java | 3 +- .../recipes/locks/InterProcessMultiLock.java | 116 +- .../recipes/locks/InterProcessMutex.java | 104 +- .../locks/InterProcessReadWriteLock.java | 90 +- .../recipes/locks/InterProcessSemaphore.java | 145 +- .../locks/InterProcessSemaphoreMutex.java | 25 +- .../locks/InterProcessSemaphoreV2.java | 253 ++- .../framework/recipes/locks/Lease.java | 5 +- .../recipes/locks/LockInternals.java | 298 ++-- .../recipes/locks/LockInternalsDriver.java | 10 +- .../recipes/locks/LockInternalsSorter.java | 5 +- .../framework/recipes/locks/Locker.java | 27 +- .../recipes/locks/PredicateResults.java | 16 +- .../framework/recipes/locks/Revocable.java | 7 +- .../recipes/locks/RevocationListener.java | 5 +- .../recipes/locks/RevocationSpec.java | 16 +- .../framework/recipes/locks/Revoker.java | 17 +- .../locks/StandardLockInternalsDriver.java | 55 +- .../framework/recipes/nodes/GroupMember.java | 61 +- .../nodes/PersistentEphemeralNode.java | 101 +- .../recipes/nodes/PersistentNode.java | 374 ++--- .../recipes/nodes/PersistentTtlNode.java | 142 +- .../recipes/queue/BlockingQueueConsumer.java | 43 +- .../recipes/queue/ChildrenCache.java | 103 +- .../recipes/queue/DistributedDelayQueue.java | 149 +- .../recipes/queue/DistributedIdQueue.java | 194 +-- .../queue/DistributedPriorityQueue.java | 86 +- .../recipes/queue/DistributedQueue.java | 514 +++--- .../framework/recipes/queue/ErrorMode.java | 3 +- .../recipes/queue/ItemSerializer.java | 76 +- .../framework/recipes/queue/MultiItem.java | 5 +- .../recipes/queue/QueueAllocator.java | 5 +- .../framework/recipes/queue/QueueBase.java | 9 +- .../framework/recipes/queue/QueueBuilder.java | 157 +- .../recipes/queue/QueueConsumer.java | 5 +- .../recipes/queue/QueuePutListener.java | 7 +- .../framework/recipes/queue/QueueSafety.java | 18 +- .../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 +- .../recipes/shared/VersionedValue.java | 12 +- .../recipes/watch/PersistentWatcher.java | 69 +- .../connection/TestThreadLocalRetryLoop.java | 96 +- .../client/TestBackgroundStates.java | 77 +- ...tResetConnectionWithBackgroundFailure.java | 48 +- .../atomic/TestCachedAtomicCounter.java | 74 +- .../atomic/TestDistributedAtomicLong.java | 236 +-- .../barriers/TestDistributedBarrier.java | 202 +-- .../TestDistributedDoubleBarrier.java | 262 ++- .../recipes/cache/BaseTestTreeCache.java | 119 +- .../recipes/cache/TestCuratorCache.java | 91 +- .../recipes/cache/TestCuratorCacheBridge.java | 35 +- .../cache/TestCuratorCacheConsistency.java | 243 ++- .../recipes/cache/TestCuratorCacheEdges.java | 74 +- .../cache/TestCuratorCacheEventOrdering.java | 18 +- .../cache/TestCuratorCacheWrappers.java | 139 +- .../recipes/cache/TestEventOrdering.java | 123 +- .../recipes/cache/TestNodeCache.java | 218 +-- .../recipes/cache/TestPathChildrenCache.java | 921 ++++------ .../TestPathChildrenCacheEventOrdering.java | 24 +- .../cache/TestPathChildrenCacheInCluster.java | 122 +- .../recipes/cache/TestTreeCache.java | 125 +- .../cache/TestTreeCacheEventOrdering.java | 27 +- .../cache/TestTreeCacheIteratorAndSize.java | 83 +- .../cache/TestTreeCacheRandomTree.java | 182 +- .../recipes/cache/TestWrappedNodeCache.java | 61 +- .../leader/ChaosMonkeyCnxnFactory.java | 49 +- .../recipes/leader/TestLeaderAcls.java | 69 +- .../recipes/leader/TestLeaderLatch.java | 881 +++++----- .../leader/TestLeaderLatchCluster.java | 71 +- .../recipes/leader/TestLeaderSelector.java | 503 +++--- .../leader/TestLeaderSelectorCluster.java | 140 +- .../leader/TestLeaderSelectorEdges.java | 155 +- .../TestLeaderSelectorParticipants.java | 115 +- .../TestLeaderSelectorWithExecutor.java | 69 +- .../framework/recipes/locks/Counter.java | 7 +- .../recipes/locks/SemaphoreClient.java | 87 +- .../framework/recipes/locks/Stepper.java | 14 +- .../locks/TestInterProcessMultiMutex.java | 99 +- .../recipes/locks/TestInterProcessMutex.java | 163 +- .../locks/TestInterProcessMutexBase.java | 503 +++--- .../locks/TestInterProcessReadWriteLock.java | 318 ++-- .../locks/TestInterProcessSemaphore.java | 672 +++----- .../TestInterProcessSemaphoreCluster.java | 275 ++- .../locks/TestInterProcessSemaphoreMutex.java | 18 +- .../framework/recipes/locks/TestLockACLs.java | 95 +- .../locks/TestLockCleanlinessWithFaults.java | 32 +- .../recipes/nodes/TestGroupMember.java | 28 +- .../nodes/TestPersistentEphemeralNode.java | 475 +++--- .../TestPersistentEphemeralNodeListener.java | 41 +- .../recipes/nodes/TestPersistentNode.java | 99 +- .../recipes/nodes/TestPersistentTtlNode.java | 91 +- .../recipes/queue/QueueItemSerializer.java | 9 +- .../recipes/queue/QueueTestProducer.java | 14 +- .../queue/TestBoundedDistributedQueue.java | 263 ++- .../queue/TestDistributedDelayQueue.java | 188 +-- .../recipes/queue/TestDistributedIdQueue.java | 120 +- .../queue/TestDistributedPriorityQueue.java | 235 ++- .../recipes/queue/TestDistributedQueue.java | 740 ++++---- .../queue/TestLongNetworkPartition.java | 76 +- .../recipes/queue/TestQueueItem.java | 35 +- .../recipes/queue/TestQueueSharder.java | 181 +- .../queue/TestSimpleDistributedQueue.java | 279 +--- .../recipes/shared/TestSharedCount.java | 301 ++-- .../recipes/watch/TestPersistentWatcher.java | 50 +- .../curator/framework/TestCompatibility.java | 20 +- .../org/apache/curator/zk35/TestIs35.java | 10 +- .../org/apache/curator/zk36/TestIs36.java | 13 +- .../curator/test/BaseClassForTests.java | 108 +- .../apache/curator/test/Compatibility.java | 62 +- .../test/DelegatingExecutorService.java | 51 +- .../apache/curator/test/DirectoryUtils.java | 16 +- .../ExecuteCalledWatchingExecutorService.java | 15 +- .../test/FailedServerStartException.java | 9 +- .../org/apache/curator/test/InstanceSpec.java | 189 ++- .../org/apache/curator/test/KillSession.java | 12 +- .../curator/test/QuorumConfigBuilder.java | 83 +- .../curator/test/QuorumPeerConfigBuilder.java | 3 +- .../org/apache/curator/test/ServerHelper.java | 120 +- .../apache/curator/test/TestingCluster.java | 122 +- .../curator/test/TestingQuorumPeerMain.java | 63 +- .../apache/curator/test/TestingServer.java | 47 +- .../curator/test/TestingZooKeeperMain.java | 207 +-- .../curator/test/TestingZooKeeperServer.java | 62 +- .../java/org/apache/curator/test/Timing.java | 82 +- .../apache/curator/test/WatchersDebug.java | 47 +- .../curator/test/ZooKeeperMainFace.java | 3 +- .../test/ZooKeeperServerEmbeddedAdapter.java | 1 - .../test/compatibility/CuratorTestBase.java | 3 +- .../curator/test/compatibility/Timing2.java | 118 +- .../curator/test/TestQuorumConfigBuilder.java | 10 +- .../curator/test/TestTestingServer.java | 47 +- .../x/async/AsyncCuratorFramework.java | 19 +- .../curator/x/async/AsyncEventException.java | 5 +- .../apache/curator/x/async/AsyncResult.java | 18 +- .../apache/curator/x/async/AsyncStage.java | 5 +- .../apache/curator/x/async/AsyncWrappers.java | 174 +- .../org/apache/curator/x/async/WatchMode.java | 3 +- .../x/async/api/AsyncCreateBuilder.java | 24 +- .../x/async/api/AsyncCuratorFrameworkDsl.java | 3 +- .../x/async/api/AsyncDeleteBuilder.java | 5 +- .../curator/x/async/api/AsyncEnsemblable.java | 3 +- .../x/async/api/AsyncExistsBuilder.java | 5 +- .../x/async/api/AsyncGetACLBuilder.java | 5 +- .../x/async/api/AsyncGetChildrenBuilder.java | 5 +- .../x/async/api/AsyncGetConfigBuilder.java | 3 +- .../x/async/api/AsyncGetDataBuilder.java | 3 +- .../x/async/api/AsyncMultiTransaction.java | 5 +- .../x/async/api/AsyncPathAndBytesable.java | 3 +- .../curator/x/async/api/AsyncPathable.java | 3 +- .../x/async/api/AsyncReconfigBuilder.java | 11 +- .../async/api/AsyncRemoveWatchesBuilder.java | 11 +- .../x/async/api/AsyncSetACLBuilder.java | 5 +- .../x/async/api/AsyncSetDataBuilder.java | 3 +- .../curator/x/async/api/AsyncSyncBuilder.java | 5 +- .../api/AsyncTransactionCheckBuilder.java | 3 +- .../api/AsyncTransactionCreateBuilder.java | 8 +- .../api/AsyncTransactionDeleteBuilder.java | 3 +- .../x/async/api/AsyncTransactionOp.java | 3 +- .../api/AsyncTransactionSetDataBuilder.java | 3 +- .../x/async/api/AsyncWatchBuilder.java | 8 +- .../x/async/api/AsyncWatchBuilder2.java | 7 +- .../curator/x/async/api/CreateOption.java | 3 +- .../curator/x/async/api/DeleteOption.java | 3 +- .../curator/x/async/api/ExistsOption.java | 3 +- .../x/async/api/RemoveWatcherOption.java | 3 +- .../api/WatchableAsyncCuratorFramework.java | 3 +- .../async/details/AsyncCreateBuilderImpl.java | 98 +- .../details/AsyncCuratorFrameworkImpl.java | 146 +- .../async/details/AsyncDeleteBuilderImpl.java | 37 +- .../async/details/AsyncExistsBuilderImpl.java | 35 +- .../details/AsyncGetChildrenBuilderImpl.java | 19 +- .../details/AsyncGetConfigBuilderImpl.java | 17 +- .../details/AsyncGetDataBuilderImpl.java | 26 +- .../details/AsyncReconfigBuilderImpl.java | 46 +- .../AsyncRemoveWatchesBuilderImpl.java | 77 +- .../x/async/details/AsyncResultImpl.java | 72 +- .../async/details/AsyncSetACLBuilderImpl.java | 22 +- .../details/AsyncSetDataBuilderImpl.java | 29 +- .../async/details/AsyncTransactionOpImpl.java | 139 +- .../async/details/AsyncWatchBuilderImpl.java | 29 +- .../x/async/details/BackgroundProc.java | 6 +- .../x/async/details/BackgroundProcs.java | 46 +- .../x/async/details/BuilderCommon.java | 11 +- .../curator/x/async/details/Filters.java | 20 +- .../x/async/details/InternalCallback.java | 19 +- .../x/async/details/InternalWatcher.java | 47 +- .../curator/x/async/migrations/Migration.java | 5 +- .../async/migrations/MigrationException.java | 9 +- .../x/async/migrations/MigrationManager.java | 121 +- .../x/async/migrations/MigrationSet.java | 15 +- .../async/modeled/JacksonModelSerializer.java | 54 +- .../x/async/modeled/ModelSerializer.java | 12 +- .../curator/x/async/modeled/ModelSpec.java | 24 +- .../x/async/modeled/ModelSpecBuilder.java | 38 +- .../x/async/modeled/ModeledFramework.java | 16 +- .../modeled/ModeledFrameworkBuilder.java | 53 +- .../x/async/modeled/ModeledOptions.java | 3 +- .../curator/x/async/modeled/NodeName.java | 11 +- .../curator/x/async/modeled/Resolvable.java | 6 +- .../apache/curator/x/async/modeled/ZNode.java | 13 +- .../apache/curator/x/async/modeled/ZPath.java | 41 +- .../cached/CachedModeledFramework.java | 7 +- .../x/async/modeled/cached/ModeledCache.java | 7 +- .../modeled/cached/ModeledCacheListener.java | 27 +- .../details/CachedModeledFrameworkImpl.java | 199 +-- .../async/modeled/details/ModelSpecImpl.java | 144 +- .../x/async/modeled/details/ModelStage.java | 80 +- .../modeled/details/ModeledCacheImpl.java | 189 +-- .../modeled/details/ModeledFrameworkImpl.java | 377 ++--- .../VersionedModeledFrameworkImpl.java | 37 +- .../x/async/modeled/details/ZNodeImpl.java | 17 +- .../x/async/modeled/details/ZPathImpl.java | 186 +-- .../x/async/modeled/typed/TypedModelSpec.java | 9 +- .../async/modeled/typed/TypedModelSpec0.java | 9 +- .../async/modeled/typed/TypedModelSpec10.java | 21 +- .../async/modeled/typed/TypedModelSpec2.java | 9 +- .../async/modeled/typed/TypedModelSpec3.java | 10 +- .../async/modeled/typed/TypedModelSpec4.java | 17 +- .../async/modeled/typed/TypedModelSpec5.java | 17 +- .../async/modeled/typed/TypedModelSpec6.java | 17 +- .../async/modeled/typed/TypedModelSpec7.java | 17 +- .../async/modeled/typed/TypedModelSpec8.java | 17 +- .../async/modeled/typed/TypedModelSpec9.java | 19 +- .../modeled/typed/TypedModeledFramework.java | 21 +- .../modeled/typed/TypedModeledFramework0.java | 21 +- .../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 +- .../x/async/modeled/typed/TypedZPath.java | 9 +- .../x/async/modeled/typed/TypedZPath0.java | 9 +- .../x/async/modeled/typed/TypedZPath10.java | 11 +- .../x/async/modeled/typed/TypedZPath2.java | 9 +- .../x/async/modeled/typed/TypedZPath3.java | 9 +- .../x/async/modeled/typed/TypedZPath4.java | 9 +- .../x/async/modeled/typed/TypedZPath5.java | 9 +- .../x/async/modeled/typed/TypedZPath6.java | 9 +- .../x/async/modeled/typed/TypedZPath7.java | 9 +- .../x/async/modeled/typed/TypedZPath8.java | 9 +- .../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 +++---- .../imps/TestFrameworkBackground.java | 169 +- .../x/async/CompletableBaseClassForTests.java | 44 +- .../curator/x/async/TestAsyncWrappers.java | 39 +- .../curator/x/async/TestBasicOperations.java | 83 +- .../migrations/TestMigrationManager.java | 162 +- .../x/async/migrations/models/ModelV1.java | 12 +- .../x/async/migrations/models/ModelV2.java | 15 +- .../x/async/migrations/models/ModelV3.java | 18 +- .../modeled/TestCachedModeledFramework.java | 135 +- .../x/async/modeled/TestModeledFramework.java | 144 +- .../modeled/TestModeledFrameworkBase.java | 12 +- .../curator/x/async/modeled/TestZPath.java | 37 +- .../x/async/modeled/models/TestModel.java | 50 +- .../async/modeled/models/TestNewerModel.java | 71 +- .../async/modeled/models/TestSimpleModel.java | 35 +- .../contexts/GenericDiscoveryContext.java | 50 +- .../contexts/IntegerDiscoveryContext.java | 37 +- .../server/contexts/MapDiscoveryContext.java | 18 +- .../contexts/StringDiscoveryContext.java | 34 +- .../entity/JsonServiceInstanceMarshaller.java | 105 +- .../JsonServiceInstancesMarshaller.java | 81 +- .../entity/JsonServiceNamesMarshaller.java | 53 +- .../server/entity/ServiceInstances.java | 14 +- .../discovery/server/entity/ServiceNames.java | 12 +- .../server/rest/DiscoveryContext.java | 13 +- .../server/rest/DiscoveryResource.java | 148 +- .../server/rest/InstanceCleanup.java | 91 +- .../jetty_jersey/MapDiscoveryResource.java | 12 +- .../server/jetty_jersey/ServiceDetails.java | 98 +- .../ServiceDetailsDiscoveryContext.java | 14 +- .../ServiceDetailsDiscoveryResource.java | 7 +- .../jetty_jersey/StringDiscoveryResource.java | 10 +- .../jetty_jersey/TestMapsWithJersey.java | 77 +- .../TestObjectPayloadWithJersey.java | 74 +- .../jetty_jersey/TestStringsWithJersey.java | 79 +- .../jetty_resteasy/RestEasyApplication.java | 18 +- .../jetty_resteasy/RestEasySingletons.java | 14 +- .../StringDiscoveryResource.java | 16 +- .../TestStringsWithRestEasy.java | 101 +- .../server/mocks/MockServiceDiscovery.java | 61 +- .../x/discovery/DownInstancePolicy.java | 15 +- .../curator/x/discovery/InstanceFilter.java | 4 +- .../curator/x/discovery/LocalIpFilter.java | 5 +- .../curator/x/discovery/ProviderStrategy.java | 5 +- .../curator/x/discovery/ServiceCache.java | 9 +- .../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 +- .../curator/x/discovery/ServiceType.java | 11 +- .../apache/curator/x/discovery/UriSpec.java | 176 +- .../details/DownInstanceManager.java | 38 +- .../details/FilteredInstanceProvider.java | 11 +- .../x/discovery/details/InstanceProvider.java | 7 +- .../discovery/details/InstanceSerializer.java | 5 +- .../details/JsonInstanceSerializer.java | 35 +- .../curator/x/discovery/details/Latch.java | 14 +- .../discovery/details/OldServiceInstance.java | 95 +- .../details/ServiceCacheBuilderImpl.java | 29 +- .../x/discovery/details/ServiceCacheImpl.java | 132 +- .../details/ServiceCacheListener.java | 3 +- .../details/ServiceDiscoveryImpl.java | 334 ++-- .../details/ServiceProviderBuilderImpl.java | 36 +- .../details/ServiceProviderImpl.java | 55 +- .../discovery/strategies/RandomStrategy.java | 21 +- .../strategies/RoundRobinStrategy.java | 21 +- .../discovery/strategies/StickyStrategy.java | 54 +- .../x/discovery/ServiceCacheLeakTester.java | 50 +- .../discovery/TestJsonInstanceSerializer.java | 128 +- .../x/discovery/TestLocalIpFilter.java | 32 +- .../curator/x/discovery/TestServiceCache.java | 251 +-- .../curator/x/discovery/TestStrategies.java | 94 +- .../curator/x/discovery/TestUriSpec.java | 45 +- .../details/TestDownInstanceManager.java | 35 +- ...stJsonInstanceSerializerCompatibility.java | 103 +- .../details/TestNewServiceInstance.java | 69 +- .../details/TestServiceCacheRace.java | 89 +- .../details/TestServiceDiscovery.java | 256 +-- .../details/TestServiceDiscoveryBuilder.java | 31 +- .../details/TestServiceProvider.java | 69 +- .../details/TestWatchedInstances.java | 58 +- 692 files changed, 21226 insertions(+), 29270 deletions(-) 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 88325f22f..d367d50db 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.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 tracer, boolean canBeReadOnly) - { + ConnectionState( + ZookeeperFactory zookeeperFactory, + EnsembleProvider ensembleProvider, + int sessionTimeoutMs, + Watcher parentWatcher, + AtomicReference 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 @@ void start() throws Exception 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 @@ synchronized void reset() throws Exception 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 @@ public long getSessionId() { 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 @@ private boolean checkState(Event.KeeperState state, boolean wasConnected) 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 2df63f426..91d7626cd 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 @@ 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 51cad402e..ecb072f65 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.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 = new AtomicReference(); @@ -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 CuratorZookeeperClient(String connectString, int sessionTimeoutMs, int co * @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 CuratorZookeeperClient(EnsembleProvider ensembleProvider, int sessionTime * {@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 CuratorZookeeperClient(ZookeeperFactory zookeeperFactory, EnsembleProvide * 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 CuratorZookeeperClient(ZookeeperFactory zookeeperFactory, EnsembleProvide 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 CuratorZookeeperClient(ZookeeperFactory zookeeperFactory, EnsembleProvide * @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 ZooKeeper getZooKeeper() throws Exception * * @return new retry loop */ - public RetryLoop newRetryLoop() - { + public RetryLoop newRetryLoop() { return new RetryLoopImpl(retryPolicy.get(), tracer); } @@ -158,8 +198,7 @@ public RetryLoop newRetryLoop() * @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 SessionFailRetryLoop newSessionFailRetryLoop(SessionFailRetryLoop.Mode mo * * @return true/false */ - public boolean isConnected() - { + public boolean isConnected() { return state.isConnected(); } @@ -180,12 +218,11 @@ public boolean isConnected() * @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 boolean blockUntilConnectedOrTimedOut() throws InterruptedException * * @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 void start() throws Exception 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 void close(int waitForShutdownTimeoutMs) * * @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 void setRetryPolicy(RetryPolicy policy) * * @return policy */ - public RetryPolicy getRetryPolicy() - { + public RetryPolicy getRetryPolicy() { return retryPolicy.get(); } @@ -276,8 +305,7 @@ public RetryPolicy getRetryPolicy() * @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 TimeTrace startTracer(String name) * @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 OperationTrace startAdvancedTracer(String name) * * @return tracing driver */ - public TracerDriver getTracerDriver() - { + public TracerDriver getTracerDriver() { return tracer.get(); } @@ -306,8 +332,7 @@ public TracerDriver getTracerDriver() * * @param tracer new tracing driver */ - public void setTracerDriver(TracerDriver tracer) - { + public void setTracerDriver(TracerDriver tracer) { this.tracer.set(tracer); } @@ -317,8 +342,7 @@ public void setTracerDriver(TracerDriver tracer) * * @return connection string */ - public String getCurrentConnectionString() - { + public String getCurrentConnectionString() { return state.getEnsembleProvider().getConnectionString(); } @@ -327,8 +351,7 @@ public String getCurrentConnectionString() * * @return timeout */ - public int getConnectionTimeoutMs() - { + public int getConnectionTimeoutMs() { return connectionTimeoutMs; } @@ -337,8 +360,7 @@ public int getConnectionTimeoutMs() * * @throws Exception errors */ - public void reset() throws Exception - { + public void reset() throws Exception { state.reset(); } @@ -348,8 +370,7 @@ public void reset() throws Exception * * @return the current instance index */ - public long getInstanceIndex() - { + public long getInstanceIndex() { return state.getInstanceIndex(); } @@ -358,18 +379,15 @@ public long getInstanceIndex() * * @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 @@ void removeParentWatcher(Watcher watcher) * * @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 void process(WatchedEvent event) 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 a8c6d53d3..e178177c5 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.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 @@ ZooKeeper getZooKeeper() throws Exception }; } - 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 31b4aa641..b6c5cff09 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 @@ 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 85a79caee..f6c160a9d 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; /** *

Mechanism to perform an operation on Zookeeper that is safe against @@ -57,15 +57,13 @@ * and if it becomes an interface we risk {@link java.lang.IncompatibleClassChangeError}s with clients. *

*/ -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 static RetrySleeper getDefaultRetrySleeper() * @return procedure result * @throws Exception any non-retriable errors */ - public static T callWithRetry(CuratorZookeeperClient client, Callable proc) throws Exception - { + public static T callWithRetry(CuratorZookeeperClient client, Callable 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 85991274a..318a76b9f 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 tracer) - { + RetryLoopImpl(RetryPolicy retryPolicy, AtomicReference 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 2f0a79ab6..b433e5055 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 @@ /** * 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 034563cd9..ccc907000 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 @@ /** * 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 e81c275ec..34e14e403 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 @@ 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; /** *

@@ -92,37 +92,32 @@ * } * */ -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 failedSessionThreads = Sets.newSetFromMap(Maps.newConcurrentMap()); + private static final Set failedSessionThreads = + Sets.newSetFromMap(Maps.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 enum Mode * @return procedure result * @throws Exception any non-retriable errors */ - public static T callWithRetry(CuratorZookeeperClient client, Mode mode, Callable proc) throws Exception - { - T result = null; - SessionFailRetryLoop retryLoop = client.newSessionFailRetryLoop(mode); + public static T callWithRetry(CuratorZookeeperClient client, Mode mode, Callable 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 void start() * * @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 boolean shouldContinue() * 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 void close() * @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 d645e36c3..9927e0b5e 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 @@ /** * {@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 723f59dbe..289db2e2e 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 TimeTrace(String name, TracerDriver driver) /** * 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 40e14bb50..96673422b 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; /** *

@@ -62,61 +62,48 @@ * *

*/ -public class ThreadLocalRetryLoop -{ +public class ThreadLocalRetryLoop { private static final Logger log = LoggerFactory.getLogger(ThreadLocalRetryLoop.class); private static final ThreadLocal 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 void takeException(Exception exception) throws Exception * @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 newRetryLoopSupplier) - { + public RetryLoop getRetryLoop(Supplier 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 RetryLoop getRetryLoop(Supplier newRetryLoopSupplier) * 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 2644f2fa0..800dd0cea 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 @@ /** * 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 6d1f6ac4d..1484b8e03 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 f84c1c56a..8ef3de09f 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 69021ed29..89fad26b8 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 @@ /** * 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 24f32f067..f52456d45 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 95a0511a2..c8ca4e64c 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 @@ 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 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 FixedEnsembleProvider(String connectionString) * @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 b85588c63..a53884a0e 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 @@ /** * 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 e9f56f309..929b3b372 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 ExponentialBackoffRetry(int baseSleepTimeMs, int maxRetries) * @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 c84313839..a4d148fe7 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 allowsRetry. */ -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 71b5ed784..1ff49c342 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 @@ /** * 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 cac6e0a5c..89b6bfadc 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 @@ /** * 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 3ce006e05..24fb94ee9 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 @@ /** * 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 8b729f530..a5d256845 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 @@ public boolean allowRetry(int retryCount, long elapsedTimeMs, RetrySleeper sleep 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 29089637e..f388305a2 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.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> futures = Sets.newSetFromMap(Maps., Boolean>newConcurrentMap()); private final ExecutorService executorService; private final boolean shutdownOnClose; protected final AtomicBoolean isOpen = new AtomicBoolean(true); - protected class InternalScheduledFutureTask implements Future - { + protected class InternalScheduledFutureTask implements Future { 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 extends FutureTask - { + protected class InternalFutureTask extends FutureTask { private final RunnableFuture task; - InternalFutureTask(RunnableFuture task) - { + InternalFutureTask(RunnableFuture task) { super(task, null); this.task = task; futures.add(task); } - protected void done() - { + protected void done() { futures.remove(task); } } @@ -105,17 +94,15 @@ protected void done() /** * @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 CloseableExecutorService(ExecutorService executorService, boolean shutdow * * @return true 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 @@ int size() * Closes any tasks currently in progress */ @Override - public void close() - { + public void close() { isOpen.set(false); Iterator> 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 void close() * @param task the task to submit * @return a future to watch the task */ - public Future submit(Callable task) - { + public Future submit(Callable task) { Preconditions.checkState(isOpen.get(), "CloseableExecutorService is closed"); InternalFutureTask futureTask = new InternalFutureTask(new FutureTask(task)); @@ -183,8 +164,7 @@ public Future submit(Callable task) * @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 futureTask = new InternalFutureTask(new FutureTask(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 5b832b741..8fbc420ee 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 @@ * 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 CloseableScheduledExecutorService(ScheduledExecutorService scheduledExecu * @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 CloseableScheduledExecutorService(ScheduledExecutorService scheduledExecu * the task and whose get() method will return * null 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 futureTask = new InternalFutureTask(new FutureTask(task, null)); @@ -91,11 +88,11 @@ public Future schedule(Runnable task, long delay, TimeUnit unit) * the task, and whose get() 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 fd0a84f98..63fc0fe7d 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 https://issues.apache.org/jira/browse/CURATOR-85 *

*/ - 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 5e5f2987b..03545cdea 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 6a8d6e832..10821cfe6 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 @@ * 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 0cc4227a5..a99348cc1 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 5439421a6..22dd1f65c 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 c9bf1971d..af3e4b26c 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.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 2843f3445..ce23cbd81 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; /** *

@@ -51,32 +51,27 @@ * @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; - 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 EnsurePath(String path) * @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 EnsurePath(String path, InternalACLProvider aclProvider) * @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 void ensure(CuratorZookeeperClient client) throws Exception * * @return view */ - public EnsurePath excludingLast() - { + public EnsurePath excludingLast() { return new EnsurePath(path, helper, false, aclProvider); } - protected EnsurePath(String path, AtomicReference helper, boolean makeLastNode, InternalACLProvider aclProvider) - { + protected EnsurePath( + String path, AtomicReference helper, boolean makeLastNode, InternalACLProvider aclProvider) { this.path = path; this.makeLastNode = makeLastNode; this.aclProvider = aclProvider; @@ -126,40 +118,30 @@ protected EnsurePath(String path, AtomicReference helper, boolean makeLa * * @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() - { - @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() { + @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 932c2274e..64e813184 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 @@ * 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 void propagate() * * @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 13e79e54c..caba991b3 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 getAclForPath(String path); + public List 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 cb36a7295..22be8ba6a 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 @@ 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 110f3b0ee..d8c7af4d9 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 static String validatePath(String path) throws IllegalArgumentException { 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 static String validatePath(String path) throws IllegalArgumentException { 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 static String validatePath(String path) throws IllegalArgumentException { } 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 a89963e13..7c2a80104 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 @@ 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 9ac88e168..5364ab5ce 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.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 static CreateMode getContainerCreateMode() * * @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 @@ private static class CreateModeHolder * @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 static String fixForNamespace(String namespace, String path) * @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 static String fixForNamespace(String namespace, String path, boolean isSe * @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 int hashCode() } @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 String toString() * @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 static String extractSequentialSuffix(String path) { 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 static String extractSequentialSuffix(String path) { * @param path the path * @return an array of parts */ - public static List split(String path) - { + public static List split(String path) { PathUtils.validatePath(path); return PATH_SPLITTER.splitToList(path); } @@ -261,8 +233,7 @@ public static List split(String path) * @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 static void mkdirs(ZooKeeper zookeeper, String path) throws InterruptedEx * @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 static void mkdirs(ZooKeeper zookeeper, String path, boolean makeLastNode * @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 static void mkdirs(ZooKeeper zookeeper, String path, boolean makeLastNode * @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 = 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 static void mkdirs(ZooKeeper zookeeper, String path, boolean makeLastNode * @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 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 static void deleteChildren(ZooKeeper zookeeper, String path, boolean dele * @throws InterruptedException thread interruption * @throws org.apache.zookeeper.KeeperException zookeeper errors */ - public static List getSortedChildren(ZooKeeper zookeeper, String path) throws InterruptedException, KeeperException - { + public static List getSortedChildren(ZooKeeper zookeeper, String path) + throws InterruptedException, KeeperException { List children = zookeeper.getChildren(path, false); List sortedList = Lists.newArrayList(children); Collections.sort(sortedList); @@ -431,8 +384,7 @@ public static List getSortedChildren(ZooKeeper zookeeper, String path) t * @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 static String makePath(String parent, String child) * @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 static String makePath(String parent, String firstChild, String... restCh 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 static String makePath(String parent, String firstChild, String... restCh } } - private static int nullableStringLength(String s) - { + private static int nullableStringLength(String s) { return s != null ? s.length() : 0; } @@ -495,31 +439,24 @@ private static int nullableStringLength(String s) * @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 @@ private static void joinPath(StringBuilder path, String parent, String child) 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 @@ private static void joinPath(StringBuilder path, String parent, String child) 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 eaa80ebb7..f15aaccb4 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.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 a81dbcbe0..58946934d 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.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.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 void testReconnect() throws Exception 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 dffc7b637..11e7de7b6 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.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.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.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.any(), anyBoolean()); @@ -71,51 +67,39 @@ public void testBasic() throws Exception } @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.any(), anyBoolean())).thenAnswer - ( - new Answer() - { - @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.any(), anyBoolean())).thenAnswer(new Answer() { + @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() - { - @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() { + @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 73020ede7..87217875d 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 void testIsZk37() throws Exception { } @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 69ebbae09..ff2491b4f 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.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.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 void testRetryForever() throws Exception } @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 7459c1e72..0b509e848 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.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() - { - @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() { + @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() - { - @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() { + @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() - { - @Override - public Object call() throws Exception - { - RetryLoop.callWithRetry - ( - client, - new Callable() - { - @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() { + @Override + public Object call() throws Exception { + RetryLoop.callWithRetry(client, new Callable() { + @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() - { - @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() { + @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() - { - @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() { + @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() - { - @Override - public Object call() throws Exception - { - RetryLoop.callWithRetry - ( - client, - new Callable() - { - @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() { + @Override + public Object call() throws Exception { + RetryLoop.callWithRetry(client, new Callable() { + @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 1a3fa72fc..8760607ee 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 @@ 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.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) () -> { - 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) () -> { + 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 void testBasicCallable() throws InterruptedException } @Test - public void testListeningRunnable() throws InterruptedException - { + public void testListeningRunnable() throws InterruptedException { CloseableExecutorService service = new CloseableExecutorService(executorService); List> 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 void testListeningRunnable() throws InterruptedException } @Test - public void testListeningCallable() throws InterruptedException - { + public void testListeningCallable() throws InterruptedException { CloseableExecutorService service = new CloseableExecutorService(executorService); final CountDownLatch startLatch = new CountDownLatch(QTY); List> futures = Lists.newArrayList(); - for ( int i = 0; i < QTY; ++i ) - { - Future future = service.submit - ( - (Callable) () -> { - 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) () -> { + 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 void testListeningCallable() throws InterruptedException } @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 void testPartialRunnable() throws InterruptedException 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 e854a9f0d..42ad7a6bb 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 @@ 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 void run() 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 05f46a88a..2b20d8826 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 void testMakePath() } @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 4b67a8c4f..89dc844e1 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 static void createThenWatch(CuratorFramework client, String path) // 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 watchedStage) - { + private static void handleWatchedStage(CompletionStage watchedStage) { // async handling of Watchers is complicated because watchers can trigger multiple times // and CompletionStage don't support this behavior @@ -119,8 +112,8 @@ private static void handleWatchedStage(CompletionStage watchedStag // 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 11da6ba4e..bb9aa9118 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 static void main(String[] args) throws Exception 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 static void main(String[] args) throws Exception } } - 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 cbfcc7a84..1e947d526 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.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 static void main(String[] args) throws Exception 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 void childEvent(CuratorFramework client, PathChildrenCacheEvent event) th 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 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 ): " + 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 ): " + 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 : Adds or updates a node with the given name"); System.out.println("remove : 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 5c49e078e..dbb0b2115 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 static void main(String[] args) throws Exception 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 e932fa5eb..3949b8b01 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.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.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 serviceDiscovery = null; - Map> providers = Maps.newHashMap(); - try - { + TestingServer server = new TestingServer(); + CuratorFramework client = null; + ServiceDiscovery serviceDiscovery = null; + Map> providers = Maps.newHashMap(); + try { client = CuratorFrameworkFactory.newClient(server.getConnectString(), new ExponentialBackoffRetry(1000, 3)); client.start(); - JsonInstanceSerializer serializer = new JsonInstanceSerializer(InstanceDetails.class); - serviceDiscovery = ServiceDiscoveryBuilder.builder(InstanceDetails.class).client(client).basePath(PATH).serializer(serializer).build(); + JsonInstanceSerializer serializer = + new JsonInstanceSerializer(InstanceDetails.class); + serviceDiscovery = ServiceDiscoveryBuilder.builder(InstanceDetails.class) + .client(client) + .basePath(PATH) + .serializer(serializer) + .build(); serviceDiscovery.start(); processCommands(serviceDiscovery, providers, client); - } - finally - { - for ( ServiceProvider cache : providers.values() ) - { + } finally { + for (ServiceProvider cache : providers.values()) { CloseableUtils.closeQuietly(cache); } @@ -79,165 +77,139 @@ public static void main(String[] args) throws Exception } } - private static void processCommands(ServiceDiscovery serviceDiscovery, Map> providers, CuratorFramework client) throws Exception - { + private static void processCommands( + ServiceDiscovery serviceDiscovery, + Map> providers, + CuratorFramework client) + throws Exception { // More scaffolding that does a simple command line processor printHelp(); - List servers = Lists.newArrayList(); - try - { - BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); - boolean done = false; - while ( !done ) - { + List 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 serviceDiscovery, Map> providers, String command) throws Exception - { + private static void listRandomInstance( + String[] args, + ServiceDiscovery serviceDiscovery, + Map> 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 ): " + command); return; } - String serviceName = args[0]; - ServiceProvider provider = providers.get(serviceName); - if ( provider == null ) - { - provider = serviceDiscovery.serviceProviderBuilder().serviceName(serviceName).providerStrategy(new RandomStrategy()).build(); + String serviceName = args[0]; + ServiceProvider provider = providers.get(serviceName); + if (provider == null) { + provider = serviceDiscovery + .serviceProviderBuilder() + .serviceName(serviceName) + .providerStrategy(new RandomStrategy()) + .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 instance = provider.getInstance(); - if ( instance == null ) - { + ServiceInstance instance = provider.getInstance(); + if (instance == null) { System.err.println("No instances named: " + serviceName); - } - else - { + } else { outputInstance(instance); } } - private static void listInstances(ServiceDiscovery serviceDiscovery) throws Exception - { + private static void listInstances(ServiceDiscovery serviceDiscovery) throws Exception { // This shows how to query all the instances in service discovery - try - { - Collection serviceNames = serviceDiscovery.queryForNames(); + try { + Collection serviceNames = serviceDiscovery.queryForNames(); System.out.println(serviceNames.size() + " type(s)"); - for ( String serviceName : serviceNames ) - { - Collection> instances = serviceDiscovery.queryForInstances(serviceName); + for (String serviceName : serviceNames) { + Collection> instances = + serviceDiscovery.queryForInstances(serviceName); System.out.println(serviceName); - for ( ServiceInstance instance : instances ) - { + for (ServiceInstance 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 instance) - { + private static void outputInstance(ServiceInstance instance) { System.out.println("\t" + instance.getPayload().getDescription() + ": " + instance.buildUriSpec()); } - private static void deleteInstance(String[] args, String command, List servers) - { + private static void deleteInstance(String[] args, String command, List 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 ): " + command); return; } - final String serviceName = args[0]; - ExampleServer server = Iterables.find - ( - servers, - new Predicate() - { - @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() { + @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 boolean apply(ExampleServer server) System.out.println("Removed a random instance of: " + serviceName); } - private static void addInstance(String[] args, CuratorFramework client, String command, List servers) throws Exception - { + private static void addInstance(String[] args, CuratorFramework client, String command, List 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 ): " + 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 : Adds a mock service with the given name and description"); System.out.println("delete : 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 9b461ee89..aabeeccac 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 serviceDiscovery; private final ServiceInstance 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.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 serializer = new JsonInstanceSerializer(InstanceDetails.class); + JsonInstanceSerializer serializer = + new JsonInstanceSerializer(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 getThisInstance() - { + public ServiceInstance 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 8c40a9795..8124cf629 100644 --- a/curator-examples/src/main/java/discovery/InstanceDetails.java +++ b/curator-examples/src/main/java/discovery/InstanceDetails.java @@ -26,27 +26,22 @@ * 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 31c799c38..aba6fac1c 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.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 static CuratorFramework createSimple(String connectionString) 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 8ac760985..9cde6287c 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 static void createIdempotent(CuratorFramework client, String path, b 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 void eventReceived(CuratorFramework client, CuratorEvent event) throws Ex 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 static void setDataIdempotent(CuratorFramework client, String path, 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 static void deleteIdempotent(CuratorFramework client, String path, i client.delete().quietly().forPath(path); } - public static List watchedGetChildren(CuratorFramework client, String path) throws Exception - { + public static List 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 static List watchedGetChildren(CuratorFramework client, String pa return client.getChildren().watched().forPath(path); } - public static List watchedGetChildren(CuratorFramework client, String path, Watcher watcher) throws Exception - { + public static List 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 49d7920e8..8e6fa5db1 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 transaction(CuratorFramework client) throws Exception - { +public class TransactionExamples { + public static Collection 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 results = client.transaction().forOperations(createOp, setDataOp, deleteOp); + Collection 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 3b9f22b7f..50965ff7e 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 ExampleClient(CuratorFramework client, String path, String name) 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 1c3de744a..c8e9fd8cd 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 clients = Lists.newArrayList(); - List 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 clients = Lists.newArrayList(); + List 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 static void main(String[] args) throws Exception 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 5c7cd1d9e..52fe9ae07 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 ac578e9bb..58650d6a0 100644 --- a/curator-examples/src/main/java/locking/FakeLimitedResource.java +++ b/curator-examples/src/main/java/locking/FakeLimitedResource.java @@ -24,25 +24,19 @@ /** * 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 bd2026e41..ec6a93215 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 task = new Callable() - { + ExecutorService service = Executors.newFixedThreadPool(QTY); + final TestingServer server = new TestingServer(); + try { + for (int i = 0; i < QTY; ++i) { + final int index = i; + Callable task = new Callable() { @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 Void call() throws Exception 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 c78a39bdb..5207c8fcc 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 5806ecbc9..064d00fd3 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 wrap(AsyncCuratorFramework client) - { +public class ModeledCuratorExamples { + public static ModeledFramework wrap(AsyncCuratorFramework client) { JacksonModelSerializer serializer = JacksonModelSerializer.build(PersonModel.class); // build a model specification - you can pre-build all the model specifications for your app at startup - ModelSpec modelSpec = ModelSpec.builder(ZPath.parse("/example/path"), serializer).build(); + ModelSpec 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 static ModeledFramework wrap(AsyncCuratorFramework client) return ModeledFramework.wrap(client, modelSpec); } - public static void createOrUpdate(ModeledFramework modeled, PersonModel model) - { + public static void createOrUpdate(ModeledFramework modeled, PersonModel model) { // change the affected path to be modeled's base path plus id: i.e. "/example/path/{id}" ModeledFramework atId = modeled.child(model.getId().getId()); @@ -51,16 +49,12 @@ public static void createOrUpdate(ModeledFramework modeled, PersonM atId.set(model); // note - this is async } - public static void readPerson(ModeledFramework modeled, String id, Consumer receiver) - { + public static void readPerson(ModeledFramework modeled, String id, Consumer 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 f747bf8f5..d07364dd0 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 resolved = modelSpec.resolved(model.getContainerType(), model.getId()); @@ -34,18 +32,15 @@ public static void createOrUpdate(PersonModelSpec modelSpec, PersonModel model) resolved.set(model); // note - this is async } - public static void readPerson(PersonModelSpec modelSpec, ContainerType containerType, PersonId id, Consumer receiver) - { + public static void readPerson( + PersonModelSpec modelSpec, ContainerType containerType, PersonId id, Consumer receiver) { ModeledFramework 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 143c8a463..3c5700ce0 100644 --- a/curator-examples/src/main/java/modeled/PersonId.java +++ b/curator-examples/src/main/java/modeled/PersonId.java @@ -21,51 +21,42 @@ 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 52be5d948..c3960412a 100644 --- a/curator-examples/src/main/java/modeled/PersonModel.java +++ b/curator-examples/src/main/java/modeled/PersonModel.java @@ -21,21 +21,18 @@ 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 PersonModel(PersonId id, ContainerType containerType, String firstName, S 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 int hashCode() } @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 79286ebb3..5251b2799 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.ModeledFramework; import org.apache.curator.x.async.modeled.ZPath; -public class PersonModelSpec -{ +public class PersonModelSpec { private final AsyncCuratorFramework client; private final ModelSpec modelSpec; - public PersonModelSpec(AsyncCuratorFramework client) - { + public PersonModelSpec(AsyncCuratorFramework client) { this.client = client; JacksonModelSerializer serializer = JacksonModelSerializer.build(PersonModel.class); @@ -39,8 +37,7 @@ public PersonModelSpec(AsyncCuratorFramework client) modelSpec = ModelSpec.builder(path, serializer).build(); } - public ModeledFramework resolved(ContainerType containerType, PersonId personId) - { + public ModeledFramework resolved(ContainerType containerType, PersonId personId) { ModelSpec 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 82212bf1d..c46b08c88 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.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 locationAvailableClient = TypedModeledFramework2.from( - ModeledFramework.builder(), - builder(LocationAvailable.class), - "/root/pubsub/messages/locations/{group}/{priority}/{id}" - ); + public static final TypedModeledFramework2 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 userCreatedClient = TypedModeledFramework2.from( - ModeledFramework.builder(), - builder(UserCreated.class), - "/root/pubsub/messages/users/{group}/{priority}/{id}" - ); + public static final TypedModeledFramework2 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 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 ModelSpecBuilder builder(Class clazz) - { + private static ModelSpecBuilder builder(Class 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 73267e7b7..4c33322d4 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.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 Publisher(AsyncCuratorFramework client) * * @param instance instance to publish */ - public void publishInstance(Instance instance) - { + public void publishInstance(Instance instance) { ModeledFramework 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 void publishInstance(Instance instance) * * @param instances instances to publish */ - public void publishInstances(List instances) - { + public void publishInstances(List instances) { List 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 void publishInstances(List instances) * @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 void publishLocationAvailable(Group group, LocationAvailable locationAvai * @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 void publishUserCreated(Group group, UserCreated userCreated) * @param group group * @param locationsAvailable messages to publish */ - public void publishLocationsAvailable(Group group, List locationsAvailable) - { + public void publishLocationsAvailable(Group group, List locationsAvailable) { publishMessages(Clients.locationAvailableClient, group, locationsAvailable); } @@ -117,13 +109,12 @@ public void publishLocationsAvailable(Group group, List locat * @param group group * @param usersCreated messages to publish */ - public void publishUsersCreated(Group group, List usersCreated) - { + public void publishUsersCreated(Group group, List usersCreated) { publishMessages(Clients.userCreatedClient, group, usersCreated); } - private void publishMessage(TypedModeledFramework2 typedClient, Group group, T message) - { + private void publishMessage( + TypedModeledFramework2 typedClient, Group group, T message) { ModeledFramework resolvedClient = typedClient.resolved(client, group, message.getPriority()); resolvedClient.set(message).exceptionally(e -> { log.error("Could not publish message: " + message, e); @@ -131,14 +122,13 @@ private void publishMessage(TypedModeledFramework2 void publishMessages(TypedModeledFramework2 typedClient, Group group, List messages) - { + private void publishMessages( + TypedModeledFramework2 typedClient, Group group, List messages) { List 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 861059f83..727b76b25 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.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 void start() } @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 void close() throws IOException 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 instances = IntStream.range(1, 10) - .mapToObj(__ -> new Instance(nextId(), random(InstanceType.values()), random(hostnames), random(ports))) - .collect(Collectors.toList()); + case 1: { + List 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 locationsAvailable = IntStream.range(1, 10) - .mapToObj(__ -> new LocationAvailable(nextId(), random(Priority.values()), random(locations), random(durations))) - .collect(Collectors.toList()); + case 3: { + List 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 usersCreated = IntStream.range(1, 10) - .mapToObj(__ -> new UserCreated(nextId(), random(Priority.values()), random(locations), random(positions))) - .collect(Collectors.toList()); + case 5: { + List 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 @@ private void publishSomething(Publisher publisher) } } - private ModeledCacheListener generalListener() - { - return (type, path, stat, model) -> System.out.println(String.format("Subscribed %s @ %s", model.getClass().getSimpleName(), path)); + private ModeledCacheListener generalListener() { + return (type, path, stat, model) -> System.out.println( + String.format("Subscribed %s @ %s", model.getClass().getSimpleName(), path)); } @SafeVarargs - private final T random(T... tab) - { + private final 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 ec2561a0b..aa8d09fb1 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.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 Subscriber(AsyncCuratorFramework client) * @param priority priority to listen for * @return CachedModeledFramework instance (already started) */ - public CachedModeledFramework startLocationAvailableSubscriber(Group group, Priority priority) - { + public CachedModeledFramework startLocationAvailableSubscriber(Group group, Priority priority) { return startSubscriber(Clients.locationAvailableClient, group, priority); } @@ -58,8 +55,7 @@ public CachedModeledFramework startLocationAvailableSubscribe * @param priority priority to listen for * @return CachedModeledFramework instance (already started) */ - public CachedModeledFramework startUserCreatedSubscriber(Group group, Priority priority) - { + public CachedModeledFramework startUserCreatedSubscriber(Group group, Priority priority) { return startSubscriber(Clients.userCreatedClient, group, priority); } @@ -69,16 +65,17 @@ public CachedModeledFramework startUserCreatedSubscriber(Group grou * @param instanceType type to listen for * @return CachedModeledFramework instance (already started) */ - public CachedModeledFramework startInstanceSubscriber(InstanceType instanceType) - { - CachedModeledFramework resolved = Clients.instanceClient.resolved(client, instanceType).cached(); + public CachedModeledFramework startInstanceSubscriber(InstanceType instanceType) { + CachedModeledFramework resolved = + Clients.instanceClient.resolved(client, instanceType).cached(); resolved.start(); return resolved; } - private CachedModeledFramework startSubscriber(TypedModeledFramework2 typedClient, Group group, Priority priority) - { - CachedModeledFramework resolved = typedClient.resolved(client, group, priority).cached(); + private CachedModeledFramework startSubscriber( + TypedModeledFramework2 typedClient, Group group, Priority priority) { + CachedModeledFramework 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 d762373bc..375a79a81 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 90fcb21f5..aa7909872 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 0baa61718..1436b1df3 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 @@ 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 68180f9d1..77195bffa 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 1253779ec..a590205a0 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 81e36250f..340aced95 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 c0448306e..ca026e561 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 7a7a564f9..7279a0c95 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 @@ 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 byte[] getAuth() { } @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 bbcd3cfc0..25b701ca5 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.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 postSafeNotify(Object monitorHolder) - { + default CompletableFuture postSafeNotify(Object monitorHolder) { return runSafe(() -> { - synchronized(monitorHolder) { + synchronized (monitorHolder) { monitorHolder.notifyAll(); } }); @@ -358,7 +356,7 @@ default CompletableFuture postSafeNotify(Object monitorHolder) /** * 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 54ace5090..59ffb4288 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.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.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 static Builder builder() * @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 static CuratorFramework newClient(String connectString, RetryPolicy retry * @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 static CuratorFramework newClient(String connectString, int sessionTimeou * @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 static CuratorFramework newClient(String connectString, int sessionTimeou * * @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 static class Builder 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 static class Builder * * @return new CuratorFramework */ - public CuratorFramework build() - { + public CuratorFramework build() { return new CuratorFrameworkImpl(this); } @@ -196,8 +192,7 @@ public CuratorFramework build() * * @return temp instance */ - public CuratorTempFramework buildTemp() - { + public CuratorTempFramework buildTemp() { return buildTemp(DEFAULT_INACTIVE_THRESHOLD_MS, TimeUnit.MILLISECONDS); } @@ -211,8 +206,7 @@ public CuratorTempFramework buildTemp() * @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 CuratorTempFramework buildTemp(long inactiveThreshold, TimeUnit unit) * @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 Builder authorization(String scheme, byte[] auth) * @param authInfos list of {@link AuthInfo} objects with scheme and auth * @return this */ - public Builder authorization(List authInfos) - { + public Builder authorization(List authInfos) { this.authInfos = ImmutableList.copyOf(authInfos); return this; } @@ -252,8 +245,7 @@ public Builder authorization(List authInfos) * @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 Builder connectString(String connectString) * @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 Builder ensembleProvider(EnsembleProvider ensembleProvider) /** * Allows to configure if the ensemble configuration changes will be watched. * The default value is {@code true}.
- * + * * 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
- * + * * @param withEnsembleTracker use {@code false} if you want to avoid following ensemble configuration changes * @return this */ @@ -302,8 +293,7 @@ public boolean withEnsembleTracker() { * @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 Builder defaultData(byte[] defaultData) * @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 Builder namespace(String namespace) * @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 Builder sessionTimeoutMs(int sessionTimeoutMs) * @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 Builder connectionTimeoutMs(int connectionTimeoutMs) * @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 Builder maxCloseWaitMs(int maxCloseWaitMs) * @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 Builder retryPolicy(RetryPolicy retryPolicy) * @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 Builder threadFactory(ThreadFactory threadFactory) * @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 Builder compressionProvider(CompressionProvider compressionProvider) * @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 Builder zookeeperFactory(ZookeeperFactory zookeeperFactory) * @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 Builder aclProvider(ACLProvider aclProvider) * for details * @return this */ - public Builder canBeReadOnly(boolean canBeReadOnly) - { + public Builder canBeReadOnly(boolean canBeReadOnly) { this.canBeReadOnly = canBeReadOnly; return this; } @@ -421,8 +401,7 @@ public Builder canBeReadOnly(boolean canBeReadOnly) * * @return this */ - public Builder dontUseContainerParents() - { + public Builder dontUseContainerParents() { this.useContainerParentsIfAvailable = false; return this; } @@ -434,8 +413,7 @@ public Builder dontUseContainerParents() * @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 Builder connectionStateErrorPolicy(ConnectionStateErrorPolicy connectionS * @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 Builder simulatedSessionExpirationPercent(int simulatedSessionExpirationP 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 Builder zkClientConfig(ZKClientConfig zkClientConfig) { * @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 Builder schemaSet(SchemaSet schemaSet) * @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 Builder runSafeService(Executor runSafeService) * @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 getAuthInfos() - { + public List 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 b4af0e3af..72bc0ce8f 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; /** *

@@ -35,12 +35,11 @@ * http://whilefalse.blogspot.com/2012/12/building-global-highly-available.html *

*/ -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 f3637ac8b..5d07982b8 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 @@ * 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 EnsureContainers(CuratorFramework client, String path) * * @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 void ensure() throws Exception /** * 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 fb9235412..c6f1b8f3d 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 3e3c95288..950aeec71 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 extends - ParentACLable>, - BackgroundPathAndBytesable -{ -} +public interface ACLBackgroundPathAndBytesable + extends ParentACLable>, BackgroundPathAndBytesable {} 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 cefd44fbc..3c83149a1 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 extends - ACLBackgroundPathAndBytesable, - BackgroundPathAndBytesable, - CreateModable> -{ -} +public interface ACLCreateModeBackgroundPathAndBytesable + extends ACLBackgroundPathAndBytesable, + BackgroundPathAndBytesable, + CreateModable> {} 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 43f095156..23a523227 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 extends - ACLPathAndBytesable, - CreateModable> -{ -} +public interface ACLCreateModePathAndBytesable + extends ACLPathAndBytesable, CreateModable> {} 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 ec3ea9617..8d81abc5f 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 extends - ACLCreateModeBackgroundPathAndBytesable, - Statable> -{ -} +public interface ACLCreateModeStatBackgroundPathAndBytesable + extends ACLCreateModeBackgroundPathAndBytesable, Statable> {} 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 39047b1dd..5da9b019b 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 extends - ParentACLable>, - PathAndBytesable -{ -} +public interface ACLPathAndBytesable extends ParentACLable>, PathAndBytesable {} 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 3d5d04d43..89a1c96f5 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}). * * @return default ACL list */ - public List getDefaultAcl(); + public List getDefaultAcl(); /** * Return the ACL list to use for the given path @@ -39,5 +38,5 @@ public interface ACLProvider extends InternalACLProvider * @param path path (NOTE: might be null) * @return ACL list */ - public List getAclForPath(String path); + public List getAclForPath(String path); } diff --git a/curator-framework/src/main/java/org/apache/curator/framework/api/ACLable.java b/curator-framework/src/main/java/org/apache/curator/framework/api/ACLable.java index a1964000e..553b3b1ee 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/api/ACLable.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/api/ACLable.java @@ -19,12 +19,11 @@ package org.apache.curator.framework.api; +import java.util.List; import org.apache.zookeeper.ZooDefs; import org.apache.zookeeper.data.ACL; -import java.util.List; -public interface ACLable -{ +public interface ACLable { /** * Set an ACL list (default is {@link ZooDefs.Ids#OPEN_ACL_UNSAFE}) * diff --git a/curator-framework/src/main/java/org/apache/curator/framework/api/ACLableExistBuilderMain.java b/curator-framework/src/main/java/org/apache/curator/framework/api/ACLableExistBuilderMain.java index 33f4a49bf..2d4021a56 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/api/ACLableExistBuilderMain.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/api/ACLableExistBuilderMain.java @@ -19,8 +19,4 @@ package org.apache.curator.framework.api; -public interface ACLableExistBuilderMain extends - ExistsBuilderMain, - ACLable -{ -} +public interface ACLableExistBuilderMain extends ExistsBuilderMain, ACLable {} diff --git a/curator-framework/src/main/java/org/apache/curator/framework/api/AddStatConfigEnsembleable.java b/curator-framework/src/main/java/org/apache/curator/framework/api/AddStatConfigEnsembleable.java index 98b1ea37f..fcb223c07 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/api/AddStatConfigEnsembleable.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/api/AddStatConfigEnsembleable.java @@ -24,10 +24,5 @@ * This builder has access only to the non-incremental reconfiguration methods withMembers, so that we prevent * mixing concepts that can't be used together. */ -public interface AddStatConfigEnsembleable extends - Addable>, - ConfigureEnsembleable, - Statable -{ - -} +public interface AddStatConfigEnsembleable + extends Addable>, ConfigureEnsembleable, Statable {} diff --git a/curator-framework/src/main/java/org/apache/curator/framework/api/AddWatchBuilder.java b/curator-framework/src/main/java/org/apache/curator/framework/api/AddWatchBuilder.java index bc73ff2fa..dab64c604 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/api/AddWatchBuilder.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/api/AddWatchBuilder.java @@ -21,8 +21,7 @@ import org.apache.zookeeper.AddWatchMode; -public interface AddWatchBuilder extends AddWatchBuilder2 -{ +public interface AddWatchBuilder extends AddWatchBuilder2 { /** * The mode to use. By default, {@link org.apache.zookeeper.AddWatchMode#PERSISTENT_RECURSIVE} is used * @@ -30,4 +29,4 @@ public interface AddWatchBuilder extends AddWatchBuilder2 * @return this */ AddWatchBuilder2 withMode(AddWatchMode mode); -} \ No newline at end of file +} diff --git a/curator-framework/src/main/java/org/apache/curator/framework/api/AddWatchBuilder2.java b/curator-framework/src/main/java/org/apache/curator/framework/api/AddWatchBuilder2.java index aeec8fbb5..7d6e3a0cc 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/api/AddWatchBuilder2.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/api/AddWatchBuilder2.java @@ -19,9 +19,5 @@ package org.apache.curator.framework.api; -public interface AddWatchBuilder2 extends - Backgroundable>>, - WatchableBase>, - Pathable -{ -} \ No newline at end of file +public interface AddWatchBuilder2 + extends Backgroundable>>, WatchableBase>, Pathable {} diff --git a/curator-framework/src/main/java/org/apache/curator/framework/api/Addable.java b/curator-framework/src/main/java/org/apache/curator/framework/api/Addable.java index ea53ad73e..c7b54a6ca 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/api/Addable.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/api/Addable.java @@ -21,8 +21,7 @@ import java.util.List; -public interface Addable -{ +public interface Addable { /** * Sets one or more members that are meant to be part of the ensemble. * The expected format is server.[id]=[hostname]:[peer port]:[election port]:[type];[client port] diff --git a/curator-framework/src/main/java/org/apache/curator/framework/api/AsyncReconfigurable.java b/curator-framework/src/main/java/org/apache/curator/framework/api/AsyncReconfigurable.java index 73f83e751..d8520ee47 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/api/AsyncReconfigurable.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/api/AsyncReconfigurable.java @@ -19,7 +19,7 @@ package org.apache.curator.framework.api; -public interface AsyncReconfigurable { +public interface AsyncReconfigurable { /** * Sets the configuration version to use. diff --git a/curator-framework/src/main/java/org/apache/curator/framework/api/BackgroundCallback.java b/curator-framework/src/main/java/org/apache/curator/framework/api/BackgroundCallback.java index 3c391ce39..313f1ffb8 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/api/BackgroundCallback.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/api/BackgroundCallback.java @@ -24,8 +24,7 @@ /** * Functor for an async background operation */ -public interface BackgroundCallback -{ +public interface BackgroundCallback { /** * Called when the async background operation completes * diff --git a/curator-framework/src/main/java/org/apache/curator/framework/api/BackgroundEnsembleable.java b/curator-framework/src/main/java/org/apache/curator/framework/api/BackgroundEnsembleable.java index 8abfb4b28..4128e3a12 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/api/BackgroundEnsembleable.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/api/BackgroundEnsembleable.java @@ -19,8 +19,4 @@ package org.apache.curator.framework.api; -public interface BackgroundEnsembleable extends - Backgroundable>, - Ensembleable -{ -} +public interface BackgroundEnsembleable extends Backgroundable>, Ensembleable {} diff --git a/curator-framework/src/main/java/org/apache/curator/framework/api/BackgroundPathAndBytesable.java b/curator-framework/src/main/java/org/apache/curator/framework/api/BackgroundPathAndBytesable.java index c189457f9..1839a157c 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/api/BackgroundPathAndBytesable.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/api/BackgroundPathAndBytesable.java @@ -19,8 +19,5 @@ package org.apache.curator.framework.api; -public interface BackgroundPathAndBytesable extends - Backgroundable>, - PathAndBytesable -{ -} +public interface BackgroundPathAndBytesable + extends Backgroundable>, PathAndBytesable {} diff --git a/curator-framework/src/main/java/org/apache/curator/framework/api/BackgroundPathable.java b/curator-framework/src/main/java/org/apache/curator/framework/api/BackgroundPathable.java index 972163b21..08e54f32a 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/api/BackgroundPathable.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/api/BackgroundPathable.java @@ -19,8 +19,4 @@ package org.apache.curator.framework.api; -public interface BackgroundPathable extends - Backgroundable>, - Pathable -{ -} +public interface BackgroundPathable extends Backgroundable>, Pathable {} diff --git a/curator-framework/src/main/java/org/apache/curator/framework/api/BackgroundPathableQuietlyable.java b/curator-framework/src/main/java/org/apache/curator/framework/api/BackgroundPathableQuietlyable.java index 4ea9f19af..f28dca582 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/api/BackgroundPathableQuietlyable.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/api/BackgroundPathableQuietlyable.java @@ -19,6 +19,4 @@ package org.apache.curator.framework.api; -public interface BackgroundPathableQuietlyable extends BackgroundPathable, Quietly> -{ -} +public interface BackgroundPathableQuietlyable extends BackgroundPathable, Quietly> {} diff --git a/curator-framework/src/main/java/org/apache/curator/framework/api/BackgroundVersionable.java b/curator-framework/src/main/java/org/apache/curator/framework/api/BackgroundVersionable.java index 3b5660e15..ca883eda9 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/api/BackgroundVersionable.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/api/BackgroundVersionable.java @@ -19,8 +19,4 @@ package org.apache.curator.framework.api; -public interface BackgroundVersionable extends - BackgroundPathable, - Versionable> -{ -} +public interface BackgroundVersionable extends BackgroundPathable, Versionable> {} diff --git a/curator-framework/src/main/java/org/apache/curator/framework/api/Backgroundable.java b/curator-framework/src/main/java/org/apache/curator/framework/api/Backgroundable.java index 05b3a967a..bdb0f3bb9 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/api/Backgroundable.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/api/Backgroundable.java @@ -21,8 +21,7 @@ import java.util.concurrent.Executor; -public interface Backgroundable -{ +public interface Backgroundable { /** * Perform the action in the background * diff --git a/curator-framework/src/main/java/org/apache/curator/framework/api/ChildrenDeletable.java b/curator-framework/src/main/java/org/apache/curator/framework/api/ChildrenDeletable.java index 9aa13ea53..898e5b332 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/api/ChildrenDeletable.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/api/ChildrenDeletable.java @@ -19,8 +19,7 @@ package org.apache.curator.framework.api; -public interface ChildrenDeletable extends BackgroundVersionable -{ +public interface ChildrenDeletable extends BackgroundVersionable { /** *

diff --git a/curator-framework/src/main/java/org/apache/curator/framework/api/Compressible.java b/curator-framework/src/main/java/org/apache/curator/framework/api/Compressible.java index 06891ba59..1aaca83c7 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/api/Compressible.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/api/Compressible.java @@ -19,8 +19,7 @@ package org.apache.curator.framework.api; -public interface Compressible -{ +public interface Compressible { /** * Cause the data to be compressed using the configured compression provider * diff --git a/curator-framework/src/main/java/org/apache/curator/framework/api/CompressionProvider.java b/curator-framework/src/main/java/org/apache/curator/framework/api/CompressionProvider.java index 22ed20d25..91809c7f2 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/api/CompressionProvider.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/api/CompressionProvider.java @@ -19,9 +19,8 @@ package org.apache.curator.framework.api; -public interface CompressionProvider -{ - public byte[] compress(String path, byte[] data) throws Exception; +public interface CompressionProvider { + public byte[] compress(String path, byte[] data) throws Exception; - public byte[] decompress(String path, byte[] compressedData) throws Exception; + public byte[] decompress(String path, byte[] compressedData) throws Exception; } diff --git a/curator-framework/src/main/java/org/apache/curator/framework/api/ConfigureEnsembleable.java b/curator-framework/src/main/java/org/apache/curator/framework/api/ConfigureEnsembleable.java index bcb127f3a..3d37b48fe 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/api/ConfigureEnsembleable.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/api/ConfigureEnsembleable.java @@ -19,9 +19,7 @@ package org.apache.curator.framework.api; -public interface ConfigureEnsembleable extends - Ensembleable -{ +public interface ConfigureEnsembleable extends Ensembleable { /** * Sets the configuration version to use. diff --git a/curator-framework/src/main/java/org/apache/curator/framework/api/CreateBackgroundModeACLable.java b/curator-framework/src/main/java/org/apache/curator/framework/api/CreateBackgroundModeACLable.java index c500e9f13..c7eba5897 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/api/CreateBackgroundModeACLable.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/api/CreateBackgroundModeACLable.java @@ -21,17 +21,16 @@ import org.apache.zookeeper.CreateMode; -public interface CreateBackgroundModeACLable extends - BackgroundPathAndBytesable, - CreateModable>, - ACLCreateModeBackgroundPathAndBytesable -{ +public interface CreateBackgroundModeACLable + extends BackgroundPathAndBytesable, + CreateModable>, + ACLCreateModeBackgroundPathAndBytesable { /** * Causes any parent nodes to get created if they haven't already been * * @return this */ - public ACLCreateModePathAndBytesable creatingParentsIfNeeded(); + public ACLCreateModePathAndBytesable creatingParentsIfNeeded(); /** * Causes any parent nodes to get created using {@link CreateMode#CONTAINER} if they haven't already been. @@ -66,5 +65,5 @@ public interface CreateBackgroundModeACLable extends * * @return this */ - public ACLPathAndBytesable withProtectedEphemeralSequential(); + public ACLPathAndBytesable withProtectedEphemeralSequential(); } diff --git a/curator-framework/src/main/java/org/apache/curator/framework/api/CreateBackgroundModeStatACLable.java b/curator-framework/src/main/java/org/apache/curator/framework/api/CreateBackgroundModeStatACLable.java index 304a02249..d8b533f0d 100755 --- a/curator-framework/src/main/java/org/apache/curator/framework/api/CreateBackgroundModeStatACLable.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/api/CreateBackgroundModeStatACLable.java @@ -21,18 +21,17 @@ import org.apache.zookeeper.CreateMode; -public interface CreateBackgroundModeStatACLable extends - BackgroundPathAndBytesable, - CreateModable>, - ACLCreateModeBackgroundPathAndBytesable, - Statable -{ +public interface CreateBackgroundModeStatACLable + extends BackgroundPathAndBytesable, + CreateModable>, + ACLCreateModeBackgroundPathAndBytesable, + Statable { /** * Causes any parent nodes to get created if they haven't already been * * @return this */ - public ACLCreateModePathAndBytesable creatingParentsIfNeeded(); + public ACLCreateModePathAndBytesable creatingParentsIfNeeded(); /** * Causes any parent nodes to get created using {@link CreateMode#CONTAINER} if they haven't already been. @@ -67,5 +66,5 @@ public interface CreateBackgroundModeStatACLable extends * * @return this */ - public ACLPathAndBytesable withProtectedEphemeralSequential(); + public ACLPathAndBytesable withProtectedEphemeralSequential(); } diff --git a/curator-framework/src/main/java/org/apache/curator/framework/api/CreateBuilder.java b/curator-framework/src/main/java/org/apache/curator/framework/api/CreateBuilder.java index 68ad0c14f..8879f538f 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/api/CreateBuilder.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/api/CreateBuilder.java @@ -19,8 +19,7 @@ package org.apache.curator.framework.api; -public interface CreateBuilder extends CreateBuilderMain, Idempotentable -{ +public interface CreateBuilder extends CreateBuilderMain, Idempotentable { /** * Specify a TTL when mode is {@link org.apache.zookeeper.CreateMode#PERSISTENT_WITH_TTL} or * {@link org.apache.zookeeper.CreateMode#PERSISTENT_SEQUENTIAL_WITH_TTL}. If diff --git a/curator-framework/src/main/java/org/apache/curator/framework/api/CreateBuilder2.java b/curator-framework/src/main/java/org/apache/curator/framework/api/CreateBuilder2.java index c910586af..1b2cb87ac 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/api/CreateBuilder2.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/api/CreateBuilder2.java @@ -19,8 +19,7 @@ package org.apache.curator.framework.api; -public interface CreateBuilder2 extends CreateBuilderMain -{ +public interface CreateBuilder2 extends CreateBuilderMain { /** * Specify a TTL when mode is {@link org.apache.zookeeper.CreateMode#PERSISTENT_WITH_TTL} or * {@link org.apache.zookeeper.CreateMode#PERSISTENT_SEQUENTIAL_WITH_TTL}. If diff --git a/curator-framework/src/main/java/org/apache/curator/framework/api/CreateBuilderMain.java b/curator-framework/src/main/java/org/apache/curator/framework/api/CreateBuilderMain.java index 0b3bd1e61..3bcfc62d5 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/api/CreateBuilderMain.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/api/CreateBuilderMain.java @@ -20,17 +20,15 @@ package org.apache.curator.framework.api; import java.util.UUID; - import org.apache.curator.framework.imps.ProtectedUtils; import org.apache.zookeeper.CreateMode; -public interface CreateBuilderMain extends - BackgroundPathAndBytesable, - CreateModable>, - ACLCreateModeBackgroundPathAndBytesable, - Compressible, - Statable> -{ +public interface CreateBuilderMain + extends BackgroundPathAndBytesable, + CreateModable>, + ACLCreateModeBackgroundPathAndBytesable, + Compressible, + Statable> { /** * Causes any parent nodes to get created if they haven't already been @@ -57,7 +55,7 @@ public interface CreateBuilderMain extends * @return this */ @Deprecated - public ACLPathAndBytesable withProtectedEphemeralSequential(); + public ACLPathAndBytesable withProtectedEphemeralSequential(); /** *

@@ -92,5 +90,5 @@ public interface CreateBuilderMain extends * * @return this */ - public ACLCreateModeStatBackgroundPathAndBytesable withProtection(); + public ACLCreateModeStatBackgroundPathAndBytesable withProtection(); } diff --git a/curator-framework/src/main/java/org/apache/curator/framework/api/CreateModable.java b/curator-framework/src/main/java/org/apache/curator/framework/api/CreateModable.java index 2d4b0d78b..fe8cdd68a 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/api/CreateModable.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/api/CreateModable.java @@ -21,8 +21,7 @@ import org.apache.zookeeper.CreateMode; -public interface CreateModable -{ +public interface CreateModable { /** * Set a create mode - the default is {@link CreateMode#PERSISTENT} * diff --git a/curator-framework/src/main/java/org/apache/curator/framework/api/CreateProtectACLCreateModePathAndBytesable.java b/curator-framework/src/main/java/org/apache/curator/framework/api/CreateProtectACLCreateModePathAndBytesable.java index 93b3268a1..28285cdf9 100755 --- a/curator-framework/src/main/java/org/apache/curator/framework/api/CreateProtectACLCreateModePathAndBytesable.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/api/CreateProtectACLCreateModePathAndBytesable.java @@ -21,9 +21,7 @@ import org.apache.zookeeper.CreateMode; -public interface CreateProtectACLCreateModePathAndBytesable extends - ProtectACLCreateModePathAndBytesable -{ +public interface CreateProtectACLCreateModePathAndBytesable extends ProtectACLCreateModePathAndBytesable { /** * Causes any parent nodes to get created if they haven't already been * @@ -69,5 +67,5 @@ public interface CreateProtectACLCreateModePathAndBytesable extends * * @return this */ - public ACLCreateModeBackgroundPathAndBytesable withProtection(); + public ACLCreateModeBackgroundPathAndBytesable withProtection(); } diff --git a/curator-framework/src/main/java/org/apache/curator/framework/api/CuratorEvent.java b/curator-framework/src/main/java/org/apache/curator/framework/api/CuratorEvent.java index 6a99f5b65..118ac3002 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/api/CuratorEvent.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/api/CuratorEvent.java @@ -19,12 +19,11 @@ package org.apache.curator.framework.api; +import java.util.List; import org.apache.curator.framework.api.transaction.CuratorTransactionResult; -import org.apache.zookeeper.OpResult; import org.apache.zookeeper.WatchedEvent; import org.apache.zookeeper.data.ACL; import org.apache.zookeeper.data.Stat; -import java.util.List; /** * A super set of all the various Zookeeper events/background methods. @@ -32,8 +31,7 @@ * IMPORTANT: the methods only return values as specified by the operation that generated them. Many methods * will return null */ -public interface CuratorEvent -{ +public interface CuratorEvent { /** * check here first - this value determines the type of event and which methods will have * valid values diff --git a/curator-framework/src/main/java/org/apache/curator/framework/api/CuratorEventType.java b/curator-framework/src/main/java/org/apache/curator/framework/api/CuratorEventType.java index 73cb897d2..d5693cad2 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/api/CuratorEventType.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/api/CuratorEventType.java @@ -22,8 +22,7 @@ import org.apache.curator.framework.CuratorFramework; import org.apache.zookeeper.Watcher; -public enum CuratorEventType -{ +public enum CuratorEventType { /** * Corresponds to {@link CuratorFramework#create()} */ diff --git a/curator-framework/src/main/java/org/apache/curator/framework/api/CuratorListener.java b/curator-framework/src/main/java/org/apache/curator/framework/api/CuratorListener.java index a6dc5ef90..f4e943b5e 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/api/CuratorListener.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/api/CuratorListener.java @@ -24,8 +24,7 @@ /** * Receives notifications about errors and background events */ -public interface CuratorListener -{ +public interface CuratorListener { /** * Called when a background task has completed or a watch has triggered * @@ -33,5 +32,5 @@ public interface CuratorListener * @param event the event * @throws Exception any errors */ - public void eventReceived(CuratorFramework client, CuratorEvent event) throws Exception; + public void eventReceived(CuratorFramework client, CuratorEvent event) throws Exception; } diff --git a/curator-framework/src/main/java/org/apache/curator/framework/api/CuratorWatcher.java b/curator-framework/src/main/java/org/apache/curator/framework/api/CuratorWatcher.java index c9afaabda..80272f88b 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/api/CuratorWatcher.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/api/CuratorWatcher.java @@ -25,8 +25,7 @@ /** * A version of {@link Watcher} that can throw an exception */ -public interface CuratorWatcher -{ +public interface CuratorWatcher { /** * Same as {@link Watcher#process(WatchedEvent)}. If an exception * is thrown, Curator will log it diff --git a/curator-framework/src/main/java/org/apache/curator/framework/api/Decompressible.java b/curator-framework/src/main/java/org/apache/curator/framework/api/Decompressible.java index 35b8ea364..b6e6bbba9 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/api/Decompressible.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/api/Decompressible.java @@ -19,12 +19,11 @@ package org.apache.curator.framework.api; -public interface Decompressible -{ +public interface Decompressible { /** * Cause the data to be de-compressed using the configured compression provider * * @return this */ - public T decompressed(); + public T decompressed(); } diff --git a/curator-framework/src/main/java/org/apache/curator/framework/api/DeleteBuilder.java b/curator-framework/src/main/java/org/apache/curator/framework/api/DeleteBuilder.java index cdcb91baf..d9ba24046 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/api/DeleteBuilder.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/api/DeleteBuilder.java @@ -19,9 +19,5 @@ package org.apache.curator.framework.api; -public interface DeleteBuilder extends - Quietly, - DeleteBuilderMain, - Idempotentable -{ -} +public interface DeleteBuilder + extends Quietly, DeleteBuilderMain, Idempotentable {} diff --git a/curator-framework/src/main/java/org/apache/curator/framework/api/DeleteBuilderMain.java b/curator-framework/src/main/java/org/apache/curator/framework/api/DeleteBuilderMain.java index ee0918354..7cd76e350 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/api/DeleteBuilderMain.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/api/DeleteBuilderMain.java @@ -19,6 +19,4 @@ package org.apache.curator.framework.api; -public interface DeleteBuilderMain extends GuaranteeableDeletable, ChildrenDeletable -{ -} +public interface DeleteBuilderMain extends GuaranteeableDeletable, ChildrenDeletable {} diff --git a/curator-framework/src/main/java/org/apache/curator/framework/api/ErrorListenerEnsembleable.java b/curator-framework/src/main/java/org/apache/curator/framework/api/ErrorListenerEnsembleable.java index c5bd24070..d658f8f2f 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/api/ErrorListenerEnsembleable.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/api/ErrorListenerEnsembleable.java @@ -19,8 +19,7 @@ package org.apache.curator.framework.api; -public interface ErrorListenerEnsembleable extends Ensembleable -{ +public interface ErrorListenerEnsembleable extends Ensembleable { /** * Set an error listener for this background operation. If an exception * occurs while processing the call in the background, this listener will diff --git a/curator-framework/src/main/java/org/apache/curator/framework/api/ErrorListenerMultiTransactionMain.java b/curator-framework/src/main/java/org/apache/curator/framework/api/ErrorListenerMultiTransactionMain.java index 83382ce42..acee4bf16 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/api/ErrorListenerMultiTransactionMain.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/api/ErrorListenerMultiTransactionMain.java @@ -21,8 +21,7 @@ import org.apache.curator.framework.api.transaction.CuratorMultiTransactionMain; -public interface ErrorListenerMultiTransactionMain extends CuratorMultiTransactionMain -{ +public interface ErrorListenerMultiTransactionMain extends CuratorMultiTransactionMain { /** * Set an error listener for this background operation. If an exception * occurs while processing the call in the background, this listener will diff --git a/curator-framework/src/main/java/org/apache/curator/framework/api/ErrorListenerPathAndBytesable.java b/curator-framework/src/main/java/org/apache/curator/framework/api/ErrorListenerPathAndBytesable.java index 5e9de3509..0aaee4a5f 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/api/ErrorListenerPathAndBytesable.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/api/ErrorListenerPathAndBytesable.java @@ -19,8 +19,7 @@ package org.apache.curator.framework.api; -public interface ErrorListenerPathAndBytesable extends PathAndBytesable -{ +public interface ErrorListenerPathAndBytesable extends PathAndBytesable { /** * Set an error listener for this background operation. If an exception * occurs while processing the call in the background, this listener will diff --git a/curator-framework/src/main/java/org/apache/curator/framework/api/ErrorListenerPathable.java b/curator-framework/src/main/java/org/apache/curator/framework/api/ErrorListenerPathable.java index 2787e168d..a2e517637 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/api/ErrorListenerPathable.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/api/ErrorListenerPathable.java @@ -19,8 +19,7 @@ package org.apache.curator.framework.api; -public interface ErrorListenerPathable extends Pathable -{ +public interface ErrorListenerPathable extends Pathable { /** * Set an error listener for this background operation. If an exception * occurs while processing the call in the background, this listener will diff --git a/curator-framework/src/main/java/org/apache/curator/framework/api/ErrorListenerReconfigBuilderMain.java b/curator-framework/src/main/java/org/apache/curator/framework/api/ErrorListenerReconfigBuilderMain.java index 50e44ada3..e5ad09e90 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/api/ErrorListenerReconfigBuilderMain.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/api/ErrorListenerReconfigBuilderMain.java @@ -19,8 +19,7 @@ package org.apache.curator.framework.api; -public interface ErrorListenerReconfigBuilderMain extends ReconfigBuilderMain -{ +public interface ErrorListenerReconfigBuilderMain extends ReconfigBuilderMain { /** * Set an error listener for this background operation. If an exception * occurs while processing the call in the background, this listener will diff --git a/curator-framework/src/main/java/org/apache/curator/framework/api/ExistsBuilder.java b/curator-framework/src/main/java/org/apache/curator/framework/api/ExistsBuilder.java index 85d27554c..ba869ee1b 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/api/ExistsBuilder.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/api/ExistsBuilder.java @@ -21,9 +21,7 @@ import org.apache.zookeeper.CreateMode; -public interface ExistsBuilder extends - ExistsBuilderMain -{ +public interface ExistsBuilder extends ExistsBuilderMain { /** * Causes any parent nodes to get created if they haven't already been * diff --git a/curator-framework/src/main/java/org/apache/curator/framework/api/ExistsBuilderMain.java b/curator-framework/src/main/java/org/apache/curator/framework/api/ExistsBuilderMain.java index c6fedee0b..c384fc81d 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/api/ExistsBuilderMain.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/api/ExistsBuilderMain.java @@ -21,8 +21,4 @@ import org.apache.zookeeper.data.Stat; -public interface ExistsBuilderMain extends - Watchable>, - BackgroundPathable -{ -} +public interface ExistsBuilderMain extends Watchable>, BackgroundPathable {} diff --git a/curator-framework/src/main/java/org/apache/curator/framework/api/GetACLBuilder.java b/curator-framework/src/main/java/org/apache/curator/framework/api/GetACLBuilder.java index 47db7ed8b..4dee82f10 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/api/GetACLBuilder.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/api/GetACLBuilder.java @@ -19,11 +19,7 @@ package org.apache.curator.framework.api; -import org.apache.zookeeper.data.ACL; import java.util.List; +import org.apache.zookeeper.data.ACL; -public interface GetACLBuilder extends - BackgroundPathable>, - Statable>> -{ -} +public interface GetACLBuilder extends BackgroundPathable>, Statable>> {} diff --git a/curator-framework/src/main/java/org/apache/curator/framework/api/GetChildrenBuilder.java b/curator-framework/src/main/java/org/apache/curator/framework/api/GetChildrenBuilder.java index 5319c5d7b..343a03852 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/api/GetChildrenBuilder.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/api/GetChildrenBuilder.java @@ -21,9 +21,7 @@ import java.util.List; -public interface GetChildrenBuilder extends - Watchable>>, - BackgroundPathable>, - Statable>> -{ -} +public interface GetChildrenBuilder + extends Watchable>>, + BackgroundPathable>, + Statable>> {} diff --git a/curator-framework/src/main/java/org/apache/curator/framework/api/GetConfigBuilder.java b/curator-framework/src/main/java/org/apache/curator/framework/api/GetConfigBuilder.java index 7bd432891..3a10be596 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/api/GetConfigBuilder.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/api/GetConfigBuilder.java @@ -19,10 +19,8 @@ package org.apache.curator.framework.api; -public interface GetConfigBuilder extends - Ensembleable, - Backgroundable>, - Watchable>, - Statable> -{ -} +public interface GetConfigBuilder + extends Ensembleable, + Backgroundable>, + Watchable>, + Statable> {} diff --git a/curator-framework/src/main/java/org/apache/curator/framework/api/GetDataBuilder.java b/curator-framework/src/main/java/org/apache/curator/framework/api/GetDataBuilder.java index 664507001..50f63a11a 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/api/GetDataBuilder.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/api/GetDataBuilder.java @@ -19,10 +19,8 @@ package org.apache.curator.framework.api; -public interface GetDataBuilder extends - Watchable>, - BackgroundPathable, - Statable>, - Decompressible -{ -} +public interface GetDataBuilder + extends Watchable>, + BackgroundPathable, + Statable>, + Decompressible {} diff --git a/curator-framework/src/main/java/org/apache/curator/framework/api/GetDataWatchBackgroundStatable.java b/curator-framework/src/main/java/org/apache/curator/framework/api/GetDataWatchBackgroundStatable.java index a22dabcae..c8cb376f7 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/api/GetDataWatchBackgroundStatable.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/api/GetDataWatchBackgroundStatable.java @@ -19,9 +19,5 @@ package org.apache.curator.framework.api; -public interface GetDataWatchBackgroundStatable extends - Watchable>, - BackgroundPathable, - Statable> -{ -} +public interface GetDataWatchBackgroundStatable + extends Watchable>, BackgroundPathable, Statable> {} diff --git a/curator-framework/src/main/java/org/apache/curator/framework/api/Guaranteeable.java b/curator-framework/src/main/java/org/apache/curator/framework/api/Guaranteeable.java index 61cd63491..1ce275fe2 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/api/Guaranteeable.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/api/Guaranteeable.java @@ -19,14 +19,13 @@ package org.apache.curator.framework.api; -public interface Guaranteeable -{ +public interface Guaranteeable { /** * Solves edge cases where an operation may succeed on the server but connection failure occurs before a * response can be successfully returned to the client. - * - * @see org.apache.curator.framework.api.GuaranteeableDeletable - * + * + * @see org.apache.curator.framework.api.GuaranteeableDeletable + * * @return this */ public T guaranteed(); diff --git a/curator-framework/src/main/java/org/apache/curator/framework/api/GuaranteeableDeletable.java b/curator-framework/src/main/java/org/apache/curator/framework/api/GuaranteeableDeletable.java index c9e07dd1c..e0757abf9 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/api/GuaranteeableDeletable.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/api/GuaranteeableDeletable.java @@ -32,9 +32,7 @@ * exception when the deletion fails. But, you can be assured that as long as the * {@link org.apache.curator.framework.CuratorFramework} instance is open attempts will be made to delete the node. *

- * + * * @return this */ -public interface GuaranteeableDeletable extends Guaranteeable, BackgroundVersionable -{ -} +public interface GuaranteeableDeletable extends Guaranteeable, BackgroundVersionable {} diff --git a/curator-framework/src/main/java/org/apache/curator/framework/api/Idempotentable.java b/curator-framework/src/main/java/org/apache/curator/framework/api/Idempotentable.java index ce2538826..46fa610e3 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/api/Idempotentable.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/api/Idempotentable.java @@ -19,8 +19,7 @@ package org.apache.curator.framework.api; -public interface Idempotentable -{ +public interface Idempotentable { /** * If the first try of this operation gets a transient error, curator will retry * the operation, and treat it as successful so long as the end state of the znode diff --git a/curator-framework/src/main/java/org/apache/curator/framework/api/JoinStatConfigEnsembleable.java b/curator-framework/src/main/java/org/apache/curator/framework/api/JoinStatConfigEnsembleable.java index 9836dacc4..0527e27ea 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/api/JoinStatConfigEnsembleable.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/api/JoinStatConfigEnsembleable.java @@ -24,10 +24,5 @@ * This builder has access only to the incremental reconfiguration methods joining and leaving, so that we prevent * mixing concepts that can't be used together. */ -public interface JoinStatConfigEnsembleable extends - Joinable, - ConfigureEnsembleable, - Statable -{ - -} +public interface JoinStatConfigEnsembleable + extends Joinable, ConfigureEnsembleable, Statable {} diff --git a/curator-framework/src/main/java/org/apache/curator/framework/api/Joinable.java b/curator-framework/src/main/java/org/apache/curator/framework/api/Joinable.java index 9c3ac0227..2e46f21d9 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/api/Joinable.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/api/Joinable.java @@ -21,8 +21,7 @@ import java.util.List; -public interface Joinable -{ +public interface Joinable { /** * Adds one or more servers to joining the ensemble. * The expected format is server.[id]=[hostname]:[peer port]:[election port]:[type];[client port] diff --git a/curator-framework/src/main/java/org/apache/curator/framework/api/LeaveStatConfigEnsembleable.java b/curator-framework/src/main/java/org/apache/curator/framework/api/LeaveStatConfigEnsembleable.java index 3dbe6b5c3..7efe823f3 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/api/LeaveStatConfigEnsembleable.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/api/LeaveStatConfigEnsembleable.java @@ -24,10 +24,5 @@ * This builder has access only to the incremental reconfiguration methods joining and leaving, so that we prevent * mixing concepts that can't be used together. */ -public interface LeaveStatConfigEnsembleable extends - Leaveable, - ConfigureEnsembleable, - Statable -{ - -} +public interface LeaveStatConfigEnsembleable + extends Leaveable, ConfigureEnsembleable, Statable {} diff --git a/curator-framework/src/main/java/org/apache/curator/framework/api/Leaveable.java b/curator-framework/src/main/java/org/apache/curator/framework/api/Leaveable.java index faaf39b15..59cc8ed4b 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/api/Leaveable.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/api/Leaveable.java @@ -21,8 +21,7 @@ import java.util.List; -public interface Leaveable -{ +public interface Leaveable { /** * Sets one or more servers to leaving the ensemble. * diff --git a/curator-framework/src/main/java/org/apache/curator/framework/api/Membersable.java b/curator-framework/src/main/java/org/apache/curator/framework/api/Membersable.java index 3abef81f0..db45d5d48 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/api/Membersable.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/api/Membersable.java @@ -21,8 +21,7 @@ import java.util.List; -public interface Membersable -{ +public interface Membersable { /** * Sets one or more members that are meant to be the ensemble. * The expected format is server.[id]=[hostname]:[peer port]:[election port]:[type];[client port] diff --git a/curator-framework/src/main/java/org/apache/curator/framework/api/ParentACLable.java b/curator-framework/src/main/java/org/apache/curator/framework/api/ParentACLable.java index 40b4260f0..c2a7ba0ae 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/api/ParentACLable.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/api/ParentACLable.java @@ -19,11 +19,10 @@ package org.apache.curator.framework.api; +import java.util.List; import org.apache.zookeeper.ZooDefs; import org.apache.zookeeper.data.ACL; -import java.util.List; - public interface ParentACLable extends ACLable { /** @@ -37,5 +36,4 @@ public interface ParentACLable extends ACLable { * @return this */ T withACL(List aclList, boolean applyToParents); - } diff --git a/curator-framework/src/main/java/org/apache/curator/framework/api/PathAndBytesable.java b/curator-framework/src/main/java/org/apache/curator/framework/api/PathAndBytesable.java index 70d96710d..c644d6d60 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/api/PathAndBytesable.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/api/PathAndBytesable.java @@ -21,8 +21,7 @@ import org.apache.curator.framework.CuratorFrameworkFactory; -public interface PathAndBytesable -{ +public interface PathAndBytesable { /** * Commit the currently building operation using the given path and data * @@ -31,7 +30,7 @@ public interface PathAndBytesable * @return operation result if any * @throws Exception errors */ - public T forPath(String path, byte[] data) throws Exception; + public T forPath(String path, byte[] data) throws Exception; /** * Commit the currently building operation using the given path and the default data @@ -42,5 +41,5 @@ public interface PathAndBytesable * @return operation result if any * @throws Exception errors */ - public T forPath(String path) throws Exception; + public T forPath(String path) throws Exception; } diff --git a/curator-framework/src/main/java/org/apache/curator/framework/api/Pathable.java b/curator-framework/src/main/java/org/apache/curator/framework/api/Pathable.java index 8e1cd7013..f7de8db17 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/api/Pathable.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/api/Pathable.java @@ -19,8 +19,7 @@ package org.apache.curator.framework.api; -public interface Pathable -{ +public interface Pathable { /** * Commit the currently building operation using the given path * @@ -28,5 +27,5 @@ public interface Pathable * @return operation result if any * @throws Exception errors */ - public T forPath(String path) throws Exception; + public T forPath(String path) throws Exception; } diff --git a/curator-framework/src/main/java/org/apache/curator/framework/api/ProtectACLCreateModePathAndBytesable.java b/curator-framework/src/main/java/org/apache/curator/framework/api/ProtectACLCreateModePathAndBytesable.java index 04e74bfa4..35118b0f0 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/api/ProtectACLCreateModePathAndBytesable.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/api/ProtectACLCreateModePathAndBytesable.java @@ -19,10 +19,8 @@ package org.apache.curator.framework.api; -public interface ProtectACLCreateModePathAndBytesable extends - ACLBackgroundPathAndBytesable, - CreateModable> -{ +public interface ProtectACLCreateModePathAndBytesable + extends ACLBackgroundPathAndBytesable, CreateModable> { /** *

* Hat-tip to https://github.com/sbridges for pointing this out @@ -51,5 +49,5 @@ public interface ProtectACLCreateModePathAndBytesable extends * * @return this */ - public ACLCreateModeBackgroundPathAndBytesable withProtection(); + public ACLCreateModeBackgroundPathAndBytesable withProtection(); } diff --git a/curator-framework/src/main/java/org/apache/curator/framework/api/ProtectACLCreateModeStatPathAndBytesable.java b/curator-framework/src/main/java/org/apache/curator/framework/api/ProtectACLCreateModeStatPathAndBytesable.java index 8f6099240..261b5d1d3 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/api/ProtectACLCreateModeStatPathAndBytesable.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/api/ProtectACLCreateModeStatPathAndBytesable.java @@ -19,8 +19,5 @@ package org.apache.curator.framework.api; -public interface ProtectACLCreateModeStatPathAndBytesable extends - ProtectACLCreateModePathAndBytesable, - Statable> -{ -} +public interface ProtectACLCreateModeStatPathAndBytesable + extends ProtectACLCreateModePathAndBytesable, Statable> {} diff --git a/curator-framework/src/main/java/org/apache/curator/framework/api/Quietly.java b/curator-framework/src/main/java/org/apache/curator/framework/api/Quietly.java index edcef08c1..f7b188edc 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/api/Quietly.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/api/Quietly.java @@ -19,7 +19,6 @@ package org.apache.curator.framework.api; -public interface Quietly -{ +public interface Quietly { public T quietly(); } diff --git a/curator-framework/src/main/java/org/apache/curator/framework/api/ReconfigBuilder.java b/curator-framework/src/main/java/org/apache/curator/framework/api/ReconfigBuilder.java index e409d23e1..2e368dd9e 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/api/ReconfigBuilder.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/api/ReconfigBuilder.java @@ -19,8 +19,4 @@ package org.apache.curator.framework.api; -public interface ReconfigBuilder extends - ReconfigBuilderMain, - Backgroundable -{ -} +public interface ReconfigBuilder extends ReconfigBuilderMain, Backgroundable {} diff --git a/curator-framework/src/main/java/org/apache/curator/framework/api/ReconfigBuilderMain.java b/curator-framework/src/main/java/org/apache/curator/framework/api/ReconfigBuilderMain.java index ae82d3999..8a090ad12 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/api/ReconfigBuilderMain.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/api/ReconfigBuilderMain.java @@ -19,9 +19,7 @@ package org.apache.curator.framework.api; -public interface ReconfigBuilderMain extends - Joinable, - Leaveable, - Membersable -{ -} +public interface ReconfigBuilderMain + extends Joinable, + Leaveable, + Membersable {} diff --git a/curator-framework/src/main/java/org/apache/curator/framework/api/RemoveWatchesBuilder.java b/curator-framework/src/main/java/org/apache/curator/framework/api/RemoveWatchesBuilder.java index 06aad2bb8..05cfd9f71 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/api/RemoveWatchesBuilder.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/api/RemoveWatchesBuilder.java @@ -17,32 +17,31 @@ * under the License. */ -package org.apache.curator.framework.api; - -import org.apache.zookeeper.Watcher; - -/** - * Builder to allow watches to be removed - */ -public interface RemoveWatchesBuilder -{ - /** - * Specify the watcher to be removed - * @param watcher - * @return - */ - public RemoveWatchesType remove(Watcher watcher); - - /** - * Specify the watcher to be removed - * @param watcher - * @return - */ - public RemoveWatchesType remove(CuratorWatcher watcher); - - /** - * Specify that all watches should be removed - * @return - */ - public RemoveWatchesType removeAll(); -} +package org.apache.curator.framework.api; + +import org.apache.zookeeper.Watcher; + +/** + * Builder to allow watches to be removed + */ +public interface RemoveWatchesBuilder { + /** + * Specify the watcher to be removed + * @param watcher + * @return + */ + public RemoveWatchesType remove(Watcher watcher); + + /** + * Specify the watcher to be removed + * @param watcher + * @return + */ + public RemoveWatchesType remove(CuratorWatcher watcher); + + /** + * Specify that all watches should be removed + * @return + */ + public RemoveWatchesType removeAll(); +} diff --git a/curator-framework/src/main/java/org/apache/curator/framework/api/RemoveWatchesLocal.java b/curator-framework/src/main/java/org/apache/curator/framework/api/RemoveWatchesLocal.java index 5c6a19dd7..ea13133c9 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/api/RemoveWatchesLocal.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/api/RemoveWatchesLocal.java @@ -17,20 +17,18 @@ * under the License. */ -package org.apache.curator.framework.api; - -/** - * Builder to allow the specification of whether it is acceptable to remove client side watch information - * in the case where ZK cannot be contacted. - */ -public interface RemoveWatchesLocal extends BackgroundPathableQuietlyable -{ - - /** - * Specify if the client should just remove client side watches if a connection to ZK - * is not available. Note that the standard Curator retry loop will not be used in t - * @return - */ - public BackgroundPathableQuietlyable locally(); - -} +package org.apache.curator.framework.api; + +/** + * Builder to allow the specification of whether it is acceptable to remove client side watch information + * in the case where ZK cannot be contacted. + */ +public interface RemoveWatchesLocal extends BackgroundPathableQuietlyable { + + /** + * Specify if the client should just remove client side watches if a connection to ZK + * is not available. Note that the standard Curator retry loop will not be used in t + * @return + */ + public BackgroundPathableQuietlyable locally(); +} diff --git a/curator-framework/src/main/java/org/apache/curator/framework/api/RemoveWatchesType.java b/curator-framework/src/main/java/org/apache/curator/framework/api/RemoveWatchesType.java index 122cf44b5..717272064 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/api/RemoveWatchesType.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/api/RemoveWatchesType.java @@ -17,22 +17,20 @@ * under the License. */ -package org.apache.curator.framework.api; - -import org.apache.zookeeper.Watcher.WatcherType; - -/** - * Builder to allow the specification of whether it is acceptable to remove client side watch information - * in the case where ZK cannot be contacted. - */ -public interface RemoveWatchesType extends RemoveWatchesLocal, Guaranteeable> -{ - - /** - * Specify the type of watcher to be removed. - * @param watcherType - * @return - */ - public RemoveWatchesLocal ofType(WatcherType watcherType); - -} +package org.apache.curator.framework.api; + +import org.apache.zookeeper.Watcher.WatcherType; + +/** + * Builder to allow the specification of whether it is acceptable to remove client side watch information + * in the case where ZK cannot be contacted. + */ +public interface RemoveWatchesType extends RemoveWatchesLocal, Guaranteeable> { + + /** + * Specify the type of watcher to be removed. + * @param watcherType + * @return + */ + public RemoveWatchesLocal ofType(WatcherType watcherType); +} diff --git a/curator-framework/src/main/java/org/apache/curator/framework/api/SetACLBuilder.java b/curator-framework/src/main/java/org/apache/curator/framework/api/SetACLBuilder.java index c27c55e6e..3edc79395 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/api/SetACLBuilder.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/api/SetACLBuilder.java @@ -21,8 +21,5 @@ import org.apache.zookeeper.data.Stat; -public interface SetACLBuilder extends - ACLable>, - Versionable>> -{ -} +public interface SetACLBuilder + extends ACLable>, Versionable>> {} diff --git a/curator-framework/src/main/java/org/apache/curator/framework/api/SetDataBackgroundVersionable.java b/curator-framework/src/main/java/org/apache/curator/framework/api/SetDataBackgroundVersionable.java index 23c910339..7044826f4 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/api/SetDataBackgroundVersionable.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/api/SetDataBackgroundVersionable.java @@ -21,8 +21,5 @@ import org.apache.zookeeper.data.Stat; -public interface SetDataBackgroundVersionable extends - BackgroundPathAndBytesable, - Versionable> -{ -} +public interface SetDataBackgroundVersionable + extends BackgroundPathAndBytesable, Versionable> {} diff --git a/curator-framework/src/main/java/org/apache/curator/framework/api/SetDataBuilder.java b/curator-framework/src/main/java/org/apache/curator/framework/api/SetDataBuilder.java index 622e24279..d323095b0 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/api/SetDataBuilder.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/api/SetDataBuilder.java @@ -21,10 +21,8 @@ import org.apache.zookeeper.data.Stat; -public interface SetDataBuilder extends - BackgroundPathAndBytesable, - Versionable>, - Compressible, - Idempotentable -{ -} +public interface SetDataBuilder + extends BackgroundPathAndBytesable, + Versionable>, + Compressible, + Idempotentable {} diff --git a/curator-framework/src/main/java/org/apache/curator/framework/api/StatConfigureEnsembleable.java b/curator-framework/src/main/java/org/apache/curator/framework/api/StatConfigureEnsembleable.java index 79d50000f..634c12572 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/api/StatConfigureEnsembleable.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/api/StatConfigureEnsembleable.java @@ -19,8 +19,4 @@ package org.apache.curator.framework.api; -public interface StatConfigureEnsembleable extends - Statable, - ConfigureEnsembleable -{ -} \ No newline at end of file +public interface StatConfigureEnsembleable extends Statable, ConfigureEnsembleable {} diff --git a/curator-framework/src/main/java/org/apache/curator/framework/api/StatPathable.java b/curator-framework/src/main/java/org/apache/curator/framework/api/StatPathable.java index dfd9d1a3e..aa69d88fc 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/api/StatPathable.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/api/StatPathable.java @@ -19,8 +19,4 @@ package org.apache.curator.framework.api; -public interface StatPathable extends - Pathable, - Statable> -{ -} +public interface StatPathable extends Pathable, Statable> {} diff --git a/curator-framework/src/main/java/org/apache/curator/framework/api/Statable.java b/curator-framework/src/main/java/org/apache/curator/framework/api/Statable.java index 9953147dd..4171c9881 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/api/Statable.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/api/Statable.java @@ -21,8 +21,7 @@ import org.apache.zookeeper.data.Stat; -public interface Statable -{ +public interface Statable { /** * Have the operation fill the provided stat object * diff --git a/curator-framework/src/main/java/org/apache/curator/framework/api/SyncBuilder.java b/curator-framework/src/main/java/org/apache/curator/framework/api/SyncBuilder.java index eaa2ceef5..97663df6d 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/api/SyncBuilder.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/api/SyncBuilder.java @@ -19,7 +19,4 @@ package org.apache.curator.framework.api; -public interface SyncBuilder extends - BackgroundPathable -{ -} +public interface SyncBuilder extends BackgroundPathable {} diff --git a/curator-framework/src/main/java/org/apache/curator/framework/api/TempGetDataBuilder.java b/curator-framework/src/main/java/org/apache/curator/framework/api/TempGetDataBuilder.java index a6e19b060..4c60c0c71 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/api/TempGetDataBuilder.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/api/TempGetDataBuilder.java @@ -19,9 +19,5 @@ package org.apache.curator.framework.api; -public interface TempGetDataBuilder extends - StatPathable, - Decompressible>, - Pathable -{ -} +public interface TempGetDataBuilder + extends StatPathable, Decompressible>, Pathable {} diff --git a/curator-framework/src/main/java/org/apache/curator/framework/api/UnhandledErrorListener.java b/curator-framework/src/main/java/org/apache/curator/framework/api/UnhandledErrorListener.java index 9a483a113..a0b5e816a 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/api/UnhandledErrorListener.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/api/UnhandledErrorListener.java @@ -19,16 +19,12 @@ package org.apache.curator.framework.api; -import org.apache.curator.framework.state.ConnectionState; -import org.apache.curator.framework.state.ConnectionStateListener; - -public interface UnhandledErrorListener -{ +public interface UnhandledErrorListener { /** * Called when an exception is caught in a background thread, handler, etc. * * @param message Source message * @param e exception */ - public void unhandledError(String message, Throwable e); + public void unhandledError(String message, Throwable e); } diff --git a/curator-framework/src/main/java/org/apache/curator/framework/api/VersionPathAndBytesable.java b/curator-framework/src/main/java/org/apache/curator/framework/api/VersionPathAndBytesable.java index 8ddb739f7..12241ae70 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/api/VersionPathAndBytesable.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/api/VersionPathAndBytesable.java @@ -19,8 +19,4 @@ package org.apache.curator.framework.api; -public interface VersionPathAndBytesable extends - Versionable>, - PathAndBytesable -{ -} +public interface VersionPathAndBytesable extends Versionable>, PathAndBytesable {} diff --git a/curator-framework/src/main/java/org/apache/curator/framework/api/Versionable.java b/curator-framework/src/main/java/org/apache/curator/framework/api/Versionable.java index b87102b48..1484e1346 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/api/Versionable.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/api/Versionable.java @@ -19,13 +19,12 @@ package org.apache.curator.framework.api; -public interface Versionable -{ +public interface Versionable { /** * Use the given version (the default is -1) * * @param version version to use * @return this */ - public T withVersion(int version); + public T withVersion(int version); } diff --git a/curator-framework/src/main/java/org/apache/curator/framework/api/WatchBackgroundEnsembleable.java b/curator-framework/src/main/java/org/apache/curator/framework/api/WatchBackgroundEnsembleable.java index 00ffb72df..666d80488 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/api/WatchBackgroundEnsembleable.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/api/WatchBackgroundEnsembleable.java @@ -19,8 +19,5 @@ package org.apache.curator.framework.api; -public interface WatchBackgroundEnsembleable extends - Watchable>, - BackgroundEnsembleable -{ -} +public interface WatchBackgroundEnsembleable + extends Watchable>, BackgroundEnsembleable {} diff --git a/curator-framework/src/main/java/org/apache/curator/framework/api/WatchPathable.java b/curator-framework/src/main/java/org/apache/curator/framework/api/WatchPathable.java index b59094d31..4ae1cea27 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/api/WatchPathable.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/api/WatchPathable.java @@ -19,8 +19,4 @@ package org.apache.curator.framework.api; -public interface WatchPathable extends - Watchable>, - Pathable -{ -} +public interface WatchPathable extends Watchable>, Pathable {} diff --git a/curator-framework/src/main/java/org/apache/curator/framework/api/Watchable.java b/curator-framework/src/main/java/org/apache/curator/framework/api/Watchable.java index c66c4c12b..d399f2d38 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/api/Watchable.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/api/Watchable.java @@ -19,8 +19,7 @@ package org.apache.curator.framework.api; -public interface Watchable extends WatchableBase -{ +public interface Watchable extends WatchableBase { /** * Have the operation set a watch * diff --git a/curator-framework/src/main/java/org/apache/curator/framework/api/WatchableBase.java b/curator-framework/src/main/java/org/apache/curator/framework/api/WatchableBase.java index ace5e915e..20a40932b 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/api/WatchableBase.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/api/WatchableBase.java @@ -21,8 +21,7 @@ import org.apache.zookeeper.Watcher; -public interface WatchableBase -{ +public interface WatchableBase { /** * Set a watcher for the operation * diff --git a/curator-framework/src/main/java/org/apache/curator/framework/api/WatchesBuilder.java b/curator-framework/src/main/java/org/apache/curator/framework/api/WatchesBuilder.java index 55c6b4c86..0b689255d 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/api/WatchesBuilder.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/api/WatchesBuilder.java @@ -20,14 +20,13 @@ package org.apache.curator.framework.api; /** - * Builder to allow watches to be removed + * Builder to allow watches to be removed */ -public interface WatchesBuilder extends RemoveWatchesBuilder -{ +public interface WatchesBuilder extends RemoveWatchesBuilder { /** * Start an add watch operation * * @return builder */ AddWatchBuilder add(); -} \ No newline at end of file +} diff --git a/curator-framework/src/main/java/org/apache/curator/framework/api/transaction/CuratorMultiTransaction.java b/curator-framework/src/main/java/org/apache/curator/framework/api/transaction/CuratorMultiTransaction.java index 83744dae7..15e42cd58 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/api/transaction/CuratorMultiTransaction.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/api/transaction/CuratorMultiTransaction.java @@ -22,8 +22,5 @@ import org.apache.curator.framework.api.Backgroundable; import org.apache.curator.framework.api.ErrorListenerMultiTransactionMain; -public interface CuratorMultiTransaction extends - Backgroundable, - CuratorMultiTransactionMain -{ -} +public interface CuratorMultiTransaction + extends Backgroundable, CuratorMultiTransactionMain {} diff --git a/curator-framework/src/main/java/org/apache/curator/framework/api/transaction/CuratorMultiTransactionMain.java b/curator-framework/src/main/java/org/apache/curator/framework/api/transaction/CuratorMultiTransactionMain.java index db88dcf25..de8f07153 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/api/transaction/CuratorMultiTransactionMain.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/api/transaction/CuratorMultiTransactionMain.java @@ -19,11 +19,10 @@ package org.apache.curator.framework.api.transaction; -import org.apache.curator.framework.CuratorFramework; import java.util.List; +import org.apache.curator.framework.CuratorFramework; -public interface CuratorMultiTransactionMain -{ +public interface CuratorMultiTransactionMain { /** * Commit the given operations as a single transaction. Create the * operation instances via {@link CuratorFramework#transactionOp()} diff --git a/curator-framework/src/main/java/org/apache/curator/framework/api/transaction/CuratorOp.java b/curator-framework/src/main/java/org/apache/curator/framework/api/transaction/CuratorOp.java index af0e465cc..8990f8fb2 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/api/transaction/CuratorOp.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/api/transaction/CuratorOp.java @@ -24,8 +24,7 @@ /** * Internal representation of a transaction operation */ -public interface CuratorOp -{ +public interface CuratorOp { Op get(); TypeAndPath getTypeAndPath(); diff --git a/curator-framework/src/main/java/org/apache/curator/framework/api/transaction/CuratorTransaction.java b/curator-framework/src/main/java/org/apache/curator/framework/api/transaction/CuratorTransaction.java index 1b1368516..a9b3646a2 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/api/transaction/CuratorTransaction.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/api/transaction/CuratorTransaction.java @@ -54,8 +54,7 @@ * * @deprecated Use {@link CuratorFramework#transaction()} */ -public interface CuratorTransaction -{ +public interface CuratorTransaction { /** * Start a create builder in the transaction * diff --git a/curator-framework/src/main/java/org/apache/curator/framework/api/transaction/CuratorTransactionBridge.java b/curator-framework/src/main/java/org/apache/curator/framework/api/transaction/CuratorTransactionBridge.java index 6cb371fd6..56bb91f92 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/api/transaction/CuratorTransactionBridge.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/api/transaction/CuratorTransactionBridge.java @@ -19,8 +19,7 @@ package org.apache.curator.framework.api.transaction; -public interface CuratorTransactionBridge -{ +public interface CuratorTransactionBridge { /** * Syntactic sugar to make the fluent interface more readable * diff --git a/curator-framework/src/main/java/org/apache/curator/framework/api/transaction/CuratorTransactionFinal.java b/curator-framework/src/main/java/org/apache/curator/framework/api/transaction/CuratorTransactionFinal.java index 48ba57c70..a9e9c86d9 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/api/transaction/CuratorTransactionFinal.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/api/transaction/CuratorTransactionFinal.java @@ -24,8 +24,7 @@ /** * Adds commit to the transaction interface */ -public interface CuratorTransactionFinal extends CuratorTransaction -{ +public interface CuratorTransactionFinal extends CuratorTransaction { /** * Commit all added operations as an atomic unit and return results * for the operations. One result is returned for each operation added. diff --git a/curator-framework/src/main/java/org/apache/curator/framework/api/transaction/CuratorTransactionResult.java b/curator-framework/src/main/java/org/apache/curator/framework/api/transaction/CuratorTransactionResult.java index 40b0c7e05..d0e5be84b 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/api/transaction/CuratorTransactionResult.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/api/transaction/CuratorTransactionResult.java @@ -26,8 +26,7 @@ /** * Holds the result of one transactional operation */ -public class CuratorTransactionResult -{ +public class CuratorTransactionResult { private final OperationType type; private final String forPath; private final String resultPath; @@ -44,25 +43,20 @@ public class CuratorTransactionResult * @param forPath path * @return predicate */ - public static Predicate ofTypeAndPath(final OperationType type, final String forPath) - { - return new Predicate() - { + public static Predicate ofTypeAndPath(final OperationType type, final String forPath) { + return new Predicate() { @Override - public boolean apply(CuratorTransactionResult result) - { + public boolean apply(CuratorTransactionResult result) { return (result.getType() == type) && result.getForPath().equals(forPath); } }; } - public CuratorTransactionResult(OperationType type, String forPath, String resultPath, Stat resultStat) - { + public CuratorTransactionResult(OperationType type, String forPath, String resultPath, Stat resultStat) { this(type, forPath, resultPath, resultStat, 0); } - public CuratorTransactionResult(OperationType type, String forPath, String resultPath, Stat resultStat, int error) - { + public CuratorTransactionResult(OperationType type, String forPath, String resultPath, Stat resultStat, int error) { this.forPath = forPath; this.resultPath = resultPath; this.resultStat = resultStat; @@ -75,8 +69,7 @@ public CuratorTransactionResult(OperationType type, String forPath, String resul * * @return operation type */ - public OperationType getType() - { + public OperationType getType() { return type; } @@ -85,8 +78,7 @@ public OperationType getType() * * @return operation input path */ - public String getForPath() - { + public String getForPath() { return forPath; } @@ -96,8 +88,7 @@ public String getForPath() * * @return generated path or null */ - public String getResultPath() - { + public String getResultPath() { return resultPath; } @@ -107,8 +98,7 @@ public String getResultPath() * * @return generated stat or null */ - public Stat getResultStat() - { + public Stat getResultStat() { return resultStat; } @@ -117,8 +107,7 @@ public Stat getResultStat() * * @return error or 0 */ - public int getError() - { + public int getError() { return error; } } diff --git a/curator-framework/src/main/java/org/apache/curator/framework/api/transaction/OperationType.java b/curator-framework/src/main/java/org/apache/curator/framework/api/transaction/OperationType.java index f7d276937..cf38de6cb 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/api/transaction/OperationType.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/api/transaction/OperationType.java @@ -22,8 +22,7 @@ /** * Transaction operation types */ -public enum OperationType -{ +public enum OperationType { /** * {@link TransactionOp#create()} */ diff --git a/curator-framework/src/main/java/org/apache/curator/framework/api/transaction/TransactionCheckBuilder.java b/curator-framework/src/main/java/org/apache/curator/framework/api/transaction/TransactionCheckBuilder.java index d75f1182a..da1079e8a 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/api/transaction/TransactionCheckBuilder.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/api/transaction/TransactionCheckBuilder.java @@ -22,8 +22,4 @@ import org.apache.curator.framework.api.Pathable; import org.apache.curator.framework.api.Versionable; -public interface TransactionCheckBuilder extends - Pathable, - Versionable> -{ -} +public interface TransactionCheckBuilder extends Pathable, Versionable> {} diff --git a/curator-framework/src/main/java/org/apache/curator/framework/api/transaction/TransactionCreateBuilder.java b/curator-framework/src/main/java/org/apache/curator/framework/api/transaction/TransactionCreateBuilder.java index ced16b5dd..e28336242 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/api/transaction/TransactionCreateBuilder.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/api/transaction/TransactionCreateBuilder.java @@ -19,8 +19,7 @@ package org.apache.curator.framework.api.transaction; -public interface TransactionCreateBuilder extends TransactionCreateBuilder2 -{ +public interface TransactionCreateBuilder extends TransactionCreateBuilder2 { /** * Specify a TTL when mode is {@link org.apache.zookeeper.CreateMode#PERSISTENT_WITH_TTL} or * {@link org.apache.zookeeper.CreateMode#PERSISTENT_SEQUENTIAL_WITH_TTL}. If diff --git a/curator-framework/src/main/java/org/apache/curator/framework/api/transaction/TransactionCreateBuilder2.java b/curator-framework/src/main/java/org/apache/curator/framework/api/transaction/TransactionCreateBuilder2.java index 502e14036..53540de55 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/api/transaction/TransactionCreateBuilder2.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/api/transaction/TransactionCreateBuilder2.java @@ -25,11 +25,9 @@ import org.apache.curator.framework.api.CreateModable; import org.apache.curator.framework.api.PathAndBytesable; -public interface TransactionCreateBuilder2 extends - PathAndBytesable, - CreateModable>, - ACLPathAndBytesable, - ACLCreateModePathAndBytesable, - Compressible> -{ -} +public interface TransactionCreateBuilder2 + extends PathAndBytesable, + CreateModable>, + ACLPathAndBytesable, + ACLCreateModePathAndBytesable, + Compressible> {} diff --git a/curator-framework/src/main/java/org/apache/curator/framework/api/transaction/TransactionDeleteBuilder.java b/curator-framework/src/main/java/org/apache/curator/framework/api/transaction/TransactionDeleteBuilder.java index 6b6491a2f..0ff7f2e79 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/api/transaction/TransactionDeleteBuilder.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/api/transaction/TransactionDeleteBuilder.java @@ -22,8 +22,4 @@ import org.apache.curator.framework.api.Pathable; import org.apache.curator.framework.api.Versionable; -public interface TransactionDeleteBuilder extends - Pathable, - Versionable> -{ -} +public interface TransactionDeleteBuilder extends Pathable, Versionable> {} diff --git a/curator-framework/src/main/java/org/apache/curator/framework/api/transaction/TransactionOp.java b/curator-framework/src/main/java/org/apache/curator/framework/api/transaction/TransactionOp.java index a082f51a7..e59c8ca15 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/api/transaction/TransactionOp.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/api/transaction/TransactionOp.java @@ -25,8 +25,7 @@ * Builds operations that can be committed as a transaction * via {@link CuratorFramework#transaction()} */ -public interface TransactionOp -{ +public interface TransactionOp { /** * Start a create builder in the transaction * diff --git a/curator-framework/src/main/java/org/apache/curator/framework/api/transaction/TransactionSetDataBuilder.java b/curator-framework/src/main/java/org/apache/curator/framework/api/transaction/TransactionSetDataBuilder.java index 5556b108f..fe73b3e10 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/api/transaction/TransactionSetDataBuilder.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/api/transaction/TransactionSetDataBuilder.java @@ -24,10 +24,8 @@ import org.apache.curator.framework.api.VersionPathAndBytesable; import org.apache.curator.framework.api.Versionable; -public interface TransactionSetDataBuilder extends - PathAndBytesable, - Versionable>, - VersionPathAndBytesable, - Compressible> -{ -} +public interface TransactionSetDataBuilder + extends PathAndBytesable, + Versionable>, + VersionPathAndBytesable, + Compressible> {} diff --git a/curator-framework/src/main/java/org/apache/curator/framework/api/transaction/TypeAndPath.java b/curator-framework/src/main/java/org/apache/curator/framework/api/transaction/TypeAndPath.java index 834e4a740..7d557d47a 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/api/transaction/TypeAndPath.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/api/transaction/TypeAndPath.java @@ -19,24 +19,20 @@ package org.apache.curator.framework.api.transaction; -public class TypeAndPath -{ +public class TypeAndPath { private final OperationType type; private final String forPath; - public TypeAndPath(OperationType type, String forPath) - { + public TypeAndPath(OperationType type, String forPath) { this.type = type; this.forPath = forPath; } - public OperationType getType() - { + public OperationType getType() { return type; } - public String getForPath() - { + public String getForPath() { return forPath; } } diff --git a/curator-framework/src/main/java/org/apache/curator/framework/imps/ACLing.java b/curator-framework/src/main/java/org/apache/curator/framework/imps/ACLing.java index 820cb0252..7136996b1 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/imps/ACLing.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/imps/ACLing.java @@ -20,47 +20,39 @@ package org.apache.curator.framework.imps; import com.google.common.collect.ImmutableList; +import java.util.List; import org.apache.curator.framework.api.ACLProvider; import org.apache.curator.utils.InternalACLProvider; import org.apache.zookeeper.data.ACL; -import java.util.List; -class ACLing implements InternalACLProvider -{ - private final List aclList; - private final ACLProvider aclProvider; - private final boolean applyToParents; +class ACLing implements InternalACLProvider { + private final List aclList; + private final ACLProvider aclProvider; + private final boolean applyToParents; - ACLing(ACLProvider aclProvider) - { + ACLing(ACLProvider aclProvider) { this(aclProvider, null); } - ACLing(ACLProvider aclProvider, List aclList) - { + ACLing(ACLProvider aclProvider, List aclList) { this(aclProvider, aclList, false); } - ACLing(ACLProvider aclProvider, List aclList, boolean applyToParents) - { + ACLing(ACLProvider aclProvider, List aclList, boolean applyToParents) { this.aclProvider = aclProvider; this.aclList = (aclList != null) ? ImmutableList.copyOf(aclList) : null; this.applyToParents = applyToParents; } - InternalACLProvider getACLProviderForParents() - { + InternalACLProvider getACLProviderForParents() { return applyToParents ? this : aclProvider; } - List getAclList(String path) - { - if ( aclList != null ) return aclList; - if ( path != null ) - { + List getAclList(String path) { + if (aclList != null) return aclList; + if (path != null) { List localAclList = aclProvider.getAclForPath(path); - if ( localAclList != null ) - { + if (localAclList != null) { return localAclList; } } diff --git a/curator-framework/src/main/java/org/apache/curator/framework/imps/AddWatchBuilderImpl.java b/curator-framework/src/main/java/org/apache/curator/framework/imps/AddWatchBuilderImpl.java index 3bdf87a5b..76868e8be 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/imps/AddWatchBuilderImpl.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/imps/AddWatchBuilderImpl.java @@ -19,6 +19,7 @@ package org.apache.curator.framework.imps; +import java.util.concurrent.Executor; import org.apache.curator.RetryLoop; import org.apache.curator.drivers.OperationTrace; import org.apache.curator.framework.api.AddWatchBuilder; @@ -31,23 +32,20 @@ import org.apache.curator.framework.api.WatchableBase; import org.apache.zookeeper.AddWatchMode; import org.apache.zookeeper.Watcher; -import java.util.concurrent.Executor; -public class AddWatchBuilderImpl implements AddWatchBuilder, Pathable, BackgroundOperation -{ +public class AddWatchBuilderImpl implements AddWatchBuilder, Pathable, BackgroundOperation { private final CuratorFrameworkImpl client; private Watching watching; private Backgrounding backgrounding = new Backgrounding(); private AddWatchMode mode = AddWatchMode.PERSISTENT_RECURSIVE; - AddWatchBuilderImpl(CuratorFrameworkImpl client) - { + AddWatchBuilderImpl(CuratorFrameworkImpl client) { this.client = client; watching = new Watching(client, true); } - public AddWatchBuilderImpl(CuratorFrameworkImpl client, Watching watching, Backgrounding backgrounding, AddWatchMode mode) - { + public AddWatchBuilderImpl( + CuratorFrameworkImpl client, Watching watching, Backgrounding backgrounding, AddWatchMode mode) { this.client = client; this.watching = watching; this.backgrounding = backgrounding; @@ -55,143 +53,149 @@ public AddWatchBuilderImpl(CuratorFrameworkImpl client, Watching watching, Backg } @Override - public WatchableBase> inBackground() - { + public WatchableBase> inBackground() { backgrounding = new Backgrounding(); return this; } @Override - public AddWatchBuilder2 withMode(AddWatchMode mode) - { + public AddWatchBuilder2 withMode(AddWatchMode mode) { this.mode = mode; return this; } @Override - public Pathable usingWatcher(Watcher watcher) - { + public Pathable usingWatcher(Watcher watcher) { watching = new Watching(client, watcher); return this; } @Override - public Pathable usingWatcher(CuratorWatcher watcher) - { + public Pathable usingWatcher(CuratorWatcher watcher) { watching = new Watching(client, watcher); return this; } @Override - public WatchableBase> inBackground(Object context) - { + public WatchableBase> inBackground(Object context) { backgrounding = new Backgrounding(context); return this; } @Override - public WatchableBase> inBackground(BackgroundCallback callback) - { + public WatchableBase> inBackground(BackgroundCallback callback) { backgrounding = new Backgrounding(callback); return this; } @Override - public WatchableBase> inBackground(BackgroundCallback callback, Object context) - { + public WatchableBase> inBackground(BackgroundCallback callback, Object context) { backgrounding = new Backgrounding(callback, context); return this; } @Override - public WatchableBase> inBackground(BackgroundCallback callback, Executor executor) - { + public WatchableBase> inBackground(BackgroundCallback callback, Executor executor) { backgrounding = new Backgrounding(callback, executor); return this; } @Override - public WatchableBase> inBackground(BackgroundCallback callback, Object context, Executor executor) - { + public WatchableBase> inBackground(BackgroundCallback callback, Object context, Executor executor) { backgrounding = new Backgrounding(client, callback, context, executor); return this; } @Override - public Void forPath(String path) throws Exception - { - if ( backgrounding.inBackground() ) - { - client.processBackgroundOperation(new OperationAndData<>(this, path, backgrounding.getCallback(), null, backgrounding.getContext(), watching), null); - } - else - { + public Void forPath(String path) throws Exception { + if (backgrounding.inBackground()) { + client.processBackgroundOperation( + new OperationAndData<>( + this, path, backgrounding.getCallback(), null, backgrounding.getContext(), watching), + null); + } else { pathInForeground(path); } return null; } @Override - public void performBackgroundOperation(final OperationAndData data) throws Exception - { + public void performBackgroundOperation(final OperationAndData data) throws Exception { String path = data.getData(); String fixedPath = client.fixForNamespace(path); - try - { - final OperationTrace trace = client.getZookeeperClient().startAdvancedTracer("AddWatchBuilderImpl-Background"); - if ( watching.isWatched() ) - { - client.getZooKeeper().addWatch - ( - fixedPath, - mode, - (rc, path1, ctx) -> { - trace.setReturnCode(rc).setWithWatcher(true).setPath(path1).commit(); - CuratorEvent event = new CuratorEventImpl(client, CuratorEventType.ADD_WATCH, rc, path1, null, ctx, null, null, null, null, null, null); - client.processBackgroundOperation(data, event); - }, - backgrounding.getContext() - ); + try { + final OperationTrace trace = + client.getZookeeperClient().startAdvancedTracer("AddWatchBuilderImpl-Background"); + if (watching.isWatched()) { + client.getZooKeeper() + .addWatch( + fixedPath, + mode, + (rc, path1, ctx) -> { + trace.setReturnCode(rc) + .setWithWatcher(true) + .setPath(path1) + .commit(); + CuratorEvent event = new CuratorEventImpl( + client, + CuratorEventType.ADD_WATCH, + rc, + path1, + null, + ctx, + null, + null, + null, + null, + null, + null); + client.processBackgroundOperation(data, event); + }, + backgrounding.getContext()); + } else { + client.getZooKeeper() + .addWatch( + fixedPath, + watching.getWatcher(path), + mode, + (rc, path1, ctx) -> { + trace.setReturnCode(rc) + .setWithWatcher(true) + .setPath(path1) + .commit(); + CuratorEvent event = new CuratorEventImpl( + client, + CuratorEventType.ADD_WATCH, + rc, + path1, + null, + ctx, + null, + null, + null, + null, + null, + null); + client.processBackgroundOperation(data, event); + }, + backgrounding.getContext()); } - else - { - client.getZooKeeper().addWatch - ( - fixedPath, - watching.getWatcher(path), - mode, - (rc, path1, ctx) -> { - trace.setReturnCode(rc).setWithWatcher(true).setPath(path1).commit(); - CuratorEvent event = new CuratorEventImpl(client, CuratorEventType.ADD_WATCH, rc, path1, null, ctx, null, null, null, null, null, null); - client.processBackgroundOperation(data, event); - }, - backgrounding.getContext() - ); - } - } - catch ( Throwable e ) - { + } catch (Throwable e) { backgrounding.checkError(e, watching); } } - private void pathInForeground(final String path) throws Exception - { + private void pathInForeground(final String path) throws Exception { final String fixedPath = client.fixForNamespace(path); OperationTrace trace = client.getZookeeperClient().startAdvancedTracer("AddWatchBuilderImpl-Foreground"); - RetryLoop.callWithRetry - ( - client.getZookeeperClient(), () -> { - if ( watching.isWatched() ) - { - client.getZooKeeper().addWatch(fixedPath, mode); - } - else - { - client.getZooKeeper().addWatch(fixedPath, watching.getWatcher(path), mode); - } - return null; - }); + RetryLoop.callWithRetry(client.getZookeeperClient(), () -> { + if (watching.isWatched()) { + client.getZooKeeper().addWatch(fixedPath, mode); + } else { + client.getZooKeeper().addWatch(fixedPath, watching.getWatcher(path), mode); + } + return null; + }); trace.setPath(fixedPath).setWithWatcher(true).commit(); } -} \ No newline at end of file +} diff --git a/curator-framework/src/main/java/org/apache/curator/framework/imps/BackgroundOperation.java b/curator-framework/src/main/java/org/apache/curator/framework/imps/BackgroundOperation.java index 22a75c714..2fd812251 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/imps/BackgroundOperation.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/imps/BackgroundOperation.java @@ -19,7 +19,6 @@ package org.apache.curator.framework.imps; -interface BackgroundOperation -{ +interface BackgroundOperation { public void performBackgroundOperation(OperationAndData data) throws Exception; } diff --git a/curator-framework/src/main/java/org/apache/curator/framework/imps/BackgroundSyncImpl.java b/curator-framework/src/main/java/org/apache/curator/framework/imps/BackgroundSyncImpl.java index 1915bd8b0..f8edef3ad 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/imps/BackgroundSyncImpl.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/imps/BackgroundSyncImpl.java @@ -23,36 +23,44 @@ import org.apache.curator.framework.api.CuratorEventType; import org.apache.zookeeper.AsyncCallback; -class BackgroundSyncImpl implements BackgroundOperation -{ +class BackgroundSyncImpl implements BackgroundOperation { private final CuratorFrameworkImpl client; private final Object context; - BackgroundSyncImpl(CuratorFrameworkImpl client, Object context) - { + BackgroundSyncImpl(CuratorFrameworkImpl client, Object context) { this.client = client; this.context = context; } @Override - public void performBackgroundOperation(final OperationAndData operationAndData) throws Exception - { + public void performBackgroundOperation(final OperationAndData operationAndData) throws Exception { final OperationTrace trace = client.getZookeeperClient().startAdvancedTracer("BackgroundSyncImpl"); final String data = operationAndData.getData(); - client.getZooKeeper().sync - ( - data, - new AsyncCallback.VoidCallback() - { - @Override - public void processResult(int rc, String path, Object ctx) - { - trace.setReturnCode(rc).setRequestBytesLength(data).commit(); - CuratorEventImpl event = new CuratorEventImpl(client, CuratorEventType.SYNC, rc, path, null, ctx, null, null, null, null, null, null); - client.processBackgroundOperation(operationAndData, event); - } - }, - context - ); + client.getZooKeeper() + .sync( + data, + new AsyncCallback.VoidCallback() { + @Override + public void processResult(int rc, String path, Object ctx) { + trace.setReturnCode(rc) + .setRequestBytesLength(data) + .commit(); + CuratorEventImpl event = new CuratorEventImpl( + client, + CuratorEventType.SYNC, + rc, + path, + null, + ctx, + null, + null, + null, + null, + null, + null); + client.processBackgroundOperation(operationAndData, event); + } + }, + context); } } diff --git a/curator-framework/src/main/java/org/apache/curator/framework/imps/Backgrounding.java b/curator-framework/src/main/java/org/apache/curator/framework/imps/Backgrounding.java index 6a6aab6aa..60d253c25 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/imps/Backgrounding.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/imps/Backgrounding.java @@ -20,67 +20,58 @@ package org.apache.curator.framework.imps; import com.google.common.base.Throwables; +import java.util.concurrent.Executor; 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.UnhandledErrorListener; import org.apache.curator.utils.ThreadUtils; import org.apache.zookeeper.KeeperException; -import java.util.concurrent.Executor; -public class Backgrounding -{ +public class Backgrounding { private final boolean inBackground; private final Object context; private final BackgroundCallback callback; private final UnhandledErrorListener errorListener; - Backgrounding(Object context) - { + Backgrounding(Object context) { this.inBackground = true; this.context = context; this.callback = null; errorListener = null; } - Backgrounding(BackgroundCallback callback) - { + Backgrounding(BackgroundCallback callback) { this.inBackground = true; this.context = null; this.callback = callback; errorListener = null; } - Backgrounding(boolean inBackground) - { + Backgrounding(boolean inBackground) { this.inBackground = inBackground; this.context = null; this.callback = null; errorListener = null; } - Backgrounding(BackgroundCallback callback, Object context) - { + Backgrounding(BackgroundCallback callback, Object context) { this.inBackground = true; this.context = context; this.callback = callback; errorListener = null; } - Backgrounding(CuratorFrameworkImpl client, BackgroundCallback callback, Object context, Executor executor) - { + Backgrounding(CuratorFrameworkImpl client, BackgroundCallback callback, Object context, Executor executor) { this(wrapCallback(client, callback, executor), context); } - Backgrounding(CuratorFrameworkImpl client, BackgroundCallback callback, Executor executor) - { + Backgrounding(CuratorFrameworkImpl client, BackgroundCallback callback, Executor executor) { this(wrapCallback(client, callback, executor)); } - Backgrounding(Backgrounding rhs, UnhandledErrorListener errorListener) - { - if ( rhs == null ) - { + Backgrounding(Backgrounding rhs, UnhandledErrorListener errorListener) { + if (rhs == null) { rhs = new Backgrounding(); } this.inBackground = rhs.inBackground; @@ -89,86 +80,63 @@ public class Backgrounding this.errorListener = errorListener; } - public Backgrounding(BackgroundCallback callback, UnhandledErrorListener errorListener) - { + public Backgrounding(BackgroundCallback callback, UnhandledErrorListener errorListener) { this.callback = callback; this.errorListener = errorListener; inBackground = true; context = null; } - Backgrounding() - { + Backgrounding() { inBackground = false; context = null; this.callback = null; errorListener = null; } - boolean inBackground() - { + boolean inBackground() { return inBackground; } - Object getContext() - { + Object getContext() { return context; } - BackgroundCallback getCallback() - { + BackgroundCallback getCallback() { return callback; } - void checkError(Throwable e, Watching watching) throws Exception - { - if ( e != null ) - { - if ( errorListener != null ) - { + void checkError(Throwable e, Watching watching) throws Exception { + if (e != null) { + if (errorListener != null) { errorListener.unhandledError("n/a", e); - } - else if ( e instanceof Exception ) - { - throw (Exception)e; - } - else - { + } else if (e instanceof Exception) { + throw (Exception) e; + } else { Throwables.propagate(e); } } } - private static BackgroundCallback wrapCallback(final CuratorFrameworkImpl client, final BackgroundCallback callback, final Executor executor) - { - return new BackgroundCallback() - { + private static BackgroundCallback wrapCallback( + final CuratorFrameworkImpl client, final BackgroundCallback callback, final Executor executor) { + return new BackgroundCallback() { @Override - public void processResult(CuratorFramework dummy, final CuratorEvent event) throws Exception - { - executor.execute - ( - new Runnable() - { - @Override - public void run() - { - try - { - callback.processResult(client, event); - } - catch ( Exception e ) - { - ThreadUtils.checkInterrupted(e); - if ( e instanceof KeeperException ) - { - client.validateConnection(client.codeToState(((KeeperException)e).code())); - } - client.logError("Background operation result handling threw exception", e); - } + public void processResult(CuratorFramework dummy, final CuratorEvent event) throws Exception { + executor.execute(new Runnable() { + @Override + public void run() { + try { + callback.processResult(client, event); + } catch (Exception e) { + ThreadUtils.checkInterrupted(e); + if (e instanceof KeeperException) { + client.validateConnection(client.codeToState(((KeeperException) e).code())); } + client.logError("Background operation result handling threw exception", e); } - ); + } + }); } }; } diff --git a/curator-framework/src/main/java/org/apache/curator/framework/imps/CreateBuilderImpl.java b/curator-framework/src/main/java/org/apache/curator/framework/imps/CreateBuilderImpl.java index ea31ef53c..6d07aa019 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/imps/CreateBuilderImpl.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/imps/CreateBuilderImpl.java @@ -64,8 +64,11 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -public class CreateBuilderImpl implements CreateBuilder, CreateBuilder2, BackgroundOperation, ErrorListenerPathAndBytesable -{ +public class CreateBuilderImpl + implements CreateBuilder, + CreateBuilder2, + BackgroundOperation, + ErrorListenerPathAndBytesable { private final Logger log = LoggerFactory.getLogger(getClass()); private final CuratorFrameworkImpl client; private final ProtectedMode protectedMode = new ProtectedMode(); @@ -83,13 +86,14 @@ public class CreateBuilderImpl implements CreateBuilder, CreateBuilder2, Backgro @VisibleForTesting boolean failNextCreateForTesting = false; + @VisibleForTesting boolean failBeforeNextCreateForTesting = false; + @VisibleForTesting boolean failNextIdempotentCheckForTesting = false; - CreateBuilderImpl(CuratorFrameworkImpl client) - { + CreateBuilderImpl(CuratorFrameworkImpl client) { this.client = client; createMode = CreateMode.PERSISTENT; backgrounding = new Backgrounding(); @@ -102,8 +106,18 @@ public class CreateBuilderImpl implements CreateBuilder, CreateBuilder2, Backgro ttl = -1; } - public CreateBuilderImpl(CuratorFrameworkImpl client, CreateMode createMode, Backgrounding backgrounding, boolean createParentsIfNeeded, boolean createParentsAsContainers, boolean doProtected, boolean compress, boolean setDataIfExists, List aclList, Stat storingStat, long ttl) - { + public CreateBuilderImpl( + CuratorFrameworkImpl client, + CreateMode createMode, + Backgrounding backgrounding, + boolean createParentsIfNeeded, + boolean createParentsAsContainers, + boolean doProtected, + boolean compress, + boolean setDataIfExists, + List aclList, + Stat storingStat, + long ttl) { this.client = client; this.createMode = createMode; this.backgrounding = backgrounding; @@ -114,375 +128,318 @@ public CreateBuilderImpl(CuratorFrameworkImpl client, CreateMode createMode, Bac this.acling = new ACLing(client.getAclProvider(), aclList); this.storingStat = storingStat; this.ttl = ttl; - if ( doProtected ) - { + if (doProtected) { protectedMode.setProtectedMode(); } } - public void setSetDataIfExistsVersion(int version) - { + public void setSetDataIfExistsVersion(int version) { this.setDataIfExistsVersion = version; } @Override - public CreateBuilder2 orSetData() - { + public CreateBuilder2 orSetData() { return orSetData(-1); } @Override - public CreateBuilder2 orSetData(int version) - { + public CreateBuilder2 orSetData(int version) { setDataIfExists = true; setDataIfExistsVersion = version; return this; } @Override - public CreateBuilder2 idempotent() - { + public CreateBuilder2 idempotent() { this.idempotent = true; return this; } @Override - public CreateBuilderMain withTtl(long ttl) - { + public CreateBuilderMain withTtl(long ttl) { this.ttl = ttl; return this; } - TransactionCreateBuilder asTransactionCreateBuilder(final T context, final CuratorMultiTransactionRecord transaction) - { - return new TransactionCreateBuilder() - { + TransactionCreateBuilder asTransactionCreateBuilder( + final T context, final CuratorMultiTransactionRecord transaction) { + return new TransactionCreateBuilder() { @Override - public PathAndBytesable withACL(List aclList) - { + public PathAndBytesable withACL(List aclList) { return withACL(aclList, false); } @Override - public PathAndBytesable withACL(List aclList, boolean applyToParents) - { + public PathAndBytesable withACL(List aclList, boolean applyToParents) { CreateBuilderImpl.this.withACL(aclList, applyToParents); return this; } @Override - public TransactionCreateBuilder2 withTtl(long ttl) - { + public TransactionCreateBuilder2 withTtl(long ttl) { CreateBuilderImpl.this.withTtl(ttl); return this; } @Override - public ACLPathAndBytesable withMode(CreateMode mode) - { + public ACLPathAndBytesable withMode(CreateMode mode) { CreateBuilderImpl.this.withMode(mode); return this; } @Override - public ACLCreateModePathAndBytesable compressed() - { + public ACLCreateModePathAndBytesable compressed() { CreateBuilderImpl.this.compressed(); return this; } @Override - public T forPath(String path) throws Exception - { + public T forPath(String path) throws Exception { return forPath(path, client.getDefaultData()); } @Override - public T forPath(String path, byte[] data) throws Exception - { - if ( compress ) - { + public T forPath(String path, byte[] data) throws Exception { + if (compress) { data = client.getCompressionProvider().compress(path, data); } String fixedPath = client.fixForNamespace(path); - transaction.add(Op.create(fixedPath, data, acling.getAclList(path), createMode, ttl), OperationType.CREATE, path); + transaction.add( + Op.create(fixedPath, data, acling.getAclList(path), createMode, ttl), + OperationType.CREATE, + path); return context; } }; } @Override - public CreateBackgroundModeStatACLable compressed() - { + public CreateBackgroundModeStatACLable compressed() { compress = true; - return new CreateBackgroundModeStatACLable() - { + return new CreateBackgroundModeStatACLable() { @Override - public CreateBackgroundModeACLable storingStatIn(Stat stat) - { + public CreateBackgroundModeACLable storingStatIn(Stat stat) { storingStat = stat; return asCreateBackgroundModeACLable(); } @Override - public ACLCreateModePathAndBytesable creatingParentsIfNeeded() - { + public ACLCreateModePathAndBytesable creatingParentsIfNeeded() { createParentsIfNeeded = true; return asACLCreateModePathAndBytesable(); } @Override - public ACLCreateModePathAndBytesable creatingParentContainersIfNeeded() - { + public ACLCreateModePathAndBytesable creatingParentContainersIfNeeded() { setCreateParentsAsContainers(); return creatingParentsIfNeeded(); } @Override - public ACLPathAndBytesable withProtectedEphemeralSequential() - { + public ACLPathAndBytesable withProtectedEphemeralSequential() { return CreateBuilderImpl.this.withProtectedEphemeralSequential(); } @Override - public BackgroundPathAndBytesable withACL(List aclList) - { + public BackgroundPathAndBytesable withACL(List aclList) { return CreateBuilderImpl.this.withACL(aclList); } @Override - public BackgroundPathAndBytesable withACL(List aclList, boolean applyToParents) - { + public BackgroundPathAndBytesable withACL(List aclList, boolean applyToParents) { return CreateBuilderImpl.this.withACL(aclList, applyToParents); } @Override - public ErrorListenerPathAndBytesable inBackground(BackgroundCallback callback, Object context) - { + public ErrorListenerPathAndBytesable inBackground(BackgroundCallback callback, Object context) { return CreateBuilderImpl.this.inBackground(callback, context); } @Override - public ErrorListenerPathAndBytesable inBackground(BackgroundCallback callback, Object context, Executor executor) - { + public ErrorListenerPathAndBytesable inBackground( + BackgroundCallback callback, Object context, Executor executor) { return CreateBuilderImpl.this.inBackground(callback, context, executor); } @Override - public ErrorListenerPathAndBytesable inBackground() - { + public ErrorListenerPathAndBytesable inBackground() { return CreateBuilderImpl.this.inBackground(); } @Override - public ErrorListenerPathAndBytesable inBackground(Object context) - { + public ErrorListenerPathAndBytesable inBackground(Object context) { return CreateBuilderImpl.this.inBackground(context); } @Override - public ErrorListenerPathAndBytesable inBackground(BackgroundCallback callback) - { + public ErrorListenerPathAndBytesable inBackground(BackgroundCallback callback) { return CreateBuilderImpl.this.inBackground(callback); } @Override - public ErrorListenerPathAndBytesable inBackground(BackgroundCallback callback, Executor executor) - { + public ErrorListenerPathAndBytesable inBackground(BackgroundCallback callback, Executor executor) { return CreateBuilderImpl.this.inBackground(callback, executor); } @Override - public ACLBackgroundPathAndBytesable withMode(CreateMode mode) - { + public ACLBackgroundPathAndBytesable withMode(CreateMode mode) { return CreateBuilderImpl.this.withMode(mode); } @Override - public String forPath(String path, byte[] data) throws Exception - { + public String forPath(String path, byte[] data) throws Exception { return CreateBuilderImpl.this.forPath(path, data); } @Override - public String forPath(String path) throws Exception - { + public String forPath(String path) throws Exception { return CreateBuilderImpl.this.forPath(path); } }; } @Override - public ACLBackgroundPathAndBytesable withACL(List aclList) - { + public ACLBackgroundPathAndBytesable withACL(List aclList) { return withACL(aclList, false); } @Override - public ACLBackgroundPathAndBytesable withACL(List aclList, boolean applyToParents) - { + public ACLBackgroundPathAndBytesable withACL(List aclList, boolean applyToParents) { acling = new ACLing(client.getAclProvider(), aclList, applyToParents); - return new ACLBackgroundPathAndBytesable() - { + return new ACLBackgroundPathAndBytesable() { @Override - public BackgroundPathAndBytesable withACL(List aclList) - { + public BackgroundPathAndBytesable withACL(List aclList) { return CreateBuilderImpl.this.withACL(aclList); } @Override - public BackgroundPathAndBytesable withACL(List aclList, boolean applyToParents) - { + public BackgroundPathAndBytesable withACL(List aclList, boolean applyToParents) { return CreateBuilderImpl.this.withACL(aclList, applyToParents); } @Override - public ErrorListenerPathAndBytesable inBackground() - { + public ErrorListenerPathAndBytesable inBackground() { return CreateBuilderImpl.this.inBackground(); } @Override - public ErrorListenerPathAndBytesable inBackground(BackgroundCallback callback, Object context) - { + public ErrorListenerPathAndBytesable inBackground(BackgroundCallback callback, Object context) { return CreateBuilderImpl.this.inBackground(callback, context); } @Override - public ErrorListenerPathAndBytesable inBackground(BackgroundCallback callback, Object context, Executor executor) - { + public ErrorListenerPathAndBytesable inBackground( + BackgroundCallback callback, Object context, Executor executor) { return CreateBuilderImpl.this.inBackground(callback, context, executor); } @Override - public ErrorListenerPathAndBytesable inBackground(Object context) - { + public ErrorListenerPathAndBytesable inBackground(Object context) { return CreateBuilderImpl.this.inBackground(context); } @Override - public ErrorListenerPathAndBytesable inBackground(BackgroundCallback callback) - { + public ErrorListenerPathAndBytesable inBackground(BackgroundCallback callback) { return CreateBuilderImpl.this.inBackground(callback); } @Override - public ErrorListenerPathAndBytesable inBackground(BackgroundCallback callback, Executor executor) - { + public ErrorListenerPathAndBytesable inBackground(BackgroundCallback callback, Executor executor) { return CreateBuilderImpl.this.inBackground(callback, executor); } @Override - public String forPath(String path, byte[] data) throws Exception - { + public String forPath(String path, byte[] data) throws Exception { return CreateBuilderImpl.this.forPath(path, data); } @Override - public String forPath(String path) throws Exception - { + public String forPath(String path) throws Exception { return CreateBuilderImpl.this.forPath(path); } }; } @Override - public ProtectACLCreateModeStatPathAndBytesable creatingParentContainersIfNeeded() - { + public ProtectACLCreateModeStatPathAndBytesable creatingParentContainersIfNeeded() { setCreateParentsAsContainers(); return creatingParentsIfNeeded(); } - private void setCreateParentsAsContainers() - { - if ( client.useContainerParentsIfAvailable() ) - { + private void setCreateParentsAsContainers() { + if (client.useContainerParentsIfAvailable()) { createParentsAsContainers = true; } } @Override - public ProtectACLCreateModeStatPathAndBytesable creatingParentsIfNeeded() - { + public ProtectACLCreateModeStatPathAndBytesable creatingParentsIfNeeded() { createParentsIfNeeded = true; - return new ProtectACLCreateModeStatPathAndBytesable() - { + return new ProtectACLCreateModeStatPathAndBytesable() { @Override - public ACLCreateModeBackgroundPathAndBytesable withProtection() - { + public ACLCreateModeBackgroundPathAndBytesable withProtection() { return CreateBuilderImpl.this.withProtection(); } @Override - public BackgroundPathAndBytesable withACL(List aclList) - { + public BackgroundPathAndBytesable withACL(List aclList) { return withACL(aclList, false); } @Override - public BackgroundPathAndBytesable withACL(List aclList, boolean applyToParents) - { + public BackgroundPathAndBytesable withACL(List aclList, boolean applyToParents) { return CreateBuilderImpl.this.withACL(aclList, applyToParents); } @Override - public ErrorListenerPathAndBytesable inBackground() - { + public ErrorListenerPathAndBytesable inBackground() { return CreateBuilderImpl.this.inBackground(); } @Override - public ErrorListenerPathAndBytesable inBackground(Object context) - { + public ErrorListenerPathAndBytesable inBackground(Object context) { return CreateBuilderImpl.this.inBackground(context); } @Override - public ErrorListenerPathAndBytesable inBackground(BackgroundCallback callback) - { + public ErrorListenerPathAndBytesable inBackground(BackgroundCallback callback) { return CreateBuilderImpl.this.inBackground(callback); } @Override - public ErrorListenerPathAndBytesable inBackground(BackgroundCallback callback, Object context) - { + public ErrorListenerPathAndBytesable inBackground(BackgroundCallback callback, Object context) { return CreateBuilderImpl.this.inBackground(callback, context); } @Override - public ErrorListenerPathAndBytesable inBackground(BackgroundCallback callback, Executor executor) - { + public ErrorListenerPathAndBytesable inBackground(BackgroundCallback callback, Executor executor) { return CreateBuilderImpl.this.inBackground(callback, executor); } @Override - public ErrorListenerPathAndBytesable inBackground(BackgroundCallback callback, Object context, Executor executor) - { + public ErrorListenerPathAndBytesable inBackground( + BackgroundCallback callback, Object context, Executor executor) { return CreateBuilderImpl.this.inBackground(callback, context, executor); } @Override - public ACLBackgroundPathAndBytesable withMode(CreateMode mode) - { + public ACLBackgroundPathAndBytesable withMode(CreateMode mode) { return CreateBuilderImpl.this.withMode(mode); } @Override - public String forPath(String path, byte[] data) throws Exception - { + public String forPath(String path, byte[] data) throws Exception { return CreateBuilderImpl.this.forPath(path, data); } @Override - public String forPath(String path) throws Exception - { + public String forPath(String path) throws Exception { return CreateBuilderImpl.this.forPath(path); } @Override - public ACLBackgroundPathAndBytesable storingStatIn(Stat stat) - { + public ACLBackgroundPathAndBytesable storingStatIn(Stat stat) { storingStat = stat; return CreateBuilderImpl.this; } @@ -490,113 +447,96 @@ public ACLBackgroundPathAndBytesable storingStatIn(Stat stat) } @Override - public ACLCreateModeStatBackgroundPathAndBytesable withProtection() - { + public ACLCreateModeStatBackgroundPathAndBytesable withProtection() { protectedMode.setProtectedMode(); return asACLCreateModeStatBackgroundPathAndBytesable(); } @Override - public ACLPathAndBytesable withProtectedEphemeralSequential() - { + public ACLPathAndBytesable withProtectedEphemeralSequential() { protectedMode.setProtectedMode(); createMode = CreateMode.EPHEMERAL_SEQUENTIAL; - return new ACLPathAndBytesable() - { + return new ACLPathAndBytesable() { @Override - public PathAndBytesable withACL(List aclList) - { + public PathAndBytesable withACL(List aclList) { return CreateBuilderImpl.this.withACL(aclList); } @Override - public PathAndBytesable withACL(List aclList, boolean applyToParents) - { + public PathAndBytesable withACL(List aclList, boolean applyToParents) { return CreateBuilderImpl.this.withACL(aclList, applyToParents); } @Override - public String forPath(String path, byte[] data) throws Exception - { + public String forPath(String path, byte[] data) throws Exception { return CreateBuilderImpl.this.forPath(path, data); } @Override - public String forPath(String path) throws Exception - { + public String forPath(String path) throws Exception { return CreateBuilderImpl.this.forPath(path); } }; } @Override - public ACLBackgroundPathAndBytesable withMode(CreateMode mode) - { + public ACLBackgroundPathAndBytesable withMode(CreateMode mode) { createMode = mode; return this; } @Override - public ErrorListenerPathAndBytesable inBackground(BackgroundCallback callback, Object context) - { + public ErrorListenerPathAndBytesable inBackground(BackgroundCallback callback, Object context) { backgrounding = new Backgrounding(callback, context); return this; } @Override - public ErrorListenerPathAndBytesable inBackground(BackgroundCallback callback, Object context, Executor executor) - { + public ErrorListenerPathAndBytesable inBackground( + BackgroundCallback callback, Object context, Executor executor) { backgrounding = new Backgrounding(client, callback, context, executor); return this; } @Override - public ErrorListenerPathAndBytesable inBackground(BackgroundCallback callback) - { + public ErrorListenerPathAndBytesable inBackground(BackgroundCallback callback) { backgrounding = new Backgrounding(callback); return this; } @Override - public ErrorListenerPathAndBytesable inBackground(BackgroundCallback callback, Executor executor) - { + public ErrorListenerPathAndBytesable inBackground(BackgroundCallback callback, Executor executor) { backgrounding = new Backgrounding(client, callback, executor); return this; } @Override - public ErrorListenerPathAndBytesable inBackground() - { + public ErrorListenerPathAndBytesable inBackground() { backgrounding = new Backgrounding(true); return this; } @Override - public ErrorListenerPathAndBytesable inBackground(Object context) - { + public ErrorListenerPathAndBytesable inBackground(Object context) { backgrounding = new Backgrounding(context); return this; } @Override - public PathAndBytesable withUnhandledErrorListener(UnhandledErrorListener listener) - { + public PathAndBytesable withUnhandledErrorListener(UnhandledErrorListener listener) { backgrounding = new Backgrounding(backgrounding, listener); return this; } @Override - public String forPath(String path) throws Exception - { + public String forPath(String path) throws Exception { return forPath(path, client.getDefaultData()); } @Override - public String forPath(final String givenPath, byte[] data) throws Exception - { - if ( compress ) - { + public String forPath(final String givenPath, byte[] data) throws Exception { + if (compress) { data = client.getCompressionProvider().compress(givenPath, data); } @@ -605,35 +545,29 @@ public String forPath(final String givenPath, byte[] data) throws Exception client.getSchemaSet().getSchema(givenPath).validateCreate(createMode, givenPath, data, aclList); String returnPath = null; - if ( backgrounding.inBackground() ) - { + if (backgrounding.inBackground()) { pathInBackground(adjustedPath, data, givenPath); - } - else - { + } else { String path = protectedPathInForeground(adjustedPath, data, aclList); returnPath = client.unfixForNamespace(path); } return returnPath; } - private String protectedPathInForeground(String adjustedPath, byte[] data, List aclList) throws Exception - { - try - { + private String protectedPathInForeground(String adjustedPath, byte[] data, List aclList) throws Exception { + try { return pathInForeground(adjustedPath, data, aclList); - } - catch ( Exception e) - { + } catch (Exception e) { ThreadUtils.checkInterrupted(e); - if ( ( e instanceof KeeperException.ConnectionLossException || - !( e instanceof KeeperException )) && protectedMode.doProtected() ) - { + if ((e instanceof KeeperException.ConnectionLossException || !(e instanceof KeeperException)) + && protectedMode.doProtected()) { /* * CURATOR-45 + CURATOR-79: we don't know if the create operation was successful or not, * register the znode to be sure it is deleted later. */ - new FindAndDeleteProtectedNodeInBackground(client, ZKPaths.getPathAndNode(adjustedPath).getPath(), protectedMode.protectedId()).execute(); + new FindAndDeleteProtectedNodeInBackground( + client, ZKPaths.getPathAndNode(adjustedPath).getPath(), protectedMode.protectedId()) + .execute(); /* * The current UUID is scheduled to be deleted, it is not safe to use it again. * If this builder is used again later create a new UUID @@ -646,57 +580,60 @@ private String protectedPathInForeground(String adjustedPath, byte[] data, List< } @Override - public void performBackgroundOperation(final OperationAndData operationAndData) throws Exception - { - try - { - final OperationTrace trace = client.getZookeeperClient().startAdvancedTracer("CreateBuilderImpl-Background"); + public void performBackgroundOperation(final OperationAndData operationAndData) throws Exception { + try { + final OperationTrace trace = + client.getZookeeperClient().startAdvancedTracer("CreateBuilderImpl-Background"); final byte[] data = operationAndData.getData().getData(); - AsyncCallback.Create2Callback callback = new AsyncCallback.Create2Callback() - { + AsyncCallback.Create2Callback callback = new AsyncCallback.Create2Callback() { @Override - public void processResult(int rc, String path, Object ctx, String name, Stat stat) - { - trace.setReturnCode(rc).setRequestBytesLength(data).setPath(path).commit(); + public void processResult(int rc, String path, Object ctx, String name, Stat stat) { + trace.setReturnCode(rc) + .setRequestBytesLength(data) + .setPath(path) + .commit(); - if ( (stat != null) && (storingStat != null) ) - { + if ((stat != null) && (storingStat != null)) { DataTree.copyStat(stat, storingStat); } - if ( (rc == KeeperException.Code.NONODE.intValue()) && createParentsIfNeeded ) - { - backgroundCreateParentsThenNode(client, operationAndData, operationAndData.getData().getPath(), backgrounding, acling.getACLProviderForParents(), createParentsAsContainers); - } - else if ( (rc == KeeperException.Code.NODEEXISTS.intValue()) && setDataIfExists ) - { - backgroundSetData(client, operationAndData, operationAndData.getData().getPath(), backgrounding); - } - else if ( (rc == KeeperException.Code.NODEEXISTS.intValue()) && idempotent ) - { - backgroundCheckIdempotent(client, operationAndData, operationAndData.getData().getPath(), backgrounding); - } - else - { + if ((rc == KeeperException.Code.NONODE.intValue()) && createParentsIfNeeded) { + backgroundCreateParentsThenNode( + client, + operationAndData, + operationAndData.getData().getPath(), + backgrounding, + acling.getACLProviderForParents(), + createParentsAsContainers); + } else if ((rc == KeeperException.Code.NODEEXISTS.intValue()) && setDataIfExists) { + backgroundSetData( + client, + operationAndData, + operationAndData.getData().getPath(), + backgrounding); + } else if ((rc == KeeperException.Code.NODEEXISTS.intValue()) && idempotent) { + backgroundCheckIdempotent( + client, + operationAndData, + operationAndData.getData().getPath(), + backgrounding); + } else { sendBackgroundResponse(rc, path, ctx, name, stat, operationAndData); } } }; - client.getZooKeeper().create - ( - operationAndData.getData().getPath(), - data, - acling.getAclList(operationAndData.getData().getPath()), - createMode, - callback, - backgrounding.getContext(), - ttl - ); - - } - catch ( Throwable e ) - { + client.getZooKeeper() + .create( + operationAndData.getData().getPath(), + data, + acling.getAclList(operationAndData.getData().getPath()), + createMode, + callback, + backgrounding.getContext(), + ttl); + + } catch (Throwable e) { backgrounding.checkError(e, null); } } @@ -708,14 +645,12 @@ public CreateProtectACLCreateModePathAndBytesable storingStatIn(Stat sta return new CreateProtectACLCreateModePathAndBytesable() { @Override - public BackgroundPathAndBytesable withACL(List aclList) - { + public BackgroundPathAndBytesable withACL(List aclList) { return CreateBuilderImpl.this.withACL(aclList); } @Override - public BackgroundPathAndBytesable withACL(List aclList, boolean applyToParents) - { + public BackgroundPathAndBytesable withACL(List aclList, boolean applyToParents) { return CreateBuilderImpl.this.withACL(aclList, applyToParents); } @@ -745,8 +680,8 @@ public ErrorListenerPathAndBytesable inBackground(BackgroundCallback cal } @Override - public ErrorListenerPathAndBytesable inBackground(BackgroundCallback callback, Object context, - Executor executor) { + public ErrorListenerPathAndBytesable inBackground( + BackgroundCallback callback, Object context, Executor executor) { return CreateBuilderImpl.this.inBackground(callback, context, executor); } @@ -782,22 +717,22 @@ public ProtectACLCreateModePathAndBytesable creatingParentContainersIfNe }; } - static void backgroundCreateParentsThenNode(final CuratorFrameworkImpl client, final OperationAndData mainOperationAndData, final String path, Backgrounding backgrounding, final InternalACLProvider aclProvider, final boolean createParentsAsContainers) - { - BackgroundOperation operation = new BackgroundOperation() - { - @Override - public void performBackgroundOperation(OperationAndData dummy) throws Exception - { - try - { + static void backgroundCreateParentsThenNode( + final CuratorFrameworkImpl client, + final OperationAndData mainOperationAndData, + final String path, + Backgrounding backgrounding, + final InternalACLProvider aclProvider, + final boolean createParentsAsContainers) { + BackgroundOperation operation = new BackgroundOperation() { + @Override + public void performBackgroundOperation(OperationAndData dummy) throws Exception { + try { ZKPaths.mkdirs(client.getZooKeeper(), path, false, aclProvider, createParentsAsContainers); - } - catch ( KeeperException e ) - { - if ( !client.getZookeeperClient().getRetryPolicy().allowRetry(e) ) - { - sendBackgroundResponse(client, e.code().intValue(), e.getPath(), null, null, null, mainOperationAndData); + } catch (KeeperException e) { + if (!client.getZookeeperClient().getRetryPolicy().allowRetry(e)) { + sendBackgroundResponse( + client, e.code().intValue(), e.getPath(), null, null, null, mainOperationAndData); throw e; } // otherwise safe to ignore as it will get retried @@ -805,38 +740,38 @@ public void performBackgroundOperation(OperationAndData dummy) throws Excepti client.queueOperation(mainOperationAndData); } }; - OperationAndData parentOperation = new OperationAndData<>(operation, mainOperationAndData.getData(), null, null, backgrounding.getContext(), null); + OperationAndData parentOperation = new OperationAndData<>( + operation, mainOperationAndData.getData(), null, null, backgrounding.getContext(), null); client.queueOperation(parentOperation); } - private void backgroundSetData(final CuratorFrameworkImpl client, final OperationAndData mainOperationAndData, final String path, final Backgrounding backgrounding) - { - final AsyncCallback.StatCallback statCallback = new AsyncCallback.StatCallback() - { - @Override - public void processResult(int rc, String path, Object ctx, Stat stat) - { - if ( rc == KeeperException.Code.NONODE.intValue() ) - { - client.queueOperation(mainOperationAndData); // try to create it again - } - else - { + private void backgroundSetData( + final CuratorFrameworkImpl client, + final OperationAndData mainOperationAndData, + final String path, + final Backgrounding backgrounding) { + final AsyncCallback.StatCallback statCallback = new AsyncCallback.StatCallback() { + @Override + public void processResult(int rc, String path, Object ctx, Stat stat) { + if (rc == KeeperException.Code.NONODE.intValue()) { + client.queueOperation(mainOperationAndData); // try to create it again + } else { sendBackgroundResponse(rc, path, ctx, path, stat, mainOperationAndData); } } }; - BackgroundOperation operation = new BackgroundOperation() - { - @Override - public void performBackgroundOperation(OperationAndData op) throws Exception - { - try - { - client.getZooKeeper().setData(path, mainOperationAndData.getData().getData(), setDataIfExistsVersion, statCallback, backgrounding.getContext()); - } - catch ( KeeperException e ) - { + BackgroundOperation operation = new BackgroundOperation() { + @Override + public void performBackgroundOperation(OperationAndData op) throws Exception { + try { + client.getZooKeeper() + .setData( + path, + mainOperationAndData.getData().getData(), + setDataIfExistsVersion, + statCallback, + backgrounding.getContext()); + } catch (KeeperException e) { // ignore } } @@ -844,28 +779,23 @@ public void performBackgroundOperation(OperationAndData op) throws client.queueOperation(new OperationAndData<>(operation, null, null, null, null, null)); } - private void backgroundCheckIdempotent(final CuratorFrameworkImpl client, final OperationAndData mainOperationAndData, final String path, final Backgrounding backgrounding) - { - final AsyncCallback.DataCallback dataCallback = new AsyncCallback.DataCallback() - { - @Override - public void processResult(int rc, String path, Object ctx, byte[] data, Stat stat) - { - if ( rc == KeeperException.Code.NONODE.intValue() ) - { - client.queueOperation(mainOperationAndData); // try to create it again - } - else - { - if ( rc == KeeperException.Code.OK.intValue() ) - { - if ( failNextIdempotentCheckForTesting ) - { + private void backgroundCheckIdempotent( + final CuratorFrameworkImpl client, + final OperationAndData mainOperationAndData, + final String path, + final Backgrounding backgrounding) { + final AsyncCallback.DataCallback dataCallback = new AsyncCallback.DataCallback() { + @Override + public void processResult(int rc, String path, Object ctx, byte[] data, Stat stat) { + if (rc == KeeperException.Code.NONODE.intValue()) { + client.queueOperation(mainOperationAndData); // try to create it again + } else { + if (rc == KeeperException.Code.OK.intValue()) { + if (failNextIdempotentCheckForTesting) { failNextIdempotentCheckForTesting = false; rc = KeeperException.Code.CONNECTIONLOSS.intValue(); - } - else if ( !IdempotentUtils.matches(0, mainOperationAndData.getData().getData(), stat.getVersion(), data) ) - { + } else if (!IdempotentUtils.matches( + 0, mainOperationAndData.getData().getData(), stat.getVersion(), data)) { rc = KeeperException.Code.NODEEXISTS.intValue(); } } @@ -873,17 +803,12 @@ else if ( !IdempotentUtils.matches(0, mainOperationAndData.getData().getData(), } } }; - BackgroundOperation operation = new BackgroundOperation() - { + BackgroundOperation operation = new BackgroundOperation() { @Override - public void performBackgroundOperation(OperationAndData op) throws Exception - { - try - { + public void performBackgroundOperation(OperationAndData op) throws Exception { + try { client.getZooKeeper().getData(path, false, dataCallback, backgrounding.getContext()); - } - catch ( KeeperException e ) - { + } catch (KeeperException e) { // ignore client.logError("Unexpected exception in async idempotent check for, ignoring: " + path, e); } @@ -892,82 +817,76 @@ public void performBackgroundOperation(OperationAndData op) throws client.queueOperation(new OperationAndData<>(operation, null, null, null, null, null)); } - private void sendBackgroundResponse(int rc, String path, Object ctx, String name, Stat stat, OperationAndData operationAndData) - { + private void sendBackgroundResponse( + int rc, String path, Object ctx, String name, Stat stat, OperationAndData operationAndData) { sendBackgroundResponse(client, rc, path, ctx, name, stat, operationAndData); } - private static void sendBackgroundResponse(CuratorFrameworkImpl client, int rc, String path, Object ctx, String name, Stat stat, OperationAndData operationAndData) - { - CuratorEvent event = new CuratorEventImpl(client, CuratorEventType.CREATE, rc, path, name, ctx, stat, null, null, null, null, null); + private static void sendBackgroundResponse( + CuratorFrameworkImpl client, + int rc, + String path, + Object ctx, + String name, + Stat stat, + OperationAndData operationAndData) { + CuratorEvent event = new CuratorEventImpl( + client, CuratorEventType.CREATE, rc, path, name, ctx, stat, null, null, null, null, null); client.processBackgroundOperation(operationAndData, event); } - private ACLCreateModePathAndBytesable asACLCreateModePathAndBytesable() - { - return new ACLCreateModePathAndBytesable() - { + private ACLCreateModePathAndBytesable asACLCreateModePathAndBytesable() { + return new ACLCreateModePathAndBytesable() { @Override - public PathAndBytesable withACL(List aclList) - { + public PathAndBytesable withACL(List aclList) { return CreateBuilderImpl.this.withACL(aclList); } @Override - public PathAndBytesable withACL(List aclList, boolean applyToParents) - { + public PathAndBytesable withACL(List aclList, boolean applyToParents) { CreateBuilderImpl.this.withACL(aclList, applyToParents); return this; } @Override - public ACLPathAndBytesable withMode(CreateMode mode) - { + public ACLPathAndBytesable withMode(CreateMode mode) { createMode = mode; - return new ACLPathAndBytesable() - { + return new ACLPathAndBytesable() { @Override - public PathAndBytesable withACL(List aclList) - { + public PathAndBytesable withACL(List aclList) { return CreateBuilderImpl.this.withACL(aclList); } @Override - public PathAndBytesable withACL(List aclList, boolean applyToParents) - { + public PathAndBytesable withACL(List aclList, boolean applyToParents) { return CreateBuilderImpl.this.withACL(aclList, applyToParents); } @Override - public String forPath(String path, byte[] data) throws Exception - { + public String forPath(String path, byte[] data) throws Exception { return CreateBuilderImpl.this.forPath(path, data); } @Override - public String forPath(String path) throws Exception - { + public String forPath(String path) throws Exception { return CreateBuilderImpl.this.forPath(path); } }; } @Override - public String forPath(String path, byte[] data) throws Exception - { + public String forPath(String path, byte[] data) throws Exception { return CreateBuilderImpl.this.forPath(path, data); } @Override - public String forPath(String path) throws Exception - { + public String forPath(String path) throws Exception { return CreateBuilderImpl.this.forPath(path); } }; } - private CreateBackgroundModeACLable asCreateBackgroundModeACLable() - { + private CreateBackgroundModeACLable asCreateBackgroundModeACLable() { return new CreateBackgroundModeACLable() { @Override @@ -976,8 +895,7 @@ public BackgroundPathAndBytesable withACL(List aclList) { } @Override - public BackgroundPathAndBytesable withACL(List aclList, boolean applyToParents) - { + public BackgroundPathAndBytesable withACL(List aclList, boolean applyToParents) { return CreateBuilderImpl.this.withACL(aclList, applyToParents); } @@ -997,7 +915,8 @@ public String forPath(String path, byte[] data) throws Exception { } @Override - public ErrorListenerPathAndBytesable inBackground(BackgroundCallback callback, Object context, Executor executor) { + public ErrorListenerPathAndBytesable inBackground( + BackgroundCallback callback, Object context, Executor executor) { return CreateBuilderImpl.this.inBackground(callback, context, executor); } @@ -1045,18 +964,15 @@ public ACLCreateModePathAndBytesable creatingParentContainersIfNeeded() }; } - private ACLCreateModeStatBackgroundPathAndBytesable asACLCreateModeStatBackgroundPathAndBytesable() - { - return new ACLCreateModeStatBackgroundPathAndBytesable() - { + private ACLCreateModeStatBackgroundPathAndBytesable asACLCreateModeStatBackgroundPathAndBytesable() { + return new ACLCreateModeStatBackgroundPathAndBytesable() { @Override public BackgroundPathAndBytesable withACL(List aclList) { return CreateBuilderImpl.this.withACL(aclList); } @Override - public BackgroundPathAndBytesable withACL(List aclList, boolean applyToParents) - { + public BackgroundPathAndBytesable withACL(List aclList, boolean applyToParents) { CreateBuilderImpl.this.withACL(aclList, applyToParents); return this; } @@ -1067,7 +983,8 @@ public ErrorListenerPathAndBytesable inBackground() { } @Override - public ErrorListenerPathAndBytesable inBackground(BackgroundCallback callback, Object context, Executor executor) { + public ErrorListenerPathAndBytesable inBackground( + BackgroundCallback callback, Object context, Executor executor) { return CreateBuilderImpl.this.inBackground(callback, context, executor); } @@ -1117,232 +1034,201 @@ public ACLCreateModeBackgroundPathAndBytesable storingStatIn(Stat stat) @VisibleForTesting volatile boolean debugForceFindProtectedNode = false; - private void pathInBackground(final String path, final byte[] data, final String givenPath) - { + private void pathInBackground(final String path, final byte[] data, final String givenPath) { final AtomicBoolean firstTime = new AtomicBoolean(true); - OperationAndData operationAndData = new OperationAndData(this, new PathAndBytes(path, data), backgrounding.getCallback(), - new OperationAndData.ErrorCallback() - { - public void retriesExhausted(OperationAndData operationAndData) - { - if ( protectedMode.doProtected() ) - { - // all retries have failed, findProtectedNodeInForeground(..) included, schedule a clean up - new FindAndDeleteProtectedNodeInBackground(client, ZKPaths.getPathAndNode(path).getPath(), protectedMode.protectedId()).execute(); - // assign a new id if this builder is used again later - protectedMode.resetProtectedId(); - } - } - }, - backgrounding.getContext(), - null) - { - @Override - void callPerformBackgroundOperation() throws Exception - { - boolean callSuper = true; - boolean localFirstTime = firstTime.getAndSet(false) && !debugForceFindProtectedNode; + OperationAndData operationAndData = + new OperationAndData( + this, + new PathAndBytes(path, data), + backgrounding.getCallback(), + new OperationAndData.ErrorCallback() { + public void retriesExhausted(OperationAndData operationAndData) { + if (protectedMode.doProtected()) { + // all retries have failed, findProtectedNodeInForeground(..) included, schedule a + // clean up + new FindAndDeleteProtectedNodeInBackground( + client, + ZKPaths.getPathAndNode(path).getPath(), + protectedMode.protectedId()) + .execute(); + // assign a new id if this builder is used again later + protectedMode.resetProtectedId(); + } + } + }, + backgrounding.getContext(), + null) { + @Override + void callPerformBackgroundOperation() throws Exception { + boolean callSuper = true; + boolean localFirstTime = firstTime.getAndSet(false) && !debugForceFindProtectedNode; - protectedMode.checkSetSessionId(client, createMode); - if ( !localFirstTime && protectedMode.doProtected() ) - { - debugForceFindProtectedNode = false; - String createdPath = null; - try - { - createdPath = findProtectedNodeInForeground(path); - } - catch ( KeeperException.ConnectionLossException e ) - { - sendBackgroundResponse(KeeperException.Code.CONNECTIONLOSS.intValue(), path, backgrounding.getContext(), null, null, this); - callSuper = false; - } - if ( createdPath != null ) - { - try - { - sendBackgroundResponse(KeeperException.Code.OK.intValue(), createdPath, backgrounding.getContext(), createdPath, null, this); + protectedMode.checkSetSessionId(client, createMode); + if (!localFirstTime && protectedMode.doProtected()) { + debugForceFindProtectedNode = false; + String createdPath = null; + try { + createdPath = findProtectedNodeInForeground(path); + } catch (KeeperException.ConnectionLossException e) { + sendBackgroundResponse( + KeeperException.Code.CONNECTIONLOSS.intValue(), + path, + backgrounding.getContext(), + null, + null, + this); + callSuper = false; + } + if (createdPath != null) { + try { + sendBackgroundResponse( + KeeperException.Code.OK.intValue(), + createdPath, + backgrounding.getContext(), + createdPath, + null, + this); + } catch (Exception e) { + ThreadUtils.checkInterrupted(e); + client.logError("Processing protected create for path: " + givenPath, e); + } + callSuper = false; + } } - catch ( Exception e ) - { - ThreadUtils.checkInterrupted(e); - client.logError("Processing protected create for path: " + givenPath, e); + + if (failBeforeNextCreateForTesting) { + failBeforeNextCreateForTesting = false; + throw new KeeperException.ConnectionLossException(); } - callSuper = false; - } - } - if ( failBeforeNextCreateForTesting ) - { - failBeforeNextCreateForTesting = false; - throw new KeeperException.ConnectionLossException(); - } + if (failNextCreateForTesting) { + failNextCreateForTesting = false; + try { + // simulate success on server without notification to client + // if another error occurs in pathInForeground that isn't NodeExists, this hangs instead + // of fully propagating the error. Likely not worth fixing though. + pathInForeground(path, data, acling.getAclList(path)); + } catch (KeeperException.NodeExistsException e) { + client.logError( + "NodeExists while injecting failure after create, ignoring: " + givenPath, e); + } + throw new KeeperException.ConnectionLossException(); + } - if ( failNextCreateForTesting ) - { - failNextCreateForTesting = false; - try - { - // simulate success on server without notification to client - // if another error occurs in pathInForeground that isn't NodeExists, this hangs instead of fully propagating the error. Likely not worth fixing though. - pathInForeground(path, data, acling.getAclList(path)); - } - catch ( KeeperException.NodeExistsException e ) - { - client.logError("NodeExists while injecting failure after create, ignoring: " + givenPath, e); + if (callSuper) { + super.callPerformBackgroundOperation(); + } } - throw new KeeperException.ConnectionLossException(); - } - - if ( callSuper ) - { - super.callPerformBackgroundOperation(); - } - } - }; + }; client.processBackgroundOperation(operationAndData, null); } - private String pathInForeground(final String path, final byte[] data, final List aclList) throws Exception - { + private String pathInForeground(final String path, final byte[] data, final List aclList) throws Exception { OperationTrace trace = client.getZookeeperClient().startAdvancedTracer("CreateBuilderImpl-Foreground"); final AtomicBoolean firstTime = new AtomicBoolean(true); - String returnPath = RetryLoop.callWithRetry - ( - client.getZookeeperClient(), - new Callable() - { - @Override - public String call() throws Exception - { - boolean localFirstTime = firstTime.getAndSet(false) && !debugForceFindProtectedNode; - protectedMode.checkSetSessionId(client, createMode); + String returnPath = RetryLoop.callWithRetry(client.getZookeeperClient(), new Callable() { + @Override + public String call() throws Exception { + boolean localFirstTime = firstTime.getAndSet(false) && !debugForceFindProtectedNode; + protectedMode.checkSetSessionId(client, createMode); - String createdPath = null; - if ( !localFirstTime && protectedMode.doProtected() ) - { - debugForceFindProtectedNode = false; - createdPath = findProtectedNodeInForeground(path); - } + String createdPath = null; + if (!localFirstTime && protectedMode.doProtected()) { + debugForceFindProtectedNode = false; + createdPath = findProtectedNodeInForeground(path); + } - if ( createdPath == null ) - { - try - { - if ( failBeforeNextCreateForTesting ) - { - failBeforeNextCreateForTesting = false; - throw new KeeperException.ConnectionLossException(); - } - createdPath = client.getZooKeeper().create(path, data, aclList, createMode, storingStat, ttl); + if (createdPath == null) { + try { + if (failBeforeNextCreateForTesting) { + failBeforeNextCreateForTesting = false; + throw new KeeperException.ConnectionLossException(); + } + createdPath = client.getZooKeeper().create(path, data, aclList, createMode, storingStat, ttl); + } catch (KeeperException.NoNodeException e) { + if (createParentsIfNeeded) { + ZKPaths.mkdirs( + client.getZooKeeper(), + path, + false, + acling.getACLProviderForParents(), + createParentsAsContainers); + createdPath = client.getZooKeeper() + .create(path, data, acling.getAclList(path), createMode, storingStat, ttl); + } else { + throw e; + } + } catch (KeeperException.NodeExistsException e) { + if (setDataIfExists) { + Stat setStat = client.getZooKeeper().setData(path, data, setDataIfExistsVersion); + if (storingStat != null) { + DataTree.copyStat(setStat, storingStat); } - catch ( KeeperException.NoNodeException e ) - { - if ( createParentsIfNeeded ) - { - ZKPaths.mkdirs(client.getZooKeeper(), path, false, acling.getACLProviderForParents(), createParentsAsContainers); - createdPath = client.getZooKeeper().create(path, data, acling.getAclList(path), createMode, storingStat, ttl); - } - else - { - throw e; - } + createdPath = path; + } else if (idempotent) { + if (failNextIdempotentCheckForTesting) { + failNextIdempotentCheckForTesting = false; + throw new KeeperException.ConnectionLossException(); } - catch ( KeeperException.NodeExistsException e ) - { - if ( setDataIfExists ) - { - Stat setStat = client.getZooKeeper().setData(path, data, setDataIfExistsVersion); - if ( storingStat != null ) - { - DataTree.copyStat(setStat, storingStat); - } - createdPath = path; - } - else if ( idempotent ) - { - if ( failNextIdempotentCheckForTesting ) - { - failNextIdempotentCheckForTesting = false; - throw new KeeperException.ConnectionLossException(); - } - Stat getStat = new Stat(); - byte[] existingData = client.getZooKeeper().getData(path, false, getStat); - // check to see if data version == 0 and data matches the idempotent case - if ( IdempotentUtils.matches(0, data, getStat.getVersion(), existingData) ) - { - if ( storingStat != null ) - { - DataTree.copyStat(getStat, storingStat); - } - createdPath = path; - } - else - { - throw e; - } - } - else - { - throw e; + Stat getStat = new Stat(); + byte[] existingData = client.getZooKeeper().getData(path, false, getStat); + // check to see if data version == 0 and data matches the idempotent case + if (IdempotentUtils.matches(0, data, getStat.getVersion(), existingData)) { + if (storingStat != null) { + DataTree.copyStat(getStat, storingStat); } + createdPath = path; + } else { + throw e; } + } else { + throw e; } - - if ( failNextCreateForTesting ) - { - failNextCreateForTesting = false; - throw new KeeperException.ConnectionLossException(); - } - return createdPath; } } - ); + + if (failNextCreateForTesting) { + failNextCreateForTesting = false; + throw new KeeperException.ConnectionLossException(); + } + return createdPath; + } + }); trace.setRequestBytesLength(data).setPath(path).commit(); return returnPath; } - private String findProtectedNodeInForeground(final String path) throws Exception - { - OperationTrace trace = client.getZookeeperClient().startAdvancedTracer("CreateBuilderImpl-findProtectedNodeInForeground"); + private String findProtectedNodeInForeground(final String path) throws Exception { + OperationTrace trace = + client.getZookeeperClient().startAdvancedTracer("CreateBuilderImpl-findProtectedNodeInForeground"); - String returnPath = RetryLoop.callWithRetry - ( - client.getZookeeperClient(), - new Callable() - { - @Override - public String call() throws Exception - { - String foundNode = null; - try - { - final ZKPaths.PathAndNode pathAndNode = ZKPaths.getPathAndNode(path); - List children = client.getZooKeeper().getChildren(pathAndNode.getPath(), false); - - foundNode = findNode(children, pathAndNode.getPath(), protectedMode.protectedId()); - log.debug("Protected mode findNode result: {}", foundNode); - - foundNode = protectedMode.validateFoundNode(client, createMode, foundNode); - } - catch ( KeeperException.NoNodeException ignore ) - { - // ignore - } - return foundNode; - } + String returnPath = RetryLoop.callWithRetry(client.getZookeeperClient(), new Callable() { + @Override + public String call() throws Exception { + String foundNode = null; + try { + final ZKPaths.PathAndNode pathAndNode = ZKPaths.getPathAndNode(path); + List children = client.getZooKeeper().getChildren(pathAndNode.getPath(), false); + + foundNode = findNode(children, pathAndNode.getPath(), protectedMode.protectedId()); + log.debug("Protected mode findNode result: {}", foundNode); + + foundNode = protectedMode.validateFoundNode(client, createMode, foundNode); + } catch (KeeperException.NoNodeException ignore) { + // ignore } - ); + return foundNode; + } + }); trace.setPath(path).commit(); return returnPath; } @VisibleForTesting - String adjustPath(String path) throws Exception - { + String adjustPath(String path) throws Exception { return ProtectedUtils.toProtectedZNodePath(path, protectedMode.protectedId()); } @@ -1354,24 +1240,18 @@ String adjustPath(String path) throws Exception * @param protectedId the protected id * @return the absolute path of the znode or null if it is not found */ - static String findNode(final List children, final String path, final String protectedId) - { + static String findNode(final List children, final String path, final String protectedId) { final String protectedPrefix = ProtectedUtils.getProtectedPrefix(protectedId); - String foundNode = Iterables.find - ( + String foundNode = Iterables.find( children, - new Predicate() - { + new Predicate() { @Override - public boolean apply(String node) - { + public boolean apply(String node) { return node.startsWith(protectedPrefix); } }, - null - ); - if ( foundNode != null ) - { + null); + if (foundNode != null) { foundNode = ZKPaths.makePath(path, foundNode); } return foundNode; diff --git a/curator-framework/src/main/java/org/apache/curator/framework/imps/CuratorEventImpl.java b/curator-framework/src/main/java/org/apache/curator/framework/imps/CuratorEventImpl.java index 4e316cd69..e492e46a0 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/imps/CuratorEventImpl.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/imps/CuratorEventImpl.java @@ -20,17 +20,16 @@ package org.apache.curator.framework.imps; import com.google.common.collect.ImmutableList; +import java.util.Arrays; +import java.util.List; import org.apache.curator.framework.api.CuratorEvent; import org.apache.curator.framework.api.CuratorEventType; import org.apache.curator.framework.api.transaction.CuratorTransactionResult; import org.apache.zookeeper.WatchedEvent; import org.apache.zookeeper.data.ACL; import org.apache.zookeeper.data.Stat; -import java.util.Arrays; -import java.util.List; -class CuratorEventImpl implements CuratorEvent -{ +class CuratorEventImpl implements CuratorEvent { private final CuratorEventType type; private final int resultCode; private final String path; @@ -44,91 +43,89 @@ class CuratorEventImpl implements CuratorEvent private final List opResults; @Override - public CuratorEventType getType() - { + public CuratorEventType getType() { return type; } @Override - public int getResultCode() - { + public int getResultCode() { return resultCode; } @Override - public String getPath() - { + public String getPath() { return path; } @Override - public Object getContext() - { + public Object getContext() { return context; } @Override - public Stat getStat() - { + public Stat getStat() { return stat; } @Override - public byte[] getData() - { + public byte[] getData() { return data; } @Override - public String getName() - { + public String getName() { return name; } @Override - public List getChildren() - { + public List getChildren() { return children; } @Override - public WatchedEvent getWatchedEvent() - { + public WatchedEvent getWatchedEvent() { return watchedEvent; } @Override - public List getACLList() - { + public List getACLList() { return aclList; } @Override - public List getOpResults() - { + public List getOpResults() { return opResults; } @Override - public String toString() - { - return "CuratorEventImpl{" + - "type=" + type + - ", resultCode=" + resultCode + - ", path='" + path + '\'' + - ", name='" + name + '\'' + - ", children=" + children + - ", context=" + context + - ", stat=" + stat + - ", data=" + Arrays.toString(data) + - ", watchedEvent=" + watchedEvent + - ", aclList=" + aclList + - ", opResults=" + opResults + - '}'; + public String toString() { + return "CuratorEventImpl{" + "type=" + + type + ", resultCode=" + + resultCode + ", path='" + + path + '\'' + ", name='" + + name + '\'' + ", children=" + + children + ", context=" + + context + ", stat=" + + stat + ", data=" + + Arrays.toString(data) + ", watchedEvent=" + + watchedEvent + ", aclList=" + + aclList + ", opResults=" + + opResults + '}'; } - CuratorEventImpl(CuratorFrameworkImpl client, CuratorEventType type, int resultCode, String path, String name, Object context, Stat stat, byte[] data, List children, WatchedEvent watchedEvent, List aclList, List opResults) - { + CuratorEventImpl( + CuratorFrameworkImpl client, + CuratorEventType type, + int resultCode, + String path, + String name, + Object context, + Stat stat, + byte[] data, + List children, + WatchedEvent watchedEvent, + List aclList, + List opResults) { this.type = type; this.resultCode = resultCode; this.opResults = (opResults != null) ? ImmutableList.copyOf(opResults) : null; diff --git a/curator-framework/src/main/java/org/apache/curator/framework/imps/CuratorFrameworkImpl.java b/curator-framework/src/main/java/org/apache/curator/framework/imps/CuratorFrameworkImpl.java index 3c02a3cd3..9683b8863 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/imps/CuratorFrameworkImpl.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/imps/CuratorFrameworkImpl.java @@ -19,6 +19,9 @@ package org.apache.curator.framework.imps; +import com.google.common.annotations.VisibleForTesting; +import com.google.common.base.Preconditions; +import com.google.common.collect.ImmutableList; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; @@ -37,7 +40,6 @@ import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicReference; - import org.apache.curator.CuratorConnectionLossException; import org.apache.curator.CuratorZookeeperClient; import org.apache.curator.RetryLoop; @@ -90,12 +92,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.google.common.annotations.VisibleForTesting; -import com.google.common.base.Preconditions; -import com.google.common.collect.ImmutableList; - -public class CuratorFrameworkImpl implements CuratorFramework -{ +public class CuratorFrameworkImpl implements CuratorFramework { private final Logger log = LoggerFactory.getLogger(getClass()); private final CuratorZookeeperClient client; private final StandardListenerManager listeners; @@ -124,41 +121,50 @@ public class CuratorFrameworkImpl implements CuratorFramework private volatile ExecutorService executorService; private final AtomicBoolean logAsErrorConnectionErrors = new AtomicBoolean(false); - private static final boolean LOG_ALL_CONNECTION_ISSUES_AS_ERROR_LEVEL = !Boolean.getBoolean(DebugUtils.PROPERTY_LOG_ONLY_FIRST_CONNECTION_ISSUE_AS_ERROR_LEVEL); + private static final boolean LOG_ALL_CONNECTION_ISSUES_AS_ERROR_LEVEL = + !Boolean.getBoolean(DebugUtils.PROPERTY_LOG_ONLY_FIRST_CONNECTION_ISSUE_AS_ERROR_LEVEL); - interface DebugBackgroundListener - { + interface DebugBackgroundListener { void listen(OperationAndData data); } volatile DebugBackgroundListener debugListener = null; + @VisibleForTesting public volatile UnhandledErrorListener debugUnhandledErrorListener = null; private final AtomicReference state; - public CuratorFrameworkImpl(CuratorFrameworkFactory.Builder builder) - { - ZookeeperFactory localZookeeperFactory = makeZookeeperFactory(builder.getZookeeperFactory(), builder.getZkClientConfig()); - this.client = new CuratorZookeeperClient - ( + public CuratorFrameworkImpl(CuratorFrameworkFactory.Builder builder) { + ZookeeperFactory localZookeeperFactory = + makeZookeeperFactory(builder.getZookeeperFactory(), builder.getZkClientConfig()); + this.client = new CuratorZookeeperClient( localZookeeperFactory, builder.getEnsembleProvider(), builder.getSessionTimeoutMs(), builder.getConnectionTimeoutMs(), builder.getWaitForShutdownTimeoutMs(), - new Watcher() - { + new Watcher() { @Override - public void process(WatchedEvent watchedEvent) - { - CuratorEvent event = new CuratorEventImpl(CuratorFrameworkImpl.this, CuratorEventType.WATCHED, watchedEvent.getState().getIntValue(), unfixForNamespace(watchedEvent.getPath()), null, null, null, null, null, watchedEvent, null, null); + public void process(WatchedEvent watchedEvent) { + CuratorEvent event = new CuratorEventImpl( + CuratorFrameworkImpl.this, + CuratorEventType.WATCHED, + watchedEvent.getState().getIntValue(), + unfixForNamespace(watchedEvent.getPath()), + null, + null, + null, + null, + null, + watchedEvent, + null, + null); processEvent(event); } }, builder.getRetryPolicy(), - builder.canBeReadOnly() - ); + builder.canBeReadOnly()); internalConnectionHandler = new StandardInternalConnectionHandler(); listeners = StandardListenerManager.standard(); @@ -168,102 +174,99 @@ public void process(WatchedEvent watchedEvent) namespace = new NamespaceImpl(this, builder.getNamespace()); threadFactory = getThreadFactory(builder); maxCloseWaitMs = builder.getMaxCloseWaitMs(); - connectionStateManager = new ConnectionStateManager(this, builder.getThreadFactory(), builder.getSessionTimeoutMs(), builder.getSimulatedSessionExpirationPercent(), builder.getConnectionStateListenerManagerFactory()); + connectionStateManager = new ConnectionStateManager( + this, + builder.getThreadFactory(), + builder.getSessionTimeoutMs(), + builder.getSimulatedSessionExpirationPercent(), + builder.getConnectionStateListenerManagerFactory()); compressionProvider = builder.getCompressionProvider(); aclProvider = builder.getAclProvider(); state = new AtomicReference(CuratorFrameworkState.LATENT); useContainerParentsIfAvailable = builder.useContainerParentsIfAvailable(); - connectionStateErrorPolicy = Preconditions.checkNotNull(builder.getConnectionStateErrorPolicy(), "errorPolicy cannot be null"); + connectionStateErrorPolicy = + Preconditions.checkNotNull(builder.getConnectionStateErrorPolicy(), "errorPolicy cannot be null"); schemaSet = Preconditions.checkNotNull(builder.getSchemaSet(), "schemaSet cannot be null"); byte[] builderDefaultData = builder.getDefaultData(); - defaultData = (builderDefaultData != null) ? Arrays.copyOf(builderDefaultData, builderDefaultData.length) : new byte[0]; + defaultData = (builderDefaultData != null) + ? Arrays.copyOf(builderDefaultData, builderDefaultData.length) + : new byte[0]; authInfos = buildAuths(builder); failedDeleteManager = new FailedDeleteManager(this); failedRemoveWatcherManager = new FailedRemoveWatchManager(this); namespaceFacadeCache = new NamespaceFacadeCache(this); - ensembleTracker = builder.withEnsembleTracker() ? new EnsembleTracker(this, builder.getEnsembleProvider()) : null; + ensembleTracker = + builder.withEnsembleTracker() ? new EnsembleTracker(this, builder.getEnsembleProvider()) : null; runSafeService = makeRunSafeService(builder); } - private Executor makeRunSafeService(CuratorFrameworkFactory.Builder builder) - { - if ( builder.getRunSafeService() != null ) - { + private Executor makeRunSafeService(CuratorFrameworkFactory.Builder builder) { + if (builder.getRunSafeService() != null) { return builder.getRunSafeService(); } ThreadFactory threadFactory = builder.getThreadFactory(); - if ( threadFactory == null ) - { + if (threadFactory == null) { threadFactory = ThreadUtils.newThreadFactory("SafeNotifyService"); } return Executors.newSingleThreadExecutor(threadFactory); } - private List buildAuths(CuratorFrameworkFactory.Builder builder) - { + private List buildAuths(CuratorFrameworkFactory.Builder builder) { ImmutableList.Builder builder1 = ImmutableList.builder(); - if ( builder.getAuthInfos() != null ) - { + if (builder.getAuthInfos() != null) { builder1.addAll(builder.getAuthInfos()); } return builder1.build(); } @Override - public CompletableFuture runSafe(Runnable runnable) - { + public CompletableFuture runSafe(Runnable runnable) { return CompletableFuture.runAsync(runnable, runSafeService); } @Override - public WatcherRemoveCuratorFramework newWatcherRemoveCuratorFramework() - { + public WatcherRemoveCuratorFramework newWatcherRemoveCuratorFramework() { return new WatcherRemovalFacade(this); } @Override - public QuorumVerifier getCurrentConfig() - { + public QuorumVerifier getCurrentConfig() { return (ensembleTracker != null) ? ensembleTracker.getCurrentConfig() : null; } - private ZookeeperFactory makeZookeeperFactory(final ZookeeperFactory actualZookeeperFactory, ZKClientConfig zkClientConfig) - { - return new ZookeeperFactory() - { + private ZookeeperFactory makeZookeeperFactory( + final ZookeeperFactory actualZookeeperFactory, ZKClientConfig zkClientConfig) { + return new ZookeeperFactory() { @Override - public ZooKeeper newZooKeeper(String connectString, int sessionTimeout, Watcher watcher, boolean canBeReadOnly) throws Exception - { - ZooKeeper zooKeeper = actualZookeeperFactory.newZooKeeper(connectString, sessionTimeout, watcher, canBeReadOnly, zkClientConfig); + public ZooKeeper newZooKeeper( + String connectString, int sessionTimeout, Watcher watcher, boolean canBeReadOnly) throws Exception { + ZooKeeper zooKeeper = actualZookeeperFactory.newZooKeeper( + connectString, sessionTimeout, watcher, canBeReadOnly, zkClientConfig); addAuthInfos(zooKeeper); return zooKeeper; } }; } - + private void addAuthInfos(ZooKeeper zooKeeper) { - for ( AuthInfo auth: authInfos) - { - zooKeeper.addAuthInfo(auth.getScheme(), auth.getAuth()); - } - } - - private ThreadFactory getThreadFactory(CuratorFrameworkFactory.Builder builder) - { + for (AuthInfo auth : authInfos) { + zooKeeper.addAuthInfo(auth.getScheme(), auth.getAuth()); + } + } + + private ThreadFactory getThreadFactory(CuratorFrameworkFactory.Builder builder) { ThreadFactory threadFactory = builder.getThreadFactory(); - if ( threadFactory == null ) - { + if (threadFactory == null) { threadFactory = ThreadUtils.newThreadFactory("Framework"); } return threadFactory; } - protected CuratorFrameworkImpl(CuratorFrameworkImpl parent) - { + protected CuratorFrameworkImpl(CuratorFrameworkImpl parent) { client = parent.client; listeners = parent.listeners; unhandledErrorListeners = parent.unhandledErrorListeners; @@ -290,75 +293,61 @@ protected CuratorFrameworkImpl(CuratorFrameworkImpl parent) } @Override - public void createContainers(String path) throws Exception - { + public void createContainers(String path) throws Exception { checkExists().creatingParentContainersIfNeeded().forPath(ZKPaths.makePath(path, "foo")); } @Override - public void clearWatcherReferences(Watcher watcher) - { + public void clearWatcherReferences(Watcher watcher) { // NOP } @Override - public CuratorFrameworkState getState() - { + public CuratorFrameworkState getState() { return state.get(); } @Override @Deprecated - public boolean isStarted() - { + public boolean isStarted() { return state.get() == CuratorFrameworkState.STARTED; } @Override - public boolean blockUntilConnected(int maxWaitTime, TimeUnit units) throws InterruptedException - { + public boolean blockUntilConnected(int maxWaitTime, TimeUnit units) throws InterruptedException { return connectionStateManager.blockUntilConnected(maxWaitTime, units); } @Override - public void blockUntilConnected() throws InterruptedException - { + public void blockUntilConnected() throws InterruptedException { blockUntilConnected(0, null); } @Override - public ConnectionStateErrorPolicy getConnectionStateErrorPolicy() - { + public ConnectionStateErrorPolicy getConnectionStateErrorPolicy() { return connectionStateErrorPolicy; } @Override - public void start() - { + public void start() { log.info("Starting"); - if ( !state.compareAndSet(CuratorFrameworkState.LATENT, CuratorFrameworkState.STARTED) ) - { + if (!state.compareAndSet(CuratorFrameworkState.LATENT, CuratorFrameworkState.STARTED)) { throw new IllegalStateException("Cannot be started more than once"); } - try - { + try { connectionStateManager.start(); // ordering dependency - must be called before client.start() - final ConnectionStateListener listener = new ConnectionStateListener() - { + final ConnectionStateListener listener = new ConnectionStateListener() { @Override - public void stateChanged(CuratorFramework client, ConnectionState newState) - { - if ( ConnectionState.CONNECTED == newState || ConnectionState.RECONNECTED == newState ) - { + public void stateChanged(CuratorFramework client, ConnectionState newState) { + if (ConnectionState.CONNECTED == newState || ConnectionState.RECONNECTED == newState) { logAsErrorConnectionErrors.set(true); } } @Override - public boolean doNotProxy() - { + public boolean doNotProxy() { return true; } }; @@ -368,66 +357,62 @@ public boolean doNotProxy() client.start(); executorService = Executors.newSingleThreadScheduledExecutor(threadFactory); - executorService.submit(new Callable() - { + executorService.submit(new Callable() { @Override - public Object call() throws Exception - { + public Object call() throws Exception { backgroundOperationsLoop(); return null; } }); - if ( ensembleTracker != null ) - { + if (ensembleTracker != null) { ensembleTracker.start(); } log.info(schemaSet.toDocumentation()); - } - catch ( Exception e ) - { + } catch (Exception e) { ThreadUtils.checkInterrupted(e); handleBackgroundOperationException(null, e); } } @Override - public void close() - { + public void close() { log.debug("Closing"); - if ( state.compareAndSet(CuratorFrameworkState.STARTED, CuratorFrameworkState.STOPPED) ) - { - listeners.forEach(listener -> - { - CuratorEvent event = new CuratorEventImpl(CuratorFrameworkImpl.this, CuratorEventType.CLOSING, 0, null, null, null, null, null, null, null, null, null); - try - { + if (state.compareAndSet(CuratorFrameworkState.STARTED, CuratorFrameworkState.STOPPED)) { + listeners.forEach(listener -> { + CuratorEvent event = new CuratorEventImpl( + CuratorFrameworkImpl.this, + CuratorEventType.CLOSING, + 0, + null, + null, + null, + null, + null, + null, + null, + null, + null); + try { listener.eventReceived(CuratorFrameworkImpl.this, event); - } - catch ( Exception e ) - { + } catch (Exception e) { ThreadUtils.checkInterrupted(e); log.error("Exception while sending Closing event", e); } }); - if ( executorService != null ) - { + if (executorService != null) { executorService.shutdownNow(); - try - { + try { executorService.awaitTermination(maxCloseWaitMs, TimeUnit.MILLISECONDS); - } - catch ( InterruptedException e ) - { + } catch (InterruptedException e) { // Interrupted while interrupting; I give up. Thread.currentThread().interrupt(); } } - if ( ensembleTracker != null ) - { + if (ensembleTracker != null) { ensembleTracker.close(); } listeners.clear(); @@ -439,141 +424,124 @@ public void close() @Override @Deprecated - public CuratorFramework nonNamespaceView() - { + public CuratorFramework nonNamespaceView() { return usingNamespace(null); } @Override - public String getNamespace() - { + public String getNamespace() { String str = namespace.getNamespace(); return (str != null) ? str : ""; } - private void checkState() - { + private void checkState() { CuratorFrameworkState state = getState(); - Preconditions.checkState(state == CuratorFrameworkState.STARTED, "Expected state [%s] was [%s]", CuratorFrameworkState.STARTED, state); + Preconditions.checkState( + state == CuratorFrameworkState.STARTED, + "Expected state [%s] was [%s]", + CuratorFrameworkState.STARTED, + state); } @Override - public CuratorFramework usingNamespace(String newNamespace) - { + public CuratorFramework usingNamespace(String newNamespace) { checkState(); return namespaceFacadeCache.get(newNamespace); } @Override - public CreateBuilder create() - { + public CreateBuilder create() { checkState(); return new CreateBuilderImpl(this); } @Override - public DeleteBuilder delete() - { + public DeleteBuilder delete() { checkState(); return new DeleteBuilderImpl(this); } @Override - public ExistsBuilder checkExists() - { + public ExistsBuilder checkExists() { checkState(); return new ExistsBuilderImpl(this); } @Override - public GetDataBuilder getData() - { + public GetDataBuilder getData() { checkState(); return new GetDataBuilderImpl(this); } @Override - public SetDataBuilder setData() - { + public SetDataBuilder setData() { checkState(); return new SetDataBuilderImpl(this); } @Override - public GetChildrenBuilder getChildren() - { + public GetChildrenBuilder getChildren() { checkState(); return new GetChildrenBuilderImpl(this); } @Override - public GetACLBuilder getACL() - { + public GetACLBuilder getACL() { checkState(); return new GetACLBuilderImpl(this); } @Override - public SetACLBuilder setACL() - { + public SetACLBuilder setACL() { checkState(); return new SetACLBuilderImpl(this); } @Override - public ReconfigBuilder reconfig() - { + public ReconfigBuilder reconfig() { return new ReconfigBuilderImpl(this); } @Override - public GetConfigBuilder getConfig() - { + public GetConfigBuilder getConfig() { return new GetConfigBuilderImpl(this); } @Override - public CuratorTransaction inTransaction() - { + public CuratorTransaction inTransaction() { checkState(); return new CuratorTransactionImpl(this); } @Override - public CuratorMultiTransaction transaction() - { + public CuratorMultiTransaction transaction() { checkState(); return new CuratorMultiTransactionImpl(this); } @Override - public TransactionOp transactionOp() - { + public TransactionOp transactionOp() { checkState(); return new TransactionOpImpl(this); } @Override - public Listenable getConnectionStateListenable() - { + public Listenable getConnectionStateListenable() { return connectionStateManager.getListenable(); } @Override - public Listenable getCuratorListenable() - { + public Listenable getCuratorListenable() { return listeners; } @Override - public Listenable getUnhandledErrorListenable() - { + public Listenable getUnhandledErrorListenable() { return unhandledErrorListeners; } @Override - public void sync(String path, Object context) - { + public void sync(String path, Object context) { checkState(); path = fixForNamespace(path); @@ -582,114 +550,96 @@ public void sync(String path, Object context) } @Override - public SyncBuilder sync() - { + public SyncBuilder sync() { return new SyncBuilderImpl(this); } @Override - public RemoveWatchesBuilder watches() - { + public RemoveWatchesBuilder watches() { return new RemoveWatchesBuilderImpl(this); } @Override - public WatchesBuilder watchers() - { - Preconditions.checkState(Compatibility.hasPersistentWatchers(), "watchers() is not supported in the ZooKeeper library being used. Use watches() instead."); + public WatchesBuilder watchers() { + Preconditions.checkState( + Compatibility.hasPersistentWatchers(), + "watchers() is not supported in the ZooKeeper library being used. Use watches() instead."); return new WatchesBuilderImpl(this); } - protected void internalSync(CuratorFrameworkImpl impl, String path, Object context) - { + protected void internalSync(CuratorFrameworkImpl impl, String path, Object context) { BackgroundOperation operation = new BackgroundSyncImpl(impl, context); performBackgroundOperation(new OperationAndData(operation, path, null, null, context, null)); } @Override - public CuratorZookeeperClient getZookeeperClient() - { + public CuratorZookeeperClient getZookeeperClient() { return client; } @Override - public EnsurePath newNamespaceAwareEnsurePath(String path) - { + public EnsurePath newNamespaceAwareEnsurePath(String path) { return namespace.newNamespaceAwareEnsurePath(path); } @Override - public SchemaSet getSchemaSet() - { + public SchemaSet getSchemaSet() { return schemaSet; } - ACLProvider getAclProvider() - { + ACLProvider getAclProvider() { return aclProvider; } - FailedDeleteManager getFailedDeleteManager() - { + FailedDeleteManager getFailedDeleteManager() { return failedDeleteManager; } - FailedRemoveWatchManager getFailedRemoveWatcherManager() - { + FailedRemoveWatchManager getFailedRemoveWatcherManager() { return failedRemoveWatcherManager; } - RetryLoop newRetryLoop() - { + RetryLoop newRetryLoop() { return client.newRetryLoop(); } - ZooKeeper getZooKeeper() throws Exception - { + ZooKeeper getZooKeeper() throws Exception { return client.getZooKeeper(); } - CompressionProvider getCompressionProvider() - { + CompressionProvider getCompressionProvider() { return compressionProvider; } - boolean useContainerParentsIfAvailable() - { + boolean useContainerParentsIfAvailable() { return useContainerParentsIfAvailable; } - void processBackgroundOperation(OperationAndData operationAndData, CuratorEvent event) - { + void processBackgroundOperation(OperationAndData operationAndData, CuratorEvent event) { boolean isInitialExecution = (event == null); - if ( isInitialExecution ) - { + if (isInitialExecution) { performBackgroundOperation(operationAndData); return; } boolean doQueueOperation = false; - do - { + do { KeeperException.Code code = KeeperException.Code.get(event.getResultCode()); - if ( (code != KeeperException.Code.OK) && getZookeeperClient().getRetryPolicy().allowRetry(KeeperException.create(code)) ) - { + if ((code != KeeperException.Code.OK) + && getZookeeperClient().getRetryPolicy().allowRetry(KeeperException.create(code))) { doQueueOperation = checkBackgroundRetry(operationAndData, event); break; } - if ( operationAndData.getCallback() != null ) - { + if (operationAndData.getCallback() != null) { sendToBackgroundCallback(operationAndData, event); break; } processEvent(event); - } - while ( false ); + } while (false); - if ( doQueueOperation ) - { + if (doQueueOperation) { queueOperation(operationAndData); } } @@ -698,38 +648,27 @@ void processBackgroundOperation(OperationAndData operatio * @param operationAndData operation entry * @return true if the operation was actually queued, false if not */ - boolean queueOperation(OperationAndData operationAndData) - { - if ( getState() == CuratorFrameworkState.STARTED ) - { + boolean queueOperation(OperationAndData operationAndData) { + if (getState() == CuratorFrameworkState.STARTED) { backgroundOperations.offer(operationAndData); return true; } return false; } - void logError(String reason, final Throwable e) - { - if ( (reason == null) || (reason.length() == 0) ) - { + void logError(String reason, final Throwable e) { + if ((reason == null) || (reason.length() == 0)) { reason = "n/a"; } - if ( !Boolean.getBoolean(DebugUtils.PROPERTY_DONT_LOG_CONNECTION_ISSUES) || !(e instanceof KeeperException) ) - { - if ( e instanceof KeeperException.ConnectionLossException ) - { - if ( LOG_ALL_CONNECTION_ISSUES_AS_ERROR_LEVEL || logAsErrorConnectionErrors.compareAndSet(true, false) ) - { + if (!Boolean.getBoolean(DebugUtils.PROPERTY_DONT_LOG_CONNECTION_ISSUES) || !(e instanceof KeeperException)) { + if (e instanceof KeeperException.ConnectionLossException) { + if (LOG_ALL_CONNECTION_ISSUES_AS_ERROR_LEVEL || logAsErrorConnectionErrors.compareAndSet(true, false)) { log.error(reason, e); - } - else - { + } else { log.debug(reason, e); } - } - else - { + } else { log.error(reason, e); } } @@ -737,178 +676,145 @@ void logError(String reason, final Throwable e) final String localReason = reason; unhandledErrorListeners.forEach(l -> l.unhandledError(localReason, e)); - if ( debugUnhandledErrorListener != null ) - { + if (debugUnhandledErrorListener != null) { debugUnhandledErrorListener.unhandledError(reason, e); } } - String unfixForNamespace(String path) - { + String unfixForNamespace(String path) { return namespace.unfixForNamespace(path); } - String fixForNamespace(String path) - { + String fixForNamespace(String path) { return namespace.fixForNamespace(path, false); } - String fixForNamespace(String path, boolean isSequential) - { + String fixForNamespace(String path, boolean isSequential) { return namespace.fixForNamespace(path, isSequential); } - byte[] getDefaultData() - { + byte[] getDefaultData() { return defaultData; } - NamespaceFacadeCache getNamespaceFacadeCache() - { + NamespaceFacadeCache getNamespaceFacadeCache() { return namespaceFacadeCache; } - void validateConnection(Watcher.Event.KeeperState state) - { - if ( state == Watcher.Event.KeeperState.Disconnected ) - { + void validateConnection(Watcher.Event.KeeperState state) { + if (state == Watcher.Event.KeeperState.Disconnected) { internalConnectionHandler.suspendConnection(this); - } - else if ( state == Watcher.Event.KeeperState.Expired ) - { + } else if (state == Watcher.Event.KeeperState.Expired) { connectionStateManager.addStateChange(ConnectionState.LOST); - } - else if ( state == Watcher.Event.KeeperState.SyncConnected ) - { + } else if (state == Watcher.Event.KeeperState.SyncConnected) { internalConnectionHandler.checkNewConnection(this); connectionStateManager.addStateChange(ConnectionState.RECONNECTED); unSleepBackgroundOperations(); - } - else if ( state == Watcher.Event.KeeperState.ConnectedReadOnly ) - { + } else if (state == Watcher.Event.KeeperState.ConnectedReadOnly) { internalConnectionHandler.checkNewConnection(this); connectionStateManager.addStateChange(ConnectionState.READ_ONLY); } } - void checkInstanceIndex() - { + void checkInstanceIndex() { long instanceIndex = client.getInstanceIndex(); long newInstanceIndex = currentInstanceIndex.getAndSet(instanceIndex); - if ( (newInstanceIndex >= 0) && (instanceIndex != newInstanceIndex) ) // currentInstanceIndex is initially -1 - ignore this + if ((newInstanceIndex >= 0) + && (instanceIndex != newInstanceIndex)) // currentInstanceIndex is initially -1 - ignore this { connectionStateManager.addStateChange(ConnectionState.LOST); } } - Watcher.Event.KeeperState codeToState(KeeperException.Code code) - { - switch ( code ) - { - case AUTHFAILED: - case NOAUTH: - { - return Watcher.Event.KeeperState.AuthFailed; - } + Watcher.Event.KeeperState codeToState(KeeperException.Code code) { + switch (code) { + case AUTHFAILED: + case NOAUTH: { + return Watcher.Event.KeeperState.AuthFailed; + } - case CONNECTIONLOSS: - case OPERATIONTIMEOUT: - { - return Watcher.Event.KeeperState.Disconnected; - } + case CONNECTIONLOSS: + case OPERATIONTIMEOUT: { + return Watcher.Event.KeeperState.Disconnected; + } - case SESSIONEXPIRED: - { - return Watcher.Event.KeeperState.Expired; - } + case SESSIONEXPIRED: { + return Watcher.Event.KeeperState.Expired; + } - case OK: - case SESSIONMOVED: - { - return Watcher.Event.KeeperState.SyncConnected; - } + case OK: + case SESSIONMOVED: { + return Watcher.Event.KeeperState.SyncConnected; + } } return Watcher.Event.KeeperState.fromInt(-1); } - WatcherRemovalManager getWatcherRemovalManager() - { + WatcherRemovalManager getWatcherRemovalManager() { return null; } - boolean setToSuspended() - { + boolean setToSuspended() { return connectionStateManager.setToSuspended(); } - void addStateChange(ConnectionState newConnectionState) - { + void addStateChange(ConnectionState newConnectionState) { connectionStateManager.addStateChange(newConnectionState); } - EnsembleTracker getEnsembleTracker() - { + EnsembleTracker getEnsembleTracker() { return ensembleTracker; } @VisibleForTesting volatile CountDownLatch debugCheckBackgroundRetryLatch; + @VisibleForTesting volatile CountDownLatch debugCheckBackgroundRetryReadyLatch; + @VisibleForTesting volatile KeeperException.Code injectedCode; @SuppressWarnings({"ThrowableResultOfMethodCallIgnored"}) - private boolean checkBackgroundRetry(OperationAndData operationAndData, CuratorEvent event) - { + private boolean checkBackgroundRetry(OperationAndData operationAndData, CuratorEvent event) { boolean doRetry = false; - if ( client.getRetryPolicy().allowRetry(operationAndData.getThenIncrementRetryCount(), operationAndData.getElapsedTimeMs(), operationAndData) ) - { + if (client.getRetryPolicy() + .allowRetry( + operationAndData.getThenIncrementRetryCount(), + operationAndData.getElapsedTimeMs(), + operationAndData)) { doRetry = true; - } - else - { - if ( operationAndData.getErrorCallback() != null ) - { + } else { + if (operationAndData.getErrorCallback() != null) { operationAndData.getErrorCallback().retriesExhausted(operationAndData); } - if ( operationAndData.getCallback() != null ) - { + if (operationAndData.getCallback() != null) { sendToBackgroundCallback(operationAndData, event); } KeeperException.Code code = KeeperException.Code.get(event.getResultCode()); Exception e = null; - try - { + try { e = (code != null) ? KeeperException.create(code) : null; - } - catch ( Throwable t ) - { + } catch (Throwable t) { ThreadUtils.checkInterrupted(t); } - if ( e == null ) - { + if (e == null) { e = new Exception("Unknown result codegetResultCode()"); } - if ( debugCheckBackgroundRetryLatch != null ) // scaffolding to test CURATOR-525 + if (debugCheckBackgroundRetryLatch != null) // scaffolding to test CURATOR-525 { - if ( debugCheckBackgroundRetryReadyLatch != null ) - { + if (debugCheckBackgroundRetryReadyLatch != null) { debugCheckBackgroundRetryReadyLatch.countDown(); } - try - { + try { debugCheckBackgroundRetryLatch.await(); - if (injectedCode != null) - { + if (injectedCode != null) { code = injectedCode; } - } - catch ( InterruptedException ex ) - { + } catch (InterruptedException ex) { Thread.currentThread().interrupt(); } } @@ -919,99 +825,78 @@ private boolean checkBackgroundRetry(OperationAndData ope return doRetry; } - private void sendToBackgroundCallback(OperationAndData operationAndData, CuratorEvent event) - { - try - { + private void sendToBackgroundCallback( + OperationAndData operationAndData, CuratorEvent event) { + try { operationAndData.getCallback().processResult(this, event); - } - catch ( Exception e ) - { + } catch (Exception e) { ThreadUtils.checkInterrupted(e); handleBackgroundOperationException(operationAndData, e); } } - private void handleBackgroundOperationException(OperationAndData operationAndData, Throwable e) - { - do - { - if ( (operationAndData != null) && getZookeeperClient().getRetryPolicy().allowRetry(e) ) - { - if ( !Boolean.getBoolean(DebugUtils.PROPERTY_DONT_LOG_CONNECTION_ISSUES) ) - { + private void handleBackgroundOperationException( + OperationAndData operationAndData, Throwable e) { + do { + if ((operationAndData != null) + && getZookeeperClient().getRetryPolicy().allowRetry(e)) { + if (!Boolean.getBoolean(DebugUtils.PROPERTY_DONT_LOG_CONNECTION_ISSUES)) { log.debug("Retry-able exception received", e); } - if ( client.getRetryPolicy().allowRetry(operationAndData.getThenIncrementRetryCount(), operationAndData.getElapsedTimeMs(), operationAndData) ) - { - if ( !Boolean.getBoolean(DebugUtils.PROPERTY_DONT_LOG_CONNECTION_ISSUES) ) - { + if (client.getRetryPolicy() + .allowRetry( + operationAndData.getThenIncrementRetryCount(), + operationAndData.getElapsedTimeMs(), + operationAndData)) { + if (!Boolean.getBoolean(DebugUtils.PROPERTY_DONT_LOG_CONNECTION_ISSUES)) { log.debug("Retrying operation"); } backgroundOperations.offer(operationAndData); break; - } - else - { - if ( !Boolean.getBoolean(DebugUtils.PROPERTY_DONT_LOG_CONNECTION_ISSUES) ) - { + } else { + if (!Boolean.getBoolean(DebugUtils.PROPERTY_DONT_LOG_CONNECTION_ISSUES)) { log.debug("Retry policy did not allow retry"); } - if ( operationAndData.getErrorCallback() != null ) - { + if (operationAndData.getErrorCallback() != null) { operationAndData.getErrorCallback().retriesExhausted(operationAndData); } } } logError("Background exception was not retry-able or retry gave up", e); - } - while ( false ); + } while (false); } - private void backgroundOperationsLoop() - { - try - { - while ( state.get() == CuratorFrameworkState.STARTED ) - { + private void backgroundOperationsLoop() { + try { + while (state.get() == CuratorFrameworkState.STARTED) { OperationAndData operationAndData; - try - { + try { operationAndData = backgroundOperations.take(); - if ( debugListener != null ) - { + if (debugListener != null) { debugListener.listen(operationAndData); } performBackgroundOperation(operationAndData); - } - catch ( InterruptedException e ) - { + } catch (InterruptedException e) { // swallow the interrupt as it's only possible from either a background // operation and, thus, doesn't apply to this loop or the instance // is being closed in which case the while test will get it } } - } - finally - { + } finally { log.info("backgroundOperationsLoop exiting"); } } - void performBackgroundOperation(OperationAndData operationAndData) - { - try - { - if ( !operationAndData.isConnectionRequired() || client.isConnected() ) - { + void performBackgroundOperation(OperationAndData operationAndData) { + try { + if (!operationAndData.isConnectionRequired() || client.isConnected()) { operationAndData.callPerformBackgroundOperation(); return; } - client.getZooKeeper(); // important - allow connection resets, timeouts, etc. to occur - if ( operationAndData.getElapsedTimeMs() < client.getConnectionTimeoutMs() ) - { + client.getZooKeeper(); // important - allow connection resets, timeouts, etc. to occur + if (operationAndData.getElapsedTimeMs() < client.getConnectionTimeoutMs()) { sleepAndQueueOperation(operationAndData); return; } @@ -1020,19 +905,27 @@ void performBackgroundOperation(OperationAndData operationAndData) * Fix edge case reported as CURATOR-52. Connection timeout is detected when the initial (or previously failed) connection * cannot be re-established. This needs to be run through the retry policy and callbacks need to get invoked, etc. */ - WatchedEvent watchedEvent = new WatchedEvent(Watcher.Event.EventType.None, Watcher.Event.KeeperState.Disconnected, null); - CuratorEvent event = new CuratorEventImpl(this, CuratorEventType.WATCHED, KeeperException.Code.CONNECTIONLOSS.intValue(), null, null, operationAndData.getContext(), null, null, null, watchedEvent, null, null); - if ( checkBackgroundRetry(operationAndData, event) ) - { + WatchedEvent watchedEvent = + new WatchedEvent(Watcher.Event.EventType.None, Watcher.Event.KeeperState.Disconnected, null); + CuratorEvent event = new CuratorEventImpl( + this, + CuratorEventType.WATCHED, + KeeperException.Code.CONNECTIONLOSS.intValue(), + null, + null, + operationAndData.getContext(), + null, + null, + null, + watchedEvent, + null, + null); + if (checkBackgroundRetry(operationAndData, event)) { queueOperation(operationAndData); - } - else - { + } else { logError("Background retry gave up", new CuratorConnectionLossException()); } - } - catch ( Throwable e ) - { + } catch (Throwable e) { ThreadUtils.checkInterrupted(e); handleBackgroundOperationException(operationAndData, e); } @@ -1041,51 +934,42 @@ void performBackgroundOperation(OperationAndData operationAndData) @VisibleForTesting volatile long sleepAndQueueOperationSeconds = 1; - private void sleepAndQueueOperation(OperationAndData operationAndData) throws InterruptedException - { + private void sleepAndQueueOperation(OperationAndData operationAndData) throws InterruptedException { operationAndData.sleepFor(sleepAndQueueOperationSeconds, TimeUnit.SECONDS); - if ( queueOperation(operationAndData) ) - { + if (queueOperation(operationAndData)) { forcedSleepOperations.add(operationAndData); } } - private void unSleepBackgroundOperations() - { + private void unSleepBackgroundOperations() { Collection> drain = new ArrayList<>(forcedSleepOperations.size()); forcedSleepOperations.drainTo(drain); log.debug("Clearing sleep for {} operations", drain.size()); - for ( OperationAndData operation : drain ) - { + for (OperationAndData operation : drain) { operation.clearSleep(); - if ( backgroundOperations.remove(operation) ) // due to the internals of DelayQueue, operation must be removed/re-added so that re-sorting occurs + if (backgroundOperations.remove( + operation)) // due to the internals of DelayQueue, operation must be removed/re-added so that + // re-sorting occurs { backgroundOperations.offer(operation); } } } - private void processEvent(final CuratorEvent curatorEvent) - { - if ( curatorEvent.getType() == CuratorEventType.WATCHED ) - { + private void processEvent(final CuratorEvent curatorEvent) { + if (curatorEvent.getType() == CuratorEventType.WATCHED) { validateConnection(curatorEvent.getWatchedEvent().getState()); } - listeners.forEach(listener -> - { - try - { + listeners.forEach(listener -> { + try { OperationTrace trace = client.startAdvancedTracer("EventListener"); listener.eventReceived(CuratorFrameworkImpl.this, curatorEvent); trace.commit(); - } - catch ( Exception e ) - { + } catch (Exception e) { ThreadUtils.checkInterrupted(e); logError("Event listener threw exception", e); } }); } - } diff --git a/curator-framework/src/main/java/org/apache/curator/framework/imps/CuratorFrameworkState.java b/curator-framework/src/main/java/org/apache/curator/framework/imps/CuratorFrameworkState.java index 37b6c8d63..c41c88323 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/imps/CuratorFrameworkState.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/imps/CuratorFrameworkState.java @@ -24,8 +24,7 @@ /** * @see CuratorFramework#getState() */ -public enum CuratorFrameworkState -{ +public enum CuratorFrameworkState { /** * {@link CuratorFramework#start()} has not yet been called */ diff --git a/curator-framework/src/main/java/org/apache/curator/framework/imps/CuratorMultiTransactionImpl.java b/curator-framework/src/main/java/org/apache/curator/framework/imps/CuratorMultiTransactionImpl.java index f68ef78d3..4a9ed7b8b 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/imps/CuratorMultiTransactionImpl.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/imps/CuratorMultiTransactionImpl.java @@ -21,6 +21,10 @@ import com.google.common.base.Preconditions; import com.google.common.collect.Lists; +import java.util.Arrays; +import java.util.List; +import java.util.concurrent.Callable; +import java.util.concurrent.Executor; import org.apache.curator.RetryLoop; import org.apache.curator.TimeTrace; import org.apache.curator.framework.api.BackgroundCallback; @@ -40,167 +44,157 @@ import org.apache.zookeeper.proto.CreateRequest; import org.apache.zookeeper.proto.DeleteRequest; import org.apache.zookeeper.proto.SetDataRequest; -import java.util.Arrays; -import java.util.List; -import java.util.concurrent.Callable; -import java.util.concurrent.Executor; -public class CuratorMultiTransactionImpl implements - CuratorMultiTransaction, - CuratorMultiTransactionMain, - BackgroundOperation, - ErrorListenerMultiTransactionMain -{ +public class CuratorMultiTransactionImpl + implements CuratorMultiTransaction, + CuratorMultiTransactionMain, + BackgroundOperation, + ErrorListenerMultiTransactionMain { private final CuratorFrameworkImpl client; private Backgrounding backgrounding = new Backgrounding(); - public CuratorMultiTransactionImpl(CuratorFrameworkImpl client) - { + public CuratorMultiTransactionImpl(CuratorFrameworkImpl client) { this.client = client; } - public CuratorMultiTransactionImpl(CuratorFrameworkImpl client, Backgrounding backgrounding) - { + public CuratorMultiTransactionImpl(CuratorFrameworkImpl client, Backgrounding backgrounding) { this.client = client; this.backgrounding = backgrounding; } @Override - public ErrorListenerMultiTransactionMain inBackground() - { + public ErrorListenerMultiTransactionMain inBackground() { backgrounding = new Backgrounding(true); return this; } @Override - public ErrorListenerMultiTransactionMain inBackground(Object context) - { + public ErrorListenerMultiTransactionMain inBackground(Object context) { backgrounding = new Backgrounding(context); return this; } @Override - public ErrorListenerMultiTransactionMain inBackground(BackgroundCallback callback) - { + public ErrorListenerMultiTransactionMain inBackground(BackgroundCallback callback) { backgrounding = new Backgrounding(callback); return this; } @Override - public ErrorListenerMultiTransactionMain inBackground(BackgroundCallback callback, Object context) - { + public ErrorListenerMultiTransactionMain inBackground(BackgroundCallback callback, Object context) { backgrounding = new Backgrounding(callback, context); return this; } @Override - public ErrorListenerMultiTransactionMain inBackground(BackgroundCallback callback, Executor executor) - { + public ErrorListenerMultiTransactionMain inBackground(BackgroundCallback callback, Executor executor) { backgrounding = new Backgrounding(callback, executor); return this; } @Override - public ErrorListenerMultiTransactionMain inBackground(BackgroundCallback callback, Object context, Executor executor) - { + public ErrorListenerMultiTransactionMain inBackground( + BackgroundCallback callback, Object context, Executor executor) { backgrounding = new Backgrounding(client, callback, context, executor); return this; } @Override - public CuratorMultiTransactionMain withUnhandledErrorListener(UnhandledErrorListener listener) - { + public CuratorMultiTransactionMain withUnhandledErrorListener(UnhandledErrorListener listener) { backgrounding = new Backgrounding(backgrounding, listener); return this; } @Override - public List forOperations(CuratorOp... operations) throws Exception - { + public List forOperations(CuratorOp... operations) throws Exception { List ops = (operations != null) ? Arrays.asList(operations) : Lists.newArrayList(); return forOperations(ops); } @Override - public List forOperations(List operations) throws Exception - { + public List forOperations(List operations) throws Exception { operations = Preconditions.checkNotNull(operations, "operations cannot be null"); Preconditions.checkArgument(!operations.isEmpty(), "operations list cannot be empty"); CuratorMultiTransactionRecord record = new CuratorMultiTransactionRecord(); - for ( CuratorOp curatorOp : operations ) - { - Schema schema = client.getSchemaSet().getSchema(curatorOp.getTypeAndPath().getForPath()); - record.add(curatorOp.get(), curatorOp.getTypeAndPath().getType(), curatorOp.getTypeAndPath().getForPath()); - if ( (curatorOp.get().getType() == ZooDefs.OpCode.create) || (curatorOp.get().getType() == ZooDefs.OpCode.createContainer) ) - { - CreateRequest createRequest = (CreateRequest)curatorOp.get().toRequestRecord(); + for (CuratorOp curatorOp : operations) { + Schema schema = + client.getSchemaSet().getSchema(curatorOp.getTypeAndPath().getForPath()); + record.add( + curatorOp.get(), + curatorOp.getTypeAndPath().getType(), + curatorOp.getTypeAndPath().getForPath()); + if ((curatorOp.get().getType() == ZooDefs.OpCode.create) + || (curatorOp.get().getType() == ZooDefs.OpCode.createContainer)) { + CreateRequest createRequest = (CreateRequest) curatorOp.get().toRequestRecord(); CreateMode createMode = CreateMode.fromFlag(createRequest.getFlags(), CreateMode.PERSISTENT); - schema.validateCreate(createMode, createRequest.getPath(), createRequest.getData(), createRequest.getAcl()); - } - else if ( (curatorOp.get().getType() == ZooDefs.OpCode.delete) || (curatorOp.get().getType() == ZooDefs.OpCode.deleteContainer) ) - { - DeleteRequest deleteRequest = (DeleteRequest)curatorOp.get().toRequestRecord(); + schema.validateCreate( + createMode, createRequest.getPath(), createRequest.getData(), createRequest.getAcl()); + } else if ((curatorOp.get().getType() == ZooDefs.OpCode.delete) + || (curatorOp.get().getType() == ZooDefs.OpCode.deleteContainer)) { + DeleteRequest deleteRequest = (DeleteRequest) curatorOp.get().toRequestRecord(); schema.validateDelete(deleteRequest.getPath()); - } - else if ( curatorOp.get().getType() == ZooDefs.OpCode.setData ) - { - SetDataRequest setDataRequest = (SetDataRequest)curatorOp.get().toRequestRecord(); + } else if (curatorOp.get().getType() == ZooDefs.OpCode.setData) { + SetDataRequest setDataRequest = (SetDataRequest) curatorOp.get().toRequestRecord(); schema.validateGeneral(setDataRequest.getPath(), setDataRequest.getData(), null); } } - if ( backgrounding.inBackground() ) - { - client.processBackgroundOperation(new OperationAndData<>(this, record, backgrounding.getCallback(), null, backgrounding.getContext(), null), null); + if (backgrounding.inBackground()) { + client.processBackgroundOperation( + new OperationAndData<>( + this, record, backgrounding.getCallback(), null, backgrounding.getContext(), null), + null); return null; - } - else - { + } else { return forOperationsInForeground(record); } } @Override - public void performBackgroundOperation(final OperationAndData operationAndData) throws Exception - { - try - { + public void performBackgroundOperation(final OperationAndData operationAndData) + throws Exception { + try { final TimeTrace trace = client.getZookeeperClient().startTracer("CuratorMultiTransactionImpl-Background"); - AsyncCallback.MultiCallback callback = new AsyncCallback.MultiCallback() - { + AsyncCallback.MultiCallback callback = new AsyncCallback.MultiCallback() { @Override - public void processResult(int rc, String path, Object ctx, List opResults) - { + public void processResult(int rc, String path, Object ctx, List opResults) { trace.commit(); - List curatorResults = (opResults != null) ? CuratorTransactionImpl.wrapResults(client, opResults, operationAndData.getData()) : null; - CuratorEvent event = new CuratorEventImpl(client, CuratorEventType.TRANSACTION, rc, path, null, ctx, null, null, null, null, null, curatorResults); + List curatorResults = (opResults != null) + ? CuratorTransactionImpl.wrapResults(client, opResults, operationAndData.getData()) + : null; + CuratorEvent event = new CuratorEventImpl( + client, + CuratorEventType.TRANSACTION, + rc, + path, + null, + ctx, + null, + null, + null, + null, + null, + curatorResults); client.processBackgroundOperation(operationAndData, event); } }; client.getZooKeeper().multi(operationAndData.getData(), callback, backgrounding.getContext()); - } - catch ( Throwable e ) - { + } catch (Throwable e) { backgrounding.checkError(e, null); } } - private List forOperationsInForeground(final CuratorMultiTransactionRecord record) throws Exception - { + private List forOperationsInForeground(final CuratorMultiTransactionRecord record) + throws Exception { TimeTrace trace = client.getZookeeperClient().startTracer("CuratorMultiTransactionImpl-Foreground"); - List responseData = RetryLoop.callWithRetry - ( - client.getZookeeperClient(), - new Callable>() - { - @Override - public List call() throws Exception - { - return client.getZooKeeper().multi(record); - } - } - ); + List responseData = + RetryLoop.callWithRetry(client.getZookeeperClient(), new Callable>() { + @Override + public List call() throws Exception { + return client.getZooKeeper().multi(record); + } + }); trace.commit(); return CuratorTransactionImpl.wrapResults(client, responseData, record); diff --git a/curator-framework/src/main/java/org/apache/curator/framework/imps/CuratorMultiTransactionRecord.java b/curator-framework/src/main/java/org/apache/curator/framework/imps/CuratorMultiTransactionRecord.java index 93b4786c3..a667782b9 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/imps/CuratorMultiTransactionRecord.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/imps/CuratorMultiTransactionRecord.java @@ -20,39 +20,33 @@ package org.apache.curator.framework.imps; import com.google.common.collect.Lists; -import org.apache.curator.framework.api.transaction.OperationType; -import org.apache.curator.framework.api.transaction.TypeAndPath; -import org.apache.zookeeper.Op; import java.security.MessageDigest; import java.util.ArrayList; import java.util.Iterator; import java.util.List; +import org.apache.curator.framework.api.transaction.OperationType; +import org.apache.curator.framework.api.transaction.TypeAndPath; +import org.apache.zookeeper.Op; -class CuratorMultiTransactionRecord implements Iterable -{ +class CuratorMultiTransactionRecord implements Iterable { private final List metadata = Lists.newArrayList(); private final List ops = new ArrayList<>(); - void add(Op op, OperationType type, String forPath) - { + void add(Op op, OperationType type, String forPath) { ops.add(op); metadata.add(new TypeAndPath(type, forPath)); } - TypeAndPath getMetadata(int index) - { + TypeAndPath getMetadata(int index) { return metadata.get(index); } - int metadataSize() - { + int metadataSize() { return metadata.size(); } - void addToDigest(MessageDigest digest) - { - for ( Op op : ops ) - { + void addToDigest(MessageDigest digest) { + for (Op op : ops) { digest.update(op.getPath().getBytes()); digest.update(Integer.toString(op.getType()).getBytes()); digest.update(op.toRequestRecord().toString().getBytes()); @@ -60,13 +54,11 @@ void addToDigest(MessageDigest digest) } @Override - public Iterator iterator() - { + public Iterator iterator() { return ops.iterator(); } - int size() - { + int size() { return ops.size(); } } diff --git a/curator-framework/src/main/java/org/apache/curator/framework/imps/CuratorTempFrameworkImpl.java b/curator-framework/src/main/java/org/apache/curator/framework/imps/CuratorTempFrameworkImpl.java index b920e1d4a..fff6a4024 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/imps/CuratorTempFrameworkImpl.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/imps/CuratorTempFrameworkImpl.java @@ -20,100 +20,85 @@ package org.apache.curator.framework.imps; import com.google.common.annotations.VisibleForTesting; -import com.google.common.util.concurrent.ThreadFactoryBuilder; -import org.apache.curator.utils.CloseableUtils; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ThreadFactory; +import java.util.concurrent.TimeUnit; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.CuratorTempFramework; import org.apache.curator.framework.api.TempGetDataBuilder; import org.apache.curator.framework.api.transaction.CuratorTransaction; +import org.apache.curator.utils.CloseableUtils; import org.apache.curator.utils.ThreadUtils; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.ThreadFactory; -import java.util.concurrent.TimeUnit; -public class CuratorTempFrameworkImpl implements CuratorTempFramework -{ - private final CuratorFrameworkFactory.Builder factory; - private final long inactiveThresholdMs; +public class CuratorTempFrameworkImpl implements CuratorTempFramework { + private final CuratorFrameworkFactory.Builder factory; + private final long inactiveThresholdMs; // guarded by sync - private CuratorFrameworkImpl client; + private CuratorFrameworkImpl client; // guarded by sync - private ScheduledExecutorService cleanup; + private ScheduledExecutorService cleanup; // guarded by sync - private long lastAccess; + private long lastAccess; - public CuratorTempFrameworkImpl(CuratorFrameworkFactory.Builder factory, long inactiveThresholdMs) - { + public CuratorTempFrameworkImpl(CuratorFrameworkFactory.Builder factory, long inactiveThresholdMs) { this.factory = factory; this.inactiveThresholdMs = inactiveThresholdMs; } @Override - public void close() - { + public void close() { closeClient(); } @Override - public CuratorTransaction inTransaction() throws Exception - { + public CuratorTransaction inTransaction() throws Exception { openConnectionIfNeeded(); return new CuratorTransactionImpl(client); } @Override - public TempGetDataBuilder getData() throws Exception - { + public TempGetDataBuilder getData() throws Exception { openConnectionIfNeeded(); return new TempGetDataBuilderImpl(client); } @VisibleForTesting - synchronized CuratorFrameworkImpl getClient() - { + synchronized CuratorFrameworkImpl getClient() { return client; } @VisibleForTesting - synchronized ScheduledExecutorService getCleanup() - { + synchronized ScheduledExecutorService getCleanup() { return cleanup; } @VisibleForTesting - synchronized void updateLastAccess() - { + synchronized void updateLastAccess() { lastAccess = System.currentTimeMillis(); } - private synchronized void openConnectionIfNeeded() throws Exception - { - if ( client == null ) - { - client = (CuratorFrameworkImpl)factory.build(); // cast is safe - we control both sides of this + private synchronized void openConnectionIfNeeded() throws Exception { + if (client == null) { + client = (CuratorFrameworkImpl) factory.build(); // cast is safe - we control both sides of this client.start(); } - if ( cleanup == null ) - { + if (cleanup == null) { ThreadFactory threadFactory = factory.getThreadFactory(); - if (threadFactory == null) - { + if (threadFactory == null) { threadFactory = ThreadUtils.newGenericThreadFactory("CuratorTempFrameworkImpl"); } cleanup = Executors.newScheduledThreadPool(1, threadFactory); - Runnable command = new Runnable() - { + Runnable command = new Runnable() { @Override - public void run() - { + public void run() { checkInactive(); } }; @@ -123,25 +108,20 @@ public void run() updateLastAccess(); } - private synchronized void checkInactive() - { - long elapsed = System.currentTimeMillis() - lastAccess; - if ( elapsed >= inactiveThresholdMs ) - { + private synchronized void checkInactive() { + long elapsed = System.currentTimeMillis() - lastAccess; + if (elapsed >= inactiveThresholdMs) { closeClient(); } } - private synchronized void closeClient() - { - if ( cleanup != null ) - { + private synchronized void closeClient() { + if (cleanup != null) { cleanup.shutdownNow(); cleanup = null; } - if ( client != null ) - { + if (client != null) { CloseableUtils.closeQuietly(client); client = null; } diff --git a/curator-framework/src/main/java/org/apache/curator/framework/imps/CuratorTransactionImpl.java b/curator-framework/src/main/java/org/apache/curator/framework/imps/CuratorTransactionImpl.java index b99bc12c6..19a4f2175 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/imps/CuratorTransactionImpl.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/imps/CuratorTransactionImpl.java @@ -21,6 +21,9 @@ import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; +import java.util.Collection; +import java.util.List; +import java.util.concurrent.Callable; import org.apache.curator.RetryLoop; import org.apache.curator.framework.api.Pathable; import org.apache.curator.framework.api.transaction.*; @@ -29,33 +32,26 @@ import org.apache.zookeeper.OpResult; import org.apache.zookeeper.ZooDefs; import org.apache.zookeeper.data.Stat; -import java.util.Collection; -import java.util.List; -import java.util.concurrent.Callable; @SuppressWarnings("deprecation") -class CuratorTransactionImpl implements CuratorTransaction, CuratorTransactionBridge, CuratorTransactionFinal -{ +class CuratorTransactionImpl implements CuratorTransaction, CuratorTransactionBridge, CuratorTransactionFinal { private final CuratorFrameworkImpl client; private final CuratorMultiTransactionRecord transaction; private boolean isCommitted = false; - CuratorTransactionImpl(CuratorFrameworkImpl client) - { + CuratorTransactionImpl(CuratorFrameworkImpl client) { this.client = client; transaction = new CuratorMultiTransactionRecord(); } @Override - public CuratorTransactionFinal and() - { + public CuratorTransactionFinal and() { return this; } @Override - public TransactionCreateBuilder create() - { + public TransactionCreateBuilder create() { Preconditions.checkState(!isCommitted, "transaction already committed"); CuratorTransactionBridge asBridge = this; @@ -63,8 +59,7 @@ public TransactionCreateBuilder create() } @Override - public TransactionDeleteBuilder delete() - { + public TransactionDeleteBuilder delete() { Preconditions.checkState(!isCommitted, "transaction already committed"); CuratorTransactionBridge asBridge = this; @@ -72,8 +67,7 @@ public TransactionDeleteBuilder delete() } @Override - public TransactionSetDataBuilder setData() - { + public TransactionSetDataBuilder setData() { Preconditions.checkState(!isCommitted, "transaction already committed"); CuratorTransactionBridge asBridge = this; @@ -81,23 +75,20 @@ public TransactionSetDataBuilder setData() } @Override - public TransactionCheckBuilder check() - { + public TransactionCheckBuilder check() { Preconditions.checkState(!isCommitted, "transaction already committed"); CuratorTransactionBridge asBridge = this; return makeTransactionCheckBuilder(client, asBridge, transaction); } - static TransactionCheckBuilder makeTransactionCheckBuilder(final CuratorFrameworkImpl client, final T context, final CuratorMultiTransactionRecord transaction) - { - return new TransactionCheckBuilder() - { + static TransactionCheckBuilder makeTransactionCheckBuilder( + final CuratorFrameworkImpl client, final T context, final CuratorMultiTransactionRecord transaction) { + return new TransactionCheckBuilder() { private int version = -1; @Override - public T forPath(String path) throws Exception - { + public T forPath(String path) throws Exception { String fixedPath = client.fixForNamespace(path); transaction.add(Op.check(fixedPath, version), OperationType.CHECK, path); @@ -105,8 +96,7 @@ public T forPath(String path) throws Exception } @Override - public Pathable withVersion(int version) - { + public Pathable withVersion(int version) { this.version = version; return this; } @@ -114,37 +104,30 @@ public Pathable withVersion(int version) } @Override - public Collection commit() throws Exception - { + public Collection commit() throws Exception { Preconditions.checkState(!isCommitted, "transaction already committed"); isCommitted = true; - List resultList = RetryLoop.callWithRetry - ( - client.getZookeeperClient(), - new Callable>() - { + List resultList = + RetryLoop.callWithRetry(client.getZookeeperClient(), new Callable>() { @Override - public List call() throws Exception - { + public List call() throws Exception { return doOperation(); } - } - ); + }); - if ( resultList.size() != transaction.metadataSize() ) - { - throw new IllegalStateException(String.format("Result size (%d) doesn't match input size (%d)", resultList.size(), transaction.metadataSize())); + if (resultList.size() != transaction.metadataSize()) { + throw new IllegalStateException(String.format( + "Result size (%d) doesn't match input size (%d)", resultList.size(), transaction.metadataSize())); } return wrapResults(client, resultList, transaction); } - static List wrapResults(CuratorFrameworkImpl client, List resultList, CuratorMultiTransactionRecord transaction) - { + static List wrapResults( + CuratorFrameworkImpl client, List resultList, CuratorMultiTransactionRecord transaction) { ImmutableList.Builder builder = ImmutableList.builder(); - for ( int i = 0; i < resultList.size(); ++i ) - { + for (int i = 0; i < resultList.size(); ++i) { OpResult opResult = resultList.get(i); TypeAndPath metadata = transaction.getMetadata(i); CuratorTransactionResult curatorResult = makeCuratorResult(client, opResult, metadata); @@ -154,36 +137,31 @@ static List wrapResults(CuratorFrameworkImpl client, L return builder.build(); } - static CuratorTransactionResult makeCuratorResult(CuratorFrameworkImpl client, OpResult opResult, TypeAndPath metadata) - { + static CuratorTransactionResult makeCuratorResult( + CuratorFrameworkImpl client, OpResult opResult, TypeAndPath metadata) { String resultPath = null; Stat resultStat = null; int error = 0; - switch ( opResult.getType() ) - { - default: - { + switch (opResult.getType()) { + default: { // NOP break; } - case ZooDefs.OpCode.create: - { - OpResult.CreateResult createResult = (OpResult.CreateResult)opResult; + case ZooDefs.OpCode.create: { + OpResult.CreateResult createResult = (OpResult.CreateResult) opResult; resultPath = client.unfixForNamespace(createResult.getPath()); break; } - case ZooDefs.OpCode.setData: - { - OpResult.SetDataResult setDataResult = (OpResult.SetDataResult)opResult; + case ZooDefs.OpCode.setData: { + OpResult.SetDataResult setDataResult = (OpResult.SetDataResult) opResult; resultStat = setDataResult.getStat(); break; } - case ZooDefs.OpCode.error: - { - OpResult.ErrorResult errorResult = (OpResult.ErrorResult)opResult; + case ZooDefs.OpCode.error: { + OpResult.ErrorResult errorResult = (OpResult.ErrorResult) opResult; error = errorResult.getErr(); break; } @@ -192,18 +170,14 @@ static CuratorTransactionResult makeCuratorResult(CuratorFrameworkImpl client, O return new CuratorTransactionResult(metadata.getType(), metadata.getForPath(), resultPath, resultStat, error); } - private List doOperation() throws Exception - { + private List doOperation() throws Exception { List opResults = client.getZooKeeper().multi(transaction); - if ( opResults.size() > 0 ) - { + if (opResults.size() > 0) { OpResult firstResult = opResults.get(0); - if ( firstResult.getType() == ZooDefs.OpCode.error ) - { - OpResult.ErrorResult error = (OpResult.ErrorResult)firstResult; + if (firstResult.getType() == ZooDefs.OpCode.error) { + OpResult.ErrorResult error = (OpResult.ErrorResult) firstResult; KeeperException.Code code = KeeperException.Code.get(error.getErr()); - if ( code == null ) - { + if (code == null) { code = KeeperException.Code.UNIMPLEMENTED; } throw KeeperException.create(code); diff --git a/curator-framework/src/main/java/org/apache/curator/framework/imps/DefaultACLProvider.java b/curator-framework/src/main/java/org/apache/curator/framework/imps/DefaultACLProvider.java index cc782450d..76d47fb36 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/imps/DefaultACLProvider.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/imps/DefaultACLProvider.java @@ -19,22 +19,19 @@ package org.apache.curator.framework.imps; +import java.util.List; import org.apache.curator.framework.api.ACLProvider; import org.apache.zookeeper.ZooDefs; import org.apache.zookeeper.data.ACL; -import java.util.List; -public class DefaultACLProvider implements ACLProvider -{ +public class DefaultACLProvider implements ACLProvider { @Override - public List getDefaultAcl() - { + public List getDefaultAcl() { return ZooDefs.Ids.OPEN_ACL_UNSAFE; } @Override - public List getAclForPath(String path) - { + public List getAclForPath(String path) { return ZooDefs.Ids.OPEN_ACL_UNSAFE; } } diff --git a/curator-framework/src/main/java/org/apache/curator/framework/imps/DeleteBuilderImpl.java b/curator-framework/src/main/java/org/apache/curator/framework/imps/DeleteBuilderImpl.java index 21cfee5a1..efd177dd4 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/imps/DeleteBuilderImpl.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/imps/DeleteBuilderImpl.java @@ -20,6 +20,8 @@ package org.apache.curator.framework.imps; import com.google.common.annotations.VisibleForTesting; +import java.util.concurrent.Callable; +import java.util.concurrent.Executor; import org.apache.curator.RetryLoop; import org.apache.curator.drivers.OperationTrace; import org.apache.curator.framework.api.*; @@ -30,11 +32,8 @@ import org.apache.zookeeper.AsyncCallback; import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.Op; -import java.util.concurrent.Callable; -import java.util.concurrent.Executor; -public class DeleteBuilderImpl implements DeleteBuilder, BackgroundOperation, ErrorListenerPathable -{ +public class DeleteBuilderImpl implements DeleteBuilder, BackgroundOperation, ErrorListenerPathable { private final CuratorFrameworkImpl client; private int version; private Backgrounding backgrounding; @@ -44,11 +43,11 @@ public class DeleteBuilderImpl implements DeleteBuilder, BackgroundOperation TransactionDeleteBuilder asTransactionDeleteBuilder(final T context, final CuratorMultiTransactionRecord transaction) - { - return new TransactionDeleteBuilder() - { + TransactionDeleteBuilder asTransactionDeleteBuilder( + final T context, final CuratorMultiTransactionRecord transaction) { + return new TransactionDeleteBuilder() { @Override - public T forPath(String path) throws Exception - { + public T forPath(String path) throws Exception { String fixedPath = client.fixForNamespace(path); transaction.add(Op.delete(fixedPath, version), OperationType.DELETE, path); return context; } @Override - public Pathable withVersion(int version) - { + public Pathable withVersion(int version) { DeleteBuilderImpl.this.withVersion(version); return this; } @@ -89,266 +90,220 @@ public Pathable withVersion(int version) } @Override - public DeleteBuilderMain quietly() - { + public DeleteBuilderMain quietly() { quietly = true; return this; } @Override - public DeleteBuilderMain idempotent() - { + public DeleteBuilderMain idempotent() { // idempotent == quietly for deletes, but keep the interface to be consistent with Create/SetData return quietly(); } @Override - public ChildrenDeletable guaranteed() - { + public ChildrenDeletable guaranteed() { guaranteed = true; return this; } @Override - public BackgroundVersionable deletingChildrenIfNeeded() - { + public BackgroundVersionable deletingChildrenIfNeeded() { deletingChildrenIfNeeded = true; return this; } @Override - public BackgroundPathable withVersion(int version) - { + public BackgroundPathable withVersion(int version) { this.version = version; return this; } @Override - public ErrorListenerPathable inBackground(BackgroundCallback callback, Object context) - { + public ErrorListenerPathable inBackground(BackgroundCallback callback, Object context) { backgrounding = new Backgrounding(callback, context); return this; } @Override - public ErrorListenerPathable inBackground(BackgroundCallback callback, Object context, Executor executor) - { + public ErrorListenerPathable inBackground(BackgroundCallback callback, Object context, Executor executor) { backgrounding = new Backgrounding(client, callback, context, executor); return this; } @Override - public ErrorListenerPathable inBackground(BackgroundCallback callback) - { + public ErrorListenerPathable inBackground(BackgroundCallback callback) { backgrounding = new Backgrounding(callback); return this; } @Override - public ErrorListenerPathable inBackground(BackgroundCallback callback, Executor executor) - { + public ErrorListenerPathable inBackground(BackgroundCallback callback, Executor executor) { backgrounding = new Backgrounding(client, callback, executor); return this; } @Override - public ErrorListenerPathable inBackground() - { + public ErrorListenerPathable inBackground() { backgrounding = new Backgrounding(true); return this; } @Override - public ErrorListenerPathable inBackground(Object context) - { + public ErrorListenerPathable inBackground(Object context) { backgrounding = new Backgrounding(context); return this; } @Override - public Pathable withUnhandledErrorListener(UnhandledErrorListener listener) - { + public Pathable withUnhandledErrorListener(UnhandledErrorListener listener) { backgrounding = new Backgrounding(backgrounding, listener); return this; } @Override - public void performBackgroundOperation(final OperationAndData operationAndData) throws Exception - { - try - { - final OperationTrace trace = client.getZookeeperClient().startAdvancedTracer("DeleteBuilderImpl-Background"); - client.getZooKeeper().delete - ( - operationAndData.getData(), - version, - new AsyncCallback.VoidCallback() - { - @Override - public void processResult(int rc, String path, Object ctx) - { - trace.setReturnCode(rc).setPath(path).commit(); - - if ( (rc == KeeperException.Code.OK.intValue()) && failNextDeleteForTesting ) - { - failNextDeleteForTesting = false; - rc = KeeperException.Code.CONNECTIONLOSS.intValue(); - } - if ( (rc == KeeperException.Code.NOTEMPTY.intValue()) && deletingChildrenIfNeeded ) - { - backgroundDeleteChildrenThenNode(operationAndData); - } - else - { - if ( (rc == KeeperException.Code.NONODE.intValue()) && quietly ) - { - rc = KeeperException.Code.OK.intValue(); + public void performBackgroundOperation(final OperationAndData operationAndData) throws Exception { + try { + final OperationTrace trace = + client.getZookeeperClient().startAdvancedTracer("DeleteBuilderImpl-Background"); + client.getZooKeeper() + .delete( + operationAndData.getData(), + version, + new AsyncCallback.VoidCallback() { + @Override + public void processResult(int rc, String path, Object ctx) { + trace.setReturnCode(rc).setPath(path).commit(); + + if ((rc == KeeperException.Code.OK.intValue()) && failNextDeleteForTesting) { + failNextDeleteForTesting = false; + rc = KeeperException.Code.CONNECTIONLOSS.intValue(); + } + if ((rc == KeeperException.Code.NOTEMPTY.intValue()) && deletingChildrenIfNeeded) { + backgroundDeleteChildrenThenNode(operationAndData); + } else { + if ((rc == KeeperException.Code.NONODE.intValue()) && quietly) { + rc = KeeperException.Code.OK.intValue(); + } + CuratorEvent event = new CuratorEventImpl( + client, + CuratorEventType.DELETE, + rc, + path, + null, + ctx, + null, + null, + null, + null, + null, + null); + client.processBackgroundOperation(operationAndData, event); + } } - CuratorEvent event = new CuratorEventImpl(client, CuratorEventType.DELETE, rc, path, null, ctx, null, null, null, null, null, null); - client.processBackgroundOperation(operationAndData, event); - } - } - }, - backgrounding.getContext() - ); - } - catch ( Throwable e ) - { + }, + backgrounding.getContext()); + } catch (Throwable e) { backgrounding.checkError(e, null); } } - private void backgroundDeleteChildrenThenNode(final OperationAndData mainOperationAndData) - { - BackgroundOperation operation = new BackgroundOperation() - { + private void backgroundDeleteChildrenThenNode(final OperationAndData mainOperationAndData) { + BackgroundOperation operation = new BackgroundOperation() { @Override - public void performBackgroundOperation(OperationAndData dummy) throws Exception - { - try - { + public void performBackgroundOperation(OperationAndData dummy) throws Exception { + try { ZKPaths.deleteChildren(client.getZooKeeper(), mainOperationAndData.getData(), false); - } - catch ( KeeperException e ) - { + } catch (KeeperException e) { // ignore } client.queueOperation(mainOperationAndData); } }; - OperationAndData parentOperation = new OperationAndData(operation, mainOperationAndData.getData(), null, null, backgrounding.getContext(), null); + OperationAndData parentOperation = new OperationAndData( + operation, mainOperationAndData.getData(), null, null, backgrounding.getContext(), null); client.queueOperation(parentOperation); } @Override - public Void forPath(String path) throws Exception - { + public Void forPath(String path) throws Exception { client.getSchemaSet().getSchema(path).validateDelete(path); final String unfixedPath = path; path = client.fixForNamespace(path); - if ( backgrounding.inBackground() ) - { + if (backgrounding.inBackground()) { OperationAndData.ErrorCallback errorCallback = null; - if ( guaranteed ) - { - errorCallback = new OperationAndData.ErrorCallback() - { + if (guaranteed) { + errorCallback = new OperationAndData.ErrorCallback() { @Override - public void retriesExhausted(OperationAndData operationAndData) - { + public void retriesExhausted(OperationAndData operationAndData) { client.getFailedDeleteManager().addFailedOperation(unfixedPath); } }; } - OperationAndData operationAndData = new OperationAndData(this, path, backgrounding.getCallback(), errorCallback, backgrounding.getContext(), null) - { - @Override - void callPerformBackgroundOperation() throws Exception - { - // inject fault before performing operation - if ( failBeforeNextDeleteForTesting ) - { - failBeforeNextDeleteForTesting = false; - throw new KeeperException.ConnectionLossException(); - } - super.callPerformBackgroundOperation(); - } - }; + OperationAndData operationAndData = + new OperationAndData( + this, path, backgrounding.getCallback(), errorCallback, backgrounding.getContext(), null) { + @Override + void callPerformBackgroundOperation() throws Exception { + // inject fault before performing operation + if (failBeforeNextDeleteForTesting) { + failBeforeNextDeleteForTesting = false; + throw new KeeperException.ConnectionLossException(); + } + super.callPerformBackgroundOperation(); + } + }; client.processBackgroundOperation(operationAndData, null); - } - else - { + } else { pathInForeground(path, unfixedPath); } return null; } - protected int getVersion() - { + protected int getVersion() { return version; } - private void pathInForeground(final String path, String unfixedPath) throws Exception - { + private void pathInForeground(final String path, String unfixedPath) throws Exception { OperationTrace trace = client.getZookeeperClient().startAdvancedTracer("DeleteBuilderImpl-Foreground"); - try - { - RetryLoop.callWithRetry - ( - client.getZookeeperClient(), - new Callable() - { - @Override - public Void call() throws Exception - { - if ( failBeforeNextDeleteForTesting ) - { - failBeforeNextDeleteForTesting = false; - throw new KeeperException.ConnectionLossException(); - } - - try - { - client.getZooKeeper().delete(path, version); - } - catch ( KeeperException.NoNodeException e ) - { - if ( !quietly ) - { - throw e; - } - } - catch ( KeeperException.NotEmptyException e ) - { - if ( deletingChildrenIfNeeded ) - { - ZKPaths.deleteChildren(client.getZooKeeper(), path, true); - } - else - { - throw e; - } - } - - if ( failNextDeleteForTesting ) - { - failNextDeleteForTesting = false; - throw new KeeperException.ConnectionLossException(); - } + try { + RetryLoop.callWithRetry(client.getZookeeperClient(), new Callable() { + @Override + public Void call() throws Exception { + if (failBeforeNextDeleteForTesting) { + failBeforeNextDeleteForTesting = false; + throw new KeeperException.ConnectionLossException(); + } - return null; + try { + client.getZooKeeper().delete(path, version); + } catch (KeeperException.NoNodeException e) { + if (!quietly) { + throw e; + } + } catch (KeeperException.NotEmptyException e) { + if (deletingChildrenIfNeeded) { + ZKPaths.deleteChildren(client.getZooKeeper(), path, true); + } else { + throw e; } } - ); - } - catch ( Exception e ) - { + + if (failNextDeleteForTesting) { + failNextDeleteForTesting = false; + throw new KeeperException.ConnectionLossException(); + } + + return null; + } + }); + } catch (Exception e) { ThreadUtils.checkInterrupted(e); - //Only retry a guaranteed delete if it's a retryable error - if ( (client.getZookeeperClient().getRetryPolicy().allowRetry(e) || (e instanceof InterruptedException)) && guaranteed ) - { + // Only retry a guaranteed delete if it's a retryable error + if ((client.getZookeeperClient().getRetryPolicy().allowRetry(e) || (e instanceof InterruptedException)) + && guaranteed) { client.getFailedDeleteManager().addFailedOperation(unfixedPath); } throw e; diff --git a/curator-framework/src/main/java/org/apache/curator/framework/imps/EnsembleTracker.java b/curator-framework/src/main/java/org/apache/curator/framework/imps/EnsembleTracker.java index f7b99f8f2..90cb3fc60 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/imps/EnsembleTracker.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/imps/EnsembleTracker.java @@ -22,6 +22,13 @@ import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; import com.google.common.collect.Maps; +import java.io.ByteArrayInputStream; +import java.io.Closeable; +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.util.Properties; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; import org.apache.curator.ensemble.EnsembleProvider; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.WatcherRemoveCuratorFramework; @@ -40,83 +47,62 @@ import org.apache.zookeeper.server.quorum.flexible.QuorumVerifier; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.io.ByteArrayInputStream; -import java.io.Closeable; -import java.net.InetAddress; -import java.net.InetSocketAddress; -import java.util.Properties; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.concurrent.atomic.AtomicReference; @VisibleForTesting -public class EnsembleTracker implements Closeable, CuratorWatcher -{ +public class EnsembleTracker implements Closeable, CuratorWatcher { private final Logger log = LoggerFactory.getLogger(getClass()); private final WatcherRemoveCuratorFramework client; private final EnsembleProvider ensembleProvider; private final AtomicReference state = new AtomicReference<>(State.LATENT); private final AtomicInteger outstanding = new AtomicInteger(0); - private final AtomicReference currentConfig = new AtomicReference<>(new QuorumMaj(Maps.newHashMap())); - private final ConnectionStateListener connectionStateListener = new ConnectionStateListener() - { + private final AtomicReference currentConfig = + new AtomicReference<>(new QuorumMaj(Maps.newHashMap())); + private final ConnectionStateListener connectionStateListener = new ConnectionStateListener() { @Override - public void stateChanged(CuratorFramework client, ConnectionState newState) - { - if ( (newState == ConnectionState.CONNECTED) || (newState == ConnectionState.RECONNECTED) ) - { - try - { + public void stateChanged(CuratorFramework client, ConnectionState newState) { + if ((newState == ConnectionState.CONNECTED) || (newState == ConnectionState.RECONNECTED)) { + try { reset(); - } - catch ( Exception e ) - { + } catch (Exception e) { log.error("Trying to reset after reconnection", e); } } } @Override - public boolean doNotProxy() - { + public boolean doNotProxy() { return true; } }; - private enum State - { + private enum State { LATENT, STARTED, CLOSED } - EnsembleTracker(CuratorFramework client, EnsembleProvider ensembleProvider) - { + EnsembleTracker(CuratorFramework client, EnsembleProvider ensembleProvider) { this.client = client.newWatcherRemoveCuratorFramework(); this.ensembleProvider = ensembleProvider; } - public void start() throws Exception - { + public void start() throws Exception { Preconditions.checkState(state.compareAndSet(State.LATENT, State.STARTED), "Cannot be started more than once"); client.getConnectionStateListenable().addListener(connectionStateListener); reset(); } @Override - public void close() - { - if ( state.compareAndSet(State.STARTED, State.CLOSED) ) - { + public void close() { + if (state.compareAndSet(State.STARTED, State.CLOSED)) { client.removeWatchers(); client.getConnectionStateListenable().removeListener(connectionStateListener); } } @Override - public void process(WatchedEvent event) throws Exception - { - if ( event.getType() == Watcher.Event.EventType.NodeDataChanged ) - { + public void process(WatchedEvent event) throws Exception { + if (event.getType() == Watcher.Event.EventType.NodeDataChanged) { reset(); } } @@ -126,59 +112,49 @@ public void process(WatchedEvent event) throws Exception * * @return config */ - public QuorumVerifier getCurrentConfig() - { + public QuorumVerifier getCurrentConfig() { return currentConfig.get(); } @VisibleForTesting - public boolean hasOutstanding() - { + public boolean hasOutstanding() { return outstanding.get() > 0; } - private void reset() throws Exception - { - if ( (client.getState() == CuratorFrameworkState.STARTED) && (state.get() == State.STARTED) ) - { - BackgroundCallback backgroundCallback = new BackgroundCallback() - { + private void reset() throws Exception { + if ((client.getState() == CuratorFrameworkState.STARTED) && (state.get() == State.STARTED)) { + BackgroundCallback backgroundCallback = new BackgroundCallback() { @Override - public void processResult(CuratorFramework client, CuratorEvent event) throws Exception - { + public void processResult(CuratorFramework client, CuratorEvent event) throws Exception { outstanding.decrementAndGet(); - if ( (event.getType() == CuratorEventType.GET_CONFIG) && (event.getResultCode() == KeeperException.Code.OK.intValue()) ) - { + if ((event.getType() == CuratorEventType.GET_CONFIG) + && (event.getResultCode() == KeeperException.Code.OK.intValue())) { processConfigData(event.getData()); } } }; outstanding.incrementAndGet(); - try - { - client.getConfig().usingWatcher(this).inBackground(backgroundCallback).forEnsemble(); - outstanding.incrementAndGet(); // finally block will decrement - } - finally - { + try { + client.getConfig() + .usingWatcher(this) + .inBackground(backgroundCallback) + .forEnsemble(); + outstanding.incrementAndGet(); // finally block will decrement + } finally { outstanding.decrementAndGet(); } } } @VisibleForTesting - public static String configToConnectionString(QuorumVerifier data) throws Exception - { + public static String configToConnectionString(QuorumVerifier data) throws Exception { StringBuilder sb = new StringBuilder(); - for ( QuorumPeer.QuorumServer server : data.getAllMembers().values() ) - { - if ( server.clientAddr == null ) - { + for (QuorumPeer.QuorumServer server : data.getAllMembers().values()) { + if (server.clientAddr == null) { // Invalid client address configuration in zoo.cfg continue; } - if ( sb.length() != 0 ) - { + if (sb.length() != 0) { sb.append(","); } sb.append(getHostString(server)).append(":").append(server.clientAddr.getPort()); @@ -190,45 +166,34 @@ public static String configToConnectionString(QuorumVerifier data) throws Except private static String getHostString(QuorumPeer.QuorumServer server) { InetSocketAddress clientAddr = server.clientAddr; InetAddress clientIpAddr = clientAddr.getAddress(); - if ( clientIpAddr != null && clientIpAddr.isAnyLocalAddress() ) - { + if (clientIpAddr != null && clientIpAddr.isAnyLocalAddress()) { return Compatibility.getHostString(server); - } - else - { + } else { return clientAddr.getHostString(); } } - private void processConfigData(byte[] data) throws Exception - { + private void processConfigData(byte[] data) throws Exception { Properties properties = new Properties(); properties.load(new ByteArrayInputStream(data)); log.info("New config event received: {}", properties); - if (!properties.isEmpty()) - { + if (!properties.isEmpty()) { QuorumMaj newConfig = new QuorumMaj(properties); String connectionString = configToConnectionString(newConfig).trim(); - if (!connectionString.isEmpty()) - { + if (!connectionString.isEmpty()) { currentConfig.set(newConfig); String oldConnectionString = ensembleProvider.getConnectionString(); int i = oldConnectionString.indexOf('/'); - if (i >= 0) - { + if (i >= 0) { String chroot = oldConnectionString.substring(i); connectionString += chroot; } ensembleProvider.setConnectionString(connectionString); - } - else - { + } else { log.debug("Invalid config event received: {}", properties); } - } - else - { + } else { log.debug("Ignoring new config as it is empty"); } } diff --git a/curator-framework/src/main/java/org/apache/curator/framework/imps/ExistsBuilderImpl.java b/curator-framework/src/main/java/org/apache/curator/framework/imps/ExistsBuilderImpl.java index 642e9d684..0b4661d60 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/imps/ExistsBuilderImpl.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/imps/ExistsBuilderImpl.java @@ -19,6 +19,9 @@ package org.apache.curator.framework.imps; +import java.util.List; +import java.util.concurrent.Callable; +import java.util.concurrent.Executor; import org.apache.curator.RetryLoop; import org.apache.curator.drivers.OperationTrace; import org.apache.curator.framework.api.*; @@ -29,12 +32,8 @@ import org.apache.zookeeper.data.ACL; import org.apache.zookeeper.data.Stat; -import java.util.List; -import java.util.concurrent.Callable; -import java.util.concurrent.Executor; - -public class ExistsBuilderImpl implements ExistsBuilder, BackgroundOperation, ErrorListenerPathable, ACLableExistBuilderMain -{ +public class ExistsBuilderImpl + implements ExistsBuilder, BackgroundOperation, ErrorListenerPathable, ACLableExistBuilderMain { private final CuratorFrameworkImpl client; private Backgrounding backgrounding; private Watching watching; @@ -42,13 +41,16 @@ public class ExistsBuilderImpl implements ExistsBuilder, BackgroundOperation aclList) - { + public ExistsBuilderMain withACL(List aclList) { acling = new ACLing(client.getAclProvider(), aclList, true); return this; } @Override - public BackgroundPathable watched() - { + public BackgroundPathable watched() { watching = new Watching(client, true); return this; } @Override - public BackgroundPathable usingWatcher(Watcher watcher) - { + public BackgroundPathable usingWatcher(Watcher watcher) { watching = new Watching(client, watcher); return this; } @Override - public BackgroundPathable usingWatcher(CuratorWatcher watcher) - { + public BackgroundPathable usingWatcher(CuratorWatcher watcher) { watching = new Watching(client, watcher); return this; } @Override - public ErrorListenerPathable inBackground(BackgroundCallback callback, Object context) - { + public ErrorListenerPathable inBackground(BackgroundCallback callback, Object context) { backgrounding = new Backgrounding(callback, context); return this; } @Override - public ErrorListenerPathable inBackground(BackgroundCallback callback, Object context, Executor executor) - { + public ErrorListenerPathable inBackground(BackgroundCallback callback, Object context, Executor executor) { backgrounding = new Backgrounding(client, callback, context, executor); return this; } @Override - public ErrorListenerPathable inBackground(BackgroundCallback callback) - { + public ErrorListenerPathable inBackground(BackgroundCallback callback) { backgrounding = new Backgrounding(callback); return this; } @Override - public ErrorListenerPathable inBackground(BackgroundCallback callback, Executor executor) - { + public ErrorListenerPathable inBackground(BackgroundCallback callback, Executor executor) { backgrounding = new Backgrounding(client, callback, executor); return this; } @Override - public ErrorListenerPathable inBackground() - { + public ErrorListenerPathable inBackground() { backgrounding = new Backgrounding(true); return this; } @Override - public ErrorListenerPathable inBackground(Object context) - { + public ErrorListenerPathable inBackground(Object context) { backgrounding = new Backgrounding(context); return this; } @Override - public Pathable withUnhandledErrorListener(UnhandledErrorListener listener) - { + public Pathable withUnhandledErrorListener(UnhandledErrorListener listener) { backgrounding = new Backgrounding(backgrounding, listener); return this; } @Override - public void performBackgroundOperation(final OperationAndData operationAndData) throws Exception - { - try - { - final OperationTrace trace = client.getZookeeperClient().startAdvancedTracer("ExistsBuilderImpl-Background"); - AsyncCallback.StatCallback callback = new AsyncCallback.StatCallback() - { + public void performBackgroundOperation(final OperationAndData operationAndData) throws Exception { + try { + final OperationTrace trace = + client.getZookeeperClient().startAdvancedTracer("ExistsBuilderImpl-Background"); + AsyncCallback.StatCallback callback = new AsyncCallback.StatCallback() { @Override - public void processResult(int rc, String path, Object ctx, Stat stat) - { + public void processResult(int rc, String path, Object ctx, Stat stat) { watching.commitWatcher(rc, true); - trace.setReturnCode(rc).setPath(path).setWithWatcher(watching.hasWatcher()).setStat(stat).commit(); - CuratorEvent event = new CuratorEventImpl(client, CuratorEventType.EXISTS, rc, path, null, ctx, stat, null, null, null, null, null); + trace.setReturnCode(rc) + .setPath(path) + .setWithWatcher(watching.hasWatcher()) + .setStat(stat) + .commit(); + CuratorEvent event = new CuratorEventImpl( + client, CuratorEventType.EXISTS, rc, path, null, ctx, stat, null, null, null, null, null); client.processBackgroundOperation(operationAndData, event); } }; - if ( watching.isWatched() ) - { + if (watching.isWatched()) { client.getZooKeeper().exists(operationAndData.getData(), true, callback, backgrounding.getContext()); + } else { + client.getZooKeeper() + .exists( + operationAndData.getData(), + watching.getWatcher(operationAndData.getData()), + callback, + backgrounding.getContext()); } - else - { - client.getZooKeeper().exists(operationAndData.getData(), watching.getWatcher(operationAndData.getData()), callback, backgrounding.getContext()); - } - } - catch ( Throwable e ) - { + } catch (Throwable e) { backgrounding.checkError(e, watching); } } @Override - public Stat forPath(String path) throws Exception - { + public Stat forPath(String path) throws Exception { path = client.fixForNamespace(path); client.getSchemaSet().getSchema(path).validateWatch(path, watching.isWatched() || watching.hasWatcher()); - Stat returnStat = null; - if ( backgrounding.inBackground() ) - { - OperationAndData operationAndData = new OperationAndData(this, path, backgrounding.getCallback(), null, backgrounding.getContext(), watching); - if ( createParentContainersIfNeeded || createParentsIfNeeded ) - { - CreateBuilderImpl.backgroundCreateParentsThenNode(client, operationAndData, operationAndData.getData(), backgrounding, acling.getACLProviderForParents(), createParentContainersIfNeeded); - } - else - { + Stat returnStat = null; + if (backgrounding.inBackground()) { + OperationAndData operationAndData = new OperationAndData( + this, path, backgrounding.getCallback(), null, backgrounding.getContext(), watching); + if (createParentContainersIfNeeded || createParentsIfNeeded) { + CreateBuilderImpl.backgroundCreateParentsThenNode( + client, + operationAndData, + operationAndData.getData(), + backgrounding, + acling.getACLProviderForParents(), + createParentContainersIfNeeded); + } else { client.processBackgroundOperation(operationAndData, null); } - } - else - { + } else { returnStat = pathInForeground(path); } return returnStat; } - private Stat pathInForeground(final String path) throws Exception - { - if ( createParentContainersIfNeeded || createParentsIfNeeded ) - { + private Stat pathInForeground(final String path) throws Exception { + if (createParentContainersIfNeeded || createParentsIfNeeded) { final String parent = ZKPaths.getPathAndNode(path).getPath(); - if ( !parent.equals(ZKPaths.PATH_SEPARATOR) ) - { - OperationTrace trace = client.getZookeeperClient().startAdvancedTracer("ExistsBuilderImpl-Foreground-CreateParents"); - RetryLoop.callWithRetry - ( - client.getZookeeperClient(), - new Callable() - { - @Override - public Void call() throws Exception - { - try - { - ZKPaths.mkdirs(client.getZooKeeper(), parent, true, acling.getACLProviderForParents(), createParentContainersIfNeeded); - } - catch ( KeeperException.NodeExistsException e ) - { - // ignore - } - catch ( KeeperException.NoNodeException e ) - { - // ignore - } - return null; + if (!parent.equals(ZKPaths.PATH_SEPARATOR)) { + OperationTrace trace = + client.getZookeeperClient().startAdvancedTracer("ExistsBuilderImpl-Foreground-CreateParents"); + RetryLoop.callWithRetry(client.getZookeeperClient(), new Callable() { + @Override + public Void call() throws Exception { + try { + ZKPaths.mkdirs( + client.getZooKeeper(), + parent, + true, + acling.getACLProviderForParents(), + createParentContainersIfNeeded); + } catch (KeeperException.NodeExistsException e) { + // ignore + } catch (KeeperException.NoNodeException e) { + // ignore } + return null; } - ); + }); trace.setPath(path).commit(); } } return pathInForegroundStandard(path); } - private Stat pathInForegroundStandard(final String path) throws Exception - { - OperationTrace trace = client.getZookeeperClient().startAdvancedTracer("ExistsBuilderImpl-Foreground"); - Stat returnStat = RetryLoop.callWithRetry - ( - client.getZookeeperClient(), - new Callable() - { - @Override - public Stat call() throws Exception - { - Stat returnStat; - if ( watching.isWatched() ) - { - returnStat = client.getZooKeeper().exists(path, true); - } - else - { - returnStat = client.getZooKeeper().exists(path, watching.getWatcher(path)); - int rc = (returnStat != null) ? KeeperException.NoNodeException.Code.OK.intValue() : KeeperException.NoNodeException.Code.NONODE.intValue(); - watching.commitWatcher(rc, true); - } - return returnStat; + private Stat pathInForegroundStandard(final String path) throws Exception { + OperationTrace trace = client.getZookeeperClient().startAdvancedTracer("ExistsBuilderImpl-Foreground"); + Stat returnStat = RetryLoop.callWithRetry(client.getZookeeperClient(), new Callable() { + @Override + public Stat call() throws Exception { + Stat returnStat; + if (watching.isWatched()) { + returnStat = client.getZooKeeper().exists(path, true); + } else { + returnStat = client.getZooKeeper().exists(path, watching.getWatcher(path)); + int rc = (returnStat != null) + ? KeeperException.NoNodeException.Code.OK.intValue() + : KeeperException.NoNodeException.Code.NONODE.intValue(); + watching.commitWatcher(rc, true); } + return returnStat; } - ); - trace.setPath(path).setWithWatcher(watching.hasWatcher()).setStat(returnStat).commit(); + }); + trace.setPath(path) + .setWithWatcher(watching.hasWatcher()) + .setStat(returnStat) + .commit(); return returnStat; } } diff --git a/curator-framework/src/main/java/org/apache/curator/framework/imps/ExtractingCuratorOp.java b/curator-framework/src/main/java/org/apache/curator/framework/imps/ExtractingCuratorOp.java index ad8932584..585eb9066 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/imps/ExtractingCuratorOp.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/imps/ExtractingCuratorOp.java @@ -20,41 +20,35 @@ package org.apache.curator.framework.imps; import com.google.common.base.Preconditions; +import java.security.MessageDigest; import org.apache.curator.framework.api.transaction.CuratorOp; import org.apache.curator.framework.api.transaction.TypeAndPath; import org.apache.zookeeper.Op; -import java.security.MessageDigest; -public class ExtractingCuratorOp implements CuratorOp -{ +public class ExtractingCuratorOp implements CuratorOp { private final CuratorMultiTransactionRecord record = new CuratorMultiTransactionRecord(); - CuratorMultiTransactionRecord getRecord() - { + CuratorMultiTransactionRecord getRecord() { return record; } @Override - public TypeAndPath getTypeAndPath() - { + public TypeAndPath getTypeAndPath() { validate(); return record.getMetadata(0); } @Override - public Op get() - { + public Op get() { validate(); return record.iterator().next(); } - public void addToDigest(MessageDigest digest) - { + public void addToDigest(MessageDigest digest) { record.addToDigest(digest); } - private void validate() - { + private void validate() { Preconditions.checkArgument(record.size() > 0, "No operation has been added"); Preconditions.checkArgument(record.size() == 1, "Multiple operations added"); } diff --git a/curator-framework/src/main/java/org/apache/curator/framework/imps/FailedDeleteManager.java b/curator-framework/src/main/java/org/apache/curator/framework/imps/FailedDeleteManager.java index c854a9476..7fedb2289 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/imps/FailedDeleteManager.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/imps/FailedDeleteManager.java @@ -21,17 +21,13 @@ import org.apache.curator.framework.CuratorFramework; -class FailedDeleteManager extends FailedOperationManager -{ - FailedDeleteManager(CuratorFramework client) - { +class FailedDeleteManager extends FailedOperationManager { + FailedDeleteManager(CuratorFramework client) { super(client); } @Override - protected void executeGuaranteedOperationInBackground(String path) - throws Exception - { + protected void executeGuaranteedOperationInBackground(String path) throws Exception { client.delete().guaranteed().inBackground().forPath(path); } } diff --git a/curator-framework/src/main/java/org/apache/curator/framework/imps/FailedOperationManager.java b/curator-framework/src/main/java/org/apache/curator/framework/imps/FailedOperationManager.java index 1e8101cbd..95f50739d 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/imps/FailedOperationManager.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/imps/FailedOperationManager.java @@ -19,53 +19,42 @@ package org.apache.curator.framework.imps; +import com.google.common.annotations.VisibleForTesting; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.utils.ThreadUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.google.common.annotations.VisibleForTesting; - -abstract class FailedOperationManager -{ +abstract class FailedOperationManager { private final Logger log = LoggerFactory.getLogger(getClass()); protected final CuratorFramework client; - + @VisibleForTesting volatile FailedOperationManagerListener debugListener = null; - - interface FailedOperationManagerListener - { - public void pathAddedForGuaranteedOperation(T detail); + + interface FailedOperationManagerListener { + public void pathAddedForGuaranteedOperation(T detail); } - FailedOperationManager(CuratorFramework client) - { + FailedOperationManager(CuratorFramework client) { this.client = client; } - void addFailedOperation(T details) - { - if ( debugListener != null ) - { + void addFailedOperation(T details) { + if (debugListener != null) { debugListener.pathAddedForGuaranteedOperation(details); } - - - if ( client.getState() == CuratorFrameworkState.STARTED ) - { + + if (client.getState() == CuratorFrameworkState.STARTED) { log.debug("Details being added to guaranteed operation set: " + details); - try - { + try { executeGuaranteedOperationInBackground(details); - } - catch ( Exception e ) - { + } catch (Exception e) { ThreadUtils.checkInterrupted(e); addFailedOperation(details); } } } - + protected abstract void executeGuaranteedOperationInBackground(T details) throws Exception; } diff --git a/curator-framework/src/main/java/org/apache/curator/framework/imps/FailedRemoveWatchManager.java b/curator-framework/src/main/java/org/apache/curator/framework/imps/FailedRemoveWatchManager.java index f88a287fc..eff5202d8 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/imps/FailedRemoveWatchManager.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/imps/FailedRemoveWatchManager.java @@ -22,34 +22,25 @@ import org.apache.curator.framework.CuratorFramework; import org.apache.zookeeper.Watcher; -class FailedRemoveWatchManager extends FailedOperationManager -{ - FailedRemoveWatchManager(CuratorFramework client) - { +class FailedRemoveWatchManager extends FailedOperationManager { + FailedRemoveWatchManager(CuratorFramework client) { super(client); } @Override - protected void executeGuaranteedOperationInBackground(FailedRemoveWatchDetails details) - throws Exception - { - if(details.watcher == null) - { + protected void executeGuaranteedOperationInBackground(FailedRemoveWatchDetails details) throws Exception { + if (details.watcher == null) { client.watches().removeAll().guaranteed().inBackground().forPath(details.path); - } - else - { + } else { client.watches().remove(details.watcher).guaranteed().inBackground().forPath(details.path); } } - - static class FailedRemoveWatchDetails - { + + static class FailedRemoveWatchDetails { public final String path; public final Watcher watcher; - - public FailedRemoveWatchDetails(String path, Watcher watcher) - { + + public FailedRemoveWatchDetails(String path, Watcher watcher) { this.path = path; this.watcher = watcher; } diff --git a/curator-framework/src/main/java/org/apache/curator/framework/imps/FindAndDeleteProtectedNodeInBackground.java b/curator-framework/src/main/java/org/apache/curator/framework/imps/FindAndDeleteProtectedNodeInBackground.java index 9798f36e0..697e35a4f 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/imps/FindAndDeleteProtectedNodeInBackground.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/imps/FindAndDeleteProtectedNodeInBackground.java @@ -20,6 +20,8 @@ package org.apache.curator.framework.imps; import com.google.common.annotations.VisibleForTesting; +import java.util.List; +import java.util.concurrent.atomic.AtomicBoolean; import org.apache.curator.drivers.OperationTrace; import org.apache.curator.framework.api.CuratorEventType; import org.apache.curator.utils.ThreadUtils; @@ -29,35 +31,30 @@ import org.apache.zookeeper.data.Stat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.util.List; -import java.util.concurrent.atomic.AtomicBoolean; -class FindAndDeleteProtectedNodeInBackground implements BackgroundOperation -{ +class FindAndDeleteProtectedNodeInBackground implements BackgroundOperation { private final Logger log = LoggerFactory.getLogger(getClass()); private final CuratorFrameworkImpl client; private final String namespaceAdjustedParentPath; private final String protectedId; - FindAndDeleteProtectedNodeInBackground(CuratorFrameworkImpl client, String namespaceAdjustedParentPath, String protectedId) - { + FindAndDeleteProtectedNodeInBackground( + CuratorFrameworkImpl client, String namespaceAdjustedParentPath, String protectedId) { this.client = client; this.namespaceAdjustedParentPath = namespaceAdjustedParentPath; this.protectedId = protectedId; } - void execute() - { - OperationAndData.ErrorCallback errorCallback = new OperationAndData.ErrorCallback() - { + void execute() { + OperationAndData.ErrorCallback errorCallback = new OperationAndData.ErrorCallback() { @Override - public void retriesExhausted(OperationAndData operationAndData) - { + public void retriesExhausted(OperationAndData operationAndData) { operationAndData.reset(); client.processBackgroundOperation(operationAndData, null); } }; - OperationAndData operationAndData = new OperationAndData(this, null, null, errorCallback, null, null); + OperationAndData operationAndData = + new OperationAndData(this, null, null, errorCallback, null, null); client.processBackgroundOperation(operationAndData, null); } @@ -65,33 +62,29 @@ public void retriesExhausted(OperationAndData operationAndData) static final AtomicBoolean debugInsertError = new AtomicBoolean(false); @Override - public void performBackgroundOperation(final OperationAndData operationAndData) throws Exception - { - final OperationTrace trace = client.getZookeeperClient().startAdvancedTracer("FindAndDeleteProtectedNodeInBackground"); - AsyncCallback.Children2Callback callback = new AsyncCallback.Children2Callback() - { + public void performBackgroundOperation(final OperationAndData operationAndData) throws Exception { + final OperationTrace trace = + client.getZookeeperClient().startAdvancedTracer("FindAndDeleteProtectedNodeInBackground"); + AsyncCallback.Children2Callback callback = new AsyncCallback.Children2Callback() { @Override - public void processResult(int rc, String path, Object o, List strings, Stat stat) - { + public void processResult(int rc, String path, Object o, List strings, Stat stat) { trace.setReturnCode(rc).setPath(path).setStat(stat).commit(); - if ( debugInsertError.compareAndSet(true, false) ) - { + if (debugInsertError.compareAndSet(true, false)) { rc = KeeperException.Code.CONNECTIONLOSS.intValue(); } - if ( rc == KeeperException.Code.OK.intValue() ) - { - final String node = CreateBuilderImpl.findNode(strings, "/", protectedId); // due to namespacing, don't let CreateBuilderImpl.findNode adjust the path - if ( node != null ) - { - try - { - String deletePath = client.unfixForNamespace(ZKPaths.makePath(namespaceAdjustedParentPath, node)); + if (rc == KeeperException.Code.OK.intValue()) { + final String node = CreateBuilderImpl.findNode( + strings, + "/", + protectedId); // due to namespacing, don't let CreateBuilderImpl.findNode adjust the path + if (node != null) { + try { + String deletePath = + client.unfixForNamespace(ZKPaths.makePath(namespaceAdjustedParentPath, node)); client.delete().guaranteed().inBackground().forPath(deletePath); - } - catch ( Exception e ) - { + } catch (Exception e) { ThreadUtils.checkInterrupted(e); log.error("Could not start guaranteed delete for node: " + node); rc = KeeperException.Code.CONNECTIONLOSS.intValue(); @@ -99,9 +92,20 @@ public void processResult(int rc, String path, Object o, List strings, S } } - if ( rc != KeeperException.Code.OK.intValue() ) - { - CuratorEventImpl event = new CuratorEventImpl(client, CuratorEventType.CHILDREN, rc, path, null, o, stat, null, strings, null, null, null); + if (rc != KeeperException.Code.OK.intValue()) { + CuratorEventImpl event = new CuratorEventImpl( + client, + CuratorEventType.CHILDREN, + rc, + path, + null, + o, + stat, + null, + strings, + null, + null, + null); client.processBackgroundOperation(operationAndData, event); } } diff --git a/curator-framework/src/main/java/org/apache/curator/framework/imps/GetACLBuilderImpl.java b/curator-framework/src/main/java/org/apache/curator/framework/imps/GetACLBuilderImpl.java index 20fbcb62e..e04eec009 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/imps/GetACLBuilderImpl.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/imps/GetACLBuilderImpl.java @@ -19,6 +19,9 @@ package org.apache.curator.framework.imps; +import java.util.List; +import java.util.concurrent.Callable; +import java.util.concurrent.Executor; import org.apache.curator.RetryLoop; import org.apache.curator.drivers.OperationTrace; import org.apache.curator.framework.api.BackgroundCallback; @@ -30,143 +33,119 @@ import org.apache.zookeeper.AsyncCallback; import org.apache.zookeeper.data.ACL; import org.apache.zookeeper.data.Stat; -import java.util.List; -import java.util.concurrent.Callable; -import java.util.concurrent.Executor; -public class GetACLBuilderImpl implements GetACLBuilder, BackgroundOperation, ErrorListenerPathable> -{ +public class GetACLBuilderImpl implements GetACLBuilder, BackgroundOperation, ErrorListenerPathable> { private final CuratorFrameworkImpl client; - private Backgrounding backgrounding; - private Stat responseStat; + private Backgrounding backgrounding; + private Stat responseStat; - GetACLBuilderImpl(CuratorFrameworkImpl client) - { + GetACLBuilderImpl(CuratorFrameworkImpl client) { this.client = client; backgrounding = new Backgrounding(); responseStat = new Stat(); } - public GetACLBuilderImpl(CuratorFrameworkImpl client, Backgrounding backgrounding, Stat responseStat) - { + public GetACLBuilderImpl(CuratorFrameworkImpl client, Backgrounding backgrounding, Stat responseStat) { this.client = client; this.backgrounding = backgrounding; this.responseStat = responseStat; } @Override - public ErrorListenerPathable> inBackground(BackgroundCallback callback, Object context) - { + public ErrorListenerPathable> inBackground(BackgroundCallback callback, Object context) { backgrounding = new Backgrounding(callback, context); return this; } @Override - public ErrorListenerPathable> inBackground(BackgroundCallback callback, Object context, Executor executor) - { + public ErrorListenerPathable> inBackground( + BackgroundCallback callback, Object context, Executor executor) { backgrounding = new Backgrounding(client, callback, context, executor); return this; } @Override - public ErrorListenerPathable> inBackground() - { + public ErrorListenerPathable> inBackground() { backgrounding = new Backgrounding(true); return this; } @Override - public ErrorListenerPathable> inBackground(Object context) - { + public ErrorListenerPathable> inBackground(Object context) { backgrounding = new Backgrounding(context); return this; } @Override - public ErrorListenerPathable> inBackground(BackgroundCallback callback) - { + public ErrorListenerPathable> inBackground(BackgroundCallback callback) { backgrounding = new Backgrounding(callback); return this; } @Override - public ErrorListenerPathable> inBackground(BackgroundCallback callback, Executor executor) - { + public ErrorListenerPathable> inBackground(BackgroundCallback callback, Executor executor) { backgrounding = new Backgrounding(client, callback, executor); return this; } @Override - public Pathable> withUnhandledErrorListener(UnhandledErrorListener listener) - { + public Pathable> withUnhandledErrorListener(UnhandledErrorListener listener) { backgrounding = new Backgrounding(backgrounding, listener); return this; } @Override - public Pathable> storingStatIn(Stat stat) - { + public Pathable> storingStatIn(Stat stat) { responseStat = stat; return this; } @Override - public void performBackgroundOperation(final OperationAndData operationAndData) throws Exception - { - try - { - final OperationTrace trace = client.getZookeeperClient().startAdvancedTracer("GetACLBuilderImpl-Background"); - AsyncCallback.ACLCallback callback = new AsyncCallback.ACLCallback() - { + public void performBackgroundOperation(final OperationAndData operationAndData) throws Exception { + try { + final OperationTrace trace = + client.getZookeeperClient().startAdvancedTracer("GetACLBuilderImpl-Background"); + AsyncCallback.ACLCallback callback = new AsyncCallback.ACLCallback() { @Override - public void processResult(int rc, String path, Object ctx, List acl, Stat stat) - { + public void processResult(int rc, String path, Object ctx, List acl, Stat stat) { trace.setReturnCode(rc).setPath(path).setStat(stat).commit(); - CuratorEventImpl event = new CuratorEventImpl(client, CuratorEventType.GET_ACL, rc, path, null, ctx, stat, null, null, null, acl, null); + CuratorEventImpl event = new CuratorEventImpl( + client, CuratorEventType.GET_ACL, rc, path, null, ctx, stat, null, null, null, acl, null); client.processBackgroundOperation(operationAndData, event); } }; - client.getZooKeeper().getACL(operationAndData.getData(), responseStat, callback, backgrounding.getContext()); - } - catch ( Throwable e ) - { + client.getZooKeeper() + .getACL(operationAndData.getData(), responseStat, callback, backgrounding.getContext()); + } catch (Throwable e) { backgrounding.checkError(e, null); } } @Override - public List forPath(String path) throws Exception - { + public List forPath(String path) throws Exception { path = client.fixForNamespace(path); - List result = null; - if ( backgrounding.inBackground() ) - { - client.processBackgroundOperation(new OperationAndData(this, path, backgrounding.getCallback(), null, backgrounding.getContext(), null), null); - } - else - { + List result = null; + if (backgrounding.inBackground()) { + client.processBackgroundOperation( + new OperationAndData( + this, path, backgrounding.getCallback(), null, backgrounding.getContext(), null), + null); + } else { result = pathInForeground(path); } return result; } - private List pathInForeground(final String path) throws Exception - { - OperationTrace trace = client.getZookeeperClient().startAdvancedTracer("GetACLBuilderImpl-Foreground"); - List result = RetryLoop.callWithRetry - ( - client.getZookeeperClient(), - new Callable>() - { - @Override - public List call() throws Exception - { - return client.getZooKeeper().getACL(path, responseStat); - } + private List pathInForeground(final String path) throws Exception { + OperationTrace trace = client.getZookeeperClient().startAdvancedTracer("GetACLBuilderImpl-Foreground"); + List result = RetryLoop.callWithRetry(client.getZookeeperClient(), new Callable>() { + @Override + public List call() throws Exception { + return client.getZooKeeper().getACL(path, responseStat); } - ); + }); trace.setPath(path).setStat(responseStat).commit(); return result; } diff --git a/curator-framework/src/main/java/org/apache/curator/framework/imps/GetChildrenBuilderImpl.java b/curator-framework/src/main/java/org/apache/curator/framework/imps/GetChildrenBuilderImpl.java index 26695c234..9089988b2 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/imps/GetChildrenBuilderImpl.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/imps/GetChildrenBuilderImpl.java @@ -20,6 +20,9 @@ package org.apache.curator.framework.imps; import com.google.common.collect.Lists; +import java.util.List; +import java.util.concurrent.Callable; +import java.util.concurrent.Executor; import org.apache.curator.RetryLoop; import org.apache.curator.drivers.OperationTrace; import org.apache.curator.framework.api.BackgroundCallback; @@ -35,27 +38,23 @@ import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.Watcher; import org.apache.zookeeper.data.Stat; -import java.util.List; -import java.util.concurrent.Callable; -import java.util.concurrent.Executor; -public class GetChildrenBuilderImpl implements GetChildrenBuilder, BackgroundOperation, ErrorListenerPathable> -{ +public class GetChildrenBuilderImpl + implements GetChildrenBuilder, BackgroundOperation, ErrorListenerPathable> { private final CuratorFrameworkImpl client; private Watching watching; private Backgrounding backgrounding; - private Stat responseStat; + private Stat responseStat; - GetChildrenBuilderImpl(CuratorFrameworkImpl client) - { + GetChildrenBuilderImpl(CuratorFrameworkImpl client) { this.client = client; watching = new Watching(client); backgrounding = new Backgrounding(); responseStat = null; } - public GetChildrenBuilderImpl(CuratorFrameworkImpl client, Watcher watcher, Backgrounding backgrounding, Stat responseStat) - { + public GetChildrenBuilderImpl( + CuratorFrameworkImpl client, Watcher watcher, Backgrounding backgrounding, Stat responseStat) { this.client = client; this.watching = new Watching(client, watcher); this.backgrounding = backgrounding; @@ -63,34 +62,28 @@ public GetChildrenBuilderImpl(CuratorFrameworkImpl client, Watcher watcher, Back } @Override - public WatchPathable> storingStatIn(Stat stat) - { + public WatchPathable> storingStatIn(Stat stat) { responseStat = stat; - return new WatchPathable>() - { + return new WatchPathable>() { @Override - public List forPath(String path) throws Exception - { + public List forPath(String path) throws Exception { return GetChildrenBuilderImpl.this.forPath(path); } @Override - public Pathable> watched() - { + public Pathable> watched() { GetChildrenBuilderImpl.this.watched(); return GetChildrenBuilderImpl.this; } @Override - public Pathable> usingWatcher(Watcher watcher) - { + public Pathable> usingWatcher(Watcher watcher) { GetChildrenBuilderImpl.this.usingWatcher(watcher); return GetChildrenBuilderImpl.this; } @Override - public Pathable> usingWatcher(CuratorWatcher watcher) - { + public Pathable> usingWatcher(CuratorWatcher watcher) { GetChildrenBuilderImpl.this.usingWatcher(watcher); return GetChildrenBuilderImpl.this; } @@ -98,156 +91,152 @@ public Pathable> usingWatcher(CuratorWatcher watcher) } @Override - public ErrorListenerPathable> inBackground(BackgroundCallback callback, Object context) - { + public ErrorListenerPathable> inBackground(BackgroundCallback callback, Object context) { backgrounding = new Backgrounding(callback, context); return this; } @Override - public ErrorListenerPathable> inBackground(BackgroundCallback callback, Object context, Executor executor) - { + public ErrorListenerPathable> inBackground( + BackgroundCallback callback, Object context, Executor executor) { backgrounding = new Backgrounding(client, callback, context, executor); return this; } @Override - public ErrorListenerPathable> inBackground(BackgroundCallback callback) - { + public ErrorListenerPathable> inBackground(BackgroundCallback callback) { backgrounding = new Backgrounding(callback); return this; } @Override - public ErrorListenerPathable> inBackground(BackgroundCallback callback, Executor executor) - { + public ErrorListenerPathable> inBackground(BackgroundCallback callback, Executor executor) { backgrounding = new Backgrounding(client, callback, executor); return this; } @Override - public ErrorListenerPathable> inBackground() - { + public ErrorListenerPathable> inBackground() { backgrounding = new Backgrounding(true); return this; } @Override - public ErrorListenerPathable> inBackground(Object context) - { + public ErrorListenerPathable> inBackground(Object context) { backgrounding = new Backgrounding(context); return this; } @Override - public Pathable> withUnhandledErrorListener(UnhandledErrorListener listener) - { + public Pathable> withUnhandledErrorListener(UnhandledErrorListener listener) { backgrounding = new Backgrounding(backgrounding, listener); return this; } @Override - public BackgroundPathable> watched() - { + public BackgroundPathable> watched() { watching = new Watching(client, true); return this; } @Override - public BackgroundPathable> usingWatcher(Watcher watcher) - { + public BackgroundPathable> usingWatcher(Watcher watcher) { watching = new Watching(client, watcher); return this; } @Override - public BackgroundPathable> usingWatcher(CuratorWatcher watcher) - { + public BackgroundPathable> usingWatcher(CuratorWatcher watcher) { watching = new Watching(client, watcher); return this; } @Override - public void performBackgroundOperation(final OperationAndData operationAndData) throws Exception - { - try - { - final OperationTrace trace = client.getZookeeperClient().startAdvancedTracer("GetChildrenBuilderImpl-Background"); - AsyncCallback.Children2Callback callback = new AsyncCallback.Children2Callback() - { + public void performBackgroundOperation(final OperationAndData operationAndData) throws Exception { + try { + final OperationTrace trace = + client.getZookeeperClient().startAdvancedTracer("GetChildrenBuilderImpl-Background"); + AsyncCallback.Children2Callback callback = new AsyncCallback.Children2Callback() { @Override - public void processResult(int rc, String path, Object o, List strings, Stat stat) - { + public void processResult(int rc, String path, Object o, List strings, Stat stat) { watching.commitWatcher(rc, false); - trace.setReturnCode(rc).setPath(path).setWithWatcher(watching.hasWatcher()).setStat(stat).commit(); - if ( strings == null ) - { + trace.setReturnCode(rc) + .setPath(path) + .setWithWatcher(watching.hasWatcher()) + .setStat(stat) + .commit(); + if (strings == null) { strings = Lists.newArrayList(); } - CuratorEventImpl event = new CuratorEventImpl(client, CuratorEventType.CHILDREN, rc, path, null, o, stat, null, strings, null, null, null); + CuratorEventImpl event = new CuratorEventImpl( + client, + CuratorEventType.CHILDREN, + rc, + path, + null, + o, + stat, + null, + strings, + null, + null, + null); client.processBackgroundOperation(operationAndData, event); } }; - if ( watching.isWatched() ) - { - client.getZooKeeper().getChildren(operationAndData.getData(), true, callback, backgrounding.getContext()); - } - else - { - client.getZooKeeper().getChildren(operationAndData.getData(), watching.getWatcher(operationAndData.getData()), callback, backgrounding.getContext()); + if (watching.isWatched()) { + client.getZooKeeper() + .getChildren(operationAndData.getData(), true, callback, backgrounding.getContext()); + } else { + client.getZooKeeper() + .getChildren( + operationAndData.getData(), + watching.getWatcher(operationAndData.getData()), + callback, + backgrounding.getContext()); } - } - catch ( Throwable e ) - { + } catch (Throwable e) { backgrounding.checkError(e, watching); } } @Override - public List forPath(String path) throws Exception - { + public List forPath(String path) throws Exception { client.getSchemaSet().getSchema(path).validateWatch(path, watching.isWatched() || watching.hasWatcher()); path = client.fixForNamespace(path); - List children = null; - if ( backgrounding.inBackground() ) - { - client.processBackgroundOperation(new OperationAndData(this, path, backgrounding.getCallback(), null, backgrounding.getContext(), watching), null); - } - else - { + List children = null; + if (backgrounding.inBackground()) { + client.processBackgroundOperation( + new OperationAndData( + this, path, backgrounding.getCallback(), null, backgrounding.getContext(), watching), + null); + } else { children = pathInForeground(path); } return children; } - private List pathInForeground(final String path) throws Exception - { - OperationTrace trace = client.getZookeeperClient().startAdvancedTracer("GetChildrenBuilderImpl-Foreground"); - List children = RetryLoop.callWithRetry - ( - client.getZookeeperClient(), - new Callable>() - { - @Override - public List call() throws Exception - { - List children; - if ( watching.isWatched() ) - { - children = client.getZooKeeper().getChildren(path, true, responseStat); - } - else - { - children = client.getZooKeeper().getChildren(path, watching.getWatcher(path), responseStat); - watching.commitWatcher(KeeperException.NoNodeException.Code.OK.intValue(), false); - } - return children; + private List pathInForeground(final String path) throws Exception { + OperationTrace trace = client.getZookeeperClient().startAdvancedTracer("GetChildrenBuilderImpl-Foreground"); + List children = RetryLoop.callWithRetry(client.getZookeeperClient(), new Callable>() { + @Override + public List call() throws Exception { + List children; + if (watching.isWatched()) { + children = client.getZooKeeper().getChildren(path, true, responseStat); + } else { + children = client.getZooKeeper().getChildren(path, watching.getWatcher(path), responseStat); + watching.commitWatcher(KeeperException.NoNodeException.Code.OK.intValue(), false); } + return children; } - ); - trace.setPath(path).setWithWatcher(watching.hasWatcher()).setStat(responseStat).commit(); + }); + trace.setPath(path) + .setWithWatcher(watching.hasWatcher()) + .setStat(responseStat) + .commit(); return children; } } diff --git a/curator-framework/src/main/java/org/apache/curator/framework/imps/GetConfigBuilderImpl.java b/curator-framework/src/main/java/org/apache/curator/framework/imps/GetConfigBuilderImpl.java index 54855231e..5ec913e9d 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/imps/GetConfigBuilderImpl.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/imps/GetConfigBuilderImpl.java @@ -19,6 +19,8 @@ package org.apache.curator.framework.imps; +import java.util.concurrent.Callable; +import java.util.concurrent.Executor; import org.apache.curator.RetryLoop; import org.apache.curator.TimeTrace; import org.apache.curator.framework.api.*; @@ -27,26 +29,22 @@ import org.apache.zookeeper.Watcher; import org.apache.zookeeper.ZooDefs; import org.apache.zookeeper.data.Stat; -import java.util.concurrent.Callable; -import java.util.concurrent.Executor; -public class GetConfigBuilderImpl implements GetConfigBuilder, BackgroundOperation, ErrorListenerEnsembleable -{ +public class GetConfigBuilderImpl + implements GetConfigBuilder, BackgroundOperation, ErrorListenerEnsembleable { private final CuratorFrameworkImpl client; private Backgrounding backgrounding; private Watching watching; private Stat stat; - public GetConfigBuilderImpl(CuratorFrameworkImpl client) - { + public GetConfigBuilderImpl(CuratorFrameworkImpl client) { this.client = client; backgrounding = new Backgrounding(); watching = new Watching(client); } - public GetConfigBuilderImpl(CuratorFrameworkImpl client, Backgrounding backgrounding, Watcher watcher, Stat stat) - { + public GetConfigBuilderImpl(CuratorFrameworkImpl client, Backgrounding backgrounding, Watcher watcher, Stat stat) { this.client = client; this.backgrounding = backgrounding; this.watching = new Watching(client, watcher); @@ -54,260 +52,225 @@ public GetConfigBuilderImpl(CuratorFrameworkImpl client, Backgrounding backgroun } @Override - public WatchBackgroundEnsembleable storingStatIn(Stat stat) - { + public WatchBackgroundEnsembleable storingStatIn(Stat stat) { this.stat = stat; - return new WatchBackgroundEnsembleable() - { + return new WatchBackgroundEnsembleable() { @Override - public ErrorListenerEnsembleable inBackground() - { + public ErrorListenerEnsembleable inBackground() { return GetConfigBuilderImpl.this.inBackground(); } @Override - public ErrorListenerEnsembleable inBackground(Object context) - { + public ErrorListenerEnsembleable inBackground(Object context) { return GetConfigBuilderImpl.this.inBackground(context); } @Override - public ErrorListenerEnsembleable inBackground(BackgroundCallback callback) - { + public ErrorListenerEnsembleable inBackground(BackgroundCallback callback) { return GetConfigBuilderImpl.this.inBackground(callback); } @Override - public ErrorListenerEnsembleable inBackground(BackgroundCallback callback, Object context) - { + public ErrorListenerEnsembleable inBackground(BackgroundCallback callback, Object context) { return GetConfigBuilderImpl.this.inBackground(callback, context); } @Override - public ErrorListenerEnsembleable inBackground(BackgroundCallback callback, Executor executor) - { + public ErrorListenerEnsembleable inBackground(BackgroundCallback callback, Executor executor) { return GetConfigBuilderImpl.this.inBackground(callback, executor); } @Override - public ErrorListenerEnsembleable inBackground(BackgroundCallback callback, Object context, Executor executor) - { + public ErrorListenerEnsembleable inBackground( + BackgroundCallback callback, Object context, Executor executor) { return GetConfigBuilderImpl.this.inBackground(callback, context, executor); } @Override - public byte[] forEnsemble() throws Exception - { + public byte[] forEnsemble() throws Exception { return GetConfigBuilderImpl.this.forEnsemble(); } @Override - public BackgroundEnsembleable watched() - { + public BackgroundEnsembleable watched() { return GetConfigBuilderImpl.this.watched(); } @Override - public BackgroundEnsembleable usingWatcher(Watcher watcher) - { + public BackgroundEnsembleable usingWatcher(Watcher watcher) { return GetConfigBuilderImpl.this.usingWatcher(watcher); } @Override - public BackgroundEnsembleable usingWatcher(CuratorWatcher watcher) - { + public BackgroundEnsembleable usingWatcher(CuratorWatcher watcher) { return GetConfigBuilderImpl.this.usingWatcher(watcher); } }; } @Override - public BackgroundEnsembleable watched() - { + public BackgroundEnsembleable watched() { watching = new Watching(client, true); return new InternalBackgroundEnsembleable(); } @Override - public BackgroundEnsembleable usingWatcher(Watcher watcher) - { + public BackgroundEnsembleable usingWatcher(Watcher watcher) { watching = new Watching(client, watcher); return new InternalBackgroundEnsembleable(); } @Override - public BackgroundEnsembleable usingWatcher(CuratorWatcher watcher) - { + public BackgroundEnsembleable usingWatcher(CuratorWatcher watcher) { watching = new Watching(client, watcher); return new InternalBackgroundEnsembleable(); } @Override - public ErrorListenerEnsembleable inBackground() - { + public ErrorListenerEnsembleable inBackground() { backgrounding = new Backgrounding(true); return this; } @Override - public ErrorListenerEnsembleable inBackground(Object context) - { + public ErrorListenerEnsembleable inBackground(Object context) { backgrounding = new Backgrounding(context); return this; } @Override - public ErrorListenerEnsembleable inBackground(BackgroundCallback callback) - { + public ErrorListenerEnsembleable inBackground(BackgroundCallback callback) { backgrounding = new Backgrounding(callback); return this; } @Override - public ErrorListenerEnsembleable inBackground(BackgroundCallback callback, Object context) - { + public ErrorListenerEnsembleable inBackground(BackgroundCallback callback, Object context) { backgrounding = new Backgrounding(callback, context); return this; } @Override - public ErrorListenerEnsembleable inBackground(BackgroundCallback callback, Executor executor) - { + public ErrorListenerEnsembleable inBackground(BackgroundCallback callback, Executor executor) { backgrounding = new Backgrounding(callback, executor); return this; } @Override - public ErrorListenerEnsembleable inBackground(BackgroundCallback callback, Object context, Executor executor) - { + public ErrorListenerEnsembleable inBackground( + BackgroundCallback callback, Object context, Executor executor) { backgrounding = new Backgrounding(client, callback, context, executor); return this; } @Override - public Ensembleable withUnhandledErrorListener(UnhandledErrorListener listener) - { + public Ensembleable withUnhandledErrorListener(UnhandledErrorListener listener) { backgrounding = new Backgrounding(backgrounding, listener); return this; } @Override - public byte[] forEnsemble() throws Exception - { - if ( backgrounding.inBackground() ) - { - client.processBackgroundOperation(new OperationAndData(this, null, backgrounding.getCallback(), null, backgrounding.getContext(), watching), null); + public byte[] forEnsemble() throws Exception { + if (backgrounding.inBackground()) { + client.processBackgroundOperation( + new OperationAndData( + this, null, backgrounding.getCallback(), null, backgrounding.getContext(), watching), + null); return null; - } - else - { + } else { return configInForeground(); } } @Override - public void performBackgroundOperation(final OperationAndData operationAndData) throws Exception - { - try - { + public void performBackgroundOperation(final OperationAndData operationAndData) throws Exception { + try { final TimeTrace trace = client.getZookeeperClient().startTracer("GetDataBuilderImpl-Background"); - AsyncCallback.DataCallback callback = new AsyncCallback.DataCallback() - { + AsyncCallback.DataCallback callback = new AsyncCallback.DataCallback() { @Override - public void processResult(int rc, String path, Object ctx, byte[] data, Stat stat) - { + public void processResult(int rc, String path, Object ctx, byte[] data, Stat stat) { watching.commitWatcher(rc, false); trace.commit(); - CuratorEvent event = new CuratorEventImpl(client, CuratorEventType.GET_CONFIG, rc, path, null, ctx, stat, data, null, null, null, null); + CuratorEvent event = new CuratorEventImpl( + client, + CuratorEventType.GET_CONFIG, + rc, + path, + null, + ctx, + stat, + data, + null, + null, + null, + null); client.processBackgroundOperation(operationAndData, event); } }; - if ( watching.isWatched() ) - { + if (watching.isWatched()) { client.getZooKeeper().getConfig(true, callback, backgrounding.getContext()); + } else { + client.getZooKeeper() + .getConfig(watching.getWatcher(ZooDefs.CONFIG_NODE), callback, backgrounding.getContext()); } - else - { - client.getZooKeeper().getConfig(watching.getWatcher(ZooDefs.CONFIG_NODE), callback, backgrounding.getContext()); - } - } - catch ( Throwable e ) - { + } catch (Throwable e) { backgrounding.checkError(e, watching); } } - private byte[] configInForeground() throws Exception - { + private byte[] configInForeground() throws Exception { TimeTrace trace = client.getZookeeperClient().startTracer("GetConfigBuilderImpl-Foreground"); - try - { - return RetryLoop.callWithRetry - ( - client.getZookeeperClient(), - new Callable() - { - @Override - public byte[] call() throws Exception - { - if ( watching.isWatched() ) - { - return client.getZooKeeper().getConfig(true, stat); - } - byte[] config = client.getZooKeeper().getConfig(watching.getWatcher(ZooDefs.CONFIG_NODE), stat); - watching.commitWatcher(KeeperException.NoNodeException.Code.OK.intValue(), false); - return config; + try { + return RetryLoop.callWithRetry(client.getZookeeperClient(), new Callable() { + @Override + public byte[] call() throws Exception { + if (watching.isWatched()) { + return client.getZooKeeper().getConfig(true, stat); } + byte[] config = client.getZooKeeper().getConfig(watching.getWatcher(ZooDefs.CONFIG_NODE), stat); + watching.commitWatcher(KeeperException.NoNodeException.Code.OK.intValue(), false); + return config; } - ); - } - finally - { + }); + } finally { trace.commit(); } } - private class InternalBackgroundEnsembleable implements BackgroundEnsembleable - { + private class InternalBackgroundEnsembleable implements BackgroundEnsembleable { @Override - public ErrorListenerEnsembleable inBackground() - { + public ErrorListenerEnsembleable inBackground() { return GetConfigBuilderImpl.this.inBackground(); } @Override - public ErrorListenerEnsembleable inBackground(Object context) - { + public ErrorListenerEnsembleable inBackground(Object context) { return GetConfigBuilderImpl.this.inBackground(context); } @Override - public ErrorListenerEnsembleable inBackground(BackgroundCallback callback) - { + public ErrorListenerEnsembleable inBackground(BackgroundCallback callback) { return GetConfigBuilderImpl.this.inBackground(callback); } @Override - public ErrorListenerEnsembleable inBackground(BackgroundCallback callback, Object context) - { + public ErrorListenerEnsembleable inBackground(BackgroundCallback callback, Object context) { return GetConfigBuilderImpl.this.inBackground(callback, context); } @Override - public ErrorListenerEnsembleable inBackground(BackgroundCallback callback, Executor executor) - { + public ErrorListenerEnsembleable inBackground(BackgroundCallback callback, Executor executor) { return GetConfigBuilderImpl.this.inBackground(callback, executor); } @Override - public ErrorListenerEnsembleable inBackground(BackgroundCallback callback, Object context, Executor executor) - { + public ErrorListenerEnsembleable inBackground( + BackgroundCallback callback, Object context, Executor executor) { return GetConfigBuilderImpl.this.inBackground(callback, context, executor); } @Override - public byte[] forEnsemble() throws Exception - { + public byte[] forEnsemble() throws Exception { return GetConfigBuilderImpl.this.forEnsemble(); } } diff --git a/curator-framework/src/main/java/org/apache/curator/framework/imps/GetDataBuilderImpl.java b/curator-framework/src/main/java/org/apache/curator/framework/imps/GetDataBuilderImpl.java index 5f73cbc55..a031200fa 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/imps/GetDataBuilderImpl.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/imps/GetDataBuilderImpl.java @@ -19,6 +19,8 @@ package org.apache.curator.framework.imps; +import java.util.concurrent.Callable; +import java.util.concurrent.Executor; import org.apache.curator.RetryLoop; import org.apache.curator.drivers.OperationTrace; import org.apache.curator.framework.api.*; @@ -30,20 +32,16 @@ import org.apache.zookeeper.server.DataTree; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.util.concurrent.Callable; -import java.util.concurrent.Executor; -public class GetDataBuilderImpl implements GetDataBuilder, BackgroundOperation, ErrorListenerPathable -{ - private final Logger log = LoggerFactory.getLogger(getClass()); - private final CuratorFrameworkImpl client; - private Stat responseStat; - private Watching watching; - private Backgrounding backgrounding; - private boolean decompress; - - GetDataBuilderImpl(CuratorFrameworkImpl client) - { +public class GetDataBuilderImpl implements GetDataBuilder, BackgroundOperation, ErrorListenerPathable { + private final Logger log = LoggerFactory.getLogger(getClass()); + private final CuratorFrameworkImpl client; + private Stat responseStat; + private Watching watching; + private Backgrounding backgrounding; + private boolean decompress; + + GetDataBuilderImpl(CuratorFrameworkImpl client) { this.client = client; responseStat = null; watching = new Watching(client); @@ -51,8 +49,12 @@ public class GetDataBuilderImpl implements GetDataBuilder, BackgroundOperation inBackground() - { + public ErrorListenerPathable inBackground() { return GetDataBuilderImpl.this.inBackground(); } @Override - public ErrorListenerPathable inBackground(BackgroundCallback callback, Object context) - { + public ErrorListenerPathable inBackground(BackgroundCallback callback, Object context) { return GetDataBuilderImpl.this.inBackground(callback, context); } @Override - public ErrorListenerPathable inBackground(BackgroundCallback callback, Object context, Executor executor) - { + public ErrorListenerPathable inBackground( + BackgroundCallback callback, Object context, Executor executor) { return GetDataBuilderImpl.this.inBackground(callback, context, executor); } @Override - public ErrorListenerPathable inBackground(Object context) - { + public ErrorListenerPathable inBackground(Object context) { return GetDataBuilderImpl.this.inBackground(context); } @Override - public ErrorListenerPathable inBackground(BackgroundCallback callback) - { + public ErrorListenerPathable inBackground(BackgroundCallback callback) { return GetDataBuilderImpl.this.inBackground(callback); } @Override - public ErrorListenerPathable inBackground(BackgroundCallback callback, Executor executor) - { + public ErrorListenerPathable inBackground(BackgroundCallback callback, Executor executor) { return GetDataBuilderImpl.this.inBackground(callback, executor); } @Override - public byte[] forPath(String path) throws Exception - { + public byte[] forPath(String path) throws Exception { return GetDataBuilderImpl.this.forPath(path); } @Override - public WatchPathable storingStatIn(Stat stat) - { + public WatchPathable storingStatIn(Stat stat) { return GetDataBuilderImpl.this.storingStatIn(stat); } @Override - public BackgroundPathable watched() - { + public BackgroundPathable watched() { return GetDataBuilderImpl.this.watched(); } @Override - public BackgroundPathable usingWatcher(Watcher watcher) - { + public BackgroundPathable usingWatcher(Watcher watcher) { return GetDataBuilderImpl.this.usingWatcher(watcher); } @Override - public BackgroundPathable usingWatcher(CuratorWatcher watcher) - { + public BackgroundPathable usingWatcher(CuratorWatcher watcher) { return GetDataBuilderImpl.this.usingWatcher(watcher); } }; } @Override - public WatchPathable storingStatIn(Stat stat) - { + public WatchPathable storingStatIn(Stat stat) { this.responseStat = stat; - return new WatchPathable() - { + return new WatchPathable() { @Override - public byte[] forPath(String path) throws Exception - { + public byte[] forPath(String path) throws Exception { return GetDataBuilderImpl.this.forPath(path); } @Override - public Pathable watched() - { + public Pathable watched() { GetDataBuilderImpl.this.watched(); return GetDataBuilderImpl.this; } @Override - public Pathable usingWatcher(Watcher watcher) - { + public Pathable usingWatcher(Watcher watcher) { GetDataBuilderImpl.this.usingWatcher(watcher); return GetDataBuilderImpl.this; } @Override - public Pathable usingWatcher(CuratorWatcher watcher) - { + public Pathable usingWatcher(CuratorWatcher watcher) { GetDataBuilderImpl.this.usingWatcher(watcher); return GetDataBuilderImpl.this; } @@ -170,169 +154,150 @@ public Pathable usingWatcher(CuratorWatcher watcher) } @Override - public ErrorListenerPathable inBackground(BackgroundCallback callback, Object context) - { + public ErrorListenerPathable inBackground(BackgroundCallback callback, Object context) { backgrounding = new Backgrounding(callback, context); return this; } @Override - public ErrorListenerPathable inBackground(BackgroundCallback callback, Object context, Executor executor) - { + public ErrorListenerPathable inBackground(BackgroundCallback callback, Object context, Executor executor) { backgrounding = new Backgrounding(client, callback, context, executor); return this; } @Override - public ErrorListenerPathable inBackground(BackgroundCallback callback) - { + public ErrorListenerPathable inBackground(BackgroundCallback callback) { backgrounding = new Backgrounding(callback); return this; } @Override - public ErrorListenerPathable inBackground(BackgroundCallback callback, Executor executor) - { + public ErrorListenerPathable inBackground(BackgroundCallback callback, Executor executor) { backgrounding = new Backgrounding(client, callback, executor); return this; } @Override - public ErrorListenerPathable inBackground() - { + public ErrorListenerPathable inBackground() { backgrounding = new Backgrounding(true); return this; } @Override - public ErrorListenerPathable inBackground(Object context) - { + public ErrorListenerPathable inBackground(Object context) { backgrounding = new Backgrounding(context); return this; } @Override - public Pathable withUnhandledErrorListener(UnhandledErrorListener listener) - { + public Pathable withUnhandledErrorListener(UnhandledErrorListener listener) { backgrounding = new Backgrounding(backgrounding, listener); return this; } @Override - public BackgroundPathable watched() - { + public BackgroundPathable watched() { watching = new Watching(client, true); return this; } @Override - public BackgroundPathable usingWatcher(Watcher watcher) - { + public BackgroundPathable usingWatcher(Watcher watcher) { watching = new Watching(client, watcher); return this; } @Override - public BackgroundPathable usingWatcher(CuratorWatcher watcher) - { + public BackgroundPathable usingWatcher(CuratorWatcher watcher) { watching = new Watching(client, watcher); return this; } @Override - public void performBackgroundOperation(final OperationAndData operationAndData) throws Exception - { - try - { - final OperationTrace trace = client.getZookeeperClient().startAdvancedTracer("GetDataBuilderImpl-Background"); - AsyncCallback.DataCallback callback = new AsyncCallback.DataCallback() - { + public void performBackgroundOperation(final OperationAndData operationAndData) throws Exception { + try { + final OperationTrace trace = + client.getZookeeperClient().startAdvancedTracer("GetDataBuilderImpl-Background"); + AsyncCallback.DataCallback callback = new AsyncCallback.DataCallback() { @Override - public void processResult(int rc, String path, Object ctx, byte[] data, Stat stat) - { + public void processResult(int rc, String path, Object ctx, byte[] data, Stat stat) { watching.commitWatcher(rc, false); - trace.setReturnCode(rc).setResponseBytesLength(data).setPath(path).setWithWatcher(watching.hasWatcher()).setStat(stat).commit(); - if ( (responseStat != null) && (stat != null) ) - { + trace.setReturnCode(rc) + .setResponseBytesLength(data) + .setPath(path) + .setWithWatcher(watching.hasWatcher()) + .setStat(stat) + .commit(); + if ((responseStat != null) && (stat != null)) { DataTree.copyStat(stat, responseStat); } - if ( decompress && (data != null) ) - { - try - { + if (decompress && (data != null)) { + try { data = client.getCompressionProvider().decompress(path, data); - } - catch ( Exception e ) - { + } catch (Exception e) { ThreadUtils.checkInterrupted(e); log.error("Decompressing for path: " + path, e); rc = KeeperException.Code.DATAINCONSISTENCY.intValue(); } } - CuratorEvent event = new CuratorEventImpl(client, CuratorEventType.GET_DATA, rc, path, null, ctx, stat, data, null, null, null, null); + CuratorEvent event = new CuratorEventImpl( + client, CuratorEventType.GET_DATA, rc, path, null, ctx, stat, data, null, null, null, null); client.processBackgroundOperation(operationAndData, event); } }; - if ( watching.isWatched() ) - { + if (watching.isWatched()) { client.getZooKeeper().getData(operationAndData.getData(), true, callback, backgrounding.getContext()); + } else { + client.getZooKeeper() + .getData( + operationAndData.getData(), + watching.getWatcher(operationAndData.getData()), + callback, + backgrounding.getContext()); } - else - { - client.getZooKeeper().getData(operationAndData.getData(), watching.getWatcher(operationAndData.getData()), callback, backgrounding.getContext()); - } - } - catch ( Throwable e ) - { + } catch (Throwable e) { backgrounding.checkError(e, watching); } } @Override - public byte[] forPath(String path) throws Exception - { + public byte[] forPath(String path) throws Exception { client.getSchemaSet().getSchema(path).validateWatch(path, watching.isWatched() || watching.hasWatcher()); path = client.fixForNamespace(path); - byte[] responseData = null; - if ( backgrounding.inBackground() ) - { - client.processBackgroundOperation(new OperationAndData(this, path, backgrounding.getCallback(), null, backgrounding.getContext(), watching), null); - } - else - { + byte[] responseData = null; + if (backgrounding.inBackground()) { + client.processBackgroundOperation( + new OperationAndData( + this, path, backgrounding.getCallback(), null, backgrounding.getContext(), watching), + null); + } else { responseData = pathInForeground(path); } return responseData; } - private byte[] pathInForeground(final String path) throws Exception - { - OperationTrace trace = client.getZookeeperClient().startAdvancedTracer("GetDataBuilderImpl-Foreground"); - byte[] responseData = RetryLoop.callWithRetry - ( - client.getZookeeperClient(), - new Callable() - { - @Override - public byte[] call() throws Exception - { - byte[] responseData; - if ( watching.isWatched() ) - { - responseData = client.getZooKeeper().getData(path, true, responseStat); - } - else - { - responseData = client.getZooKeeper().getData(path, watching.getWatcher(path), responseStat); - watching.commitWatcher(KeeperException.NoNodeException.Code.OK.intValue(), false); - } - return responseData; + private byte[] pathInForeground(final String path) throws Exception { + OperationTrace trace = client.getZookeeperClient().startAdvancedTracer("GetDataBuilderImpl-Foreground"); + byte[] responseData = RetryLoop.callWithRetry(client.getZookeeperClient(), new Callable() { + @Override + public byte[] call() throws Exception { + byte[] responseData; + if (watching.isWatched()) { + responseData = client.getZooKeeper().getData(path, true, responseStat); + } else { + responseData = client.getZooKeeper().getData(path, watching.getWatcher(path), responseStat); + watching.commitWatcher(KeeperException.NoNodeException.Code.OK.intValue(), false); } + return responseData; } - ); - trace.setResponseBytesLength(responseData).setPath(path).setWithWatcher(watching.hasWatcher()).setStat(responseStat).commit(); + }); + trace.setResponseBytesLength(responseData) + .setPath(path) + .setWithWatcher(watching.hasWatcher()) + .setStat(responseStat) + .commit(); return decompress ? client.getCompressionProvider().decompress(path, responseData) : responseData; } diff --git a/curator-framework/src/main/java/org/apache/curator/framework/imps/GzipCompressionProvider.java b/curator-framework/src/main/java/org/apache/curator/framework/imps/GzipCompressionProvider.java index 913628315..8d5136e9e 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/imps/GzipCompressionProvider.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/imps/GzipCompressionProvider.java @@ -20,8 +20,6 @@ package org.apache.curator.framework.imps; import com.google.common.annotations.VisibleForTesting; -import org.apache.curator.framework.api.CompressionProvider; - import java.io.EOFException; import java.io.IOException; import java.nio.BufferUnderflowException; @@ -30,9 +28,9 @@ import java.util.Arrays; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.zip.*; +import org.apache.curator.framework.api.CompressionProvider; -public class GzipCompressionProvider implements CompressionProvider -{ +public class GzipCompressionProvider implements CompressionProvider { // This class re-implements java.util.zip.GZIPInputStream and GZIPOutputStream functionality to avoid // creation many finalized Deflater and Inflater objects on heap (see // https://issues.apache.org/jira/browse/CURATOR-487). Even when Curator's minimum supported Java version becomes @@ -49,6 +47,7 @@ public class GzipCompressionProvider implements CompressionProvider // The value of the OS bit has changed in JDK 16; // see https://bugs.openjdk.org/browse/JDK-8244706 for details. private static final byte OS_BIT; + static { final String version = System.getProperty("java.specification.version"); if (version.contains(".")) { @@ -61,22 +60,23 @@ public class GzipCompressionProvider implements CompressionProvider /** See {@code java.util.zip.GZIPOutputStream.writeHeader()} */ private static final byte[] GZIP_HEADER = new byte[] { - (byte) GZIP_MAGIC, // Magic number (byte 0) - (byte) (GZIP_MAGIC >> 8), // Magic number (byte 1) - Deflater.DEFLATED, // Compression method (CM) - 0, // Flags (FLG) - 0, // Modification time MTIME (byte 0) - 0, // Modification time MTIME (byte 1) - 0, // Modification time MTIME (byte 2) - 0, // Modification time MTIME (byte 3) - 0, // Extra flags (XFLG) - OS_BIT // Operating system (OS) + (byte) GZIP_MAGIC, // Magic number (byte 0) + (byte) (GZIP_MAGIC >> 8), // Magic number (byte 1) + Deflater.DEFLATED, // Compression method (CM) + 0, // Flags (FLG) + 0, // Modification time MTIME (byte 0) + 0, // Modification time MTIME (byte 1) + 0, // Modification time MTIME (byte 2) + 0, // Modification time MTIME (byte 3) + 0, // Extra flags (XFLG) + OS_BIT // Operating system (OS) }; /** GZip flags, {@link #GZIP_HEADER}'s 4th byte */ private static final int FHCRC = 1 << 1; + private static final int FEXTRA = 1 << 2; - private static final int FNAME = 1 << 3; + private static final int FNAME = 1 << 3; private static final int FCOMMENT = 1 << 4; private static final int GZIP_HEADER_SIZE = GZIP_HEADER.length; @@ -94,29 +94,25 @@ public class GzipCompressionProvider implements CompressionProvider * of strongly-referenced objects. */ private static final ConcurrentLinkedQueue DEFLATER_POOL = new ConcurrentLinkedQueue<>(); + private static final ConcurrentLinkedQueue INFLATER_POOL = new ConcurrentLinkedQueue<>(); /** The value verified in GzipCompressionProviderTest.testEmpty() */ - private static final byte[] COMPRESSED_EMPTY_BYTES = new byte[] { - 31, -117, 8, 0, 0, 0, 0, 0, 0, OS_BIT, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0 - }; + private static final byte[] COMPRESSED_EMPTY_BYTES = + new byte[] {31, -117, 8, 0, 0, 0, 0, 0, 0, OS_BIT, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0}; - private static Deflater acquireDeflater() - { + private static Deflater acquireDeflater() { Deflater deflater = DEFLATER_POOL.poll(); - if ( deflater == null ) - { + if (deflater == null) { // Using the same settings as in GZIPOutputStream constructor deflater = new Deflater(Deflater.DEFAULT_COMPRESSION, true); } return deflater; } - private static Inflater acquireInflater() - { + private static Inflater acquireInflater() { Inflater inflater = INFLATER_POOL.poll(); - if ( inflater == null ) - { + if (inflater == null) { // Using the same nowrap setting as GZIPInputStream constructor inflater = new Inflater(true); } @@ -124,10 +120,8 @@ private static Inflater acquireInflater() } @Override - public byte[] compress(String path, byte[] data) - { - if ( data.length == 0 ) - { + public byte[] compress(String path, byte[] data) { + if (data.length == 0) { // clone() because clients could update the array return COMPRESSED_EMPTY_BYTES.clone(); } @@ -135,21 +129,18 @@ public byte[] compress(String path, byte[] data) } @VisibleForTesting - static byte[] doCompress(byte[] data) - { + static byte[] doCompress(byte[] data) { byte[] result = Arrays.copyOf(GZIP_HEADER, conservativeGZippedSizeEstimate(data.length)); Deflater deflater = acquireDeflater(); try { deflater.setInput(data); deflater.finish(); int offset = GZIP_HEADER_SIZE; - while ( true ) - { + while (true) { int available = result.length - GZIP_TRAILER_SIZE - offset; int numCompressedBytes = deflater.deflate(result, offset, available); offset += numCompressedBytes; - if ( deflater.finished() ) - { + if (deflater.finished()) { break; } int newResultLength = result.length + (result.length / 2); @@ -161,8 +152,7 @@ static byte[] doCompress(byte[] data) writeLittleEndianInt(result, offset, (int) crc.getValue()); writeLittleEndianInt(result, offset + 4, data.length); int endOffset = offset + GZIP_TRAILER_SIZE; - if ( result.length != endOffset ) - { + if (result.length != endOffset) { result = Arrays.copyOf(result, endOffset); } return result; @@ -172,24 +162,19 @@ static byte[] doCompress(byte[] data) } } - private static int conservativeGZippedSizeEstimate(int dataSize) - { + private static int conservativeGZippedSizeEstimate(int dataSize) { int conservativeCompressedDataSizeEstimate; - if ( dataSize < 512 ) - { + if (dataSize < 512) { // Assuming DEFLATE doesn't compress small data well conservativeCompressedDataSizeEstimate = Math.max(dataSize, MIN_COMPRESSED_DATA_SIZE); - } - else - { + } else { // Assuming pretty bad 2:1 compression ratio conservativeCompressedDataSizeEstimate = Math.max(512, dataSize / 2); } return GZIP_HEADER_SIZE + conservativeCompressedDataSizeEstimate + GZIP_TRAILER_SIZE; } - private static void writeLittleEndianInt(byte[] b, int offset, int v) - { + private static void writeLittleEndianInt(byte[] b, int offset, int v) { b[offset] = (byte) v; b[offset + 1] = (byte) (v >> 8); b[offset + 2] = (byte) (v >> 16); @@ -198,8 +183,7 @@ private static void writeLittleEndianInt(byte[] b, int offset, int v) @Override public byte[] decompress(String path, byte[] gzippedDataBytes) throws IOException { - if ( Arrays.equals(gzippedDataBytes, COMPRESSED_EMPTY_BYTES) ) - { + if (Arrays.equals(gzippedDataBytes, COMPRESSED_EMPTY_BYTES)) { // Allocating a new array instead of creating a static constant because clients may somehow depend on the // identity of the returned arrays return new byte[0]; @@ -207,8 +191,7 @@ public byte[] decompress(String path, byte[] gzippedDataBytes) throws IOExceptio ByteBuffer gzippedData = ByteBuffer.wrap(gzippedDataBytes); gzippedData.order(ByteOrder.LITTLE_ENDIAN); int headerSize = readGzipHeader(gzippedData); - if ( gzippedDataBytes.length < headerSize + MIN_COMPRESSED_DATA_SIZE + GZIP_TRAILER_SIZE ) - { + if (gzippedDataBytes.length < headerSize + MIN_COMPRESSED_DATA_SIZE + GZIP_TRAILER_SIZE) { throw new EOFException("Too short GZipped data"); } int compressedDataSize = gzippedDataBytes.length - headerSize - GZIP_TRAILER_SIZE; @@ -221,8 +204,7 @@ public byte[] decompress(String path, byte[] gzippedDataBytes) throws IOExceptio inflater.setInput(gzippedDataBytes, headerSize, compressedDataSize); CRC32 crc = new CRC32(); int offset = 0; - while (true) - { + while (true) { int numDecompressedBytes; try { numDecompressedBytes = inflater.inflate(result, offset, result.length - offset); @@ -232,43 +214,36 @@ public byte[] decompress(String path, byte[] gzippedDataBytes) throws IOExceptio } crc.update(result, offset, numDecompressedBytes); offset += numDecompressedBytes; - if ( inflater.finished() || inflater.needsDictionary() ) - { + if (inflater.finished() || inflater.needsDictionary()) { break; } // Just calling inflater.needsInput() doesn't work as expected, apparently it doesn't uphold it's own // contract and could have needsInput() == true if numDecompressedBytes != 0 and that just means that // there is not enough space in the result array - else if ( numDecompressedBytes == 0 && inflater.needsInput() ) - { + else if (numDecompressedBytes == 0 && inflater.needsInput()) { throw new ZipException("Corrupt GZipped data"); } // Inflater's contract doesn't say whether it's able to be finished() without returning 0 from inflate() // call, so the additional `numDecompressedBytes == 0` condition ensures that we did another cycle and // definitely need to inflate some more bytes. - if ( result.length == MAX_SAFE_JAVA_BYTE_ARRAY_SIZE && numDecompressedBytes == 0 ) - { + if (result.length == MAX_SAFE_JAVA_BYTE_ARRAY_SIZE && numDecompressedBytes == 0) { throw new OutOfMemoryError("Unable to uncompress that much data into a single byte[] array"); } int newResultLength = (int) Math.min((long) result.length + (result.length / 2), MAX_SAFE_JAVA_BYTE_ARRAY_SIZE); - if ( result.length != newResultLength ) - { + if (result.length != newResultLength) { result = Arrays.copyOf(result, newResultLength); } } - if ( inflater.getRemaining() != 0 ) - { + if (inflater.getRemaining() != 0) { throw new ZipException("Expected just one GZip block, without garbage in the end"); } int checksum = gzippedData.getInt(gzippedDataBytes.length - GZIP_TRAILER_SIZE); int numUncompressedBytes = gzippedData.getInt(gzippedDataBytes.length - Integer.BYTES); - if ( checksum != (int) crc.getValue() || numUncompressedBytes != offset ) - { + if (checksum != (int) crc.getValue() || numUncompressedBytes != offset) { throw new ZipException("Corrupt GZIP trailer"); } - if ( result.length != offset ) - { + if (result.length != offset) { result = Arrays.copyOf(result, offset); } return result; @@ -281,8 +256,7 @@ else if ( numDecompressedBytes == 0 && inflater.needsInput() ) /** * Returns the header size */ - private static int readGzipHeader(ByteBuffer gzippedData) throws IOException - { + private static int readGzipHeader(ByteBuffer gzippedData) throws IOException { try { return doReadHeader(gzippedData); } catch (BufferUnderflowException e) { @@ -291,44 +265,36 @@ private static int readGzipHeader(ByteBuffer gzippedData) throws IOException } private static int doReadHeader(ByteBuffer gzippedData) throws IOException { - if ( gzippedData.getChar() != GZIP_MAGIC ) - { + if (gzippedData.getChar() != GZIP_MAGIC) { throw new ZipException("Not in GZip format"); } - if ( gzippedData.get() != Deflater.DEFLATED ) - { + if (gzippedData.get() != Deflater.DEFLATED) { throw new ZipException("Unsupported compression method"); } int flags = gzippedData.get(); // Skip MTIME, XFL, and OS fields skip(gzippedData, Integer.BYTES + Byte.BYTES + Byte.BYTES); - if ( (flags & FEXTRA) != 0 ) - { + if ((flags & FEXTRA) != 0) { int extraBytes = gzippedData.getChar(); skip(gzippedData, extraBytes); } - if ( (flags & FNAME) != 0 ) - { + if ((flags & FNAME) != 0) { skipZeroTerminatedString(gzippedData); } - if ( (flags & FCOMMENT) != 0 ) - { + if ((flags & FCOMMENT) != 0) { skipZeroTerminatedString(gzippedData); } - if ( (flags & FHCRC) != 0 ) - { + if ((flags & FHCRC) != 0) { CRC32 crc = new CRC32(); crc.update(gzippedData.array(), 0, gzippedData.position()); - if ( gzippedData.getChar() != (char) crc.getValue() ) - { + if (gzippedData.getChar() != (char) crc.getValue()) { throw new ZipException("Corrupt GZIP header"); } } return gzippedData.position(); } - private static void skip(ByteBuffer gzippedData, int skipBytes) throws IOException - { + private static void skip(ByteBuffer gzippedData, int skipBytes) throws IOException { try { gzippedData.position(gzippedData.position() + skipBytes); } catch (IllegalArgumentException e) { @@ -336,8 +302,7 @@ private static void skip(ByteBuffer gzippedData, int skipBytes) throws IOExcepti } } - private static void skipZeroTerminatedString(ByteBuffer gzippedData) - { + private static void skipZeroTerminatedString(ByteBuffer gzippedData) { while (gzippedData.get() != 0) { // loop } diff --git a/curator-framework/src/main/java/org/apache/curator/framework/imps/IdempotentUtils.java b/curator-framework/src/main/java/org/apache/curator/framework/imps/IdempotentUtils.java index 91b57a511..a26b5da6b 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/imps/IdempotentUtils.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/imps/IdempotentUtils.java @@ -22,16 +22,14 @@ import java.util.Arrays; /* - * Utilties Class for idempotent operations. + * Utilties Class for idempotent operations. */ -class IdempotentUtils -{ +class IdempotentUtils { /** - * Returns whether the version and data currently in the node match what would be expected in the idempotent retry case. + * Returns whether the version and data currently in the node match what would be expected in the idempotent retry case. */ - static boolean matches(int expectedVersion, byte[] expectedData, int actualVersion, byte[] actualData) - { + static boolean matches(int expectedVersion, byte[] expectedData, int actualVersion, byte[] actualData) { return expectedVersion == actualVersion && Arrays.equals(expectedData, actualData); } } diff --git a/curator-framework/src/main/java/org/apache/curator/framework/imps/InternalConnectionHandler.java b/curator-framework/src/main/java/org/apache/curator/framework/imps/InternalConnectionHandler.java index 206c5db77..9b4ab4b77 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/imps/InternalConnectionHandler.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/imps/InternalConnectionHandler.java @@ -19,8 +19,7 @@ package org.apache.curator.framework.imps; -interface InternalConnectionHandler -{ +interface InternalConnectionHandler { void checkNewConnection(CuratorFrameworkImpl client); void suspendConnection(CuratorFrameworkImpl client); diff --git a/curator-framework/src/main/java/org/apache/curator/framework/imps/NamespaceFacade.java b/curator-framework/src/main/java/org/apache/curator/framework/imps/NamespaceFacade.java index a0508b1c8..1887a86b7 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/imps/NamespaceFacade.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/imps/NamespaceFacade.java @@ -30,130 +30,110 @@ import org.apache.curator.utils.EnsurePath; import org.apache.zookeeper.ZooKeeper; -class NamespaceFacade extends CuratorFrameworkImpl -{ +class NamespaceFacade extends CuratorFrameworkImpl { private final CuratorFrameworkImpl client; private final NamespaceImpl namespace; private final FailedDeleteManager failedDeleteManager = new FailedDeleteManager(this); - NamespaceFacade(CuratorFrameworkImpl client, String namespace) - { + NamespaceFacade(CuratorFrameworkImpl client, String namespace) { super(client); this.client = client; this.namespace = new NamespaceImpl(client, namespace); } @Override - public CuratorFramework nonNamespaceView() - { + public CuratorFramework nonNamespaceView() { return usingNamespace(null); } @Override - public CuratorFramework usingNamespace(String newNamespace) - { + public CuratorFramework usingNamespace(String newNamespace) { return client.getNamespaceFacadeCache().get(newNamespace); } @Override - public String getNamespace() - { + public String getNamespace() { return namespace.getNamespace(); } @Override - public void start() - { + public void start() { throw new UnsupportedOperationException(); } @Override - public void close() - { + public void close() { throw new UnsupportedOperationException(); } @Override - public Listenable getConnectionStateListenable() - { + public Listenable getConnectionStateListenable() { return client.getConnectionStateListenable(); } @Override - public Listenable getCuratorListenable() - { - throw new UnsupportedOperationException("getCuratorListenable() is only available from a non-namespaced CuratorFramework instance"); + public Listenable getCuratorListenable() { + throw new UnsupportedOperationException( + "getCuratorListenable() is only available from a non-namespaced CuratorFramework instance"); } @Override - public Listenable getUnhandledErrorListenable() - { + public Listenable getUnhandledErrorListenable() { return client.getUnhandledErrorListenable(); } @Override - public void sync(String path, Object context) - { + public void sync(String path, Object context) { internalSync(this, path, context); } @Override - public CuratorZookeeperClient getZookeeperClient() - { + public CuratorZookeeperClient getZookeeperClient() { return client.getZookeeperClient(); } @Override - RetryLoop newRetryLoop() - { + RetryLoop newRetryLoop() { return client.newRetryLoop(); } @Override - ZooKeeper getZooKeeper() throws Exception - { + ZooKeeper getZooKeeper() throws Exception { return client.getZooKeeper(); } @Override - void processBackgroundOperation(OperationAndData operationAndData, CuratorEvent event) - { + void processBackgroundOperation(OperationAndData operationAndData, CuratorEvent event) { client.processBackgroundOperation(operationAndData, event); } @Override - void logError(String reason, Throwable e) - { + void logError(String reason, Throwable e) { client.logError(reason, e); } @Override - String unfixForNamespace(String path) - { + String unfixForNamespace(String path) { return namespace.unfixForNamespace(path); } @Override - String fixForNamespace(String path) - { + String fixForNamespace(String path) { return namespace.fixForNamespace(path, false); } @Override - String fixForNamespace(String path, boolean isSequential) - { + String fixForNamespace(String path, boolean isSequential) { return namespace.fixForNamespace(path, isSequential); } @Override - public EnsurePath newNamespaceAwareEnsurePath(String path) - { + public EnsurePath newNamespaceAwareEnsurePath(String path) { return namespace.newNamespaceAwareEnsurePath(path); } @Override - FailedDeleteManager getFailedDeleteManager() - { + FailedDeleteManager getFailedDeleteManager() { return failedDeleteManager; } } diff --git a/curator-framework/src/main/java/org/apache/curator/framework/imps/NamespaceFacadeCache.java b/curator-framework/src/main/java/org/apache/curator/framework/imps/NamespaceFacadeCache.java index 33e0c33aa..80b07149b 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/imps/NamespaceFacadeCache.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/imps/NamespaceFacadeCache.java @@ -25,37 +25,29 @@ import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; -class NamespaceFacadeCache -{ - private final CuratorFrameworkImpl client; - private final NamespaceFacade nullNamespace; - private final CacheLoader loader = new CacheLoader() - { +class NamespaceFacadeCache { + private final CuratorFrameworkImpl client; + private final NamespaceFacade nullNamespace; + private final CacheLoader loader = new CacheLoader() { @Override - public NamespaceFacade load(String namespace) throws Exception - { + public NamespaceFacade load(String namespace) throws Exception { return new NamespaceFacade(client, namespace); } }; private final LoadingCache cache = CacheBuilder.newBuilder() - .expireAfterAccess(5, TimeUnit.MINUTES) // does this need config? probably not - .build(loader); + .expireAfterAccess(5, TimeUnit.MINUTES) // does this need config? probably not + .build(loader); - NamespaceFacadeCache(CuratorFrameworkImpl client) - { + NamespaceFacadeCache(CuratorFrameworkImpl client) { this.client = client; nullNamespace = new NamespaceFacade(client, null); } - NamespaceFacade get(String namespace) - { - try - { + NamespaceFacade get(String namespace) { + try { return (namespace != null) ? cache.get(namespace) : nullNamespace; - } - catch ( ExecutionException e ) - { - throw new RuntimeException(e); // should never happen + } catch (ExecutionException e) { + throw new RuntimeException(e); // should never happen } } } diff --git a/curator-framework/src/main/java/org/apache/curator/framework/imps/NamespaceImpl.java b/curator-framework/src/main/java/org/apache/curator/framework/imps/NamespaceImpl.java index 07b5d8f91..7e4d53e92 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/imps/NamespaceImpl.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/imps/NamespaceImpl.java @@ -19,33 +19,25 @@ package org.apache.curator.framework.imps; +import java.util.concurrent.Callable; +import java.util.concurrent.atomic.AtomicBoolean; import org.apache.curator.CuratorZookeeperClient; import org.apache.curator.RetryLoop; -import org.apache.curator.framework.CuratorFramework; import org.apache.curator.utils.EnsurePath; import org.apache.curator.utils.PathUtils; import org.apache.curator.utils.ThreadUtils; import org.apache.curator.utils.ZKPaths; -import org.apache.zookeeper.ZooDefs; -import java.util.concurrent.Callable; -import java.util.concurrent.atomic.AtomicBoolean; -class NamespaceImpl -{ +class NamespaceImpl { private final CuratorFrameworkImpl client; private final String namespace; private final AtomicBoolean ensurePathNeeded; - NamespaceImpl(CuratorFrameworkImpl client, String namespace) - { - if ( namespace != null ) - { - try - { + NamespaceImpl(CuratorFrameworkImpl client, String namespace) { + if (namespace != null) { + try { PathUtils.validatePath("/" + namespace); - } - catch ( IllegalArgumentException e ) - { + } catch (IllegalArgumentException e) { throw new IllegalArgumentException("Invalid namespace: " + namespace + ", " + e.getMessage()); } } @@ -55,48 +47,38 @@ class NamespaceImpl ensurePathNeeded = new AtomicBoolean(namespace != null); } - String getNamespace() - { + String getNamespace() { return namespace; } - String unfixForNamespace(String path) - { - if ( (namespace != null) && (path != null) ) - { - String namespacePath = ZKPaths.makePath(namespace, null); - if ( !namespacePath.equals("/") && path.startsWith(namespacePath) ) - { + String unfixForNamespace(String path) { + if ((namespace != null) && (path != null)) { + String namespacePath = ZKPaths.makePath(namespace, null); + if (!namespacePath.equals("/") && path.startsWith(namespacePath)) { path = (path.length() > namespacePath.length()) ? path.substring(namespacePath.length()) : "/"; } } return path; } - String fixForNamespace(String path, boolean isSequential) - { - if ( ensurePathNeeded.get() ) - { - try - { + String fixForNamespace(String path, boolean isSequential) { + if (ensurePathNeeded.get()) { + try { final CuratorZookeeperClient zookeeperClient = client.getZookeeperClient(); - RetryLoop.callWithRetry - ( - zookeeperClient, - new Callable() - { - @Override - public Object call() throws Exception - { - ZKPaths.mkdirs(zookeeperClient.getZooKeeper(), ZKPaths.makePath("/", namespace), true, client.getAclProvider(), true); - return null; - } + RetryLoop.callWithRetry(zookeeperClient, new Callable() { + @Override + public Object call() throws Exception { + ZKPaths.mkdirs( + zookeeperClient.getZooKeeper(), + ZKPaths.makePath("/", namespace), + true, + client.getAclProvider(), + true); + return null; } - ); + }); ensurePathNeeded.set(false); - } - catch ( Exception e ) - { + } catch (Exception e) { ThreadUtils.checkInterrupted(e); client.logError("Ensure path threw exception", e); } @@ -105,8 +87,7 @@ public Object call() throws Exception return ZKPaths.fixForNamespace(namespace, path, isSequential); } - EnsurePath newNamespaceAwareEnsurePath(String path) - { + EnsurePath newNamespaceAwareEnsurePath(String path) { return new EnsurePath(fixForNamespace(path, false), client.getAclProvider()); } } diff --git a/curator-framework/src/main/java/org/apache/curator/framework/imps/NamespaceWatchedEvent.java b/curator-framework/src/main/java/org/apache/curator/framework/imps/NamespaceWatchedEvent.java index 981b6977c..4bff03f35 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/imps/NamespaceWatchedEvent.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/imps/NamespaceWatchedEvent.java @@ -21,10 +21,8 @@ import org.apache.zookeeper.WatchedEvent; -class NamespaceWatchedEvent extends WatchedEvent -{ - NamespaceWatchedEvent(CuratorFrameworkImpl client, WatchedEvent event) - { +class NamespaceWatchedEvent extends WatchedEvent { + NamespaceWatchedEvent(CuratorFrameworkImpl client, WatchedEvent event) { super(event.getType(), event.getState(), client.unfixForNamespace(event.getPath())); } } diff --git a/curator-framework/src/main/java/org/apache/curator/framework/imps/NamespaceWatcher.java b/curator-framework/src/main/java/org/apache/curator/framework/imps/NamespaceWatcher.java index 851d5a0e6..c3f0d8e29 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/imps/NamespaceWatcher.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/imps/NamespaceWatcher.java @@ -21,70 +21,56 @@ import com.google.common.base.Objects; import com.google.common.base.Preconditions; +import java.io.Closeable; import org.apache.curator.framework.api.CuratorWatcher; import org.apache.curator.utils.ThreadUtils; import org.apache.zookeeper.WatchedEvent; import org.apache.zookeeper.Watcher; -import java.io.Closeable; -class NamespaceWatcher implements Watcher, Closeable -{ +class NamespaceWatcher implements Watcher, Closeable { private volatile CuratorFrameworkImpl client; private volatile Watcher actualWatcher; private final String unfixedPath; private volatile CuratorWatcher curatorWatcher; - NamespaceWatcher(CuratorFrameworkImpl client, Watcher actualWatcher, String unfixedPath) - { + NamespaceWatcher(CuratorFrameworkImpl client, Watcher actualWatcher, String unfixedPath) { this.client = client; this.actualWatcher = actualWatcher; this.unfixedPath = Preconditions.checkNotNull(unfixedPath, "unfixedPath cannot be null"); this.curatorWatcher = null; } - NamespaceWatcher(CuratorFrameworkImpl client, CuratorWatcher curatorWatcher, String unfixedPath) - { + NamespaceWatcher(CuratorFrameworkImpl client, CuratorWatcher curatorWatcher, String unfixedPath) { this.client = client; this.actualWatcher = null; this.curatorWatcher = curatorWatcher; this.unfixedPath = Preconditions.checkNotNull(unfixedPath, "unfixedPath cannot be null"); } - String getUnfixedPath() - { + String getUnfixedPath() { return unfixedPath; } @Override - public void close() - { + public void close() { client = null; actualWatcher = null; curatorWatcher = null; } @Override - public void process(WatchedEvent event) - { - if ( client != null ) - { - if ( (event.getType() != Event.EventType.None) && (client.getWatcherRemovalManager() != null) ) - { + public void process(WatchedEvent event) { + if (client != null) { + if ((event.getType() != Event.EventType.None) && (client.getWatcherRemovalManager() != null)) { client.getWatcherRemovalManager().noteTriggeredWatcher(this); } - if ( actualWatcher != null ) - { + if (actualWatcher != null) { actualWatcher.process(new NamespaceWatchedEvent(client, event)); - } - else if ( curatorWatcher != null ) - { - try - { + } else if (curatorWatcher != null) { + try { curatorWatcher.process(new NamespaceWatchedEvent(client, event)); - } - catch ( Exception e ) - { + } catch (Exception e) { ThreadUtils.checkInterrupted(e); client.logError("Watcher exception", e); } @@ -96,31 +82,26 @@ else if ( curatorWatcher != null ) * NamespaceWatcher should equal other wrappers that wrap the same instance. */ @Override - public boolean equals(Object o) - { - if ( this == o ) - { + public boolean equals(Object o) { + if (this == o) { return true; } - if ( o == null ) - { + if (o == null) { return false; } - if ( getClass() == o.getClass() ) - { - NamespaceWatcher watcher = (NamespaceWatcher)o; + if (getClass() == o.getClass()) { + NamespaceWatcher watcher = (NamespaceWatcher) o; return Objects.equal(unfixedPath, watcher.getUnfixedPath()) - && Objects.equal(actualWatcher, watcher.actualWatcher) - && Objects.equal(curatorWatcher, watcher.curatorWatcher); + && Objects.equal(actualWatcher, watcher.actualWatcher) + && Objects.equal(curatorWatcher, watcher.curatorWatcher); } return false; } @Override - public int hashCode() - { + public int hashCode() { return Objects.hashCode(actualWatcher, unfixedPath, curatorWatcher); } } diff --git a/curator-framework/src/main/java/org/apache/curator/framework/imps/OperationAndData.java b/curator-framework/src/main/java/org/apache/curator/framework/imps/OperationAndData.java index 88258f407..14a08312a 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/imps/OperationAndData.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/imps/OperationAndData.java @@ -20,15 +20,14 @@ package org.apache.curator.framework.imps; import com.google.common.annotations.VisibleForTesting; -import org.apache.curator.RetrySleeper; -import org.apache.curator.framework.api.BackgroundCallback; import java.util.concurrent.Delayed; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; +import org.apache.curator.RetrySleeper; +import org.apache.curator.framework.api.BackgroundCallback; -class OperationAndData implements Delayed, RetrySleeper -{ +class OperationAndData implements Delayed, RetrySleeper { private static final AtomicLong nextOrdinal = new AtomicLong(); private final BackgroundOperation operation; @@ -42,13 +41,17 @@ class OperationAndData implements Delayed, RetrySleeper private final Object context; private final boolean connectionRequired; - interface ErrorCallback - { + interface ErrorCallback { void retriesExhausted(OperationAndData operationAndData); } - - OperationAndData(BackgroundOperation operation, T data, BackgroundCallback callback, ErrorCallback errorCallback, Object context, boolean connectionRequired) - { + + OperationAndData( + BackgroundOperation operation, + T data, + BackgroundCallback callback, + ErrorCallback errorCallback, + Object context, + boolean connectionRequired) { this.operation = operation; this.data = data; this.callback = callback; @@ -58,94 +61,82 @@ interface ErrorCallback reset(); } - void reset() - { + void reset() { retryCount.set(0); ordinal.set(nextOrdinal.getAndIncrement()); } - OperationAndData(BackgroundOperation operation, T data, BackgroundCallback callback, ErrorCallback errorCallback, Object context, Watching watching) - { + OperationAndData( + BackgroundOperation operation, + T data, + BackgroundCallback callback, + ErrorCallback errorCallback, + Object context, + Watching watching) { this(operation, data, callback, errorCallback, context, true); } - Object getContext() - { + Object getContext() { return context; } - - boolean isConnectionRequired() - { + + boolean isConnectionRequired() { return connectionRequired; } - void callPerformBackgroundOperation() throws Exception - { + void callPerformBackgroundOperation() throws Exception { operation.performBackgroundOperation(this); } - T getData() - { + T getData() { return data; } - long getElapsedTimeMs() - { + long getElapsedTimeMs() { return System.currentTimeMillis() - startTimeMs; } - int getThenIncrementRetryCount() - { + int getThenIncrementRetryCount() { return retryCount.getAndIncrement(); } - BackgroundCallback getCallback() - { + BackgroundCallback getCallback() { return callback; } - ErrorCallback getErrorCallback() - { + ErrorCallback getErrorCallback() { return errorCallback; } @VisibleForTesting - BackgroundOperation getOperation() - { + BackgroundOperation getOperation() { return operation; } - void clearSleep() - { + void clearSleep() { sleepUntilTimeMs.set(0); } @Override - public void sleepFor(long time, TimeUnit unit) throws InterruptedException - { + public void sleepFor(long time, TimeUnit unit) throws InterruptedException { sleepUntilTimeMs.set(System.currentTimeMillis() + TimeUnit.MILLISECONDS.convert(time, unit)); } @Override - public long getDelay(TimeUnit unit) - { + public long getDelay(TimeUnit unit) { return unit.convert(sleepUntilTimeMs.get() - System.currentTimeMillis(), TimeUnit.MILLISECONDS); } @Override - public int compareTo(Delayed o) - { - if ( o == this ) - { + public int compareTo(Delayed o) { + if (o == this) { return 0; } long diff = getDelay(TimeUnit.MILLISECONDS) - o.getDelay(TimeUnit.MILLISECONDS); - if ( diff == 0 ) - { - if ( o instanceof OperationAndData ) - { - diff = ordinal.get() - ((OperationAndData)o).ordinal.get(); + if (diff == 0) { + if (o instanceof OperationAndData) { + diff = ordinal.get() - ((OperationAndData) o).ordinal.get(); } } diff --git a/curator-framework/src/main/java/org/apache/curator/framework/imps/PathAndBytes.java b/curator-framework/src/main/java/org/apache/curator/framework/imps/PathAndBytes.java index 682602b8a..bd29341c5 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/imps/PathAndBytes.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/imps/PathAndBytes.java @@ -19,24 +19,20 @@ package org.apache.curator.framework.imps; -class PathAndBytes -{ - private final String path; - private final byte[] data; +class PathAndBytes { + private final String path; + private final byte[] data; - PathAndBytes(String path, byte[] data) - { + PathAndBytes(String path, byte[] data) { this.path = path; this.data = data; } - String getPath() - { + String getPath() { return path; } - byte[] getData() - { + byte[] getData() { return data; } } diff --git a/curator-framework/src/main/java/org/apache/curator/framework/imps/ProtectedMode.java b/curator-framework/src/main/java/org/apache/curator/framework/imps/ProtectedMode.java index 83528031f..08a006bfa 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/imps/ProtectedMode.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/imps/ProtectedMode.java @@ -19,16 +19,15 @@ package org.apache.curator.framework.imps; +import java.util.UUID; import org.apache.zookeeper.CreateMode; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.util.UUID; /** * manage the protected mode state for {@link org.apache.curator.framework.imps.CreateBuilderImpl} */ -class ProtectedMode -{ +class ProtectedMode { private final Logger log = LoggerFactory.getLogger(getClass()); private volatile String protectedId = null; private volatile long sessionId = 0; @@ -36,32 +35,28 @@ class ProtectedMode /** * Enable protected mode */ - void setProtectedMode() - { + void setProtectedMode() { resetProtectedId(); } /** * Update the protected mode ID */ - void resetProtectedId() - { + void resetProtectedId() { protectedId = UUID.randomUUID().toString(); } /** * @return true if protected mode has been enabled */ - boolean doProtected() - { + boolean doProtected() { return (protectedId != null); } /** * @return the protected mode ID if protected mode is enabled */ - String protectedId() - { + String protectedId() { return protectedId; } @@ -72,10 +67,8 @@ String protectedId() * @param createMode create mode in use * @throws Exception errors */ - void checkSetSessionId(CuratorFrameworkImpl client, CreateMode createMode) throws Exception - { - if ( doProtected() && (sessionId == 0) && createMode.isEphemeral() ) - { + void checkSetSessionId(CuratorFrameworkImpl client, CreateMode createMode) throws Exception { + if (doProtected() && (sessionId == 0) && createMode.isEphemeral()) { sessionId = client.getZooKeeper().getSessionId(); } } @@ -89,16 +82,15 @@ void checkSetSessionId(CuratorFrameworkImpl client, CreateMode createMode) throw * @return either the found node or null - client should always use the returned value * @throws Exception errors */ - String validateFoundNode(CuratorFrameworkImpl client, CreateMode createMode, String foundNode) throws Exception - { - if ( doProtected() && createMode.isEphemeral() ) - { + String validateFoundNode(CuratorFrameworkImpl client, CreateMode createMode, String foundNode) throws Exception { + if (doProtected() && createMode.isEphemeral()) { long clientSessionId = client.getZooKeeper().getSessionId(); - if ( this.sessionId != clientSessionId ) - { - log.info("Session has changed during protected mode with ephemeral. old: {} new: {}", this.sessionId, clientSessionId); - if ( foundNode != null ) - { + if (this.sessionId != clientSessionId) { + log.info( + "Session has changed during protected mode with ephemeral. old: {} new: {}", + this.sessionId, + clientSessionId); + if (foundNode != null) { log.info("Deleted old session's found node: {}", foundNode); client.getFailedDeleteManager().executeGuaranteedOperationInBackground(foundNode); foundNode = null; diff --git a/curator-framework/src/main/java/org/apache/curator/framework/imps/ProtectedUtils.java b/curator-framework/src/main/java/org/apache/curator/framework/imps/ProtectedUtils.java index d5e44f99b..3c625a44c 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/imps/ProtectedUtils.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/imps/ProtectedUtils.java @@ -20,19 +20,17 @@ package org.apache.curator.framework.imps; import com.google.common.annotations.VisibleForTesting; -import org.apache.curator.framework.api.CreateBuilderMain; -import org.apache.curator.utils.ZKPaths; import java.util.Optional; import java.util.UUID; +import org.apache.curator.framework.api.CreateBuilderMain; +import org.apache.curator.utils.ZKPaths; /** * Utility class to handle ZNode names when using {@link CreateBuilderMain#withProtection()} */ -public final class ProtectedUtils -{ +public final class ProtectedUtils { - private ProtectedUtils() - { + private ProtectedUtils() { throw new RuntimeException("Protected Utils is a helper class"); } @@ -52,8 +50,9 @@ private ProtectedUtils() * Prefix length on ZNode name when using {@link CreateBuilderMain#withProtection()} */ @VisibleForTesting - static final int PROTECTED_PREFIX_WITH_UUID_LENGTH = PROTECTED_PREFIX.length() + 36 // UUID canonical text representation produced by {@link UUID#toString()} - + 1; // Separator length + static final int PROTECTED_PREFIX_WITH_UUID_LENGTH = PROTECTED_PREFIX.length() + + 36 // UUID canonical text representation produced by {@link UUID#toString()} + + 1; // Separator length /** * Provides a prefix to be prepended to a ZNode name when protected. The method assumes that the provided string @@ -62,14 +61,12 @@ private ProtectedUtils() * @param protectedId canonical text representation of a UUID * @return string that concatenates {@value #PROTECTED_PREFIX}, the given id and {@value #PROTECTED_SEPARATOR} */ - public static String getProtectedPrefix(final String protectedId) - { + public static String getProtectedPrefix(final String protectedId) { return PROTECTED_PREFIX + protectedId + PROTECTED_SEPARATOR; } /** Extracts protectedId assuming provided name has a valid protected format */ - private static String extractProtectedIdInternal(final String znodeName) - { + private static String extractProtectedIdInternal(final String znodeName) { return znodeName.substring(PROTECTED_PREFIX.length(), PROTECTED_PREFIX_WITH_UUID_LENGTH - 1); } @@ -79,18 +76,15 @@ private static String extractProtectedIdInternal(final String znodeName) * @param znodeName ZNode name * @return {@code true} if the given ZNode name starts with Curator's generated protected prefix */ - public static boolean isProtectedZNode(final String znodeName) - { - if ( znodeName.length() > PROTECTED_PREFIX_WITH_UUID_LENGTH && znodeName.startsWith(PROTECTED_PREFIX) && znodeName.charAt(PROTECTED_PREFIX_WITH_UUID_LENGTH - 1) == PROTECTED_SEPARATOR ) - { - try - { + public static boolean isProtectedZNode(final String znodeName) { + if (znodeName.length() > PROTECTED_PREFIX_WITH_UUID_LENGTH + && znodeName.startsWith(PROTECTED_PREFIX) + && znodeName.charAt(PROTECTED_PREFIX_WITH_UUID_LENGTH - 1) == PROTECTED_SEPARATOR) { + try { //noinspection ResultOfMethodCallIgnored UUID.fromString(extractProtectedIdInternal(znodeName)); return true; - } - catch ( IllegalArgumentException e ) - { + } catch (IllegalArgumentException e) { // Not an UUID } } @@ -103,8 +97,7 @@ public static boolean isProtectedZNode(final String znodeName) * @param znodeName ZNode name * @return string without Curator's generated protected prefix if present; original string if prefix not present */ - public static String normalize(final String znodeName) - { + public static String normalize(final String znodeName) { return isProtectedZNode(znodeName) ? znodeName.substring(PROTECTED_PREFIX_WITH_UUID_LENGTH) : znodeName; } @@ -114,8 +107,7 @@ public static String normalize(final String znodeName) * @param path ZNode path * @return string without Curator's generated protected prefix if present in ZNode name; original string if prefix not present */ - public static String normalizePath(final String path) - { + public static String normalizePath(final String path) { final ZKPaths.PathAndNode pathAndNode = ZKPaths.getPathAndNode(path); final String name = pathAndNode.getNode(); return isProtectedZNode(name) ? ZKPaths.makePath(pathAndNode.getPath(), normalize(name)) : path; @@ -127,8 +119,7 @@ public static String normalizePath(final String path) * @param znodeName name of the ZNode * @return Optional with protectedId if the name is protected or {@code Optional#empty()} */ - public static Optional extractProtectedId(final String znodeName) - { + public static Optional extractProtectedId(final String znodeName) { return Optional.ofNullable(isProtectedZNode(znodeName) ? extractProtectedIdInternal(znodeName) : null); } @@ -136,12 +127,11 @@ public static Optional extractProtectedId(final String znodeName) * Converts a given ZNode name to protected format * * @param znodeName name to be converted (e.g. 'name1') - * @param protectedId UUID canonical text representation used in protection mode (e.g. '53345f98-9423-4e0c-a7b5-9f819e3ec2e1') + * @param protectedId UUID canonical text representation used in protection mode (e.g. '53345f98-9423-4e0c-a7b5-9f819e3ec2e1') * @return name with protected mode prefix (e.g. '_c_53345f98-9423-4e0c-a7b5-9f819e3ec2e1-name1') * or the same name if protectedId is {@code null} */ - public static String toProtectedZNode(final String znodeName, final String protectedId) - { + public static String toProtectedZNode(final String znodeName, final String protectedId) { return (protectedId == null) ? znodeName : getProtectedPrefix(protectedId) + znodeName; } @@ -149,14 +139,12 @@ public static String toProtectedZNode(final String znodeName, final String prote * Converts a given path to protected format * * @param path complete path to be converted (e.g. '/root/path1') - * @param protectedId UUID canonical text representation used in protection mode (e.g. '53345f98-9423-4e0c-a7b5-9f819e3ec2e1') + * @param protectedId UUID canonical text representation used in protection mode (e.g. '53345f98-9423-4e0c-a7b5-9f819e3ec2e1') * @return path with protected mode prefix (e.g. '/root/_c_53345f98-9423-4e0c-a7b5-9f819e3ec2e1-path1') * or the same path if protectedId is {@code null} */ - public static String toProtectedZNodePath(final String path, final String protectedId) - { - if ( protectedId == null ) - { + public static String toProtectedZNodePath(final String path, final String protectedId) { + if (protectedId == null) { return path; } final ZKPaths.PathAndNode pathAndNode = ZKPaths.getPathAndNode(path); diff --git a/curator-framework/src/main/java/org/apache/curator/framework/imps/ReconfigBuilderImpl.java b/curator-framework/src/main/java/org/apache/curator/framework/imps/ReconfigBuilderImpl.java index af5a9a43b..f30397d5d 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/imps/ReconfigBuilderImpl.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/imps/ReconfigBuilderImpl.java @@ -20,6 +20,10 @@ package org.apache.curator.framework.imps; import com.google.common.collect.ImmutableList; +import java.util.Arrays; +import java.util.List; +import java.util.concurrent.Callable; +import java.util.concurrent.Executor; import org.apache.curator.RetryLoop; import org.apache.curator.TimeTrace; import org.apache.curator.framework.api.*; @@ -27,13 +31,9 @@ import org.apache.zookeeper.admin.ZooKeeperAdmin; import org.apache.zookeeper.data.Stat; import org.apache.zookeeper.server.DataTree; -import java.util.Arrays; -import java.util.List; -import java.util.concurrent.Callable; -import java.util.concurrent.Executor; -public class ReconfigBuilderImpl implements ReconfigBuilder, BackgroundOperation, ErrorListenerReconfigBuilderMain -{ +public class ReconfigBuilderImpl + implements ReconfigBuilder, BackgroundOperation, ErrorListenerReconfigBuilderMain { private final CuratorFrameworkImpl client; private Backgrounding backgrounding = new Backgrounding(); @@ -43,13 +43,18 @@ public class ReconfigBuilderImpl implements ReconfigBuilder, BackgroundOperation private List joining; private List leaving; - public ReconfigBuilderImpl(CuratorFrameworkImpl client) - { + public ReconfigBuilderImpl(CuratorFrameworkImpl client) { this.client = client; } - public ReconfigBuilderImpl(CuratorFrameworkImpl client, Backgrounding backgrounding, Stat responseStat, long fromConfig, List newMembers, List joining, List leaving) - { + public ReconfigBuilderImpl( + CuratorFrameworkImpl client, + Backgrounding backgrounding, + Stat responseStat, + long fromConfig, + List newMembers, + List joining, + List leaving) { this.client = client; this.backgrounding = backgrounding; this.responseStat = responseStat; @@ -59,96 +64,83 @@ public ReconfigBuilderImpl(CuratorFrameworkImpl client, Backgrounding background this.leaving = leaving; } - public byte[] forEnsemble() throws Exception - { - if ( backgrounding.inBackground() ) - { - client.processBackgroundOperation(new OperationAndData<>(this, null, backgrounding.getCallback(), null, backgrounding.getContext(), null), null); + public byte[] forEnsemble() throws Exception { + if (backgrounding.inBackground()) { + client.processBackgroundOperation( + new OperationAndData<>( + this, null, backgrounding.getCallback(), null, backgrounding.getContext(), null), + null); return new byte[0]; - } - else - { + } else { return ensembleInForeground(); } } @Override - public ErrorListenerReconfigBuilderMain inBackground() - { + public ErrorListenerReconfigBuilderMain inBackground() { backgrounding = new Backgrounding(true); return this; } @Override - public ErrorListenerReconfigBuilderMain inBackground(Object context) - { + public ErrorListenerReconfigBuilderMain inBackground(Object context) { backgrounding = new Backgrounding(context); return this; } @Override - public ErrorListenerReconfigBuilderMain inBackground(BackgroundCallback callback) - { + public ErrorListenerReconfigBuilderMain inBackground(BackgroundCallback callback) { backgrounding = new Backgrounding(callback); return this; } @Override - public ErrorListenerReconfigBuilderMain inBackground(BackgroundCallback callback, Object context) - { + public ErrorListenerReconfigBuilderMain inBackground(BackgroundCallback callback, Object context) { backgrounding = new Backgrounding(callback, context); return this; } @Override - public ErrorListenerReconfigBuilderMain inBackground(BackgroundCallback callback, Executor executor) - { + public ErrorListenerReconfigBuilderMain inBackground(BackgroundCallback callback, Executor executor) { backgrounding = new Backgrounding(callback, executor); return this; } @Override - public ErrorListenerReconfigBuilderMain inBackground(BackgroundCallback callback, Object context, Executor executor) - { + public ErrorListenerReconfigBuilderMain inBackground( + BackgroundCallback callback, Object context, Executor executor) { backgrounding = new Backgrounding(client, callback, context, executor); return this; } @Override - public ReconfigBuilderMain withUnhandledErrorListener(UnhandledErrorListener listener) - { + public ReconfigBuilderMain withUnhandledErrorListener(UnhandledErrorListener listener) { backgrounding = new Backgrounding(backgrounding, listener); return this; } @Override - public StatConfigureEnsembleable withNewMembers(String... server) - { + public StatConfigureEnsembleable withNewMembers(String... server) { return withNewMembers((server != null) ? Arrays.asList(server) : null); } @Override - public StatConfigureEnsembleable withNewMembers(List servers) - { + public StatConfigureEnsembleable withNewMembers(List servers) { newMembers = (servers != null && !servers.isEmpty()) ? ImmutableList.copyOf(servers) : null; - return new StatConfigureEnsembleable() - { + return new StatConfigureEnsembleable() { @Override - public Ensembleable fromConfig(long config) throws Exception - { + public Ensembleable fromConfig(long config) throws Exception { fromConfig = config; return this; } @Override - public byte[] forEnsemble() throws Exception - { + public byte[] forEnsemble() throws Exception { return ReconfigBuilderImpl.this.forEnsemble(); } @Override - public ConfigureEnsembleable storingStatIn(Stat stat) - { + public ConfigureEnsembleable storingStatIn(Stat stat) { responseStat = stat; return this; } @@ -156,142 +148,126 @@ public ConfigureEnsembleable storingStatIn(Stat stat) } @Override - public LeaveStatConfigEnsembleable joining(String... server) - { + public LeaveStatConfigEnsembleable joining(String... server) { return joining((server != null) ? Arrays.asList(server) : null); } @Override - public LeaveStatConfigEnsembleable joining(List servers) - { + public LeaveStatConfigEnsembleable joining(List servers) { joining = (servers != null && !servers.isEmpty()) ? ImmutableList.copyOf(servers) : null; - return new LeaveStatConfigEnsembleable() - { + return new LeaveStatConfigEnsembleable() { @Override - public byte[] forEnsemble() throws Exception - { + public byte[] forEnsemble() throws Exception { return ReconfigBuilderImpl.this.forEnsemble(); } @Override - public ConfigureEnsembleable storingStatIn(Stat stat) - { + public ConfigureEnsembleable storingStatIn(Stat stat) { responseStat = stat; return this; } @Override - public Ensembleable fromConfig(long config) throws Exception - { + public Ensembleable fromConfig(long config) throws Exception { fromConfig = config; return this; } @Override - public JoinStatConfigEnsembleable leaving(String... server) - { + public JoinStatConfigEnsembleable leaving(String... server) { return ReconfigBuilderImpl.this.leaving(server); } @Override - public JoinStatConfigEnsembleable leaving(List servers) - { + public JoinStatConfigEnsembleable leaving(List servers) { return ReconfigBuilderImpl.this.leaving(servers); } }; } @Override - public JoinStatConfigEnsembleable leaving(String... server) - { + public JoinStatConfigEnsembleable leaving(String... server) { return leaving((server != null) ? Arrays.asList(server) : null); } @Override - public JoinStatConfigEnsembleable leaving(List servers) - { + public JoinStatConfigEnsembleable leaving(List servers) { leaving = (servers != null && !servers.isEmpty()) ? ImmutableList.copyOf(servers) : null; - return new JoinStatConfigEnsembleable() - { + return new JoinStatConfigEnsembleable() { @Override - public byte[] forEnsemble() throws Exception - { + public byte[] forEnsemble() throws Exception { return ReconfigBuilderImpl.this.forEnsemble(); } @Override - public ConfigureEnsembleable storingStatIn(Stat stat) - { + public ConfigureEnsembleable storingStatIn(Stat stat) { responseStat = stat; return this; } @Override - public Ensembleable fromConfig(long config) throws Exception - { + public Ensembleable fromConfig(long config) throws Exception { fromConfig = config; return this; } @Override - public LeaveStatConfigEnsembleable joining(String... server) - { + public LeaveStatConfigEnsembleable joining(String... server) { return joining((server != null) ? Arrays.asList(server) : null); } @Override - public LeaveStatConfigEnsembleable joining(List servers) - { + public LeaveStatConfigEnsembleable joining(List servers) { return ReconfigBuilderImpl.this.joining(servers); } }; } @Override - public void performBackgroundOperation(final OperationAndData data) throws Exception - { - try - { + public void performBackgroundOperation(final OperationAndData data) throws Exception { + try { final TimeTrace trace = client.getZookeeperClient().startTracer("ReconfigBuilderImpl-Background"); - AsyncCallback.DataCallback callback = new AsyncCallback.DataCallback() - { + AsyncCallback.DataCallback callback = new AsyncCallback.DataCallback() { @Override - public void processResult(int rc, String path, Object ctx, byte[] bytes, Stat stat) - { + public void processResult(int rc, String path, Object ctx, byte[] bytes, Stat stat) { trace.commit(); - if ( (responseStat != null) && (stat != null) ) - { + if ((responseStat != null) && (stat != null)) { DataTree.copyStat(stat, responseStat); } - CuratorEvent event = new CuratorEventImpl(client, CuratorEventType.RECONFIG, rc, path, null, ctx, stat, bytes, null, null, null, null); + CuratorEvent event = new CuratorEventImpl( + client, + CuratorEventType.RECONFIG, + rc, + path, + null, + ctx, + stat, + bytes, + null, + null, + null, + null); client.processBackgroundOperation(data, event); } }; - ((ZooKeeperAdmin)client.getZooKeeper()).reconfigure(joining, leaving, newMembers, fromConfig, callback, backgrounding.getContext()); - } - catch ( Throwable e ) - { + ((ZooKeeperAdmin) client.getZooKeeper()) + .reconfigure(joining, leaving, newMembers, fromConfig, callback, backgrounding.getContext()); + } catch (Throwable e) { backgrounding.checkError(e, null); } } - private byte[] ensembleInForeground() throws Exception - { + private byte[] ensembleInForeground() throws Exception { TimeTrace trace = client.getZookeeperClient().startTracer("ReconfigBuilderImpl-Foreground"); - byte[] responseData = RetryLoop.callWithRetry - ( - client.getZookeeperClient(), - new Callable() - { - @Override - public byte[] call() throws Exception - { - return ((ZooKeeperAdmin)client.getZooKeeper()).reconfigure(joining, leaving, newMembers, fromConfig, responseStat); - } - } - ); + byte[] responseData = RetryLoop.callWithRetry(client.getZookeeperClient(), new Callable() { + @Override + public byte[] call() throws Exception { + return ((ZooKeeperAdmin) client.getZooKeeper()) + .reconfigure(joining, leaving, newMembers, fromConfig, responseStat); + } + }); trace.commit(); return responseData; } diff --git a/curator-framework/src/main/java/org/apache/curator/framework/imps/RemoveWatchesBuilderImpl.java b/curator-framework/src/main/java/org/apache/curator/framework/imps/RemoveWatchesBuilderImpl.java index 0aab58227..c93f59fbe 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/imps/RemoveWatchesBuilderImpl.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/imps/RemoveWatchesBuilderImpl.java @@ -17,337 +17,306 @@ * under the License. */ -package org.apache.curator.framework.imps; - -import org.apache.curator.RetryLoop; -import org.apache.curator.TimeTrace; -import org.apache.curator.framework.api.*; -import org.apache.curator.utils.DebugUtils; -import org.apache.zookeeper.AsyncCallback; -import org.apache.zookeeper.KeeperException; -import org.apache.zookeeper.Watcher; -import org.apache.zookeeper.Watcher.WatcherType; -import org.apache.zookeeper.ZooKeeper; -import java.util.concurrent.Callable; -import java.util.concurrent.Executor; - - -public class RemoveWatchesBuilderImpl implements RemoveWatchesBuilder, RemoveWatchesType, RemoveWatchesLocal, BackgroundOperation, ErrorListenerPathable -{ - private CuratorFrameworkImpl client; - private Watcher watcher; - private CuratorWatcher curatorWatcher; - private WatcherType watcherType; - private boolean guaranteed; - private boolean local; - private boolean quietly; - private Backgrounding backgrounding; - - public RemoveWatchesBuilderImpl(CuratorFrameworkImpl client) - { - this.client = client; - this.watcher = null; - this.curatorWatcher = null; - this.watcherType = WatcherType.Any; - this.guaranteed = false; - this.local = false; - this.quietly = false; - this.backgrounding = new Backgrounding(); - } - - public RemoveWatchesBuilderImpl(CuratorFrameworkImpl client, Watcher watcher, CuratorWatcher curatorWatcher, WatcherType watcherType, boolean guaranteed, boolean local, boolean quietly, Backgrounding backgrounding) - { - this.client = client; - this.watcher = watcher; - this.curatorWatcher = curatorWatcher; - this.watcherType = watcherType; - this.guaranteed = guaranteed; - this.local = local; - this.quietly = quietly; - this.backgrounding = backgrounding; - } - - void internalRemoval(Watcher watcher, String path) throws Exception - { - this.watcher = watcher; - watcherType = WatcherType.Any; - quietly = true; - guaranteed = true; - if ( Boolean.getBoolean(DebugUtils.PROPERTY_REMOVE_WATCHERS_IN_FOREGROUND) ) - { - this.backgrounding = new Backgrounding(); - pathInForeground(path); - } - else - { - this.backgrounding = new Backgrounding(true); - pathInBackground(path); - } - } - - @Override - public RemoveWatchesType remove(Watcher watcher) - { - this.watcher = watcher; - this.curatorWatcher = null; - return this; - } - - @Override - public RemoveWatchesType remove(CuratorWatcher watcher) - { - this.watcher = null; - this.curatorWatcher = watcher; - return this; - } - - @Override - public RemoveWatchesType removeAll() - { - this.watcher = null; - this.curatorWatcher = null; - return this; - } - - @Override - public RemoveWatchesLocal ofType(WatcherType watcherType) - { - this.watcherType = watcherType; - - return this; - } - - @Override - public ErrorListenerPathable inBackground(BackgroundCallback callback, Object context) - { - backgrounding = new Backgrounding(callback, context); - return this; - } - - @Override - public ErrorListenerPathable inBackground(BackgroundCallback callback, Object context, Executor executor) - { - backgrounding = new Backgrounding(client, callback, context, executor); - return this; - } - - @Override - public ErrorListenerPathable inBackground(BackgroundCallback callback) - { - backgrounding = new Backgrounding(callback); - return this; - } - - @Override - public ErrorListenerPathable inBackground(BackgroundCallback callback, Executor executor) - { - backgrounding = new Backgrounding(client, callback, executor); - return this; - } - - @Override - public ErrorListenerPathable inBackground() - { - backgrounding = new Backgrounding(true); - return this; - } - - @Override - public ErrorListenerPathable inBackground(Object context) - { - backgrounding = new Backgrounding(context); - return this; - } - - @Override - public Pathable withUnhandledErrorListener(UnhandledErrorListener listener) - { - backgrounding = new Backgrounding(backgrounding, listener); - return this; - } - - @Override - public RemoveWatchesLocal guaranteed() - { - guaranteed = true; - return this; - } - - @Override - public BackgroundPathableQuietlyable locally() - { - local = true; - return this; - } - - @Override - public BackgroundPathable quietly() - { - quietly = true; - return this; - } - - @Override - public Void forPath(String path) throws Exception - { - final String adjustedPath = client.fixForNamespace(path); - - if(backgrounding.inBackground()) - { - pathInBackground(adjustedPath); - } - else - { - pathInForeground(adjustedPath); - } - - return null; - } - - protected CuratorFrameworkImpl getClient() - { - return client; - } - - private void pathInBackground(final String path) - { - OperationAndData.ErrorCallback errorCallback = null; - - //Only need an error callback if we're in guaranteed mode - if(guaranteed) - { - errorCallback = new OperationAndData.ErrorCallback() - { - @Override - public void retriesExhausted(OperationAndData operationAndData) - { - client.getFailedRemoveWatcherManager().addFailedOperation(new FailedRemoveWatchManager.FailedRemoveWatchDetails(path, watcher)); - } - }; - } - - client.processBackgroundOperation(new OperationAndData(this, path, backgrounding.getCallback(), - errorCallback, backgrounding.getContext(), !local), null); - } - - private void pathInForeground(final String path) throws Exception - { - NamespaceWatcher namespaceWatcher = makeNamespaceWatcher(path); - //For the local case we don't want to use the normal retry loop and we don't want to block until a connection is available. - //We just execute the removeWatch, and if it fails, ZK will just remove local watches. - if ( local ) - { - ZooKeeper zkClient = client.getZooKeeper(); - if ( namespaceWatcher != null ) - { - zkClient.removeWatches(path, namespaceWatcher, watcherType, local); - } - else - { - zkClient.removeAllWatches(path, watcherType, local); - } - } - else - { - final NamespaceWatcher finalNamespaceWatcher = namespaceWatcher; - RetryLoop.callWithRetry(client.getZookeeperClient(), - new Callable() - { - @Override - public Void call() throws Exception - { - try - { - ZooKeeper zkClient = client.getZookeeperClient().getZooKeeper(); - - if ( finalNamespaceWatcher != null ) - { - zkClient.removeWatches(path, finalNamespaceWatcher, watcherType, false); - } - else - { - zkClient.removeAllWatches(path, watcherType, false); - } - } - catch(Exception e) - { - if ( client.getZookeeperClient().getRetryPolicy().allowRetry(e) && guaranteed ) - { - //Setup the guaranteed handler - client.getFailedRemoveWatcherManager().addFailedOperation(new FailedRemoveWatchManager.FailedRemoveWatchDetails(path, finalNamespaceWatcher)); - throw e; - } - else if (e instanceof KeeperException.NoWatcherException && quietly) - { - // ignore - } - else - { - //Rethrow - throw e; - } - } - - return null; - } - }); - } - } - - private NamespaceWatcher makeNamespaceWatcher(String path) - { - NamespaceWatcher namespaceWatcher = null; - if ( watcher != null ) - { - if ( watcher instanceof NamespaceWatcher ) - { - namespaceWatcher = (NamespaceWatcher)watcher; - } - else - { - namespaceWatcher = new NamespaceWatcher(client, watcher, path); - } - } - else if ( curatorWatcher != null ) - { - namespaceWatcher = new NamespaceWatcher(client, curatorWatcher, path); - } - return namespaceWatcher; - } - - @Override - public void performBackgroundOperation(final OperationAndData operationAndData) - throws Exception - { - try - { - final TimeTrace trace = client.getZookeeperClient().startTracer("RemoteWatches-Background"); - - AsyncCallback.VoidCallback callback = new AsyncCallback.VoidCallback() - { - @Override - public void processResult(int rc, String path, Object ctx) - { - trace.commit(); - CuratorEvent event = new CuratorEventImpl(client, CuratorEventType.REMOVE_WATCHES, rc, path, null, ctx, null, null, null, null, null, null); - client.processBackgroundOperation(operationAndData, event); - } - }; - - ZooKeeper zkClient = client.getZooKeeper(); - NamespaceWatcher namespaceWatcher = makeNamespaceWatcher(operationAndData.getData()); - if(namespaceWatcher == null) - { - zkClient.removeAllWatches(operationAndData.getData(), watcherType, local, callback, operationAndData.getContext()); - } - else - { - zkClient.removeWatches(operationAndData.getData(), namespaceWatcher, watcherType, local, callback, operationAndData.getContext()); - } - } - catch ( Throwable e ) - { - backgrounding.checkError(e, null); - } - } -} +package org.apache.curator.framework.imps; + +import java.util.concurrent.Callable; +import java.util.concurrent.Executor; +import org.apache.curator.RetryLoop; +import org.apache.curator.TimeTrace; +import org.apache.curator.framework.api.*; +import org.apache.curator.utils.DebugUtils; +import org.apache.zookeeper.AsyncCallback; +import org.apache.zookeeper.KeeperException; +import org.apache.zookeeper.Watcher; +import org.apache.zookeeper.Watcher.WatcherType; +import org.apache.zookeeper.ZooKeeper; + +public class RemoveWatchesBuilderImpl + implements RemoveWatchesBuilder, + RemoveWatchesType, + RemoveWatchesLocal, + BackgroundOperation, + ErrorListenerPathable { + private CuratorFrameworkImpl client; + private Watcher watcher; + private CuratorWatcher curatorWatcher; + private WatcherType watcherType; + private boolean guaranteed; + private boolean local; + private boolean quietly; + private Backgrounding backgrounding; + + public RemoveWatchesBuilderImpl(CuratorFrameworkImpl client) { + this.client = client; + this.watcher = null; + this.curatorWatcher = null; + this.watcherType = WatcherType.Any; + this.guaranteed = false; + this.local = false; + this.quietly = false; + this.backgrounding = new Backgrounding(); + } + + public RemoveWatchesBuilderImpl( + CuratorFrameworkImpl client, + Watcher watcher, + CuratorWatcher curatorWatcher, + WatcherType watcherType, + boolean guaranteed, + boolean local, + boolean quietly, + Backgrounding backgrounding) { + this.client = client; + this.watcher = watcher; + this.curatorWatcher = curatorWatcher; + this.watcherType = watcherType; + this.guaranteed = guaranteed; + this.local = local; + this.quietly = quietly; + this.backgrounding = backgrounding; + } + + void internalRemoval(Watcher watcher, String path) throws Exception { + this.watcher = watcher; + watcherType = WatcherType.Any; + quietly = true; + guaranteed = true; + if (Boolean.getBoolean(DebugUtils.PROPERTY_REMOVE_WATCHERS_IN_FOREGROUND)) { + this.backgrounding = new Backgrounding(); + pathInForeground(path); + } else { + this.backgrounding = new Backgrounding(true); + pathInBackground(path); + } + } + + @Override + public RemoveWatchesType remove(Watcher watcher) { + this.watcher = watcher; + this.curatorWatcher = null; + return this; + } + + @Override + public RemoveWatchesType remove(CuratorWatcher watcher) { + this.watcher = null; + this.curatorWatcher = watcher; + return this; + } + + @Override + public RemoveWatchesType removeAll() { + this.watcher = null; + this.curatorWatcher = null; + return this; + } + + @Override + public RemoveWatchesLocal ofType(WatcherType watcherType) { + this.watcherType = watcherType; + + return this; + } + + @Override + public ErrorListenerPathable inBackground(BackgroundCallback callback, Object context) { + backgrounding = new Backgrounding(callback, context); + return this; + } + + @Override + public ErrorListenerPathable inBackground(BackgroundCallback callback, Object context, Executor executor) { + backgrounding = new Backgrounding(client, callback, context, executor); + return this; + } + + @Override + public ErrorListenerPathable inBackground(BackgroundCallback callback) { + backgrounding = new Backgrounding(callback); + return this; + } + + @Override + public ErrorListenerPathable inBackground(BackgroundCallback callback, Executor executor) { + backgrounding = new Backgrounding(client, callback, executor); + return this; + } + + @Override + public ErrorListenerPathable inBackground() { + backgrounding = new Backgrounding(true); + return this; + } + + @Override + public ErrorListenerPathable inBackground(Object context) { + backgrounding = new Backgrounding(context); + return this; + } + + @Override + public Pathable withUnhandledErrorListener(UnhandledErrorListener listener) { + backgrounding = new Backgrounding(backgrounding, listener); + return this; + } + + @Override + public RemoveWatchesLocal guaranteed() { + guaranteed = true; + return this; + } + + @Override + public BackgroundPathableQuietlyable locally() { + local = true; + return this; + } + + @Override + public BackgroundPathable quietly() { + quietly = true; + return this; + } + + @Override + public Void forPath(String path) throws Exception { + final String adjustedPath = client.fixForNamespace(path); + + if (backgrounding.inBackground()) { + pathInBackground(adjustedPath); + } else { + pathInForeground(adjustedPath); + } + + return null; + } + + protected CuratorFrameworkImpl getClient() { + return client; + } + + private void pathInBackground(final String path) { + OperationAndData.ErrorCallback errorCallback = null; + + // Only need an error callback if we're in guaranteed mode + if (guaranteed) { + errorCallback = new OperationAndData.ErrorCallback() { + @Override + public void retriesExhausted(OperationAndData operationAndData) { + client.getFailedRemoveWatcherManager() + .addFailedOperation(new FailedRemoveWatchManager.FailedRemoveWatchDetails(path, watcher)); + } + }; + } + + client.processBackgroundOperation( + new OperationAndData( + this, path, backgrounding.getCallback(), errorCallback, backgrounding.getContext(), !local), + null); + } + + private void pathInForeground(final String path) throws Exception { + NamespaceWatcher namespaceWatcher = makeNamespaceWatcher(path); + // For the local case we don't want to use the normal retry loop and we don't want to block until a connection + // is available. + // We just execute the removeWatch, and if it fails, ZK will just remove local watches. + if (local) { + ZooKeeper zkClient = client.getZooKeeper(); + if (namespaceWatcher != null) { + zkClient.removeWatches(path, namespaceWatcher, watcherType, local); + } else { + zkClient.removeAllWatches(path, watcherType, local); + } + } else { + final NamespaceWatcher finalNamespaceWatcher = namespaceWatcher; + RetryLoop.callWithRetry(client.getZookeeperClient(), new Callable() { + @Override + public Void call() throws Exception { + try { + ZooKeeper zkClient = client.getZookeeperClient().getZooKeeper(); + + if (finalNamespaceWatcher != null) { + zkClient.removeWatches(path, finalNamespaceWatcher, watcherType, false); + } else { + zkClient.removeAllWatches(path, watcherType, false); + } + } catch (Exception e) { + if (client.getZookeeperClient().getRetryPolicy().allowRetry(e) && guaranteed) { + // Setup the guaranteed handler + client.getFailedRemoveWatcherManager() + .addFailedOperation(new FailedRemoveWatchManager.FailedRemoveWatchDetails( + path, finalNamespaceWatcher)); + throw e; + } else if (e instanceof KeeperException.NoWatcherException && quietly) { + // ignore + } else { + // Rethrow + throw e; + } + } + + return null; + } + }); + } + } + + private NamespaceWatcher makeNamespaceWatcher(String path) { + NamespaceWatcher namespaceWatcher = null; + if (watcher != null) { + if (watcher instanceof NamespaceWatcher) { + namespaceWatcher = (NamespaceWatcher) watcher; + } else { + namespaceWatcher = new NamespaceWatcher(client, watcher, path); + } + } else if (curatorWatcher != null) { + namespaceWatcher = new NamespaceWatcher(client, curatorWatcher, path); + } + return namespaceWatcher; + } + + @Override + public void performBackgroundOperation(final OperationAndData operationAndData) throws Exception { + try { + final TimeTrace trace = client.getZookeeperClient().startTracer("RemoteWatches-Background"); + + AsyncCallback.VoidCallback callback = new AsyncCallback.VoidCallback() { + @Override + public void processResult(int rc, String path, Object ctx) { + trace.commit(); + CuratorEvent event = new CuratorEventImpl( + client, + CuratorEventType.REMOVE_WATCHES, + rc, + path, + null, + ctx, + null, + null, + null, + null, + null, + null); + client.processBackgroundOperation(operationAndData, event); + } + }; + + ZooKeeper zkClient = client.getZooKeeper(); + NamespaceWatcher namespaceWatcher = makeNamespaceWatcher(operationAndData.getData()); + if (namespaceWatcher == null) { + zkClient.removeAllWatches( + operationAndData.getData(), watcherType, local, callback, operationAndData.getContext()); + } else { + zkClient.removeWatches( + operationAndData.getData(), + namespaceWatcher, + watcherType, + local, + callback, + operationAndData.getContext()); + } + } catch (Throwable e) { + backgrounding.checkError(e, null); + } + } +} diff --git a/curator-framework/src/main/java/org/apache/curator/framework/imps/SetACLBuilderImpl.java b/curator-framework/src/main/java/org/apache/curator/framework/imps/SetACLBuilderImpl.java index eaafc3bc0..c54328d82 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/imps/SetACLBuilderImpl.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/imps/SetACLBuilderImpl.java @@ -19,38 +19,36 @@ package org.apache.curator.framework.imps; +import java.util.List; +import java.util.concurrent.Callable; +import java.util.concurrent.Executor; import org.apache.curator.RetryLoop; import org.apache.curator.drivers.OperationTrace; import org.apache.curator.framework.api.*; import org.apache.curator.framework.api.BackgroundCallback; -import org.apache.curator.framework.api.CuratorEventType; import org.apache.curator.framework.api.CuratorEvent; +import org.apache.curator.framework.api.CuratorEventType; import org.apache.curator.framework.api.SetACLBuilder; import org.apache.zookeeper.AsyncCallback; import org.apache.zookeeper.data.ACL; import org.apache.zookeeper.data.Stat; -import java.util.List; -import java.util.concurrent.Callable; -import java.util.concurrent.Executor; -public class SetACLBuilderImpl implements SetACLBuilder, BackgroundPathable, BackgroundOperation, ErrorListenerPathable -{ +public class SetACLBuilderImpl + implements SetACLBuilder, BackgroundPathable, BackgroundOperation, ErrorListenerPathable { private final CuratorFrameworkImpl client; - private ACLing acling; - private Backgrounding backgrounding; - private int version; + private ACLing acling; + private Backgrounding backgrounding; + private int version; - SetACLBuilderImpl(CuratorFrameworkImpl client) - { + SetACLBuilderImpl(CuratorFrameworkImpl client) { this.client = client; backgrounding = new Backgrounding(); acling = new ACLing(client.getAclProvider()); version = -1; } - public SetACLBuilderImpl(CuratorFrameworkImpl client, Backgrounding backgrounding, List aclList, int version) - { + public SetACLBuilderImpl(CuratorFrameworkImpl client, Backgrounding backgrounding, List aclList, int version) { this.client = client; this.acling = new ACLing(client.getAclProvider(), aclList); this.version = version; @@ -58,134 +56,126 @@ public SetACLBuilderImpl(CuratorFrameworkImpl client, Backgrounding backgroundin } @Override - public BackgroundPathable withACL(List aclList) - { + public BackgroundPathable withACL(List aclList) { acling = new ACLing(client.getAclProvider(), aclList, false); return this; } @Override - public ACLable> withVersion(int version) - { + public ACLable> withVersion(int version) { this.version = version; return this; } @Override - public ErrorListenerPathable inBackground() - { + public ErrorListenerPathable inBackground() { backgrounding = new Backgrounding(true); return this; } @Override - public ErrorListenerPathable inBackground(Object context) - { + public ErrorListenerPathable inBackground(Object context) { backgrounding = new Backgrounding(context); return this; } @Override - public ErrorListenerPathable inBackground(BackgroundCallback callback) - { + public ErrorListenerPathable inBackground(BackgroundCallback callback) { backgrounding = new Backgrounding(callback); return this; } @Override - public ErrorListenerPathable inBackground(BackgroundCallback callback, Object context) - { + public ErrorListenerPathable inBackground(BackgroundCallback callback, Object context) { backgrounding = new Backgrounding(callback, context); return this; } @Override - public ErrorListenerPathable inBackground(BackgroundCallback callback, Object context, Executor executor) - { + public ErrorListenerPathable inBackground(BackgroundCallback callback, Object context, Executor executor) { backgrounding = new Backgrounding(client, callback, context, executor); return this; } @Override - public ErrorListenerPathable inBackground(BackgroundCallback callback, Executor executor) - { + public ErrorListenerPathable inBackground(BackgroundCallback callback, Executor executor) { backgrounding = new Backgrounding(client, callback, executor); return this; } @Override - public Pathable withUnhandledErrorListener(UnhandledErrorListener listener) - { + public Pathable withUnhandledErrorListener(UnhandledErrorListener listener) { backgrounding = new Backgrounding(backgrounding, listener); return this; } @Override - public Stat forPath(String path) throws Exception - { + public Stat forPath(String path) throws Exception { String fixedPath = client.fixForNamespace(path); List aclList = acling.getAclList(fixedPath); client.getSchemaSet().getSchema(path).validateGeneral(path, null, aclList); - Stat resultStat = null; - if ( backgrounding.inBackground() ) - { - client.processBackgroundOperation(new OperationAndData(this, fixedPath, backgrounding.getCallback(), null, backgrounding.getContext(), null), null); - } - else - { + Stat resultStat = null; + if (backgrounding.inBackground()) { + client.processBackgroundOperation( + new OperationAndData( + this, fixedPath, backgrounding.getCallback(), null, backgrounding.getContext(), null), + null); + } else { resultStat = pathInForeground(fixedPath, aclList); } return resultStat; } @Override - public void performBackgroundOperation(final OperationAndData operationAndData) throws Exception - { - try - { - final OperationTrace trace = client.getZookeeperClient().startAdvancedTracer("SetACLBuilderImpl-Background"); - String path = operationAndData.getData(); - client.getZooKeeper().setACL - ( - path, - acling.getAclList(path), - version, - new AsyncCallback.StatCallback() - { - @SuppressWarnings({"unchecked"}) - @Override - public void processResult(int rc, String path, Object ctx, Stat stat) - { - trace.setReturnCode(rc).setPath(path).setStat(stat).commit(); - CuratorEvent event = new CuratorEventImpl(client, CuratorEventType.SET_ACL, rc, path, null, ctx, stat, null, null, null, null, null); - client.processBackgroundOperation(operationAndData, event); - } - }, - backgrounding.getContext() - ); - } - catch ( Throwable e ) - { + public void performBackgroundOperation(final OperationAndData operationAndData) throws Exception { + try { + final OperationTrace trace = + client.getZookeeperClient().startAdvancedTracer("SetACLBuilderImpl-Background"); + String path = operationAndData.getData(); + client.getZooKeeper() + .setACL( + path, + acling.getAclList(path), + version, + new AsyncCallback.StatCallback() { + @SuppressWarnings({"unchecked"}) + @Override + public void processResult(int rc, String path, Object ctx, Stat stat) { + trace.setReturnCode(rc) + .setPath(path) + .setStat(stat) + .commit(); + CuratorEvent event = new CuratorEventImpl( + client, + CuratorEventType.SET_ACL, + rc, + path, + null, + ctx, + stat, + null, + null, + null, + null, + null); + client.processBackgroundOperation(operationAndData, event); + } + }, + backgrounding.getContext()); + } catch (Throwable e) { backgrounding.checkError(e, null); } } - private Stat pathInForeground(final String path, final List aclList) throws Exception - { - OperationTrace trace = client.getZookeeperClient().startAdvancedTracer("SetACLBuilderImpl-Foreground"); - Stat resultStat = RetryLoop.callWithRetry - ( - client.getZookeeperClient(), - new Callable() - { - @Override - public Stat call() throws Exception - { - return client.getZooKeeper().setACL(path, aclList, version); - } + private Stat pathInForeground(final String path, final List aclList) throws Exception { + OperationTrace trace = client.getZookeeperClient().startAdvancedTracer("SetACLBuilderImpl-Foreground"); + Stat resultStat = RetryLoop.callWithRetry(client.getZookeeperClient(), new Callable() { + @Override + public Stat call() throws Exception { + return client.getZooKeeper().setACL(path, aclList, version); } - ); + }); trace.setPath(path).setStat(resultStat).commit(); return resultStat; } diff --git a/curator-framework/src/main/java/org/apache/curator/framework/imps/SetDataBuilderImpl.java b/curator-framework/src/main/java/org/apache/curator/framework/imps/SetDataBuilderImpl.java index 00fb4e118..73472cac1 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/imps/SetDataBuilderImpl.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/imps/SetDataBuilderImpl.java @@ -20,6 +20,9 @@ package org.apache.curator.framework.imps; import com.google.common.annotations.VisibleForTesting; +import java.util.Arrays; +import java.util.concurrent.Callable; +import java.util.concurrent.Executor; import org.apache.curator.RetryLoop; import org.apache.curator.drivers.OperationTrace; import org.apache.curator.framework.api.*; @@ -28,76 +31,66 @@ import org.apache.zookeeper.AsyncCallback; import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.Op; -import org.apache.zookeeper.ZooDefs; import org.apache.zookeeper.data.Stat; -import java.util.Arrays; -import java.util.concurrent.Callable; -import java.util.concurrent.Executor; -public class SetDataBuilderImpl implements SetDataBuilder, BackgroundOperation, ErrorListenerPathAndBytesable -{ - private final CuratorFrameworkImpl client; - private Backgrounding backgrounding; - private int version; - private boolean compress; - private boolean idempotent = false; +public class SetDataBuilderImpl + implements SetDataBuilder, BackgroundOperation, ErrorListenerPathAndBytesable { + private final CuratorFrameworkImpl client; + private Backgrounding backgrounding; + private int version; + private boolean compress; + private boolean idempotent = false; @VisibleForTesting boolean failNextSetForTesting = false; + @VisibleForTesting boolean failBeforeNextSetForTesting = false; + @VisibleForTesting boolean failNextIdempotentCheckForTesting = false; - SetDataBuilderImpl(CuratorFrameworkImpl client) - { + SetDataBuilderImpl(CuratorFrameworkImpl client) { this.client = client; backgrounding = new Backgrounding(); version = -1; compress = false; } - public SetDataBuilderImpl(CuratorFrameworkImpl client, Backgrounding backgrounding, int version, boolean compress) - { + public SetDataBuilderImpl(CuratorFrameworkImpl client, Backgrounding backgrounding, int version, boolean compress) { this.client = client; this.backgrounding = backgrounding; this.version = version; this.compress = compress; } - TransactionSetDataBuilder asTransactionSetDataBuilder(final T context, final CuratorMultiTransactionRecord transaction) - { - return new TransactionSetDataBuilder() - { + TransactionSetDataBuilder asTransactionSetDataBuilder( + final T context, final CuratorMultiTransactionRecord transaction) { + return new TransactionSetDataBuilder() { @Override - public T forPath(String path, byte[] data) throws Exception - { - if ( compress ) - { + public T forPath(String path, byte[] data) throws Exception { + if (compress) { data = client.getCompressionProvider().compress(path, data); } - String fixedPath = client.fixForNamespace(path); + String fixedPath = client.fixForNamespace(path); transaction.add(Op.setData(fixedPath, data, version), OperationType.SET_DATA, path); return context; } @Override - public T forPath(String path) throws Exception - { + public T forPath(String path) throws Exception { return forPath(path, client.getDefaultData()); } @Override - public PathAndBytesable withVersion(int version) - { + public PathAndBytesable withVersion(int version) { SetDataBuilderImpl.this.withVersion(version); return this; } @Override - public VersionPathAndBytesable compressed() - { + public VersionPathAndBytesable compressed() { compress = true; return this; } @@ -105,164 +98,140 @@ public VersionPathAndBytesable compressed() } @Override - public SetDataBackgroundVersionable compressed() - { + public SetDataBackgroundVersionable compressed() { compress = true; - return new SetDataBackgroundVersionable() - { + return new SetDataBackgroundVersionable() { @Override - public ErrorListenerPathAndBytesable inBackground() - { + public ErrorListenerPathAndBytesable inBackground() { return SetDataBuilderImpl.this.inBackground(); } @Override - public ErrorListenerPathAndBytesable inBackground(BackgroundCallback callback, Object context) - { + public ErrorListenerPathAndBytesable inBackground(BackgroundCallback callback, Object context) { return SetDataBuilderImpl.this.inBackground(callback, context); } @Override - public ErrorListenerPathAndBytesable inBackground(BackgroundCallback callback, Object context, Executor executor) - { + public ErrorListenerPathAndBytesable inBackground( + BackgroundCallback callback, Object context, Executor executor) { return SetDataBuilderImpl.this.inBackground(callback, context, executor); } @Override - public ErrorListenerPathAndBytesable inBackground(Object context) - { + public ErrorListenerPathAndBytesable inBackground(Object context) { return SetDataBuilderImpl.this.inBackground(context); } @Override - public ErrorListenerPathAndBytesable inBackground(BackgroundCallback callback) - { + public ErrorListenerPathAndBytesable inBackground(BackgroundCallback callback) { return SetDataBuilderImpl.this.inBackground(callback); } @Override - public ErrorListenerPathAndBytesable inBackground(BackgroundCallback callback, Executor executor) - { + public ErrorListenerPathAndBytesable inBackground(BackgroundCallback callback, Executor executor) { return SetDataBuilderImpl.this.inBackground(callback, executor); } @Override - public Stat forPath(String path, byte[] data) throws Exception - { + public Stat forPath(String path, byte[] data) throws Exception { return SetDataBuilderImpl.this.forPath(path, data); } @Override - public Stat forPath(String path) throws Exception - { + public Stat forPath(String path) throws Exception { return SetDataBuilderImpl.this.forPath(path); } @Override - public BackgroundPathAndBytesable withVersion(int version) - { + public BackgroundPathAndBytesable withVersion(int version) { return SetDataBuilderImpl.this.withVersion(version); } }; } @Override - public BackgroundPathAndBytesable withVersion(int version) - { + public BackgroundPathAndBytesable withVersion(int version) { this.version = version; return this; } @Override - public SetDataBuilder idempotent() - { + public SetDataBuilder idempotent() { this.idempotent = true; return this; } @Override - public ErrorListenerPathAndBytesable inBackground(BackgroundCallback callback, Object context) - { + public ErrorListenerPathAndBytesable inBackground(BackgroundCallback callback, Object context) { backgrounding = new Backgrounding(callback, context); return this; } @Override - public ErrorListenerPathAndBytesable inBackground(BackgroundCallback callback, Object context, Executor executor) - { + public ErrorListenerPathAndBytesable inBackground( + BackgroundCallback callback, Object context, Executor executor) { backgrounding = new Backgrounding(client, callback, context, executor); return this; } @Override - public ErrorListenerPathAndBytesable inBackground(BackgroundCallback callback) - { + public ErrorListenerPathAndBytesable inBackground(BackgroundCallback callback) { backgrounding = new Backgrounding(callback); return this; } @Override - public ErrorListenerPathAndBytesable inBackground() - { + public ErrorListenerPathAndBytesable inBackground() { backgrounding = new Backgrounding(true); return this; } @Override - public ErrorListenerPathAndBytesable inBackground(Object context) - { + public ErrorListenerPathAndBytesable inBackground(Object context) { backgrounding = new Backgrounding(context); return this; } @Override - public ErrorListenerPathAndBytesable inBackground(BackgroundCallback callback, Executor executor) - { + public ErrorListenerPathAndBytesable inBackground(BackgroundCallback callback, Executor executor) { backgrounding = new Backgrounding(client, callback, executor); return this; } @Override - public PathAndBytesable withUnhandledErrorListener(UnhandledErrorListener listener) - { + public PathAndBytesable withUnhandledErrorListener(UnhandledErrorListener listener) { backgrounding = new Backgrounding(backgrounding, listener); return this; } - private void backgroundCheckIdempotent(final CuratorFrameworkImpl client, final OperationAndData mainOperationAndData, final String path, final Backgrounding backgrounding) - { - final AsyncCallback.DataCallback dataCallback = new AsyncCallback.DataCallback() - { + private void backgroundCheckIdempotent( + final CuratorFrameworkImpl client, + final OperationAndData mainOperationAndData, + final String path, + final Backgrounding backgrounding) { + final AsyncCallback.DataCallback dataCallback = new AsyncCallback.DataCallback() { @Override - public void processResult(int rc, String path, Object ctx, byte[] data, Stat stat) - { - if ( rc == KeeperException.Code.OK.intValue() ) - { - if ( failNextIdempotentCheckForTesting ) - { - failNextIdempotentCheckForTesting = false; - rc = KeeperException.Code.CONNECTIONLOSS.intValue(); - } - else if ( !idempotentSetMatches(stat.getVersion(), mainOperationAndData.getData().getData(), data) ) - { - rc = KeeperException.Code.BADVERSION.intValue(); - } + public void processResult(int rc, String path, Object ctx, byte[] data, Stat stat) { + if (rc == KeeperException.Code.OK.intValue()) { + if (failNextIdempotentCheckForTesting) { + failNextIdempotentCheckForTesting = false; + rc = KeeperException.Code.CONNECTIONLOSS.intValue(); + } else if (!idempotentSetMatches( + stat.getVersion(), mainOperationAndData.getData().getData(), data)) { + rc = KeeperException.Code.BADVERSION.intValue(); } - final CuratorEvent event = new CuratorEventImpl(client, CuratorEventType.SET_DATA, rc, path, null, ctx, stat, null, null, null, null, null); - client.processBackgroundOperation(mainOperationAndData, event); + } + final CuratorEvent event = new CuratorEventImpl( + client, CuratorEventType.SET_DATA, rc, path, null, ctx, stat, null, null, null, null, null); + client.processBackgroundOperation(mainOperationAndData, event); } }; - BackgroundOperation operation = new BackgroundOperation() - { + BackgroundOperation operation = new BackgroundOperation() { @Override - public void performBackgroundOperation(OperationAndData op) throws Exception - { - try - { + public void performBackgroundOperation(OperationAndData op) throws Exception { + try { client.getZooKeeper().getData(path, false, dataCallback, backgrounding.getContext()); - } - catch ( KeeperException e ) - { + } catch (KeeperException e) { // ignore client.logError("Unexpected exception in async idempotent check for, ignoring: " + path, e); } @@ -272,97 +241,103 @@ public void performBackgroundOperation(OperationAndData op) throws } @Override - public void performBackgroundOperation(final OperationAndData operationAndData) throws Exception - { - try - { - final OperationTrace trace = client.getZookeeperClient().startAdvancedTracer("SetDataBuilderImpl-Background"); + public void performBackgroundOperation(final OperationAndData operationAndData) throws Exception { + try { + final OperationTrace trace = + client.getZookeeperClient().startAdvancedTracer("SetDataBuilderImpl-Background"); final byte[] data = operationAndData.getData().getData(); - client.getZooKeeper().setData - ( - operationAndData.getData().getPath(), - data, - version, - new AsyncCallback.StatCallback() - { - @SuppressWarnings({"unchecked"}) - @Override - public void processResult(int rc, String path, Object ctx, Stat stat) - { - trace.setReturnCode(rc).setRequestBytesLength(data).setPath(path).setStat(stat).commit(); - if ( (rc == KeeperException.Code.OK.intValue()) && failNextSetForTesting ) - { - failNextSetForTesting = false; - rc = KeeperException.Code.CONNECTIONLOSS.intValue(); - } - - if ( rc == KeeperException.Code.BADVERSION.intValue() && idempotent ) - { - backgroundCheckIdempotent(client, operationAndData, operationAndData.getData().getPath(), backgrounding); - } - else - { - CuratorEvent event = new CuratorEventImpl(client, CuratorEventType.SET_DATA, rc, path, null, ctx, stat, null, null, null, null, null); - client.processBackgroundOperation(operationAndData, event); - } - } - - }, - backgrounding.getContext() - ); - } - catch ( Throwable e ) - { + client.getZooKeeper() + .setData( + operationAndData.getData().getPath(), + data, + version, + new AsyncCallback.StatCallback() { + @SuppressWarnings({"unchecked"}) + @Override + public void processResult(int rc, String path, Object ctx, Stat stat) { + trace.setReturnCode(rc) + .setRequestBytesLength(data) + .setPath(path) + .setStat(stat) + .commit(); + if ((rc == KeeperException.Code.OK.intValue()) && failNextSetForTesting) { + failNextSetForTesting = false; + rc = KeeperException.Code.CONNECTIONLOSS.intValue(); + } + + if (rc == KeeperException.Code.BADVERSION.intValue() && idempotent) { + backgroundCheckIdempotent( + client, + operationAndData, + operationAndData.getData().getPath(), + backgrounding); + } else { + CuratorEvent event = new CuratorEventImpl( + client, + CuratorEventType.SET_DATA, + rc, + path, + null, + ctx, + stat, + null, + null, + null, + null, + null); + client.processBackgroundOperation(operationAndData, event); + } + } + }, + backgrounding.getContext()); + } catch (Throwable e) { backgrounding.checkError(e, null); } } @Override - public Stat forPath(String path) throws Exception - { + public Stat forPath(String path) throws Exception { return forPath(path, client.getDefaultData()); } @Override - public Stat forPath(String path, byte[] data) throws Exception - { + public Stat forPath(String path, byte[] data) throws Exception { client.getSchemaSet().getSchema(path).validateGeneral(path, data, null); - if ( compress ) - { + if (compress) { data = client.getCompressionProvider().compress(path, data); } path = client.fixForNamespace(path); - Stat resultStat = null; - if ( backgrounding.inBackground() ) - { - OperationAndData operationAndData = new OperationAndData(this, new PathAndBytes(path, data), backgrounding.getCallback(), null, backgrounding.getContext(), null) - { - @Override - void callPerformBackgroundOperation() throws Exception - { - // inject fault before performing operation - if ( failBeforeNextSetForTesting ) - { - failBeforeNextSetForTesting = false; - throw new KeeperException.ConnectionLossException(); - } - super.callPerformBackgroundOperation(); - } - }; + Stat resultStat = null; + if (backgrounding.inBackground()) { + OperationAndData operationAndData = + new OperationAndData( + this, + new PathAndBytes(path, data), + backgrounding.getCallback(), + null, + backgrounding.getContext(), + null) { + @Override + void callPerformBackgroundOperation() throws Exception { + // inject fault before performing operation + if (failBeforeNextSetForTesting) { + failBeforeNextSetForTesting = false; + throw new KeeperException.ConnectionLossException(); + } + super.callPerformBackgroundOperation(); + } + }; client.processBackgroundOperation(operationAndData, null); - } - else - { + } else { resultStat = pathInForeground(path, data); } return resultStat; } - int getVersion() - { + int getVersion() { return version; } @@ -371,69 +346,51 @@ int getVersion() * If the client did specify a version, idempotentcy has the additional constraint that the current version must be * one larger than the specified version, which is the behavior that would be observed in the normal (non-idempotent, non-failure) case for setData. */ - private boolean idempotentSetMatches(int getVersion, byte[] data, byte[] getData) - { - return ( version == -1 || (version + 1 == getVersion) ) && Arrays.equals(data, getData); + private boolean idempotentSetMatches(int getVersion, byte[] data, byte[] getData) { + return (version == -1 || (version + 1 == getVersion)) && Arrays.equals(data, getData); } - private Stat pathInForeground(final String path, final byte[] data) throws Exception - { - OperationTrace trace = client.getZookeeperClient().startAdvancedTracer("SetDataBuilderImpl-Foreground"); - Stat resultStat = RetryLoop.callWithRetry - ( - client.getZookeeperClient(), - new Callable() - { - @Override - public Stat call() throws Exception - { - if ( failBeforeNextSetForTesting ) - { - failBeforeNextSetForTesting = false; - throw new KeeperException.ConnectionLossException(); - } + private Stat pathInForeground(final String path, final byte[] data) throws Exception { + OperationTrace trace = client.getZookeeperClient().startAdvancedTracer("SetDataBuilderImpl-Foreground"); + Stat resultStat = RetryLoop.callWithRetry(client.getZookeeperClient(), new Callable() { + @Override + public Stat call() throws Exception { + if (failBeforeNextSetForTesting) { + failBeforeNextSetForTesting = false; + throw new KeeperException.ConnectionLossException(); + } - Stat localResultStat = null; - try - { - localResultStat = client.getZooKeeper().setData(path, data, version); + Stat localResultStat = null; + try { + localResultStat = client.getZooKeeper().setData(path, data, version); + } catch (KeeperException.BadVersionException e) { + if (!idempotent) { + throw e; } - catch ( KeeperException.BadVersionException e ) - { - if ( !idempotent ) - { - throw e; - } - Stat getStat = new Stat(); + Stat getStat = new Stat(); - // inject fault before performing operation - if ( failNextIdempotentCheckForTesting ) - { - failNextIdempotentCheckForTesting = false; - throw new KeeperException.ConnectionLossException(); - } - - byte[] existingData = client.getZooKeeper().getData(path, false, getStat); - if ( idempotentSetMatches(getStat.getVersion(), data, existingData) ) - { - localResultStat = getStat; - } - else - { - throw e; - } + // inject fault before performing operation + if (failNextIdempotentCheckForTesting) { + failNextIdempotentCheckForTesting = false; + throw new KeeperException.ConnectionLossException(); } - if ( failNextSetForTesting ) - { - failNextSetForTesting = false; - throw new KeeperException.ConnectionLossException(); + byte[] existingData = client.getZooKeeper().getData(path, false, getStat); + if (idempotentSetMatches(getStat.getVersion(), data, existingData)) { + localResultStat = getStat; + } else { + throw e; } - return localResultStat; } + + if (failNextSetForTesting) { + failNextSetForTesting = false; + throw new KeeperException.ConnectionLossException(); + } + return localResultStat; } - ); + }); trace.setRequestBytesLength(data).setPath(path).setStat(resultStat).commit(); return resultStat; } diff --git a/curator-framework/src/main/java/org/apache/curator/framework/imps/StandardInternalConnectionHandler.java b/curator-framework/src/main/java/org/apache/curator/framework/imps/StandardInternalConnectionHandler.java index 827a35382..88fe09c47 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/imps/StandardInternalConnectionHandler.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/imps/StandardInternalConnectionHandler.java @@ -19,17 +19,14 @@ package org.apache.curator.framework.imps; -class StandardInternalConnectionHandler implements InternalConnectionHandler -{ +class StandardInternalConnectionHandler implements InternalConnectionHandler { @Override - public void suspendConnection(CuratorFrameworkImpl client) - { + public void suspendConnection(CuratorFrameworkImpl client) { client.setToSuspended(); } @Override - public void checkNewConnection(CuratorFrameworkImpl client) - { + public void checkNewConnection(CuratorFrameworkImpl client) { client.checkInstanceIndex(); } } diff --git a/curator-framework/src/main/java/org/apache/curator/framework/imps/SyncBuilderImpl.java b/curator-framework/src/main/java/org/apache/curator/framework/imps/SyncBuilderImpl.java index a0bb366d9..db599cd3a 100755 --- a/curator-framework/src/main/java/org/apache/curator/framework/imps/SyncBuilderImpl.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/imps/SyncBuilderImpl.java @@ -19,6 +19,7 @@ package org.apache.curator.framework.imps; +import java.util.concurrent.Executor; import org.apache.curator.drivers.OperationTrace; import org.apache.curator.framework.api.BackgroundCallback; import org.apache.curator.framework.api.CuratorEvent; @@ -28,105 +29,89 @@ import org.apache.curator.framework.api.SyncBuilder; import org.apache.curator.framework.api.UnhandledErrorListener; import org.apache.zookeeper.AsyncCallback; -import java.util.concurrent.Executor; -public class SyncBuilderImpl implements SyncBuilder, BackgroundOperation, ErrorListenerPathable -{ +public class SyncBuilderImpl implements SyncBuilder, BackgroundOperation, ErrorListenerPathable { private final CuratorFrameworkImpl client; private Backgrounding backgrounding = new Backgrounding(); - public SyncBuilderImpl(CuratorFrameworkImpl client) - { - //To change body of created methods use File | Settings | File Templates. + public SyncBuilderImpl(CuratorFrameworkImpl client) { + // To change body of created methods use File | Settings | File Templates. this.client = client; } - public SyncBuilderImpl(CuratorFrameworkImpl client, Backgrounding backgrounding) - { + public SyncBuilderImpl(CuratorFrameworkImpl client, Backgrounding backgrounding) { this.client = client; this.backgrounding = backgrounding; } @Override - public ErrorListenerPathable inBackground() - { + public ErrorListenerPathable inBackground() { // NOP always in background return this; } @Override - public ErrorListenerPathable inBackground(Object context) - { + public ErrorListenerPathable inBackground(Object context) { backgrounding = new Backgrounding(context); return this; } @Override - public ErrorListenerPathable inBackground(BackgroundCallback callback) - { + public ErrorListenerPathable inBackground(BackgroundCallback callback) { backgrounding = new Backgrounding(callback); return this; } @Override - public ErrorListenerPathable inBackground(BackgroundCallback callback, Object context) - { + public ErrorListenerPathable inBackground(BackgroundCallback callback, Object context) { backgrounding = new Backgrounding(callback, context); return this; } @Override - public ErrorListenerPathable inBackground(BackgroundCallback callback, Executor executor) - { + public ErrorListenerPathable inBackground(BackgroundCallback callback, Executor executor) { backgrounding = new Backgrounding(client, callback, executor); return this; } @Override - public ErrorListenerPathable inBackground(BackgroundCallback callback, Object context, Executor executor) - { + public ErrorListenerPathable inBackground(BackgroundCallback callback, Object context, Executor executor) { backgrounding = new Backgrounding(client, callback, context, executor); return this; } @Override - public Pathable withUnhandledErrorListener(UnhandledErrorListener listener) - { + public Pathable withUnhandledErrorListener(UnhandledErrorListener listener) { backgrounding = new Backgrounding(backgrounding, listener); return this; } @Override - public void performBackgroundOperation(final OperationAndData operationAndData) throws Exception - { - try - { + public void performBackgroundOperation(final OperationAndData operationAndData) throws Exception { + try { final OperationTrace trace = client.getZookeeperClient().startAdvancedTracer("SyncBuilderImpl-Background"); final String path = operationAndData.getData(); String adjustedPath = client.fixForNamespace(path); - AsyncCallback.VoidCallback voidCallback = new AsyncCallback.VoidCallback() - { + AsyncCallback.VoidCallback voidCallback = new AsyncCallback.VoidCallback() { @Override - public void processResult(int rc, String path, Object ctx) - { + public void processResult(int rc, String path, Object ctx) { trace.setReturnCode(rc).setPath(path).commit(); - CuratorEvent event = new CuratorEventImpl(client, CuratorEventType.SYNC, rc, path, path, ctx, null, null, null, null, null, null); + CuratorEvent event = new CuratorEventImpl( + client, CuratorEventType.SYNC, rc, path, path, ctx, null, null, null, null, null, null); client.processBackgroundOperation(operationAndData, event); } }; client.getZooKeeper().sync(adjustedPath, voidCallback, backgrounding.getContext()); - } - catch ( Throwable e ) - { + } catch (Throwable e) { backgrounding.checkError(e, null); } } @Override - public Void forPath(String path) throws Exception - { - OperationAndData operationAndData = new OperationAndData(this, path, backgrounding.getCallback(), null, backgrounding.getContext(), null); + public Void forPath(String path) throws Exception { + OperationAndData operationAndData = new OperationAndData( + this, path, backgrounding.getCallback(), null, backgrounding.getContext(), null); client.processBackgroundOperation(operationAndData, null); return null; } diff --git a/curator-framework/src/main/java/org/apache/curator/framework/imps/TempGetDataBuilderImpl.java b/curator-framework/src/main/java/org/apache/curator/framework/imps/TempGetDataBuilderImpl.java index 220018dd5..63c9706c9 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/imps/TempGetDataBuilderImpl.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/imps/TempGetDataBuilderImpl.java @@ -19,60 +19,52 @@ package org.apache.curator.framework.imps; +import java.util.concurrent.Callable; import org.apache.curator.RetryLoop; import org.apache.curator.drivers.OperationTrace; import org.apache.curator.framework.api.Pathable; import org.apache.curator.framework.api.StatPathable; import org.apache.curator.framework.api.TempGetDataBuilder; import org.apache.zookeeper.data.Stat; -import java.util.concurrent.Callable; -class TempGetDataBuilderImpl implements TempGetDataBuilder -{ - private final CuratorFrameworkImpl client; - private Stat responseStat; - private boolean decompress; +class TempGetDataBuilderImpl implements TempGetDataBuilder { + private final CuratorFrameworkImpl client; + private Stat responseStat; + private boolean decompress; - TempGetDataBuilderImpl(CuratorFrameworkImpl client) - { + TempGetDataBuilderImpl(CuratorFrameworkImpl client) { this.client = client; responseStat = null; decompress = false; } @Override - public StatPathable decompressed() - { + public StatPathable decompressed() { decompress = true; return this; } @Override - public Pathable storingStatIn(Stat stat) - { + public Pathable storingStatIn(Stat stat) { responseStat = stat; return this; } @Override - public byte[] forPath(String path) throws Exception - { - final String localPath = client.fixForNamespace(path); + public byte[] forPath(String path) throws Exception { + final String localPath = client.fixForNamespace(path); - OperationTrace trace = client.getZookeeperClient().startAdvancedTracer("GetDataBuilderImpl-Foreground"); - byte[] responseData = RetryLoop.callWithRetry - ( - client.getZookeeperClient(), - new Callable() - { - @Override - public byte[] call() throws Exception - { - return client.getZooKeeper().getData(localPath, false, responseStat); - } + OperationTrace trace = client.getZookeeperClient().startAdvancedTracer("GetDataBuilderImpl-Foreground"); + byte[] responseData = RetryLoop.callWithRetry(client.getZookeeperClient(), new Callable() { + @Override + public byte[] call() throws Exception { + return client.getZooKeeper().getData(localPath, false, responseStat); } - ); - trace.setResponseBytesLength(responseData).setPath(path).setStat(responseStat).commit(); + }); + trace.setResponseBytesLength(responseData) + .setPath(path) + .setStat(responseStat) + .commit(); return decompress ? client.getCompressionProvider().decompress(path, responseData) : responseData; } diff --git a/curator-framework/src/main/java/org/apache/curator/framework/imps/TransactionOpImpl.java b/curator-framework/src/main/java/org/apache/curator/framework/imps/TransactionOpImpl.java index 6347834f0..41f7949c8 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/imps/TransactionOpImpl.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/imps/TransactionOpImpl.java @@ -26,41 +26,34 @@ import org.apache.curator.framework.api.transaction.TransactionOp; import org.apache.curator.framework.api.transaction.TransactionSetDataBuilder; -public class TransactionOpImpl implements TransactionOp -{ +public class TransactionOpImpl implements TransactionOp { private final CuratorFrameworkImpl client; - public TransactionOpImpl(CuratorFrameworkImpl client) - { + public TransactionOpImpl(CuratorFrameworkImpl client) { this.client = client; } @Override - public TransactionCreateBuilder create() - { + public TransactionCreateBuilder create() { ExtractingCuratorOp op = new ExtractingCuratorOp(); return new CreateBuilderImpl(client).asTransactionCreateBuilder(op, op.getRecord()); } @Override - public TransactionDeleteBuilder delete() - { + public TransactionDeleteBuilder delete() { ExtractingCuratorOp op = new ExtractingCuratorOp(); return new DeleteBuilderImpl(client).asTransactionDeleteBuilder(op, op.getRecord()); } @Override - public TransactionSetDataBuilder setData() - { + public TransactionSetDataBuilder setData() { ExtractingCuratorOp op = new ExtractingCuratorOp(); return new SetDataBuilderImpl(client).asTransactionSetDataBuilder(op, op.getRecord()); } @Override - public TransactionCheckBuilder check() - { + public TransactionCheckBuilder check() { ExtractingCuratorOp op = new ExtractingCuratorOp(); return CuratorTransactionImpl.makeTransactionCheckBuilder(client, op, op.getRecord()); } - } diff --git a/curator-framework/src/main/java/org/apache/curator/framework/imps/WatcherRemovalFacade.java b/curator-framework/src/main/java/org/apache/curator/framework/imps/WatcherRemovalFacade.java index 82f32d3d4..ba5ce42cc 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/imps/WatcherRemovalFacade.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/imps/WatcherRemovalFacade.java @@ -29,162 +29,135 @@ import org.apache.curator.framework.listen.Listenable; import org.apache.curator.framework.state.ConnectionStateListener; import org.apache.curator.utils.EnsurePath; -import org.apache.zookeeper.Watcher; import org.apache.zookeeper.ZooKeeper; import org.apache.zookeeper.server.quorum.flexible.QuorumVerifier; -class WatcherRemovalFacade extends CuratorFrameworkImpl implements WatcherRemoveCuratorFramework -{ +class WatcherRemovalFacade extends CuratorFrameworkImpl implements WatcherRemoveCuratorFramework { private final CuratorFrameworkImpl client; private final WatcherRemovalManager removalManager; - WatcherRemovalFacade(CuratorFrameworkImpl client) - { + WatcherRemovalFacade(CuratorFrameworkImpl client) { super(client); this.client = client; removalManager = new WatcherRemovalManager(client); } @Override - public WatcherRemoveCuratorFramework newWatcherRemoveCuratorFramework() - { + public WatcherRemoveCuratorFramework newWatcherRemoveCuratorFramework() { return client.newWatcherRemoveCuratorFramework(); } - WatcherRemovalManager getRemovalManager() - { + WatcherRemovalManager getRemovalManager() { return removalManager; } @Override - public QuorumVerifier getCurrentConfig() - { + public QuorumVerifier getCurrentConfig() { return client.getCurrentConfig(); } @Override - public void removeWatchers() - { + public void removeWatchers() { removalManager.removeWatchers(); } @Override - WatcherRemovalManager getWatcherRemovalManager() - { + WatcherRemovalManager getWatcherRemovalManager() { return removalManager; } @Override - public CuratorFramework nonNamespaceView() - { + public CuratorFramework nonNamespaceView() { return client.nonNamespaceView(); } @Override - public CuratorFramework usingNamespace(String newNamespace) - { + public CuratorFramework usingNamespace(String newNamespace) { return client.usingNamespace(newNamespace); } @Override - public String getNamespace() - { + public String getNamespace() { return client.getNamespace(); } @Override - public void start() - { + public void start() { throw new UnsupportedOperationException(); } @Override - public void close() - { + public void close() { throw new UnsupportedOperationException(); } @Override - public Listenable getConnectionStateListenable() - { + public Listenable getConnectionStateListenable() { return client.getConnectionStateListenable(); } @Override - public Listenable getCuratorListenable() - { + public Listenable getCuratorListenable() { return client.getCuratorListenable(); } @Override - public Listenable getUnhandledErrorListenable() - { + public Listenable getUnhandledErrorListenable() { return client.getUnhandledErrorListenable(); } @Override - public void sync(String path, Object context) - { + public void sync(String path, Object context) { client.sync(path, context); } @Override - public CuratorZookeeperClient getZookeeperClient() - { + public CuratorZookeeperClient getZookeeperClient() { return client.getZookeeperClient(); } @Override - RetryLoop newRetryLoop() - { + RetryLoop newRetryLoop() { return client.newRetryLoop(); } @Override - ZooKeeper getZooKeeper() throws Exception - { + ZooKeeper getZooKeeper() throws Exception { return client.getZooKeeper(); } @Override - void processBackgroundOperation(OperationAndData operationAndData, CuratorEvent event) - { + void processBackgroundOperation(OperationAndData operationAndData, CuratorEvent event) { client.processBackgroundOperation(operationAndData, event); } @Override - void logError(String reason, Throwable e) - { + void logError(String reason, Throwable e) { client.logError(reason, e); } @Override - String unfixForNamespace(String path) - { + String unfixForNamespace(String path) { return client.unfixForNamespace(path); } @Override - String fixForNamespace(String path) - { + String fixForNamespace(String path) { return client.fixForNamespace(path); } - + @Override - String fixForNamespace(String path, boolean isSequential) - { - return client.fixForNamespace(path, isSequential); + String fixForNamespace(String path, boolean isSequential) { + return client.fixForNamespace(path, isSequential); } @Override - public EnsurePath newNamespaceAwareEnsurePath(String path) - { + public EnsurePath newNamespaceAwareEnsurePath(String path) { return client.newNamespaceAwareEnsurePath(path); } @Override - FailedDeleteManager getFailedDeleteManager() - { + FailedDeleteManager getFailedDeleteManager() { return client.getFailedDeleteManager(); } } diff --git a/curator-framework/src/main/java/org/apache/curator/framework/imps/WatcherRemovalManager.java b/curator-framework/src/main/java/org/apache/curator/framework/imps/WatcherRemovalManager.java index 9ac569bf9..f8b4a3984 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/imps/WatcherRemovalManager.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/imps/WatcherRemovalManager.java @@ -23,59 +23,48 @@ import com.google.common.base.Preconditions; import com.google.common.collect.Lists; import com.google.common.collect.Sets; +import java.util.List; +import java.util.Set; import org.apache.zookeeper.Watcher; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.util.List; -import java.util.Set; -public class WatcherRemovalManager -{ +public class WatcherRemovalManager { private final Logger log = LoggerFactory.getLogger(getClass()); private final CuratorFrameworkImpl client; private final Set entries = Sets.newConcurrentHashSet(); - WatcherRemovalManager(CuratorFrameworkImpl client) - { + WatcherRemovalManager(CuratorFrameworkImpl client) { this.client = client; } - void add(NamespaceWatcher watcher) - { + void add(NamespaceWatcher watcher) { watcher = Preconditions.checkNotNull(watcher, "watcher cannot be null"); entries.add(watcher); } @VisibleForTesting - Set getEntries() - { + Set getEntries() { return Sets.newHashSet(entries); } - void removeWatchers() - { + void removeWatchers() { List localEntries = Lists.newArrayList(entries); - while ( localEntries.size() > 0 ) - { + while (localEntries.size() > 0) { NamespaceWatcher watcher = localEntries.remove(0); - if ( entries.remove(watcher) ) - { - try - { + if (entries.remove(watcher)) { + try { log.debug("Removing watcher for path: " + watcher.getUnfixedPath()); RemoveWatchesBuilderImpl builder = new RemoveWatchesBuilderImpl(client); builder.internalRemoval(watcher, watcher.getUnfixedPath()); - } - catch ( Exception e ) - { + } catch (Exception e) { log.error("Could not remove watcher for path: " + watcher.getUnfixedPath()); } } } } - void noteTriggeredWatcher(NamespaceWatcher watcher) - { + void noteTriggeredWatcher(NamespaceWatcher watcher) { entries.remove(watcher); } } diff --git a/curator-framework/src/main/java/org/apache/curator/framework/imps/WatchesBuilderImpl.java b/curator-framework/src/main/java/org/apache/curator/framework/imps/WatchesBuilderImpl.java index d80d52b26..cb63dc8b3 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/imps/WatchesBuilderImpl.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/imps/WatchesBuilderImpl.java @@ -25,21 +25,25 @@ import org.apache.zookeeper.Watcher; import org.apache.zookeeper.Watcher.WatcherType; -public class WatchesBuilderImpl extends RemoveWatchesBuilderImpl implements WatchesBuilder -{ - public WatchesBuilderImpl(CuratorFrameworkImpl client) - { +public class WatchesBuilderImpl extends RemoveWatchesBuilderImpl implements WatchesBuilder { + public WatchesBuilderImpl(CuratorFrameworkImpl client) { super(client); } - public WatchesBuilderImpl(CuratorFrameworkImpl client, Watcher watcher, CuratorWatcher curatorWatcher, WatcherType watcherType, boolean guaranteed, boolean local, boolean quietly, Backgrounding backgrounding) - { + public WatchesBuilderImpl( + CuratorFrameworkImpl client, + Watcher watcher, + CuratorWatcher curatorWatcher, + WatcherType watcherType, + boolean guaranteed, + boolean local, + boolean quietly, + Backgrounding backgrounding) { super(client, watcher, curatorWatcher, watcherType, guaranteed, local, quietly, backgrounding); } @Override - public AddWatchBuilder add() - { + public AddWatchBuilder add() { return new AddWatchBuilderImpl(getClient()); } -} \ No newline at end of file +} diff --git a/curator-framework/src/main/java/org/apache/curator/framework/imps/Watching.java b/curator-framework/src/main/java/org/apache/curator/framework/imps/Watching.java index fef544ab6..92b16731c 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/imps/Watching.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/imps/Watching.java @@ -23,87 +23,70 @@ import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.Watcher; -public class Watching -{ +public class Watching { private final Watcher watcher; private final CuratorWatcher curatorWatcher; private final boolean watched; private final CuratorFrameworkImpl client; private NamespaceWatcher namespaceWatcher; - public Watching(CuratorFrameworkImpl client, boolean watched) - { + public Watching(CuratorFrameworkImpl client, boolean watched) { this.client = client; this.watcher = null; this.curatorWatcher = null; this.watched = watched; } - public Watching(CuratorFrameworkImpl client, Watcher watcher) - { + public Watching(CuratorFrameworkImpl client, Watcher watcher) { this.client = client; this.watcher = watcher; this.curatorWatcher = null; this.watched = false; } - public Watching(CuratorFrameworkImpl client, CuratorWatcher watcher) - { + public Watching(CuratorFrameworkImpl client, CuratorWatcher watcher) { this.client = client; this.watcher = null; this.curatorWatcher = watcher; this.watched = false; } - public Watching(CuratorFrameworkImpl client) - { + public Watching(CuratorFrameworkImpl client) { this.client = client; watcher = null; watched = false; curatorWatcher = null; } - Watcher getWatcher(String unfixedPath) - { + Watcher getWatcher(String unfixedPath) { namespaceWatcher = null; - if ( watcher != null ) - { + if (watcher != null) { namespaceWatcher = new NamespaceWatcher(client, this.watcher, unfixedPath); - } - else if ( curatorWatcher != null ) - { + } else if (curatorWatcher != null) { namespaceWatcher = new NamespaceWatcher(client, curatorWatcher, unfixedPath); } return namespaceWatcher; } - boolean hasWatcher() - { + boolean hasWatcher() { return (watcher != null) || (curatorWatcher != null); } - boolean isWatched() - { + boolean isWatched() { return watched; } - void commitWatcher(int rc, boolean isExists) - { + void commitWatcher(int rc, boolean isExists) { boolean doCommit = false; - if ( isExists ) - { + if (isExists) { doCommit = ((rc == KeeperException.Code.OK.intValue()) || (rc == KeeperException.Code.NONODE.intValue())); - } - else - { + } else { doCommit = (rc == KeeperException.Code.OK.intValue()); } - if ( doCommit && (namespaceWatcher != null) ) - { - if ( client.getWatcherRemovalManager() != null ) - { + if (doCommit && (namespaceWatcher != null)) { + if (client.getWatcherRemovalManager() != null) { client.getWatcherRemovalManager().add(namespaceWatcher); } } diff --git a/curator-framework/src/main/java/org/apache/curator/framework/listen/Listenable.java b/curator-framework/src/main/java/org/apache/curator/framework/listen/Listenable.java index da9b9b8fc..efd118729 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/listen/Listenable.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/listen/Listenable.java @@ -24,15 +24,14 @@ /** * Abstracts a listenable object */ -public interface Listenable -{ +public interface Listenable { /** * Add the given listener. The listener will be executed in the containing * instance's thread. * * @param listener listener to add */ - public void addListener(T listener); + public void addListener(T listener); /** * Add the given listener. The listener will be executed using the given @@ -41,12 +40,12 @@ public interface Listenable * @param listener listener to add * @param executor executor to run listener in */ - public void addListener(T listener, Executor executor); + public void addListener(T listener, Executor executor); /** * Remove the given listener * * @param listener listener to remove */ - public void removeListener(T listener); + public void removeListener(T listener); } diff --git a/curator-framework/src/main/java/org/apache/curator/framework/listen/ListenerEntry.java b/curator-framework/src/main/java/org/apache/curator/framework/listen/ListenerEntry.java index 62e2d05dd..100f1af43 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/listen/ListenerEntry.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/listen/ListenerEntry.java @@ -25,13 +25,11 @@ * Generic holder POJO for a listener and its executor * @param the listener type */ -public class ListenerEntry -{ - public final T listener; +public class ListenerEntry { + public final T listener; public final Executor executor; - public ListenerEntry(T listener, Executor executor) - { + public ListenerEntry(T listener, Executor executor) { this.listener = listener; this.executor = executor; } diff --git a/curator-framework/src/main/java/org/apache/curator/framework/listen/ListenerManager.java b/curator-framework/src/main/java/org/apache/curator/framework/listen/ListenerManager.java index 8a0f96def..e26d098de 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/listen/ListenerManager.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/listen/ListenerManager.java @@ -21,8 +21,7 @@ import java.util.function.Consumer; -public interface ListenerManager extends Listenable -{ +public interface ListenerManager extends Listenable { /** * Remove all listeners */ @@ -43,8 +42,7 @@ public interface ListenerManager extends Listenable */ void forEach(Consumer function); - default boolean isEmpty() - { + default boolean isEmpty() { return size() == 0; } } diff --git a/curator-framework/src/main/java/org/apache/curator/framework/listen/MappingListenerManager.java b/curator-framework/src/main/java/org/apache/curator/framework/listen/MappingListenerManager.java index d0b57c293..44f199d97 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/listen/MappingListenerManager.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/listen/MappingListenerManager.java @@ -19,20 +19,19 @@ package org.apache.curator.framework.listen; -import org.apache.curator.utils.ThreadUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.Executor; import java.util.function.Consumer; import java.util.function.Function; +import org.apache.curator.utils.ThreadUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * Version of ListenerManager that supports mapping/wrapping of listeners */ -public class MappingListenerManager implements ListenerManager -{ +public class MappingListenerManager implements ListenerManager { private final Logger log = LoggerFactory.getLogger(getClass()); private final Map> listeners = new ConcurrentHashMap<>(); private final Function mapper; @@ -43,57 +42,45 @@ public class MappingListenerManager implements ListenerManager * @param mapper listener mapper/wrapper * @return new container */ - public static ListenerManager mapping(Function mapper) - { + public static ListenerManager mapping(Function mapper) { return new MappingListenerManager<>(mapper); } @Override - public void addListener(K listener) - { + public void addListener(K listener) { addListener(listener, Runnable::run); } @Override - public void addListener(K listener, Executor executor) - { + public void addListener(K listener, Executor executor) { V mapped = mapper.apply(listener); listeners.put(listener, new ListenerEntry<>(mapped, executor)); } @Override - public void removeListener(K listener) - { - if ( listener != null ) - { + public void removeListener(K listener) { + if (listener != null) { listeners.remove(listener); } } @Override - public void clear() - { + public void clear() { listeners.clear(); } @Override - public int size() - { + public int size() { return listeners.size(); } @Override - public void forEach(Consumer function) - { - for ( ListenerEntry entry : listeners.values() ) - { + public void forEach(Consumer function) { + for (ListenerEntry entry : listeners.values()) { entry.executor.execute(() -> { - try - { + try { function.accept(entry.listener); - } - catch ( Throwable e ) - { + } catch (Throwable e) { ThreadUtils.checkInterrupted(e); log.error(String.format("Listener (%s) threw an exception", entry.listener), e); } @@ -101,8 +88,7 @@ public void forEach(Consumer function) } } - MappingListenerManager(Function mapper) - { + MappingListenerManager(Function mapper) { this.mapper = mapper; } } diff --git a/curator-framework/src/main/java/org/apache/curator/framework/listen/StandardListenerManager.java b/curator-framework/src/main/java/org/apache/curator/framework/listen/StandardListenerManager.java index f7d3277c3..dfb8a948e 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/listen/StandardListenerManager.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/listen/StandardListenerManager.java @@ -27,8 +27,7 @@ /** * Non mapping version of a listener container */ -public class StandardListenerManager implements UnaryListenerManager -{ +public class StandardListenerManager implements UnaryListenerManager { private final ListenerManager container; /** @@ -36,8 +35,7 @@ public class StandardListenerManager implements UnaryListenerManager * * @return new container */ - public static StandardListenerManager standard() - { + public static StandardListenerManager standard() { MappingListenerManager container = new MappingListenerManager<>(Function.identity()); return new StandardListenerManager<>(container); } @@ -48,50 +46,42 @@ public static StandardListenerManager standard() * @param mapper listener mapper/wrapper * @return new container */ - public static StandardListenerManager mappingStandard(UnaryOperator mapper) - { + public static StandardListenerManager mappingStandard(UnaryOperator mapper) { MappingListenerManager container = new MappingListenerManager<>(mapper); return new StandardListenerManager<>(container); } @Override - public void addListener(T listener) - { + public void addListener(T listener) { container.addListener(listener); } @Override - public void addListener(T listener, Executor executor) - { + public void addListener(T listener, Executor executor) { container.addListener(listener, executor); } @Override - public void removeListener(T listener) - { + public void removeListener(T listener) { container.removeListener(listener); } @Override - public void clear() - { + public void clear() { container.clear(); } @Override - public int size() - { + public int size() { return container.size(); } @Override - public void forEach(Consumer function) - { + public void forEach(Consumer function) { container.forEach(function); } - private StandardListenerManager(ListenerManager container) - { + private StandardListenerManager(ListenerManager container) { this.container = container; } } diff --git a/curator-framework/src/main/java/org/apache/curator/framework/listen/UnaryListenerManager.java b/curator-framework/src/main/java/org/apache/curator/framework/listen/UnaryListenerManager.java index 1a6479420..862e84ffc 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/listen/UnaryListenerManager.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/listen/UnaryListenerManager.java @@ -22,6 +22,4 @@ /** * A {@link ListenerManager} that doesn't do any mapping */ -public interface UnaryListenerManager extends ListenerManager -{ -} +public interface UnaryListenerManager extends ListenerManager {} diff --git a/curator-framework/src/main/java/org/apache/curator/framework/schema/DefaultSchemaValidator.java b/curator-framework/src/main/java/org/apache/curator/framework/schema/DefaultSchemaValidator.java index b54f32c59..84cd42b45 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/schema/DefaultSchemaValidator.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/schema/DefaultSchemaValidator.java @@ -19,17 +19,15 @@ package org.apache.curator.framework.schema; -import org.apache.zookeeper.data.ACL; import java.util.List; +import org.apache.zookeeper.data.ACL; /** * The default data validator - always returns true */ -public class DefaultSchemaValidator implements SchemaValidator -{ +public class DefaultSchemaValidator implements SchemaValidator { @Override - public boolean isValid(Schema schema, String path, byte[] data, List acl) - { + public boolean isValid(Schema schema, String path, byte[] data, List acl) { return true; } } diff --git a/curator-framework/src/main/java/org/apache/curator/framework/schema/Schema.java b/curator-framework/src/main/java/org/apache/curator/framework/schema/Schema.java index 180e6ecdf..a11e4384f 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/schema/Schema.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/schema/Schema.java @@ -21,18 +21,17 @@ import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableMap; -import org.apache.curator.utils.ZKPaths; -import org.apache.zookeeper.CreateMode; -import org.apache.zookeeper.data.ACL; import java.util.List; import java.util.Map; import java.util.regex.Pattern; +import org.apache.curator.utils.ZKPaths; +import org.apache.zookeeper.CreateMode; +import org.apache.zookeeper.data.ACL; /** * Represents and documents operations allowed for a given path pattern */ -public class Schema -{ +public class Schema { private final String name; private final Pattern pathRegex; private final String fixedPath; @@ -44,8 +43,7 @@ public class Schema private final boolean canBeDeleted; private final Map metadata; - public enum Allowance - { + public enum Allowance { CAN, MUST, CANNOT @@ -58,8 +56,7 @@ public enum Allowance * @param path full ZNode path. This schema only applies to an exact match * @return builder */ - public static SchemaBuilder builder(String path) - { + public static SchemaBuilder builder(String path) { return new SchemaBuilder(null, path); } @@ -69,8 +66,7 @@ public static SchemaBuilder builder(String path) * @param pathRegex regex for the path. This schema applies to any matching paths * @return builder */ - public static SchemaBuilder builder(Pattern pathRegex) - { + public static SchemaBuilder builder(Pattern pathRegex) { return new SchemaBuilder(pathRegex, null); } @@ -80,12 +76,8 @@ public static SchemaBuilder builder(Pattern pathRegex) * @param parentPath Path to the parent node * @return builder */ - public static SchemaBuilder builderForRecipeParent(String parentPath) - { - return new SchemaBuilder(null, parentPath) - .sequential(Allowance.CANNOT) - .ephemeral(Allowance.CANNOT) - ; + public static SchemaBuilder builderForRecipeParent(String parentPath) { + return new SchemaBuilder(null, parentPath).sequential(Allowance.CANNOT).ephemeral(Allowance.CANNOT); } /** @@ -94,18 +86,25 @@ public static SchemaBuilder builderForRecipeParent(String parentPath) * @param parentPath Path to the parent node * @return builder */ - public static SchemaBuilder builderForRecipe(String parentPath) - { + public static SchemaBuilder builderForRecipe(String parentPath) { return new SchemaBuilder(Pattern.compile(ZKPaths.makePath(parentPath, ".*")), null) - .sequential(Allowance.MUST) - .ephemeral(Allowance.MUST) - .watched(Allowance.MUST) - .canBeDeleted(true) - ; + .sequential(Allowance.MUST) + .ephemeral(Allowance.MUST) + .watched(Allowance.MUST) + .canBeDeleted(true); } - Schema(String name, Pattern pathRegex, String path, String documentation, SchemaValidator schemaValidator, Allowance ephemeral, Allowance sequential, Allowance watched, boolean canBeDeleted, Map metadata) - { + Schema( + String name, + Pattern pathRegex, + String path, + String documentation, + SchemaValidator schemaValidator, + Allowance ephemeral, + Allowance sequential, + Allowance watched, + boolean canBeDeleted, + Map metadata) { Preconditions.checkArgument((pathRegex != null) || (path != null), "pathRegex and path cannot both be null"); this.pathRegex = pathRegex; this.fixedPath = fixPath(path); @@ -119,12 +118,9 @@ public static SchemaBuilder builderForRecipe(String parentPath) this.canBeDeleted = canBeDeleted; } - private String fixPath(String path) - { - if ( path != null ) - { - if ( path.endsWith(ZKPaths.PATH_SEPARATOR) ) - { + private String fixPath(String path) { + if (path != null) { + if (path.endsWith(ZKPaths.PATH_SEPARATOR)) { return (path.length() > 1) ? path.substring(0, path.length() - 1) : ""; } return path; @@ -138,10 +134,8 @@ private String fixPath(String path) * @param path the znode full path * @throws SchemaViolation if schema does not allow znode deletion */ - public void validateDelete(String path) - { - if ( !canBeDeleted ) - { + public void validateDelete(String path) { + if (!canBeDeleted) { throw new SchemaViolation(this, new SchemaViolation.ViolatorData(path, null, null), "Cannot be deleted"); } } @@ -153,15 +147,12 @@ public void validateDelete(String path) * @param isWatching true if attempt is being made to watch node * @throws SchemaViolation if schema's watching setting does not match */ - public void validateWatch(String path, boolean isWatching) - { - if ( isWatching && (watched == Allowance.CANNOT) ) - { + public void validateWatch(String path, boolean isWatching) { + if (isWatching && (watched == Allowance.CANNOT)) { throw new SchemaViolation(this, new SchemaViolation.ViolatorData(path, null, null), "Cannot be watched"); } - if ( !isWatching && (watched == Allowance.MUST) ) - { + if (!isWatching && (watched == Allowance.MUST)) { throw new SchemaViolation(this, new SchemaViolation.ViolatorData(path, null, null), "Must be watched"); } } @@ -175,25 +166,20 @@ public void validateWatch(String path, boolean isWatching) * @param acl the creation acls * @throws SchemaViolation if schema's create mode setting does not match or data is invalid */ - public void validateCreate(CreateMode mode, String path, byte[] data, List acl) - { - if ( mode.isEphemeral() && (ephemeral == Allowance.CANNOT) ) - { + public void validateCreate(CreateMode mode, String path, byte[] data, List acl) { + if (mode.isEphemeral() && (ephemeral == Allowance.CANNOT)) { throw new SchemaViolation(this, new SchemaViolation.ViolatorData(path, data, acl), "Cannot be ephemeral"); } - if ( !mode.isEphemeral() && (ephemeral == Allowance.MUST) ) - { + if (!mode.isEphemeral() && (ephemeral == Allowance.MUST)) { throw new SchemaViolation(this, new SchemaViolation.ViolatorData(path, data, acl), "Must be ephemeral"); } - if ( mode.isSequential() && (sequential == Allowance.CANNOT) ) - { + if (mode.isSequential() && (sequential == Allowance.CANNOT)) { throw new SchemaViolation(this, new SchemaViolation.ViolatorData(path, data, acl), "Cannot be sequential"); } - if ( !mode.isSequential() && (sequential == Allowance.MUST) ) - { + if (!mode.isSequential() && (sequential == Allowance.MUST)) { throw new SchemaViolation(this, new SchemaViolation.ViolatorData(path, data, acl), "Must be sequential"); } @@ -209,16 +195,13 @@ public void validateCreate(CreateMode mode, String path, byte[] data, List * @param acl if creating, the acls otherwise null or empty list * @throws SchemaViolation if data is invalid */ - public void validateGeneral(String path, byte[] data, List acl) - { - if ( !schemaValidator.isValid(this, path, data, acl) ) - { + public void validateGeneral(String path, byte[] data, List acl) { + if (!schemaValidator.isValid(this, path, data, acl)) { throw new SchemaViolation(this, new SchemaViolation.ViolatorData(path, data, acl), "Data is not valid"); } } - public String getName() - { + public String getName() { return name; } @@ -228,115 +211,98 @@ public String getName() * * @return path */ - public String getRawPath() - { + public String getRawPath() { return (fixedPath != null) ? fixedPath : pathRegex.pattern(); } - public Map getMetadata() - { + public Map getMetadata() { return metadata; } - public Pattern getPathRegex() - { + public Pattern getPathRegex() { return pathRegex; } - public String getPath() - { + public String getPath() { return fixedPath; } - public String getDocumentation() - { + public String getDocumentation() { return documentation; } - public SchemaValidator getSchemaValidator() - { + public SchemaValidator getSchemaValidator() { return schemaValidator; } - public Allowance getEphemeral() - { + public Allowance getEphemeral() { return ephemeral; } - public Allowance getSequential() - { + public Allowance getSequential() { return sequential; } - public Allowance getWatched() - { + public Allowance getWatched() { return watched; } - public boolean canBeDeleted() - { + public boolean canBeDeleted() { return canBeDeleted; } // intentionally only path and pathRegex @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; } - Schema schema = (Schema)o; + Schema schema = (Schema) o; //noinspection SimplifiableIfStatement - if ( !pathRegex.equals(schema.pathRegex) ) - { + if (!pathRegex.equals(schema.pathRegex)) { return false; } return fixedPath.equals(schema.fixedPath); - } // intentionally only path and pathRegex @Override - public int hashCode() - { + public int hashCode() { int result = pathRegex.hashCode(); result = 31 * result + fixedPath.hashCode(); return result; } @Override - public String toString() - { - return "Schema{" + - "name='" + name + '\'' + - ", pathRegex=" + pathRegex + - ", path='" + fixedPath + '\'' + - ", documentation='" + documentation + '\'' + - ", dataValidator=" + schemaValidator.getClass() + - ", ephemeral=" + ephemeral + - ", sequential=" + sequential + - ", watched=" + watched + - ", canBeDeleted=" + canBeDeleted + - ", metadata=" + metadata + - '}'; + public String toString() { + return "Schema{" + "name='" + + name + '\'' + ", pathRegex=" + + pathRegex + ", path='" + + fixedPath + '\'' + ", documentation='" + + documentation + '\'' + ", dataValidator=" + + schemaValidator.getClass() + ", ephemeral=" + + ephemeral + ", sequential=" + + sequential + ", watched=" + + watched + ", canBeDeleted=" + + canBeDeleted + ", metadata=" + + metadata + '}'; } - public String toDocumentation() - { + public String toDocumentation() { String pathLabel = (pathRegex != null) ? "Path Regex: " : "Path: "; return "Name: " + name + '\n' - + pathLabel + getRawPath() + '\n' - + "Doc: " + documentation + '\n' - + "Validator: " + schemaValidator.getClass().getSimpleName() + '\n' - + "Meta: " + metadata + '\n' - + String.format("ephemeral: %s | sequential: %s | watched: %s | canBeDeleted: %s", ephemeral, sequential, watched, canBeDeleted) + '\n' - ; + + pathLabel + getRawPath() + '\n' + + "Doc: " + documentation + '\n' + + "Validator: " + schemaValidator.getClass().getSimpleName() + '\n' + + "Meta: " + metadata + '\n' + + String.format( + "ephemeral: %s | sequential: %s | watched: %s | canBeDeleted: %s", + ephemeral, sequential, watched, canBeDeleted) + + '\n'; } } diff --git a/curator-framework/src/main/java/org/apache/curator/framework/schema/SchemaBuilder.java b/curator-framework/src/main/java/org/apache/curator/framework/schema/SchemaBuilder.java index b477193ee..f8a0b94c0 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/schema/SchemaBuilder.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/schema/SchemaBuilder.java @@ -25,8 +25,7 @@ import java.util.UUID; import java.util.regex.Pattern; -public class SchemaBuilder -{ +public class SchemaBuilder { private final Pattern pathRegex; private final String path; private String name = UUID.randomUUID().toString(); @@ -43,17 +42,25 @@ public class SchemaBuilder * * @return new schema */ - public Schema build() - { - return new Schema(name, pathRegex, path, documentation, schemaValidator, ephemeral, sequential, watched, canBeDeleted, metadata); + public Schema build() { + return new Schema( + name, + pathRegex, + path, + documentation, + schemaValidator, + ephemeral, + sequential, + watched, + canBeDeleted, + metadata); } /** * @param name unique name for this schema * @return this for chaining */ - public SchemaBuilder name(String name) - { + public SchemaBuilder name(String name) { this.name = Preconditions.checkNotNull(name, "name cannot be null"); return this; } @@ -62,8 +69,7 @@ public SchemaBuilder name(String name) * @param documentation user displayable documentation for the schema * @return this for chaining */ - public SchemaBuilder documentation(String documentation) - { + public SchemaBuilder documentation(String documentation) { this.documentation = Preconditions.checkNotNull(documentation, "documentation cannot be null"); return this; } @@ -72,8 +78,7 @@ public SchemaBuilder documentation(String documentation) * @param schemaValidator a data validator - will be used to validate data set for the znode * @return this for chaining */ - public SchemaBuilder dataValidator(SchemaValidator schemaValidator) - { + public SchemaBuilder dataValidator(SchemaValidator schemaValidator) { this.schemaValidator = Preconditions.checkNotNull(schemaValidator, "dataValidator cannot be null"); return this; } @@ -82,8 +87,7 @@ public SchemaBuilder dataValidator(SchemaValidator schemaValidator) * @param ephemeral whether can, must or cannot be ephemeral * @return this for chaining */ - public SchemaBuilder ephemeral(Schema.Allowance ephemeral) - { + public SchemaBuilder ephemeral(Schema.Allowance ephemeral) { this.ephemeral = Preconditions.checkNotNull(ephemeral, "ephemeral cannot be null"); return this; } @@ -92,8 +96,7 @@ public SchemaBuilder ephemeral(Schema.Allowance ephemeral) * @param sequential whether can, must or cannot be sequential * @return this for chaining */ - public SchemaBuilder sequential(Schema.Allowance sequential) - { + public SchemaBuilder sequential(Schema.Allowance sequential) { this.sequential = Preconditions.checkNotNull(sequential, "sequential cannot be null"); return this; } @@ -102,8 +105,7 @@ public SchemaBuilder sequential(Schema.Allowance sequential) * @param watched whether can, must or cannot be watched * @return this for chaining */ - public SchemaBuilder watched(Schema.Allowance watched) - { + public SchemaBuilder watched(Schema.Allowance watched) { this.watched = watched; return this; } @@ -112,8 +114,7 @@ public SchemaBuilder watched(Schema.Allowance watched) * @param canBeDeleted true if znode can be deleted * @return this for chaining */ - public SchemaBuilder canBeDeleted(boolean canBeDeleted) - { + public SchemaBuilder canBeDeleted(boolean canBeDeleted) { this.canBeDeleted = canBeDeleted; return this; } @@ -122,14 +123,12 @@ public SchemaBuilder canBeDeleted(boolean canBeDeleted) * @param metadata any field -> value you want * @return this for chaining */ - public SchemaBuilder metadata(Map metadata) - { + public SchemaBuilder metadata(Map metadata) { this.metadata = ImmutableMap.copyOf(metadata); return this; } - SchemaBuilder(Pattern pathRegex, String path) - { + SchemaBuilder(Pattern pathRegex, String path) { this.pathRegex = pathRegex; this.path = path; } diff --git a/curator-framework/src/main/java/org/apache/curator/framework/schema/SchemaSet.java b/curator-framework/src/main/java/org/apache/curator/framework/schema/SchemaSet.java index af6eb29c5..ed9776669 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/schema/SchemaSet.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/schema/SchemaSet.java @@ -27,33 +27,28 @@ import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Maps; -import org.apache.curator.framework.CuratorFramework; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.concurrent.ExecutionException; +import org.apache.curator.framework.CuratorFramework; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * Collection of all schemas for a Curator instance */ -public class SchemaSet -{ +public class SchemaSet { private final Logger log = LoggerFactory.getLogger(getClass()); private final Map schemas; private final Map pathToSchemas; private final List regexSchemas; - private final CacheLoader cacheLoader = new CacheLoader() - { + private final CacheLoader cacheLoader = new CacheLoader() { @Override - public Schema load(String path) throws Exception - { - for ( Schema schema : regexSchemas ) - { - if ( schema.getPathRegex().matcher(path).matches() ) - { + public Schema load(String path) throws Exception { + for (Schema schema : regexSchemas) { + if (schema.getPathRegex().matcher(path).matches()) { log.debug("path -> {}", schema); return schema; } @@ -61,13 +56,31 @@ public Schema load(String path) throws Exception return nullSchema; } }; - private final LoadingCache regexCache = CacheBuilder - .newBuilder() - .softValues() - .build(cacheLoader); + private final LoadingCache regexCache = + CacheBuilder.newBuilder().softValues().build(cacheLoader); - private static final Schema nullSchema = new Schema("__null__", null, "", "Null schema", new DefaultSchemaValidator(), Schema.Allowance.CAN, Schema.Allowance.CAN, Schema.Allowance.CAN, true, ImmutableMap.of()); - private static final Schema defaultSchema = new Schema("__default__", null, "", "Default schema", new DefaultSchemaValidator(), Schema.Allowance.CAN, Schema.Allowance.CAN, Schema.Allowance.CAN, true, ImmutableMap.of()); + private static final Schema nullSchema = new Schema( + "__null__", + null, + "", + "Null schema", + new DefaultSchemaValidator(), + Schema.Allowance.CAN, + Schema.Allowance.CAN, + Schema.Allowance.CAN, + true, + ImmutableMap.of()); + private static final Schema defaultSchema = new Schema( + "__default__", + null, + "", + "Default schema", + new DefaultSchemaValidator(), + Schema.Allowance.CAN, + Schema.Allowance.CAN, + Schema.Allowance.CAN, + true, + ImmutableMap.of()); private final boolean useDefaultSchema; /** @@ -75,13 +88,10 @@ public Schema load(String path) throws Exception * * @return default schema set */ - public static SchemaSet getDefaultSchemaSet() - { - return new SchemaSet(Collections.emptyList(), true) - { + public static SchemaSet getDefaultSchemaSet() { + return new SchemaSet(Collections.emptyList(), true) { @Override - public String toDocumentation() - { + public String toDocumentation() { return "Default schema"; } }; @@ -97,29 +107,22 @@ public String toDocumentation() * @param schemas the schemas for the set. * @param useDefaultSchema if true, return a default schema when there is no match. Otherwise, an exception is thrown */ - public SchemaSet(List schemas, boolean useDefaultSchema) - { + public SchemaSet(List schemas, boolean useDefaultSchema) { schemas = Preconditions.checkNotNull(schemas, "schemas cannot be null"); this.useDefaultSchema = useDefaultSchema; - this.schemas = Maps.uniqueIndex(schemas, new Function() - { + this.schemas = Maps.uniqueIndex(schemas, new Function() { @Override - public String apply(Schema schema) - { + public String apply(Schema schema) { return schema.getName(); } }); ImmutableMap.Builder pathBuilder = ImmutableMap.builder(); ImmutableList.Builder regexBuilder = ImmutableList.builder(); - for ( Schema schema : schemas ) - { - if ( schema.getPath() != null ) - { + for (Schema schema : schemas) { + if (schema.getPath() != null) { pathBuilder.put(schema.getPath(), schema); - } - else - { + } else { regexBuilder.add(schema); } } @@ -132,8 +135,7 @@ public String apply(Schema schema) * * @return schemas */ - public Collection getSchemas() - { + public Collection getSchemas() { return schemas.values(); } @@ -143,36 +145,28 @@ public Collection getSchemas() * @param path ZNode full path * @return matching schema or a default schema */ - public Schema getSchema(String path) - { - if ( schemas.size() > 0 ) - { + public Schema getSchema(String path) { + if (schemas.size() > 0) { Schema schema = pathToSchemas.get(path); - if ( schema == null ) - { - try - { + if (schema == null) { + try { schema = regexCache.get(path); - if ( schema.equals(nullSchema) ) - { + if (schema.equals(nullSchema)) { schema = useDefaultSchema ? defaultSchema : null; } - } - catch ( ExecutionException e ) - { + } catch (ExecutionException e) { throw new RuntimeException(e); } } - if ( schema != null ) - { + if (schema != null) { return schema; } } - if ( useDefaultSchema ) - { + if (useDefaultSchema) { return defaultSchema; } - throw new SchemaViolation(null, new SchemaViolation.ViolatorData(path, null, null), "No schema found for: " + path); + throw new SchemaViolation( + null, new SchemaViolation.ViolatorData(path, null, null), "No schema found for: " + path); } /** @@ -182,8 +176,7 @@ public Schema getSchema(String path) * @param name path/schema name * @return ZNode path */ - public static String getNamedPath(CuratorFramework client, String name) - { + public static String getNamedPath(CuratorFramework client, String name) { return client.getSchemaSet().getNamedSchema(name).getRawPath(); } @@ -193,8 +186,7 @@ public static String getNamedPath(CuratorFramework client, String name) * @param name name * @return schema or null */ - public Schema getNamedSchema(String name) - { + public Schema getNamedSchema(String name) { return schemas.get(name); } @@ -203,12 +195,13 @@ public Schema getNamedSchema(String name) * * @return documentation */ - public String toDocumentation() - { + public String toDocumentation() { StringBuilder str = new StringBuilder("Curator Schemas:\n\n"); - for ( Map.Entry schemaEntry : schemas.entrySet() ) - { - str.append(schemaEntry.getKey()).append('\n').append(schemaEntry.getValue().toDocumentation()).append('\n'); + for (Map.Entry schemaEntry : schemas.entrySet()) { + str.append(schemaEntry.getKey()) + .append('\n') + .append(schemaEntry.getValue().toDocumentation()) + .append('\n'); } return str.toString(); } diff --git a/curator-framework/src/main/java/org/apache/curator/framework/schema/SchemaSetLoader.java b/curator-framework/src/main/java/org/apache/curator/framework/schema/SchemaSetLoader.java index fe4a5e14e..b3707b4c4 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/schema/SchemaSetLoader.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/schema/SchemaSetLoader.java @@ -63,15 +63,13 @@ * *

*/ -public class SchemaSetLoader -{ +public class SchemaSetLoader { private final List schemas; /** * Called to map a schema validator name in the JSON stream to an actual data validator */ - public interface SchemaValidatorMapper - { + public interface SchemaValidatorMapper { /** * @param name name of the validator * @return the validator @@ -83,8 +81,7 @@ public interface SchemaValidatorMapper * @param json the json to parse * @param schemaValidatorMapper mapper from validator name to instance - can be null if not needed */ - public SchemaSetLoader(String json, SchemaValidatorMapper schemaValidatorMapper) - { + public SchemaSetLoader(String json, SchemaValidatorMapper schemaValidatorMapper) { this(getRoot(new StringReader(json)), schemaValidatorMapper); } @@ -92,8 +89,7 @@ public SchemaSetLoader(String json, SchemaValidatorMapper schemaValidatorMapper) * @param jsonStream the json stream to parse * @param schemaValidatorMapper mapper from validator name to instance - can be null if not needed */ - public SchemaSetLoader(Reader jsonStream, SchemaValidatorMapper schemaValidatorMapper) - { + public SchemaSetLoader(Reader jsonStream, SchemaValidatorMapper schemaValidatorMapper) { this(getRoot(jsonStream), schemaValidatorMapper); } @@ -101,8 +97,7 @@ public SchemaSetLoader(Reader jsonStream, SchemaValidatorMapper schemaValidatorM * @param root a Jackson root node * @param schemaValidatorMapper mapper from validator name to instance - can be null if not needed */ - public SchemaSetLoader(JsonNode root, SchemaValidatorMapper schemaValidatorMapper) - { + public SchemaSetLoader(JsonNode root, SchemaValidatorMapper schemaValidatorMapper) { ImmutableList.Builder builder = ImmutableList.builder(); read(builder, root, schemaValidatorMapper); schemas = builder.build(); @@ -112,106 +107,90 @@ public SchemaSetLoader(JsonNode root, SchemaValidatorMapper schemaValidatorMappe * @param useDefaultSchema if true, return a default schema when there is no match. Otherwise, an exception is thrown * @return schema set */ - public SchemaSet toSchemaSet(boolean useDefaultSchema) - { + public SchemaSet toSchemaSet(boolean useDefaultSchema) { return new SchemaSet(schemas, useDefaultSchema); } - public List getSchemas() - { + public List getSchemas() { return schemas; } - private static JsonNode getRoot(Reader in) - { - try - { + private static JsonNode getRoot(Reader in) { + try { return new ObjectMapper().readTree(in); - } - catch ( IOException e ) - { + } catch (IOException e) { throw new RuntimeException(e); } } - private void read(ImmutableList.Builder builder, JsonNode node, SchemaValidatorMapper schemaValidatorMapper) - { - for ( JsonNode child : node ) - { + private void read( + ImmutableList.Builder builder, JsonNode node, SchemaValidatorMapper schemaValidatorMapper) { + for (JsonNode child : node) { readNode(builder, child, schemaValidatorMapper); } } - private void readNode(ImmutableList.Builder builder, JsonNode node, SchemaValidatorMapper schemaValidatorMapper) - { + private void readNode( + ImmutableList.Builder builder, JsonNode node, SchemaValidatorMapper schemaValidatorMapper) { String name = getText(node, "name", null); String path = getText(node, "path", null); boolean isRegex = getBoolean(node, "isRegex"); - if ( name == null ) - { + if (name == null) { throw new RuntimeException("name is required at: " + node); } - if ( path == null ) - { + if (path == null) { throw new RuntimeException("path is required at: " + node); } SchemaBuilder schemaBuilder = isRegex ? Schema.builder(Pattern.compile(path)) : Schema.builder(path); String schemaValidatorName = getText(node, "schemaValidator", null); - if ( schemaValidatorName != null ) - { - if ( schemaValidatorMapper == null ) - { + if (schemaValidatorName != null) { + if (schemaValidatorMapper == null) { throw new RuntimeException("No SchemaValidatorMapper provided but needed at: " + node); } schemaBuilder.dataValidator(schemaValidatorMapper.getSchemaValidator(schemaValidatorName)); } Map metadata = Maps.newHashMap(); - if ( node.has("metadata") ) - { + if (node.has("metadata")) { JsonNode metadataNode = node.get("metadata"); Iterator fieldNameIterator = metadataNode.fieldNames(); - while ( fieldNameIterator.hasNext() ) - { + while (fieldNameIterator.hasNext()) { String fieldName = fieldNameIterator.next(); metadata.put(fieldName, getText(metadataNode, fieldName, "")); } } - Schema schema = schemaBuilder.name(name) - .documentation(getText(node, "documentation", "")) - .ephemeral(getAllowance(node, "ephemeral")) - .sequential(getAllowance(node, "sequential")) - .watched(getAllowance(node, "watched")) - .canBeDeleted(getBoolean(node, "canBeDeleted")) - .metadata(metadata) - .build(); + Schema schema = schemaBuilder + .name(name) + .documentation(getText(node, "documentation", "")) + .ephemeral(getAllowance(node, "ephemeral")) + .sequential(getAllowance(node, "sequential")) + .watched(getAllowance(node, "watched")) + .canBeDeleted(getBoolean(node, "canBeDeleted")) + .metadata(metadata) + .build(); builder.add(schema); } - private String getText(JsonNode node, String name, String defaultValue) - { + private String getText(JsonNode node, String name, String defaultValue) { JsonNode namedNode = node.get(name); return (namedNode != null) ? namedNode.asText() : defaultValue; } - private boolean getBoolean(JsonNode node, String name) - { + private boolean getBoolean(JsonNode node, String name) { JsonNode namedNode = node.get(name); return (namedNode != null) && namedNode.asBoolean(); } - private Schema.Allowance getAllowance(JsonNode node, String name) - { + private Schema.Allowance getAllowance(JsonNode node, String name) { JsonNode namedNode = node.get(name); - try - { - return (namedNode != null) ? Schema.Allowance.valueOf(namedNode.asText().toUpperCase()) : Schema.Allowance.CAN; - } - catch ( IllegalArgumentException ignore ) - { + try { + return (namedNode != null) + ? Schema.Allowance.valueOf(namedNode.asText().toUpperCase()) + : Schema.Allowance.CAN; + } catch (IllegalArgumentException ignore) { throw new RuntimeException("Must be one of: " + Arrays.toString(Schema.Allowance.values()) + " at " + node); } } diff --git a/curator-framework/src/main/java/org/apache/curator/framework/schema/SchemaValidator.java b/curator-framework/src/main/java/org/apache/curator/framework/schema/SchemaValidator.java index a59c1500c..ecee293dd 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/schema/SchemaValidator.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/schema/SchemaValidator.java @@ -19,11 +19,10 @@ package org.apache.curator.framework.schema; -import org.apache.zookeeper.data.ACL; import java.util.List; +import org.apache.zookeeper.data.ACL; -public interface SchemaValidator -{ +public interface SchemaValidator { /** * @param schema the schema being validated * @param path the path being operated on diff --git a/curator-framework/src/main/java/org/apache/curator/framework/schema/SchemaViolation.java b/curator-framework/src/main/java/org/apache/curator/framework/schema/SchemaViolation.java index 8f77b34d8..49b62f31c 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/schema/SchemaViolation.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/schema/SchemaViolation.java @@ -20,15 +20,14 @@ package org.apache.curator.framework.schema; import com.google.common.collect.ImmutableList; -import org.apache.zookeeper.data.ACL; import java.util.Arrays; import java.util.List; +import org.apache.zookeeper.data.ACL; /** * Thrown by the various validation methods in a Schema */ -public class SchemaViolation extends RuntimeException -{ +public class SchemaViolation extends RuntimeException { private final Schema schema; private final String violation; private final ViolatorData violatorData; @@ -36,14 +35,12 @@ public class SchemaViolation extends RuntimeException /** * Data about the calling API that violated the schema */ - public static class ViolatorData - { + public static class ViolatorData { private final String path; private final byte[] data; private final List acl; - public ViolatorData(String path, byte[] data, List acl) - { + public ViolatorData(String path, byte[] data, List acl) { this.path = path; this.data = (data != null) ? Arrays.copyOf(data, data.length) : null; this.acl = (acl != null) ? ImmutableList.copyOf(acl) : null; @@ -54,8 +51,7 @@ public ViolatorData(String path, byte[] data, List acl) * * @return path or null */ - public String getPath() - { + public String getPath() { return path; } @@ -64,8 +60,7 @@ public String getPath() * * @return data or null */ - public byte[] getData() - { + public byte[] getData() { return data; } @@ -74,14 +69,12 @@ public byte[] getData() * * @return ACLs or null */ - public List getAcl() - { + public List getAcl() { return acl; } @Override - public String toString() - { + public String toString() { String dataString = (data != null) ? new String(data) : ""; return "ViolatorData{" + "path='" + path + '\'' + ", data=" + dataString + ", acl=" + acl + '}'; } @@ -91,8 +84,7 @@ public String toString() * @param violation the violation * @deprecated use {@link #SchemaViolation(Schema, ViolatorData, String)} instance */ - public SchemaViolation(String violation) - { + public SchemaViolation(String violation) { super(String.format("Schema violation: %s", violation)); this.schema = null; this.violation = violation; @@ -104,8 +96,7 @@ public SchemaViolation(String violation) * @param violation the violation * @deprecated use {@link #SchemaViolation(Schema, ViolatorData, String)} instance */ - public SchemaViolation(Schema schema, String violation) - { + public SchemaViolation(Schema schema, String violation) { super(String.format("Schema violation: %s for schema: %s", violation, schema)); this.schema = schema; this.violation = violation; @@ -117,37 +108,31 @@ public SchemaViolation(Schema schema, String violation) * @param violatorData data about the caller who violated the schema * @param violation the violation */ - public SchemaViolation(Schema schema, ViolatorData violatorData, String violation) - { + public SchemaViolation(Schema schema, ViolatorData violatorData, String violation) { super(toString(schema, violation, violatorData)); this.schema = schema; this.violation = violation; this.violatorData = violatorData; } - public Schema getSchema() - { + public Schema getSchema() { return schema; } - public String getViolation() - { + public String getViolation() { return violation; } - public ViolatorData getViolatorData() - { + public ViolatorData getViolatorData() { return violatorData; } @Override - public String toString() - { + public String toString() { return toString(schema, violation, violatorData) + super.toString(); } - private static String toString(Schema schema, String violation, ViolatorData violatorData) - { + private static String toString(Schema schema, String violation, ViolatorData violatorData) { return (violation != null ? violation : "") + " " + schema + " " + violatorData; } } diff --git a/curator-framework/src/main/java/org/apache/curator/framework/state/CircuitBreaker.java b/curator-framework/src/main/java/org/apache/curator/framework/state/CircuitBreaker.java index 77c3fc899..dec124eb4 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/state/CircuitBreaker.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/state/CircuitBreaker.java @@ -19,16 +19,15 @@ package org.apache.curator.framework.state; -import org.apache.curator.RetryPolicy; -import org.apache.curator.RetrySleeper; -import org.apache.curator.utils.ThreadUtils; import java.time.Duration; import java.util.Objects; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; +import org.apache.curator.RetryPolicy; +import org.apache.curator.RetrySleeper; +import org.apache.curator.utils.ThreadUtils; -class CircuitBreaker -{ +class CircuitBreaker { private final RetryPolicy retryPolicy; private final ScheduledExecutorService service; @@ -36,58 +35,49 @@ class CircuitBreaker private int retryCount = 0; private long startNanos = 0; - static CircuitBreaker build(RetryPolicy retryPolicy) - { - return new CircuitBreaker(retryPolicy, ThreadUtils.newSingleThreadScheduledExecutor("CircuitBreakingConnectionStateListener")); + static CircuitBreaker build(RetryPolicy retryPolicy) { + return new CircuitBreaker( + retryPolicy, ThreadUtils.newSingleThreadScheduledExecutor("CircuitBreakingConnectionStateListener")); } - static CircuitBreaker build(RetryPolicy retryPolicy, ScheduledExecutorService service) - { + static CircuitBreaker build(RetryPolicy retryPolicy, ScheduledExecutorService service) { return new CircuitBreaker(retryPolicy, service); } // IMPORTANT - all methods below MUST be guarded by synchronization - boolean isOpen() - { + boolean isOpen() { return isOpen; } - int getRetryCount() - { + int getRetryCount() { return retryCount; } - boolean tryToOpen(Runnable completion) - { - if ( isOpen ) - { + boolean tryToOpen(Runnable completion) { + if (isOpen) { return false; } isOpen = true; retryCount = 0; startNanos = System.nanoTime(); - if ( tryToRetry(completion) ) - { + if (tryToRetry(completion)) { return true; } close(); return false; } - boolean tryToRetry(Runnable completion) - { - if ( !isOpen ) - { + boolean tryToRetry(Runnable completion) { + if (!isOpen) { return false; } - long[] sleepTimeNanos = new long[]{0L}; + long[] sleepTimeNanos = new long[] {0L}; RetrySleeper retrySleeper = (time, unit) -> sleepTimeNanos[0] = unit.toNanos(time); Duration elapsedTime = Duration.ofNanos(System.nanoTime() - startNanos); - if ( retryPolicy.allowRetry(retryCount, elapsedTime.toMillis(), retrySleeper) ) - { + if (retryPolicy.allowRetry(retryCount, elapsedTime.toMillis(), retrySleeper)) { ++retryCount; service.schedule(completion, sleepTimeNanos[0], TimeUnit.NANOSECONDS); return true; @@ -95,8 +85,7 @@ boolean tryToRetry(Runnable completion) return false; } - boolean close() - { + boolean close() { boolean wasOpen = isOpen; retryCount = 0; isOpen = false; @@ -104,8 +93,7 @@ boolean close() return wasOpen; } - private CircuitBreaker(RetryPolicy retryPolicy, ScheduledExecutorService service) - { + private CircuitBreaker(RetryPolicy retryPolicy, ScheduledExecutorService service) { this.retryPolicy = Objects.requireNonNull(retryPolicy, "retryPolicy cannot be null"); this.service = Objects.requireNonNull(service, "service cannot be null"); } diff --git a/curator-framework/src/main/java/org/apache/curator/framework/state/CircuitBreakingConnectionStateListener.java b/curator-framework/src/main/java/org/apache/curator/framework/state/CircuitBreakingConnectionStateListener.java index 5be1adb34..b3702bc49 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/state/CircuitBreakingConnectionStateListener.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/state/CircuitBreakingConnectionStateListener.java @@ -19,12 +19,12 @@ package org.apache.curator.framework.state; +import java.util.Objects; +import java.util.concurrent.ScheduledExecutorService; import org.apache.curator.RetryPolicy; import org.apache.curator.framework.CuratorFramework; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.util.Objects; -import java.util.concurrent.ScheduledExecutorService; /** *

@@ -73,8 +73,7 @@ * *

*/ -public class CircuitBreakingConnectionStateListener implements ConnectionStateListener -{ +public class CircuitBreakingConnectionStateListener implements ConnectionStateListener { private final Logger log = LoggerFactory.getLogger(getClass()); private final CuratorFramework client; private final ConnectionStateListener listener; @@ -92,8 +91,8 @@ public class CircuitBreakingConnectionStateListener implements ConnectionStateLi * @param listener listener to manage * @param retryPolicy breaking policy to use */ - public CircuitBreakingConnectionStateListener(CuratorFramework client, ConnectionStateListener listener, RetryPolicy retryPolicy) - { + public CircuitBreakingConnectionStateListener( + CuratorFramework client, ConnectionStateListener listener, RetryPolicy retryPolicy) { this(client, listener, CircuitBreaker.build(retryPolicy)); } @@ -103,13 +102,16 @@ public CircuitBreakingConnectionStateListener(CuratorFramework client, Connectio * @param retryPolicy breaking policy to use * @param service scheduler to use */ - public CircuitBreakingConnectionStateListener(CuratorFramework client, ConnectionStateListener listener, RetryPolicy retryPolicy, ScheduledExecutorService service) - { + public CircuitBreakingConnectionStateListener( + CuratorFramework client, + ConnectionStateListener listener, + RetryPolicy retryPolicy, + ScheduledExecutorService service) { this(client, listener, CircuitBreaker.build(retryPolicy, service)); } - CircuitBreakingConnectionStateListener(CuratorFramework client, ConnectionStateListener listener, CircuitBreaker circuitBreaker) - { + CircuitBreakingConnectionStateListener( + CuratorFramework client, ConnectionStateListener listener, CircuitBreaker circuitBreaker) { this.client = Objects.requireNonNull(client, "client cannot be null"); this.listener = Objects.requireNonNull(listener, "listener cannot be null"); this.circuitBreaker = Objects.requireNonNull(circuitBreaker, "circuitBreaker cannot be null"); @@ -117,14 +119,10 @@ public CircuitBreakingConnectionStateListener(CuratorFramework client, Connectio } @Override - public synchronized void stateChanged(CuratorFramework client, ConnectionState newState) - { - if ( circuitBreaker.isOpen() ) - { + public synchronized void stateChanged(CuratorFramework client, ConnectionState newState) { + if (circuitBreaker.isOpen()) { handleOpenStateChange(newState); - } - else - { + } else { handleClosedStateChange(newState); } } @@ -134,38 +132,28 @@ public synchronized void stateChanged(CuratorFramework client, ConnectionState n * * @return true/false */ - public synchronized boolean isOpen() - { + public synchronized boolean isOpen() { return circuitBreaker.isOpen(); } - private synchronized void handleClosedStateChange(ConnectionState newState) - { - if ( !newState.isConnected() ) - { - if ( circuitBreaker.tryToOpen(this::checkCloseCircuit) ) - { + private synchronized void handleClosedStateChange(ConnectionState newState) { + if (!newState.isConnected()) { + if (circuitBreaker.tryToOpen(this::checkCloseCircuit)) { log.info("Circuit is opening. State: {} post-retryCount: {}", newState, circuitBreaker.getRetryCount()); circuitLastState = circuitInitialState = newState; circuitLostHasBeenSent = (newState == ConnectionState.LOST); - } - else - { + } else { log.debug("Could not open circuit breaker. State: {}", newState); } } callListener(newState); } - private synchronized void handleOpenStateChange(ConnectionState newState) - { - if ( circuitLostHasBeenSent || (newState != ConnectionState.LOST) ) - { + private synchronized void handleOpenStateChange(ConnectionState newState) { + if (circuitLostHasBeenSent || (newState != ConnectionState.LOST)) { log.debug("Circuit is open. Ignoring state change: {}", newState); circuitLastState = newState; - } - else - { + } else { log.debug("Circuit is open. State changed to LOST. Sending to listener."); circuitLostHasBeenSent = true; circuitLastState = circuitInitialState = ConnectionState.LOST; @@ -173,41 +161,37 @@ private synchronized void handleOpenStateChange(ConnectionState newState) } } - private synchronized void checkCloseCircuit() - { - if ( (circuitLastState == null) || circuitLastState.isConnected() ) - { + private synchronized void checkCloseCircuit() { + if ((circuitLastState == null) || circuitLastState.isConnected()) { log.info("Circuit is closing. Initial state: {} - Last state: {}", circuitInitialState, circuitLastState); closeCircuit(); - } - else if ( circuitBreaker.tryToRetry(this::checkCloseCircuit) ) - { - log.debug("Circuit open is continuing due to retry. State: {} post-retryCount: {}", circuitLastState, circuitBreaker.getRetryCount()); - } - else - { - log.info("Circuit is closing due to retries exhausted. Initial state: {} - Last state: {}", circuitInitialState, circuitLastState); + } else if (circuitBreaker.tryToRetry(this::checkCloseCircuit)) { + log.debug( + "Circuit open is continuing due to retry. State: {} post-retryCount: {}", + circuitLastState, + circuitBreaker.getRetryCount()); + } else { + log.info( + "Circuit is closing due to retries exhausted. Initial state: {} - Last state: {}", + circuitInitialState, + circuitLastState); closeCircuit(); } } - private synchronized void callListener(ConnectionState newState) - { - if ( newState != null ) - { + private synchronized void callListener(ConnectionState newState) { + if (newState != null) { listener.stateChanged(client, newState); } } - private synchronized void closeCircuit() - { + private synchronized void closeCircuit() { ConnectionState stateToSend = (circuitLastState == circuitInitialState) ? null : circuitLastState; reset(); callListener(stateToSend); } - private synchronized void reset() - { + private synchronized void reset() { circuitLastState = null; circuitInitialState = null; circuitLostHasBeenSent = false; diff --git a/curator-framework/src/main/java/org/apache/curator/framework/state/CircuitBreakingManager.java b/curator-framework/src/main/java/org/apache/curator/framework/state/CircuitBreakingManager.java index 07fd860f8..259309218 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/state/CircuitBreakingManager.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/state/CircuitBreakingManager.java @@ -19,73 +19,61 @@ package org.apache.curator.framework.state; +import java.util.concurrent.Executor; +import java.util.function.Consumer; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.listen.StandardListenerManager; import org.apache.curator.framework.listen.UnaryListenerManager; -import java.util.concurrent.Executor; -import java.util.function.Consumer; -class CircuitBreakingManager implements UnaryListenerManager -{ +class CircuitBreakingManager implements UnaryListenerManager { private final StandardListenerManager mainContainer = StandardListenerManager.standard(); - private final StandardListenerManager doNotProxyContainer = StandardListenerManager.standard(); + private final StandardListenerManager doNotProxyContainer = + StandardListenerManager.standard(); private final CircuitBreakingConnectionStateListener masterListener; - CircuitBreakingManager(CuratorFramework client, CircuitBreaker circuitBreaker) - { - ConnectionStateListener masterStateChanged = (__, newState) -> mainContainer.forEach(listener -> listener.stateChanged(client, newState)); + CircuitBreakingManager(CuratorFramework client, CircuitBreaker circuitBreaker) { + ConnectionStateListener masterStateChanged = + (__, newState) -> mainContainer.forEach(listener -> listener.stateChanged(client, newState)); masterListener = new CircuitBreakingConnectionStateListener(client, masterStateChanged, circuitBreaker); } @Override - public void clear() - { + public void clear() { doNotProxyContainer.clear(); mainContainer.clear(); } @Override - public int size() - { + public int size() { return mainContainer.size() + doNotProxyContainer.size(); } @Override - public void forEach(Consumer function) - { + public void forEach(Consumer function) { doNotProxyContainer.forEach(function); function.accept(masterListener); } @Override - public void addListener(ConnectionStateListener listener) - { - if ( listener.doNotProxy() ) - { + public void addListener(ConnectionStateListener listener) { + if (listener.doNotProxy()) { doNotProxyContainer.addListener(listener); - } - else - { + } else { mainContainer.addListener(listener); } } @Override - public void addListener(ConnectionStateListener listener, Executor executor) - { - if ( listener.doNotProxy() ) - { + public void addListener(ConnectionStateListener listener, Executor executor) { + if (listener.doNotProxy()) { doNotProxyContainer.addListener(listener, executor); - } - else - { + } else { mainContainer.addListener(listener, executor); } } @Override - public void removeListener(ConnectionStateListener listener) - { + public void removeListener(ConnectionStateListener listener) { mainContainer.removeListener(listener); doNotProxyContainer.removeListener(listener); } diff --git a/curator-framework/src/main/java/org/apache/curator/framework/state/ConnectionState.java b/curator-framework/src/main/java/org/apache/curator/framework/state/ConnectionState.java index 587a76e52..d099f3ec7 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/state/ConnectionState.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/state/ConnectionState.java @@ -26,16 +26,13 @@ /** * Represents state changes in the connection to ZK */ -public enum ConnectionState -{ +public enum ConnectionState { /** * Sent for the first successful connection to the server. NOTE: You will only * get one of these messages for any CuratorFramework instance. */ - CONNECTED - { - public boolean isConnected() - { + CONNECTED { + public boolean isConnected() { return true; } }, @@ -44,10 +41,8 @@ public boolean isConnected() * There has been a loss of connection. Leaders, locks, etc. should suspend * until the connection is re-established. */ - SUSPENDED - { - public boolean isConnected() - { + SUSPENDED { + public boolean isConnected() { return false; } }, @@ -55,10 +50,8 @@ public boolean isConnected() /** * A suspended, lost, or read-only connection has been re-established */ - RECONNECTED - { - public boolean isConnected() - { + RECONNECTED { + public boolean isConnected() { return true; } }, @@ -74,10 +67,8 @@ public boolean isConnected() * elapses during a network partition. *

*/ - LOST - { - public boolean isConnected() - { + LOST { + public boolean isConnected() { return false; } }, @@ -89,15 +80,11 @@ public boolean isConnected() * http://wiki.apache.org/hadoop/ZooKeeper/GSoCReadOnlyMode. * The connection will remain in read only mode until another state change is sent. */ - READ_ONLY - { - public boolean isConnected() - { + READ_ONLY { + public boolean isConnected() { return true; } - } - - ; + }; /** * Check if this state indicates that Curator has a connection to ZooKeeper diff --git a/curator-framework/src/main/java/org/apache/curator/framework/state/ConnectionStateErrorPolicy.java b/curator-framework/src/main/java/org/apache/curator/framework/state/ConnectionStateErrorPolicy.java index a44cbd3ea..075d81b3c 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/state/ConnectionStateErrorPolicy.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/state/ConnectionStateErrorPolicy.java @@ -25,8 +25,7 @@ * * @since 3.0.0 */ -public interface ConnectionStateErrorPolicy -{ +public interface ConnectionStateErrorPolicy { /** * Returns true if the given state should cause the recipe to * act as though the connection has been lost. i.e. locks should diff --git a/curator-framework/src/main/java/org/apache/curator/framework/state/ConnectionStateListener.java b/curator-framework/src/main/java/org/apache/curator/framework/state/ConnectionStateListener.java index 573ffedc3..62be250f1 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/state/ConnectionStateListener.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/state/ConnectionStateListener.java @@ -21,8 +21,7 @@ import org.apache.curator.framework.CuratorFramework; -public interface ConnectionStateListener -{ +public interface ConnectionStateListener { /** * Called when there is a state change in the connection * @@ -39,8 +38,7 @@ public interface ConnectionStateListener * * @return true/false */ - default boolean doNotProxy() - { + default boolean doNotProxy() { return false; } } diff --git a/curator-framework/src/main/java/org/apache/curator/framework/state/ConnectionStateListenerManagerFactory.java b/curator-framework/src/main/java/org/apache/curator/framework/state/ConnectionStateListenerManagerFactory.java index 325e60ec1..de67f5a55 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/state/ConnectionStateListenerManagerFactory.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/state/ConnectionStateListenerManagerFactory.java @@ -19,15 +19,14 @@ package org.apache.curator.framework.state; +import java.util.concurrent.ScheduledExecutorService; import org.apache.curator.RetryPolicy; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.listen.StandardListenerManager; import org.apache.curator.framework.listen.UnaryListenerManager; -import java.util.concurrent.ScheduledExecutorService; @FunctionalInterface -public interface ConnectionStateListenerManagerFactory -{ +public interface ConnectionStateListenerManagerFactory { /** * Create a new listener manager * @@ -49,8 +48,7 @@ public interface ConnectionStateListenerManagerFactory * @param retryPolicy the circuit breaking policy to use * @return new listener manager factory */ - static ConnectionStateListenerManagerFactory circuitBreaking(RetryPolicy retryPolicy) - { + static ConnectionStateListenerManagerFactory circuitBreaking(RetryPolicy retryPolicy) { return client -> new CircuitBreakingManager(client, CircuitBreaker.build(retryPolicy)); } @@ -63,8 +61,8 @@ static ConnectionStateListenerManagerFactory circuitBreaking(RetryPolicy retryPo * @param service the scheduler to use * @return new listener manager factory */ - static ConnectionStateListenerManagerFactory circuitBreaking(RetryPolicy retryPolicy, ScheduledExecutorService service) - { + static ConnectionStateListenerManagerFactory circuitBreaking( + RetryPolicy retryPolicy, ScheduledExecutorService service) { return client -> new CircuitBreakingManager(client, CircuitBreaker.build(retryPolicy, service)); } } diff --git a/curator-framework/src/main/java/org/apache/curator/framework/state/ConnectionStateManager.java b/curator-framework/src/main/java/org/apache/curator/framework/state/ConnectionStateManager.java index 17d32d0ad..ac963a213 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/state/ConnectionStateManager.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/state/ConnectionStateManager.java @@ -20,12 +20,6 @@ package org.apache.curator.framework.state; import com.google.common.base.Preconditions; -import org.apache.curator.framework.CuratorFramework; -import org.apache.curator.framework.listen.Listenable; -import org.apache.curator.framework.listen.UnaryListenerManager; -import org.apache.curator.utils.ThreadUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import java.io.Closeable; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; @@ -36,26 +30,26 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; +import org.apache.curator.framework.CuratorFramework; +import org.apache.curator.framework.listen.Listenable; +import org.apache.curator.framework.listen.UnaryListenerManager; +import org.apache.curator.utils.ThreadUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * Used internally to manage connection state */ -public class ConnectionStateManager implements Closeable -{ +public class ConnectionStateManager implements Closeable { private static final int QUEUE_SIZE; - static - { + static { int size = 25; String property = System.getProperty("ConnectionStateManagerSize", null); - if ( property != null ) - { - try - { + if (property != null) { + try { size = Integer.parseInt(property); - } - catch ( NumberFormatException ignore ) - { + } catch (NumberFormatException ignore) { // ignore } } @@ -79,8 +73,7 @@ public class ConnectionStateManager implements Closeable private volatile long lastExpiredInstanceIndex = -1; - private enum State - { + private enum State { LATENT, STARTED, CLOSED @@ -92,9 +85,14 @@ private enum State * @param sessionTimeoutMs the ZK session timeout in milliseconds * @param sessionExpirationPercent percentage of negotiated session timeout to use when simulating a session timeout. 0 means don't simulate at all */ - public ConnectionStateManager(CuratorFramework client, ThreadFactory threadFactory, int sessionTimeoutMs, int sessionExpirationPercent) - { - this(client, threadFactory, sessionTimeoutMs, sessionExpirationPercent, ConnectionStateListenerManagerFactory.standard); + public ConnectionStateManager( + CuratorFramework client, ThreadFactory threadFactory, int sessionTimeoutMs, int sessionExpirationPercent) { + this( + client, + threadFactory, + sessionTimeoutMs, + sessionExpirationPercent, + ConnectionStateListenerManagerFactory.standard); } /** @@ -104,13 +102,16 @@ public ConnectionStateManager(CuratorFramework client, ThreadFactory threadFacto * @param sessionExpirationPercent percentage of negotiated session timeout to use when simulating a session timeout. 0 means don't simulate at all * @param managerFactory manager factory to use */ - public ConnectionStateManager(CuratorFramework client, ThreadFactory threadFactory, int sessionTimeoutMs, int sessionExpirationPercent, ConnectionStateListenerManagerFactory managerFactory) - { + public ConnectionStateManager( + CuratorFramework client, + ThreadFactory threadFactory, + int sessionTimeoutMs, + int sessionExpirationPercent, + ConnectionStateListenerManagerFactory managerFactory) { this.client = client; this.sessionTimeoutMs = sessionTimeoutMs; this.sessionExpirationPercent = sessionExpirationPercent; - if ( threadFactory == null ) - { + if (threadFactory == null) { threadFactory = ThreadUtils.newThreadFactory("ConnectionStateManager"); } service = Executors.newSingleThreadExecutor(threadFactory); @@ -120,29 +121,21 @@ public ConnectionStateManager(CuratorFramework client, ThreadFactory threadFacto /** * Start the manager */ - public void start() - { + public void start() { Preconditions.checkState(state.compareAndSet(State.LATENT, State.STARTED), "Cannot be started more than once"); - service.submit - ( - new Callable() - { - @Override - public Object call() throws Exception - { - processEvents(); - return null; - } - } - ); + service.submit(new Callable() { + @Override + public Object call() throws Exception { + processEvents(); + return null; + } + }); } @Override - public void close() - { - if ( state.compareAndSet(State.STARTED, State.CLOSED) ) - { + public void close() { + if (state.compareAndSet(State.STARTED, State.CLOSED)) { service.shutdownNow(); listeners.clear(); } @@ -154,8 +147,7 @@ public void close() * @return listenable * @since 4.2.0 return type has changed from ListenerContainer to Listenable */ - public Listenable getListenable() - { + public Listenable getListenable() { return listeners; } @@ -164,15 +156,12 @@ public Listenable getListenable() * * @return true if connection is set to SUSPENDED */ - public synchronized boolean setToSuspended() - { - if ( state.get() != State.STARTED ) - { + public synchronized boolean setToSuspended() { + if (state.get() != State.STARTED) { return false; } - if ( (currentConnectionState == ConnectionState.LOST) || (currentConnectionState == ConnectionState.SUSPENDED) ) - { + if ((currentConnectionState == ConnectionState.LOST) || (currentConnectionState == ConnectionState.SUSPENDED)) { return false; } @@ -189,24 +178,22 @@ public synchronized boolean setToSuspended() * @param newConnectionState new state * @return true if the state actually changed, false if it was already at that state */ - public synchronized boolean addStateChange(ConnectionState newConnectionState) - { - if ( state.get() != State.STARTED ) - { + public synchronized boolean addStateChange(ConnectionState newConnectionState) { + if (state.get() != State.STARTED) { return false; } ConnectionState previousState = currentConnectionState; - if ( previousState == newConnectionState ) - { + if (previousState == newConnectionState) { return false; } setCurrentConnectionState(newConnectionState); ConnectionState localState = newConnectionState; - boolean isNegativeMessage = ((newConnectionState == ConnectionState.LOST) || (newConnectionState == ConnectionState.SUSPENDED) || (newConnectionState == ConnectionState.READ_ONLY)); - if ( !isNegativeMessage && initialConnectMessageSent.compareAndSet(false, true) ) - { + boolean isNegativeMessage = ((newConnectionState == ConnectionState.LOST) + || (newConnectionState == ConnectionState.SUSPENDED) + || (newConnectionState == ConnectionState.READ_ONLY)); + if (!isNegativeMessage && initialConnectMessageSent.compareAndSet(false, true)) { localState = ConnectionState.CONNECTED; } @@ -215,92 +202,75 @@ public synchronized boolean addStateChange(ConnectionState newConnectionState) return true; } - public synchronized boolean blockUntilConnected(int maxWaitTime, TimeUnit units) throws InterruptedException - { + public synchronized boolean blockUntilConnected(int maxWaitTime, TimeUnit units) throws InterruptedException { long startTime = System.currentTimeMillis(); boolean hasMaxWait = (units != null); long maxWaitTimeMs = hasMaxWait ? TimeUnit.MILLISECONDS.convert(maxWaitTime, units) : 0; - while ( !isConnected() ) - { - if ( hasMaxWait ) - { + while (!isConnected()) { + if (hasMaxWait) { long waitTime = maxWaitTimeMs - (System.currentTimeMillis() - startTime); - if ( waitTime <= 0 ) - { + if (waitTime <= 0) { return isConnected(); } wait(waitTime); - } - else - { + } else { wait(); } } return isConnected(); } - public synchronized boolean isConnected() - { + public synchronized boolean isConnected() { return (currentConnectionState != null) && currentConnectionState.isConnected(); } - private void postState(ConnectionState state) - { + private void postState(ConnectionState state) { log.info("State change: " + state); notifyAll(); - while ( !eventQueue.offer(state) ) - { + while (!eventQueue.offer(state)) { eventQueue.poll(); log.warn("ConnectionStateManager queue full - dropping events to make room"); } } - private void processEvents() - { - while ( state.get() == State.STARTED ) - { - try - { + private void processEvents() { + while (state.get() == State.STARTED) { + try { int useSessionTimeoutMs = getUseSessionTimeoutMs(); - long elapsedMs = startOfSuspendedEpoch == 0 ? useSessionTimeoutMs / 2 : System.currentTimeMillis() - startOfSuspendedEpoch; + long elapsedMs = startOfSuspendedEpoch == 0 + ? useSessionTimeoutMs / 2 + : System.currentTimeMillis() - startOfSuspendedEpoch; long pollMaxMs = useSessionTimeoutMs - elapsedMs; final ConnectionState newState = eventQueue.poll(pollMaxMs, TimeUnit.MILLISECONDS); - if ( newState != null ) - { - if ( listeners.isEmpty() ) - { + if (newState != null) { + if (listeners.isEmpty()) { log.warn("There are no ConnectionStateListeners registered."); } listeners.forEach(listener -> listener.stateChanged(client, newState)); - } - else if ( sessionExpirationPercent > 0 ) - { - synchronized(this) - { + } else if (sessionExpirationPercent > 0) { + synchronized (this) { checkSessionExpiration(); } } - synchronized(this) - { - if ( (currentConnectionState == ConnectionState.LOST) && client.getZookeeperClient().isConnected() ) - { - // CURATOR-525 - there is a race whereby LOST is sometimes set after the connection has been repaired + synchronized (this) { + if ((currentConnectionState == ConnectionState.LOST) + && client.getZookeeperClient().isConnected()) { + // CURATOR-525 - there is a race whereby LOST is sometimes set after the connection has been + // repaired // this "hack" fixes it by forcing the state to RECONNECTED log.warn("ConnectionState is LOST but isConnected() is true. Forcing RECONNECTED."); addStateChange(ConnectionState.RECONNECTED); } } - } - catch ( InterruptedException e ) - { + } catch (InterruptedException e) { // swallow the interrupt as it's only possible from either a background // operation and, thus, doesn't apply to this loop or the instance // is being closed in which case the while test will get it @@ -308,57 +278,52 @@ else if ( sessionExpirationPercent > 0 ) } } - private void checkSessionExpiration() - { - if ( (currentConnectionState == ConnectionState.SUSPENDED) && (startOfSuspendedEpoch != 0) ) - { + private void checkSessionExpiration() { + if ((currentConnectionState == ConnectionState.SUSPENDED) && (startOfSuspendedEpoch != 0)) { long elapsedMs = System.currentTimeMillis() - startOfSuspendedEpoch; int useSessionTimeoutMs = getUseSessionTimeoutMs(); - if ( elapsedMs >= useSessionTimeoutMs ) - { - startOfSuspendedEpoch = System.currentTimeMillis(); // reset startOfSuspendedEpoch to avoid spinning on this session expiration injection CURATOR-405 - log.warn(String.format("Session timeout has elapsed while SUSPENDED. Injecting a session expiration. Elapsed ms: %d. Adjusted session timeout ms: %d", elapsedMs, useSessionTimeoutMs)); - try - { + if (elapsedMs >= useSessionTimeoutMs) { + startOfSuspendedEpoch = + System.currentTimeMillis(); // reset startOfSuspendedEpoch to avoid spinning on this session + // expiration injection CURATOR-405 + log.warn(String.format( + "Session timeout has elapsed while SUSPENDED. Injecting a session expiration. Elapsed ms: %d. Adjusted session timeout ms: %d", + elapsedMs, useSessionTimeoutMs)); + try { if (lastExpiredInstanceIndex == client.getZookeeperClient().getInstanceIndex()) { - // last expiration didn't work for this instance, so event thread is dead and a reset is needed. CURATOR-561 + // last expiration didn't work for this instance, so event thread is dead and a reset is needed. + // CURATOR-561 client.getZookeeperClient().reset(); } else { lastExpiredInstanceIndex = client.getZookeeperClient().getInstanceIndex(); client.getZookeeperClient().getZooKeeper().getTestable().injectSessionExpiration(); } - } - catch ( Exception e ) - { + } catch (Exception e) { log.error("Could not inject session expiration", e); } } - } - else if ( currentConnectionState == ConnectionState.LOST ) - { - try - { + } else if (currentConnectionState == ConnectionState.LOST) { + try { // give ConnectionState.checkTimeouts() a chance to run, reset ensemble providers, etc. client.getZookeeperClient().getZooKeeper(); - } - catch ( Exception e ) - { + } catch (Exception e) { log.error("Could not get ZooKeeper", e); } } } - private void setCurrentConnectionState(ConnectionState newConnectionState) - { + private void setCurrentConnectionState(ConnectionState newConnectionState) { currentConnectionState = newConnectionState; startOfSuspendedEpoch = (currentConnectionState == ConnectionState.SUSPENDED) ? System.currentTimeMillis() : 0; } private int getUseSessionTimeoutMs() { int lastNegotiatedSessionTimeoutMs = client.getZookeeperClient().getLastNegotiatedSessionTimeoutMs(); - int useSessionTimeoutMs = (lastNegotiatedSessionTimeoutMs > 0) ? lastNegotiatedSessionTimeoutMs : sessionTimeoutMs; - useSessionTimeoutMs = sessionExpirationPercent > 0 && startOfSuspendedEpoch != 0 ? (useSessionTimeoutMs * sessionExpirationPercent) / 100 : useSessionTimeoutMs; + int useSessionTimeoutMs = + (lastNegotiatedSessionTimeoutMs > 0) ? lastNegotiatedSessionTimeoutMs : sessionTimeoutMs; + useSessionTimeoutMs = sessionExpirationPercent > 0 && startOfSuspendedEpoch != 0 + ? (useSessionTimeoutMs * sessionExpirationPercent) / 100 + : useSessionTimeoutMs; return useSessionTimeoutMs; } - } diff --git a/curator-framework/src/main/java/org/apache/curator/framework/state/SessionConnectionStateErrorPolicy.java b/curator-framework/src/main/java/org/apache/curator/framework/state/SessionConnectionStateErrorPolicy.java index 0a78ad9f5..c98a726e3 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/state/SessionConnectionStateErrorPolicy.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/state/SessionConnectionStateErrorPolicy.java @@ -22,11 +22,9 @@ /** * This policy treats only {@link ConnectionState#LOST} as an error */ -public class SessionConnectionStateErrorPolicy implements ConnectionStateErrorPolicy -{ +public class SessionConnectionStateErrorPolicy implements ConnectionStateErrorPolicy { @Override - public boolean isErrorState(ConnectionState state) - { + public boolean isErrorState(ConnectionState state) { return state == ConnectionState.LOST; } } diff --git a/curator-framework/src/main/java/org/apache/curator/framework/state/StandardConnectionStateErrorPolicy.java b/curator-framework/src/main/java/org/apache/curator/framework/state/StandardConnectionStateErrorPolicy.java index 87f4408cb..e2bc4017d 100644 --- a/curator-framework/src/main/java/org/apache/curator/framework/state/StandardConnectionStateErrorPolicy.java +++ b/curator-framework/src/main/java/org/apache/curator/framework/state/StandardConnectionStateErrorPolicy.java @@ -23,11 +23,9 @@ * This policy treats {@link ConnectionState#SUSPENDED} and {@link ConnectionState#LOST} * as errors */ -public class StandardConnectionStateErrorPolicy implements ConnectionStateErrorPolicy -{ +public class StandardConnectionStateErrorPolicy implements ConnectionStateErrorPolicy { @Override - public boolean isErrorState(ConnectionState state) - { + public boolean isErrorState(ConnectionState state) { return ((state == ConnectionState.SUSPENDED) || (state == ConnectionState.LOST)); } } diff --git a/curator-framework/src/test/java/org/apache/curator/framework/ensemble/TestEnsembleProvider.java b/curator-framework/src/test/java/org/apache/curator/framework/ensemble/TestEnsembleProvider.java index 7646603f4..d65bec9ba 100644 --- a/curator-framework/src/test/java/org/apache/curator/framework/ensemble/TestEnsembleProvider.java +++ b/curator-framework/src/test/java/org/apache/curator/framework/ensemble/TestEnsembleProvider.java @@ -20,7 +20,8 @@ package org.apache.curator.framework.ensemble; import static org.junit.jupiter.api.Assertions.assertTrue; - +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Semaphore; import org.apache.curator.ensemble.EnsembleProvider; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; @@ -33,55 +34,40 @@ import org.apache.curator.utils.CloseableUtils; import org.junit.jupiter.api.Test; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.Semaphore; - -public class TestEnsembleProvider extends BaseClassForTests -{ +public class TestEnsembleProvider extends BaseClassForTests { private final Timing timing = new Timing(); @Test - public void testBasic() - { + public void testBasic() { Semaphore counter = new Semaphore(0); final CuratorFramework client = newClient(counter); - try - { + try { client.start(); assertTrue(timing.acquireSemaphore(counter)); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } @Test - public void testAfterSessionExpiration() throws Exception - { + public void testAfterSessionExpiration() throws Exception { TestingServer oldServer = server; Semaphore counter = new Semaphore(0); final CuratorFramework client = newClient(counter); - try - { + try { final CountDownLatch connectedLatch = new CountDownLatch(1); final CountDownLatch lostLatch = new CountDownLatch(1); final CountDownLatch reconnectedLatch = new CountDownLatch(1); - ConnectionStateListener listener = new ConnectionStateListener() - { + ConnectionStateListener listener = new ConnectionStateListener() { @Override - public void stateChanged(CuratorFramework client, ConnectionState newState) - { - if ( newState == ConnectionState.CONNECTED ) - { + public void stateChanged(CuratorFramework client, ConnectionState newState) { + if (newState == ConnectionState.CONNECTED) { connectedLatch.countDown(); } - if ( newState == ConnectionState.LOST ) - { + if (newState == ConnectionState.LOST) { lostLatch.countDown(); } - if ( newState == ConnectionState.RECONNECTED ) - { + if (newState == ConnectionState.RECONNECTED) { reconnectedLatch.countDown(); } } @@ -95,69 +81,59 @@ public void stateChanged(CuratorFramework client, ConnectionState newState) assertTrue(timing.awaitLatch(lostLatch)); counter.drainPermits(); - for ( int i = 0; i < 5; ++i ) - { + for (int i = 0; i < 5; ++i) { // the ensemble provider should still be called periodically when the connection is lost assertTrue(timing.acquireSemaphore(counter), "Failed when i is: " + i); } - server = new TestingServer(); // this changes the CountingEnsembleProvider's value for getConnectionString() - connection should notice this and recover + server = new TestingServer(); // this changes the CountingEnsembleProvider's value for getConnectionString() + // - connection should notice this and recover assertTrue(timing.awaitLatch(reconnectedLatch)); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); CloseableUtils.closeQuietly(oldServer); } } - private CuratorFramework newClient(Semaphore counter) - { + private CuratorFramework newClient(Semaphore counter) { return CuratorFrameworkFactory.builder() - .ensembleProvider(new CountingEnsembleProvider(counter)) - .sessionTimeoutMs(timing.session()) - .connectionTimeoutMs(timing.connection()) - .retryPolicy(new RetryOneTime(1)) - .build(); + .ensembleProvider(new CountingEnsembleProvider(counter)) + .sessionTimeoutMs(timing.session()) + .connectionTimeoutMs(timing.connection()) + .retryPolicy(new RetryOneTime(1)) + .build(); } - private class CountingEnsembleProvider implements EnsembleProvider - { + private class CountingEnsembleProvider implements EnsembleProvider { private final Semaphore getConnectionStringCounter; - public CountingEnsembleProvider(Semaphore getConnectionStringCounter) - { + public CountingEnsembleProvider(Semaphore getConnectionStringCounter) { this.getConnectionStringCounter = getConnectionStringCounter; } @Override - public void start() - { + public void start() { // NOP } @Override - public String getConnectionString() - { + public String getConnectionString() { getConnectionStringCounter.release(); return server.getConnectString(); } @Override - public void close() - { + public void close() { // NOP } @Override - public void setConnectionString(String connectionString) - { + public void setConnectionString(String connectionString) { // NOP } @Override - public boolean updateServerListEnabled() - { + public boolean updateServerListEnabled() { return false; } } diff --git a/curator-framework/src/test/java/org/apache/curator/framework/imps/TestBlockUntilConnected.java b/curator-framework/src/test/java/org/apache/curator/framework/imps/TestBlockUntilConnected.java index 6d0dea8af..651e7a10c 100644 --- a/curator-framework/src/test/java/org/apache/curator/framework/imps/TestBlockUntilConnected.java +++ b/curator-framework/src/test/java/org/apache/curator/framework/imps/TestBlockUntilConnected.java @@ -22,7 +22,10 @@ import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; - +import java.util.Timer; +import java.util.TimerTask; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.state.ConnectionState; @@ -34,35 +37,24 @@ import org.apache.curator.utils.CloseableUtils; import org.junit.jupiter.api.Test; -import java.util.Timer; -import java.util.TimerTask; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; - -public class TestBlockUntilConnected extends BaseClassForTests -{ +public class TestBlockUntilConnected extends BaseClassForTests { /** * Test the case where we're already connected */ @Test - public void testBlockUntilConnectedCurrentlyConnected() throws Exception - { + public void testBlockUntilConnectedCurrentlyConnected() throws Exception { Timing timing = new Timing(); - CuratorFramework client = CuratorFrameworkFactory.builder(). - connectString(server.getConnectString()). - retryPolicy(new RetryOneTime(1)). - build(); + CuratorFramework client = CuratorFrameworkFactory.builder() + .connectString(server.getConnectString()) + .retryPolicy(new RetryOneTime(1)) + .build(); - try - { + try { final CountDownLatch connectedLatch = new CountDownLatch(1); - client.getConnectionStateListenable().addListener(new ConnectionStateListener() - { + client.getConnectionStateListenable().addListener(new ConnectionStateListener() { @Override - public void stateChanged(CuratorFramework client, ConnectionState newState) - { - if ( newState.isConnected() ) - { + public void stateChanged(CuratorFramework client, ConnectionState newState) { + if (newState.isConnected()) { connectedLatch.countDown(); } } @@ -72,13 +64,9 @@ public void stateChanged(CuratorFramework client, ConnectionState newState) assertTrue(timing.awaitLatch(connectedLatch), "Timed out awaiting latch"); assertTrue(client.blockUntilConnected(1, TimeUnit.SECONDS), "Not connected"); - } - catch ( InterruptedException e ) - { + } catch (InterruptedException e) { fail("Unexpected interruption"); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } @@ -87,24 +75,18 @@ public void stateChanged(CuratorFramework client, ConnectionState newState) * Test the case where we are not currently connected and never have been */ @Test - public void testBlockUntilConnectedCurrentlyNeverConnected() - { - CuratorFramework client = CuratorFrameworkFactory.builder(). - connectString(server.getConnectString()). - retryPolicy(new RetryOneTime(1)). - build(); + public void testBlockUntilConnectedCurrentlyNeverConnected() { + CuratorFramework client = CuratorFrameworkFactory.builder() + .connectString(server.getConnectString()) + .retryPolicy(new RetryOneTime(1)) + .build(); - try - { + try { client.start(); assertTrue(client.blockUntilConnected(5, TimeUnit.SECONDS), "Not connected"); - } - catch ( InterruptedException e ) - { + } catch (InterruptedException e) { fail("Unexpected interruption"); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } @@ -113,52 +95,43 @@ public void testBlockUntilConnectedCurrentlyNeverConnected() * Test the case where we are not currently connected, but have been previously */ @Test - public void testBlockUntilConnectedCurrentlyAwaitingReconnect() - { + public void testBlockUntilConnectedCurrentlyAwaitingReconnect() { Timing timing = new Timing(); - CuratorFramework client = CuratorFrameworkFactory.builder(). - connectString(server.getConnectString()). - sessionTimeoutMs(timing.session()). - retryPolicy(new RetryOneTime(1)). - build(); + CuratorFramework client = CuratorFrameworkFactory.builder() + .connectString(server.getConnectString()) + .sessionTimeoutMs(timing.session()) + .retryPolicy(new RetryOneTime(1)) + .build(); final CountDownLatch lostLatch = new CountDownLatch(1); - client.getConnectionStateListenable().addListener(new ConnectionStateListener() - { + client.getConnectionStateListenable().addListener(new ConnectionStateListener() { @Override - public void stateChanged(CuratorFramework client, ConnectionState newState) - { - if ( newState == ConnectionState.LOST ) - { + public void stateChanged(CuratorFramework client, ConnectionState newState) { + if (newState == ConnectionState.LOST) { lostLatch.countDown(); } } }); - try - { + try { client.start(); - //Block until we're connected + // Block until we're connected assertTrue(client.blockUntilConnected(5, TimeUnit.SECONDS), "Failed to connect"); - //Kill the server + // Kill the server CloseableUtils.closeQuietly(server); - //Wait until we hit the lost state + // Wait until we hit the lost state assertTrue(timing.awaitLatch(lostLatch), "Failed to reach LOST state"); server = new TestingServer(server.getPort(), server.getTempDirectory()); assertTrue(client.blockUntilConnected(5, TimeUnit.SECONDS), "Not connected"); - } - catch ( Exception e ) - { + } catch (Exception e) { fail("Unexpected exception " + e); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } @@ -168,27 +141,21 @@ public void stateChanged(CuratorFramework client, ConnectionState newState) * connection becomes available. */ @Test - public void testBlockUntilConnectedConnectTimeout() - { - //Kill the server + public void testBlockUntilConnectedConnectTimeout() { + // Kill the server CloseableUtils.closeQuietly(server); - CuratorFramework client = CuratorFrameworkFactory.builder(). - connectString(server.getConnectString()). - retryPolicy(new RetryOneTime(1)). - build(); + CuratorFramework client = CuratorFrameworkFactory.builder() + .connectString(server.getConnectString()) + .retryPolicy(new RetryOneTime(1)) + .build(); - try - { + try { client.start(); assertFalse(client.blockUntilConnected(5, TimeUnit.SECONDS), "Connected"); - } - catch ( InterruptedException e ) - { + } catch (InterruptedException e) { fail("Unexpected interruption"); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } @@ -198,42 +165,36 @@ public void testBlockUntilConnectedConnectTimeout() * prior to a connection becoming available */ @Test - public void testBlockUntilConnectedInterrupt() - { - //Kill the server + public void testBlockUntilConnectedInterrupt() { + // Kill the server CloseableUtils.closeQuietly(server); - final CuratorFramework client = CuratorFrameworkFactory.builder(). - connectString(server.getConnectString()). - retryPolicy(new RetryOneTime(1)). - build(); + final CuratorFramework client = CuratorFrameworkFactory.builder() + .connectString(server.getConnectString()) + .retryPolicy(new RetryOneTime(1)) + .build(); - try - { + try { client.start(); final Thread threadToInterrupt = Thread.currentThread(); Timer timer = new Timer(); - timer.schedule(new TimerTask() - { + timer.schedule( + new TimerTask() { - @Override - public void run() - { - threadToInterrupt.interrupt(); - } - }, 3000); + @Override + public void run() { + threadToInterrupt.interrupt(); + } + }, + 3000); client.blockUntilConnected(5, TimeUnit.SECONDS); fail("Expected interruption did not occur"); - } - catch ( InterruptedException e ) - { - //This is expected - } - finally - { + } catch (InterruptedException e) { + // This is expected + } finally { CloseableUtils.closeQuietly(client); } } @@ -242,21 +203,17 @@ public void run() * Test that we are actually connected every time that we block until connection is established in a tight loop. */ @Test - public void testBlockUntilConnectedTightLoop() throws InterruptedException - { + public void testBlockUntilConnectedTightLoop() throws InterruptedException { CuratorFramework client; - for(int i = 0 ; i < 50 ; i++) - { + for (int i = 0; i < 50; i++) { client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(100)); - try - { + try { client.start(); client.blockUntilConnected(); - assertTrue(client.getZookeeperClient().isConnected(), "Not connected after blocking for connection #" + i); - } - finally - { + assertTrue( + client.getZookeeperClient().isConnected(), "Not connected after blocking for connection #" + i); + } finally { client.close(); } } diff --git a/curator-framework/src/test/java/org/apache/curator/framework/imps/TestCleanState.java b/curator-framework/src/test/java/org/apache/curator/framework/imps/TestCleanState.java index 3e6e13c7e..2678b0bbf 100644 --- a/curator-framework/src/test/java/org/apache/curator/framework/imps/TestCleanState.java +++ b/curator-framework/src/test/java/org/apache/curator/framework/imps/TestCleanState.java @@ -19,111 +19,88 @@ package org.apache.curator.framework.imps; +import java.util.concurrent.Callable; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.test.WatchersDebug; import org.apache.curator.test.compatibility.Timing2; import org.apache.curator.utils.CloseableUtils; import org.apache.zookeeper.ZooKeeper; -import java.util.concurrent.Callable; import org.awaitility.Awaitility; -public class TestCleanState -{ +public class TestCleanState { private static final boolean IS_ENABLED = Boolean.getBoolean("PROPERTY_VALIDATE_NO_REMAINING_WATCHERS"); - public static void closeAndTestClean(CuratorFramework client) - { - if ( (client == null) || !IS_ENABLED ) - { + public static void closeAndTestClean(CuratorFramework client) { + if ((client == null) || !IS_ENABLED) { return; } - try - { + try { Timing2 timing = new Timing2(); - CuratorFrameworkImpl internalClient = (CuratorFrameworkImpl)client; + CuratorFrameworkImpl internalClient = (CuratorFrameworkImpl) client; EnsembleTracker ensembleTracker = internalClient.getEnsembleTracker(); - if ( ensembleTracker != null ) - { - Awaitility.await() - .until(() -> !ensembleTracker.hasOutstanding()); + if (ensembleTracker != null) { + Awaitility.await().until(() -> !ensembleTracker.hasOutstanding()); ensembleTracker.close(); } ZooKeeper zooKeeper = internalClient.getZooKeeper(); - if ( zooKeeper != null ) - { + if (zooKeeper != null) { final int maxLoops = 3; - for ( int i = 0; i < maxLoops; ++i ) // it takes time for the watcher removals to settle due to async/watchers, etc. So, if there are remaining watchers, sleep a bit + for (int i = 0; + i < maxLoops; + ++i) // it takes time for the watcher removals to settle due to async/watchers, etc. So, if + // there are remaining watchers, sleep a bit { - if ( i > 0 ) - { + if (i > 0) { timing.multiple(.5).sleepABit(); } boolean isLast = (i + 1) == maxLoops; - if ( WatchersDebug.getChildWatches(zooKeeper).size() != 0 ) - { - if ( isLast ) - { - throw new AssertionError("One or more child watchers are still registered: " + WatchersDebug.getChildWatches(zooKeeper)); + if (WatchersDebug.getChildWatches(zooKeeper).size() != 0) { + if (isLast) { + throw new AssertionError("One or more child watchers are still registered: " + + WatchersDebug.getChildWatches(zooKeeper)); } continue; } - if ( WatchersDebug.getExistWatches(zooKeeper).size() != 0 ) - { - if ( isLast ) - { - throw new AssertionError("One or more exists watchers are still registered: " + WatchersDebug.getExistWatches(zooKeeper)); + if (WatchersDebug.getExistWatches(zooKeeper).size() != 0) { + if (isLast) { + throw new AssertionError("One or more exists watchers are still registered: " + + WatchersDebug.getExistWatches(zooKeeper)); } continue; } - if ( WatchersDebug.getDataWatches(zooKeeper).size() != 0 ) - { - if ( isLast ) - { - throw new AssertionError("One or more data watchers are still registered: " + WatchersDebug.getDataWatches(zooKeeper)); + if (WatchersDebug.getDataWatches(zooKeeper).size() != 0) { + if (isLast) { + throw new AssertionError("One or more data watchers are still registered: " + + WatchersDebug.getDataWatches(zooKeeper)); } continue; } break; } } - } - catch ( IllegalStateException ignore ) - { + } catch (IllegalStateException ignore) { // client already closed - } - catch ( Exception e ) - { - e.printStackTrace(); // not sure what to do here - } - finally - { + } catch (Exception e) { + e.printStackTrace(); // not sure what to do here + } finally { CloseableUtils.closeQuietly(client); } } - public static void test(CuratorFramework client, Callable proc) throws Exception - { + public static void test(CuratorFramework client, Callable proc) throws Exception { boolean succeeded = false; - try - { + try { proc.call(); succeeded = true; - } - finally - { - if ( succeeded ) - { + } finally { + if (succeeded) { closeAndTestClean(client); - } - else - { + } else { CloseableUtils.closeQuietly(client); } } } - private TestCleanState() - { - } + private TestCleanState() {} } diff --git a/curator-framework/src/test/java/org/apache/curator/framework/imps/TestCompression.java b/curator-framework/src/test/java/org/apache/curator/framework/imps/TestCompression.java index 8bb9373aa..691b74374 100644 --- a/curator-framework/src/test/java/org/apache/curator/framework/imps/TestCompression.java +++ b/curator-framework/src/test/java/org/apache/curator/framework/imps/TestCompression.java @@ -22,66 +22,56 @@ import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; - -import org.apache.curator.test.BaseClassForTests; -import org.apache.curator.utils.CloseableUtils; +import java.util.concurrent.atomic.AtomicInteger; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.api.CompressionProvider; import org.apache.curator.retry.RetryOneTime; +import org.apache.curator.test.BaseClassForTests; +import org.apache.curator.utils.CloseableUtils; import org.junit.jupiter.api.Test; -import java.util.concurrent.atomic.AtomicInteger; - -public class TestCompression extends BaseClassForTests -{ +public class TestCompression extends BaseClassForTests { @Test - public void testCompressionProvider() throws Exception - { - final byte[] data = "here's a string".getBytes(); - - final AtomicInteger compressCounter = new AtomicInteger(); - final AtomicInteger decompressCounter = new AtomicInteger(); - CompressionProvider compressionProvider = new CompressionProvider() - { + public void testCompressionProvider() throws Exception { + final byte[] data = "here's a string".getBytes(); + + final AtomicInteger compressCounter = new AtomicInteger(); + final AtomicInteger decompressCounter = new AtomicInteger(); + CompressionProvider compressionProvider = new CompressionProvider() { @Override - public byte[] compress(String path, byte[] data) throws Exception - { + public byte[] compress(String path, byte[] data) throws Exception { compressCounter.incrementAndGet(); - byte[] bytes = new byte[data.length * 2]; + byte[] bytes = new byte[data.length * 2]; System.arraycopy(data, 0, bytes, 0, data.length); System.arraycopy(data, 0, bytes, data.length, data.length); return bytes; } @Override - public byte[] decompress(String path, byte[] compressedData) throws Exception - { + public byte[] decompress(String path, byte[] compressedData) throws Exception { decompressCounter.incrementAndGet(); - byte[] bytes = new byte[compressedData.length / 2]; + byte[] bytes = new byte[compressedData.length / 2]; System.arraycopy(compressedData, 0, bytes, 0, bytes.length); return bytes; } }; - CuratorFramework client = CuratorFrameworkFactory.builder(). - compressionProvider(compressionProvider). - connectString(server.getConnectString()). - retryPolicy(new RetryOneTime(1)). - build(); - try - { + CuratorFramework client = CuratorFrameworkFactory.builder() + .compressionProvider(compressionProvider) + .connectString(server.getConnectString()) + .retryPolicy(new RetryOneTime(1)) + .build(); + try { client.start(); client.create().compressed().creatingParentsIfNeeded().forPath("/a/b/c", data); assertNotEquals(data, client.getData().forPath("/a/b/c")); assertEquals(data.length, client.getData().decompressed().forPath("/a/b/c").length); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } @@ -90,13 +80,11 @@ public byte[] decompress(String path, byte[] compressedData) throws Exception } @Test - public void testSetData() throws Exception - { - final byte[] data = "here's a string".getBytes(); + public void testSetData() throws Exception { + final byte[] data = "here's a string".getBytes(); - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); - try - { + CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); + try { client.start(); client.create().creatingParentsIfNeeded().forPath("/a/b/c", data); @@ -104,30 +92,24 @@ public void testSetData() throws Exception client.setData().compressed().forPath("/a/b/c", data); assertEquals(data.length, client.getData().decompressed().forPath("/a/b/c").length); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } @Test - public void testSimple() throws Exception - { - final byte[] data = "here's a string".getBytes(); + public void testSimple() throws Exception { + final byte[] data = "here's a string".getBytes(); - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); - try - { + CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); + try { client.start(); client.create().compressed().creatingParentsIfNeeded().forPath("/a/b/c", data); assertNotEquals(data, client.getData().forPath("/a/b/c")); assertEquals(data.length, client.getData().decompressed().forPath("/a/b/c").length); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } diff --git a/curator-framework/src/test/java/org/apache/curator/framework/imps/TestCompressionInTransactionNew.java b/curator-framework/src/test/java/org/apache/curator/framework/imps/TestCompressionInTransactionNew.java index bf4a63a3b..7d389e351 100644 --- a/curator-framework/src/test/java/org/apache/curator/framework/imps/TestCompressionInTransactionNew.java +++ b/curator-framework/src/test/java/org/apache/curator/framework/imps/TestCompressionInTransactionNew.java @@ -30,86 +30,75 @@ import org.apache.curator.utils.CloseableUtils; import org.junit.jupiter.api.Test; -public class TestCompressionInTransactionNew extends BaseClassForTests -{ +public class TestCompressionInTransactionNew extends BaseClassForTests { @Test - public void testSetData() throws Exception - { + public void testSetData() throws Exception { final String path = "/a"; - final byte[] data = "here's a string".getBytes(); + final byte[] data = "here's a string".getBytes(); - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); - try - { + CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); + try { client.start(); - //Create uncompressed data in a transaction + // Create uncompressed data in a transaction CuratorOp op = client.transactionOp().create().forPath(path, data); client.transaction().forOperations(op); assertArrayEquals(data, client.getData().forPath(path)); - //Create compressed data in transaction + // Create compressed data in transaction op = client.transactionOp().setData().compressed().forPath(path, data); client.transaction().forOperations(op); assertArrayEquals(data, client.getData().decompressed().forPath(path)); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } - + @Test - public void testSetCompressedAndUncompressed() throws Exception - { + public void testSetCompressedAndUncompressed() throws Exception { final String path1 = "/a"; final String path2 = "/b"; - - final byte[] data1 = "here's a string".getBytes(); - final byte[] data2 = "here's another string".getBytes(); - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); - try - { + final byte[] data1 = "here's a string".getBytes(); + final byte[] data2 = "here's another string".getBytes(); + + CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); + try { client.start(); - //Create the nodes + // Create the nodes CuratorOp op1 = client.transactionOp().create().compressed().forPath(path1); CuratorOp op2 = client.transactionOp().create().forPath(path2); client.transaction().forOperations(op1, op2); - //Check they exist + // Check they exist assertNotNull(client.checkExists().forPath(path1)); assertNotNull(client.checkExists().forPath(path2)); - - //Set the nodes, path1 compressed, path2 uncompressed. + + // Set the nodes, path1 compressed, path2 uncompressed. op1 = client.transactionOp().setData().compressed().forPath(path1, data1); op2 = client.transactionOp().setData().forPath(path2, data2); client.transaction().forOperations(op1, op2); - + assertNotEquals(data1, client.getData().forPath(path1)); assertArrayEquals(data1, client.getData().decompressed().forPath(path1)); - + assertArrayEquals(data2, client.getData().forPath(path2)); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } - } - + } + @Test - public void testSimple() throws Exception - { + public void testSimple() throws Exception { final String path1 = "/a"; final String path2 = "/a/b"; - - final byte[] data1 = "here's a string".getBytes(); - final byte[] data2 = "here's another string".getBytes(); - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); - try - { + final byte[] data1 = "here's a string".getBytes(); + final byte[] data2 = "here's another string".getBytes(); + + CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); + try { client.start(); CuratorOp op1 = client.transactionOp().create().compressed().forPath(path1, data1); @@ -119,33 +108,29 @@ public void testSimple() throws Exception assertNotEquals(data1, client.getData().forPath(path1)); assertArrayEquals(data1, client.getData().decompressed().forPath(path1)); - + assertNotEquals(data2, client.getData().forPath(path2)); assertArrayEquals(data2, client.getData().decompressed().forPath(path2)); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } - } - + } + /** * Test the case where both uncompressed and compressed data is generated in * the same transaction * @throws Exception */ @Test - public void testCreateCompressedAndUncompressed() throws Exception - { + public void testCreateCompressedAndUncompressed() throws Exception { final String path1 = "/a"; final String path2 = "/b"; - - final byte[] data1 = "here's a string".getBytes(); - final byte[] data2 = "here's another string".getBytes(); - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); - try - { + final byte[] data1 = "here's a string".getBytes(); + final byte[] data2 = "here's another string".getBytes(); + + CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); + try { client.start(); CuratorOp op1 = client.transactionOp().create().compressed().forPath(path1, data1); @@ -154,11 +139,9 @@ public void testCreateCompressedAndUncompressed() throws Exception assertNotEquals(data1, client.getData().forPath(path1)); assertArrayEquals(data1, client.getData().decompressed().forPath(path1)); - + assertArrayEquals(data2, client.getData().forPath(path2)); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } diff --git a/curator-framework/src/test/java/org/apache/curator/framework/imps/TestCompressionInTransactionOld.java b/curator-framework/src/test/java/org/apache/curator/framework/imps/TestCompressionInTransactionOld.java index 66186bfaa..d347e20fe 100644 --- a/curator-framework/src/test/java/org/apache/curator/framework/imps/TestCompressionInTransactionOld.java +++ b/curator-framework/src/test/java/org/apache/curator/framework/imps/TestCompressionInTransactionOld.java @@ -22,137 +22,153 @@ import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; - -import org.apache.curator.test.BaseClassForTests; -import org.apache.curator.utils.CloseableUtils; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.retry.RetryOneTime; +import org.apache.curator.test.BaseClassForTests; +import org.apache.curator.utils.CloseableUtils; import org.junit.jupiter.api.Test; @SuppressWarnings("deprecation") -public class TestCompressionInTransactionOld extends BaseClassForTests -{ +public class TestCompressionInTransactionOld extends BaseClassForTests { @Test - public void testSetData() throws Exception - { + public void testSetData() throws Exception { final String path = "/a"; - final byte[] data = "here's a string".getBytes(); + final byte[] data = "here's a string".getBytes(); - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); - try - { + CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); + try { client.start(); - //Create uncompressed data in a transaction + // Create uncompressed data in a transaction client.inTransaction().create().forPath(path, data).and().commit(); assertArrayEquals(data, client.getData().forPath(path)); - //Create compressed data in transaction - client.inTransaction().setData().compressed().forPath(path, data).and().commit(); + // Create compressed data in transaction + client.inTransaction() + .setData() + .compressed() + .forPath(path, data) + .and() + .commit(); assertArrayEquals(data, client.getData().decompressed().forPath(path)); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } - + @Test - public void testSetCompressedAndUncompressed() throws Exception - { + public void testSetCompressedAndUncompressed() throws Exception { final String path1 = "/a"; final String path2 = "/b"; - - final byte[] data1 = "here's a string".getBytes(); - final byte[] data2 = "here's another string".getBytes(); - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); - try - { - client.start(); + final byte[] data1 = "here's a string".getBytes(); + final byte[] data2 = "here's another string".getBytes(); - //Create the nodes - client.inTransaction().create().compressed().forPath(path1).and(). - create().forPath(path2).and().commit(); + CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); + try { + client.start(); - //Check they exist + // Create the nodes + client.inTransaction() + .create() + .compressed() + .forPath(path1) + .and() + .create() + .forPath(path2) + .and() + .commit(); + + // Check they exist assertNotNull(client.checkExists().forPath(path1)); assertNotNull(client.checkExists().forPath(path2)); - - //Set the nodes, path1 compressed, path2 uncompressed. - client.inTransaction().setData().compressed().forPath(path1, data1).and(). - setData().forPath(path2, data2).and().commit(); - + + // Set the nodes, path1 compressed, path2 uncompressed. + client.inTransaction() + .setData() + .compressed() + .forPath(path1, data1) + .and() + .setData() + .forPath(path2, data2) + .and() + .commit(); + assertNotEquals(data1, client.getData().forPath(path1)); assertArrayEquals(data1, client.getData().decompressed().forPath(path1)); - + assertArrayEquals(data2, client.getData().forPath(path2)); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } - } - + } + @Test - public void testSimple() throws Exception - { + public void testSimple() throws Exception { final String path1 = "/a"; final String path2 = "/a/b"; - - final byte[] data1 = "here's a string".getBytes(); - final byte[] data2 = "here's another string".getBytes(); - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); - try - { + final byte[] data1 = "here's a string".getBytes(); + final byte[] data2 = "here's another string".getBytes(); + + CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); + try { client.start(); - client.inTransaction().create().compressed().forPath(path1, data1).and(). - create().compressed().forPath(path2, data2).and().commit(); + client.inTransaction() + .create() + .compressed() + .forPath(path1, data1) + .and() + .create() + .compressed() + .forPath(path2, data2) + .and() + .commit(); assertNotEquals(data1, client.getData().forPath(path1)); assertArrayEquals(data1, client.getData().decompressed().forPath(path1)); - + assertNotEquals(data2, client.getData().forPath(path2)); assertArrayEquals(data2, client.getData().decompressed().forPath(path2)); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } - } - + } + /** * Test the case where both uncompressed and compressed data is generated in * the same transaction * @throws Exception */ @Test - public void testCreateCompressedAndUncompressed() throws Exception - { + public void testCreateCompressedAndUncompressed() throws Exception { final String path1 = "/a"; final String path2 = "/b"; - - final byte[] data1 = "here's a string".getBytes(); - final byte[] data2 = "here's another string".getBytes(); - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); - try - { + final byte[] data1 = "here's a string".getBytes(); + final byte[] data2 = "here's another string".getBytes(); + + CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); + try { client.start(); - client.inTransaction().create().compressed().forPath(path1, data1).and(). - create().forPath(path2, data2).and().commit(); + client.inTransaction() + .create() + .compressed() + .forPath(path1, data1) + .and() + .create() + .forPath(path2, data2) + .and() + .commit(); assertNotEquals(data1, client.getData().forPath(path1)); assertArrayEquals(data1, client.getData().decompressed().forPath(path1)); - + assertArrayEquals(data2, client.getData().forPath(path2)); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } diff --git a/curator-framework/src/test/java/org/apache/curator/framework/imps/TestCreate.java b/curator-framework/src/test/java/org/apache/curator/framework/imps/TestCreate.java index f1f24e813..a83192754 100644 --- a/curator-framework/src/test/java/org/apache/curator/framework/imps/TestCreate.java +++ b/curator-framework/src/test/java/org/apache/curator/framework/imps/TestCreate.java @@ -23,8 +23,12 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assertions.fail; - +import java.util.Collections; +import java.util.List; +import java.util.Optional; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.api.ACLProvider; @@ -42,92 +46,75 @@ import org.apache.zookeeper.data.Stat; import org.junit.jupiter.api.Test; -import java.util.Collections; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicInteger; - -public class TestCreate extends BaseClassForTests -{ - private static final List READ_CREATE = Collections.singletonList(new ACL(ZooDefs.Perms.CREATE | ZooDefs.Perms.READ, ANYONE_ID_UNSAFE)); - private static final List READ_CREATE_WRITE = Collections.singletonList(new ACL(ZooDefs.Perms.CREATE | ZooDefs.Perms.READ | ZooDefs.Perms.WRITE, ANYONE_ID_UNSAFE)); +public class TestCreate extends BaseClassForTests { + private static final List READ_CREATE = + Collections.singletonList(new ACL(ZooDefs.Perms.CREATE | ZooDefs.Perms.READ, ANYONE_ID_UNSAFE)); + private static final List READ_CREATE_WRITE = Collections.singletonList( + new ACL(ZooDefs.Perms.CREATE | ZooDefs.Perms.READ | ZooDefs.Perms.WRITE, ANYONE_ID_UNSAFE)); - private static ACLProvider testACLProvider = new ACLProvider() - { + private static ACLProvider testACLProvider = new ACLProvider() { @Override - public List getDefaultAcl() - { + public List getDefaultAcl() { return ZooDefs.Ids.OPEN_ACL_UNSAFE; } @Override - public List getAclForPath(String path) - { - switch ( path ) - { - case "/bar": - return READ_CREATE; - case "/bar/foo": - return READ_CREATE_WRITE; + public List getAclForPath(String path) { + switch (path) { + case "/bar": + return READ_CREATE; + case "/bar/foo": + return READ_CREATE_WRITE; } return null; } }; - private CuratorFramework createClient(ACLProvider aclProvider) - { - return CuratorFrameworkFactory.builder(). - aclProvider(aclProvider). - connectString(server.getConnectString()). - retryPolicy(new RetryOneTime(1)). - build(); + private CuratorFramework createClient(ACLProvider aclProvider) { + return CuratorFrameworkFactory.builder() + .aclProvider(aclProvider) + .connectString(server.getConnectString()) + .retryPolicy(new RetryOneTime(1)) + .build(); } /** * Tests that the ACL list provided to the create builder is used for creating the parents. */ @Test - public void testCreateWithParentsWithAcl() throws Exception - { + public void testCreateWithParentsWithAcl() throws Exception { CuratorFramework client = createClient(new DefaultACLProvider()); - try - { + try { client.start(); String path = "/bar/foo"; - List acl = Collections.singletonList(new ACL(ZooDefs.Perms.CREATE | ZooDefs.Perms.READ, ANYONE_ID_UNSAFE)); + List acl = + Collections.singletonList(new ACL(ZooDefs.Perms.CREATE | ZooDefs.Perms.READ, ANYONE_ID_UNSAFE)); client.create().creatingParentsIfNeeded().withACL(acl).forPath(path); List actual_bar_foo = client.getACL().forPath(path); assertEquals(actual_bar_foo, acl); List actual_bar = client.getACL().forPath("/bar"); assertEquals(actual_bar, ZooDefs.Ids.OPEN_ACL_UNSAFE); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } @Test - public void testCreateWithParentsWithAclApplyToParents() throws Exception - { + public void testCreateWithParentsWithAclApplyToParents() throws Exception { CuratorFramework client = createClient(new DefaultACLProvider()); - try - { + try { client.start(); String path = "/bar/foo"; - List acl = Collections.singletonList(new ACL(ZooDefs.Perms.CREATE | ZooDefs.Perms.READ, ANYONE_ID_UNSAFE)); + List acl = + Collections.singletonList(new ACL(ZooDefs.Perms.CREATE | ZooDefs.Perms.READ, ANYONE_ID_UNSAFE)); client.create().creatingParentsIfNeeded().withACL(acl, true).forPath(path); List actual_bar_foo = client.getACL().forPath(path); assertEquals(actual_bar_foo, acl); List actual_bar = client.getACL().forPath("/bar"); assertEquals(actual_bar, acl); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } @@ -136,63 +123,61 @@ public void testCreateWithParentsWithAclApplyToParents() throws Exception * Tests that the ACL list provided to the create builder is used for creating the parents. */ @Test - public void testCreateWithParentsWithAclInBackground() throws Exception - { + public void testCreateWithParentsWithAclInBackground() throws Exception { CuratorFramework client = createClient(new DefaultACLProvider()); - try - { + try { client.start(); final CountDownLatch latch = new CountDownLatch(1); String path = "/bar/foo"; - List acl = Collections.singletonList(new ACL(ZooDefs.Perms.CREATE | ZooDefs.Perms.READ, ANYONE_ID_UNSAFE)); - BackgroundCallback callback = new BackgroundCallback() - { + List acl = + Collections.singletonList(new ACL(ZooDefs.Perms.CREATE | ZooDefs.Perms.READ, ANYONE_ID_UNSAFE)); + BackgroundCallback callback = new BackgroundCallback() { @Override - public void processResult(CuratorFramework client, CuratorEvent event) throws Exception - { + public void processResult(CuratorFramework client, CuratorEvent event) throws Exception { latch.countDown(); } }; - client.create().creatingParentsIfNeeded().withACL(acl).inBackground(callback).forPath(path); + client.create() + .creatingParentsIfNeeded() + .withACL(acl) + .inBackground(callback) + .forPath(path); assertTrue(latch.await(2000, TimeUnit.MILLISECONDS), "Callback not invoked"); List actual_bar_foo = client.getACL().forPath(path); assertEquals(actual_bar_foo, acl); List actual_bar = client.getACL().forPath("/bar"); assertEquals(actual_bar, ZooDefs.Ids.OPEN_ACL_UNSAFE); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } @Test - public void testCreateWithParentsWithAclApplyToParentsInBackground() throws Exception - { + public void testCreateWithParentsWithAclApplyToParentsInBackground() throws Exception { CuratorFramework client = createClient(new DefaultACLProvider()); - try - { + try { client.start(); final CountDownLatch latch = new CountDownLatch(1); String path = "/bar/foo"; - List acl = Collections.singletonList(new ACL(ZooDefs.Perms.CREATE | ZooDefs.Perms.READ, ANYONE_ID_UNSAFE)); - BackgroundCallback callback = new BackgroundCallback() - { + List acl = + Collections.singletonList(new ACL(ZooDefs.Perms.CREATE | ZooDefs.Perms.READ, ANYONE_ID_UNSAFE)); + BackgroundCallback callback = new BackgroundCallback() { @Override - public void processResult(CuratorFramework client, CuratorEvent event) throws Exception - { + public void processResult(CuratorFramework client, CuratorEvent event) throws Exception { latch.countDown(); } }; - client.create().creatingParentsIfNeeded().withACL(acl, true).inBackground(callback).forPath(path); + client.create() + .creatingParentsIfNeeded() + .withACL(acl, true) + .inBackground(callback) + .forPath(path); assertTrue(latch.await(2000, TimeUnit.MILLISECONDS), "Callback not invoked"); List actual_bar_foo = client.getACL().forPath(path); assertEquals(actual_bar_foo, acl); List actual_bar = client.getACL().forPath("/bar"); assertEquals(actual_bar, acl); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } @@ -201,11 +186,9 @@ public void processResult(CuratorFramework client, CuratorEvent event) throws Ex * Tests that if no ACL list provided to the create builder, then the ACL list is created based on the client's ACLProvider. */ @Test - public void testCreateWithParentsWithoutAcl() throws Exception - { + public void testCreateWithParentsWithoutAcl() throws Exception { CuratorFramework client = createClient(testACLProvider); - try - { + try { client.start(); String path = "/bar/foo/boo"; @@ -216,9 +199,7 @@ public void testCreateWithParentsWithoutAcl() throws Exception assertEquals(actual_bar_foo, READ_CREATE_WRITE); List actual_bar = client.getACL().forPath("/bar"); assertEquals(actual_bar, READ_CREATE); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } @@ -227,19 +208,15 @@ public void testCreateWithParentsWithoutAcl() throws Exception * Tests that if no ACL list provided to the create builder, then the ACL list is created based on the client's ACLProvider. */ @Test - public void testCreateWithParentsWithoutAclInBackground() throws Exception - { + public void testCreateWithParentsWithoutAclInBackground() throws Exception { CuratorFramework client = createClient(testACLProvider); - try - { + try { client.start(); final CountDownLatch latch = new CountDownLatch(1); - BackgroundCallback callback = new BackgroundCallback() - { + BackgroundCallback callback = new BackgroundCallback() { @Override - public void processResult(CuratorFramework client, CuratorEvent event) throws Exception - { + public void processResult(CuratorFramework client, CuratorEvent event) throws Exception { latch.countDown(); } }; @@ -253,41 +230,38 @@ public void processResult(CuratorFramework client, CuratorEvent event) throws Ex assertEquals(actual_bar_foo, READ_CREATE_WRITE); List actual_bar = client.getACL().forPath("/bar"); assertEquals(actual_bar, READ_CREATE); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } - private void check(CuratorFramework client, CreateBuilderMain builder, String path, byte[] data, boolean expectedSuccess) throws Exception - { - int expectedCode = (expectedSuccess) ? KeeperException.Code.OK.intValue() : KeeperException.Code.NODEEXISTS.intValue(); - try - { + private void check( + CuratorFramework client, CreateBuilderMain builder, String path, byte[] data, boolean expectedSuccess) + throws Exception { + int expectedCode = + (expectedSuccess) ? KeeperException.Code.OK.intValue() : KeeperException.Code.NODEEXISTS.intValue(); + try { builder.forPath(path, data); assertEquals(expectedCode, KeeperException.Code.OK.intValue()); Stat stat = new Stat(); byte[] actualData = client.getData().storingStatIn(stat).forPath(path); assertTrue(IdempotentUtils.matches(0, data, stat.getVersion(), actualData)); - } - catch (KeeperException e) - { + } catch (KeeperException e) { assertEquals(expectedCode, e.getCode()); } } - private void checkBackground(CuratorFramework client, CreateBuilderMain builder, String path, byte[] data, boolean expectedSuccess) throws Exception - { - int expectedCode = (expectedSuccess) ? KeeperException.Code.OK.intValue() : KeeperException.Code.NODEEXISTS.intValue(); + private void checkBackground( + CuratorFramework client, CreateBuilderMain builder, String path, byte[] data, boolean expectedSuccess) + throws Exception { + int expectedCode = + (expectedSuccess) ? KeeperException.Code.OK.intValue() : KeeperException.Code.NODEEXISTS.intValue(); AtomicInteger actualCode = new AtomicInteger(-1); CountDownLatch latch = new CountDownLatch(1); - BackgroundCallback callback = new BackgroundCallback() - { + BackgroundCallback callback = new BackgroundCallback() { @Override - public void processResult(CuratorFramework client, CuratorEvent event) throws Exception - { + public void processResult(CuratorFramework client, CuratorEvent event) throws Exception { actualCode.set(event.getResultCode()); latch.countDown(); } @@ -298,29 +272,25 @@ public void processResult(CuratorFramework client, CuratorEvent event) throws Ex assertTrue(latch.await(5000, TimeUnit.MILLISECONDS), "Callback not invoked"); assertEquals(expectedCode, actualCode.get()); - if (expectedCode == KeeperException.Code.OK.intValue()) - { + if (expectedCode == KeeperException.Code.OK.intValue()) { Stat stat = new Stat(); byte[] actualData = client.getData().storingStatIn(stat).forPath(path); assertTrue(IdempotentUtils.matches(0, data, stat.getVersion(), actualData)); } } - private CreateBuilderMain clBefore(CreateBuilderMain builder) - { - ((CreateBuilderImpl)builder).failBeforeNextCreateForTesting = true; + private CreateBuilderMain clBefore(CreateBuilderMain builder) { + ((CreateBuilderImpl) builder).failBeforeNextCreateForTesting = true; return builder; } - private CreateBuilderMain clAfter(CreateBuilderMain builder) - { - ((CreateBuilderImpl)builder).failNextCreateForTesting = true; + private CreateBuilderMain clAfter(CreateBuilderMain builder) { + ((CreateBuilderImpl) builder).failNextCreateForTesting = true; return builder; } - private CreateBuilderMain clCheck(CreateBuilderMain builder) - { - ((CreateBuilderImpl)builder).failNextIdempotentCheckForTesting = true; + private CreateBuilderMain clCheck(CreateBuilderMain builder) { + ((CreateBuilderImpl) builder).failNextIdempotentCheckForTesting = true; return builder; } @@ -328,11 +298,9 @@ private CreateBuilderMain clCheck(CreateBuilderMain builder) * Tests that NodeExists on failNextCreate doesn't hang in background */ @Test - public void testBackgroundFaultInjectionHang() throws Exception - { + public void testBackgroundFaultInjectionHang() throws Exception { CuratorFramework client = createClient(new DefaultACLProvider()); - try - { + try { client.start(); Stat stat = new Stat(); @@ -344,9 +312,7 @@ public void testBackgroundFaultInjectionHang() throws Exception check(client, create, path, data, true); checkBackground(client, clAfter(client.create()), path, data, false); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } @@ -355,11 +321,9 @@ public void testBackgroundFaultInjectionHang() throws Exception * Tests all cases of idempotent create */ @Test - public void testIdempotentCreate() throws Exception - { + public void testIdempotentCreate() throws Exception { CuratorFramework client = createClient(new DefaultACLProvider()); - try - { + try { client.start(); Stat stat = new Stat(); @@ -393,9 +357,7 @@ public void testIdempotentCreate() throws Exception check(client, client.create().idempotent(), path, data2, false); checkBackground(client, client.create().idempotent(), pathBack, data2, false); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } @@ -404,8 +366,7 @@ public void testIdempotentCreate() throws Exception @Test public void testIdempotentCreateConnectionLoss() throws Exception { CuratorFramework client = createClient(new DefaultACLProvider()); - try - { + try { client.start(); String path1 = "/idpcreate1"; String path2 = "/idpcreate2"; @@ -418,48 +379,44 @@ public void testIdempotentCreateConnectionLoss() throws Exception { // Test that idempotent create succeeds with connection loss before or after first create check(client, clBefore(client.create().idempotent()), path1, data, true); - checkBackground(client, clBefore(client.create().idempotent()), path1+"back", data, true); + checkBackground(client, clBefore(client.create().idempotent()), path1 + "back", data, true); check(client, clAfter(client.create().idempotent()), path2, data, true); - checkBackground(client, clAfter(client.create().idempotent()), path2+"back", data, true); + checkBackground(client, clAfter(client.create().idempotent()), path2 + "back", data, true); // Test that repeating same operation succeeds, even with connection loss before/after/check check(client, clBefore(client.create().idempotent()), path1, data, true); - checkBackground(client, clBefore(client.create().idempotent()), path1+"back", data, true); + checkBackground(client, clBefore(client.create().idempotent()), path1 + "back", data, true); check(client, clAfter(client.create().idempotent()), path2, data, true); - checkBackground(client, clAfter(client.create().idempotent()), path2+"back", data, true); + checkBackground(client, clAfter(client.create().idempotent()), path2 + "back", data, true); check(client, clCheck(client.create().idempotent()), path2, data, true); - checkBackground(client, clCheck(client.create().idempotent()), path2+"back", data, true); + checkBackground(client, clCheck(client.create().idempotent()), path2 + "back", data, true); // test that idempotent correctly fails, even after connection loss, // by repeating earlier operations with different data check(client, clBefore(client.create().idempotent()), path1, data2, false); - checkBackground(client, clBefore(client.create().idempotent()), path1+"back", data2, false); + checkBackground(client, clBefore(client.create().idempotent()), path1 + "back", data2, false); check(client, clAfter(client.create().idempotent()), path2, data2, false); - checkBackground(client, clAfter(client.create().idempotent()), path2+"back", data2, false); + checkBackground(client, clAfter(client.create().idempotent()), path2 + "back", data2, false); check(client, clCheck(client.create().idempotent()), path2, data2, false); - checkBackground(client, clCheck(client.create().idempotent()), path2+"back", data2, false); + checkBackground(client, clCheck(client.create().idempotent()), path2 + "back", data2, false); // Test that non-idempotent succeeds with CL before create, but fails with connection loss after check(client, clBefore(client.create()), path3, data, true); - checkBackground(client, clBefore(client.create()), path3+"back", data, true); + checkBackground(client, clBefore(client.create()), path3 + "back", data, true); check(client, clAfter(client.create()), path4, data, false); - checkBackground(client, clAfter(client.create()), path4+"back", data, false); + checkBackground(client, clAfter(client.create()), path4 + "back", data, false); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } @Test - public void testCreateProtectedUtils() throws Exception - { - try (CuratorFramework client = CuratorFrameworkFactory.builder(). - connectString(server.getConnectString()). - retryPolicy(new RetryOneTime(1)). - build()) - { + public void testCreateProtectedUtils() throws Exception { + try (CuratorFramework client = CuratorFrameworkFactory.builder() + .connectString(server.getConnectString()) + .retryPolicy(new RetryOneTime(1)) + .build()) { client.start(); client.blockUntilConnected(); client.create().forPath("/parent"); @@ -470,7 +427,9 @@ public void testCreateProtectedUtils() throws Exception final String testZNodeName = children.get(0); assertEquals(testZNodeName.length(), ProtectedUtils.PROTECTED_PREFIX_WITH_UUID_LENGTH + "test".length()); assertTrue(testZNodeName.startsWith(ProtectedUtils.PROTECTED_PREFIX)); - assertEquals(testZNodeName.charAt(ProtectedUtils.PROTECTED_PREFIX_WITH_UUID_LENGTH - 1), ProtectedUtils.PROTECTED_SEPARATOR); + assertEquals( + testZNodeName.charAt(ProtectedUtils.PROTECTED_PREFIX_WITH_UUID_LENGTH - 1), + ProtectedUtils.PROTECTED_SEPARATOR); assertTrue(ProtectedUtils.isProtectedZNode(testZNodeName)); assertEquals(ProtectedUtils.normalize(testZNodeName), "test"); assertFalse(ProtectedUtils.isProtectedZNode("parent")); @@ -479,8 +438,7 @@ public void testCreateProtectedUtils() throws Exception } @Test - public void testProtectedUtils() throws Exception - { + public void testProtectedUtils() throws Exception { String name = "_c_53345f98-9423-4e0c-a7b5-9f819e3ec2e1-yo"; assertTrue(ProtectedUtils.isProtectedZNode(name)); assertEquals(ProtectedUtils.normalize(name), "yo"); @@ -501,7 +459,9 @@ public void testProtectedUtils() throws Exception assertEquals(name, ProtectedUtils.toProtectedZNode("yo", "53345f98-9423-4e0c-a7b5-9f819e3ec2e1")); assertEquals("yo", ProtectedUtils.toProtectedZNode("yo", null)); String path = ZKPaths.makePath("hola", "yo"); - assertEquals(ProtectedUtils.toProtectedZNodePath(path, "53345f98-9423-4e0c-a7b5-9f819e3ec2e1"), ZKPaths.makePath("hola", name)); + assertEquals( + ProtectedUtils.toProtectedZNodePath(path, "53345f98-9423-4e0c-a7b5-9f819e3ec2e1"), + ZKPaths.makePath("hola", name)); assertEquals(ProtectedUtils.toProtectedZNodePath(path, null), path); path = ZKPaths.makePath("hola", name); assertEquals(ProtectedUtils.normalizePath(path), "/hola/yo"); diff --git a/curator-framework/src/test/java/org/apache/curator/framework/imps/TestCreateReturningStat.java b/curator-framework/src/test/java/org/apache/curator/framework/imps/TestCreateReturningStat.java index 1f743fc14..7d826548e 100755 --- a/curator-framework/src/test/java/org/apache/curator/framework/imps/TestCreateReturningStat.java +++ b/curator-framework/src/test/java/org/apache/curator/framework/imps/TestCreateReturningStat.java @@ -17,238 +17,201 @@ * under the License. */ -package org.apache.curator.framework.imps; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assertions.fail; - -import org.apache.curator.framework.CuratorFramework; -import org.apache.curator.framework.CuratorFrameworkFactory; -import org.apache.curator.framework.api.BackgroundCallback; -import org.apache.curator.framework.api.CuratorEvent; -import org.apache.curator.framework.api.CuratorEventType; -import org.apache.curator.retry.RetryOneTime; -import org.apache.curator.test.compatibility.CuratorTestBase; -import org.apache.curator.test.Timing; -import org.apache.curator.utils.CloseableUtils; -import org.apache.zookeeper.data.Stat; -import org.junit.jupiter.api.Test; - -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.atomic.AtomicReference; - -public class TestCreateReturningStat extends CuratorTestBase -{ - private CuratorFramework createClient() - { - return CuratorFrameworkFactory.builder(). - connectString(server.getConnectString()). - retryPolicy(new RetryOneTime(1)). - build(); - } - - private void compare(CuratorFramework client, String path, - Stat expected) throws Exception - { - Stat queriedStat = client.checkExists().forPath(path); - - assertEquals(queriedStat, expected); - } - - @Test - public void testOrSetDataStoringStatIn() throws Exception { - try (CuratorFramework client = createClient()) - { - client.start(); - client.getZookeeperClient().blockUntilConnectedOrTimedOut(); - - final String path = "/test"; - - final Stat versionZeroStat = new Stat(); - client.create().orSetData().storingStatIn(versionZeroStat).forPath(path); - assertEquals(0, versionZeroStat.getVersion()); - - final Stat versionOneStat = new Stat(); - client.create().orSetData().storingStatIn(versionOneStat).forPath(path); - - assertEquals(versionZeroStat.getAversion(), versionOneStat.getAversion()); - assertEquals(versionZeroStat.getCtime(), versionOneStat.getCtime()); - assertEquals(versionZeroStat.getCversion(), versionOneStat.getCversion()); - assertEquals(versionZeroStat.getCzxid(), versionOneStat.getCzxid()); - assertEquals(versionZeroStat.getDataLength(), versionOneStat.getDataLength()); - assertEquals(versionZeroStat.getEphemeralOwner(), versionOneStat.getEphemeralOwner()); - assertTrue(versionZeroStat.getMtime() <= versionOneStat.getMtime()); - assertNotEquals(versionZeroStat.getMzxid(), versionOneStat.getMzxid()); - assertEquals(versionZeroStat.getNumChildren(), versionOneStat.getNumChildren()); - assertEquals(versionZeroStat.getPzxid(), versionOneStat.getPzxid()); - assertEquals(1, versionOneStat.getVersion()); - } - } - - @Test - public void testCreateReturningStat() throws Exception - { - CuratorFramework client = createClient(); - try - { - client.start(); - - String path = "/bla"; - Stat stat = new Stat(); - client.create().storingStatIn(stat).forPath(path); - - compare(client, path, stat); - } - finally - { - CloseableUtils.closeQuietly(client); - } - } - - @Test - public void testCreateReturningStatIncludingParents() throws Exception - { - CuratorFramework client = createClient(); - try - { - client.start(); - - String path = "/bla/bla"; - Stat stat = new Stat(); - client.create().creatingParentsIfNeeded().storingStatIn(stat).forPath(path); - - compare(client, path, stat); - } - finally - { - CloseableUtils.closeQuietly(client); - } - } - - @Test - public void testCreateReturningStatIncludingParentsReverse() throws Exception - { - CuratorFramework client = createClient(); - try - { - client.start(); - - String path = "/bla/bla"; - Stat stat = new Stat(); - client.create().storingStatIn(stat).creatingParentsIfNeeded().forPath(path); - - compare(client, path, stat); - } - finally - { - CloseableUtils.closeQuietly(client); - } - } - - @Test - public void testCreateReturningStatCompressed() throws Exception - { - CuratorFramework client = createClient(); - try - { - client.start(); - - String path = "/bla"; - Stat stat = new Stat(); - client.create().compressed().storingStatIn(stat).forPath(path); - - compare(client, path, stat); - } - finally - { - CloseableUtils.closeQuietly(client); - } - } - - @Test - public void testCreateReturningStatWithProtected() throws Exception - { - CuratorFramework client = createClient(); - try - { - client.start(); - - String path = "/bla"; - Stat stat = new Stat(); - path = client.create().withProtection().storingStatIn(stat).forPath(path); - - compare(client, path, stat); - } - finally - { - CloseableUtils.closeQuietly(client); - } - } - - @Test - public void testCreateReturningStatInBackground() throws Exception - { - Timing timing = new Timing(); - CuratorFramework client = createClient(); - try - { - client.start(); - - String path = "/bla"; - Stat stat = new Stat(); - - final CountDownLatch latch = new CountDownLatch(1); - final AtomicReference statRef = new AtomicReference<>(); - BackgroundCallback callback = new BackgroundCallback() { - - @Override - public void processResult(CuratorFramework client, CuratorEvent event) throws Exception { - if(event.getType() == CuratorEventType.CREATE) - { - statRef.set(event.getStat()); - - latch.countDown(); - } - } - }; - - client.create().storingStatIn(stat).inBackground(callback).forPath(path); - - if(!timing.awaitLatch(latch)) - { - fail("Timed out awaing latch"); - } - - compare(client, path, statRef.get()); - compare(client, path, stat); - } - finally - { - CloseableUtils.closeQuietly(client); - } - } - - @Test - public void testIdempotentCreateReturningStat() throws Exception - { - CuratorFramework client = createClient(); - try - { - client.start(); - - String path = "/testidp"; - client.create().forPath(path); - - Stat stat = new Stat(); - client.create().idempotent().storingStatIn(stat).forPath(path); - - compare(client, path, stat); - } - finally - { - CloseableUtils.closeQuietly(client); - } - } -} +package org.apache.curator.framework.imps; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.atomic.AtomicReference; +import org.apache.curator.framework.CuratorFramework; +import org.apache.curator.framework.CuratorFrameworkFactory; +import org.apache.curator.framework.api.BackgroundCallback; +import org.apache.curator.framework.api.CuratorEvent; +import org.apache.curator.framework.api.CuratorEventType; +import org.apache.curator.retry.RetryOneTime; +import org.apache.curator.test.Timing; +import org.apache.curator.test.compatibility.CuratorTestBase; +import org.apache.curator.utils.CloseableUtils; +import org.apache.zookeeper.data.Stat; +import org.junit.jupiter.api.Test; + +public class TestCreateReturningStat extends CuratorTestBase { + private CuratorFramework createClient() { + return CuratorFrameworkFactory.builder() + .connectString(server.getConnectString()) + .retryPolicy(new RetryOneTime(1)) + .build(); + } + + private void compare(CuratorFramework client, String path, Stat expected) throws Exception { + Stat queriedStat = client.checkExists().forPath(path); + + assertEquals(queriedStat, expected); + } + + @Test + public void testOrSetDataStoringStatIn() throws Exception { + try (CuratorFramework client = createClient()) { + client.start(); + client.getZookeeperClient().blockUntilConnectedOrTimedOut(); + + final String path = "/test"; + + final Stat versionZeroStat = new Stat(); + client.create().orSetData().storingStatIn(versionZeroStat).forPath(path); + assertEquals(0, versionZeroStat.getVersion()); + + final Stat versionOneStat = new Stat(); + client.create().orSetData().storingStatIn(versionOneStat).forPath(path); + + assertEquals(versionZeroStat.getAversion(), versionOneStat.getAversion()); + assertEquals(versionZeroStat.getCtime(), versionOneStat.getCtime()); + assertEquals(versionZeroStat.getCversion(), versionOneStat.getCversion()); + assertEquals(versionZeroStat.getCzxid(), versionOneStat.getCzxid()); + assertEquals(versionZeroStat.getDataLength(), versionOneStat.getDataLength()); + assertEquals(versionZeroStat.getEphemeralOwner(), versionOneStat.getEphemeralOwner()); + assertTrue(versionZeroStat.getMtime() <= versionOneStat.getMtime()); + assertNotEquals(versionZeroStat.getMzxid(), versionOneStat.getMzxid()); + assertEquals(versionZeroStat.getNumChildren(), versionOneStat.getNumChildren()); + assertEquals(versionZeroStat.getPzxid(), versionOneStat.getPzxid()); + assertEquals(1, versionOneStat.getVersion()); + } + } + + @Test + public void testCreateReturningStat() throws Exception { + CuratorFramework client = createClient(); + try { + client.start(); + + String path = "/bla"; + Stat stat = new Stat(); + client.create().storingStatIn(stat).forPath(path); + + compare(client, path, stat); + } finally { + CloseableUtils.closeQuietly(client); + } + } + + @Test + public void testCreateReturningStatIncludingParents() throws Exception { + CuratorFramework client = createClient(); + try { + client.start(); + + String path = "/bla/bla"; + Stat stat = new Stat(); + client.create().creatingParentsIfNeeded().storingStatIn(stat).forPath(path); + + compare(client, path, stat); + } finally { + CloseableUtils.closeQuietly(client); + } + } + + @Test + public void testCreateReturningStatIncludingParentsReverse() throws Exception { + CuratorFramework client = createClient(); + try { + client.start(); + + String path = "/bla/bla"; + Stat stat = new Stat(); + client.create().storingStatIn(stat).creatingParentsIfNeeded().forPath(path); + + compare(client, path, stat); + } finally { + CloseableUtils.closeQuietly(client); + } + } + + @Test + public void testCreateReturningStatCompressed() throws Exception { + CuratorFramework client = createClient(); + try { + client.start(); + + String path = "/bla"; + Stat stat = new Stat(); + client.create().compressed().storingStatIn(stat).forPath(path); + + compare(client, path, stat); + } finally { + CloseableUtils.closeQuietly(client); + } + } + + @Test + public void testCreateReturningStatWithProtected() throws Exception { + CuratorFramework client = createClient(); + try { + client.start(); + + String path = "/bla"; + Stat stat = new Stat(); + path = client.create().withProtection().storingStatIn(stat).forPath(path); + + compare(client, path, stat); + } finally { + CloseableUtils.closeQuietly(client); + } + } + + @Test + public void testCreateReturningStatInBackground() throws Exception { + Timing timing = new Timing(); + CuratorFramework client = createClient(); + try { + client.start(); + + String path = "/bla"; + Stat stat = new Stat(); + + final CountDownLatch latch = new CountDownLatch(1); + final AtomicReference statRef = new AtomicReference<>(); + BackgroundCallback callback = new BackgroundCallback() { + + @Override + public void processResult(CuratorFramework client, CuratorEvent event) throws Exception { + if (event.getType() == CuratorEventType.CREATE) { + statRef.set(event.getStat()); + + latch.countDown(); + } + } + }; + + client.create().storingStatIn(stat).inBackground(callback).forPath(path); + + if (!timing.awaitLatch(latch)) { + fail("Timed out awaing latch"); + } + + compare(client, path, statRef.get()); + compare(client, path, stat); + } finally { + CloseableUtils.closeQuietly(client); + } + } + + @Test + public void testIdempotentCreateReturningStat() throws Exception { + CuratorFramework client = createClient(); + try { + client.start(); + + String path = "/testidp"; + client.create().forPath(path); + + Stat stat = new Stat(); + client.create().idempotent().storingStatIn(stat).forPath(path); + + compare(client, path, stat); + } finally { + CloseableUtils.closeQuietly(client); + } + } +} diff --git a/curator-framework/src/test/java/org/apache/curator/framework/imps/TestDelete.java b/curator-framework/src/test/java/org/apache/curator/framework/imps/TestDelete.java index 37deebe06..84e1a02cf 100644 --- a/curator-framework/src/test/java/org/apache/curator/framework/imps/TestDelete.java +++ b/curator-framework/src/test/java/org/apache/curator/framework/imps/TestDelete.java @@ -20,12 +20,15 @@ package org.apache.curator.framework.imps; import static org.apache.zookeeper.KeeperException.Code.*; -import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; - +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.api.BackgroundCallback; @@ -33,7 +36,6 @@ import org.apache.curator.framework.api.CuratorEvent; import org.apache.curator.framework.api.CuratorEventType; import org.apache.curator.framework.api.CuratorListener; -import org.apache.curator.framework.api.DeleteBuilder; import org.apache.curator.framework.api.DeleteBuilderMain; import org.apache.curator.retry.RetryOneTime; import org.apache.curator.test.BaseClassForTests; @@ -41,34 +43,25 @@ import org.apache.curator.utils.CloseableUtils; import org.apache.zookeeper.KeeperException; import org.junit.jupiter.api.Test; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.LinkedBlockingQueue; -import java.util.concurrent.atomic.AtomicInteger; -public class TestDelete extends BaseClassForTests -{ +public class TestDelete extends BaseClassForTests { private static byte[] createData = new byte[] {5, 6, 7, 8}; - private CuratorFramework createClient() - { - return CuratorFrameworkFactory.builder(). - connectString(server.getConnectString()). - retryPolicy(new RetryOneTime(1)). - build(); + private CuratorFramework createClient() { + return CuratorFrameworkFactory.builder() + .connectString(server.getConnectString()) + .retryPolicy(new RetryOneTime(1)) + .build(); } /** * Tests normal delete operations */ @Test - public void testNormal() throws Exception - { + public void testNormal() throws Exception { CuratorFramework client = createClient(); - try - { + try { client.start(); String path = "/test"; @@ -83,14 +76,12 @@ public void testNormal() throws Exception client.create().forPath(path, createData); // test fails with wrong verion check(client, client.delete().withVersion(1), path, BADVERSION.intValue()); - + // test succeeds with correct version check(client, client.delete().withVersion(0), path, OK.intValue()); client.create().forPath(path, createData); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } @@ -99,48 +90,41 @@ public void testNormal() throws Exception * Tests background versions of delete */ @Test - public void testBackground() throws Exception - { + public void testBackground() throws Exception { CuratorFramework client = createClient(); - try - { + try { client.start(); String path = "/test"; // test delete with no node fails checkBackground(client, client.delete(), path, NONODE.intValue()); - - client.create().forPath(path, createData); + + client.create().forPath(path, createData); // test delete with no version succeeds checkBackground(client, client.delete(), path, OK.intValue()); - + client.create().forPath(path, createData); // test fails with wrong verion checkBackground(client, client.delete().withVersion(1), path, BADVERSION.intValue()); - + // test succeeds with correct version checkBackground(client, client.delete().withVersion(0), path, OK.intValue()); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } - // TODO jslocum refactor these into common idempotent test utils? - private void checkBackground(CuratorFramework client, BackgroundPathable builder, String path, int expectedCode) throws Exception - { + private void checkBackground( + CuratorFramework client, BackgroundPathable builder, String path, int expectedCode) throws Exception { AtomicInteger actualCode = new AtomicInteger(-1); CountDownLatch latch = new CountDownLatch(1); - BackgroundCallback callback = new BackgroundCallback() - { + BackgroundCallback callback = new BackgroundCallback() { @Override - public void processResult(CuratorFramework client, CuratorEvent event) throws Exception - { + public void processResult(CuratorFramework client, CuratorEvent event) throws Exception { actualCode.set(event.getResultCode()); latch.countDown(); } @@ -151,22 +135,18 @@ public void processResult(CuratorFramework client, CuratorEvent event) throws Ex assertTrue(latch.await(5000, TimeUnit.MILLISECONDS), "Callback not invoked"); assertEquals(expectedCode, actualCode.get()); - if ( expectedCode == OK.intValue() ) - { + if (expectedCode == OK.intValue()) { assertNull(client.checkExists().forPath(path)); } } - private void check(CuratorFramework client, BackgroundPathable builder, String path, int expectedCode) throws Exception - { - try - { + private void check(CuratorFramework client, BackgroundPathable builder, String path, int expectedCode) + throws Exception { + try { builder.forPath(path); assertEquals(expectedCode, OK.intValue()); assertNull(client.checkExists().forPath(path)); - } - catch (KeeperException e) - { + } catch (KeeperException e) { assertEquals(expectedCode, e.getCode()); } } @@ -175,11 +155,9 @@ private void check(CuratorFramework client, BackgroundPathable builder, St * Tests all cases of idempotent delete */ @Test - public void testIdempotentDelete() throws Exception - { + public void testIdempotentDelete() throws Exception { CuratorFramework client = createClient(); - try - { + try { client.start(); String path = "/idpset"; @@ -216,22 +194,18 @@ public void testIdempotentDelete() throws Exception // check that idempotent delete fails with wrong version check(client, client.delete().idempotent().withVersion(0), path, BADVERSION.intValue()); checkBackground(client, client.delete().idempotent().withVersion(0), pathBack, BADVERSION.intValue()); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } - private DeleteBuilderMain clBefore(DeleteBuilderMain builder) - { - ((DeleteBuilderImpl)builder).failBeforeNextDeleteForTesting = true; + private DeleteBuilderMain clBefore(DeleteBuilderMain builder) { + ((DeleteBuilderImpl) builder).failBeforeNextDeleteForTesting = true; return builder; } - private DeleteBuilderMain clAfter(DeleteBuilderMain builder) - { - ((DeleteBuilderImpl)builder).failNextDeleteForTesting = true; + private DeleteBuilderMain clAfter(DeleteBuilderMain builder) { + ((DeleteBuilderImpl) builder).failNextDeleteForTesting = true; return builder; } @@ -239,15 +213,15 @@ private DeleteBuilderMain clAfter(DeleteBuilderMain builder) @Test public void testIdempotentDeleteConnectionLoss() throws Exception { CuratorFramework client = createClient(); - try - { + try { client.start(); String path = "/delete"; String pathBack = "/deleteBack"; String pathNormal = "/deleteNormal"; String pathNormalBack = "/deleteNormalBack"; - // test that connection loss before or after, version or no version, idempotent delete succeeds if node doesn't exist + // test that connection loss before or after, version or no version, idempotent delete succeeds if node + // doesn't exist check(client, clBefore(client.delete().idempotent()).withVersion(0), path, OK.intValue()); checkBackground(client, clBefore(client.delete().idempotent()).withVersion(0), pathBack, OK.intValue()); check(client, clBefore(client.delete().idempotent()), path, OK.intValue()); @@ -283,10 +257,12 @@ public void testIdempotentDeleteConnectionLoss() throws Exception { client.create().forPath(path, createData); client.create().forPath(pathBack, createData); check(client, clBefore(client.delete().idempotent()).withVersion(2), path, BADVERSION.intValue()); - checkBackground(client, clBefore(client.delete().idempotent()).withVersion(2), pathBack, BADVERSION.intValue()); + checkBackground( + client, clBefore(client.delete().idempotent()).withVersion(2), pathBack, BADVERSION.intValue()); check(client, clAfter(client.delete().idempotent()).withVersion(2), path, BADVERSION.intValue()); - checkBackground(client, clAfter(client.delete().idempotent()).withVersion(2), pathBack, BADVERSION.intValue()); + checkBackground( + client, clAfter(client.delete().idempotent()).withVersion(2), pathBack, BADVERSION.intValue()); // test that non-idempotent delete with or without version succeeds when retrying with connectionloss before client.create().forPath(pathNormal, createData); @@ -308,31 +284,25 @@ public void testIdempotentDeleteConnectionLoss() throws Exception { client.create().forPath(pathNormal, createData); client.create().forPath(pathNormalBack, createData); check(client, clAfter(client.delete()), pathNormal, NONODE.intValue()); - checkBackground(client, clAfter(client.delete()), pathNormalBack, NONODE.intValue()); - - } - finally - { + checkBackground(client, clAfter(client.delete()), pathNormalBack, NONODE.intValue()); + + } finally { CloseableUtils.closeQuietly(client); } } @Test - public void testQuietDelete() throws Exception - { + public void testQuietDelete() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); - try - { + try { client.start(); client.delete().quietly().forPath("/foo/bar"); final BlockingQueue rc = new LinkedBlockingQueue<>(); - BackgroundCallback backgroundCallback = new BackgroundCallback() - { + BackgroundCallback backgroundCallback = new BackgroundCallback() { @Override - public void processResult(CuratorFramework client, CuratorEvent event) throws Exception - { + public void processResult(CuratorFramework client, CuratorEvent event) throws Exception { rc.add(event.getResultCode()); } }; @@ -341,35 +311,25 @@ public void processResult(CuratorFramework client, CuratorEvent event) throws Ex Integer code = rc.poll(new Timing().milliseconds(), TimeUnit.MILLISECONDS); assertNotNull(code); assertEquals(code.intValue(), OK.intValue()); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } @Test - public void testBackgroundDelete() throws Exception - { + public void testBackgroundDelete() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client.start(); - try - { - client.getCuratorListenable().addListener - ( - new CuratorListener() - { - @Override - public void eventReceived(CuratorFramework client, CuratorEvent event) throws Exception - { - if ( event.getType() == CuratorEventType.DELETE ) - { - assertEquals(event.getPath(), "/head"); - ((CountDownLatch)event.getContext()).countDown(); - } - } + try { + client.getCuratorListenable().addListener(new CuratorListener() { + @Override + public void eventReceived(CuratorFramework client, CuratorEvent event) throws Exception { + if (event.getType() == CuratorEventType.DELETE) { + assertEquals(event.getPath(), "/head"); + ((CountDownLatch) event.getContext()).countDown(); } - ); + } + }); client.create().forPath("/head"); assertNotNull(client.checkExists().forPath("/head")); @@ -378,35 +338,25 @@ public void eventReceived(CuratorFramework client, CuratorEvent event) throws Ex client.delete().inBackground(latch).forPath("/head"); assertTrue(latch.await(10, TimeUnit.SECONDS)); assertNull(client.checkExists().forPath("/head")); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } @Test - public void testBackgroundDeleteWithChildren() throws Exception - { + public void testBackgroundDeleteWithChildren() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client.start(); - try - { - client.getCuratorListenable().addListener - ( - new CuratorListener() - { - @Override - public void eventReceived(CuratorFramework client, CuratorEvent event) throws Exception - { - if ( event.getType() == CuratorEventType.DELETE ) - { - assertEquals(event.getPath(), "/one/two"); - ((CountDownLatch)event.getContext()).countDown(); - } - } + try { + client.getCuratorListenable().addListener(new CuratorListener() { + @Override + public void eventReceived(CuratorFramework client, CuratorEvent event) throws Exception { + if (event.getType() == CuratorEventType.DELETE) { + assertEquals(event.getPath(), "/one/two"); + ((CountDownLatch) event.getContext()).countDown(); } - ); + } + }); client.create().creatingParentsIfNeeded().forPath("/one/two/three/four"); assertNotNull(client.checkExists().forPath("/one/two/three/four")); @@ -415,69 +365,58 @@ public void eventReceived(CuratorFramework client, CuratorEvent event) throws Ex client.delete().deletingChildrenIfNeeded().inBackground(latch).forPath("/one/two"); assertTrue(latch.await(10, TimeUnit.SECONDS)); assertNull(client.checkExists().forPath("/one/two")); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } @Test - public void testDelete() throws Exception - { + public void testDelete() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client.start(); - try - { + try { client.create().forPath("/head"); assertNotNull(client.checkExists().forPath("/head")); client.delete().forPath("/head"); assertNull(client.checkExists().forPath("/head")); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } @Test - public void testDeleteWithChildren() throws Exception - { + public void testDeleteWithChildren() throws Exception { CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder(); - CuratorFramework client = builder.connectString(server.getConnectString()).retryPolicy(new RetryOneTime(1)).build(); + CuratorFramework client = builder.connectString(server.getConnectString()) + .retryPolicy(new RetryOneTime(1)) + .build(); client.start(); - try - { + try { client.create().creatingParentsIfNeeded().forPath("/one/two/three/four/five/six", "foo".getBytes()); client.delete().deletingChildrenIfNeeded().forPath("/one/two/three/four/five"); assertNull(client.checkExists().forPath("/one/two/three/four/five")); client.delete().deletingChildrenIfNeeded().forPath("/one/two"); assertNull(client.checkExists().forPath("/one/two")); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } @Test - public void testDeleteGuaranteedWithChildren() throws Exception - { + public void testDeleteGuaranteedWithChildren() throws Exception { CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder(); - CuratorFramework client = builder.connectString(server.getConnectString()).retryPolicy(new RetryOneTime(1)).build(); + CuratorFramework client = builder.connectString(server.getConnectString()) + .retryPolicy(new RetryOneTime(1)) + .build(); client.start(); - try - { + try { client.create().creatingParentsIfNeeded().forPath("/one/two/three/four/five/six", "foo".getBytes()); client.delete().guaranteed().deletingChildrenIfNeeded().forPath("/one/two/three/four/five"); assertNull(client.checkExists().forPath("/one/two/three/four/five")); client.delete().guaranteed().deletingChildrenIfNeeded().forPath("/one/two"); assertNull(client.checkExists().forPath("/one/two")); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } - } diff --git a/curator-framework/src/test/java/org/apache/curator/framework/imps/TestEnabledSessionExpiredState.java b/curator-framework/src/test/java/org/apache/curator/framework/imps/TestEnabledSessionExpiredState.java index 2ac49a632..d3e15c7f5 100644 --- a/curator-framework/src/test/java/org/apache/curator/framework/imps/TestEnabledSessionExpiredState.java +++ b/curator-framework/src/test/java/org/apache/curator/framework/imps/TestEnabledSessionExpiredState.java @@ -23,6 +23,9 @@ import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; import com.google.common.collect.Queues; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.state.ConnectionState; @@ -38,12 +41,7 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; - -public class TestEnabledSessionExpiredState extends BaseClassForTests -{ +public class TestEnabledSessionExpiredState extends BaseClassForTests { private final Timing2 timing = new Timing2(); private CuratorFramework client; @@ -51,24 +49,21 @@ public class TestEnabledSessionExpiredState extends BaseClassForTests @BeforeEach @Override - public void setup() throws Exception - { + public void setup() throws Exception { super.setup(); client = CuratorFrameworkFactory.builder() - .connectString(server.getConnectString()) - .connectionTimeoutMs(timing.connection()) - .sessionTimeoutMs(timing.session()) - .retryPolicy(new RetryOneTime(1)) - .build(); + .connectString(server.getConnectString()) + .connectionTimeoutMs(timing.connection()) + .sessionTimeoutMs(timing.session()) + .retryPolicy(new RetryOneTime(1)) + .build(); client.start(); states = Queues.newLinkedBlockingQueue(); - ConnectionStateListener listener = new ConnectionStateListener() - { + ConnectionStateListener listener = new ConnectionStateListener() { @Override - public void stateChanged(CuratorFramework client, ConnectionState newState) - { + public void stateChanged(CuratorFramework client, ConnectionState newState) { states.add(newState); } }; @@ -77,23 +72,18 @@ public void stateChanged(CuratorFramework client, ConnectionState newState) @AfterEach @Override - public void teardown() throws Exception - { - try - { + public void teardown() throws Exception { + try { CloseableUtils.closeQuietly(client); - } - finally - { + } finally { super.teardown(); } } @Test - public void testResetCausesLost() throws Exception - { + public void testResetCausesLost() throws Exception { assertEquals(states.poll(timing.milliseconds(), TimeUnit.MILLISECONDS), ConnectionState.CONNECTED); - client.checkExists().forPath("/"); // establish initial connection + client.checkExists().forPath("/"); // establish initial connection client.getZookeeperClient().reset(); assertEquals(states.poll(timing.milliseconds(), TimeUnit.MILLISECONDS), ConnectionState.LOST); @@ -101,20 +91,15 @@ public void testResetCausesLost() throws Exception } @Test - public void testInjectedWatchedEvent() throws Exception - { + public void testInjectedWatchedEvent() throws Exception { assertEquals(states.poll(timing.milliseconds(), TimeUnit.MILLISECONDS), ConnectionState.CONNECTED); final CountDownLatch latch = new CountDownLatch(1); - Watcher watcher = new Watcher() - { + Watcher watcher = new Watcher() { @Override - public void process(WatchedEvent event) - { - if ( event.getType() == Event.EventType.None ) - { - if ( event.getState() == Event.KeeperState.Expired ) - { + public void process(WatchedEvent event) { + if (event.getType() == Event.EventType.None) { + if (event.getState() == Event.KeeperState.Expired) { latch.countDown(); } } @@ -126,8 +111,7 @@ public void process(WatchedEvent event) } @Test - public void testKillSession() throws Exception - { + public void testKillSession() throws Exception { assertEquals(states.poll(timing.milliseconds(), TimeUnit.MILLISECONDS), ConnectionState.CONNECTED); client.getZookeeperClient().getZooKeeper().getTestable().injectSessionExpiration(); @@ -137,16 +121,12 @@ public void testKillSession() throws Exception } @Test - public void testReconnectWithoutExpiration() throws Exception - { + public void testReconnectWithoutExpiration() throws Exception { assertEquals(states.poll(timing.milliseconds(), TimeUnit.MILLISECONDS), ConnectionState.CONNECTED); server.stop(); - try - { - client.checkExists().forPath("/"); // any API call that will invoke the retry policy, etc. - } - catch ( KeeperException.ConnectionLossException ignore ) - { + try { + client.checkExists().forPath("/"); // any API call that will invoke the retry policy, etc. + } catch (KeeperException.ConnectionLossException ignore) { } assertEquals(states.poll(timing.milliseconds(), TimeUnit.MILLISECONDS), ConnectionState.SUSPENDED); server.restart(); @@ -155,8 +135,7 @@ public void testReconnectWithoutExpiration() throws Exception } @Test - public void testSessionExpirationFromTimeout() throws Exception - { + public void testSessionExpirationFromTimeout() throws Exception { assertEquals(states.poll(timing.milliseconds(), TimeUnit.MILLISECONDS), ConnectionState.CONNECTED); server.stop(); assertEquals(states.poll(timing.milliseconds(), TimeUnit.MILLISECONDS), ConnectionState.SUSPENDED); @@ -164,8 +143,7 @@ public void testSessionExpirationFromTimeout() throws Exception } @Test - public void testSessionExpirationFromTimeoutWithRestart() throws Exception - { + public void testSessionExpirationFromTimeoutWithRestart() throws Exception { assertEquals(states.poll(timing.milliseconds(), TimeUnit.MILLISECONDS), ConnectionState.CONNECTED); server.stop(); timing.forSessionSleep().sleep(); @@ -175,6 +153,7 @@ public void testSessionExpirationFromTimeoutWithRestart() throws Exception client.checkExists().forPath("/"); assertEquals(states.poll(timing.milliseconds(), TimeUnit.MILLISECONDS), ConnectionState.RECONNECTED); - assertNull(states.poll(timing.multiple(.5).milliseconds(), TimeUnit.MILLISECONDS)); // there should be no other events + assertNull(states.poll( + timing.multiple(.5).milliseconds(), TimeUnit.MILLISECONDS)); // there should be no other events } } diff --git a/curator-framework/src/test/java/org/apache/curator/framework/imps/TestEnsureContainers.java b/curator-framework/src/test/java/org/apache/curator/framework/imps/TestEnsureContainers.java index 2e6ad8a35..1c1101ae2 100644 --- a/curator-framework/src/test/java/org/apache/curator/framework/imps/TestEnsureContainers.java +++ b/curator-framework/src/test/java/org/apache/curator/framework/imps/TestEnsureContainers.java @@ -21,7 +21,6 @@ import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; - import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.EnsureContainers; @@ -30,33 +29,26 @@ import org.apache.curator.utils.CloseableUtils; import org.junit.jupiter.api.Test; -public class TestEnsureContainers extends BaseClassForTests -{ +public class TestEnsureContainers extends BaseClassForTests { @Test - public void testBasic() throws Exception - { + public void testBasic() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); - try - { + try { client.start(); EnsureContainers ensureContainers = new EnsureContainers(client, "/one/two/three"); ensureContainers.ensure(); assertNotNull(client.checkExists().forPath("/one/two/three")); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } @Test - public void testSingleExecution() throws Exception - { + public void testSingleExecution() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); - try - { + try { client.start(); EnsureContainers ensureContainers = new EnsureContainers(client, "/one/two/three"); @@ -67,9 +59,7 @@ public void testSingleExecution() throws Exception client.delete().forPath("/one/two/three"); ensureContainers.ensure(); assertNull(client.checkExists().forPath("/one/two/three")); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } diff --git a/curator-framework/src/test/java/org/apache/curator/framework/imps/TestExistsBuilder.java b/curator-framework/src/test/java/org/apache/curator/framework/imps/TestExistsBuilder.java index 0ac2d43e0..050b9ddef 100644 --- a/curator-framework/src/test/java/org/apache/curator/framework/imps/TestExistsBuilder.java +++ b/curator-framework/src/test/java/org/apache/curator/framework/imps/TestExistsBuilder.java @@ -23,6 +23,10 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; +import java.util.Collections; +import java.util.List; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.api.ACLProvider; @@ -35,11 +39,6 @@ import org.apache.zookeeper.data.ACL; import org.junit.jupiter.api.Test; -import java.util.Collections; -import java.util.List; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; - public class TestExistsBuilder extends BaseClassForTests { /** @@ -47,64 +46,60 @@ public class TestExistsBuilder extends BaseClassForTests { * parents. */ @Test - public void testExistsWithParentsWithAclApplyToParents() throws Exception - { + public void testExistsWithParentsWithAclApplyToParents() throws Exception { CuratorFramework client = createClient(new DefaultACLProvider()); - try - { + try { client.start(); String path = "/bar/foo/test"; - List acl = Collections.singletonList(new ACL(ZooDefs.Perms.CREATE | ZooDefs.Perms.READ, ANYONE_ID_UNSAFE)); - assertNull(client.checkExists().creatingParentsIfNeeded().withACL(acl).forPath(path)); + List acl = + Collections.singletonList(new ACL(ZooDefs.Perms.CREATE | ZooDefs.Perms.READ, ANYONE_ID_UNSAFE)); + assertNull( + client.checkExists().creatingParentsIfNeeded().withACL(acl).forPath(path)); List actual_bar = client.getACL().forPath("/bar"); assertEquals(actual_bar, acl); List actual_bar_foo = client.getACL().forPath("/bar/foo"); assertEquals(actual_bar_foo, acl); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } @Test - public void testExistsWithParentsWithAclApplyToParentsInBackground() throws Exception - { + public void testExistsWithParentsWithAclApplyToParentsInBackground() throws Exception { CuratorFramework client = createClient(new DefaultACLProvider()); - try - { + try { client.start(); final CountDownLatch latch = new CountDownLatch(1); String path = "/bar/foo/test"; - List acl = Collections.singletonList(new ACL(ZooDefs.Perms.CREATE | ZooDefs.Perms.READ, ANYONE_ID_UNSAFE)); - BackgroundCallback callback = new BackgroundCallback() - { + List acl = + Collections.singletonList(new ACL(ZooDefs.Perms.CREATE | ZooDefs.Perms.READ, ANYONE_ID_UNSAFE)); + BackgroundCallback callback = new BackgroundCallback() { @Override - public void processResult(CuratorFramework client, CuratorEvent event) throws Exception - { + public void processResult(CuratorFramework client, CuratorEvent event) throws Exception { latch.countDown(); } }; - client.checkExists().creatingParentsIfNeeded().withACL(acl).inBackground(callback).forPath(path); + client.checkExists() + .creatingParentsIfNeeded() + .withACL(acl) + .inBackground(callback) + .forPath(path); assertTrue(latch.await(2000, TimeUnit.MILLISECONDS), "Callback not invoked"); List actual_bar = client.getACL().forPath("/bar"); assertEquals(actual_bar, acl); List actual_bar_foo = client.getACL().forPath("/bar/foo"); assertEquals(actual_bar_foo, acl); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } - private CuratorFramework createClient(ACLProvider aclProvider) - { - return CuratorFrameworkFactory.builder(). - aclProvider(aclProvider). - connectString(server.getConnectString()). - retryPolicy(new RetryOneTime(1)). - build(); + private CuratorFramework createClient(ACLProvider aclProvider) { + return CuratorFrameworkFactory.builder() + .aclProvider(aclProvider) + .connectString(server.getConnectString()) + .retryPolicy(new RetryOneTime(1)) + .build(); } } diff --git a/curator-framework/src/test/java/org/apache/curator/framework/imps/TestFailedDeleteManager.java b/curator-framework/src/test/java/org/apache/curator/framework/imps/TestFailedDeleteManager.java index 8b87f8e8a..fdafbabcd 100644 --- a/curator-framework/src/test/java/org/apache/curator/framework/imps/TestFailedDeleteManager.java +++ b/curator-framework/src/test/java/org/apache/curator/framework/imps/TestFailedDeleteManager.java @@ -24,7 +24,9 @@ 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.CountDownLatch; +import java.util.concurrent.Semaphore; +import java.util.concurrent.atomic.AtomicBoolean; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.api.BackgroundCallback; @@ -40,36 +42,25 @@ import org.apache.zookeeper.KeeperException.NoNodeException; import org.junit.jupiter.api.Test; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.Semaphore; -import java.util.concurrent.atomic.AtomicBoolean; - -public class TestFailedDeleteManager extends BaseClassForTests -{ +public class TestFailedDeleteManager extends BaseClassForTests { @Test - public void testLostSession() throws Exception - { - Timing timing = new Timing(); - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new ExponentialBackoffRetry(100, 3)); - try - { + public void testLostSession() throws Exception { + Timing timing = new Timing(); + CuratorFramework client = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), timing.connection(), new ExponentialBackoffRetry(100, 3)); + try { client.start(); client.create().forPath("/test-me"); - final CountDownLatch latch = new CountDownLatch(1); - final Semaphore semaphore = new Semaphore(0); - ConnectionStateListener listener = new ConnectionStateListener() - { + final CountDownLatch latch = new CountDownLatch(1); + final Semaphore semaphore = new Semaphore(0); + ConnectionStateListener listener = new ConnectionStateListener() { @Override - public void stateChanged(CuratorFramework client, ConnectionState newState) - { - if ( (newState == ConnectionState.LOST) || (newState == ConnectionState.SUSPENDED) ) - { + public void stateChanged(CuratorFramework client, ConnectionState newState) { + if ((newState == ConnectionState.LOST) || (newState == ConnectionState.SUSPENDED)) { semaphore.release(); - } - else if ( newState == ConnectionState.RECONNECTED ) - { + } else if (newState == ConnectionState.RECONNECTED) { latch.countDown(); } } @@ -78,13 +69,10 @@ else if ( newState == ConnectionState.RECONNECTED ) server.stop(); assertTrue(timing.acquireSemaphore(semaphore)); - try - { + try { client.delete().guaranteed().forPath("/test-me"); fail(); - } - catch ( KeeperException.ConnectionLossException | KeeperException.SessionExpiredException e ) - { + } catch (KeeperException.ConnectionLossException | KeeperException.SessionExpiredException e) { // expected } assertTrue(timing.acquireSemaphore(semaphore)); @@ -97,42 +85,34 @@ else if ( newState == ConnectionState.RECONNECTED ) timing.sleepABit(); assertNull(client.checkExists().forPath("/test-me")); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } @Test - public void testWithNamespaceAndLostSession() throws Exception - { - Timing timing = new Timing(); - CuratorFramework client = CuratorFrameworkFactory.builder().connectString(server.getConnectString()) - .sessionTimeoutMs(timing.session()) - .connectionTimeoutMs(timing.connection()) - .retryPolicy(new ExponentialBackoffRetry(100, 3)) - .namespace("aisa") - .build(); - try - { + public void testWithNamespaceAndLostSession() throws Exception { + Timing timing = new Timing(); + CuratorFramework client = CuratorFrameworkFactory.builder() + .connectString(server.getConnectString()) + .sessionTimeoutMs(timing.session()) + .connectionTimeoutMs(timing.connection()) + .retryPolicy(new ExponentialBackoffRetry(100, 3)) + .namespace("aisa") + .build(); + try { client.start(); client.create().forPath("/test-me"); - final CountDownLatch latch = new CountDownLatch(1); - final Semaphore semaphore = new Semaphore(0); - ConnectionStateListener listener = new ConnectionStateListener() - { + final CountDownLatch latch = new CountDownLatch(1); + final Semaphore semaphore = new Semaphore(0); + ConnectionStateListener listener = new ConnectionStateListener() { @Override - public void stateChanged(CuratorFramework client, ConnectionState newState) - { - if ( (newState == ConnectionState.LOST) || (newState == ConnectionState.SUSPENDED) ) - { + public void stateChanged(CuratorFramework client, ConnectionState newState) { + if ((newState == ConnectionState.LOST) || (newState == ConnectionState.SUSPENDED)) { semaphore.release(); - } - else if ( newState == ConnectionState.RECONNECTED ) - { + } else if (newState == ConnectionState.RECONNECTED) { latch.countDown(); } } @@ -141,13 +121,10 @@ else if ( newState == ConnectionState.RECONNECTED ) server.stop(); assertTrue(timing.acquireSemaphore(semaphore)); - try - { + try { client.delete().guaranteed().forPath("/test-me"); fail(); - } - catch ( KeeperException.ConnectionLossException | KeeperException.SessionExpiredException e ) - { + } catch (KeeperException.ConnectionLossException | KeeperException.SessionExpiredException e) { // expected } assertTrue(timing.acquireSemaphore(semaphore)); @@ -160,42 +137,34 @@ else if ( newState == ConnectionState.RECONNECTED ) timing.sleepABit(); assertNull(client.checkExists().forPath("/test-me")); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } @Test - public void testWithNamespaceAndLostSessionAlt() throws Exception - { - Timing timing = new Timing(); - CuratorFramework client = CuratorFrameworkFactory.builder().connectString(server.getConnectString()) - .sessionTimeoutMs(timing.session()) - .connectionTimeoutMs(timing.connection()) - .retryPolicy(new ExponentialBackoffRetry(100, 3)) - .build(); - try - { + public void testWithNamespaceAndLostSessionAlt() throws Exception { + Timing timing = new Timing(); + CuratorFramework client = CuratorFrameworkFactory.builder() + .connectString(server.getConnectString()) + .sessionTimeoutMs(timing.session()) + .connectionTimeoutMs(timing.connection()) + .retryPolicy(new ExponentialBackoffRetry(100, 3)) + .build(); + try { client.start(); - CuratorFramework namespaceClient = client.usingNamespace("foo"); + CuratorFramework namespaceClient = client.usingNamespace("foo"); namespaceClient.create().forPath("/test-me"); - final CountDownLatch latch = new CountDownLatch(1); - final Semaphore semaphore = new Semaphore(0); - ConnectionStateListener listener = new ConnectionStateListener() - { + final CountDownLatch latch = new CountDownLatch(1); + final Semaphore semaphore = new Semaphore(0); + ConnectionStateListener listener = new ConnectionStateListener() { @Override - public void stateChanged(CuratorFramework client, ConnectionState newState) - { - if ( (newState == ConnectionState.LOST) || (newState == ConnectionState.SUSPENDED) ) - { + public void stateChanged(CuratorFramework client, ConnectionState newState) { + if ((newState == ConnectionState.LOST) || (newState == ConnectionState.SUSPENDED)) { semaphore.release(); - } - else if ( newState == ConnectionState.RECONNECTED ) - { + } else if (newState == ConnectionState.RECONNECTED) { latch.countDown(); } } @@ -204,13 +173,10 @@ else if ( newState == ConnectionState.RECONNECTED ) server.stop(); assertTrue(timing.acquireSemaphore(semaphore)); - try - { + try { namespaceClient.delete().guaranteed().forPath("/test-me"); fail(); - } - catch ( KeeperException.ConnectionLossException | KeeperException.SessionExpiredException e ) - { + } catch (KeeperException.ConnectionLossException | KeeperException.SessionExpiredException e) { // expected } assertTrue(timing.acquireSemaphore(semaphore)); @@ -223,148 +189,122 @@ else if ( newState == ConnectionState.RECONNECTED ) timing.sleepABit(); assertNull(namespaceClient.checkExists().forPath("/test-me")); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } @Test - public void testBasic() throws Exception - { + public void testBasic() throws Exception { final String PATH = "/one/two/three"; - Timing timing = new Timing(); + Timing timing = new Timing(); CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder(); - builder.connectString(server.getConnectString()).retryPolicy(new RetryOneTime(1)).connectionTimeoutMs(timing.connection()).sessionTimeoutMs(timing.session()); - CuratorFrameworkImpl client = new CuratorFrameworkImpl(builder); + builder.connectString(server.getConnectString()) + .retryPolicy(new RetryOneTime(1)) + .connectionTimeoutMs(timing.connection()) + .sessionTimeoutMs(timing.session()); + CuratorFrameworkImpl client = new CuratorFrameworkImpl(builder); client.start(); - try - { + try { client.create().creatingParentsIfNeeded().forPath(PATH); assertNotNull(client.checkExists().forPath(PATH)); server.stop(); // cause the next delete to fail - try - { + try { client.delete().forPath(PATH); fail(); - } - catch ( KeeperException.ConnectionLossException | KeeperException.SessionExpiredException e ) - { + } catch (KeeperException.ConnectionLossException | KeeperException.SessionExpiredException e) { // expected } - + server.restart(); assertNotNull(client.checkExists().forPath(PATH)); server.stop(); // cause the next delete to fail - try - { + try { client.delete().guaranteed().forPath(PATH); fail(); - } - catch ( KeeperException.ConnectionLossException | KeeperException.SessionExpiredException e ) - { + } catch (KeeperException.ConnectionLossException | KeeperException.SessionExpiredException e) { // expected } server.restart(); - final int TRIES = 5; - for ( int i = 0; i < TRIES; ++i ) - { - if ( client.checkExists().forPath(PATH) != null ) - { + final int TRIES = 5; + for (int i = 0; i < TRIES; ++i) { + if (client.checkExists().forPath(PATH) != null) { timing.sleepABit(); } } assertNull(client.checkExists().forPath(PATH)); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } - + @Test - public void testGuaranteedDeleteOnNonExistentNodeInForeground() throws Exception - { + public void testGuaranteedDeleteOnNonExistentNodeInForeground() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client.start(); - + final AtomicBoolean pathAdded = new AtomicBoolean(false); - - ((CuratorFrameworkImpl)client).getFailedDeleteManager().debugListener = new FailedOperationManager.FailedOperationManagerListener() - { - - @Override - public void pathAddedForGuaranteedOperation(String path) - { - pathAdded.set(true); - } - }; - - try - { + + ((CuratorFrameworkImpl) client).getFailedDeleteManager().debugListener = + new FailedOperationManager.FailedOperationManagerListener() { + + @Override + public void pathAddedForGuaranteedOperation(String path) { + pathAdded.set(true); + } + }; + + try { client.delete().guaranteed().forPath("/nonexistent"); fail(); - } - catch(NoNodeException e) - { - //Exception is expected, the delete should not be retried + } catch (NoNodeException e) { + // Exception is expected, the delete should not be retried assertFalse(pathAdded.get()); - } - finally - { + } finally { client.close(); - } + } } - + @Test - public void testGuaranteedDeleteOnNonExistentNodeInBackground() throws Exception - { + public void testGuaranteedDeleteOnNonExistentNodeInBackground() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client.start(); - + final AtomicBoolean pathAdded = new AtomicBoolean(false); - - ((CuratorFrameworkImpl)client).getFailedDeleteManager().debugListener = new FailedOperationManager.FailedOperationManagerListener() - { - - @Override - public void pathAddedForGuaranteedOperation(String path) - { - pathAdded.set(true); - } - }; - + + ((CuratorFrameworkImpl) client).getFailedDeleteManager().debugListener = + new FailedOperationManager.FailedOperationManagerListener() { + + @Override + public void pathAddedForGuaranteedOperation(String path) { + pathAdded.set(true); + } + }; + final CountDownLatch backgroundLatch = new CountDownLatch(1); - - BackgroundCallback background = new BackgroundCallback() - { - + + BackgroundCallback background = new BackgroundCallback() { + @Override - public void processResult(CuratorFramework client, CuratorEvent event) - throws Exception - { + public void processResult(CuratorFramework client, CuratorEvent event) throws Exception { backgroundLatch.countDown(); } }; - - try - { + + try { client.delete().guaranteed().inBackground(background).forPath("/nonexistent"); - + backgroundLatch.await(); - - //Exception is expected, the delete should not be retried + + // Exception is expected, the delete should not be retried assertFalse(pathAdded.get()); - } - finally - { + } finally { client.close(); - } - } + } + } } diff --git a/curator-framework/src/test/java/org/apache/curator/framework/imps/TestFramework.java b/curator-framework/src/test/java/org/apache/curator/framework/imps/TestFramework.java index 5eb632f93..f66fec642 100644 --- a/curator-framework/src/test/java/org/apache/curator/framework/imps/TestFramework.java +++ b/curator-framework/src/test/java/org/apache/curator/framework/imps/TestFramework.java @@ -26,7 +26,7 @@ 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 com.google.common.collect.Lists; import java.io.IOException; import java.util.ArrayList; import java.util.List; @@ -35,7 +35,6 @@ import java.util.concurrent.CountDownLatch; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; - import org.apache.curator.framework.AuthInfo; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; @@ -70,43 +69,35 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.google.common.collect.Lists; - @SuppressWarnings("deprecation") @Tag(CuratorTestBase.zk35TestCompatibilityGroup) -public class TestFramework extends BaseClassForTests -{ - private final Logger log = LoggerFactory.getLogger(getClass()); - +public class TestFramework extends BaseClassForTests { + private final Logger log = LoggerFactory.getLogger(getClass()); + @BeforeEach @Override - public void setup() throws Exception - { + public void setup() throws Exception { System.setProperty("znode.container.checkIntervalMs", "1000"); super.setup(); } @AfterEach @Override - public void teardown() throws Exception - { + public void teardown() throws Exception { System.clearProperty("znode.container.checkIntervalMs"); super.teardown(); } - public void testWaitForShutdownTimeoutMs() throws Exception - { + public void testWaitForShutdownTimeoutMs() throws Exception { final BlockingQueue timeoutQueue = new ArrayBlockingQueue<>(1); - ZookeeperFactory zookeeperFactory = new ZookeeperFactory() - { + ZookeeperFactory zookeeperFactory = new ZookeeperFactory() { @Override - public ZooKeeper newZooKeeper(String connectString, int sessionTimeout, Watcher watcher, boolean canBeReadOnly) throws IOException - { - return new ZooKeeper(connectString, sessionTimeout, watcher, canBeReadOnly) - { + public ZooKeeper newZooKeeper( + String connectString, int sessionTimeout, Watcher watcher, boolean canBeReadOnly) + throws IOException { + return new ZooKeeper(connectString, sessionTimeout, watcher, canBeReadOnly) { @Override - public boolean close(int waitForShutdownTimeoutMs) throws InterruptedException - { + public boolean close(int waitForShutdownTimeoutMs) throws InterruptedException { timeoutQueue.add(waitForShutdownTimeoutMs); return super.close(waitForShutdownTimeoutMs); } @@ -115,18 +106,15 @@ public boolean close(int waitForShutdownTimeoutMs) throws InterruptedException }; CuratorFramework client = CuratorFrameworkFactory.builder() - .connectString(server.getConnectString()) - .retryPolicy(new RetryOneTime(1)) - .zookeeperFactory(zookeeperFactory) - .waitForShutdownTimeoutMs(10064) - .build(); - try - { + .connectString(server.getConnectString()) + .retryPolicy(new RetryOneTime(1)) + .zookeeperFactory(zookeeperFactory) + .waitForShutdownTimeoutMs(10064) + .build(); + try { client.start(); client.checkExists().forPath("/foo"); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } @@ -136,63 +124,54 @@ public boolean close(int waitForShutdownTimeoutMs) throws InterruptedException } @Test - public void testSessionLossWithLongTimeout() throws Exception - { + public void testSessionLossWithLongTimeout() throws Exception { final Timing timing = new Timing(); - try(final CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.forWaiting().milliseconds(), - timing.connection(), new RetryOneTime(1))) - { + try (final CuratorFramework client = CuratorFrameworkFactory.newClient( + server.getConnectString(), + timing.forWaiting().milliseconds(), + timing.connection(), + new RetryOneTime(1))) { final CountDownLatch connectedLatch = new CountDownLatch(1); final CountDownLatch lostLatch = new CountDownLatch(1); final CountDownLatch restartedLatch = new CountDownLatch(1); - client.getConnectionStateListenable().addListener(new ConnectionStateListener() - { + client.getConnectionStateListenable().addListener(new ConnectionStateListener() { @Override - public void stateChanged(CuratorFramework client, ConnectionState newState) - { - if ( newState == ConnectionState.CONNECTED ) - { + public void stateChanged(CuratorFramework client, ConnectionState newState) { + if (newState == ConnectionState.CONNECTED) { connectedLatch.countDown(); - } - else if ( newState == ConnectionState.LOST ) - { + } else if (newState == ConnectionState.LOST) { lostLatch.countDown(); - } - else if ( newState == ConnectionState.RECONNECTED ) - { + } else if (newState == ConnectionState.RECONNECTED) { restartedLatch.countDown(); } } }); - + client.start(); - + assertTrue(timing.awaitLatch(connectedLatch)); - + server.stop(); timing.sleepABit(); assertTrue(timing.awaitLatch(lostLatch)); - + server.restart(); assertTrue(timing.awaitLatch(restartedLatch)); } } @Test - public void testConnectionState() throws Exception - { + public void testConnectionState() throws Exception { Timing timing = new Timing(); - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); - try - { + CuratorFramework client = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); + try { final BlockingQueue queue = new LinkedBlockingQueue(); - ConnectionStateListener listener = new ConnectionStateListener() - { + ConnectionStateListener listener = new ConnectionStateListener() { @Override - public void stateChanged(CuratorFramework client, ConnectionState newState) - { + public void stateChanged(CuratorFramework client, ConnectionState newState) { queue.add(newState); } }; @@ -203,19 +182,15 @@ public void stateChanged(CuratorFramework client, ConnectionState newState) server.stop(); assertEquals(queue.poll(timing.multiple(4).seconds(), TimeUnit.SECONDS), ConnectionState.SUSPENDED); assertEquals(queue.poll(timing.multiple(4).seconds(), TimeUnit.SECONDS), ConnectionState.LOST); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } @Test - public void testCreateOrSetData() throws Exception - { + public void testCreateOrSetData() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); - try - { + try { client.start(); String name = client.create().forPath("/hey", "there".getBytes()); @@ -231,11 +206,9 @@ public void testCreateOrSetData() throws Exception assertArrayEquals(client.getData().forPath("/a/b/c"), "what".getBytes()); final BlockingQueue queue = new LinkedBlockingQueue<>(); - BackgroundCallback backgroundCallback = new BackgroundCallback() - { + BackgroundCallback backgroundCallback = new BackgroundCallback() { @Override - public void processResult(CuratorFramework client, CuratorEvent event) throws Exception - { + public void processResult(CuratorFramework client, CuratorEvent event) throws Exception { queue.add(event); } }; @@ -251,33 +224,27 @@ public void processResult(CuratorFramework client, CuratorEvent event) throws Ex // callback should only be called once CuratorEvent unexpectedEvent = queue.poll(new Timing().milliseconds(), TimeUnit.MILLISECONDS); assertNull(unexpectedEvent); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } @Test - public void testNamespaceWithWatcher() throws Exception - { + public void testNamespaceWithWatcher() throws Exception { CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder(); - CuratorFramework client = builder.connectString(server.getConnectString()).namespace("aisa").retryPolicy(new RetryOneTime(1)).build(); + CuratorFramework client = builder.connectString(server.getConnectString()) + .namespace("aisa") + .retryPolicy(new RetryOneTime(1)) + .build(); client.start(); - try - { + try { final BlockingQueue queue = new LinkedBlockingQueue(); - Watcher watcher = new Watcher() - { + Watcher watcher = new Watcher() { @Override - public void process(WatchedEvent event) - { - try - { + public void process(WatchedEvent event) { + try { queue.put(event.getPath()); - } - catch ( InterruptedException e ) - { + } catch (InterruptedException e) { throw new Error(e); } } @@ -288,29 +255,25 @@ public void process(WatchedEvent event) String path = new Timing2().takeFromQueue(queue); assertEquals(path, "/base"); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } @Test - public void testNamespaceInBackground() throws Exception - { + public void testNamespaceInBackground() throws Exception { CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder(); - CuratorFramework client = builder.connectString(server.getConnectString()).namespace("aisa").retryPolicy(new RetryOneTime(1)).build(); + CuratorFramework client = builder.connectString(server.getConnectString()) + .namespace("aisa") + .retryPolicy(new RetryOneTime(1)) + .build(); client.start(); - try - { + try { final BlockingQueue queue = new LinkedBlockingQueue(); - CuratorListener listener = new CuratorListener() - { + CuratorListener listener = new CuratorListener() { @Override - public void eventReceived(CuratorFramework client, CuratorEvent event) throws Exception - { - if ( event.getType() == CuratorEventType.EXISTS ) - { + public void eventReceived(CuratorFramework client, CuratorEvent event) throws Exception { + if (event.getType() == CuratorEventType.EXISTS) { queue.put(event.getPath()); } } @@ -325,87 +288,69 @@ public void eventReceived(CuratorFramework client, CuratorEvent event) throws Ex client.getCuratorListenable().removeListener(listener); - BackgroundCallback callback = new BackgroundCallback() - { + BackgroundCallback callback = new BackgroundCallback() { @Override - public void processResult(CuratorFramework client, CuratorEvent event) throws Exception - { + public void processResult(CuratorFramework client, CuratorEvent event) throws Exception { queue.put(event.getPath()); } }; client.getChildren().inBackground(callback).forPath("/base"); path = queue.poll(10, TimeUnit.SECONDS); assertEquals(path, "/base"); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } @Test - public void testCreateACLSingleAuth() throws Exception - { + public void testCreateACLSingleAuth() throws Exception { CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder(); - CuratorFramework client = builder - .connectString(server.getConnectString()) - .authorization("digest", "me1:pass1".getBytes()) - .retryPolicy(new RetryOneTime(1)) - .build(); + CuratorFramework client = builder.connectString(server.getConnectString()) + .authorization("digest", "me1:pass1".getBytes()) + .retryPolicy(new RetryOneTime(1)) + .build(); client.start(); - try - { + try { ACL acl = new ACL(ZooDefs.Perms.WRITE, ZooDefs.Ids.AUTH_IDS); List aclList = Lists.newArrayList(acl); client.create().withACL(aclList).forPath("/test", "test".getBytes()); client.close(); // Try setting data with me1:pass1 - client = builder - .connectString(server.getConnectString()) - .authorization("digest", "me1:pass1".getBytes()) - .retryPolicy(new RetryOneTime(1)) - .build(); + client = builder.connectString(server.getConnectString()) + .authorization("digest", "me1:pass1".getBytes()) + .retryPolicy(new RetryOneTime(1)) + .build(); client.start(); - try - { + try { client.setData().forPath("/test", "test".getBytes()); - } - catch ( KeeperException.NoAuthException e ) - { + } catch (KeeperException.NoAuthException e) { fail("Auth failed"); } client.close(); // Try setting data with something:else - client = builder - .connectString(server.getConnectString()) - .authorization("digest", "something:else".getBytes()) - .retryPolicy(new RetryOneTime(1)) - .build(); + client = builder.connectString(server.getConnectString()) + .authorization("digest", "something:else".getBytes()) + .retryPolicy(new RetryOneTime(1)) + .build(); client.start(); - try - { + try { client.setData().forPath("/test", "test".getBytes()); fail("Should have failed with auth exception"); - } - catch ( KeeperException.NoAuthException e ) - { + } catch (KeeperException.NoAuthException e) { // expected } - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } @Test - public void testACLDeprecatedApis() throws Exception - { + public void testACLDeprecatedApis() throws Exception { CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder() - .connectString(server.getConnectString()) - .retryPolicy(new RetryOneTime(1)); + .connectString(server.getConnectString()) + .retryPolicy(new RetryOneTime(1)); assertNull(builder.getAuthScheme()); assertNull(builder.getAuthValue()); @@ -415,107 +360,84 @@ public void testACLDeprecatedApis() throws Exception } @Test - public void testCreateACLMultipleAuths() throws Exception - { + public void testCreateACLMultipleAuths() throws Exception { // Add a few authInfos List authInfos = new ArrayList(); authInfos.add(new AuthInfo("digest", "me1:pass1".getBytes())); authInfos.add(new AuthInfo("digest", "me2:pass2".getBytes())); CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder(); - CuratorFramework client = builder - .connectString(server.getConnectString()) - .authorization(authInfos) - .retryPolicy(new RetryOneTime(1)) - .build(); + CuratorFramework client = builder.connectString(server.getConnectString()) + .authorization(authInfos) + .retryPolicy(new RetryOneTime(1)) + .build(); client.start(); - try - { + try { ACL acl = new ACL(ZooDefs.Perms.WRITE, ZooDefs.Ids.AUTH_IDS); List aclList = Lists.newArrayList(acl); client.create().withACL(aclList).forPath("/test", "test".getBytes()); client.close(); // Try setting data with me1:pass1 - client = builder - .connectString(server.getConnectString()) - .authorization("digest", "me1:pass1".getBytes()) - .retryPolicy(new RetryOneTime(1)) - .build(); + client = builder.connectString(server.getConnectString()) + .authorization("digest", "me1:pass1".getBytes()) + .retryPolicy(new RetryOneTime(1)) + .build(); client.start(); - try - { + try { client.setData().forPath("/test", "test".getBytes()); - } - catch ( KeeperException.NoAuthException e ) - { + } catch (KeeperException.NoAuthException e) { fail("Auth failed"); } client.close(); // Try setting data with me1:pass1 - client = builder - .connectString(server.getConnectString()) - .authorization("digest", "me2:pass2".getBytes()) - .retryPolicy(new RetryOneTime(1)) - .build(); + client = builder.connectString(server.getConnectString()) + .authorization("digest", "me2:pass2".getBytes()) + .retryPolicy(new RetryOneTime(1)) + .build(); client.start(); - try - { + try { client.setData().forPath("/test", "test".getBytes()); - } - catch ( KeeperException.NoAuthException e ) - { + } catch (KeeperException.NoAuthException e) { fail("Auth failed"); } client.close(); // Try setting data with something:else - client = builder - .connectString(server.getConnectString()) - .authorization("digest", "something:else".getBytes()) - .retryPolicy(new RetryOneTime(1)) - .build(); + client = builder.connectString(server.getConnectString()) + .authorization("digest", "something:else".getBytes()) + .retryPolicy(new RetryOneTime(1)) + .build(); client.start(); - try - { + try { client.setData().forPath("/test", "test".getBytes()); fail("Should have failed with auth exception"); - } - catch ( KeeperException.NoAuthException e ) - { + } catch (KeeperException.NoAuthException e) { // expected } - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } @Test - public void testCreateACLWithReset() throws Exception - { + public void testCreateACLWithReset() throws Exception { Timing timing = new Timing(); CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder(); - CuratorFramework client = builder - .connectString(server.getConnectString()) - .sessionTimeoutMs(timing.session()) - .connectionTimeoutMs(timing.connection()) - .authorization("digest", "me:pass".getBytes()) - .retryPolicy(new RetryOneTime(1)) - .build(); + CuratorFramework client = builder.connectString(server.getConnectString()) + .sessionTimeoutMs(timing.session()) + .connectionTimeoutMs(timing.connection()) + .authorization("digest", "me:pass".getBytes()) + .retryPolicy(new RetryOneTime(1)) + .build(); client.start(); - try - { + try { final CountDownLatch lostLatch = new CountDownLatch(1); - ConnectionStateListener listener = new ConnectionStateListener() - { + ConnectionStateListener listener = new ConnectionStateListener() { @Override - public void stateChanged(CuratorFramework client, ConnectionState newState) - { - if ( newState == ConnectionState.LOST ) - { + public void stateChanged(CuratorFramework client, ConnectionState newState) { + if (newState == ConnectionState.LOST) { lostLatch.countDown(); } } @@ -528,40 +450,32 @@ public void stateChanged(CuratorFramework client, ConnectionState newState) server.stop(); assertTrue(timing.awaitLatch(lostLatch)); - try - { + try { client.checkExists().forPath("/"); fail("Connection should be down"); - } - catch ( KeeperException.ConnectionLossException e ) - { + } catch (KeeperException.ConnectionLossException e) { // expected } server.restart(); - try - { + try { client.setData().forPath("/test", "test".getBytes()); - } - catch ( KeeperException.NoAuthException e ) - { + } catch (KeeperException.NoAuthException e) { fail("Auth failed"); } - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } @Test - public void testCreateParents() throws Exception - { + public void testCreateParents() throws Exception { CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder(); - CuratorFramework client = builder.connectString(server.getConnectString()).retryPolicy(new RetryOneTime(1)).build(); + CuratorFramework client = builder.connectString(server.getConnectString()) + .retryPolicy(new RetryOneTime(1)) + .build(); client.start(); - try - { + try { client.create().creatingParentsIfNeeded().forPath("/one/two/three", "foo".getBytes()); byte[] data = client.getData().forPath("/one/two/three"); assertArrayEquals(data, "foo".getBytes()); @@ -569,28 +483,23 @@ public void testCreateParents() throws Exception client.create().creatingParentsIfNeeded().forPath("/one/two/another", "bar".getBytes()); data = client.getData().forPath("/one/two/another"); assertArrayEquals(data, "bar".getBytes()); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } @Test - public void testOverrideCreateParentContainers() throws Exception - { - if ( !checkForContainers() ) - { + public void testOverrideCreateParentContainers() throws Exception { + if (!checkForContainers()) { return; } CuratorFramework client = CuratorFrameworkFactory.builder() - .connectString(server.getConnectString()) - .retryPolicy(new RetryOneTime(1)) - .dontUseContainerParents() - .build(); - try - { + .connectString(server.getConnectString()) + .retryPolicy(new RetryOneTime(1)) + .dontUseContainerParents() + .build(); + try { client.start(); client.create().creatingParentContainersIfNeeded().forPath("/one/two/three", "foo".getBytes()); byte[] data = client.getData().forPath("/one/two/three"); @@ -602,25 +511,22 @@ public void testOverrideCreateParentContainers() throws Exception assertNotNull(client.checkExists().forPath("/one/two")); new Timing().sleepABit(); assertNotNull(client.checkExists().forPath("/one")); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } @Test - public void testCreateParentContainers() throws Exception - { - if ( !checkForContainers() ) - { + public void testCreateParentContainers() throws Exception { + if (!checkForContainers()) { return; } CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder(); - CuratorFramework client = builder.connectString(server.getConnectString()).retryPolicy(new RetryOneTime(1)).build(); - try - { + CuratorFramework client = builder.connectString(server.getConnectString()) + .retryPolicy(new RetryOneTime(1)) + .build(); + try { client.start(); client.create().creatingParentContainersIfNeeded().forPath("/one/two/three", "foo".getBytes()); byte[] data = client.getData().forPath("/one/two/three"); @@ -632,17 +538,13 @@ public void testCreateParentContainers() throws Exception assertNull(client.checkExists().forPath("/one/two")); new Timing().sleepABit(); assertNull(client.checkExists().forPath("/one")); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } - private boolean checkForContainers() - { - if ( ZKPaths.getContainerCreateMode() == CreateMode.PERSISTENT ) - { + private boolean checkForContainers() { + if (ZKPaths.getContainerCreateMode() == CreateMode.PERSISTENT) { System.out.println("Not using CreateMode.CONTAINER enabled version of ZooKeeper"); return false; } @@ -650,11 +552,9 @@ private boolean checkForContainers() } @Test - public void testCreatingParentsTheSame() throws Exception - { + public void testCreatingParentsTheSame() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); - try - { + try { client.start(); assertNull(client.checkExists().forPath("/one/two")); @@ -668,19 +568,15 @@ public void testCreatingParentsTheSame() throws Exception client.checkExists().creatingParentContainersIfNeeded().forPath("/one/two/three"); assertNotNull(client.checkExists().forPath("/one/two")); assertNull(client.checkExists().forPath("/one/two/three")); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } @Test - public void testExistsCreatingParents() throws Exception - { + public void testExistsCreatingParents() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); - try - { + try { client.start(); assertNull(client.checkExists().forPath("/one/two")); @@ -688,54 +584,50 @@ public void testExistsCreatingParents() throws Exception assertNotNull(client.checkExists().forPath("/one/two")); assertNull(client.checkExists().forPath("/one/two/three")); assertNull(client.checkExists().creatingParentContainersIfNeeded().forPath("/one/two/three")); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } @Test - public void testExistsCreatingParentsInBackground() throws Exception - { + public void testExistsCreatingParentsInBackground() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); - try - { + try { client.start(); assertNull(client.checkExists().forPath("/one/two")); final CountDownLatch latch = new CountDownLatch(1); - BackgroundCallback callback = new BackgroundCallback() - { + BackgroundCallback callback = new BackgroundCallback() { @Override - public void processResult(CuratorFramework client, CuratorEvent event) throws Exception - { + public void processResult(CuratorFramework client, CuratorEvent event) throws Exception { latch.countDown(); } }; - client.checkExists().creatingParentContainersIfNeeded().inBackground(callback).forPath("/one/two/three"); + client.checkExists() + .creatingParentContainersIfNeeded() + .inBackground(callback) + .forPath("/one/two/three"); assertTrue(new Timing().awaitLatch(latch)); assertNotNull(client.checkExists().forPath("/one/two")); assertNull(client.checkExists().forPath("/one/two/three")); assertNull(client.checkExists().creatingParentContainersIfNeeded().forPath("/one/two/three")); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } @Test - public void testEnsurePathWithNamespace() throws Exception - { + public void testEnsurePathWithNamespace() throws Exception { final String namespace = "jz"; CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder(); - CuratorFramework client = builder.connectString(server.getConnectString()).retryPolicy(new RetryOneTime(1)).namespace(namespace).build(); + CuratorFramework client = builder.connectString(server.getConnectString()) + .retryPolicy(new RetryOneTime(1)) + .namespace(namespace) + .build(); client.start(); - try - { + try { EnsurePath ensurePath = new EnsurePath("/pity/the/fool"); ensurePath.ensure(client.getZookeeperClient()); assertNull(client.getZookeeperClient().getZooKeeper().exists("/jz/pity/the/fool", false)); @@ -743,65 +635,60 @@ public void testEnsurePathWithNamespace() throws Exception ensurePath = client.newNamespaceAwareEnsurePath("/pity/the/fool"); ensurePath.ensure(client.getZookeeperClient()); assertNotNull(client.getZookeeperClient().getZooKeeper().exists("/jz/pity/the/fool", false)); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } @Test - public void testCreateContainersWithNamespace() throws Exception - { + public void testCreateContainersWithNamespace() throws Exception { final String namespace = "container1"; CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder(); - CuratorFramework client = builder.connectString(server.getConnectString()).retryPolicy(new RetryOneTime(1)).namespace(namespace).build(); - try - { + CuratorFramework client = builder.connectString(server.getConnectString()) + .retryPolicy(new RetryOneTime(1)) + .namespace(namespace) + .build(); + try { client.start(); String path = "/path1/path2"; client.createContainers(path); assertNotNull(client.checkExists().forPath(path)); assertNotNull(client.getZookeeperClient().getZooKeeper().exists("/" + namespace + path, false)); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } - @Test - public void testCreateContainersUsingNamespace() throws Exception - { + public void testCreateContainersUsingNamespace() throws Exception { final String namespace = "container2"; CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder(); - CuratorFramework client = builder.connectString(server.getConnectString()).retryPolicy(new RetryOneTime(1)).build(); - try - { + CuratorFramework client = builder.connectString(server.getConnectString()) + .retryPolicy(new RetryOneTime(1)) + .build(); + try { client.start(); CuratorFramework nsClient = client.usingNamespace(namespace); String path = "/path1/path2"; nsClient.createContainers(path); assertNotNull(nsClient.checkExists().forPath(path)); assertNotNull(nsClient.getZookeeperClient().getZooKeeper().exists("/" + namespace + path, false)); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } @Test - public void testNamespace() throws Exception - { + public void testNamespace() throws Exception { final String namespace = "TestNamespace"; CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder(); - CuratorFramework client = builder.connectString(server.getConnectString()).retryPolicy(new RetryOneTime(1)).namespace(namespace).build(); + CuratorFramework client = builder.connectString(server.getConnectString()) + .retryPolicy(new RetryOneTime(1)) + .namespace(namespace) + .build(); client.start(); - try - { + try { String actualPath = client.create().forPath("/test"); assertEquals(actualPath, "/test"); assertNotNull(client.getZookeeperClient().getZooKeeper().exists("/" + namespace + "/test", false)); @@ -817,30 +704,22 @@ public void testNamespace() throws Exception bytes = client.usingNamespace(null).getData().forPath("/" + namespace + "/test/child"); assertArrayEquals(bytes, "hey".getBytes()); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } @Test - public void testCustomCallback() throws Exception - { + public void testCustomCallback() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client.start(); - try - { + try { final CountDownLatch latch = new CountDownLatch(1); - BackgroundCallback callback = new BackgroundCallback() - { + BackgroundCallback callback = new BackgroundCallback() { @Override - public void processResult(CuratorFramework client, CuratorEvent event) throws Exception - { - if ( event.getType() == CuratorEventType.CREATE ) - { - if ( event.getPath().equals("/head") ) - { + public void processResult(CuratorFramework client, CuratorEvent event) throws Exception { + if (event.getType() == CuratorEventType.CREATE) { + if (event.getPath().equals("/head")) { latch.countDown(); } } @@ -848,35 +727,25 @@ public void processResult(CuratorFramework client, CuratorEvent event) throws Ex }; client.create().inBackground(callback).forPath("/head"); assertTrue(latch.await(10, TimeUnit.SECONDS)); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } @Test - public void testSync() throws Exception - { + public void testSync() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client.start(); - try - { - client.getCuratorListenable().addListener - ( - new CuratorListener() - { - @Override - public void eventReceived(CuratorFramework client, CuratorEvent event) throws Exception - { - if ( event.getType() == CuratorEventType.SYNC ) - { - assertEquals(event.getPath(), "/head"); - ((CountDownLatch)event.getContext()).countDown(); - } - } + try { + client.getCuratorListenable().addListener(new CuratorListener() { + @Override + public void eventReceived(CuratorFramework client, CuratorEvent event) throws Exception { + if (event.getType() == CuratorEventType.SYNC) { + assertEquals(event.getPath(), "/head"); + ((CountDownLatch) event.getContext()).countDown(); } - ); + } + }); client.create().forPath("/head"); assertNotNull(client.checkExists().forPath("/head")); @@ -884,102 +753,77 @@ public void eventReceived(CuratorFramework client, CuratorEvent event) throws Ex CountDownLatch latch = new CountDownLatch(1); client.sync("/head", latch); assertTrue(latch.await(10, TimeUnit.SECONDS)); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } @Test - public void testSyncNew() throws Exception - { + public void testSyncNew() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client.start(); - try - { + try { client.create().forPath("/head"); assertNotNull(client.checkExists().forPath("/head")); final CountDownLatch latch = new CountDownLatch(1); - BackgroundCallback callback = new BackgroundCallback() - { + BackgroundCallback callback = new BackgroundCallback() { @Override - public void processResult(CuratorFramework client, CuratorEvent event) throws Exception - { - if ( event.getType() == CuratorEventType.SYNC ) - { + public void processResult(CuratorFramework client, CuratorEvent event) throws Exception { + if (event.getType() == CuratorEventType.SYNC) { latch.countDown(); } } }; client.sync().inBackground(callback).forPath("/head"); assertTrue(latch.await(10, TimeUnit.SECONDS)); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } @Test - public void testGetSequentialChildren() throws Exception - { + public void testGetSequentialChildren() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client.start(); - try - { + try { client.create().forPath("/head"); - for ( int i = 0; i < 10; ++i ) - { + for (int i = 0; i < 10; ++i) { client.create().withMode(CreateMode.EPHEMERAL_SEQUENTIAL).forPath("/head/child"); } List children = client.getChildren().forPath("/head"); assertEquals(children.size(), 10); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } @Test - public void testBackgroundGetDataWithWatch() throws Exception - { + public void testBackgroundGetDataWithWatch() throws Exception { final byte[] data1 = {1, 2, 3}; final byte[] data2 = {4, 5, 6, 7}; CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client.start(); - try - { + try { final CountDownLatch watchedLatch = new CountDownLatch(1); - client.getCuratorListenable().addListener - ( - new CuratorListener() - { - @Override - public void eventReceived(CuratorFramework client, CuratorEvent event) throws Exception - { - if ( event.getType() == CuratorEventType.GET_DATA ) - { - assertEquals(event.getPath(), "/test"); - assertArrayEquals(event.getData(), data1); - ((CountDownLatch)event.getContext()).countDown(); - } - else if ( event.getType() == CuratorEventType.WATCHED ) - { - if ( event.getWatchedEvent().getType() == Watcher.Event.EventType.NodeDataChanged ) - { - assertEquals(event.getPath(), "/test"); - watchedLatch.countDown(); - } - } + client.getCuratorListenable().addListener(new CuratorListener() { + @Override + public void eventReceived(CuratorFramework client, CuratorEvent event) throws Exception { + if (event.getType() == CuratorEventType.GET_DATA) { + assertEquals(event.getPath(), "/test"); + assertArrayEquals(event.getData(), data1); + ((CountDownLatch) event.getContext()).countDown(); + } else if (event.getType() == CuratorEventType.WATCHED) { + if (event.getWatchedEvent().getType() == Watcher.Event.EventType.NodeDataChanged) { + assertEquals(event.getPath(), "/test"); + watchedLatch.countDown(); } } - ); + } + }); client.create().forPath("/test", data1); @@ -991,42 +835,30 @@ else if ( event.getType() == CuratorEventType.WATCHED ) assertTrue(watchedLatch.await(10, TimeUnit.SECONDS)); byte[] checkData = client.getData().forPath("/test"); assertArrayEquals(checkData, data2); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } @Test - public void testBackgroundCreate() throws Exception - { + public void testBackgroundCreate() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client.start(); - try - { - client.getCuratorListenable().addListener - ( - new CuratorListener() - { - @Override - public void eventReceived(CuratorFramework client, CuratorEvent event) throws Exception - { - if ( event.getType() == CuratorEventType.CREATE ) - { - assertEquals(event.getPath(), "/test"); - ((CountDownLatch)event.getContext()).countDown(); - } - } + try { + client.getCuratorListenable().addListener(new CuratorListener() { + @Override + public void eventReceived(CuratorFramework client, CuratorEvent event) throws Exception { + if (event.getType() == CuratorEventType.CREATE) { + assertEquals(event.getPath(), "/test"); + ((CountDownLatch) event.getContext()).countDown(); } - ); + } + }); CountDownLatch latch = new CountDownLatch(1); - client.create().inBackground(latch).forPath("/test", new byte[]{1, 2, 3}); + client.create().inBackground(latch).forPath("/test", new byte[] {1, 2, 3}); assertTrue(latch.await(10, TimeUnit.SECONDS)); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } @@ -1034,8 +866,7 @@ public void eventReceived(CuratorFramework client, CuratorEvent event) throws Ex @Test public void testBackgroundPathWithNamespace() throws Exception { CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder(); - try (CuratorFramework client = builder - .connectString(server.getConnectString()) + try (CuratorFramework client = builder.connectString(server.getConnectString()) .retryPolicy(new RetryOneTime(1)) .build()) { client.start(); @@ -1045,7 +876,11 @@ public void testBackgroundPathWithNamespace() throws Exception { events.add(event); }; - namespaceZoo.create().creatingParentsIfNeeded().inBackground(callback).forPath("/zoo/a"); + namespaceZoo + .create() + .creatingParentsIfNeeded() + .inBackground(callback) + .forPath("/zoo/a"); CuratorEvent event = events.poll(10, TimeUnit.SECONDS); assertNotNull(event); assertEquals("/zoo/a", event.getPath()); @@ -1059,12 +894,10 @@ public void testBackgroundPathWithNamespace() throws Exception { } @Test - public void testCreateModes() throws Exception - { + public void testCreateModes() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client.start(); - try - { + try { byte[] writtenBytes = {1, 2, 3}; client.create().forPath("/test", writtenBytes); // should be persistent @@ -1086,7 +919,8 @@ public void testCreateModes() throws Exception Stat stat = client.checkExists().forPath("/ghost"); assertNull(stat); - String realPath = client.create().withMode(CreateMode.PERSISTENT_SEQUENTIAL).forPath("/pseq", writtenBytes); + String realPath = + client.create().withMode(CreateMode.PERSISTENT_SEQUENTIAL).forPath("/pseq", writtenBytes); assertNotSame(realPath, "/pseq"); client.close(); @@ -1105,77 +939,71 @@ public void testCreateModes() throws Exception stat = client.checkExists().forPath(realPath); assertNull(stat); - } - finally - { - CloseableUtils.closeQuietly(client); + } finally { + CloseableUtils.closeQuietly(client); } } - + @Test - public void testConfigurableZookeeper() throws Exception - { - CuratorFramework client = null; - try - { - ZKClientConfig zkClientConfig = new ZKClientConfig(); - String zookeeperRequestTimeout = "30000"; - zkClientConfig.setProperty(ZKClientConfig.ZOOKEEPER_REQUEST_TIMEOUT, zookeeperRequestTimeout); - client = CuratorFrameworkFactory.newClient(server.getConnectString(), 30000, 30000, new RetryOneTime(1), zkClientConfig); + public void testConfigurableZookeeper() throws Exception { + CuratorFramework client = null; + try { + ZKClientConfig zkClientConfig = new ZKClientConfig(); + String zookeeperRequestTimeout = "30000"; + zkClientConfig.setProperty(ZKClientConfig.ZOOKEEPER_REQUEST_TIMEOUT, zookeeperRequestTimeout); + client = CuratorFrameworkFactory.newClient( + server.getConnectString(), 30000, 30000, new RetryOneTime(1), zkClientConfig); client.start(); - + byte[] writtenBytes = {1, 2, 3}; client.create().forPath("/test", writtenBytes); byte[] readBytes = client.getData().forPath("/test"); assertArrayEquals(writtenBytes, readBytes); - assertEquals(zookeeperRequestTimeout, client.getZookeeperClient().getZooKeeper().getClientConfig().getProperty(ZKClientConfig.ZOOKEEPER_REQUEST_TIMEOUT)); + assertEquals( + zookeeperRequestTimeout, + client.getZookeeperClient() + .getZooKeeper() + .getClientConfig() + .getProperty(ZKClientConfig.ZOOKEEPER_REQUEST_TIMEOUT)); } catch (NoSuchMethodError e) { log.debug("NoSuchMethodError: ", e); log.info("Got NoSuchMethodError, meaning probably this cannot be used with ZooKeeper version < 3.6.1"); - } - finally - { - try { - CloseableUtils.closeQuietly(client); - } catch (NoSuchMethodError e) { - log.debug("close: NoSuchMethodError: ", e); - log.info("close: Got NoSuchMethodError, meaning probably this cannot be used with ZooKeeper version < 3.6.1"); - } + } finally { + try { + CloseableUtils.closeQuietly(client); + } catch (NoSuchMethodError e) { + log.debug("close: NoSuchMethodError: ", e); + log.info( + "close: Got NoSuchMethodError, meaning probably this cannot be used with ZooKeeper version < 3.6.1"); + } } } @Test - public void testSimple() throws Exception - { + public void testSimple() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client.start(); - try - { - String path = client.create().withMode(CreateMode.PERSISTENT).forPath("/test", new byte[]{1, 2, 3}); + try { + String path = client.create().withMode(CreateMode.PERSISTENT).forPath("/test", new byte[] {1, 2, 3}); assertEquals(path, "/test"); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } @Test - public void testSequentialWithTrailingSeparator() throws Exception - { + public void testSequentialWithTrailingSeparator() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client.start(); - try - { + try { client.create().forPath("/test"); - //This should create a node in the form of "/test/00000001" - String path = client.create().withMode(CreateMode.PERSISTENT_SEQUENTIAL).forPath("/test/"); + // This should create a node in the form of "/test/00000001" + String path = + client.create().withMode(CreateMode.PERSISTENT_SEQUENTIAL).forPath("/test/"); assertTrue(path.startsWith("/test/")); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } diff --git a/curator-framework/src/test/java/org/apache/curator/framework/imps/TestFrameworkBackground.java b/curator-framework/src/test/java/org/apache/curator/framework/imps/TestFrameworkBackground.java index 00f2dff6c..0d0da50e3 100644 --- a/curator-framework/src/test/java/org/apache/curator/framework/imps/TestFrameworkBackground.java +++ b/curator-framework/src/test/java/org/apache/curator/framework/imps/TestFrameworkBackground.java @@ -24,6 +24,14 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import com.google.common.collect.Lists; import com.google.common.collect.Queues; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicLong; +import java.util.concurrent.atomic.AtomicReference; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.api.ACLProvider; @@ -42,111 +50,81 @@ import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicLong; -import java.util.concurrent.atomic.AtomicReference; -public class TestFrameworkBackground extends BaseClassForTests -{ +public class TestFrameworkBackground extends BaseClassForTests { private final Logger log = LoggerFactory.getLogger(getClass()); @Test - public void testErrorListener() throws Exception - { - //The first call to the ACL provider will return a reasonable - //value. The second will throw an error. This is because the ACL - //provider is accessed prior to the backgrounding call. + public void testErrorListener() throws Exception { + // The first call to the ACL provider will return a reasonable + // value. The second will throw an error. This is because the ACL + // provider is accessed prior to the backgrounding call. final AtomicBoolean aclProviderCalled = new AtomicBoolean(false); - - ACLProvider badAclProvider = new ACLProvider() - { + + ACLProvider badAclProvider = new ACLProvider() { @Override - public List getDefaultAcl() - { - if(aclProviderCalled.getAndSet(true)) - { + public List getDefaultAcl() { + if (aclProviderCalled.getAndSet(true)) { throw new UnsupportedOperationException(); - } - else - { + } else { return new ArrayList<>(); } } @Override - public List getAclForPath(String path) - { - if(aclProviderCalled.getAndSet(true)) - { + public List getAclForPath(String path) { + if (aclProviderCalled.getAndSet(true)) { throw new UnsupportedOperationException(); - } - else - { + } else { return new ArrayList<>(); } } }; CuratorFramework client = CuratorFrameworkFactory.builder() - .connectString(server.getConnectString()) - .retryPolicy(new RetryOneTime(1)) - .aclProvider(badAclProvider) - .build(); - try - { + .connectString(server.getConnectString()) + .retryPolicy(new RetryOneTime(1)) + .aclProvider(badAclProvider) + .build(); + try { client.start(); final CountDownLatch errorLatch = new CountDownLatch(1); - UnhandledErrorListener listener = new UnhandledErrorListener() - { + UnhandledErrorListener listener = new UnhandledErrorListener() { @Override - public void unhandledError(String message, Throwable e) - { - if ( e instanceof UnsupportedOperationException ) - { + public void unhandledError(String message, Throwable e) { + if (e instanceof UnsupportedOperationException) { errorLatch.countDown(); } } }; client.create().inBackground().withUnhandledErrorListener(listener).forPath("/foo"); assertTrue(new Timing().awaitLatch(errorLatch)); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } @Test - public void testListenerConnectedAtStart() throws Exception - { + public void testListenerConnectedAtStart() throws Exception { server.stop(); Timing timing = new Timing(2); - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryNTimes(0, 0)); - try - { + CuratorFramework client = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), timing.connection(), new RetryNTimes(0, 0)); + try { client.start(); final CountDownLatch connectedLatch = new CountDownLatch(1); final AtomicBoolean firstListenerAction = new AtomicBoolean(true); final AtomicReference firstListenerState = new AtomicReference(); - ConnectionStateListener listener = new ConnectionStateListener() - { + ConnectionStateListener listener = new ConnectionStateListener() { @Override - public void stateChanged(CuratorFramework client, ConnectionState newState) - { - if ( firstListenerAction.compareAndSet(true, false) ) - { + public void stateChanged(CuratorFramework client, ConnectionState newState) { + if (firstListenerAction.compareAndSet(true, false)) { firstListenerState.set(newState); System.out.println("First listener state is " + newState); } - if ( newState == ConnectionState.CONNECTED ) - { + if (newState == ConnectionState.CONNECTED) { connectedLatch.countDown(); } } @@ -161,37 +139,34 @@ public void stateChanged(CuratorFramework client, ConnectionState newState) assertTrue(timing.awaitLatch(connectedLatch)); assertFalse(firstListenerAction.get()); ConnectionState firstconnectionState = firstListenerState.get(); - assertEquals(firstconnectionState, ConnectionState.CONNECTED, "First listener state MUST BE CONNECTED but is " + firstconnectionState); - } - finally - { + assertEquals( + firstconnectionState, + ConnectionState.CONNECTED, + "First listener state MUST BE CONNECTED but is " + firstconnectionState); + } finally { CloseableUtils.closeQuietly(client); } } @Test - public void testRetries() throws Exception - { + public void testRetries() throws Exception { final int SLEEP = 1000; final int TIMES = 5; Timing timing = new Timing(); - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryNTimes(TIMES, SLEEP)); - try - { + CuratorFramework client = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), timing.connection(), new RetryNTimes(TIMES, SLEEP)); + try { client.start(); client.getZookeeperClient().blockUntilConnectedOrTimedOut(); final CountDownLatch latch = new CountDownLatch(TIMES); final List times = Lists.newArrayList(); final AtomicLong start = new AtomicLong(System.currentTimeMillis()); - ((CuratorFrameworkImpl)client).debugListener = new CuratorFrameworkImpl.DebugBackgroundListener() - { + ((CuratorFrameworkImpl) client).debugListener = new CuratorFrameworkImpl.DebugBackgroundListener() { @Override - public void listen(OperationAndData data) - { - if ( data.getOperation().getClass().getName().contains("CreateBuilderImpl") ) - { + public void listen(OperationAndData data) { + if (data.getOperation().getClass().getName().contains("CreateBuilderImpl")) { long now = System.currentTimeMillis(); times.add(now - start.get()); start.set(now); @@ -205,32 +180,27 @@ public void listen(OperationAndData data) latch.await(); - for ( long elapsed : times.subList(1, times.size()) ) // first one isn't a retry + for (long elapsed : times.subList(1, times.size())) // first one isn't a retry { assertTrue(elapsed >= SLEEP, elapsed + ": " + times); } - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } @Test - public void testBasic() throws Exception - { + public void testBasic() throws Exception { Timing timing = new Timing(); - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); - try - { + CuratorFramework client = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); + try { client.start(); final BlockingQueue paths = Queues.newLinkedBlockingQueue(); - BackgroundCallback callback = new BackgroundCallback() - { + BackgroundCallback callback = new BackgroundCallback() { @Override - public void processResult(CuratorFramework client, CuratorEvent event) throws Exception - { + public void processResult(CuratorFramework client, CuratorEvent event) throws Exception { paths.add(event.getPath()); } }; @@ -240,9 +210,7 @@ public void processResult(CuratorFramework client, CuratorEvent event) throws Ex assertEquals(paths.poll(timing.milliseconds(), TimeUnit.MILLISECONDS), "/one/two"); client.create().inBackground(callback).forPath("/one/two/three"); assertEquals(paths.poll(timing.milliseconds(), TimeUnit.MILLISECONDS), "/one/two/three"); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } @@ -252,22 +220,22 @@ public void processResult(CuratorFramework client, CuratorEvent event) throws Ex * Return code must be {@link Code#CONNECTIONLOSS} */ @Test - public void testCuratorCallbackOnError() throws Exception - { + public void testCuratorCallbackOnError() throws Exception { Timing timing = new Timing(); - CuratorFramework client = CuratorFrameworkFactory.builder().connectString(server.getConnectString()).sessionTimeoutMs(timing.session()).connectionTimeoutMs(timing.connection()).retryPolicy(new RetryOneTime(1000)).build(); + CuratorFramework client = CuratorFrameworkFactory.builder() + .connectString(server.getConnectString()) + .sessionTimeoutMs(timing.session()) + .connectionTimeoutMs(timing.connection()) + .retryPolicy(new RetryOneTime(1000)) + .build(); final CountDownLatch latch = new CountDownLatch(1); - try - { + try { client.start(); - BackgroundCallback curatorCallback = new BackgroundCallback() - { + BackgroundCallback curatorCallback = new BackgroundCallback() { @Override - public void processResult(CuratorFramework client, CuratorEvent event) throws Exception - { - if ( event.getResultCode() == Code.CONNECTIONLOSS.intValue() ) - { + public void processResult(CuratorFramework client, CuratorEvent event) throws Exception { + if (event.getResultCode() == Code.CONNECTIONLOSS.intValue()) { latch.countDown(); } } @@ -278,12 +246,9 @@ public void processResult(CuratorFramework client, CuratorEvent event) throws Ex client.getChildren().inBackground(curatorCallback).forPath("/"); // Check if the callback has been called with a correct return code assertTrue(timing.awaitLatch(latch), "Callback has not been called by curator !"); - } - finally - { + } finally { client.close(); } - } /** @@ -291,26 +256,21 @@ public void processResult(CuratorFramework client, CuratorEvent event) throws Ex * Shutdown the Curator client while there are still background operations running. */ @Test - public void testShutdown() throws Exception - { + public void testShutdown() throws Exception { Timing timing = new Timing(); - CuratorFramework client = CuratorFrameworkFactory - .builder() - .connectString(server.getConnectString()) - .sessionTimeoutMs(timing.session()) - .connectionTimeoutMs(timing.connection()).retryPolicy(new RetryOneTime(1)) - .maxCloseWaitMs(timing.forWaiting().milliseconds()) - .build(); - try - { + CuratorFramework client = CuratorFrameworkFactory.builder() + .connectString(server.getConnectString()) + .sessionTimeoutMs(timing.session()) + .connectionTimeoutMs(timing.connection()) + .retryPolicy(new RetryOneTime(1)) + .maxCloseWaitMs(timing.forWaiting().milliseconds()) + .build(); + try { final AtomicBoolean hadIllegalStateException = new AtomicBoolean(false); - ((CuratorFrameworkImpl)client).debugUnhandledErrorListener = new UnhandledErrorListener() - { + ((CuratorFrameworkImpl) client).debugUnhandledErrorListener = new UnhandledErrorListener() { @Override - public void unhandledError(String message, Throwable e) - { - if ( e instanceof IllegalStateException ) - { + public void unhandledError(String message, Throwable e) { + if (e instanceof IllegalStateException) { hadIllegalStateException.set(true); } } @@ -318,17 +278,12 @@ public void unhandledError(String message, Throwable e) client.start(); final CountDownLatch operationReadyLatch = new CountDownLatch(1); - ((CuratorFrameworkImpl)client).debugListener = new CuratorFrameworkImpl.DebugBackgroundListener() - { + ((CuratorFrameworkImpl) client).debugListener = new CuratorFrameworkImpl.DebugBackgroundListener() { @Override - public void listen(OperationAndData data) - { - try - { + public void listen(OperationAndData data) { + try { operationReadyLatch.await(); - } - catch ( InterruptedException e ) - { + } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } @@ -347,12 +302,8 @@ public void listen(OperationAndData data) // should not generate an exception assertFalse(hadIllegalStateException.get()); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } - - } diff --git a/curator-framework/src/test/java/org/apache/curator/framework/imps/TestFrameworkEdges.java b/curator-framework/src/test/java/org/apache/curator/framework/imps/TestFrameworkEdges.java index f0c91263e..581efdb9f 100644 --- a/curator-framework/src/test/java/org/apache/curator/framework/imps/TestFrameworkEdges.java +++ b/curator-framework/src/test/java/org/apache/curator/framework/imps/TestFrameworkEdges.java @@ -26,6 +26,18 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; import com.google.common.collect.Queues; +import java.util.Collections; +import java.util.List; +import java.util.Random; +import java.util.concurrent.ArrayBlockingQueue; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.Semaphore; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; import org.apache.curator.RetryPolicy; import org.apache.curator.RetrySleeper; import org.apache.curator.framework.CuratorFramework; @@ -59,41 +71,26 @@ import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.util.Collections; -import java.util.List; -import java.util.Random; -import java.util.concurrent.ArrayBlockingQueue; -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.LinkedBlockingQueue; -import java.util.concurrent.Semaphore; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicInteger; @Tag(CuratorTestBase.zk35TestCompatibilityGroup) -public class TestFrameworkEdges extends BaseClassForTests -{ +public class TestFrameworkEdges extends BaseClassForTests { private final Logger log = LoggerFactory.getLogger(getClass()); private final Timing2 timing = new Timing2(); @BeforeAll - public static void setUpClass() - { + public static void setUpClass() { System.setProperty("zookeeper.extendedTypesEnabled", "true"); } @Test @DisplayName("test case for CURATOR-525") - public void testValidateConnectionEventRaces() throws Exception - { + public void testValidateConnectionEventRaces() throws Exception { // test for CURATOR-525 - there is a race whereby Curator can go to LOST // after the connection has been repaired. Prior to the fix, the Curator // instance would become a zombie, never leaving the LOST state - try (CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), 2000, 1000, new RetryOneTime(1))) - { - CuratorFrameworkImpl clientImpl = (CuratorFrameworkImpl)client; + try (CuratorFramework client = + CuratorFrameworkFactory.newClient(server.getConnectString(), 2000, 1000, new RetryOneTime(1))) { + CuratorFrameworkImpl clientImpl = (CuratorFrameworkImpl) client; client.start(); client.getChildren().forPath("/"); @@ -113,7 +110,9 @@ public void testValidateConnectionEventRaces() throws Exception timing.awaitLatch(clientImpl.debugCheckBackgroundRetryReadyLatch); server.restart(); assertEquals(timing.takeFromQueue(stateQueue), ConnectionState.RECONNECTED); - clientImpl.injectedCode = KeeperException.Code.SESSIONEXPIRED; // simulate an expiration being handled after the connection is repaired + clientImpl.injectedCode = + KeeperException.Code + .SESSIONEXPIRED; // simulate an expiration being handled after the connection is repaired clientImpl.debugCheckBackgroundRetryLatch.countDown(); assertEquals(timing.takeFromQueue(stateQueue), ConnectionState.LOST); @@ -122,16 +121,14 @@ public void testValidateConnectionEventRaces() throws Exception } @Test - public void testInjectSessionExpiration() throws Exception - { - try (CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1))) - { + public void testInjectSessionExpiration() throws Exception { + try (CuratorFramework client = + CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1))) { client.start(); CountDownLatch expiredLatch = new CountDownLatch(1); Watcher watcher = event -> { - if ( event.getState() == Watcher.Event.KeeperState.Expired ) - { + if (event.getState() == Watcher.Event.KeeperState.Expired) { expiredLatch.countDown(); } }; @@ -142,9 +139,8 @@ public void testInjectSessionExpiration() throws Exception } @Test - public void testProtectionWithKilledSession() throws Exception - { - server.stop(); // not needed + public void testProtectionWithKilledSession() throws Exception { + server.stop(); // not needed // see CURATOR-498 // attempt to re-create the state described in the bug report: create a 3 Instance ensemble; @@ -156,24 +152,17 @@ public void testProtectionWithKilledSession() throws Exception // by the Instance Curator is connected to but the session kill needs a quorum vote (it's a // transaction) - try (TestingCluster cluster = createAndStartCluster(3)) - { + try (TestingCluster cluster = createAndStartCluster(3)) { InstanceSpec instanceSpec0 = cluster.getServers().get(0).getInstanceSpec(); CountDownLatch serverStoppedLatch = new CountDownLatch(1); - RetryPolicy retryPolicy = new RetryForever(100) - { + RetryPolicy retryPolicy = new RetryForever(100) { @Override - public boolean allowRetry(int retryCount, long elapsedTimeMs, RetrySleeper sleeper) - { - if ( serverStoppedLatch.getCount() > 0 ) - { - try - { + public boolean allowRetry(int retryCount, long elapsedTimeMs, RetrySleeper sleeper) { + if (serverStoppedLatch.getCount() > 0) { + try { cluster.killServer(instanceSpec0); - } - catch ( Exception e ) - { + } catch (Exception e) { // ignore } serverStoppedLatch.countDown(); @@ -182,12 +171,11 @@ public boolean allowRetry(int retryCount, long elapsedTimeMs, RetrySleeper sleep } }; - try (CuratorFramework client = CuratorFrameworkFactory.newClient(instanceSpec0.getConnectString(), timing.session(), timing.connection(), retryPolicy)) - { + try (CuratorFramework client = CuratorFrameworkFactory.newClient( + instanceSpec0.getConnectString(), timing.session(), timing.connection(), retryPolicy)) { BlockingQueue createdNode = new LinkedBlockingQueue<>(); BackgroundCallback callback = (__, event) -> { - if ( event.getType() == CuratorEventType.CREATE ) - { + if (event.getType() == CuratorEventType.CREATE) { createdNode.offer(event.getPath()); } }; @@ -195,13 +183,16 @@ public boolean allowRetry(int retryCount, long elapsedTimeMs, RetrySleeper sleep client.start(); client.create().forPath("/test"); - ErrorListenerPathAndBytesable builder = client.create().withProtection().withMode(CreateMode.EPHEMERAL).inBackground(callback); - ((CreateBuilderImpl)builder).failNextCreateForTesting = true; + ErrorListenerPathAndBytesable builder = client.create() + .withProtection() + .withMode(CreateMode.EPHEMERAL) + .inBackground(callback); + ((CreateBuilderImpl) builder).failNextCreateForTesting = true; builder.forPath("/test/hey"); assertTrue(timing.awaitLatch(serverStoppedLatch)); - timing.forSessionSleep().sleep(); // wait for session to expire + timing.forSessionSleep().sleep(); // wait for session to expire cluster.restartServer(instanceSpec0); String path = timing.takeFromQueue(createdNode); @@ -212,24 +203,20 @@ public boolean allowRetry(int retryCount, long elapsedTimeMs, RetrySleeper sleep } @Test - public void testBackgroundLatencyUnSleep() throws Exception - { + public void testBackgroundLatencyUnSleep() throws Exception { server.stop(); CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); - try - { + try { client.start(); - ((CuratorFrameworkImpl)client).sleepAndQueueOperationSeconds = Integer.MAX_VALUE; + ((CuratorFrameworkImpl) client).sleepAndQueueOperationSeconds = Integer.MAX_VALUE; final CountDownLatch latch = new CountDownLatch(3); - BackgroundCallback callback = new BackgroundCallback() - { + BackgroundCallback callback = new BackgroundCallback() { @Override - public void processResult(CuratorFramework client, CuratorEvent event) throws Exception - { - if ( (event.getType() == CuratorEventType.CREATE) && (event.getResultCode() == KeeperException.Code.OK.intValue()) ) - { + public void processResult(CuratorFramework client, CuratorEvent event) throws Exception { + if ((event.getType() == CuratorEventType.CREATE) + && (event.getResultCode() == KeeperException.Code.OK.intValue())) { latch.countDown(); } } @@ -241,34 +228,29 @@ public void processResult(CuratorFramework client, CuratorEvent event) throws Ex server.restart(); assertTrue(timing.awaitLatch(latch)); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } @Test - public void testCreateContainersForBadConnect() throws Exception - { + public void testCreateContainersForBadConnect() throws Exception { final int serverPort = server.getPort(); server.close(); - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), 1000, 1000, new RetryNTimes(10, timing.forSleepingABit().milliseconds())); - try - { - new Thread() - { + CuratorFramework client = CuratorFrameworkFactory.newClient( + server.getConnectString(), + 1000, + 1000, + new RetryNTimes(10, timing.forSleepingABit().milliseconds())); + try { + new Thread() { @Override - public void run() - { - try - { + public void run() { + try { Thread.sleep(3000); server = new TestingServer(serverPort, true); - } - catch ( Exception e ) - { + } catch (Exception e) { e.printStackTrace(); } } @@ -277,52 +259,42 @@ public void run() client.start(); client.createContainers("/this/does/not/exist"); assertNotNull(client.checkExists().forPath("/this/does/not/exist")); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } @Test - public void testQuickClose() throws Exception - { - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), 1, new RetryNTimes(0, 0)); - try - { + public void testQuickClose() throws Exception { + CuratorFramework client = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), 1, new RetryNTimes(0, 0)); + try { client.start(); client.close(); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } @Test - public void testProtectedCreateNodeDeletion() throws Exception - { - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), 1, new RetryNTimes(0, 0)); - try - { + public void testProtectedCreateNodeDeletion() throws Exception { + CuratorFramework client = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), 1, new RetryNTimes(0, 0)); + try { client.start(); - for ( int i = 0; i < 2; ++i ) - { + for (int i = 0; i < 2; ++i) { CuratorFramework localClient = (i == 0) ? client : client.usingNamespace("nm"); localClient.create().forPath("/parent"); assertEquals(localClient.getChildren().forPath("/parent").size(), 0); - CreateBuilderImpl createBuilder = (CreateBuilderImpl)localClient.create(); + CreateBuilderImpl createBuilder = (CreateBuilderImpl) localClient.create(); createBuilder.failNextCreateForTesting = true; FindAndDeleteProtectedNodeInBackground.debugInsertError.set(true); - try - { + try { createBuilder.withProtection().forPath("/parent/test"); fail("failNextCreateForTesting should have caused a ConnectionLossException"); - } - catch ( KeeperException.ConnectionLossException e ) - { + } catch (KeeperException.ConnectionLossException e) { // ignore, correct } @@ -332,37 +304,30 @@ public void testProtectedCreateNodeDeletion() throws Exception localClient.delete().forPath("/parent"); } - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } @Test - public void testPathsFromProtectingInBackground() throws Exception - { - for ( CreateMode mode : CreateMode.values() ) - { + public void testPathsFromProtectingInBackground() throws Exception { + for (CreateMode mode : CreateMode.values()) { internalTestPathsFromProtectingInBackground(mode); } } - private void internalTestPathsFromProtectingInBackground(CreateMode mode) throws Exception - { - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), 1, new RetryOneTime(1)); - try - { + private void internalTestPathsFromProtectingInBackground(CreateMode mode) throws Exception { + CuratorFramework client = + CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), 1, new RetryOneTime(1)); + try { client.start(); client.create().creatingParentsIfNeeded().forPath("/a/b/c"); final BlockingQueue paths = new ArrayBlockingQueue(2); - BackgroundCallback callback = new BackgroundCallback() - { + BackgroundCallback callback = new BackgroundCallback() { @Override - public void processResult(CuratorFramework client, CuratorEvent event) throws Exception - { + public void processResult(CuratorFramework client, CuratorEvent event) throws Exception { paths.put(event.getName()); paths.put(event.getPath()); } @@ -370,8 +335,7 @@ public void processResult(CuratorFramework client, CuratorEvent event) throws Ex final String TEST_PATH = "/a/b/c/test-"; long ttl = timing.forWaiting().milliseconds() * 1000; CreateBuilder firstCreateBuilder = client.create(); - if ( mode.isTTL() ) - { + if (mode.isTTL()) { firstCreateBuilder.withTtl(ttl); } firstCreateBuilder.withMode(mode).inBackground(callback).forPath(TEST_PATH); @@ -381,13 +345,13 @@ public void processResult(CuratorFramework client, CuratorEvent event) throws Ex client.close(); - client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), 1, new RetryOneTime(1)); + client = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), 1, new RetryOneTime(1)); client.start(); - CreateBuilderImpl createBuilder = (CreateBuilderImpl)client.create(); + CreateBuilderImpl createBuilder = (CreateBuilderImpl) client.create(); createBuilder.withProtection(); - if ( mode.isTTL() ) - { + if (mode.isTTL()) { createBuilder.withTtl(ttl); } @@ -399,62 +363,61 @@ public void processResult(CuratorFramework client, CuratorEvent event) throws Ex String name2 = timing.takeFromQueue(paths); String path2 = timing.takeFromQueue(paths); - assertEquals(ZKPaths.getPathAndNode(name1).getPath(), ZKPaths.getPathAndNode(TEST_PATH).getPath()); - assertEquals(ZKPaths.getPathAndNode(name2).getPath(), ZKPaths.getPathAndNode(TEST_PATH).getPath()); - assertEquals(ZKPaths.getPathAndNode(path1).getPath(), ZKPaths.getPathAndNode(TEST_PATH).getPath()); - assertEquals(ZKPaths.getPathAndNode(path2).getPath(), ZKPaths.getPathAndNode(TEST_PATH).getPath()); + assertEquals( + ZKPaths.getPathAndNode(name1).getPath(), + ZKPaths.getPathAndNode(TEST_PATH).getPath()); + assertEquals( + ZKPaths.getPathAndNode(name2).getPath(), + ZKPaths.getPathAndNode(TEST_PATH).getPath()); + assertEquals( + ZKPaths.getPathAndNode(path1).getPath(), + ZKPaths.getPathAndNode(TEST_PATH).getPath()); + assertEquals( + ZKPaths.getPathAndNode(path2).getPath(), + ZKPaths.getPathAndNode(TEST_PATH).getPath()); client.delete().deletingChildrenIfNeeded().forPath("/a/b/c"); client.delete().forPath("/a/b"); client.delete().forPath("/a"); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } @Test - public void connectionLossWithBackgroundTest() throws Exception - { - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), 1, new RetryOneTime(1)); - try - { + public void connectionLossWithBackgroundTest() throws Exception { + CuratorFramework client = + CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), 1, new RetryOneTime(1)); + try { final CountDownLatch latch = new CountDownLatch(1); client.start(); client.getZookeeperClient().blockUntilConnectedOrTimedOut(); server.close(); - client.getChildren().inBackground(new BackgroundCallback() - { - public void processResult(CuratorFramework client, CuratorEvent event) throws Exception - { - latch.countDown(); - } - }).forPath("/"); + client.getChildren() + .inBackground(new BackgroundCallback() { + public void processResult(CuratorFramework client, CuratorEvent event) throws Exception { + latch.countDown(); + } + }) + .forPath("/"); assertTrue(timing.awaitLatch(latch)); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } @Test - public void testReconnectAfterLoss() throws Exception - { - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); - try - { + public void testReconnectAfterLoss() throws Exception { + CuratorFramework client = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); + try { client.start(); final CountDownLatch lostLatch = new CountDownLatch(1); - ConnectionStateListener listener = new ConnectionStateListener() - { + ConnectionStateListener listener = new ConnectionStateListener() { @Override - public void stateChanged(CuratorFramework client, ConnectionState newState) - { - if ( newState == ConnectionState.LOST ) - { + public void stateChanged(CuratorFramework client, ConnectionState newState) { + if (newState == ConnectionState.LOST) { lostLatch.countDown(); } } @@ -467,109 +430,95 @@ public void stateChanged(CuratorFramework client, ConnectionState newState) assertTrue(timing.awaitLatch(lostLatch)); - try - { + try { client.checkExists().forPath("/"); fail(); - } - catch ( KeeperException.ConnectionLossException e ) - { + } catch (KeeperException.ConnectionLossException e) { // correct } server.restart(); client.checkExists().forPath("/"); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } @Test - public void testGetAclNoStat() throws Exception - { - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); + public void testGetAclNoStat() throws Exception { + CuratorFramework client = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); client.start(); - try - { - try - { + try { + try { client.getACL().forPath("/"); - } - catch ( NullPointerException e ) - { + } catch (NullPointerException e) { fail(); } - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } @Test - public void testMissedResponseOnBackgroundESCreate() throws Exception - { - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); + public void testMissedResponseOnBackgroundESCreate() throws Exception { + CuratorFramework client = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); client.start(); - try - { - CreateBuilderImpl createBuilder = (CreateBuilderImpl)client.create(); + try { + CreateBuilderImpl createBuilder = (CreateBuilderImpl) client.create(); createBuilder.failNextCreateForTesting = true; final BlockingQueue queue = Queues.newArrayBlockingQueue(1); - BackgroundCallback callback = new BackgroundCallback() - { + BackgroundCallback callback = new BackgroundCallback() { @Override - public void processResult(CuratorFramework client, CuratorEvent event) throws Exception - { + public void processResult(CuratorFramework client, CuratorEvent event) throws Exception { queue.put(event.getPath()); } }; - createBuilder.withProtection().withMode(CreateMode.EPHEMERAL_SEQUENTIAL).inBackground(callback).forPath("/"); + createBuilder + .withProtection() + .withMode(CreateMode.EPHEMERAL_SEQUENTIAL) + .inBackground(callback) + .forPath("/"); String ourPath = queue.poll(timing.forWaiting().seconds(), TimeUnit.SECONDS); assertTrue(ourPath.startsWith(ZKPaths.makePath("/", ProtectedUtils.PROTECTED_PREFIX))); assertFalse(createBuilder.failNextCreateForTesting); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } @Test - public void testMissedResponseOnESCreate() throws Exception - { - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); + public void testMissedResponseOnESCreate() throws Exception { + CuratorFramework client = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); client.start(); - try - { - CreateBuilderImpl createBuilder = (CreateBuilderImpl)client.create(); + try { + CreateBuilderImpl createBuilder = (CreateBuilderImpl) client.create(); createBuilder.failNextCreateForTesting = true; - String ourPath = createBuilder.withProtection().withMode(CreateMode.EPHEMERAL_SEQUENTIAL).forPath("/"); + String ourPath = createBuilder + .withProtection() + .withMode(CreateMode.EPHEMERAL_SEQUENTIAL) + .forPath("/"); assertTrue(ourPath.startsWith(ZKPaths.makePath("/", ProtectedUtils.PROTECTED_PREFIX))); assertFalse(createBuilder.failNextCreateForTesting); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } @Test - public void testSessionKilled() throws Exception - { - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); + public void testSessionKilled() throws Exception { + CuratorFramework client = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); client.start(); - try - { + try { client.create().forPath("/sessionTest"); CountDownLatch sessionDiedLatch = new CountDownLatch(1); Watcher watcher = event -> { - if ( event.getState() == Watcher.Event.KeeperState.Expired ) - { + if (event.getState() == Watcher.Event.KeeperState.Expired) { sessionDiedLatch.countDown(); } }; @@ -578,35 +527,27 @@ public void testSessionKilled() throws Exception client.getZookeeperClient().getZooKeeper().getTestable().injectSessionExpiration(); assertTrue(timing.awaitLatch(sessionDiedLatch)); assertNotNull(client.checkExists().forPath("/sessionTest")); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } @Test - public void testNestedCalls() throws Exception - { - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); + public void testNestedCalls() throws Exception { + CuratorFramework client = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); client.start(); - try - { - client.getCuratorListenable().addListener(new CuratorListener() - { + try { + client.getCuratorListenable().addListener(new CuratorListener() { @Override - public void eventReceived(CuratorFramework client, CuratorEvent event) throws Exception - { - if ( event.getType() == CuratorEventType.EXISTS ) - { + public void eventReceived(CuratorFramework client, CuratorEvent event) throws Exception { + if (event.getType() == CuratorEventType.EXISTS) { Stat stat = client.checkExists().forPath("/yo/yo/yo"); assertNull(stat); client.create().inBackground(event.getContext()).forPath("/what"); - } - else if ( event.getType() == CuratorEventType.CREATE ) - { - ((CountDownLatch)event.getContext()).countDown(); + } else if (event.getType() == CuratorEventType.CREATE) { + ((CountDownLatch) event.getContext()).countDown(); } } }); @@ -614,28 +555,22 @@ else if ( event.getType() == CuratorEventType.CREATE ) CountDownLatch latch = new CountDownLatch(1); client.checkExists().inBackground(latch).forPath("/hey"); assertTrue(latch.await(10, TimeUnit.SECONDS)); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } @Test - public void testBackgroundFailure() throws Exception - { - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); + public void testBackgroundFailure() throws Exception { + CuratorFramework client = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); client.start(); - try - { + try { final CountDownLatch latch = new CountDownLatch(1); - client.getConnectionStateListenable().addListener(new ConnectionStateListener() - { + client.getConnectionStateListenable().addListener(new ConnectionStateListener() { @Override - public void stateChanged(CuratorFramework client, ConnectionState newState) - { - if ( newState == ConnectionState.LOST ) - { + public void stateChanged(CuratorFramework client, ConnectionState newState) { + if (newState == ConnectionState.LOST) { latch.countDown(); } } @@ -648,20 +583,17 @@ public void stateChanged(CuratorFramework client, ConnectionState newState) client.checkExists().inBackground().forPath("/hey"); assertTrue(timing.awaitLatch(latch)); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } @Test - public void testFailure() throws Exception - { - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), 100, 100, new RetryOneTime(1)); + public void testFailure() throws Exception { + CuratorFramework client = + CuratorFrameworkFactory.newClient(server.getConnectString(), 100, 100, new RetryOneTime(1)); client.start(); - try - { + try { client.checkExists().forPath("/hey"); client.checkExists().inBackground().forPath("/hey"); @@ -669,55 +601,39 @@ public void testFailure() throws Exception client.checkExists().forPath("/hey"); fail(); - } - catch ( KeeperException.SessionExpiredException e ) - { + } catch (KeeperException.SessionExpiredException e) { // correct, this happens on ZK 3.6.3+ - } - catch ( KeeperException.ConnectionLossException e ) - { + } catch (KeeperException.ConnectionLossException e) { // correct, this happens on ZK 3.5.x, 3.6.0 -> 3.6.2 - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } @Test - public void testRetry() throws Exception - { + public void testRetry() throws Exception { final int MAX_RETRIES = 3; - final CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(10)); + final CuratorFramework client = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(10)); client.start(); - try - { + try { final AtomicInteger retries = new AtomicInteger(0); final Semaphore semaphore = new Semaphore(0); - RetryPolicy policy = new RetryPolicy() - { + RetryPolicy policy = new RetryPolicy() { @Override - public boolean allowRetry(int retryCount, long elapsedTimeMs, RetrySleeper sleeper) - { + public boolean allowRetry(int retryCount, long elapsedTimeMs, RetrySleeper sleeper) { semaphore.release(); - if ( retries.incrementAndGet() == MAX_RETRIES ) - { - try - { + if (retries.incrementAndGet() == MAX_RETRIES) { + try { server.restart(); - } - catch ( Exception e ) - { + } catch (Exception e) { throw new Error(e); } } - try - { + try { sleeper.sleepFor(100, TimeUnit.MILLISECONDS); - } - catch ( InterruptedException e ) - { + } catch (InterruptedException e) { Thread.currentThread().interrupt(); } return true; @@ -729,7 +645,9 @@ public boolean allowRetry(int retryCount, long elapsedTimeMs, RetrySleeper sleep // test foreground retry client.checkExists().forPath("/hey"); - assertTrue(semaphore.tryAcquire(MAX_RETRIES, timing.forWaiting().seconds(), TimeUnit.SECONDS), "Remaining leases: " + semaphore.availablePermits()); + assertTrue( + semaphore.tryAcquire(MAX_RETRIES, timing.forWaiting().seconds(), TimeUnit.SECONDS), + "Remaining leases: " + semaphore.availablePermits()); // make sure we're reconnected client.getZookeeperClient().setRetryPolicy(new RetryOneTime(100)); @@ -743,155 +661,112 @@ public boolean allowRetry(int retryCount, long elapsedTimeMs, RetrySleeper sleep // test background retry client.checkExists().inBackground().forPath("/hey"); - assertTrue(semaphore.tryAcquire(MAX_RETRIES, timing.forWaiting().seconds(), TimeUnit.SECONDS), "Remaining leases: " + semaphore.availablePermits()); - } - finally - { + assertTrue( + semaphore.tryAcquire(MAX_RETRIES, timing.forWaiting().seconds(), TimeUnit.SECONDS), + "Remaining leases: " + semaphore.availablePermits()); + } finally { CloseableUtils.closeQuietly(client); } } @Test - public void testNotStarted() throws Exception - { + public void testNotStarted() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); - try - { + try { client.getData(); fail(); - } - catch ( Exception e ) - { + } catch (Exception e) { // correct - } - catch ( Throwable e ) - { + } catch (Throwable e) { fail("", e); } } @Test - public void testStopped() throws Exception - { + public void testStopped() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); - try - { + try { client.start(); client.getData(); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } - try - { + try { client.getData(); fail(); - } - catch ( Exception e ) - { + } catch (Exception e) { // correct } } @Test - public void testDeleteChildrenConcurrently() throws Exception - { - final CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); + public void testDeleteChildrenConcurrently() throws Exception { + final CuratorFramework client = + CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); CuratorFramework client2 = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); ExecutorService executorService = Executors.newSingleThreadExecutor(); - try - { + try { client.start(); client2.start(); int childCount = 500; - for ( int i = 0; i < childCount; i++ ) - { + for (int i = 0; i < childCount; i++) { client.create().creatingParentsIfNeeded().forPath("/parent/child" + i); } final CountDownLatch latch = new CountDownLatch(1); executorService.submit(() -> { - try - { + try { client.delete().deletingChildrenIfNeeded().forPath("/parent"); - } - catch ( InterruptedException e ) - { + } catch (InterruptedException e) { Thread.currentThread().interrupt(); - } - catch ( Exception e ) - { - if ( e instanceof KeeperException.NoNodeException ) - { + } catch (Exception e) { + if (e instanceof KeeperException.NoNodeException) { fail("client delete failed, shouldn't throw NoNodeException", e); - } - else - { + } else { fail("unexpected exception", e); } - } - finally - { + } finally { latch.countDown(); } }); boolean threadDeleted = false; Random random = new Random(); - for ( int i = 0; i < childCount; i++ ) - { + for (int i = 0; i < childCount; i++) { String child = "/parent/child" + random.nextInt(childCount); - try - { - if ( !threadDeleted ) - { + try { + if (!threadDeleted) { Stat stat = client2.checkExists().forPath(child); - if ( stat == null ) - { + if (stat == null) { // the thread client has begin deleted the children threadDeleted = true; log.info("client has deleted the child {}", child); } - } - else - { - try - { + } else { + try { client2.delete().forPath(child); log.info("client2 deleted the child {} successfully", child); break; - } - catch ( KeeperException.NoNodeException ignore ) - { + } catch (KeeperException.NoNodeException ignore) { // ignore, because it's deleted by the thread client - } - catch ( Exception e ) - { + } catch (Exception e) { fail("unexpected exception", e); } } - } - catch ( Exception e ) - { + } catch (Exception e) { fail("unexpected exception", e); } } assertTrue(timing.awaitLatch(latch)); assertNull(client2.checkExists().forPath("/parent")); - } - finally - { - try - { + } finally { + try { executorService.shutdownNow(); executorService.awaitTermination(timing.milliseconds(), TimeUnit.MILLISECONDS); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); CloseableUtils.closeQuietly(client2); } diff --git a/curator-framework/src/test/java/org/apache/curator/framework/imps/TestGzipCompressionProvider.java b/curator-framework/src/test/java/org/apache/curator/framework/imps/TestGzipCompressionProvider.java index 962bb5b89..ccec951c2 100644 --- a/curator-framework/src/test/java/org/apache/curator/framework/imps/TestGzipCompressionProvider.java +++ b/curator-framework/src/test/java/org/apache/curator/framework/imps/TestGzipCompressionProvider.java @@ -29,11 +29,9 @@ import java.util.zip.GZIPOutputStream; import org.junit.jupiter.api.Test; -public class TestGzipCompressionProvider -{ +public class TestGzipCompressionProvider { @Test - public void testSimple() throws IOException - { + public void testSimple() throws IOException { GzipCompressionProvider provider = new GzipCompressionProvider(); byte[] data = "Hello, world!".getBytes(); byte[] compressedData = provider.compress(null, data); @@ -44,8 +42,7 @@ public void testSimple() throws IOException } @Test - public void testEmpty() throws IOException - { + public void testEmpty() throws IOException { GzipCompressionProvider provider = new GzipCompressionProvider(); byte[] compressedData = provider.compress(null, new byte[0]); byte[] compressedData2 = GzipCompressionProvider.doCompress(new byte[0]); @@ -62,8 +59,7 @@ public void testEmpty() throws IOException * of runtime exception. Users of {@link GzipCompressionProvider#decompress(String, byte[])} may depend on this. */ @Test - public void testDecompressCorrupt() - { + public void testDecompressCorrupt() { GzipCompressionProvider provider = new GzipCompressionProvider(); try { provider.decompress(null, new byte[100]); @@ -72,15 +68,13 @@ public void testDecompressCorrupt() // expected } byte[] compressedData = provider.compress(null, new byte[0]); - for (int i = 0; i < compressedData.length; i++) - { + for (int i = 0; i < compressedData.length; i++) { try { provider.decompress(null, Arrays.copyOf(compressedData, i)); } catch (IOException ignore) { // expected } - for (int change = 1; change < 256; change++) - { + for (int change = 1; change < 256; change++) { byte b = compressedData[i]; compressedData[i] = (byte) (b + change); try { @@ -96,12 +90,10 @@ public void testDecompressCorrupt() } @Test - public void smokeTestRandomDataWithJdk() throws IOException - { + public void smokeTestRandomDataWithJdk() throws IOException { GzipCompressionProvider provider = new GzipCompressionProvider(); ThreadLocalRandom random = ThreadLocalRandom.current(); - for (int len = 1; len < 100; len++) - { + for (int len = 1; len < 100; len++) { byte[] data = new byte[len]; for (int i = 0; i < 100; i++) { byte[] compressedData = provider.compress(null, data); @@ -115,8 +107,7 @@ public void smokeTestRandomDataWithJdk() throws IOException } } - private static byte[] jdkCompress(byte[] data) throws IOException - { + private static byte[] jdkCompress(byte[] data) throws IOException { ByteArrayOutputStream bytes = new ByteArrayOutputStream(); try (GZIPOutputStream out = new GZIPOutputStream(bytes)) { diff --git a/curator-framework/src/test/java/org/apache/curator/framework/imps/TestMultiClient.java b/curator-framework/src/test/java/org/apache/curator/framework/imps/TestMultiClient.java index a2cdaa9b4..4e49b3179 100644 --- a/curator-framework/src/test/java/org/apache/curator/framework/imps/TestMultiClient.java +++ b/curator-framework/src/test/java/org/apache/curator/framework/imps/TestMultiClient.java @@ -20,82 +20,61 @@ package org.apache.curator.framework.imps; import static org.junit.jupiter.api.Assertions.assertTrue; - -import org.apache.curator.test.BaseClassForTests; -import org.apache.curator.utils.CloseableUtils; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.api.CuratorEvent; import org.apache.curator.framework.api.CuratorEventType; import org.apache.curator.framework.api.CuratorListener; import org.apache.curator.retry.RetryOneTime; +import org.apache.curator.test.BaseClassForTests; +import org.apache.curator.utils.CloseableUtils; import org.apache.zookeeper.Watcher; import org.junit.jupiter.api.Test; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; - -public class TestMultiClient extends BaseClassForTests -{ +public class TestMultiClient extends BaseClassForTests { @Test - public void testNotify() throws Exception - { + public void testNotify() throws Exception { CuratorFramework client1 = null; CuratorFramework client2 = null; - try - { + try { client1 = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client2 = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client1.start(); client2.start(); - final CountDownLatch latch = new CountDownLatch(1); - client1.getCuratorListenable().addListener - ( - new CuratorListener() - { - @Override - public void eventReceived(CuratorFramework client, CuratorEvent event) throws Exception - { - if ( event.getType() == CuratorEventType.WATCHED ) - { - if ( event.getWatchedEvent().getType() == Watcher.Event.EventType.NodeDataChanged ) - { - if ( event.getPath().equals("/test") ) - { - latch.countDown(); - } + final CountDownLatch latch = new CountDownLatch(1); + client1.getCuratorListenable().addListener(new CuratorListener() { + @Override + public void eventReceived(CuratorFramework client, CuratorEvent event) throws Exception { + if (event.getType() == CuratorEventType.WATCHED) { + if (event.getWatchedEvent().getType() == Watcher.Event.EventType.NodeDataChanged) { + if (event.getPath().equals("/test")) { + latch.countDown(); } } } } - ); + }); - client1.create().forPath("/test", new byte[]{1, 2, 3}); + client1.create().forPath("/test", new byte[] {1, 2, 3}); client1.checkExists().watched().forPath("/test"); - client2.getCuratorListenable().addListener - ( - new CuratorListener() - { - @Override - public void eventReceived(CuratorFramework client, CuratorEvent event) throws Exception - { - if ( event.getType() == CuratorEventType.SYNC ) - { - client.setData().forPath("/test", new byte[]{10, 20}); - } + client2.getCuratorListenable().addListener(new CuratorListener() { + @Override + public void eventReceived(CuratorFramework client, CuratorEvent event) throws Exception { + if (event.getType() == CuratorEventType.SYNC) { + client.setData().forPath("/test", new byte[] {10, 20}); } } - ); + }); client2.sync().forPath("/test"); assertTrue(latch.await(10, TimeUnit.SECONDS)); - } - finally - { + } finally { CloseableUtils.closeQuietly(client1); CloseableUtils.closeQuietly(client2); } diff --git a/curator-framework/src/test/java/org/apache/curator/framework/imps/TestNamespaceFacade.java b/curator-framework/src/test/java/org/apache/curator/framework/imps/TestNamespaceFacade.java index 69aa9e4c5..131c62cce 100644 --- a/curator-framework/src/test/java/org/apache/curator/framework/imps/TestNamespaceFacade.java +++ b/curator-framework/src/test/java/org/apache/curator/framework/imps/TestNamespaceFacade.java @@ -26,40 +26,40 @@ import static org.junit.jupiter.api.Assertions.fail; import java.util.Collections; import java.util.List; - -import org.apache.curator.test.BaseClassForTests; -import org.apache.curator.utils.CloseableUtils; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.retry.RetryOneTime; -import org.apache.zookeeper.ZooDefs; +import org.apache.curator.test.BaseClassForTests; +import org.apache.curator.utils.CloseableUtils; import org.apache.zookeeper.KeeperException.NoAuthException; +import org.apache.zookeeper.ZooDefs; import org.apache.zookeeper.data.ACL; import org.junit.jupiter.api.Test; -public class TestNamespaceFacade extends BaseClassForTests -{ +public class TestNamespaceFacade extends BaseClassForTests { @Test - public void testInvalid() throws Exception - { - try - { - CuratorFrameworkFactory.builder().namespace("/snafu").retryPolicy(new RetryOneTime(1)).connectString("foo").build(); + public void testInvalid() throws Exception { + try { + CuratorFrameworkFactory.builder() + .namespace("/snafu") + .retryPolicy(new RetryOneTime(1)) + .connectString("foo") + .build(); fail(); - } - catch ( IllegalArgumentException e ) - { + } catch (IllegalArgumentException e) { // correct } } @Test - public void testGetNamespace() throws Exception - { - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); - CuratorFramework client2 = CuratorFrameworkFactory.builder().namespace("snafu").retryPolicy(new RetryOneTime(1)).connectString("foo").build(); - try - { + public void testGetNamespace() throws Exception { + CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); + CuratorFramework client2 = CuratorFrameworkFactory.builder() + .namespace("snafu") + .retryPolicy(new RetryOneTime(1)) + .connectString("foo") + .build(); + try { client.start(); CuratorFramework fooClient = client.usingNamespace("foo"); @@ -69,20 +69,16 @@ public void testGetNamespace() throws Exception assertEquals(client2.getNamespace(), "snafu"); assertEquals(fooClient.getNamespace(), "foo"); assertEquals(barClient.getNamespace(), "bar"); - } - finally - { + } finally { CloseableUtils.closeQuietly(client2); CloseableUtils.closeQuietly(client); } } @Test - public void testSimultaneous() throws Exception - { - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); - try - { + public void testSimultaneous() throws Exception { + CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); + try { client.start(); CuratorFramework fooClient = client.usingNamespace("foo"); @@ -93,36 +89,28 @@ public void testSimultaneous() throws Exception assertNotNull(client.getZookeeperClient().getZooKeeper().exists("/foo/one", false)); assertNotNull(client.getZookeeperClient().getZooKeeper().exists("/bar/one", false)); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } @Test - public void testCache() throws Exception - { - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); - try - { + public void testCache() throws Exception { + CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); + try { client.start(); assertSame(client.usingNamespace("foo"), client.usingNamespace("foo")); assertNotSame(client.usingNamespace("foo"), client.usingNamespace("bar")); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } @Test - public void testBasic() throws Exception - { - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); - try - { + public void testBasic() throws Exception { + CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); + try { client.start(); client.create().forPath("/one"); @@ -134,9 +122,7 @@ public void testBasic() throws Exception client.usingNamespace("name").create().forPath("/one"); assertNotNull(client.getZookeeperClient().getZooKeeper().exists("/name", false)); assertNotNull(client.getZookeeperClient().getZooKeeper().exists("/name/one", false)); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } @@ -145,98 +131,92 @@ public void testBasic() throws Exception * CURATOR-128: access root node within a namespace. */ @Test - public void testRootAccess() throws Exception - { - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); - try - { + public void testRootAccess() throws Exception { + CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); + try { client.start(); client.create().forPath("/one"); assertNotNull(client.getZookeeperClient().getZooKeeper().exists("/one", false)); assertNotNull(client.checkExists().forPath("/")); - try - { + try { client.checkExists().forPath(""); fail("IllegalArgumentException expected"); - } - catch ( IllegalArgumentException expected ) - { + } catch (IllegalArgumentException expected) { } assertNotNull(client.usingNamespace("one").checkExists().forPath("/")); - try - { + try { client.usingNamespace("one").checkExists().forPath(""); fail("IllegalArgumentException expected"); + } catch (IllegalArgumentException expected) { } - catch ( IllegalArgumentException expected ) - { - } - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } - @Test - public void testIsStarted() throws Exception - { - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); + public void testIsStarted() throws Exception { + CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client.start(); - CuratorFramework namespaced = client.usingNamespace(null); + CuratorFramework namespaced = client.usingNamespace(null); - assertEquals(client.getState(), namespaced.getState(), "Namespaced state did not match true state after call to start."); + assertEquals( + client.getState(), + namespaced.getState(), + "Namespaced state did not match true state after call to start."); client.close(); - assertEquals(client.getState(), namespaced.getState(), "Namespaced state did not match true state after call to close."); + assertEquals( + client.getState(), + namespaced.getState(), + "Namespaced state did not match true state after call to close."); } - + /** * Test that ACLs work on a NamespaceFacade. See CURATOR-132 * @throws Exception */ @Test - public void testACL() throws Exception - { - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); + public void testACL() throws Exception { + CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client.start(); client.getZookeeperClient().blockUntilConnectedOrTimedOut(); client.create().creatingParentsIfNeeded().forPath("/parent/child", "A string".getBytes()); CuratorFramework client2 = client.usingNamespace("parent"); - assertNotNull(client2.getData().forPath("/child")); - client.setACL().withACL(Collections.singletonList( - new ACL(ZooDefs.Perms.WRITE, ZooDefs.Ids.ANYONE_ID_UNSAFE))). - forPath("/parent/child"); + assertNotNull(client2.getData().forPath("/child")); + client.setACL() + .withACL(Collections.singletonList(new ACL(ZooDefs.Perms.WRITE, ZooDefs.Ids.ANYONE_ID_UNSAFE))) + .forPath("/parent/child"); // This will attempt to setACL on /parent/child, Previously this failed because /child // isn't present. Using "child" would case a failure because the path didn't start with // a slash - try - { + try { List acls = client2.getACL().forPath("/child"); assertNotNull(acls); assertEquals(acls.size(), 1); assertEquals(acls.get(0).getId(), ZooDefs.Ids.ANYONE_ID_UNSAFE); assertEquals(acls.get(0).getPerms(), ZooDefs.Perms.WRITE); - client2.setACL().withACL(Collections.singletonList( - new ACL(ZooDefs.Perms.DELETE, ZooDefs.Ids.ANYONE_ID_UNSAFE))). - forPath("/child"); + client2.setACL() + .withACL(Collections.singletonList(new ACL(ZooDefs.Perms.DELETE, ZooDefs.Ids.ANYONE_ID_UNSAFE))) + .forPath("/child"); fail("Expected auth exception was not thrown"); - } - catch(NoAuthException e) - { - //Expected + } catch (NoAuthException e) { + // Expected } } @Test public void testUnfixForEmptyNamespace() { - CuratorFramework client = CuratorFrameworkFactory.builder().namespace("").retryPolicy(new RetryOneTime(1)).connectString("foo").build(); + CuratorFramework client = CuratorFrameworkFactory.builder() + .namespace("") + .retryPolicy(new RetryOneTime(1)) + .connectString("foo") + .build(); CuratorFrameworkImpl clientImpl = (CuratorFrameworkImpl) client; assertEquals(clientImpl.unfixForNamespace("/foo/bar"), "/foo/bar"); diff --git a/curator-framework/src/test/java/org/apache/curator/framework/imps/TestNeverConnected.java b/curator-framework/src/test/java/org/apache/curator/framework/imps/TestNeverConnected.java index cd85bd9f9..5e399baae 100644 --- a/curator-framework/src/test/java/org/apache/curator/framework/imps/TestNeverConnected.java +++ b/curator-framework/src/test/java/org/apache/curator/framework/imps/TestNeverConnected.java @@ -21,34 +21,29 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import com.google.common.collect.Queues; -import org.apache.curator.utils.CloseableUtils; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.TimeUnit; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.state.ConnectionState; import org.apache.curator.framework.state.ConnectionStateListener; import org.apache.curator.retry.RetryOneTime; import org.apache.curator.test.Timing; +import org.apache.curator.utils.CloseableUtils; import org.junit.jupiter.api.Test; -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.TimeUnit; -public class TestNeverConnected -{ +public class TestNeverConnected { @Test - public void testNeverConnected() throws Exception - { + public void testNeverConnected() throws Exception { Timing timing = new Timing(); // use a connection string to a non-existent server CuratorFramework client = CuratorFrameworkFactory.newClient("localhost:1111", 100, 100, new RetryOneTime(1)); - try - { + try { final BlockingQueue queue = Queues.newLinkedBlockingQueue(); - ConnectionStateListener listener = new ConnectionStateListener() - { + ConnectionStateListener listener = new ConnectionStateListener() { @Override - public void stateChanged(CuratorFramework client, ConnectionState state) - { + public void stateChanged(CuratorFramework client, ConnectionState state) { queue.add(state); } }; @@ -61,9 +56,7 @@ public void stateChanged(CuratorFramework client, ConnectionState state) assertEquals(polled, ConnectionState.SUSPENDED); polled = queue.poll(timing.forWaiting().seconds(), TimeUnit.SECONDS); assertEquals(polled, ConnectionState.LOST); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } diff --git a/curator-framework/src/test/java/org/apache/curator/framework/imps/TestReadOnly.java b/curator-framework/src/test/java/org/apache/curator/framework/imps/TestReadOnly.java index be0c312fe..6dd6b5563 100644 --- a/curator-framework/src/test/java/org/apache/curator/framework/imps/TestReadOnly.java +++ b/curator-framework/src/test/java/org/apache/curator/framework/imps/TestReadOnly.java @@ -23,6 +23,10 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import com.google.common.collect.Queues; +import java.util.Iterator; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.state.ConnectionState; @@ -39,35 +43,26 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import java.util.Iterator; -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; - -public class TestReadOnly extends BaseClassForTests -{ +public class TestReadOnly extends BaseClassForTests { @BeforeEach - public void setup() - { + public void setup() { System.setProperty("readonlymode.enabled", "true"); } @AfterEach - public void tearDown() - { + public void tearDown() { System.setProperty("readonlymode.enabled", "false"); } @Test - public void testConnectionStateNewClient() throws Exception - { + public void testConnectionStateNewClient() throws Exception { Timing timing = new Timing(); CuratorFramework client = null; TestingCluster cluster = createAndStartCluster(3); - try - { + try { final CountDownLatch lostLatch = new CountDownLatch(1); - client = CuratorFrameworkFactory.newClient(cluster.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(100)); + client = CuratorFrameworkFactory.newClient( + cluster.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(100)); client.start(); client.checkExists().forPath("/"); client.getConnectionStateListenable().addListener((client1, newState) -> { @@ -77,20 +72,19 @@ public void testConnectionStateNewClient() throws Exception }); Iterator iterator = cluster.getInstances().iterator(); - for ( int i = 0; i < 2; ++i ) - { + for (int i = 0; i < 2; ++i) { cluster.killServer(iterator.next()); } timing.awaitLatch(lostLatch); client.close(); client = CuratorFrameworkFactory.builder() - .connectString(cluster.getConnectString()) - .sessionTimeoutMs(timing.session()) - .connectionTimeoutMs(timing.connection()) - .retryPolicy(new RetryNTimes(3, timing.milliseconds())) - .canBeReadOnly(true) - .build(); + .connectString(cluster.getConnectString()) + .sessionTimeoutMs(timing.session()) + .connectionTimeoutMs(timing.connection()) + .retryPolicy(new RetryNTimes(3, timing.milliseconds())) + .canBeReadOnly(true) + .build(); final BlockingQueue states = Queues.newLinkedBlockingQueue(); client.getConnectionStateListenable().addListener((client12, newState) -> states.add(newState)); @@ -100,24 +94,26 @@ public void testConnectionStateNewClient() throws Exception ConnectionState state = states.poll(timing.forWaiting().milliseconds(), TimeUnit.MILLISECONDS); assertThat(state).isEqualTo(ConnectionState.READ_ONLY); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); CloseableUtils.closeQuietly(cluster); } } @Test - public void testReadOnly() throws Exception - { + public void testReadOnly() throws Exception { Timing timing = new Timing(); CuratorFramework client = null; TestingCluster cluster = createAndStartCluster(2); - try - { - client = CuratorFrameworkFactory.builder().connectString(cluster.getConnectString()).canBeReadOnly(true).connectionTimeoutMs(timing.connection()).sessionTimeoutMs(timing.session()).retryPolicy(new ExponentialBackoffRetry(100, 3)).build(); + try { + client = CuratorFrameworkFactory.builder() + .connectString(cluster.getConnectString()) + .canBeReadOnly(true) + .connectionTimeoutMs(timing.connection()) + .sessionTimeoutMs(timing.session()) + .retryPolicy(new ExponentialBackoffRetry(100, 3)) + .build(); client.start(); client.create().forPath("/test"); @@ -125,22 +121,19 @@ public void testReadOnly() throws Exception final CountDownLatch readOnlyLatch = new CountDownLatch(1); final CountDownLatch reconnectedLatch = new CountDownLatch(1); ConnectionStateListener listener = (client1, newState) -> { - if ( newState == ConnectionState.READ_ONLY ) - { + if (newState == ConnectionState.READ_ONLY) { readOnlyLatch.countDown(); - } - else if ( newState == ConnectionState.RECONNECTED ) - { + } else if (newState == ConnectionState.RECONNECTED) { reconnectedLatch.countDown(); } }; client.getConnectionStateListenable().addListener(listener); - InstanceSpec ourInstance = cluster.findConnectionInstance(client.getZookeeperClient().getZooKeeper()); + InstanceSpec ourInstance = + cluster.findConnectionInstance(client.getZookeeperClient().getZooKeeper()); Iterator iterator = cluster.getInstances().iterator(); InstanceSpec killInstance = iterator.next(); - if ( killInstance.equals(ourInstance) ) - { + if (killInstance.equals(ourInstance)) { killInstance = iterator.next(); // kill the instance we're not connected to } cluster.killServer(killInstance); @@ -151,17 +144,14 @@ else if ( newState == ConnectionState.RECONNECTED ) assertEquals(reconnectedLatch.getCount(), 1); cluster.restartServer(killInstance); assertTrue(timing.awaitLatch(reconnectedLatch)); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); CloseableUtils.closeQuietly(cluster); } } @Override - protected void createServer() - { + protected void createServer() { // NOP } } diff --git a/curator-framework/src/test/java/org/apache/curator/framework/imps/TestReconfiguration.java b/curator-framework/src/test/java/org/apache/curator/framework/imps/TestReconfiguration.java index 082a948a1..c279749b1 100644 --- a/curator-framework/src/test/java/org/apache/curator/framework/imps/TestReconfiguration.java +++ b/curator-framework/src/test/java/org/apache/curator/framework/imps/TestReconfiguration.java @@ -19,7 +19,25 @@ package org.apache.curator.framework.imps; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import com.google.common.collect.Lists; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.Iterator; +import java.util.List; +import java.util.Properties; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; import org.apache.curator.ensemble.EnsembleProvider; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; @@ -46,39 +64,18 @@ import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.net.InetAddress; -import java.net.InetSocketAddress; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.Iterator; -import java.util.List; -import java.util.Properties; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicReference; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - -public class TestReconfiguration extends CuratorTestBase -{ +public class TestReconfiguration extends CuratorTestBase { private final Timing2 timing = new Timing2(); private TestingCluster cluster; private EnsembleProvider ensembleProvider; - private static final String superUserPasswordDigest = "curator-test:zghsj3JfJqK7DbWf0RQ1BgbJH9w="; // ran from DigestAuthenticationProvider.generateDigest(superUserPassword); + private static final String superUserPasswordDigest = "curator-test:zghsj3JfJqK7DbWf0RQ1BgbJH9w="; // ran from + // DigestAuthenticationProvider.generateDigest(superUserPassword); private static final String superUserPassword = "curator-test"; @BeforeEach @Override - public void setup() throws Exception - { + public void setup() throws Exception { super.setup(); QuorumPeerConfig.setReconfigEnabled(true); @@ -90,8 +87,7 @@ public void setup() throws Exception @AfterEach @Override - public void teardown() throws Exception - { + public void teardown() throws Exception { CloseableUtils.closeQuietly(cluster); ensembleProvider = null; System.clearProperty("zookeeper.DigestAuthenticationProvider.superDigest"); @@ -102,8 +98,7 @@ public void teardown() throws Exception @SuppressWarnings("ConstantConditions") @Test @Disabled - public void testApiPermutations() throws Exception - { + public void testApiPermutations() throws Exception { // not an actual test. Specifies all possible API possibilities Watcher watcher = null; @@ -117,7 +112,11 @@ public void testApiPermutations() throws Exception client.getConfig().storingStatIn(stat).forEnsemble(); client.getConfig().storingStatIn(stat).inBackground().forEnsemble(); client.getConfig().storingStatIn(stat).usingWatcher(watcher).forEnsemble(); - client.getConfig().storingStatIn(stat).usingWatcher(watcher).inBackground().forEnsemble(); + client.getConfig() + .storingStatIn(stat) + .usingWatcher(watcher) + .inBackground() + .forEnsemble(); // --------- @@ -163,33 +162,57 @@ public void testApiPermutations() throws Exception client.reconfig().inBackground().joining().leaving().storingStatIn(stat).forEnsemble(); client.reconfig().inBackground().withNewMembers().storingStatIn(stat).forEnsemble(); - client.reconfig().inBackground().leaving().storingStatIn(stat).fromConfig(0).forEnsemble(); - client.reconfig().inBackground().joining().storingStatIn(stat).fromConfig(0).forEnsemble(); - client.reconfig().inBackground().leaving().joining().storingStatIn(stat).fromConfig(0).forEnsemble(); - client.reconfig().inBackground().joining().leaving().storingStatIn(stat).fromConfig(0).forEnsemble(); - client.reconfig().inBackground().withNewMembers().storingStatIn(stat).fromConfig(0).forEnsemble(); + client.reconfig() + .inBackground() + .leaving() + .storingStatIn(stat) + .fromConfig(0) + .forEnsemble(); + client.reconfig() + .inBackground() + .joining() + .storingStatIn(stat) + .fromConfig(0) + .forEnsemble(); + client.reconfig() + .inBackground() + .leaving() + .joining() + .storingStatIn(stat) + .fromConfig(0) + .forEnsemble(); + client.reconfig() + .inBackground() + .joining() + .leaving() + .storingStatIn(stat) + .fromConfig(0) + .forEnsemble(); + client.reconfig() + .inBackground() + .withNewMembers() + .storingStatIn(stat) + .fromConfig(0) + .forEnsemble(); } @Test - public void testBasicGetConfig() throws Exception - { - try ( CuratorFramework client = newClient()) - { + public void testBasicGetConfig() throws Exception { + try (CuratorFramework client = newClient()) { client.start(); byte[] configData = client.getConfig().forEnsemble(); QuorumVerifier quorumVerifier = toQuorumVerifier(configData); System.out.println(quorumVerifier); assertConfig(quorumVerifier, cluster.getInstances()); - assertEquals(EnsembleTracker.configToConnectionString(quorumVerifier), ensembleProvider.getConnectionString()); + assertEquals( + EnsembleTracker.configToConnectionString(quorumVerifier), ensembleProvider.getConnectionString()); } } @Test - public void testAddWithoutEnsembleTracker() throws Exception - { + public void testAddWithoutEnsembleTracker() throws Exception { final String initialClusterCS = cluster.getConnectString(); - try ( CuratorFramework client = newClient(cluster.getConnectString(), false)) - { + try (CuratorFramework client = newClient(cluster.getConnectString(), false)) { assertEquals(((CuratorFrameworkImpl) client).getEnsembleTracker(), null); client.start(); @@ -197,11 +220,13 @@ public void testAddWithoutEnsembleTracker() throws Exception assertConfig(oldConfig, cluster.getInstances()); CountDownLatch latch = setChangeWaiter(client); - try ( TestingCluster newCluster = new TestingCluster(TestingCluster.makeSpecs(1, false)) ) - { + try (TestingCluster newCluster = new TestingCluster(TestingCluster.makeSpecs(1, false))) { newCluster.start(); - client.reconfig().joining(toReconfigSpec(newCluster.getInstances())).fromConfig(oldConfig.getVersion()).forEnsemble(); + client.reconfig() + .joining(toReconfigSpec(newCluster.getInstances())) + .fromConfig(oldConfig.getVersion()) + .forEnsemble(); assertTrue(timing.awaitLatch(latch)); @@ -211,40 +236,40 @@ public void testAddWithoutEnsembleTracker() throws Exception newInstances.addAll(newCluster.getInstances()); assertConfig(newConfig, newInstances); assertEquals(ensembleProvider.getConnectionString(), initialClusterCS); - assertNotEquals(EnsembleTracker.configToConnectionString(newConfig), ensembleProvider.getConnectionString()); + assertNotEquals( + EnsembleTracker.configToConnectionString(newConfig), ensembleProvider.getConnectionString()); assertEquals(client.getZookeeperClient().getCurrentConnectionString(), initialClusterCS); final CountDownLatch reconnectLatch = new CountDownLatch(1); - client.getConnectionStateListenable().addListener( - (cfClient, newState) -> { - if (newState == ConnectionState.RECONNECTED) reconnectLatch.countDown(); - } - ); + client.getConnectionStateListenable().addListener((cfClient, newState) -> { + if (newState == ConnectionState.RECONNECTED) reconnectLatch.countDown(); + }); client.getZookeeperClient().getZooKeeper().getTestable().injectSessionExpiration(); assertTrue(reconnectLatch.await(2, TimeUnit.SECONDS)); assertEquals(client.getZookeeperClient().getCurrentConnectionString(), initialClusterCS); assertEquals(ensembleProvider.getConnectionString(), initialClusterCS); newConfigData = client.getConfig().forEnsemble(); - assertNotEquals(EnsembleTracker.configToConnectionString(newConfig), ensembleProvider.getConnectionString()); + assertNotEquals( + EnsembleTracker.configToConnectionString(newConfig), ensembleProvider.getConnectionString()); } } } @Test - public void testAdd() throws Exception - { - try ( CuratorFramework client = newClient()) - { + public void testAdd() throws Exception { + try (CuratorFramework client = newClient()) { client.start(); QuorumVerifier oldConfig = toQuorumVerifier(client.getConfig().forEnsemble()); assertConfig(oldConfig, cluster.getInstances()); CountDownLatch latch = setChangeWaiter(client); - try ( TestingCluster newCluster = new TestingCluster(TestingCluster.makeSpecs(1, false)) ) - { + try (TestingCluster newCluster = new TestingCluster(TestingCluster.makeSpecs(1, false))) { newCluster.start(); - client.reconfig().joining(toReconfigSpec(newCluster.getInstances())).fromConfig(oldConfig.getVersion()).forEnsemble(); + client.reconfig() + .joining(toReconfigSpec(newCluster.getInstances())) + .fromConfig(oldConfig.getVersion()) + .forEnsemble(); assertTrue(timing.awaitLatch(latch)); @@ -253,39 +278,38 @@ public void testAdd() throws Exception List newInstances = Lists.newArrayList(cluster.getInstances()); newInstances.addAll(newCluster.getInstances()); assertConfig(newConfig, newInstances); - assertEquals(EnsembleTracker.configToConnectionString(newConfig), ensembleProvider.getConnectionString()); + assertEquals( + EnsembleTracker.configToConnectionString(newConfig), ensembleProvider.getConnectionString()); } } } @Test - public void testAddAsync() throws Exception - { - try ( CuratorFramework client = newClient()) - { + public void testAddAsync() throws Exception { + try (CuratorFramework client = newClient()) { client.start(); QuorumVerifier oldConfig = toQuorumVerifier(client.getConfig().forEnsemble()); assertConfig(oldConfig, cluster.getInstances()); CountDownLatch latch = setChangeWaiter(client); - try ( TestingCluster newCluster = new TestingCluster(TestingCluster.makeSpecs(1, false)) ) - { + try (TestingCluster newCluster = new TestingCluster(TestingCluster.makeSpecs(1, false))) { newCluster.start(); final CountDownLatch callbackLatch = new CountDownLatch(1); - BackgroundCallback callback = new BackgroundCallback() - { + BackgroundCallback callback = new BackgroundCallback() { @Override - public void processResult(CuratorFramework client, CuratorEvent event) throws Exception - { - if ( event.getType() == CuratorEventType.RECONFIG ) - { + public void processResult(CuratorFramework client, CuratorEvent event) throws Exception { + if (event.getType() == CuratorEventType.RECONFIG) { callbackLatch.countDown(); } } }; - client.reconfig().inBackground(callback).joining(toReconfigSpec(newCluster.getInstances())).fromConfig(oldConfig.getVersion()).forEnsemble(); + client.reconfig() + .inBackground(callback) + .joining(toReconfigSpec(newCluster.getInstances())) + .fromConfig(oldConfig.getVersion()) + .forEnsemble(); assertTrue(timing.awaitLatch(callbackLatch)); assertTrue(timing.awaitLatch(latch)); @@ -295,16 +319,15 @@ public void processResult(CuratorFramework client, CuratorEvent event) throws Ex List newInstances = Lists.newArrayList(cluster.getInstances()); newInstances.addAll(newCluster.getInstances()); assertConfig(newConfig, newInstances); - assertEquals(EnsembleTracker.configToConnectionString(newConfig), ensembleProvider.getConnectionString()); + assertEquals( + EnsembleTracker.configToConnectionString(newConfig), ensembleProvider.getConnectionString()); } } } @Test - public void testAddAndRemove() throws Exception - { - try ( CuratorFramework client = newClient()) - { + public void testAddAndRemove() throws Exception { + try (CuratorFramework client = newClient()) { client.start(); QuorumVerifier oldConfig = toQuorumVerifier(client.getConfig().forEnsemble()); @@ -312,21 +335,25 @@ public void testAddAndRemove() throws Exception CountDownLatch latch = setChangeWaiter(client); - try ( TestingCluster newCluster = new TestingCluster(TestingCluster.makeSpecs(1, false)) ) - { + try (TestingCluster newCluster = new TestingCluster(TestingCluster.makeSpecs(1, false))) { newCluster.start(); Collection oldInstances = cluster.getInstances(); - InstanceSpec us = cluster.findConnectionInstance(client.getZookeeperClient().getZooKeeper()); + InstanceSpec us = cluster.findConnectionInstance( + client.getZookeeperClient().getZooKeeper()); InstanceSpec removeSpec = oldInstances.iterator().next(); - if ( us.equals(removeSpec) ) { + if (us.equals(removeSpec)) { Iterator iterator = oldInstances.iterator(); iterator.next(); removeSpec = iterator.next(); } Collection instances = newCluster.getInstances(); - client.reconfig().leaving(Integer.toString(removeSpec.getServerId())).joining(toReconfigSpec(instances)).fromConfig(oldConfig.getVersion()).forEnsemble(); + client.reconfig() + .leaving(Integer.toString(removeSpec.getServerId())) + .joining(toReconfigSpec(instances)) + .fromConfig(oldConfig.getVersion()) + .forEnsemble(); assertTrue(timing.awaitLatch(latch)); @@ -336,16 +363,15 @@ public void testAddAndRemove() throws Exception newInstances.addAll(instances); newInstances.remove(removeSpec); assertConfig(newConfig, newInstances); - assertEquals(EnsembleTracker.configToConnectionString(newConfig), ensembleProvider.getConnectionString()); + assertEquals( + EnsembleTracker.configToConnectionString(newConfig), ensembleProvider.getConnectionString()); } } } @Test - public void testAddAndRemoveWithEmptyList() throws Exception - { - try ( CuratorFramework client = newClient()) - { + public void testAddAndRemoveWithEmptyList() throws Exception { + try (CuratorFramework client = newClient()) { client.start(); QuorumVerifier oldConfig = toQuorumVerifier(client.getConfig().forEnsemble()); @@ -354,7 +380,11 @@ public void testAddAndRemoveWithEmptyList() throws Exception CountDownLatch latch = setChangeWaiter(client); Collection oldInstances = cluster.getInstances(); - client.reconfig().leaving(Collections.emptyList()).joining(Collections.emptyList()).fromConfig(oldConfig.getVersion()).forEnsemble(); + client.reconfig() + .leaving(Collections.emptyList()) + .joining(Collections.emptyList()) + .fromConfig(oldConfig.getVersion()) + .forEnsemble(); assertTrue(timing.awaitLatch(latch)); @@ -366,10 +396,8 @@ public void testAddAndRemoveWithEmptyList() throws Exception } @Test - public void testNewMembersWithEmptyList() throws Exception - { - try ( CuratorFramework client = newClient()) - { + public void testNewMembersWithEmptyList() throws Exception { + try (CuratorFramework client = newClient()) { client.start(); QuorumVerifier oldConfig = toQuorumVerifier(client.getConfig().forEnsemble()); @@ -378,7 +406,10 @@ public void testNewMembersWithEmptyList() throws Exception CountDownLatch latch = setChangeWaiter(client); Collection oldInstances = cluster.getInstances(); - client.reconfig().withNewMembers(Collections.emptyList()).fromConfig(oldConfig.getVersion()).forEnsemble(); + client.reconfig() + .withNewMembers(Collections.emptyList()) + .fromConfig(oldConfig.getVersion()) + .forEnsemble(); assertTrue(timing.awaitLatch(latch)); @@ -391,18 +422,16 @@ public void testNewMembersWithEmptyList() throws Exception @Test @Disabled // it's what this test is inteded to do and it keeps failing - disable for now - public void testNewMembers() throws Exception - { + public void testNewMembers() throws Exception { cluster.close(); cluster = null; TestingCluster smallCluster = null; TestingCluster localCluster = new TestingCluster(5); - try - { + try { List servers = localCluster.getServers(); List smallClusterInstances = Lists.newArrayList(); - for ( int i = 0; i < 3; ++i ) // only start 3 of the 5 + for (int i = 0; i < 3; ++i) // only start 3 of the 5 { TestingZooKeeperServer server = servers.get(i); server.start(); @@ -410,8 +439,7 @@ public void testNewMembers() throws Exception } smallCluster = new TestingCluster(smallClusterInstances); - try ( CuratorFramework client = newClient(smallCluster.getConnectString())) - { + try (CuratorFramework client = newClient(smallCluster.getConnectString())) { client.start(); QuorumVerifier oldConfig = toQuorumVerifier(client.getConfig().forEnsemble()); @@ -420,26 +448,26 @@ public void testNewMembers() throws Exception CountDownLatch latch = setChangeWaiter(client); - client.reconfig().withNewMembers(toReconfigSpec(smallClusterInstances)).forEnsemble(); + client.reconfig() + .withNewMembers(toReconfigSpec(smallClusterInstances)) + .forEnsemble(); assertTrue(timing.awaitLatch(latch)); byte[] newConfigData = client.getConfig().forEnsemble(); QuorumVerifier newConfig = toQuorumVerifier(newConfigData); assertEquals(newConfig.getAllMembers().size(), 3); assertConfig(newConfig, smallClusterInstances); - assertEquals(EnsembleTracker.configToConnectionString(newConfig), ensembleProvider.getConnectionString()); + assertEquals( + EnsembleTracker.configToConnectionString(newConfig), ensembleProvider.getConnectionString()); } - } - finally - { + } finally { CloseableUtils.closeQuietly(smallCluster); CloseableUtils.closeQuietly(localCluster); } } @Test - public void testRemoveWithChroot() throws Exception - { + public void testRemoveWithChroot() throws Exception { // Use a long chroot path to circumvent ZOOKEEPER-4565 and ZOOKEEPER-4601 String chroot = "/pretty-long-chroot"; CountDownLatch ensembleLatch = new CountDownLatch(1); @@ -454,15 +482,19 @@ public void testRemoveWithChroot() throws Exception CountDownLatch latch = setChangeWaiter(client); Collection oldInstances = cluster.getInstances(); - InstanceSpec us = cluster.findConnectionInstance(client.getZookeeperClient().getZooKeeper()); + InstanceSpec us = + cluster.findConnectionInstance(client.getZookeeperClient().getZooKeeper()); InstanceSpec removeSpec = oldInstances.iterator().next(); - if ( us.equals(removeSpec) ) { + if (us.equals(removeSpec)) { Iterator iterator = oldInstances.iterator(); iterator.next(); removeSpec = iterator.next(); } - client.reconfig().leaving(Integer.toString(removeSpec.getServerId())).fromConfig(oldConfig.getVersion()).forEnsemble(); + client.reconfig() + .leaving(Integer.toString(removeSpec.getServerId())) + .fromConfig(oldConfig.getVersion()) + .forEnsemble(); assertTrue(timing.awaitLatch(latch)); @@ -484,164 +516,140 @@ public void testRemoveWithChroot() throws Exception } @Test - public void testConfigToConnectionStringIPv4Normal() throws Exception - { + public void testConfigToConnectionStringIPv4Normal() throws Exception { String config = "server.1=10.1.2.3:2888:3888:participant;10.2.3.4:2181"; String configString = EnsembleTracker.configToConnectionString(toQuorumVerifier(config.getBytes())); assertEquals("10.2.3.4:2181", configString); } @Test - public void testConfigToConnectionStringIPv6Normal() throws Exception - { - String config = "server.1=[1010:0001:0002:0003:0004:0005:0006:0007]:2888:3888:participant;[2001:db8:85a3:0:0:8a2e:370:7334]:2181"; + public void testConfigToConnectionStringIPv6Normal() throws Exception { + String config = + "server.1=[1010:0001:0002:0003:0004:0005:0006:0007]:2888:3888:participant;[2001:db8:85a3:0:0:8a2e:370:7334]:2181"; String configString = EnsembleTracker.configToConnectionString(toQuorumVerifier(config.getBytes())); assertEquals("2001:db8:85a3:0:0:8a2e:370:7334:2181", configString); } @Test - public void testConfigToConnectionStringIPv4NoClientAddr() throws Exception - { + public void testConfigToConnectionStringIPv4NoClientAddr() throws Exception { String config = "server.1=10.1.2.3:2888:3888:participant;2181"; String configString = EnsembleTracker.configToConnectionString(toQuorumVerifier(config.getBytes())); assertEquals("10.1.2.3:2181", configString); } @Test - public void testConfigToConnectionStringIPv4WildcardClientAddr() throws Exception - { + public void testConfigToConnectionStringIPv4WildcardClientAddr() throws Exception { String config = "server.1=10.1.2.3:2888:3888:participant;0.0.0.0:2181"; String configString = EnsembleTracker.configToConnectionString(toQuorumVerifier(config.getBytes())); assertEquals("10.1.2.3:2181", configString); } @Test - public void testConfigToConnectionStringNoClientAddrOrPort() throws Exception - { + public void testConfigToConnectionStringNoClientAddrOrPort() throws Exception { String config = "server.1=10.1.2.3:2888:3888:participant"; String configString = EnsembleTracker.configToConnectionString(toQuorumVerifier(config.getBytes())); assertEquals("", configString); } @Test - public void testConfigToConnectionStringPreservesHostnameNormal() throws Exception - { + public void testConfigToConnectionStringPreservesHostnameNormal() throws Exception { String config = "server.1=server.addr:2888:3888:participant;client.addr:2181"; String configString = EnsembleTracker.configToConnectionString(toQuorumVerifier(config.getBytes())); assertEquals("client.addr:2181", configString); } @Test - public void testConfigToConnectionStringPreservesHostnameNoClientAddr() throws Exception - { + public void testConfigToConnectionStringPreservesHostnameNoClientAddr() throws Exception { String config = "server.1=server.addr:2888:3888:participant;2181"; String configString = EnsembleTracker.configToConnectionString(toQuorumVerifier(config.getBytes())); assertEquals("server.addr:2181", configString); } @Test - public void testConfigToConnectionStringPreservesHostnameIPv4Wildcard() throws Exception - { + public void testConfigToConnectionStringPreservesHostnameIPv4Wildcard() throws Exception { String config = "server.1=server.addr:2888:3888:participant;0.0.0.0:2181"; String configString = EnsembleTracker.configToConnectionString(toQuorumVerifier(config.getBytes())); assertEquals("server.addr:2181", configString); } @Test - public void testConfigToConnectionStringPreservesHostnameIPv6Wildcard() throws Exception - { + public void testConfigToConnectionStringPreservesHostnameIPv6Wildcard() throws Exception { String config = "server.1=server.addr:2888:3888:participant;[::]:2181"; String configString = EnsembleTracker.configToConnectionString(toQuorumVerifier(config.getBytes())); assertEquals("server.addr:2181", configString); } @Test - public void testIPv6Wildcard1() throws Exception - { + public void testIPv6Wildcard1() throws Exception { String config = "server.1=[2001:db8:85a3:0:0:8a2e:370:7334]:2888:3888:participant;[::]:2181"; String configString = EnsembleTracker.configToConnectionString(toQuorumVerifier(config.getBytes())); assertEquals("2001:db8:85a3:0:0:8a2e:370:7334:2181", configString); } @Test - public void testIPv6Wildcard2() throws Exception - { + public void testIPv6Wildcard2() throws Exception { String config = "server.1=[1010:0001:0002:0003:0004:0005:0006:0007]:2888:3888:participant;[::0]:2181"; String configString = EnsembleTracker.configToConnectionString(toQuorumVerifier(config.getBytes())); assertEquals("1010:1:2:3:4:5:6:7:2181", configString); } @Test - public void testMixedIPv1() throws Exception - { + public void testMixedIPv1() throws Exception { String config = "server.1=10.1.2.3:2888:3888:participant;[::]:2181"; String configString = EnsembleTracker.configToConnectionString(toQuorumVerifier(config.getBytes())); assertEquals("10.1.2.3:2181", configString); } @Test - public void testMixedIPv2() throws Exception - { + public void testMixedIPv2() throws Exception { String config = "server.1=[2001:db8:85a3:0:0:8a2e:370:7334]:2888:3888:participant;127.0.0.1:2181"; String configString = EnsembleTracker.configToConnectionString(toQuorumVerifier(config.getBytes())); assertEquals("127.0.0.1:2181", configString); } @Override - protected void createServer() throws Exception - { + protected void createServer() throws Exception { // NOP } - private CuratorFramework newClient() - { + private CuratorFramework newClient() { return newClient(cluster.getConnectString(), true); } - + private CuratorFramework newClient(String connectionString) { - return newClient(connectionString, true); + return newClient(connectionString, true); } - private CuratorFramework newClient(String connectionString, boolean withEnsembleTracker) - { + private CuratorFramework newClient(String connectionString, boolean withEnsembleTracker) { return newClient(connectionString, withEnsembleTracker, null); } - private CuratorFramework newClient(String connectionString, CountDownLatch ensembleLatch) - { + private CuratorFramework newClient(String connectionString, CountDownLatch ensembleLatch) { return newClient(connectionString, ensembleLatch != null, ensembleLatch); } - private CuratorFramework newClient(String connectionString, boolean withEnsembleTracker, CountDownLatch ensembleLatch) - { + private CuratorFramework newClient( + String connectionString, boolean withEnsembleTracker, CountDownLatch ensembleLatch) { final AtomicReference connectString = new AtomicReference<>(connectionString); - ensembleProvider = new EnsembleProvider() - { + ensembleProvider = new EnsembleProvider() { @Override - public void start() throws Exception - { - } + public void start() throws Exception {} @Override - public boolean updateServerListEnabled() - { + public boolean updateServerListEnabled() { return false; } @Override - public String getConnectionString() - { + public String getConnectionString() { return connectString.get(); } @Override - public void close() throws IOException - { - } + public void close() throws IOException {} @Override - public void setConnectionString(String connectionString) - { + public void setConnectionString(String connectionString) { if (!connectionString.equals(getConnectionString())) { connectString.set(connectionString); if (ensembleLatch != null) { @@ -651,25 +659,22 @@ public void setConnectionString(String connectionString) } }; return CuratorFrameworkFactory.builder() - .ensembleProvider(ensembleProvider) - .ensembleTracker(withEnsembleTracker) - .sessionTimeoutMs(timing.session()) - .connectionTimeoutMs(timing.connection()) - .authorization("digest", superUserPassword.getBytes()) - .retryPolicy(new ExponentialBackoffRetry(timing.forSleepingABit().milliseconds(), 3)) - .build(); + .ensembleProvider(ensembleProvider) + .ensembleTracker(withEnsembleTracker) + .sessionTimeoutMs(timing.session()) + .connectionTimeoutMs(timing.connection()) + .authorization("digest", superUserPassword.getBytes()) + .retryPolicy( + new ExponentialBackoffRetry(timing.forSleepingABit().milliseconds(), 3)) + .build(); } - private CountDownLatch setChangeWaiter(CuratorFramework client) throws Exception - { + private CountDownLatch setChangeWaiter(CuratorFramework client) throws Exception { final CountDownLatch latch = new CountDownLatch(1); - Watcher watcher = new Watcher() - { + Watcher watcher = new Watcher() { @Override - public void process(WatchedEvent event) - { - if ( event.getType() == Event.EventType.NodeDataChanged ) - { + public void process(WatchedEvent event) { + if (event.getType() == Event.EventType.NodeDataChanged) { latch.countDown(); } } @@ -678,28 +683,28 @@ public void process(WatchedEvent event) return latch; } - private void assertConfig(QuorumVerifier config, Collection instances) - { - for ( InstanceSpec instance : instances ) - { - QuorumPeer.QuorumServer quorumServer = config.getAllMembers().get((long)instance.getServerId()); - assertNotNull(quorumServer, String.format("Looking for %s - found %s", instance.getServerId(), config.getAllMembers())); + private void assertConfig(QuorumVerifier config, Collection instances) { + for (InstanceSpec instance : instances) { + QuorumPeer.QuorumServer quorumServer = config.getAllMembers().get((long) instance.getServerId()); + assertNotNull( + quorumServer, + String.format("Looking for %s - found %s", instance.getServerId(), config.getAllMembers())); assertEquals(quorumServer.clientAddr.getPort(), instance.getPort()); } } - private List toReconfigSpec(Collection instances) throws Exception - { - String localhost = new InetSocketAddress((InetAddress)null, 0).getAddress().getHostAddress(); + private List toReconfigSpec(Collection instances) throws Exception { + String localhost = + new InetSocketAddress((InetAddress) null, 0).getAddress().getHostAddress(); List specs = Lists.newArrayList(); - for ( InstanceSpec instance : instances ) { - specs.add("server." + instance.getServerId() + "=" + localhost + ":" + instance.getElectionPort() + ":" + instance.getQuorumPort() + ";" + instance.getPort()); + for (InstanceSpec instance : instances) { + specs.add("server." + instance.getServerId() + "=" + localhost + ":" + instance.getElectionPort() + ":" + + instance.getQuorumPort() + ";" + instance.getPort()); } return specs; } - private static QuorumVerifier toQuorumVerifier(byte[] bytes) throws Exception - { + private static QuorumVerifier toQuorumVerifier(byte[] bytes) throws Exception { assertNotNull(bytes); Properties properties = new Properties(); properties.load(new ByteArrayInputStream(bytes)); diff --git a/curator-framework/src/test/java/org/apache/curator/framework/imps/TestSetData.java b/curator-framework/src/test/java/org/apache/curator/framework/imps/TestSetData.java index 0d526e202..20620f79a 100644 --- a/curator-framework/src/test/java/org/apache/curator/framework/imps/TestSetData.java +++ b/curator-framework/src/test/java/org/apache/curator/framework/imps/TestSetData.java @@ -23,7 +23,9 @@ import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; - +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.api.BackgroundCallback; @@ -36,32 +38,25 @@ import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.data.Stat; import org.junit.jupiter.api.Test; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicInteger; -public class TestSetData extends BaseClassForTests -{ +public class TestSetData extends BaseClassForTests { private static byte[] createData = new byte[] {5, 6, 7, 8}; - private CuratorFramework createClient() - { - return CuratorFrameworkFactory.builder(). - connectString(server.getConnectString()). - retryPolicy(new RetryOneTime(1)). - build(); + private CuratorFramework createClient() { + return CuratorFrameworkFactory.builder() + .connectString(server.getConnectString()) + .retryPolicy(new RetryOneTime(1)) + .build(); } /** * Tests normal setData operations */ @Test - public void testNormal() throws Exception - { + public void testNormal() throws Exception { CuratorFramework client = createClient(); - try - { + try { client.start(); Stat stat = new Stat(); @@ -84,9 +79,7 @@ public void testNormal() throws Exception // check that failed request didn't change znode assertArrayEquals(data2, client.getData().forPath(path)); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } @@ -95,11 +88,9 @@ public void testNormal() throws Exception * Tests background versions of setData */ @Test - public void testBackground() throws Exception - { + public void testBackground() throws Exception { CuratorFramework client = createClient(); - try - { + try { client.start(); Stat stat = new Stat(); @@ -123,40 +114,45 @@ public void testBackground() throws Exception // make sure old data is still correct assertArrayEquals(data2, client.getData().forPath(path)); - - } - finally - { + + } finally { CloseableUtils.closeQuietly(client); } } - private void check(CuratorFramework client, BackgroundPathAndBytesable builder, String path, byte[] data, int expectedCode, int expectedVersionAfter) throws Exception - { - try - { + private void check( + CuratorFramework client, + BackgroundPathAndBytesable builder, + String path, + byte[] data, + int expectedCode, + int expectedVersionAfter) + throws Exception { + try { builder.forPath(path, data); assertEquals(expectedCode, OK.intValue()); Stat stat = new Stat(); byte[] actualData = client.getData().storingStatIn(stat).forPath(path); assertTrue(IdempotentUtils.matches(expectedVersionAfter, data, stat.getVersion(), actualData)); - } - catch (KeeperException e) - { + } catch (KeeperException e) { assertEquals(expectedCode, e.getCode()); } } - private void checkBackground(CuratorFramework client, BackgroundPathAndBytesable builder, String path, byte[] data, int expectedCode, int expectedVersionAfter) throws Exception - { + private void checkBackground( + CuratorFramework client, + BackgroundPathAndBytesable builder, + String path, + byte[] data, + int expectedCode, + int expectedVersionAfter) + throws Exception { AtomicInteger actualCode = new AtomicInteger(-1); CountDownLatch latch = new CountDownLatch(1); - BackgroundCallback callback = new BackgroundCallback() - { + BackgroundCallback callback = new BackgroundCallback() { @Override - public void processResult(CuratorFramework client, CuratorEvent event) throws Exception - { + public void processResult(CuratorFramework client, CuratorEvent event) throws Exception { actualCode.set(event.getResultCode()); latch.countDown(); } @@ -167,8 +163,7 @@ public void processResult(CuratorFramework client, CuratorEvent event) throws Ex assertTrue(latch.await(5000, TimeUnit.MILLISECONDS), "Callback not invoked"); assertEquals(expectedCode, actualCode.get()); - if (expectedCode == OK.intValue()) - { + if (expectedCode == OK.intValue()) { Stat stat = new Stat(); byte[] actualData = client.getData().storingStatIn(stat).forPath(path); assertTrue(IdempotentUtils.matches(expectedVersionAfter, data, stat.getVersion(), actualData)); @@ -179,11 +174,9 @@ public void processResult(CuratorFramework client, CuratorEvent event) throws Ex * Tests all cases of idempotent set */ @Test - public void testIdempotentSet() throws Exception - { + public void testIdempotentSet() throws Exception { CuratorFramework client = createClient(); - try - { + try { client.start(); Stat stat = new Stat(); @@ -217,33 +210,30 @@ public void testIdempotentSet() throws Exception // same op with different data should fail even though version matches check(client, client.setData().idempotent().withVersion(1), path, data3, BADVERSION.intValue(), 1); - checkBackground(client, client.setData().idempotent().withVersion(1), pathBack, data3, BADVERSION.intValue(), 1); + checkBackground( + client, client.setData().idempotent().withVersion(1), pathBack, data3, BADVERSION.intValue(), 1); // same op with same data should fail even because version mismatches check(client, client.setData().idempotent().withVersion(0), path, data2, BADVERSION.intValue(), 2); - checkBackground(client, client.setData().idempotent().withVersion(0), pathBack, data2, BADVERSION.intValue(), 2); - } - finally - { + checkBackground( + client, client.setData().idempotent().withVersion(0), pathBack, data2, BADVERSION.intValue(), 2); + } finally { CloseableUtils.closeQuietly(client); } } - private SetDataBuilder clBefore(SetDataBuilder builder) - { - ((SetDataBuilderImpl)builder).failBeforeNextSetForTesting = true; + private SetDataBuilder clBefore(SetDataBuilder builder) { + ((SetDataBuilderImpl) builder).failBeforeNextSetForTesting = true; return builder; } - private SetDataBuilder clAfter(SetDataBuilder builder) - { - ((SetDataBuilderImpl)builder).failNextSetForTesting = true; + private SetDataBuilder clAfter(SetDataBuilder builder) { + ((SetDataBuilderImpl) builder).failNextSetForTesting = true; return builder; } - private SetDataBuilder clCheck(SetDataBuilder builder) - { - ((SetDataBuilderImpl)builder).failNextIdempotentCheckForTesting = true; + private SetDataBuilder clCheck(SetDataBuilder builder) { + ((SetDataBuilderImpl) builder).failNextIdempotentCheckForTesting = true; return builder; } @@ -251,8 +241,7 @@ private SetDataBuilder clCheck(SetDataBuilder builder) @Test public void testIdempotentSetConnectionLoss() throws Exception { CuratorFramework client = createClient(); - try - { + try { client.start(); String idpPath = "/idpset"; String idpPathBack = "/idpsetback"; @@ -277,56 +266,160 @@ public void testIdempotentSetConnectionLoss() throws Exception { client.create().forPath(idpPathBack, createData); // test that idempotent set succeeds with connection loss before or after first set. - // the version should only go up in all cases except CL after, without a version specified, then it should up 2 + // the version should only go up in all cases except CL after, without a version specified, then it should + // up 2 check(client, clBefore(client.setData().idempotent()).withVersion(0), idpPath, data, OK.intValue(), 1); - checkBackground(client, clBefore(client.setData().idempotent()).withVersion(0), idpPathBack, data, OK.intValue(), 1); + checkBackground( + client, + clBefore(client.setData().idempotent()).withVersion(0), + idpPathBack, + data, + OK.intValue(), + 1); check(client, clAfter(client.setData().idempotent()).withVersion(1), idpPath, data2, OK.intValue(), 2); - checkBackground(client, clAfter(client.setData().idempotent()).withVersion(1), idpPathBack, data2, OK.intValue(), 2); + checkBackground( + client, + clAfter(client.setData().idempotent()).withVersion(1), + idpPathBack, + data2, + OK.intValue(), + 2); check(client, clBefore(client.setData().idempotent()), idpPath, data3, OK.intValue(), 3); checkBackground(client, clBefore(client.setData().idempotent()), idpPathBack, data3, OK.intValue(), 3); check(client, clAfter(client.setData().idempotent()), idpPath, data4, OK.intValue(), 5); checkBackground(client, clAfter(client.setData().idempotent()), idpPathBack, data4, OK.intValue(), 5); - // test that idempotency succeeds when node is already in desired final state withVersion(4) -> (version 5, data4) + // test that idempotency succeeds when node is already in desired final state withVersion(4) -> (version 5, + // data4) check(client, clBefore(client.setData().idempotent()).withVersion(4), idpPath, data4, OK.intValue(), 5); - checkBackground(client, clBefore(client.setData().idempotent()).withVersion(4), idpPathBack, data4, OK.intValue(), 5); + checkBackground( + client, + clBefore(client.setData().idempotent()).withVersion(4), + idpPathBack, + data4, + OK.intValue(), + 5); check(client, clAfter(client.setData().idempotent()).withVersion(4), idpPath, data4, OK.intValue(), 5); - checkBackground(client, clAfter(client.setData().idempotent()).withVersion(4), idpPathBack, data4, OK.intValue(), 5); + checkBackground( + client, + clAfter(client.setData().idempotent()).withVersion(4), + idpPathBack, + data4, + OK.intValue(), + 5); check(client, clCheck(client.setData().idempotent()).withVersion(4), idpPath, data4, OK.intValue(), 5); - checkBackground(client, clCheck(client.setData().idempotent()).withVersion(4), idpPathBack, data4, OK.intValue(), 5); - - // test that idempotent set fails correctly when withVersion is set, before or after connectionloss, if data or version does not match + checkBackground( + client, + clCheck(client.setData().idempotent()).withVersion(4), + idpPathBack, + data4, + OK.intValue(), + 5); + + // test that idempotent set fails correctly when withVersion is set, before or after connectionloss, if data + // or version does not match // version is wrong (0, would have to be 4) but data is right (data4) - check(client, clBefore(client.setData().idempotent()).withVersion(0), idpPath, data4, BADVERSION.intValue(), -1); - checkBackground(client, clBefore(client.setData().idempotent()).withVersion(0), idpPathBack, data4, BADVERSION.intValue(), -1); - check(client, clAfter(client.setData().idempotent()).withVersion(0), idpPath, data4, BADVERSION.intValue(), -1); - checkBackground(client, clAfter(client.setData().idempotent()).withVersion(0), idpPathBack, data4, BADVERSION.intValue(), -1); - check(client, clCheck(client.setData().idempotent()).withVersion(0), idpPath, data4, BADVERSION.intValue(), -1); - checkBackground(client, clCheck(client.setData().idempotent()).withVersion(0), idpPathBack, data4, BADVERSION.intValue(), -1); + check( + client, + clBefore(client.setData().idempotent()).withVersion(0), + idpPath, + data4, + BADVERSION.intValue(), + -1); + checkBackground( + client, + clBefore(client.setData().idempotent()).withVersion(0), + idpPathBack, + data4, + BADVERSION.intValue(), + -1); + check( + client, + clAfter(client.setData().idempotent()).withVersion(0), + idpPath, + data4, + BADVERSION.intValue(), + -1); + checkBackground( + client, + clAfter(client.setData().idempotent()).withVersion(0), + idpPathBack, + data4, + BADVERSION.intValue(), + -1); + check( + client, + clCheck(client.setData().idempotent()).withVersion(0), + idpPath, + data4, + BADVERSION.intValue(), + -1); + checkBackground( + client, + clCheck(client.setData().idempotent()).withVersion(0), + idpPathBack, + data4, + BADVERSION.intValue(), + -1); // version is right (4) but data is wrong (data, would have to be data4) - check(client, clBefore(client.setData().idempotent()).withVersion(4), idpPath, data, BADVERSION.intValue(), -1); - checkBackground(client, clBefore(client.setData().idempotent()).withVersion(4), idpPathBack, data, BADVERSION.intValue(), -1); - check(client, clAfter(client.setData().idempotent()).withVersion(4), idpPath, data, BADVERSION.intValue(), -1); - checkBackground(client, clAfter(client.setData().idempotent()).withVersion(4), idpPathBack, data, BADVERSION.intValue(), -1); - check(client, clCheck(client.setData().idempotent()).withVersion(4), idpPath, data, BADVERSION.intValue(), -1); - checkBackground(client, clCheck(client.setData().idempotent()).withVersion(4), idpPathBack, data, BADVERSION.intValue(), -1); - - - // test that non-idempotent set withVersion succeeds when retrying with connectionloss before, but fails with connectionloss after + check( + client, + clBefore(client.setData().idempotent()).withVersion(4), + idpPath, + data, + BADVERSION.intValue(), + -1); + checkBackground( + client, + clBefore(client.setData().idempotent()).withVersion(4), + idpPathBack, + data, + BADVERSION.intValue(), + -1); + check( + client, + clAfter(client.setData().idempotent()).withVersion(4), + idpPath, + data, + BADVERSION.intValue(), + -1); + checkBackground( + client, + clAfter(client.setData().idempotent()).withVersion(4), + idpPathBack, + data, + BADVERSION.intValue(), + -1); + check( + client, + clCheck(client.setData().idempotent()).withVersion(4), + idpPath, + data, + BADVERSION.intValue(), + -1); + checkBackground( + client, + clCheck(client.setData().idempotent()).withVersion(4), + idpPathBack, + data, + BADVERSION.intValue(), + -1); + + // test that non-idempotent set withVersion succeeds when retrying with connectionloss before, but fails + // with connectionloss after client.create().forPath(path, createData); client.create().forPath(pathBack, createData); check(client, clBefore(client.setData()).withVersion(0), path, data, OK.intValue(), 1); checkBackground(client, clBefore(client.setData()).withVersion(0), pathBack, data, OK.intValue(), 1); check(client, clAfter(client.setData()).withVersion(1), path, data2, BADVERSION.intValue(), -1); - checkBackground(client, clAfter(client.setData()).withVersion(1), pathBack, data2, BADVERSION.intValue(), -1); + checkBackground( + client, clAfter(client.setData()).withVersion(1), pathBack, data2, BADVERSION.intValue(), -1); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } diff --git a/curator-framework/src/test/java/org/apache/curator/framework/imps/TestTempFramework.java b/curator-framework/src/test/java/org/apache/curator/framework/imps/TestTempFramework.java index 717c2d2f6..d565f676d 100644 --- a/curator-framework/src/test/java/org/apache/curator/framework/imps/TestTempFramework.java +++ b/curator-framework/src/test/java/org/apache/curator/framework/imps/TestTempFramework.java @@ -21,62 +21,63 @@ import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertNull; - -import org.apache.curator.test.BaseClassForTests; -import org.apache.curator.utils.CloseableUtils; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.CuratorTempFramework; import org.apache.curator.retry.RetryOneTime; +import org.apache.curator.test.BaseClassForTests; +import org.apache.curator.utils.CloseableUtils; import org.junit.jupiter.api.Test; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.TimeUnit; - -public class TestTempFramework extends BaseClassForTests -{ +public class TestTempFramework extends BaseClassForTests { @Test - public void testBasic() throws Exception - { - CuratorTempFramework client = CuratorFrameworkFactory.builder().connectString(server.getConnectString()).retryPolicy(new RetryOneTime(1)).buildTemp(); - try - { - client.inTransaction().create().forPath("/foo", "data".getBytes()).and().commit(); + public void testBasic() throws Exception { + CuratorTempFramework client = CuratorFrameworkFactory.builder() + .connectString(server.getConnectString()) + .retryPolicy(new RetryOneTime(1)) + .buildTemp(); + try { + client.inTransaction() + .create() + .forPath("/foo", "data".getBytes()) + .and() + .commit(); byte[] bytes = client.getData().forPath("/foo"); assertArrayEquals(bytes, "data".getBytes()); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } @Test - public void testInactivity() throws Exception - { - final CuratorTempFrameworkImpl client = (CuratorTempFrameworkImpl)CuratorFrameworkFactory.builder().connectString(server.getConnectString()).retryPolicy(new RetryOneTime(1)).buildTemp(1, TimeUnit.SECONDS); - try - { - ScheduledExecutorService service = Executors.newScheduledThreadPool(1); - Runnable command = new Runnable() - { + public void testInactivity() throws Exception { + final CuratorTempFrameworkImpl client = (CuratorTempFrameworkImpl) CuratorFrameworkFactory.builder() + .connectString(server.getConnectString()) + .retryPolicy(new RetryOneTime(1)) + .buildTemp(1, TimeUnit.SECONDS); + try { + ScheduledExecutorService service = Executors.newScheduledThreadPool(1); + Runnable command = new Runnable() { @Override - public void run() - { + public void run() { client.updateLastAccess(); } }; service.scheduleAtFixedRate(command, 10, 10, TimeUnit.MILLISECONDS); - client.inTransaction().create().forPath("/foo", "data".getBytes()).and().commit(); + client.inTransaction() + .create() + .forPath("/foo", "data".getBytes()) + .and() + .commit(); service.shutdownNow(); Thread.sleep(2000); assertNull(client.getCleanup()); assertNull(client.getClient()); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } diff --git a/curator-framework/src/test/java/org/apache/curator/framework/imps/TestTransactionsNew.java b/curator-framework/src/test/java/org/apache/curator/framework/imps/TestTransactionsNew.java index 02b7c729d..c10e0f46e 100644 --- a/curator-framework/src/test/java/org/apache/curator/framework/imps/TestTransactionsNew.java +++ b/curator-framework/src/test/java/org/apache/curator/framework/imps/TestTransactionsNew.java @@ -29,6 +29,11 @@ import static org.junit.jupiter.api.Assertions.fail; import com.google.common.collect.Iterables; import com.google.common.collect.Queues; +import java.util.Collection; +import java.util.List; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.TimeUnit; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.api.BackgroundCallback; @@ -45,29 +50,18 @@ import org.apache.zookeeper.data.Stat; import org.junit.jupiter.api.Test; -import java.util.Collection; -import java.util.List; -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.LinkedBlockingQueue; -import java.util.concurrent.TimeUnit; - -public class TestTransactionsNew extends BaseClassForTests -{ +public class TestTransactionsNew extends BaseClassForTests { @Test - public void testErrors() throws Exception - { + public void testErrors() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); - try - { + try { client.start(); CuratorOp createOp1 = client.transactionOp().create().forPath("/bar"); CuratorOp createOp2 = client.transactionOp().create().forPath("/z/blue"); final BlockingQueue callbackQueue = new LinkedBlockingQueue<>(); - BackgroundCallback callback = new BackgroundCallback() - { + BackgroundCallback callback = new BackgroundCallback() { @Override - public void processResult(CuratorFramework client, CuratorEvent event) throws Exception - { + public void processResult(CuratorFramework client, CuratorEvent event) throws Exception { callbackQueue.add(event); } }; @@ -78,80 +72,77 @@ public void processResult(CuratorFramework client, CuratorEvent event) throws Ex assertEquals(event.getOpResults().size(), 2); assertEquals(event.getOpResults().get(0).getError(), KeeperException.Code.OK.intValue()); assertEquals(event.getOpResults().get(1).getError(), KeeperException.Code.NONODE.intValue()); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } @Test - public void testCheckVersion() throws Exception - { + public void testCheckVersion() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); - try - { + try { client.start(); client.create().forPath("/foo"); - Stat stat = client.setData().forPath("/foo", "new".getBytes()); // up the version + Stat stat = client.setData().forPath("/foo", "new".getBytes()); // up the version - CuratorOp statOp = client.transactionOp().check().withVersion(stat.getVersion() + 1).forPath("/foo"); + CuratorOp statOp = client.transactionOp() + .check() + .withVersion(stat.getVersion() + 1) + .forPath("/foo"); CuratorOp createOp = client.transactionOp().create().forPath("/bar"); - try - { + try { client.transaction().forOperations(statOp, createOp); fail(); - } - catch ( KeeperException.BadVersionException correct ) - { + } catch (KeeperException.BadVersionException correct) { // correct } assertNull(client.checkExists().forPath("/bar")); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } @Test - public void testWithNamespace() throws Exception - { - CuratorFramework client = CuratorFrameworkFactory.builder().connectString(server.getConnectString()).retryPolicy(new RetryOneTime(1)).namespace("galt").build(); - try - { + public void testWithNamespace() throws Exception { + CuratorFramework client = CuratorFrameworkFactory.builder() + .connectString(server.getConnectString()) + .retryPolicy(new RetryOneTime(1)) + .namespace("galt") + .build(); + try { client.start(); CuratorOp createOp1 = client.transactionOp().create().forPath("/foo", "one".getBytes()); - CuratorOp createOp2 = client.transactionOp().create().withMode(CreateMode.PERSISTENT_SEQUENTIAL).forPath("/test-", "one".getBytes()); + CuratorOp createOp2 = client.transactionOp() + .create() + .withMode(CreateMode.PERSISTENT_SEQUENTIAL) + .forPath("/test-", "one".getBytes()); CuratorOp setDataOp = client.transactionOp().setData().forPath("/foo", "two".getBytes()); CuratorOp createOp3 = client.transactionOp().create().forPath("/foo/bar"); CuratorOp deleteOp = client.transactionOp().delete().forPath("/foo/bar"); - Collection results = client.transaction().forOperations(createOp1, createOp2, setDataOp, createOp3, deleteOp); + Collection results = + client.transaction().forOperations(createOp1, createOp2, setDataOp, createOp3, deleteOp); assertTrue(client.checkExists().forPath("/foo") != null); assertTrue(client.usingNamespace(null).checkExists().forPath("/galt/foo") != null); assertArrayEquals(client.getData().forPath("/foo"), "two".getBytes()); assertTrue(client.checkExists().forPath("/foo/bar") == null); - CuratorTransactionResult ephemeralResult = Iterables.find(results, CuratorTransactionResult.ofTypeAndPath(OperationType.CREATE, "/test-")); + CuratorTransactionResult ephemeralResult = + Iterables.find(results, CuratorTransactionResult.ofTypeAndPath(OperationType.CREATE, "/test-")); assertNotNull(ephemeralResult); assertNotEquals(ephemeralResult.getResultPath(), "/test-"); assertTrue(ephemeralResult.getResultPath().startsWith("/test-")); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } @Test - public void testBasic() throws Exception - { + public void testBasic() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); - try - { + try { client.start(); CuratorOp createOp1 = client.transactionOp().create().forPath("/foo"); CuratorOp createOp2 = client.transactionOp().create().forPath("/foo/bar", "snafu".getBytes()); @@ -161,36 +152,32 @@ public void testBasic() throws Exception assertTrue(client.checkExists().forPath("/foo/bar") != null); assertArrayEquals(client.getData().forPath("/foo/bar"), "snafu".getBytes()); - CuratorTransactionResult fooResult = Iterables.find(results, CuratorTransactionResult.ofTypeAndPath(OperationType.CREATE, "/foo")); - CuratorTransactionResult fooBarResult = Iterables.find(results, CuratorTransactionResult.ofTypeAndPath(OperationType.CREATE, "/foo/bar")); + CuratorTransactionResult fooResult = + Iterables.find(results, CuratorTransactionResult.ofTypeAndPath(OperationType.CREATE, "/foo")); + CuratorTransactionResult fooBarResult = + Iterables.find(results, CuratorTransactionResult.ofTypeAndPath(OperationType.CREATE, "/foo/bar")); assertNotNull(fooResult); assertNotNull(fooBarResult); assertNotSame(fooResult, fooBarResult); assertEquals(fooResult.getResultPath(), "/foo"); assertEquals(fooBarResult.getResultPath(), "/foo/bar"); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } @Test - public void testBackground() throws Exception - { + public void testBackground() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); - try - { + try { client.start(); CuratorOp createOp1 = client.transactionOp().create().forPath("/foo"); CuratorOp createOp2 = client.transactionOp().create().forPath("/foo/bar", "snafu".getBytes()); final BlockingQueue> queue = Queues.newLinkedBlockingQueue(); - BackgroundCallback callback = new BackgroundCallback() - { + BackgroundCallback callback = new BackgroundCallback() { @Override - public void processResult(CuratorFramework client, CuratorEvent event) throws Exception - { + public void processResult(CuratorFramework client, CuratorEvent event) throws Exception { queue.add(event.getOpResults()); } }; @@ -201,43 +188,48 @@ public void processResult(CuratorFramework client, CuratorEvent event) throws Ex assertTrue(client.checkExists().forPath("/foo/bar") != null); assertArrayEquals(client.getData().forPath("/foo/bar"), "snafu".getBytes()); - CuratorTransactionResult fooResult = Iterables.find(results, CuratorTransactionResult.ofTypeAndPath(OperationType.CREATE, "/foo")); - CuratorTransactionResult fooBarResult = Iterables.find(results, CuratorTransactionResult.ofTypeAndPath(OperationType.CREATE, "/foo/bar")); + CuratorTransactionResult fooResult = + Iterables.find(results, CuratorTransactionResult.ofTypeAndPath(OperationType.CREATE, "/foo")); + CuratorTransactionResult fooBarResult = + Iterables.find(results, CuratorTransactionResult.ofTypeAndPath(OperationType.CREATE, "/foo/bar")); assertNotNull(fooResult); assertNotNull(fooBarResult); assertNotSame(fooResult, fooBarResult); assertEquals(fooResult.getResultPath(), "/foo"); assertEquals(fooBarResult.getResultPath(), "/foo/bar"); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } @Test - public void testBackgroundWithNamespace() throws Exception - { - CuratorFramework client = CuratorFrameworkFactory.builder().connectString(server.getConnectString()).retryPolicy(new RetryOneTime(1)).namespace("galt").build(); - try - { + public void testBackgroundWithNamespace() throws Exception { + CuratorFramework client = CuratorFrameworkFactory.builder() + .connectString(server.getConnectString()) + .retryPolicy(new RetryOneTime(1)) + .namespace("galt") + .build(); + try { client.start(); CuratorOp createOp1 = client.transactionOp().create().forPath("/foo", "one".getBytes()); - CuratorOp createOp2 = client.transactionOp().create().withMode(CreateMode.PERSISTENT_SEQUENTIAL).forPath("/test-", "one".getBytes()); + CuratorOp createOp2 = client.transactionOp() + .create() + .withMode(CreateMode.PERSISTENT_SEQUENTIAL) + .forPath("/test-", "one".getBytes()); CuratorOp setDataOp = client.transactionOp().setData().forPath("/foo", "two".getBytes()); CuratorOp createOp3 = client.transactionOp().create().forPath("/foo/bar"); CuratorOp deleteOp = client.transactionOp().delete().forPath("/foo/bar"); final BlockingQueue> queue = Queues.newLinkedBlockingQueue(); - BackgroundCallback callback = new BackgroundCallback() - { + BackgroundCallback callback = new BackgroundCallback() { @Override - public void processResult(CuratorFramework client, CuratorEvent event) throws Exception - { + public void processResult(CuratorFramework client, CuratorEvent event) throws Exception { queue.add(event.getOpResults()); } }; - client.transaction().inBackground(callback).forOperations(createOp1, createOp2, setDataOp, createOp3, deleteOp); + client.transaction() + .inBackground(callback) + .forOperations(createOp1, createOp2, setDataOp, createOp3, deleteOp); Collection results = queue.poll(5, TimeUnit.SECONDS); @@ -247,13 +239,12 @@ public void processResult(CuratorFramework client, CuratorEvent event) throws Ex assertArrayEquals(client.getData().forPath("/foo"), "two".getBytes()); assertTrue(client.checkExists().forPath("/foo/bar") == null); - CuratorTransactionResult ephemeralResult = Iterables.find(results, CuratorTransactionResult.ofTypeAndPath(OperationType.CREATE, "/test-")); + CuratorTransactionResult ephemeralResult = + Iterables.find(results, CuratorTransactionResult.ofTypeAndPath(OperationType.CREATE, "/test-")); assertNotNull(ephemeralResult); assertNotEquals(ephemeralResult.getResultPath(), "/test-"); assertTrue(ephemeralResult.getResultPath().startsWith("/test-")); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } diff --git a/curator-framework/src/test/java/org/apache/curator/framework/imps/TestTransactionsOld.java b/curator-framework/src/test/java/org/apache/curator/framework/imps/TestTransactionsOld.java index d157d28ab..9d2a7fa53 100644 --- a/curator-framework/src/test/java/org/apache/curator/framework/imps/TestTransactionsOld.java +++ b/curator-framework/src/test/java/org/apache/curator/framework/imps/TestTransactionsOld.java @@ -28,6 +28,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; import com.google.common.collect.Iterables; +import java.util.Collection; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.api.transaction.CuratorTransactionResult; @@ -41,64 +42,64 @@ import org.apache.zookeeper.data.Stat; import org.junit.jupiter.api.Test; -import java.util.Collection; - @SuppressWarnings("deprecation") -public class TestTransactionsOld extends BaseClassForTests -{ +public class TestTransactionsOld extends BaseClassForTests { @Test - public void testCheckVersion() throws Exception - { - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); - try - { + public void testCheckVersion() throws Exception { + CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); + try { client.start(); client.create().forPath("/foo"); - Stat stat = client.setData().forPath("/foo", "new".getBytes()); // up the version + Stat stat = client.setData().forPath("/foo", "new".getBytes()); // up the version - try - { + try { client.inTransaction() - .check().withVersion(stat.getVersion() + 1).forPath("/foo") // force a bad version - .and() - .create().forPath("/bar") - .and() - .commit(); + .check() + .withVersion(stat.getVersion() + 1) + .forPath("/foo") // force a bad version + .and() + .create() + .forPath("/bar") + .and() + .commit(); fail(); - } - catch ( KeeperException.BadVersionException correct ) - { + } catch (KeeperException.BadVersionException correct) { // correct } assertNull(client.checkExists().forPath("/bar")); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } @Test - public void testWithNamespace() throws Exception - { - CuratorFramework client = CuratorFrameworkFactory.builder().connectString(server.getConnectString()).retryPolicy(new RetryOneTime(1)).namespace("galt").build(); - try - { + public void testWithNamespace() throws Exception { + CuratorFramework client = CuratorFrameworkFactory.builder() + .connectString(server.getConnectString()) + .retryPolicy(new RetryOneTime(1)) + .namespace("galt") + .build(); + try { client.start(); - Collection results = - client.inTransaction() - .create().forPath("/foo", "one".getBytes()) - .and() - .create().withMode(CreateMode.PERSISTENT_SEQUENTIAL).forPath("/test-", "one".getBytes()) - .and() - .setData().forPath("/foo", "two".getBytes()) - .and() - .create().forPath("/foo/bar") - .and() - .delete().forPath("/foo/bar") - .and() + Collection results = client.inTransaction() + .create() + .forPath("/foo", "one".getBytes()) + .and() + .create() + .withMode(CreateMode.PERSISTENT_SEQUENTIAL) + .forPath("/test-", "one".getBytes()) + .and() + .setData() + .forPath("/foo", "two".getBytes()) + .and() + .create() + .forPath("/foo/bar") + .and() + .delete() + .forPath("/foo/bar") + .and() .commit(); assertTrue(client.checkExists().forPath("/foo") != null); @@ -106,37 +107,52 @@ public void testWithNamespace() throws Exception assertArrayEquals(client.getData().forPath("/foo"), "two".getBytes()); assertTrue(client.checkExists().forPath("/foo/bar") == null); - CuratorTransactionResult ephemeralResult = Iterables.find(results, CuratorTransactionResult.ofTypeAndPath(OperationType.CREATE, "/test-")); + CuratorTransactionResult ephemeralResult = + Iterables.find(results, CuratorTransactionResult.ofTypeAndPath(OperationType.CREATE, "/test-")); assertNotNull(ephemeralResult); assertNotEquals(ephemeralResult.getResultPath(), "/test-"); assertTrue(ephemeralResult.getResultPath().startsWith("/test-")); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } @Test - public void testWithCompression() throws Exception - { - CuratorFramework client = CuratorFrameworkFactory.builder().connectString(server.getConnectString()).retryPolicy(new RetryOneTime(1)).namespace("galt").build(); + public void testWithCompression() throws Exception { + CuratorFramework client = CuratorFrameworkFactory.builder() + .connectString(server.getConnectString()) + .retryPolicy(new RetryOneTime(1)) + .namespace("galt") + .build(); client.start(); - try - { - Collection results = - client.inTransaction() - .create().compressed().forPath("/foo", "one".getBytes()) + try { + Collection results = client.inTransaction() + .create() + .compressed() + .forPath("/foo", "one".getBytes()) .and() - .create().compressed().withACL(ZooDefs.Ids.READ_ACL_UNSAFE).forPath("/bar", "two".getBytes()) + .create() + .compressed() + .withACL(ZooDefs.Ids.READ_ACL_UNSAFE) + .forPath("/bar", "two".getBytes()) .and() - .create().compressed().withMode(CreateMode.PERSISTENT_SEQUENTIAL).forPath("/test-", "three".getBytes()) + .create() + .compressed() + .withMode(CreateMode.PERSISTENT_SEQUENTIAL) + .forPath("/test-", "three".getBytes()) .and() - .create().compressed().withMode(CreateMode.PERSISTENT).withACL(ZooDefs.Ids.READ_ACL_UNSAFE).forPath("/baz", "four".getBytes()) + .create() + .compressed() + .withMode(CreateMode.PERSISTENT) + .withACL(ZooDefs.Ids.READ_ACL_UNSAFE) + .forPath("/baz", "four".getBytes()) .and() - .setData().compressed().withVersion(0).forPath("/foo", "five".getBytes()) + .setData() + .compressed() + .withVersion(0) + .forPath("/foo", "five".getBytes()) .and() - .commit(); + .commit(); assertTrue(client.checkExists().forPath("/foo") != null); assertArrayEquals(client.getData().decompressed().forPath("/foo"), "five".getBytes()); @@ -145,7 +161,8 @@ public void testWithCompression() throws Exception assertArrayEquals(client.getData().decompressed().forPath("/bar"), "two".getBytes()); assertEquals(client.getACL().forPath("/bar"), ZooDefs.Ids.READ_ACL_UNSAFE); - CuratorTransactionResult ephemeralResult = Iterables.find(results, CuratorTransactionResult.ofTypeAndPath(OperationType.CREATE, "/test-")); + CuratorTransactionResult ephemeralResult = + Iterables.find(results, CuratorTransactionResult.ofTypeAndPath(OperationType.CREATE, "/test-")); assertNotNull(ephemeralResult); assertNotEquals(ephemeralResult.getResultPath(), "/test-"); assertTrue(ephemeralResult.getResultPath().startsWith("/test-")); @@ -153,41 +170,38 @@ public void testWithCompression() throws Exception assertTrue(client.checkExists().forPath("/baz") != null); assertArrayEquals(client.getData().decompressed().forPath("/baz"), "four".getBytes()); assertEquals(client.getACL().forPath("/baz"), ZooDefs.Ids.READ_ACL_UNSAFE); - } - finally - { + } finally { client.close(); } } @Test - public void testBasic() throws Exception - { - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); - try - { + public void testBasic() throws Exception { + CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); + try { client.start(); - Collection results = - client.inTransaction() - .create().forPath("/foo") - .and() - .create().forPath("/foo/bar", "snafu".getBytes()) - .and() + Collection results = client.inTransaction() + .create() + .forPath("/foo") + .and() + .create() + .forPath("/foo/bar", "snafu".getBytes()) + .and() .commit(); assertTrue(client.checkExists().forPath("/foo/bar") != null); assertArrayEquals(client.getData().forPath("/foo/bar"), "snafu".getBytes()); - CuratorTransactionResult fooResult = Iterables.find(results, CuratorTransactionResult.ofTypeAndPath(OperationType.CREATE, "/foo")); - CuratorTransactionResult fooBarResult = Iterables.find(results, CuratorTransactionResult.ofTypeAndPath(OperationType.CREATE, "/foo/bar")); + CuratorTransactionResult fooResult = + Iterables.find(results, CuratorTransactionResult.ofTypeAndPath(OperationType.CREATE, "/foo")); + CuratorTransactionResult fooBarResult = + Iterables.find(results, CuratorTransactionResult.ofTypeAndPath(OperationType.CREATE, "/foo/bar")); assertNotNull(fooResult); assertNotNull(fooBarResult); assertNotSame(fooResult, fooBarResult); assertEquals(fooResult.getResultPath(), "/foo"); assertEquals(fooBarResult.getResultPath(), "/foo/bar"); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } diff --git a/curator-framework/src/test/java/org/apache/curator/framework/imps/TestTtlNodes.java b/curator-framework/src/test/java/org/apache/curator/framework/imps/TestTtlNodes.java index c4c82dbf9..a946d0217 100644 --- a/curator-framework/src/test/java/org/apache/curator/framework/imps/TestTtlNodes.java +++ b/curator-framework/src/test/java/org/apache/curator/framework/imps/TestTtlNodes.java @@ -21,75 +21,75 @@ import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; - +import java.util.concurrent.CountDownLatch; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.api.BackgroundCallback; import org.apache.curator.framework.api.CuratorEvent; import org.apache.curator.retry.RetryOneTime; -import org.apache.curator.test.compatibility.CuratorTestBase; import org.apache.curator.test.Timing; +import org.apache.curator.test.compatibility.CuratorTestBase; import org.apache.zookeeper.CreateMode; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import java.util.concurrent.CountDownLatch; - -public class TestTtlNodes extends CuratorTestBase -{ +public class TestTtlNodes extends CuratorTestBase { @BeforeAll public static void setUpClass() { System.setProperty("zookeeper.extendedTypesEnabled", "true"); } - + @BeforeEach @Override - public void setup() throws Exception - { + public void setup() throws Exception { System.setProperty("znode.container.checkIntervalMs", "1"); super.setup(); } @AfterEach @Override - public void teardown() throws Exception - { + public void teardown() throws Exception { super.teardown(); System.clearProperty("znode.container.checkIntervalMs"); } @Test - public void testBasic() throws Exception - { - try ( CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)) ) - { + public void testBasic() throws Exception { + try (CuratorFramework client = + CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1))) { client.start(); - client.create().withTtl(10).creatingParentsIfNeeded().withMode(CreateMode.PERSISTENT_WITH_TTL).forPath("/a/b/c"); + client.create() + .withTtl(10) + .creatingParentsIfNeeded() + .withMode(CreateMode.PERSISTENT_WITH_TTL) + .forPath("/a/b/c"); Thread.sleep(20); assertNull(client.checkExists().forPath("/a/b/c")); } } @Test - public void testBasicInBackground() throws Exception - { - try ( CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)) ) - { + public void testBasicInBackground() throws Exception { + try (CuratorFramework client = + CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1))) { client.start(); final CountDownLatch latch = new CountDownLatch(1); - BackgroundCallback callback = new BackgroundCallback() - { + BackgroundCallback callback = new BackgroundCallback() { @Override - public void processResult(CuratorFramework client, CuratorEvent event) throws Exception - { + public void processResult(CuratorFramework client, CuratorEvent event) throws Exception { latch.countDown(); } }; - client.create().withTtl(10).creatingParentsIfNeeded().withMode(CreateMode.PERSISTENT_WITH_TTL).inBackground(callback).forPath("/a/b/c"); + client.create() + .withTtl(10) + .creatingParentsIfNeeded() + .withMode(CreateMode.PERSISTENT_WITH_TTL) + .inBackground(callback) + .forPath("/a/b/c"); assertTrue(new Timing().awaitLatch(latch)); Thread.sleep(20); assertNull(client.checkExists().forPath("/a/b/c")); diff --git a/curator-framework/src/test/java/org/apache/curator/framework/imps/TestWatcherIdentity.java b/curator-framework/src/test/java/org/apache/curator/framework/imps/TestWatcherIdentity.java index 22f843c28..382b96b9d 100644 --- a/curator-framework/src/test/java/org/apache/curator/framework/imps/TestWatcherIdentity.java +++ b/curator-framework/src/test/java/org/apache/curator/framework/imps/TestWatcherIdentity.java @@ -19,7 +19,13 @@ package org.apache.curator.framework.imps; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; import com.google.common.collect.Sets; +import java.util.Set; +import java.util.concurrent.atomic.AtomicInteger; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.api.CuratorWatcher; @@ -33,153 +39,130 @@ import org.junit.jupiter.api.Test; import org.mockito.Mockito; -import java.util.Set; -import java.util.concurrent.atomic.AtomicInteger; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.mock; +public class TestWatcherIdentity extends BaseClassForTests { + private static final String PATH = "/foo"; + private static final int TIMEOUT_MS = 100000; -public class TestWatcherIdentity extends BaseClassForTests -{ - private static final String PATH = "/foo"; - private static final int TIMEOUT_MS = 100000; + private static class CountZKWatcher implements Watcher { + private final AtomicInteger count = new AtomicInteger(0); - private static class CountZKWatcher implements Watcher - { - private final AtomicInteger count = new AtomicInteger(0); + @Override + public void process(WatchedEvent event) { + count.incrementAndGet(); + } + } - @Override - public void process(WatchedEvent event) - { - count.incrementAndGet(); + @Test + public void testSameWatcherPerZKDocs() throws Exception { + CountZKWatcher actualWatcher = new CountZKWatcher(); + Timing timing = new Timing(); + CuratorFramework client = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); + try { + client.start(); + client.create().forPath("/test"); + + // per ZK docs, this watcher should only trigger once + client.checkExists().usingWatcher(actualWatcher).forPath("/test"); + client.getData().usingWatcher(actualWatcher).forPath("/test"); + + client.setData().forPath("/test", "foo".getBytes()); + client.delete().forPath("/test"); + Awaitility.await().untilAsserted(() -> assertEquals(1, actualWatcher.count.getAndSet(0))); + + client.create().forPath("/test"); + client.checkExists().usingWatcher(actualWatcher).forPath("/test"); + client.delete().forPath("/test"); + Awaitility.await().untilAsserted(() -> assertEquals(1, actualWatcher.count.get())); + } finally { + CloseableUtils.closeQuietly(client); + } } - } - - @Test - public void testSameWatcherPerZKDocs() throws Exception - { - CountZKWatcher actualWatcher = new CountZKWatcher(); - Timing timing = new Timing(); - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), - timing.connection(), new RetryOneTime(1)); - try { - client.start(); - client.create().forPath("/test"); - - // per ZK docs, this watcher should only trigger once - client.checkExists().usingWatcher(actualWatcher).forPath("/test"); - client.getData().usingWatcher(actualWatcher).forPath("/test"); - - client.setData().forPath("/test", "foo".getBytes()); - client.delete().forPath("/test"); - Awaitility.await() - .untilAsserted(() -> assertEquals(1, actualWatcher.count.getAndSet(0))); - - client.create().forPath("/test"); - client.checkExists().usingWatcher(actualWatcher).forPath("/test"); - client.delete().forPath("/test"); - Awaitility.await() - .untilAsserted(() -> assertEquals(1, actualWatcher.count.get())); - } finally { - CloseableUtils.closeQuietly(client); + + @Test + public void testSameCuratorWatcherPerZKDocs() throws Exception { + // Construct mock object + CuratorWatcher actualWatcher = mock(CuratorWatcher.class); + + Timing timing = new Timing(); + CuratorFramework client = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); + try { + client.start(); + client.create().forPath("/test"); + + // per ZK docs, this watcher should only trigger once + client.checkExists().usingWatcher(actualWatcher).forPath("/test"); + client.getData().usingWatcher(actualWatcher).forPath("/test"); + + client.setData().forPath("/test", "foo".getBytes()); + client.delete().forPath("/test"); + Mockito.verify(actualWatcher, Mockito.timeout(TIMEOUT_MS).times(1)).process(any(WatchedEvent.class)); + + client.create().forPath("/test"); + client.checkExists().usingWatcher(actualWatcher).forPath("/test"); + client.delete().forPath("/test"); + Mockito.verify(actualWatcher, Mockito.timeout(TIMEOUT_MS).times(2)).process(any(WatchedEvent.class)); + } finally { + CloseableUtils.closeQuietly(client); + } } - } - - @Test - public void testSameCuratorWatcherPerZKDocs() throws Exception - { - // Construct mock object - CuratorWatcher actualWatcher = mock(CuratorWatcher.class); - - Timing timing = new Timing(); - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), - timing.connection(), new RetryOneTime(1)); - try { - client.start(); - client.create().forPath("/test"); - - // per ZK docs, this watcher should only trigger once - client.checkExists().usingWatcher(actualWatcher).forPath("/test"); - client.getData().usingWatcher(actualWatcher).forPath("/test"); - - client.setData().forPath("/test", "foo".getBytes()); - client.delete().forPath("/test"); - Mockito.verify(actualWatcher, Mockito.timeout(TIMEOUT_MS).times(1)).process(any(WatchedEvent.class)); - - client.create().forPath("/test"); - client.checkExists().usingWatcher(actualWatcher).forPath("/test"); - client.delete().forPath("/test"); - Mockito.verify(actualWatcher, Mockito.timeout(TIMEOUT_MS).times(2)).process(any(WatchedEvent.class)); - } finally { - CloseableUtils.closeQuietly(client); + + @Test + public void testSetAddition() { + Watcher watcher = new Watcher() { + @Override + public void process(WatchedEvent event) {} + }; + NamespaceWatcher namespaceWatcher1 = new NamespaceWatcher(null, watcher, "/foo"); + NamespaceWatcher namespaceWatcher2 = new NamespaceWatcher(null, watcher, "/foo"); + assertEquals(namespaceWatcher1, namespaceWatcher2); + assertFalse(namespaceWatcher1.equals(watcher)); + assertFalse(watcher.equals(namespaceWatcher1)); + Set set = Sets.newHashSet(); + set.add(namespaceWatcher1); + set.add(namespaceWatcher2); + assertEquals(set.size(), 1); } - } - - @Test - public void testSetAddition() - { - Watcher watcher = new Watcher() - { - @Override - public void process(WatchedEvent event) - { - - } - }; - NamespaceWatcher namespaceWatcher1 = new NamespaceWatcher(null, watcher, "/foo"); - NamespaceWatcher namespaceWatcher2 = new NamespaceWatcher(null, watcher, "/foo"); - assertEquals(namespaceWatcher1, namespaceWatcher2); - assertFalse(namespaceWatcher1.equals(watcher)); - assertFalse(watcher.equals(namespaceWatcher1)); - Set set = Sets.newHashSet(); - set.add(namespaceWatcher1); - set.add(namespaceWatcher2); - assertEquals(set.size(), 1); - } - - @Test - public void testCuratorWatcher() throws Exception - { - Timing timing = new Timing(); - // Construct mock object - CuratorWatcher watcher = mock(CuratorWatcher.class); - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), - timing.connection(), new RetryOneTime(1)); - try { - client.start(); - client.create().forPath(PATH); - // Add twice the same watcher on the same path - client.getData().usingWatcher(watcher).forPath(PATH); - client.getData().usingWatcher(watcher).forPath(PATH); - // Ok, let's test it - client.setData().forPath(PATH, new byte[] {}); - Mockito.verify(watcher, Mockito.timeout(TIMEOUT_MS).times(1)).process(any(WatchedEvent.class)); - } finally { - CloseableUtils.closeQuietly(client); + + @Test + public void testCuratorWatcher() throws Exception { + Timing timing = new Timing(); + // Construct mock object + CuratorWatcher watcher = mock(CuratorWatcher.class); + CuratorFramework client = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); + try { + client.start(); + client.create().forPath(PATH); + // Add twice the same watcher on the same path + client.getData().usingWatcher(watcher).forPath(PATH); + client.getData().usingWatcher(watcher).forPath(PATH); + // Ok, let's test it + client.setData().forPath(PATH, new byte[] {}); + Mockito.verify(watcher, Mockito.timeout(TIMEOUT_MS).times(1)).process(any(WatchedEvent.class)); + } finally { + CloseableUtils.closeQuietly(client); + } } - } - - @Test - public void testZKWatcher() throws Exception - { - Timing timing = new Timing(); - CountZKWatcher watcher = new CountZKWatcher(); - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), - timing.connection(), new RetryOneTime(1)); - try { - client.start(); - client.create().forPath(PATH); - // Add twice the same watcher on the same path - client.getData().usingWatcher(watcher).forPath(PATH); - client.getData().usingWatcher(watcher).forPath(PATH); - // Ok, let's test it - client.setData().forPath(PATH, new byte[] {}); - Awaitility.await() - .untilAsserted(() -> assertEquals(1, watcher.count.get())); - } finally { - CloseableUtils.closeQuietly(client); + + @Test + public void testZKWatcher() throws Exception { + Timing timing = new Timing(); + CountZKWatcher watcher = new CountZKWatcher(); + CuratorFramework client = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); + try { + client.start(); + client.create().forPath(PATH); + // Add twice the same watcher on the same path + client.getData().usingWatcher(watcher).forPath(PATH); + client.getData().usingWatcher(watcher).forPath(PATH); + // Ok, let's test it + client.setData().forPath(PATH, new byte[] {}); + Awaitility.await().untilAsserted(() -> assertEquals(1, watcher.count.get())); + } finally { + CloseableUtils.closeQuietly(client); + } } - } } diff --git a/curator-framework/src/test/java/org/apache/curator/framework/imps/TestWatcherRemovalManager.java b/curator-framework/src/test/java/org/apache/curator/framework/imps/TestWatcherRemovalManager.java index 9113d5aaf..960a86b9c 100644 --- a/curator-framework/src/test/java/org/apache/curator/framework/imps/TestWatcherRemovalManager.java +++ b/curator-framework/src/test/java/org/apache/curator/framework/imps/TestWatcherRemovalManager.java @@ -22,41 +22,34 @@ 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 java.util.List; +import java.util.concurrent.Callable; +import java.util.concurrent.CountDownLatch; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.WatcherRemoveCuratorFramework; import org.apache.curator.framework.api.BackgroundCallback; import org.apache.curator.framework.api.CuratorEvent; import org.apache.curator.retry.RetryOneTime; -import org.apache.curator.test.compatibility.CuratorTestBase; import org.apache.curator.test.Timing; import org.apache.curator.test.WatchersDebug; +import org.apache.curator.test.compatibility.CuratorTestBase; import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.WatchedEvent; import org.apache.zookeeper.Watcher; import org.junit.jupiter.api.Test; -import java.util.List; -import java.util.concurrent.Callable; -import java.util.concurrent.CountDownLatch; - -public class TestWatcherRemovalManager extends CuratorTestBase -{ +public class TestWatcherRemovalManager extends CuratorTestBase { @Test - public void testSameWatcherDifferentPaths1Triggered() throws Exception - { + public void testSameWatcherDifferentPaths1Triggered() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); - try - { + try { client.start(); - WatcherRemovalFacade removerClient = (WatcherRemovalFacade)client.newWatcherRemoveCuratorFramework(); + WatcherRemovalFacade removerClient = (WatcherRemovalFacade) client.newWatcherRemoveCuratorFramework(); final CountDownLatch latch = new CountDownLatch(1); - Watcher watcher = new Watcher() - { + Watcher watcher = new Watcher() { @Override - public void process(WatchedEvent event) - { + public void process(WatchedEvent event) { latch.countDown(); } }; @@ -69,26 +62,20 @@ public void process(WatchedEvent event) timing.sleepABit(); removerClient.removeWatchers(); - } - finally - { + } finally { TestCleanState.closeAndTestClean(client); } } @Test - public void testSameWatcherDifferentPaths() throws Exception - { + public void testSameWatcherDifferentPaths() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); - try - { + try { client.start(); - WatcherRemovalFacade removerClient = (WatcherRemovalFacade)client.newWatcherRemoveCuratorFramework(); - Watcher watcher = new Watcher() - { + WatcherRemovalFacade removerClient = (WatcherRemovalFacade) client.newWatcherRemoveCuratorFramework(); + Watcher watcher = new Watcher() { @Override - public void process(WatchedEvent event) - { + public void process(WatchedEvent event) { // NOP } }; @@ -96,27 +83,21 @@ public void process(WatchedEvent event) removerClient.checkExists().usingWatcher(watcher).forPath("/d/e/f"); assertEquals(removerClient.getWatcherRemovalManager().getEntries().size(), 2); removerClient.removeWatchers(); - } - finally - { + } finally { TestCleanState.closeAndTestClean(client); } } @Test - public void testSameWatcherDifferentKinds1Triggered() throws Exception - { + public void testSameWatcherDifferentKinds1Triggered() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); - try - { + try { client.start(); - WatcherRemovalFacade removerClient = (WatcherRemovalFacade)client.newWatcherRemoveCuratorFramework(); + WatcherRemovalFacade removerClient = (WatcherRemovalFacade) client.newWatcherRemoveCuratorFramework(); final CountDownLatch latch = new CountDownLatch(1); - Watcher watcher = new Watcher() - { + Watcher watcher = new Watcher() { @Override - public void process(WatchedEvent event) - { + public void process(WatchedEvent event) { latch.countDown(); } }; @@ -131,26 +112,20 @@ public void process(WatchedEvent event) timing.sleepABit(); removerClient.removeWatchers(); - } - finally - { + } finally { TestCleanState.closeAndTestClean(client); } } @Test - public void testSameWatcherDifferentKinds() throws Exception - { + public void testSameWatcherDifferentKinds() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); - try - { + try { client.start(); - WatcherRemovalFacade removerClient = (WatcherRemovalFacade)client.newWatcherRemoveCuratorFramework(); - Watcher watcher = new Watcher() - { + WatcherRemovalFacade removerClient = (WatcherRemovalFacade) client.newWatcherRemoveCuratorFramework(); + Watcher watcher = new Watcher() { @Override - public void process(WatchedEvent event) - { + public void process(WatchedEvent event) { // NOP } }; @@ -159,148 +134,115 @@ public void process(WatchedEvent event) removerClient.checkExists().usingWatcher(watcher).forPath("/a/b/c"); removerClient.getData().usingWatcher(watcher).forPath("/a/b/c"); removerClient.removeWatchers(); - } - finally - { + } finally { TestCleanState.closeAndTestClean(client); } } @Test - public void testWithRetry() throws Exception - { + public void testWithRetry() throws Exception { server.stop(); CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); - try - { + try { client.start(); - WatcherRemovalFacade removerClient = (WatcherRemovalFacade)client.newWatcherRemoveCuratorFramework(); - Watcher w = new Watcher() - { + WatcherRemovalFacade removerClient = (WatcherRemovalFacade) client.newWatcherRemoveCuratorFramework(); + Watcher w = new Watcher() { @Override - public void process(WatchedEvent event) - { + public void process(WatchedEvent event) { // NOP } }; - try - { + try { removerClient.checkExists().usingWatcher(w).forPath("/one/two/three"); fail("Should have thrown ConnectionLossException"); - } - catch ( KeeperException.ConnectionLossException expected ) - { + } catch (KeeperException.ConnectionLossException expected) { // expected } assertEquals(removerClient.getWatcherRemovalManager().getEntries().size(), 0); - } - finally - { + } finally { TestCleanState.closeAndTestClean(client); } } @Test - public void testWithRetryInBackground() throws Exception - { + public void testWithRetryInBackground() throws Exception { server.stop(); CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); - try - { + try { client.start(); - WatcherRemovalFacade removerClient = (WatcherRemovalFacade)client.newWatcherRemoveCuratorFramework(); - Watcher w = new Watcher() - { + WatcherRemovalFacade removerClient = (WatcherRemovalFacade) client.newWatcherRemoveCuratorFramework(); + Watcher w = new Watcher() { @Override - public void process(WatchedEvent event) - { + public void process(WatchedEvent event) { // NOP } }; final CountDownLatch latch = new CountDownLatch(1); - BackgroundCallback callback = new BackgroundCallback() - { + BackgroundCallback callback = new BackgroundCallback() { @Override - public void processResult(CuratorFramework client, CuratorEvent event) throws Exception - { + public void processResult(CuratorFramework client, CuratorEvent event) throws Exception { latch.countDown(); } }; removerClient.checkExists().usingWatcher(w).inBackground(callback).forPath("/one/two/three"); assertTrue(new Timing().awaitLatch(latch)); assertEquals(removerClient.getWatcherRemovalManager().getEntries().size(), 0); - } - finally - { + } finally { TestCleanState.closeAndTestClean(client); } } @Test - public void testMissingNode() throws Exception - { + public void testMissingNode() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); - try - { + try { client.start(); - WatcherRemovalFacade removerClient = (WatcherRemovalFacade)client.newWatcherRemoveCuratorFramework(); - Watcher w = new Watcher() - { + WatcherRemovalFacade removerClient = (WatcherRemovalFacade) client.newWatcherRemoveCuratorFramework(); + Watcher w = new Watcher() { @Override - public void process(WatchedEvent event) - { + public void process(WatchedEvent event) { // NOP } }; - try - { + try { removerClient.getData().usingWatcher(w).forPath("/one/two/three"); fail("Should have thrown NoNodeException"); - } - catch ( KeeperException.NoNodeException expected ) - { + } catch (KeeperException.NoNodeException expected) { // expected } removerClient.removeWatchers(); - } - finally - { + } finally { TestCleanState.closeAndTestClean(client); } } @Test - public void testMissingNodeInBackground() throws Exception - { - final CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); - Callable proc = new Callable() - { + public void testMissingNodeInBackground() throws Exception { + final CuratorFramework client = + CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); + Callable proc = new Callable() { @Override - public Void call() throws Exception - { + public Void call() throws Exception { client.start(); - WatcherRemovalFacade removerClient = (WatcherRemovalFacade)client.newWatcherRemoveCuratorFramework(); - Watcher w = new Watcher() - { + WatcherRemovalFacade removerClient = (WatcherRemovalFacade) client.newWatcherRemoveCuratorFramework(); + Watcher w = new Watcher() { @Override - public void process(WatchedEvent event) - { + public void process(WatchedEvent event) { // NOP } }; final CountDownLatch latch = new CountDownLatch(1); - BackgroundCallback callback = new BackgroundCallback() - { + BackgroundCallback callback = new BackgroundCallback() { @Override - public void processResult(CuratorFramework client, CuratorEvent event) throws Exception - { + public void processResult(CuratorFramework client, CuratorEvent event) throws Exception { latch.countDown(); } }; removerClient.getData().usingWatcher(w).inBackground(callback).forPath("/one/two/three"); assertTrue(new Timing().awaitLatch(latch)); - assertEquals(removerClient.getWatcherRemovalManager().getEntries().size(), 0); + assertEquals( + removerClient.getWatcherRemovalManager().getEntries().size(), 0); removerClient.removeWatchers(); return null; } @@ -309,89 +251,69 @@ public void processResult(CuratorFramework client, CuratorEvent event) throws Ex } @Test - public void testBasic() throws Exception - { + public void testBasic() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); - try - { + try { client.start(); internalTryBasic(client); - } - finally - { + } finally { TestCleanState.closeAndTestClean(client); } } @Test - public void testBasicNamespace1() throws Exception - { + public void testBasicNamespace1() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); - try - { + try { client.start(); internalTryBasic(client.usingNamespace("foo")); - } - finally - { + } finally { TestCleanState.closeAndTestClean(client); } } @Test - public void testBasicNamespace2() throws Exception - { + public void testBasicNamespace2() throws Exception { CuratorFramework client = CuratorFrameworkFactory.builder() - .connectString(server.getConnectString()) - .retryPolicy(new RetryOneTime(1)) - .namespace("hey") - .build(); - try - { + .connectString(server.getConnectString()) + .retryPolicy(new RetryOneTime(1)) + .namespace("hey") + .build(); + try { client.start(); internalTryBasic(client); - } - finally - { + } finally { TestCleanState.closeAndTestClean(client); } } @Test - public void testBasicNamespace3() throws Exception - { + public void testBasicNamespace3() throws Exception { CuratorFramework client = CuratorFrameworkFactory.builder() - .connectString(server.getConnectString()) - .retryPolicy(new RetryOneTime(1)) - .namespace("hey") - .build(); - try - { + .connectString(server.getConnectString()) + .retryPolicy(new RetryOneTime(1)) + .namespace("hey") + .build(); + try { client.start(); internalTryBasic(client.usingNamespace("lakjsf")); - } - finally - { + } finally { TestCleanState.closeAndTestClean(client); } } @Test - public void testSameWatcher() throws Exception - { + public void testSameWatcher() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); - try - { + try { client.start(); client.create().forPath("/test"); - WatcherRemovalFacade removerClient = (WatcherRemovalFacade)client.newWatcherRemoveCuratorFramework(); + WatcherRemovalFacade removerClient = (WatcherRemovalFacade) client.newWatcherRemoveCuratorFramework(); - Watcher watcher = new Watcher() - { + Watcher watcher = new Watcher() { @Override - public void process(WatchedEvent event) - { + public void process(WatchedEvent event) { // NOP } }; @@ -401,31 +323,24 @@ public void process(WatchedEvent event) removerClient.getData().usingWatcher(watcher).forPath("/test"); assertEquals(removerClient.getRemovalManager().getEntries().size(), 1); removerClient.removeWatchers(); - } - finally - { + } finally { TestCleanState.closeAndTestClean(client); } } @Test - public void testTriggered() throws Exception - { + public void testTriggered() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); - try - { + try { client.start(); - WatcherRemovalFacade removerClient = (WatcherRemovalFacade)client.newWatcherRemoveCuratorFramework(); + WatcherRemovalFacade removerClient = (WatcherRemovalFacade) client.newWatcherRemoveCuratorFramework(); final CountDownLatch latch = new CountDownLatch(1); - Watcher watcher = new Watcher() - { + Watcher watcher = new Watcher() { @Override - public void process(WatchedEvent event) - { - if ( event.getType() == Event.EventType.NodeCreated ) - { + public void process(WatchedEvent event) { + if (event.getType() == Event.EventType.NodeCreated) { latch.countDown(); } } @@ -438,45 +353,33 @@ public void process(WatchedEvent event) assertTrue(new Timing().awaitLatch(latch)); assertEquals(removerClient.getRemovalManager().getEntries().size(), 0); - } - finally - { + } finally { TestCleanState.closeAndTestClean(client); } } @Test - public void testResetFromWatcher() throws Exception - { + public void testResetFromWatcher() throws Exception { Timing timing = new Timing(); CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); - try - { + try { client.start(); - final WatcherRemovalFacade removerClient = (WatcherRemovalFacade)client.newWatcherRemoveCuratorFramework(); + final WatcherRemovalFacade removerClient = (WatcherRemovalFacade) client.newWatcherRemoveCuratorFramework(); final CountDownLatch createdLatch = new CountDownLatch(1); final CountDownLatch deletedLatch = new CountDownLatch(1); - Watcher watcher = new Watcher() - { + Watcher watcher = new Watcher() { @Override - public void process(WatchedEvent event) - { - if ( event.getType() == Event.EventType.NodeCreated ) - { - try - { + public void process(WatchedEvent event) { + if (event.getType() == Event.EventType.NodeCreated) { + try { removerClient.checkExists().usingWatcher(this).forPath("/yo"); - } - catch ( Exception e ) - { + } catch (Exception e) { e.printStackTrace(); } createdLatch.countDown(); - } - else if ( event.getType() == Event.EventType.NodeDeleted ) - { + } else if (event.getType() == Event.EventType.NodeDeleted) { deletedLatch.countDown(); } } @@ -494,32 +397,27 @@ else if ( event.getType() == Event.EventType.NodeDeleted ) assertTrue(timing.awaitLatch(deletedLatch)); assertEquals(removerClient.getRemovalManager().getEntries().size(), 0); - } - finally - { + } finally { TestCleanState.closeAndTestClean(client); } } - private void internalTryBasic(CuratorFramework client) throws Exception - { + private void internalTryBasic(CuratorFramework client) throws Exception { WatcherRemoveCuratorFramework removerClient = client.newWatcherRemoveCuratorFramework(); final CountDownLatch latch = new CountDownLatch(1); - Watcher watcher = new Watcher() - { + Watcher watcher = new Watcher() { @Override - public void process(WatchedEvent event) - { - if ( event.getType() == Event.EventType.DataWatchRemoved ) - { + public void process(WatchedEvent event) { + if (event.getType() == Event.EventType.DataWatchRemoved) { latch.countDown(); } } }; removerClient.checkExists().usingWatcher(watcher).forPath("/hey"); - List existWatches = WatchersDebug.getExistWatches(client.getZookeeperClient().getZooKeeper()); + List existWatches = + WatchersDebug.getExistWatches(client.getZookeeperClient().getZooKeeper()); assertEquals(existWatches.size(), 1); removerClient.removeWatchers(); diff --git a/curator-framework/src/test/java/org/apache/curator/framework/imps/TestWatchesBuilder.java b/curator-framework/src/test/java/org/apache/curator/framework/imps/TestWatchesBuilder.java index 949cb12af..3dd57ae47 100644 --- a/curator-framework/src/test/java/org/apache/curator/framework/imps/TestWatchesBuilder.java +++ b/curator-framework/src/test/java/org/apache/curator/framework/imps/TestWatchesBuilder.java @@ -17,776 +17,714 @@ * under the License. */ -package org.apache.curator.framework.imps; - -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 org.apache.curator.framework.CuratorFramework; -import org.apache.curator.framework.CuratorFrameworkFactory; -import org.apache.curator.framework.api.BackgroundCallback; -import org.apache.curator.framework.api.CuratorEvent; -import org.apache.curator.framework.api.CuratorEventType; -import org.apache.curator.framework.api.CuratorListener; -import org.apache.curator.framework.api.CuratorWatcher; -import org.apache.curator.framework.imps.FailedRemoveWatchManager.FailedRemoveWatchDetails; -import org.apache.curator.framework.state.ConnectionState; -import org.apache.curator.framework.state.ConnectionStateListener; -import org.apache.curator.retry.ExponentialBackoffRetry; -import org.apache.curator.retry.RetryOneTime; -import org.apache.curator.test.Timing; -import org.apache.curator.test.compatibility.CuratorTestBase; -import org.apache.curator.utils.CloseableUtils; -import org.apache.curator.utils.ZookeeperFactory; -import org.apache.zookeeper.AddWatchMode; -import org.apache.zookeeper.KeeperException; -import org.apache.zookeeper.WatchedEvent; -import org.apache.zookeeper.Watcher; -import org.apache.zookeeper.Watcher.Event.EventType; -import org.apache.zookeeper.Watcher.WatcherType; -import org.apache.zookeeper.ZooKeeper; -import org.junit.jupiter.api.Tag; -import org.junit.jupiter.api.Test; - -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicReference; - -public class TestWatchesBuilder extends CuratorTestBase -{ - private AtomicReference registerConnectionStateListener(CuratorFramework client) - { - final AtomicReference state = new AtomicReference(); - client.getConnectionStateListenable().addListener(new ConnectionStateListener() - { - - @Override - public void stateChanged(CuratorFramework client, ConnectionState newState) - { - state.set(newState); - synchronized(state) - { - state.notify(); - } - } - }); - - return state; - } - - private boolean blockUntilDesiredConnectionState(AtomicReference stateRef, Timing timing, final ConnectionState desiredState) - { - if(stateRef.get() == desiredState) - { - return true; - } - - //noinspection SynchronizationOnLocalVariableOrMethodParameter - synchronized(stateRef) - { - if(stateRef.get() == desiredState) - { - return true; - } - - try - { - stateRef.wait(timing.milliseconds()); - return stateRef.get() == desiredState; - } - catch(InterruptedException e) - { - Thread.currentThread().interrupt(); - return false; - } - } - } - - @Test - public void testRemoveCuratorDefaultWatcher() throws Exception - { - Timing timing = new Timing(); - CuratorFramework client = CuratorFrameworkFactory.builder(). - connectString(server.getConnectString()). - retryPolicy(new RetryOneTime(1)). - build(); - try - { - client.start(); - - final CountDownLatch removedLatch = new CountDownLatch(1); - - final String path = "/"; - client.getCuratorListenable().addListener(new CuratorListener() - { - @Override - public void eventReceived(CuratorFramework client, CuratorEvent event) - throws Exception - { - if(event.getType() == CuratorEventType.WATCHED && event.getWatchedEvent().getType() == EventType.DataWatchRemoved) { - removedLatch.countDown(); - } - } - }); - - client.checkExists().watched().forPath(path); - - client.watches().removeAll().forPath(path); - - assertTrue(timing.awaitLatch(removedLatch), "Timed out waiting for watch removal"); - } - finally - { - CloseableUtils.closeQuietly(client); - } - } - - @Test - public void testRemoveCuratorWatch() throws Exception - { - Timing timing = new Timing(); - CuratorFrameworkImpl client = (CuratorFrameworkImpl)CuratorFrameworkFactory.builder(). - connectString(server.getConnectString()). - retryPolicy(new RetryOneTime(1)). - build(); - try - { - client.start(); - - final CountDownLatch removedLatch = new CountDownLatch(1); - - final String path = "/"; - CuratorWatcher watcher = new CuratorWatcher() - { - - @Override - public void process(WatchedEvent event) throws Exception - { - if(event.getPath().equals(path) && event.getType() == EventType.DataWatchRemoved) { - removedLatch.countDown(); - } - } - }; - - client.checkExists().usingWatcher(watcher).forPath(path); - - client.watches().remove(watcher).forPath(path); - - assertTrue(timing.awaitLatch(removedLatch), "Timed out waiting for watch removal"); - } - finally - { - CloseableUtils.closeQuietly(client); - } - } - - @Test - public void testRemoveWatch() throws Exception - { - Timing timing = new Timing(); - CuratorFrameworkImpl client = (CuratorFrameworkImpl)CuratorFrameworkFactory.builder(). - connectString(server.getConnectString()). - retryPolicy(new RetryOneTime(1)). - build(); - try - { - client.start(); - - final CountDownLatch removedLatch = new CountDownLatch(1); - - final String path = "/"; - Watcher watcher = new CountDownWatcher(path, removedLatch, EventType.DataWatchRemoved); - - client.checkExists().usingWatcher(watcher).forPath(path); - - client.watches().remove(watcher).forPath(path); - - assertTrue(timing.awaitLatch(removedLatch), "Timed out waiting for watch removal"); - } - finally - { - CloseableUtils.closeQuietly(client); - } - } - - @Test - public void testRemoveWatchInBackgroundWithCallback() throws Exception - { - Timing timing = new Timing(); - CuratorFrameworkImpl client = (CuratorFrameworkImpl)CuratorFrameworkFactory.builder(). - connectString(server.getConnectString()). - retryPolicy(new RetryOneTime(1)). - build(); - try - { - client.start(); - - //Make sure that the event fires on both the watcher and the callback. - final CountDownLatch removedLatch = new CountDownLatch(2); - final String path = "/"; - Watcher watcher = new CountDownWatcher(path, removedLatch, EventType.DataWatchRemoved); - - BackgroundCallback callback = new BackgroundCallback() - { - - @Override - public void processResult(CuratorFramework client, CuratorEvent event) - throws Exception - { - if(event.getType() == CuratorEventType.REMOVE_WATCHES && event.getPath().equals(path)) { - removedLatch.countDown(); - } - } - }; - - client.checkExists().usingWatcher(watcher).forPath(path); - - client.watches().remove(watcher).ofType(WatcherType.Any).inBackground(callback).forPath(path); - - assertTrue(timing.awaitLatch(removedLatch), "Timed out waiting for watch removal"); - - } - finally - { - CloseableUtils.closeQuietly(client); - } - } - - @Test - public void testRemoveWatchInBackgroundWithNoCallback() throws Exception - { - Timing timing = new Timing(); - CuratorFrameworkImpl client = (CuratorFrameworkImpl)CuratorFrameworkFactory.builder(). - connectString(server.getConnectString()). - retryPolicy(new RetryOneTime(1)). - build(); - try - { - client.start(); - - final String path = "/"; - final CountDownLatch removedLatch = new CountDownLatch(1); - Watcher watcher = new CountDownWatcher(path, removedLatch, EventType.DataWatchRemoved); - - client.checkExists().usingWatcher(watcher).forPath(path); - - client.watches().remove(watcher).inBackground().forPath(path); - - assertTrue(timing.awaitLatch(removedLatch), "Timed out waiting for watch removal"); - - } - finally - { - CloseableUtils.closeQuietly(client); - } - } - - @Test - public void testRemoveAllWatches() throws Exception - { - Timing timing = new Timing(); - CuratorFrameworkImpl client = (CuratorFrameworkImpl)CuratorFrameworkFactory.builder(). - connectString(server.getConnectString()). - retryPolicy(new RetryOneTime(1)). - build(); - try - { - client.start(); - - final String path = "/"; - final CountDownLatch removedLatch = new CountDownLatch(2); - - Watcher watcher1 = new CountDownWatcher(path, removedLatch, EventType.ChildWatchRemoved); - Watcher watcher2 = new CountDownWatcher(path, removedLatch, EventType.DataWatchRemoved); - - client.getChildren().usingWatcher(watcher1).forPath(path); - client.checkExists().usingWatcher(watcher2).forPath(path); - - client.watches().removeAll().forPath(path); - - assertTrue(timing.awaitLatch(removedLatch), "Timed out waiting for watch removal"); - } - finally - { - CloseableUtils.closeQuietly(client); - } - } - - @Test - public void testRemoveAllDataWatches() throws Exception - { - Timing timing = new Timing(); - CuratorFramework client = CuratorFrameworkFactory.builder(). - connectString(server.getConnectString()). - retryPolicy(new RetryOneTime(1)). - build(); - try - { - client.start(); - - final String path = "/"; - final AtomicBoolean removedFlag = new AtomicBoolean(false); - final CountDownLatch removedLatch = new CountDownLatch(1); - - Watcher watcher1 = new BooleanWatcher(path, removedFlag, EventType.ChildWatchRemoved); - Watcher watcher2 = new CountDownWatcher(path, removedLatch, EventType.DataWatchRemoved); - - client.getChildren().usingWatcher(watcher1).forPath(path); - client.checkExists().usingWatcher(watcher2).forPath(path); - - client.watches().removeAll().ofType(WatcherType.Data).forPath(path); - - assertTrue(timing.awaitLatch(removedLatch), "Timed out waiting for watch removal"); - assertEquals(removedFlag.get(), false); - } - finally - { - CloseableUtils.closeQuietly(client); - } - } - - @Test - public void testRemoveAllChildWatches() throws Exception - { - Timing timing = new Timing(); - CuratorFramework client = CuratorFrameworkFactory.builder(). - connectString(server.getConnectString()). - retryPolicy(new RetryOneTime(1)). - build(); - try - { - client.start(); - - final String path = "/"; - final AtomicBoolean removedFlag = new AtomicBoolean(false); - final CountDownLatch removedLatch = new CountDownLatch(1); - - Watcher watcher1 = new BooleanWatcher(path, removedFlag, EventType.DataWatchRemoved); - Watcher watcher2 = new CountDownWatcher(path, removedLatch, EventType.ChildWatchRemoved); - - client.checkExists().usingWatcher(watcher1).forPath(path); - client.getChildren().usingWatcher(watcher2).forPath(path); - - client.watches().removeAll().ofType(WatcherType.Children).forPath(path); - - assertTrue(timing.awaitLatch(removedLatch), "Timed out waiting for watch removal"); - assertEquals(removedFlag.get(), false); - } - finally - { - CloseableUtils.closeQuietly(client); - } - } - - @Test - public void testRemoveLocalWatch() throws Exception { - Timing timing = new Timing(); - CuratorFrameworkImpl client = (CuratorFrameworkImpl)CuratorFrameworkFactory.builder(). - connectString(server.getConnectString()). - retryPolicy(new RetryOneTime(1)). - build(); - try - { - client.start(); - - AtomicReference stateRef = registerConnectionStateListener(client); - - final String path = "/"; - - final CountDownLatch removedLatch = new CountDownLatch(1); - - Watcher watcher = new CountDownWatcher(path, removedLatch, EventType.DataWatchRemoved); - - client.checkExists().usingWatcher(watcher).forPath(path); - - //Stop the server so we can check if we can remove watches locally when offline - server.stop(); - - assertTrue(blockUntilDesiredConnectionState(stateRef, timing, ConnectionState.SUSPENDED)); - - client.watches().removeAll().locally().forPath(path); - - assertTrue(timing.awaitLatch(removedLatch), "Timed out waiting for watch removal"); - } - finally - { - CloseableUtils.closeQuietly(client); - } - } - - @Test - public void testRemoveLocalWatchInBackground() throws Exception { - Timing timing = new Timing(); - CuratorFrameworkImpl client = (CuratorFrameworkImpl)CuratorFrameworkFactory.builder(). - connectString(server.getConnectString()). - retryPolicy(new RetryOneTime(1)). - build(); - try - { - client.start(); - - AtomicReference stateRef = registerConnectionStateListener(client); - - final String path = "/"; - - final CountDownLatch removedLatch = new CountDownLatch(1); - - Watcher watcher = new CountDownWatcher(path, removedLatch, EventType.DataWatchRemoved); - - client.checkExists().usingWatcher(watcher).forPath(path); - - //Stop the server so we can check if we can remove watches locally when offline - server.stop(); - - assertTrue(blockUntilDesiredConnectionState(stateRef, timing, ConnectionState.SUSPENDED)); - - client.watches().removeAll().locally().inBackground().forPath(path); - - assertTrue(timing.awaitLatch(removedLatch), "Timed out waiting for watch removal"); - } - finally - { - CloseableUtils.closeQuietly(client); - } - } - - /** - * Test the case where we try and remove an unregistered watcher. In this case we expect a NoWatcherException to - * be thrown. - * @throws Exception - */ - @Test - public void testRemoveUnregisteredWatcher() throws Exception - { - CuratorFramework client = CuratorFrameworkFactory.builder(). - connectString(server.getConnectString()). - retryPolicy(new RetryOneTime(1)). - build(); - try - { - client.start(); - - final String path = "/"; - Watcher watcher = new Watcher() { - @Override - public void process(WatchedEvent event) - { - } - }; - - try - { - client.watches().remove(watcher).forPath(path); - fail("Expected KeeperException.NoWatcherException"); - } - catch ( KeeperException.NoWatcherException expected ) - { - // expected - } - } - finally - { - CloseableUtils.closeQuietly(client); - } - } - - /** - * Test the case where we try and remove an unregistered watcher but have the quietly flag set. In this case we expect success. - * @throws Exception - */ - @Test - public void testRemoveUnregisteredWatcherQuietly() throws Exception - { - Timing timing = new Timing(); - CuratorFramework client = CuratorFrameworkFactory.builder(). - connectString(server.getConnectString()). - retryPolicy(new RetryOneTime(1)). - build(); - try - { - client.start(); - - final AtomicBoolean watcherRemoved = new AtomicBoolean(false); - - final String path = "/"; - Watcher watcher = new BooleanWatcher(path, watcherRemoved, EventType.DataWatchRemoved); - - client.watches().remove(watcher).quietly().forPath(path); - - timing.sleepABit(); - - //There should be no watcher removed as none were registered. - assertEquals(watcherRemoved.get(), false); - } - finally - { - CloseableUtils.closeQuietly(client); - } - } - - @Test - public void testGuaranteedRemoveWatch() throws Exception { - Timing timing = new Timing(); - CuratorFramework client = CuratorFrameworkFactory.builder(). - connectString(server.getConnectString()). - retryPolicy(new RetryOneTime(1)). - build(); - try - { - client.start(); - - AtomicReference stateRef = registerConnectionStateListener(client); - - String path = "/"; - - CountDownLatch removeLatch = new CountDownLatch(1); - - Watcher watcher = new CountDownWatcher(path, removeLatch, EventType.DataWatchRemoved); - client.checkExists().usingWatcher(watcher).forPath(path); - - server.stop(); - - assertTrue(blockUntilDesiredConnectionState(stateRef, timing, ConnectionState.SUSPENDED)); - - //Remove the watch while we're not connected - try - { - client.watches().remove(watcher).guaranteed().forPath(path); - fail(); - } - catch(KeeperException.ConnectionLossException e) - { - //Expected - } - - server.restart(); - - timing.awaitLatch(removeLatch); - } - finally - { - CloseableUtils.closeQuietly(client); - } - } - - @Test - public void testGuaranteedRemoveWatchInBackground() throws Exception { - Timing timing = new Timing(); - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), - new ExponentialBackoffRetry(100, 3)); - try - { - client.start(); - - AtomicReference stateRef = registerConnectionStateListener(client); - - final CountDownLatch guaranteeAddedLatch = new CountDownLatch(1); - - ((CuratorFrameworkImpl)client).getFailedRemoveWatcherManager().debugListener = new FailedOperationManager.FailedOperationManagerListener() - { - - @Override - public void pathAddedForGuaranteedOperation( - FailedRemoveWatchDetails detail) - { - guaranteeAddedLatch.countDown(); - } - }; - - String path = "/"; - - CountDownLatch removeLatch = new CountDownLatch(1); - - Watcher watcher = new CountDownWatcher(path, removeLatch, EventType.DataWatchRemoved); - client.checkExists().usingWatcher(watcher).forPath(path); - - server.stop(); - assertTrue(blockUntilDesiredConnectionState(stateRef, timing, ConnectionState.SUSPENDED)); - - //Remove the watch while we're not connected - client.watches().remove(watcher).guaranteed().inBackground().forPath(path); - - timing.awaitLatch(guaranteeAddedLatch); - - server.restart(); - - timing.awaitLatch(removeLatch); - } - finally - { - CloseableUtils.closeQuietly(client); - } - } - - @Test - @Tag(CuratorTestBase.zk36Group) - public void testPersistentWatch() throws Exception - { - try ( CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)) ) - { - client.start(); - client.blockUntilConnected(); - - CountDownLatch latch = new CountDownLatch(3); - Watcher watcher = event -> latch.countDown(); - client.watchers().add().withMode(AddWatchMode.PERSISTENT).usingWatcher(watcher).forPath("/test/foo"); - - client.create().creatingParentsIfNeeded().forPath("/test/foo"); - client.setData().forPath("/test/foo", "hey".getBytes()); - client.delete().forPath("/test/foo"); - - assertTrue(timing.awaitLatch(latch)); - } - } - - @Test - @Tag(CuratorTestBase.zk36Group) - public void testPersistentWatchInBackground() throws Exception - { - try ( CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)) ) - { - client.start(); - client.blockUntilConnected(); - - CountDownLatch backgroundLatch = new CountDownLatch(1); - BackgroundCallback backgroundCallback = (__, ___) -> backgroundLatch.countDown(); - CountDownLatch latch = new CountDownLatch(3); - Watcher watcher = event -> latch.countDown(); - client.watchers().add().withMode(AddWatchMode.PERSISTENT).inBackground(backgroundCallback).usingWatcher(watcher).forPath("/test/foo"); - - client.create().creatingParentsIfNeeded().forPath("/test/foo"); - client.setData().forPath("/test/foo", "hey".getBytes()); - client.delete().forPath("/test/foo"); - - assertTrue(timing.awaitLatch(backgroundLatch)); - assertTrue(timing.awaitLatch(latch)); - } - } - - @Test - @Tag(CuratorTestBase.zk36Group) - public void testPersistentRecursiveWatch() throws Exception - { - try ( CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)) ) - { - client.start(); - client.blockUntilConnected(); - - CountDownLatch latch = new CountDownLatch(5); - Watcher watcher = event -> latch.countDown(); - client.watchers().add().withMode(AddWatchMode.PERSISTENT_RECURSIVE).usingWatcher(watcher).forPath("/test"); - - client.create().forPath("/test"); - client.create().forPath("/test/a"); - client.create().forPath("/test/a/b"); - client.create().forPath("/test/a/b/c"); - client.create().forPath("/test/a/b/c/d"); - - assertTrue(timing.awaitLatch(latch)); - } - } - - @Test - @Tag(CuratorTestBase.zk36Group) - public void testPersistentRecursiveWatchInBackground() throws Exception - { - try ( CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)) ) - { - client.start(); - client.blockUntilConnected(); - - CountDownLatch backgroundLatch = new CountDownLatch(1); - BackgroundCallback backgroundCallback = (__, ___) -> backgroundLatch.countDown(); - CountDownLatch latch = new CountDownLatch(5); - Watcher watcher = event -> latch.countDown(); - client.watchers().add().withMode(AddWatchMode.PERSISTENT_RECURSIVE).inBackground(backgroundCallback).usingWatcher(watcher).forPath("/test"); - - client.create().forPath("/test"); - client.create().forPath("/test/a"); - client.create().forPath("/test/a/b"); - client.create().forPath("/test/a/b/c"); - client.create().forPath("/test/a/b/c/d"); - - assertTrue(timing.awaitLatch(backgroundLatch)); - assertTrue(timing.awaitLatch(latch)); - } - } - - @Test - @Tag(CuratorTestBase.zk36Group) - public void testPersistentRecursiveDefaultWatch() throws Exception - { - CountDownLatch latch = new CountDownLatch(6); // 5 creates plus the initial sync - ZookeeperFactory zookeeperFactory = (connectString, sessionTimeout, watcher, canBeReadOnly) -> { - Watcher actualWatcher = event -> { - watcher.process(event); - latch.countDown(); - }; - return new ZooKeeper(connectString, sessionTimeout, actualWatcher); - }; - try (CuratorFramework client = CuratorFrameworkFactory.builder().connectString(server.getConnectString()).retryPolicy(new RetryOneTime(1)).zookeeperFactory(zookeeperFactory).build() ) - { - client.start(); - client.blockUntilConnected(); - - client.watchers().add().withMode(AddWatchMode.PERSISTENT_RECURSIVE).forPath("/test"); - - client.create().forPath("/test"); - client.create().forPath("/test/a"); - client.create().forPath("/test/a/b"); - client.create().forPath("/test/a/b/c"); - client.create().forPath("/test/a/b/c/d"); - - assertTrue(timing.awaitLatch(latch)); - } - } - - private static class CountDownWatcher implements Watcher { - private String path; - private EventType eventType; - private CountDownLatch removeLatch; - - public CountDownWatcher(String path, CountDownLatch removeLatch, EventType eventType) { - this.path = path; - this.eventType = eventType; - this.removeLatch = removeLatch; - } - - @Override - public void process(WatchedEvent event) - { - if(event.getPath() == null || event.getType() == null) { - return; - } - - if(event.getPath().equals(path) && event.getType() == eventType) { - removeLatch.countDown(); - } - } - } - - private static class BooleanWatcher implements Watcher { - private String path; - private EventType eventType; - private AtomicBoolean removedFlag; - - public BooleanWatcher(String path, AtomicBoolean removedFlag, EventType eventType) { - this.path = path; - this.eventType = eventType; - this.removedFlag = removedFlag; - } - - @Override - public void process(WatchedEvent event) - { - if(event.getPath() == null || event.getType() == null) { - return; - } - - if(event.getPath().equals(path) && event.getType() == eventType) { - removedFlag.set(true); - } - } - } -} +package org.apache.curator.framework.imps; + +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 java.util.concurrent.CountDownLatch; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicReference; +import org.apache.curator.framework.CuratorFramework; +import org.apache.curator.framework.CuratorFrameworkFactory; +import org.apache.curator.framework.api.BackgroundCallback; +import org.apache.curator.framework.api.CuratorEvent; +import org.apache.curator.framework.api.CuratorEventType; +import org.apache.curator.framework.api.CuratorListener; +import org.apache.curator.framework.api.CuratorWatcher; +import org.apache.curator.framework.imps.FailedRemoveWatchManager.FailedRemoveWatchDetails; +import org.apache.curator.framework.state.ConnectionState; +import org.apache.curator.framework.state.ConnectionStateListener; +import org.apache.curator.retry.ExponentialBackoffRetry; +import org.apache.curator.retry.RetryOneTime; +import org.apache.curator.test.Timing; +import org.apache.curator.test.compatibility.CuratorTestBase; +import org.apache.curator.utils.CloseableUtils; +import org.apache.curator.utils.ZookeeperFactory; +import org.apache.zookeeper.AddWatchMode; +import org.apache.zookeeper.KeeperException; +import org.apache.zookeeper.WatchedEvent; +import org.apache.zookeeper.Watcher; +import org.apache.zookeeper.Watcher.Event.EventType; +import org.apache.zookeeper.Watcher.WatcherType; +import org.apache.zookeeper.ZooKeeper; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +public class TestWatchesBuilder extends CuratorTestBase { + private AtomicReference registerConnectionStateListener(CuratorFramework client) { + final AtomicReference state = new AtomicReference(); + client.getConnectionStateListenable().addListener(new ConnectionStateListener() { + + @Override + public void stateChanged(CuratorFramework client, ConnectionState newState) { + state.set(newState); + synchronized (state) { + state.notify(); + } + } + }); + + return state; + } + + private boolean blockUntilDesiredConnectionState( + AtomicReference stateRef, Timing timing, final ConnectionState desiredState) { + if (stateRef.get() == desiredState) { + return true; + } + + //noinspection SynchronizationOnLocalVariableOrMethodParameter + synchronized (stateRef) { + if (stateRef.get() == desiredState) { + return true; + } + + try { + stateRef.wait(timing.milliseconds()); + return stateRef.get() == desiredState; + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + return false; + } + } + } + + @Test + public void testRemoveCuratorDefaultWatcher() throws Exception { + Timing timing = new Timing(); + CuratorFramework client = CuratorFrameworkFactory.builder() + .connectString(server.getConnectString()) + .retryPolicy(new RetryOneTime(1)) + .build(); + try { + client.start(); + + final CountDownLatch removedLatch = new CountDownLatch(1); + + final String path = "/"; + client.getCuratorListenable().addListener(new CuratorListener() { + @Override + public void eventReceived(CuratorFramework client, CuratorEvent event) throws Exception { + if (event.getType() == CuratorEventType.WATCHED + && event.getWatchedEvent().getType() == EventType.DataWatchRemoved) { + removedLatch.countDown(); + } + } + }); + + client.checkExists().watched().forPath(path); + + client.watches().removeAll().forPath(path); + + assertTrue(timing.awaitLatch(removedLatch), "Timed out waiting for watch removal"); + } finally { + CloseableUtils.closeQuietly(client); + } + } + + @Test + public void testRemoveCuratorWatch() throws Exception { + Timing timing = new Timing(); + CuratorFrameworkImpl client = (CuratorFrameworkImpl) CuratorFrameworkFactory.builder() + .connectString(server.getConnectString()) + .retryPolicy(new RetryOneTime(1)) + .build(); + try { + client.start(); + + final CountDownLatch removedLatch = new CountDownLatch(1); + + final String path = "/"; + CuratorWatcher watcher = new CuratorWatcher() { + + @Override + public void process(WatchedEvent event) throws Exception { + if (event.getPath().equals(path) && event.getType() == EventType.DataWatchRemoved) { + removedLatch.countDown(); + } + } + }; + + client.checkExists().usingWatcher(watcher).forPath(path); + + client.watches().remove(watcher).forPath(path); + + assertTrue(timing.awaitLatch(removedLatch), "Timed out waiting for watch removal"); + } finally { + CloseableUtils.closeQuietly(client); + } + } + + @Test + public void testRemoveWatch() throws Exception { + Timing timing = new Timing(); + CuratorFrameworkImpl client = (CuratorFrameworkImpl) CuratorFrameworkFactory.builder() + .connectString(server.getConnectString()) + .retryPolicy(new RetryOneTime(1)) + .build(); + try { + client.start(); + + final CountDownLatch removedLatch = new CountDownLatch(1); + + final String path = "/"; + Watcher watcher = new CountDownWatcher(path, removedLatch, EventType.DataWatchRemoved); + + client.checkExists().usingWatcher(watcher).forPath(path); + + client.watches().remove(watcher).forPath(path); + + assertTrue(timing.awaitLatch(removedLatch), "Timed out waiting for watch removal"); + } finally { + CloseableUtils.closeQuietly(client); + } + } + + @Test + public void testRemoveWatchInBackgroundWithCallback() throws Exception { + Timing timing = new Timing(); + CuratorFrameworkImpl client = (CuratorFrameworkImpl) CuratorFrameworkFactory.builder() + .connectString(server.getConnectString()) + .retryPolicy(new RetryOneTime(1)) + .build(); + try { + client.start(); + + // Make sure that the event fires on both the watcher and the callback. + final CountDownLatch removedLatch = new CountDownLatch(2); + final String path = "/"; + Watcher watcher = new CountDownWatcher(path, removedLatch, EventType.DataWatchRemoved); + + BackgroundCallback callback = new BackgroundCallback() { + + @Override + public void processResult(CuratorFramework client, CuratorEvent event) throws Exception { + if (event.getType() == CuratorEventType.REMOVE_WATCHES + && event.getPath().equals(path)) { + removedLatch.countDown(); + } + } + }; + + client.checkExists().usingWatcher(watcher).forPath(path); + + client.watches() + .remove(watcher) + .ofType(WatcherType.Any) + .inBackground(callback) + .forPath(path); + + assertTrue(timing.awaitLatch(removedLatch), "Timed out waiting for watch removal"); + + } finally { + CloseableUtils.closeQuietly(client); + } + } + + @Test + public void testRemoveWatchInBackgroundWithNoCallback() throws Exception { + Timing timing = new Timing(); + CuratorFrameworkImpl client = (CuratorFrameworkImpl) CuratorFrameworkFactory.builder() + .connectString(server.getConnectString()) + .retryPolicy(new RetryOneTime(1)) + .build(); + try { + client.start(); + + final String path = "/"; + final CountDownLatch removedLatch = new CountDownLatch(1); + Watcher watcher = new CountDownWatcher(path, removedLatch, EventType.DataWatchRemoved); + + client.checkExists().usingWatcher(watcher).forPath(path); + + client.watches().remove(watcher).inBackground().forPath(path); + + assertTrue(timing.awaitLatch(removedLatch), "Timed out waiting for watch removal"); + + } finally { + CloseableUtils.closeQuietly(client); + } + } + + @Test + public void testRemoveAllWatches() throws Exception { + Timing timing = new Timing(); + CuratorFrameworkImpl client = (CuratorFrameworkImpl) CuratorFrameworkFactory.builder() + .connectString(server.getConnectString()) + .retryPolicy(new RetryOneTime(1)) + .build(); + try { + client.start(); + + final String path = "/"; + final CountDownLatch removedLatch = new CountDownLatch(2); + + Watcher watcher1 = new CountDownWatcher(path, removedLatch, EventType.ChildWatchRemoved); + Watcher watcher2 = new CountDownWatcher(path, removedLatch, EventType.DataWatchRemoved); + + client.getChildren().usingWatcher(watcher1).forPath(path); + client.checkExists().usingWatcher(watcher2).forPath(path); + + client.watches().removeAll().forPath(path); + + assertTrue(timing.awaitLatch(removedLatch), "Timed out waiting for watch removal"); + } finally { + CloseableUtils.closeQuietly(client); + } + } + + @Test + public void testRemoveAllDataWatches() throws Exception { + Timing timing = new Timing(); + CuratorFramework client = CuratorFrameworkFactory.builder() + .connectString(server.getConnectString()) + .retryPolicy(new RetryOneTime(1)) + .build(); + try { + client.start(); + + final String path = "/"; + final AtomicBoolean removedFlag = new AtomicBoolean(false); + final CountDownLatch removedLatch = new CountDownLatch(1); + + Watcher watcher1 = new BooleanWatcher(path, removedFlag, EventType.ChildWatchRemoved); + Watcher watcher2 = new CountDownWatcher(path, removedLatch, EventType.DataWatchRemoved); + + client.getChildren().usingWatcher(watcher1).forPath(path); + client.checkExists().usingWatcher(watcher2).forPath(path); + + client.watches().removeAll().ofType(WatcherType.Data).forPath(path); + + assertTrue(timing.awaitLatch(removedLatch), "Timed out waiting for watch removal"); + assertEquals(removedFlag.get(), false); + } finally { + CloseableUtils.closeQuietly(client); + } + } + + @Test + public void testRemoveAllChildWatches() throws Exception { + Timing timing = new Timing(); + CuratorFramework client = CuratorFrameworkFactory.builder() + .connectString(server.getConnectString()) + .retryPolicy(new RetryOneTime(1)) + .build(); + try { + client.start(); + + final String path = "/"; + final AtomicBoolean removedFlag = new AtomicBoolean(false); + final CountDownLatch removedLatch = new CountDownLatch(1); + + Watcher watcher1 = new BooleanWatcher(path, removedFlag, EventType.DataWatchRemoved); + Watcher watcher2 = new CountDownWatcher(path, removedLatch, EventType.ChildWatchRemoved); + + client.checkExists().usingWatcher(watcher1).forPath(path); + client.getChildren().usingWatcher(watcher2).forPath(path); + + client.watches().removeAll().ofType(WatcherType.Children).forPath(path); + + assertTrue(timing.awaitLatch(removedLatch), "Timed out waiting for watch removal"); + assertEquals(removedFlag.get(), false); + } finally { + CloseableUtils.closeQuietly(client); + } + } + + @Test + public void testRemoveLocalWatch() throws Exception { + Timing timing = new Timing(); + CuratorFrameworkImpl client = (CuratorFrameworkImpl) CuratorFrameworkFactory.builder() + .connectString(server.getConnectString()) + .retryPolicy(new RetryOneTime(1)) + .build(); + try { + client.start(); + + AtomicReference stateRef = registerConnectionStateListener(client); + + final String path = "/"; + + final CountDownLatch removedLatch = new CountDownLatch(1); + + Watcher watcher = new CountDownWatcher(path, removedLatch, EventType.DataWatchRemoved); + + client.checkExists().usingWatcher(watcher).forPath(path); + + // Stop the server so we can check if we can remove watches locally when offline + server.stop(); + + assertTrue(blockUntilDesiredConnectionState(stateRef, timing, ConnectionState.SUSPENDED)); + + client.watches().removeAll().locally().forPath(path); + + assertTrue(timing.awaitLatch(removedLatch), "Timed out waiting for watch removal"); + } finally { + CloseableUtils.closeQuietly(client); + } + } + + @Test + public void testRemoveLocalWatchInBackground() throws Exception { + Timing timing = new Timing(); + CuratorFrameworkImpl client = (CuratorFrameworkImpl) CuratorFrameworkFactory.builder() + .connectString(server.getConnectString()) + .retryPolicy(new RetryOneTime(1)) + .build(); + try { + client.start(); + + AtomicReference stateRef = registerConnectionStateListener(client); + + final String path = "/"; + + final CountDownLatch removedLatch = new CountDownLatch(1); + + Watcher watcher = new CountDownWatcher(path, removedLatch, EventType.DataWatchRemoved); + + client.checkExists().usingWatcher(watcher).forPath(path); + + // Stop the server so we can check if we can remove watches locally when offline + server.stop(); + + assertTrue(blockUntilDesiredConnectionState(stateRef, timing, ConnectionState.SUSPENDED)); + + client.watches().removeAll().locally().inBackground().forPath(path); + + assertTrue(timing.awaitLatch(removedLatch), "Timed out waiting for watch removal"); + } finally { + CloseableUtils.closeQuietly(client); + } + } + + /** + * Test the case where we try and remove an unregistered watcher. In this case we expect a NoWatcherException to + * be thrown. + * @throws Exception + */ + @Test + public void testRemoveUnregisteredWatcher() throws Exception { + CuratorFramework client = CuratorFrameworkFactory.builder() + .connectString(server.getConnectString()) + .retryPolicy(new RetryOneTime(1)) + .build(); + try { + client.start(); + + final String path = "/"; + Watcher watcher = new Watcher() { + @Override + public void process(WatchedEvent event) {} + }; + + try { + client.watches().remove(watcher).forPath(path); + fail("Expected KeeperException.NoWatcherException"); + } catch (KeeperException.NoWatcherException expected) { + // expected + } + } finally { + CloseableUtils.closeQuietly(client); + } + } + + /** + * Test the case where we try and remove an unregistered watcher but have the quietly flag set. In this case we expect success. + * @throws Exception + */ + @Test + public void testRemoveUnregisteredWatcherQuietly() throws Exception { + Timing timing = new Timing(); + CuratorFramework client = CuratorFrameworkFactory.builder() + .connectString(server.getConnectString()) + .retryPolicy(new RetryOneTime(1)) + .build(); + try { + client.start(); + + final AtomicBoolean watcherRemoved = new AtomicBoolean(false); + + final String path = "/"; + Watcher watcher = new BooleanWatcher(path, watcherRemoved, EventType.DataWatchRemoved); + + client.watches().remove(watcher).quietly().forPath(path); + + timing.sleepABit(); + + // There should be no watcher removed as none were registered. + assertEquals(watcherRemoved.get(), false); + } finally { + CloseableUtils.closeQuietly(client); + } + } + + @Test + public void testGuaranteedRemoveWatch() throws Exception { + Timing timing = new Timing(); + CuratorFramework client = CuratorFrameworkFactory.builder() + .connectString(server.getConnectString()) + .retryPolicy(new RetryOneTime(1)) + .build(); + try { + client.start(); + + AtomicReference stateRef = registerConnectionStateListener(client); + + String path = "/"; + + CountDownLatch removeLatch = new CountDownLatch(1); + + Watcher watcher = new CountDownWatcher(path, removeLatch, EventType.DataWatchRemoved); + client.checkExists().usingWatcher(watcher).forPath(path); + + server.stop(); + + assertTrue(blockUntilDesiredConnectionState(stateRef, timing, ConnectionState.SUSPENDED)); + + // Remove the watch while we're not connected + try { + client.watches().remove(watcher).guaranteed().forPath(path); + fail(); + } catch (KeeperException.ConnectionLossException e) { + // Expected + } + + server.restart(); + + timing.awaitLatch(removeLatch); + } finally { + CloseableUtils.closeQuietly(client); + } + } + + @Test + public void testGuaranteedRemoveWatchInBackground() throws Exception { + Timing timing = new Timing(); + CuratorFramework client = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), timing.connection(), new ExponentialBackoffRetry(100, 3)); + try { + client.start(); + + AtomicReference stateRef = registerConnectionStateListener(client); + + final CountDownLatch guaranteeAddedLatch = new CountDownLatch(1); + + ((CuratorFrameworkImpl) client).getFailedRemoveWatcherManager().debugListener = + new FailedOperationManager.FailedOperationManagerListener< + FailedRemoveWatchManager.FailedRemoveWatchDetails>() { + + @Override + public void pathAddedForGuaranteedOperation(FailedRemoveWatchDetails detail) { + guaranteeAddedLatch.countDown(); + } + }; + + String path = "/"; + + CountDownLatch removeLatch = new CountDownLatch(1); + + Watcher watcher = new CountDownWatcher(path, removeLatch, EventType.DataWatchRemoved); + client.checkExists().usingWatcher(watcher).forPath(path); + + server.stop(); + assertTrue(blockUntilDesiredConnectionState(stateRef, timing, ConnectionState.SUSPENDED)); + + // Remove the watch while we're not connected + client.watches().remove(watcher).guaranteed().inBackground().forPath(path); + + timing.awaitLatch(guaranteeAddedLatch); + + server.restart(); + + timing.awaitLatch(removeLatch); + } finally { + CloseableUtils.closeQuietly(client); + } + } + + @Test + @Tag(CuratorTestBase.zk36Group) + public void testPersistentWatch() throws Exception { + try (CuratorFramework client = + CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1))) { + client.start(); + client.blockUntilConnected(); + + CountDownLatch latch = new CountDownLatch(3); + Watcher watcher = event -> latch.countDown(); + client.watchers() + .add() + .withMode(AddWatchMode.PERSISTENT) + .usingWatcher(watcher) + .forPath("/test/foo"); + + client.create().creatingParentsIfNeeded().forPath("/test/foo"); + client.setData().forPath("/test/foo", "hey".getBytes()); + client.delete().forPath("/test/foo"); + + assertTrue(timing.awaitLatch(latch)); + } + } + + @Test + @Tag(CuratorTestBase.zk36Group) + public void testPersistentWatchInBackground() throws Exception { + try (CuratorFramework client = + CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1))) { + client.start(); + client.blockUntilConnected(); + + CountDownLatch backgroundLatch = new CountDownLatch(1); + BackgroundCallback backgroundCallback = (__, ___) -> backgroundLatch.countDown(); + CountDownLatch latch = new CountDownLatch(3); + Watcher watcher = event -> latch.countDown(); + client.watchers() + .add() + .withMode(AddWatchMode.PERSISTENT) + .inBackground(backgroundCallback) + .usingWatcher(watcher) + .forPath("/test/foo"); + + client.create().creatingParentsIfNeeded().forPath("/test/foo"); + client.setData().forPath("/test/foo", "hey".getBytes()); + client.delete().forPath("/test/foo"); + + assertTrue(timing.awaitLatch(backgroundLatch)); + assertTrue(timing.awaitLatch(latch)); + } + } + + @Test + @Tag(CuratorTestBase.zk36Group) + public void testPersistentRecursiveWatch() throws Exception { + try (CuratorFramework client = + CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1))) { + client.start(); + client.blockUntilConnected(); + + CountDownLatch latch = new CountDownLatch(5); + Watcher watcher = event -> latch.countDown(); + client.watchers() + .add() + .withMode(AddWatchMode.PERSISTENT_RECURSIVE) + .usingWatcher(watcher) + .forPath("/test"); + + client.create().forPath("/test"); + client.create().forPath("/test/a"); + client.create().forPath("/test/a/b"); + client.create().forPath("/test/a/b/c"); + client.create().forPath("/test/a/b/c/d"); + + assertTrue(timing.awaitLatch(latch)); + } + } + + @Test + @Tag(CuratorTestBase.zk36Group) + public void testPersistentRecursiveWatchInBackground() throws Exception { + try (CuratorFramework client = + CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1))) { + client.start(); + client.blockUntilConnected(); + + CountDownLatch backgroundLatch = new CountDownLatch(1); + BackgroundCallback backgroundCallback = (__, ___) -> backgroundLatch.countDown(); + CountDownLatch latch = new CountDownLatch(5); + Watcher watcher = event -> latch.countDown(); + client.watchers() + .add() + .withMode(AddWatchMode.PERSISTENT_RECURSIVE) + .inBackground(backgroundCallback) + .usingWatcher(watcher) + .forPath("/test"); + + client.create().forPath("/test"); + client.create().forPath("/test/a"); + client.create().forPath("/test/a/b"); + client.create().forPath("/test/a/b/c"); + client.create().forPath("/test/a/b/c/d"); + + assertTrue(timing.awaitLatch(backgroundLatch)); + assertTrue(timing.awaitLatch(latch)); + } + } + + @Test + @Tag(CuratorTestBase.zk36Group) + public void testPersistentRecursiveDefaultWatch() throws Exception { + CountDownLatch latch = new CountDownLatch(6); // 5 creates plus the initial sync + ZookeeperFactory zookeeperFactory = (connectString, sessionTimeout, watcher, canBeReadOnly) -> { + Watcher actualWatcher = event -> { + watcher.process(event); + latch.countDown(); + }; + return new ZooKeeper(connectString, sessionTimeout, actualWatcher); + }; + try (CuratorFramework client = CuratorFrameworkFactory.builder() + .connectString(server.getConnectString()) + .retryPolicy(new RetryOneTime(1)) + .zookeeperFactory(zookeeperFactory) + .build()) { + client.start(); + client.blockUntilConnected(); + + client.watchers().add().withMode(AddWatchMode.PERSISTENT_RECURSIVE).forPath("/test"); + + client.create().forPath("/test"); + client.create().forPath("/test/a"); + client.create().forPath("/test/a/b"); + client.create().forPath("/test/a/b/c"); + client.create().forPath("/test/a/b/c/d"); + + assertTrue(timing.awaitLatch(latch)); + } + } + + private static class CountDownWatcher implements Watcher { + private String path; + private EventType eventType; + private CountDownLatch removeLatch; + + public CountDownWatcher(String path, CountDownLatch removeLatch, EventType eventType) { + this.path = path; + this.eventType = eventType; + this.removeLatch = removeLatch; + } + + @Override + public void process(WatchedEvent event) { + if (event.getPath() == null || event.getType() == null) { + return; + } + + if (event.getPath().equals(path) && event.getType() == eventType) { + removeLatch.countDown(); + } + } + } + + private static class BooleanWatcher implements Watcher { + private String path; + private EventType eventType; + private AtomicBoolean removedFlag; + + public BooleanWatcher(String path, AtomicBoolean removedFlag, EventType eventType) { + this.path = path; + this.eventType = eventType; + this.removedFlag = removedFlag; + } + + @Override + public void process(WatchedEvent event) { + if (event.getPath() == null || event.getType() == null) { + return; + } + + if (event.getPath().equals(path) && event.getType() == eventType) { + removedFlag.set(true); + } + } + } +} diff --git a/curator-framework/src/test/java/org/apache/curator/framework/imps/TestWithCluster.java b/curator-framework/src/test/java/org/apache/curator/framework/imps/TestWithCluster.java index ee6149bef..a10dcea9c 100644 --- a/curator-framework/src/test/java/org/apache/curator/framework/imps/TestWithCluster.java +++ b/curator-framework/src/test/java/org/apache/curator/framework/imps/TestWithCluster.java @@ -21,9 +21,7 @@ import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; - -import org.apache.curator.test.compatibility.CuratorTestBase; -import org.apache.curator.utils.CloseableUtils; +import java.util.concurrent.CountDownLatch; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.state.ConnectionState; @@ -33,34 +31,33 @@ import org.apache.curator.test.InstanceSpec; import org.apache.curator.test.TestingCluster; import org.apache.curator.test.Timing; +import org.apache.curator.test.compatibility.CuratorTestBase; +import org.apache.curator.utils.CloseableUtils; import org.apache.zookeeper.CreateMode; import org.junit.jupiter.api.Test; -import java.util.concurrent.CountDownLatch; - -public class TestWithCluster extends CuratorTestBase -{ +public class TestWithCluster extends CuratorTestBase { @Test - public void testSessionSurvives() throws Exception - { - Timing timing = new Timing(); - - CuratorFramework client = null; - TestingCluster cluster = createAndStartCluster(3); - try - { - client = CuratorFrameworkFactory.newClient(cluster.getConnectString(), timing.session(), timing.connection(), new ExponentialBackoffRetry(100, 3)); + public void testSessionSurvives() throws Exception { + Timing timing = new Timing(); + + CuratorFramework client = null; + TestingCluster cluster = createAndStartCluster(3); + try { + client = CuratorFrameworkFactory.newClient( + cluster.getConnectString(), + timing.session(), + timing.connection(), + new ExponentialBackoffRetry(100, 3)); client.start(); final CountDownLatch reconnectedLatch = new CountDownLatch(1); - ConnectionStateListener listener = new ConnectionStateListener() - { + ConnectionStateListener listener = new ConnectionStateListener() { @Override - public void stateChanged(CuratorFramework client, ConnectionState newState) - { - if ( newState == ConnectionState.RECONNECTED ) - { - reconnectedLatch.countDown();; + public void stateChanged(CuratorFramework client, ConnectionState newState) { + if (newState == ConnectionState.RECONNECTED) { + reconnectedLatch.countDown(); + ; } } }; @@ -69,8 +66,7 @@ public void stateChanged(CuratorFramework client, ConnectionState newState) client.create().withMode(CreateMode.EPHEMERAL).forPath("/temp", "value".getBytes()); assertNotNull(client.checkExists().forPath("/temp")); - for ( InstanceSpec spec : cluster.getInstances() ) - { + for (InstanceSpec spec : cluster.getInstances()) { cluster.killServer(spec); timing.sleepABit(); cluster.restartServer(spec); @@ -79,26 +75,21 @@ public void stateChanged(CuratorFramework client, ConnectionState newState) assertTrue(timing.awaitLatch(reconnectedLatch)); assertNotNull(client.checkExists().forPath("/temp")); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); CloseableUtils.closeQuietly(cluster); } } @Test - public void testSplitBrain() throws Exception - { - Timing timing = new Timing(); + public void testSplitBrain() throws Exception { + Timing timing = new Timing(); - CuratorFramework client = null; + CuratorFramework client = null; TestingCluster cluster = createAndStartCluster(3); - try - { + try { // make sure all instances are up - for ( InstanceSpec instanceSpec : cluster.getInstances() ) - { + for (InstanceSpec instanceSpec : cluster.getInstances()) { client = CuratorFrameworkFactory.newClient(instanceSpec.getConnectString(), new RetryOneTime(1)); client.start(); client.checkExists().forPath("/"); @@ -106,47 +97,38 @@ public void testSplitBrain() throws Exception client = null; } - client = CuratorFrameworkFactory.newClient(cluster.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); + client = CuratorFrameworkFactory.newClient( + cluster.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); client.start(); - final CountDownLatch latch = new CountDownLatch(2); - client.getConnectionStateListenable().addListener - ( - new ConnectionStateListener() - { - @Override - public void stateChanged(CuratorFramework client, ConnectionState newState) - { - if ( (newState == ConnectionState.SUSPENDED) || (newState == ConnectionState.LOST) ) - { - latch.countDown(); - } + final CountDownLatch latch = new CountDownLatch(2); + client.getConnectionStateListenable().addListener(new ConnectionStateListener() { + @Override + public void stateChanged(CuratorFramework client, ConnectionState newState) { + if ((newState == ConnectionState.SUSPENDED) || (newState == ConnectionState.LOST)) { + latch.countDown(); } } - ); + }); client.checkExists().forPath("/"); - for ( InstanceSpec instanceSpec : cluster.getInstances() ) - { - if ( !instanceSpec.equals(cluster.findConnectionInstance(client.getZookeeperClient().getZooKeeper())) ) - { + for (InstanceSpec instanceSpec : cluster.getInstances()) { + if (!instanceSpec.equals(cluster.findConnectionInstance( + client.getZookeeperClient().getZooKeeper()))) { assertTrue(cluster.killServer(instanceSpec)); } } assertTrue(timing.awaitLatch(latch)); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); CloseableUtils.closeQuietly(cluster); } } @Override - protected void createServer() throws Exception - { + protected void createServer() throws Exception { // NOP } } diff --git a/curator-framework/src/test/java/org/apache/curator/framework/schema/TestSchema.java b/curator-framework/src/test/java/org/apache/curator/framework/schema/TestSchema.java index 60ab05805..aa9b8692d 100644 --- a/curator-framework/src/test/java/org/apache/curator/framework/schema/TestSchema.java +++ b/curator-framework/src/test/java/org/apache/curator/framework/schema/TestSchema.java @@ -28,6 +28,9 @@ import com.google.common.base.Charsets; import com.google.common.collect.Maps; import com.google.common.io.Resources; +import java.io.IOException; +import java.util.List; +import java.util.Map; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.api.transaction.CuratorOp; @@ -38,15 +41,9 @@ import org.apache.zookeeper.data.ACL; import org.junit.jupiter.api.Test; -import java.io.IOException; -import java.util.List; -import java.util.Map; - -public class TestSchema extends BaseClassForTests -{ +public class TestSchema extends BaseClassForTests { @Test - public void testBasics() throws Exception - { + public void testBasics() throws Exception { SchemaSet schemaSet = loadSchemaSet("schema1.json", null); Schema schema = schemaSet.getNamedSchema("test"); assertNotNull(schema); @@ -56,193 +53,154 @@ public void testBasics() throws Exception assertEquals(schema.getMetadata(), expectedMetadata); CuratorFramework client = newClient(schemaSet); - try - { + try { client.start(); - try - { + try { String rawPath = schema.getRawPath(); assertEquals(rawPath, "/a/b/c"); client.create().creatingParentsIfNeeded().forPath(rawPath); fail("Should've violated schema"); - } - catch ( SchemaViolation dummy ) - { + } catch (SchemaViolation dummy) { // expected } - client.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL).forPath("/a/b/c"); - } - finally - { + client.create() + .creatingParentsIfNeeded() + .withMode(CreateMode.EPHEMERAL) + .forPath("/a/b/c"); + } finally { CloseableUtils.closeQuietly(client); } } @Test - public void testSchemaValidator() throws Exception - { - final SchemaValidator schemaValidator = new SchemaValidator() - { + public void testSchemaValidator() throws Exception { + final SchemaValidator schemaValidator = new SchemaValidator() { @Override - public boolean isValid(Schema schema, String path, byte[] data, List acl) - { + public boolean isValid(Schema schema, String path, byte[] data, List acl) { return data.length > 0; } }; - SchemaSetLoader.SchemaValidatorMapper schemaValidatorMapper = new SchemaSetLoader.SchemaValidatorMapper() - { + SchemaSetLoader.SchemaValidatorMapper schemaValidatorMapper = new SchemaSetLoader.SchemaValidatorMapper() { @Override - public SchemaValidator getSchemaValidator(String name) - { + public SchemaValidator getSchemaValidator(String name) { return schemaValidator; } }; SchemaSet schemaSet = loadSchemaSet("schema3.json", schemaValidatorMapper); CuratorFramework client = newClient(schemaSet); - try - { + try { client.start(); - try - { + try { client.create().forPath("/test", new byte[0]); fail("Should've violated schema"); - } - catch ( SchemaViolation dummy ) - { + } catch (SchemaViolation dummy) { // expected } client.create().forPath("/test", "good".getBytes()); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } @Test - public void testMulti() throws Exception - { + public void testMulti() throws Exception { SchemaSet schemaSet = loadSchemaSet("schema2.json", null); CuratorFramework client = newClient(schemaSet); - try - { + try { client.start(); - try - { + try { client.create().creatingParentsIfNeeded().forPath("/a/b/c"); fail("Should've violated schema: test"); - } - catch ( SchemaViolation dummy ) - { + } catch (SchemaViolation dummy) { // expected } - try - { - client.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL).forPath("/a/b/c/d/e"); + try { + client.create() + .creatingParentsIfNeeded() + .withMode(CreateMode.EPHEMERAL) + .forPath("/a/b/c/d/e"); fail("Should've violated schema: test2"); - } - catch ( SchemaViolation dummy ) - { + } catch (SchemaViolation dummy) { // expected } - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } @Test - public void testTransaction() throws Exception - { - final SchemaValidator schemaValidator = new SchemaValidator() - { + public void testTransaction() throws Exception { + final SchemaValidator schemaValidator = new SchemaValidator() { @Override - public boolean isValid(Schema schema, String path, byte[] data, List acl) - { + public boolean isValid(Schema schema, String path, byte[] data, List acl) { return data.length > 0; } }; - SchemaSetLoader.SchemaValidatorMapper schemaValidatorMapper = new SchemaSetLoader.SchemaValidatorMapper() - { + SchemaSetLoader.SchemaValidatorMapper schemaValidatorMapper = new SchemaSetLoader.SchemaValidatorMapper() { @Override - public SchemaValidator getSchemaValidator(String name) - { + public SchemaValidator getSchemaValidator(String name) { return schemaValidator; } }; SchemaSet schemaSet = loadSchemaSet("schema4.json", schemaValidatorMapper); CuratorFramework client = newClient(schemaSet); - try - { + try { client.start(); CuratorOp createAPersistent = client.transactionOp().create().forPath("/a"); - CuratorOp createAEphemeral = client.transactionOp().create().withMode(CreateMode.EPHEMERAL).forPath("/a"); + CuratorOp createAEphemeral = client.transactionOp() + .create() + .withMode(CreateMode.EPHEMERAL) + .forPath("/a"); CuratorOp deleteA = client.transactionOp().delete().forPath("/a"); CuratorOp createBEmptyData = client.transactionOp().create().forPath("/b", new byte[0]); CuratorOp createBWithData = client.transactionOp().create().forPath("/b", new byte[10]); CuratorOp setBEmptyData = client.transactionOp().setData().forPath("/b", new byte[0]); CuratorOp setBWithData = client.transactionOp().setData().forPath("/b", new byte[10]); - try - { + try { client.transaction().forOperations(createAPersistent, createAEphemeral); fail("Should've violated schema"); - } - catch ( SchemaViolation dummy ) - { + } catch (SchemaViolation dummy) { // expected } client.transaction().forOperations(createAEphemeral); - try - { + try { client.transaction().forOperations(deleteA); fail("Should've violated schema"); - } - catch ( SchemaViolation dummy ) - { + } catch (SchemaViolation dummy) { // expected } - try - { + try { client.transaction().forOperations(createBEmptyData); fail("Should've violated schema"); - } - catch ( SchemaViolation dummy ) - { + } catch (SchemaViolation dummy) { // expected } client.transaction().forOperations(createBWithData); - try - { + try { client.transaction().forOperations(setBEmptyData); fail("Should've violated schema"); - } - catch ( SchemaViolation dummy ) - { + } catch (SchemaViolation dummy) { // expected } client.transaction().forOperations(setBWithData); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } @Test - public void testYaml() throws Exception - { + public void testYaml() throws Exception { String yaml = Resources.toString(Resources.getResource("schema.yaml"), Charsets.UTF_8); JsonNode root = new ObjectMapper(new YAMLFactory()).readTree(yaml); List schemas = new SchemaSetLoader(root, null).getSchemas(); @@ -255,65 +213,69 @@ public void testYaml() throws Exception } @Test - public void testOrdering() throws Exception - { + public void testOrdering() throws Exception { SchemaSet schemaSet = loadSchemaSet("schema5.json", null); CuratorFramework client = newClient(schemaSet); - try - { + try { client.start(); - try - { - client.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL).forPath("/exact/match"); + try { + client.create() + .creatingParentsIfNeeded() + .withMode(CreateMode.EPHEMERAL) + .forPath("/exact/match"); fail("Should've violated schema"); - } - catch ( SchemaViolation dummy ) - { + } catch (SchemaViolation dummy) { // expected } - try - { - client.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL_SEQUENTIAL).forPath("/exact/foo/bar"); + try { + client.create() + .creatingParentsIfNeeded() + .withMode(CreateMode.EPHEMERAL_SEQUENTIAL) + .forPath("/exact/foo/bar"); fail("Should've violated schema"); - } - catch ( SchemaViolation dummy ) - { + } catch (SchemaViolation dummy) { // expected } - try - { - client.create().creatingParentsIfNeeded().withMode(CreateMode.PERSISTENT_SEQUENTIAL).forPath("/exact/other/bar"); + try { + client.create() + .creatingParentsIfNeeded() + .withMode(CreateMode.PERSISTENT_SEQUENTIAL) + .forPath("/exact/other/bar"); fail("Should've violated schema"); - } - catch ( SchemaViolation dummy ) - { + } catch (SchemaViolation dummy) { // expected } - client.create().creatingParentsIfNeeded().withMode(CreateMode.PERSISTENT_SEQUENTIAL).forPath("/exact/match"); // schema "1" - client.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL_SEQUENTIAL).forPath("/exact/other/thing"); // schema "2" - client.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL).forPath("/exact/foo/bar"); // schema "3" - } - finally - { + client.create() + .creatingParentsIfNeeded() + .withMode(CreateMode.PERSISTENT_SEQUENTIAL) + .forPath("/exact/match"); // schema "1" + client.create() + .creatingParentsIfNeeded() + .withMode(CreateMode.EPHEMERAL_SEQUENTIAL) + .forPath("/exact/other/thing"); // schema "2" + client.create() + .creatingParentsIfNeeded() + .withMode(CreateMode.EPHEMERAL) + .forPath("/exact/foo/bar"); // schema "3" + } finally { CloseableUtils.closeQuietly(client); } } - private CuratorFramework newClient(SchemaSet schemaSet) - { + private CuratorFramework newClient(SchemaSet schemaSet) { return CuratorFrameworkFactory.builder() - .connectString(server.getConnectString()) - .retryPolicy(new RetryOneTime(1)) - .schemaSet(schemaSet) - .build(); + .connectString(server.getConnectString()) + .retryPolicy(new RetryOneTime(1)) + .schemaSet(schemaSet) + .build(); } - private SchemaSet loadSchemaSet(String name, SchemaSetLoader.SchemaValidatorMapper schemaValidatorMapper) throws IOException - { + private SchemaSet loadSchemaSet(String name, SchemaSetLoader.SchemaValidatorMapper schemaValidatorMapper) + throws IOException { String json = Resources.toString(Resources.getResource(name), Charsets.UTF_8); return new SchemaSetLoader(json, schemaValidatorMapper).toSchemaSet(true); } diff --git a/curator-framework/src/test/java/org/apache/curator/framework/state/TestCircuitBreaker.java b/curator-framework/src/test/java/org/apache/curator/framework/state/TestCircuitBreaker.java index 12ccfb798..625c7542f 100644 --- a/curator-framework/src/test/java/org/apache/curator/framework/state/TestCircuitBreaker.java +++ b/curator-framework/src/test/java/org/apache/curator/framework/state/TestCircuitBreaker.java @@ -22,27 +22,24 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; -import org.apache.curator.RetryPolicy; -import org.apache.curator.retry.RetryForever; -import org.apache.curator.retry.RetryNTimes; -import org.apache.curator.retry.RetryUntilElapsed; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.Test; import java.time.Duration; import java.time.temporal.ChronoUnit; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; +import org.apache.curator.RetryPolicy; +import org.apache.curator.retry.RetryForever; +import org.apache.curator.retry.RetryNTimes; +import org.apache.curator.retry.RetryUntilElapsed; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.Test; -public class TestCircuitBreaker -{ - private static Duration[] lastDelay = new Duration[]{Duration.ZERO}; - private static ScheduledThreadPoolExecutor service = new ScheduledThreadPoolExecutor(1) - { +public class TestCircuitBreaker { + private static Duration[] lastDelay = new Duration[] {Duration.ZERO}; + private static ScheduledThreadPoolExecutor service = new ScheduledThreadPoolExecutor(1) { @Override - public ScheduledFuture schedule(Runnable command, long delay, TimeUnit unit) - { + public ScheduledFuture schedule(Runnable command, long delay, TimeUnit unit) { lastDelay[0] = Duration.of(unit.toNanos(delay), ChronoUnit.NANOS); command.run(); return null; @@ -50,18 +47,17 @@ public ScheduledFuture schedule(Runnable command, long delay, TimeUnit unit) }; @AfterAll - public static void tearDown() - { + public static void tearDown() { service.shutdownNow(); } @Test - public void testBasic() - { + public void testBasic() { final int retryQty = 1; final Duration delay = Duration.ofSeconds(10); - CircuitBreaker circuitBreaker = CircuitBreaker.build(new RetryNTimes(retryQty, (int)delay.toMillis()), service); + CircuitBreaker circuitBreaker = + CircuitBreaker.build(new RetryNTimes(retryQty, (int) delay.toMillis()), service); AtomicInteger counter = new AtomicInteger(0); assertTrue(circuitBreaker.tryToOpen(counter::incrementAndGet)); @@ -80,8 +76,7 @@ public void testBasic() } @Test - public void testVariousOpenRetryFails() - { + public void testVariousOpenRetryFails() { CircuitBreaker circuitBreaker = CircuitBreaker.build(new RetryForever(1), service); assertFalse(circuitBreaker.tryToRetry(() -> {})); assertTrue(circuitBreaker.tryToOpen(() -> {})); @@ -91,8 +86,7 @@ public void testVariousOpenRetryFails() } @Test - public void testWithRetryUntilElapsed() - { + public void testWithRetryUntilElapsed() { RetryPolicy retryPolicy = new RetryUntilElapsed(10000, 10000); CircuitBreaker circuitBreaker = CircuitBreaker.build(retryPolicy, service); assertTrue(circuitBreaker.tryToOpen(() -> {})); diff --git a/curator-framework/src/test/java/org/apache/curator/framework/state/TestCircuitBreakingConnectionStateListener.java b/curator-framework/src/test/java/org/apache/curator/framework/state/TestCircuitBreakingConnectionStateListener.java index 84aba9c5d..3a4fa5891 100644 --- a/curator-framework/src/test/java/org/apache/curator/framework/state/TestCircuitBreakingConnectionStateListener.java +++ b/curator-framework/src/test/java/org/apache/curator/framework/state/TestCircuitBreakingConnectionStateListener.java @@ -22,6 +22,9 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.ScheduledThreadPoolExecutor; import org.apache.curator.RetryPolicy; import org.apache.curator.RetrySleeper; import org.apache.curator.framework.CuratorFramework; @@ -32,81 +35,72 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.LinkedBlockingQueue; -import java.util.concurrent.ScheduledThreadPoolExecutor; @SuppressWarnings("SynchronizationOnLocalVariableOrMethodParameter") -public class TestCircuitBreakingConnectionStateListener -{ +public class TestCircuitBreakingConnectionStateListener { private final CuratorFramework dummyClient = CuratorFrameworkFactory.newClient("foo", new RetryOneTime(1)); private final Timing2 timing = new Timing2(); private final Timing2 retryTiming = timing.multiple(.25); private volatile ScheduledThreadPoolExecutor service; - private static class RecordingListener implements ConnectionStateListener - { + private static class RecordingListener implements ConnectionStateListener { final BlockingQueue stateChanges = new LinkedBlockingQueue<>(); @Override - public void stateChanged(CuratorFramework client, ConnectionState newState) - { + public void stateChanged(CuratorFramework client, ConnectionState newState) { stateChanges.offer(newState); } } - private class TestRetryPolicy extends RetryForever - { + private class TestRetryPolicy extends RetryForever { volatile boolean isRetrying = true; - public TestRetryPolicy() - { + public TestRetryPolicy() { super(retryTiming.milliseconds()); } @Override - public boolean allowRetry(int retryCount, long elapsedTimeMs, RetrySleeper sleeper) - { + public boolean allowRetry(int retryCount, long elapsedTimeMs, RetrySleeper sleeper) { return isRetrying && super.allowRetry(retryCount, elapsedTimeMs, sleeper); } } @BeforeEach - public void setup() - { + public void setup() { service = new ScheduledThreadPoolExecutor(1); } @AfterEach - public void tearDown() - { + public void tearDown() { service.shutdownNow(); } @Test - public void testBasic() throws Exception - { + public void testBasic() throws Exception { RecordingListener recordingListener = new RecordingListener(); TestRetryPolicy retryPolicy = new TestRetryPolicy(); - CircuitBreakingConnectionStateListener listener = new CircuitBreakingConnectionStateListener(dummyClient, recordingListener, retryPolicy, service); + CircuitBreakingConnectionStateListener listener = + new CircuitBreakingConnectionStateListener(dummyClient, recordingListener, retryPolicy, service); listener.stateChanged(dummyClient, ConnectionState.RECONNECTED); assertEquals(timing.takeFromQueue(recordingListener.stateChanges), ConnectionState.RECONNECTED); listener.stateChanged(dummyClient, ConnectionState.SUSPENDED); assertEquals(timing.takeFromQueue(recordingListener.stateChanges), ConnectionState.SUSPENDED); - listener.stateChanged(dummyClient, ConnectionState.SUSPENDED); // 2nd suspended is ignored + listener.stateChanged(dummyClient, ConnectionState.SUSPENDED); // 2nd suspended is ignored assertTrue(recordingListener.stateChanges.isEmpty()); listener.stateChanged(dummyClient, ConnectionState.LOST); assertEquals(timing.takeFromQueue(recordingListener.stateChanges), ConnectionState.LOST); - synchronized(listener) // don't let retry policy run while we're pushing state changes + synchronized (listener) // don't let retry policy run while we're pushing state changes { - listener.stateChanged(dummyClient, ConnectionState.READ_ONLY); // all further events are ignored - listener.stateChanged(dummyClient, ConnectionState.RECONNECTED); // all further events are ignored - listener.stateChanged(dummyClient, ConnectionState.SUSPENDED); // all further events are ignored - listener.stateChanged(dummyClient, ConnectionState.LOST); // all further events are ignored - listener.stateChanged(dummyClient, ConnectionState.SUSPENDED); // all further events are ignored - this will be the last event + listener.stateChanged(dummyClient, ConnectionState.READ_ONLY); // all further events are ignored + listener.stateChanged(dummyClient, ConnectionState.RECONNECTED); // all further events are ignored + listener.stateChanged(dummyClient, ConnectionState.SUSPENDED); // all further events are ignored + listener.stateChanged(dummyClient, ConnectionState.LOST); // all further events are ignored + listener.stateChanged( + dummyClient, + ConnectionState.SUSPENDED); // all further events are ignored - this will be the last event } retryTiming.multiple(2).sleep(); assertTrue(recordingListener.stateChanges.isEmpty()); @@ -116,30 +110,30 @@ public void testBasic() throws Exception } @Test - public void testResetsAfterReconnect() throws Exception - { + public void testResetsAfterReconnect() throws Exception { RecordingListener recordingListener = new RecordingListener(); TestRetryPolicy retryPolicy = new TestRetryPolicy(); - CircuitBreakingConnectionStateListener listener = new CircuitBreakingConnectionStateListener(dummyClient, recordingListener, retryPolicy, service); + CircuitBreakingConnectionStateListener listener = + new CircuitBreakingConnectionStateListener(dummyClient, recordingListener, retryPolicy, service); - synchronized(listener) // don't let retry policy run while we're pushing state changes + synchronized (listener) // don't let retry policy run while we're pushing state changes { listener.stateChanged(dummyClient, ConnectionState.LOST); - listener.stateChanged(dummyClient, ConnectionState.LOST); // second LOST ignored + listener.stateChanged(dummyClient, ConnectionState.LOST); // second LOST ignored } assertEquals(timing.takeFromQueue(recordingListener.stateChanges), ConnectionState.LOST); assertTrue(recordingListener.stateChanges.isEmpty()); - listener.stateChanged(dummyClient, ConnectionState.RECONNECTED); // causes circuit to close on next retry + listener.stateChanged(dummyClient, ConnectionState.RECONNECTED); // causes circuit to close on next retry assertEquals(timing.takeFromQueue(recordingListener.stateChanges), ConnectionState.RECONNECTED); } @Test - public void testRetryNever() throws Exception - { + public void testRetryNever() throws Exception { RecordingListener recordingListener = new RecordingListener(); RetryPolicy retryNever = (retryCount, elapsedTimeMs, sleeper) -> false; - CircuitBreakingConnectionStateListener listener = new CircuitBreakingConnectionStateListener(dummyClient, recordingListener, retryNever, service); + CircuitBreakingConnectionStateListener listener = + new CircuitBreakingConnectionStateListener(dummyClient, recordingListener, retryNever, service); listener.stateChanged(dummyClient, ConnectionState.LOST); assertEquals(timing.takeFromQueue(recordingListener.stateChanges), ConnectionState.LOST); @@ -150,13 +144,13 @@ public void testRetryNever() throws Exception } @Test - public void testRetryOnce() throws Exception - { + public void testRetryOnce() throws Exception { RecordingListener recordingListener = new RecordingListener(); RetryPolicy retryOnce = new RetryOneTime(retryTiming.milliseconds()); - CircuitBreakingConnectionStateListener listener = new CircuitBreakingConnectionStateListener(dummyClient, recordingListener, retryOnce, service); + CircuitBreakingConnectionStateListener listener = + new CircuitBreakingConnectionStateListener(dummyClient, recordingListener, retryOnce, service); - synchronized(listener) // don't let retry policy run while we're pushing state changes + synchronized (listener) // don't let retry policy run while we're pushing state changes { listener.stateChanged(dummyClient, ConnectionState.LOST); listener.stateChanged(dummyClient, ConnectionState.SUSPENDED); @@ -168,11 +162,11 @@ public void testRetryOnce() throws Exception } @Test - public void testSuspendedToLostRatcheting() throws Exception - { + public void testSuspendedToLostRatcheting() throws Exception { RecordingListener recordingListener = new RecordingListener(); RetryPolicy retryInfinite = new RetryForever(Integer.MAX_VALUE); - CircuitBreakingConnectionStateListener listener = new CircuitBreakingConnectionStateListener(dummyClient, recordingListener, retryInfinite, service); + CircuitBreakingConnectionStateListener listener = + new CircuitBreakingConnectionStateListener(dummyClient, recordingListener, retryInfinite, service); listener.stateChanged(dummyClient, ConnectionState.RECONNECTED); assertFalse(listener.isOpen()); diff --git a/curator-framework/src/test/java/org/apache/curator/framework/state/TestConnectionStateManager.java b/curator-framework/src/test/java/org/apache/curator/framework/state/TestConnectionStateManager.java index 0f53ce2f2..97e8943c7 100644 --- a/curator-framework/src/test/java/org/apache/curator/framework/state/TestConnectionStateManager.java +++ b/curator-framework/src/test/java/org/apache/curator/framework/state/TestConnectionStateManager.java @@ -22,8 +22,10 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; - import com.google.common.collect.Queues; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.retry.RetryOneTime; @@ -36,10 +38,6 @@ import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; - public class TestConnectionStateManager extends BaseClassForTests { @Test @@ -47,31 +45,27 @@ public class TestConnectionStateManager extends BaseClassForTests { public void testSessionConnectionStateErrorPolicyWithExpirationPercent30() throws Exception { Timing2 timing = new Timing2(); CuratorFramework client = CuratorFrameworkFactory.builder() - .connectString(server.getConnectString()) - .connectionTimeoutMs(1000) - .sessionTimeoutMs(timing.session()) - .retryPolicy(new RetryOneTime(1)) - .connectionStateErrorPolicy(new SessionConnectionStateErrorPolicy()) - .simulatedSessionExpirationPercent(30) - .build(); + .connectString(server.getConnectString()) + .connectionTimeoutMs(1000) + .sessionTimeoutMs(timing.session()) + .retryPolicy(new RetryOneTime(1)) + .connectionStateErrorPolicy(new SessionConnectionStateErrorPolicy()) + .simulatedSessionExpirationPercent(30) + .build(); // we should get LOST around 30% of a session plus a little "slop" for processing, etc. - final int lostStateExpectedMs = (timing.session() / 3) + timing.forSleepingABit().milliseconds(); - try - { + final int lostStateExpectedMs = + (timing.session() / 3) + timing.forSleepingABit().milliseconds(); + try { CountDownLatch connectedLatch = new CountDownLatch(1); CountDownLatch lostLatch = new CountDownLatch(1); - ConnectionStateListener stateListener = new ConnectionStateListener() - { + ConnectionStateListener stateListener = new ConnectionStateListener() { @Override - public void stateChanged(CuratorFramework client, ConnectionState newState) - { - if ( newState == ConnectionState.CONNECTED ) - { + public void stateChanged(CuratorFramework client, ConnectionState newState) { + if (newState == ConnectionState.CONNECTED) { connectedLatch.countDown(); } - if ( newState == ConnectionState.LOST ) - { + if (newState == ConnectionState.LOST) { lostLatch.countDown(); } } @@ -85,8 +79,7 @@ public void stateChanged(CuratorFramework client, ConnectionState newState) server.close(); assertTrue(lostLatch.await(lostStateExpectedMs, TimeUnit.MILLISECONDS)); - } - finally { + } finally { CloseableUtils.closeQuietly(client); } } @@ -109,19 +102,25 @@ public void testConnectionStateRecoversFromUnexpectedExpiredConnection() throws try { ConnectionState polled = queue.poll(timing.forWaiting().seconds(), TimeUnit.SECONDS); assertEquals(polled, ConnectionState.CONNECTED); - client.getZookeeperClient().getZooKeeper().getTestable().queueEvent(new WatchedEvent( - Watcher.Event.EventType.None, Watcher.Event.KeeperState.Disconnected, null)); + client.getZookeeperClient() + .getZooKeeper() + .getTestable() + .queueEvent(new WatchedEvent( + Watcher.Event.EventType.None, Watcher.Event.KeeperState.Disconnected, null)); polled = queue.poll(timing.forWaiting().seconds(), TimeUnit.SECONDS); assertEquals(polled, ConnectionState.SUSPENDED); assertThrows(RuntimeException.class, () -> client.getZookeeperClient() - .getZooKeeper().getTestable().queueEvent(new WatchedEvent( - Watcher.Event.EventType.None, Watcher.Event.KeeperState.Expired, null) { - @Override - public String getPath() { - // exception will cause ZooKeeper to update current state but fail to notify watchers - throw new RuntimeException("Path doesn't exist!"); - } - })); + .getZooKeeper() + .getTestable() + .queueEvent( + new WatchedEvent(Watcher.Event.EventType.None, Watcher.Event.KeeperState.Expired, null) { + @Override + public String getPath() { + // exception will cause ZooKeeper to update current state but fail to notify + // watchers + throw new RuntimeException("Path doesn't exist!"); + } + })); polled = queue.poll(timing.forWaiting().seconds(), TimeUnit.SECONDS); assertEquals(polled, ConnectionState.LOST); polled = queue.poll(timing.forWaiting().seconds(), TimeUnit.SECONDS); diff --git a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/AfterConnectionEstablished.java b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/AfterConnectionEstablished.java index 3ffdd7d8b..299f9c572 100644 --- a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/AfterConnectionEstablished.java +++ b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/AfterConnectionEstablished.java @@ -19,19 +19,18 @@ package org.apache.curator.framework.recipes; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Future; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.utils.ThreadUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Future; /** * Utility class to allow execution of logic once a ZooKeeper connection becomes available. */ -public class AfterConnectionEstablished -{ - private final static Logger log = LoggerFactory.getLogger(AfterConnectionEstablished.class); +public class AfterConnectionEstablished { + private static final Logger log = LoggerFactory.getLogger(AfterConnectionEstablished.class); /** * Spawns a new new background thread that will block until a connection is available and @@ -41,27 +40,20 @@ public class AfterConnectionEstablished * @param runAfterConnection The logic to run * @return future of the task so it can be canceled, etc. if needed */ - public static Future execute(final CuratorFramework client, final Runnable runAfterConnection) throws Exception - { - //Block until connected - final ExecutorService executor = ThreadUtils.newSingleThreadExecutor(ThreadUtils.getProcessName(runAfterConnection.getClass())); - Runnable internalCall = new Runnable() - { + public static Future execute(final CuratorFramework client, final Runnable runAfterConnection) throws Exception { + // Block until connected + final ExecutorService executor = + ThreadUtils.newSingleThreadExecutor(ThreadUtils.getProcessName(runAfterConnection.getClass())); + Runnable internalCall = new Runnable() { @Override - public void run() - { - try - { + public void run() { + try { client.blockUntilConnected(); runAfterConnection.run(); - } - catch ( Exception e ) - { + } catch (Exception e) { ThreadUtils.checkInterrupted(e); log.error("An error occurred blocking until a connection is available", e); - } - finally - { + } finally { executor.shutdown(); } } @@ -69,7 +61,5 @@ public void run() return executor.submit(internalCall); } - private AfterConnectionEstablished() - { - } + private AfterConnectionEstablished() {} } diff --git a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/atomic/AtomicStats.java b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/atomic/AtomicStats.java index f290b3712..c86f6cf81 100644 --- a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/atomic/AtomicStats.java +++ b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/atomic/AtomicStats.java @@ -22,20 +22,18 @@ /** * Debugging stats about operations */ -public class AtomicStats -{ - private int optimisticTries = 0; - private int promotedLockTries = 0; - private long optimisticTimeMs = 0; - private long promotedTimeMs = 0; +public class AtomicStats { + private int optimisticTries = 0; + private int promotedLockTries = 0; + private long optimisticTimeMs = 0; + private long promotedTimeMs = 0; /** * Returns the number of optimistic locks used to perform the operation * * @return qty */ - public int getOptimisticTries() - { + public int getOptimisticTries() { return optimisticTries; } @@ -44,8 +42,7 @@ public int getOptimisticTries() * * @return qty */ - public int getPromotedLockTries() - { + public int getPromotedLockTries() { return promotedLockTries; } @@ -54,8 +51,7 @@ public int getPromotedLockTries() * * @return time in ms */ - public long getOptimisticTimeMs() - { + public long getOptimisticTimeMs() { return optimisticTimeMs; } @@ -64,28 +60,23 @@ public long getOptimisticTimeMs() * * @return time in ms */ - public long getPromotedTimeMs() - { + public long getPromotedTimeMs() { return promotedTimeMs; } - void incrementOptimisticTries() - { + void incrementOptimisticTries() { ++optimisticTries; } - void incrementPromotedTries() - { + void incrementPromotedTries() { ++promotedLockTries; } - void setOptimisticTimeMs(long optimisticTimeMs) - { + void setOptimisticTimeMs(long optimisticTimeMs) { this.optimisticTimeMs = optimisticTimeMs; } - void setPromotedTimeMs(long promotedTimeMs) - { + void setPromotedTimeMs(long promotedTimeMs) { this.promotedTimeMs = promotedTimeMs; } } diff --git a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/atomic/AtomicValue.java b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/atomic/AtomicValue.java index 7b7d2182b..7d4c9bd78 100644 --- a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/atomic/AtomicValue.java +++ b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/atomic/AtomicValue.java @@ -22,34 +22,33 @@ /** * Abstracts a value returned from one of the Atomics */ -public interface AtomicValue -{ +public interface AtomicValue { /** * MUST be checked. Returns true if the operation succeeded. If false is returned, * the operation failed and the atomic was not updated. * * @return true/false */ - public boolean succeeded(); + public boolean succeeded(); /** * Returns the value of the counter prior to the operation * * @return pre-operation value */ - public T preValue(); + public T preValue(); /** * Returns the value of the counter after to the operation * * @return post-operation value */ - public T postValue(); + public T postValue(); /** * Returns debugging stats about the operation * * @return stats */ - public AtomicStats getStats(); + public AtomicStats getStats(); } diff --git a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/atomic/CachedAtomicInteger.java b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/atomic/CachedAtomicInteger.java index 0400e5bda..0441da9aa 100644 --- a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/atomic/CachedAtomicInteger.java +++ b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/atomic/CachedAtomicInteger.java @@ -22,20 +22,18 @@ /** * Uses an {@link DistributedAtomicNumber} and allocates values in chunks for better performance */ -public class CachedAtomicInteger -{ - private final DistributedAtomicInteger number; - private final int cacheFactor; +public class CachedAtomicInteger { + private final DistributedAtomicInteger number; + private final int cacheFactor; - private AtomicValue currentValue = null; - private int currentIndex = 0; + private AtomicValue currentValue = null; + private int currentIndex = 0; /** * @param number the number to use * @param cacheFactor the number of values to allocate at a time */ - public CachedAtomicInteger(DistributedAtomicInteger number, int cacheFactor) - { + public CachedAtomicInteger(DistributedAtomicInteger number, int cacheFactor) { this.number = number; this.cacheFactor = cacheFactor; } @@ -47,15 +45,12 @@ public CachedAtomicInteger(DistributedAtomicInteger number, int cacheFactor) * @return next increment * @throws Exception errors */ - public AtomicValue next() throws Exception - { + public AtomicValue next() throws Exception { MutableAtomicValue result = new MutableAtomicValue(0, 0); - if ( currentValue == null ) - { + if (currentValue == null) { currentValue = number.add(cacheFactor); - if ( !currentValue.succeeded() ) - { + if (!currentValue.succeeded()) { currentValue = null; result.succeeded = false; return result; @@ -67,8 +62,7 @@ public AtomicValue next() throws Exception result.preValue = currentValue.preValue() + currentIndex; result.postValue = result.preValue + 1; - if ( ++currentIndex >= cacheFactor ) - { + if (++currentIndex >= cacheFactor) { currentValue = null; } diff --git a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/atomic/CachedAtomicLong.java b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/atomic/CachedAtomicLong.java index a03b0f11a..94698f49f 100644 --- a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/atomic/CachedAtomicLong.java +++ b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/atomic/CachedAtomicLong.java @@ -22,20 +22,18 @@ /** * Uses an {@link DistributedAtomicNumber} and allocates values in chunks for better performance */ -public class CachedAtomicLong -{ +public class CachedAtomicLong { private final DistributedAtomicLong number; - private final long cacheFactor; + private final long cacheFactor; - private AtomicValue currentValue = null; - private int currentIndex = 0; + private AtomicValue currentValue = null; + private int currentIndex = 0; /** * @param number the number to use * @param cacheFactor the number of values to allocate at a time */ - public CachedAtomicLong(DistributedAtomicLong number, int cacheFactor) - { + public CachedAtomicLong(DistributedAtomicLong number, int cacheFactor) { this.number = number; this.cacheFactor = cacheFactor; } @@ -47,15 +45,12 @@ public CachedAtomicLong(DistributedAtomicLong number, int cacheFactor) * @return next increment * @throws Exception errors */ - public AtomicValue next() throws Exception - { + public AtomicValue next() throws Exception { MutableAtomicValue result = new MutableAtomicValue(0L, 0L); - if ( currentValue == null ) - { + if (currentValue == null) { currentValue = number.add(cacheFactor); - if ( !currentValue.succeeded() ) - { + if (!currentValue.succeeded()) { currentValue = null; result.succeeded = false; return result; @@ -67,8 +62,7 @@ public AtomicValue next() throws Exception result.preValue = currentValue.preValue() + currentIndex; result.postValue = result.preValue + 1; - if ( ++currentIndex >= cacheFactor ) - { + if (++currentIndex >= cacheFactor) { currentValue = null; } diff --git a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/atomic/DistributedAtomicInteger.java b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/atomic/DistributedAtomicInteger.java index 7ea134b37..235ec95d4 100644 --- a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/atomic/DistributedAtomicInteger.java +++ b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/atomic/DistributedAtomicInteger.java @@ -21,12 +21,12 @@ import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; -import org.apache.curator.RetryPolicy; -import org.apache.curator.framework.CuratorFramework; -import org.apache.curator.framework.recipes.locks.InterProcessMutex; import java.nio.BufferOverflowException; import java.nio.BufferUnderflowException; import java.nio.ByteBuffer; +import org.apache.curator.RetryPolicy; +import org.apache.curator.framework.CuratorFramework; +import org.apache.curator.framework.recipes.locks.InterProcessMutex; /** *

A counter that attempts atomic increments. It first tries uses optimistic locking. If that fails, @@ -36,9 +36,8 @@ *

The various increment methods return an {@link AtomicValue} object. You must always check * {@link AtomicValue#succeeded()}. None of the methods (other than get()) are guaranteed to succeed.

*/ -public class DistributedAtomicInteger implements DistributedAtomicNumber -{ - private final DistributedAtomicValue value; +public class DistributedAtomicInteger implements DistributedAtomicNumber { + private final DistributedAtomicValue value; /** * Creates in optimistic mode only - i.e. the promotion to a mutex is not done @@ -47,8 +46,7 @@ public class DistributedAtomicInteger implements DistributedAtomicNumber get() throws Exception - { + public AtomicValue get() throws Exception { return new AtomicInteger(value.get()); } @Override - public void forceSet(Integer newValue) throws Exception - { + public void forceSet(Integer newValue) throws Exception { value.forceSet(valueToBytes(newValue)); } @Override - public AtomicValue compareAndSet(Integer expectedValue, Integer newValue) throws Exception - { + public AtomicValue compareAndSet(Integer expectedValue, Integer newValue) throws Exception { return new AtomicInteger(value.compareAndSet(valueToBytes(expectedValue), valueToBytes(newValue))); } @Override - public AtomicValue trySet(Integer newValue) throws Exception - { + public AtomicValue trySet(Integer newValue) throws Exception { return new AtomicInteger(value.trySet(valueToBytes(newValue))); } @Override - public boolean initialize(Integer initialize) throws Exception - { + public boolean initialize(Integer initialize) throws Exception { return value.initialize(valueToBytes(initialize)); } @@ -105,8 +98,7 @@ public boolean initialize(Integer initialize) throws Exception * @throws Exception ZooKeeper errors */ @Override - public AtomicValue increment() throws Exception - { + public AtomicValue increment() throws Exception { return worker(1); } @@ -118,8 +110,7 @@ public AtomicValue increment() throws Exception * @throws Exception ZooKeeper errors */ @Override - public AtomicValue decrement() throws Exception - { + public AtomicValue decrement() throws Exception { return worker(-1); } @@ -132,8 +123,7 @@ public AtomicValue decrement() throws Exception * @throws Exception ZooKeeper errors */ @Override - public AtomicValue add(Integer delta) throws Exception - { + public AtomicValue add(Integer delta) throws Exception { return worker(delta); } @@ -146,93 +136,75 @@ public AtomicValue add(Integer delta) throws Exception * @throws Exception ZooKeeper errors */ @Override - public AtomicValue subtract(Integer delta) throws Exception - { + public AtomicValue subtract(Integer delta) throws Exception { return worker(-1 * delta); } @VisibleForTesting - byte[] valueToBytes(Integer newValue) - { + byte[] valueToBytes(Integer newValue) { Preconditions.checkNotNull(newValue, "newValue cannot be null"); - byte[] newData = new byte[4]; + byte[] newData = new byte[4]; ByteBuffer wrapper = ByteBuffer.wrap(newData); wrapper.putInt(newValue); return newData; } @VisibleForTesting - int bytesToValue(byte[] data) - { - if ( (data == null) || (data.length == 0) ) - { + int bytesToValue(byte[] data) { + if ((data == null) || (data.length == 0)) { return 0; } ByteBuffer wrapper = ByteBuffer.wrap(data); - try - { + try { return wrapper.getInt(); - } - catch ( BufferUnderflowException e ) - { + } catch (BufferUnderflowException e) { throw value.createCorruptionException(data); - } - catch ( BufferOverflowException e ) - { + } catch (BufferOverflowException e) { throw value.createCorruptionException(data); } } - private AtomicValue worker(final Integer addAmount) throws Exception - { + private AtomicValue worker(final Integer addAmount) throws Exception { Preconditions.checkNotNull(addAmount, "addAmount cannot be null"); - MakeValue makeValue = new MakeValue() - { + MakeValue makeValue = new MakeValue() { @Override - public byte[] makeFrom(byte[] previous) - { - int previousValue = (previous != null) ? bytesToValue(previous) : 0; - int newValue = previousValue + addAmount; + public byte[] makeFrom(byte[] previous) { + int previousValue = (previous != null) ? bytesToValue(previous) : 0; + int newValue = previousValue + addAmount; return valueToBytes(newValue); } }; - AtomicValue result = value.trySet(makeValue); + AtomicValue result = value.trySet(makeValue); return new AtomicInteger(result); } - private class AtomicInteger implements AtomicValue - { + private class AtomicInteger implements AtomicValue { private AtomicValue bytes; - private AtomicInteger(AtomicValue bytes) - { + private AtomicInteger(AtomicValue bytes) { this.bytes = bytes; } @Override - public boolean succeeded() - { + public boolean succeeded() { return bytes.succeeded(); } @Override - public Integer preValue() - { + public Integer preValue() { return bytesToValue(bytes.preValue()); } @Override - public Integer postValue() - { + public Integer postValue() { return bytesToValue(bytes.postValue()); } @Override - public AtomicStats getStats() - { + public AtomicStats getStats() { return bytes.getStats(); } } diff --git a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/atomic/DistributedAtomicLong.java b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/atomic/DistributedAtomicLong.java index 16f086037..8a614e4e9 100644 --- a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/atomic/DistributedAtomicLong.java +++ b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/atomic/DistributedAtomicLong.java @@ -21,12 +21,12 @@ import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; -import org.apache.curator.RetryPolicy; -import org.apache.curator.framework.CuratorFramework; -import org.apache.curator.framework.recipes.locks.InterProcessMutex; import java.nio.BufferOverflowException; import java.nio.BufferUnderflowException; import java.nio.ByteBuffer; +import org.apache.curator.RetryPolicy; +import org.apache.curator.framework.CuratorFramework; +import org.apache.curator.framework.recipes.locks.InterProcessMutex; /** *

A counter that attempts atomic increments. It first tries uses optimistic locking. If that fails, @@ -36,9 +36,8 @@ *

The various increment methods return an {@link AtomicValue} object. You must always check * {@link AtomicValue#succeeded()}. None of the methods (other than get()) are guaranteed to succeed.

*/ -public class DistributedAtomicLong implements DistributedAtomicNumber -{ - private final DistributedAtomicValue value; +public class DistributedAtomicLong implements DistributedAtomicNumber { + private final DistributedAtomicValue value; /** * Creates in optimistic mode only - i.e. the promotion to a mutex is not done @@ -47,8 +46,7 @@ public class DistributedAtomicLong implements DistributedAtomicNumber * @param counterPath path to hold the value * @param retryPolicy the retry policy to use */ - public DistributedAtomicLong(CuratorFramework client, String counterPath, RetryPolicy retryPolicy) - { + public DistributedAtomicLong(CuratorFramework client, String counterPath, RetryPolicy retryPolicy) { this(client, counterPath, retryPolicy, null); } @@ -62,38 +60,33 @@ public DistributedAtomicLong(CuratorFramework client, String counterPath, RetryP * @param retryPolicy the retry policy to use * @param promotedToLock the arguments for the mutex promotion */ - public DistributedAtomicLong(CuratorFramework client, String counterPath, RetryPolicy retryPolicy, PromotedToLock promotedToLock) - { + public DistributedAtomicLong( + CuratorFramework client, String counterPath, RetryPolicy retryPolicy, PromotedToLock promotedToLock) { value = new DistributedAtomicValue(client, counterPath, retryPolicy, promotedToLock); } @Override - public AtomicValue get() throws Exception - { + public AtomicValue get() throws Exception { return new AtomicLong(value.get()); } @Override - public void forceSet(Long newValue) throws Exception - { + public void forceSet(Long newValue) throws Exception { value.forceSet(valueToBytes(newValue)); } @Override - public AtomicValue compareAndSet(Long expectedValue, Long newValue) throws Exception - { + public AtomicValue compareAndSet(Long expectedValue, Long newValue) throws Exception { return new AtomicLong(value.compareAndSet(valueToBytes(expectedValue), valueToBytes(newValue))); } @Override - public AtomicValue trySet(Long newValue) throws Exception - { + public AtomicValue trySet(Long newValue) throws Exception { return new AtomicLong(value.trySet(valueToBytes(newValue))); } @Override - public boolean initialize(Long initialize) throws Exception - { + public boolean initialize(Long initialize) throws Exception { return value.initialize(valueToBytes(initialize)); } @@ -105,8 +98,7 @@ public boolean initialize(Long initialize) throws Exception * @throws Exception ZooKeeper errors */ @Override - public AtomicValue increment() throws Exception - { + public AtomicValue increment() throws Exception { return worker(1L); } @@ -118,8 +110,7 @@ public AtomicValue increment() throws Exception * @throws Exception ZooKeeper errors */ @Override - public AtomicValue decrement() throws Exception - { + public AtomicValue decrement() throws Exception { return worker(-1L); } @@ -132,8 +123,7 @@ public AtomicValue decrement() throws Exception * @throws Exception ZooKeeper errors */ @Override - public AtomicValue add(Long delta) throws Exception - { + public AtomicValue add(Long delta) throws Exception { return worker(delta); } @@ -146,93 +136,75 @@ public AtomicValue add(Long delta) throws Exception * @throws Exception ZooKeeper errors */ @Override - public AtomicValue subtract(Long delta) throws Exception - { + public AtomicValue subtract(Long delta) throws Exception { return worker(-1 * delta); } @VisibleForTesting - byte[] valueToBytes(Long newValue) - { + byte[] valueToBytes(Long newValue) { Preconditions.checkNotNull(newValue, "newValue cannot be null"); - byte[] newData = new byte[8]; + byte[] newData = new byte[8]; ByteBuffer wrapper = ByteBuffer.wrap(newData); wrapper.putLong(newValue); return newData; } @VisibleForTesting - long bytesToValue(byte[] data) - { - if ( (data == null) || (data.length == 0) ) - { + long bytesToValue(byte[] data) { + if ((data == null) || (data.length == 0)) { return 0; } ByteBuffer wrapper = ByteBuffer.wrap(data); - try - { + try { return wrapper.getLong(); - } - catch ( BufferUnderflowException e ) - { + } catch (BufferUnderflowException e) { throw value.createCorruptionException(data); - } - catch ( BufferOverflowException e ) - { + } catch (BufferOverflowException e) { throw value.createCorruptionException(data); } } - private AtomicValue worker(final Long addAmount) throws Exception - { + private AtomicValue worker(final Long addAmount) throws Exception { Preconditions.checkNotNull(addAmount, "addAmount cannot be null"); - MakeValue makeValue = new MakeValue() - { + MakeValue makeValue = new MakeValue() { @Override - public byte[] makeFrom(byte[] previous) - { - long previousValue = (previous != null) ? bytesToValue(previous) : 0; - long newValue = previousValue + addAmount; + public byte[] makeFrom(byte[] previous) { + long previousValue = (previous != null) ? bytesToValue(previous) : 0; + long newValue = previousValue + addAmount; return valueToBytes(newValue); } }; - AtomicValue result = value.trySet(makeValue); + AtomicValue result = value.trySet(makeValue); return new AtomicLong(result); } - private class AtomicLong implements AtomicValue - { + private class AtomicLong implements AtomicValue { private AtomicValue bytes; - private AtomicLong(AtomicValue bytes) - { + private AtomicLong(AtomicValue bytes) { this.bytes = bytes; } @Override - public boolean succeeded() - { + public boolean succeeded() { return bytes.succeeded(); } @Override - public Long preValue() - { + public Long preValue() { return bytesToValue(bytes.preValue()); } @Override - public Long postValue() - { + public Long postValue() { return bytesToValue(bytes.postValue()); } @Override - public AtomicStats getStats() - { + public AtomicStats getStats() { return bytes.getStats(); } } diff --git a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/atomic/DistributedAtomicNumber.java b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/atomic/DistributedAtomicNumber.java index c2f815526..a40323225 100644 --- a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/atomic/DistributedAtomicNumber.java +++ b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/atomic/DistributedAtomicNumber.java @@ -19,8 +19,7 @@ package org.apache.curator.framework.recipes.atomic; -public interface DistributedAtomicNumber -{ +public interface DistributedAtomicNumber { /** * Returns the current value of the counter. NOTE: if the value has never been set, * 0 is returned. diff --git a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/atomic/DistributedAtomicValue.java b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/atomic/DistributedAtomicValue.java index d6ee901c8..d64f099df 100644 --- a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/atomic/DistributedAtomicValue.java +++ b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/atomic/DistributedAtomicValue.java @@ -19,6 +19,7 @@ package org.apache.curator.framework.recipes.atomic; +import java.util.Arrays; import org.apache.curator.RetryLoop; import org.apache.curator.RetryPolicy; import org.apache.curator.framework.CuratorFramework; @@ -26,7 +27,6 @@ import org.apache.curator.utils.PathUtils; import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.data.Stat; -import java.util.Arrays; /** *

A distributed value that attempts atomic sets. It first tries uses optimistic locking. If that fails, @@ -36,12 +36,11 @@ *

The various methods return an {@link AtomicValue} object. You must always check * {@link AtomicValue#succeeded()}. None of the methods (other than get()) are guaranteed to succeed.

*/ -public class DistributedAtomicValue -{ - private final CuratorFramework client; - private final String path; - private final RetryPolicy retryPolicy; - private final PromotedToLock promotedToLock; +public class DistributedAtomicValue { + private final CuratorFramework client; + private final String path; + private final RetryPolicy retryPolicy; + private final PromotedToLock promotedToLock; private final InterProcessMutex mutex; /** @@ -51,8 +50,7 @@ public class DistributedAtomicValue * @param path path to hold the value * @param retryPolicy the retry policy to use */ - public DistributedAtomicValue(CuratorFramework client, String path, RetryPolicy retryPolicy) - { + public DistributedAtomicValue(CuratorFramework client, String path, RetryPolicy retryPolicy) { this(client, path, retryPolicy, null); } @@ -66,8 +64,8 @@ public DistributedAtomicValue(CuratorFramework client, String path, RetryPolicy * @param retryPolicy the retry policy to use * @param promotedToLock the arguments for the mutex promotion */ - public DistributedAtomicValue(CuratorFramework client, String path, RetryPolicy retryPolicy, PromotedToLock promotedToLock) - { + public DistributedAtomicValue( + CuratorFramework client, String path, RetryPolicy retryPolicy, PromotedToLock promotedToLock) { this.client = client; this.path = PathUtils.validatePath(path); this.retryPolicy = retryPolicy; @@ -82,9 +80,8 @@ public DistributedAtomicValue(CuratorFramework client, String path, RetryPolicy * @return value info * @throws Exception ZooKeeper errors */ - public AtomicValue get() throws Exception - { - MutableAtomicValue result = new MutableAtomicValue(null, null, false); + public AtomicValue get() throws Exception { + MutableAtomicValue result = new MutableAtomicValue(null, null, false); getCurrentValue(result, new Stat()); result.postValue = result.preValue; result.succeeded = true; @@ -97,20 +94,13 @@ public AtomicValue get() throws Exception * @param newValue the new value * @throws Exception ZooKeeper errors */ - public void forceSet(byte[] newValue) throws Exception - { - try - { + public void forceSet(byte[] newValue) throws Exception { + try { client.setData().forPath(path, newValue); - } - catch ( KeeperException.NoNodeException dummy ) - { - try - { + } catch (KeeperException.NoNodeException dummy) { + try { client.create().creatingParentContainersIfNeeded().forPath(path, newValue); - } - catch ( KeeperException.NodeExistsException dummy2 ) - { + } catch (KeeperException.NodeExistsException dummy2) { client.setData().forPath(path, newValue); } } @@ -127,30 +117,21 @@ public void forceSet(byte[] newValue) throws Exception * @return value info * @throws Exception ZooKeeper errors */ - public AtomicValue compareAndSet(byte[] expectedValue, byte[] newValue) throws Exception - { - Stat stat = new Stat(); - MutableAtomicValue result = new MutableAtomicValue(null, null, false); - boolean createIt = getCurrentValue(result, stat); - if ( !createIt && Arrays.equals(expectedValue, result.preValue) ) - { - try - { + public AtomicValue compareAndSet(byte[] expectedValue, byte[] newValue) throws Exception { + Stat stat = new Stat(); + MutableAtomicValue result = new MutableAtomicValue(null, null, false); + boolean createIt = getCurrentValue(result, stat); + if (!createIt && Arrays.equals(expectedValue, result.preValue)) { + try { client.setData().withVersion(stat.getVersion()).forPath(path, newValue); result.succeeded = true; result.postValue = newValue; - } - catch ( KeeperException.BadVersionException dummy ) - { + } catch (KeeperException.BadVersionException dummy) { result.succeeded = false; - } - catch ( KeeperException.NoNodeException dummy ) - { + } catch (KeeperException.NoNodeException dummy) { result.succeeded = false; } - } - else - { + } else { result.succeeded = false; } return result; @@ -164,21 +145,17 @@ public AtomicValue compareAndSet(byte[] expectedValue, byte[] newValue) * @return value info * @throws Exception ZooKeeper errors */ - public AtomicValue trySet(final byte[] newValue) throws Exception - { - MutableAtomicValue result = new MutableAtomicValue(null, null, false); + public AtomicValue trySet(final byte[] newValue) throws Exception { + MutableAtomicValue result = new MutableAtomicValue(null, null, false); - MakeValue makeValue = new MakeValue() - { + MakeValue makeValue = new MakeValue() { @Override - public byte[] makeFrom(byte[] previous) - { + public byte[] makeFrom(byte[] previous) { return newValue; } }; tryOptimistic(result, makeValue); - if ( !result.succeeded() && (mutex != null) ) - { + if (!result.succeeded() && (mutex != null)) { tryWithMutex(result, makeValue); } @@ -193,46 +170,35 @@ public byte[] makeFrom(byte[] previous) * @return true if the value was set, false if the node already existed * @throws Exception ZooKeeper errors */ - public boolean initialize(byte[] value) throws Exception - { - try - { + public boolean initialize(byte[] value) throws Exception { + try { client.create().creatingParentContainersIfNeeded().forPath(path, value); - } - catch ( KeeperException.NodeExistsException ignore ) - { + } catch (KeeperException.NodeExistsException ignore) { // ignore return false; } return true; } - AtomicValue trySet(MakeValue makeValue) throws Exception - { - MutableAtomicValue result = new MutableAtomicValue(null, null, false); + AtomicValue trySet(MakeValue makeValue) throws Exception { + MutableAtomicValue result = new MutableAtomicValue(null, null, false); tryOptimistic(result, makeValue); - if ( !result.succeeded() && (mutex != null) ) - { + if (!result.succeeded() && (mutex != null)) { tryWithMutex(result, makeValue); } return result; } - RuntimeException createCorruptionException(byte[] bytes) - { - StringBuilder str = new StringBuilder(); + RuntimeException createCorruptionException(byte[] bytes) { + StringBuilder str = new StringBuilder(); str.append('['); - boolean first = true; - for ( byte b : bytes ) - { - if ( first ) - { + boolean first = true; + for (byte b : bytes) { + if (first) { first = false; - } - else - { + } else { str.append(", "); } str.append("0x").append(Integer.toHexString((b & 0xff))); @@ -241,75 +207,61 @@ RuntimeException createCorruptionException(byte[] bytes) return new RuntimeException(String.format("Corrupted data for node \"%s\": %s", path, str.toString())); } - private boolean getCurrentValue(MutableAtomicValue result, Stat stat) throws Exception - { - boolean createIt = false; - try - { + private boolean getCurrentValue(MutableAtomicValue result, Stat stat) throws Exception { + boolean createIt = false; + try { result.preValue = client.getData().storingStatIn(stat).forPath(path); - } - catch ( KeeperException.NoNodeException e ) - { + } catch (KeeperException.NoNodeException e) { result.preValue = null; createIt = true; } return createIt; } - private void tryWithMutex(MutableAtomicValue result, MakeValue makeValue) throws Exception - { - long startMs = System.currentTimeMillis(); - int retryCount = 0; + private void tryWithMutex(MutableAtomicValue result, MakeValue makeValue) throws Exception { + long startMs = System.currentTimeMillis(); + int retryCount = 0; - if ( mutex.acquire(promotedToLock.getMaxLockTime(), promotedToLock.getMaxLockTimeUnit()) ) - { - try - { - boolean done = false; - while ( !done ) - { - result.stats.incrementPromotedTries(); - if ( tryOnce(result, makeValue) ) - { - result.succeeded = true; - done = true; - } - else - { - if ( !promotedToLock.getRetryPolicy().allowRetry(retryCount++, System.currentTimeMillis() - startMs, RetryLoop.getDefaultRetrySleeper()) ) - { - done = true; - } - } - } - } - finally - { - mutex.release(); - } - } + if (mutex.acquire(promotedToLock.getMaxLockTime(), promotedToLock.getMaxLockTimeUnit())) { + try { + boolean done = false; + while (!done) { + result.stats.incrementPromotedTries(); + if (tryOnce(result, makeValue)) { + result.succeeded = true; + done = true; + } else { + if (!promotedToLock + .getRetryPolicy() + .allowRetry( + retryCount++, + System.currentTimeMillis() - startMs, + RetryLoop.getDefaultRetrySleeper())) { + done = true; + } + } + } + } finally { + mutex.release(); + } + } - result.stats.setPromotedTimeMs(System.currentTimeMillis() - startMs); + result.stats.setPromotedTimeMs(System.currentTimeMillis() - startMs); } - private void tryOptimistic(MutableAtomicValue result, MakeValue makeValue) throws Exception - { - long startMs = System.currentTimeMillis(); - int retryCount = 0; + private void tryOptimistic(MutableAtomicValue result, MakeValue makeValue) throws Exception { + long startMs = System.currentTimeMillis(); + int retryCount = 0; - boolean done = false; - while ( !done ) - { + boolean done = false; + while (!done) { result.stats.incrementOptimisticTries(); - if ( tryOnce(result, makeValue) ) - { + if (tryOnce(result, makeValue)) { result.succeeded = true; done = true; - } - else - { - if ( !retryPolicy.allowRetry(retryCount++, System.currentTimeMillis() - startMs, RetryLoop.getDefaultRetrySleeper()) ) - { + } else { + if (!retryPolicy.allowRetry( + retryCount++, System.currentTimeMillis() - startMs, RetryLoop.getDefaultRetrySleeper())) { done = true; } } @@ -318,36 +270,25 @@ private void tryOptimistic(MutableAtomicValue result, MakeValue makeValu result.stats.setOptimisticTimeMs(System.currentTimeMillis() - startMs); } - private boolean tryOnce(MutableAtomicValue result, MakeValue makeValue) throws Exception - { - Stat stat = new Stat(); - boolean createIt = getCurrentValue(result, stat); + private boolean tryOnce(MutableAtomicValue result, MakeValue makeValue) throws Exception { + Stat stat = new Stat(); + boolean createIt = getCurrentValue(result, stat); - boolean success = false; - try - { - byte[] newValue = makeValue.makeFrom(result.preValue); - if ( createIt ) - { + boolean success = false; + try { + byte[] newValue = makeValue.makeFrom(result.preValue); + if (createIt) { client.create().creatingParentContainersIfNeeded().forPath(path, newValue); - } - else - { + } else { client.setData().withVersion(stat.getVersion()).forPath(path, newValue); } result.postValue = Arrays.copyOf(newValue, newValue.length); success = true; - } - catch ( KeeperException.NodeExistsException e ) - { + } catch (KeeperException.NodeExistsException e) { // do Retry - } - catch ( KeeperException.BadVersionException e ) - { + } catch (KeeperException.BadVersionException e) { // do Retry - } - catch ( KeeperException.NoNodeException e ) - { + } catch (KeeperException.NoNodeException e) { // do Retry } diff --git a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/atomic/MakeValue.java b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/atomic/MakeValue.java index d9c3edf6c..c471e427b 100644 --- a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/atomic/MakeValue.java +++ b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/atomic/MakeValue.java @@ -19,7 +19,6 @@ package org.apache.curator.framework.recipes.atomic; -interface MakeValue -{ - public byte[] makeFrom(byte[] previous); +interface MakeValue { + public byte[] makeFrom(byte[] previous); } diff --git a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/atomic/MutableAtomicValue.java b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/atomic/MutableAtomicValue.java index 8150ad8f5..d415e4946 100644 --- a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/atomic/MutableAtomicValue.java +++ b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/atomic/MutableAtomicValue.java @@ -19,46 +19,39 @@ package org.apache.curator.framework.recipes.atomic; -class MutableAtomicValue implements AtomicValue -{ +class MutableAtomicValue implements AtomicValue { T preValue; T postValue; boolean succeeded = false; AtomicStats stats = new AtomicStats(); - MutableAtomicValue(T preValue, T postValue) - { + MutableAtomicValue(T preValue, T postValue) { this(preValue, postValue, false); } - MutableAtomicValue(T preValue, T postValue, boolean succeeded) - { + MutableAtomicValue(T preValue, T postValue, boolean succeeded) { this.preValue = preValue; this.postValue = postValue; this.succeeded = succeeded; } @Override - public T preValue() - { + public T preValue() { return preValue; } @Override - public T postValue() - { + public T postValue() { return postValue; } @Override - public boolean succeeded() - { + public boolean succeeded() { return succeeded; } @Override - public AtomicStats getStats() - { + public AtomicStats getStats() { return stats; } } diff --git a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/atomic/PromotedToLock.java b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/atomic/PromotedToLock.java index 4b631c4e8..509039476 100644 --- a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/atomic/PromotedToLock.java +++ b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/atomic/PromotedToLock.java @@ -20,46 +20,43 @@ package org.apache.curator.framework.recipes.atomic; import com.google.common.base.Preconditions; +import java.util.concurrent.TimeUnit; import org.apache.curator.RetryPolicy; import org.apache.curator.retry.RetryNTimes; -import java.util.concurrent.TimeUnit; import org.apache.curator.utils.PathUtils; /** * Abstraction of arguments for mutex promotion. Use {@link #builder()} to create. */ -public class PromotedToLock -{ - private final String path; - private final long maxLockTime; - private final TimeUnit maxLockTimeUnit; - private final RetryPolicy retryPolicy; +public class PromotedToLock { + private final String path; + private final long maxLockTime; + private final TimeUnit maxLockTimeUnit; + private final RetryPolicy retryPolicy; /** * Allocate a new builder * * @return new builder */ - public static Builder builder() - { + public static Builder builder() { return new Builder(); } - public static class Builder - { - private PromotedToLock instance = new PromotedToLock(null, -1, null, new RetryNTimes(0, 0)); + public static class Builder { + private PromotedToLock instance = new PromotedToLock(null, -1, null, new RetryNTimes(0, 0)); /** * Build the argument block * * @return new block */ - public PromotedToLock build() - { + public PromotedToLock build() { Preconditions.checkNotNull(instance.path, "path cannot be null"); Preconditions.checkNotNull(instance.retryPolicy, "retryPolicy cannot be null"); - return new PromotedToLock(instance.path, instance.maxLockTime, instance.maxLockTimeUnit, instance.retryPolicy); + return new PromotedToLock( + instance.path, instance.maxLockTime, instance.maxLockTimeUnit, instance.retryPolicy); } /** @@ -68,9 +65,9 @@ public PromotedToLock build() * @param path path * @return this */ - public Builder lockPath(String path) - { - instance = new PromotedToLock(PathUtils.validatePath(path), instance.maxLockTime, instance.maxLockTimeUnit, instance.retryPolicy); + public Builder lockPath(String path) { + instance = new PromotedToLock( + PathUtils.validatePath(path), instance.maxLockTime, instance.maxLockTimeUnit, instance.retryPolicy); return this; } @@ -80,8 +77,7 @@ public Builder lockPath(String path) * @param retryPolicy new policy * @return this */ - public Builder retryPolicy(RetryPolicy retryPolicy) - { + public Builder retryPolicy(RetryPolicy retryPolicy) { instance = new PromotedToLock(instance.path, instance.maxLockTime, instance.maxLockTimeUnit, retryPolicy); return this; } @@ -93,39 +89,31 @@ public Builder retryPolicy(RetryPolicy retryPolicy) * @param maxLockTimeUnit unit * @return this */ - public Builder timeout(long maxLockTime, TimeUnit maxLockTimeUnit) - { + public Builder timeout(long maxLockTime, TimeUnit maxLockTimeUnit) { instance = new PromotedToLock(instance.path, maxLockTime, maxLockTimeUnit, instance.retryPolicy); return this; } - private Builder() - { - } + private Builder() {} } - String getPath() - { + String getPath() { return path; } - long getMaxLockTime() - { + long getMaxLockTime() { return maxLockTime; } - TimeUnit getMaxLockTimeUnit() - { + TimeUnit getMaxLockTimeUnit() { return maxLockTimeUnit; } - RetryPolicy getRetryPolicy() - { + RetryPolicy getRetryPolicy() { return retryPolicy; } - private PromotedToLock(String path, long maxLockTime, TimeUnit maxLockTimeUnit, RetryPolicy retryPolicy) - { + private PromotedToLock(String path, long maxLockTime, TimeUnit maxLockTimeUnit, RetryPolicy retryPolicy) { this.path = path; this.maxLockTime = maxLockTime; this.maxLockTimeUnit = maxLockTimeUnit; diff --git a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/barriers/DistributedBarrier.java b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/barriers/DistributedBarrier.java index 7fd382e73..7894d106f 100644 --- a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/barriers/DistributedBarrier.java +++ b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/barriers/DistributedBarrier.java @@ -19,12 +19,12 @@ package org.apache.curator.framework.recipes.barriers; +import java.util.concurrent.TimeUnit; import org.apache.curator.framework.CuratorFramework; +import org.apache.curator.utils.PathUtils; import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.WatchedEvent; import org.apache.zookeeper.Watcher; -import java.util.concurrent.TimeUnit; -import org.apache.curator.utils.PathUtils; /** *

@@ -36,15 +36,12 @@ * until a condition is met at which time all the nodes are allowed to proceed * */ -public class DistributedBarrier -{ +public class DistributedBarrier { private final CuratorFramework client; private final String barrierPath; - private final Watcher watcher = new Watcher() - { + private final Watcher watcher = new Watcher() { @Override - public void process(WatchedEvent event) - { + public void process(WatchedEvent event) { client.postSafeNotify(DistributedBarrier.this); } }; @@ -53,8 +50,7 @@ public void process(WatchedEvent event) * @param client client * @param barrierPath path to use as the barrier */ - public DistributedBarrier(CuratorFramework client, String barrierPath) - { + public DistributedBarrier(CuratorFramework client, String barrierPath) { this.client = client; this.barrierPath = PathUtils.validatePath(barrierPath); } @@ -64,14 +60,10 @@ public DistributedBarrier(CuratorFramework client, String barrierPath) * * @throws Exception errors */ - public synchronized void setBarrier() throws Exception - { - try - { + public synchronized void setBarrier() throws Exception { + try { client.create().creatingParentContainersIfNeeded().forPath(barrierPath); - } - catch ( KeeperException.NodeExistsException ignore ) - { + } catch (KeeperException.NodeExistsException ignore) { // ignore } } @@ -81,14 +73,10 @@ public synchronized void setBarrier() throws Exception * * @throws Exception errors */ - public synchronized void removeBarrier() throws Exception - { - try - { + public synchronized void removeBarrier() throws Exception { + try { client.delete().forPath(barrierPath); - } - catch ( KeeperException.NoNodeException ignore ) - { + } catch (KeeperException.NoNodeException ignore) { // ignore } } @@ -98,8 +86,7 @@ public synchronized void removeBarrier() throws Exception * * @throws Exception errors */ - public synchronized void waitOnBarrier() throws Exception - { + public synchronized void waitOnBarrier() throws Exception { waitOnBarrier(-1, null); } @@ -111,33 +98,26 @@ public synchronized void waitOnBarrier() throws Exception * @return true if the wait was successful, false if the timeout elapsed first * @throws Exception errors */ - public synchronized boolean waitOnBarrier(long maxWait, TimeUnit unit) throws Exception - { - long startMs = System.currentTimeMillis(); - boolean hasMaxWait = (unit != null); - long maxWaitMs = hasMaxWait ? TimeUnit.MILLISECONDS.convert(maxWait, unit) : Long.MAX_VALUE; + public synchronized boolean waitOnBarrier(long maxWait, TimeUnit unit) throws Exception { + long startMs = System.currentTimeMillis(); + boolean hasMaxWait = (unit != null); + long maxWaitMs = hasMaxWait ? TimeUnit.MILLISECONDS.convert(maxWait, unit) : Long.MAX_VALUE; - boolean result; - for(;;) - { + boolean result; + for (; ; ) { result = (client.checkExists().usingWatcher(watcher).forPath(barrierPath) == null); - if ( result ) - { + if (result) { break; } - if ( hasMaxWait ) - { - long elapsed = System.currentTimeMillis() - startMs; - long thisWaitMs = maxWaitMs - elapsed; - if ( thisWaitMs <= 0 ) - { + if (hasMaxWait) { + long elapsed = System.currentTimeMillis() - startMs; + long thisWaitMs = maxWaitMs - elapsed; + if (thisWaitMs <= 0) { break; } wait(thisWaitMs); - } - else - { + } else { wait(); } } diff --git a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/barriers/DistributedDoubleBarrier.java b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/barriers/DistributedDoubleBarrier.java index 059ab06e8..b6dd69dad 100644 --- a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/barriers/DistributedDoubleBarrier.java +++ b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/barriers/DistributedDoubleBarrier.java @@ -24,20 +24,20 @@ import com.google.common.base.Predicate; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; -import org.apache.curator.framework.CuratorFramework; -import org.apache.curator.utils.ZKPaths; -import org.apache.zookeeper.CreateMode; -import org.apache.zookeeper.KeeperException; -import org.apache.zookeeper.WatchedEvent; -import org.apache.zookeeper.Watcher; -import org.apache.zookeeper.data.Stat; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.UUID; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; +import org.apache.curator.framework.CuratorFramework; import org.apache.curator.utils.PathUtils; +import org.apache.curator.utils.ZKPaths; +import org.apache.zookeeper.CreateMode; +import org.apache.zookeeper.KeeperException; +import org.apache.zookeeper.WatchedEvent; +import org.apache.zookeeper.Watcher; +import org.apache.zookeeper.data.Stat; /** *

@@ -51,8 +51,7 @@ * once they have finished. * */ -public class DistributedDoubleBarrier -{ +public class DistributedDoubleBarrier { private final CuratorFramework client; private final String barrierPath; private final int memberQty; @@ -60,14 +59,12 @@ public class DistributedDoubleBarrier private final String readyPath; private final AtomicBoolean hasBeenNotified = new AtomicBoolean(false); private final AtomicBoolean connectionLost = new AtomicBoolean(false); - private final Watcher watcher = new Watcher() - { + private final Watcher watcher = new Watcher() { @Override - public void process(WatchedEvent event) - { + public void process(WatchedEvent event) { connectionLost.set(event.getState() != Event.KeeperState.SyncConnected); client.runSafe(() -> { - synchronized(DistributedDoubleBarrier.this) { + synchronized (DistributedDoubleBarrier.this) { hasBeenNotified.set(true); DistributedDoubleBarrier.this.notifyAll(); } @@ -75,7 +72,7 @@ public void process(WatchedEvent event) } }; - private static final String READY_NODE = "ready"; + private static final String READY_NODE = "ready"; /** * Creates the barrier abstraction. memberQty is the number of members in the @@ -87,8 +84,7 @@ public void process(WatchedEvent event) * @param memberQty the number of members in the barrier. NOTE: more than memberQty * can enter the barrier. memberQty is a threshold, not a limit */ - public DistributedDoubleBarrier(CuratorFramework client, String barrierPath, int memberQty) - { + public DistributedDoubleBarrier(CuratorFramework client, String barrierPath, int memberQty) { Preconditions.checkState(memberQty > 0, "memberQty cannot be 0"); this.client = client; @@ -103,8 +99,7 @@ public DistributedDoubleBarrier(CuratorFramework client, String barrierPath, int * * @throws Exception interruptions, errors, etc. */ - public void enter() throws Exception - { + public void enter() throws Exception { enter(-1, null); } @@ -117,18 +112,19 @@ public void enter() throws Exception * @return true if the entry was successful, false if the timeout elapsed first * @throws Exception interruptions, errors, etc. */ - public boolean enter(long maxWait, TimeUnit unit) throws Exception - { - long startMs = System.currentTimeMillis(); - boolean hasMaxWait = (unit != null); - long maxWaitMs = hasMaxWait ? TimeUnit.MILLISECONDS.convert(maxWait, unit) : Long.MAX_VALUE; + public boolean enter(long maxWait, TimeUnit unit) throws Exception { + long startMs = System.currentTimeMillis(); + boolean hasMaxWait = (unit != null); + long maxWaitMs = hasMaxWait ? TimeUnit.MILLISECONDS.convert(maxWait, unit) : Long.MAX_VALUE; - boolean readyPathExists = (client.checkExists().usingWatcher(watcher).forPath(readyPath) != null); - client.create().creatingParentContainersIfNeeded().withMode(CreateMode.EPHEMERAL).forPath(ourPath); + boolean readyPathExists = (client.checkExists().usingWatcher(watcher).forPath(readyPath) != null); + client.create() + .creatingParentContainersIfNeeded() + .withMode(CreateMode.EPHEMERAL) + .forPath(ourPath); - boolean result = (readyPathExists || internalEnter(startMs, hasMaxWait, maxWaitMs)); - if ( connectionLost.get() ) - { + boolean result = (readyPathExists || internalEnter(startMs, hasMaxWait, maxWaitMs)); + if (connectionLost.get()) { throw new KeeperException.ConnectionLossException(); } @@ -140,8 +136,7 @@ public boolean enter(long maxWait, TimeUnit unit) throws Exception * * @throws Exception interruptions, errors, etc. */ - public synchronized void leave() throws Exception - { + public synchronized void leave() throws Exception { leave(-1, null); } @@ -154,193 +149,144 @@ public synchronized void leave() throws Exception * @return true if leaving was successful, false if the timeout elapsed first * @throws Exception interruptions, errors, etc. */ - public synchronized boolean leave(long maxWait, TimeUnit unit) throws Exception - { - long startMs = System.currentTimeMillis(); - boolean hasMaxWait = (unit != null); - long maxWaitMs = hasMaxWait ? TimeUnit.MILLISECONDS.convert(maxWait, unit) : Long.MAX_VALUE; + public synchronized boolean leave(long maxWait, TimeUnit unit) throws Exception { + long startMs = System.currentTimeMillis(); + boolean hasMaxWait = (unit != null); + long maxWaitMs = hasMaxWait ? TimeUnit.MILLISECONDS.convert(maxWait, unit) : Long.MAX_VALUE; return internalLeave(startMs, hasMaxWait, maxWaitMs); } @VisibleForTesting - protected List getChildrenForEntering() throws Exception - { + protected List getChildrenForEntering() throws Exception { return client.getChildren().forPath(barrierPath); } - private List filterAndSortChildren(List children) - { - Iterable filtered = Iterables.filter - ( - children, - new Predicate() - { - @Override - public boolean apply(String name) - { - return !name.equals(READY_NODE); - } + private List filterAndSortChildren(List children) { + Iterable filtered = Iterables.filter(children, new Predicate() { + @Override + public boolean apply(String name) { + return !name.equals(READY_NODE); } - ); + }); ArrayList filteredList = Lists.newArrayList(filtered); Collections.sort(filteredList); return filteredList; } - private boolean internalLeave(long startMs, boolean hasMaxWait, long maxWaitMs) throws Exception - { - String ourPathName = ZKPaths.getNodeFromPath(ourPath); - boolean ourNodeShouldExist = true; - boolean result = true; - for(;;) - { - if ( connectionLost.get() ) - { + private boolean internalLeave(long startMs, boolean hasMaxWait, long maxWaitMs) throws Exception { + String ourPathName = ZKPaths.getNodeFromPath(ourPath); + boolean ourNodeShouldExist = true; + boolean result = true; + for (; ; ) { + if (connectionLost.get()) { throw new KeeperException.ConnectionLossException(); } List children; - try - { + try { children = client.getChildren().forPath(barrierPath); - } - catch ( KeeperException.NoNodeException dummy ) - { + } catch (KeeperException.NoNodeException dummy) { children = Lists.newArrayList(); } children = filterAndSortChildren(children); - if ( (children == null) || (children.size() == 0) ) - { + if ((children == null) || (children.size() == 0)) { break; } - int ourIndex = children.indexOf(ourPathName); - if ( (ourIndex < 0) && ourNodeShouldExist ) - { - if ( connectionLost.get() ) - { - break; // connection was lost but we've reconnected. However, our ephemeral node is gone - } - else - { + int ourIndex = children.indexOf(ourPathName); + if ((ourIndex < 0) && ourNodeShouldExist) { + if (connectionLost.get()) { + break; // connection was lost but we've reconnected. However, our ephemeral node is gone + } else { throw new IllegalStateException(String.format("Our path (%s) is missing", ourPathName)); } } - if ( children.size() == 1 ) - { - if ( ourNodeShouldExist && !children.get(0).equals(ourPathName) ) - { - throw new IllegalStateException(String.format("Last path (%s) is not ours (%s)", children.get(0), ourPathName)); + if (children.size() == 1) { + if (ourNodeShouldExist && !children.get(0).equals(ourPathName)) { + throw new IllegalStateException( + String.format("Last path (%s) is not ours (%s)", children.get(0), ourPathName)); } checkDeleteOurPath(ourNodeShouldExist); break; } - Stat stat; - boolean IsLowestNode = (ourIndex == 0); - if ( IsLowestNode ) - { - String highestNodePath = ZKPaths.makePath(barrierPath, children.get(children.size() - 1)); + Stat stat; + boolean IsLowestNode = (ourIndex == 0); + if (IsLowestNode) { + String highestNodePath = ZKPaths.makePath(barrierPath, children.get(children.size() - 1)); stat = client.checkExists().usingWatcher(watcher).forPath(highestNodePath); - } - else - { - String lowestNodePath = ZKPaths.makePath(barrierPath, children.get(0)); + } else { + String lowestNodePath = ZKPaths.makePath(barrierPath, children.get(0)); stat = client.checkExists().usingWatcher(watcher).forPath(lowestNodePath); checkDeleteOurPath(ourNodeShouldExist); ourNodeShouldExist = false; } - if ( stat != null ) - { - if ( hasMaxWait ) - { - long elapsed = System.currentTimeMillis() - startMs; - long thisWaitMs = maxWaitMs - elapsed; - if ( thisWaitMs <= 0 ) - { + if (stat != null) { + if (hasMaxWait) { + long elapsed = System.currentTimeMillis() - startMs; + long thisWaitMs = maxWaitMs - elapsed; + if (thisWaitMs <= 0) { result = false; break; - } - else - { + } else { wait(thisWaitMs); } - } - else - { + } else { wait(); } } } - try - { + try { client.delete().forPath(readyPath); - } - catch ( KeeperException.NoNodeException ignore ) - { + } catch (KeeperException.NoNodeException ignore) { // ignore } return result; } - private void checkDeleteOurPath(boolean shouldExist) throws Exception - { - if ( shouldExist ) - { + private void checkDeleteOurPath(boolean shouldExist) throws Exception { + if (shouldExist) { client.delete().forPath(ourPath); } } - private synchronized boolean internalEnter(long startMs, boolean hasMaxWait, long maxWaitMs) throws Exception - { + private synchronized boolean internalEnter(long startMs, boolean hasMaxWait, long maxWaitMs) throws Exception { boolean result = true; - do - { - List children = getChildrenForEntering(); - int count = (children != null) ? children.size() : 0; - if ( count >= memberQty ) - { - try - { + do { + List children = getChildrenForEntering(); + int count = (children != null) ? children.size() : 0; + if (count >= memberQty) { + try { client.create().forPath(readyPath); - } - catch ( KeeperException.NodeExistsException ignore ) - { + } catch (KeeperException.NodeExistsException ignore) { // ignore } break; } - if ( hasMaxWait && !hasBeenNotified.get() ) - { - long elapsed = System.currentTimeMillis() - startMs; - long thisWaitMs = maxWaitMs - elapsed; - if ( thisWaitMs <= 0 ) - { + if (hasMaxWait && !hasBeenNotified.get()) { + long elapsed = System.currentTimeMillis() - startMs; + long thisWaitMs = maxWaitMs - elapsed; + if (thisWaitMs <= 0) { result = false; - } - else - { + } else { wait(thisWaitMs); } - if ( !hasBeenNotified.get() ) - { + if (!hasBeenNotified.get()) { result = false; } - } - else - { + } else { wait(); } - } while ( false ); + } while (false); return result; } diff --git a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/ChildData.java b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/ChildData.java index 533a24a5f..de32aab5c 100644 --- a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/ChildData.java +++ b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/ChildData.java @@ -19,18 +19,16 @@ package org.apache.curator.framework.recipes.cache; -import org.apache.zookeeper.data.Stat; import java.util.Arrays; import org.apache.curator.utils.PathUtils; +import org.apache.zookeeper.data.Stat; -public class ChildData implements Comparable -{ +public class ChildData implements Comparable { private final String path; private final Stat stat; private final byte[] data; - public ChildData(String path, Stat stat, byte[] data) - { + public ChildData(String path, Stat stat, byte[] data) { this.path = PathUtils.validatePath(path); this.stat = stat; this.data = data; @@ -42,14 +40,11 @@ public ChildData(String path, Stat stat, byte[] data) * Note: this class has a natural ordering that is inconsistent with equals. */ @Override - public int compareTo(ChildData rhs) - { - if ( this == rhs ) - { + public int compareTo(ChildData rhs) { + if (this == rhs) { return 0; } - if ( rhs == null || getClass() != rhs.getClass() ) - { + if (rhs == null || getClass() != rhs.getClass()) { return -1; } @@ -58,29 +53,23 @@ public int compareTo(ChildData rhs) @SuppressWarnings("RedundantIfStatement") @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; } - ChildData childData = (ChildData)o; + ChildData childData = (ChildData) o; - if ( !Arrays.equals(data, childData.data) ) - { + if (!Arrays.equals(data, childData.data)) { return false; } - if ( path != null ? !path.equals(childData.path) : childData.path != null ) - { + if (path != null ? !path.equals(childData.path) : childData.path != null) { return false; } - if ( stat != null ? !stat.equals(childData.stat) : childData.stat != null ) - { + if (stat != null ? !stat.equals(childData.stat) : childData.stat != null) { return false; } @@ -88,8 +77,7 @@ public boolean equals(Object o) } @Override - public int hashCode() - { + public int hashCode() { int result = path != null ? path.hashCode() : 0; result = 31 * result + (stat != null ? stat.hashCode() : 0); result = 31 * result + Arrays.hashCode(data); @@ -101,8 +89,7 @@ public int hashCode() * * @return full path */ - public String getPath() - { + public String getPath() { return path; } @@ -111,8 +98,7 @@ public String getPath() * * @return stat or null */ - public Stat getStat() - { + public Stat getStat() { return stat; } @@ -124,18 +110,12 @@ public Stat getStat() * * @return node data or null */ - public byte[] getData() - { + public byte[] getData() { return data; } @Override - public String toString() - { - return "ChildData{" + - "path='" + path + '\'' + - ", stat=" + stat + - ", data=" + Arrays.toString(data) + - '}'; + public String toString() { + return "ChildData{" + "path='" + path + '\'' + ", stat=" + stat + ", data=" + Arrays.toString(data) + '}'; } } diff --git a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/CompatibleCuratorCacheBridge.java b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/CompatibleCuratorCacheBridge.java index 2f83f59c4..22f59394c 100644 --- a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/CompatibleCuratorCacheBridge.java +++ b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/CompatibleCuratorCacheBridge.java @@ -19,124 +19,107 @@ package org.apache.curator.framework.recipes.cache; +import static org.apache.curator.framework.recipes.cache.CuratorCacheListener.Type.*; import com.google.common.collect.Sets; -import org.apache.curator.framework.CuratorFramework; -import org.apache.curator.framework.listen.Listenable; -import org.apache.curator.framework.listen.StandardListenerManager; import java.util.Collections; import java.util.Optional; import java.util.Set; import java.util.concurrent.ExecutorService; import java.util.stream.Stream; import java.util.stream.StreamSupport; - -import static org.apache.curator.framework.recipes.cache.CuratorCacheListener.Type.*; +import org.apache.curator.framework.CuratorFramework; +import org.apache.curator.framework.listen.Listenable; +import org.apache.curator.framework.listen.StandardListenerManager; /** * Version of CuratorCacheBridge for pre-ZK 3.6 - uses TreeCache instead of CuratorCache */ @SuppressWarnings("deprecation") -class CompatibleCuratorCacheBridge implements CuratorCacheBridge, TreeCacheListener -{ +class CompatibleCuratorCacheBridge implements CuratorCacheBridge, TreeCacheListener { private final TreeCache cache; private final StandardListenerManager listenerManager = StandardListenerManager.standard(); - CompatibleCuratorCacheBridge(CuratorFramework client, String path, CuratorCache.Options[] optionsArg, ExecutorService executorService, boolean cacheData) - { + CompatibleCuratorCacheBridge( + CuratorFramework client, + String path, + CuratorCache.Options[] optionsArg, + ExecutorService executorService, + boolean cacheData) { Set options = (optionsArg != null) ? Sets.newHashSet(optionsArg) : Collections.emptySet(); TreeCache.Builder builder = TreeCache.newBuilder(client, path).setCacheData(cacheData); - if ( options.contains(CuratorCache.Options.SINGLE_NODE_CACHE) ) - { + if (options.contains(CuratorCache.Options.SINGLE_NODE_CACHE)) { builder.setMaxDepth(0); } - if ( options.contains(CuratorCache.Options.COMPRESSED_DATA) ) - { + if (options.contains(CuratorCache.Options.COMPRESSED_DATA)) { builder.setDataIsCompressed(true); } - if ( executorService != null ) - { + if (executorService != null) { builder.setExecutor(executorService); } cache = builder.build(); } @Override - public void start() - { - try - { + public void start() { + try { cache.getListenable().addListener(this); cache.start(); - } - catch ( Exception e ) - { + } catch (Exception e) { throw new RuntimeException(e); } } @Override - public void close() - { + public void close() { cache.close(); } @Override - public boolean isCuratorCache() - { + public boolean isCuratorCache() { return false; } @Override - public Listenable listenable() - { + public Listenable listenable() { return listenerManager; } @Override - public Optional get(String path) - { + public Optional get(String path) { return Optional.ofNullable(cache.getCurrentData(path)); } @Override - public int size() - { + public int size() { return cache.size(); } @Override - public Stream stream() - { + public Stream stream() { Iterable iterable = cache::iterator; return StreamSupport.stream(iterable.spliterator(), false); } @Override - public void childEvent(CuratorFramework client, TreeCacheEvent event) throws Exception - { - switch ( event.getType() ) - { - case NODE_ADDED: - { + public void childEvent(CuratorFramework client, TreeCacheEvent event) throws Exception { + switch (event.getType()) { + case NODE_ADDED: { listenerManager.forEach(listener -> listener.event(NODE_CREATED, null, event.getData())); break; } - case NODE_REMOVED: - { + case NODE_REMOVED: { listenerManager.forEach(listener -> listener.event(NODE_DELETED, event.getData(), null)); break; } - case NODE_UPDATED: - { + case NODE_UPDATED: { listenerManager.forEach(listener -> listener.event(NODE_CHANGED, event.getOldData(), event.getData())); break; } - case INITIALIZED: - { + case INITIALIZED: { listenerManager.forEach(CuratorCacheListener::initialized); break; } diff --git a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/CuratorCache.java b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/CuratorCache.java index 36fbd9b82..0eeff7602 100644 --- a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/CuratorCache.java +++ b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/CuratorCache.java @@ -19,11 +19,11 @@ package org.apache.curator.framework.recipes.cache; -import org.apache.curator.framework.CuratorFramework; -import org.apache.curator.framework.listen.Listenable; import java.io.Closeable; import java.util.Optional; import java.util.stream.Stream; +import org.apache.curator.framework.CuratorFramework; +import org.apache.curator.framework.listen.Listenable; /** *

@@ -47,13 +47,11 @@ * numbers when updating nodes. *

*/ -public interface CuratorCache extends Closeable, CuratorCacheAccessor -{ +public interface CuratorCache extends Closeable, CuratorCacheAccessor { /** * cache build options */ - enum Options - { + enum Options { /** * Normally the entire tree of nodes starting at the given node are cached. This option * causes only the given node to be cached (i.e. a single node cache) @@ -80,8 +78,7 @@ enum Options * @param options any options * @return cache (note it must be started via {@link #start()} */ - static CuratorCache build(CuratorFramework client, String path, Options... options) - { + static CuratorCache build(CuratorFramework client, String path, Options... options) { return builder(client, path).withOptions(options).build(); } @@ -92,8 +89,7 @@ static CuratorCache build(CuratorFramework client, String path, Options... optio * @param path path to cache * @return builder */ - static CuratorCacheBuilder builder(CuratorFramework client, String path) - { + static CuratorCacheBuilder builder(CuratorFramework client, String path) { return new CuratorCacheBuilderImpl(client, path); } @@ -107,8 +103,7 @@ static CuratorCacheBuilder builder(CuratorFramework client, String path) * @param path path to cache * @return bridge builder */ - static CuratorCacheBridgeBuilder bridgeBuilder(CuratorFramework client, String path) - { + static CuratorCacheBridgeBuilder bridgeBuilder(CuratorFramework client, String path) { return new CuratorCacheBridgeBuilderImpl(client, path); } diff --git a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/CuratorCacheAccessor.java b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/CuratorCacheAccessor.java index 7a7480df5..d65281d28 100644 --- a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/CuratorCacheAccessor.java +++ b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/CuratorCacheAccessor.java @@ -19,16 +19,15 @@ package org.apache.curator.framework.recipes.cache; -import org.apache.curator.utils.ZKPaths; import java.util.Optional; import java.util.function.Predicate; import java.util.stream.Stream; +import org.apache.curator.utils.ZKPaths; /** * Methods to access the underlying storage */ -public interface CuratorCacheAccessor -{ +public interface CuratorCacheAccessor { /** * Return an entry from storage * @@ -65,8 +64,7 @@ public interface CuratorCacheAccessor * @param parentPath the parent path to filter on * @return filtered stream */ - static Predicate parentPathFilter(String parentPath) - { + static Predicate parentPathFilter(String parentPath) { return d -> { ZKPaths.PathAndNode pathAndNode = ZKPaths.getPathAndNode(d.getPath()); return pathAndNode.getPath().equals(parentPath); diff --git a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/CuratorCacheBridge.java b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/CuratorCacheBridge.java index 2bd6c152c..f86431d2a 100644 --- a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/CuratorCacheBridge.java +++ b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/CuratorCacheBridge.java @@ -25,8 +25,7 @@ * otherwise */ @SuppressWarnings("deprecation") -public interface CuratorCacheBridge extends CuratorCache -{ +public interface CuratorCacheBridge extends CuratorCache { /** * Returns true if the underlying cache is {@link org.apache.curator.framework.recipes.cache.CuratorCache} (i.e. ZooKeeper 3.6+). * Otherwise it is {@link org.apache.curator.framework.recipes.cache.TreeCache} (i.e. ZooKeeper 3.5.x) diff --git a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/CuratorCacheBridgeBuilder.java b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/CuratorCacheBridgeBuilder.java index d424fcbd5..b9c1c7a78 100644 --- a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/CuratorCacheBridgeBuilder.java +++ b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/CuratorCacheBridgeBuilder.java @@ -21,8 +21,7 @@ import java.util.concurrent.ExecutorService; -public interface CuratorCacheBridgeBuilder -{ +public interface CuratorCacheBridgeBuilder { /** * @param options any options * @return this @@ -54,4 +53,4 @@ public interface CuratorCacheBridgeBuilder * @return new Curator Cache Bridge */ CuratorCacheBridge build(); -} \ No newline at end of file +} diff --git a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/CuratorCacheBridgeBuilderImpl.java b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/CuratorCacheBridgeBuilderImpl.java index 9b439c221..ac9b6ac53 100644 --- a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/CuratorCacheBridgeBuilderImpl.java +++ b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/CuratorCacheBridgeBuilderImpl.java @@ -19,13 +19,12 @@ package org.apache.curator.framework.recipes.cache; +import java.util.concurrent.ExecutorService; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.utils.Compatibility; import org.slf4j.LoggerFactory; -import java.util.concurrent.ExecutorService; -class CuratorCacheBridgeBuilderImpl implements CuratorCacheBridgeBuilder -{ +class CuratorCacheBridgeBuilderImpl implements CuratorCacheBridgeBuilder { private final CuratorFramework client; private final String path; private CuratorCache.Options[] options; @@ -33,45 +32,39 @@ class CuratorCacheBridgeBuilderImpl implements CuratorCacheBridgeBuilder private ExecutorService executorService = null; private final boolean forceTreeCache = Boolean.getBoolean("curator-cache-bridge-force-tree-cache"); - CuratorCacheBridgeBuilderImpl(CuratorFramework client, String path) - { + CuratorCacheBridgeBuilderImpl(CuratorFramework client, String path) { this.client = client; this.path = path; } @Override - public CuratorCacheBridgeBuilder withOptions(CuratorCache.Options... options) - { + public CuratorCacheBridgeBuilder withOptions(CuratorCache.Options... options) { this.options = options; return this; } @Override - public CuratorCacheBridgeBuilder withDataNotCached() - { + public CuratorCacheBridgeBuilder withDataNotCached() { cacheData = false; return this; } @Override - public CuratorCacheBridgeBuilder withExecutorService(ExecutorService executorService) - { + public CuratorCacheBridgeBuilder withExecutorService(ExecutorService executorService) { this.executorService = executorService; return this; } @Override - public CuratorCacheBridge build() - { - if ( !forceTreeCache && Compatibility.hasPersistentWatchers() ) - { - if ( executorService != null ) - { + public CuratorCacheBridge build() { + if (!forceTreeCache && Compatibility.hasPersistentWatchers()) { + if (executorService != null) { LoggerFactory.getLogger(getClass()).warn("CuratorCache does not support custom ExecutorService"); } - CuratorCacheStorage storage = cacheData ? CuratorCacheStorage.standard() : CuratorCacheStorage.dataNotCached(); + CuratorCacheStorage storage = + cacheData ? CuratorCacheStorage.standard() : CuratorCacheStorage.dataNotCached(); return new CuratorCacheImpl(client, storage, path, options, null); } return new CompatibleCuratorCacheBridge(client, path, options, executorService, cacheData); } -} \ No newline at end of file +} diff --git a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/CuratorCacheBuilder.java b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/CuratorCacheBuilder.java index 23eb39442..415d2cfc0 100644 --- a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/CuratorCacheBuilder.java +++ b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/CuratorCacheBuilder.java @@ -21,8 +21,7 @@ import java.util.function.Consumer; -public interface CuratorCacheBuilder -{ +public interface CuratorCacheBuilder { /** * @param options any options * @return this @@ -51,4 +50,4 @@ public interface CuratorCacheBuilder * @return new Curator Cache */ CuratorCache build(); -} \ No newline at end of file +} diff --git a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/CuratorCacheBuilderImpl.java b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/CuratorCacheBuilderImpl.java index 4821166b7..a64a9befe 100644 --- a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/CuratorCacheBuilderImpl.java +++ b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/CuratorCacheBuilderImpl.java @@ -19,47 +19,41 @@ package org.apache.curator.framework.recipes.cache; -import org.apache.curator.framework.CuratorFramework; import java.util.function.Consumer; +import org.apache.curator.framework.CuratorFramework; -class CuratorCacheBuilderImpl implements CuratorCacheBuilder -{ +class CuratorCacheBuilderImpl implements CuratorCacheBuilder { private final CuratorFramework client; private final String path; private CuratorCacheStorage storage; private Consumer exceptionHandler; private CuratorCache.Options[] options; - CuratorCacheBuilderImpl(CuratorFramework client, String path) - { + CuratorCacheBuilderImpl(CuratorFramework client, String path) { this.client = client; this.path = path; } @Override - public CuratorCacheBuilder withOptions(CuratorCache.Options... options) - { + public CuratorCacheBuilder withOptions(CuratorCache.Options... options) { this.options = options; return this; } @Override - public CuratorCacheBuilder withStorage(CuratorCacheStorage storage) - { + public CuratorCacheBuilder withStorage(CuratorCacheStorage storage) { this.storage = storage; return this; } @Override - public CuratorCacheBuilder withExceptionHandler(Consumer exceptionHandler) - { + public CuratorCacheBuilder withExceptionHandler(Consumer exceptionHandler) { this.exceptionHandler = exceptionHandler; return this; } @Override - public CuratorCache build() - { + public CuratorCache build() { return new CuratorCacheImpl(client, storage, path, options, exceptionHandler); } -} \ No newline at end of file +} diff --git a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/CuratorCacheImpl.java b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/CuratorCacheImpl.java index c45887a68..3fccc37b0 100644 --- a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/CuratorCacheImpl.java +++ b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/CuratorCacheImpl.java @@ -19,9 +19,19 @@ package org.apache.curator.framework.recipes.cache; +import static org.apache.curator.framework.recipes.cache.CuratorCacheListener.Type.*; +import static org.apache.zookeeper.KeeperException.Code.NONODE; +import static org.apache.zookeeper.KeeperException.Code.OK; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; import com.google.common.collect.Sets; +import java.util.Collections; +import java.util.Optional; +import java.util.Set; +import java.util.concurrent.Phaser; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Consumer; +import java.util.stream.Stream; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.api.BackgroundCallback; import org.apache.curator.framework.api.CuratorEvent; @@ -35,20 +45,8 @@ import org.apache.zookeeper.data.Stat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.util.Collections; -import java.util.Optional; -import java.util.Set; -import java.util.concurrent.Phaser; -import java.util.concurrent.atomic.AtomicReference; -import java.util.function.Consumer; -import java.util.stream.Stream; -import static org.apache.curator.framework.recipes.cache.CuratorCacheListener.Type.*; -import static org.apache.zookeeper.KeeperException.Code.NONODE; -import static org.apache.zookeeper.KeeperException.Code.OK; - -class CuratorCacheImpl implements CuratorCache, CuratorCacheBridge -{ +class CuratorCacheImpl implements CuratorCache, CuratorCacheBridge { private final Logger log = LoggerFactory.getLogger(getClass()); private final AtomicReference state = new AtomicReference<>(State.LATENT); private final PersistentWatcher persistentWatcher; @@ -69,15 +67,18 @@ protected boolean onAdvance(int phase, int registeredParties) { } }; - private enum State - { + private enum State { LATENT, STARTED, CLOSED } - CuratorCacheImpl(CuratorFramework client, CuratorCacheStorage storage, String path, Options[] optionsArg, Consumer exceptionHandler) - { + CuratorCacheImpl( + CuratorFramework client, + CuratorCacheStorage storage, + String path, + Options[] optionsArg, + Consumer exceptionHandler) { Set options = (optionsArg != null) ? Sets.newHashSet(optionsArg) : Collections.emptySet(); this.client = client; this.storage = (storage != null) ? storage : CuratorCacheStorage.standard(); @@ -92,65 +93,53 @@ private enum State } @Override - public void start() - { + public void start() { Preconditions.checkState(state.compareAndSet(State.LATENT, State.STARTED), "Already started"); persistentWatcher.start(); } @Override - public void close() - { - if ( state.compareAndSet(State.STARTED, State.CLOSED) ) - { + public void close() { + if (state.compareAndSet(State.STARTED, State.CLOSED)) { persistentWatcher.close(); - if ( clearOnClose ) - { + if (clearOnClose) { storage.clear(); } } } @Override - public boolean isCuratorCache() - { + public boolean isCuratorCache() { return true; } @Override - public Listenable listenable() - { + public Listenable listenable() { return listenerManager; } @Override - public Optional get(String path) - { + public Optional get(String path) { return storage.get(path); } @Override - public int size() - { + public int size() { return storage.size(); } @Override - public Stream stream() - { + public Stream stream() { return storage.stream(); } @VisibleForTesting - CuratorCacheStorage storage() - { + CuratorCacheStorage storage() { return storage; } - private void rebuild() - { - if ( state.get() != State.STARTED ) - { + private void rebuild() { + if (state.get() != State.STARTED) { return; } @@ -160,63 +149,46 @@ private void rebuild() // rebuild remaining nodes - note: this may cause some nodes to be queried twice // (though versions checks will minimize that). If someone can think of a better // way let us know - storage.stream() - .map(ChildData::getPath) - .filter(p -> !p.equals(path)) - .forEach(this::nodeChanged); + storage.stream().map(ChildData::getPath).filter(p -> !p.equals(path)).forEach(this::nodeChanged); } - private void processEvent(WatchedEvent event) - { - if ( state.get() != State.STARTED ) - { + private void processEvent(WatchedEvent event) { + if (state.get() != State.STARTED) { return; } // NOTE: Persistent/Recursive watchers never trigger NodeChildrenChanged - switch ( event.getType() ) - { - case NodeDataChanged: - case NodeCreated: - { - nodeChanged(event.getPath()); - break; - } + switch (event.getType()) { + case NodeDataChanged: + case NodeCreated: { + nodeChanged(event.getPath()); + break; + } - case NodeDeleted: - { - removeStorage(event.getPath()); - break; - } + case NodeDeleted: { + removeStorage(event.getPath()); + break; + } } } - private void checkChildrenChanged(String fromPath, Stat oldStat, Stat newStat) - { - if ( (state.get() != State.STARTED) || !recursive ) - { + private void checkChildrenChanged(String fromPath, Stat oldStat, Stat newStat) { + if ((state.get() != State.STARTED) || !recursive) { return; } - if ( (oldStat != null) && (oldStat.getCversion() == newStat.getCversion()) ) - { + if ((oldStat != null) && (oldStat.getCversion() == newStat.getCversion())) { return; // children haven't changed } - try - { + try { BackgroundCallback callback = (__, event) -> { - if ( event.getResultCode() == OK.intValue() ) - { + if (event.getResultCode() == OK.intValue()) { event.getChildren().forEach(child -> nodeChanged(ZKPaths.makePath(fromPath, child))); - } - else if ( event.getResultCode() == NONODE.intValue() ) - { + } else if (event.getResultCode() == NONODE.intValue()) { removeStorage(event.getPath()); - } - else - { + } else { handleException(event); } outstandingOps.arriveAndDeregister(); @@ -224,92 +196,69 @@ else if ( event.getResultCode() == NONODE.intValue() ) outstandingOps.register(); client.getChildren().inBackground(callback).forPath(fromPath); - } - catch ( Exception e ) - { + } catch (Exception e) { handleException(e); } } - private void nodeChanged(String fromPath) - { - if ( state.get() != State.STARTED ) - { + private void nodeChanged(String fromPath) { + if (state.get() != State.STARTED) { return; } - try - { + try { BackgroundCallback callback = (__, event) -> { - if ( event.getResultCode() == OK.intValue() ) - { - Optional childData = putStorage(new ChildData(event.getPath(), event.getStat(), event.getData())); - checkChildrenChanged(event.getPath(), childData.map(ChildData::getStat).orElse(null), event.getStat()); - } - else if ( event.getResultCode() == NONODE.intValue() ) - { + if (event.getResultCode() == OK.intValue()) { + Optional childData = + putStorage(new ChildData(event.getPath(), event.getStat(), event.getData())); + checkChildrenChanged( + event.getPath(), childData.map(ChildData::getStat).orElse(null), event.getStat()); + } else if (event.getResultCode() == NONODE.intValue()) { removeStorage(event.getPath()); - } - else - { + } else { handleException(event); } outstandingOps.arriveAndDeregister(); }; outstandingOps.register(); - if ( compressedData ) - { + if (compressedData) { client.getData().decompressed().inBackground(callback).forPath(fromPath); - } - else - { + } else { client.getData().inBackground(callback).forPath(fromPath); } - } - catch ( Exception e ) - { + } catch (Exception e) { handleException(e); } } - private Optional putStorage(ChildData data) - { + private Optional putStorage(ChildData data) { Optional previousData = storage.put(data); - if ( previousData.isPresent() ) - { - if ( previousData.get().getStat().getVersion() != data.getStat().getVersion() ) - { + if (previousData.isPresent()) { + if (previousData.get().getStat().getVersion() != data.getStat().getVersion()) { callListeners(l -> l.event(NODE_CHANGED, previousData.get(), data)); } - } - else - { + } else { callListeners(l -> l.event(NODE_CREATED, null, data)); } return previousData; } - private void removeStorage(String path) - { + private void removeStorage(String path) { storage.remove(path).ifPresent(previousData -> callListeners(l -> l.event(NODE_DELETED, previousData, null))); } - private void callListeners(Consumer proc) - { - if ( state.get() == State.STARTED ) - { + private void callListeners(Consumer proc) { + if (state.get() == State.STARTED) { client.runSafe(() -> listenerManager.forEach(proc)); } } - private void handleException(CuratorEvent event) - { + private void handleException(CuratorEvent event) { handleException(KeeperException.create(KeeperException.Code.get(event.getResultCode()))); } - private void handleException(Exception e) - { + private void handleException(Exception e) { ThreadUtils.checkInterrupted(e); exceptionHandler.accept(e); } diff --git a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/CuratorCacheListener.java b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/CuratorCacheListener.java index 850058a51..8aa77fae4 100644 --- a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/CuratorCacheListener.java +++ b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/CuratorCacheListener.java @@ -25,13 +25,11 @@ * are wrapped in {@link org.apache.curator.framework.CuratorFramework#runSafe(Runnable)} when called. */ @FunctionalInterface -public interface CuratorCacheListener -{ +public interface CuratorCacheListener { /** * An enumerated type that describes a change */ - enum Type - { + enum Type { /** * A new node was added to the cache */ @@ -61,8 +59,7 @@ enum Type * When the cache is started, the initial nodes are tracked and when they are finished loading * into the cache this method is called. */ - default void initialized() - { + default void initialized() { // NOP } @@ -71,8 +68,7 @@ default void initialized() * * @return builder */ - static CuratorCacheListenerBuilder builder() - { + static CuratorCacheListenerBuilder builder() { return new CuratorCacheListenerBuilderImpl(); } -} \ No newline at end of file +} diff --git a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/CuratorCacheListenerBuilder.java b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/CuratorCacheListenerBuilder.java index a11578516..31d13c5e2 100644 --- a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/CuratorCacheListenerBuilder.java +++ b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/CuratorCacheListenerBuilder.java @@ -19,12 +19,11 @@ package org.apache.curator.framework.recipes.cache; +import java.util.function.Consumer; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.recipes.cache.CuratorCacheListener.Type; -import java.util.function.Consumer; -public interface CuratorCacheListenerBuilder -{ +public interface CuratorCacheListenerBuilder { /** * Add a standard listener * @@ -42,8 +41,7 @@ public interface CuratorCacheListenerBuilder CuratorCacheListenerBuilder forCreates(Consumer listener); @FunctionalInterface - interface ChangeListener - { + interface ChangeListener { void event(ChildData oldNode, ChildData node); } @@ -91,7 +89,8 @@ interface ChangeListener * @param listener the listener to wrap * @return a CuratorCacheListener that forwards to the given listener */ - CuratorCacheListenerBuilder forPathChildrenCache(String rootPath, CuratorFramework client, PathChildrenCacheListener listener); + CuratorCacheListenerBuilder forPathChildrenCache( + String rootPath, CuratorFramework client, PathChildrenCacheListener listener); /** * Bridge listener. You can reuse old-style {@link org.apache.curator.framework.recipes.cache.TreeCacheListener}s @@ -127,4 +126,4 @@ interface ChangeListener * @return new listener */ CuratorCacheListener build(); -} \ No newline at end of file +} diff --git a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/CuratorCacheListenerBuilderImpl.java b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/CuratorCacheListenerBuilderImpl.java index 2414f3d6b..b792804a3 100644 --- a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/CuratorCacheListenerBuilderImpl.java +++ b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/CuratorCacheListenerBuilderImpl.java @@ -19,29 +19,25 @@ package org.apache.curator.framework.recipes.cache; -import org.apache.curator.framework.CuratorFramework; import java.util.ArrayList; import java.util.List; import java.util.function.Consumer; +import org.apache.curator.framework.CuratorFramework; -class CuratorCacheListenerBuilderImpl implements CuratorCacheListenerBuilder -{ +class CuratorCacheListenerBuilderImpl implements CuratorCacheListenerBuilder { private final List listeners = new ArrayList<>(); private boolean afterInitializedOnly = false; @Override - public CuratorCacheListenerBuilder forAll(CuratorCacheListener listener) - { + public CuratorCacheListenerBuilder forAll(CuratorCacheListener listener) { listeners.add(listener); return this; } @Override - public CuratorCacheListenerBuilder forCreates(Consumer listener) - { + public CuratorCacheListenerBuilder forCreates(Consumer listener) { listeners.add((type, oldNode, node) -> { - if ( type == CuratorCacheListener.Type.NODE_CREATED ) - { + if (type == CuratorCacheListener.Type.NODE_CREATED) { listener.accept(node); } }); @@ -49,11 +45,9 @@ public CuratorCacheListenerBuilder forCreates(Consumer listener) } @Override - public CuratorCacheListenerBuilder forChanges(ChangeListener listener) - { + public CuratorCacheListenerBuilder forChanges(ChangeListener listener) { listeners.add((type, oldNode, node) -> { - if ( type == CuratorCacheListener.Type.NODE_CHANGED ) - { + if (type == CuratorCacheListener.Type.NODE_CHANGED) { listener.event(oldNode, node); } }); @@ -61,11 +55,9 @@ public CuratorCacheListenerBuilder forChanges(ChangeListener listener) } @Override - public CuratorCacheListenerBuilder forCreatesAndChanges(ChangeListener listener) - { + public CuratorCacheListenerBuilder forCreatesAndChanges(ChangeListener listener) { listeners.add((type, oldNode, node) -> { - if ( (type == CuratorCacheListener.Type.NODE_CHANGED) || (type == CuratorCacheListener.Type.NODE_CREATED) ) - { + if ((type == CuratorCacheListener.Type.NODE_CHANGED) || (type == CuratorCacheListener.Type.NODE_CREATED)) { listener.event(oldNode, node); } }); @@ -73,11 +65,9 @@ public CuratorCacheListenerBuilder forCreatesAndChanges(ChangeListener listener) } @Override - public CuratorCacheListenerBuilder forDeletes(Consumer listener) - { + public CuratorCacheListenerBuilder forDeletes(Consumer listener) { listeners.add((type, oldNode, node) -> { - if ( type == CuratorCacheListener.Type.NODE_DELETED ) - { + if (type == CuratorCacheListener.Type.NODE_DELETED) { listener.accept(oldNode); } }); @@ -85,19 +75,15 @@ public CuratorCacheListenerBuilder forDeletes(Consumer listener) } @Override - public CuratorCacheListenerBuilder forInitialized(Runnable listener) - { - CuratorCacheListener localListener = new CuratorCacheListener() - { + public CuratorCacheListenerBuilder forInitialized(Runnable listener) { + CuratorCacheListener localListener = new CuratorCacheListener() { @Override - public void event(Type type, ChildData oldData, ChildData data) - { + public void event(Type type, ChildData oldData, ChildData data) { // NOP } @Override - public void initialized() - { + public void initialized() { listener.run(); } }; @@ -106,56 +92,48 @@ public void initialized() } @Override - public CuratorCacheListenerBuilder forPathChildrenCache(String rootPath, CuratorFramework client, PathChildrenCacheListener listener) - { + public CuratorCacheListenerBuilder forPathChildrenCache( + String rootPath, CuratorFramework client, PathChildrenCacheListener listener) { listeners.add(new PathChildrenCacheListenerWrapper(rootPath, client, listener)); return this; } @Override - public CuratorCacheListenerBuilder forTreeCache(CuratorFramework client, TreeCacheListener listener) - { + public CuratorCacheListenerBuilder forTreeCache(CuratorFramework client, TreeCacheListener listener) { listeners.add(new TreeCacheListenerWrapper(client, listener)); return this; } @Override - public CuratorCacheListenerBuilder forNodeCache(NodeCacheListener listener) - { + public CuratorCacheListenerBuilder forNodeCache(NodeCacheListener listener) { listeners.add(new NodeCacheListenerWrapper(listener)); return this; } @Override - public CuratorCacheListenerBuilder afterInitialized() - { + public CuratorCacheListenerBuilder afterInitialized() { afterInitializedOnly = true; return this; } @Override - public CuratorCacheListener build() - { + public CuratorCacheListener build() { List copy = new ArrayList<>(listeners); - return new CuratorCacheListener() - { + return new CuratorCacheListener() { private volatile boolean isInitialized = !afterInitializedOnly; @Override - public void event(Type type, ChildData oldData, ChildData data) - { - if ( isInitialized ) - { + public void event(Type type, ChildData oldData, ChildData data) { + if (isInitialized) { copy.forEach(l -> l.event(type, oldData, data)); } } @Override - public void initialized() - { + public void initialized() { isInitialized = true; copy.forEach(CuratorCacheListener::initialized); } }; } -} \ No newline at end of file +} diff --git a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/CuratorCacheStorage.java b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/CuratorCacheStorage.java index f2b0525dd..3648503ae 100644 --- a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/CuratorCacheStorage.java +++ b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/CuratorCacheStorage.java @@ -25,15 +25,13 @@ /** * Interface for maintaining data in a {@link CuratorCache} */ -public interface CuratorCacheStorage extends CuratorCacheAccessor -{ +public interface CuratorCacheStorage extends CuratorCacheAccessor { /** * Return a new standard storage instance * * @return storage instance */ - static CuratorCacheStorage standard() - { + static CuratorCacheStorage standard() { return new StandardCuratorCacheStorage(true); } @@ -43,8 +41,7 @@ static CuratorCacheStorage standard() * * @return storage instance that does not retain data bytes */ - static CuratorCacheStorage dataNotCached() - { + static CuratorCacheStorage dataNotCached() { return new StandardCuratorCacheStorage(false); } diff --git a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/DefaultTreeCacheSelector.java b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/DefaultTreeCacheSelector.java index 4bb0d3211..8cfbce1c0 100644 --- a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/DefaultTreeCacheSelector.java +++ b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/DefaultTreeCacheSelector.java @@ -22,17 +22,14 @@ /** * Default TreeCache selector - returns true for all methods */ -public class DefaultTreeCacheSelector implements TreeCacheSelector -{ +public class DefaultTreeCacheSelector implements TreeCacheSelector { @Override - public boolean traverseChildren(String fullPath) - { + public boolean traverseChildren(String fullPath) { return true; } @Override - public boolean acceptChild(String fullPath) - { + public boolean acceptChild(String fullPath) { return true; } } diff --git a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/EventOperation.java b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/EventOperation.java index 431b781d0..6873d348f 100644 --- a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/EventOperation.java +++ b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/EventOperation.java @@ -19,28 +19,22 @@ package org.apache.curator.framework.recipes.cache; -class EventOperation implements Operation -{ +class EventOperation implements Operation { private final PathChildrenCache cache; private final PathChildrenCacheEvent event; - EventOperation(PathChildrenCache cache, PathChildrenCacheEvent event) - { + EventOperation(PathChildrenCache cache, PathChildrenCacheEvent event) { this.cache = cache; this.event = event; } @Override - public void invoke() - { + public void invoke() { cache.callListeners(event); } @Override - public String toString() - { - return "EventOperation{" + - "event=" + event + - '}'; + public String toString() { + return "EventOperation{" + "event=" + event + '}'; } } diff --git a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/GetDataOperation.java b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/GetDataOperation.java index adcb2ccab..2c1aa744e 100644 --- a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/GetDataOperation.java +++ b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/GetDataOperation.java @@ -21,40 +21,33 @@ import org.apache.curator.utils.PathUtils; -class GetDataOperation implements Operation -{ +class GetDataOperation implements Operation { private final PathChildrenCache cache; private final String fullPath; - GetDataOperation(PathChildrenCache cache, String fullPath) - { + GetDataOperation(PathChildrenCache cache, String fullPath) { this.cache = cache; this.fullPath = PathUtils.validatePath(fullPath); } @Override - public void invoke() throws Exception - { + public void invoke() throws Exception { cache.getDataAndStat(fullPath); } @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; } - GetDataOperation that = (GetDataOperation)o; + GetDataOperation that = (GetDataOperation) o; //noinspection RedundantIfStatement - if ( !fullPath.equals(that.fullPath) ) - { + if (!fullPath.equals(that.fullPath)) { return false; } @@ -62,16 +55,12 @@ public boolean equals(Object o) } @Override - public int hashCode() - { + public int hashCode() { return fullPath.hashCode(); } @Override - public String toString() - { - return "GetDataOperation{" + - "fullPath='" + fullPath + '\'' + - '}'; + public String toString() { + return "GetDataOperation{" + "fullPath='" + fullPath + '\'' + '}'; } } diff --git a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/NodeCache.java b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/NodeCache.java index c0db271c0..c303aa441 100644 --- a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/NodeCache.java +++ b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/NodeCache.java @@ -22,7 +22,11 @@ import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Objects; import com.google.common.base.Preconditions; - +import java.io.Closeable; +import java.io.IOException; +import java.util.concurrent.Exchanger; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicReference; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.WatcherRemoveCuratorFramework; import org.apache.curator.framework.api.BackgroundCallback; @@ -40,12 +44,6 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.io.Closeable; -import java.io.IOException; -import java.util.concurrent.Exchanger; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicReference; - /** *

A utility that attempts to keep the data from a node locally cached. This class * will watch the node, respond to update/create/delete events, pull down the data, etc. You can @@ -58,8 +56,7 @@ * @deprecated replace by {@link org.apache.curator.framework.recipes.cache.CuratorCache} */ @Deprecated -public class NodeCache implements Closeable -{ +public class NodeCache implements Closeable { private final Logger log = LoggerFactory.getLogger(getClass()); private final WatcherRemoveCuratorFramework client; private final String path; @@ -68,62 +65,45 @@ public class NodeCache implements Closeable private final AtomicReference state = new AtomicReference(State.LATENT); private final StandardListenerManager listeners = StandardListenerManager.standard(); private final AtomicBoolean isConnected = new AtomicBoolean(true); - private ConnectionStateListener connectionStateListener = new ConnectionStateListener() - { + private ConnectionStateListener connectionStateListener = new ConnectionStateListener() { @Override - public void stateChanged(CuratorFramework client, ConnectionState newState) - { - if ( (newState == ConnectionState.CONNECTED) || (newState == ConnectionState.RECONNECTED) ) - { - if ( isConnected.compareAndSet(false, true) ) - { - try - { + public void stateChanged(CuratorFramework client, ConnectionState newState) { + if ((newState == ConnectionState.CONNECTED) || (newState == ConnectionState.RECONNECTED)) { + if (isConnected.compareAndSet(false, true)) { + try { reset(); - } - catch ( Exception e ) - { + } catch (Exception e) { ThreadUtils.checkInterrupted(e); log.error("Trying to reset after reconnection", e); } } - } - else - { + } else { isConnected.set(false); } } }; - private Watcher watcher = new Watcher() - { + private Watcher watcher = new Watcher() { @Override - public void process(WatchedEvent event) - { - try - { + public void process(WatchedEvent event) { + try { reset(); - } - catch(Exception e) - { + } catch (Exception e) { ThreadUtils.checkInterrupted(e); handleException(e); } } }; - private enum State - { + private enum State { LATENT, STARTED, CLOSED } - private final BackgroundCallback backgroundCallback = new BackgroundCallback() - { + private final BackgroundCallback backgroundCallback = new BackgroundCallback() { @Override - public void processResult(CuratorFramework client, CuratorEvent event) throws Exception - { + public void processResult(CuratorFramework client, CuratorEvent event) throws Exception { processBackgroundResult(event); } }; @@ -132,8 +112,7 @@ public void processResult(CuratorFramework client, CuratorEvent event) throws Ex * @param client curator client * @param path the full path to the node to cache */ - public NodeCache(CuratorFramework client, String path) - { + public NodeCache(CuratorFramework client, String path) { this(client, path, false); } @@ -142,15 +121,13 @@ public NodeCache(CuratorFramework client, String path) * @param path the full path to the node to cache * @param dataIsCompressed if true, data in the path is compressed */ - public NodeCache(CuratorFramework client, String path, boolean dataIsCompressed) - { + public NodeCache(CuratorFramework client, String path, boolean dataIsCompressed) { this.client = client.newWatcherRemoveCuratorFramework(); this.path = PathUtils.validatePath(path); this.dataIsCompressed = dataIsCompressed; } - public CuratorFramework getClient() - { + public CuratorFramework getClient() { return client; } @@ -159,8 +136,7 @@ public CuratorFramework getClient() * * @throws Exception errors */ - public void start() throws Exception - { + public void start() throws Exception { start(false); } @@ -171,14 +147,12 @@ public void start() throws Exception * returns in order to get an initial view of the node * @throws Exception errors */ - public void start(boolean buildInitial) throws Exception - { + public void start(boolean buildInitial) throws Exception { Preconditions.checkState(state.compareAndSet(State.LATENT, State.STARTED), "Cannot be started more than once"); client.getConnectionStateListenable().addListener(connectionStateListener); - if ( buildInitial ) - { + if (buildInitial) { client.checkExists().creatingParentContainersIfNeeded().forPath(path); internalRebuild(); } @@ -186,10 +160,8 @@ public void start(boolean buildInitial) throws Exception } @Override - public void close() throws IOException - { - if ( state.compareAndSet(State.STARTED, State.CLOSED) ) - { + public void close() throws IOException { + if (state.compareAndSet(State.STARTED, State.CLOSED)) { client.removeWatchers(); listeners.clear(); client.getConnectionStateListenable().removeListener(connectionStateListener); @@ -200,7 +172,7 @@ public void close() throws IOException // has something to do with Guava's cache and circular references connectionStateListener = null; watcher = null; - } + } } /** @@ -208,8 +180,7 @@ public void close() throws IOException * * @return listenable */ - public Listenable getListenable() - { + public Listenable getListenable() { Preconditions.checkState(state.get() != State.CLOSED, "Closed"); return listeners; @@ -221,8 +192,7 @@ public Listenable getListenable() * * @throws Exception errors */ - public void rebuild() throws Exception - { + public void rebuild() throws Exception { Preconditions.checkState(state.get() == State.STARTED, "Not started"); internalRebuild(); @@ -237,8 +207,7 @@ public void rebuild() throws Exception * * @return data or null */ - public ChildData getCurrentData() - { + public ChildData getCurrentData() { return data.get(); } @@ -247,65 +216,60 @@ public ChildData getCurrentData() * * @return path */ - public String getPath() - { + public String getPath() { return path; } @VisibleForTesting volatile Exchanger rebuildTestExchanger; - private void reset() throws Exception - { - if ( (state.get() == State.STARTED) && isConnected.get() ) - { - client.checkExists().creatingParentContainersIfNeeded().usingWatcher(watcher).inBackground(backgroundCallback).forPath(path); + private void reset() throws Exception { + if ((state.get() == State.STARTED) && isConnected.get()) { + client.checkExists() + .creatingParentContainersIfNeeded() + .usingWatcher(watcher) + .inBackground(backgroundCallback) + .forPath(path); } } - private void internalRebuild() throws Exception - { - try - { - Stat stat = new Stat(); - byte[] bytes = dataIsCompressed ? client.getData().decompressed().storingStatIn(stat).forPath(path) : client.getData().storingStatIn(stat).forPath(path); + private void internalRebuild() throws Exception { + try { + Stat stat = new Stat(); + byte[] bytes = dataIsCompressed + ? client.getData().decompressed().storingStatIn(stat).forPath(path) + : client.getData().storingStatIn(stat).forPath(path); data.set(new ChildData(path, stat, bytes)); - } - catch ( KeeperException.NoNodeException e ) - { + } catch (KeeperException.NoNodeException e) { data.set(null); } } - private void processBackgroundResult(CuratorEvent event) throws Exception - { - switch ( event.getType() ) - { - case GET_DATA: - { - if ( event.getResultCode() == KeeperException.Code.OK.intValue() ) - { + private void processBackgroundResult(CuratorEvent event) throws Exception { + switch (event.getType()) { + case GET_DATA: { + if (event.getResultCode() == KeeperException.Code.OK.intValue()) { ChildData childData = new ChildData(path, event.getStat(), event.getData()); setNewData(childData); } break; } - case EXISTS: - { - if ( event.getResultCode() == KeeperException.Code.NONODE.intValue() ) - { + case EXISTS: { + if (event.getResultCode() == KeeperException.Code.NONODE.intValue()) { setNewData(null); - } - else if ( event.getResultCode() == KeeperException.Code.OK.intValue() ) - { - if ( dataIsCompressed ) - { - client.getData().decompressed().usingWatcher(watcher).inBackground(backgroundCallback).forPath(path); - } - else - { - client.getData().usingWatcher(watcher).inBackground(backgroundCallback).forPath(path); + } else if (event.getResultCode() == KeeperException.Code.OK.intValue()) { + if (dataIsCompressed) { + client.getData() + .decompressed() + .usingWatcher(watcher) + .inBackground(backgroundCallback) + .forPath(path); + } else { + client.getData() + .usingWatcher(watcher) + .inBackground(backgroundCallback) + .forPath(path); } } break; @@ -313,44 +277,34 @@ else if ( event.getResultCode() == KeeperException.Code.OK.intValue() ) } } - private void setNewData(ChildData newData) throws InterruptedException - { - ChildData previousData = data.getAndSet(newData); - if ( !Objects.equal(previousData, newData) ) - { + private void setNewData(ChildData newData) throws InterruptedException { + ChildData previousData = data.getAndSet(newData); + if (!Objects.equal(previousData, newData)) { listeners.forEach(listener -> { - try - { + try { listener.nodeChanged(); - } - catch ( Exception e ) - { + } catch (Exception e) { ThreadUtils.checkInterrupted(e); log.error("Calling listener", e); } }); - if ( rebuildTestExchanger != null ) - { - try - { + if (rebuildTestExchanger != null) { + try { rebuildTestExchanger.exchange(new Object()); - } - catch ( InterruptedException e ) - { + } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } } } - + /** * Default behavior is just to log the exception * * @param e the exception */ - protected void handleException(Throwable e) - { + protected void handleException(Throwable e) { log.error("", e); } } diff --git a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/NodeCacheListener.java b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/NodeCacheListener.java index 78e28b231..b4385eff4 100644 --- a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/NodeCacheListener.java +++ b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/NodeCacheListener.java @@ -19,10 +19,9 @@ package org.apache.curator.framework.recipes.cache; -public interface NodeCacheListener -{ +public interface NodeCacheListener { /** * Called when a change has occurred */ - public void nodeChanged() throws Exception; + public void nodeChanged() throws Exception; } diff --git a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/NodeCacheListenerWrapper.java b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/NodeCacheListenerWrapper.java index e6fd355f1..2229b1324 100644 --- a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/NodeCacheListenerWrapper.java +++ b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/NodeCacheListenerWrapper.java @@ -19,28 +19,19 @@ package org.apache.curator.framework.recipes.cache; -import org.apache.curator.framework.recipes.cache.ChildData; -import org.apache.curator.framework.recipes.cache.NodeCacheListener; - -class NodeCacheListenerWrapper implements CuratorCacheListener -{ +class NodeCacheListenerWrapper implements CuratorCacheListener { private final NodeCacheListener listener; - NodeCacheListenerWrapper(NodeCacheListener listener) - { + NodeCacheListenerWrapper(NodeCacheListener listener) { this.listener = listener; } @Override - public void event(Type type, ChildData oldData, ChildData data) - { - try - { + public void event(Type type, ChildData oldData, ChildData data) { + try { listener.nodeChanged(); - } - catch ( Exception e ) - { + } catch (Exception e) { throw new RuntimeException(e); } } -} \ No newline at end of file +} diff --git a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/Operation.java b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/Operation.java index ff2626198..b61ba36e7 100644 --- a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/Operation.java +++ b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/Operation.java @@ -19,7 +19,6 @@ package org.apache.curator.framework.recipes.cache; -interface Operation -{ - public void invoke() throws Exception; +interface Operation { + public void invoke() throws Exception; } diff --git a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/PathChildrenCache.java b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/PathChildrenCache.java index 9ef9f0488..d80b8a925 100644 --- a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/PathChildrenCache.java +++ b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/PathChildrenCache.java @@ -25,6 +25,17 @@ import com.google.common.collect.ImmutableList; import com.google.common.collect.Maps; import com.google.common.collect.Sets; +import java.io.Closeable; +import java.io.IOException; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentMap; +import java.util.concurrent.Exchanger; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.ThreadFactory; +import java.util.concurrent.atomic.AtomicReference; import java.util.function.Supplier; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.EnsureContainers; @@ -45,17 +56,6 @@ import org.apache.zookeeper.data.Stat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.io.Closeable; -import java.io.IOException; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.ConcurrentMap; -import java.util.concurrent.Exchanger; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.ThreadFactory; -import java.util.concurrent.atomic.AtomicReference; /** *

A utility that attempts to keep all data from all children of a ZK path locally cached. This class @@ -69,8 +69,7 @@ * @deprecated replace by {@link org.apache.curator.framework.recipes.cache.CuratorCache} */ @Deprecated -public class PathChildrenCache implements Closeable -{ +public class PathChildrenCache implements Closeable { private final Logger log = LoggerFactory.getLogger(getClass()); private final WatcherRemoveCuratorFramework client; private final String path; @@ -84,8 +83,7 @@ public class PathChildrenCache implements Closeable private final AtomicReference state = new AtomicReference(State.LATENT); private final EnsureContainers ensureContainers; - private enum State - { + private enum State { LATENT, STARTED, CLOSED @@ -95,33 +93,23 @@ private enum State private static final boolean USE_EXISTS = Boolean.getBoolean("curator-path-children-cache-use-exists"); - private volatile Watcher childrenWatcher = new Watcher() - { + private volatile Watcher childrenWatcher = new Watcher() { @Override - public void process(WatchedEvent event) - { + public void process(WatchedEvent event) { offerOperation(new RefreshOperation(PathChildrenCache.this, RefreshMode.STANDARD)); } }; - private volatile Watcher dataWatcher = new Watcher() - { + private volatile Watcher dataWatcher = new Watcher() { @Override - public void process(WatchedEvent event) - { - try - { - if ( event.getType() == Event.EventType.NodeDeleted ) - { + public void process(WatchedEvent event) { + try { + if (event.getType() == Event.EventType.NodeDeleted) { remove(event.getPath()); - } - else if ( event.getType() == Event.EventType.NodeDataChanged ) - { + } else if (event.getType() == Event.EventType.NodeDataChanged) { offerOperation(new GetDataOperation(PathChildrenCache.this, event.getPath())); } - } - catch ( Exception e ) - { + } catch (Exception e) { ThreadUtils.checkInterrupted(e); handleException(e); } @@ -131,15 +119,14 @@ else if ( event.getType() == Event.EventType.NodeDataChanged ) @VisibleForTesting volatile Exchanger rebuildTestExchanger; - private volatile ConnectionStateListener connectionStateListener = new ConnectionStateListener() - { + private volatile ConnectionStateListener connectionStateListener = new ConnectionStateListener() { @Override - public void stateChanged(CuratorFramework client, ConnectionState newState) - { + public void stateChanged(CuratorFramework client, ConnectionState newState) { handleStateChange(newState); } }; - public static final Supplier defaultThreadFactorySupplier = () -> ThreadUtils.newThreadFactory("PathChildrenCache"); + public static final Supplier defaultThreadFactorySupplier = + () -> ThreadUtils.newThreadFactory("PathChildrenCache"); /** * @param client the client @@ -149,9 +136,14 @@ public void stateChanged(CuratorFramework client, ConnectionState newState) */ @Deprecated @SuppressWarnings("deprecation") - public PathChildrenCache(CuratorFramework client, String path, PathChildrenCacheMode mode) - { - this(client, path, mode != PathChildrenCacheMode.CACHE_PATHS_ONLY, false, new CloseableExecutorService(Executors.newSingleThreadExecutor(defaultThreadFactorySupplier.get()), true)); + public PathChildrenCache(CuratorFramework client, String path, PathChildrenCacheMode mode) { + this( + client, + path, + mode != PathChildrenCacheMode.CACHE_PATHS_ONLY, + false, + new CloseableExecutorService( + Executors.newSingleThreadExecutor(defaultThreadFactorySupplier.get()), true)); } /** @@ -163,9 +155,14 @@ public PathChildrenCache(CuratorFramework client, String path, PathChildrenCache */ @Deprecated @SuppressWarnings("deprecation") - public PathChildrenCache(CuratorFramework client, String path, PathChildrenCacheMode mode, ThreadFactory threadFactory) - { - this(client, path, mode != PathChildrenCacheMode.CACHE_PATHS_ONLY, false, new CloseableExecutorService(Executors.newSingleThreadExecutor(threadFactory), true)); + public PathChildrenCache( + CuratorFramework client, String path, PathChildrenCacheMode mode, ThreadFactory threadFactory) { + this( + client, + path, + mode != PathChildrenCacheMode.CACHE_PATHS_ONLY, + false, + new CloseableExecutorService(Executors.newSingleThreadExecutor(threadFactory), true)); } /** @@ -173,9 +170,14 @@ public PathChildrenCache(CuratorFramework client, String path, PathChildrenCache * @param path path to watch * @param cacheData if true, node contents are cached in addition to the stat */ - public PathChildrenCache(CuratorFramework client, String path, boolean cacheData) - { - this(client, path, cacheData, false, new CloseableExecutorService(Executors.newSingleThreadExecutor(defaultThreadFactorySupplier.get()), true)); + public PathChildrenCache(CuratorFramework client, String path, boolean cacheData) { + this( + client, + path, + cacheData, + false, + new CloseableExecutorService( + Executors.newSingleThreadExecutor(defaultThreadFactorySupplier.get()), true)); } /** @@ -184,9 +186,13 @@ public PathChildrenCache(CuratorFramework client, String path, boolean cacheData * @param cacheData if true, node contents are cached in addition to the stat * @param threadFactory factory to use when creating internal threads */ - public PathChildrenCache(CuratorFramework client, String path, boolean cacheData, ThreadFactory threadFactory) - { - this(client, path, cacheData, false, new CloseableExecutorService(Executors.newSingleThreadExecutor(threadFactory), true)); + public PathChildrenCache(CuratorFramework client, String path, boolean cacheData, ThreadFactory threadFactory) { + this( + client, + path, + cacheData, + false, + new CloseableExecutorService(Executors.newSingleThreadExecutor(threadFactory), true)); } /** @@ -196,9 +202,18 @@ public PathChildrenCache(CuratorFramework client, String path, boolean cacheData * @param dataIsCompressed if true, data in the path is compressed * @param threadFactory factory to use when creating internal threads */ - public PathChildrenCache(CuratorFramework client, String path, boolean cacheData, boolean dataIsCompressed, ThreadFactory threadFactory) - { - this(client, path, cacheData, dataIsCompressed, new CloseableExecutorService(Executors.newSingleThreadExecutor(threadFactory), true)); + public PathChildrenCache( + CuratorFramework client, + String path, + boolean cacheData, + boolean dataIsCompressed, + ThreadFactory threadFactory) { + this( + client, + path, + cacheData, + dataIsCompressed, + new CloseableExecutorService(Executors.newSingleThreadExecutor(threadFactory), true)); } /** @@ -208,8 +223,12 @@ public PathChildrenCache(CuratorFramework client, String path, boolean cacheData * @param dataIsCompressed if true, data in the path is compressed * @param executorService ExecutorService to use for the PathChildrenCache's background thread. This service should be single threaded, otherwise the cache may see inconsistent results. */ - public PathChildrenCache(CuratorFramework client, String path, boolean cacheData, boolean dataIsCompressed, final ExecutorService executorService) - { + public PathChildrenCache( + CuratorFramework client, + String path, + boolean cacheData, + boolean dataIsCompressed, + final ExecutorService executorService) { this(client, path, cacheData, dataIsCompressed, new CloseableExecutorService(executorService)); } @@ -220,8 +239,12 @@ public PathChildrenCache(CuratorFramework client, String path, boolean cacheData * @param dataIsCompressed if true, data in the path is compressed * @param executorService Closeable ExecutorService to use for the PathChildrenCache's background thread. This service should be single threaded, otherwise the cache may see inconsistent results. */ - public PathChildrenCache(CuratorFramework client, String path, boolean cacheData, boolean dataIsCompressed, final CloseableExecutorService executorService) - { + public PathChildrenCache( + CuratorFramework client, + String path, + boolean cacheData, + boolean dataIsCompressed, + final CloseableExecutorService executorService) { this.client = client.newWatcherRemoveCuratorFramework(); this.path = PathUtils.validatePath(path); this.cacheData = cacheData; @@ -235,8 +258,7 @@ public PathChildrenCache(CuratorFramework client, String path, boolean cacheData * * @throws Exception errors */ - public void start() throws Exception - { + public void start() throws Exception { start(StartMode.NORMAL); } @@ -250,16 +272,14 @@ public void start() throws Exception * @deprecated use {@link #start(StartMode)} */ @Deprecated - public void start(boolean buildInitial) throws Exception - { + public void start(boolean buildInitial) throws Exception { start(buildInitial ? StartMode.BUILD_INITIAL_CACHE : StartMode.NORMAL); } /** * Method of priming cache on {@link PathChildrenCache#start(StartMode)} */ - public enum StartMode - { + public enum StartMode { /** * The cache will be primed (in the background) with initial values. * Events for existing and new nodes will be posted. @@ -287,29 +307,24 @@ public enum StartMode * @param mode Method for priming the cache * @throws Exception errors */ - public void start(StartMode mode) throws Exception - { + public void start(StartMode mode) throws Exception { Preconditions.checkState(state.compareAndSet(State.LATENT, State.STARTED), "already started"); mode = Preconditions.checkNotNull(mode, "mode cannot be null"); client.getConnectionStateListenable().addListener(connectionStateListener); - switch ( mode ) - { - case NORMAL: - { + switch (mode) { + case NORMAL: { offerOperation(new RefreshOperation(this, RefreshMode.STANDARD)); break; } - case BUILD_INITIAL_CACHE: - { + case BUILD_INITIAL_CACHE: { rebuild(); break; } - case POST_INITIALIZED_EVENT: - { + case POST_INITIALIZED_EVENT: { initialSet.set(Maps.newConcurrentMap()); offerOperation(new RefreshOperation(this, RefreshMode.POST_INITIALIZED)); break; @@ -323,8 +338,7 @@ public void start(StartMode mode) throws Exception * * @throws Exception errors */ - public void rebuild() throws Exception - { + public void rebuild() throws Exception { Preconditions.checkState(state.get() == State.STARTED, "cache has been closed"); ensurePath(); @@ -332,13 +346,11 @@ public void rebuild() throws Exception clear(); List children = client.getChildren().forPath(path); - for ( String child : children ) - { + for (String child : children) { String fullPath = ZKPaths.makePath(path, child); internalRebuildNode(fullPath); - if ( rebuildTestExchanger != null ) - { + if (rebuildTestExchanger != null) { rebuildTestExchanger.exchange(new Object()); } } @@ -354,9 +366,9 @@ public void rebuild() throws Exception * @param fullPath full path of the node to rebuild * @throws Exception errors */ - public void rebuildNode(String fullPath) throws Exception - { - Preconditions.checkArgument(ZKPaths.getPathAndNode(fullPath).getPath().equals(path), "Node is not part of this cache: " + fullPath); + public void rebuildNode(String fullPath) throws Exception { + Preconditions.checkArgument( + ZKPaths.getPathAndNode(fullPath).getPath().equals(path), "Node is not part of this cache: " + fullPath); Preconditions.checkState(state.get() == State.STARTED, "cache has been closed"); ensurePath(); @@ -373,10 +385,8 @@ public void rebuildNode(String fullPath) throws Exception * @throws IOException errors */ @Override - public void close() throws IOException - { - if ( state.compareAndSet(State.STARTED, State.CLOSED) ) - { + public void close() throws IOException { + if (state.compareAndSet(State.STARTED, State.CLOSED)) { client.getConnectionStateListenable().removeListener(connectionStateListener); listeners.clear(); @@ -397,8 +407,7 @@ public void close() throws IOException * * @return listenable */ - public Listenable getListenable() - { + public Listenable getListenable() { return listeners; } @@ -408,8 +417,7 @@ public Listenable getListenable() * * @return list of children and data */ - public List getCurrentData() - { + public List getCurrentData() { return ImmutableList.copyOf(Sets.newTreeSet(currentData.values())); } @@ -421,8 +429,7 @@ public List getCurrentData() * @param fullPath full path to the node to check * @return data or null */ - public ChildData getCurrentData(String fullPath) - { + public ChildData getCurrentData(String fullPath) { return currentData.get(fullPath); } @@ -432,8 +439,7 @@ public ChildData getCurrentData(String fullPath) * * @param fullPath the path of the node to clear */ - public void clearDataBytes(String fullPath) - { + public void clearDataBytes(String fullPath) { clearDataBytes(fullPath, -1); } @@ -445,15 +451,11 @@ public void clearDataBytes(String fullPath) * @param ifVersion if non-negative, only clear the data if the data's version matches this version * @return true if the data was cleared */ - public boolean clearDataBytes(String fullPath, int ifVersion) - { + public boolean clearDataBytes(String fullPath, int ifVersion) { ChildData data = currentData.get(fullPath); - if ( data != null ) - { - if ( (ifVersion < 0) || (ifVersion == data.getStat().getVersion()) ) - { - if ( data.getData() != null ) - { + if (data != null) { + if ((ifVersion < 0) || (ifVersion == data.getStat().getVersion())) { + if (data.getData() != null) { currentData.replace(fullPath, data, new ChildData(data.getPath(), data.getStat(), null)); } return true; @@ -467,8 +469,7 @@ public boolean clearDataBytes(String fullPath, int ifVersion) * * @throws Exception errors */ - public void clearAndRefresh() throws Exception - { + public void clearAndRefresh() throws Exception { currentData.clear(); offerOperation(new RefreshOperation(this, RefreshMode.STANDARD)); } @@ -477,46 +478,38 @@ public void clearAndRefresh() throws Exception * Clears the current data without beginning a new query and without generating any events * for listeners. */ - public void clear() - { + public void clear() { currentData.clear(); } - enum RefreshMode - { + enum RefreshMode { STANDARD, FORCE_GET_DATA_AND_STAT, POST_INITIALIZED, NO_NODE_EXCEPTION } - void refresh(final RefreshMode mode) throws Exception - { + void refresh(final RefreshMode mode) throws Exception { ensurePath(); - final BackgroundCallback callback = new BackgroundCallback() - { + final BackgroundCallback callback = new BackgroundCallback() { @Override - public void processResult(CuratorFramework client, CuratorEvent event) throws Exception - { - if ( reRemoveWatchersOnBackgroundClosed() ) - { + public void processResult(CuratorFramework client, CuratorEvent event) throws Exception { + if (reRemoveWatchersOnBackgroundClosed()) { return; } - if ( event.getResultCode() == KeeperException.Code.OK.intValue() ) - { + if (event.getResultCode() == KeeperException.Code.OK.intValue()) { processChildren(event.getChildren(), mode); - } - else if ( event.getResultCode() == KeeperException.Code.NONODE.intValue() ) - { - if ( mode == RefreshMode.NO_NODE_EXCEPTION ) - { - log.debug("KeeperException.NoNodeException received for getChildren() and refresh has failed. Resetting ensureContainers but not refreshing. Path: [{}]", path); + } else if (event.getResultCode() == KeeperException.Code.NONODE.intValue()) { + if (mode == RefreshMode.NO_NODE_EXCEPTION) { + log.debug( + "KeeperException.NoNodeException received for getChildren() and refresh has failed. Resetting ensureContainers but not refreshing. Path: [{}]", + path); ensureContainers.reset(); - } - else - { - log.debug("KeeperException.NoNodeException received for getChildren(). Resetting ensureContainers. Path: [{}]", path); + } else { + log.debug( + "KeeperException.NoNodeException received for getChildren(). Resetting ensureContainers. Path: [{}]", + path); ensureContainers.reset(); offerOperation(new RefreshOperation(PathChildrenCache.this, RefreshMode.NO_NODE_EXCEPTION)); } @@ -524,53 +517,53 @@ else if ( event.getResultCode() == KeeperException.Code.NONODE.intValue() ) } }; - client.getChildren().usingWatcher(childrenWatcher).inBackground(callback).forPath(path); + client.getChildren() + .usingWatcher(childrenWatcher) + .inBackground(callback) + .forPath(path); } - void callListeners(final PathChildrenCacheEvent event) - { + void callListeners(final PathChildrenCacheEvent event) { listeners.forEach(listener -> { - try - { + try { listener.childEvent(client, event); - } - catch ( Exception e ) - { + } catch (Exception e) { ThreadUtils.checkInterrupted(e); handleException(e); } }); } - void getDataAndStat(final String fullPath) throws Exception - { - BackgroundCallback callback = new BackgroundCallback() - { + void getDataAndStat(final String fullPath) throws Exception { + BackgroundCallback callback = new BackgroundCallback() { @Override - public void processResult(CuratorFramework client, CuratorEvent event) throws Exception - { - if ( reRemoveWatchersOnBackgroundClosed() ) - { + public void processResult(CuratorFramework client, CuratorEvent event) throws Exception { + if (reRemoveWatchersOnBackgroundClosed()) { return; } applyNewData(fullPath, event.getResultCode(), event.getStat(), cacheData ? event.getData() : null); } }; - if ( USE_EXISTS && !cacheData ) - { - client.checkExists().usingWatcher(dataWatcher).inBackground(callback).forPath(fullPath); - } - else - { - // always use getData() instead of exists() to avoid leaving unneeded watchers which is a type of resource leak - if ( dataIsCompressed && cacheData ) - { - client.getData().decompressed().usingWatcher(dataWatcher).inBackground(callback).forPath(fullPath); - } - else - { - client.getData().usingWatcher(dataWatcher).inBackground(callback).forPath(fullPath); + if (USE_EXISTS && !cacheData) { + client.checkExists() + .usingWatcher(dataWatcher) + .inBackground(callback) + .forPath(fullPath); + } else { + // always use getData() instead of exists() to avoid leaving unneeded watchers which is a type of resource + // leak + if (dataIsCompressed && cacheData) { + client.getData() + .decompressed() + .usingWatcher(dataWatcher) + .inBackground(callback) + .forPath(fullPath); + } else { + client.getData() + .usingWatcher(dataWatcher) + .inBackground(callback) + .forPath(fullPath); } } } @@ -580,126 +573,104 @@ public void processResult(CuratorFramework client, CuratorEvent event) throws Ex * * @param e the exception */ - protected void handleException(Throwable e) - { + protected void handleException(Throwable e) { log.error("", e); } - protected void ensurePath() throws Exception - { + protected void ensurePath() throws Exception { ensureContainers.ensure(); } @VisibleForTesting - protected void remove(String fullPath) - { + protected void remove(String fullPath) { ChildData data = currentData.remove(fullPath); - if ( data != null ) - { - offerOperation(new EventOperation(this, new PathChildrenCacheEvent(PathChildrenCacheEvent.Type.CHILD_REMOVED, data))); + if (data != null) { + offerOperation(new EventOperation( + this, new PathChildrenCacheEvent(PathChildrenCacheEvent.Type.CHILD_REMOVED, data))); } Map localInitialSet = initialSet.get(); - if ( localInitialSet != null ) - { + if (localInitialSet != null) { localInitialSet.remove(ZKPaths.getNodeFromPath(fullPath)); maybeOfferInitializedEvent(localInitialSet); } } - private boolean reRemoveWatchersOnBackgroundClosed() - { - if ( state.get().equals(State.CLOSED)) - { + private boolean reRemoveWatchersOnBackgroundClosed() { + if (state.get().equals(State.CLOSED)) { client.removeWatchers(); return true; } return false; } - private void internalRebuildNode(String fullPath) throws Exception - { - if ( cacheData ) - { - try - { + private void internalRebuildNode(String fullPath) throws Exception { + if (cacheData) { + try { Stat stat = new Stat(); - byte[] bytes = dataIsCompressed ? client.getData().decompressed().storingStatIn(stat).forPath(fullPath) : client.getData().storingStatIn(stat).forPath(fullPath); + byte[] bytes = dataIsCompressed + ? client.getData().decompressed().storingStatIn(stat).forPath(fullPath) + : client.getData().storingStatIn(stat).forPath(fullPath); currentData.put(fullPath, new ChildData(fullPath, stat, bytes)); - } - catch ( KeeperException.NoNodeException ignore ) - { + } catch (KeeperException.NoNodeException ignore) { // node no longer exists - remove it currentData.remove(fullPath); } - } - else - { + } else { Stat stat = client.checkExists().forPath(fullPath); - if ( stat != null ) - { + if (stat != null) { currentData.put(fullPath, new ChildData(fullPath, stat, null)); - } - else - { + } else { // node no longer exists - remove it currentData.remove(fullPath); } } } - private void handleStateChange(ConnectionState newState) - { - switch ( newState ) - { - case SUSPENDED: - { - offerOperation(new EventOperation(this, new PathChildrenCacheEvent(PathChildrenCacheEvent.Type.CONNECTION_SUSPENDED, null))); - break; - } - - case LOST: - { - offerOperation(new EventOperation(this, new PathChildrenCacheEvent(PathChildrenCacheEvent.Type.CONNECTION_LOST, null))); - break; - } + private void handleStateChange(ConnectionState newState) { + switch (newState) { + case SUSPENDED: { + offerOperation(new EventOperation( + this, new PathChildrenCacheEvent(PathChildrenCacheEvent.Type.CONNECTION_SUSPENDED, null))); + break; + } - case CONNECTED: - case RECONNECTED: - { - try - { - offerOperation(new RefreshOperation(this, RefreshMode.FORCE_GET_DATA_AND_STAT)); - offerOperation(new EventOperation(this, new PathChildrenCacheEvent(PathChildrenCacheEvent.Type.CONNECTION_RECONNECTED, null))); + case LOST: { + offerOperation(new EventOperation( + this, new PathChildrenCacheEvent(PathChildrenCacheEvent.Type.CONNECTION_LOST, null))); + break; } - catch ( Exception e ) - { - ThreadUtils.checkInterrupted(e); - handleException(e); + + case CONNECTED: + case RECONNECTED: { + try { + offerOperation(new RefreshOperation(this, RefreshMode.FORCE_GET_DATA_AND_STAT)); + offerOperation(new EventOperation( + this, + new PathChildrenCacheEvent(PathChildrenCacheEvent.Type.CONNECTION_RECONNECTED, null))); + } catch (Exception e) { + ThreadUtils.checkInterrupted(e); + handleException(e); + } + break; } - break; - } } } - private void processChildren(List children, RefreshMode mode) throws Exception - { + private void processChildren(List children, RefreshMode mode) throws Exception { Set removedNodes = Sets.newHashSet(currentData.keySet()); - for ( String child : children ) { + for (String child : children) { removedNodes.remove(ZKPaths.makePath(path, child)); } - for ( String fullPath : removedNodes ) - { + for (String fullPath : removedNodes) { remove(fullPath); } - for ( String name : children ) - { + for (String name : children) { String fullPath = ZKPaths.makePath(path, name); - if ( (mode == RefreshMode.FORCE_GET_DATA_AND_STAT) || !currentData.containsKey(fullPath) ) - { + if ((mode == RefreshMode.FORCE_GET_DATA_AND_STAT) || !currentData.containsKey(fullPath)) { getDataAndStat(fullPath); } @@ -708,117 +679,91 @@ private void processChildren(List children, RefreshMode mode) throws Exc maybeOfferInitializedEvent(initialSet.get()); } - private void applyNewData(String fullPath, int resultCode, Stat stat, byte[] bytes) - { - if ( resultCode == KeeperException.Code.OK.intValue() ) // otherwise - node must have dropped or something - we should be getting another event + private void applyNewData(String fullPath, int resultCode, Stat stat, byte[] bytes) { + if (resultCode + == KeeperException.Code.OK + .intValue()) // otherwise - node must have dropped or something - we should be getting another + // event { ChildData data = new ChildData(fullPath, stat, bytes); ChildData previousData = currentData.put(fullPath, data); - if ( previousData == null ) // i.e. new + if (previousData == null) // i.e. new { - offerOperation(new EventOperation(this, new PathChildrenCacheEvent(PathChildrenCacheEvent.Type.CHILD_ADDED, data))); - } - else if ( stat.getMzxid() != previousData.getStat().getMzxid() ) - { - offerOperation(new EventOperation(this, new PathChildrenCacheEvent(PathChildrenCacheEvent.Type.CHILD_UPDATED, data))); + offerOperation(new EventOperation( + this, new PathChildrenCacheEvent(PathChildrenCacheEvent.Type.CHILD_ADDED, data))); + } else if (stat.getMzxid() != previousData.getStat().getMzxid()) { + offerOperation(new EventOperation( + this, new PathChildrenCacheEvent(PathChildrenCacheEvent.Type.CHILD_UPDATED, data))); } updateInitialSet(ZKPaths.getNodeFromPath(fullPath), data); - } - else if ( resultCode == KeeperException.Code.NONODE.intValue() ) - { + } else if (resultCode == KeeperException.Code.NONODE.intValue()) { log.debug("NoNode at path {}, removing child from initialSet", fullPath); remove(fullPath); } } - private void updateInitialSet(String name, ChildData data) - { + private void updateInitialSet(String name, ChildData data) { Map localInitialSet = initialSet.get(); - if ( localInitialSet != null ) - { + if (localInitialSet != null) { localInitialSet.put(name, data); maybeOfferInitializedEvent(localInitialSet); } } - private void maybeOfferInitializedEvent(Map localInitialSet) - { - if ( !hasUninitialized(localInitialSet) ) - { + private void maybeOfferInitializedEvent(Map localInitialSet) { + if (!hasUninitialized(localInitialSet)) { // all initial children have been processed - send initialized message - if ( initialSet.getAndSet(null) != null ) // avoid edge case - don't send more than 1 INITIALIZED event + if (initialSet.getAndSet(null) != null) // avoid edge case - don't send more than 1 INITIALIZED event { final List children = ImmutableList.copyOf(localInitialSet.values()); - PathChildrenCacheEvent event = new PathChildrenCacheEvent(PathChildrenCacheEvent.Type.INITIALIZED, null) - { - @Override - public List getInitialData() - { - return children; - } - }; + PathChildrenCacheEvent event = + new PathChildrenCacheEvent(PathChildrenCacheEvent.Type.INITIALIZED, null) { + @Override + public List getInitialData() { + return children; + } + }; offerOperation(new EventOperation(this, event)); } } } - private boolean hasUninitialized(Map localInitialSet) - { - if ( localInitialSet == null ) - { + private boolean hasUninitialized(Map localInitialSet) { + if (localInitialSet == null) { return false; } - Map uninitializedChildren = Maps.filterValues - ( - localInitialSet, - new Predicate() - { - @Override - public boolean apply(ChildData input) - { - return (input == NULL_CHILD_DATA); // check against ref intentional - } - } - ); + Map uninitializedChildren = Maps.filterValues(localInitialSet, new Predicate() { + @Override + public boolean apply(ChildData input) { + return (input == NULL_CHILD_DATA); // check against ref intentional + } + }); return (uninitializedChildren.size() != 0); } - void offerOperation(final Operation operation) - { - if ( operationsQuantizer.add(operation) ) - { - submitToExecutor - ( - new Runnable() - { - @Override - public void run() - { - try - { - operationsQuantizer.remove(operation); - operation.invoke(); - } - catch ( InterruptedException e ) - { - //We expect to get interrupted during shutdown, - //so just ignore these events - if ( state.get() != State.CLOSED ) - { - handleException(e); - } - Thread.currentThread().interrupt(); - } - catch ( Exception e ) - { - ThreadUtils.checkInterrupted(e); + void offerOperation(final Operation operation) { + if (operationsQuantizer.add(operation)) { + submitToExecutor(new Runnable() { + @Override + public void run() { + try { + operationsQuantizer.remove(operation); + operation.invoke(); + } catch (InterruptedException e) { + // We expect to get interrupted during shutdown, + // so just ignore these events + if (state.get() != State.CLOSED) { handleException(e); } + Thread.currentThread().interrupt(); + } catch (Exception e) { + ThreadUtils.checkInterrupted(e); + handleException(e); } } - ); + }); } } @@ -835,10 +780,8 @@ public void run() * * @param command The runnable to run */ - private synchronized void submitToExecutor(final Runnable command) - { - if ( state.get() == State.STARTED ) - { + private synchronized void submitToExecutor(final Runnable command) { + if (state.get() == State.STARTED) { executorService.submit(command); } } diff --git a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/PathChildrenCacheEvent.java b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/PathChildrenCacheEvent.java index 8d7fb868a..cffff8dc4 100644 --- a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/PathChildrenCacheEvent.java +++ b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/PathChildrenCacheEvent.java @@ -19,22 +19,20 @@ package org.apache.curator.framework.recipes.cache; -import org.apache.curator.framework.state.ConnectionState; import java.util.List; +import org.apache.curator.framework.state.ConnectionState; /** * POJO that abstracts a change to a path */ -public class PathChildrenCacheEvent -{ +public class PathChildrenCacheEvent { private final Type type; private final ChildData data; /** * Type of change */ - public enum Type - { + public enum Type { /** * A child was added to the path */ @@ -98,8 +96,7 @@ public enum Type * @param type event type * @param data event data or null */ - public PathChildrenCacheEvent(Type type, ChildData data) - { + public PathChildrenCacheEvent(Type type, ChildData data) { this.type = type; this.data = data; } @@ -107,16 +104,14 @@ public PathChildrenCacheEvent(Type type, ChildData data) /** * @return change type */ - public Type getType() - { + public Type getType() { return type; } /** * @return the node's data */ - public ChildData getData() - { + public ChildData getData() { return data; } @@ -127,17 +122,12 @@ public ChildData getData() * * @return initial state of cache for {@link Type#INITIALIZED} events. Otherwise, null. */ - public List getInitialData() - { + public List getInitialData() { return null; } @Override - public String toString() - { - return "PathChildrenCacheEvent{" + - "type=" + type + - ", data=" + data + - '}'; + public String toString() { + return "PathChildrenCacheEvent{" + "type=" + type + ", data=" + data + '}'; } } diff --git a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/PathChildrenCacheListener.java b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/PathChildrenCacheListener.java index 0e8a30923..79b33c121 100644 --- a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/PathChildrenCacheListener.java +++ b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/PathChildrenCacheListener.java @@ -24,8 +24,7 @@ /** * Listener for PathChildrenCache changes */ -public interface PathChildrenCacheListener -{ +public interface PathChildrenCacheListener { /** * Called when a change has occurred * @@ -33,5 +32,5 @@ public interface PathChildrenCacheListener * @param event describes the change * @throws Exception errors */ - public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception; + public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception; } diff --git a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/PathChildrenCacheListenerWrapper.java b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/PathChildrenCacheListenerWrapper.java index ebfb2fc2e..afffb69bd 100644 --- a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/PathChildrenCacheListenerWrapper.java +++ b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/PathChildrenCacheListenerWrapper.java @@ -22,27 +22,22 @@ import java.util.Objects; import org.apache.curator.framework.CuratorFramework; -class PathChildrenCacheListenerWrapper implements CuratorCacheListener -{ +class PathChildrenCacheListenerWrapper implements CuratorCacheListener { private final PathChildrenCacheListener listener; private final CuratorFramework client; private final String rootPath; - PathChildrenCacheListenerWrapper(String rootPath, CuratorFramework client, PathChildrenCacheListener listener) - { - Objects.requireNonNull(rootPath,"rootPath cannot be null"); + PathChildrenCacheListenerWrapper(String rootPath, CuratorFramework client, PathChildrenCacheListener listener) { + Objects.requireNonNull(rootPath, "rootPath cannot be null"); this.rootPath = rootPath; this.listener = listener; this.client = client; } @Override - public void event(Type type, ChildData oldData, ChildData data) - { - switch ( type ) - { - case NODE_CREATED: - { + public void event(Type type, ChildData oldData, ChildData data) { + switch (type) { + case NODE_CREATED: { if (rootPath.equals(data.getPath())) { return; } @@ -50,8 +45,7 @@ public void event(Type type, ChildData oldData, ChildData data) break; } - case NODE_CHANGED: - { + case NODE_CHANGED: { if (rootPath.equals(data.getPath())) { return; } @@ -59,8 +53,7 @@ public void event(Type type, ChildData oldData, ChildData data) break; } - case NODE_DELETED: - { + case NODE_DELETED: { if (rootPath.equals(oldData.getPath())) { return; } @@ -71,21 +64,16 @@ public void event(Type type, ChildData oldData, ChildData data) } @Override - public void initialized() - { + public void initialized() { sendEvent(null, PathChildrenCacheEvent.Type.INITIALIZED); } - private void sendEvent(ChildData node, PathChildrenCacheEvent.Type type) - { + private void sendEvent(ChildData node, PathChildrenCacheEvent.Type type) { PathChildrenCacheEvent event = new PathChildrenCacheEvent(type, node); - try - { + try { listener.childEvent(client, event); - } - catch ( Exception e ) - { + } catch (Exception e) { throw new RuntimeException(e); } } -} \ No newline at end of file +} diff --git a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/PathChildrenCacheMode.java b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/PathChildrenCacheMode.java index 06aead1c9..d952c5610 100644 --- a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/PathChildrenCacheMode.java +++ b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/PathChildrenCacheMode.java @@ -19,8 +19,8 @@ package org.apache.curator.framework.recipes.cache; -import org.apache.curator.framework.CuratorFramework; import java.util.concurrent.ThreadFactory; +import org.apache.curator.framework.CuratorFramework; /** * Controls which data is cached @@ -29,8 +29,7 @@ * or {@link PathChildrenCache#PathChildrenCache(CuratorFramework, String, boolean, ThreadFactory)} */ @Deprecated -public enum PathChildrenCacheMode -{ +public enum PathChildrenCacheMode { /** * The cache will hold all the children, the data for each child node * and the stat for each child node diff --git a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/RefreshOperation.java b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/RefreshOperation.java index 6ea443aa7..a86818c66 100644 --- a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/RefreshOperation.java +++ b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/RefreshOperation.java @@ -19,40 +19,33 @@ package org.apache.curator.framework.recipes.cache; -class RefreshOperation implements Operation -{ +class RefreshOperation implements Operation { private final PathChildrenCache cache; private final PathChildrenCache.RefreshMode mode; - RefreshOperation(PathChildrenCache cache, PathChildrenCache.RefreshMode mode) - { + RefreshOperation(PathChildrenCache cache, PathChildrenCache.RefreshMode mode) { this.cache = cache; this.mode = mode; } @Override - public void invoke() throws Exception - { + public void invoke() throws Exception { cache.refresh(mode); } @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; } - RefreshOperation that = (RefreshOperation)o; + RefreshOperation that = (RefreshOperation) o; //noinspection RedundantIfStatement - if ( mode != that.mode ) - { + if (mode != that.mode) { return false; } @@ -60,14 +53,12 @@ public boolean equals(Object o) } @Override - public int hashCode() - { + public int hashCode() { return mode.hashCode(); } @Override - public String toString() - { + public String toString() { return "RefreshOperation(" + mode + "){}"; } } diff --git a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/StandardCuratorCacheStorage.java b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/StandardCuratorCacheStorage.java index 5eb4cc6e0..3cf01b1d4 100644 --- a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/StandardCuratorCacheStorage.java +++ b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/StandardCuratorCacheStorage.java @@ -24,51 +24,43 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.stream.Stream; -class StandardCuratorCacheStorage implements CuratorCacheStorage -{ +class StandardCuratorCacheStorage implements CuratorCacheStorage { private final Map dataMap; private final boolean cacheBytes; - StandardCuratorCacheStorage(boolean cacheBytes) - { + StandardCuratorCacheStorage(boolean cacheBytes) { this.dataMap = new ConcurrentHashMap<>(); this.cacheBytes = cacheBytes; } @Override - public Optional put(ChildData data) - { + public Optional put(ChildData data) { ChildData localData = cacheBytes ? data : new ChildData(data.getPath(), data.getStat(), null); return Optional.ofNullable(dataMap.put(data.getPath(), localData)); } @Override - public Optional remove(String path) - { + public Optional remove(String path) { return Optional.ofNullable(dataMap.remove(path)); } @Override - public Optional get(String path) - { + public Optional get(String path) { return Optional.ofNullable(dataMap.get(path)); } @Override - public int size() - { + public int size() { return dataMap.size(); } @Override - public Stream stream() - { + public Stream stream() { return dataMap.values().stream(); } @Override - public void clear() - { + public void clear() { dataMap.clear(); } -} \ No newline at end of file +} diff --git a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/TreeCache.java b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/TreeCache.java index 91ae7531c..2aaa8cc47 100644 --- a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/TreeCache.java +++ b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/TreeCache.java @@ -19,10 +19,27 @@ package org.apache.curator.framework.recipes.cache; +import static com.google.common.base.Preconditions.checkNotNull; +import static org.apache.curator.utils.PathUtils.validatePath; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Maps; +import java.io.Closeable; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentMap; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.ThreadFactory; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicLong; +import java.util.concurrent.atomic.AtomicReference; +import java.util.concurrent.atomic.AtomicReferenceFieldUpdater; import java.util.function.Supplier; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.WatcherRemoveCuratorFramework; @@ -45,24 +62,6 @@ import org.apache.zookeeper.data.Stat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.io.Closeable; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.concurrent.ConcurrentMap; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.ThreadFactory; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicLong; -import java.util.concurrent.atomic.AtomicReference; -import java.util.concurrent.atomic.AtomicReferenceFieldUpdater; - -import static com.google.common.base.Preconditions.checkNotNull; -import static org.apache.curator.utils.PathUtils.validatePath; /** *

A utility that attempts to keep all data from all children of a ZK path locally cached. This class @@ -76,15 +75,13 @@ * @deprecated replace by {@link org.apache.curator.framework.recipes.cache.CuratorCache} */ @Deprecated -public class TreeCache implements Closeable -{ +public class TreeCache implements Closeable { private static final Logger LOG = LoggerFactory.getLogger(TreeCache.class); private final boolean createParentNodes; private final boolean disableZkWatches; private final TreeCacheSelector selector; - public static final class Builder - { + public static final class Builder { private final CuratorFramework client; private final String path; private boolean cacheData = true; @@ -95,8 +92,7 @@ public static final class Builder private boolean disableZkWatches = false; private TreeCacheSelector selector = new DefaultTreeCacheSelector(); - private Builder(CuratorFramework client, String path) - { + private Builder(CuratorFramework client, String path) { this.client = checkNotNull(client); this.path = validatePath(path); } @@ -104,21 +100,27 @@ private Builder(CuratorFramework client, String path) /** * Builds the {@link TreeCache} based on configured values. */ - public TreeCache build() - { + public TreeCache build() { ExecutorService executor = executorService; - if ( executor == null ) - { + if (executor == null) { executor = Executors.newSingleThreadExecutor(defaultThreadFactorySupplier.get()); } - return new TreeCache(client, path, cacheData, dataIsCompressed, maxDepth, executor, createParentNodes, disableZkWatches, selector); + return new TreeCache( + client, + path, + cacheData, + dataIsCompressed, + maxDepth, + executor, + createParentNodes, + disableZkWatches, + selector); } /** * Sets whether or not to cache byte data per node; default {@code true}. */ - public Builder setCacheData(boolean cacheData) - { + public Builder setCacheData(boolean cacheData) { this.cacheData = cacheData; return this; } @@ -126,8 +128,7 @@ public Builder setCacheData(boolean cacheData) /** * Sets whether or to decompress node data; default {@code false}. */ - public Builder setDataIsCompressed(boolean dataIsCompressed) - { + public Builder setDataIsCompressed(boolean dataIsCompressed) { this.dataIsCompressed = dataIsCompressed; return this; } @@ -135,16 +136,14 @@ public Builder setDataIsCompressed(boolean dataIsCompressed) /** * Sets the executor to publish events; a default executor will be created if not specified. */ - public Builder setExecutor(ThreadFactory threadFactory) - { + public Builder setExecutor(ThreadFactory threadFactory) { return setExecutor(Executors.newSingleThreadExecutor(threadFactory)); } /** * Sets the executor to publish events; a default executor will be created if not specified. */ - public Builder setExecutor(ExecutorService executorService) - { + public Builder setExecutor(ExecutorService executorService) { this.executorService = checkNotNull(executorService); return this; } @@ -155,8 +154,7 @@ public Builder setExecutor(ExecutorService executorService) * root node and its immediate children (kind of like {@link PathChildrenCache}. * Default: {@code Integer.MAX_VALUE} */ - public Builder setMaxDepth(int maxDepth) - { + public Builder setMaxDepth(int maxDepth) { this.maxDepth = maxDepth; return this; } @@ -168,8 +166,7 @@ public Builder setMaxDepth(int maxDepth) * @param createParentNodes true to create parent nodes * @return this for chaining */ - public Builder setCreateParentNodes(boolean createParentNodes) - { + public Builder setCreateParentNodes(boolean createParentNodes) { this.createParentNodes = createParentNodes; return this; } @@ -180,8 +177,7 @@ public Builder setCreateParentNodes(boolean createParentNodes) * @param disableZkWatches true to disable zk watches * @return this for chaining */ - public Builder disableZkWatches(boolean disableZkWatches) - { + public Builder disableZkWatches(boolean disableZkWatches) { this.disableZkWatches = disableZkWatches; return this; } @@ -192,8 +188,7 @@ public Builder disableZkWatches(boolean disableZkWatches) * @param selector new selector * @return this for chaining */ - public Builder setSelector(TreeCacheSelector selector) - { + public Builder setSelector(TreeCacheSelector selector) { this.selector = selector; return this; } @@ -212,41 +207,38 @@ public Builder setSelector(TreeCacheSelector selector) * the server * @return a new builder */ - public static Builder newBuilder(CuratorFramework client, String path) - { + public static Builder newBuilder(CuratorFramework client, String path) { return new Builder(client, path); } private static final ChildData DEAD = new ChildData("/", null, null); - static boolean isLive(ChildData cd) - { + static boolean isLive(ChildData cd) { return cd != null && cd != DEAD; } - private static final AtomicReferenceFieldUpdater childDataUpdater = AtomicReferenceFieldUpdater.newUpdater(TreeNode.class, ChildData.class, "childData"); + private static final AtomicReferenceFieldUpdater childDataUpdater = + AtomicReferenceFieldUpdater.newUpdater(TreeNode.class, ChildData.class, "childData"); - private static final AtomicReferenceFieldUpdater> childrenUpdater = (AtomicReferenceFieldUpdater)AtomicReferenceFieldUpdater.newUpdater(TreeNode.class, ConcurrentMap.class, "children"); + private static final AtomicReferenceFieldUpdater> childrenUpdater = + (AtomicReferenceFieldUpdater) + AtomicReferenceFieldUpdater.newUpdater(TreeNode.class, ConcurrentMap.class, "children"); - final class TreeNode implements Watcher, BackgroundCallback - { + final class TreeNode implements Watcher, BackgroundCallback { volatile ChildData childData; final TreeNode parent; final String path; volatile ConcurrentMap children; final int depth; - TreeNode(String path, TreeNode parent) - { + TreeNode(String path, TreeNode parent) { this.path = path; this.parent = parent; this.depth = parent == null ? 0 : parent.depth + 1; } - private void refresh() throws Exception - { - if ((depth < maxDepth) && selector.traverseChildren(path)) - { + private void refresh() throws Exception { + if ((depth < maxDepth) && selector.traverseChildren(path)) { outstandingOps.addAndGet(2); doRefreshData(); doRefreshChildren(); @@ -255,46 +247,36 @@ private void refresh() throws Exception } } - private void refreshChildren() throws Exception - { - if ((depth < maxDepth) && selector.traverseChildren(path)) - { + private void refreshChildren() throws Exception { + if ((depth < maxDepth) && selector.traverseChildren(path)) { outstandingOps.incrementAndGet(); doRefreshChildren(); } } - private void refreshData() throws Exception - { + private void refreshData() throws Exception { outstandingOps.incrementAndGet(); doRefreshData(); } - private void doRefreshChildren() throws Exception - { - if ( treeState.get() == TreeState.STARTED ) - { + private void doRefreshChildren() throws Exception { + if (treeState.get() == TreeState.STARTED) { maybeWatch(client.getChildren()).forPath(path); } } - private void doRefreshData() throws Exception - { - if ( treeState.get() == TreeState.STARTED ) - { - if ( dataIsCompressed ) - { + private void doRefreshData() throws Exception { + if (treeState.get() == TreeState.STARTED) { + if (dataIsCompressed) { maybeWatch(client.getData().decompressed()).forPath(path); - } - else - { + } else { maybeWatch(client.getData()).forPath(path); } } } private > & BackgroundPathable> Pathable maybeWatch( - P dataBuilder) { + P dataBuilder) { if (disableZkWatches) { return dataBuilder.inBackground(this); } else { @@ -302,225 +284,184 @@ private > & BackgroundPathable> } } - void wasReconnected() throws Exception - { + void wasReconnected() throws Exception { refresh(); ConcurrentMap childMap = children; - if ( childMap != null ) - { - for ( TreeNode child : childMap.values() ) - { + if (childMap != null) { + for (TreeNode child : childMap.values()) { child.wasReconnected(); } } } - void wasCreated() throws Exception - { + void wasCreated() throws Exception { refresh(); } - void wasDeleted() throws Exception - { + void wasDeleted() throws Exception { ChildData oldChildData = childDataUpdater.getAndSet(this, DEAD); - if ( oldChildData == DEAD ) - { + if (oldChildData == DEAD) { return; } ConcurrentMap childMap = childrenUpdater.getAndSet(this, null); - if ( childMap != null ) - { + if (childMap != null) { ArrayList childCopy = new ArrayList(childMap.values()); childMap.clear(); - for ( TreeNode child : childCopy ) - { + for (TreeNode child : childCopy) { child.wasDeleted(); } } - if ( treeState.get() == TreeState.CLOSED ) - { + if (treeState.get() == TreeState.CLOSED) { return; } - if ( isLive(oldChildData) ) - { + if (isLive(oldChildData)) { publishEvent(TreeCacheEvent.Type.NODE_REMOVED, oldChildData, null); } - if ( parent == null ) - { + if (parent == null) { // Root node; use an exist query to watch for existence. maybeWatch(client.checkExists()).forPath(path); - } - else - { + } else { // Remove from parent if we're currently a child ConcurrentMap parentChildMap = parent.children; - if ( parentChildMap != null ) - { + if (parentChildMap != null) { parentChildMap.remove(ZKPaths.getNodeFromPath(path), this); } } } @Override - public void process(WatchedEvent event) - { + public void process(WatchedEvent event) { LOG.debug("process: {}", event); - try - { - switch ( event.getType() ) - { - case NodeCreated: - Preconditions.checkState(parent == null, "unexpected NodeCreated on non-root node"); - wasCreated(); - break; - case NodeChildrenChanged: - refreshChildren(); - break; - case NodeDataChanged: - refreshData(); - break; - case NodeDeleted: - wasDeleted(); - break; + try { + switch (event.getType()) { + case NodeCreated: + Preconditions.checkState(parent == null, "unexpected NodeCreated on non-root node"); + wasCreated(); + break; + case NodeChildrenChanged: + refreshChildren(); + break; + case NodeDataChanged: + refreshData(); + break; + case NodeDeleted: + wasDeleted(); + break; } - } - catch ( Exception e ) - { + } catch (Exception e) { ThreadUtils.checkInterrupted(e); handleException(e); } } @Override - public void processResult(CuratorFramework client, CuratorEvent event) throws Exception - { + public void processResult(CuratorFramework client, CuratorEvent event) throws Exception { LOG.debug("processResult: {}", event); Stat newStat = event.getStat(); - switch ( event.getType() ) - { - case EXISTS: - Preconditions.checkState(parent == null, "unexpected EXISTS on non-root node"); - if ( event.getResultCode() == KeeperException.Code.OK.intValue() ) - { - childDataUpdater.compareAndSet(this, DEAD, null); - wasCreated(); - } - break; - case CHILDREN: - if ( event.getResultCode() == KeeperException.Code.OK.intValue() ) - { - ChildData oldChildData = childData; - //TODO consider doing update of cversion, pzxid, numChildren only - if ( isLive(oldChildData) && oldChildData.getStat().getMzxid() == newStat.getMzxid() ) - { - // Only update stat if mzxid is same, otherwise we might obscure - // GET_DATA event updates. - childDataUpdater.compareAndSet(this, oldChildData, new ChildData(oldChildData.getPath(), newStat, oldChildData.getData())); + switch (event.getType()) { + case EXISTS: + Preconditions.checkState(parent == null, "unexpected EXISTS on non-root node"); + if (event.getResultCode() == KeeperException.Code.OK.intValue()) { + childDataUpdater.compareAndSet(this, DEAD, null); + wasCreated(); } + break; + case CHILDREN: + if (event.getResultCode() == KeeperException.Code.OK.intValue()) { + ChildData oldChildData = childData; + // TODO consider doing update of cversion, pzxid, numChildren only + if (isLive(oldChildData) && oldChildData.getStat().getMzxid() == newStat.getMzxid()) { + // Only update stat if mzxid is same, otherwise we might obscure + // GET_DATA event updates. + childDataUpdater.compareAndSet( + this, + oldChildData, + new ChildData(oldChildData.getPath(), newStat, oldChildData.getData())); + } - if ( event.getChildren().isEmpty() ) - { - break; - } + if (event.getChildren().isEmpty()) { + break; + } - ConcurrentMap childMap = children; - while ( childMap == null ) - { - childMap = Maps.newConcurrentMap(); - if ( !childrenUpdater.compareAndSet(this, null, childMap) ) - { - childMap = children; + ConcurrentMap childMap = children; + while (childMap == null) { + childMap = Maps.newConcurrentMap(); + if (!childrenUpdater.compareAndSet(this, null, childMap)) { + childMap = children; + } } - } - // Present new children in sorted order for test determinism. - List newChildren = new ArrayList(); - for ( String child : event.getChildren() ) - { - if ( !childMap.containsKey(child) && selector.acceptChild(ZKPaths.makePath(path, child)) ) - { - newChildren.add(child); + // Present new children in sorted order for test determinism. + List newChildren = new ArrayList(); + for (String child : event.getChildren()) { + if (!childMap.containsKey(child) && selector.acceptChild(ZKPaths.makePath(path, child))) { + newChildren.add(child); + } } - } - Collections.sort(newChildren); - for ( String child : newChildren ) - { - String fullPath = ZKPaths.makePath(path, child); - TreeNode node = new TreeNode(fullPath, this); - if ( childMap.putIfAbsent(child, node) == null ) - { - node.wasCreated(); + Collections.sort(newChildren); + for (String child : newChildren) { + String fullPath = ZKPaths.makePath(path, child); + TreeNode node = new TreeNode(fullPath, this); + if (childMap.putIfAbsent(child, node) == null) { + node.wasCreated(); + } } + } else if (event.getResultCode() == KeeperException.Code.NONODE.intValue()) { + wasDeleted(); } - } - else if ( event.getResultCode() == KeeperException.Code.NONODE.intValue() ) - { - wasDeleted(); - } - break; - case GET_DATA: - if ( event.getResultCode() == KeeperException.Code.OK.intValue() ) - { - String eventPath = event.getPath(); - ChildData toPublish = new ChildData(eventPath, newStat, event.getData()); - ChildData toUpdate = cacheData ? toPublish : new ChildData(eventPath, newStat, null); - while ( true ) - { - final ChildData oldChildData = childData; - // Ignore this event if we've already processed a newer update for this node. - if ( isLive(oldChildData) && newStat.getMzxid() <= oldChildData.getStat().getMzxid() ) - { - break; - } - // Non-root nodes are not allowed to transition from dead -> live; - // make sure this isn't a delayed response that came in after death. - if ( parent != null && oldChildData == DEAD ) - { - break; - } - if ( childDataUpdater.compareAndSet(this, oldChildData, toUpdate) ) - { - if ( isLive(oldChildData) ) - { - publishEvent(TreeCacheEvent.Type.NODE_UPDATED, toPublish, oldChildData); + break; + case GET_DATA: + if (event.getResultCode() == KeeperException.Code.OK.intValue()) { + String eventPath = event.getPath(); + ChildData toPublish = new ChildData(eventPath, newStat, event.getData()); + ChildData toUpdate = cacheData ? toPublish : new ChildData(eventPath, newStat, null); + while (true) { + final ChildData oldChildData = childData; + // Ignore this event if we've already processed a newer update for this node. + if (isLive(oldChildData) + && newStat.getMzxid() + <= oldChildData.getStat().getMzxid()) { + break; } - else - { - publishEvent(TreeCacheEvent.Type.NODE_ADDED, toPublish, null); + // Non-root nodes are not allowed to transition from dead -> live; + // make sure this isn't a delayed response that came in after death. + if (parent != null && oldChildData == DEAD) { + break; + } + if (childDataUpdater.compareAndSet(this, oldChildData, toUpdate)) { + if (isLive(oldChildData)) { + publishEvent(TreeCacheEvent.Type.NODE_UPDATED, toPublish, oldChildData); + } else { + publishEvent(TreeCacheEvent.Type.NODE_ADDED, toPublish, null); + } + break; } - break; } + } else if (event.getResultCode() == KeeperException.Code.NONODE.intValue()) { + wasDeleted(); } - } - else if ( event.getResultCode() == KeeperException.Code.NONODE.intValue() ) - { - wasDeleted(); - } - break; - default: - // An unknown event, probably an error of some sort like connection loss. - LOG.info(String.format("Unknown event %s", event)); - // Don't produce an initialized event on error; reconnect can fix this. - outstandingOps.decrementAndGet(); - return; + break; + default: + // An unknown event, probably an error of some sort like connection loss. + LOG.info(String.format("Unknown event %s", event)); + // Don't produce an initialized event on error; reconnect can fix this. + outstandingOps.decrementAndGet(); + return; } - if ( outstandingOps.decrementAndGet() == 0 ) - { - if ( isInitialized.compareAndSet(false, true) ) - { + if (outstandingOps.decrementAndGet() == 0) { + if (isInitialized.compareAndSet(false, true)) { publishEvent(TreeCacheEvent.Type.INITIALIZED); } } } } - private enum TreeState - { + private enum TreeState { LATENT, STARTED, CLOSED @@ -546,16 +487,15 @@ private enum TreeState private final StandardListenerManager errorListeners = StandardListenerManager.standard(); private final AtomicReference treeState = new AtomicReference(TreeState.LATENT); - private final ConnectionStateListener connectionStateListener = new ConnectionStateListener() - { + private final ConnectionStateListener connectionStateListener = new ConnectionStateListener() { @Override - public void stateChanged(CuratorFramework client, ConnectionState newState) - { + public void stateChanged(CuratorFramework client, ConnectionState newState) { handleStateChange(newState); } }; - private static final Supplier defaultThreadFactorySupplier = () -> ThreadUtils.newThreadFactory("TreeCache"); + private static final Supplier defaultThreadFactorySupplier = + () -> ThreadUtils.newThreadFactory("TreeCache"); /** * Create a TreeCache for the given client and path with default options. @@ -570,9 +510,17 @@ public void stateChanged(CuratorFramework client, ConnectionState newState) * the server * @see #newBuilder(CuratorFramework, String) */ - public TreeCache(CuratorFramework client, String path) - { - this(client, path, true, false, Integer.MAX_VALUE, Executors.newSingleThreadExecutor(defaultThreadFactorySupplier.get()), false, false, new DefaultTreeCacheSelector()); + public TreeCache(CuratorFramework client, String path) { + this( + client, + path, + true, + false, + Integer.MAX_VALUE, + Executors.newSingleThreadExecutor(defaultThreadFactorySupplier.get()), + false, + false, + new DefaultTreeCacheSelector()); } /** @@ -585,8 +533,16 @@ public TreeCache(CuratorFramework client, String path) * @param disableZkWatches true to disable Zookeeper watches * @param selector the selector to use */ - TreeCache(CuratorFramework client, String path, boolean cacheData, boolean dataIsCompressed, int maxDepth, final ExecutorService executorService, boolean createParentNodes, boolean disableZkWatches, TreeCacheSelector selector) - { + TreeCache( + CuratorFramework client, + String path, + boolean cacheData, + boolean dataIsCompressed, + int maxDepth, + final ExecutorService executorService, + boolean createParentNodes, + boolean disableZkWatches, + TreeCacheSelector selector) { this.createParentNodes = createParentNodes; this.selector = Preconditions.checkNotNull(selector, "selector cannot be null"); this.root = new TreeNode(validatePath(path), null); @@ -605,16 +561,13 @@ public TreeCache(CuratorFramework client, String path) * @return this * @throws Exception errors */ - public TreeCache start() throws Exception - { + public TreeCache start() throws Exception { Preconditions.checkState(treeState.compareAndSet(TreeState.LATENT, TreeState.STARTED), "already started"); - if ( createParentNodes ) - { + if (createParentNodes) { client.createContainers(root.path); } client.getConnectionStateListenable().addListener(connectionStateListener); - if ( client.getZookeeperClient().isConnected() ) - { + if (client.getZookeeperClient().isConnected()) { root.wasCreated(); } return this; @@ -624,20 +577,15 @@ public TreeCache start() throws Exception * Close/end the cache. */ @Override - public void close() - { - if ( treeState.compareAndSet(TreeState.STARTED, TreeState.CLOSED) ) - { + public void close() { + if (treeState.compareAndSet(TreeState.STARTED, TreeState.CLOSED)) { client.removeWatchers(); client.getConnectionStateListenable().removeListener(connectionStateListener); listeners.clear(); executorService.shutdown(); - try - { + try { root.wasDeleted(); - } - catch ( Exception e ) - { + } catch (Exception e) { ThreadUtils.checkInterrupted(e); handleException(e); } @@ -649,8 +597,7 @@ public void close() * * @return listenable */ - public Listenable getListenable() - { + public Listenable getListenable() { return listeners; } @@ -660,13 +607,11 @@ public Listenable getListenable() * TODO: consider making public. */ @VisibleForTesting - public Listenable getUnhandledErrorListenable() - { + public Listenable getUnhandledErrorListenable() { return errorListeners; } - private TreeNode find(String findPath) - { + private TreeNode find(String findPath) { PathUtils.validatePath(findPath); LinkedList rootElements = new LinkedList(ZKPaths.split(root.path)); LinkedList findElements = new LinkedList(ZKPaths.split(findPath)); @@ -687,13 +632,11 @@ private TreeNode find(String findPath) while (!findElements.isEmpty()) { String nextFind = findElements.removeFirst(); ConcurrentMap map = current.children; - if ( map == null ) - { + if (map == null) { return null; } current = map.get(nextFind); - if ( current == null ) - { + if (current == null) { return null; } } @@ -708,28 +651,21 @@ private TreeNode find(String findPath) * @param fullPath full path to the node to check * @return a possibly-empty list of children if the node is alive, or null */ - public Map getCurrentChildren(String fullPath) - { + public Map getCurrentChildren(String fullPath) { TreeNode node = find(fullPath); - if ( node == null || !isLive(node.childData) ) - { + if (node == null || !isLive(node.childData)) { return null; } ConcurrentMap map = node.children; Map result; - if ( map == null ) - { + if (map == null) { result = ImmutableMap.of(); - } - else - { + } else { ImmutableMap.Builder builder = ImmutableMap.builder(); - for ( Map.Entry entry : map.entrySet() ) - { + for (Map.Entry entry : map.entrySet()) { ChildData childData = entry.getValue().childData; // Double-check liveness after retrieving data. - if ( isLive(childData) ) - { + if (isLive(childData)) { builder.put(entry.getKey(), childData); } } @@ -748,11 +684,9 @@ public Map getCurrentChildren(String fullPath) * @param fullPath full path to the node to check * @return data if the node is alive, or null */ - public ChildData getCurrentData(String fullPath) - { + public ChildData getCurrentData(String fullPath) { TreeNode node = find(fullPath); - if ( node == null ) - { + if (node == null) { return null; } ChildData result = node.childData; @@ -765,8 +699,7 @@ public ChildData getCurrentData(String fullPath) * * @return a possibly-empty iterator of nodes in the cache */ - public Iterator iterator() - { + public Iterator iterator() { return new TreeCacheIterator(root); } @@ -776,42 +709,30 @@ public Iterator iterator() * * @return size */ - public int size() - { + public int size() { return size(root); } - private int size(TreeNode node) - { + private int size(TreeNode node) { int size; - if ( isLive(node.childData) ) - { + if (isLive(node.childData)) { size = 1; - if ( node.children != null ) - { - for ( TreeNode child : node.children.values() ) - { + if (node.children != null) { + for (TreeNode child : node.children.values()) { size += size(child); } } - } - else - { + } else { size = 0; } return size; } - private void callListeners(final TreeCacheEvent event) - { - listeners.forEach(listener -> - { - try - { + private void callListeners(final TreeCacheEvent event) { + listeners.forEach(listener -> { + try { listener.childEvent(client, event); - } - catch ( Exception e ) - { + } catch (Exception e) { ThreadUtils.checkInterrupted(e); handleException(e); } @@ -821,22 +742,14 @@ private void callListeners(final TreeCacheEvent event) /** * Send an exception to any listeners, or else log the error if there are none. */ - private void handleException(final Throwable e) - { - if ( errorListeners.size() == 0 ) - { + private void handleException(final Throwable e) { + if (errorListeners.size() == 0) { LOG.error("", e); - } - else - { - errorListeners.forEach(listener -> - { - try - { + } else { + errorListeners.forEach(listener -> { + try { listener.unhandledError("", e); - } - catch ( Exception e2 ) - { + } catch (Exception e2) { ThreadUtils.checkInterrupted(e2); LOG.error("Exception handling exception", e2); } @@ -844,72 +757,55 @@ private void handleException(final Throwable e) } } - private void handleStateChange(ConnectionState newState) - { - switch ( newState ) - { - case SUSPENDED: - publishEvent(TreeCacheEvent.Type.CONNECTION_SUSPENDED); - break; - - case LOST: - isInitialized.set(false); - publishEvent(TreeCacheEvent.Type.CONNECTION_LOST); - break; - - case CONNECTED: - try - { - root.wasCreated(); - } - catch ( Exception e ) - { - ThreadUtils.checkInterrupted(e); - handleException(e); - } - break; + private void handleStateChange(ConnectionState newState) { + switch (newState) { + case SUSPENDED: + publishEvent(TreeCacheEvent.Type.CONNECTION_SUSPENDED); + break; - case RECONNECTED: - try - { - root.wasReconnected(); - publishEvent(TreeCacheEvent.Type.CONNECTION_RECONNECTED); - } - catch ( Exception e ) - { - ThreadUtils.checkInterrupted(e); - handleException(e); - } - break; + case LOST: + isInitialized.set(false); + publishEvent(TreeCacheEvent.Type.CONNECTION_LOST); + break; + + case CONNECTED: + try { + root.wasCreated(); + } catch (Exception e) { + ThreadUtils.checkInterrupted(e); + handleException(e); + } + break; + + case RECONNECTED: + try { + root.wasReconnected(); + publishEvent(TreeCacheEvent.Type.CONNECTION_RECONNECTED); + } catch (Exception e) { + ThreadUtils.checkInterrupted(e); + handleException(e); + } + break; } } - private void publishEvent(TreeCacheEvent.Type type) - { + private void publishEvent(TreeCacheEvent.Type type) { publishEvent(new TreeCacheEvent(type, null)); } - private void publishEvent(TreeCacheEvent.Type type, ChildData data, ChildData oldData) - { + private void publishEvent(TreeCacheEvent.Type type, ChildData data, ChildData oldData) { publishEvent(new TreeCacheEvent(type, data, oldData)); } - private void publishEvent(final TreeCacheEvent event) - { - if ( treeState.get() != TreeState.CLOSED ) - { + private void publishEvent(final TreeCacheEvent event) { + if (treeState.get() != TreeState.CLOSED) { LOG.debug("publishEvent: {}", event); - executorService.submit(new Runnable() - { + executorService.submit(new Runnable() { @Override - public void run() - { - try - { + public void run() { + try { callListeners(event); - } - catch ( Exception e ) - { + } catch (Exception e) { ThreadUtils.checkInterrupted(e); handleException(e); } diff --git a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/TreeCacheEvent.java b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/TreeCacheEvent.java index e421e0dd4..3ac73764b 100644 --- a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/TreeCacheEvent.java +++ b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/TreeCacheEvent.java @@ -22,8 +22,7 @@ /** * POJO that abstracts a change to a path */ -public class TreeCacheEvent -{ +public class TreeCacheEvent { private final Type type; private final ChildData data; private final ChildData oldData; @@ -31,8 +30,7 @@ public class TreeCacheEvent /** * Type of change */ - public enum Type - { + public enum Type { /** * A node was added. */ @@ -112,8 +110,7 @@ public enum Type * @param type event type * @param data event data or null */ - public TreeCacheEvent(Type type, ChildData data) - { + public TreeCacheEvent(Type type, ChildData data) { this(type, data, null); } @@ -122,8 +119,7 @@ public TreeCacheEvent(Type type, ChildData data) * @param data event data or null * @param oldData event oldData or null */ - public TreeCacheEvent(Type type, ChildData data, ChildData oldData) - { + public TreeCacheEvent(Type type, ChildData data, ChildData oldData) { this.type = type; this.data = data; this.oldData = oldData; @@ -132,33 +128,26 @@ public TreeCacheEvent(Type type, ChildData data, ChildData oldData) /** * @return change type */ - public Type getType() - { + public Type getType() { return type; } /** * @return the node's data */ - public ChildData getData() - { + public ChildData getData() { return data; } /** * @return the node's old data when the type is {@link org.apache.curator.framework.recipes.cache.TreeCacheEvent.Type#NODE_UPDATED} */ - public ChildData getOldData() - { + public ChildData getOldData() { return oldData; } @Override - public String toString() - { - return TreeCacheEvent.class.getSimpleName() + "{" + - "type=" + type + - ", data=" + data + - '}'; + public String toString() { + return TreeCacheEvent.class.getSimpleName() + "{" + "type=" + type + ", data=" + data + '}'; } } diff --git a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/TreeCacheIterator.java b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/TreeCacheIterator.java index 89ae2e54c..c73476a73 100644 --- a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/TreeCacheIterator.java +++ b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/TreeCacheIterator.java @@ -25,78 +25,62 @@ import java.util.NoSuchElementException; // depth first iterator over tree cache nodes -class TreeCacheIterator implements Iterator -{ +class TreeCacheIterator implements Iterator { private final LinkedList stack = new LinkedList<>(); private Current current; - private static class Current - { + private static class Current { final Iterator iterator; TreeCache.TreeNode node; - Current(Iterator iterator) - { + Current(Iterator iterator) { this.iterator = iterator; node = iterator.next(); } } - TreeCacheIterator(TreeCache.TreeNode root) - { + TreeCacheIterator(TreeCache.TreeNode root) { current = new Current(Iterators.forArray(root)); stack.push(current); } @Override - public boolean hasNext() - { + public boolean hasNext() { return (current != null) && TreeCache.isLive(current.node.childData); } @Override - public ChildData next() - { - if ( current == null ) - { + public ChildData next() { + if (current == null) { throw new NoSuchElementException(); } - ChildData result = current.node.childData; // result of next iteration is current node's data + ChildData result = current.node.childData; // result of next iteration is current node's data // set the next node for the next iteration (or note completion) - do - { + do { setNext(); - } while ( (current != null) && !TreeCache.isLive(current.node.childData) ); + } while ((current != null) && !TreeCache.isLive(current.node.childData)); return result; } - private void setNext() - { - if ( current.node.children != null ) - { + private void setNext() { + if (current.node.children != null) { stack.push(current); current = new Current(current.node.children.values().iterator()); - } - else while ( true ) - { - if ( current.iterator.hasNext() ) - { - current.node = current.iterator.next(); - break; - } - else if ( stack.size() > 0 ) - { - current = stack.pop(); + } else + while (true) { + if (current.iterator.hasNext()) { + current.node = current.iterator.next(); + break; + } else if (stack.size() > 0) { + current = stack.pop(); + } else { + current = null; // done + break; + } } - else - { - current = null; // done - break; - } - } } } diff --git a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/TreeCacheListener.java b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/TreeCacheListener.java index 79b2bf84e..395d2b455 100644 --- a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/TreeCacheListener.java +++ b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/TreeCacheListener.java @@ -24,8 +24,7 @@ /** * Listener for {@link TreeCache} changes */ -public interface TreeCacheListener -{ +public interface TreeCacheListener { /** * Called when a change has occurred * diff --git a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/TreeCacheListenerWrapper.java b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/TreeCacheListenerWrapper.java index 7183c3bb7..7711e6bc2 100644 --- a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/TreeCacheListenerWrapper.java +++ b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/TreeCacheListenerWrapper.java @@ -21,36 +21,29 @@ import org.apache.curator.framework.CuratorFramework; -class TreeCacheListenerWrapper implements CuratorCacheListener -{ +class TreeCacheListenerWrapper implements CuratorCacheListener { private final CuratorFramework client; private final TreeCacheListener listener; - TreeCacheListenerWrapper(CuratorFramework client, TreeCacheListener listener) - { + TreeCacheListenerWrapper(CuratorFramework client, TreeCacheListener listener) { this.client = client; this.listener = listener; } @Override - public void event(Type type, ChildData oldData, ChildData data) - { - switch ( type ) - { - case NODE_CREATED: - { + public void event(Type type, ChildData oldData, ChildData data) { + switch (type) { + case NODE_CREATED: { sendEvent(data, null, TreeCacheEvent.Type.NODE_ADDED); break; } - case NODE_CHANGED: - { + case NODE_CHANGED: { sendEvent(data, oldData, TreeCacheEvent.Type.NODE_UPDATED); break; } - case NODE_DELETED: - { + case NODE_DELETED: { sendEvent(oldData, null, TreeCacheEvent.Type.NODE_REMOVED); break; } @@ -58,21 +51,16 @@ public void event(Type type, ChildData oldData, ChildData data) } @Override - public void initialized() - { + public void initialized() { sendEvent(null, null, TreeCacheEvent.Type.INITIALIZED); } - private void sendEvent(ChildData node, ChildData oldNode, TreeCacheEvent.Type type) - { + private void sendEvent(ChildData node, ChildData oldNode, TreeCacheEvent.Type type) { TreeCacheEvent event = new TreeCacheEvent(type, node, oldNode); - try - { + try { listener.childEvent(client, event); - } - catch ( Exception e ) - { + } catch (Exception e) { throw new RuntimeException(e); } } -} \ No newline at end of file +} diff --git a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/TreeCacheSelector.java b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/TreeCacheSelector.java index f65a2f70f..4a2a951ce 100644 --- a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/TreeCacheSelector.java +++ b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/TreeCacheSelector.java @@ -45,8 +45,7 @@ * false from acceptChild("/root/n1-c"). *

*/ -public interface TreeCacheSelector -{ +public interface TreeCacheSelector { /** * Return true if children of this path should be cached. * i.e. if false is returned, this node is not queried to diff --git a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/leader/CancelLeadershipException.java b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/leader/CancelLeadershipException.java index 246c988ca..0e9d9491b 100644 --- a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/leader/CancelLeadershipException.java +++ b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/leader/CancelLeadershipException.java @@ -27,24 +27,18 @@ * cause {@link LeaderSelector#interruptLeadership()} to get called. IMPORTANT: this is only supported * when thrown from {@link LeaderSelectorListener#stateChanged(CuratorFramework, ConnectionState)}. */ -public class CancelLeadershipException extends RuntimeException -{ - public CancelLeadershipException() - { - } +public class CancelLeadershipException extends RuntimeException { + public CancelLeadershipException() {} - public CancelLeadershipException(String message) - { + public CancelLeadershipException(String message) { super(message); } - public CancelLeadershipException(String message, Throwable cause) - { + public CancelLeadershipException(String message, Throwable cause) { super(message, cause); } - public CancelLeadershipException(Throwable cause) - { + public CancelLeadershipException(Throwable cause) { super(cause); } } diff --git a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/leader/LeaderLatch.java b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/leader/LeaderLatch.java index 26193a04a..2c01857e0 100644 --- a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/leader/LeaderLatch.java +++ b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/leader/LeaderLatch.java @@ -21,6 +21,17 @@ import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; +import java.io.Closeable; +import java.io.EOFException; +import java.io.IOException; +import java.util.Collection; +import java.util.List; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Executor; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicReference; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.WatcherRemoveCuratorFramework; import org.apache.curator.framework.api.BackgroundCallback; @@ -32,6 +43,7 @@ import org.apache.curator.framework.recipes.locks.StandardLockInternalsDriver; import org.apache.curator.framework.state.ConnectionState; import org.apache.curator.framework.state.ConnectionStateListener; +import org.apache.curator.utils.PathUtils; import org.apache.curator.utils.ThreadUtils; import org.apache.curator.utils.ZKPaths; import org.apache.zookeeper.CreateMode; @@ -40,18 +52,6 @@ import org.apache.zookeeper.Watcher; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.io.Closeable; -import java.io.EOFException; -import java.io.IOException; -import java.util.Collection; -import java.util.List; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.Executor; -import java.util.concurrent.Future; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicReference; -import org.apache.curator.utils.PathUtils; /** *

@@ -61,8 +61,7 @@ * group will randomly be chosen *

*/ -public class LeaderLatch implements Closeable -{ +public class LeaderLatch implements Closeable { private final Logger log = LoggerFactory.getLogger(getClass()); private final WatcherRemoveCuratorFramework client; private final String latchPath; @@ -75,28 +74,23 @@ public class LeaderLatch implements Closeable private final CloseMode closeMode; private final AtomicReference> startTask = new AtomicReference>(); - private final ConnectionStateListener listener = new ConnectionStateListener() - { + private final ConnectionStateListener listener = new ConnectionStateListener() { @Override - public void stateChanged(CuratorFramework client, ConnectionState newState) - { + public void stateChanged(CuratorFramework client, ConnectionState newState) { handleStateChange(newState); } }; private static final String LOCK_NAME = "latch-"; - private static final LockInternalsSorter sorter = new LockInternalsSorter() - { + private static final LockInternalsSorter sorter = new LockInternalsSorter() { @Override - public String fixForSorting(String str, String lockName) - { + public String fixForSorting(String str, String lockName) { return StandardLockInternalsDriver.standardFixForSorting(str, lockName); } }; - public enum State - { + public enum State { LATENT, STARTED, CLOSED @@ -105,8 +99,7 @@ public enum State /** * How to handle listeners when the latch is closed */ - public enum CloseMode - { + public enum CloseMode { /** * When the latch is closed, listeners will *not* be notified (default behavior) */ @@ -122,8 +115,7 @@ public enum CloseMode * @param client the client * @param latchPath the path for this leadership group */ - public LeaderLatch(CuratorFramework client, String latchPath) - { + public LeaderLatch(CuratorFramework client, String latchPath) { this(client, latchPath, "", CloseMode.SILENT); } @@ -132,8 +124,7 @@ public LeaderLatch(CuratorFramework client, String latchPath) * @param latchPath the path for this leadership group * @param id participant ID */ - public LeaderLatch(CuratorFramework client, String latchPath, String id) - { + public LeaderLatch(CuratorFramework client, String latchPath, String id) { this(client, latchPath, id, CloseMode.SILENT); } @@ -143,9 +134,9 @@ public LeaderLatch(CuratorFramework client, String latchPath, String id) * @param id participant ID * @param closeMode behaviour of listener on explicit close. */ - public LeaderLatch(CuratorFramework client, String latchPath, String id, CloseMode closeMode) - { - this.client = Preconditions.checkNotNull(client, "client cannot be null").newWatcherRemoveCuratorFramework(); + public LeaderLatch(CuratorFramework client, String latchPath, String id, CloseMode closeMode) { + this.client = + Preconditions.checkNotNull(client, "client cannot be null").newWatcherRemoveCuratorFramework(); this.latchPath = PathUtils.validatePath(latchPath); this.id = Preconditions.checkNotNull(id, "id cannot be null"); this.closeMode = Preconditions.checkNotNull(closeMode, "closeMode cannot be null"); @@ -156,21 +147,15 @@ public LeaderLatch(CuratorFramework client, String latchPath, String id, CloseMo * * @throws Exception errors */ - public void start() throws Exception - { + public void start() throws Exception { Preconditions.checkState(state.compareAndSet(State.LATENT, State.STARTED), "Cannot be started more than once"); - startTask.set(AfterConnectionEstablished.execute(client, new Runnable() - { + startTask.set(AfterConnectionEstablished.execute(client, new Runnable() { @Override - public void run() - { - try - { + public void run() { + try { internalStart(); - } - finally - { + } finally { startTask.set(null); } } @@ -185,14 +170,12 @@ public void run() * @throws IOException errors */ @Override - public void close() throws IOException - { + public void close() throws IOException { close(closeMode); } @VisibleForTesting - void closeOnDemand() throws IOException - { + void closeOnDemand() throws IOException { internalClose(closeMode, false); } @@ -204,21 +187,15 @@ void closeOnDemand() throws IOException * @param closeMode allows the default close mode to be overridden at the time the latch is closed. * @throws IOException errors */ - public void close(CloseMode closeMode) throws IOException - { + public void close(CloseMode closeMode) throws IOException { internalClose(closeMode, true); } - private synchronized void internalClose(CloseMode closeMode, boolean failOnClosed) throws IOException - { - if (!state.compareAndSet(State.STARTED, State.CLOSED)) - { - if (failOnClosed) - { + private synchronized void internalClose(CloseMode closeMode, boolean failOnClosed) throws IOException { + if (!state.compareAndSet(State.STARTED, State.CLOSED)) { + if (failOnClosed) { throw new IllegalStateException("Already closed or has not been started"); - } - else - { + } else { return; } } @@ -227,45 +204,35 @@ private synchronized void internalClose(CloseMode closeMode, boolean failOnClose cancelStartTask(); - try - { + try { setNode(null); client.removeWatchers(); - } - catch ( Exception e ) - { + } catch (Exception e) { ThreadUtils.checkInterrupted(e); throw new IOException(e); - } - finally - { + } finally { client.getConnectionStateListenable().removeListener(listener); - switch ( closeMode ) - { - case NOTIFY_LEADER: - { - setLeadership(false); - listeners.clear(); - break; - } + switch (closeMode) { + case NOTIFY_LEADER: { + setLeadership(false); + listeners.clear(); + break; + } - default: - { - listeners.clear(); - setLeadership(false); - break; - } + default: { + listeners.clear(); + setLeadership(false); + break; + } } } } @VisibleForTesting - protected boolean cancelStartTask() - { + protected boolean cancelStartTask() { Future localStartTask = startTask.getAndSet(null); - if ( localStartTask != null ) - { + if (localStartTask != null) { localStartTask.cancel(true); return true; } @@ -284,8 +251,7 @@ protected boolean cancelStartTask() * * @param listener the listener to attach */ - public void addListener(LeaderLatchListener listener) - { + public void addListener(LeaderLatchListener listener) { listeners.addListener(listener); } @@ -302,8 +268,7 @@ public void addListener(LeaderLatchListener listener) * @param listener the listener to attach * @param executor An executor to run the methods for the listener on. */ - public void addListener(LeaderLatchListener listener, Executor executor) - { + public void addListener(LeaderLatchListener listener, Executor executor) { listeners.addListener(listener, executor); } @@ -312,8 +277,7 @@ public void addListener(LeaderLatchListener listener, Executor executor) * * @param listener the listener to remove */ - public void removeListener(LeaderLatchListener listener) - { + public void removeListener(LeaderLatchListener listener) { listeners.removeListener(listener); } @@ -344,17 +308,13 @@ public void removeListener(LeaderLatchListener listener) * @throws EOFException if the instance is {@linkplain #close() closed} * while waiting */ - public void await() throws InterruptedException, EOFException - { - synchronized(this) - { - while ( (state.get() == State.STARTED) && !hasLeadership.get() ) - { + public void await() throws InterruptedException, EOFException { + synchronized (this) { + while ((state.get() == State.STARTED) && !hasLeadership.get()) { wait(); } } - if ( state.get() != State.STARTED ) - { + if (state.get() != State.STARTED) { throw new EOFException(); } } @@ -397,26 +357,20 @@ public void await() throws InterruptedException, EOFException * @throws InterruptedException if the current thread is interrupted * while waiting */ - public boolean await(long timeout, TimeUnit unit) throws InterruptedException - { + public boolean await(long timeout, TimeUnit unit) throws InterruptedException { long waitNanos = TimeUnit.NANOSECONDS.convert(timeout, unit); - synchronized(this) - { - while ( true ) - { - if ( state.get() != State.STARTED ) - { + synchronized (this) { + while (true) { + if (state.get() != State.STARTED) { return false; } - if ( hasLeadership() ) - { + if (hasLeadership()) { return true; } - if ( waitNanos <= 0 ) - { + if (waitNanos <= 0) { return false; } @@ -433,8 +387,7 @@ public boolean await(long timeout, TimeUnit unit) throws InterruptedException * * @return participant Id */ - public String getId() - { + public String getId() { return id; } @@ -446,8 +399,7 @@ public String getId() * * @return the state of the current instance */ - public State getState() - { + public State getState() { return state.get(); } @@ -465,8 +417,7 @@ public State getState() * @return participants * @throws Exception ZK errors, interruptions, etc. */ - public Collection getParticipants() throws Exception - { + public Collection getParticipants() throws Exception { Collection participantNodes = LockInternals.getParticipantNodes(client, latchPath, LOCK_NAME, sorter); return LeaderSelector.getParticipants(client, participantNodes); } @@ -486,8 +437,7 @@ public Collection getParticipants() throws Exception * @return leader * @throws Exception ZK errors, interruptions, etc. */ - public Participant getLeader() throws Exception - { + public Participant getLeader() throws Exception { Collection participantNodes = LockInternals.getParticipantNodes(client, latchPath, LOCK_NAME, sorter); return LeaderSelector.getLeader(client, participantNodes); } @@ -497,8 +447,7 @@ public Participant getLeader() throws Exception * * @return true/false */ - public boolean hasLeadership() - { + public boolean hasLeadership() { return (state.get() == State.STARTED) && hasLeadership.get(); } @@ -516,8 +465,7 @@ public boolean hasLeadership() * * @return lock node path or null */ - public String getOurPath() - { + public String getOurPath() { return ourPath.get(); } @@ -532,8 +480,7 @@ public String getOurPath() * * @return last lock node path that was leader ever or null */ - public String getLastPathIsLeader() - { + public String getLastPathIsLeader() { return lastPathIsLeader.get(); } @@ -544,58 +491,47 @@ public String getLastPathIsLeader() volatile CountDownLatch debugResetWaitBeforeNodeDeleteLatch = null; @VisibleForTesting - void reset() throws Exception - { + void reset() throws Exception { setLeadership(false); - if ( debugResetWaitBeforeNodeDeleteLatch != null ) - { + if (debugResetWaitBeforeNodeDeleteLatch != null) { debugResetWaitBeforeNodeDeleteLatch.await(); } setNode(null); - BackgroundCallback callback = new BackgroundCallback() - { + BackgroundCallback callback = new BackgroundCallback() { @Override - public void processResult(CuratorFramework client, CuratorEvent event) throws Exception - { - if ( debugResetWaitLatch != null ) - { + public void processResult(CuratorFramework client, CuratorEvent event) throws Exception { + if (debugResetWaitLatch != null) { debugResetWaitLatch.await(); debugResetWaitLatch = null; } - if ( event.getResultCode() == KeeperException.Code.OK.intValue() ) - { + if (event.getResultCode() == KeeperException.Code.OK.intValue()) { setNode(event.getName()); - if ( state.get() == State.CLOSED ) - { + if (state.get() == State.CLOSED) { setNode(null); - } - else - { + } else { getChildren(); } - } - else - { + } else { log.error("getChildren() failed. rc = " + event.getResultCode()); } } }; - client.create().creatingParentContainersIfNeeded().withProtection().withMode(CreateMode.EPHEMERAL_SEQUENTIAL).inBackground(callback).forPath(ZKPaths.makePath(latchPath, LOCK_NAME), LeaderSelector.getIdBytes(id)); + client.create() + .creatingParentContainersIfNeeded() + .withProtection() + .withMode(CreateMode.EPHEMERAL_SEQUENTIAL) + .inBackground(callback) + .forPath(ZKPaths.makePath(latchPath, LOCK_NAME), LeaderSelector.getIdBytes(id)); } - private synchronized void internalStart() - { - if ( state.get() == State.STARTED ) - { + private synchronized void internalStart() { + if (state.get() == State.STARTED) { client.getConnectionStateListenable().addListener(listener); - try - { + try { reset(); - } - catch ( Exception e ) - { + } catch (Exception e) { ThreadUtils.checkInterrupted(e); log.error("An error occurred checking resetting leadership.", e); } @@ -605,10 +541,8 @@ private synchronized void internalStart() @VisibleForTesting volatile CountDownLatch debugCheckLeaderShipLatch = null; - private void checkLeadership(List children) throws Exception - { - if ( debugCheckLeaderShipLatch != null ) - { + private void checkLeadership(List children) throws Exception { + if (debugCheckLeaderShipLatch != null) { debugCheckLeaderShipLatch.await(); } @@ -618,33 +552,22 @@ private void checkLeadership(List children) throws Exception log.debug("checkLeadership with id: {}, ourPath: {}, children: {}", id, localOurPath, sortedChildren); - if ( ourIndex < 0 ) - { + if (ourIndex < 0) { log.error("Can't find our node. Resetting. Index: " + ourIndex); reset(); - } - else if ( ourIndex == 0 ) - { + } else if (ourIndex == 0) { lastPathIsLeader.set(localOurPath); setLeadership(true); - } - else - { + } else { setLeadership(false); String watchPath = sortedChildren.get(ourIndex - 1); - Watcher watcher = new Watcher() - { + Watcher watcher = new Watcher() { @Override - public void process(WatchedEvent event) - { - if ( state.get() == State.STARTED && event.getType() == Event.EventType.NodeDeleted ) - { - try - { + public void process(WatchedEvent event) { + if (state.get() == State.STARTED && event.getType() == Event.EventType.NodeDeleted) { + try { getChildren(); - } - catch ( Exception ex ) - { + } catch (Exception ex) { ThreadUtils.checkInterrupted(ex); log.error("An error occurred checking the leadership.", ex); } @@ -652,32 +575,28 @@ public void process(WatchedEvent event) } }; - BackgroundCallback callback = new BackgroundCallback() - { + BackgroundCallback callback = new BackgroundCallback() { @Override - public void processResult(CuratorFramework client, CuratorEvent event) throws Exception - { - if ( event.getResultCode() == KeeperException.Code.NONODE.intValue() ) - { + public void processResult(CuratorFramework client, CuratorEvent event) throws Exception { + if (event.getResultCode() == KeeperException.Code.NONODE.intValue()) { // previous node is gone - retry getChildren getChildren(); } } }; // use getData() instead of exists() to avoid leaving unneeded watchers which is a type of resource leak - client.getData().usingWatcher(watcher).inBackground(callback).forPath(ZKPaths.makePath(latchPath, watchPath)); + client.getData() + .usingWatcher(watcher) + .inBackground(callback) + .forPath(ZKPaths.makePath(latchPath, watchPath)); } } - private void getChildren() throws Exception - { - BackgroundCallback callback = new BackgroundCallback() - { + private void getChildren() throws Exception { + BackgroundCallback callback = new BackgroundCallback() { @Override - public void processResult(CuratorFramework client, CuratorEvent event) throws Exception - { - if ( event.getResultCode() == KeeperException.Code.OK.intValue() ) - { + public void processResult(CuratorFramework client, CuratorEvent event) throws Exception { + if (event.getResultCode() == KeeperException.Code.OK.intValue()) { checkLeadership(event.getChildren()); } } @@ -686,27 +605,20 @@ public void processResult(CuratorFramework client, CuratorEvent event) throws Ex } @VisibleForTesting - protected void handleStateChange(ConnectionState newState) - { - switch ( newState ) - { - default: - { + protected void handleStateChange(ConnectionState newState) { + switch (newState) { + default: { // NOP break; } - case RECONNECTED: - { - try - { - if ( client.getConnectionStateErrorPolicy().isErrorState(ConnectionState.SUSPENDED) || !hasLeadership.get() ) - { + case RECONNECTED: { + try { + if (client.getConnectionStateErrorPolicy().isErrorState(ConnectionState.SUSPENDED) + || !hasLeadership.get()) { getChildren(); } - } - catch ( Exception e ) - { + } catch (Exception e) { ThreadUtils.checkInterrupted(e); log.error("Could not reset leader latch", e); setLeadership(false); @@ -714,44 +626,35 @@ protected void handleStateChange(ConnectionState newState) break; } - case SUSPENDED: - { - if ( client.getConnectionStateErrorPolicy().isErrorState(ConnectionState.SUSPENDED) ) - { + case SUSPENDED: { + if (client.getConnectionStateErrorPolicy().isErrorState(ConnectionState.SUSPENDED)) { setLeadership(false); } break; } - case LOST: - { + case LOST: { setLeadership(false); break; } } } - private synchronized void setLeadership(boolean newValue) - { + private synchronized void setLeadership(boolean newValue) { boolean oldValue = hasLeadership.getAndSet(newValue); - if ( oldValue && !newValue ) - { // Lost leadership, was true, now false + if (oldValue && !newValue) { // Lost leadership, was true, now false listeners.forEach(LeaderLatchListener::notLeader); - } - else if ( !oldValue && newValue ) - { // Gained leadership, was false, now true + } else if (!oldValue && newValue) { // Gained leadership, was false, now true listeners.forEach(LeaderLatchListener::isLeader); } notifyAll(); } - private void setNode(String newValue) throws Exception - { + private void setNode(String newValue) throws Exception { String oldPath = ourPath.getAndSet(newValue); log.debug("setNode with id: {}, oldPath: {}, newValue: {}", id, oldPath, newValue); - if ( oldPath != null ) - { + if (oldPath != null) { client.delete().guaranteed().inBackground().forPath(oldPath); } } diff --git a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/leader/LeaderLatchListener.java b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/leader/LeaderLatchListener.java index c994fa729..de6e6f644 100644 --- a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/leader/LeaderLatchListener.java +++ b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/leader/LeaderLatchListener.java @@ -27,21 +27,20 @@ * before these methods get called. The contract is that if that happens, you should see another call to the other * method pretty quickly. */ -public interface LeaderLatchListener -{ - /** - * This is called when the LeaderLatch's state goes from hasLeadership = false to hasLeadership = true. - * - * Note that it is possible that by the time this method call happens, hasLeadership has fallen back to false. If - * this occurs, you can expect {@link #notLeader()} to also be called. - */ - public void isLeader(); +public interface LeaderLatchListener { + /** + * This is called when the LeaderLatch's state goes from hasLeadership = false to hasLeadership = true. + * + * Note that it is possible that by the time this method call happens, hasLeadership has fallen back to false. If + * this occurs, you can expect {@link #notLeader()} to also be called. + */ + public void isLeader(); - /** - * This is called when the LeaderLatch's state goes from hasLeadership = true to hasLeadership = false. - * - * Note that it is possible that by the time this method call happens, hasLeadership has become true. If - * this occurs, you can expect {@link #isLeader()} to also be called. - */ - public void notLeader(); + /** + * This is called when the LeaderLatch's state goes from hasLeadership = true to hasLeadership = false. + * + * Note that it is possible that by the time this method call happens, hasLeadership has become true. If + * this occurs, you can expect {@link #isLeader()} to also be called. + */ + public void notLeader(); } diff --git a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/leader/LeaderSelector.java b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/leader/LeaderSelector.java index afc3a8c7e..5f3d660c1 100644 --- a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/leader/LeaderSelector.java +++ b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/leader/LeaderSelector.java @@ -23,14 +23,6 @@ import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; -import org.apache.curator.framework.CuratorFramework; -import org.apache.curator.framework.recipes.locks.InterProcessMutex; -import org.apache.curator.framework.state.ConnectionState; -import org.apache.curator.utils.CloseableExecutorService; -import org.apache.curator.utils.ThreadUtils; -import org.apache.zookeeper.KeeperException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import java.io.Closeable; import java.io.UnsupportedEncodingException; import java.util.Collection; @@ -48,7 +40,15 @@ import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; +import org.apache.curator.framework.CuratorFramework; +import org.apache.curator.framework.recipes.locks.InterProcessMutex; +import org.apache.curator.framework.state.ConnectionState; +import org.apache.curator.utils.CloseableExecutorService; import org.apache.curator.utils.PathUtils; +import org.apache.curator.utils.ThreadUtils; +import org.apache.zookeeper.KeeperException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** *

@@ -63,8 +63,7 @@ * (from ZK's point of view). *

*/ -public class LeaderSelector implements Closeable -{ +public class LeaderSelector implements Closeable { private final Logger log = LoggerFactory.getLogger(getClass()); private final CuratorFramework client; private final LeaderSelectorListener listener; @@ -82,10 +81,10 @@ public class LeaderSelector implements Closeable @VisibleForTesting volatile CountDownLatch debugLeadershipLatch = null; + volatile CountDownLatch debugLeadershipWaitLatch = null; - private enum State - { + private enum State { LATENT, STARTED, CLOSED @@ -98,9 +97,12 @@ private enum State * @param leaderPath the path for this leadership group * @param listener listener */ - public LeaderSelector(CuratorFramework client, String leaderPath, LeaderSelectorListener listener) - { - this(client, leaderPath, new CloseableExecutorService(Executors.newSingleThreadExecutor(defaultThreadFactory), true), listener); + public LeaderSelector(CuratorFramework client, String leaderPath, LeaderSelectorListener listener) { + this( + client, + leaderPath, + new CloseableExecutorService(Executors.newSingleThreadExecutor(defaultThreadFactory), true), + listener); } /** @@ -113,8 +115,12 @@ public LeaderSelector(CuratorFramework client, String leaderPath, LeaderSelector */ @SuppressWarnings("UnusedParameters") @Deprecated - public LeaderSelector(CuratorFramework client, String leaderPath, ThreadFactory threadFactory, Executor executor, LeaderSelectorListener listener) - { + public LeaderSelector( + CuratorFramework client, + String leaderPath, + ThreadFactory threadFactory, + Executor executor, + LeaderSelectorListener listener) { this(client, leaderPath, new CloseableExecutorService(wrapExecutor(executor), true), listener); } @@ -124,8 +130,11 @@ public LeaderSelector(CuratorFramework client, String leaderPath, ThreadFactory * @param executorService thread pool to use * @param listener listener */ - public LeaderSelector(CuratorFramework client, String leaderPath, ExecutorService executorService, LeaderSelectorListener listener) - { + public LeaderSelector( + CuratorFramework client, + String leaderPath, + ExecutorService executorService, + LeaderSelectorListener listener) { this(client, leaderPath, new CloseableExecutorService(executorService), listener); } @@ -135,8 +144,11 @@ public LeaderSelector(CuratorFramework client, String leaderPath, ExecutorServic * @param executorService thread pool to use * @param listener listener */ - public LeaderSelector(CuratorFramework client, String leaderPath, CloseableExecutorService executorService, LeaderSelectorListener listener) - { + public LeaderSelector( + CuratorFramework client, + String leaderPath, + CloseableExecutorService executorService, + LeaderSelectorListener listener) { Preconditions.checkNotNull(client, "client cannot be null"); PathUtils.validatePath(leaderPath); Preconditions.checkNotNull(listener, "listener cannot be null"); @@ -146,24 +158,18 @@ public LeaderSelector(CuratorFramework client, String leaderPath, CloseableExecu hasLeadership = false; this.executorService = executorService; - mutex = new InterProcessMutex(client, leaderPath) - { + mutex = new InterProcessMutex(client, leaderPath) { @Override - protected byte[] getLockNodeBytes() - { + protected byte[] getLockNodeBytes() { return (id.length() > 0) ? getIdBytes(id) : null; } }; } - static byte[] getIdBytes(String id) - { - try - { + static byte[] getIdBytes(String id) { + try { return id.getBytes("UTF-8"); - } - catch ( UnsupportedEncodingException e ) - { + } catch (UnsupportedEncodingException e) { throw new Error(e); // this should never happen } } @@ -173,8 +179,7 @@ static byte[] getIdBytes(String id) * instance is not requeued. Calling this method puts the leader selector into a mode where it * will always requeue itself. */ - public void autoRequeue() - { + public void autoRequeue() { autoRequeue.set(true); } @@ -185,8 +190,7 @@ public void autoRequeue() * * @param id ID */ - public void setId(String id) - { + public void setId(String id) { Preconditions.checkNotNull(id, "id cannot be null"); this.id = id; @@ -197,8 +201,7 @@ public void setId(String id) * * @return id */ - public String getId() - { + public String getId() { return id; } @@ -208,8 +211,7 @@ public String getId() * IMPORTANT: previous versions allowed this method to be called multiple times. This * is no longer supported. Use {@link #requeue()} for this purpose. */ - public void start() - { + public void start() { Preconditions.checkState(state.compareAndSet(State.LATENT, State.STARTED), "Cannot be started more than once"); Preconditions.checkState(!executorService.isShutdown(), "Already started"); @@ -230,21 +232,16 @@ public void start() * * @return true if re-queue is successful */ - public boolean requeue() - { + public boolean requeue() { Preconditions.checkState(state.get() == State.STARTED, "close() has already been called"); return internalRequeue(); } - private synchronized boolean internalRequeue() - { - if ( ourTask == null && (state.get() == State.STARTED) ) - { - ourTask = executorService.submit(new Callable() - { + private synchronized boolean internalRequeue() { + if (ourTask == null && (state.get() == State.STARTED)) { + ourTask = executorService.submit(new Callable() { @Override - public Void call() throws Exception - { + public Void call() throws Exception { doWorkLoop(); return null; } @@ -258,9 +255,9 @@ public Void call() throws Exception /** * Shutdown this selector and remove yourself from the leadership group */ - public synchronized void close() - { - Preconditions.checkState(state.compareAndSet(State.STARTED, State.CLOSED), "Already closed or has not been started"); + public synchronized void close() { + Preconditions.checkState( + state.compareAndSet(State.STARTED, State.CLOSED), "Already closed or has not been started"); client.getConnectionStateListenable().removeListener(listener); executorService.close(); @@ -281,27 +278,24 @@ public synchronized void close() * @return participants * @throws Exception ZK errors, interruptions, etc. */ - public Collection getParticipants() throws Exception - { + public Collection getParticipants() throws Exception { Collection participantNodes = mutex.getParticipantNodes(); return getParticipants(client, participantNodes); } - static Collection getParticipants(CuratorFramework client, Collection participantNodes) throws Exception - { + static Collection getParticipants(CuratorFramework client, Collection participantNodes) + throws Exception { ImmutableList.Builder builder = ImmutableList.builder(); boolean isLeader = true; - for ( String path : participantNodes ) - { + for (String path : participantNodes) { Participant participant = participantForPath(client, path, isLeader); - if( participant != null ) - { + if (participant != null) { builder.add(participant); - isLeader = false; // by definition the first node is the leader + isLeader = false; // by definition the first node is the leader } } @@ -323,32 +317,26 @@ static Collection getParticipants(CuratorFramework client, Collecti * @return leader * @throws Exception ZK errors, interruptions, etc. */ - public Participant getLeader() throws Exception - { + public Participant getLeader() throws Exception { Collection participantNodes = mutex.getParticipantNodes(); return getLeader(client, participantNodes); } - static Participant getLeader(CuratorFramework client, Collection participantNodes) throws Exception - { + static Participant getLeader(CuratorFramework client, Collection participantNodes) throws Exception { Participant result = null; - if ( participantNodes.size() > 0 ) - { + if (participantNodes.size() > 0) { Iterator iter = participantNodes.iterator(); - while ( iter.hasNext() ) - { + while (iter.hasNext()) { result = participantForPath(client, iter.next(), true); - if ( result != null ) - { + if (result != null) { break; } } } - if( result == null ) - { + if (result == null) { result = new Participant(); } @@ -360,8 +348,7 @@ static Participant getLeader(CuratorFramework client, Collection partici * * @return true/false */ - public boolean hasLeadership() - { + public boolean hasLeadership() { return hasLeadership; } @@ -407,23 +394,19 @@ private synchronized void cancelElection() { /** * Attempt to cancel and interrupt the current leadership if this instance has leadership */ - public synchronized void interruptLeadership() - { + public synchronized void interruptLeadership() { if (hasLeadership) { cancelElection(); } } - private static Participant participantForPath(CuratorFramework client, String path, boolean markAsLeader) throws Exception - { - try - { + private static Participant participantForPath(CuratorFramework client, String path, boolean markAsLeader) + throws Exception { + try { byte[] bytes = client.getData().forPath(path); String thisId = new String(bytes, "UTF-8"); return new Participant(thisId, markAsLeader); - } - catch ( KeeperException.NoNodeException e ) - { + } catch (KeeperException.NoNodeException e) { return null; } } @@ -436,66 +419,46 @@ private static Participant participantForPath(CuratorFramework client, String pa * {@link LeaderSelectorListener#takeLeadership(CuratorFramework)}. */ @VisibleForTesting - void doWork() throws Exception - { + void doWork() throws Exception { taskStarted(); hasLeadership = false; - try - { + try { mutex.acquire(); hasLeadership = true; - try - { - if ( debugLeadershipLatch != null ) - { + try { + if (debugLeadershipLatch != null) { debugLeadershipLatch.countDown(); } - if ( debugLeadershipWaitLatch != null ) - { + if (debugLeadershipWaitLatch != null) { debugLeadershipWaitLatch.await(); } listener.takeLeadership(client); - } - catch ( InterruptedException e ) - { + } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw e; - } - catch ( Throwable e ) - { + } catch (Throwable e) { ThreadUtils.checkInterrupted(e); } - } - catch ( InterruptedException e ) - { + } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw e; - } - finally - { - if ( taskDone() ) - { - boolean wasInterrupted = Thread.interrupted(); // clear any interrupted status so that mutex.release() works immediately - try - { + } finally { + if (taskDone()) { + boolean wasInterrupted = + Thread.interrupted(); // clear any interrupted status so that mutex.release() works immediately + try { mutex.release(); - } - catch ( Exception e ) - { - if ( failedMutexReleaseCount != null ) - { + } catch (Exception e) { + if (failedMutexReleaseCount != null) { failedMutexReleaseCount.incrementAndGet(); } ThreadUtils.checkInterrupted(e); log.error("The leader threw an exception", e); // ignore errors - this is just a safety - } - finally - { - if ( wasInterrupted ) - { + } finally { + if (wasInterrupted) { Thread.currentThread().interrupt(); } } @@ -503,78 +466,61 @@ void doWork() throws Exception } } - private void doWorkLoop() throws Exception - { + private void doWorkLoop() throws Exception { KeeperException exception = null; - try - { + try { doWork(); - } - catch ( KeeperException.ConnectionLossException e ) - { + } catch (KeeperException.ConnectionLossException e) { exception = e; - } - catch ( KeeperException.SessionExpiredException e ) - { + } catch (KeeperException.SessionExpiredException e) { exception = e; - } - catch ( InterruptedException ignore ) - { + } catch (InterruptedException ignore) { Thread.currentThread().interrupt(); } - if ( (exception != null) && !autoRequeue.get() ) // autoRequeue should ignore connection loss or session expired and just keep trying + if ((exception != null) + && !autoRequeue + .get()) // autoRequeue should ignore connection loss or session expired and just keep trying { throw exception; } } // temporary wrapper for deprecated constructor - private static ExecutorService wrapExecutor(final Executor executor) - { - return new AbstractExecutorService() - { + private static ExecutorService wrapExecutor(final Executor executor) { + return new AbstractExecutorService() { private volatile boolean isShutdown = false; private volatile boolean isTerminated = false; @Override - public void shutdown() - { + public void shutdown() { isShutdown = true; } @Override - public List shutdownNow() - { + public List shutdownNow() { return Lists.newArrayList(); } @Override - public boolean isShutdown() - { + public boolean isShutdown() { return isShutdown; } @Override - public boolean isTerminated() - { + public boolean isTerminated() { return isTerminated; } @Override - public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException - { + public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException { throw new UnsupportedOperationException(); } @Override - public void execute(Runnable command) - { - try - { + public void execute(Runnable command) { + try { executor.execute(command); - } - finally - { + } finally { isShutdown = true; isTerminated = true; } @@ -582,32 +528,25 @@ public void execute(Runnable command) }; } - private static class WrappedListener implements LeaderSelectorListener - { + private static class WrappedListener implements LeaderSelectorListener { private final LeaderSelector leaderSelector; private final LeaderSelectorListener listener; - public WrappedListener(LeaderSelector leaderSelector, LeaderSelectorListener listener) - { + public WrappedListener(LeaderSelector leaderSelector, LeaderSelectorListener listener) { this.leaderSelector = leaderSelector; this.listener = listener; } @Override - public void takeLeadership(CuratorFramework client) throws Exception - { + public void takeLeadership(CuratorFramework client) throws Exception { listener.takeLeadership(client); } @Override - public void stateChanged(CuratorFramework client, ConnectionState newState) - { - try - { + public void stateChanged(CuratorFramework client, ConnectionState newState) { + try { listener.stateChanged(client, newState); - } - catch ( CancelLeadershipException dummy ) - { + } catch (CancelLeadershipException dummy) { // If we cancel only leadership but not whole election, then we could hand over // dated leadership to client with no further cancellation. Dated leadership is // possible due to separated steps in leadership acquire: server data(e.g. election sequence) diff --git a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/leader/LeaderSelectorListener.java b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/leader/LeaderSelectorListener.java index cb3ecdf06..8de881d64 100644 --- a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/leader/LeaderSelectorListener.java +++ b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/leader/LeaderSelectorListener.java @@ -28,8 +28,7 @@ * * @see LeaderSelector */ -public interface LeaderSelectorListener extends ConnectionStateListener -{ +public interface LeaderSelectorListener extends ConnectionStateListener { /** * Called when your instance has been granted leadership. This method * should not return until you wish to release leadership. @@ -46,5 +45,5 @@ public interface LeaderSelectorListener extends ConnectionStateListener * @param client the client * @throws Exception any errors */ - public void takeLeadership(CuratorFramework client) throws Exception; + public void takeLeadership(CuratorFramework client) throws Exception; } diff --git a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/leader/LeaderSelectorListenerAdapter.java b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/leader/LeaderSelectorListenerAdapter.java index bed177c21..c8fae1f2d 100644 --- a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/leader/LeaderSelectorListenerAdapter.java +++ b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/leader/LeaderSelectorListenerAdapter.java @@ -26,13 +26,10 @@ * An implementation of {@link LeaderSelectorListener} that adds the recommended handling * for connection state problems */ -public abstract class LeaderSelectorListenerAdapter implements LeaderSelectorListener -{ +public abstract class LeaderSelectorListenerAdapter implements LeaderSelectorListener { @Override - public void stateChanged(CuratorFramework client, ConnectionState newState) - { - if ( client.getConnectionStateErrorPolicy().isErrorState(newState) ) - { + public void stateChanged(CuratorFramework client, ConnectionState newState) { + if (client.getConnectionStateErrorPolicy().isErrorState(newState)) { throw new CancelLeadershipException(); } } diff --git a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/leader/Participant.java b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/leader/Participant.java index 5ac7ef2ea..dc2c13c3c 100644 --- a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/leader/Participant.java +++ b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/leader/Participant.java @@ -23,23 +23,20 @@ * Describes a participant in a leadership selection */ @SuppressWarnings({"RedundantIfStatement"}) -public class Participant -{ - private final String id; - private final boolean isLeader; +public class Participant { + private final String id; + private final boolean isLeader; /** * @param id the ID * @param leader true if the leader */ - public Participant(String id, boolean leader) - { + public Participant(String id, boolean leader) { this.id = id; isLeader = leader; } - Participant() - { + Participant() { this("", false); } @@ -48,8 +45,7 @@ public Participant(String id, boolean leader) * * @return id */ - public String getId() - { + public String getId() { return id; } @@ -58,40 +54,30 @@ public String getId() * * @return true/false */ - public boolean isLeader() - { + public boolean isLeader() { return isLeader; } @Override - public String toString() - { - return "Participant{" + - "id='" + id + '\'' + - ", isLeader=" + isLeader + - '}'; + public String toString() { + return "Participant{" + "id='" + id + '\'' + ", isLeader=" + isLeader + '}'; } @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; } - Participant that = (Participant)o; + Participant that = (Participant) o; - if ( isLeader != that.isLeader ) - { + if (isLeader != that.isLeader) { return false; } - if ( !id.equals(that.id) ) - { + if (!id.equals(that.id)) { return false; } @@ -99,8 +85,7 @@ public boolean equals(Object o) } @Override - public int hashCode() - { + public int hashCode() { int result = id.hashCode(); result = 31 * result + (isLeader ? 1 : 0); return result; diff --git a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/locks/InterProcessLock.java b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/locks/InterProcessLock.java index c08a31197..08dd65e0f 100644 --- a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/locks/InterProcessLock.java +++ b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/locks/InterProcessLock.java @@ -24,8 +24,7 @@ /** * NOTE: depending on its implementation, {@link #release()} may throw an exception if the current thread does not own the lock */ -public interface InterProcessLock -{ +public interface InterProcessLock { /** * Acquire the mutex - blocking until it's available. Each call to acquire must be balanced by a call * to {@link #release()} diff --git a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/locks/InterProcessMultiLock.java b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/locks/InterProcessMultiLock.java index 6ec28d8a2..336e91335 100644 --- a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/locks/InterProcessMultiLock.java +++ b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/locks/InterProcessMultiLock.java @@ -19,22 +19,20 @@ package org.apache.curator.framework.recipes.locks; +import static com.google.common.collect.Lists.reverse; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; -import org.apache.curator.framework.CuratorFramework; -import org.apache.curator.utils.ThreadUtils; import java.util.List; import java.util.concurrent.TimeUnit; - -import static com.google.common.collect.Lists.reverse; +import org.apache.curator.framework.CuratorFramework; +import org.apache.curator.utils.ThreadUtils; /** * A container that manages multiple locks as a single entity. When {@link #acquire()} is called, * all the locks are acquired. If that fails, any paths that were acquired are released. Similarly, when * {@link #release()} is called, all locks are released (failures are ignored). */ -public class InterProcessMultiLock implements InterProcessLock -{ +public class InterProcessMultiLock implements InterProcessLock { private final List locks; /** @@ -43,8 +41,7 @@ public class InterProcessMultiLock implements InterProcessLock * @param client the client * @param paths list of paths to manage in the order that they are to be locked */ - public InterProcessMultiLock(CuratorFramework client, List paths) - { + public InterProcessMultiLock(CuratorFramework client, List paths) { // paths get checked in each individual InterProcessMutex, so trust them here this(makeLocks(client, paths)); } @@ -54,17 +51,14 @@ public InterProcessMultiLock(CuratorFramework client, List paths) * * @param locks the locks */ - public InterProcessMultiLock(List locks) - { + public InterProcessMultiLock(List locks) { this.locks = ImmutableList.copyOf(locks); } - private static List makeLocks(CuratorFramework client, List paths) - { + private static List makeLocks(CuratorFramework client, List paths) { ImmutableList.Builder builder = ImmutableList.builder(); - for ( String path : paths ) - { - InterProcessLock lock = new InterProcessMutex(client, path); + for (String path : paths) { + InterProcessLock lock = new InterProcessMutex(client, path); builder.add(lock); } return builder.build(); @@ -74,8 +68,7 @@ private static List makeLocks(CuratorFramework client, List acquired = Lists.newArrayList(); - boolean success = true; - for ( InterProcessLock lock : locks ) - { - try - { - if ( unit == null ) - { + public boolean acquire(long time, TimeUnit unit) throws Exception { + Exception exception = null; + List acquired = Lists.newArrayList(); + boolean success = true; + for (InterProcessLock lock : locks) { + try { + if (unit == null) { lock.acquire(); acquired.add(lock); - } - else - { - if ( lock.acquire(time, unit) ) - { + } else { + if (lock.acquire(time, unit)) { acquired.add(lock); - } - else - { + } else { success = false; break; } } - } - catch ( Exception e ) - { + } catch (Exception e) { ThreadUtils.checkInterrupted(e); success = false; exception = e; } } - if ( !success ) - { - for ( InterProcessLock lock : reverse(acquired) ) - { - try - { + if (!success) { + for (InterProcessLock lock : reverse(acquired)) { + try { lock.release(); - } - catch ( Exception e ) - { + } catch (Exception e) { ThreadUtils.checkInterrupted(e); // ignore } } } - if ( exception != null ) - { + if (exception != null) { throw exception; } - + return success; } @@ -146,51 +122,39 @@ public boolean acquire(long time, TimeUnit unit) throws Exception * {@inheritDoc} * *

NOTE: locks are released in the reverse order that they were acquired.

- * + * * @throws Exception ZK errors, interruptions, current thread does not own the lock * */ @Override - public synchronized void release() throws Exception - { - Exception baseException = null; - - for ( InterProcessLock lock : reverse(locks) ) - { - try - { + public synchronized void release() throws Exception { + Exception baseException = null; + + for (InterProcessLock lock : reverse(locks)) { + try { lock.release(); - } - catch ( Exception e ) - { + } catch (Exception e) { ThreadUtils.checkInterrupted(e); - if ( baseException == null ) - { + if (baseException == null) { baseException = e; - } - else - { + } else { baseException = new Exception(baseException); } } } - if ( baseException != null ) - { + if (baseException != null) { throw baseException; } } @Override - public synchronized boolean isAcquiredInThisProcess() - { + public synchronized boolean isAcquiredInThisProcess() { // it's subjective what the correct meaning is here - I choose to return true // only if all of the locks are acquired - for ( InterProcessLock lock : locks ) - { - if ( !lock.isAcquiredInThisProcess() ) - { + for (InterProcessLock lock : locks) { + if (!lock.isAcquiredInThisProcess()) { return false; } } diff --git a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/locks/InterProcessMutex.java b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/locks/InterProcessMutex.java index 66c61c6e0..63b89c169 100644 --- a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/locks/InterProcessMutex.java +++ b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/locks/InterProcessMutex.java @@ -21,13 +21,13 @@ import com.google.common.collect.Maps; import com.google.common.util.concurrent.MoreExecutors; -import org.apache.curator.framework.CuratorFramework; import java.io.IOException; import java.util.Collection; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.Executor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; +import org.apache.curator.framework.CuratorFramework; import org.apache.curator.utils.PathUtils; /** @@ -35,21 +35,18 @@ * use the same lock path will achieve an inter-process critical section. Further, this mutex is * "fair" - each user will get the mutex in the order requested (from ZK's point of view) */ -public class InterProcessMutex implements InterProcessLock, Revocable -{ +public class InterProcessMutex implements InterProcessLock, Revocable { private final LockInternals internals; private final String basePath; private final ConcurrentMap threadData = Maps.newConcurrentMap(); - private static class LockData - { + private static class LockData { final Thread owningThread; final String lockPath; final AtomicInteger lockCount = new AtomicInteger(1); - private LockData(Thread owningThread, String lockPath) - { + private LockData(Thread owningThread, String lockPath) { this.owningThread = owningThread; this.lockPath = lockPath; } @@ -61,8 +58,7 @@ private LockData(Thread owningThread, String lockPath) * @param client client * @param path the path to lock */ - public InterProcessMutex(CuratorFramework client, String path) - { + public InterProcessMutex(CuratorFramework client, String path) { this(client, path, new StandardLockInternalsDriver()); } @@ -71,8 +67,7 @@ public InterProcessMutex(CuratorFramework client, String path) * @param path the path to lock * @param driver lock driver */ - public InterProcessMutex(CuratorFramework client, String path, LockInternalsDriver driver) - { + public InterProcessMutex(CuratorFramework client, String path, LockInternalsDriver driver) { this(client, path, LOCK_NAME, 1, driver); } @@ -84,10 +79,8 @@ public InterProcessMutex(CuratorFramework client, String path, LockInternalsDriv * @throws Exception ZK errors, connection interruptions */ @Override - public void acquire() throws Exception - { - if ( !internalLock(-1, null) ) - { + public void acquire() throws Exception { + if (!internalLock(-1, null)) { throw new IOException("Lost connection while trying to acquire lock: " + basePath); } } @@ -103,8 +96,7 @@ public void acquire() throws Exception * @throws Exception ZK errors, connection interruptions */ @Override - public boolean acquire(long time, TimeUnit unit) throws Exception - { + public boolean acquire(long time, TimeUnit unit) throws Exception { return internalLock(time, unit); } @@ -114,8 +106,7 @@ public boolean acquire(long time, TimeUnit unit) throws Exception * @return true/false */ @Override - public boolean isAcquiredInThisProcess() - { + public boolean isAcquiredInThisProcess() { return (threadData.size() > 0); } @@ -126,35 +117,28 @@ public boolean isAcquiredInThisProcess() * @throws Exception ZK errors, interruptions, current thread does not own the lock */ @Override - public void release() throws Exception - { + public void release() throws Exception { /* - Note on concurrency: a given lockData instance - can be only acted on by a single thread so locking isn't necessary - */ + Note on concurrency: a given lockData instance + can be only acted on by a single thread so locking isn't necessary + */ Thread currentThread = Thread.currentThread(); LockData lockData = threadData.get(currentThread); - if ( lockData == null ) - { + if (lockData == null) { throw new IllegalMonitorStateException("You do not own the lock: " + basePath); } int newLockCount = lockData.lockCount.decrementAndGet(); - if ( newLockCount > 0 ) - { + if (newLockCount > 0) { return; } - if ( newLockCount < 0 ) - { + if (newLockCount < 0) { throw new IllegalMonitorStateException("Lock count has gone negative for lock: " + basePath); } - try - { + try { internals.releaseLock(lockData.lockPath); - } - finally - { + } finally { threadData.remove(currentThread); } } @@ -165,60 +149,52 @@ public void release() throws Exception * @return list of nodes * @throws Exception ZK errors, interruptions, etc. */ - public Collection getParticipantNodes() throws Exception - { - return LockInternals.getParticipantNodes(internals.getClient(), basePath, internals.getLockName(), internals.getDriver()); + public Collection getParticipantNodes() throws Exception { + return LockInternals.getParticipantNodes( + internals.getClient(), basePath, internals.getLockName(), internals.getDriver()); } @Override - public void makeRevocable(RevocationListener listener) - { + public void makeRevocable(RevocationListener listener) { makeRevocable(listener, MoreExecutors.directExecutor()); } @Override - public void makeRevocable(final RevocationListener listener, Executor executor) - { - internals.makeRevocable(new RevocationSpec(executor, new Runnable() - { - @Override - public void run() - { - listener.revocationRequested(InterProcessMutex.this); - } - })); + public void makeRevocable(final RevocationListener listener, Executor executor) { + internals.makeRevocable(new RevocationSpec(executor, new Runnable() { + @Override + public void run() { + listener.revocationRequested(InterProcessMutex.this); + } + })); } - InterProcessMutex(CuratorFramework client, String path, String lockName, int maxLeases, LockInternalsDriver driver) - { + InterProcessMutex( + CuratorFramework client, String path, String lockName, int maxLeases, LockInternalsDriver driver) { basePath = PathUtils.validatePath(path); internals = new LockInternals(client, driver, path, lockName, maxLeases); } /** * Returns true if the mutex is acquired by the calling thread - * + * * @return true/false */ - public boolean isOwnedByCurrentThread() - { + public boolean isOwnedByCurrentThread() { LockData lockData = threadData.get(Thread.currentThread()); return (lockData != null) && (lockData.lockCount.get() > 0); } - protected byte[] getLockNodeBytes() - { + protected byte[] getLockNodeBytes() { return null; } - protected String getLockPath() - { + protected String getLockPath() { LockData lockData = threadData.get(Thread.currentThread()); return lockData != null ? lockData.lockPath : null; } - private boolean internalLock(long time, TimeUnit unit) throws Exception - { + private boolean internalLock(long time, TimeUnit unit) throws Exception { /* Note on concurrency: a given lockData instance can be only acted on by a single thread so locking isn't necessary @@ -227,16 +203,14 @@ private boolean internalLock(long time, TimeUnit unit) throws Exception Thread currentThread = Thread.currentThread(); LockData lockData = threadData.get(currentThread); - if ( lockData != null ) - { + if (lockData != null) { // re-entering lockData.lockCount.incrementAndGet(); return true; } String lockPath = internals.attemptLock(time, unit, getLockNodeBytes()); - if ( lockPath != null ) - { + if (lockPath != null) { LockData newLockData = new LockData(currentThread, lockPath); threadData.put(currentThread, newLockData); return true; diff --git a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/locks/InterProcessReadWriteLock.java b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/locks/InterProcessReadWriteLock.java index b0a8e1786..85b0ab073 100644 --- a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/locks/InterProcessReadWriteLock.java +++ b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/locks/InterProcessReadWriteLock.java @@ -22,11 +22,10 @@ import com.google.common.base.Predicate; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; -import org.apache.curator.framework.CuratorFramework; - import java.util.Arrays; import java.util.Collection; import java.util.List; +import org.apache.curator.framework.CuratorFramework; /** *

@@ -54,41 +53,41 @@ * lock to the write lock is not possible. *

*/ -public class InterProcessReadWriteLock -{ +public class InterProcessReadWriteLock { private final ReadLock readMutex; private final WriteLock writeMutex; // must be the same length. LockInternals depends on it - private static final String READ_LOCK_NAME = "__READ__"; + private static final String READ_LOCK_NAME = "__READ__"; private static final String WRITE_LOCK_NAME = "__WRIT__"; - private static class SortingLockInternalsDriver extends StandardLockInternalsDriver - { + private static class SortingLockInternalsDriver extends StandardLockInternalsDriver { @Override - public final String fixForSorting(String str, String lockName) - { + public final String fixForSorting(String str, String lockName) { str = super.fixForSorting(str, READ_LOCK_NAME); str = super.fixForSorting(str, WRITE_LOCK_NAME); return str; } } - private static class InternalInterProcessMutex extends InterProcessMutex - { + private static class InternalInterProcessMutex extends InterProcessMutex { private final String lockName; private final byte[] lockData; - InternalInterProcessMutex(CuratorFramework client, String path, String lockName, byte[] lockData, int maxLeases, LockInternalsDriver driver) - { + InternalInterProcessMutex( + CuratorFramework client, + String path, + String lockName, + byte[] lockData, + int maxLeases, + LockInternalsDriver driver) { super(client, path, lockName, maxLeases, driver); this.lockName = lockName; this.lockData = (lockData == null) ? null : Arrays.copyOf(lockData, lockData.length); } @Override - final public Collection getParticipantNodes() throws Exception - { + public final Collection getParticipantNodes() throws Exception { return ImmutableList.copyOf(Iterables.filter(super.getParticipantNodes(), new Predicate() { @Override public boolean apply(String node) { @@ -98,35 +97,29 @@ public boolean apply(String node) { } @Override - final protected byte[] getLockNodeBytes() - { + protected final byte[] getLockNodeBytes() { return lockData; } @Override - protected String getLockPath() - { + protected String getLockPath() { return super.getLockPath(); } } - public static class WriteLock extends InternalInterProcessMutex - { - public WriteLock(CuratorFramework client, String basePath, byte[] lockData) - { + public static class WriteLock extends InternalInterProcessMutex { + public WriteLock(CuratorFramework client, String basePath, byte[] lockData) { super(client, basePath, WRITE_LOCK_NAME, lockData, 1, new SortingLockInternalsDriver()); } @Override - public String getLockPath() - { + public String getLockPath() { return super.getLockPath(); } } public static class ReadLock extends InternalInterProcessMutex { - public ReadLock(CuratorFramework client, String basePath, byte[] lockData, WriteLock writeLock) - { + public ReadLock(CuratorFramework client, String basePath, byte[] lockData, WriteLock writeLock) { super(client, basePath, READ_LOCK_NAME, lockData, Integer.MAX_VALUE, new SortingLockInternalsDriver() { @Override protected String getSortingSequence() { @@ -139,11 +132,8 @@ protected String getSortingSequence() { @Override public PredicateResults getsTheLock( - CuratorFramework client, - List children, - String sequenceNodeName, - int maxLeases - ) throws Exception { + CuratorFramework client, List children, String sequenceNodeName, int maxLeases) + throws Exception { if (writeLock.isOwnedByCurrentThread()) { return new PredicateResults(null, true); } @@ -172,34 +162,30 @@ public PredicateResults getsTheLock( } @Override - public String getLockPath() - { + public String getLockPath() { return super.getLockPath(); } } - /** - * @param client the client - * @param basePath path to use for locking - */ - public InterProcessReadWriteLock(CuratorFramework client, String basePath) - { + /** + * @param client the client + * @param basePath path to use for locking + */ + public InterProcessReadWriteLock(CuratorFramework client, String basePath) { this(client, basePath, null); } - /** - * @param client the client - * @param basePath path to use for locking - * @param lockData the data to store in the lock nodes - */ - public InterProcessReadWriteLock(CuratorFramework client, String basePath, byte[] lockData) - { + /** + * @param client the client + * @param basePath path to use for locking + * @param lockData the data to store in the lock nodes + */ + public InterProcessReadWriteLock(CuratorFramework client, String basePath, byte[] lockData) { this.writeMutex = new WriteLock(client, basePath, lockData); this.readMutex = new ReadLock(client, basePath, lockData, writeMutex); } - protected InterProcessReadWriteLock(WriteLock writeLock, ReadLock readLock) - { + protected InterProcessReadWriteLock(WriteLock writeLock, ReadLock readLock) { this.writeMutex = writeLock; this.readMutex = readLock; } @@ -209,8 +195,7 @@ protected InterProcessReadWriteLock(WriteLock writeLock, ReadLock readLock) * * @return read lock */ - public ReadLock readLock() - { + public ReadLock readLock() { return readMutex; } @@ -219,8 +204,7 @@ public ReadLock readLock() * * @return write lock */ - public WriteLock writeLock() - { + public WriteLock writeLock() { return writeMutex; } } diff --git a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/locks/InterProcessSemaphore.java b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/locks/InterProcessSemaphore.java index 546260bda..e74e047de 100644 --- a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/locks/InterProcessSemaphore.java +++ b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/locks/InterProcessSemaphore.java @@ -21,19 +21,19 @@ import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; -import org.apache.curator.utils.CloseableUtils; +import java.io.IOException; +import java.util.Collection; +import java.util.concurrent.TimeUnit; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.recipes.shared.SharedCountListener; import org.apache.curator.framework.recipes.shared.SharedCountReader; import org.apache.curator.framework.state.ConnectionState; +import org.apache.curator.utils.CloseableUtils; import org.apache.curator.utils.ThreadUtils; import org.apache.curator.utils.ZKPaths; import org.apache.zookeeper.KeeperException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.io.IOException; -import java.util.Collection; -import java.util.concurrent.TimeUnit; /** *

@@ -67,20 +67,18 @@ * @deprecated Use {@link InterProcessSemaphoreV2} instead of this class. It uses a better algorithm. */ @Deprecated -public class InterProcessSemaphore -{ - private final Logger log = LoggerFactory.getLogger(getClass()); +public class InterProcessSemaphore { + private final Logger log = LoggerFactory.getLogger(getClass()); private final LockInternals internals; - private static final String LOCK_NAME = "lock-"; + private static final String LOCK_NAME = "lock-"; /** * @param client the client * @param path path for the semaphore * @param maxLeases the max number of leases to allow for this instance */ - public InterProcessSemaphore(CuratorFramework client, String path, int maxLeases) - { + public InterProcessSemaphore(CuratorFramework client, String path, int maxLeases) { this(client, path, maxLeases, null); } @@ -89,34 +87,30 @@ public InterProcessSemaphore(CuratorFramework client, String path, int maxLeases * @param path path for the semaphore * @param count the shared count to use for the max leases */ - public InterProcessSemaphore(CuratorFramework client, String path, SharedCountReader count) - { + public InterProcessSemaphore(CuratorFramework client, String path, SharedCountReader count) { this(client, path, 0, count); } - private InterProcessSemaphore(CuratorFramework client, String path, int maxLeases, SharedCountReader count) - { + private InterProcessSemaphore(CuratorFramework client, String path, int maxLeases, SharedCountReader count) { // path verified in LockInternals - internals = new LockInternals(client, new StandardLockInternalsDriver(), path, LOCK_NAME, (count != null) ? count.getCount() : maxLeases); - if ( count != null ) - { - count.addListener - ( - new SharedCountListener() - { - @Override - public void countHasChanged(SharedCountReader sharedCount, int newCount) throws Exception - { - internals.setMaxLeases(newCount); - } + internals = new LockInternals( + client, + new StandardLockInternalsDriver(), + path, + LOCK_NAME, + (count != null) ? count.getCount() : maxLeases); + if (count != null) { + count.addListener(new SharedCountListener() { + @Override + public void countHasChanged(SharedCountReader sharedCount, int newCount) throws Exception { + internals.setMaxLeases(newCount); + } - @Override - public void stateChanged(CuratorFramework client, ConnectionState newState) - { - // no need to handle this here - clients should set their own connection state listener - } + @Override + public void stateChanged(CuratorFramework client, ConnectionState newState) { + // no need to handle this here - clients should set their own connection state listener } - ); + }); } } @@ -125,10 +119,8 @@ public void stateChanged(CuratorFramework client, ConnectionState newState) * * @param leases leases to close */ - public void returnAll(Collection leases) - { - for ( Lease l : leases ) - { + public void returnAll(Collection leases) { + for (Lease l : leases) { CloseableUtils.closeQuietly(l); } } @@ -138,8 +130,7 @@ public void returnAll(Collection leases) * * @param lease lease to close */ - public void returnLease(Lease lease) - { + public void returnLease(Lease lease) { CloseableUtils.closeQuietly(lease); } @@ -153,9 +144,8 @@ public void returnLease(Lease lease) * @return the new lease * @throws Exception ZK errors, interruptions, etc. */ - public Lease acquire() throws Exception - { - String path = internals.attemptLock(-1, null, null); + public Lease acquire() throws Exception { + String path = internals.attemptLock(-1, null, null); return makeLease(path); } @@ -171,21 +161,16 @@ public Lease acquire() throws Exception * @return the new leases * @throws Exception ZK errors, interruptions, etc. */ - public Collection acquire(int qty) throws Exception - { + public Collection acquire(int qty) throws Exception { Preconditions.checkArgument(qty > 0, "qty cannot be 0"); - ImmutableList.Builder builder = ImmutableList.builder(); - try - { - while ( qty-- > 0 ) - { - String path = internals.attemptLock(-1, null, null); + ImmutableList.Builder builder = ImmutableList.builder(); + try { + while (qty-- > 0) { + String path = internals.attemptLock(-1, null, null); builder.add(makeLease(path)); } - } - catch ( Exception e ) - { + } catch (Exception e) { ThreadUtils.checkInterrupted(e); returnAll(builder.build()); throw e; @@ -206,9 +191,8 @@ public Collection acquire(int qty) throws Exception * @return the new lease or null if time ran out * @throws Exception ZK errors, interruptions, etc. */ - public Lease acquire(long time, TimeUnit unit) throws Exception - { - String path = internals.attemptLock(time, unit, null); + public Lease acquire(long time, TimeUnit unit) throws Exception { + String path = internals.attemptLock(time, unit, null); return (path != null) ? makeLease(path) : null; } @@ -228,32 +212,26 @@ public Lease acquire(long time, TimeUnit unit) throws Exception * @return the new leases or null if time ran out * @throws Exception ZK errors, interruptions, etc. */ - public Collection acquire(int qty, long time, TimeUnit unit) throws Exception - { - long startMs = System.currentTimeMillis(); - long waitMs = TimeUnit.MILLISECONDS.convert(time, unit); + public Collection acquire(int qty, long time, TimeUnit unit) throws Exception { + long startMs = System.currentTimeMillis(); + long waitMs = TimeUnit.MILLISECONDS.convert(time, unit); Preconditions.checkArgument(qty > 0, "qty cannot be 0"); - ImmutableList.Builder builder = ImmutableList.builder(); - try - { - while ( qty-- > 0 ) - { - long elapsedMs = System.currentTimeMillis() - startMs; - long thisWaitMs = waitMs - elapsedMs; + ImmutableList.Builder builder = ImmutableList.builder(); + try { + while (qty-- > 0) { + long elapsedMs = System.currentTimeMillis() - startMs; + long thisWaitMs = waitMs - elapsedMs; - String path = (thisWaitMs > 0) ? internals.attemptLock(thisWaitMs, TimeUnit.MILLISECONDS, null) : null; - if ( path == null ) - { + String path = (thisWaitMs > 0) ? internals.attemptLock(thisWaitMs, TimeUnit.MILLISECONDS, null) : null; + if (path == null) { returnAll(builder.build()); return null; } builder.add(makeLease(path)); } - } - catch ( Exception e ) - { + } catch (Exception e) { ThreadUtils.checkInterrupted(e); returnAll(builder.build()); throw e; @@ -262,31 +240,22 @@ public Collection acquire(int qty, long time, TimeUnit unit) throws Excep return builder.build(); } - private Lease makeLease(final String path) - { - return new Lease() - { + private Lease makeLease(final String path) { + return new Lease() { @Override - public void close() throws IOException - { - try - { + public void close() throws IOException { + try { internals.releaseLock(path); - } - catch ( KeeperException.NoNodeException e ) - { + } catch (KeeperException.NoNodeException e) { log.warn("Lease already released", e); - } - catch ( Exception e ) - { + } catch (Exception e) { ThreadUtils.checkInterrupted(e); throw new IOException(e); } } @Override - public byte[] getData() throws Exception - { + public byte[] getData() throws Exception { return internals.getClient().getData().forPath(path); } diff --git a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/locks/InterProcessSemaphoreMutex.java b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/locks/InterProcessSemaphoreMutex.java index dc965e565..4cacbfea6 100644 --- a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/locks/InterProcessSemaphoreMutex.java +++ b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/locks/InterProcessSemaphoreMutex.java @@ -20,16 +20,15 @@ package org.apache.curator.framework.recipes.locks; import com.google.common.base.Preconditions; +import java.util.concurrent.TimeUnit; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.WatcherRemoveCuratorFramework; -import java.util.concurrent.TimeUnit; /** * A NON re-entrant mutex that works across JVMs. Uses Zookeeper to hold the lock. All processes in all JVMs that * use the same lock path will achieve an inter-process critical section. */ -public class InterProcessSemaphoreMutex implements InterProcessLock -{ +public class InterProcessSemaphoreMutex implements InterProcessLock { private final InterProcessSemaphoreV2 semaphore; private final WatcherRemoveCuratorFramework watcherRemoveClient; private volatile Lease lease; @@ -38,25 +37,21 @@ public class InterProcessSemaphoreMutex implements InterProcessLock * @param client the client * @param path path for the lock */ - public InterProcessSemaphoreMutex(CuratorFramework client, String path) - { + public InterProcessSemaphoreMutex(CuratorFramework client, String path) { watcherRemoveClient = client.newWatcherRemoveCuratorFramework(); this.semaphore = new InterProcessSemaphoreV2(watcherRemoveClient, path, 1); } @Override - public void acquire() throws Exception - { + public void acquire() throws Exception { lease = semaphore.acquire(); } @Override - public boolean acquire(long time, TimeUnit unit) throws Exception - { + public boolean acquire(long time, TimeUnit unit) throws Exception { Lease acquiredLease = semaphore.acquire(time, unit); - if ( acquiredLease == null ) - { - return false; // important - don't overwrite lease field if couldn't be acquired + if (acquiredLease == null) { + return false; // important - don't overwrite lease field if couldn't be acquired } lease = acquiredLease; return true; @@ -70,8 +65,7 @@ public boolean acquire(long time, TimeUnit unit) throws Exception * */ @Override - public void release() throws Exception - { + public void release() throws Exception { Lease lease = this.lease; Preconditions.checkState(lease != null, "Not acquired"); @@ -81,8 +75,7 @@ public void release() throws Exception } @Override - public boolean isAcquiredInThisProcess() - { + public boolean isAcquiredInThisProcess() { return (lease != null); } } diff --git a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/locks/InterProcessSemaphoreV2.java b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/locks/InterProcessSemaphoreV2.java index 6376b37ce..e14ff196e 100644 --- a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/locks/InterProcessSemaphoreV2.java +++ b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/locks/InterProcessSemaphoreV2.java @@ -22,6 +22,13 @@ import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.google.common.collect.Sets; +import java.io.IOException; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; +import java.util.Set; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; import org.apache.curator.RetryLoop; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.WatcherRemoveCuratorFramework; @@ -40,13 +47,6 @@ import org.apache.zookeeper.Watcher; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.io.IOException; -import java.util.Arrays; -import java.util.Collection; -import java.util.List; -import java.util.Set; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; /** *

@@ -76,17 +76,14 @@ * Thanks to Ben Bangert (ben@groovie.org) for the algorithm used. *

*/ -public class InterProcessSemaphoreV2 -{ +public class InterProcessSemaphoreV2 { private final Logger log = LoggerFactory.getLogger(getClass()); private final InterProcessMutex lock; private final WatcherRemoveCuratorFramework client; private final String leasesPath; - private final Watcher watcher = new Watcher() - { + private final Watcher watcher = new Watcher() { @Override - public void process(WatchedEvent event) - { + public void process(WatchedEvent event) { client.postSafeNotify(InterProcessSemaphoreV2.this); } }; @@ -97,18 +94,14 @@ public void process(WatchedEvent event) private static final String LOCK_PARENT = "locks"; private static final String LEASE_PARENT = "leases"; private static final String LEASE_BASE_NAME = "lease-"; - public static final Set LOCK_SCHEMA = Sets.newHashSet( - LOCK_PARENT, - LEASE_PARENT - ); + public static final Set LOCK_SCHEMA = Sets.newHashSet(LOCK_PARENT, LEASE_PARENT); /** * @param client the client * @param path path for the semaphore * @param maxLeases the max number of leases to allow for this instance */ - public InterProcessSemaphoreV2(CuratorFramework client, String path, int maxLeases) - { + public InterProcessSemaphoreV2(CuratorFramework client, String path, int maxLeases) { this(client, path, maxLeases, null); } @@ -117,39 +110,30 @@ public InterProcessSemaphoreV2(CuratorFramework client, String path, int maxLeas * @param path path for the semaphore * @param count the shared count to use for the max leases */ - public InterProcessSemaphoreV2(CuratorFramework client, String path, SharedCountReader count) - { + public InterProcessSemaphoreV2(CuratorFramework client, String path, SharedCountReader count) { this(client, path, 0, count); } - private InterProcessSemaphoreV2(CuratorFramework client, String path, int maxLeases, SharedCountReader count) - { + private InterProcessSemaphoreV2(CuratorFramework client, String path, int maxLeases, SharedCountReader count) { this.client = client.newWatcherRemoveCuratorFramework(); path = PathUtils.validatePath(path); lock = new InterProcessMutex(client, ZKPaths.makePath(path, LOCK_PARENT)); this.maxLeases = (count != null) ? count.getCount() : maxLeases; leasesPath = ZKPaths.makePath(path, LEASE_PARENT); - if ( count != null ) - { - count.addListener - ( - new SharedCountListener() - { - @Override - public void countHasChanged(SharedCountReader sharedCount, int newCount) throws Exception - { - InterProcessSemaphoreV2.this.maxLeases = newCount; - client.postSafeNotify(InterProcessSemaphoreV2.this); - } + if (count != null) { + count.addListener(new SharedCountListener() { + @Override + public void countHasChanged(SharedCountReader sharedCount, int newCount) throws Exception { + InterProcessSemaphoreV2.this.maxLeases = newCount; + client.postSafeNotify(InterProcessSemaphoreV2.this); + } - @Override - public void stateChanged(CuratorFramework client, ConnectionState newState) - { - // no need to handle this here - clients should set their own connection state listener - } - } - ); + @Override + public void stateChanged(CuratorFramework client, ConnectionState newState) { + // no need to handle this here - clients should set their own connection state listener + } + }); } } @@ -159,8 +143,7 @@ public void stateChanged(CuratorFramework client, ConnectionState newState) * * @param nodeData node data */ - public void setNodeData(byte[] nodeData) - { + public void setNodeData(byte[] nodeData) { this.nodeData = (nodeData != null) ? Arrays.copyOf(nodeData, nodeData.length) : null; } @@ -170,8 +153,7 @@ public void setNodeData(byte[] nodeData) * @return list of nodes * @throws Exception ZK errors, interruptions, etc. */ - public Collection getParticipantNodes() throws Exception - { + public Collection getParticipantNodes() throws Exception { return client.getChildren().forPath(leasesPath); } @@ -180,10 +162,8 @@ public Collection getParticipantNodes() throws Exception * * @param leases leases to close */ - public void returnAll(Collection leases) - { - for ( Lease l : leases ) - { + public void returnAll(Collection leases) { + for (Lease l : leases) { CloseableUtils.closeQuietly(l); } } @@ -193,8 +173,7 @@ public void returnAll(Collection leases) * * @param lease lease to close */ - public void returnLease(Lease lease) - { + public void returnLease(Lease lease) { CloseableUtils.closeQuietly(lease); } @@ -207,8 +186,7 @@ public void returnLease(Lease lease) * @return the new lease * @throws Exception ZK errors, interruptions, etc. */ - public Lease acquire() throws Exception - { + public Lease acquire() throws Exception { Collection leases = acquire(1, 0, null); return leases.iterator().next(); } @@ -224,8 +202,7 @@ public Lease acquire() throws Exception * @return the new leases * @throws Exception ZK errors, interruptions, etc. */ - public Collection acquire(int qty) throws Exception - { + public Collection acquire(int qty) throws Exception { return acquire(qty, 0, null); } @@ -241,8 +218,7 @@ public Collection acquire(int qty) throws Exception * @return the new lease or null if time ran out * @throws Exception ZK errors, interruptions, etc. */ - public Lease acquire(long time, TimeUnit unit) throws Exception - { + public Lease acquire(long time, TimeUnit unit) throws Exception { Collection leases = acquire(1, time, unit); return (leases != null) ? leases.iterator().next() : null; } @@ -262,8 +238,7 @@ public Lease acquire(long time, TimeUnit unit) throws Exception * @return the new leases or null if time ran out * @throws Exception ZK errors, interruptions, etc. */ - public Collection acquire(int qty, long time, TimeUnit unit) throws Exception - { + public Collection acquire(int qty, long time, TimeUnit unit) throws Exception { long startMs = System.currentTimeMillis(); boolean hasWait = (unit != null); long waitMs = hasWait ? TimeUnit.MILLISECONDS.convert(time, unit) : 0; @@ -272,35 +247,34 @@ public Collection acquire(int qty, long time, TimeUnit unit) throws Excep ImmutableList.Builder builder = ImmutableList.builder(); boolean success = false; - try - { - while ( qty-- > 0 ) - { + try { + while (qty-- > 0) { int retryCount = 0; long startMillis = System.currentTimeMillis(); boolean isDone = false; - while ( !isDone ) - { - switch ( internalAcquire1Lease(builder, startMs, hasWait, waitMs) ) - { - case CONTINUE: - { + while (!isDone) { + switch (internalAcquire1Lease(builder, startMs, hasWait, waitMs)) { + case CONTINUE: { isDone = true; break; } - case RETURN_NULL: - { + case RETURN_NULL: { return null; } - case RETRY_DUE_TO_MISSING_NODE: - { + case RETRY_DUE_TO_MISSING_NODE: { // gets thrown by internalAcquire1Lease when it can't find the lock node - // this can happen when the session expires, etc. So, if the retry allows, just try it all again - if ( !client.getZookeeperClient().getRetryPolicy().allowRetry(retryCount++, System.currentTimeMillis() - startMillis, RetryLoop.getDefaultRetrySleeper()) ) - { - throw new KeeperException.NoNodeException("Sequential path not found - possible session loss"); + // this can happen when the session expires, etc. So, if the retry allows, just try it all + // again + if (!client.getZookeeperClient() + .getRetryPolicy() + .allowRetry( + retryCount++, + System.currentTimeMillis() - startMillis, + RetryLoop.getDefaultRetrySleeper())) { + throw new KeeperException.NoNodeException( + "Sequential path not found - possible session loss"); } // try again break; @@ -309,11 +283,8 @@ public Collection acquire(int qty, long time, TimeUnit unit) throws Excep } } success = true; - } - finally - { - if ( !success ) - { + } finally { + if (!success) { returnAll(builder.build()); } } @@ -321,8 +292,7 @@ public Collection acquire(int qty, long time, TimeUnit unit) throws Excep return builder.build(); } - private enum InternalAcquireResult - { + private enum InternalAcquireResult { CONTINUE, RETURN_NULL, RETRY_DUE_TO_MISSING_NODE @@ -332,87 +302,71 @@ private enum InternalAcquireResult static volatile CountDownLatch debugFailedGetChildrenLatch = null; volatile CountDownLatch debugWaitLatch = null; - private InternalAcquireResult internalAcquire1Lease(ImmutableList.Builder builder, long startMs, boolean hasWait, long waitMs) throws Exception - { - if ( client.getState() != CuratorFrameworkState.STARTED ) - { + private InternalAcquireResult internalAcquire1Lease( + ImmutableList.Builder builder, long startMs, boolean hasWait, long waitMs) throws Exception { + if (client.getState() != CuratorFrameworkState.STARTED) { return InternalAcquireResult.RETURN_NULL; } - if ( hasWait ) - { + if (hasWait) { long thisWaitMs = getThisWaitMs(startMs, waitMs); - if ( !lock.acquire(thisWaitMs, TimeUnit.MILLISECONDS) ) - { + if (!lock.acquire(thisWaitMs, TimeUnit.MILLISECONDS)) { return InternalAcquireResult.RETURN_NULL; } - } - else - { + } else { lock.acquire(); } Lease lease = null; boolean success = false; - try - { - PathAndBytesable createBuilder = client.create().creatingParentContainersIfNeeded().withProtection().withMode(CreateMode.EPHEMERAL_SEQUENTIAL); - String path = (nodeData != null) ? createBuilder.forPath(ZKPaths.makePath(leasesPath, LEASE_BASE_NAME), nodeData) : createBuilder.forPath(ZKPaths.makePath(leasesPath, LEASE_BASE_NAME)); + try { + PathAndBytesable createBuilder = client.create() + .creatingParentContainersIfNeeded() + .withProtection() + .withMode(CreateMode.EPHEMERAL_SEQUENTIAL); + String path = (nodeData != null) + ? createBuilder.forPath(ZKPaths.makePath(leasesPath, LEASE_BASE_NAME), nodeData) + : createBuilder.forPath(ZKPaths.makePath(leasesPath, LEASE_BASE_NAME)); String nodeName = ZKPaths.getNodeFromPath(path); lease = makeLease(path); - if ( debugAcquireLatch != null ) - { + if (debugAcquireLatch != null) { debugAcquireLatch.await(); } - try - { - synchronized(this) - { - for(;;) - { + try { + synchronized (this) { + for (; ; ) { List children; - try - { - children = client.getChildren().usingWatcher(watcher).forPath(leasesPath); - } - catch ( Exception e ) - { - if ( debugFailedGetChildrenLatch != null ) - { + try { + children = + client.getChildren().usingWatcher(watcher).forPath(leasesPath); + } catch (Exception e) { + if (debugFailedGetChildrenLatch != null) { debugFailedGetChildrenLatch.countDown(); } throw e; } - if ( !children.contains(nodeName) ) - { + if (!children.contains(nodeName)) { log.error("Sequential path not found: " + path); return InternalAcquireResult.RETRY_DUE_TO_MISSING_NODE; } - if ( children.size() <= maxLeases ) - { + if (children.size() <= maxLeases) { break; } - if ( hasWait ) - { + if (hasWait) { long thisWaitMs = getThisWaitMs(startMs, waitMs); - if ( thisWaitMs <= 0 ) - { + if (thisWaitMs <= 0) { return InternalAcquireResult.RETURN_NULL; } - if ( debugWaitLatch != null ) - { + if (debugWaitLatch != null) { debugWaitLatch.countDown(); } wait(thisWaitMs); - } - else - { - if ( debugWaitLatch != null ) - { + } else { + if (debugWaitLatch != null) { debugWaitLatch.countDown(); } wait(); @@ -420,55 +374,40 @@ private InternalAcquireResult internalAcquire1Lease(ImmutableList.Builder } success = true; } - } - finally - { - if ( !success ) - { + } finally { + if (!success) { returnLease(lease); } client.removeWatchers(); } - } - finally - { + } finally { lock.release(); } builder.add(Preconditions.checkNotNull(lease)); return InternalAcquireResult.CONTINUE; } - private long getThisWaitMs(long startMs, long waitMs) - { + private long getThisWaitMs(long startMs, long waitMs) { long elapsedMs = System.currentTimeMillis() - startMs; return waitMs - elapsedMs; } - private Lease makeLease(final String path) - { - return new Lease() - { + private Lease makeLease(final String path) { + return new Lease() { @Override - public void close() throws IOException - { - try - { + public void close() throws IOException { + try { client.delete().guaranteed().forPath(path); - } - catch ( KeeperException.NoNodeException e ) - { + } catch (KeeperException.NoNodeException e) { log.warn("Lease already released", e); - } - catch ( Exception e ) - { + } catch (Exception e) { ThreadUtils.checkInterrupted(e); throw new IOException(e); } } @Override - public byte[] getData() throws Exception - { + public byte[] getData() throws Exception { return client.getData().forPath(path); } diff --git a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/locks/Lease.java b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/locks/Lease.java index 62e473695..28e823a31 100644 --- a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/locks/Lease.java +++ b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/locks/Lease.java @@ -27,8 +27,7 @@ * to close this lease when it is no longer needed so that other blocked clients can use it. If the * client crashes (or its session expires, etc.) the lease will automatically be closed. */ -public interface Lease extends Closeable -{ +public interface Lease extends Closeable { /** * Releases the lease so that other clients/processes can acquire it * @@ -43,7 +42,7 @@ public interface Lease extends Closeable * @return data * @throws Exception errors */ - public byte[] getData() throws Exception; + public byte[] getData() throws Exception; /** * Return the the node for this lease diff --git a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/locks/LockInternals.java b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/locks/LockInternals.java index bc6475b46..a5f30c408 100644 --- a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/locks/LockInternals.java +++ b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/locks/LockInternals.java @@ -23,6 +23,13 @@ import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; import org.apache.curator.RetryLoop; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.WatcherRemoveCuratorFramework; @@ -34,70 +41,50 @@ import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.WatchedEvent; import org.apache.zookeeper.Watcher; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.Comparator; -import java.util.List; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicReference; -public class LockInternals -{ - private final WatcherRemoveCuratorFramework client; - private final String path; - private final String basePath; - private final LockInternalsDriver driver; - private final String lockName; - private final AtomicReference revocable = new AtomicReference(null); - private final CuratorWatcher revocableWatcher = new CuratorWatcher() - { +public class LockInternals { + private final WatcherRemoveCuratorFramework client; + private final String path; + private final String basePath; + private final LockInternalsDriver driver; + private final String lockName; + private final AtomicReference revocable = new AtomicReference(null); + private final CuratorWatcher revocableWatcher = new CuratorWatcher() { @Override - public void process(WatchedEvent event) throws Exception - { - if ( event.getType() == Watcher.Event.EventType.NodeDataChanged ) - { + public void process(WatchedEvent event) throws Exception { + if (event.getType() == Watcher.Event.EventType.NodeDataChanged) { checkRevocableWatcher(event.getPath()); } } }; - private final Watcher watcher = new Watcher() - { + private final Watcher watcher = new Watcher() { @Override - public void process(WatchedEvent event) - { + public void process(WatchedEvent event) { client.postSafeNotify(LockInternals.this); } }; - private volatile int maxLeases; + private volatile int maxLeases; - static final byte[] REVOKE_MESSAGE = "__REVOKE__".getBytes(); + static final byte[] REVOKE_MESSAGE = "__REVOKE__".getBytes(); /** * Attempt to delete the lock node so that sequence numbers get reset * * @throws Exception errors */ - public void clean() throws Exception - { - try - { + public void clean() throws Exception { + try { client.delete().forPath(basePath); - } - catch ( KeeperException.BadVersionException ignore ) - { + } catch (KeeperException.BadVersionException ignore) { // ignore - another thread/process got the lock - } - catch ( KeeperException.NotEmptyException ignore ) - { + } catch (KeeperException.NotEmptyException ignore) { // ignore - other threads/processes are waiting } } - LockInternals(CuratorFramework client, LockInternalsDriver driver, String path, String lockName, int maxLeases) - { + LockInternals(CuratorFramework client, LockInternalsDriver driver, String path, String lockName, int maxLeases) { this.driver = driver; this.lockName = lockName; this.maxLeases = maxLeases; @@ -107,248 +94,189 @@ public void clean() throws Exception this.path = ZKPaths.makePath(path, lockName); } - synchronized void setMaxLeases(int maxLeases) - { + synchronized void setMaxLeases(int maxLeases) { this.maxLeases = maxLeases; notifyAll(); } - void makeRevocable(RevocationSpec entry) - { + void makeRevocable(RevocationSpec entry) { revocable.set(entry); } - final void releaseLock(String lockPath) throws Exception - { + final void releaseLock(String lockPath) throws Exception { client.removeWatchers(); revocable.set(null); deleteOurPath(lockPath); } - CuratorFramework getClient() - { + CuratorFramework getClient() { return client; } - public static Collection getParticipantNodes(CuratorFramework client, final String basePath, String lockName, LockInternalsSorter sorter) throws Exception - { - List names = getSortedChildren(client, basePath, lockName, sorter); - Iterable transformed = Iterables.transform - ( - names, - new Function() - { - @Override - public String apply(String name) - { - return ZKPaths.makePath(basePath, name); - } - } - ); + public static Collection getParticipantNodes( + CuratorFramework client, final String basePath, String lockName, LockInternalsSorter sorter) + throws Exception { + List names = getSortedChildren(client, basePath, lockName, sorter); + Iterable transformed = Iterables.transform(names, new Function() { + @Override + public String apply(String name) { + return ZKPaths.makePath(basePath, name); + } + }); return ImmutableList.copyOf(transformed); } - public static List getSortedChildren(CuratorFramework client, String basePath, final String lockName, final LockInternalsSorter sorter) throws Exception - { - try - { + public static List getSortedChildren( + CuratorFramework client, String basePath, final String lockName, final LockInternalsSorter sorter) + throws Exception { + try { List children = client.getChildren().forPath(basePath); List sortedList = Lists.newArrayList(children); - Collections.sort - ( - sortedList, - new Comparator() - { - @Override - public int compare(String lhs, String rhs) - { - return sorter.fixForSorting(lhs, lockName).compareTo(sorter.fixForSorting(rhs, lockName)); - } + Collections.sort(sortedList, new Comparator() { + @Override + public int compare(String lhs, String rhs) { + return sorter.fixForSorting(lhs, lockName).compareTo(sorter.fixForSorting(rhs, lockName)); } - ); + }); return sortedList; - } - catch ( KeeperException.NoNodeException ignore ) - { + } catch (KeeperException.NoNodeException ignore) { return Collections.emptyList(); } } - public static List getSortedChildren(final String lockName, final LockInternalsSorter sorter, List children) - { + public static List getSortedChildren( + final String lockName, final LockInternalsSorter sorter, List children) { List sortedList = Lists.newArrayList(children); - Collections.sort - ( - sortedList, - new Comparator() - { - @Override - public int compare(String lhs, String rhs) - { - return sorter.fixForSorting(lhs, lockName).compareTo(sorter.fixForSorting(rhs, lockName)); - } + Collections.sort(sortedList, new Comparator() { + @Override + public int compare(String lhs, String rhs) { + return sorter.fixForSorting(lhs, lockName).compareTo(sorter.fixForSorting(rhs, lockName)); } - ); + }); return sortedList; } - List getSortedChildren() throws Exception - { + List getSortedChildren() throws Exception { return getSortedChildren(client, basePath, lockName, driver); } - String getLockName() - { + String getLockName() { return lockName; } - LockInternalsDriver getDriver() - { + LockInternalsDriver getDriver() { return driver; } - String attemptLock(long time, TimeUnit unit, byte[] lockNodeBytes) throws Exception - { - final long startMillis = System.currentTimeMillis(); - final Long millisToWait = (unit != null) ? unit.toMillis(time) : null; - final byte[] localLockNodeBytes = (revocable.get() != null) ? new byte[0] : lockNodeBytes; - int retryCount = 0; + String attemptLock(long time, TimeUnit unit, byte[] lockNodeBytes) throws Exception { + final long startMillis = System.currentTimeMillis(); + final Long millisToWait = (unit != null) ? unit.toMillis(time) : null; + final byte[] localLockNodeBytes = (revocable.get() != null) ? new byte[0] : lockNodeBytes; + int retryCount = 0; - String ourPath = null; - boolean hasTheLock = false; - boolean isDone = false; - while ( !isDone ) - { + String ourPath = null; + boolean hasTheLock = false; + boolean isDone = false; + while (!isDone) { isDone = true; - try - { + try { ourPath = driver.createsTheLock(client, path, localLockNodeBytes); hasTheLock = internalLockLoop(startMillis, millisToWait, ourPath); - } - catch ( KeeperException.NoNodeException e ) - { + } catch (KeeperException.NoNodeException e) { // gets thrown by StandardLockInternalsDriver when it can't find the lock node // this can happen when the session expires, etc. So, if the retry allows, just try it all again - if ( client.getZookeeperClient().getRetryPolicy().allowRetry(retryCount++, System.currentTimeMillis() - startMillis, RetryLoop.getDefaultRetrySleeper()) ) - { + if (client.getZookeeperClient() + .getRetryPolicy() + .allowRetry( + retryCount++, + System.currentTimeMillis() - startMillis, + RetryLoop.getDefaultRetrySleeper())) { isDone = false; - } - else - { + } else { throw e; } } } - if ( hasTheLock ) - { + if (hasTheLock) { return ourPath; } return null; } - private void checkRevocableWatcher(String path) throws Exception - { - RevocationSpec entry = revocable.get(); - if ( entry != null ) - { - try - { - byte[] bytes = client.getData().usingWatcher(revocableWatcher).forPath(path); - if ( Arrays.equals(bytes, REVOKE_MESSAGE) ) - { + private void checkRevocableWatcher(String path) throws Exception { + RevocationSpec entry = revocable.get(); + if (entry != null) { + try { + byte[] bytes = client.getData().usingWatcher(revocableWatcher).forPath(path); + if (Arrays.equals(bytes, REVOKE_MESSAGE)) { entry.getExecutor().execute(entry.getRunnable()); } - } - catch ( KeeperException.NoNodeException ignore ) - { + } catch (KeeperException.NoNodeException ignore) { // ignore } } } - private boolean internalLockLoop(long startMillis, Long millisToWait, String ourPath) throws Exception - { - boolean haveTheLock = false; - boolean doDelete = false; - try - { - if ( revocable.get() != null ) - { + private boolean internalLockLoop(long startMillis, Long millisToWait, String ourPath) throws Exception { + boolean haveTheLock = false; + boolean doDelete = false; + try { + if (revocable.get() != null) { client.getData().usingWatcher(revocableWatcher).forPath(ourPath); } - while ( (client.getState() == CuratorFrameworkState.STARTED) && !haveTheLock ) - { - List children = getSortedChildren(); - String sequenceNodeName = ourPath.substring(basePath.length() + 1); // +1 to include the slash + while ((client.getState() == CuratorFrameworkState.STARTED) && !haveTheLock) { + List children = getSortedChildren(); + String sequenceNodeName = ourPath.substring(basePath.length() + 1); // +1 to include the slash - PredicateResults predicateResults = driver.getsTheLock(client, children, sequenceNodeName, maxLeases); - if ( predicateResults.getsTheLock() ) - { + PredicateResults predicateResults = driver.getsTheLock(client, children, sequenceNodeName, maxLeases); + if (predicateResults.getsTheLock()) { haveTheLock = true; - } - else - { - String previousSequencePath = basePath + "/" + predicateResults.getPathToWatch(); + } else { + String previousSequencePath = basePath + "/" + predicateResults.getPathToWatch(); - synchronized(this) - { - try - { - // use getData() instead of exists() to avoid leaving unneeded watchers which is a type of resource leak + synchronized (this) { + try { + // use getData() instead of exists() to avoid leaving unneeded watchers which is a type of + // resource leak client.getData().usingWatcher(watcher).forPath(previousSequencePath); - if ( millisToWait != null ) - { + if (millisToWait != null) { millisToWait -= (System.currentTimeMillis() - startMillis); startMillis = System.currentTimeMillis(); - if ( millisToWait <= 0 ) - { - doDelete = true; // timed out - delete our node + if (millisToWait <= 0) { + doDelete = true; // timed out - delete our node break; } wait(millisToWait); - } - else - { + } else { wait(); } - } - catch ( KeeperException.NoNodeException e ) - { + } catch (KeeperException.NoNodeException e) { // it has been deleted (i.e. lock released). Try to acquire again } } } } - } - catch ( Exception e ) - { + } catch (Exception e) { ThreadUtils.checkInterrupted(e); doDelete = true; throw e; - } - finally - { - if ( doDelete ) - { + } finally { + if (doDelete) { deleteOurPath(ourPath); } } return haveTheLock; } - private void deleteOurPath(String ourPath) throws Exception - { - try - { + private void deleteOurPath(String ourPath) throws Exception { + try { client.delete().guaranteed().forPath(ourPath); - } - catch ( KeeperException.NoNodeException e ) - { + } catch (KeeperException.NoNodeException e) { // ignore - already deleted (possibly expired session, etc.) } } diff --git a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/locks/LockInternalsDriver.java b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/locks/LockInternalsDriver.java index 158956c4e..23e38e0a8 100644 --- a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/locks/LockInternalsDriver.java +++ b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/locks/LockInternalsDriver.java @@ -19,12 +19,12 @@ package org.apache.curator.framework.recipes.locks; -import org.apache.curator.framework.CuratorFramework; import java.util.List; +import org.apache.curator.framework.CuratorFramework; -public interface LockInternalsDriver extends LockInternalsSorter -{ - public PredicateResults getsTheLock(CuratorFramework client, List children, String sequenceNodeName, int maxLeases) throws Exception; +public interface LockInternalsDriver extends LockInternalsSorter { + public PredicateResults getsTheLock( + CuratorFramework client, List children, String sequenceNodeName, int maxLeases) throws Exception; - public String createsTheLock(CuratorFramework client, String path, byte[] lockNodeBytes) throws Exception; + public String createsTheLock(CuratorFramework client, String path, byte[] lockNodeBytes) throws Exception; } diff --git a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/locks/LockInternalsSorter.java b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/locks/LockInternalsSorter.java index 71eab0cec..178cf6506 100644 --- a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/locks/LockInternalsSorter.java +++ b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/locks/LockInternalsSorter.java @@ -19,7 +19,6 @@ package org.apache.curator.framework.recipes.locks; -public interface LockInternalsSorter -{ - public String fixForSorting(String str, String lockName); +public interface LockInternalsSorter { + public String fixForSorting(String str, String lockName); } diff --git a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/locks/Locker.java b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/locks/Locker.java index 6b356f6a1..51f797b82 100644 --- a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/locks/Locker.java +++ b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/locks/Locker.java @@ -40,8 +40,7 @@ * *

*/ -public class Locker implements AutoCloseable -{ +public class Locker implements AutoCloseable { private final InterProcessLock lock; private final AtomicBoolean acquired = new AtomicBoolean(false); @@ -51,12 +50,10 @@ public class Locker implements AutoCloseable * @param unit time unit of timeout * @throws Exception Curator errors or {@link TimeoutException} if the lock cannot be acquired within the timeout */ - public Locker(InterProcessLock lock, long timeout, TimeUnit unit) throws Exception - { + public Locker(InterProcessLock lock, long timeout, TimeUnit unit) throws Exception { this.lock = lock; acquired.set(acquireLock(lock, timeout, unit)); - if ( !acquired.get() ) - { + if (!acquired.get()) { throw new TimeoutException("Could not acquire lock within timeout of " + unit.toMillis(timeout) + "ms"); } } @@ -65,8 +62,7 @@ public Locker(InterProcessLock lock, long timeout, TimeUnit unit) throws Excepti * @param lock a lock implementation (e.g. {@link InterProcessMutex}, {@link InterProcessSemaphoreV2}, etc.) * @throws Exception errors */ - public Locker(InterProcessLock lock) throws Exception - { + public Locker(InterProcessLock lock) throws Exception { this.lock = lock; acquireLock(lock); acquired.set(true); @@ -77,26 +73,21 @@ public Locker(InterProcessLock lock) throws Exception * Relase the lock if it has been acquired. Can be safely called multiple times. * Only the first call will unlock. */ - public void close() throws Exception - { - if ( acquired.compareAndSet(true, false) ) - { + public void close() throws Exception { + if (acquired.compareAndSet(true, false)) { releaseLock(); } } - protected void releaseLock() throws Exception - { + protected void releaseLock() throws Exception { lock.release(); } - protected void acquireLock(InterProcessLock lock) throws Exception - { + protected void acquireLock(InterProcessLock lock) throws Exception { lock.acquire(); } - protected boolean acquireLock(InterProcessLock lock, long timeout, TimeUnit unit) throws Exception - { + protected boolean acquireLock(InterProcessLock lock, long timeout, TimeUnit unit) throws Exception { return lock.acquire(timeout, unit); } } diff --git a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/locks/PredicateResults.java b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/locks/PredicateResults.java index fe9f2a5e6..4780fae6e 100644 --- a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/locks/PredicateResults.java +++ b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/locks/PredicateResults.java @@ -19,24 +19,20 @@ package org.apache.curator.framework.recipes.locks; -public class PredicateResults -{ - private final boolean getsTheLock; - private final String pathToWatch; +public class PredicateResults { + private final boolean getsTheLock; + private final String pathToWatch; - public PredicateResults(String pathToWatch, boolean getsTheLock) - { + public PredicateResults(String pathToWatch, boolean getsTheLock) { this.pathToWatch = pathToWatch; this.getsTheLock = getsTheLock; } - public String getPathToWatch() - { + public String getPathToWatch() { return pathToWatch; } - public boolean getsTheLock() - { + public boolean getsTheLock() { return getsTheLock; } } diff --git a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/locks/Revocable.java b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/locks/Revocable.java index e5df55bb3..04e4bf81d 100644 --- a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/locks/Revocable.java +++ b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/locks/Revocable.java @@ -24,15 +24,14 @@ /** * Specifies locks that can be revoked */ -public interface Revocable -{ +public interface Revocable { /** * Make the lock revocable. Your listener will get called when another process/thread * wants you to release the lock. Revocation is cooperative. * * @param listener the listener */ - public void makeRevocable(RevocationListener listener); + public void makeRevocable(RevocationListener listener); /** * Make the lock revocable. Your listener will get called when another process/thread @@ -41,5 +40,5 @@ public interface Revocable * @param listener the listener * @param executor executor for the listener */ - public void makeRevocable(RevocationListener listener, Executor executor); + public void makeRevocable(RevocationListener listener, Executor executor); } diff --git a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/locks/RevocationListener.java b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/locks/RevocationListener.java index cebf74588..ba7e5ad54 100644 --- a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/locks/RevocationListener.java +++ b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/locks/RevocationListener.java @@ -19,13 +19,12 @@ package org.apache.curator.framework.recipes.locks; -public interface RevocationListener -{ +public interface RevocationListener { /** * Called when a revocation request has been received. You should release the lock as soon * as possible. Revocation is cooperative. * * @param forLock the lock that should release */ - public void revocationRequested(T forLock); + public void revocationRequested(T forLock); } diff --git a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/locks/RevocationSpec.java b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/locks/RevocationSpec.java index f1cf7e91a..82d926a42 100644 --- a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/locks/RevocationSpec.java +++ b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/locks/RevocationSpec.java @@ -21,24 +21,20 @@ import java.util.concurrent.Executor; -class RevocationSpec -{ - private final Runnable runnable; - private final Executor executor; +class RevocationSpec { + private final Runnable runnable; + private final Executor executor; - RevocationSpec(Executor executor, Runnable runnable) - { + RevocationSpec(Executor executor, Runnable runnable) { this.runnable = runnable; this.executor = executor; } - Runnable getRunnable() - { + Runnable getRunnable() { return runnable; } - Executor getExecutor() - { + Executor getExecutor() { return executor; } } diff --git a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/locks/Revoker.java b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/locks/Revoker.java index da412fffc..8dd9e4c91 100644 --- a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/locks/Revoker.java +++ b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/locks/Revoker.java @@ -22,8 +22,7 @@ import org.apache.curator.framework.CuratorFramework; import org.apache.zookeeper.KeeperException; -public class Revoker -{ +public class Revoker { /** * Utility to mark a lock for revocation. Assuming that the lock has been registered with * a {@link RevocationListener}, it will get called and the lock should be released. Note, @@ -34,19 +33,13 @@ public class Revoker * {@link InterProcessMutex#getParticipantNodes()} * @throws Exception errors */ - public static void attemptRevoke(CuratorFramework client, String path) throws Exception - { - try - { + public static void attemptRevoke(CuratorFramework client, String path) throws Exception { + try { client.setData().forPath(path, LockInternals.REVOKE_MESSAGE); - } - catch ( KeeperException.NoNodeException ignore ) - { + } catch (KeeperException.NoNodeException ignore) { // ignore } } - private Revoker() - { - } + private Revoker() {} } diff --git a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/locks/StandardLockInternalsDriver.java b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/locks/StandardLockInternalsDriver.java index b9e5d52a5..fd664f28d 100644 --- a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/locks/StandardLockInternalsDriver.java +++ b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/locks/StandardLockInternalsDriver.java @@ -19,25 +19,24 @@ package org.apache.curator.framework.recipes.locks; +import java.util.List; import org.apache.curator.framework.CuratorFramework; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.KeeperException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.util.List; -public class StandardLockInternalsDriver implements LockInternalsDriver -{ - static private final Logger log = LoggerFactory.getLogger(StandardLockInternalsDriver.class); +public class StandardLockInternalsDriver implements LockInternalsDriver { + private static final Logger log = LoggerFactory.getLogger(StandardLockInternalsDriver.class); @Override - public PredicateResults getsTheLock(CuratorFramework client, List children, String sequenceNodeName, int maxLeases) throws Exception - { - int ourIndex = children.indexOf(sequenceNodeName); + public PredicateResults getsTheLock( + CuratorFramework client, List children, String sequenceNodeName, int maxLeases) throws Exception { + int ourIndex = children.indexOf(sequenceNodeName); validateOurIndex(sequenceNodeName, ourIndex); - boolean getsTheLock = ourIndex < maxLeases; - String pathToWatch = getsTheLock ? null : children.get(ourIndex - maxLeases); + boolean getsTheLock = ourIndex < maxLeases; + String pathToWatch = getsTheLock ? null : children.get(ourIndex - maxLeases); return new PredicateResults(pathToWatch, getsTheLock); } @@ -47,8 +46,7 @@ protected String getSortingSequence() { } @Override - public String createsTheLock(CuratorFramework client, String path, byte[] lockNodeBytes) throws Exception - { + public String createsTheLock(CuratorFramework client, String path, byte[] lockNodeBytes) throws Exception { CreateMode createMode = CreateMode.EPHEMERAL_SEQUENTIAL; String sequence = getSortingSequence(); @@ -57,39 +55,38 @@ public String createsTheLock(CuratorFramework client, String path, byte[] lockNo createMode = CreateMode.EPHEMERAL; } String ourPath; - if ( lockNodeBytes != null ) - { - ourPath = client.create().creatingParentContainersIfNeeded().withProtection().withMode(createMode).forPath(path, lockNodeBytes); - } - else - { - ourPath = client.create().creatingParentContainersIfNeeded().withProtection().withMode(createMode).forPath(path); + if (lockNodeBytes != null) { + ourPath = client.create() + .creatingParentContainersIfNeeded() + .withProtection() + .withMode(createMode) + .forPath(path, lockNodeBytes); + } else { + ourPath = client.create() + .creatingParentContainersIfNeeded() + .withProtection() + .withMode(createMode) + .forPath(path); } return ourPath; } - @Override - public String fixForSorting(String str, String lockName) - { + public String fixForSorting(String str, String lockName) { return standardFixForSorting(str, lockName); } - public static String standardFixForSorting(String str, String lockName) - { + public static String standardFixForSorting(String str, String lockName) { int index = str.lastIndexOf(lockName); - if ( index >= 0 ) - { + if (index >= 0) { index += lockName.length(); return index <= str.length() ? str.substring(index) : ""; } return str; } - static void validateOurIndex(String sequenceNodeName, int ourIndex) throws KeeperException - { - if ( ourIndex < 0 ) - { + static void validateOurIndex(String sequenceNodeName, int ourIndex) throws KeeperException { + if (ourIndex < 0) { throw new KeeperException.NoNodeException("Sequential path not found: " + sequenceNodeName); } } diff --git a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/nodes/GroupMember.java b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/nodes/GroupMember.java index 91b501eab..41b994211 100644 --- a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/nodes/GroupMember.java +++ b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/nodes/GroupMember.java @@ -19,9 +19,13 @@ package org.apache.curator.framework.recipes.nodes; +import static org.apache.curator.framework.recipes.cache.CuratorCacheAccessor.parentPathFilter; import com.google.common.base.Preconditions; import com.google.common.base.Throwables; import com.google.common.collect.ImmutableMap; +import java.io.Closeable; +import java.util.Iterator; +import java.util.Map; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.recipes.cache.ChildData; @@ -31,18 +35,12 @@ import org.apache.curator.utils.ThreadUtils; import org.apache.curator.utils.ZKPaths; import org.apache.zookeeper.CreateMode; -import java.io.Closeable; -import java.util.Iterator; -import java.util.Map; - -import static org.apache.curator.framework.recipes.cache.CuratorCacheAccessor.parentPathFilter; /** * Group membership management. Adds this instance into a group and * keeps a cache of members in the group */ -public class GroupMember implements Closeable -{ +public class GroupMember implements Closeable { private final PersistentNode pen; private final CuratorCacheBridge cache; private final String membershipPath; @@ -53,8 +51,7 @@ public class GroupMember implements Closeable * @param membershipPath the path to use for membership * @param thisId ID of this group member. MUST be unique for the group */ - public GroupMember(CuratorFramework client, String membershipPath, String thisId) - { + public GroupMember(CuratorFramework client, String membershipPath, String thisId) { this(client, membershipPath, thisId, CuratorFrameworkFactory.getLocalAddress()); } @@ -64,28 +61,24 @@ public GroupMember(CuratorFramework client, String membershipPath, String thisId * @param thisId ID of this group member. MUST be unique for the group * @param payload the payload to write in our member node */ - public GroupMember(CuratorFramework client, String membershipPath, String thisId, byte[] payload) - { + public GroupMember(CuratorFramework client, String membershipPath, String thisId, byte[] payload) { this.membershipPath = membershipPath; this.thisId = Preconditions.checkNotNull(thisId, "thisId cannot be null"); cache = CuratorCache.bridgeBuilder(client, membershipPath).build(); - pen = new PersistentNode(client, CreateMode.EPHEMERAL, false, ZKPaths.makePath(membershipPath, thisId), payload); + pen = new PersistentNode( + client, CreateMode.EPHEMERAL, false, ZKPaths.makePath(membershipPath, thisId), payload); } /** * Start the group membership. Register thisId as a member and begin * caching all members */ - public void start() - { + public void start() { pen.start(); - try - { + try { cache.start(); - } - catch ( Exception e ) - { + } catch (Exception e) { ThreadUtils.checkInterrupted(e); Throwables.propagate(e); } @@ -96,14 +89,10 @@ public void start() * * @param data new data (cannot be null) */ - public void setThisData(byte[] data) - { - try - { + public void setThisData(byte[] data) { + try { pen.setData(data); - } - catch ( Exception e ) - { + } catch (Exception e) { ThreadUtils.checkInterrupted(e); Throwables.propagate(e); } @@ -113,8 +102,7 @@ public void setThisData(byte[] data) * Have thisId leave the group and stop caching membership */ @Override - public void close() - { + public void close() { CloseableUtils.closeQuietly(cache); CloseableUtils.closeQuietly(pen); } @@ -125,22 +113,20 @@ public void close() * * @return membership */ - public Map getCurrentMembers() - { + public Map getCurrentMembers() { ImmutableMap.Builder builder = ImmutableMap.builder(); boolean thisIdAdded = false; - Iterator iterator = cache.stream().filter(parentPathFilter(membershipPath)).iterator(); - while ( iterator.hasNext() ) - { + Iterator iterator = + cache.stream().filter(parentPathFilter(membershipPath)).iterator(); + while (iterator.hasNext()) { ChildData data = iterator.next(); String id = idFromPath(data.getPath()); thisIdAdded = thisIdAdded || id.equals(thisId); builder.put(id, data.getData()); } - if ( !thisIdAdded ) - { - builder.put(thisId, pen.getData()); // this instance is always a member + if (!thisIdAdded) { + builder.put(thisId, pen.getData()); // this instance is always a member } return builder.build(); } @@ -151,8 +137,7 @@ public Map getCurrentMembers() * @param path full ZNode path * @return id */ - public String idFromPath(String path) - { + public String idFromPath(String path) { return ZKPaths.getNodeFromPath(path); } } diff --git a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/nodes/PersistentEphemeralNode.java b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/nodes/PersistentEphemeralNode.java index 1b60a7157..284b27818 100644 --- a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/nodes/PersistentEphemeralNode.java +++ b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/nodes/PersistentEphemeralNode.java @@ -34,87 +34,73 @@ * @deprecated This has been replaced with the more general {@link PersistentNode} */ @Deprecated -public class PersistentEphemeralNode extends PersistentNode -{ +public class PersistentEphemeralNode extends PersistentNode { /** * The mode for node creation * * @deprecated This has been replaced with the more general {@link PersistentNode} */ @Deprecated - public enum Mode - { + public enum Mode { /** * Same as {@link CreateMode#EPHEMERAL} */ - EPHEMERAL() - { - @Override - protected CreateMode getCreateMode(boolean pathIsSet) - { - return CreateMode.EPHEMERAL; - } + EPHEMERAL() { + @Override + protected CreateMode getCreateMode(boolean pathIsSet) { + return CreateMode.EPHEMERAL; + } - @Override - protected boolean isProtected() - { - return false; - } - }, + @Override + protected boolean isProtected() { + return false; + } + }, /** * Same as {@link CreateMode#EPHEMERAL_SEQUENTIAL} */ - EPHEMERAL_SEQUENTIAL() - { - @Override - protected CreateMode getCreateMode(boolean pathIsSet) - { - return pathIsSet ? CreateMode.EPHEMERAL : CreateMode.EPHEMERAL_SEQUENTIAL; - } + EPHEMERAL_SEQUENTIAL() { + @Override + protected CreateMode getCreateMode(boolean pathIsSet) { + return pathIsSet ? CreateMode.EPHEMERAL : CreateMode.EPHEMERAL_SEQUENTIAL; + } - @Override - protected boolean isProtected() - { - return false; - } - }, + @Override + protected boolean isProtected() { + return false; + } + }, /** * Same as {@link CreateMode#EPHEMERAL} with protection */ - PROTECTED_EPHEMERAL() - { - @Override - protected CreateMode getCreateMode(boolean pathIsSet) - { - return CreateMode.EPHEMERAL; - } + PROTECTED_EPHEMERAL() { + @Override + protected CreateMode getCreateMode(boolean pathIsSet) { + return CreateMode.EPHEMERAL; + } - @Override - protected boolean isProtected() - { - return true; - } - }, + @Override + protected boolean isProtected() { + return true; + } + }, /** * Same as {@link CreateMode#EPHEMERAL_SEQUENTIAL} with protection */ - PROTECTED_EPHEMERAL_SEQUENTIAL() - { - @Override - protected CreateMode getCreateMode(boolean pathIsSet) - { - return pathIsSet ? CreateMode.EPHEMERAL : CreateMode.EPHEMERAL_SEQUENTIAL; - } + PROTECTED_EPHEMERAL_SEQUENTIAL() { + @Override + protected CreateMode getCreateMode(boolean pathIsSet) { + return pathIsSet ? CreateMode.EPHEMERAL : CreateMode.EPHEMERAL_SEQUENTIAL; + } - @Override - protected boolean isProtected() - { - return true; - } - }; + @Override + protected boolean isProtected() { + return true; + } + }; protected abstract CreateMode getCreateMode(boolean pathIsSet); @@ -128,8 +114,7 @@ protected boolean isProtected() * @param initData data for the node */ @SuppressWarnings("deprecation") - public PersistentEphemeralNode(CuratorFramework client, Mode mode, String basePath, byte[] initData) - { + public PersistentEphemeralNode(CuratorFramework client, Mode mode, String basePath, byte[] initData) { super(client, mode.getCreateMode(false), mode.isProtected(), basePath, initData); } } diff --git a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/nodes/PersistentNode.java b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/nodes/PersistentNode.java index aa2f1a6f2..b7a87fd22 100644 --- a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/nodes/PersistentNode.java +++ b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/nodes/PersistentNode.java @@ -21,6 +21,13 @@ import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; +import java.io.Closeable; +import java.io.IOException; +import java.util.Arrays; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicLong; +import java.util.concurrent.atomic.AtomicReference; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.WatcherRemoveCuratorFramework; import org.apache.curator.framework.api.ACLBackgroundPathAndBytesable; @@ -43,14 +50,6 @@ import org.apache.zookeeper.Watcher.Event.EventType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.io.Closeable; -import java.io.IOException; -import java.util.Arrays; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicLong; -import java.util.concurrent.atomic.AtomicReference; /** *

@@ -61,9 +60,9 @@ * Thanks to bbeck (https://github.com/bbeck) for the initial coding and design *

*/ -public class PersistentNode implements Closeable -{ - private final AtomicReference initialCreateLatch = new AtomicReference(new CountDownLatch(1)); +public class PersistentNode implements Closeable { + private final AtomicReference initialCreateLatch = + new AtomicReference(new CountDownLatch(1)); private final Logger log = LoggerFactory.getLogger(getClass()); private final WatcherRemoveCuratorFramework client; private final AtomicReference nodePath = new AtomicReference(null); @@ -77,82 +76,61 @@ public class PersistentNode implements Closeable private final BackgroundCallback backgroundCallback; private final boolean useProtection; private final boolean useParentCreation; - private final AtomicReference>> createMethod = new AtomicReference>>(null); + private final AtomicReference>> createMethod = + new AtomicReference>>(null); private final StandardListenerManager listeners = StandardListenerManager.standard(); - private final CuratorWatcher watcher = new CuratorWatcher() - { + private final CuratorWatcher watcher = new CuratorWatcher() { @Override - public void process(WatchedEvent event) throws Exception - { - if ( isActive() ) - { - if ( event.getType() == EventType.NodeDeleted ) - { + public void process(WatchedEvent event) throws Exception { + if (isActive()) { + if (event.getType() == EventType.NodeDeleted) { createNode(); - } - else if ( event.getType() == EventType.NodeDataChanged ) - { + } else if (event.getType() == EventType.NodeDataChanged) { watchNode(); } } } }; - private final BackgroundCallback checkExistsCallback = new BackgroundCallback() - { + private final BackgroundCallback checkExistsCallback = new BackgroundCallback() { @Override - public void processResult(CuratorFramework dummy, CuratorEvent event) throws Exception - { - if ( isActive() ) - { - if ( event.getResultCode() == KeeperException.Code.NONODE.intValue() ) - { + public void processResult(CuratorFramework dummy, CuratorEvent event) throws Exception { + if (isActive()) { + if (event.getResultCode() == KeeperException.Code.NONODE.intValue()) { createNode(); - } - else - { + } else { boolean isEphemeral = event.getStat().getEphemeralOwner() != 0; - if ( isEphemeral != mode.isEphemeral() ) - { - log.warn("Existing node ephemeral state doesn't match requested state. Maybe the node was created outside of PersistentNode? " + basePath); + if (isEphemeral != mode.isEphemeral()) { + log.warn( + "Existing node ephemeral state doesn't match requested state. Maybe the node was created outside of PersistentNode? " + + basePath); } } - } - else - { + } else { client.removeWatchers(); } } }; - private final BackgroundCallback setDataCallback = new BackgroundCallback() - { + private final BackgroundCallback setDataCallback = new BackgroundCallback() { @Override - public void processResult(CuratorFramework dummy, CuratorEvent event) - throws Exception - { - //If the result is ok then initialisation is complete (if we're still initialising) - //Don't retry on other errors as the only recoverable cases will be connection loss - //and the node not existing, both of which are already handled by other watches. - if ( event.getResultCode() == KeeperException.Code.OK.intValue() ) - { - //Update is ok, mark initialisation as complete if required. + public void processResult(CuratorFramework dummy, CuratorEvent event) throws Exception { + // If the result is ok then initialisation is complete (if we're still initialising) + // Don't retry on other errors as the only recoverable cases will be connection loss + // and the node not existing, both of which are already handled by other watches. + if (event.getResultCode() == KeeperException.Code.OK.intValue()) { + // Update is ok, mark initialisation as complete if required. initialisationComplete(); - } - else if ( event.getResultCode() == KeeperException.Code.NOAUTH.intValue() ) - { + } else if (event.getResultCode() == KeeperException.Code.NOAUTH.intValue()) { log.warn("Client does not have authorisation to write node at path {}", event.getPath()); authFailure = true; } } }; - private final ConnectionStateListener connectionStateListener = new ConnectionStateListener() - { + private final ConnectionStateListener connectionStateListener = new ConnectionStateListener() { @Override - public void stateChanged(CuratorFramework dummy, ConnectionState newState) - { - if ( (newState == ConnectionState.RECONNECTED) && isActive() ) - { + public void stateChanged(CuratorFramework dummy, ConnectionState newState) { + if ((newState == ConnectionState.RECONNECTED) && isActive()) { createNode(); } } @@ -161,8 +139,7 @@ public void stateChanged(CuratorFramework dummy, ConnectionState newState) @VisibleForTesting volatile CountDownLatch debugCreateNodeLatch = null; - private enum State - { + private enum State { LATENT, STARTED, CLOSED @@ -175,8 +152,12 @@ private enum State * @param basePath the base path for the node * @param initData data for the node */ - public PersistentNode(CuratorFramework givenClient, final CreateMode mode, boolean useProtection, final String basePath, byte[] initData) - { + public PersistentNode( + CuratorFramework givenClient, + final CreateMode mode, + boolean useProtection, + final String basePath, + byte[] initData) { this(givenClient, mode, useProtection, basePath, initData, -1, true); } @@ -188,7 +169,13 @@ public PersistentNode(CuratorFramework givenClient, final CreateMode mode, boole * @param initData data for the node * @param useParentCreation if true, call {@link CreateBuilder#creatingParentContainersIfNeeded()} */ - public PersistentNode(CuratorFramework givenClient, final CreateMode mode, boolean useProtection, final String basePath, byte[] initData, boolean useParentCreation) { + public PersistentNode( + CuratorFramework givenClient, + final CreateMode mode, + boolean useProtection, + final String basePath, + byte[] initData, + boolean useParentCreation) { this(givenClient, mode, useProtection, basePath, initData, -1, useParentCreation); } @@ -201,27 +188,29 @@ public PersistentNode(CuratorFramework givenClient, final CreateMode mode, boole * @param ttl for ttl modes, the ttl to use * @param useParentCreation if true, call {@link CreateBuilder#creatingParentContainersIfNeeded()} */ - public PersistentNode(CuratorFramework givenClient, final CreateMode mode, boolean useProtection, final String basePath, byte[] initData, long ttl, boolean useParentCreation) - { + public PersistentNode( + CuratorFramework givenClient, + final CreateMode mode, + boolean useProtection, + final String basePath, + byte[] initData, + long ttl, + boolean useParentCreation) { this.useProtection = useProtection; this.useParentCreation = useParentCreation; - this.client = Preconditions.checkNotNull(givenClient, "client cannot be null").newWatcherRemoveCuratorFramework(); + this.client = + Preconditions.checkNotNull(givenClient, "client cannot be null").newWatcherRemoveCuratorFramework(); this.basePath = PathUtils.validatePath(basePath); this.mode = Preconditions.checkNotNull(mode, "mode cannot be null"); this.ttl = ttl; final byte[] data = Preconditions.checkNotNull(initData, "data cannot be null"); - backgroundCallback = new BackgroundCallback() - { + backgroundCallback = new BackgroundCallback() { @Override - public void processResult(CuratorFramework dummy, CuratorEvent event) throws Exception - { - if ( isActive() ) - { + public void processResult(CuratorFramework dummy, CuratorEvent event) throws Exception { + if (isActive()) { processBackgroundCallback(event); - } - else - { + } else { processBackgroundCallbackClosedState(event); } } @@ -230,82 +219,62 @@ public void processResult(CuratorFramework dummy, CuratorEvent event) throws Exc this.data.set(Arrays.copyOf(data, data.length)); } - private void processBackgroundCallbackClosedState(CuratorEvent event) - { + private void processBackgroundCallbackClosedState(CuratorEvent event) { String path = null; - if ( event.getResultCode() == KeeperException.Code.NODEEXISTS.intValue() ) - { + if (event.getResultCode() == KeeperException.Code.NODEEXISTS.intValue()) { path = event.getPath(); - } - else if ( event.getResultCode() == KeeperException.Code.OK.intValue() ) - { + } else if (event.getResultCode() == KeeperException.Code.OK.intValue()) { path = event.getName(); } - if ( path != null ) - { - try - { + if (path != null) { + try { client.delete().guaranteed().inBackground().forPath(path); - } - catch ( Exception e ) - { + } catch (Exception e) { log.error("Could not delete node after close", e); } } } - private void processBackgroundCallback(CuratorEvent event) throws Exception - { + private void processBackgroundCallback(CuratorEvent event) throws Exception { String path = null; boolean nodeExists = false; - if ( event.getResultCode() == KeeperException.Code.NODEEXISTS.intValue() ) - { + if (event.getResultCode() == KeeperException.Code.NODEEXISTS.intValue()) { path = event.getPath(); nodeExists = true; - } - else if ( event.getResultCode() == KeeperException.Code.OK.intValue() ) - { + } else if (event.getResultCode() == KeeperException.Code.OK.intValue()) { path = event.getName(); - } - else if ( event.getResultCode() == KeeperException.Code.NOAUTH.intValue() ) - { + } else if (event.getResultCode() == KeeperException.Code.NOAUTH.intValue()) { log.warn("Client does not have authorisation to create node at path {}", event.getPath()); authFailure = true; return; - } else if ( event.getResultCode() == KeeperException.Code.NONODE.intValue() ) - { - log.warn("Client cannot create parent hierarchy for path {} with useParentCreation set to {}", event.getPath(), useParentCreation); + } else if (event.getResultCode() == KeeperException.Code.NONODE.intValue()) { + log.warn( + "Client cannot create parent hierarchy for path {} with useParentCreation set to {}", + event.getPath(), + useParentCreation); parentCreationFailure = true; return; } - if ( path != null ) - { + if (path != null) { authFailure = false; nodePath.set(path); watchNode(); - if ( nodeExists ) - { + if (nodeExists) { client.setData().inBackground(setDataCallback).forPath(getActualPath(), getData()); - } - else - { + } else { initialisationComplete(); notifyListeners(); } - } - else - { + } else { createNode(); } } - private void initialisationComplete() - { + private void initialisationComplete() { CountDownLatch localLatch = initialCreateLatch.getAndSet(null); - if ( localLatch != null ) - { + if (localLatch != null) { localLatch.countDown(); } } @@ -314,8 +283,7 @@ private void initialisationComplete() * You must call start() to initiate the persistent node. An attempt to create the node * in the background will be started */ - public void start() - { + public void start() { Preconditions.checkState(state.compareAndSet(State.LATENT, State.STARTED), "Already started"); client.getConnectionStateListenable().addListener(connectionStateListener); @@ -331,8 +299,7 @@ public void start() * @return if the node was created before timeout * @throws InterruptedException if the thread is interrupted */ - public boolean waitForInitialCreate(long timeout, TimeUnit unit) throws InterruptedException - { + public boolean waitForInitialCreate(long timeout, TimeUnit unit) throws InterruptedException { Preconditions.checkState(state.get() == State.STARTED, "Not started"); CountDownLatch localLatch = initialCreateLatch.get(); @@ -343,33 +310,24 @@ public boolean waitForInitialCreate(long timeout, TimeUnit unit) throws Interrup final AtomicLong debugWaitMsForBackgroundBeforeClose = new AtomicLong(0); @Override - public void close() throws IOException - { - if ( debugWaitMsForBackgroundBeforeClose.get() > 0 ) - { - try - { + public void close() throws IOException { + if (debugWaitMsForBackgroundBeforeClose.get() > 0) { + try { Thread.sleep(debugWaitMsForBackgroundBeforeClose.get()); - } - catch ( InterruptedException e ) - { + } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } - if ( !state.compareAndSet(State.STARTED, State.CLOSED) ) - { + if (!state.compareAndSet(State.STARTED, State.CLOSED)) { return; } client.getConnectionStateListenable().removeListener(connectionStateListener); - try - { + try { deleteNode(); - } - catch ( Exception e ) - { + } catch (Exception e) { ThreadUtils.checkInterrupted(e); throw new IOException(e); } @@ -382,8 +340,7 @@ public void close() throws IOException * * @return listenable */ - public Listenable getListenable() - { + public Listenable getListenable() { return listeners; } @@ -392,8 +349,7 @@ public Listenable getListenable() * * @return node path or null */ - public String getActualPath() - { + public String getActualPath() { return nodePath.get(); } @@ -406,14 +362,14 @@ public String getActualPath() * @param data new data value * @throws Exception errors */ - public void setData(byte[] data) throws Exception - { + public void setData(byte[] data) throws Exception { data = Preconditions.checkNotNull(data, "data cannot be null"); - Preconditions.checkState(nodePath.get() != null, "initial create has not been processed. Call waitForInitialCreate() to ensure."); + Preconditions.checkState( + nodePath.get() != null, + "initial create has not been processed. Call waitForInitialCreate() to ensure."); Preconditions.checkState(!parentCreationFailure, "Failed to create parent nodes."); this.data.set(Arrays.copyOf(data, data.length)); - if ( isActive() ) - { + if (isActive()) { client.setData().inBackground(setDataCallback).forPath(getActualPath(), getData()); } } @@ -423,153 +379,126 @@ public void setData(byte[] data) throws Exception * * @return our data */ - public byte[] getData() - { + public byte[] getData() { return this.data.get(); } - protected void deleteNode() throws Exception - { + protected void deleteNode() throws Exception { String localNodePath = nodePath.getAndSet(null); - if ( localNodePath != null ) - { - try - { + if (localNodePath != null) { + try { client.delete().guaranteed().forPath(localNodePath); - } - catch ( KeeperException.NoNodeException ignore ) - { + } catch (KeeperException.NoNodeException ignore) { // ignore } } } - private void createNode() - { - if ( !isActive() ) - { + private void createNode() { + if (!isActive()) { return; } - if ( debugCreateNodeLatch != null ) - { - try - { + if (debugCreateNodeLatch != null) { + try { debugCreateNodeLatch.await(); - } - catch ( InterruptedException e ) - { + } catch (InterruptedException e) { Thread.currentThread().interrupt(); return; } } - try - { + try { String existingPath = nodePath.get(), createPath; - if ( existingPath != null && !useProtection ) - { + if (existingPath != null && !useProtection) { createPath = existingPath; - } - else if ( existingPath != null && mode.isSequential() ) - { + } else if (existingPath != null && mode.isSequential()) { createPath = basePath + ZKPaths.extractSequentialSuffix(existingPath); - } - else - { + } else { createPath = basePath; } CreateModable> localCreateMethod = createMethod.get(); - if ( localCreateMethod == null ) - { + if (localCreateMethod == null) { CreateBuilderMain createBuilder = mode.isTTL() ? client.create().withTtl(ttl) : client.create(); CreateModable> tempCreateMethod; if (useParentCreation) { - tempCreateMethod = useProtection ? createBuilder.creatingParentContainersIfNeeded().withProtection() : createBuilder.creatingParentContainersIfNeeded(); + tempCreateMethod = useProtection + ? createBuilder.creatingParentContainersIfNeeded().withProtection() + : createBuilder.creatingParentContainersIfNeeded(); } else { tempCreateMethod = useProtection ? createBuilder.withProtection() : createBuilder; } createMethod.compareAndSet(null, tempCreateMethod); localCreateMethod = createMethod.get(); } - localCreateMethod.withMode(getCreateMode(existingPath != null)).inBackground(backgroundCallback).forPath(createPath, data.get()); - } - catch ( Exception e ) - { + localCreateMethod + .withMode(getCreateMode(existingPath != null)) + .inBackground(backgroundCallback) + .forPath(createPath, data.get()); + } catch (Exception e) { ThreadUtils.checkInterrupted(e); - throw new RuntimeException("Creating node. BasePath: " + basePath, e); // should never happen unless there's a programming error - so throw RuntimeException + throw new RuntimeException( + "Creating node. BasePath: " + basePath, + e); // should never happen unless there's a programming error - so throw RuntimeException } } - private CreateMode getCreateMode(boolean pathIsSet) - { - if ( pathIsSet ) - { - switch ( mode ) - { - default: - { + private CreateMode getCreateMode(boolean pathIsSet) { + if (pathIsSet) { + switch (mode) { + default: { break; } - case EPHEMERAL_SEQUENTIAL: - { - return CreateMode.EPHEMERAL; // protection case - node already set + case EPHEMERAL_SEQUENTIAL: { + return CreateMode.EPHEMERAL; // protection case - node already set } - case PERSISTENT_SEQUENTIAL: - { - return CreateMode.PERSISTENT; // protection case - node already set + case PERSISTENT_SEQUENTIAL: { + return CreateMode.PERSISTENT; // protection case - node already set } - case PERSISTENT_SEQUENTIAL_WITH_TTL: - { - return CreateMode.PERSISTENT_WITH_TTL; // protection case - node already set + case PERSISTENT_SEQUENTIAL_WITH_TTL: { + return CreateMode.PERSISTENT_WITH_TTL; // protection case - node already set } } } return mode; } - private void watchNode() throws Exception - { - if ( !isActive() ) - { + private void watchNode() throws Exception { + if (!isActive()) { return; } String localNodePath = nodePath.get(); - if ( localNodePath != null ) - { - client.checkExists().usingWatcher(watcher).inBackground(checkExistsCallback).forPath(localNodePath); + if (localNodePath != null) { + client.checkExists() + .usingWatcher(watcher) + .inBackground(checkExistsCallback) + .forPath(localNodePath); } } - private void notifyListeners() - { + private void notifyListeners() { final String path = getActualPath(); listeners.forEach(listener -> { - try - { + try { listener.nodeCreated(path); - } - catch ( Exception e ) - { + } catch (Exception e) { ThreadUtils.checkInterrupted(e); log.error("From PersistentNode listener", e); } }); } - private boolean isActive() - { + private boolean isActive() { return (state.get() == State.STARTED); } @VisibleForTesting - boolean isAuthFailure() - { + boolean isAuthFailure() { return authFailure; } @@ -577,5 +506,4 @@ boolean isAuthFailure() boolean isParentCreationFailure() { return parentCreationFailure; } - } diff --git a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/nodes/PersistentTtlNode.java b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/nodes/PersistentTtlNode.java index 4d21fbe78..2b2ba561a 100644 --- a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/nodes/PersistentTtlNode.java +++ b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/nodes/PersistentTtlNode.java @@ -19,13 +19,6 @@ package org.apache.curator.framework.recipes.nodes; -import org.apache.curator.framework.CuratorFramework; -import org.apache.curator.utils.ThreadUtils; -import org.apache.curator.utils.ZKPaths; -import org.apache.zookeeper.CreateMode; -import org.apache.zookeeper.KeeperException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import java.io.Closeable; import java.io.IOException; import java.util.Objects; @@ -34,6 +27,13 @@ import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; +import org.apache.curator.framework.CuratorFramework; +import org.apache.curator.utils.ThreadUtils; +import org.apache.curator.utils.ZKPaths; +import org.apache.zookeeper.CreateMode; +import org.apache.zookeeper.KeeperException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** *

@@ -55,8 +55,7 @@ * the keep-alive is done in a way that does not generate watch triggers on the parent node. *

*/ -public class PersistentTtlNode implements Closeable -{ +public class PersistentTtlNode implements Closeable { public static final String DEFAULT_CHILD_NODE_NAME = "touch"; public static final int DEFAULT_TOUCH_SCHEDULE_FACTOR = 2; public static final boolean DEFAULT_USE_PARENT_CREATION = true; @@ -76,9 +75,16 @@ public class PersistentTtlNode implements Closeable * @param ttlMs max ttl for the node in milliseconds * @param initData data for the node */ - public PersistentTtlNode(CuratorFramework client, String path, long ttlMs, byte[] initData) - { - this(client, Executors.newSingleThreadScheduledExecutor(ThreadUtils.newThreadFactory("PersistentTtlNode")), path, ttlMs, initData, DEFAULT_CHILD_NODE_NAME, DEFAULT_TOUCH_SCHEDULE_FACTOR, DEFAULT_USE_PARENT_CREATION); + public PersistentTtlNode(CuratorFramework client, String path, long ttlMs, byte[] initData) { + this( + client, + Executors.newSingleThreadScheduledExecutor(ThreadUtils.newThreadFactory("PersistentTtlNode")), + path, + ttlMs, + initData, + DEFAULT_CHILD_NODE_NAME, + DEFAULT_TOUCH_SCHEDULE_FACTOR, + DEFAULT_USE_PARENT_CREATION); } /** @@ -88,9 +94,17 @@ public PersistentTtlNode(CuratorFramework client, String path, long ttlMs, byte[ * @param initData data for the node * @param useParentCreation if true, parent ZNode can be created without ancestors */ - public PersistentTtlNode(CuratorFramework client, String path, long ttlMs, byte[] initData, boolean useParentCreation) - { - this(client, Executors.newSingleThreadScheduledExecutor(ThreadUtils.newThreadFactory("PersistentTtlNode")), path, ttlMs, initData, DEFAULT_CHILD_NODE_NAME, DEFAULT_TOUCH_SCHEDULE_FACTOR, useParentCreation); + public PersistentTtlNode( + CuratorFramework client, String path, long ttlMs, byte[] initData, boolean useParentCreation) { + this( + client, + Executors.newSingleThreadScheduledExecutor(ThreadUtils.newThreadFactory("PersistentTtlNode")), + path, + ttlMs, + initData, + DEFAULT_CHILD_NODE_NAME, + DEFAULT_TOUCH_SCHEDULE_FACTOR, + useParentCreation); } /** @@ -103,9 +117,23 @@ public PersistentTtlNode(CuratorFramework client, String path, long ttlMs, byte[ * @param touchScheduleFactor how ofter to set/create the child node as a factor of the ttlMs. i.e. * the child is touched every (ttlMs / touchScheduleFactor) */ - public PersistentTtlNode(CuratorFramework client, ScheduledExecutorService executorService, String path, long ttlMs, byte[] initData, String childNodeName, int touchScheduleFactor) - { - this(client, executorService, path, ttlMs, initData, childNodeName, touchScheduleFactor, DEFAULT_USE_PARENT_CREATION); + public PersistentTtlNode( + CuratorFramework client, + ScheduledExecutorService executorService, + String path, + long ttlMs, + byte[] initData, + String childNodeName, + int touchScheduleFactor) { + this( + client, + executorService, + path, + ttlMs, + initData, + childNodeName, + touchScheduleFactor, + DEFAULT_USE_PARENT_CREATION); } /** @@ -119,16 +147,21 @@ public PersistentTtlNode(CuratorFramework client, ScheduledExecutorService execu * the child is touched every (ttlMs / touchScheduleFactor) * @param useParentCreation if true, parent ZNode can be created without ancestors */ - public PersistentTtlNode(CuratorFramework client, ScheduledExecutorService executorService, String path, long ttlMs, byte[] initData, String childNodeName, int touchScheduleFactor, boolean useParentCreation) - { + public PersistentTtlNode( + CuratorFramework client, + ScheduledExecutorService executorService, + String path, + long ttlMs, + byte[] initData, + String childNodeName, + int touchScheduleFactor, + boolean useParentCreation) { this.client = Objects.requireNonNull(client, "client cannot be null"); this.ttlMs = ttlMs; this.touchScheduleFactor = touchScheduleFactor; - node = new PersistentNode(client, CreateMode.CONTAINER, false, path, initData, useParentCreation) - { + node = new PersistentNode(client, CreateMode.CONTAINER, false, path, initData, useParentCreation) { @Override - protected void deleteNode() - { + protected void deleteNode() { // NOP } }; @@ -139,40 +172,33 @@ protected void deleteNode() /** * You must call start() to initiate the persistent ttl node */ - public void start() - { + public void start() { node.start(); - Runnable touchTask = new Runnable() - { + Runnable touchTask = new Runnable() { @Override - public void run() - { - try - { - try - { + public void run() { + try { + try { client.setData().forPath(childPath); + } catch (KeeperException.NoNodeException e) { + client.create() + .orSetData() + .withTtl(ttlMs) + .withMode(CreateMode.PERSISTENT_WITH_TTL) + .forPath(childPath); } - catch ( KeeperException.NoNodeException e ) - { - client.create().orSetData().withTtl(ttlMs).withMode(CreateMode.PERSISTENT_WITH_TTL).forPath(childPath); - } - } - catch ( KeeperException.NoNodeException ignore ) - { + } catch (KeeperException.NoNodeException ignore) { // ignore - } - catch ( Exception e ) - { - if ( !ThreadUtils.checkInterrupted(e) ) - { + } catch (Exception e) { + if (!ThreadUtils.checkInterrupted(e)) { log.debug("Could not touch child node", e); } } } }; - Future future = executorService.scheduleAtFixedRate(touchTask, ttlMs / touchScheduleFactor, ttlMs / touchScheduleFactor, TimeUnit.MILLISECONDS); + Future future = executorService.scheduleAtFixedRate( + touchTask, ttlMs / touchScheduleFactor, ttlMs / touchScheduleFactor, TimeUnit.MILLISECONDS); futureRef.set(future); } @@ -185,8 +211,7 @@ public void run() * @return if the node was created before timeout * @throws InterruptedException if the thread is interrupted */ - public boolean waitForInitialCreate(long timeout, TimeUnit unit) throws InterruptedException - { + public boolean waitForInitialCreate(long timeout, TimeUnit unit) throws InterruptedException { return node.waitForInitialCreate(timeout, unit); } @@ -199,8 +224,7 @@ public boolean waitForInitialCreate(long timeout, TimeUnit unit) throws Interrup * @param data new data value * @throws Exception errors */ - public void setData(byte[] data) throws Exception - { + public void setData(byte[] data) throws Exception { node.setData(data); } @@ -209,8 +233,7 @@ public void setData(byte[] data) throws Exception * * @return our data */ - public byte[] getData() - { + public byte[] getData() { return node.getData(); } @@ -220,19 +243,14 @@ public byte[] getData() * based on the ttl. */ @Override - public void close() - { + public void close() { Future future = futureRef.getAndSet(null); - if ( future != null ) - { + if (future != null) { future.cancel(true); } - try - { + try { node.close(); - } - catch ( IOException e ) - { + } catch (IOException e) { throw new RuntimeException(e); } } diff --git a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/queue/BlockingQueueConsumer.java b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/queue/BlockingQueueConsumer.java index fdba44e4a..900f403b7 100644 --- a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/queue/BlockingQueueConsumer.java +++ b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/queue/BlockingQueueConsumer.java @@ -20,30 +20,28 @@ package org.apache.curator.framework.recipes.queue; import com.google.common.collect.ImmutableList; -import org.apache.curator.framework.CuratorFramework; -import org.apache.curator.framework.state.ConnectionState; -import org.apache.curator.framework.state.ConnectionStateListener; import java.util.Collection; import java.util.List; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; +import org.apache.curator.framework.CuratorFramework; +import org.apache.curator.framework.state.ConnectionState; +import org.apache.curator.framework.state.ConnectionStateListener; /** * Utility - a queue consumer that provides behavior similar to a {@link BlockingQueue} */ -public class BlockingQueueConsumer implements QueueConsumer -{ - private final ConnectionStateListener connectionStateListener; - private final BlockingQueue items; +public class BlockingQueueConsumer implements QueueConsumer { + private final ConnectionStateListener connectionStateListener; + private final BlockingQueue items; /** * Creates with capacity of {@link Integer#MAX_VALUE} * @param connectionStateListener listener for connection state changes */ - public BlockingQueueConsumer(ConnectionStateListener connectionStateListener) - { + public BlockingQueueConsumer(ConnectionStateListener connectionStateListener) { this(connectionStateListener, new LinkedBlockingQueue()); } @@ -51,8 +49,7 @@ public BlockingQueueConsumer(ConnectionStateListener connectionStateListener) * @param capacity max capacity (i.e. puts block if full) * @param connectionStateListener listener for connection state changes */ - public BlockingQueueConsumer(ConnectionStateListener connectionStateListener, int capacity) - { + public BlockingQueueConsumer(ConnectionStateListener connectionStateListener, int capacity) { this(connectionStateListener, new ArrayBlockingQueue(capacity)); } @@ -62,15 +59,13 @@ public BlockingQueueConsumer(ConnectionStateListener connectionStateListener, in * @param queue queue to use * @param connectionStateListener listener for connection state changes */ - public BlockingQueueConsumer(ConnectionStateListener connectionStateListener, BlockingQueue queue) - { + public BlockingQueueConsumer(ConnectionStateListener connectionStateListener, BlockingQueue queue) { this.connectionStateListener = connectionStateListener; this.items = queue; } @Override - public void consumeMessage(T message) throws Exception - { + public void consumeMessage(T message) throws Exception { items.add(message); } @@ -79,8 +74,7 @@ public void consumeMessage(T message) throws Exception * * @return items (can be empty) */ - public List getItems() - { + public List getItems() { return ImmutableList.copyOf(items); } @@ -89,8 +83,7 @@ public List getItems() * * @return currently queue item count or 0 */ - public int size() - { + public int size() { return items.size(); } @@ -100,8 +93,7 @@ public int size() * @return the item * @throws InterruptedException thread interruption */ - public T take() throws InterruptedException - { + public T take() throws InterruptedException { return items.take(); } @@ -114,8 +106,7 @@ public T take() throws InterruptedException * @return next item or null * @throws InterruptedException thread interruption */ - public T take(int time, TimeUnit unit) throws InterruptedException - { + public T take(int time, TimeUnit unit) throws InterruptedException { return items.poll(time, unit); } @@ -142,14 +133,12 @@ public T take(int time, TimeUnit unit) throws InterruptedException * queue, or some property of an element of this queue prevents * it from being added to the specified collection */ - public int drainTo(Collection c) - { + public int drainTo(Collection c) { return items.drainTo(c); } @Override - public void stateChanged(CuratorFramework client, ConnectionState newState) - { + public void stateChanged(CuratorFramework client, ConnectionState newState) { connectionStateListener.stateChanged(client, newState); } } diff --git a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/queue/ChildrenCache.java b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/queue/ChildrenCache.java index 7e46370be..d9b4d35e1 100644 --- a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/queue/ChildrenCache.java +++ b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/queue/ChildrenCache.java @@ -21,6 +21,12 @@ import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; +import java.io.Closeable; +import java.io.IOException; +import java.util.List; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicReference; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.WatcherRemoveCuratorFramework; import org.apache.curator.framework.api.BackgroundCallback; @@ -31,39 +37,26 @@ import org.apache.curator.utils.PathUtils; import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.WatchedEvent; -import java.io.Closeable; -import java.io.IOException; -import java.util.List; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicReference; -class ChildrenCache implements Closeable -{ +class ChildrenCache implements Closeable { private final WatcherRemoveCuratorFramework client; private final String path; private final AtomicReference children = new AtomicReference(new Data(Lists.newArrayList(), 0)); private final AtomicBoolean isClosed = new AtomicBoolean(false); - private final CuratorWatcher watcher = new CuratorWatcher() - { + private final CuratorWatcher watcher = new CuratorWatcher() { @Override - public void process(WatchedEvent event) throws Exception - { - if ( !isClosed.get() ) - { + public void process(WatchedEvent event) throws Exception { + if (!isClosed.get()) { sync(); } } }; - private final BackgroundCallback callback = new BackgroundCallback() - { + private final BackgroundCallback callback = new BackgroundCallback() { @Override - public void processResult(CuratorFramework client, CuratorEvent event) throws Exception - { - if ( event.getResultCode() == KeeperException.Code.OK.intValue() ) - { + public void processResult(CuratorFramework client, CuratorEvent event) throws Exception { + if (event.getResultCode() == KeeperException.Code.OK.intValue()) { setNewChildren(event.getChildren()); } } @@ -71,99 +64,79 @@ public void processResult(CuratorFramework client, CuratorEvent event) throws Ex private final ConnectionStateListener connectionStateListener = (__, newState) -> { if ((newState == ConnectionState.CONNECTED) || (newState == ConnectionState.RECONNECTED)) { - try - { + try { sync(); - } - catch ( Exception e ) - { + } catch (Exception e) { throw new RuntimeException(e); } } }; - static class Data - { - final List children; - final long version; + static class Data { + final List children; + final long version; - private Data(List children, long version) - { + private Data(List children, long version) { this.children = ImmutableList.copyOf(children); this.version = version; } } - ChildrenCache(CuratorFramework client, String path) - { + ChildrenCache(CuratorFramework client, String path) { this.client = client.newWatcherRemoveCuratorFramework(); this.path = PathUtils.validatePath(path); } - void start() throws Exception - { + void start() throws Exception { client.getConnectionStateListenable().addListener(connectionStateListener); sync(); } @Override - public void close() throws IOException - { + public void close() throws IOException { client.removeWatchers(); client.getConnectionStateListenable().removeListener(connectionStateListener); isClosed.set(true); notifyFromCallback(); } - Data getData() - { + Data getData() { return children.get(); } - Data blockingNextGetData(long startVersion) throws InterruptedException - { + Data blockingNextGetData(long startVersion) throws InterruptedException { return blockingNextGetData(startVersion, 0, null); } - synchronized Data blockingNextGetData(long startVersion, long maxWait, TimeUnit unit) throws InterruptedException - { - long startMs = System.currentTimeMillis(); - boolean hasMaxWait = (unit != null); - long maxWaitMs = hasMaxWait ? unit.toMillis(maxWait) : -1; - while ( startVersion == children.get().version ) - { - if ( hasMaxWait ) - { - long elapsedMs = System.currentTimeMillis() - startMs; - long thisWaitMs = maxWaitMs - elapsedMs; - if ( thisWaitMs <= 0 ) - { + synchronized Data blockingNextGetData(long startVersion, long maxWait, TimeUnit unit) throws InterruptedException { + long startMs = System.currentTimeMillis(); + boolean hasMaxWait = (unit != null); + long maxWaitMs = hasMaxWait ? unit.toMillis(maxWait) : -1; + while (startVersion == children.get().version) { + if (hasMaxWait) { + long elapsedMs = System.currentTimeMillis() - startMs; + long thisWaitMs = maxWaitMs - elapsedMs; + if (thisWaitMs <= 0) { break; } wait(thisWaitMs); - } - else - { + } else { wait(); } } return children.get(); } - private synchronized void notifyFromCallback() - { + private synchronized void notifyFromCallback() { notifyAll(); } - private synchronized void sync() throws Exception - { + private synchronized void sync() throws Exception { client.getChildren().usingWatcher(watcher).inBackground(callback).forPath(path); } - private synchronized void setNewChildren(List newChildren) - { - if ( newChildren != null ) - { + private synchronized void setNewChildren(List newChildren) { + if (newChildren != null) { Data currentData = children.get(); children.set(new Data(newChildren, currentData.version + 1)); diff --git a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/queue/DistributedDelayQueue.java b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/queue/DistributedDelayQueue.java index 9c273c6d3..ac65ffd7a 100644 --- a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/queue/DistributedDelayQueue.java +++ b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/queue/DistributedDelayQueue.java @@ -21,8 +21,6 @@ import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; -import org.apache.curator.framework.CuratorFramework; -import org.apache.curator.framework.listen.Listenable; import java.io.Closeable; import java.io.IOException; import java.util.Collections; @@ -31,6 +29,8 @@ import java.util.concurrent.Executor; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; +import org.apache.curator.framework.CuratorFramework; +import org.apache.curator.framework.listen.Listenable; /** *

@@ -39,14 +39,12 @@ * until the time elapses. *

*/ -public class DistributedDelayQueue implements Closeable, QueueBase -{ - private final DistributedQueue queue; +public class DistributedDelayQueue implements Closeable, QueueBase { + private final DistributedQueue queue; - private static final char SEPARATOR = '|'; + private static final char SEPARATOR = '|'; - DistributedDelayQueue - ( + DistributedDelayQueue( CuratorFramework client, QueueConsumer consumer, QueueSerializer serializer, @@ -57,58 +55,45 @@ public class DistributedDelayQueue implements Closeable, QueueBase String lockPath, int maxItems, boolean putInBackground, - int finalFlushMs - ) - { + int finalFlushMs) { Preconditions.checkArgument(minItemsBeforeRefresh >= 0, "minItemsBeforeRefresh cannot be negative"); - queue = new DistributedQueue - ( - client, - consumer, - serializer, - queuePath, - threadFactory, - executor, - minItemsBeforeRefresh, - true, - lockPath, - maxItems, - putInBackground, - finalFlushMs - ) - { - @Override - protected long getDelay(String itemNode) - { - return getDelay(itemNode, System.currentTimeMillis()); - } - - private long getDelay(String itemNode, long sortTime) - { - long epoch = getEpoch(itemNode); - return epoch - sortTime; - } + queue = + new DistributedQueue( + client, + consumer, + serializer, + queuePath, + threadFactory, + executor, + minItemsBeforeRefresh, + true, + lockPath, + maxItems, + putInBackground, + finalFlushMs) { + @Override + protected long getDelay(String itemNode) { + return getDelay(itemNode, System.currentTimeMillis()); + } - @Override - protected void sortChildren(List children) - { - final long sortTime = System.currentTimeMillis(); - Collections.sort - ( - children, - new Comparator() - { - @Override - public int compare(String o1, String o2) - { - long diff = getDelay(o1, sortTime) - getDelay(o2, sortTime); - return (diff < 0) ? -1 : ((diff > 0) ? 1 : 0); - } + private long getDelay(String itemNode, long sortTime) { + long epoch = getEpoch(itemNode); + return epoch - sortTime; } - ); - } - }; + + @Override + protected void sortChildren(List children) { + final long sortTime = System.currentTimeMillis(); + Collections.sort(children, new Comparator() { + @Override + public int compare(String o1, String o2) { + long diff = getDelay(o1, sortTime) - getDelay(o2, sortTime); + return (diff < 0) ? -1 : ((diff > 0) ? 1 : 0); + } + }); + } + }; } /** @@ -117,14 +102,12 @@ public int compare(String o1, String o2) * @throws Exception startup errors */ @Override - public void start() throws Exception - { + public void start() throws Exception { queue.start(); } @Override - public void close() throws IOException - { + public void close() throws IOException { queue.close(); } @@ -138,8 +121,7 @@ public void close() throws IOException * @param delayUntilEpoch future epoch (milliseconds) when this item will be available to consumers * @throws Exception connection issues */ - public void put(T item, long delayUntilEpoch) throws Exception - { + public void put(T item, long delayUntilEpoch) throws Exception { put(item, delayUntilEpoch, 0, null); } @@ -154,8 +136,7 @@ public void put(T item, long delayUntilEpoch) throws Exception * @return true if items was added, false if timed out * @throws Exception */ - public boolean put(T item, long delayUntilEpoch, int maxWait, TimeUnit unit) throws Exception - { + public boolean put(T item, long delayUntilEpoch, int maxWait, TimeUnit unit) throws Exception { Preconditions.checkArgument(delayUntilEpoch > 0, "delayUntilEpoch cannot be negative"); queue.checkState(); @@ -173,8 +154,7 @@ public boolean put(T item, long delayUntilEpoch, int maxWait, TimeUnit unit * @param delayUntilEpoch future epoch (milliseconds) when this item will be available to consumers * @throws Exception connection issues */ - public void putMulti(MultiItem items, long delayUntilEpoch) throws Exception - { + public void putMulti(MultiItem items, long delayUntilEpoch) throws Exception { putMulti(items, delayUntilEpoch, 0, null); } @@ -189,8 +169,7 @@ public void putMulti(MultiItem items, long delayUntilEpoch) throws Except * @return true if items was added, false if timed out * @throws Exception */ - public boolean putMulti(MultiItem items, long delayUntilEpoch, int maxWait, TimeUnit unit) throws Exception - { + public boolean putMulti(MultiItem items, long delayUntilEpoch, int maxWait, TimeUnit unit) throws Exception { Preconditions.checkArgument(delayUntilEpoch > 0, "delayUntilEpoch cannot be negative"); queue.checkState(); @@ -199,14 +178,12 @@ public boolean putMulti(MultiItem items, long delayUntilEpoch, int maxWa } @Override - public void setErrorMode(ErrorMode newErrorMode) - { + public void setErrorMode(ErrorMode newErrorMode) { queue.setErrorMode(newErrorMode); } @Override - public boolean flushPuts(long waitTime, TimeUnit timeUnit) throws InterruptedException - { + public boolean flushPuts(long waitTime, TimeUnit timeUnit) throws InterruptedException { return queue.flushPuts(waitTime, timeUnit); } @@ -216,8 +193,7 @@ public boolean flushPuts(long waitTime, TimeUnit timeUnit) throws InterruptedExc * @return put listener container */ @Override - public Listenable> getPutListenerContainer() - { + public Listenable> getPutListenerContainer() { return queue.getPutListenerContainer(); } @@ -228,30 +204,23 @@ public Listenable> getPutListenerContainer() * @return count (can be 0) */ @Override - public int getLastMessageCount() - { + public int getLastMessageCount() { return queue.getLastMessageCount(); } @VisibleForTesting - static String epochToString(long epoch) - { + static String epochToString(long epoch) { return SEPARATOR + String.format("%08X", epoch) + SEPARATOR; } - private static long getEpoch(String itemNode) - { - int index2 = itemNode.lastIndexOf(SEPARATOR); - int index1 = (index2 > 0) ? itemNode.lastIndexOf(SEPARATOR, index2 - 1) : -1; - if ( (index1 > 0) && (index2 > (index1 + 1)) ) - { - try - { - String epochStr = itemNode.substring(index1 + 1, index2); + private static long getEpoch(String itemNode) { + int index2 = itemNode.lastIndexOf(SEPARATOR); + int index1 = (index2 > 0) ? itemNode.lastIndexOf(SEPARATOR, index2 - 1) : -1; + if ((index1 > 0) && (index2 > (index1 + 1))) { + try { + String epochStr = itemNode.substring(index1 + 1, index2); return Long.parseLong(epochStr, 16); - } - catch ( NumberFormatException ignore ) - { + } catch (NumberFormatException ignore) { // ignore } } diff --git a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/queue/DistributedIdQueue.java b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/queue/DistributedIdQueue.java index ecf743c06..03bab3bc1 100644 --- a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/queue/DistributedIdQueue.java +++ b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/queue/DistributedIdQueue.java @@ -21,10 +21,6 @@ import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; -import org.apache.curator.framework.CuratorFramework; -import org.apache.curator.framework.listen.Listenable; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.Collections; import java.util.Comparator; @@ -32,100 +28,101 @@ import java.util.concurrent.Executor; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; +import org.apache.curator.framework.CuratorFramework; +import org.apache.curator.framework.listen.Listenable; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * A version of {@link DistributedQueue} that allows IDs to be associated with queue items. Items * can then be removed from the queue if needed */ -public class DistributedIdQueue implements QueueBase -{ - private final Logger log = LoggerFactory.getLogger(getClass()); - private final DistributedQueue queue; +public class DistributedIdQueue implements QueueBase { + private final Logger log = LoggerFactory.getLogger(getClass()); + private final DistributedQueue queue; - private static final char SEPARATOR = '|'; + private static final char SEPARATOR = '|'; - private static class Parts - { - final String id; - final String cleaned; + private static class Parts { + final String id; + final String cleaned; - private Parts(String id, String cleaned) - { + private Parts(String id, String cleaned) { this.id = id; this.cleaned = cleaned; } } - DistributedIdQueue - ( - CuratorFramework client, - QueueConsumer consumer, QueueSerializer - serializer, String - queuePath, ThreadFactory - threadFactory, Executor - executor, - int minItemsBeforeRefresh, - boolean refreshOnWatch, - String lockPath, - int maxItems, - boolean putInBackground, - int finalFlushMs - ) - { - queue = new DistributedQueue(client, consumer, serializer, queuePath, threadFactory, executor, minItemsBeforeRefresh, refreshOnWatch, lockPath, maxItems, putInBackground, finalFlushMs) - { - @Override - protected void sortChildren(List children) - { - internalSortChildren(children); - } - - @Override - protected String makeRequeueItemPath(String itemPath) - { - return makeIdPath(parseId(itemPath).id); - } - }; - - if ( queue.makeItemPath().contains(Character.toString(SEPARATOR)) ) - { + DistributedIdQueue( + CuratorFramework client, + QueueConsumer consumer, + QueueSerializer serializer, + String queuePath, + ThreadFactory threadFactory, + Executor executor, + int minItemsBeforeRefresh, + boolean refreshOnWatch, + String lockPath, + int maxItems, + boolean putInBackground, + int finalFlushMs) { + queue = + new DistributedQueue( + client, + consumer, + serializer, + queuePath, + threadFactory, + executor, + minItemsBeforeRefresh, + refreshOnWatch, + lockPath, + maxItems, + putInBackground, + finalFlushMs) { + @Override + protected void sortChildren(List children) { + internalSortChildren(children); + } + + @Override + protected String makeRequeueItemPath(String itemPath) { + return makeIdPath(parseId(itemPath).id); + } + }; + + if (queue.makeItemPath().contains(Character.toString(SEPARATOR))) { throw new IllegalStateException("DistributedQueue can't use " + SEPARATOR); } } @Override - public void start() throws Exception - { + public void start() throws Exception { queue.start(); } @Override - public void close() throws IOException - { + public void close() throws IOException { queue.close(); } @Override - public Listenable> getPutListenerContainer() - { + public Listenable> getPutListenerContainer() { return queue.getPutListenerContainer(); } @Override - public void setErrorMode(ErrorMode newErrorMode) - { + public void setErrorMode(ErrorMode newErrorMode) { queue.setErrorMode(newErrorMode); } @Override - public boolean flushPuts(long waitTime, TimeUnit timeUnit) throws InterruptedException - { + public boolean flushPuts(long waitTime, TimeUnit timeUnit) throws InterruptedException { return queue.flushPuts(waitTime, timeUnit); } @Override - public int getLastMessageCount() - { + public int getLastMessageCount() { return queue.getLastMessageCount(); } @@ -138,8 +135,7 @@ public int getLastMessageCount() * @param itemId item Id * @throws Exception errors */ - public void put(T item, String itemId) throws Exception - { + public void put(T item, String itemId) throws Exception { put(item, itemId, 0, null); } @@ -154,8 +150,7 @@ public void put(T item, String itemId) throws Exception * @return true if items was added, false if timed out * @throws Exception */ - public boolean put(T item, String itemId, int maxWait, TimeUnit unit) throws Exception - { + public boolean put(T item, String itemId, int maxWait, TimeUnit unit) throws Exception { Preconditions.checkArgument(isValidId(itemId), "Invalid id: " + itemId); queue.checkState(); @@ -170,19 +165,15 @@ public boolean put(T item, String itemId, int maxWait, TimeUnit unit) throws Exc * @return number of items removed * @throws Exception errors */ - public int remove(String id) throws Exception - { + public int remove(String id) throws Exception { id = Preconditions.checkNotNull(id, "id cannot be null"); queue.checkState(); - int count = 0; - for ( String name : queue.getChildren() ) - { - if ( parseId(name).id.equals(id) ) - { - if ( queue.tryRemove(name) ) - { + int count = 0; + for (String name : queue.getChildren()) { + if (parseId(name).id.equals(id)) { + if (queue.tryRemove(name)) { ++count; } } @@ -192,12 +183,9 @@ public int remove(String id) throws Exception } @VisibleForTesting - boolean debugIsQueued(String id) throws Exception - { - for ( String name : queue.getChildren() ) - { - if ( parseId(name).id.equals(id) ) - { + boolean debugIsQueued(String id) throws Exception { + for (String name : queue.getChildren()) { + if (parseId(name).id.equals(id)) { return true; } } @@ -205,52 +193,38 @@ boolean debugIsQueued(String id) throws Exception return false; } - private String makeIdPath(String itemId) - { + private String makeIdPath(String itemId) { return queue.makeItemPath() + SEPARATOR + fixId(itemId) + SEPARATOR; } - private void internalSortChildren(List children) - { - Collections.sort - ( - children, - new Comparator() - { - @Override - public int compare(String o1, String o2) - { - return parseId(o1).cleaned.compareTo(parseId(o2).cleaned); - } + private void internalSortChildren(List children) { + Collections.sort(children, new Comparator() { + @Override + public int compare(String o1, String o2) { + return parseId(o1).cleaned.compareTo(parseId(o2).cleaned); } - ); + }); } - - private boolean isValidId(String id) - { + + private boolean isValidId(String id) { return (id != null) && (id.length() > 0); } - private static String fixId(String id) - { + private static String fixId(String id) { String fixed = id.replace('/', '_'); return fixed.replace(SEPARATOR, '_'); } - private Parts parseId(String name) - { - int firstIndex = name.indexOf(SEPARATOR); - int secondIndex = name.indexOf(SEPARATOR, firstIndex + 1); - if ( (firstIndex < 0) || (secondIndex < 0) ) - { + private Parts parseId(String name) { + int firstIndex = name.indexOf(SEPARATOR); + int secondIndex = name.indexOf(SEPARATOR, firstIndex + 1); + if ((firstIndex < 0) || (secondIndex < 0)) { log.error("Bad node in queue: " + name); return new Parts(name, name); } - return new Parts - ( - name.substring(firstIndex + 1, secondIndex), - name.substring(0, firstIndex) + name.substring(secondIndex + 1) - ); + return new Parts( + name.substring(firstIndex + 1, secondIndex), + name.substring(0, firstIndex) + name.substring(secondIndex + 1)); } } diff --git a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/queue/DistributedPriorityQueue.java b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/queue/DistributedPriorityQueue.java index 240351b6d..10ffaf9ea 100644 --- a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/queue/DistributedPriorityQueue.java +++ b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/queue/DistributedPriorityQueue.java @@ -21,13 +21,13 @@ import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; -import org.apache.curator.framework.CuratorFramework; -import org.apache.curator.framework.listen.Listenable; import java.io.Closeable; import java.io.IOException; import java.util.concurrent.Executor; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; +import org.apache.curator.framework.CuratorFramework; +import org.apache.curator.framework.listen.Listenable; /** *

An implementation of the Distributed Priority Queue ZK recipe.

@@ -36,12 +36,10 @@ *

IMPORTANT NOTE: The priority queue will perform far worse than a standard queue. Every time an * item is added to/removed from the queue, every watcher must re-get all the nodes

*/ -public class DistributedPriorityQueue implements Closeable, QueueBase -{ - private final DistributedQueue queue; +public class DistributedPriorityQueue implements Closeable, QueueBase { + private final DistributedQueue queue; - DistributedPriorityQueue - ( + DistributedPriorityQueue( CuratorFramework client, QueueConsumer consumer, QueueSerializer serializer, @@ -52,26 +50,22 @@ public class DistributedPriorityQueue implements Closeable, QueueBase String lockPath, int maxItems, boolean putInBackground, - int finalFlushMs - ) - { + int finalFlushMs) { Preconditions.checkArgument(minItemsBeforeRefresh >= 0, "minItemsBeforeRefresh cannot be negative"); - queue = new DistributedQueue - ( - client, - consumer, - serializer, - queuePath, - threadFactory, - executor, - minItemsBeforeRefresh, - true, - lockPath, - maxItems, - putInBackground, - finalFlushMs - ); + queue = new DistributedQueue( + client, + consumer, + serializer, + queuePath, + threadFactory, + executor, + minItemsBeforeRefresh, + true, + lockPath, + maxItems, + putInBackground, + finalFlushMs); } /** @@ -80,14 +74,12 @@ public class DistributedPriorityQueue implements Closeable, QueueBase * @throws Exception startup errors */ @Override - public void start() throws Exception - { + public void start() throws Exception { queue.start(); } @Override - public void close() throws IOException - { + public void close() throws IOException { queue.close(); } @@ -101,8 +93,7 @@ public void close() throws IOException * @param priority item's priority - lower numbers come out of the queue first * @throws Exception connection issues */ - public void put(T item, int priority) throws Exception - { + public void put(T item, int priority) throws Exception { put(item, priority, 0, null); } @@ -117,11 +108,10 @@ public void put(T item, int priority) throws Exception * @return true if items was added, false if timed out * @throws Exception */ - public boolean put(T item, int priority, int maxWait, TimeUnit unit) throws Exception - { + public boolean put(T item, int priority, int maxWait, TimeUnit unit) throws Exception { queue.checkState(); - String priorityHex = priorityToString(priority); + String priorityHex = priorityToString(priority); return queue.internalPut(item, null, queue.makeItemPath() + priorityHex, maxWait, unit); } @@ -135,8 +125,7 @@ public boolean put(T item, int priority, int maxWait, TimeUnit unit) throws * @param priority item priority - lower numbers come out of the queue first * @throws Exception connection issues */ - public void putMulti(MultiItem items, int priority) throws Exception - { + public void putMulti(MultiItem items, int priority) throws Exception { putMulti(items, priority, 0, null); } @@ -151,23 +140,20 @@ public void putMulti(MultiItem items, int priority) throws Exception * @return true if items was added, false if timed out * @throws Exception */ - public boolean putMulti(MultiItem items, int priority, int maxWait, TimeUnit unit) throws Exception - { + public boolean putMulti(MultiItem items, int priority, int maxWait, TimeUnit unit) throws Exception { queue.checkState(); - String priorityHex = priorityToString(priority); + String priorityHex = priorityToString(priority); return queue.internalPut(null, items, queue.makeItemPath() + priorityHex, maxWait, unit); } @Override - public void setErrorMode(ErrorMode newErrorMode) - { + public void setErrorMode(ErrorMode newErrorMode) { queue.setErrorMode(newErrorMode); } @Override - public boolean flushPuts(long waitTime, TimeUnit timeUnit) throws InterruptedException - { + public boolean flushPuts(long waitTime, TimeUnit timeUnit) throws InterruptedException { return queue.flushPuts(waitTime, timeUnit); } @@ -177,8 +163,7 @@ public boolean flushPuts(long waitTime, TimeUnit timeUnit) throws InterruptedExc * @return put listener container */ @Override - public Listenable> getPutListenerContainer() - { + public Listenable> getPutListenerContainer() { return queue.getPutListenerContainer(); } @@ -189,23 +174,20 @@ public Listenable> getPutListenerContainer() * @return count (can be 0) */ @Override - public int getLastMessageCount() - { + public int getLastMessageCount() { return queue.getLastMessageCount(); } @VisibleForTesting - ChildrenCache getCache() - { + ChildrenCache getCache() { return queue.getCache(); } @VisibleForTesting - static String priorityToString(int priority) - { + static String priorityToString(int priority) { // the padded hex val of the number prefixed with a 0 for negative numbers // and a 1 for positive (so that it sorts correctly) - long l = (long)priority & 0xFFFFFFFFL; + long l = (long) priority & 0xFFFFFFFFL; return String.format("%s%08X", (priority >= 0) ? "1" : "0", l); } } diff --git a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/queue/DistributedQueue.java b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/queue/DistributedQueue.java index f18a88d0b..60afbc3e9 100644 --- a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/queue/DistributedQueue.java +++ b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/queue/DistributedQueue.java @@ -22,6 +22,18 @@ import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; import com.google.common.collect.Lists; +import java.io.IOException; +import java.util.Collections; +import java.util.List; +import java.util.concurrent.Callable; +import java.util.concurrent.Executor; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Semaphore; +import java.util.concurrent.ThreadFactory; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.api.BackgroundCallback; import org.apache.curator.framework.api.CuratorEvent; @@ -39,18 +51,6 @@ import org.apache.zookeeper.data.Stat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.io.IOException; -import java.util.Collections; -import java.util.List; -import java.util.concurrent.Callable; -import java.util.concurrent.Executor; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.Semaphore; -import java.util.concurrent.ThreadFactory; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.concurrent.atomic.AtomicReference; /** *

An implementation of the Distributed Queue ZK recipe. Items put into the queue @@ -66,8 +66,7 @@ * a {@link QueueBuilder#lockPath(String)} * */ -public class DistributedQueue implements QueueBase -{ +public class DistributedQueue implements QueueBase { private final Logger log = LoggerFactory.getLogger(getClass()); private final CuratorFramework client; private final QueueSerializer serializer; @@ -81,33 +80,31 @@ public class DistributedQueue implements QueueBase private final boolean isProducerOnly; private final String lockPath; private final AtomicReference errorMode = new AtomicReference(ErrorMode.REQUEUE); - private final StandardListenerManager> putListenerContainer = StandardListenerManager.standard(); + private final StandardListenerManager> putListenerContainer = + StandardListenerManager.standard(); private final AtomicInteger lastChildCount = new AtomicInteger(0); private final int maxItems; private final int finalFlushMs; private final boolean putInBackground; private final ChildrenCache childrenCache; - private final AtomicInteger putCount = new AtomicInteger(0); + private final AtomicInteger putCount = new AtomicInteger(0); - private enum State - { + private enum State { LATENT, STARTED, STOPPED } @VisibleForTesting - protected enum ProcessType - { + protected enum ProcessType { NORMAL, REMOVE } - private static final String QUEUE_ITEM_NAME = "queue-"; + private static final String QUEUE_ITEM_NAME = "queue-"; - DistributedQueue - ( + DistributedQueue( CuratorFramework client, QueueConsumer consumer, QueueSerializer serializer, @@ -119,9 +116,7 @@ protected enum ProcessType String lockPath, int maxItems, boolean putInBackground, - int finalFlushMs - ) - { + int finalFlushMs) { Preconditions.checkNotNull(client, "client cannot be null"); Preconditions.checkNotNull(serializer, "serializer cannot be null"); Preconditions.checkNotNull(threadFactory, "threadFactory cannot be null"); @@ -143,9 +138,9 @@ protected enum ProcessType service = Executors.newFixedThreadPool(2, threadFactory); childrenCache = new ChildrenCache(client, queuePath); - if ( (maxItems != QueueBuilder.NOT_SET) && putInBackground ) - { - log.warn("Bounded queues should set putInBackground(false) in the builder. Putting in the background will result in spotty maxItem consistency."); + if ((maxItems != QueueBuilder.NOT_SET) && putInBackground) { + log.warn( + "Bounded queues should set putInBackground(false) in the builder. Putting in the background will result in spotty maxItem consistency."); } } @@ -155,68 +150,46 @@ protected enum ProcessType * @throws Exception startup errors */ @Override - public void start() throws Exception - { - if ( !state.compareAndSet(State.LATENT, State.STARTED) ) - { + public void start() throws Exception { + if (!state.compareAndSet(State.LATENT, State.STARTED)) { throw new IllegalStateException(); } - try - { + try { client.create().creatingParentContainersIfNeeded().forPath(queuePath); - } - catch ( KeeperException.NodeExistsException ignore ) - { + } catch (KeeperException.NodeExistsException ignore) { // this is OK } - if ( lockPath != null ) - { - try - { + if (lockPath != null) { + try { client.create().creatingParentContainersIfNeeded().forPath(lockPath); - } - catch ( KeeperException.NodeExistsException ignore ) - { + } catch (KeeperException.NodeExistsException ignore) { // this is OK } } - if ( !isProducerOnly || (maxItems != QueueBuilder.NOT_SET) ) - { + if (!isProducerOnly || (maxItems != QueueBuilder.NOT_SET)) { childrenCache.start(); } - if ( !isProducerOnly ) - { - service.submit - ( - new Callable() - { - @Override - public Object call() - { - runLoop(); - return null; - } - } - ); + if (!isProducerOnly) { + service.submit(new Callable() { + @Override + public Object call() { + runLoop(); + return null; + } + }); } } @Override - public void close() throws IOException - { - if ( state.compareAndSet(State.STARTED, State.STOPPED) ) - { - if ( finalFlushMs > 0 ) - { - try - { + public void close() throws IOException { + if (state.compareAndSet(State.STARTED, State.STOPPED)) { + if (finalFlushMs > 0) { + try { flushPuts(finalFlushMs, TimeUnit.MILLISECONDS); - } - catch ( InterruptedException e ) - { + } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } @@ -233,8 +206,7 @@ public void close() throws IOException * @return put listener container */ @Override - public Listenable> getPutListenerContainer() - { + public Listenable> getPutListenerContainer() { return putListenerContainer; } @@ -245,13 +217,12 @@ public Listenable> getPutListenerContainer() * @param newErrorMode the new error mode (the default is {@link ErrorMode#REQUEUE} */ @Override - public void setErrorMode(ErrorMode newErrorMode) - { + public void setErrorMode(ErrorMode newErrorMode) { Preconditions.checkNotNull(lockPath, "lockPath cannot be null"); - if ( newErrorMode == ErrorMode.REQUEUE ) - { - log.warn("ErrorMode.REQUEUE requires ZooKeeper version 3.4.x+ - make sure you are not using a prior version"); + if (newErrorMode == ErrorMode.REQUEUE) { + log.warn( + "ErrorMode.REQUEUE requires ZooKeeper version 3.4.x+ - make sure you are not using a prior version"); } errorMode.set(newErrorMode); @@ -266,23 +237,19 @@ public void setErrorMode(ErrorMode newErrorMode) * @throws InterruptedException if thread was interrupted */ @Override - public boolean flushPuts(long waitTime, TimeUnit timeUnit) throws InterruptedException - { - long msWaitRemaining = TimeUnit.MILLISECONDS.convert(waitTime, timeUnit); - synchronized(putCount) - { - while ( putCount.get() > 0 ) - { - if ( msWaitRemaining <= 0 ) - { + public boolean flushPuts(long waitTime, TimeUnit timeUnit) throws InterruptedException { + long msWaitRemaining = TimeUnit.MILLISECONDS.convert(waitTime, timeUnit); + synchronized (putCount) { + while (putCount.get() > 0) { + if (msWaitRemaining <= 0) { return false; } - long startMs = System.currentTimeMillis(); + long startMs = System.currentTimeMillis(); putCount.wait(msWaitRemaining); - long elapsedMs = System.currentTimeMillis() - startMs; + long elapsedMs = System.currentTimeMillis() - startMs; msWaitRemaining -= elapsedMs; } } @@ -298,8 +265,7 @@ public boolean flushPuts(long waitTime, TimeUnit timeUnit) throws InterruptedExc * @param item item to add * @throws Exception connection issues */ - public void put(T item) throws Exception - { + public void put(T item) throws Exception { put(item, 0, null); } @@ -313,11 +279,10 @@ public void put(T item) throws Exception * @return true if items was added, false if timed out * @throws Exception */ - public boolean put(T item, int maxWait, TimeUnit unit) throws Exception - { + public boolean put(T item, int maxWait, TimeUnit unit) throws Exception { checkState(); - String path = makeItemPath(); + String path = makeItemPath(); return internalPut(item, null, path, maxWait, unit); } @@ -330,8 +295,7 @@ public boolean put(T item, int maxWait, TimeUnit unit) throws Exception * @param items items to add * @throws Exception connection issues */ - public void putMulti(MultiItem items) throws Exception - { + public void putMulti(MultiItem items) throws Exception { putMulti(items, 0, null); } @@ -345,11 +309,10 @@ public void putMulti(MultiItem items) throws Exception * @return true if items was added, false if timed out * @throws Exception */ - public boolean putMulti(MultiItem items, int maxWait, TimeUnit unit) throws Exception - { + public boolean putMulti(MultiItem items, int maxWait, TimeUnit unit) throws Exception { checkState(); - String path = makeItemPath(); + String path = makeItemPath(); return internalPut(null, items, path, maxWait, unit); } @@ -360,93 +323,73 @@ public boolean putMulti(MultiItem items, int maxWait, TimeUnit unit) thro * @return count (can be 0) */ @Override - public int getLastMessageCount() - { + public int getLastMessageCount() { return lastChildCount.get(); } - boolean internalPut(final T item, MultiItem multiItem, String path, int maxWait, TimeUnit unit) throws Exception - { - if ( !blockIfMaxed(maxWait, unit) ) - { + boolean internalPut(final T item, MultiItem multiItem, String path, int maxWait, TimeUnit unit) + throws Exception { + if (!blockIfMaxed(maxWait, unit)) { return false; } final MultiItem givenMultiItem = multiItem; - if ( item != null ) - { - final AtomicReference ref = new AtomicReference(item); - multiItem = new MultiItem() - { + if (item != null) { + final AtomicReference ref = new AtomicReference(item); + multiItem = new MultiItem() { @Override - public T nextItem() throws Exception - { + public T nextItem() throws Exception { return ref.getAndSet(null); } }; } putCount.incrementAndGet(); - byte[] bytes = ItemSerializer.serialize(multiItem, serializer); - if ( putInBackground ) - { + byte[] bytes = ItemSerializer.serialize(multiItem, serializer); + if (putInBackground) { doPutInBackground(item, path, givenMultiItem, bytes); - } - else - { + } else { doPutInForeground(item, path, givenMultiItem, bytes); } return true; } - private void doPutInForeground(final T item, String path, final MultiItem givenMultiItem, byte[] bytes) throws Exception - { + private void doPutInForeground(final T item, String path, final MultiItem givenMultiItem, byte[] bytes) + throws Exception { client.create().withMode(CreateMode.PERSISTENT_SEQUENTIAL).forPath(path, bytes); - synchronized(putCount) - { + synchronized (putCount) { putCount.decrementAndGet(); putCount.notifyAll(); } putListenerContainer.forEach(listener -> { - if ( item != null ) - { + if (item != null) { listener.putCompleted(item); - } - else - { + } else { listener.putMultiCompleted(givenMultiItem); } }); } - private void doPutInBackground(final T item, String path, final MultiItem givenMultiItem, byte[] bytes) throws Exception - { - BackgroundCallback callback = new BackgroundCallback() - { + private void doPutInBackground(final T item, String path, final MultiItem givenMultiItem, byte[] bytes) + throws Exception { + BackgroundCallback callback = new BackgroundCallback() { @Override - public void processResult(CuratorFramework client, CuratorEvent event) throws Exception - { - if ( event.getResultCode() != KeeperException.Code.OK.intValue() ) - { + public void processResult(CuratorFramework client, CuratorEvent event) throws Exception { + if (event.getResultCode() != KeeperException.Code.OK.intValue()) { return; } - if ( event.getType() == CuratorEventType.CREATE ) - { - synchronized(putCount) - { + if (event.getType() == CuratorEventType.CREATE) { + synchronized (putCount) { putCount.decrementAndGet(); putCount.notifyAll(); } } putListenerContainer.forEach(listener -> { - if ( item != null ) - { + if (item != null) { listener.putCompleted(item); - } - else - { + } else { listener.putMultiCompleted(givenMultiItem); } }); @@ -456,225 +399,174 @@ public void processResult(CuratorFramework client, CuratorEvent event) throws Ex } @VisibleForTesting - void internalCreateNode(String path, byte[] bytes, BackgroundCallback callback) throws Exception - { - client.create().withMode(CreateMode.PERSISTENT_SEQUENTIAL).inBackground(callback).forPath(path, bytes); + void internalCreateNode(String path, byte[] bytes, BackgroundCallback callback) throws Exception { + client.create() + .withMode(CreateMode.PERSISTENT_SEQUENTIAL) + .inBackground(callback) + .forPath(path, bytes); } - void checkState() throws Exception - { - if ( state.get() != State.STARTED ) - { + void checkState() throws Exception { + if (state.get() != State.STARTED) { throw new IllegalStateException(); } } - String makeItemPath() - { + String makeItemPath() { return ZKPaths.makePath(queuePath, QUEUE_ITEM_NAME); } @VisibleForTesting - ChildrenCache getCache() - { + ChildrenCache getCache() { return childrenCache; } - protected void sortChildren(List children) - { + protected void sortChildren(List children) { Collections.sort(children); } - protected List getChildren() throws Exception - { + protected List getChildren() throws Exception { return client.getChildren().forPath(queuePath); } - protected long getDelay(String itemNode) - { + protected long getDelay(String itemNode) { return 0; } - protected boolean tryRemove(String itemNode) throws Exception - { - boolean isUsingLockSafety = (lockPath != null); - if ( isUsingLockSafety ) - { + protected boolean tryRemove(String itemNode) throws Exception { + boolean isUsingLockSafety = (lockPath != null); + if (isUsingLockSafety) { return processWithLockSafety(itemNode, ProcessType.REMOVE); } return processNormally(itemNode, ProcessType.REMOVE); } - private boolean blockIfMaxed(int maxWait, TimeUnit unit) throws Exception - { + private boolean blockIfMaxed(int maxWait, TimeUnit unit) throws Exception { ChildrenCache.Data data = childrenCache.getData(); - while ( data.children.size() >= maxItems ) - { - long previousVersion = data.version; + while (data.children.size() >= maxItems) { + long previousVersion = data.version; data = childrenCache.blockingNextGetData(data.version, maxWait, unit); - if ( data.version == previousVersion ) - { + if (data.version == previousVersion) { return false; } } return true; } - private void runLoop() - { - long currentVersion = -1; - long maxWaitMs = -1; - try - { - while ( state.get() == State.STARTED ) - { - try - { - ChildrenCache.Data data = (maxWaitMs > 0) ? childrenCache.blockingNextGetData(currentVersion, maxWaitMs, TimeUnit.MILLISECONDS) : childrenCache.blockingNextGetData(currentVersion); + private void runLoop() { + long currentVersion = -1; + long maxWaitMs = -1; + try { + while (state.get() == State.STARTED) { + try { + ChildrenCache.Data data = (maxWaitMs > 0) + ? childrenCache.blockingNextGetData(currentVersion, maxWaitMs, TimeUnit.MILLISECONDS) + : childrenCache.blockingNextGetData(currentVersion); currentVersion = data.version; - List children = Lists.newArrayList(data.children); + List children = Lists.newArrayList(data.children); sortChildren(children); // makes sure items are processed in the correct order - if ( children.size() > 0 ) - { + if (children.size() > 0) { maxWaitMs = getDelay(children.get(0)); - if ( maxWaitMs > 0 ) - { + if (maxWaitMs > 0) { continue; } - } - else - { + } else { continue; } processChildren(children, currentVersion); - } - catch ( InterruptedException e ) - { + } catch (InterruptedException e) { // swallow the interrupt as it's only possible from either a background // operation and, thus, doesn't apply to this loop or the instance // is being closed in which case the while test will get it } } - } - catch ( Exception e ) - { + } catch (Exception e) { log.error("Exception caught in background handler", e); } } - private void processChildren(List children, long currentVersion) throws Exception - { + private void processChildren(List children, long currentVersion) throws Exception { final Semaphore processedLatch = new Semaphore(0); - final boolean isUsingLockSafety = (lockPath != null); - int min = minItemsBeforeRefresh; - for ( final String itemNode : children ) - { - if ( Thread.currentThread().isInterrupted() ) - { + final boolean isUsingLockSafety = (lockPath != null); + int min = minItemsBeforeRefresh; + for (final String itemNode : children) { + if (Thread.currentThread().isInterrupted()) { processedLatch.release(children.size()); break; } - if ( !itemNode.startsWith(QUEUE_ITEM_NAME) ) - { + if (!itemNode.startsWith(QUEUE_ITEM_NAME)) { log.warn("Foreign node in queue path: " + itemNode); processedLatch.release(); continue; } - if ( min-- <= 0 ) - { - if ( refreshOnWatch && (currentVersion != childrenCache.getData().version) ) - { + if (min-- <= 0) { + if (refreshOnWatch && (currentVersion != childrenCache.getData().version)) { processedLatch.release(children.size()); break; } } - if ( getDelay(itemNode) > 0 ) - { + if (getDelay(itemNode) > 0) { processedLatch.release(); continue; } - executor.execute - ( - new Runnable() - { - @Override - public void run() - { - try - { - if ( isUsingLockSafety ) - { - processWithLockSafety(itemNode, ProcessType.NORMAL); - } - else - { - processNormally(itemNode, ProcessType.NORMAL); - } - } - catch ( Exception e ) - { - ThreadUtils.checkInterrupted(e); - log.error("Error processing message at " + itemNode, e); - } - finally - { - processedLatch.release(); + executor.execute(new Runnable() { + @Override + public void run() { + try { + if (isUsingLockSafety) { + processWithLockSafety(itemNode, ProcessType.NORMAL); + } else { + processNormally(itemNode, ProcessType.NORMAL); } + } catch (Exception e) { + ThreadUtils.checkInterrupted(e); + log.error("Error processing message at " + itemNode, e); + } finally { + processedLatch.release(); } } - ); + }); } processedLatch.acquire(children.size()); } - private enum ProcessMessageBytesCode - { + private enum ProcessMessageBytesCode { NORMAL, REQUEUE } - private ProcessMessageBytesCode processMessageBytes(String itemNode, byte[] bytes) throws Exception - { - ProcessMessageBytesCode resultCode = ProcessMessageBytesCode.NORMAL; - MultiItem items; - try - { + private ProcessMessageBytesCode processMessageBytes(String itemNode, byte[] bytes) throws Exception { + ProcessMessageBytesCode resultCode = ProcessMessageBytesCode.NORMAL; + MultiItem items; + try { items = ItemSerializer.deserialize(bytes, serializer); - } - catch ( Throwable e ) - { + } catch (Throwable e) { ThreadUtils.checkInterrupted(e); log.error("Corrupted queue item: " + itemNode, e); return resultCode; } - for(;;) - { - T item = items.nextItem(); - if ( item == null ) - { + for (; ; ) { + T item = items.nextItem(); + if (item == null) { break; } - try - { + try { consumer.consumeMessage(item); - } - catch ( Throwable e ) - { + } catch (Throwable e) { ThreadUtils.checkInterrupted(e); log.error("Exception processing queue item: " + itemNode, e); - if ( errorMode.get() == ErrorMode.REQUEUE ) - { + if (errorMode.get() == ErrorMode.REQUEUE) { resultCode = ProcessMessageBytesCode.REQUEUE; break; } @@ -683,40 +575,29 @@ private ProcessMessageBytesCode processMessageBytes(String itemNode, byte[] byte return resultCode; } - private boolean processNormally(String itemNode, ProcessType type) throws Exception - { - try - { - String itemPath = ZKPaths.makePath(queuePath, itemNode); - Stat stat = new Stat(); + private boolean processNormally(String itemNode, ProcessType type) throws Exception { + try { + String itemPath = ZKPaths.makePath(queuePath, itemNode); + Stat stat = new Stat(); - byte[] bytes = null; - if ( type == ProcessType.NORMAL ) - { + byte[] bytes = null; + if (type == ProcessType.NORMAL) { bytes = client.getData().storingStatIn(stat).forPath(itemPath); } - if ( client.getState() == CuratorFrameworkState.STARTED ) - { + if (client.getState() == CuratorFrameworkState.STARTED) { client.delete().withVersion(stat.getVersion()).forPath(itemPath); } - if ( type == ProcessType.NORMAL ) - { + if (type == ProcessType.NORMAL) { processMessageBytes(itemNode, bytes); } return true; - } - catch ( KeeperException.NodeExistsException ignore ) - { + } catch (KeeperException.NodeExistsException ignore) { // another process got it - } - catch ( KeeperException.NoNodeException ignore ) - { + } catch (KeeperException.NoNodeException ignore) { // another process got it - } - catch ( KeeperException.BadVersionException ignore ) - { + } catch (KeeperException.BadVersionException ignore) { // another process got it } @@ -724,56 +605,44 @@ private boolean processNormally(String itemNode, ProcessType type) throws Except } @VisibleForTesting - protected boolean processWithLockSafety(String itemNode, ProcessType type) throws Exception - { - String lockNodePath = ZKPaths.makePath(lockPath, itemNode); - boolean lockCreated = false; - try - { + protected boolean processWithLockSafety(String itemNode, ProcessType type) throws Exception { + String lockNodePath = ZKPaths.makePath(lockPath, itemNode); + boolean lockCreated = false; + try { client.create().withMode(CreateMode.EPHEMERAL).forPath(lockNodePath); lockCreated = true; - String itemPath = ZKPaths.makePath(queuePath, itemNode); + String itemPath = ZKPaths.makePath(queuePath, itemNode); boolean requeue = false; - byte[] bytes = null; - if ( type == ProcessType.NORMAL ) - { + byte[] bytes = null; + if (type == ProcessType.NORMAL) { bytes = client.getData().forPath(itemPath); requeue = (processMessageBytes(itemNode, bytes) == ProcessMessageBytesCode.REQUEUE); } - if ( requeue ) - { + if (requeue) { client.inTransaction() - .delete().forPath(itemPath) - .and() - .create().withMode(CreateMode.PERSISTENT_SEQUENTIAL).forPath(makeRequeueItemPath(itemPath), bytes) - .and() - .commit(); - } - else - { + .delete() + .forPath(itemPath) + .and() + .create() + .withMode(CreateMode.PERSISTENT_SEQUENTIAL) + .forPath(makeRequeueItemPath(itemPath), bytes) + .and() + .commit(); + } else { client.delete().forPath(itemPath); } return true; - } - catch ( KeeperException.NodeExistsException ignore ) - { + } catch (KeeperException.NodeExistsException ignore) { // another process got it - } - catch ( KeeperException.NoNodeException ignore ) - { + } catch (KeeperException.NoNodeException ignore) { // another process got it - } - catch ( KeeperException.BadVersionException ignore ) - { + } catch (KeeperException.BadVersionException ignore) { // another process got it - } - finally - { - if ( lockCreated ) - { + } finally { + if (lockCreated) { client.delete().guaranteed().forPath(lockNodePath); } } @@ -781,8 +650,7 @@ protected boolean processWithLockSafety(String itemNode, ProcessType type) throw return false; } - protected String makeRequeueItemPath(String itemPath) - { + protected String makeRequeueItemPath(String itemPath) { return makeItemPath(); } } diff --git a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/queue/ErrorMode.java b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/queue/ErrorMode.java index 9610baef4..f080da8bf 100644 --- a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/queue/ErrorMode.java +++ b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/queue/ErrorMode.java @@ -23,8 +23,7 @@ * Used when the queue is created with a {@link QueueBuilder#lockPath(String)}. Determines * the behavior when the queue consumer throws an exception */ -public enum ErrorMode -{ +public enum ErrorMode { /** * If the consumer throws an exception, requeue the message. This is the default. */ diff --git a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/queue/ItemSerializer.java b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/queue/ItemSerializer.java index 4b519cf29..82bfb7052 100644 --- a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/queue/ItemSerializer.java +++ b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/queue/ItemSerializer.java @@ -28,78 +28,64 @@ import java.util.Iterator; import java.util.List; -class ItemSerializer -{ - private static final int VERSION = 0x00010001; +class ItemSerializer { + private static final int VERSION = 0x00010001; - private static final byte ITEM_OPCODE = 0x01; - private static final byte EOF_OPCODE = 0x02; + private static final byte ITEM_OPCODE = 0x01; + private static final byte EOF_OPCODE = 0x02; - private static final int INITIAL_BUFFER_SIZE = 0x1000; + private static final int INITIAL_BUFFER_SIZE = 0x1000; - static MultiItem deserialize(byte[] bytes, QueueSerializer serializer) throws Exception - { - DataInputStream in = new DataInputStream(new ByteArrayInputStream(bytes)); - int version = in.readInt(); - if ( version != VERSION ) - { + static MultiItem deserialize(byte[] bytes, QueueSerializer serializer) throws Exception { + DataInputStream in = new DataInputStream(new ByteArrayInputStream(bytes)); + int version = in.readInt(); + if (version != VERSION) { throw new IOException(String.format("Incorrect version. Expected %d - Found: %d", VERSION, version)); } - List items = Lists.newArrayList(); - for(;;) - { - byte opcode = in.readByte(); - if ( opcode == EOF_OPCODE ) - { + List items = Lists.newArrayList(); + for (; ; ) { + byte opcode = in.readByte(); + if (opcode == EOF_OPCODE) { break; } - if ( opcode != ITEM_OPCODE ) - { + if (opcode != ITEM_OPCODE) { throw new IOException(String.format("Incorrect opcode. Expected %d - Found: %d", ITEM_OPCODE, opcode)); } - int size = in.readInt(); - if ( size < 0 ) - { + int size = in.readInt(); + if (size < 0) { throw new IOException(String.format("Bad size: %d", size)); } - byte[] itemBytes = new byte[size]; - if ( size > 0 ) - { + byte[] itemBytes = new byte[size]; + if (size > 0) { in.readFully(itemBytes); } items.add(serializer.deserialize(itemBytes)); } - final Iterator iterator = items.iterator(); - return new MultiItem() - { + final Iterator iterator = items.iterator(); + return new MultiItem() { @Override - public T nextItem() - { + public T nextItem() { return iterator.hasNext() ? iterator.next() : null; } }; } - static byte[] serialize(MultiItem items, QueueSerializer serializer) throws Exception - { - ByteArrayOutputStream bytes = new ByteArrayOutputStream(INITIAL_BUFFER_SIZE); - DataOutputStream out = new DataOutputStream(bytes); + static byte[] serialize(MultiItem items, QueueSerializer serializer) throws Exception { + ByteArrayOutputStream bytes = new ByteArrayOutputStream(INITIAL_BUFFER_SIZE); + DataOutputStream out = new DataOutputStream(bytes); out.writeInt(VERSION); - for(;;) - { - T item = items.nextItem(); - if ( item == null ) - { + for (; ; ) { + T item = items.nextItem(); + if (item == null) { break; } - byte[] itemBytes = serializer.serialize(item); + byte[] itemBytes = serializer.serialize(item); out.writeByte(ITEM_OPCODE); out.writeInt(itemBytes.length); - if ( itemBytes.length > 0 ) - { + if (itemBytes.length > 0) { out.write(itemBytes); } } @@ -109,7 +95,5 @@ static byte[] serialize(MultiItem items, QueueSerializer seriali return bytes.toByteArray(); } - private ItemSerializer() - { - } + private ItemSerializer() {} } diff --git a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/queue/MultiItem.java b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/queue/MultiItem.java index eb8433fe1..315902351 100644 --- a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/queue/MultiItem.java +++ b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/queue/MultiItem.java @@ -24,8 +24,7 @@ * @see DistributedQueue#putMulti(MultiItem) * @see DistributedPriorityQueue#putMulti(MultiItem, int) */ -public interface MultiItem -{ +public interface MultiItem { /** * Called repeatedly to get the items to add to the queue. This method * should return null when there are no more items to add. @@ -33,5 +32,5 @@ public interface MultiItem * @return item or null * @throws Exception any errors */ - public T nextItem() throws Exception; + public T nextItem() throws Exception; } diff --git a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/queue/QueueAllocator.java b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/queue/QueueAllocator.java index 60fc69bdd..dc766a582 100644 --- a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/queue/QueueAllocator.java +++ b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/queue/QueueAllocator.java @@ -21,7 +21,6 @@ import org.apache.curator.framework.CuratorFramework; -public interface QueueAllocator> -{ - public T allocateQueue(CuratorFramework client, String queuePath); +public interface QueueAllocator> { + public T allocateQueue(CuratorFramework client, String queuePath); } diff --git a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/queue/QueueBase.java b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/queue/QueueBase.java index 1a24c5a9c..4312280ea 100644 --- a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/queue/QueueBase.java +++ b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/queue/QueueBase.java @@ -19,18 +19,17 @@ package org.apache.curator.framework.recipes.queue; -import org.apache.curator.framework.listen.Listenable; import java.io.Closeable; import java.util.concurrent.TimeUnit; +import org.apache.curator.framework.listen.Listenable; -public interface QueueBase extends Closeable -{ +public interface QueueBase extends Closeable { /** * Start the queue. No other methods work until this is called * * @throws Exception startup errors */ - void start() throws Exception; + void start() throws Exception; /** * Return the manager for put listeners @@ -45,7 +44,7 @@ public interface QueueBase extends Closeable * * @param newErrorMode the new error mode (the default is {@link ErrorMode#REQUEUE} */ - void setErrorMode(ErrorMode newErrorMode); + void setErrorMode(ErrorMode newErrorMode); /** * Wait until any pending puts are committed diff --git a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/queue/QueueBuilder.java b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/queue/QueueBuilder.java index ba8043a35..ba934a436 100644 --- a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/queue/QueueBuilder.java +++ b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/queue/QueueBuilder.java @@ -21,19 +21,18 @@ import com.google.common.base.Preconditions; import com.google.common.util.concurrent.MoreExecutors; -import org.apache.curator.framework.CuratorFramework; -import org.apache.curator.utils.ThreadUtils; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; +import org.apache.curator.framework.CuratorFramework; import org.apache.curator.utils.PathUtils; +import org.apache.curator.utils.ThreadUtils; /** * The builder for both {@link DistributedQueue} and {@link DistributedPriorityQueue} */ -public class QueueBuilder -{ +public class QueueBuilder { private final CuratorFramework client; private final QueueConsumer consumer; private final QueueSerializer serializer; @@ -46,7 +45,7 @@ public class QueueBuilder private boolean putInBackground = true; private int finalFlushMs = 5000; - static final ThreadFactory defaultThreadFactory = ThreadUtils.newThreadFactory("QueueBuilder"); + static final ThreadFactory defaultThreadFactory = ThreadUtils.newThreadFactory("QueueBuilder"); static final int NOT_SET = Integer.MAX_VALUE; @@ -60,8 +59,8 @@ public class QueueBuilder * @param queuePath path to store queue * @return builder */ - public static QueueBuilder builder(CuratorFramework client, QueueConsumer consumer, QueueSerializer serializer, String queuePath) - { + public static QueueBuilder builder( + CuratorFramework client, QueueConsumer consumer, QueueSerializer serializer, String queuePath) { return new QueueBuilder(client, consumer, serializer, queuePath); } @@ -70,23 +69,20 @@ public static QueueBuilder builder(CuratorFramework client, QueueCo * * @return distributed queue */ - public DistributedQueue buildQueue() - { - return new DistributedQueue - ( - client, - consumer, - serializer, - queuePath, - factory, - executor, - Integer.MAX_VALUE, - false, - lockPath, - maxItems, - putInBackground, - finalFlushMs - ); + public DistributedQueue buildQueue() { + return new DistributedQueue( + client, + consumer, + serializer, + queuePath, + factory, + executor, + Integer.MAX_VALUE, + false, + lockPath, + maxItems, + putInBackground, + finalFlushMs); } /** @@ -94,23 +90,20 @@ public DistributedQueue buildQueue() * * @return distributed id queue */ - public DistributedIdQueue buildIdQueue() - { - return new DistributedIdQueue - ( - client, - consumer, - serializer, - queuePath, - factory, - executor, - Integer.MAX_VALUE, - false, - lockPath, - maxItems, - putInBackground, - finalFlushMs - ); + public DistributedIdQueue buildIdQueue() { + return new DistributedIdQueue( + client, + consumer, + serializer, + queuePath, + factory, + executor, + Integer.MAX_VALUE, + false, + lockPath, + maxItems, + putInBackground, + finalFlushMs); } /** @@ -132,22 +125,19 @@ public DistributedIdQueue buildIdQueue() * @param minItemsBeforeRefresh minimum items to process before refreshing the item list * @return distributed priority queue */ - public DistributedPriorityQueue buildPriorityQueue(int minItemsBeforeRefresh) - { - return new DistributedPriorityQueue - ( - client, - consumer, - serializer, - queuePath, - factory, - executor, - minItemsBeforeRefresh, - lockPath, - maxItems, - putInBackground, - finalFlushMs - ); + public DistributedPriorityQueue buildPriorityQueue(int minItemsBeforeRefresh) { + return new DistributedPriorityQueue( + client, + consumer, + serializer, + queuePath, + factory, + executor, + minItemsBeforeRefresh, + lockPath, + maxItems, + putInBackground, + finalFlushMs); } /** @@ -155,22 +145,19 @@ public DistributedPriorityQueue buildPriorityQueue(int minItemsBeforeRef * * @return distributed delay queue */ - public DistributedDelayQueue buildDelayQueue() - { - return new DistributedDelayQueue - ( - client, - consumer, - serializer, - queuePath, - factory, - executor, - Integer.MAX_VALUE, - lockPath, - maxItems, - putInBackground, - finalFlushMs - ); + public DistributedDelayQueue buildDelayQueue() { + return new DistributedDelayQueue( + client, + consumer, + serializer, + queuePath, + factory, + executor, + Integer.MAX_VALUE, + lockPath, + maxItems, + putInBackground, + finalFlushMs); } /** @@ -179,8 +166,7 @@ public DistributedDelayQueue buildDelayQueue() * @param factory new thread factory to use * @return this */ - public QueueBuilder threadFactory(ThreadFactory factory) - { + public QueueBuilder threadFactory(ThreadFactory factory) { Preconditions.checkNotNull(factory, "factory cannot be null"); this.factory = factory; @@ -193,8 +179,7 @@ public QueueBuilder threadFactory(ThreadFactory factory) * @param executor new executor to use * @return this */ - public QueueBuilder executor(Executor executor) - { + public QueueBuilder executor(Executor executor) { Preconditions.checkNotNull(executor, "executor cannot be null"); this.executor = executor; @@ -213,8 +198,7 @@ public QueueBuilder executor(Executor executor) * @param path path for the lock * @return this */ - public QueueBuilder lockPath(String path) - { + public QueueBuilder lockPath(String path) { lockPath = PathUtils.validatePath(path); return this; } @@ -229,8 +213,7 @@ public QueueBuilder lockPath(String path) * @param maxItems the upper bound for the queue * @return this */ - public QueueBuilder maxItems(int maxItems) - { + public QueueBuilder maxItems(int maxItems) { this.maxItems = maxItems; putInBackground = false; return this; @@ -242,8 +225,7 @@ public QueueBuilder maxItems(int maxItems) * @param putInBackground true to put in the background (default). false to put in the foreground. * @return this */ - public QueueBuilder putInBackground(boolean putInBackground) - { + public QueueBuilder putInBackground(boolean putInBackground) { this.putInBackground = putInBackground; return this; } @@ -256,14 +238,13 @@ public QueueBuilder putInBackground(boolean putInBackground) * @param unit the unit * @return this */ - public QueueBuilder finalFlushTime(int time, TimeUnit unit) - { - finalFlushMs = (int)unit.toMillis(time); + public QueueBuilder finalFlushTime(int time, TimeUnit unit) { + finalFlushMs = (int) unit.toMillis(time); return this; } - private QueueBuilder(CuratorFramework client, QueueConsumer consumer, QueueSerializer serializer, String queuePath) - { + private QueueBuilder( + CuratorFramework client, QueueConsumer consumer, QueueSerializer serializer, String queuePath) { this.client = client; this.consumer = consumer; this.serializer = serializer; diff --git a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/queue/QueueConsumer.java b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/queue/QueueConsumer.java index ad5d6c8df..1999b3b66 100644 --- a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/queue/QueueConsumer.java +++ b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/queue/QueueConsumer.java @@ -24,13 +24,12 @@ /** * Message Consumer */ -public interface QueueConsumer extends ConnectionStateListener -{ +public interface QueueConsumer extends ConnectionStateListener { /** * Process a message from the queue * * @param message message to process * @throws Exception any errors */ - public void consumeMessage(T message) throws Exception; + public void consumeMessage(T message) throws Exception; } diff --git a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/queue/QueuePutListener.java b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/queue/QueuePutListener.java index b8548698c..31d2d8e88 100644 --- a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/queue/QueuePutListener.java +++ b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/queue/QueuePutListener.java @@ -23,19 +23,18 @@ * Queue puts are done in the background. Use this listener to * be notified when the put completes */ -public interface QueuePutListener -{ +public interface QueuePutListener { /** * Notification that a single item put has completed * * @param item the item */ - public void putCompleted(T item); + public void putCompleted(T item); /** * Notification that a multi item put has completed * * @param items the items */ - public void putMultiCompleted(MultiItem items); + public void putMultiCompleted(MultiItem items); } diff --git a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/queue/QueueSafety.java b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/queue/QueueSafety.java index 350b80625..fd8128c50 100644 --- a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/queue/QueueSafety.java +++ b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/queue/QueueSafety.java @@ -26,8 +26,7 @@ * Parameter block for specifying queue safety with either {@link DistributedQueue} or * {@link DistributedPriorityQueue} */ -public class QueueSafety -{ +public class QueueSafety { private final String lockPath; private final QueueConsumer consumer; private final BlockingQueue queue; @@ -36,32 +35,27 @@ public class QueueSafety * @param lockPath ZKPath to use for locking purposes * @param consumer the message consumer */ - public QueueSafety(String lockPath, QueueConsumer consumer) - { + public QueueSafety(String lockPath, QueueConsumer consumer) { this.lockPath = PathUtils.validatePath(lockPath); this.consumer = consumer; this.queue = null; } - QueueSafety(String lockPath, BlockingQueue queue) - { + QueueSafety(String lockPath, BlockingQueue queue) { this.lockPath = PathUtils.validatePath(lockPath); this.consumer = null; this.queue = queue; } - String getLockPath() - { + String getLockPath() { return lockPath; } - QueueConsumer getConsumer() - { + QueueConsumer getConsumer() { return consumer; } - BlockingQueue getQueue() - { + BlockingQueue getQueue() { return queue; } } diff --git a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/queue/QueueSerializer.java b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/queue/QueueSerializer.java index ad65ddb5e..3f04db2f0 100644 --- a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/queue/QueueSerializer.java +++ b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/queue/QueueSerializer.java @@ -22,15 +22,14 @@ /** * Helper to serialize/deserialize queue items */ -public interface QueueSerializer -{ +public interface QueueSerializer { /** * Turn a queue item into bytes * * @param item the item * @return byte representation */ - public byte[] serialize(T item); + public byte[] serialize(T item); /** * Deserialize bytes into a queue item @@ -38,5 +37,5 @@ public interface QueueSerializer * @param bytes byte representation * @return item */ - public T deserialize(byte[] bytes); + public T deserialize(byte[] bytes); } diff --git a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/queue/QueueSharder.java b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/queue/QueueSharder.java index 47c77de92..47b073dbe 100644 --- a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/queue/QueueSharder.java +++ b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/queue/QueueSharder.java @@ -24,14 +24,6 @@ import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; -import org.apache.curator.utils.CloseableUtils; -import org.apache.curator.framework.CuratorFramework; -import org.apache.curator.framework.recipes.leader.LeaderLatch; -import org.apache.curator.utils.ThreadUtils; -import org.apache.curator.utils.ZKPaths; -import org.apache.zookeeper.data.Stat; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import java.io.Closeable; import java.io.IOException; import java.util.Collection; @@ -44,6 +36,14 @@ import java.util.concurrent.Executors; import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.atomic.AtomicReference; +import org.apache.curator.framework.CuratorFramework; +import org.apache.curator.framework.recipes.leader.LeaderLatch; +import org.apache.curator.utils.CloseableUtils; +import org.apache.curator.utils.ThreadUtils; +import org.apache.curator.utils.ZKPaths; +import org.apache.zookeeper.data.Stat; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** *

@@ -64,23 +64,21 @@ * queues. *

*/ -public class QueueSharder> implements Closeable -{ - private final Logger log = LoggerFactory.getLogger(getClass()); - private final CuratorFramework client; - private final QueueAllocator queueAllocator; - private final String queuePath; - private final QueueSharderPolicies policies; - private final ConcurrentMap queues = Maps.newConcurrentMap(); - private final Set preferredQueues = Sets.newSetFromMap(Maps.newConcurrentMap()); - private final AtomicReference state = new AtomicReference(State.LATENT); - private final LeaderLatch leaderLatch; - private final ExecutorService service; +public class QueueSharder> implements Closeable { + private final Logger log = LoggerFactory.getLogger(getClass()); + private final CuratorFramework client; + private final QueueAllocator queueAllocator; + private final String queuePath; + private final QueueSharderPolicies policies; + private final ConcurrentMap queues = Maps.newConcurrentMap(); + private final Set preferredQueues = Sets.newSetFromMap(Maps.newConcurrentMap()); + private final AtomicReference state = new AtomicReference(State.LATENT); + private final LeaderLatch leaderLatch; + private final ExecutorService service; - private static final String QUEUE_PREFIX = "queue-"; + private static final String QUEUE_PREFIX = "queue-"; - private enum State - { + private enum State { LATENT, STARTED, CLOSED @@ -93,8 +91,12 @@ private enum State * @param leaderPath path for the leader that monitors queue sizes (must be different than queuePath) * @param policies sharding policies */ - public QueueSharder(CuratorFramework client, QueueAllocator queueAllocator, String queuePath, String leaderPath, QueueSharderPolicies policies) - { + public QueueSharder( + CuratorFramework client, + QueueAllocator queueAllocator, + String queuePath, + String leaderPath, + QueueSharderPolicies policies) { this.client = client; this.queueAllocator = queueAllocator; this.queuePath = queuePath; @@ -108,8 +110,7 @@ public QueueSharder(CuratorFramework client, QueueAllocator queueAllocator * * @throws Exception errors */ - public void start() throws Exception - { + public void start() throws Exception { Preconditions.checkState(state.compareAndSet(State.LATENT, State.STARTED), "Cannot be started more than once"); client.createContainers(queuePath); @@ -117,49 +118,34 @@ public void start() throws Exception getInitialQueues(); leaderLatch.start(); - service.submit - ( - new Callable() - { - @Override - public Void call() throws Exception - { - while ( state.get() == State.STARTED ) - { - try - { - Thread.sleep(policies.getThresholdCheckMs()); - checkThreshold(); - } - catch ( InterruptedException e ) - { - // swallow the interrupt as it's only possible from either a background - // operation and, thus, doesn't apply to this loop or the instance - // is being closed in which case the while test will get it - } + service.submit(new Callable() { + @Override + public Void call() throws Exception { + while (state.get() == State.STARTED) { + try { + Thread.sleep(policies.getThresholdCheckMs()); + checkThreshold(); + } catch (InterruptedException e) { + // swallow the interrupt as it's only possible from either a background + // operation and, thus, doesn't apply to this loop or the instance + // is being closed in which case the while test will get it } - return null; } + return null; } - ); + }); } @Override - public void close() - { - if ( state.compareAndSet(State.STARTED, State.CLOSED) ) - { + public void close() { + if (state.compareAndSet(State.STARTED, State.CLOSED)) { service.shutdownNow(); CloseableUtils.closeQuietly(leaderLatch); - for ( T queue : queues.values() ) - { - try - { + for (T queue : queues.values()) { + try { queue.close(); - } - catch ( IOException e ) - { + } catch (IOException e) { log.error("Closing a queue", e); } } @@ -172,15 +158,12 @@ public void close() * * @return a queue */ - public T getQueue() - { + public T getQueue() { Preconditions.checkState(state.get() == State.STARTED, "Not started"); - List localPreferredQueues = Lists.newArrayList(preferredQueues); - if ( localPreferredQueues.size() > 0 ) - { - String key = localPreferredQueues.get( - ThreadLocalRandom.current().nextInt(localPreferredQueues.size())); + List localPreferredQueues = Lists.newArrayList(preferredQueues); + if (localPreferredQueues.size() > 0) { + String key = localPreferredQueues.get(ThreadLocalRandom.current().nextInt(localPreferredQueues.size())); return queues.get(key); } @@ -194,8 +177,7 @@ public T getQueue() * * @return qty */ - public int getShardQty() - { + public int getShardQty() { return queues.size(); } @@ -204,85 +186,70 @@ public int getShardQty() * * @return paths */ - public Collection getQueuePaths() - { + public Collection getQueuePaths() { return ImmutableSet.copyOf(queues.keySet()); } - private void getInitialQueues() throws Exception - { - List children = client.getChildren().forPath(queuePath); - for ( String child : children ) - { - String queuePath = ZKPaths.makePath(this.queuePath, child); + private void getInitialQueues() throws Exception { + List children = client.getChildren().forPath(queuePath); + for (String child : children) { + String queuePath = ZKPaths.makePath(this.queuePath, child); addNewQueueIfNeeded(queuePath); } - if ( children.size() == 0 ) - { + if (children.size() == 0) { addNewQueueIfNeeded(null); } } - private void addNewQueueIfNeeded(String newQueuePath) throws Exception - { - if ( newQueuePath == null ) - { - newQueuePath = ZKPaths.makePath(queuePath, QUEUE_PREFIX + UUID.randomUUID().toString()); + private void addNewQueueIfNeeded(String newQueuePath) throws Exception { + if (newQueuePath == null) { + newQueuePath = + ZKPaths.makePath(queuePath, QUEUE_PREFIX + UUID.randomUUID().toString()); } - if ( !queues.containsKey(newQueuePath) ) - { - T queue = queueAllocator.allocateQueue(client, newQueuePath); - if ( queues.putIfAbsent(newQueuePath, queue) == null ) - { + if (!queues.containsKey(newQueuePath)) { + T queue = queueAllocator.allocateQueue(client, newQueuePath); + if (queues.putIfAbsent(newQueuePath, queue) == null) { queue.start(); preferredQueues.add(newQueuePath); } } } - private void checkThreshold() - { - try - { - boolean addAQueueIfLeader = false; - int size = 0; - List children = client.getChildren().forPath(queuePath); - for ( String child : children ) - { - String queuePath = ZKPaths.makePath(this.queuePath, child); + private void checkThreshold() { + try { + boolean addAQueueIfLeader = false; + int size = 0; + List children = client.getChildren().forPath(queuePath); + for (String child : children) { + String queuePath = ZKPaths.makePath(this.queuePath, child); addNewQueueIfNeeded(queuePath); - Stat stat = client.checkExists().forPath(queuePath); - if ( stat.getNumChildren() >= policies.getNewQueueThreshold() ) - { + Stat stat = client.checkExists().forPath(queuePath); + if (stat.getNumChildren() >= policies.getNewQueueThreshold()) { size = stat.getNumChildren(); addAQueueIfLeader = true; preferredQueues.remove(queuePath); - } - else if ( stat.getNumChildren() <= (policies.getNewQueueThreshold() / 2) ) - { + } else if (stat.getNumChildren() <= (policies.getNewQueueThreshold() / 2)) { preferredQueues.add(queuePath); } } - if ( addAQueueIfLeader && leaderLatch.hasLeadership() ) - { - if ( queues.size() < policies.getMaxQueues() ) - { - log.info(String.format("Adding a queue due to exceeded threshold. Queue Size: %d - Threshold: %d", size, policies.getNewQueueThreshold())); + if (addAQueueIfLeader && leaderLatch.hasLeadership()) { + if (queues.size() < policies.getMaxQueues()) { + log.info(String.format( + "Adding a queue due to exceeded threshold. Queue Size: %d - Threshold: %d", + size, policies.getNewQueueThreshold())); addNewQueueIfNeeded(null); - } - else - { - log.warn(String.format("Max number of queues (%d) reached. Consider increasing the max.", policies.getMaxQueues())); + } else { + log.warn(String.format( + "Max number of queues (%d) reached. Consider increasing the max.", + policies.getMaxQueues())); } } - } - catch ( Exception e ) - { + } catch (Exception e) { ThreadUtils.checkInterrupted(e); log.error("Checking queue counts against threshold", e); } diff --git a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/queue/QueueSharderPolicies.java b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/queue/QueueSharderPolicies.java index db093d737..da60df8aa 100644 --- a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/queue/QueueSharderPolicies.java +++ b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/queue/QueueSharderPolicies.java @@ -26,20 +26,18 @@ * Various policies/options for sharding. Usage: * QueueSharderPolicies.builder().foo().bar().build(); */ -public class QueueSharderPolicies -{ - private int newQueueThreshold; - private int thresholdCheckMs; - private int maxQueues; +public class QueueSharderPolicies { + private int newQueueThreshold; + private int thresholdCheckMs; + private int maxQueues; private ThreadFactory threadFactory; - private static final int DEFAULT_QUEUE_THRESHOLD = 10000; - private static final int DEFAULT_THRESHOLD_CHECK_MS = 30000; - private static final int DEFAULT_MAX_QUEUES = 10; + private static final int DEFAULT_QUEUE_THRESHOLD = 10000; + private static final int DEFAULT_THRESHOLD_CHECK_MS = 30000; + private static final int DEFAULT_MAX_QUEUES = 10; - public static class Builder - { - private QueueSharderPolicies policies = new QueueSharderPolicies(); + public static class Builder { + private QueueSharderPolicies policies = new QueueSharderPolicies(); /** * Change the queue threshold. This is the number of items that causes @@ -48,8 +46,7 @@ public static class Builder * @param newQueueThreshold new value * @return this */ - public Builder newQueueThreshold(int newQueueThreshold) - { + public Builder newQueueThreshold(int newQueueThreshold) { Preconditions.checkArgument(newQueueThreshold > 0, "newQueueThreshold must be a positive number"); policies.newQueueThreshold = newQueueThreshold; @@ -63,8 +60,7 @@ public Builder newQueueThreshold(int newQueueThreshold) * @param thresholdCheckMs period in milliseconds * @return this */ - public Builder thresholdCheckMs(int thresholdCheckMs) - { + public Builder thresholdCheckMs(int thresholdCheckMs) { Preconditions.checkArgument(thresholdCheckMs > 0, "thresholdCheckMs must be a positive number"); policies.thresholdCheckMs = thresholdCheckMs; @@ -77,8 +73,7 @@ public Builder thresholdCheckMs(int thresholdCheckMs) * @param maxQueues the new max * @return this */ - public Builder maxQueues(int maxQueues) - { + public Builder maxQueues(int maxQueues) { Preconditions.checkArgument(maxQueues > 0, "thresholdCheckMs must be a positive number"); policies.maxQueues = maxQueues; @@ -91,27 +86,20 @@ public Builder maxQueues(int maxQueues) * @param threadFactory new factory * @return this */ - public Builder threadFactory(ThreadFactory threadFactory) - { + public Builder threadFactory(ThreadFactory threadFactory) { policies.threadFactory = Preconditions.checkNotNull(threadFactory, "threadFactory cannot be null"); return this; } - public QueueSharderPolicies build() - { - try - { + public QueueSharderPolicies build() { + try { return policies; - } - finally - { + } finally { policies = new QueueSharderPolicies(); } } - private Builder() - { - } + private Builder() {} } /** @@ -119,33 +107,27 @@ private Builder() * * @return builder */ - public static Builder builder() - { + public static Builder builder() { return new Builder(); } - int getNewQueueThreshold() - { + int getNewQueueThreshold() { return newQueueThreshold; } - int getThresholdCheckMs() - { + int getThresholdCheckMs() { return thresholdCheckMs; } - int getMaxQueues() - { + int getMaxQueues() { return maxQueues; } - ThreadFactory getThreadFactory() - { + ThreadFactory getThreadFactory() { return threadFactory; } - private QueueSharderPolicies() - { + private QueueSharderPolicies() { this.newQueueThreshold = DEFAULT_QUEUE_THRESHOLD; this.thresholdCheckMs = DEFAULT_THRESHOLD_CHECK_MS; this.maxQueues = DEFAULT_MAX_QUEUES; diff --git a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/queue/SimpleDistributedQueue.java b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/queue/SimpleDistributedQueue.java index 421b08c40..f472c388b 100644 --- a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/queue/SimpleDistributedQueue.java +++ b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/queue/SimpleDistributedQueue.java @@ -19,6 +19,11 @@ package org.apache.curator.framework.recipes.queue; +import java.util.Collections; +import java.util.List; +import java.util.NoSuchElementException; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.EnsureContainers; import org.apache.curator.utils.PathUtils; @@ -29,11 +34,6 @@ import org.apache.zookeeper.Watcher; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.util.Collections; -import java.util.List; -import java.util.NoSuchElementException; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; /** *

@@ -46,8 +46,7 @@ * it can read from an existing queue *

*/ -public class SimpleDistributedQueue -{ +public class SimpleDistributedQueue { private final Logger log = LoggerFactory.getLogger(getClass()); private final CuratorFramework client; private final String path; @@ -59,8 +58,7 @@ public class SimpleDistributedQueue * @param client the client * @param path path to store queue nodes */ - public SimpleDistributedQueue(CuratorFramework client, String path) - { + public SimpleDistributedQueue(CuratorFramework client, String path) { this.client = client; this.path = PathUtils.validatePath(path); ensureContainers = new EnsureContainers(client, path); @@ -73,11 +71,9 @@ public SimpleDistributedQueue(CuratorFramework client, String path) * @throws Exception errors * @throws NoSuchElementException if the queue is empty */ - public byte[] element() throws Exception - { + public byte[] element() throws Exception { byte[] bytes = internalElement(false, null); - if ( bytes == null ) - { + if (bytes == null) { throw new NoSuchElementException(); } return bytes; @@ -90,11 +86,9 @@ public byte[] element() throws Exception * @throws Exception errors * @throws NoSuchElementException if the queue is empty */ - public byte[] remove() throws Exception - { + public byte[] remove() throws Exception { byte[] bytes = internalElement(true, null); - if ( bytes == null ) - { + if (bytes == null) { throw new NoSuchElementException(); } return bytes; @@ -106,8 +100,7 @@ public byte[] remove() throws Exception * @return The former head of the queue * @throws Exception errors */ - public byte[] take() throws Exception - { + public byte[] take() throws Exception { return internalPoll(0, null); } @@ -118,10 +111,12 @@ public byte[] take() throws Exception * @return true if data was successfully added * @throws Exception errors */ - public boolean offer(byte[] data) throws Exception - { + public boolean offer(byte[] data) throws Exception { String thisPath = ZKPaths.makePath(path, PREFIX); - client.create().creatingParentContainersIfNeeded().withMode(CreateMode.PERSISTENT_SEQUENTIAL).forPath(thisPath, data); + client.create() + .creatingParentContainersIfNeeded() + .withMode(CreateMode.PERSISTENT_SEQUENTIAL) + .forPath(thisPath, data); return true; } @@ -131,14 +126,10 @@ public boolean offer(byte[] data) throws Exception * @return data at the first element of the queue, or null. * @throws Exception errors */ - public byte[] peek() throws Exception - { - try - { + public byte[] peek() throws Exception { + try { return element(); - } - catch ( NoSuchElementException e ) - { + } catch (NoSuchElementException e) { return null; } } @@ -155,8 +146,7 @@ public byte[] peek() throws Exception * specified waiting time elapses before an element is available * @throws Exception errors */ - public byte[] poll(long timeout, TimeUnit unit) throws Exception - { + public byte[] poll(long timeout, TimeUnit unit) throws Exception { return internalPoll(timeout, unit); } @@ -166,110 +156,85 @@ public byte[] poll(long timeout, TimeUnit unit) throws Exception * @return Head of the queue or null. * @throws Exception errors */ - public byte[] poll() throws Exception - { - try - { + public byte[] poll() throws Exception { + try { return remove(); - } - catch ( NoSuchElementException e ) - { + } catch (NoSuchElementException e) { return null; } } - protected void ensurePath() throws Exception - { + protected void ensurePath() throws Exception { ensureContainers.ensure(); } - private byte[] internalPoll(long timeout, TimeUnit unit) throws Exception - { + private byte[] internalPoll(long timeout, TimeUnit unit) throws Exception { ensurePath(); - long startMs = System.currentTimeMillis(); - boolean hasTimeout = (unit != null); - long maxWaitMs = hasTimeout ? TimeUnit.MILLISECONDS.convert(timeout, unit) : Long.MAX_VALUE; - for(;;) - { - final CountDownLatch latch = new CountDownLatch(1); - Watcher watcher = new Watcher() - { + long startMs = System.currentTimeMillis(); + boolean hasTimeout = (unit != null); + long maxWaitMs = hasTimeout ? TimeUnit.MILLISECONDS.convert(timeout, unit) : Long.MAX_VALUE; + for (; ; ) { + final CountDownLatch latch = new CountDownLatch(1); + Watcher watcher = new Watcher() { @Override - public void process(WatchedEvent event) - { + public void process(WatchedEvent event) { latch.countDown(); } }; - byte[] bytes; - try - { + byte[] bytes; + try { bytes = internalElement(true, watcher); - } - catch ( NoSuchElementException dummy ) - { + } catch (NoSuchElementException dummy) { log.debug("Parent containers appear to have lapsed - recreate and retry"); ensureContainers.reset(); continue; } - if ( bytes != null ) - { + if (bytes != null) { return bytes; } - if ( hasTimeout ) - { - long elapsedMs = System.currentTimeMillis() - startMs; - long thisWaitMs = maxWaitMs - elapsedMs; - if ( thisWaitMs <= 0 ) - { + if (hasTimeout) { + long elapsedMs = System.currentTimeMillis() - startMs; + long thisWaitMs = maxWaitMs - elapsedMs; + if (thisWaitMs <= 0) { return null; } latch.await(thisWaitMs, TimeUnit.MILLISECONDS); - } - else - { + } else { latch.await(); } } } - private byte[] internalElement(boolean removeIt, Watcher watcher) throws Exception - { + private byte[] internalElement(boolean removeIt, Watcher watcher) throws Exception { ensurePath(); List nodes; - try - { - nodes = (watcher != null) ? client.getChildren().usingWatcher(watcher).forPath(path) : client.getChildren().forPath(path); - } - catch ( KeeperException.NoNodeException dummy ) - { + try { + nodes = (watcher != null) + ? client.getChildren().usingWatcher(watcher).forPath(path) + : client.getChildren().forPath(path); + } catch (KeeperException.NoNodeException dummy) { throw new NoSuchElementException(); } Collections.sort(nodes); - for ( String node : nodes ) - { - if ( !node.startsWith(PREFIX) ) - { + for (String node : nodes) { + if (!node.startsWith(PREFIX)) { log.warn("Foreign node in queue path: " + node); continue; } - String thisPath = ZKPaths.makePath(path, node); - try - { + String thisPath = ZKPaths.makePath(path, node); + try { byte[] bytes = client.getData().forPath(thisPath); - if ( removeIt ) - { + if (removeIt) { client.delete().forPath(thisPath); } return bytes; - } - catch ( KeeperException.NoNodeException ignore ) - { - //Another client removed the node first, try next + } catch (KeeperException.NoNodeException ignore) { + // Another client removed the node first, try next } } diff --git a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/shared/SharedCount.java b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/shared/SharedCount.java index 5dcf63af4..c401a3b05 100644 --- a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/shared/SharedCount.java +++ b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/shared/SharedCount.java @@ -22,48 +22,43 @@ import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.Maps; import com.google.common.util.concurrent.MoreExecutors; -import org.apache.curator.framework.CuratorFramework; -import org.apache.curator.framework.listen.Listenable; -import org.apache.curator.framework.state.ConnectionState; import java.io.Closeable; import java.io.IOException; import java.nio.ByteBuffer; import java.util.Map; import java.util.concurrent.Executor; +import org.apache.curator.framework.CuratorFramework; +import org.apache.curator.framework.listen.Listenable; +import org.apache.curator.framework.state.ConnectionState; /** * Manages a shared integer. All clients watching the same path will have the up-to-date * value of the shared integer (considering ZK's normal consistency guarantees). */ -public class SharedCount implements Closeable, SharedCountReader, Listenable -{ +public class SharedCount implements Closeable, SharedCountReader, Listenable { private final Map listeners = Maps.newConcurrentMap(); - private final SharedValue sharedValue; + private final SharedValue sharedValue; /** * @param client the client * @param path the shared path - i.e. where the shared count is stored * @param seedValue the initial value for the count if/f the path has not yet been created */ - public SharedCount(CuratorFramework client, String path, int seedValue) - { + public SharedCount(CuratorFramework client, String path, int seedValue) { sharedValue = new SharedValue(client, path, toBytes(seedValue)); } - protected SharedCount(CuratorFramework client, String path, SharedValue sv) - { + protected SharedCount(CuratorFramework client, String path, SharedValue sv) { sharedValue = sv; } @Override - public int getCount() - { + public int getCount() { return fromBytes(sharedValue.getValue()); } @Override - public VersionedValue getVersionedValue() - { + public VersionedValue getVersionedValue() { VersionedValue localValue = sharedValue.getVersionedValue(); return new VersionedValue(localValue.getVersion(), fromBytes(localValue.getValue())); } @@ -74,8 +69,7 @@ public VersionedValue getVersionedValue() * @param newCount new value * @throws Exception ZK errors, interruptions, etc. */ - public void setCount(int newCount) throws Exception - { + public void setCount(int newCount) throws Exception { sharedValue.setValue(toBytes(newCount)); } @@ -95,8 +89,7 @@ public void setCount(int newCount) throws Exception * @throws Exception ZK errors, interruptions, etc. */ @Deprecated - public boolean trySetCount(int newCount) throws Exception - { + public boolean trySetCount(int newCount) throws Exception { return sharedValue.trySetValue(toBytes(newCount)); } @@ -111,32 +104,27 @@ public boolean trySetCount(int newCount) throws Exception * was not successful, {@link #getCount()} will return the updated value * @throws Exception ZK errors, interruptions, etc. */ - public boolean trySetCount(VersionedValue previous, int newCount) throws Exception - { - VersionedValue previousCopy = new VersionedValue(previous.getVersion(), toBytes(previous.getValue())); + public boolean trySetCount(VersionedValue previous, int newCount) throws Exception { + VersionedValue previousCopy = + new VersionedValue(previous.getVersion(), toBytes(previous.getValue())); return sharedValue.trySetValue(previousCopy, toBytes(newCount)); } @Override - public void addListener(SharedCountListener listener) - { + public void addListener(SharedCountListener listener) { addListener(listener, MoreExecutors.directExecutor()); } @Override - public void addListener(final SharedCountListener listener, Executor executor) - { - SharedValueListener valueListener = new SharedValueListener() - { + public void addListener(final SharedCountListener listener, Executor executor) { + SharedValueListener valueListener = new SharedValueListener() { @Override - public void valueHasChanged(SharedValueReader sharedValue, byte[] newValue) throws Exception - { + public void valueHasChanged(SharedValueReader sharedValue, byte[] newValue) throws Exception { listener.countHasChanged(SharedCount.this, fromBytes(newValue)); } @Override - public void stateChanged(CuratorFramework client, ConnectionState newState) - { + public void stateChanged(CuratorFramework client, ConnectionState newState) { listener.stateChanged(client, newState); } }; @@ -145,10 +133,9 @@ public void stateChanged(CuratorFramework client, ConnectionState newState) } @Override - public void removeListener(SharedCountListener listener) - { + public void removeListener(SharedCountListener listener) { SharedValueListener valueListener = listeners.remove(listener); - if(valueListener != null) { + if (valueListener != null) { sharedValue.getListenable().removeListener(valueListener); } } @@ -159,27 +146,23 @@ public void removeListener(SharedCountListener listener) * * @throws Exception ZK errors, interruptions, etc. */ - public void start() throws Exception - { + public void start() throws Exception { sharedValue.start(); } @Override - public void close() throws IOException - { + public void close() throws IOException { sharedValue.close(); } @VisibleForTesting - static byte[] toBytes(int value) - { - byte[] bytes = new byte[4]; + static byte[] toBytes(int value) { + byte[] bytes = new byte[4]; ByteBuffer.wrap(bytes).putInt(value); return bytes; } - private static int fromBytes(byte[] bytes) - { + private static int fromBytes(byte[] bytes) { return ByteBuffer.wrap(bytes).getInt(); } } diff --git a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/shared/SharedCountListener.java b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/shared/SharedCountListener.java index 950f5beb0..059ff1ea2 100644 --- a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/shared/SharedCountListener.java +++ b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/shared/SharedCountListener.java @@ -24,8 +24,7 @@ /** * Listener for changes to a shared count */ -public interface SharedCountListener extends ConnectionStateListener -{ +public interface SharedCountListener extends ConnectionStateListener { /** * Called when the shared value has changed * @@ -33,5 +32,5 @@ public interface SharedCountListener extends ConnectionStateListener * @param newCount the new count * @throws Exception errors */ - public void countHasChanged(SharedCountReader sharedCount, int newCount) throws Exception; + public void countHasChanged(SharedCountReader sharedCount, int newCount) throws Exception; } diff --git a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/shared/SharedCountReader.java b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/shared/SharedCountReader.java index d87babd46..35c8e26c7 100644 --- a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/shared/SharedCountReader.java +++ b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/shared/SharedCountReader.java @@ -24,14 +24,13 @@ /** * Abstracts a shared integer and allows listening for changes to its value */ -public interface SharedCountReader extends Listenable -{ +public interface SharedCountReader extends Listenable { /** * Return the current value of the count * * @return count */ - public int getCount(); + public int getCount(); /** * Return the current count and version diff --git a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/shared/SharedValue.java b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/shared/SharedValue.java index d5f971fbb..50e50edd0 100644 --- a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/shared/SharedValue.java +++ b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/shared/SharedValue.java @@ -21,6 +21,10 @@ import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; +import java.io.Closeable; +import java.io.IOException; +import java.util.Arrays; +import java.util.concurrent.atomic.AtomicReference; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.WatcherRemoveCuratorFramework; import org.apache.curator.framework.api.BackgroundCallback; @@ -38,18 +42,13 @@ import org.apache.zookeeper.data.Stat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.io.Closeable; -import java.io.IOException; -import java.util.Arrays; -import java.util.concurrent.atomic.AtomicReference; /** * Manages a shared value. All clients watching the same path will have the up-to-date * value (considering ZK's normal consistency guarantees). */ -public class SharedValue implements Closeable, SharedValueReader -{ - private static final int UNINITIALIZED_VERSION = -1; +public class SharedValue implements Closeable, SharedValueReader { + private static final int UNINITIALIZED_VERSION = -1; private final Logger log = LoggerFactory.getLogger(getClass()); private final StandardListenerManager listeners = StandardListenerManager.standard(); @@ -60,33 +59,25 @@ public class SharedValue implements Closeable, SharedValueReader private final AtomicReference> currentValue; private final CuratorWatcher watcher; - private class SharedValueCuratorWatcher implements CuratorWatcher - { + private class SharedValueCuratorWatcher implements CuratorWatcher { @Override - public void process(WatchedEvent event) throws Exception - { - if ( state.get() == State.STARTED && event.getType() != Watcher.Event.EventType.None ) - { + public void process(WatchedEvent event) throws Exception { + if (state.get() == State.STARTED && event.getType() != Watcher.Event.EventType.None) { // don't block event thread in possible retry readValueAndNotifyListenersInBackground(); } } - }; + } + ; - private final ConnectionStateListener connectionStateListener = new ConnectionStateListener() - { + private final ConnectionStateListener connectionStateListener = new ConnectionStateListener() { @Override - public void stateChanged(CuratorFramework client, ConnectionState newState) - { + public void stateChanged(CuratorFramework client, ConnectionState newState) { notifyListenerOfStateChanged(newState); - if ( newState.isConnected() ) - { - try - { + if (newState.isConnected()) { + try { readValueAndNotifyListenersInBackground(); - } - catch ( Exception e ) - { + } catch (Exception e) { ThreadUtils.checkInterrupted(e); log.error("Could not read value after reconnect", e); } @@ -94,8 +85,7 @@ public void stateChanged(CuratorFramework client, ConnectionState newState) } }; - private enum State - { + private enum State { LATENT, STARTED, CLOSED @@ -106,38 +96,37 @@ private enum State * @param path the shared path - i.e. where the shared value is stored * @param seedValue the initial value for the value if/f the path has not yet been created */ - public SharedValue(CuratorFramework client, String path, byte[] seedValue) - { + public SharedValue(CuratorFramework client, String path, byte[] seedValue) { this.client = client.newWatcherRemoveCuratorFramework(); this.path = PathUtils.validatePath(path); this.seedValue = Arrays.copyOf(seedValue, seedValue.length); this.watcher = new SharedValueCuratorWatcher(); - currentValue = new AtomicReference>(new VersionedValue(UNINITIALIZED_VERSION, Arrays.copyOf(seedValue, seedValue.length))); + currentValue = new AtomicReference>( + new VersionedValue(UNINITIALIZED_VERSION, Arrays.copyOf(seedValue, seedValue.length))); } @VisibleForTesting - protected SharedValue(WatcherRemoveCuratorFramework client, String path, byte[] seedValue, CuratorWatcher watcher) - { + protected SharedValue(WatcherRemoveCuratorFramework client, String path, byte[] seedValue, CuratorWatcher watcher) { this.client = client; this.path = PathUtils.validatePath(path); this.seedValue = Arrays.copyOf(seedValue, seedValue.length); // inject watcher for testing this.watcher = watcher; - currentValue = new AtomicReference>(new VersionedValue(UNINITIALIZED_VERSION, Arrays.copyOf(seedValue, seedValue.length))); + currentValue = new AtomicReference>( + new VersionedValue(UNINITIALIZED_VERSION, Arrays.copyOf(seedValue, seedValue.length))); } @Override - public byte[] getValue() - { + public byte[] getValue() { VersionedValue localCopy = currentValue.get(); return Arrays.copyOf(localCopy.getValue(), localCopy.getValue().length); } @Override - public VersionedValue getVersionedValue() - { + public VersionedValue getVersionedValue() { VersionedValue localCopy = currentValue.get(); - return new VersionedValue(localCopy.getVersion(), Arrays.copyOf(localCopy.getValue(), localCopy.getValue().length)); + return new VersionedValue( + localCopy.getVersion(), Arrays.copyOf(localCopy.getValue(), localCopy.getValue().length)); } /** @@ -146,8 +135,7 @@ public VersionedValue getVersionedValue() * @param newValue new value * @throws Exception ZK errors, interruptions, etc. */ - public void setValue(byte[] newValue) throws Exception - { + public void setValue(byte[] newValue) throws Exception { Preconditions.checkState(state.get() == State.STARTED, "not started"); Stat result = client.setData().forPath(path, newValue); @@ -170,8 +158,7 @@ public void setValue(byte[] newValue) throws Exception * @throws Exception ZK errors, interruptions, etc. */ @Deprecated - public boolean trySetValue(byte[] newValue) throws Exception - { + public boolean trySetValue(byte[] newValue) throws Exception { return trySetValue(currentValue.get(), newValue); } @@ -186,24 +173,19 @@ public boolean trySetValue(byte[] newValue) throws Exception * was not successful, {@link #getValue()} will return the updated value * @throws Exception ZK errors, interruptions, etc. */ - public boolean trySetValue(VersionedValue previous, byte[] newValue) throws Exception - { + public boolean trySetValue(VersionedValue previous, byte[] newValue) throws Exception { Preconditions.checkState(state.get() == State.STARTED, "not started"); VersionedValue current = currentValue.get(); - if ( previous.getVersion() != current.getVersion() || !Arrays.equals(previous.getValue(), current.getValue()) ) - { + if (previous.getVersion() != current.getVersion() || !Arrays.equals(previous.getValue(), current.getValue())) { return false; } - try - { + try { Stat result = client.setData().withVersion(previous.getVersion()).forPath(path, newValue); updateValue(result.getVersion(), Arrays.copyOf(newValue, newValue.length)); return true; - } - catch ( KeeperException.BadVersionException ignore ) - { + } catch (KeeperException.BadVersionException ignore) { // ignore } @@ -211,18 +193,14 @@ public boolean trySetValue(VersionedValue previous, byte[] newValue) thr return false; } - private void updateValue(int version, byte[] bytes) - { - while (true) - { + private void updateValue(int version, byte[] bytes) { + while (true) { VersionedValue current = currentValue.get(); - if (current.getVersion() >= version) - { + if (current.getVersion() >= version) { // A newer version was concurrently set. return; } - if ( currentValue.compareAndSet(current, new VersionedValue(version, bytes)) ) - { + if (currentValue.compareAndSet(current, new VersionedValue(version, bytes))) { // Successfully set. return; } @@ -235,8 +213,7 @@ private void updateValue(int version, byte[] bytes) * * @return listenable */ - public Listenable getListenable() - { + public Listenable getListenable() { return listeners; } @@ -246,17 +223,13 @@ public Listenable getListenable() * * @throws Exception ZK errors, interruptions, etc. */ - public void start() throws Exception - { + public void start() throws Exception { Preconditions.checkState(state.compareAndSet(State.LATENT, State.STARTED), "Cannot be started more than once"); client.getConnectionStateListenable().addListener(connectionStateListener); - try - { + try { client.create().creatingParentContainersIfNeeded().forPath(path, seedValue); - } - catch ( KeeperException.NodeExistsException ignore ) - { + } catch (KeeperException.NodeExistsException ignore) { // ignore } @@ -264,18 +237,17 @@ public void start() throws Exception } @Override - public void close() throws IOException - { + public void close() throws IOException { state.set(State.CLOSED); client.removeWatchers(); client.getConnectionStateListenable().removeListener(connectionStateListener); listeners.clear(); } - private void readValue() throws Exception - { + private void readValue() throws Exception { Stat localStat = new Stat(); - byte[] bytes = client.getData().storingStatIn(localStat).usingWatcher(watcher).forPath(path); + byte[] bytes = + client.getData().storingStatIn(localStat).usingWatcher(watcher).forPath(path); updateValue(localStat.getVersion(), bytes); } @@ -289,29 +261,26 @@ public void processResult(CuratorFramework client, CuratorEvent event) throws Ex } }; - private void readValueAndNotifyListenersInBackground() throws Exception - { - client.getData().usingWatcher(watcher).inBackground(upadateAndNotifyListenerCallback).forPath(path); + private void readValueAndNotifyListenersInBackground() throws Exception { + client.getData() + .usingWatcher(watcher) + .inBackground(upadateAndNotifyListenerCallback) + .forPath(path); } - private void notifyListeners() - { + private void notifyListeners() { final byte[] localValue = getValue(); listeners.forEach(listener -> { - try - { + try { listener.valueHasChanged(SharedValue.this, localValue); - } - catch ( Exception e ) - { + } catch (Exception e) { ThreadUtils.checkInterrupted(e); log.error("From SharedValue listener", e); } }); } - private void notifyListenerOfStateChanged(final ConnectionState newState) - { + private void notifyListenerOfStateChanged(final ConnectionState newState) { listeners.forEach(listener -> listener.stateChanged(client, newState)); } } diff --git a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/shared/SharedValueListener.java b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/shared/SharedValueListener.java index 5dc32384f..54f84206f 100644 --- a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/shared/SharedValueListener.java +++ b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/shared/SharedValueListener.java @@ -24,8 +24,7 @@ /** * Listener for changes to a shared value */ -public interface SharedValueListener extends ConnectionStateListener -{ +public interface SharedValueListener extends ConnectionStateListener { /** * Called when the shared value has changed * diff --git a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/shared/SharedValueReader.java b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/shared/SharedValueReader.java index 1fdc564de..5c0995a1e 100644 --- a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/shared/SharedValueReader.java +++ b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/shared/SharedValueReader.java @@ -24,14 +24,13 @@ /** * Abstracts a shared value and allows listening for changes to the value */ -public interface SharedValueReader -{ +public interface SharedValueReader { /** * Return the current value of the count * * @return count */ - public byte[] getValue(); + public byte[] getValue(); /** * Return the current version and value diff --git a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/shared/VersionedValue.java b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/shared/VersionedValue.java index 323709f1b..64d9780b7 100644 --- a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/shared/VersionedValue.java +++ b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/shared/VersionedValue.java @@ -24,8 +24,7 @@ /** * POJO for a version and a value */ -public class VersionedValue -{ +public class VersionedValue { private final int version; private final T value; @@ -33,19 +32,16 @@ public class VersionedValue * @param version the version * @param value the value (cannot be null) */ - VersionedValue(int version, T value) - { + VersionedValue(int version, T value) { this.version = version; this.value = Preconditions.checkNotNull(value, "value cannot be null"); } - public int getVersion() - { + public int getVersion() { return version; } - public T getValue() - { + public T getValue() { return value; } } diff --git a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/watch/PersistentWatcher.java b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/watch/PersistentWatcher.java index 9577be3c0..bf950cede 100644 --- a/curator-recipes/src/main/java/org/apache/curator/framework/recipes/watch/PersistentWatcher.java +++ b/curator-recipes/src/main/java/org/apache/curator/framework/recipes/watch/PersistentWatcher.java @@ -38,6 +38,9 @@ package org.apache.curator.framework.recipes.watch; import com.google.common.base.Preconditions; +import java.io.Closeable; +import java.util.Objects; +import java.util.concurrent.atomic.AtomicReference; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.api.BackgroundCallback; import org.apache.curator.framework.listen.Listenable; @@ -49,23 +52,18 @@ import org.apache.zookeeper.Watcher; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.io.Closeable; -import java.util.Objects; -import java.util.concurrent.atomic.AtomicReference; /** * A managed persistent watcher. The watch will be managed such that it stays set through * connection lapses, etc. */ -public class PersistentWatcher implements Closeable -{ +public class PersistentWatcher implements Closeable { private final Logger log = LoggerFactory.getLogger(getClass()); private final AtomicReference state = new AtomicReference<>(State.LATENT); private final StandardListenerManager listeners = StandardListenerManager.standard(); private final StandardListenerManager resetListeners = StandardListenerManager.standard(); private final ConnectionStateListener connectionStateListener = (client, newState) -> { - if ( newState.isConnected() ) - { + if (newState.isConnected()) { reset(); } }; @@ -74,8 +72,7 @@ public class PersistentWatcher implements Closeable private final String basePath; private final boolean recursive; - private enum State - { + private enum State { LATENT, STARTED, CLOSED @@ -86,8 +83,7 @@ private enum State * @param basePath path to set the watch on * @param recursive ZooKeeper persistent watches can optionally be recursive */ - public PersistentWatcher(CuratorFramework client, String basePath, boolean recursive) - { + public PersistentWatcher(CuratorFramework client, String basePath, boolean recursive) { this.client = Objects.requireNonNull(client, "client cannot be null"); this.basePath = Objects.requireNonNull(basePath, "basePath cannot be null"); this.recursive = recursive; @@ -96,8 +92,7 @@ public PersistentWatcher(CuratorFramework client, String basePath, boolean recur /** * Start watching */ - public void start() - { + public void start() { Preconditions.checkState(state.compareAndSet(State.LATENT, State.STARTED), "Already started"); client.getConnectionStateListenable().addListener(connectionStateListener); reset(); @@ -107,18 +102,13 @@ public void start() * Remove the watcher */ @Override - public void close() - { - if ( state.compareAndSet(State.STARTED, State.CLOSED) ) - { + public void close() { + if (state.compareAndSet(State.STARTED, State.CLOSED)) { listeners.clear(); client.getConnectionStateListenable().removeListener(connectionStateListener); - try - { + try { client.watchers().remove(watcher).guaranteed().inBackground().forPath(basePath); - } - catch ( Exception e ) - { + } catch (Exception e) { ThreadUtils.checkInterrupted(e); log.debug(String.format("Could not remove watcher for path: %s", basePath), e); } @@ -130,8 +120,7 @@ public void close() * * @return listener container */ - public Listenable getListenable() - { + public Listenable getListenable() { return listeners; } @@ -141,34 +130,30 @@ public Listenable getListenable() * * @return listener container */ - public Listenable getResetListenable() - { + public Listenable getResetListenable() { return resetListeners; } - private void reset() - { - if ( state.get() != State.STARTED ) - { + private void reset() { + if (state.get() != State.STARTED) { return; } - - try - { + + try { BackgroundCallback callback = (__, event) -> { - if ( event.getResultCode() == KeeperException.Code.OK.intValue() ) - { + if (event.getResultCode() == KeeperException.Code.OK.intValue()) { resetListeners.forEach(Runnable::run); - } - else - { + } else { reset(); } }; - client.watchers().add().withMode(recursive ? AddWatchMode.PERSISTENT_RECURSIVE : AddWatchMode.PERSISTENT).inBackground(callback).usingWatcher(watcher).forPath(basePath); - } - catch ( Exception e ) - { + client.watchers() + .add() + .withMode(recursive ? AddWatchMode.PERSISTENT_RECURSIVE : AddWatchMode.PERSISTENT) + .inBackground(callback) + .usingWatcher(watcher) + .forPath(basePath); + } catch (Exception e) { log.error("Could not reset persistent watch at path: " + basePath, e); } } diff --git a/curator-recipes/src/test/java/org/apache/curator/connection/TestThreadLocalRetryLoop.java b/curator-recipes/src/test/java/org/apache/curator/connection/TestThreadLocalRetryLoop.java index dbce038d6..3596a493f 100644 --- a/curator-recipes/src/test/java/org/apache/curator/connection/TestThreadLocalRetryLoop.java +++ b/curator-recipes/src/test/java/org/apache/curator/connection/TestThreadLocalRetryLoop.java @@ -23,6 +23,11 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; import org.apache.curator.RetryLoop; import org.apache.curator.RetryPolicy; import org.apache.curator.RetrySleeper; @@ -36,106 +41,101 @@ import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicInteger; - -public class TestThreadLocalRetryLoop extends CuratorTestBase -{ +public class TestThreadLocalRetryLoop extends CuratorTestBase { private static final int retryCount = 4; private static final String backgroundThreadNameBase = "ignore-curator-background-thread"; @Test @DisplayName("Check for fix for CURATOR-559") - public void testRecursingRetry() throws Exception - { + public void testRecursingRetry() throws Exception { AtomicInteger count = new AtomicInteger(); - try (CuratorFramework client = newClient(count)) - { + try (CuratorFramework client = newClient(count)) { prep(client, count); doOperation(client); - assertEquals(count.get(), retryCount + 1); // Curator's retry policy has been off by 1 since inception - we might consider fixing it someday + assertEquals( + count.get(), + retryCount + + 1); // Curator's retry policy has been off by 1 since inception - we might consider fixing + // it someday } } @Test @DisplayName("Check for fix for CURATOR-559 with multiple threads") - public void testThreadedRecursingRetry() throws Exception - { + public void testThreadedRecursingRetry() throws Exception { final int threadQty = 4; ExecutorService executorService = Executors.newFixedThreadPool(threadQty); AtomicInteger count = new AtomicInteger(); - try (CuratorFramework client = newClient(count)) - { + try (CuratorFramework client = newClient(count)) { prep(client, count); - for ( int i = 0; i < threadQty; ++i ) - { + for (int i = 0; i < threadQty; ++i) { executorService.submit(() -> doOperation(client)); } executorService.shutdown(); assertTrue(executorService.awaitTermination(timing.milliseconds(), TimeUnit.MILLISECONDS)); - assertEquals(count.get(), threadQty * (retryCount + 1)); // Curator's retry policy has been off by 1 since inception - we might consider fixing it someday + assertEquals( + count.get(), + threadQty + * (retryCount + 1)); // Curator's retry policy has been off by 1 since inception - we might + // consider fixing it someday } } @Test - public void testBadReleaseWithNoGet() - { - assertThrows(NullPointerException.class, ()-> { - ThreadLocalRetryLoop retryLoopStack = new ThreadLocalRetryLoop(); - retryLoopStack.release(); - }); + public void testBadReleaseWithNoGet() { + assertThrows(NullPointerException.class, () -> { + ThreadLocalRetryLoop retryLoopStack = new ThreadLocalRetryLoop(); + retryLoopStack.release(); + }); } - private CuratorFramework newClient(AtomicInteger count) - { + private CuratorFramework newClient(AtomicInteger count) { RetryPolicy retryPolicy = makeRetryPolicy(count); - return CuratorFrameworkFactory.builder().connectString(server.getConnectString()).connectionTimeoutMs(100).sessionTimeoutMs(100).retryPolicy(retryPolicy).threadFactory(ThreadUtils.newThreadFactory(backgroundThreadNameBase)).build(); + return CuratorFrameworkFactory.builder() + .connectString(server.getConnectString()) + .connectionTimeoutMs(100) + .sessionTimeoutMs(100) + .retryPolicy(retryPolicy) + .threadFactory(ThreadUtils.newThreadFactory(backgroundThreadNameBase)) + .build(); } - private void prep(CuratorFramework client, AtomicInteger count) throws Exception - { + private void prep(CuratorFramework client, AtomicInteger count) throws Exception { client.start(); client.create().forPath("/test"); CountDownLatch lostLatch = new CountDownLatch(1); client.getConnectionStateListenable().addListener((__, newState) -> { - if ( newState == ConnectionState.LOST ) - { + if (newState == ConnectionState.LOST) { lostLatch.countDown(); } }); server.stop(); assertTrue(timing.awaitLatch(lostLatch)); - count.set(0); // in case the server shutdown incremented the count + count.set(0); // in case the server shutdown incremented the count } - private Void doOperation(CuratorFramework client) throws Exception - { - try - { + private Void doOperation(CuratorFramework client) throws Exception { + try { RetryLoop.callWithRetry(client.getZookeeperClient(), () -> { client.checkExists().forPath("/hey"); return null; }); fail("Should have thrown an exception"); - } - catch ( KeeperException dummy ) - { + } catch (KeeperException dummy) { // correct } return null; } - private RetryPolicy makeRetryPolicy(AtomicInteger count) - { - return new RetryNTimes(retryCount, 1) - { + private RetryPolicy makeRetryPolicy(AtomicInteger count) { + return new RetryNTimes(retryCount, 1) { @Override - public boolean allowRetry(int retryCount, long elapsedTimeMs, RetrySleeper sleeper) - { - if ( !Thread.currentThread().getName().contains(backgroundThreadNameBase) ) // if it does, it's Curator's background thread - don't count these + public boolean allowRetry(int retryCount, long elapsedTimeMs, RetrySleeper sleeper) { + if (!Thread.currentThread() + .getName() + .contains( + backgroundThreadNameBase)) // if it does, it's Curator's background thread - don't count + // these { count.incrementAndGet(); } diff --git a/curator-recipes/src/test/java/org/apache/curator/framework/client/TestBackgroundStates.java b/curator-recipes/src/test/java/org/apache/curator/framework/client/TestBackgroundStates.java index 54c482ed9..7a3036833 100644 --- a/curator-recipes/src/test/java/org/apache/curator/framework/client/TestBackgroundStates.java +++ b/curator-recipes/src/test/java/org/apache/curator/framework/client/TestBackgroundStates.java @@ -22,6 +22,10 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import com.google.common.collect.Queues; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.recipes.nodes.PersistentEphemeralNode; @@ -34,44 +38,34 @@ import org.apache.curator.utils.CloseableUtils; import org.junit.jupiter.api.Test; -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicReference; - // NOTE: these tests are in Framework as they use the PersistentEphemeralNode recipe -public class TestBackgroundStates extends BaseClassForTests -{ +public class TestBackgroundStates extends BaseClassForTests { @Test - public void testListenersReconnectedIsOK() throws Exception - { + public void testListenersReconnectedIsOK() throws Exception { server.close(); Timing timing = new Timing(); - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); + CuratorFramework client = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); PersistentEphemeralNode node = null; - try - { + try { client.start(); - node = new PersistentEphemeralNode(client, PersistentEphemeralNode.Mode.EPHEMERAL, "/abc/node", "hello".getBytes()); + node = new PersistentEphemeralNode( + client, PersistentEphemeralNode.Mode.EPHEMERAL, "/abc/node", "hello".getBytes()); node.start(); final CountDownLatch connectedLatch = new CountDownLatch(1); final CountDownLatch reconnectedLatch = new CountDownLatch(1); final AtomicReference lastState = new AtomicReference(); - ConnectionStateListener listener = new ConnectionStateListener() - { + ConnectionStateListener listener = new ConnectionStateListener() { @Override - public void stateChanged(CuratorFramework client, ConnectionState newState) - { + public void stateChanged(CuratorFramework client, ConnectionState newState) { lastState.set(newState); - if ( newState == ConnectionState.CONNECTED ) - { + if (newState == ConnectionState.CONNECTED) { connectedLatch.countDown(); } - if ( newState == ConnectionState.RECONNECTED ) - { + if (newState == ConnectionState.RECONNECTED) { reconnectedLatch.countDown(); } } @@ -87,31 +81,29 @@ public void stateChanged(CuratorFramework client, ConnectionState newState) assertTrue(timing.awaitLatch(reconnectedLatch)); timing.sleepABit(); assertEquals(lastState.get(), ConnectionState.RECONNECTED); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); CloseableUtils.closeQuietly(node); } } @Test - public void testConnectionStateListener() throws Exception - { + public void testConnectionStateListener() throws Exception { server.close(); Timing timing = new Timing(); - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(timing.milliseconds())); - try - { + CuratorFramework client = CuratorFrameworkFactory.newClient( + server.getConnectString(), + timing.session(), + timing.connection(), + new RetryOneTime(timing.milliseconds())); + try { client.start(); final BlockingQueue stateVector = Queues.newLinkedBlockingQueue(1); - ConnectionStateListener listener = new ConnectionStateListener() - { + ConnectionStateListener listener = new ConnectionStateListener() { @Override - public void stateChanged(CuratorFramework client, ConnectionState newState) - { + public void stateChanged(CuratorFramework client, ConnectionState newState) { stateVector.offer(newState); } }; @@ -120,20 +112,21 @@ public void stateChanged(CuratorFramework client, ConnectionState newState) client.getConnectionStateListenable().addListener(listener); server = new TestingServer(server.getPort()); - assertEquals(stateVector.poll(waitingTiming.milliseconds(), TimeUnit.MILLISECONDS), ConnectionState.CONNECTED); + assertEquals( + stateVector.poll(waitingTiming.milliseconds(), TimeUnit.MILLISECONDS), ConnectionState.CONNECTED); server.stop(); - assertEquals(stateVector.poll(waitingTiming.milliseconds(), TimeUnit.MILLISECONDS), ConnectionState.SUSPENDED); + assertEquals( + stateVector.poll(waitingTiming.milliseconds(), TimeUnit.MILLISECONDS), ConnectionState.SUSPENDED); assertEquals(stateVector.poll(waitingTiming.milliseconds(), TimeUnit.MILLISECONDS), ConnectionState.LOST); server.restart(); - assertEquals(stateVector.poll(waitingTiming.milliseconds(), TimeUnit.MILLISECONDS), ConnectionState.RECONNECTED); + assertEquals( + stateVector.poll(waitingTiming.milliseconds(), TimeUnit.MILLISECONDS), ConnectionState.RECONNECTED); server.close(); - assertEquals(stateVector.poll(waitingTiming.milliseconds(), TimeUnit.MILLISECONDS), ConnectionState.SUSPENDED); + assertEquals( + stateVector.poll(waitingTiming.milliseconds(), TimeUnit.MILLISECONDS), ConnectionState.SUSPENDED); assertEquals(stateVector.poll(waitingTiming.milliseconds(), TimeUnit.MILLISECONDS), ConnectionState.LOST); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } - -} \ No newline at end of file +} diff --git a/curator-recipes/src/test/java/org/apache/curator/framework/client/TestResetConnectionWithBackgroundFailure.java b/curator-recipes/src/test/java/org/apache/curator/framework/client/TestResetConnectionWithBackgroundFailure.java index 074aa4a4b..bc3c660c8 100644 --- a/curator-recipes/src/test/java/org/apache/curator/framework/client/TestResetConnectionWithBackgroundFailure.java +++ b/curator-recipes/src/test/java/org/apache/curator/framework/client/TestResetConnectionWithBackgroundFailure.java @@ -21,6 +21,8 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import com.google.common.collect.Queues; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.TimeUnit; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.recipes.leader.LeaderSelector; @@ -35,31 +37,25 @@ import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.TimeUnit; -public class TestResetConnectionWithBackgroundFailure extends BaseClassForTests -{ +public class TestResetConnectionWithBackgroundFailure extends BaseClassForTests { private final Logger log = LoggerFactory.getLogger(getClass()); @Test - public void testConnectionStateListener() throws Exception - { + public void testConnectionStateListener() throws Exception { server.stop(); LeaderSelector selector = null; Timing timing = new Timing(); - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); - try - { + CuratorFramework client = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); + try { client.start(); timing.sleepABit(); - LeaderSelectorListener listenerLeader = new LeaderSelectorListenerAdapter() - { + LeaderSelectorListener listenerLeader = new LeaderSelectorListenerAdapter() { @Override - public void takeLeadership(CuratorFramework client) throws Exception - { + public void takeLeadership(CuratorFramework client) throws Exception { Thread.currentThread().join(); } }; @@ -68,11 +64,9 @@ public void takeLeadership(CuratorFramework client) throws Exception selector.start(); final BlockingQueue listenerSequence = Queues.newLinkedBlockingQueue(); - ConnectionStateListener listener1 = new ConnectionStateListener() - { + ConnectionStateListener listener1 = new ConnectionStateListener() { @Override - public void stateChanged(CuratorFramework client, ConnectionState newState) - { + public void stateChanged(CuratorFramework client, ConnectionState newState) { listenerSequence.add(newState); } }; @@ -82,27 +76,29 @@ public void stateChanged(CuratorFramework client, ConnectionState newState) client.getConnectionStateListenable().addListener(listener1); log.debug("Starting ZK server"); server.restart(); - assertEquals(listenerSequence.poll(forWaiting.milliseconds(), TimeUnit.MILLISECONDS), ConnectionState.CONNECTED); + assertEquals( + listenerSequence.poll(forWaiting.milliseconds(), TimeUnit.MILLISECONDS), ConnectionState.CONNECTED); log.debug("Stopping ZK server"); server.stop(); - assertEquals(listenerSequence.poll(forWaiting.milliseconds(), TimeUnit.MILLISECONDS), ConnectionState.SUSPENDED); + assertEquals( + listenerSequence.poll(forWaiting.milliseconds(), TimeUnit.MILLISECONDS), ConnectionState.SUSPENDED); assertEquals(listenerSequence.poll(forWaiting.milliseconds(), TimeUnit.MILLISECONDS), ConnectionState.LOST); log.debug("Starting ZK server"); server.restart(); - assertEquals(listenerSequence.poll(forWaiting.milliseconds(), TimeUnit.MILLISECONDS), ConnectionState.RECONNECTED); + assertEquals( + listenerSequence.poll(forWaiting.milliseconds(), TimeUnit.MILLISECONDS), + ConnectionState.RECONNECTED); log.debug("Stopping ZK server"); server.close(); - assertEquals(listenerSequence.poll(forWaiting.milliseconds(), TimeUnit.MILLISECONDS), ConnectionState.SUSPENDED); + assertEquals( + listenerSequence.poll(forWaiting.milliseconds(), TimeUnit.MILLISECONDS), ConnectionState.SUSPENDED); assertEquals(listenerSequence.poll(forWaiting.milliseconds(), TimeUnit.MILLISECONDS), ConnectionState.LOST); - } - finally - { + } finally { CloseableUtils.closeQuietly(selector); CloseableUtils.closeQuietly(client); } } - -} \ No newline at end of file +} diff --git a/curator-recipes/src/test/java/org/apache/curator/framework/recipes/atomic/TestCachedAtomicCounter.java b/curator-recipes/src/test/java/org/apache/curator/framework/recipes/atomic/TestCachedAtomicCounter.java index facf058d1..2f2fe7d23 100644 --- a/curator-recipes/src/test/java/org/apache/curator/framework/recipes/atomic/TestCachedAtomicCounter.java +++ b/curator-recipes/src/test/java/org/apache/curator/framework/recipes/atomic/TestCachedAtomicCounter.java @@ -22,87 +22,70 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; - +import java.util.concurrent.atomic.AtomicReference; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.retry.RetryOneTime; import org.apache.curator.test.BaseClassForTests; import org.junit.jupiter.api.Test; -import java.util.concurrent.atomic.AtomicReference; - -public class TestCachedAtomicCounter extends BaseClassForTests -{ +public class TestCachedAtomicCounter extends BaseClassForTests { @Test - public void testWithError() throws Exception - { - final int FACTOR = 100; + public void testWithError() throws Exception { + final int FACTOR = 100; CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client.start(); - try - { - AtomicValue value = new MutableAtomicValue(0L, (long)FACTOR, true); - final AtomicReference> fakeValueRef = new AtomicReference>(value); - DistributedAtomicLong dal = new DistributedAtomicLong(client, "/", null, null) - { + try { + AtomicValue value = new MutableAtomicValue(0L, (long) FACTOR, true); + final AtomicReference> fakeValueRef = new AtomicReference>(value); + DistributedAtomicLong dal = new DistributedAtomicLong(client, "/", null, null) { @Override - public AtomicValue trySet(Long newValue) throws Exception - { + public AtomicValue trySet(Long newValue) throws Exception { return fakeValueRef.get(); } @Override - public AtomicValue get() throws Exception - { + public AtomicValue get() throws Exception { return fakeValueRef.get(); } @Override - public AtomicValue increment() throws Exception - { + public AtomicValue increment() throws Exception { return fakeValueRef.get(); } @Override - public AtomicValue decrement() throws Exception - { + public AtomicValue decrement() throws Exception { return fakeValueRef.get(); } @Override - public AtomicValue add(Long delta) throws Exception - { + public AtomicValue add(Long delta) throws Exception { return fakeValueRef.get(); } @Override - public AtomicValue subtract(Long delta) throws Exception - { + public AtomicValue subtract(Long delta) throws Exception { return fakeValueRef.get(); } @Override - public void forceSet(Long newValue) throws Exception - { - } + public void forceSet(Long newValue) throws Exception {} @Override - public AtomicValue compareAndSet(Long expectedValue, Long newValue) throws Exception - { + public AtomicValue compareAndSet(Long expectedValue, Long newValue) throws Exception { return fakeValueRef.get(); } }; CachedAtomicLong cachedLong = new CachedAtomicLong(dal, FACTOR); - for ( int i = 0; i < FACTOR; ++i ) - { + for (int i = 0; i < FACTOR; ++i) { value = cachedLong.next(); assertTrue(value.succeeded()); assertEquals(value.preValue().longValue(), i); assertEquals(value.postValue().longValue(), i + 1); - if ( i == 0 ) - { + if (i == 0) { MutableAtomicValue badValue = new MutableAtomicValue(0L, 0L); badValue.succeeded = false; fakeValueRef.set(badValue); @@ -111,32 +94,25 @@ public AtomicValue compareAndSet(Long expectedValue, Long newValue) throws value = cachedLong.next(); assertFalse(value.succeeded()); - } - finally - { + } finally { client.close(); } - } + } @Test - public void testBasic() throws Exception - { + public void testBasic() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client.start(); - try - { + try { DistributedAtomicLong dal = new DistributedAtomicLong(client, "/counter", new RetryOneTime(1)); CachedAtomicLong cachedLong = new CachedAtomicLong(dal, 100); - for ( long i = 0; i < 200; ++i ) - { - AtomicValue value = cachedLong.next(); + for (long i = 0; i < 200; ++i) { + AtomicValue value = cachedLong.next(); assertTrue(value.succeeded()); assertEquals(value.preValue().longValue(), i); assertEquals(value.postValue().longValue(), i + 1); } - } - finally - { + } finally { client.close(); } } diff --git a/curator-recipes/src/test/java/org/apache/curator/framework/recipes/atomic/TestDistributedAtomicLong.java b/curator-recipes/src/test/java/org/apache/curator/framework/recipes/atomic/TestDistributedAtomicLong.java index d5c83b3c6..02c40c91e 100644 --- a/curator-recipes/src/test/java/org/apache/curator/framework/recipes/atomic/TestDistributedAtomicLong.java +++ b/curator-recipes/src/test/java/org/apache/curator/framework/recipes/atomic/TestDistributedAtomicLong.java @@ -23,19 +23,7 @@ import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; - import com.google.common.collect.Lists; -import org.apache.curator.RetryPolicy; -import org.apache.curator.framework.CuratorFramework; -import org.apache.curator.framework.CuratorFrameworkFactory; -import org.apache.curator.retry.ExponentialBackoffRetry; -import org.apache.curator.retry.RetryOneTime; -import org.apache.commons.math.stat.descriptive.SummaryStatistics; -import org.apache.commons.math.stat.descriptive.SynchronizedSummaryStatistics; -import org.apache.curator.test.BaseClassForTests; -import org.apache.curator.utils.CloseableUtils; -import org.junit.jupiter.api.Test; - import java.nio.BufferOverflowException; import java.nio.BufferUnderflowException; import java.util.List; @@ -46,47 +34,44 @@ import java.util.concurrent.Future; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; +import org.apache.commons.math.stat.descriptive.SummaryStatistics; +import org.apache.commons.math.stat.descriptive.SynchronizedSummaryStatistics; +import org.apache.curator.RetryPolicy; +import org.apache.curator.framework.CuratorFramework; +import org.apache.curator.framework.CuratorFrameworkFactory; +import org.apache.curator.retry.ExponentialBackoffRetry; +import org.apache.curator.retry.RetryOneTime; +import org.apache.curator.test.BaseClassForTests; +import org.apache.curator.utils.CloseableUtils; +import org.junit.jupiter.api.Test; -public class TestDistributedAtomicLong extends BaseClassForTests -{ +public class TestDistributedAtomicLong extends BaseClassForTests { @Test - public void testCorruptedValue() throws Exception - { - final CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); + public void testCorruptedValue() throws Exception { + final CuratorFramework client = + CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client.start(); - try - { + try { client.create().forPath("/counter", "foo".getBytes()); - DistributedAtomicLong dal = new DistributedAtomicLong(client, "/counter", new RetryOneTime(1)); - try - { + DistributedAtomicLong dal = new DistributedAtomicLong(client, "/counter", new RetryOneTime(1)); + try { dal.get().postValue(); - } - catch ( BufferUnderflowException e ) - { + } catch (BufferUnderflowException e) { fail("", e); - } - catch ( BufferOverflowException e ) - { + } catch (BufferOverflowException e) { fail("", e); - } - catch ( RuntimeException e ) - { + } catch (RuntimeException e) { // correct } - } - finally - { + } finally { client.close(); } } @Test - public void testCompareAndSetWithFreshInstance() throws Exception - { + public void testCompareAndSetWithFreshInstance() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); - try - { + try { client.start(); DistributedAtomicLong dal = new DistributedAtomicLong(client, "/counter", new RetryOneTime(1)); AtomicValue result = dal.compareAndSet(0L, 1L); @@ -97,36 +82,27 @@ public void testCompareAndSetWithFreshInstance() throws Exception assertTrue(result.succeeded()); assertFalse(dal.initialize(0L)); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } @Test - public void testCompareAndSet() throws Exception - { - final CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); + public void testCompareAndSet() throws Exception { + final CuratorFramework client = + CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client.start(); - try - { - final AtomicBoolean doIncrement = new AtomicBoolean(false); - DistributedAtomicLong dal = new DistributedAtomicLong(client, "/counter", new RetryOneTime(1)) - { + try { + final AtomicBoolean doIncrement = new AtomicBoolean(false); + DistributedAtomicLong dal = new DistributedAtomicLong(client, "/counter", new RetryOneTime(1)) { @Override - public byte[] valueToBytes(Long newValue) - { - if ( doIncrement.get() ) - { + public byte[] valueToBytes(Long newValue) { + if (doIncrement.get()) { DistributedAtomicLong inc = new DistributedAtomicLong(client, "/counter", new RetryOneTime(1)); - try - { + try { // this will force a bad version exception inc.increment(); - } - catch ( Exception e ) - { + } catch (Exception e) { throw new Error(e); } } @@ -141,69 +117,50 @@ public byte[] valueToBytes(Long newValue) doIncrement.set(true); assertFalse(dal.compareAndSet(5L, 10L).succeeded()); - } - finally - { + } finally { client.close(); } } @Test - public void testForceSet() throws Exception - { + public void testForceSet() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client.start(); - try - { + try { final DistributedAtomicLong dal = new DistributedAtomicLong(client, "/counter", new RetryOneTime(1)); - ExecutorService executorService = Executors.newFixedThreadPool(2); - executorService.submit - ( - new Callable() - { - @Override - public Object call() throws Exception - { - for ( int i = 0; i < 1000; ++i ) - { - dal.increment(); - Thread.sleep(10); - } - return null; + ExecutorService executorService = Executors.newFixedThreadPool(2); + executorService.submit(new Callable() { + @Override + public Object call() throws Exception { + for (int i = 0; i < 1000; ++i) { + dal.increment(); + Thread.sleep(10); } + return null; } - ); - executorService.submit - ( - new Callable() - { - @Override - public Object call() throws Exception - { - for ( int i = 0; i < 1000; ++i ) - { - dal.forceSet(0L); - Thread.sleep(10); - } - return null; + }); + executorService.submit(new Callable() { + @Override + public Object call() throws Exception { + for (int i = 0; i < 1000; ++i) { + dal.forceSet(0L); + Thread.sleep(10); } + return null; } - ); + }); assertTrue(dal.get().preValue() < 10); - } - finally - { + } finally { client.close(); } } @Test - public void testSimulation() throws Exception - { - final int threadQty = 20; - final int executionQty = 50; + public void testSimulation() throws Exception { + final int threadQty = 20; + final int executionQty = 50; final AtomicInteger optimisticTries = new AtomicInteger(); final AtomicInteger promotedLockTries = new AtomicInteger(); @@ -211,15 +168,12 @@ public void testSimulation() throws Exception final AtomicInteger errors = new AtomicInteger(); final SummaryStatistics timingStats = new SynchronizedSummaryStatistics(); - List> procs = Lists.newArrayList(); - ExecutorService executorService = Executors.newFixedThreadPool(threadQty); - for ( int i = 0; i < threadQty; ++i ) - { - Callable proc = new Callable() - { + List> procs = Lists.newArrayList(); + ExecutorService executorService = Executors.newFixedThreadPool(threadQty); + for (int i = 0; i < threadQty; ++i) { + Callable proc = new Callable() { @Override - public Void call() throws Exception - { + public Void call() throws Exception { doSimulation(executionQty, timingStats, optimisticTries, promotedLockTries, failures, errors); return null; } @@ -227,8 +181,7 @@ public Void call() throws Exception procs.add(executorService.submit(proc)); } - for ( Future f : procs ) - { + for (Future f : procs) { f.get(); } @@ -249,15 +202,13 @@ public Void call() throws Exception } @Test - public void testBasic() throws Exception - { - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); + public void testBasic() throws Exception { + CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client.start(); - try - { + try { DistributedAtomicLong dal = new DistributedAtomicLong(client, "/foo/bar/counter", new RetryOneTime(1)); - AtomicValue value = dal.increment(); + AtomicValue value = dal.increment(); assertTrue(value.succeeded()); assertEquals(value.getStats().getOptimisticTries(), 1); assertEquals(value.getStats().getPromotedLockTries(), 0); @@ -284,54 +235,51 @@ public void testBasic() throws Exception assertEquals(value.getStats().getPromotedLockTries(), 0); assertEquals(value.preValue().longValue(), 10L); assertEquals(value.postValue().longValue(), 5L); - } - finally - { + } finally { client.close(); } } - private void doSimulation(int executionQty, SummaryStatistics timingStats, AtomicInteger optimisticTries, AtomicInteger promotedLockTries, AtomicInteger failures, AtomicInteger errors) throws Exception - { - Random random = new Random(); - long previousValue = -1; - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); + private void doSimulation( + int executionQty, + SummaryStatistics timingStats, + AtomicInteger optimisticTries, + AtomicInteger promotedLockTries, + AtomicInteger failures, + AtomicInteger errors) + throws Exception { + Random random = new Random(); + long previousValue = -1; + CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client.start(); - try - { - RetryPolicy retryPolicy = new ExponentialBackoffRetry(3, 3); - PromotedToLock.Builder builder = PromotedToLock.builder().lockPath("/lock").retryPolicy(retryPolicy); + try { + RetryPolicy retryPolicy = new ExponentialBackoffRetry(3, 3); + PromotedToLock.Builder builder = + PromotedToLock.builder().lockPath("/lock").retryPolicy(retryPolicy); DistributedAtomicLong dal = new DistributedAtomicLong(client, "/counter", retryPolicy, builder.build()); - for ( int i = 0; i < executionQty; ++i ) - { + for (int i = 0; i < executionQty; ++i) { Thread.sleep(random.nextInt(10)); - long start = System.currentTimeMillis(); - AtomicValue value = dal.increment(); - long elapsed = System.currentTimeMillis() - start; + long start = System.currentTimeMillis(); + AtomicValue value = dal.increment(); + long elapsed = System.currentTimeMillis() - start; timingStats.addValue(elapsed); - if ( value.succeeded() ) - { - if ( value.postValue() <= previousValue ) - { + if (value.succeeded()) { + if (value.postValue() <= previousValue) { errors.incrementAndGet(); } previousValue = value.postValue(); - } - else - { + } else { failures.incrementAndGet(); } optimisticTries.addAndGet(value.getStats().getOptimisticTries()); promotedLockTries.addAndGet(value.getStats().getPromotedLockTries()); } - } - finally - { + } finally { client.close(); } } diff --git a/curator-recipes/src/test/java/org/apache/curator/framework/recipes/barriers/TestDistributedBarrier.java b/curator-recipes/src/test/java/org/apache/curator/framework/recipes/barriers/TestDistributedBarrier.java index 06de22a9e..8646f99c3 100644 --- a/curator-recipes/src/test/java/org/apache/curator/framework/recipes/barriers/TestDistributedBarrier.java +++ b/curator-recipes/src/test/java/org/apache/curator/framework/recipes/barriers/TestDistributedBarrier.java @@ -22,82 +22,69 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; import com.google.common.collect.Lists; -import org.apache.curator.test.BaseClassForTests; -import org.apache.curator.utils.CloseableUtils; -import org.apache.curator.framework.CuratorFramework; -import org.apache.curator.framework.CuratorFrameworkFactory; -import org.apache.curator.retry.RetryOneTime; -import org.apache.zookeeper.KeeperException; -import org.junit.jupiter.api.Test; - import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; +import org.apache.curator.framework.CuratorFramework; +import org.apache.curator.framework.CuratorFrameworkFactory; +import org.apache.curator.retry.RetryOneTime; +import org.apache.curator.test.BaseClassForTests; +import org.apache.curator.utils.CloseableUtils; +import org.apache.zookeeper.KeeperException; +import org.junit.jupiter.api.Test; -public class TestDistributedBarrier extends BaseClassForTests -{ +public class TestDistributedBarrier extends BaseClassForTests { @Test - public void testServerCrash() throws Exception - { - final int TIMEOUT = 1000; - - final CuratorFramework client = CuratorFrameworkFactory.builder().connectString(server.getConnectString()).connectionTimeoutMs(TIMEOUT).retryPolicy(new RetryOneTime(1)).build(); - try - { + public void testServerCrash() throws Exception { + final int TIMEOUT = 1000; + + final CuratorFramework client = CuratorFrameworkFactory.builder() + .connectString(server.getConnectString()) + .connectionTimeoutMs(TIMEOUT) + .retryPolicy(new RetryOneTime(1)) + .build(); + try { client.start(); - final DistributedBarrier barrier = new DistributedBarrier(client, "/barrier"); + final DistributedBarrier barrier = new DistributedBarrier(client, "/barrier"); barrier.setBarrier(); - final ExecutorService service = Executors.newSingleThreadExecutor(); - Future future = service.submit - ( - new Callable() - { - @Override - public Object call() throws Exception - { - Thread.sleep(TIMEOUT / 2); - server.stop(); - return null; - } + final ExecutorService service = Executors.newSingleThreadExecutor(); + Future future = service.submit(new Callable() { + @Override + public Object call() throws Exception { + Thread.sleep(TIMEOUT / 2); + server.stop(); + return null; } - ); + }); barrier.waitOnBarrier(TIMEOUT * 2, TimeUnit.SECONDS); future.get(); fail(); - } - catch ( KeeperException.ConnectionLossException expected ) - { + } catch (KeeperException.ConnectionLossException expected) { // expected - } - finally - { + } finally { client.close(); } } @Test - public void testMultiClient() throws Exception - { - CuratorFramework client1 = null; - CuratorFramework client2 = null; - try - { + public void testMultiClient() throws Exception { + CuratorFramework client1 = null; + CuratorFramework client2 = null; + try { { - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); - try - { + CuratorFramework client = + CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); + try { client.start(); - DistributedBarrier barrier = new DistributedBarrier(client, "/barrier"); + DistributedBarrier barrier = new DistributedBarrier(client, "/barrier"); barrier.setBarrier(); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } @@ -105,117 +92,88 @@ public void testMultiClient() throws Exception client1 = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client2 = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); - List> futures = Lists.newArrayList(); - ExecutorService service = Executors.newCachedThreadPool(); - for ( final CuratorFramework c : new CuratorFramework[]{client1, client2} ) - { - Future future = service.submit - ( - new Callable() - { - @Override - public Object call() throws Exception - { - c.start(); - DistributedBarrier barrier = new DistributedBarrier(c, "/barrier"); - barrier.waitOnBarrier(10, TimeUnit.MILLISECONDS); - return null; - } + List> futures = Lists.newArrayList(); + ExecutorService service = Executors.newCachedThreadPool(); + for (final CuratorFramework c : new CuratorFramework[] {client1, client2}) { + Future future = service.submit(new Callable() { + @Override + public Object call() throws Exception { + c.start(); + DistributedBarrier barrier = new DistributedBarrier(c, "/barrier"); + barrier.waitOnBarrier(10, TimeUnit.MILLISECONDS); + return null; } - ); + }); futures.add(future); } Thread.sleep(1000); { - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); - try - { + CuratorFramework client = + CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); + try { client.start(); - DistributedBarrier barrier = new DistributedBarrier(client, "/barrier"); + DistributedBarrier barrier = new DistributedBarrier(client, "/barrier"); barrier.removeBarrier(); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } - for ( Future f : futures ) - { + for (Future f : futures) { f.get(); } - } - finally - { + } finally { CloseableUtils.closeQuietly(client1); CloseableUtils.closeQuietly(client2); } } @Test - public void testNoBarrier() throws Exception - { - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); - try - { + public void testNoBarrier() throws Exception { + CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); + try { client.start(); - final DistributedBarrier barrier = new DistributedBarrier(client, "/barrier"); + final DistributedBarrier barrier = new DistributedBarrier(client, "/barrier"); assertTrue(barrier.waitOnBarrier(10, TimeUnit.SECONDS)); // just for grins, test the infinite wait - ExecutorService service = Executors.newSingleThreadExecutor(); - Future future = service.submit - ( - new Callable() - { - @Override - public Object call() throws Exception - { - barrier.waitOnBarrier(); - return ""; - } + ExecutorService service = Executors.newSingleThreadExecutor(); + Future future = service.submit(new Callable() { + @Override + public Object call() throws Exception { + barrier.waitOnBarrier(); + return ""; } - ); + }); assertTrue(future.get(10, TimeUnit.SECONDS) != null); - } - finally - { + } finally { client.close(); } } @Test - public void testBasic() throws Exception - { - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); - try - { + public void testBasic() throws Exception { + CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); + try { client.start(); - final DistributedBarrier barrier = new DistributedBarrier(client, "/barrier"); + final DistributedBarrier barrier = new DistributedBarrier(client, "/barrier"); barrier.setBarrier(); - ExecutorService service = Executors.newSingleThreadExecutor(); - service.submit - ( - new Callable() - { - @Override - public Object call() throws Exception - { - Thread.sleep(1000); - barrier.removeBarrier(); - return null; - } + ExecutorService service = Executors.newSingleThreadExecutor(); + service.submit(new Callable() { + @Override + public Object call() throws Exception { + Thread.sleep(1000); + barrier.removeBarrier(); + return null; } - ); + }); assertTrue(barrier.waitOnBarrier(10, TimeUnit.SECONDS)); - } - finally - { + } finally { client.close(); } } diff --git a/curator-recipes/src/test/java/org/apache/curator/framework/recipes/barriers/TestDistributedDoubleBarrier.java b/curator-recipes/src/test/java/org/apache/curator/framework/recipes/barriers/TestDistributedDoubleBarrier.java index a8546cb22..6739a3ce9 100644 --- a/curator-recipes/src/test/java/org/apache/curator/framework/recipes/barriers/TestDistributedDoubleBarrier.java +++ b/curator-recipes/src/test/java/org/apache/curator/framework/recipes/barriers/TestDistributedDoubleBarrier.java @@ -22,14 +22,6 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import com.google.common.collect.Lists; -import org.apache.curator.test.BaseClassForTests; -import org.apache.curator.utils.CloseableUtils; -import org.apache.curator.framework.CuratorFramework; -import org.apache.curator.framework.CuratorFrameworkFactory; -import org.apache.curator.retry.RetryOneTime; -import org.apache.curator.test.Timing; -import org.junit.jupiter.api.Test; - import java.io.Closeable; import java.util.List; import java.util.concurrent.Callable; @@ -41,72 +33,66 @@ import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; +import org.apache.curator.framework.CuratorFramework; +import org.apache.curator.framework.CuratorFrameworkFactory; +import org.apache.curator.retry.RetryOneTime; +import org.apache.curator.test.BaseClassForTests; +import org.apache.curator.test.Timing; +import org.apache.curator.utils.CloseableUtils; +import org.junit.jupiter.api.Test; -public class TestDistributedDoubleBarrier extends BaseClassForTests -{ - private static final int QTY = 5; +public class TestDistributedDoubleBarrier extends BaseClassForTests { + private static final int QTY = 5; @Test - public void testMultiClient() throws Exception - { - final Timing timing = new Timing(); - final CountDownLatch postEnterLatch = new CountDownLatch(QTY); - final CountDownLatch postLeaveLatch = new CountDownLatch(QTY); - final AtomicInteger count = new AtomicInteger(0); - final AtomicInteger max = new AtomicInteger(0); - List> futures = Lists.newArrayList(); - ExecutorService service = Executors.newCachedThreadPool(); - for ( int i = 0; i < QTY; ++i ) - { - Future future = service.submit - ( - new Callable() - { - @Override - public Void call() throws Exception - { - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); - try - { - client.start(); - DistributedDoubleBarrier barrier = new DistributedDoubleBarrier(client, "/barrier", QTY); - - assertTrue(barrier.enter(timing.seconds(), TimeUnit.SECONDS)); - - synchronized(TestDistributedDoubleBarrier.this) - { - int thisCount = count.incrementAndGet(); - if ( thisCount > max.get() ) - { - max.set(thisCount); - } + public void testMultiClient() throws Exception { + final Timing timing = new Timing(); + final CountDownLatch postEnterLatch = new CountDownLatch(QTY); + final CountDownLatch postLeaveLatch = new CountDownLatch(QTY); + final AtomicInteger count = new AtomicInteger(0); + final AtomicInteger max = new AtomicInteger(0); + List> futures = Lists.newArrayList(); + ExecutorService service = Executors.newCachedThreadPool(); + for (int i = 0; i < QTY; ++i) { + Future future = service.submit(new Callable() { + @Override + public Void call() throws Exception { + CuratorFramework client = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); + try { + client.start(); + DistributedDoubleBarrier barrier = new DistributedDoubleBarrier(client, "/barrier", QTY); + + assertTrue(barrier.enter(timing.seconds(), TimeUnit.SECONDS)); + + synchronized (TestDistributedDoubleBarrier.this) { + int thisCount = count.incrementAndGet(); + if (thisCount > max.get()) { + max.set(thisCount); } + } - postEnterLatch.countDown(); - assertTrue(timing.awaitLatch(postEnterLatch)); - - assertEquals(count.get(), QTY); + postEnterLatch.countDown(); + assertTrue(timing.awaitLatch(postEnterLatch)); - assertTrue(barrier.leave(timing.seconds(), TimeUnit.SECONDS)); - count.decrementAndGet(); + assertEquals(count.get(), QTY); - postLeaveLatch.countDown(); - assertTrue(timing.awaitLatch(postEnterLatch)); - } - finally - { - CloseableUtils.closeQuietly(client); - } + assertTrue(barrier.leave(timing.seconds(), TimeUnit.SECONDS)); + count.decrementAndGet(); - return null; + postLeaveLatch.countDown(); + assertTrue(timing.awaitLatch(postEnterLatch)); + } finally { + CloseableUtils.closeQuietly(client); } + + return null; } - ); + }); futures.add(future); } - for ( Future f : futures ) - { + for (Future f : futures) { f.get(); } assertEquals(count.get(), 0); @@ -114,128 +100,104 @@ public Void call() throws Exception } @Test - public void testOverSubscribed() throws Exception - { - final Timing timing = new Timing(); - final CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); - ExecutorService service = Executors.newCachedThreadPool(); + public void testOverSubscribed() throws Exception { + final Timing timing = new Timing(); + final CuratorFramework client = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); + ExecutorService service = Executors.newCachedThreadPool(); ExecutorCompletionService completionService = new ExecutorCompletionService(service); - try - { + try { client.start(); - final Semaphore semaphore = new Semaphore(0); - final CountDownLatch latch = new CountDownLatch(1); - for ( int i = 0; i < (QTY + 1); ++i ) - { - completionService.submit - ( - new Callable() - { - @Override - public Void call() throws Exception - { - DistributedDoubleBarrier barrier = new DistributedDoubleBarrier(client, "/barrier", QTY) - { - @Override - protected List getChildrenForEntering() throws Exception - { - semaphore.release(); - assertTrue(timing.awaitLatch(latch)); - return super.getChildrenForEntering(); - } - }; - assertTrue(barrier.enter(timing.seconds(), TimeUnit.SECONDS)); - assertTrue(barrier.leave(timing.seconds(), TimeUnit.SECONDS)); - return null; - } + final Semaphore semaphore = new Semaphore(0); + final CountDownLatch latch = new CountDownLatch(1); + for (int i = 0; i < (QTY + 1); ++i) { + completionService.submit(new Callable() { + @Override + public Void call() throws Exception { + DistributedDoubleBarrier barrier = new DistributedDoubleBarrier(client, "/barrier", QTY) { + @Override + protected List getChildrenForEntering() throws Exception { + semaphore.release(); + assertTrue(timing.awaitLatch(latch)); + return super.getChildrenForEntering(); + } + }; + assertTrue(barrier.enter(timing.seconds(), TimeUnit.SECONDS)); + assertTrue(barrier.leave(timing.seconds(), TimeUnit.SECONDS)); + return null; } - ); + }); } - assertTrue(semaphore.tryAcquire(QTY + 1, timing.seconds(), TimeUnit.SECONDS)); // wait until all QTY+1 barriers are trying to enter + assertTrue(semaphore.tryAcquire( + QTY + 1, timing.seconds(), TimeUnit.SECONDS)); // wait until all QTY+1 barriers are trying to enter latch.countDown(); - for ( int i = 0; i < (QTY + 1); ++i ) - { + for (int i = 0; i < (QTY + 1); ++i) { completionService.take().get(); // to check for assertions } - } - finally - { + } finally { service.shutdown(); CloseableUtils.closeQuietly(client); } } @Test - public void testBasic() throws Exception - { - final Timing timing = new Timing(); - final List closeables = Lists.newArrayList(); - final CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); - try - { + public void testBasic() throws Exception { + final Timing timing = new Timing(); + final List closeables = Lists.newArrayList(); + final CuratorFramework client = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); + try { closeables.add(client); client.start(); - final CountDownLatch postEnterLatch = new CountDownLatch(QTY); - final CountDownLatch postLeaveLatch = new CountDownLatch(QTY); - final AtomicInteger count = new AtomicInteger(0); - final AtomicInteger max = new AtomicInteger(0); - List> futures = Lists.newArrayList(); - ExecutorService service = Executors.newCachedThreadPool(); - for ( int i = 0; i < QTY; ++i ) - { - Future future = service.submit - ( - new Callable() - { - @Override - public Void call() throws Exception - { - DistributedDoubleBarrier barrier = new DistributedDoubleBarrier(client, "/barrier", QTY); - - assertTrue(barrier.enter(timing.seconds(), TimeUnit.SECONDS)); - - synchronized(TestDistributedDoubleBarrier.this) - { - int thisCount = count.incrementAndGet(); - if ( thisCount > max.get() ) - { - max.set(thisCount); - } + final CountDownLatch postEnterLatch = new CountDownLatch(QTY); + final CountDownLatch postLeaveLatch = new CountDownLatch(QTY); + final AtomicInteger count = new AtomicInteger(0); + final AtomicInteger max = new AtomicInteger(0); + List> futures = Lists.newArrayList(); + ExecutorService service = Executors.newCachedThreadPool(); + for (int i = 0; i < QTY; ++i) { + Future future = service.submit(new Callable() { + @Override + public Void call() throws Exception { + DistributedDoubleBarrier barrier = new DistributedDoubleBarrier(client, "/barrier", QTY); + + assertTrue(barrier.enter(timing.seconds(), TimeUnit.SECONDS)); + + synchronized (TestDistributedDoubleBarrier.this) { + int thisCount = count.incrementAndGet(); + if (thisCount > max.get()) { + max.set(thisCount); } + } - postEnterLatch.countDown(); - assertTrue(timing.awaitLatch(postEnterLatch)); + postEnterLatch.countDown(); + assertTrue(timing.awaitLatch(postEnterLatch)); - assertEquals(count.get(), QTY); + assertEquals(count.get(), QTY); - assertTrue(barrier.leave(10, TimeUnit.SECONDS)); - count.decrementAndGet(); + assertTrue(barrier.leave(10, TimeUnit.SECONDS)); + count.decrementAndGet(); - postLeaveLatch.countDown(); - assertTrue(timing.awaitLatch(postLeaveLatch)); + postLeaveLatch.countDown(); + assertTrue(timing.awaitLatch(postLeaveLatch)); - return null; - } + return null; } - ); + }); futures.add(future); } - for ( Future f : futures ) - { + for (Future f : futures) { f.get(); } assertEquals(count.get(), 0); assertEquals(max.get(), QTY); - } - finally - { - for ( Closeable c : closeables ) - { + } finally { + for (Closeable c : closeables) { CloseableUtils.closeQuietly(c); } } diff --git a/curator-recipes/src/test/java/org/apache/curator/framework/recipes/cache/BaseTestTreeCache.java b/curator-recipes/src/test/java/org/apache/curator/framework/recipes/cache/BaseTestTreeCache.java index 8ab8f77a3..d5a913cae 100644 --- a/curator-recipes/src/test/java/org/apache/curator/framework/recipes/cache/BaseTestTreeCache.java +++ b/curator-recipes/src/test/java/org/apache/curator/framework/recipes/cache/BaseTestTreeCache.java @@ -19,6 +19,16 @@ package org.apache.curator.framework.recipes.cache; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.api.UnhandledErrorListener; @@ -30,20 +40,7 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.LinkedBlockingQueue; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicBoolean; - -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - -public class BaseTestTreeCache extends BaseClassForTests -{ +public class BaseTestTreeCache extends BaseClassForTests { CuratorFramework client; TreeCache cache; protected final AtomicBoolean hadBackgroundException = new AtomicBoolean(false); @@ -53,14 +50,11 @@ public class BaseTestTreeCache extends BaseClassForTests /** * Automatically records all events into an easily testable event stream. */ - final TreeCacheListener eventListener = new TreeCacheListener() - { + final TreeCacheListener eventListener = new TreeCacheListener() { @Override - public void childEvent(CuratorFramework client, TreeCacheEvent event) throws Exception - { + public void childEvent(CuratorFramework client, TreeCacheEvent event) throws Exception { // Suppress any events related to /zookeeper paths - if ( event.getData() != null && event.getData().getPath().startsWith("/zookeeper") ) - { + if (event.getData() != null && event.getData().getPath().startsWith("/zookeeper")) { return; } events.add(event); @@ -70,11 +64,9 @@ public void childEvent(CuratorFramework client, TreeCacheEvent event) throws Exc /** * Ensures that tests don't cause any background errors. */ - final UnhandledErrorListener errorListener = new UnhandledErrorListener() - { + final UnhandledErrorListener errorListener = new UnhandledErrorListener() { @Override - public void unhandledError(String message, Throwable e) - { + public void unhandledError(String message, Throwable e) { hadBackgroundException.set(true); e.printStackTrace(System.err); } @@ -83,8 +75,7 @@ public void unhandledError(String message, Throwable e) /** * Construct a TreeCache that records exceptions and automatically listens. */ - protected TreeCache newTreeCacheWithListeners(CuratorFramework client, String path) - { + protected TreeCache newTreeCacheWithListeners(CuratorFramework client, String path) { TreeCache result = new TreeCache(client, path); result.getListenable().addListener(eventListener); result.getUnhandledErrorListenable().addListener(errorListener); @@ -94,8 +85,7 @@ protected TreeCache newTreeCacheWithListeners(CuratorFramework client, String pa /** * Finish constructing a TreeCache that records exceptions and automatically listens. */ - protected TreeCache buildWithListeners(TreeCache.Builder builder) - { + protected TreeCache buildWithListeners(TreeCache.Builder builder) { TreeCache result = builder.build(); result.getListenable().addListener(eventListener); result.getUnhandledErrorListenable().addListener(errorListener); @@ -104,38 +94,30 @@ protected TreeCache buildWithListeners(TreeCache.Builder builder) @Override @BeforeEach - public void setup() throws Exception - { + public void setup() throws Exception { super.setup(); initCuratorFramework(); } - void initCuratorFramework() - { - client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); + void initCuratorFramework() { + client = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); client.start(); client.getUnhandledErrorListenable().addListener(errorListener); } @Override @AfterEach - public void teardown() throws Exception - { - try - { - try - { + public void teardown() throws Exception { + try { + try { assertFalse(hadBackgroundException.get(), "Background exceptions were thrown, see stderr for details"); assertNoMoreEvents(); - } - finally - { + } finally { CloseableUtils.closeQuietly(cache); TestCleanState.closeAndTestClean(client); } - } - finally - { + } finally { super.teardown(); } } @@ -143,70 +125,63 @@ public void teardown() throws Exception /** * Asserts the event queue is empty. */ - void assertNoMoreEvents() throws InterruptedException - { + void assertNoMoreEvents() throws InterruptedException { timing.sleepABit(); - assertTrue(events.isEmpty(), String.format("Expected no events, found %d; first event: %s", events.size(), events.peek())); + assertTrue( + events.isEmpty(), + String.format("Expected no events, found %d; first event: %s", events.size(), events.peek())); } /** * Asserts the given event is next in the queue, and consumes it from the queue. */ - TreeCacheEvent assertEvent(TreeCacheEvent.Type expectedType) throws InterruptedException - { + TreeCacheEvent assertEvent(TreeCacheEvent.Type expectedType) throws InterruptedException { return assertEvent(expectedType, null); } /** * Asserts the given event is next in the queue, and consumes it from the queue. */ - TreeCacheEvent assertEvent(TreeCacheEvent.Type expectedType, String expectedPath) throws InterruptedException - { + TreeCacheEvent assertEvent(TreeCacheEvent.Type expectedType, String expectedPath) throws InterruptedException { return assertEvent(expectedType, expectedPath, null); } /** * Asserts the given event is next in the queue, and consumes it from the queue. */ - TreeCacheEvent assertEvent(TreeCacheEvent.Type expectedType, String expectedPath, byte[] expectedData) throws InterruptedException - { + TreeCacheEvent assertEvent(TreeCacheEvent.Type expectedType, String expectedPath, byte[] expectedData) + throws InterruptedException { return assertEvent(expectedType, expectedPath, expectedData, false); } - TreeCacheEvent assertEvent(TreeCacheEvent.Type expectedType, String expectedPath, byte[] expectedData, boolean ignoreConnectionEvents) throws InterruptedException - { + TreeCacheEvent assertEvent( + TreeCacheEvent.Type expectedType, String expectedPath, byte[] expectedData, boolean ignoreConnectionEvents) + throws InterruptedException { TreeCacheEvent event = events.poll(timing.forWaiting().seconds(), TimeUnit.SECONDS); assertNotNull(event, String.format("Expected type: %s, path: %s", expectedType, expectedPath)); - if ( ignoreConnectionEvents ) - { - if ( (event.getType() == TreeCacheEvent.Type.CONNECTION_SUSPENDED) || (event.getType() == TreeCacheEvent.Type.CONNECTION_LOST) || (event.getType() == TreeCacheEvent.Type.CONNECTION_RECONNECTED) ) - { + if (ignoreConnectionEvents) { + if ((event.getType() == TreeCacheEvent.Type.CONNECTION_SUSPENDED) + || (event.getType() == TreeCacheEvent.Type.CONNECTION_LOST) + || (event.getType() == TreeCacheEvent.Type.CONNECTION_RECONNECTED)) { return assertEvent(expectedType, expectedPath, expectedData, ignoreConnectionEvents); } } String message = event.toString(); assertEquals(event.getType(), expectedType, message); - if ( expectedPath == null ) - { + if (expectedPath == null) { assertNull(event.getData(), message); - } - else - { + } else { assertNotNull(event.getData(), message); assertEquals(event.getData().getPath(), expectedPath, message); } - if ( expectedData != null ) - { + if (expectedData != null) { assertArrayEquals(event.getData().getData(), expectedData, message); } - if ( event.getType() == TreeCacheEvent.Type.NODE_UPDATED) - { + if (event.getType() == TreeCacheEvent.Type.NODE_UPDATED) { assertNotNull(event.getOldData()); - } - else - { + } else { assertNull(event.getOldData()); } diff --git a/curator-recipes/src/test/java/org/apache/curator/framework/recipes/cache/TestCuratorCache.java b/curator-recipes/src/test/java/org/apache/curator/framework/recipes/cache/TestCuratorCache.java index b8a4b28df..411a51af1 100644 --- a/curator-recipes/src/test/java/org/apache/curator/framework/recipes/cache/TestCuratorCache.java +++ b/curator-recipes/src/test/java/org/apache/curator/framework/recipes/cache/TestCuratorCache.java @@ -23,7 +23,9 @@ import static org.apache.curator.framework.recipes.cache.CuratorCacheListener.builder; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; - +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Semaphore; +import java.util.concurrent.atomic.AtomicInteger; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.retry.RetryOneTime; @@ -31,27 +33,28 @@ import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.Semaphore; -import java.util.concurrent.atomic.AtomicInteger; - @Tag(CuratorTestBase.zk36Group) -public class TestCuratorCache extends CuratorTestBase -{ +public class TestCuratorCache extends CuratorTestBase { @Test public void testUpdateWhenNotCachingData() throws Exception // mostly copied from TestPathChildrenCache - { + { CuratorCacheStorage storage = new StandardCuratorCacheStorage(false); - try (CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1))) - { + try (CuratorFramework client = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1))) { client.start(); final CountDownLatch updatedLatch = new CountDownLatch(1); final CountDownLatch addedLatch = new CountDownLatch(1); client.create().creatingParentsIfNeeded().forPath("/test"); - try (CuratorCache cache = CuratorCache.builder(client, "/test").withStorage(storage).build()) - { - cache.listenable().addListener(builder().forChanges((__, ___) -> updatedLatch.countDown()).build()); - cache.listenable().addListener(builder().forCreates(__ -> addedLatch.countDown()).build()); + try (CuratorCache cache = + CuratorCache.builder(client, "/test").withStorage(storage).build()) { + cache.listenable() + .addListener(builder() + .forChanges((__, ___) -> updatedLatch.countDown()) + .build()); + cache.listenable() + .addListener(builder() + .forCreates(__ -> addedLatch.countDown()) + .build()); cache.start(); client.create().forPath("/test/foo", "first".getBytes()); @@ -64,34 +67,31 @@ public void testUpdateWhenNotCachingData() throws Exception // mostly copied fro } @Test - public void testAfterInitialized() throws Exception - { - try (CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1))) - { + public void testAfterInitialized() throws Exception { + try (CuratorFramework client = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1))) { client.start(); client.create().creatingParentsIfNeeded().forPath("/test"); client.create().creatingParentsIfNeeded().forPath("/test/one"); client.create().creatingParentsIfNeeded().forPath("/test/one/two"); client.create().creatingParentsIfNeeded().forPath("/test/one/two/three"); - try (CuratorCache cache = CuratorCache.build(client, "/test")) - { + try (CuratorCache cache = CuratorCache.build(client, "/test")) { CountDownLatch initializedLatch = new CountDownLatch(1); AtomicInteger eventCount = new AtomicInteger(0); - CuratorCacheListener listener = new CuratorCacheListener() - { + CuratorCacheListener listener = new CuratorCacheListener() { @Override - public void event(Type type, ChildData oldData, ChildData data) - { + public void event(Type type, ChildData oldData, ChildData data) { eventCount.incrementAndGet(); } @Override - public void initialized() - { + public void initialized() { initializedLatch.countDown(); } }; - cache.listenable().addListener(builder().forAll(listener).afterInitialized().build()); + cache.listenable() + .addListener( + builder().forAll(listener).afterInitialized().build()); cache.start(); assertTrue(timing.awaitLatch(initializedLatch)); @@ -106,20 +106,24 @@ public void initialized() } @Test - public void testListenerBuilder() throws Exception - { - try (CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1))) - { + public void testListenerBuilder() throws Exception { + try (CuratorFramework client = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1))) { client.start(); - try (CuratorCache cache = CuratorCache.build(client, "/test")) - { + try (CuratorCache cache = CuratorCache.build(client, "/test")) { Semaphore all = new Semaphore(0); Semaphore deletes = new Semaphore(0); Semaphore changes = new Semaphore(0); Semaphore creates = new Semaphore(0); Semaphore createsAndChanges = new Semaphore(0); - CuratorCacheListener listener = builder().forAll((__, ___, ____) -> all.release()).forDeletes(__ -> deletes.release()).forChanges((__, ___) -> changes.release()).forCreates(__ -> creates.release()).forCreatesAndChanges((__, ___) -> createsAndChanges.release()).build(); + CuratorCacheListener listener = builder() + .forAll((__, ___, ____) -> all.release()) + .forDeletes(__ -> deletes.release()) + .forChanges((__, ___) -> changes.release()) + .forCreates(__ -> creates.release()) + .forCreatesAndChanges((__, ___) -> createsAndChanges.release()) + .build(); cache.listenable().addListener(listener); cache.start(); @@ -148,17 +152,17 @@ public void testListenerBuilder() throws Exception } @Test - public void testClearOnClose() throws Exception - { - try (CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1))) - { + public void testClearOnClose() throws Exception { + try (CuratorFramework client = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1))) { CuratorCacheStorage storage; client.start(); - try ( CuratorCache cache = CuratorCache.builder(client, "/test").withOptions(DO_NOT_CLEAR_ON_CLOSE).build() ) - { + try (CuratorCache cache = CuratorCache.builder(client, "/test") + .withOptions(DO_NOT_CLEAR_ON_CLOSE) + .build()) { cache.start(); - storage = ((CuratorCacheImpl)cache).storage(); + storage = ((CuratorCacheImpl) cache).storage(); client.create().forPath("/test", "foo".getBytes()); client.create().forPath("/test/bar", "bar".getBytes()); @@ -166,10 +170,9 @@ public void testClearOnClose() throws Exception } assertEquals(storage.size(), 2); - try ( CuratorCache cache = CuratorCache.build(client, "/test") ) - { + try (CuratorCache cache = CuratorCache.build(client, "/test")) { cache.start(); - storage = ((CuratorCacheImpl)cache).storage(); + storage = ((CuratorCacheImpl) cache).storage(); timing.sleepABit(); } diff --git a/curator-recipes/src/test/java/org/apache/curator/framework/recipes/cache/TestCuratorCacheBridge.java b/curator-recipes/src/test/java/org/apache/curator/framework/recipes/cache/TestCuratorCacheBridge.java index 69b006278..bc7d856c8 100644 --- a/curator-recipes/src/test/java/org/apache/curator/framework/recipes/cache/TestCuratorCacheBridge.java +++ b/curator-recipes/src/test/java/org/apache/curator/framework/recipes/cache/TestCuratorCacheBridge.java @@ -21,7 +21,6 @@ import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; - import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.retry.RetryOneTime; @@ -29,21 +28,17 @@ import org.apache.curator.utils.Compatibility; import org.junit.jupiter.api.Test; -public class TestCuratorCacheBridge extends CuratorTestBase -{ +public class TestCuratorCacheBridge extends CuratorTestBase { @Test - public void testImplementationSelection() - { - try (CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1))) - { - CuratorCacheBridge cache = CuratorCache.bridgeBuilder(client, "/foo").build(); - if ( Compatibility.hasPersistentWatchers() ) - { + public void testImplementationSelection() { + try (CuratorFramework client = + CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1))) { + CuratorCacheBridge cache = + CuratorCache.bridgeBuilder(client, "/foo").build(); + if (Compatibility.hasPersistentWatchers()) { assertTrue(cache instanceof CuratorCacheImpl); assertTrue(cache.isCuratorCache()); - } - else - { + } else { assertTrue(cache instanceof CompatibleCuratorCacheBridge); assertFalse(cache.isCuratorCache()); } @@ -51,17 +46,15 @@ public void testImplementationSelection() } @Test - public void testForceTreeCache() - { + public void testForceTreeCache() { System.setProperty("curator-cache-bridge-force-tree-cache", "true"); - try (CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1))) - { - CuratorCacheBridge cache = CuratorCache.bridgeBuilder(client, "/foo").build(); + try (CuratorFramework client = + CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1))) { + CuratorCacheBridge cache = + CuratorCache.bridgeBuilder(client, "/foo").build(); assertTrue(cache instanceof CompatibleCuratorCacheBridge); assertFalse(cache.isCuratorCache()); - } - finally - { + } finally { System.clearProperty("curator-cache-bridge-force-tree-cache"); } } diff --git a/curator-recipes/src/test/java/org/apache/curator/framework/recipes/cache/TestCuratorCacheConsistency.java b/curator-recipes/src/test/java/org/apache/curator/framework/recipes/cache/TestCuratorCacheConsistency.java index f9ae96eac..4aaca73e0 100644 --- a/curator-recipes/src/test/java/org/apache/curator/framework/recipes/cache/TestCuratorCacheConsistency.java +++ b/curator-recipes/src/test/java/org/apache/curator/framework/recipes/cache/TestCuratorCacheConsistency.java @@ -22,18 +22,6 @@ import static org.apache.curator.framework.recipes.cache.CuratorCache.Options.DO_NOT_CLEAR_ON_CLOSE; import static org.apache.curator.framework.recipes.cache.CuratorCacheListener.builder; import static org.junit.jupiter.api.Assertions.fail; - -import org.apache.curator.framework.CuratorFramework; -import org.apache.curator.framework.CuratorFrameworkFactory; -import org.apache.curator.retry.ExponentialBackoffRetry; -import org.apache.curator.test.InstanceSpec; -import org.apache.curator.test.TestingCluster; -import org.apache.curator.test.compatibility.CuratorTestBase; -import org.apache.curator.utils.ZKPaths; -import org.junit.jupiter.api.Tag; -import org.junit.jupiter.api.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import java.io.Closeable; import java.time.Duration; import java.time.Instant; @@ -48,14 +36,24 @@ import java.util.concurrent.atomic.AtomicReference; import java.util.stream.Collectors; import java.util.stream.IntStream; +import org.apache.curator.framework.CuratorFramework; +import org.apache.curator.framework.CuratorFrameworkFactory; +import org.apache.curator.retry.ExponentialBackoffRetry; +import org.apache.curator.test.InstanceSpec; +import org.apache.curator.test.TestingCluster; +import org.apache.curator.test.compatibility.CuratorTestBase; +import org.apache.curator.utils.ZKPaths; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * Randomly create nodes in a tree while a set of CuratorCaches listens. Afterwards, validate * that the caches contain the same values as ZK itself */ @Tag(CuratorTestBase.zk36Group) -public class TestCuratorCacheConsistency extends CuratorTestBase -{ +public class TestCuratorCacheConsistency extends CuratorTestBase { private final Logger log = LoggerFactory.getLogger(getClass()); private final ThreadLocalRandom random = ThreadLocalRandom.current(); @@ -68,60 +66,62 @@ public class TestCuratorCacheConsistency extends CuratorTestBase private static final String BASE_PATH = "/test"; - private class Client implements Closeable - { + private class Client implements Closeable { private final CuratorFramework client; private final CuratorCache cache; private final int index; private final Map listenerDataMap = new HashMap<>(); - Client(int index, String connectionString, AtomicReference errorSignal) - { + Client(int index, String connectionString, AtomicReference errorSignal) { this.index = index; client = buildClient(connectionString); - cache = CuratorCache.builder(client, BASE_PATH).withOptions(DO_NOT_CLEAR_ON_CLOSE).withExceptionHandler(errorSignal::set).build(); + cache = CuratorCache.builder(client, BASE_PATH) + .withOptions(DO_NOT_CLEAR_ON_CLOSE) + .withExceptionHandler(errorSignal::set) + .build(); // listenerDataMap is a local data map that will hold values sent by listeners // this way, the listener code can be tested for validity and consistency - CuratorCacheListener listener = builder().forCreates(node -> { - ChildData previous = listenerDataMap.put(node.getPath(), node); - if ( previous != null ) - { - errorSignal.set(new Exception(String.format("Client: %d - Create for existing node: %s", index, node.getPath()))); - } - }).forChanges((oldNode, node) -> { - ChildData previous = listenerDataMap.put(node.getPath(), node); - if ( (previous == null) || !Arrays.equals(previous.getData(), oldNode.getData()) ) - { - errorSignal.set(new Exception(String.format("Client: %d - Bad old value for change node: %s", index, node.getPath()))); - } - }).forDeletes(node -> { - ChildData previous = listenerDataMap.remove(node.getPath()); - if ( previous == null ) - { - errorSignal.set(new Exception(String.format("Client: %d - Delete for non-existent node: %s", index, node.getPath()))); - } - }).build(); + CuratorCacheListener listener = builder() + .forCreates(node -> { + ChildData previous = listenerDataMap.put(node.getPath(), node); + if (previous != null) { + errorSignal.set(new Exception( + String.format("Client: %d - Create for existing node: %s", index, node.getPath()))); + } + }) + .forChanges((oldNode, node) -> { + ChildData previous = listenerDataMap.put(node.getPath(), node); + if ((previous == null) || !Arrays.equals(previous.getData(), oldNode.getData())) { + errorSignal.set(new Exception(String.format( + "Client: %d - Bad old value for change node: %s", index, node.getPath()))); + } + }) + .forDeletes(node -> { + ChildData previous = listenerDataMap.remove(node.getPath()); + if (previous == null) { + errorSignal.set(new Exception(String.format( + "Client: %d - Delete for non-existent node: %s", index, node.getPath()))); + } + }) + .build(); cache.listenable().addListener(listener); } - void start() - { + void start() { client.start(); cache.start(); } @Override - public void close() - { + public void close() { cache.close(); client.close(); } } @Test - public void testConsistencyAfterSimulation() throws Exception - { + public void testConsistencyAfterSimulation() throws Exception { int clientQty = random.nextInt(10, 20); int maxDepth = random.nextInt(5, 10); @@ -131,21 +131,17 @@ public void testConsistencyAfterSimulation() throws Exception Map actualTree; AtomicReference errorSignal = new AtomicReference<>(); - try (TestingCluster cluster = new TestingCluster(clusterSize)) - { + try (TestingCluster cluster = new TestingCluster(clusterSize)) { cluster.start(); initializeBasePath(cluster); - try - { + try { clients = buildClients(cluster, clientQty, errorSignal); workLoop(cluster, clients, maxDepth, errorSignal); log.info("Test complete - sleeping to allow events to complete"); timing.sleepABit(); - } - finally - { + } finally { clients.forEach(Client::close); } @@ -155,11 +151,10 @@ public void testConsistencyAfterSimulation() throws Exception log.info("client qty: {}", clientQty); Map> errorsList = clients.stream() - .map(client -> findErrors(client, actualTree)) - .filter(errorsEntry -> !errorsEntry.getValue().isEmpty()) - .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); - if ( !errorsList.isEmpty() ) - { + .map(client -> findErrors(client, actualTree)) + .filter(errorsEntry -> !errorsEntry.getValue().isEmpty()) + .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); + if (!errorsList.isEmpty()) { log.error("{} clients had errors", errorsList.size()); errorsList.forEach((index, errorList) -> { log.error("Client {}", index); @@ -172,73 +167,62 @@ public void testConsistencyAfterSimulation() throws Exception } // build a data map recursively from the actual values in ZK - private Map buildActual(TestingCluster cluster) - { + private Map buildActual(TestingCluster cluster) { Map actual = new HashMap<>(); - try (CuratorFramework client = buildClient(cluster.getConnectString())) - { + try (CuratorFramework client = buildClient(cluster.getConnectString())) { client.start(); buildActual(client, actual, BASE_PATH); } return actual; } - private void buildActual(CuratorFramework client, Map actual, String fromPath) - { - try - { + private void buildActual(CuratorFramework client, Map actual, String fromPath) { + try { byte[] bytes = client.getData().forPath(fromPath); actual.put(fromPath, new String(bytes)); - client.getChildren().forPath(fromPath).forEach(child -> buildActual(client, actual, ZKPaths.makePath(fromPath, child))); - } - catch ( Exception e ) - { + client.getChildren() + .forPath(fromPath) + .forEach(child -> buildActual(client, actual, ZKPaths.makePath(fromPath, child))); + } catch (Exception e) { fail("", e); } } - private List buildClients(TestingCluster cluster, int clientQty, AtomicReference errorSignal) - { + private List buildClients(TestingCluster cluster, int clientQty, AtomicReference errorSignal) { return IntStream.range(0, clientQty) - .mapToObj(index -> new Client(index, cluster.getConnectString(), errorSignal)) - .peek(Client::start) - .collect(Collectors.toList()); + .mapToObj(index -> new Client(index, cluster.getConnectString(), errorSignal)) + .peek(Client::start) + .collect(Collectors.toList()); } - private void initializeBasePath(TestingCluster cluster) throws Exception - { - try (CuratorFramework client = buildClient(cluster.getConnectString())) - { + private void initializeBasePath(TestingCluster cluster) throws Exception { + try (CuratorFramework client = buildClient(cluster.getConnectString())) { client.start(); client.create().forPath(BASE_PATH, "".getBytes()); } } - private void workLoop(TestingCluster cluster, List clients, int maxDepth, AtomicReference errorSignal) throws Exception - { + private void workLoop( + TestingCluster cluster, List clients, int maxDepth, AtomicReference errorSignal) + throws Exception { Instant start = Instant.now(); Instant lastServerKill = Instant.now(); int serverKillIndex = 0; - while ( true ) - { + while (true) { Duration elapsed = Duration.between(start, Instant.now()); - if ( elapsed.compareTo(testLength) >= 0 ) - { + if (elapsed.compareTo(testLength) >= 0) { break; } Exception errorSignalException = errorSignal.get(); - if ( errorSignalException != null ) - { + if (errorSignalException != null) { fail("A client's error handler was called", errorSignalException); } Duration elapsedFromLastServerKill = Duration.between(lastServerKill, Instant.now()); - if ( elapsedFromLastServerKill.compareTo(thirdOfTestLength) >= 0 ) - { + if (elapsedFromLastServerKill.compareTo(thirdOfTestLength) >= 0) { lastServerKill = Instant.now(); - if ( serverKillIndex < maxServerKills ) - { + if (serverKillIndex < maxServerKills) { doKillServer(cluster, serverKillIndex++); } } @@ -246,12 +230,9 @@ private void workLoop(TestingCluster cluster, List clients, int maxDepth int thisDepth = random.nextInt(0, maxDepth); String thisPath = randomPath(thisDepth); CuratorFramework client = randomClient(clients); - if ( random.nextBoolean() ) - { + if (random.nextBoolean()) { doDelete(client, thisPath); - } - else - { + } else { doChange(client, thisPath); } @@ -259,89 +240,67 @@ private void workLoop(TestingCluster cluster, List clients, int maxDepth } } - private void doChange(CuratorFramework client, String thisPath) - { - try - { + private void doChange(CuratorFramework client, String thisPath) { + try { String thisData = Long.toString(random.nextLong()); client.create().orSetData().creatingParentsIfNeeded().forPath(thisPath, thisData.getBytes()); - } - catch ( Exception e ) - { + } catch (Exception e) { fail("Could not create/set: " + thisPath); } } - private void doDelete(CuratorFramework client, String thisPath) - { - if ( thisPath.equals(BASE_PATH) ) - { + private void doDelete(CuratorFramework client, String thisPath) { + if (thisPath.equals(BASE_PATH)) { return; } - try - { + try { client.delete().quietly().deletingChildrenIfNeeded().forPath(thisPath); - } - catch ( Exception e ) - { + } catch (Exception e) { fail("Could not delete: " + thisPath); } } - private void doKillServer(TestingCluster cluster, int serverKillIndex) throws Exception - { + private void doKillServer(TestingCluster cluster, int serverKillIndex) throws Exception { log.info("Killing server {}", serverKillIndex); InstanceSpec killSpec = new ArrayList<>(cluster.getInstances()).get(serverKillIndex); cluster.killServer(killSpec); } - private CuratorFramework randomClient(List clients) - { + private CuratorFramework randomClient(List clients) { return clients.get(random.nextInt(clients.size())).client; } - private Map.Entry> findErrors(Client client, Map tree) - { - CuratorCacheStorage storage = ((CuratorCacheImpl)client.cache).storage(); + private Map.Entry> findErrors(Client client, Map tree) { + CuratorCacheStorage storage = ((CuratorCacheImpl) client.cache).storage(); List errors = new ArrayList<>(); - if ( tree.size() != storage.size() ) - { + if (tree.size() != storage.size()) { errors.add(String.format("Size mismatch. Expected: %d - Actual: %d", tree.size(), storage.size())); } tree.keySet().forEach(path -> { - if ( !storage.get(path).isPresent() ) - { + if (!storage.get(path).isPresent()) { errors.add(String.format("Path %s in master but not client", path)); } }); storage.stream().forEach(data -> { String treeValue = tree.get(data.getPath()); - if ( treeValue != null ) - { - if ( !treeValue.equals(new String(data.getData())) ) - { + if (treeValue != null) { + if (!treeValue.equals(new String(data.getData()))) { errors.add(String.format("Data at %s is not the same", data.getPath())); } ChildData listenersMapData = client.listenerDataMap.get(data.getPath()); - if ( listenersMapData == null ) - { + if (listenersMapData == null) { errors.add(String.format("listenersMap missing data at: %s", data.getPath())); - } - else if ( !treeValue.equals(new String(listenersMapData.getData())) ) - { + } else if (!treeValue.equals(new String(listenersMapData.getData()))) { errors.add(String.format("Data at %s in listenersMap is not the same", data.getPath())); } - } - else - { + } else { errors.add(String.format("Path %s in client but not master", data.getPath())); } }); client.listenerDataMap.keySet().forEach(path -> { - if ( !storage.get(path).isPresent() ) - { + if (!storage.get(path).isPresent()) { errors.add(String.format("Path %s in listenersMap but not storage", path)); } }); @@ -349,11 +308,9 @@ else if ( !treeValue.equals(new String(listenersMapData.getData())) ) return new AbstractMap.SimpleEntry<>(client.index, errors); } - private String randomPath(int depth) - { + private String randomPath(int depth) { StringBuilder str = new StringBuilder(BASE_PATH); - while ( depth-- > 0 ) - { + while (depth-- > 0) { int levelNodeName = random.nextInt(nodesPerLevel); str.append("/").append(levelNodeName); } @@ -361,14 +318,12 @@ private String randomPath(int depth) } @Override - protected void createServer() - { + protected void createServer() { // do nothing - we'll be using TestingCluster instead } - private CuratorFramework buildClient(String connectionString) - { + private CuratorFramework buildClient(String connectionString) { ExponentialBackoffRetry retryPolicy = new ExponentialBackoffRetry(100, 100); return CuratorFrameworkFactory.newClient(connectionString, timing.session(), timing.connection(), retryPolicy); } -} \ No newline at end of file +} diff --git a/curator-recipes/src/test/java/org/apache/curator/framework/recipes/cache/TestCuratorCacheEdges.java b/curator-recipes/src/test/java/org/apache/curator/framework/recipes/cache/TestCuratorCacheEdges.java index 9c8f2882d..85725da10 100644 --- a/curator-recipes/src/test/java/org/apache/curator/framework/recipes/cache/TestCuratorCacheEdges.java +++ b/curator-recipes/src/test/java/org/apache/curator/framework/recipes/cache/TestCuratorCacheEdges.java @@ -23,7 +23,7 @@ import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; - +import java.util.concurrent.CountDownLatch; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.state.ConnectionState; @@ -34,19 +34,15 @@ import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; -import java.util.concurrent.CountDownLatch; - @Tag(CuratorTestBase.zk36Group) -public class TestCuratorCacheEdges extends CuratorTestBase -{ +public class TestCuratorCacheEdges extends CuratorTestBase { @Test - public void testReconnectConsistency() throws Exception - { + public void testReconnectConsistency() throws Exception { final byte[] first = "one".getBytes(); final byte[] second = "two".getBytes(); - try (CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1))) - { + try (CuratorFramework client = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1))) { client.start(); client.create().forPath("/root", first); client.create().forPath("/root/1", first); @@ -58,10 +54,15 @@ public void testReconnectConsistency() throws Exception client.create().forPath("/root/2/22", first); CuratorCacheStorage storage = CuratorCacheStorage.standard(); - try (CuratorCache cache = CuratorCache.builder(client, "/root").withStorage(storage).withOptions(DO_NOT_CLEAR_ON_CLOSE).build()) - { + try (CuratorCache cache = CuratorCache.builder(client, "/root") + .withStorage(storage) + .withOptions(DO_NOT_CLEAR_ON_CLOSE) + .build()) { CountDownLatch latch = new CountDownLatch(1); - cache.listenable().addListener(CuratorCacheListener.builder().forInitialized(latch::countDown).build()); + cache.listenable() + .addListener(CuratorCacheListener.builder() + .forInitialized(latch::countDown) + .build()); cache.start(); assertTrue(timing.awaitLatch(latch)); } @@ -82,10 +83,15 @@ public void testReconnectConsistency() throws Exception client.create().forPath("/root/1/13/132", second); client.create().forPath("/root/1/13/132/1321", second); - try (CuratorCache cache = CuratorCache.builder(client, "/root").withStorage(storage).withOptions(DO_NOT_CLEAR_ON_CLOSE).build()) - { + try (CuratorCache cache = CuratorCache.builder(client, "/root") + .withStorage(storage) + .withOptions(DO_NOT_CLEAR_ON_CLOSE) + .build()) { CountDownLatch latch = new CountDownLatch(1); - cache.listenable().addListener(CuratorCacheListener.builder().forInitialized(latch::countDown).build()); + cache.listenable() + .addListener(CuratorCacheListener.builder() + .forInitialized(latch::countDown) + .build()); cache.start(); assertTrue(timing.awaitLatch(latch)); } @@ -94,37 +100,40 @@ public void testReconnectConsistency() throws Exception assertArrayEquals(storage.get("/root").map(ChildData::getData).orElse(null), second); assertArrayEquals(storage.get("/root/1").map(ChildData::getData).orElse(null), first); assertArrayEquals(storage.get("/root/1/11").map(ChildData::getData).orElse(null), first); - assertArrayEquals(storage.get("/root/1/11/111").map(ChildData::getData).orElse(null), second); - assertArrayEquals(storage.get("/root/1/11/111/1111").map(ChildData::getData).orElse(null), second); - assertArrayEquals(storage.get("/root/1/11/111/1112").map(ChildData::getData).orElse(null), second); + assertArrayEquals( + storage.get("/root/1/11/111").map(ChildData::getData).orElse(null), second); + assertArrayEquals( + storage.get("/root/1/11/111/1111").map(ChildData::getData).orElse(null), second); + assertArrayEquals( + storage.get("/root/1/11/111/1112").map(ChildData::getData).orElse(null), second); assertArrayEquals(storage.get("/root/1/12").map(ChildData::getData).orElse(null), first); assertArrayEquals(storage.get("/root/1/13").map(ChildData::getData).orElse(null), first); - assertArrayEquals(storage.get("/root/1/13/131").map(ChildData::getData).orElse(null), second); - assertArrayEquals(storage.get("/root/1/13/132").map(ChildData::getData).orElse(null), second); - assertArrayEquals(storage.get("/root/1/13/132/1321").map(ChildData::getData).orElse(null), second); + assertArrayEquals( + storage.get("/root/1/13/131").map(ChildData::getData).orElse(null), second); + assertArrayEquals( + storage.get("/root/1/13/132").map(ChildData::getData).orElse(null), second); + assertArrayEquals( + storage.get("/root/1/13/132/1321").map(ChildData::getData).orElse(null), second); } } @Test - public void testServerLoss() throws Exception // mostly copied from TestPathChildrenCacheInCluster - { - try (TestingCluster cluster = new TestingCluster(3)) - { + public void testServerLoss() throws Exception // mostly copied from TestPathChildrenCacheInCluster + { + try (TestingCluster cluster = new TestingCluster(3)) { cluster.start(); - try (CuratorFramework client = CuratorFrameworkFactory.newClient(cluster.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1))) - { + try (CuratorFramework client = CuratorFrameworkFactory.newClient( + cluster.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1))) { client.start(); client.create().creatingParentsIfNeeded().forPath("/test"); - try (CuratorCache cache = CuratorCache.build(client, "/test")) - { + try (CuratorCache cache = CuratorCache.build(client, "/test")) { cache.start(); CountDownLatch reconnectLatch = new CountDownLatch(1); client.getConnectionStateListenable().addListener((__, newState) -> { - if ( newState == ConnectionState.RECONNECTED ) - { + if (newState == ConnectionState.RECONNECTED) { reconnectLatch.countDown(); } }); @@ -137,7 +146,8 @@ public void testServerLoss() throws Exception // mostly copied from TestPathCh assertTrue(timing.awaitLatch(latch)); - InstanceSpec connectionInstance = cluster.findConnectionInstance(client.getZookeeperClient().getZooKeeper()); + InstanceSpec connectionInstance = cluster.findConnectionInstance( + client.getZookeeperClient().getZooKeeper()); cluster.killServer(connectionInstance); assertTrue(timing.awaitLatch(reconnectLatch)); diff --git a/curator-recipes/src/test/java/org/apache/curator/framework/recipes/cache/TestCuratorCacheEventOrdering.java b/curator-recipes/src/test/java/org/apache/curator/framework/recipes/cache/TestCuratorCacheEventOrdering.java index 18a0fc977..9b617d68a 100644 --- a/curator-recipes/src/test/java/org/apache/curator/framework/recipes/cache/TestCuratorCacheEventOrdering.java +++ b/curator-recipes/src/test/java/org/apache/curator/framework/recipes/cache/TestCuratorCacheEventOrdering.java @@ -19,31 +19,25 @@ package org.apache.curator.framework.recipes.cache; +import java.util.concurrent.BlockingQueue; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.test.compatibility.CuratorTestBase; import org.junit.jupiter.api.Tag; -import java.util.concurrent.BlockingQueue; @Tag(CuratorTestBase.zk36Group) -public class TestCuratorCacheEventOrdering extends TestEventOrdering -{ +public class TestCuratorCacheEventOrdering extends TestEventOrdering { @Override - protected int getActualQty(CuratorCache cache) - { + protected int getActualQty(CuratorCache cache) { return cache.size(); } @Override - protected CuratorCache newCache(CuratorFramework client, String path, BlockingQueue events) - { + protected CuratorCache newCache(CuratorFramework client, String path, BlockingQueue events) { CuratorCache cache = CuratorCache.build(client, path); cache.listenable().addListener((type, oldNode, node) -> { - if ( type == CuratorCacheListener.Type.NODE_CREATED ) - { + if (type == CuratorCacheListener.Type.NODE_CREATED) { events.add(new Event(EventType.ADDED, node.getPath())); - } - else if ( type == CuratorCacheListener.Type.NODE_DELETED ) - { + } else if (type == CuratorCacheListener.Type.NODE_DELETED) { events.add(new Event(EventType.DELETED, oldNode.getPath())); } }); diff --git a/curator-recipes/src/test/java/org/apache/curator/framework/recipes/cache/TestCuratorCacheWrappers.java b/curator-recipes/src/test/java/org/apache/curator/framework/recipes/cache/TestCuratorCacheWrappers.java index 0e44d3419..f519bc441 100644 --- a/curator-recipes/src/test/java/org/apache/curator/framework/recipes/cache/TestCuratorCacheWrappers.java +++ b/curator-recipes/src/test/java/org/apache/curator/framework/recipes/cache/TestCuratorCacheWrappers.java @@ -28,58 +28,67 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; import com.google.common.collect.ImmutableSet; -import org.apache.curator.framework.CuratorFramework; -import org.apache.curator.framework.CuratorFrameworkFactory; -import org.apache.curator.retry.RetryOneTime; -import org.apache.curator.test.compatibility.CuratorTestBase; -import org.junit.jupiter.api.Tag; -import org.junit.jupiter.api.Test; - import java.util.AbstractMap; import java.util.Map; import java.util.concurrent.BlockingQueue; +import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; import java.util.function.Supplier; import java.util.stream.Collectors; import java.util.stream.Stream; -import java.util.concurrent.CopyOnWriteArrayList; +import org.apache.curator.framework.CuratorFramework; +import org.apache.curator.framework.CuratorFrameworkFactory; +import org.apache.curator.retry.RetryOneTime; +import org.apache.curator.test.compatibility.CuratorTestBase; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; @Tag(CuratorTestBase.zk36Group) -public class TestCuratorCacheWrappers extends CuratorTestBase -{ +public class TestCuratorCacheWrappers extends CuratorTestBase { @Test - public void testPathChildrenCache() throws Exception // copied from TestPathChildrenCache#testBasics() - { - try (CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1))) - { + public void testPathChildrenCache() throws Exception // copied from TestPathChildrenCache#testBasics() + { + try (CuratorFramework client = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1))) { client.start(); client.create().forPath("/test"); final CopyOnWriteArrayList eventsTrace = new CopyOnWriteArrayList<>(); final BlockingQueue events = new LinkedBlockingQueue<>(); - try (CuratorCache cache = CuratorCache.build(client, "/test")) - { + try (CuratorCache cache = CuratorCache.build(client, "/test")) { PathChildrenCacheListener listener = (__, event) -> { eventsTrace.add(event); - if ( event.getData().getPath().equals("/test/one") ) - { + if (event.getData().getPath().equals("/test/one")) { events.offer(event.getType()); } }; - cache.listenable().addListener(builder().forPathChildrenCache("/test", client, listener).build()); + cache.listenable() + .addListener(builder() + .forPathChildrenCache("/test", client, listener) + .build()); cache.start(); client.create().forPath("/test/one", "hey there".getBytes()); - assertEquals(events.poll(timing.forWaiting().seconds(), TimeUnit.SECONDS), PathChildrenCacheEvent.Type.CHILD_ADDED); + assertEquals( + events.poll(timing.forWaiting().seconds(), TimeUnit.SECONDS), + PathChildrenCacheEvent.Type.CHILD_ADDED); client.setData().forPath("/test/one", "sup!".getBytes()); - assertEquals(events.poll(timing.forWaiting().seconds(), TimeUnit.SECONDS), PathChildrenCacheEvent.Type.CHILD_UPDATED); - assertEquals(new String(cache.get("/test/one").orElseThrow(AssertionError::new).getData()), "sup!"); + assertEquals( + events.poll(timing.forWaiting().seconds(), TimeUnit.SECONDS), + PathChildrenCacheEvent.Type.CHILD_UPDATED); + assertEquals( + new String(cache.get("/test/one") + .orElseThrow(AssertionError::new) + .getData()), + "sup!"); client.delete().forPath("/test/one"); - assertEquals(events.poll(timing.forWaiting().seconds(), TimeUnit.SECONDS), PathChildrenCacheEvent.Type.CHILD_REMOVED); + assertEquals( + events.poll(timing.forWaiting().seconds(), TimeUnit.SECONDS), + PathChildrenCacheEvent.Type.CHILD_REMOVED); // Please note that there is not guarantee on the order of events // For instance INITIALIZED event can appear in the middle of the observed sequence. @@ -103,67 +112,83 @@ public void testPathChildrenCache() throws Exception // copied from TestPathC } @Test - public void testTreeCache() throws Exception // copied from TestTreeCache#testBasics() - { + public void testTreeCache() throws Exception // copied from TestTreeCache#testBasics() + { BaseTestTreeCache treeCacheBase = new BaseTestTreeCache(); - try (CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1))) - { + try (CuratorFramework client = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1))) { client.start(); client.create().forPath("/test"); - try (CuratorCache cache = CuratorCache.build(client, "/test")) - { - cache.listenable().addListener(builder().forTreeCache(client, treeCacheBase.eventListener).build()); + try (CuratorCache cache = CuratorCache.build(client, "/test")) { + cache.listenable() + .addListener(builder() + .forTreeCache(client, treeCacheBase.eventListener) + .build()); cache.start(); treeCacheBase.assertEvent(TreeCacheEvent.Type.NODE_ADDED, "/test"); treeCacheBase.assertEvent(TreeCacheEvent.Type.INITIALIZED); - assertEquals(toMap(cache.stream().filter(parentPathFilter("/test"))).keySet(), ImmutableSet.of()); + assertEquals( + toMap(cache.stream().filter(parentPathFilter("/test"))).keySet(), ImmutableSet.of()); assertEquals(cache.stream().filter(parentPathFilter("/t")).count(), 0); assertEquals(cache.stream().filter(parentPathFilter("/testing")).count(), 0); client.create().forPath("/test/one", "hey there".getBytes()); treeCacheBase.assertEvent(TreeCacheEvent.Type.NODE_ADDED, "/test/one"); - assertEquals(toMap(cache.stream().filter(parentPathFilter("/test"))).keySet(), ImmutableSet.of("/test/one")); - assertEquals(new String(cache.get("/test/one").orElseThrow(AssertionError::new).getData()), "hey there"); - assertEquals(toMap(cache.stream().filter(parentPathFilter("/test/one"))).keySet(), ImmutableSet.of()); + assertEquals( + toMap(cache.stream().filter(parentPathFilter("/test"))).keySet(), ImmutableSet.of("/test/one")); + assertEquals( + new String(cache.get("/test/one") + .orElseThrow(AssertionError::new) + .getData()), + "hey there"); + assertEquals( + toMap(cache.stream().filter(parentPathFilter("/test/one"))) + .keySet(), + ImmutableSet.of()); assertEquals(cache.stream().filter(parentPathFilter("/test/o")).count(), 0); - assertEquals(cache.stream().filter(parentPathFilter("/test/onely")).count(), 0); + assertEquals( + cache.stream().filter(parentPathFilter("/test/onely")).count(), 0); client.setData().forPath("/test/one", "sup!".getBytes()); treeCacheBase.assertEvent(TreeCacheEvent.Type.NODE_UPDATED, "/test/one"); - assertEquals(toMap(cache.stream().filter(parentPathFilter("/test"))).keySet(), ImmutableSet.of("/test/one")); - assertEquals(new String(cache.get("/test/one").orElseThrow(AssertionError::new).getData()), "sup!"); + assertEquals( + toMap(cache.stream().filter(parentPathFilter("/test"))).keySet(), ImmutableSet.of("/test/one")); + assertEquals( + new String(cache.get("/test/one") + .orElseThrow(AssertionError::new) + .getData()), + "sup!"); client.delete().forPath("/test/one"); treeCacheBase.assertEvent(TreeCacheEvent.Type.NODE_REMOVED, "/test/one", "sup!".getBytes()); - assertEquals(toMap(cache.stream().filter(parentPathFilter("/test"))).keySet(), ImmutableSet.of()); + assertEquals( + toMap(cache.stream().filter(parentPathFilter("/test"))).keySet(), ImmutableSet.of()); } } } @Test - public void testNodeCache() throws Exception // copied from TestNodeCache#testBasics() - { - try ( CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)) ) - { + public void testNodeCache() throws Exception // copied from TestNodeCache#testBasics() + { + try (CuratorFramework client = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1))) { client.start(); client.create().forPath("/test"); - try (CuratorCache cache = CuratorCache.build(client, "/test/node", SINGLE_NODE_CACHE)) - { - Supplier getRootData = () -> cache.get("/test/node").orElseThrow(() -> new AssertionError("is not present")); + try (CuratorCache cache = CuratorCache.build(client, "/test/node", SINGLE_NODE_CACHE)) { + Supplier getRootData = + () -> cache.get("/test/node").orElseThrow(() -> new AssertionError("is not present")); cache.start(); final Semaphore semaphore = new Semaphore(0); - cache.listenable().addListener(builder().forNodeCache(semaphore::release).build()); - try - { + cache.listenable() + .addListener(builder().forNodeCache(semaphore::release).build()); + try { getRootData.get(); fail("Should have thrown"); - } - catch ( AssertionError expected ) - { + } catch (AssertionError expected) { // expected } @@ -177,22 +202,18 @@ public void testNodeCache() throws Exception // copied from TestNodeCache#tes client.delete().forPath("/test/node"); assertTrue(timing.acquireSemaphore(semaphore)); - try - { + try { getRootData.get(); fail("Should have thrown"); - } - catch ( AssertionError expected ) - { + } catch (AssertionError expected) { // expected } } } } - private static Map toMap(Stream stream) - { + private static Map toMap(Stream stream) { return stream.map(data -> new AbstractMap.SimpleEntry<>(data.getPath(), data)) - .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); + .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); } } diff --git a/curator-recipes/src/test/java/org/apache/curator/framework/recipes/cache/TestEventOrdering.java b/curator-recipes/src/test/java/org/apache/curator/framework/recipes/cache/TestEventOrdering.java index 473171d9f..3f4b01fea 100644 --- a/curator-recipes/src/test/java/org/apache/curator/framework/recipes/cache/TestEventOrdering.java +++ b/curator-recipes/src/test/java/org/apache/curator/framework/recipes/cache/TestEventOrdering.java @@ -23,15 +23,6 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import com.google.common.collect.Lists; import com.google.common.collect.Queues; -import org.apache.curator.framework.CuratorFramework; -import org.apache.curator.framework.CuratorFrameworkFactory; -import org.apache.curator.retry.RetryOneTime; -import org.apache.curator.test.BaseClassForTests; -import org.apache.curator.test.compatibility.Timing2; -import org.apache.curator.utils.CloseableUtils; -import org.apache.zookeeper.KeeperException; -import org.junit.jupiter.api.Test; - import java.io.Closeable; import java.util.List; import java.util.Random; @@ -41,76 +32,72 @@ 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.RetryOneTime; +import org.apache.curator.test.BaseClassForTests; +import org.apache.curator.test.compatibility.Timing2; +import org.apache.curator.utils.CloseableUtils; +import org.apache.zookeeper.KeeperException; +import org.junit.jupiter.api.Test; -public abstract class TestEventOrdering extends BaseClassForTests -{ +public abstract class TestEventOrdering extends BaseClassForTests { private final Timing2 timing = new Timing2(); private final long start = System.currentTimeMillis(); private static final int THREAD_QTY = 100; private static final int ITERATIONS = 100; private static final int NODE_QTY = 10; - public enum EventType - { + public enum EventType { ADDED, DELETED } - public static class Event - { + public static class Event { public final EventType eventType; public final String path; public final long time = System.currentTimeMillis(); - public Event(EventType eventType, String path) - { + public Event(EventType eventType, String path) { this.eventType = eventType; this.path = path; } } @Test - public void testEventOrdering() throws Exception - { + public void testEventOrdering() throws Exception { ExecutorService executorService = Executors.newFixedThreadPool(THREAD_QTY); BlockingQueue events = Queues.newLinkedBlockingQueue(); - final CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); + final CuratorFramework client = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); T cache = null; - try - { + try { client.start(); client.create().forPath("/root"); cache = newCache(client, "/root", events); final Random random = new Random(); - final Callable task = new Callable() - { + final Callable task = new Callable() { @Override - public Void call() throws Exception - { - for ( int i = 0; i < ITERATIONS; ++i ) - { + public Void call() throws Exception { + for (int i = 0; i < ITERATIONS; ++i) { String node = "/root/" + random.nextInt(NODE_QTY); - try - { - switch ( random.nextInt(3) ) - { - default: - case 0: - client.create().forPath(node); - break; - - case 1: - client.setData().forPath(node, "new".getBytes()); - break; - - case 2: - client.delete().forPath(node); - break; + try { + switch (random.nextInt(3)) { + default: + case 0: + client.create().forPath(node); + break; + + case 1: + client.setData().forPath(node, "new".getBytes()); + break; + + case 2: + client.delete().forPath(node); + break; } - } - catch ( KeeperException ignore ) - { + } catch (KeeperException ignore) { // ignore } } @@ -119,19 +106,13 @@ public Void call() throws Exception }; final CountDownLatch latch = new CountDownLatch(THREAD_QTY); - for ( int i = 0; i < THREAD_QTY; ++i ) - { - Callable wrapped = new Callable() - { + for (int i = 0; i < THREAD_QTY; ++i) { + Callable wrapped = new Callable() { @Override - public Void call() throws Exception - { - try - { + public Void call() throws Exception { + try { return task.call(); - } - finally - { + } finally { latch.countDown(); } } @@ -144,17 +125,17 @@ public Void call() throws Exception List localEvents = Lists.newArrayList(); int eventSuggestedQty = 0; - while ( events.size() > 0 ) - { + while (events.size() > 0) { Event event = timing.takeFromQueue(events); localEvents.add(event); eventSuggestedQty += (event.eventType == EventType.ADDED) ? 1 : -1; } int actualQty = getActualQty(cache); - assertEquals(actualQty, eventSuggestedQty, String.format("actual %s expected %s:\n %s", actualQty, eventSuggestedQty, asString(localEvents))); - } - finally - { + assertEquals( + actualQty, + eventSuggestedQty, + String.format("actual %s expected %s:\n %s", actualQty, eventSuggestedQty, asString(localEvents))); + } finally { executorService.shutdownNow(); //noinspection ThrowFromFinallyBlock executorService.awaitTermination(timing.milliseconds(), TimeUnit.MILLISECONDS); @@ -167,14 +148,18 @@ public Void call() throws Exception protected abstract T newCache(CuratorFramework client, String path, BlockingQueue events) throws Exception; - private String asString(List events) - { + private String asString(List events) { int qty = 0; StringBuilder str = new StringBuilder(); - for ( Event event : events ) - { + for (Event event : events) { qty += (event.eventType == EventType.ADDED) ? 1 : -1; - str.append(event.eventType).append(" ").append(event.path).append(" @ ").append(event.time - start).append(' ').append(qty); + str.append(event.eventType) + .append(" ") + .append(event.path) + .append(" @ ") + .append(event.time - start) + .append(' ') + .append(qty); str.append("\n"); } return str.toString(); diff --git a/curator-recipes/src/test/java/org/apache/curator/framework/recipes/cache/TestNodeCache.java b/curator-recipes/src/test/java/org/apache/curator/framework/recipes/cache/TestNodeCache.java index 21b3ee155..edf92eaff 100644 --- a/curator-recipes/src/test/java/org/apache/curator/framework/recipes/cache/TestNodeCache.java +++ b/curator-recipes/src/test/java/org/apache/curator/framework/recipes/cache/TestNodeCache.java @@ -20,25 +20,10 @@ package org.apache.curator.framework.recipes.cache; import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; 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 org.apache.curator.framework.imps.TestCleanState; -import org.apache.curator.test.BaseClassForTests; -import org.apache.curator.test.compatibility.CuratorTestBase; -import org.apache.curator.test.compatibility.Timing2; -import org.apache.curator.utils.CloseableUtils; -import org.apache.curator.framework.CuratorFramework; -import org.apache.curator.framework.CuratorFrameworkFactory; -import org.apache.curator.framework.api.UnhandledErrorListener; -import org.apache.curator.retry.RetryOneTime; -import org.apache.curator.test.Timing; -import org.junit.jupiter.api.Tag; -import org.junit.jupiter.api.Test; - import java.util.concurrent.Callable; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Exchanger; @@ -48,46 +33,45 @@ import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; +import org.apache.curator.framework.CuratorFramework; +import org.apache.curator.framework.CuratorFrameworkFactory; +import org.apache.curator.framework.api.UnhandledErrorListener; +import org.apache.curator.framework.imps.TestCleanState; +import org.apache.curator.retry.RetryOneTime; +import org.apache.curator.test.BaseClassForTests; +import org.apache.curator.test.Timing; +import org.apache.curator.test.compatibility.CuratorTestBase; +import org.apache.curator.test.compatibility.Timing2; +import org.apache.curator.utils.CloseableUtils; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; @Tag(CuratorTestBase.zk35TestCompatibilityGroup) -public class TestNodeCache extends BaseClassForTests -{ +public class TestNodeCache extends BaseClassForTests { @Test - public void testDeleteThenCreate() throws Exception - { - NodeCache cache = null; - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); + public void testDeleteThenCreate() throws Exception { + NodeCache cache = null; + CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client.start(); - try - { + try { client.create().creatingParentsIfNeeded().forPath("/test/foo", "one".getBytes()); - final AtomicReference error = new AtomicReference(); - client.getUnhandledErrorListenable().addListener - ( - new UnhandledErrorListener() - { - @Override - public void unhandledError(String message, Throwable e) - { - error.set(e); - } + final AtomicReference error = new AtomicReference(); + client.getUnhandledErrorListenable().addListener(new UnhandledErrorListener() { + @Override + public void unhandledError(String message, Throwable e) { + error.set(e); } - ); + }); - final Semaphore semaphore = new Semaphore(0); + final Semaphore semaphore = new Semaphore(0); cache = new NodeCache(client, "/test/foo"); - cache.getListenable().addListener - ( - new NodeCacheListener() - { - @Override - public void nodeChanged() throws Exception - { - semaphore.release(); - } + cache.getListenable().addListener(new NodeCacheListener() { + @Override + public void nodeChanged() throws Exception { + semaphore.release(); } - ); + }); cache.start(true); assertArrayEquals(cache.getCurrentData().getData(), "one".getBytes()); @@ -98,113 +82,93 @@ public void nodeChanged() throws Exception assertTrue(semaphore.tryAcquire(1, 10, TimeUnit.SECONDS)); Throwable t = error.get(); - if ( t != null ) - { + if (t != null) { fail("Assert", t); } assertArrayEquals(cache.getCurrentData().getData(), "two".getBytes()); cache.close(); - } - finally - { + } finally { CloseableUtils.closeQuietly(cache); TestCleanState.closeAndTestClean(client); } } @Test - public void testRebuildAgainstOtherProcesses() throws Exception - { - Timing2 timing2 = new Timing2(); - NodeCache cache = null; - final CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); + public void testRebuildAgainstOtherProcesses() throws Exception { + Timing2 timing2 = new Timing2(); + NodeCache cache = null; + final CuratorFramework client = + CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client.start(); - try - { + try { client.create().forPath("/test"); client.create().forPath("/test/snafu", "original".getBytes()); - final CountDownLatch latch = new CountDownLatch(1); + final CountDownLatch latch = new CountDownLatch(1); cache = new NodeCache(client, "/test/snafu"); - cache.getListenable().addListener - ( - new NodeCacheListener() - { - @Override - public void nodeChanged() throws Exception - { - latch.countDown(); - } + cache.getListenable().addListener(new NodeCacheListener() { + @Override + public void nodeChanged() throws Exception { + latch.countDown(); } - ); + }); cache.rebuildTestExchanger = new Exchanger(); - ExecutorService service = Executors.newSingleThreadExecutor(); - final NodeCache finalCache = cache; - Future future = service.submit - ( - new Callable() - { - @Override - public Object call() throws Exception - { - finalCache.rebuildTestExchanger.exchange(new Object(), timing2.forWaiting().seconds(), TimeUnit.SECONDS); + ExecutorService service = Executors.newSingleThreadExecutor(); + final NodeCache finalCache = cache; + Future future = service.submit(new Callable() { + @Override + public Object call() throws Exception { + finalCache.rebuildTestExchanger.exchange( + new Object(), timing2.forWaiting().seconds(), TimeUnit.SECONDS); - // simulate another process updating the node while we're rebuilding - client.setData().forPath("/test/snafu", "other".getBytes()); + // simulate another process updating the node while we're rebuilding + client.setData().forPath("/test/snafu", "other".getBytes()); - ChildData currentData = finalCache.getCurrentData(); - assertNotNull(currentData); + ChildData currentData = finalCache.getCurrentData(); + assertNotNull(currentData); - finalCache.rebuildTestExchanger.exchange(new Object(), timing2.forWaiting().seconds(), TimeUnit.SECONDS); + finalCache.rebuildTestExchanger.exchange( + new Object(), timing2.forWaiting().seconds(), TimeUnit.SECONDS); - return null; - } + return null; } - ); + }); cache.start(false); future.get(); assertTrue(timing2.awaitLatch(latch)); assertNotNull(cache.getCurrentData()); assertArrayEquals(cache.getCurrentData().getData(), "other".getBytes()); - } - finally - { + } finally { CloseableUtils.closeQuietly(cache); TestCleanState.closeAndTestClean(client); } } @Test - public void testKilledSession() throws Exception - { - NodeCache cache = null; - Timing timing = new Timing(); - CuratorFramework client = null; - try - { - client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); + public void testKilledSession() throws Exception { + NodeCache cache = null; + Timing timing = new Timing(); + CuratorFramework client = null; + try { + client = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); client.start(); client.create().creatingParentsIfNeeded().forPath("/test/node", "start".getBytes()); cache = new NodeCache(client, "/test/node"); cache.start(true); - final CountDownLatch latch = new CountDownLatch(1); - cache.getListenable().addListener - ( - new NodeCacheListener() - { - @Override - public void nodeChanged() throws Exception - { - latch.countDown(); - } + final CountDownLatch latch = new CountDownLatch(1); + cache.getListenable().addListener(new NodeCacheListener() { + @Override + public void nodeChanged() throws Exception { + latch.countDown(); } - ); + }); client.getZookeeperClient().getZooKeeper().getTestable().injectSessionExpiration(); Thread.sleep(timing.multiple(1.5).session()); @@ -213,40 +177,32 @@ public void nodeChanged() throws Exception client.setData().forPath("/test/node", "new data".getBytes()); assertTrue(timing.awaitLatch(latch)); - } - finally - { + } finally { CloseableUtils.closeQuietly(cache); TestCleanState.closeAndTestClean(client); } } @Test - public void testBasics() throws Exception - { - NodeCache cache = null; - Timing timing = new Timing(); - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); + public void testBasics() throws Exception { + NodeCache cache = null; + Timing timing = new Timing(); + CuratorFramework client = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); client.start(); - try - { + try { client.create().forPath("/test"); cache = new NodeCache(client, "/test/node"); cache.start(true); - final Semaphore semaphore = new Semaphore(0); - cache.getListenable().addListener - ( - new NodeCacheListener() - { - @Override - public void nodeChanged() throws Exception - { - semaphore.release(); - } + final Semaphore semaphore = new Semaphore(0); + cache.getListenable().addListener(new NodeCacheListener() { + @Override + public void nodeChanged() throws Exception { + semaphore.release(); } - ); + }); assertNull(cache.getCurrentData()); @@ -261,9 +217,7 @@ public void nodeChanged() throws Exception client.delete().forPath("/test/node"); assertTrue(timing.acquireSemaphore(semaphore)); assertNull(cache.getCurrentData()); - } - finally - { + } finally { CloseableUtils.closeQuietly(cache); TestCleanState.closeAndTestClean(client); } diff --git a/curator-recipes/src/test/java/org/apache/curator/framework/recipes/cache/TestPathChildrenCache.java b/curator-recipes/src/test/java/org/apache/curator/framework/recipes/cache/TestPathChildrenCache.java index 283bb18ae..3548e61e3 100644 --- a/curator-recipes/src/test/java/org/apache/curator/framework/recipes/cache/TestPathChildrenCache.java +++ b/curator-recipes/src/test/java/org/apache/curator/framework/recipes/cache/TestPathChildrenCache.java @@ -29,6 +29,19 @@ import static org.junit.jupiter.api.Assertions.fail; import com.google.common.collect.Lists; import com.google.common.collect.Queues; +import java.util.List; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.Callable; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Exchanger; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.Semaphore; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.api.UnhandledErrorListener; @@ -47,87 +60,75 @@ import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; -import java.util.List; -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.Callable; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.Exchanger; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; -import java.util.concurrent.LinkedBlockingQueue; -import java.util.concurrent.Semaphore; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.concurrent.atomic.AtomicReference; - @Tag(CuratorTestBase.zk35TestCompatibilityGroup) -public class TestPathChildrenCache extends BaseClassForTests -{ +public class TestPathChildrenCache extends BaseClassForTests { @Test - public void testParentContainerMissing() throws Exception - { + public void testParentContainerMissing() throws Exception { Timing timing = new Timing(); CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); PathChildrenCache cache = new PathChildrenCache(client, "/a/b/test", true); - try - { + try { client.start(); CountDownLatch startedLatch = new CountDownLatch(1); client.getConnectionStateListenable().addListener((__, newState) -> { - if ( newState == ConnectionState.CONNECTED ) - { + if (newState == ConnectionState.CONNECTED) { startedLatch.countDown(); } }); assertTrue(timing.awaitLatch(startedLatch)); final BlockingQueue events = Queues.newLinkedBlockingQueue(); - PathChildrenCacheListener listener = new PathChildrenCacheListener() - { + PathChildrenCacheListener listener = new PathChildrenCacheListener() { @Override - public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception - { + public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception { events.add(event.getType()); } }; cache.getListenable().addListener(listener); cache.start(PathChildrenCache.StartMode.POST_INITIALIZED_EVENT); - assertEquals(events.poll(timing.forWaiting().milliseconds(), TimeUnit.MILLISECONDS), PathChildrenCacheEvent.Type.INITIALIZED); + assertEquals( + events.poll(timing.forWaiting().milliseconds(), TimeUnit.MILLISECONDS), + PathChildrenCacheEvent.Type.INITIALIZED); client.create().forPath("/a/b/test/one"); client.create().forPath("/a/b/test/two"); - assertEquals(events.poll(timing.forWaiting().milliseconds(), TimeUnit.MILLISECONDS), PathChildrenCacheEvent.Type.CHILD_ADDED); - assertEquals(events.poll(timing.forWaiting().milliseconds(), TimeUnit.MILLISECONDS), PathChildrenCacheEvent.Type.CHILD_ADDED); + assertEquals( + events.poll(timing.forWaiting().milliseconds(), TimeUnit.MILLISECONDS), + PathChildrenCacheEvent.Type.CHILD_ADDED); + assertEquals( + events.poll(timing.forWaiting().milliseconds(), TimeUnit.MILLISECONDS), + PathChildrenCacheEvent.Type.CHILD_ADDED); client.delete().forPath("/a/b/test/one"); client.delete().forPath("/a/b/test/two"); client.delete().forPath("/a/b/test"); - assertEquals(events.poll(timing.forWaiting().milliseconds(), TimeUnit.MILLISECONDS), PathChildrenCacheEvent.Type.CHILD_REMOVED); - assertEquals(events.poll(timing.forWaiting().milliseconds(), TimeUnit.MILLISECONDS), PathChildrenCacheEvent.Type.CHILD_REMOVED); + assertEquals( + events.poll(timing.forWaiting().milliseconds(), TimeUnit.MILLISECONDS), + PathChildrenCacheEvent.Type.CHILD_REMOVED); + assertEquals( + events.poll(timing.forWaiting().milliseconds(), TimeUnit.MILLISECONDS), + PathChildrenCacheEvent.Type.CHILD_REMOVED); timing.sleepABit(); client.create().creatingParentContainersIfNeeded().forPath("/a/b/test/new"); - assertEquals(events.poll(timing.forWaiting().milliseconds(), TimeUnit.MILLISECONDS), PathChildrenCacheEvent.Type.CHILD_ADDED); - } - finally - { + assertEquals( + events.poll(timing.forWaiting().milliseconds(), TimeUnit.MILLISECONDS), + PathChildrenCacheEvent.Type.CHILD_ADDED); + } finally { CloseableUtils.closeQuietly(cache); CloseableUtils.closeQuietly(client); } } @Test - public void testInitializedEvenIfChildDeleted() throws Exception - { - final CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); + public void testInitializedEvenIfChildDeleted() throws Exception { + final CuratorFramework client = + CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); - PathChildrenCache cache = new PathChildrenCache(client, "/a/b/test", true) - { + PathChildrenCache cache = new PathChildrenCache(client, "/a/b/test", true) { @Override - void getDataAndStat(final String fullPath) throws Exception - { + void getDataAndStat(final String fullPath) throws Exception { // before installing a data watcher on the child, let's delete this child client.delete().forPath("/a/b/test/one"); super.getDataAndStat(fullPath); @@ -136,19 +137,15 @@ void getDataAndStat(final String fullPath) throws Exception Timing timing = new Timing(); - try - { + try { client.start(); final CountDownLatch cacheInitialized = new CountDownLatch(1); - PathChildrenCacheListener listener = new PathChildrenCacheListener() - { + PathChildrenCacheListener listener = new PathChildrenCacheListener() { @Override - public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception - { - if ( event.getType() == PathChildrenCacheEvent.Type.INITIALIZED ) - { + public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception { + if (event.getType() == PathChildrenCacheEvent.Type.INITIALIZED) { cacheInitialized.countDown(); } } @@ -161,52 +158,41 @@ public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) th assertTrue(timing.awaitLatch(cacheInitialized)); assertEquals(cache.getCurrentData().size(), 0); - } - finally - { + } finally { CloseableUtils.closeQuietly(cache); CloseableUtils.closeQuietly(client); } } @Test - public void testWithBadConnect() throws Exception - { + public void testWithBadConnect() throws Exception { final int serverPort = server.getPort(); server.close(); Timing timing = new Timing(); - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), 1000, 1000, new RetryOneTime(1)); - try - { + CuratorFramework client = + CuratorFrameworkFactory.newClient(server.getConnectString(), 1000, 1000, new RetryOneTime(1)); + try { client.start(); final CountDownLatch ensurePathLatch = new CountDownLatch(1); - PathChildrenCache cache = new PathChildrenCache(client, "/", true) - { + PathChildrenCache cache = new PathChildrenCache(client, "/", true) { @Override - protected void ensurePath() throws Exception - { - try - { + protected void ensurePath() throws Exception { + try { super.ensurePath(); - } - catch ( Exception e ) - { + } catch (Exception e) { ensurePathLatch.countDown(); throw e; } } }; final CountDownLatch addedLatch = new CountDownLatch(1); - PathChildrenCacheListener listener = new PathChildrenCacheListener() - { + PathChildrenCacheListener listener = new PathChildrenCacheListener() { @Override - public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception - { - if ( event.getType() == PathChildrenCacheEvent.Type.CHILD_ADDED && - event.getData().getPath().equals("/baz")) - { + public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception { + if (event.getType() == PathChildrenCacheEvent.Type.CHILD_ADDED + && event.getData().getPath().equals("/baz")) { addedLatch.countDown(); } } @@ -216,14 +202,11 @@ public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) th assertTrue(timing.awaitLatch(ensurePathLatch)); final CountDownLatch connectedLatch = new CountDownLatch(1); - client.getConnectionStateListenable().addListener(new ConnectionStateListener() - { + client.getConnectionStateListenable().addListener(new ConnectionStateListener() { @Override - public void stateChanged(CuratorFramework client, ConnectionState newState) - { - if(newState == ConnectionState.CONNECTED) - { + public void stateChanged(CuratorFramework client, ConnectionState newState) { + if (newState == ConnectionState.CONNECTED) { connectedLatch.countDown(); } } @@ -233,64 +216,52 @@ public void stateChanged(CuratorFramework client, ConnectionState newState) assertTrue(timing.awaitLatch(connectedLatch)); - client.create().creatingParentContainersIfNeeded().forPath("/baz", new byte[]{1, 2, 3}); + client.create().creatingParentContainersIfNeeded().forPath("/baz", new byte[] {1, 2, 3}); assertNotNull(client.checkExists().forPath("/baz"), "/baz does not exist"); assertTrue(timing.awaitLatch(addedLatch)); assertNotNull(cache.getCurrentData("/baz"), "cache doesn't see /baz"); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } @Test - public void testPostInitializedForEmpty() throws Exception - { + public void testPostInitializedForEmpty() throws Exception { Timing timing = new Timing(); PathChildrenCache cache = null; - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); - try - { + CuratorFramework client = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); + try { client.start(); final CountDownLatch latch = new CountDownLatch(1); cache = new PathChildrenCache(client, "/test", true); - cache.getListenable().addListener - ( - new PathChildrenCacheListener() - { - @Override - public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception - { - if ( event.getType() == PathChildrenCacheEvent.Type.INITIALIZED ) - { - latch.countDown(); - } - } + cache.getListenable().addListener(new PathChildrenCacheListener() { + @Override + public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception { + if (event.getType() == PathChildrenCacheEvent.Type.INITIALIZED) { + latch.countDown(); } - ); + } + }); cache.start(PathChildrenCache.StartMode.POST_INITIALIZED_EVENT); assertTrue(timing.awaitLatch(latch)); - } - finally - { + } finally { CloseableUtils.closeQuietly(cache); TestCleanState.closeAndTestClean(client); } } @Test - public void testAsyncInitialPopulation() throws Exception - { + public void testAsyncInitialPopulation() throws Exception { Timing timing = new Timing(); PathChildrenCache cache = null; - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); - try - { + CuratorFramework client = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); + try { client.start(); client.create().forPath("/test"); @@ -298,17 +269,12 @@ public void testAsyncInitialPopulation() throws Exception final BlockingQueue events = new LinkedBlockingQueue(); cache = new PathChildrenCache(client, "/test", true); - cache.getListenable().addListener - ( - new PathChildrenCacheListener() - { - @Override - public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception - { - events.offer(event); - } - } - ); + cache.getListenable().addListener(new PathChildrenCacheListener() { + @Override + public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception { + events.offer(event); + } + }); cache.start(PathChildrenCache.StartMode.POST_INITIALIZED_EVENT); PathChildrenCacheEvent event = events.poll(timing.forWaiting().seconds(), TimeUnit.SECONDS); @@ -317,22 +283,19 @@ public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) th event = events.poll(timing.forWaiting().seconds(), TimeUnit.SECONDS); assertEquals(event.getType(), PathChildrenCacheEvent.Type.INITIALIZED); assertEquals(event.getInitialData().size(), 1); - } - finally - { + } finally { CloseableUtils.closeQuietly(cache); TestCleanState.closeAndTestClean(client); } } @Test - public void testChildrenInitialized() throws Exception - { + public void testChildrenInitialized() throws Exception { Timing timing = new Timing(); PathChildrenCache cache = null; - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); - try - { + CuratorFramework client = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); + try { client.start(); client.create().forPath("/test"); @@ -340,24 +303,16 @@ public void testChildrenInitialized() throws Exception final CountDownLatch addedLatch = new CountDownLatch(3); final CountDownLatch initLatch = new CountDownLatch(1); - cache.getListenable().addListener - ( - new PathChildrenCacheListener() - { - @Override - public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception - { - if ( event.getType() == PathChildrenCacheEvent.Type.CHILD_ADDED ) - { - addedLatch.countDown(); - } - else if ( event.getType() == PathChildrenCacheEvent.Type.INITIALIZED ) - { - initLatch.countDown(); - } - } + cache.getListenable().addListener(new PathChildrenCacheListener() { + @Override + public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception { + if (event.getType() == PathChildrenCacheEvent.Type.CHILD_ADDED) { + addedLatch.countDown(); + } else if (event.getType() == PathChildrenCacheEvent.Type.INITIALIZED) { + initLatch.countDown(); } - ); + } + }); client.create().forPath("/test/1", "1".getBytes()); client.create().forPath("/test/2", "2".getBytes()); @@ -371,43 +326,34 @@ else if ( event.getType() == PathChildrenCacheEvent.Type.INITIALIZED ) assertArrayEquals(cache.getCurrentData().get(0).getData(), "1".getBytes()); assertArrayEquals(cache.getCurrentData().get(1).getData(), "2".getBytes()); assertArrayEquals(cache.getCurrentData().get(2).getData(), "3".getBytes()); - } - finally - { + } finally { CloseableUtils.closeQuietly(cache); TestCleanState.closeAndTestClean(client); } } @Test - public void testChildrenInitializedNormal() throws Exception - { + public void testChildrenInitializedNormal() throws Exception { Timing timing = new Timing(); PathChildrenCache cache = null; - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); - try - { + CuratorFramework client = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); + try { client.start(); client.create().forPath("/test"); cache = new PathChildrenCache(client, "/test", true); final CountDownLatch addedLatch = new CountDownLatch(3); - cache.getListenable().addListener - ( - new PathChildrenCacheListener() - { - @Override - public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception - { - assertNotEquals(event.getType(), PathChildrenCacheEvent.Type.INITIALIZED); - if ( event.getType() == PathChildrenCacheEvent.Type.CHILD_ADDED ) - { - addedLatch.countDown(); - } - } + cache.getListenable().addListener(new PathChildrenCacheListener() { + @Override + public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception { + assertNotEquals(event.getType(), PathChildrenCacheEvent.Type.INITIALIZED); + if (event.getType() == PathChildrenCacheEvent.Type.CHILD_ADDED) { + addedLatch.countDown(); } - ); + } + }); client.create().forPath("/test/1", "1".getBytes()); client.create().forPath("/test/2", "2".getBytes()); @@ -420,46 +366,35 @@ public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) th assertArrayEquals(cache.getCurrentData().get(0).getData(), "1".getBytes()); assertArrayEquals(cache.getCurrentData().get(1).getData(), "2".getBytes()); assertArrayEquals(cache.getCurrentData().get(2).getData(), "3".getBytes()); - } - finally - { + } finally { CloseableUtils.closeQuietly(cache); TestCleanState.closeAndTestClean(client); } } @Test - public void testUpdateWhenNotCachingData() throws Exception - { + public void testUpdateWhenNotCachingData() throws Exception { Timing timing = new Timing(); PathChildrenCache cache = null; - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); + CuratorFramework client = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); client.start(); - try - { + try { final CountDownLatch updatedLatch = new CountDownLatch(1); final CountDownLatch addedLatch = new CountDownLatch(1); client.create().creatingParentsIfNeeded().forPath("/test"); cache = new PathChildrenCache(client, "/test", false); - cache.getListenable().addListener - ( - new PathChildrenCacheListener() - { - @Override - public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception - { - if ( event.getType() == PathChildrenCacheEvent.Type.CHILD_UPDATED ) - { - updatedLatch.countDown(); - } - else if ( event.getType() == PathChildrenCacheEvent.Type.CHILD_ADDED ) - { - addedLatch.countDown(); - } - } + cache.getListenable().addListener(new PathChildrenCacheListener() { + @Override + public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception { + if (event.getType() == PathChildrenCacheEvent.Type.CHILD_UPDATED) { + updatedLatch.countDown(); + } else if (event.getType() == PathChildrenCacheEvent.Type.CHILD_ADDED) { + addedLatch.countDown(); } - ); + } + }); cache.start(PathChildrenCache.StartMode.BUILD_INITIAL_CACHE); client.create().forPath("/test/foo", "first".getBytes()); @@ -467,100 +402,73 @@ else if ( event.getType() == PathChildrenCacheEvent.Type.CHILD_ADDED ) client.setData().forPath("/test/foo", "something new".getBytes()); assertTrue(timing.awaitLatch(updatedLatch)); - } - finally - { + } finally { CloseableUtils.closeQuietly(cache); TestCleanState.closeAndTestClean(client); } } @Test - public void testEnsurePath() throws Exception - { + public void testEnsurePath() throws Exception { Timing timing = new Timing(); - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); + CuratorFramework client = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); client.start(); - try - { - try ( PathChildrenCache cache = new PathChildrenCache(client, "/one/two/three", false) ) - { + try { + try (PathChildrenCache cache = new PathChildrenCache(client, "/one/two/three", false)) { cache.start(); timing.sleepABit(); - try - { + try { client.create().forPath("/one/two/three/four"); - } - catch ( KeeperException.NoNodeException e ) - { + } catch (KeeperException.NoNodeException e) { fail("Path should exist", e); } } timing.sleepABit(); - } - finally - { + } finally { TestCleanState.closeAndTestClean(client); } } @Test - public void testDeleteThenCreate() throws Exception - { + public void testDeleteThenCreate() throws Exception { Timing timing = new Timing(); - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); + CuratorFramework client = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); client.start(); - try - { + try { client.create().forPath("/test"); client.create().forPath("/test/foo", "one".getBytes()); final AtomicReference error = new AtomicReference(); - client.getUnhandledErrorListenable().addListener - ( - new UnhandledErrorListener() - { - @Override - public void unhandledError(String message, Throwable e) - { - error.set(e); - } - } - ); + client.getUnhandledErrorListenable().addListener(new UnhandledErrorListener() { + @Override + public void unhandledError(String message, Throwable e) { + error.set(e); + } + }); final CountDownLatch removedLatch = new CountDownLatch(1); final CountDownLatch postRemovedLatch = new CountDownLatch(1); final CountDownLatch dataLatch = new CountDownLatch(1); - try ( PathChildrenCache cache = new PathChildrenCache(client, "/test", true) ) - { - cache.getListenable().addListener - ( - new PathChildrenCacheListener() - { - @Override - public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception - { - if ( event.getType() == PathChildrenCacheEvent.Type.CHILD_REMOVED ) - { - removedLatch.countDown(); - assertTrue(postRemovedLatch.await(10, TimeUnit.SECONDS)); - } - else - { - try - { - assertArrayEquals(event.getData().getData(), "two".getBytes()); - } - finally - { - dataLatch.countDown(); - } - } + try (PathChildrenCache cache = new PathChildrenCache(client, "/test", true)) { + cache.getListenable().addListener(new PathChildrenCacheListener() { + @Override + public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception { + if (event.getType() == PathChildrenCacheEvent.Type.CHILD_REMOVED) { + removedLatch.countDown(); + assertTrue(postRemovedLatch.await(10, TimeUnit.SECONDS)); + } else { + try { + assertArrayEquals(event.getData().getData(), "two".getBytes()); + } finally { + dataLatch.countDown(); } } - ); + } + }); cache.start(PathChildrenCache.StartMode.BUILD_INITIAL_CACHE); client.delete().forPath("/test/foo"); @@ -570,97 +478,76 @@ public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) th assertTrue(timing.awaitLatch(dataLatch)); Throwable t = error.get(); - if ( t != null ) - { + if (t != null) { fail("Assert", t); } } - } - finally - { + } finally { TestCleanState.closeAndTestClean(client); } } @Test - public void testRebuildAgainstOtherProcesses() throws Exception - { + public void testRebuildAgainstOtherProcesses() throws Exception { Timing timing = new Timing(); - final CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); + final CuratorFramework client = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); client.start(); - try - { + try { client.create().forPath("/test"); client.create().forPath("/test/foo"); client.create().forPath("/test/bar"); client.create().forPath("/test/snafu", "original".getBytes()); final CountDownLatch addedLatch = new CountDownLatch(2); - try ( final PathChildrenCache cache = new PathChildrenCache(client, "/test", true) ) - { - cache.getListenable().addListener - ( - new PathChildrenCacheListener() - { - @Override - public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception - { - if ( event.getType() == PathChildrenCacheEvent.Type.CHILD_ADDED ) - { - if ( event.getData().getPath().equals("/test/test") ) - { - addedLatch.countDown(); - } - } - else if ( event.getType() == PathChildrenCacheEvent.Type.CHILD_UPDATED ) - { - if ( event.getData().getPath().equals("/test/snafu") ) - { - addedLatch.countDown(); - } - } + try (final PathChildrenCache cache = new PathChildrenCache(client, "/test", true)) { + cache.getListenable().addListener(new PathChildrenCacheListener() { + @Override + public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception { + if (event.getType() == PathChildrenCacheEvent.Type.CHILD_ADDED) { + if (event.getData().getPath().equals("/test/test")) { + addedLatch.countDown(); + } + } else if (event.getType() == PathChildrenCacheEvent.Type.CHILD_UPDATED) { + if (event.getData().getPath().equals("/test/snafu")) { + addedLatch.countDown(); } } - ); + } + }); cache.rebuildTestExchanger = new Exchanger(); ExecutorService service = Executors.newSingleThreadExecutor(); final AtomicReference deletedPath = new AtomicReference(); - Future future = service.submit - ( - new Callable() - { - @Override - public Object call() throws Exception - { - cache.rebuildTestExchanger.exchange(new Object()); - - // simulate another process adding a node while we're rebuilding - client.create().forPath("/test/test"); - - List currentData = cache.getCurrentData(); - assertTrue(currentData.size() > 0); - - // simulate another process removing a node while we're rebuilding - client.delete().forPath(currentData.get(0).getPath()); - deletedPath.set(currentData.get(0).getPath()); - - cache.rebuildTestExchanger.exchange(new Object()); - - ChildData childData = null; - while ( childData == null ) - { - childData = cache.getCurrentData("/test/snafu"); - Thread.sleep(1000); - } - assertArrayEquals(childData.getData(), "original".getBytes()); - client.setData().forPath("/test/snafu", "grilled".getBytes()); - - cache.rebuildTestExchanger.exchange(new Object()); - - return null; - } + Future future = service.submit(new Callable() { + @Override + public Object call() throws Exception { + cache.rebuildTestExchanger.exchange(new Object()); + + // simulate another process adding a node while we're rebuilding + client.create().forPath("/test/test"); + + List currentData = cache.getCurrentData(); + assertTrue(currentData.size() > 0); + + // simulate another process removing a node while we're rebuilding + client.delete().forPath(currentData.get(0).getPath()); + deletedPath.set(currentData.get(0).getPath()); + + cache.rebuildTestExchanger.exchange(new Object()); + + ChildData childData = null; + while (childData == null) { + childData = cache.getCurrentData("/test/snafu"); + Thread.sleep(1000); } - ); + assertArrayEquals(childData.getData(), "original".getBytes()); + client.setData().forPath("/test/snafu", "grilled".getBytes()); + + cache.rebuildTestExchanger.exchange(new Object()); + + return null; + } + }); cache.start(PathChildrenCache.StartMode.BUILD_INITIAL_CACHE); future.get(); @@ -669,23 +556,20 @@ public Object call() throws Exception assertNull(cache.getCurrentData(deletedPath.get())); assertArrayEquals(cache.getCurrentData("/test/snafu").getData(), "grilled".getBytes()); } - } - finally - { + } finally { TestCleanState.closeAndTestClean(client); } } // see https://github.com/Netflix/curator/issues/27 - was caused by not comparing old->new data @Test - public void testIssue27() throws Exception - { + public void testIssue27() throws Exception { Timing timing = new Timing(); PathChildrenCache cache = null; - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); + CuratorFramework client = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); client.start(); - try - { + try { client.create().forPath("/base"); client.create().forPath("/base/a"); client.create().forPath("/base/b"); @@ -696,18 +580,13 @@ public void testIssue27() throws Exception final List events = Lists.newArrayList(); final Semaphore semaphore = new Semaphore(0); cache = new PathChildrenCache(client, "/base", true); - cache.getListenable().addListener - ( - new PathChildrenCacheListener() - { - @Override - public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception - { - events.add(event.getType()); - semaphore.release(); - } - } - ); + cache.getListenable().addListener(new PathChildrenCacheListener() { + @Override + public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception { + events.add(event.getType()); + semaphore.release(); + } + }); cache.start(); assertTrue(timing.acquireSemaphore(semaphore, 3)); @@ -718,18 +597,14 @@ public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) th client.create().forPath("/base/a"); assertTrue(timing.acquireSemaphore(semaphore, 1)); - List expected = Lists.newArrayList - ( + List expected = Lists.newArrayList( PathChildrenCacheEvent.Type.CHILD_ADDED, PathChildrenCacheEvent.Type.CHILD_ADDED, PathChildrenCacheEvent.Type.CHILD_ADDED, PathChildrenCacheEvent.Type.CHILD_REMOVED, - PathChildrenCacheEvent.Type.CHILD_ADDED - ); + PathChildrenCacheEvent.Type.CHILD_ADDED); assertEquals(expected, events); - } - finally - { + } finally { CloseableUtils.closeQuietly(cache); TestCleanState.closeAndTestClean(client); } @@ -737,14 +612,13 @@ public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) th // test Issue 27 using new rebuild() method @Test - public void testIssue27Alt() throws Exception - { + public void testIssue27Alt() throws Exception { Timing timing = new Timing(); PathChildrenCache cache = null; - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); + CuratorFramework client = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); client.start(); - try - { + try { client.create().forPath("/base"); client.create().forPath("/base/a"); client.create().forPath("/base/b"); @@ -755,18 +629,13 @@ public void testIssue27Alt() throws Exception final List events = Lists.newArrayList(); final Semaphore semaphore = new Semaphore(0); cache = new PathChildrenCache(client, "/base", true); - cache.getListenable().addListener - ( - new PathChildrenCacheListener() - { - @Override - public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception - { - events.add(event.getType()); - semaphore.release(); - } - } - ); + cache.getListenable().addListener(new PathChildrenCacheListener() { + @Override + public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception { + events.add(event.getType()); + semaphore.release(); + } + }); cache.start(PathChildrenCache.StartMode.BUILD_INITIAL_CACHE); client.delete().forPath("/base/a"); @@ -775,29 +644,23 @@ public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) th client.create().forPath("/base/a"); assertTrue(timing.acquireSemaphore(semaphore, 1)); - List expected = Lists.newArrayList - ( - PathChildrenCacheEvent.Type.CHILD_REMOVED, - PathChildrenCacheEvent.Type.CHILD_ADDED - ); + List expected = Lists.newArrayList( + PathChildrenCacheEvent.Type.CHILD_REMOVED, PathChildrenCacheEvent.Type.CHILD_ADDED); assertEquals(expected, events); - } - finally - { + } finally { CloseableUtils.closeQuietly(cache); TestCleanState.closeAndTestClean(client); } } @Test - public void testKilledSession() throws Exception - { + public void testKilledSession() throws Exception { Timing timing = new Timing(); PathChildrenCache cache = null; CuratorFramework client = null; - try - { - client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); + try { + client = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); client.start(); client.create().forPath("/test"); @@ -808,32 +671,20 @@ public void testKilledSession() throws Exception final CountDownLatch lostLatch = new CountDownLatch(1); final CountDownLatch reconnectedLatch = new CountDownLatch(1); final CountDownLatch removedLatch = new CountDownLatch(1); - cache.getListenable().addListener - ( - new PathChildrenCacheListener() - { - @Override - public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception - { - if ( event.getType() == PathChildrenCacheEvent.Type.CHILD_ADDED ) - { - childAddedLatch.countDown(); - } - else if ( event.getType() == PathChildrenCacheEvent.Type.CONNECTION_LOST ) - { - lostLatch.countDown(); - } - else if ( event.getType() == PathChildrenCacheEvent.Type.CONNECTION_RECONNECTED ) - { - reconnectedLatch.countDown(); - } - else if ( event.getType() == PathChildrenCacheEvent.Type.CHILD_REMOVED ) - { - removedLatch.countDown(); - } - } + cache.getListenable().addListener(new PathChildrenCacheListener() { + @Override + public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception { + if (event.getType() == PathChildrenCacheEvent.Type.CHILD_ADDED) { + childAddedLatch.countDown(); + } else if (event.getType() == PathChildrenCacheEvent.Type.CONNECTION_LOST) { + lostLatch.countDown(); + } else if (event.getType() == PathChildrenCacheEvent.Type.CONNECTION_RECONNECTED) { + reconnectedLatch.countDown(); + } else if (event.getType() == PathChildrenCacheEvent.Type.CHILD_REMOVED) { + removedLatch.countDown(); } - ); + } + }); client.create().withMode(CreateMode.EPHEMERAL).forPath("/test/me", "data".getBytes()); assertTrue(timing.awaitLatch(childAddedLatch)); @@ -842,57 +693,48 @@ else if ( event.getType() == PathChildrenCacheEvent.Type.CHILD_REMOVED ) assertTrue(timing.awaitLatch(lostLatch)); assertTrue(timing.awaitLatch(reconnectedLatch)); assertTrue(timing.awaitLatch(removedLatch)); - } - finally - { + } finally { CloseableUtils.closeQuietly(cache); TestCleanState.closeAndTestClean(client); } } @Test - public void testModes() throws Exception - { + public void testModes() throws Exception { Timing timing = new Timing(); - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); + CuratorFramework client = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); client.start(); - try - { + try { client.create().forPath("/test"); - for ( boolean cacheData : new boolean[]{false, true} ) - { + for (boolean cacheData : new boolean[] {false, true}) { internalTestMode(client, cacheData); client.delete().forPath("/test/one"); client.delete().forPath("/test/two"); } - } - finally - { + } finally { TestCleanState.closeAndTestClean(client); } } @Test - public void testRebuildNode() throws Exception - { + public void testRebuildNode() throws Exception { Timing timing = new Timing(); PathChildrenCache cache = null; - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); - try - { + CuratorFramework client = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); + try { client.start(); client.create().creatingParentsIfNeeded().forPath("/test/one", "one".getBytes()); final CountDownLatch latch = new CountDownLatch(1); final AtomicInteger counter = new AtomicInteger(); final Semaphore semaphore = new Semaphore(1); - cache = new PathChildrenCache(client, "/test", true) - { + cache = new PathChildrenCache(client, "/test", true) { @Override - void getDataAndStat(String fullPath) throws Exception - { + void getDataAndStat(String fullPath) throws Exception { semaphore.acquire(); counter.incrementAndGet(); super.getDataAndStat(fullPath); @@ -911,48 +753,34 @@ void getDataAndStat(String fullPath) throws Exception semaphore.release(1000); timing.sleepABit(); - } - finally - { + } finally { CloseableUtils.closeQuietly(cache); TestCleanState.closeAndTestClean(client); } } - private void internalTestMode(CuratorFramework client, boolean cacheData) throws Exception - { - try ( PathChildrenCache cache = new PathChildrenCache(client, "/test", cacheData) ) - { + private void internalTestMode(CuratorFramework client, boolean cacheData) throws Exception { + try (PathChildrenCache cache = new PathChildrenCache(client, "/test", cacheData)) { final CountDownLatch latch = new CountDownLatch(2); - cache.getListenable().addListener - ( - new PathChildrenCacheListener() - { - @Override - public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception - { - if ( event.getType() == PathChildrenCacheEvent.Type.CHILD_ADDED ) - { - latch.countDown(); - } - } + cache.getListenable().addListener(new PathChildrenCacheListener() { + @Override + public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception { + if (event.getType() == PathChildrenCacheEvent.Type.CHILD_ADDED) { + latch.countDown(); } - ); + } + }); cache.start(); client.create().forPath("/test/one", "one".getBytes()); client.create().forPath("/test/two", "two".getBytes()); assertTrue(latch.await(10, TimeUnit.SECONDS)); - for ( ChildData data : cache.getCurrentData() ) - { - if ( cacheData ) - { + for (ChildData data : cache.getCurrentData()) { + if (cacheData) { assertNotNull(data.getData()); assertNotNull(data.getStat()); - } - else - { + } else { assertNull(data.getData()); assertNotNull(data.getStat()); } @@ -961,136 +789,128 @@ public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) th } @Test - public void testBasics() throws Exception - { + public void testBasics() throws Exception { Timing timing = new Timing(); - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); + CuratorFramework client = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); client.start(); - try - { + try { client.create().forPath("/test"); - final BlockingQueue events = new LinkedBlockingQueue(); - try ( PathChildrenCache cache = new PathChildrenCache(client, "/test", true) ) - { - cache.getListenable().addListener - ( - new PathChildrenCacheListener() - { - @Override - public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception - { - if ( event.getData().getPath().equals("/test/one") ) - { - events.offer(event.getType()); - } - } + final BlockingQueue events = + new LinkedBlockingQueue(); + try (PathChildrenCache cache = new PathChildrenCache(client, "/test", true)) { + cache.getListenable().addListener(new PathChildrenCacheListener() { + @Override + public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception { + if (event.getData().getPath().equals("/test/one")) { + events.offer(event.getType()); } - ); + } + }); cache.start(); client.create().forPath("/test/one", "hey there".getBytes()); - assertEquals(events.poll(timing.forWaiting().seconds(), TimeUnit.SECONDS), PathChildrenCacheEvent.Type.CHILD_ADDED); + assertEquals( + events.poll(timing.forWaiting().seconds(), TimeUnit.SECONDS), + PathChildrenCacheEvent.Type.CHILD_ADDED); client.setData().forPath("/test/one", "sup!".getBytes()); - assertEquals(events.poll(timing.forWaiting().seconds(), TimeUnit.SECONDS), PathChildrenCacheEvent.Type.CHILD_UPDATED); + assertEquals( + events.poll(timing.forWaiting().seconds(), TimeUnit.SECONDS), + PathChildrenCacheEvent.Type.CHILD_UPDATED); assertEquals(new String(cache.getCurrentData("/test/one").getData()), "sup!"); client.delete().forPath("/test/one"); - assertEquals(events.poll(timing.forWaiting().seconds(), TimeUnit.SECONDS), PathChildrenCacheEvent.Type.CHILD_REMOVED); + assertEquals( + events.poll(timing.forWaiting().seconds(), TimeUnit.SECONDS), + PathChildrenCacheEvent.Type.CHILD_REMOVED); } - } - finally - { + } finally { TestCleanState.closeAndTestClean(client); } } @Test - public void testBasicsOnTwoCachesWithSameExecutor() throws Exception - { + public void testBasicsOnTwoCachesWithSameExecutor() throws Exception { Timing timing = new Timing(); - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); + CuratorFramework client = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); client.start(); - try - { + try { client.create().forPath("/test"); - final BlockingQueue events = new LinkedBlockingQueue(); + final BlockingQueue events = + new LinkedBlockingQueue(); final ExecutorService exec = Executors.newSingleThreadExecutor(); - try ( PathChildrenCache cache = new PathChildrenCache(client, "/test", true, false, exec) ) - { - cache.getListenable().addListener - ( - new PathChildrenCacheListener() - { - @Override - public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception - { - if ( event.getData().getPath().equals("/test/one") ) - { - events.offer(event.getType()); - } - } + try (PathChildrenCache cache = new PathChildrenCache(client, "/test", true, false, exec)) { + cache.getListenable().addListener(new PathChildrenCacheListener() { + @Override + public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception { + if (event.getData().getPath().equals("/test/one")) { + events.offer(event.getType()); } - ); + } + }); cache.start(); - final BlockingQueue events2 = new LinkedBlockingQueue(); - try ( PathChildrenCache cache2 = new PathChildrenCache(client, "/test", true, false, exec) ) - { - cache2.getListenable().addListener( - new PathChildrenCacheListener() - { - @Override - public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) - throws Exception - { - if ( event.getData().getPath().equals("/test/one") ) - { - events2.offer(event.getType()); - } + final BlockingQueue events2 = + new LinkedBlockingQueue(); + try (PathChildrenCache cache2 = new PathChildrenCache(client, "/test", true, false, exec)) { + cache2.getListenable().addListener(new PathChildrenCacheListener() { + @Override + public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception { + if (event.getData().getPath().equals("/test/one")) { + events2.offer(event.getType()); } } - ); + }); cache2.start(); client.create().forPath("/test/one", "hey there".getBytes()); - assertEquals(events.poll(timing.forWaiting().seconds(), TimeUnit.SECONDS), PathChildrenCacheEvent.Type.CHILD_ADDED); - assertEquals(events2.poll(timing.forWaiting().seconds(), TimeUnit.SECONDS), PathChildrenCacheEvent.Type.CHILD_ADDED); + assertEquals( + events.poll(timing.forWaiting().seconds(), TimeUnit.SECONDS), + PathChildrenCacheEvent.Type.CHILD_ADDED); + assertEquals( + events2.poll(timing.forWaiting().seconds(), TimeUnit.SECONDS), + PathChildrenCacheEvent.Type.CHILD_ADDED); client.setData().forPath("/test/one", "sup!".getBytes()); - assertEquals(events.poll(timing.forWaiting().seconds(), TimeUnit.SECONDS), PathChildrenCacheEvent.Type.CHILD_UPDATED); - assertEquals(events2.poll(timing.forWaiting().seconds(), TimeUnit.SECONDS), PathChildrenCacheEvent.Type.CHILD_UPDATED); + assertEquals( + events.poll(timing.forWaiting().seconds(), TimeUnit.SECONDS), + PathChildrenCacheEvent.Type.CHILD_UPDATED); + assertEquals( + events2.poll(timing.forWaiting().seconds(), TimeUnit.SECONDS), + PathChildrenCacheEvent.Type.CHILD_UPDATED); assertEquals(new String(cache.getCurrentData("/test/one").getData()), "sup!"); assertEquals(new String(cache2.getCurrentData("/test/one").getData()), "sup!"); client.delete().forPath("/test/one"); - assertEquals(events.poll(timing.forWaiting().seconds(), TimeUnit.SECONDS), PathChildrenCacheEvent.Type.CHILD_REMOVED); - assertEquals(events2.poll(timing.forWaiting().seconds(), TimeUnit.SECONDS), PathChildrenCacheEvent.Type.CHILD_REMOVED); + assertEquals( + events.poll(timing.forWaiting().seconds(), TimeUnit.SECONDS), + PathChildrenCacheEvent.Type.CHILD_REMOVED); + assertEquals( + events2.poll(timing.forWaiting().seconds(), TimeUnit.SECONDS), + PathChildrenCacheEvent.Type.CHILD_REMOVED); } } - } - finally - { + } finally { TestCleanState.closeAndTestClean(client); } } @Test - public void testDeleteNodeAfterCloseDoesntCallExecutor() - throws Exception - { + public void testDeleteNodeAfterCloseDoesntCallExecutor() throws Exception { Timing timing = new Timing(); - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); + CuratorFramework client = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); client.start(); - try - { + try { client.create().forPath("/test"); - final ExecuteCalledWatchingExecutorService exec = new ExecuteCalledWatchingExecutorService(Executors.newSingleThreadExecutor()); - try ( PathChildrenCache cache = new PathChildrenCache(client, "/test", true, false, exec) ) - { + final ExecuteCalledWatchingExecutorService exec = + new ExecuteCalledWatchingExecutorService(Executors.newSingleThreadExecutor()); + try (PathChildrenCache cache = new PathChildrenCache(client, "/test", true, false, exec)) { cache.start(); client.create().forPath("/test/one", "hey there".getBytes()); @@ -1105,12 +925,9 @@ public void testDeleteNodeAfterCloseDoesntCallExecutor() client.delete().forPath("/test/one"); timing.sleepABit(); assertFalse(exec.isExecuteCalled()); - } - finally - { + } finally { TestCleanState.closeAndTestClean(client); } - } /** @@ -1119,44 +936,36 @@ public void testDeleteNodeAfterCloseDoesntCallExecutor() * @throws Exception */ @Test - public void testInterruptedOperationOnShutdown() throws Exception - { - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), 30000, 30000, new RetryOneTime(1)); + public void testInterruptedOperationOnShutdown() throws Exception { + CuratorFramework client = + CuratorFrameworkFactory.newClient(server.getConnectString(), 30000, 30000, new RetryOneTime(1)); client.start(); - try - { + try { final CountDownLatch latch = new CountDownLatch(1); - try ( final PathChildrenCache cache = new PathChildrenCache(client, "/test", false) { + try (final PathChildrenCache cache = new PathChildrenCache(client, "/test", false) { @Override - protected void handleException(Throwable e) - { + protected void handleException(Throwable e) { latch.countDown(); } - } ) - { + }) { cache.start(); - cache.offerOperation(new Operation() - { + cache.offerOperation(new Operation() { @Override - public void invoke() throws Exception - { + public void invoke() throws Exception { Thread.sleep(5000); } }); Thread.sleep(1000); - } latch.await(5, TimeUnit.SECONDS); assertTrue(latch.getCount() == 1, "Unexpected exception occurred"); - } - finally - { + } finally { TestCleanState.closeAndTestClean(client); } } diff --git a/curator-recipes/src/test/java/org/apache/curator/framework/recipes/cache/TestPathChildrenCacheEventOrdering.java b/curator-recipes/src/test/java/org/apache/curator/framework/recipes/cache/TestPathChildrenCacheEventOrdering.java index b69265a68..3505121a8 100644 --- a/curator-recipes/src/test/java/org/apache/curator/framework/recipes/cache/TestPathChildrenCacheEventOrdering.java +++ b/curator-recipes/src/test/java/org/apache/curator/framework/recipes/cache/TestPathChildrenCacheEventOrdering.java @@ -19,32 +19,26 @@ package org.apache.curator.framework.recipes.cache; -import org.apache.curator.framework.CuratorFramework; import java.util.concurrent.BlockingQueue; +import org.apache.curator.framework.CuratorFramework; -public class TestPathChildrenCacheEventOrdering extends TestEventOrdering -{ +public class TestPathChildrenCacheEventOrdering extends TestEventOrdering { @Override - protected int getActualQty(PathChildrenCache cache) - { + protected int getActualQty(PathChildrenCache cache) { return cache.getCurrentData().size(); } @Override - protected PathChildrenCache newCache(CuratorFramework client, String path, final BlockingQueue events) throws Exception - { + protected PathChildrenCache newCache(CuratorFramework client, String path, final BlockingQueue events) + throws Exception { PathChildrenCache cache = new PathChildrenCache(client, path, false); - PathChildrenCacheListener listener = new PathChildrenCacheListener() - { + PathChildrenCacheListener listener = new PathChildrenCacheListener() { @Override - public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception - { - if ( event.getType() == PathChildrenCacheEvent.Type.CHILD_ADDED ) - { + public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception { + if (event.getType() == PathChildrenCacheEvent.Type.CHILD_ADDED) { events.add(new Event(EventType.ADDED, event.getData().getPath())); } - if ( event.getType() == PathChildrenCacheEvent.Type.CHILD_REMOVED ) - { + if (event.getType() == PathChildrenCacheEvent.Type.CHILD_REMOVED) { events.add(new Event(EventType.DELETED, event.getData().getPath())); } } diff --git a/curator-recipes/src/test/java/org/apache/curator/framework/recipes/cache/TestPathChildrenCacheInCluster.java b/curator-recipes/src/test/java/org/apache/curator/framework/recipes/cache/TestPathChildrenCacheInCluster.java index e0576144e..d8c22240f 100644 --- a/curator-recipes/src/test/java/org/apache/curator/framework/recipes/cache/TestPathChildrenCacheInCluster.java +++ b/curator-recipes/src/test/java/org/apache/curator/framework/recipes/cache/TestPathChildrenCacheInCluster.java @@ -22,48 +22,43 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import com.google.common.collect.Queues; -import org.apache.curator.test.BaseClassForTests; -import org.apache.curator.test.compatibility.CuratorTestBase; -import org.apache.curator.utils.CloseableUtils; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.retry.RetryOneTime; +import org.apache.curator.test.BaseClassForTests; import org.apache.curator.test.InstanceSpec; import org.apache.curator.test.TestingCluster; import org.apache.curator.test.Timing; +import org.apache.curator.test.compatibility.CuratorTestBase; +import org.apache.curator.utils.CloseableUtils; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicReference; - @Tag(CuratorTestBase.zk35TestCompatibilityGroup) -public class TestPathChildrenCacheInCluster extends BaseClassForTests -{ +public class TestPathChildrenCacheInCluster extends BaseClassForTests { @Test - @Disabled // this test is very flakey - it needs to be re-written at some point - public void testMissedDelete() throws Exception - { + @Disabled // this test is very flakey - it needs to be re-written at some point + public void testMissedDelete() throws Exception { Timing timing = new Timing(); PathChildrenCache cache = null; CuratorFramework client1 = null; CuratorFramework client2 = null; TestingCluster cluster = createAndStartCluster(3); - try - { + try { // client 1 only connects to 1 server InstanceSpec client1Instance = cluster.getInstances().iterator().next(); - client1 = CuratorFrameworkFactory.newClient(client1Instance.getConnectString(), 1000, 1000, new RetryOneTime(1)); + client1 = CuratorFrameworkFactory.newClient( + client1Instance.getConnectString(), 1000, 1000, new RetryOneTime(1)); cache = new PathChildrenCache(client1, "/test", true); final BlockingQueue events = Queues.newLinkedBlockingQueue(); - PathChildrenCacheListener listener = new PathChildrenCacheListener() - { + PathChildrenCacheListener listener = new PathChildrenCacheListener() { @Override - public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception - { + public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception { events.add(event.getType()); } }; @@ -74,25 +69,36 @@ public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) th client1.start(); client2.start(); cache.start(PathChildrenCache.StartMode.POST_INITIALIZED_EVENT); - assertEquals(events.poll(timing.milliseconds(), TimeUnit.MILLISECONDS), PathChildrenCacheEvent.Type.CONNECTION_RECONNECTED); - assertEquals(events.poll(timing.milliseconds(), TimeUnit.MILLISECONDS), PathChildrenCacheEvent.Type.INITIALIZED); + assertEquals( + events.poll(timing.milliseconds(), TimeUnit.MILLISECONDS), + PathChildrenCacheEvent.Type.CONNECTION_RECONNECTED); + assertEquals( + events.poll(timing.milliseconds(), TimeUnit.MILLISECONDS), PathChildrenCacheEvent.Type.INITIALIZED); client2.create().creatingParentsIfNeeded().forPath("/test/node", "first".getBytes()); - assertEquals(events.poll(timing.milliseconds(), TimeUnit.MILLISECONDS), PathChildrenCacheEvent.Type.CHILD_ADDED); + assertEquals( + events.poll(timing.milliseconds(), TimeUnit.MILLISECONDS), PathChildrenCacheEvent.Type.CHILD_ADDED); cluster.killServer(client1Instance); - assertEquals(events.poll(timing.milliseconds(), TimeUnit.MILLISECONDS), PathChildrenCacheEvent.Type.CONNECTION_SUSPENDED); - assertEquals(events.poll(timing.milliseconds(), TimeUnit.MILLISECONDS), PathChildrenCacheEvent.Type.CONNECTION_LOST); + assertEquals( + events.poll(timing.milliseconds(), TimeUnit.MILLISECONDS), + PathChildrenCacheEvent.Type.CONNECTION_SUSPENDED); + assertEquals( + events.poll(timing.milliseconds(), TimeUnit.MILLISECONDS), + PathChildrenCacheEvent.Type.CONNECTION_LOST); client2.delete().forPath("/test/node"); client2.create().forPath("/test/node", "second".getBytes()); cluster.restartServer(client1Instance); - assertEquals(events.poll(timing.milliseconds(), TimeUnit.MILLISECONDS), PathChildrenCacheEvent.Type.CONNECTION_RECONNECTED); - assertEquals(events.poll(timing.milliseconds(), TimeUnit.MILLISECONDS), PathChildrenCacheEvent.Type.CHILD_UPDATED); // "/test/node" is different - should register as updated - } - finally - { + assertEquals( + events.poll(timing.milliseconds(), TimeUnit.MILLISECONDS), + PathChildrenCacheEvent.Type.CONNECTION_RECONNECTED); + assertEquals( + events.poll(timing.milliseconds(), TimeUnit.MILLISECONDS), + PathChildrenCacheEvent.Type + .CHILD_UPDATED); // "/test/node" is different - should register as updated + } finally { CloseableUtils.closeQuietly(client1); CloseableUtils.closeQuietly(client2); CloseableUtils.closeQuietly(cache); @@ -101,47 +107,36 @@ public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) th } @Test - public void testServerLoss() throws Exception - { - Timing timing = new Timing(); + public void testServerLoss() throws Exception { + Timing timing = new Timing(); CuratorFramework client = null; PathChildrenCache cache = null; TestingCluster cluster = createAndStartCluster(3); - try - { - client = CuratorFrameworkFactory.newClient(cluster.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); + try { + client = CuratorFrameworkFactory.newClient( + cluster.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); client.start(); client.create().creatingParentsIfNeeded().forPath("/test"); cache = new PathChildrenCache(client, "/test", false); cache.start(); - final CountDownLatch resetLatch = new CountDownLatch(1); - final CountDownLatch reconnectLatch = new CountDownLatch(1); - final AtomicReference latch = new AtomicReference(new CountDownLatch(3)); - cache.getListenable().addListener - ( - new PathChildrenCacheListener() - { - @Override - public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception - { - if ( event.getType() == PathChildrenCacheEvent.Type.CONNECTION_SUSPENDED ) - { - resetLatch.countDown(); - } - else if ( event.getType() == PathChildrenCacheEvent.Type.CONNECTION_RECONNECTED ) - { - reconnectLatch.countDown(); - } - else if ( event.getType() == PathChildrenCacheEvent.Type.CHILD_ADDED ) - { - latch.get().countDown(); - } - } + final CountDownLatch resetLatch = new CountDownLatch(1); + final CountDownLatch reconnectLatch = new CountDownLatch(1); + final AtomicReference latch = new AtomicReference(new CountDownLatch(3)); + cache.getListenable().addListener(new PathChildrenCacheListener() { + @Override + public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception { + if (event.getType() == PathChildrenCacheEvent.Type.CONNECTION_SUSPENDED) { + resetLatch.countDown(); + } else if (event.getType() == PathChildrenCacheEvent.Type.CONNECTION_RECONNECTED) { + reconnectLatch.countDown(); + } else if (event.getType() == PathChildrenCacheEvent.Type.CHILD_ADDED) { + latch.get().countDown(); } - ); + } + }); client.create().forPath("/test/one"); client.create().forPath("/test/two"); @@ -149,15 +144,14 @@ else if ( event.getType() == PathChildrenCacheEvent.Type.CHILD_ADDED ) assertTrue(latch.get().await(10, TimeUnit.SECONDS)); - InstanceSpec connectionInstance = cluster.findConnectionInstance(client.getZookeeperClient().getZooKeeper()); + InstanceSpec connectionInstance = + cluster.findConnectionInstance(client.getZookeeperClient().getZooKeeper()); cluster.killServer(connectionInstance); assertTrue(timing.awaitLatch(reconnectLatch)); assertEquals(cache.getCurrentData().size(), 3); - } - finally - { + } finally { CloseableUtils.closeQuietly(cache); CloseableUtils.closeQuietly(client); CloseableUtils.closeQuietly(cluster); diff --git a/curator-recipes/src/test/java/org/apache/curator/framework/recipes/cache/TestTreeCache.java b/curator-recipes/src/test/java/org/apache/curator/framework/recipes/cache/TestTreeCache.java index 354e3b22e..6a9ae6294 100644 --- a/curator-recipes/src/test/java/org/apache/curator/framework/recipes/cache/TestTreeCache.java +++ b/curator-recipes/src/test/java/org/apache/curator/framework/recipes/cache/TestTreeCache.java @@ -25,6 +25,8 @@ import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; import com.google.common.collect.ImmutableSet; +import java.util.concurrent.Semaphore; +import java.util.concurrent.atomic.AtomicBoolean; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.api.UnhandledErrorListener; import org.apache.curator.framework.recipes.cache.TreeCacheEvent.Type; @@ -34,15 +36,10 @@ import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; -import java.util.concurrent.Semaphore; -import java.util.concurrent.atomic.AtomicBoolean; - @Tag(CuratorTestBase.zk35TestCompatibilityGroup) -public class TestTreeCache extends BaseTestTreeCache -{ +public class TestTreeCache extends BaseTestTreeCache { @Test - public void testSelector() throws Exception - { + public void testSelector() throws Exception { client.create().forPath("/root"); client.create().forPath("/root/n1-a"); client.create().forPath("/root/n1-b"); @@ -52,17 +49,14 @@ public void testSelector() throws Exception client.create().forPath("/root/n1-c"); client.create().forPath("/root/n1-d"); - TreeCacheSelector selector = new TreeCacheSelector() - { + TreeCacheSelector selector = new TreeCacheSelector() { @Override - public boolean traverseChildren(String fullPath) - { + public boolean traverseChildren(String fullPath) { return !fullPath.equals("/root/n1-b/n2-b"); } @Override - public boolean acceptChild(String fullPath) - { + public boolean acceptChild(String fullPath) { return !fullPath.equals("/root/n1-c"); } }; @@ -80,8 +74,7 @@ public boolean acceptChild(String fullPath) } @Test - public void testStartup() throws Exception - { + public void testStartup() throws Exception { client.create().forPath("/test"); client.create().forPath("/test/1", "one".getBytes()); client.create().forPath("/test/2", "two".getBytes()); @@ -105,8 +98,7 @@ public void testStartup() throws Exception } @Test - public void testCreateParents() throws Exception - { + public void testCreateParents() throws Exception { cache = newTreeCacheWithListeners(client, "/one/two/three"); cache.start(); assertEvent(TreeCacheEvent.Type.INITIALIZED); @@ -114,7 +106,8 @@ public void testCreateParents() throws Exception assertNull(client.checkExists().forPath("/one/two/three")); cache.close(); - cache = buildWithListeners(TreeCache.newBuilder(client, "/one/two/three").setCreateParentNodes(true)); + cache = buildWithListeners( + TreeCache.newBuilder(client, "/one/two/three").setCreateParentNodes(true)); cache.start(); assertEvent(TreeCacheEvent.Type.NODE_ADDED, "/one/two/three"); assertEvent(TreeCacheEvent.Type.INITIALIZED); @@ -123,8 +116,7 @@ public void testCreateParents() throws Exception } @Test - public void testStartEmpty() throws Exception - { + public void testStartEmpty() throws Exception { cache = newTreeCacheWithListeners(client, "/test"); cache.start(); assertEvent(TreeCacheEvent.Type.INITIALIZED); @@ -135,8 +127,7 @@ public void testStartEmpty() throws Exception } @Test - public void testStartEmptyDeeper() throws Exception - { + public void testStartEmptyDeeper() throws Exception { cache = newTreeCacheWithListeners(client, "/test/foo/bar"); cache.start(); assertEvent(TreeCacheEvent.Type.INITIALIZED); @@ -149,8 +140,7 @@ public void testStartEmptyDeeper() throws Exception } @Test - public void testDepth0() throws Exception - { + public void testDepth0() throws Exception { client.create().forPath("/test"); client.create().forPath("/test/1", "one".getBytes()); client.create().forPath("/test/2", "two".getBytes()); @@ -170,8 +160,7 @@ public void testDepth0() throws Exception } @Test - public void testDepth1() throws Exception - { + public void testDepth1() throws Exception { client.create().forPath("/test"); client.create().forPath("/test/1", "one".getBytes()); client.create().forPath("/test/2", "two".getBytes()); @@ -196,8 +185,7 @@ public void testDepth1() throws Exception } @Test - public void testDepth1Deeper() throws Exception - { + public void testDepth1Deeper() throws Exception { client.create().forPath("/test"); client.create().forPath("/test/foo"); client.create().forPath("/test/foo/bar"); @@ -217,8 +205,7 @@ public void testDepth1Deeper() throws Exception } @Test - public void testAsyncInitialPopulation() throws Exception - { + public void testAsyncInitialPopulation() throws Exception { client.create().forPath("/test"); client.create().forPath("/test/one", "hey there".getBytes()); @@ -231,8 +218,7 @@ public void testAsyncInitialPopulation() throws Exception } @Test - public void testFromRoot() throws Exception - { + public void testFromRoot() throws Exception { client.create().forPath("/test"); client.create().forPath("/test/one", "hey there".getBytes()); @@ -251,8 +237,7 @@ public void testFromRoot() throws Exception } @Test - public void testFromRootWithDepth() throws Exception - { + public void testFromRootWithDepth() throws Exception { client.create().forPath("/test"); client.create().forPath("/test/one", "hey there".getBytes()); @@ -270,8 +255,7 @@ public void testFromRootWithDepth() throws Exception } @Test - public void testWithNamespace() throws Exception - { + public void testWithNamespace() throws Exception { client.create().forPath("/outer"); client.create().forPath("/outer/foo"); client.create().forPath("/outer/test"); @@ -290,8 +274,7 @@ public void testWithNamespace() throws Exception } @Test - public void testWithNamespaceAtRoot() throws Exception - { + public void testWithNamespaceAtRoot() throws Exception { client.create().forPath("/outer"); client.create().forPath("/outer/foo"); client.create().forPath("/outer/test"); @@ -313,8 +296,7 @@ public void testWithNamespaceAtRoot() throws Exception } @Test - public void testSyncInitialPopulation() throws Exception - { + public void testSyncInitialPopulation() throws Exception { cache = newTreeCacheWithListeners(client, "/test"); cache.start(); assertEvent(TreeCacheEvent.Type.INITIALIZED); @@ -327,8 +309,7 @@ public void testSyncInitialPopulation() throws Exception } @Test - public void testChildrenInitialized() throws Exception - { + public void testChildrenInitialized() throws Exception { client.create().forPath("/test", "".getBytes()); client.create().forPath("/test/1", "1".getBytes()); client.create().forPath("/test/2", "2".getBytes()); @@ -345,8 +326,7 @@ public void testChildrenInitialized() throws Exception } @Test - public void testUpdateWhenNotCachingData() throws Exception - { + public void testUpdateWhenNotCachingData() throws Exception { client.create().forPath("/test"); cache = buildWithListeners(TreeCache.newBuilder(client, "/test").setCacheData(false)); @@ -367,8 +347,7 @@ public void testUpdateWhenNotCachingData() throws Exception } @Test - public void testDeleteThenCreate() throws Exception - { + public void testDeleteThenCreate() throws Exception { client.create().forPath("/test"); client.create().forPath("/test/foo", "one".getBytes()); @@ -392,8 +371,7 @@ public void testDeleteThenCreate() throws Exception } @Test - public void testDeleteThenCreateRoot() throws Exception - { + public void testDeleteThenCreateRoot() throws Exception { client.create().forPath("/test"); client.create().forPath("/test/foo", "one".getBytes()); @@ -416,8 +394,7 @@ public void testDeleteThenCreateRoot() throws Exception } @Test - public void testKilledSession() throws Exception - { + public void testKilledSession() throws Exception { client.create().forPath("/test"); cache = newTreeCacheWithListeners(client, "/test"); @@ -438,8 +415,7 @@ public void testKilledSession() throws Exception } @Test - public void testBasics() throws Exception - { + public void testBasics() throws Exception { client.create().forPath("/test"); cache = newTreeCacheWithListeners(client, "/test"); @@ -471,8 +447,7 @@ public void testBasics() throws Exception } @Test - public void testBasicsWithNoZkWatches() throws Exception - { + public void testBasicsWithNoZkWatches() throws Exception { client.create().forPath("/test"); client.create().forPath("/test/one", "hey there".getBytes()); @@ -495,24 +470,20 @@ public void testBasicsWithNoZkWatches() throws Exception } @Test - public void testBasicsOnTwoCaches() throws Exception - { + public void testBasicsOnTwoCaches() throws Exception { TreeCache cache2 = newTreeCacheWithListeners(client, "/test"); - cache2.getListenable().removeListener(eventListener); // Don't listen on the second cache. + cache2.getListenable().removeListener(eventListener); // Don't listen on the second cache. // Just ensures the same event count; enables test flow control on cache2. final Semaphore semaphore = new Semaphore(0); - cache2.getListenable().addListener(new TreeCacheListener() - { + cache2.getListenable().addListener(new TreeCacheListener() { @Override - public void childEvent(CuratorFramework client, TreeCacheEvent event) throws Exception - { + public void childEvent(CuratorFramework client, TreeCacheEvent event) throws Exception { semaphore.release(); } }); - try - { + try { client.create().forPath("/test"); cache = newTreeCacheWithListeners(client, "/test"); @@ -543,16 +514,13 @@ public void childEvent(CuratorFramework client, TreeCacheEvent event) throws Exc assertNoMoreEvents(); assertEquals(semaphore.availablePermits(), 0); - } - finally - { + } finally { CloseableUtils.closeQuietly(cache2); } } @Test - public void testDeleteNodeAfterCloseDoesntCallExecutor() throws Exception - { + public void testDeleteNodeAfterCloseDoesntCallExecutor() throws Exception { client.create().forPath("/test"); cache = newTreeCacheWithListeners(client, "/test"); @@ -575,8 +543,7 @@ public void testDeleteNodeAfterCloseDoesntCallExecutor() throws Exception * Make sure TreeCache gets to a sane state when we can't initially connect to server. */ @Test - public void testServerNotStartedYet() throws Exception - { + public void testServerNotStartedYet() throws Exception { // Stop the existing server. server.stop(); @@ -600,20 +567,16 @@ public void testServerNotStartedYet() throws Exception } @Test - public void testErrorListener() throws Exception - { + public void testErrorListener() throws Exception { client.create().forPath("/test"); cache = buildWithListeners(TreeCache.newBuilder(client, "/test")); // Register a listener that throws an exception for the event - cache.getListenable().addListener(new TreeCacheListener() - { + cache.getListenable().addListener(new TreeCacheListener() { @Override - public void childEvent(CuratorFramework client, TreeCacheEvent event) throws Exception - { - if ( event.getType() == Type.NODE_UPDATED ) - { + public void childEvent(CuratorFramework client, TreeCacheEvent event) throws Exception { + if (event.getType() == Type.NODE_UPDATED) { throw new RuntimeException("Test Exception"); } } @@ -621,11 +584,9 @@ public void childEvent(CuratorFramework client, TreeCacheEvent event) throws Exc cache.getUnhandledErrorListenable().removeListener(errorListener); final AtomicBoolean isProcessed = new AtomicBoolean(false); - cache.getUnhandledErrorListenable().addListener(new UnhandledErrorListener() - { + cache.getUnhandledErrorListenable().addListener(new UnhandledErrorListener() { @Override - public void unhandledError(String message, Throwable e) - { + public void unhandledError(String message, Throwable e) { assertFalse(isProcessed.compareAndSet(false, true)); } }); diff --git a/curator-recipes/src/test/java/org/apache/curator/framework/recipes/cache/TestTreeCacheEventOrdering.java b/curator-recipes/src/test/java/org/apache/curator/framework/recipes/cache/TestTreeCacheEventOrdering.java index dca301d33..fd6ba2808 100644 --- a/curator-recipes/src/test/java/org/apache/curator/framework/recipes/cache/TestTreeCacheEventOrdering.java +++ b/curator-recipes/src/test/java/org/apache/curator/framework/recipes/cache/TestTreeCacheEventOrdering.java @@ -19,34 +19,27 @@ package org.apache.curator.framework.recipes.cache; -import org.apache.curator.framework.CuratorFramework; import java.util.concurrent.BlockingQueue; +import org.apache.curator.framework.CuratorFramework; -public class TestTreeCacheEventOrdering extends TestEventOrdering -{ +public class TestTreeCacheEventOrdering extends TestEventOrdering { @Override - protected int getActualQty(TreeCache cache) - { + protected int getActualQty(TreeCache cache) { return cache.getCurrentChildren("/root").size(); } @Override - protected TreeCache newCache(CuratorFramework client, String path, final BlockingQueue events) throws Exception - { + protected TreeCache newCache(CuratorFramework client, String path, final BlockingQueue events) + throws Exception { TreeCache cache = new TreeCache(client, path); - TreeCacheListener listener = new TreeCacheListener() - { + TreeCacheListener listener = new TreeCacheListener() { @Override - public void childEvent(CuratorFramework client, TreeCacheEvent event) throws Exception - { - if ( (event.getData() != null) && (event.getData().getPath().startsWith("/root/")) ) - { - if ( event.getType() == TreeCacheEvent.Type.NODE_ADDED ) - { + public void childEvent(CuratorFramework client, TreeCacheEvent event) throws Exception { + if ((event.getData() != null) && (event.getData().getPath().startsWith("/root/"))) { + if (event.getType() == TreeCacheEvent.Type.NODE_ADDED) { events.add(new Event(EventType.ADDED, event.getData().getPath())); } - if ( event.getType() == TreeCacheEvent.Type.NODE_REMOVED ) - { + if (event.getType() == TreeCacheEvent.Type.NODE_REMOVED) { events.add(new Event(EventType.DELETED, event.getData().getPath())); } } diff --git a/curator-recipes/src/test/java/org/apache/curator/framework/recipes/cache/TestTreeCacheIteratorAndSize.java b/curator-recipes/src/test/java/org/apache/curator/framework/recipes/cache/TestTreeCacheIteratorAndSize.java index 99695fb4a..d724fec1d 100644 --- a/curator-recipes/src/test/java/org/apache/curator/framework/recipes/cache/TestTreeCacheIteratorAndSize.java +++ b/curator-recipes/src/test/java/org/apache/curator/framework/recipes/cache/TestTreeCacheIteratorAndSize.java @@ -24,24 +24,21 @@ import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import com.google.common.collect.Sets; -import org.apache.curator.framework.CuratorFramework; -import org.apache.curator.framework.CuratorFrameworkFactory; -import org.apache.curator.retry.RetryOneTime; -import org.apache.curator.test.compatibility.CuratorTestBase; -import org.junit.jupiter.api.Test; - import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.concurrent.ThreadLocalRandom; +import org.apache.curator.framework.CuratorFramework; +import org.apache.curator.framework.CuratorFrameworkFactory; +import org.apache.curator.retry.RetryOneTime; +import org.apache.curator.test.compatibility.CuratorTestBase; +import org.junit.jupiter.api.Test; -public class TestTreeCacheIteratorAndSize extends CuratorTestBase -{ +public class TestTreeCacheIteratorAndSize extends CuratorTestBase { @Test - public void testBasic() throws Exception - { + public void testBasic() throws Exception { final String[] nodes = { "/base/test", "/base/test/3", @@ -60,17 +57,15 @@ public void testBasic() throws Exception "/base/test/3/3/3" }; - try ( CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)) ) - { + try (CuratorFramework client = + CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1))) { client.start(); String basePath = "/base/test"; - try (TreeCache treeCache = new TreeCache(client, basePath) ) - { + try (TreeCache treeCache = new TreeCache(client, basePath)) { treeCache.start(); - for ( String node : nodes ) - { + for (String node : nodes) { client.create().creatingParentsIfNeeded().forPath(node, node.getBytes()); } @@ -78,15 +73,13 @@ public void testBasic() throws Exception Iterator iterator = treeCache.iterator(); Map iteratorValues = new HashMap<>(); - while ( iterator.hasNext() ) - { + while (iterator.hasNext()) { ChildData next = iterator.next(); iteratorValues.put(next.getPath(), next.getData()); } assertEquals(iteratorValues.size(), nodes.length); - for ( String node : nodes ) - { + for (String node : nodes) { assertArrayEquals(iteratorValues.get(node), node.getBytes()); } @@ -96,35 +89,33 @@ public void testBasic() throws Exception } @Test - public void testIteratorWithRandomGraph() throws Exception - { + public void testIteratorWithRandomGraph() throws Exception { Map pathAndData = new HashMap<>(); ThreadLocalRandom random = ThreadLocalRandom.current(); int nodeQty = random.nextInt(100, 200); int maxPerRow = random.nextInt(1, 10); int maxDepth = random.nextInt(3, 5); - try ( CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)) ) - { + try (CuratorFramework client = + CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1))) { client.start(); String basePath = "/base/test"; - try (TreeCache treeCache = new TreeCache(client, basePath) ) - { + try (TreeCache treeCache = new TreeCache(client, basePath)) { treeCache.start(); client.create().creatingParentsIfNeeded().forPath(basePath, "0".getBytes()); pathAndData.put(basePath, "0"); - while ( nodeQty-- > 0 ) - { + while (nodeQty-- > 0) { int thisDepth = random.nextInt(1, maxDepth + 1); StringBuilder path = new StringBuilder(basePath); - for ( int i = 0; i < thisDepth; ++i ) - { + for (int i = 0; i < thisDepth; ++i) { path.append("/").append(random.nextInt(maxPerRow)); long value = random.nextLong(); pathAndData.put(path.toString(), Long.toString(value)); - client.create().orSetData().forPath(path.toString(), Long.toString(value).getBytes()); + client.create() + .orSetData() + .forPath(path.toString(), Long.toString(value).getBytes()); } } @@ -134,8 +125,7 @@ public void testIteratorWithRandomGraph() throws Exception // at this point we have a cached graph of random nodes with random values Iterator iterator = treeCache.iterator(); - while ( iterator.hasNext() ) - { + while (iterator.hasNext()) { ChildData next = iterator.next(); assertTrue(pathAndData.containsKey(next.getPath())); assertArrayEquals(pathAndData.get(next.getPath()).getBytes(), next.getData()); @@ -148,14 +138,12 @@ public void testIteratorWithRandomGraph() throws Exception } @Test - public void testEmptyTree() throws Exception - { - try (CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1))) - { + public void testEmptyTree() throws Exception { + try (CuratorFramework client = + CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1))) { client.start(); - try (TreeCache treeCache = new TreeCache(client, "/base/test")) - { + try (TreeCache treeCache = new TreeCache(client, "/base/test")) { treeCache.start(); Iterator iterator = treeCache.iterator(); @@ -166,14 +154,12 @@ public void testEmptyTree() throws Exception } @Test - public void testWithDeletedNodes() throws Exception - { - try (CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1))) - { + public void testWithDeletedNodes() throws Exception { + try (CuratorFramework client = + CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1))) { client.start(); - try (TreeCache treeCache = new TreeCache(client, "/foo")) - { + try (TreeCache treeCache = new TreeCache(client, "/foo")) { treeCache.start(); client.create().forPath("/foo"); @@ -192,13 +178,14 @@ public void testWithDeletedNodes() throws Exception Iterator iterator = treeCache.iterator(); Set paths = new HashSet<>(); - while ( iterator.hasNext() ) - { + while (iterator.hasNext()) { ChildData next = iterator.next(); paths.add(next.getPath()); } - assertEquals(paths, Sets.newHashSet("/foo", "/foo/a1", "/foo/a2", "/foo/a2/a2.1", "/foo/a3", "/foo/a3/a3.2")); + assertEquals( + paths, + Sets.newHashSet("/foo", "/foo/a1", "/foo/a2", "/foo/a2/a2.1", "/foo/a3", "/foo/a3/a3.2")); assertEquals(treeCache.size(), 6); } } diff --git a/curator-recipes/src/test/java/org/apache/curator/framework/recipes/cache/TestTreeCacheRandomTree.java b/curator-recipes/src/test/java/org/apache/curator/framework/recipes/cache/TestTreeCacheRandomTree.java index 9a63b57fe..13c30e66e 100644 --- a/curator-recipes/src/test/java/org/apache/curator/framework/recipes/cache/TestTreeCacheRandomTree.java +++ b/curator-recipes/src/test/java/org/apache/curator/framework/recipes/cache/TestTreeCacheRandomTree.java @@ -24,28 +24,24 @@ import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertSame; import com.google.common.collect.Iterables; -import org.apache.curator.framework.CuratorFramework; -import org.apache.curator.utils.ZKPaths; -import org.junit.jupiter.api.Test; - import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.Random; +import org.apache.curator.framework.CuratorFramework; +import org.apache.curator.utils.ZKPaths; +import org.junit.jupiter.api.Test; -public class TestTreeCacheRandomTree extends BaseTestTreeCache -{ +public class TestTreeCacheRandomTree extends BaseTestTreeCache { /** * A randomly generated source-of-truth node for {@link #testGiantRandomDeepTree()} */ - private static final class TestNode - { + private static final class TestNode { String fullPath; byte[] data; Map children = new HashMap(); - TestNode(String fullPath, byte[] data) - { + TestNode(String fullPath, byte[] data) { this.fullPath = fullPath; this.data = data; } @@ -75,16 +71,12 @@ public void testGiantRandomDeepTreeWithDepth() throws Exception { * a TreeCache to follow the changes. At each step, assert that TreeCache matches our * source-of-truth test data, and that we see exactly the set of events we expect to see. */ - private void doTestGiantRandomDeepTree() throws Exception - { + private void doTestGiantRandomDeepTree() throws Exception { client.create().forPath("/tree", null); CuratorFramework cl = client.usingNamespace("tree"); - if ( withDepth ) - { + if (withDepth) { cache = buildWithListeners(TreeCache.newBuilder(cl, "/").setMaxDepth(TEST_DEPTH)); - } - else - { + } else { cache = newTreeCacheWithListeners(cl, "/"); } cache.start(); @@ -97,14 +89,12 @@ private void doTestGiantRandomDeepTree() throws Exception int removals = 0; int updates = 0; - for ( int i = 0; i < ITERATIONS; ++i ) - { + for (int i = 0; i < ITERATIONS; ++i) { // Select a node to update, randomly navigate down through the tree int depth = 0; TestNode last = null; TestNode node = root; - while ( !node.children.isEmpty() && random.nextDouble() < DIVE_CHANCE ) - { + while (!node.children.isEmpty() && random.nextDouble() < DIVE_CHANCE) { // Go down a level in the tree. Select a random child for the next iteration. last = node; node = Iterables.get(node.children.values(), random.nextInt(node.children.size())); @@ -113,78 +103,71 @@ private void doTestGiantRandomDeepTree() throws Exception maxDepth = Math.max(depth, maxDepth); // Okay we found a node, let's do something interesting with it. - switch ( random.nextInt(3) ) - { - case 0: - // Try a removal if we have no children and we're not the root node. - if ( node != root && node.children.isEmpty() ) - { - // Delete myself from parent. - TestNode removed = last.children.remove(ZKPaths.getNodeFromPath(node.fullPath)); - assertSame(node, removed); - - // Delete from ZK - cl.delete().forPath(node.fullPath); - - // TreeCache should see the delete. - if (shouldSeeEventAt(node.fullPath)) - { - assertEvent(TreeCacheEvent.Type.NODE_REMOVED, node.fullPath); + switch (random.nextInt(3)) { + case 0: + // Try a removal if we have no children and we're not the root node. + if (node != root && node.children.isEmpty()) { + // Delete myself from parent. + TestNode removed = last.children.remove(ZKPaths.getNodeFromPath(node.fullPath)); + assertSame(node, removed); + + // Delete from ZK + cl.delete().forPath(node.fullPath); + + // TreeCache should see the delete. + if (shouldSeeEventAt(node.fullPath)) { + assertEvent(TreeCacheEvent.Type.NODE_REMOVED, node.fullPath); + } + ++removals; + } + break; + case 1: + // Do an update. + byte[] newData = new byte[10]; + random.nextBytes(newData); + + if (Arrays.equals(node.data, newData)) { + // Randomly generated the same data! Very small chance, just skip. + continue; + } + + // Update source-of-truth. + node.data = newData; + + // Update in ZK. + cl.setData().forPath(node.fullPath, node.data); + + // TreeCache should see the update. + if (shouldSeeEventAt(node.fullPath)) { + assertEvent(TreeCacheEvent.Type.NODE_UPDATED, node.fullPath, node.data); + } + + ++updates; + break; + case 2: + // Add a new child. + String name = Long.toHexString(random.nextLong()); + if (node.children.containsKey(name)) { + // Randomly generated the same name! Very small chance, just skip. + continue; } - ++removals; - } - break; - case 1: - // Do an update. - byte[] newData = new byte[10]; - random.nextBytes(newData); - - if ( Arrays.equals(node.data, newData) ) - { - // Randomly generated the same data! Very small chance, just skip. - continue; - } - - // Update source-of-truth. - node.data = newData; - - // Update in ZK. - cl.setData().forPath(node.fullPath, node.data); - - // TreeCache should see the update. - if (shouldSeeEventAt(node.fullPath)) - { - assertEvent(TreeCacheEvent.Type.NODE_UPDATED, node.fullPath, node.data); - } - - ++updates; - break; - case 2: - // Add a new child. - String name = Long.toHexString(random.nextLong()); - if ( node.children.containsKey(name) ) - { - // Randomly generated the same name! Very small chance, just skip. - continue; - } - - // Add a new child to our test tree. - byte[] data = new byte[10]; - random.nextBytes(data); - TestNode child = new TestNode(ZKPaths.makePath(node.fullPath, name), data); - node.children.put(name, child); - - // Add to ZK. - cl.create().forPath(child.fullPath, child.data); - - // TreeCache should see the add. - if (shouldSeeEventAt(child.fullPath)) - { - assertEvent(TreeCacheEvent.Type.NODE_ADDED, child.fullPath, child.data); - } - - ++adds; - break; + + // Add a new child to our test tree. + byte[] data = new byte[10]; + random.nextBytes(data); + TestNode child = new TestNode(ZKPaths.makePath(node.fullPath, name), data); + node.children.put(name, child); + + // Add to ZK. + cl.create().forPath(child.fullPath, child.data); + + // TreeCache should see the add. + if (shouldSeeEventAt(child.fullPath)) { + assertEvent(TreeCacheEvent.Type.NODE_ADDED, child.fullPath, child.data); + } + + ++adds; + break; } // Each iteration, ensure the cached state matches our source-of-truth tree. @@ -194,23 +177,22 @@ private void doTestGiantRandomDeepTree() throws Exception // Typical stats for this test: maxDepth: 10, adds: 349, removals: 198, updates: 320 // We get more adds than removals because removals only happen if we're at a leaf. - System.out.println(String.format("maxDepth: %s, adds: %s, removals: %s, updates: %s", maxDepth, adds, removals, updates)); + System.out.println( + String.format("maxDepth: %s, adds: %s, removals: %s, updates: %s", maxDepth, adds, removals, updates)); assertNoMoreEvents(); } /** * Returns true we should see an event at this path based on maxDepth, false otherwise. */ - private boolean shouldSeeEventAt(String fullPath) - { + private boolean shouldSeeEventAt(String fullPath) { return !withDepth || ZKPaths.split(fullPath).size() <= TEST_DEPTH; } /** * Recursively assert that current children equal expected children. */ - private void assertTreeEquals(TreeCache cache, TestNode expectedNode, int depth) - { + private void assertTreeEquals(TreeCache cache, TestNode expectedNode, int depth) { String path = expectedNode.fullPath; Map cacheChildren = cache.getCurrentChildren(path); assertNotNull(cacheChildren, path); @@ -221,8 +203,7 @@ private void assertTreeEquals(TreeCache cache, TestNode expectedNode, int depth) assertEquals(cacheChildren.keySet(), expectedNode.children.keySet(), path); - for ( Map.Entry entry : expectedNode.children.entrySet() ) - { + for (Map.Entry entry : expectedNode.children.entrySet()) { String nodeName = entry.getKey(); ChildData childData = cacheChildren.get(nodeName); TestNode expectedChild = entry.getValue(); @@ -234,8 +215,7 @@ private void assertTreeEquals(TreeCache cache, TestNode expectedNode, int depth) /** * Assert that the given node data matches expected test node data. */ - private static void assertNodeEquals(ChildData actualChild, TestNode expectedNode) - { + private static void assertNodeEquals(ChildData actualChild, TestNode expectedNode) { String path = expectedNode.fullPath; assertNotNull(actualChild, path); assertArrayEquals(actualChild.getData(), expectedNode.data, path); diff --git a/curator-recipes/src/test/java/org/apache/curator/framework/recipes/cache/TestWrappedNodeCache.java b/curator-recipes/src/test/java/org/apache/curator/framework/recipes/cache/TestWrappedNodeCache.java index 0e8b1a0de..aad6647c1 100644 --- a/curator-recipes/src/test/java/org/apache/curator/framework/recipes/cache/TestWrappedNodeCache.java +++ b/curator-recipes/src/test/java/org/apache/curator/framework/recipes/cache/TestWrappedNodeCache.java @@ -19,11 +19,14 @@ package org.apache.curator.framework.recipes.cache; +import static org.apache.curator.framework.recipes.cache.CuratorCacheListener.builder; import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; - +import java.util.Optional; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Semaphore; +import java.util.function.Supplier; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.imps.TestCleanState; @@ -34,23 +37,13 @@ import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; -import java.util.Optional; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.Semaphore; -import java.util.function.Supplier; - -import static org.apache.curator.framework.recipes.cache.CuratorCacheListener.builder; - @Tag(CuratorTestBase.zk36Group) -public class TestWrappedNodeCache extends CuratorTestBase -{ +public class TestWrappedNodeCache extends CuratorTestBase { @Test - public void testDeleteThenCreate() throws Exception - { + public void testDeleteThenCreate() throws Exception { CuratorCache cache = null; CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); - try - { + try { client.start(); client.create().creatingParentsIfNeeded().forPath("/test/foo", "one".getBytes()); @@ -74,34 +67,30 @@ public void testDeleteThenCreate() throws Exception assertTrue(rootData.get().isPresent()); assertArrayEquals(rootData.get().get().getData(), "two".getBytes()); - } - finally - { + } finally { CloseableUtils.closeQuietly(cache); TestCleanState.closeAndTestClean(client); } } @Test - public void testKilledSession() throws Exception - { + public void testKilledSession() throws Exception { CuratorCache cache = null; CuratorFramework client = null; - try - { - client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); + try { + client = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); client.start(); client.create().creatingParentsIfNeeded().forPath("/test/node", "start".getBytes()); CountDownLatch lostLatch = new CountDownLatch(1); client.getConnectionStateListenable().addListener((__, newState) -> { - if ( newState == ConnectionState.LOST ) - { + if (newState == ConnectionState.LOST) { lostLatch.countDown(); } }); - cache = CuratorCache.build(client,"/test/node"); + cache = CuratorCache.build(client, "/test/node"); Semaphore latch = new Semaphore(0); NodeCacheListener listener = latch::release; @@ -122,9 +111,7 @@ public void testKilledSession() throws Exception assertTrue(timing.acquireSemaphore(latch)); assertTrue(rootData.get().isPresent()); assertArrayEquals(rootData.get().get().getData(), "new data".getBytes()); - } - finally - { + } finally { CloseableUtils.closeQuietly(cache); TestCleanState.closeAndTestClean(client); } @@ -132,12 +119,11 @@ public void testKilledSession() throws Exception @SuppressWarnings("ConstantConditions") @Test - public void testBasics() throws Exception - { + public void testBasics() throws Exception { CuratorCache cache = null; - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); - try - { + CuratorFramework client = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); + try { client.start(); client.create().forPath("/test"); @@ -163,16 +149,13 @@ public void testBasics() throws Exception client.delete().forPath("/test/node"); assertTrue(timing.acquireSemaphore(semaphore)); assertNull(rootData.get().orElse(null)); - } - finally - { + } finally { CloseableUtils.closeQuietly(cache); TestCleanState.closeAndTestClean(client); } } - private Supplier> getRootDataProc(CuratorCache cache, String rootPath) - { + private Supplier> getRootDataProc(CuratorCache cache, String rootPath) { return () -> cache.get(rootPath); } } diff --git a/curator-recipes/src/test/java/org/apache/curator/framework/recipes/leader/ChaosMonkeyCnxnFactory.java b/curator-recipes/src/test/java/org/apache/curator/framework/recipes/leader/ChaosMonkeyCnxnFactory.java index 50d51a36c..e6109f87c 100644 --- a/curator-recipes/src/test/java/org/apache/curator/framework/recipes/leader/ChaosMonkeyCnxnFactory.java +++ b/curator-recipes/src/test/java/org/apache/curator/framework/recipes/leader/ChaosMonkeyCnxnFactory.java @@ -19,6 +19,8 @@ package org.apache.curator.framework.recipes.leader; +import java.io.IOException; +import java.nio.ByteBuffer; import org.apache.curator.test.Compatibility; import org.apache.curator.test.TestingZooKeeperMain; import org.apache.zookeeper.ZooDefs; @@ -30,8 +32,6 @@ import org.apache.zookeeper.server.ZooKeeperServerShutdownHandler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.io.IOException; -import java.nio.ByteBuffer; /** * A connection factory that will behave like the NIOServerCnxnFactory except that @@ -39,8 +39,7 @@ * been created in Zookeeper. * Subsequent create operations will succeed. */ -public class ChaosMonkeyCnxnFactory extends NIOServerCnxnFactory -{ +public class ChaosMonkeyCnxnFactory extends NIOServerCnxnFactory { public static final String CHAOS_ZNODE = "/mylock"; public static final String CHAOS_ZNODE_PREFIX = CHAOS_ZNODE + "/"; @@ -50,18 +49,15 @@ public class ChaosMonkeyCnxnFactory extends NIOServerCnxnFactory public static final long LOCKOUT_DURATION_MS = 6000; @Override - public void startup(ZooKeeperServer zks) throws IOException, InterruptedException - { + public void startup(ZooKeeperServer zks) throws IOException, InterruptedException { super.startup(new ChaosMonkeyZookeeperServer(zks)); } - public static class ChaosMonkeyZookeeperServer extends ZooKeeperServer - { + public static class ChaosMonkeyZookeeperServer extends ZooKeeperServer { private final ZooKeeperServer zks; private long firstError = 0; - public ChaosMonkeyZookeeperServer(ZooKeeperServer zks) - { + public ChaosMonkeyZookeeperServer(ZooKeeperServer zks) { this.zks = zks; setTxnLogFactory(zks.getTxnLogFactory()); setTickTime(zks.getTickTime()); @@ -70,22 +66,21 @@ public ChaosMonkeyZookeeperServer(ZooKeeperServer zks) } @Override - public void startup() - { + public void startup() { super.startup(); - if ( zks instanceof TestingZooKeeperMain.TestZooKeeperServer ) - { - ((TestingZooKeeperMain.TestZooKeeperServer)zks).noteStartup(); + if (zks instanceof TestingZooKeeperMain.TestZooKeeperServer) { + ((TestingZooKeeperMain.TestZooKeeperServer) zks).noteStartup(); } } @Override - public void submitRequest(Request si) - { + public void submitRequest(Request si) { long remaining = firstError != 0 ? LOCKOUT_DURATION_MS - (System.currentTimeMillis() - firstError) : 0; - if ( si.type != ZooDefs.OpCode.createSession && si.type != ZooDefs.OpCode.sync && si.type != ZooDefs.OpCode.ping - && firstError != 0 && remaining > 0 ) - { + if (si.type != ZooDefs.OpCode.createSession + && si.type != ZooDefs.OpCode.sync + && si.type != ZooDefs.OpCode.ping + && firstError != 0 + && remaining > 0) { log.debug("Rejected : " + si.toString()); // Still reject request log.debug("Still not ready for " + remaining + "ms"); @@ -96,25 +91,19 @@ public void submitRequest(Request si) log.debug("Applied : " + si.toString()); super.submitRequest(si); // Raise an error if a lock is created - if ( (si.type == ZooDefs.OpCode.create) || (si.type == ZooDefs.OpCode.create2) ) - { + if ((si.type == ZooDefs.OpCode.create) || (si.type == ZooDefs.OpCode.create2)) { CreateRequest createRequest = new CreateRequest(); - try - { + try { ByteBuffer duplicate = si.request.duplicate(); duplicate.rewind(); ByteBufferInputStream.byteBuffer2Record(duplicate, createRequest); - if ( createRequest.getPath().startsWith(CHAOS_ZNODE_PREFIX) - && firstError == 0 ) - { + if (createRequest.getPath().startsWith(CHAOS_ZNODE_PREFIX) && firstError == 0) { firstError = System.currentTimeMillis(); // The znode has been created, close the connection and don't tell it to client log.warn("Closing connection right after " + createRequest.getPath() + " creation"); Compatibility.serverCnxnClose(si.cnxn); } - } - catch ( Exception e ) - { + } catch (Exception e) { // Should not happen Compatibility.serverCnxnClose(si.cnxn); } diff --git a/curator-recipes/src/test/java/org/apache/curator/framework/recipes/leader/TestLeaderAcls.java b/curator-recipes/src/test/java/org/apache/curator/framework/recipes/leader/TestLeaderAcls.java index 3df80bcbc..9104fe958 100644 --- a/curator-recipes/src/test/java/org/apache/curator/framework/recipes/leader/TestLeaderAcls.java +++ b/curator-recipes/src/test/java/org/apache/curator/framework/recipes/leader/TestLeaderAcls.java @@ -20,7 +20,11 @@ package org.apache.curator.framework.recipes.leader; import static org.junit.jupiter.api.Assertions.assertTrue; - +import java.security.NoSuchAlgorithmException; +import java.util.Collections; +import java.util.List; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; import org.apache.curator.RetryPolicy; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; @@ -38,40 +42,25 @@ import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; -import java.security.NoSuchAlgorithmException; -import java.util.Collections; -import java.util.List; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; - -public class TestLeaderAcls extends BaseClassForTests -{ +public class TestLeaderAcls extends BaseClassForTests { private final Timing timing = new Timing(); @Test @DisplayName("Validation test for CURATOR-365") - public void testAclErrorWithLeader() throws Exception - { - ACLProvider provider = new ACLProvider() - { + public void testAclErrorWithLeader() throws Exception { + ACLProvider provider = new ACLProvider() { @Override - public List getDefaultAcl() - { + public List getDefaultAcl() { return ZooDefs.Ids.OPEN_ACL_UNSAFE; } @Override - public List getAclForPath(String path) - { - if ( path.equals("/base") ) - { - try - { + public List getAclForPath(String path) { + if (path.equals("/base")) { + try { String testDigest = DigestAuthenticationProvider.generateDigest("test:test"); return Collections.singletonList(new ACL(ZooDefs.Perms.ALL, new Id("digest", testDigest))); - } - catch ( NoSuchAlgorithmException e ) - { + } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } } @@ -81,15 +70,13 @@ public List getAclForPath(String path) RetryPolicy retryPolicy = new ExponentialBackoffRetry(timing.milliseconds(), 3); CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder() - .connectString(server.getConnectString()) - .retryPolicy(retryPolicy) - .aclProvider(provider) - .authorization("digest", "test:test".getBytes()) - ; + .connectString(server.getConnectString()) + .retryPolicy(retryPolicy) + .aclProvider(provider) + .authorization("digest", "test:test".getBytes()); CuratorFramework client = builder.build(); LeaderLatch latch = null; - try - { + try { client.start(); latch = new LeaderLatch(client, "/base"); @@ -99,18 +86,14 @@ public List getAclForPath(String path) latch = null; CuratorFramework noAuthClient = CuratorFrameworkFactory.newClient(server.getConnectString(), retryPolicy); - try - { + try { noAuthClient.start(); final CountDownLatch noAuthLatch = new CountDownLatch(1); - UnhandledErrorListener listener = new UnhandledErrorListener() - { + UnhandledErrorListener listener = new UnhandledErrorListener() { @Override - public void unhandledError(String message, Throwable e) - { - if ( e instanceof KeeperException.NoAuthException ) - { + public void unhandledError(String message, Throwable e) { + if (e instanceof KeeperException.NoAuthException) { noAuthLatch.countDown(); } } @@ -122,14 +105,10 @@ public void unhandledError(String message, Throwable e) latch = new LeaderLatch(noAuthClient, "/base/second"); latch.start(); assertTrue(timing.awaitLatch(noAuthLatch)); - } - finally - { + } finally { CloseableUtils.closeQuietly(noAuthClient); } - } - finally - { + } finally { CloseableUtils.closeQuietly(latch); CloseableUtils.closeQuietly(client); } diff --git a/curator-recipes/src/test/java/org/apache/curator/framework/recipes/leader/TestLeaderLatch.java b/curator-recipes/src/test/java/org/apache/curator/framework/recipes/leader/TestLeaderLatch.java index 0c8bdbadd..dc79f6668 100644 --- a/curator-recipes/src/test/java/org/apache/curator/framework/recipes/leader/TestLeaderLatch.java +++ b/curator-recipes/src/test/java/org/apache/curator/framework/recipes/leader/TestLeaderLatch.java @@ -32,8 +32,26 @@ import java.io.Closeable; import java.time.Duration; import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.List; import java.util.Objects; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.Callable; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorCompletionService; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; import java.util.concurrent.ForkJoinPool; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.Semaphore; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicLong; +import java.util.stream.Collectors; +import java.util.stream.IntStream; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.imps.TestCleanState; @@ -55,93 +73,66 @@ import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.List; -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.Callable; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.ExecutorCompletionService; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.LinkedBlockingQueue; -import java.util.concurrent.Semaphore; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.concurrent.atomic.AtomicLong; -import java.util.stream.Collectors; -import java.util.stream.IntStream; - @Tag(CuratorTestBase.zk35TestCompatibilityGroup) -public class TestLeaderLatch extends BaseClassForTests -{ +public class TestLeaderLatch extends BaseClassForTests { private static final String PATH_NAME = "/one/two/me"; private static final int MAX_LOOPS = 5; - private static class Holder - { + private static class Holder { final BlockingQueue stateChanges = new LinkedBlockingQueue<>(); final CountDownLatch isLockedLatch = new CountDownLatch(1); volatile LeaderLatch latch; } @Test - public void testWithCircuitBreaker() throws Exception - { + public void testWithCircuitBreaker() throws Exception { final int threadQty = 5; ExecutorService executorService = Executors.newFixedThreadPool(threadQty); List holders = Collections.emptyList(); Timing2 timing = new Timing2(); - ConnectionStateListenerManagerFactory managerFactory = ConnectionStateListenerManagerFactory.circuitBreaking(new RetryForever(timing.multiple(2).milliseconds())); + ConnectionStateListenerManagerFactory managerFactory = ConnectionStateListenerManagerFactory.circuitBreaking( + new RetryForever(timing.multiple(2).milliseconds())); CuratorFramework client = CuratorFrameworkFactory.builder() - .connectString(server.getConnectString()) - .retryPolicy(new RetryOneTime(1)) - .connectionStateListenerManagerFactory(managerFactory) - .connectionTimeoutMs(timing.connection()) - .sessionTimeoutMs(timing.session()) - .build(); + .connectString(server.getConnectString()) + .retryPolicy(new RetryOneTime(1)) + .connectionStateListenerManagerFactory(managerFactory) + .connectionTimeoutMs(timing.connection()) + .sessionTimeoutMs(timing.session()) + .build(); try { client.start(); client.create().forPath("/hey"); Semaphore lostSemaphore = new Semaphore(0); - ConnectionStateListener unProxiedListener = new ConnectionStateListener() - { + ConnectionStateListener unProxiedListener = new ConnectionStateListener() { @Override - public void stateChanged(CuratorFramework client, ConnectionState newState) - { - if ( newState == ConnectionState.LOST ) - { + public void stateChanged(CuratorFramework client, ConnectionState newState) { + if (newState == ConnectionState.LOST) { lostSemaphore.release(); } } @Override - public boolean doNotProxy() - { + public boolean doNotProxy() { return true; } }; client.getConnectionStateListenable().addListener(unProxiedListener); holders = IntStream.range(0, threadQty) - .mapToObj(index -> { - Holder holder = new Holder(); - holder.latch = new LeaderLatch(client, "/foo/bar/" + index) - { - @Override - protected void handleStateChange(ConnectionState newState) - { - holder.stateChanges.offer(newState); - super.handleStateChange(newState); - } - }; - return holder; - }) - .collect(Collectors.toList()); + .mapToObj(index -> { + Holder holder = new Holder(); + holder.latch = new LeaderLatch(client, "/foo/bar/" + index) { + @Override + protected void handleStateChange(ConnectionState newState) { + holder.stateChanges.offer(newState); + super.handleStateChange(newState); + } + }; + return holder; + }) + .collect(Collectors.toList()); holders.forEach(holder -> { executorService.submit(() -> { @@ -153,7 +144,7 @@ protected void handleStateChange(ConnectionState newState) timing.awaitLatch(holder.isLockedLatch); }); - for ( int i = 0; i < 4; ++i ) // note: 4 is just a random number of loops to simulate disconnections + for (int i = 0; i < 4; ++i) // note: 4 is just a random number of loops to simulate disconnections { server.stop(); assertTrue(timing.acquireSemaphore(lostSemaphore)); @@ -161,16 +152,13 @@ protected void handleStateChange(ConnectionState newState) timing.sleepABit(); } - for ( Holder holder : holders ) - { + for (Holder holder : holders) { assertTrue(holder.latch.await(timing.forWaiting().milliseconds(), TimeUnit.MILLISECONDS)); assertEquals(timing.takeFromQueue(holder.stateChanges), ConnectionState.SUSPENDED); assertEquals(timing.takeFromQueue(holder.stateChanges), ConnectionState.LOST); assertEquals(timing.takeFromQueue(holder.stateChanges), ConnectionState.RECONNECTED); } - } - finally - { + } finally { holders.forEach(holder -> CloseableUtils.closeQuietly(holder.latch)); CloseableUtils.closeQuietly(client); executorService.shutdownNow(); @@ -178,27 +166,24 @@ protected void handleStateChange(ConnectionState newState) } @Test - public void testUncreatedPathGetLeader() throws Exception - { - try ( CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)) ) - { + public void testUncreatedPathGetLeader() throws Exception { + try (CuratorFramework client = + CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1))) { client.start(); LeaderLatch latch = new LeaderLatch(client, "/foo/bar"); - latch.getLeader(); // CURATOR-436 - was throwing NoNodeException + latch.getLeader(); // CURATOR-436 - was throwing NoNodeException } } @Test - public void testWatchedNodeDeletedOnReconnect() throws Exception - { + public void testWatchedNodeDeletedOnReconnect() throws Exception { final String latchPath = "/foo/bar"; Timing2 timing = new Timing2(); - try ( CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)) ) - { + try (CuratorFramework client = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1))) { client.start(); LeaderLatch latch1 = new LeaderLatch(client, latchPath, "1"); - try ( LeaderLatch latch2 = new LeaderLatch(client, latchPath, "2") ) - { + try (LeaderLatch latch2 = new LeaderLatch(client, latchPath, "2")) { latch1.start(); assertTrue(latch1.await(timing.milliseconds(), TimeUnit.MILLISECONDS)); @@ -206,42 +191,43 @@ public void testWatchedNodeDeletedOnReconnect() throws Exception timing.sleepABit(); latch2.debugCheckLeaderShipLatch = new CountDownLatch(1); - latch1.close(); // simulate the leader's path getting deleted + latch1.close(); // simulate the leader's path getting deleted latch1 = null; - timing.sleepABit(); // after this, latch2 should be blocked just before getting the path in checkLeadership() + timing.sleepABit(); // after this, latch2 should be blocked just before getting the path in + // checkLeadership() latch2.reset(); // force the internal "ourPath" to get reset - latch2.debugCheckLeaderShipLatch.countDown(); // allow checkLeadership() to continue + latch2.debugCheckLeaderShipLatch.countDown(); // allow checkLeadership() to continue assertTrue(latch2.await(timing.forSessionSleep().forWaiting().milliseconds(), TimeUnit.MILLISECONDS)); timing.sleepABit(); assertEquals(client.getChildren().forPath(latchPath).size(), 1); - } - finally - { + } finally { CloseableUtils.closeQuietly(latch1); } } } @Test - public void testResettingOfLeadershipAfterConcurrentLeadershipChange() throws Exception - { + public void testResettingOfLeadershipAfterConcurrentLeadershipChange() throws Exception { final String latchPath = "/test"; final Timing2 timing = new Timing2(); final BlockingQueue events = Queues.newLinkedBlockingQueue(); final List closeableResources = new ArrayList<>(); - try - { + try { final String id0 = "id0"; final CuratorFramework client0 = createAndStartClient(server.getConnectString(), timing, id0, events); closeableResources.add(client0); final LeaderLatch latch0 = createAndStartLeaderLatch(client0, latchPath, id0, events); closeableResources.add(latch0); - assertEquals(new TestEvent(id0, TestEventType.GAINED_CONNECTION), events.poll(timing.forWaiting().milliseconds(), TimeUnit.MILLISECONDS)); - assertEquals(new TestEvent(id0, TestEventType.GAINED_LEADERSHIP), events.poll(timing.forWaiting().milliseconds(), TimeUnit.MILLISECONDS)); + assertEquals( + new TestEvent(id0, TestEventType.GAINED_CONNECTION), + events.poll(timing.forWaiting().milliseconds(), TimeUnit.MILLISECONDS)); + assertEquals( + new TestEvent(id0, TestEventType.GAINED_LEADERSHIP), + events.poll(timing.forWaiting().milliseconds(), TimeUnit.MILLISECONDS)); final String id1 = "id1"; final CuratorFramework client1 = createAndStartClient(server.getConnectString(), timing, id1, events); @@ -249,10 +235,13 @@ public void testResettingOfLeadershipAfterConcurrentLeadershipChange() throws Ex final LeaderLatch latch1 = createAndStartLeaderLatch(client1, latchPath, id1, events); closeableResources.add(latch1); - assertEquals(new TestEvent(id1, TestEventType.GAINED_CONNECTION), events.poll(timing.forWaiting().milliseconds(), TimeUnit.MILLISECONDS)); + assertEquals( + new TestEvent(id1, TestEventType.GAINED_CONNECTION), + events.poll(timing.forWaiting().milliseconds(), TimeUnit.MILLISECONDS)); // wait for the non-leading LeaderLatch (i.e. latch1) instance to be done with its creation - // this call is time-consuming but necessary because we don't have a handle to detect the end of the reset call + // this call is time-consuming but necessary because we don't have a handle to detect the end of the reset + // call timing.forWaiting().sleepABit(); assertTrue(latch0.hasLeadership()); @@ -264,59 +253,69 @@ public void testResettingOfLeadershipAfterConcurrentLeadershipChange() throws Ex // force latch0 and latch1 reset to trigger the actual test latch0.reset(); - // latch1 needs to be called within a separate thread since it's going to be blocked by the CountDownLatch outside an async call + // latch1 needs to be called within a separate thread since it's going to be blocked by the CountDownLatch + // outside an async call ForkJoinPool.commonPool().submit(() -> { latch1.reset(); return null; }); - // latch0.reset() will result in it losing its leadership, deleting its old child node and creating a new child node before being blocked by its debugResetWaitLatch - assertEquals(new TestEvent(id0, TestEventType.LOST_LEADERSHIP), events.poll(timing.forWaiting().milliseconds(), TimeUnit.MILLISECONDS)); - // latch1.reset() is blocked but latch1 will gain leadership due its node watching latch0's node to be deleted - assertEquals(new TestEvent(id1, TestEventType.GAINED_LEADERSHIP), events.poll(timing.forWaiting().milliseconds(), TimeUnit.MILLISECONDS)); + // latch0.reset() will result in it losing its leadership, deleting its old child node and creating a new + // child node before being blocked by its debugResetWaitLatch + assertEquals( + new TestEvent(id0, TestEventType.LOST_LEADERSHIP), + events.poll(timing.forWaiting().milliseconds(), TimeUnit.MILLISECONDS)); + // latch1.reset() is blocked but latch1 will gain leadership due its node watching latch0's node to be + // deleted + assertEquals( + new TestEvent(id1, TestEventType.GAINED_LEADERSHIP), + events.poll(timing.forWaiting().milliseconds(), TimeUnit.MILLISECONDS)); assertFalse(latch0.hasLeadership()); assertTrue(latch1.hasLeadership()); - // latch0.reset() continues with the getChildren call, finds itself not being the leader and starts listening to the node created by latch1 + // latch0.reset() continues with the getChildren call, finds itself not being the leader and starts + // listening to the node created by latch1 latch0.debugResetWaitLatch.countDown(); timing.sleepABit(); - // latch1.reset() continues, deletes its old child node and creates a new child node before being blocked by its debugResetWaitLatch + // latch1.reset() continues, deletes its old child node and creates a new child node before being blocked by + // its debugResetWaitLatch latch1.debugResetWaitBeforeNodeDeleteLatch.countDown(); // latch0 receives NodeDeleteEvent and then finds itself to be the leader - assertEquals(new TestEvent(id0, TestEventType.GAINED_LEADERSHIP), events.poll(timing.forWaiting().milliseconds(), TimeUnit.MILLISECONDS)); + assertEquals( + new TestEvent(id0, TestEventType.GAINED_LEADERSHIP), + events.poll(timing.forWaiting().milliseconds(), TimeUnit.MILLISECONDS)); assertTrue(latch0.hasLeadership()); // latch1.reset() continues and finds itself not being the leader latch1.debugResetWaitLatch.countDown(); - // this call is time-consuming but necessary because we don't have a handle to detect the end of the reset call + // this call is time-consuming but necessary because we don't have a handle to detect the end of the reset + // call timing.forWaiting().sleepABit(); assertTrue(latch0.hasLeadership()); assertFalse(latch1.hasLeadership()); - } - finally - { + } finally { // reverse is necessary for closing the LeaderLatch instances before closing the corresponding client Collections.reverse(closeableResources); closeableResources.forEach(CloseableUtils::closeQuietly); } } - private static CuratorFramework createAndStartClient(String zkConnectString, Timing2 timing, String id, Collection events) { + private static CuratorFramework createAndStartClient( + String zkConnectString, Timing2 timing, String id, Collection events) { final CuratorFramework client = CuratorFrameworkFactory.builder() - .connectString(zkConnectString) - .connectionTimeoutMs(timing.connection()) - .sessionTimeoutMs(timing.session()) - .retryPolicy(new RetryOneTime(1)) - .connectionStateErrorPolicy(new StandardConnectionStateErrorPolicy()) - .build(); + .connectString(zkConnectString) + .connectionTimeoutMs(timing.connection()) + .sessionTimeoutMs(timing.session()) + .retryPolicy(new RetryOneTime(1)) + .connectionStateErrorPolicy(new StandardConnectionStateErrorPolicy()) + .build(); client.getConnectionStateListenable().addListener((client1, newState) -> { - if ( newState == ConnectionState.CONNECTED ) - { + if (newState == ConnectionState.CONNECTED) { events.add(new TestEvent(id, TestEventType.GAINED_CONNECTION)); } }); @@ -326,8 +325,8 @@ private static CuratorFramework createAndStartClient(String zkConnectString, Tim return client; } - private static LeaderLatch createAndStartLeaderLatch(CuratorFramework client, String latchPath, String id, Collection events) throws Exception - { + private static LeaderLatch createAndStartLeaderLatch( + CuratorFramework client, String latchPath, String id, Collection events) throws Exception { final LeaderLatch latch = new LeaderLatch(client, latchPath, id); latch.addListener(new LeaderLatchListener() { @Override @@ -345,8 +344,7 @@ public void notLeader() { return latch; } - private enum TestEventType - { + private enum TestEventType { GAINED_LEADERSHIP, LOST_LEADERSHIP, GAINED_CONNECTION; @@ -356,8 +354,7 @@ private static class TestEvent { private final String id; private final TestEventType eventType; - public TestEvent(String id, TestEventType eventType) - { + public TestEvent(String id, TestEventType eventType) { this.id = id; this.eventType = eventType; } @@ -372,41 +369,45 @@ public boolean equals(Object o) { } @Test - public void testLeadershipElectionWhenNodeDisappearsAfterChildrenAreRetrieved() throws Exception - { + public void testLeadershipElectionWhenNodeDisappearsAfterChildrenAreRetrieved() throws Exception { final String latchPath = "/foo/bar"; final Timing2 timing = new Timing2(); final Duration pollInterval = Duration.ofMillis(100); - try (CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1))) - { + try (CuratorFramework client = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1))) { client.start(); LeaderLatch latchInitialLeader = new LeaderLatch(client, latchPath, "initial-leader"); LeaderLatch latchCandidate0 = new LeaderLatch(client, latchPath, "candidate-0"); LeaderLatch latchCandidate1 = new LeaderLatch(client, latchPath, "candidate-1"); - try - { + try { latchInitialLeader.start(); - // we want to make sure that the leader gets leadership before other instances are going to join the party + // we want to make sure that the leader gets leadership before other instances are going to join the + // party waitForALeader(Collections.singletonList(latchInitialLeader), new Timing()); - // candidate #0 will wait for the leader to go away - this should happen after the child nodes are retrieved by candidate #0 + // candidate #0 will wait for the leader to go away - this should happen after the child nodes are + // retrieved by candidate #0 latchCandidate0.debugCheckLeaderShipLatch = new CountDownLatch(1); latchCandidate0.start(); final int expectedChildrenAfterCandidate0Joins = 2; - Awaitility.await("There should be " + expectedChildrenAfterCandidate0Joins + " child nodes created after candidate #0 joins the leader election.") + Awaitility.await("There should be " + expectedChildrenAfterCandidate0Joins + + " child nodes created after candidate #0 joins the leader election.") .pollInterval(pollInterval) .pollInSameThread() - .until(() -> client.getChildren().forPath(latchPath).size() == expectedChildrenAfterCandidate0Joins); + .until(() -> + client.getChildren().forPath(latchPath).size() == expectedChildrenAfterCandidate0Joins); // no extra CountDownLatch needs to be set here because candidate #1 will rely on candidate #0 latchCandidate1.start(); final int expectedChildrenAfterCandidate1Joins = 3; - Awaitility.await("There should be " + expectedChildrenAfterCandidate1Joins + " child nodes created after candidate #1 joins the leader election.") + Awaitility.await("There should be " + expectedChildrenAfterCandidate1Joins + + " child nodes created after candidate #1 joins the leader election.") .pollInterval(pollInterval) .pollInSameThread() - .until(() -> client.getChildren().forPath(latchPath).size() == expectedChildrenAfterCandidate1Joins); + .until(() -> + client.getChildren().forPath(latchPath).size() == expectedChildrenAfterCandidate1Joins); // triggers the removal of the corresponding child node after candidate #0 retrieved the children latchInitialLeader.close(); @@ -416,11 +417,8 @@ public void testLeadershipElectionWhenNodeDisappearsAfterChildrenAreRetrieved() waitForALeader(Arrays.asList(latchCandidate0, latchCandidate1), new Timing()); assertTrue(latchCandidate0.hasLeadership() ^ latchCandidate1.hasLeadership()); - } - finally - { - for (LeaderLatch latchToClose : Arrays.asList(latchInitialLeader, latchCandidate0, latchCandidate1)) - { + } finally { + for (LeaderLatch latchToClose : Arrays.asList(latchInitialLeader, latchCandidate0, latchCandidate1)) { latchToClose.closeOnDemand(); } } @@ -428,29 +426,27 @@ public void testLeadershipElectionWhenNodeDisappearsAfterChildrenAreRetrieved() } @Test - public void testSessionErrorPolicy() throws Exception - { + public void testSessionErrorPolicy() throws Exception { Timing timing = new Timing(); LeaderLatch latch = null; CuratorFramework client = null; - for ( int i = 0; i < 2; ++i ) - { + for (int i = 0; i < 2; ++i) { boolean isSessionIteration = (i == 0); - try - { + try { client = CuratorFrameworkFactory.builder() - .connectString(server.getConnectString()) - .connectionTimeoutMs(10000) - .sessionTimeoutMs(60000) - .retryPolicy(new RetryOneTime(1)) - .connectionStateErrorPolicy(isSessionIteration ? new SessionConnectionStateErrorPolicy() : new StandardConnectionStateErrorPolicy()) - .build(); + .connectString(server.getConnectString()) + .connectionTimeoutMs(10000) + .sessionTimeoutMs(60000) + .retryPolicy(new RetryOneTime(1)) + .connectionStateErrorPolicy( + isSessionIteration + ? new SessionConnectionStateErrorPolicy() + : new StandardConnectionStateErrorPolicy()) + .build(); final BlockingQueue states = Queues.newLinkedBlockingQueue(); - ConnectionStateListener stateListener = new ConnectionStateListener() - { + ConnectionStateListener stateListener = new ConnectionStateListener() { @Override - public void stateChanged(CuratorFramework client, ConnectionState newState) - { + public void stateChanged(CuratorFramework client, ConnectionState newState) { states.add(newState.name()); } }; @@ -459,48 +455,50 @@ public void stateChanged(CuratorFramework client, ConnectionState newState) final String latchPatch = "/test"; latch = new LeaderLatch(client, latchPatch); - LeaderLatchListener listener = new LeaderLatchListener() - { + LeaderLatchListener listener = new LeaderLatchListener() { @Override - public void isLeader() - { + public void isLeader() { states.add("true"); } @Override - public void notLeader() - { + public void notLeader() { states.add("false"); } }; latch.addListener(listener); latch.start(); - assertEquals(states.poll(timing.forWaiting().milliseconds(), TimeUnit.MILLISECONDS), ConnectionState.CONNECTED.name()); + assertEquals( + states.poll(timing.forWaiting().milliseconds(), TimeUnit.MILLISECONDS), + ConnectionState.CONNECTED.name()); assertEquals(states.poll(timing.forWaiting().milliseconds(), TimeUnit.MILLISECONDS), "true"); final List beforeResetChildren = client.getChildren().forPath(latchPatch); server.stop(); - if ( isSessionIteration ) - { - assertEquals(states.poll(timing.forWaiting().milliseconds(), TimeUnit.MILLISECONDS), ConnectionState.SUSPENDED.name()); + if (isSessionIteration) { + assertEquals( + states.poll(timing.forWaiting().milliseconds(), TimeUnit.MILLISECONDS), + ConnectionState.SUSPENDED.name()); server.restart(); - assertEquals(states.poll(timing.forWaiting().milliseconds(), TimeUnit.MILLISECONDS), ConnectionState.RECONNECTED.name()); + assertEquals( + states.poll(timing.forWaiting().milliseconds(), TimeUnit.MILLISECONDS), + ConnectionState.RECONNECTED.name()); assertNull(states.poll(timing.milliseconds(), TimeUnit.MILLISECONDS)); - } - else - { + } else { String s = states.poll(timing.forWaiting().milliseconds(), TimeUnit.MILLISECONDS); - assertTrue("false".equals(s) || ConnectionState.SUSPENDED.name().equals(s)); + assertTrue("false".equals(s) + || ConnectionState.SUSPENDED.name().equals(s)); s = states.poll(timing.forWaiting().milliseconds(), TimeUnit.MILLISECONDS); - assertTrue("false".equals(s) || ConnectionState.SUSPENDED.name().equals(s)); + assertTrue("false".equals(s) + || ConnectionState.SUSPENDED.name().equals(s)); server.restart(); - assertEquals(states.poll(timing.forWaiting().milliseconds(), TimeUnit.MILLISECONDS), ConnectionState.RECONNECTED.name()); + assertEquals( + states.poll(timing.forWaiting().milliseconds(), TimeUnit.MILLISECONDS), + ConnectionState.RECONNECTED.name()); assertEquals(states.poll(timing.forWaiting().milliseconds(), TimeUnit.MILLISECONDS), "true"); final List afterResetChildren = client.getChildren().forPath(latchPatch); assertEquals(beforeResetChildren, afterResetChildren); } - } - finally - { + } finally { CloseableUtils.closeQuietly(latch); CloseableUtils.closeQuietly(client); } @@ -508,55 +506,55 @@ public void notLeader() } @Test - public void testErrorPolicies() throws Exception - { + public void testErrorPolicies() throws Exception { Timing2 timing = new Timing2(); LeaderLatch latch = null; CuratorFramework client = CuratorFrameworkFactory.builder() - .connectString(server.getConnectString()) - .connectionTimeoutMs(1000) - .sessionTimeoutMs(timing.session()) - .retryPolicy(new RetryOneTime(1)) - .connectionStateErrorPolicy(new StandardConnectionStateErrorPolicy()) - .build(); - try - { + .connectString(server.getConnectString()) + .connectionTimeoutMs(1000) + .sessionTimeoutMs(timing.session()) + .retryPolicy(new RetryOneTime(1)) + .connectionStateErrorPolicy(new StandardConnectionStateErrorPolicy()) + .build(); + try { final BlockingQueue states = Queues.newLinkedBlockingQueue(); - ConnectionStateListener stateListener = new ConnectionStateListener() - { + ConnectionStateListener stateListener = new ConnectionStateListener() { @Override - public void stateChanged(CuratorFramework client, ConnectionState newState) - { + public void stateChanged(CuratorFramework client, ConnectionState newState) { states.add(newState.name()); } }; client.getConnectionStateListenable().addListener(stateListener); client.start(); latch = new LeaderLatch(client, "/test"); - LeaderLatchListener listener = new LeaderLatchListener() - { + LeaderLatchListener listener = new LeaderLatchListener() { @Override - public void isLeader() - { + public void isLeader() { states.add("true"); } @Override - public void notLeader() - { + public void notLeader() { states.add("false"); } }; latch.addListener(listener); latch.start(); - assertEquals(states.poll(timing.forWaiting().milliseconds(), TimeUnit.MILLISECONDS), ConnectionState.CONNECTED.name()); + assertEquals( + states.poll(timing.forWaiting().milliseconds(), TimeUnit.MILLISECONDS), + ConnectionState.CONNECTED.name()); assertEquals(states.poll(timing.forWaiting().milliseconds(), TimeUnit.MILLISECONDS), "true"); server.close(); List next = Lists.newArrayList(); next.add(states.poll(timing.forWaiting().milliseconds(), TimeUnit.MILLISECONDS)); next.add(states.poll(timing.forWaiting().milliseconds(), TimeUnit.MILLISECONDS)); - assertTrue(next.equals(Arrays.asList(ConnectionState.SUSPENDED.name(), "false")) || next.equals(Arrays.asList("false", ConnectionState.SUSPENDED.name())), next.toString()); - assertEquals(states.poll(timing.forSessionSleep().milliseconds(), TimeUnit.MILLISECONDS), ConnectionState.LOST.name()); + assertTrue( + next.equals(Arrays.asList(ConnectionState.SUSPENDED.name(), "false")) + || next.equals(Arrays.asList("false", ConnectionState.SUSPENDED.name())), + next.toString()); + assertEquals( + states.poll(timing.forSessionSleep().milliseconds(), TimeUnit.MILLISECONDS), + ConnectionState.LOST.name()); latch.close(); client.close(); @@ -565,61 +563,61 @@ public void notLeader() server = new TestingServer(); client = CuratorFrameworkFactory.builder() - .connectString(server.getConnectString()) - .connectionTimeoutMs(1000) - .sessionTimeoutMs(timing.session()) - .retryPolicy(new RetryOneTime(1)) - .connectionStateErrorPolicy(new SessionConnectionStateErrorPolicy()) - .build(); + .connectString(server.getConnectString()) + .connectionTimeoutMs(1000) + .sessionTimeoutMs(timing.session()) + .retryPolicy(new RetryOneTime(1)) + .connectionStateErrorPolicy(new SessionConnectionStateErrorPolicy()) + .build(); client.getConnectionStateListenable().addListener(stateListener); client.start(); latch = new LeaderLatch(client, "/test"); latch.addListener(listener); latch.start(); - assertEquals(states.poll(timing.forWaiting().milliseconds(), TimeUnit.MILLISECONDS), ConnectionState.CONNECTED.name()); + assertEquals( + states.poll(timing.forWaiting().milliseconds(), TimeUnit.MILLISECONDS), + ConnectionState.CONNECTED.name()); assertEquals(states.poll(timing.forWaiting().milliseconds(), TimeUnit.MILLISECONDS), "true"); server.close(); - assertEquals(states.poll(timing.forWaiting().milliseconds(), TimeUnit.MILLISECONDS), ConnectionState.SUSPENDED.name()); + assertEquals( + states.poll(timing.forWaiting().milliseconds(), TimeUnit.MILLISECONDS), + ConnectionState.SUSPENDED.name()); next = Lists.newArrayList(); next.add(states.poll(timing.forSessionSleep().milliseconds(), TimeUnit.MILLISECONDS)); next.add(states.poll(timing.forSessionSleep().milliseconds(), TimeUnit.MILLISECONDS)); - assertTrue(next.equals(Arrays.asList(ConnectionState.LOST.name(), "false")) || next.equals(Arrays.asList("false", ConnectionState.LOST.name())), next.toString()); - } - finally - { + assertTrue( + next.equals(Arrays.asList(ConnectionState.LOST.name(), "false")) + || next.equals(Arrays.asList("false", ConnectionState.LOST.name())), + next.toString()); + } finally { CloseableUtils.closeQuietly(latch); CloseableUtils.closeQuietly(client); } } @Test - public void testProperCloseWithoutConnectionEstablished() throws Exception - { + public void testProperCloseWithoutConnectionEstablished() throws Exception { server.stop(); Timing timing = new Timing(); LeaderLatch latch = null; - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); - try - { + CuratorFramework client = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); + try { client.start(); final AtomicBoolean resetCalled = new AtomicBoolean(false); final CountDownLatch cancelStartTaskLatch = new CountDownLatch(1); - latch = new LeaderLatch(client, PATH_NAME) - { + latch = new LeaderLatch(client, PATH_NAME) { @Override - void reset() throws Exception - { + void reset() throws Exception { resetCalled.set(true); super.reset(); } @Override - protected boolean cancelStartTask() - { - if ( super.cancelStartTask() ) - { + protected boolean cancelStartTask() { + if (super.cancelStartTask()) { cancelStartTaskLatch.countDown(); return true; } @@ -633,28 +631,25 @@ protected boolean cancelStartTask() assertTrue(timing.awaitLatch(cancelStartTaskLatch)); assertFalse(resetCalled.get()); - } - finally - { + } finally { CloseableUtils.closeQuietly(latch); TestCleanState.closeAndTestClean(client); } } @Test - public void testResetRace() throws Exception - { + public void testResetRace() throws Exception { Timing timing = new Timing(); LeaderLatch latch = null; - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); - try - { + CuratorFramework client = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); + try { client.start(); latch = new LeaderLatch(client, PATH_NAME); latch.debugResetWaitLatch = new CountDownLatch(1); - latch.start(); // will call reset() - latch.reset(); // should not result in two nodes + latch.start(); // will call reset() + latch.reset(); // should not result in two nodes timing.sleepABit(); @@ -663,21 +658,18 @@ public void testResetRace() throws Exception timing.sleepABit(); assertEquals(client.getChildren().forPath(PATH_NAME).size(), 1); - } - finally - { + } finally { CloseableUtils.closeQuietly(latch); TestCleanState.closeAndTestClean(client); } } @Test - public void testCreateDeleteRace() throws Exception - { + public void testCreateDeleteRace() throws Exception { Timing timing = new Timing(); - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); - try - { + CuratorFramework client = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); + try { client.start(); client.create().creatingParentsIfNeeded().forPath(PATH_NAME); @@ -696,41 +688,34 @@ public void testCreateDeleteRace() throws Exception assertEquals(client.getChildren().forPath(PATH_NAME).size(), 0); - } - finally - { + } finally { TestCleanState.closeAndTestClean(client); } } @Test - public void testLostConnection() throws Exception - { + public void testLostConnection() throws Exception { final int PARTICIPANT_QTY = 10; List latches = Lists.newArrayList(); final Timing timing = new Timing(); - final CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); - try - { + final CuratorFramework client = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); + try { client.start(); final CountDownLatch countDownLatch = new CountDownLatch(1); - client.getConnectionStateListenable().addListener(new ConnectionStateListener() - { + client.getConnectionStateListenable().addListener(new ConnectionStateListener() { @Override - public void stateChanged(CuratorFramework client, ConnectionState newState) - { - if ( newState == ConnectionState.LOST ) - { + public void stateChanged(CuratorFramework client, ConnectionState newState) { + if (newState == ConnectionState.LOST) { countDownLatch.countDown(); } } }); - for ( int i = 0; i < PARTICIPANT_QTY; ++i ) - { + for (int i = 0; i < PARTICIPANT_QTY; ++i) { LeaderLatch latch = new LeaderLatch(client, PATH_NAME); latch.start(); latches.add(latch); @@ -747,11 +732,8 @@ public void stateChanged(CuratorFramework client, ConnectionState newState) server.restart(); assertEquals(waitForALeader(latches, timing).size(), 1); // should reconnect - } - finally - { - for ( LeaderLatch latch : latches ) - { + } finally { + for (LeaderLatch latch : latches) { CloseableUtils.closeQuietly(latch); } TestCleanState.closeAndTestClean(client); @@ -759,41 +741,36 @@ public void stateChanged(CuratorFramework client, ConnectionState newState) } @Test - public void testCorrectWatching() throws Exception - { + public void testCorrectWatching() throws Exception { final int PARTICIPANT_QTY = 10; final int PARTICIPANT_ID = 2; List latches = Lists.newArrayList(); final Timing timing = new Timing(); - final CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); - try - { + final CuratorFramework client = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); + try { client.start(); - for ( int i = 0; i < PARTICIPANT_QTY; ++i ) - { + for (int i = 0; i < PARTICIPANT_QTY; ++i) { LeaderLatch latch = new LeaderLatch(client, PATH_NAME); latch.start(); latches.add(latch); waitForALeader(latches, timing); } - //we need to close a Participant that doesn't be actual leader (first Participant) nor the last + // we need to close a Participant that doesn't be actual leader (first Participant) nor the last latches.get(PARTICIPANT_ID).close(); - //As the previous algorithm assumed that if the watched node is deleted gets the leadership - //we need to ensure that the PARTICIPANT_ID-1 is not getting (wrongly) elected as leader. + // As the previous algorithm assumed that if the watched node is deleted gets the leadership + // we need to ensure that the PARTICIPANT_ID-1 is not getting (wrongly) elected as leader. assertTrue(!latches.get(PARTICIPANT_ID - 1).hasLeadership()); - } - finally - { - //removes the already closed participant + } finally { + // removes the already closed participant latches.remove(PARTICIPANT_ID); - for ( LeaderLatch latch : latches ) - { + for (LeaderLatch latch : latches) { CloseableUtils.closeQuietly(latch); } TestCleanState.closeAndTestClean(client); @@ -801,49 +778,40 @@ public void testCorrectWatching() throws Exception } @Test - public void testWaiting() throws Exception - { + public void testWaiting() throws Exception { final int LOOPS = 10; - for ( int i = 0; i < LOOPS; ++i ) - { + for (int i = 0; i < LOOPS; ++i) { System.out.println("TRY #" + i); internalTestWaitingOnce(); Thread.sleep(10); } } - private void internalTestWaitingOnce() throws Exception - { + private void internalTestWaitingOnce() throws Exception { final int PARTICIPANT_QTY = 10; ExecutorService executorService = Executors.newFixedThreadPool(PARTICIPANT_QTY); ExecutorCompletionService service = new ExecutorCompletionService(executorService); final Timing timing = new Timing(); - final CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); - try - { + final CuratorFramework client = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); + try { client.start(); final AtomicBoolean thereIsALeader = new AtomicBoolean(false); - for ( int i = 0; i < PARTICIPANT_QTY; ++i ) - { - service.submit(new Callable() - { + for (int i = 0; i < PARTICIPANT_QTY; ++i) { + service.submit(new Callable() { @Override - public Void call() throws Exception - { + public Void call() throws Exception { LeaderLatch latch = new LeaderLatch(client, PATH_NAME); - try - { + try { latch.start(); assertTrue(latch.await(timing.forWaiting().seconds(), TimeUnit.SECONDS)); assertTrue(thereIsALeader.compareAndSet(false, true)); - Thread.sleep((int)(10 * Math.random())); + Thread.sleep((int) (10 * Math.random())); thereIsALeader.set(false); - } - finally - { + } finally { latch.close(); } return null; @@ -851,89 +819,77 @@ public Void call() throws Exception }); } - for ( int i = 0; i < PARTICIPANT_QTY; ++i ) - { + for (int i = 0; i < PARTICIPANT_QTY; ++i) { service.take().get(); } - } - finally - { + } finally { executorService.shutdownNow(); TestCleanState.closeAndTestClean(client); } } @Test - public void testBasic() throws Exception - { + public void testBasic() throws Exception { basic(Mode.START_IMMEDIATELY); } @Test - public void testBasicAlt() throws Exception - { + public void testBasicAlt() throws Exception { basic(Mode.START_IN_THREADS); } @Test - public void testCallbackSanity() throws Exception - { + public void testCallbackSanity() throws Exception { final int PARTICIPANT_QTY = 10; final CountDownLatch timesSquare = new CountDownLatch(PARTICIPANT_QTY); final AtomicLong masterCounter = new AtomicLong(0); final AtomicLong notLeaderCounter = new AtomicLong(0); Timing timing = new Timing(); - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); - ExecutorService exec = Executors.newSingleThreadExecutor(new ThreadFactoryBuilder().setDaemon(true).setNameFormat("callbackSanity-%s").build()); + CuratorFramework client = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); + ExecutorService exec = Executors.newSingleThreadExecutor(new ThreadFactoryBuilder() + .setDaemon(true) + .setNameFormat("callbackSanity-%s") + .build()); List latches = Lists.newArrayList(); - for ( int i = 0; i < PARTICIPANT_QTY; ++i ) - { + for (int i = 0; i < PARTICIPANT_QTY; ++i) { final LeaderLatch latch = new LeaderLatch(client, PATH_NAME); - latch.addListener(new LeaderLatchListener() - { - boolean beenLeader = false; + latch.addListener( + new LeaderLatchListener() { + boolean beenLeader = false; - @Override - public void isLeader() - { - if ( !beenLeader ) - { - masterCounter.incrementAndGet(); - beenLeader = true; - try - { - latch.reset(); - } - catch ( Exception e ) - { - throw Throwables.propagate(e); + @Override + public void isLeader() { + if (!beenLeader) { + masterCounter.incrementAndGet(); + beenLeader = true; + try { + latch.reset(); + } catch (Exception e) { + throw Throwables.propagate(e); + } + } else { + masterCounter.incrementAndGet(); + CloseableUtils.closeQuietly(latch); + timesSquare.countDown(); + } } - } - else - { - masterCounter.incrementAndGet(); - CloseableUtils.closeQuietly(latch); - timesSquare.countDown(); - } - } - @Override - public void notLeader() - { - notLeaderCounter.incrementAndGet(); - } - }, exec); + @Override + public void notLeader() { + notLeaderCounter.incrementAndGet(); + } + }, + exec); latches.add(latch); } - try - { + try { client.start(); - for ( LeaderLatch latch : latches ) - { + for (LeaderLatch latch : latches) { latch.start(); } @@ -941,17 +897,12 @@ public void notLeader() assertEquals(masterCounter.get(), PARTICIPANT_QTY * 2); assertEquals(notLeaderCounter.get(), PARTICIPANT_QTY); - for ( LeaderLatch latch : latches ) - { + for (LeaderLatch latch : latches) { assertEquals(latch.getState(), LeaderLatch.State.CLOSED); } - } - finally - { - for ( LeaderLatch latch : latches ) - { - if ( latch.getState() != LeaderLatch.State.CLOSED ) - { + } finally { + for (LeaderLatch latch : latches) { + if (latch.getState() != LeaderLatch.State.CLOSED) { CloseableUtils.closeQuietly(latch); } } @@ -960,8 +911,7 @@ public void notLeader() } @Test - public void testCallbackNotifyLeader() throws Exception - { + public void testCallbackNotifyLeader() throws Exception { final int PARTICIPANT_QTY = 10; final int SILENT_QTY = 3; @@ -970,58 +920,53 @@ public void testCallbackNotifyLeader() throws Exception final AtomicLong notLeaderCounter = new AtomicLong(0); Timing timing = new Timing(); - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); - ExecutorService exec = Executors.newSingleThreadExecutor(new ThreadFactoryBuilder().setDaemon(true).setNameFormat("callbackNotifyLeader-%s").build()); + CuratorFramework client = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); + ExecutorService exec = Executors.newSingleThreadExecutor(new ThreadFactoryBuilder() + .setDaemon(true) + .setNameFormat("callbackNotifyLeader-%s") + .build()); List latches = Lists.newArrayList(); - for ( int i = 0; i < PARTICIPANT_QTY; ++i ) - { - LeaderLatch.CloseMode closeMode = i < SILENT_QTY ? LeaderLatch.CloseMode.SILENT : LeaderLatch.CloseMode.NOTIFY_LEADER; + for (int i = 0; i < PARTICIPANT_QTY; ++i) { + LeaderLatch.CloseMode closeMode = + i < SILENT_QTY ? LeaderLatch.CloseMode.SILENT : LeaderLatch.CloseMode.NOTIFY_LEADER; final LeaderLatch latch = new LeaderLatch(client, PATH_NAME, "", closeMode); - latch.addListener(new LeaderLatchListener() - { - boolean beenLeader = false; + latch.addListener( + new LeaderLatchListener() { + boolean beenLeader = false; - @Override - public void isLeader() - { - if ( !beenLeader ) - { - masterCounter.incrementAndGet(); - beenLeader = true; - try - { - latch.reset(); - } - catch ( Exception e ) - { - throw Throwables.propagate(e); + @Override + public void isLeader() { + if (!beenLeader) { + masterCounter.incrementAndGet(); + beenLeader = true; + try { + latch.reset(); + } catch (Exception e) { + throw Throwables.propagate(e); + } + } else { + masterCounter.incrementAndGet(); + CloseableUtils.closeQuietly(latch); + timesSquare.countDown(); + } } - } - else - { - masterCounter.incrementAndGet(); - CloseableUtils.closeQuietly(latch); - timesSquare.countDown(); - } - } - @Override - public void notLeader() - { - notLeaderCounter.incrementAndGet(); - } - }, exec); + @Override + public void notLeader() { + notLeaderCounter.incrementAndGet(); + } + }, + exec); latches.add(latch); } - try - { + try { client.start(); - for ( LeaderLatch latch : latches ) - { + for (LeaderLatch latch : latches) { latch.start(); } @@ -1029,17 +974,12 @@ public void notLeader() assertEquals(masterCounter.get(), PARTICIPANT_QTY * 2); assertEquals(notLeaderCounter.get(), PARTICIPANT_QTY * 2 - SILENT_QTY); - for ( LeaderLatch latch : latches ) - { + for (LeaderLatch latch : latches) { assertEquals(latch.getState(), LeaderLatch.State.CLOSED); } - } - finally - { - for ( LeaderLatch latch : latches ) - { - if ( latch.getState() != LeaderLatch.State.CLOSED ) - { + } finally { + for (LeaderLatch latch : latches) { + if (latch.getState() != LeaderLatch.State.CLOSED) { CloseableUtils.closeQuietly(latch); } } @@ -1048,47 +988,38 @@ public void notLeader() } @Test - public void testCallbackDontNotify() throws Exception - { + public void testCallbackDontNotify() throws Exception { final AtomicLong masterCounter = new AtomicLong(0); final AtomicLong notLeaderCounter = new AtomicLong(0); Timing timing = new Timing(); - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); + CuratorFramework client = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); final LeaderLatch leader = new LeaderLatch(client, PATH_NAME); final LeaderLatch notifiedLeader = new LeaderLatch(client, PATH_NAME, "", LeaderLatch.CloseMode.NOTIFY_LEADER); - leader.addListener(new LeaderLatchListener() - { + leader.addListener(new LeaderLatchListener() { @Override - public void isLeader() - { - } + public void isLeader() {} @Override - public void notLeader() - { + public void notLeader() { masterCounter.incrementAndGet(); } }); - notifiedLeader.addListener(new LeaderLatchListener() - { + notifiedLeader.addListener(new LeaderLatchListener() { @Override - public void isLeader() - { - } + public void isLeader() {} @Override - public void notLeader() - { + public void notLeader() { notLeaderCounter.incrementAndGet(); } }); - try - { + try { client.start(); leader.start(); @@ -1111,15 +1042,11 @@ public void notLeader() assertEquals(masterCounter.get(), 1); assertEquals(notLeaderCounter.get(), 0); - } - finally - { - if ( leader.getState() != LeaderLatch.State.CLOSED ) - { + } finally { + if (leader.getState() != LeaderLatch.State.CLOSED) { CloseableUtils.closeQuietly(leader); } - if ( notifiedLeader.getState() != LeaderLatch.State.CLOSED ) - { + if (notifiedLeader.getState() != LeaderLatch.State.CLOSED) { CloseableUtils.closeQuietly(notifiedLeader); } TestCleanState.closeAndTestClean(client); @@ -1127,12 +1054,12 @@ public void notLeader() } @Test - public void testNoServerAtStart() - { + public void testNoServerAtStart() { CloseableUtils.closeQuietly(server); Timing timing = new Timing(); - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryNTimes(5, 1000)); + CuratorFramework client = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), timing.connection(), new RetryNTimes(5, 1000)); client.start(); @@ -1140,25 +1067,20 @@ public void testNoServerAtStart() final CountDownLatch leaderCounter = new CountDownLatch(1); final AtomicInteger leaderCount = new AtomicInteger(0); final AtomicInteger notLeaderCount = new AtomicInteger(0); - leader.addListener(new LeaderLatchListener() - { + leader.addListener(new LeaderLatchListener() { @Override - public void isLeader() - { + public void isLeader() { leaderCounter.countDown(); leaderCount.incrementAndGet(); } @Override - public void notLeader() - { + public void notLeader() { notLeaderCount.incrementAndGet(); } - }); - try - { + try { leader.start(); timing.sleepABit(); @@ -1170,57 +1092,45 @@ public void notLeader() assertEquals(leaderCount.get(), 1, "Elected too many times"); assertEquals(notLeaderCount.get(), 0, "Unelected too many times"); - } - catch ( Exception e ) - { + } catch (Exception e) { fail("Unexpected exception", e); - } - finally - { + } finally { CloseableUtils.closeQuietly(leader); TestCleanState.closeAndTestClean(client); CloseableUtils.closeQuietly(server); } } - private enum Mode - { + private enum Mode { START_IMMEDIATELY, START_IN_THREADS } - private void basic(Mode mode) throws Exception - { - final int PARTICIPANT_QTY = 1;//0; + private void basic(Mode mode) throws Exception { + final int PARTICIPANT_QTY = 1; // 0; List latches = Lists.newArrayList(); Timing timing = new Timing(); - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); - try - { + CuratorFramework client = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); + try { client.start(); - for ( int i = 0; i < PARTICIPANT_QTY; ++i ) - { + for (int i = 0; i < PARTICIPANT_QTY; ++i) { LeaderLatch latch = new LeaderLatch(client, PATH_NAME); - if ( mode == Mode.START_IMMEDIATELY ) - { + if (mode == Mode.START_IMMEDIATELY) { latch.start(); } latches.add(latch); } - if ( mode == Mode.START_IN_THREADS ) - { + if (mode == Mode.START_IN_THREADS) { ExecutorService service = Executors.newFixedThreadPool(latches.size()); - for ( final LeaderLatch latch : latches ) - { - service.submit(new Callable() - { + for (final LeaderLatch latch : latches) { + service.submit(new Callable() { @Override - public Object call() throws Exception - { - Thread.sleep((int)(100 * Math.random())); + public Object call() throws Exception { + Thread.sleep((int) (100 * Math.random())); latch.start(); return null; } @@ -1229,36 +1139,30 @@ public Object call() throws Exception service.shutdown(); } - while ( latches.size() > 0 ) - { + while (latches.size() > 0) { List leaders = waitForALeader(latches, timing); assertEquals(leaders.size(), 1); // there can only be one leader LeaderLatch theLeader = leaders.get(0); - if ( mode == Mode.START_IMMEDIATELY ) - { - assertEquals(latches.indexOf(theLeader), 0); // assert ordering - leadership should advance in start order + if (mode == Mode.START_IMMEDIATELY) { + assertEquals( + latches.indexOf(theLeader), + 0); // assert ordering - leadership should advance in start order } theLeader.close(); latches.remove(theLeader); } - } - finally - { - for ( LeaderLatch latch : latches ) - { + } finally { + for (LeaderLatch latch : latches) { CloseableUtils.closeQuietly(latch); } TestCleanState.closeAndTestClean(client); } } - private List waitForALeader(List latches, Timing timing) throws InterruptedException - { - for ( int i = 0; i < MAX_LOOPS; ++i ) - { + private List waitForALeader(List latches, Timing timing) throws InterruptedException { + for (int i = 0; i < MAX_LOOPS; ++i) { List leaders = getLeaders(latches); - if ( leaders.size() != 0 ) - { + if (leaders.size() != 0) { return leaders; } timing.sleepABit(); @@ -1266,13 +1170,10 @@ private List waitForALeader(List latches, Timing timin return Lists.newArrayList(); } - private List getLeaders(Collection latches) - { + private List getLeaders(Collection latches) { List leaders = Lists.newArrayList(); - for ( LeaderLatch latch : latches ) - { - if ( latch.hasLeadership() ) - { + for (LeaderLatch latch : latches) { + if (latch.hasLeadership()) { leaders.add(latch); } } @@ -1280,11 +1181,11 @@ private List getLeaders(Collection latches) } @Test - public void testRelativePath() - { - assertThrows(IllegalArgumentException.class, ()->{ + public void testRelativePath() { + assertThrows(IllegalArgumentException.class, () -> { Timing timing = new Timing(); - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); + CuratorFramework client = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); new LeaderLatch(client, "parent"); }); } diff --git a/curator-recipes/src/test/java/org/apache/curator/framework/recipes/leader/TestLeaderLatchCluster.java b/curator-recipes/src/test/java/org/apache/curator/framework/recipes/leader/TestLeaderLatchCluster.java index 7692d7b18..8f9112405 100644 --- a/curator-recipes/src/test/java/org/apache/curator/framework/recipes/leader/TestLeaderLatchCluster.java +++ b/curator-recipes/src/test/java/org/apache/curator/framework/recipes/leader/TestLeaderLatchCluster.java @@ -22,6 +22,8 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import com.google.common.collect.Lists; +import java.util.Collection; +import java.util.List; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.retry.ExponentialBackoffRetry; @@ -32,21 +34,15 @@ import org.apache.curator.utils.CloseableUtils; import org.junit.jupiter.api.Test; -import java.util.Collection; -import java.util.List; - -public class TestLeaderLatchCluster extends CuratorTestBase -{ +public class TestLeaderLatchCluster extends CuratorTestBase { private static final int MAX_LOOPS = 5; - private static class ClientAndLatch - { - final CuratorFramework client; - final LeaderLatch latch; - final int index; + private static class ClientAndLatch { + final CuratorFramework client; + final LeaderLatch latch; + final int index; - private ClientAndLatch(CuratorFramework client, LeaderLatch latch, int index) - { + private ClientAndLatch(CuratorFramework client, LeaderLatch latch, int index) { this.client = client; this.latch = latch; this.index = index; @@ -54,20 +50,21 @@ private ClientAndLatch(CuratorFramework client, LeaderLatch latch, int index) } @Test - public void testInCluster() throws Exception - { + public void testInCluster() throws Exception { final int PARTICIPANT_QTY = 3; final int sessionLength = timing.session() / 4; - List clients = Lists.newArrayList(); - TestingCluster cluster = createAndStartCluster(PARTICIPANT_QTY); - try - { - List instances = Lists.newArrayList(cluster.getInstances()); - for ( int i = 0; i < PARTICIPANT_QTY; ++i ) - { - CuratorFramework client = CuratorFrameworkFactory.newClient(instances.get(i).getConnectString(), sessionLength, sessionLength, new ExponentialBackoffRetry(100, 3)); - LeaderLatch latch = new LeaderLatch(client, "/latch"); + List clients = Lists.newArrayList(); + TestingCluster cluster = createAndStartCluster(PARTICIPANT_QTY); + try { + List instances = Lists.newArrayList(cluster.getInstances()); + for (int i = 0; i < PARTICIPANT_QTY; ++i) { + CuratorFramework client = CuratorFrameworkFactory.newClient( + instances.get(i).getConnectString(), + sessionLength, + sessionLength, + new ExponentialBackoffRetry(100, 3)); + LeaderLatch latch = new LeaderLatch(client, "/latch"); clients.add(new ClientAndLatch(client, latch, i)); client.start(); @@ -85,11 +82,8 @@ public void testInCluster() throws Exception assertNotNull(leader); assertEquals(getLeaders(clients).size(), 1); - } - finally - { - for ( ClientAndLatch client : clients ) - { + } finally { + for (ClientAndLatch client : clients) { CloseableUtils.closeQuietly(client.latch); CloseableUtils.closeQuietly(client.client); } @@ -98,18 +92,14 @@ public void testInCluster() throws Exception } @Override - protected void createServer() - { + protected void createServer() { // NOP } - private ClientAndLatch waitForALeader(List latches, Timing2 timing) throws InterruptedException - { - for ( int i = 0; i < MAX_LOOPS; ++i ) - { + private ClientAndLatch waitForALeader(List latches, Timing2 timing) throws InterruptedException { + for (int i = 0; i < MAX_LOOPS; ++i) { List leaders = getLeaders(latches); - if ( leaders.size() != 0 ) - { + if (leaders.size() != 0) { return leaders.get(0); } timing.sleepABit(); @@ -117,13 +107,10 @@ private ClientAndLatch waitForALeader(List latches, Timing2 timi return null; } - private List getLeaders(Collection latches) - { + private List getLeaders(Collection latches) { List leaders = Lists.newArrayList(); - for ( ClientAndLatch clientAndLatch : latches ) - { - if ( clientAndLatch.latch.hasLeadership() ) - { + for (ClientAndLatch clientAndLatch : latches) { + if (clientAndLatch.latch.hasLeadership()) { leaders.add(clientAndLatch); } } diff --git a/curator-recipes/src/test/java/org/apache/curator/framework/recipes/leader/TestLeaderSelector.java b/curator-recipes/src/test/java/org/apache/curator/framework/recipes/leader/TestLeaderSelector.java index e8a980c98..5e4dc1f67 100644 --- a/curator-recipes/src/test/java/org/apache/curator/framework/recipes/leader/TestLeaderSelector.java +++ b/curator-recipes/src/test/java/org/apache/curator/framework/recipes/leader/TestLeaderSelector.java @@ -28,6 +28,19 @@ import com.google.common.collect.Lists; import com.google.common.collect.Queues; import com.google.common.collect.Sets; +import java.util.Arrays; +import java.util.List; +import java.util.Set; +import java.util.concurrent.AbstractExecutorService; +import java.util.concurrent.ArrayBlockingQueue; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.Semaphore; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.state.ConnectionState; @@ -42,48 +55,26 @@ import org.apache.curator.utils.CloseableUtils; import org.junit.jupiter.api.Test; -import java.util.Arrays; -import java.util.List; -import java.util.Set; -import java.util.concurrent.ArrayBlockingQueue; -import java.util.concurrent.AbstractExecutorService; -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.LinkedBlockingQueue; -import java.util.concurrent.Semaphore; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicInteger; - -public class TestLeaderSelector extends BaseClassForTests -{ +public class TestLeaderSelector extends BaseClassForTests { private static final String PATH_NAME = "/one/two/me"; @Test - public void testInterruption() throws Exception - { + public void testInterruption() throws Exception { Timing2 timing = new Timing2(); LeaderSelector selector = null; CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); - try - { + try { client.start(); CountDownLatch exitLatch = new CountDownLatch(1); BlockingQueue threadExchange = new ArrayBlockingQueue<>(1); - LeaderSelectorListener listener = new LeaderSelectorListenerAdapter() - { + LeaderSelectorListener listener = new LeaderSelectorListenerAdapter() { @Override - public void takeLeadership(CuratorFramework client) throws Exception - { + public void takeLeadership(CuratorFramework client) throws Exception { threadExchange.put(Thread.currentThread()); - try - { + try { Thread.currentThread().join(); - } - finally - { + } finally { exitLatch.countDown(); } } @@ -96,53 +87,41 @@ public void takeLeadership(CuratorFramework client) throws Exception assertTrue(timing.awaitLatch(exitLatch)); timing.sleepABit(); // wait for leader selector to clear nodes assertEquals(0, selector.failedMutexReleaseCount.get()); - } - finally - { + } finally { CloseableUtils.closeQuietly(selector); CloseableUtils.closeQuietly(client); } } @Test - public void testErrorPolicies() throws Exception - { + public void testErrorPolicies() throws Exception { Timing2 timing = new Timing2(); LeaderSelector selector = null; - CuratorFramework client = CuratorFrameworkFactory - .builder() - .connectString(server.getConnectString()) - .connectionTimeoutMs(timing.connection()) - .sessionTimeoutMs(timing.session()) - .retryPolicy(new RetryOneTime(1)) - .connectionStateErrorPolicy(new StandardConnectionStateErrorPolicy()) - .build(); - try - { + CuratorFramework client = CuratorFrameworkFactory.builder() + .connectString(server.getConnectString()) + .connectionTimeoutMs(timing.connection()) + .sessionTimeoutMs(timing.session()) + .retryPolicy(new RetryOneTime(1)) + .connectionStateErrorPolicy(new StandardConnectionStateErrorPolicy()) + .build(); + try { final BlockingQueue changes = Queues.newLinkedBlockingQueue(); - ConnectionStateListener stateListener = new ConnectionStateListener() - { + ConnectionStateListener stateListener = new ConnectionStateListener() { @Override - public void stateChanged(CuratorFramework client, ConnectionState newState) - { + public void stateChanged(CuratorFramework client, ConnectionState newState) { changes.add(newState.name()); } }; client.getConnectionStateListenable().addListener(stateListener); client.start(); - LeaderSelectorListener listener = new LeaderSelectorListenerAdapter() - { + LeaderSelectorListener listener = new LeaderSelectorListenerAdapter() { @Override - public void takeLeadership(CuratorFramework client) throws Exception - { + public void takeLeadership(CuratorFramework client) throws Exception { changes.add("leader"); - try - { + try { Thread.currentThread().join(); - } - catch ( InterruptedException e ) - { + } catch (InterruptedException e) { changes.add("release"); Thread.currentThread().interrupt(); } @@ -151,14 +130,21 @@ public void takeLeadership(CuratorFramework client) throws Exception selector = new LeaderSelector(client, "/test", listener); selector.start(); - assertEquals(changes.poll(timing.forWaiting().milliseconds(), TimeUnit.MILLISECONDS), ConnectionState.CONNECTED.name()); + assertEquals( + changes.poll(timing.forWaiting().milliseconds(), TimeUnit.MILLISECONDS), + ConnectionState.CONNECTED.name()); assertEquals(changes.poll(timing.forWaiting().milliseconds(), TimeUnit.MILLISECONDS), "leader"); server.close(); List next = Lists.newArrayList(); next.add(changes.poll(timing.forSessionSleep().milliseconds(), TimeUnit.MILLISECONDS)); next.add(changes.poll(timing.forSessionSleep().milliseconds(), TimeUnit.MILLISECONDS)); - assertTrue(next.equals(Arrays.asList(ConnectionState.SUSPENDED.name(), "release")) || next.equals(Arrays.asList("release", ConnectionState.SUSPENDED.name())), next.toString()); - assertEquals(changes.poll(timing.forSessionSleep().milliseconds(), TimeUnit.MILLISECONDS), ConnectionState.LOST.name()); + assertTrue( + next.equals(Arrays.asList(ConnectionState.SUSPENDED.name(), "release")) + || next.equals(Arrays.asList("release", ConnectionState.SUSPENDED.name())), + next.toString()); + assertEquals( + changes.poll(timing.forSessionSleep().milliseconds(), TimeUnit.MILLISECONDS), + ConnectionState.LOST.name()); selector.close(); client.close(); @@ -166,52 +152,52 @@ public void takeLeadership(CuratorFramework client) throws Exception changes.clear(); server = new TestingServer(); - client = CuratorFrameworkFactory - .builder() - .connectString(server.getConnectString()) - .connectionTimeoutMs(timing.connection()) - .sessionTimeoutMs(timing.session()) - .retryPolicy(new RetryOneTime(1)) - .connectionStateErrorPolicy(new SessionConnectionStateErrorPolicy()) - .build(); + client = CuratorFrameworkFactory.builder() + .connectString(server.getConnectString()) + .connectionTimeoutMs(timing.connection()) + .sessionTimeoutMs(timing.session()) + .retryPolicy(new RetryOneTime(1)) + .connectionStateErrorPolicy(new SessionConnectionStateErrorPolicy()) + .build(); client.getConnectionStateListenable().addListener(stateListener); client.start(); selector = new LeaderSelector(client, "/test", listener); selector.start(); - assertEquals(changes.poll(timing.forWaiting().milliseconds(), TimeUnit.MILLISECONDS), ConnectionState.CONNECTED.name()); + assertEquals( + changes.poll(timing.forWaiting().milliseconds(), TimeUnit.MILLISECONDS), + ConnectionState.CONNECTED.name()); assertEquals(changes.poll(timing.forWaiting().milliseconds(), TimeUnit.MILLISECONDS), "leader"); server.stop(); - assertEquals(changes.poll(timing.forWaiting().milliseconds(), TimeUnit.MILLISECONDS), ConnectionState.SUSPENDED.name()); + assertEquals( + changes.poll(timing.forWaiting().milliseconds(), TimeUnit.MILLISECONDS), + ConnectionState.SUSPENDED.name()); next = Lists.newArrayList(); next.add(changes.poll(timing.forSessionSleep().milliseconds(), TimeUnit.MILLISECONDS)); next.add(changes.poll(timing.forSessionSleep().milliseconds(), TimeUnit.MILLISECONDS)); - assertTrue(next.equals(Arrays.asList(ConnectionState.LOST.name(), "release")) || next.equals(Arrays.asList("release", ConnectionState.LOST.name())), next.toString()); - } - finally - { + assertTrue( + next.equals(Arrays.asList(ConnectionState.LOST.name(), "release")) + || next.equals(Arrays.asList("release", ConnectionState.LOST.name())), + next.toString()); + } finally { CloseableUtils.closeQuietly(selector); CloseableUtils.closeQuietly(client); } } @Test - public void testLeaderNodeDeleteOnInterrupt() throws Exception - { + public void testLeaderNodeDeleteOnInterrupt() throws Exception { Timing2 timing = new Timing2(); LeaderSelector selector = null; CuratorFramework client = null; - try - { - client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); + try { + client = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); final CountDownLatch reconnectedLatch = new CountDownLatch(1); - ConnectionStateListener connectionStateListener = new ConnectionStateListener() - { + ConnectionStateListener connectionStateListener = new ConnectionStateListener() { @Override - public void stateChanged(CuratorFramework client, ConnectionState newState) - { - if ( newState == ConnectionState.RECONNECTED ) - { + public void stateChanged(CuratorFramework client, ConnectionState newState) { + if (newState == ConnectionState.RECONNECTED) { reconnectedLatch.countDown(); } } @@ -220,26 +206,19 @@ public void stateChanged(CuratorFramework client, ConnectionState newState) client.start(); final BlockingQueue queue = new ArrayBlockingQueue(1); - LeaderSelectorListener listener = new LeaderSelectorListener() - { + LeaderSelectorListener listener = new LeaderSelectorListener() { @Override - public void takeLeadership(CuratorFramework client) throws Exception - { + public void takeLeadership(CuratorFramework client) throws Exception { queue.add(Thread.currentThread()); - try - { + try { Thread.currentThread().join(); - } - catch ( InterruptedException e ) - { + } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } @Override - public void stateChanged(CuratorFramework client, ConnectionState newState) - { - } + public void stateChanged(CuratorFramework client, ConnectionState newState) {} }; selector = new LeaderSelector(client, "/leader", listener); selector.start(); @@ -252,9 +231,7 @@ public void stateChanged(CuratorFramework client, ConnectionState newState) timing.sleepABit(); assertEquals(client.getChildren().forPath("/leader").size(), 0); - } - finally - { + } finally { CloseableUtils.closeQuietly(selector); CloseableUtils.closeQuietly(client); } @@ -303,22 +280,19 @@ public void execute(Runnable command) { } @Test - public void testInterruptLeadershipWithRequeue() throws Exception - { + public void testInterruptLeadershipWithRequeue() throws Exception { Timing timing = new Timing(); LeaderSelector selector = null; CuratorFramework client = null; - try - { - client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); + try { + client = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); client.start(); final Semaphore semaphore = new Semaphore(0); - LeaderSelectorListener listener = new LeaderSelectorListenerAdapter() - { + LeaderSelectorListener listener = new LeaderSelectorListenerAdapter() { @Override - public void takeLeadership(CuratorFramework client) throws Exception - { + public void takeLeadership(CuratorFramework client) throws Exception { semaphore.release(); Thread.currentThread().join(); } @@ -336,46 +310,36 @@ public void takeLeadership(CuratorFramework client) throws Exception selector.interruptLeadership(); assertTrue(timing.acquireSemaphore(semaphore)); - } - finally - { + } finally { CloseableUtils.closeQuietly(selector); CloseableUtils.closeQuietly(client); } } @Test - public void testInterruptLeadership() throws Exception - { + public void testInterruptLeadership() throws Exception { LeaderSelector selector = null; Timing timing = new Timing(); - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); - try - { + CuratorFramework client = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); + try { client.start(); final CountDownLatch isLeaderLatch = new CountDownLatch(1); final CountDownLatch losingLeaderLatch = new CountDownLatch(1); - LeaderSelectorListener listener = new LeaderSelectorListener() - { + LeaderSelectorListener listener = new LeaderSelectorListener() { @Override - public void takeLeadership(CuratorFramework client) throws Exception - { + public void takeLeadership(CuratorFramework client) throws Exception { isLeaderLatch.countDown(); - try - { + try { Thread.currentThread().join(); - } - finally - { + } finally { losingLeaderLatch.countDown(); } } @Override - public void stateChanged(CuratorFramework client, ConnectionState newState) - { - } + public void stateChanged(CuratorFramework client, ConnectionState newState) {} }; selector = new LeaderSelector(client, "/leader", listener); @@ -384,44 +348,35 @@ public void stateChanged(CuratorFramework client, ConnectionState newState) assertTrue(timing.awaitLatch(isLeaderLatch)); selector.interruptLeadership(); assertTrue(timing.awaitLatch(losingLeaderLatch)); - } - finally - { + } finally { CloseableUtils.closeQuietly(selector); CloseableUtils.closeQuietly(client); } } @Test - public void testRaceAtStateChanged() throws Exception - { + public void testRaceAtStateChanged() throws Exception { LeaderSelector selector = null; Timing timing = new Timing(); - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); - try - { + CuratorFramework client = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); + try { client.start(); final CountDownLatch takeLeadershipLatch = new CountDownLatch(1); final CountDownLatch lostLatch = new CountDownLatch(1); final CountDownLatch reconnectedLatch = new CountDownLatch(1); - LeaderSelectorListener listener = new LeaderSelectorListener() - { + LeaderSelectorListener listener = new LeaderSelectorListener() { @Override - public void takeLeadership(CuratorFramework client) throws Exception - { - takeLeadershipLatch.countDown(); // should never get here + public void takeLeadership(CuratorFramework client) throws Exception { + takeLeadershipLatch.countDown(); // should never get here } @Override - public void stateChanged(CuratorFramework client, ConnectionState newState) - { - if ( newState == ConnectionState.RECONNECTED ) - { + public void stateChanged(CuratorFramework client, ConnectionState newState) { + if (newState == ConnectionState.RECONNECTED) { reconnectedLatch.countDown(); - } - else if ( newState == ConnectionState.LOST ) - { + } else if (newState == ConnectionState.LOST) { lostLatch.countDown(); throw new CancelLeadershipException(); } @@ -446,76 +401,69 @@ else if ( newState == ConnectionState.LOST ) assertTrue(timing.awaitLatch(reconnectedLatch)); assertFalse(takeLeadershipLatch.await(3, TimeUnit.SECONDS)); - } - finally - { + } finally { CloseableUtils.closeQuietly(selector); CloseableUtils.closeQuietly(client); } } @Test - public void testAutoRequeue() throws Exception - { + public void testAutoRequeue() throws Exception { Timing timing = new Timing(); LeaderSelector selector = null; - CuratorFramework client = CuratorFrameworkFactory.builder().connectString(server.getConnectString()).retryPolicy(new RetryOneTime(1)).sessionTimeoutMs(timing.session()).build(); - try - { + CuratorFramework client = CuratorFrameworkFactory.builder() + .connectString(server.getConnectString()) + .retryPolicy(new RetryOneTime(1)) + .sessionTimeoutMs(timing.session()) + .build(); + try { client.start(); final Semaphore semaphore = new Semaphore(0); - LeaderSelectorListener listener = new LeaderSelectorListener() - { + LeaderSelectorListener listener = new LeaderSelectorListener() { @Override - public void takeLeadership(CuratorFramework client) throws Exception - { + public void takeLeadership(CuratorFramework client) throws Exception { Thread.sleep(10); semaphore.release(); } @Override - public void stateChanged(CuratorFramework client, ConnectionState newState) - { - } + public void stateChanged(CuratorFramework client, ConnectionState newState) {} }; selector = new LeaderSelector(client, "/leader", listener); selector.autoRequeue(); selector.start(); assertTrue(timing.acquireSemaphore(semaphore, 2)); - } - finally - { + } finally { CloseableUtils.closeQuietly(selector); CloseableUtils.closeQuietly(client); } } @Test - public void testServerDying() throws Exception - { + public void testServerDying() throws Exception { Timing timing = new Timing(); LeaderSelector selector = null; - CuratorFramework client = CuratorFrameworkFactory.builder().connectionTimeoutMs(timing.connection()).connectString(server.getConnectString()).retryPolicy(new RetryOneTime(1)).sessionTimeoutMs(timing.session()).build(); + CuratorFramework client = CuratorFrameworkFactory.builder() + .connectionTimeoutMs(timing.connection()) + .connectString(server.getConnectString()) + .retryPolicy(new RetryOneTime(1)) + .sessionTimeoutMs(timing.session()) + .build(); client.start(); - try - { + try { final Semaphore semaphore = new Semaphore(0); - LeaderSelectorListener listener = new LeaderSelectorListener() - { + LeaderSelectorListener listener = new LeaderSelectorListener() { @Override - public void takeLeadership(CuratorFramework client) throws Exception - { + public void takeLeadership(CuratorFramework client) throws Exception { semaphore.release(); Thread.sleep(Integer.MAX_VALUE); } @Override - public void stateChanged(CuratorFramework client, ConnectionState newState) - { - if ( newState == ConnectionState.LOST ) - { + public void stateChanged(CuratorFramework client, ConnectionState newState) { + if (newState == ConnectionState.LOST) { semaphore.release(); } } @@ -528,47 +476,36 @@ public void stateChanged(CuratorFramework client, ConnectionState newState) server.close(); timing.acquireSemaphore(semaphore); - } - finally - { + } finally { CloseableUtils.closeQuietly(selector); CloseableUtils.closeQuietly(client); } } @Test - public void testKillSessionThenCloseShouldElectNewLeader() throws Exception - { + public void testKillSessionThenCloseShouldElectNewLeader() throws Exception { final Timing timing = new Timing(); - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); + CuratorFramework client = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); client.start(); - try - { + try { final Semaphore semaphore = new Semaphore(0); final CountDownLatch interruptedLatch = new CountDownLatch(1); final AtomicInteger leaderCount = new AtomicInteger(0); - LeaderSelectorListener listener = new LeaderSelectorListenerAdapter() - { + LeaderSelectorListener listener = new LeaderSelectorListenerAdapter() { @Override - public void takeLeadership(CuratorFramework client) throws Exception - { + public void takeLeadership(CuratorFramework client) throws Exception { leaderCount.incrementAndGet(); - try - { + try { semaphore.release(); - try - { + try { Thread.currentThread().join(); - } - catch ( InterruptedException e ) - { + } catch (InterruptedException e) { Thread.currentThread().interrupt(); interruptedLatch.countDown(); } - } - finally - { + } finally { leaderCount.decrementAndGet(); } } @@ -597,18 +534,13 @@ public void takeLeadership(CuratorFramework client) throws Exception assertTrue(timing.acquireSemaphore(semaphore, 1)); assertEquals(leaderCount.get(), 1); - if ( leaderSelector1.hasLeadership() ) - { + if (leaderSelector1.hasLeadership()) { leaderSelector1.close(); leaderSelector1Closed = true; - } - else if ( leaderSelector2.hasLeadership() ) - { + } else if (leaderSelector2.hasLeadership()) { leaderSelector2.close(); leaderSelector2Closed = true; - } - else - { + } else { fail("No leaderselector has leadership!"); } @@ -616,17 +548,13 @@ else if ( leaderSelector2.hasLeadership() ) assertTrue(timing.acquireSemaphore(semaphore, 1)); assertEquals(leaderCount.get(), 1); - if ( !leaderSelector1Closed ) - { + if (!leaderSelector1Closed) { leaderSelector1.close(); } - if ( !leaderSelector2Closed ) - { + if (!leaderSelector2Closed) { leaderSelector2.close(); } - } - finally - { + } finally { client.close(); } } @@ -638,38 +566,29 @@ else if ( leaderSelector2.hasLeadership() ) * it uses autoRequeue instead of explicitly calling requeue */ @Test - public void testKillServerThenCloseShouldElectNewLeader() throws Exception - { + public void testKillServerThenCloseShouldElectNewLeader() throws Exception { final Timing timing = new Timing(); - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); + CuratorFramework client = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); client.start(); - try - { + try { final Semaphore semaphore = new Semaphore(0); final CountDownLatch interruptedLatch = new CountDownLatch(1); final AtomicInteger leaderCount = new AtomicInteger(0); - LeaderSelectorListener listener = new LeaderSelectorListenerAdapter() - { + LeaderSelectorListener listener = new LeaderSelectorListenerAdapter() { @Override - public void takeLeadership(CuratorFramework client) throws Exception - { + public void takeLeadership(CuratorFramework client) throws Exception { leaderCount.incrementAndGet(); - try - { + try { semaphore.release(); - try - { + try { Thread.currentThread().join(); - } - catch ( InterruptedException e ) - { + } catch (InterruptedException e) { Thread.currentThread().interrupt(); interruptedLatch.countDown(); } - } - finally - { + } finally { leaderCount.decrementAndGet(); } } @@ -698,18 +617,13 @@ public void takeLeadership(CuratorFramework client) throws Exception assertTrue(timing.acquireSemaphore(semaphore, 1)); assertEquals(leaderCount.get(), 1); - if ( leaderSelector1.hasLeadership() ) - { + if (leaderSelector1.hasLeadership()) { leaderSelector1.close(); leaderSelector1Closed = true; - } - else if ( leaderSelector2.hasLeadership() ) - { + } else if (leaderSelector2.hasLeadership()) { leaderSelector2.close(); leaderSelector2Closed = true; - } - else - { + } else { fail("No leaderselector has leadership!"); } @@ -717,53 +631,39 @@ else if ( leaderSelector2.hasLeadership() ) assertTrue(timing.acquireSemaphore(semaphore, 1)); assertEquals(leaderCount.get(), 1); - if ( !leaderSelector1Closed ) - { + if (!leaderSelector1Closed) { leaderSelector1.close(); } - if ( !leaderSelector2Closed ) - { + if (!leaderSelector2Closed) { leaderSelector2.close(); } - } - finally - { + } finally { client.close(); } } @Test - public void testClosing() throws Exception - { + public void testClosing() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client.start(); - try - { + try { final CountDownLatch latch = new CountDownLatch(1); - LeaderSelector leaderSelector1 = new LeaderSelector(client, PATH_NAME, new LeaderSelectorListener() - { + LeaderSelector leaderSelector1 = new LeaderSelector(client, PATH_NAME, new LeaderSelectorListener() { @Override - public void stateChanged(CuratorFramework client, ConnectionState newState) - { - } + public void stateChanged(CuratorFramework client, ConnectionState newState) {} @Override - public void takeLeadership(CuratorFramework client) throws Exception - { + public void takeLeadership(CuratorFramework client) throws Exception { latch.await(10, TimeUnit.SECONDS); } }); - LeaderSelector leaderSelector2 = new LeaderSelector(client, PATH_NAME, new LeaderSelectorListener() - { + LeaderSelector leaderSelector2 = new LeaderSelector(client, PATH_NAME, new LeaderSelectorListener() { @Override - public void stateChanged(CuratorFramework client, ConnectionState newState) - { - } + public void stateChanged(CuratorFramework client, ConnectionState newState) {} @Override - public void takeLeadership(CuratorFramework client) throws Exception - { + public void takeLeadership(CuratorFramework client) throws Exception { latch.await(10, TimeUnit.SECONDS); } }); @@ -771,8 +671,7 @@ public void takeLeadership(CuratorFramework client) throws Exception leaderSelector1.start(); leaderSelector2.start(); - while ( !leaderSelector1.hasLeadership() && !leaderSelector2.hasLeadership() ) - { + while (!leaderSelector1.hasLeadership() && !leaderSelector2.hasLeadership()) { Thread.sleep(1000); } @@ -780,13 +679,10 @@ public void takeLeadership(CuratorFramework client) throws Exception LeaderSelector positiveLeader; LeaderSelector negativeLeader; - if ( leaderSelector1.hasLeadership() ) - { + if (leaderSelector1.hasLeadership()) { positiveLeader = leaderSelector1; negativeLeader = leaderSelector2; - } - else - { + } else { positiveLeader = leaderSelector2; negativeLeader = leaderSelector1; } @@ -799,64 +695,50 @@ public void takeLeadership(CuratorFramework client) throws Exception positiveLeader.close(); Thread.sleep(1000); assertFalse(positiveLeader.hasLeadership()); - } - finally - { + } finally { client.close(); } } @SuppressWarnings({"ForLoopReplaceableByForEach"}) @Test - public void testRotatingLeadership() throws Exception - { + public void testRotatingLeadership() throws Exception { final int LEADER_QTY = 5; final int REPEAT_QTY = 3; final Timing timing = new Timing(); - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); + CuratorFramework client = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); client.start(); - try - { + try { final BlockingQueue leaderList = new LinkedBlockingQueue(); List selectors = Lists.newArrayList(); - for ( int i = 0; i < LEADER_QTY; ++i ) - { + for (int i = 0; i < LEADER_QTY; ++i) { final int ourIndex = i; - LeaderSelector leaderSelector = new LeaderSelector(client, PATH_NAME, new LeaderSelectorListener() - { + LeaderSelector leaderSelector = new LeaderSelector(client, PATH_NAME, new LeaderSelectorListener() { @Override - public void takeLeadership(CuratorFramework client) throws Exception - { + public void takeLeadership(CuratorFramework client) throws Exception { timing.sleepABit(); leaderList.add(ourIndex); } @Override - public void stateChanged(CuratorFramework client, ConnectionState newState) - { - } + public void stateChanged(CuratorFramework client, ConnectionState newState) {} }); selectors.add(leaderSelector); } List localLeaderList = Lists.newArrayList(); - for ( int i = 1; i <= REPEAT_QTY; ++i ) - { - for ( LeaderSelector leaderSelector : selectors ) - { - if ( i > 1 ) - { + for (int i = 1; i <= REPEAT_QTY; ++i) { + for (LeaderSelector leaderSelector : selectors) { + if (i > 1) { leaderSelector.requeue(); - } - else - { + } else { leaderSelector.start(); } } - while ( localLeaderList.size() != (i * selectors.size()) ) - { + while (localLeaderList.size() != (i * selectors.size())) { Integer polledIndex = leaderList.poll(10, TimeUnit.SECONDS); assertNotNull(polledIndex); localLeaderList.add(polledIndex); @@ -864,17 +746,14 @@ public void stateChanged(CuratorFramework client, ConnectionState newState) timing.sleepABit(); } - for ( LeaderSelector leaderSelector : selectors ) - { + for (LeaderSelector leaderSelector : selectors) { leaderSelector.close(); } System.out.println(localLeaderList); - for ( int i = 0; i < REPEAT_QTY; ++i ) - { + for (int i = 0; i < REPEAT_QTY; ++i) { Set uniques = Sets.newHashSet(); - for ( int j = 0; j < selectors.size(); ++j ) - { + for (int j = 0; j < selectors.size(); ++j) { assertTrue(localLeaderList.size() > 0); int thisIndex = localLeaderList.remove(0); @@ -882,9 +761,7 @@ public void stateChanged(CuratorFramework client, ConnectionState newState) uniques.add(thisIndex); } } - } - finally - { + } finally { client.close(); } } diff --git a/curator-recipes/src/test/java/org/apache/curator/framework/recipes/leader/TestLeaderSelectorCluster.java b/curator-recipes/src/test/java/org/apache/curator/framework/recipes/leader/TestLeaderSelectorCluster.java index 278f6c0fd..fbd400a6d 100644 --- a/curator-recipes/src/test/java/org/apache/curator/framework/recipes/leader/TestLeaderSelectorCluster.java +++ b/curator-recipes/src/test/java/org/apache/curator/framework/recipes/leader/TestLeaderSelectorCluster.java @@ -22,9 +22,11 @@ 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 org.apache.curator.test.compatibility.CuratorTestBase; -import org.apache.curator.utils.CloseableUtils; +import java.util.Collection; +import java.util.List; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Semaphore; +import java.util.concurrent.atomic.AtomicReference; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.state.ConnectionState; @@ -32,91 +34,75 @@ import org.apache.curator.test.InstanceSpec; import org.apache.curator.test.TestingCluster; import org.apache.curator.test.Timing; +import org.apache.curator.test.compatibility.CuratorTestBase; +import org.apache.curator.utils.CloseableUtils; import org.apache.curator.utils.ZKPaths; import org.junit.jupiter.api.Test; -import java.util.Collection; -import java.util.List; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.Semaphore; -import java.util.concurrent.atomic.AtomicReference; - @SuppressWarnings("ThrowableResultOfMethodCallIgnored") -public class TestLeaderSelectorCluster extends CuratorTestBase -{ +public class TestLeaderSelectorCluster extends CuratorTestBase { @Test - public void testRestart() throws Exception - { - final Timing timing = new Timing(); - - CuratorFramework client = null; - TestingCluster cluster = createAndStartCluster(3); - try - { - client = CuratorFrameworkFactory.newClient(cluster.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); + public void testRestart() throws Exception { + final Timing timing = new Timing(); + + CuratorFramework client = null; + TestingCluster cluster = createAndStartCluster(3); + try { + client = CuratorFrameworkFactory.newClient( + cluster.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); client.start(); - final Semaphore semaphore = new Semaphore(0); - LeaderSelectorListener listener = new LeaderSelectorListener() - { + final Semaphore semaphore = new Semaphore(0); + LeaderSelectorListener listener = new LeaderSelectorListener() { @Override - public void takeLeadership(CuratorFramework client) throws Exception - { - List names = client.getChildren().forPath("/leader"); + public void takeLeadership(CuratorFramework client) throws Exception { + List names = client.getChildren().forPath("/leader"); assertTrue(names.size() > 0); semaphore.release(); } @Override - public void stateChanged(CuratorFramework client, ConnectionState newState) - { - } + public void stateChanged(CuratorFramework client, ConnectionState newState) {} }; - LeaderSelector selector = new LeaderSelector(client, "/leader", listener); + LeaderSelector selector = new LeaderSelector(client, "/leader", listener); selector.autoRequeue(); selector.start(); assertTrue(timing.acquireSemaphore(semaphore)); - InstanceSpec connectionInstance = cluster.findConnectionInstance(client.getZookeeperClient().getZooKeeper()); + InstanceSpec connectionInstance = + cluster.findConnectionInstance(client.getZookeeperClient().getZooKeeper()); cluster.killServer(connectionInstance); assertTrue(timing.multiple(4).acquireSemaphore(semaphore)); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); CloseableUtils.closeQuietly(cluster); } } @Test - public void testLostRestart() throws Exception - { - final Timing timing = new Timing(); - - CuratorFramework client = null; - TestingCluster cluster = createAndStartCluster(3); - try - { - client = CuratorFrameworkFactory.newClient(cluster.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); + public void testLostRestart() throws Exception { + final Timing timing = new Timing(); + + CuratorFramework client = null; + TestingCluster cluster = createAndStartCluster(3); + try { + client = CuratorFrameworkFactory.newClient( + cluster.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); client.start(); client.sync().forPath("/"); - final AtomicReference error = new AtomicReference(null); - final AtomicReference lockNode = new AtomicReference(null); - final Semaphore semaphore = new Semaphore(0); - final CountDownLatch lostLatch = new CountDownLatch(1); - final CountDownLatch internalLostLatch = new CountDownLatch(1); - LeaderSelectorListener listener = new LeaderSelectorListener() - { + final AtomicReference error = new AtomicReference(null); + final AtomicReference lockNode = new AtomicReference(null); + final Semaphore semaphore = new Semaphore(0); + final CountDownLatch lostLatch = new CountDownLatch(1); + final CountDownLatch internalLostLatch = new CountDownLatch(1); + LeaderSelectorListener listener = new LeaderSelectorListener() { @Override - public void takeLeadership(CuratorFramework client) throws Exception - { - try - { - List names = client.getChildren().forPath("/leader"); - if ( names.size() != 1 ) - { + public void takeLeadership(CuratorFramework client) throws Exception { + try { + List names = client.getChildren().forPath("/leader"); + if (names.size() != 1) { semaphore.release(); Exception exception = new Exception("Names size isn't 1: " + names.size()); error.set(exception); @@ -125,35 +111,29 @@ public void takeLeadership(CuratorFramework client) throws Exception lockNode.set(names.get(0)); semaphore.release(); - if ( !timing.multiple(4).awaitLatch(internalLostLatch) ) - { + if (!timing.multiple(4).awaitLatch(internalLostLatch)) { error.set(new Exception("internalLostLatch await failed")); } - } - finally - { + } finally { lostLatch.countDown(); } } @Override - public void stateChanged(CuratorFramework client, ConnectionState newState) - { - if ( newState == ConnectionState.LOST ) - { + public void stateChanged(CuratorFramework client, ConnectionState newState) { + if (newState == ConnectionState.LOST) { internalLostLatch.countDown(); } } }; - LeaderSelector selector = new LeaderSelector(client, "/leader", listener); + LeaderSelector selector = new LeaderSelector(client, "/leader", listener); selector.start(); assertTrue(timing.multiple(4).acquireSemaphore(semaphore)); - if ( error.get() != null ) - { + if (error.get() != null) { throw new AssertionError(error.get()); } - Collection instances = cluster.getInstances(); + Collection instances = cluster.getInstances(); cluster.stop(); assertTrue(timing.multiple(4).awaitLatch(lostLatch)); @@ -161,16 +141,15 @@ public void stateChanged(CuratorFramework client, ConnectionState newState) assertFalse(selector.hasLeadership()); assertNotNull(lockNode.get()); - + cluster = new TestingCluster(instances.toArray(new InstanceSpec[instances.size()])); cluster.start(); - try - { - client.delete().forPath(ZKPaths.makePath("/leader", lockNode.get())); // simulate the lock deleting due to session expiration - } - catch ( Exception ignore ) - { + try { + client.delete() + .forPath(ZKPaths.makePath( + "/leader", lockNode.get())); // simulate the lock deleting due to session expiration + } catch (Exception ignore) { // ignore } @@ -179,17 +158,14 @@ public void stateChanged(CuratorFramework client, ConnectionState newState) selector.requeue(); assertTrue(timing.multiple(4).acquireSemaphore(semaphore)); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); CloseableUtils.closeQuietly(cluster); } } @Override - protected void createServer() throws Exception - { + protected void createServer() throws Exception { // NOP } } diff --git a/curator-recipes/src/test/java/org/apache/curator/framework/recipes/leader/TestLeaderSelectorEdges.java b/curator-recipes/src/test/java/org/apache/curator/framework/recipes/leader/TestLeaderSelectorEdges.java index 331ac49cd..0ca650c87 100644 --- a/curator-recipes/src/test/java/org/apache/curator/framework/recipes/leader/TestLeaderSelectorEdges.java +++ b/curator-recipes/src/test/java/org/apache/curator/framework/recipes/leader/TestLeaderSelectorEdges.java @@ -22,7 +22,8 @@ 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 java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.api.BackgroundCallback; @@ -38,25 +39,20 @@ import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; /** * Test cases designed after CURATOR-45 */ -public class TestLeaderSelectorEdges extends BaseClassForTests -{ +public class TestLeaderSelectorEdges extends BaseClassForTests { private final Logger log = LoggerFactory.getLogger(getClass()); @BeforeAll - public static void setCNXFactory() - { + public static void setCNXFactory() { System.setProperty(ServerCnxnFactory.ZOOKEEPER_SERVER_CNXN_FACTORY, ChaosMonkeyCnxnFactory.class.getName()); } @AfterAll - public static void resetCNXFactory() - { + public static void resetCNXFactory() { System.clearProperty(ServerCnxnFactory.ZOOKEEPER_SERVER_CNXN_FACTORY); } @@ -67,23 +63,19 @@ public static void resetCNXFactory() * @throws Exception */ @Test - public void flappingTest() throws Exception - { - final CuratorFramework client = - CuratorFrameworkFactory.builder() + public void flappingTest() throws Exception { + final CuratorFramework client = CuratorFrameworkFactory.builder() .connectString(server.getConnectString()) .retryPolicy(new RetryNTimes(1, 500)) .sessionTimeoutMs(30000) .build(); final TestLeaderSelectorListener listener = new TestLeaderSelectorListener(); - LeaderSelector leaderSelector1 = - new LeaderSelector(client, ChaosMonkeyCnxnFactory.CHAOS_ZNODE, listener); + LeaderSelector leaderSelector1 = new LeaderSelector(client, ChaosMonkeyCnxnFactory.CHAOS_ZNODE, listener); LeaderSelector leaderSelector2 = null; client.start(); - try - { + try { client.create().forPath(ChaosMonkeyCnxnFactory.CHAOS_ZNODE); leaderSelector1.start(); // At this point the ChaosMonkeyZookeeperServer must close the connection @@ -94,72 +86,57 @@ public void flappingTest() throws Exception // Wait FailedDelete Thread.sleep(ChaosMonkeyCnxnFactory.LOCKOUT_DURATION_MS * 2); // Check that there is no znode - final int children = client.getChildren().forPath(ChaosMonkeyCnxnFactory.CHAOS_ZNODE).size(); - assertEquals(children, 0, - "Still " + children + " znodes under " + ChaosMonkeyCnxnFactory.CHAOS_ZNODE + " lock"); + final int children = client.getChildren() + .forPath(ChaosMonkeyCnxnFactory.CHAOS_ZNODE) + .size(); + assertEquals( + children, 0, "Still " + children + " znodes under " + ChaosMonkeyCnxnFactory.CHAOS_ZNODE + " lock"); // Check that a new LeaderSelector can be started - leaderSelector2 = new LeaderSelector(client, ChaosMonkeyCnxnFactory.CHAOS_ZNODE, - listener); + leaderSelector2 = new LeaderSelector(client, ChaosMonkeyCnxnFactory.CHAOS_ZNODE, listener); leaderSelector2.start(); assertTrue(listener.takeLeadership.await(1, TimeUnit.SECONDS)); - } - finally - { - try - { + } finally { + try { leaderSelector1.close(); - } - catch ( IllegalStateException e ) - { + } catch (IllegalStateException e) { fail(e.getMessage()); } - try - { - if ( leaderSelector2 != null ) - { + try { + if (leaderSelector2 != null) { leaderSelector2.close(); } - } - catch ( IllegalStateException e ) - { + } catch (IllegalStateException e) { fail(e.getMessage()); } client.close(); } } - private class TestLeaderSelectorListener implements LeaderSelectorListener - { + private class TestLeaderSelectorListener implements LeaderSelectorListener { final CountDownLatch takeLeadership = new CountDownLatch(1); final CountDownLatch reconnected = new CountDownLatch(1); @Override - public void takeLeadership(CuratorFramework client) throws Exception - { + public void takeLeadership(CuratorFramework client) throws Exception { log.info("-->takeLeadership({})", client.toString()); takeLeadership.countDown(); log.info("<--takeLeadership({})", client.toString()); } @Override - public void stateChanged(CuratorFramework client, ConnectionState newState) - { - if ( newState == ConnectionState.RECONNECTED ) - { + public void stateChanged(CuratorFramework client, ConnectionState newState) { + if (newState == ConnectionState.RECONNECTED) { reconnected.countDown(); } } - } /** * Create a protected node in background with a retry policy */ @Test - public void createProtectedNodeInBackgroundTest() throws Exception - { - final CuratorFramework client = - CuratorFrameworkFactory.builder() + public void createProtectedNodeInBackgroundTest() throws Exception { + final CuratorFramework client = CuratorFrameworkFactory.builder() .connectString(server.getConnectString()) .retryPolicy(new RetryNTimes(2, 100)) .connectionTimeoutMs(1000) @@ -167,51 +144,41 @@ public void createProtectedNodeInBackgroundTest() throws Exception .build(); final CountDownLatch latch = new CountDownLatch(1); client.start(); - try - { + try { client.create().forPath(ChaosMonkeyCnxnFactory.CHAOS_ZNODE); client.create() - .withProtection() - .withMode(CreateMode.EPHEMERAL_SEQUENTIAL) - .inBackground( - new BackgroundCallback() - { - public void processResult(CuratorFramework client, CuratorEvent event) - throws Exception - { + .withProtection() + .withMode(CreateMode.EPHEMERAL_SEQUENTIAL) + .inBackground(new BackgroundCallback() { + public void processResult(CuratorFramework client, CuratorEvent event) throws Exception { log.info("Receive event {}", event.toString()); - if ( event.getResultCode() == KeeperException.Code.CONNECTIONLOSS.intValue() ) - { + if (event.getResultCode() == KeeperException.Code.CONNECTIONLOSS.intValue()) { latch.countDown(); } } - } - ) - .forPath(ChaosMonkeyCnxnFactory.CHAOS_ZNODE_PREFIX + "foo-"); + }) + .forPath(ChaosMonkeyCnxnFactory.CHAOS_ZNODE_PREFIX + "foo-"); assertTrue(latch.await(30, TimeUnit.SECONDS), "Callback has not been called"); // Wait for the znode to be deleted Thread.sleep(ChaosMonkeyCnxnFactory.LOCKOUT_DURATION_MS * 2); // Check that there is no znode - final int children = client.getChildren().forPath(ChaosMonkeyCnxnFactory.CHAOS_ZNODE).size(); - assertEquals(children, 0, - "Still " + children + " znodes under " + ChaosMonkeyCnxnFactory.CHAOS_ZNODE + " lock"); - } - finally - { + final int children = client.getChildren() + .forPath(ChaosMonkeyCnxnFactory.CHAOS_ZNODE) + .size(); + assertEquals( + children, 0, "Still " + children + " znodes under " + ChaosMonkeyCnxnFactory.CHAOS_ZNODE + " lock"); + } finally { client.close(); } - } /** * Same test as above but without a retry policy */ @Test - public void createProtectedNodeInBackgroundTestNoRetry() throws Exception - { - final CuratorFramework client = - CuratorFrameworkFactory.builder() + public void createProtectedNodeInBackgroundTestNoRetry() throws Exception { + final CuratorFramework client = CuratorFrameworkFactory.builder() .connectString(server.getConnectString()) .retryPolicy(new RetryNTimes(0, 0)) .connectionTimeoutMs(1000) @@ -219,40 +186,32 @@ public void createProtectedNodeInBackgroundTestNoRetry() throws Exception .build(); final CountDownLatch latch = new CountDownLatch(1); client.start(); - try - { + try { client.create().forPath(ChaosMonkeyCnxnFactory.CHAOS_ZNODE); client.create() - .withProtection() - .withMode(CreateMode.EPHEMERAL_SEQUENTIAL) - .inBackground( - new BackgroundCallback() - { - public void processResult(CuratorFramework client, CuratorEvent event) - throws Exception - { + .withProtection() + .withMode(CreateMode.EPHEMERAL_SEQUENTIAL) + .inBackground(new BackgroundCallback() { + public void processResult(CuratorFramework client, CuratorEvent event) throws Exception { log.info("Receive event {}", event.toString()); - if ( event.getResultCode() == KeeperException.Code.CONNECTIONLOSS.intValue() ) - { + if (event.getResultCode() == KeeperException.Code.CONNECTIONLOSS.intValue()) { latch.countDown(); } } - } - ) - .forPath(ChaosMonkeyCnxnFactory.CHAOS_ZNODE_PREFIX + "foo-"); + }) + .forPath(ChaosMonkeyCnxnFactory.CHAOS_ZNODE_PREFIX + "foo-"); assertTrue(latch.await(30, TimeUnit.SECONDS), "Callback has not been called"); // Wait for the znode to be deleted Thread.sleep(ChaosMonkeyCnxnFactory.LOCKOUT_DURATION_MS * 2); // Check that there is no znode - final int children = client.getChildren().forPath(ChaosMonkeyCnxnFactory.CHAOS_ZNODE).size(); - assertEquals(children, 0, - "Still " + children + " znodes under " + ChaosMonkeyCnxnFactory.CHAOS_ZNODE + " lock"); - } - finally - { + final int children = client.getChildren() + .forPath(ChaosMonkeyCnxnFactory.CHAOS_ZNODE) + .size(); + assertEquals( + children, 0, "Still " + children + " znodes under " + ChaosMonkeyCnxnFactory.CHAOS_ZNODE + " lock"); + } finally { client.close(); } - } } diff --git a/curator-recipes/src/test/java/org/apache/curator/framework/recipes/leader/TestLeaderSelectorParticipants.java b/curator-recipes/src/test/java/org/apache/curator/framework/recipes/leader/TestLeaderSelectorParticipants.java index 34b62ba23..cce616a8a 100644 --- a/curator-recipes/src/test/java/org/apache/curator/framework/recipes/leader/TestLeaderSelectorParticipants.java +++ b/curator-recipes/src/test/java/org/apache/curator/framework/recipes/leader/TestLeaderSelectorParticipants.java @@ -24,45 +24,37 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import com.google.common.collect.Lists; import com.google.common.collect.Sets; -import org.apache.curator.test.BaseClassForTests; -import org.apache.curator.utils.CloseableUtils; -import org.apache.curator.framework.CuratorFramework; -import org.apache.curator.framework.CuratorFrameworkFactory; -import org.apache.curator.framework.state.ConnectionState; -import org.apache.curator.retry.RetryOneTime; -import org.junit.jupiter.api.Test; - import java.util.Collection; import java.util.List; import java.util.Set; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; +import org.apache.curator.framework.CuratorFramework; +import org.apache.curator.framework.CuratorFrameworkFactory; +import org.apache.curator.framework.state.ConnectionState; +import org.apache.curator.retry.RetryOneTime; +import org.apache.curator.test.BaseClassForTests; +import org.apache.curator.utils.CloseableUtils; +import org.junit.jupiter.api.Test; -public class TestLeaderSelectorParticipants extends BaseClassForTests -{ +public class TestLeaderSelectorParticipants extends BaseClassForTests { @Test - public void testId() throws Exception - { - LeaderSelector selector = null; - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); - try - { + public void testId() throws Exception { + LeaderSelector selector = null; + CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); + try { client.start(); - final CountDownLatch latch = new CountDownLatch(1); - LeaderSelectorListener listener = new LeaderSelectorListener() - { + final CountDownLatch latch = new CountDownLatch(1); + LeaderSelectorListener listener = new LeaderSelectorListener() { @Override - public void takeLeadership(CuratorFramework client) throws Exception - { + public void takeLeadership(CuratorFramework client) throws Exception { latch.countDown(); Thread.currentThread().join(); } @Override - public void stateChanged(CuratorFramework client, ConnectionState newState) - { - } + public void stateChanged(CuratorFramework client, ConnectionState newState) {} }; selector = new LeaderSelector(client, "/ls", listener); selector.setId("A is A"); @@ -74,53 +66,42 @@ public void stateChanged(CuratorFramework client, ConnectionState newState) assertTrue(leader.isLeader()); assertEquals(leader.getId(), "A is A"); - Collection participants = selector.getParticipants(); + Collection participants = selector.getParticipants(); assertEquals(participants.size(), 1); assertEquals(participants.iterator().next().getId(), "A is A"); assertEquals(participants.iterator().next().getId(), selector.getId()); - } - finally - { + } finally { CloseableUtils.closeQuietly(selector); CloseableUtils.closeQuietly(client); } } @Test - public void testBasic() throws Exception - { - final int SELECTOR_QTY = 10; - - List selectors = Lists.newArrayList(); - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); - try - { + public void testBasic() throws Exception { + final int SELECTOR_QTY = 10; + + List selectors = Lists.newArrayList(); + CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); + try { client.start(); - final CountDownLatch leaderLatch = new CountDownLatch(1); - final CountDownLatch workingLatch = new CountDownLatch(SELECTOR_QTY); - LeaderSelectorListener listener = new LeaderSelectorListener() - { + final CountDownLatch leaderLatch = new CountDownLatch(1); + final CountDownLatch workingLatch = new CountDownLatch(SELECTOR_QTY); + LeaderSelectorListener listener = new LeaderSelectorListener() { @Override - public void takeLeadership(CuratorFramework client) throws Exception - { + public void takeLeadership(CuratorFramework client) throws Exception { leaderLatch.countDown(); Thread.currentThread().join(); } @Override - public void stateChanged(CuratorFramework client, ConnectionState newState) - { - } + public void stateChanged(CuratorFramework client, ConnectionState newState) {} }; - for ( int i = 0; i < SELECTOR_QTY; ++i ) - { - LeaderSelector selector = new LeaderSelector(client, "/ls", listener) - { + for (int i = 0; i < SELECTOR_QTY; ++i) { + LeaderSelector selector = new LeaderSelector(client, "/ls", listener) { @Override - void doWork() throws Exception - { + void doWork() throws Exception { workingLatch.countDown(); super.doWork(); } @@ -129,28 +110,24 @@ void doWork() throws Exception selectors.add(selector); } - for ( LeaderSelector selector : selectors ) - { + for (LeaderSelector selector : selectors) { selector.start(); } assertTrue(leaderLatch.await(10, TimeUnit.SECONDS)); assertTrue(workingLatch.await(10, TimeUnit.SECONDS)); - + Thread.sleep(1000); // some time for locks to acquire - Collection participants = selectors.get(0).getParticipants(); - for ( int i = 1; i < selectors.size(); ++i ) - { + Collection participants = selectors.get(0).getParticipants(); + for (int i = 1; i < selectors.size(); ++i) { assertEquals(participants, selectors.get(i).getParticipants()); } - Set ids = Sets.newHashSet(); - int leaderCount = 0; - for ( Participant participant : participants ) - { - if ( participant.isLeader() ) - { + Set ids = Sets.newHashSet(); + int leaderCount = 0; + for (Participant participant : participants) { + if (participant.isLeader()) { ++leaderCount; } assertFalse(ids.contains(participant.getId())); @@ -158,17 +135,13 @@ void doWork() throws Exception } assertEquals(leaderCount, 1); - Set expectedIds = Sets.newHashSet(); - for ( int i = 0; i < SELECTOR_QTY; ++i ) - { + Set expectedIds = Sets.newHashSet(); + for (int i = 0; i < SELECTOR_QTY; ++i) { expectedIds.add(Integer.toString(i)); } assertEquals(expectedIds, ids); - } - finally - { - for ( LeaderSelector selector : selectors ) - { + } finally { + for (LeaderSelector selector : selectors) { CloseableUtils.closeQuietly(selector); } CloseableUtils.closeQuietly(client); diff --git a/curator-recipes/src/test/java/org/apache/curator/framework/recipes/leader/TestLeaderSelectorWithExecutor.java b/curator-recipes/src/test/java/org/apache/curator/framework/recipes/leader/TestLeaderSelectorWithExecutor.java index f0673c923..8d30ce127 100644 --- a/curator-recipes/src/test/java/org/apache/curator/framework/recipes/leader/TestLeaderSelectorWithExecutor.java +++ b/curator-recipes/src/test/java/org/apache/curator/framework/recipes/leader/TestLeaderSelectorWithExecutor.java @@ -20,39 +20,34 @@ package org.apache.curator.framework.recipes.leader; import static org.junit.jupiter.api.Assertions.assertEquals; - -import org.apache.curator.test.BaseClassForTests; -import org.apache.curator.utils.CloseableUtils; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.ThreadFactory; +import java.util.concurrent.atomic.AtomicInteger; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.state.ConnectionState; import org.apache.curator.retry.ExponentialBackoffRetry; +import org.apache.curator.test.BaseClassForTests; import org.apache.curator.test.Timing; +import org.apache.curator.utils.CloseableUtils; import org.apache.curator.utils.ThreadUtils; import org.junit.jupiter.api.Test; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.ThreadFactory; -import java.util.concurrent.atomic.AtomicInteger; - -public class TestLeaderSelectorWithExecutor extends BaseClassForTests -{ +public class TestLeaderSelectorWithExecutor extends BaseClassForTests { private static final ThreadFactory threadFactory = ThreadUtils.newThreadFactory("FeedGenerator"); @Test - public void test() throws Exception - { + public void test() throws Exception { Timing timing = new Timing(); LeaderSelector leaderSelector = null; CuratorFramework client = CuratorFrameworkFactory.builder() - .retryPolicy(new ExponentialBackoffRetry(100, 3)) - .connectString(server.getConnectString()) - .sessionTimeoutMs(timing.session()) - .connectionTimeoutMs(timing.connection()) - .build(); - try - { + .retryPolicy(new ExponentialBackoffRetry(100, 3)) + .connectString(server.getConnectString()) + .sessionTimeoutMs(timing.session()) + .connectionTimeoutMs(timing.connection()) + .build(); + try { client.start(); MyLeaderSelectorListener listener = new MyLeaderSelectorListener(); @@ -65,53 +60,39 @@ public void test() throws Exception timing.sleepABit(); assertEquals(listener.getLeaderCount(), 1); - } - finally - { + } finally { CloseableUtils.closeQuietly(leaderSelector); CloseableUtils.closeQuietly(client); } } - private class MyLeaderSelectorListener implements LeaderSelectorListener - { + private class MyLeaderSelectorListener implements LeaderSelectorListener { private volatile Thread ourThread; private final AtomicInteger leaderCount = new AtomicInteger(0); - public int getLeaderCount() - { + public int getLeaderCount() { return leaderCount.get(); } @Override - public void takeLeadership(CuratorFramework curatorFramework) throws Exception - { + public void takeLeadership(CuratorFramework curatorFramework) throws Exception { ourThread = Thread.currentThread(); - try - { + try { leaderCount.incrementAndGet(); - while ( !Thread.currentThread().isInterrupted() ) - { + while (!Thread.currentThread().isInterrupted()) { Thread.sleep(1000); } - } - catch ( InterruptedException e ) - { + } catch (InterruptedException e) { Thread.currentThread().interrupt(); - } - finally - { + } finally { leaderCount.decrementAndGet(); } } @Override - public void stateChanged(CuratorFramework curatorFramework, ConnectionState newState) - { - if ( (newState == ConnectionState.LOST) || (newState == ConnectionState.SUSPENDED) ) - { - if ( ourThread != null ) - { + public void stateChanged(CuratorFramework curatorFramework, ConnectionState newState) { + if ((newState == ConnectionState.LOST) || (newState == ConnectionState.SUSPENDED)) { + if (ourThread != null) { ourThread.interrupt(); } } diff --git a/curator-recipes/src/test/java/org/apache/curator/framework/recipes/locks/Counter.java b/curator-recipes/src/test/java/org/apache/curator/framework/recipes/locks/Counter.java index 0c03fa43d..c99ee0f3d 100644 --- a/curator-recipes/src/test/java/org/apache/curator/framework/recipes/locks/Counter.java +++ b/curator-recipes/src/test/java/org/apache/curator/framework/recipes/locks/Counter.java @@ -19,8 +19,7 @@ package org.apache.curator.framework.recipes.locks; -class Counter -{ - int currentCount = 0; - int maxCount = 0; +class Counter { + int currentCount = 0; + int maxCount = 0; } diff --git a/curator-recipes/src/test/java/org/apache/curator/framework/recipes/locks/SemaphoreClient.java b/curator-recipes/src/test/java/org/apache/curator/framework/recipes/locks/SemaphoreClient.java index 948ed946f..fee6390df 100644 --- a/curator-recipes/src/test/java/org/apache/curator/framework/recipes/locks/SemaphoreClient.java +++ b/curator-recipes/src/test/java/org/apache/curator/framework/recipes/locks/SemaphoreClient.java @@ -19,20 +19,19 @@ package org.apache.curator.framework.recipes.locks; -import org.apache.curator.utils.CloseableUtils; +import java.io.Closeable; +import java.io.IOException; +import java.util.concurrent.Callable; +import java.util.concurrent.atomic.AtomicReference; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.state.ConnectionState; import org.apache.curator.framework.state.ConnectionStateListener; import org.apache.curator.retry.ExponentialBackoffRetry; import org.apache.curator.test.Timing; -import java.io.Closeable; -import java.io.IOException; -import java.util.concurrent.Callable; -import java.util.concurrent.atomic.AtomicReference; +import org.apache.curator.utils.CloseableUtils; -class SemaphoreClient implements Callable, ConnectionStateListener, Closeable -{ +class SemaphoreClient implements Callable, ConnectionStateListener, Closeable { private final CuratorFramework client; private final String semaphorePath; private final Callable operation; @@ -43,12 +42,12 @@ class SemaphoreClient implements Callable, ConnectionStateListener, Closea private static final int CLIENT_EXCEPTION_HANDLER_SLEEP_TIME_SECS = 10; private static final int MAX_SEMAPHORE_LEASES = 1; - private static final AtomicReference activeClient = new AtomicReference(null); + private static final AtomicReference activeClient = new AtomicReference(null); - SemaphoreClient(String connectionString, String semaphorePath, Callable operation) throws IOException - { + SemaphoreClient(String connectionString, String semaphorePath, Callable operation) throws IOException { Timing timing = new Timing(); - this.client = CuratorFrameworkFactory.newClient(connectionString, timing.session(), timing.connection(), new ExponentialBackoffRetry(100, 3)); + this.client = CuratorFrameworkFactory.newClient( + connectionString, timing.session(), timing.connection(), new ExponentialBackoffRetry(100, 3)); client.start(); this.semaphorePath = semaphorePath; @@ -56,95 +55,69 @@ class SemaphoreClient implements Callable, ConnectionStateListener, Closea } @Override - public void close() throws IOException - { + public void close() throws IOException { shouldRun = false; } - boolean hasAcquired() - { + boolean hasAcquired() { return hasAcquired; } @Override - public void stateChanged(CuratorFramework client, ConnectionState newState) - { + public void stateChanged(CuratorFramework client, ConnectionState newState) { hasAcquired = false; } - static SemaphoreClient getActiveClient() - { + static SemaphoreClient getActiveClient() { return activeClient.get(); } @Override - public Void call() throws Exception - { + public Void call() throws Exception { shouldRun = true; client.getConnectionStateListenable().addListener(this); - try - { - while ( shouldRun ) - { - try - { + try { + while (shouldRun) { + try { acquireAndRun(); - } - catch ( InterruptedException e ) - { + } catch (InterruptedException e) { Thread.currentThread().interrupt(); // propagate up, don't sleep throw e; - } - catch ( Exception e ) - { + } catch (Exception e) { Thread.sleep(CLIENT_EXCEPTION_HANDLER_SLEEP_TIME_SECS * 1000L); } } - } - catch ( InterruptedException e ) - { + } catch (InterruptedException e) { Thread.currentThread().interrupt(); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } return null; } - private void acquireAndRun() throws Exception - { + private void acquireAndRun() throws Exception { InterProcessSemaphoreV2 semaphore = new InterProcessSemaphoreV2(client, semaphorePath, MAX_SEMAPHORE_LEASES); Lease lease = semaphore.acquire(); - try - { + try { hasAcquired = true; - if ( activeClient.compareAndSet(null, this) ) - { + if (activeClient.compareAndSet(null, this)) { throw new Exception("Multiple acquirers"); } - try - { - while ( hasAcquired && shouldRun ) - { + try { + while (hasAcquired && shouldRun) { operation.call(); } - } - finally - { - if ( activeClient.compareAndSet(this, null) ) - { + } finally { + if (activeClient.compareAndSet(this, null)) { //noinspection ThrowFromFinallyBlock throw new Exception("Bad release"); } } - } - finally - { + } finally { semaphore.returnLease(lease); } } diff --git a/curator-recipes/src/test/java/org/apache/curator/framework/recipes/locks/Stepper.java b/curator-recipes/src/test/java/org/apache/curator/framework/recipes/locks/Stepper.java index a6c5c2052..8e7936d0f 100644 --- a/curator-recipes/src/test/java/org/apache/curator/framework/recipes/locks/Stepper.java +++ b/curator-recipes/src/test/java/org/apache/curator/framework/recipes/locks/Stepper.java @@ -19,22 +19,18 @@ package org.apache.curator.framework.recipes.locks; -class Stepper -{ - private int available = 0; +class Stepper { + private int available = 0; - synchronized void await() throws InterruptedException - { - while ( available == 0 ) - { + synchronized void await() throws InterruptedException { + while (available == 0) { wait(); } --available; notifyAll(); } - synchronized void countDown(int qty) - { + synchronized void countDown(int qty) { available += qty; notifyAll(); } diff --git a/curator-recipes/src/test/java/org/apache/curator/framework/recipes/locks/TestInterProcessMultiMutex.java b/curator-recipes/src/test/java/org/apache/curator/framework/recipes/locks/TestInterProcessMultiMutex.java index d353a57ef..13a3bed66 100644 --- a/curator-recipes/src/test/java/org/apache/curator/framework/recipes/locks/TestInterProcessMultiMutex.java +++ b/curator-recipes/src/test/java/org/apache/curator/framework/recipes/locks/TestInterProcessMultiMutex.java @@ -22,140 +22,111 @@ import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; - +import java.io.IOException; +import java.util.Arrays; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.imps.TestCleanState; import org.apache.curator.retry.RetryOneTime; import org.junit.jupiter.api.Test; -import java.io.IOException; -import java.util.Arrays; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicBoolean; - -public class TestInterProcessMultiMutex extends TestInterProcessMutexBase -{ - private static final String LOCK_PATH_1 = LOCK_BASE_PATH + "/our-lock-1"; - private static final String LOCK_PATH_2 = LOCK_BASE_PATH + "/our-lock-2"; +public class TestInterProcessMultiMutex extends TestInterProcessMutexBase { + private static final String LOCK_PATH_1 = LOCK_BASE_PATH + "/our-lock-1"; + private static final String LOCK_PATH_2 = LOCK_BASE_PATH + "/our-lock-2"; @Override - protected InterProcessLock makeLock(CuratorFramework client) - { + protected InterProcessLock makeLock(CuratorFramework client) { return new InterProcessMultiLock(client, Arrays.asList(LOCK_PATH_1, LOCK_PATH_2)); } @Test - public void testSomeReleasesFail() throws IOException - { + public void testSomeReleasesFail() throws IOException { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client.start(); - try - { - InterProcessLock goodLock = new InterProcessMutex(client, LOCK_PATH_1); - final InterProcessLock otherGoodLock = new InterProcessMutex(client, LOCK_PATH_2); - InterProcessLock badLock = new InterProcessLock() - { + try { + InterProcessLock goodLock = new InterProcessMutex(client, LOCK_PATH_1); + final InterProcessLock otherGoodLock = new InterProcessMutex(client, LOCK_PATH_2); + InterProcessLock badLock = new InterProcessLock() { @Override - public void acquire() throws Exception - { + public void acquire() throws Exception { otherGoodLock.acquire(); } @Override - public boolean acquire(long time, TimeUnit unit) throws Exception - { + public boolean acquire(long time, TimeUnit unit) throws Exception { return otherGoodLock.acquire(time, unit); } @Override - public void release() throws Exception - { + public void release() throws Exception { throw new Exception("foo"); } @Override - public boolean isAcquiredInThisProcess() - { + public boolean isAcquiredInThisProcess() { return otherGoodLock.isAcquiredInThisProcess(); } }; - InterProcessMultiLock lock = new InterProcessMultiLock(Arrays.asList(goodLock, badLock)); - try - { + InterProcessMultiLock lock = new InterProcessMultiLock(Arrays.asList(goodLock, badLock)); + try { lock.acquire(); lock.release(); fail(); - } - catch ( Exception e ) - { + } catch (Exception e) { // ignore } assertFalse(goodLock.isAcquiredInThisProcess()); assertTrue(otherGoodLock.isAcquiredInThisProcess()); - } - finally - { + } finally { TestCleanState.closeAndTestClean(client); } } @Test - public void testSomeLocksFailToLock() throws IOException - { + public void testSomeLocksFailToLock() throws IOException { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client.start(); - try - { - final AtomicBoolean goodLockWasLocked = new AtomicBoolean(false); - final InterProcessLock goodLock = new InterProcessMutex(client, LOCK_PATH_1); - InterProcessLock badLock = new InterProcessLock() - { + try { + final AtomicBoolean goodLockWasLocked = new AtomicBoolean(false); + final InterProcessLock goodLock = new InterProcessMutex(client, LOCK_PATH_1); + InterProcessLock badLock = new InterProcessLock() { @Override - public void acquire() throws Exception - { - if ( goodLock.isAcquiredInThisProcess() ) - { + public void acquire() throws Exception { + if (goodLock.isAcquiredInThisProcess()) { goodLockWasLocked.set(true); } throw new Exception("foo"); } @Override - public boolean acquire(long time, TimeUnit unit) throws Exception - { + public boolean acquire(long time, TimeUnit unit) throws Exception { throw new Exception("foo"); } @Override - public void release() throws Exception - { + public void release() throws Exception { throw new Exception("foo"); } @Override - public boolean isAcquiredInThisProcess() - { + public boolean isAcquiredInThisProcess() { return false; } }; - InterProcessMultiLock lock = new InterProcessMultiLock(Arrays.asList(goodLock, badLock)); - try - { + InterProcessMultiLock lock = new InterProcessMultiLock(Arrays.asList(goodLock, badLock)); + try { lock.acquire(); fail(); - } - catch ( Exception e ) - { + } catch (Exception e) { // ignore } assertFalse(goodLock.isAcquiredInThisProcess()); assertTrue(goodLockWasLocked.get()); - } - finally - { + } finally { TestCleanState.closeAndTestClean(client); } } diff --git a/curator-recipes/src/test/java/org/apache/curator/framework/recipes/locks/TestInterProcessMutex.java b/curator-recipes/src/test/java/org/apache/curator/framework/recipes/locks/TestInterProcessMutex.java index 2a15a5f78..fedd6a555 100644 --- a/curator-recipes/src/test/java/org/apache/curator/framework/recipes/locks/TestInterProcessMutex.java +++ b/curator-recipes/src/test/java/org/apache/curator/framework/recipes/locks/TestInterProcessMutex.java @@ -20,10 +20,17 @@ package org.apache.curator.framework.recipes.locks; import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; import com.google.common.collect.Lists; +import java.util.Collection; +import java.util.concurrent.Callable; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.imps.TestCleanState; @@ -34,55 +41,40 @@ import org.apache.zookeeper.CreateMode; import org.junit.jupiter.api.Test; -import java.util.Collection; -import java.util.concurrent.Callable; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; -import java.util.concurrent.TimeUnit; - -public class TestInterProcessMutex extends TestInterProcessMutexBase -{ +public class TestInterProcessMutex extends TestInterProcessMutexBase { private static final String LOCK_PATH = LOCK_BASE_PATH + "/our-lock"; @Override - protected InterProcessLock makeLock(CuratorFramework client) - { + protected InterProcessLock makeLock(CuratorFramework client) { return new InterProcessMutex(client, LOCK_PATH); } @Test - public void testWithSchema() throws Exception - { + public void testWithSchema() throws Exception { Schema schemaRoot = Schema.builderForRecipeParent("/foo").name("root").build(); Schema schemaLocks = Schema.builderForRecipe("/foo").name("locks").build(); SchemaSet schemaSet = new SchemaSet(Lists.newArrayList(schemaRoot, schemaLocks), false); CuratorFramework client = CuratorFrameworkFactory.builder() - .connectString(server.getConnectString()) - .retryPolicy(new RetryOneTime(1)) - .schemaSet(schemaSet) - .build(); - try - { + .connectString(server.getConnectString()) + .retryPolicy(new RetryOneTime(1)) + .schemaSet(schemaSet) + .build(); + try { client.start(); InterProcessMutex lock = new InterProcessMutex(client, "/foo"); lock.acquire(); lock.release(); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } @Test - public void testRevoking() throws Exception - { - final CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); - try - { + public void testRevoking() throws Exception { + final CuratorFramework client = + CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); + try { client.start(); final InterProcessMutex lock = new InterProcessMutex(client, LOCK_PATH); @@ -90,81 +82,70 @@ public void testRevoking() throws Exception final CountDownLatch revokeLatch = new CountDownLatch(1); final CountDownLatch lockLatch = new CountDownLatch(1); - Future f1 = executorService.submit - ( - new Callable() - { + Future f1 = executorService.submit(new Callable() { + @Override + public Void call() throws Exception { + RevocationListener listener = new RevocationListener() { @Override - public Void call() throws Exception - { - RevocationListener listener = new RevocationListener() - { - @Override - public void revocationRequested(InterProcessMutex lock) - { - revokeLatch.countDown(); - } - }; - lock.makeRevocable(listener); - lock.acquire(); - lockLatch.countDown(); - revokeLatch.await(); - lock.release(); - return null; + public void revocationRequested(InterProcessMutex lock) { + revokeLatch.countDown(); } - } - ); + }; + lock.makeRevocable(listener); + lock.acquire(); + lockLatch.countDown(); + revokeLatch.await(); + lock.release(); + return null; + } + }); - Future f2 = executorService.submit - ( - new Callable() - { - @Override - public Void call() throws Exception - { - assertTrue(lockLatch.await(10, TimeUnit.SECONDS)); - Collection nodes = lock.getParticipantNodes(); - assertEquals(nodes.size(), 1); - Revoker.attemptRevoke(client, nodes.iterator().next()); - - InterProcessMutex l2 = new InterProcessMutex(client, LOCK_PATH); - assertTrue(l2.acquire(5, TimeUnit.SECONDS)); - l2.release(); - return null; - } - } - ); + Future f2 = executorService.submit(new Callable() { + @Override + public Void call() throws Exception { + assertTrue(lockLatch.await(10, TimeUnit.SECONDS)); + Collection nodes = lock.getParticipantNodes(); + assertEquals(nodes.size(), 1); + Revoker.attemptRevoke(client, nodes.iterator().next()); + + InterProcessMutex l2 = new InterProcessMutex(client, LOCK_PATH); + assertTrue(l2.acquire(5, TimeUnit.SECONDS)); + l2.release(); + return null; + } + }); f2.get(); f1.get(); - } - finally - { + } finally { TestCleanState.closeAndTestClean(client); } } @Test - public void testPersistentLock() throws Exception - { - final CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); + public void testPersistentLock() throws Exception { + final CuratorFramework client = + CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client.start(); - try - { - final InterProcessMutex lock = new InterProcessMutex(client, LOCK_PATH, new StandardLockInternalsDriver() - { + try { + final InterProcessMutex lock = new InterProcessMutex(client, LOCK_PATH, new StandardLockInternalsDriver() { @Override - public String createsTheLock(CuratorFramework client, String path, byte[] lockNodeBytes) throws Exception - { + public String createsTheLock(CuratorFramework client, String path, byte[] lockNodeBytes) + throws Exception { String ourPath; - if ( lockNodeBytes != null ) - { - ourPath = client.create().creatingParentsIfNeeded().withProtection().withMode(CreateMode.PERSISTENT).forPath(path, lockNodeBytes); - } - else - { - ourPath = client.create().creatingParentsIfNeeded().withProtection().withMode(CreateMode.PERSISTENT).forPath(path); + if (lockNodeBytes != null) { + ourPath = client.create() + .creatingParentsIfNeeded() + .withProtection() + .withMode(CreateMode.PERSISTENT) + .forPath(path, lockNodeBytes); + } else { + ourPath = client.create() + .creatingParentsIfNeeded() + .withProtection() + .withMode(CreateMode.PERSISTENT) + .forPath(path); } return ourPath; } @@ -182,9 +163,7 @@ public String createsTheLock(CuratorFramework client, String path, byte[] lockNo String actualLockPath = lock.getLockPath(); lock.release(); assertNull(client.checkExists().forPath(actualLockPath)); - } - finally - { + } finally { TestCleanState.closeAndTestClean(client); } } diff --git a/curator-recipes/src/test/java/org/apache/curator/framework/recipes/locks/TestInterProcessMutexBase.java b/curator-recipes/src/test/java/org/apache/curator/framework/recipes/locks/TestInterProcessMutexBase.java index 6dfe4c921..92cf397f8 100644 --- a/curator-recipes/src/test/java/org/apache/curator/framework/recipes/locks/TestInterProcessMutexBase.java +++ b/curator-recipes/src/test/java/org/apache/curator/framework/recipes/locks/TestInterProcessMutexBase.java @@ -25,6 +25,17 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; import com.google.common.collect.Lists; +import java.util.List; +import java.util.concurrent.Callable; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorCompletionService; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.Semaphore; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicReference; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.state.ConnectionState; @@ -39,20 +50,7 @@ import org.apache.zookeeper.KeeperException; import org.junit.jupiter.api.Test; -import java.util.List; -import java.util.concurrent.Callable; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.ExecutorCompletionService; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; -import java.util.concurrent.Semaphore; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicReference; - -public abstract class TestInterProcessMutexBase extends BaseClassForTests -{ +public abstract class TestInterProcessMutexBase extends BaseClassForTests { protected static final String LOCK_BASE_PATH = "/locks"; private volatile CountDownLatch waitLatchForBar = null; @@ -61,44 +59,36 @@ public abstract class TestInterProcessMutexBase extends BaseClassForTests protected abstract InterProcessLock makeLock(CuratorFramework client); @Test - public void testLocker() throws Exception - { + public void testLocker() throws Exception { final Timing timing = new Timing(); - final CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new ExponentialBackoffRetry(100, 3)); - try - { + final CuratorFramework client = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), timing.connection(), new ExponentialBackoffRetry(100, 3)); + try { client.start(); InterProcessLock lock = makeLock(client); - try ( Locker locker = new Locker(lock, timing.milliseconds(), TimeUnit.MILLISECONDS) ) - { + try (Locker locker = new Locker(lock, timing.milliseconds(), TimeUnit.MILLISECONDS)) { assertTrue(lock.isAcquiredInThisProcess()); } assertFalse(lock.isAcquiredInThisProcess()); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } @Test - public void testWaitingProcessKilledServer() throws Exception - { + public void testWaitingProcessKilledServer() throws Exception { final Timing timing = new Timing(); - final CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new ExponentialBackoffRetry(100, 3)); - try - { + final CuratorFramework client = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), timing.connection(), new ExponentialBackoffRetry(100, 3)); + try { client.start(); final CountDownLatch latch = new CountDownLatch(1); - ConnectionStateListener listener = new ConnectionStateListener() - { + ConnectionStateListener listener = new ConnectionStateListener() { @Override - public void stateChanged(CuratorFramework client, ConnectionState newState) - { - if ( !newState.isConnected() ) - { + public void stateChanged(CuratorFramework client, ConnectionState newState) { + if (!newState.isConnected()) { latch.countDown(); } } @@ -107,116 +97,87 @@ public void stateChanged(CuratorFramework client, ConnectionState newState) final AtomicBoolean isFirst = new AtomicBoolean(true); final Object result = new Object(); - ExecutorCompletionService service = new ExecutorCompletionService(Executors.newFixedThreadPool(2)); - for ( int i = 0; i < 2; ++i ) - { - service.submit - ( - new Callable() - { - @Override - public Object call() throws Exception - { - InterProcessLock lock = makeLock(client); - lock.acquire(); - try - { - if ( isFirst.compareAndSet(true, false) ) - { - timing.sleepABit(); - - server.stop(); - assertTrue(timing.forWaiting().awaitLatch(latch)); - server.restart(); - } + ExecutorCompletionService service = + new ExecutorCompletionService(Executors.newFixedThreadPool(2)); + for (int i = 0; i < 2; ++i) { + service.submit(new Callable() { + @Override + public Object call() throws Exception { + InterProcessLock lock = makeLock(client); + lock.acquire(); + try { + if (isFirst.compareAndSet(true, false)) { + timing.sleepABit(); + + server.stop(); + assertTrue(timing.forWaiting().awaitLatch(latch)); + server.restart(); } - finally - { - try - { - lock.release(); - } - catch ( KeeperException.SessionExpiredException dummy ) - { - // happens sometimes with a few tests - ignore - } + } finally { + try { + lock.release(); + } catch (KeeperException.SessionExpiredException dummy) { + // happens sometimes with a few tests - ignore } - return result; } + return result; } - ); + }); } - for ( int i = 0; i < 2; ++i ) - { + for (int i = 0; i < 2; ++i) { assertEquals(service.take().get(timing.forWaiting().milliseconds(), TimeUnit.MILLISECONDS), result); } - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } @Test - public void testKilledSession() throws Exception - { + public void testKilledSession() throws Exception { final Timing2 timing = new Timing2(); - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new ExponentialBackoffRetry(100, 3)); + CuratorFramework client = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), timing.connection(), new ExponentialBackoffRetry(100, 3)); client.start(); - try - { + try { final InterProcessLock mutex1 = makeLock(client); final InterProcessLock mutex2 = makeLock(client); final Semaphore semaphore = new Semaphore(0); - ExecutorCompletionService service = new ExecutorCompletionService(Executors.newFixedThreadPool(2)); - service.submit - ( - new Callable() - { - @Override - public Object call() throws Exception - { - mutex1.acquire(); - semaphore.release(); - Thread.sleep(1000000); - return null; - } - } - ); + ExecutorCompletionService service = + new ExecutorCompletionService(Executors.newFixedThreadPool(2)); + service.submit(new Callable() { + @Override + public Object call() throws Exception { + mutex1.acquire(); + semaphore.release(); + Thread.sleep(1000000); + return null; + } + }); - service.submit - ( - new Callable() - { - @Override - public Object call() throws Exception - { - mutex2.acquire(); - semaphore.release(); - Thread.sleep(1000000); - return null; - } - } - ); + service.submit(new Callable() { + @Override + public Object call() throws Exception { + mutex2.acquire(); + semaphore.release(); + Thread.sleep(1000000); + return null; + } + }); assertTrue(timing.acquireSemaphore(semaphore, 1)); client.getZookeeperClient().getZooKeeper().getTestable().injectSessionExpiration(); assertTrue(timing.forSessionSleep().acquireSemaphore(semaphore, 1)); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } @Test - public void testContainerCleanup() throws Exception - { - if ( !ZKPaths.hasContainerSupport() ) - { + public void testContainerCleanup() throws Exception { + if (!ZKPaths.hasContainerSupport()) { System.out.println("ZooKeeper version does not support Containers. Skipping test"); return; } @@ -224,101 +185,80 @@ public void testContainerCleanup() throws Exception server.close(); System.setProperty("znode.container.checkIntervalMs", "10"); - try - { + try { server = new TestingServer(); final int THREAD_QTY = 10; ExecutorService service = null; - final CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new ExponentialBackoffRetry(100, 3)); - try - { + final CuratorFramework client = + CuratorFrameworkFactory.newClient(server.getConnectString(), new ExponentialBackoffRetry(100, 3)); + try { client.start(); List> threads = Lists.newArrayList(); service = Executors.newCachedThreadPool(); - for ( int i = 0; i < THREAD_QTY; ++i ) - { - Future t = service.submit - ( - new Callable() - { - @Override - public Object call() throws Exception - { - InterProcessLock lock = makeLock(client); - lock.acquire(); - try - { - Thread.sleep(10); - } - finally - { - lock.release(); - } - return null; + for (int i = 0; i < THREAD_QTY; ++i) { + Future t = service.submit(new Callable() { + @Override + public Object call() throws Exception { + InterProcessLock lock = makeLock(client); + lock.acquire(); + try { + Thread.sleep(10); + } finally { + lock.release(); } + return null; } - ); + }); threads.add(t); } - for ( Future t : threads ) - { + for (Future t : threads) { t.get(); } new Timing().sleepABit(); assertNull(client.checkExists().forPath(LOCK_BASE_PATH)); - } - finally - { - if ( service != null ) - { + } finally { + if (service != null) { service.shutdownNow(); } CloseableUtils.closeQuietly(client); } - } - finally - { + } finally { System.clearProperty("znode.container.checkIntervalMs"); } } @Test - public void testWithNamespace() throws Exception - { - CuratorFramework client = CuratorFrameworkFactory.builder(). - connectString(server.getConnectString()). - retryPolicy(new ExponentialBackoffRetry(100, 3)). - namespace("test"). - build(); + public void testWithNamespace() throws Exception { + CuratorFramework client = CuratorFrameworkFactory.builder() + .connectString(server.getConnectString()) + .retryPolicy(new ExponentialBackoffRetry(100, 3)) + .namespace("test") + .build(); client.start(); - try - { + try { InterProcessLock mutex = makeLock(client); mutex.acquire(10, TimeUnit.SECONDS); Thread.sleep(100); mutex.release(); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } @Test - public void testReentrantSingleLock() throws Exception - { + public void testReentrantSingleLock() throws Exception { final int THREAD_QTY = 10; - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new ExponentialBackoffRetry(100, 3)); + CuratorFramework client = + CuratorFrameworkFactory.newClient(server.getConnectString(), new ExponentialBackoffRetry(100, 3)); client.start(); - try - { + try { final AtomicBoolean hasLock = new AtomicBoolean(false); final AtomicBoolean isFirst = new AtomicBoolean(true); final Semaphore semaphore = new Semaphore(1); @@ -326,121 +266,88 @@ public void testReentrantSingleLock() throws Exception List> threads = Lists.newArrayList(); ExecutorService service = Executors.newCachedThreadPool(); - for ( int i = 0; i < THREAD_QTY; ++i ) - { - Future t = service.submit - ( - new Callable() - { - @Override - public Object call() throws Exception - { - semaphore.acquire(); - mutex.acquire(); - try - { - assertTrue(hasLock.compareAndSet(false, true)); - if ( isFirst.compareAndSet(true, false) ) - { - semaphore.release(THREAD_QTY - 1); - while ( semaphore.availablePermits() > 0 ) - { - Thread.sleep(100); - } - } - else - { - Thread.sleep(100); - } - } - finally - { - mutex.release(); - hasLock.set(false); + for (int i = 0; i < THREAD_QTY; ++i) { + Future t = service.submit(new Callable() { + @Override + public Object call() throws Exception { + semaphore.acquire(); + mutex.acquire(); + try { + assertTrue(hasLock.compareAndSet(false, true)); + if (isFirst.compareAndSet(true, false)) { + semaphore.release(THREAD_QTY - 1); + while (semaphore.availablePermits() > 0) { + Thread.sleep(100); } - return null; + } else { + Thread.sleep(100); } + } finally { + mutex.release(); + hasLock.set(false); } - ); + return null; + } + }); threads.add(t); } - for ( Future t : threads ) - { + for (Future t : threads) { t.get(); } - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } @Test - public void testReentrant2Threads() throws Exception - { - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new ExponentialBackoffRetry(100, 3)); + public void testReentrant2Threads() throws Exception { + CuratorFramework client = + CuratorFrameworkFactory.newClient(server.getConnectString(), new ExponentialBackoffRetry(100, 3)); client.start(); - try - { + try { waitLatchForBar = new CountDownLatch(1); countLatchForBar = new CountDownLatch(1); final InterProcessLock mutex = makeLock(client); - Executors.newSingleThreadExecutor().submit - ( - new Callable() - { - @Override - public Object call() throws Exception - { - assertTrue(countLatchForBar.await(10, TimeUnit.SECONDS)); - try - { - mutex.acquire(10, TimeUnit.SECONDS); - fail(); - } - catch ( Exception e ) - { - // correct - } - finally - { - waitLatchForBar.countDown(); - } - return null; - } + Executors.newSingleThreadExecutor().submit(new Callable() { + @Override + public Object call() throws Exception { + assertTrue(countLatchForBar.await(10, TimeUnit.SECONDS)); + try { + mutex.acquire(10, TimeUnit.SECONDS); + fail(); + } catch (Exception e) { + // correct + } finally { + waitLatchForBar.countDown(); } - ); + return null; + } + }); foo(mutex); assertFalse(mutex.isAcquiredInThisProcess()); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } @Test - public void testReentrant() throws Exception - { - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new ExponentialBackoffRetry(100, 3)); + public void testReentrant() throws Exception { + CuratorFramework client = + CuratorFrameworkFactory.newClient(server.getConnectString(), new ExponentialBackoffRetry(100, 3)); client.start(); - try - { + try { InterProcessLock mutex = makeLock(client); foo(mutex); assertFalse(mutex.isAcquiredInThisProcess()); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } - private void foo(InterProcessLock mutex) throws Exception - { + private void foo(InterProcessLock mutex) throws Exception { mutex.acquire(10, TimeUnit.SECONDS); assertTrue(mutex.isAcquiredInThisProcess()); bar(mutex); @@ -448,12 +355,10 @@ private void foo(InterProcessLock mutex) throws Exception mutex.release(); } - private void bar(InterProcessLock mutex) throws Exception - { + private void bar(InterProcessLock mutex) throws Exception { mutex.acquire(10, TimeUnit.SECONDS); assertTrue(mutex.isAcquiredInThisProcess()); - if ( countLatchForBar != null ) - { + if (countLatchForBar != null) { countLatchForBar.countDown(); waitLatchForBar.await(10, TimeUnit.SECONDS); } @@ -462,8 +367,7 @@ private void bar(InterProcessLock mutex) throws Exception mutex.release(); } - private void snafu(InterProcessLock mutex) throws Exception - { + private void snafu(InterProcessLock mutex) throws Exception { mutex.acquire(10, TimeUnit.SECONDS); assertTrue(mutex.isAcquiredInThisProcess()); mutex.release(); @@ -471,12 +375,10 @@ private void snafu(InterProcessLock mutex) throws Exception } @Test - public void test2Clients() throws Exception - { + public void test2Clients() throws Exception { CuratorFramework client1 = null; CuratorFramework client2 = null; - try - { + try { client1 = CuratorFrameworkFactory.newClient(server.getConnectString(), new ExponentialBackoffRetry(100, 3)); client2 = CuratorFrameworkFactory.newClient(server.getConnectString(), new ExponentialBackoffRetry(100, 3)); client1.start(); @@ -493,53 +395,36 @@ public void test2Clients() throws Exception final AtomicReference exceptionRef = new AtomicReference(); ExecutorService service = Executors.newCachedThreadPool(); - Future future1 = service.submit - ( - new Callable() - { - @Override - public Object call() throws Exception - { - try - { - mutexForClient1.acquire(10, TimeUnit.SECONDS); - acquiredLatchForClient1.countDown(); - latchForClient1.await(10, TimeUnit.SECONDS); - mutexForClient1.release(); - } - catch ( Exception e ) - { - exceptionRef.set(e); - } - return null; - } + Future future1 = service.submit(new Callable() { + @Override + public Object call() throws Exception { + try { + mutexForClient1.acquire(10, TimeUnit.SECONDS); + acquiredLatchForClient1.countDown(); + latchForClient1.await(10, TimeUnit.SECONDS); + mutexForClient1.release(); + } catch (Exception e) { + exceptionRef.set(e); } - ); - Future future2 = service.submit - ( - new Callable() - { - @Override - public Object call() throws Exception - { - try - { - mutexForClient2.acquire(10, TimeUnit.SECONDS); - acquiredLatchForClient2.countDown(); - latchForClient2.await(10, TimeUnit.SECONDS); - mutexForClient2.release(); - } - catch ( Exception e ) - { - exceptionRef.set(e); - } - return null; - } + return null; + } + }); + Future future2 = service.submit(new Callable() { + @Override + public Object call() throws Exception { + try { + mutexForClient2.acquire(10, TimeUnit.SECONDS); + acquiredLatchForClient2.countDown(); + latchForClient2.await(10, TimeUnit.SECONDS); + mutexForClient2.release(); + } catch (Exception e) { + exceptionRef.set(e); } - ); + return null; + } + }); - while ( !mutexForClient1.isAcquiredInThisProcess() && !mutexForClient2.isAcquiredInThisProcess() ) - { + while (!mutexForClient1.isAcquiredInThisProcess() && !mutexForClient2.isAcquiredInThisProcess()) { Thread.sleep(1000); assertFalse(future1.isDone() && future2.isDone()); } @@ -550,19 +435,15 @@ public Object call() throws Exception assertTrue(mutexForClient1.isAcquiredInThisProcess() != mutexForClient2.isAcquiredInThisProcess()); Exception exception = exceptionRef.get(); - if ( exception != null ) - { + if (exception != null) { throw exception; } - if ( mutexForClient1.isAcquiredInThisProcess() ) - { + if (mutexForClient1.isAcquiredInThisProcess()) { latchForClient1.countDown(); assertTrue(acquiredLatchForClient2.await(10, TimeUnit.SECONDS)); assertTrue(mutexForClient2.isAcquiredInThisProcess()); - } - else - { + } else { latchForClient2.countDown(); assertTrue(acquiredLatchForClient1.await(10, TimeUnit.SECONDS)); assertTrue(mutexForClient1.isAcquiredInThisProcess()); @@ -570,9 +451,7 @@ public Object call() throws Exception future1.get(); future2.get(); - } - finally - { + } finally { CloseableUtils.closeQuietly(client1); CloseableUtils.closeQuietly(client2); } diff --git a/curator-recipes/src/test/java/org/apache/curator/framework/recipes/locks/TestInterProcessReadWriteLock.java b/curator-recipes/src/test/java/org/apache/curator/framework/recipes/locks/TestInterProcessReadWriteLock.java index f1dbe456a..690270bc6 100644 --- a/curator-recipes/src/test/java/org/apache/curator/framework/recipes/locks/TestInterProcessReadWriteLock.java +++ b/curator-recipes/src/test/java/org/apache/curator/framework/recipes/locks/TestInterProcessReadWriteLock.java @@ -27,15 +27,6 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; import com.google.common.collect.Lists; -import org.apache.curator.framework.CuratorFramework; -import org.apache.curator.framework.CuratorFrameworkFactory; -import org.apache.curator.framework.imps.TestCleanState; -import org.apache.curator.retry.RetryOneTime; -import org.apache.curator.test.BaseClassForTests; -import org.apache.curator.test.KillSession; -import org.apache.zookeeper.KeeperException; -import org.junit.jupiter.api.Test; - import java.util.Collection; import java.util.List; import java.util.Random; @@ -48,18 +39,23 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicInteger; +import org.apache.curator.framework.CuratorFramework; +import org.apache.curator.framework.CuratorFrameworkFactory; +import org.apache.curator.framework.imps.TestCleanState; +import org.apache.curator.retry.RetryOneTime; +import org.apache.curator.test.BaseClassForTests; +import org.apache.curator.test.KillSession; +import org.apache.zookeeper.KeeperException; +import org.junit.jupiter.api.Test; -public class TestInterProcessReadWriteLock extends BaseClassForTests -{ +public class TestInterProcessReadWriteLock extends BaseClassForTests { @Test - public void testGetParticipantNodes() throws Exception - { + public void testGetParticipantNodes() throws Exception { final int READERS = 20; final int WRITERS = 8; CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); - try - { + try { client.start(); final CountDownLatch latch = new CountDownLatch(READERS + WRITERS); @@ -67,56 +63,39 @@ public void testGetParticipantNodes() throws Exception final InterProcessReadWriteLock lock = new InterProcessReadWriteLock(client, "/lock"); final CountDownLatch exitLatch = new CountDownLatch(1); - ExecutorCompletionService service = new ExecutorCompletionService(Executors.newCachedThreadPool()); - for ( int i = 0; i < READERS; ++i ) - { - service.submit - ( - new Callable() - { - @Override - public Void call() throws Exception - { - lock.readLock().acquire(); - try - { - latch.countDown(); - readLatch.countDown(); - exitLatch.await(); - } - finally - { - lock.readLock().release(); - } - return null; + ExecutorCompletionService service = + new ExecutorCompletionService(Executors.newCachedThreadPool()); + for (int i = 0; i < READERS; ++i) { + service.submit(new Callable() { + @Override + public Void call() throws Exception { + lock.readLock().acquire(); + try { + latch.countDown(); + readLatch.countDown(); + exitLatch.await(); + } finally { + lock.readLock().release(); } + return null; } - ); + }); } - for ( int i = 0; i < WRITERS; ++i ) - { - service.submit - ( - new Callable() - { - @Override - public Void call() throws Exception - { - assertTrue(readLatch.await(10, TimeUnit.SECONDS)); - latch.countDown(); // must be before as there can only be one writer - lock.writeLock().acquire(); - try - { - exitLatch.await(); - } - finally - { - lock.writeLock().release(); - } - return null; + for (int i = 0; i < WRITERS; ++i) { + service.submit(new Callable() { + @Override + public Void call() throws Exception { + assertTrue(readLatch.await(10, TimeUnit.SECONDS)); + latch.countDown(); // must be before as there can only be one writer + lock.writeLock().acquire(); + try { + exitLatch.await(); + } finally { + lock.writeLock().release(); } + return null; } - ); + }); } assertTrue(latch.await(10, TimeUnit.SECONDS)); @@ -128,23 +107,18 @@ public Void call() throws Exception assertEquals(writers.size(), WRITERS); exitLatch.countDown(); - for ( int i = 0; i < (READERS + WRITERS); ++i ) - { + for (int i = 0; i < (READERS + WRITERS); ++i) { service.take().get(); } - } - finally - { + } finally { TestCleanState.closeAndTestClean(client); } } @Test - public void testThatUpgradingIsDisallowed() throws Exception - { + public void testThatUpgradingIsDisallowed() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); - try - { + try { client.start(); InterProcessReadWriteLock lock = new InterProcessReadWriteLock(client, "/lock"); @@ -152,19 +126,15 @@ public void testThatUpgradingIsDisallowed() throws Exception assertFalse(lock.writeLock().acquire(5, TimeUnit.SECONDS)); lock.readLock().release(); - } - finally - { + } finally { TestCleanState.closeAndTestClean(client); } } @Test - public void testThatDowngradingRespectsThreads() throws Exception - { + public void testThatDowngradingRespectsThreads() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); - try - { + try { client.start(); final InterProcessReadWriteLock lock = new InterProcessReadWriteLock(client, "/lock"); @@ -174,58 +144,41 @@ public void testThatDowngradingRespectsThreads() throws Exception final CountDownLatch latch = new CountDownLatch(1); final CountDownLatch releaseLatch = new CountDownLatch(1); - Future f1 = t1.submit - ( - new Callable() - { - @Override - public Object call() throws Exception - { - lock.writeLock().acquire(); - latch.countDown(); - try - { - releaseLatch.await(); - } - finally - { - lock.writeLock().release(); - } - return null; - } + Future f1 = t1.submit(new Callable() { + @Override + public Object call() throws Exception { + lock.writeLock().acquire(); + latch.countDown(); + try { + releaseLatch.await(); + } finally { + lock.writeLock().release(); } - ); - - Future f2 = t2.submit - ( - new Callable() - { - @Override - public Object call() throws Exception - { - assertTrue(latch.await(10, TimeUnit.SECONDS)); - assertFalse(lock.readLock().acquire(5, TimeUnit.SECONDS)); - return null; - } - } - ); + return null; + } + }); + + Future f2 = t2.submit(new Callable() { + @Override + public Object call() throws Exception { + assertTrue(latch.await(10, TimeUnit.SECONDS)); + assertFalse(lock.readLock().acquire(5, TimeUnit.SECONDS)); + return null; + } + }); f2.get(); releaseLatch.countDown(); f1.get(); - } - finally - { + } finally { TestCleanState.closeAndTestClean(client); } } @Test - public void testDowngrading() throws Exception - { + public void testDowngrading() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); - try - { + try { client.start(); InterProcessReadWriteLock lock = new InterProcessReadWriteLock(client, "/lock"); @@ -234,20 +187,16 @@ public void testDowngrading() throws Exception lock.writeLock().release(); lock.readLock().release(); - } - finally - { + } finally { TestCleanState.closeAndTestClean(client); } } @Test - public void testContendingDowngrading() throws Exception - { + public void testContendingDowngrading() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); ExecutorService executor = Executors.newCachedThreadPool(); - try - { + try { client.start(); InterProcessReadWriteLock lock1 = new InterProcessReadWriteLock(client, "/lock"); @@ -274,17 +223,14 @@ public void testContendingDowngrading() throws Exception // Let lock2 have chance to respond to write-release writeAcquire.get(20, TimeUnit.MILLISECONDS); }); - } - finally - { + } finally { TestCleanState.closeAndTestClean(client); executor.shutdown(); } } @Test - public void testBasic() throws Exception - { + public void testBasic() throws Exception { final int CONCURRENCY = 8; final int ITERATIONS = 100; @@ -296,51 +242,44 @@ public void testBasic() throws Exception List> futures = Lists.newArrayList(); ExecutorService service = Executors.newCachedThreadPool(); - for ( int i = 0; i < CONCURRENCY; ++i ) - { - Future future = service.submit - ( - new Callable() - { - @Override - public Void call() throws Exception - { - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); - client.start(); - try - { - InterProcessReadWriteLock lock = new InterProcessReadWriteLock(client, "/lock"); - for ( int i = 0; i < ITERATIONS; ++i ) - { - if ( random.nextInt(100) < 10 ) - { - doLocking(lock.writeLock(), concurrentCount, maxConcurrentCount, random, 1); - writeCount.incrementAndGet(); - } - else - { - doLocking(lock.readLock(), concurrentCount, maxConcurrentCount, random, Integer.MAX_VALUE); - readCount.incrementAndGet(); - } - } - } - finally - { - TestCleanState.closeAndTestClean(client); + for (int i = 0; i < CONCURRENCY; ++i) { + Future future = service.submit(new Callable() { + @Override + public Void call() throws Exception { + CuratorFramework client = + CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); + client.start(); + try { + InterProcessReadWriteLock lock = new InterProcessReadWriteLock(client, "/lock"); + for (int i = 0; i < ITERATIONS; ++i) { + if (random.nextInt(100) < 10) { + doLocking(lock.writeLock(), concurrentCount, maxConcurrentCount, random, 1); + writeCount.incrementAndGet(); + } else { + doLocking( + lock.readLock(), + concurrentCount, + maxConcurrentCount, + random, + Integer.MAX_VALUE); + readCount.incrementAndGet(); } - return null; } + } finally { + TestCleanState.closeAndTestClean(client); } - ); + return null; + } + }); futures.add(future); } - for ( Future future : futures ) - { + for (Future future : futures) { future.get(); } - System.out.println("Writes: " + writeCount.get() + " - Reads: " + readCount.get() + " - Max Reads: " + maxConcurrentCount.get()); + System.out.println("Writes: " + writeCount.get() + " - Reads: " + readCount.get() + " - Max Reads: " + + maxConcurrentCount.get()); assertTrue(writeCount.get() > 0); assertTrue(readCount.get() > 0); @@ -348,15 +287,13 @@ public Void call() throws Exception } @Test - public void testSetNodeData() throws Exception - { + public void testSetNodeData() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); - try - { + try { client.start(); - final byte[] nodeData = new byte[]{1, 2, 3, 4}; + final byte[] nodeData = new byte[] {1, 2, 3, 4}; InterProcessReadWriteLock lock = new InterProcessReadWriteLock(client, "/lock", nodeData); @@ -370,27 +307,27 @@ public void testSetNodeData() throws Exception byte dataInZk[] = client.getData().forPath("/lock/" + children.get(0)); assertNotNull(dataInZk); - assertArrayEquals(new byte[]{1, 2, 3, 4}, dataInZk); + assertArrayEquals(new byte[] {1, 2, 3, 4}, dataInZk); lock.writeLock().release(); - } - finally - { + } finally { TestCleanState.closeAndTestClean(client); } } - private void doLocking(InterProcessLock lock, AtomicInteger concurrentCount, AtomicInteger maxConcurrentCount, Random random, int maxAllowed) throws Exception - { - try - { + private void doLocking( + InterProcessLock lock, + AtomicInteger concurrentCount, + AtomicInteger maxConcurrentCount, + Random random, + int maxAllowed) + throws Exception { + try { assertTrue(lock.acquire(10, TimeUnit.SECONDS)); int localConcurrentCount; - synchronized(this) - { + synchronized (this) { localConcurrentCount = concurrentCount.incrementAndGet(); - if ( localConcurrentCount > maxConcurrentCount.get() ) - { + if (localConcurrentCount > maxConcurrentCount.get()) { maxConcurrentCount.set(localConcurrentCount); } } @@ -398,11 +335,8 @@ private void doLocking(InterProcessLock lock, AtomicInteger concurrentCount, Ato assertTrue(localConcurrentCount <= maxAllowed, "" + localConcurrentCount); Thread.sleep(random.nextInt(9) + 1); - } - finally - { - synchronized(this) - { + } finally { + synchronized (this) { concurrentCount.decrementAndGet(); lock.release(); } @@ -410,12 +344,10 @@ private void doLocking(InterProcessLock lock, AtomicInteger concurrentCount, Ato } @Test - public void testLockPath() throws Exception - { + public void testLockPath() throws Exception { CuratorFramework client1 = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); CuratorFramework client2 = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); - try - { + try { client1.start(); client2.start(); InterProcessReadWriteLock lock1 = new InterProcessReadWriteLock(client1, "/lock"); @@ -430,9 +362,7 @@ public void testLockPath() throws Exception } lock2.readLock().release(); lock1.writeLock().release(); - } - finally - { + } finally { TestCleanState.closeAndTestClean(client2); TestCleanState.closeAndTestClean(client1); } diff --git a/curator-recipes/src/test/java/org/apache/curator/framework/recipes/locks/TestInterProcessSemaphore.java b/curator-recipes/src/test/java/org/apache/curator/framework/recipes/locks/TestInterProcessSemaphore.java index 9cba32d3f..226b91c49 100644 --- a/curator-recipes/src/test/java/org/apache/curator/framework/recipes/locks/TestInterProcessSemaphore.java +++ b/curator-recipes/src/test/java/org/apache/curator/framework/recipes/locks/TestInterProcessSemaphore.java @@ -26,6 +26,19 @@ import static org.junit.jupiter.api.Assertions.fail; import com.google.common.collect.Lists; import com.google.common.collect.Queues; +import java.util.Collection; +import java.util.List; +import java.util.Random; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.Callable; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorCompletionService; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.concurrent.atomic.AtomicInteger; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.api.CuratorWatcher; @@ -42,26 +55,10 @@ import org.apache.zookeeper.Watcher; import org.junit.jupiter.api.Test; -import java.util.Collection; -import java.util.List; -import java.util.Random; -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.Callable; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.ExecutorCompletionService; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; -import java.util.concurrent.atomic.AtomicInteger; - @SuppressWarnings({"SynchronizationOnLocalVariableOrMethodParameter"}) -public class TestInterProcessSemaphore extends BaseClassForTests -{ +public class TestInterProcessSemaphore extends BaseClassForTests { @Test - public void testAcquireAfterLostServer() throws Exception - { + public void testAcquireAfterLostServer() throws Exception { // CURATOR-335 final String SEMAPHORE_PATH = "/test"; @@ -72,64 +69,53 @@ public void testAcquireAfterLostServer() throws Exception final Timing timing = new Timing(); - final CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.forWaiting().milliseconds(), timing.connection(), new RetryOneTime(1)); // long session time on purpose - try - { + final CuratorFramework client = CuratorFrameworkFactory.newClient( + server.getConnectString(), + timing.forWaiting().milliseconds(), + timing.connection(), + new RetryOneTime(1)); // long session time on purpose + try { client.start(); - InterProcessSemaphoreV2.debugAcquireLatch = new CountDownLatch(1); // cause one of the semaphores to create its node and then wait - InterProcessSemaphoreV2.debugFailedGetChildrenLatch = new CountDownLatch(1); // semaphore will notify when getChildren() fails + InterProcessSemaphoreV2.debugAcquireLatch = + new CountDownLatch(1); // cause one of the semaphores to create its node and then wait + InterProcessSemaphoreV2.debugFailedGetChildrenLatch = + new CountDownLatch(1); // semaphore will notify when getChildren() fails final CountDownLatch isReadyLatch = new CountDownLatch(NUM_CLIENTS); final BlockingQueue acquiredQueue = Queues.newLinkedBlockingQueue(); - Runnable runner = new Runnable() - { + Runnable runner = new Runnable() { @Override - public void run() - { - while ( !Thread.currentThread().isInterrupted() ) - { - InterProcessSemaphoreV2 semaphore = new InterProcessSemaphoreV2(client, SEMAPHORE_PATH, MAX_SEMAPHORES); + public void run() { + while (!Thread.currentThread().isInterrupted()) { + InterProcessSemaphoreV2 semaphore = + new InterProcessSemaphoreV2(client, SEMAPHORE_PATH, MAX_SEMAPHORES); Lease lease = null; - try - { + try { isReadyLatch.countDown(); lease = semaphore.acquire(); acquiredQueue.add(true); timing.sleepABit(); - } - catch ( InterruptedException e ) - { + } catch (InterruptedException e) { Thread.currentThread().interrupt(); break; - } - catch ( KeeperException e ) - { - try - { + } catch (KeeperException e) { + try { timing.sleepABit(); - } - catch ( InterruptedException e2 ) - { + } catch (InterruptedException e2) { Thread.currentThread().interrupt(); break; } - } - catch ( Exception ignore ) - { + } catch (Exception ignore) { // ignore - } - finally - { - if ( lease != null ) - { + } finally { + if (lease != null) { semaphore.returnLease(lease); } } } } }; - for ( int i = 0; i < NUM_CLIENTS; ++i ) - { + for (int i = 0; i < NUM_CLIENTS; ++i) { executor.execute(runner); } assertTrue(timing.awaitLatch(isReadyLatch)); @@ -137,54 +123,46 @@ public void run() final CountDownLatch lostLatch = new CountDownLatch(1); final CountDownLatch restartedLatch = new CountDownLatch(1); - client.getConnectionStateListenable().addListener(new ConnectionStateListener() - { + client.getConnectionStateListenable().addListener(new ConnectionStateListener() { @Override - public void stateChanged(CuratorFramework client, ConnectionState newState) - { - if ( newState == ConnectionState.LOST ) - { + public void stateChanged(CuratorFramework client, ConnectionState newState) { + if (newState == ConnectionState.LOST) { lostLatch.countDown(); - } - else if ( newState == ConnectionState.RECONNECTED ) - { + } else if (newState == ConnectionState.RECONNECTED) { restartedLatch.countDown(); } } }); - + server.stop(); assertTrue(timing.multiple(1.25).awaitLatch(lostLatch)); - InterProcessSemaphoreV2.debugAcquireLatch.countDown(); // the waiting semaphore proceeds to getChildren - which should fail - assertTrue(timing.awaitLatch(InterProcessSemaphoreV2.debugFailedGetChildrenLatch)); // wait until getChildren fails + InterProcessSemaphoreV2.debugAcquireLatch + .countDown(); // the waiting semaphore proceeds to getChildren - which should fail + assertTrue(timing.awaitLatch( + InterProcessSemaphoreV2.debugFailedGetChildrenLatch)); // wait until getChildren fails server.restart(); assertTrue(timing.awaitLatch(restartedLatch)); - for ( int i = 0; i < NUM_CLIENTS; ++i ) - { + for (int i = 0; i < NUM_CLIENTS; ++i) { // acquires should continue as normal after server restart Boolean polled = acquiredQueue.poll(timing.forWaiting().milliseconds(), TimeUnit.MILLISECONDS); - if ( (polled == null) || !polled ) - { + if ((polled == null) || !polled) { fail("Semaphores not reacquired after restart"); } } - } - finally - { + } finally { executor.shutdownNow(); CloseableUtils.closeQuietly(client); } } @Test - public void testThreadedLeaseIncrease() throws Exception - { + public void testThreadedLeaseIncrease() throws Exception { final Timing timing = new Timing(); - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); - try - { + CuratorFramework client = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); + try { client.start(); final SharedCount count = new SharedCount(client, "/foo/count", 1); @@ -196,64 +174,52 @@ public void testThreadedLeaseIncrease() throws Exception final CountDownLatch latch1 = new CountDownLatch(1); final CountDownLatch latch2 = new CountDownLatch(1); - Future future1 = service.submit - ( - new Callable() - { - @Override - public Object call() throws Exception - { - Lease lease = semaphore.acquire(timing.seconds(), TimeUnit.SECONDS); - assertNotNull(lease); - latch1.countDown(); - lease = semaphore.acquire(timing.forWaiting().seconds(), TimeUnit.SECONDS); - assertNotNull(lease); - latch2.countDown(); - return null; - } - } - ); - Future future2 = service.submit - ( - new Callable() - { - @Override - public Object call() throws Exception - { - assertTrue(latch1.await(timing.forWaiting().seconds(), TimeUnit.SECONDS)); - timing.sleepABit(); // make sure second acquire is waiting - assertTrue(count.trySetCount(2)); - //Make sure second acquire takes less than full waiting time: - timing.sleepABit(); - assertTrue(latch2.await(0, TimeUnit.SECONDS)); - return null; - } - } - ); + Future future1 = service.submit(new Callable() { + @Override + public Object call() throws Exception { + Lease lease = semaphore.acquire(timing.seconds(), TimeUnit.SECONDS); + assertNotNull(lease); + latch1.countDown(); + lease = semaphore.acquire(timing.forWaiting().seconds(), TimeUnit.SECONDS); + assertNotNull(lease); + latch2.countDown(); + return null; + } + }); + Future future2 = service.submit(new Callable() { + @Override + public Object call() throws Exception { + assertTrue(latch1.await(timing.forWaiting().seconds(), TimeUnit.SECONDS)); + timing.sleepABit(); // make sure second acquire is waiting + assertTrue(count.trySetCount(2)); + // Make sure second acquire takes less than full waiting time: + timing.sleepABit(); + assertTrue(latch2.await(0, TimeUnit.SECONDS)); + return null; + } + }); future1.get(); future2.get(); count.close(); - } - finally - { + } finally { TestCleanState.closeAndTestClean(client); } } @Test - public void testClientClose() throws Exception - { + public void testClientClose() throws Exception { final Timing timing = new Timing(); CuratorFramework client1 = null; CuratorFramework client2 = null; InterProcessSemaphoreV2 semaphore1; InterProcessSemaphoreV2 semaphore2; - try - { - client1 = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); - client2 = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); + try { + client1 = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); + client2 = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); client1.start(); client2.start(); @@ -268,21 +234,18 @@ public void testClientClose() throws Exception lease = semaphore1.acquire(10, TimeUnit.SECONDS); assertNotNull(lease); - client1.close(); // should release any held leases + client1.close(); // should release any held leases client1 = null; assertNotNull(semaphore2.acquire(timing.forWaiting().seconds(), TimeUnit.SECONDS)); - } - finally - { + } finally { TestCleanState.closeAndTestClean(client1); TestCleanState.closeAndTestClean(client2); } } @Test - public void testMaxPerSession() throws Exception - { + public void testMaxPerSession() throws Exception { final int CLIENT_QTY = 10; final int LOOP_QTY = 100; final Random random = new Random(); @@ -293,90 +256,67 @@ public void testMaxPerSession() throws Exception ExecutorService service = Executors.newCachedThreadPool(); final Counter counter = new Counter(); final AtomicInteger available = new AtomicInteger(SESSION_MAX); - for ( int i = 0; i < CLIENT_QTY; ++i ) - { - futures.add - ( - service.submit - ( - new Callable() - { - @Override - public Object call() throws Exception - { - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); - client.start(); - try - { - InterProcessSemaphoreV2 semaphore = new InterProcessSemaphoreV2(client, "/test", SESSION_MAX); - - for ( int i = 0; i < LOOP_QTY; ++i ) - { - long start = System.currentTimeMillis(); - int thisQty; - synchronized(available) - { - if ( (System.currentTimeMillis() - start) > 10000 ) - { - throw new TimeoutException(); - } - while ( available.get() == 0 ) - { - available.wait(timing.forWaiting().milliseconds()); - } - - thisQty = (available.get() > 1) ? (random.nextInt(available.get()) + 1) : 1; - - available.addAndGet(-1 * thisQty); - assertTrue(available.get() >= 0); - } - Collection leases = semaphore.acquire(thisQty, timing.forWaiting().seconds(), TimeUnit.SECONDS); - assertNotNull(leases); - try - { - synchronized(counter) - { - counter.currentCount += thisQty; - if ( counter.currentCount > counter.maxCount ) - { - counter.maxCount = counter.currentCount; - } - } - Thread.sleep(random.nextInt(25)); - } - finally - { - synchronized(counter) - { - counter.currentCount -= thisQty; - } - semaphore.returnAll(leases); - synchronized(available) - { - available.addAndGet(thisQty); - available.notifyAll(); - } - } - } - } - finally - { - TestCleanState.closeAndTestClean(client); + for (int i = 0; i < CLIENT_QTY; ++i) { + futures.add(service.submit(new Callable() { + @Override + public Object call() throws Exception { + CuratorFramework client = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); + client.start(); + try { + InterProcessSemaphoreV2 semaphore = new InterProcessSemaphoreV2(client, "/test", SESSION_MAX); + + for (int i = 0; i < LOOP_QTY; ++i) { + long start = System.currentTimeMillis(); + int thisQty; + synchronized (available) { + if ((System.currentTimeMillis() - start) > 10000) { + throw new TimeoutException(); + } + while (available.get() == 0) { + available.wait(timing.forWaiting().milliseconds()); + } + + thisQty = (available.get() > 1) ? (random.nextInt(available.get()) + 1) : 1; + + available.addAndGet(-1 * thisQty); + assertTrue(available.get() >= 0); + } + Collection leases = semaphore.acquire( + thisQty, timing.forWaiting().seconds(), TimeUnit.SECONDS); + assertNotNull(leases); + try { + synchronized (counter) { + counter.currentCount += thisQty; + if (counter.currentCount > counter.maxCount) { + counter.maxCount = counter.currentCount; } - return null; + } + Thread.sleep(random.nextInt(25)); + } finally { + synchronized (counter) { + counter.currentCount -= thisQty; + } + semaphore.returnAll(leases); + synchronized (available) { + available.addAndGet(thisQty); + available.notifyAll(); } } - ) - ); + } + } finally { + TestCleanState.closeAndTestClean(client); + } + return null; + } + })); } - for ( Future f : futures ) - { + for (Future f : futures) { f.get(); } - synchronized(counter) - { + synchronized (counter) { assertTrue(counter.currentCount == 0); assertTrue(counter.maxCount > 0); assertTrue(counter.maxCount <= SESSION_MAX); @@ -385,8 +325,7 @@ public Object call() throws Exception } @Test - public void testRelease1AtATime() throws Exception - { + public void testRelease1AtATime() throws Exception { final Timing timing = new Timing(); final int CLIENT_QTY = 10; final int MAX = CLIENT_QTY / 2; @@ -396,55 +335,41 @@ public void testRelease1AtATime() throws Exception List> futures = Lists.newArrayList(); ExecutorService service = Executors.newFixedThreadPool(CLIENT_QTY); - for ( int i = 0; i < CLIENT_QTY; ++i ) - { - Future f = service.submit - ( - new Callable() - { - @Override - public Object call() throws Exception - { - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); - client.start(); - try - { - InterProcessSemaphoreV2 semaphore = new InterProcessSemaphoreV2(client, "/test", MAX); - Lease lease = semaphore.acquire(timing.forWaiting().seconds(), TimeUnit.SECONDS); - assertNotNull(lease); - uses.incrementAndGet(); - try - { - synchronized(maxLeases) - { - int qty = activeQty.incrementAndGet(); - if ( qty > maxLeases.get() ) - { - maxLeases.set(qty); - } - } - - timing.sleepABit(); - } - finally - { - activeQty.decrementAndGet(); - lease.close(); + for (int i = 0; i < CLIENT_QTY; ++i) { + Future f = service.submit(new Callable() { + @Override + public Object call() throws Exception { + CuratorFramework client = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); + client.start(); + try { + InterProcessSemaphoreV2 semaphore = new InterProcessSemaphoreV2(client, "/test", MAX); + Lease lease = semaphore.acquire(timing.forWaiting().seconds(), TimeUnit.SECONDS); + assertNotNull(lease); + uses.incrementAndGet(); + try { + synchronized (maxLeases) { + int qty = activeQty.incrementAndGet(); + if (qty > maxLeases.get()) { + maxLeases.set(qty); } } - finally - { - TestCleanState.closeAndTestClean(client); - } - return null; + + timing.sleepABit(); + } finally { + activeQty.decrementAndGet(); + lease.close(); } + } finally { + TestCleanState.closeAndTestClean(client); } - ); + return null; + } + }); futures.add(f); } - for ( Future f : futures ) - { + for (Future f : futures) { f.get(); } @@ -453,168 +378,132 @@ public Object call() throws Exception } @Test - public void testReleaseInChunks() throws Exception - { + public void testReleaseInChunks() throws Exception { final Timing timing = new Timing(); final int MAX_LEASES = 11; final int THREADS = 100; - final CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); + final CuratorFramework client = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); client.start(); - try - { + try { final Stepper latch = new Stepper(); final Random random = new Random(); final Counter counter = new Counter(); ExecutorService service = Executors.newCachedThreadPool(); ExecutorCompletionService completionService = new ExecutorCompletionService(service); - for ( int i = 0; i < THREADS; ++i ) - { - completionService.submit - ( - new Callable() - { - @Override - public Object call() throws Exception - { - InterProcessSemaphoreV2 semaphore = new InterProcessSemaphoreV2(client, "/test", MAX_LEASES); - Lease lease = semaphore.acquire(timing.forWaiting().seconds(), TimeUnit.SECONDS); - if ( lease == null ) - { - throw new Exception("timed out"); + for (int i = 0; i < THREADS; ++i) { + completionService.submit(new Callable() { + @Override + public Object call() throws Exception { + InterProcessSemaphoreV2 semaphore = new InterProcessSemaphoreV2(client, "/test", MAX_LEASES); + Lease lease = semaphore.acquire(timing.forWaiting().seconds(), TimeUnit.SECONDS); + if (lease == null) { + throw new Exception("timed out"); + } + try { + synchronized (counter) { + ++counter.currentCount; + if (counter.currentCount > counter.maxCount) { + counter.maxCount = counter.currentCount; } - try - { - synchronized(counter) - { - ++counter.currentCount; - if ( counter.currentCount > counter.maxCount ) - { - counter.maxCount = counter.currentCount; - } - counter.notifyAll(); - } + counter.notifyAll(); + } - latch.await(); - } - finally - { - synchronized(counter) - { - --counter.currentCount; - } - semaphore.returnLease(lease); - } - return null; + latch.await(); + } finally { + synchronized (counter) { + --counter.currentCount; } + semaphore.returnLease(lease); } - ); + return null; + } + }); } int remaining = THREADS; - while ( remaining > 0 ) - { + while (remaining > 0) { int times = Math.min(random.nextInt(5) + 1, remaining); latch.countDown(times); remaining -= times; Thread.sleep(random.nextInt(100) + 1); } - for ( int i = 0; i < THREADS; ++i ) - { + for (int i = 0; i < THREADS; ++i) { completionService.take(); } timing.sleepABit(); - synchronized(counter) - { + synchronized (counter) { assertTrue(counter.currentCount == 0); assertTrue(counter.maxCount > 0); assertTrue(counter.maxCount <= MAX_LEASES); System.out.println(counter.maxCount); } - } - finally - { + } finally { TestCleanState.closeAndTestClean(client); } } @Test - public void testThreads() throws Exception - { + public void testThreads() throws Exception { final int THREAD_QTY = 10; Timing timing = new Timing(); - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); + CuratorFramework client = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); client.start(); - try - { + try { final InterProcessSemaphoreV2 semaphore = new InterProcessSemaphoreV2(client, "/test", 1); ExecutorService service = Executors.newFixedThreadPool(THREAD_QTY); - for ( int i = 0; i < THREAD_QTY; ++i ) - { - service.submit - ( - new Callable() - { - @Override - public Object call() throws Exception - { - Lease lease = semaphore.acquire(); - try - { - Thread.sleep(1); - } - finally - { - lease.close(); - } - return null; - } + for (int i = 0; i < THREAD_QTY; ++i) { + service.submit(new Callable() { + @Override + public Object call() throws Exception { + Lease lease = semaphore.acquire(); + try { + Thread.sleep(1); + } finally { + lease.close(); } - ); + return null; + } + }); } service.shutdown(); assertTrue(service.awaitTermination(10, TimeUnit.SECONDS)); - } - finally - { + } finally { TestCleanState.closeAndTestClean(client); } } @Test - public void testSimple() throws Exception - { + public void testSimple() throws Exception { Timing timing = new Timing(); - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); + CuratorFramework client = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); client.start(); - try - { + try { InterProcessSemaphoreV2 semaphore = new InterProcessSemaphoreV2(client, "/test", 1); assertNotNull(semaphore.acquire(timing.forWaiting().seconds(), TimeUnit.SECONDS)); assertNull(semaphore.acquire(timing.forWaiting().seconds(), TimeUnit.SECONDS)); - } - finally - { + } finally { TestCleanState.closeAndTestClean(client); } } @Test - public void testSimple2() throws Exception - { + public void testSimple2() throws Exception { final int MAX_LEASES = 3; Timing timing = new Timing(); List leases = Lists.newArrayList(); - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); + CuratorFramework client = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); client.start(); - try - { - for ( int i = 0; i < MAX_LEASES; ++i ) - { + try { + for (int i = 0; i < MAX_LEASES; ++i) { InterProcessSemaphoreV2 semaphore = new InterProcessSemaphoreV2(client, "/test", MAX_LEASES); Lease lease = semaphore.acquire(timing.forWaiting().seconds(), TimeUnit.SECONDS); assertNotNull(lease); @@ -627,11 +516,8 @@ public void testSimple2() throws Exception leases.remove(0).close(); assertNotNull(semaphore.acquire(timing.forWaiting().seconds(), TimeUnit.SECONDS)); - } - finally - { - for ( Lease l : leases ) - { + } finally { + for (Lease l : leases) { CloseableUtils.closeQuietly(l); } TestCleanState.closeAndTestClean(client); @@ -639,28 +525,23 @@ public void testSimple2() throws Exception } @Test - public void testGetParticipantNodes() throws Exception - { + public void testGetParticipantNodes() throws Exception { final int LEASES = 3; Timing timing = new Timing(); - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); + CuratorFramework client = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); List leases = Lists.newArrayList(); client.start(); - try - { + try { InterProcessSemaphoreV2 semaphore = new InterProcessSemaphoreV2(client, "/test", LEASES); - for ( int i = 0; i < LEASES; ++i ) - { + for (int i = 0; i < LEASES; ++i) { leases.add(semaphore.acquire()); } assertEquals(semaphore.getParticipantNodes().size(), LEASES); - } - finally - { - for ( Lease l : leases ) - { + } finally { + for (Lease l : leases) { CloseableUtils.closeQuietly(l); } TestCleanState.closeAndTestClean(client); @@ -668,14 +549,13 @@ public void testGetParticipantNodes() throws Exception } @Test - public void testNoOrphanedNodes() throws Exception - { + public void testNoOrphanedNodes() throws Exception { final Timing timing = new Timing(); final ExecutorService executor = Executors.newFixedThreadPool(1); - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); + CuratorFramework client = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); client.start(); - try - { + try { final InterProcessSemaphoreV2 semaphore = new InterProcessSemaphoreV2(client, "/test", 1); Lease lease = semaphore.acquire(timing.forWaiting().seconds(), TimeUnit.SECONDS); assertNotNull(lease); @@ -683,23 +563,20 @@ public void testNoOrphanedNodes() throws Exception assertEquals(childNodes.size(), 1); final CountDownLatch nodeCreatedLatch = new CountDownLatch(1); - client.getChildren().usingWatcher(new CuratorWatcher() - { - @Override - public void process(WatchedEvent event) throws Exception - { - if ( event.getType() == Watcher.Event.EventType.NodeCreated ) - { - nodeCreatedLatch.countDown(); - } - } - }).forPath("/test/leases"); + client.getChildren() + .usingWatcher(new CuratorWatcher() { + @Override + public void process(WatchedEvent event) throws Exception { + if (event.getType() == Watcher.Event.EventType.NodeCreated) { + nodeCreatedLatch.countDown(); + } + } + }) + .forPath("/test/leases"); - final Future leaseFuture = executor.submit(new Callable() - { + final Future leaseFuture = executor.submit(new Callable() { @Override - public Lease call() throws Exception - { + public Lease call() throws Exception { return semaphore.acquire(timing.forWaiting().multiple(2).seconds(), TimeUnit.SECONDS); } }); @@ -707,10 +584,8 @@ public Lease call() throws Exception // wait for second lease to create its node timing.awaitLatch(nodeCreatedLatch); String newNode = null; - for ( String c : client.getChildren().forPath("/test/leases") ) - { - if ( !childNodes.contains(c) ) - { + for (String c : client.getChildren().forPath("/test/leases")) { + if (!childNodes.contains(c)) { newNode = c; } } @@ -728,36 +603,33 @@ public Lease call() throws Exception // no more lease exist. must be possible to acquire a new one assertNotNull(semaphore.acquire(timing.forWaiting().seconds(), TimeUnit.SECONDS)); - } - finally - { + } finally { executor.shutdownNow(); TestCleanState.closeAndTestClean(client); } } - + @Test - public void testInterruptAcquire() throws Exception - { + public void testInterruptAcquire() throws Exception { // CURATOR-462 final Timing timing = new Timing(); - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); + CuratorFramework client = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); client.start(); - try - { + try { final InterProcessSemaphoreV2 s1 = new InterProcessSemaphoreV2(client, "/test", 1); final InterProcessSemaphoreV2 s2 = new InterProcessSemaphoreV2(client, "/test", 1); final InterProcessSemaphoreV2 s3 = new InterProcessSemaphoreV2(client, "/test", 1); - + final CountDownLatch debugWaitLatch = s2.debugWaitLatch = new CountDownLatch(1); - + // Acquire exclusive semaphore Lease lease = s1.acquire(timing.forWaiting().seconds(), TimeUnit.SECONDS); assertNotNull(lease); - + // Queue up another semaphore on the same path Future handle = Executors.newSingleThreadExecutor().submit(new Callable() { - + @Override public Object call() throws Exception { s2.acquire(); @@ -767,20 +639,18 @@ public Object call() throws Exception { // Wait until second lease is created and the wait is started for it to become active assertTrue(timing.awaitLatch(debugWaitLatch)); - + // Interrupt the wait handle.cancel(true); - + // Assert that the second lease is gone timing.sleepABit(); assertEquals(client.getChildren().forPath("/test/leases").size(), 1); - + // Assert that after closing the first (current) semaphore, we can acquire a new one s1.returnLease(lease); assertNotNull(s3.acquire(timing.forWaiting().seconds(), TimeUnit.SECONDS)); - } - finally - { + } finally { TestCleanState.closeAndTestClean(client); } } diff --git a/curator-recipes/src/test/java/org/apache/curator/framework/recipes/locks/TestInterProcessSemaphoreCluster.java b/curator-recipes/src/test/java/org/apache/curator/framework/recipes/locks/TestInterProcessSemaphoreCluster.java index 4a5c2749d..3eadc588e 100644 --- a/curator-recipes/src/test/java/org/apache/curator/framework/recipes/locks/TestInterProcessSemaphoreCluster.java +++ b/curator-recipes/src/test/java/org/apache/curator/framework/recipes/locks/TestInterProcessSemaphoreCluster.java @@ -23,6 +23,18 @@ import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; import com.google.common.collect.Lists; +import java.io.IOException; +import java.util.Iterator; +import java.util.List; +import java.util.concurrent.Callable; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorCompletionService; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Semaphore; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; import org.apache.curator.ensemble.EnsembleProvider; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; @@ -39,138 +51,91 @@ import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; -import java.io.IOException; -import java.util.Iterator; -import java.util.List; -import java.util.concurrent.Callable; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.ExecutorCompletionService; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.Semaphore; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.concurrent.atomic.AtomicReference; - @Tag(CuratorTestBase.zk35TestCompatibilityGroup) -public class TestInterProcessSemaphoreCluster extends BaseClassForTests -{ +public class TestInterProcessSemaphoreCluster extends BaseClassForTests { @Test - public void testKilledServerWithEnsembleProvider() throws Exception - { - final int CLIENT_QTY = 10; - final Timing timing = new Timing(); - final String PATH = "/foo/bar/lock"; + public void testKilledServerWithEnsembleProvider() throws Exception { + final int CLIENT_QTY = 10; + final Timing timing = new Timing(); + final String PATH = "/foo/bar/lock"; - ExecutorService executorService = Executors.newFixedThreadPool(CLIENT_QTY); + ExecutorService executorService = Executors.newFixedThreadPool(CLIENT_QTY); ExecutorCompletionService completionService = new ExecutorCompletionService(executorService); - TestingCluster cluster = createAndStartCluster(3); - try - { - final AtomicReference connectionString = new AtomicReference(cluster.getConnectString()); - final EnsembleProvider provider = new EnsembleProvider() - { + TestingCluster cluster = createAndStartCluster(3); + try { + final AtomicReference connectionString = new AtomicReference(cluster.getConnectString()); + final EnsembleProvider provider = new EnsembleProvider() { @Override - public void setConnectionString(String connectionString) - { - } + public void setConnectionString(String connectionString) {} @Override - public boolean updateServerListEnabled() - { + public boolean updateServerListEnabled() { return false; } @Override - public void start() throws Exception - { - } + public void start() throws Exception {} @Override - public String getConnectionString() - { + public String getConnectionString() { return connectionString.get(); } @Override - public void close() throws IOException - { - } + public void close() throws IOException {} }; - final Semaphore acquiredSemaphore = new Semaphore(0); - final AtomicInteger acquireCount = new AtomicInteger(0); - final CountDownLatch suspendedLatch = new CountDownLatch(CLIENT_QTY); - for ( int i = 0; i < CLIENT_QTY; ++i ) - { - completionService.submit - ( - new Callable() - { - @Override - public Void call() throws Exception - { - CuratorFramework client = CuratorFrameworkFactory.builder() + final Semaphore acquiredSemaphore = new Semaphore(0); + final AtomicInteger acquireCount = new AtomicInteger(0); + final CountDownLatch suspendedLatch = new CountDownLatch(CLIENT_QTY); + for (int i = 0; i < CLIENT_QTY; ++i) { + completionService.submit(new Callable() { + @Override + public Void call() throws Exception { + CuratorFramework client = CuratorFrameworkFactory.builder() .ensembleProvider(provider) .sessionTimeoutMs(timing.session()) .connectionTimeoutMs(timing.connection()) .retryPolicy(new ExponentialBackoffRetry(100, 3)) .build(); - try - { - final Semaphore suspendedSemaphore = new Semaphore(0); - client.getConnectionStateListenable().addListener - ( - new ConnectionStateListener() - { - @Override - public void stateChanged(CuratorFramework client, ConnectionState newState) - { - if ( (newState == ConnectionState.SUSPENDED) || (newState == ConnectionState.LOST) ) - { - suspendedLatch.countDown(); - suspendedSemaphore.release(); - } - } + try { + final Semaphore suspendedSemaphore = new Semaphore(0); + client.getConnectionStateListenable().addListener(new ConnectionStateListener() { + @Override + public void stateChanged(CuratorFramework client, ConnectionState newState) { + if ((newState == ConnectionState.SUSPENDED) || (newState == ConnectionState.LOST)) { + suspendedLatch.countDown(); + suspendedSemaphore.release(); } - ); + } + }); - client.start(); + client.start(); - InterProcessSemaphoreV2 semaphore = new InterProcessSemaphoreV2(client, PATH, 1); + InterProcessSemaphoreV2 semaphore = new InterProcessSemaphoreV2(client, PATH, 1); - while ( !Thread.currentThread().isInterrupted() ) - { - Lease lease = null; - try - { - lease = semaphore.acquire(); - acquiredSemaphore.release(); - acquireCount.incrementAndGet(); - suspendedSemaphore.acquire(); - } - catch ( Exception e ) - { - // just retry - } - finally - { - if ( lease != null ) - { - acquireCount.decrementAndGet(); - CloseableUtils.closeQuietly(lease); - } + while (!Thread.currentThread().isInterrupted()) { + Lease lease = null; + try { + lease = semaphore.acquire(); + acquiredSemaphore.release(); + acquireCount.incrementAndGet(); + suspendedSemaphore.acquire(); + } catch (Exception e) { + // just retry + } finally { + if (lease != null) { + acquireCount.decrementAndGet(); + CloseableUtils.closeQuietly(lease); } } } - finally - { - TestCleanState.closeAndTestClean(client); - } - return null; + } finally { + TestCleanState.closeAndTestClean(client); } + return null; } - ); + }); } assertTrue(timing.acquireSemaphore(acquiredSemaphore)); @@ -189,9 +154,7 @@ public void stateChanged(CuratorFramework client, ConnectionState newState) assertTrue(timing.acquireSemaphore(acquiredSemaphore)); timing.forWaiting().sleepABit(); assertEquals(1, acquireCount.get()); - } - finally - { + } finally { executorService.shutdown(); executorService.awaitTermination(10, TimeUnit.SECONDS); executorService.shutdownNow(); @@ -200,37 +163,28 @@ public void stateChanged(CuratorFramework client, ConnectionState newState) } @Test - public void testCluster() throws Exception - { - final int QTY = 20; - final int OPERATION_TIME_MS = 1000; - final String PATH = "/foo/bar/lock"; + public void testCluster() throws Exception { + final int QTY = 20; + final int OPERATION_TIME_MS = 1000; + final String PATH = "/foo/bar/lock"; - ExecutorService executorService = Executors.newFixedThreadPool(QTY); + ExecutorService executorService = Executors.newFixedThreadPool(QTY); ExecutorCompletionService completionService = new ExecutorCompletionService(executorService); - final Timing timing = new Timing(); - List semaphoreClients = Lists.newArrayList(); - TestingCluster cluster = createAndStartCluster(3); - try - { - final AtomicInteger opCount = new AtomicInteger(0); - for ( int i = 0; i < QTY; ++i ) - { - SemaphoreClient semaphoreClient = new SemaphoreClient - ( - cluster.getConnectString(), - PATH, - new Callable() - { - @Override - public Void call() throws Exception - { - opCount.incrementAndGet(); - Thread.sleep(OPERATION_TIME_MS); - return null; - } - } - ); + final Timing timing = new Timing(); + List semaphoreClients = Lists.newArrayList(); + TestingCluster cluster = createAndStartCluster(3); + try { + final AtomicInteger opCount = new AtomicInteger(0); + for (int i = 0; i < QTY; ++i) { + SemaphoreClient semaphoreClient = + new SemaphoreClient(cluster.getConnectString(), PATH, new Callable() { + @Override + public Void call() throws Exception { + opCount.incrementAndGet(); + Thread.sleep(OPERATION_TIME_MS); + return null; + } + }); completionService.submit(semaphoreClient); semaphoreClients.add(semaphoreClient); } @@ -239,47 +193,44 @@ public Void call() throws Exception assertNotNull(SemaphoreClient.getActiveClient()); - final CountDownLatch latch = new CountDownLatch(1); - CuratorFramework client = CuratorFrameworkFactory.newClient(cluster.getConnectString(), timing.session(), timing.connection(), new ExponentialBackoffRetry(100, 3)); - ConnectionStateListener listener = new ConnectionStateListener() - { + final CountDownLatch latch = new CountDownLatch(1); + CuratorFramework client = CuratorFrameworkFactory.newClient( + cluster.getConnectString(), + timing.session(), + timing.connection(), + new ExponentialBackoffRetry(100, 3)); + ConnectionStateListener listener = new ConnectionStateListener() { @Override - public void stateChanged(CuratorFramework client, ConnectionState newState) - { - if ( newState == ConnectionState.LOST ) - { + public void stateChanged(CuratorFramework client, ConnectionState newState) { + if (newState == ConnectionState.LOST) { latch.countDown(); } } }; client.getConnectionStateListenable().addListener(listener); client.start(); - try - { + try { client.getZookeeperClient().blockUntilConnectedOrTimedOut(); cluster.stop(); latch.await(); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } - long startTicks = System.currentTimeMillis(); - for(;;) - { - int thisOpCount = opCount.get(); + long startTicks = System.currentTimeMillis(); + for (; ; ) { + int thisOpCount = opCount.get(); Thread.sleep(2 * OPERATION_TIME_MS); - if ( thisOpCount == opCount.get() ) - { - break; // checking that the op count isn't increasing + if (thisOpCount == opCount.get()) { + break; // checking that the op count isn't increasing } - assertTrue((System.currentTimeMillis() - startTicks) < timing.forWaiting().milliseconds()); + assertTrue((System.currentTimeMillis() - startTicks) + < timing.forWaiting().milliseconds()); } - int thisOpCount = opCount.get(); + int thisOpCount = opCount.get(); Iterator iterator = cluster.getInstances().iterator(); cluster = new TestingCluster(iterator.next(), iterator.next()); @@ -287,20 +238,16 @@ public void stateChanged(CuratorFramework client, ConnectionState newState) timing.forWaiting().sleepABit(); startTicks = System.currentTimeMillis(); - for(;;) - { + for (; ; ) { Thread.sleep(2 * OPERATION_TIME_MS); - if ( opCount.get() > thisOpCount ) - { - break; // checking that semaphore has started working again + if (opCount.get() > thisOpCount) { + break; // checking that semaphore has started working again } - assertTrue((System.currentTimeMillis() - startTicks) < timing.forWaiting().milliseconds()); + assertTrue((System.currentTimeMillis() - startTicks) + < timing.forWaiting().milliseconds()); } - } - finally - { - for ( SemaphoreClient semaphoreClient : semaphoreClients ) - { + } finally { + for (SemaphoreClient semaphoreClient : semaphoreClients) { CloseableUtils.closeQuietly(semaphoreClient); } CloseableUtils.closeQuietly(cluster); diff --git a/curator-recipes/src/test/java/org/apache/curator/framework/recipes/locks/TestInterProcessSemaphoreMutex.java b/curator-recipes/src/test/java/org/apache/curator/framework/recipes/locks/TestInterProcessSemaphoreMutex.java index 8ea5699b9..67e173b8c 100644 --- a/curator-recipes/src/test/java/org/apache/curator/framework/recipes/locks/TestInterProcessSemaphoreMutex.java +++ b/curator-recipes/src/test/java/org/apache/curator/framework/recipes/locks/TestInterProcessSemaphoreMutex.java @@ -23,34 +23,26 @@ import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; -public class TestInterProcessSemaphoreMutex extends TestInterProcessMutexBase -{ +public class TestInterProcessSemaphoreMutex extends TestInterProcessMutexBase { private static final String LOCK_PATH = LOCK_BASE_PATH + "/our-lock"; @Override @Test @Disabled - public void testReentrant() - { - } + public void testReentrant() {} @Override @Test @Disabled - public void testReentrant2Threads() - { - } + public void testReentrant2Threads() {} @Override @Test @Disabled - public void testReentrantSingleLock() - { - } + public void testReentrantSingleLock() {} @Override - protected InterProcessLock makeLock(CuratorFramework client) - { + protected InterProcessLock makeLock(CuratorFramework client) { return new InterProcessSemaphoreMutex(client, LOCK_PATH); } } diff --git a/curator-recipes/src/test/java/org/apache/curator/framework/recipes/locks/TestLockACLs.java b/curator-recipes/src/test/java/org/apache/curator/framework/recipes/locks/TestLockACLs.java index 9eaec0d39..a1a8c41a3 100644 --- a/curator-recipes/src/test/java/org/apache/curator/framework/recipes/locks/TestLockACLs.java +++ b/curator-recipes/src/test/java/org/apache/curator/framework/recipes/locks/TestLockACLs.java @@ -21,113 +21,104 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; - -import org.apache.curator.framework.imps.TestCleanState; -import org.apache.curator.test.BaseClassForTests; -import org.apache.curator.utils.CloseableUtils; +import java.util.Collections; +import java.util.List; import org.apache.curator.RetryPolicy; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.api.ACLProvider; +import org.apache.curator.framework.imps.TestCleanState; import org.apache.curator.retry.ExponentialBackoffRetry; +import org.apache.curator.test.BaseClassForTests; +import org.apache.curator.utils.CloseableUtils; import org.apache.zookeeper.ZooDefs; import org.apache.zookeeper.data.ACL; import org.apache.zookeeper.data.Id; import org.junit.jupiter.api.Test; -import java.util.Collections; -import java.util.List; +public class TestLockACLs extends BaseClassForTests { + private static final List ACLS1 = + Collections.singletonList(new ACL(ZooDefs.Perms.ALL, new Id("ip", "127.0.0.1"))); + private static final List ACLS2 = + Collections.singletonList(new ACL(ZooDefs.Perms.CREATE | ZooDefs.Perms.READ, new Id("ip", "127.0.0.1"))); -public class TestLockACLs extends BaseClassForTests -{ - private static final List ACLS1 = Collections.singletonList(new ACL(ZooDefs.Perms.ALL, new Id("ip", "127.0.0.1"))); - private static final List ACLS2 = Collections.singletonList(new ACL(ZooDefs.Perms.CREATE | ZooDefs.Perms.READ, new Id("ip", "127.0.0.1"))); - - private CuratorFramework createClient(ACLProvider provider) throws Exception - { + private CuratorFramework createClient(ACLProvider provider) throws Exception { RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3); CuratorFramework client = CuratorFrameworkFactory.builder() - .namespace("ns") - .connectString(server.getConnectString()) - .retryPolicy(retryPolicy) - .aclProvider(provider) - .build(); + .namespace("ns") + .connectString(server.getConnectString()) + .retryPolicy(retryPolicy) + .aclProvider(provider) + .build(); client.start(); return client; } @Test - public void testLockACLs() throws Exception - { + public void testLockACLs() throws Exception { CuratorFramework client = createClient(new TestLockACLsProvider()); - try - { + try { client.create().forPath("/foo"); assertNotNull(client.checkExists().forPath("/foo")); - assertEquals(ZooDefs.Perms.ALL, client.getACL().forPath("/foo").get(0).getPerms()); + assertEquals( + ZooDefs.Perms.ALL, client.getACL().forPath("/foo").get(0).getPerms()); assertEquals("ip", client.getACL().forPath("/foo").get(0).getId().getScheme()); - assertEquals("127.0.0.1", client.getACL().forPath("/foo").get(0).getId().getId()); + assertEquals( + "127.0.0.1", client.getACL().forPath("/foo").get(0).getId().getId()); InterProcessReadWriteLock lock = new InterProcessReadWriteLock(client, "/bar"); InterProcessMutex writeLock = lock.writeLock(); writeLock.acquire(); assertNotNull(client.checkExists().forPath("/bar")); - assertEquals(ZooDefs.Perms.ALL, client.getACL().forPath("/bar").get(0).getPerms()); + assertEquals( + ZooDefs.Perms.ALL, client.getACL().forPath("/bar").get(0).getPerms()); assertEquals("ip", client.getACL().forPath("/bar").get(0).getId().getScheme()); - assertEquals("127.0.0.1", client.getACL().forPath("/bar").get(0).getId().getId()); - } - finally - { + assertEquals( + "127.0.0.1", client.getACL().forPath("/bar").get(0).getId().getId()); + } finally { TestCleanState.closeAndTestClean(client); } } @Test - public void testACLsCreatingParents() throws Exception - { + public void testACLsCreatingParents() throws Exception { CuratorFramework client = createClient(new TestACLsCreatingParentsProvider()); - try - { + try { client.create().creatingParentsIfNeeded().forPath("/parent/foo"); - assertEquals(ZooDefs.Perms.CREATE | ZooDefs.Perms.READ, client.getACL().forPath("/parent").get(0).getPerms()); - assertEquals(ZooDefs.Perms.ALL, client.getACL().forPath("/parent/foo").get(0).getPerms()); - } - finally - { + assertEquals( + ZooDefs.Perms.CREATE | ZooDefs.Perms.READ, + client.getACL().forPath("/parent").get(0).getPerms()); + assertEquals( + ZooDefs.Perms.ALL, + client.getACL().forPath("/parent/foo").get(0).getPerms()); + } finally { CloseableUtils.closeQuietly(client); } } - private class TestACLsCreatingParentsProvider implements ACLProvider - { + private class TestACLsCreatingParentsProvider implements ACLProvider { @Override - public List getDefaultAcl() - { + public List getDefaultAcl() { return ACLS1; } @Override - public List getAclForPath(String path) - { - if ( path.equals("/ns/parent") ) - { + public List getAclForPath(String path) { + if (path.equals("/ns/parent")) { return ACLS2; } return ACLS1; } } - private class TestLockACLsProvider implements ACLProvider - { + private class TestLockACLsProvider implements ACLProvider { @Override - public List getDefaultAcl() - { + public List getDefaultAcl() { return ACLS1; } @Override - public List getAclForPath(String path) - { + public List getAclForPath(String path) { return ACLS1; } } diff --git a/curator-recipes/src/test/java/org/apache/curator/framework/recipes/locks/TestLockCleanlinessWithFaults.java b/curator-recipes/src/test/java/org/apache/curator/framework/recipes/locks/TestLockCleanlinessWithFaults.java index 31f15d3b8..d1f285008 100644 --- a/curator-recipes/src/test/java/org/apache/curator/framework/recipes/locks/TestLockCleanlinessWithFaults.java +++ b/curator-recipes/src/test/java/org/apache/curator/framework/recipes/locks/TestLockCleanlinessWithFaults.java @@ -21,7 +21,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.fail; - +import java.util.List; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.imps.TestCleanState; @@ -30,47 +30,35 @@ import org.apache.zookeeper.KeeperException; import org.junit.jupiter.api.Test; -import java.util.List; - -public class TestLockCleanlinessWithFaults extends BaseClassForTests -{ +public class TestLockCleanlinessWithFaults extends BaseClassForTests { @Test - public void testNodeDeleted() throws Exception - { + public void testNodeDeleted() throws Exception { final String PATH = "/foo/bar"; - CuratorFramework client = null; - try - { + CuratorFramework client = null; + try { client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryNTimes(0, 0)); client.start(); client.create().creatingParentsIfNeeded().forPath(PATH); assertEquals(client.checkExists().forPath(PATH).getNumChildren(), 0); - LockInternals internals = new LockInternals(client, new StandardLockInternalsDriver(), PATH, "lock-", 1) - { + LockInternals internals = new LockInternals(client, new StandardLockInternalsDriver(), PATH, "lock-", 1) { @Override - List getSortedChildren() throws Exception - { + List getSortedChildren() throws Exception { throw new KeeperException.NoNodeException(); } }; - try - { + try { internals.attemptLock(0, null, null); fail(); - } - catch ( KeeperException.NoNodeException dummy ) - { + } catch (KeeperException.NoNodeException dummy) { // expected } // make sure no nodes are left lying around assertEquals(client.checkExists().forPath(PATH).getNumChildren(), 0); - } - finally - { + } finally { TestCleanState.closeAndTestClean(client); } } diff --git a/curator-recipes/src/test/java/org/apache/curator/framework/recipes/nodes/TestGroupMember.java b/curator-recipes/src/test/java/org/apache/curator/framework/recipes/nodes/TestGroupMember.java index cf79fae22..03ad6a839 100644 --- a/curator-recipes/src/test/java/org/apache/curator/framework/recipes/nodes/TestGroupMember.java +++ b/curator-recipes/src/test/java/org/apache/curator/framework/recipes/nodes/TestGroupMember.java @@ -25,6 +25,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import com.google.common.base.Function; import com.google.common.collect.Maps; +import java.util.Map; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.retry.RetryOneTime; @@ -35,22 +36,17 @@ import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; -import java.util.Map; - @Tag(CuratorTestBase.zk35TestCompatibilityGroup) -public class TestGroupMember extends BaseClassForTests -{ +public class TestGroupMember extends BaseClassForTests { // NOTE - don't need many tests as this class is just a wrapper around two existing recipes @Test - public void testBasic() throws Exception - { + public void testBasic() throws Exception { Timing timing = new Timing(); GroupMember groupMember1 = null; GroupMember groupMember2 = null; CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); - try - { + try { client.start(); groupMember1 = new GroupMember(client, "/member", "1"); @@ -64,19 +60,15 @@ public void testBasic() throws Exception Map currentMembers1 = groupMember1.getCurrentMembers(); Map currentMembers2 = groupMember2.getCurrentMembers(); - Map convertMembers1 = Maps.transformValues(currentMembers1, new Function() - { + Map convertMembers1 = Maps.transformValues(currentMembers1, new Function() { @Override - public String apply(byte[] input) - { + public String apply(byte[] input) { return new String(input); } }); - Map convertMembers2 = Maps.transformValues(currentMembers2, new Function() - { + Map convertMembers2 = Maps.transformValues(currentMembers2, new Function() { @Override - public String apply(byte[] input) - { + public String apply(byte[] input) { return new String(input); } }); @@ -101,9 +93,7 @@ public String apply(byte[] input) currentMembers1 = groupMember1.getCurrentMembers(); assertTrue(currentMembers1.containsKey("1")); assertArrayEquals(currentMembers1.get("1"), "something".getBytes()); - } - finally - { + } finally { CloseableUtils.closeQuietly(groupMember1); CloseableUtils.closeQuietly(groupMember2); CloseableUtils.closeQuietly(client); diff --git a/curator-recipes/src/test/java/org/apache/curator/framework/recipes/nodes/TestPersistentEphemeralNode.java b/curator-recipes/src/test/java/org/apache/curator/framework/recipes/nodes/TestPersistentEphemeralNode.java index 88d98700d..b8aa2488e 100644 --- a/curator-recipes/src/test/java/org/apache/curator/framework/recipes/nodes/TestPersistentEphemeralNode.java +++ b/curator-recipes/src/test/java/org/apache/curator/framework/recipes/nodes/TestPersistentEphemeralNode.java @@ -29,6 +29,15 @@ import com.google.common.base.Throwables; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Lists; +import java.io.IOException; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.Set; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Semaphore; +import java.util.concurrent.TimeUnit; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.api.ACLProvider; @@ -53,19 +62,9 @@ import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.io.IOException; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.List; -import java.util.Set; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.Semaphore; -import java.util.concurrent.TimeUnit; @SuppressWarnings("deprecation") -public class TestPersistentEphemeralNode extends BaseClassForTests -{ +public class TestPersistentEphemeralNode extends BaseClassForTests { private static final Logger log = LoggerFactory.getLogger(TestPersistentEphemeralNode.class); private static final String DIR = "/test"; private static final String PATH = ZKPaths.makePath(DIR, "/foo"); @@ -77,53 +76,43 @@ public class TestPersistentEphemeralNode extends BaseClassForTests @AfterEach @Override - public void teardown() throws Exception - { - try - { - for ( PersistentEphemeralNode node : createdNodes ) - { + public void teardown() throws Exception { + try { + for (PersistentEphemeralNode node : createdNodes) { CloseableUtils.closeQuietly(node); } - for ( CuratorFramework curator : curatorInstances ) - { + for (CuratorFramework curator : curatorInstances) { TestCleanState.closeAndTestClean(curator); } - } - finally - { + } finally { super.teardown(); } } @Test - public void testListenersReconnectedIsFast() throws Exception - { + public void testListenersReconnectedIsFast() throws Exception { server.stop(); - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); - try - { + CuratorFramework client = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); + try { client.start(); - try ( PersistentEphemeralNode node = new PersistentEphemeralNode(client, PersistentEphemeralNode.Mode.EPHEMERAL, "/abc/node", "hello".getBytes()) ) - { - node.debugWaitMsForBackgroundBeforeClose.set(timing.forSleepingABit().milliseconds()); + try (PersistentEphemeralNode node = new PersistentEphemeralNode( + client, PersistentEphemeralNode.Mode.EPHEMERAL, "/abc/node", "hello".getBytes())) { + node.debugWaitMsForBackgroundBeforeClose.set( + timing.forSleepingABit().milliseconds()); node.start(); final CountDownLatch connectedLatch = new CountDownLatch(1); final CountDownLatch reconnectedLatch = new CountDownLatch(1); - ConnectionStateListener listener = new ConnectionStateListener() - { + ConnectionStateListener listener = new ConnectionStateListener() { @Override - public void stateChanged(CuratorFramework client, ConnectionState newState) - { - if ( newState == ConnectionState.CONNECTED ) - { + public void stateChanged(CuratorFramework client, ConnectionState newState) { + if (newState == ConnectionState.CONNECTED) { connectedLatch.countDown(); } - if ( newState == ConnectionState.RECONNECTED ) - { + if (newState == ConnectionState.RECONNECTED) { reconnectedLatch.countDown(); } } @@ -140,35 +129,31 @@ public void stateChanged(CuratorFramework client, ConnectionState newState) timing.sleepABit(); assertTrue(timing.awaitLatch(reconnectedLatch)); } - } - finally - { + } finally { TestCleanState.closeAndTestClean(client); } } @Test - public void testNoServerAtStart() throws Exception - { + public void testNoServerAtStart() throws Exception { server.stop(); - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); + CuratorFramework client = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); PersistentEphemeralNode node = null; - try - { + try { client.start(); - node = new PersistentEphemeralNode(client, PersistentEphemeralNode.Mode.EPHEMERAL, "/abc/node", "hello".getBytes()); - node.debugWaitMsForBackgroundBeforeClose.set(timing.forSleepingABit().milliseconds()); + node = new PersistentEphemeralNode( + client, PersistentEphemeralNode.Mode.EPHEMERAL, "/abc/node", "hello".getBytes()); + node.debugWaitMsForBackgroundBeforeClose.set( + timing.forSleepingABit().milliseconds()); node.start(); final CountDownLatch connectedLatch = new CountDownLatch(1); - ConnectionStateListener listener = new ConnectionStateListener() - { + ConnectionStateListener listener = new ConnectionStateListener() { @Override - public void stateChanged(CuratorFramework client, ConnectionState newState) - { - if ( newState == ConnectionState.CONNECTED ) - { + public void stateChanged(CuratorFramework client, ConnectionState newState) { + if (newState == ConnectionState.CONNECTED) { connectedLatch.countDown(); } } @@ -184,81 +169,71 @@ public void stateChanged(CuratorFramework client, ConnectionState newState) timing.sleepABit(); assertTrue(node.waitForInitialCreate(timing.forWaiting().milliseconds(), TimeUnit.MILLISECONDS)); - } - finally - { + } finally { CloseableUtils.closeQuietly(node); TestCleanState.closeAndTestClean(client); } } @Test - public void testNullCurator() - { - assertThrows(NullPointerException.class, ()-> { + public void testNullCurator() { + assertThrows(NullPointerException.class, () -> { new PersistentEphemeralNode(null, PersistentEphemeralNode.Mode.EPHEMERAL, PATH, new byte[0]); }); } @Test - public void testNullPath() - { - assertThrows(IllegalArgumentException.class, ()-> { + public void testNullPath() { + assertThrows(IllegalArgumentException.class, () -> { CuratorFramework curator = newCurator(); new PersistentEphemeralNode(curator, PersistentEphemeralNode.Mode.EPHEMERAL, null, new byte[0]); }); } @Test - public void testNullData() - { - assertThrows(NullPointerException.class, ()-> { + public void testNullData() { + assertThrows(NullPointerException.class, () -> { CuratorFramework curator = newCurator(); new PersistentEphemeralNode(curator, PersistentEphemeralNode.Mode.EPHEMERAL, PATH, null); }); } @Test - public void testNullMode() - { - assertThrows(NullPointerException.class, ()->{ + public void testNullMode() { + assertThrows(NullPointerException.class, () -> { CuratorFramework curator = newCurator(); new PersistentEphemeralNode(curator, null, PATH, new byte[0]); - }); + }); } @Test - public void testSettingDataSequential() throws Exception - { + public void testSettingDataSequential() throws Exception { setDataTest(PersistentEphemeralNode.Mode.EPHEMERAL_SEQUENTIAL); } @Test - public void testSettingData() throws Exception - { + public void testSettingData() throws Exception { setDataTest(PersistentEphemeralNode.Mode.EPHEMERAL); } - protected void setDataTest(PersistentEphemeralNode.Mode mode) throws Exception - { + protected void setDataTest(PersistentEphemeralNode.Mode mode) throws Exception { PersistentEphemeralNode node = null; - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); - try - { + CuratorFramework client = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); + try { client.start(); node = new PersistentEphemeralNode(client, mode, PATH, "a".getBytes()); - node.debugWaitMsForBackgroundBeforeClose.set(timing.forSleepingABit().milliseconds()); + node.debugWaitMsForBackgroundBeforeClose.set( + timing.forSleepingABit().milliseconds()); node.start(); assertTrue(node.waitForInitialCreate(timing.forWaiting().seconds(), TimeUnit.SECONDS)); assertArrayEquals(client.getData().forPath(node.getActualPath()), "a".getBytes()); final Semaphore semaphore = new Semaphore(0); - Watcher watcher = new Watcher() - { + Watcher watcher = new Watcher() { @Override - public void process(WatchedEvent arg0) - { + public void process(WatchedEvent arg0) { semaphore.release(); } }; @@ -273,31 +248,26 @@ public void process(WatchedEvent arg0) assertArrayEquals(client.getData().usingWatcher(watcher).forPath(node.getActualPath()), "c".getBytes()); node.close(); assertTrue(timing.acquireSemaphore(semaphore)); - } - finally - { + } finally { CloseableUtils.closeQuietly(node); TestCleanState.closeAndTestClean(client); } } @Test - public void testDeletesNodeWhenClosed() throws Exception - { + public void testDeletesNodeWhenClosed() throws Exception { CuratorFramework curator = newCurator(); - PersistentEphemeralNode node = new PersistentEphemeralNode(curator, PersistentEphemeralNode.Mode.EPHEMERAL, PATH, new byte[0]); + PersistentEphemeralNode node = + new PersistentEphemeralNode(curator, PersistentEphemeralNode.Mode.EPHEMERAL, PATH, new byte[0]); node.debugWaitMsForBackgroundBeforeClose.set(timing.forSleepingABit().milliseconds()); node.start(); String path = null; - try - { + try { node.waitForInitialCreate(5, TimeUnit.SECONDS); path = node.getActualPath(); assertNodeExists(curator, path); - } - finally - { + } finally { CloseableUtils.closeQuietly(node); } @@ -305,11 +275,11 @@ public void testDeletesNodeWhenClosed() throws Exception } @Test - public void testClosingMultipleTimes() throws Exception - { + public void testClosingMultipleTimes() throws Exception { CuratorFramework curator = newCurator(); - PersistentEphemeralNode node = new PersistentEphemeralNode(curator, PersistentEphemeralNode.Mode.EPHEMERAL, PATH, new byte[0]); + PersistentEphemeralNode node = + new PersistentEphemeralNode(curator, PersistentEphemeralNode.Mode.EPHEMERAL, PATH, new byte[0]); node.debugWaitMsForBackgroundBeforeClose.set(timing.forSleepingABit().milliseconds()); node.start(); node.waitForInitialCreate(timing.forWaiting().seconds(), TimeUnit.SECONDS); @@ -323,15 +293,14 @@ public void testClosingMultipleTimes() throws Exception } @Test - public void testDeletesNodeWhenSessionDisconnects() throws Exception - { + public void testDeletesNodeWhenSessionDisconnects() throws Exception { CuratorFramework curator = newCurator(); CuratorFramework observer = newCurator(); - PersistentEphemeralNode node = new PersistentEphemeralNode(curator, PersistentEphemeralNode.Mode.EPHEMERAL, PATH, new byte[0]); + PersistentEphemeralNode node = + new PersistentEphemeralNode(curator, PersistentEphemeralNode.Mode.EPHEMERAL, PATH, new byte[0]); node.debugWaitMsForBackgroundBeforeClose.set(timing.forSleepingABit().milliseconds()); - try - { + try { node.start(); node.waitForInitialCreate(timing.forWaiting().seconds(), TimeUnit.SECONDS); assertNodeExists(observer, node.getActualPath()); @@ -346,23 +315,20 @@ public void testDeletesNodeWhenSessionDisconnects() throws Exception // Make sure the node got deleted assertTrue(deletedTrigger.firedWithin(timing.forSessionSleep().seconds(), TimeUnit.SECONDS)); node.debugCreateNodeLatch.countDown(); - } - finally - { + } finally { CloseableUtils.closeQuietly(node); } } @Test - public void testRecreatesNodeWhenSessionReconnects() throws Exception - { + public void testRecreatesNodeWhenSessionReconnects() throws Exception { CuratorFramework curator = newCurator(); CuratorFramework observer = newCurator(); - PersistentEphemeralNode node = new PersistentEphemeralNode(curator, PersistentEphemeralNode.Mode.EPHEMERAL, PATH, new byte[0]); + PersistentEphemeralNode node = + new PersistentEphemeralNode(curator, PersistentEphemeralNode.Mode.EPHEMERAL, PATH, new byte[0]); node.debugWaitMsForBackgroundBeforeClose.set(timing.forSleepingABit().milliseconds()); - try - { + try { node.start(); node.waitForInitialCreate(5, TimeUnit.SECONDS); assertNodeExists(observer, node.getActualPath()); @@ -380,32 +346,29 @@ public void testRecreatesNodeWhenSessionReconnects() throws Exception // Check for it to be recreated... Trigger createdTrigger = Trigger.created(); Stat stat = observer.checkExists().usingWatcher(createdTrigger).forPath(node.getActualPath()); - assertTrue(stat != null || createdTrigger.firedWithin(timing.forWaiting().seconds(), TimeUnit.SECONDS)); - } - finally - { + assertTrue(stat != null + || createdTrigger.firedWithin(timing.forWaiting().seconds(), TimeUnit.SECONDS)); + } finally { CloseableUtils.closeQuietly(node); } } @Test - public void testRecreatesNodeWhenSessionReconnectsMultipleTimes() throws Exception - { + public void testRecreatesNodeWhenSessionReconnectsMultipleTimes() throws Exception { CuratorFramework curator = newCurator(); CuratorFramework observer = newCurator(); - PersistentEphemeralNode node = new PersistentEphemeralNode(curator, PersistentEphemeralNode.Mode.EPHEMERAL, PATH, new byte[0]); + PersistentEphemeralNode node = + new PersistentEphemeralNode(curator, PersistentEphemeralNode.Mode.EPHEMERAL, PATH, new byte[0]); node.debugWaitMsForBackgroundBeforeClose.set(timing.forSleepingABit().milliseconds()); - try - { + try { node.start(); node.waitForInitialCreate(timing.forWaiting().seconds(), TimeUnit.SECONDS); String path = node.getActualPath(); assertNodeExists(observer, path); // We should be able to disconnect multiple times and each time the node should be recreated. - for ( int i = 0; i < 5; i++ ) - { + for (int i = 0; i < 5; i++) { Trigger deletionTrigger = Trigger.deletedOrSetData(); Stat stat = observer.checkExists().usingWatcher(deletionTrigger).forPath(path); assertNotNull(stat, "node should exist: " + path); @@ -415,38 +378,41 @@ public void testRecreatesNodeWhenSessionReconnectsMultipleTimes() throws Excepti curator.getZookeeperClient().getZooKeeper().getTestable().injectSessionExpiration(); // Make sure the node ended up getting deleted... - assertTrue(deletionTrigger.firedWithin(timing.multiple(1.5).forSessionSleep().seconds(), TimeUnit.SECONDS)); + assertTrue(deletionTrigger.firedWithin( + timing.multiple(1.5).forSessionSleep().seconds(), TimeUnit.SECONDS)); node.debugCreateNodeLatch.countDown(); // Now put a watch in the background looking to see if it gets created... Trigger creationTrigger = Trigger.created(); stat = observer.checkExists().usingWatcher(creationTrigger).forPath(path); - assertTrue(stat != null || creationTrigger.firedWithin(timing.forWaiting().seconds(), TimeUnit.SECONDS)); + assertTrue(stat != null + || creationTrigger.firedWithin(timing.forWaiting().seconds(), TimeUnit.SECONDS)); } - } - finally - { + } finally { CloseableUtils.closeQuietly(node); } } @Test - public void testRecreatesNodeWhenEphemeralOwnerSessionExpires() throws Exception - { + public void testRecreatesNodeWhenEphemeralOwnerSessionExpires() throws Exception { CuratorFramework curator = newCurator(); CuratorFramework nodeCreator = newCurator(); CuratorFramework observer = newCurator(); - nodeCreator.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL).forPath(PATH, new byte[0]); + nodeCreator + .create() + .creatingParentsIfNeeded() + .withMode(CreateMode.EPHEMERAL) + .forPath(PATH, new byte[0]); Trigger dataChangedTrigger = Trigger.dataChanged(); observer.getData().usingWatcher(dataChangedTrigger).forPath(PATH); - PersistentEphemeralNode node = new PersistentEphemeralNode(curator, PersistentEphemeralNode.Mode.EPHEMERAL, PATH, new byte[0]); + PersistentEphemeralNode node = + new PersistentEphemeralNode(curator, PersistentEphemeralNode.Mode.EPHEMERAL, PATH, new byte[0]); node.debugWaitMsForBackgroundBeforeClose.set(timing.forSleepingABit().milliseconds()); node.start(); - try - { + try { node.waitForInitialCreate(5, TimeUnit.SECONDS); assertNodeExists(observer, node.getActualPath()); @@ -463,23 +429,21 @@ public void testRecreatesNodeWhenEphemeralOwnerSessionExpires() throws Exception // Check for it to be recreated... Trigger createdTrigger = Trigger.created(); Stat stat = observer.checkExists().usingWatcher(createdTrigger).forPath(node.getActualPath()); - assertTrue(stat != null || createdTrigger.firedWithin(timing.forWaiting().seconds(), TimeUnit.SECONDS)); - } - finally - { + assertTrue(stat != null + || createdTrigger.firedWithin(timing.forWaiting().seconds(), TimeUnit.SECONDS)); + } finally { node.close(); } } @Test - public void testRecreatesNodeWhenItGetsDeleted() throws Exception - { + public void testRecreatesNodeWhenItGetsDeleted() throws Exception { CuratorFramework curator = newCurator(); - PersistentEphemeralNode node = new PersistentEphemeralNode(curator, PersistentEphemeralNode.Mode.EPHEMERAL, PATH, new byte[0]); + PersistentEphemeralNode node = + new PersistentEphemeralNode(curator, PersistentEphemeralNode.Mode.EPHEMERAL, PATH, new byte[0]); node.debugWaitMsForBackgroundBeforeClose.set(timing.forSleepingABit().milliseconds()); - try - { + try { node.start(); node.waitForInitialCreate(timing.forWaiting().seconds(), TimeUnit.SECONDS); String originalNode = node.getActualPath(); @@ -492,59 +456,54 @@ public void testRecreatesNodeWhenItGetsDeleted() throws Exception // node that gets created is going to be exactly the same as the original. Trigger createdWatchTrigger = Trigger.created(); Stat stat = curator.checkExists().usingWatcher(createdWatchTrigger).forPath(originalNode); - assertTrue(stat != null || createdWatchTrigger.firedWithin(timing.forWaiting().seconds(), TimeUnit.SECONDS)); - } - finally - { + assertTrue(stat != null + || createdWatchTrigger.firedWithin(timing.forWaiting().seconds(), TimeUnit.SECONDS)); + } finally { CloseableUtils.closeQuietly(node); } } @Test - public void testNodesCreateUniquePaths() throws Exception - { + public void testNodesCreateUniquePaths() throws Exception { CuratorFramework curator = newCurator(); - try ( PersistentEphemeralNode node1 = new PersistentEphemeralNode(curator, PersistentEphemeralNode.Mode.EPHEMERAL_SEQUENTIAL, PATH, new byte[0]) ) - { - node1.debugWaitMsForBackgroundBeforeClose.set(timing.forSleepingABit().milliseconds()); + try (PersistentEphemeralNode node1 = new PersistentEphemeralNode( + curator, PersistentEphemeralNode.Mode.EPHEMERAL_SEQUENTIAL, PATH, new byte[0])) { + node1.debugWaitMsForBackgroundBeforeClose.set( + timing.forSleepingABit().milliseconds()); node1.start(); node1.waitForInitialCreate(timing.forWaiting().seconds(), TimeUnit.SECONDS); String path1 = node1.getActualPath(); - PersistentEphemeralNode node2 = new PersistentEphemeralNode(curator, PersistentEphemeralNode.Mode.EPHEMERAL_SEQUENTIAL, PATH, new byte[0]); - node2.debugWaitMsForBackgroundBeforeClose.set(timing.forSleepingABit().milliseconds()); + PersistentEphemeralNode node2 = new PersistentEphemeralNode( + curator, PersistentEphemeralNode.Mode.EPHEMERAL_SEQUENTIAL, PATH, new byte[0]); + node2.debugWaitMsForBackgroundBeforeClose.set( + timing.forSleepingABit().milliseconds()); node2.start(); - try - { + try { node2.waitForInitialCreate(timing.forWaiting().seconds(), TimeUnit.SECONDS); String path2 = node2.getActualPath(); assertFalse(path1.equals(path2)); - } - finally - { + } finally { node2.close(); } } } @Test - public void testData() throws Exception - { + public void testData() throws Exception { CuratorFramework curator = newCurator(); byte[] data = "Hello World".getBytes(); - PersistentEphemeralNode node = new PersistentEphemeralNode(curator, PersistentEphemeralNode.Mode.EPHEMERAL, PATH, data); + PersistentEphemeralNode node = + new PersistentEphemeralNode(curator, PersistentEphemeralNode.Mode.EPHEMERAL, PATH, data); node.debugWaitMsForBackgroundBeforeClose.set(timing.forSleepingABit().milliseconds()); - try - { + try { node.start(); node.waitForInitialCreate(timing.forWaiting().seconds(), TimeUnit.SECONDS); assertTrue(Arrays.equals(curator.getData().forPath(node.getActualPath()), data)); - } - finally - { + } finally { CloseableUtils.closeQuietly(node); } } @@ -555,39 +514,39 @@ public void testData() throws Exception * @throws Exception */ @Test - public void testSetDataWhenNodeExists() throws Exception - { + public void testSetDataWhenNodeExists() throws Exception { CuratorFramework curator = newCurator(); - curator.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL).forPath(PATH, "InitialData".getBytes()); + curator.create() + .creatingParentsIfNeeded() + .withMode(CreateMode.EPHEMERAL) + .forPath(PATH, "InitialData".getBytes()); byte[] data = "Hello World".getBytes(); - PersistentEphemeralNode node = new PersistentEphemeralNode(curator, PersistentEphemeralNode.Mode.EPHEMERAL, PATH, data); + PersistentEphemeralNode node = + new PersistentEphemeralNode(curator, PersistentEphemeralNode.Mode.EPHEMERAL, PATH, data); node.debugWaitMsForBackgroundBeforeClose.set(timing.forSleepingABit().milliseconds()); - try - { + try { node.start(); node.waitForInitialCreate(timing.forWaiting().seconds(), TimeUnit.SECONDS); assertTrue(Arrays.equals(curator.getData().forPath(node.getActualPath()), data)); - } - finally - { + } finally { CloseableUtils.closeQuietly(node); } } @Test - public void testSetDataWhenDisconnected() throws Exception - { + public void testSetDataWhenDisconnected() throws Exception { CuratorFramework curator = newCurator(); byte[] initialData = "Hello World".getBytes(); byte[] updatedData = "Updated".getBytes(); - PersistentEphemeralNode node = new PersistentEphemeralNode(curator, PersistentEphemeralNode.Mode.EPHEMERAL, PATH, initialData); - try - { - node.debugWaitMsForBackgroundBeforeClose.set(timing.forSleepingABit().milliseconds()); + PersistentEphemeralNode node = + new PersistentEphemeralNode(curator, PersistentEphemeralNode.Mode.EPHEMERAL, PATH, initialData); + try { + node.debugWaitMsForBackgroundBeforeClose.set( + timing.forSleepingABit().milliseconds()); node.start(); node.waitForInitialCreate(timing.forWaiting().seconds(), TimeUnit.SECONDS); assertTrue(Arrays.equals(curator.getData().forPath(node.getActualPath()), initialData)); @@ -596,16 +555,13 @@ public void testSetDataWhenDisconnected() throws Exception final CountDownLatch dataUpdateLatch = new CountDownLatch(1); - Watcher watcher = new Watcher() - { - @Override - public void process(WatchedEvent event) - { - if ( event.getType() == EventType.NodeDataChanged ) - { - dataUpdateLatch.countDown(); - } - } + Watcher watcher = new Watcher() { + @Override + public void process(WatchedEvent event) { + if (event.getType() == EventType.NodeDataChanged) { + dataUpdateLatch.countDown(); + } + } }; curator.getData().usingWatcher(watcher).inBackground().forPath(node.getActualPath()); @@ -616,25 +572,23 @@ public void process(WatchedEvent event) assertTrue(timing.awaitLatch(dataUpdateLatch)); assertTrue(Arrays.equals(curator.getData().forPath(node.getActualPath()), updatedData)); - } - finally - { + } finally { CloseableUtils.closeQuietly(node); } } @Test - public void testSetUpdatedDataWhenReconnected() throws Exception - { + public void testSetUpdatedDataWhenReconnected() throws Exception { CuratorFramework curator = newCurator(); byte[] initialData = "Hello World".getBytes(); byte[] updatedData = "Updated".getBytes(); - PersistentEphemeralNode node = new PersistentEphemeralNode(curator, PersistentEphemeralNode.Mode.EPHEMERAL, PATH, initialData); - try - { - node.debugWaitMsForBackgroundBeforeClose.set(timing.forSleepingABit().milliseconds()); + PersistentEphemeralNode node = + new PersistentEphemeralNode(curator, PersistentEphemeralNode.Mode.EPHEMERAL, PATH, initialData); + try { + node.debugWaitMsForBackgroundBeforeClose.set( + timing.forSleepingABit().milliseconds()); node.start(); node.waitForInitialCreate(timing.forWaiting().seconds(), TimeUnit.SECONDS); assertTrue(Arrays.equals(curator.getData().forPath(node.getActualPath()), initialData)); @@ -645,20 +599,20 @@ public void testSetUpdatedDataWhenReconnected() throws Exception server.restart(); final CountDownLatch dataUpdateLatch = new CountDownLatch(1); - curator.getData().inBackground(new BackgroundCallback() { + curator.getData() + .inBackground(new BackgroundCallback() { - @Override - public void processResult(CuratorFramework client, CuratorEvent event) throws Exception { - dataUpdateLatch.countDown(); - } - }).forPath(node.getActualPath()); + @Override + public void processResult(CuratorFramework client, CuratorEvent event) throws Exception { + dataUpdateLatch.countDown(); + } + }) + .forPath(node.getActualPath()); assertTrue(timing.awaitLatch(dataUpdateLatch)); assertTrue(Arrays.equals(curator.getData().forPath(node.getActualPath()), updatedData)); - } - finally - { + } finally { CloseableUtils.closeQuietly(node); } } @@ -670,15 +624,14 @@ public void processResult(CuratorFramework client, CuratorEvent event) throws Ex * @throws Exception */ @Test - public void testProtected() throws Exception - { + public void testProtected() throws Exception { CuratorFramework curator = newCurator(); - PersistentEphemeralNode node = new PersistentEphemeralNode(curator, PersistentEphemeralNode.Mode.PROTECTED_EPHEMERAL, PATH, - new byte[0]); - try - { - node.debugWaitMsForBackgroundBeforeClose.set(timing.forSleepingABit().milliseconds()); + PersistentEphemeralNode node = new PersistentEphemeralNode( + curator, PersistentEphemeralNode.Mode.PROTECTED_EPHEMERAL, PATH, new byte[0]); + try { + node.debugWaitMsForBackgroundBeforeClose.set( + timing.forSleepingABit().milliseconds()); node.start(); node.waitForInitialCreate(timing.forWaiting().seconds(), TimeUnit.SECONDS); assertNodeExists(curator, node.getActualPath()); @@ -689,26 +642,22 @@ public void testProtected() throws Exception assertNodeExists(curator, node.getActualPath()); - //There should only be a single child, the persisted ephemeral node + // There should only be a single child, the persisted ephemeral node List children = curator.getChildren().forPath(DIR); assertFalse(children == null); assertEquals(children.size(), 1); - } - finally - { + } finally { CloseableUtils.closeQuietly(node); } } @Test - public void testNoCreatePermission() throws Exception - { + public void testNoCreatePermission() throws Exception { CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder(); - CuratorFramework client = builder - .connectString(server.getConnectString()) - .authorization("digest", "me1:pass1".getBytes()) - .retryPolicy(new RetryOneTime(1)) - .build(); + CuratorFramework client = builder.connectString(server.getConnectString()) + .authorization("digest", "me1:pass1".getBytes()) + .retryPolicy(new RetryOneTime(1)) + .build(); PersistentEphemeralNode node = null; try { @@ -719,13 +668,13 @@ public void testNoCreatePermission() throws Exception client.create().withACL(aclList).forPath(DIR, new byte[0]); client.close(); - //New client without authentication - client = newCurator(); + // New client without authentication + client = newCurator(); - node = new PersistentEphemeralNode(client, PersistentEphemeralNode.Mode.EPHEMERAL, PATH, - new byte[0]); - node.debugWaitMsForBackgroundBeforeClose.set(timing.forSleepingABit().milliseconds()); - node.start(); + node = new PersistentEphemeralNode(client, PersistentEphemeralNode.Mode.EPHEMERAL, PATH, new byte[0]); + node.debugWaitMsForBackgroundBeforeClose.set( + timing.forSleepingABit().milliseconds()); + node.start(); node.waitForInitialCreate(timing.seconds(), TimeUnit.SECONDS); assertNodeDoesNotExist(client, PATH); @@ -737,11 +686,12 @@ public void testNoCreatePermission() throws Exception } @Test - public void testNoWritePermission() throws Exception - { + public void testNoWritePermission() throws Exception { final ACLProvider aclProvider = new ACLProvider() { - final ACL acl = new ACL(ZooDefs.Perms.READ | ZooDefs.Perms.CREATE | ZooDefs.Perms.DELETE, ZooDefs.Ids.ANYONE_ID_UNSAFE); + final ACL acl = new ACL( + ZooDefs.Perms.READ | ZooDefs.Perms.CREATE | ZooDefs.Perms.DELETE, ZooDefs.Ids.ANYONE_ID_UNSAFE); final List aclList = Collections.singletonList(acl); + @Override public List getDefaultAcl() { return aclList; @@ -754,8 +704,7 @@ public List getAclForPath(String path) { }; CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder(); - CuratorFramework client = builder - .connectString(server.getConnectString()) + CuratorFramework client = builder.connectString(server.getConnectString()) .aclProvider(aclProvider) .retryPolicy(new RetryOneTime(1)) .build(); @@ -764,8 +713,7 @@ public List getAclForPath(String path) { try { client.start(); - node = new PersistentEphemeralNode(client, PersistentEphemeralNode.Mode.EPHEMERAL, PATH, - new byte[0]); + node = new PersistentEphemeralNode(client, PersistentEphemeralNode.Mode.EPHEMERAL, PATH, new byte[0]); node.start(); assertTrue(node.waitForInitialCreate(timing.seconds(), TimeUnit.SECONDS), "Node not created"); @@ -784,33 +732,29 @@ public List getAclForPath(String path) { } } - private void assertNodeExists(CuratorFramework curator, String path) throws Exception - { + private void assertNodeExists(CuratorFramework curator, String path) throws Exception { assertNotNull(path); assertTrue(curator.checkExists().forPath(path) != null); } - private void assertNodeDoesNotExist(CuratorFramework curator, String path) throws Exception - { + private void assertNodeDoesNotExist(CuratorFramework curator, String path) throws Exception { assertTrue(curator.checkExists().forPath(path) == null); } - private CuratorFramework newCurator() throws IOException - { - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); + private CuratorFramework newCurator() throws IOException { + CuratorFramework client = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); client.start(); curatorInstances.add(client); return client; } - private static final class Trigger implements Watcher - { + private static final class Trigger implements Watcher { private final Set types; private final CountDownLatch latch; - public Trigger(Event.EventType... types) - { + public Trigger(Event.EventType... types) { assertNotNull(types); this.types = ImmutableSet.copyOf(types); @@ -818,43 +762,32 @@ public Trigger(Event.EventType... types) } @Override - public void process(WatchedEvent event) - { - if ( types.contains(event.getType()) ) - { + public void process(WatchedEvent event) { + if (types.contains(event.getType())) { latch.countDown(); - } - else if ( event.getType() != EventType.None ) - { + } else if (event.getType() != EventType.None) { log.warn("Unexpected watcher event: " + event); } } - public boolean firedWithin(long duration, TimeUnit unit) - { - try - { + public boolean firedWithin(long duration, TimeUnit unit) { + try { return latch.await(duration, unit); - } - catch ( InterruptedException e ) - { + } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw Throwables.propagate(e); } } - private static Trigger created() - { + private static Trigger created() { return new Trigger(Event.EventType.NodeCreated); } - private static Trigger deletedOrSetData() - { + private static Trigger deletedOrSetData() { return new Trigger(Event.EventType.NodeDeleted, EventType.NodeDataChanged); } - private static Trigger dataChanged() - { + private static Trigger dataChanged() { return new Trigger(EventType.NodeDataChanged); } } diff --git a/curator-recipes/src/test/java/org/apache/curator/framework/recipes/nodes/TestPersistentEphemeralNodeListener.java b/curator-recipes/src/test/java/org/apache/curator/framework/recipes/nodes/TestPersistentEphemeralNodeListener.java index b114dc3a0..df450eaf0 100644 --- a/curator-recipes/src/test/java/org/apache/curator/framework/recipes/nodes/TestPersistentEphemeralNodeListener.java +++ b/curator-recipes/src/test/java/org/apache/curator/framework/recipes/nodes/TestPersistentEphemeralNodeListener.java @@ -21,7 +21,9 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; - +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.state.ConnectionState; @@ -32,41 +34,32 @@ import org.apache.curator.utils.CloseableUtils; import org.junit.jupiter.api.Test; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicReference; - @SuppressWarnings("deprecation") -public class TestPersistentEphemeralNodeListener extends BaseClassForTests -{ +public class TestPersistentEphemeralNodeListener extends BaseClassForTests { @Test - public void testListenersReconnectedIsOK() throws Exception - { + public void testListenersReconnectedIsOK() throws Exception { server.stop(); Timing timing = new Timing(); - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); - try - { + CuratorFramework client = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); + try { client.start(); - PersistentEphemeralNode node = new PersistentEphemeralNode(client, PersistentEphemeralNode.Mode.EPHEMERAL, "/abc/node", "hello".getBytes()); + PersistentEphemeralNode node = new PersistentEphemeralNode( + client, PersistentEphemeralNode.Mode.EPHEMERAL, "/abc/node", "hello".getBytes()); node.start(); final CountDownLatch connectedLatch = new CountDownLatch(1); final CountDownLatch reconnectedLatch = new CountDownLatch(1); final AtomicReference lastState = new AtomicReference(); - ConnectionStateListener listener = new ConnectionStateListener() - { + ConnectionStateListener listener = new ConnectionStateListener() { @Override - public void stateChanged(CuratorFramework client, ConnectionState newState) - { + public void stateChanged(CuratorFramework client, ConnectionState newState) { lastState.set(newState); - if ( newState == ConnectionState.CONNECTED ) - { + if (newState == ConnectionState.CONNECTED) { connectedLatch.countDown(); } - if ( newState == ConnectionState.RECONNECTED ) - { + if (newState == ConnectionState.RECONNECTED) { reconnectedLatch.countDown(); } } @@ -82,10 +75,8 @@ public void stateChanged(CuratorFramework client, ConnectionState newState) assertTrue(timing.awaitLatch(reconnectedLatch)); timing.sleepABit(); assertEquals(lastState.get(), ConnectionState.RECONNECTED); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } -} \ No newline at end of file +} diff --git a/curator-recipes/src/test/java/org/apache/curator/framework/recipes/nodes/TestPersistentNode.java b/curator-recipes/src/test/java/org/apache/curator/framework/recipes/nodes/TestPersistentNode.java index 5f136d124..27f70948b 100644 --- a/curator-recipes/src/test/java/org/apache/curator/framework/recipes/nodes/TestPersistentNode.java +++ b/curator-recipes/src/test/java/org/apache/curator/framework/recipes/nodes/TestPersistentNode.java @@ -26,7 +26,8 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; - +import java.util.List; +import java.util.concurrent.TimeUnit; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.retry.RetryOneTime; @@ -37,52 +38,41 @@ import org.apache.zookeeper.CreateMode; import org.junit.jupiter.api.Test; -import java.util.List; -import java.util.concurrent.TimeUnit; - -public class TestPersistentNode extends BaseClassForTests -{ +public class TestPersistentNode extends BaseClassForTests { @Test - public void testQuickSetData() throws Exception - { + public void testQuickSetData() throws Exception { final byte[] TEST_DATA = "hey".getBytes(); final byte[] ALT_TEST_DATA = "there".getBytes(); Timing timing = new Timing(); PersistentNode pen = null; - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); - try - { + CuratorFramework client = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); + try { client.start(); pen = new PersistentNode(client, CreateMode.PERSISTENT, false, "/test", TEST_DATA); pen.start(); - try - { + try { pen.setData(ALT_TEST_DATA); fail("IllegalStateException should have been thrown"); - } - catch ( IllegalStateException dummy ) - { + } catch (IllegalStateException dummy) { // expected } - } - finally - { + } finally { CloseableUtils.closeQuietly(pen); CloseableUtils.closeQuietly(client); } } @Test - public void testBasic() throws Exception - { + public void testBasic() throws Exception { final byte[] TEST_DATA = "hey".getBytes(); Timing2 timing = new Timing2(); PersistentNode pen = null; - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); - try - { + CuratorFramework client = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); + try { client.start(); pen = new PersistentNode(client, CreateMode.PERSISTENT, false, "/test", TEST_DATA); pen.debugWaitMsForBackgroundBeforeClose.set(timing.forSleepingABit().milliseconds()); @@ -90,14 +80,13 @@ public void testBasic() throws Exception assertTrue(pen.waitForInitialCreate(timing.milliseconds(), TimeUnit.MILLISECONDS)); client.close(); // cause session to end - force checks that node is persistent - client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); + client = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); client.start(); byte[] bytes = client.getData().forPath("/test"); assertArrayEquals(bytes, TEST_DATA); - } - finally - { + } finally { CloseableUtils.closeQuietly(pen); CloseableUtils.closeQuietly(client); } @@ -107,7 +96,8 @@ public void testBasic() throws Exception public void testCreationWithParentCreationOff() throws Exception { Timing2 timing = new Timing2(); PersistentNode pen = null; - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); + CuratorFramework client = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); try { client.start(); @@ -120,7 +110,6 @@ public void testCreationWithParentCreationOff() throws Exception { CloseableUtils.closeQuietly(pen); CloseableUtils.closeQuietly(client); } - } @Test @@ -128,7 +117,8 @@ public void testRecreationWithParentCreationOff() throws Exception { final byte[] TEST_DATA = "hey".getBytes(); Timing2 timing = new Timing2(); PersistentNode pen = null; - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); + CuratorFramework client = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); try { client.start(); @@ -154,40 +144,34 @@ public void testRecreationWithParentCreationOff() throws Exception { CloseableUtils.closeQuietly(pen); CloseableUtils.closeQuietly(client); } - - } @Test - public void testQuickClose() throws Exception - { + public void testQuickClose() throws Exception { Timing timing = new Timing(); PersistentNode pen = null; - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); - try - { + CuratorFramework client = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); + try { client.start(); pen = new PersistentNode(client, CreateMode.PERSISTENT, false, "/test/one/two", new byte[0]); pen.start(); pen.close(); timing.sleepABit(); assertNull(client.checkExists().forPath("/test/one/two")); - } - finally - { + } finally { CloseableUtils.closeQuietly(pen); CloseableUtils.closeQuietly(client); } } @Test - public void testQuickCloseNodeExists() throws Exception - { + public void testQuickCloseNodeExists() throws Exception { Timing timing = new Timing(); PersistentNode pen = null; - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); - try - { + CuratorFramework client = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); + try { client.start(); client.create().creatingParentsIfNeeded().forPath("/test/one/two"); @@ -196,40 +180,35 @@ public void testQuickCloseNodeExists() throws Exception pen.close(); timing.sleepABit(); assertNull(client.checkExists().forPath("/test/one/two")); - } - finally - { + } finally { CloseableUtils.closeQuietly(pen); CloseableUtils.closeQuietly(client); } } @Test - public void testEphemeralSequentialWithProtectionReconnection() throws Exception - { + public void testEphemeralSequentialWithProtectionReconnection() throws Exception { Timing timing = new Timing(); PersistentNode pen = null; - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); - try - { + CuratorFramework client = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); + try { client.start(); client.create().creatingParentsIfNeeded().forPath("/test/one"); pen = new PersistentNode(client, CreateMode.EPHEMERAL_SEQUENTIAL, true, "/test/one/two", new byte[0]); pen.start(); List children = client.getChildren().forPath("/test/one"); - System.out.println("children before restart: "+children); + System.out.println("children before restart: " + children); assertEquals(1, children.size()); server.stop(); timing.sleepABit(); server.restart(); timing.sleepABit(); List childrenAfter = client.getChildren().forPath("/test/one"); - System.out.println("children after restart: "+childrenAfter); - assertEquals(children, childrenAfter, "unexpected znodes: "+childrenAfter); - } - finally - { + System.out.println("children after restart: " + childrenAfter); + assertEquals(children, childrenAfter, "unexpected znodes: " + childrenAfter); + } finally { CloseableUtils.closeQuietly(pen); CloseableUtils.closeQuietly(client); } diff --git a/curator-recipes/src/test/java/org/apache/curator/framework/recipes/nodes/TestPersistentTtlNode.java b/curator-recipes/src/test/java/org/apache/curator/framework/recipes/nodes/TestPersistentTtlNode.java index 60a0623fc..ddc9f3975 100644 --- a/curator-recipes/src/test/java/org/apache/curator/framework/recipes/nodes/TestPersistentTtlNode.java +++ b/curator-recipes/src/test/java/org/apache/curator/framework/recipes/nodes/TestPersistentTtlNode.java @@ -19,13 +19,15 @@ package org.apache.curator.framework.recipes.nodes; +import static org.apache.curator.framework.recipes.cache.PathChildrenCache.StartMode.BUILD_INITIAL_CACHE; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertArrayEquals; - +import static org.junit.jupiter.api.Assertions.assertTrue; +import java.util.concurrent.Semaphore; +import java.util.concurrent.TimeUnit; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.recipes.cache.PathChildrenCache; @@ -41,13 +43,7 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import java.util.concurrent.Semaphore; -import java.util.concurrent.TimeUnit; - -import static org.apache.curator.framework.recipes.cache.PathChildrenCache.StartMode.BUILD_INITIAL_CACHE; - -public class TestPersistentTtlNode extends CuratorTestBase -{ +public class TestPersistentTtlNode extends CuratorTestBase { private final Timing timing = new Timing(); private final long ttlMs = timing.multiple(.10).milliseconds(); // a small number @@ -58,35 +54,30 @@ public static void setUpClass() { @BeforeEach @Override - public void setup() throws Exception - { + public void setup() throws Exception { System.setProperty("znode.container.checkIntervalMs", "1"); super.setup(); } @AfterEach @Override - public void teardown() throws Exception - { + public void teardown() throws Exception { System.clearProperty("znode.container.checkIntervalMs"); super.teardown(); } @Test - public void testBasic() throws Exception - { - try (CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1))) - { + public void testBasic() throws Exception { + try (CuratorFramework client = + CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1))) { client.start(); - try (PersistentTtlNode node = new PersistentTtlNode(client, "/test", ttlMs, new byte[0])) - { + try (PersistentTtlNode node = new PersistentTtlNode(client, "/test", ttlMs, new byte[0])) { node.start(); assertTrue(node.waitForInitialCreate(timing.session(), TimeUnit.MILLISECONDS)); - for ( int i = 0; i < 5; ++i ) - { - Thread.sleep(ttlMs + (ttlMs / 2)); // sleep a bit more than the TTL + for (int i = 0; i < 5; ++i) { + Thread.sleep(ttlMs + (ttlMs / 2)); // sleep a bit more than the TTL assertNotNull(client.checkExists().forPath("/test")); } } @@ -98,21 +89,20 @@ public void testBasic() throws Exception } @Test - public void testForcedDeleteOfTouchNode() throws Exception - { - try (CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1))) - { + public void testForcedDeleteOfTouchNode() throws Exception { + try (CuratorFramework client = + CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1))) { client.start(); - try (PersistentTtlNode node = new PersistentTtlNode(client, "/test", ttlMs, new byte[0])) - { + try (PersistentTtlNode node = new PersistentTtlNode(client, "/test", ttlMs, new byte[0])) { node.start(); assertTrue(node.waitForInitialCreate(timing.session(), TimeUnit.MILLISECONDS)); - for ( int i = 0; i < 5; ++i ) - { + for (int i = 0; i < 5; ++i) { Thread.sleep(ttlMs); - client.delete().quietly().forPath(ZKPaths.makePath("test", PersistentTtlNode.DEFAULT_CHILD_NODE_NAME)); + client.delete() + .quietly() + .forPath(ZKPaths.makePath("test", PersistentTtlNode.DEFAULT_CHILD_NODE_NAME)); } timing.sleepABit(); @@ -122,20 +112,18 @@ public void testForcedDeleteOfTouchNode() throws Exception } @Test - public void testRecreationOfParentNodeWithParentCreationOff() throws Exception - { + public void testRecreationOfParentNodeWithParentCreationOff() throws Exception { final byte[] TEST_DATA = "hey".getBytes(); Timing2 timing = new Timing2(); String containerPath = ZKPaths.makePath("test", "one", "two"); String childPath = ZKPaths.makePath("test", "one", "two", PersistentTtlNode.DEFAULT_CHILD_NODE_NAME); - try (CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1))) - { + try (CuratorFramework client = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1))) { client.start(); client.create().creatingParentsIfNeeded().forPath("/test/one"); - try (PersistentTtlNode node = new PersistentTtlNode(client, containerPath, ttlMs, TEST_DATA, false)) - { + try (PersistentTtlNode node = new PersistentTtlNode(client, containerPath, ttlMs, TEST_DATA, false)) { node.start(); assertTrue(node.waitForInitialCreate(timing.milliseconds(), TimeUnit.MILLISECONDS)); @@ -143,11 +131,11 @@ public void testRecreationOfParentNodeWithParentCreationOff() throws Exception assertNotNull(client.checkExists().forPath(containerPath)); assertNotNull(client.checkExists().forPath(childPath)); - client.delete().deletingChildrenIfNeeded().forPath("/test/one"); timing.sleepABit(); - // The underlying persistent node should not be able to recreate itself as the lazy parent creation is disabled + // The underlying persistent node should not be able to recreate itself as the lazy parent creation is + // disabled assertNull(client.checkExists().forPath(containerPath)); assertNull(client.checkExists().forPath(childPath)); @@ -160,24 +148,19 @@ public void testRecreationOfParentNodeWithParentCreationOff() throws Exception } @Test - public void testEventsOnParent() throws Exception - { - try (CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1))) - { + public void testEventsOnParent() throws Exception { + try (CuratorFramework client = + CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1))) { client.start(); - try (PersistentTtlNode node = new PersistentTtlNode(client, "/test", ttlMs, new byte[0])) - { - try(PathChildrenCache cache = new PathChildrenCache(client, "/", true)) - { + try (PersistentTtlNode node = new PersistentTtlNode(client, "/test", ttlMs, new byte[0])) { + try (PathChildrenCache cache = new PathChildrenCache(client, "/", true)) { final Semaphore changes = new Semaphore(0); - PathChildrenCacheListener listener = new PathChildrenCacheListener() - { + PathChildrenCacheListener listener = new PathChildrenCacheListener() { @Override - public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception - { - if ( (event.getType() == PathChildrenCacheEvent.Type.CHILD_UPDATED) && "/test".equals(event.getData().getPath()) ) - { + public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception { + if ((event.getType() == PathChildrenCacheEvent.Type.CHILD_UPDATED) + && "/test".equals(event.getData().getPath())) { changes.release(); } } diff --git a/curator-recipes/src/test/java/org/apache/curator/framework/recipes/queue/QueueItemSerializer.java b/curator-recipes/src/test/java/org/apache/curator/framework/recipes/queue/QueueItemSerializer.java index 3d34f84ac..b033a21a5 100644 --- a/curator-recipes/src/test/java/org/apache/curator/framework/recipes/queue/QueueItemSerializer.java +++ b/curator-recipes/src/test/java/org/apache/curator/framework/recipes/queue/QueueItemSerializer.java @@ -19,17 +19,14 @@ package org.apache.curator.framework.recipes.queue; -class QueueItemSerializer implements QueueSerializer -{ +class QueueItemSerializer implements QueueSerializer { @Override - public byte[] serialize(TestQueueItem item) - { + public byte[] serialize(TestQueueItem item) { return item.str.getBytes(); } @Override - public TestQueueItem deserialize(byte[] bytes) - { + public TestQueueItem deserialize(byte[] bytes) { return new TestQueueItem(new String(bytes)); } } diff --git a/curator-recipes/src/test/java/org/apache/curator/framework/recipes/queue/QueueTestProducer.java b/curator-recipes/src/test/java/org/apache/curator/framework/recipes/queue/QueueTestProducer.java index 2c36e400a..36806a0f1 100644 --- a/curator-recipes/src/test/java/org/apache/curator/framework/recipes/queue/QueueTestProducer.java +++ b/curator-recipes/src/test/java/org/apache/curator/framework/recipes/queue/QueueTestProducer.java @@ -21,25 +21,21 @@ import java.util.concurrent.Callable; -public class QueueTestProducer implements Callable -{ +public class QueueTestProducer implements Callable { private final DistributedQueue queue; private final int itemQty; private final int startIndex; - public QueueTestProducer(DistributedQueue queue, int itemQty, int startIndex) - { + public QueueTestProducer(DistributedQueue queue, int itemQty, int startIndex) { this.queue = queue; this.itemQty = itemQty; this.startIndex = startIndex; } @Override - public Void call() throws Exception - { - int count = 0; - while ( !Thread.currentThread().isInterrupted() && (count < itemQty) ) - { + public Void call() throws Exception { + int count = 0; + while (!Thread.currentThread().isInterrupted() && (count < itemQty)) { queue.put(new TestQueueItem(Integer.toString(count + startIndex))); ++count; } diff --git a/curator-recipes/src/test/java/org/apache/curator/framework/recipes/queue/TestBoundedDistributedQueue.java b/curator-recipes/src/test/java/org/apache/curator/framework/recipes/queue/TestBoundedDistributedQueue.java index c04c51a7d..7219f2b75 100644 --- a/curator-recipes/src/test/java/org/apache/curator/framework/recipes/queue/TestBoundedDistributedQueue.java +++ b/curator-recipes/src/test/java/org/apache/curator/framework/recipes/queue/TestBoundedDistributedQueue.java @@ -22,19 +22,6 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; - -import org.apache.curator.framework.CuratorFramework; -import org.apache.curator.framework.CuratorFrameworkFactory; -import org.apache.curator.framework.imps.CuratorFrameworkState; -import org.apache.curator.framework.state.ConnectionState; -import org.apache.curator.retry.RetryOneTime; -import org.apache.curator.test.BaseClassForTests; -import org.apache.curator.test.Timing; -import org.apache.curator.utils.CloseableUtils; -import org.apache.zookeeper.WatchedEvent; -import org.apache.zookeeper.Watcher; -import org.junit.jupiter.api.Test; - import java.util.Arrays; import java.util.List; import java.util.concurrent.Callable; @@ -46,202 +33,188 @@ import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; +import org.apache.curator.framework.CuratorFramework; +import org.apache.curator.framework.CuratorFrameworkFactory; +import org.apache.curator.framework.imps.CuratorFrameworkState; +import org.apache.curator.framework.state.ConnectionState; +import org.apache.curator.retry.RetryOneTime; +import org.apache.curator.test.BaseClassForTests; +import org.apache.curator.test.Timing; +import org.apache.curator.utils.CloseableUtils; +import org.apache.zookeeper.WatchedEvent; +import org.apache.zookeeper.Watcher; +import org.junit.jupiter.api.Test; -public class TestBoundedDistributedQueue extends BaseClassForTests -{ - private static final QueueSerializer serializer = new QueueSerializer() - { +public class TestBoundedDistributedQueue extends BaseClassForTests { + private static final QueueSerializer serializer = new QueueSerializer() { @Override - public byte[] serialize(String item) - { + public byte[] serialize(String item) { return item.getBytes(); } @Override - public String deserialize(byte[] bytes) - { + public String deserialize(byte[] bytes) { return new String(bytes); } }; @SuppressWarnings("SynchronizationOnLocalVariableOrMethodParameter") @Test - public void testMulti() throws Exception - { - final String PATH = "/queue"; - final int CLIENT_QTY = 4; - final int MAX_ITEMS = 10; - final int ADD_ITEMS = MAX_ITEMS * 100; + public void testMulti() throws Exception { + final String PATH = "/queue"; + final int CLIENT_QTY = 4; + final int MAX_ITEMS = 10; + final int ADD_ITEMS = MAX_ITEMS * 100; - final QueueConsumer consumer = new QueueConsumer() - { + final QueueConsumer consumer = new QueueConsumer() { @Override - public void consumeMessage(String message) throws Exception - { + public void consumeMessage(String message) throws Exception { Thread.sleep(10); } @Override - public void stateChanged(CuratorFramework client, ConnectionState newState) - { - } + public void stateChanged(CuratorFramework client, ConnectionState newState) {} }; - final Timing timing = new Timing(); - final ExecutorService executor = Executors.newCachedThreadPool(); - ExecutorCompletionService completionService = new ExecutorCompletionService(executor); + final Timing timing = new Timing(); + final ExecutorService executor = Executors.newCachedThreadPool(); + ExecutorCompletionService completionService = new ExecutorCompletionService(executor); - final CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); - try - { + final CuratorFramework client = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); + try { client.start(); client.create().forPath(PATH); - final CountDownLatch isWaitingLatch = new CountDownLatch(1); - final AtomicBoolean isDone = new AtomicBoolean(false); - final List counts = new CopyOnWriteArrayList(); - final Object lock = new Object(); - executor.submit - ( - new Callable() - { - @Override - public Void call() throws Exception - { - Watcher watcher = new Watcher() - { - @Override - public void process(WatchedEvent event) - { - synchronized(lock) - { - lock.notifyAll(); - } - } - }; - - while ( !Thread.currentThread().isInterrupted() && client.getState() == CuratorFrameworkState.STARTED && !isDone.get() ) - { - synchronized(lock) - { - int size = client.getChildren().usingWatcher(watcher).forPath(PATH).size(); - counts.add(size); - isWaitingLatch.countDown(); - lock.wait(); + final CountDownLatch isWaitingLatch = new CountDownLatch(1); + final AtomicBoolean isDone = new AtomicBoolean(false); + final List counts = new CopyOnWriteArrayList(); + final Object lock = new Object(); + executor.submit(new Callable() { + @Override + public Void call() throws Exception { + Watcher watcher = new Watcher() { + @Override + public void process(WatchedEvent event) { + synchronized (lock) { + lock.notifyAll(); } } - return null; + }; + + while (!Thread.currentThread().isInterrupted() + && client.getState() == CuratorFrameworkState.STARTED + && !isDone.get()) { + synchronized (lock) { + int size = client.getChildren() + .usingWatcher(watcher) + .forPath(PATH) + .size(); + counts.add(size); + isWaitingLatch.countDown(); + lock.wait(); + } } + return null; } - ); + }); isWaitingLatch.await(); - for ( int i = 0; i < CLIENT_QTY; ++i ) - { - final int index = i; - completionService.submit - ( - new Callable() - { - @Override - public Void call() throws Exception - { - CuratorFramework client = null; - DistributedQueue queue = null; - - try - { - client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); - client.start(); - queue = QueueBuilder.builder(client, consumer, serializer, PATH).executor(executor).maxItems(MAX_ITEMS).putInBackground(false).lockPath("/locks").buildQueue(); - queue.start(); - - for ( int i = 0; i < ADD_ITEMS; ++i ) - { - queue.put("" + index + "-" + i); - } - } - finally - { - CloseableUtils.closeQuietly(queue); - CloseableUtils.closeQuietly(client); + for (int i = 0; i < CLIENT_QTY; ++i) { + final int index = i; + completionService.submit(new Callable() { + @Override + public Void call() throws Exception { + CuratorFramework client = null; + DistributedQueue queue = null; + + try { + client = CuratorFrameworkFactory.newClient( + server.getConnectString(), + timing.session(), + timing.connection(), + new RetryOneTime(1)); + client.start(); + queue = QueueBuilder.builder(client, consumer, serializer, PATH) + .executor(executor) + .maxItems(MAX_ITEMS) + .putInBackground(false) + .lockPath("/locks") + .buildQueue(); + queue.start(); + + for (int i = 0; i < ADD_ITEMS; ++i) { + queue.put("" + index + "-" + i); } - return null; + } finally { + CloseableUtils.closeQuietly(queue); + CloseableUtils.closeQuietly(client); } + return null; } - ); + }); } - for ( int i = 0; i < CLIENT_QTY; ++i ) - { + for (int i = 0; i < CLIENT_QTY; ++i) { completionService.take().get(); } isDone.set(true); - synchronized(lock) - { + synchronized (lock) { lock.notifyAll(); } - for ( int count : counts ) - { + for (int count : counts) { assertTrue(count <= (MAX_ITEMS * CLIENT_QTY), counts.toString()); } - } - finally - { + } finally { executor.shutdownNow(); CloseableUtils.closeQuietly(client); } } @Test - public void testSimple() throws Exception - { - Timing timing = new Timing(); - DistributedQueue queue = null; - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); - try - { + public void testSimple() throws Exception { + Timing timing = new Timing(); + DistributedQueue queue = null; + CuratorFramework client = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); + try { client.start(); - final List messages = new CopyOnWriteArrayList(); - final CountDownLatch latch = new CountDownLatch(2); - final Semaphore semaphore = new Semaphore(0); - QueueConsumer consumer = new QueueConsumer() - { + final List messages = new CopyOnWriteArrayList(); + final CountDownLatch latch = new CountDownLatch(2); + final Semaphore semaphore = new Semaphore(0); + QueueConsumer consumer = new QueueConsumer() { @Override - public void consumeMessage(String message) throws Exception - { + public void consumeMessage(String message) throws Exception { messages.add(message); semaphore.acquire(); } @Override - public void stateChanged(CuratorFramework client, ConnectionState newState) - { - } + public void stateChanged(CuratorFramework client, ConnectionState newState) {} }; - queue = QueueBuilder.builder(client, consumer, serializer, "/queue").executor(Executors.newSingleThreadExecutor()).maxItems(1).buildQueue(); + queue = QueueBuilder.builder(client, consumer, serializer, "/queue") + .executor(Executors.newSingleThreadExecutor()) + .maxItems(1) + .buildQueue(); queue.start(); - QueuePutListener listener = new QueuePutListener() - { + QueuePutListener listener = new QueuePutListener() { @Override - public void putCompleted(String item) - { + public void putCompleted(String item) { latch.countDown(); } @Override - public void putMultiCompleted(MultiItem items) - { - } + public void putMultiCompleted(MultiItem items) {} }; queue.getPutListenerContainer().addListener(listener); - assertTrue(queue.put("1", timing.milliseconds(), TimeUnit.MILLISECONDS)); // should end up in consumer - assertTrue(queue.put("2", timing.milliseconds(), TimeUnit.MILLISECONDS)); // should sit blocking in DistributedQueue + assertTrue(queue.put("1", timing.milliseconds(), TimeUnit.MILLISECONDS)); // should end up in consumer + assertTrue(queue.put( + "2", timing.milliseconds(), TimeUnit.MILLISECONDS)); // should sit blocking in DistributedQueue assertTrue(timing.awaitLatch(latch)); timing.sleepABit(); assertFalse(queue.put("3", timing.multiple(.5).milliseconds(), TimeUnit.MILLISECONDS)); @@ -251,10 +224,8 @@ public void putMultiCompleted(MultiItem items) assertTrue(queue.put("4", timing.milliseconds(), TimeUnit.MILLISECONDS)); assertTrue(queue.put("5", timing.milliseconds(), TimeUnit.MILLISECONDS)); - for ( int i = 0; i < 5; ++i ) - { - if ( messages.size() == 3 ) - { + for (int i = 0; i < 5; ++i) { + if (messages.size() == 3) { break; } timing.sleepABit(); @@ -262,9 +233,7 @@ public void putMultiCompleted(MultiItem items) timing.sleepABit(); assertEquals(messages, Arrays.asList("1", "2", "3", "4", "5")); - } - finally - { + } finally { CloseableUtils.closeQuietly(queue); CloseableUtils.closeQuietly(client); } diff --git a/curator-recipes/src/test/java/org/apache/curator/framework/recipes/queue/TestDistributedDelayQueue.java b/curator-recipes/src/test/java/org/apache/curator/framework/recipes/queue/TestDistributedDelayQueue.java index 077e06dfc..a633192eb 100644 --- a/curator-recipes/src/test/java/org/apache/curator/framework/recipes/queue/TestDistributedDelayQueue.java +++ b/curator-recipes/src/test/java/org/apache/curator/framework/recipes/queue/TestDistributedDelayQueue.java @@ -23,16 +23,6 @@ import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; - -import org.apache.curator.test.BaseClassForTests; -import org.apache.curator.utils.CloseableUtils; -import org.apache.curator.framework.CuratorFramework; -import org.apache.curator.framework.CuratorFrameworkFactory; -import org.apache.curator.framework.state.ConnectionStateListener; -import org.apache.curator.retry.RetryOneTime; -import org.apache.curator.test.Timing; -import org.junit.jupiter.api.Test; -import org.mockito.Mockito; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; @@ -40,24 +30,33 @@ import java.util.Map; import java.util.Random; import java.util.concurrent.TimeUnit; +import org.apache.curator.framework.CuratorFramework; +import org.apache.curator.framework.CuratorFrameworkFactory; +import org.apache.curator.framework.state.ConnectionStateListener; +import org.apache.curator.retry.RetryOneTime; +import org.apache.curator.test.BaseClassForTests; +import org.apache.curator.test.Timing; +import org.apache.curator.utils.CloseableUtils; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; -public class TestDistributedDelayQueue extends BaseClassForTests -{ +public class TestDistributedDelayQueue extends BaseClassForTests { @Test - public void testLateAddition() throws Exception - { - Timing timing = new Timing(); - DistributedDelayQueue queue = null; - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); + public void testLateAddition() throws Exception { + Timing timing = new Timing(); + DistributedDelayQueue queue = null; + CuratorFramework client = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); client.start(); - try - { - BlockingQueueConsumer consumer = new BlockingQueueConsumer(Mockito.mock(ConnectionStateListener.class)); - queue = QueueBuilder.builder(client, consumer, new LongSerializer(), "/test").buildDelayQueue(); + try { + BlockingQueueConsumer consumer = + new BlockingQueueConsumer(Mockito.mock(ConnectionStateListener.class)); + queue = QueueBuilder.builder(client, consumer, new LongSerializer(), "/test") + .buildDelayQueue(); queue.start(); - queue.put(1L, System.currentTimeMillis() + Integer.MAX_VALUE); // never come out - Long value = consumer.take(1, TimeUnit.SECONDS); + queue.put(1L, System.currentTimeMillis() + Integer.MAX_VALUE); // never come out + Long value = consumer.take(1, TimeUnit.SECONDS); assertNull(value); queue.put(2L, System.currentTimeMillis()); @@ -66,157 +65,146 @@ public void testLateAddition() throws Exception value = consumer.take(1, TimeUnit.SECONDS); assertNull(value); - } - finally - { + } finally { CloseableUtils.closeQuietly(queue); CloseableUtils.closeQuietly(client); } } @Test - public void testBasic() throws Exception - { - Timing timing = new Timing(); - DistributedDelayQueue queue = null; - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); + public void testBasic() throws Exception { + Timing timing = new Timing(); + DistributedDelayQueue queue = null; + CuratorFramework client = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); client.start(); - try - { - BlockingQueueConsumer consumer = new BlockingQueueConsumer(Mockito.mock(ConnectionStateListener.class)); - queue = QueueBuilder.builder(client, consumer, new LongSerializer(), "/test").buildDelayQueue(); + try { + BlockingQueueConsumer consumer = + new BlockingQueueConsumer(Mockito.mock(ConnectionStateListener.class)); + queue = QueueBuilder.builder(client, consumer, new LongSerializer(), "/test") + .buildDelayQueue(); queue.start(); queue.put(1L, System.currentTimeMillis() + 1000); Thread.sleep(100); - assertEquals(consumer.size(), 0); // delay hasn't been reached + assertEquals(consumer.size(), 0); // delay hasn't been reached - Long value = consumer.take(timing.forWaiting().seconds(), TimeUnit.SECONDS); + Long value = consumer.take(timing.forWaiting().seconds(), TimeUnit.SECONDS); assertEquals(value, Long.valueOf(1)); - } - finally - { + } finally { CloseableUtils.closeQuietly(queue); CloseableUtils.closeQuietly(client); } } @Test - public void testSimple() throws Exception - { + public void testSimple() throws Exception { final int QTY = 10; - Timing timing = new Timing(); - DistributedDelayQueue queue = null; - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); + Timing timing = new Timing(); + DistributedDelayQueue queue = null; + CuratorFramework client = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); client.start(); - try - { - BlockingQueueConsumer consumer = new BlockingQueueConsumer(Mockito.mock(ConnectionStateListener.class)); - queue = QueueBuilder.builder(client, consumer, new LongSerializer(), "/test").buildDelayQueue(); + try { + BlockingQueueConsumer consumer = + new BlockingQueueConsumer(Mockito.mock(ConnectionStateListener.class)); + queue = QueueBuilder.builder(client, consumer, new LongSerializer(), "/test") + .buildDelayQueue(); queue.start(); Random random = new Random(); - for ( int i = 0; i < QTY; ++i ) - { - long delay = System.currentTimeMillis() + random.nextInt(100); + for (int i = 0; i < QTY; ++i) { + long delay = System.currentTimeMillis() + random.nextInt(100); queue.put(delay, delay); } - long lastValue = -1; - for ( int i = 0; i < QTY; ++i ) - { - Long value = consumer.take(timing.forWaiting().seconds(), TimeUnit.SECONDS); + long lastValue = -1; + for (int i = 0; i < QTY; ++i) { + Long value = consumer.take(timing.forWaiting().seconds(), TimeUnit.SECONDS); assertNotNull(value); assertTrue(value >= lastValue); lastValue = value; } - } - finally - { + } finally { CloseableUtils.closeQuietly(queue); CloseableUtils.closeQuietly(client); } } - + @Test - public void testSorting() throws Exception - { - Timing timing = new Timing(); + public void testSorting() throws Exception { + Timing timing = new Timing(); - //Need to use a fairly large number to ensure that sorting can take some time. + // Need to use a fairly large number to ensure that sorting can take some time. final int QTY = 1000; final int DELAY_MS = timing.multiple(.1).milliseconds(); - DistributedDelayQueue putQueue = null; - DistributedDelayQueue getQueue = null; - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); + DistributedDelayQueue putQueue = null; + DistributedDelayQueue getQueue = null; + CuratorFramework client = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); client.start(); - try - { - putQueue = QueueBuilder.builder(client, null, new LongSerializer(), "/test2").putInBackground(false).buildDelayQueue(); + try { + putQueue = QueueBuilder.builder(client, null, new LongSerializer(), "/test2") + .putInBackground(false) + .buildDelayQueue(); putQueue.start(); - + Map data = new HashMap(); - - //Make the earliest a second into the future, so we can ensure that everything's - //been added prior to the consumption starting. Otherwise it's possible to start - //processing entries before they've all been added so the ordering will be - //incorrect. + + // Make the earliest a second into the future, so we can ensure that everything's + // been added prior to the consumption starting. Otherwise it's possible to start + // processing entries before they've all been added so the ordering will be + // incorrect. long delay = System.currentTimeMillis() + DELAY_MS; - for ( long i = 0; i < QTY; ++i ) - { + for (long i = 0; i < QTY; ++i) { data.put(delay, i); - - //We want to make the elements close together but not exactly the same MS. + + // We want to make the elements close together but not exactly the same MS. delay += 1; } - - //Randomly sort the list + + // Randomly sort the list List keys = new ArrayList(data.keySet()); Collections.shuffle(keys); - //Put the messages onto the queue in random order, but with the appropriate - //delay and value - for ( Long key : keys ) - { + // Put the messages onto the queue in random order, but with the appropriate + // delay and value + for (Long key : keys) { putQueue.put(data.get(key), key); } - BlockingQueueConsumer consumer = new BlockingQueueConsumer(Mockito.mock(ConnectionStateListener.class)); - getQueue = QueueBuilder.builder(client, consumer, new LongSerializer(), "/test2").putInBackground(false).buildDelayQueue(); + BlockingQueueConsumer consumer = + new BlockingQueueConsumer(Mockito.mock(ConnectionStateListener.class)); + getQueue = QueueBuilder.builder(client, consumer, new LongSerializer(), "/test2") + .putInBackground(false) + .buildDelayQueue(); getQueue.start(); long lastValue = -1; - for ( int i = 0; i < QTY; ++i ) - { + for (int i = 0; i < QTY; ++i) { Long value = consumer.take(DELAY_MS * 2, TimeUnit.MILLISECONDS); assertNotNull(value); assertEquals(value, new Long(lastValue + 1)); lastValue = value; } - } - finally - { + } finally { CloseableUtils.closeQuietly(putQueue); CloseableUtils.closeQuietly(getQueue); CloseableUtils.closeQuietly(client); } } - - private static class LongSerializer implements QueueSerializer - { + private static class LongSerializer implements QueueSerializer { @Override - public byte[] serialize(Long item) - { + public byte[] serialize(Long item) { return Long.toString(item).getBytes(); } @Override - public Long deserialize(byte[] bytes) - { + public Long deserialize(byte[] bytes) { return Long.parseLong(new String(bytes)); } } diff --git a/curator-recipes/src/test/java/org/apache/curator/framework/recipes/queue/TestDistributedIdQueue.java b/curator-recipes/src/test/java/org/apache/curator/framework/recipes/queue/TestDistributedIdQueue.java index dfa9775a1..f43134cd4 100644 --- a/curator-recipes/src/test/java/org/apache/curator/framework/recipes/queue/TestDistributedIdQueue.java +++ b/curator-recipes/src/test/java/org/apache/curator/framework/recipes/queue/TestDistributedIdQueue.java @@ -22,143 +22,127 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import com.google.common.collect.Lists; -import org.apache.curator.test.BaseClassForTests; -import org.apache.curator.utils.CloseableUtils; +import java.util.List; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.state.ConnectionState; import org.apache.curator.framework.state.ConnectionStateListener; import org.apache.curator.retry.RetryOneTime; +import org.apache.curator.test.BaseClassForTests; +import org.apache.curator.utils.CloseableUtils; import org.junit.jupiter.api.Test; import org.mockito.Mockito; -import java.util.List; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; @SuppressWarnings({"SynchronizationOnLocalVariableOrMethodParameter"}) -public class TestDistributedIdQueue extends BaseClassForTests -{ - private static final String QUEUE_PATH = "/a/queue"; +public class TestDistributedIdQueue extends BaseClassForTests { + private static final String QUEUE_PATH = "/a/queue"; - private static final QueueSerializer serializer = new QueueItemSerializer(); + private static final QueueSerializer serializer = new QueueItemSerializer(); @Test - public void testDeletingWithLock() throws Exception - { - DistributedIdQueue queue = null; + public void testDeletingWithLock() throws Exception { + DistributedIdQueue queue = null; CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client.start(); - try - { - final CountDownLatch consumingLatch = new CountDownLatch(1); - final CountDownLatch waitLatch = new CountDownLatch(1); - QueueConsumer consumer = new QueueConsumer() - { + try { + final CountDownLatch consumingLatch = new CountDownLatch(1); + final CountDownLatch waitLatch = new CountDownLatch(1); + QueueConsumer consumer = new QueueConsumer() { @Override - public void consumeMessage(TestQueueItem message) throws Exception - { + public void consumeMessage(TestQueueItem message) throws Exception { consumingLatch.countDown(); waitLatch.await(); } @Override - public void stateChanged(CuratorFramework client, ConnectionState newState) - { - } + public void stateChanged(CuratorFramework client, ConnectionState newState) {} }; - queue = QueueBuilder.builder(client, consumer, serializer, QUEUE_PATH).lockPath("/locks").buildIdQueue(); + queue = QueueBuilder.builder(client, consumer, serializer, QUEUE_PATH) + .lockPath("/locks") + .buildIdQueue(); queue.start(); queue.put(new TestQueueItem("test"), "id"); - - assertTrue(consumingLatch.await(10, TimeUnit.SECONDS)); // wait until consumer has it + + assertTrue(consumingLatch.await(10, TimeUnit.SECONDS)); // wait until consumer has it assertEquals(queue.remove("id"), 0); waitLatch.countDown(); - } - finally - { + } finally { CloseableUtils.closeQuietly(queue); CloseableUtils.closeQuietly(client); } } @Test - public void testOrdering() throws Exception - { - final int ITEM_QTY = 100; + public void testOrdering() throws Exception { + final int ITEM_QTY = 100; - DistributedIdQueue queue = null; + DistributedIdQueue queue = null; CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client.start(); - try - { - BlockingQueueConsumer consumer = new BlockingQueueConsumer(Mockito.mock(ConnectionStateListener.class)); + try { + BlockingQueueConsumer consumer = + new BlockingQueueConsumer(Mockito.mock(ConnectionStateListener.class)); - queue = QueueBuilder.builder(client, consumer, serializer, QUEUE_PATH).buildIdQueue(); + queue = QueueBuilder.builder(client, consumer, serializer, QUEUE_PATH) + .buildIdQueue(); queue.start(); - - List ids = Lists.newArrayList(); - for ( int i = 0; i < ITEM_QTY; ++i ) - { - String id = Double.toString(Math.random()); + + List ids = Lists.newArrayList(); + for (int i = 0; i < ITEM_QTY; ++i) { + String id = Double.toString(Math.random()); ids.add(id); queue.put(new TestQueueItem(id), id); } - int iteration = 0; - while ( consumer.size() < ITEM_QTY ) - { + int iteration = 0; + while (consumer.size() < ITEM_QTY) { assertTrue(++iteration < ITEM_QTY); Thread.sleep(1000); } - int i = 0; - for ( TestQueueItem item : consumer.getItems() ) - { + int i = 0; + for (TestQueueItem item : consumer.getItems()) { assertEquals(item.str, ids.get(i++)); } - } - finally - { + } finally { CloseableUtils.closeQuietly(queue); CloseableUtils.closeQuietly(client); } } @Test - public void testRequeuingWithLock() throws Exception - { - DistributedIdQueue queue = null; + public void testRequeuingWithLock() throws Exception { + DistributedIdQueue queue = null; CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client.start(); - try - { - final CountDownLatch consumingLatch = new CountDownLatch(1); + try { + final CountDownLatch consumingLatch = new CountDownLatch(1); - QueueConsumer consumer = new QueueConsumer() - { + QueueConsumer consumer = new QueueConsumer() { @Override - public void consumeMessage(TestQueueItem message) throws Exception - { + public void consumeMessage(TestQueueItem message) throws Exception { consumingLatch.countDown(); // Throw an exception so requeuing occurs throw new Exception("Consumer failed"); } @Override - public void stateChanged(CuratorFramework client, ConnectionState newState) - { - } + public void stateChanged(CuratorFramework client, ConnectionState newState) {} }; - queue = QueueBuilder.builder(client, consumer, serializer, QUEUE_PATH).lockPath("/locks").buildIdQueue(); + queue = QueueBuilder.builder(client, consumer, serializer, QUEUE_PATH) + .lockPath("/locks") + .buildIdQueue(); queue.start(); queue.put(new TestQueueItem("test"), "id"); - assertTrue(consumingLatch.await(10, TimeUnit.SECONDS)); // wait until consumer has it + assertTrue(consumingLatch.await(10, TimeUnit.SECONDS)); // wait until consumer has it // Sleep one more second @@ -166,9 +150,7 @@ public void stateChanged(CuratorFramework client, ConnectionState newState) assertTrue(queue.debugIsQueued("id")); - } - finally - { + } finally { CloseableUtils.closeQuietly(queue); CloseableUtils.closeQuietly(client); } diff --git a/curator-recipes/src/test/java/org/apache/curator/framework/recipes/queue/TestDistributedPriorityQueue.java b/curator-recipes/src/test/java/org/apache/curator/framework/recipes/queue/TestDistributedPriorityQueue.java index f763f013d..04786db97 100644 --- a/curator-recipes/src/test/java/org/apache/curator/framework/recipes/queue/TestDistributedPriorityQueue.java +++ b/curator-recipes/src/test/java/org/apache/curator/framework/recipes/queue/TestDistributedPriorityQueue.java @@ -23,91 +23,86 @@ import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; - -import org.apache.curator.test.BaseClassForTests; -import org.apache.curator.utils.CloseableUtils; +import java.util.ArrayList; +import java.util.List; +import java.util.Random; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.SynchronousQueue; +import java.util.concurrent.TimeUnit; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.state.ConnectionState; import org.apache.curator.framework.state.ConnectionStateListener; import org.apache.curator.retry.RetryOneTime; +import org.apache.curator.test.BaseClassForTests; import org.apache.curator.test.Timing; +import org.apache.curator.utils.CloseableUtils; import org.junit.jupiter.api.Test; import org.mockito.Mockito; -import java.util.ArrayList; -import java.util.List; -import java.util.Random; -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.SynchronousQueue; -import java.util.concurrent.TimeUnit; -public class TestDistributedPriorityQueue extends BaseClassForTests -{ +public class TestDistributedPriorityQueue extends BaseClassForTests { @Test - public void testMinItemsBeforeRefresh() throws Exception - { - DistributedPriorityQueue queue = null; + public void testMinItemsBeforeRefresh() throws Exception { + DistributedPriorityQueue queue = null; CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client.start(); - try - { + try { final int minItemsBeforeRefresh = 3; - BlockingQueueConsumer consumer = new BlockingQueueConsumer(Mockito.mock(ConnectionStateListener.class)); - queue = QueueBuilder.builder(client, consumer, new IntSerializer(), "/test").buildPriorityQueue(minItemsBeforeRefresh); + BlockingQueueConsumer consumer = + new BlockingQueueConsumer(Mockito.mock(ConnectionStateListener.class)); + queue = QueueBuilder.builder(client, consumer, new IntSerializer(), "/test") + .buildPriorityQueue(minItemsBeforeRefresh); queue.start(); - for ( int i = 0; i < 10; ++i ) - { + for (int i = 0; i < 10; ++i) { queue.put(i, 10 + i); } assertEquals(consumer.take(1, TimeUnit.SECONDS), new Integer(0)); queue.put(1000, 1); // lower priority - int count = 0; - while ( consumer.take(1, TimeUnit.SECONDS) < 1000 ) - { + int count = 0; + while (consumer.take(1, TimeUnit.SECONDS) < 1000) { ++count; } - assertTrue(Math.abs(minItemsBeforeRefresh - count) < minItemsBeforeRefresh, String.format("Diff: %d - min: %d", Math.abs(minItemsBeforeRefresh - count), minItemsBeforeRefresh)); // allows for some slack - testing that within a slop value the newly inserted item with lower priority comes out - } - finally - { + assertTrue( + Math.abs(minItemsBeforeRefresh - count) < minItemsBeforeRefresh, + String.format( + "Diff: %d - min: %d", + Math.abs(minItemsBeforeRefresh - count), + minItemsBeforeRefresh)); // allows for some slack - testing that within a slop value the + // newly inserted item with lower priority comes out + } finally { CloseableUtils.closeQuietly(queue); CloseableUtils.closeQuietly(client); } } @Test - public void testSortingWhileTaking() throws Exception - { - Timing timing = new Timing(); - DistributedPriorityQueue queue = null; - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); + public void testSortingWhileTaking() throws Exception { + Timing timing = new Timing(); + DistributedPriorityQueue queue = null; + CuratorFramework client = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); client.start(); - try - { - final BlockingQueue blockingQueue = new SynchronousQueue(); - QueueConsumer consumer = new QueueConsumer() - { + try { + final BlockingQueue blockingQueue = new SynchronousQueue(); + QueueConsumer consumer = new QueueConsumer() { @Override - public void consumeMessage(Integer message) throws Exception - { + public void consumeMessage(Integer message) throws Exception { blockingQueue.put(message); } @Override - public void stateChanged(CuratorFramework client, ConnectionState newState) - { - } + public void stateChanged(CuratorFramework client, ConnectionState newState) {} }; - queue = QueueBuilder.builder(client, consumer, new IntSerializer(), "/test").buildPriorityQueue(0); + queue = QueueBuilder.builder(client, consumer, new IntSerializer(), "/test") + .buildPriorityQueue(0); queue.start(); - for ( int i = 0; i < 10; ++i ) - { + for (int i = 0; i < 10; ++i) { queue.put(i, 10); } @@ -115,153 +110,143 @@ public void stateChanged(CuratorFramework client, ConnectionState newState) timing.sleepABit(); queue.put(1000, 1); // lower priority timing.sleepABit(); - assertEquals(blockingQueue.poll(timing.seconds(), TimeUnit.SECONDS), new Integer(1)); // is in consumer already + assertEquals( + blockingQueue.poll(timing.seconds(), TimeUnit.SECONDS), new Integer(1)); // is in consumer already assertEquals(blockingQueue.poll(timing.seconds(), TimeUnit.SECONDS), new Integer(1000)); - } - finally - { + } finally { CloseableUtils.closeQuietly(queue); CloseableUtils.closeQuietly(client); } } @Test - public void testAdditions() throws Exception - { - DistributedPriorityQueue queue = null; + public void testAdditions() throws Exception { + DistributedPriorityQueue queue = null; CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client.start(); - try - { - final CountDownLatch latch = new CountDownLatch(1); - QueueSerializer serializer = new IntSerializer() - { + try { + final CountDownLatch latch = new CountDownLatch(1); + QueueSerializer serializer = new IntSerializer() { @Override - public Integer deserialize(byte[] bytes) - { + public Integer deserialize(byte[] bytes) { // gets called in the Queue's event processing thread - try - { + try { latch.await(); - } - catch ( InterruptedException e ) - { + } catch (InterruptedException e) { // ignore } return super.deserialize(bytes); } }; - BlockingQueueConsumer consumer = new BlockingQueueConsumer(Mockito.mock(ConnectionStateListener.class)); + BlockingQueueConsumer consumer = + new BlockingQueueConsumer(Mockito.mock(ConnectionStateListener.class)); queue = QueueBuilder.builder(client, consumer, serializer, "/test").buildPriorityQueue(1); queue.start(); - for ( int i = 0; i < 10; ++i ) - { + for (int i = 0; i < 10; ++i) { queue.put(10, 10); - if ( i == 0 ) - { + if (i == 0) { queue.put(1, 1); latch.countDown(); } } assertOrdering(consumer, 10); - } - finally - { + } finally { CloseableUtils.closeQuietly(queue); CloseableUtils.closeQuietly(client); } } @Test - public void testSimple() throws Exception - { - List nums = new ArrayList(); + public void testSimple() throws Exception { + List nums = new ArrayList(); - Timing timing = new Timing(); - DistributedPriorityQueue queue = null; - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); + Timing timing = new Timing(); + DistributedPriorityQueue queue = null; + CuratorFramework client = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); client.start(); - try - { - final CountDownLatch hasConsumedLatch = new CountDownLatch(1); - final CountDownLatch okToConsumeLatch = new CountDownLatch(1); - BlockingQueueConsumer consumer = new BlockingQueueConsumer(Mockito.mock(ConnectionStateListener.class)) - { - @Override - public void consumeMessage(Integer message) throws Exception - { - hasConsumedLatch.countDown(); - okToConsumeLatch.await(); - super.consumeMessage(message); - } - }; - queue = QueueBuilder.builder(client, consumer, new IntSerializer(), "/test").buildPriorityQueue(0); + try { + final CountDownLatch hasConsumedLatch = new CountDownLatch(1); + final CountDownLatch okToConsumeLatch = new CountDownLatch(1); + BlockingQueueConsumer consumer = + new BlockingQueueConsumer(Mockito.mock(ConnectionStateListener.class)) { + @Override + public void consumeMessage(Integer message) throws Exception { + hasConsumedLatch.countDown(); + okToConsumeLatch.await(); + super.consumeMessage(message); + } + }; + queue = QueueBuilder.builder(client, consumer, new IntSerializer(), "/test") + .buildPriorityQueue(0); queue.start(); nums.add(Integer.MIN_VALUE); - queue.put(Integer.MIN_VALUE, Integer.MIN_VALUE); // the queue background thread will be blocking with the first item - make sure it's the lowest value + queue.put( + Integer.MIN_VALUE, + Integer.MIN_VALUE); // the queue background thread will be blocking with the first item - make sure + // it's the lowest value assertTrue(timing.awaitLatch(hasConsumedLatch)); - Random random = new Random(); - for ( int i = 0; i < 100; ++i ) - { - int priority = random.nextInt(); + Random random = new Random(); + for (int i = 0; i < 100; ++i) { + int priority = random.nextInt(); nums.add(priority); queue.put(priority, priority); } - while ( queue.getCache().getData().children.size() < (nums.size() - 1) ) // -1 because the first message has already been consumed + while (queue.getCache().getData().children.size() + < (nums.size() - 1)) // -1 because the first message has already been consumed { timing.sleepABit(); // wait for the cache to catch up } okToConsumeLatch.countDown(); assertOrdering(consumer, nums.size()); - } - catch ( AssertionError e ) - { - StringBuilder message = new StringBuilder(e.getMessage()); - for ( int i : nums ) - { - message.append(i).append("\t").append(DistributedPriorityQueue.priorityToString(i)).append("\n"); + } catch (AssertionError e) { + StringBuilder message = new StringBuilder(e.getMessage()); + for (int i : nums) { + message.append(i) + .append("\t") + .append(DistributedPriorityQueue.priorityToString(i)) + .append("\n"); } fail(message.toString()); - } - finally - { + } finally { CloseableUtils.closeQuietly(queue); CloseableUtils.closeQuietly(client); } } - private void assertOrdering(BlockingQueueConsumer consumer, int qty) throws Exception - { - int previous = 0; - for ( int i = 0; i < qty; ++i ) - { - Integer value = consumer.take(10, TimeUnit.SECONDS); + private void assertOrdering(BlockingQueueConsumer consumer, int qty) throws Exception { + int previous = 0; + for (int i = 0; i < qty; ++i) { + Integer value = consumer.take(10, TimeUnit.SECONDS); assertNotNull(value); - if ( i > 0 ) - { - assertTrue(value >= previous, String.format("Value: (%d:%s) Previous: (%d:%s)", value, DistributedPriorityQueue.priorityToString(value), previous, DistributedPriorityQueue.priorityToString(previous))); + if (i > 0) { + assertTrue( + value >= previous, + String.format( + "Value: (%d:%s) Previous: (%d:%s)", + value, + DistributedPriorityQueue.priorityToString(value), + previous, + DistributedPriorityQueue.priorityToString(previous))); } previous = value; } } - private static class IntSerializer implements QueueSerializer - { + private static class IntSerializer implements QueueSerializer { @Override - public byte[] serialize(Integer item) - { + public byte[] serialize(Integer item) { return Integer.toString(item).getBytes(); } @Override - public Integer deserialize(byte[] bytes) - { + public Integer deserialize(byte[] bytes) { return Integer.parseInt(new String(bytes)); } } diff --git a/curator-recipes/src/test/java/org/apache/curator/framework/recipes/queue/TestDistributedQueue.java b/curator-recipes/src/test/java/org/apache/curator/framework/recipes/queue/TestDistributedQueue.java index 3378333f4..43f088407 100644 --- a/curator-recipes/src/test/java/org/apache/curator/framework/recipes/queue/TestDistributedQueue.java +++ b/curator-recipes/src/test/java/org/apache/curator/framework/recipes/queue/TestDistributedQueue.java @@ -25,22 +25,8 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import com.google.common.collect.Lists; import com.google.common.collect.Sets; -import org.apache.curator.test.BaseClassForTests; -import org.apache.curator.utils.CloseableUtils; import com.google.common.util.concurrent.MoreExecutors; import com.google.common.util.concurrent.ThreadFactoryBuilder; -import org.apache.curator.framework.CuratorFramework; -import org.apache.curator.framework.CuratorFrameworkFactory; -import org.apache.curator.framework.api.BackgroundCallback; -import org.apache.curator.framework.imps.CuratorFrameworkState; -import org.apache.curator.framework.state.ConnectionState; -import org.apache.curator.framework.state.ConnectionStateListener; -import org.apache.curator.retry.ExponentialBackoffRetry; -import org.apache.curator.retry.RetryOneTime; -import org.apache.curator.test.Timing; -import org.apache.zookeeper.CreateMode; -import org.junit.jupiter.api.Test; -import org.mockito.Mockito; import java.util.ArrayList; import java.util.List; import java.util.Set; @@ -53,259 +39,241 @@ import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; +import org.apache.curator.framework.CuratorFramework; +import org.apache.curator.framework.CuratorFrameworkFactory; +import org.apache.curator.framework.api.BackgroundCallback; +import org.apache.curator.framework.imps.CuratorFrameworkState; +import org.apache.curator.framework.state.ConnectionState; +import org.apache.curator.framework.state.ConnectionStateListener; +import org.apache.curator.retry.ExponentialBackoffRetry; +import org.apache.curator.retry.RetryOneTime; +import org.apache.curator.test.BaseClassForTests; +import org.apache.curator.test.Timing; +import org.apache.curator.utils.CloseableUtils; +import org.apache.zookeeper.CreateMode; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; @SuppressWarnings({"SynchronizationOnLocalVariableOrMethodParameter"}) -public class TestDistributedQueue extends BaseClassForTests -{ - private static final String QUEUE_PATH = "/a/queue"; +public class TestDistributedQueue extends BaseClassForTests { + private static final String QUEUE_PATH = "/a/queue"; - private static final QueueSerializer serializer = new QueueItemSerializer(); + private static final QueueSerializer serializer = new QueueItemSerializer(); @Test - public void testRetryAfterFailure_Curator56() throws Exception - { + public void testRetryAfterFailure_Curator56() throws Exception { /* - https://issues.apache.org/jira/browse/CURATOR-56 + https://issues.apache.org/jira/browse/CURATOR-56 - This tests against ever growing node name bug - */ + This tests against ever growing node name bug + */ DistributedQueue queue = null; - final CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); + final CuratorFramework client = + CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client.start(); - try - { + try { final int RETRY_COUNT = 1; final CountDownLatch retryCounter = new CountDownLatch(RETRY_COUNT + 1); final List names = new ArrayList(); - QueueConsumer consumer = new QueueConsumer() - { + QueueConsumer consumer = new QueueConsumer() { @Override - public void consumeMessage(TestQueueItem messsage) throws Exception - { + public void consumeMessage(TestQueueItem messsage) throws Exception { List queueItems = client.getChildren().forPath(QUEUE_PATH); names.add(queueItems.get(0)); - if (retryCounter.getCount() > 1) - { + if (retryCounter.getCount() > 1) { retryCounter.countDown(); throw new Exception("Something went wrong"); - } - else - { + } else { retryCounter.countDown(); } } @Override - public void stateChanged(CuratorFramework client, ConnectionState newState) - { - } + public void stateChanged(CuratorFramework client, ConnectionState newState) {} }; queue = QueueBuilder.builder(client, consumer, serializer, QUEUE_PATH) - .lockPath("/lock") - .buildQueue(); + .lockPath("/lock") + .buildQueue(); queue.start(); queue.put(new TestQueueItem("test")); retryCounter.await(10, TimeUnit.SECONDS); - assertEquals(retryCounter.getCount(), 0, "Queue item was not consumed. Retry counter is " + retryCounter.getCount()); + assertEquals( + retryCounter.getCount(), + 0, + "Queue item was not consumed. Retry counter is " + retryCounter.getCount()); assertEquals(names.size(), 2); - assertEquals(names.get(0).length(), names.get(1).length(), "name1: " + names.get(0) + " - " + "name2: " + names.get(1)); - } - finally - { + assertEquals( + names.get(0).length(), + names.get(1).length(), + "name1: " + names.get(0) + " - " + "name2: " + names.get(1)); + } finally { CloseableUtils.closeQuietly(queue); CloseableUtils.closeQuietly(client); } } @Test - public void testCustomExecutor() throws Exception - { - final int ITERATIONS = 1000; + public void testCustomExecutor() throws Exception { + final int ITERATIONS = 1000; - Timing timing = new Timing(); - DistributedQueue queue = null; - final CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); + Timing timing = new Timing(); + DistributedQueue queue = null; + final CuratorFramework client = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); client.start(); - try - { - final CountDownLatch latch = new CountDownLatch(ITERATIONS); - QueueConsumer consumer = new QueueConsumer() - { + try { + final CountDownLatch latch = new CountDownLatch(ITERATIONS); + QueueConsumer consumer = new QueueConsumer() { @Override - public void consumeMessage(String message) throws Exception - { + public void consumeMessage(String message) throws Exception { latch.countDown(); } @Override - public void stateChanged(CuratorFramework client, ConnectionState newState) - { - } + public void stateChanged(CuratorFramework client, ConnectionState newState) {} }; - QueueSerializer serializer = new QueueSerializer() - { + QueueSerializer serializer = new QueueSerializer() { @Override - public byte[] serialize(String item) - { + public byte[] serialize(String item) { return item.getBytes(); } @Override - public String deserialize(byte[] bytes) - { + public String deserialize(byte[] bytes) { return new String(bytes); } }; - Executor executor = Executors.newCachedThreadPool(); - - final Set used = Sets.newHashSet(); - final Set doubleUsed = Sets.newHashSet(); - queue = new DistributedQueue - ( - client, - consumer, - serializer, - QUEUE_PATH, - QueueBuilder.defaultThreadFactory, - executor, - Integer.MAX_VALUE, - false, - "/lock", - QueueBuilder.NOT_SET, - true, - timing.milliseconds() - ) - { - @SuppressWarnings("SimplifiableConditionalExpression") - @Override - protected boolean processWithLockSafety(String itemNode, DistributedQueue.ProcessType type) throws Exception - { - if ( used.contains(itemNode) ) - { - doubleUsed.add(itemNode); - } - else - { - used.add(itemNode); - } - return (client.getState() == CuratorFrameworkState.STARTED) ? super.processWithLockSafety(itemNode, type) : false; - } - }; + Executor executor = Executors.newCachedThreadPool(); + + final Set used = Sets.newHashSet(); + final Set doubleUsed = Sets.newHashSet(); + queue = + new DistributedQueue( + client, + consumer, + serializer, + QUEUE_PATH, + QueueBuilder.defaultThreadFactory, + executor, + Integer.MAX_VALUE, + false, + "/lock", + QueueBuilder.NOT_SET, + true, + timing.milliseconds()) { + @SuppressWarnings("SimplifiableConditionalExpression") + @Override + protected boolean processWithLockSafety(String itemNode, DistributedQueue.ProcessType type) + throws Exception { + if (used.contains(itemNode)) { + doubleUsed.add(itemNode); + } else { + used.add(itemNode); + } + return (client.getState() == CuratorFrameworkState.STARTED) + ? super.processWithLockSafety(itemNode, type) + : false; + } + }; queue.start(); - for ( int i = 0; i < ITERATIONS; ++i ) - { + for (int i = 0; i < ITERATIONS; ++i) { queue.put(Integer.toString(i)); } assertTrue(timing.awaitLatch(latch)); assertTrue(doubleUsed.size() == 0, doubleUsed.toString()); - } - finally - { + } finally { CloseableUtils.closeQuietly(queue); CloseableUtils.closeQuietly(client); } } @Test - public void testPutListener() throws Exception - { - final int itemQty = 10; + public void testPutListener() throws Exception { + final int itemQty = 10; - DistributedQueue queue = null; + DistributedQueue queue = null; CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client.start(); - try - { - BlockingQueueConsumer consumer = new BlockingQueueConsumer(Mockito.mock(ConnectionStateListener.class)); + try { + BlockingQueueConsumer consumer = + new BlockingQueueConsumer(Mockito.mock(ConnectionStateListener.class)); - queue = QueueBuilder.builder(client, consumer, serializer, QUEUE_PATH).buildQueue(); + queue = QueueBuilder.builder(client, consumer, serializer, QUEUE_PATH) + .buildQueue(); queue.start(); - QueueTestProducer producer = new QueueTestProducer(queue, itemQty, 0); + QueueTestProducer producer = new QueueTestProducer(queue, itemQty, 0); - final AtomicInteger listenerCalls = new AtomicInteger(0); - QueuePutListener listener = new QueuePutListener() - { + final AtomicInteger listenerCalls = new AtomicInteger(0); + QueuePutListener listener = new QueuePutListener() { @Override - public void putCompleted(TestQueueItem item) - { + public void putCompleted(TestQueueItem item) { listenerCalls.incrementAndGet(); } @Override - public void putMultiCompleted(MultiItem items) - { - } + public void putMultiCompleted(MultiItem items) {} }; queue.getPutListenerContainer().addListener(listener); - ExecutorService service = Executors.newCachedThreadPool(); + ExecutorService service = Executors.newCachedThreadPool(); service.submit(producer); - int iteration = 0; - while ( consumer.size() < itemQty ) - { + int iteration = 0; + while (consumer.size() < itemQty) { assertTrue(++iteration < 10); Thread.sleep(1000); } - int i = 0; - for ( TestQueueItem item : consumer.getItems() ) - { + int i = 0; + for (TestQueueItem item : consumer.getItems()) { assertEquals(item.str, Integer.toString(i++)); } - + assertEquals(listenerCalls.get(), itemQty); - } - finally - { + } finally { CloseableUtils.closeQuietly(queue); CloseableUtils.closeQuietly(client); } } - + @Test - public void testErrorMode() throws Exception - { - Timing timing = new Timing(); - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); + public void testErrorMode() throws Exception { + Timing timing = new Timing(); + CuratorFramework client = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); client.start(); - try - { - final AtomicReference latch = new AtomicReference(new CountDownLatch(1)); - final AtomicInteger count = new AtomicInteger(0); - QueueConsumer consumer = new QueueConsumer() - { + try { + final AtomicReference latch = new AtomicReference(new CountDownLatch(1)); + final AtomicInteger count = new AtomicInteger(0); + QueueConsumer consumer = new QueueConsumer() { @Override - public void consumeMessage(TestQueueItem message) throws Exception - { - if ( count.incrementAndGet() < 2 ) - { + public void consumeMessage(TestQueueItem message) throws Exception { + if (count.incrementAndGet() < 2) { throw new Exception(); } latch.get().countDown(); } @Override - public void stateChanged(CuratorFramework client, ConnectionState newState) - { - } + public void stateChanged(CuratorFramework client, ConnectionState newState) {} }; - DistributedQueue queue = QueueBuilder.builder(client, consumer, serializer, QUEUE_PATH).lockPath("/locks").buildQueue(); - try - { + DistributedQueue queue = QueueBuilder.builder(client, consumer, serializer, QUEUE_PATH) + .lockPath("/locks") + .buildQueue(); + try { queue.start(); - TestQueueItem item = new TestQueueItem("1"); + TestQueueItem item = new TestQueueItem("1"); queue.put(item); assertTrue(timing.awaitLatch(latch.get())); @@ -321,68 +289,53 @@ public void stateChanged(CuratorFramework client, ConnectionState newState) assertFalse(latch.get().await(5, TimeUnit.SECONDS)); // consumer should get called only once assertEquals(count.get(), 1); - } - finally - { + } finally { queue.close(); } - } - finally - { + } finally { client.close(); } } @Test - public void testNoDuplicateProcessing() throws Exception - { - final int itemQty = 1000; - final int consumerQty = 4; + public void testNoDuplicateProcessing() throws Exception { + final int itemQty = 1000; + final int consumerQty = 4; - Timing timing = new Timing(); + Timing timing = new Timing(); - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new ExponentialBackoffRetry(100, 3)); + CuratorFramework client = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), timing.connection(), new ExponentialBackoffRetry(100, 3)); client.start(); - try - { - DistributedQueue producerQueue = QueueBuilder.builder(client, null, serializer, QUEUE_PATH).buildQueue(); - try - { + try { + DistributedQueue producerQueue = + QueueBuilder.builder(client, null, serializer, QUEUE_PATH).buildQueue(); + try { producerQueue.start(); - for ( int i = 0; i < itemQty; ++i ) - { - TestQueueItem item = new TestQueueItem(Integer.toString(i)); + for (int i = 0; i < itemQty; ++i) { + TestQueueItem item = new TestQueueItem(Integer.toString(i)); producerQueue.put(item); } producerQueue.flushPuts(timing.multiple(2).seconds(), TimeUnit.SECONDS); - } - finally - { + } finally { producerQueue.close(); } - } - finally - { + } finally { client.close(); } - final Set consumedMessages = Sets.newHashSet(); - final Set duplicateMessages = Sets.newHashSet(); + final Set consumedMessages = Sets.newHashSet(); + final Set duplicateMessages = Sets.newHashSet(); - final CountDownLatch latch = new CountDownLatch(itemQty); - List> consumers = Lists.newArrayList(); - List consumerClients = Lists.newArrayList(); - try - { - final QueueConsumer ourQueue = new QueueConsumer() - { + final CountDownLatch latch = new CountDownLatch(itemQty); + List> consumers = Lists.newArrayList(); + List consumerClients = Lists.newArrayList(); + try { + final QueueConsumer ourQueue = new QueueConsumer() { @Override - public void consumeMessage(TestQueueItem message) - { - synchronized(consumedMessages) - { - if ( consumedMessages.contains(message.str) ) - { + public void consumeMessage(TestQueueItem message) { + synchronized (consumedMessages) { + if (consumedMessages.contains(message.str)) { duplicateMessages.add(message.str); } consumedMessages.add(message.str); @@ -391,158 +344,139 @@ public void consumeMessage(TestQueueItem message) } @Override - public void stateChanged(CuratorFramework client, ConnectionState newState) - { - } + public void stateChanged(CuratorFramework client, ConnectionState newState) {} }; - for ( int i = 0; i < consumerQty; ++i ) - { - CuratorFramework thisClient = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); + for (int i = 0; i < consumerQty; ++i) { + CuratorFramework thisClient = + CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); consumerClients.add(thisClient); thisClient.start(); - DistributedQueue thisConsumer = QueueBuilder.builder(thisClient, ourQueue, serializer, QUEUE_PATH). - lockPath("/a/locks"). - buildQueue(); + DistributedQueue thisConsumer = QueueBuilder.builder( + thisClient, ourQueue, serializer, QUEUE_PATH) + .lockPath("/a/locks") + .buildQueue(); consumers.add(thisConsumer); } - for ( DistributedQueue consumer : consumers ) - { + for (DistributedQueue consumer : consumers) { consumer.start(); } timing.awaitLatch(latch); assertTrue(duplicateMessages.size() == 0, duplicateMessages.toString()); - } - finally - { - for ( DistributedQueue consumer : consumers ) - { - CloseableUtils.closeQuietly(consumer); + } finally { + for (DistributedQueue consumer : consumers) { + CloseableUtils.closeQuietly(consumer); } - for ( CuratorFramework curatorFramework : consumerClients ) - { + for (CuratorFramework curatorFramework : consumerClients) { CloseableUtils.closeQuietly(curatorFramework); } } } @Test - public void testSafetyWithCrash() throws Exception - { - final int itemQty = 100; - - DistributedQueue producerQueue = null; - DistributedQueue consumerQueue1 = null; - DistributedQueue consumerQueue2 = null; - - CuratorFramework producerClient = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); - CuratorFramework consumerClient1 = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); - CuratorFramework consumerClient2 = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); - try - { + public void testSafetyWithCrash() throws Exception { + final int itemQty = 100; + + DistributedQueue producerQueue = null; + DistributedQueue consumerQueue1 = null; + DistributedQueue consumerQueue2 = null; + + CuratorFramework producerClient = + CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); + CuratorFramework consumerClient1 = + CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); + CuratorFramework consumerClient2 = + CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); + try { producerClient.start(); consumerClient1.start(); consumerClient2.start(); - ExecutorService service = Executors.newCachedThreadPool(); + ExecutorService service = Executors.newCachedThreadPool(); // make the producer queue { - producerQueue = QueueBuilder.builder(producerClient, null, serializer, QUEUE_PATH).buildQueue(); + producerQueue = QueueBuilder.builder(producerClient, null, serializer, QUEUE_PATH) + .buildQueue(); producerQueue.start(); QueueTestProducer producer = new QueueTestProducer(producerQueue, itemQty, 0); service.submit(producer); } - final Set takenItems = Sets.newTreeSet(); - final Set takenItemsForConsumer1 = Sets.newTreeSet(); - final Set takenItemsForConsumer2 = Sets.newTreeSet(); - final AtomicReference thrownItemFromConsumer1 = new AtomicReference(null); + final Set takenItems = Sets.newTreeSet(); + final Set takenItemsForConsumer1 = Sets.newTreeSet(); + final Set takenItemsForConsumer2 = Sets.newTreeSet(); + final AtomicReference thrownItemFromConsumer1 = new AtomicReference(null); // make the first consumer queue { - final QueueConsumer ourQueue = new QueueConsumer() - { + final QueueConsumer ourQueue = new QueueConsumer() { @Override - public void consumeMessage(TestQueueItem message) throws Exception - { - synchronized(takenItems) - { - if ( takenItems.size() > 10 ) - { + public void consumeMessage(TestQueueItem message) throws Exception { + synchronized (takenItems) { + if (takenItems.size() > 10) { thrownItemFromConsumer1.set(message); - throw new Exception("dummy"); // simulate a crash + throw new Exception("dummy"); // simulate a crash } } - + addToTakenItems(message, takenItems, itemQty); - synchronized(takenItemsForConsumer1) - { + synchronized (takenItemsForConsumer1) { takenItemsForConsumer1.add(message); } - Thread.sleep((long)(Math.random() * 5)); + Thread.sleep((long) (Math.random() * 5)); } @Override - public void stateChanged(CuratorFramework client, ConnectionState newState) - { - } + public void stateChanged(CuratorFramework client, ConnectionState newState) {} }; - consumerQueue1 = QueueBuilder.builder(consumerClient1, ourQueue, serializer, QUEUE_PATH). - lockPath("/a/locks"). - buildQueue(); + consumerQueue1 = QueueBuilder.builder(consumerClient1, ourQueue, serializer, QUEUE_PATH) + .lockPath("/a/locks") + .buildQueue(); consumerQueue1.start(); } // make the second consumer queue { - final QueueConsumer ourQueue = new QueueConsumer() - { + final QueueConsumer ourQueue = new QueueConsumer() { @Override - public void consumeMessage(TestQueueItem message) throws Exception - { + public void consumeMessage(TestQueueItem message) throws Exception { addToTakenItems(message, takenItems, itemQty); - synchronized(takenItemsForConsumer2) - { + synchronized (takenItemsForConsumer2) { takenItemsForConsumer2.add(message); } - Thread.sleep((long)(Math.random() * 5)); + Thread.sleep((long) (Math.random() * 5)); } @Override - public void stateChanged(CuratorFramework client, ConnectionState newState) - { - } + public void stateChanged(CuratorFramework client, ConnectionState newState) {} }; - consumerQueue2 = QueueBuilder.builder(consumerClient2, ourQueue, serializer, QUEUE_PATH). - lockPath("/a/locks"). - buildQueue(); + consumerQueue2 = QueueBuilder.builder(consumerClient2, ourQueue, serializer, QUEUE_PATH) + .lockPath("/a/locks") + .buildQueue(); consumerQueue2.start(); } - synchronized(takenItems) - { - while ( takenItems.size() < itemQty ) - { + synchronized (takenItems) { + while (takenItems.size() < itemQty) { takenItems.wait(1000); } } - int i = 0; - for ( TestQueueItem item : takenItems ) - { + int i = 0; + for (TestQueueItem item : takenItems) { assertEquals(item.str, Integer.toString(i++)); } assertNotNull(thrownItemFromConsumer1.get()); assertTrue((takenItemsForConsumer2.contains(thrownItemFromConsumer1.get()))); - assertTrue(Sets.intersection(takenItemsForConsumer1, takenItemsForConsumer2).size() == 0); - } - finally - { + assertTrue(Sets.intersection(takenItemsForConsumer1, takenItemsForConsumer2) + .size() + == 0); + } finally { CloseableUtils.closeQuietly(producerQueue); CloseableUtils.closeQuietly(consumerQueue1); CloseableUtils.closeQuietly(consumerQueue2); @@ -553,90 +487,75 @@ public void stateChanged(CuratorFramework client, ConnectionState newState) } } - private void addToTakenItems(TestQueueItem message, Set takenItems, int itemQty) - { - synchronized(takenItems) - { + private void addToTakenItems(TestQueueItem message, Set takenItems, int itemQty) { + synchronized (takenItems) { takenItems.add(message); - if ( takenItems.size() > itemQty ) - { + if (takenItems.size() > itemQty) { takenItems.notifyAll(); } } } @Test - public void testSafetyBasic() throws Exception - { - final int itemQty = 10; + public void testSafetyBasic() throws Exception { + final int itemQty = 10; - DistributedQueue queue = null; - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); + DistributedQueue queue = null; + CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client.start(); - try - { - final BlockingQueueConsumer consumer = new BlockingQueueConsumer(Mockito.mock(ConnectionStateListener.class)); - queue = QueueBuilder.builder(client, consumer, serializer, QUEUE_PATH). - lockPath("/a/locks"). - buildQueue(); + try { + final BlockingQueueConsumer consumer = + new BlockingQueueConsumer(Mockito.mock(ConnectionStateListener.class)); + queue = QueueBuilder.builder(client, consumer, serializer, QUEUE_PATH) + .lockPath("/a/locks") + .buildQueue(); queue.start(); QueueTestProducer producer = new QueueTestProducer(queue, itemQty, 0); - ExecutorService service = Executors.newCachedThreadPool(); + ExecutorService service = Executors.newCachedThreadPool(); service.submit(producer); - final CountDownLatch latch = new CountDownLatch(1); - service.submit - ( - new Callable() - { - @Override - public Object call() throws Exception - { - for ( int i = 0; i < itemQty; ++i ) - { - TestQueueItem item = consumer.take(); - assertEquals(item.str, Integer.toString(i)); - } - latch.countDown(); - return null; + final CountDownLatch latch = new CountDownLatch(1); + service.submit(new Callable() { + @Override + public Object call() throws Exception { + for (int i = 0; i < itemQty; ++i) { + TestQueueItem item = consumer.take(); + assertEquals(item.str, Integer.toString(i)); } + latch.countDown(); + return null; } - ); + }); assertTrue(latch.await(10, TimeUnit.SECONDS)); - } - finally - { + } finally { CloseableUtils.closeQuietly(queue); CloseableUtils.closeQuietly(client); } } @Test - public void testPutMulti() throws Exception - { - final int itemQty = 100; + public void testPutMulti() throws Exception { + final int itemQty = 100; - DistributedQueue queue = null; + DistributedQueue queue = null; CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client.start(); - try - { - BlockingQueueConsumer consumer = new BlockingQueueConsumer(Mockito.mock(ConnectionStateListener.class)); + try { + BlockingQueueConsumer consumer = + new BlockingQueueConsumer(Mockito.mock(ConnectionStateListener.class)); - queue = QueueBuilder.builder(client, consumer, serializer, QUEUE_PATH).buildQueue(); + queue = QueueBuilder.builder(client, consumer, serializer, QUEUE_PATH) + .buildQueue(); queue.start(); - MultiItem items = new MultiItem() - { - private int index = 0; + MultiItem items = new MultiItem() { + private int index = 0; @Override - public TestQueueItem nextItem() throws Exception - { - if ( index >= itemQty ) - { + public TestQueueItem nextItem() throws Exception { + if (index >= itemQty) { return null; } return new TestQueueItem(Integer.toString(index++)); @@ -644,99 +563,103 @@ public TestQueueItem nextItem() throws Exception }; queue.putMulti(items); - for ( int i = 0; i < itemQty; ++i ) - { - TestQueueItem queueItem = consumer.take(1, TimeUnit.SECONDS); + for (int i = 0; i < itemQty; ++i) { + TestQueueItem queueItem = consumer.take(1, TimeUnit.SECONDS); assertNotNull(queueItem); assertEquals(queueItem, new TestQueueItem(Integer.toString(i))); } - } - finally - { + } finally { CloseableUtils.closeQuietly(queue); CloseableUtils.closeQuietly(client); } } @Test - public void testMultiPutterSingleGetter() throws Exception - { - final int itemQty = 100; + public void testMultiPutterSingleGetter() throws Exception { + final int itemQty = 100; - DistributedQueue queue = null; + DistributedQueue queue = null; CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client.start(); - try - { - BlockingQueueConsumer consumer = new BlockingQueueConsumer(Mockito.mock(ConnectionStateListener.class)); + try { + BlockingQueueConsumer consumer = + new BlockingQueueConsumer(Mockito.mock(ConnectionStateListener.class)); - queue = QueueBuilder.builder(client, consumer, serializer, QUEUE_PATH).buildQueue(); + queue = QueueBuilder.builder(client, consumer, serializer, QUEUE_PATH) + .buildQueue(); queue.start(); QueueTestProducer producer1 = new QueueTestProducer(queue, itemQty / 2, 0); QueueTestProducer producer2 = new QueueTestProducer(queue, ((itemQty + 1) / 2), itemQty / 2); - ExecutorService service = Executors.newCachedThreadPool(); + ExecutorService service = Executors.newCachedThreadPool(); service.submit(producer1); service.submit(producer2); - int iteration = 0; - while ( consumer.size() < itemQty ) - { + int iteration = 0; + while (consumer.size() < itemQty) { assertTrue(++iteration < 10); Thread.sleep(1000); } List items = consumer.getItems(); - assertEquals(com.google.common.collect.Sets.newHashSet(items).size(), items.size()); // check no duplicates - } - finally - { + assertEquals( + com.google.common.collect.Sets.newHashSet(items) + .size(), + items.size()); // check no duplicates + } finally { CloseableUtils.closeQuietly(queue); CloseableUtils.closeQuietly(client); } } @Test - public void testFlush() throws Exception - { - final Timing timing = new Timing(); - final CountDownLatch latch = new CountDownLatch(1); - DistributedQueue queue = null; - final CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); + public void testFlush() throws Exception { + final Timing timing = new Timing(); + final CountDownLatch latch = new CountDownLatch(1); + DistributedQueue queue = null; + final CuratorFramework client = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); client.start(); - try - { - final AtomicBoolean firstTime = new AtomicBoolean(true); - queue = new DistributedQueue(client, null, serializer, "/test", new ThreadFactoryBuilder().build(), MoreExecutors.directExecutor(), 10, true, null, QueueBuilder.NOT_SET, true, 0) - { - @Override - void internalCreateNode(final String path, final byte[] bytes, final BackgroundCallback callback) throws Exception - { - if ( firstTime.compareAndSet(true, false) ) - { - Executors.newSingleThreadExecutor().submit - ( - new Callable() - { - @Override - public Object call() throws Exception - { - latch.await(); - timing.sleepABit(); - client.create().withMode(CreateMode.PERSISTENT_SEQUENTIAL).inBackground(callback).forPath(path, bytes); - return null; - } + try { + final AtomicBoolean firstTime = new AtomicBoolean(true); + queue = + new DistributedQueue( + client, + null, + serializer, + "/test", + new ThreadFactoryBuilder().build(), + MoreExecutors.directExecutor(), + 10, + true, + null, + QueueBuilder.NOT_SET, + true, + 0) { + @Override + void internalCreateNode( + final String path, final byte[] bytes, final BackgroundCallback callback) + throws Exception { + if (firstTime.compareAndSet(true, false)) { + Executors.newSingleThreadExecutor().submit(new Callable() { + @Override + public Object call() throws Exception { + latch.await(); + timing.sleepABit(); + client.create() + .withMode(CreateMode.PERSISTENT_SEQUENTIAL) + .inBackground(callback) + .forPath(path, bytes); + return null; + } + }); + } else { + super.internalCreateNode(path, bytes, callback); } - ); - } - else - { - super.internalCreateNode(path, bytes, callback); - } - } - }; + } + }; queue.start(); queue.put(new TestQueueItem("1")); @@ -744,11 +667,8 @@ public Object call() throws Exception latch.countDown(); assertTrue(queue.flushPuts(timing.forWaiting().seconds(), TimeUnit.SECONDS)); - } - finally - { - if ( latch.getCount() > 0 ) - { + } finally { + if (latch.getCount() > 0) { latch.countDown(); } @@ -758,40 +678,36 @@ public Object call() throws Exception } @Test - public void testSimple() throws Exception - { - final int itemQty = 10; + public void testSimple() throws Exception { + final int itemQty = 10; - DistributedQueue queue = null; + DistributedQueue queue = null; CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client.start(); - try - { - BlockingQueueConsumer consumer = new BlockingQueueConsumer(Mockito.mock(ConnectionStateListener.class)); + try { + BlockingQueueConsumer consumer = + new BlockingQueueConsumer(Mockito.mock(ConnectionStateListener.class)); - queue = QueueBuilder.builder(client, consumer, serializer, QUEUE_PATH).buildQueue(); + queue = QueueBuilder.builder(client, consumer, serializer, QUEUE_PATH) + .buildQueue(); queue.start(); QueueTestProducer producer = new QueueTestProducer(queue, itemQty, 0); - ExecutorService service = Executors.newCachedThreadPool(); + ExecutorService service = Executors.newCachedThreadPool(); service.submit(producer); - int iteration = 0; - while ( consumer.size() < itemQty ) - { + int iteration = 0; + while (consumer.size() < itemQty) { assertTrue(++iteration < 10); Thread.sleep(1000); } - int i = 0; - for ( TestQueueItem item : consumer.getItems() ) - { + int i = 0; + for (TestQueueItem item : consumer.getItems()) { assertEquals(item.str, Integer.toString(i++)); } - } - finally - { + } finally { CloseableUtils.closeQuietly(queue); CloseableUtils.closeQuietly(client); } diff --git a/curator-recipes/src/test/java/org/apache/curator/framework/recipes/queue/TestLongNetworkPartition.java b/curator-recipes/src/test/java/org/apache/curator/framework/recipes/queue/TestLongNetworkPartition.java index 7d45b751d..0e827203d 100644 --- a/curator-recipes/src/test/java/org/apache/curator/framework/recipes/queue/TestLongNetworkPartition.java +++ b/curator-recipes/src/test/java/org/apache/curator/framework/recipes/queue/TestLongNetworkPartition.java @@ -19,6 +19,9 @@ package org.apache.curator.framework.recipes.queue; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.TimeUnit; +import java.util.function.Consumer; import org.apache.curator.ensemble.fixed.FixedEnsembleProvider; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; @@ -27,9 +30,6 @@ import org.apache.curator.test.TestingCluster; import org.apache.curator.test.compatibility.Timing2; import org.junit.jupiter.api.Test; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.TimeUnit; -import java.util.function.Consumer; public class TestLongNetworkPartition { private static final Timing2 timing = new Timing2(); @@ -40,20 +40,18 @@ public void testLongNetworkPartition() throws Exception { final CompletableFuture done = new CompletableFuture<>(); try (final TestingCluster testingCluster = started(new TestingCluster(1)); final CuratorFramework dyingCuratorFramework = getCuratorFramework(testingCluster.getConnectString()); - final DistributedQueue dyingQueue = newQueue(dyingCuratorFramework, item -> { - if ( item.equals("0") ) - { - done.complete(null); - } - })) - { + final DistributedQueue dyingQueue = newQueue(dyingCuratorFramework, item -> { + if (item.equals("0")) { + done.complete(null); + } + })) { dyingQueue.start(); testingCluster.killServer(testingCluster.getInstances().iterator().next()); timing.forSessionSleep().multiple(2).sleep(); - testingCluster.restartServer(testingCluster.getInstances().iterator().next()); + testingCluster.restartServer( + testingCluster.getInstances().iterator().next()); try (final CuratorFramework aliveCuratorFramework = getCuratorFramework(testingCluster.getConnectString()); - final DistributedQueue aliveQueue = newQueue(aliveCuratorFramework, null)) - { + final DistributedQueue aliveQueue = newQueue(aliveCuratorFramework, null)) { aliveQueue.start(); aliveQueue.put("0"); done.get(timing.forWaiting().milliseconds(), TimeUnit.MILLISECONDS); @@ -63,26 +61,33 @@ public void testLongNetworkPartition() throws Exception { private static DistributedQueue newQueue(CuratorFramework curatorFramework, Consumer consumer) { curatorFramework.start(); - return QueueBuilder.builder(curatorFramework, consumer == null ? null : new QueueConsumer() { - @Override - public void consumeMessage(String o) { - consumer.accept(o); - } + return QueueBuilder.builder( + curatorFramework, + consumer == null + ? null + : new QueueConsumer() { + @Override + public void consumeMessage(String o) { + consumer.accept(o); + } - @Override - public void stateChanged(CuratorFramework curatorFramework, ConnectionState connectionState) { - } - }, new QueueSerializer() { - @Override - public byte[] serialize(String item) { - return item.getBytes(); - } + @Override + public void stateChanged( + CuratorFramework curatorFramework, ConnectionState connectionState) {} + }, + new QueueSerializer() { + @Override + public byte[] serialize(String item) { + return item.getBytes(); + } - @Override - public String deserialize(byte[] bytes) { - return new String(bytes); - } - }, "/MyChildrenCacheTest/queue").buildQueue(); + @Override + public String deserialize(byte[] bytes) { + return new String(bytes); + } + }, + "/MyChildrenCacheTest/queue") + .buildQueue(); } private static TestingCluster started(TestingCluster testingCluster) throws Exception { @@ -92,8 +97,9 @@ private static TestingCluster started(TestingCluster testingCluster) throws Exce private static CuratorFramework getCuratorFramework(String connectString) { return CuratorFrameworkFactory.builder() - .ensembleProvider(new FixedEnsembleProvider(connectString, true)) - .sessionTimeoutMs(timing.session()) - .retryPolicy(new ExponentialBackoffRetry(1000, 3)).build(); + .ensembleProvider(new FixedEnsembleProvider(connectString, true)) + .sessionTimeoutMs(timing.session()) + .retryPolicy(new ExponentialBackoffRetry(1000, 3)) + .build(); } -} \ No newline at end of file +} diff --git a/curator-recipes/src/test/java/org/apache/curator/framework/recipes/queue/TestQueueItem.java b/curator-recipes/src/test/java/org/apache/curator/framework/recipes/queue/TestQueueItem.java index 82065ec40..fd81b59e4 100644 --- a/curator-recipes/src/test/java/org/apache/curator/framework/recipes/queue/TestQueueItem.java +++ b/curator-recipes/src/test/java/org/apache/curator/framework/recipes/queue/TestQueueItem.java @@ -19,50 +19,41 @@ package org.apache.curator.framework.recipes.queue; -class TestQueueItem implements Comparable -{ - final String str; +class TestQueueItem implements Comparable { + final String str; - TestQueueItem(String str) - { + TestQueueItem(String str) { this.str = str; } @Override - public int compareTo(TestQueueItem rhs) - { - if ( this == rhs ) - { + public int compareTo(TestQueueItem rhs) { + if (this == rhs) { return 0; } - int val = Integer.parseInt(str); - int rhsVal = Integer.parseInt(rhs.str); - int diff = val - rhsVal; + int val = Integer.parseInt(str); + int rhsVal = Integer.parseInt(rhs.str); + int diff = val - rhsVal; return (diff < 0) ? -1 : ((diff > 0) ? 1 : 0); } @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; } - TestQueueItem that = (TestQueueItem)o; + TestQueueItem that = (TestQueueItem) o; return str.equals(that.str); - } @Override - public int hashCode() - { + public int hashCode() { return str.hashCode(); } } diff --git a/curator-recipes/src/test/java/org/apache/curator/framework/recipes/queue/TestQueueSharder.java b/curator-recipes/src/test/java/org/apache/curator/framework/recipes/queue/TestQueueSharder.java index 44004ad0e..055052be4 100644 --- a/curator-recipes/src/test/java/org/apache/curator/framework/recipes/queue/TestQueueSharder.java +++ b/curator-recipes/src/test/java/org/apache/curator/framework/recipes/queue/TestQueueSharder.java @@ -23,6 +23,9 @@ import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; import com.google.common.collect.Sets; +import java.util.Set; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; import org.apache.commons.math.stat.descriptive.SummaryStatistics; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; @@ -34,54 +37,46 @@ import org.apache.curator.utils.CloseableUtils; import org.junit.jupiter.api.Test; -import java.util.Set; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; - -public class TestQueueSharder extends BaseClassForTests -{ +public class TestQueueSharder extends BaseClassForTests { @Test - public void testDistribution() throws Exception - { - final int threshold = 100; - final int factor = 10; - - Timing timing = new Timing(); - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); - QueueSharder> sharder = null; - try - { + public void testDistribution() throws Exception { + final int threshold = 100; + final int factor = 10; + + Timing timing = new Timing(); + CuratorFramework client = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); + QueueSharder> sharder = null; + try { client.start(); - final CountDownLatch latch = new CountDownLatch(1); - QueueConsumer consumer = new QueueConsumer() - { + final CountDownLatch latch = new CountDownLatch(1); + QueueConsumer consumer = new QueueConsumer() { @Override - public void consumeMessage(String message) throws Exception - { + public void consumeMessage(String message) throws Exception { latch.await(); } @Override - public void stateChanged(CuratorFramework client, ConnectionState newState) - { - } + public void stateChanged(CuratorFramework client, ConnectionState newState) {} }; - QueueAllocator> distributedQueueAllocator = makeAllocator(consumer); - QueueSharderPolicies policies = QueueSharderPolicies.builder().newQueueThreshold(threshold).thresholdCheckMs(1).build(); - sharder = new QueueSharder>(client, distributedQueueAllocator, "/queues", "/leader", policies); + QueueAllocator> distributedQueueAllocator = makeAllocator(consumer); + QueueSharderPolicies policies = QueueSharderPolicies.builder() + .newQueueThreshold(threshold) + .thresholdCheckMs(1) + .build(); + sharder = new QueueSharder>( + client, distributedQueueAllocator, "/queues", "/leader", policies); sharder.start(); - for ( int i = 0; i < (factor * threshold); ++i ) - { + for (int i = 0; i < (factor * threshold); ++i) { sharder.getQueue().put(Integer.toString(i)); Thread.sleep(5); } timing.forWaiting().sleepABit(); - SummaryStatistics statistics = new SummaryStatistics(); - for ( String path : sharder.getQueuePaths() ) - { + SummaryStatistics statistics = new SummaryStatistics(); + for (String path : sharder.getQueuePaths()) { int numChildren = client.checkExists().forPath(path).getNumChildren(); assertTrue(numChildren > 0); assertTrue(numChildren >= (threshold * .1)); @@ -90,9 +85,7 @@ public void stateChanged(CuratorFramework client, ConnectionState newState) latch.countDown(); assertTrue(statistics.getMean() >= (threshold * .9)); - } - finally - { + } finally { timing.sleepABit(); // let queue clear CloseableUtils.closeQuietly(sharder); CloseableUtils.closeQuietly(client); @@ -100,25 +93,28 @@ public void stateChanged(CuratorFramework client, ConnectionState newState) } @Test - public void testSharderWatchSync() throws Exception - { - Timing timing = new Timing(); - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); - - final BlockingQueueConsumer consumer = makeConsumer(null); - QueueAllocator> distributedQueueAllocator = makeAllocator(consumer); - QueueSharderPolicies policies = QueueSharderPolicies.builder().newQueueThreshold(2).thresholdCheckMs(1).build(); - - QueueSharder> sharder1 = new QueueSharder>(client, distributedQueueAllocator, "/queues", "/leader", policies); - QueueSharder> sharder2 = new QueueSharder>(client, distributedQueueAllocator, "/queues", "/leader", policies); - try - { + public void testSharderWatchSync() throws Exception { + Timing timing = new Timing(); + CuratorFramework client = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); + + final BlockingQueueConsumer consumer = makeConsumer(null); + QueueAllocator> distributedQueueAllocator = makeAllocator(consumer); + QueueSharderPolicies policies = QueueSharderPolicies.builder() + .newQueueThreshold(2) + .thresholdCheckMs(1) + .build(); + + QueueSharder> sharder1 = new QueueSharder>( + client, distributedQueueAllocator, "/queues", "/leader", policies); + QueueSharder> sharder2 = new QueueSharder>( + client, distributedQueueAllocator, "/queues", "/leader", policies); + try { client.start(); sharder1.start(); sharder2.start(); - for ( int i = 0; i < 20; ++i ) - { + for (int i = 0; i < 20; ++i) { sharder1.getQueue().put(Integer.toString(i)); } timing.sleepABit(); @@ -126,9 +122,7 @@ public void testSharderWatchSync() throws Exception assertTrue((sharder1.getShardQty() > 1) || (sharder2.getShardQty() > 1)); timing.forWaiting().sleepABit(); assertEquals(sharder1.getShardQty(), sharder2.getShardQty()); - } - finally - { + } finally { timing.sleepABit(); // let queues clear CloseableUtils.closeQuietly(sharder1); CloseableUtils.closeQuietly(sharder2); @@ -137,18 +131,21 @@ public void testSharderWatchSync() throws Exception } @Test - public void testSimpleDistributedQueue() throws Exception - { - Timing timing = new Timing(); - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); - - final CountDownLatch latch = new CountDownLatch(1); - final BlockingQueueConsumer consumer = makeConsumer(latch); - QueueAllocator> distributedQueueAllocator = makeAllocator(consumer); - QueueSharderPolicies policies = QueueSharderPolicies.builder().newQueueThreshold(2).thresholdCheckMs(1).build(); - QueueSharder> sharder = new QueueSharder>(client, distributedQueueAllocator, "/queues", "/leader", policies); - try - { + public void testSimpleDistributedQueue() throws Exception { + Timing timing = new Timing(); + CuratorFramework client = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); + + final CountDownLatch latch = new CountDownLatch(1); + final BlockingQueueConsumer consumer = makeConsumer(latch); + QueueAllocator> distributedQueueAllocator = makeAllocator(consumer); + QueueSharderPolicies policies = QueueSharderPolicies.builder() + .newQueueThreshold(2) + .thresholdCheckMs(1) + .build(); + QueueSharder> sharder = new QueueSharder>( + client, distributedQueueAllocator, "/queues", "/leader", policies); + try { client.start(); sharder.start(); @@ -166,9 +163,8 @@ public void testSimpleDistributedQueue() throws Exception assertTrue(sharder.getShardQty() > 1); - Set consumed = Sets.newHashSet(); - for ( int i = 0; i < 8; ++i ) - { + Set consumed = Sets.newHashSet(); + for (int i = 0; i < 8; ++i) { String s = consumer.take(timing.forWaiting().milliseconds(), TimeUnit.MILLISECONDS); assertNotNull(s); consumed.add(s); @@ -176,65 +172,52 @@ public void testSimpleDistributedQueue() throws Exception assertEquals(consumed, Sets.newHashSet("one", "two", "three", "four", "five", "six", "seven", "eight")); - int shardQty = sharder.getShardQty(); + int shardQty = sharder.getShardQty(); sharder.close(); // check re-open - sharder = new QueueSharder>(client, distributedQueueAllocator, "/queues", "/leader", policies); + sharder = new QueueSharder>( + client, distributedQueueAllocator, "/queues", "/leader", policies); sharder.start(); assertEquals(sharder.getShardQty(), shardQty); - } - finally - { + } finally { CloseableUtils.closeQuietly(sharder); CloseableUtils.closeQuietly(client); } } - private QueueAllocator> makeAllocator(final QueueConsumer consumer) - { - final QueueSerializer serializer = new QueueSerializer() - { + private QueueAllocator> makeAllocator(final QueueConsumer consumer) { + final QueueSerializer serializer = new QueueSerializer() { @Override - public byte[] serialize(String item) - { + public byte[] serialize(String item) { return item.getBytes(); } @Override - public String deserialize(byte[] bytes) - { + public String deserialize(byte[] bytes) { return new String(bytes); } }; - return new QueueAllocator>() - { + return new QueueAllocator>() { @Override - public DistributedQueue allocateQueue(CuratorFramework client, String queuePath) - { - return QueueBuilder.builder(client, consumer, serializer, queuePath).buildQueue(); + public DistributedQueue allocateQueue(CuratorFramework client, String queuePath) { + return QueueBuilder.builder(client, consumer, serializer, queuePath) + .buildQueue(); } }; } - private BlockingQueueConsumer makeConsumer(final CountDownLatch latch) - { - ConnectionStateListener connectionStateListener = new ConnectionStateListener() - { + private BlockingQueueConsumer makeConsumer(final CountDownLatch latch) { + ConnectionStateListener connectionStateListener = new ConnectionStateListener() { @Override - public void stateChanged(CuratorFramework client, ConnectionState newState) - { - } + public void stateChanged(CuratorFramework client, ConnectionState newState) {} }; - return new BlockingQueueConsumer(connectionStateListener) - { + return new BlockingQueueConsumer(connectionStateListener) { @Override - public void consumeMessage(String message) throws Exception - { - if ( latch != null ) - { + public void consumeMessage(String message) throws Exception { + if (latch != null) { latch.await(); } super.consumeMessage(message); diff --git a/curator-recipes/src/test/java/org/apache/curator/framework/recipes/queue/TestSimpleDistributedQueue.java b/curator-recipes/src/test/java/org/apache/curator/framework/recipes/queue/TestSimpleDistributedQueue.java index 611db4157..b28aa3e85 100644 --- a/curator-recipes/src/test/java/org/apache/curator/framework/recipes/queue/TestSimpleDistributedQueue.java +++ b/curator-recipes/src/test/java/org/apache/curator/framework/recipes/queue/TestSimpleDistributedQueue.java @@ -22,50 +22,40 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; - +import java.util.NoSuchElementException; +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.RetryOneTime; import org.apache.curator.test.BaseClassForTests; import org.apache.curator.test.TestingServer; import org.apache.curator.test.Timing; import org.apache.curator.utils.CloseableUtils; -import org.apache.curator.framework.CuratorFramework; -import org.apache.curator.framework.CuratorFrameworkFactory; -import org.apache.curator.retry.RetryOneTime; import org.junit.jupiter.api.Test; -import java.util.NoSuchElementException; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.TimeUnit; - -public class TestSimpleDistributedQueue extends BaseClassForTests -{ - private static abstract class QueueUser implements Runnable - { +public class TestSimpleDistributedQueue extends BaseClassForTests { + private abstract static class QueueUser implements Runnable { private static final String QUEUE_PATH = "/queue"; private static final int ITEM_COUNT = 10; protected final SimpleDistributedQueue queue; private final int sleepMillis; - public QueueUser(CuratorFramework curator, int sleepMillis) - { + public QueueUser(CuratorFramework curator, int sleepMillis) { this.queue = new SimpleDistributedQueue(curator, QUEUE_PATH); this.sleepMillis = sleepMillis; } @Override - public void run() - { - try - { - for ( int i = 0; i < ITEM_COUNT; i++ ) - { + public void run() { + try { + for (int i = 0; i < ITEM_COUNT; i++) { processItem(i); Thread.sleep(sleepMillis); } - } - catch ( Exception e ) - { + } catch (Exception e) { throw new RuntimeException(e); } } @@ -74,8 +64,7 @@ public void run() } @Test - public void testHangFromContainerLoss() throws Exception - { + public void testHangFromContainerLoss() throws Exception { // for CURATOR-308 server.close(); @@ -84,30 +73,24 @@ public void testHangFromContainerLoss() throws Exception Timing timing = new Timing().multiple(.1); CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); - try - { + try { client.start(); ExecutorService executor = Executors.newFixedThreadPool(2); - executor.execute(new QueueUser(client, timing.milliseconds()) - { + executor.execute(new QueueUser(client, timing.milliseconds()) { @Override - protected void processItem(int itemNumber) throws Exception - { + protected void processItem(int itemNumber) throws Exception { System.out.println("Offering item"); - queue.offer(new byte[]{(byte)itemNumber}); + queue.offer(new byte[] {(byte) itemNumber}); } }); - executor.execute(new QueueUser(client, timing.multiple(.5).milliseconds()) - { + executor.execute(new QueueUser(client, timing.multiple(.5).milliseconds()) { @Override - protected void processItem(int itemNumber) throws Exception - { + protected void processItem(int itemNumber) throws Exception { System.out.println("Taking item " + itemNumber); byte[] item = queue.take(); - if ( item == null ) - { + if (item == null) { throw new IllegalStateException("Null result for item " + itemNumber); } System.out.println("Got item " + item[0]); @@ -115,53 +98,44 @@ protected void processItem(int itemNumber) throws Exception }); executor.shutdown(); - assertTrue(executor.awaitTermination((QueueUser.ITEM_COUNT * 2) * timing.milliseconds(), TimeUnit.MILLISECONDS)); - } - finally - { + assertTrue(executor.awaitTermination( + (QueueUser.ITEM_COUNT * 2) * timing.milliseconds(), TimeUnit.MILLISECONDS)); + } finally { CloseableUtils.closeQuietly(client); System.clearProperty("znode.container.checkIntervalMs"); } } @Test - public void testPollWithTimeout() throws Exception - { + public void testPollWithTimeout() throws Exception { CuratorFramework clients[] = null; - try - { + try { String dir = "/testOffer1"; final int num_clients = 1; clients = new CuratorFramework[num_clients]; SimpleDistributedQueue queueHandles[] = new SimpleDistributedQueue[num_clients]; - for ( int i = 0; i < clients.length; i++ ) - { + for (int i = 0; i < clients.length; i++) { clients[i] = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); clients[i].start(); queueHandles[i] = new SimpleDistributedQueue(clients[i], dir); } assertNull(queueHandles[0].poll(3, TimeUnit.SECONDS)); - } - finally - { + } finally { closeAll(clients); } } @Test - public void testOffer1() throws Exception - { + public void testOffer1() throws Exception { CuratorFramework clients[] = null; - try - { + try { String dir = "/testOffer1"; String testString = "Hello World"; final int num_clients = 1; clients = new CuratorFramework[num_clients]; SimpleDistributedQueue queueHandles[] = new SimpleDistributedQueue[num_clients]; - for ( int i = 0; i < clients.length; i++ ) - { + for (int i = 0; i < clients.length; i++) { clients[i] = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); clients[i].start(); queueHandles[i] = new SimpleDistributedQueue(clients[i], dir); @@ -171,26 +145,21 @@ public void testOffer1() throws Exception byte dequeuedBytes[] = queueHandles[0].remove(); assertEquals(new String(dequeuedBytes), testString); - } - finally - { + } finally { closeAll(clients); } } @Test - public void testOffer2() throws Exception - { + public void testOffer2() throws Exception { CuratorFramework clients[] = null; - try - { + try { String dir = "/testOffer2"; String testString = "Hello World"; final int num_clients = 2; clients = new CuratorFramework[num_clients]; SimpleDistributedQueue queueHandles[] = new SimpleDistributedQueue[num_clients]; - for ( int i = 0; i < clients.length; i++ ) - { + for (int i = 0; i < clients.length; i++) { clients[i] = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); clients[i].start(); queueHandles[i] = new SimpleDistributedQueue(clients[i], dir); @@ -200,26 +169,21 @@ public void testOffer2() throws Exception byte dequeuedBytes[] = queueHandles[1].remove(); assertEquals(new String(dequeuedBytes), testString); - } - finally - { + } finally { closeAll(clients); } } @Test - public void testTake1() throws Exception - { + public void testTake1() throws Exception { CuratorFramework clients[] = null; - try - { + try { String dir = "/testTake1"; String testString = "Hello World"; final int num_clients = 1; clients = new CuratorFramework[num_clients]; SimpleDistributedQueue queueHandles[] = new SimpleDistributedQueue[num_clients]; - for ( int i = 0; i < clients.length; i++ ) - { + for (int i = 0; i < clients.length; i++) { clients[i] = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); clients[i].start(); queueHandles[i] = new SimpleDistributedQueue(clients[i], dir); @@ -229,180 +193,142 @@ public void testTake1() throws Exception byte dequeuedBytes[] = queueHandles[0].take(); assertEquals(new String(dequeuedBytes), testString); - } - finally - { + } finally { closeAll(clients); } } @Test - public void testRemova1() throws Exception - { + public void testRemova1() throws Exception { CuratorFramework clients[] = null; - try - { + try { String dir = "/testRemove1"; final int num_clients = 1; clients = new CuratorFramework[num_clients]; SimpleDistributedQueue queueHandles[] = new SimpleDistributedQueue[num_clients]; - for ( int i = 0; i < clients.length; i++ ) - { + for (int i = 0; i < clients.length; i++) { clients[i] = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); clients[i].start(); queueHandles[i] = new SimpleDistributedQueue(clients[i], dir); } - try - { + try { queueHandles[0].remove(); - } - catch ( NoSuchElementException e ) - { + } catch (NoSuchElementException e) { return; } assertTrue(false); - } - finally - { + } finally { closeAll(clients); } } - public void createNremoveMtest(String dir, int n, int m) throws Exception - { + public void createNremoveMtest(String dir, int n, int m) throws Exception { CuratorFramework clients[] = null; - try - { + try { String testString = "Hello World"; final int num_clients = 2; clients = new CuratorFramework[num_clients]; SimpleDistributedQueue queueHandles[] = new SimpleDistributedQueue[num_clients]; - for ( int i = 0; i < clients.length; i++ ) - { + for (int i = 0; i < clients.length; i++) { clients[i] = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); clients[i].start(); queueHandles[i] = new SimpleDistributedQueue(clients[i], dir); } - for ( int i = 0; i < n; i++ ) - { + for (int i = 0; i < n; i++) { String offerString = testString + i; queueHandles[0].offer(offerString.getBytes()); } byte data[] = null; - for ( int i = 0; i < m; i++ ) - { + for (int i = 0; i < m; i++) { data = queueHandles[1].remove(); } assertEquals(new String(data), testString + (m - 1)); - } - finally - { + } finally { closeAll(clients); } } @Test - public void testRemove2() throws Exception - { + public void testRemove2() throws Exception { createNremoveMtest("/testRemove2", 10, 2); } @Test - public void testRemove3() throws Exception - { + public void testRemove3() throws Exception { createNremoveMtest("/testRemove3", 1000, 1000); } - public void createNremoveMelementTest(String dir, int n, int m) throws Exception - { + public void createNremoveMelementTest(String dir, int n, int m) throws Exception { CuratorFramework clients[] = null; - try - { + try { String testString = "Hello World"; final int num_clients = 2; clients = new CuratorFramework[num_clients]; SimpleDistributedQueue queueHandles[] = new SimpleDistributedQueue[num_clients]; - for ( int i = 0; i < clients.length; i++ ) - { + for (int i = 0; i < clients.length; i++) { clients[i] = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); clients[i].start(); queueHandles[i] = new SimpleDistributedQueue(clients[i], dir); } - for ( int i = 0; i < n; i++ ) - { + for (int i = 0; i < n; i++) { String offerString = testString + i; queueHandles[0].offer(offerString.getBytes()); } - for ( int i = 0; i < m; i++ ) - { + for (int i = 0; i < m; i++) { queueHandles[1].remove(); } assertEquals(new String(queueHandles[1].element()), testString + m); - } - finally - { + } finally { closeAll(clients); } } @Test - public void testElement1() throws Exception - { + public void testElement1() throws Exception { createNremoveMelementTest("/testElement1", 1, 0); } @Test - public void testElement2() throws Exception - { + public void testElement2() throws Exception { createNremoveMelementTest("/testElement2", 10, 2); } @Test - public void testElement3() throws Exception - { + public void testElement3() throws Exception { createNremoveMelementTest("/testElement3", 1000, 500); } @Test - public void testElement4() throws Exception - { + public void testElement4() throws Exception { createNremoveMelementTest("/testElement4", 1000, 1000 - 1); } @Test - public void testTakeWait1() throws Exception - { + public void testTakeWait1() throws Exception { CuratorFramework clients[] = null; - try - { + try { String dir = "/testTakeWait1"; final String testString = "Hello World"; final int num_clients = 1; clients = new CuratorFramework[num_clients]; final SimpleDistributedQueue queueHandles[] = new SimpleDistributedQueue[num_clients]; - for ( int i = 0; i < clients.length; i++ ) - { + for (int i = 0; i < clients.length; i++) { clients[i] = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); clients[i].start(); queueHandles[i] = new SimpleDistributedQueue(clients[i], dir); } final byte[] takeResult[] = new byte[1][]; - Thread takeThread = new Thread() - { - public void run() - { - try - { + Thread takeThread = new Thread() { + public void run() { + try { takeResult[0] = queueHandles[0].take(); - } - catch ( Exception e ) - { + } catch (Exception e) { // ignore } } @@ -410,16 +336,11 @@ public void run() takeThread.start(); Thread.sleep(1000); - Thread offerThread = new Thread() - { - public void run() - { - try - { + Thread offerThread = new Thread() { + public void run() { + try { queueHandles[0].offer(testString.getBytes()); - } - catch ( Exception e ) - { + } catch (Exception e) { // ignore } } @@ -431,42 +352,32 @@ public void run() assertTrue(takeResult[0] != null); assertEquals(new String(takeResult[0]), testString); - } - finally - { + } finally { closeAll(clients); } } @Test - public void testTakeWait2() throws Exception - { + public void testTakeWait2() throws Exception { String dir = "/testTakeWait2"; final String testString = "Hello World"; final int num_clients = 1; final CuratorFramework clients[] = new CuratorFramework[num_clients]; final SimpleDistributedQueue queueHandles[] = new SimpleDistributedQueue[num_clients]; - for ( int i = 0; i < clients.length; i++ ) - { + for (int i = 0; i < clients.length; i++) { clients[i] = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); clients[i].start(); queueHandles[i] = new SimpleDistributedQueue(clients[i], dir); } int num_attempts = 2; - for ( int i = 0; i < num_attempts; i++ ) - { + for (int i = 0; i < num_attempts; i++) { final byte[] takeResult[] = new byte[1][]; final String threadTestString = testString + i; - Thread takeThread = new Thread() - { - public void run() - { - try - { + Thread takeThread = new Thread() { + public void run() { + try { takeResult[0] = queueHandles[0].take(); - } - catch ( Exception e ) - { + } catch (Exception e) { // ignore } } @@ -474,16 +385,11 @@ public void run() takeThread.start(); Thread.sleep(1000); - Thread offerThread = new Thread() - { - public void run() - { - try - { + Thread offerThread = new Thread() { + public void run() { + try { queueHandles[0].offer(threadTestString.getBytes()); - } - catch ( Exception e ) - { + } catch (Exception e) { // ignore } } @@ -498,12 +404,9 @@ public void run() } } - private void closeAll(CuratorFramework[] clients) - { - if ( clients != null ) - { - for ( CuratorFramework c : clients ) - { + private void closeAll(CuratorFramework[] clients) { + if (clients != null) { + for (CuratorFramework c : clients) { CloseableUtils.closeQuietly(c); } } diff --git a/curator-recipes/src/test/java/org/apache/curator/framework/recipes/shared/TestSharedCount.java b/curator-recipes/src/test/java/org/apache/curator/framework/recipes/shared/TestSharedCount.java index 4c9742677..b7b56c06a 100644 --- a/curator-recipes/src/test/java/org/apache/curator/framework/recipes/shared/TestSharedCount.java +++ b/curator-recipes/src/test/java/org/apache/curator/framework/recipes/shared/TestSharedCount.java @@ -24,6 +24,18 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import com.google.common.collect.Lists; import com.google.common.util.concurrent.ThreadFactoryBuilder; +import java.util.List; +import java.util.Random; +import java.util.concurrent.Callable; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.Phaser; +import java.util.concurrent.Semaphore; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.api.BackgroundCallback; @@ -39,92 +51,62 @@ import org.apache.zookeeper.WatchedEvent; import org.junit.jupiter.api.Test; -import java.util.List; -import java.util.Random; -import java.util.concurrent.Callable; -import java.util.concurrent.CopyOnWriteArrayList; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; -import java.util.concurrent.Phaser; -import java.util.concurrent.Semaphore; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicInteger; - -public class TestSharedCount extends CuratorTestBase -{ +public class TestSharedCount extends CuratorTestBase { @Test - public void testMultiClients() throws Exception - { + public void testMultiClients() throws Exception { final int CLIENT_QTY = 5; List>> futures = Lists.newArrayList(); final List clients = new CopyOnWriteArrayList(); final List counts = new CopyOnWriteArrayList(); - try - { + try { final CountDownLatch startLatch = new CountDownLatch(CLIENT_QTY); final Semaphore semaphore = new Semaphore(0); - ExecutorService service = Executors.newCachedThreadPool(new ThreadFactoryBuilder().setNameFormat("Test-%d").build()); - for ( int i = 0; i < CLIENT_QTY; ++i ) - { - Future> future = service.submit - ( - new Callable>() - { + ExecutorService service = Executors.newCachedThreadPool( + new ThreadFactoryBuilder().setNameFormat("Test-%d").build()); + for (int i = 0; i < CLIENT_QTY; ++i) { + Future> future = service.submit(new Callable>() { + @Override + public List call() throws Exception { + final List countList = Lists.newArrayList(); + CuratorFramework client = + CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); + clients.add(client); + client.start(); + client.checkExists().forPath("/"); // clear initial connect event + + SharedCount count = new SharedCount(client, "/count", 10); + counts.add(count); + + final CountDownLatch latch = new CountDownLatch(1); + count.addListener(new SharedCountListener() { @Override - public List call() throws Exception - { - final List countList = Lists.newArrayList(); - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); - clients.add(client); - client.start(); - client.checkExists().forPath("/"); // clear initial connect event - - SharedCount count = new SharedCount(client, "/count", 10); - counts.add(count); - - final CountDownLatch latch = new CountDownLatch(1); - count.addListener - ( - new SharedCountListener() - { - @Override - public void countHasChanged(SharedCountReader sharedCount, int newCount) throws Exception - { - if ( newCount < 0 ) - { - latch.countDown(); - } - else - { - countList.add(newCount); - } - - semaphore.release(); - } - - @Override - public void stateChanged(CuratorFramework client, ConnectionState newState) - { - } - } - ); - count.start(); - startLatch.countDown(); - latch.await(); - return countList; + public void countHasChanged(SharedCountReader sharedCount, int newCount) throws Exception { + if (newCount < 0) { + latch.countDown(); + } else { + countList.add(newCount); + } + + semaphore.release(); } - } - ); + + @Override + public void stateChanged(CuratorFramework client, ConnectionState newState) {} + }); + count.start(); + startLatch.countDown(); + latch.await(); + return countList; + } + }); futures.add(future); } CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); clients.add(client); client.start(); - client.checkExists().forPath("/"); // clear initial connect event + client.checkExists().forPath("/"); // clear initial connect event assertTrue(startLatch.await(10, TimeUnit.SECONDS)); @@ -134,8 +116,7 @@ public void stateChanged(CuratorFramework client, ConnectionState newState) List countList = Lists.newArrayList(); Random random = new Random(); - for ( int i = 0; i < 100; ++i ) - { + for (int i = 0; i < 100; ++i) { Thread.sleep(random.nextInt(10)); int next = random.nextInt(100); @@ -146,47 +127,37 @@ public void stateChanged(CuratorFramework client, ConnectionState newState) } count.setCount(-1); - for ( Future> future : futures ) - { + for (Future> future : futures) { List thisCountList = future.get(); assertEquals(thisCountList, countList); } - } - finally - { - for ( SharedCount count : counts ) - { + } finally { + for (SharedCount count : counts) { CloseableUtils.closeQuietly(count); } - for ( CuratorFramework client : clients ) - { + for (CuratorFramework client : clients) { CloseableUtils.closeQuietly(client); } } } @Test - public void testSimple() throws Exception - { + public void testSimple() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); SharedCount count = new SharedCount(client, "/count", 0); - try - { + try { client.start(); count.start(); final CountDownLatch setLatch = new CountDownLatch(3); - SharedCountListener listener = new SharedCountListener() - { + SharedCountListener listener = new SharedCountListener() { @Override - public void countHasChanged(SharedCountReader sharedCount, int newCount) throws Exception - { + public void countHasChanged(SharedCountReader sharedCount, int newCount) throws Exception { setLatch.countDown(); } @Override - public void stateChanged(CuratorFramework client, ConnectionState newState) - { + public void stateChanged(CuratorFramework client, ConnectionState newState) { // nop } }; @@ -201,22 +172,18 @@ public void stateChanged(CuratorFramework client, ConnectionState newState) assertEquals(count.getCount(), 10); assertTrue(new Timing().awaitLatch(setLatch)); - } - finally - { + } finally { CloseableUtils.closeQuietly(count); CloseableUtils.closeQuietly(client); } } @Test - public void testSimpleVersioned() throws Exception - { + public void testSimpleVersioned() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); SharedCount count = new SharedCount(client, "/count", 0); client.start(); - try - { + try { count.start(); VersionedValue current = count.getVersionedValue(); @@ -246,24 +213,20 @@ public void testSimpleVersioned() throws Exception // Server changed client.setData().forPath("/count", SharedCount.toBytes(88)); assertFalse(count.trySetCount(current, 234)); - } - finally - { + } finally { CloseableUtils.closeQuietly(count); CloseableUtils.closeQuietly(client); } } @Test - public void testMultiClientVersioned() throws Exception - { + public void testMultiClientVersioned() throws Exception { Timing timing = new Timing(); CuratorFramework client1 = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); CuratorFramework client2 = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); SharedCount count1 = new SharedCount(client1, "/count", 0); SharedCount count2 = new SharedCount(client2, "/count", 0); - try - { + try { client1.start(); client2.start(); count1.start(); @@ -277,17 +240,14 @@ public void testMultiClientVersioned() throws Exception timing.sleepABit(); final CountDownLatch setLatch = new CountDownLatch(2); - SharedCountListener listener = new SharedCountListener() - { + SharedCountListener listener = new SharedCountListener() { @Override - public void countHasChanged(SharedCountReader sharedCount, int newCount) throws Exception - { + public void countHasChanged(SharedCountReader sharedCount, int newCount) throws Exception { setLatch.countDown(); } @Override - public void stateChanged(CuratorFramework client, ConnectionState newState) - { + public void stateChanged(CuratorFramework client, ConnectionState newState) { // nop } }; @@ -300,9 +260,7 @@ public void stateChanged(CuratorFramework client, ConnectionState newState) versionedValue1 = count1.getVersionedValue(); assertTrue(count1.trySetCount(versionedValue1, 40)); assertTrue(timing.awaitLatch(setLatch)); - } - finally - { + } finally { CloseableUtils.closeQuietly(count2); CloseableUtils.closeQuietly(count1); CloseableUtils.closeQuietly(client2); @@ -310,16 +268,13 @@ public void stateChanged(CuratorFramework client, ConnectionState newState) } } - @Test - public void testMultiClientDifferentSeed() throws Exception - { + public void testMultiClientDifferentSeed() throws Exception { CuratorFramework client1 = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); CuratorFramework client2 = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); SharedCount count1 = new SharedCount(client1, "/count", 10); SharedCount count2 = new SharedCount(client2, "/count", 20); - try - { + try { client1.start(); client2.start(); count1.start(); @@ -327,9 +282,7 @@ public void testMultiClientDifferentSeed() throws Exception assertEquals(count1.getCount(), 10); assertEquals(count2.getCount(), 10); - } - finally - { + } finally { CloseableUtils.closeQuietly(count2); CloseableUtils.closeQuietly(count1); CloseableUtils.closeQuietly(client2); @@ -337,13 +290,12 @@ public void testMultiClientDifferentSeed() throws Exception } } - @Test - public void testDisconnectEventOnWatcherDoesNotRetry() throws Exception - { + public void testDisconnectEventOnWatcherDoesNotRetry() throws Exception { final CountDownLatch gotSuspendEvent = new CountDownLatch(1); - CuratorFramework curatorFramework = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryNTimes(10, 1000)); + CuratorFramework curatorFramework = + CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryNTimes(10, 1000)); curatorFramework.start(); curatorFramework.blockUntilConnected(); @@ -359,29 +311,26 @@ public void stateChanged(CuratorFramework client, ConnectionState newState) { } }); - try - { + try { server.stop(); // if watcher goes into 10second retry loop we won't get timely notification assertTrue(gotSuspendEvent.await(5, TimeUnit.SECONDS)); - } - finally - { + } finally { CloseableUtils.closeQuietly(sharedCount); CloseableUtils.closeQuietly(curatorFramework); } } @Test - public void testDisconnectReconnectEventDoesNotFireValueWatcher() throws Exception - { + public void testDisconnectReconnectEventDoesNotFireValueWatcher() throws Exception { final CountDownLatch gotSuspendEvent = new CountDownLatch(1); final CountDownLatch gotChangeEvent = new CountDownLatch(1); final CountDownLatch getReconnectEvent = new CountDownLatch(1); final AtomicInteger numChangeEvents = new AtomicInteger(0); - CuratorFramework curatorFramework = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryNTimes(10, 500)); + CuratorFramework curatorFramework = + CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryNTimes(10, 500)); curatorFramework.start(); curatorFramework.blockUntilConnected(); @@ -405,8 +354,7 @@ public void stateChanged(CuratorFramework client, ConnectionState newState) { }); sharedCount.start(); - try - { + try { sharedCount.setCount(11); assertTrue(gotChangeEvent.await(2, TimeUnit.SECONDS)); @@ -421,60 +369,60 @@ public void stateChanged(CuratorFramework client, ConnectionState newState) { // flush background task queue final CountDownLatch flushDone = new CountDownLatch(1); - curatorFramework.getData().inBackground(new BackgroundCallback() { - @Override - public void processResult(CuratorFramework client, CuratorEvent event) throws Exception { - flushDone.countDown(); - } - }).forPath("/count"); + curatorFramework + .getData() + .inBackground(new BackgroundCallback() { + @Override + public void processResult(CuratorFramework client, CuratorEvent event) throws Exception { + flushDone.countDown(); + } + }) + .forPath("/count"); flushDone.await(5, TimeUnit.SECONDS); // CURATOR-311: when a Curator client's state became RECONNECTED, countHasChanged method is called back - // because the Curator client calls readValueAndNotifyListenersInBackground in SharedValue#ConnectionStateListener#stateChanged. + // because the Curator client calls readValueAndNotifyListenersInBackground in + // SharedValue#ConnectionStateListener#stateChanged. assertTrue(numChangeEvents.get() > 2); - } - finally - { + } finally { CloseableUtils.closeQuietly(sharedCount); CloseableUtils.closeQuietly(curatorFramework); } } - @Test - public void testDisconnectReconnectWithMultipleClients() throws Exception - { + public void testDisconnectReconnectWithMultipleClients() throws Exception { Timing timing = new Timing(); - CuratorFramework curatorFramework1 = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryNTimes(10, 500)); - CuratorFramework curatorFramework2 = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryNTimes(10, 500)); + CuratorFramework curatorFramework1 = + CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryNTimes(10, 500)); + CuratorFramework curatorFramework2 = + CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryNTimes(10, 500)); curatorFramework1.start(); - curatorFramework1.checkExists().forPath("/"); // clear initial connect events + curatorFramework1.checkExists().forPath("/"); // clear initial connect events curatorFramework2.start(); - curatorFramework2.checkExists().forPath("/"); // clear initial connect events + curatorFramework2.checkExists().forPath("/"); // clear initial connect events final String sharedCountPath = "/count"; final int initialCount = 10; SharedCount sharedCount1 = new SharedCount(curatorFramework1, sharedCountPath, initialCount); - SharedCount sharedCountWithFaultyWatcher = createSharedCountWithFaultyWatcher(curatorFramework2, sharedCountPath, initialCount); + SharedCount sharedCountWithFaultyWatcher = + createSharedCountWithFaultyWatcher(curatorFramework2, sharedCountPath, initialCount); - class MySharedCountListener implements SharedCountListener - { - final public Phaser gotSuspendEvent = new Phaser(1); - final public Phaser gotChangeEvent = new Phaser(1); - final public Phaser getReconnectEvent = new Phaser(1); - final public AtomicInteger numChangeEvents = new AtomicInteger(0); + class MySharedCountListener implements SharedCountListener { + public final Phaser gotSuspendEvent = new Phaser(1); + public final Phaser gotChangeEvent = new Phaser(1); + public final Phaser getReconnectEvent = new Phaser(1); + public final AtomicInteger numChangeEvents = new AtomicInteger(0); @Override - public void countHasChanged(SharedCountReader sharedCount, int newCount) throws Exception - { + public void countHasChanged(SharedCountReader sharedCount, int newCount) throws Exception { numChangeEvents.incrementAndGet(); gotChangeEvent.arrive(); } @Override - public void stateChanged(CuratorFramework client, ConnectionState newState) - { + public void stateChanged(CuratorFramework client, ConnectionState newState) { if (newState == ConnectionState.SUSPENDED) { gotSuspendEvent.arrive(); } else if (newState == ConnectionState.RECONNECTED) { @@ -489,8 +437,7 @@ public void stateChanged(CuratorFramework client, ConnectionState newState) MySharedCountListener listener2 = new MySharedCountListener(); sharedCountWithFaultyWatcher.addListener(listener2); - try - { + try { sharedCount1.setCount(12); assertEquals(listener1.gotChangeEvent.awaitAdvanceInterruptibly(0, timing.seconds(), TimeUnit.SECONDS), 1); assertEquals(sharedCount1.getCount(), 12); @@ -505,15 +452,19 @@ public void stateChanged(CuratorFramework client, ConnectionState newState) server.restart(); - assertEquals(listener2.getReconnectEvent.awaitAdvanceInterruptibly(i, timing.forWaiting().seconds(), TimeUnit.SECONDS), i + 1); + assertEquals( + listener2.getReconnectEvent.awaitAdvanceInterruptibly( + i, timing.forWaiting().seconds(), TimeUnit.SECONDS), + i + 1); // CURATOR-311 introduces to Curator's client reading server's shared count value // when client's state gets ConnectionState.RECONNECTED. Following tests ensures that. - assertEquals(listener2.gotChangeEvent.awaitAdvanceInterruptibly(i, timing.forWaiting().seconds(), TimeUnit.SECONDS), i + 1); + assertEquals( + listener2.gotChangeEvent.awaitAdvanceInterruptibly( + i, timing.forWaiting().seconds(), TimeUnit.SECONDS), + i + 1); assertEquals(sharedCountWithFaultyWatcher.getCount(), 13 + i); } - } - finally - { + } finally { CloseableUtils.closeQuietly(sharedCount1); CloseableUtils.closeQuietly(curatorFramework1); CloseableUtils.closeQuietly(sharedCountWithFaultyWatcher); @@ -534,16 +485,16 @@ class FaultySharedValue extends SharedValue { public FaultySharedValue(CuratorFramework client, String path, byte[] seedValue) { super(client.newWatcherRemoveCuratorFramework(), path, seedValue, faultyWatcher); } - }; + } + ; final SharedValue faultySharedValue = new FaultySharedValue(curatorFramework, path, SharedCount.toBytes(val)); class FaultySharedCount extends SharedCount { public FaultySharedCount(CuratorFramework client, String path, int val) { super(client, path, faultySharedValue); } - }; + } + ; return new FaultySharedCount(curatorFramework, path, val); } - - } diff --git a/curator-recipes/src/test/java/org/apache/curator/framework/recipes/watch/TestPersistentWatcher.java b/curator-recipes/src/test/java/org/apache/curator/framework/recipes/watch/TestPersistentWatcher.java index fd73de60c..f486bd534 100644 --- a/curator-recipes/src/test/java/org/apache/curator/framework/recipes/watch/TestPersistentWatcher.java +++ b/curator-recipes/src/test/java/org/apache/curator/framework/recipes/watch/TestPersistentWatcher.java @@ -21,7 +21,9 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; - +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.LinkedBlockingQueue; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.state.ConnectionState; @@ -32,45 +34,33 @@ import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.LinkedBlockingQueue; - @Tag(CuratorTestBase.zk36Group) -public class TestPersistentWatcher extends CuratorTestBase -{ +public class TestPersistentWatcher extends CuratorTestBase { @Test - public void testConnectionLostRecursive() throws Exception - { + public void testConnectionLostRecursive() throws Exception { internalTest(true); } @Test - public void testConnectionLost() throws Exception - { + public void testConnectionLost() throws Exception { internalTest(false); } - private void internalTest(boolean recursive) throws Exception - { - try ( CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)) ) - { + private void internalTest(boolean recursive) throws Exception { + try (CuratorFramework client = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1))) { CountDownLatch lostLatch = new CountDownLatch(1); CountDownLatch reconnectedLatch = new CountDownLatch(1); client.start(); client.getConnectionStateListenable().addListener((__, newState) -> { - if ( newState == ConnectionState.LOST ) - { + if (newState == ConnectionState.LOST) { lostLatch.countDown(); - } - else if ( newState == ConnectionState.RECONNECTED ) - { + } else if (newState == ConnectionState.RECONNECTED) { reconnectedLatch.countDown(); } }); - try ( PersistentWatcher persistentWatcher = new PersistentWatcher(client, "/top/main", recursive) ) - { + try (PersistentWatcher persistentWatcher = new PersistentWatcher(client, "/top/main", recursive)) { persistentWatcher.start(); BlockingQueue events = new LinkedBlockingQueue<>(); @@ -78,13 +68,10 @@ else if ( newState == ConnectionState.RECONNECTED ) client.create().creatingParentsIfNeeded().forPath("/top/main/a"); assertEquals(timing.takeFromQueue(events).getPath(), "/top/main"); - if ( recursive ) - { + if (recursive) { assertEquals(timing.takeFromQueue(events).getPath(), "/top/main/a"); - } - else - { - assertEquals(timing.takeFromQueue(events).getPath(), "/top/main"); // child added + } else { + assertEquals(timing.takeFromQueue(events).getPath(), "/top/main"); // child added } server.stop(); @@ -94,11 +81,10 @@ else if ( newState == ConnectionState.RECONNECTED ) server.restart(); assertTrue(timing.awaitLatch(reconnectedLatch)); - timing.sleepABit(); // time to allow watcher to get reset + timing.sleepABit(); // time to allow watcher to get reset events.clear(); - if ( recursive ) - { + if (recursive) { client.setData().forPath("/top/main/a", "foo".getBytes()); assertEquals(timing.takeFromQueue(events).getType(), Watcher.Event.EventType.NodeDataChanged); } @@ -107,4 +93,4 @@ else if ( newState == ConnectionState.RECONNECTED ) } } } -} \ No newline at end of file +} diff --git a/curator-test-zk35/src/test/java/org/apache/curator/framework/TestCompatibility.java b/curator-test-zk35/src/test/java/org/apache/curator/framework/TestCompatibility.java index 5434c1b83..f4abfd735 100644 --- a/curator-test-zk35/src/test/java/org/apache/curator/framework/TestCompatibility.java +++ b/curator-test-zk35/src/test/java/org/apache/curator/framework/TestCompatibility.java @@ -26,14 +26,13 @@ import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; -public class TestCompatibility extends CuratorTestBase -{ +public class TestCompatibility extends CuratorTestBase { @Test @Tag(zk35TestCompatibilityGroup) - public void testPersistentWatchesNotAvailable() - { - assertThrows(IllegalStateException.class, ()-> { - try (CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1))) { + public void testPersistentWatchesNotAvailable() { + assertThrows(IllegalStateException.class, () -> { + try (CuratorFramework client = + CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1))) { client.start(); client.watchers().add().forPath("/foo"); } @@ -42,11 +41,10 @@ public void testPersistentWatchesNotAvailable() @Test @Tag(zk35TestCompatibilityGroup) - public void testPersistentWatchesNotAvailableAsync() - { - assertThrows(IllegalStateException.class, ()->{ - try ( CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)) ) - { + public void testPersistentWatchesNotAvailableAsync() { + assertThrows(IllegalStateException.class, () -> { + try (CuratorFramework client = + CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1))) { client.start(); AsyncCuratorFramework async = AsyncCuratorFramework.wrap(client); diff --git a/curator-test-zk35/src/test/java/org/apache/curator/zk35/TestIs35.java b/curator-test-zk35/src/test/java/org/apache/curator/zk35/TestIs35.java index 283f1f89e..9af5368f3 100644 --- a/curator-test-zk35/src/test/java/org/apache/curator/zk35/TestIs35.java +++ b/curator-test-zk35/src/test/java/org/apache/curator/zk35/TestIs35.java @@ -26,21 +26,17 @@ import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; -public class TestIs35 extends CuratorTestBase -{ +public class TestIs35 extends CuratorTestBase { @Test @Tag(zk35TestCompatibilityGroup) - public void testIsZk35() - { + public void testIsZk35() { assertFalse(Compatibility.hasGetReachableOrOneMethod()); assertTrue(Compatibility.hasAddrField()); assertFalse(Compatibility.hasPersistentWatchers()); } @Override - protected void createServer() - { + protected void createServer() { // NOP } } - diff --git a/curator-test-zk36/src/test/java/org/apache/curator/zk36/TestIs36.java b/curator-test-zk36/src/test/java/org/apache/curator/zk36/TestIs36.java index bfe7b2485..373160bf7 100644 --- a/curator-test-zk36/src/test/java/org/apache/curator/zk36/TestIs36.java +++ b/curator-test-zk36/src/test/java/org/apache/curator/zk36/TestIs36.java @@ -21,30 +21,27 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; - import org.apache.curator.test.compatibility.CuratorTestBase; import org.apache.curator.utils.Compatibility; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; -public class TestIs36 extends CuratorTestBase -{ +public class TestIs36 extends CuratorTestBase { @Test @Tag(zk36Group) - public void testIsZk36() - { + public void testIsZk36() { assertTrue(Compatibility.hasGetReachableOrOneMethod()); assertTrue(Compatibility.hasAddrField()); assertTrue(Compatibility.hasPersistentWatchers()); try { Class.forName("org.apache.zookeeper.proto.WhoAmIResponse"); fail("WhoAmIResponse is introduced after ZooKeeper 3.7"); - } catch (ClassNotFoundException ignore) {} + } catch (ClassNotFoundException ignore) { + } } @Override - protected void createServer() - { + protected void createServer() { // NOP } } diff --git a/curator-test/src/main/java/org/apache/curator/test/BaseClassForTests.java b/curator-test/src/main/java/org/apache/curator/test/BaseClassForTests.java index feb3c3dcd..fe1393efb 100644 --- a/curator-test/src/main/java/org/apache/curator/test/BaseClassForTests.java +++ b/curator-test/src/main/java/org/apache/curator/test/BaseClassForTests.java @@ -19,16 +19,15 @@ package org.apache.curator.test; +import java.io.IOException; +import java.net.BindException; +import java.util.concurrent.atomic.AtomicBoolean; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.io.IOException; -import java.net.BindException; -import java.util.concurrent.atomic.AtomicBoolean; -public class BaseClassForTests -{ +public class BaseClassForTests { protected volatile TestingServer server; private final Logger log = LoggerFactory.getLogger(getClass()); @@ -38,60 +37,51 @@ public class BaseClassForTests private static final String INTERNAL_PROPERTY_REMOVE_WATCHERS_IN_FOREGROUND; private static final String INTERNAL_PROPERTY_VALIDATE_NAMESPACE_WATCHER_MAP_EMPTY; - static - { + static { String logConnectionIssues = null; - try - { + try { // use reflection to avoid adding a circular dependency in the pom Class debugUtilsClazz = Class.forName("org.apache.curator.utils.DebugUtils"); - logConnectionIssues = (String)debugUtilsClazz.getField("PROPERTY_DONT_LOG_CONNECTION_ISSUES").get(null); - } - catch ( Exception e ) - { + logConnectionIssues = (String) debugUtilsClazz + .getField("PROPERTY_DONT_LOG_CONNECTION_ISSUES") + .get(null); + } catch (Exception e) { e.printStackTrace(); } INTERNAL_PROPERTY_DONT_LOG_CONNECTION_ISSUES = logConnectionIssues; String s = null; - try - { + try { // use reflection to avoid adding a circular dependency in the pom - s = (String)Class.forName("org.apache.curator.utils.DebugUtils").getField("PROPERTY_REMOVE_WATCHERS_IN_FOREGROUND").get(null); - } - catch ( Exception e ) - { + s = (String) Class.forName("org.apache.curator.utils.DebugUtils") + .getField("PROPERTY_REMOVE_WATCHERS_IN_FOREGROUND") + .get(null); + } catch (Exception e) { e.printStackTrace(); } INTERNAL_PROPERTY_REMOVE_WATCHERS_IN_FOREGROUND = s; s = null; - try - { + try { // use reflection to avoid adding a circular dependency in the pom - s = (String)Class.forName("org.apache.curator.utils.DebugUtils").getField("PROPERTY_VALIDATE_NAMESPACE_WATCHER_MAP_EMPTY").get(null); - } - catch ( Exception e ) - { + s = (String) Class.forName("org.apache.curator.utils.DebugUtils") + .getField("PROPERTY_VALIDATE_NAMESPACE_WATCHER_MAP_EMPTY") + .get(null); + } catch (Exception e) { e.printStackTrace(); } INTERNAL_PROPERTY_VALIDATE_NAMESPACE_WATCHER_MAP_EMPTY = s; } @BeforeEach - public void setup() throws Exception - { - if ( INTERNAL_PROPERTY_DONT_LOG_CONNECTION_ISSUES != null ) - { + public void setup() throws Exception { + if (INTERNAL_PROPERTY_DONT_LOG_CONNECTION_ISSUES != null) { System.setProperty(INTERNAL_PROPERTY_DONT_LOG_CONNECTION_ISSUES, "true"); } System.setProperty(INTERNAL_PROPERTY_REMOVE_WATCHERS_IN_FOREGROUND, "true"); System.setProperty(INTERNAL_PROPERTY_VALIDATE_NAMESPACE_WATCHER_MAP_EMPTY, "true"); - try - { + try { createServer(); - } - catch ( FailedServerStartException ignore ) - { + } catch (FailedServerStartException ignore) { log.warn("Failed to start server - retrying 1 more time"); // server creation failed - we've sometime seen this with re-used addresses, etc. - retry one more time closeServer(); @@ -99,23 +89,16 @@ public void setup() throws Exception } } - public TestingCluster createAndStartCluster(int qty) throws Exception - { + public TestingCluster createAndStartCluster(int qty) throws Exception { TestingCluster cluster = new TestingCluster(qty); - try - { + try { cluster.start(); - } - catch ( FailedServerStartException e ) - { + } catch (FailedServerStartException e) { log.warn("Failed to start cluster - retrying 1 more time"); // cluster creation failed - we've sometime seen this with re-used addresses, etc. - retry one more time - try - { + try { cluster.close(); - } - catch ( Exception ex ) - { + } catch (Exception ex) { // ignore } cluster = new TestingCluster(qty); @@ -124,16 +107,11 @@ public TestingCluster createAndStartCluster(int qty) throws Exception return cluster; } - protected void createServer() throws Exception - { - while ( server == null ) - { - try - { + protected void createServer() throws Exception { + while (server == null) { + try { server = new TestingServer(); - } - catch ( BindException e ) - { + } catch (BindException e) { server = null; throw new FailedServerStartException("Getting bind exception - retrying to allocate server"); } @@ -141,27 +119,19 @@ protected void createServer() throws Exception } @AfterEach - public void teardown() throws Exception - { + public void teardown() throws Exception { System.clearProperty(INTERNAL_PROPERTY_VALIDATE_NAMESPACE_WATCHER_MAP_EMPTY); System.clearProperty(INTERNAL_PROPERTY_REMOVE_WATCHERS_IN_FOREGROUND); closeServer(); } - private void closeServer() - { - if ( server != null ) - { - try - { + private void closeServer() { + if (server != null) { + try { server.close(); - } - catch ( IOException e ) - { + } catch (IOException e) { e.printStackTrace(); - } - finally - { + } finally { server = null; } } diff --git a/curator-test/src/main/java/org/apache/curator/test/Compatibility.java b/curator-test/src/main/java/org/apache/curator/test/Compatibility.java index 804a5c386..f28ba4bf8 100644 --- a/curator-test/src/main/java/org/apache/curator/test/Compatibility.java +++ b/curator-test/src/main/java/org/apache/curator/test/Compatibility.java @@ -19,54 +19,48 @@ package org.apache.curator.test; +import java.lang.reflect.Method; import org.apache.zookeeper.server.ServerCnxn; import org.apache.zookeeper.server.ServerCnxnFactory; -import java.lang.reflect.Method; @SuppressWarnings({"unchecked", "rawtypes"}) -public class Compatibility -{ +public class Compatibility { private static final Method closeAllWithReasonMethod; private static final Method closeAllMethod; private static final Method closeWithReasonMethod; private static final Method closeMethod; private static final Object disconnectReasonObj; - static - { + static { Object localDisconnectReasonObj; Method localCloseAllWithReasonMethod; Method localCloseAllMethod; Method localCloseWithReasonMethod; Method localCloseMethod; - try - { + try { Class disconnectReasonClass = Class.forName("org.apache.zookeeper.server.ServerCnxn$DisconnectReason"); localDisconnectReasonObj = Enum.valueOf(disconnectReasonClass, "UNKNOWN"); - localCloseAllWithReasonMethod = ServerCnxnFactory.class.getDeclaredMethod("closeAll", disconnectReasonClass); + localCloseAllWithReasonMethod = + ServerCnxnFactory.class.getDeclaredMethod("closeAll", disconnectReasonClass); localCloseWithReasonMethod = ServerCnxn.class.getDeclaredMethod("close", disconnectReasonClass); localCloseAllMethod = null; localCloseMethod = null; localCloseAllWithReasonMethod.setAccessible(true); localCloseWithReasonMethod.setAccessible(true); - } - catch ( Throwable e ) - { + } catch (Throwable e) { localDisconnectReasonObj = null; localCloseAllWithReasonMethod = null; localCloseWithReasonMethod = null; - try - { + try { localCloseAllMethod = ServerCnxnFactory.class.getDeclaredMethod("closeAll"); localCloseMethod = ServerCnxn.class.getDeclaredMethod("close"); localCloseAllMethod.setAccessible(true); localCloseMethod.setAccessible(true); - } - catch ( Throwable ex ) - { - throw new IllegalStateException("Could not reflectively find ServerCnxnFactory/ServerCnxn close methods"); + } catch (Throwable ex) { + throw new IllegalStateException( + "Could not reflectively find ServerCnxnFactory/ServerCnxn close methods"); } } disconnectReasonObj = localDisconnectReasonObj; @@ -76,40 +70,26 @@ public class Compatibility closeWithReasonMethod = localCloseWithReasonMethod; } - public static void serverCnxnFactoryCloseAll(ServerCnxnFactory factory) - { - try - { - if ( closeAllMethod != null ) - { + public static void serverCnxnFactoryCloseAll(ServerCnxnFactory factory) { + try { + if (closeAllMethod != null) { closeAllMethod.invoke(factory); - } - else - { + } else { closeAllWithReasonMethod.invoke(factory, disconnectReasonObj); } - } - catch ( Exception e ) - { + } catch (Exception e) { throw new RuntimeException("Could not close factory", e); } } - public static void serverCnxnClose(ServerCnxn cnxn) - { - try - { - if ( closeMethod != null ) - { + public static void serverCnxnClose(ServerCnxn cnxn) { + try { + if (closeMethod != null) { closeMethod.invoke(cnxn); - } - else - { + } else { closeWithReasonMethod.invoke(cnxn, disconnectReasonObj); } - } - catch ( Exception e ) - { + } catch (Exception e) { throw new RuntimeException("Could not close connection", e); } } diff --git a/curator-test/src/main/java/org/apache/curator/test/DelegatingExecutorService.java b/curator-test/src/main/java/org/apache/curator/test/DelegatingExecutorService.java index 96b3167d9..b0550aaf0 100644 --- a/curator-test/src/main/java/org/apache/curator/test/DelegatingExecutorService.java +++ b/curator-test/src/main/java/org/apache/curator/test/DelegatingExecutorService.java @@ -23,98 +23,77 @@ import java.util.List; import java.util.concurrent.*; -public class DelegatingExecutorService implements ExecutorService -{ +public class DelegatingExecutorService implements ExecutorService { private final ExecutorService delegate; - public DelegatingExecutorService( - ExecutorService delegate - ) - { + public DelegatingExecutorService(ExecutorService delegate) { this.delegate = delegate; } - @Override - public void shutdown() - { + public void shutdown() { delegate.shutdown(); } @Override - public List shutdownNow() - { + public List shutdownNow() { return delegate.shutdownNow(); } @Override - public boolean isShutdown() - { + public boolean isShutdown() { return delegate.isShutdown(); } @Override - public boolean isTerminated() - { + public boolean isTerminated() { return delegate.isTerminated(); } @Override - public boolean awaitTermination(long timeout, TimeUnit unit) - throws InterruptedException - { + public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException { return delegate.awaitTermination(timeout, unit); } @Override - public Future submit(Callable task) - { + public Future submit(Callable task) { return delegate.submit(task); } @Override - public Future submit(Runnable task, T result) - { + public Future submit(Runnable task, T result) { return delegate.submit(task, result); } @Override - public Future submit(Runnable task) - { + public Future submit(Runnable task) { return delegate.submit(task); } @Override - public List> invokeAll(Collection> tasks) - throws InterruptedException - { + public List> invokeAll(Collection> tasks) throws InterruptedException { return delegate.invokeAll(tasks); } @Override public List> invokeAll(Collection> tasks, long timeout, TimeUnit unit) - throws InterruptedException - { + throws InterruptedException { return delegate.invokeAll(tasks, timeout, unit); } @Override - public T invokeAny(Collection> tasks) - throws InterruptedException, ExecutionException - { + public T invokeAny(Collection> tasks) throws InterruptedException, ExecutionException { return delegate.invokeAny(tasks); } @Override public T invokeAny(Collection> tasks, long timeout, TimeUnit unit) - throws InterruptedException, ExecutionException, TimeoutException - { + throws InterruptedException, ExecutionException, TimeoutException { return delegate.invokeAny(tasks, timeout, unit); } @Override - public void execute(Runnable command) - { + public void execute(Runnable command) { delegate.execute(command); } } diff --git a/curator-test/src/main/java/org/apache/curator/test/DirectoryUtils.java b/curator-test/src/main/java/org/apache/curator/test/DirectoryUtils.java index 2c7c1410e..a74501f5f 100644 --- a/curator-test/src/main/java/org/apache/curator/test/DirectoryUtils.java +++ b/curator-test/src/main/java/org/apache/curator/test/DirectoryUtils.java @@ -20,19 +20,18 @@ package org.apache.curator.test; import com.google.common.base.Preconditions; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; import java.io.UncheckedIOException; import java.nio.file.Files; import java.nio.file.Path; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; // copied from Google Guava as these methods are now deprecated // NOTE: removed the line of code documented: Symbolic links will have different canonical and absolute paths // Update May 28, 2017 - change exception into logs -public class DirectoryUtils -{ +public class DirectoryUtils { private static final Logger log = LoggerFactory.getLogger(DirectoryUtils.class); public static File createTempDirectory() { @@ -44,8 +43,7 @@ public static File createTempDirectory() { } } - public static void deleteRecursively(File file) throws IOException - { + public static void deleteRecursively(File file) throws IOException { if (file.isDirectory()) { deleteDirectoryContents(file); } @@ -54,10 +52,8 @@ public static void deleteRecursively(File file) throws IOException } } - public static void deleteDirectoryContents(File directory) - throws IOException { - Preconditions.checkArgument(directory.isDirectory(), - "Not a directory: %s", directory); + public static void deleteDirectoryContents(File directory) throws IOException { + Preconditions.checkArgument(directory.isDirectory(), "Not a directory: %s", directory); File[] files = directory.listFiles(); if (files == null) { log.warn("directory.listFiles() returned null for: " + directory); diff --git a/curator-test/src/main/java/org/apache/curator/test/ExecuteCalledWatchingExecutorService.java b/curator-test/src/main/java/org/apache/curator/test/ExecuteCalledWatchingExecutorService.java index 0bdb4485e..2ccb392a1 100644 --- a/curator-test/src/main/java/org/apache/curator/test/ExecuteCalledWatchingExecutorService.java +++ b/curator-test/src/main/java/org/apache/curator/test/ExecuteCalledWatchingExecutorService.java @@ -21,29 +21,24 @@ import java.util.concurrent.ExecutorService; -public class ExecuteCalledWatchingExecutorService extends DelegatingExecutorService -{ +public class ExecuteCalledWatchingExecutorService extends DelegatingExecutorService { boolean executeCalled = false; - public ExecuteCalledWatchingExecutorService(ExecutorService delegate) - { + public ExecuteCalledWatchingExecutorService(ExecutorService delegate) { super(delegate); } @Override - public synchronized void execute(Runnable command) - { + public synchronized void execute(Runnable command) { executeCalled = true; super.execute(command); } - public synchronized boolean isExecuteCalled() - { + public synchronized boolean isExecuteCalled() { return executeCalled; } - public synchronized void setExecuteCalled(boolean executeCalled) - { + public synchronized void setExecuteCalled(boolean executeCalled) { this.executeCalled = executeCalled; } } diff --git a/curator-test/src/main/java/org/apache/curator/test/FailedServerStartException.java b/curator-test/src/main/java/org/apache/curator/test/FailedServerStartException.java index 0c7db3706..59ef3b421 100644 --- a/curator-test/src/main/java/org/apache/curator/test/FailedServerStartException.java +++ b/curator-test/src/main/java/org/apache/curator/test/FailedServerStartException.java @@ -19,15 +19,12 @@ package org.apache.curator.test; -public class FailedServerStartException extends IllegalStateException -{ - public FailedServerStartException(Throwable cause) - { +public class FailedServerStartException extends IllegalStateException { + public FailedServerStartException(Throwable cause) { super(cause); } - public FailedServerStartException(String s) - { + public FailedServerStartException(String s) { super(s); } } diff --git a/curator-test/src/main/java/org/apache/curator/test/InstanceSpec.java b/curator-test/src/main/java/org/apache/curator/test/InstanceSpec.java index 02373164a..a5beced5a 100644 --- a/curator-test/src/main/java/org/apache/curator/test/InstanceSpec.java +++ b/curator-test/src/main/java/org/apache/curator/test/InstanceSpec.java @@ -31,32 +31,25 @@ /** * Abstracts one of the servers in the ensemble */ -public class InstanceSpec -{ +public class InstanceSpec { private static final AtomicInteger nextServerId = new AtomicInteger(1); private static final String localhost; - static - { + static { String address = "localhost"; - try - { + try { // This is a workaround for people using OS X Lion. On Lion when a process tries to connect to a link-local // address it takes 5 seconds to establish the connection for some reason. So instead of using 'localhost' // which could return the link-local address randomly, we'll manually resolve it and look for an address to // return that isn't link-local. If for some reason we can't find an address that isn't link-local then // we'll fall back to the default lof just looking up 'localhost'. - for ( InetAddress a : InetAddress.getAllByName("localhost") ) - { - if ( !a.isLinkLocalAddress() ) - { + for (InetAddress a : InetAddress.getAllByName("localhost")) { + if (!a.isLinkLocalAddress()) { address = a.getHostAddress(); break; } } - } - catch ( UnknownHostException e ) - { + } catch (UnknownHostException e) { // Something went wrong, just default to the existing approach of using 'localhost'. } localhost = address; @@ -70,41 +63,30 @@ public class InstanceSpec private final int serverId; private final int tickTime; private final int maxClientCnxns; - private final Map customProperties; + private final Map customProperties; private final String hostname; public static void reset() { nextServerId.set(1); } - public static InstanceSpec newInstanceSpec() - { + public static InstanceSpec newInstanceSpec() { return new InstanceSpec(null, -1, -1, -1, true, -1, -1, -1); } - public static int getRandomPort() - { + public static int getRandomPort() { ServerSocket server = null; - try - { + try { server = new ServerSocket(0); server.setReuseAddress(true); return server.getLocalPort(); - } - catch ( IOException e ) - { + } catch (IOException e) { throw new Error(e); - } - finally - { - if ( server != null ) - { - try - { + } finally { + if (server != null) { + try { server.close(); - } - catch ( IOException ignore ) - { + } catch (IOException ignore) { // ignore } } @@ -119,8 +101,13 @@ public static int getRandomPort() * @param deleteDataDirectoryOnClose if true, the data directory will be deleted when {@link TestingCluster#close()} is called * @param serverId the server ID for the instance */ - public InstanceSpec(File dataDirectory, int port, int electionPort, int quorumPort, boolean deleteDataDirectoryOnClose, int serverId) - { + public InstanceSpec( + File dataDirectory, + int port, + int electionPort, + int quorumPort, + boolean deleteDataDirectoryOnClose, + int serverId) { this(dataDirectory, port, electionPort, quorumPort, deleteDataDirectoryOnClose, serverId, -1, -1, null, null); } @@ -134,8 +121,26 @@ public InstanceSpec(File dataDirectory, int port, int electionPort, int quorumPo * @param tickTime tickTime. Set -1 to used fault server configuration * @param maxClientCnxns max number of client connections from the same IP. Set -1 to use default server configuration */ - public InstanceSpec(File dataDirectory, int port, int electionPort, int quorumPort, boolean deleteDataDirectoryOnClose, int serverId, int tickTime, int maxClientCnxns) { - this(dataDirectory, port, electionPort, quorumPort, deleteDataDirectoryOnClose, serverId, tickTime, maxClientCnxns, null, null); + public InstanceSpec( + File dataDirectory, + int port, + int electionPort, + int quorumPort, + boolean deleteDataDirectoryOnClose, + int serverId, + int tickTime, + int maxClientCnxns) { + this( + dataDirectory, + port, + electionPort, + quorumPort, + deleteDataDirectoryOnClose, + serverId, + tickTime, + maxClientCnxns, + null, + null); } /** @@ -149,9 +154,27 @@ public InstanceSpec(File dataDirectory, int port, int electionPort, int quorumPo * @param maxClientCnxns max number of client connections from the same IP. Set -1 to use default server configuration * @param customProperties other properties to be passed to the server */ - public InstanceSpec(File dataDirectory, int port, int electionPort, int quorumPort, boolean deleteDataDirectoryOnClose, int serverId, int tickTime, int maxClientCnxns, Map customProperties) - { - this(dataDirectory, port, electionPort, quorumPort, deleteDataDirectoryOnClose, serverId, tickTime, maxClientCnxns, customProperties, null); + public InstanceSpec( + File dataDirectory, + int port, + int electionPort, + int quorumPort, + boolean deleteDataDirectoryOnClose, + int serverId, + int tickTime, + int maxClientCnxns, + Map customProperties) { + this( + dataDirectory, + port, + electionPort, + quorumPort, + deleteDataDirectoryOnClose, + serverId, + tickTime, + maxClientCnxns, + customProperties, + null); } /** @@ -166,8 +189,17 @@ public InstanceSpec(File dataDirectory, int port, int electionPort, int quorumPo * @param customProperties other properties to be passed to the server * @param hostname Hostname or IP if the cluster is intending to be bounded into external interfaces */ - public InstanceSpec(File dataDirectory, int port, int electionPort, int quorumPort, boolean deleteDataDirectoryOnClose, int serverId, int tickTime, int maxClientCnxns, Map customProperties,String hostname) - { + public InstanceSpec( + File dataDirectory, + int port, + int electionPort, + int quorumPort, + boolean deleteDataDirectoryOnClose, + int serverId, + int tickTime, + int maxClientCnxns, + Map customProperties, + String hostname) { this.dataDirectory = (dataDirectory != null) ? dataDirectory : DirectoryUtils.createTempDirectory(); this.port = (port >= 0) ? port : getRandomPort(); this.electionPort = (electionPort >= 0) ? electionPort : getRandomPort(); @@ -176,32 +208,29 @@ public InstanceSpec(File dataDirectory, int port, int electionPort, int quorumPo this.serverId = (serverId >= 0) ? serverId : nextServerId.getAndIncrement(); this.tickTime = (tickTime > 0 ? tickTime : -1); // -1 to set default value this.maxClientCnxns = (maxClientCnxns >= 0 ? maxClientCnxns : -1); // -1 to set default value - this.customProperties = customProperties != null ? Collections.unmodifiableMap(customProperties) : Collections.emptyMap(); + this.customProperties = customProperties != null + ? Collections.unmodifiableMap(customProperties) + : Collections.emptyMap(); this.hostname = hostname == null ? localhost : hostname; } - public int getServerId() - { + public int getServerId() { return serverId; } - public File getDataDirectory() - { + public File getDataDirectory() { return dataDirectory; } - public int getPort() - { + public int getPort() { return port; } - public int getElectionPort() - { + public int getElectionPort() { return electionPort; } - public int getQuorumPort() - { + public int getQuorumPort() { return quorumPort; } @@ -209,23 +238,19 @@ public int getQuorumPort() * @deprecated use {@link TestingServer#getConnectString()} or {@link TestingCluster#getConnectString()} instead */ @Deprecated - public String getConnectString() - { + public String getConnectString() { return hostname + ":" + port; } - public int getTickTime() - { + public int getTickTime() { return tickTime; } - public int getMaxClientCnxns() - { + public int getMaxClientCnxns() { return maxClientCnxns; } - public boolean deleteDataDirectoryOnClose() - { + public boolean deleteDataDirectoryOnClose() { return deleteDataDirectoryOnClose; } @@ -238,43 +263,37 @@ public String getHostname() { } @Override - public String toString() - { - return "InstanceSpec{" + - "dataDirectory=" + dataDirectory + - ", port=" + port + - ", electionPort=" + electionPort + - ", quorumPort=" + quorumPort + - ", deleteDataDirectoryOnClose=" + deleteDataDirectoryOnClose + - ", serverId=" + serverId + - ", tickTime=" + tickTime + - ", maxClientCnxns=" + maxClientCnxns + - ", customProperties=" + customProperties + - ", hostname=" + hostname + - "} " + super.toString(); + public String toString() { + return "InstanceSpec{" + "dataDirectory=" + + dataDirectory + ", port=" + + port + ", electionPort=" + + electionPort + ", quorumPort=" + + quorumPort + ", deleteDataDirectoryOnClose=" + + deleteDataDirectoryOnClose + ", serverId=" + + serverId + ", tickTime=" + + tickTime + ", maxClientCnxns=" + + maxClientCnxns + ", customProperties=" + + customProperties + ", hostname=" + + hostname + "} " + + super.toString(); } @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; } - InstanceSpec that = (InstanceSpec)o; + InstanceSpec that = (InstanceSpec) o; return hostname.equals(that.getHostname()) && port == that.port; - } @Override - public int hashCode() - { + public int hashCode() { return hostname.hashCode() + port; } } diff --git a/curator-test/src/main/java/org/apache/curator/test/KillSession.java b/curator-test/src/main/java/org/apache/curator/test/KillSession.java index 684ca377d..d9008d511 100644 --- a/curator-test/src/main/java/org/apache/curator/test/KillSession.java +++ b/curator-test/src/main/java/org/apache/curator/test/KillSession.java @@ -26,16 +26,14 @@ * Utility to simulate a ZK session dying. *

*/ -public class KillSession -{ +public class KillSession { /** * Kill the given ZK session * * @param client the client to kill * @since 3.0.0 */ - public static void kill(ZooKeeper client) - { + public static void kill(ZooKeeper client) { client.getTestable().injectSessionExpiration(); } @@ -47,8 +45,7 @@ public static void kill(ZooKeeper client) * @throws Exception errors * @deprecated use {@link #kill(ZooKeeper)} instead */ - public static void kill(ZooKeeper client, String connectString) throws Exception - { + public static void kill(ZooKeeper client, String connectString) throws Exception { kill(client); } @@ -61,8 +58,7 @@ public static void kill(ZooKeeper client, String connectString) throws Excep * @throws Exception errors * @deprecated use {@link #kill(ZooKeeper)} instead */ - public static void kill(ZooKeeper client, String connectString, int maxMs) throws Exception - { + public static void kill(ZooKeeper client, String connectString, int maxMs) throws Exception { kill(client); } } diff --git a/curator-test/src/main/java/org/apache/curator/test/QuorumConfigBuilder.java b/curator-test/src/main/java/org/apache/curator/test/QuorumConfigBuilder.java index 5d22b746f..9b8b951a8 100644 --- a/curator-test/src/main/java/org/apache/curator/test/QuorumConfigBuilder.java +++ b/curator-test/src/main/java/org/apache/curator/test/QuorumConfigBuilder.java @@ -22,8 +22,6 @@ import com.google.common.base.Throwables; import com.google.common.collect.ImmutableList; import com.google.common.io.Files; -import org.apache.curator.test.compatibility.Timing2; -import org.apache.zookeeper.server.quorum.QuorumPeerConfig; import java.io.Closeable; import java.io.File; import java.io.IOException; @@ -31,84 +29,69 @@ import java.util.List; import java.util.Map; import java.util.Properties; +import org.apache.curator.test.compatibility.Timing2; +import org.apache.zookeeper.server.quorum.QuorumPeerConfig; @SuppressWarnings("UnusedDeclaration") -public class QuorumConfigBuilder implements Closeable -{ +public class QuorumConfigBuilder implements Closeable { private final ImmutableList instanceSpecs; private final boolean fromRandom; private final File fakeConfigFile; - public QuorumConfigBuilder(Collection specs) - { + public QuorumConfigBuilder(Collection specs) { this(specs.toArray(new InstanceSpec[0])); } - public QuorumConfigBuilder(InstanceSpec... specs) - { + public QuorumConfigBuilder(InstanceSpec... specs) { fromRandom = (specs == null) || (specs.length == 0); instanceSpecs = fromRandom ? ImmutableList.of(InstanceSpec.newInstanceSpec()) : ImmutableList.copyOf(specs); File fakeConfigFile = null; - try - { + try { fakeConfigFile = File.createTempFile("temp", "temp"); - } - catch ( IOException e ) - { + } catch (IOException e) { Throwables.propagate(e); } this.fakeConfigFile = fakeConfigFile; } - public boolean isFromRandom() - { + public boolean isFromRandom() { return fromRandom; } - public QuorumPeerConfig buildConfig() throws Exception - { + public QuorumPeerConfig buildConfig() throws Exception { return buildConfig(0); } - public InstanceSpec getInstanceSpec(int index) - { + public InstanceSpec getInstanceSpec(int index) { return instanceSpecs.get(index); } - public List getInstanceSpecs() - { + public List getInstanceSpecs() { return instanceSpecs; } - public int size() - { + public int size() { return instanceSpecs.size(); } @Override - public void close() - { - if ( fakeConfigFile != null ) - { + public void close() { + if (fakeConfigFile != null) { //noinspection ResultOfMethodCallIgnored fakeConfigFile.delete(); } } - public QuorumPeerConfig buildConfig(int instanceIndex) throws Exception - { + public QuorumPeerConfig buildConfig(int instanceIndex) throws Exception { InstanceSpec spec = instanceSpecs.get(instanceIndex); return buildConfig(instanceIndex, spec.getPort()); } - public QuorumPeerConfig buildConfig(int instanceIndex, int instancePort) throws Exception - { + public QuorumPeerConfig buildConfig(int instanceIndex, int instancePort) throws Exception { Properties properties = buildConfigProperties(instanceIndex, instancePort); - QuorumPeerConfig config = new QuorumPeerConfig() - { + QuorumPeerConfig config = new QuorumPeerConfig() { { - if ( fakeConfigFile != null ) - { + if (fakeConfigFile != null) { configFileStr = fakeConfigFile.getPath(); } } @@ -117,19 +100,16 @@ public QuorumPeerConfig buildConfig(int instanceIndex, int instancePort) throws return config; } - public Properties buildConfigProperties(int instanceIndex) throws Exception - { + public Properties buildConfigProperties(int instanceIndex) throws Exception { InstanceSpec spec = instanceSpecs.get(instanceIndex); return buildConfigProperties(instanceIndex, spec.getPort()); } - public Properties buildConfigProperties(int instanceIndex, int instancePort) throws Exception - { + public Properties buildConfigProperties(int instanceIndex, int instancePort) throws Exception { boolean isCluster = (instanceSpecs.size() > 1); InstanceSpec spec = instanceSpecs.get(instanceIndex); - if ( isCluster ) - { + if (isCluster) { Files.write(Integer.toString(spec.getServerId()).getBytes(), new File(spec.getDataDirectory(), "myid")); } @@ -145,20 +125,25 @@ public Properties buildConfigProperties(int instanceIndex, int instancePort) thr properties.setProperty("tickTime", tickTime); properties.setProperty("minSessionTimeout", tickTime); int maxClientCnxns = spec.getMaxClientCnxns(); - if ( maxClientCnxns >= 0 ) - { + if (maxClientCnxns >= 0) { properties.setProperty("maxClientCnxns", Integer.toString(maxClientCnxns)); } - if ( isCluster ) - { - for ( InstanceSpec thisSpec : instanceSpecs ) - { + if (isCluster) { + for (InstanceSpec thisSpec : instanceSpecs) { int clientPort = thisSpec == spec ? instancePort : thisSpec.getPort(); - properties.setProperty("server." + thisSpec.getServerId(), String.format("%s:%d:%d;%s:%d", thisSpec.getHostname(), thisSpec.getQuorumPort(), thisSpec.getElectionPort(), thisSpec.getHostname(), clientPort)); + properties.setProperty( + "server." + thisSpec.getServerId(), + String.format( + "%s:%d:%d;%s:%d", + thisSpec.getHostname(), + thisSpec.getQuorumPort(), + thisSpec.getElectionPort(), + thisSpec.getHostname(), + clientPort)); } } - Map customProperties = spec.getCustomProperties(); + Map customProperties = spec.getCustomProperties(); if (customProperties != null) { properties.putAll(customProperties); } diff --git a/curator-test/src/main/java/org/apache/curator/test/QuorumPeerConfigBuilder.java b/curator-test/src/main/java/org/apache/curator/test/QuorumPeerConfigBuilder.java index 8fce47186..294bb916e 100644 --- a/curator-test/src/main/java/org/apache/curator/test/QuorumPeerConfigBuilder.java +++ b/curator-test/src/main/java/org/apache/curator/test/QuorumPeerConfigBuilder.java @@ -19,9 +19,8 @@ package org.apache.curator.test; -import org.apache.zookeeper.server.quorum.QuorumPeerConfig; - import java.util.Properties; +import org.apache.zookeeper.server.quorum.QuorumPeerConfig; public class QuorumPeerConfigBuilder { private final QuorumConfigBuilder configBuilder; diff --git a/curator-test/src/main/java/org/apache/curator/test/ServerHelper.java b/curator-test/src/main/java/org/apache/curator/test/ServerHelper.java index 4577b6303..9d4f9dcbd 100644 --- a/curator-test/src/main/java/org/apache/curator/test/ServerHelper.java +++ b/curator-test/src/main/java/org/apache/curator/test/ServerHelper.java @@ -19,22 +19,20 @@ package org.apache.curator.test; -import org.apache.zookeeper.server.ZooKeeperServer; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.net.InetSocketAddress; +import org.apache.zookeeper.server.ZooKeeperServer; -class ServerHelper -{ - private static class ServerCnxnFactoryMethods - { +class ServerHelper { + private static class ServerCnxnFactoryMethods { private final Constructor constructor; private final Method configureMethod; private final Method startupMethod; private final Method shutdownMethod; - private ServerCnxnFactoryMethods(Constructor constructor, Method configureMethod, Method startupMethod, Method shutdownMethod) - { + private ServerCnxnFactoryMethods( + Constructor constructor, Method configureMethod, Method startupMethod, Method shutdownMethod) { this.constructor = constructor; this.configureMethod = configureMethod; this.startupMethod = startupMethod; @@ -42,71 +40,52 @@ private ServerCnxnFactoryMethods(Constructor constructor, Method configureMet } } - private static class NioServerCnxnMethods - { + private static class NioServerCnxnMethods { private final Constructor constructor; private final Method startupMethod; private final Method shutdownMethod; - private NioServerCnxnMethods(Constructor constructor, Method startupMethod, Method shutdownMethod) - { + private NioServerCnxnMethods(Constructor constructor, Method startupMethod, Method shutdownMethod) { this.constructor = constructor; this.startupMethod = startupMethod; this.shutdownMethod = shutdownMethod; } } - private static final ServerCnxnFactoryMethods serverCnxnFactoryMethods; + private static final ServerCnxnFactoryMethods serverCnxnFactoryMethods; private static final NioServerCnxnMethods nioServerCnxn; - static - { - Class serverCnxnFactoryClass = null; - Class nioServerCnxnFactoryClass = null; - try - { + static { + Class serverCnxnFactoryClass = null; + Class nioServerCnxnFactoryClass = null; + try { serverCnxnFactoryClass = Class.forName("org.apache.zookeeper.server.NIOServerCnxnFactory"); - } - catch ( ClassNotFoundException ignore ) - { + } catch (ClassNotFoundException ignore) { // ignore } - try - { + try { nioServerCnxnFactoryClass = Class.forName("org.apache.zookeeper.server.NIOServerCnxn$Factory"); - } - catch ( ClassNotFoundException ignore ) - { + } catch (ClassNotFoundException ignore) { // ignore } - ServerCnxnFactoryMethods localServerCnxnFactoryMethods = null; + ServerCnxnFactoryMethods localServerCnxnFactoryMethods = null; NioServerCnxnMethods localNioServerCnxn = null; - try - { - if ( serverCnxnFactoryClass != null ) - { - localServerCnxnFactoryMethods = new ServerCnxnFactoryMethods - ( - serverCnxnFactoryClass.getConstructor(), - serverCnxnFactoryClass.getDeclaredMethod("configure", InetSocketAddress.class, Integer.TYPE), - serverCnxnFactoryClass.getDeclaredMethod("startup", ZooKeeperServer.class), - serverCnxnFactoryClass.getDeclaredMethod("shutdown") - ); - } - else if ( nioServerCnxnFactoryClass != null ) - { - localNioServerCnxn = new NioServerCnxnMethods - ( - nioServerCnxnFactoryClass.getConstructor(InetSocketAddress.class), - nioServerCnxnFactoryClass.getDeclaredMethod("startup", ZooKeeperServer.class), - nioServerCnxnFactoryClass.getDeclaredMethod("shutdown") - ); + try { + if (serverCnxnFactoryClass != null) { + localServerCnxnFactoryMethods = new ServerCnxnFactoryMethods( + serverCnxnFactoryClass.getConstructor(), + serverCnxnFactoryClass.getDeclaredMethod("configure", InetSocketAddress.class, Integer.TYPE), + serverCnxnFactoryClass.getDeclaredMethod("startup", ZooKeeperServer.class), + serverCnxnFactoryClass.getDeclaredMethod("shutdown")); + } else if (nioServerCnxnFactoryClass != null) { + localNioServerCnxn = new NioServerCnxnMethods( + nioServerCnxnFactoryClass.getConstructor(InetSocketAddress.class), + nioServerCnxnFactoryClass.getDeclaredMethod("startup", ZooKeeperServer.class), + nioServerCnxnFactoryClass.getDeclaredMethod("shutdown")); } - } - catch ( Exception e ) - { + } catch (Exception e) { e.printStackTrace(); throw new Error(e); } @@ -115,50 +94,35 @@ else if ( nioServerCnxnFactoryClass != null ) nioServerCnxn = localNioServerCnxn; } - static Object makeFactory(ZooKeeperServer server, int port) throws Exception - { - Object factory; - if ( nioServerCnxn != null ) - { + static Object makeFactory(ZooKeeperServer server, int port) throws Exception { + Object factory; + if (nioServerCnxn != null) { factory = nioServerCnxn.constructor.newInstance(new InetSocketAddress(port)); - if ( server != null ) - { + if (server != null) { nioServerCnxn.startupMethod.invoke(factory, server); } - } - else - { + } else { factory = serverCnxnFactoryMethods.constructor.newInstance(); serverCnxnFactoryMethods.configureMethod.invoke(factory, new InetSocketAddress(port), 0); - if ( server != null ) - { + if (server != null) { serverCnxnFactoryMethods.startupMethod.invoke(factory, server); } } return factory; } - - static void shutdownFactory(Object factory) - { - try - { - if ( nioServerCnxn != null ) - { + + static void shutdownFactory(Object factory) { + try { + if (nioServerCnxn != null) { nioServerCnxn.shutdownMethod.invoke(factory); - } - else - { + } else { serverCnxnFactoryMethods.shutdownMethod.invoke(factory); } - } - catch ( Exception e ) - { + } catch (Exception e) { e.printStackTrace(); throw new Error(e); } } - private ServerHelper() - { - } + private ServerHelper() {} } diff --git a/curator-test/src/main/java/org/apache/curator/test/TestingCluster.java b/curator-test/src/main/java/org/apache/curator/test/TestingCluster.java index dc0dff1f3..07b3474f4 100644 --- a/curator-test/src/main/java/org/apache/curator/test/TestingCluster.java +++ b/curator-test/src/main/java/org/apache/curator/test/TestingCluster.java @@ -25,7 +25,6 @@ import com.google.common.collect.ImmutableMap; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; -import org.apache.zookeeper.ZooKeeper; import java.io.Closeable; import java.io.IOException; import java.lang.reflect.Method; @@ -33,13 +32,13 @@ import java.util.Collection; import java.util.List; import java.util.Map; +import org.apache.zookeeper.ZooKeeper; /** * manages an internally running ensemble of ZooKeeper servers. FOR TESTING PURPOSES ONLY */ -public class TestingCluster implements Closeable -{ - private final List servers; +public class TestingCluster implements Closeable { + private final List servers; /** * Creates an ensemble comprised of n servers. Each server will use @@ -47,8 +46,7 @@ public class TestingCluster implements Closeable * * @param instanceQty number of servers to create in the ensemble */ - public TestingCluster(int instanceQty) - { + public TestingCluster(int instanceQty) { this(makeSpecs(instanceQty)); } @@ -57,8 +55,7 @@ public TestingCluster(int instanceQty) * * @param specs the server specs */ - public TestingCluster(InstanceSpec... specs) - { + public TestingCluster(InstanceSpec... specs) { this(listToMap(ImmutableList.copyOf(specs))); } @@ -67,8 +64,7 @@ public TestingCluster(InstanceSpec... specs) * * @param specs the server specs */ - public TestingCluster(Collection specs) - { + public TestingCluster(Collection specs) { this(listToMap(specs)); } @@ -78,11 +74,9 @@ public TestingCluster(Collection specs) * @param specs map of an instance spec to its set of quorum instances. Allows simulation of an ensemble with instances * having different config peers */ - public TestingCluster(Map> specs) - { + public TestingCluster(Map> specs) { ImmutableList.Builder serverBuilder = ImmutableList.builder(); - for ( Map.Entry> entry : specs.entrySet() ) - { + for (Map.Entry> entry : specs.entrySet()) { List instanceSpecs = Lists.newArrayList(entry.getValue()); int index = instanceSpecs.indexOf(entry.getKey()); Preconditions.checkState(index >= 0, entry.getKey() + " not found in specs"); @@ -97,25 +91,18 @@ public TestingCluster(Map> specs) * * @return set of servers */ - public Collection getInstances() - { - Iterable transformed = Iterables.transform - ( - servers, - new Function() - { + public Collection getInstances() { + Iterable transformed = + Iterables.transform(servers, new Function() { @Override - public InstanceSpec apply(TestingZooKeeperServer server) - { + public InstanceSpec apply(TestingZooKeeperServer server) { return server.getInstanceSpec(); } - } - ); + }); return Lists.newArrayList(transformed); } - public List getServers() - { + public List getServers() { return Lists.newArrayList(servers); } @@ -124,13 +111,10 @@ public List getServers() * * @return connection string */ - public String getConnectString() - { - StringBuilder str = new StringBuilder(); - for ( InstanceSpec spec : getInstances() ) - { - if ( str.length() > 0 ) - { + public String getConnectString() { + StringBuilder str = new StringBuilder(); + for (InstanceSpec spec : getInstances()) { + if (str.length() > 0) { str.append(","); } str.append(spec.getConnectString()); @@ -143,10 +127,8 @@ public String getConnectString() * * @throws Exception errors */ - public void start() throws Exception - { - for ( TestingZooKeeperServer server : servers ) - { + public void start() throws Exception { + for (TestingZooKeeperServer server : servers) { server.start(); } } @@ -154,10 +136,8 @@ public void start() throws Exception /** * Shutdown the ensemble WITHOUT freeing resources, etc. */ - public void stop() throws IOException - { - for ( TestingZooKeeperServer server : servers ) - { + public void stop() throws IOException { + for (TestingZooKeeperServer server : servers) { server.stop(); } } @@ -169,10 +149,8 @@ public void stop() throws IOException * @throws IOException errors */ @Override - public void close() throws IOException - { - for ( TestingZooKeeperServer server : servers ) - { + public void close() throws IOException { + for (TestingZooKeeperServer server : servers) { server.close(); } } @@ -184,12 +162,9 @@ public void close() throws IOException * @return true if the instance was found * @throws Exception errors */ - public boolean killServer(InstanceSpec instance) throws Exception - { - for ( TestingZooKeeperServer server : servers ) - { - if ( server.getInstanceSpec().equals(instance) ) - { + public boolean killServer(InstanceSpec instance) throws Exception { + for (TestingZooKeeperServer server : servers) { + if (server.getInstanceSpec().equals(instance)) { server.kill(); return true; } @@ -204,12 +179,9 @@ public boolean killServer(InstanceSpec instance) throws Exception * @return true of the server was found * @throws Exception errors */ - public boolean restartServer(InstanceSpec instance) throws Exception - { - for ( TestingZooKeeperServer server : servers ) - { - if ( server.getInstanceSpec().equals(instance) ) - { + public boolean restartServer(InstanceSpec instance) throws Exception { + for (TestingZooKeeperServer server : servers) { + if (server.getInstanceSpec().equals(instance)) { server.restart(); return true; } @@ -224,17 +196,13 @@ public boolean restartServer(InstanceSpec instance) throws Exception * @return the server * @throws Exception errors */ - public InstanceSpec findConnectionInstance(ZooKeeper client) throws Exception - { - Method m = ZooKeeper.class.getDeclaredMethod("testableRemoteSocketAddress"); + public InstanceSpec findConnectionInstance(ZooKeeper client) throws Exception { + Method m = ZooKeeper.class.getDeclaredMethod("testableRemoteSocketAddress"); m.setAccessible(true); - InetSocketAddress address = (InetSocketAddress)m.invoke(client); - if ( address != null ) - { - for ( TestingZooKeeperServer server : servers ) - { - if ( server.getInstanceSpec().getPort() == address.getPort() ) - { + InetSocketAddress address = (InetSocketAddress) m.invoke(client); + if (address != null) { + for (TestingZooKeeperServer server : servers) { + if (server.getInstanceSpec().getPort() == address.getPort()) { return server.getInstanceSpec(); } } @@ -243,31 +211,25 @@ public InstanceSpec findConnectionInstance(ZooKeeper client) throws Exception return null; } - public static Map> makeSpecs(int instanceQty) - { + public static Map> makeSpecs(int instanceQty) { return makeSpecs(instanceQty, true); } - public static Map> makeSpecs(int instanceQty, boolean resetServerIds) - { - if ( resetServerIds ) - { + public static Map> makeSpecs(int instanceQty, boolean resetServerIds) { + if (resetServerIds) { InstanceSpec.reset(); } ImmutableList.Builder builder = ImmutableList.builder(); - for ( int i = 0; i < instanceQty; ++i ) - { + for (int i = 0; i < instanceQty; ++i) { builder.add(InstanceSpec.newInstanceSpec()); } return listToMap(builder.build()); } - private static Map> listToMap(Collection list) - { + private static Map> listToMap(Collection list) { ImmutableMap.Builder> mapBuilder = ImmutableMap.builder(); - for ( InstanceSpec spec : list ) - { + for (InstanceSpec spec : list) { mapBuilder.put(spec, list); } diff --git a/curator-test/src/main/java/org/apache/curator/test/TestingQuorumPeerMain.java b/curator-test/src/main/java/org/apache/curator/test/TestingQuorumPeerMain.java index de249729e..b5b1d8be0 100644 --- a/curator-test/src/main/java/org/apache/curator/test/TestingQuorumPeerMain.java +++ b/curator-test/src/main/java/org/apache/curator/test/TestingQuorumPeerMain.java @@ -27,63 +27,49 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -class TestingQuorumPeerMain extends QuorumPeerMain implements ZooKeeperMainFace -{ +class TestingQuorumPeerMain extends QuorumPeerMain implements ZooKeeperMainFace { private static final Logger log = LoggerFactory.getLogger(TestingQuorumPeerMain.class); private volatile boolean isClosed = false; @Override - public void kill() - { - try - { - if ( quorumPeer != null ) - { - Field cnxnFactoryField = QuorumPeer.class.getDeclaredField("cnxnFactory"); + public void kill() { + try { + if (quorumPeer != null) { + Field cnxnFactoryField = QuorumPeer.class.getDeclaredField("cnxnFactory"); cnxnFactoryField.setAccessible(true); - ServerCnxnFactory cnxnFactory = (ServerCnxnFactory)cnxnFactoryField.get(quorumPeer); + ServerCnxnFactory cnxnFactory = (ServerCnxnFactory) cnxnFactoryField.get(quorumPeer); Compatibility.serverCnxnFactoryCloseAll(cnxnFactory); - Field ssField = cnxnFactory.getClass().getDeclaredField("ss"); + Field ssField = cnxnFactory.getClass().getDeclaredField("ss"); ssField.setAccessible(true); - ServerSocketChannel ss = (ServerSocketChannel)ssField.get(cnxnFactory); + ServerSocketChannel ss = (ServerSocketChannel) ssField.get(cnxnFactory); ss.close(); } close(); - } - catch ( Exception e ) - { + } catch (Exception e) { e.printStackTrace(); } } @Override - public void close() - { - if ( (quorumPeer != null) && !isClosed ) - { + public void close() { + if ((quorumPeer != null) && !isClosed) { isClosed = true; quorumPeer.shutdown(); } } - private void blockUntilStarted() - { + private void blockUntilStarted() { long startTime = System.currentTimeMillis(); - while ( (quorumPeer == null) && ((System.currentTimeMillis() - startTime) <= TestingZooKeeperMain.MAX_WAIT_MS) ) - { - try - { + while ((quorumPeer == null) && ((System.currentTimeMillis() - startTime) <= TestingZooKeeperMain.MAX_WAIT_MS)) { + try { Thread.sleep(10); - } - catch ( InterruptedException e ) - { + } catch (InterruptedException e) { Thread.currentThread().interrupt(); break; } } - if ( quorumPeer == null ) - { + if (quorumPeer == null) { throw new FailedServerStartException("quorumPeer never got set"); } } @@ -91,12 +77,17 @@ private void blockUntilStarted() @Override public void start(QuorumPeerConfigBuilder configBuilder) { new Thread(() -> { - try { - runFromConfig(configBuilder.buildConfig()); - } catch (Exception e) { - log.error("From testing server (random state: {}) for instance: {}", configBuilder.isFromRandom(), configBuilder.getInstanceSpec(), e); - } - }).start(); + try { + runFromConfig(configBuilder.buildConfig()); + } catch (Exception e) { + log.error( + "From testing server (random state: {}) for instance: {}", + configBuilder.isFromRandom(), + configBuilder.getInstanceSpec(), + e); + } + }) + .start(); blockUntilStarted(); } diff --git a/curator-test/src/main/java/org/apache/curator/test/TestingServer.java b/curator-test/src/main/java/org/apache/curator/test/TestingServer.java index 1309682d4..e7ef2dcb9 100644 --- a/curator-test/src/main/java/org/apache/curator/test/TestingServer.java +++ b/curator-test/src/main/java/org/apache/curator/test/TestingServer.java @@ -26,8 +26,7 @@ /** * manages an internally running ZooKeeper server. FOR TESTING PURPOSES ONLY */ -public class TestingServer implements Closeable -{ +public class TestingServer implements Closeable { private final TestingZooKeeperServer testingZooKeeperServer; private final InstanceSpec spec; @@ -40,8 +39,7 @@ TestingZooKeeperServer getTestingZooKeeperServer() { * * @throws Exception errors */ - public TestingServer() throws Exception - { + public TestingServer() throws Exception { this(-1, null, true); } @@ -51,8 +49,7 @@ public TestingServer() throws Exception * @param start True if the server should be started, false otherwise * @throws Exception errors */ - public TestingServer(boolean start) throws Exception - { + public TestingServer(boolean start) throws Exception { this(-1, null, start); } @@ -62,8 +59,7 @@ public TestingServer(boolean start) throws Exception * @param port the port * @throws Exception errors */ - public TestingServer(int port) throws Exception - { + public TestingServer(int port) throws Exception { this(port, null, true); } @@ -74,8 +70,7 @@ public TestingServer(int port) throws Exception * @param start True if the server should be started, false otherwise * @throws Exception errors */ - public TestingServer(int port, boolean start) throws Exception - { + public TestingServer(int port, boolean start) throws Exception { this(port, null, start); } @@ -86,8 +81,7 @@ public TestingServer(int port, boolean start) throws Exception * @param tempDirectory directory to use * @throws Exception errors */ - public TestingServer(int port, File tempDirectory) throws Exception - { + public TestingServer(int port, File tempDirectory) throws Exception { this(port, tempDirectory, true); } @@ -99,8 +93,7 @@ public TestingServer(int port, File tempDirectory) throws Exception * @param start True if the server should be started, false otherwise * @throws Exception errors */ - public TestingServer(int port, File tempDirectory, boolean start) throws Exception - { + public TestingServer(int port, File tempDirectory, boolean start) throws Exception { this(new InstanceSpec(tempDirectory, Math.max(0, port), -1, -1, true, -1), start); } @@ -111,13 +104,11 @@ public TestingServer(int port, File tempDirectory, boolean start) throws Excepti * @param start True if the server should be started, false otherwise * @throws Exception errors */ - public TestingServer(InstanceSpec spec, boolean start) throws Exception - { + public TestingServer(InstanceSpec spec, boolean start) throws Exception { this.spec = spec; testingZooKeeperServer = new TestingZooKeeperServer(new QuorumConfigBuilder(spec)); - if ( start ) - { + if (start) { testingZooKeeperServer.start(); } } @@ -128,8 +119,7 @@ public TestingServer(InstanceSpec spec, boolean start) throws Exception * @return port * @throws IllegalStateException if server is configured to bind to port 0 but not started */ - public int getPort() - { + public int getPort() { int port = spec.getPort(); if (port > 0) { return port; @@ -142,8 +132,7 @@ public int getPort() * * @return directory */ - public File getTempDirectory() - { + public File getTempDirectory() { return spec.getDataDirectory(); } @@ -152,16 +141,14 @@ public File getTempDirectory() * * @throws Exception */ - public void start() throws Exception - { + public void start() throws Exception { testingZooKeeperServer.start(); } /** * Stop the server without deleting the temp directory */ - public void stop() throws IOException - { + public void stop() throws IOException { testingZooKeeperServer.stop(); } @@ -173,8 +160,7 @@ public void stop() throws IOException * * @throws Exception */ - public void restart() throws Exception - { + public void restart() throws Exception { testingZooKeeperServer.restart(); } @@ -182,8 +168,7 @@ public void restart() throws Exception * Close the server and any open clients and delete the temp directory */ @Override - public void close() throws IOException - { + public void close() throws IOException { testingZooKeeperServer.close(); } @@ -196,4 +181,4 @@ public void close() throws IOException public String getConnectString() { return spec.getHostname() + ":" + getPort(); } -} \ No newline at end of file +} diff --git a/curator-test/src/main/java/org/apache/curator/test/TestingZooKeeperMain.java b/curator-test/src/main/java/org/apache/curator/test/TestingZooKeeperMain.java index ef014ca57..74d39daf2 100644 --- a/curator-test/src/main/java/org/apache/curator/test/TestingZooKeeperMain.java +++ b/curator-test/src/main/java/org/apache/curator/test/TestingZooKeeperMain.java @@ -41,8 +41,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -public class TestingZooKeeperMain implements ZooKeeperMainFace -{ +public class TestingZooKeeperMain implements ZooKeeperMainFace { private static final Logger log = LoggerFactory.getLogger(TestingZooKeeperMain.class); private final CountDownLatch latch = new CountDownLatch(1); @@ -55,44 +54,36 @@ public class TestingZooKeeperMain implements ZooKeeperMainFace private static final Timing timing = new Timing(); static final int MAX_WAIT_MS; - static - { + + static { long startMs = System.currentTimeMillis(); - try - { + try { // this can take forever and fails tests - ZK calls it internally so there's nothing we can do // pre flight it and use it to calculate max wait //noinspection ResultOfMethodCallIgnored InetAddress.getLocalHost().getCanonicalHostName(); - } - catch ( UnknownHostException e ) - { + } catch (UnknownHostException e) { // ignore } long elapsed = System.currentTimeMillis() - startMs; - MAX_WAIT_MS = Math.max((int)elapsed * 2, 1000); + MAX_WAIT_MS = Math.max((int) elapsed * 2, 1000); } @Override - public void kill() - { - try - { - if ( cnxnFactory != null ) - { + public void kill() { + try { + if (cnxnFactory != null) { Compatibility.serverCnxnFactoryCloseAll(cnxnFactory); Field ssField = cnxnFactory.getClass().getDeclaredField("ss"); ssField.setAccessible(true); - ServerSocketChannel ss = (ServerSocketChannel)ssField.get(cnxnFactory); + ServerSocketChannel ss = (ServerSocketChannel) ssField.get(cnxnFactory); ss.close(); } close(); - } - catch ( Exception e ) - { - e.printStackTrace(); // just ignore - this class is only for testing + } catch (Exception e) { + e.printStackTrace(); // just ignore - this class is only for testing } } @@ -100,131 +91,96 @@ TestZooKeeperServer getZkServer() { return zkServer; } - private void runFromConfig(QuorumPeerConfig config) throws Exception - { - try - { + private void runFromConfig(QuorumPeerConfig config) throws Exception { + try { Field instance = MBeanRegistry.class.getDeclaredField("instance"); instance.setAccessible(true); - MBeanRegistry nopMBeanRegistry = new MBeanRegistry() - { + MBeanRegistry nopMBeanRegistry = new MBeanRegistry() { @Override - public void register(ZKMBeanInfo bean, ZKMBeanInfo parent) - { + public void register(ZKMBeanInfo bean, ZKMBeanInfo parent) { // NOP } @Override - public void unregister(ZKMBeanInfo bean) - { + public void unregister(ZKMBeanInfo bean) { // NOP } }; instance.set(null, nopMBeanRegistry); - } - catch ( Exception e ) - { + } catch (Exception e) { log.error("Could not fix MBeanRegistry"); } ServerConfig serverConfig = new ServerConfig(); serverConfig.readFrom(config); - try - { + try { internalRunFromConfig(serverConfig); - } - catch ( IOException e ) - { + } catch (IOException e) { startingException.set(e); throw e; } } - private void blockUntilStarted() - { - if (!timing.awaitLatch(latch)) - { + private void blockUntilStarted() { + if (!timing.awaitLatch(latch)) { throw new FailedServerStartException("Timed out waiting for server startup"); } - if ( zkServer != null ) - { + if (zkServer != null) { //noinspection SynchronizeOnNonFinalField - synchronized(zkServer) - { - while ( !zkServer.isRunning() ) - { - try - { + synchronized (zkServer) { + while (!zkServer.isRunning()) { + try { zkServer.wait(); - } - catch ( InterruptedException e ) - { + } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new FailedServerStartException("Server start interrupted"); } } } - } - else - { + } else { throw new FailedServerStartException("No zkServer."); } Exception exception = startingException.get(); - if ( exception != null ) - { + if (exception != null) { throw new FailedServerStartException(exception); } } @Override - public void close() throws IOException - { - try - { + public void close() throws IOException { + try { cnxnFactory.shutdown(); - } - catch ( Throwable e ) - { - e.printStackTrace(); // just ignore - this class is only for testing - } - finally - { + } catch (Throwable e) { + e.printStackTrace(); // just ignore - this class is only for testing + } finally { cnxnFactory = null; } - if ( containerManager != null ) { + if (containerManager != null) { containerManager.stop(); containerManager = null; } - try - { - if ( zkServer != null ) - { + try { + if (zkServer != null) { zkServer.shutdown(); ZKDatabase zkDb = zkServer.getZKDatabase(); - if ( zkDb != null ) - { + if (zkDb != null) { // make ZK server close its log files zkDb.close(); } } - } - catch ( Throwable e ) - { - e.printStackTrace(); // just ignore - this class is only for testing - } - finally - { + } catch (Throwable e) { + e.printStackTrace(); // just ignore - this class is only for testing + } finally { zkServer = null; } } // copied from ZooKeeperServerMain.java - private void internalRunFromConfig(ServerConfig config) throws IOException - { + private void internalRunFromConfig(ServerConfig config) throws IOException { log.info("Starting server"); try { // Note that this thread isn't going to be doing anything else, @@ -234,26 +190,25 @@ private void internalRunFromConfig(ServerConfig config) throws IOException FileTxnSnapLog txnLog = new FileTxnSnapLog(config.getDataLogDir(), config.getDataDir()); zkServer = new TestZooKeeperServer(txnLog, config); - try - { + try { cnxnFactory = ServerCnxnFactory.createFactory(); - cnxnFactory.configure(config.getClientPortAddress(), - config.getMaxClientCnxns()); - } - catch ( IOException e ) - { + cnxnFactory.configure(config.getClientPortAddress(), config.getMaxClientCnxns()); + } catch (IOException e) { log.info("Could not start server. Waiting and trying one more time.", e); timing.sleepABit(); cnxnFactory = ServerCnxnFactory.createFactory(); - cnxnFactory.configure(config.getClientPortAddress(), - config.getMaxClientCnxns()); + cnxnFactory.configure(config.getClientPortAddress(), config.getMaxClientCnxns()); } cnxnFactory.startup(zkServer); - containerManager = new ContainerManager(zkServer.getZKDatabase(), zkServer.getFirstProcessor(), Integer.getInteger("znode.container.checkIntervalMs", (int)TimeUnit.MINUTES.toMillis(1L)), Integer.getInteger("znode.container.maxPerMinute", 10000)); + containerManager = new ContainerManager( + zkServer.getZKDatabase(), + zkServer.getFirstProcessor(), + Integer.getInteger("znode.container.checkIntervalMs", (int) TimeUnit.MINUTES.toMillis(1L)), + Integer.getInteger("znode.container.maxPerMinute", 10000)); containerManager.start(); latch.countDown(); cnxnFactory.join(); - if ( (zkServer != null) && zkServer.isRunning()) { + if ((zkServer != null) && zkServer.isRunning()) { zkServer.shutdown(); } } catch (InterruptedException e) { @@ -265,16 +220,20 @@ private void internalRunFromConfig(ServerConfig config) throws IOException @Override public void start(QuorumPeerConfigBuilder configBuilder) { - new Thread(() -> { - try - { - runFromConfig(configBuilder.buildConfig()); - } - catch ( Exception e ) - { - log.error(String.format("From testing server (random state: %s) for instance: %s", configBuilder.isFromRandom(), configBuilder.getInstanceSpec()), e); - } - }, "zk-main-thread").start(); + new Thread( + () -> { + try { + runFromConfig(configBuilder.buildConfig()); + } catch (Exception e) { + log.error( + String.format( + "From testing server (random state: %s) for instance: %s", + configBuilder.isFromRandom(), configBuilder.getInstanceSpec()), + e); + } + }, + "zk-main-thread") + .start(); blockUntilStarted(); } @@ -284,12 +243,10 @@ public int getClientPort() { return cnxnFactory == null ? -1 : cnxnFactory.getLocalPort(); } - public static class TestZooKeeperServer extends ZooKeeperServer - { + public static class TestZooKeeperServer extends ZooKeeperServer { private final FileTxnSnapLog txnLog; - public TestZooKeeperServer(FileTxnSnapLog txnLog, ServerConfig config) - { + public TestZooKeeperServer(FileTxnSnapLog txnLog, ServerConfig config) { this.txnLog = txnLog; this.setTxnLogFactory(txnLog); // tickTime would affect min and max session timeout: should be set first @@ -299,52 +256,42 @@ public TestZooKeeperServer(FileTxnSnapLog txnLog, ServerConfig config) } @Override - public synchronized void shutdown(boolean fullyShutDown) - { + public synchronized void shutdown(boolean fullyShutDown) { super.shutdown(fullyShutDown); - try - { + try { txnLog.close(); - } - catch ( IOException e ) - { + } catch (IOException e) { // ignore } } private final AtomicBoolean isRunning = new AtomicBoolean(false); - public RequestProcessor getFirstProcessor() - { + public RequestProcessor getFirstProcessor() { return firstProcessor; } @Override - protected void setState(State state) - { + protected void setState(State state) { this.state = state; // avoid ZKShutdownHandler is not registered message } - protected void registerJMX() - { + protected void registerJMX() { // NOP } @Override - protected void unregisterJMX() - { + protected void unregisterJMX() { // NOP } @Override - public boolean isRunning() - { + public boolean isRunning() { return isRunning.get() || super.isRunning(); } - public void noteStartup() - { + public void noteStartup() { synchronized (this) { isRunning.set(true); this.notifyAll(); diff --git a/curator-test/src/main/java/org/apache/curator/test/TestingZooKeeperServer.java b/curator-test/src/main/java/org/apache/curator/test/TestingZooKeeperServer.java index 0df2a85a5..a034d47c7 100644 --- a/curator-test/src/main/java/org/apache/curator/test/TestingZooKeeperServer.java +++ b/curator-test/src/main/java/org/apache/curator/test/TestingZooKeeperServer.java @@ -23,16 +23,13 @@ import java.io.IOException; import java.util.Collection; import java.util.concurrent.atomic.AtomicReference; - -import org.apache.zookeeper.server.quorum.QuorumPeerConfig; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Thanks to Jeremie BORDIER (ahfeel) for this code */ -public class TestingZooKeeperServer implements Closeable -{ +public class TestingZooKeeperServer implements Closeable { private static final Logger log = LoggerFactory.getLogger(TestingZooKeeperServer.class); static boolean hasZooKeeperServerEmbedded; @@ -58,19 +55,19 @@ ZooKeeperMainFace getMain() { return main; } - private enum State - { - LATENT, STARTED, STOPPED, CLOSED + private enum State { + LATENT, + STARTED, + STOPPED, + CLOSED } - public TestingZooKeeperServer(QuorumConfigBuilder configBuilder) - { + public TestingZooKeeperServer(QuorumConfigBuilder configBuilder) { this(configBuilder, 0); } - public TestingZooKeeperServer(QuorumConfigBuilder configBuilder, int thisInstanceIndex) - { - System.setProperty("zookeeper.jmx.log4j.disable", "true"); // disable JMX logging + public TestingZooKeeperServer(QuorumConfigBuilder configBuilder, int thisInstanceIndex) { + System.setProperty("zookeeper.jmx.log4j.disable", "true"); // disable JMX logging this.configBuilder = configBuilder; this.thisInstanceIndex = thisInstanceIndex; @@ -92,13 +89,11 @@ private boolean isCluster() { return configBuilder.size() > 1; } - public Collection getInstanceSpecs() - { + public Collection getInstanceSpecs() { return configBuilder.getInstanceSpecs(); } - public void kill() - { + public void kill() { main.kill(); state.set(State.STOPPED); } @@ -109,17 +104,14 @@ public void kill() * it will be restarted. If it is in a CLOSED state then an exception will * be thrown. */ - public void restart() throws Exception - { + public void restart() throws Exception { // Can't restart from a closed state as all the temporary data is gone - if ( state.get() == State.CLOSED ) - { + if (state.get() == State.CLOSED) { throw new IllegalStateException("Cannot restart a closed instance"); } // If the server's currently running then stop it. - if ( state.get() == State.STARTED ) - { + if (state.get() == State.STARTED) { stop(); } @@ -130,40 +122,32 @@ public void restart() throws Exception start(); } - public void stop() throws IOException - { - if ( state.compareAndSet(State.STARTED, State.STOPPED) ) - { + public void stop() throws IOException { + if (state.compareAndSet(State.STARTED, State.STOPPED)) { main.close(); } } - public InstanceSpec getInstanceSpec() - { + public InstanceSpec getInstanceSpec() { return configBuilder.getInstanceSpec(thisInstanceIndex); } @Override - public void close() throws IOException - { + public void close() throws IOException { stop(); - if ( state.compareAndSet(State.STOPPED, State.CLOSED) ) - { + if (state.compareAndSet(State.STOPPED, State.CLOSED)) { configBuilder.close(); InstanceSpec spec = getInstanceSpec(); - if ( spec.deleteDataDirectoryOnClose() ) - { + if (spec.deleteDataDirectoryOnClose()) { DirectoryUtils.deleteRecursively(spec.getDataDirectory()); } } } - public void start() throws Exception - { - if ( !state.compareAndSet(State.LATENT, State.STARTED) ) - { + public void start() throws Exception { + if (!state.compareAndSet(State.LATENT, State.STARTED)) { return; } @@ -177,4 +161,4 @@ public int getLocalPort() { } return thisInstancePort; } -} \ No newline at end of file +} diff --git a/curator-test/src/main/java/org/apache/curator/test/Timing.java b/curator-test/src/main/java/org/apache/curator/test/Timing.java index 239468306..e5d6d3443 100644 --- a/curator-test/src/main/java/org/apache/curator/test/Timing.java +++ b/curator-test/src/main/java/org/apache/curator/test/Timing.java @@ -26,8 +26,7 @@ /** * Utility to get various testing times */ -public class Timing -{ +public class Timing { private final long value; private final TimeUnit unit; private final int waitingMultiple; @@ -39,8 +38,7 @@ public class Timing /** * Use the default base time */ - public Timing() - { + public Timing() { this(Integer.getInteger("timing-multiple", 1), getWaitingMultiple()); } @@ -49,9 +47,8 @@ public Timing() * * @param multiple the multiple */ - public Timing(double multiple) - { - this((long)(DEFAULT_SECONDS * multiple), TimeUnit.SECONDS, getWaitingMultiple()); + public Timing(double multiple) { + this((long) (DEFAULT_SECONDS * multiple), TimeUnit.SECONDS, getWaitingMultiple()); } /** @@ -60,17 +57,15 @@ public Timing(double multiple) * @param multiple the multiple * @param waitingMultiple multiple of main timing to use when waiting */ - public Timing(double multiple, int waitingMultiple) - { - this((long)(DEFAULT_SECONDS * multiple), TimeUnit.SECONDS, waitingMultiple); + public Timing(double multiple, int waitingMultiple) { + this((long) (DEFAULT_SECONDS * multiple), TimeUnit.SECONDS, waitingMultiple); } /** * @param value base time * @param unit base time unit */ - public Timing(long value, TimeUnit unit) - { + public Timing(long value, TimeUnit unit) { this(value, unit, getWaitingMultiple()); } @@ -79,8 +74,7 @@ public Timing(long value, TimeUnit unit) * @param unit base time unit * @param waitingMultiple multiple of main timing to use when waiting */ - public Timing(long value, TimeUnit unit, int waitingMultiple) - { + public Timing(long value, TimeUnit unit, int waitingMultiple) { this.value = value; this.unit = unit; this.waitingMultiple = waitingMultiple; @@ -91,9 +85,8 @@ public Timing(long value, TimeUnit unit, int waitingMultiple) * * @return time ms */ - public int milliseconds() - { - return (int)TimeUnit.MILLISECONDS.convert(value, unit); + public int milliseconds() { + return (int) TimeUnit.MILLISECONDS.convert(value, unit); } /** @@ -101,9 +94,8 @@ public int milliseconds() * * @return time secs */ - public int seconds() - { - return (int)value; + public int seconds() { + return (int) value; } /** @@ -112,15 +104,11 @@ public int seconds() * @param latch latch to wait on * @return result of {@link CountDownLatch#await(long, TimeUnit)} */ - public boolean awaitLatch(CountDownLatch latch) - { + public boolean awaitLatch(CountDownLatch latch) { Timing m = forWaiting(); - try - { + try { return latch.await(m.value, m.unit); - } - catch ( InterruptedException e ) - { + } catch (InterruptedException e) { Thread.currentThread().interrupt(); } return false; @@ -132,15 +120,11 @@ public boolean awaitLatch(CountDownLatch latch) * @param semaphore the semaphore * @return result of {@link Semaphore#tryAcquire()} */ - public boolean acquireSemaphore(Semaphore semaphore) - { + public boolean acquireSemaphore(Semaphore semaphore) { Timing m = forWaiting(); - try - { + try { return semaphore.tryAcquire(m.value, m.unit); - } - catch ( InterruptedException e ) - { + } catch (InterruptedException e) { Thread.currentThread().interrupt(); } return false; @@ -153,15 +137,11 @@ public boolean acquireSemaphore(Semaphore semaphore) * @param n number of permits to acquire * @return result of {@link Semaphore#tryAcquire(int, long, TimeUnit)} */ - public boolean acquireSemaphore(Semaphore semaphore, int n) - { + public boolean acquireSemaphore(Semaphore semaphore, int n) { Timing m = forWaiting(); - try - { + try { return semaphore.tryAcquire(n, m.value, m.unit); - } - catch ( InterruptedException e ) - { + } catch (InterruptedException e) { Thread.currentThread().interrupt(); } return false; @@ -173,9 +153,8 @@ public boolean acquireSemaphore(Semaphore semaphore, int n) * @param n the multiple * @return this timing times the multiple */ - public Timing multiple(double n) - { - return new Timing((int)(value * n), unit); + public Timing multiple(double n) { + return new Timing((int) (value * n), unit); } /** @@ -184,8 +163,7 @@ public Timing multiple(double n) * @return this timing multiplied */ @SuppressWarnings("PointlessArithmeticExpression") - public Timing forWaiting() - { + public Timing forWaiting() { return multiple(waitingMultiple); } @@ -194,8 +172,7 @@ public Timing forWaiting() * * @throws InterruptedException if interrupted */ - public void sleepABit() throws InterruptedException - { + public void sleepABit() throws InterruptedException { unit.sleep(value / 4); } @@ -204,8 +181,7 @@ public void sleepABit() throws InterruptedException * * @return session timeout */ - public int session() - { + public int session() { return multiple(SESSION_MULTIPLE).milliseconds(); } @@ -214,13 +190,11 @@ public int session() * * @return connection timeout */ - public int connection() - { + public int connection() { return milliseconds(); } - private static Integer getWaitingMultiple() - { + private static Integer getWaitingMultiple() { return Integer.getInteger("timing-waiting-multiple", DEFAULT_WAITING_MULTIPLE); } } diff --git a/curator-test/src/main/java/org/apache/curator/test/WatchersDebug.java b/curator-test/src/main/java/org/apache/curator/test/WatchersDebug.java index c8d6b5c07..eab24f7f9 100644 --- a/curator-test/src/main/java/org/apache/curator/test/WatchersDebug.java +++ b/curator-test/src/main/java/org/apache/curator/test/WatchersDebug.java @@ -19,28 +19,24 @@ package org.apache.curator.test; -import org.apache.zookeeper.ZooKeeper; import java.lang.reflect.Method; import java.util.List; +import org.apache.zookeeper.ZooKeeper; -public class WatchersDebug -{ +public class WatchersDebug { private static final Method getDataWatches; private static final Method getExistWatches; private static final Method getChildWatches; - static - { + + static { Method localGetDataWatches = null; Method localGetExistWatches = null; Method localGetChildWatches = null; - try - { + try { localGetDataWatches = getMethod("getDataWatches"); localGetExistWatches = getMethod("getExistWatches"); localGetChildWatches = getMethod("getChildWatches"); - } - catch ( NoSuchMethodException e ) - { + } catch (NoSuchMethodException e) { e.printStackTrace(); } getDataWatches = localGetDataWatches; @@ -48,45 +44,34 @@ public class WatchersDebug getChildWatches = localGetChildWatches; } - public static List getDataWatches(ZooKeeper zooKeeper) - { + public static List getDataWatches(ZooKeeper zooKeeper) { return callMethod(zooKeeper, WatchersDebug.getDataWatches); } - public static List getExistWatches(ZooKeeper zooKeeper) - { + public static List getExistWatches(ZooKeeper zooKeeper) { return callMethod(zooKeeper, getExistWatches); } - public static List getChildWatches(ZooKeeper zooKeeper) - { + public static List getChildWatches(ZooKeeper zooKeeper) { return callMethod(zooKeeper, getChildWatches); } - private WatchersDebug() - { - } + private WatchersDebug() {} - private static Method getMethod(String name) throws NoSuchMethodException - { + private static Method getMethod(String name) throws NoSuchMethodException { Method m = ZooKeeper.class.getDeclaredMethod(name); m.setAccessible(true); return m; } - private static List callMethod(ZooKeeper zooKeeper, Method method) - { - if ( zooKeeper == null ) - { + private static List callMethod(ZooKeeper zooKeeper, Method method) { + if (zooKeeper == null) { return null; } - try - { + try { //noinspection unchecked - return (List)method.invoke(zooKeeper); - } - catch ( Exception e ) - { + return (List) method.invoke(zooKeeper); + } catch (Exception e) { throw new RuntimeException(e); } } diff --git a/curator-test/src/main/java/org/apache/curator/test/ZooKeeperMainFace.java b/curator-test/src/main/java/org/apache/curator/test/ZooKeeperMainFace.java index 1e95d2ca6..827cda517 100644 --- a/curator-test/src/main/java/org/apache/curator/test/ZooKeeperMainFace.java +++ b/curator-test/src/main/java/org/apache/curator/test/ZooKeeperMainFace.java @@ -21,8 +21,7 @@ import java.io.Closeable; -interface ZooKeeperMainFace extends Closeable -{ +interface ZooKeeperMainFace extends Closeable { void start(QuorumPeerConfigBuilder configBuilder); void kill(); diff --git a/curator-test/src/main/java/org/apache/curator/test/ZooKeeperServerEmbeddedAdapter.java b/curator-test/src/main/java/org/apache/curator/test/ZooKeeperServerEmbeddedAdapter.java index 95ff863dd..553c4b5ca 100644 --- a/curator-test/src/main/java/org/apache/curator/test/ZooKeeperServerEmbeddedAdapter.java +++ b/curator-test/src/main/java/org/apache/curator/test/ZooKeeperServerEmbeddedAdapter.java @@ -25,7 +25,6 @@ import java.nio.file.Paths; import java.time.Duration; import java.util.Properties; - import org.apache.zookeeper.server.ServerCnxnFactory; import org.apache.zookeeper.server.ZooKeeperServerMain; import org.apache.zookeeper.server.embedded.ZooKeeperServerEmbedded; diff --git a/curator-test/src/main/java/org/apache/curator/test/compatibility/CuratorTestBase.java b/curator-test/src/main/java/org/apache/curator/test/compatibility/CuratorTestBase.java index a7b846fd6..47ff1e274 100644 --- a/curator-test/src/main/java/org/apache/curator/test/compatibility/CuratorTestBase.java +++ b/curator-test/src/main/java/org/apache/curator/test/compatibility/CuratorTestBase.java @@ -21,8 +21,7 @@ import org.apache.curator.test.BaseClassForTests; -public class CuratorTestBase extends BaseClassForTests -{ +public class CuratorTestBase extends BaseClassForTests { public static final String zk36Group = "zk36"; public static final String zk37Group = "zk37"; public static final String zk35TestCompatibilityGroup = "zk35TestCompatibility"; diff --git a/curator-test/src/main/java/org/apache/curator/test/compatibility/Timing2.java b/curator-test/src/main/java/org/apache/curator/test/compatibility/Timing2.java index d8fe15370..946b65ebf 100644 --- a/curator-test/src/main/java/org/apache/curator/test/compatibility/Timing2.java +++ b/curator-test/src/main/java/org/apache/curator/test/compatibility/Timing2.java @@ -30,8 +30,7 @@ * * Copied from the old Timing class which is now deprecated. Needed this to support ZK 3.4 compatibility */ -public class Timing2 -{ +public class Timing2 { private final long value; private final TimeUnit unit; private final int waitingMultiple; @@ -40,13 +39,14 @@ public class Timing2 private static final int DEFAULT_SECONDS = 10; private static final int DEFAULT_WAITING_MULTIPLE = 5; private static final double SESSION_MULTIPLE = 1.5; - private static final double SESSION_SLEEP_MULTIPLE = SESSION_MULTIPLE * 1.75; // has to be at least session + 2/3 of a session to account for missed heartbeat then session expiration + private static final double SESSION_SLEEP_MULTIPLE = SESSION_MULTIPLE + * 1.75; // has to be at least session + 2/3 of a session to account for missed heartbeat then session + // expiration /** * Use the default base time */ - public Timing2() - { + public Timing2() { this(Integer.getInteger("timing-multiple", 1), getWaitingMultiple()); } @@ -55,9 +55,8 @@ public Timing2() * * @param multiple the multiple */ - public Timing2(double multiple) - { - this((long)(DEFAULT_SECONDS * multiple), TimeUnit.SECONDS, getWaitingMultiple()); + public Timing2(double multiple) { + this((long) (DEFAULT_SECONDS * multiple), TimeUnit.SECONDS, getWaitingMultiple()); } /** @@ -66,17 +65,15 @@ public Timing2(double multiple) * @param multiple the multiple * @param waitingMultiple multiple of main timing to use when waiting */ - public Timing2(double multiple, int waitingMultiple) - { - this((long)(DEFAULT_SECONDS * multiple), TimeUnit.SECONDS, waitingMultiple); + public Timing2(double multiple, int waitingMultiple) { + this((long) (DEFAULT_SECONDS * multiple), TimeUnit.SECONDS, waitingMultiple); } /** * @param value base time * @param unit base time unit */ - public Timing2(long value, TimeUnit unit) - { + public Timing2(long value, TimeUnit unit) { this(value, unit, getWaitingMultiple()); } @@ -85,8 +82,7 @@ public Timing2(long value, TimeUnit unit) * @param unit base time unit * @param waitingMultiple multiple of main timing to use when waiting */ - public Timing2(long value, TimeUnit unit, int waitingMultiple) - { + public Timing2(long value, TimeUnit unit, int waitingMultiple) { this.value = value; this.unit = unit; this.waitingMultiple = waitingMultiple; @@ -97,9 +93,8 @@ public Timing2(long value, TimeUnit unit, int waitingMultiple) * * @return time ms */ - public int milliseconds() - { - return (int)TimeUnit.MILLISECONDS.convert(value, unit); + public int milliseconds() { + return (int) TimeUnit.MILLISECONDS.convert(value, unit); } /** @@ -107,9 +102,8 @@ public int milliseconds() * * @return time secs */ - public int seconds() - { - return (int)value; + public int seconds() { + return (int) value; } /** @@ -118,15 +112,11 @@ public int seconds() * @param latch latch to wait on * @return result of {@link java.util.concurrent.CountDownLatch#await(long, java.util.concurrent.TimeUnit)} */ - public boolean awaitLatch(CountDownLatch latch) - { + public boolean awaitLatch(CountDownLatch latch) { Timing2 m = forWaiting(); - try - { + try { return latch.await(m.value, m.unit); - } - catch ( InterruptedException e ) - { + } catch (InterruptedException e) { Thread.currentThread().interrupt(); } return false; @@ -139,20 +129,15 @@ public boolean awaitLatch(CountDownLatch latch) * @return item * @throws Exception interrupted or timed out */ - public T takeFromQueue(BlockingQueue queue) throws Exception - { + public T takeFromQueue(BlockingQueue queue) throws Exception { Timing2 m = forWaiting(); - try - { + try { T value = queue.poll(m.value, m.unit); - if ( value == null ) - { + if (value == null) { throw new TimeoutException("Timed out trying to take from queue"); } return value; - } - catch ( InterruptedException e ) - { + } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw e; } @@ -164,15 +149,11 @@ public T takeFromQueue(BlockingQueue queue) throws Exception * @param semaphore the semaphore * @return result of {@link java.util.concurrent.Semaphore#tryAcquire()} */ - public boolean acquireSemaphore(Semaphore semaphore) - { + public boolean acquireSemaphore(Semaphore semaphore) { Timing2 m = forWaiting(); - try - { + try { return semaphore.tryAcquire(m.value, m.unit); - } - catch ( InterruptedException e ) - { + } catch (InterruptedException e) { Thread.currentThread().interrupt(); } return false; @@ -185,15 +166,11 @@ public boolean acquireSemaphore(Semaphore semaphore) * @param n number of permits to acquire * @return result of {@link java.util.concurrent.Semaphore#tryAcquire(int, long, java.util.concurrent.TimeUnit)} */ - public boolean acquireSemaphore(Semaphore semaphore, int n) - { + public boolean acquireSemaphore(Semaphore semaphore, int n) { Timing2 m = forWaiting(); - try - { + try { return semaphore.tryAcquire(n, m.value, m.unit); - } - catch ( InterruptedException e ) - { + } catch (InterruptedException e) { Thread.currentThread().interrupt(); } return false; @@ -205,9 +182,8 @@ public boolean acquireSemaphore(Semaphore semaphore, int n) * @param n the multiple * @return this timing times the multiple */ - public Timing2 multiple(double n) - { - return new Timing2((int)(value * n), unit); + public Timing2 multiple(double n) { + return new Timing2((int) (value * n), unit); } /** @@ -217,9 +193,8 @@ public Timing2 multiple(double n) * @param waitingMultiple new waitingMultiple * @return this timing times the multiple */ - public Timing2 multiple(double n, int waitingMultiple) - { - return new Timing2((int)(value * n), unit, waitingMultiple); + public Timing2 multiple(double n, int waitingMultiple) { + return new Timing2((int) (value * n), unit, waitingMultiple); } /** @@ -228,8 +203,7 @@ public Timing2 multiple(double n, int waitingMultiple) * @return this timing multiplied */ @SuppressWarnings("PointlessArithmeticExpression") - public Timing2 forWaiting() - { + public Timing2 forWaiting() { return multiple(waitingMultiple); } @@ -238,8 +212,7 @@ public Timing2 forWaiting() * * @return this timing multiplied */ - public Timing2 forSessionSleep() - { + public Timing2 forSessionSleep() { return multiple(SESSION_SLEEP_MULTIPLE, 1); } @@ -248,8 +221,7 @@ public Timing2 forSessionSleep() * * @return this timing multiplied */ - public Timing2 forSleepingABit() - { + public Timing2 forSleepingABit() { return multiple(.25); } @@ -258,8 +230,7 @@ public Timing2 forSleepingABit() * * @throws InterruptedException if interrupted */ - public void sleepABit() throws InterruptedException - { + public void sleepABit() throws InterruptedException { forSleepingABit().sleep(); } @@ -268,8 +239,7 @@ public void sleepABit() throws InterruptedException * * @throws InterruptedException if interrupted */ - public void sleep() throws InterruptedException - { + public void sleep() throws InterruptedException { unit.sleep(value); } @@ -278,8 +248,7 @@ public void sleep() throws InterruptedException * * @return session timeout */ - public int session() - { + public int session() { return multiple(SESSION_MULTIPLE).milliseconds(); } @@ -288,8 +257,7 @@ public int session() * * @return connection timeout */ - public int connection() - { + public int connection() { return milliseconds(); } @@ -298,13 +266,11 @@ public int connection() * * @return tick time */ - public int tickTime() - { - return (int)Math.max(1, milliseconds() * TICK_TIME_MULTIPLE); + public int tickTime() { + return (int) Math.max(1, milliseconds() * TICK_TIME_MULTIPLE); } - private static Integer getWaitingMultiple() - { + private static Integer getWaitingMultiple() { return Integer.getInteger("timing-waiting-multiple", DEFAULT_WAITING_MULTIPLE); } } diff --git a/curator-test/src/test/java/org/apache/curator/test/TestQuorumConfigBuilder.java b/curator-test/src/test/java/org/apache/curator/test/TestQuorumConfigBuilder.java index f75727a90..cdf6437ef 100644 --- a/curator-test/src/test/java/org/apache/curator/test/TestQuorumConfigBuilder.java +++ b/curator-test/src/test/java/org/apache/curator/test/TestQuorumConfigBuilder.java @@ -31,18 +31,20 @@ public class TestQuorumConfigBuilder { @Test public void testCustomProperties() throws Exception { - Map customProperties = new HashMap(); + Map customProperties = new HashMap(); customProperties.put("authProvider.1", "org.apache.zookeeper.server.auth.SASLAuthenticationProvider"); customProperties.put("kerberos.removeHostFromPrincipal", "true"); customProperties.put("kerberos.removeRealmFromPrincipal", "true"); - InstanceSpec spec = new InstanceSpec(null, -1, -1, -1, true, 1,-1, -1,customProperties); + InstanceSpec spec = new InstanceSpec(null, -1, -1, -1, true, 1, -1, -1, customProperties); TestingServer server = new TestingServer(spec, true); try { - assertEquals("org.apache.zookeeper.server.auth.SASLAuthenticationProvider", System.getProperty("zookeeper.authProvider.1")); + assertEquals( + "org.apache.zookeeper.server.auth.SASLAuthenticationProvider", + System.getProperty("zookeeper.authProvider.1")); assertEquals("true", System.getProperty("zookeeper.kerberos.removeHostFromPrincipal")); assertEquals("true", System.getProperty("zookeeper.kerberos.removeRealmFromPrincipal")); } finally { server.close(); } } -} \ No newline at end of file +} diff --git a/curator-test/src/test/java/org/apache/curator/test/TestTestingServer.java b/curator-test/src/test/java/org/apache/curator/test/TestTestingServer.java index 40291aed1..c442533b7 100644 --- a/curator-test/src/test/java/org/apache/curator/test/TestTestingServer.java +++ b/curator-test/src/test/java/org/apache/curator/test/TestTestingServer.java @@ -20,35 +20,34 @@ package org.apache.curator.test; import static org.junit.jupiter.api.Assertions.assertEquals; - import java.io.File; - import org.apache.zookeeper.server.ZooKeeperServer; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; public class TestTestingServer { - @TempDir - File zkTmpDir; - - @Test - public void setCustomTickTimeTest() throws Exception { - TestingZooKeeperServer.hasZooKeeperServerEmbedded = false; - - final int defaultZkTickTime = ZooKeeperServer.DEFAULT_TICK_TIME; - final int customTickMs; - if (defaultZkTickTime > 0) { - customTickMs = defaultZkTickTime + (defaultZkTickTime == Integer.MAX_VALUE ? -1 : +1); - } else { - customTickMs = 100; - } - final InstanceSpec spec = new InstanceSpec(zkTmpDir, -1, -1, -1, true, -1, customTickMs, -1); - final int zkTickTime; - try (TestingServer testingServer = new TestingServer(spec, true)) { - TestingZooKeeperMain main = (TestingZooKeeperMain) testingServer.getTestingZooKeeperServer().getMain(); - zkTickTime = main.getZkServer().getTickTime(); - } - assertEquals(customTickMs, zkTickTime); - } + @TempDir + File zkTmpDir; + + @Test + public void setCustomTickTimeTest() throws Exception { + TestingZooKeeperServer.hasZooKeeperServerEmbedded = false; + + final int defaultZkTickTime = ZooKeeperServer.DEFAULT_TICK_TIME; + final int customTickMs; + if (defaultZkTickTime > 0) { + customTickMs = defaultZkTickTime + (defaultZkTickTime == Integer.MAX_VALUE ? -1 : +1); + } else { + customTickMs = 100; + } + final InstanceSpec spec = new InstanceSpec(zkTmpDir, -1, -1, -1, true, -1, customTickMs, -1); + final int zkTickTime; + try (TestingServer testingServer = new TestingServer(spec, true)) { + TestingZooKeeperMain main = (TestingZooKeeperMain) + testingServer.getTestingZooKeeperServer().getMain(); + zkTickTime = main.getZkServer().getTickTime(); + } + assertEquals(customTickMs, zkTickTime); + } } diff --git a/curator-x-async/src/main/java/org/apache/curator/x/async/AsyncCuratorFramework.java b/curator-x-async/src/main/java/org/apache/curator/x/async/AsyncCuratorFramework.java index 5c91e9285..687fa1b46 100644 --- a/curator-x-async/src/main/java/org/apache/curator/x/async/AsyncCuratorFramework.java +++ b/curator-x-async/src/main/java/org/apache/curator/x/async/AsyncCuratorFramework.java @@ -19,20 +19,19 @@ package org.apache.curator.x.async; +import java.util.function.UnaryOperator; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.api.CuratorEvent; import org.apache.curator.framework.api.UnhandledErrorListener; import org.apache.curator.x.async.api.AsyncCuratorFrameworkDsl; import org.apache.curator.x.async.details.AsyncCuratorFrameworkImpl; import org.apache.zookeeper.WatchedEvent; -import java.util.function.UnaryOperator; /** * Zookeeper framework-style client that returns composable async operations * that implement {@link java.util.concurrent.CompletionStage} */ -public interface AsyncCuratorFramework extends AsyncCuratorFrameworkDsl -{ +public interface AsyncCuratorFramework extends AsyncCuratorFrameworkDsl { /** * Takes an old-style Curator instance and returns a new async instance that * wraps it. Note: the instance must have been created through a chain that @@ -43,8 +42,7 @@ public interface AsyncCuratorFramework extends AsyncCuratorFrameworkDsl * @param client instance to wrap * @return wrapped instance */ - static AsyncCuratorFramework wrap(CuratorFramework client) - { + static AsyncCuratorFramework wrap(CuratorFramework client) { return new AsyncCuratorFrameworkImpl(client); } @@ -93,7 +91,10 @@ static AsyncCuratorFramework wrap(CuratorFramework client) * @see #with(org.apache.curator.framework.api.UnhandledErrorListener) * @return facade */ - AsyncCuratorFrameworkDsl with(UnhandledErrorListener listener, UnaryOperator resultFilter, UnaryOperator watcherFilter); + AsyncCuratorFrameworkDsl with( + UnhandledErrorListener listener, + UnaryOperator resultFilter, + UnaryOperator watcherFilter); /** * Set any combination of listener, filters or watch mode @@ -107,5 +108,9 @@ static AsyncCuratorFramework wrap(CuratorFramework client) * @see #with(org.apache.curator.framework.api.UnhandledErrorListener) * @return facade */ - AsyncCuratorFrameworkDsl with(WatchMode mode, UnhandledErrorListener listener, UnaryOperator resultFilter, UnaryOperator watcherFilter); + AsyncCuratorFrameworkDsl with( + WatchMode mode, + UnhandledErrorListener listener, + UnaryOperator resultFilter, + UnaryOperator watcherFilter); } diff --git a/curator-x-async/src/main/java/org/apache/curator/x/async/AsyncEventException.java b/curator-x-async/src/main/java/org/apache/curator/x/async/AsyncEventException.java index 4e77e20aa..e90a3aaf2 100644 --- a/curator-x-async/src/main/java/org/apache/curator/x/async/AsyncEventException.java +++ b/curator-x-async/src/main/java/org/apache/curator/x/async/AsyncEventException.java @@ -19,15 +19,14 @@ package org.apache.curator.x.async; +import java.util.concurrent.CompletionStage; import org.apache.zookeeper.WatchedEvent; import org.apache.zookeeper.Watcher; -import java.util.concurrent.CompletionStage; /** * The exception type set for async watchers */ -public abstract class AsyncEventException extends Exception -{ +public abstract class AsyncEventException extends Exception { /** * Returns the error condition that temporarily triggered the watcher. NOTE: the watcher * will most likely still be set. Use {@link #reset()} to stage on the successful trigger diff --git a/curator-x-async/src/main/java/org/apache/curator/x/async/AsyncResult.java b/curator-x-async/src/main/java/org/apache/curator/x/async/AsyncResult.java index 27bb468c5..f9637f1af 100644 --- a/curator-x-async/src/main/java/org/apache/curator/x/async/AsyncResult.java +++ b/curator-x-async/src/main/java/org/apache/curator/x/async/AsyncResult.java @@ -19,10 +19,10 @@ package org.apache.curator.x.async; -import org.apache.curator.x.async.details.AsyncResultImpl; -import org.apache.zookeeper.KeeperException; import java.util.Optional; import java.util.concurrent.CompletionStage; +import org.apache.curator.x.async.details.AsyncResultImpl; +import org.apache.zookeeper.KeeperException; /** *

@@ -41,8 +41,7 @@ *

* @param value type */ -public interface AsyncResult -{ +public interface AsyncResult { /** * Return a new stage that wraps an async stage into a result-style completion stage. The returned * CompletionStage will always complete successfully. @@ -51,14 +50,11 @@ public interface AsyncResult * @param value type * @return completion stage that resolves to a result */ - static CompletionStage> of(AsyncStage stage) - { + static CompletionStage> of(AsyncStage stage) { return stage.handle((value, ex) -> { - if ( ex != null ) - { - if ( ex instanceof KeeperException ) - { - return new AsyncResultImpl(((KeeperException)ex).code()); + if (ex != null) { + if (ex instanceof KeeperException) { + return new AsyncResultImpl(((KeeperException) ex).code()); } return new AsyncResultImpl(ex); } diff --git a/curator-x-async/src/main/java/org/apache/curator/x/async/AsyncStage.java b/curator-x-async/src/main/java/org/apache/curator/x/async/AsyncStage.java index 586016855..3317de952 100644 --- a/curator-x-async/src/main/java/org/apache/curator/x/async/AsyncStage.java +++ b/curator-x-async/src/main/java/org/apache/curator/x/async/AsyncStage.java @@ -19,14 +19,13 @@ package org.apache.curator.x.async; -import org.apache.zookeeper.WatchedEvent; import java.util.concurrent.CompletionStage; +import org.apache.zookeeper.WatchedEvent; /** * A {@link java.util.concurrent.CompletionStage} that is the result of most operations. */ -public interface AsyncStage extends CompletionStage -{ +public interface AsyncStage extends CompletionStage { /** *

* If the {@link org.apache.curator.x.async.api.WatchableAsyncCuratorFramework} facade is diff --git a/curator-x-async/src/main/java/org/apache/curator/x/async/AsyncWrappers.java b/curator-x-async/src/main/java/org/apache/curator/x/async/AsyncWrappers.java index 160eb3d75..ca75c7484 100644 --- a/curator-x-async/src/main/java/org/apache/curator/x/async/AsyncWrappers.java +++ b/curator-x-async/src/main/java/org/apache/curator/x/async/AsyncWrappers.java @@ -21,11 +21,6 @@ import com.google.common.base.Throwables; import com.google.common.collect.Maps; -import org.apache.curator.framework.recipes.locks.InterProcessLock; -import org.apache.curator.utils.ThreadUtils; -import org.apache.curator.utils.ZKPaths; -import org.apache.curator.x.async.api.ExistsOption; -import org.apache.zookeeper.KeeperException; import java.util.Collections; import java.util.List; import java.util.Map; @@ -33,6 +28,11 @@ import java.util.concurrent.CompletionStage; import java.util.concurrent.Executor; import java.util.concurrent.TimeUnit; +import org.apache.curator.framework.recipes.locks.InterProcessLock; +import org.apache.curator.utils.ThreadUtils; +import org.apache.curator.utils.ZKPaths; +import org.apache.curator.x.async.api.ExistsOption; +import org.apache.zookeeper.KeeperException; /** *

@@ -71,8 +71,7 @@ * *

*/ -public class AsyncWrappers -{ +public class AsyncWrappers { /** *

* Return the children of the given path (keyed by the full path) and the data for each node. @@ -88,8 +87,7 @@ public class AsyncWrappers * * @return CompletionStage */ - public static CompletionStage> childrenWithData(AsyncCuratorFramework client, String path) - { + public static CompletionStage> childrenWithData(AsyncCuratorFramework client, String path) { return childrenWithData(client, path, false); } @@ -109,23 +107,17 @@ public static CompletionStage> childrenWithData(AsyncCurator * @param isCompressed pass true if data is compressed * @return CompletionStage */ - public static CompletionStage> childrenWithData(AsyncCuratorFramework client, String path, boolean isCompressed) - { + public static CompletionStage> childrenWithData( + AsyncCuratorFramework client, String path, boolean isCompressed) { CompletableFuture> future = new CompletableFuture<>(); client.getChildren().forPath(path).handle((children, e) -> { - if ( e != null ) - { - if ( Throwables.getRootCause(e) instanceof KeeperException.NoNodeException ) - { + if (e != null) { + if (Throwables.getRootCause(e) instanceof KeeperException.NoNodeException) { future.complete(Maps.newHashMap()); - } - else - { + } else { future.completeExceptionally(e); } - } - else - { + } else { completeChildren(client, future, path, children, isCompressed); } return null; @@ -140,8 +132,7 @@ public static CompletionStage> childrenWithData(AsyncCurator * @param path path to ensure * @return stage */ - public static CompletionStage asyncEnsureParents(AsyncCuratorFramework client, String path) - { + public static CompletionStage asyncEnsureParents(AsyncCuratorFramework client, String path) { return ensure(client, path, ExistsOption.createParentsIfNeeded); } @@ -152,8 +143,7 @@ public static CompletionStage asyncEnsureParents(AsyncCuratorFramework cli * @param path path to ensure * @return stage */ - public static CompletionStage asyncEnsureContainers(AsyncCuratorFramework client, String path) - { + public static CompletionStage asyncEnsureContainers(AsyncCuratorFramework client, String path) { return ensure(client, path, ExistsOption.createParentsAsContainers); } @@ -161,9 +151,7 @@ public static CompletionStage asyncEnsureContainers(AsyncCuratorFramework * Set as the completion stage's exception when trying to acquire a lock * times out */ - public static class TimeoutException extends RuntimeException - { - } + public static class TimeoutException extends RuntimeException {} /** * Attempt to acquire the given lock asynchronously using the given timeout and executor. If the lock @@ -176,15 +164,12 @@ public static class TimeoutException extends RuntimeException * @param executor executor to use to asynchronously acquire * @return stage */ - public static CompletionStage lockAsync(InterProcessLock lock, long timeout, TimeUnit unit, Executor executor) - { + public static CompletionStage lockAsync( + InterProcessLock lock, long timeout, TimeUnit unit, Executor executor) { CompletableFuture future = new CompletableFuture<>(); - if ( executor == null ) - { + if (executor == null) { CompletableFuture.runAsync(() -> lock(future, lock, timeout, unit)); - } - else - { + } else { CompletableFuture.runAsync(() -> lock(future, lock, timeout, unit), executor); } return future; @@ -201,15 +186,12 @@ public static CompletionStage lockAsync(InterProcessLock lock, long timeou * @param executor executor to use to asynchronously acquire * @return stage */ - public static CompletionStage lockAsyncIf(InterProcessLock lock, long timeout, TimeUnit unit, Executor executor) - { + public static CompletionStage lockAsyncIf( + InterProcessLock lock, long timeout, TimeUnit unit, Executor executor) { CompletableFuture future = new CompletableFuture<>(); - if ( executor == null ) - { + if (executor == null) { CompletableFuture.runAsync(() -> lockIf(future, lock, timeout, unit)); - } - else - { + } else { CompletableFuture.runAsync(() -> lockIf(future, lock, timeout, unit), executor); } return future; @@ -223,8 +205,7 @@ public static CompletionStage lockAsyncIf(InterProcessLock lock, long t * @param executor executor to use to asynchronously acquire * @return stage */ - public static CompletionStage lockAsync(InterProcessLock lock, Executor executor) - { + public static CompletionStage lockAsync(InterProcessLock lock, Executor executor) { return lockAsync(lock, 0, null, executor); } @@ -238,8 +219,7 @@ public static CompletionStage lockAsync(InterProcessLock lock, Executor ex * @param unit time unit of timeout * @return stage */ - public static CompletionStage lockAsync(InterProcessLock lock, long timeout, TimeUnit unit) - { + public static CompletionStage lockAsync(InterProcessLock lock, long timeout, TimeUnit unit) { return lockAsync(lock, timeout, unit, null); } @@ -253,8 +233,7 @@ public static CompletionStage lockAsync(InterProcessLock lock, long timeou * @param unit time unit of timeout * @return stage */ - public static CompletionStage lockAsyncIf(InterProcessLock lock, long timeout, TimeUnit unit) - { + public static CompletionStage lockAsyncIf(InterProcessLock lock, long timeout, TimeUnit unit) { return lockAsyncIf(lock, timeout, unit, null); } @@ -265,8 +244,7 @@ public static CompletionStage lockAsyncIf(InterProcessLock lock, long t * {@link org.apache.curator.framework.recipes.locks.InterProcessSemaphoreV2}, etc.) * @return stage */ - public static CompletionStage lockAsync(InterProcessLock lock) - { + public static CompletionStage lockAsync(InterProcessLock lock) { return lockAsync(lock, 0, null, null); } @@ -275,8 +253,7 @@ public static CompletionStage lockAsync(InterProcessLock lock) * * @param lock lock to release */ - public static void release(InterProcessLock lock) - { + public static void release(InterProcessLock lock) { release(lock, true); } @@ -286,89 +263,69 @@ public static void release(InterProcessLock lock) * @param lock lock to release * @param ignoreNoLockExceptions if true {@link java.lang.IllegalStateException} is ignored */ - public static void release(InterProcessLock lock, boolean ignoreNoLockExceptions) - { - try - { + public static void release(InterProcessLock lock, boolean ignoreNoLockExceptions) { + try { lock.release(); - } - catch ( IllegalStateException e ) - { - if ( !ignoreNoLockExceptions ) - { + } catch (IllegalStateException e) { + if (!ignoreNoLockExceptions) { throw new RuntimeException(e); } - } - catch ( Exception e ) - { + } catch (Exception e) { ThreadUtils.checkInterrupted(e); throw new RuntimeException(e); } } - private static void lockIf(CompletableFuture future, InterProcessLock lock, long timeout, TimeUnit unit) - { - try - { + private static void lockIf(CompletableFuture future, InterProcessLock lock, long timeout, TimeUnit unit) { + try { future.complete(lock.acquire(timeout, unit)); - } - catch ( Exception e ) - { + } catch (Exception e) { ThreadUtils.checkInterrupted(e); future.completeExceptionally(e); } } - private static void lock(CompletableFuture future, InterProcessLock lock, long timeout, TimeUnit unit) - { - try - { - if ( unit != null ) - { - if ( lock.acquire(timeout, unit) ) - { + private static void lock(CompletableFuture future, InterProcessLock lock, long timeout, TimeUnit unit) { + try { + if (unit != null) { + if (lock.acquire(timeout, unit)) { future.complete(null); - } - else - { + } else { future.completeExceptionally(new TimeoutException()); } - } - else - { + } else { lock.acquire(); future.complete(null); } - } - catch ( Throwable e ) - { + } catch (Throwable e) { ThreadUtils.checkInterrupted(e); future.completeExceptionally(e); } } - private static void completeChildren(AsyncCuratorFramework client, CompletableFuture> future, String parentPath, List children, boolean isCompressed) - { + private static void completeChildren( + AsyncCuratorFramework client, + CompletableFuture> future, + String parentPath, + List children, + boolean isCompressed) { Map nodes = Maps.newHashMap(); - if ( children.size() == 0 ) - { + if (children.size() == 0) { future.complete(nodes); return; } children.forEach(node -> { String path = ZKPaths.makePath(parentPath, node); - AsyncStage stage = isCompressed ? client.getData().decompressed().forPath(path) : client.getData().forPath(path); + AsyncStage stage = isCompressed + ? client.getData().decompressed().forPath(path) + : client.getData().forPath(path); stage.handle((data, e) -> { - if ( e != null ) - { + if (e != null) { future.completeExceptionally(e); - } - else - { + } else { nodes.put(path, data); - if ( nodes.size() == children.size() ) - { + if (nodes.size() == children.size()) { future.complete(nodes); } } @@ -377,18 +334,13 @@ private static void completeChildren(AsyncCuratorFramework client, CompletableFu }); } - private static CompletionStage ensure(AsyncCuratorFramework client, String path, ExistsOption option) - { + private static CompletionStage ensure(AsyncCuratorFramework client, String path, ExistsOption option) { String localPath = ZKPaths.makePath(path, "foo"); - return client - .checkExists() - .withOptions(Collections.singleton(option)) - .forPath(localPath) - .thenApply(__ -> null) - ; + return client.checkExists() + .withOptions(Collections.singleton(option)) + .forPath(localPath) + .thenApply(__ -> null); } - private AsyncWrappers() - { - } + private AsyncWrappers() {} } diff --git a/curator-x-async/src/main/java/org/apache/curator/x/async/WatchMode.java b/curator-x-async/src/main/java/org/apache/curator/x/async/WatchMode.java index e2c22fa39..1b8468b50 100644 --- a/curator-x-async/src/main/java/org/apache/curator/x/async/WatchMode.java +++ b/curator-x-async/src/main/java/org/apache/curator/x/async/WatchMode.java @@ -19,8 +19,7 @@ package org.apache.curator.x.async; -public enum WatchMode -{ +public enum WatchMode { /** * The {@link java.util.concurrent.CompletionStage}<org.apache.zookeeper.WatchedEvent> will only * complete on successful trigger. i.e. connection issues are ignored diff --git a/curator-x-async/src/main/java/org/apache/curator/x/async/api/AsyncCreateBuilder.java b/curator-x-async/src/main/java/org/apache/curator/x/async/api/AsyncCreateBuilder.java index da19ddb19..ab33ec918 100644 --- a/curator-x-async/src/main/java/org/apache/curator/x/async/api/AsyncCreateBuilder.java +++ b/curator-x-async/src/main/java/org/apache/curator/x/async/api/AsyncCreateBuilder.java @@ -19,18 +19,17 @@ package org.apache.curator.x.async.api; +import java.util.List; +import java.util.Set; import org.apache.curator.x.async.AsyncStage; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.data.ACL; import org.apache.zookeeper.data.Stat; -import java.util.List; -import java.util.Set; /** * Builder for ZNode creates */ -public interface AsyncCreateBuilder extends AsyncPathAndBytesable> -{ +public interface AsyncCreateBuilder extends AsyncPathAndBytesable> { /** * Have the operation fill the provided stat object * @@ -107,7 +106,8 @@ public interface AsyncCreateBuilder extends AsyncPathAndBytesable> withOptions(Set options, CreateMode createMode, List aclList); + AsyncPathAndBytesable> withOptions( + Set options, CreateMode createMode, List aclList); /** * set options and mode @@ -133,7 +133,8 @@ public interface AsyncCreateBuilder extends AsyncPathAndBytesable> withOptions(Set options, CreateMode createMode, List aclList, Stat stat); + AsyncPathAndBytesable> withOptions( + Set options, CreateMode createMode, List aclList, Stat stat); /** * set options, mode, ACLs, and stat @@ -150,7 +151,8 @@ public interface AsyncCreateBuilder extends AsyncPathAndBytesable> withOptions(Set options, CreateMode createMode, List aclList, Stat stat, long ttl); + AsyncPathAndBytesable> withOptions( + Set options, CreateMode createMode, List aclList, Stat stat, long ttl); /** * set options, mode, ACLs, and stat @@ -169,5 +171,11 @@ public interface AsyncCreateBuilder extends AsyncPathAndBytesable> withOptions(Set options, CreateMode createMode, List aclList, Stat stat, long ttl, int setDataVersion); + AsyncPathAndBytesable> withOptions( + Set options, + CreateMode createMode, + List aclList, + Stat stat, + long ttl, + int setDataVersion); } diff --git a/curator-x-async/src/main/java/org/apache/curator/x/async/api/AsyncCuratorFrameworkDsl.java b/curator-x-async/src/main/java/org/apache/curator/x/async/api/AsyncCuratorFrameworkDsl.java index b0fa01f03..751ddb26e 100644 --- a/curator-x-async/src/main/java/org/apache/curator/x/async/api/AsyncCuratorFrameworkDsl.java +++ b/curator-x-async/src/main/java/org/apache/curator/x/async/api/AsyncCuratorFrameworkDsl.java @@ -24,8 +24,7 @@ /** * Zookeeper framework-style client */ -public interface AsyncCuratorFrameworkDsl extends WatchableAsyncCuratorFramework -{ +public interface AsyncCuratorFrameworkDsl extends WatchableAsyncCuratorFramework { /** *

* Returns a facade that adds watching to any of the subsequently created builders. i.e. all diff --git a/curator-x-async/src/main/java/org/apache/curator/x/async/api/AsyncDeleteBuilder.java b/curator-x-async/src/main/java/org/apache/curator/x/async/api/AsyncDeleteBuilder.java index f22544980..c0aac7c28 100644 --- a/curator-x-async/src/main/java/org/apache/curator/x/async/api/AsyncDeleteBuilder.java +++ b/curator-x-async/src/main/java/org/apache/curator/x/async/api/AsyncDeleteBuilder.java @@ -19,14 +19,13 @@ package org.apache.curator.x.async.api; -import org.apache.curator.x.async.AsyncStage; import java.util.Set; +import org.apache.curator.x.async.AsyncStage; /** * Builder for ZNode deletions */ -public interface AsyncDeleteBuilder extends AsyncPathable> -{ +public interface AsyncDeleteBuilder extends AsyncPathable> { /** * Changes the deletion options. By default, no options are used * diff --git a/curator-x-async/src/main/java/org/apache/curator/x/async/api/AsyncEnsemblable.java b/curator-x-async/src/main/java/org/apache/curator/x/async/api/AsyncEnsemblable.java index b95c6e313..71ef2509e 100644 --- a/curator-x-async/src/main/java/org/apache/curator/x/async/api/AsyncEnsemblable.java +++ b/curator-x-async/src/main/java/org/apache/curator/x/async/api/AsyncEnsemblable.java @@ -22,8 +22,7 @@ /** * Terminal operation for config/reconfig builders */ -public interface AsyncEnsemblable -{ +public interface AsyncEnsemblable { /** * Commit the currently building operation and invoke ZooKeeper * diff --git a/curator-x-async/src/main/java/org/apache/curator/x/async/api/AsyncExistsBuilder.java b/curator-x-async/src/main/java/org/apache/curator/x/async/api/AsyncExistsBuilder.java index acb16f4cf..ae7c482ca 100644 --- a/curator-x-async/src/main/java/org/apache/curator/x/async/api/AsyncExistsBuilder.java +++ b/curator-x-async/src/main/java/org/apache/curator/x/async/api/AsyncExistsBuilder.java @@ -19,15 +19,14 @@ package org.apache.curator.x.async.api; +import java.util.Set; import org.apache.curator.x.async.AsyncStage; import org.apache.zookeeper.data.Stat; -import java.util.Set; /** * Builder for ZNode exists */ -public interface AsyncExistsBuilder extends AsyncPathable> -{ +public interface AsyncExistsBuilder extends AsyncPathable> { /** * Use the given options. The default is to use no options * diff --git a/curator-x-async/src/main/java/org/apache/curator/x/async/api/AsyncGetACLBuilder.java b/curator-x-async/src/main/java/org/apache/curator/x/async/api/AsyncGetACLBuilder.java index 6da26c7fd..8f6088b10 100644 --- a/curator-x-async/src/main/java/org/apache/curator/x/async/api/AsyncGetACLBuilder.java +++ b/curator-x-async/src/main/java/org/apache/curator/x/async/api/AsyncGetACLBuilder.java @@ -19,16 +19,15 @@ package org.apache.curator.x.async.api; +import java.util.List; import org.apache.curator.x.async.AsyncStage; import org.apache.zookeeper.data.ACL; import org.apache.zookeeper.data.Stat; -import java.util.List; /** * Builder for getAcls */ -public interface AsyncGetACLBuilder extends AsyncPathable>> -{ +public interface AsyncGetACLBuilder extends AsyncPathable>> { /** * Have the operation fill the provided stat object * diff --git a/curator-x-async/src/main/java/org/apache/curator/x/async/api/AsyncGetChildrenBuilder.java b/curator-x-async/src/main/java/org/apache/curator/x/async/api/AsyncGetChildrenBuilder.java index fa4b715fa..89dce2de8 100644 --- a/curator-x-async/src/main/java/org/apache/curator/x/async/api/AsyncGetChildrenBuilder.java +++ b/curator-x-async/src/main/java/org/apache/curator/x/async/api/AsyncGetChildrenBuilder.java @@ -19,15 +19,14 @@ package org.apache.curator.x.async.api; +import java.util.List; import org.apache.curator.x.async.AsyncStage; import org.apache.zookeeper.data.Stat; -import java.util.List; /** * Builder for getChildren() */ -public interface AsyncGetChildrenBuilder extends AsyncPathable>> -{ +public interface AsyncGetChildrenBuilder extends AsyncPathable>> { /** * Have the operation fill the provided stat object * diff --git a/curator-x-async/src/main/java/org/apache/curator/x/async/api/AsyncGetConfigBuilder.java b/curator-x-async/src/main/java/org/apache/curator/x/async/api/AsyncGetConfigBuilder.java index a2887a630..3ceb2324a 100644 --- a/curator-x-async/src/main/java/org/apache/curator/x/async/api/AsyncGetConfigBuilder.java +++ b/curator-x-async/src/main/java/org/apache/curator/x/async/api/AsyncGetConfigBuilder.java @@ -25,8 +25,7 @@ /** * Builder for getConfig() */ -public interface AsyncGetConfigBuilder extends AsyncEnsemblable> -{ +public interface AsyncGetConfigBuilder extends AsyncEnsemblable> { /** * Have the operation fill the provided stat object * diff --git a/curator-x-async/src/main/java/org/apache/curator/x/async/api/AsyncGetDataBuilder.java b/curator-x-async/src/main/java/org/apache/curator/x/async/api/AsyncGetDataBuilder.java index ee5b23995..1840e39b3 100644 --- a/curator-x-async/src/main/java/org/apache/curator/x/async/api/AsyncGetDataBuilder.java +++ b/curator-x-async/src/main/java/org/apache/curator/x/async/api/AsyncGetDataBuilder.java @@ -25,8 +25,7 @@ /** * Builder to get ZNode data */ -public interface AsyncGetDataBuilder extends AsyncPathable> -{ +public interface AsyncGetDataBuilder extends AsyncPathable> { /** * Cause the data to be de-compressed using the configured compression provider * diff --git a/curator-x-async/src/main/java/org/apache/curator/x/async/api/AsyncMultiTransaction.java b/curator-x-async/src/main/java/org/apache/curator/x/async/api/AsyncMultiTransaction.java index fd6cad7a1..ed5f2df04 100644 --- a/curator-x-async/src/main/java/org/apache/curator/x/async/api/AsyncMultiTransaction.java +++ b/curator-x-async/src/main/java/org/apache/curator/x/async/api/AsyncMultiTransaction.java @@ -19,16 +19,15 @@ package org.apache.curator.x.async.api; +import java.util.List; import org.apache.curator.framework.api.transaction.CuratorOp; import org.apache.curator.framework.api.transaction.CuratorTransactionResult; import org.apache.curator.x.async.AsyncStage; -import java.util.List; /** * Terminal operation to support multi/transactions */ -public interface AsyncMultiTransaction -{ +public interface AsyncMultiTransaction { /** * Invoke ZooKeeper to commit the given operations as a single transaction. Create the * operation instances via {@link org.apache.curator.x.async.AsyncCuratorFramework#transactionOp()} diff --git a/curator-x-async/src/main/java/org/apache/curator/x/async/api/AsyncPathAndBytesable.java b/curator-x-async/src/main/java/org/apache/curator/x/async/api/AsyncPathAndBytesable.java index 2a9f3a4e7..4201879be 100644 --- a/curator-x-async/src/main/java/org/apache/curator/x/async/api/AsyncPathAndBytesable.java +++ b/curator-x-async/src/main/java/org/apache/curator/x/async/api/AsyncPathAndBytesable.java @@ -22,8 +22,7 @@ /** * Terminal operation for various builders */ -public interface AsyncPathAndBytesable extends AsyncPathable -{ +public interface AsyncPathAndBytesable extends AsyncPathable { /** * Commit the currently building operation using the given path and data * and invoke ZooKeeper diff --git a/curator-x-async/src/main/java/org/apache/curator/x/async/api/AsyncPathable.java b/curator-x-async/src/main/java/org/apache/curator/x/async/api/AsyncPathable.java index 41b9d5604..4fe49e039 100644 --- a/curator-x-async/src/main/java/org/apache/curator/x/async/api/AsyncPathable.java +++ b/curator-x-async/src/main/java/org/apache/curator/x/async/api/AsyncPathable.java @@ -22,8 +22,7 @@ /** * Terminal operation for various builders */ -public interface AsyncPathable -{ +public interface AsyncPathable { /** * Commit the currently building operation using the given path * and invoke ZooKeeper diff --git a/curator-x-async/src/main/java/org/apache/curator/x/async/api/AsyncReconfigBuilder.java b/curator-x-async/src/main/java/org/apache/curator/x/async/api/AsyncReconfigBuilder.java index 8fd192f26..840323077 100644 --- a/curator-x-async/src/main/java/org/apache/curator/x/async/api/AsyncReconfigBuilder.java +++ b/curator-x-async/src/main/java/org/apache/curator/x/async/api/AsyncReconfigBuilder.java @@ -19,15 +19,14 @@ package org.apache.curator.x.async.api; +import java.util.List; import org.apache.curator.x.async.AsyncStage; import org.apache.zookeeper.data.Stat; -import java.util.List; /** * Builder for reconfigs */ -public interface AsyncReconfigBuilder -{ +public interface AsyncReconfigBuilder { /** * Sets one or more members that are meant to be the ensemble. * The expected format is: server.[id]=[hostname]:[peer port]:[election port]:[type];[client port] @@ -68,7 +67,8 @@ public interface AsyncReconfigBuilder * @see #withJoiningAndLeaving(java.util.List, java.util.List) * @return this */ - AsyncEnsemblable> withJoiningAndLeaving(List joining, List leaving, long fromConfig); + AsyncEnsemblable> withJoiningAndLeaving( + List joining, List leaving, long fromConfig); /** * Same as {@link #withNewMembers(java.util.List)} but allows a stat to hold the stat info from "/zookeeper/config" @@ -115,5 +115,6 @@ public interface AsyncReconfigBuilder * @see #withJoiningAndLeaving(java.util.List, java.util.List, org.apache.zookeeper.data.Stat) * @return this */ - AsyncEnsemblable> withJoiningAndLeaving(List joining, List leaving, Stat stat, long fromConfig); + AsyncEnsemblable> withJoiningAndLeaving( + List joining, List leaving, Stat stat, long fromConfig); } diff --git a/curator-x-async/src/main/java/org/apache/curator/x/async/api/AsyncRemoveWatchesBuilder.java b/curator-x-async/src/main/java/org/apache/curator/x/async/api/AsyncRemoveWatchesBuilder.java index 6bc1e6fe2..95849e80b 100644 --- a/curator-x-async/src/main/java/org/apache/curator/x/async/api/AsyncRemoveWatchesBuilder.java +++ b/curator-x-async/src/main/java/org/apache/curator/x/async/api/AsyncRemoveWatchesBuilder.java @@ -19,16 +19,15 @@ package org.apache.curator.x.async.api; +import java.util.Set; import org.apache.curator.framework.api.CuratorWatcher; import org.apache.curator.x.async.AsyncStage; import org.apache.zookeeper.Watcher; -import java.util.Set; /** * Builder for watcher removal */ -public interface AsyncRemoveWatchesBuilder -{ +public interface AsyncRemoveWatchesBuilder { /** * @param watcher the watcher to remove * @return this @@ -78,7 +77,8 @@ public interface AsyncRemoveWatchesBuilder * @param options watcher removal options * @return this */ - AsyncPathable> removing(Watcher watcher, Watcher.WatcherType watcherType, Set options); + AsyncPathable> removing( + Watcher watcher, Watcher.WatcherType watcherType, Set options); /** * Remove a watcher of a given type @@ -88,7 +88,8 @@ public interface AsyncRemoveWatchesBuilder * @param options watcher removal options * @return this */ - AsyncPathable> removing(CuratorWatcher watcher, Watcher.WatcherType watcherType, Set options); + AsyncPathable> removing( + CuratorWatcher watcher, Watcher.WatcherType watcherType, Set options); /** * Remove all watchers of a given type diff --git a/curator-x-async/src/main/java/org/apache/curator/x/async/api/AsyncSetACLBuilder.java b/curator-x-async/src/main/java/org/apache/curator/x/async/api/AsyncSetACLBuilder.java index a8d9e1a9c..bdbfc1a25 100644 --- a/curator-x-async/src/main/java/org/apache/curator/x/async/api/AsyncSetACLBuilder.java +++ b/curator-x-async/src/main/java/org/apache/curator/x/async/api/AsyncSetACLBuilder.java @@ -19,16 +19,15 @@ package org.apache.curator.x.async.api; +import java.util.List; import org.apache.curator.x.async.AsyncStage; import org.apache.zookeeper.data.ACL; import org.apache.zookeeper.data.Stat; -import java.util.List; /** * Builder for setting ACLs */ -public interface AsyncSetACLBuilder -{ +public interface AsyncSetACLBuilder { /** * Set the given ACLs * diff --git a/curator-x-async/src/main/java/org/apache/curator/x/async/api/AsyncSetDataBuilder.java b/curator-x-async/src/main/java/org/apache/curator/x/async/api/AsyncSetDataBuilder.java index 2dd8b4dea..972ddcfaa 100644 --- a/curator-x-async/src/main/java/org/apache/curator/x/async/api/AsyncSetDataBuilder.java +++ b/curator-x-async/src/main/java/org/apache/curator/x/async/api/AsyncSetDataBuilder.java @@ -25,8 +25,7 @@ /** * Builder for setting ZNode data */ -public interface AsyncSetDataBuilder extends AsyncPathAndBytesable> -{ +public interface AsyncSetDataBuilder extends AsyncPathAndBytesable> { /** * Cause the data to be compressed using the configured compression provider * diff --git a/curator-x-async/src/main/java/org/apache/curator/x/async/api/AsyncSyncBuilder.java b/curator-x-async/src/main/java/org/apache/curator/x/async/api/AsyncSyncBuilder.java index e3bc0ebc4..3d21d5073 100644 --- a/curator-x-async/src/main/java/org/apache/curator/x/async/api/AsyncSyncBuilder.java +++ b/curator-x-async/src/main/java/org/apache/curator/x/async/api/AsyncSyncBuilder.java @@ -24,7 +24,4 @@ /** * Builder for syncs */ -public interface AsyncSyncBuilder extends - AsyncPathable> -{ -} +public interface AsyncSyncBuilder extends AsyncPathable> {} diff --git a/curator-x-async/src/main/java/org/apache/curator/x/async/api/AsyncTransactionCheckBuilder.java b/curator-x-async/src/main/java/org/apache/curator/x/async/api/AsyncTransactionCheckBuilder.java index af3de296e..5d4e17332 100644 --- a/curator-x-async/src/main/java/org/apache/curator/x/async/api/AsyncTransactionCheckBuilder.java +++ b/curator-x-async/src/main/java/org/apache/curator/x/async/api/AsyncTransactionCheckBuilder.java @@ -24,8 +24,7 @@ /** * @see AsyncTransactionOp#check() */ -public interface AsyncTransactionCheckBuilder extends AsyncPathable -{ +public interface AsyncTransactionCheckBuilder extends AsyncPathable { /** * Use the given version (the default is -1) * diff --git a/curator-x-async/src/main/java/org/apache/curator/x/async/api/AsyncTransactionCreateBuilder.java b/curator-x-async/src/main/java/org/apache/curator/x/async/api/AsyncTransactionCreateBuilder.java index 864eb1248..1bb7de523 100644 --- a/curator-x-async/src/main/java/org/apache/curator/x/async/api/AsyncTransactionCreateBuilder.java +++ b/curator-x-async/src/main/java/org/apache/curator/x/async/api/AsyncTransactionCreateBuilder.java @@ -19,16 +19,15 @@ package org.apache.curator.x.async.api; +import java.util.List; import org.apache.curator.framework.api.transaction.CuratorOp; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.data.ACL; -import java.util.List; /** * @see AsyncTransactionOp#create() */ -public interface AsyncTransactionCreateBuilder extends AsyncPathAndBytesable -{ +public interface AsyncTransactionCreateBuilder extends AsyncPathAndBytesable { /** * Specify a mode for the create. The default is {@link org.apache.zookeeper.CreateMode#PERSISTENT} * @@ -89,5 +88,6 @@ public interface AsyncTransactionCreateBuilder extends AsyncPathAndBytesable withOptions(CreateMode createMode, List aclList, boolean compressed, long ttl); + AsyncPathAndBytesable withOptions( + CreateMode createMode, List aclList, boolean compressed, long ttl); } diff --git a/curator-x-async/src/main/java/org/apache/curator/x/async/api/AsyncTransactionDeleteBuilder.java b/curator-x-async/src/main/java/org/apache/curator/x/async/api/AsyncTransactionDeleteBuilder.java index 7210831d3..c22e0080e 100644 --- a/curator-x-async/src/main/java/org/apache/curator/x/async/api/AsyncTransactionDeleteBuilder.java +++ b/curator-x-async/src/main/java/org/apache/curator/x/async/api/AsyncTransactionDeleteBuilder.java @@ -24,8 +24,7 @@ /** * @see AsyncTransactionOp#delete() */ -public interface AsyncTransactionDeleteBuilder extends AsyncPathable -{ +public interface AsyncTransactionDeleteBuilder extends AsyncPathable { /** * Changes the version number used. By default, -1 is used * diff --git a/curator-x-async/src/main/java/org/apache/curator/x/async/api/AsyncTransactionOp.java b/curator-x-async/src/main/java/org/apache/curator/x/async/api/AsyncTransactionOp.java index 40e8e428b..1bd6d817f 100644 --- a/curator-x-async/src/main/java/org/apache/curator/x/async/api/AsyncTransactionOp.java +++ b/curator-x-async/src/main/java/org/apache/curator/x/async/api/AsyncTransactionOp.java @@ -23,8 +23,7 @@ * Builds operations that can be committed as a transaction * via {@link org.apache.curator.x.async.AsyncCuratorFramework#transaction()} */ -public interface AsyncTransactionOp -{ +public interface AsyncTransactionOp { /** * Start a create builder in the transaction * diff --git a/curator-x-async/src/main/java/org/apache/curator/x/async/api/AsyncTransactionSetDataBuilder.java b/curator-x-async/src/main/java/org/apache/curator/x/async/api/AsyncTransactionSetDataBuilder.java index 922256a14..37f45a1d2 100644 --- a/curator-x-async/src/main/java/org/apache/curator/x/async/api/AsyncTransactionSetDataBuilder.java +++ b/curator-x-async/src/main/java/org/apache/curator/x/async/api/AsyncTransactionSetDataBuilder.java @@ -24,8 +24,7 @@ /** * @see AsyncTransactionOp#setData() */ -public interface AsyncTransactionSetDataBuilder extends AsyncPathAndBytesable -{ +public interface AsyncTransactionSetDataBuilder extends AsyncPathAndBytesable { /** * Changes the version number used. By default, -1 is used * diff --git a/curator-x-async/src/main/java/org/apache/curator/x/async/api/AsyncWatchBuilder.java b/curator-x-async/src/main/java/org/apache/curator/x/async/api/AsyncWatchBuilder.java index 751082071..218a92125 100644 --- a/curator-x-async/src/main/java/org/apache/curator/x/async/api/AsyncWatchBuilder.java +++ b/curator-x-async/src/main/java/org/apache/curator/x/async/api/AsyncWatchBuilder.java @@ -23,10 +23,8 @@ import org.apache.curator.x.async.AsyncStage; import org.apache.zookeeper.AddWatchMode; -public interface AsyncWatchBuilder extends - WatchableBase>>, - AsyncPathable> -{ +public interface AsyncWatchBuilder + extends WatchableBase>>, AsyncPathable> { /** * The mode to use. By default, {@link org.apache.zookeeper.AddWatchMode#PERSISTENT_RECURSIVE} is used * @@ -34,4 +32,4 @@ public interface AsyncWatchBuilder extends * @return this */ AsyncWatchBuilder2 withMode(AddWatchMode mode); -} \ No newline at end of file +} diff --git a/curator-x-async/src/main/java/org/apache/curator/x/async/api/AsyncWatchBuilder2.java b/curator-x-async/src/main/java/org/apache/curator/x/async/api/AsyncWatchBuilder2.java index 43a1e49d1..9156bc4dc 100644 --- a/curator-x-async/src/main/java/org/apache/curator/x/async/api/AsyncWatchBuilder2.java +++ b/curator-x-async/src/main/java/org/apache/curator/x/async/api/AsyncWatchBuilder2.java @@ -22,8 +22,5 @@ import org.apache.curator.framework.api.WatchableBase; import org.apache.curator.x.async.AsyncStage; -public interface AsyncWatchBuilder2 extends - WatchableBase>>, - AsyncPathable> -{ -} \ No newline at end of file +public interface AsyncWatchBuilder2 + extends WatchableBase>>, AsyncPathable> {} diff --git a/curator-x-async/src/main/java/org/apache/curator/x/async/api/CreateOption.java b/curator-x-async/src/main/java/org/apache/curator/x/async/api/CreateOption.java index 0b8f9cd6a..6214f9c1d 100644 --- a/curator-x-async/src/main/java/org/apache/curator/x/async/api/CreateOption.java +++ b/curator-x-async/src/main/java/org/apache/curator/x/async/api/CreateOption.java @@ -22,8 +22,7 @@ /** * Options when creating ZNodes */ -public enum CreateOption -{ +public enum CreateOption { /** * Causes any parent nodes to get created if they haven't already been */ diff --git a/curator-x-async/src/main/java/org/apache/curator/x/async/api/DeleteOption.java b/curator-x-async/src/main/java/org/apache/curator/x/async/api/DeleteOption.java index 2069fbe3d..0e6d550a5 100644 --- a/curator-x-async/src/main/java/org/apache/curator/x/async/api/DeleteOption.java +++ b/curator-x-async/src/main/java/org/apache/curator/x/async/api/DeleteOption.java @@ -22,8 +22,7 @@ /** * Options to use when deleting ZNodes */ -public enum DeleteOption -{ +public enum DeleteOption { /** * Prevents the reporting of {@link org.apache.zookeeper.KeeperException.NoNodeException}s. * If the ZNode doesn't exist the delete method will appear to succeed. diff --git a/curator-x-async/src/main/java/org/apache/curator/x/async/api/ExistsOption.java b/curator-x-async/src/main/java/org/apache/curator/x/async/api/ExistsOption.java index 649db4a42..cc777a425 100644 --- a/curator-x-async/src/main/java/org/apache/curator/x/async/api/ExistsOption.java +++ b/curator-x-async/src/main/java/org/apache/curator/x/async/api/ExistsOption.java @@ -22,8 +22,7 @@ /** * Options to use when checking for ZNode existence */ -public enum ExistsOption -{ +public enum ExistsOption { /** * see {@link CreateOption#createParentsIfNeeded} */ diff --git a/curator-x-async/src/main/java/org/apache/curator/x/async/api/RemoveWatcherOption.java b/curator-x-async/src/main/java/org/apache/curator/x/async/api/RemoveWatcherOption.java index 33696bbf5..ca909e347 100644 --- a/curator-x-async/src/main/java/org/apache/curator/x/async/api/RemoveWatcherOption.java +++ b/curator-x-async/src/main/java/org/apache/curator/x/async/api/RemoveWatcherOption.java @@ -22,8 +22,7 @@ /** * Options to use when removing watchers */ -public enum RemoveWatcherOption -{ +public enum RemoveWatcherOption { /** * Solves edge cases where an operation may succeed on the server but connection failure occurs before a * response can be successfully returned to the client. diff --git a/curator-x-async/src/main/java/org/apache/curator/x/async/api/WatchableAsyncCuratorFramework.java b/curator-x-async/src/main/java/org/apache/curator/x/async/api/WatchableAsyncCuratorFramework.java index 1e3642bcc..86ab5b13c 100644 --- a/curator-x-async/src/main/java/org/apache/curator/x/async/api/WatchableAsyncCuratorFramework.java +++ b/curator-x-async/src/main/java/org/apache/curator/x/async/api/WatchableAsyncCuratorFramework.java @@ -22,8 +22,7 @@ /** * operations that support watching */ -public interface WatchableAsyncCuratorFramework -{ +public interface WatchableAsyncCuratorFramework { /** * Start an exists builder. The builder will return a Stat object as if org.apache.zookeeper.ZooKeeper.exists() were called. Thus, a null * means that it does not exist and an actual Stat object means it does exist. diff --git a/curator-x-async/src/main/java/org/apache/curator/x/async/details/AsyncCreateBuilderImpl.java b/curator-x-async/src/main/java/org/apache/curator/x/async/details/AsyncCreateBuilderImpl.java index ec576b17f..5ab579934 100644 --- a/curator-x-async/src/main/java/org/apache/curator/x/async/details/AsyncCreateBuilderImpl.java +++ b/curator-x-async/src/main/java/org/apache/curator/x/async/details/AsyncCreateBuilderImpl.java @@ -19,6 +19,12 @@ package org.apache.curator.x.async.details; +import static org.apache.curator.x.async.details.BackgroundProcs.nameProc; +import static org.apache.curator.x.async.details.BackgroundProcs.safeCall; +import java.util.Collections; +import java.util.List; +import java.util.Objects; +import java.util.Set; import org.apache.curator.framework.imps.CreateBuilderImpl; import org.apache.curator.framework.imps.CuratorFrameworkImpl; import org.apache.curator.x.async.AsyncStage; @@ -28,16 +34,8 @@ import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.data.ACL; import org.apache.zookeeper.data.Stat; -import java.util.Collections; -import java.util.List; -import java.util.Objects; -import java.util.Set; - -import static org.apache.curator.x.async.details.BackgroundProcs.nameProc; -import static org.apache.curator.x.async.details.BackgroundProcs.safeCall; -class AsyncCreateBuilderImpl implements AsyncCreateBuilder -{ +class AsyncCreateBuilderImpl implements AsyncCreateBuilder { private final CuratorFrameworkImpl client; private final Filters filters; private CreateMode createMode = CreateMode.PERSISTENT; @@ -47,65 +45,57 @@ class AsyncCreateBuilderImpl implements AsyncCreateBuilder private long ttl = -1; private int setDataVersion = -1; - AsyncCreateBuilderImpl(CuratorFrameworkImpl client, Filters filters) - { + AsyncCreateBuilderImpl(CuratorFrameworkImpl client, Filters filters) { this.client = client; this.filters = filters; } @Override - public AsyncPathAndBytesable> storingStatIn(Stat stat) - { + public AsyncPathAndBytesable> storingStatIn(Stat stat) { this.stat = stat; return this; } @Override - public AsyncPathAndBytesable> withMode(CreateMode createMode) - { + public AsyncPathAndBytesable> withMode(CreateMode createMode) { this.createMode = Objects.requireNonNull(createMode, "createMode cannot be null"); return this; } @Override - public AsyncPathAndBytesable> withACL(List aclList) - { + public AsyncPathAndBytesable> withACL(List aclList) { this.aclList = aclList; return this; } @Override - public AsyncPathAndBytesable> withTtl(long ttl) - { + public AsyncPathAndBytesable> withTtl(long ttl) { this.ttl = ttl; return this; } @Override - public AsyncPathAndBytesable> withSetDataVersion(int version) - { + public AsyncPathAndBytesable> withSetDataVersion(int version) { this.setDataVersion = version; return this; } @Override - public AsyncPathAndBytesable> withOptions(Set options) - { + public AsyncPathAndBytesable> withOptions(Set options) { this.options = Objects.requireNonNull(options, "options cannot be null"); return this; } @Override - public AsyncPathAndBytesable> withOptions(Set options, List aclList) - { + public AsyncPathAndBytesable> withOptions(Set options, List aclList) { this.options = Objects.requireNonNull(options, "options cannot be null"); this.aclList = aclList; return this; } @Override - public AsyncPathAndBytesable> withOptions(Set options, CreateMode createMode, List aclList) - { + public AsyncPathAndBytesable> withOptions( + Set options, CreateMode createMode, List aclList) { this.options = Objects.requireNonNull(options, "options cannot be null"); this.aclList = aclList; this.createMode = Objects.requireNonNull(createMode, "createMode cannot be null"); @@ -113,16 +103,15 @@ public AsyncPathAndBytesable> withOptions(Set o } @Override - public AsyncPathAndBytesable> withOptions(Set options, CreateMode createMode) - { + public AsyncPathAndBytesable> withOptions(Set options, CreateMode createMode) { this.options = Objects.requireNonNull(options, "options cannot be null"); this.createMode = Objects.requireNonNull(createMode, "createMode cannot be null"); return this; } @Override - public AsyncPathAndBytesable> withOptions(Set options, CreateMode createMode, List aclList, Stat stat) - { + public AsyncPathAndBytesable> withOptions( + Set options, CreateMode createMode, List aclList, Stat stat) { this.options = Objects.requireNonNull(options, "options cannot be null"); this.aclList = aclList; this.createMode = Objects.requireNonNull(createMode, "createMode cannot be null"); @@ -131,8 +120,8 @@ public AsyncPathAndBytesable> withOptions(Set o } @Override - public AsyncPathAndBytesable> withOptions(Set options, CreateMode createMode, List aclList, Stat stat, long ttl) - { + public AsyncPathAndBytesable> withOptions( + Set options, CreateMode createMode, List aclList, Stat stat, long ttl) { this.options = Objects.requireNonNull(options, "options cannot be null"); this.aclList = aclList; this.createMode = Objects.requireNonNull(createMode, "createMode cannot be null"); @@ -142,8 +131,13 @@ public AsyncPathAndBytesable> withOptions(Set o } @Override - public AsyncPathAndBytesable> withOptions(Set options, CreateMode createMode, List aclList, Stat stat, long ttl, int setDataVersion) - { + public AsyncPathAndBytesable> withOptions( + Set options, + CreateMode createMode, + List aclList, + Stat stat, + long ttl, + int setDataVersion) { this.options = Objects.requireNonNull(options, "options cannot be null"); this.aclList = aclList; this.createMode = Objects.requireNonNull(createMode, "createMode cannot be null"); @@ -154,32 +148,30 @@ public AsyncPathAndBytesable> withOptions(Set o } @Override - public AsyncStage forPath(String path) - { + public AsyncStage forPath(String path) { return internalForPath(path, null, false); } @Override - public AsyncStage forPath(String path, byte[] data) - { + public AsyncStage forPath(String path, byte[] data) { return internalForPath(path, data, true); } - private AsyncStage internalForPath(String path, byte[] data, boolean useData) - { + private AsyncStage internalForPath(String path, byte[] data, boolean useData) { BuilderCommon common = new BuilderCommon<>(filters, nameProc); - CreateBuilderImpl builder = new CreateBuilderImpl(client, - createMode, - common.backgrounding, - options.contains(CreateOption.createParentsIfNeeded) || options.contains(CreateOption.createParentsAsContainers), - options.contains(CreateOption.createParentsAsContainers), - options.contains(CreateOption.doProtected), - options.contains(CreateOption.compress), - options.contains(CreateOption.setDataIfExists), - aclList, - stat, - ttl - ); + CreateBuilderImpl builder = new CreateBuilderImpl( + client, + createMode, + common.backgrounding, + options.contains(CreateOption.createParentsIfNeeded) + || options.contains(CreateOption.createParentsAsContainers), + options.contains(CreateOption.createParentsAsContainers), + options.contains(CreateOption.doProtected), + options.contains(CreateOption.compress), + options.contains(CreateOption.setDataIfExists), + aclList, + stat, + ttl); builder.setSetDataIfExistsVersion(setDataVersion); return safeCall(common.internalCallback, () -> useData ? builder.forPath(path, data) : builder.forPath(path)); } diff --git a/curator-x-async/src/main/java/org/apache/curator/x/async/details/AsyncCuratorFrameworkImpl.java b/curator-x-async/src/main/java/org/apache/curator/x/async/details/AsyncCuratorFrameworkImpl.java index afeee947c..7e38a821f 100644 --- a/curator-x-async/src/main/java/org/apache/curator/x/async/details/AsyncCuratorFrameworkImpl.java +++ b/curator-x-async/src/main/java/org/apache/curator/x/async/details/AsyncCuratorFrameworkImpl.java @@ -19,7 +19,11 @@ package org.apache.curator.x.async.details; +import static org.apache.curator.x.async.details.BackgroundProcs.*; import com.google.common.base.Preconditions; +import java.util.List; +import java.util.Objects; +import java.util.function.UnaryOperator; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.api.CuratorEvent; import org.apache.curator.framework.api.UnhandledErrorListener; @@ -36,38 +40,29 @@ import org.apache.zookeeper.WatchedEvent; import org.apache.zookeeper.data.ACL; import org.apache.zookeeper.data.Stat; -import java.util.List; -import java.util.Objects; -import java.util.function.UnaryOperator; -import static org.apache.curator.x.async.details.BackgroundProcs.*; - -public class AsyncCuratorFrameworkImpl implements AsyncCuratorFramework -{ +public class AsyncCuratorFrameworkImpl implements AsyncCuratorFramework { private final CuratorFrameworkImpl client; private final Filters filters; private final WatchMode watchMode; private final boolean watched; - public AsyncCuratorFrameworkImpl(CuratorFramework client) - { + public AsyncCuratorFrameworkImpl(CuratorFramework client) { this(reveal(client), new Filters(null, null, null), WatchMode.stateChangeAndSuccess, false); } - private static CuratorFrameworkImpl reveal(CuratorFramework client) - { - try - { - return (CuratorFrameworkImpl)Objects.requireNonNull(client, "client cannot be null"); - } - catch ( Exception e ) - { - throw new IllegalArgumentException("Only Curator clients created through CuratorFrameworkFactory are supported: " + client.getClass().getName()); + private static CuratorFrameworkImpl reveal(CuratorFramework client) { + try { + return (CuratorFrameworkImpl) Objects.requireNonNull(client, "client cannot be null"); + } catch (Exception e) { + throw new IllegalArgumentException( + "Only Curator clients created through CuratorFrameworkFactory are supported: " + + client.getClass().getName()); } } - public AsyncCuratorFrameworkImpl(CuratorFrameworkImpl client, Filters filters, WatchMode watchMode, boolean watched) - { + public AsyncCuratorFrameworkImpl( + CuratorFrameworkImpl client, Filters filters, WatchMode watchMode, boolean watched) { this.client = Objects.requireNonNull(client, "client cannot be null"); this.filters = Objects.requireNonNull(filters, "filters cannot be null"); this.watchMode = Objects.requireNonNull(watchMode, "watchMode cannot be null"); @@ -75,40 +70,33 @@ public AsyncCuratorFrameworkImpl(CuratorFrameworkImpl client, Filters filters, W } @Override - public AsyncCreateBuilder create() - { + public AsyncCreateBuilder create() { return new AsyncCreateBuilderImpl(client, filters); } @Override - public AsyncDeleteBuilder delete() - { + public AsyncDeleteBuilder delete() { return new AsyncDeleteBuilderImpl(client, filters); } @Override - public AsyncSetDataBuilder setData() - { + public AsyncSetDataBuilder setData() { return new AsyncSetDataBuilderImpl(client, filters); } @Override - public AsyncGetACLBuilder getACL() - { - return new AsyncGetACLBuilder() - { + public AsyncGetACLBuilder getACL() { + return new AsyncGetACLBuilder() { private Stat stat = null; @Override - public AsyncPathable>> storingStatIn(Stat stat) - { + public AsyncPathable>> storingStatIn(Stat stat) { this.stat = stat; return this; } @Override - public AsyncStage> forPath(String path) - { + public AsyncStage> forPath(String path) { BuilderCommon> common = new BuilderCommon<>(filters, aclProc); GetACLBuilderImpl builder = new GetACLBuilderImpl(client, common.backgrounding, stat); return safeCall(common.internalCallback, () -> builder.forPath(path)); @@ -117,20 +105,17 @@ public AsyncStage> forPath(String path) } @Override - public AsyncSetACLBuilder setACL() - { + public AsyncSetACLBuilder setACL() { return new AsyncSetACLBuilderImpl(client, filters); } @Override - public AsyncReconfigBuilder reconfig() - { + public AsyncReconfigBuilder reconfig() { return new AsyncReconfigBuilderImpl(client, filters); } @Override - public AsyncMultiTransaction transaction() - { + public AsyncMultiTransaction transaction() { return operations -> { BuilderCommon> common = new BuilderCommon<>(filters, opResultsProc); CuratorMultiTransactionImpl builder = new CuratorMultiTransactionImpl(client, common.backgrounding); @@ -139,8 +124,7 @@ public AsyncMultiTransaction transaction() } @Override - public AsyncSyncBuilder sync() - { + public AsyncSyncBuilder sync() { return path -> { BuilderCommon common = new BuilderCommon<>(filters, ignoredProc); SyncBuilderImpl builder = new SyncBuilderImpl(client, common.backgrounding); @@ -149,102 +133,102 @@ public AsyncSyncBuilder sync() } @Override - public AsyncRemoveWatchesBuilder removeWatches() - { + public AsyncRemoveWatchesBuilder removeWatches() { return new AsyncRemoveWatchesBuilderImpl(client, filters); } @Override - public AsyncWatchBuilder addWatch() - { - Preconditions.checkState(Compatibility.hasPersistentWatchers(), "addWatch() is not supported in the ZooKeeper library being used."); + public AsyncWatchBuilder addWatch() { + Preconditions.checkState( + Compatibility.hasPersistentWatchers(), + "addWatch() is not supported in the ZooKeeper library being used."); return new AsyncWatchBuilderImpl(client, filters); } @Override - public CuratorFramework unwrap() - { + public CuratorFramework unwrap() { return client; } @Override - public WatchableAsyncCuratorFramework watched() - { + public WatchableAsyncCuratorFramework watched() { return new AsyncCuratorFrameworkImpl(client, filters, watchMode, true); } @Override - public AsyncCuratorFrameworkDsl with(WatchMode mode) - { + public AsyncCuratorFrameworkDsl with(WatchMode mode) { return new AsyncCuratorFrameworkImpl(client, filters, mode, watched); } @Override - public AsyncCuratorFrameworkDsl with(WatchMode mode, UnhandledErrorListener listener, UnaryOperator resultFilter, UnaryOperator watcherFilter) - { - return new AsyncCuratorFrameworkImpl(client, new Filters(listener, filters.getResultFilter(), filters.getWatcherFilter()), mode, watched); + public AsyncCuratorFrameworkDsl with( + WatchMode mode, + UnhandledErrorListener listener, + UnaryOperator resultFilter, + UnaryOperator watcherFilter) { + return new AsyncCuratorFrameworkImpl( + client, new Filters(listener, filters.getResultFilter(), filters.getWatcherFilter()), mode, watched); } @Override - public AsyncCuratorFrameworkDsl with(UnhandledErrorListener listener) - { - return new AsyncCuratorFrameworkImpl(client, new Filters(listener, filters.getResultFilter(), filters.getWatcherFilter()), watchMode, watched); + public AsyncCuratorFrameworkDsl with(UnhandledErrorListener listener) { + return new AsyncCuratorFrameworkImpl( + client, + new Filters(listener, filters.getResultFilter(), filters.getWatcherFilter()), + watchMode, + watched); } @Override - public AsyncCuratorFrameworkDsl with(UnaryOperator resultFilter, UnaryOperator watcherFilter) - { - return new AsyncCuratorFrameworkImpl(client, new Filters(filters.getListener(), resultFilter, watcherFilter), watchMode, watched); + public AsyncCuratorFrameworkDsl with( + UnaryOperator resultFilter, UnaryOperator watcherFilter) { + return new AsyncCuratorFrameworkImpl( + client, new Filters(filters.getListener(), resultFilter, watcherFilter), watchMode, watched); } @Override - public AsyncCuratorFrameworkDsl with(UnhandledErrorListener listener, UnaryOperator resultFilter, UnaryOperator watcherFilter) - { - return new AsyncCuratorFrameworkImpl(client, new Filters(listener, resultFilter, watcherFilter), watchMode, watched); + public AsyncCuratorFrameworkDsl with( + UnhandledErrorListener listener, + UnaryOperator resultFilter, + UnaryOperator watcherFilter) { + return new AsyncCuratorFrameworkImpl( + client, new Filters(listener, resultFilter, watcherFilter), watchMode, watched); } @Override - public AsyncTransactionOp transactionOp() - { + public AsyncTransactionOp transactionOp() { return new AsyncTransactionOpImpl(client); } @Override - public AsyncExistsBuilder checkExists() - { + public AsyncExistsBuilder checkExists() { return new AsyncExistsBuilderImpl(client, filters, getBuilderWatchMode()); } @Override - public AsyncGetDataBuilder getData() - { + public AsyncGetDataBuilder getData() { return new AsyncGetDataBuilderImpl(client, filters, getBuilderWatchMode()); } @Override - public AsyncGetChildrenBuilder getChildren() - { + public AsyncGetChildrenBuilder getChildren() { return new AsyncGetChildrenBuilderImpl(client, filters, getBuilderWatchMode()); } @Override - public AsyncGetConfigBuilder getConfig() - { + public AsyncGetConfigBuilder getConfig() { return new AsyncGetConfigBuilderImpl(client, filters, getBuilderWatchMode()); } - Filters getFilters() - { + Filters getFilters() { return filters; } - CuratorFrameworkImpl getClient() - { + CuratorFrameworkImpl getClient() { return client; } - private WatchMode getBuilderWatchMode() - { + private WatchMode getBuilderWatchMode() { return watched ? watchMode : null; } } diff --git a/curator-x-async/src/main/java/org/apache/curator/x/async/details/AsyncDeleteBuilderImpl.java b/curator-x-async/src/main/java/org/apache/curator/x/async/details/AsyncDeleteBuilderImpl.java index 1f70ca734..b1175f7b7 100644 --- a/curator-x-async/src/main/java/org/apache/curator/x/async/details/AsyncDeleteBuilderImpl.java +++ b/curator-x-async/src/main/java/org/apache/curator/x/async/details/AsyncDeleteBuilderImpl.java @@ -19,58 +19,57 @@ package org.apache.curator.x.async.details; +import static org.apache.curator.x.async.details.BackgroundProcs.ignoredProc; +import static org.apache.curator.x.async.details.BackgroundProcs.safeCall; +import java.util.Collections; +import java.util.Objects; +import java.util.Set; import org.apache.curator.framework.imps.CuratorFrameworkImpl; import org.apache.curator.framework.imps.DeleteBuilderImpl; import org.apache.curator.x.async.AsyncStage; import org.apache.curator.x.async.api.AsyncDeleteBuilder; import org.apache.curator.x.async.api.AsyncPathable; import org.apache.curator.x.async.api.DeleteOption; -import java.util.Collections; -import java.util.Objects; -import java.util.Set; - -import static org.apache.curator.x.async.details.BackgroundProcs.ignoredProc; -import static org.apache.curator.x.async.details.BackgroundProcs.safeCall; -class AsyncDeleteBuilderImpl implements AsyncDeleteBuilder -{ +class AsyncDeleteBuilderImpl implements AsyncDeleteBuilder { private final CuratorFrameworkImpl client; private final Filters filters; private Set options = Collections.emptySet(); private int version = -1; - AsyncDeleteBuilderImpl(CuratorFrameworkImpl client, Filters filters) - { + AsyncDeleteBuilderImpl(CuratorFrameworkImpl client, Filters filters) { this.client = client; this.filters = filters; } @Override - public AsyncPathable> withOptions(Set options) - { + public AsyncPathable> withOptions(Set options) { return withOptionsAndVersion(options, -1); } @Override - public AsyncPathable> withOptionsAndVersion(Set options, int version) - { + public AsyncPathable> withOptionsAndVersion(Set options, int version) { this.options = Objects.requireNonNull(options, "options cannot be null"); this.version = version; return this; } @Override - public AsyncPathable> withVersion(int version) - { + public AsyncPathable> withVersion(int version) { this.version = version; return this; } @Override - public AsyncStage forPath(String path) - { + public AsyncStage forPath(String path) { BuilderCommon common = new BuilderCommon<>(filters, ignoredProc); - DeleteBuilderImpl builder = new DeleteBuilderImpl(client, version, common.backgrounding, options.contains(DeleteOption.deletingChildrenIfNeeded), options.contains(DeleteOption.guaranteed), options.contains(DeleteOption.quietly)); + DeleteBuilderImpl builder = new DeleteBuilderImpl( + client, + version, + common.backgrounding, + options.contains(DeleteOption.deletingChildrenIfNeeded), + options.contains(DeleteOption.guaranteed), + options.contains(DeleteOption.quietly)); return safeCall(common.internalCallback, () -> builder.forPath(path)); } } diff --git a/curator-x-async/src/main/java/org/apache/curator/x/async/details/AsyncExistsBuilderImpl.java b/curator-x-async/src/main/java/org/apache/curator/x/async/details/AsyncExistsBuilderImpl.java index 057d70492..002713081 100644 --- a/curator-x-async/src/main/java/org/apache/curator/x/async/details/AsyncExistsBuilderImpl.java +++ b/curator-x-async/src/main/java/org/apache/curator/x/async/details/AsyncExistsBuilderImpl.java @@ -19,6 +19,11 @@ package org.apache.curator.x.async.details; +import static org.apache.curator.x.async.details.BackgroundProcs.safeCall; +import static org.apache.curator.x.async.details.BackgroundProcs.safeStatProc; +import java.util.Collections; +import java.util.Objects; +import java.util.Set; import org.apache.curator.framework.imps.CuratorFrameworkImpl; import org.apache.curator.framework.imps.ExistsBuilderImpl; import org.apache.curator.x.async.AsyncStage; @@ -27,44 +32,34 @@ import org.apache.curator.x.async.api.AsyncPathable; import org.apache.curator.x.async.api.ExistsOption; import org.apache.zookeeper.data.Stat; -import java.util.Collections; -import java.util.Objects; -import java.util.Set; - -import static org.apache.curator.x.async.details.BackgroundProcs.safeCall; -import static org.apache.curator.x.async.details.BackgroundProcs.safeStatProc; -class AsyncExistsBuilderImpl implements AsyncExistsBuilder -{ +class AsyncExistsBuilderImpl implements AsyncExistsBuilder { private final CuratorFrameworkImpl client; private final Filters filters; private final WatchMode watchMode; private Set options = Collections.emptySet(); - AsyncExistsBuilderImpl(CuratorFrameworkImpl client, Filters filters, WatchMode watchMode) - { + AsyncExistsBuilderImpl(CuratorFrameworkImpl client, Filters filters, WatchMode watchMode) { this.client = client; this.filters = filters; this.watchMode = watchMode; } @Override - public AsyncPathable> withOptions(Set options) - { + public AsyncPathable> withOptions(Set options) { this.options = Objects.requireNonNull(options, "options cannot be null"); return this; } @Override - public AsyncStage forPath(String path) - { + public AsyncStage forPath(String path) { BuilderCommon common = new BuilderCommon<>(filters, watchMode, safeStatProc); - ExistsBuilderImpl builder = new ExistsBuilderImpl(client, - common.backgrounding, - common.watcher, - options.contains(ExistsOption.createParentsIfNeeded), - options.contains(ExistsOption.createParentsAsContainers) - ); + ExistsBuilderImpl builder = new ExistsBuilderImpl( + client, + common.backgrounding, + common.watcher, + options.contains(ExistsOption.createParentsIfNeeded), + options.contains(ExistsOption.createParentsAsContainers)); return safeCall(common.internalCallback, () -> builder.forPath(path)); } } diff --git a/curator-x-async/src/main/java/org/apache/curator/x/async/details/AsyncGetChildrenBuilderImpl.java b/curator-x-async/src/main/java/org/apache/curator/x/async/details/AsyncGetChildrenBuilderImpl.java index 005160736..f30a52986 100644 --- a/curator-x-async/src/main/java/org/apache/curator/x/async/details/AsyncGetChildrenBuilderImpl.java +++ b/curator-x-async/src/main/java/org/apache/curator/x/async/details/AsyncGetChildrenBuilderImpl.java @@ -19,6 +19,9 @@ package org.apache.curator.x.async.details; +import static org.apache.curator.x.async.details.BackgroundProcs.childrenProc; +import static org.apache.curator.x.async.details.BackgroundProcs.safeCall; +import java.util.List; import org.apache.curator.framework.imps.CuratorFrameworkImpl; import org.apache.curator.framework.imps.GetChildrenBuilderImpl; import org.apache.curator.x.async.AsyncStage; @@ -26,36 +29,28 @@ import org.apache.curator.x.async.api.AsyncGetChildrenBuilder; import org.apache.curator.x.async.api.AsyncPathable; import org.apache.zookeeper.data.Stat; -import java.util.List; - -import static org.apache.curator.x.async.details.BackgroundProcs.childrenProc; -import static org.apache.curator.x.async.details.BackgroundProcs.safeCall; -class AsyncGetChildrenBuilderImpl implements AsyncGetChildrenBuilder -{ +class AsyncGetChildrenBuilderImpl implements AsyncGetChildrenBuilder { private final CuratorFrameworkImpl client; private final Filters filters; private final WatchMode watchMode; private Stat stat = null; - AsyncGetChildrenBuilderImpl(CuratorFrameworkImpl client, Filters filters, WatchMode watchMode) - { + AsyncGetChildrenBuilderImpl(CuratorFrameworkImpl client, Filters filters, WatchMode watchMode) { this.client = client; this.filters = filters; this.watchMode = watchMode; } @Override - public AsyncStage> forPath(String path) - { + public AsyncStage> forPath(String path) { BuilderCommon> common = new BuilderCommon<>(filters, watchMode, childrenProc); GetChildrenBuilderImpl builder = new GetChildrenBuilderImpl(client, common.watcher, common.backgrounding, stat); return safeCall(common.internalCallback, () -> builder.forPath(path)); } @Override - public AsyncPathable>> storingStatIn(Stat stat) - { + public AsyncPathable>> storingStatIn(Stat stat) { this.stat = stat; return this; } diff --git a/curator-x-async/src/main/java/org/apache/curator/x/async/details/AsyncGetConfigBuilderImpl.java b/curator-x-async/src/main/java/org/apache/curator/x/async/details/AsyncGetConfigBuilderImpl.java index b67c1b268..a3390bea9 100644 --- a/curator-x-async/src/main/java/org/apache/curator/x/async/details/AsyncGetConfigBuilderImpl.java +++ b/curator-x-async/src/main/java/org/apache/curator/x/async/details/AsyncGetConfigBuilderImpl.java @@ -19,6 +19,8 @@ package org.apache.curator.x.async.details; +import static org.apache.curator.x.async.details.BackgroundProcs.dataProc; +import static org.apache.curator.x.async.details.BackgroundProcs.safeCall; import org.apache.curator.framework.imps.CuratorFrameworkImpl; import org.apache.curator.framework.imps.GetConfigBuilderImpl; import org.apache.curator.x.async.AsyncStage; @@ -27,33 +29,26 @@ import org.apache.curator.x.async.api.AsyncGetConfigBuilder; import org.apache.zookeeper.data.Stat; -import static org.apache.curator.x.async.details.BackgroundProcs.dataProc; -import static org.apache.curator.x.async.details.BackgroundProcs.safeCall; - -class AsyncGetConfigBuilderImpl implements AsyncGetConfigBuilder -{ +class AsyncGetConfigBuilderImpl implements AsyncGetConfigBuilder { private final CuratorFrameworkImpl client; private final Filters filters; private final WatchMode watchMode; private Stat stat = null; - AsyncGetConfigBuilderImpl(CuratorFrameworkImpl client, Filters filters, WatchMode watchMode) - { + AsyncGetConfigBuilderImpl(CuratorFrameworkImpl client, Filters filters, WatchMode watchMode) { this.client = client; this.filters = filters; this.watchMode = watchMode; } @Override - public AsyncEnsemblable> storingStatIn(Stat stat) - { + public AsyncEnsemblable> storingStatIn(Stat stat) { this.stat = stat; return this; } @Override - public AsyncStage forEnsemble() - { + public AsyncStage forEnsemble() { BuilderCommon common = new BuilderCommon<>(filters, watchMode, dataProc); GetConfigBuilderImpl builder = new GetConfigBuilderImpl(client, common.backgrounding, common.watcher, stat); return safeCall(common.internalCallback, builder::forEnsemble); diff --git a/curator-x-async/src/main/java/org/apache/curator/x/async/details/AsyncGetDataBuilderImpl.java b/curator-x-async/src/main/java/org/apache/curator/x/async/details/AsyncGetDataBuilderImpl.java index ac179ba04..a94d1052b 100644 --- a/curator-x-async/src/main/java/org/apache/curator/x/async/details/AsyncGetDataBuilderImpl.java +++ b/curator-x-async/src/main/java/org/apache/curator/x/async/details/AsyncGetDataBuilderImpl.java @@ -19,6 +19,8 @@ package org.apache.curator.x.async.details; +import static org.apache.curator.x.async.details.BackgroundProcs.dataProc; +import static org.apache.curator.x.async.details.BackgroundProcs.safeCall; import org.apache.curator.framework.imps.CuratorFrameworkImpl; import org.apache.curator.framework.imps.GetDataBuilderImpl; import org.apache.curator.x.async.AsyncStage; @@ -27,51 +29,43 @@ import org.apache.curator.x.async.api.AsyncPathable; import org.apache.zookeeper.data.Stat; -import static org.apache.curator.x.async.details.BackgroundProcs.dataProc; -import static org.apache.curator.x.async.details.BackgroundProcs.safeCall; - -class AsyncGetDataBuilderImpl implements AsyncGetDataBuilder -{ +class AsyncGetDataBuilderImpl implements AsyncGetDataBuilder { private final CuratorFrameworkImpl client; private final Filters filters; private final WatchMode watchMode; private boolean decompressed = false; private Stat stat = null; - AsyncGetDataBuilderImpl(CuratorFrameworkImpl client, Filters filters, WatchMode watchMode) - { + AsyncGetDataBuilderImpl(CuratorFrameworkImpl client, Filters filters, WatchMode watchMode) { this.client = client; this.filters = filters; this.watchMode = watchMode; } @Override - public AsyncPathable> decompressed() - { + public AsyncPathable> decompressed() { decompressed = true; return this; } @Override - public AsyncPathable> storingStatIn(Stat stat) - { + public AsyncPathable> storingStatIn(Stat stat) { this.stat = stat; return this; } @Override - public AsyncPathable> decompressedStoringStatIn(Stat stat) - { + public AsyncPathable> decompressedStoringStatIn(Stat stat) { decompressed = true; this.stat = stat; return this; } @Override - public AsyncStage forPath(String path) - { + public AsyncStage forPath(String path) { BuilderCommon common = new BuilderCommon<>(filters, watchMode, dataProc); - GetDataBuilderImpl builder = new GetDataBuilderImpl(client, stat, common.watcher, common.backgrounding, decompressed); + GetDataBuilderImpl builder = + new GetDataBuilderImpl(client, stat, common.watcher, common.backgrounding, decompressed); return safeCall(common.internalCallback, () -> builder.forPath(path)); } } diff --git a/curator-x-async/src/main/java/org/apache/curator/x/async/details/AsyncReconfigBuilderImpl.java b/curator-x-async/src/main/java/org/apache/curator/x/async/details/AsyncReconfigBuilderImpl.java index 7e989a9db..b490113bf 100644 --- a/curator-x-async/src/main/java/org/apache/curator/x/async/details/AsyncReconfigBuilderImpl.java +++ b/curator-x-async/src/main/java/org/apache/curator/x/async/details/AsyncReconfigBuilderImpl.java @@ -19,19 +19,17 @@ package org.apache.curator.x.async.details; +import static org.apache.curator.x.async.details.BackgroundProcs.ignoredProc; +import static org.apache.curator.x.async.details.BackgroundProcs.safeCall; +import java.util.List; import org.apache.curator.framework.imps.CuratorFrameworkImpl; import org.apache.curator.framework.imps.ReconfigBuilderImpl; import org.apache.curator.x.async.AsyncStage; import org.apache.curator.x.async.api.AsyncEnsemblable; import org.apache.curator.x.async.api.AsyncReconfigBuilder; import org.apache.zookeeper.data.Stat; -import java.util.List; - -import static org.apache.curator.x.async.details.BackgroundProcs.ignoredProc; -import static org.apache.curator.x.async.details.BackgroundProcs.safeCall; -class AsyncReconfigBuilderImpl implements AsyncReconfigBuilder, AsyncEnsemblable> -{ +class AsyncReconfigBuilderImpl implements AsyncReconfigBuilder, AsyncEnsemblable> { private final CuratorFrameworkImpl client; private final Filters filters; private Stat stat = null; @@ -40,46 +38,41 @@ class AsyncReconfigBuilderImpl implements AsyncReconfigBuilder, AsyncEnsemblable private List joining = null; private List leaving = null; - AsyncReconfigBuilderImpl(CuratorFrameworkImpl client, Filters filters) - { + AsyncReconfigBuilderImpl(CuratorFrameworkImpl client, Filters filters) { this.client = client; this.filters = filters; } @Override - public AsyncEnsemblable> withNewMembers(List servers) - { + public AsyncEnsemblable> withNewMembers(List servers) { this.newMembers = servers; return this; } @Override - public AsyncEnsemblable> withJoiningAndLeaving(List joining, List leaving) - { + public AsyncEnsemblable> withJoiningAndLeaving(List joining, List leaving) { this.joining = joining; this.leaving = leaving; return this; } @Override - public AsyncEnsemblable> withNewMembers(List servers, Stat stat) - { + public AsyncEnsemblable> withNewMembers(List servers, Stat stat) { this.newMembers = servers; this.stat = stat; return this; } @Override - public AsyncEnsemblable> withJoiningAndLeaving(List joining, List leaving, Stat stat) - { + public AsyncEnsemblable> withJoiningAndLeaving( + List joining, List leaving, Stat stat) { this.joining = joining; this.leaving = leaving; return this; } @Override - public AsyncEnsemblable> withNewMembers(List servers, Stat stat, long fromConfig) - { + public AsyncEnsemblable> withNewMembers(List servers, Stat stat, long fromConfig) { this.newMembers = servers; this.stat = stat; this.fromConfig = fromConfig; @@ -87,8 +80,8 @@ public AsyncEnsemblable> withNewMembers(List servers, S } @Override - public AsyncEnsemblable> withJoiningAndLeaving(List joining, List leaving, Stat stat, long fromConfig) - { + public AsyncEnsemblable> withJoiningAndLeaving( + List joining, List leaving, Stat stat, long fromConfig) { this.joining = joining; this.leaving = leaving; this.stat = stat; @@ -97,16 +90,15 @@ public AsyncEnsemblable> withJoiningAndLeaving(List joi } @Override - public AsyncEnsemblable> withNewMembers(List servers, long fromConfig) - { + public AsyncEnsemblable> withNewMembers(List servers, long fromConfig) { this.newMembers = servers; this.fromConfig = fromConfig; return this; } @Override - public AsyncEnsemblable> withJoiningAndLeaving(List joining, List leaving, long fromConfig) - { + public AsyncEnsemblable> withJoiningAndLeaving( + List joining, List leaving, long fromConfig) { this.joining = joining; this.leaving = leaving; this.fromConfig = fromConfig; @@ -114,10 +106,10 @@ public AsyncEnsemblable> withJoiningAndLeaving(List joi } @Override - public AsyncStage forEnsemble() - { + public AsyncStage forEnsemble() { BuilderCommon common = new BuilderCommon<>(filters, ignoredProc); - ReconfigBuilderImpl builder = new ReconfigBuilderImpl(client, common.backgrounding, stat, fromConfig, newMembers, joining, leaving); + ReconfigBuilderImpl builder = + new ReconfigBuilderImpl(client, common.backgrounding, stat, fromConfig, newMembers, joining, leaving); return safeCall(common.internalCallback, () -> { builder.forEnsemble(); return null; diff --git a/curator-x-async/src/main/java/org/apache/curator/x/async/details/AsyncRemoveWatchesBuilderImpl.java b/curator-x-async/src/main/java/org/apache/curator/x/async/details/AsyncRemoveWatchesBuilderImpl.java index 428eb98d8..5f111b737 100644 --- a/curator-x-async/src/main/java/org/apache/curator/x/async/details/AsyncRemoveWatchesBuilderImpl.java +++ b/curator-x-async/src/main/java/org/apache/curator/x/async/details/AsyncRemoveWatchesBuilderImpl.java @@ -19,6 +19,11 @@ package org.apache.curator.x.async.details; +import static org.apache.curator.x.async.details.BackgroundProcs.ignoredProc; +import static org.apache.curator.x.async.details.BackgroundProcs.safeCall; +import java.util.Collections; +import java.util.Objects; +import java.util.Set; import org.apache.curator.framework.api.CuratorWatcher; import org.apache.curator.framework.imps.CuratorFrameworkImpl; import org.apache.curator.framework.imps.RemoveWatchesBuilderImpl; @@ -27,15 +32,8 @@ import org.apache.curator.x.async.api.AsyncRemoveWatchesBuilder; import org.apache.curator.x.async.api.RemoveWatcherOption; import org.apache.zookeeper.Watcher; -import java.util.Collections; -import java.util.Objects; -import java.util.Set; - -import static org.apache.curator.x.async.details.BackgroundProcs.ignoredProc; -import static org.apache.curator.x.async.details.BackgroundProcs.safeCall; -class AsyncRemoveWatchesBuilderImpl implements AsyncRemoveWatchesBuilder, AsyncPathable> -{ +class AsyncRemoveWatchesBuilderImpl implements AsyncRemoveWatchesBuilder, AsyncPathable> { private final CuratorFrameworkImpl client; private final Filters filters; private Watcher.WatcherType watcherType = Watcher.WatcherType.Any; @@ -43,39 +41,34 @@ class AsyncRemoveWatchesBuilderImpl implements AsyncRemoveWatchesBuilder, AsyncP private Watcher watcher = null; private CuratorWatcher curatorWatcher = null; - AsyncRemoveWatchesBuilderImpl(CuratorFrameworkImpl client, Filters filters) - { + AsyncRemoveWatchesBuilderImpl(CuratorFrameworkImpl client, Filters filters) { this.client = client; this.filters = filters; } @Override - public AsyncPathable> removing(Watcher watcher) - { + public AsyncPathable> removing(Watcher watcher) { this.watcher = Objects.requireNonNull(watcher, "watcher cannot be null"); this.curatorWatcher = null; return this; } @Override - public AsyncPathable> removing(CuratorWatcher watcher) - { + public AsyncPathable> removing(CuratorWatcher watcher) { this.curatorWatcher = Objects.requireNonNull(watcher, "watcher cannot be null"); this.watcher = null; return this; } @Override - public AsyncPathable> removingAll() - { + public AsyncPathable> removingAll() { this.curatorWatcher = null; this.watcher = null; return this; } @Override - public AsyncPathable> removing(Watcher watcher, Set options) - { + public AsyncPathable> removing(Watcher watcher, Set options) { this.watcher = Objects.requireNonNull(watcher, "watcher cannot be null"); this.options = Objects.requireNonNull(options, "options cannot be null"); this.curatorWatcher = null; @@ -83,8 +76,7 @@ public AsyncPathable> removing(Watcher watcher, Set> removing(CuratorWatcher watcher, Set options) - { + public AsyncPathable> removing(CuratorWatcher watcher, Set options) { this.curatorWatcher = Objects.requireNonNull(watcher, "watcher cannot be null"); this.options = Objects.requireNonNull(options, "options cannot be null"); this.watcher = null; @@ -92,8 +84,7 @@ public AsyncPathable> removing(CuratorWatcher watcher, Set> removingAll(Set options) - { + public AsyncPathable> removingAll(Set options) { this.options = Objects.requireNonNull(options, "options cannot be null"); this.curatorWatcher = null; this.watcher = null; @@ -101,8 +92,8 @@ public AsyncPathable> removingAll(Set opti } @Override - public AsyncPathable> removing(Watcher watcher, Watcher.WatcherType watcherType, Set options) - { + public AsyncPathable> removing( + Watcher watcher, Watcher.WatcherType watcherType, Set options) { this.watcher = Objects.requireNonNull(watcher, "watcher cannot be null"); this.options = Objects.requireNonNull(options, "options cannot be null"); this.watcherType = Objects.requireNonNull(watcherType, "watcherType cannot be null"); @@ -111,8 +102,8 @@ public AsyncPathable> removing(Watcher watcher, Watcher.Watcher } @Override - public AsyncPathable> removing(CuratorWatcher watcher, Watcher.WatcherType watcherType, Set options) - { + public AsyncPathable> removing( + CuratorWatcher watcher, Watcher.WatcherType watcherType, Set options) { this.curatorWatcher = Objects.requireNonNull(watcher, "watcher cannot be null"); this.options = Objects.requireNonNull(options, "options cannot be null"); this.watcherType = Objects.requireNonNull(watcherType, "watcherType cannot be null"); @@ -121,8 +112,8 @@ public AsyncPathable> removing(CuratorWatcher watcher, Watcher. } @Override - public AsyncPathable> removingAll(Watcher.WatcherType watcherType, Set options) - { + public AsyncPathable> removingAll( + Watcher.WatcherType watcherType, Set options) { this.options = Objects.requireNonNull(options, "options cannot be null"); this.watcherType = Objects.requireNonNull(watcherType, "watcherType cannot be null"); this.curatorWatcher = null; @@ -131,8 +122,7 @@ public AsyncPathable> removingAll(Watcher.WatcherType watcherTy } @Override - public AsyncPathable> removing(Watcher watcher, Watcher.WatcherType watcherType) - { + public AsyncPathable> removing(Watcher watcher, Watcher.WatcherType watcherType) { this.watcher = Objects.requireNonNull(watcher, "watcher cannot be null"); this.watcherType = Objects.requireNonNull(watcherType, "watcherType cannot be null"); this.curatorWatcher = null; @@ -140,8 +130,7 @@ public AsyncPathable> removing(Watcher watcher, Watcher.Watcher } @Override - public AsyncPathable> removing(CuratorWatcher watcher, Watcher.WatcherType watcherType) - { + public AsyncPathable> removing(CuratorWatcher watcher, Watcher.WatcherType watcherType) { this.curatorWatcher = Objects.requireNonNull(watcher, "watcher cannot be null"); this.watcherType = Objects.requireNonNull(watcherType, "watcherType cannot be null"); this.watcher = null; @@ -149,8 +138,7 @@ public AsyncPathable> removing(CuratorWatcher watcher, Watcher. } @Override - public AsyncPathable> removingAll(Watcher.WatcherType watcherType) - { + public AsyncPathable> removingAll(Watcher.WatcherType watcherType) { this.watcherType = Objects.requireNonNull(watcherType, "watcherType cannot be null"); this.curatorWatcher = null; this.watcher = null; @@ -158,18 +146,17 @@ public AsyncPathable> removingAll(Watcher.WatcherType watcherTy } @Override - public AsyncStage forPath(String path) - { + public AsyncStage forPath(String path) { BuilderCommon common = new BuilderCommon<>(filters, ignoredProc); - RemoveWatchesBuilderImpl builder = new RemoveWatchesBuilderImpl(client, - watcher, - curatorWatcher, - watcherType, - options.contains(RemoveWatcherOption.guaranteed), - options.contains(RemoveWatcherOption.local), - options.contains(RemoveWatcherOption.guaranteed), - common.backgrounding - ); + RemoveWatchesBuilderImpl builder = new RemoveWatchesBuilderImpl( + client, + watcher, + curatorWatcher, + watcherType, + options.contains(RemoveWatcherOption.guaranteed), + options.contains(RemoveWatcherOption.local), + options.contains(RemoveWatcherOption.guaranteed), + common.backgrounding); return safeCall(common.internalCallback, () -> builder.forPath(path)); } } diff --git a/curator-x-async/src/main/java/org/apache/curator/x/async/details/AsyncResultImpl.java b/curator-x-async/src/main/java/org/apache/curator/x/async/details/AsyncResultImpl.java index 550ab4078..2f2d2d430 100644 --- a/curator-x-async/src/main/java/org/apache/curator/x/async/details/AsyncResultImpl.java +++ b/curator-x-async/src/main/java/org/apache/curator/x/async/details/AsyncResultImpl.java @@ -19,116 +19,95 @@ package org.apache.curator.x.async.details; -import org.apache.curator.x.async.AsyncResult; -import org.apache.zookeeper.KeeperException; import java.util.Objects; import java.util.Optional; +import org.apache.curator.x.async.AsyncResult; +import org.apache.zookeeper.KeeperException; -public class AsyncResultImpl implements AsyncResult -{ +public class AsyncResultImpl implements AsyncResult { private final T value; private final KeeperException.Code code; private final Throwable exception; - public AsyncResultImpl() - { + public AsyncResultImpl() { this(null, KeeperException.Code.OK, null); } - public AsyncResultImpl(KeeperException.Code code) - { + public AsyncResultImpl(KeeperException.Code code) { this(null, code, null); } - public AsyncResultImpl(T value) - { + public AsyncResultImpl(T value) { this(value, KeeperException.Code.OK, null); } - public AsyncResultImpl(Throwable exception) - { + public AsyncResultImpl(Throwable exception) { this(null, KeeperException.Code.SYSTEMERROR, exception); } - private AsyncResultImpl(T value, KeeperException.Code code, Throwable exception) - { + private AsyncResultImpl(T value, KeeperException.Code code, Throwable exception) { this.value = value; this.exception = exception; this.code = Objects.requireNonNull(code, "error cannot be null"); } - public T getRawValue() - { + public T getRawValue() { return value; } - public Optional getValue() - { + public Optional getValue() { return Optional.ofNullable(value); } - public KeeperException.Code getCode() - { + public KeeperException.Code getCode() { return code; } - public Throwable getRawException() - { + public Throwable getRawException() { return exception; } - public Optional getException() - { + public Optional getException() { return Optional.ofNullable(exception); } - public void checkException() - { - if ( exception != null ) - { + public void checkException() { + if (exception != null) { throw new RuntimeException(exception); } } @Override - public void checkError() - { + public void checkError() { checkException(); - if ( code != KeeperException.Code.OK ) - { + if (code != KeeperException.Code.OK) { throw new RuntimeException(KeeperException.create(code)); } } @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; } - AsyncResultImpl that = (AsyncResultImpl)o; + AsyncResultImpl that = (AsyncResultImpl) o; - if ( value != null ? !value.equals(that.value) : that.value != null ) - { + if (value != null ? !value.equals(that.value) : that.value != null) { return false; } //noinspection SimplifiableIfStatement - if ( code != that.code ) - { + if (code != that.code) { return false; } return exception != null ? exception.equals(that.exception) : that.exception == null; } @Override - public int hashCode() - { + public int hashCode() { int result = value != null ? value.hashCode() : 0; result = 31 * result + code.hashCode(); result = 31 * result + (exception != null ? exception.hashCode() : 0); @@ -136,8 +115,7 @@ public int hashCode() } @Override - public String toString() - { + public String toString() { return "AsyncResult{" + "value=" + value + ", code=" + code + ", exception=" + exception + '}'; } } diff --git a/curator-x-async/src/main/java/org/apache/curator/x/async/details/AsyncSetACLBuilderImpl.java b/curator-x-async/src/main/java/org/apache/curator/x/async/details/AsyncSetACLBuilderImpl.java index 583764a27..5160be6ef 100644 --- a/curator-x-async/src/main/java/org/apache/curator/x/async/details/AsyncSetACLBuilderImpl.java +++ b/curator-x-async/src/main/java/org/apache/curator/x/async/details/AsyncSetACLBuilderImpl.java @@ -19,6 +19,9 @@ package org.apache.curator.x.async.details; +import static org.apache.curator.x.async.details.BackgroundProcs.safeCall; +import static org.apache.curator.x.async.details.BackgroundProcs.statProc; +import java.util.List; import org.apache.curator.framework.imps.CuratorFrameworkImpl; import org.apache.curator.framework.imps.SetACLBuilderImpl; import org.apache.curator.x.async.AsyncStage; @@ -26,42 +29,33 @@ import org.apache.curator.x.async.api.AsyncSetACLBuilder; import org.apache.zookeeper.data.ACL; import org.apache.zookeeper.data.Stat; -import java.util.List; - -import static org.apache.curator.x.async.details.BackgroundProcs.safeCall; -import static org.apache.curator.x.async.details.BackgroundProcs.statProc; -class AsyncSetACLBuilderImpl implements AsyncSetACLBuilder, AsyncPathable> -{ +class AsyncSetACLBuilderImpl implements AsyncSetACLBuilder, AsyncPathable> { private final CuratorFrameworkImpl client; private final Filters filters; private int version = -1; private List aclList = null; - AsyncSetACLBuilderImpl(CuratorFrameworkImpl client, Filters filters) - { + AsyncSetACLBuilderImpl(CuratorFrameworkImpl client, Filters filters) { this.client = client; this.filters = filters; } @Override - public AsyncPathable> withACL(List aclList) - { + public AsyncPathable> withACL(List aclList) { this.aclList = aclList; return this; } @Override - public AsyncPathable> withACL(List aclList, int version) - { + public AsyncPathable> withACL(List aclList, int version) { this.aclList = aclList; this.version = version; return this; } @Override - public AsyncStage forPath(String path) - { + public AsyncStage forPath(String path) { BuilderCommon common = new BuilderCommon<>(filters, statProc); SetACLBuilderImpl builder = new SetACLBuilderImpl(client, common.backgrounding, aclList, version); return safeCall(common.internalCallback, () -> builder.forPath(path)); diff --git a/curator-x-async/src/main/java/org/apache/curator/x/async/details/AsyncSetDataBuilderImpl.java b/curator-x-async/src/main/java/org/apache/curator/x/async/details/AsyncSetDataBuilderImpl.java index 7f4a4cd58..af1452457 100644 --- a/curator-x-async/src/main/java/org/apache/curator/x/async/details/AsyncSetDataBuilderImpl.java +++ b/curator-x-async/src/main/java/org/apache/curator/x/async/details/AsyncSetDataBuilderImpl.java @@ -19,6 +19,8 @@ package org.apache.curator.x.async.details; +import static org.apache.curator.x.async.details.BackgroundProcs.safeCall; +import static org.apache.curator.x.async.details.BackgroundProcs.statProc; import org.apache.curator.framework.imps.CuratorFrameworkImpl; import org.apache.curator.framework.imps.SetDataBuilderImpl; import org.apache.curator.x.async.AsyncStage; @@ -26,58 +28,47 @@ import org.apache.curator.x.async.api.AsyncSetDataBuilder; import org.apache.zookeeper.data.Stat; -import static org.apache.curator.x.async.details.BackgroundProcs.safeCall; -import static org.apache.curator.x.async.details.BackgroundProcs.statProc; - -class AsyncSetDataBuilderImpl implements AsyncSetDataBuilder -{ +class AsyncSetDataBuilderImpl implements AsyncSetDataBuilder { private final CuratorFrameworkImpl client; private final Filters filters; private boolean compressed = false; private int version = -1; - AsyncSetDataBuilderImpl(CuratorFrameworkImpl client, Filters filters) - { + AsyncSetDataBuilderImpl(CuratorFrameworkImpl client, Filters filters) { this.client = client; this.filters = filters; } @Override - public AsyncStage forPath(String path) - { + public AsyncStage forPath(String path) { return internalForPath(path, null, false); } @Override - public AsyncStage forPath(String path, byte[] data) - { + public AsyncStage forPath(String path, byte[] data) { return internalForPath(path, data, true); } @Override - public AsyncPathAndBytesable> compressed() - { + public AsyncPathAndBytesable> compressed() { compressed = true; return this; } @Override - public AsyncPathAndBytesable> compressedWithVersion(int version) - { + public AsyncPathAndBytesable> compressedWithVersion(int version) { compressed = true; this.version = version; return this; } @Override - public AsyncPathAndBytesable> withVersion(int version) - { + public AsyncPathAndBytesable> withVersion(int version) { this.version = version; return this; } - private AsyncStage internalForPath(String path, byte[] data, boolean useData) - { + private AsyncStage internalForPath(String path, byte[] data, boolean useData) { BuilderCommon common = new BuilderCommon<>(filters, statProc); SetDataBuilderImpl builder = new SetDataBuilderImpl(client, common.backgrounding, version, compressed); return safeCall(common.internalCallback, () -> useData ? builder.forPath(path, data) : builder.forPath(path)); diff --git a/curator-x-async/src/main/java/org/apache/curator/x/async/details/AsyncTransactionOpImpl.java b/curator-x-async/src/main/java/org/apache/curator/x/async/details/AsyncTransactionOpImpl.java index 559572f27..e9ccbf16d 100644 --- a/curator-x-async/src/main/java/org/apache/curator/x/async/details/AsyncTransactionOpImpl.java +++ b/curator-x-async/src/main/java/org/apache/curator/x/async/details/AsyncTransactionOpImpl.java @@ -19,6 +19,8 @@ package org.apache.curator.x.async.details; +import java.util.List; +import java.util.Objects; import org.apache.curator.framework.api.ACLPathAndBytesable; import org.apache.curator.framework.api.PathAndBytesable; import org.apache.curator.framework.api.VersionPathAndBytesable; @@ -35,65 +37,55 @@ import org.apache.curator.x.async.api.AsyncTransactionSetDataBuilder; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.data.ACL; -import java.util.List; -import java.util.Objects; -class AsyncTransactionOpImpl implements AsyncTransactionOp -{ +class AsyncTransactionOpImpl implements AsyncTransactionOp { private final CuratorFrameworkImpl client; - AsyncTransactionOpImpl(CuratorFrameworkImpl client) - { + AsyncTransactionOpImpl(CuratorFrameworkImpl client) { this.client = client; } @Override - public AsyncTransactionCreateBuilder create() - { - return new AsyncTransactionCreateBuilder() - { + public AsyncTransactionCreateBuilder create() { + return new AsyncTransactionCreateBuilder() { private List aclList = null; private CreateMode createMode = CreateMode.PERSISTENT; private boolean compressed = false; private long ttl = -1; @Override - public AsyncPathAndBytesable withMode(CreateMode createMode) - { + public AsyncPathAndBytesable withMode(CreateMode createMode) { this.createMode = Objects.requireNonNull(createMode, "createMode cannot be null"); return this; } @Override - public AsyncPathAndBytesable withACL(List aclList) - { + public AsyncPathAndBytesable withACL(List aclList) { this.aclList = aclList; return this; } @Override - public AsyncPathAndBytesable compressed() - { + public AsyncPathAndBytesable compressed() { compressed = true; return this; } @Override - public AsyncPathAndBytesable withTtl(long ttl) - { + public AsyncPathAndBytesable withTtl(long ttl) { this.ttl = ttl; return this; } @Override - public AsyncPathAndBytesable withOptions(CreateMode createMode, List aclList, boolean compressed) - { + public AsyncPathAndBytesable withOptions( + CreateMode createMode, List aclList, boolean compressed) { return withOptions(createMode, aclList, compressed, ttl); } @Override - public AsyncPathAndBytesable withOptions(CreateMode createMode, List aclList, boolean compressed, long ttl) - { + public AsyncPathAndBytesable withOptions( + CreateMode createMode, List aclList, boolean compressed, long ttl) { this.createMode = Objects.requireNonNull(createMode, "createMode cannot be null"); this.aclList = aclList; this.compressed = compressed; @@ -102,146 +94,119 @@ public AsyncPathAndBytesable withOptions(CreateMode createMode, List< } @Override - public CuratorOp forPath(String path, byte[] data) - { + public CuratorOp forPath(String path, byte[] data) { return internalForPath(path, data, true); } @Override - public CuratorOp forPath(String path) - { + public CuratorOp forPath(String path) { return internalForPath(path, null, false); } - private CuratorOp internalForPath(String path, byte[] data, boolean useData) - { - TransactionCreateBuilder2 builder1 = (ttl > 0) ? client.transactionOp().create().withTtl(ttl) : client.transactionOp().create(); - ACLPathAndBytesable builder2 = compressed ? builder1.compressed().withMode(createMode) : builder1.withMode(createMode); + private CuratorOp internalForPath(String path, byte[] data, boolean useData) { + TransactionCreateBuilder2 builder1 = (ttl > 0) + ? client.transactionOp().create().withTtl(ttl) + : client.transactionOp().create(); + ACLPathAndBytesable builder2 = + compressed ? builder1.compressed().withMode(createMode) : builder1.withMode(createMode); PathAndBytesable builder3 = builder2.withACL(aclList); - try - { + try { return useData ? builder3.forPath(path, data) : builder3.forPath(path); - } - catch ( Exception e ) - { - throw new RuntimeException(e); // should never happen + } catch (Exception e) { + throw new RuntimeException(e); // should never happen } } }; } @Override - public AsyncTransactionDeleteBuilder delete() - { - return new AsyncTransactionDeleteBuilder() - { + public AsyncTransactionDeleteBuilder delete() { + return new AsyncTransactionDeleteBuilder() { private int version = -1; @Override - public AsyncPathable withVersion(int version) - { + public AsyncPathable withVersion(int version) { this.version = version; return this; } @Override - public CuratorOp forPath(String path) - { - try - { + public CuratorOp forPath(String path) { + try { return client.transactionOp().delete().withVersion(version).forPath(path); - } - catch ( Exception e ) - { - throw new RuntimeException(e); // should never happen + } catch (Exception e) { + throw new RuntimeException(e); // should never happen } } }; } @Override - public AsyncTransactionSetDataBuilder setData() - { - return new AsyncTransactionSetDataBuilder() - { + public AsyncTransactionSetDataBuilder setData() { + return new AsyncTransactionSetDataBuilder() { private int version = -1; private boolean compressed = false; @Override - public AsyncPathAndBytesable withVersion(int version) - { + public AsyncPathAndBytesable withVersion(int version) { this.version = version; return this; } @Override - public AsyncPathAndBytesable compressed() - { + public AsyncPathAndBytesable compressed() { compressed = true; return this; } @Override - public AsyncPathAndBytesable withVersionCompressed(int version) - { + public AsyncPathAndBytesable withVersionCompressed(int version) { this.version = version; compressed = true; return this; } @Override - public CuratorOp forPath(String path, byte[] data) - { + public CuratorOp forPath(String path, byte[] data) { return internalForPath(path, data, true); } @Override - public CuratorOp forPath(String path) - { + public CuratorOp forPath(String path) { return internalForPath(path, null, false); } - private CuratorOp internalForPath(String path, byte[] data, boolean useData) - { - TransactionSetDataBuilder builder1 = client.transactionOp().setData(); + private CuratorOp internalForPath(String path, byte[] data, boolean useData) { + TransactionSetDataBuilder builder1 = + client.transactionOp().setData(); VersionPathAndBytesable builder2 = compressed ? builder1.compressed() : builder1; PathAndBytesable builder3 = builder2.withVersion(version); - try - { + try { return useData ? builder3.forPath(path, data) : builder3.forPath(path); - } - catch ( Exception e ) - { - throw new RuntimeException(e); // should never happen + } catch (Exception e) { + throw new RuntimeException(e); // should never happen } } }; } @Override - public AsyncTransactionCheckBuilder check() - { - return new AsyncTransactionCheckBuilder() - { + public AsyncTransactionCheckBuilder check() { + return new AsyncTransactionCheckBuilder() { private int version = -1; @Override - public AsyncPathable withVersion(int version) - { + public AsyncPathable withVersion(int version) { this.version = version; return this; } @Override - public CuratorOp forPath(String path) - { - try - { + public CuratorOp forPath(String path) { + try { return client.transactionOp().check().withVersion(version).forPath(path); - } - catch ( Exception e ) - { - throw new RuntimeException(e); // should never happen + } catch (Exception e) { + throw new RuntimeException(e); // should never happen } } }; diff --git a/curator-x-async/src/main/java/org/apache/curator/x/async/details/AsyncWatchBuilderImpl.java b/curator-x-async/src/main/java/org/apache/curator/x/async/details/AsyncWatchBuilderImpl.java index 7e7b6b865..cc7cc015d 100644 --- a/curator-x-async/src/main/java/org/apache/curator/x/async/details/AsyncWatchBuilderImpl.java +++ b/curator-x-async/src/main/java/org/apache/curator/x/async/details/AsyncWatchBuilderImpl.java @@ -19,6 +19,8 @@ package org.apache.curator.x.async.details; +import static org.apache.curator.x.async.details.BackgroundProcs.ignoredProc; +import static org.apache.curator.x.async.details.BackgroundProcs.safeCall; import org.apache.curator.framework.api.CuratorWatcher; import org.apache.curator.framework.api.WatchableBase; import org.apache.curator.framework.imps.AddWatchBuilderImpl; @@ -31,49 +33,44 @@ import org.apache.zookeeper.AddWatchMode; import org.apache.zookeeper.Watcher; -import static org.apache.curator.x.async.details.BackgroundProcs.ignoredProc; -import static org.apache.curator.x.async.details.BackgroundProcs.safeCall; - -class AsyncWatchBuilderImpl implements AsyncWatchBuilder, AsyncWatchBuilder2, WatchableBase>>, AsyncPathable> -{ +class AsyncWatchBuilderImpl + implements AsyncWatchBuilder, + AsyncWatchBuilder2, + WatchableBase>>, + AsyncPathable> { private final CuratorFrameworkImpl client; private final Filters filters; private Watching watching; private AddWatchMode mode = AddWatchMode.PERSISTENT_RECURSIVE; - AsyncWatchBuilderImpl(CuratorFrameworkImpl client, Filters filters) - { + AsyncWatchBuilderImpl(CuratorFrameworkImpl client, Filters filters) { this.client = client; this.filters = filters; watching = new Watching(client, true); } @Override - public AsyncWatchBuilder2 withMode(AddWatchMode mode) - { + public AsyncWatchBuilder2 withMode(AddWatchMode mode) { this.mode = mode; return this; } @Override - public AsyncPathable> usingWatcher(Watcher watcher) - { + public AsyncPathable> usingWatcher(Watcher watcher) { watching = new Watching(client, watcher); return this; } @Override - public AsyncPathable> usingWatcher(CuratorWatcher watcher) - { + public AsyncPathable> usingWatcher(CuratorWatcher watcher) { watching = new Watching(client, watcher); return this; } @Override - public AsyncStage forPath(String path) - { + public AsyncStage forPath(String path) { BuilderCommon common = new BuilderCommon<>(filters, ignoredProc); AddWatchBuilderImpl builder = new AddWatchBuilderImpl(client, watching, common.backgrounding, mode); return safeCall(common.internalCallback, () -> builder.forPath(path)); } -} \ No newline at end of file +} diff --git a/curator-x-async/src/main/java/org/apache/curator/x/async/details/BackgroundProc.java b/curator-x-async/src/main/java/org/apache/curator/x/async/details/BackgroundProc.java index 2a15dda9e..1752077fa 100644 --- a/curator-x-async/src/main/java/org/apache/curator/x/async/details/BackgroundProc.java +++ b/curator-x-async/src/main/java/org/apache/curator/x/async/details/BackgroundProc.java @@ -19,10 +19,8 @@ package org.apache.curator.x.async.details; -import org.apache.curator.framework.api.CuratorEvent; import java.util.concurrent.CompletableFuture; import java.util.function.BiFunction; +import org.apache.curator.framework.api.CuratorEvent; -interface BackgroundProc extends BiFunction, Void> -{ -} +interface BackgroundProc extends BiFunction, Void> {} diff --git a/curator-x-async/src/main/java/org/apache/curator/x/async/details/BackgroundProcs.java b/curator-x-async/src/main/java/org/apache/curator/x/async/details/BackgroundProcs.java index a1a3975cd..82b4f10bb 100644 --- a/curator-x-async/src/main/java/org/apache/curator/x/async/details/BackgroundProcs.java +++ b/curator-x-async/src/main/java/org/apache/curator/x/async/details/BackgroundProcs.java @@ -19,30 +19,27 @@ package org.apache.curator.x.async.details; +import java.util.List; +import java.util.concurrent.Callable; +import java.util.function.Function; import org.apache.curator.framework.api.CuratorEvent; import org.apache.curator.framework.api.transaction.CuratorTransactionResult; import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.data.ACL; import org.apache.zookeeper.data.Stat; -import java.util.List; -import java.util.concurrent.Callable; -import java.util.function.Function; -class BackgroundProcs -{ +class BackgroundProcs { static final BackgroundProc nameProc = makeProc(CuratorEvent::getName); static final BackgroundProc pathProc = makeProc(CuratorEvent::getPath); static final BackgroundProc ignoredProc = makeProc(e -> null); static final BackgroundProc dataProc = makeProc(CuratorEvent::getData); static final BackgroundProc statProc = makeProc(CuratorEvent::getStat); static final BackgroundProc safeStatProc = (event, future) -> { - if ( (event.getResultCode() == 0) || (event.getResultCode() == KeeperException.Code.NONODE.intValue()) ) - { + if ((event.getResultCode() == 0) || (event.getResultCode() == KeeperException.Code.NONODE.intValue())) { future.complete(event.getStat()); - } - else - { - future.completeExceptionally(KeeperException.create(KeeperException.Code.get(event.getResultCode()), event.getPath())); + } else { + future.completeExceptionally( + KeeperException.create(KeeperException.Code.get(event.getResultCode()), event.getPath())); } return null; }; @@ -50,35 +47,26 @@ class BackgroundProcs static final BackgroundProc> aclProc = makeProc(CuratorEvent::getACLList); static final BackgroundProc> opResultsProc = makeProc(CuratorEvent::getOpResults); - static BackgroundProc makeProc(Function proc) - { + static BackgroundProc makeProc(Function proc) { return (event, future) -> { - if ( event.getResultCode() == 0 ) - { + if (event.getResultCode() == 0) { future.complete(proc.apply(event)); - } - else - { - future.completeExceptionally(KeeperException.create(KeeperException.Code.get(event.getResultCode()), event.getPath())); + } else { + future.completeExceptionally( + KeeperException.create(KeeperException.Code.get(event.getResultCode()), event.getPath())); } return null; }; } - static InternalCallback safeCall(InternalCallback callback, Callable proc) - { - try - { + static InternalCallback safeCall(InternalCallback callback, Callable proc) { + try { proc.call(); - } - catch ( Exception e ) - { + } catch (Exception e) { callback.toCompletableFuture().completeExceptionally(e); } return callback; } - BackgroundProcs() - { - } + BackgroundProcs() {} } diff --git a/curator-x-async/src/main/java/org/apache/curator/x/async/details/BuilderCommon.java b/curator-x-async/src/main/java/org/apache/curator/x/async/details/BuilderCommon.java index bb0bb67ef..cb0c056b9 100644 --- a/curator-x-async/src/main/java/org/apache/curator/x/async/details/BuilderCommon.java +++ b/curator-x-async/src/main/java/org/apache/curator/x/async/details/BuilderCommon.java @@ -22,19 +22,16 @@ import org.apache.curator.framework.imps.Backgrounding; import org.apache.curator.x.async.WatchMode; -class BuilderCommon -{ +class BuilderCommon { final InternalCallback internalCallback; final Backgrounding backgrounding; final InternalWatcher watcher; - BuilderCommon(Filters filters, BackgroundProc proc) - { - this(filters,null, proc); + BuilderCommon(Filters filters, BackgroundProc proc) { + this(filters, null, proc); } - BuilderCommon(Filters filters, WatchMode watchMode, BackgroundProc proc) - { + BuilderCommon(Filters filters, WatchMode watchMode, BackgroundProc proc) { watcher = (watchMode != null) ? new InternalWatcher(watchMode, filters.getWatcherFilter()) : null; internalCallback = new InternalCallback<>(proc, watcher, filters.getResultFilter()); backgrounding = new Backgrounding(internalCallback, filters.getListener()); diff --git a/curator-x-async/src/main/java/org/apache/curator/x/async/details/Filters.java b/curator-x-async/src/main/java/org/apache/curator/x/async/details/Filters.java index 083866b76..9c6117793 100644 --- a/curator-x-async/src/main/java/org/apache/curator/x/async/details/Filters.java +++ b/curator-x-async/src/main/java/org/apache/curator/x/async/details/Filters.java @@ -19,36 +19,34 @@ package org.apache.curator.x.async.details; +import java.util.function.UnaryOperator; import org.apache.curator.framework.api.CuratorEvent; import org.apache.curator.framework.api.UnhandledErrorListener; import org.apache.zookeeper.WatchedEvent; -import java.util.function.UnaryOperator; -public class Filters -{ +public class Filters { private final UnhandledErrorListener listener; private final UnaryOperator resultFilter; private final UnaryOperator watcherFilter; - public Filters(UnhandledErrorListener listener, UnaryOperator resultFilter, UnaryOperator watcherFilter) - { + public Filters( + UnhandledErrorListener listener, + UnaryOperator resultFilter, + UnaryOperator watcherFilter) { this.listener = listener; this.resultFilter = resultFilter; this.watcherFilter = watcherFilter; } - public UnhandledErrorListener getListener() - { + public UnhandledErrorListener getListener() { return listener; } - public UnaryOperator getResultFilter() - { + public UnaryOperator getResultFilter() { return resultFilter; } - public UnaryOperator getWatcherFilter() - { + public UnaryOperator getWatcherFilter() { return watcherFilter; } } diff --git a/curator-x-async/src/main/java/org/apache/curator/x/async/details/InternalCallback.java b/curator-x-async/src/main/java/org/apache/curator/x/async/details/InternalCallback.java index 60f3cf33a..5bdd3cec8 100644 --- a/curator-x-async/src/main/java/org/apache/curator/x/async/details/InternalCallback.java +++ b/curator-x-async/src/main/java/org/apache/curator/x/async/details/InternalCallback.java @@ -19,37 +19,34 @@ package org.apache.curator.x.async.details; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionStage; +import java.util.function.UnaryOperator; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.api.BackgroundCallback; import org.apache.curator.framework.api.CuratorEvent; import org.apache.curator.x.async.AsyncStage; import org.apache.zookeeper.WatchedEvent; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.CompletionStage; -import java.util.function.UnaryOperator; -class InternalCallback extends CompletableFuture implements BackgroundCallback, AsyncStage -{ +class InternalCallback extends CompletableFuture implements BackgroundCallback, AsyncStage { private final BackgroundProc resultFunction; private final InternalWatcher watcher; private final UnaryOperator resultFilter; - InternalCallback(BackgroundProc resultFunction, InternalWatcher watcher, UnaryOperator resultFilter) - { + InternalCallback( + BackgroundProc resultFunction, InternalWatcher watcher, UnaryOperator resultFilter) { this.resultFunction = resultFunction; this.watcher = watcher; this.resultFilter = resultFilter; } @Override - public CompletionStage event() - { + public CompletionStage event() { return (watcher != null) ? watcher.getFuture() : null; } @Override - public void processResult(CuratorFramework client, CuratorEvent event) throws Exception - { + public void processResult(CuratorFramework client, CuratorEvent event) throws Exception { event = (resultFilter != null) ? resultFilter.apply(event) : event; resultFunction.apply(event, this); } diff --git a/curator-x-async/src/main/java/org/apache/curator/x/async/details/InternalWatcher.java b/curator-x-async/src/main/java/org/apache/curator/x/async/details/InternalWatcher.java index 5849ee745..2fee7ab27 100644 --- a/curator-x-async/src/main/java/org/apache/curator/x/async/details/InternalWatcher.java +++ b/curator-x-async/src/main/java/org/apache/curator/x/async/details/InternalWatcher.java @@ -20,44 +20,36 @@ package org.apache.curator.x.async.details; import com.google.common.base.Preconditions; -import org.apache.curator.x.async.AsyncEventException; -import org.apache.curator.x.async.WatchMode; -import org.apache.zookeeper.WatchedEvent; -import org.apache.zookeeper.Watcher; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.UnaryOperator; +import org.apache.curator.x.async.AsyncEventException; +import org.apache.curator.x.async.WatchMode; +import org.apache.zookeeper.WatchedEvent; +import org.apache.zookeeper.Watcher; -class InternalWatcher implements Watcher -{ +class InternalWatcher implements Watcher { private final WatchMode watchMode; private final UnaryOperator watcherFilter; private volatile CompletableFuture future = new CompletableFuture<>(); - InternalWatcher(WatchMode watchMode, UnaryOperator watcherFilter) - { + InternalWatcher(WatchMode watchMode, UnaryOperator watcherFilter) { this.watchMode = watchMode; this.watcherFilter = watcherFilter; } - CompletableFuture getFuture() - { + CompletableFuture getFuture() { return future; } @Override - public void process(WatchedEvent event) - { + public void process(WatchedEvent event) { final WatchedEvent localEvent = (watcherFilter != null) ? watcherFilter.apply(event) : event; - switch ( localEvent.getState() ) - { - default: - { - if ( (watchMode != WatchMode.stateChangeOnly) && (localEvent.getType() != Event.EventType.None) ) - { - if ( !future.complete(localEvent) ) - { + switch (localEvent.getState()) { + default: { + if ((watchMode != WatchMode.stateChangeOnly) && (localEvent.getType() != Event.EventType.None)) { + if (!future.complete(localEvent)) { future.obtrudeValue(localEvent); } } @@ -66,23 +58,18 @@ public void process(WatchedEvent event) case Disconnected: case AuthFailed: - case Expired: - { - if ( watchMode != WatchMode.successOnly ) - { - AsyncEventException exception = new AsyncEventException() - { + case Expired: { + if (watchMode != WatchMode.successOnly) { + AsyncEventException exception = new AsyncEventException() { private final AtomicBoolean isReset = new AtomicBoolean(false); @Override - public Event.KeeperState getKeeperState() - { + public Event.KeeperState getKeeperState() { return localEvent.getState(); } @Override - public CompletionStage reset() - { + public CompletionStage reset() { Preconditions.checkState(isReset.compareAndSet(false, true), "Already reset"); future = new CompletableFuture<>(); return future; diff --git a/curator-x-async/src/main/java/org/apache/curator/x/async/migrations/Migration.java b/curator-x-async/src/main/java/org/apache/curator/x/async/migrations/Migration.java index 8cb449af4..af76eb73e 100644 --- a/curator-x-async/src/main/java/org/apache/curator/x/async/migrations/Migration.java +++ b/curator-x-async/src/main/java/org/apache/curator/x/async/migrations/Migration.java @@ -19,15 +19,14 @@ package org.apache.curator.x.async.migrations; -import org.apache.curator.framework.api.transaction.CuratorOp; import java.util.List; +import org.apache.curator.framework.api.transaction.CuratorOp; /** * Models a single migration/transition */ @FunctionalInterface -public interface Migration -{ +public interface Migration { /** * Return the operations to execute in a transaction. IMPORTANT: during a migration * this method may be called multiple times. diff --git a/curator-x-async/src/main/java/org/apache/curator/x/async/migrations/MigrationException.java b/curator-x-async/src/main/java/org/apache/curator/x/async/migrations/MigrationException.java index feac36cda..20c02e9a1 100644 --- a/curator-x-async/src/main/java/org/apache/curator/x/async/migrations/MigrationException.java +++ b/curator-x-async/src/main/java/org/apache/curator/x/async/migrations/MigrationException.java @@ -21,18 +21,15 @@ import java.util.Objects; -public class MigrationException extends RuntimeException -{ +public class MigrationException extends RuntimeException { private final String migrationId; - public MigrationException(String migrationId, String message) - { + public MigrationException(String migrationId, String message) { super(message); this.migrationId = Objects.requireNonNull(migrationId, "migrationId cannot be null"); } - public String getMigrationId() - { + public String getMigrationId() { return migrationId; } } diff --git a/curator-x-async/src/main/java/org/apache/curator/x/async/migrations/MigrationManager.java b/curator-x-async/src/main/java/org/apache/curator/x/async/migrations/MigrationManager.java index 95975b662..a2d5cc288 100644 --- a/curator-x-async/src/main/java/org/apache/curator/x/async/migrations/MigrationManager.java +++ b/curator-x-async/src/main/java/org/apache/curator/x/async/migrations/MigrationManager.java @@ -19,15 +19,9 @@ package org.apache.curator.x.async.migrations; +import static org.apache.curator.x.async.AsyncWrappers.*; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Throwables; -import org.apache.curator.framework.api.transaction.CuratorOp; -import org.apache.curator.framework.imps.ExtractingCuratorOp; -import org.apache.curator.framework.recipes.locks.InterProcessLock; -import org.apache.curator.framework.recipes.locks.InterProcessSemaphoreMutex; -import org.apache.curator.utils.ZKPaths; -import org.apache.curator.x.async.AsyncCuratorFramework; -import org.apache.zookeeper.CreateMode; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.time.Duration; @@ -43,14 +37,18 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Collectors; - -import static org.apache.curator.x.async.AsyncWrappers.*; +import org.apache.curator.framework.api.transaction.CuratorOp; +import org.apache.curator.framework.imps.ExtractingCuratorOp; +import org.apache.curator.framework.recipes.locks.InterProcessLock; +import org.apache.curator.framework.recipes.locks.InterProcessSemaphoreMutex; +import org.apache.curator.utils.ZKPaths; +import org.apache.curator.x.async.AsyncCuratorFramework; +import org.apache.zookeeper.CreateMode; /** * Manages migrations */ -public class MigrationManager -{ +public class MigrationManager { private final AsyncCuratorFramework client; private final String lockPath; private final String metaDataPath; @@ -66,8 +64,8 @@ public class MigrationManager * @param executor the executor to use * @param lockMax max time to wait for locks */ - public MigrationManager(AsyncCuratorFramework client, String lockPath, String metaDataPath, Executor executor, Duration lockMax) - { + public MigrationManager( + AsyncCuratorFramework client, String lockPath, String metaDataPath, Executor executor, Duration lockMax) { this.client = Objects.requireNonNull(client, "client cannot be null"); this.lockPath = Objects.requireNonNull(lockPath, "lockPath cannot be null"); this.metaDataPath = Objects.requireNonNull(metaDataPath, "metaDataPath cannot be null"); @@ -82,8 +80,7 @@ public MigrationManager(AsyncCuratorFramework client, String lockPath, String me * @return completion stage. If there is a migration-specific error, the stage will be completed * exceptionally with {@link org.apache.curator.x.async.migrations.MigrationException}. */ - public CompletionStage migrate(MigrationSet set) - { + public CompletionStage migrate(MigrationSet set) { InterProcessLock lock = new InterProcessSemaphoreMutex(client.unwrap(), ZKPaths.makePath(lockPath, set.id())); CompletionStage lockStage = lockAsync(lock, lockMax.toMillis(), TimeUnit.MILLISECONDS, executor); return lockStage.thenCompose(__ -> runMigrationInLock(lock, set)); @@ -99,101 +96,82 @@ public CompletionStage migrate(MigrationSet set) * @return the list of actual migrations to perform. The filter can return any value here or an empty list. * @throws MigrationException errors */ - protected List filter(MigrationSet set, List operationHashesInOrder) throws MigrationException - { - if ( operationHashesInOrder.size() > set.migrations().size() ) - { - throw new MigrationException(set.id(), String.format("More metadata than migrations. Migration ID: %s", set.id())); + protected List filter(MigrationSet set, List operationHashesInOrder) throws MigrationException { + if (operationHashesInOrder.size() > set.migrations().size()) { + throw new MigrationException( + set.id(), String.format("More metadata than migrations. Migration ID: %s", set.id())); } int compareSize = Math.min(set.migrations().size(), operationHashesInOrder.size()); - for ( int i = 0; i < compareSize; ++i ) - { + for (int i = 0; i < compareSize; ++i) { byte[] setHash = hash(set.migrations().get(i).operations()); - if ( !Arrays.equals(setHash, operationHashesInOrder.get(i)) ) - { + if (!Arrays.equals(setHash, operationHashesInOrder.get(i))) { throw new MigrationException(set.id(), String.format("Metadata mismatch. Migration ID: %s", set.id())); } } - return set.migrations().subList(operationHashesInOrder.size(), set.migrations().size()); + return set.migrations() + .subList(operationHashesInOrder.size(), set.migrations().size()); } - private byte[] hash(List operations) - { + private byte[] hash(List operations) { MessageDigest digest; - try - { + try { digest = MessageDigest.getInstance("SHA-256"); - } - catch ( NoSuchAlgorithmException e ) - { + } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } operations.forEach(op -> { - if ( op instanceof ExtractingCuratorOp ) - { - ((ExtractingCuratorOp)op).addToDigest(digest); - } - else - { + if (op instanceof ExtractingCuratorOp) { + ((ExtractingCuratorOp) op).addToDigest(digest); + } else { digest.update(op.toString().getBytes()); } }); return digest.digest(); } - private CompletionStage runMigrationInLock(InterProcessLock lock, MigrationSet set) - { + private CompletionStage runMigrationInLock(InterProcessLock lock, MigrationSet set) { String thisMetaDataPath = ZKPaths.makePath(metaDataPath, set.id()); return childrenWithData(client, thisMetaDataPath) - .thenCompose(metaData -> applyMetaData(set, metaData, thisMetaDataPath)) - .handle((v, e) -> { - release(lock, true); - if ( e != null ) - { - Throwables.propagate(e); - } - return v; - } - ); + .thenCompose(metaData -> applyMetaData(set, metaData, thisMetaDataPath)) + .handle((v, e) -> { + release(lock, true); + if (e != null) { + Throwables.propagate(e); + } + return v; + }); } - private CompletionStage applyMetaData(MigrationSet set, Map metaData, String thisMetaDataPath) - { - List sortedMetaData = metaData.keySet() - .stream() - .sorted(Comparator.naturalOrder()) - .map(metaData::get) - .collect(Collectors.toList()); + private CompletionStage applyMetaData( + MigrationSet set, Map metaData, String thisMetaDataPath) { + List sortedMetaData = metaData.keySet().stream() + .sorted(Comparator.naturalOrder()) + .map(metaData::get) + .collect(Collectors.toList()); List toBeApplied; - try - { + try { toBeApplied = filter(set, sortedMetaData); - } - catch ( MigrationException e ) - { + } catch (MigrationException e) { CompletableFuture future = new CompletableFuture<>(); future.completeExceptionally(e); return future; } - if ( toBeApplied.size() == 0 ) - { + if (toBeApplied.size() == 0) { return CompletableFuture.completedFuture(null); } return asyncEnsureContainers(client, thisMetaDataPath) - .thenCompose(__ -> applyMetaDataAfterEnsure(toBeApplied, thisMetaDataPath)); + .thenCompose(__ -> applyMetaDataAfterEnsure(toBeApplied, thisMetaDataPath)); } @VisibleForTesting volatile AtomicInteger debugCount = null; - private CompletionStage applyMetaDataAfterEnsure(List toBeApplied, String thisMetaDataPath) - { - if ( debugCount != null ) - { + private CompletionStage applyMetaDataAfterEnsure(List toBeApplied, String thisMetaDataPath) { + if (debugCount != null) { debugCount.incrementAndGet(); } @@ -202,7 +180,10 @@ private CompletionStage applyMetaDataAfterEnsure(List toBeAppli toBeApplied.forEach(migration -> { List thisMigrationOperations = migration.operations(); operations.addAll(thisMigrationOperations); - operations.add(client.transactionOp().create().withMode(CreateMode.PERSISTENT_SEQUENTIAL).forPath(metaDataBasePath, hash(thisMigrationOperations))); + operations.add(client.transactionOp() + .create() + .withMode(CreateMode.PERSISTENT_SEQUENTIAL) + .forPath(metaDataBasePath, hash(thisMigrationOperations))); }); return client.transaction().forOperations(operations).thenApply(__ -> null); } diff --git a/curator-x-async/src/main/java/org/apache/curator/x/async/migrations/MigrationSet.java b/curator-x-async/src/main/java/org/apache/curator/x/async/migrations/MigrationSet.java index 35bac9e9d..a024f18e2 100644 --- a/curator-x-async/src/main/java/org/apache/curator/x/async/migrations/MigrationSet.java +++ b/curator-x-async/src/main/java/org/apache/curator/x/async/migrations/MigrationSet.java @@ -27,8 +27,7 @@ * Models a set of migrations. Each individual migration is applied * in a transaction. */ -public interface MigrationSet -{ +public interface MigrationSet { /** * @return the unique ID for this migration set */ @@ -39,21 +38,17 @@ public interface MigrationSet */ List migrations(); - static MigrationSet build(String id, List migrations) - { + static MigrationSet build(String id, List migrations) { Objects.requireNonNull(id, "id cannot be null"); final List migrationsCopy = ImmutableList.copyOf(migrations); - return new MigrationSet() - { + return new MigrationSet() { @Override - public String id() - { + public String id() { return id; } @Override - public List migrations() - { + public List migrations() { return migrationsCopy; } }; diff --git a/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/JacksonModelSerializer.java b/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/JacksonModelSerializer.java index c2497c863..1e07cf26d 100644 --- a/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/JacksonModelSerializer.java +++ b/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/JacksonModelSerializer.java @@ -36,89 +36,71 @@ * file to avoid adding a new dependency to Curator. Therefore, if you wish to use the * JacksonModelSerializer you must manually add the dependency to your build system */ -public class JacksonModelSerializer implements ModelSerializer -{ +public class JacksonModelSerializer implements ModelSerializer { private static final ObjectMapper mapper = new ObjectMapper(); - static - { + + static { mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); } private final ObjectReader reader; private final ObjectWriter writer; - public static JacksonModelSerializer build(Class modelClass) - { + public static JacksonModelSerializer build(Class modelClass) { return new JacksonModelSerializer<>(modelClass); } - public static JacksonModelSerializer build(JavaType type) - { + public static JacksonModelSerializer build(JavaType type) { return new JacksonModelSerializer<>(type); } - public static JacksonModelSerializer build(TypeReference type) - { + public static JacksonModelSerializer build(TypeReference type) { return new JacksonModelSerializer<>(type); } - public JacksonModelSerializer(Class modelClass) - { + public JacksonModelSerializer(Class modelClass) { this(mapper.getTypeFactory().constructType(modelClass)); } - public JacksonModelSerializer(JavaType type) - { + public JacksonModelSerializer(JavaType type) { reader = mapper.readerFor(type); writer = mapper.writerFor(type); } - public JacksonModelSerializer(TypeReference type) - { + public JacksonModelSerializer(TypeReference type) { reader = mapper.readerFor(type); writer = mapper.writerFor(type); } - public JacksonModelSerializer(ObjectMapper mapper, JavaType type) - { + public JacksonModelSerializer(ObjectMapper mapper, JavaType type) { reader = mapper.readerFor(type); writer = mapper.writerFor(type); } - public JacksonModelSerializer(ObjectMapper mapper, TypeReference type) - { + public JacksonModelSerializer(ObjectMapper mapper, TypeReference type) { reader = mapper.readerFor(type); writer = mapper.writerFor(type); } - public JacksonModelSerializer(ObjectReader reader, ObjectWriter writer) - { + public JacksonModelSerializer(ObjectReader reader, ObjectWriter writer) { this.reader = Objects.requireNonNull(reader, "reader cannot be null"); this.writer = Objects.requireNonNull(writer, "writer cannot be null"); } @Override - public byte[] serialize(T model) - { - try - { + public byte[] serialize(T model) { + try { return writer.writeValueAsBytes(model); - } - catch ( JsonProcessingException e ) - { + } catch (JsonProcessingException e) { throw new RuntimeException(String.format("Could not serialize value: %s", model), e); } } @Override - public T deserialize(byte[] bytes) - { - try - { + public T deserialize(byte[] bytes) { + try { return reader.readValue(bytes); - } - catch ( IOException e ) - { + } catch (IOException e) { throw new RuntimeException(String.format("Could not deserialize value: %s", Arrays.toString(bytes)), e); } } diff --git a/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/ModelSerializer.java b/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/ModelSerializer.java index 679429df7..cfbaf25e8 100644 --- a/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/ModelSerializer.java +++ b/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/ModelSerializer.java @@ -22,8 +22,7 @@ /** * Serializing interface for models */ -public interface ModelSerializer -{ +public interface ModelSerializer { /** * Given a model return the serialized bytes * @@ -45,17 +44,14 @@ public interface ModelSerializer /** * A pass through serializer */ - ModelSerializer raw = new ModelSerializer() - { + ModelSerializer raw = new ModelSerializer() { @Override - public byte[] serialize(byte[] model) - { + public byte[] serialize(byte[] model) { return model; } @Override - public byte[] deserialize(byte[] bytes) - { + public byte[] deserialize(byte[] bytes) { return bytes; } }; diff --git a/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/ModelSpec.java b/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/ModelSpec.java index b70e35151..5185a8249 100644 --- a/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/ModelSpec.java +++ b/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/ModelSpec.java @@ -20,13 +20,13 @@ package org.apache.curator.x.async.modeled; import com.google.common.collect.ImmutableSet; +import java.util.List; +import java.util.Set; import org.apache.curator.framework.schema.Schema; import org.apache.curator.x.async.api.CreateOption; import org.apache.curator.x.async.api.DeleteOption; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.data.ACL; -import java.util.List; -import java.util.Set; /** * A full specification for dealing with a portion of the ZooKeeper tree. ModelSpec's contain: @@ -40,9 +40,9 @@ *

  • Optional schema generation
  • * */ -public interface ModelSpec extends Resolvable -{ - Set defaultCreateOptions = ImmutableSet.of(CreateOption.createParentsAsContainers, CreateOption.setDataIfExists); +public interface ModelSpec extends Resolvable { + Set defaultCreateOptions = + ImmutableSet.of(CreateOption.createParentsAsContainers, CreateOption.setDataIfExists); Set defaultDeleteOptions = ImmutableSet.of(DeleteOption.guaranteed); /** @@ -54,11 +54,10 @@ public interface ModelSpec extends Resolvable * @param serializer the model's serializer * @return builder */ - static ModelSpecBuilder builder(ZPath path, ModelSerializer serializer) - { + static ModelSpecBuilder builder(ZPath path, ModelSerializer serializer) { return new ModelSpecBuilder<>(path, serializer) - .withCreateOptions(defaultCreateOptions) - .withDeleteOptions(defaultDeleteOptions); + .withCreateOptions(defaultCreateOptions) + .withDeleteOptions(defaultDeleteOptions); } /** @@ -69,11 +68,10 @@ static ModelSpecBuilder builder(ZPath path, ModelSerializer serializer * @param serializer the model's serializer * @return builder */ - static ModelSpecBuilder builder(ModelSerializer serializer) - { + static ModelSpecBuilder builder(ModelSerializer serializer) { return new ModelSpecBuilder<>(serializer) - .withCreateOptions(defaultCreateOptions) - .withDeleteOptions(defaultDeleteOptions); + .withCreateOptions(defaultCreateOptions) + .withDeleteOptions(defaultDeleteOptions); } /** diff --git a/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/ModelSpecBuilder.java b/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/ModelSpecBuilder.java index 5643aa376..41a9fe8b7 100644 --- a/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/ModelSpecBuilder.java +++ b/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/ModelSpecBuilder.java @@ -20,18 +20,17 @@ package org.apache.curator.x.async.modeled; import com.google.common.collect.ImmutableSet; +import java.util.Collections; +import java.util.List; +import java.util.Objects; +import java.util.Set; import org.apache.curator.x.async.api.CreateOption; import org.apache.curator.x.async.api.DeleteOption; import org.apache.curator.x.async.modeled.details.ModelSpecImpl; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.data.ACL; -import java.util.Collections; -import java.util.List; -import java.util.Objects; -import java.util.Set; -public class ModelSpecBuilder -{ +public class ModelSpecBuilder { private final ModelSerializer serializer; private ZPath path; private CreateMode createMode = CreateMode.PERSISTENT; @@ -45,8 +44,7 @@ public class ModelSpecBuilder * * @return new ModelSpec instance */ - public ModelSpec build() - { + public ModelSpec build() { return new ModelSpecImpl<>(path, serializer, createMode, aclList, createOptions, deleteOptions, ttl); } @@ -56,8 +54,7 @@ public ModelSpec build() * @param createMode create mode * @return this for chaining */ - public ModelSpecBuilder withCreateMode(CreateMode createMode) - { + public ModelSpecBuilder withCreateMode(CreateMode createMode) { this.createMode = createMode; return this; } @@ -72,8 +69,7 @@ public ModelSpecBuilder withCreateMode(CreateMode createMode) * @param ttl the ttl * @return this for chaining */ - public ModelSpecBuilder withTtl(long ttl) - { + public ModelSpecBuilder withTtl(long ttl) { this.ttl = ttl; return this; } @@ -84,8 +80,7 @@ public ModelSpecBuilder withTtl(long ttl) * @param aclList ACLs * @return this for chaining */ - public ModelSpecBuilder withAclList(List aclList) - { + public ModelSpecBuilder withAclList(List aclList) { this.aclList = aclList; return this; } @@ -96,8 +91,7 @@ public ModelSpecBuilder withAclList(List aclList) * @param createOptions options * @return this for chaining */ - public ModelSpecBuilder withCreateOptions(Set createOptions) - { + public ModelSpecBuilder withCreateOptions(Set createOptions) { this.createOptions = (createOptions != null) ? ImmutableSet.copyOf(createOptions) : null; return this; } @@ -108,8 +102,7 @@ public ModelSpecBuilder withCreateOptions(Set createOptions) * @param deleteOptions options * @return this for chaining */ - public ModelSpecBuilder withDeleteOptions(Set deleteOptions) - { + public ModelSpecBuilder withDeleteOptions(Set deleteOptions) { this.deleteOptions = (deleteOptions != null) ? ImmutableSet.copyOf(deleteOptions) : null; return this; } @@ -120,19 +113,16 @@ public ModelSpecBuilder withDeleteOptions(Set deleteOptions) * @param path new path * @return this for chaining */ - public ModelSpecBuilder withPath(ZPath path) - { + public ModelSpecBuilder withPath(ZPath path) { this.path = Objects.requireNonNull(path, "path cannot be null"); return this; } - ModelSpecBuilder(ModelSerializer serializer) - { + ModelSpecBuilder(ModelSerializer serializer) { this.serializer = Objects.requireNonNull(serializer, "serializer cannot be null"); } - ModelSpecBuilder(ZPath path, ModelSerializer serializer) - { + ModelSpecBuilder(ZPath path, ModelSerializer serializer) { this.path = Objects.requireNonNull(path, "path cannot be null"); this.serializer = Objects.requireNonNull(serializer, "serializer cannot be null"); } diff --git a/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/ModeledFramework.java b/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/ModeledFramework.java index 413dc1a6f..9a5285677 100644 --- a/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/ModeledFramework.java +++ b/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/ModeledFramework.java @@ -19,6 +19,8 @@ package org.apache.curator.x.async.modeled; +import java.util.List; +import java.util.concurrent.ExecutorService; import org.apache.curator.framework.api.transaction.CuratorOp; import org.apache.curator.framework.api.transaction.CuratorTransactionResult; import org.apache.curator.x.async.AsyncCuratorFramework; @@ -26,11 +28,8 @@ import org.apache.curator.x.async.modeled.cached.CachedModeledFramework; import org.apache.curator.x.async.modeled.versioned.VersionedModeledFramework; import org.apache.zookeeper.data.Stat; -import java.util.List; -import java.util.concurrent.ExecutorService; -public interface ModeledFramework -{ +public interface ModeledFramework { /** * Return a new ModeledFramework for the given model * @@ -38,8 +37,7 @@ public interface ModeledFramework * @param model the model * @return new Modeled Curator instance */ - static ModeledFramework wrap(AsyncCuratorFramework client, ModelSpec model) - { + static ModeledFramework wrap(AsyncCuratorFramework client, ModelSpec model) { return builder(client, model).build(); } @@ -50,8 +48,7 @@ static ModeledFramework wrap(AsyncCuratorFramework client, ModelSpec m * @param model the model * @return builder */ - static ModeledFrameworkBuilder builder(AsyncCuratorFramework client, ModelSpec model) - { + static ModeledFrameworkBuilder builder(AsyncCuratorFramework client, ModelSpec model) { return new ModeledFrameworkBuilder<>(client, model); } @@ -62,8 +59,7 @@ static ModeledFrameworkBuilder builder(AsyncCuratorFramework client, Mode * * @return builder */ - static ModeledFrameworkBuilder builder() - { + static ModeledFrameworkBuilder builder() { return new ModeledFrameworkBuilder<>(); } diff --git a/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/ModeledFrameworkBuilder.java b/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/ModeledFrameworkBuilder.java index c1a00b644..683d49308 100644 --- a/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/ModeledFrameworkBuilder.java +++ b/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/ModeledFrameworkBuilder.java @@ -20,19 +20,18 @@ package org.apache.curator.x.async.modeled; import com.google.common.collect.ImmutableSet; +import java.util.Collections; +import java.util.Objects; +import java.util.Set; +import java.util.function.UnaryOperator; import org.apache.curator.framework.api.CuratorEvent; import org.apache.curator.framework.api.UnhandledErrorListener; import org.apache.curator.x.async.AsyncCuratorFramework; import org.apache.curator.x.async.WatchMode; import org.apache.curator.x.async.modeled.details.ModeledFrameworkImpl; import org.apache.zookeeper.WatchedEvent; -import java.util.Collections; -import java.util.Objects; -import java.util.Set; -import java.util.function.UnaryOperator; -public class ModeledFrameworkBuilder -{ +public class ModeledFrameworkBuilder { private AsyncCuratorFramework client; private ModelSpec modelSpec; private WatchMode watchMode; @@ -46,17 +45,9 @@ public class ModeledFrameworkBuilder * * @return new ModeledFramework instance */ - public ModeledFramework build() - { + public ModeledFramework build() { return ModeledFrameworkImpl.build( - client, - modelSpec, - watchMode, - watcherFilter, - unhandledErrorListener, - resultFilter, - modeledOptions - ); + client, modelSpec, watchMode, watcherFilter, unhandledErrorListener, resultFilter, modeledOptions); } /** @@ -66,8 +57,7 @@ public ModeledFramework build() * @return this for chaining * @see org.apache.curator.x.async.AsyncStage#event() */ - public ModeledFrameworkBuilder watched() - { + public ModeledFrameworkBuilder watched() { this.watchMode = WatchMode.stateChangeAndSuccess; return this; } @@ -79,8 +69,7 @@ public ModeledFrameworkBuilder watched() * @return this for chaining * @see org.apache.curator.x.async.AsyncStage#event() */ - public ModeledFrameworkBuilder watched(WatchMode watchMode) - { + public ModeledFrameworkBuilder watched(WatchMode watchMode) { this.watchMode = watchMode; return this; } @@ -93,8 +82,7 @@ public ModeledFrameworkBuilder watched(WatchMode watchMode) * @return this for chaining * @see org.apache.curator.x.async.AsyncStage#event() */ - public ModeledFrameworkBuilder watched(WatchMode watchMode, UnaryOperator watcherFilter) - { + public ModeledFrameworkBuilder watched(WatchMode watchMode, UnaryOperator watcherFilter) { this.watchMode = watchMode; this.watcherFilter = watcherFilter; return this; @@ -106,8 +94,7 @@ public ModeledFrameworkBuilder watched(WatchMode watchMode, UnaryOperator withUnhandledErrorListener(UnhandledErrorListener unhandledErrorListener) - { + public ModeledFrameworkBuilder withUnhandledErrorListener(UnhandledErrorListener unhandledErrorListener) { this.unhandledErrorListener = unhandledErrorListener; return this; } @@ -118,8 +105,7 @@ public ModeledFrameworkBuilder withUnhandledErrorListener(UnhandledErrorListe * @param resultFilter filter * @return this for chaining */ - public ModeledFrameworkBuilder withResultFilter(UnaryOperator resultFilter) - { + public ModeledFrameworkBuilder withResultFilter(UnaryOperator resultFilter) { this.resultFilter = resultFilter; return this; } @@ -130,8 +116,7 @@ public ModeledFrameworkBuilder withResultFilter(UnaryOperator r * @param modelSpec model spec * @return this for chaining */ - public ModeledFrameworkBuilder withModelSpec(ModelSpec modelSpec) - { + public ModeledFrameworkBuilder withModelSpec(ModelSpec modelSpec) { this.modelSpec = Objects.requireNonNull(modelSpec, "modelSpec cannot be null"); return this; } @@ -142,8 +127,7 @@ public ModeledFrameworkBuilder withModelSpec(ModelSpec modelSpec) * @param client new client * @return this for chaining */ - public ModeledFrameworkBuilder withClient(AsyncCuratorFramework client) - { + public ModeledFrameworkBuilder withClient(AsyncCuratorFramework client) { this.client = Objects.requireNonNull(client, "client cannot be null"); return this; } @@ -154,19 +138,16 @@ public ModeledFrameworkBuilder withClient(AsyncCuratorFramework client) * @param modeledOptions new options set * @return this for chaining */ - public ModeledFrameworkBuilder withOptions(Set modeledOptions) - { + public ModeledFrameworkBuilder withOptions(Set modeledOptions) { this.modeledOptions = ImmutableSet.copyOf(Objects.requireNonNull(modeledOptions, "client cannot be null")); return this; } - ModeledFrameworkBuilder() - { + ModeledFrameworkBuilder() { modeledOptions = Collections.singleton(ModeledOptions.ignoreMissingNodesForChildren); } - ModeledFrameworkBuilder(AsyncCuratorFramework client, ModelSpec modelSpec) - { + ModeledFrameworkBuilder(AsyncCuratorFramework client, ModelSpec modelSpec) { this.client = Objects.requireNonNull(client, "client cannot be null"); this.modelSpec = Objects.requireNonNull(modelSpec, "modelSpec cannot be null"); modeledOptions = Collections.singleton(ModeledOptions.ignoreMissingNodesForChildren); diff --git a/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/ModeledOptions.java b/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/ModeledOptions.java index e68821bfd..dafa5d6ab 100644 --- a/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/ModeledOptions.java +++ b/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/ModeledOptions.java @@ -19,8 +19,7 @@ package org.apache.curator.x.async.modeled; -public enum ModeledOptions -{ +public enum ModeledOptions { /** * Causes {@link ModeledFramework#children()} and {@link ModeledFramework#childrenAsZNodes()} * to ignore {@link org.apache.zookeeper.KeeperException.NoNodeException} and merely return diff --git a/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/NodeName.java b/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/NodeName.java index 5e0bbd927..465e8f592 100644 --- a/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/NodeName.java +++ b/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/NodeName.java @@ -25,15 +25,12 @@ * the {@link #nodeName()} method is used instead of calling toString() */ @FunctionalInterface -public interface NodeName -{ +public interface NodeName { String nodeName(); - static String nameFrom(Object obj) - { - if ( obj instanceof NodeName ) - { - return ((NodeName)obj).nodeName(); + static String nameFrom(Object obj) { + if (obj instanceof NodeName) { + return ((NodeName) obj).nodeName(); } return String.valueOf(obj); } diff --git a/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/Resolvable.java b/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/Resolvable.java index afb935a28..0b746f1b4 100644 --- a/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/Resolvable.java +++ b/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/Resolvable.java @@ -22,8 +22,7 @@ import java.util.Arrays; import java.util.List; -public interface Resolvable -{ +public interface Resolvable { /** * When creating paths, any node in the path can be set to {@link ZPath#parameter()}. * At runtime, the ZPath can be "resolved" by replacing these nodes with values. @@ -32,8 +31,7 @@ public interface Resolvable * parameter nodes in the path * @return new resolved ZPath */ - default Object resolved(Object... parameters) - { + default Object resolved(Object... parameters) { return resolved(Arrays.asList(parameters)); } diff --git a/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/ZNode.java b/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/ZNode.java index 956e5e128..c7dd80f2b 100644 --- a/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/ZNode.java +++ b/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/ZNode.java @@ -19,17 +19,16 @@ package org.apache.curator.x.async.modeled; -import org.apache.curator.x.async.AsyncStage; -import org.apache.zookeeper.data.Stat; import java.util.List; import java.util.concurrent.CompletionStage; import java.util.stream.Collectors; +import org.apache.curator.x.async.AsyncStage; +import org.apache.zookeeper.data.Stat; /** * Abstracts a ZooKeeper node */ -public interface ZNode -{ +public interface ZNode { /** * The path of the node * @@ -57,8 +56,7 @@ public interface ZNode * @param from original stage * @return stage of models */ - static CompletionStage> models(AsyncStage>> from) - { + static CompletionStage> models(AsyncStage>> from) { return from.thenApply(nodes -> nodes.stream().map(ZNode::model).collect(Collectors.toList())); } @@ -68,8 +66,7 @@ static CompletionStage> models(AsyncStage>> from) * @param from original stage * @return stage of a model */ - static CompletionStage model(AsyncStage> from) - { + static CompletionStage model(AsyncStage> from) { return from.thenApply(ZNode::model); } } diff --git a/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/ZPath.java b/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/ZPath.java index f612d94e4..024622525 100644 --- a/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/ZPath.java +++ b/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/ZPath.java @@ -19,19 +19,17 @@ package org.apache.curator.x.async.modeled; -import org.apache.curator.x.async.modeled.details.ZPathImpl; +import static org.apache.curator.utils.ZKPaths.PATH_SEPARATOR; import java.util.Arrays; import java.util.List; import java.util.function.UnaryOperator; import java.util.regex.Pattern; - -import static org.apache.curator.utils.ZKPaths.PATH_SEPARATOR; +import org.apache.curator.x.async.modeled.details.ZPathImpl; /** * Abstracts a ZooKeeper ZNode path */ -public interface ZPath extends Resolvable -{ +public interface ZPath extends Resolvable { /** * The root path: "/" */ @@ -41,8 +39,7 @@ public interface ZPath extends Resolvable * Returns the special node name that can be used for replacements at runtime * via {@link #resolved(Object...)} when passed via the various from() methods */ - static String parameter() - { + static String parameter() { return parameter("id"); } @@ -51,8 +48,7 @@ static String parameter() * has no effect and is only for debugging purposes. When toString() is called * on ZPaths, this code shows. */ - static String parameter(String name) - { + static String parameter(String name) { return PATH_SEPARATOR + "{" + name + "}"; } @@ -66,8 +62,7 @@ static String parameter(String name) * @return ZPath * @throws IllegalArgumentException if the path is invalid */ - static ZPath parse(String fullPath) - { + static ZPath parse(String fullPath) { return ZPathImpl.parse(fullPath, s -> s); } @@ -81,8 +76,7 @@ static ZPath parse(String fullPath) * @return ZPath * @throws IllegalArgumentException if the path is invalid */ - static ZPath parseWithIds(String fullPath) - { + static ZPath parseWithIds(String fullPath) { return ZPathImpl.parse(fullPath, s -> isId(s) ? (PATH_SEPARATOR + s) : s); } @@ -92,8 +86,7 @@ static ZPath parseWithIds(String fullPath) * @param s string to check * @return true/false */ - static boolean isId(String s) - { + static boolean isId(String s) { return s.startsWith("{") && s.endsWith("}"); } @@ -105,8 +98,7 @@ static boolean isId(String s) * @return ZPath * @throws IllegalArgumentException if the path is invalid */ - static ZPath parse(String fullPath, UnaryOperator nameFilter) - { + static ZPath parse(String fullPath, UnaryOperator nameFilter) { return ZPathImpl.parse(fullPath, nameFilter); } @@ -120,8 +112,7 @@ static ZPath parse(String fullPath, UnaryOperator nameFilter) * @return ZPath * @throws IllegalArgumentException if any of the names is invalid */ - static ZPath from(String... names) - { + static ZPath from(String... names) { return ZPathImpl.from(names); } @@ -134,8 +125,7 @@ static ZPath from(String... names) * @return ZPath * @throws IllegalArgumentException if any of the names is invalid */ - static ZPath from(List names) - { + static ZPath from(List names) { return ZPathImpl.from(names); } @@ -151,8 +141,7 @@ static ZPath from(List names) * @return ZPath * @throws IllegalArgumentException if any of the names is invalid */ - static ZPath from(ZPath base, String... names) - { + static ZPath from(ZPath base, String... names) { return ZPathImpl.from(base, names); } @@ -166,8 +155,7 @@ static ZPath from(ZPath base, String... names) * @return ZPath * @throws IllegalArgumentException if any of the names is invalid */ - static ZPath from(ZPath base, List names) - { + static ZPath from(ZPath base, List names) { return ZPathImpl.from(base, names); } @@ -188,8 +176,7 @@ static ZPath from(ZPath base, List names) * @return new resolved ZPath */ @Override - default ZPath resolved(Object... parameters) - { + default ZPath resolved(Object... parameters) { return resolved(Arrays.asList(parameters)); } diff --git a/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/cached/CachedModeledFramework.java b/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/cached/CachedModeledFramework.java index c22336095..ede671df8 100644 --- a/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/cached/CachedModeledFramework.java +++ b/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/cached/CachedModeledFramework.java @@ -19,17 +19,16 @@ package org.apache.curator.x.async.modeled.cached; +import java.io.Closeable; +import java.util.List; import org.apache.curator.framework.listen.Listenable; import org.apache.curator.x.async.AsyncStage; import org.apache.curator.x.async.modeled.ModeledFramework; import org.apache.curator.x.async.modeled.ZNode; import org.apache.curator.x.async.modeled.ZPath; import org.apache.zookeeper.data.Stat; -import java.io.Closeable; -import java.util.List; -public interface CachedModeledFramework extends ModeledFramework, Closeable -{ +public interface CachedModeledFramework extends ModeledFramework, Closeable { /** * Return the cache instance * diff --git a/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/cached/ModeledCache.java b/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/cached/ModeledCache.java index 4784ee0a9..afd7b09d1 100644 --- a/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/cached/ModeledCache.java +++ b/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/cached/ModeledCache.java @@ -19,13 +19,12 @@ package org.apache.curator.x.async.modeled.cached; -import org.apache.curator.x.async.modeled.ZNode; -import org.apache.curator.x.async.modeled.ZPath; import java.util.Map; import java.util.Optional; +import org.apache.curator.x.async.modeled.ZNode; +import org.apache.curator.x.async.modeled.ZPath; -public interface ModeledCache -{ +public interface ModeledCache { /** * Return the modeled current data for the given path. There are no guarantees of accuracy. This is * merely the most recent view of the data. If there is no node at the given path, diff --git a/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/cached/ModeledCacheListener.java b/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/cached/ModeledCacheListener.java index 52a6a098b..9c30da088 100644 --- a/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/cached/ModeledCacheListener.java +++ b/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/cached/ModeledCacheListener.java @@ -24,10 +24,8 @@ import org.slf4j.LoggerFactory; @FunctionalInterface -public interface ModeledCacheListener -{ - enum Type - { +public interface ModeledCacheListener { + enum Type { /** * A child was added to the path */ @@ -57,8 +55,7 @@ enum Type /** * The cache has finished initializing */ - default void initialized() - { + default void initialized() { // NOP } @@ -68,8 +65,7 @@ default void initialized() * * @param e the exception */ - default void handleException(Exception e) - { + default void handleException(Exception e) { LoggerFactory.getLogger(getClass()).error("Could not process cache message", e); } @@ -81,24 +77,19 @@ default void handleException(Exception e) * * @return wrapped listener */ - default ModeledCacheListener postInitializedOnly() - { - return new ModeledCacheListener() - { + default ModeledCacheListener postInitializedOnly() { + return new ModeledCacheListener() { private volatile boolean isInitialized = false; @Override - public void accept(Type type, ZPath path, Stat stat, T model) - { - if ( isInitialized ) - { + public void accept(Type type, ZPath path, Stat stat, T model) { + if (isInitialized) { ModeledCacheListener.this.accept(type, path, stat, model); } } @Override - public void initialized() - { + public void initialized() { isInitialized = true; ModeledCacheListener.this.initialized(); } diff --git a/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/details/CachedModeledFrameworkImpl.java b/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/details/CachedModeledFrameworkImpl.java index 3868cb510..acccbfecf 100644 --- a/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/details/CachedModeledFrameworkImpl.java +++ b/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/details/CachedModeledFrameworkImpl.java @@ -19,6 +19,14 @@ package org.apache.curator.x.async.modeled.details; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.Executor; +import java.util.concurrent.ExecutorService; +import java.util.function.Function; +import java.util.function.Supplier; +import java.util.stream.Collectors; import org.apache.curator.framework.api.transaction.CuratorOp; import org.apache.curator.framework.api.transaction.CuratorTransactionResult; import org.apache.curator.framework.listen.Listenable; @@ -35,301 +43,246 @@ import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.data.Stat; import org.apache.zookeeper.server.DataTree; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.concurrent.Executor; -import java.util.concurrent.ExecutorService; -import java.util.function.Function; -import java.util.function.Supplier; -import java.util.stream.Collectors; -class CachedModeledFrameworkImpl implements CachedModeledFramework -{ +class CachedModeledFrameworkImpl implements CachedModeledFramework { private final ModeledFramework client; private final ModeledCacheImpl cache; private final Executor executor; - CachedModeledFrameworkImpl(ModeledFramework client, ExecutorService executor) - { + CachedModeledFrameworkImpl(ModeledFramework client, ExecutorService executor) { this(client, new ModeledCacheImpl<>(client.unwrap().unwrap(), client.modelSpec(), executor), executor); } - private CachedModeledFrameworkImpl(ModeledFramework client, ModeledCacheImpl cache, Executor executor) - { + private CachedModeledFrameworkImpl(ModeledFramework client, ModeledCacheImpl cache, Executor executor) { this.client = client; this.cache = cache; this.executor = executor; } @Override - public ModeledCache cache() - { + public ModeledCache cache() { return cache; } @Override - public void start() - { + public void start() { cache.start(); } @Override - public void close() - { + public void close() { cache.close(); } @Override - public Listenable> listenable() - { + public Listenable> listenable() { return cache.listenable(); } @Override - public CachedModeledFramework cached() - { + public CachedModeledFramework cached() { throw new UnsupportedOperationException("Already a cached instance"); } @Override - public CachedModeledFramework cached(ExecutorService executor) - { + public CachedModeledFramework cached(ExecutorService executor) { throw new UnsupportedOperationException("Already a cached instance"); } @Override - public VersionedModeledFramework versioned() - { + public VersionedModeledFramework versioned() { return new VersionedModeledFrameworkImpl<>(this); } @Override - public AsyncCuratorFramework unwrap() - { + public AsyncCuratorFramework unwrap() { return client.unwrap(); } @Override - public ModelSpec modelSpec() - { + public ModelSpec modelSpec() { return client.modelSpec(); } @Override - public CachedModeledFramework child(Object child) - { + public CachedModeledFramework child(Object child) { return new CachedModeledFrameworkImpl<>(client.child(child), cache, executor); } @Override - public ModeledFramework parent() - { - throw new UnsupportedOperationException("Not supported for CachedModeledFramework. Instead, call parent() on the ModeledFramework before calling cached()"); + public ModeledFramework parent() { + throw new UnsupportedOperationException( + "Not supported for CachedModeledFramework. Instead, call parent() on the ModeledFramework before calling cached()"); } @Override - public CachedModeledFramework withPath(ZPath path) - { + public CachedModeledFramework withPath(ZPath path) { return new CachedModeledFrameworkImpl<>(client.withPath(path), cache, executor); } @Override - public AsyncStage set(T model) - { + public AsyncStage set(T model) { return client.set(model); } @Override - public AsyncStage set(T model, Stat storingStatIn) - { + public AsyncStage set(T model, Stat storingStatIn) { return client.set(model, storingStatIn); } @Override - public AsyncStage set(T model, Stat storingStatIn, int version) - { + public AsyncStage set(T model, Stat storingStatIn, int version) { return client.set(model, storingStatIn, version); } @Override - public AsyncStage set(T model, int version) - { + public AsyncStage set(T model, int version) { return client.set(model, version); } @Override - public AsyncStage read() - { + public AsyncStage read() { return internalRead(ZNode::model, this::exceptionally); } @Override - public AsyncStage read(Stat storingStatIn) - { - return internalRead(n -> { - if ( storingStatIn != null ) - { - DataTree.copyStat(n.stat(), storingStatIn); - } - return n.model(); - }, this::exceptionally); + public AsyncStage read(Stat storingStatIn) { + return internalRead( + n -> { + if (storingStatIn != null) { + DataTree.copyStat(n.stat(), storingStatIn); + } + return n.model(); + }, + this::exceptionally); } @Override - public AsyncStage> readAsZNode() - { + public AsyncStage> readAsZNode() { return internalRead(Function.identity(), this::exceptionally); } @Override - public AsyncStage readThrough() - { + public AsyncStage readThrough() { return internalRead(ZNode::model, client::read); } @Override - public AsyncStage readThrough(Stat storingStatIn) - { + public AsyncStage readThrough(Stat storingStatIn) { return internalRead(ZNode::model, () -> client.read(storingStatIn)); } @Override - public AsyncStage> readThroughAsZNode() - { + public AsyncStage> readThroughAsZNode() { return internalRead(Function.identity(), client::readAsZNode); } @Override - public AsyncStage> list() - { - List children = cache.currentChildren() - .values() - .stream() - .map(ZNode::model) - .collect(Collectors.toList()); + public AsyncStage> list() { + List children = + cache.currentChildren().values().stream().map(ZNode::model).collect(Collectors.toList()); return ModelStage.completed(children); } @Override - public AsyncStage update(T model) - { + public AsyncStage update(T model) { return client.update(model); } @Override - public AsyncStage update(T model, int version) - { + public AsyncStage update(T model, int version) { return client.update(model, version); } @Override - public AsyncStage delete() - { + public AsyncStage delete() { return client.delete(); } @Override - public AsyncStage delete(int version) - { + public AsyncStage delete(int version) { return client.delete(version); } @Override - public AsyncStage checkExists() - { + public AsyncStage checkExists() { ZPath path = client.modelSpec().path(); Optional> data = cache.currentData(path); return data.map(node -> completed(node.stat())).orElseGet(() -> completed(null)); } @Override - public AsyncStage> children() - { - List paths = cache.currentChildren(client.modelSpec().path()) - .keySet() - .stream() - .filter(path -> !path.isRoot() && path.parent().equals(client.modelSpec().path())) - .collect(Collectors.toList()); + public AsyncStage> children() { + List paths = cache.currentChildren(client.modelSpec().path()).keySet().stream() + .filter(path -> !path.isRoot() + && path.parent().equals(client.modelSpec().path())) + .collect(Collectors.toList()); return completed(paths); } @Override - public AsyncStage>> childrenAsZNodes() - { - List> nodes = cache.currentChildren(client.modelSpec().path()) - .entrySet() - .stream() - .filter(e -> !e.getKey().isRoot() && e.getKey().parent().equals(client.modelSpec().path())) - .map(Map.Entry::getValue) - .collect(Collectors.toList()); + public AsyncStage>> childrenAsZNodes() { + List> nodes = cache.currentChildren(client.modelSpec().path()).entrySet().stream() + .filter(e -> !e.getKey().isRoot() + && e.getKey().parent().equals(client.modelSpec().path())) + .map(Map.Entry::getValue) + .collect(Collectors.toList()); return completed(nodes); } @Override - public CuratorOp createOp(T model) - { + public CuratorOp createOp(T model) { return client.createOp(model); } @Override - public CuratorOp updateOp(T model) - { + public CuratorOp updateOp(T model) { return client.updateOp(model); } @Override - public CuratorOp updateOp(T model, int version) - { + public CuratorOp updateOp(T model, int version) { return client.updateOp(model, version); } @Override - public CuratorOp deleteOp() - { + public CuratorOp deleteOp() { return client.deleteOp(); } @Override - public CuratorOp deleteOp(int version) - { + public CuratorOp deleteOp(int version) { return client.deleteOp(version); } @Override - public CuratorOp checkExistsOp() - { + public CuratorOp checkExistsOp() { return client.checkExistsOp(); } @Override - public CuratorOp checkExistsOp(int version) - { + public CuratorOp checkExistsOp(int version) { return client.checkExistsOp(version); } @Override - public AsyncStage> inTransaction(List operations) - { + public AsyncStage> inTransaction(List operations) { return client.inTransaction(operations); } - private AsyncStage completed(U value) - { + private AsyncStage completed(U value) { return ModelStage.completed(value); } - private AsyncStage exceptionally() - { - KeeperException.NoNodeException exception = new KeeperException.NoNodeException(client.modelSpec().path().fullPath()); + private AsyncStage exceptionally() { + KeeperException.NoNodeException exception = + new KeeperException.NoNodeException(client.modelSpec().path().fullPath()); return ModelStage.exceptionally(exception); } - private AsyncStage internalRead(Function, U> resolver, Supplier> elseProc) - { + private AsyncStage internalRead(Function, U> resolver, Supplier> elseProc) { ZPath path = client.modelSpec().path(); Optional> data = cache.currentData(path); - return data.map(node -> completed(resolver.apply(node))) - .orElseGet(elseProc); + return data.map(node -> completed(resolver.apply(node))).orElseGet(elseProc); } } diff --git a/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/details/ModelSpecImpl.java b/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/details/ModelSpecImpl.java index f51b3cbf8..6b6af28b4 100644 --- a/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/details/ModelSpecImpl.java +++ b/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/details/ModelSpecImpl.java @@ -21,6 +21,9 @@ import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; +import java.util.List; +import java.util.Objects; +import java.util.Set; import org.apache.curator.framework.schema.Schema; import org.apache.curator.framework.schema.SchemaValidator; import org.apache.curator.framework.schema.SchemaViolation; @@ -32,12 +35,8 @@ import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.ZooDefs; import org.apache.zookeeper.data.ACL; -import java.util.List; -import java.util.Objects; -import java.util.Set; -public class ModelSpecImpl implements ModelSpec, SchemaValidator -{ +public class ModelSpecImpl implements ModelSpec, SchemaValidator { private final ZPath path; private final ModelSerializer serializer; private final CreateMode createMode; @@ -47,8 +46,14 @@ public class ModelSpecImpl implements ModelSpec, SchemaValidator private final long ttl; private volatile Schema schema = null; - public ModelSpecImpl(ZPath path, ModelSerializer serializer, CreateMode createMode, List aclList, Set createOptions, Set deleteOptions, long ttl) - { + public ModelSpecImpl( + ZPath path, + ModelSerializer serializer, + CreateMode createMode, + List aclList, + Set createOptions, + Set deleteOptions, + long ttl) { this.path = Objects.requireNonNull(path, "path cannot be null"); this.serializer = Objects.requireNonNull(serializer, "serializer cannot be null"); this.createMode = Objects.requireNonNull(createMode, "createMode cannot be null"); @@ -59,180 +64,153 @@ public ModelSpecImpl(ZPath path, ModelSerializer serializer, CreateMode creat } @Override - public ModelSpec child(Object child) - { + public ModelSpec child(Object child) { return withPath(path.child(child)); } @Override - public ModelSpec parent() - { + public ModelSpec parent() { return withPath(path.parent()); } @Override - public ModelSpec resolved(Object... parameters) - { + public ModelSpec resolved(Object... parameters) { return withPath(path.resolved(parameters)); } @Override - public ModelSpec resolved(List parameters) - { + public ModelSpec resolved(List parameters) { return withPath(path.resolved(parameters)); } @Override - public ModelSpec withPath(ZPath newPath) - { + public ModelSpec withPath(ZPath newPath) { return new ModelSpecImpl<>(newPath, serializer, createMode, aclList, createOptions, deleteOptions, ttl); } @Override - public ZPath path() - { + public ZPath path() { return path; } @Override - public ModelSerializer serializer() - { + public ModelSerializer serializer() { return serializer; } @Override - public CreateMode createMode() - { + public CreateMode createMode() { return createMode; } @Override - public List aclList() - { + public List aclList() { return aclList; } @Override - public Set createOptions() - { + public Set createOptions() { return createOptions; } @Override - public Set deleteOptions() - { + public Set deleteOptions() { return deleteOptions; } @Override - public long ttl() - { + public long ttl() { return ttl; } @Override - public Schema schema() - { - if ( schema == null ) - { + public Schema schema() { + if (schema == null) { schema = Schema.builder(path.toSchemaPathPattern()) - .dataValidator(this) - .ephemeral(createMode.isEphemeral() ? Schema.Allowance.MUST : Schema.Allowance.CANNOT) - .canBeDeleted(true) - .sequential(createMode.isSequential() ? Schema.Allowance.MUST : Schema.Allowance.CANNOT) - .watched(Schema.Allowance.CAN) - .build(); + .dataValidator(this) + .ephemeral(createMode.isEphemeral() ? Schema.Allowance.MUST : Schema.Allowance.CANNOT) + .canBeDeleted(true) + .sequential(createMode.isSequential() ? Schema.Allowance.MUST : Schema.Allowance.CANNOT) + .watched(Schema.Allowance.CAN) + .build(); } return schema; } @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; } - ModelSpecImpl modelSpec = (ModelSpecImpl)o; + ModelSpecImpl modelSpec = (ModelSpecImpl) o; - if ( ttl != modelSpec.ttl ) - { + if (ttl != modelSpec.ttl) { return false; } - if ( !path.equals(modelSpec.path) ) - { + if (!path.equals(modelSpec.path)) { return false; } - if ( !serializer.equals(modelSpec.serializer) ) - { + if (!serializer.equals(modelSpec.serializer)) { return false; } - if ( createMode != modelSpec.createMode ) - { + if (createMode != modelSpec.createMode) { return false; } - if ( !aclList.equals(modelSpec.aclList) ) - { + if (!aclList.equals(modelSpec.aclList)) { return false; } - if ( !createOptions.equals(modelSpec.createOptions) ) - { + if (!createOptions.equals(modelSpec.createOptions)) { return false; } //noinspection SimplifiableIfStatement - if ( !deleteOptions.equals(modelSpec.deleteOptions) ) - { + if (!deleteOptions.equals(modelSpec.deleteOptions)) { return false; } return schema.equals(modelSpec.schema); } @Override - public int hashCode() - { + public int hashCode() { int result = path.hashCode(); result = 31 * result + serializer.hashCode(); result = 31 * result + createMode.hashCode(); result = 31 * result + aclList.hashCode(); result = 31 * result + createOptions.hashCode(); result = 31 * result + deleteOptions.hashCode(); - result = 31 * result + (int)(ttl ^ (ttl >>> 32)); + result = 31 * result + (int) (ttl ^ (ttl >>> 32)); result = 31 * result + schema.hashCode(); return result; } @Override - public String toString() - { - return "ModelSpecImpl{" + "path=" + path + ", serializer=" + serializer + ", createMode=" + createMode + ", aclList=" + aclList + ", createOptions=" + createOptions + ", deleteOptions=" + deleteOptions + ", ttl=" + ttl + ", schema=" + schema + '}'; + public String toString() { + return "ModelSpecImpl{" + "path=" + path + ", serializer=" + serializer + ", createMode=" + createMode + + ", aclList=" + aclList + ", createOptions=" + createOptions + ", deleteOptions=" + deleteOptions + + ", ttl=" + ttl + ", schema=" + schema + '}'; } @Override - public boolean isValid(Schema schema, String path, byte[] data, List acl) - { - if ( acl != null ) - { + public boolean isValid(Schema schema, String path, byte[] data, List acl) { + if (acl != null) { List localAclList = (aclList.size() > 0) ? aclList : ZooDefs.Ids.OPEN_ACL_UNSAFE; - if ( !acl.equals(localAclList) ) - { - throw new SchemaViolation(schema, new SchemaViolation.ViolatorData(path, data, acl), "ACLs do not match model ACLs"); + if (!acl.equals(localAclList)) { + throw new SchemaViolation( + schema, new SchemaViolation.ViolatorData(path, data, acl), "ACLs do not match model ACLs"); } } - if ( data != null ) - { - try - { + if (data != null) { + try { serializer.deserialize(data); - } - catch ( RuntimeException e ) - { - throw new SchemaViolation(schema, new SchemaViolation.ViolatorData(path, data, acl), "Data cannot be deserialized into a model"); + } catch (RuntimeException e) { + throw new SchemaViolation( + schema, + new SchemaViolation.ViolatorData(path, data, acl), + "Data cannot be deserialized into a model"); } } return true; diff --git a/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/details/ModelStage.java b/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/details/ModelStage.java index 10553c62b..4ff667eb4 100644 --- a/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/details/ModelStage.java +++ b/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/details/ModelStage.java @@ -19,8 +19,6 @@ package org.apache.curator.x.async.modeled.details; -import org.apache.curator.x.async.AsyncStage; -import org.apache.zookeeper.WatchedEvent; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; import java.util.concurrent.Executor; @@ -28,144 +26,126 @@ import java.util.function.BiFunction; import java.util.function.Consumer; import java.util.function.Function; +import org.apache.curator.x.async.AsyncStage; +import org.apache.zookeeper.WatchedEvent; -class ModelStage extends CompletableFuture implements AsyncStage -{ +class ModelStage extends CompletableFuture implements AsyncStage { private final CompletionStage event; - static ModelStage make() - { + static ModelStage make() { return new ModelStage<>(null); } - static ModelStage make(CompletionStage event) - { + static ModelStage make(CompletionStage event) { return new ModelStage<>(event); } - static ModelStage completed(U value) - { + static ModelStage completed(U value) { ModelStage stage = new ModelStage<>(null); stage.complete(value); return stage; } - static ModelStage exceptionally(Exception e) - { + static ModelStage exceptionally(Exception e) { ModelStage stage = new ModelStage<>(null); stage.completeExceptionally(e); return stage; } - static ModelStage async(Executor executor) - { + static ModelStage async(Executor executor) { return new AsyncModelStage<>(executor); } - static ModelStage asyncCompleted(U value, Executor executor) - { + static ModelStage asyncCompleted(U value, Executor executor) { ModelStage stage = new AsyncModelStage<>(executor); stage.complete(value); return stage; } - static ModelStage asyncExceptionally(Exception e, Executor executor) - { + static ModelStage asyncExceptionally(Exception e, Executor executor) { ModelStage stage = new AsyncModelStage<>(executor); stage.completeExceptionally(e); return stage; } @Override - public CompletionStage event() - { + public CompletionStage event() { return event; } - private ModelStage(CompletionStage event) - { + private ModelStage(CompletionStage event) { this.event = event; } - private static class AsyncModelStage extends ModelStage - { + private static class AsyncModelStage extends ModelStage { private final Executor executor; - public AsyncModelStage(Executor executor) - { + public AsyncModelStage(Executor executor) { super(null); this.executor = executor; } @Override - public CompletableFuture thenApplyAsync(Function fn) - { + public CompletableFuture thenApplyAsync(Function fn) { return super.thenApplyAsync(fn, executor); } @Override - public CompletableFuture thenAcceptAsync(Consumer action) - { + public CompletableFuture thenAcceptAsync(Consumer action) { return super.thenAcceptAsync(action, executor); } @Override - public CompletableFuture thenRunAsync(Runnable action) - { + public CompletableFuture thenRunAsync(Runnable action) { return super.thenRunAsync(action, executor); } @Override - public CompletableFuture thenCombineAsync(CompletionStage other, BiFunction fn) - { + public CompletableFuture thenCombineAsync( + CompletionStage other, BiFunction fn) { return super.thenCombineAsync(other, fn, executor); } @Override - public CompletableFuture thenAcceptBothAsync(CompletionStage other, BiConsumer action) - { + public CompletableFuture thenAcceptBothAsync( + CompletionStage other, BiConsumer action) { return super.thenAcceptBothAsync(other, action, executor); } @Override - public CompletableFuture runAfterBothAsync(CompletionStage other, Runnable action) - { + public CompletableFuture runAfterBothAsync(CompletionStage other, Runnable action) { return super.runAfterBothAsync(other, action, executor); } @Override - public CompletableFuture applyToEitherAsync(CompletionStage other, Function fn) - { + public CompletableFuture applyToEitherAsync( + CompletionStage other, Function fn) { return super.applyToEitherAsync(other, fn, executor); } @Override - public CompletableFuture acceptEitherAsync(CompletionStage other, Consumer action) - { + public CompletableFuture acceptEitherAsync( + CompletionStage other, Consumer action) { return super.acceptEitherAsync(other, action, executor); } @Override - public CompletableFuture runAfterEitherAsync(CompletionStage other, Runnable action) - { + public CompletableFuture runAfterEitherAsync(CompletionStage other, Runnable action) { return super.runAfterEitherAsync(other, action, executor); } @Override - public CompletableFuture thenComposeAsync(Function> fn) - { + public CompletableFuture thenComposeAsync(Function> fn) { return super.thenComposeAsync(fn, executor); } @Override - public CompletableFuture whenCompleteAsync(BiConsumer action) - { + public CompletableFuture whenCompleteAsync(BiConsumer action) { return super.whenCompleteAsync(action, executor); } @Override - public CompletableFuture handleAsync(BiFunction fn) - { + public CompletableFuture handleAsync(BiFunction fn) { return super.handleAsync(fn, executor); } } diff --git a/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/details/ModeledCacheImpl.java b/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/details/ModeledCacheImpl.java index 7bef5e37d..6f23cdd3e 100644 --- a/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/details/ModeledCacheImpl.java +++ b/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/details/ModeledCacheImpl.java @@ -19,6 +19,12 @@ package org.apache.curator.x.async.modeled.details; +import java.util.AbstractMap; +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ExecutorService; +import java.util.stream.Collectors; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.EnsureContainers; import org.apache.curator.framework.listen.Listenable; @@ -38,186 +44,159 @@ import org.apache.curator.x.async.modeled.cached.ModeledCache; import org.apache.curator.x.async.modeled.cached.ModeledCacheListener; import org.apache.zookeeper.data.Stat; -import java.util.AbstractMap; -import java.util.Map; -import java.util.Optional; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ExecutorService; -import java.util.stream.Collectors; -class ModeledCacheImpl implements TreeCacheListener, ModeledCache -{ +class ModeledCacheImpl implements TreeCacheListener, ModeledCache { private final CuratorCacheBridge cache; private final Map> entries = new ConcurrentHashMap<>(); private final ModelSerializer serializer; - private final StandardListenerManager> listenerContainer = StandardListenerManager.standard(); + private final StandardListenerManager> listenerContainer = + StandardListenerManager.standard(); private final ZPath basePath; private final EnsureContainers ensureContainers; - private static final class Entry - { + private static final class Entry { final Stat stat; final T model; - Entry(Stat stat, T model) - { + Entry(Stat stat, T model) { this.stat = stat; this.model = model; } } - ModeledCacheImpl(CuratorFramework client, ModelSpec modelSpec, ExecutorService executor) - { - if ( !modelSpec.path().isResolved() && !modelSpec.path().isRoot() && modelSpec.path().parent().isResolved() ) - { + ModeledCacheImpl(CuratorFramework client, ModelSpec modelSpec, ExecutorService executor) { + if (!modelSpec.path().isResolved() + && !modelSpec.path().isRoot() + && modelSpec.path().parent().isResolved()) { modelSpec = modelSpec.parent(); // i.e. the last item is a parameter } basePath = modelSpec.path(); this.serializer = modelSpec.serializer(); - CuratorCacheBridgeBuilder bridgeBuilder = CuratorCache.bridgeBuilder(client, basePath.fullPath()).withDataNotCached().withExecutorService(executor); - if ( modelSpec.createOptions().contains(CreateOption.compress) ) - { + CuratorCacheBridgeBuilder bridgeBuilder = CuratorCache.bridgeBuilder(client, basePath.fullPath()) + .withDataNotCached() + .withExecutorService(executor); + if (modelSpec.createOptions().contains(CreateOption.compress)) { bridgeBuilder = bridgeBuilder.withOptions(CuratorCache.Options.COMPRESSED_DATA); } cache = bridgeBuilder.build(); - cache.listenable().addListener(CuratorCacheListener.builder().forTreeCache(client, this).build()); + cache.listenable() + .addListener(CuratorCacheListener.builder() + .forTreeCache(client, this) + .build()); - if ( modelSpec.createOptions().contains(CreateOption.createParentsIfNeeded) || modelSpec.createOptions().contains(CreateOption.createParentsAsContainers) ) - { + if (modelSpec.createOptions().contains(CreateOption.createParentsIfNeeded) + || modelSpec.createOptions().contains(CreateOption.createParentsAsContainers)) { ensureContainers = new EnsureContainers(client, basePath.fullPath()); - } - else - { + } else { ensureContainers = null; } } - public void start() - { - try - { - if ( ensureContainers != null ) - { + public void start() { + try { + if (ensureContainers != null) { ensureContainers.ensure(); } cache.start(); - } - catch ( Exception e ) - { + } catch (Exception e) { throw new RuntimeException(e); } } - public void close() - { + public void close() { cache.close(); entries.clear(); } @Override - public Optional> currentData(ZPath path) - { + public Optional> currentData(ZPath path) { Entry entry = entries.get(path); - if ( entry != null ) - { + if (entry != null) { return Optional.of(new ZNodeImpl<>(path, entry.stat, entry.model)); } return Optional.empty(); } - ZPath basePath() - { + ZPath basePath() { return basePath; } - Map> currentChildren() - { + Map> currentChildren() { return currentChildren(basePath); } @Override - public Map> currentChildren(ZPath path) - { - return entries.entrySet() - .stream() - .filter(entry -> entry.getKey().startsWith(path)) - .map(entry -> new AbstractMap.SimpleEntry<>(entry.getKey(), new ZNodeImpl<>(entry.getKey(), entry.getValue().stat, entry.getValue().model))) - .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); + public Map> currentChildren(ZPath path) { + return entries.entrySet().stream() + .filter(entry -> entry.getKey().startsWith(path)) + .map(entry -> new AbstractMap.SimpleEntry<>( + entry.getKey(), new ZNodeImpl<>(entry.getKey(), entry.getValue().stat, entry.getValue().model))) + .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); } - public Listenable> listenable() - { + public Listenable> listenable() { return listenerContainer; } @Override - public void childEvent(CuratorFramework client, TreeCacheEvent event) - { - try - { + public void childEvent(CuratorFramework client, TreeCacheEvent event) { + try { internalChildEvent(event); - } - catch ( Exception e ) - { + } catch (Exception e) { ThreadUtils.checkInterrupted(e); listenerContainer.forEach(l -> l.handleException(e)); } } - private void internalChildEvent(TreeCacheEvent event) - { - switch ( event.getType() ) - { - case NODE_ADDED: - case NODE_UPDATED: - { - ZPath path = ZPath.parse(event.getData().getPath()); - byte[] bytes = event.getData().getData(); - if ( (bytes != null) && (bytes.length > 0) ) // otherwise it's probably just a parent node being created - { - T model = serializer.deserialize(bytes); - entries.put(path, new Entry<>(event.getData().getStat(), model)); - ModeledCacheListener.Type type = (event.getType() == TreeCacheEvent.Type.NODE_ADDED) ? ModeledCacheListener.Type.NODE_ADDED : ModeledCacheListener.Type.NODE_UPDATED; - accept(type, path, event.getData().getStat(), model); + private void internalChildEvent(TreeCacheEvent event) { + switch (event.getType()) { + case NODE_ADDED: + case NODE_UPDATED: { + ZPath path = ZPath.parse(event.getData().getPath()); + byte[] bytes = event.getData().getData(); + if ((bytes != null) && (bytes.length > 0)) // otherwise it's probably just a parent node being created + { + T model = serializer.deserialize(bytes); + entries.put(path, new Entry<>(event.getData().getStat(), model)); + ModeledCacheListener.Type type = (event.getType() == TreeCacheEvent.Type.NODE_ADDED) + ? ModeledCacheListener.Type.NODE_ADDED + : ModeledCacheListener.Type.NODE_UPDATED; + accept(type, path, event.getData().getStat(), model); + } + break; } - break; - } - case NODE_REMOVED: - { - ZPath path = ZPath.parse(event.getData().getPath()); - Entry entry = entries.remove(path); - T model = null; - if (entry != null) { - model = entry.model; - } - else if (event.getData().getData() != null) { - model = serializer.deserialize(event.getData().getData()); + case NODE_REMOVED: { + ZPath path = ZPath.parse(event.getData().getPath()); + Entry entry = entries.remove(path); + T model = null; + if (entry != null) { + model = entry.model; + } else if (event.getData().getData() != null) { + model = serializer.deserialize(event.getData().getData()); + } + if (model != null) { + Stat stat = (entry != null) ? entry.stat : event.getData().getStat(); + accept(ModeledCacheListener.Type.NODE_REMOVED, path, stat, model); + } + + break; } - if (model != null) { - Stat stat = (entry != null) ? entry.stat : event.getData().getStat(); - accept(ModeledCacheListener.Type.NODE_REMOVED, path, stat, model); - } - - break; - } - case INITIALIZED: - { - listenerContainer.forEach(ModeledCacheListener::initialized); - break; - } + case INITIALIZED: { + listenerContainer.forEach(ModeledCacheListener::initialized); + break; + } - default: - // ignore - break; + default: + // ignore + break; } } - private void accept(ModeledCacheListener.Type type, ZPath path, Stat stat, T model) - { + private void accept(ModeledCacheListener.Type type, ZPath path, Stat stat, T model) { listenerContainer.forEach(l -> l.accept(type, path, stat, model)); } } diff --git a/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/details/ModeledFrameworkImpl.java b/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/details/ModeledFrameworkImpl.java index bb9ade83a..01e95decc 100644 --- a/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/details/ModeledFrameworkImpl.java +++ b/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/details/ModeledFrameworkImpl.java @@ -23,6 +23,14 @@ import com.google.common.base.Throwables; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Lists; +import java.util.Collections; +import java.util.List; +import java.util.Objects; +import java.util.Set; +import java.util.concurrent.ExecutorService; +import java.util.function.Function; +import java.util.function.UnaryOperator; +import java.util.stream.Collectors; import org.apache.curator.framework.api.CuratorEvent; import org.apache.curator.framework.api.UnhandledErrorListener; import org.apache.curator.framework.api.transaction.CuratorOp; @@ -49,17 +57,8 @@ import org.apache.zookeeper.WatchedEvent; import org.apache.zookeeper.data.ACL; import org.apache.zookeeper.data.Stat; -import java.util.Collections; -import java.util.List; -import java.util.Objects; -import java.util.Set; -import java.util.concurrent.ExecutorService; -import java.util.function.Function; -import java.util.function.UnaryOperator; -import java.util.stream.Collectors; -public class ModeledFrameworkImpl implements ModeledFramework -{ +public class ModeledFrameworkImpl implements ModeledFramework { private final AsyncCuratorFramework client; private final WatchableAsyncCuratorFramework watchableClient; private final ModelSpec modelSpec; @@ -71,8 +70,14 @@ public class ModeledFrameworkImpl implements ModeledFramework private final boolean isWatched; private final Set modeledOptions; - public static ModeledFrameworkImpl build(AsyncCuratorFramework client, ModelSpec model, WatchMode watchMode, UnaryOperator watcherFilter, UnhandledErrorListener unhandledErrorListener, UnaryOperator resultFilter, Set modeledOptions) - { + public static ModeledFrameworkImpl build( + AsyncCuratorFramework client, + ModelSpec model, + WatchMode watchMode, + UnaryOperator watcherFilter, + UnhandledErrorListener unhandledErrorListener, + UnaryOperator resultFilter, + Set modeledOptions) { boolean isWatched = (watchMode != null); Objects.requireNonNull(client, "client cannot be null"); @@ -81,25 +86,34 @@ public static ModeledFrameworkImpl build(AsyncCuratorFramework client, Mo watchMode = (watchMode != null) ? watchMode : WatchMode.stateChangeAndSuccess; - AsyncCuratorFrameworkDsl dslClient = client.with(watchMode, unhandledErrorListener, resultFilter, watcherFilter); + AsyncCuratorFrameworkDsl dslClient = + client.with(watchMode, unhandledErrorListener, resultFilter, watcherFilter); WatchableAsyncCuratorFramework watchableClient = isWatched ? dslClient.watched() : dslClient; return new ModeledFrameworkImpl<>( - client, - dslClient, - watchableClient, - model, - watchMode, - watcherFilter, - unhandledErrorListener, - resultFilter, - isWatched, - modeledOptions - ); - } - - private ModeledFrameworkImpl(AsyncCuratorFramework client, AsyncCuratorFrameworkDsl dslClient, WatchableAsyncCuratorFramework watchableClient, ModelSpec modelSpec, WatchMode watchMode, UnaryOperator watcherFilter, UnhandledErrorListener unhandledErrorListener, UnaryOperator resultFilter, boolean isWatched, Set modeledOptions) - { + client, + dslClient, + watchableClient, + model, + watchMode, + watcherFilter, + unhandledErrorListener, + resultFilter, + isWatched, + modeledOptions); + } + + private ModeledFrameworkImpl( + AsyncCuratorFramework client, + AsyncCuratorFrameworkDsl dslClient, + WatchableAsyncCuratorFramework watchableClient, + ModelSpec modelSpec, + WatchMode watchMode, + UnaryOperator watcherFilter, + UnhandledErrorListener unhandledErrorListener, + UnaryOperator resultFilter, + boolean isWatched, + Set modeledOptions) { this.client = client; this.dslClient = dslClient; this.watchableClient = watchableClient; @@ -113,146 +127,131 @@ private ModeledFrameworkImpl(AsyncCuratorFramework client, AsyncCuratorFramework } @Override - public CachedModeledFramework cached() - { + public CachedModeledFramework cached() { return cached(ThreadUtils.newSingleThreadExecutor("CachedModeledFramework")); } @Override - public CachedModeledFramework cached(ExecutorService executor) - { - Preconditions.checkState(!isWatched, "CachedModeledFramework cannot be used with watched instances as the internal cache would bypass the watchers."); + public CachedModeledFramework cached(ExecutorService executor) { + Preconditions.checkState( + !isWatched, + "CachedModeledFramework cannot be used with watched instances as the internal cache would bypass the watchers."); return new CachedModeledFrameworkImpl<>(this, Objects.requireNonNull(executor, "executor cannot be null")); } @Override - public VersionedModeledFramework versioned() - { + public VersionedModeledFramework versioned() { return new VersionedModeledFrameworkImpl<>(this); } @Override - public ModelSpec modelSpec() - { + public ModelSpec modelSpec() { return modelSpec; } @Override - public AsyncCuratorFramework unwrap() - { + public AsyncCuratorFramework unwrap() { return client; } @Override - public AsyncStage set(T item) - { + public AsyncStage set(T item) { return set(item, null, -1); } @Override - public AsyncStage set(T item, Stat storingStatIn) - { + public AsyncStage set(T item, Stat storingStatIn) { return set(item, storingStatIn, -1); } @Override - public AsyncStage set(T item, int version) - { + public AsyncStage set(T item, int version) { return set(item, null, version); } @Override - public AsyncStage set(T item, Stat storingStatIn, int version) - { - try - { + public AsyncStage set(T item, Stat storingStatIn, int version) { + try { byte[] bytes = modelSpec.serializer().serialize(item); - return dslClient.create() - .withOptions(modelSpec.createOptions(), modelSpec.createMode(), fixAclList(modelSpec.aclList()), storingStatIn, modelSpec.ttl(), version) - .forPath(resolveForSet(item), bytes); - } - catch ( Exception e ) - { + return dslClient + .create() + .withOptions( + modelSpec.createOptions(), + modelSpec.createMode(), + fixAclList(modelSpec.aclList()), + storingStatIn, + modelSpec.ttl(), + version) + .forPath(resolveForSet(item), bytes); + } catch (Exception e) { return ModelStage.exceptionally(e); } } @Override - public AsyncStage read() - { + public AsyncStage read() { return internalRead(ZNode::model, null); } @Override - public AsyncStage read(Stat storingStatIn) - { + public AsyncStage read(Stat storingStatIn) { return internalRead(ZNode::model, storingStatIn); } @Override - public AsyncStage> readAsZNode() - { + public AsyncStage> readAsZNode() { return internalRead(Function.identity(), null); } @Override - public AsyncStage update(T item) - { + public AsyncStage update(T item) { return update(item, -1); } @Override - public AsyncStage update(T item, int version) - { - try - { + public AsyncStage update(T item, int version) { + try { byte[] bytes = modelSpec.serializer().serialize(item); AsyncSetDataBuilder dataBuilder = dslClient.setData(); - AsyncPathAndBytesable> next = isCompressed() ? dataBuilder.compressedWithVersion(version) : dataBuilder.withVersion(version); + AsyncPathAndBytesable> next = + isCompressed() ? dataBuilder.compressedWithVersion(version) : dataBuilder.withVersion(version); return next.forPath(resolveForSet(item), bytes); - } - catch ( Exception e ) - { + } catch (Exception e) { return ModelStage.exceptionally(e); } } @Override - public AsyncStage checkExists() - { + public AsyncStage checkExists() { return watchableClient.checkExists().forPath(modelSpec.path().fullPath()); } @Override - public AsyncStage delete() - { + public AsyncStage delete() { return delete(-1); } @Override - public AsyncStage delete(int version) - { - return dslClient.delete().withOptionsAndVersion(modelSpec.deleteOptions(), version).forPath(modelSpec.path().fullPath()); + public AsyncStage delete(int version) { + return dslClient + .delete() + .withOptionsAndVersion(modelSpec.deleteOptions(), version) + .forPath(modelSpec.path().fullPath()); } @Override - public AsyncStage> children() - { + public AsyncStage> children() { return internalGetChildren(modelSpec.path()); } @Override - public AsyncStage>> childrenAsZNodes() - { + public AsyncStage>> childrenAsZNodes() { ModelStage>> modelStage = ModelStage.make(); Preconditions.checkState(!isWatched, "childrenAsZNodes() cannot be used with watched instances."); children().handle((children, e) -> { - if ( e != null ) - { + if (e != null) { modelStage.completeExceptionally(e); - } - else - { + } else { completeChildrenAsZNodes(modelStage, children); } return null; @@ -260,24 +259,18 @@ public AsyncStage>> childrenAsZNodes() return modelStage; } - private void completeChildrenAsZNodes(ModelStage>> modelStage, List children) - { + private void completeChildrenAsZNodes(ModelStage>> modelStage, List children) { List> nodes = Lists.newArrayList(); - if ( children.size() == 0 ) - { + if (children.size() == 0) { modelStage.complete(nodes); return; } children.forEach(path -> withPath(path).readAsZNode().handle((node, e) -> { - if ( e != null ) - { + if (e != null) { modelStage.completeExceptionally(e); - } - else - { + } else { nodes.add(node); - if ( nodes.size() == children.size() ) - { + if (nodes.size() == children.size()) { modelStage.complete(nodes); } } @@ -285,24 +278,18 @@ private void completeChildrenAsZNodes(ModelStage>> modelStage, Lis })); } - private AsyncStage> internalGetChildren(ZPath path) - { + private AsyncStage> internalGetChildren(ZPath path) { AsyncStage> asyncStage = watchableClient.getChildren().forPath(path.fullPath()); ModelStage> modelStage = ModelStage.make(asyncStage.event()); asyncStage.whenComplete((children, e) -> { - if ( e != null ) - { - if ( modeledOptions.contains(ModeledOptions.ignoreMissingNodesForChildren) && (Throwables.getRootCause(e) instanceof KeeperException.NoNodeException) ) - { + if (e != null) { + if (modeledOptions.contains(ModeledOptions.ignoreMissingNodesForChildren) + && (Throwables.getRootCause(e) instanceof KeeperException.NoNodeException)) { modelStage.complete(Collections.emptyList()); - } - else - { + } else { modelStage.completeExceptionally(e); } - } - else - { + } else { modelStage.complete(children.stream().map(path::child).collect(Collectors.toList())); } }); @@ -310,145 +297,136 @@ private AsyncStage> internalGetChildren(ZPath path) } @Override - public ModeledFramework parent() - { + public ModeledFramework parent() { ModelSpec newModelSpec = modelSpec.parent(); return new ModeledFrameworkImpl<>( - client, - dslClient, - watchableClient, - newModelSpec, - watchMode, - watcherFilter, - unhandledErrorListener, - resultFilter, - isWatched, - modeledOptions - ); + client, + dslClient, + watchableClient, + newModelSpec, + watchMode, + watcherFilter, + unhandledErrorListener, + resultFilter, + isWatched, + modeledOptions); } @Override - public ModeledFramework child(Object child) - { + public ModeledFramework child(Object child) { ModelSpec newModelSpec = modelSpec.child(child); return new ModeledFrameworkImpl<>( - client, - dslClient, - watchableClient, - newModelSpec, - watchMode, - watcherFilter, - unhandledErrorListener, - resultFilter, - isWatched, - modeledOptions - ); + client, + dslClient, + watchableClient, + newModelSpec, + watchMode, + watcherFilter, + unhandledErrorListener, + resultFilter, + isWatched, + modeledOptions); } @Override - public ModeledFramework withPath(ZPath path) - { + public ModeledFramework withPath(ZPath path) { ModelSpec newModelSpec = modelSpec.withPath(path); return new ModeledFrameworkImpl<>( - client, - dslClient, - watchableClient, - newModelSpec, - watchMode, - watcherFilter, - unhandledErrorListener, - resultFilter, - isWatched, - modeledOptions - ); - } - - public static boolean isCompressed(Set createOptions) - { + client, + dslClient, + watchableClient, + newModelSpec, + watchMode, + watcherFilter, + unhandledErrorListener, + resultFilter, + isWatched, + modeledOptions); + } + + public static boolean isCompressed(Set createOptions) { return createOptions.contains(CreateOption.compress); } @Override - public CuratorOp createOp(T model) - { + public CuratorOp createOp(T model) { return client.transactionOp() - .create() - .withOptions(modelSpec.createMode(), fixAclList(modelSpec.aclList()), modelSpec.createOptions().contains(CreateOption.compress), modelSpec.ttl()) - .forPath(resolveForSet(model), modelSpec.serializer().serialize(model)); + .create() + .withOptions( + modelSpec.createMode(), + fixAclList(modelSpec.aclList()), + modelSpec.createOptions().contains(CreateOption.compress), + modelSpec.ttl()) + .forPath(resolveForSet(model), modelSpec.serializer().serialize(model)); } @Override - public CuratorOp updateOp(T model) - { + public CuratorOp updateOp(T model) { return updateOp(model, -1); } @Override - public CuratorOp updateOp(T model, int version) - { + public CuratorOp updateOp(T model, int version) { AsyncTransactionSetDataBuilder builder = client.transactionOp().setData(); - if ( isCompressed() ) - { - return builder.withVersionCompressed(version).forPath(resolveForSet(model), modelSpec.serializer().serialize(model)); + if (isCompressed()) { + return builder.withVersionCompressed(version) + .forPath(resolveForSet(model), modelSpec.serializer().serialize(model)); } - return builder.withVersion(version).forPath(resolveForSet(model), modelSpec.serializer().serialize(model)); + return builder.withVersion(version) + .forPath(resolveForSet(model), modelSpec.serializer().serialize(model)); } @Override - public CuratorOp deleteOp() - { + public CuratorOp deleteOp() { return deleteOp(-1); } @Override - public CuratorOp deleteOp(int version) - { - return client.transactionOp().delete().withVersion(version).forPath(modelSpec.path().fullPath()); + public CuratorOp deleteOp(int version) { + return client.transactionOp() + .delete() + .withVersion(version) + .forPath(modelSpec.path().fullPath()); } @Override - public CuratorOp checkExistsOp() - { + public CuratorOp checkExistsOp() { return checkExistsOp(-1); } @Override - public CuratorOp checkExistsOp(int version) - { - return client.transactionOp().check().withVersion(version).forPath(modelSpec.path().fullPath()); + public CuratorOp checkExistsOp(int version) { + return client.transactionOp() + .check() + .withVersion(version) + .forPath(modelSpec.path().fullPath()); } @Override - public AsyncStage> inTransaction(List operations) - { + public AsyncStage> inTransaction(List operations) { return client.transaction().forOperations(operations); } - private boolean isCompressed() - { + private boolean isCompressed() { return modelSpec.createOptions().contains(CreateOption.compress); } - private ModelStage internalRead(Function, U> resolver, Stat storingStatIn) - { + private ModelStage internalRead(Function, U> resolver, Stat storingStatIn) { Stat stat = (storingStatIn != null) ? storingStatIn : new Stat(); - AsyncPathable> next = isCompressed() ? watchableClient.getData().decompressedStoringStatIn(stat) : watchableClient.getData().storingStatIn(stat); + AsyncPathable> next = isCompressed() + ? watchableClient.getData().decompressedStoringStatIn(stat) + : watchableClient.getData().storingStatIn(stat); AsyncStage asyncStage = next.forPath(modelSpec.path().fullPath()); ModelStage modelStage = ModelStage.make(asyncStage.event()); asyncStage.whenComplete((value, e) -> { - if ( e != null ) - { + if (e != null) { modelStage.completeExceptionally(e); - } - else - { - try - { - ZNode node = new ZNodeImpl<>(modelSpec.path(), stat, modelSpec.serializer().deserialize(value)); + } else { + try { + ZNode node = new ZNodeImpl<>( + modelSpec.path(), stat, modelSpec.serializer().deserialize(value)); modelStage.complete(resolver.apply(node)); - } - catch ( Exception deserializeException ) - { + } catch (Exception deserializeException) { modelStage.completeExceptionally(deserializeException); } } @@ -456,17 +434,14 @@ private ModelStage internalRead(Function, U> resolver, Stat stor return modelStage; } - private String resolveForSet(T model) - { - if ( modelSpec.path().isResolved() ) - { + private String resolveForSet(T model) { + if (modelSpec.path().isResolved()) { return modelSpec.path().fullPath(); } return modelSpec.path().resolved(model).fullPath(); } - private List fixAclList(List aclList) - { - return (aclList.size() > 0) ? aclList : null; // workaround for old, bad design. empty list not accepted + private List fixAclList(List aclList) { + return (aclList.size() > 0) ? aclList : null; // workaround for old, bad design. empty list not accepted } } diff --git a/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/details/VersionedModeledFrameworkImpl.java b/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/details/VersionedModeledFrameworkImpl.java index de5cae2f4..0c88eecfe 100644 --- a/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/details/VersionedModeledFrameworkImpl.java +++ b/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/details/VersionedModeledFrameworkImpl.java @@ -26,61 +26,50 @@ import org.apache.curator.x.async.modeled.versioned.VersionedModeledFramework; import org.apache.zookeeper.data.Stat; -class VersionedModeledFrameworkImpl implements VersionedModeledFramework -{ +class VersionedModeledFrameworkImpl implements VersionedModeledFramework { private final ModeledFramework client; - VersionedModeledFrameworkImpl(ModeledFramework client) - { + VersionedModeledFrameworkImpl(ModeledFramework client) { this.client = client; } @Override - public AsyncStage set(Versioned model) - { + public AsyncStage set(Versioned model) { return client.set(model.model(), model.version()); } @Override - public AsyncStage set(Versioned model, Stat storingStatIn) - { + public AsyncStage set(Versioned model, Stat storingStatIn) { return client.set(model.model(), storingStatIn, model.version()); } @Override - public AsyncStage> read() - { + public AsyncStage> read() { return read(null); } @Override - public AsyncStage> read(Stat storingStatIn) - { + public AsyncStage> read(Stat storingStatIn) { Stat localStat = (storingStatIn != null) ? storingStatIn : new Stat(); AsyncStage stage = client.read(localStat); ModelStage> modelStage = ModelStage.make(stage.event()); stage.whenComplete((model, e) -> { - if ( e != null ) - { - modelStage.completeExceptionally(e); - } - else - { - modelStage.complete(Versioned.from(model, localStat.getVersion())); - } + if (e != null) { + modelStage.completeExceptionally(e); + } else { + modelStage.complete(Versioned.from(model, localStat.getVersion())); + } }); return modelStage; } @Override - public AsyncStage update(Versioned model) - { + public AsyncStage update(Versioned model) { return client.update(model.model(), model.version()); } @Override - public CuratorOp updateOp(Versioned model) - { + public CuratorOp updateOp(Versioned model) { return client.updateOp(model.model(), model.version()); } } diff --git a/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/details/ZNodeImpl.java b/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/details/ZNodeImpl.java index 989b61e1c..867f6cfea 100644 --- a/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/details/ZNodeImpl.java +++ b/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/details/ZNodeImpl.java @@ -19,39 +19,34 @@ package org.apache.curator.x.async.modeled.details; +import java.util.Objects; import org.apache.curator.x.async.modeled.ZNode; import org.apache.curator.x.async.modeled.ZPath; import org.apache.zookeeper.data.Stat; -import java.util.Objects; -public class ZNodeImpl implements ZNode -{ +public class ZNodeImpl implements ZNode { private final ZPath path; private final Stat stat; private final T model; - public ZNodeImpl(ZPath path, Stat stat, T model) - { + public ZNodeImpl(ZPath path, Stat stat, T model) { this.path = Objects.requireNonNull(path, "path cannot be null"); this.stat = Objects.requireNonNull(stat, "stat cannot be null"); this.model = Objects.requireNonNull(model, "model cannot be null"); } @Override - public ZPath path() - { + public ZPath path() { return path; } @Override - public Stat stat() - { + public Stat stat() { return stat; } @Override - public T model() - { + public T model() { return model; } } diff --git a/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/details/ZPathImpl.java b/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/details/ZPathImpl.java index 37f080a41..896065b8c 100644 --- a/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/details/ZPathImpl.java +++ b/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/details/ZPathImpl.java @@ -19,11 +19,9 @@ package org.apache.curator.x.async.modeled.details; +import static org.apache.curator.utils.ZKPaths.PATH_SEPARATOR; import com.google.common.base.Splitter; import com.google.common.collect.ImmutableList; -import org.apache.curator.x.async.modeled.NodeName; -import org.apache.curator.x.async.modeled.ZPath; -import org.apache.zookeeper.common.PathUtils; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; @@ -33,11 +31,11 @@ import java.util.function.UnaryOperator; import java.util.regex.Pattern; import java.util.stream.Collectors; +import org.apache.curator.x.async.modeled.NodeName; +import org.apache.curator.x.async.modeled.ZPath; +import org.apache.zookeeper.common.PathUtils; -import static org.apache.curator.utils.ZKPaths.PATH_SEPARATOR; - -public class ZPathImpl implements ZPath -{ +public class ZPathImpl implements ZPath { public static final ZPath root = new ZPathImpl(Collections.singletonList(PATH_SEPARATOR), null); private final List nodes; @@ -46,61 +44,44 @@ public class ZPathImpl implements ZPath private volatile ZPath parent = null; private volatile Pattern schema = null; - public static ZPath parse(String fullPath, UnaryOperator nameFilter) - { + public static ZPath parse(String fullPath, UnaryOperator nameFilter) { return parseInternal(fullPath, nameFilter); } - private static ZPathImpl parseInternal(String fullPath, UnaryOperator nameFilter) - { + private static ZPathImpl parseInternal(String fullPath, UnaryOperator nameFilter) { List nodes = ImmutableList.builder() - .add(PATH_SEPARATOR) - .addAll( - Splitter.on(PATH_SEPARATOR) - .omitEmptyStrings() - .splitToList(fullPath) - .stream() - .map(nameFilter) - .collect(Collectors.toList()) - ) - .build(); + .add(PATH_SEPARATOR) + .addAll(Splitter.on(PATH_SEPARATOR).omitEmptyStrings().splitToList(fullPath).stream() + .map(nameFilter) + .collect(Collectors.toList())) + .build(); nodes.forEach(ZPathImpl::validate); return new ZPathImpl(nodes, null); } - public static ZPath from(String[] names) - { + public static ZPath from(String[] names) { return from(null, Arrays.asList(names)); } - public static ZPath from(List names) - { + public static ZPath from(List names) { return from(null, names); } - public static ZPath from(ZPath base, String[] names) - { + public static ZPath from(ZPath base, String[] names) { return from(base, Arrays.asList(names)); } - public static ZPath from(ZPath base, List names) - { + public static ZPath from(ZPath base, List names) { names = Objects.requireNonNull(names, "names cannot be null"); names.forEach(ZPathImpl::validate); ImmutableList.Builder builder = ImmutableList.builder(); - if ( base != null ) - { - if ( base instanceof ZPathImpl ) - { - builder.addAll(((ZPathImpl)base).nodes); - } - else - { + if (base != null) { + if (base instanceof ZPathImpl) { + builder.addAll(((ZPathImpl) base).nodes); + } else { builder.addAll(Splitter.on(PATH_SEPARATOR).omitEmptyStrings().splitToList(base.fullPath())); } - } - else - { + } else { builder.add(PATH_SEPARATOR); } List nodes = builder.addAll(names).build(); @@ -108,133 +89,110 @@ public static ZPath from(ZPath base, List names) } @Override - public ZPath child(Object child) - { + public ZPath child(Object child) { return new ZPathImpl(nodes, NodeName.nameFrom(child)); } @Override - public ZPath parent() - { + public ZPath parent() { checkRootAccess(); - if ( parent == null ) - { + if (parent == null) { parent = new ZPathImpl(nodes.subList(0, nodes.size() - 1), null); } return parent; } @Override - public boolean isRoot() - { + public boolean isRoot() { return nodes.size() == 1; } @Override - public boolean startsWith(ZPath path) - { + public boolean startsWith(ZPath path) { ZPathImpl rhs; - if ( path instanceof ZPathImpl ) - { - rhs = (ZPathImpl)path; - } - else - { + if (path instanceof ZPathImpl) { + rhs = (ZPathImpl) path; + } else { rhs = parseInternal(path.fullPath(), s -> s); } - return (nodes.size() >= rhs.nodes.size()) && nodes.subList(0, rhs.nodes.size()).equals(rhs.nodes); + return (nodes.size() >= rhs.nodes.size()) + && nodes.subList(0, rhs.nodes.size()).equals(rhs.nodes); } @Override - public Pattern toSchemaPathPattern() - { - if ( schema == null ) - { + public Pattern toSchemaPathPattern() { + if (schema == null) { schema = Pattern.compile(buildFullPath(s -> isParameter(s) ? ".*" : s)); } return schema; } @Override - public String fullPath() - { + public String fullPath() { checkResolved(); - if ( fullPath == null ) - { + if (fullPath == null) { fullPath = buildFullPath(s -> s); } return fullPath; } @Override - public String nodeName() - { + public String nodeName() { return nodes.get(nodes.size() - 1); } @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; } - ZPathImpl zPaths = (ZPathImpl)o; + ZPathImpl zPaths = (ZPathImpl) o; return nodes.equals(zPaths.nodes); } @Override - public int hashCode() - { + public int hashCode() { return nodes.hashCode(); } @Override - public String toString() - { - return nodes.subList(1, nodes.size()) - .stream().map(name -> isParameter(name) ? name.substring(1) : name) - .collect(Collectors.joining(PATH_SEPARATOR, PATH_SEPARATOR, "")); + public String toString() { + return nodes.subList(1, nodes.size()).stream() + .map(name -> isParameter(name) ? name.substring(1) : name) + .collect(Collectors.joining(PATH_SEPARATOR, PATH_SEPARATOR, "")); } @Override - public ZPath resolved(List parameters) - { + public ZPath resolved(List parameters) { Iterator iterator = parameters.iterator(); List nodeNames = nodes.stream() - .map(name -> { - if ( isParameter(name) && iterator.hasNext() ) - { - return NodeName.nameFrom(iterator.next()); - } - return name; - }) - .collect(Collectors.toList()); + .map(name -> { + if (isParameter(name) && iterator.hasNext()) { + return NodeName.nameFrom(iterator.next()); + } + return name; + }) + .collect(Collectors.toList()); return new ZPathImpl(nodeNames, null); } @Override - public boolean isResolved() - { + public boolean isResolved() { return isResolved; } - private static boolean isParameter(String name) - { + private static boolean isParameter(String name) { return (name.length() > 1) && name.startsWith(PATH_SEPARATOR); } - private ZPathImpl(List nodes, String child) - { + private ZPathImpl(List nodes, String child) { ImmutableList.Builder builder = ImmutableList.builder().addAll(nodes); - if ( child != null ) - { + if (child != null) { validate(child); builder.add(child); } @@ -242,45 +200,35 @@ private ZPathImpl(List nodes, String child) isResolved = this.nodes.stream().noneMatch(ZPathImpl::isParameter); } - private void checkRootAccess() - { - if ( isRoot() ) - { + private void checkRootAccess() { + if (isRoot()) { throw new NoSuchElementException("The root has no parent"); } } - private void checkResolved() - { - if ( !isResolved) - { + private void checkResolved() { + if (!isResolved) { throw new IllegalStateException("This ZPath has not been resolved: " + toString()); } } - private static void validate(String nodeName) - { - if ( isParameter(Objects.requireNonNull(nodeName, "nodeName cannot be null")) ) - { + private static void validate(String nodeName) { + if (isParameter(Objects.requireNonNull(nodeName, "nodeName cannot be null"))) { return; } - if ( nodeName.equals(PATH_SEPARATOR) ) - { + if (nodeName.equals(PATH_SEPARATOR)) { return; } PathUtils.validatePath(PATH_SEPARATOR + nodeName); } - private String buildFullPath(UnaryOperator filter) - { + private String buildFullPath(UnaryOperator filter) { boolean addSeparator = false; StringBuilder str = new StringBuilder(); int size = nodes.size(); int parameterIndex = 0; - for ( int i = 0; i < size; ++i ) - { - if ( i > 1 ) - { + for (int i = 0; i < size; ++i) { + if (i > 1) { str.append(PATH_SEPARATOR); } str.append(filter.apply(nodes.get(i))); diff --git a/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedModelSpec.java b/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedModelSpec.java index a1102cad9..961fed91f 100644 --- a/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedModelSpec.java +++ b/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedModelSpec.java @@ -46,8 +46,7 @@ *

    */ @FunctionalInterface -public interface TypedModelSpec -{ +public interface TypedModelSpec { /** * Resolve into a ZPath using the given parameter * @@ -65,8 +64,7 @@ public interface TypedModelSpec * @param path typed path * @return new TypedModelSpec */ - static TypedModelSpec from(ModelSpecBuilder builder, TypedZPath path) - { + static TypedModelSpec from(ModelSpecBuilder builder, TypedZPath path) { return p1 -> builder.withPath(path.resolved(p1)).build(); } @@ -80,8 +78,7 @@ static TypedModelSpec from(ModelSpecBuilder builder, TypedZPat * @param pathWithIds typed path * @return new TypedModelSpec */ - static TypedModelSpec from(ModelSpecBuilder builder, String pathWithIds) - { + static TypedModelSpec from(ModelSpecBuilder builder, String pathWithIds) { TypedZPath zPath = TypedZPath.from(pathWithIds); return p1 -> builder.withPath(zPath.resolved(p1)).build(); } diff --git a/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedModelSpec0.java b/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedModelSpec0.java index 88cb9b8cd..b591703f6 100644 --- a/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedModelSpec0.java +++ b/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedModelSpec0.java @@ -26,8 +26,7 @@ * Same as {@link TypedModelSpec}, but with 0 parameters */ @FunctionalInterface -public interface TypedModelSpec0 -{ +public interface TypedModelSpec0 { ModelSpec resolved(); /** @@ -39,8 +38,7 @@ public interface TypedModelSpec0 * @param path typed path * @return new TypedModelSpec */ - static TypedModelSpec0 from(ModelSpecBuilder builder, TypedZPath0 path) - { + static TypedModelSpec0 from(ModelSpecBuilder builder, TypedZPath0 path) { return () -> builder.withPath(path.resolved()).build(); } @@ -54,8 +52,7 @@ static TypedModelSpec0 from(ModelSpecBuilder builder, TypedZPath0 path * @param pathWithIds typed path * @return new TypedModelSpec */ - static TypedModelSpec0 from(ModelSpecBuilder builder, String pathWithIds) - { + static TypedModelSpec0 from(ModelSpecBuilder builder, String pathWithIds) { TypedZPath0 zPath = TypedZPath0.from(pathWithIds); return () -> builder.withPath(zPath.resolved()).build(); } diff --git a/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedModelSpec10.java b/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedModelSpec10.java index c503e50d2..2cfaf5657 100644 --- a/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedModelSpec10.java +++ b/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedModelSpec10.java @@ -26,8 +26,7 @@ * Same as {@link org.apache.curator.x.async.modeled.typed.TypedModelSpec}, but with 10 parameters */ @FunctionalInterface -public interface TypedModelSpec10 -{ +public interface TypedModelSpec10 { ModelSpec resolved(P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6, P7 p7, P8 p8, P9 p9, P10 p10); /** @@ -39,9 +38,12 @@ public interface TypedModelSpec10 * @param path typed path * @return new TypedModelSpec */ - static TypedModelSpec10 from(ModelSpecBuilder builder, TypedZPath10 path) - { - return (p1, p2, p3, p4, p5, p6, p7, p8, p9, p10) -> builder.withPath(path.resolved(p1, p2, p3, p4, p5, p6, p7, p8, p9, p10)).build(); + static + TypedModelSpec10 from( + ModelSpecBuilder builder, TypedZPath10 path) { + return (p1, p2, p3, p4, p5, p6, p7, p8, p9, p10) -> builder.withPath( + path.resolved(p1, p2, p3, p4, p5, p6, p7, p8, p9, p10)) + .build(); } /** @@ -54,9 +56,12 @@ static TypedModelSpec10 TypedModelSpec10 from(ModelSpecBuilder builder, String pathWithIds) - { + static + TypedModelSpec10 from( + ModelSpecBuilder builder, String pathWithIds) { TypedZPath10 zPath = TypedZPath10.from(pathWithIds); - return (p1, p2, p3, p4, p5, p6, p7, p8, p9, p10) -> builder.withPath(zPath.resolved(p1, p2, p3, p4, p5, p6, p7, p8, p9, p10)).build(); + return (p1, p2, p3, p4, p5, p6, p7, p8, p9, p10) -> builder.withPath( + zPath.resolved(p1, p2, p3, p4, p5, p6, p7, p8, p9, p10)) + .build(); } } diff --git a/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedModelSpec2.java b/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedModelSpec2.java index eb13131df..04b51e1f0 100644 --- a/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedModelSpec2.java +++ b/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedModelSpec2.java @@ -26,8 +26,7 @@ * Same as {@link org.apache.curator.x.async.modeled.typed.TypedModelSpec}, but with 2 parameters */ @FunctionalInterface -public interface TypedModelSpec2 -{ +public interface TypedModelSpec2 { ModelSpec resolved(P1 p1, P2 p2); /** @@ -39,8 +38,7 @@ public interface TypedModelSpec2 * @param path typed path * @return new TypedModelSpec */ - static TypedModelSpec2 from(ModelSpecBuilder builder, TypedZPath2 path) - { + static TypedModelSpec2 from(ModelSpecBuilder builder, TypedZPath2 path) { return (p1, p2) -> builder.withPath(path.resolved(p1, p2)).build(); } @@ -54,8 +52,7 @@ static TypedModelSpec2 from(ModelSpecBuilder builder, * @param pathWithIds typed path * @return new TypedModelSpec */ - static TypedModelSpec2 from(ModelSpecBuilder builder, String pathWithIds) - { + static TypedModelSpec2 from(ModelSpecBuilder builder, String pathWithIds) { TypedZPath2 zPath = TypedZPath2.from(pathWithIds); return (p1, p2) -> builder.withPath(zPath.resolved(p1, p2)).build(); } diff --git a/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedModelSpec3.java b/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedModelSpec3.java index d06ca966d..304db31ba 100644 --- a/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedModelSpec3.java +++ b/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedModelSpec3.java @@ -26,8 +26,7 @@ * Same as {@link org.apache.curator.x.async.modeled.typed.TypedModelSpec}, but with 3 parameters */ @FunctionalInterface -public interface TypedModelSpec3 -{ +public interface TypedModelSpec3 { ModelSpec resolved(P1 p1, P2 p2, P3 p3); /** @@ -39,8 +38,8 @@ public interface TypedModelSpec3 * @param path typed path * @return new TypedModelSpec */ - static TypedModelSpec3 from(ModelSpecBuilder builder, TypedZPath3 path) - { + static TypedModelSpec3 from( + ModelSpecBuilder builder, TypedZPath3 path) { return (p1, p2, p3) -> builder.withPath(path.resolved(p1, p2, p3)).build(); } @@ -54,8 +53,7 @@ static TypedModelSpec3 from(ModelSpecBuilder b * @param pathWithIds typed path * @return new TypedModelSpec */ - static TypedModelSpec3 from(ModelSpecBuilder builder, String pathWithIds) - { + static TypedModelSpec3 from(ModelSpecBuilder builder, String pathWithIds) { TypedZPath3 zPath = TypedZPath3.from(pathWithIds); return (p1, p2, p3) -> builder.withPath(zPath.resolved(p1, p2, p3)).build(); } diff --git a/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedModelSpec4.java b/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedModelSpec4.java index fece71e9f..82aa99178 100644 --- a/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedModelSpec4.java +++ b/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedModelSpec4.java @@ -26,8 +26,7 @@ * Same as {@link org.apache.curator.x.async.modeled.typed.TypedModelSpec}, but with 4 parameters */ @FunctionalInterface -public interface TypedModelSpec4 -{ +public interface TypedModelSpec4 { ModelSpec resolved(P1 p1, P2 p2, P3 p3, P4 p4); /** @@ -39,9 +38,10 @@ public interface TypedModelSpec4 * @param path typed path * @return new TypedModelSpec */ - static TypedModelSpec4 from(ModelSpecBuilder builder, TypedZPath4 path) - { - return (p1, p2, p3, p4) -> builder.withPath(path.resolved(p1, p2, p3, p4)).build(); + static TypedModelSpec4 from( + ModelSpecBuilder builder, TypedZPath4 path) { + return (p1, p2, p3, p4) -> + builder.withPath(path.resolved(p1, p2, p3, p4)).build(); } /** @@ -54,9 +54,10 @@ static TypedModelSpec4 from(ModelSpecBuil * @param pathWithIds typed path * @return new TypedModelSpec */ - static TypedModelSpec4 from(ModelSpecBuilder builder, String pathWithIds) - { + static TypedModelSpec4 from( + ModelSpecBuilder builder, String pathWithIds) { TypedZPath4 zPath = TypedZPath4.from(pathWithIds); - return (p1, p2, p3, p4) -> builder.withPath(zPath.resolved(p1, p2, p3, p4)).build(); + return (p1, p2, p3, p4) -> + builder.withPath(zPath.resolved(p1, p2, p3, p4)).build(); } } diff --git a/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedModelSpec5.java b/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedModelSpec5.java index b96489a72..377cb48c9 100644 --- a/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedModelSpec5.java +++ b/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedModelSpec5.java @@ -26,8 +26,7 @@ * Same as {@link org.apache.curator.x.async.modeled.typed.TypedModelSpec}, but with 5 parameters */ @FunctionalInterface -public interface TypedModelSpec5 -{ +public interface TypedModelSpec5 { ModelSpec resolved(P1 p1, P2 p2, P3 p3, P4 p4, P5 p5); /** @@ -39,9 +38,10 @@ public interface TypedModelSpec5 * @param path typed path * @return new TypedModelSpec */ - static TypedModelSpec5 from(ModelSpecBuilder builder, TypedZPath5 path) - { - return (p1, p2, p3, p4, p5) -> builder.withPath(path.resolved(p1, p2, p3, p4, p5)).build(); + static TypedModelSpec5 from( + ModelSpecBuilder builder, TypedZPath5 path) { + return (p1, p2, p3, p4, p5) -> + builder.withPath(path.resolved(p1, p2, p3, p4, p5)).build(); } /** @@ -54,9 +54,10 @@ static TypedModelSpec5 from(Model * @param pathWithIds typed path * @return new TypedModelSpec */ - static TypedModelSpec5 from(ModelSpecBuilder builder, String pathWithIds) - { + static TypedModelSpec5 from( + ModelSpecBuilder builder, String pathWithIds) { TypedZPath5 zPath = TypedZPath5.from(pathWithIds); - return (p1, p2, p3, p4, p5) -> builder.withPath(zPath.resolved(p1, p2, p3, p4, p5)).build(); + return (p1, p2, p3, p4, p5) -> + builder.withPath(zPath.resolved(p1, p2, p3, p4, p5)).build(); } } diff --git a/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedModelSpec6.java b/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedModelSpec6.java index e6cd38af1..2cf8380b3 100644 --- a/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedModelSpec6.java +++ b/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedModelSpec6.java @@ -26,8 +26,7 @@ * Same as {@link org.apache.curator.x.async.modeled.typed.TypedModelSpec}, but with 6 parameters */ @FunctionalInterface -public interface TypedModelSpec6 -{ +public interface TypedModelSpec6 { ModelSpec resolved(P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6); /** @@ -39,9 +38,10 @@ public interface TypedModelSpec6 * @param path typed path * @return new TypedModelSpec */ - static TypedModelSpec6 from(ModelSpecBuilder builder, TypedZPath6 path) - { - return (p1, p2, p3, p4, p5, p6) -> builder.withPath(path.resolved(p1, p2, p3, p4, p5, p6)).build(); + static TypedModelSpec6 from( + ModelSpecBuilder builder, TypedZPath6 path) { + return (p1, p2, p3, p4, p5, p6) -> + builder.withPath(path.resolved(p1, p2, p3, p4, p5, p6)).build(); } /** @@ -54,9 +54,10 @@ static TypedModelSpec6 fr * @param pathWithIds typed path * @return new TypedModelSpec */ - static TypedModelSpec6 from(ModelSpecBuilder builder, String pathWithIds) - { + static TypedModelSpec6 from( + ModelSpecBuilder builder, String pathWithIds) { TypedZPath6 zPath = TypedZPath6.from(pathWithIds); - return (p1, p2, p3, p4, p5, p6) -> builder.withPath(zPath.resolved(p1, p2, p3, p4, p5, p6)).build(); + return (p1, p2, p3, p4, p5, p6) -> + builder.withPath(zPath.resolved(p1, p2, p3, p4, p5, p6)).build(); } } diff --git a/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedModelSpec7.java b/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedModelSpec7.java index 60d9c9ed3..8cc9b057d 100644 --- a/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedModelSpec7.java +++ b/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedModelSpec7.java @@ -26,8 +26,7 @@ * Same as {@link org.apache.curator.x.async.modeled.typed.TypedModelSpec}, but with 7 parameters */ @FunctionalInterface -public interface TypedModelSpec7 -{ +public interface TypedModelSpec7 { ModelSpec resolved(P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6, P7 p7); /** @@ -39,9 +38,10 @@ public interface TypedModelSpec7 * @param path typed path * @return new TypedModelSpec */ - static TypedModelSpec7 from(ModelSpecBuilder builder, TypedZPath7 path) - { - return (p1, p2, p3, p4, p5, p6, p7) -> builder.withPath(path.resolved(p1, p2, p3, p4, p5, p6, p7)).build(); + static TypedModelSpec7 from( + ModelSpecBuilder builder, TypedZPath7 path) { + return (p1, p2, p3, p4, p5, p6, p7) -> + builder.withPath(path.resolved(p1, p2, p3, p4, p5, p6, p7)).build(); } /** @@ -54,9 +54,10 @@ static TypedModelSpec7 TypedModelSpec7 from(ModelSpecBuilder builder, String pathWithIds) - { + static TypedModelSpec7 from( + ModelSpecBuilder builder, String pathWithIds) { TypedZPath7 zPath = TypedZPath7.from(pathWithIds); - return (p1, p2, p3, p4, p5, p6, p7) -> builder.withPath(zPath.resolved(p1, p2, p3, p4, p5, p6, p7)).build(); + return (p1, p2, p3, p4, p5, p6, p7) -> + builder.withPath(zPath.resolved(p1, p2, p3, p4, p5, p6, p7)).build(); } } diff --git a/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedModelSpec8.java b/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedModelSpec8.java index 6ffdcca3e..acfd5b3c8 100644 --- a/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedModelSpec8.java +++ b/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedModelSpec8.java @@ -26,8 +26,7 @@ * Same as {@link org.apache.curator.x.async.modeled.typed.TypedModelSpec}, but with 8 parameters */ @FunctionalInterface -public interface TypedModelSpec8 -{ +public interface TypedModelSpec8 { ModelSpec resolved(P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6, P7 p7, P8 p8); /** @@ -39,9 +38,10 @@ public interface TypedModelSpec8 * @param path typed path * @return new TypedModelSpec */ - static TypedModelSpec8 from(ModelSpecBuilder builder, TypedZPath8 path) - { - return (p1, p2, p3, p4, p5, p6, p7, p8) -> builder.withPath(path.resolved(p1, p2, p3, p4, p5, p6, p7, p8)).build(); + static TypedModelSpec8 from( + ModelSpecBuilder builder, TypedZPath8 path) { + return (p1, p2, p3, p4, p5, p6, p7, p8) -> + builder.withPath(path.resolved(p1, p2, p3, p4, p5, p6, p7, p8)).build(); } /** @@ -54,9 +54,10 @@ static TypedModelSpec8 TypedModelSpec8 from(ModelSpecBuilder builder, String pathWithIds) - { + static TypedModelSpec8 from( + ModelSpecBuilder builder, String pathWithIds) { TypedZPath8 zPath = TypedZPath8.from(pathWithIds); - return (p1, p2, p3, p4, p5, p6, p7, p8) -> builder.withPath(zPath.resolved(p1, p2, p3, p4, p5, p6, p7, p8)).build(); + return (p1, p2, p3, p4, p5, p6, p7, p8) -> + builder.withPath(zPath.resolved(p1, p2, p3, p4, p5, p6, p7, p8)).build(); } } diff --git a/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedModelSpec9.java b/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedModelSpec9.java index 0cd9a17b4..52ea625ad 100644 --- a/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedModelSpec9.java +++ b/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedModelSpec9.java @@ -26,8 +26,7 @@ * Same as {@link org.apache.curator.x.async.modeled.typed.TypedModelSpec}, but with 9 parameters */ @FunctionalInterface -public interface TypedModelSpec9 -{ +public interface TypedModelSpec9 { ModelSpec resolved(P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6, P7 p7, P8 p8, P9 p9); /** @@ -39,9 +38,11 @@ public interface TypedModelSpec9 * @param path typed path * @return new TypedModelSpec */ - static TypedModelSpec9 from(ModelSpecBuilder builder, TypedZPath9 path) - { - return (p1, p2, p3, p4, p5, p6, p7, p8, p9) -> builder.withPath(path.resolved(p1, p2, p3, p4, p5, p6, p7, p8, p9)).build(); + static TypedModelSpec9 from( + ModelSpecBuilder builder, TypedZPath9 path) { + return (p1, p2, p3, p4, p5, p6, p7, p8, p9) -> builder.withPath( + path.resolved(p1, p2, p3, p4, p5, p6, p7, p8, p9)) + .build(); } /** @@ -54,9 +55,11 @@ static TypedModelSpec9 TypedModelSpec9 from(ModelSpecBuilder builder, String pathWithIds) - { + static TypedModelSpec9 from( + ModelSpecBuilder builder, String pathWithIds) { TypedZPath9 zPath = TypedZPath9.from(pathWithIds); - return (p1, p2, p3, p4, p5, p6, p7, p8, p9) -> builder.withPath(zPath.resolved(p1, p2, p3, p4, p5, p6, p7, p8, p9)).build(); + return (p1, p2, p3, p4, p5, p6, p7, p8, p9) -> builder.withPath( + zPath.resolved(p1, p2, p3, p4, p5, p6, p7, p8, p9)) + .build(); } } diff --git a/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedModeledFramework.java b/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedModeledFramework.java index 1184af076..9dd840d33 100644 --- a/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedModeledFramework.java +++ b/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedModeledFramework.java @@ -51,8 +51,7 @@ *

    */ @FunctionalInterface -public interface TypedModeledFramework -{ +public interface TypedModeledFramework { /** * Resolve into a ModeledFramework using the given parameter * @@ -71,9 +70,12 @@ public interface TypedModeledFramework * @param modelSpec TypedModelSpec * @return new TypedModeledFramework */ - static TypedModeledFramework from(ModeledFrameworkBuilder frameworkBuilder, TypedModelSpec modelSpec) - { - return (client, p1) -> frameworkBuilder.withClient(client).withModelSpec(modelSpec.resolved(p1)).build(); + static TypedModeledFramework from( + ModeledFrameworkBuilder frameworkBuilder, TypedModelSpec modelSpec) { + return (client, p1) -> frameworkBuilder + .withClient(client) + .withModelSpec(modelSpec.resolved(p1)) + .build(); } /** @@ -86,9 +88,12 @@ static TypedModeledFramework from(ModeledFrameworkBuilder fram * @param pathWithIds path with {XXXX} parameters * @return new TypedModeledFramework */ - static TypedModeledFramework from(ModeledFrameworkBuilder frameworkBuilder, ModelSpecBuilder modelSpecBuilder, String pathWithIds) - { + static TypedModeledFramework from( + ModeledFrameworkBuilder frameworkBuilder, ModelSpecBuilder modelSpecBuilder, String pathWithIds) { TypedModelSpec typedModelSpec = TypedModelSpec.from(modelSpecBuilder, pathWithIds); - return (client, p1) -> frameworkBuilder.withClient(client).withModelSpec(typedModelSpec.resolved(p1)).build(); + return (client, p1) -> frameworkBuilder + .withClient(client) + .withModelSpec(typedModelSpec.resolved(p1)) + .build(); } } diff --git a/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedModeledFramework0.java b/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedModeledFramework0.java index 8d8a4a65d..e6be548e1 100644 --- a/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedModeledFramework0.java +++ b/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedModeledFramework0.java @@ -28,8 +28,7 @@ * Same as {@link TypedModeledFramework}, but with 0 parameters */ @FunctionalInterface -public interface TypedModeledFramework0 -{ +public interface TypedModeledFramework0 { ModeledFramework resolved(AsyncCuratorFramework client); /** @@ -41,9 +40,12 @@ public interface TypedModeledFramework0 * @param modelSpec TypedModelSpec * @return new TypedModeledFramework */ - static TypedModeledFramework0 from(ModeledFrameworkBuilder frameworkBuilder, TypedModelSpec0 modelSpec) - { - return (client) -> frameworkBuilder.withClient(client).withModelSpec(modelSpec.resolved()).build(); + static TypedModeledFramework0 from( + ModeledFrameworkBuilder frameworkBuilder, TypedModelSpec0 modelSpec) { + return (client) -> frameworkBuilder + .withClient(client) + .withModelSpec(modelSpec.resolved()) + .build(); } /** @@ -56,9 +58,12 @@ static TypedModeledFramework0 from(ModeledFrameworkBuilder frameworkBu * @param pathWithIds path with {XXXX} parameters * @return new TypedModeledFramework */ - static TypedModeledFramework0 from(ModeledFrameworkBuilder frameworkBuilder, ModelSpecBuilder modelSpecBuilder, String pathWithIds) - { + static TypedModeledFramework0 from( + ModeledFrameworkBuilder frameworkBuilder, ModelSpecBuilder modelSpecBuilder, String pathWithIds) { TypedModelSpec0 typedModelSpec = TypedModelSpec0.from(modelSpecBuilder, pathWithIds); - return (client) -> frameworkBuilder.withClient(client).withModelSpec(typedModelSpec.resolved()).build(); + return (client) -> frameworkBuilder + .withClient(client) + .withModelSpec(typedModelSpec.resolved()) + .build(); } } diff --git a/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedModeledFramework10.java b/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedModeledFramework10.java index 22ace32c5..5900d4764 100644 --- a/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedModeledFramework10.java +++ b/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedModeledFramework10.java @@ -28,9 +28,9 @@ * Same as {@link org.apache.curator.x.async.modeled.typed.TypedModeledFramework}, but with 10 parameters */ @FunctionalInterface -public interface TypedModeledFramework10 -{ - ModeledFramework resolved(AsyncCuratorFramework client, P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6, P7 p7, P8 p8, P9 p9, P10 p10); +public interface TypedModeledFramework10 { + ModeledFramework resolved( + AsyncCuratorFramework client, P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6, P7 p7, P8 p8, P9 p9, P10 p10); /** * Return a new TypedModeledFramework using the given modeled framework builder and typed model spec. @@ -41,9 +41,14 @@ public interface TypedModeledFramework10 TypedModeledFramework10 from(ModeledFrameworkBuilder frameworkBuilder, TypedModelSpec10 modelSpec) - { - return (client, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10) -> frameworkBuilder.withClient(client).withModelSpec(modelSpec.resolved(p1, p2, p3, p4, p5, p6, p7, p8, p9, p10)).build(); + static + TypedModeledFramework10 from( + ModeledFrameworkBuilder frameworkBuilder, + TypedModelSpec10 modelSpec) { + return (client, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10) -> frameworkBuilder + .withClient(client) + .withModelSpec(modelSpec.resolved(p1, p2, p3, p4, p5, p6, p7, p8, p9, p10)) + .build(); } /** @@ -56,9 +61,16 @@ static TypedModeledFramework10 TypedModeledFramework10 from(ModeledFrameworkBuilder frameworkBuilder, ModelSpecBuilder modelSpecBuilder, String pathWithIds) - { - TypedModelSpec10 typedModelSpec = TypedModelSpec10.from(modelSpecBuilder, pathWithIds); - return (client, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10) -> frameworkBuilder.withClient(client).withModelSpec(typedModelSpec.resolved(p1, p2, p3, p4, p5, p6, p7, p8, p9, p10)).build(); + static + TypedModeledFramework10 from( + ModeledFrameworkBuilder frameworkBuilder, + ModelSpecBuilder modelSpecBuilder, + String pathWithIds) { + TypedModelSpec10 typedModelSpec = + TypedModelSpec10.from(modelSpecBuilder, pathWithIds); + return (client, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10) -> frameworkBuilder + .withClient(client) + .withModelSpec(typedModelSpec.resolved(p1, p2, p3, p4, p5, p6, p7, p8, p9, p10)) + .build(); } } diff --git a/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedModeledFramework2.java b/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedModeledFramework2.java index 285e817db..4c6a010bc 100644 --- a/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedModeledFramework2.java +++ b/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedModeledFramework2.java @@ -28,8 +28,7 @@ * Same as {@link org.apache.curator.x.async.modeled.typed.TypedModeledFramework}, but with 2 parameters */ @FunctionalInterface -public interface TypedModeledFramework2 -{ +public interface TypedModeledFramework2 { ModeledFramework resolved(AsyncCuratorFramework client, P1 p1, P2 p2); /** @@ -41,9 +40,12 @@ public interface TypedModeledFramework2 * @param modelSpec TypedModelSpec * @return new TypedModeledFramework */ - static TypedModeledFramework2 from(ModeledFrameworkBuilder frameworkBuilder, TypedModelSpec2 modelSpec) - { - return (client, p1, p2) -> frameworkBuilder.withClient(client).withModelSpec(modelSpec.resolved(p1, p2)).build(); + static TypedModeledFramework2 from( + ModeledFrameworkBuilder frameworkBuilder, TypedModelSpec2 modelSpec) { + return (client, p1, p2) -> frameworkBuilder + .withClient(client) + .withModelSpec(modelSpec.resolved(p1, p2)) + .build(); } /** @@ -56,9 +58,12 @@ static TypedModeledFramework2 from(ModeledFrameworkBuilde * @param pathWithIds path with {XXXX} parameters * @return new TypedModeledFramework */ - static TypedModeledFramework2 from(ModeledFrameworkBuilder frameworkBuilder, ModelSpecBuilder modelSpecBuilder, String pathWithIds) - { + static TypedModeledFramework2 from( + ModeledFrameworkBuilder frameworkBuilder, ModelSpecBuilder modelSpecBuilder, String pathWithIds) { TypedModelSpec2 typedModelSpec = TypedModelSpec2.from(modelSpecBuilder, pathWithIds); - return (client, p1, p2) -> frameworkBuilder.withClient(client).withModelSpec(typedModelSpec.resolved(p1, p2)).build(); + return (client, p1, p2) -> frameworkBuilder + .withClient(client) + .withModelSpec(typedModelSpec.resolved(p1, p2)) + .build(); } } diff --git a/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedModeledFramework3.java b/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedModeledFramework3.java index 109e72860..a4aec7c20 100644 --- a/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedModeledFramework3.java +++ b/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedModeledFramework3.java @@ -28,8 +28,7 @@ * Same as {@link org.apache.curator.x.async.modeled.typed.TypedModeledFramework}, but with 3 parameters */ @FunctionalInterface -public interface TypedModeledFramework3 -{ +public interface TypedModeledFramework3 { ModeledFramework resolved(AsyncCuratorFramework client, P1 p1, P2 p2, P3 p3); /** @@ -41,9 +40,12 @@ public interface TypedModeledFramework3 * @param modelSpec TypedModelSpec * @return new TypedModeledFramework */ - static TypedModeledFramework3 from(ModeledFrameworkBuilder frameworkBuilder, TypedModelSpec3 modelSpec) - { - return (client, p1, p2, p3) -> frameworkBuilder.withClient(client).withModelSpec(modelSpec.resolved(p1, p2, p3)).build(); + static TypedModeledFramework3 from( + ModeledFrameworkBuilder frameworkBuilder, TypedModelSpec3 modelSpec) { + return (client, p1, p2, p3) -> frameworkBuilder + .withClient(client) + .withModelSpec(modelSpec.resolved(p1, p2, p3)) + .build(); } /** @@ -56,9 +58,12 @@ static TypedModeledFramework3 from(ModeledFramewo * @param pathWithIds path with {XXXX} parameters * @return new TypedModeledFramework */ - static TypedModeledFramework3 from(ModeledFrameworkBuilder frameworkBuilder, ModelSpecBuilder modelSpecBuilder, String pathWithIds) - { + static TypedModeledFramework3 from( + ModeledFrameworkBuilder frameworkBuilder, ModelSpecBuilder modelSpecBuilder, String pathWithIds) { TypedModelSpec3 typedModelSpec = TypedModelSpec3.from(modelSpecBuilder, pathWithIds); - return (client, p1, p2, p3) -> frameworkBuilder.withClient(client).withModelSpec(typedModelSpec.resolved(p1, p2, p3)).build(); + return (client, p1, p2, p3) -> frameworkBuilder + .withClient(client) + .withModelSpec(typedModelSpec.resolved(p1, p2, p3)) + .build(); } } diff --git a/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedModeledFramework4.java b/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedModeledFramework4.java index da3aa9660..c0332de63 100644 --- a/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedModeledFramework4.java +++ b/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedModeledFramework4.java @@ -28,8 +28,7 @@ * Same as {@link org.apache.curator.x.async.modeled.typed.TypedModeledFramework}, but with 4 parameters */ @FunctionalInterface -public interface TypedModeledFramework4 -{ +public interface TypedModeledFramework4 { ModeledFramework resolved(AsyncCuratorFramework client, P1 p1, P2 p2, P3 p3, P4 p4); /** @@ -41,9 +40,12 @@ public interface TypedModeledFramework4 * @param modelSpec TypedModelSpec * @return new TypedModeledFramework */ - static TypedModeledFramework4 from(ModeledFrameworkBuilder frameworkBuilder, TypedModelSpec4 modelSpec) - { - return (client, p1, p2, p3, p4) -> frameworkBuilder.withClient(client).withModelSpec(modelSpec.resolved(p1, p2, p3, p4)).build(); + static TypedModeledFramework4 from( + ModeledFrameworkBuilder frameworkBuilder, TypedModelSpec4 modelSpec) { + return (client, p1, p2, p3, p4) -> frameworkBuilder + .withClient(client) + .withModelSpec(modelSpec.resolved(p1, p2, p3, p4)) + .build(); } /** @@ -56,9 +58,12 @@ static TypedModeledFramework4 from(Modele * @param pathWithIds path with {XXXX} parameters * @return new TypedModeledFramework */ - static TypedModeledFramework4 from(ModeledFrameworkBuilder frameworkBuilder, ModelSpecBuilder modelSpecBuilder, String pathWithIds) - { + static TypedModeledFramework4 from( + ModeledFrameworkBuilder frameworkBuilder, ModelSpecBuilder modelSpecBuilder, String pathWithIds) { TypedModelSpec4 typedModelSpec = TypedModelSpec4.from(modelSpecBuilder, pathWithIds); - return (client, p1, p2, p3, p4) -> frameworkBuilder.withClient(client).withModelSpec(typedModelSpec.resolved(p1, p2, p3, p4)).build(); + return (client, p1, p2, p3, p4) -> frameworkBuilder + .withClient(client) + .withModelSpec(typedModelSpec.resolved(p1, p2, p3, p4)) + .build(); } } diff --git a/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedModeledFramework5.java b/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedModeledFramework5.java index 1abc78fb9..a2c111f9e 100644 --- a/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedModeledFramework5.java +++ b/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedModeledFramework5.java @@ -28,8 +28,7 @@ * Same as {@link org.apache.curator.x.async.modeled.typed.TypedModeledFramework}, but with 5 parameters */ @FunctionalInterface -public interface TypedModeledFramework5 -{ +public interface TypedModeledFramework5 { ModeledFramework resolved(AsyncCuratorFramework client, P1 p1, P2 p2, P3 p3, P4 p4, P5 p5); /** @@ -41,9 +40,12 @@ public interface TypedModeledFramework5 * @param modelSpec TypedModelSpec * @return new TypedModeledFramework */ - static TypedModeledFramework5 from(ModeledFrameworkBuilder frameworkBuilder, TypedModelSpec5 modelSpec) - { - return (client, p1, p2, p3, p4, p5) -> frameworkBuilder.withClient(client).withModelSpec(modelSpec.resolved(p1, p2, p3, p4, p5)).build(); + static TypedModeledFramework5 from( + ModeledFrameworkBuilder frameworkBuilder, TypedModelSpec5 modelSpec) { + return (client, p1, p2, p3, p4, p5) -> frameworkBuilder + .withClient(client) + .withModelSpec(modelSpec.resolved(p1, p2, p3, p4, p5)) + .build(); } /** @@ -56,9 +58,12 @@ static TypedModeledFramework5 fro * @param pathWithIds path with {XXXX} parameters * @return new TypedModeledFramework */ - static TypedModeledFramework5 from(ModeledFrameworkBuilder frameworkBuilder, ModelSpecBuilder modelSpecBuilder, String pathWithIds) - { + static TypedModeledFramework5 from( + ModeledFrameworkBuilder frameworkBuilder, ModelSpecBuilder modelSpecBuilder, String pathWithIds) { TypedModelSpec5 typedModelSpec = TypedModelSpec5.from(modelSpecBuilder, pathWithIds); - return (client, p1, p2, p3, p4, p5) -> frameworkBuilder.withClient(client).withModelSpec(typedModelSpec.resolved(p1, p2, p3, p4, p5)).build(); + return (client, p1, p2, p3, p4, p5) -> frameworkBuilder + .withClient(client) + .withModelSpec(typedModelSpec.resolved(p1, p2, p3, p4, p5)) + .build(); } } diff --git a/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedModeledFramework6.java b/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedModeledFramework6.java index 236d7db4e..836fde981 100644 --- a/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedModeledFramework6.java +++ b/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedModeledFramework6.java @@ -28,8 +28,7 @@ * Same as {@link org.apache.curator.x.async.modeled.typed.TypedModeledFramework}, but with 6 parameters */ @FunctionalInterface -public interface TypedModeledFramework6 -{ +public interface TypedModeledFramework6 { ModeledFramework resolved(AsyncCuratorFramework client, P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6); /** @@ -41,9 +40,12 @@ public interface TypedModeledFramework6 * @param modelSpec TypedModelSpec * @return new TypedModeledFramework */ - static TypedModeledFramework6 from(ModeledFrameworkBuilder frameworkBuilder, TypedModelSpec6 modelSpec) - { - return (client, p1, p2, p3, p4, p5, p6) -> frameworkBuilder.withClient(client).withModelSpec(modelSpec.resolved(p1, p2, p3, p4, p5, p6)).build(); + static TypedModeledFramework6 from( + ModeledFrameworkBuilder frameworkBuilder, TypedModelSpec6 modelSpec) { + return (client, p1, p2, p3, p4, p5, p6) -> frameworkBuilder + .withClient(client) + .withModelSpec(modelSpec.resolved(p1, p2, p3, p4, p5, p6)) + .build(); } /** @@ -56,9 +58,12 @@ static TypedModeledFramework6 TypedModeledFramework6 from(ModeledFrameworkBuilder frameworkBuilder, ModelSpecBuilder modelSpecBuilder, String pathWithIds) - { + static TypedModeledFramework6 from( + ModeledFrameworkBuilder frameworkBuilder, ModelSpecBuilder modelSpecBuilder, String pathWithIds) { TypedModelSpec6 typedModelSpec = TypedModelSpec6.from(modelSpecBuilder, pathWithIds); - return (client, p1, p2, p3, p4, p5, p6) -> frameworkBuilder.withClient(client).withModelSpec(typedModelSpec.resolved(p1, p2, p3, p4, p5, p6)).build(); + return (client, p1, p2, p3, p4, p5, p6) -> frameworkBuilder + .withClient(client) + .withModelSpec(typedModelSpec.resolved(p1, p2, p3, p4, p5, p6)) + .build(); } } diff --git a/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedModeledFramework7.java b/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedModeledFramework7.java index 938ab91c2..22c211c68 100644 --- a/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedModeledFramework7.java +++ b/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedModeledFramework7.java @@ -28,8 +28,7 @@ * Same as {@link org.apache.curator.x.async.modeled.typed.TypedModeledFramework}, but with 7 parameters */ @FunctionalInterface -public interface TypedModeledFramework7 -{ +public interface TypedModeledFramework7 { ModeledFramework resolved(AsyncCuratorFramework client, P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6, P7 p7); /** @@ -41,9 +40,12 @@ public interface TypedModeledFramework7 * @param modelSpec TypedModelSpec * @return new TypedModeledFramework */ - static TypedModeledFramework7 from(ModeledFrameworkBuilder frameworkBuilder, TypedModelSpec7 modelSpec) - { - return (client, p1, p2, p3, p4, p5, p6, p7) -> frameworkBuilder.withClient(client).withModelSpec(modelSpec.resolved(p1, p2, p3, p4, p5, p6, p7)).build(); + static TypedModeledFramework7 from( + ModeledFrameworkBuilder frameworkBuilder, TypedModelSpec7 modelSpec) { + return (client, p1, p2, p3, p4, p5, p6, p7) -> frameworkBuilder + .withClient(client) + .withModelSpec(modelSpec.resolved(p1, p2, p3, p4, p5, p6, p7)) + .build(); } /** @@ -56,9 +58,13 @@ static TypedModeledFramework7 TypedModeledFramework7 from(ModeledFrameworkBuilder frameworkBuilder, ModelSpecBuilder modelSpecBuilder, String pathWithIds) - { - TypedModelSpec7 typedModelSpec = TypedModelSpec7.from(modelSpecBuilder, pathWithIds); - return (client, p1, p2, p3, p4, p5, p6, p7) -> frameworkBuilder.withClient(client).withModelSpec(typedModelSpec.resolved(p1, p2, p3, p4, p5, p6, p7)).build(); + static TypedModeledFramework7 from( + ModeledFrameworkBuilder frameworkBuilder, ModelSpecBuilder modelSpecBuilder, String pathWithIds) { + TypedModelSpec7 typedModelSpec = + TypedModelSpec7.from(modelSpecBuilder, pathWithIds); + return (client, p1, p2, p3, p4, p5, p6, p7) -> frameworkBuilder + .withClient(client) + .withModelSpec(typedModelSpec.resolved(p1, p2, p3, p4, p5, p6, p7)) + .build(); } } diff --git a/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedModeledFramework8.java b/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedModeledFramework8.java index 526e77d0e..049fce0ee 100644 --- a/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedModeledFramework8.java +++ b/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedModeledFramework8.java @@ -28,8 +28,7 @@ * Same as {@link org.apache.curator.x.async.modeled.typed.TypedModeledFramework}, but with 8 parameters */ @FunctionalInterface -public interface TypedModeledFramework8 -{ +public interface TypedModeledFramework8 { ModeledFramework resolved(AsyncCuratorFramework client, P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6, P7 p7, P8 p8); /** @@ -41,9 +40,12 @@ public interface TypedModeledFramework8 * @param modelSpec TypedModelSpec * @return new TypedModeledFramework */ - static TypedModeledFramework8 from(ModeledFrameworkBuilder frameworkBuilder, TypedModelSpec8 modelSpec) - { - return (client, p1, p2, p3, p4, p5, p6, p7, p8) -> frameworkBuilder.withClient(client).withModelSpec(modelSpec.resolved(p1, p2, p3, p4, p5, p6, p7, p8)).build(); + static TypedModeledFramework8 from( + ModeledFrameworkBuilder frameworkBuilder, TypedModelSpec8 modelSpec) { + return (client, p1, p2, p3, p4, p5, p6, p7, p8) -> frameworkBuilder + .withClient(client) + .withModelSpec(modelSpec.resolved(p1, p2, p3, p4, p5, p6, p7, p8)) + .build(); } /** @@ -56,9 +58,13 @@ static TypedModeledFramework8 TypedModeledFramework8 from(ModeledFrameworkBuilder frameworkBuilder, ModelSpecBuilder modelSpecBuilder, String pathWithIds) - { - TypedModelSpec8 typedModelSpec = TypedModelSpec8.from(modelSpecBuilder, pathWithIds); - return (client, p1, p2, p3, p4, p5, p6, p7, p8) -> frameworkBuilder.withClient(client).withModelSpec(typedModelSpec.resolved(p1, p2, p3, p4, p5, p6, p7, p8)).build(); + static TypedModeledFramework8 from( + ModeledFrameworkBuilder frameworkBuilder, ModelSpecBuilder modelSpecBuilder, String pathWithIds) { + TypedModelSpec8 typedModelSpec = + TypedModelSpec8.from(modelSpecBuilder, pathWithIds); + return (client, p1, p2, p3, p4, p5, p6, p7, p8) -> frameworkBuilder + .withClient(client) + .withModelSpec(typedModelSpec.resolved(p1, p2, p3, p4, p5, p6, p7, p8)) + .build(); } } diff --git a/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedModeledFramework9.java b/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedModeledFramework9.java index b4704d668..55a2d070a 100644 --- a/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedModeledFramework9.java +++ b/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedModeledFramework9.java @@ -28,9 +28,9 @@ * Same as {@link org.apache.curator.x.async.modeled.typed.TypedModeledFramework}, but with 9 parameters */ @FunctionalInterface -public interface TypedModeledFramework9 -{ - ModeledFramework resolved(AsyncCuratorFramework client, P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6, P7 p7, P8 p8, P9 p9); +public interface TypedModeledFramework9 { + ModeledFramework resolved( + AsyncCuratorFramework client, P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6, P7 p7, P8 p8, P9 p9); /** * Return a new TypedModeledFramework using the given modeled framework builder and typed model spec. @@ -41,9 +41,13 @@ public interface TypedModeledFramework9 * @param modelSpec TypedModelSpec * @return new TypedModeledFramework */ - static TypedModeledFramework9 from(ModeledFrameworkBuilder frameworkBuilder, TypedModelSpec9 modelSpec) - { - return (client, p1, p2, p3, p4, p5, p6, p7, p8, p9) -> frameworkBuilder.withClient(client).withModelSpec(modelSpec.resolved(p1, p2, p3, p4, p5, p6, p7, p8, p9)).build(); + static TypedModeledFramework9 from( + ModeledFrameworkBuilder frameworkBuilder, + TypedModelSpec9 modelSpec) { + return (client, p1, p2, p3, p4, p5, p6, p7, p8, p9) -> frameworkBuilder + .withClient(client) + .withModelSpec(modelSpec.resolved(p1, p2, p3, p4, p5, p6, p7, p8, p9)) + .build(); } /** @@ -56,9 +60,13 @@ static TypedModeledFramework9 TypedModeledFramework9 from(ModeledFrameworkBuilder frameworkBuilder, ModelSpecBuilder modelSpecBuilder, String pathWithIds) - { - TypedModelSpec9 typedModelSpec = TypedModelSpec9.from(modelSpecBuilder, pathWithIds); - return (client, p1, p2, p3, p4, p5, p6, p7, p8, p9) -> frameworkBuilder.withClient(client).withModelSpec(typedModelSpec.resolved(p1, p2, p3, p4, p5, p6, p7, p8, p9)).build(); + static TypedModeledFramework9 from( + ModeledFrameworkBuilder frameworkBuilder, ModelSpecBuilder modelSpecBuilder, String pathWithIds) { + TypedModelSpec9 typedModelSpec = + TypedModelSpec9.from(modelSpecBuilder, pathWithIds); + return (client, p1, p2, p3, p4, p5, p6, p7, p8, p9) -> frameworkBuilder + .withClient(client) + .withModelSpec(typedModelSpec.resolved(p1, p2, p3, p4, p5, p6, p7, p8, p9)) + .build(); } } diff --git a/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedZPath.java b/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedZPath.java index e9631f4b7..bb24e37e9 100644 --- a/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedZPath.java +++ b/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedZPath.java @@ -59,8 +59,7 @@ *

    */ @FunctionalInterface -public interface TypedZPath -{ +public interface TypedZPath { /** * Resolve into a ZPath using the given parameter * @@ -75,8 +74,7 @@ public interface TypedZPath * @param pathWithIds path to pass to {@link org.apache.curator.x.async.modeled.ZPath#parseWithIds} * @return TypedZPath */ - static TypedZPath from(String pathWithIds) - { + static TypedZPath from(String pathWithIds) { return from(ZPath.parseWithIds(pathWithIds)); } @@ -86,8 +84,7 @@ static TypedZPath from(String pathWithIds) * @param path path to use * @return TypedZPath */ - static TypedZPath from(ZPath path) - { + static TypedZPath from(ZPath path) { return path::resolved; } } diff --git a/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedZPath0.java b/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedZPath0.java index 95c241eff..1810aad4f 100644 --- a/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedZPath0.java +++ b/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedZPath0.java @@ -25,8 +25,7 @@ * Same as {@link TypedZPath}, but with 0 parameters. */ @FunctionalInterface -public interface TypedZPath0 -{ +public interface TypedZPath0 { ZPath resolved(); /** @@ -35,8 +34,7 @@ public interface TypedZPath0 * @param pathWithIds path to pass to {@link org.apache.curator.x.async.modeled.ZPath#parseWithIds} * @return TypedZPath */ - static TypedZPath0 from(String pathWithIds) - { + static TypedZPath0 from(String pathWithIds) { return from(ZPath.parseWithIds(pathWithIds)); } @@ -46,8 +44,7 @@ static TypedZPath0 from(String pathWithIds) * @param path path to use * @return TypedZPath */ - static TypedZPath0 from(ZPath path) - { + static TypedZPath0 from(ZPath path) { return path::resolved; } } diff --git a/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedZPath10.java b/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedZPath10.java index 450553b28..1390bfb75 100644 --- a/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedZPath10.java +++ b/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedZPath10.java @@ -25,8 +25,7 @@ * Same as {@link org.apache.curator.x.async.modeled.typed.TypedZPath}, but with 10 parameters */ @FunctionalInterface -public interface TypedZPath10 -{ +public interface TypedZPath10 { ZPath resolved(T1 p1, T2 p2, T3 p3, T4 p4, T5 p5, T6 p6, T7 p7, T8 p8, T9 p9, T10 p10); /** @@ -35,8 +34,8 @@ public interface TypedZPath10 * @param pathWithIds path to pass to {@link org.apache.curator.x.async.modeled.ZPath#parseWithIds} * @return TypedZPath */ - static TypedZPath10 from(String pathWithIds) - { + static TypedZPath10 from( + String pathWithIds) { return from(ZPath.parseWithIds(pathWithIds)); } @@ -46,8 +45,8 @@ static TypedZPath10 TypedZPath10 from(ZPath path) - { + static TypedZPath10 from( + ZPath path) { return (p1, p2, p3, p4, p5, p6, p7, p8, p9, p10) -> path.resolved(p1, p2, p3, p4, p5, p6, p7, p8, p9, p10); } } diff --git a/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedZPath2.java b/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedZPath2.java index d5746bf70..42f6dfbf6 100644 --- a/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedZPath2.java +++ b/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedZPath2.java @@ -25,8 +25,7 @@ * Same as {@link org.apache.curator.x.async.modeled.typed.TypedZPath}, but with 2 parameters */ @FunctionalInterface -public interface TypedZPath2 -{ +public interface TypedZPath2 { ZPath resolved(T1 p1, T2 p2); /** @@ -35,8 +34,7 @@ public interface TypedZPath2 * @param pathWithIds path to pass to {@link org.apache.curator.x.async.modeled.ZPath#parseWithIds} * @return TypedZPath */ - static TypedZPath2 from(String pathWithIds) - { + static TypedZPath2 from(String pathWithIds) { return from(ZPath.parseWithIds(pathWithIds)); } @@ -46,8 +44,7 @@ static TypedZPath2 from(String pathWithIds) * @param path path to use * @return TypedZPath */ - static TypedZPath2 from(ZPath path) - { + static TypedZPath2 from(ZPath path) { return (p1, p2) -> path.resolved(p1, p2); } } diff --git a/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedZPath3.java b/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedZPath3.java index 3d244b67d..bbd019a68 100644 --- a/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedZPath3.java +++ b/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedZPath3.java @@ -25,8 +25,7 @@ * Same as {@link org.apache.curator.x.async.modeled.typed.TypedZPath}, but with 3 parameters */ @FunctionalInterface -public interface TypedZPath3 -{ +public interface TypedZPath3 { ZPath resolved(T1 p1, T2 p2, T3 p3); /** @@ -35,8 +34,7 @@ public interface TypedZPath3 * @param pathWithIds path to pass to {@link org.apache.curator.x.async.modeled.ZPath#parseWithIds} * @return TypedZPath */ - static TypedZPath3 from(String pathWithIds) - { + static TypedZPath3 from(String pathWithIds) { return from(ZPath.parseWithIds(pathWithIds)); } @@ -46,8 +44,7 @@ static TypedZPath3 from(String pathWithIds) * @param path path to use * @return TypedZPath */ - static TypedZPath3 from(ZPath path) - { + static TypedZPath3 from(ZPath path) { return (p1, p2, p3) -> path.resolved(p1, p2, p3); } } diff --git a/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedZPath4.java b/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedZPath4.java index c1314c9a0..660bdab79 100644 --- a/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedZPath4.java +++ b/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedZPath4.java @@ -25,8 +25,7 @@ * Same as {@link org.apache.curator.x.async.modeled.typed.TypedZPath}, but with 4 parameters */ @FunctionalInterface -public interface TypedZPath4 -{ +public interface TypedZPath4 { ZPath resolved(T1 p1, T2 p2, T3 p3, T4 p4); /** @@ -35,8 +34,7 @@ public interface TypedZPath4 * @param pathWithIds path to pass to {@link org.apache.curator.x.async.modeled.ZPath#parseWithIds} * @return TypedZPath */ - static TypedZPath4 from(String pathWithIds) - { + static TypedZPath4 from(String pathWithIds) { return from(ZPath.parseWithIds(pathWithIds)); } @@ -46,8 +44,7 @@ static TypedZPath4 from(String pathWithIds) * @param path path to use * @return TypedZPath */ - static TypedZPath4 from(ZPath path) - { + static TypedZPath4 from(ZPath path) { return (p1, p2, p3, p4) -> path.resolved(p1, p2, p3, p4); } } diff --git a/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedZPath5.java b/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedZPath5.java index 4841f320f..09041fe2b 100644 --- a/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedZPath5.java +++ b/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedZPath5.java @@ -25,8 +25,7 @@ * Same as {@link org.apache.curator.x.async.modeled.typed.TypedZPath}, but with 5 parameters */ @FunctionalInterface -public interface TypedZPath5 -{ +public interface TypedZPath5 { ZPath resolved(T1 p1, T2 p2, T3 p3, T4 p4, T5 p5); /** @@ -35,8 +34,7 @@ public interface TypedZPath5 * @param pathWithIds path to pass to {@link org.apache.curator.x.async.modeled.ZPath#parseWithIds} * @return TypedZPath */ - static TypedZPath5 from(String pathWithIds) - { + static TypedZPath5 from(String pathWithIds) { return from(ZPath.parseWithIds(pathWithIds)); } @@ -46,8 +44,7 @@ static TypedZPath5 from(String pathWith * @param path path to use * @return TypedZPath */ - static TypedZPath5 from(ZPath path) - { + static TypedZPath5 from(ZPath path) { return (p1, p2, p3, p4, p5) -> path.resolved(p1, p2, p3, p4, p5); } } diff --git a/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedZPath6.java b/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedZPath6.java index 08be396b4..fce5d8622 100644 --- a/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedZPath6.java +++ b/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedZPath6.java @@ -25,8 +25,7 @@ * Same as {@link org.apache.curator.x.async.modeled.typed.TypedZPath}, but with 6 parameters */ @FunctionalInterface -public interface TypedZPath6 -{ +public interface TypedZPath6 { ZPath resolved(T1 p1, T2 p2, T3 p3, T4 p4, T5 p5, T6 p6); /** @@ -35,8 +34,7 @@ public interface TypedZPath6 * @param pathWithIds path to pass to {@link org.apache.curator.x.async.modeled.ZPath#parseWithIds} * @return TypedZPath */ - static TypedZPath6 from(String pathWithIds) - { + static TypedZPath6 from(String pathWithIds) { return from(ZPath.parseWithIds(pathWithIds)); } @@ -46,8 +44,7 @@ static TypedZPath6 from(String * @param path path to use * @return TypedZPath */ - static TypedZPath6 from(ZPath path) - { + static TypedZPath6 from(ZPath path) { return (p1, p2, p3, p4, p5, p6) -> path.resolved(p1, p2, p3, p4, p5, p6); } } diff --git a/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedZPath7.java b/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedZPath7.java index ac509a2ec..a03e3fa84 100644 --- a/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedZPath7.java +++ b/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedZPath7.java @@ -25,8 +25,7 @@ * Same as {@link org.apache.curator.x.async.modeled.typed.TypedZPath}, but with 7 parameters */ @FunctionalInterface -public interface TypedZPath7 -{ +public interface TypedZPath7 { ZPath resolved(T1 p1, T2 p2, T3 p3, T4 p4, T5 p5, T6 p6, T7 p7); /** @@ -35,8 +34,7 @@ public interface TypedZPath7 * @param pathWithIds path to pass to {@link org.apache.curator.x.async.modeled.ZPath#parseWithIds} * @return TypedZPath */ - static TypedZPath7 from(String pathWithIds) - { + static TypedZPath7 from(String pathWithIds) { return from(ZPath.parseWithIds(pathWithIds)); } @@ -46,8 +44,7 @@ static TypedZPath7 from * @param path path to use * @return TypedZPath */ - static TypedZPath7 from(ZPath path) - { + static TypedZPath7 from(ZPath path) { return (p1, p2, p3, p4, p5, p6, p7) -> path.resolved(p1, p2, p3, p4, p5, p6, p7); } } diff --git a/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedZPath8.java b/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedZPath8.java index be69858d4..59564a8dd 100644 --- a/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedZPath8.java +++ b/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedZPath8.java @@ -25,8 +25,7 @@ * Same as {@link org.apache.curator.x.async.modeled.typed.TypedZPath}, but with 8 parameters */ @FunctionalInterface -public interface TypedZPath8 -{ +public interface TypedZPath8 { ZPath resolved(T1 p1, T2 p2, T3 p3, T4 p4, T5 p5, T6 p6, T7 p7, T8 p8); /** @@ -35,8 +34,7 @@ public interface TypedZPath8 * @param pathWithIds path to pass to {@link org.apache.curator.x.async.modeled.ZPath#parseWithIds} * @return TypedZPath */ - static TypedZPath8 from(String pathWithIds) - { + static TypedZPath8 from(String pathWithIds) { return from(ZPath.parseWithIds(pathWithIds)); } @@ -46,8 +44,7 @@ static TypedZPath8 TypedZPath8 from(ZPath path) - { + static TypedZPath8 from(ZPath path) { return (p1, p2, p3, p4, p5, p6, p7, p8) -> path.resolved(p1, p2, p3, p4, p5, p6, p7, p8); } } diff --git a/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedZPath9.java b/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedZPath9.java index 2d5ff90ff..6b616aa21 100644 --- a/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedZPath9.java +++ b/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/typed/TypedZPath9.java @@ -25,8 +25,7 @@ * Same as {@link org.apache.curator.x.async.modeled.typed.TypedZPath}, but with 9 parameters */ @FunctionalInterface -public interface TypedZPath9 -{ +public interface TypedZPath9 { ZPath resolved(T1 p1, T2 p2, T3 p3, T4 p4, T5 p5, T6 p6, T7 p7, T8 p8, T9 p9); /** @@ -35,8 +34,8 @@ public interface TypedZPath9 * @param pathWithIds path to pass to {@link org.apache.curator.x.async.modeled.ZPath#parseWithIds} * @return TypedZPath */ - static TypedZPath9 from(String pathWithIds) - { + static TypedZPath9 from( + String pathWithIds) { return from(ZPath.parseWithIds(pathWithIds)); } @@ -46,8 +45,7 @@ static TypedZPath9 TypedZPath9 from(ZPath path) - { + static TypedZPath9 from(ZPath path) { return (p1, p2, p3, p4, p5, p6, p7, p8, p9) -> path.resolved(p1, p2, p3, p4, p5, p6, p7, p8, p9); } } diff --git a/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/versioned/Versioned.java b/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/versioned/Versioned.java index fcc5b3b4d..f8eef5d3b 100644 --- a/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/versioned/Versioned.java +++ b/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/versioned/Versioned.java @@ -24,8 +24,7 @@ * {@link org.apache.curator.x.async.modeled.ModeledFramework#versioned()} APIs */ @FunctionalInterface -public interface Versioned -{ +public interface Versioned { /** * Returns the contained model * @@ -38,8 +37,7 @@ public interface Versioned * * @return version */ - default int version() - { + default int version() { return -1; } @@ -50,19 +48,15 @@ default int version() * @param version version * @return new Versioned wrapper */ - static Versioned from(T model, int version) - { - return new Versioned() - { + static Versioned from(T model, int version) { + return new Versioned() { @Override - public int version() - { + public int version() { return version; } @Override - public T model() - { + public T model() { return model; } }; diff --git a/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/versioned/VersionedModeledFramework.java b/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/versioned/VersionedModeledFramework.java index 09b789cb1..7e66c9086 100644 --- a/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/versioned/VersionedModeledFramework.java +++ b/curator-x-async/src/main/java/org/apache/curator/x/async/modeled/versioned/VersionedModeledFramework.java @@ -23,8 +23,7 @@ import org.apache.curator.x.async.AsyncStage; import org.apache.zookeeper.data.Stat; -public interface VersionedModeledFramework -{ +public interface VersionedModeledFramework { /** * @see org.apache.curator.x.async.modeled.ModeledFramework#set(Object) */ diff --git a/curator-x-async/src/test/java/org/apache/curator/framework/imps/TestAddWatch.java b/curator-x-async/src/test/java/org/apache/curator/framework/imps/TestAddWatch.java index d7a779e73..a92b21816 100644 --- a/curator-x-async/src/test/java/org/apache/curator/framework/imps/TestAddWatch.java +++ b/curator-x-async/src/test/java/org/apache/curator/framework/imps/TestAddWatch.java @@ -20,7 +20,7 @@ package org.apache.curator.framework.imps; import static org.junit.jupiter.api.Assertions.assertTrue; - +import java.util.concurrent.CountDownLatch; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.retry.RetryOneTime; @@ -32,22 +32,23 @@ import org.apache.zookeeper.ZooKeeper; import org.junit.jupiter.api.Test; -import java.util.concurrent.CountDownLatch; - -public class TestAddWatch extends CuratorTestBase -{ +public class TestAddWatch extends CuratorTestBase { @Test - public void testPersistentRecursiveWatch() throws Exception - { - try ( CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)) ) - { + public void testPersistentRecursiveWatch() throws Exception { + try (CuratorFramework client = + CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1))) { client.start(); client.blockUntilConnected(); CountDownLatch latch = new CountDownLatch(5); Watcher watcher = event -> latch.countDown(); AsyncCuratorFramework async = AsyncCuratorFramework.wrap(client); - async.addWatch().withMode(AddWatchMode.PERSISTENT_RECURSIVE).usingWatcher(watcher).forPath("/test").toCompletableFuture().get(); + async.addWatch() + .withMode(AddWatchMode.PERSISTENT_RECURSIVE) + .usingWatcher(watcher) + .forPath("/test") + .toCompletableFuture() + .get(); client.create().forPath("/test"); client.create().forPath("/test/a"); @@ -60,9 +61,8 @@ public void testPersistentRecursiveWatch() throws Exception } @Test - public void testPersistentRecursiveDefaultWatch() throws Exception - { - CountDownLatch latch = new CountDownLatch(6); // 5 creates plus the initial sync + public void testPersistentRecursiveDefaultWatch() throws Exception { + CountDownLatch latch = new CountDownLatch(6); // 5 creates plus the initial sync ZookeeperFactory zookeeperFactory = (connectString, sessionTimeout, watcher, canBeReadOnly) -> { Watcher actualWatcher = event -> { watcher.process(event); @@ -70,8 +70,11 @@ public void testPersistentRecursiveDefaultWatch() throws Exception }; return new ZooKeeper(connectString, sessionTimeout, actualWatcher); }; - try (CuratorFramework client = CuratorFrameworkFactory.builder().connectString(server.getConnectString()).retryPolicy(new RetryOneTime(1)).zookeeperFactory(zookeeperFactory).build() ) - { + try (CuratorFramework client = CuratorFrameworkFactory.builder() + .connectString(server.getConnectString()) + .retryPolicy(new RetryOneTime(1)) + .zookeeperFactory(zookeeperFactory) + .build()) { client.start(); client.blockUntilConnected(); diff --git a/curator-x-async/src/test/java/org/apache/curator/framework/imps/TestFramework.java b/curator-x-async/src/test/java/org/apache/curator/framework/imps/TestFramework.java index 017b37cdc..f0d249d0c 100644 --- a/curator-x-async/src/test/java/org/apache/curator/framework/imps/TestFramework.java +++ b/curator-x-async/src/test/java/org/apache/curator/framework/imps/TestFramework.java @@ -26,6 +26,16 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; import com.google.common.collect.Lists; +import java.util.ArrayList; +import java.util.Collections; +import java.util.EnumSet; +import java.util.List; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.Semaphore; +import java.util.concurrent.TimeUnit; import org.apache.curator.framework.AuthInfo; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; @@ -52,42 +62,26 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import java.util.ArrayList; -import java.util.Collections; -import java.util.EnumSet; -import java.util.List; -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.LinkedBlockingQueue; -import java.util.concurrent.Semaphore; -import java.util.concurrent.TimeUnit; - @SuppressWarnings("deprecation") -public class TestFramework extends BaseClassForTests -{ +public class TestFramework extends BaseClassForTests { @BeforeEach @Override - public void setup() throws Exception - { + public void setup() throws Exception { System.setProperty("znode.container.checkIntervalMs", "1000"); super.setup(); } @AfterEach @Override - public void teardown() throws Exception - { + public void teardown() throws Exception { System.clearProperty("znode.container.checkIntervalMs"); super.teardown(); } @Test - public void testQuietDelete() throws Exception - { + public void testQuietDelete() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); - try - { + try { client.start(); AsyncCuratorFramework async = AsyncCuratorFramework.wrap(client); @@ -95,222 +89,201 @@ public void testQuietDelete() throws Exception final BlockingQueue rc = new LinkedBlockingQueue<>(); BackgroundCallback backgroundCallback = (client1, event) -> rc.add(event.getResultCode()); - async.delete().withOptions(EnumSet.of(DeleteOption.quietly)).forPath("/foo/bar/hey").handle((v, e) -> { - if ( e == null ) - { - rc.add(KeeperException.Code.OK.intValue()); - } - else - { - rc.add(((KeeperException)e).code().intValue()); - } - return null; - }); + async.delete() + .withOptions(EnumSet.of(DeleteOption.quietly)) + .forPath("/foo/bar/hey") + .handle((v, e) -> { + if (e == null) { + rc.add(KeeperException.Code.OK.intValue()); + } else { + rc.add(((KeeperException) e).code().intValue()); + } + return null; + }); Integer code = rc.poll(new Timing().milliseconds(), TimeUnit.MILLISECONDS); assertNotNull(code); assertEquals(code.intValue(), KeeperException.Code.OK.intValue()); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } @Test - public void testNamespaceWithWatcher() throws Exception - { + public void testNamespaceWithWatcher() throws Exception { CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder(); - CuratorFramework client = builder.connectString(server.getConnectString()).namespace("aisa").retryPolicy(new RetryOneTime(1)).build(); + CuratorFramework client = builder.connectString(server.getConnectString()) + .namespace("aisa") + .retryPolicy(new RetryOneTime(1)) + .build(); client.start(); - try - { + try { AsyncCuratorFramework async = AsyncCuratorFramework.wrap(client); BlockingQueue queue = new LinkedBlockingQueue(); - async.create().forPath("/base"). - thenRun(() -> async.watched().getChildren().forPath("/base").event().handle((event, x) -> { - try - { - queue.put(event.getPath()); - } - catch ( InterruptedException e ) - { - throw new Error(e); - } - return null; - })) - .thenRun(() -> async.create().forPath("/base/child")); + async.create() + .forPath("/base") + .thenRun(() -> async.watched() + .getChildren() + .forPath("/base") + .event() + .handle((event, x) -> { + try { + queue.put(event.getPath()); + } catch (InterruptedException e) { + throw new Error(e); + } + return null; + })) + .thenRun(() -> async.create().forPath("/base/child")); String path = queue.take(); assertEquals(path, "/base"); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } @Test - public void testCreateACLSingleAuth() throws Exception - { + public void testCreateACLSingleAuth() throws Exception { CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder(); - CuratorFramework client = builder - .connectString(server.getConnectString()) - .authorization("digest", "me1:pass1".getBytes()) - .retryPolicy(new RetryOneTime(1)) - .build(); + CuratorFramework client = builder.connectString(server.getConnectString()) + .authorization("digest", "me1:pass1".getBytes()) + .retryPolicy(new RetryOneTime(1)) + .build(); client.start(); - try - { + try { ACL acl = new ACL(ZooDefs.Perms.WRITE, ZooDefs.Ids.AUTH_IDS); List aclList = Lists.newArrayList(acl); client.create().withACL(aclList).forPath("/test", "test".getBytes()); client.close(); // Try setting data with me1:pass1 - client = builder - .connectString(server.getConnectString()) - .authorization("digest", "me1:pass1".getBytes()) - .retryPolicy(new RetryOneTime(1)) - .build(); + client = builder.connectString(server.getConnectString()) + .authorization("digest", "me1:pass1".getBytes()) + .retryPolicy(new RetryOneTime(1)) + .build(); client.start(); - try - { + try { AsyncCuratorFramework async = AsyncCuratorFramework.wrap(client); - async.setData().forPath("/test", "test".getBytes()).toCompletableFuture().get(); - } - catch ( ExecutionException e ) - { + async.setData() + .forPath("/test", "test".getBytes()) + .toCompletableFuture() + .get(); + } catch (ExecutionException e) { fail("Auth failed"); } client.close(); // Try setting data with something:else - client = builder - .connectString(server.getConnectString()) - .authorization("digest", "something:else".getBytes()) - .retryPolicy(new RetryOneTime(1)) - .build(); + client = builder.connectString(server.getConnectString()) + .authorization("digest", "something:else".getBytes()) + .retryPolicy(new RetryOneTime(1)) + .build(); client.start(); - try - { + try { AsyncCuratorFramework async = AsyncCuratorFramework.wrap(client); - async.setData().forPath("/test", "test".getBytes()).toCompletableFuture().get(); + async.setData() + .forPath("/test", "test".getBytes()) + .toCompletableFuture() + .get(); fail("Should have failed with auth exception"); - } - catch ( ExecutionException e ) - { + } catch (ExecutionException e) { // expected } - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } @Test - public void testCreateACLMultipleAuths() throws Exception - { + public void testCreateACLMultipleAuths() throws Exception { // Add a few authInfos List authInfos = new ArrayList(); authInfos.add(new AuthInfo("digest", "me1:pass1".getBytes())); authInfos.add(new AuthInfo("digest", "me2:pass2".getBytes())); CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder(); - CuratorFramework client = builder - .connectString(server.getConnectString()) - .authorization(authInfos) - .retryPolicy(new RetryOneTime(1)) - .build(); + CuratorFramework client = builder.connectString(server.getConnectString()) + .authorization(authInfos) + .retryPolicy(new RetryOneTime(1)) + .build(); client.start(); - try - { + try { ACL acl = new ACL(ZooDefs.Perms.WRITE, ZooDefs.Ids.AUTH_IDS); List aclList = Lists.newArrayList(acl); client.create().withACL(aclList).forPath("/test", "test".getBytes()); client.close(); // Try setting data with me1:pass1 - client = builder - .connectString(server.getConnectString()) - .authorization("digest", "me1:pass1".getBytes()) - .retryPolicy(new RetryOneTime(1)) - .build(); + client = builder.connectString(server.getConnectString()) + .authorization("digest", "me1:pass1".getBytes()) + .retryPolicy(new RetryOneTime(1)) + .build(); client.start(); - try - { + try { AsyncCuratorFramework async = AsyncCuratorFramework.wrap(client); - async.setData().forPath("/test", "test".getBytes()).toCompletableFuture().get(); - } - catch ( ExecutionException e ) - { + async.setData() + .forPath("/test", "test".getBytes()) + .toCompletableFuture() + .get(); + } catch (ExecutionException e) { fail("Auth failed"); } client.close(); // Try setting data with me1:pass1 - client = builder - .connectString(server.getConnectString()) - .authorization("digest", "me2:pass2".getBytes()) - .retryPolicy(new RetryOneTime(1)) - .build(); + client = builder.connectString(server.getConnectString()) + .authorization("digest", "me2:pass2".getBytes()) + .retryPolicy(new RetryOneTime(1)) + .build(); client.start(); - try - { + try { AsyncCuratorFramework async = AsyncCuratorFramework.wrap(client); - async.setData().forPath("/test", "test".getBytes()).toCompletableFuture().get(); - } - catch ( ExecutionException e ) - { + async.setData() + .forPath("/test", "test".getBytes()) + .toCompletableFuture() + .get(); + } catch (ExecutionException e) { fail("Auth failed"); } client.close(); // Try setting data with something:else - client = builder - .connectString(server.getConnectString()) - .authorization("digest", "something:else".getBytes()) - .retryPolicy(new RetryOneTime(1)) - .build(); + client = builder.connectString(server.getConnectString()) + .authorization("digest", "something:else".getBytes()) + .retryPolicy(new RetryOneTime(1)) + .build(); client.start(); - try - { + try { AsyncCuratorFramework async = AsyncCuratorFramework.wrap(client); - async.setData().forPath("/test", "test".getBytes()).toCompletableFuture().get(); + async.setData() + .forPath("/test", "test".getBytes()) + .toCompletableFuture() + .get(); fail("Should have failed with auth exception"); - } - catch ( ExecutionException e ) - { + } catch (ExecutionException e) { // expected } - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } @Test - public void testCreateACLWithReset() throws Exception - { + public void testCreateACLWithReset() throws Exception { Timing timing = new Timing(); CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder(); - CuratorFramework client = builder - .connectString(server.getConnectString()) - .sessionTimeoutMs(timing.session()) - .connectionTimeoutMs(timing.connection()) - .authorization("digest", "me:pass".getBytes()) - .retryPolicy(new ExponentialBackoffRetry(100, 5)) - .build(); + CuratorFramework client = builder.connectString(server.getConnectString()) + .sessionTimeoutMs(timing.session()) + .connectionTimeoutMs(timing.connection()) + .authorization("digest", "me:pass".getBytes()) + .retryPolicy(new ExponentialBackoffRetry(100, 5)) + .build(); client.start(); - try - { + try { final CountDownLatch lostLatch = new CountDownLatch(1); - ConnectionStateListener listener = (client1, newState) -> - { - if ( newState == ConnectionState.LOST ) - { + ConnectionStateListener listener = (client1, newState) -> { + if (newState == ConnectionState.LOST) { lostLatch.countDown(); } }; @@ -322,112 +295,122 @@ public void testCreateACLWithReset() throws Exception server.stop(); assertTrue(timing.awaitLatch(lostLatch)); - try - { + try { AsyncCuratorFramework async = AsyncCuratorFramework.wrap(client); async.checkExists().forPath("/").toCompletableFuture().get(); fail("Connection should be down"); - } - catch ( ExecutionException e ) - { + } catch (ExecutionException e) { // expected } server.restart(); - try - { + try { AsyncCuratorFramework async = AsyncCuratorFramework.wrap(client); - async.setData().forPath("/test", "test".getBytes()).toCompletableFuture().get(); - } - catch ( ExecutionException e ) - { + async.setData() + .forPath("/test", "test".getBytes()) + .toCompletableFuture() + .get(); + } catch (ExecutionException e) { fail("Auth failed", e); } - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } @Test - public void testCreateParents() throws Exception - { + public void testCreateParents() throws Exception { CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder(); - CuratorFramework client = builder.connectString(server.getConnectString()).retryPolicy(new RetryOneTime(1)).build(); + CuratorFramework client = builder.connectString(server.getConnectString()) + .retryPolicy(new RetryOneTime(1)) + .build(); client.start(); - try - { + try { AsyncCuratorFramework async = AsyncCuratorFramework.wrap(client); - async.create().withOptions(EnumSet.of(CreateOption.createParentsIfNeeded)).forPath("/one/two/three", "foo".getBytes()).toCompletableFuture().get(); - byte[] data = async.getData().forPath("/one/two/three").toCompletableFuture().get(); + async.create() + .withOptions(EnumSet.of(CreateOption.createParentsIfNeeded)) + .forPath("/one/two/three", "foo".getBytes()) + .toCompletableFuture() + .get(); + byte[] data = async.getData() + .forPath("/one/two/three") + .toCompletableFuture() + .get(); assertArrayEquals(data, "foo".getBytes()); - async.create().withOptions(EnumSet.of(CreateOption.createParentsIfNeeded)).forPath("/one/two/another", "bar".getBytes()); - data = async.getData().forPath("/one/two/another").toCompletableFuture().get(); + async.create() + .withOptions(EnumSet.of(CreateOption.createParentsIfNeeded)) + .forPath("/one/two/another", "bar".getBytes()); + data = async.getData() + .forPath("/one/two/another") + .toCompletableFuture() + .get(); assertArrayEquals(data, "bar".getBytes()); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } @Test - public void testCreateParentContainers() throws Exception - { - if ( !checkForContainers() ) - { + public void testCreateParentContainers() throws Exception { + if (!checkForContainers()) { return; } CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder(); - CuratorFramework client = builder.connectString(server.getConnectString()).retryPolicy(new RetryOneTime(1)).build(); - try - { + CuratorFramework client = builder.connectString(server.getConnectString()) + .retryPolicy(new RetryOneTime(1)) + .build(); + try { client.start(); AsyncCuratorFramework async = AsyncCuratorFramework.wrap(client); - async.create().withOptions(EnumSet.of(CreateOption.createParentsAsContainers)).forPath("/one/two/three", "foo".getBytes()).toCompletableFuture().get(); - byte[] data = async.getData().forPath("/one/two/three").toCompletableFuture().get(); + async.create() + .withOptions(EnumSet.of(CreateOption.createParentsAsContainers)) + .forPath("/one/two/three", "foo".getBytes()) + .toCompletableFuture() + .get(); + byte[] data = async.getData() + .forPath("/one/two/three") + .toCompletableFuture() + .get(); assertArrayEquals(data, "foo".getBytes()); async.delete().forPath("/one/two/three").toCompletableFuture().get(); new Timing().sleepABit(); - assertNull(async.checkExists().forPath("/one/two").toCompletableFuture().get()); + assertNull(async.checkExists() + .forPath("/one/two") + .toCompletableFuture() + .get()); new Timing().sleepABit(); assertNull(async.checkExists().forPath("/one").toCompletableFuture().get()); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } @Test - public void testCreateWithProtection() throws ExecutionException, InterruptedException - { + public void testCreateWithProtection() throws ExecutionException, InterruptedException { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); - try - { + try { client.start(); AsyncCuratorFramework async = AsyncCuratorFramework.wrap(client); - String path = async.create().withOptions(Collections.singleton(CreateOption.doProtected)).forPath("/yo").toCompletableFuture().get(); + String path = async.create() + .withOptions(Collections.singleton(CreateOption.doProtected)) + .forPath("/yo") + .toCompletableFuture() + .get(); String node = ZKPaths.getNodeFromPath(path); // CURATOR-489: confirm that the node contains a valid UUID, eg '_c_53345f98-9423-4e0c-a7b5-9f819e3ec2e1-yo' assertTrue(ProtectedUtils.isProtectedZNode(node)); assertEquals(ProtectedUtils.normalize(node), "yo"); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } - private boolean checkForContainers() - { - if ( ZKPaths.getContainerCreateMode() == CreateMode.PERSISTENT ) - { + private boolean checkForContainers() { + if (ZKPaths.getContainerCreateMode() == CreateMode.PERSISTENT) { System.out.println("Not using CreateMode.CONTAINER enabled version of ZooKeeper"); return false; } @@ -435,60 +418,91 @@ private boolean checkForContainers() } @Test - public void testCreatingParentsTheSame() throws Exception - { + public void testCreatingParentsTheSame() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); - try - { + try { client.start(); AsyncCuratorFramework async = AsyncCuratorFramework.wrap(client); assertNull(client.checkExists().forPath("/one/two")); - async.create().withOptions(EnumSet.of(CreateOption.createParentsAsContainers)).forPath("/one/two/three").toCompletableFuture().get(); - assertNotNull(async.checkExists().forPath("/one/two").toCompletableFuture().get()); - - async.delete().withOptions(EnumSet.of(DeleteOption.deletingChildrenIfNeeded)).forPath("/one").toCompletableFuture().get(); + async.create() + .withOptions(EnumSet.of(CreateOption.createParentsAsContainers)) + .forPath("/one/two/three") + .toCompletableFuture() + .get(); + assertNotNull(async.checkExists() + .forPath("/one/two") + .toCompletableFuture() + .get()); + + async.delete() + .withOptions(EnumSet.of(DeleteOption.deletingChildrenIfNeeded)) + .forPath("/one") + .toCompletableFuture() + .get(); assertNull(client.checkExists().forPath("/one")); - assertNull(async.checkExists().forPath("/one/two").toCompletableFuture().get()); - async.checkExists().withOptions(EnumSet.of(ExistsOption.createParentsAsContainers)).forPath("/one/two/three").toCompletableFuture().get(); - assertNotNull(async.checkExists().forPath("/one/two").toCompletableFuture().get()); - assertNull(async.checkExists().forPath("/one/two/three").toCompletableFuture().get()); - } - finally - { + assertNull(async.checkExists() + .forPath("/one/two") + .toCompletableFuture() + .get()); + async.checkExists() + .withOptions(EnumSet.of(ExistsOption.createParentsAsContainers)) + .forPath("/one/two/three") + .toCompletableFuture() + .get(); + assertNotNull(async.checkExists() + .forPath("/one/two") + .toCompletableFuture() + .get()); + assertNull(async.checkExists() + .forPath("/one/two/three") + .toCompletableFuture() + .get()); + } finally { CloseableUtils.closeQuietly(client); } } @Test - public void testExistsCreatingParents() throws Exception - { + public void testExistsCreatingParents() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); - try - { + try { client.start(); AsyncCuratorFramework async = AsyncCuratorFramework.wrap(client); - assertNull(async.checkExists().forPath("/one/two").toCompletableFuture().get()); - async.checkExists().withOptions(EnumSet.of(ExistsOption.createParentsAsContainers)).forPath("/one/two/three").toCompletableFuture().get(); - assertNotNull(async.checkExists().forPath("/one/two").toCompletableFuture().get()); - assertNull(async.checkExists().forPath("/one/two/three").toCompletableFuture().get()); - assertNull(async.checkExists().withOptions(EnumSet.of(ExistsOption.createParentsAsContainers)).forPath("/one/two/three").toCompletableFuture().get()); - } - finally - { + assertNull(async.checkExists() + .forPath("/one/two") + .toCompletableFuture() + .get()); + async.checkExists() + .withOptions(EnumSet.of(ExistsOption.createParentsAsContainers)) + .forPath("/one/two/three") + .toCompletableFuture() + .get(); + assertNotNull(async.checkExists() + .forPath("/one/two") + .toCompletableFuture() + .get()); + assertNull(async.checkExists() + .forPath("/one/two/three") + .toCompletableFuture() + .get()); + assertNull(async.checkExists() + .withOptions(EnumSet.of(ExistsOption.createParentsAsContainers)) + .forPath("/one/two/three") + .toCompletableFuture() + .get()); + } finally { CloseableUtils.closeQuietly(client); } } @Test - public void testSyncNew() throws Exception - { + public void testSyncNew() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client.start(); - try - { + try { client.create().forPath("/head"); assertNotNull(client.checkExists().forPath("/head")); @@ -501,132 +515,136 @@ public void testSyncNew() throws Exception return null; }); assertTrue(latch.await(10, TimeUnit.SECONDS)); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } @Test - public void testBackgroundDelete() throws Exception - { + public void testBackgroundDelete() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client.start(); - try - { + try { AsyncCuratorFramework async = AsyncCuratorFramework.wrap(client); CountDownLatch latch = new CountDownLatch(1); - async.create().forPath("/head").thenRun(() -> - async.delete().forPath("/head").handle((v, e) -> { - assertNull(v); - assertNull(e); - latch.countDown(); - return null; - }) - ); + async.create() + .forPath("/head") + .thenRun(() -> async.delete().forPath("/head").handle((v, e) -> { + assertNull(v); + assertNull(e); + latch.countDown(); + return null; + })); assertTrue(latch.await(10, TimeUnit.SECONDS)); assertNull(client.checkExists().forPath("/head")); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } @Test - public void testBackgroundDeleteWithChildren() throws Exception - { + public void testBackgroundDeleteWithChildren() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client.start(); - try - { - client.getCuratorListenable().addListener - ((client1, event) -> - { - if ( event.getType() == CuratorEventType.DELETE ) - { - assertEquals(event.getPath(), "/one/two"); - ((CountDownLatch)event.getContext()).countDown(); - } - }); + try { + client.getCuratorListenable().addListener((client1, event) -> { + if (event.getType() == CuratorEventType.DELETE) { + assertEquals(event.getPath(), "/one/two"); + ((CountDownLatch) event.getContext()).countDown(); + } + }); CountDownLatch latch = new CountDownLatch(1); AsyncCuratorFramework async = AsyncCuratorFramework.wrap(client); - async.create().withOptions(EnumSet.of(CreateOption.createParentsIfNeeded)).forPath("/one/two/three/four").thenRun(() -> - async.delete().withOptions(EnumSet.of(DeleteOption.deletingChildrenIfNeeded)).forPath("/one/two").handle((v, e) -> { - assertNull(v); - assertNull(e); - latch.countDown(); - return null; - }) - ); + async.create() + .withOptions(EnumSet.of(CreateOption.createParentsIfNeeded)) + .forPath("/one/two/three/four") + .thenRun(() -> async.delete() + .withOptions(EnumSet.of(DeleteOption.deletingChildrenIfNeeded)) + .forPath("/one/two") + .handle((v, e) -> { + assertNull(v); + assertNull(e); + latch.countDown(); + return null; + })); assertTrue(latch.await(10, TimeUnit.SECONDS)); assertNull(client.checkExists().forPath("/one/two")); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } @Test - public void testDeleteGuaranteedWithChildren() throws Exception - { + public void testDeleteGuaranteedWithChildren() throws Exception { CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder(); - CuratorFramework client = builder.connectString(server.getConnectString()).retryPolicy(new RetryOneTime(1)).build(); + CuratorFramework client = builder.connectString(server.getConnectString()) + .retryPolicy(new RetryOneTime(1)) + .build(); client.start(); - try - { + try { AsyncCuratorFramework async = AsyncCuratorFramework.wrap(client); - async.create().withOptions(EnumSet.of(CreateOption.createParentsIfNeeded)).forPath("/one/two/three/four/five/six", "foo".getBytes()).toCompletableFuture().get(); - async.delete().withOptions(EnumSet.of(DeleteOption.guaranteed, DeleteOption.deletingChildrenIfNeeded)).forPath("/one/two/three/four/five").toCompletableFuture().get(); - assertNull(async.checkExists().forPath("/one/two/three/four/five").toCompletableFuture().get()); - async.delete().withOptions(EnumSet.of(DeleteOption.guaranteed, DeleteOption.deletingChildrenIfNeeded)).forPath("/one/two").toCompletableFuture().get(); - assertNull(async.checkExists().forPath("/one/two").toCompletableFuture().get()); - } - finally - { + async.create() + .withOptions(EnumSet.of(CreateOption.createParentsIfNeeded)) + .forPath("/one/two/three/four/five/six", "foo".getBytes()) + .toCompletableFuture() + .get(); + async.delete() + .withOptions(EnumSet.of(DeleteOption.guaranteed, DeleteOption.deletingChildrenIfNeeded)) + .forPath("/one/two/three/four/five") + .toCompletableFuture() + .get(); + assertNull(async.checkExists() + .forPath("/one/two/three/four/five") + .toCompletableFuture() + .get()); + async.delete() + .withOptions(EnumSet.of(DeleteOption.guaranteed, DeleteOption.deletingChildrenIfNeeded)) + .forPath("/one/two") + .toCompletableFuture() + .get(); + assertNull(async.checkExists() + .forPath("/one/two") + .toCompletableFuture() + .get()); + } finally { CloseableUtils.closeQuietly(client); } } @Test - public void testGetSequentialChildren() throws Exception - { + public void testGetSequentialChildren() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client.start(); - try - { + try { Semaphore semaphore = new Semaphore(0); AsyncCuratorFramework async = AsyncCuratorFramework.wrap(client); async.create().forPath("/head").thenRun(() -> { - for ( int i = 0; i < 10; ++i ) - { - async.create().withMode(CreateMode.EPHEMERAL_SEQUENTIAL).forPath("/head/child").thenRun(semaphore::release); + for (int i = 0; i < 10; ++i) { + async.create() + .withMode(CreateMode.EPHEMERAL_SEQUENTIAL) + .forPath("/head/child") + .thenRun(semaphore::release); } }); assertTrue(new Timing().acquireSemaphore(semaphore, 10)); - List children = async.getChildren().forPath("/head").toCompletableFuture().get(); + List children = + async.getChildren().forPath("/head").toCompletableFuture().get(); assertEquals(children.size(), 10); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } @Test - public void testBackgroundGetDataWithWatch() throws Exception - { + public void testBackgroundGetDataWithWatch() throws Exception { final byte[] data1 = {1, 2, 3}; final byte[] data2 = {4, 5, 6, 7}; CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client.start(); - try - { + try { AsyncCuratorFramework async = AsyncCuratorFramework.wrap(client); async.create().forPath("/test", data1).toCompletableFuture().get(); @@ -648,11 +666,10 @@ public void testBackgroundGetDataWithWatch() throws Exception async.setData().forPath("/test", data2); assertTrue(watchedLatch.await(10, TimeUnit.SECONDS)); - byte[] checkData = async.getData().forPath("/test").toCompletableFuture().get(); + byte[] checkData = + async.getData().forPath("/test").toCompletableFuture().get(); assertArrayEquals(checkData, data2); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } diff --git a/curator-x-async/src/test/java/org/apache/curator/framework/imps/TestFrameworkBackground.java b/curator-x-async/src/test/java/org/apache/curator/framework/imps/TestFrameworkBackground.java index 07049a4c8..fe18aa90e 100644 --- a/curator-x-async/src/test/java/org/apache/curator/framework/imps/TestFrameworkBackground.java +++ b/curator-x-async/src/test/java/org/apache/curator/framework/imps/TestFrameworkBackground.java @@ -23,6 +23,12 @@ import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import com.google.common.collect.Lists; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicLong; +import java.util.concurrent.atomic.AtomicReference; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.api.ACLProvider; @@ -40,103 +46,78 @@ import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicLong; -import java.util.concurrent.atomic.AtomicReference; -public class TestFrameworkBackground extends BaseClassForTests -{ +public class TestFrameworkBackground extends BaseClassForTests { private final Logger log = LoggerFactory.getLogger(getClass()); @Test - public void testErrorListener() throws Exception - { - //The first call to the ACL provider will return a reasonable - //value. The second will throw an error. This is because the ACL - //provider is accessed prior to the backgrounding call. + public void testErrorListener() throws Exception { + // The first call to the ACL provider will return a reasonable + // value. The second will throw an error. This is because the ACL + // provider is accessed prior to the backgrounding call. final AtomicBoolean aclProviderCalled = new AtomicBoolean(false); - - ACLProvider badAclProvider = new ACLProvider() - { + + ACLProvider badAclProvider = new ACLProvider() { @Override - public List getDefaultAcl() - { - if(aclProviderCalled.getAndSet(true)) - { + public List getDefaultAcl() { + if (aclProviderCalled.getAndSet(true)) { throw new UnsupportedOperationException(); - } - else - { + } else { return new ArrayList<>(); } } @Override - public List getAclForPath(String path) - { - if(aclProviderCalled.getAndSet(true)) - { + public List getAclForPath(String path) { + if (aclProviderCalled.getAndSet(true)) { throw new UnsupportedOperationException(); - } - else - { + } else { return new ArrayList<>(); } } }; CuratorFramework client = CuratorFrameworkFactory.builder() - .connectString(server.getConnectString()) - .retryPolicy(new RetryOneTime(1)) - .aclProvider(badAclProvider) - .build(); - try - { + .connectString(server.getConnectString()) + .retryPolicy(new RetryOneTime(1)) + .aclProvider(badAclProvider) + .build(); + try { client.start(); AsyncCuratorFramework async = AsyncCuratorFramework.wrap(client); final CountDownLatch errorLatch = new CountDownLatch(1); UnhandledErrorListener listener = (message, e) -> { - if ( e instanceof UnsupportedOperationException ) - { + if (e instanceof UnsupportedOperationException) { errorLatch.countDown(); } }; async.with(listener).create().forPath("/foo"); assertTrue(new Timing().awaitLatch(errorLatch)); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } @Test - public void testListenerConnectedAtStart() throws Exception - { + public void testListenerConnectedAtStart() throws Exception { server.stop(); Timing timing = new Timing(2); - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryNTimes(0, 0)); - try - { + CuratorFramework client = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), timing.connection(), new RetryNTimes(0, 0)); + try { client.start(); AsyncCuratorFramework async = AsyncCuratorFramework.wrap(client); final CountDownLatch connectedLatch = new CountDownLatch(1); final AtomicBoolean firstListenerAction = new AtomicBoolean(true); final AtomicReference firstListenerState = new AtomicReference<>(); - ConnectionStateListener listener = (client1, newState) -> - { - if ( firstListenerAction.compareAndSet(true, false) ) - { + ConnectionStateListener listener = (client1, newState) -> { + if (firstListenerAction.compareAndSet(true, false)) { firstListenerState.set(newState); System.out.println("First listener state is " + newState); } - if ( newState == ConnectionState.CONNECTED ) - { + if (newState == ConnectionState.CONNECTED) { connectedLatch.countDown(); } }; @@ -150,24 +131,24 @@ public void testListenerConnectedAtStart() throws Exception assertTrue(timing.awaitLatch(connectedLatch)); assertFalse(firstListenerAction.get()); ConnectionState firstconnectionState = firstListenerState.get(); - assertEquals(firstconnectionState, ConnectionState.CONNECTED, "First listener state MUST BE CONNECTED but is " + firstconnectionState); - } - finally - { + assertEquals( + firstconnectionState, + ConnectionState.CONNECTED, + "First listener state MUST BE CONNECTED but is " + firstconnectionState); + } finally { CloseableUtils.closeQuietly(client); } } @Test - public void testRetries() throws Exception - { + public void testRetries() throws Exception { final int SLEEP = 1000; final int TIMES = 5; Timing timing = new Timing(); - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryNTimes(TIMES, SLEEP)); - try - { + CuratorFramework client = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), timing.connection(), new RetryNTimes(TIMES, SLEEP)); + try { client.start(); AsyncCuratorFramework async = AsyncCuratorFramework.wrap(client); client.getZookeeperClient().blockUntilConnectedOrTimedOut(); @@ -175,10 +156,8 @@ public void testRetries() throws Exception final CountDownLatch latch = new CountDownLatch(TIMES); final List times = Lists.newArrayList(); final AtomicLong start = new AtomicLong(System.currentTimeMillis()); - ((CuratorFrameworkImpl)client).debugListener = data -> - { - if ( data.getOperation().getClass().getName().contains("CreateBuilderImpl") ) - { + ((CuratorFrameworkImpl) client).debugListener = data -> { + if (data.getOperation().getClass().getName().contains("CreateBuilderImpl")) { long now = System.currentTimeMillis(); times.add(now - start.get()); start.set(now); @@ -191,13 +170,11 @@ public void testRetries() throws Exception latch.await(); - for ( long elapsed : times.subList(1, times.size()) ) // first one isn't a retry + for (long elapsed : times.subList(1, times.size())) // first one isn't a retry { assertTrue(elapsed >= SLEEP, elapsed + ": " + times); } - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } @@ -207,20 +184,22 @@ public void testRetries() throws Exception * Return code must be {@link org.apache.zookeeper.KeeperException.Code#CONNECTIONLOSS} */ @Test - public void testCuratorCallbackOnError() throws Exception - { + public void testCuratorCallbackOnError() throws Exception { Timing timing = new Timing(); final CountDownLatch latch = new CountDownLatch(1); - try ( CuratorFramework client = CuratorFrameworkFactory.builder().connectString(server.getConnectString()).sessionTimeoutMs(timing.session()).connectionTimeoutMs(timing.connection()).retryPolicy(new RetryOneTime(1000)).build() ) - { + try (CuratorFramework client = CuratorFrameworkFactory.builder() + .connectString(server.getConnectString()) + .sessionTimeoutMs(timing.session()) + .connectionTimeoutMs(timing.connection()) + .retryPolicy(new RetryOneTime(1000)) + .build()) { client.start(); AsyncCuratorFramework async = AsyncCuratorFramework.wrap(client); // Stop the Zookeeper server server.stop(); // Attempt to retrieve children list async.getChildren().forPath("/").handle((children, e) -> { - if ( e instanceof KeeperException.ConnectionLossException ) - { + if (e instanceof KeeperException.ConnectionLossException) { latch.countDown(); } return null; @@ -235,23 +214,19 @@ public void testCuratorCallbackOnError() throws Exception * Shutdown the Curator client while there are still background operations running. */ @Test - public void testShutdown() throws Exception - { + public void testShutdown() throws Exception { Timing timing = new Timing(); - CuratorFramework client = CuratorFrameworkFactory - .builder() - .connectString(server.getConnectString()) - .sessionTimeoutMs(timing.session()) - .connectionTimeoutMs(timing.connection()).retryPolicy(new RetryOneTime(1)) - .maxCloseWaitMs(timing.forWaiting().milliseconds()) - .build(); - try - { + CuratorFramework client = CuratorFrameworkFactory.builder() + .connectString(server.getConnectString()) + .sessionTimeoutMs(timing.session()) + .connectionTimeoutMs(timing.connection()) + .retryPolicy(new RetryOneTime(1)) + .maxCloseWaitMs(timing.forWaiting().milliseconds()) + .build(); + try { final AtomicBoolean hadIllegalStateException = new AtomicBoolean(false); - ((CuratorFrameworkImpl)client).debugUnhandledErrorListener = (message, e) -> - { - if ( e instanceof IllegalStateException ) - { + ((CuratorFrameworkImpl) client).debugUnhandledErrorListener = (message, e) -> { + if (e instanceof IllegalStateException) { hadIllegalStateException.set(true); } }; @@ -259,14 +234,10 @@ public void testShutdown() throws Exception AsyncCuratorFramework async = AsyncCuratorFramework.wrap(client); final CountDownLatch operationReadyLatch = new CountDownLatch(1); - ((CuratorFrameworkImpl)client).debugListener = data -> - { - try - { + ((CuratorFrameworkImpl) client).debugListener = data -> { + try { operationReadyLatch.await(); - } - catch ( InterruptedException e ) - { + } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }; @@ -284,9 +255,7 @@ public void testShutdown() throws Exception // should not generate an exception assertFalse(hadIllegalStateException.get()); - } - finally - { + } finally { CloseableUtils.closeQuietly(client); } } diff --git a/curator-x-async/src/test/java/org/apache/curator/x/async/CompletableBaseClassForTests.java b/curator-x-async/src/test/java/org/apache/curator/x/async/CompletableBaseClassForTests.java index a4d99da71..bf97631b9 100644 --- a/curator-x-async/src/test/java/org/apache/curator/x/async/CompletableBaseClassForTests.java +++ b/curator-x-async/src/test/java/org/apache/curator/x/async/CompletableBaseClassForTests.java @@ -22,16 +22,15 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.fail; import com.google.common.base.Throwables; -import org.apache.curator.test.BaseClassForTests; -import org.apache.curator.test.compatibility.Timing2; import java.util.concurrent.CompletionStage; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.function.BiConsumer; +import org.apache.curator.test.BaseClassForTests; +import org.apache.curator.test.compatibility.Timing2; -public abstract class CompletableBaseClassForTests extends BaseClassForTests -{ +public abstract class CompletableBaseClassForTests extends BaseClassForTests { protected static final Timing2 timing = new Timing2(); protected void joinThrowable(CompletionStage stage) throws Throwable { @@ -48,39 +47,30 @@ protected void exceptional(CompletionStage stage, Class }); } - protected void complete(CompletionStage stage) - { + protected void complete(CompletionStage stage) { complete(stage, (v, e) -> { - if ( e != null ) - { + if (e != null) { Throwables.propagate(e); } }); } - protected void complete(CompletionStage stage, BiConsumer handler) - { - try - { + protected void complete(CompletionStage stage, BiConsumer handler) { + try { stage.handle((v, e) -> { - handler.accept(v, e); - return null; - }).toCompletableFuture().get(timing.forWaiting().milliseconds(), TimeUnit.MILLISECONDS); - } - catch ( InterruptedException e ) - { + handler.accept(v, e); + return null; + }) + .toCompletableFuture() + .get(timing.forWaiting().milliseconds(), TimeUnit.MILLISECONDS); + } catch (InterruptedException e) { Thread.interrupted(); - } - catch ( ExecutionException e ) - { - if ( e.getCause() instanceof AssertionError ) - { - throw (AssertionError)e.getCause(); + } catch (ExecutionException e) { + if (e.getCause() instanceof AssertionError) { + throw (AssertionError) e.getCause(); } fail("get() failed", e); - } - catch ( TimeoutException e ) - { + } catch (TimeoutException e) { fail("get() timed out"); } } diff --git a/curator-x-async/src/test/java/org/apache/curator/x/async/TestAsyncWrappers.java b/curator-x-async/src/test/java/org/apache/curator/x/async/TestAsyncWrappers.java index 24905a1e2..a04db7081 100644 --- a/curator-x-async/src/test/java/org/apache/curator/x/async/TestAsyncWrappers.java +++ b/curator-x-async/src/test/java/org/apache/curator/x/async/TestAsyncWrappers.java @@ -21,23 +21,19 @@ import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; - +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.recipes.locks.InterProcessMutex; import org.apache.curator.retry.RetryOneTime; import org.junit.jupiter.api.Test; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; - -public class TestAsyncWrappers extends CompletableBaseClassForTests -{ +public class TestAsyncWrappers extends CompletableBaseClassForTests { @Test - public void testBasic() - { - try ( CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)) ) - { + public void testBasic() { + try (CuratorFramework client = + CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1))) { client.start(); InterProcessMutex lock = new InterProcessMutex(client, "/one/two"); @@ -49,28 +45,27 @@ public void testBasic() } @Test - public void testContention() throws Exception - { - try ( CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)) ) - { + public void testContention() throws Exception { + try (CuratorFramework client = + CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1))) { client.start(); InterProcessMutex lock1 = new InterProcessMutex(client, "/one/two"); InterProcessMutex lock2 = new InterProcessMutex(client, "/one/two"); CountDownLatch latch = new CountDownLatch(1); AsyncWrappers.lockAsync(lock1).thenAccept(__ -> { - latch.countDown(); // don't release the lock + latch.countDown(); // don't release the lock }); assertTrue(timing.awaitLatch(latch)); CountDownLatch latch2 = new CountDownLatch(1); - AsyncWrappers.lockAsync(lock2, timing.forSleepingABit().milliseconds(), TimeUnit.MILLISECONDS).exceptionally(e -> { - if ( e instanceof AsyncWrappers.TimeoutException ) - { - latch2.countDown(); // lock should still be held - } - return null; - }); + AsyncWrappers.lockAsync(lock2, timing.forSleepingABit().milliseconds(), TimeUnit.MILLISECONDS) + .exceptionally(e -> { + if (e instanceof AsyncWrappers.TimeoutException) { + latch2.countDown(); // lock should still be held + } + return null; + }); assertTrue(timing.awaitLatch(latch2)); } } diff --git a/curator-x-async/src/test/java/org/apache/curator/x/async/TestBasicOperations.java b/curator-x-async/src/test/java/org/apache/curator/x/async/TestBasicOperations.java index 27f03cbed..1ee7d7334 100644 --- a/curator-x-async/src/test/java/org/apache/curator/x/async/TestBasicOperations.java +++ b/curator-x-async/src/test/java/org/apache/curator/x/async/TestBasicOperations.java @@ -29,7 +29,10 @@ import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; - +import java.io.IOException; +import java.util.Arrays; +import java.util.concurrent.CompletionStage; +import java.util.concurrent.CountDownLatch; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.api.transaction.CuratorOp; @@ -42,76 +45,74 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import java.io.IOException; -import java.util.Arrays; -import java.util.concurrent.CompletionStage; -import java.util.concurrent.CountDownLatch; - -public class TestBasicOperations extends CompletableBaseClassForTests -{ +public class TestBasicOperations extends CompletableBaseClassForTests { private AsyncCuratorFramework client; @BeforeEach @Override - public void setup() throws Exception - { + public void setup() throws Exception { super.setup(); - CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(timing.forSleepingABit().milliseconds())); + CuratorFramework client = CuratorFrameworkFactory.newClient( + server.getConnectString(), + new RetryOneTime(timing.forSleepingABit().milliseconds())); client.start(); this.client = AsyncCuratorFramework.wrap(client); } @AfterEach @Override - public void teardown() throws Exception - { + public void teardown() throws Exception { CloseableUtils.closeQuietly(client.unwrap()); super.teardown(); } @Test - public void testCreateTransactionWithMode() throws Exception - { + public void testCreateTransactionWithMode() throws Exception { complete(AsyncWrappers.asyncEnsureContainers(client, "/test")); - CuratorOp op1 = client.transactionOp().create().withMode(PERSISTENT_SEQUENTIAL).forPath("/test/node-"); - CuratorOp op2 = client.transactionOp().create().withMode(PERSISTENT_SEQUENTIAL).forPath("/test/node-"); + CuratorOp op1 = + client.transactionOp().create().withMode(PERSISTENT_SEQUENTIAL).forPath("/test/node-"); + CuratorOp op2 = + client.transactionOp().create().withMode(PERSISTENT_SEQUENTIAL).forPath("/test/node-"); complete(client.transaction().forOperations(Arrays.asList(op1, op2))); assertEquals(client.unwrap().getChildren().forPath("/test").size(), 2); } @Test - public void testCrud() - { + public void testCrud() { AsyncStage createStage = client.create().forPath("/test", "one".getBytes()); complete(createStage, (path, e) -> assertEquals(path, "/test")); AsyncStage getStage = client.getData().forPath("/test"); complete(getStage, (data, e) -> assertArrayEquals(data, "one".getBytes())); - CompletionStage combinedStage = client.setData().forPath("/test", "new".getBytes()).thenCompose( - __ -> client.getData().forPath("/test")); + CompletionStage combinedStage = client.setData() + .forPath("/test", "new".getBytes()) + .thenCompose(__ -> client.getData().forPath("/test")); complete(combinedStage, (data, e) -> assertArrayEquals(data, "new".getBytes())); - CompletionStage combinedDelete = client.create().withMode(EPHEMERAL_SEQUENTIAL).forPath("/deleteme").thenCompose( - path -> client.delete().forPath(path)); + CompletionStage combinedDelete = client.create() + .withMode(EPHEMERAL_SEQUENTIAL) + .forPath("/deleteme") + .thenCompose(path -> client.delete().forPath(path)); complete(combinedDelete, (v, e) -> assertNull(e)); - CompletionStage setDataIfStage = client.create().withOptions(of(compress, setDataIfExists)).forPath("/test", "last".getBytes()) - .thenCompose(__ -> client.getData().decompressed().forPath("/test")); + CompletionStage setDataIfStage = client.create() + .withOptions(of(compress, setDataIfExists)) + .forPath("/test", "last".getBytes()) + .thenCompose(__ -> client.getData().decompressed().forPath("/test")); complete(setDataIfStage, (data, e) -> assertArrayEquals(data, "last".getBytes())); } @Test - public void testException() - { + public void testException() { CountDownLatch latch = new CountDownLatch(1); client.getData().forPath("/woop").exceptionally(e -> { assertTrue(e instanceof KeeperException); - assertEquals(((KeeperException)e).code(), KeeperException.Code.NONODE); + assertEquals(((KeeperException) e).code(), KeeperException.Code.NONODE); latch.countDown(); return null; }); @@ -119,8 +120,7 @@ public void testException() } @Test - public void testWatching() - { + public void testWatching() { CountDownLatch latch = new CountDownLatch(1); client.watched().checkExists().forPath("/test").event().whenComplete((event, exception) -> { assertNull(exception); @@ -132,16 +132,12 @@ public void testWatching() } @Test - public void testWatchingWithServerLoss() throws Exception - { + public void testWatchingWithServerLoss() throws Exception { AsyncStage stage = client.watched().checkExists().forPath("/test"); stage.thenRun(() -> { - try - { + try { server.stop(); - } - catch ( IOException e ) - { + } catch (IOException e) { // ignore } }); @@ -149,8 +145,8 @@ public void testWatchingWithServerLoss() throws Exception CountDownLatch latch = new CountDownLatch(1); complete(stage.event(), (v, e) -> { assertTrue(e instanceof AsyncEventException); - assertEquals(((AsyncEventException)e).getKeeperState(), Watcher.Event.KeeperState.Disconnected); - ((AsyncEventException)e).reset().thenRun(latch::countDown); + assertEquals(((AsyncEventException) e).getKeeperState(), Watcher.Event.KeeperState.Disconnected); + ((AsyncEventException) e).reset().thenRun(latch::countDown); }); server.restart(); @@ -159,9 +155,9 @@ public void testWatchingWithServerLoss() throws Exception } @Test - public void testResultWrapper() throws Exception - { - CompletionStage> resultStage = AsyncResult.of(client.create().forPath("/first")); + public void testResultWrapper() throws Exception { + CompletionStage> resultStage = + AsyncResult.of(client.create().forPath("/first")); complete(resultStage, (v, e) -> { assertNull(e); assertEquals(v.getRawValue(), "/first"); @@ -197,8 +193,7 @@ public void testResultWrapper() throws Exception } @Test - public void testGetDataWithStat() - { + public void testGetDataWithStat() { complete(client.create().forPath("/test", "hey".getBytes())); Stat stat = new Stat(); diff --git a/curator-x-async/src/test/java/org/apache/curator/x/async/migrations/TestMigrationManager.java b/curator-x-async/src/test/java/org/apache/curator/x/async/migrations/TestMigrationManager.java index 90b1b94d4..fc86a6423 100644 --- a/curator-x-async/src/test/java/org/apache/curator/x/async/migrations/TestMigrationManager.java +++ b/curator-x-async/src/test/java/org/apache/curator/x/async/migrations/TestMigrationManager.java @@ -26,6 +26,18 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; import com.google.common.base.Throwables; +import java.time.Duration; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.concurrent.CompletionStage; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.api.transaction.CuratorOp; @@ -46,21 +58,7 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import java.time.Duration; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.concurrent.CompletionStage; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.concurrent.atomic.AtomicReference; - -public class TestMigrationManager extends CompletableBaseClassForTests -{ +public class TestMigrationManager extends CompletableBaseClassForTests { private static final String LOCK_PATH = "/migrations/locks"; private static final String META_DATA_PATH = "/migrations/metadata"; private AsyncCuratorFramework client; @@ -78,44 +76,45 @@ public class TestMigrationManager extends CompletableBaseClassForTests @BeforeEach @Override - public void setup() throws Exception - { + public void setup() throws Exception { super.setup(); filterIsSetLatch = new CountDownLatch(1); - CuratorFramework rawClient = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(100)); + CuratorFramework rawClient = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(100)); rawClient.start(); this.client = AsyncCuratorFramework.wrap(rawClient); ZPath modelPath = ZPath.parse("/test/it"); - v1Spec = ModelSpec.builder(modelPath, JacksonModelSerializer.build(ModelV1.class)).build(); - v2Spec = ModelSpec.builder(modelPath, JacksonModelSerializer.build(ModelV2.class)).build(); - v3Spec = ModelSpec.builder(modelPath, JacksonModelSerializer.build(ModelV3.class)).build(); - - v1opA = client.unwrap().transactionOp().create().forPath(v1Spec.path().parent().fullPath()); + v1Spec = ModelSpec.builder(modelPath, JacksonModelSerializer.build(ModelV1.class)) + .build(); + v2Spec = ModelSpec.builder(modelPath, JacksonModelSerializer.build(ModelV2.class)) + .build(); + v3Spec = ModelSpec.builder(modelPath, JacksonModelSerializer.build(ModelV3.class)) + .build(); + + v1opA = client.unwrap() + .transactionOp() + .create() + .forPath(v1Spec.path().parent().fullPath()); v1opB = ModeledFramework.wrap(client, v1Spec).createOp(new ModelV1("Test")); v2op = ModeledFramework.wrap(client, v2Spec).updateOp(new ModelV2("Test 2", 10)); v3op = ModeledFramework.wrap(client, v3Spec).updateOp(new ModelV3("One", "Two", 30)); executor = Executors.newCachedThreadPool(); - manager = new MigrationManager(client, LOCK_PATH, META_DATA_PATH, executor, Duration.ofMinutes(10)) - { + manager = new MigrationManager(client, LOCK_PATH, META_DATA_PATH, executor, Duration.ofMinutes(10)) { @Override - protected List filter(MigrationSet set, List operationHashesInOrder) throws MigrationException - { + protected List filter(MigrationSet set, List operationHashesInOrder) + throws MigrationException { CountDownLatch localLatch = filterLatch.getAndSet(null); - if ( localLatch != null ) - { + if (localLatch != null) { filterIsSetLatch.countDown(); - try - { + try { localLatch.await(); - } - catch ( InterruptedException e ) - { + } catch (InterruptedException e) { Thread.currentThread().interrupt(); Throwables.propagate(e); } @@ -128,16 +127,14 @@ protected List filter(MigrationSet set, List operationHashesI @AfterEach @Override - public void teardown() throws Exception - { + public void teardown() throws Exception { CloseableUtils.closeQuietly(client.unwrap()); executor.shutdownNow(); super.teardown(); } @Test - public void testBasic() - { + public void testBasic() { Migration m1 = () -> Arrays.asList(v1opA, v1opB); Migration m2 = () -> Collections.singletonList(v2op); Migration m3 = () -> Collections.singletonList(v3op); @@ -154,12 +151,11 @@ public void testBasic() int count = manager.debugCount.get(); complete(manager.migrate(migrationSet)); - assertEquals(manager.debugCount.get(), count); // second call should do nothing + assertEquals(manager.debugCount.get(), count); // second call should do nothing } @Test - public void testStaged() - { + public void testStaged() { Migration m1 = () -> Arrays.asList(v1opA, v1opB); MigrationSet migrationSet = MigrationSet.build("1", Collections.singletonList(m1)); complete(manager.migrate(migrationSet)); @@ -190,8 +186,7 @@ public void testStaged() } @Test - public void testDocExample() throws Exception - { + public void testDocExample() throws Exception { CuratorOp op1 = client.transactionOp().create().forPath("/parent"); CuratorOp op2 = client.transactionOp().create().forPath("/parent/one"); CuratorOp op3 = client.transactionOp().create().forPath("/parent/two"); @@ -206,7 +201,7 @@ public void testDocExample() throws Exception assertArrayEquals(client.unwrap().getData().forPath("/main"), "hey".getBytes()); CuratorOp newOp1 = client.transactionOp().create().forPath("/new"); - CuratorOp newOp2 = client.transactionOp().delete().forPath("/main"); // maybe this is no longer needed + CuratorOp newOp2 = client.transactionOp().delete().forPath("/main"); // maybe this is no longer needed Migration newMigration = () -> Arrays.asList(newOp1, newOp2); migrationSet = MigrationSet.build("main", Arrays.asList(initialMigration, newMigration)); @@ -216,8 +211,7 @@ public void testDocExample() throws Exception } @Test - public void testChecksumDataError() - { + public void testChecksumDataError() { CuratorOp op1 = client.transactionOp().create().forPath("/test"); CuratorOp op2 = client.transactionOp().create().forPath("/test/bar", "first".getBytes()); Migration migration = () -> Arrays.asList(op1, op2); @@ -227,20 +221,16 @@ public void testChecksumDataError() CuratorOp op2Changed = client.transactionOp().create().forPath("/test/bar", "second".getBytes()); migration = () -> Arrays.asList(op1, op2Changed); migrationSet = MigrationSet.build("1", Collections.singletonList(migration)); - try - { + try { complete(manager.migrate(migrationSet)); fail("Should throw"); - } - catch ( Throwable e ) - { + } catch (Throwable e) { assertTrue(Throwables.getRootCause(e) instanceof MigrationException); } } @Test - public void testChecksumPathError() - { + public void testChecksumPathError() { CuratorOp op1 = client.transactionOp().create().forPath("/test2"); CuratorOp op2 = client.transactionOp().create().forPath("/test2/bar"); Migration migration = () -> Arrays.asList(op1, op2); @@ -250,52 +240,41 @@ public void testChecksumPathError() CuratorOp op2Changed = client.transactionOp().create().forPath("/test/bar"); migration = () -> Arrays.asList(op1, op2Changed); migrationSet = MigrationSet.build("1", Collections.singletonList(migration)); - try - { + try { complete(manager.migrate(migrationSet)); fail("Should throw"); - } - catch ( Throwable e ) - { + } catch (Throwable e) { assertTrue(Throwables.getRootCause(e) instanceof MigrationException); } } @Test - public void testPartialApplyForBadOps() throws Exception - { + public void testPartialApplyForBadOps() throws Exception { CuratorOp op1 = client.transactionOp().create().forPath("/test", "something".getBytes()); CuratorOp op2 = client.transactionOp().create().forPath("/a/b/c"); Migration m1 = () -> Collections.singletonList(op1); Migration m2 = () -> Collections.singletonList(op2); MigrationSet migrationSet = MigrationSet.build("1", Arrays.asList(m1, m2)); - try - { + try { complete(manager.migrate(migrationSet)); fail("Should throw"); - } - catch ( Throwable e ) - { + } catch (Throwable e) { assertTrue(Throwables.getRootCause(e) instanceof KeeperException.NoNodeException); } - assertNull(client.unwrap().checkExists().forPath("/test")); // should be all or nothing + assertNull(client.unwrap().checkExists().forPath("/test")); // should be all or nothing } @Test - public void testTransactionForBadOps() throws Exception - { + public void testTransactionForBadOps() throws Exception { CuratorOp op1 = client.transactionOp().create().forPath("/test2", "something".getBytes()); CuratorOp op2 = client.transactionOp().create().forPath("/a/b/c/d"); Migration migration = () -> Arrays.asList(op1, op2); MigrationSet migrationSet = MigrationSet.build("1", Collections.singletonList(migration)); - try - { + try { complete(manager.migrate(migrationSet)); fail("Should throw"); - } - catch ( Throwable e ) - { + } catch (Throwable e) { assertTrue(Throwables.getRootCause(e) instanceof KeeperException.NoNodeException); } @@ -303,8 +282,7 @@ public void testTransactionForBadOps() throws Exception } @Test - public void testConcurrency1() throws Exception - { + public void testConcurrency1() throws Exception { CuratorOp op1 = client.transactionOp().create().forPath("/test"); CuratorOp op2 = client.transactionOp().create().forPath("/test/bar", "first".getBytes()); Migration migration = () -> Arrays.asList(op1, op2); @@ -314,15 +292,20 @@ public void testConcurrency1() throws Exception CompletionStage first = manager.migrate(migrationSet); assertTrue(timing.awaitLatch(filterIsSetLatch)); - MigrationManager manager2 = new MigrationManager(client, LOCK_PATH, META_DATA_PATH, executor, Duration.ofMillis(timing.forSleepingABit().milliseconds())); - try - { + MigrationManager manager2 = new MigrationManager( + client, + LOCK_PATH, + META_DATA_PATH, + executor, + Duration.ofMillis(timing.forSleepingABit().milliseconds())); + try { complete(manager2.migrate(migrationSet)); fail("Should throw"); - } - catch ( Throwable e ) - { - assertTrue(Throwables.getRootCause(e) instanceof AsyncWrappers.TimeoutException, "Should throw AsyncWrappers.TimeoutException, was: " + Throwables.getStackTraceAsString(Throwables.getRootCause(e))); + } catch (Throwable e) { + assertTrue( + Throwables.getRootCause(e) instanceof AsyncWrappers.TimeoutException, + "Should throw AsyncWrappers.TimeoutException, was: " + + Throwables.getStackTraceAsString(Throwables.getRootCause(e))); } latch.countDown(); @@ -331,8 +314,7 @@ public void testConcurrency1() throws Exception } @Test - public void testConcurrency2() throws Exception - { + public void testConcurrency2() throws Exception { CuratorOp op1 = client.transactionOp().create().forPath("/test"); CuratorOp op2 = client.transactionOp().create().forPath("/test/bar", "first".getBytes()); Migration migration = () -> Arrays.asList(op1, op2); @@ -343,14 +325,14 @@ public void testConcurrency2() throws Exception assertTrue(timing.awaitLatch(filterIsSetLatch)); CompletionStage second = manager.migrate(migrationSet); - try - { + try { second.toCompletableFuture().get(timing.forSleepingABit().milliseconds(), TimeUnit.MILLISECONDS); fail("Should throw"); - } - catch ( Throwable e ) - { - assertTrue(Throwables.getRootCause(e) instanceof TimeoutException, "Should throw TimeoutException, was: " + Throwables.getStackTraceAsString(Throwables.getRootCause(e))); + } catch (Throwable e) { + assertTrue( + Throwables.getRootCause(e) instanceof TimeoutException, + "Should throw TimeoutException, was: " + + Throwables.getStackTraceAsString(Throwables.getRootCause(e))); } latch.countDown(); diff --git a/curator-x-async/src/test/java/org/apache/curator/x/async/migrations/models/ModelV1.java b/curator-x-async/src/test/java/org/apache/curator/x/async/migrations/models/ModelV1.java index 0f9085c27..6465a138a 100644 --- a/curator-x-async/src/test/java/org/apache/curator/x/async/migrations/models/ModelV1.java +++ b/curator-x-async/src/test/java/org/apache/curator/x/async/migrations/models/ModelV1.java @@ -19,22 +19,18 @@ package org.apache.curator.x.async.migrations.models; -public class ModelV1 -{ +public class ModelV1 { private final String name; - public ModelV1() - { + public ModelV1() { this(""); } - public ModelV1(String name) - { + public ModelV1(String name) { this.name = name; } - public String getName() - { + public String getName() { return name; } } diff --git a/curator-x-async/src/test/java/org/apache/curator/x/async/migrations/models/ModelV2.java b/curator-x-async/src/test/java/org/apache/curator/x/async/migrations/models/ModelV2.java index 85bd463c6..7c9b888f8 100644 --- a/curator-x-async/src/test/java/org/apache/curator/x/async/migrations/models/ModelV2.java +++ b/curator-x-async/src/test/java/org/apache/curator/x/async/migrations/models/ModelV2.java @@ -19,29 +19,24 @@ package org.apache.curator.x.async.migrations.models; -public class ModelV2 -{ +public class ModelV2 { private final String name; private final int age; - public ModelV2() - { + public ModelV2() { this("", 0); } - public ModelV2(String name, int age) - { + public ModelV2(String name, int age) { this.name = name; this.age = age; } - public String getName() - { + public String getName() { return name; } - public int getAge() - { + public int getAge() { return age; } } diff --git a/curator-x-async/src/test/java/org/apache/curator/x/async/migrations/models/ModelV3.java b/curator-x-async/src/test/java/org/apache/curator/x/async/migrations/models/ModelV3.java index 0418190ad..ceab423f0 100644 --- a/curator-x-async/src/test/java/org/apache/curator/x/async/migrations/models/ModelV3.java +++ b/curator-x-async/src/test/java/org/apache/curator/x/async/migrations/models/ModelV3.java @@ -19,36 +19,30 @@ package org.apache.curator.x.async.migrations.models; -public class ModelV3 -{ +public class ModelV3 { private final String firstName; private final String lastName; private final int age; - public ModelV3() - { + public ModelV3() { this("", "", 0); } - public ModelV3(String firstName, String lastName, int age) - { + public ModelV3(String firstName, String lastName, int age) { this.firstName = firstName; this.lastName = lastName; this.age = age; } - public String getFirstName() - { + public String getFirstName() { return firstName; } - public String getLastName() - { + public String getLastName() { return lastName; } - public int getAge() - { + public int getAge() { return age; } } diff --git a/curator-x-async/src/test/java/org/apache/curator/x/async/modeled/TestCachedModeledFramework.java b/curator-x-async/src/test/java/org/apache/curator/x/async/modeled/TestCachedModeledFramework.java index 692417d0b..65c68aba9 100644 --- a/curator-x-async/src/test/java/org/apache/curator/x/async/modeled/TestCachedModeledFramework.java +++ b/curator-x-async/src/test/java/org/apache/curator/x/async/modeled/TestCachedModeledFramework.java @@ -24,18 +24,7 @@ import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; - import com.google.common.collect.Sets; -import org.apache.curator.framework.state.ConnectionState; -import org.apache.curator.test.Timing; -import org.apache.curator.test.compatibility.CuratorTestBase; -import org.apache.curator.x.async.modeled.cached.CachedModeledFramework; -import org.apache.curator.x.async.modeled.cached.ModeledCacheListener; -import org.apache.curator.x.async.modeled.models.TestModel; -import org.apache.zookeeper.data.Stat; -import org.junit.jupiter.api.Tag; -import org.junit.jupiter.api.Test; - import java.io.IOException; import java.math.BigInteger; import java.util.Arrays; @@ -49,30 +38,36 @@ import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.Stream; +import org.apache.curator.framework.state.ConnectionState; +import org.apache.curator.test.Timing; +import org.apache.curator.test.compatibility.CuratorTestBase; +import org.apache.curator.x.async.modeled.cached.CachedModeledFramework; +import org.apache.curator.x.async.modeled.cached.ModeledCacheListener; +import org.apache.curator.x.async.modeled.models.TestModel; +import org.apache.zookeeper.data.Stat; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; @Tag(CuratorTestBase.zk35TestCompatibilityGroup) -public class TestCachedModeledFramework extends TestModeledFrameworkBase -{ +public class TestCachedModeledFramework extends TestModeledFrameworkBase { @Test - public void testDownServer() throws IOException - { + public void testDownServer() throws IOException { Timing timing = new Timing(); TestModel model = new TestModel("a", "b", "c", 1, BigInteger.ONE); - CachedModeledFramework client = ModeledFramework.wrap(async, modelSpec).cached(); + CachedModeledFramework client = + ModeledFramework.wrap(async, modelSpec).cached(); Semaphore semaphore = new Semaphore(0); client.listenable().addListener((t, p, s, m) -> semaphore.release()); client.start(); - try - { + try { client.child(model).set(model); assertTrue(timing.acquireSemaphore(semaphore)); CountDownLatch latch = new CountDownLatch(1); rawClient.getConnectionStateListenable().addListener((__, state) -> { - if ( state == ConnectionState.LOST ) - { + if (state == ConnectionState.LOST) { latch.countDown(); } }); @@ -83,49 +78,43 @@ public void testDownServer() throws IOException assertNotNull(value); assertNull(e); })); - } - finally - { + } finally { client.close(); } } @Test - public void testPostInitializedFilter() - { + public void testPostInitializedFilter() { TestModel model1 = new TestModel("a", "b", "c", 1, BigInteger.ONE); TestModel model2 = new TestModel("d", "e", "f", 1, BigInteger.ONE); - CachedModeledFramework client = ModeledFramework.wrap(async, modelSpec).cached(); + CachedModeledFramework client = + ModeledFramework.wrap(async, modelSpec).cached(); Semaphore semaphore = new Semaphore(0); ModeledCacheListener listener = (t, p, s, m) -> semaphore.release(); client.listenable().addListener(listener.postInitializedOnly()); - complete(client.child("1").set(model1)); // set before cache is started + complete(client.child("1").set(model1)); // set before cache is started client.start(); - try - { + try { assertFalse(timing.forSleepingABit().acquireSemaphore(semaphore)); - client.child("2").set(model2); // set before cache is started + client.child("2").set(model2); // set before cache is started assertTrue(timing.acquireSemaphore(semaphore)); - } - finally - { + } finally { client.close(); } } @Test - public void testChildren() - { + public void testChildren() { TestModel parent = new TestModel("a", "b", "c", 20, BigInteger.ONE); TestModel child1 = new TestModel("d", "e", "f", 1, BigInteger.ONE); TestModel child2 = new TestModel("g", "h", "i", 1, BigInteger.ONE); TestModel grandChild1 = new TestModel("j", "k", "l", 10, BigInteger.ONE); TestModel grandChild2 = new TestModel("m", "n", "0", 5, BigInteger.ONE); - try (CachedModeledFramework client = ModeledFramework.wrap(async, modelSpec).cached()) - { + try (CachedModeledFramework client = + ModeledFramework.wrap(async, modelSpec).cached()) { CountDownLatch latch = new CountDownLatch(5); client.listenable().addListener((t, p, s, m) -> latch.countDown()); @@ -137,17 +126,14 @@ public void testChildren() complete(client.child("p").child("c2").child("g2").set(grandChild2)); assertTrue(timing.awaitLatch(latch)); - complete(client.child("p").children(), (v, e) -> - { + complete(client.child("p").children(), (v, e) -> { List paths = Arrays.asList( - client.child("p").child("c1").modelSpec().path(), - client.child("p").child("c2").modelSpec().path() - ); + client.child("p").child("c1").modelSpec().path(), + client.child("p").child("c2").modelSpec().path()); assertEquals(v, paths); }); - complete(client.child("p").childrenAsZNodes(), (v, e) -> - { + complete(client.child("p").childrenAsZNodes(), (v, e) -> { Set cachedModels = toSet(v.stream(), ZNode::model); assertEquals(cachedModels, Sets.newHashSet(child1, child2)); @@ -158,18 +144,21 @@ public void testChildren() }); }); - complete(client.child("p").child("c1").childrenAsZNodes(), (v, e) -> assertEquals(toSet(v.stream(), ZNode::model), Sets.newHashSet(grandChild1))); - complete(client.child("p").child("c2").childrenAsZNodes(), (v, e) -> assertEquals(toSet(v.stream(), ZNode::model), Sets.newHashSet(grandChild2))); + complete( + client.child("p").child("c1").childrenAsZNodes(), + (v, e) -> assertEquals(toSet(v.stream(), ZNode::model), Sets.newHashSet(grandChild1))); + complete( + client.child("p").child("c2").childrenAsZNodes(), + (v, e) -> assertEquals(toSet(v.stream(), ZNode::model), Sets.newHashSet(grandChild2))); } } // note: CURATOR-546 @Test - public void testAccessCacheDirectly() - { + public void testAccessCacheDirectly() { TestModel model = new TestModel("a", "b", "c", 20, BigInteger.ONE); - try (CachedModeledFramework client = ModeledFramework.wrap(async, modelSpec).cached()) - { + try (CachedModeledFramework client = + ModeledFramework.wrap(async, modelSpec).cached()) { CountDownLatch latch = new CountDownLatch(1); client.listenable().addListener((t, p, s, m) -> latch.countDown()); @@ -178,10 +167,17 @@ public void testAccessCacheDirectly() assertTrue(timing.awaitLatch(latch)); // call 2 times in a row to validate CURATOR-546 - Optional> optZNode = client.cache().currentData(modelSpec.path().child("m")); - assertEquals(optZNode.orElseThrow(() -> new AssertionError("node is missing")).model(), model); + Optional> optZNode = + client.cache().currentData(modelSpec.path().child("m")); + assertEquals( + optZNode.orElseThrow(() -> new AssertionError("node is missing")) + .model(), + model); optZNode = client.cache().currentData(modelSpec.path().child("m")); - assertEquals(optZNode.orElseThrow(() -> new AssertionError("node is missing")).model(), model); + assertEquals( + optZNode.orElseThrow(() -> new AssertionError("node is missing")) + .model(), + model); } } @@ -189,8 +185,7 @@ public void testAccessCacheDirectly() // model serializer. // See: CURATOR-609 @Test - public void testEmptyNodeJacksonDeserialization() - { + public void testEmptyNodeJacksonDeserialization() { final TestModel model = new TestModel("a", "b", "c", 20, BigInteger.ONE); verifyEmptyNodeDeserialization(model, modelSpec); } @@ -199,15 +194,14 @@ public void testEmptyNodeJacksonDeserialization() // model serializer. // See: CURATOR-609 @Test - public void testEmptyNodeRawDeserialization() - { + public void testEmptyNodeRawDeserialization() { final byte[] byteModel = {0x01, 0x02, 0x03}; - final ModelSpec byteModelSpec = ModelSpec.builder(path, ModelSerializer.raw).build(); + final ModelSpec byteModelSpec = + ModelSpec.builder(path, ModelSerializer.raw).build(); verifyEmptyNodeDeserialization(byteModel, byteModelSpec); } - private void verifyEmptyNodeDeserialization(T model, ModelSpec parentModelSpec) - { + private void verifyEmptyNodeDeserialization(T model, ModelSpec parentModelSpec) { // The sub-path is the ZNode that will be removed that does not contain any model data. Their should be no // attempt to deserialize this empty ZNode. final String subPath = parentModelSpec.path().toString() + "/sub"; @@ -223,8 +217,7 @@ private void verifyEmptyNodeDeserialization(T model, ModelSpec parentMode // Create a custom listener to signal the end of the test and ensure that nothing is thrown. final ModeledCacheListener listener = new ModeledCacheListener() { @Override - public void accept(Type t, ZPath p, Stat s, T m) - { + public void accept(Type t, ZPath p, Stat s, T m) { // We don't expect the handler to be called with a null model. if (m == null) { modelWasNull.set(true); @@ -235,8 +228,7 @@ public void accept(Type t, ZPath p, Stat s, T m) } } - public void handleException(Exception e) - { + public void handleException(Exception e) { caughtHandleException.set(e); } }; @@ -244,14 +236,16 @@ public void handleException(Exception e) final ModelSerializer serializer = parentModelSpec.serializer(); // Create a cache client to watch the parent path. - try (CachedModeledFramework cacheClient = ModeledFramework.wrap(async, parentModelSpec).cached()) - { + try (CachedModeledFramework cacheClient = + ModeledFramework.wrap(async, parentModelSpec).cached()) { cacheClient.listenable().addListener(listener); - ModelSpec testModelSpec = ModelSpec.builder(ZPath.parse(testModelPath), serializer).build(); + ModelSpec testModelSpec = + ModelSpec.builder(ZPath.parse(testModelPath), serializer).build(); ModeledFramework testModelClient = ModeledFramework.wrap(async, testModelSpec); - ModelSpec signalModelSpec = ModelSpec.builder(ZPath.parse(signalModelPath), serializer).build(); + ModelSpec signalModelSpec = + ModelSpec.builder(ZPath.parse(signalModelPath), serializer).build(); ModeledFramework signalModelClient = ModeledFramework.wrap(async, signalModelSpec); cacheClient.start(); @@ -274,8 +268,7 @@ public void handleException(Exception e) } } - private Set toSet(Stream stream, Function mapper) - { - return stream.map(mapper).collect(Collectors.toSet()); + private Set toSet(Stream stream, Function mapper) { + return stream.map(mapper).collect(Collectors.toSet()); } } diff --git a/curator-x-async/src/test/java/org/apache/curator/x/async/modeled/TestModeledFramework.java b/curator-x-async/src/test/java/org/apache/curator/x/async/modeled/TestModeledFramework.java index 7f5c6816d..768c90128 100644 --- a/curator-x-async/src/test/java/org/apache/curator/x/async/modeled/TestModeledFramework.java +++ b/curator-x-async/src/test/java/org/apache/curator/x/async/modeled/TestModeledFramework.java @@ -59,11 +59,9 @@ import org.apache.zookeeper.server.auth.DigestAuthenticationProvider; import org.junit.jupiter.api.Test; -public class TestModeledFramework extends TestModeledFrameworkBase -{ +public class TestModeledFramework extends TestModeledFrameworkBase { @Test - public void testCrud() - { + public void testCrud() { TestModel rawModel = new TestModel("John", "Galt", "1 Galt's Gulch", 42, BigInteger.valueOf(1)); TestModel rawModel2 = new TestModel("Wayne", "Rooney", "Old Trafford", 10, BigInteger.valueOf(1)); ModeledFramework client = ModeledFramework.wrap(async, modelSpec); @@ -78,9 +76,9 @@ public void testCrud() } @Test - public void testBackwardCompatibility() - { - TestNewerModel rawNewModel = new TestNewerModel("John", "Galt", "1 Galt's Gulch", 42, BigInteger.valueOf(1), 100); + public void testBackwardCompatibility() { + TestNewerModel rawNewModel = + new TestNewerModel("John", "Galt", "1 Galt's Gulch", 42, BigInteger.valueOf(1), 100); ModeledFramework clientForNew = ModeledFramework.wrap(async, newModelSpec); complete(clientForNew.set(rawNewModel), (s, e) -> assertNotNull(s)); @@ -89,10 +87,10 @@ public void testBackwardCompatibility() } @Test - public void testWatched() throws InterruptedException - { + public void testWatched() throws InterruptedException { CountDownLatch latch = new CountDownLatch(1); - ModeledFramework client = ModeledFramework.builder(async, modelSpec).watched().build(); + ModeledFramework client = + ModeledFramework.builder(async, modelSpec).watched().build(); client.checkExists().event().whenComplete((event, ex) -> latch.countDown()); timing.sleepABit(); assertEquals(latch.getCount(), 1); @@ -101,10 +99,10 @@ public void testWatched() throws InterruptedException } @Test - public void testGetChildren() - { + public void testGetChildren() { TestModel model = new TestModel("John", "Galt", "1 Galt's Gulch", 42, BigInteger.valueOf(1)); - ModeledFramework client = ModeledFramework.builder(async, modelSpec).build(); + ModeledFramework client = + ModeledFramework.builder(async, modelSpec).build(); complete(client.child("one").set(model)); complete(client.child("two").set(model)); complete(client.child("three").set(model)); @@ -114,8 +112,7 @@ public void testGetChildren() } @Test - public void testDelete() - { + public void testDelete() { ModeledFramework client = ModeledFramework.wrap(async, modelSpec); complete(client.set(new TestModel())); @@ -131,8 +128,7 @@ public void testDelete() exceptional(client.delete(), KeeperException.NotEmptyException.class); - ModelSpec deleteChildren = ModelSpec - .builder(modelSpec.path(), modelSpec.serializer()) + ModelSpec deleteChildren = ModelSpec.builder(modelSpec.path(), modelSpec.serializer()) .withDeleteOptions(Collections.singleton(DeleteOption.deletingChildrenIfNeeded)) .build(); @@ -140,59 +136,63 @@ public void testDelete() exceptional(ModeledFramework.wrap(async, deleteChildren).delete(), KeeperException.NoNodeException.class); exceptional(client.read(), KeeperException.NoNodeException.class); - ModelSpec quietly = ModelSpec - .builder(modelSpec.path(), modelSpec.serializer()) + ModelSpec quietly = ModelSpec.builder(modelSpec.path(), modelSpec.serializer()) .withDeleteOptions(Collections.singleton(DeleteOption.quietly)) .build(); complete(ModeledFramework.wrap(async, quietly).delete()); } @Test - public void testBadNode() - { - complete(async.create().forPath(modelSpec.path().fullPath(), "fubar".getBytes()), (v, e) -> { - }); // ignore error + public void testBadNode() { + complete(async.create().forPath(modelSpec.path().fullPath(), "fubar".getBytes()), (v, e) -> {}); // ignore error - ModeledFramework client = ModeledFramework.builder(async, modelSpec).watched().build(); + ModeledFramework client = + ModeledFramework.builder(async, modelSpec).watched().build(); complete(client.read(), (model, e) -> assertTrue(e instanceof KeeperException.NoNodeException)); } @Test - public void testSchema() throws Exception - { + public void testSchema() throws Exception { Schema schema = modelSpec.schema(); - try (CuratorFramework schemaClient = CuratorFrameworkFactory.builder().connectString(server.getConnectString()).retryPolicy(new RetryOneTime(1)).schemaSet(new SchemaSet(Collections.singletonList(schema), false)).build()) - { + try (CuratorFramework schemaClient = CuratorFrameworkFactory.builder() + .connectString(server.getConnectString()) + .retryPolicy(new RetryOneTime(1)) + .schemaSet(new SchemaSet(Collections.singletonList(schema), false)) + .build()) { schemaClient.start(); - try - { + try { schemaClient.create().forPath(modelSpec.path().fullPath(), "asflasfas".getBytes()); fail("Should've thrown SchemaViolation"); - } - catch ( SchemaViolation dummy ) - { + } catch (SchemaViolation dummy) { // expected } - ModeledFramework modeledSchemaClient = ModeledFramework.wrap(AsyncCuratorFramework.wrap(schemaClient), modelSpec); - complete(modeledSchemaClient.set(new TestModel("one", "two", "three", 4, BigInteger.ONE)), (dummy, e) -> assertNull(e)); + ModeledFramework modeledSchemaClient = + ModeledFramework.wrap(AsyncCuratorFramework.wrap(schemaClient), modelSpec); + complete( + modeledSchemaClient.set(new TestModel("one", "two", "three", 4, BigInteger.ONE)), + (dummy, e) -> assertNull(e)); } } @Test - public void testVersioned() - { + public void testVersioned() { ModeledFramework client = ModeledFramework.wrap(async, modelSpec); TestModel model = new TestModel("John", "Galt", "Galt's Gulch", 21, BigInteger.valueOf(1010101)); complete(client.set(model)); - complete(client.set(model)); // so that version goes to 1 + complete(client.set(model)); // so that version goes to 1 VersionedModeledFramework versioned = client.versioned(); - complete(versioned.read().whenComplete((v, e) -> { - assertNull(e); - assertTrue(v.version() > 0); - }).thenCompose(versioned::set), (s, e) -> assertNull(e)); // read version is correct; set moves version to 2 + complete( + versioned + .read() + .whenComplete((v, e) -> { + assertNull(e); + assertTrue(v.version() > 0); + }) + .thenCompose(versioned::set), + (s, e) -> assertNull(e)); // read version is correct; set moves version to 2 Versioned badVersion = Versioned.from(model, 100000); complete(versioned.set(badVersion), (v, e) -> assertTrue(e instanceof KeeperException.BadVersionException)); @@ -207,41 +207,54 @@ public void testVersioned() final Stat stat = new Stat(); complete(client.read(stat)); // wrong version, needs to fail - complete(client.delete(stat.getVersion() + 1), (v, e) -> assertTrue(e instanceof KeeperException.BadVersionException)); + complete( + client.delete(stat.getVersion() + 1), + (v, e) -> assertTrue(e instanceof KeeperException.BadVersionException)); // correct version complete(client.delete(stat.getVersion())); } @Test - public void testAcl() throws NoSuchAlgorithmException - { - List aclList = Collections.singletonList(new ACL(ZooDefs.Perms.WRITE, new Id("digest", DigestAuthenticationProvider.generateDigest("test:test")))); - ModelSpec aclModelSpec = ModelSpec.builder(modelSpec.path(), modelSpec.serializer()).withAclList(aclList).build(); + public void testAcl() throws NoSuchAlgorithmException { + List aclList = Collections.singletonList(new ACL( + ZooDefs.Perms.WRITE, new Id("digest", DigestAuthenticationProvider.generateDigest("test:test")))); + ModelSpec aclModelSpec = ModelSpec.builder(modelSpec.path(), modelSpec.serializer()) + .withAclList(aclList) + .build(); ModeledFramework client = ModeledFramework.wrap(async, aclModelSpec); complete(client.set(new TestModel("John", "Galt", "Galt's Gulch", 21, BigInteger.valueOf(1010101)))); - complete(client.update(new TestModel("John", "Galt", "Galt's Gulch", 54, BigInteger.valueOf(88))), (__, e) -> assertNotNull(e, "Should've gotten an auth failure")); + complete( + client.update(new TestModel("John", "Galt", "Galt's Gulch", 54, BigInteger.valueOf(88))), + (__, e) -> assertNotNull(e, "Should've gotten an auth failure")); - try (CuratorFramework authCurator = CuratorFrameworkFactory.builder().connectString(server.getConnectString()).retryPolicy(new RetryOneTime(1)).authorization("digest", "test:test".getBytes()).build()) - { + try (CuratorFramework authCurator = CuratorFrameworkFactory.builder() + .connectString(server.getConnectString()) + .retryPolicy(new RetryOneTime(1)) + .authorization("digest", "test:test".getBytes()) + .build()) { authCurator.start(); - ModeledFramework authClient = ModeledFramework.wrap(AsyncCuratorFramework.wrap(authCurator), aclModelSpec); - complete(authClient.update(new TestModel("John", "Galt", "Galt's Gulch", 42, BigInteger.valueOf(66))), (__, e) -> assertNull(e, "Should've succeeded")); + ModeledFramework authClient = + ModeledFramework.wrap(AsyncCuratorFramework.wrap(authCurator), aclModelSpec); + complete( + authClient.update(new TestModel("John", "Galt", "Galt's Gulch", 42, BigInteger.valueOf(66))), + (__, e) -> assertNull(e, "Should've succeeded")); } } @Test - public void testExceptionHandling() throws Exception - { - final List writeAcl = Collections.singletonList(new ACL(ZooDefs.Perms.WRITE, new Id("digest", DigestAuthenticationProvider.generateDigest("test:test")))); + public void testExceptionHandling() throws Exception { + final List writeAcl = Collections.singletonList(new ACL( + ZooDefs.Perms.WRITE, new Id("digest", DigestAuthenticationProvider.generateDigest("test:test")))); // An ACLProvider is used to get the Write ACL (for the test user) for any path "/test/**". final ACLProvider aclProvider = new ACLProvider() { @Override - public List getDefaultAcl() { return ZooDefs.Ids.READ_ACL_UNSAFE; } + public List getDefaultAcl() { + return ZooDefs.Ids.READ_ACL_UNSAFE; + } @Override - public List getAclForPath(String path) - { + public List getAclForPath(String path) { // Any sub-path "/test/**" should only be writeable by the test user. return path.startsWith("/test") ? writeAcl : getDefaultAcl(); } @@ -271,19 +284,20 @@ public List getAclForPath(String path) // I overrode the TestModel provided path with a multi-component path under the "/test" parent path // (which was previously created with ACL protection). ModelSpec aclModelSpec = ModelSpec.builder(ZPath.parse("/test/foo/bar"), modelSpec.serializer()) - .withCreateOptions(EnumSet.of(CreateOption.createParentsIfNeeded, CreateOption.createParentsAsContainers)) + .withCreateOptions( + EnumSet.of(CreateOption.createParentsIfNeeded, CreateOption.createParentsAsContainers)) .build(); - ModeledFramework noAuthClient = ModeledFramework.wrap(AsyncCuratorFramework.wrap(unauthorizedFramework), aclModelSpec); + ModeledFramework noAuthClient = + ModeledFramework.wrap(AsyncCuratorFramework.wrap(unauthorizedFramework), aclModelSpec); - noAuthClient.set(new TestModel("John", "Galt", "Galt's Gulch", 42, BigInteger.valueOf(66))) + noAuthClient + .set(new TestModel("John", "Galt", "Galt's Gulch", 42, BigInteger.valueOf(66))) .toCompletableFuture() .get(timing.forWaiting().milliseconds(), TimeUnit.MILLISECONDS); fail("expect to throw a NoAuth KeeperException"); - } - catch (ExecutionException | CompletionException e) - { - assertTrue(e.getCause() instanceof KeeperException.NoAuthException); + } catch (ExecutionException | CompletionException e) { + assertTrue(e.getCause() instanceof KeeperException.NoAuthException); } } } diff --git a/curator-x-async/src/test/java/org/apache/curator/x/async/modeled/TestModeledFrameworkBase.java b/curator-x-async/src/test/java/org/apache/curator/x/async/modeled/TestModeledFrameworkBase.java index bb5b06db8..2941ef33a 100644 --- a/curator-x-async/src/test/java/org/apache/curator/x/async/modeled/TestModeledFrameworkBase.java +++ b/curator-x-async/src/test/java/org/apache/curator/x/async/modeled/TestModeledFrameworkBase.java @@ -30,8 +30,7 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; -public class TestModeledFrameworkBase extends CompletableBaseClassForTests -{ +public class TestModeledFrameworkBase extends CompletableBaseClassForTests { protected static final ZPath path = ZPath.parse("/test/path"); protected CuratorFramework rawClient; protected ModelSpec modelSpec; @@ -40,11 +39,11 @@ public class TestModeledFrameworkBase extends CompletableBaseClassForTests @BeforeEach @Override - public void setup() throws Exception - { + public void setup() throws Exception { super.setup(); - rawClient = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); + rawClient = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); rawClient.start(); async = AsyncCuratorFramework.wrap(rawClient); @@ -57,8 +56,7 @@ public void setup() throws Exception @AfterEach @Override - public void teardown() throws Exception - { + public void teardown() throws Exception { CloseableUtils.closeQuietly(rawClient); super.teardown(); } diff --git a/curator-x-async/src/test/java/org/apache/curator/x/async/modeled/TestZPath.java b/curator-x-async/src/test/java/org/apache/curator/x/async/modeled/TestZPath.java index 08545633a..a93183d3a 100644 --- a/curator-x-async/src/test/java/org/apache/curator/x/async/modeled/TestZPath.java +++ b/curator-x-async/src/test/java/org/apache/curator/x/async/modeled/TestZPath.java @@ -29,11 +29,9 @@ import org.apache.curator.x.async.modeled.details.ZPathImpl; import org.junit.jupiter.api.Test; -public class TestZPath -{ +public class TestZPath { @Test - public void testRoot() - { + public void testRoot() { assertEquals(ZPath.root.nodeName(), ZKPaths.PATH_SEPARATOR); assertEquals(ZPath.root, ZPathImpl.root); assertTrue(ZPath.root.isRoot()); @@ -42,8 +40,7 @@ public void testRoot() } @Test - public void testBasic() - { + public void testBasic() { ZPath path = ZPath.root.child("one").child("two"); assertFalse(path.isRoot()); assertEquals(path, ZPath.root.child("one").child("two")); @@ -51,8 +48,8 @@ public void testBasic() assertEquals(path.nodeName(), "two"); assertEquals(path.fullPath(), "/one/two"); assertEquals(path.parent().fullPath(), "/one"); - assertEquals(path.fullPath(), "/one/two"); // call twice to test the internal cache - assertEquals(path.parent().fullPath(), "/one"); // call twice to test the internal cache + assertEquals(path.fullPath(), "/one/two"); // call twice to test the internal cache + assertEquals(path.parent().fullPath(), "/one"); // call twice to test the internal cache assertTrue(path.startsWith(ZPath.root.child("one"))); assertFalse(path.startsWith(ZPath.root.child("two"))); @@ -69,33 +66,31 @@ public void testBasic() } @Test - public void testParsing() - { + public void testParsing() { assertEquals(ZPath.parse("/"), ZPath.root); - assertEquals(ZPath.parse("/one/two/three"), ZPath.root.child("one").child("two").child("three")); + assertEquals( + ZPath.parse("/one/two/three"), + ZPath.root.child("one").child("two").child("three")); assertEquals(ZPath.parse("/one/two/three"), ZPath.from("one", "two", "three")); assertEquals(ZPath.parseWithIds("/one/{id}/two/{id}"), ZPath.from("one", parameter(), "two", parameter())); } @Test - public void testUnresolvedPath() - { - assertThrows(IllegalStateException.class, ()->{ + public void testUnresolvedPath() { + assertThrows(IllegalStateException.class, () -> { ZPath path = ZPath.from("one", parameter(), "two"); path.fullPath(); }); } @Test - public void testResolvedPath() - { + public void testResolvedPath() { ZPath path = ZPath.from("one", parameter(), "two", parameter()); assertEquals(path.resolved("a", "b"), ZPath.from("one", "a", "two", "b")); } @Test - public void testSchema() - { + public void testSchema() { ZPath path = ZPath.from("one", parameter(), "two", parameter()); assertEquals(path.toSchemaPathPattern().toString(), "/one/.*/two/.*"); path = ZPath.parse("/one/two/three"); @@ -107,16 +102,14 @@ public void testSchema() } @Test - public void testCustomIds() - { + public void testCustomIds() { assertEquals(ZPath.parseWithIds("/a/{a}/bee/{bee}/c/{c}").toString(), "/a/{a}/bee/{bee}/c/{c}"); assertEquals(ZPath.from("a", parameter(), "b", parameter()).toString(), "/a/{id}/b/{id}"); assertEquals(ZPath.from("a", parameter("foo"), "b", parameter("bar")).toString(), "/a/{foo}/b/{bar}"); } @Test - public void testPartialResolution() - { + public void testPartialResolution() { ZPath path = ZPath.parseWithIds("/one/{1}/two/{2}"); assertFalse(path.parent().isResolved()); assertFalse(path.parent().parent().isResolved()); diff --git a/curator-x-async/src/test/java/org/apache/curator/x/async/modeled/models/TestModel.java b/curator-x-async/src/test/java/org/apache/curator/x/async/modeled/models/TestModel.java index d34cf642a..8e84282b2 100644 --- a/curator-x-async/src/test/java/org/apache/curator/x/async/modeled/models/TestModel.java +++ b/curator-x-async/src/test/java/org/apache/curator/x/async/modeled/models/TestModel.java @@ -22,21 +22,18 @@ import java.math.BigInteger; import java.util.Objects; -public class TestModel -{ +public class TestModel { private final String firstName; private final String lastName; private final String address; private final int age; private final BigInteger salary; - public TestModel() - { + public TestModel() { this("", "", "", 0, BigInteger.ZERO); } - public TestModel(String firstName, String lastName, String address, int age, BigInteger salary) - { + public TestModel(String firstName, String lastName, String address, int age, BigInteger salary) { this.firstName = Objects.requireNonNull(firstName, "firstName cannot be null"); this.lastName = Objects.requireNonNull(lastName, "lastName cannot be null"); this.address = Objects.requireNonNull(address, "address cannot be null"); @@ -44,68 +41,55 @@ public TestModel(String firstName, String lastName, String address, int age, Big this.salary = salary; } - public String getFirstName() - { + public String getFirstName() { return firstName; } - public String getLastName() - { + public String getLastName() { return lastName; } - public String getAddress() - { + public String getAddress() { return address; } - public int getAge() - { + public int getAge() { return age; } - public BigInteger getSalary() - { + public BigInteger getSalary() { return salary; } @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; } - TestModel testModel = (TestModel)o; + TestModel testModel = (TestModel) o; - if ( age != testModel.age ) - { + if (age != testModel.age) { return false; } - if ( !firstName.equals(testModel.firstName) ) - { + if (!firstName.equals(testModel.firstName)) { return false; } - if ( !lastName.equals(testModel.lastName) ) - { + if (!lastName.equals(testModel.lastName)) { return false; } //noinspection SimplifiableIfStatement - if ( !address.equals(testModel.address) ) - { + if (!address.equals(testModel.address)) { return false; } return salary.equals(testModel.salary); } @Override - public int hashCode() - { + public int hashCode() { int result = firstName.hashCode(); result = 31 * result + lastName.hashCode(); result = 31 * result + address.hashCode(); diff --git a/curator-x-async/src/test/java/org/apache/curator/x/async/modeled/models/TestNewerModel.java b/curator-x-async/src/test/java/org/apache/curator/x/async/modeled/models/TestNewerModel.java index 47c8e4c03..5765c94b9 100644 --- a/curator-x-async/src/test/java/org/apache/curator/x/async/modeled/models/TestNewerModel.java +++ b/curator-x-async/src/test/java/org/apache/curator/x/async/modeled/models/TestNewerModel.java @@ -22,8 +22,7 @@ import java.math.BigInteger; import java.util.Objects; -public class TestNewerModel -{ +public class TestNewerModel { private final String firstName; private final String lastName; private final String address; @@ -31,13 +30,12 @@ public class TestNewerModel private final BigInteger salary; private final long newField; - public TestNewerModel() - { + public TestNewerModel() { this("", "", "", 0, BigInteger.ZERO, 0); } - public TestNewerModel(String firstName, String lastName, String address, int age, BigInteger salary, long newField) - { + public TestNewerModel( + String firstName, String lastName, String address, int age, BigInteger salary, long newField) { this.firstName = Objects.requireNonNull(firstName, "firstName cannot be null"); this.lastName = Objects.requireNonNull(lastName, "lastName cannot be null"); this.address = Objects.requireNonNull(address, "address cannot be null"); @@ -46,93 +44,76 @@ public TestNewerModel(String firstName, String lastName, String address, int age this.newField = newField; } - public String getFirstName() - { + public String getFirstName() { return firstName; } - public String getLastName() - { + public String getLastName() { return lastName; } - public String getAddress() - { + public String getAddress() { return address; } - public int getAge() - { + public int getAge() { return age; } - public BigInteger getSalary() - { + public BigInteger getSalary() { return salary; } - public long getNewField() - { + public long getNewField() { return newField; } - public boolean equalsOld(TestModel model) - { + public boolean equalsOld(TestModel model) { return firstName.equals(model.getFirstName()) - && lastName.equals(model.getLastName()) - && address.equals(model.getAddress()) - && salary.equals(model.getSalary()) - && age == model.getAge() - ; + && lastName.equals(model.getLastName()) + && address.equals(model.getAddress()) + && salary.equals(model.getSalary()) + && age == model.getAge(); } @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; } - TestNewerModel that = (TestNewerModel)o; + TestNewerModel that = (TestNewerModel) o; - if ( age != that.age ) - { + if (age != that.age) { return false; } - if ( newField != that.newField ) - { + if (newField != that.newField) { return false; } - if ( !firstName.equals(that.firstName) ) - { + if (!firstName.equals(that.firstName)) { return false; } - if ( !lastName.equals(that.lastName) ) - { + if (!lastName.equals(that.lastName)) { return false; } //noinspection SimplifiableIfStatement - if ( !address.equals(that.address) ) - { + if (!address.equals(that.address)) { return false; } return salary.equals(that.salary); } @Override - public int hashCode() - { + public int hashCode() { int result = firstName.hashCode(); result = 31 * result + lastName.hashCode(); result = 31 * result + address.hashCode(); result = 31 * result + age; result = 31 * result + salary.hashCode(); - result = 31 * result + (int)(newField ^ (newField >>> 32)); + result = 31 * result + (int) (newField ^ (newField >>> 32)); return result; } } diff --git a/curator-x-async/src/test/java/org/apache/curator/x/async/modeled/models/TestSimpleModel.java b/curator-x-async/src/test/java/org/apache/curator/x/async/modeled/models/TestSimpleModel.java index cd95e08d3..a1c02b2a7 100644 --- a/curator-x-async/src/test/java/org/apache/curator/x/async/modeled/models/TestSimpleModel.java +++ b/curator-x-async/src/test/java/org/apache/curator/x/async/modeled/models/TestSimpleModel.java @@ -21,65 +21,54 @@ import java.util.Objects; -public class TestSimpleModel -{ +public class TestSimpleModel { private final String name; private final int age; - public TestSimpleModel() - { + public TestSimpleModel() { this("", 0); } - public TestSimpleModel(String name, int age) - { + public TestSimpleModel(String name, int age) { this.name = Objects.requireNonNull(name, "name cannot be null"); this.age = Objects.requireNonNull(age, "age cannot be null"); } - public String getName() - { + public String getName() { return name; } - 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; } - TestSimpleModel that = (TestSimpleModel)o; + TestSimpleModel that = (TestSimpleModel) o; //noinspection SimplifiableIfStatement - if ( age != that.age ) - { + if (age != that.age) { return false; } return name.equals(that.name); } @Override - public int hashCode() - { + public int hashCode() { int result = name.hashCode(); result = 31 * result + age; return result; } @Override - public String toString() - { + public String toString() { return "TestSimpleModel{" + "name='" + name + '\'' + ", age=" + age + '}'; } } diff --git a/curator-x-discovery-server/src/main/java/org/apache/curator/x/discovery/server/contexts/GenericDiscoveryContext.java b/curator-x-discovery-server/src/main/java/org/apache/curator/x/discovery/server/contexts/GenericDiscoveryContext.java index f63ea6baf..a539c4a93 100644 --- a/curator-x-discovery-server/src/main/java/org/apache/curator/x/discovery/server/contexts/GenericDiscoveryContext.java +++ b/curator-x-discovery-server/src/main/java/org/apache/curator/x/discovery/server/contexts/GenericDiscoveryContext.java @@ -23,30 +23,35 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; import com.google.common.reflect.TypeToken; +import javax.ws.rs.ext.ContextResolver; +import javax.ws.rs.ext.Provider; import org.apache.curator.x.discovery.ProviderStrategy; import org.apache.curator.x.discovery.ServiceDiscovery; import org.apache.curator.x.discovery.server.rest.DiscoveryContext; -import javax.ws.rs.ext.ContextResolver; -import javax.ws.rs.ext.Provider; /** * For convenience, a version of {@link DiscoveryContext} that uses any generic type as the payload */ @Provider -public class GenericDiscoveryContext implements DiscoveryContext, ContextResolver> -{ +public class GenericDiscoveryContext implements DiscoveryContext, ContextResolver> { private final ServiceDiscovery serviceDiscovery; private final ProviderStrategy providerStrategy; private final int instanceRefreshMs; private final TypeToken payloadType; - public GenericDiscoveryContext(ServiceDiscovery serviceDiscovery, ProviderStrategy providerStrategy, int instanceRefreshMs, Class payloadType) - { + public GenericDiscoveryContext( + ServiceDiscovery serviceDiscovery, + ProviderStrategy providerStrategy, + int instanceRefreshMs, + Class payloadType) { this(serviceDiscovery, providerStrategy, instanceRefreshMs, TypeToken.of(payloadType)); } - public GenericDiscoveryContext(ServiceDiscovery serviceDiscovery, ProviderStrategy providerStrategy, int instanceRefreshMs, TypeToken payloadType) - { + public GenericDiscoveryContext( + ServiceDiscovery serviceDiscovery, + ProviderStrategy providerStrategy, + int instanceRefreshMs, + TypeToken payloadType) { this.serviceDiscovery = serviceDiscovery; this.providerStrategy = providerStrategy; this.instanceRefreshMs = instanceRefreshMs; @@ -54,48 +59,41 @@ public GenericDiscoveryContext(ServiceDiscovery serviceDiscovery, ProviderStr } @Override - public ProviderStrategy getProviderStrategy() - { + public ProviderStrategy getProviderStrategy() { return providerStrategy; } @Override - public int getInstanceRefreshMs() - { + public int getInstanceRefreshMs() { return instanceRefreshMs; } @Override - public ServiceDiscovery getServiceDiscovery() - { + public ServiceDiscovery getServiceDiscovery() { return serviceDiscovery; } - @Override - public void marshallJson(ObjectNode node, String fieldName, T payload) throws Exception - { - if ( payload == null ) - { + @Override + public void marshallJson(ObjectNode node, String fieldName, T payload) throws Exception { + if (payload == null) { //noinspection unchecked - payload = (T)payloadType.getRawType().getDeclaredConstructor().newInstance(); + payload = (T) payloadType.getRawType().getDeclaredConstructor().newInstance(); } node.putPOJO(fieldName, payload); } - @Override - public T unMarshallJson(JsonNode node) throws Exception - { + @Override + public T unMarshallJson(JsonNode node) throws Exception { T payload; ObjectMapper mapper = new ObjectMapper(); //noinspection unchecked - payload = (T)mapper.readValue(node.toString(), payloadType.getRawType()); + payload = (T) mapper.readValue(node.toString(), payloadType.getRawType()); return payload; } @Override - public DiscoveryContext getContext(Class type) - { + public DiscoveryContext getContext(Class type) { return this; } } diff --git a/curator-x-discovery-server/src/main/java/org/apache/curator/x/discovery/server/contexts/IntegerDiscoveryContext.java b/curator-x-discovery-server/src/main/java/org/apache/curator/x/discovery/server/contexts/IntegerDiscoveryContext.java index a9e962baf..483df690a 100644 --- a/curator-x-discovery-server/src/main/java/org/apache/curator/x/discovery/server/contexts/IntegerDiscoveryContext.java +++ b/curator-x-discovery-server/src/main/java/org/apache/curator/x/discovery/server/contexts/IntegerDiscoveryContext.java @@ -21,70 +21,63 @@ import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.ObjectNode; +import javax.ws.rs.ext.ContextResolver; +import javax.ws.rs.ext.Provider; import org.apache.curator.x.discovery.ProviderStrategy; import org.apache.curator.x.discovery.ServiceDiscovery; import org.apache.curator.x.discovery.server.rest.DiscoveryContext; -import javax.ws.rs.ext.ContextResolver; -import javax.ws.rs.ext.Provider; /** * For convenience, a version of {@link DiscoveryContext} that uses an int as the * payload */ @Provider -public class IntegerDiscoveryContext implements DiscoveryContext, ContextResolver> -{ +public class IntegerDiscoveryContext implements DiscoveryContext, ContextResolver> { private final ServiceDiscovery serviceDiscovery; private final ProviderStrategy providerStrategy; private final int instanceRefreshMs; - public IntegerDiscoveryContext(ServiceDiscovery serviceDiscovery, ProviderStrategy providerStrategy, int instanceRefreshMs) - { + public IntegerDiscoveryContext( + ServiceDiscovery serviceDiscovery, + ProviderStrategy providerStrategy, + int instanceRefreshMs) { this.serviceDiscovery = serviceDiscovery; this.providerStrategy = providerStrategy; this.instanceRefreshMs = instanceRefreshMs; } @Override - public ProviderStrategy getProviderStrategy() - { + public ProviderStrategy getProviderStrategy() { return providerStrategy; } @Override - public int getInstanceRefreshMs() - { + public int getInstanceRefreshMs() { return instanceRefreshMs; } @Override - public ServiceDiscovery getServiceDiscovery() - { + public ServiceDiscovery getServiceDiscovery() { return serviceDiscovery; } @Override - public void marshallJson(ObjectNode node, String fieldName, Integer payload) throws Exception - { - if ( payload != null ) - { + public void marshallJson(ObjectNode node, String fieldName, Integer payload) throws Exception { + if (payload != null) { node.put(fieldName, payload.toString()); } } @Override - public Integer unMarshallJson(JsonNode node) throws Exception - { - if ( node != null ) - { + public Integer unMarshallJson(JsonNode node) throws Exception { + if (node != null) { return Integer.parseInt(node.asText()); } return null; } @Override - public DiscoveryContext getContext(Class type) - { + public DiscoveryContext getContext(Class type) { return this; } } diff --git a/curator-x-discovery-server/src/main/java/org/apache/curator/x/discovery/server/contexts/MapDiscoveryContext.java b/curator-x-discovery-server/src/main/java/org/apache/curator/x/discovery/server/contexts/MapDiscoveryContext.java index 61725dfd1..7af1ca1df 100644 --- a/curator-x-discovery-server/src/main/java/org/apache/curator/x/discovery/server/contexts/MapDiscoveryContext.java +++ b/curator-x-discovery-server/src/main/java/org/apache/curator/x/discovery/server/contexts/MapDiscoveryContext.java @@ -20,22 +20,24 @@ package org.apache.curator.x.discovery.server.contexts; import com.google.common.reflect.TypeToken; +import java.util.Map; +import javax.ws.rs.ext.ContextResolver; +import javax.ws.rs.ext.Provider; import org.apache.curator.x.discovery.ProviderStrategy; import org.apache.curator.x.discovery.ServiceDiscovery; import org.apache.curator.x.discovery.server.rest.DiscoveryContext; -import javax.ws.rs.ext.ContextResolver; -import javax.ws.rs.ext.Provider; -import java.util.Map; /** * For convenience, a version of {@link DiscoveryContext} that uses a String-to-String map as the * payload */ @Provider -public class MapDiscoveryContext extends GenericDiscoveryContext> implements ContextResolver>> -{ - public MapDiscoveryContext(ServiceDiscovery> serviceDiscovery, ProviderStrategy> providerStrategy, int instanceRefreshMs) - { - super(serviceDiscovery, providerStrategy, instanceRefreshMs, new TypeToken>(){}); +public class MapDiscoveryContext extends GenericDiscoveryContext> + implements ContextResolver>> { + public MapDiscoveryContext( + ServiceDiscovery> serviceDiscovery, + ProviderStrategy> providerStrategy, + int instanceRefreshMs) { + super(serviceDiscovery, providerStrategy, instanceRefreshMs, new TypeToken>() {}); } } diff --git a/curator-x-discovery-server/src/main/java/org/apache/curator/x/discovery/server/contexts/StringDiscoveryContext.java b/curator-x-discovery-server/src/main/java/org/apache/curator/x/discovery/server/contexts/StringDiscoveryContext.java index 674d6ecc4..f032e7f71 100644 --- a/curator-x-discovery-server/src/main/java/org/apache/curator/x/discovery/server/contexts/StringDiscoveryContext.java +++ b/curator-x-discovery-server/src/main/java/org/apache/curator/x/discovery/server/contexts/StringDiscoveryContext.java @@ -21,66 +21,60 @@ import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.ObjectNode; +import javax.ws.rs.ext.ContextResolver; +import javax.ws.rs.ext.Provider; import org.apache.curator.x.discovery.ProviderStrategy; import org.apache.curator.x.discovery.ServiceDiscovery; import org.apache.curator.x.discovery.server.rest.DiscoveryContext; -import javax.ws.rs.ext.ContextResolver; -import javax.ws.rs.ext.Provider; /** * For convenience, a version of {@link DiscoveryContext} that uses a string as the * payload */ @Provider -public class StringDiscoveryContext implements DiscoveryContext, ContextResolver> -{ +public class StringDiscoveryContext implements DiscoveryContext, ContextResolver> { private final ServiceDiscovery serviceDiscovery; private final ProviderStrategy providerStrategy; private final int instanceRefreshMs; - public StringDiscoveryContext(ServiceDiscovery serviceDiscovery, ProviderStrategy providerStrategy, int instanceRefreshMs) - { + public StringDiscoveryContext( + ServiceDiscovery serviceDiscovery, + ProviderStrategy providerStrategy, + int instanceRefreshMs) { this.serviceDiscovery = serviceDiscovery; this.providerStrategy = providerStrategy; this.instanceRefreshMs = instanceRefreshMs; } @Override - public ProviderStrategy getProviderStrategy() - { + public ProviderStrategy getProviderStrategy() { return providerStrategy; } @Override - public int getInstanceRefreshMs() - { + public int getInstanceRefreshMs() { return instanceRefreshMs; } @Override - public ServiceDiscovery getServiceDiscovery() - { + public ServiceDiscovery getServiceDiscovery() { return serviceDiscovery; } @Override - public void marshallJson(ObjectNode node, String fieldName, String payload) throws Exception - { - if ( payload != null ) - { + public void marshallJson(ObjectNode node, String fieldName, String payload) throws Exception { + if (payload != null) { node.put(fieldName, payload); } } @Override - public String unMarshallJson(JsonNode node) throws Exception - { + public String unMarshallJson(JsonNode node) throws Exception { return (node != null) ? node.asText() : null; } @Override - public DiscoveryContext getContext(Class type) - { + public DiscoveryContext getContext(Class type) { return this; } } diff --git a/curator-x-discovery-server/src/main/java/org/apache/curator/x/discovery/server/entity/JsonServiceInstanceMarshaller.java b/curator-x-discovery-server/src/main/java/org/apache/curator/x/discovery/server/entity/JsonServiceInstanceMarshaller.java index c8c832483..6e1f54c01 100644 --- a/curator-x-discovery-server/src/main/java/org/apache/curator/x/discovery/server/entity/JsonServiceInstanceMarshaller.java +++ b/curator-x-discovery-server/src/main/java/org/apache/curator/x/discovery/server/entity/JsonServiceInstanceMarshaller.java @@ -22,11 +22,11 @@ import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; -import org.apache.curator.utils.ThreadUtils; -import org.apache.curator.x.discovery.ServiceInstance; -import org.apache.curator.x.discovery.ServiceInstanceBuilder; -import org.apache.curator.x.discovery.ServiceType; -import org.apache.curator.x.discovery.server.rest.DiscoveryContext; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.lang.annotation.Annotation; +import java.lang.reflect.Type; import javax.ws.rs.Consumes; import javax.ws.rs.Produces; import javax.ws.rs.WebApplicationException; @@ -35,11 +35,11 @@ import javax.ws.rs.ext.MessageBodyReader; import javax.ws.rs.ext.MessageBodyWriter; import javax.ws.rs.ext.Provider; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.lang.annotation.Annotation; -import java.lang.reflect.Type; +import org.apache.curator.utils.ThreadUtils; +import org.apache.curator.x.discovery.ServiceInstance; +import org.apache.curator.x.discovery.ServiceInstanceBuilder; +import org.apache.curator.x.discovery.ServiceType; +import org.apache.curator.x.discovery.server.rest.DiscoveryContext; /** * Message body reader/writer. Inject this as appropriate for the JAX-RS implementation you are using @@ -47,19 +47,17 @@ @Provider @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) -public class JsonServiceInstanceMarshaller implements MessageBodyReader>, MessageBodyWriter> -{ - private final static ObjectMapper mapper = new ObjectMapper(); +public class JsonServiceInstanceMarshaller + implements MessageBodyReader>, MessageBodyWriter> { + private static final ObjectMapper mapper = new ObjectMapper(); private final DiscoveryContext context; - public JsonServiceInstanceMarshaller(DiscoveryContext context) - { + public JsonServiceInstanceMarshaller(DiscoveryContext context) { this.context = context; } - static ServiceInstance readInstance(JsonNode node, DiscoveryContext context) throws Exception - { + static ServiceInstance readInstance(JsonNode node, DiscoveryContext context) throws Exception { ServiceInstanceBuilder builder = ServiceInstance.builder(); builder.name(node.get("name").asText()); @@ -71,21 +69,18 @@ static ServiceInstance readInstance(JsonNode node, DiscoveryContext con Integer port = getInteger(node, "port"); Integer sslPort = getInteger(node, "sslPort"); - if ( port != null ) - { + if (port != null) { builder.port(port); } - if ( sslPort != null ) - { + if (sslPort != null) { builder.sslPort(sslPort); } return builder.build(); } - static ObjectNode writeInstance(ObjectMapper mapper, ServiceInstance instance, DiscoveryContext context) - { - ObjectNode node = mapper.createObjectNode(); + static ObjectNode writeInstance(ObjectMapper mapper, ServiceInstance instance, DiscoveryContext context) { + ObjectNode node = mapper.createObjectNode(); node.put("name", instance.getName()); node.put("id", instance.getId()); node.put("address", instance.getAddress()); @@ -93,12 +88,9 @@ static ObjectNode writeInstance(ObjectMapper mapper, ServiceInstance insta putInteger(node, "sslPort", instance.getSslPort()); node.put("registrationTimeUTC", instance.getRegistrationTimeUTC()); node.put("serviceType", instance.getServiceType().name()); - try - { + try { context.marshallJson(node, "payload", instance.getPayload()); - } - catch ( Exception e ) - { + } catch (Exception e) { ThreadUtils.checkInterrupted(e); throw new WebApplicationException(e); } @@ -106,57 +98,66 @@ static ObjectNode writeInstance(ObjectMapper mapper, ServiceInstance insta return node; } - private static Integer getInteger(JsonNode node, String fieldName) - { + private static Integer getInteger(JsonNode node, String fieldName) { JsonNode intNode = node.get(fieldName); return (intNode != null) ? intNode.asInt() : null; } - private static void putInteger(ObjectNode node, String fieldName, Integer value) - { - if ( value != null ) - { + private static void putInteger(ObjectNode node, String fieldName, Integer value) { + if (value != null) { node.put(fieldName, value); } } @Override - public boolean isReadable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) - { + public boolean isReadable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { return isWriteable(type, genericType, annotations, mediaType); } @Override - public boolean isWriteable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) - { + public boolean isWriteable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { return ServiceInstance.class.isAssignableFrom(type) && mediaType.equals(MediaType.APPLICATION_JSON_TYPE); } @Override - public long getSize(ServiceInstance serviceInstance, Class type, Type genericType, Annotation[] annotations, MediaType mediaType) - { + public long getSize( + ServiceInstance serviceInstance, + Class type, + Type genericType, + Annotation[] annotations, + MediaType mediaType) { return -1; } @Override - public ServiceInstance readFrom(Class> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, InputStream entityStream) throws IOException, WebApplicationException - { - try - { - JsonNode node = mapper.readTree(entityStream); + public ServiceInstance readFrom( + Class> type, + Type genericType, + Annotation[] annotations, + MediaType mediaType, + MultivaluedMap httpHeaders, + InputStream entityStream) + throws IOException, WebApplicationException { + try { + JsonNode node = mapper.readTree(entityStream); return readInstance(node, context); - } - catch ( Exception e ) - { + } catch (Exception e) { ThreadUtils.checkInterrupted(e); throw new WebApplicationException(e); } } @Override - public void writeTo(ServiceInstance serviceInstance, Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException - { - ObjectNode node = writeInstance(mapper, serviceInstance, context); + public void writeTo( + ServiceInstance serviceInstance, + Class type, + Type genericType, + Annotation[] annotations, + MediaType mediaType, + MultivaluedMap httpHeaders, + OutputStream entityStream) + throws IOException, WebApplicationException { + ObjectNode node = writeInstance(mapper, serviceInstance, context); mapper.writeValue(entityStream, node); } } diff --git a/curator-x-discovery-server/src/main/java/org/apache/curator/x/discovery/server/entity/JsonServiceInstancesMarshaller.java b/curator-x-discovery-server/src/main/java/org/apache/curator/x/discovery/server/entity/JsonServiceInstancesMarshaller.java index 8e790ba59..ebe7a0a85 100644 --- a/curator-x-discovery-server/src/main/java/org/apache/curator/x/discovery/server/entity/JsonServiceInstancesMarshaller.java +++ b/curator-x-discovery-server/src/main/java/org/apache/curator/x/discovery/server/entity/JsonServiceInstancesMarshaller.java @@ -24,9 +24,12 @@ import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; import com.google.common.collect.Lists; -import org.apache.curator.utils.ThreadUtils; -import org.apache.curator.x.discovery.ServiceInstance; -import org.apache.curator.x.discovery.server.rest.DiscoveryContext; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.lang.annotation.Annotation; +import java.lang.reflect.Type; +import java.util.List; import javax.ws.rs.Consumes; import javax.ws.rs.Produces; import javax.ws.rs.WebApplicationException; @@ -35,12 +38,9 @@ import javax.ws.rs.ext.MessageBodyReader; import javax.ws.rs.ext.MessageBodyWriter; import javax.ws.rs.ext.Provider; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.lang.annotation.Annotation; -import java.lang.reflect.Type; -import java.util.List; +import org.apache.curator.utils.ThreadUtils; +import org.apache.curator.x.discovery.ServiceInstance; +import org.apache.curator.x.discovery.server.rest.DiscoveryContext; /** * Message body reader/writer. Inject this as appropriate for the JAX-RS implementation you are using @@ -48,64 +48,73 @@ @Provider @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) -public class JsonServiceInstancesMarshaller implements MessageBodyReader>, MessageBodyWriter> -{ +public class JsonServiceInstancesMarshaller + implements MessageBodyReader>, MessageBodyWriter> { private final DiscoveryContext context; - public JsonServiceInstancesMarshaller(DiscoveryContext context) - { + public JsonServiceInstancesMarshaller(DiscoveryContext context) { this.context = context; } @Override - public boolean isReadable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) - { + public boolean isReadable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { return isWriteable(type, genericType, annotations, mediaType); } @Override - public boolean isWriteable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) - { + public boolean isWriteable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { return ServiceInstances.class.isAssignableFrom(type) && mediaType.equals(MediaType.APPLICATION_JSON_TYPE); } @Override - public long getSize(ServiceInstances serviceInstances, Class type, Type genericType, Annotation[] annotations, MediaType mediaType) - { + public long getSize( + ServiceInstances serviceInstances, + Class type, + Type genericType, + Annotation[] annotations, + MediaType mediaType) { return -1; } @Override - public ServiceInstances readFrom(Class> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, InputStream entityStream) throws IOException, WebApplicationException - { - try - { - List> instances = Lists.newArrayList(); - ObjectMapper mapper = new ObjectMapper(); - JsonNode tree = mapper.reader().readTree(entityStream); - for ( int i = 0; i < tree.size(); ++i ) - { - JsonNode node = tree.get(i); + public ServiceInstances readFrom( + Class> type, + Type genericType, + Annotation[] annotations, + MediaType mediaType, + MultivaluedMap httpHeaders, + InputStream entityStream) + throws IOException, WebApplicationException { + try { + List> instances = Lists.newArrayList(); + ObjectMapper mapper = new ObjectMapper(); + JsonNode tree = mapper.reader().readTree(entityStream); + for (int i = 0; i < tree.size(); ++i) { + JsonNode node = tree.get(i); ServiceInstance instance = JsonServiceInstanceMarshaller.readInstance(node, context); instances.add(instance); } return new ServiceInstances(instances); - } - catch ( Exception e ) - { + } catch (Exception e) { ThreadUtils.checkInterrupted(e); throw new WebApplicationException(e); } } @Override - public void writeTo(ServiceInstances serviceInstances, Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException - { + public void writeTo( + ServiceInstances serviceInstances, + Class type, + Type genericType, + Annotation[] annotations, + MediaType mediaType, + MultivaluedMap httpHeaders, + OutputStream entityStream) + throws IOException, WebApplicationException { ObjectMapper mapper = new ObjectMapper(); ArrayNode arrayNode = mapper.createArrayNode(); List> instanceList = serviceInstances.getServices(); - for ( ServiceInstance instance : instanceList ) - { + for (ServiceInstance instance : instanceList) { ObjectNode node = JsonServiceInstanceMarshaller.writeInstance(mapper, instance, context); arrayNode.add(node); } diff --git a/curator-x-discovery-server/src/main/java/org/apache/curator/x/discovery/server/entity/JsonServiceNamesMarshaller.java b/curator-x-discovery-server/src/main/java/org/apache/curator/x/discovery/server/entity/JsonServiceNamesMarshaller.java index 05007d561..a112659c1 100644 --- a/curator-x-discovery-server/src/main/java/org/apache/curator/x/discovery/server/entity/JsonServiceNamesMarshaller.java +++ b/curator-x-discovery-server/src/main/java/org/apache/curator/x/discovery/server/entity/JsonServiceNamesMarshaller.java @@ -45,22 +45,25 @@ @Provider @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) -public class JsonServiceNamesMarshaller implements MessageBodyReader, MessageBodyWriter -{ +public class JsonServiceNamesMarshaller implements MessageBodyReader, MessageBodyWriter { @Override - public boolean isReadable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) - { + public boolean isReadable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { return allow(type, mediaType); } @Override - public ServiceNames readFrom(Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, InputStream entityStream) throws IOException, WebApplicationException - { - List names = Lists.newArrayList(); - ObjectMapper mapper = new ObjectMapper(); + public ServiceNames readFrom( + Class type, + Type genericType, + Annotation[] annotations, + MediaType mediaType, + MultivaluedMap httpHeaders, + InputStream entityStream) + throws IOException, WebApplicationException { + List names = Lists.newArrayList(); + ObjectMapper mapper = new ObjectMapper(); JsonNode tree = mapper.reader().readTree(entityStream); - for ( int i = 0; i < tree.size(); ++i ) - { + for (int i = 0; i < tree.size(); ++i) { JsonNode node = tree.get(i); names.add(node.get("name").asText()); } @@ -68,25 +71,30 @@ public ServiceNames readFrom(Class type, Type genericType, Annotat } @Override - public boolean isWriteable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) - { + public boolean isWriteable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { return allow(type, mediaType); } @Override - public long getSize(ServiceNames serviceNames, Class type, Type genericType, Annotation[] annotations, MediaType mediaType) - { + public long getSize( + ServiceNames serviceNames, Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { return -1; } @Override - public void writeTo(ServiceNames serviceNames, Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException - { - ObjectMapper mapper = new ObjectMapper(); - ArrayNode arrayNode = mapper.createArrayNode(); - for ( String name : serviceNames.getNames() ) - { - ObjectNode node = mapper.createObjectNode(); + public void writeTo( + ServiceNames serviceNames, + Class type, + Type genericType, + Annotation[] annotations, + MediaType mediaType, + MultivaluedMap httpHeaders, + OutputStream entityStream) + throws IOException, WebApplicationException { + ObjectMapper mapper = new ObjectMapper(); + ArrayNode arrayNode = mapper.createArrayNode(); + for (String name : serviceNames.getNames()) { + ObjectNode node = mapper.createObjectNode(); node.put("name", name); arrayNode.add(node); } @@ -94,8 +102,7 @@ public void writeTo(ServiceNames serviceNames, Class type, Type genericType, mapper.writer().writeValue(entityStream, arrayNode); } - private static boolean allow(Class type, MediaType mediaType) - { + private static boolean allow(Class type, MediaType mediaType) { return ServiceNames.class.isAssignableFrom(type) && mediaType.equals(MediaType.APPLICATION_JSON_TYPE); } } diff --git a/curator-x-discovery-server/src/main/java/org/apache/curator/x/discovery/server/entity/ServiceInstances.java b/curator-x-discovery-server/src/main/java/org/apache/curator/x/discovery/server/entity/ServiceInstances.java index 56383bb4b..bcd6c9ff5 100644 --- a/curator-x-discovery-server/src/main/java/org/apache/curator/x/discovery/server/entity/ServiceInstances.java +++ b/curator-x-discovery-server/src/main/java/org/apache/curator/x/discovery/server/entity/ServiceInstances.java @@ -21,29 +21,25 @@ import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; -import org.apache.curator.x.discovery.ServiceInstance; import java.util.Collection; import java.util.List; +import org.apache.curator.x.discovery.ServiceInstance; /** * Raw generic lists don't work well in JAX-RS. Thus, this wrapper is needed. */ -public class ServiceInstances -{ +public class ServiceInstances { private final List> services; - public ServiceInstances() - { + public ServiceInstances() { services = Lists.newArrayList(); } - public ServiceInstances(Collection> c) - { + public ServiceInstances(Collection> c) { services = Lists.newArrayList(c); } - public List> getServices() - { + public List> getServices() { return ImmutableList.copyOf(services); } } diff --git a/curator-x-discovery-server/src/main/java/org/apache/curator/x/discovery/server/entity/ServiceNames.java b/curator-x-discovery-server/src/main/java/org/apache/curator/x/discovery/server/entity/ServiceNames.java index d54012013..058043a6f 100644 --- a/curator-x-discovery-server/src/main/java/org/apache/curator/x/discovery/server/entity/ServiceNames.java +++ b/curator-x-discovery-server/src/main/java/org/apache/curator/x/discovery/server/entity/ServiceNames.java @@ -27,22 +27,18 @@ /** * Raw generic lists don't work well in JAX-RS. Thus, this wrapper is needed. */ -public class ServiceNames -{ +public class ServiceNames { private final List names; - public ServiceNames() - { + public ServiceNames() { names = Lists.newArrayList(); } - public ServiceNames(Collection c) - { + public ServiceNames(Collection c) { names = Lists.newArrayList(c); } - public List getNames() - { + public List getNames() { return ImmutableList.copyOf(names); } } diff --git a/curator-x-discovery-server/src/main/java/org/apache/curator/x/discovery/server/rest/DiscoveryContext.java b/curator-x-discovery-server/src/main/java/org/apache/curator/x/discovery/server/rest/DiscoveryContext.java index 48041766f..a14038e57 100644 --- a/curator-x-discovery-server/src/main/java/org/apache/curator/x/discovery/server/rest/DiscoveryContext.java +++ b/curator-x-discovery-server/src/main/java/org/apache/curator/x/discovery/server/rest/DiscoveryContext.java @@ -27,21 +27,20 @@ /** * Bridge between the specifics of your needs and the generic implementation */ -public interface DiscoveryContext -{ +public interface DiscoveryContext { /** * Return the threshold in milliseconds to consider a registration stale * * @return number of milliseconds */ - public int getInstanceRefreshMs(); + public int getInstanceRefreshMs(); /** * Return the service singleton * * @return service */ - public ServiceDiscovery getServiceDiscovery(); + public ServiceDiscovery getServiceDiscovery(); /** * Serialize your payload @@ -51,7 +50,7 @@ public interface DiscoveryContext * @param payload the payload value (can be null) * @throws Exception any errors */ - public void marshallJson(ObjectNode node, String fieldName, T payload) throws Exception; + public void marshallJson(ObjectNode node, String fieldName, T payload) throws Exception; /** * Deserialize your payload @@ -60,12 +59,12 @@ public interface DiscoveryContext * @return the payload or null * @throws Exception any errors */ - public T unMarshallJson(JsonNode node) throws Exception; + public T unMarshallJson(JsonNode node) throws Exception; /** * Return the provider strategy to use for {@link DiscoveryResource#getAny(String)} * * @return strategy */ - public ProviderStrategy getProviderStrategy(); + public ProviderStrategy getProviderStrategy(); } diff --git a/curator-x-discovery-server/src/main/java/org/apache/curator/x/discovery/server/rest/DiscoveryResource.java b/curator-x-discovery-server/src/main/java/org/apache/curator/x/discovery/server/rest/DiscoveryResource.java index 7f3f90615..73f804d1c 100644 --- a/curator-x-discovery-server/src/main/java/org/apache/curator/x/discovery/server/rest/DiscoveryResource.java +++ b/curator-x-discovery-server/src/main/java/org/apache/curator/x/discovery/server/rest/DiscoveryResource.java @@ -20,14 +20,9 @@ package org.apache.curator.x.discovery.server.rest; import com.google.common.collect.Lists; -import org.apache.curator.utils.ThreadUtils; -import org.apache.curator.x.discovery.ServiceInstance; -import org.apache.curator.x.discovery.ServiceType; -import org.apache.curator.x.discovery.details.InstanceProvider; -import org.apache.curator.x.discovery.server.entity.ServiceInstances; -import org.apache.curator.x.discovery.server.entity.ServiceNames; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import java.util.Collection; +import java.util.Collections; +import java.util.List; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; @@ -37,9 +32,13 @@ import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; -import java.util.Collection; -import java.util.Collections; -import java.util.List; +import org.apache.curator.utils.ThreadUtils; +import org.apache.curator.x.discovery.ServiceInstance; +import org.apache.curator.x.discovery.details.InstanceProvider; +import org.apache.curator.x.discovery.server.entity.ServiceInstances; +import org.apache.curator.x.discovery.server.entity.ServiceNames; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** *

    @@ -68,14 +67,12 @@ * } * */ -public abstract class DiscoveryResource -{ - private static final Logger log = LoggerFactory.getLogger(DiscoveryResource.class); +public abstract class DiscoveryResource { + private static final Logger log = LoggerFactory.getLogger(DiscoveryResource.class); private final DiscoveryContext context; - public DiscoveryResource(DiscoveryContext context) - { + public DiscoveryResource(DiscoveryContext context) { this.context = context; } @@ -83,26 +80,21 @@ public DiscoveryResource(DiscoveryContext context) @Path("v1/service/{name}/{id}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - public Response putService(ServiceInstance instance, @PathParam("name") String name, @PathParam("id") String id) - { - if ( !instance.getId().equals(id) || !instance.getName().equals(name) ) - { + public Response putService( + ServiceInstance instance, @PathParam("name") String name, @PathParam("id") String id) { + if (!instance.getId().equals(id) || !instance.getName().equals(name)) { log.info("Request where path id and/or name doesn't match entity"); return Response.status(Response.Status.BAD_REQUEST).build(); } - - if ( instance.getServiceType().isDynamic() ) - { + + if (instance.getServiceType().isDynamic()) { log.info("Service type cannot be dynamic"); return Response.status(Response.Status.BAD_REQUEST).build(); } - try - { + try { context.getServiceDiscovery().registerService(instance); - } - catch ( Exception e ) - { + } catch (Exception e) { ThreadUtils.checkInterrupted(e); log.error("Trying to register service", e); return Response.serverError().build(); @@ -113,19 +105,14 @@ public Response putService(ServiceInstance instance, @PathParam("name") S @DELETE @Path("v1/service/{name}/{id}") - public Response removeService(@PathParam("name") String name, @PathParam("id") String id) - { - try - { + public Response removeService(@PathParam("name") String name, @PathParam("id") String id) { + try { ServiceInstance instance = context.getServiceDiscovery().queryForInstance(name, id); - if ( instance != null ) - { + if (instance != null) { //noinspection unchecked context.getServiceDiscovery().unregisterService(instance); } - } - catch ( Exception e ) - { + } catch (Exception e) { ThreadUtils.checkInterrupted(e); log.error("Trying to delete service", e); return Response.serverError().build(); @@ -137,32 +124,27 @@ public Response removeService(@PathParam("name") String name, @PathParam("id @GET @Path("{name}/{id}") @Produces(MediaType.APPLICATION_JSON) - public Response getDeprecated(@PathParam("name") String name, @PathParam("id") String id) - { + public Response getDeprecated(@PathParam("name") String name, @PathParam("id") String id) { return internalGet(name, id, true); } - + @GET @Path("v1/service/{name}/{id}") @Produces(MediaType.APPLICATION_JSON) - public Response get(@PathParam("name") String name, @PathParam("id") String id) - { + public Response get(@PathParam("name") String name, @PathParam("id") String id) { return internalGet(name, id, false); } @GET @Path("v1/service") @Produces(MediaType.APPLICATION_JSON) - public Response getAllNames() - { - try - { - List instances = Lists.newArrayList(context.getServiceDiscovery().queryForNames()); + public Response getAllNames() { + try { + List instances = + Lists.newArrayList(context.getServiceDiscovery().queryForNames()); Collections.sort(instances); return Response.ok(new ServiceNames(instances)).build(); - } - catch ( Exception e ) - { + } catch (Exception e) { log.error("Trying to get service names", e); return Response.serverError().build(); } @@ -171,15 +153,12 @@ public Response getAllNames() @GET @Path("v1/service/{name}") @Produces(MediaType.APPLICATION_JSON) - public Response getAll(@PathParam("name") String name) - { - try - { - Collection> instances = context.getServiceDiscovery().queryForInstances(name); + public Response getAll(@PathParam("name") String name) { + try { + Collection> instances = + context.getServiceDiscovery().queryForInstances(name); return Response.ok(new ServiceInstances(instances)).build(); - } - catch ( Exception e ) - { + } catch (Exception e) { ThreadUtils.checkInterrupted(e); log.error(String.format("Trying to get instances from service (%s)", name), e); return Response.serverError().build(); @@ -189,54 +168,41 @@ public Response getAll(@PathParam("name") String name) @GET @Path("v1/anyservice/{name}") @Produces(MediaType.APPLICATION_JSON) - public Response getAny(@PathParam("name") String name) - { - try - { - final List> instances = Lists.newArrayList(context.getServiceDiscovery().queryForInstances(name)); - ServiceInstance randomInstance = context.getProviderStrategy().getInstance - ( - new InstanceProvider() - { - @Override - public List> getInstances() throws Exception - { - return instances; - } - } - ); - if ( randomInstance == null ) - { + public Response getAny(@PathParam("name") String name) { + try { + final List> instances = + Lists.newArrayList(context.getServiceDiscovery().queryForInstances(name)); + ServiceInstance randomInstance = context.getProviderStrategy().getInstance(new InstanceProvider() { + @Override + public List> getInstances() throws Exception { + return instances; + } + }); + if (randomInstance == null) { return Response.status(Response.Status.NOT_FOUND).build(); } return Response.ok(randomInstance).build(); - } - catch ( Exception e ) - { + } catch (Exception e) { ThreadUtils.checkInterrupted(e); log.error(String.format("Trying to get any instance from service (%s)", name), e); return Response.serverError().build(); } } - private Response internalGet(String name, String id, boolean addDeprecationHeader) - { - try - { + private Response internalGet(String name, String id, boolean addDeprecationHeader) { + try { ServiceInstance instance = context.getServiceDiscovery().queryForInstance(name, id); - if ( instance == null ) - { + if (instance == null) { return Response.status(Response.Status.NOT_FOUND).build(); } Response.ResponseBuilder builder = Response.ok(instance); - if ( addDeprecationHeader ) - { - builder = builder.header("Warning", "This API has been deprecated. Please see the updated spec for the replacement API."); + if (addDeprecationHeader) { + builder = builder.header( + "Warning", + "This API has been deprecated. Please see the updated spec for the replacement API."); } return builder.build(); - } - catch ( Exception e ) - { + } catch (Exception e) { ThreadUtils.checkInterrupted(e); log.error(String.format("Trying to get instance (%s) from service (%s)", id, name), e); return Response.serverError().build(); diff --git a/curator-x-discovery-server/src/main/java/org/apache/curator/x/discovery/server/rest/InstanceCleanup.java b/curator-x-discovery-server/src/main/java/org/apache/curator/x/discovery/server/rest/InstanceCleanup.java index 922685375..2923a9e63 100644 --- a/curator-x-discovery-server/src/main/java/org/apache/curator/x/discovery/server/rest/InstanceCleanup.java +++ b/curator-x-discovery-server/src/main/java/org/apache/curator/x/discovery/server/rest/InstanceCleanup.java @@ -20,106 +20,87 @@ package org.apache.curator.x.discovery.server.rest; import com.google.common.base.Preconditions; +import java.io.Closeable; +import java.io.IOException; +import java.util.Collection; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; import org.apache.curator.utils.ThreadUtils; import org.apache.curator.x.discovery.ServiceDiscovery; import org.apache.curator.x.discovery.ServiceInstance; import org.apache.curator.x.discovery.ServiceType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.io.Closeable; -import java.io.IOException; -import java.util.Collection; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.TimeUnit; /** * A background task that purges stale registrations. You should allocate a singleton * of this class, call {@link #start()} and then call {@link #close()} when your application * is shutting down. */ -public class InstanceCleanup implements Closeable -{ - private static final Logger log = LoggerFactory.getLogger(InstanceCleanup.class); +public class InstanceCleanup implements Closeable { + private static final Logger log = LoggerFactory.getLogger(InstanceCleanup.class); - private final ServiceDiscovery discovery; - private final int instanceRefreshMs; - private final ScheduledExecutorService service = ThreadUtils.newSingleThreadScheduledExecutor("InstanceCleanup"); + private final ServiceDiscovery discovery; + private final int instanceRefreshMs; + private final ScheduledExecutorService service = ThreadUtils.newSingleThreadScheduledExecutor("InstanceCleanup"); /** * @param discovery the service being monitored * @param instanceRefreshMs time in milliseconds to consider a registration stale */ - public InstanceCleanup(ServiceDiscovery discovery, int instanceRefreshMs) - { + public InstanceCleanup(ServiceDiscovery discovery, int instanceRefreshMs) { //noinspection unchecked - this.discovery = (ServiceDiscovery)discovery; // this cast is safe - this class never accesses the payload + this.discovery = + (ServiceDiscovery) discovery; // this cast is safe - this class never accesses the payload this.instanceRefreshMs = instanceRefreshMs; } /** * Start the task */ - public void start() - { + public void start() { Preconditions.checkArgument(!service.isShutdown(), "already started"); - service.scheduleWithFixedDelay - ( - new Runnable() - { - @Override - public void run() - { - doWork(); - } - }, - instanceRefreshMs, - instanceRefreshMs, - TimeUnit.MILLISECONDS - ); + service.scheduleWithFixedDelay( + new Runnable() { + @Override + public void run() { + doWork(); + } + }, + instanceRefreshMs, + instanceRefreshMs, + TimeUnit.MILLISECONDS); } @Override - public void close() throws IOException - { + public void close() throws IOException { Preconditions.checkArgument(!service.isShutdown(), "not started"); service.shutdownNow(); } - private void doWork() - { - try - { - for ( String name : discovery.queryForNames() ) - { + private void doWork() { + try { + for (String name : discovery.queryForNames()) { checkService(name); } - } - catch ( Exception e ) - { + } catch (Exception e) { ThreadUtils.checkInterrupted(e); log.error("GC for service names", e); } } - private void checkService(String name) - { - try - { - Collection> instances = discovery.queryForInstances(name); - for ( ServiceInstance instance : instances ) - { - if ( instance.getServiceType() == ServiceType.STATIC ) - { - if ( (System.currentTimeMillis() - instance.getRegistrationTimeUTC()) > instanceRefreshMs ) - { + private void checkService(String name) { + try { + Collection> instances = discovery.queryForInstances(name); + for (ServiceInstance instance : instances) { + if (instance.getServiceType() == ServiceType.STATIC) { + if ((System.currentTimeMillis() - instance.getRegistrationTimeUTC()) > instanceRefreshMs) { discovery.unregisterService(instance); } } } - } - catch ( Exception e ) - { + } catch (Exception e) { ThreadUtils.checkInterrupted(e); log.error(String.format("GC for service: %s", name), e); } diff --git a/curator-x-discovery-server/src/test/java/org/apache/curator/x/discovery/server/jetty_jersey/MapDiscoveryResource.java b/curator-x-discovery-server/src/test/java/org/apache/curator/x/discovery/server/jetty_jersey/MapDiscoveryResource.java index 110cd06b6..8933d71e6 100644 --- a/curator-x-discovery-server/src/test/java/org/apache/curator/x/discovery/server/jetty_jersey/MapDiscoveryResource.java +++ b/curator-x-discovery-server/src/test/java/org/apache/curator/x/discovery/server/jetty_jersey/MapDiscoveryResource.java @@ -19,18 +19,16 @@ package org.apache.curator.x.discovery.server.jetty_jersey; -import org.apache.curator.x.discovery.server.rest.DiscoveryContext; -import org.apache.curator.x.discovery.server.rest.DiscoveryResource; +import java.util.Map; import javax.ws.rs.Path; import javax.ws.rs.core.Context; import javax.ws.rs.ext.ContextResolver; -import java.util.Map; +import org.apache.curator.x.discovery.server.rest.DiscoveryContext; +import org.apache.curator.x.discovery.server.rest.DiscoveryResource; @Path("/") -public class MapDiscoveryResource extends DiscoveryResource> -{ - public MapDiscoveryResource(@Context ContextResolver>> resolver) - { +public class MapDiscoveryResource extends DiscoveryResource> { + public MapDiscoveryResource(@Context ContextResolver>> resolver) { super(resolver.getContext(DiscoveryContext.class)); } } diff --git a/curator-x-discovery-server/src/test/java/org/apache/curator/x/discovery/server/jetty_jersey/ServiceDetails.java b/curator-x-discovery-server/src/test/java/org/apache/curator/x/discovery/server/jetty_jersey/ServiceDetails.java index 464c73cfd..e4a1bb417 100644 --- a/curator-x-discovery-server/src/test/java/org/apache/curator/x/discovery/server/jetty_jersey/ServiceDetails.java +++ b/curator-x-discovery-server/src/test/java/org/apache/curator/x/discovery/server/jetty_jersey/ServiceDetails.java @@ -28,64 +28,56 @@ */ @JsonRootName("details") public class ServiceDetails { - - private Map data; - - private String description; - - public String getDescription() { - return description; - } - public void setDescription(String description) { - this.description = description; - } + private Map data; - public ServiceDetails() { - this(new HashMap()); - } + private String description; - public ServiceDetails(Map data) { - this.data = data; - } + public String getDescription() { + return description; + } - public void setData(Map data) { - this.data = data; - } + public void setDescription(String description) { + this.description = description; + } - public Map getData() { - return data; - } + public ServiceDetails() { + this(new HashMap()); + } - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((data == null) ? 0 : data.hashCode()); - result = prime * result - + ((description == null) ? 0 : description.hashCode()); - return result; - } + public ServiceDetails(Map data) { + this.data = data; + } - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - ServiceDetails other = (ServiceDetails) obj; - if (data == null) { - if (other.data != null) - return false; - } else if (!data.equals(other.data)) - return false; - if (description == null) { - if (other.description != null) - return false; - } else if (!description.equals(other.description)) - return false; - return true; - } + public void setData(Map data) { + this.data = data; + } + + public Map getData() { + return data; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((data == null) ? 0 : data.hashCode()); + result = prime * result + ((description == null) ? 0 : description.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) return true; + if (obj == null) return false; + if (getClass() != obj.getClass()) return false; + ServiceDetails other = (ServiceDetails) obj; + if (data == null) { + if (other.data != null) return false; + } else if (!data.equals(other.data)) return false; + if (description == null) { + if (other.description != null) return false; + } else if (!description.equals(other.description)) return false; + return true; + } } diff --git a/curator-x-discovery-server/src/test/java/org/apache/curator/x/discovery/server/jetty_jersey/ServiceDetailsDiscoveryContext.java b/curator-x-discovery-server/src/test/java/org/apache/curator/x/discovery/server/jetty_jersey/ServiceDetailsDiscoveryContext.java index b2b3ddfa3..fbe19b33d 100644 --- a/curator-x-discovery-server/src/test/java/org/apache/curator/x/discovery/server/jetty_jersey/ServiceDetailsDiscoveryContext.java +++ b/curator-x-discovery-server/src/test/java/org/apache/curator/x/discovery/server/jetty_jersey/ServiceDetailsDiscoveryContext.java @@ -21,7 +21,6 @@ import javax.ws.rs.ext.ContextResolver; import javax.ws.rs.ext.Provider; - import org.apache.curator.x.discovery.ProviderStrategy; import org.apache.curator.x.discovery.ServiceDiscovery; import org.apache.curator.x.discovery.server.contexts.GenericDiscoveryContext; @@ -31,11 +30,12 @@ * A DiscoveryContext that maps a concrete payload object of ServiceDetails */ @Provider -public class ServiceDetailsDiscoveryContext extends GenericDiscoveryContext implements DiscoveryContext, ContextResolver> -{ - public ServiceDetailsDiscoveryContext(ServiceDiscovery serviceDiscovery, ProviderStrategy providerStrategy, int instanceRefreshMs) - { - super(serviceDiscovery, providerStrategy, instanceRefreshMs, ServiceDetails.class); - +public class ServiceDetailsDiscoveryContext extends GenericDiscoveryContext + implements DiscoveryContext, ContextResolver> { + public ServiceDetailsDiscoveryContext( + ServiceDiscovery serviceDiscovery, + ProviderStrategy providerStrategy, + int instanceRefreshMs) { + super(serviceDiscovery, providerStrategy, instanceRefreshMs, ServiceDetails.class); } } diff --git a/curator-x-discovery-server/src/test/java/org/apache/curator/x/discovery/server/jetty_jersey/ServiceDetailsDiscoveryResource.java b/curator-x-discovery-server/src/test/java/org/apache/curator/x/discovery/server/jetty_jersey/ServiceDetailsDiscoveryResource.java index 81c4b8f23..d488a96bb 100644 --- a/curator-x-discovery-server/src/test/java/org/apache/curator/x/discovery/server/jetty_jersey/ServiceDetailsDiscoveryResource.java +++ b/curator-x-discovery-server/src/test/java/org/apache/curator/x/discovery/server/jetty_jersey/ServiceDetailsDiscoveryResource.java @@ -22,15 +22,12 @@ import javax.ws.rs.Path; import javax.ws.rs.core.Context; import javax.ws.rs.ext.ContextResolver; - import org.apache.curator.x.discovery.server.rest.DiscoveryContext; import org.apache.curator.x.discovery.server.rest.DiscoveryResource; @Path("/") -public class ServiceDetailsDiscoveryResource extends DiscoveryResource -{ - public ServiceDetailsDiscoveryResource(@Context ContextResolver> resolver) - { +public class ServiceDetailsDiscoveryResource extends DiscoveryResource { + public ServiceDetailsDiscoveryResource(@Context ContextResolver> resolver) { super(resolver.getContext(DiscoveryContext.class)); } } diff --git a/curator-x-discovery-server/src/test/java/org/apache/curator/x/discovery/server/jetty_jersey/StringDiscoveryResource.java b/curator-x-discovery-server/src/test/java/org/apache/curator/x/discovery/server/jetty_jersey/StringDiscoveryResource.java index 1cdded6ab..4ee658438 100644 --- a/curator-x-discovery-server/src/test/java/org/apache/curator/x/discovery/server/jetty_jersey/StringDiscoveryResource.java +++ b/curator-x-discovery-server/src/test/java/org/apache/curator/x/discovery/server/jetty_jersey/StringDiscoveryResource.java @@ -19,17 +19,15 @@ package org.apache.curator.x.discovery.server.jetty_jersey; -import org.apache.curator.x.discovery.server.rest.DiscoveryContext; -import org.apache.curator.x.discovery.server.rest.DiscoveryResource; import javax.ws.rs.Path; import javax.ws.rs.core.Context; import javax.ws.rs.ext.ContextResolver; +import org.apache.curator.x.discovery.server.rest.DiscoveryContext; +import org.apache.curator.x.discovery.server.rest.DiscoveryResource; @Path("/") -public class StringDiscoveryResource extends DiscoveryResource -{ - public StringDiscoveryResource(@Context ContextResolver> resolver) - { +public class StringDiscoveryResource extends DiscoveryResource { + public StringDiscoveryResource(@Context ContextResolver> resolver) { super(resolver.getContext(DiscoveryContext.class)); } } diff --git a/curator-x-discovery-server/src/test/java/org/apache/curator/x/discovery/server/jetty_jersey/TestMapsWithJersey.java b/curator-x-discovery-server/src/test/java/org/apache/curator/x/discovery/server/jetty_jersey/TestMapsWithJersey.java index fbfcbbd3e..be90a530a 100644 --- a/curator-x-discovery-server/src/test/java/org/apache/curator/x/discovery/server/jetty_jersey/TestMapsWithJersey.java +++ b/curator-x-discovery-server/src/test/java/org/apache/curator/x/discovery/server/jetty_jersey/TestMapsWithJersey.java @@ -30,6 +30,10 @@ import com.sun.jersey.api.client.config.DefaultClientConfig; import com.sun.jersey.api.core.DefaultResourceConfig; import com.sun.jersey.spi.container.servlet.ServletContainer; +import java.util.Map; +import java.util.Set; +import javax.ws.rs.core.Application; +import javax.ws.rs.core.MediaType; import org.apache.curator.test.InstanceSpec; import org.apache.curator.x.discovery.ServiceInstance; import org.apache.curator.x.discovery.ServiceType; @@ -47,13 +51,8 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import javax.ws.rs.core.Application; -import javax.ws.rs.core.MediaType; -import java.util.Map; -import java.util.Set; -public class TestMapsWithJersey -{ +public class TestMapsWithJersey { private static final String HOST = "127.0.0.1"; private Server server; private JsonServiceNamesMarshaller serviceNamesMarshaller; @@ -63,27 +62,24 @@ public class TestMapsWithJersey private int port; @BeforeEach - public void setup() throws Exception - { - context = new MapDiscoveryContext(new MockServiceDiscovery>(), new RandomStrategy>(), 1000); + public void setup() throws Exception { + context = new MapDiscoveryContext( + new MockServiceDiscovery>(), new RandomStrategy>(), 1000); serviceNamesMarshaller = new JsonServiceNamesMarshaller(); serviceInstanceMarshaller = new JsonServiceInstanceMarshaller>(context); serviceInstancesMarshaller = new JsonServiceInstancesMarshaller>(context); - Application application = new DefaultResourceConfig() - { + Application application = new DefaultResourceConfig() { @Override - public Set> getClasses() - { - Set> classes = Sets.newHashSet(); + public Set> getClasses() { + Set> classes = Sets.newHashSet(); classes.add(MapDiscoveryResource.class); return classes; } @Override - public Set getSingletons() - { - Set singletons = Sets.newHashSet(); + public Set getSingletons() { + Set singletons = Sets.newHashSet(); singletons.add(context); singletons.add(serviceNamesMarshaller); singletons.add(serviceInstanceMarshaller); @@ -103,33 +99,29 @@ public Set getSingletons() server.setHandler(root); server.start(); } - + @AfterEach - public void teardown() throws Exception - { + public void teardown() throws Exception { server.stop(); server.join(); } @Test - public void testRegisterService() throws Exception - { - Map payload = Maps.newHashMap(); + public void testRegisterService() throws Exception { + Map payload = Maps.newHashMap(); payload.put("one", "1"); payload.put("two", "2"); payload.put("three", "3"); ServiceInstance> service = ServiceInstance.>builder() - .name("test") - .payload(payload) - .serviceType(ServiceType.STATIC) - .build(); + .name("test") + .payload(payload) + .serviceType(ServiceType.STATIC) + .build(); - ClientConfig config = new DefaultClientConfig() - { + ClientConfig config = new DefaultClientConfig() { @Override - public Set getSingletons() - { - Set singletons = Sets.newHashSet(); + public Set getSingletons() { + Set singletons = Sets.newHashSet(); singletons.add(context); singletons.add(serviceNamesMarshaller); singletons.add(serviceInstanceMarshaller); @@ -137,23 +129,28 @@ public Set getSingletons() return singletons; } }; - Client client = Client.create(config); - WebResource resource = client.resource("http://" + HOST + ":" + port); - resource.path("/v1/service/test/" + service.getId()).type(MediaType.APPLICATION_JSON_TYPE).put(service); + Client client = Client.create(config); + WebResource resource = client.resource("http://" + HOST + ":" + port); + resource.path("/v1/service/test/" + service.getId()) + .type(MediaType.APPLICATION_JSON_TYPE) + .put(service); ServiceNames names = resource.path("/v1/service").get(ServiceNames.class); assertEquals(names.getNames(), Lists.newArrayList("test")); - GenericType>> type = new GenericType>>(){}; - ServiceInstances> instances = resource.path("/v1/service/test").get(type); + GenericType>> type = + new GenericType>>() {}; + ServiceInstances> instances = + resource.path("/v1/service/test").get(type); assertEquals(instances.getServices().size(), 1); assertEquals(instances.getServices().get(0), service); assertEquals(instances.getServices().get(0).getPayload(), payload); // Retrieve a single instance - GenericType>> singleInstanceType = new GenericType>>(){}; - ServiceInstance> instance = resource.path("/v1/service/test/" + service.getId()).get(singleInstanceType); + GenericType>> singleInstanceType = + new GenericType>>() {}; + ServiceInstance> instance = + resource.path("/v1/service/test/" + service.getId()).get(singleInstanceType); assertEquals(instance, service); - } } diff --git a/curator-x-discovery-server/src/test/java/org/apache/curator/x/discovery/server/jetty_jersey/TestObjectPayloadWithJersey.java b/curator-x-discovery-server/src/test/java/org/apache/curator/x/discovery/server/jetty_jersey/TestObjectPayloadWithJersey.java index 876895f21..93e532e84 100644 --- a/curator-x-discovery-server/src/test/java/org/apache/curator/x/discovery/server/jetty_jersey/TestObjectPayloadWithJersey.java +++ b/curator-x-discovery-server/src/test/java/org/apache/curator/x/discovery/server/jetty_jersey/TestObjectPayloadWithJersey.java @@ -29,6 +29,9 @@ import com.sun.jersey.api.client.config.DefaultClientConfig; import com.sun.jersey.api.core.DefaultResourceConfig; import com.sun.jersey.spi.container.servlet.ServletContainer; +import java.util.Set; +import javax.ws.rs.core.Application; +import javax.ws.rs.core.MediaType; import org.apache.curator.test.InstanceSpec; import org.apache.curator.x.discovery.ServiceInstance; import org.apache.curator.x.discovery.ServiceType; @@ -45,12 +48,8 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import javax.ws.rs.core.Application; -import javax.ws.rs.core.MediaType; -import java.util.Set; -public class TestObjectPayloadWithJersey -{ +public class TestObjectPayloadWithJersey { private static final String HOST = "127.0.0.1"; private Server server; private JsonServiceNamesMarshaller serviceNamesMarshaller; @@ -60,27 +59,24 @@ public class TestObjectPayloadWithJersey private int port; @BeforeEach - public void setup() throws Exception - { - context = new ServiceDetailsDiscoveryContext(new MockServiceDiscovery(), new RandomStrategy(), 1000); + public void setup() throws Exception { + context = new ServiceDetailsDiscoveryContext( + new MockServiceDiscovery(), new RandomStrategy(), 1000); serviceNamesMarshaller = new JsonServiceNamesMarshaller(); serviceInstanceMarshaller = new JsonServiceInstanceMarshaller(context); serviceInstancesMarshaller = new JsonServiceInstancesMarshaller(context); - Application application = new DefaultResourceConfig() - { + Application application = new DefaultResourceConfig() { @Override - public Set> getClasses() - { - Set> classes = Sets.newHashSet(); + public Set> getClasses() { + Set> classes = Sets.newHashSet(); classes.add(ServiceDetailsDiscoveryResource.class); return classes; } @Override - public Set getSingletons() - { - Set singletons = Sets.newHashSet(); + public Set getSingletons() { + Set singletons = Sets.newHashSet(); singletons.add(context); singletons.add(serviceNamesMarshaller); singletons.add(serviceInstanceMarshaller); @@ -100,34 +96,30 @@ public Set getSingletons() server.setHandler(root); server.start(); } - + @AfterEach - public void teardown() throws Exception - { + public void teardown() throws Exception { server.stop(); server.join(); } @Test - public void testRegisterService() throws Exception - { - ServiceDetails payload = new ServiceDetails(); + public void testRegisterService() throws Exception { + ServiceDetails payload = new ServiceDetails(); payload.setDescription("Example description for test"); payload.getData().put("one", "1"); payload.getData().put("two", "2"); payload.getData().put("three", "3"); ServiceInstance service = ServiceInstance.builder() - .name("test") - .payload(payload) - .serviceType(ServiceType.STATIC) - .build(); + .name("test") + .payload(payload) + .serviceType(ServiceType.STATIC) + .build(); - ClientConfig config = new DefaultClientConfig() - { + ClientConfig config = new DefaultClientConfig() { @Override - public Set getSingletons() - { - Set singletons = Sets.newHashSet(); + public Set getSingletons() { + Set singletons = Sets.newHashSet(); singletons.add(context); singletons.add(serviceNamesMarshaller); singletons.add(serviceInstanceMarshaller); @@ -135,23 +127,27 @@ public Set getSingletons() return singletons; } }; - Client client = Client.create(config); - WebResource resource = client.resource("http://" + HOST + ":" + port); - resource.path("/v1/service/test/" + service.getId()).type(MediaType.APPLICATION_JSON_TYPE).put(service); + Client client = Client.create(config); + WebResource resource = client.resource("http://" + HOST + ":" + port); + resource.path("/v1/service/test/" + service.getId()) + .type(MediaType.APPLICATION_JSON_TYPE) + .put(service); ServiceNames names = resource.path("/v1/service").get(ServiceNames.class); assertEquals(names.getNames(), Lists.newArrayList("test")); - GenericType> type = new GenericType>(){}; - ServiceInstances instances = resource.path("/v1/service/test").get(type); + GenericType> type = new GenericType>() {}; + ServiceInstances instances = + resource.path("/v1/service/test").get(type); assertEquals(instances.getServices().size(), 1); assertEquals(instances.getServices().get(0), service); assertEquals(instances.getServices().get(0).getPayload(), payload); // Retrieve a single instance - GenericType> singleInstanceType = new GenericType>(){}; - ServiceInstance instance = resource.path("/v1/service/test/" + service.getId()).get(singleInstanceType); + GenericType> singleInstanceType = + new GenericType>() {}; + ServiceInstance instance = + resource.path("/v1/service/test/" + service.getId()).get(singleInstanceType); assertEquals(instance, service); - } } diff --git a/curator-x-discovery-server/src/test/java/org/apache/curator/x/discovery/server/jetty_jersey/TestStringsWithJersey.java b/curator-x-discovery-server/src/test/java/org/apache/curator/x/discovery/server/jetty_jersey/TestStringsWithJersey.java index 3fcff1407..96373a90b 100644 --- a/curator-x-discovery-server/src/test/java/org/apache/curator/x/discovery/server/jetty_jersey/TestStringsWithJersey.java +++ b/curator-x-discovery-server/src/test/java/org/apache/curator/x/discovery/server/jetty_jersey/TestStringsWithJersey.java @@ -29,6 +29,9 @@ import com.sun.jersey.api.client.config.DefaultClientConfig; import com.sun.jersey.api.core.DefaultResourceConfig; import com.sun.jersey.spi.container.servlet.ServletContainer; +import java.util.Set; +import javax.ws.rs.core.Application; +import javax.ws.rs.core.MediaType; import org.apache.curator.test.InstanceSpec; import org.apache.curator.x.discovery.ServiceInstance; import org.apache.curator.x.discovery.ServiceType; @@ -46,12 +49,8 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import javax.ws.rs.core.Application; -import javax.ws.rs.core.MediaType; -import java.util.Set; -public class TestStringsWithJersey -{ +public class TestStringsWithJersey { private static final String HOST = "127.0.0.1"; private Server server; private JsonServiceNamesMarshaller serviceNamesMarshaller; @@ -61,27 +60,23 @@ public class TestStringsWithJersey private int port; @BeforeEach - public void setup() throws Exception - { + public void setup() throws Exception { context = new StringDiscoveryContext(new MockServiceDiscovery(), new RandomStrategy(), 1000); serviceNamesMarshaller = new JsonServiceNamesMarshaller(); serviceInstanceMarshaller = new JsonServiceInstanceMarshaller(context); serviceInstancesMarshaller = new JsonServiceInstancesMarshaller(context); - Application application = new DefaultResourceConfig() - { + Application application = new DefaultResourceConfig() { @Override - public Set> getClasses() - { - Set> classes = Sets.newHashSet(); + public Set> getClasses() { + Set> classes = Sets.newHashSet(); classes.add(StringDiscoveryResource.class); return classes; } @Override - public Set getSingletons() - { - Set singletons = Sets.newHashSet(); + public Set getSingletons() { + Set singletons = Sets.newHashSet(); singletons.add(context); singletons.add(serviceNamesMarshaller); singletons.add(serviceInstanceMarshaller); @@ -101,29 +96,25 @@ public Set getSingletons() server.setHandler(root); server.start(); } - + @AfterEach - public void teardown() throws Exception - { + public void teardown() throws Exception { server.stop(); server.join(); } @Test - public void testRegisterService() throws Exception - { + public void testRegisterService() throws Exception { ServiceInstance service = ServiceInstance.builder() - .name("test") - .payload("From Test") - .serviceType(ServiceType.STATIC) - .build(); + .name("test") + .payload("From Test") + .serviceType(ServiceType.STATIC) + .build(); - ClientConfig config = new DefaultClientConfig() - { + ClientConfig config = new DefaultClientConfig() { @Override - public Set getSingletons() - { - Set singletons = Sets.newHashSet(); + public Set getSingletons() { + Set singletons = Sets.newHashSet(); singletons.add(context); singletons.add(serviceNamesMarshaller); singletons.add(serviceInstanceMarshaller); @@ -131,33 +122,33 @@ public Set getSingletons() return singletons; } }; - Client client = Client.create(config); - WebResource resource = client.resource("http://" + HOST + ":" + port); - resource.path("/v1/service/test/" + service.getId()).type(MediaType.APPLICATION_JSON_TYPE).put(service); + Client client = Client.create(config); + WebResource resource = client.resource("http://" + HOST + ":" + port); + resource.path("/v1/service/test/" + service.getId()) + .type(MediaType.APPLICATION_JSON_TYPE) + .put(service); ServiceNames names = resource.path("/v1/service").get(ServiceNames.class); assertEquals(names.getNames(), Lists.newArrayList("test")); - GenericType> type = new GenericType>(){}; + GenericType> type = new GenericType>() {}; ServiceInstances instances = resource.path("/v1/service/test").get(type); assertEquals(instances.getServices().size(), 1); assertEquals(instances.getServices().get(0), service); // Retrieve a single instance - GenericType> singleInstanceType = new GenericType>(){}; - ServiceInstance instance = resource.path("/v1/service/test/" + service.getId()).get(singleInstanceType); + GenericType> singleInstanceType = new GenericType>() {}; + ServiceInstance instance = + resource.path("/v1/service/test/" + service.getId()).get(singleInstanceType); assertEquals(instance, service); } @Test - public void testEmptyServiceNames() - { - ClientConfig config = new DefaultClientConfig() - { + public void testEmptyServiceNames() { + ClientConfig config = new DefaultClientConfig() { @Override - public Set getSingletons() - { - Set singletons = Sets.newHashSet(); + public Set getSingletons() { + Set singletons = Sets.newHashSet(); singletons.add(context); singletons.add(serviceNamesMarshaller); singletons.add(serviceInstanceMarshaller); @@ -165,8 +156,8 @@ public Set getSingletons() return singletons; } }; - Client client = Client.create(config); - WebResource resource = client.resource("http://" + HOST + ":" + port); + Client client = Client.create(config); + WebResource resource = client.resource("http://" + HOST + ":" + port); ServiceNames names = resource.path("/v1/service").get(ServiceNames.class); assertEquals(names.getNames(), Lists.newArrayList()); } diff --git a/curator-x-discovery-server/src/test/java/org/apache/curator/x/discovery/server/jetty_resteasy/RestEasyApplication.java b/curator-x-discovery-server/src/test/java/org/apache/curator/x/discovery/server/jetty_resteasy/RestEasyApplication.java index f1f45fcec..a46daa95b 100644 --- a/curator-x-discovery-server/src/test/java/org/apache/curator/x/discovery/server/jetty_resteasy/RestEasyApplication.java +++ b/curator-x-discovery-server/src/test/java/org/apache/curator/x/discovery/server/jetty_resteasy/RestEasyApplication.java @@ -20,26 +20,24 @@ package org.apache.curator.x.discovery.server.jetty_resteasy; import com.google.common.collect.Sets; -import javax.ws.rs.core.Application; import java.util.Set; import java.util.concurrent.atomic.AtomicReference; +import javax.ws.rs.core.Application; -public class RestEasyApplication extends Application -{ - public static final AtomicReference singletonsRef = new AtomicReference(new RestEasySingletons()); +public class RestEasyApplication extends Application { + public static final AtomicReference singletonsRef = + new AtomicReference(new RestEasySingletons()); @Override - public Set> getClasses() - { - Set> classes = Sets.newHashSet(); + public Set> getClasses() { + Set> classes = Sets.newHashSet(); classes.add(StringDiscoveryResource.class); return classes; } @Override - public Set getSingletons() - { - Set singletons = Sets.newHashSet(); + public Set getSingletons() { + Set singletons = Sets.newHashSet(); singletons.add(singletonsRef.get().contextSingleton); singletons.add(singletonsRef.get().serviceNamesMarshallerSingleton); singletons.add(singletonsRef.get().serviceInstanceMarshallerSingleton); diff --git a/curator-x-discovery-server/src/test/java/org/apache/curator/x/discovery/server/jetty_resteasy/RestEasySingletons.java b/curator-x-discovery-server/src/test/java/org/apache/curator/x/discovery/server/jetty_resteasy/RestEasySingletons.java index 6717cc47e..ad11b09db 100644 --- a/curator-x-discovery-server/src/test/java/org/apache/curator/x/discovery/server/jetty_resteasy/RestEasySingletons.java +++ b/curator-x-discovery-server/src/test/java/org/apache/curator/x/discovery/server/jetty_resteasy/RestEasySingletons.java @@ -20,21 +20,23 @@ package org.apache.curator.x.discovery.server.jetty_resteasy; import org.apache.curator.x.discovery.ServiceDiscovery; +import org.apache.curator.x.discovery.server.contexts.StringDiscoveryContext; import org.apache.curator.x.discovery.server.entity.JsonServiceInstanceMarshaller; import org.apache.curator.x.discovery.server.entity.JsonServiceInstancesMarshaller; import org.apache.curator.x.discovery.server.entity.JsonServiceNamesMarshaller; import org.apache.curator.x.discovery.server.mocks.MockServiceDiscovery; -import org.apache.curator.x.discovery.server.contexts.StringDiscoveryContext; import org.apache.curator.x.discovery.strategies.RandomStrategy; /** * For testing purposes only. You will inject these however is appropriate for your application */ -public class RestEasySingletons -{ +public class RestEasySingletons { public final ServiceDiscovery serviceDiscoverySingleton = new MockServiceDiscovery(); - public final StringDiscoveryContext contextSingleton = new StringDiscoveryContext(serviceDiscoverySingleton, new RandomStrategy(), 1000); - public final JsonServiceInstanceMarshaller serviceInstanceMarshallerSingleton = new JsonServiceInstanceMarshaller(contextSingleton); - public final JsonServiceInstancesMarshaller serviceInstancesMarshallerSingleton = new JsonServiceInstancesMarshaller(contextSingleton); + public final StringDiscoveryContext contextSingleton = + new StringDiscoveryContext(serviceDiscoverySingleton, new RandomStrategy(), 1000); + public final JsonServiceInstanceMarshaller serviceInstanceMarshallerSingleton = + new JsonServiceInstanceMarshaller(contextSingleton); + public final JsonServiceInstancesMarshaller serviceInstancesMarshallerSingleton = + new JsonServiceInstancesMarshaller(contextSingleton); public final JsonServiceNamesMarshaller serviceNamesMarshallerSingleton = new JsonServiceNamesMarshaller(); } diff --git a/curator-x-discovery-server/src/test/java/org/apache/curator/x/discovery/server/jetty_resteasy/StringDiscoveryResource.java b/curator-x-discovery-server/src/test/java/org/apache/curator/x/discovery/server/jetty_resteasy/StringDiscoveryResource.java index 7c83a8840..230f63818 100644 --- a/curator-x-discovery-server/src/test/java/org/apache/curator/x/discovery/server/jetty_resteasy/StringDiscoveryResource.java +++ b/curator-x-discovery-server/src/test/java/org/apache/curator/x/discovery/server/jetty_resteasy/StringDiscoveryResource.java @@ -19,25 +19,23 @@ package org.apache.curator.x.discovery.server.jetty_resteasy; -import org.apache.curator.x.discovery.server.rest.DiscoveryContext; -import org.apache.curator.x.discovery.server.rest.DiscoveryResource; import javax.ws.rs.Path; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.ext.ContextResolver; import javax.ws.rs.ext.Providers; +import org.apache.curator.x.discovery.server.rest.DiscoveryContext; +import org.apache.curator.x.discovery.server.rest.DiscoveryResource; @Path("/") -public class StringDiscoveryResource extends DiscoveryResource -{ - public StringDiscoveryResource(@Context Providers providers) - { +public class StringDiscoveryResource extends DiscoveryResource { + public StringDiscoveryResource(@Context Providers providers) { super(getContextFromProvider(providers)); } - private static DiscoveryContext getContextFromProvider(Providers providers) - { - ContextResolver contextResolver = providers.getContextResolver(DiscoveryContext.class, MediaType.WILDCARD_TYPE); + private static DiscoveryContext getContextFromProvider(Providers providers) { + ContextResolver contextResolver = + providers.getContextResolver(DiscoveryContext.class, MediaType.WILDCARD_TYPE); //noinspection unchecked return contextResolver.getContext(DiscoveryContext.class); } diff --git a/curator-x-discovery-server/src/test/java/org/apache/curator/x/discovery/server/jetty_resteasy/TestStringsWithRestEasy.java b/curator-x-discovery-server/src/test/java/org/apache/curator/x/discovery/server/jetty_resteasy/TestStringsWithRestEasy.java index 3379a02ae..cb3a9df10 100644 --- a/curator-x-discovery-server/src/test/java/org/apache/curator/x/discovery/server/jetty_resteasy/TestStringsWithRestEasy.java +++ b/curator-x-discovery-server/src/test/java/org/apache/curator/x/discovery/server/jetty_resteasy/TestStringsWithRestEasy.java @@ -23,6 +23,16 @@ import com.google.common.collect.Lists; import com.google.common.io.ByteSource; import com.google.common.io.CharStreams; +import java.io.BufferedReader; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.net.HttpURLConnection; +import java.net.URL; +import java.net.URLConnection; +import javax.ws.rs.core.MediaType; import org.apache.curator.test.InstanceSpec; import org.apache.curator.x.discovery.ServiceInstance; import org.apache.curator.x.discovery.ServiceType; @@ -37,36 +47,24 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import javax.ws.rs.core.MediaType; -import java.io.BufferedReader; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.OutputStream; -import java.net.HttpURLConnection; -import java.net.URL; -import java.net.URLConnection; @SuppressWarnings("unchecked") -public class TestStringsWithRestEasy -{ +public class TestStringsWithRestEasy { private static final String HOST = "127.0.0.1"; private Server server; private int port; @BeforeEach - public void setup() throws Exception - { + public void setup() throws Exception { RestEasyApplication.singletonsRef.set(new RestEasySingletons()); ResteasyProviderFactory.setInstance(new ResteasyProviderFactory()); - HttpServletDispatcher dispatcher = new HttpServletDispatcher(); + HttpServletDispatcher dispatcher = new HttpServletDispatcher(); port = InstanceSpec.getRandomPort(); server = new Server(port); - + ServletContextHandler root = new ServletContextHandler(ServletContextHandler.SESSIONS); root.setContextPath("/"); root.setServer(server); @@ -80,78 +78,85 @@ public void setup() throws Exception } @AfterEach - public void teardown() throws Exception - { + public void teardown() throws Exception { server.stop(); server.join(); } @Test - public void testRegisterService() throws Exception - { - RestEasySingletons restEasySingletons = RestEasyApplication.singletonsRef.get(); + public void testRegisterService() throws Exception { + RestEasySingletons restEasySingletons = RestEasyApplication.singletonsRef.get(); ServiceInstance service = ServiceInstance.builder() - .name("test") - .payload("From Test") - .serviceType(ServiceType.STATIC) - .build(); + .name("test") + .payload("From Test") + .serviceType(ServiceType.STATIC) + .build(); - ByteArrayOutputStream out = new ByteArrayOutputStream(); + ByteArrayOutputStream out = new ByteArrayOutputStream(); restEasySingletons.serviceInstanceMarshallerSingleton.writeTo(service, null, null, null, null, null, out); getJson("http://" + HOST + ":" + port + "/v1/service/test/" + service.getId(), new String(out.toByteArray())); String json = getJson("http://" + HOST + ":" + port + "/v1/service", null); - ServiceNames names = restEasySingletons.serviceNamesMarshallerSingleton.readFrom(ServiceNames.class, null, null, MediaType.APPLICATION_JSON_TYPE, null, new ByteArrayInputStream(json.getBytes())); + ServiceNames names = restEasySingletons.serviceNamesMarshallerSingleton.readFrom( + ServiceNames.class, + null, + null, + MediaType.APPLICATION_JSON_TYPE, + null, + new ByteArrayInputStream(json.getBytes())); assertEquals(names.getNames(), Lists.newArrayList("test")); json = getJson("http://" + HOST + ":" + port + "/v1/service/test", null); - ServiceInstances instances = restEasySingletons.serviceInstancesMarshallerSingleton.readFrom(null, null, null, null, null, new ByteArrayInputStream(json.getBytes())); + ServiceInstances instances = restEasySingletons.serviceInstancesMarshallerSingleton.readFrom( + null, null, null, null, null, new ByteArrayInputStream(json.getBytes())); assertEquals(instances.getServices().size(), 1); assertEquals(instances.getServices().get(0), service); // Retrieve single instance json = getJson("http://" + HOST + ":" + port + "/v1/service/test/" + service.getId(), null); - ServiceInstance instance = restEasySingletons.serviceInstanceMarshallerSingleton.readFrom(null, null, null, null, null, new ByteArrayInputStream(json.getBytes())); + ServiceInstance instance = restEasySingletons.serviceInstanceMarshallerSingleton.readFrom( + null, null, null, null, null, new ByteArrayInputStream(json.getBytes())); assertEquals(instance, service); - } @Test - public void testEmptyServiceNames() throws Exception - { - String json = getJson("http://" + HOST + ":" + port + "/v1/service", null); - ServiceNames names = RestEasyApplication.singletonsRef.get().serviceNamesMarshallerSingleton.readFrom(ServiceNames.class, null, null, MediaType.APPLICATION_JSON_TYPE, null, new ByteArrayInputStream(json.getBytes())); + public void testEmptyServiceNames() throws Exception { + String json = getJson("http://" + HOST + ":" + port + "/v1/service", null); + ServiceNames names = RestEasyApplication.singletonsRef + .get() + .serviceNamesMarshallerSingleton + .readFrom( + ServiceNames.class, + null, + null, + MediaType.APPLICATION_JSON_TYPE, + null, + new ByteArrayInputStream(json.getBytes())); assertEquals(names.getNames(), Lists.newArrayList()); } - private String getJson(String urlStr, String body) throws IOException - { - URL url = new URL(urlStr); - URLConnection urlConnection = url.openConnection(); + private String getJson(String urlStr, String body) throws IOException { + URL url = new URL(urlStr); + URLConnection urlConnection = url.openConnection(); urlConnection.addRequestProperty("Accept", "application/json"); - if ( body != null ) - { - ((HttpURLConnection)urlConnection).setRequestMethod("PUT"); + if (body != null) { + ((HttpURLConnection) urlConnection).setRequestMethod("PUT"); urlConnection.addRequestProperty("Content-Type", "application/json"); urlConnection.addRequestProperty("Content-Length", Integer.toString(body.length())); urlConnection.setDoOutput(true); - OutputStream out = urlConnection.getOutputStream(); + OutputStream out = urlConnection.getOutputStream(); ByteSource.wrap(body.getBytes()).copyTo(out); } BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); - try - { + try { return CharStreams.toString(in); - } - finally - { + } finally { in.close(); } } - } diff --git a/curator-x-discovery-server/src/test/java/org/apache/curator/x/discovery/server/mocks/MockServiceDiscovery.java b/curator-x-discovery-server/src/test/java/org/apache/curator/x/discovery/server/mocks/MockServiceDiscovery.java index 54d4852f5..c224c08e1 100644 --- a/curator-x-discovery-server/src/test/java/org/apache/curator/x/discovery/server/mocks/MockServiceDiscovery.java +++ b/curator-x-discovery-server/src/test/java/org/apache/curator/x/discovery/server/mocks/MockServiceDiscovery.java @@ -24,80 +24,60 @@ import com.google.common.collect.Maps; import com.google.common.collect.Multimap; import com.google.common.collect.Multimaps; +import java.io.IOException; +import java.util.Collection; import org.apache.curator.x.discovery.ServiceCacheBuilder; import org.apache.curator.x.discovery.ServiceDiscovery; import org.apache.curator.x.discovery.ServiceInstance; import org.apache.curator.x.discovery.ServiceProviderBuilder; -import java.io.IOException; -import java.util.Collection; -public class MockServiceDiscovery implements ServiceDiscovery -{ - private final Multimap> services = Multimaps.synchronizedMultimap - ( - Multimaps.newMultimap - ( - Maps.>>newHashMap(), - new Supplier>>() - { +public class MockServiceDiscovery implements ServiceDiscovery { + private final Multimap> services = Multimaps.synchronizedMultimap(Multimaps.newMultimap( + Maps.>>newHashMap(), new Supplier>>() { @Override - public Collection> get() - { + public Collection> get() { return Lists.newArrayList(); } - } - ) - ); + })); @Override - public void start() throws Exception - { - } + public void start() throws Exception {} @Override - public void registerService(ServiceInstance service) throws Exception - { + public void registerService(ServiceInstance service) throws Exception { services.put(service.getName(), service); } @Override - public void unregisterService(ServiceInstance service) throws Exception - { + public void unregisterService(ServiceInstance service) throws Exception { services.remove(service.getName(), service); } @Override - public void updateService(ServiceInstance service) throws Exception - { + public void updateService(ServiceInstance service) throws Exception { services.put(service.getName(), service); } @Override - public ServiceCacheBuilder serviceCacheBuilder() - { + public ServiceCacheBuilder serviceCacheBuilder() { throw new UnsupportedOperationException(); } @Override - public Collection queryForNames() throws Exception - { + public Collection queryForNames() throws Exception { return services.keys(); } @Override - public Collection> queryForInstances(String name) throws Exception - { + public Collection> queryForInstances(String name) throws Exception { return services.get(name); } @Override - public ServiceInstance queryForInstance(String name, String id) throws Exception - { + public ServiceInstance queryForInstance(String name, String id) throws Exception { Collection> instances = services.get(name); - for ( ServiceInstance instance : instances ) - { - if ( instance.getId().equals(id) ) - { + for (ServiceInstance instance : instances) { + if (instance.getId().equals(id)) { return instance; } } @@ -105,13 +85,10 @@ public ServiceInstance queryForInstance(String name, String id) throws Except } @Override - public ServiceProviderBuilder serviceProviderBuilder() - { + public ServiceProviderBuilder serviceProviderBuilder() { throw new UnsupportedOperationException(); } @Override - public void close() throws IOException - { - } + public void close() throws IOException {} } diff --git a/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/DownInstancePolicy.java b/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/DownInstancePolicy.java index 3179baca2..10d49edea 100644 --- a/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/DownInstancePolicy.java +++ b/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/DownInstancePolicy.java @@ -24,8 +24,7 @@ /** * Abstraction for values that determine when an instance is down */ -public class DownInstancePolicy -{ +public class DownInstancePolicy { private final long timeoutMs; private final int errorThreshold; @@ -35,8 +34,7 @@ public class DownInstancePolicy /** * Policy with default values */ - public DownInstancePolicy() - { + public DownInstancePolicy() { this(DEFAULT_TIMEOUT_MS, TimeUnit.MILLISECONDS, DEFAULT_THRESHOLD); } @@ -45,19 +43,16 @@ public DownInstancePolicy() * @param unit time unit * @param errorThreshold number of errors within time window that denotes a down instance */ - public DownInstancePolicy(long timeout, TimeUnit unit, int errorThreshold) - { + public DownInstancePolicy(long timeout, TimeUnit unit, int errorThreshold) { this.timeoutMs = unit.toMillis(timeout); this.errorThreshold = errorThreshold; } - public long getTimeoutMs() - { + public long getTimeoutMs() { return timeoutMs; } - public int getErrorThreshold() - { + public int getErrorThreshold() { return errorThreshold; } } diff --git a/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/InstanceFilter.java b/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/InstanceFilter.java index d62a0f13f..cf89df7cc 100644 --- a/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/InstanceFilter.java +++ b/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/InstanceFilter.java @@ -24,6 +24,4 @@ /** * Typedef for an Instance predicate */ -public interface InstanceFilter extends Predicate> -{ -} +public interface InstanceFilter extends Predicate> {} diff --git a/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/LocalIpFilter.java b/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/LocalIpFilter.java index 942c3b0a9..59c0f6e67 100644 --- a/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/LocalIpFilter.java +++ b/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/LocalIpFilter.java @@ -23,7 +23,6 @@ import java.net.NetworkInterface; import java.net.SocketException; -public interface LocalIpFilter -{ - public boolean use(NetworkInterface networkInterface, InetAddress address) throws SocketException; +public interface LocalIpFilter { + public boolean use(NetworkInterface networkInterface, InetAddress address) throws SocketException; } diff --git a/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/ProviderStrategy.java b/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/ProviderStrategy.java index 80f20ca13..98d895e5a 100644 --- a/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/ProviderStrategy.java +++ b/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/ProviderStrategy.java @@ -24,8 +24,7 @@ /** * A strategy for picking one from a set of instances */ -public interface ProviderStrategy -{ +public interface ProviderStrategy { /** * Given a source of instances, return one of them for a single use. * @@ -33,5 +32,5 @@ public interface ProviderStrategy * @return the instance to use * @throws Exception any errors */ - public ServiceInstance getInstance(InstanceProvider instanceProvider) throws Exception; + public ServiceInstance getInstance(InstanceProvider instanceProvider) throws Exception; } diff --git a/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/ServiceCache.java b/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/ServiceCache.java index 5498d7220..6fbffa179 100644 --- a/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/ServiceCache.java +++ b/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/ServiceCache.java @@ -19,15 +19,14 @@ package org.apache.curator.x.discovery; -import org.apache.curator.framework.listen.Listenable; -import org.apache.curator.x.discovery.details.InstanceProvider; -import org.apache.curator.x.discovery.details.ServiceCacheListener; import java.io.Closeable; import java.util.List; import java.util.concurrent.CountDownLatch; +import org.apache.curator.framework.listen.Listenable; +import org.apache.curator.x.discovery.details.InstanceProvider; +import org.apache.curator.x.discovery.details.ServiceCacheListener; -public interface ServiceCache extends Closeable, Listenable, InstanceProvider -{ +public interface ServiceCache extends Closeable, Listenable, InstanceProvider { /** * Return the current list of instances. NOTE: there is no guarantee of freshness. This is * merely the last known list of instances. However, the list is updated via a ZooKeeper watcher diff --git a/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/ServiceCacheBuilder.java b/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/ServiceCacheBuilder.java index 13714f173..16feafff2 100644 --- a/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/ServiceCacheBuilder.java +++ b/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/ServiceCacheBuilder.java @@ -22,8 +22,7 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.ThreadFactory; -public interface ServiceCacheBuilder -{ +public interface ServiceCacheBuilder { /** * Return a new service cache with the current settings * diff --git a/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/ServiceDiscovery.java b/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/ServiceDiscovery.java index 8dc13212c..808fc9e45 100644 --- a/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/ServiceDiscovery.java +++ b/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/ServiceDiscovery.java @@ -19,12 +19,11 @@ package org.apache.curator.x.discovery; -import org.apache.curator.x.discovery.strategies.RoundRobinStrategy; import java.io.Closeable; import java.util.Collection; +import org.apache.curator.x.discovery.strategies.RoundRobinStrategy; -public interface ServiceDiscovery extends Closeable -{ +public interface ServiceDiscovery extends Closeable { /** * The discovery must be started before use * @@ -38,7 +37,7 @@ public interface ServiceDiscovery extends Closeable * @param service service to add * @throws Exception errors */ - public void registerService(ServiceInstance service) throws Exception; + public void registerService(ServiceInstance service) throws Exception; /** * Update a service @@ -46,7 +45,7 @@ public interface ServiceDiscovery extends Closeable * @param service service to update * @throws Exception errors */ - public void updateService(ServiceInstance service) throws Exception; + public void updateService(ServiceInstance service) throws Exception; /** * Unregister/remove a service instance @@ -54,7 +53,7 @@ public interface ServiceDiscovery extends Closeable * @param service the service * @throws Exception errors */ - public void unregisterService(ServiceInstance service) throws Exception; + public void unregisterService(ServiceInstance service) throws Exception; /** * Allocate a new service cache builder. The refresh padding is defaulted to 1 second. @@ -78,7 +77,7 @@ public interface ServiceDiscovery extends Closeable * @return list of instances (or an empty list) * @throws Exception errors */ - public Collection> queryForInstances(String name) throws Exception; + public Collection> queryForInstances(String name) throws Exception; /** * Return a service instance POJO diff --git a/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/ServiceDiscoveryBuilder.java b/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/ServiceDiscoveryBuilder.java index 08825dbd4..a5159a659 100644 --- a/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/ServiceDiscoveryBuilder.java +++ b/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/ServiceDiscoveryBuilder.java @@ -24,8 +24,7 @@ import org.apache.curator.x.discovery.details.JsonInstanceSerializer; import org.apache.curator.x.discovery.details.ServiceDiscoveryImpl; -public class ServiceDiscoveryBuilder -{ +public class ServiceDiscoveryBuilder { private CuratorFramework client; private String basePath; private InstanceSerializer serializer; @@ -40,8 +39,7 @@ public class ServiceDiscoveryBuilder * if your instances don't need a payload) * @return new builder */ - public static ServiceDiscoveryBuilder builder(Class payloadClass) - { + public static ServiceDiscoveryBuilder builder(Class payloadClass) { return new ServiceDiscoveryBuilder(payloadClass); } @@ -51,10 +49,8 @@ public static ServiceDiscoveryBuilder builder(Class payloadClass) * * @return new service discovery */ - public ServiceDiscovery build() - { - if ( serializer == null ) - { + public ServiceDiscovery build() { + if (serializer == null) { serializer(new JsonInstanceSerializer(payloadClass)); } return new ServiceDiscoveryImpl(client, basePath, serializer, thisInstance, watchInstances); @@ -66,8 +62,7 @@ public ServiceDiscovery build() * @param client client * @return this */ - public ServiceDiscoveryBuilder client(CuratorFramework client) - { + public ServiceDiscoveryBuilder client(CuratorFramework client) { this.client = client; return this; } @@ -78,8 +73,7 @@ public ServiceDiscoveryBuilder client(CuratorFramework client) * @param basePath base path * @return this */ - public ServiceDiscoveryBuilder basePath(String basePath) - { + public ServiceDiscoveryBuilder basePath(String basePath) { this.basePath = basePath; return this; } @@ -90,8 +84,7 @@ public ServiceDiscoveryBuilder basePath(String basePath) * @param serializer the serializer * @return this */ - public ServiceDiscoveryBuilder serializer(InstanceSerializer serializer) - { + public ServiceDiscoveryBuilder serializer(InstanceSerializer serializer) { this.serializer = serializer; return this; } @@ -102,8 +95,7 @@ public ServiceDiscoveryBuilder serializer(InstanceSerializer serializer) * @param thisInstance initial instance * @return this */ - public ServiceDiscoveryBuilder thisInstance(ServiceInstance thisInstance) - { + public ServiceDiscoveryBuilder thisInstance(ServiceInstance thisInstance) { this.thisInstance = thisInstance; return this; } @@ -116,14 +108,12 @@ public ServiceDiscoveryBuilder thisInstance(ServiceInstance thisInstance) * @param watchInstances true to watch instances * @return this */ - public ServiceDiscoveryBuilder watchInstances(boolean watchInstances) - { + public ServiceDiscoveryBuilder watchInstances(boolean watchInstances) { this.watchInstances = watchInstances; return this; } - ServiceDiscoveryBuilder(Class payloadClass) - { + ServiceDiscoveryBuilder(Class payloadClass) { this.payloadClass = payloadClass; } } diff --git a/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/ServiceInstance.java b/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/ServiceInstance.java index e7a896c96..24e104bb1 100644 --- a/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/ServiceInstance.java +++ b/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/ServiceInstance.java @@ -30,18 +30,17 @@ /** * POJO that represents a service instance */ -public class ServiceInstance -{ - private final String name; - private final String id; - private final String address; - private final Integer port; - private final Integer sslPort; - private final T payload; - private final long registrationTimeUTC; - private final ServiceType serviceType; - private final UriSpec uriSpec; - private final boolean enabled; +public class ServiceInstance { + private final String name; + private final String id; + private final String address; + private final Integer port; + private final Integer sslPort; + private final T payload; + private final long registrationTimeUTC; + private final ServiceType serviceType; + private final UriSpec uriSpec; + private final boolean enabled; /** * Return a new builder. The {@link #address} is set to the ip of the first @@ -50,16 +49,14 @@ public class ServiceInstance * @return builder * @throws Exception errors getting the local IP */ - public static ServiceInstanceBuilderbuilder() throws Exception - { - String address = null; + public static ServiceInstanceBuilder builder() throws Exception { + String address = null; Collection ips = ServiceInstanceBuilder.getAllLocalIPs(); - if ( ips.size() > 0 ) - { - address = ips.iterator().next().getHostAddress(); // default to the first address + if (ips.size() > 0) { + address = ips.iterator().next().getHostAddress(); // default to the first address } - String id = UUID.randomUUID().toString(); + String id = UUID.randomUUID().toString(); return new ServiceInstanceBuilder().address(address).id(id).registrationTimeUTC(System.currentTimeMillis()); } @@ -75,8 +72,16 @@ public class ServiceInstance * @param serviceType type of the service * @param uriSpec the uri spec or null */ - public ServiceInstance(String name, String id, String address, Integer port, Integer sslPort, T payload, long registrationTimeUTC, ServiceType serviceType, UriSpec uriSpec) - { + public ServiceInstance( + String name, + String id, + String address, + Integer port, + Integer sslPort, + T payload, + long registrationTimeUTC, + ServiceType serviceType, + UriSpec uriSpec) { this(name, id, address, port, sslPort, payload, registrationTimeUTC, serviceType, uriSpec, true); } @@ -98,8 +103,17 @@ public ServiceInstance(String name, String id, String address, Integer port, Int * @param uriSpec the uri spec or null * @param enabled true if the instance should be considered enabled */ - public ServiceInstance(String name, String id, String address, Integer port, Integer sslPort, T payload, long registrationTimeUTC, ServiceType serviceType, UriSpec uriSpec, boolean enabled) - { + public ServiceInstance( + String name, + String id, + String address, + Integer port, + Integer sslPort, + T payload, + long registrationTimeUTC, + ServiceType serviceType, + UriSpec uriSpec, + boolean enabled) { name = Preconditions.checkNotNull(name, "name cannot be null"); id = Preconditions.checkNotNull(id, "id cannot be null"); @@ -118,54 +132,44 @@ public ServiceInstance(String name, String id, String address, Integer port, Int /** * Inits to default values. Only exists for deserialization */ - ServiceInstance() - { + ServiceInstance() { this("", "", null, null, null, null, 0, ServiceType.DYNAMIC, null, true); } - public String getName() - { + public String getName() { return name; } - public String getId() - { + public String getId() { return id; } - public String getAddress() - { + public String getAddress() { return address; } - public Integer getPort() - { + public Integer getPort() { return port; } - public Integer getSslPort() - { + public Integer getSslPort() { return sslPort; } - @JsonTypeInfo(use= JsonTypeInfo.Id.CLASS, defaultImpl=Object.class) - public T getPayload() - { + @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, defaultImpl = Object.class) + public T getPayload() { return payload; } - public long getRegistrationTimeUTC() - { + public long getRegistrationTimeUTC() { return registrationTimeUTC; } - public ServiceType getServiceType() - { + public ServiceType getServiceType() { return serviceType; } - public UriSpec getUriSpec() - { + public UriSpec getUriSpec() { return uriSpec; } @@ -178,74 +182,58 @@ public UriSpec getUriSpec() * * @return true/false */ - public boolean isEnabled() - { + public boolean isEnabled() { return enabled; } - public String buildUriSpec() - { + public String buildUriSpec() { return buildUriSpec(Maps.newHashMap()); } - public String buildUriSpec(Map variables) - { + public String buildUriSpec(Map variables) { return (uriSpec != null) ? uriSpec.build(this, variables) : ""; } @SuppressWarnings("RedundantIfStatement") @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; } - ServiceInstance that = (ServiceInstance)o; + ServiceInstance that = (ServiceInstance) o; - if ( registrationTimeUTC != that.registrationTimeUTC ) - { + if (registrationTimeUTC != that.registrationTimeUTC) { return false; } - if ( address != null ? !address.equals(that.address) : that.address != null ) - { + if (address != null ? !address.equals(that.address) : that.address != null) { return false; } - if ( id != null ? !id.equals(that.id) : that.id != null ) - { + if (id != null ? !id.equals(that.id) : that.id != null) { return false; } - if ( name != null ? !name.equals(that.name) : that.name != null ) - { + if (name != null ? !name.equals(that.name) : that.name != null) { return false; } - if ( payload != null ? !payload.equals(that.payload) : that.payload != null ) - { + if (payload != null ? !payload.equals(that.payload) : that.payload != null) { return false; } - if ( port != null ? !port.equals(that.port) : that.port != null ) - { + if (port != null ? !port.equals(that.port) : that.port != null) { return false; } - if ( serviceType != that.serviceType ) - { + if (serviceType != that.serviceType) { return false; } - if ( sslPort != null ? !sslPort.equals(that.sslPort) : that.sslPort != null ) - { + if (sslPort != null ? !sslPort.equals(that.sslPort) : that.sslPort != null) { return false; } - if ( uriSpec != null ? !uriSpec.equals(that.uriSpec) : that.uriSpec != null ) - { + if (uriSpec != null ? !uriSpec.equals(that.uriSpec) : that.uriSpec != null) { return false; } - if ( enabled != that.enabled ) - { + if (enabled != that.enabled) { return false; } @@ -253,15 +241,14 @@ public boolean equals(Object o) } @Override - public int hashCode() - { + public int hashCode() { int result = name != null ? name.hashCode() : 0; result = 31 * result + (id != null ? id.hashCode() : 0); result = 31 * result + (address != null ? address.hashCode() : 0); result = 31 * result + (port != null ? port.hashCode() : 0); result = 31 * result + (sslPort != null ? sslPort.hashCode() : 0); result = 31 * result + (payload != null ? payload.hashCode() : 0); - result = 31 * result + (int)(registrationTimeUTC ^ (registrationTimeUTC >>> 32)); + result = 31 * result + (int) (registrationTimeUTC ^ (registrationTimeUTC >>> 32)); result = 31 * result + (serviceType != null ? serviceType.hashCode() : 0); result = 31 * result + (uriSpec != null ? uriSpec.hashCode() : 0); result = 31 * result + (enabled ? 1 : 0); @@ -269,19 +256,17 @@ public int hashCode() } @Override - public String toString() - { - return "ServiceInstance{" + - "name='" + name + '\'' + - ", id='" + id + '\'' + - ", address='" + address + '\'' + - ", port=" + port + - ", sslPort=" + sslPort + - ", payload=" + payload + - ", registrationTimeUTC=" + registrationTimeUTC + - ", serviceType=" + serviceType + - ", uriSpec=" + uriSpec + - ", enabled=" + enabled + - '}'; + public String toString() { + return "ServiceInstance{" + "name='" + + name + '\'' + ", id='" + + id + '\'' + ", address='" + + address + '\'' + ", port=" + + port + ", sslPort=" + + sslPort + ", payload=" + + payload + ", registrationTimeUTC=" + + registrationTimeUTC + ", serviceType=" + + serviceType + ", uriSpec=" + + uriSpec + ", enabled=" + + enabled + '}'; } } diff --git a/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/ServiceInstanceBuilder.java b/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/ServiceInstanceBuilder.java index c3e3407bb..fc0e63629 100644 --- a/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/ServiceInstanceBuilder.java +++ b/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/ServiceInstanceBuilder.java @@ -31,8 +31,7 @@ /** * Builder for service instances */ -public class ServiceInstanceBuilder -{ +public class ServiceInstanceBuilder { private T payload; private String name; private String address; @@ -44,25 +43,22 @@ public class ServiceInstanceBuilder private UriSpec uriSpec; private boolean enabled = true; - private static final AtomicReference localIpFilter = new AtomicReference - ( - new LocalIpFilter() - { - @Override - public boolean use(NetworkInterface nif, InetAddress adr) throws SocketException - { - return (adr != null) && !adr.isLoopbackAddress() && (nif.isPointToPoint() || !adr.isLinkLocalAddress()); - } - } - ); + private static final AtomicReference localIpFilter = + new AtomicReference(new LocalIpFilter() { + @Override + public boolean use(NetworkInterface nif, InetAddress adr) throws SocketException { + return (adr != null) + && !adr.isLoopbackAddress() + && (nif.isPointToPoint() || !adr.isLinkLocalAddress()); + } + }); /** * Replace the default local ip filter used by {@link #getAllLocalIPs()} * * @param newLocalIpFilter the new local ip filter */ - public static void setLocalIpFilter(LocalIpFilter newLocalIpFilter) - { + public static void setLocalIpFilter(LocalIpFilter newLocalIpFilter) { localIpFilter.set(newLocalIpFilter); } @@ -71,81 +67,68 @@ public static void setLocalIpFilter(LocalIpFilter newLocalIpFilter) * * @return ip filter */ - public static LocalIpFilter getLocalIpFilter() - { + public static LocalIpFilter getLocalIpFilter() { return localIpFilter.get(); } - ServiceInstanceBuilder() - { - } + ServiceInstanceBuilder() {} /** * Return a new instance with the currently set values * * @return instance */ - public ServiceInstance build() - { - return new ServiceInstance(name, id, address, port, sslPort, payload, registrationTimeUTC, serviceType, uriSpec, enabled); + public ServiceInstance build() { + return new ServiceInstance( + name, id, address, port, sslPort, payload, registrationTimeUTC, serviceType, uriSpec, enabled); } - public ServiceInstanceBuilder name(String name) - { + public ServiceInstanceBuilder name(String name) { this.name = name; return this; } - public ServiceInstanceBuilder address(String address) - { + public ServiceInstanceBuilder address(String address) { this.address = address; return this; } - public ServiceInstanceBuilder id(String id) - { + public ServiceInstanceBuilder id(String id) { this.id = id; return this; } - public ServiceInstanceBuilder port(int port) - { + public ServiceInstanceBuilder port(int port) { this.port = port; return this; } - public ServiceInstanceBuilder sslPort(int port) - { + public ServiceInstanceBuilder sslPort(int port) { this.sslPort = port; return this; } - public ServiceInstanceBuilder payload(T payload) - { + public ServiceInstanceBuilder payload(T payload) { this.payload = payload; return this; } - public ServiceInstanceBuilder serviceType(ServiceType serviceType) - { + public ServiceInstanceBuilder serviceType(ServiceType serviceType) { this.serviceType = serviceType; return this; } - public ServiceInstanceBuilder registrationTimeUTC(long registrationTimeUTC) - { + public ServiceInstanceBuilder registrationTimeUTC(long registrationTimeUTC) { this.registrationTimeUTC = registrationTimeUTC; return this; } - public ServiceInstanceBuilder uriSpec(UriSpec uriSpec) - { + public ServiceInstanceBuilder uriSpec(UriSpec uriSpec) { this.uriSpec = uriSpec; return this; } - public ServiceInstanceBuilder enabled(boolean enabled) - { + public ServiceInstanceBuilder enabled(boolean enabled) { this.enabled = enabled; return this; } @@ -169,23 +152,19 @@ public ServiceInstanceBuilder enabled(boolean enabled) * @since 0.1.0 * @throws SocketException errors */ - public static Collection getAllLocalIPs() throws SocketException - { + public static Collection getAllLocalIPs() throws SocketException { List listAdr = Lists.newArrayList(); Enumeration nifs = NetworkInterface.getNetworkInterfaces(); if (nifs == null) return listAdr; - while (nifs.hasMoreElements()) - { + while (nifs.hasMoreElements()) { NetworkInterface nif = nifs.nextElement(); // We ignore subinterfaces - as not yet needed. Enumeration adrs = nif.getInetAddresses(); - while ( adrs.hasMoreElements() ) - { + while (adrs.hasMoreElements()) { InetAddress adr = adrs.nextElement(); - if ( localIpFilter.get().use(nif, adr) ) - { + if (localIpFilter.get().use(nif, adr)) { listAdr.add(adr); } } diff --git a/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/ServiceProvider.java b/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/ServiceProvider.java index 94574c935..b707b96ef 100644 --- a/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/ServiceProvider.java +++ b/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/ServiceProvider.java @@ -19,17 +19,16 @@ package org.apache.curator.x.discovery; -import org.apache.curator.x.discovery.details.InstanceProvider; import java.io.Closeable; import java.io.IOException; import java.util.Collection; +import org.apache.curator.x.discovery.details.InstanceProvider; /** * The main API for Discovery. This class is essentially a facade over a {@link ProviderStrategy} * paired with an {@link InstanceProvider} */ -public interface ServiceProvider extends Closeable -{ +public interface ServiceProvider extends Closeable { /** * The provider must be started before use * diff --git a/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/ServiceProviderBuilder.java b/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/ServiceProviderBuilder.java index ef7b340a6..bd161da2f 100644 --- a/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/ServiceProviderBuilder.java +++ b/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/ServiceProviderBuilder.java @@ -19,12 +19,11 @@ package org.apache.curator.x.discovery; -import org.apache.curator.x.discovery.strategies.RoundRobinStrategy; import java.util.concurrent.ExecutorService; import java.util.concurrent.ThreadFactory; +import org.apache.curator.x.discovery.strategies.RoundRobinStrategy; -public interface ServiceProviderBuilder -{ +public interface ServiceProviderBuilder { /** * Allocate a new service provider based on the current builder settings * diff --git a/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/ServiceType.java b/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/ServiceType.java index bc7a6ea7d..c74e01f3e 100644 --- a/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/ServiceType.java +++ b/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/ServiceType.java @@ -19,14 +19,13 @@ package org.apache.curator.x.discovery; -public enum ServiceType -{ +public enum ServiceType { DYNAMIC, STATIC, - PERMANENT, + PERMANENT, DYNAMIC_SEQUENTIAL; - public boolean isDynamic() { - return this == DYNAMIC || this == DYNAMIC_SEQUENTIAL; - } + public boolean isDynamic() { + return this == DYNAMIC || this == DYNAMIC_SEQUENTIAL; + } } diff --git a/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/UriSpec.java b/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/UriSpec.java index da623b844..fa85b894e 100644 --- a/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/UriSpec.java +++ b/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/UriSpec.java @@ -24,12 +24,12 @@ import com.google.common.collect.Iterators; import com.google.common.collect.Lists; import com.google.common.collect.Maps; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.StringTokenizer; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** *

    @@ -43,117 +43,106 @@ * Several pre-defined fields are listed as constants in this class (e.g. {@link #FIELD_SCHEME}). *

    */ -public class UriSpec implements Iterable -{ - private final Logger log = LoggerFactory.getLogger(getClass()); - private final List parts = Lists.newArrayList(); +public class UriSpec implements Iterable { + private final Logger log = LoggerFactory.getLogger(getClass()); + private final List parts = Lists.newArrayList(); /** * This defaults to "http". If a {@link ServiceInstance} is passed when building and an sslPort * is specified in the instance, the replacement is "https". */ - public static final String FIELD_SCHEME = "scheme"; + public static final String FIELD_SCHEME = "scheme"; /** * If a {@link ServiceInstance} is passed when building, the replacement is {@link ServiceInstance#getName()} */ - public static final String FIELD_NAME = "name"; + public static final String FIELD_NAME = "name"; /** * If a {@link ServiceInstance} is passed when building, the replacement is {@link ServiceInstance#getId()} */ - public static final String FIELD_ID = "id"; + public static final String FIELD_ID = "id"; /** * If a {@link ServiceInstance} is passed when building, the replacement is {@link ServiceInstance#getAddress()} */ - public static final String FIELD_ADDRESS = "address"; + public static final String FIELD_ADDRESS = "address"; /** * If a {@link ServiceInstance} is passed when building, the replacement is {@link ServiceInstance#getPort()} */ - public static final String FIELD_PORT = "port"; + public static final String FIELD_PORT = "port"; /** * If a {@link ServiceInstance} is passed when building, the replacement is {@link ServiceInstance#getSslPort()} */ - public static final String FIELD_SSL_PORT = "ssl-port"; + public static final String FIELD_SSL_PORT = "ssl-port"; /** * If a {@link ServiceInstance} is passed when building, the replacement is {@link ServiceInstance#getRegistrationTimeUTC()} */ - public static final String FIELD_REGISTRATION_TIME_UTC = "registration-time-utc"; + public static final String FIELD_REGISTRATION_TIME_UTC = "registration-time-utc"; /** * If a {@link ServiceInstance} is passed when building, the replacement is {@link ServiceInstance#getServiceType()} */ - public static final String FIELD_SERVICE_TYPE = "service-type"; + public static final String FIELD_SERVICE_TYPE = "service-type"; /** * Always replaced with '{' - i.e. this is how to insert a literal '{' */ - public static final String FIELD_OPEN_BRACE = "["; + public static final String FIELD_OPEN_BRACE = "["; /** * Always replaced with '}' - i.e. this is how to insert a literal '}' */ - public static final String FIELD_CLOSE_BRACE = "]"; + public static final String FIELD_CLOSE_BRACE = "]"; /** * Represents one token in the Uri spec */ - public static class Part - { - private final String value; - private final boolean variable; + public static class Part { + private final String value; + private final boolean variable; /** * @param value the token value * @param isVariable if true, a replacement field. If false, a literal string */ - public Part(String value, boolean isVariable) - { + public Part(String value, boolean isVariable) { this.value = value; this.variable = isVariable; } - public Part() - { + public Part() { value = ""; variable = false; } - public String getValue() - { + public String getValue() { return value; } - public boolean isVariable() - { + public boolean isVariable() { return variable; } @SuppressWarnings("RedundantIfStatement") @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; } - Part part = (Part)o; + Part part = (Part) o; - if ( variable != part.variable ) - { + if (variable != part.variable) { return false; } - if ( !value.equals(part.value) ) - { + if (!value.equals(part.value)) { return false; } @@ -161,43 +150,33 @@ public boolean equals(Object o) } @Override - public int hashCode() - { + public int hashCode() { int result = value.hashCode(); result = 31 * result + (variable ? 1 : 0); return result; } } - public UriSpec() - { + public UriSpec() { // NOP } /** * @param rawSpec the spec to parse */ - public UriSpec(String rawSpec) - { - boolean isInsideVariable = false; - StringTokenizer tokenizer = new StringTokenizer(rawSpec, "{}", true); - while ( tokenizer.hasMoreTokens() ) - { - String token = tokenizer.nextToken(); - if ( token.equals("{") ) - { + public UriSpec(String rawSpec) { + boolean isInsideVariable = false; + StringTokenizer tokenizer = new StringTokenizer(rawSpec, "{}", true); + while (tokenizer.hasMoreTokens()) { + String token = tokenizer.nextToken(); + if (token.equals("{")) { Preconditions.checkState(!isInsideVariable, "{ is not allowed inside of a variable specification"); isInsideVariable = true; - } - else if ( token.equals("}") ) - { + } else if (token.equals("}")) { Preconditions.checkState(isInsideVariable, "} must be preceded by {"); isInsideVariable = false; - } - else - { - if ( isInsideVariable ) - { + } else { + if (isInsideVariable) { token = token.trim(); } add(new Part(token, isInsideVariable)); @@ -212,8 +191,7 @@ else if ( token.equals("}") ) * * @return UriSpec string */ - public String build() - { + public String build() { return build(null, Maps.newHashMap()); } @@ -223,8 +201,7 @@ public String build() * @param serviceInstance instance to use for pre-defined replacement fields * @return UriSpec string */ - public String build(ServiceInstance serviceInstance) - { + public String build(ServiceInstance serviceInstance) { return build(serviceInstance, Maps.newHashMap()); } @@ -235,8 +212,7 @@ public String build(ServiceInstance serviceInstance) * in this map override pre-defined fields * @return UriSpec string */ - public String build(Map variables) - { + public String build(Map variables) { return build(null, variables); } @@ -248,47 +224,41 @@ public String build(Map variables) * in this map override pre-defined fields * @return UriSpec string */ - public String build(ServiceInstance serviceInstance, Map variables) - { - Map localVariables = Maps.newHashMap(); + public String build(ServiceInstance serviceInstance, Map variables) { + Map localVariables = Maps.newHashMap(); localVariables.put(FIELD_OPEN_BRACE, "{"); localVariables.put(FIELD_CLOSE_BRACE, "}"); localVariables.put(FIELD_SCHEME, "http"); - if ( serviceInstance != null ) - { + if (serviceInstance != null) { localVariables.put(FIELD_NAME, nullCheck(serviceInstance.getName())); localVariables.put(FIELD_ID, nullCheck(serviceInstance.getId())); localVariables.put(FIELD_ADDRESS, nullCheck(serviceInstance.getAddress())); localVariables.put(FIELD_PORT, nullCheck(serviceInstance.getPort())); localVariables.put(FIELD_SSL_PORT, nullCheck(serviceInstance.getSslPort())); localVariables.put(FIELD_REGISTRATION_TIME_UTC, nullCheck(serviceInstance.getRegistrationTimeUTC())); - localVariables.put(FIELD_SERVICE_TYPE, (serviceInstance.getServiceType() != null) ? serviceInstance.getServiceType().name().toLowerCase() : ""); - if ( serviceInstance.getSslPort() != null ) - { + localVariables.put( + FIELD_SERVICE_TYPE, + (serviceInstance.getServiceType() != null) + ? serviceInstance.getServiceType().name().toLowerCase() + : ""); + if (serviceInstance.getSslPort() != null) { localVariables.put(FIELD_SCHEME, "https"); } } localVariables.putAll(variables); - StringBuilder str = new StringBuilder(); - for ( Part p : parts ) - { - if ( p.isVariable() ) - { + StringBuilder str = new StringBuilder(); + for (Part p : parts) { + if (p.isVariable()) { Object value = localVariables.get(p.getValue()); - if ( value == null ) - { + if (value == null) { log.debug("Variable not found: " + p.getValue()); - } - else - { + } else { str.append(value); } - } - else - { + } else { str.append(p.getValue()); } } @@ -297,16 +267,14 @@ public String build(ServiceInstance serviceInstance, Map va } @Override - public Iterator iterator() - { + public Iterator iterator() { return Iterators.unmodifiableIterator(parts.iterator()); } /** * @return the parts */ - public List getParts() - { + public List getParts() { return ImmutableList.copyOf(parts); } @@ -315,8 +283,7 @@ public List getParts() * * @param part part to add */ - public void add(Part part) - { + public void add(Part part) { parts.add(part); } @@ -325,28 +292,23 @@ public void add(Part part) * * @param part the part */ - public void remove(Part part) - { + public void remove(Part part) { parts.remove(part); } @SuppressWarnings("RedundantIfStatement") @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; } - UriSpec spec = (UriSpec)o; + UriSpec spec = (UriSpec) o; - if ( !parts.equals(spec.parts) ) - { + if (!parts.equals(spec.parts)) { return false; } @@ -354,13 +316,11 @@ public boolean equals(Object o) } @Override - public int hashCode() - { + public int hashCode() { return parts.hashCode(); } - private Object nullCheck(Object o) - { + private Object nullCheck(Object o) { return (o != null) ? o : ""; } } diff --git a/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/details/DownInstanceManager.java b/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/details/DownInstanceManager.java index c469bbb95..cd124f2e4 100644 --- a/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/details/DownInstanceManager.java +++ b/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/details/DownInstanceManager.java @@ -20,36 +20,30 @@ package org.apache.curator.x.discovery.details; import com.google.common.collect.Maps; - -import org.apache.curator.x.discovery.DownInstancePolicy; -import org.apache.curator.x.discovery.InstanceFilter; -import org.apache.curator.x.discovery.ServiceInstance; - import java.util.Iterator; import java.util.Map.Entry; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; +import org.apache.curator.x.discovery.DownInstancePolicy; +import org.apache.curator.x.discovery.InstanceFilter; +import org.apache.curator.x.discovery.ServiceInstance; -class DownInstanceManager implements InstanceFilter -{ +class DownInstanceManager implements InstanceFilter { private final ConcurrentMap, Status> statuses = Maps.newConcurrentMap(); private final DownInstancePolicy downInstancePolicy; private final AtomicLong lastPurge = new AtomicLong(System.currentTimeMillis()); - private static class Status - { + private static class Status { private final long startMs = System.currentTimeMillis(); private final AtomicInteger errorCount = new AtomicInteger(0); } - DownInstanceManager(DownInstancePolicy downInstancePolicy) - { + DownInstanceManager(DownInstancePolicy downInstancePolicy) { this.downInstancePolicy = downInstancePolicy; } - void add(ServiceInstance instance) - { + void add(ServiceInstance instance) { purge(); Status newStatus = new Status(); @@ -59,35 +53,29 @@ void add(ServiceInstance instance) } @Override - public boolean apply(ServiceInstance instance) - { + public boolean apply(ServiceInstance instance) { purge(); Status status = statuses.get(instance); return (status == null) || (status.errorCount.get() < downInstancePolicy.getErrorThreshold()); } - private void purge() - { + private void purge() { long localLastPurge = lastPurge.get(); long ticksSinceLastPurge = System.currentTimeMillis() - localLastPurge; - if ( ticksSinceLastPurge < (downInstancePolicy.getTimeoutMs() / 2) ) - { + if (ticksSinceLastPurge < (downInstancePolicy.getTimeoutMs() / 2)) { return; } - if ( !lastPurge.compareAndSet(localLastPurge, System.currentTimeMillis()) ) - { + if (!lastPurge.compareAndSet(localLastPurge, System.currentTimeMillis())) { return; } Iterator, Status>> it = statuses.entrySet().iterator(); - while ( it.hasNext() ) - { + while (it.hasNext()) { Entry, Status> entry = it.next(); long elapsedMs = System.currentTimeMillis() - entry.getValue().startMs; - if ( elapsedMs >= downInstancePolicy.getTimeoutMs() ) - { + if (elapsedMs >= downInstancePolicy.getTimeoutMs()) { it.remove(); } } diff --git a/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/details/FilteredInstanceProvider.java b/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/details/FilteredInstanceProvider.java index cfe72e089..10fbaac65 100644 --- a/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/details/FilteredInstanceProvider.java +++ b/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/details/FilteredInstanceProvider.java @@ -23,24 +23,21 @@ import com.google.common.base.Predicates; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; +import java.util.List; import org.apache.curator.x.discovery.InstanceFilter; import org.apache.curator.x.discovery.ServiceInstance; -import java.util.List; -class FilteredInstanceProvider implements InstanceProvider -{ +class FilteredInstanceProvider implements InstanceProvider { private final InstanceProvider instanceProvider; private final Predicate> predicates; - FilteredInstanceProvider(InstanceProvider instanceProvider, List> filters) - { + FilteredInstanceProvider(InstanceProvider instanceProvider, List> filters) { this.instanceProvider = instanceProvider; predicates = Predicates.and(filters); } @Override - public List> getInstances() throws Exception - { + public List> getInstances() throws Exception { Iterable> filtered = Iterables.filter(instanceProvider.getInstances(), predicates); return ImmutableList.copyOf(filtered); } diff --git a/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/details/InstanceProvider.java b/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/details/InstanceProvider.java index 8ff089e9a..1134de88d 100644 --- a/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/details/InstanceProvider.java +++ b/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/details/InstanceProvider.java @@ -19,18 +19,17 @@ package org.apache.curator.x.discovery.details; -import org.apache.curator.x.discovery.ServiceInstance; import java.util.List; +import org.apache.curator.x.discovery.ServiceInstance; /** * Provides a set of available instances for a service so that a strategy can pick one of them */ -public interface InstanceProvider -{ +public interface InstanceProvider { /** * Return the current available set of instances * @return instances * @throws Exception any errors */ - public List> getInstances() throws Exception; + public List> getInstances() throws Exception; } diff --git a/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/details/InstanceSerializer.java b/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/details/InstanceSerializer.java index 879878245..c731791fe 100644 --- a/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/details/InstanceSerializer.java +++ b/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/details/InstanceSerializer.java @@ -24,8 +24,7 @@ /** * Injectable serializer for service instances */ -public interface InstanceSerializer -{ +public interface InstanceSerializer { /** * Serialize an instance into bytes * @@ -33,7 +32,7 @@ public interface InstanceSerializer * @return byte array representing the instance * @throws Exception any errors */ - public byte[] serialize(ServiceInstance instance) throws Exception; + public byte[] serialize(ServiceInstance instance) throws Exception; /** * Deserialize a byte array into an instance diff --git a/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/details/JsonInstanceSerializer.java b/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/details/JsonInstanceSerializer.java index 89086774a..91e9e9060 100644 --- a/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/details/JsonInstanceSerializer.java +++ b/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/details/JsonInstanceSerializer.java @@ -29,8 +29,7 @@ * A serializer that uses Jackson to serialize/deserialize as JSON. IMPORTANT: The instance * payload must support Jackson */ -public class JsonInstanceSerializer implements InstanceSerializer -{ +public class JsonInstanceSerializer implements InstanceSerializer { private final ObjectMapper mapper; private final Class payloadClass; private final boolean compatibleSerializationMode; @@ -47,8 +46,7 @@ public class JsonInstanceSerializer implements InstanceSerializer * * @param payloadClass used to validate payloads when deserializing */ - public JsonInstanceSerializer(Class payloadClass) - { + public JsonInstanceSerializer(Class payloadClass) { this(payloadClass, true, false); } @@ -64,14 +62,13 @@ public JsonInstanceSerializer(Class payloadClass) * @param payloadClass used to validate payloads when deserializing * @param compatibleSerializationMode pass true to serialize in a manner that supports clients pre-CURATOR-275 */ - public JsonInstanceSerializer(Class payloadClass, boolean compatibleSerializationMode) - { + public JsonInstanceSerializer(Class payloadClass, boolean compatibleSerializationMode) { this(payloadClass, compatibleSerializationMode, false); } @VisibleForTesting - JsonInstanceSerializer(Class payloadClass, boolean compatibleSerializationMode, boolean failOnUnknownProperties) - { + JsonInstanceSerializer( + Class payloadClass, boolean compatibleSerializationMode, boolean failOnUnknownProperties) { this.payloadClass = payloadClass; this.compatibleSerializationMode = compatibleSerializationMode; mapper = new ObjectMapper(); @@ -81,19 +78,25 @@ public JsonInstanceSerializer(Class payloadClass, boolean compatibleSerializa @SuppressWarnings({"unchecked"}) @Override - public ServiceInstance deserialize(byte[] bytes) throws Exception - { + public ServiceInstance deserialize(byte[] bytes) throws Exception { ServiceInstance rawServiceInstance = mapper.readValue(bytes, type); payloadClass.cast(rawServiceInstance.getPayload()); // just to verify that it's the correct type - return (ServiceInstance)rawServiceInstance; + return (ServiceInstance) rawServiceInstance; } @Override - public byte[] serialize(ServiceInstance instance) throws Exception - { - if ( compatibleSerializationMode ) - { - OldServiceInstance compatible = new OldServiceInstance(instance.getName(), instance.getId(), instance.getAddress(), instance.getPort(), instance.getSslPort(), instance.getPayload(), instance.getRegistrationTimeUTC(), instance.getServiceType(), instance.getUriSpec()); + public byte[] serialize(ServiceInstance instance) throws Exception { + if (compatibleSerializationMode) { + OldServiceInstance compatible = new OldServiceInstance( + instance.getName(), + instance.getId(), + instance.getAddress(), + instance.getPort(), + instance.getSslPort(), + instance.getPayload(), + instance.getRegistrationTimeUTC(), + instance.getServiceType(), + instance.getUriSpec()); return mapper.writeValueAsBytes(compatible); } return mapper.writeValueAsBytes(instance); diff --git a/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/details/Latch.java b/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/details/Latch.java index 6139380aa..5d584dfbc 100644 --- a/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/details/Latch.java +++ b/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/details/Latch.java @@ -19,20 +19,16 @@ package org.apache.curator.x.discovery.details; -class Latch -{ - private volatile boolean laden = false; +class Latch { + private volatile boolean laden = false; - synchronized void set() - { + synchronized void set() { laden = true; notifyAll(); } - synchronized void await() throws InterruptedException - { - while ( !laden ) - { + synchronized void await() throws InterruptedException { + while (!laden) { wait(); } laden = false; diff --git a/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/details/OldServiceInstance.java b/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/details/OldServiceInstance.java index 2b5f119fe..182b1790c 100644 --- a/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/details/OldServiceInstance.java +++ b/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/details/OldServiceInstance.java @@ -27,8 +27,7 @@ /** * POJO that represents a service instance */ -class OldServiceInstance -{ +class OldServiceInstance { private final String name; private final String id; private final String address; @@ -50,8 +49,16 @@ class OldServiceInstance * @param serviceType type of the service * @param uriSpec the uri spec or null */ - OldServiceInstance(String name, String id, String address, Integer port, Integer sslPort, T payload, long registrationTimeUTC, ServiceType serviceType, UriSpec uriSpec) - { + OldServiceInstance( + String name, + String id, + String address, + Integer port, + Integer sslPort, + T payload, + long registrationTimeUTC, + ServiceType serviceType, + UriSpec uriSpec) { name = Preconditions.checkNotNull(name, "name cannot be null"); id = Preconditions.checkNotNull(id, "id cannot be null"); @@ -66,106 +73,84 @@ class OldServiceInstance this.registrationTimeUTC = registrationTimeUTC; } - OldServiceInstance() - { + OldServiceInstance() { this("", "", null, null, null, null, 0, ServiceType.DYNAMIC, null); } - public String getName() - { + public String getName() { return name; } - public String getId() - { + public String getId() { return id; } - public String getAddress() - { + public String getAddress() { return address; } - public Integer getPort() - { + public Integer getPort() { return port; } - public Integer getSslPort() - { + public Integer getSslPort() { return sslPort; } @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, defaultImpl = Object.class) - public T getPayload() - { + public T getPayload() { return payload; } - public long getRegistrationTimeUTC() - { + public long getRegistrationTimeUTC() { return registrationTimeUTC; } - public ServiceType getServiceType() - { + public ServiceType getServiceType() { return serviceType; } - public UriSpec getUriSpec() - { + public UriSpec getUriSpec() { return uriSpec; } @SuppressWarnings("RedundantIfStatement") @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; } - OldServiceInstance that = (OldServiceInstance)o; + OldServiceInstance that = (OldServiceInstance) o; - if ( registrationTimeUTC != that.registrationTimeUTC ) - { + if (registrationTimeUTC != that.registrationTimeUTC) { return false; } - if ( address != null ? !address.equals(that.address) : that.address != null ) - { + if (address != null ? !address.equals(that.address) : that.address != null) { return false; } - if ( id != null ? !id.equals(that.id) : that.id != null ) - { + if (id != null ? !id.equals(that.id) : that.id != null) { return false; } - if ( name != null ? !name.equals(that.name) : that.name != null ) - { + if (name != null ? !name.equals(that.name) : that.name != null) { return false; } - if ( payload != null ? !payload.equals(that.payload) : that.payload != null ) - { + if (payload != null ? !payload.equals(that.payload) : that.payload != null) { return false; } - if ( port != null ? !port.equals(that.port) : that.port != null ) - { + if (port != null ? !port.equals(that.port) : that.port != null) { return false; } - if ( serviceType != that.serviceType ) - { + if (serviceType != that.serviceType) { return false; } - if ( sslPort != null ? !sslPort.equals(that.sslPort) : that.sslPort != null ) - { + if (sslPort != null ? !sslPort.equals(that.sslPort) : that.sslPort != null) { return false; } - if ( uriSpec != null ? !uriSpec.equals(that.uriSpec) : that.uriSpec != null ) - { + if (uriSpec != null ? !uriSpec.equals(that.uriSpec) : that.uriSpec != null) { return false; } @@ -173,23 +158,23 @@ public boolean equals(Object o) } @Override - public int hashCode() - { + public int hashCode() { int result = name != null ? name.hashCode() : 0; result = 31 * result + (id != null ? id.hashCode() : 0); result = 31 * result + (address != null ? address.hashCode() : 0); result = 31 * result + (port != null ? port.hashCode() : 0); result = 31 * result + (sslPort != null ? sslPort.hashCode() : 0); result = 31 * result + (payload != null ? payload.hashCode() : 0); - result = 31 * result + (int)(registrationTimeUTC ^ (registrationTimeUTC >>> 32)); + result = 31 * result + (int) (registrationTimeUTC ^ (registrationTimeUTC >>> 32)); result = 31 * result + (serviceType != null ? serviceType.hashCode() : 0); result = 31 * result + (uriSpec != null ? uriSpec.hashCode() : 0); return result; } @Override - public String toString() - { - return "ServiceInstance{" + "name='" + name + '\'' + ", id='" + id + '\'' + ", address='" + address + '\'' + ", port=" + port + ", sslPort=" + sslPort + ", payload=" + payload + ", registrationTimeUTC=" + registrationTimeUTC + ", serviceType=" + serviceType + ", uriSpec=" + uriSpec + '}'; + public String toString() { + return "ServiceInstance{" + "name='" + name + '\'' + ", id='" + id + '\'' + ", address='" + address + '\'' + + ", port=" + port + ", sslPort=" + sslPort + ", payload=" + payload + ", registrationTimeUTC=" + + registrationTimeUTC + ", serviceType=" + serviceType + ", uriSpec=" + uriSpec + '}'; } } diff --git a/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/details/ServiceCacheBuilderImpl.java b/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/details/ServiceCacheBuilderImpl.java index 3b006aec9..4ccb6bf0e 100644 --- a/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/details/ServiceCacheBuilderImpl.java +++ b/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/details/ServiceCacheBuilderImpl.java @@ -19,23 +19,21 @@ package org.apache.curator.x.discovery.details; -import org.apache.curator.x.discovery.ServiceCache; -import org.apache.curator.x.discovery.ServiceCacheBuilder; import java.util.concurrent.ExecutorService; import java.util.concurrent.ThreadFactory; +import org.apache.curator.x.discovery.ServiceCache; +import org.apache.curator.x.discovery.ServiceCacheBuilder; /** * Builder for a service cache */ -class ServiceCacheBuilderImpl implements ServiceCacheBuilder -{ +class ServiceCacheBuilderImpl implements ServiceCacheBuilder { private ServiceDiscoveryImpl discovery; private String name; private ThreadFactory threadFactory; private ExecutorService executorService; - ServiceCacheBuilderImpl(ServiceDiscoveryImpl discovery) - { + ServiceCacheBuilderImpl(ServiceDiscoveryImpl discovery) { this.discovery = discovery; } @@ -45,14 +43,10 @@ class ServiceCacheBuilderImpl implements ServiceCacheBuilder * @return service cache */ @Override - public ServiceCache build() - { - if (threadFactory != null) - { + public ServiceCache build() { + if (threadFactory != null) { return new ServiceCacheImpl(discovery, name, threadFactory); - } - else - { + } else { return new ServiceCacheImpl(discovery, name, executorService); } } @@ -64,8 +58,7 @@ public ServiceCache build() * @return this */ @Override - public ServiceCacheBuilder name(String name) - { + public ServiceCacheBuilder name(String name) { this.name = name; return this; } @@ -78,8 +71,7 @@ public ServiceCacheBuilder name(String name) */ @Override @Deprecated - public ServiceCacheBuilder threadFactory(ThreadFactory threadFactory) - { + public ServiceCacheBuilder threadFactory(ThreadFactory threadFactory) { this.threadFactory = threadFactory; this.executorService = null; return this; @@ -92,8 +84,7 @@ public ServiceCacheBuilder threadFactory(ThreadFactory threadFactory) * @return this */ @Override - public ServiceCacheBuilder executorService(ExecutorService executorService) - { + public ServiceCacheBuilder executorService(ExecutorService executorService) { this.executorService = executorService; return this; } diff --git a/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/details/ServiceCacheImpl.java b/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/details/ServiceCacheImpl.java index 6397a395e..6ebd5d2bf 100644 --- a/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/details/ServiceCacheImpl.java +++ b/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/details/ServiceCacheImpl.java @@ -23,6 +23,14 @@ import com.google.common.base.Preconditions; import com.google.common.collect.Lists; import com.google.common.collect.Maps; +import java.util.List; +import java.util.concurrent.ConcurrentMap; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Executor; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.ThreadFactory; +import java.util.concurrent.atomic.AtomicReference; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.EnsureContainers; import org.apache.curator.framework.listen.StandardListenerManager; @@ -36,17 +44,8 @@ import org.apache.curator.utils.ZKPaths; import org.apache.curator.x.discovery.ServiceCache; import org.apache.curator.x.discovery.ServiceInstance; -import java.util.List; -import java.util.concurrent.ConcurrentMap; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.Executor; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.ThreadFactory; -import java.util.concurrent.atomic.AtomicReference; -public class ServiceCacheImpl implements ServiceCache, PathChildrenCacheListener -{ +public class ServiceCacheImpl implements ServiceCache, PathChildrenCacheListener { private final StandardListenerManager listenerContainer = StandardListenerManager.standard(); private final ServiceDiscoveryImpl discovery; private final AtomicReference state = new AtomicReference<>(State.LATENT); @@ -55,24 +54,22 @@ public class ServiceCacheImpl implements ServiceCache, PathChildrenCacheLi private final EnsureContainers ensureContainers; private final CountDownLatch initializedLatch = new CountDownLatch(1); - private enum State - { - LATENT, STARTED, STOPPED + private enum State { + LATENT, + STARTED, + STOPPED } - private static ExecutorService convertThreadFactory(ThreadFactory threadFactory) - { + private static ExecutorService convertThreadFactory(ThreadFactory threadFactory) { Preconditions.checkNotNull(threadFactory, "threadFactory cannot be null"); return Executors.newSingleThreadExecutor(threadFactory); } - ServiceCacheImpl(ServiceDiscoveryImpl discovery, String name, ThreadFactory threadFactory) - { + ServiceCacheImpl(ServiceDiscoveryImpl discovery, String name, ThreadFactory threadFactory) { this(discovery, name, convertThreadFactory(threadFactory)); } - ServiceCacheImpl(ServiceDiscoveryImpl discovery, String name, ExecutorService executorService) - { + ServiceCacheImpl(ServiceDiscoveryImpl discovery, String name, ExecutorService executorService) { Preconditions.checkNotNull(discovery, "discovery cannot be null"); Preconditions.checkNotNull(name, "name cannot be null"); @@ -80,48 +77,44 @@ private static ExecutorService convertThreadFactory(ThreadFactory threadFactory) String path = discovery.pathForName(name); cache = CuratorCache.bridgeBuilder(discovery.getClient(), path) - .withExecutorService(executorService) - .withDataNotCached() - .build(); + .withExecutorService(executorService) + .withDataNotCached() + .build(); CuratorCacheListener listener = CuratorCacheListener.builder() - .forPathChildrenCache(path, discovery.getClient(), this) - .forInitialized(this::initialized) - .build(); + .forPathChildrenCache(path, discovery.getClient(), this) + .forInitialized(this::initialized) + .build(); cache.listenable().addListener(listener); ensureContainers = new EnsureContainers(discovery.getClient(), path); } @Override - public List> getInstances() - { + public List> getInstances() { return Lists.newArrayList(instances.values()); } @VisibleForTesting volatile CountDownLatch debugStartLatch = null; + volatile CountDownLatch debugStartWaitLatch = null; @Override - public void start() throws Exception - { + public void start() throws Exception { startImmediate().await(); } @Override - public CountDownLatch startImmediate() throws Exception - { + public CountDownLatch startImmediate() throws Exception { Preconditions.checkState(state.compareAndSet(State.LATENT, State.STARTED), "Cannot be started more than once"); ensureContainers.ensure(); cache.start(); - if ( debugStartLatch != null ) - { + if (debugStartLatch != null) { initializedLatch.await(); debugStartLatch.countDown(); debugStartLatch = null; } - if ( debugStartWaitLatch != null ) - { + if (debugStartWaitLatch != null) { debugStartWaitLatch.await(); debugStartWaitLatch = null; } @@ -130,11 +123,12 @@ public CountDownLatch startImmediate() throws Exception } @Override - public void close() - { - Preconditions.checkState(state.compareAndSet(State.STARTED, State.STOPPED), "Already closed or has not been started"); + public void close() { + Preconditions.checkState( + state.compareAndSet(State.STARTED, State.STOPPED), "Already closed or has not been started"); - listenerContainer.forEach(l -> discovery.getClient().getConnectionStateListenable().removeListener(l)); + listenerContainer.forEach( + l -> discovery.getClient().getConnectionStateListenable().removeListener(l)); listenerContainer.clear(); CloseableUtils.closeQuietly(cache); @@ -143,75 +137,61 @@ public void close() } @Override - public void addListener(ServiceCacheListener listener) - { + public void addListener(ServiceCacheListener listener) { listenerContainer.addListener(listener); discovery.getClient().getConnectionStateListenable().addListener(listener); } @Override - public void addListener(ServiceCacheListener listener, Executor executor) - { + public void addListener(ServiceCacheListener listener, Executor executor) { listenerContainer.addListener(listener, executor); discovery.getClient().getConnectionStateListenable().addListener(listener, executor); } @Override - public void removeListener(ServiceCacheListener listener) - { + public void removeListener(ServiceCacheListener listener) { listenerContainer.removeListener(listener); discovery.getClient().getConnectionStateListenable().removeListener(listener); } @Override - public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) - { + public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) { boolean notifyListeners = false; - switch ( event.getType() ) - { - case CHILD_ADDED: - case CHILD_UPDATED: - { - addInstance(event.getData()); - notifyListeners = true; - break; + switch (event.getType()) { + case CHILD_ADDED: + case CHILD_UPDATED: { + addInstance(event.getData()); + notifyListeners = true; + break; + } + + case CHILD_REMOVED: { + instances.remove(instanceIdFromData(event.getData())); + notifyListeners = true; + break; + } } - case CHILD_REMOVED: - { - instances.remove(instanceIdFromData(event.getData())); - notifyListeners = true; - break; - } - } - - if ( notifyListeners && (initializedLatch.getCount() == 0) ) - { + if (notifyListeners && (initializedLatch.getCount() == 0)) { listenerContainer.forEach(ServiceCacheListener::cacheChanged); } } - private String instanceIdFromData(ChildData childData) - { + private String instanceIdFromData(ChildData childData) { return ZKPaths.getNodeFromPath(childData.getPath()); } - private void addInstance(ChildData childData) - { - try - { + private void addInstance(ChildData childData) { + try { String instanceId = instanceIdFromData(childData); ServiceInstance serviceInstance = discovery.getSerializer().deserialize(childData.getData()); instances.put(instanceId, serviceInstance); - } - catch ( Exception e ) - { + } catch (Exception e) { throw new RuntimeException(e); } } - private void initialized() - { + private void initialized() { discovery.cacheOpened(this); initializedLatch.countDown(); } diff --git a/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/details/ServiceCacheListener.java b/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/details/ServiceCacheListener.java index 234a676ac..d6a07b9af 100644 --- a/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/details/ServiceCacheListener.java +++ b/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/details/ServiceCacheListener.java @@ -24,8 +24,7 @@ /** * Listener for changes to a service cache */ -public interface ServiceCacheListener extends ConnectionStateListener -{ +public interface ServiceCacheListener extends ConnectionStateListener { /** * Called when the cache has changed (instances added/deleted, etc.) */ diff --git a/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/details/ServiceDiscoveryImpl.java b/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/details/ServiceDiscoveryImpl.java index f52de4f37..c711e4436 100644 --- a/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/details/ServiceDiscoveryImpl.java +++ b/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/details/ServiceDiscoveryImpl.java @@ -25,6 +25,10 @@ import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; +import java.io.IOException; +import java.util.Collection; +import java.util.List; +import java.util.concurrent.ConcurrentMap; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.recipes.cache.CuratorCache; import org.apache.curator.framework.recipes.cache.CuratorCacheBridge; @@ -47,56 +51,43 @@ import org.apache.zookeeper.Watcher; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.io.IOException; -import java.util.Collection; -import java.util.List; -import java.util.concurrent.ConcurrentMap; /** * A mechanism to register and query service instances using ZooKeeper */ @SuppressWarnings("SynchronizationOnLocalVariableOrMethodParameter") -public class ServiceDiscoveryImpl implements ServiceDiscovery -{ +public class ServiceDiscoveryImpl implements ServiceDiscovery { private final Logger log = LoggerFactory.getLogger(getClass()); private final CuratorFramework client; private final String basePath; private final InstanceSerializer serializer; private final ConcurrentMap> services = Maps.newConcurrentMap(); - private final Collection> caches = Sets.newSetFromMap(Maps., Boolean>newConcurrentMap()); - private final Collection> providers = Sets.newSetFromMap(Maps., Boolean>newConcurrentMap()); + private final Collection> caches = + Sets.newSetFromMap(Maps., Boolean>newConcurrentMap()); + private final Collection> providers = + Sets.newSetFromMap(Maps., Boolean>newConcurrentMap()); private final boolean watchInstances; - private final ConnectionStateListener connectionStateListener = new ConnectionStateListener() - { + private final ConnectionStateListener connectionStateListener = new ConnectionStateListener() { @Override - public void stateChanged(CuratorFramework client, ConnectionState newState) - { - if ( (newState == ConnectionState.RECONNECTED) || (newState == ConnectionState.CONNECTED) ) - { - try - { + public void stateChanged(CuratorFramework client, ConnectionState newState) { + if ((newState == ConnectionState.RECONNECTED) || (newState == ConnectionState.CONNECTED)) { + try { log.debug("Re-registering due to reconnection"); reRegisterServices(); - } - catch (InterruptedException ex) - { + } catch (InterruptedException ex) { Thread.currentThread().interrupt(); - } - catch ( Exception e ) - { + } catch (Exception e) { log.error("Could not re-register instances after reconnection", e); } } } }; - private static class Entry - { + private static class Entry { private volatile ServiceInstance service; private volatile CuratorCacheBridge cache; - private Entry(ServiceInstance service) - { + private Entry(ServiceInstance service) { this.service = service; } } @@ -108,14 +99,17 @@ private Entry(ServiceInstance service) * @param thisInstance instance that represents the service that is running. The instance will get auto-registered * @param watchInstances if true, watches for changes to locally registered instances */ - public ServiceDiscoveryImpl(CuratorFramework client, String basePath, InstanceSerializer serializer, ServiceInstance thisInstance, boolean watchInstances) - { + public ServiceDiscoveryImpl( + CuratorFramework client, + String basePath, + InstanceSerializer serializer, + ServiceInstance thisInstance, + boolean watchInstances) { this.watchInstances = watchInstances; this.client = Preconditions.checkNotNull(client, "client cannot be null"); this.basePath = Preconditions.checkNotNull(basePath, "basePath cannot be null"); this.serializer = Preconditions.checkNotNull(serializer, "serializer cannot be null"); - if ( thisInstance != null ) - { + if (thisInstance != null) { Entry entry = new Entry(thisInstance); entry.cache = makeNodeCache(thisInstance); services.put(thisInstance.getId(), entry); @@ -128,40 +122,28 @@ public ServiceDiscoveryImpl(CuratorFramework client, String basePath, InstanceSe * @throws Exception errors */ @Override - public void start() throws Exception - { - try - { + public void start() throws Exception { + try { reRegisterServices(); - } - catch ( KeeperException e ) - { + } catch (KeeperException e) { log.error("Could not register instances - will try again later", e); } client.getConnectionStateListenable().addListener(connectionStateListener); } @Override - public void close() throws IOException - { + public void close() throws IOException { ExceptionAccumulator accumulator = new ExceptionAccumulator(); - for ( ServiceProvider provider : Lists.newArrayList(providers) ) - { + for (ServiceProvider provider : Lists.newArrayList(providers)) { CloseableUtils.closeQuietly(provider); } - for ( Entry entry : services.values() ) - { - try - { + for (Entry entry : services.values()) { + try { internalUnregisterService(entry); - } - catch ( KeeperException.NoNodeException ignore ) - { + } catch (KeeperException.NoNodeException ignore) { // ignore - } - catch ( Exception e ) - { + } catch (Exception e) { accumulator.add(e); log.error("Could not unregister instance: " + entry.service.getName(), e); } @@ -178,14 +160,12 @@ public void close() throws IOException * @throws Exception errors */ @Override - public void registerService(ServiceInstance service) throws Exception - { + public void registerService(ServiceInstance service) throws Exception { Entry newEntry = new Entry(service); Entry oldEntry = services.putIfAbsent(service.getId(), newEntry); Entry useEntry = (oldEntry != null) ? oldEntry : newEntry; - synchronized(useEntry) - { - if ( useEntry == newEntry ) // i.e. is new + synchronized (useEntry) { + if (useEntry == newEntry) // i.e. is new { useEntry.cache = makeNodeCache(service); } @@ -194,15 +174,12 @@ public void registerService(ServiceInstance service) throws Exception } @Override - public void updateService(final ServiceInstance service) throws Exception - { + public void updateService(final ServiceInstance service) throws Exception { Entry entry = services.get(service.getId()); - if ( entry == null ) - { + if (entry == null) { throw new Exception("Service not registered: " + service); } - synchronized(entry) - { + synchronized (entry) { entry.service = service; byte[] bytes = serializer.serialize(service); String path = pathForInstance(service.getName(), service.getId()); @@ -211,35 +188,33 @@ public void updateService(final ServiceInstance service) throws Exception } @VisibleForTesting - protected void internalRegisterService(ServiceInstance service) throws Exception - { + protected void internalRegisterService(ServiceInstance service) throws Exception { byte[] bytes = serializer.serialize(service); String path = pathForInstance(service.getName(), service.getId()); final int MAX_TRIES = 2; boolean isDone = false; - for ( int i = 0; !isDone && (i < MAX_TRIES); ++i ) - { - try - { - CreateMode mode; - switch (service.getServiceType()) { - case DYNAMIC: - mode = CreateMode.EPHEMERAL; - break; - case DYNAMIC_SEQUENTIAL: - mode = CreateMode.EPHEMERAL_SEQUENTIAL; - break; - default: - mode = CreateMode.PERSISTENT; - break; - } - client.create().creatingParentContainersIfNeeded().withMode(mode).forPath(path, bytes); + for (int i = 0; !isDone && (i < MAX_TRIES); ++i) { + try { + CreateMode mode; + switch (service.getServiceType()) { + case DYNAMIC: + mode = CreateMode.EPHEMERAL; + break; + case DYNAMIC_SEQUENTIAL: + mode = CreateMode.EPHEMERAL_SEQUENTIAL; + break; + default: + mode = CreateMode.PERSISTENT; + break; + } + client.create() + .creatingParentContainersIfNeeded() + .withMode(mode) + .forPath(path, bytes); isDone = true; - } - catch ( KeeperException.NodeExistsException e ) - { - client.delete().forPath(path); // must delete then re-create so that watchers fire + } catch (KeeperException.NodeExistsException e) { + client.delete().forPath(path); // must delete then re-create so that watchers fire } } } @@ -251,8 +226,7 @@ protected void internalRegisterService(ServiceInstance service) throws Except * @throws Exception errors */ @Override - public void unregisterService(ServiceInstance service) throws Exception - { + public void unregisterService(ServiceInstance service) throws Exception { Entry entry = services.remove(service.getId()); internalUnregisterService(entry); } @@ -263,11 +237,10 @@ public void unregisterService(ServiceInstance service) throws Exception * @return the builder */ @Override - public ServiceProviderBuilder serviceProviderBuilder() - { + public ServiceProviderBuilder serviceProviderBuilder() { return new ServiceProviderBuilderImpl(this) - .providerStrategy(new RoundRobinStrategy()) - .threadFactory(ThreadUtils.newThreadFactory("ServiceProvider")); + .providerStrategy(new RoundRobinStrategy()) + .threadFactory(ThreadUtils.newThreadFactory("ServiceProvider")); } /** @@ -276,8 +249,7 @@ public ServiceProviderBuilder serviceProviderBuilder() * @return new cache builder */ @Override - public ServiceCacheBuilder serviceCacheBuilder() - { + public ServiceCacheBuilder serviceCacheBuilder() { return new ServiceCacheBuilderImpl(this); } @@ -288,8 +260,7 @@ public ServiceCacheBuilder serviceCacheBuilder() * @throws Exception errors */ @Override - public Collection queryForNames() throws Exception - { + public Collection queryForNames() throws Exception { List names = client.getChildren().forPath(basePath); return ImmutableList.copyOf(names); } @@ -302,8 +273,7 @@ public Collection queryForNames() throws Exception * @throws Exception errors */ @Override - public Collection> queryForInstances(String name) throws Exception - { + public Collection> queryForInstances(String name) throws Exception { return queryForInstances(name, null); } @@ -316,83 +286,63 @@ public Collection> queryForInstances(String name) throws Exce * @throws Exception errors */ @Override - public ServiceInstance queryForInstance(String name, String id) throws Exception - { + public ServiceInstance queryForInstance(String name, String id) throws Exception { String path = pathForInstance(name, id); - try - { + try { byte[] bytes = client.getData().forPath(path); return serializer.deserialize(bytes); - } - catch ( KeeperException.NoNodeException ignore ) - { + } catch (KeeperException.NoNodeException ignore) { // ignore } return null; } - void cacheOpened(ServiceCache cache) - { + void cacheOpened(ServiceCache cache) { caches.add(cache); } - void cacheClosed(ServiceCache cache) - { + void cacheClosed(ServiceCache cache) { caches.remove(cache); } - void providerOpened(ServiceProvider provider) - { + void providerOpened(ServiceProvider provider) { providers.add(provider); } - void providerClosed(ServiceProvider cache) - { + void providerClosed(ServiceProvider cache) { providers.remove(cache); } - CuratorFramework getClient() - { + CuratorFramework getClient() { return client; } - String pathForName(String name) - { + String pathForName(String name) { return ZKPaths.makePath(basePath, name); } - InstanceSerializer getSerializer() - { + InstanceSerializer getSerializer() { return serializer; } - List> queryForInstances(String name, Watcher watcher) throws Exception - { + List> queryForInstances(String name, Watcher watcher) throws Exception { ImmutableList.Builder> builder = ImmutableList.builder(); String path = pathForName(name); List instanceIds; - if ( watcher != null ) - { + if (watcher != null) { instanceIds = getChildrenWatched(path, watcher, true); - } - else - { - try - { + } else { + try { instanceIds = client.getChildren().forPath(path); - } - catch ( KeeperException.NoNodeException e ) - { + } catch (KeeperException.NoNodeException e) { instanceIds = Lists.newArrayList(); } } - for ( String id : instanceIds ) - { + for (String id : instanceIds) { ServiceInstance instance = queryForInstance(name, id); - if ( instance != null ) - { + if (instance != null) { builder.add(instance); } } @@ -400,34 +350,23 @@ List> queryForInstances(String name, Watcher watcher) throws } @VisibleForTesting - int debugServicesQty() - { + int debugServicesQty() { return services.size(); } - private List getChildrenWatched(String path, Watcher watcher, boolean recurse) throws Exception - { + private List getChildrenWatched(String path, Watcher watcher, boolean recurse) throws Exception { List instanceIds; - try - { + try { instanceIds = client.getChildren().usingWatcher(watcher).forPath(path); - } - catch ( KeeperException.NoNodeException e ) - { - if ( recurse ) - { - try - { + } catch (KeeperException.NoNodeException e) { + if (recurse) { + try { client.create().creatingParentContainersIfNeeded().forPath(path); - } - catch ( KeeperException.NodeExistsException ignore ) - { + } catch (KeeperException.NodeExistsException ignore) { // ignore } instanceIds = getChildrenWatched(path, watcher, false); - } - else - { + } else { throw e; } } @@ -435,92 +374,71 @@ private List getChildrenWatched(String path, Watcher watcher, boolean re } @VisibleForTesting - String pathForInstance(String name, String id) - { + String pathForInstance(String name, String id) { return ZKPaths.makePath(pathForName(name), id); } @VisibleForTesting - ServiceInstance getRegisteredService(String id) - { + ServiceInstance getRegisteredService(String id) { Entry entry = services.get(id); return (entry != null) ? entry.service : null; } - private void reRegisterServices() throws Exception - { - for ( final Entry entry : services.values() ) - { - synchronized(entry) - { + private void reRegisterServices() throws Exception { + for (final Entry entry : services.values()) { + synchronized (entry) { internalRegisterService(entry.service); } } } - private CuratorCacheBridge makeNodeCache(final ServiceInstance instance) - { - if ( !watchInstances ) - { + private CuratorCacheBridge makeNodeCache(final ServiceInstance instance) { + if (!watchInstances) { return null; } - CuratorCacheBridge cache = CuratorCache.bridgeBuilder(client, pathForInstance(instance.getName(), instance.getId())) - .withOptions(CuratorCache.Options.SINGLE_NODE_CACHE) - .withDataNotCached() - .build(); + CuratorCacheBridge cache = CuratorCache.bridgeBuilder( + client, pathForInstance(instance.getName(), instance.getId())) + .withOptions(CuratorCache.Options.SINGLE_NODE_CACHE) + .withDataNotCached() + .build(); CuratorCacheListener listener = CuratorCacheListener.builder() - .afterInitialized() - .forAll((__, ___, data) -> { - if ( data != null ) - { - try - { - ServiceInstance newInstance = serializer.deserialize(data.getData()); - Entry entry = services.get(newInstance.getId()); - if ( entry != null ) - { - synchronized(entry) - { - entry.service = newInstance; + .afterInitialized() + .forAll((__, ___, data) -> { + if (data != null) { + try { + ServiceInstance newInstance = serializer.deserialize(data.getData()); + Entry entry = services.get(newInstance.getId()); + if (entry != null) { + synchronized (entry) { + entry.service = newInstance; + } } + } catch (Exception e) { + log.debug("Could not deserialize: " + data.getPath()); } + } else { + log.warn("Instance data has been deleted for: " + instance); } - catch ( Exception e ) - { - log.debug("Could not deserialize: " + data.getPath()); - } - } - else - { - log.warn("Instance data has been deleted for: " + instance); - } - }) - .build(); + }) + .build(); cache.listenable().addListener(listener); cache.start(); return cache; } - private void internalUnregisterService(final Entry entry) throws Exception - { - if ( entry != null ) - { - synchronized(entry) - { - if ( entry.cache != null ) - { + private void internalUnregisterService(final Entry entry) throws Exception { + if (entry != null) { + synchronized (entry) { + if (entry.cache != null) { CloseableUtils.closeQuietly(entry.cache); entry.cache = null; } String path = pathForInstance(entry.service.getName(), entry.service.getId()); - try - { + try { client.delete().guaranteed().forPath(path); - } - catch ( KeeperException.NoNodeException ignore ) - { + } catch (KeeperException.NoNodeException ignore) { // ignore } } diff --git a/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/details/ServiceProviderBuilderImpl.java b/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/details/ServiceProviderBuilderImpl.java index c7246a6a0..9781114f3 100644 --- a/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/details/ServiceProviderBuilderImpl.java +++ b/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/details/ServiceProviderBuilderImpl.java @@ -20,21 +20,20 @@ package org.apache.curator.x.discovery.details; import com.google.common.collect.Lists; +import java.util.List; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.ThreadFactory; import org.apache.curator.x.discovery.DownInstancePolicy; import org.apache.curator.x.discovery.InstanceFilter; import org.apache.curator.x.discovery.ProviderStrategy; import org.apache.curator.x.discovery.ServiceProvider; import org.apache.curator.x.discovery.ServiceProviderBuilder; import org.apache.curator.x.discovery.strategies.RoundRobinStrategy; -import java.util.List; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.ThreadFactory; /** * Builder for service providers */ -class ServiceProviderBuilderImpl implements ServiceProviderBuilder -{ +class ServiceProviderBuilderImpl implements ServiceProviderBuilder { private ServiceDiscoveryImpl discovery; private String serviceName; private ProviderStrategy providerStrategy; @@ -43,13 +42,12 @@ class ServiceProviderBuilderImpl implements ServiceProviderBuilder private List> filters = Lists.newArrayList(); private DownInstancePolicy downInstancePolicy = new DownInstancePolicy(); - public ServiceProvider build() - { - return new ServiceProviderImpl(discovery, serviceName, providerStrategy, threadFactory, executorService, filters, downInstancePolicy); + public ServiceProvider build() { + return new ServiceProviderImpl( + discovery, serviceName, providerStrategy, threadFactory, executorService, filters, downInstancePolicy); } - ServiceProviderBuilderImpl(ServiceDiscoveryImpl discovery) - { + ServiceProviderBuilderImpl(ServiceDiscoveryImpl discovery) { this.discovery = discovery; } @@ -60,8 +58,7 @@ public ServiceProvider build() * @return this */ @Override - public ServiceProviderBuilder serviceName(String serviceName) - { + public ServiceProviderBuilder serviceName(String serviceName) { this.serviceName = serviceName; return this; } @@ -73,8 +70,7 @@ public ServiceProviderBuilder serviceName(String serviceName) * @return this */ @Override - public ServiceProviderBuilder providerStrategy(ProviderStrategy providerStrategy) - { + public ServiceProviderBuilder providerStrategy(ProviderStrategy providerStrategy) { this.providerStrategy = providerStrategy; return this; } @@ -87,30 +83,26 @@ public ServiceProviderBuilder providerStrategy(ProviderStrategy providerSt */ @Override @Deprecated - public ServiceProviderBuilder threadFactory(ThreadFactory threadFactory) - { + public ServiceProviderBuilder threadFactory(ThreadFactory threadFactory) { this.threadFactory = threadFactory; this.executorService = null; return this; } @Override - public ServiceProviderBuilder downInstancePolicy(DownInstancePolicy downInstancePolicy) - { + public ServiceProviderBuilder downInstancePolicy(DownInstancePolicy downInstancePolicy) { this.downInstancePolicy = downInstancePolicy; return this; } @Override - public ServiceProviderBuilder additionalFilter(InstanceFilter filter) - { + public ServiceProviderBuilder additionalFilter(InstanceFilter filter) { filters.add(filter); return this; } @Override - public ServiceProviderBuilder executorService(ExecutorService executorService) - { + public ServiceProviderBuilder executorService(ExecutorService executorService) { this.executorService = executorService; this.threadFactory = null; return this; diff --git a/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/details/ServiceProviderImpl.java b/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/details/ServiceProviderImpl.java index 76ed51c4a..b4ee2812d 100644 --- a/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/details/ServiceProviderImpl.java +++ b/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/details/ServiceProviderImpl.java @@ -20,6 +20,12 @@ package org.apache.curator.x.discovery.details; import com.google.common.collect.Lists; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.ThreadFactory; import org.apache.curator.x.discovery.DownInstancePolicy; import org.apache.curator.x.discovery.InstanceFilter; import org.apache.curator.x.discovery.ProviderStrategy; @@ -27,42 +33,44 @@ import org.apache.curator.x.discovery.ServiceCacheBuilder; import org.apache.curator.x.discovery.ServiceInstance; import org.apache.curator.x.discovery.ServiceProvider; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.ThreadFactory; /** * The main interface for Service Discovery. Encapsulates the discovery service for a particular * named service along with a provider strategy. */ -public class ServiceProviderImpl implements ServiceProvider -{ +public class ServiceProviderImpl implements ServiceProvider { private final ServiceCache cache; private final InstanceProvider instanceProvider; private final ServiceDiscoveryImpl discovery; private final ProviderStrategy providerStrategy; private final DownInstanceManager downInstanceManager; - public ServiceProviderImpl(ServiceDiscoveryImpl discovery, String serviceName, ProviderStrategy providerStrategy, ThreadFactory threadFactory, List> filters, DownInstancePolicy downInstancePolicy) - { + public ServiceProviderImpl( + ServiceDiscoveryImpl discovery, + String serviceName, + ProviderStrategy providerStrategy, + ThreadFactory threadFactory, + List> filters, + DownInstancePolicy downInstancePolicy) { this(discovery, serviceName, providerStrategy, threadFactory, null, filters, downInstancePolicy); } - protected ServiceProviderImpl(ServiceDiscoveryImpl discovery, String serviceName, ProviderStrategy providerStrategy, ThreadFactory threadFactory, ExecutorService executorService, List> filters, DownInstancePolicy downInstancePolicy) - { + protected ServiceProviderImpl( + ServiceDiscoveryImpl discovery, + String serviceName, + ProviderStrategy providerStrategy, + ThreadFactory threadFactory, + ExecutorService executorService, + List> filters, + DownInstancePolicy downInstancePolicy) { this.discovery = discovery; this.providerStrategy = providerStrategy; downInstanceManager = new DownInstanceManager<>(downInstancePolicy); final ServiceCacheBuilder builder = discovery.serviceCacheBuilder().name(serviceName); - if (executorService != null) - { + if (executorService != null) { builder.executorService(executorService); - } else - { + } else { //noinspection deprecation builder.threadFactory(threadFactory); } @@ -80,8 +88,7 @@ protected ServiceProviderImpl(ServiceDiscoveryImpl discovery, String serviceN * @throws Exception any errors */ @Override - public void start() throws Exception - { + public void start() throws Exception { cache.start(); discovery.providerOpened(this); } @@ -90,8 +97,7 @@ public void start() throws Exception * {@inheritDoc} */ @Override - public void close() throws IOException - { + public void close() throws IOException { discovery.providerClosed(this); cache.close(); } @@ -104,8 +110,7 @@ public void close() throws IOException * @throws Exception any errors */ @Override - public Collection> getAllInstances() throws Exception - { + public Collection> getAllInstances() throws Exception { return instanceProvider.getInstances(); } @@ -117,14 +122,12 @@ public Collection> getAllInstances() throws Exception * @throws Exception any errors */ @Override - public ServiceInstance getInstance() throws Exception - { + public ServiceInstance getInstance() throws Exception { return providerStrategy.getInstance(instanceProvider); } @Override - public void noteError(ServiceInstance instance) - { + public void noteError(ServiceInstance instance) { downInstanceManager.add(instance); } } diff --git a/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/strategies/RandomStrategy.java b/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/strategies/RandomStrategy.java index 2d9d76226..cca5ca2a7 100644 --- a/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/strategies/RandomStrategy.java +++ b/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/strategies/RandomStrategy.java @@ -19,28 +19,25 @@ package org.apache.curator.x.discovery.strategies; -import org.apache.curator.x.discovery.details.InstanceProvider; -import org.apache.curator.x.discovery.ProviderStrategy; -import org.apache.curator.x.discovery.ServiceInstance; import java.util.List; import java.util.Random; +import org.apache.curator.x.discovery.ProviderStrategy; +import org.apache.curator.x.discovery.ServiceInstance; +import org.apache.curator.x.discovery.details.InstanceProvider; /** * This strategy always picks a random instance from the list */ -public class RandomStrategy implements ProviderStrategy -{ - private final Random random = new Random(); +public class RandomStrategy implements ProviderStrategy { + private final Random random = new Random(); @Override - public ServiceInstance getInstance(InstanceProvider instanceProvider) throws Exception - { - List> instances = instanceProvider.getInstances(); - if ( instances.size() == 0 ) - { + public ServiceInstance getInstance(InstanceProvider instanceProvider) throws Exception { + List> instances = instanceProvider.getInstances(); + if (instances.size() == 0) { return null; } - int thisIndex = random.nextInt(instances.size()); + int thisIndex = random.nextInt(instances.size()); return instances.get(thisIndex); } } diff --git a/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/strategies/RoundRobinStrategy.java b/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/strategies/RoundRobinStrategy.java index 4d7924f2a..246da28c3 100644 --- a/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/strategies/RoundRobinStrategy.java +++ b/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/strategies/RoundRobinStrategy.java @@ -19,28 +19,25 @@ package org.apache.curator.x.discovery.strategies; -import org.apache.curator.x.discovery.details.InstanceProvider; -import org.apache.curator.x.discovery.ProviderStrategy; -import org.apache.curator.x.discovery.ServiceInstance; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; +import org.apache.curator.x.discovery.ProviderStrategy; +import org.apache.curator.x.discovery.ServiceInstance; +import org.apache.curator.x.discovery.details.InstanceProvider; /** * This strategy rotates sequentially through the list of instances */ -public class RoundRobinStrategy implements ProviderStrategy -{ - private final AtomicInteger index = new AtomicInteger(0); +public class RoundRobinStrategy implements ProviderStrategy { + private final AtomicInteger index = new AtomicInteger(0); @Override - public ServiceInstance getInstance(InstanceProvider instanceProvider) throws Exception - { - List> instances = instanceProvider.getInstances(); - if ( instances.size() == 0 ) - { + public ServiceInstance getInstance(InstanceProvider instanceProvider) throws Exception { + List> instances = instanceProvider.getInstances(); + if (instances.size() == 0) { return null; } - int thisIndex = Math.abs(index.getAndIncrement()); + int thisIndex = Math.abs(index.getAndIncrement()); return instances.get(thisIndex % instances.size()); } } diff --git a/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/strategies/StickyStrategy.java b/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/strategies/StickyStrategy.java index aa927dadc..e884a119a 100644 --- a/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/strategies/StickyStrategy.java +++ b/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/strategies/StickyStrategy.java @@ -19,60 +19,49 @@ package org.apache.curator.x.discovery.strategies; -import org.apache.curator.x.discovery.ProviderStrategy; -import org.apache.curator.x.discovery.ServiceInstance; -import org.apache.curator.x.discovery.details.InstanceProvider; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; +import org.apache.curator.x.discovery.ProviderStrategy; +import org.apache.curator.x.discovery.ServiceInstance; +import org.apache.curator.x.discovery.details.InstanceProvider; /** * This strategy uses a master strategy to pick the initial instance. Once picked, * that instance is always returned. If, however, the currently selected instance * is no longer in the list, the master strategy is used to pick a new instance. */ -public class StickyStrategy implements ProviderStrategy -{ - private final ProviderStrategy masterStrategy; - private final AtomicReference> ourInstance = new AtomicReference>(null); - private final AtomicInteger instanceNumber = new AtomicInteger(-1); +public class StickyStrategy implements ProviderStrategy { + private final ProviderStrategy masterStrategy; + private final AtomicReference> ourInstance = new AtomicReference>(null); + private final AtomicInteger instanceNumber = new AtomicInteger(-1); /** * @param masterStrategy the strategy to use for picking the sticky instance */ - public StickyStrategy(ProviderStrategy masterStrategy) - { + public StickyStrategy(ProviderStrategy masterStrategy) { this.masterStrategy = masterStrategy; } @Override - public ServiceInstance getInstance(InstanceProvider instanceProvider) throws Exception - { - final List> instances = instanceProvider.getInstances(); + public ServiceInstance getInstance(InstanceProvider instanceProvider) throws Exception { + final List> instances = instanceProvider.getInstances(); { - ServiceInstance localOurInstance = ourInstance.get(); - if ( !instances.contains(localOurInstance) ) - { + ServiceInstance localOurInstance = ourInstance.get(); + if (!instances.contains(localOurInstance)) { ourInstance.compareAndSet(localOurInstance, null); } } - - if ( ourInstance.get() == null ) - { - ServiceInstance instance = masterStrategy.getInstance - ( - new InstanceProvider() - { - @Override - public List> getInstances() throws Exception - { - return instances; - } + + if (ourInstance.get() == null) { + ServiceInstance instance = masterStrategy.getInstance(new InstanceProvider() { + @Override + public List> getInstances() throws Exception { + return instances; } - ); - if ( ourInstance.compareAndSet(null, instance) ) - { + }); + if (ourInstance.compareAndSet(null, instance)) { instanceNumber.incrementAndGet(); } } @@ -86,8 +75,7 @@ public List> getInstances() throws Exception * * @return instance number */ - public int getInstanceNumber() - { + public int getInstanceNumber() { return instanceNumber.get(); } } diff --git a/curator-x-discovery/src/test/java/org/apache/curator/x/discovery/ServiceCacheLeakTester.java b/curator-x-discovery/src/test/java/org/apache/curator/x/discovery/ServiceCacheLeakTester.java index 89eda56f7..ef202f78a 100644 --- a/curator-x-discovery/src/test/java/org/apache/curator/x/discovery/ServiceCacheLeakTester.java +++ b/curator-x-discovery/src/test/java/org/apache/curator/x/discovery/ServiceCacheLeakTester.java @@ -29,15 +29,13 @@ import org.junit.jupiter.api.Tag; @Tag(CuratorTestBase.zk35TestCompatibilityGroup) -public class ServiceCacheLeakTester -{ - public static void main(String[] args) throws Exception - { +public class ServiceCacheLeakTester { + public static void main(String[] args) throws Exception { TestingServer testingServer = new TestingServer(); - final CuratorFramework curatorFramework = CuratorFrameworkFactory.newClient(testingServer.getConnectString(), new RetryOneTime(1)); - try - { + final CuratorFramework curatorFramework = + CuratorFrameworkFactory.newClient(testingServer.getConnectString(), new RetryOneTime(1)); + try { curatorFramework.start(); doWork(curatorFramework); @@ -45,37 +43,39 @@ public static void main(String[] args) throws Exception System.out.println("Done - get dump"); Thread.currentThread().join(); - } - finally - { + } finally { CloseableUtils.closeQuietly(curatorFramework); CloseableUtils.closeQuietly(testingServer); } } - private static void doWork(CuratorFramework curatorFramework) throws Exception - { - ServiceInstance thisInstance = ServiceInstance.builder().name("myservice").build(); - final ServiceDiscovery serviceDiscovery = ServiceDiscoveryBuilder.builder(Void.class).client(curatorFramework.usingNamespace("dev")).basePath("/instances").thisInstance(thisInstance).build(); + private static void doWork(CuratorFramework curatorFramework) throws Exception { + ServiceInstance thisInstance = + ServiceInstance.builder().name("myservice").build(); + final ServiceDiscovery serviceDiscovery = ServiceDiscoveryBuilder.builder(Void.class) + .client(curatorFramework.usingNamespace("dev")) + .basePath("/instances") + .thisInstance(thisInstance) + .build(); serviceDiscovery.start(); - for ( int i = 0; i < 100000; i++ ) - { + for (int i = 0; i < 100000; i++) { final ServiceProvider s = serviceProvider(serviceDiscovery, "myservice"); s.start(); - try - { + try { s.getInstance().buildUriSpec(); - } - finally - { + } finally { s.close(); } } } - private static ServiceProvider serviceProvider(ServiceDiscovery serviceDiscovery, String name) throws Exception - { - return serviceDiscovery.serviceProviderBuilder().serviceName(name).providerStrategy(new RandomStrategy()).build(); + private static ServiceProvider serviceProvider(ServiceDiscovery serviceDiscovery, String name) + throws Exception { + return serviceDiscovery + .serviceProviderBuilder() + .serviceName(name) + .providerStrategy(new RandomStrategy()) + .build(); } -} \ No newline at end of file +} diff --git a/curator-x-discovery/src/test/java/org/apache/curator/x/discovery/TestJsonInstanceSerializer.java b/curator-x-discovery/src/test/java/org/apache/curator/x/discovery/TestJsonInstanceSerializer.java index b44e4fa89..4d11cdfcc 100644 --- a/curator-x-discovery/src/test/java/org/apache/curator/x/discovery/TestJsonInstanceSerializer.java +++ b/curator-x-discovery/src/test/java/org/apache/curator/x/discovery/TestJsonInstanceSerializer.java @@ -29,16 +29,15 @@ import org.apache.curator.x.discovery.details.JsonInstanceSerializer; import org.junit.jupiter.api.Test; -public class TestJsonInstanceSerializer -{ +public class TestJsonInstanceSerializer { @Test - public void testBasic() throws Exception - { - JsonInstanceSerializer serializer = new JsonInstanceSerializer(String.class); - ServiceInstance instance = new ServiceInstance("name", "id", "address", 10, 20, "payload", 0, ServiceType.DYNAMIC, new UriSpec("{a}/b/{c}"), true); - byte[] bytes = serializer.serialize(instance); + public void testBasic() throws Exception { + JsonInstanceSerializer serializer = new JsonInstanceSerializer(String.class); + ServiceInstance instance = new ServiceInstance( + "name", "id", "address", 10, 20, "payload", 0, ServiceType.DYNAMIC, new UriSpec("{a}/b/{c}"), true); + byte[] bytes = serializer.serialize(instance); - ServiceInstance rhs = serializer.deserialize(bytes); + ServiceInstance rhs = serializer.deserialize(bytes); assertEquals(instance, rhs); assertEquals(instance.getId(), rhs.getId()); assertEquals(instance.getName(), rhs.getName()); @@ -51,31 +50,28 @@ public void testBasic() throws Exception } @Test - public void testWrongPayloadType() throws Exception - { - JsonInstanceSerializer stringSerializer = new JsonInstanceSerializer(String.class); - JsonInstanceSerializer doubleSerializer = new JsonInstanceSerializer(Double.class); - - byte[] bytes = stringSerializer.serialize(new ServiceInstance("name", "id", "address", 10, 20, "payload", 0, ServiceType.DYNAMIC, new UriSpec("{a}/b/{c}"), true)); - try - { + public void testWrongPayloadType() throws Exception { + JsonInstanceSerializer stringSerializer = new JsonInstanceSerializer(String.class); + JsonInstanceSerializer doubleSerializer = new JsonInstanceSerializer(Double.class); + + byte[] bytes = stringSerializer.serialize(new ServiceInstance( + "name", "id", "address", 10, 20, "payload", 0, ServiceType.DYNAMIC, new UriSpec("{a}/b/{c}"), true)); + try { doubleSerializer.deserialize(bytes); fail(); - } - catch ( ClassCastException e ) - { + } catch (ClassCastException e) { // correct } } @Test - public void testNoPayload() throws Exception - { - JsonInstanceSerializer serializer = new JsonInstanceSerializer(Void.class); - ServiceInstance instance = new ServiceInstance("name", "id", "address", 10, 20, null, 0, ServiceType.DYNAMIC, new UriSpec("{a}/b/{c}"), true); - byte[] bytes = serializer.serialize(instance); + public void testNoPayload() throws Exception { + JsonInstanceSerializer serializer = new JsonInstanceSerializer(Void.class); + ServiceInstance instance = new ServiceInstance( + "name", "id", "address", 10, 20, null, 0, ServiceType.DYNAMIC, new UriSpec("{a}/b/{c}"), true); + byte[] bytes = serializer.serialize(instance); - ServiceInstance rhs = serializer.deserialize(bytes); + ServiceInstance rhs = serializer.deserialize(bytes); assertEquals(instance, rhs); assertEquals(instance.getId(), rhs.getId()); assertEquals(instance.getName(), rhs.getName()); @@ -88,26 +84,25 @@ public void testNoPayload() throws Exception } @Test - public void testNoEnabledState() throws Exception - { - JsonInstanceSerializer serializer = new JsonInstanceSerializer(Void.class); - byte[] bytes = "{}".getBytes("utf-8"); + public void testNoEnabledState() throws Exception { + JsonInstanceSerializer serializer = new JsonInstanceSerializer(Void.class); + byte[] bytes = "{}".getBytes("utf-8"); - ServiceInstance instance = serializer.deserialize(bytes); + ServiceInstance instance = serializer.deserialize(bytes); assertTrue(instance.isEnabled(), "Instance that has no 'enabled' should be assumed enabled"); } @Test - public void testPayloadAsList() throws Exception - { - JsonInstanceSerializer serializer = new JsonInstanceSerializer(Object.class, false); + public void testPayloadAsList() throws Exception { + JsonInstanceSerializer serializer = new JsonInstanceSerializer(Object.class, false); List payload = new ArrayList(); payload.add("Test value 1"); payload.add("Test value 2"); - ServiceInstance instance = new ServiceInstance("name", "id", "address", 10, 20, payload, 0, ServiceType.DYNAMIC, new UriSpec("{a}/b/{c}"), false); - byte[] bytes = serializer.serialize(instance); + ServiceInstance instance = new ServiceInstance( + "name", "id", "address", 10, 20, payload, 0, ServiceType.DYNAMIC, new UriSpec("{a}/b/{c}"), false); + byte[] bytes = serializer.serialize(instance); - ServiceInstance rhs = serializer.deserialize(bytes); + ServiceInstance rhs = serializer.deserialize(bytes); assertEquals(instance, rhs); assertEquals(instance.getId(), rhs.getId()); assertEquals(instance.getName(), rhs.getName()); @@ -119,18 +114,17 @@ public void testPayloadAsList() throws Exception assertEquals(instance.isEnabled(), rhs.isEnabled()); } - @Test - public void testPayloadAsMap() throws Exception - { - JsonInstanceSerializer serializer = new JsonInstanceSerializer(Object.class, false); - Map payload = new HashMap(); + public void testPayloadAsMap() throws Exception { + JsonInstanceSerializer serializer = new JsonInstanceSerializer(Object.class, false); + Map payload = new HashMap(); payload.put("1", "Test value 1"); payload.put("2", "Test value 2"); - ServiceInstance instance = new ServiceInstance("name", "id", "address", 10, 20, payload, 0, ServiceType.DYNAMIC, new UriSpec("{a}/b/{c}"), false); - byte[] bytes = serializer.serialize(instance); + ServiceInstance instance = new ServiceInstance( + "name", "id", "address", 10, 20, payload, 0, ServiceType.DYNAMIC, new UriSpec("{a}/b/{c}"), false); + byte[] bytes = serializer.serialize(instance); - ServiceInstance rhs = serializer.deserialize(bytes); + ServiceInstance rhs = serializer.deserialize(bytes); assertEquals(instance, rhs); assertEquals(instance.getId(), rhs.getId()); assertEquals(instance.getName(), rhs.getName()); @@ -143,15 +137,15 @@ public void testPayloadAsMap() throws Exception } @Test - public void testPayloadClass() throws Exception - { - JsonInstanceSerializer serializer = new JsonInstanceSerializer(Payload.class); + public void testPayloadClass() throws Exception { + JsonInstanceSerializer serializer = new JsonInstanceSerializer(Payload.class); Payload payload = new Payload(); payload.setVal("Test value"); - ServiceInstance instance = new ServiceInstance("name", "id", "address", 10, 20, payload, 0, ServiceType.DYNAMIC, new UriSpec("{a}/b/{c}"), true); - byte[] bytes = serializer.serialize(instance); + ServiceInstance instance = new ServiceInstance( + "name", "id", "address", 10, 20, payload, 0, ServiceType.DYNAMIC, new UriSpec("{a}/b/{c}"), true); + byte[] bytes = serializer.serialize(instance); - ServiceInstance rhs = serializer.deserialize(bytes); + ServiceInstance rhs = serializer.deserialize(bytes); assertEquals(instance, rhs); assertEquals(instance.getId(), rhs.getId()); assertEquals(instance.getName(), rhs.getName()); @@ -164,30 +158,28 @@ public void testPayloadClass() throws Exception } public static class Payload { - private String val; - public String getVal() { - return val; - } + private String val; - public Payload() - { + public String getVal() { + return val; } - public Payload(String val) - { + public Payload() {} + + public Payload(String val) { this.val = val; } public void setVal(String val) { - this.val = val; - } - @Override - public boolean equals(Object other) { - if (other == null || !(other instanceof Payload)) return false; - String otherVal = ((Payload)other).getVal(); - if (val == null) return val == otherVal; - return val.equals(otherVal); - } - } + this.val = val; + } + @Override + public boolean equals(Object other) { + if (other == null || !(other instanceof Payload)) return false; + String otherVal = ((Payload) other).getVal(); + if (val == null) return val == otherVal; + return val.equals(otherVal); + } + } } diff --git a/curator-x-discovery/src/test/java/org/apache/curator/x/discovery/TestLocalIpFilter.java b/curator-x-discovery/src/test/java/org/apache/curator/x/discovery/TestLocalIpFilter.java index fd4c8008b..9014822b2 100644 --- a/curator-x-discovery/src/test/java/org/apache/curator/x/discovery/TestLocalIpFilter.java +++ b/curator-x-discovery/src/test/java/org/apache/curator/x/discovery/TestLocalIpFilter.java @@ -22,37 +22,27 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import com.google.common.collect.Lists; -import org.junit.jupiter.api.Test; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.util.List; +import org.junit.jupiter.api.Test; -public class TestLocalIpFilter -{ +public class TestLocalIpFilter { @Test - public void testFilterEverything() throws SocketException - { + public void testFilterEverything() throws SocketException { LocalIpFilter localIpFilter = ServiceInstanceBuilder.getLocalIpFilter(); - try - { - ServiceInstanceBuilder.setLocalIpFilter - ( - new LocalIpFilter() - { - @Override - public boolean use(NetworkInterface networkInterface, InetAddress address) throws SocketException - { - return false; - } - } - ); + try { + ServiceInstanceBuilder.setLocalIpFilter(new LocalIpFilter() { + @Override + public boolean use(NetworkInterface networkInterface, InetAddress address) throws SocketException { + return false; + } + }); List allLocalIPs = Lists.newArrayList(ServiceInstanceBuilder.getAllLocalIPs()); assertEquals(allLocalIPs.size(), 0); - } - finally - { + } finally { ServiceInstanceBuilder.setLocalIpFilter(localIpFilter); } diff --git a/curator-x-discovery/src/test/java/org/apache/curator/x/discovery/TestServiceCache.java b/curator-x-discovery/src/test/java/org/apache/curator/x/discovery/TestServiceCache.java index 6feedb6e7..8f5d7f7ed 100644 --- a/curator-x-discovery/src/test/java/org/apache/curator/x/discovery/TestServiceCache.java +++ b/curator-x-discovery/src/test/java/org/apache/curator/x/discovery/TestServiceCache.java @@ -23,6 +23,14 @@ import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import com.google.common.collect.Lists; +import java.io.Closeable; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Executors; +import java.util.concurrent.Semaphore; +import java.util.concurrent.TimeUnit; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.state.ConnectionState; @@ -37,287 +45,306 @@ import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; -import java.io.Closeable; -import java.util.Collection; -import java.util.Collections; -import java.util.List; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.Executors; -import java.util.concurrent.Semaphore; -import java.util.concurrent.TimeUnit; - @Tag(CuratorTestBase.zk35TestCompatibilityGroup) -public class TestServiceCache extends BaseClassForTests -{ +public class TestServiceCache extends BaseClassForTests { @Test - public void testInitialLoad() throws Exception - { + public void testInitialLoad() throws Exception { List closeables = Lists.newArrayList(); - try - { + try { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); closeables.add(client); client.start(); - ServiceDiscovery discovery = ServiceDiscoveryBuilder.builder(String.class).basePath("/discovery").client(client).build(); + ServiceDiscovery discovery = ServiceDiscoveryBuilder.builder(String.class) + .basePath("/discovery") + .client(client) + .build(); closeables.add(discovery); discovery.start(); - ServiceCache cache = discovery.serviceCacheBuilder().name("test").build(); + ServiceCache cache = + discovery.serviceCacheBuilder().name("test").build(); closeables.add(cache); final CountDownLatch latch = new CountDownLatch(3); - ServiceCacheListener listener = new ServiceCacheListener() - { + ServiceCacheListener listener = new ServiceCacheListener() { @Override - public void cacheChanged() - { + public void cacheChanged() { latch.countDown(); } @Override - public void stateChanged(CuratorFramework client, ConnectionState newState) - { - } + public void stateChanged(CuratorFramework client, ConnectionState newState) {} }; cache.addListener(listener); cache.start(); - ServiceInstance instance1 = ServiceInstance.builder().payload("test").name("test").port(10064).build(); - ServiceInstance instance2 = ServiceInstance.builder().payload("test").name("test").port(10065).build(); - ServiceInstance instance3 = ServiceInstance.builder().payload("test").name("test").port(10066).build(); + ServiceInstance instance1 = ServiceInstance.builder() + .payload("test") + .name("test") + .port(10064) + .build(); + ServiceInstance instance2 = ServiceInstance.builder() + .payload("test") + .name("test") + .port(10065) + .build(); + ServiceInstance instance3 = ServiceInstance.builder() + .payload("test") + .name("test") + .port(10066) + .build(); discovery.registerService(instance1); discovery.registerService(instance2); discovery.registerService(instance3); assertTrue(latch.await(10, TimeUnit.SECONDS)); - ServiceCache cache2 = discovery.serviceCacheBuilder().name("test").build(); + ServiceCache cache2 = + discovery.serviceCacheBuilder().name("test").build(); closeables.add(cache2); cache2.start(); assertEquals(cache2.getInstances().size(), 3); - } - finally - { + } finally { Collections.reverse(closeables); - for ( Closeable c : closeables ) - { + for (Closeable c : closeables) { CloseableUtils.closeQuietly(c); } } } @Test - public void testViaProvider() throws Exception - { + public void testViaProvider() throws Exception { Timing timing = new Timing(); List closeables = Lists.newArrayList(); - try - { + try { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); closeables.add(client); client.start(); - ServiceDiscovery discovery = ServiceDiscoveryBuilder.builder(String.class).basePath("/discovery").client(client).build(); + ServiceDiscovery discovery = ServiceDiscoveryBuilder.builder(String.class) + .basePath("/discovery") + .client(client) + .build(); closeables.add(discovery); discovery.start(); - ServiceProvider serviceProvider = discovery.serviceProviderBuilder().serviceName("test").build(); + ServiceProvider serviceProvider = + discovery.serviceProviderBuilder().serviceName("test").build(); closeables.add(serviceProvider); serviceProvider.start(); - ServiceInstance instance = ServiceInstance.builder().payload("thing").name("test").port(10064).build(); + ServiceInstance instance = ServiceInstance.builder() + .payload("thing") + .name("test") + .port(10064) + .build(); discovery.registerService(instance); int count = 0; ServiceInstance foundInstance = null; - while ( foundInstance == null ) - { + while (foundInstance == null) { assertTrue(count++ < 5); foundInstance = serviceProvider.getInstance(); timing.sleepABit(); } assertEquals(foundInstance, instance); - ServiceInstance instance2 = ServiceInstance.builder().address("foo").payload("thing").name("test").port(10064).build(); + ServiceInstance instance2 = ServiceInstance.builder() + .address("foo") + .payload("thing") + .name("test") + .port(10064) + .build(); discovery.registerService(instance2); timing.sleepABit(); Collection> allInstances = serviceProvider.getAllInstances(); assertEquals(allInstances.size(), 2); - } - finally - { + } finally { Collections.reverse(closeables); - for ( Closeable c : closeables ) - { + for (Closeable c : closeables) { CloseableUtils.closeQuietly(c); } } } @Test - public void testUpdate() throws Exception - { + public void testUpdate() throws Exception { List closeables = Lists.newArrayList(); - try - { + try { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); closeables.add(client); client.start(); - ServiceInstance instance = ServiceInstance.builder().payload("thing").name("test").port(10064).build(); - ServiceDiscovery discovery = ServiceDiscoveryBuilder.builder(String.class).basePath("/test").client(client).thisInstance(instance).build(); + ServiceInstance instance = ServiceInstance.builder() + .payload("thing") + .name("test") + .port(10064) + .build(); + ServiceDiscovery discovery = ServiceDiscoveryBuilder.builder(String.class) + .basePath("/test") + .client(client) + .thisInstance(instance) + .build(); closeables.add(discovery); discovery.start(); final CountDownLatch latch = new CountDownLatch(1); - ServiceCache cache = discovery.serviceCacheBuilder().name("test").build(); + ServiceCache cache = + discovery.serviceCacheBuilder().name("test").build(); closeables.add(cache); - ServiceCacheListener listener = new ServiceCacheListener() - { + ServiceCacheListener listener = new ServiceCacheListener() { @Override - public void cacheChanged() - { + public void cacheChanged() { latch.countDown(); } @Override - public void stateChanged(CuratorFramework client, ConnectionState newState) - { - } + public void stateChanged(CuratorFramework client, ConnectionState newState) {} }; cache.addListener(listener); cache.start(); - instance = ServiceInstance.builder().payload("changed").name("test").port(10064).id(instance.getId()).build(); + instance = ServiceInstance.builder() + .payload("changed") + .name("test") + .port(10064) + .id(instance.getId()) + .build(); discovery.updateService(instance); assertTrue(latch.await(10, TimeUnit.SECONDS)); assertEquals(cache.getInstances().size(), 1); assertEquals(cache.getInstances().get(0).getPayload(), instance.getPayload()); - } - finally - { + } finally { Collections.reverse(closeables); - for ( Closeable c : closeables ) - { + for (Closeable c : closeables) { CloseableUtils.closeQuietly(c); } } } @Test - public void testCache() throws Exception - { + public void testCache() throws Exception { List closeables = Lists.newArrayList(); - try - { + try { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); closeables.add(client); client.start(); - ServiceDiscovery discovery = ServiceDiscoveryBuilder.builder(String.class).basePath("/discovery").client(client).build(); + ServiceDiscovery discovery = ServiceDiscoveryBuilder.builder(String.class) + .basePath("/discovery") + .client(client) + .build(); closeables.add(discovery); discovery.start(); - ServiceCache cache = discovery.serviceCacheBuilder().name("test").build(); + ServiceCache cache = + discovery.serviceCacheBuilder().name("test").build(); closeables.add(cache); cache.start(); final Semaphore semaphore = new Semaphore(0); - ServiceCacheListener listener = new ServiceCacheListener() - { + ServiceCacheListener listener = new ServiceCacheListener() { @Override - public void cacheChanged() - { + public void cacheChanged() { semaphore.release(); } @Override - public void stateChanged(CuratorFramework client, ConnectionState newState) - { - } + public void stateChanged(CuratorFramework client, ConnectionState newState) {} }; cache.addListener(listener); - ServiceInstance instance1 = ServiceInstance.builder().payload("thing").name("test").port(10064).build(); - ServiceInstance instance2 = ServiceInstance.builder().payload("thing").name("test").port(10065).build(); + ServiceInstance instance1 = ServiceInstance.builder() + .payload("thing") + .name("test") + .port(10064) + .build(); + ServiceInstance instance2 = ServiceInstance.builder() + .payload("thing") + .name("test") + .port(10065) + .build(); discovery.registerService(instance1); assertTrue(semaphore.tryAcquire(10, TimeUnit.SECONDS)); discovery.registerService(instance2); assertTrue(semaphore.tryAcquire(3, TimeUnit.SECONDS)); - ServiceInstance instance3 = ServiceInstance.builder().payload("thing").name("another").port(10064).build(); + ServiceInstance instance3 = ServiceInstance.builder() + .payload("thing") + .name("another") + .port(10064) + .build(); discovery.registerService(instance3); - assertFalse(semaphore.tryAcquire(3, TimeUnit.SECONDS)); // should not get called for a different service - } - finally - { + assertFalse(semaphore.tryAcquire(3, TimeUnit.SECONDS)); // should not get called for a different service + } finally { Collections.reverse(closeables); - for ( Closeable c : closeables ) - { + for (Closeable c : closeables) { CloseableUtils.closeQuietly(c); } } } @Test - public void testExecutorServiceIsInvoked() throws Exception - { - if ( Compatibility.hasPersistentWatchers() ) - { + public void testExecutorServiceIsInvoked() throws Exception { + if (Compatibility.hasPersistentWatchers()) { return; // for ZK 3.6 the underlying cache ignores the executor } List closeables = Lists.newArrayList(); - try - { + try { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); closeables.add(client); client.start(); - ServiceDiscovery discovery = ServiceDiscoveryBuilder.builder(String.class).basePath("/discovery").client(client).build(); + ServiceDiscovery discovery = ServiceDiscoveryBuilder.builder(String.class) + .basePath("/discovery") + .client(client) + .build(); closeables.add(discovery); discovery.start(); - ExecuteCalledWatchingExecutorService exec = new ExecuteCalledWatchingExecutorService(Executors.newSingleThreadExecutor()); + ExecuteCalledWatchingExecutorService exec = + new ExecuteCalledWatchingExecutorService(Executors.newSingleThreadExecutor()); assertFalse(exec.isExecuteCalled()); - ServiceCache cache = discovery.serviceCacheBuilder().name("test").executorService(exec).build(); + ServiceCache cache = discovery + .serviceCacheBuilder() + .name("test") + .executorService(exec) + .build(); closeables.add(cache); cache.start(); final Semaphore semaphore = new Semaphore(0); - ServiceCacheListener listener = new ServiceCacheListener() - { + ServiceCacheListener listener = new ServiceCacheListener() { @Override - public void cacheChanged() - { + public void cacheChanged() { semaphore.release(); } @Override - public void stateChanged(CuratorFramework client, ConnectionState newState) - { - } + public void stateChanged(CuratorFramework client, ConnectionState newState) {} }; cache.addListener(listener); - ServiceInstance instance1 = ServiceInstance.builder().payload("thing").name("test").port(10064).build(); + ServiceInstance instance1 = ServiceInstance.builder() + .payload("thing") + .name("test") + .port(10064) + .build(); discovery.registerService(instance1); assertTrue(semaphore.tryAcquire(10, TimeUnit.SECONDS)); assertTrue(exec.isExecuteCalled()); - } - finally - { + } finally { Collections.reverse(closeables); - for ( Closeable c : closeables ) - { + for (Closeable c : closeables) { CloseableUtils.closeQuietly(c); } } diff --git a/curator-x-discovery/src/test/java/org/apache/curator/x/discovery/TestStrategies.java b/curator-x-discovery/src/test/java/org/apache/curator/x/discovery/TestStrategies.java index 2e9cb86d1..b3d902b8a 100644 --- a/curator-x-discovery/src/test/java/org/apache/curator/x/discovery/TestStrategies.java +++ b/curator-x-discovery/src/test/java/org/apache/curator/x/discovery/TestStrategies.java @@ -23,100 +23,89 @@ import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import com.google.common.collect.Lists; +import java.util.List; +import org.apache.commons.math.stat.descriptive.SummaryStatistics; import org.apache.curator.x.discovery.details.InstanceProvider; import org.apache.curator.x.discovery.strategies.RandomStrategy; import org.apache.curator.x.discovery.strategies.RoundRobinStrategy; import org.apache.curator.x.discovery.strategies.StickyStrategy; -import org.apache.commons.math.stat.descriptive.SummaryStatistics; import org.junit.jupiter.api.Test; -import java.util.List; -public class TestStrategies -{ - private static class TestInstanceProvider implements InstanceProvider - { - private final List> instances; +public class TestStrategies { + private static class TestInstanceProvider implements InstanceProvider { + private final List> instances; - private TestInstanceProvider(int qty) throws Exception - { + private TestInstanceProvider(int qty) throws Exception { this(qty, 0); } - private TestInstanceProvider(int qty, int startingAt) throws Exception - { + private TestInstanceProvider(int qty, int startingAt) throws Exception { instances = Lists.newArrayList(); - for ( int i = 0; i < qty; ++i ) - { + for (int i = 0; i < qty; ++i) { ServiceInstanceBuilder builder = ServiceInstance.builder(); - instances.add(builder.id(Integer.toString(i + startingAt)).name("foo").build()); + instances.add( + builder.id(Integer.toString(i + startingAt)).name("foo").build()); } } @Override - public List> getInstances() throws Exception - { + public List> getInstances() throws Exception { return instances; } } @Test - public void testRandom() throws Exception - { - final int QTY = 10; - final int ITERATIONS = 1000; - - TestInstanceProvider instanceProvider = new TestInstanceProvider(QTY, 0); - ProviderStrategy strategy = new RandomStrategy(); - - long[] counts = new long[QTY]; - for ( int i = 0; i < ITERATIONS; ++i ) - { - ServiceInstance instance = strategy.getInstance(instanceProvider); - int id = Integer.parseInt(instance.getId()); + public void testRandom() throws Exception { + final int QTY = 10; + final int ITERATIONS = 1000; + + TestInstanceProvider instanceProvider = new TestInstanceProvider(QTY, 0); + ProviderStrategy strategy = new RandomStrategy(); + + long[] counts = new long[QTY]; + for (int i = 0; i < ITERATIONS; ++i) { + ServiceInstance instance = strategy.getInstance(instanceProvider); + int id = Integer.parseInt(instance.getId()); counts[id]++; } - SummaryStatistics statistic = new SummaryStatistics(); - for ( int i = 0; i < QTY; ++i ) - { + SummaryStatistics statistic = new SummaryStatistics(); + for (int i = 0; i < QTY; ++i) { statistic.addValue(counts[i]); } - assertTrue(statistic.getStandardDeviation() <= (QTY * 2), "" + statistic.getStandardDeviation()); // meager check for even distribution + assertTrue( + statistic.getStandardDeviation() <= (QTY * 2), + "" + statistic.getStandardDeviation()); // meager check for even distribution } @Test - public void testRoundRobin() throws Exception - { - final int QTY = 10; + public void testRoundRobin() throws Exception { + final int QTY = 10; - TestInstanceProvider instanceProvider = new TestInstanceProvider(QTY); - ProviderStrategy strategy = new RoundRobinStrategy(); + TestInstanceProvider instanceProvider = new TestInstanceProvider(QTY); + ProviderStrategy strategy = new RoundRobinStrategy(); - for ( int i = 0; i < QTY; ++i ) - { + for (int i = 0; i < QTY; ++i) { ServiceInstance instance = strategy.getInstance(instanceProvider); assertEquals(instance.getId(), Integer.toString(i)); } - for ( int i = 0; i < (1234 * QTY); ++i ) - { + for (int i = 0; i < (1234 * QTY); ++i) { ServiceInstance instance = strategy.getInstance(instanceProvider); assertEquals(instance.getId(), Integer.toString(i % QTY)); } } @Test - public void testSticky() throws Exception - { - final int QTY = 10; + public void testSticky() throws Exception { + final int QTY = 10; - TestInstanceProvider instanceProvider = new TestInstanceProvider(QTY); - StickyStrategy strategy = new StickyStrategy(new RandomStrategy()); + TestInstanceProvider instanceProvider = new TestInstanceProvider(QTY); + StickyStrategy strategy = new StickyStrategy(new RandomStrategy()); - ServiceInstance theInstance = strategy.getInstance(instanceProvider); - int instanceNumber = strategy.getInstanceNumber(); - for ( int i = 0; i < 1000; ++i ) - { + ServiceInstance theInstance = strategy.getInstance(instanceProvider); + int instanceNumber = strategy.getInstanceNumber(); + for (int i = 0; i < 1000; ++i) { assertEquals(strategy.getInstance(instanceProvider), theInstance); } @@ -126,8 +115,7 @@ public void testSticky() throws Exception assertFalse(instanceNumber == strategy.getInstanceNumber()); theInstance = strategy.getInstance(instanceProvider); - for ( int i = 0; i < 1000; ++i ) - { + for (int i = 0; i < 1000; ++i) { assertEquals(strategy.getInstance(instanceProvider), theInstance); } } diff --git a/curator-x-discovery/src/test/java/org/apache/curator/x/discovery/TestUriSpec.java b/curator-x-discovery/src/test/java/org/apache/curator/x/discovery/TestUriSpec.java index bedcc6159..fdeb05184 100644 --- a/curator-x-discovery/src/test/java/org/apache/curator/x/discovery/TestUriSpec.java +++ b/curator-x-discovery/src/test/java/org/apache/curator/x/discovery/TestUriSpec.java @@ -21,22 +21,20 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import com.google.common.collect.Maps; -import org.junit.jupiter.api.Test; import java.util.Iterator; import java.util.Map; +import org.junit.jupiter.api.Test; -public class TestUriSpec -{ +public class TestUriSpec { @Test - public void testScheme() - { - UriSpec spec = new UriSpec("{scheme}://foo.com"); + public void testScheme() { + UriSpec spec = new UriSpec("{scheme}://foo.com"); - ServiceInstanceBuilder builder = new ServiceInstanceBuilder(); + ServiceInstanceBuilder builder = new ServiceInstanceBuilder(); builder.id("x"); builder.name("foo"); builder.port(5); - ServiceInstance instance = builder.build(); + ServiceInstance instance = builder.build(); assertEquals(spec.build(instance), "http://foo.com"); builder.sslPort(5); @@ -45,9 +43,8 @@ public void testScheme() } @Test - public void testFromInstance() - { - ServiceInstanceBuilder builder = new ServiceInstanceBuilder(); + public void testFromInstance() { + ServiceInstanceBuilder builder = new ServiceInstanceBuilder(); builder.address("1.2.3.4"); builder.name("foo"); builder.id("bar"); @@ -55,20 +52,20 @@ public void testFromInstance() builder.sslPort(6); builder.registrationTimeUTC(789); builder.serviceType(ServiceType.PERMANENT); - ServiceInstance instance = builder.build(); + ServiceInstance instance = builder.build(); - UriSpec spec = new UriSpec("{scheme}://{address}:{port}:{ssl-port}/{name}/{id}/{registration-time-utc}/{service-type}"); + UriSpec spec = new UriSpec( + "{scheme}://{address}:{port}:{ssl-port}/{name}/{id}/{registration-time-utc}/{service-type}"); - Map m = Maps.newHashMap(); + Map m = Maps.newHashMap(); m.put("scheme", "test"); assertEquals(spec.build(instance, m), "test://1.2.3.4:5:6/foo/bar/789/permanent"); } @Test - public void testEscapes() - { - UriSpec spec = new UriSpec("{one}two-three-{[}four{]}-five{six}"); - Iterator iterator = spec.iterator(); + public void testEscapes() { + UriSpec spec = new UriSpec("{one}two-three-{[}four{]}-five{six}"); + Iterator iterator = spec.iterator(); checkPart(iterator.next(), "one", true); checkPart(iterator.next(), "two-three-", false); checkPart(iterator.next(), "[", true); @@ -77,17 +74,16 @@ public void testEscapes() checkPart(iterator.next(), "-five", false); checkPart(iterator.next(), "six", true); - Map m = Maps.newHashMap(); + Map m = Maps.newHashMap(); m.put("one", 1); m.put("six", 6); assertEquals(spec.build(m), "1two-three-{four}-five6"); } @Test - public void testBasic() - { - UriSpec spec = new UriSpec("{one}{two}three-four-five{six}seven{eight}"); - Iterator iterator = spec.iterator(); + public void testBasic() { + UriSpec spec = new UriSpec("{one}{two}three-four-five{six}seven{eight}"); + Iterator iterator = spec.iterator(); checkPart(iterator.next(), "one", true); checkPart(iterator.next(), "two", true); checkPart(iterator.next(), "three-four-five", false); @@ -96,8 +92,7 @@ public void testBasic() checkPart(iterator.next(), "eight", true); } - private void checkPart(UriSpec.Part p, String value, boolean isVariable) - { + private void checkPart(UriSpec.Part p, String value, boolean isVariable) { assertEquals(p.getValue(), value); assertEquals(p.isVariable(), isVariable); } diff --git a/curator-x-discovery/src/test/java/org/apache/curator/x/discovery/details/TestDownInstanceManager.java b/curator-x-discovery/src/test/java/org/apache/curator/x/discovery/details/TestDownInstanceManager.java index aca6e5276..3617f9173 100644 --- a/curator-x-discovery/src/test/java/org/apache/curator/x/discovery/details/TestDownInstanceManager.java +++ b/curator-x-discovery/src/test/java/org/apache/curator/x/discovery/details/TestDownInstanceManager.java @@ -21,21 +21,22 @@ import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; +import java.util.concurrent.TimeUnit; import org.apache.curator.x.discovery.DownInstancePolicy; import org.apache.curator.x.discovery.ServiceInstance; import org.junit.jupiter.api.Test; -import java.util.concurrent.TimeUnit; -public class TestDownInstanceManager -{ +public class TestDownInstanceManager { private static final DownInstancePolicy debugDownInstancePolicy = new DownInstancePolicy(1, TimeUnit.SECONDS, 1); - private static final DownInstancePolicy debugMultiDownInstancePolicy = new DownInstancePolicy(1, TimeUnit.SECONDS, 2); + private static final DownInstancePolicy debugMultiDownInstancePolicy = + new DownInstancePolicy(1, TimeUnit.SECONDS, 2); @Test - public void testBasic() throws Exception - { - ServiceInstance instance1 = ServiceInstance.builder().name("hey").id("1").build(); - ServiceInstance instance2 = ServiceInstance.builder().name("hey").id("2").build(); + public void testBasic() throws Exception { + ServiceInstance instance1 = + ServiceInstance.builder().name("hey").id("1").build(); + ServiceInstance instance2 = + ServiceInstance.builder().name("hey").id("2").build(); DownInstanceManager downInstanceManager = new DownInstanceManager(debugDownInstancePolicy); assertTrue(downInstanceManager.apply(instance1)); @@ -47,10 +48,11 @@ public void testBasic() throws Exception } @Test - public void testThreshold() throws Exception - { - ServiceInstance instance1 = ServiceInstance.builder().name("hey").id("1").build(); - ServiceInstance instance2 = ServiceInstance.builder().name("hey").id("2").build(); + public void testThreshold() throws Exception { + ServiceInstance instance1 = + ServiceInstance.builder().name("hey").id("1").build(); + ServiceInstance instance2 = + ServiceInstance.builder().name("hey").id("2").build(); DownInstanceManager downInstanceManager = new DownInstanceManager(debugMultiDownInstancePolicy); assertTrue(downInstanceManager.apply(instance1)); @@ -66,10 +68,11 @@ public void testThreshold() throws Exception } @Test - public void testExpiration() throws Exception - { - ServiceInstance instance1 = ServiceInstance.builder().name("hey").id("1").build(); - ServiceInstance instance2 = ServiceInstance.builder().name("hey").id("2").build(); + public void testExpiration() throws Exception { + ServiceInstance instance1 = + ServiceInstance.builder().name("hey").id("1").build(); + ServiceInstance instance2 = + ServiceInstance.builder().name("hey").id("2").build(); DownInstanceManager downInstanceManager = new DownInstanceManager(debugDownInstancePolicy); diff --git a/curator-x-discovery/src/test/java/org/apache/curator/x/discovery/details/TestJsonInstanceSerializerCompatibility.java b/curator-x-discovery/src/test/java/org/apache/curator/x/discovery/details/TestJsonInstanceSerializerCompatibility.java index 560e2f6d7..44ca0bf84 100644 --- a/curator-x-discovery/src/test/java/org/apache/curator/x/discovery/details/TestJsonInstanceSerializerCompatibility.java +++ b/curator-x-discovery/src/test/java/org/apache/curator/x/discovery/details/TestJsonInstanceSerializerCompatibility.java @@ -24,45 +24,79 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.ObjectMapper; +import java.net.URI; +import java.util.Date; import org.apache.curator.x.discovery.ServiceInstance; import org.apache.curator.x.discovery.ServiceType; import org.apache.curator.x.discovery.TestJsonInstanceSerializer; import org.apache.curator.x.discovery.UriSpec; import org.junit.jupiter.api.Test; -import java.net.URI; -import java.util.Date; -public class TestJsonInstanceSerializerCompatibility -{ +public class TestJsonInstanceSerializerCompatibility { @Test - public void testCompatibilityMode() throws Exception - { - JsonInstanceSerializer serializer = new JsonInstanceSerializer(TestJsonInstanceSerializer.Payload.class, true, true); - ServiceInstance instance = new ServiceInstance("name", "id", "address", 10, 20, new TestJsonInstanceSerializer.Payload("test"), 0, ServiceType.DYNAMIC, new UriSpec("{a}/b/{c}"), true); + public void testCompatibilityMode() throws Exception { + JsonInstanceSerializer serializer = new JsonInstanceSerializer< + TestJsonInstanceSerializer.Payload>(TestJsonInstanceSerializer.Payload.class, true, true); + ServiceInstance instance = + new ServiceInstance( + "name", + "id", + "address", + 10, + 20, + new TestJsonInstanceSerializer.Payload("test"), + 0, + ServiceType.DYNAMIC, + new UriSpec("{a}/b/{c}"), + true); byte[] bytes = serializer.serialize(instance); - OldServiceInstance oldInstance = new OldServiceInstance("name", "id", "address", 10, 20, new TestJsonInstanceSerializer.Payload("test"), 0, ServiceType.DYNAMIC, new UriSpec("{a}/b/{c}")); + OldServiceInstance oldInstance = + new OldServiceInstance( + "name", + "id", + "address", + 10, + 20, + new TestJsonInstanceSerializer.Payload("test"), + 0, + ServiceType.DYNAMIC, + new UriSpec("{a}/b/{c}")); ObjectMapper mapper = new ObjectMapper(); byte[] oldBytes = mapper.writeValueAsBytes(oldInstance); assertArrayEquals(bytes, oldBytes, String.format("%s vs %s", new String(bytes), new String(oldBytes))); } @Test - public void testBackwardCompatibility() throws Exception - { - JsonInstanceSerializer serializer = new JsonInstanceSerializer(TestJsonInstanceSerializer.Payload.class, true, true); - ServiceInstance instance = new ServiceInstance("name", "id", "address", 10, 20, new TestJsonInstanceSerializer.Payload("test"), 0, ServiceType.DYNAMIC, new UriSpec("{a}/b/{c}"), false); + public void testBackwardCompatibility() throws Exception { + JsonInstanceSerializer serializer = new JsonInstanceSerializer< + TestJsonInstanceSerializer.Payload>(TestJsonInstanceSerializer.Payload.class, true, true); + ServiceInstance instance = + new ServiceInstance( + "name", + "id", + "address", + 10, + 20, + new TestJsonInstanceSerializer.Payload("test"), + 0, + ServiceType.DYNAMIC, + new UriSpec("{a}/b/{c}"), + false); byte[] bytes = serializer.serialize(instance); instance = serializer.deserialize(bytes); - assertTrue(instance.isEnabled()); // passed false for enabled in the ctor but that is lost with compatibleSerializationMode + assertTrue(instance.isEnabled()); // passed false for enabled in the ctor but that is lost with + // compatibleSerializationMode ObjectMapper mapper = new ObjectMapper(); JavaType type = mapper.getTypeFactory().constructType(OldServiceInstance.class); OldServiceInstance rawServiceInstance = mapper.readValue(bytes, type); - TestJsonInstanceSerializer.Payload.class.cast(rawServiceInstance.getPayload()); // just to verify that it's the correct type + TestJsonInstanceSerializer.Payload.class.cast( + rawServiceInstance.getPayload()); // just to verify that it's the correct type //noinspection unchecked - OldServiceInstance check = (OldServiceInstance)rawServiceInstance; + OldServiceInstance check = + (OldServiceInstance) rawServiceInstance; assertEquals(check.getName(), instance.getName()); assertEquals(check.getId(), instance.getId()); assertEquals(check.getAddress(), instance.getAddress()); @@ -75,13 +109,23 @@ public void testBackwardCompatibility() throws Exception } @Test - public void testForwardCompatibility() throws Exception - { - OldServiceInstance oldInstance = new OldServiceInstance("name", "id", "address", 10, 20, new TestJsonInstanceSerializer.Payload("test"), 0, ServiceType.DYNAMIC, new UriSpec("{a}/b/{c}")); + public void testForwardCompatibility() throws Exception { + OldServiceInstance oldInstance = + new OldServiceInstance( + "name", + "id", + "address", + 10, + 20, + new TestJsonInstanceSerializer.Payload("test"), + 0, + ServiceType.DYNAMIC, + new UriSpec("{a}/b/{c}")); ObjectMapper mapper = new ObjectMapper(); byte[] oldJson = mapper.writeValueAsBytes(oldInstance); - JsonInstanceSerializer serializer = new JsonInstanceSerializer(TestJsonInstanceSerializer.Payload.class); + JsonInstanceSerializer serializer = new JsonInstanceSerializer< + TestJsonInstanceSerializer.Payload>(TestJsonInstanceSerializer.Payload.class); ServiceInstance instance = serializer.deserialize(oldJson); assertEquals(oldInstance.getName(), instance.getName()); assertEquals(oldInstance.getId(), instance.getId()); @@ -96,9 +140,22 @@ public void testForwardCompatibility() throws Exception } @Test - public void testFutureChanges() throws Exception - { - TestNewServiceInstance newInstance = new TestNewServiceInstance("name", "id", "address", 10, 20, "hey", 0, ServiceType.DYNAMIC, new UriSpec("{a}/b/{c}"), false, "what", 10101L, new Date(), new URI("http://hey")); + public void testFutureChanges() throws Exception { + TestNewServiceInstance newInstance = new TestNewServiceInstance( + "name", + "id", + "address", + 10, + 20, + "hey", + 0, + ServiceType.DYNAMIC, + new UriSpec("{a}/b/{c}"), + false, + "what", + 10101L, + new Date(), + new URI("http://hey")); byte[] newInstanceBytes = new ObjectMapper().writeValueAsBytes(newInstance); JsonInstanceSerializer serializer = new JsonInstanceSerializer(String.class); ServiceInstance instance = serializer.deserialize(newInstanceBytes); diff --git a/curator-x-discovery/src/test/java/org/apache/curator/x/discovery/details/TestNewServiceInstance.java b/curator-x-discovery/src/test/java/org/apache/curator/x/discovery/details/TestNewServiceInstance.java index 2050661c5..eedf89848 100644 --- a/curator-x-discovery/src/test/java/org/apache/curator/x/discovery/details/TestNewServiceInstance.java +++ b/curator-x-discovery/src/test/java/org/apache/curator/x/discovery/details/TestNewServiceInstance.java @@ -21,13 +21,12 @@ import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.google.common.base.Preconditions; -import org.apache.curator.x.discovery.ServiceType; -import org.apache.curator.x.discovery.UriSpec; import java.net.URI; import java.util.Date; +import org.apache.curator.x.discovery.ServiceType; +import org.apache.curator.x.discovery.UriSpec; -class TestNewServiceInstance -{ +class TestNewServiceInstance { private final String name; private final String id; private final String address; @@ -43,8 +42,21 @@ class TestNewServiceInstance private final Date new3; private final URI new4; - public TestNewServiceInstance(String name, String id, String address, Integer port, Integer sslPort, T payload, long registrationTimeUTC, ServiceType serviceType, UriSpec uriSpec, boolean enabled, String new1, Long new2, Date new3, URI new4) - { + public TestNewServiceInstance( + String name, + String id, + String address, + Integer port, + Integer sslPort, + T payload, + long registrationTimeUTC, + ServiceType serviceType, + UriSpec uriSpec, + boolean enabled, + String new1, + Long new2, + Date new3, + URI new4) { name = Preconditions.checkNotNull(name, "name cannot be null"); id = Preconditions.checkNotNull(id, "id cannot be null"); @@ -67,79 +79,64 @@ public TestNewServiceInstance(String name, String id, String address, Integer po /** * Inits to default values. Only exists for deserialization */ - TestNewServiceInstance() - { + TestNewServiceInstance() { this("", "", null, null, null, null, 0, ServiceType.DYNAMIC, null, true, null, null, null, null); } - public String getName() - { + public String getName() { return name; } - public String getId() - { + public String getId() { return id; } - public String getAddress() - { + public String getAddress() { return address; } - public Integer getPort() - { + public Integer getPort() { return port; } - public Integer getSslPort() - { + public Integer getSslPort() { return sslPort; } @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, defaultImpl = Object.class) - public T getPayload() - { + public T getPayload() { return payload; } - public long getRegistrationTimeUTC() - { + public long getRegistrationTimeUTC() { return registrationTimeUTC; } - public ServiceType getServiceType() - { + public ServiceType getServiceType() { return serviceType; } - public UriSpec getUriSpec() - { + public UriSpec getUriSpec() { return uriSpec; } - public boolean isEnabled() - { + public boolean isEnabled() { return enabled; } - public String getNew1() - { + public String getNew1() { return new1; } - public Long getNew2() - { + public Long getNew2() { return new2; } - public Date getNew3() - { + public Date getNew3() { return new3; } - public URI getNew4() - { + public URI getNew4() { return new4; } } diff --git a/curator-x-discovery/src/test/java/org/apache/curator/x/discovery/details/TestServiceCacheRace.java b/curator-x-discovery/src/test/java/org/apache/curator/x/discovery/details/TestServiceCacheRace.java index 831ad769c..61a00696f 100644 --- a/curator-x-discovery/src/test/java/org/apache/curator/x/discovery/details/TestServiceCacheRace.java +++ b/curator-x-discovery/src/test/java/org/apache/curator/x/discovery/details/TestServiceCacheRace.java @@ -21,6 +21,11 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import com.google.common.collect.Lists; +import java.io.Closeable; +import java.util.Collections; +import java.util.List; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Executors; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.state.ConnectionState; @@ -37,94 +42,96 @@ import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; import org.slf4j.LoggerFactory; -import java.io.Closeable; -import java.util.Collections; -import java.util.List; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.Executors; @Tag(CuratorTestBase.zk35TestCompatibilityGroup) -public class TestServiceCacheRace extends BaseClassForTests -{ +public class TestServiceCacheRace extends BaseClassForTests { private final Timing timing = new Timing(); - // validates CURATOR-452 which exposed a race in ServiceCacheImpl's start() method caused by an optimization whereby it clears the dataBytes of its internal PathChildrenCache + // validates CURATOR-452 which exposed a race in ServiceCacheImpl's start() method caused by an optimization whereby + // it clears the dataBytes of its internal PathChildrenCache @Test - public void testRaceOnInitialLoad() throws Exception - { + public void testRaceOnInitialLoad() throws Exception { List closeables = Lists.newArrayList(); - try - { + try { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); closeables.add(client); client.start(); - ServiceDiscovery discovery = ServiceDiscoveryBuilder.builder(String.class).basePath("/discovery").client(client).build(); + ServiceDiscovery discovery = ServiceDiscoveryBuilder.builder(String.class) + .basePath("/discovery") + .client(client) + .build(); closeables.add(discovery); discovery.start(); CountDownLatch cacheStartLatch = new CountDownLatch(1); CountDownLatch cacheWaitLatch = new CountDownLatch(1); - final ServiceCache cache = discovery.serviceCacheBuilder().name("test").build(); + final ServiceCache cache = + discovery.serviceCacheBuilder().name("test").build(); closeables.add(cache); - ((ServiceCacheImpl)cache).debugStartLatch = cacheStartLatch; // causes ServiceCacheImpl.start to notify just after starting its internal PathChildrenCache - ((ServiceCacheImpl)cache).debugStartWaitLatch = cacheWaitLatch; // causes ServiceCacheImpl.start to wait before iterating over its internal PathChildrenCache + ((ServiceCacheImpl) cache).debugStartLatch = + cacheStartLatch; // causes ServiceCacheImpl.start to notify just after starting its internal + // PathChildrenCache + ((ServiceCacheImpl) cache).debugStartWaitLatch = + cacheWaitLatch; // causes ServiceCacheImpl.start to wait before iterating over its internal + // PathChildrenCache - ServiceInstance instance1 = ServiceInstance.builder().payload("test").name("test").port(10064).build(); + ServiceInstance instance1 = ServiceInstance.builder() + .payload("test") + .name("test") + .port(10064) + .build(); discovery.registerService(instance1); - CloseableExecutorService closeableExecutorService = new CloseableExecutorService(Executors.newSingleThreadExecutor()); + CloseableExecutorService closeableExecutorService = + new CloseableExecutorService(Executors.newSingleThreadExecutor()); closeables.add(closeableExecutorService); final CountDownLatch startCompletedLatch = new CountDownLatch(1); - Runnable proc = new Runnable() - { + Runnable proc = new Runnable() { @Override - public void run() - { - try - { + public void run() { + try { cache.start(); startCompletedLatch.countDown(); - } - catch ( Exception e ) - { + } catch (Exception e) { LoggerFactory.getLogger(getClass()).error("Start failed", e); throw new RuntimeException(e); } } }; closeableExecutorService.submit(proc); - assertTrue(timing.awaitLatch(cacheStartLatch)); // wait until ServiceCacheImpl's internal PathChildrenCache is started and primed + assertTrue(timing.awaitLatch( + cacheStartLatch)); // wait until ServiceCacheImpl's internal PathChildrenCache is started and primed final CountDownLatch cacheChangedLatch = new CountDownLatch(1); - ServiceCacheListener listener = new ServiceCacheListener() - { + ServiceCacheListener listener = new ServiceCacheListener() { @Override - public void cacheChanged() - { + public void cacheChanged() { cacheChangedLatch.countDown(); } @Override - public void stateChanged(CuratorFramework client, ConnectionState newState) - { + public void stateChanged(CuratorFramework client, ConnectionState newState) { // NOP } }; cache.addListener(listener); - ServiceInstance instance2 = ServiceInstance.builder().payload("test").name("test").port(10065).build(); - discovery.registerService(instance2); // cause ServiceCacheImpl's internal PathChildrenCache listener to get called which will clear the dataBytes + ServiceInstance instance2 = ServiceInstance.builder() + .payload("test") + .name("test") + .port(10065) + .build(); + discovery.registerService( + instance2); // cause ServiceCacheImpl's internal PathChildrenCache listener to get called which will + // clear the dataBytes assertTrue(timing.awaitLatch(cacheChangedLatch)); cacheWaitLatch.countDown(); assertTrue(timing.awaitLatch(startCompletedLatch)); - } - finally - { + } finally { Collections.reverse(closeables); - for ( Closeable c : closeables ) - { + for (Closeable c : closeables) { CloseableUtils.closeQuietly(c); } } diff --git a/curator-x-discovery/src/test/java/org/apache/curator/x/discovery/details/TestServiceDiscovery.java b/curator-x-discovery/src/test/java/org/apache/curator/x/discovery/details/TestServiceDiscovery.java index e8a6354ff..01fa12733 100644 --- a/curator-x-discovery/src/test/java/org/apache/curator/x/discovery/details/TestServiceDiscovery.java +++ b/curator-x-discovery/src/test/java/org/apache/curator/x/discovery/details/TestServiceDiscovery.java @@ -24,6 +24,11 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import com.google.common.collect.Lists; import com.google.common.collect.Sets; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Semaphore; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.retry.RetryOneTime; @@ -37,47 +42,45 @@ import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; -import java.util.Collections; -import java.util.Comparator; -import java.util.List; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.Semaphore; - @Tag(CuratorTestBase.zk35TestCompatibilityGroup) -public class TestServiceDiscovery extends BaseClassForTests -{ - private static final Comparator> comparator = new Comparator>() - { +public class TestServiceDiscovery extends BaseClassForTests { + private static final Comparator> comparator = new Comparator>() { @Override - public int compare(ServiceInstance o1, ServiceInstance o2) - { + public int compare(ServiceInstance o1, ServiceInstance o2) { return o1.getId().compareTo(o2.getId()); } }; @Test - public void testCrashedServerMultiInstances() throws Exception - { + public void testCrashedServerMultiInstances() throws Exception { CuratorFramework client = null; ServiceDiscovery discovery = null; - try - { + try { Timing timing = new Timing(); - client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); + client = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); client.start(); final Semaphore semaphore = new Semaphore(0); - ServiceInstance instance1 = ServiceInstance.builder().payload("thing").name("test").port(10064).build(); - ServiceInstance instance2 = ServiceInstance.builder().payload("thing").name("test").port(10065).build(); - discovery = new ServiceDiscoveryImpl(client, "/test", new JsonInstanceSerializer(String.class), instance1, false) - { - @Override - protected void internalRegisterService(ServiceInstance service) throws Exception - { - super.internalRegisterService(service); - semaphore.release(); - } - }; + ServiceInstance instance1 = ServiceInstance.builder() + .payload("thing") + .name("test") + .port(10064) + .build(); + ServiceInstance instance2 = ServiceInstance.builder() + .payload("thing") + .name("test") + .port(10065) + .build(); + discovery = + new ServiceDiscoveryImpl( + client, "/test", new JsonInstanceSerializer(String.class), instance1, false) { + @Override + protected void internalRegisterService(ServiceInstance service) throws Exception { + super.internalRegisterService(service); + semaphore.release(); + } + }; discovery.start(); discovery.registerService(instance2); @@ -91,36 +94,37 @@ protected void internalRegisterService(ServiceInstance service) throws E timing.acquireSemaphore(semaphore, 2); assertEquals(discovery.queryForInstances("test").size(), 2); - } - finally - { + } finally { CloseableUtils.closeQuietly(discovery); CloseableUtils.closeQuietly(client); } } @Test - public void testCrashedServer() throws Exception - { + public void testCrashedServer() throws Exception { CuratorFramework client = null; ServiceDiscovery discovery = null; - try - { + try { Timing timing = new Timing(); - client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); + client = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); client.start(); final Semaphore semaphore = new Semaphore(0); - ServiceInstance instance = ServiceInstance.builder().payload("thing").name("test").port(10064).build(); - discovery = new ServiceDiscoveryImpl(client, "/test", new JsonInstanceSerializer(String.class), instance, false) - { - @Override - protected void internalRegisterService(ServiceInstance service) throws Exception - { - super.internalRegisterService(service); - semaphore.release(); - } - }; + ServiceInstance instance = ServiceInstance.builder() + .payload("thing") + .name("test") + .port(10064) + .build(); + discovery = + new ServiceDiscoveryImpl( + client, "/test", new JsonInstanceSerializer(String.class), instance, false) { + @Override + protected void internalRegisterService(ServiceInstance service) throws Exception { + super.internalRegisterService(service); + semaphore.release(); + } + }; discovery.start(); timing.acquireSemaphore(semaphore); @@ -133,28 +137,30 @@ protected void internalRegisterService(ServiceInstance service) throws E timing.acquireSemaphore(semaphore); assertEquals(discovery.queryForInstances("test").size(), 1); - } - finally - { + } finally { CloseableUtils.closeQuietly(discovery); CloseableUtils.closeQuietly(client); } } @Test - public void testCrashedInstance() throws Exception - { + public void testCrashedInstance() throws Exception { CuratorFramework client = null; ServiceDiscovery discovery = null; - try - { + try { Timing timing = new Timing(); - client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); + client = CuratorFrameworkFactory.newClient( + server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); client.start(); - ServiceInstance instance = ServiceInstance.builder().payload("thing").name("test").port(10064).build(); - discovery = new ServiceDiscoveryImpl(client, "/test", new JsonInstanceSerializer(String.class), instance, false); + ServiceInstance instance = ServiceInstance.builder() + .payload("thing") + .name("test") + .port(10064) + .build(); + discovery = new ServiceDiscoveryImpl( + client, "/test", new JsonInstanceSerializer(String.class), instance, false); discovery.start(); assertEquals(discovery.queryForInstances("test").size(), 1); @@ -163,33 +169,36 @@ public void testCrashedInstance() throws Exception Thread.sleep(timing.multiple(1.5).session()); assertEquals(discovery.queryForInstances("test").size(), 1); - } - finally - { + } finally { CloseableUtils.closeQuietly(discovery); CloseableUtils.closeQuietly(client); } } @Test - public void testMultipleInstances() throws Exception - { + public void testMultipleInstances() throws Exception { final String SERVICE_ONE = "one"; final String SERVICE_TWO = "two"; CuratorFramework client = null; ServiceDiscovery discovery = null; - try - { + try { client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client.start(); - ServiceInstance s1_i1 = ServiceInstance.builder().name(SERVICE_ONE).build(); - ServiceInstance s1_i2 = ServiceInstance.builder().name(SERVICE_ONE).build(); - ServiceInstance s2_i1 = ServiceInstance.builder().name(SERVICE_TWO).build(); - ServiceInstance s2_i2 = ServiceInstance.builder().name(SERVICE_TWO).build(); - - discovery = ServiceDiscoveryBuilder.builder(Void.class).client(client).basePath("/test").build(); + ServiceInstance s1_i1 = + ServiceInstance.builder().name(SERVICE_ONE).build(); + ServiceInstance s1_i2 = + ServiceInstance.builder().name(SERVICE_ONE).build(); + ServiceInstance s2_i1 = + ServiceInstance.builder().name(SERVICE_TWO).build(); + ServiceInstance s2_i2 = + ServiceInstance.builder().name(SERVICE_TWO).build(); + + discovery = ServiceDiscoveryBuilder.builder(Void.class) + .client(client) + .basePath("/test") + .build(); discovery.start(); discovery.registerService(s1_i1); @@ -215,26 +224,30 @@ public void testMultipleInstances() throws Exception queriedInstances = Lists.newArrayList(discovery.queryForInstances(SERVICE_TWO)); Collections.sort(queriedInstances, comparator); assertEquals(queriedInstances, list, String.format("Not equal 2: %s - d: %s", list, queriedInstances)); - } - finally - { + } finally { CloseableUtils.closeQuietly(discovery); CloseableUtils.closeQuietly(client); } } @Test - public void testBasic() throws Exception - { + public void testBasic() throws Exception { CuratorFramework client = null; ServiceDiscovery discovery = null; - try - { + try { client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client.start(); - ServiceInstance instance = ServiceInstance.builder().payload("thing").name("test").port(10064).build(); - discovery = ServiceDiscoveryBuilder.builder(String.class).basePath("/test").client(client).thisInstance(instance).build(); + ServiceInstance instance = ServiceInstance.builder() + .payload("thing") + .name("test") + .port(10064) + .build(); + discovery = ServiceDiscoveryBuilder.builder(String.class) + .basePath("/test") + .client(client) + .thisInstance(instance) + .build(); discovery.start(); assertEquals(discovery.queryForNames(), Collections.singletonList("test")); @@ -242,29 +255,33 @@ public void testBasic() throws Exception List> list = Lists.newArrayList(); list.add(instance); assertEquals(discovery.queryForInstances("test"), list); - } - finally - { + } finally { CloseableUtils.closeQuietly(discovery); CloseableUtils.closeQuietly(client); } } @Test - public void testNoServerOnStart() throws Exception - { + public void testNoServerOnStart() throws Exception { Timing timing = new Timing(); server.stop(); CuratorFramework client = null; ServiceDiscovery discovery = null; - try - { + try { client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client.start(); - ServiceInstance instance = ServiceInstance.builder().payload("thing").name("test").port(10064).build(); - discovery = ServiceDiscoveryBuilder.builder(String.class).basePath("/test").client(client).thisInstance(instance).build(); + ServiceInstance instance = ServiceInstance.builder() + .payload("thing") + .name("test") + .port(10064) + .build(); + discovery = ServiceDiscoveryBuilder.builder(String.class) + .basePath("/test") + .client(client) + .thisInstance(instance) + .build(); discovery.start(); server.restart(); @@ -274,9 +291,7 @@ public void testNoServerOnStart() throws Exception List> list = Lists.newArrayList(); list.add(instance); assertEquals(discovery.queryForInstances("test"), list); - } - finally - { + } finally { CloseableUtils.closeQuietly(discovery); CloseableUtils.closeQuietly(client); } @@ -284,26 +299,20 @@ public void testNoServerOnStart() throws Exception // CURATOR-164 @Test - public void testUnregisterService() throws Exception - { + public void testUnregisterService() throws Exception { final String name = "name"; final CountDownLatch restartLatch = new CountDownLatch(1); - InstanceSerializer slowSerializer = new JsonInstanceSerializer(String.class) - { + InstanceSerializer slowSerializer = new JsonInstanceSerializer(String.class) { private boolean first = true; @Override - public byte[] serialize(ServiceInstance instance) throws Exception - { - if ( first ) - { + public byte[] serialize(ServiceInstance instance) throws Exception { + if (first) { System.out.println("Serializer first registration."); first = false; - } - else - { + } else { System.out.println("Waiting for reconnect to finish."); // Simulate the serialize method being slow. // This could just be a timed wait, but that's kind of non-deterministic. @@ -315,13 +324,22 @@ public byte[] serialize(ServiceInstance instance) throws Exception CuratorFramework client = null; ServiceDiscovery discovery = null; - try - { + try { client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client.start(); - ServiceInstance instance = ServiceInstance.builder().payload("thing").name(name).port(10064).build(); - discovery = ServiceDiscoveryBuilder.builder(String.class).basePath("/test").client(client).thisInstance(instance).serializer(slowSerializer).watchInstances(true).build(); + ServiceInstance instance = ServiceInstance.builder() + .payload("thing") + .name(name) + .port(10064) + .build(); + discovery = ServiceDiscoveryBuilder.builder(String.class) + .basePath("/test") + .client(client) + .thisInstance(instance) + .serializer(slowSerializer) + .watchInstances(true) + .build(); discovery.start(); assertFalse(discovery.queryForInstances(name).isEmpty(), "Service should start registered."); @@ -335,33 +353,35 @@ public byte[] serialize(ServiceInstance instance) throws Exception new Timing().sleepABit(); // Wait for the rest of registration to finish. assertTrue(discovery.queryForInstances(name).isEmpty(), "Service should have unregistered."); - } - finally - { + } finally { CloseableUtils.closeQuietly(discovery); CloseableUtils.closeQuietly(client); } } @Test - public void testCleaning() throws Exception - { + public void testCleaning() throws Exception { CuratorFramework client = null; ServiceDiscovery discovery = null; - try - { + try { client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client.start(); - ServiceInstance instance = ServiceInstance.builder().payload("thing").name("test").port(10064).build(); - discovery = ServiceDiscoveryBuilder.builder(String.class).basePath("/test").client(client).thisInstance(instance).build(); + ServiceInstance instance = ServiceInstance.builder() + .payload("thing") + .name("test") + .port(10064) + .build(); + discovery = ServiceDiscoveryBuilder.builder(String.class) + .basePath("/test") + .client(client) + .thisInstance(instance) + .build(); discovery.start(); discovery.unregisterService(instance); - assertEquals(((ServiceDiscoveryImpl)discovery).debugServicesQty(), 0); - } - finally - { + assertEquals(((ServiceDiscoveryImpl) discovery).debugServicesQty(), 0); + } finally { CloseableUtils.closeQuietly(discovery); CloseableUtils.closeQuietly(client); } diff --git a/curator-x-discovery/src/test/java/org/apache/curator/x/discovery/details/TestServiceDiscoveryBuilder.java b/curator-x-discovery/src/test/java/org/apache/curator/x/discovery/details/TestServiceDiscoveryBuilder.java index c92977183..5f36b8cf6 100644 --- a/curator-x-discovery/src/test/java/org/apache/curator/x/discovery/details/TestServiceDiscoveryBuilder.java +++ b/curator-x-discovery/src/test/java/org/apache/curator/x/discovery/details/TestServiceDiscoveryBuilder.java @@ -22,7 +22,6 @@ 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 org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.retry.RetryOneTime; @@ -34,40 +33,38 @@ import org.junit.jupiter.api.Test; @Tag(CuratorTestBase.zk35TestCompatibilityGroup) -public class TestServiceDiscoveryBuilder extends BaseClassForTests -{ +public class TestServiceDiscoveryBuilder extends BaseClassForTests { @Test - public void testDefaultSerializer() - { + public void testDefaultSerializer() { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); - ServiceDiscoveryBuilder builder = ServiceDiscoveryBuilder.builder(Object.class).client(client); - ServiceDiscoveryImpl discovery = (ServiceDiscoveryImpl) builder.basePath("/path").build(); + ServiceDiscoveryBuilder builder = + ServiceDiscoveryBuilder.builder(Object.class).client(client); + ServiceDiscoveryImpl discovery = + (ServiceDiscoveryImpl) builder.basePath("/path").build(); assertNotNull(discovery.getSerializer(), "default serializer not set"); assertTrue(discovery.getSerializer() instanceof JsonInstanceSerializer, "default serializer not JSON"); } @Test - public void testSetSerializer() - { + public void testSetSerializer() { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); - ServiceDiscoveryBuilder builder = ServiceDiscoveryBuilder.builder(Object.class).client(client); - builder.serializer(new InstanceSerializer() - { + ServiceDiscoveryBuilder builder = + ServiceDiscoveryBuilder.builder(Object.class).client(client); + builder.serializer(new InstanceSerializer() { @Override - public byte[] serialize(ServiceInstance instance) - { + public byte[] serialize(ServiceInstance instance) { return null; } @Override - public ServiceInstance deserialize(byte[] bytes) - { + public ServiceInstance deserialize(byte[] bytes) { return null; } }); - ServiceDiscoveryImpl discovery = (ServiceDiscoveryImpl) builder.basePath("/path").build(); + ServiceDiscoveryImpl discovery = + (ServiceDiscoveryImpl) builder.basePath("/path").build(); assertNotNull(discovery.getSerializer(), "default serializer not set"); assertFalse(discovery.getSerializer() instanceof JsonInstanceSerializer, "set serializer is JSON"); } diff --git a/curator-x-discovery/src/test/java/org/apache/curator/x/discovery/details/TestServiceProvider.java b/curator-x-discovery/src/test/java/org/apache/curator/x/discovery/details/TestServiceProvider.java index 5aabd4908..9255402be 100644 --- a/curator-x-discovery/src/test/java/org/apache/curator/x/discovery/details/TestServiceProvider.java +++ b/curator-x-discovery/src/test/java/org/apache/curator/x/discovery/details/TestServiceProvider.java @@ -21,10 +21,10 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; +import com.google.common.collect.Lists; import java.io.Closeable; import java.util.Collections; import java.util.List; - import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.retry.RetryOneTime; @@ -35,30 +35,35 @@ import org.apache.curator.x.discovery.ServiceDiscoveryBuilder; import org.apache.curator.x.discovery.ServiceInstance; import org.apache.curator.x.discovery.ServiceProvider; -import com.google.common.collect.Lists; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; @Tag(CuratorTestBase.zk35TestCompatibilityGroup) -public class TestServiceProvider extends BaseClassForTests -{ +public class TestServiceProvider extends BaseClassForTests { @Test - public void testBasic() throws Exception - { + public void testBasic() throws Exception { List closeables = Lists.newArrayList(); - try - { + try { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); closeables.add(client); client.start(); - ServiceInstance instance = ServiceInstance.builder().payload("thing").name("test").port(10064).build(); - ServiceDiscovery discovery = ServiceDiscoveryBuilder.builder(String.class).basePath("/test").client(client).thisInstance(instance).build(); + ServiceInstance instance = ServiceInstance.builder() + .payload("thing") + .name("test") + .port(10064) + .build(); + ServiceDiscovery discovery = ServiceDiscoveryBuilder.builder(String.class) + .basePath("/test") + .client(client) + .thisInstance(instance) + .build(); closeables.add(discovery); discovery.start(); - ServiceProvider provider = discovery.serviceProviderBuilder().serviceName("test").build(); + ServiceProvider provider = + discovery.serviceProviderBuilder().serviceName("test").build(); closeables.add(provider); provider.start(); @@ -67,48 +72,52 @@ public void testBasic() throws Exception List> list = Lists.newArrayList(); list.add(instance); assertEquals(provider.getAllInstances(), list); - } - finally - { + } finally { Collections.reverse(closeables); - for ( Closeable c : closeables ) - { + for (Closeable c : closeables) { CloseableUtils.closeQuietly(c); } } } @Test - public void testDisabledInstance() throws Exception - { + public void testDisabledInstance() throws Exception { List closeables = Lists.newArrayList(); - try - { + try { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); closeables.add(client); client.start(); - ServiceInstance instance = ServiceInstance.builder().payload("thing").name("test").port(10064).enabled(false).build(); + ServiceInstance instance = ServiceInstance.builder() + .payload("thing") + .name("test") + .port(10064) + .enabled(false) + .build(); InstanceSerializer serializer = new JsonInstanceSerializer<>(String.class, false); - ServiceDiscovery discovery = ServiceDiscoveryBuilder.builder(String.class).serializer(serializer).basePath("/test").client(client).thisInstance(instance).build(); + ServiceDiscovery discovery = ServiceDiscoveryBuilder.builder(String.class) + .serializer(serializer) + .basePath("/test") + .client(client) + .thisInstance(instance) + .build(); closeables.add(discovery); discovery.start(); - ServiceProvider provider = discovery.serviceProviderBuilder().serviceName("test").build(); + ServiceProvider provider = + discovery.serviceProviderBuilder().serviceName("test").build(); closeables.add(provider); provider.start(); assertEquals(provider.getInstance(), null); - assertTrue(provider.getAllInstances().isEmpty(), "Disabled instance still appears available via service provider"); - } - finally - { + assertTrue( + provider.getAllInstances().isEmpty(), + "Disabled instance still appears available via service provider"); + } finally { Collections.reverse(closeables); - for ( Closeable c : closeables ) - { + for (Closeable c : closeables) { CloseableUtils.closeQuietly(c); } } } - } diff --git a/curator-x-discovery/src/test/java/org/apache/curator/x/discovery/details/TestWatchedInstances.java b/curator-x-discovery/src/test/java/org/apache/curator/x/discovery/details/TestWatchedInstances.java index 6d5fcbd78..cf903f69b 100644 --- a/curator-x-discovery/src/test/java/org/apache/curator/x/discovery/details/TestWatchedInstances.java +++ b/curator-x-discovery/src/test/java/org/apache/curator/x/discovery/details/TestWatchedInstances.java @@ -22,6 +22,10 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import com.google.common.collect.Lists; +import java.io.Closeable; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.retry.RetryOneTime; @@ -33,32 +37,27 @@ import org.apache.curator.x.discovery.ServiceInstance; import org.junit.jupiter.api.Test; -import java.io.Closeable; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -public class TestWatchedInstances extends BaseClassForTests -{ +public class TestWatchedInstances extends BaseClassForTests { @Test - public void testWatchedInstances() throws Exception - { + public void testWatchedInstances() throws Exception { Timing timing = new Timing(); List closeables = Lists.newArrayList(); - try - { + try { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); closeables.add(client); client.start(); - ServiceInstance instance = ServiceInstance.builder().payload("thing").name("test").port(10064).build(); - ServiceDiscovery discovery = ServiceDiscoveryBuilder - .builder(String.class) - .basePath("/test") - .client(client) - .thisInstance(instance) - .watchInstances(true) - .build(); + ServiceInstance instance = ServiceInstance.builder() + .payload("thing") + .name("test") + .port(10064) + .build(); + ServiceDiscovery discovery = ServiceDiscoveryBuilder.builder(String.class) + .basePath("/test") + .client(client) + .thisInstance(instance) + .watchInstances(true) + .build(); closeables.add(discovery); discovery.start(); @@ -68,14 +67,14 @@ public void testWatchedInstances() throws Exception list.add(instance); assertEquals(discovery.queryForInstances("test"), list); - ServiceDiscoveryImpl discoveryImpl = (ServiceDiscoveryImpl)discovery; + ServiceDiscoveryImpl discoveryImpl = (ServiceDiscoveryImpl) discovery; ServiceInstance changedInstance = ServiceInstance.builder() - .id(instance.getId()) - .address(instance.getAddress()) - .payload("different") - .name(instance.getName()) - .port(instance.getPort()) - .build(); + .id(instance.getId()) + .address(instance.getAddress()) + .payload("different") + .name(instance.getName()) + .port(instance.getPort()) + .build(); String path = discoveryImpl.pathForInstance("test", instance.getId()); byte[] bytes = discoveryImpl.getSerializer().serialize(changedInstance); client.setData().forPath(path, bytes); @@ -84,12 +83,9 @@ public void testWatchedInstances() throws Exception ServiceInstance registeredService = discoveryImpl.getRegisteredService(instance.getId()); assertNotNull(registeredService); assertEquals(registeredService.getPayload(), "different"); - } - finally - { + } finally { Collections.reverse(closeables); - for ( Closeable c : closeables ) - { + for (Closeable c : closeables) { CloseableUtils.closeQuietly(c); } }