summaryrefslogtreecommitdiff
path: root/zookeeper-server/src/test/java/org/apache
diff options
context:
space:
mode:
authortison <wander4096@gmail.com>2019-08-17 08:13:15 -0700
committerMichael Han <hanm@apache.org>2019-08-17 08:13:15 -0700
commitfe940cdd8fb23ba09684cefb73233d570f4a20fa (patch)
tree28de6768b6ef6f233840636cb50a1cd35512e319 /zookeeper-server/src/test/java/org/apache
parent04cc5cae1e7d4b007490e68109a676b88ce790a3 (diff)
downloadzookeeper-fe940cdd8fb23ba09684cefb73233d570f4a20fa.tar.gz
ZOOKEEPER-3475: Enable Checkstyle configuration on zookeeper-server
- [x] org/apache/zookeeper - [x] org/apache/zookeeper/admin - [x] org/apache/zookeeper/cli - [x] org/apache/zookeeper/client - [x] org/apache/zookeeper/common - [x] org/apache/zookeeper/jmx - [x] org/apache/zookeeper/metrics - [x] org/apache/zookeeper/metrics/impl - [x] org/apache/zookeeper/server - [x] org/apache/zookeeper/server/admin - [x] org/apache/zookeeper/server/auth - [x] org/apache/zookeeper/server/command - [x] org/apache/zookeeper/server/metric - [x] org/apache/zookeeper/server/persistence - [x] org/apache/zookeeper/server/quorum - [x] org/apache/zookeeper/server/quorum/auth - [x] org/apache/zookeeper/server/quorum/flexible - [x] org/apache/zookeeper/server/util - [x] org/apache/zookeeper/server/watch - [x] org/apache/zookeeper/test - [x] org/apache/zookeeper/util - [x] org/apache/zookeeper/version/util Author: tison <wander4096@gmail.com> Reviewers: Brian Nixon <nixon@fb.com>, Enrico Olivelli <eolivelli@gmail.com>, Michael Han <hanm@apache.org> Closes #1049 from TisonKun/ZOOKEEPER-3475
Diffstat (limited to 'zookeeper-server/src/test/java/org/apache')
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/ClientCanonicalizeTest.java20
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/ClientCnxnSocketTest.java8
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/ClientReconnectTest.java27
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/ClientRequestTimeoutTest.java79
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/CustomHostProviderTest.java38
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/GetAllChildrenNumberTest.java42
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/GetEphemeralsTest.java111
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/JUnit4ZKTestRunner.java27
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/JaasConfiguration.java12
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/MockPacket.java27
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/MultiOperationRecordTest.java21
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/MultiResponseTest.java18
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/PortAssignment.java34
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/PortAssignmentTest.java50
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/RemoveWatchesCmdTest.java122
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/RemoveWatchesTest.java645
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/SaslAuthTest.java58
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/ServerConfigTest.java19
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/TestableZooKeeper.java72
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/VerGenTest.java26
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/ZKParameterized.java14
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/ZKTestCase.java21
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/ZKUtilTest.java8
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/ZooKeeperTest.java360
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/client/ZKClientConfigTest.java11
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/common/AtomicFileWritingIdiomTest.java22
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/common/BaseX509ParameterizedTestCase.java8
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/common/FileChangeWatcherTest.java152
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/common/FileKeyStoreLoaderBuilderProviderTest.java24
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/common/JKSFileLoaderTest.java107
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/common/KeyStoreFileTypeTest.java66
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/common/NetUtilsTest.java24
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/common/PEMFileLoaderTest.java121
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/common/PKCS12FileLoaderTest.java46
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/common/PathTrieTest.java62
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/common/PathUtilsTest.java63
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/common/TimeTest.java29
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/common/X509KeyType.java5
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/common/X509TestContext.java130
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/common/X509TestHelpers.java176
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/common/X509UtilTest.java253
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/common/ZKTrustManagerTest.java52
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/metrics/BaseTestMetricsProvider.java5
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/metrics/MetricsUtils.java6
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/BlueThrottleTest.java62
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/ByteBufferInputStreamTest.java70
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/CRCTest.java42
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/ConnectionMetricsTest.java69
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/CreateContainerTest.java174
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/CreateTTLTest.java129
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/DataNodeTest.java10
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/DataTreeTest.java220
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/DatadirCleanupManagerTest.java34
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/DeserializationPerfTest.java56
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/Emulate353TTLTest.java42
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/EphemeralTypeTest.java35
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/FinalRequestProcessorTest.java51
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/InvalidSnapCountTest.java37
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/InvalidSnapshotTest.java17
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/MockNIOServerCnxn.java10
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/MockSelectorThread.java4
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/MockServerCnxn.java10
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/MultiOpSessionUpgradeTest.java61
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/NIOServerCnxnFactoryTest.java13
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/NIOServerCnxnTest.java48
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/NettyServerCnxnTest.java94
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/NodeHashMapImplTest.java36
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/PrepRequestProcessorMetricsTest.java92
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/PrepRequestProcessorTest.java104
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/PurgeTxnTest.java173
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/ReferenceCountedACLCacheTest.java32
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/RequestThrottlerTest.java71
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/SerializationPerfTest.java57
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/ServerIdTest.java27
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/ServerMetricsTest.java35
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/ServerStatsTest.java39
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/SessionTrackerTest.java49
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/SnapshotDigestTest.java70
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/ToStringTest.java10
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/ZooKeeperCriticalThreadMetricsTest.java27
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/ZooKeeperServerBeanTest.java12
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/ZooKeeperServerConfTest.java14
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/ZooKeeperServerMainTest.java359
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/ZooKeeperServerStartupTest.java107
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/ZooKeeperServerTest.java56
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/ZooKeeperThreadTest.java17
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/ZxidRolloverTest.java91
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/admin/CommandResponseTest.java13
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/admin/CommandsTest.java161
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/admin/JettyAdminServerTest.java130
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/metric/AvgMinMaxCounterSetTest.java56
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/metric/AvgMinMaxPercentileCounterSetTest.java94
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/metric/AvgMinMaxPercentileCounterTest.java52
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/persistence/EmptySnapshotTest.java46
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/persistence/FileTxnLogTest.java442
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/persistence/FileTxnSnapLogMetricsTest.java43
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/persistence/FileTxnSnapLogTest.java117
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/persistence/SnapStreamTest.java56
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/persistence/TxnLogToolkitTest.java28
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/BufferStatsTest.java7
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/CnxManagerTest.java259
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/CommitProcessorConcurrencyTest.java390
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/CommitProcessorMetricsTest.java204
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/CommitProcessorTest.java222
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/DelayRequestProcessor.java6
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/EagerACLFilterTest.java102
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/EphemeralNodeDeletionTest.java95
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/FLEBackwardElectionRoundTest.java44
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/FLELostMessageTest.java33
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/FLEOutOfElectionTest.java45
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/FLETestUtils.java22
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/FuzzySnapshotRelatedTest.java124
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/LeaderBeanTest.java46
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/LeaderMetricsTest.java44
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/LeaderWithObserverTest.java100
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/LearnerHandlerMetricsTest.java52
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/LearnerHandlerTest.java68
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/LearnerMetricsTest.java43
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/LearnerSyncThrottlerTest.java51
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/LearnerTest.java82
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/LocalPeerBeanTest.java5
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/QuorumBeanTest.java7
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/QuorumPeerConfigTest.java38
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/QuorumPeerMainTest.java852
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/QuorumPeerTest.java24
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/QuorumPeerTestBase.java135
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/QuorumRequestPipelineTest.java87
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/QuorumSSLTest.java386
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/QuorumServerTest.java62
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/RaceConditionTest.java52
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/ReconfigBackupTest.java168
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/ReconfigDuringLeaderSyncTest.java61
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/ReconfigFailureCasesTest.java61
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/ReconfigLegacyTest.java114
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/ReconfigRecoveryTest.java269
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/ReconfigRollingRestartCompatibilityTest.java92
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/RemotePeerBeanTest.java6
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/SessionUpgradeQuorumTest.java102
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/StandaloneDisabledTest.java96
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/StatCommandTest.java22
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/StatResetCommandTest.java22
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/SyncRequestProcessorMetricTest.java66
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/UnifiedServerSocketModeDetectionTest.java107
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/UnifiedServerSocketTest.java161
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/WatchLeakTest.java53
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/Zab1_0Test.java750
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/ZabUtils.java58
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/auth/KerberosSecurityTestcase.java24
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/auth/KerberosTestUtils.java16
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/auth/MiniKdc.java82
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/auth/MiniKdcTest.java102
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/auth/QuorumAuthTestBase.java57
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/auth/QuorumAuthUpgradeTest.java78
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/auth/QuorumDigestAuthTest.java97
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/auth/QuorumKerberosAuthTest.java52
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/auth/QuorumKerberosHostBasedAuthTest.java91
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/util/AdHashTest.java28
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/util/BitHashSetTest.java74
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/util/BitMapTest.java41
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/util/ConfigUtilsTest.java26
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/util/JvmPauseMonitorTest.java26
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/util/PortForwarder.java91
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/util/RequestPathMetricsCollectorTest.java397
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/util/SerializeUtilsTest.java27
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/util/VerifyingFileFactoryTest.java20
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/watch/WatchManagerTest.java143
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/watch/WatcherCleanerTest.java69
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/watch/WatcherOrBitSetTest.java34
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/watch/WatchesPathReportTest.java20
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/watch/WatchesReportTest.java20
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/server/watch/WatchesSummaryTest.java14
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/test/ACLCountTest.java58
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/test/ACLRootTest.java34
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/test/ACLTest.java104
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/test/AsyncHammerTest.java78
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/test/AsyncOps.java337
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/test/AsyncOpsTest.java17
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/test/AsyncTest.java52
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/test/AtomicFileOutputStreamTest.java10
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/test/AuthTest.java109
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/test/BufferSizeTest.java43
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/test/ChrootAsyncTest.java13
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/test/ChrootClientTest.java15
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/test/ChrootTest.java77
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/test/ClientBase.java221
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/test/ClientHammerTest.java82
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/test/ClientPortBindTest.java54
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/test/ClientRetryTest.java15
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/test/ClientSSLTest.java19
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/test/ClientSkipACLTest.java10
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/test/ClientTest.java458
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/test/ConnectStringParserTest.java76
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/test/CreateModeTest.java71
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/test/CreateTest.java170
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/test/DisconnectableZooKeeper.java17
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/test/DisconnectedWatcherTest.java133
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/test/DuplicateLocalSessionUpgradeTest.java30
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/test/EmptiedSnapshotRecoveryTest.java42
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/test/EnsembleAuthTest.java11
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/test/EventTypeTest.java19
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/test/FLENewEpochTest.java126
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/test/FLEPredicateTest.java79
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/test/FLERestartTest.java66
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/test/FLETest.java287
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/test/FLEZeroWeightTest.java90
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/test/FollowerResyncConcurrencyTest.java288
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/test/FourLetterWordsQuorumTest.java31
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/test/FourLetterWordsTest.java66
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/test/FourLetterWordsWhiteListTest.java48
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/test/GetChildren2Test.java95
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/test/GetProposalFromTxnTest.java30
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/test/HierarchicalQuorumTest.java165
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/test/IntegrityCheck.java78
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/test/InvalidSnapshotTest.java31
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/test/JMXEnv.java117
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/test/KeeperStateTest.java24
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/test/KeyAuthClientTest.java18
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/test/LeaderSessionTrackerTest.java39
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/test/LoadFromLogNoServerTest.java92
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/test/LoadFromLogTest.java124
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/test/LocalSessionRequestTest.java33
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/test/LocalSessionsOnlyTest.java44
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/test/LogChopperTest.java41
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/test/MaxCnxnsTest.java38
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/test/MultiAsyncTransactionTest.java40
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/test/MultiOperationTest.java546
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/test/NIOConnectionFactoryFdLeakTest.java19
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/test/NettyNettySuiteBase.java10
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/test/NettyNettySuiteHammerTest.java7
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/test/NettyNettySuiteTest.java15
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/test/NioNettySuiteBase.java7
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/test/NioNettySuiteHammerTest.java7
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/test/NioNettySuiteTest.java15
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/test/NonRecoverableErrorTest.java62
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/test/NullDataTest.java31
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/test/OOMTest.java90
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/test/OSMXBeanTest.java30
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/test/ObserverHierarchicalQuorumTest.java4
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/test/ObserverLETest.java25
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/test/ObserverMasterTest.java441
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/test/ObserverQuorumHammerTest.java8
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/test/ObserverTest.java39
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/test/QuorumBase.java185
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/test/QuorumHammerTest.java5
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/test/QuorumMajorityTest.java81
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/test/QuorumQuotaTest.java31
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/test/QuorumTest.java219
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/test/QuorumUtil.java80
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/test/QuorumUtilTest.java20
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/test/QuorumZxidSyncTest.java42
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/test/ReadOnlyModeTest.java129
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/test/ReconfigExceptionTest.java69
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/test/ReconfigMisconfigTest.java45
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/test/ReconfigTest.java659
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/test/RecoveryTest.java89
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/test/RepeatStartupTest.java22
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/test/ResponseCacheTest.java39
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/test/RestoreCommittedLogTest.java33
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/test/SSLAuthTest.java22
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/test/SaslAuthDesignatedClientTest.java175
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/test/SaslAuthDesignatedServerTest.java39
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/test/SaslAuthFailDesignatedClientTest.java65
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/test/SaslAuthFailTest.java55
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/test/SaslAuthMissingClientConfigTest.java43
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/test/SaslAuthRequiredFailNoSASLTest.java64
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/test/SaslAuthRequiredFailWrongSASLTest.java68
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/test/SaslAuthRequiredTest.java60
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/test/SaslClientTest.java30
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/test/SaslSuperUserTest.java71
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/test/SaslTestUtil.java74
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/test/ServerCnxnTest.java33
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/test/SessionInvalidationTest.java25
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/test/SessionTest.java230
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/test/SessionTimeoutTest.java51
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/test/SessionTrackerCheckTest.java58
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/test/SessionUpgradeTest.java95
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/test/SledgeHammer.java29
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/test/StandaloneTest.java61
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/test/StatTest.java156
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/test/StaticHostProviderTest.java185
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/test/StringUtilTest.java10
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/test/SyncCallTest.java91
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/test/TestByteBufAllocator.java44
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/test/TestByteBufAllocatorTestHelper.java15
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/test/TestHammer.java40
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/test/TestUtils.java18
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/test/TruncateTest.java82
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/test/WatchEventWhenAutoResetTest.java54
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/test/WatchedEventTest.java81
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/test/WatcherFuncTest.java253
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/test/WatcherTest.java238
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/test/X509AuthTest.java76
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/test/ZkDatabaseCorruptionTest.java91
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/test/ZooKeeperQuotaTest.java80
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/test/ZooKeeperTestClient.java773
-rw-r--r--zookeeper-server/src/test/java/org/apache/zookeeper/util/PemReaderTest.java48
296 files changed, 12213 insertions, 13788 deletions
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/ClientCanonicalizeTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/ClientCanonicalizeTest.java
index 91dec23b6..799af3a2f 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/ClientCanonicalizeTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/ClientCanonicalizeTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -15,17 +15,18 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
package org.apache.zookeeper;
+import static org.junit.Assert.assertEquals;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
import java.io.IOException;
import org.apache.zookeeper.client.ZKClientConfig;
-import org.junit.Assert;
import org.junit.Test;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.when;
-
public class ClientCanonicalizeTest extends ZKTestCase {
+
@Test
public void testClientCanonicalization() throws IOException, InterruptedException {
SaslServerPrincipal.WrapperInetSocketAddress addr = mock(SaslServerPrincipal.WrapperInetSocketAddress.class);
@@ -38,7 +39,7 @@ public class ClientCanonicalizeTest extends ZKTestCase {
ZKClientConfig conf = new ZKClientConfig();
String principal = SaslServerPrincipal.getServerPrincipal(addr, conf);
- Assert.assertEquals("The computed principal does not appear to have been canonicalized", "zookeeper/zk1.apache.org", principal);
+ assertEquals("The computed principal does not appear to have been canonicalized", "zookeeper/zk1.apache.org", principal);
}
@Test
@@ -54,8 +55,7 @@ public class ClientCanonicalizeTest extends ZKTestCase {
ZKClientConfig conf = new ZKClientConfig();
conf.setProperty(ZKClientConfig.ZK_SASL_CLIENT_CANONICALIZE_HOSTNAME, "false");
String principal = SaslServerPrincipal.getServerPrincipal(addr, conf);
- Assert.assertEquals("The computed principal does appears to have been canonicalized incorrectly", "zookeeper/zookeeper.apache.org",
- principal);
+ assertEquals("The computed principal does appears to have been canonicalized incorrectly", "zookeeper/zookeeper.apache.org", principal);
}
@Test
@@ -70,7 +70,7 @@ public class ClientCanonicalizeTest extends ZKTestCase {
ZKClientConfig conf = new ZKClientConfig();
String principal = SaslServerPrincipal.getServerPrincipal(addr, conf);
- Assert.assertEquals("The computed principal does appear to have falled back to the original host name",
- "zookeeper/zookeeper.apache.org", principal);
+ assertEquals("The computed principal does appear to have falled back to the original host name", "zookeeper/zookeeper.apache.org", principal);
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/ClientCnxnSocketTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/ClientCnxnSocketTest.java
index 0550bcfd4..310d34fce 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/ClientCnxnSocketTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/ClientCnxnSocketTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -15,21 +15,21 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
package org.apache.zookeeper;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
-
import java.io.IOException;
-
import org.apache.zookeeper.client.ZKClientConfig;
-import org.apache.zookeeper.test.TestByteBufAllocator;
import org.apache.zookeeper.common.ZKConfig;
+import org.apache.zookeeper.test.TestByteBufAllocator;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class ClientCnxnSocketTest {
+
@Before
public void setUp() {
ClientCnxnSocketNetty.setTestAllocator(TestByteBufAllocator.getInstance());
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/ClientReconnectTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/ClientReconnectTest.java
index 48775347a..e77283c84 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/ClientReconnectTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/ClientReconnectTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -15,36 +15,35 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package org.apache.zookeeper;
+package org.apache.zookeeper;
+import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
-
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SocketChannel;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
-
-import org.apache.zookeeper.client.ZKClientConfig;
import org.apache.zookeeper.client.HostProvider;
-import org.junit.Assert;
+import org.apache.zookeeper.client.ZKClientConfig;
import org.junit.Test;
public class ClientReconnectTest extends ZKTestCase {
+
private SocketChannel sc;
private CountDownLatch countDownLatch = new CountDownLatch(3);
-
+
class MockCnxn extends ClientCnxnSocketNIO {
+
MockCnxn() throws IOException {
super(new ZKClientConfig());
}
@Override
- void registerAndConnect(SocketChannel sock, InetSocketAddress addr) throws
- IOException {
+ void registerAndConnect(SocketChannel sock, InetSocketAddress addr) throws IOException {
countDownLatch.countDown();
throw new IOException("failed to register");
}
@@ -53,6 +52,7 @@ public class ClientReconnectTest extends ZKTestCase {
SocketChannel createSock() {
return sc;
}
+
}
@Test
@@ -63,16 +63,15 @@ public class ClientReconnectTest extends ZKTestCase {
when(hostProvider.next(anyLong())).thenReturn(inaddr);
ZooKeeper zk = mock(ZooKeeper.class);
when(zk.getClientConfig()).thenReturn(new ZKClientConfig());
- sc = SocketChannel.open();
+ sc = SocketChannel.open();
ClientCnxnSocketNIO nioCnxn = new MockCnxn();
ClientWatchManager watcher = mock(ClientWatchManager.class);
- ClientCnxn clientCnxn = new ClientCnxn(
- "tmp", hostProvider, 5000,
- zk, watcher, nioCnxn, false);
+ ClientCnxn clientCnxn = new ClientCnxn("tmp", hostProvider, 5000, zk, watcher, nioCnxn, false);
clientCnxn.start();
countDownLatch.await(5000, TimeUnit.MILLISECONDS);
- Assert.assertTrue(countDownLatch.getCount() == 0);
+ assertTrue(countDownLatch.getCount() == 0);
clientCnxn.close();
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/ClientRequestTimeoutTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/ClientRequestTimeoutTest.java
index 8fcc371ac..7c3bf5198 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/ClientRequestTimeoutTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/ClientRequestTimeoutTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -20,19 +20,18 @@ package org.apache.zookeeper;
import static org.apache.zookeeper.test.ClientBase.CONNECTION_TIMEOUT;
import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
-
import java.io.IOException;
-
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.client.HostProvider;
import org.apache.zookeeper.server.quorum.QuorumPeerTestBase;
import org.apache.zookeeper.test.ClientBase;
import org.apache.zookeeper.test.ClientBase.CountdownWatcher;
-import org.junit.Assert;
import org.junit.Test;
public class ClientRequestTimeoutTest extends QuorumPeerTestBase {
+
private static final int SERVER_COUNT = 3;
private boolean dropPacket = false;
private int dropPacketType = ZooDefs.OpCode.create;
@@ -40,44 +39,39 @@ public class ClientRequestTimeoutTest extends QuorumPeerTestBase {
@Test(timeout = 120000)
public void testClientRequestTimeout() throws Exception {
int requestTimeOut = 15000;
- System.setProperty("zookeeper.request.timeout",
- Integer.toString(requestTimeOut));
- final int clientPorts[] = new int[SERVER_COUNT];
+ System.setProperty("zookeeper.request.timeout", Integer.toString(requestTimeOut));
+ final int[] clientPorts = new int[SERVER_COUNT];
StringBuilder sb = new StringBuilder();
String server;
for (int i = 0; i < SERVER_COUNT; i++) {
clientPorts[i] = PortAssignment.unique();
- server = "server." + i + "=127.0.0.1:" + PortAssignment.unique()
- + ":" + PortAssignment.unique() + ":participant;127.0.0.1:"
- + clientPorts[i];
+ server = "server." + i + "=127.0.0.1:" + PortAssignment.unique() + ":" + PortAssignment.unique()
+ + ":participant;127.0.0.1:" + clientPorts[i];
sb.append(server + "\n");
}
String currentQuorumCfgSection = sb.toString();
- MainThread mt[] = new MainThread[SERVER_COUNT];
+ MainThread[] mt = new MainThread[SERVER_COUNT];
for (int i = 0; i < SERVER_COUNT; i++) {
- mt[i] = new MainThread(i, clientPorts[i], currentQuorumCfgSection,
- false);
+ mt[i] = new MainThread(i, clientPorts[i], currentQuorumCfgSection, false);
mt[i].start();
}
// ensure server started
for (int i = 0; i < SERVER_COUNT; i++) {
- Assert.assertTrue("waiting for server " + i + " being up",
- ClientBase.waitForServerUp("127.0.0.1:" + clientPorts[i],
- CONNECTION_TIMEOUT));
+ assertTrue(
+ "waiting for server " + i + " being up",
+ ClientBase.waitForServerUp("127.0.0.1:" + clientPorts[i], CONNECTION_TIMEOUT));
}
CountdownWatcher watch1 = new CountdownWatcher();
- CustomZooKeeper zk = new CustomZooKeeper(getCxnString(clientPorts),
- ClientBase.CONNECTION_TIMEOUT, watch1);
+ CustomZooKeeper zk = new CustomZooKeeper(getCxnString(clientPorts), ClientBase.CONNECTION_TIMEOUT, watch1);
watch1.waitForConnected(ClientBase.CONNECTION_TIMEOUT);
String data = "originalData";
// lets see one successful operation
- zk.create("/clientHang1", data.getBytes(), Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT_SEQUENTIAL);
+ zk.create("/clientHang1", data.getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL);
// now make environment for client hang
dropPacket = true;
@@ -85,12 +79,10 @@ public class ClientRequestTimeoutTest extends QuorumPeerTestBase {
// Test synchronous API
try {
- zk.create("/clientHang2", data.getBytes(), Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk.create("/clientHang2", data.getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
fail("KeeperException is expected.");
} catch (KeeperException exception) {
- assertEquals(KeeperException.Code.REQUESTTIMEOUT.intValue(),
- exception.code().intValue());
+ assertEquals(KeeperException.Code.REQUESTTIMEOUT.intValue(), exception.code().intValue());
}
// do cleanup
@@ -118,12 +110,15 @@ public class ClientRequestTimeoutTest extends QuorumPeerTestBase {
class CustomClientCnxn extends ClientCnxn {
- public CustomClientCnxn(String chrootPath, HostProvider hostProvider,
- int sessionTimeout, ZooKeeper zooKeeper,
- ClientWatchManager watcher, ClientCnxnSocket clientCnxnSocket,
- boolean canBeReadOnly) throws IOException {
- super(chrootPath, hostProvider, sessionTimeout, zooKeeper, watcher,
- clientCnxnSocket, canBeReadOnly);
+ public CustomClientCnxn(
+ String chrootPath,
+ HostProvider hostProvider,
+ int sessionTimeout,
+ ZooKeeper zooKeeper,
+ ClientWatchManager watcher,
+ ClientCnxnSocket clientCnxnSocket,
+ boolean canBeReadOnly) throws IOException {
+ super(chrootPath, hostProvider, sessionTimeout, zooKeeper, watcher, clientCnxnSocket, canBeReadOnly);
}
@Override
@@ -135,23 +130,27 @@ public class ClientRequestTimeoutTest extends QuorumPeerTestBase {
}
super.finishPacket(p);
}
+
}
class CustomZooKeeper extends ZooKeeper {
- public CustomZooKeeper(String connectString, int sessionTimeout,
- Watcher watcher) throws IOException {
+
+ public CustomZooKeeper(String connectString, int sessionTimeout, Watcher watcher) throws IOException {
super(connectString, sessionTimeout, watcher);
}
@Override
- protected ClientCnxn createConnection(String chrootPath,
- HostProvider hostProvider, int sessionTimeout,
- ZooKeeper zooKeeper, ClientWatchManager watcher,
- ClientCnxnSocket clientCnxnSocket, boolean canBeReadOnly)
- throws IOException {
- return new CustomClientCnxn(chrootPath, hostProvider,
- sessionTimeout, zooKeeper, watcher, clientCnxnSocket,
- canBeReadOnly);
+ protected ClientCnxn createConnection(
+ String chrootPath,
+ HostProvider hostProvider,
+ int sessionTimeout,
+ ZooKeeper zooKeeper,
+ ClientWatchManager watcher,
+ ClientCnxnSocket clientCnxnSocket,
+ boolean canBeReadOnly) throws IOException {
+ return new CustomClientCnxn(chrootPath, hostProvider, sessionTimeout, zooKeeper, watcher, clientCnxnSocket, canBeReadOnly);
}
+
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/CustomHostProviderTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/CustomHostProviderTest.java
index f9762d249..e53fec071 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/CustomHostProviderTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/CustomHostProviderTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -15,21 +15,24 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
package org.apache.zookeeper;
-import org.apache.zookeeper.client.HostProvider;
-import org.apache.zookeeper.test.ClientBase;
-import org.junit.Assert;
-import org.junit.Test;
+import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.Collection;
import java.util.concurrent.atomic.AtomicInteger;
+import org.apache.zookeeper.client.HostProvider;
+import org.apache.zookeeper.test.ClientBase;
+import org.junit.Test;
public class CustomHostProviderTest extends ZKTestCase implements Watcher {
+
private AtomicInteger counter = new AtomicInteger(3);
private class SpecialHostProvider implements HostProvider {
+
// ignores its connectstring, and next() always returns localhost:2181
// it will count down when updateServerList() is called
@Override
@@ -44,36 +47,39 @@ public class CustomHostProviderTest extends ZKTestCase implements Watcher {
public void onConnected() {
}
@Override
- public boolean updateServerList(Collection<InetSocketAddress>
- serverAddresses, InetSocketAddress currentHost) {
+ public boolean updateServerList(Collection<InetSocketAddress> serverAddresses, InetSocketAddress currentHost) {
counter.decrementAndGet();
return false;
}
+
}
@Override
public void process(WatchedEvent event) {
}
@Test
- public void testZooKeeperWithCustomHostProvider() throws IOException,
- InterruptedException {
+ public void testZooKeeperWithCustomHostProvider() throws IOException, InterruptedException {
final int CLIENT_PORT = PortAssignment.unique();
final HostProvider specialHostProvider = new SpecialHostProvider();
int expectedCounter = 3;
counter.set(expectedCounter);
- ZooKeeper zkDefaults = new ZooKeeper("127.0.0.1:" + CLIENT_PORT,
- ClientBase.CONNECTION_TIMEOUT, this, false);
+ ZooKeeper zkDefaults = new ZooKeeper("127.0.0.1:" + CLIENT_PORT, ClientBase.CONNECTION_TIMEOUT, this, false);
- ZooKeeper zkSpecial = new ZooKeeper("127.0.0.1:" + CLIENT_PORT,
- ClientBase.CONNECTION_TIMEOUT, this, false, specialHostProvider);
+ ZooKeeper zkSpecial = new ZooKeeper(
+ "127.0.0.1:" + CLIENT_PORT,
+ ClientBase.CONNECTION_TIMEOUT,
+ this,
+ false,
+ specialHostProvider);
- Assert.assertTrue(counter.get() == expectedCounter);
+ assertTrue(counter.get() == expectedCounter);
zkDefaults.updateServerList("127.0.0.1:" + PortAssignment.unique());
- Assert.assertTrue(counter.get() == expectedCounter);
+ assertTrue(counter.get() == expectedCounter);
zkSpecial.updateServerList("127.0.0.1:" + PortAssignment.unique());
expectedCounter--;
- Assert.assertTrue(counter.get() == expectedCounter);
+ assertTrue(counter.get() == expectedCounter);
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/GetAllChildrenNumberTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/GetAllChildrenNumberTest.java
index 0536a43b8..b13ceafc1 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/GetAllChildrenNumberTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/GetAllChildrenNumberTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,16 +18,17 @@
package org.apache.zookeeper;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.fail;
import java.io.IOException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
-
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.test.ClientBase;
-import org.junit.Assert;
import org.junit.Test;
public class GetAllChildrenNumberTest extends ClientBase {
+
private static final String BASE = "/getAllChildrenNumberTest";
private static final String BASE_EXT = BASE + "EXT";
private static final int PERSISTENT_CNT = 2;
@@ -55,17 +56,17 @@ public class GetAllChildrenNumberTest extends ClientBase {
//a bad case
try {
zk.getAllChildrenNumber(null);
- Assert.fail("the path for getAllChildrenNumber must not be null.");
+ fail("the path for getAllChildrenNumber must not be null.");
} catch (IllegalArgumentException e) {
//expected
}
- Assert.assertEquals(EPHEMERAL_CNT, zk.getAllChildrenNumber(BASE + "/0"));
- Assert.assertEquals(0, zk.getAllChildrenNumber(BASE + "/0/ephem0"));
- Assert.assertEquals(0, zk.getAllChildrenNumber(BASE_EXT));
- Assert.assertEquals(PERSISTENT_CNT + PERSISTENT_CNT * EPHEMERAL_CNT, zk.getAllChildrenNumber(BASE));
+ assertEquals(EPHEMERAL_CNT, zk.getAllChildrenNumber(BASE + "/0"));
+ assertEquals(0, zk.getAllChildrenNumber(BASE + "/0/ephem0"));
+ assertEquals(0, zk.getAllChildrenNumber(BASE_EXT));
+ assertEquals(PERSISTENT_CNT + PERSISTENT_CNT * EPHEMERAL_CNT, zk.getAllChildrenNumber(BASE));
// 6(EPHEMERAL) + 2(PERSISTENT) + 3("/zookeeper,/zookeeper/quota,/zookeeper/config") + 1(BASE_EXT) + 1(BASE) = 13
- Assert.assertEquals(13, zk.getAllChildrenNumber("/"));
+ assertEquals(13, zk.getAllChildrenNumber("/"));
}
@Test
@@ -77,36 +78,31 @@ public class GetAllChildrenNumberTest extends ClientBase {
@Override
public void processResult(int rc, String path, Object ctx, int number) {
if (path == null) {
- Assert.fail((String.format("the path of getAllChildrenNumber was null.")));
+ fail((String.format("the path of getAllChildrenNumber was null.")));
}
- Assert.assertEquals(13, number);
+ assertEquals(13, number);
doneProcessing.countDown();
}
}, null);
long waitForCallbackSecs = 2L;
if (!doneProcessing.await(waitForCallbackSecs, TimeUnit.SECONDS)) {
- Assert.fail(String.format("getAllChildrenNumber didn't callback within %d seconds",
- waitForCallbackSecs));
+ fail(String.format("getAllChildrenNumber didn't callback within %d seconds", waitForCallbackSecs));
}
}
- private void generatePaths(int persistantCnt, int ephemeralCnt)
- throws KeeperException, InterruptedException {
+ private void generatePaths(int persistantCnt, int ephemeralCnt) throws KeeperException, InterruptedException {
- zk.create(BASE, BASE.getBytes(), Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
- zk.create(BASE_EXT, BASE_EXT.getBytes(), Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk.create(BASE, BASE.getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
+ zk.create(BASE_EXT, BASE_EXT.getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
for (int p = 0; p < persistantCnt; p++) {
String base = BASE + "/" + p;
- zk.create(base, base.getBytes(), Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk.create(base, base.getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
for (int e = 0; e < ephemeralCnt; e++) {
String ephem = base + "/ephem" + e;
- zk.create(ephem, ephem.getBytes(), Ids.OPEN_ACL_UNSAFE,
- CreateMode.EPHEMERAL);
+ zk.create(ephem, ephem.getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
}
}
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/GetEphemeralsTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/GetEphemeralsTest.java
index 355223fc6..6d4dea10c 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/GetEphemeralsTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/GetEphemeralsTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,22 +18,20 @@
package org.apache.zookeeper;
-import org.apache.zookeeper.AsyncCallback;
-import org.apache.zookeeper.CreateMode;
-import org.apache.zookeeper.KeeperException;
-import org.apache.zookeeper.ZooDefs.Ids;
-import org.apache.zookeeper.ZooKeeper;
-import org.apache.zookeeper.test.ClientBase;
-import org.junit.Assert;
-import org.junit.Test;
-
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
+import org.apache.zookeeper.ZooDefs.Ids;
+import org.apache.zookeeper.test.ClientBase;
+import org.junit.Test;
public class GetEphemeralsTest extends ClientBase {
+
private static final String BASE = "/base";
private static final int PERSISTENT_CNT = 2;
private static final int EPHEMERAL_CNT = 2;
@@ -59,13 +57,10 @@ public class GetEphemeralsTest extends ClientBase {
@Test
public void testGetEphemeralsSync() throws KeeperException, InterruptedException {
List<String> actual = zk.getEphemerals();
- Assert.assertEquals( "Expected ephemeral count for allPaths",
- actual.size() , expected.length);
+ assertEquals("Expected ephemeral count for allPaths", actual.size(), expected.length);
for (int i = 0; i < expected.length; i++) {
String path = expected[i];
- Assert.assertTrue(
- String.format("Path=%s exists in get All Ephemerals list ", path),
- actual.contains(path));
+ assertTrue(String.format("Path=%s exists in get All Ephemerals list ", path), actual.contains(path));
}
}
@@ -73,54 +68,46 @@ public class GetEphemeralsTest extends ClientBase {
public void testGetEphemeralsSyncByPath() throws KeeperException, InterruptedException {
final String prefixPath = BASE + 0;
List<String> actual = zk.getEphemerals(prefixPath);
- Assert.assertEquals( "Expected ephemeral count for allPaths",
- actual.size() , EPHEMERAL_CNT);
+ assertEquals("Expected ephemeral count for allPaths", actual.size(), EPHEMERAL_CNT);
for (int i = 0; i < EPHEMERAL_CNT; i++) {
String path = expected[i];
- Assert.assertTrue(String.format("Path=%s exists in getEphemerals(%s) list ",
- path, prefixPath), actual.contains(path));
+ assertTrue(String.format("Path=%s exists in getEphemerals(%s) list ", path, prefixPath), actual.contains(path));
}
}
@Test
- public void testGetEphemerals()
- throws IOException, KeeperException, InterruptedException {
+ public void testGetEphemerals() throws IOException, KeeperException, InterruptedException {
final CountDownLatch doneProcessing = new CountDownLatch(1);
final List<String> unexpectedBehavior = new ArrayList<String>();
zk.getEphemerals(new AsyncCallback.EphemeralsCallback() {
@Override
public void processResult(int rc, Object ctx, List<String> paths) {
- if (paths == null ) {
- unexpectedBehavior.add(String.format("Expected ephemeral count for" +
- " allPaths to be %d but was null", expected.length));
+ if (paths == null) {
+ unexpectedBehavior.add(String.format("Expected ephemeral count for"
+ + " allPaths to be %d but was null", expected.length));
} else if (paths.size() != expected.length) {
- unexpectedBehavior.add(
- String.format("Expected ephemeral count for allPaths to be %d but was %d",
- expected.length, paths.size()));
+ unexpectedBehavior.add(String.format("Expected ephemeral count for allPaths to be %d but was %d", expected.length, paths.size()));
}
for (int i = 0; i < expected.length; i++) {
String path = expected[i];
if (!paths.contains(path)) {
- unexpectedBehavior.add(
- String.format("Path=%s exists in getEphemerals list ", path));
+ unexpectedBehavior.add(String.format("Path=%s exists in getEphemerals list ", path));
}
}
doneProcessing.countDown();
}
}, null);
- long waitForCallbackSecs = 2l;
+ long waitForCallbackSecs = 2L;
if (!doneProcessing.await(waitForCallbackSecs, TimeUnit.SECONDS)) {
- Assert.fail(String.format("getEphemerals didn't callback within %d seconds",
- waitForCallbackSecs));
+ fail(String.format("getEphemerals didn't callback within %d seconds", waitForCallbackSecs));
}
checkForUnexpectedBehavior(unexpectedBehavior);
}
@Test
- public void testGetEphemeralsByPath()
- throws IOException, KeeperException, InterruptedException {
+ public void testGetEphemeralsByPath() throws IOException, KeeperException, InterruptedException {
final CountDownLatch doneProcessing = new CountDownLatch(1);
final String checkPath = BASE + "0";
@@ -128,36 +115,30 @@ public class GetEphemeralsTest extends ClientBase {
zk.getEphemerals(checkPath, new AsyncCallback.EphemeralsCallback() {
@Override
public void processResult(int rc, Object ctx, List<String> paths) {
- if (paths == null ) {
- unexpectedBehavior.add(
- String.format("Expected ephemeral count for %s to be %d but was null",
- checkPath, expected.length));
+ if (paths == null) {
+ unexpectedBehavior.add(String.format("Expected ephemeral count for %s to be %d but was null", checkPath, expected.length));
} else if (paths.size() != EPHEMERAL_CNT) {
- unexpectedBehavior.add(
- String.format("Expected ephemeral count for %s to be %d but was %d",
- checkPath, EPHEMERAL_CNT, paths.size()));
+ unexpectedBehavior.add(String.format("Expected ephemeral count for %s to be %d but was %d", checkPath, EPHEMERAL_CNT, paths.size()));
}
for (int i = 0; i < EPHEMERAL_CNT; i++) {
String path = expected[i];
- if(! paths.contains(path)) {
- unexpectedBehavior.add(String.format("Expected path=%s didn't exist " +
- "in getEphemerals list.", path));
+ if (!paths.contains(path)) {
+ unexpectedBehavior.add(String.format("Expected path=%s didn't exist "
+ + "in getEphemerals list.", path));
}
}
doneProcessing.countDown();
}
}, null);
- long waitForCallbackSecs = 2l;
+ long waitForCallbackSecs = 2L;
if (!doneProcessing.await(waitForCallbackSecs, TimeUnit.SECONDS)) {
- Assert.fail(String.format("getEphemerals(%s) didn't callback within %d seconds",
- checkPath, waitForCallbackSecs));
+ fail(String.format("getEphemerals(%s) didn't callback within %d seconds", checkPath, waitForCallbackSecs));
}
checkForUnexpectedBehavior(unexpectedBehavior);
}
@Test
- public void testGetEphemeralsEmpty()
- throws IOException, KeeperException, InterruptedException {
+ public void testGetEphemeralsEmpty() throws IOException, KeeperException, InterruptedException {
final CountDownLatch doneProcessing = new CountDownLatch(1);
final String checkPath = "/unknownPath";
@@ -166,22 +147,17 @@ public class GetEphemeralsTest extends ClientBase {
zk.getEphemerals(checkPath, new AsyncCallback.EphemeralsCallback() {
@Override
public void processResult(int rc, Object ctx, List<String> paths) {
- if (paths == null ) {
- unexpectedBehavior.add(
- String.format("Expected ephemeral count for %s to be %d but was null",
- checkPath, expectedSize));
+ if (paths == null) {
+ unexpectedBehavior.add(String.format("Expected ephemeral count for %s to be %d but was null", checkPath, expectedSize));
} else if (paths.size() != expectedSize) {
- unexpectedBehavior.add(
- String.format("Expected ephemeral count for %s to be %d but was %d",
- checkPath, expectedSize, paths.size()));
+ unexpectedBehavior.add(String.format("Expected ephemeral count for %s to be %d but was %d", checkPath, expectedSize, paths.size()));
}
doneProcessing.countDown();
}
}, null);
- long waitForCallbackSecs = 2l;
+ long waitForCallbackSecs = 2L;
if (!doneProcessing.await(waitForCallbackSecs, TimeUnit.SECONDS)) {
- Assert.fail(String.format("getEphemerals(%s) didn't callback within %d seconds",
- checkPath, waitForCallbackSecs));
+ fail(String.format("getEphemerals(%s) didn't callback within %d seconds", checkPath, waitForCallbackSecs));
}
checkForUnexpectedBehavior(unexpectedBehavior);
}
@@ -190,32 +166,28 @@ public class GetEphemeralsTest extends ClientBase {
public void testGetEphemeralsErrors() throws KeeperException {
try {
zk.getEphemerals(null, null, null);
- Assert.fail("Should have thrown a IllegalArgumentException for a null prefixPath");
+ fail("Should have thrown a IllegalArgumentException for a null prefixPath");
} catch (IllegalArgumentException e) {
//pass
}
try {
zk.getEphemerals("no leading slash", null, null);
- Assert.fail("Should have thrown a IllegalArgumentException " +
- "for a prefix with no leading slash");
+ fail("Should have thrown a IllegalArgumentException " + "for a prefix with no leading slash");
} catch (IllegalArgumentException e) {
//pass
}
}
- private String[] generatePaths(int persistantCnt, int ephemeralCnt)
- throws KeeperException, InterruptedException {
+ private String[] generatePaths(int persistantCnt, int ephemeralCnt) throws KeeperException, InterruptedException {
final String[] expected = new String[persistantCnt * ephemeralCnt];
for (int p = 0; p < persistantCnt; p++) {
String base = BASE + p;
- zk.create(base, base.getBytes(), Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk.create(base, base.getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
for (int e = 0; e < ephemeralCnt; e++) {
String ephem = base + "/ephem" + e;
- zk.create(ephem, ephem.getBytes(), Ids.OPEN_ACL_UNSAFE,
- CreateMode.EPHEMERAL);
+ zk.create(ephem, ephem.getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
expected[p * ephemeralCnt + e] = ephem;
}
}
@@ -229,7 +201,8 @@ public class GetEphemeralsTest extends ClientBase {
for (String error : unexpectedBehavior) {
b.append("ERROR: ").append(error).append(NEWLINE);
}
- Assert.fail(b.toString());
+ fail(b.toString());
}
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/JUnit4ZKTestRunner.java b/zookeeper-server/src/test/java/org/apache/zookeeper/JUnit4ZKTestRunner.java
index 75699a3f1..a5d78c334 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/JUnit4ZKTestRunner.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/JUnit4ZKTestRunner.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,22 +18,23 @@
package org.apache.zookeeper;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
+import java.util.Arrays;
+import java.util.List;
import org.junit.Test;
import org.junit.internal.runners.statements.InvokeMethod;
import org.junit.runners.BlockJUnit4ClassRunner;
import org.junit.runners.model.FrameworkMethod;
import org.junit.runners.model.InitializationError;
import org.junit.runners.model.Statement;
-import java.util.Arrays;
-import java.util.List;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/**
* The sole responsibility of this class is to print to the log when a test
* starts and when it finishes.
*/
public class JUnit4ZKTestRunner extends BlockJUnit4ClassRunner {
+
private static final Logger LOG = LoggerFactory.getLogger(JUnit4ZKTestRunner.class);
public JUnit4ZKTestRunner(Class<?> klass) throws InitializationError {
@@ -41,7 +42,9 @@ public class JUnit4ZKTestRunner extends BlockJUnit4ClassRunner {
}
@SuppressWarnings("unchecked")
- public static List<FrameworkMethod> computeTestMethodsForClass(final Class klass, final List<FrameworkMethod> defaultMethods) {
+ public static List<FrameworkMethod> computeTestMethodsForClass(
+ final Class klass,
+ final List<FrameworkMethod> defaultMethods) {
List<FrameworkMethod> list = defaultMethods;
String methodName = System.getProperty("test.method");
if (methodName == null) {
@@ -57,13 +60,13 @@ public class JUnit4ZKTestRunner extends BlockJUnit4ClassRunner {
return list;
}
-
@Override
protected List<FrameworkMethod> computeTestMethods() {
return computeTestMethodsForClass(getTestClass().getJavaClass(), super.computeTestMethods());
}
public static class LoggedInvokeMethod extends InvokeMethod {
+
private final FrameworkMethod method;
private final String name;
@@ -91,10 +94,10 @@ public class JUnit4ZKTestRunner extends BlockJUnit4ClassRunner {
// expected exception as defined in the @Test annotation.
// Check the annotation and log an appropriate message.
Test annotation = this.method.getAnnotation(Test.class);
- if (annotation != null && annotation.expected() != null &&
- annotation.expected().isAssignableFrom(t.getClass())) {
- LOG.info("TEST METHOD {} THREW EXPECTED EXCEPTION {}", name,
- annotation.expected());
+ if (annotation != null
+ && annotation.expected() != null
+ && annotation.expected().isAssignableFrom(t.getClass())) {
+ LOG.info("TEST METHOD {} THREW EXPECTED EXCEPTION {}", name, annotation.expected());
} else {
LOG.info("TEST METHOD FAILED {}", name, t);
}
@@ -102,10 +105,12 @@ public class JUnit4ZKTestRunner extends BlockJUnit4ClassRunner {
}
LOG.info("FINISHED TEST METHOD {}", name);
}
+
}
@Override
protected Statement methodInvoker(FrameworkMethod method, Object test) {
return new LoggedInvokeMethod(method, test);
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/JaasConfiguration.java b/zookeeper-server/src/test/java/org/apache/zookeeper/JaasConfiguration.java
index bf145d024..aecc7ede1 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/JaasConfiguration.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/JaasConfiguration.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -20,7 +20,6 @@ package org.apache.zookeeper;
import java.util.HashMap;
import java.util.Map;
-
import javax.security.auth.login.AppConfigurationEntry;
import javax.security.auth.login.AppConfigurationEntry.LoginModuleControlFlag;
@@ -35,8 +34,8 @@ import javax.security.auth.login.AppConfigurationEntry.LoginModuleControlFlag;
* "username", "passowrd");
*/
public class JaasConfiguration extends javax.security.auth.login.Configuration {
- private final Map<String, AppConfigurationEntry[]> sections =
- new HashMap<String, AppConfigurationEntry[]>();
+
+ private final Map<String, AppConfigurationEntry[]> sections = new HashMap<String, AppConfigurationEntry[]>();
public JaasConfiguration() {
}
@@ -62,7 +61,7 @@ public class JaasConfiguration extends javax.security.auth.login.Configuration {
* @param loginModuleName Login module name
* @param conf login key/value args
*/
- public void addSection(String name, String loginModuleName, final Map<String,String> conf) {
+ public void addSection(String name, String loginModuleName, final Map<String, String> conf) {
AppConfigurationEntry[] entries = new AppConfigurationEntry[1];
entries[0] = new AppConfigurationEntry(loginModuleName, LoginModuleControlFlag.REQUIRED, conf);
this.sections.put(name, entries);
@@ -72,4 +71,5 @@ public class JaasConfiguration extends javax.security.auth.login.Configuration {
public AppConfigurationEntry[] getAppConfigurationEntry(String appName) {
return sections.get(appName);
}
-} \ No newline at end of file
+
+}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/MockPacket.java b/zookeeper-server/src/test/java/org/apache/zookeeper/MockPacket.java
index f4bb19a5a..9d880fd39 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/MockPacket.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/MockPacket.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,23 +18,30 @@
package org.apache.zookeeper;
-import org.apache.zookeeper.proto.RequestHeader;
-import org.apache.zookeeper.proto.ReplyHeader;
+import java.nio.ByteBuffer;
import org.apache.jute.Record;
import org.apache.zookeeper.ZooKeeper.WatchRegistration;
-import java.nio.ByteBuffer;
+import org.apache.zookeeper.proto.ReplyHeader;
+import org.apache.zookeeper.proto.RequestHeader;
public class MockPacket extends ClientCnxn.Packet {
- public MockPacket(RequestHeader requestHeader, ReplyHeader replyHeader,
- Record request, Record response,
- WatchRegistration watchRegistration) {
+ public MockPacket(
+ RequestHeader requestHeader,
+ ReplyHeader replyHeader,
+ Record request,
+ Record response,
+ WatchRegistration watchRegistration) {
super(requestHeader, replyHeader, request, response, watchRegistration);
}
- public MockPacket(RequestHeader requestHeader, ReplyHeader replyHeader,
- Record request, Record response,
- WatchRegistration watchRegistration, boolean readOnly) {
+ public MockPacket(
+ RequestHeader requestHeader,
+ ReplyHeader replyHeader,
+ Record request,
+ Record response,
+ WatchRegistration watchRegistration,
+ boolean readOnly) {
super(requestHeader, replyHeader, request, response, watchRegistration, readOnly);
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/MultiOperationRecordTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/MultiOperationRecordTest.java
index 122c1ac21..75da5df31 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/MultiOperationRecordTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/MultiOperationRecordTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,17 +18,17 @@
package org.apache.zookeeper;
+import static org.junit.Assert.assertEquals;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.nio.ByteBuffer;
import org.apache.jute.BinaryInputArchive;
import org.apache.jute.BinaryOutputArchive;
import org.apache.zookeeper.server.ByteBufferInputStream;
-import org.junit.Assert;
import org.junit.Test;
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.nio.ByteBuffer;
-
public class MultiOperationRecordTest extends ZKTestCase {
+
@Test
public void testRoundTrip() throws IOException {
MultiOperationRecord request = new MultiOperationRecord();
@@ -39,8 +39,8 @@ public class MultiOperationRecordTest extends ZKTestCase {
MultiOperationRecord decodedRequest = codeDecode(request);
- Assert.assertEquals(request, decodedRequest);
- Assert.assertEquals(request.hashCode(), decodedRequest.hashCode());
+ assertEquals(request, decodedRequest);
+ assertEquals(request.hashCode(), decodedRequest.hashCode());
}
@Test
@@ -48,8 +48,8 @@ public class MultiOperationRecordTest extends ZKTestCase {
MultiOperationRecord request = new MultiOperationRecord();
MultiOperationRecord decodedRequest = codeDecode(request);
- Assert.assertEquals(request, decodedRequest);
- Assert.assertEquals(request.hashCode(), decodedRequest.hashCode());
+ assertEquals(request, decodedRequest);
+ assertEquals(request.hashCode(), decodedRequest.hashCode());
}
private MultiOperationRecord codeDecode(MultiOperationRecord request) throws IOException {
@@ -65,4 +65,5 @@ public class MultiOperationRecordTest extends ZKTestCase {
decodedRequest.deserialize(bia, "request");
return decodedRequest;
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/MultiResponseTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/MultiResponseTest.java
index 75d9a1207..7993d04c3 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/MultiResponseTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/MultiResponseTest.java
@@ -17,18 +17,18 @@
package org.apache.zookeeper;
+import static org.junit.Assert.assertEquals;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.nio.ByteBuffer;
import org.apache.jute.BinaryInputArchive;
import org.apache.jute.BinaryOutputArchive;
import org.apache.zookeeper.data.Stat;
import org.apache.zookeeper.server.ByteBufferInputStream;
-import org.junit.Assert;
import org.junit.Test;
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.nio.ByteBuffer;
-
public class MultiResponseTest extends ZKTestCase {
+
public void testRoundTrip() throws IOException {
MultiResponse response = new MultiResponse();
@@ -42,8 +42,8 @@ public class MultiResponseTest extends ZKTestCase {
MultiResponse decodedResponse = codeDecode(response);
- Assert.assertEquals(response, decodedResponse);
- Assert.assertEquals(response.hashCode(), decodedResponse.hashCode());
+ assertEquals(response, decodedResponse);
+ assertEquals(response.hashCode(), decodedResponse.hashCode());
}
@Test
@@ -51,8 +51,8 @@ public class MultiResponseTest extends ZKTestCase {
MultiResponse result = new MultiResponse();
MultiResponse decodedResult = codeDecode(result);
- Assert.assertEquals(result, decodedResult);
- Assert.assertEquals(result.hashCode(), decodedResult.hashCode());
+ assertEquals(result, decodedResult);
+ assertEquals(result.hashCode(), decodedResult.hashCode());
}
private MultiResponse codeDecode(MultiResponse request) throws IOException {
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/PortAssignment.java b/zookeeper-server/src/test/java/org/apache/zookeeper/PortAssignment.java
index d3008696c..22a12a64a 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/PortAssignment.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/PortAssignment.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -22,12 +22,12 @@ import java.io.IOException;
import java.net.ServerSocket;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
-
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** Assign ports to tests */
public final class PortAssignment {
+
private static final Logger LOG = LoggerFactory.getLogger(PortAssignment.class);
// The available port range that we use stays away from the ephemeral port
@@ -61,24 +61,24 @@ public final class PortAssignment {
*
* @return port
*/
- public synchronized static int unique() {
+ public static synchronized int unique() {
if (portRange == null) {
Integer threadId = Integer.getInteger("zookeeper.junit.threadid");
- portRange = setupPortRange(System.getProperty("test.junit.threads"),
- threadId != null ? "threadid=" + threadId :
- System.getProperty("sun.java.command"));
+ portRange = setupPortRange(
+ System.getProperty("test.junit.threads"),
+ threadId != null ? "threadid=" + threadId : System.getProperty("sun.java.command"));
nextPort = portRange.getMinimum();
}
int candidatePort = nextPort;
- for (;;) {
+ for (; ; ) {
++candidatePort;
if (candidatePort > portRange.getMaximum()) {
candidatePort = portRange.getMinimum();
}
if (candidatePort == nextPort) {
throw new IllegalStateException(String.format(
- "Could not assign port from range %s. The entire " +
- "range has been exhausted.", portRange));
+ "Could not assign port from range %s. The entire range has been exhausted.",
+ portRange));
}
try {
ServerSocket s = new ServerSocket(candidatePort);
@@ -87,8 +87,8 @@ public final class PortAssignment {
LOG.info("Assigned port {} from range {}.", nextPort, portRange);
return nextPort;
} catch (IOException e) {
- LOG.debug("Could not bind to port {} from range {}. " +
- "Attempting next port.", candidatePort, portRange, e);
+ LOG.debug("Could not bind to port {} from range {}. Attempting next port.",
+ candidatePort, portRange, e);
}
}
}
@@ -120,8 +120,7 @@ public final class PortAssignment {
try {
processCount = Integer.valueOf(strProcessCount);
} catch (NumberFormatException e) {
- LOG.warn("Error parsing test.junit.threads = {}.",
- strProcessCount, e);
+ LOG.warn("Error parsing test.junit.threads = {}.", strProcessCount, e);
}
}
@@ -145,13 +144,11 @@ public final class PortAssignment {
// Use these values to calculate the valid range for port assignments
// within this test process. We lose a few possible ports to the
// remainder, but that's acceptable.
- int portRangeSize = (GLOBAL_MAX_PORT - GLOBAL_BASE_PORT) /
- processCount;
+ int portRangeSize = (GLOBAL_MAX_PORT - GLOBAL_BASE_PORT) / processCount;
int minPort = GLOBAL_BASE_PORT + ((threadId - 1) * portRangeSize);
int maxPort = minPort + portRangeSize - 1;
newPortRange = new PortRange(minPort, maxPort);
- LOG.info("Test process {}/{} using ports from {}.", threadId,
- processCount, newPortRange);
+ LOG.info("Test process {}/{} using ports from {}.", threadId, processCount, newPortRange);
} else {
// If running outside the context of Ant or Ant is using a single
// test process, then use all valid ports.
@@ -166,6 +163,7 @@ public final class PortAssignment {
* Contains the minimum and maximum (both inclusive) in a range of ports.
*/
static final class PortRange {
+
private final int minimum;
private final int maximum;
@@ -202,6 +200,7 @@ public final class PortAssignment {
public String toString() {
return String.format("%d - %d", minimum, maximum);
}
+
}
/**
@@ -209,4 +208,5 @@ public final class PortAssignment {
*/
private PortAssignment() {
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/PortAssignmentTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/PortAssignmentTest.java
index 28691c673..234adb1b7 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/PortAssignmentTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/PortAssignmentTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -19,14 +19,12 @@
package org.apache.zookeeper;
import static org.junit.Assert.assertEquals;
-
import java.util.Arrays;
import java.util.Collection;
-
+import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
-import org.junit.Test;
@RunWith(Parameterized.class)
@Parameterized.UseParametersRunnerFactory(ZKParameterized.RunnerFactory.class)
@@ -39,24 +37,23 @@ public class PortAssignmentTest {
@Parameters
public static Collection<Object[]> data() {
- return Arrays.<Object[]>asList(
- new Object[] { "8", "threadid=1", 11221, 13913 },
- new Object[] { "8", "threadid=2", 13914, 16606 },
- new Object[] { "8", "threadid=3", 16607, 19299 },
- new Object[] { "8", "threadid=4", 19300, 21992 },
- new Object[] { "8", "threadid=5", 21993, 24685 },
- new Object[] { "8", "threadid=6", 24686, 27378 },
- new Object[] { "8", "threadid=7", 27379, 30071 },
- new Object[] { "8", "threadid=8", 30072, 32764 },
- new Object[] { "1", "threadid=1", 11221, 32767 },
- new Object[] { "2", "threadid=1", 11221, 21993 },
- new Object[] { "2", "threadid=2", 21994, 32766 },
- new Object[] { null, null, 11221, 32767 },
- new Object[] { "", "", 11221, 32767 });
+ return Arrays.asList(
+ new Object[]{"8", "threadid=1", 11221, 13913},
+ new Object[]{"8", "threadid=2", 13914, 16606},
+ new Object[]{"8", "threadid=3", 16607, 19299},
+ new Object[]{"8", "threadid=4", 19300, 21992},
+ new Object[]{"8", "threadid=5", 21993, 24685},
+ new Object[]{"8", "threadid=6", 24686, 27378},
+ new Object[]{"8", "threadid=7", 27379, 30071},
+ new Object[]{"8", "threadid=8", 30072, 32764},
+ new Object[]{"1", "threadid=1", 11221, 32767},
+ new Object[]{"2", "threadid=1", 11221, 21993},
+ new Object[]{"2", "threadid=2", 21994, 32766},
+ new Object[]{null, null, 11221, 32767},
+ new Object[]{"", "", 11221, 32767});
}
- public PortAssignmentTest(String strProcessCount, String cmdLine,
- int expectedMinimumPort, int expectedMaximumPort) {
+ public PortAssignmentTest(String strProcessCount, String cmdLine, int expectedMinimumPort, int expectedMaximumPort) {
this.strProcessCount = strProcessCount;
this.cmdLine = cmdLine;
this.expectedMinimumPort = expectedMinimumPort;
@@ -65,16 +62,13 @@ public class PortAssignmentTest {
@Test
public void testSetupPortRange() {
- PortAssignment.PortRange portRange = PortAssignment.setupPortRange(
- strProcessCount, cmdLine);
- assertEquals(buildAssertionMessage("minimum"), expectedMinimumPort,
- portRange.getMinimum());
- assertEquals(buildAssertionMessage("maximum"), expectedMaximumPort,
- portRange.getMaximum());
+ PortAssignment.PortRange portRange = PortAssignment.setupPortRange(strProcessCount, cmdLine);
+ assertEquals(buildAssertionMessage("minimum"), expectedMinimumPort, portRange.getMinimum());
+ assertEquals(buildAssertionMessage("maximum"), expectedMaximumPort, portRange.getMaximum());
}
private String buildAssertionMessage(String checkType) {
- return String.format("strProcessCount = %s, cmdLine = %s, checking %s",
- strProcessCount, cmdLine, checkType);
+ return String.format("strProcessCount = %s, cmdLine = %s, checking %s", strProcessCount, cmdLine, checkType);
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/RemoveWatchesCmdTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/RemoveWatchesCmdTest.java
index c239404e4..51d916e4b 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/RemoveWatchesCmdTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/RemoveWatchesCmdTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -15,19 +15,20 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
package org.apache.zookeeper;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
-
import org.apache.zookeeper.Watcher.Event.EventType;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.test.ClientBase;
-import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -36,8 +37,8 @@ import org.slf4j.LoggerFactory;
* Testing remove watches using command line
*/
public class RemoveWatchesCmdTest extends ClientBase {
- private static final Logger LOG = LoggerFactory
- .getLogger(RemoveWatchesCmdTest.class);
+
+ private static final Logger LOG = LoggerFactory.getLogger(RemoveWatchesCmdTest.class);
private ZooKeeper zk;
private ZooKeeperMain zkMain;
@@ -68,10 +69,8 @@ public class RemoveWatchesCmdTest extends ClientBase {
expectedEvents.add(EventType.DataWatchRemoved);
MyWatcher myWatcher = new MyWatcher("/testnode1", expectedEvents, 2);
- zk.create("/testnode1", "data".getBytes(), Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
- zk.create("/testnode2", "data".getBytes(), Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk.create("/testnode1", "data".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
+ zk.create("/testnode2", "data".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
LOG.info("Adding childwatcher to /testnode1 and /testnode2");
zk.getChildren("/testnode1", myWatcher);
@@ -84,17 +83,13 @@ public class RemoveWatchesCmdTest extends ClientBase {
String cmdstring = "removewatches /testnode1";
LOG.info("Remove watchers using shell command : {}", cmdstring);
zkMain.cl.parseCommand(cmdstring);
- Assert.assertTrue("Removewatches cmd fails to remove child watches",
- zkMain.processZKCmd(zkMain.cl));
+ assertTrue("Removewatches cmd fails to remove child watches", zkMain.processZKCmd(zkMain.cl));
LOG.info("Waiting for the DataWatchRemoved event");
myWatcher.matches();
// verifying that other path child watches are not affected
- Assert.assertTrue(
- "Failed to find child watches for the path testnode2", zk
- .getChildWatches().contains("/testnode2"));
- Assert.assertTrue("Failed to find data watches for the path testnode2",
- zk.getDataWatches().contains("/testnode2"));
+ assertTrue("Failed to find child watches for the path testnode2", zk.getChildWatches().contains("/testnode2"));
+ assertTrue("Failed to find data watches for the path testnode2", zk.getDataWatches().contains("/testnode2"));
}
/**
@@ -107,23 +102,19 @@ public class RemoveWatchesCmdTest extends ClientBase {
expectedEvents.add(EventType.DataWatchRemoved);
MyWatcher myWatcher = new MyWatcher("/testnode1", expectedEvents, 1);
- zk.create("/testnode1", "data".getBytes(), Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk.create("/testnode1", "data".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
zk.getData("/testnode1", myWatcher, null);
String cmdstring = "removewatches /testnode1 -d";
LOG.info("Remove watchers using shell command : {}", cmdstring);
zkMain.cl.parseCommand(cmdstring);
- Assert.assertTrue("Removewatches cmd fails to remove data watches",
- zkMain.processZKCmd(zkMain.cl));
+ assertTrue("Removewatches cmd fails to remove data watches", zkMain.processZKCmd(zkMain.cl));
LOG.info("Waiting for the DataWatchRemoved event");
myWatcher.matches();
// verifying that other path data watches are removed
- Assert.assertEquals(
- "Data watches are not removed : " + zk.getDataWatches(), 0, zk
- .getDataWatches().size());
+ assertEquals("Data watches are not removed : " + zk.getDataWatches(), 0, zk.getDataWatches().size());
}
/**
@@ -134,8 +125,7 @@ public class RemoveWatchesCmdTest extends ClientBase {
List<EventType> expectedEvents = new ArrayList<Watcher.Event.EventType>();
expectedEvents.add(EventType.DataWatchRemoved);
MyWatcher myWatcher1 = new MyWatcher("/testnode1", expectedEvents, 1);
- MyWatcher myWatcher2 = new MyWatcher("/testnode1/testnode2",
- expectedEvents, 1);
+ MyWatcher myWatcher2 = new MyWatcher("/testnode1/testnode2", expectedEvents, 1);
// Adding pre-created watcher
LOG.info("Adding NodeCreated watcher");
zk.exists("/testnode1", myWatcher1);
@@ -144,27 +134,21 @@ public class RemoveWatchesCmdTest extends ClientBase {
String cmdstring1 = "removewatches /testnode1 -d";
LOG.info("Remove watchers using shell command : {}", cmdstring1);
zkMain.cl.parseCommand(cmdstring1);
- Assert.assertTrue(
- "Removewatches cmd fails to remove pre-create watches",
- zkMain.processZKCmd(zkMain.cl));
+ assertTrue("Removewatches cmd fails to remove pre-create watches", zkMain.processZKCmd(zkMain.cl));
myWatcher1.matches();
- Assert.assertEquals(
- "Failed to remove pre-create watches :" + zk.getExistWatches(),
- 1, zk.getExistWatches().size());
- Assert.assertTrue(
- "Failed to remove pre-create watches :" + zk.getExistWatches(),
- zk.getExistWatches().contains("/testnode1/testnode2"));
+ assertEquals("Failed to remove pre-create watches :"
+ + zk.getExistWatches(), 1, zk.getExistWatches().size());
+ assertTrue("Failed to remove pre-create watches :"
+ + zk.getExistWatches(), zk.getExistWatches().contains("/testnode1/testnode2"));
String cmdstring2 = "removewatches /testnode1/testnode2 -d";
LOG.info("Remove watchers using shell command : {}", cmdstring2);
zkMain.cl.parseCommand(cmdstring2);
- Assert.assertTrue("Removewatches cmd fails to remove data watches",
- zkMain.processZKCmd(zkMain.cl));
+ assertTrue("Removewatches cmd fails to remove data watches", zkMain.processZKCmd(zkMain.cl));
myWatcher2.matches();
- Assert.assertEquals(
- "Failed to remove pre-create watches : " + zk.getExistWatches(),
- 0, zk.getExistWatches().size());
+ assertEquals("Failed to remove pre-create watches : "
+ + zk.getExistWatches(), 0, zk.getExistWatches().size());
}
/**
@@ -176,20 +160,16 @@ public class RemoveWatchesCmdTest extends ClientBase {
expectedEvents.add(EventType.ChildWatchRemoved);
MyWatcher myWatcher = new MyWatcher("/testnode1", expectedEvents, 1);
- zk.create("/testnode1", "data".getBytes(), Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk.create("/testnode1", "data".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
LOG.info("Adding child changed watcher");
zk.getChildren("/testnode1", myWatcher);
String cmdstring = "removewatches /testnode1 -c";
LOG.info("Remove watchers using shell command : {}", cmdstring);
zkMain.cl.parseCommand(cmdstring);
- Assert.assertTrue("Removewatches cmd fails to remove child watches",
- zkMain.processZKCmd(zkMain.cl));
+ assertTrue("Removewatches cmd fails to remove child watches", zkMain.processZKCmd(zkMain.cl));
myWatcher.matches();
- Assert.assertEquals(
- "Failed to remove child watches : " + zk.getChildWatches(), 0,
- zk.getChildWatches().size());
+ assertEquals("Failed to remove child watches : " + zk.getChildWatches(), 0, zk.getChildWatches().size());
}
/**
@@ -203,27 +183,21 @@ public class RemoveWatchesCmdTest extends ClientBase {
expectedEvents.add(EventType.NodeDeleted);
MyWatcher myWatcher = new MyWatcher("/testnode1", expectedEvents, 1);
- zk.create("/testnode1", "data".getBytes(), Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
- zk.create("/testnode1/testnode2", "data".getBytes(),
- Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
+ zk.create("/testnode1", "data".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
+ zk.create("/testnode1/testnode2", "data".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
zk.getChildren("/testnode1/testnode2", myWatcher);
zk.getChildren("/testnode1", myWatcher);
String cmdstring = "removewatches /testnode1 -c";
LOG.info("Remove watchers using shell command : {}", cmdstring);
zkMain.cl.parseCommand(cmdstring);
- Assert.assertTrue("Removewatches cmd fails to remove child watches",
- zkMain.processZKCmd(zkMain.cl));
+ assertTrue("Removewatches cmd fails to remove child watches", zkMain.processZKCmd(zkMain.cl));
LOG.info("Waiting for the ChildWatchRemoved event");
myWatcher.matches();
- Assert.assertEquals(
- "Failed to remove child watches : " + zk.getChildWatches(), 1,
- zk.getChildWatches().size());
+ assertEquals("Failed to remove child watches : " + zk.getChildWatches(), 1, zk.getChildWatches().size());
- Assert.assertTrue(
- "Failed to remove child watches :" + zk.getChildWatches(), zk
- .getChildWatches().contains("/testnode1/testnode2"));
+ assertTrue("Failed to remove child watches :"
+ + zk.getChildWatches(), zk.getChildWatches().contains("/testnode1/testnode2"));
// verify node delete watcher
zk.delete("/testnode1/testnode2", -1);
@@ -243,8 +217,7 @@ public class RemoveWatchesCmdTest extends ClientBase {
* connection
*/
@Test(timeout = 30000)
- public void testRemoveWatchesLocallyWhenNoServerConnection()
- throws Exception {
+ public void testRemoveWatchesLocallyWhenNoServerConnection() throws Exception {
verifyRemoveAnyWatches(true);
}
@@ -272,8 +245,7 @@ public class RemoveWatchesCmdTest extends ClientBase {
}
private void addWatchNotifications(
- final Map<String, List<EventType>> pathVsEvent,
- WatchedEvent event) {
+ final Map<String, List<EventType>> pathVsEvent, WatchedEvent event) {
List<EventType> events = pathVsEvent.get(event.getPath());
if (null == events) {
events = new ArrayList<Watcher.Event.EventType>();
@@ -282,8 +254,7 @@ public class RemoveWatchesCmdTest extends ClientBase {
events.add(event.getType());
}
};
- zk.create("/testnode1", "data".getBytes(), Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk.create("/testnode1", "data".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
zk.getChildren("/testnode1", watcher);
zk.getData("/testnode1", watcher, null);
String cmdstring = "removewatches /testnode1 -a";
@@ -295,22 +266,16 @@ public class RemoveWatchesCmdTest extends ClientBase {
LOG.info("Remove watchers using shell command : {}", cmdstring);
zkMain.cl.parseCommand(cmdstring);
- Assert.assertTrue(
- "Removewatches cmd fails to remove child/data watches",
- zkMain.processZKCmd(zkMain.cl));
+ assertTrue("Removewatches cmd fails to remove child/data watches", zkMain.processZKCmd(zkMain.cl));
LOG.info("Waiting for the WatchRemoved events");
watcherLatch.await(10, TimeUnit.SECONDS);
- Assert.assertEquals("Didn't receives WatchRemoved events!", 1,
- pathVsEvent.size());
- Assert.assertTrue(
- "Didn't receives DataWatchRemoved!",
- pathVsEvent.get("/testnode1").contains(
- EventType.DataWatchRemoved));
- Assert.assertTrue("Didn't receives ChildWatchRemoved!", pathVsEvent
- .get("/testnode1").contains(EventType.ChildWatchRemoved));
+ assertEquals("Didn't receives WatchRemoved events!", 1, pathVsEvent.size());
+ assertTrue("Didn't receives DataWatchRemoved!", pathVsEvent.get("/testnode1").contains(EventType.DataWatchRemoved));
+ assertTrue("Didn't receives ChildWatchRemoved!", pathVsEvent.get("/testnode1").contains(EventType.ChildWatchRemoved));
}
private class MyWatcher implements Watcher {
+
private final String path;
private String eventPath;
private final CountDownLatch latch;
@@ -323,8 +288,7 @@ public class RemoveWatchesCmdTest extends ClientBase {
}
public void process(WatchedEvent event) {
- LOG.debug("Event path : {}, eventPath : {}"
- + new Object[] { path, event.getPath() });
+ LOG.debug("Event path : {}, eventPath : {}" + new Object[]{path, event.getPath()});
this.eventPath = event.getPath();
if (expectedEvents.contains(event.getType())) {
latch.countDown();
@@ -336,10 +300,10 @@ public class RemoveWatchesCmdTest extends ClientBase {
LOG.error("Failed to get watch notifications!");
return false;
}
- LOG.debug("Client path : {} eventPath : {}", new Object[] { path,
- eventPath });
+ LOG.debug("Client path : {} eventPath : {}", new Object[]{path, eventPath});
return path.equals(eventPath);
}
+
}
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/RemoveWatchesTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/RemoveWatchesTest.java
index 3abfc3ae4..2acb96938 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/RemoveWatchesTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/RemoveWatchesTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,6 +18,12 @@
package org.apache.zookeeper;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
@@ -27,9 +33,8 @@ import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.TimeoutException;
import java.util.concurrent.TimeUnit;
-
+import java.util.concurrent.TimeoutException;
import org.apache.commons.collections.CollectionUtils;
import org.apache.zookeeper.KeeperException.Code;
import org.apache.zookeeper.KeeperException.NoWatcherException;
@@ -39,7 +44,6 @@ import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.client.ZKClientConfig;
import org.apache.zookeeper.server.ServerCnxn;
import org.apache.zookeeper.test.ClientBase;
-import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
@@ -53,8 +57,8 @@ import org.slf4j.LoggerFactory;
@RunWith(Parameterized.class)
@Parameterized.UseParametersRunnerFactory(ZKParameterized.RunnerFactory.class)
public class RemoveWatchesTest extends ClientBase {
- private static final Logger LOG = LoggerFactory
- .getLogger(RemoveWatchesTest.class);
+
+ private static final Logger LOG = LoggerFactory.getLogger(RemoveWatchesTest.class);
private ZooKeeper zk1 = null;
private ZooKeeper zk2 = null;
@@ -67,10 +71,12 @@ public class RemoveWatchesTest extends ClientBase {
@Override
public void tearDown() throws Exception {
- if (zk1 != null)
+ if (zk1 != null) {
zk1.close();
- if (zk2 != null)
+ }
+ if (zk2 != null) {
zk2.close();
+ }
super.tearDown();
}
@@ -82,23 +88,23 @@ public class RemoveWatchesTest extends ClientBase {
@Parameters
public static Collection<Object[]> configs() {
- return Arrays.asList(new Object[][] { { false }, { true }, });
+ return Arrays.asList(new Object[][]{{false}, {true}});
}
- private void removeWatches(ZooKeeper zk, String path, Watcher watcher,
- WatcherType watcherType, boolean local, KeeperException.Code rc)
- throws InterruptedException, KeeperException {
- LOG.info(
- "Sending removeWatches req using zk {} path: {} type: {} watcher: {} ",
- new Object[] { zk, path, watcherType, watcher });
+ private void removeWatches(
+ ZooKeeper zk,
+ String path,
+ Watcher watcher,
+ WatcherType watcherType,
+ boolean local,
+ KeeperException.Code rc) throws InterruptedException, KeeperException {
+ LOG.info("Sending removeWatches req using zk {} path: {} type: {} watcher: {} ", zk, path, watcherType, watcher);
if (useAsync) {
MyCallback c1 = new MyCallback(rc.intValue(), path);
zk.removeWatches(path, watcher, watcherType, local, c1, null);
- Assert.assertTrue("Didn't succeeds removeWatch operation",
- c1.matches());
+ assertTrue("Didn't succeeds removeWatch operation", c1.matches());
if (KeeperException.Code.OK.intValue() != c1.rc) {
- KeeperException ke = KeeperException
- .create(KeeperException.Code.get(c1.rc));
+ KeeperException ke = KeeperException.create(KeeperException.Code.get(c1.rc));
throw ke;
}
} else {
@@ -106,19 +112,19 @@ public class RemoveWatchesTest extends ClientBase {
}
}
- private void removeAllWatches(ZooKeeper zk, String path,
- WatcherType watcherType, boolean local, KeeperException.Code rc)
- throws InterruptedException, KeeperException {
- LOG.info("Sending removeWatches req using zk {} path: {} type: {} ",
- new Object[] { zk, path, watcherType });
+ private void removeAllWatches(
+ ZooKeeper zk,
+ String path,
+ WatcherType watcherType,
+ boolean local,
+ KeeperException.Code rc) throws InterruptedException, KeeperException {
+ LOG.info("Sending removeWatches req using zk {} path: {} type: {} ", zk, path, watcherType);
if (useAsync) {
MyCallback c1 = new MyCallback(rc.intValue(), path);
zk.removeAllWatches(path, watcherType, local, c1, null);
- Assert.assertTrue("Didn't succeeds removeWatch operation",
- c1.matches());
+ assertTrue("Didn't succeeds removeWatch operation", c1.matches());
if (KeeperException.Code.OK.intValue() != c1.rc) {
- KeeperException ke = KeeperException
- .create(KeeperException.Code.get(c1.rc));
+ KeeperException ke = KeeperException.create(KeeperException.Code.get(c1.rc));
throw ke;
}
} else {
@@ -134,22 +140,16 @@ public class RemoveWatchesTest extends ClientBase {
zk1.create("/node1", null, Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
zk1.create("/node2", null, Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
MyWatcher w1 = new MyWatcher("/node1", 1);
- LOG.info("Adding data watcher {} on path {}", new Object[] { w1,
- "/node1" });
- Assert.assertNotNull("Didn't set data watches",
- zk2.exists("/node1", w1));
+ LOG.info("Adding data watcher {} on path {}", new Object[]{w1, "/node1"});
+ assertNotNull("Didn't set data watches", zk2.exists("/node1", w1));
MyWatcher w2 = new MyWatcher("/node2", 1);
- LOG.info("Adding data watcher {} on path {}", new Object[] { w2,
- "/node1" });
- Assert.assertNotNull("Didn't set data watches",
- zk2.exists("/node2", w2));
+ LOG.info("Adding data watcher {} on path {}", new Object[]{w2, "/node1"});
+ assertNotNull("Didn't set data watches", zk2.exists("/node2", w2));
removeWatches(zk2, "/node1", w1, WatcherType.Data, false, Code.OK);
- Assert.assertEquals("Didn't find data watcher", 1,
- zk2.getDataWatches().size());
- Assert.assertEquals("Didn't find data watcher", "/node2",
- zk2.getDataWatches().get(0));
+ assertEquals("Didn't find data watcher", 1, zk2.getDataWatches().size());
+ assertEquals("Didn't find data watcher", "/node2", zk2.getDataWatches().get(0));
removeWatches(zk2, "/node2", w2, WatcherType.Any, false, Code.OK);
- Assert.assertTrue("Didn't remove data watcher", w2.matches());
+ assertTrue("Didn't remove data watcher", w2.matches());
// closing session should remove ephemeral nodes and trigger data
// watches if any
if (zk1 != null) {
@@ -158,12 +158,8 @@ public class RemoveWatchesTest extends ClientBase {
}
List<EventType> events = w1.getEventsAfterWatchRemoval();
- Assert.assertFalse(
- "Shouldn't get NodeDeletedEvent after watch removal",
- events.contains(EventType.NodeDeleted));
- Assert.assertEquals(
- "Shouldn't get NodeDeletedEvent after watch removal", 0,
- events.size());
+ assertFalse("Shouldn't get NodeDeletedEvent after watch removal", events.contains(EventType.NodeDeleted));
+ assertEquals("Shouldn't get NodeDeletedEvent after watch removal", 0, events.size());
}
/**
@@ -171,26 +167,19 @@ public class RemoveWatchesTest extends ClientBase {
* connection
*/
@Test(timeout = 90000)
- public void testMultipleDataWatchers() throws IOException,
- InterruptedException, KeeperException {
+ public void testMultipleDataWatchers() throws IOException, InterruptedException, KeeperException {
zk1.create("/node1", null, Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
MyWatcher w1 = new MyWatcher("/node1", 1);
- LOG.info("Adding data watcher {} on path {}", new Object[] { w1,
- "/node1" });
- Assert.assertNotNull("Didn't set data watches",
- zk2.exists("/node1", w1));
+ LOG.info("Adding data watcher {} on path {}", new Object[]{w1, "/node1"});
+ assertNotNull("Didn't set data watches", zk2.exists("/node1", w1));
MyWatcher w2 = new MyWatcher("/node1", 1);
- LOG.info("Adding data watcher {} on path {}", new Object[] { w2,
- "/node1" });
- Assert.assertNotNull("Didn't set data watches",
- zk2.exists("/node1", w2));
+ LOG.info("Adding data watcher {} on path {}", new Object[]{w2, "/node1"});
+ assertNotNull("Didn't set data watches", zk2.exists("/node1", w2));
removeWatches(zk2, "/node1", w2, WatcherType.Data, false, Code.OK);
- Assert.assertEquals("Didn't find data watcher", 1,
- zk2.getDataWatches().size());
- Assert.assertEquals("Didn't find data watcher", "/node1",
- zk2.getDataWatches().get(0));
+ assertEquals("Didn't find data watcher", 1, zk2.getDataWatches().size());
+ assertEquals("Didn't find data watcher", "/node1", zk2.getDataWatches().get(0));
removeWatches(zk2, "/node1", w1, WatcherType.Any, false, Code.OK);
- Assert.assertTrue("Didn't remove data watcher", w2.matches());
+ assertTrue("Didn't remove data watcher", w2.matches());
// closing session should remove ephemeral nodes and trigger data
// watches if any
if (zk1 != null) {
@@ -199,9 +188,7 @@ public class RemoveWatchesTest extends ClientBase {
}
List<EventType> events = w2.getEventsAfterWatchRemoval();
- Assert.assertEquals(
- "Shouldn't get NodeDeletedEvent after watch removal", 0,
- events.size());
+ assertEquals("Shouldn't get NodeDeletedEvent after watch removal", 0, events.size());
}
/**
@@ -209,26 +196,21 @@ public class RemoveWatchesTest extends ClientBase {
* connection
*/
@Test(timeout = 90000)
- public void testMultipleChildWatchers() throws IOException,
- InterruptedException, KeeperException {
+ public void testMultipleChildWatchers() throws IOException, InterruptedException, KeeperException {
zk1.create("/node1", null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
MyWatcher w1 = new MyWatcher("/node1", 1);
- LOG.info("Adding child watcher {} on path {}", new Object[] { w1,
- "/node1" });
+ LOG.info("Adding child watcher {} on path {}", new Object[]{w1, "/node1"});
zk2.getChildren("/node1", w1);
MyWatcher w2 = new MyWatcher("/node1", 1);
- LOG.info("Adding child watcher {} on path {}", new Object[] { w2,
- "/node1" });
+ LOG.info("Adding child watcher {} on path {}", new Object[]{w2, "/node1"});
zk2.getChildren("/node1", w2);
removeWatches(zk2, "/node1", w2, WatcherType.Children, false, Code.OK);
- Assert.assertTrue("Didn't remove child watcher", w2.matches());
- Assert.assertEquals("Didn't find child watcher", 1, zk2
- .getChildWatches().size());
+ assertTrue("Didn't remove child watcher", w2.matches());
+ assertEquals("Didn't find child watcher", 1, zk2.getChildWatches().size());
removeWatches(zk2, "/node1", w1, WatcherType.Any, false, Code.OK);
- Assert.assertTrue("Didn't remove child watcher", w1.matches());
+ assertTrue("Didn't remove child watcher", w1.matches());
// create child to see NodeChildren notification
- zk1.create("/node1/node2", null, Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk1.create("/node1/node2", null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
// waiting for child watchers to be notified
int count = 30;
while (count > 0) {
@@ -240,8 +222,7 @@ public class RemoveWatchesTest extends ClientBase {
}
// watcher2
List<EventType> events = w2.getEventsAfterWatchRemoval();
- Assert.assertEquals("Shouldn't get NodeChildrenChanged event", 0,
- events.size());
+ assertEquals("Shouldn't get NodeChildrenChanged event", 0, events.size());
}
/**
@@ -249,31 +230,23 @@ public class RemoveWatchesTest extends ClientBase {
* data, child, exists
*/
@Test(timeout = 90000)
- public void testRemoveAllWatchers() throws IOException,
- InterruptedException, KeeperException {
+ public void testRemoveAllWatchers() throws IOException, InterruptedException, KeeperException {
zk1.create("/node1", null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
MyWatcher w1 = new MyWatcher("/node1", 2);
MyWatcher w2 = new MyWatcher("/node1", 2);
- LOG.info("Adding data watcher {} on path {}", new Object[] { w1,
- "/node1" });
- Assert.assertNotNull("Didn't set data watches",
- zk2.exists("/node1", w1));
- LOG.info("Adding data watcher {} on path {}", new Object[] { w2,
- "/node1" });
- Assert.assertNotNull("Didn't set data watches",
- zk2.exists("/node1", w2));
- LOG.info("Adding child watcher {} on path {}", new Object[] { w1,
- "/node1" });
+ LOG.info("Adding data watcher {} on path {}", new Object[]{w1, "/node1"});
+ assertNotNull("Didn't set data watches", zk2.exists("/node1", w1));
+ LOG.info("Adding data watcher {} on path {}", new Object[]{w2, "/node1"});
+ assertNotNull("Didn't set data watches", zk2.exists("/node1", w2));
+ LOG.info("Adding child watcher {} on path {}", new Object[]{w1, "/node1"});
zk2.getChildren("/node1", w1);
- LOG.info("Adding child watcher {} on path {}", new Object[] { w2,
- "/node1" });
+ LOG.info("Adding child watcher {} on path {}", new Object[]{w2, "/node1"});
zk2.getChildren("/node1", w2);
removeWatches(zk2, "/node1", w1, WatcherType.Any, false, Code.OK);
removeWatches(zk2, "/node1", w2, WatcherType.Any, false, Code.OK);
- zk1.create("/node1/child", null, Ids.OPEN_ACL_UNSAFE,
- CreateMode.EPHEMERAL);
- Assert.assertTrue("Didn't remove data watcher", w1.matches());
- Assert.assertTrue("Didn't remove child watcher", w2.matches());
+ zk1.create("/node1/child", null, Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
+ assertTrue("Didn't remove data watcher", w1.matches());
+ assertTrue("Didn't remove child watcher", w2.matches());
}
/**
@@ -281,36 +254,27 @@ public class RemoveWatchesTest extends ClientBase {
* watchers. Child watchers shouldn't be removed
*/
@Test(timeout = 90000)
- public void testRemoveAllDataWatchers() throws IOException,
- InterruptedException, KeeperException {
+ public void testRemoveAllDataWatchers() throws IOException, InterruptedException, KeeperException {
zk1.create("/node1", null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
MyWatcher w1 = new MyWatcher("/node1", 1);
MyWatcher w2 = new MyWatcher("/node1", 1);
- LOG.info("Adding data watcher {} on path {}", new Object[] { w1,
- "/node1" });
- Assert.assertNotNull("Didn't set data watches",
- zk2.exists("/node1", w1));
- LOG.info("Adding data watcher {} on path {}", new Object[] { w2,
- "/node1" });
- Assert.assertNotNull("Didn't set data watches",
- zk2.exists("/node1", w2));
- LOG.info("Adding child watcher {} on path {}", new Object[] { w1,
- "/node1" });
+ LOG.info("Adding data watcher {} on path {}", new Object[]{w1, "/node1"});
+ assertNotNull("Didn't set data watches", zk2.exists("/node1", w1));
+ LOG.info("Adding data watcher {} on path {}", new Object[]{w2, "/node1"});
+ assertNotNull("Didn't set data watches", zk2.exists("/node1", w2));
+ LOG.info("Adding child watcher {} on path {}", new Object[]{w1, "/node1"});
zk2.getChildren("/node1", w1);
- LOG.info("Adding child watcher {} on path {}", new Object[] { w2,
- "/node1" });
+ LOG.info("Adding child watcher {} on path {}", new Object[]{w2, "/node1"});
zk2.getChildren("/node1", w2);
removeWatches(zk2, "/node1", w1, WatcherType.Data, false, Code.OK);
removeWatches(zk2, "/node1", w2, WatcherType.Data, false, Code.OK);
- zk1.create("/node1/child", null, Ids.OPEN_ACL_UNSAFE,
- CreateMode.EPHEMERAL);
- Assert.assertTrue("Didn't remove data watcher", w1.matches());
- Assert.assertTrue("Didn't remove data watcher", w2.matches());
+ zk1.create("/node1/child", null, Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
+ assertTrue("Didn't remove data watcher", w1.matches());
+ assertTrue("Didn't remove data watcher", w2.matches());
// waiting for child watchers to be notified
int count = 10;
while (count > 0) {
- if (w1.getEventsAfterWatchRemoval().size() > 0
- && w2.getEventsAfterWatchRemoval().size() > 0) {
+ if (w1.getEventsAfterWatchRemoval().size() > 0 && w2.getEventsAfterWatchRemoval().size() > 0) {
break;
}
count--;
@@ -318,16 +282,12 @@ public class RemoveWatchesTest extends ClientBase {
}
// watcher1
List<EventType> events = w1.getEventsAfterWatchRemoval();
- Assert.assertEquals("Didn't get NodeChildrenChanged event", 1,
- events.size());
- Assert.assertTrue("Didn't get NodeChildrenChanged event",
- events.contains(EventType.NodeChildrenChanged));
+ assertEquals("Didn't get NodeChildrenChanged event", 1, events.size());
+ assertTrue("Didn't get NodeChildrenChanged event", events.contains(EventType.NodeChildrenChanged));
// watcher2
events = w2.getEventsAfterWatchRemoval();
- Assert.assertEquals("Didn't get NodeChildrenChanged event", 1,
- events.size());
- Assert.assertTrue("Didn't get NodeChildrenChanged event",
- events.contains(EventType.NodeChildrenChanged));
+ assertEquals("Didn't get NodeChildrenChanged event", 1, events.size());
+ assertTrue("Didn't get NodeChildrenChanged event", events.contains(EventType.NodeChildrenChanged));
}
/**
@@ -335,35 +295,27 @@ public class RemoveWatchesTest extends ClientBase {
* watchers. Data watchers shouldn't be removed
*/
@Test(timeout = 90000)
- public void testRemoveAllChildWatchers() throws IOException,
- InterruptedException, KeeperException {
+ public void testRemoveAllChildWatchers() throws IOException, InterruptedException, KeeperException {
zk1.create("/node1", null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
MyWatcher w1 = new MyWatcher("/node1", 1);
MyWatcher w2 = new MyWatcher("/node1", 1);
- LOG.info("Adding data watcher {} on path {}", new Object[] { w1,
- "/node1" });
- Assert.assertNotNull("Didn't set data watches",
- zk2.exists("/node1", w1));
- LOG.info("Adding data watcher {} on path {}", new Object[] { w2,
- "/node1" });
- Assert.assertNotNull("Didn't set data watches",
- zk2.exists("/node1", w2));
- LOG.info("Adding child watcher {} on path {}", new Object[] { w1,
- "/node1" });
+ LOG.info("Adding data watcher {} on path {}", new Object[]{w1, "/node1"});
+ assertNotNull("Didn't set data watches", zk2.exists("/node1", w1));
+ LOG.info("Adding data watcher {} on path {}", new Object[]{w2, "/node1"});
+ assertNotNull("Didn't set data watches", zk2.exists("/node1", w2));
+ LOG.info("Adding child watcher {} on path {}", new Object[]{w1, "/node1"});
zk2.getChildren("/node1", w1);
- LOG.info("Adding child watcher {} on path {}", new Object[] { w2,
- "/node1" });
+ LOG.info("Adding child watcher {} on path {}", new Object[]{w2, "/node1"});
zk2.getChildren("/node1", w2);
removeWatches(zk2, "/node1", w1, WatcherType.Children, false, Code.OK);
removeWatches(zk2, "/node1", w2, WatcherType.Children, false, Code.OK);
zk1.setData("/node1", "test".getBytes(), -1);
- Assert.assertTrue("Didn't remove child watcher", w1.matches());
- Assert.assertTrue("Didn't remove child watcher", w2.matches());
+ assertTrue("Didn't remove child watcher", w1.matches());
+ assertTrue("Didn't remove child watcher", w2.matches());
// waiting for child watchers to be notified
int count = 10;
while (count > 0) {
- if (w1.getEventsAfterWatchRemoval().size() > 0
- && w2.getEventsAfterWatchRemoval().size() > 0) {
+ if (w1.getEventsAfterWatchRemoval().size() > 0 && w2.getEventsAfterWatchRemoval().size() > 0) {
break;
}
count--;
@@ -371,69 +323,55 @@ public class RemoveWatchesTest extends ClientBase {
}
// watcher1
List<EventType> events = w1.getEventsAfterWatchRemoval();
- Assert.assertEquals("Didn't get NodeDataChanged event", 1,
- events.size());
- Assert.assertTrue("Didn't get NodeDataChanged event",
- events.contains(EventType.NodeDataChanged));
+ assertEquals("Didn't get NodeDataChanged event", 1, events.size());
+ assertTrue("Didn't get NodeDataChanged event", events.contains(EventType.NodeDataChanged));
// watcher2
events = w2.getEventsAfterWatchRemoval();
- Assert.assertEquals("Didn't get NodeDataChanged event", 1,
- events.size());
- Assert.assertTrue("Didn't get NodeDataChanged event",
- events.contains(EventType.NodeDataChanged));
+ assertEquals("Didn't get NodeDataChanged event", 1, events.size());
+ assertTrue("Didn't get NodeDataChanged event", events.contains(EventType.NodeDataChanged));
}
/**
* Test verifies given watcher doesn't exists!
*/
@Test(timeout = 90000)
- public void testNoWatcherException() throws IOException,
- InterruptedException, KeeperException {
+ public void testNoWatcherException() throws IOException, InterruptedException, KeeperException {
zk1.create("/node1", null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
MyWatcher w1 = new MyWatcher("/node1", 2);
MyWatcher w2 = new MyWatcher("/node1", 2);
- LOG.info("Adding data watcher {} on path {}", new Object[] { w1,
- "/node1" });
- Assert.assertNotNull("Didn't set data watches",
- zk2.exists("/node1", w1));
- LOG.info("Adding data watcher {} on path {}", new Object[] { w2,
- "/node1" });
- Assert.assertNull("Didn't set data watches", zk2.exists("/node2", w2));
- LOG.info("Adding child watcher {} on path {}", new Object[] { w1,
- "/node1" });
+ LOG.info("Adding data watcher {} on path {}", new Object[]{w1, "/node1"});
+ assertNotNull("Didn't set data watches", zk2.exists("/node1", w1));
+ LOG.info("Adding data watcher {} on path {}", new Object[]{w2, "/node1"});
+ assertNull("Didn't set data watches", zk2.exists("/node2", w2));
+ LOG.info("Adding child watcher {} on path {}", new Object[]{w1, "/node1"});
zk2.getChildren("/node1", w1);
- LOG.info("Adding child watcher {} on path {}", new Object[] { w2,
- "/node1" });
+ LOG.info("Adding child watcher {} on path {}", new Object[]{w2, "/node1"});
zk2.getChildren("/node1", w2);
// New Watcher which will be used for removal
MyWatcher w3 = new MyWatcher("/node1", 2);
try {
- removeWatches(zk2, "/node1", w3, WatcherType.Any, false,
- Code.NOWATCHER);
- Assert.fail("Should throw exception as given watcher doesn't exists");
+ removeWatches(zk2, "/node1", w3, WatcherType.Any, false, Code.NOWATCHER);
+ fail("Should throw exception as given watcher doesn't exists");
} catch (KeeperException.NoWatcherException nwe) {
// expected
}
try {
- removeWatches(zk2, "/node1", w3, WatcherType.Children, false,
- Code.NOWATCHER);
- Assert.fail("Should throw exception as given watcher doesn't exists");
+ removeWatches(zk2, "/node1", w3, WatcherType.Children, false, Code.NOWATCHER);
+ fail("Should throw exception as given watcher doesn't exists");
} catch (KeeperException.NoWatcherException nwe) {
// expected
}
try {
- removeWatches(zk2, "/node1", w3, WatcherType.Data, false,
- Code.NOWATCHER);
- Assert.fail("Should throw exception as given watcher doesn't exists");
+ removeWatches(zk2, "/node1", w3, WatcherType.Data, false, Code.NOWATCHER);
+ fail("Should throw exception as given watcher doesn't exists");
} catch (KeeperException.NoWatcherException nwe) {
// expected
}
try {
- removeWatches(zk2, "/nonexists", w3, WatcherType.Data, false,
- Code.NOWATCHER);
- Assert.fail("Should throw exception as given watcher doesn't exists");
+ removeWatches(zk2, "/nonexists", w3, WatcherType.Data, false, Code.NOWATCHER);
+ fail("Should throw exception as given watcher doesn't exists");
} catch (KeeperException.NoWatcherException nwe) {
// expected
}
@@ -449,26 +387,19 @@ public class RemoveWatchesTest extends ClientBase {
MyWatcher w1 = new MyWatcher("/node1", 1);
MyWatcher w2 = new MyWatcher("/node1", 2);
// Add multiple data watches
- LOG.info("Adding data watcher {} on path {}", new Object[] { w1,
- "/node1" });
- Assert.assertNotNull("Didn't set data watches",
- zk2.exists("/node1", w1));
- LOG.info("Adding data watcher {} on path {}", new Object[] { w2,
- "/node1" });
- Assert.assertNotNull("Didn't set data watches",
- zk2.exists("/node1", w2));
+ LOG.info("Adding data watcher {} on path {}", new Object[]{w1, "/node1"});
+ assertNotNull("Didn't set data watches", zk2.exists("/node1", w1));
+ LOG.info("Adding data watcher {} on path {}", new Object[]{w2, "/node1"});
+ assertNotNull("Didn't set data watches", zk2.exists("/node1", w2));
// Add child watch
- LOG.info("Adding child watcher {} on path {}", new Object[] { w2,
- "/node1" });
+ LOG.info("Adding child watcher {} on path {}", new Object[]{w2, "/node1"});
zk2.getChildren("/node1", w2);
removeWatches(zk2, "/node1", w1, WatcherType.Any, false, Code.OK);
- Assert.assertTrue("Didn't remove data watcher", w1.matches());
- Assert.assertEquals("Didn't find child watcher", 1, zk2
- .getChildWatches().size());
- Assert.assertEquals("Didn't find data watcher", 1, zk2
- .getDataWatches().size());
+ assertTrue("Didn't remove data watcher", w1.matches());
+ assertEquals("Didn't find child watcher", 1, zk2.getChildWatches().size());
+ assertEquals("Didn't find data watcher", 1, zk2.getDataWatches().size());
removeWatches(zk2, "/node1", w2, WatcherType.Any, false, Code.OK);
- Assert.assertTrue("Didn't remove child watcher", w2.matches());
+ assertTrue("Didn't remove child watcher", w2.matches());
}
/**
@@ -480,25 +411,19 @@ public class RemoveWatchesTest extends ClientBase {
zk1.create("/node1", null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
MyWatcher w1 = new MyWatcher("/node1", 2);
MyWatcher w2 = new MyWatcher("/node1", 1);
- LOG.info("Adding data watcher {} on path {}", new Object[] { w1,
- "/node1" });
- Assert.assertNotNull("Didn't set data watches",
- zk2.exists("/node1", w1));
+ LOG.info("Adding data watcher {} on path {}", new Object[]{w1, "/node1"});
+ assertNotNull("Didn't set data watches", zk2.exists("/node1", w1));
// Add multiple child watches
- LOG.info("Adding child watcher {} on path {}", new Object[] { w1,
- "/node1" });
+ LOG.info("Adding child watcher {} on path {}", new Object[]{w1, "/node1"});
zk2.getChildren("/node1", w2);
- LOG.info("Adding child watcher {} on path {}", new Object[] { w2,
- "/node1" });
+ LOG.info("Adding child watcher {} on path {}", new Object[]{w2, "/node1"});
zk2.getChildren("/node1", w1);
removeWatches(zk2, "/node1", w2, WatcherType.Any, false, Code.OK);
- Assert.assertTrue("Didn't remove child watcher", w2.matches());
- Assert.assertEquals("Didn't find child watcher", 1, zk2
- .getChildWatches().size());
- Assert.assertEquals("Didn't find data watcher", 1, zk2
- .getDataWatches().size());
+ assertTrue("Didn't remove child watcher", w2.matches());
+ assertEquals("Didn't find child watcher", 1, zk2.getChildWatches().size());
+ assertEquals("Didn't find data watcher", 1, zk2.getDataWatches().size());
removeWatches(zk2, "/node1", w1, WatcherType.Any, false, Code.OK);
- Assert.assertTrue("Didn't remove watchers", w1.matches());
+ assertTrue("Didn't remove watchers", w1.matches());
}
/**
@@ -510,34 +435,29 @@ public class RemoveWatchesTest extends ClientBase {
zk1.create("/node1", null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
MyWatcher w1 = new MyWatcher("/node1", 2);
MyWatcher w2 = new MyWatcher("/node1", 1);
- LOG.info("Adding data watcher {} on path {}", new Object[] { w1,
- "/node1" });
- Assert.assertNotNull("Didn't set data watches",
- zk2.exists("/node1", w1));
+ LOG.info("Adding data watcher {} on path {}", new Object[]{w1, "/node1"});
+ assertNotNull("Didn't set data watches", zk2.exists("/node1", w1));
// Add multiple child watches
- LOG.info("Adding child watcher {} on path {}", new Object[] { w1,
- "/node1" });
+ LOG.info("Adding child watcher {} on path {}", new Object[]{w1, "/node1"});
zk2.getChildren("/node1", w1);
- LOG.info("Adding child watcher {} on path {}", new Object[] { w1,
- "/node1" });
+ LOG.info("Adding child watcher {} on path {}", new Object[]{w1, "/node1"});
zk2.getChildren("/node1", w2);
stopServer();
removeWatches(zk2, "/node1", w2, WatcherType.Any, true, Code.OK);
- Assert.assertTrue("Didn't remove child watcher", w2.matches());
- Assert.assertFalse("Shouldn't remove data watcher", w1.matches());
+ assertTrue("Didn't remove child watcher", w2.matches());
+ assertFalse("Shouldn't remove data watcher", w1.matches());
try {
- removeWatches(zk2, "/node1", w1, WatcherType.Any, false,
- Code.CONNECTIONLOSS);
- Assert.fail("Should throw exception as last watch removal requires server connection");
+ removeWatches(zk2, "/node1", w1, WatcherType.Any, false, Code.CONNECTIONLOSS);
+ fail("Should throw exception as last watch removal requires server connection");
} catch (KeeperException.ConnectionLossException nwe) {
// expected
}
- Assert.assertFalse("Shouldn't remove data watcher", w1.matches());
+ assertFalse("Shouldn't remove data watcher", w1.matches());
// when local=true, here if connection not available, simply removes
// from local session
removeWatches(zk2, "/node1", w1, WatcherType.Any, true, Code.OK);
- Assert.assertTrue("Didn't remove data watcher", w1.matches());
+ assertTrue("Didn't remove data watcher", w1.matches());
}
/**
@@ -555,20 +475,16 @@ public class RemoveWatchesTest extends ClientBase {
final String nodePath = path + i;
w = new MyWatcher(nodePath, 1);
wList.add(w);
- LOG.info("Adding pre node watcher {} on path {}", new Object[] { w,
- nodePath });
+ LOG.info("Adding pre node watcher {} on path {}", new Object[]{w, nodePath});
zk1.exists(nodePath, w);
}
- Assert.assertEquals("Failed to add watchers!", count, zk1
- .getExistWatches().size());
+ assertEquals("Failed to add watchers!", count, zk1.getExistWatches().size());
for (int i = 0; i < count; i++) {
final MyWatcher watcher = wList.get(i);
- removeWatches(zk1, path + i, watcher, WatcherType.Data, false,
- Code.OK);
- Assert.assertTrue("Didn't remove data watcher", watcher.matches());
+ removeWatches(zk1, path + i, watcher, WatcherType.Data, false, Code.OK);
+ assertTrue("Didn't remove data watcher", watcher.matches());
}
- Assert.assertEquals("Didn't remove watch references!", 0, zk1
- .getExistWatches().size());
+ assertEquals("Didn't remove watch references!", 0, zk1.getExistWatches().size());
}
/**
@@ -585,29 +501,24 @@ public class RemoveWatchesTest extends ClientBase {
// Child watcher
for (int i = 0; i < count; i++) {
String nodePath = path + i;
- zk1.create(nodePath, null, Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk1.create(nodePath, null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
nodePath += "/";
}
for (int i = 0; i < count; i++) {
String nodePath = path + i;
w = new MyWatcher(path + i, 1);
wList.add(w);
- LOG.info("Adding child watcher {} on path {}", new Object[] { w,
- nodePath });
+ LOG.info("Adding child watcher {} on path {}", new Object[]{w, nodePath});
zk1.getChildren(nodePath, w);
nodePath += "/";
}
- Assert.assertEquals("Failed to add watchers!", count, zk1
- .getChildWatches().size());
+ assertEquals("Failed to add watchers!", count, zk1.getChildWatches().size());
for (int i = 0; i < count; i++) {
final MyWatcher watcher = wList.get(i);
- removeWatches(zk1, path + i, watcher, WatcherType.Children, false,
- Code.OK);
- Assert.assertTrue("Didn't remove child watcher", watcher.matches());
+ removeWatches(zk1, path + i, watcher, WatcherType.Children, false, Code.OK);
+ assertTrue("Didn't remove child watcher", watcher.matches());
}
- Assert.assertEquals("Didn't remove watch references!", 0, zk1
- .getChildWatches().size());
+ assertEquals("Didn't remove watch references!", 0, zk1.getChildWatches().size());
}
/**
@@ -626,23 +537,18 @@ public class RemoveWatchesTest extends ClientBase {
String nodePath = path + i;
w = new MyWatcher(path + i, 1);
wList.add(w);
- zk1.create(nodePath, null, Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
- LOG.info("Adding data watcher {} on path {}", new Object[] { w,
- nodePath });
+ zk1.create(nodePath, null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
+ LOG.info("Adding data watcher {} on path {}", new Object[]{w, nodePath});
zk1.getData(nodePath, w, null);
nodePath += "/";
}
- Assert.assertEquals("Failed to add watchers!", count, zk1
- .getDataWatches().size());
+ assertEquals("Failed to add watchers!", count, zk1.getDataWatches().size());
for (int i = 0; i < count; i++) {
final MyWatcher watcher = wList.get(i);
- removeWatches(zk1, path + i, watcher, WatcherType.Data, false,
- Code.OK);
- Assert.assertTrue("Didn't remove data watcher", watcher.matches());
+ removeWatches(zk1, path + i, watcher, WatcherType.Data, false, Code.OK);
+ assertTrue("Didn't remove data watcher", watcher.matches());
}
- Assert.assertEquals("Didn't remove watch references!", 0, zk1
- .getDataWatches().size());
+ assertEquals("Didn't remove watch references!", 0, zk1.getDataWatches().size());
}
/**
@@ -659,44 +565,36 @@ public class RemoveWatchesTest extends ClientBase {
// Child watcher
for (int i = 0; i < count; i++) {
String nodePath = path + i;
- zk1.create(nodePath, null, Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk1.create(nodePath, null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
nodePath += "/";
}
for (int i = 0; i < count; i++) {
String nodePath = path + i;
w = new MyWatcher(path + i, 2);
wList.add(w);
- LOG.info("Adding child watcher {} on path {}", new Object[] { w,
- nodePath });
+ LOG.info("Adding child watcher {} on path {}", new Object[]{w, nodePath});
zk1.getChildren(nodePath, w);
nodePath += "/";
}
- Assert.assertEquals("Failed to add watchers!", count, zk1
- .getChildWatches().size());
+ assertEquals("Failed to add watchers!", count, zk1.getChildWatches().size());
// Data watcher
for (int i = 0; i < count; i++) {
String nodePath = path + i;
w = wList.get(i);
- LOG.info("Adding data watcher {} on path {}", new Object[] { w,
- nodePath });
+ LOG.info("Adding data watcher {} on path {}", new Object[]{w, nodePath});
zk1.getData(nodePath, w, null);
nodePath += "/";
}
- Assert.assertEquals("Failed to add watchers!", count, zk1
- .getDataWatches().size());
+ assertEquals("Failed to add watchers!", count, zk1.getDataWatches().size());
stopServer();
for (int i = 0; i < count; i++) {
final MyWatcher watcher = wList.get(i);
- removeWatches(zk1, path + i, watcher, WatcherType.Any, true,
- Code.OK);
- Assert.assertTrue("Didn't remove watcher", watcher.matches());
+ removeWatches(zk1, path + i, watcher, WatcherType.Any, true, Code.OK);
+ assertTrue("Didn't remove watcher", watcher.matches());
}
- Assert.assertEquals("Didn't remove watch references!", 0, zk1
- .getChildWatches().size());
- Assert.assertEquals("Didn't remove watch references!", 0, zk1
- .getDataWatches().size());
+ assertEquals("Didn't remove watch references!", 0, zk1.getChildWatches().size());
+ assertEquals("Didn't remove watch references!", 0, zk1.getDataWatches().size());
}
/**
@@ -721,23 +619,18 @@ public class RemoveWatchesTest extends ClientBase {
zk1.create("/node1", null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
MyWatcher w1 = new MyWatcher("/node1", 2);
MyWatcher w2 = new MyWatcher("/node1", 1);
- LOG.info("Adding data watcher {} on path {}", new Object[] { w1,
- "/node1" });
- Assert.assertNotNull("Didn't set data watches",
- zk2.exists("/node1", w1));
+ LOG.info("Adding data watcher {} on path {}", new Object[]{w1, "/node1"});
+ assertNotNull("Didn't set data watches", zk2.exists("/node1", w1));
// Add multiple child watches
- LOG.info("Adding child watcher {} on path {}", new Object[] { w1,
- "/node1" });
+ LOG.info("Adding child watcher {} on path {}", new Object[]{w1, "/node1"});
zk2.getChildren("/node1", w2);
- LOG.info("Adding child watcher {} on path {}", new Object[] { w2,
- "/node1" });
+ LOG.info("Adding child watcher {} on path {}", new Object[]{w2, "/node1"});
zk2.getChildren("/node1", w1);
removeWatches(zk2, "/node1", w1, WatcherType.Any, false, Code.OK);
- Assert.assertTrue("Didn't remove child watcher", w1.matches());
- Assert.assertEquals("Didn't find child watcher", 1, zk2
- .getChildWatches().size());
+ assertTrue("Didn't remove child watcher", w1.matches());
+ assertEquals("Didn't find child watcher", 1, zk2.getChildWatches().size());
removeWatches(zk2, "/node1", w2, WatcherType.Any, false, Code.OK);
- Assert.assertTrue("Didn't remove child watcher", w2.matches());
+ assertTrue("Didn't remove child watcher", w2.matches());
}
/**
@@ -762,8 +655,7 @@ public class RemoveWatchesTest extends ClientBase {
*
*/
@Test(timeout = 90000)
- public void testNoWatcherServerException()
- throws InterruptedException, IOException, TimeoutException {
+ public void testNoWatcherServerException() throws InterruptedException, IOException, TimeoutException {
CountdownWatcher watcher = new CountdownWatcher();
MyZooKeeper zk = new MyZooKeeper(hostPort, CONNECTION_TIMEOUT, watcher);
boolean nw = false;
@@ -778,22 +670,19 @@ public class RemoveWatchesTest extends ClientBase {
}
}
- Assert.assertTrue("Server didn't return NOWATCHER",
- zk.getRemoveWatchesRC() == Code.NOWATCHER.intValue());
- Assert.assertTrue("NoWatcherException didn't happen", nw);
+ assertTrue("Server didn't return NOWATCHER", zk.getRemoveWatchesRC() == Code.NOWATCHER.intValue());
+ assertTrue("NoWatcherException didn't happen", nw);
}
/**
* Test verifies given watcher doesn't exists!
*/
@Test(timeout = 90000)
- public void testRemoveAllNoWatcherException() throws IOException,
- InterruptedException, KeeperException {
+ public void testRemoveAllNoWatcherException() throws IOException, InterruptedException, KeeperException {
zk1.create("/node1", null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
try {
- removeAllWatches(zk2, "/node1", WatcherType.Any, false,
- Code.NOWATCHER);
- Assert.fail("Should throw exception as given watcher doesn't exists");
+ removeAllWatches(zk2, "/node1", WatcherType.Any, false, Code.NOWATCHER);
+ fail("Should throw exception as given watcher doesn't exists");
} catch (KeeperException.NoWatcherException nwe) {
// expected
}
@@ -807,12 +696,11 @@ public class RemoveWatchesTest extends ClientBase {
zk1.create("/node1", null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
try {
if (useAsync) {
- zk1.removeWatches("/node1", null, WatcherType.Data, false,
- null, null);
+ zk1.removeWatches("/node1", null, WatcherType.Data, false, null, null);
} else {
zk1.removeWatches("/node1", null, WatcherType.Data, false);
}
- Assert.fail("Must throw IllegalArgumentException as watcher is null!");
+ fail("Must throw IllegalArgumentException as watcher is null!");
} catch (IllegalArgumentException iae) {
// expected
}
@@ -844,23 +732,17 @@ public class RemoveWatchesTest extends ClientBase {
}
};
// Add multiple data watches
- LOG.info("Adding data watcher {} on path {}", new Object[] { w1,
- "/node1" });
- Assert.assertNotNull("Didn't set data watches",
- zk2.exists("/node1", w1));
- LOG.info("Adding data watcher {} on path {}", new Object[] { w2,
- "/node1" });
- Assert.assertNotNull("Didn't set data watches",
- zk2.exists("/node1", w2));
+ LOG.info("Adding data watcher {} on path {}", new Object[]{w1, "/node1"});
+ assertNotNull("Didn't set data watches", zk2.exists("/node1", w1));
+ LOG.info("Adding data watcher {} on path {}", new Object[]{w2, "/node1"});
+ assertNotNull("Didn't set data watches", zk2.exists("/node1", w2));
removeWatches(zk2, "/node1", w1, WatcherType.Data, false, Code.OK);
- Assert.assertTrue("Didn't remove data watcher",
- rmWatchCount.await(CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS));
+ assertTrue("Didn't remove data watcher", rmWatchCount.await(CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS));
zk1.setData("/node1", "test".getBytes(), -1);
LOG.info("Waiting for data watchers to be notified");
- Assert.assertTrue("Didn't get data watch notification!",
- dataWatchCount.await(CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS));
+ assertTrue("Didn't get data watch notification!", dataWatchCount.await(CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS));
}
/**
@@ -889,25 +771,17 @@ public class RemoveWatchesTest extends ClientBase {
}
};
// Add multiple child watches
- LOG.info("Adding child watcher {} on path {}", new Object[] { w1,
- "/node1" });
- Assert.assertEquals("Didn't set child watches", 0,
- zk2.getChildren("/node1", w1).size());
- LOG.info("Adding child watcher {} on path {}", new Object[] { w2,
- "/node1" });
- Assert.assertEquals("Didn't set child watches", 0,
- zk2.getChildren("/node1", w2).size());
+ LOG.info("Adding child watcher {} on path {}", new Object[]{w1, "/node1"});
+ assertEquals("Didn't set child watches", 0, zk2.getChildren("/node1", w1).size());
+ LOG.info("Adding child watcher {} on path {}", new Object[]{w2, "/node1"});
+ assertEquals("Didn't set child watches", 0, zk2.getChildren("/node1", w2).size());
removeWatches(zk2, "/node1", w1, WatcherType.Children, false, Code.OK);
- Assert.assertTrue("Didn't remove child watcher",
- rmWatchCount.await(CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS));
+ assertTrue("Didn't remove child watcher", rmWatchCount.await(CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS));
- zk1.create("/node1/node2", null, Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk1.create("/node1/node2", null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
LOG.info("Waiting for child watchers to be notified");
- Assert.assertTrue("Didn't get child watch notification!",
- childWatchCount
- .await(CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS));
+ assertTrue("Didn't get child watch notification!", childWatchCount.await(CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS));
}
/**
@@ -950,25 +824,16 @@ public class RemoveWatchesTest extends ClientBase {
}
};
// Add multiple data watches
- LOG.info("Adding data watcher {} on path {}", new Object[] { w1,
- "/node1" });
- Assert.assertNotNull("Didn't set data watches",
- zk2.exists("/node1", w1));
- LOG.info("Adding data watcher {} on path {}", new Object[] { w2,
- "/node1" });
- Assert.assertNotNull("Didn't set data watches",
- zk2.exists("/node1", w2));
-
- Assert.assertTrue("Server session is not a watcher",
- isServerSessionWatcher(zk2.getSessionId(), "/node1",
- WatcherType.Data));
+ LOG.info("Adding data watcher {} on path {}", new Object[]{w1, "/node1"});
+ assertNotNull("Didn't set data watches", zk2.exists("/node1", w1));
+ LOG.info("Adding data watcher {} on path {}", new Object[]{w2, "/node1"});
+ assertNotNull("Didn't set data watches", zk2.exists("/node1", w2));
+
+ assertTrue("Server session is not a watcher", isServerSessionWatcher(zk2.getSessionId(), "/node1", WatcherType.Data));
removeAllWatches(zk2, "/node1", WatcherType.Data, false, Code.OK);
- Assert.assertTrue("Didn't remove data watcher",
- rmWatchCount.await(CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS));
+ assertTrue("Didn't remove data watcher", rmWatchCount.await(CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS));
- Assert.assertFalse("Server session is still a watcher after removal",
- isServerSessionWatcher(zk2.getSessionId(), "/node1",
- WatcherType.Data));
+ assertFalse("Server session is still a watcher after removal", isServerSessionWatcher(zk2.getSessionId(), "/node1", WatcherType.Data));
}
/**
@@ -1011,25 +876,16 @@ public class RemoveWatchesTest extends ClientBase {
}
};
// Add multiple child watches
- LOG.info("Adding child watcher {} on path {}", new Object[] { w1,
- "/node1" });
- Assert.assertEquals("Didn't set child watches", 0,
- zk2.getChildren("/node1", w1).size());
- LOG.info("Adding child watcher {} on path {}", new Object[] { w2,
- "/node1" });
- Assert.assertEquals("Didn't set child watches", 0,
- zk2.getChildren("/node1", w2).size());
-
- Assert.assertTrue("Server session is not a watcher",
- isServerSessionWatcher(zk2.getSessionId(), "/node1",
- WatcherType.Children));
+ LOG.info("Adding child watcher {} on path {}", new Object[]{w1, "/node1"});
+ assertEquals("Didn't set child watches", 0, zk2.getChildren("/node1", w1).size());
+ LOG.info("Adding child watcher {} on path {}", new Object[]{w2, "/node1"});
+ assertEquals("Didn't set child watches", 0, zk2.getChildren("/node1", w2).size());
+
+ assertTrue("Server session is not a watcher", isServerSessionWatcher(zk2.getSessionId(), "/node1", WatcherType.Children));
removeAllWatches(zk2, "/node1", WatcherType.Children, false, Code.OK);
- Assert.assertTrue("Didn't remove child watcher",
- rmWatchCount.await(CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS));
+ assertTrue("Didn't remove child watcher", rmWatchCount.await(CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS));
- Assert.assertFalse("Server session is still a watcher after removal",
- isServerSessionWatcher(zk2.getSessionId(), "/node1",
- WatcherType.Children));
+ assertFalse("Server session is still a watcher after removal", isServerSessionWatcher(zk2.getSessionId(), "/node1", WatcherType.Children));
}
/**
@@ -1076,42 +932,30 @@ public class RemoveWatchesTest extends ClientBase {
}
};
// Add multiple child watches
- LOG.info("Adding child watcher {} on path {}", new Object[] { w1,
- "/node1" });
- Assert.assertEquals("Didn't set child watches", 0,
- zk2.getChildren("/node1", w1).size());
- LOG.info("Adding child watcher {} on path {}", new Object[] { w2,
- "/node1" });
- Assert.assertEquals("Didn't set child watches", 0,
- zk2.getChildren("/node1", w2).size());
+ LOG.info("Adding child watcher {} on path {}", new Object[]{w1, "/node1"});
+ assertEquals("Didn't set child watches", 0, zk2.getChildren("/node1", w1).size());
+ LOG.info("Adding child watcher {} on path {}", new Object[]{w2, "/node1"});
+ assertEquals("Didn't set child watches", 0, zk2.getChildren("/node1", w2).size());
// Add multiple data watches
- LOG.info("Adding data watcher {} on path {}", new Object[] { w1,
- "/node1" });
- Assert.assertNotNull("Didn't set data watches",
- zk2.exists("/node1", w1));
- LOG.info("Adding data watcher {} on path {}", new Object[] { w2,
- "/node1" });
- Assert.assertNotNull("Didn't set data watches",
- zk2.exists("/node1", w2));
-
- Assert.assertTrue("Server session is not a watcher",
- isServerSessionWatcher(zk2.getSessionId(), "/node1",
- WatcherType.Data));
+ LOG.info("Adding data watcher {} on path {}", new Object[]{w1, "/node1"});
+ assertNotNull("Didn't set data watches", zk2.exists("/node1", w1));
+ LOG.info("Adding data watcher {} on path {}", new Object[]{w2, "/node1"});
+ assertNotNull("Didn't set data watches", zk2.exists("/node1", w2));
+
+ assertTrue("Server session is not a watcher", isServerSessionWatcher(zk2.getSessionId(), "/node1", WatcherType.Data));
removeAllWatches(zk2, "/node1", WatcherType.Any, false, Code.OK);
- Assert.assertTrue("Didn't remove data watcher",
- rmWatchCount.await(CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS));
- Assert.assertFalse("Server session is still a watcher after removal",
- isServerSessionWatcher(zk2.getSessionId(), "/node1",
- WatcherType.Data));
- Assert.assertEquals("Received watch notification after removal!", 2,
- watchCount.getCount());
+ assertTrue("Didn't remove data watcher", rmWatchCount.await(CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS));
+ assertFalse("Server session is still a watcher after removal", isServerSessionWatcher(zk2.getSessionId(), "/node1", WatcherType.Data));
+ assertEquals("Received watch notification after removal!", 2, watchCount.getCount());
}
/* a mocked ZK class that doesn't do client-side verification
* before/after calling removeWatches */
private class MyZooKeeper extends ZooKeeper {
+
class MyWatchManager extends ZKWatchManager {
+
public MyWatchManager(boolean disableAutoWatchReset) {
super(disableAutoWatchReset);
}
@@ -1119,22 +963,24 @@ public class RemoveWatchesTest extends ClientBase {
public int lastrc;
/* Pretend that any watcher exists */
- void containsWatcher(String path, Watcher watcher,
- WatcherType watcherType) throws NoWatcherException {
+ void containsWatcher(String path, Watcher watcher, WatcherType watcherType) throws NoWatcherException {
}
/* save the return error code by the server */
protected boolean removeWatches(
Map<String, Set<Watcher>> pathVsWatcher,
- Watcher watcher, String path, boolean local, int rc,
+ Watcher watcher,
+ String path,
+ boolean local,
+ int rc,
Set<Watcher> removedWatchers) throws KeeperException {
lastrc = rc;
return false;
}
+
}
- public MyZooKeeper(String hp, int timeout, Watcher watcher)
- throws IOException {
+ public MyZooKeeper(String hp, int timeout, Watcher watcher) throws IOException {
super(hp, timeout, watcher, false);
}
@@ -1148,9 +994,11 @@ public class RemoveWatchesTest extends ClientBase {
public int getRemoveWatchesRC() {
return myWatchManager.lastrc;
}
+
}
private class MyWatcher implements Watcher {
+
private final String path;
private String eventPath;
private CountDownLatch latch;
@@ -1161,8 +1009,7 @@ public class RemoveWatchesTest extends ClientBase {
}
public void process(WatchedEvent event) {
- LOG.debug("Event path : {}, eventPath : {}"
- + new Object[] { path, event.getPath() });
+ LOG.debug("Event path : {}, eventPath : {}" + new Object[]{path, event.getPath()});
this.eventPath = event.getPath();
// notifies watcher removal
if (latch.getCount() == 0) {
@@ -1170,8 +1017,7 @@ public class RemoveWatchesTest extends ClientBase {
eventsAfterWatchRemoval.add(event.getType());
}
}
- if (event.getType() == EventType.ChildWatchRemoved
- || event.getType() == EventType.DataWatchRemoved) {
+ if (event.getType() == EventType.ChildWatchRemoved || event.getType() == EventType.DataWatchRemoved) {
latch.countDown();
}
}
@@ -1185,21 +1031,22 @@ public class RemoveWatchesTest extends ClientBase {
* @throws InterruptedException if interrupted while waiting on latch
*/
public boolean matches() throws InterruptedException {
- if (!latch.await(CONNECTION_TIMEOUT/5, TimeUnit.MILLISECONDS)) {
+ if (!latch.await(CONNECTION_TIMEOUT / 5, TimeUnit.MILLISECONDS)) {
LOG.error("Failed waiting to remove the watches");
return false;
}
- LOG.debug("Client path : {} eventPath : {}", new Object[] { path,
- eventPath });
+ LOG.debug("Client path : {} eventPath : {}", new Object[]{path, eventPath});
return path.equals(eventPath);
}
public List<EventType> getEventsAfterWatchRemoval() {
return eventsAfterWatchRemoval;
}
+
}
private class MyCallback implements AsyncCallback.VoidCallback {
+
private final String path;
private final int rc;
private String eventPath;
@@ -1228,11 +1075,12 @@ public class RemoveWatchesTest extends ClientBase {
* @throws InterruptedException if interrupted while waiting on latch
*/
public boolean matches() throws InterruptedException {
- if (!latch.await(CONNECTION_TIMEOUT/5, TimeUnit.MILLISECONDS)) {
+ if (!latch.await(CONNECTION_TIMEOUT / 5, TimeUnit.MILLISECONDS)) {
return false;
}
return path.equals(eventPath) && rc == eventRc;
}
+
}
/**
@@ -1243,16 +1091,15 @@ public class RemoveWatchesTest extends ClientBase {
* @param type the type of watcher
* @return true if the client session is a watcher on path for the type
*/
- private boolean isServerSessionWatcher(long sessionId, String path,
- WatcherType type) {
+ private boolean isServerSessionWatcher(long sessionId, String path, WatcherType type) {
Set<ServerCnxn> cnxns = new HashSet<>();
CollectionUtils.addAll(cnxns, serverFactory.getConnections().iterator());
for (ServerCnxn cnxn : cnxns) {
if (cnxn.getSessionId() == sessionId) {
- return serverFactory.getZooKeeperServer().getZKDatabase().getDataTree()
- .containsWatcher(path, type, cnxn);
+ return serverFactory.getZooKeeperServer().getZKDatabase().getDataTree().containsWatcher(path, type, cnxn);
}
}
return false;
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/SaslAuthTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/SaslAuthTest.java
index 088fe1f02..a63ab1014 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/SaslAuthTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/SaslAuthTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,8 +18,9 @@
package org.apache.zookeeper;
+import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
-
+import static org.junit.Assert.fail;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
@@ -28,7 +29,6 @@ import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
-
import org.apache.zookeeper.ClientCnxn.EventThread;
import org.apache.zookeeper.ClientCnxn.SendThread;
import org.apache.zookeeper.Watcher.Event.KeeperState;
@@ -37,15 +37,14 @@ import org.apache.zookeeper.data.ACL;
import org.apache.zookeeper.data.Id;
import org.apache.zookeeper.test.ClientBase;
import org.junit.AfterClass;
-import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
public class SaslAuthTest extends ClientBase {
+
@BeforeClass
public static void init() {
- System.setProperty("zookeeper.authProvider.1",
- "org.apache.zookeeper.server.auth.SASLAuthenticationProvider");
+ System.setProperty("zookeeper.authProvider.1", "org.apache.zookeeper.server.auth.SASLAuthenticationProvider");
try {
File tmpDir = createTmpDir();
File saslConfFile = new File(tmpDir, "jaas.conf");
@@ -61,7 +60,7 @@ public class SaslAuthTest extends ClientBase {
}
private static String getJaasFileContent() {
- StringBuilder jaasContent=new StringBuilder();
+ StringBuilder jaasContent = new StringBuilder();
String newLine = System.getProperty("line.separator");
jaasContent.append("Server {");
jaasContent.append(newLine);
@@ -91,25 +90,24 @@ public class SaslAuthTest extends ClientBase {
}
private final CountDownLatch authFailed = new CountDownLatch(1);
-
+
@Override
- protected TestableZooKeeper createClient(String hp)
- throws IOException, InterruptedException
- {
+ protected TestableZooKeeper createClient(String hp) throws IOException, InterruptedException {
MyWatcher watcher = new MyWatcher();
return createClient(watcher, hp);
}
private class MyWatcher extends CountdownWatcher {
+
@Override
public synchronized void process(WatchedEvent event) {
if (event.getState() == KeeperState.AuthFailed) {
authFailed.countDown();
- }
- else {
+ } else {
super.process(event);
}
}
+
}
@Test
@@ -134,11 +132,11 @@ public class SaslAuthTest extends ClientBase {
validIds.add("service/host.name.com@KERB.REALM");
int i = 0;
- for(String validId: validIds) {
+ for (String validId : validIds) {
List<ACL> aclList = new ArrayList<ACL>();
- ACL acl = new ACL(0,new Id("sasl",validId));
+ ACL acl = new ACL(0, new Id("sasl", validId));
aclList.add(acl);
- zk.create("/valid"+i,null,aclList,CreateMode.PERSISTENT);
+ zk.create("/valid" + i, null, aclList, CreateMode.PERSISTENT);
i++;
}
}
@@ -152,23 +150,21 @@ public class SaslAuthTest extends ClientBase {
invalidIds.add("user@KERB.REALM1@KERB.REALM2");
int i = 0;
- for(String invalidId: invalidIds) {
+ for (String invalidId : invalidIds) {
List<ACL> aclList = new ArrayList<ACL>();
try {
- ACL acl = new ACL(0,new Id("sasl",invalidId));
+ ACL acl = new ACL(0, new Id("sasl", invalidId));
aclList.add(acl);
- zk.create("/invalid"+i,null,aclList,CreateMode.PERSISTENT);
- Assert.fail("SASLAuthenticationProvider.isValid() failed to catch invalid Id.");
- }
- catch (KeeperException.InvalidACLException e) {
+ zk.create("/invalid" + i, null, aclList, CreateMode.PERSISTENT);
+ fail("SASLAuthenticationProvider.isValid() failed to catch invalid Id.");
+ } catch (KeeperException.InvalidACLException e) {
// ok.
- }
- finally {
+ } finally {
i++;
}
}
}
-
+
@Test
public void testZKOperationsAfterClientSaslAuthFailure() throws Exception {
CountdownWatcher watcher = new CountdownWatcher();
@@ -184,8 +180,7 @@ public class SaslAuthTest extends ClientBase {
boolean success = false;
while (!success && tryCount++ <= totalTry) {
try {
- zk.create("/saslAuthFail", "data".getBytes(), Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT_SEQUENTIAL);
+ zk.create("/saslAuthFail", "data".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL);
success = true;
} catch (KeeperException.ConnectionLossException e) {
Thread.sleep(1000);
@@ -222,10 +217,10 @@ public class SaslAuthTest extends ClientBase {
try {
zk.addAuthInfo("FOO", "BAR".getBytes());
zk.getData("/path1", false, null);
- Assert.fail("Should get auth state error");
+ fail("Should get auth state error");
} catch (KeeperException.AuthFailedException e) {
if (!authFailed.await(CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS)) {
- Assert.fail("Should have called my watcher");
+ fail("Should have called my watcher");
}
}
Field cnxnField = zk.getClass().getDeclaredField("cnxn");
@@ -239,9 +234,8 @@ public class SaslAuthTest extends ClientBase {
EventThread eventThread = (EventThread) eventThreadField.get(clientCnxn);
sendThread.join(CONNECTION_TIMEOUT);
eventThread.join(CONNECTION_TIMEOUT);
- Assert.assertFalse("SendThread did not shutdown after authFail", sendThread.isAlive());
- Assert.assertFalse("EventThread did not shutdown after authFail",
- eventThread.isAlive());
+ assertFalse("SendThread did not shutdown after authFail", sendThread.isAlive());
+ assertFalse("EventThread did not shutdown after authFail", eventThread.isAlive());
} finally {
if (zk != null) {
zk.close();
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/ServerConfigTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/ServerConfigTest.java
index e54267048..a2b437184 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/ServerConfigTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/ServerConfigTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,18 +18,16 @@
package org.apache.zookeeper;
-import org.apache.zookeeper.server.ServerConfig;
-import org.apache.zookeeper.server.quorum.QuorumPeerConfig;
-import org.junit.Before;
-import org.junit.Test;
-
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
-
import java.io.File;
+import org.apache.zookeeper.server.ServerConfig;
+import org.apache.zookeeper.server.quorum.QuorumPeerConfig;
+import org.junit.Before;
+import org.junit.Test;
public class ServerConfigTest {
@@ -40,7 +38,7 @@ public class ServerConfigTest {
serverConfig = new ServerConfig();
}
- @Test(expected=IllegalArgumentException.class)
+ @Test(expected = IllegalArgumentException.class)
public void testFewArguments() {
String[] args = {"2181"};
serverConfig.parse(args);
@@ -57,7 +55,7 @@ public class ServerConfigTest {
assertEquals(10000, serverConfig.getMaxClientCnxns());
}
- @Test(expected=IllegalArgumentException.class)
+ @Test(expected = IllegalArgumentException.class)
public void testTooManyArguments() {
String[] args = {"2181", "/data/dir", "60000", "10000", "9999"};
serverConfig.parse(args);
@@ -94,4 +92,5 @@ public class ServerConfigTest {
assertNotNull(b);
return new File(a).equals(b);
}
-} \ No newline at end of file
+
+}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/TestableZooKeeper.java b/zookeeper-server/src/test/java/org/apache/zookeeper/TestableZooKeeper.java
index 34c8c0cba..a02127aae 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/TestableZooKeeper.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/TestableZooKeeper.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -23,7 +23,6 @@ import java.net.SocketAddress;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
-
import org.apache.jute.Record;
import org.apache.zookeeper.admin.ZooKeeperAdmin;
import org.apache.zookeeper.client.HostProvider;
@@ -32,17 +31,29 @@ import org.apache.zookeeper.proto.RequestHeader;
public class TestableZooKeeper extends ZooKeeperAdmin {
- public TestableZooKeeper(String host, int sessionTimeout,
- Watcher watcher) throws IOException {
+ public TestableZooKeeper(String host, int sessionTimeout, Watcher watcher) throws IOException {
super(host, sessionTimeout, watcher);
}
class TestableClientCnxn extends ClientCnxn {
- TestableClientCnxn(String chrootPath, HostProvider hostProvider, int sessionTimeout, ZooKeeper zooKeeper,
- ClientWatchManager watcher, ClientCnxnSocket clientCnxnSocket, boolean canBeReadOnly)
- throws IOException {
- super(chrootPath, hostProvider, sessionTimeout, zooKeeper, watcher,
- clientCnxnSocket, 0, new byte[16], canBeReadOnly);
+
+ TestableClientCnxn(
+ String chrootPath,
+ HostProvider hostProvider,
+ int sessionTimeout,
+ ZooKeeper zooKeeper,
+ ClientWatchManager watcher,
+ ClientCnxnSocket clientCnxnSocket,
+ boolean canBeReadOnly) throws IOException {
+ super(chrootPath,
+ hostProvider,
+ sessionTimeout,
+ zooKeeper,
+ watcher,
+ clientCnxnSocket,
+ 0,
+ new byte[16],
+ canBeReadOnly);
}
void setXid(int newXid) {
@@ -52,36 +63,45 @@ public class TestableZooKeeper extends ZooKeeperAdmin {
int checkXid() {
return xid;
}
+
}
- protected ClientCnxn createConnection(String chrootPath,
- HostProvider hostProvider, int sessionTimeout, ZooKeeper zooKeeper,
- ClientWatchManager watcher, ClientCnxnSocket clientCnxnSocket,
- boolean canBeReadOnly) throws IOException {
- return new TestableClientCnxn(chrootPath, hostProvider, sessionTimeout, this,
- watcher, clientCnxnSocket, canBeReadOnly);
+ protected ClientCnxn createConnection(
+ String chrootPath,
+ HostProvider hostProvider,
+ int sessionTimeout,
+ ZooKeeper zooKeeper,
+ ClientWatchManager watcher,
+ ClientCnxnSocket clientCnxnSocket,
+ boolean canBeReadOnly) throws IOException {
+ return new TestableClientCnxn(
+ chrootPath,
+ hostProvider,
+ sessionTimeout,
+ this,
+ watcher,
+ clientCnxnSocket,
+ canBeReadOnly);
}
public void setXid(int xid) {
- ((TestableClientCnxn)cnxn).setXid(xid);
+ ((TestableClientCnxn) cnxn).setXid(xid);
}
public int checkXid() {
- return ((TestableClientCnxn)cnxn).checkXid();
+ return ((TestableClientCnxn) cnxn).checkXid();
}
-
+
@Override
public List<String> getChildWatches() {
return super.getChildWatches();
}
-
@Override
public List<String> getDataWatches() {
return super.getDataWatches();
}
-
@Override
public List<String> getExistWatches() {
return super.getExistWatches();
@@ -92,7 +112,7 @@ public class TestableZooKeeper extends ZooKeeperAdmin {
* later attempt to reconnect.
*/
public void testableConnloss() throws IOException {
- synchronized(cnxn) {
+ synchronized (cnxn) {
cnxn.sendThread.testableCloseSocket();
}
}
@@ -107,7 +127,7 @@ public class TestableZooKeeper extends ZooKeeperAdmin {
final CountDownLatch initiatedPause = new CountDownLatch(1);
new Thread() {
public void run() {
- synchronized(cnxn) {
+ synchronized (cnxn) {
try {
try {
cnxn.sendThread.testableCloseSocket();
@@ -146,8 +166,11 @@ public class TestableZooKeeper extends ZooKeeperAdmin {
return cnxn.getLastZxid();
}
- public ReplyHeader submitRequest(RequestHeader h, Record request,
- Record response, WatchRegistration watchRegistration) throws InterruptedException {
+ public ReplyHeader submitRequest(
+ RequestHeader h,
+ Record request,
+ Record response,
+ WatchRegistration watchRegistration) throws InterruptedException {
return cnxn.submitRequest(h, request, response, watchRegistration);
}
@@ -159,4 +182,5 @@ public class TestableZooKeeper extends ZooKeeperAdmin {
public void disconnect() {
cnxn.disconnect();
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/VerGenTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/VerGenTest.java
index 1d99e4546..1542df0ca 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/VerGenTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/VerGenTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,19 +18,17 @@
package org.apache.zookeeper;
+import static org.junit.Assert.assertEquals;
import java.io.File;
import java.util.Arrays;
import java.util.Collection;
-
import org.apache.zookeeper.test.ClientBase;
import org.apache.zookeeper.version.util.VerGen;
-import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
-
/**
* Test VerGen, used during the build.
*
@@ -38,17 +36,10 @@ import org.junit.runners.Parameterized.Parameters;
@RunWith(Parameterized.class)
@Parameterized.UseParametersRunnerFactory(ZKParameterized.RunnerFactory.class)
public class VerGenTest extends ZKTestCase {
+
@Parameters
public static Collection<Object[]> data() {
- return Arrays.asList(new Object[][] {
- {"1.2.3", new Object[] {1, 2, 3, null}},
- {"1.2.3-dev", new Object[] {1, 2, 3, "dev"}},
- {"1.2.3-SNAPSHOT", new Object[] {1, 2, 3, "SNAPSHOT"}},
- {"1.2.3-SNAPSHOT", new Object[] {1, 2, 3, "SNAPSHOT"}},
- {"1.2.3-foo-bar+123", new Object[] {1, 2, 3, "foo-bar+123"}},
- {"1.2.3.4.5-SNAPSHOT", new Object[] {1, 2, 3, "SNAPSHOT"}},
- {"1.2.3.4.5-foo-bar+123", new Object[] {1, 2, 3, "foo-bar+123"}}
- });
+ return Arrays.asList(new Object[][]{{"1.2.3", new Object[]{1, 2, 3, null}}, {"1.2.3-dev", new Object[]{1, 2, 3, "dev"}}, {"1.2.3-SNAPSHOT", new Object[]{1, 2, 3, "SNAPSHOT"}}, {"1.2.3-SNAPSHOT", new Object[]{1, 2, 3, "SNAPSHOT"}}, {"1.2.3-foo-bar+123", new Object[]{1, 2, 3, "foo-bar+123"}}, {"1.2.3.4.5-SNAPSHOT", new Object[]{1, 2, 3, "SNAPSHOT"}}, {"1.2.3.4.5-foo-bar+123", new Object[]{1, 2, 3, "foo-bar+123"}}});
}
private String input;
@@ -63,10 +54,10 @@ public class VerGenTest extends ZKTestCase {
@Test
public void testParser() {
VerGen.Version v = VerGen.parseVersionString(input);
- Assert.assertEquals(expected[0], v.maj);
- Assert.assertEquals(expected[1], v.min);
- Assert.assertEquals(expected[2], v.micro);
- Assert.assertEquals(expected[3], v.qualifier);
+ assertEquals(expected[0], v.maj);
+ assertEquals(expected[1], v.min);
+ assertEquals(expected[2], v.micro);
+ assertEquals(expected[3], v.qualifier);
}
@Test
@@ -76,4 +67,5 @@ public class VerGenTest extends ZKTestCase {
VerGen.generateFile(outputDir, v, "1", "Nov1");
ClientBase.recursiveDelete(outputDir);
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/ZKParameterized.java b/zookeeper-server/src/test/java/org/apache/zookeeper/ZKParameterized.java
index 5bf0b17f2..6b5359096 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/ZKParameterized.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/ZKParameterized.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,6 +18,7 @@
package org.apache.zookeeper;
+import java.util.List;
import org.junit.runners.model.FrameworkMethod;
import org.junit.runners.model.InitializationError;
import org.junit.runners.model.Statement;
@@ -27,32 +28,35 @@ import org.junit.runners.parameterized.TestWithParameters;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.util.List;
-
public class ZKParameterized {
+
private static final Logger LOG = LoggerFactory.getLogger(ZKParameterized.class);
+
public static class RunnerFactory extends BlockJUnit4ClassRunnerWithParametersFactory {
+
@Override
public org.junit.runner.Runner createRunnerForTestWithParameters(TestWithParameters test) throws InitializationError {
return new ZKParameterized.Runner(test);
}
+
}
public static class Runner extends BlockJUnit4ClassRunnerWithParameters {
+
public Runner(TestWithParameters test) throws InitializationError {
super(test);
}
-
@Override
protected List<FrameworkMethod> computeTestMethods() {
return JUnit4ZKTestRunner.computeTestMethodsForClass(getTestClass().getJavaClass(), super.computeTestMethods());
}
-
@Override
protected Statement methodInvoker(FrameworkMethod method, Object test) {
return new JUnit4ZKTestRunner.LoggedInvokeMethod(method, test);
}
+
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/ZKTestCase.java b/zookeeper-server/src/test/java/org/apache/zookeeper/ZKTestCase.java
index 00eeef485..4dfcb1d2b 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/ZKTestCase.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/ZKTestCase.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,15 +18,14 @@
package org.apache.zookeeper;
-import org.junit.Assert;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
+import static org.junit.Assert.fail;
+import java.time.LocalDateTime;
import org.junit.Rule;
import org.junit.rules.TestWatcher;
import org.junit.runner.Description;
import org.junit.runner.RunWith;
-
-import java.time.LocalDateTime;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/**
* Base class for a non-parameterized ZK test.
@@ -37,6 +36,7 @@ import java.time.LocalDateTime;
@SuppressWarnings("deprecation")
@RunWith(JUnit4ZKTestRunner.class)
public class ZKTestCase {
+
private static final Logger LOG = LoggerFactory.getLogger(ZKTestCase.class);
private String testName;
@@ -46,8 +46,8 @@ public class ZKTestCase {
}
@Rule
- public TestWatcher watchman= new TestWatcher() {
-
+ public TestWatcher watchman = new TestWatcher() {
+
@Override
public void starting(Description method) {
// By default, disable starting a JettyAdminServer in tests to avoid
@@ -79,10 +79,12 @@ public class ZKTestCase {
};
public interface WaitForCondition {
+
/**
* @return true when success
*/
boolean evaluate();
+
}
/**
@@ -101,6 +103,7 @@ public class ZKTestCase {
}
Thread.sleep(100);
}
- Assert.fail(msg);
+ fail(msg);
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/ZKUtilTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/ZKUtilTest.java
index cd8e59b00..43e986978 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/ZKUtilTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/ZKUtilTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -15,21 +15,21 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
package org.apache.zookeeper;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assume.assumeTrue;
-
import java.io.File;
import java.io.IOException;
import java.util.UUID;
-
import org.junit.BeforeClass;
import org.junit.Test;
public class ZKUtilTest {
+
private static final File testData = new File(System.getProperty("test.data.dir", "build/test/data"));
@BeforeClass
@@ -85,4 +85,4 @@ public class ZKUtilTest {
assertEquals(expectedMessage, error);
}
-} \ No newline at end of file
+}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/ZooKeeperTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/ZooKeeperTest.java
index 3c85409d5..d19f627e0 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/ZooKeeperTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/ZooKeeperTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -15,10 +15,14 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package org.apache.zookeeper;
-import static org.junit.Assert.*;
+package org.apache.zookeeper;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
@@ -26,10 +30,15 @@ import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
-
import org.apache.zookeeper.AsyncCallback.VoidCallback;
import org.apache.zookeeper.ZooDefs.Ids;
-import org.apache.zookeeper.cli.*;
+import org.apache.zookeeper.cli.CliCommand;
+import org.apache.zookeeper.cli.CliException;
+import org.apache.zookeeper.cli.CliWrapperException;
+import org.apache.zookeeper.cli.LsCommand;
+import org.apache.zookeeper.cli.MalformedCommandException;
+import org.apache.zookeeper.cli.MalformedPathException;
+import org.apache.zookeeper.cli.SyncCommand;
import org.apache.zookeeper.client.ConnectStringParser;
import org.apache.zookeeper.client.HostProvider;
import org.apache.zookeeper.client.StaticHostProvider;
@@ -39,7 +48,6 @@ import org.apache.zookeeper.data.ACL;
import org.apache.zookeeper.data.Id;
import org.apache.zookeeper.data.Stat;
import org.apache.zookeeper.test.ClientBase;
-import org.junit.Assert;
import org.junit.Test;
/**
@@ -52,89 +60,74 @@ public class ZooKeeperTest extends ClientBase {
private static final String LINE_SEPARATOR = System.getProperty("line.separator", "\n");
@Test
- public void testDeleteRecursive()
- throws IOException, InterruptedException, KeeperException
- {
+ public void testDeleteRecursive() throws IOException, InterruptedException, KeeperException {
final ZooKeeper zk = createClient();
setupDataTree(zk);
- Assert.assertTrue(ZKUtil.deleteRecursive(zk, "/a/c", 1000));
+ assertTrue(ZKUtil.deleteRecursive(zk, "/a/c", 1000));
List<String> children = zk.getChildren("/a", false);
- Assert.assertEquals("1 children - c should be deleted ", 1, children.size());
- Assert.assertTrue(children.contains("b"));
+ assertEquals("1 children - c should be deleted ", 1, children.size());
+ assertTrue(children.contains("b"));
- Assert.assertTrue(ZKUtil.deleteRecursive(zk, "/a", 1000));
- Assert.assertNull(zk.exists("/a", null));
+ assertTrue(ZKUtil.deleteRecursive(zk, "/a", 1000));
+ assertNull(zk.exists("/a", null));
}
@Test
- public void testDeleteRecursiveFail()
- throws IOException, InterruptedException, KeeperException
- {
+ public void testDeleteRecursiveFail() throws IOException, InterruptedException, KeeperException {
final ZooKeeper zk = createClient();
setupDataTree(zk);
- ACL deleteProtection = new ACL(ZooDefs.Perms.DELETE,
- new Id("digest", "user:tl+z3z0vO6PfPfEENfLF96E6pM0="/* password is test */));
- List<ACL> acls = Arrays.asList(
- new ACL(ZooDefs.Perms.READ, Ids.ANYONE_ID_UNSAFE),
- deleteProtection
- );
+ ACL deleteProtection = new ACL(ZooDefs.Perms.DELETE, new Id("digest", "user:tl+z3z0vO6PfPfEENfLF96E6pM0="/* password is test */));
+ List<ACL> acls = Arrays.asList(new ACL(ZooDefs.Perms.READ, Ids.ANYONE_ID_UNSAFE), deleteProtection);
// poison the well
zk.create("/a/c/0/surprise", "".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
- Assert.assertEquals(1, zk.getACL("/a/c/0", new Stat()).size());
+ assertEquals(1, zk.getACL("/a/c/0", new Stat()).size());
zk.setACL("/a/c/0", acls, -1);
- Assert.assertEquals(2, zk.getACL("/a/c/0", new Stat()).size());
+ assertEquals(2, zk.getACL("/a/c/0", new Stat()).size());
- Assert.assertFalse(ZKUtil.deleteRecursive(zk, "/a/c", 1000));
+ assertFalse(ZKUtil.deleteRecursive(zk, "/a/c", 1000));
List<String> children = zk.getChildren("/a", false);
- Assert.assertEquals("2 children - c should fail to be deleted ", 2, children.size());
- Assert.assertTrue(children.contains("b"));
+ assertEquals("2 children - c should fail to be deleted ", 2, children.size());
+ assertTrue(children.contains("b"));
- Assert.assertTrue(ZKUtil.deleteRecursive(zk, "/a/b", 1000));
+ assertTrue(ZKUtil.deleteRecursive(zk, "/a/b", 1000));
children = zk.getChildren("/a", false);
- Assert.assertEquals("1 children - b should be deleted ", 1, children.size());
+ assertEquals("1 children - b should be deleted ", 1, children.size());
// acquire immunity to poison
zk.addAuthInfo(deleteProtection.getId().getScheme(), "user:test".getBytes());
- Assert.assertTrue(ZKUtil.deleteRecursive(zk, "/a", 1000));
- Assert.assertNull(zk.exists("/a", null));
+ assertTrue(ZKUtil.deleteRecursive(zk, "/a", 1000));
+ assertNull(zk.exists("/a", null));
}
private void setupDataTree(ZooKeeper zk) throws KeeperException, InterruptedException {
// making sure setdata works on /
zk.setData("/", "some".getBytes(), -1);
- zk.create("/a", "some".getBytes(), Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk.create("/a", "some".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
- zk.create("/a/b", "some".getBytes(), Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk.create("/a/b", "some".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
- zk.create("/a/b/v", "some".getBytes(), Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk.create("/a/b/v", "some".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
for (int i = 1000; i < 3000; ++i) {
- zk.create("/a/b/v/" + i, "some".getBytes(), Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk.create("/a/b/v/" + i, "some".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
}
- zk.create("/a/c", "some".getBytes(), Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk.create("/a/c", "some".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
- zk.create("/a/c/v", "some".getBytes(), Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk.create("/a/c/v", "some".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
for (int i = 0; i < 500; ++i) {
- zk.create("/a/c/" + i, "some".getBytes(), Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk.create("/a/c/" + i, "some".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
}
List<String> children = zk.getChildren("/a", false);
- Assert.assertEquals("2 children - b & c should be present ", 2, children.size());
- Assert.assertTrue(children.contains("b"));
- Assert.assertTrue(children.contains("c"));
+ assertEquals("2 children - b & c should be present ", 2, children.size());
+ assertTrue(children.contains("b"));
+ assertTrue(children.contains("c"));
}
@Test
@@ -142,30 +135,23 @@ public class ZooKeeperTest extends ClientBase {
final ZooKeeper zk = createClient();
// making sure setdata works on /
zk.setData("/", "some".getBytes(), -1);
- zk.create("/a", "some".getBytes(), Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk.create("/a", "some".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
- zk.create("/a/b", "some".getBytes(), Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk.create("/a/b", "some".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
- zk.create("/a/b/v", "some".getBytes(), Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk.create("/a/b/v", "some".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
- zk.create("/a/b/v/1", "some".getBytes(), Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk.create("/a/b/v/1", "some".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
- zk.create("/a/c", "some".getBytes(), Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk.create("/a/c", "some".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
- zk.create("/a/c/v", "some".getBytes(), Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk.create("/a/c/v", "some".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
List<String> children = zk.getChildren("/a", false);
- Assert.assertEquals("2 children - b & c should be present ", children
- .size(), 2);
- Assert.assertTrue(children.contains("b"));
- Assert.assertTrue(children.contains("c"));
+ assertEquals("2 children - b & c should be present ", children.size(), 2);
+ assertTrue(children.contains("b"));
+ assertTrue(children.contains("c"));
ZooKeeperMain zkMain = new ZooKeeperMain(zk);
// 'rmr' is deprecated, so the test here is just for backwards
@@ -173,47 +159,38 @@ public class ZooKeeperTest extends ClientBase {
String cmdstring0 = "rmr /a/b/v";
String cmdstring1 = "deleteall /a";
zkMain.cl.parseCommand(cmdstring0);
- Assert.assertFalse(zkMain.processZKCmd(zkMain.cl));
- Assert.assertEquals(null, zk.exists("/a/b/v", null));
+ assertFalse(zkMain.processZKCmd(zkMain.cl));
+ assertEquals(null, zk.exists("/a/b/v", null));
zkMain.cl.parseCommand(cmdstring1);
- Assert.assertFalse(zkMain.processZKCmd(zkMain.cl));
- Assert.assertNull(zk.exists("/a", null));
+ assertFalse(zkMain.processZKCmd(zkMain.cl));
+ assertNull(zk.exists("/a", null));
}
@Test
- public void testDeleteRecursiveAsync() throws IOException,
- InterruptedException, KeeperException {
+ public void testDeleteRecursiveAsync() throws IOException, InterruptedException, KeeperException {
final ZooKeeper zk = createClient();
// making sure setdata works on /
zk.setData("/", "some".getBytes(), -1);
- zk.create("/a", "some".getBytes(), Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk.create("/a", "some".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
- zk.create("/a/b", "some".getBytes(), Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk.create("/a/b", "some".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
- zk.create("/a/b/v", "some".getBytes(), Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk.create("/a/b/v", "some".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
- zk.create("/a/b/v/1", "some".getBytes(), Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk.create("/a/b/v/1", "some".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
- zk.create("/a/c", "some".getBytes(), Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk.create("/a/c", "some".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
- zk.create("/a/c/v", "some".getBytes(), Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk.create("/a/c/v", "some".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
for (int i = 0; i < 50; ++i) {
- zk.create("/a/c/" + i, "some".getBytes(), Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk.create("/a/c/" + i, "some".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
}
List<String> children = zk.getChildren("/a", false);
- Assert.assertEquals("2 children - b & c should be present ", children
- .size(), 2);
- Assert.assertTrue(children.contains("b"));
- Assert.assertTrue(children.contains("c"));
+ assertEquals("2 children - b & c should be present ", children.size(), 2);
+ assertTrue(children.contains("b"));
+ assertTrue(children.contains("c"));
VoidCallback cb = new VoidCallback() {
@@ -231,22 +208,21 @@ public class ZooKeeperTest extends ClientBase {
synchronized (ctx) {
ctx.wait();
}
- Assert.assertEquals(4, ((AtomicInteger) ctx).get());
+ assertEquals(4, ctx.get());
}
@Test
- public void testStatWhenPathDoesNotExist() throws IOException,
- InterruptedException, MalformedCommandException {
- final ZooKeeper zk = createClient();
- ZooKeeperMain main = new ZooKeeperMain(zk);
- String cmdstring = "stat /invalidPath";
- main.cl.parseCommand(cmdstring);
- try {
- main.processZKCmd(main.cl);
- Assert.fail("As Node does not exist, command should fail by throwing No Node Exception.");
- } catch (CliException e) {
- Assert.assertEquals("Node does not exist: /invalidPath", e.getMessage());
- }
+ public void testStatWhenPathDoesNotExist() throws IOException, InterruptedException, MalformedCommandException {
+ final ZooKeeper zk = createClient();
+ ZooKeeperMain main = new ZooKeeperMain(zk);
+ String cmdstring = "stat /invalidPath";
+ main.cl.parseCommand(cmdstring);
+ try {
+ main.processZKCmd(main.cl);
+ fail("As Node does not exist, command should fail by throwing No Node Exception.");
+ } catch (CliException e) {
+ assertEquals("Node does not exist: /invalidPath", e.getMessage());
+ }
}
@Test
@@ -255,22 +231,22 @@ public class ZooKeeperTest extends ClientBase {
ZooKeeperMain zkMain = new ZooKeeperMain(zk);
String cmdstring = " ls / ";
zkMain.cl.parseCommand(cmdstring);
- Assert.assertEquals("Spaces also considered as characters", zkMain.cl.getNumArguments(), 2);
- Assert.assertEquals("ls is not taken as first argument", zkMain.cl.getCmdArgument(0), "ls");
- Assert.assertEquals("/ is not taken as second argument", zkMain.cl.getCmdArgument(1), "/");
+ assertEquals("Spaces also considered as characters", zkMain.cl.getNumArguments(), 2);
+ assertEquals("ls is not taken as first argument", zkMain.cl.getCmdArgument(0), "ls");
+ assertEquals("/ is not taken as second argument", zkMain.cl.getCmdArgument(1), "/");
}
@Test
public void testParseWithQuotes() throws Exception {
final ZooKeeper zk = createClient();
ZooKeeperMain zkMain = new ZooKeeperMain(zk);
- for (String quoteChar : new String[] {"'", "\""}) {
+ for (String quoteChar : new String[]{"'", "\""}) {
String cmdstring = String.format("create /node %1$squoted data%1$s", quoteChar);
zkMain.cl.parseCommand(cmdstring);
- Assert.assertEquals("quotes combine arguments", zkMain.cl.getNumArguments(), 3);
- Assert.assertEquals("create is not taken as first argument", zkMain.cl.getCmdArgument(0), "create");
- Assert.assertEquals("/node is not taken as second argument", zkMain.cl.getCmdArgument(1), "/node");
- Assert.assertEquals("quoted data is not taken as third argument", zkMain.cl.getCmdArgument(2), "quoted data");
+ assertEquals("quotes combine arguments", zkMain.cl.getNumArguments(), 3);
+ assertEquals("create is not taken as first argument", zkMain.cl.getCmdArgument(0), "create");
+ assertEquals("/node is not taken as second argument", zkMain.cl.getCmdArgument(1), "/node");
+ assertEquals("quoted data is not taken as third argument", zkMain.cl.getCmdArgument(2), "quoted data");
}
}
@@ -278,15 +254,18 @@ public class ZooKeeperTest extends ClientBase {
public void testParseWithMixedQuotes() throws Exception {
final ZooKeeper zk = createClient();
ZooKeeperMain zkMain = new ZooKeeperMain(zk);
- for (String[] quoteChars : new String[][] {{"'", "\""}, {"\"", "'"}}) {
+ for (String[] quoteChars : new String[][]{{"'", "\""}, {"\"", "'"}}) {
String outerQuotes = quoteChars[0];
String innerQuotes = quoteChars[1];
String cmdstring = String.format("create /node %1$s%2$squoted data%2$s%1$s", outerQuotes, innerQuotes);
zkMain.cl.parseCommand(cmdstring);
- Assert.assertEquals("quotes combine arguments", zkMain.cl.getNumArguments(), 3);
- Assert.assertEquals("create is not taken as first argument", zkMain.cl.getCmdArgument(0), "create");
- Assert.assertEquals("/node is not taken as second argument", zkMain.cl.getCmdArgument(1), "/node");
- Assert.assertEquals("quoted data is not taken as third argument", zkMain.cl.getCmdArgument(2), innerQuotes + "quoted data" + innerQuotes);
+ assertEquals("quotes combine arguments", zkMain.cl.getNumArguments(), 3);
+ assertEquals("create is not taken as first argument", zkMain.cl.getCmdArgument(0), "create");
+ assertEquals("/node is not taken as second argument", zkMain.cl.getCmdArgument(1), "/node");
+ assertEquals(
+ "quoted data is not taken as third argument",
+ zkMain.cl.getCmdArgument(2),
+ innerQuotes + "quoted data" + innerQuotes);
}
}
@@ -296,10 +275,10 @@ public class ZooKeeperTest extends ClientBase {
ZooKeeperMain zkMain = new ZooKeeperMain(zk);
String cmdstring = "create /node ''";
zkMain.cl.parseCommand(cmdstring);
- Assert.assertEquals("empty quotes should produce arguments", zkMain.cl.getNumArguments(), 3);
- Assert.assertEquals("create is not taken as first argument", zkMain.cl.getCmdArgument(0), "create");
- Assert.assertEquals("/node is not taken as second argument", zkMain.cl.getCmdArgument(1), "/node");
- Assert.assertEquals("empty string is not taken as third argument", zkMain.cl.getCmdArgument(2), "");
+ assertEquals("empty quotes should produce arguments", zkMain.cl.getNumArguments(), 3);
+ assertEquals("create is not taken as first argument", zkMain.cl.getCmdArgument(0), "create");
+ assertEquals("/node is not taken as second argument", zkMain.cl.getCmdArgument(1), "/node");
+ assertEquals("empty string is not taken as third argument", zkMain.cl.getCmdArgument(2), "");
}
@Test
@@ -308,16 +287,16 @@ public class ZooKeeperTest extends ClientBase {
ZooKeeperMain zkMain = new ZooKeeperMain(zk);
String cmdstring = "create /node '' ''";
zkMain.cl.parseCommand(cmdstring);
- Assert.assertEquals("expected 5 arguments", zkMain.cl.getNumArguments(), 4);
- Assert.assertEquals("create is not taken as first argument", zkMain.cl.getCmdArgument(0), "create");
- Assert.assertEquals("/node is not taken as second argument", zkMain.cl.getCmdArgument(1), "/node");
- Assert.assertEquals("empty string is not taken as third argument", zkMain.cl.getCmdArgument(2), "");
- Assert.assertEquals("empty string is not taken as fourth argument", zkMain.cl.getCmdArgument(3), "");
+ assertEquals("expected 5 arguments", zkMain.cl.getNumArguments(), 4);
+ assertEquals("create is not taken as first argument", zkMain.cl.getCmdArgument(0), "create");
+ assertEquals("/node is not taken as second argument", zkMain.cl.getCmdArgument(1), "/node");
+ assertEquals("empty string is not taken as third argument", zkMain.cl.getCmdArgument(2), "");
+ assertEquals("empty string is not taken as fourth argument", zkMain.cl.getCmdArgument(3), "");
}
@Test
public void testNonexistantCommand() throws Exception {
- testInvalidCommand("cret -s /node1", 127);
+ testInvalidCommand("cret -s /node1", 127);
}
@Test
@@ -347,16 +326,16 @@ public class ZooKeeperTest extends ClientBase {
// Verify that the exit code is set properly
zkMain.processCmd(zkMain.cl);
- Assert.assertEquals(exitCode, zkMain.exitCode);
+ assertEquals(exitCode, zkMain.exitCode);
// Verify that the correct exception is thrown
try {
- zkMain.processZKCmd(zkMain.cl);
- Assert.fail();
+ zkMain.processZKCmd(zkMain.cl);
+ fail();
} catch (CliException e) {
- return;
+ return;
}
- Assert.fail("invalid command should throw CliException");
+ fail("invalid command should throw CliException");
}
@Test
@@ -366,29 +345,23 @@ public class ZooKeeperTest extends ClientBase {
// create persistent sequential node
String cmdstring = "create -s /node ";
zkMain.cl.parseCommand(cmdstring);
- Assert.assertTrue("Doesn't create node without data", zkMain
- .processZKCmd(zkMain.cl));
+ assertTrue("Doesn't create node without data", zkMain.processZKCmd(zkMain.cl));
// create ephemeral node
cmdstring = "create -e /node ";
zkMain.cl.parseCommand(cmdstring);
- Assert.assertTrue("Doesn't create node without data", zkMain
- .processZKCmd(zkMain.cl));
+ assertTrue("Doesn't create node without data", zkMain.processZKCmd(zkMain.cl));
// create ephemeral sequential node
cmdstring = "create -s -e /node ";
zkMain.cl.parseCommand(cmdstring);
- Assert.assertTrue("Doesn't create node without data", zkMain
- .processZKCmd(zkMain.cl));
+ assertTrue("Doesn't create node without data", zkMain.processZKCmd(zkMain.cl));
// creating ephemeral with wrong option.
cmdstring = "create -s y /node";
zkMain.cl.parseCommand(cmdstring);
try {
- Assert.assertTrue("Created node with wrong option", zkMain
- .processZKCmd(zkMain.cl));
- Assert.fail("Created the node with wrong option should "
- + "throw Exception.");
+ assertTrue("Created node with wrong option", zkMain.processZKCmd(zkMain.cl));
+ fail("Created the node with wrong option should " + "throw Exception.");
} catch (MalformedPathException e) {
- Assert.assertEquals("Path must start with / character", e
- .getMessage());
+ assertEquals("Path must start with / character", e.getMessage());
}
}
@@ -399,9 +372,7 @@ public class ZooKeeperTest extends ClientBase {
// create persistent sequential node
String cmdstring = "create -s /l data ip:10.18.52.144:cdrwa f g h";
zkMain.cl.parseCommand(cmdstring);
- Assert.assertTrue(
- "Not considering the extra arguments after the acls.", zkMain
- .processZKCmd(zkMain.cl));
+ assertTrue("Not considering the extra arguments after the acls.", zkMain.processZKCmd(zkMain.cl));
}
@Test
@@ -410,8 +381,7 @@ public class ZooKeeperTest extends ClientBase {
ZooKeeperMain zkMain = new ZooKeeperMain(zk);
String cmdstring = "create /node2";
zkMain.cl.parseCommand(cmdstring);
- Assert.assertTrue("Not creating Persistent node.", zkMain
- .processZKCmd(zkMain.cl));
+ assertTrue("Not creating Persistent node.", zkMain.processZKCmd(zkMain.cl));
}
@Test
@@ -422,11 +392,11 @@ public class ZooKeeperTest extends ClientBase {
String cmdstring2 = "delete /node2";
String cmdstring3 = "ls /node2";
zkMain.cl.parseCommand(cmdstring1);
- Assert.assertTrue(zkMain.processZKCmd(zkMain.cl));
+ assertTrue(zkMain.processZKCmd(zkMain.cl));
zkMain.cl.parseCommand(cmdstring2);
- Assert.assertFalse(zkMain.processZKCmd(zkMain.cl));
+ assertFalse(zkMain.processZKCmd(zkMain.cl));
zkMain.cl.parseCommand(cmdstring3);
- Assert.assertFalse("", zkMain.processCmd(zkMain.cl));
+ assertFalse("", zkMain.processCmd(zkMain.cl));
}
@Test
@@ -442,11 +412,11 @@ public class ZooKeeperTest extends ClientBase {
String cmdstring2 = "stat /node3";
String cmdstring3 = "delete /node3";
zkMain.cl.parseCommand(cmdstring1);
- Assert.assertTrue(zkMain.processZKCmd(zkMain.cl));
+ assertTrue(zkMain.processZKCmd(zkMain.cl));
zkMain.cl.parseCommand(cmdstring2);
- Assert.assertFalse(zkMain.processZKCmd(zkMain.cl));
+ assertFalse(zkMain.processZKCmd(zkMain.cl));
zkMain.cl.parseCommand(cmdstring3);
- Assert.assertFalse(zkMain.processZKCmd(zkMain.cl));
+ assertFalse(zkMain.processZKCmd(zkMain.cl));
}
@Test
@@ -457,10 +427,10 @@ public class ZooKeeperTest extends ClientBase {
String cmdstring1 = "stat /node123";
zkMain.cl.parseCommand(cmdstring1);
try {
- Assert.assertFalse(zkMain.processZKCmd(zkMain.cl));
- Assert.fail("Path doesn't exists so, command should fail.");
+ assertFalse(zkMain.processZKCmd(zkMain.cl));
+ fail("Path doesn't exists so, command should fail.");
} catch (CliWrapperException e) {
- Assert.assertEquals(KeeperException.Code.NONODE, ((KeeperException)e.getCause()).code());
+ assertEquals(KeeperException.Code.NONODE, ((KeeperException) e.getCause()).code());
}
}
@@ -474,37 +444,37 @@ public class ZooKeeperTest extends ClientBase {
Stat stat = new Stat();
int version = 0;
zkMain.cl.parseCommand(cmdstring1);
- Assert.assertTrue(zkMain.processZKCmd(zkMain.cl));
+ assertTrue(zkMain.processZKCmd(zkMain.cl));
stat = zk.exists("/node4", true);
version = stat.getVersion();
zkMain.cl.parseCommand(cmdstring2);
- Assert.assertFalse(zkMain.processZKCmd(zkMain.cl));
+ assertFalse(zkMain.processZKCmd(zkMain.cl));
stat = zk.exists("/node4", true);
- Assert.assertEquals(version + 1, stat.getVersion());
+ assertEquals(version + 1, stat.getVersion());
zkMain.cl.parseCommand(cmdstring3);
- Assert.assertFalse(zkMain.processZKCmd(zkMain.cl));
+ assertFalse(zkMain.processZKCmd(zkMain.cl));
}
@Test
public void testCheckInvalidAcls() throws Exception {
- final ZooKeeper zk = createClient();
- ZooKeeperMain zkMain = new ZooKeeperMain(zk);
- String cmdstring = "create -s -e /node data ip:scheme:gggsd"; //invalid acl's
+ final ZooKeeper zk = createClient();
+ ZooKeeperMain zkMain = new ZooKeeperMain(zk);
+ String cmdstring = "create -s -e /node data ip:scheme:gggsd"; //invalid acl's
- // For Invalid ACls should not throw exception
- zkMain.executeLine(cmdstring);
+ // For Invalid ACls should not throw exception
+ zkMain.executeLine(cmdstring);
}
@Test
public void testDeleteWithInvalidVersionNo() throws Exception {
- final ZooKeeper zk = createClient();
- ZooKeeperMain zkMain = new ZooKeeperMain(zk);
- String cmdstring = "create -s -e /node1 data ";
- String cmdstring1 = "delete /node1 2";//invalid dataversion no
- zkMain.executeLine(cmdstring);
+ final ZooKeeper zk = createClient();
+ ZooKeeperMain zkMain = new ZooKeeperMain(zk);
+ String cmdstring = "create -s -e /node1 data ";
+ String cmdstring1 = "delete /node1 2"; //invalid dataversion no
+ zkMain.executeLine(cmdstring);
- // For Invalid dataversion number should not throw exception
- zkMain.executeLine(cmdstring1);
+ // For Invalid dataversion number should not throw exception
+ zkMain.executeLine(cmdstring1);
}
@Test
@@ -542,16 +512,14 @@ public class ZooKeeperTest extends ClientBase {
System.setErr(new PrintStream(errContent));
try {
zkMain.executeLine(cmd1);
- Assert.assertEquals("Command index out of range", errContent
- .toString().trim());
+ assertEquals("Command index out of range", errContent.toString().trim());
} finally {
// revert redirect of out/err streams - important step!
System.setErr(systemErr);
}
}
- private static void runCommandExpect(CliCommand command, List<String> expectedResults)
- throws Exception {
+ private static void runCommandExpect(CliCommand command, List<String> expectedResults) throws Exception {
// call command and put result in byteStream
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
PrintStream out = new PrintStream(byteStream);
@@ -559,8 +527,7 @@ public class ZooKeeperTest extends ClientBase {
command.exec();
String result = byteStream.toString();
- assertTrue(result, result.contains(
- StringUtils.joinStrings(expectedResults, LINE_SEPARATOR)));
+ assertTrue(result, result.contains(StringUtils.joinStrings(expectedResults, LINE_SEPARATOR)));
}
@Test
@@ -654,9 +621,9 @@ public class ZooKeeperTest extends ClientBase {
try {
runCommandExpect(cmd, new ArrayList<String>());
- Assert.fail("Path doesn't exists so, command should fail.");
+ fail("Path doesn't exists so, command should fail.");
} catch (CliWrapperException e) {
- Assert.assertEquals(KeeperException.Code.NONODE, ((KeeperException)e.getCause()).code());
+ assertEquals(KeeperException.Code.NONODE, ((KeeperException) e.getCause()).code());
}
}
@@ -675,14 +642,14 @@ public class ZooKeeperTest extends ClientBase {
ZooKeeperMain zkMain = new ZooKeeperMain(zk);
String setAclCommand = "setAcl -R /a world:anyone:r";
zkMain.cl.parseCommand(setAclCommand);
- Assert.assertFalse(zkMain.processZKCmd(zkMain.cl));
+ assertFalse(zkMain.processZKCmd(zkMain.cl));
- Assert.assertEquals(Ids.READ_ACL_UNSAFE, zk.getACL("/a", new Stat()));
- Assert.assertEquals(Ids.READ_ACL_UNSAFE, zk.getACL("/a/b", new Stat()));
- Assert.assertEquals(Ids.READ_ACL_UNSAFE, zk.getACL("/a/b/c", new Stat()));
- Assert.assertEquals(Ids.READ_ACL_UNSAFE, zk.getACL("/a/d", new Stat()));
+ assertEquals(Ids.READ_ACL_UNSAFE, zk.getACL("/a", new Stat()));
+ assertEquals(Ids.READ_ACL_UNSAFE, zk.getACL("/a/b", new Stat()));
+ assertEquals(Ids.READ_ACL_UNSAFE, zk.getACL("/a/b/c", new Stat()));
+ assertEquals(Ids.READ_ACL_UNSAFE, zk.getACL("/a/d", new Stat()));
// /e is unset, its acl should remain the same.
- Assert.assertEquals(Ids.OPEN_ACL_UNSAFE, zk.getACL("/e", new Stat()));
+ assertEquals(Ids.OPEN_ACL_UNSAFE, zk.getACL("/e", new Stat()));
}
@Test
@@ -692,16 +659,20 @@ public class ZooKeeperTest extends ClientBase {
try {
zk = createClient();
ZKClientConfig clientConfig = new ZKClientConfig();
- clientConfig.setProperty(ZKClientConfig.ZOOKEEPER_CLIENT_CNXN_SOCKET,
- "org.apache.zookeeper.ClientCnxnSocketNetty");
+ clientConfig.setProperty(ZKClientConfig.ZOOKEEPER_CLIENT_CNXN_SOCKET, "org.apache.zookeeper.ClientCnxnSocketNetty");
CountdownWatcher watcher = new CountdownWatcher();
- HostProvider aHostProvider = new StaticHostProvider(
- new ConnectStringParser(hostPort).getServerAddresses());
- newZKClient = new ZooKeeper(hostPort, zk.getSessionTimeout(), watcher,
- zk.getSessionId(), zk.getSessionPasswd(), false, aHostProvider, clientConfig);
+ HostProvider aHostProvider = new StaticHostProvider(new ConnectStringParser(hostPort).getServerAddresses());
+ newZKClient = new ZooKeeper(
+ hostPort,
+ zk.getSessionTimeout(),
+ watcher,
+ zk.getSessionId(),
+ zk.getSessionPasswd(),
+ false,
+ aHostProvider,
+ clientConfig);
watcher.waitForConnected(CONNECTION_TIMEOUT);
- assertEquals("Old client session id and new clinet session id must be same",
- zk.getSessionId(), newZKClient.getSessionId());
+ assertEquals("Old client session id and new clinet session id must be same", zk.getSessionId(), newZKClient.getSessionId());
} finally {
zk.close();
newZKClient.close();
@@ -719,4 +690,5 @@ public class ZooKeeperTest extends ClientBase {
runCommandExpect(cmd, expected);
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/client/ZKClientConfigTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/client/ZKClientConfigTest.java
index 00a57f4aa..e0c25a104 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/client/ZKClientConfigTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/client/ZKClientConfigTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -29,7 +29,6 @@ import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
-
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
@@ -38,7 +37,6 @@ import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
-
import org.apache.zookeeper.common.ZKConfig;
import org.apache.zookeeper.server.quorum.QuorumPeerConfig.ConfigException;
import org.junit.BeforeClass;
@@ -47,6 +45,7 @@ import org.junit.Test;
import org.junit.rules.Timeout;
public class ZKClientConfigTest {
+
private static final File testData = new File(System.getProperty("test.data.dir", "src/test/resources/data"));
@Rule
public Timeout timeout = new Timeout(10, TimeUnit.SECONDS);
@@ -144,8 +143,7 @@ public class ZKClientConfigTest {
@Test
public void testSetConfiguration() {
ZKClientConfig conf = new ZKClientConfig();
- String defaultValue = conf.getProperty(ZKClientConfig.ENABLE_CLIENT_SASL_KEY,
- ZKClientConfig.ENABLE_CLIENT_SASL_DEFAULT);
+ String defaultValue = conf.getProperty(ZKClientConfig.ENABLE_CLIENT_SASL_KEY, ZKClientConfig.ENABLE_CLIENT_SASL_DEFAULT);
if (defaultValue.equals("true")) {
conf.setProperty(ENABLE_CLIENT_SASL_KEY, "false");
} else {
@@ -182,8 +180,7 @@ public class ZKClientConfigTest {
// property is set but with white spaces
value = 12345;
- conf.setProperty(ZKConfig.JUTE_MAXBUFFER,
- " " + Integer.toString(value) + " ");
+ conf.setProperty(ZKConfig.JUTE_MAXBUFFER, " " + value + " ");
result = conf.getInt(ZKConfig.JUTE_MAXBUFFER, defaultValue);
assertEquals(value, result);
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/common/AtomicFileWritingIdiomTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/common/AtomicFileWritingIdiomTest.java
index 477ac8e33..d128ecc84 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/common/AtomicFileWritingIdiomTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/common/AtomicFileWritingIdiomTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -15,19 +15,19 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
package org.apache.zookeeper.common;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
-
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.Writer;
-
+import java.nio.charset.StandardCharsets;
import org.apache.zookeeper.ZKTestCase;
import org.apache.zookeeper.common.AtomicFileWritingIdiom.OutputStreamStatement;
import org.apache.zookeeper.common.AtomicFileWritingIdiom.WriterStatement;
@@ -53,7 +53,7 @@ public class AtomicFileWritingIdiomTest extends ZKTestCase {
new AtomicFileWritingIdiom(target, new OutputStreamStatement() {
@Override
public void write(OutputStream os) throws IOException {
- os.write("after".getBytes("ASCII"));
+ os.write("after".getBytes(StandardCharsets.US_ASCII));
assertTrue("implementation of AtomicFileOutputStream has changed, update the test", tmp.exists());
}
});
@@ -93,7 +93,7 @@ public class AtomicFileWritingIdiomTest extends ZKTestCase {
new AtomicFileWritingIdiom(target, new OutputStreamStatement() {
@Override
public void write(OutputStream os) throws IOException {
- os.write("after".getBytes("ASCII"));
+ os.write("after".getBytes(StandardCharsets.US_ASCII));
os.flush();
assertTrue("implementation of AtomicFileOutputStream has changed, update the test", tmp.exists());
throw new RuntimeException();
@@ -147,7 +147,7 @@ public class AtomicFileWritingIdiomTest extends ZKTestCase {
new AtomicFileWritingIdiom(target, new OutputStreamStatement() {
@Override
public void write(OutputStream os) throws IOException {
- os.write("after".getBytes("ASCII"));
+ os.write("after".getBytes(StandardCharsets.US_ASCII));
os.flush();
assertTrue("implementation of AtomicFileOutputStream has changed, update the test", tmp.exists());
throw new IOException();
@@ -201,7 +201,7 @@ public class AtomicFileWritingIdiomTest extends ZKTestCase {
new AtomicFileWritingIdiom(target, new OutputStreamStatement() {
@Override
public void write(OutputStream os) throws IOException {
- os.write("after".getBytes("ASCII"));
+ os.write("after".getBytes(StandardCharsets.US_ASCII));
os.flush();
assertTrue("implementation of AtomicFileOutputStream has changed, update the test", tmp.exists());
throw new Error();
@@ -255,7 +255,7 @@ public class AtomicFileWritingIdiomTest extends ZKTestCase {
new AtomicFileWritingIdiom(target, new OutputStreamStatement() {
@Override
public void write(OutputStream os) throws IOException {
- os.write("after".getBytes("ASCII"));
+ os.write("after".getBytes(StandardCharsets.US_ASCII));
assertTrue("implementation of AtomicFileOutputStream has changed, update the test", tmp.exists());
}
});
@@ -294,7 +294,7 @@ public class AtomicFileWritingIdiomTest extends ZKTestCase {
new AtomicFileWritingIdiom(target, new OutputStreamStatement() {
@Override
public void write(OutputStream os) throws IOException {
- os.write("after".getBytes("ASCII"));
+ os.write("after".getBytes(StandardCharsets.US_ASCII));
os.flush();
assertTrue("implementation of AtomicFileOutputStream has changed, update the test", tmp.exists());
throw new RuntimeException();
@@ -341,7 +341,7 @@ public class AtomicFileWritingIdiomTest extends ZKTestCase {
byte[] b = new byte[20];
int nb;
while ((nb = fis.read(b)) != -1) {
- result.append(new String(b, 0, nb, encoding));
+ result.append(new String(b, 0, nb, encoding));
}
fis.close();
return result.toString();
@@ -353,7 +353,7 @@ public class AtomicFileWritingIdiomTest extends ZKTestCase {
private void createFile(File file, String content) throws IOException {
FileOutputStream fos = new FileOutputStream(file);
- fos.write(content.getBytes("ASCII"));
+ fos.write(content.getBytes(StandardCharsets.US_ASCII));
fos.close();
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/common/BaseX509ParameterizedTestCase.java b/zookeeper-server/src/test/java/org/apache/zookeeper/common/BaseX509ParameterizedTestCase.java
index 73b91963d..b4790cfd9 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/common/BaseX509ParameterizedTestCase.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/common/BaseX509ParameterizedTestCase.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -25,7 +25,6 @@ import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
-
import org.apache.commons.io.FileUtils;
import org.apache.zookeeper.ZKTestCase;
import org.apache.zookeeper.test.ClientBase;
@@ -42,6 +41,7 @@ import org.junit.BeforeClass;
* and caching the X509TestContext objects used by the tests.
*/
public abstract class BaseX509ParameterizedTestCase extends ZKTestCase {
+
/**
* Default parameters suitable for most subclasses. See example usage
* in {@link X509UtilTest}.
@@ -97,8 +97,7 @@ public abstract class BaseX509ParameterizedTestCase extends ZKTestCase {
* for the current index if one is not already cached.
*/
protected BaseX509ParameterizedTestCase(
- Integer paramIndex,
- java.util.function.Supplier<X509TestContext> contextSupplier) {
+ Integer paramIndex, java.util.function.Supplier<X509TestContext> contextSupplier) {
if (cachedTestContexts.containsKey(paramIndex)) {
x509TestContext = cachedTestContexts.get(paramIndex);
} else {
@@ -106,4 +105,5 @@ public abstract class BaseX509ParameterizedTestCase extends ZKTestCase {
cachedTestContexts.put(paramIndex, x509TestContext);
}
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/common/FileChangeWatcherTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/common/FileChangeWatcherTest.java
index 2ef6a8625..d85c86e81 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/common/FileChangeWatcherTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/common/FileChangeWatcherTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,6 +18,9 @@
package org.apache.zookeeper.common;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
@@ -26,7 +29,6 @@ import java.nio.file.WatchEvent;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
-
import org.apache.commons.io.FileUtils;
import org.apache.zookeeper.ZKTestCase;
import org.apache.zookeeper.test.ClientBase;
@@ -36,11 +38,8 @@ import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-
public class FileChangeWatcherTest extends ZKTestCase {
+
private static File tempDir;
private static File tempFile;
@@ -67,31 +66,25 @@ public class FileChangeWatcherTest extends ZKTestCase {
FileChangeWatcher watcher = null;
try {
final List<WatchEvent<?>> events = new ArrayList<>();
- watcher = new FileChangeWatcher(
- tempDir.toPath(),
- event -> {
- LOG.info("Got an update: " + event.kind() + " " + event.context());
- // Filter out the extra ENTRY_CREATE events that are
- // sometimes seen at the start. Even though we create the watcher
- // after the file exists, sometimes we still get a create event.
- if (StandardWatchEventKinds.ENTRY_CREATE.equals(event.kind())) {
- return;
- }
- synchronized (events) {
- events.add(event);
- events.notifyAll();
- }
- });
+ watcher = new FileChangeWatcher(tempDir.toPath(), event -> {
+ LOG.info("Got an update: " + event.kind() + " " + event.context());
+ // Filter out the extra ENTRY_CREATE events that are
+ // sometimes seen at the start. Even though we create the watcher
+ // after the file exists, sometimes we still get a create event.
+ if (StandardWatchEventKinds.ENTRY_CREATE.equals(event.kind())) {
+ return;
+ }
+ synchronized (events) {
+ events.add(event);
+ events.notifyAll();
+ }
+ });
watcher.start();
watcher.waitForState(FileChangeWatcher.State.RUNNING);
- Thread.sleep(1000L); // XXX hack
+ Thread.sleep(1000L); // TODO hack
for (int i = 0; i < 3; i++) {
LOG.info("Modifying file, attempt " + (i + 1));
- FileUtils.writeStringToFile(
- tempFile,
- "Hello world " + i + "\n",
- StandardCharsets.UTF_8,
- true);
+ FileUtils.writeStringToFile(tempFile, "Hello world " + i + "\n", StandardCharsets.UTF_8, true);
synchronized (events) {
if (events.size() < i + 1) {
events.wait(3000L);
@@ -115,24 +108,22 @@ public class FileChangeWatcherTest extends ZKTestCase {
FileChangeWatcher watcher = null;
try {
final List<WatchEvent<?>> events = new ArrayList<>();
- watcher = new FileChangeWatcher(
- tempDir.toPath(),
- event -> {
- LOG.info("Got an update: " + event.kind() + " " + event.context());
- // Filter out the extra ENTRY_CREATE events that are
- // sometimes seen at the start. Even though we create the watcher
- // after the file exists, sometimes we still get a create event.
- if (StandardWatchEventKinds.ENTRY_CREATE.equals(event.kind())) {
- return;
- }
- synchronized (events) {
- events.add(event);
- events.notifyAll();
- }
- });
+ watcher = new FileChangeWatcher(tempDir.toPath(), event -> {
+ LOG.info("Got an update: " + event.kind() + " " + event.context());
+ // Filter out the extra ENTRY_CREATE events that are
+ // sometimes seen at the start. Even though we create the watcher
+ // after the file exists, sometimes we still get a create event.
+ if (StandardWatchEventKinds.ENTRY_CREATE.equals(event.kind())) {
+ return;
+ }
+ synchronized (events) {
+ events.add(event);
+ events.notifyAll();
+ }
+ });
watcher.start();
watcher.waitForState(FileChangeWatcher.State.RUNNING);
- Thread.sleep(1000L); // XXX hack
+ Thread.sleep(1000L); // TODO hack
LOG.info("Touching file");
FileUtils.touch(tempFile);
synchronized (events) {
@@ -157,18 +148,16 @@ public class FileChangeWatcherTest extends ZKTestCase {
FileChangeWatcher watcher = null;
try {
final List<WatchEvent<?>> events = new ArrayList<>();
- watcher = new FileChangeWatcher(
- tempDir.toPath(),
- event -> {
- LOG.info("Got an update: " + event.kind() + " " + event.context());
- synchronized (events) {
- events.add(event);
- events.notifyAll();
- }
- });
+ watcher = new FileChangeWatcher(tempDir.toPath(), event -> {
+ LOG.info("Got an update: " + event.kind() + " " + event.context());
+ synchronized (events) {
+ events.add(event);
+ events.notifyAll();
+ }
+ });
watcher.start();
watcher.waitForState(FileChangeWatcher.State.RUNNING);
- Thread.sleep(1000L); // XXX hack
+ Thread.sleep(1000L); // TODO hack
File tempFile2 = File.createTempFile("zk_test_", "", tempDir);
tempFile2.deleteOnExit();
synchronized (events) {
@@ -193,24 +182,22 @@ public class FileChangeWatcherTest extends ZKTestCase {
FileChangeWatcher watcher = null;
try {
final List<WatchEvent<?>> events = new ArrayList<>();
- watcher = new FileChangeWatcher(
- tempDir.toPath(),
- event -> {
- LOG.info("Got an update: " + event.kind() + " " + event.context());
- // Filter out the extra ENTRY_CREATE events that are
- // sometimes seen at the start. Even though we create the watcher
- // after the file exists, sometimes we still get a create event.
- if (StandardWatchEventKinds.ENTRY_CREATE.equals(event.kind())) {
- return;
- }
- synchronized (events) {
- events.add(event);
- events.notifyAll();
- }
- });
+ watcher = new FileChangeWatcher(tempDir.toPath(), event -> {
+ LOG.info("Got an update: " + event.kind() + " " + event.context());
+ // Filter out the extra ENTRY_CREATE events that are
+ // sometimes seen at the start. Even though we create the watcher
+ // after the file exists, sometimes we still get a create event.
+ if (StandardWatchEventKinds.ENTRY_CREATE.equals(event.kind())) {
+ return;
+ }
+ synchronized (events) {
+ events.add(event);
+ events.notifyAll();
+ }
+ });
watcher.start();
watcher.waitForState(FileChangeWatcher.State.RUNNING);
- Thread.sleep(1000L); // XXX hack
+ Thread.sleep(1000L); // TODO hack
tempFile.delete();
synchronized (events) {
if (events.isEmpty()) {
@@ -234,22 +221,20 @@ public class FileChangeWatcherTest extends ZKTestCase {
FileChangeWatcher watcher = null;
try {
final AtomicInteger callCount = new AtomicInteger(0);
- watcher = new FileChangeWatcher(
- tempDir.toPath(),
- event -> {
- LOG.info("Got an update: " + event.kind() + " " + event.context());
- int oldValue;
- synchronized (callCount) {
- oldValue = callCount.getAndIncrement();
- callCount.notifyAll();
- }
- if (oldValue == 0) {
- throw new RuntimeException("This error should not crash the watcher thread");
- }
- });
+ watcher = new FileChangeWatcher(tempDir.toPath(), event -> {
+ LOG.info("Got an update: " + event.kind() + " " + event.context());
+ int oldValue;
+ synchronized (callCount) {
+ oldValue = callCount.getAndIncrement();
+ callCount.notifyAll();
+ }
+ if (oldValue == 0) {
+ throw new RuntimeException("This error should not crash the watcher thread");
+ }
+ });
watcher.start();
watcher.waitForState(FileChangeWatcher.State.RUNNING);
- Thread.sleep(1000L); // XXX hack
+ Thread.sleep(1000L); // TODO hack
LOG.info("Modifying file");
FileUtils.writeStringToFile(tempFile, "Hello world\n", StandardCharsets.UTF_8, true);
synchronized (callCount) {
@@ -274,4 +259,5 @@ public class FileChangeWatcherTest extends ZKTestCase {
}
}
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/common/FileKeyStoreLoaderBuilderProviderTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/common/FileKeyStoreLoaderBuilderProviderTest.java
index 612eb0da0..52640e505 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/common/FileKeyStoreLoaderBuilderProviderTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/common/FileKeyStoreLoaderBuilderProviderTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,37 +18,33 @@
package org.apache.zookeeper.common;
+import static org.junit.Assert.assertTrue;
import org.apache.zookeeper.ZKTestCase;
-import org.junit.Assert;
import org.junit.Test;
public class FileKeyStoreLoaderBuilderProviderTest extends ZKTestCase {
+
@Test
public void testGetBuilderForJKSFileType() {
- FileKeyStoreLoader.Builder<?> builder =
- FileKeyStoreLoaderBuilderProvider.getBuilderForKeyStoreFileType(
- KeyStoreFileType.JKS);
- Assert.assertTrue(builder instanceof JKSFileLoader.Builder);
+ FileKeyStoreLoader.Builder<?> builder = FileKeyStoreLoaderBuilderProvider.getBuilderForKeyStoreFileType(KeyStoreFileType.JKS);
+ assertTrue(builder instanceof JKSFileLoader.Builder);
}
@Test
public void testGetBuilderForPEMFileType() {
- FileKeyStoreLoader.Builder<?> builder =
- FileKeyStoreLoaderBuilderProvider.getBuilderForKeyStoreFileType(
- KeyStoreFileType.PEM);
- Assert.assertTrue(builder instanceof PEMFileLoader.Builder);
+ FileKeyStoreLoader.Builder<?> builder = FileKeyStoreLoaderBuilderProvider.getBuilderForKeyStoreFileType(KeyStoreFileType.PEM);
+ assertTrue(builder instanceof PEMFileLoader.Builder);
}
@Test
public void testGetBuilderForPKCS12FileType() {
- FileKeyStoreLoader.Builder<?> builder =
- FileKeyStoreLoaderBuilderProvider.getBuilderForKeyStoreFileType(
- KeyStoreFileType.PKCS12);
- Assert.assertTrue(builder instanceof PKCS12FileLoader.Builder);
+ FileKeyStoreLoader.Builder<?> builder = FileKeyStoreLoaderBuilderProvider.getBuilderForKeyStoreFileType(KeyStoreFileType.PKCS12);
+ assertTrue(builder instanceof PKCS12FileLoader.Builder);
}
@Test(expected = NullPointerException.class)
public void testGetBuilderForNullFileType() {
FileKeyStoreLoaderBuilderProvider.getBuilderForKeyStoreFileType(null);
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/common/JKSFileLoaderTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/common/JKSFileLoaderTest.java
index 5e916f36f..7a349bcde 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/common/JKSFileLoaderTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/common/JKSFileLoaderTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,11 +18,10 @@
package org.apache.zookeeper.common;
+import static org.junit.Assert.assertEquals;
import java.io.IOException;
import java.security.KeyStore;
import java.util.Collection;
-
-import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
@@ -36,19 +35,10 @@ public class JKSFileLoaderTest extends BaseX509ParameterizedTestCase {
}
public JKSFileLoaderTest(
- final X509KeyType caKeyType,
- final X509KeyType certKeyType,
- final String keyPassword,
- final Integer paramIndex) {
+ final X509KeyType caKeyType, final X509KeyType certKeyType, final String keyPassword, final Integer paramIndex) {
super(paramIndex, () -> {
try {
- return X509TestContext.newBuilder()
- .setTempDir(tempDir)
- .setKeyStorePassword(keyPassword)
- .setKeyStoreKeyType(certKeyType)
- .setTrustStorePassword(keyPassword)
- .setTrustStoreKeyType(caKeyType)
- .build();
+ return X509TestContext.newBuilder().setTempDir(tempDir).setKeyStorePassword(keyPassword).setKeyStoreKeyType(certKeyType).setTrustStorePassword(keyPassword).setTrustStoreKeyType(caKeyType).build();
} catch (Exception e) {
throw new RuntimeException(e);
}
@@ -57,109 +47,66 @@ public class JKSFileLoaderTest extends BaseX509ParameterizedTestCase {
@Test
public void testLoadKeyStore() throws Exception {
- String path = x509TestContext.getKeyStoreFile(KeyStoreFileType.JKS)
- .getAbsolutePath();
- KeyStore ks = new JKSFileLoader.Builder()
- .setKeyStorePath(path)
- .setKeyStorePassword(x509TestContext.getKeyStorePassword())
- .build()
- .loadKeyStore();
- Assert.assertEquals(1, ks.size());
+ String path = x509TestContext.getKeyStoreFile(KeyStoreFileType.JKS).getAbsolutePath();
+ KeyStore ks = new JKSFileLoader.Builder().setKeyStorePath(path).setKeyStorePassword(x509TestContext.getKeyStorePassword()).build().loadKeyStore();
+ assertEquals(1, ks.size());
}
@Test(expected = Exception.class)
public void testLoadKeyStoreWithWrongPassword() throws Exception {
- String path = x509TestContext.getKeyStoreFile(KeyStoreFileType.JKS)
- .getAbsolutePath();
- new JKSFileLoader.Builder()
- .setKeyStorePath(path)
- .setKeyStorePassword("wrong password")
- .build()
- .loadKeyStore();
+ String path = x509TestContext.getKeyStoreFile(KeyStoreFileType.JKS).getAbsolutePath();
+ new JKSFileLoader.Builder().setKeyStorePath(path).setKeyStorePassword("wrong password").build().loadKeyStore();
}
@Test(expected = IOException.class)
public void testLoadKeyStoreWithWrongFilePath() throws Exception {
- String path = x509TestContext.getKeyStoreFile(KeyStoreFileType.JKS)
- .getAbsolutePath();
- new JKSFileLoader.Builder()
- .setKeyStorePath(path + ".does_not_exist")
- .setKeyStorePassword(x509TestContext.getKeyStorePassword())
- .build()
- .loadKeyStore();
+ String path = x509TestContext.getKeyStoreFile(KeyStoreFileType.JKS).getAbsolutePath();
+ new JKSFileLoader.Builder().setKeyStorePath(path
+ + ".does_not_exist").setKeyStorePassword(x509TestContext.getKeyStorePassword()).build().loadKeyStore();
}
@Test(expected = NullPointerException.class)
public void testLoadKeyStoreWithNullFilePath() throws Exception {
- new JKSFileLoader.Builder()
- .setKeyStorePassword(x509TestContext.getKeyStorePassword())
- .build()
- .loadKeyStore();
+ new JKSFileLoader.Builder().setKeyStorePassword(x509TestContext.getKeyStorePassword()).build().loadKeyStore();
}
@Test(expected = IOException.class)
public void testLoadKeyStoreWithWrongFileType() throws Exception {
// Trying to load a PEM file with JKS loader should fail
- String path = x509TestContext.getKeyStoreFile(KeyStoreFileType.PEM)
- .getAbsolutePath();
- new JKSFileLoader.Builder()
- .setKeyStorePath(path)
- .setKeyStorePassword(x509TestContext.getKeyStorePassword())
- .build()
- .loadKeyStore();
+ String path = x509TestContext.getKeyStoreFile(KeyStoreFileType.PEM).getAbsolutePath();
+ new JKSFileLoader.Builder().setKeyStorePath(path).setKeyStorePassword(x509TestContext.getKeyStorePassword()).build().loadKeyStore();
}
@Test
public void testLoadTrustStore() throws Exception {
- String path = x509TestContext.getTrustStoreFile(KeyStoreFileType.JKS)
- .getAbsolutePath();
- KeyStore ts = new JKSFileLoader.Builder()
- .setTrustStorePath(path)
- .setTrustStorePassword(x509TestContext.getTrustStorePassword())
- .build()
- .loadTrustStore();
- Assert.assertEquals(1, ts.size());
+ String path = x509TestContext.getTrustStoreFile(KeyStoreFileType.JKS).getAbsolutePath();
+ KeyStore ts = new JKSFileLoader.Builder().setTrustStorePath(path).setTrustStorePassword(x509TestContext.getTrustStorePassword()).build().loadTrustStore();
+ assertEquals(1, ts.size());
}
@Test(expected = Exception.class)
public void testLoadTrustStoreWithWrongPassword() throws Exception {
- String path = x509TestContext.getTrustStoreFile(KeyStoreFileType.JKS)
- .getAbsolutePath();
- new JKSFileLoader.Builder()
- .setTrustStorePath(path)
- .setTrustStorePassword("wrong password")
- .build()
- .loadTrustStore();
+ String path = x509TestContext.getTrustStoreFile(KeyStoreFileType.JKS).getAbsolutePath();
+ new JKSFileLoader.Builder().setTrustStorePath(path).setTrustStorePassword("wrong password").build().loadTrustStore();
}
@Test(expected = IOException.class)
public void testLoadTrustStoreWithWrongFilePath() throws Exception {
- String path = x509TestContext.getTrustStoreFile(KeyStoreFileType.JKS)
- .getAbsolutePath();
- new JKSFileLoader.Builder()
- .setTrustStorePath(path + ".does_not_exist")
- .setTrustStorePassword(x509TestContext.getTrustStorePassword())
- .build()
- .loadTrustStore();
+ String path = x509TestContext.getTrustStoreFile(KeyStoreFileType.JKS).getAbsolutePath();
+ new JKSFileLoader.Builder().setTrustStorePath(path
+ + ".does_not_exist").setTrustStorePassword(x509TestContext.getTrustStorePassword()).build().loadTrustStore();
}
@Test(expected = NullPointerException.class)
public void testLoadTrustStoreWithNullFilePath() throws Exception {
- new JKSFileLoader.Builder()
- .setTrustStorePassword(x509TestContext.getTrustStorePassword())
- .build()
- .loadTrustStore();
+ new JKSFileLoader.Builder().setTrustStorePassword(x509TestContext.getTrustStorePassword()).build().loadTrustStore();
}
@Test(expected = IOException.class)
public void testLoadTrustStoreWithWrongFileType() throws Exception {
// Trying to load a PEM file with JKS loader should fail
- String path = x509TestContext.getTrustStoreFile(KeyStoreFileType.PEM)
- .getAbsolutePath();
- new JKSFileLoader.Builder()
- .setTrustStorePath(path)
- .setTrustStorePassword(x509TestContext.getTrustStorePassword())
- .build()
- .loadTrustStore();
+ String path = x509TestContext.getTrustStoreFile(KeyStoreFileType.PEM).getAbsolutePath();
+ new JKSFileLoader.Builder().setTrustStorePath(path).setTrustStorePassword(x509TestContext.getTrustStorePassword()).build().loadTrustStore();
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/common/KeyStoreFileTypeTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/common/KeyStoreFileTypeTest.java
index 9265af90b..feeed8103 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/common/KeyStoreFileTypeTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/common/KeyStoreFileTypeTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,34 +18,36 @@
package org.apache.zookeeper.common;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNull;
import org.apache.zookeeper.ZKTestCase;
-import org.junit.Assert;
import org.junit.Test;
public class KeyStoreFileTypeTest extends ZKTestCase {
+
@Test
public void testGetPropertyValue() {
- Assert.assertEquals("PEM", KeyStoreFileType.PEM.getPropertyValue());
- Assert.assertEquals("JKS", KeyStoreFileType.JKS.getPropertyValue());
- Assert.assertEquals("PKCS12", KeyStoreFileType.PKCS12.getPropertyValue());
+ assertEquals("PEM", KeyStoreFileType.PEM.getPropertyValue());
+ assertEquals("JKS", KeyStoreFileType.JKS.getPropertyValue());
+ assertEquals("PKCS12", KeyStoreFileType.PKCS12.getPropertyValue());
}
@Test
public void testFromPropertyValue() {
- Assert.assertEquals(KeyStoreFileType.PEM, KeyStoreFileType.fromPropertyValue("PEM"));
- Assert.assertEquals(KeyStoreFileType.JKS, KeyStoreFileType.fromPropertyValue("JKS"));
- Assert.assertEquals(KeyStoreFileType.PKCS12, KeyStoreFileType.fromPropertyValue("PKCS12"));
- Assert.assertNull(KeyStoreFileType.fromPropertyValue(""));
- Assert.assertNull(KeyStoreFileType.fromPropertyValue(null));
+ assertEquals(KeyStoreFileType.PEM, KeyStoreFileType.fromPropertyValue("PEM"));
+ assertEquals(KeyStoreFileType.JKS, KeyStoreFileType.fromPropertyValue("JKS"));
+ assertEquals(KeyStoreFileType.PKCS12, KeyStoreFileType.fromPropertyValue("PKCS12"));
+ assertNull(KeyStoreFileType.fromPropertyValue(""));
+ assertNull(KeyStoreFileType.fromPropertyValue(null));
}
@Test
public void testFromPropertyValueIgnoresCase() {
- Assert.assertEquals(KeyStoreFileType.PEM, KeyStoreFileType.fromPropertyValue("pem"));
- Assert.assertEquals(KeyStoreFileType.JKS, KeyStoreFileType.fromPropertyValue("jks"));
- Assert.assertEquals(KeyStoreFileType.PKCS12, KeyStoreFileType.fromPropertyValue("pkcs12"));
- Assert.assertNull(KeyStoreFileType.fromPropertyValue(""));
- Assert.assertNull(KeyStoreFileType.fromPropertyValue(null));
+ assertEquals(KeyStoreFileType.PEM, KeyStoreFileType.fromPropertyValue("pem"));
+ assertEquals(KeyStoreFileType.JKS, KeyStoreFileType.fromPropertyValue("jks"));
+ assertEquals(KeyStoreFileType.PKCS12, KeyStoreFileType.fromPropertyValue("pkcs12"));
+ assertNull(KeyStoreFileType.fromPropertyValue(""));
+ assertNull(KeyStoreFileType.fromPropertyValue(null));
}
@Test(expected = IllegalArgumentException.class)
@@ -55,18 +57,12 @@ public class KeyStoreFileTypeTest extends ZKTestCase {
@Test
public void testFromFilename() {
- Assert.assertEquals(KeyStoreFileType.JKS,
- KeyStoreFileType.fromFilename("mykey.jks"));
- Assert.assertEquals(KeyStoreFileType.JKS,
- KeyStoreFileType.fromFilename("/path/to/key/dir/mykey.jks"));
- Assert.assertEquals(KeyStoreFileType.PEM,
- KeyStoreFileType.fromFilename("mykey.pem"));
- Assert.assertEquals(KeyStoreFileType.PEM,
- KeyStoreFileType.fromFilename("/path/to/key/dir/mykey.pem"));
- Assert.assertEquals(KeyStoreFileType.PKCS12,
- KeyStoreFileType.fromFilename("mykey.p12"));
- Assert.assertEquals(KeyStoreFileType.PKCS12,
- KeyStoreFileType.fromFilename("/path/to/key/dir/mykey.p12"));
+ assertEquals(KeyStoreFileType.JKS, KeyStoreFileType.fromFilename("mykey.jks"));
+ assertEquals(KeyStoreFileType.JKS, KeyStoreFileType.fromFilename("/path/to/key/dir/mykey.jks"));
+ assertEquals(KeyStoreFileType.PEM, KeyStoreFileType.fromFilename("mykey.pem"));
+ assertEquals(KeyStoreFileType.PEM, KeyStoreFileType.fromFilename("/path/to/key/dir/mykey.pem"));
+ assertEquals(KeyStoreFileType.PKCS12, KeyStoreFileType.fromFilename("mykey.p12"));
+ assertEquals(KeyStoreFileType.PKCS12, KeyStoreFileType.fromFilename("/path/to/key/dir/mykey.p12"));
}
@Test(expected = IllegalArgumentException.class)
@@ -77,18 +73,11 @@ public class KeyStoreFileTypeTest extends ZKTestCase {
@Test
public void testFromPropertyValueOrFileName() {
// Property value takes precedence if provided
- Assert.assertEquals(KeyStoreFileType.JKS,
- KeyStoreFileType.fromPropertyValueOrFileName(
- "JKS", "prod.key"));
- Assert.assertEquals(KeyStoreFileType.PEM,
- KeyStoreFileType.fromPropertyValueOrFileName(
- "PEM", "prod.key"));
- Assert.assertEquals(KeyStoreFileType.PKCS12,
- KeyStoreFileType.fromPropertyValueOrFileName(
- "PKCS12", "prod.key"));
+ assertEquals(KeyStoreFileType.JKS, KeyStoreFileType.fromPropertyValueOrFileName("JKS", "prod.key"));
+ assertEquals(KeyStoreFileType.PEM, KeyStoreFileType.fromPropertyValueOrFileName("PEM", "prod.key"));
+ assertEquals(KeyStoreFileType.PKCS12, KeyStoreFileType.fromPropertyValueOrFileName("PKCS12", "prod.key"));
// Falls back to filename detection if no property value
- Assert.assertEquals(KeyStoreFileType.JKS,
- KeyStoreFileType.fromPropertyValueOrFileName("", "prod.jks"));
+ assertEquals(KeyStoreFileType.JKS, KeyStoreFileType.fromPropertyValueOrFileName("", "prod.jks"));
}
@Test(expected = IllegalArgumentException.class)
@@ -100,4 +89,5 @@ public class KeyStoreFileTypeTest extends ZKTestCase {
public void testFromPropertyValueOrFileNameThrowsOnBadFileExtension() {
KeyStoreFileType.fromPropertyValueOrFileName("", "prod.key");
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/common/NetUtilsTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/common/NetUtilsTest.java
index 24b3472e4..c61eeba4e 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/common/NetUtilsTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/common/NetUtilsTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,12 +18,13 @@
package org.apache.zookeeper.common;
+import static org.hamcrest.CoreMatchers.anyOf;
+import static org.hamcrest.CoreMatchers.equalTo;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertThat;
+import java.net.InetSocketAddress;
import org.apache.zookeeper.ZKTestCase;
-import org.hamcrest.core.AnyOf;
-import org.hamcrest.core.IsEqual;
-import org.junit.Assert;
import org.junit.Test;
-import java.net.InetSocketAddress;
public class NetUtilsTest extends ZKTestCase {
@@ -38,35 +39,34 @@ public class NetUtilsTest extends ZKTestCase {
@Test
public void testFormatInetAddrGoodIpv4() {
InetSocketAddress isa = new InetSocketAddress(v4addr, port);
- Assert.assertEquals("127.0.0.1:1234", NetUtils.formatInetAddr(isa));
+ assertEquals("127.0.0.1:1234", NetUtils.formatInetAddr(isa));
}
@Test
public void testFormatInetAddrGoodIpv6Local() {
// Have to use the expanded address here, hence not using v6addr in instantiation
InetSocketAddress isa = new InetSocketAddress("::1", port);
- Assert.assertEquals(v6local, NetUtils.formatInetAddr(isa));
+ assertEquals(v6local, NetUtils.formatInetAddr(isa));
}
@Test
public void testFormatInetAddrGoodIpv6Ext() {
// Have to use the expanded address here, hence not using v6addr in instantiation
InetSocketAddress isa = new InetSocketAddress("2600::", port);
- Assert.assertEquals(v6ext, NetUtils.formatInetAddr(isa));
+ assertEquals(v6ext, NetUtils.formatInetAddr(isa));
}
@Test
public void testFormatInetAddrGoodHostname() {
InetSocketAddress isa = new InetSocketAddress("localhost", 1234);
- Assert.assertThat(NetUtils.formatInetAddr(isa),
- AnyOf.anyOf(IsEqual.equalTo(v4local), IsEqual.equalTo(v6local)
- ));
+ assertThat(NetUtils.formatInetAddr(isa), anyOf(equalTo(v4local), equalTo(v6local)));
}
@Test
public void testFormatAddrUnresolved() {
InetSocketAddress isa = InetSocketAddress.createUnresolved("doesnt.exist.com", 1234);
- Assert.assertEquals("doesnt.exist.com:1234", NetUtils.formatInetAddr(isa));
+ assertEquals("doesnt.exist.com:1234", NetUtils.formatInetAddr(isa));
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/common/PEMFileLoaderTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/common/PEMFileLoaderTest.java
index e78c750bf..05ef12e76 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/common/PEMFileLoaderTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/common/PEMFileLoaderTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,12 +18,11 @@
package org.apache.zookeeper.common;
+import static org.junit.Assert.assertEquals;
import java.io.IOException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.util.Collection;
-
-import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
@@ -37,19 +36,19 @@ public class PEMFileLoaderTest extends BaseX509ParameterizedTestCase {
}
public PEMFileLoaderTest(
- final X509KeyType caKeyType,
- final X509KeyType certKeyType,
- final String keyPassword,
- final Integer paramIndex) {
+ final X509KeyType caKeyType,
+ final X509KeyType certKeyType,
+ final String keyPassword,
+ final Integer paramIndex) {
super(paramIndex, () -> {
try {
return X509TestContext.newBuilder()
- .setTempDir(tempDir)
- .setKeyStorePassword(keyPassword)
- .setKeyStoreKeyType(certKeyType)
- .setTrustStorePassword(keyPassword)
- .setTrustStoreKeyType(caKeyType)
- .build();
+ .setTempDir(tempDir)
+ .setKeyStorePassword(keyPassword)
+ .setKeyStoreKeyType(certKeyType)
+ .setTrustStorePassword(keyPassword)
+ .setTrustStoreKeyType(caKeyType)
+ .build();
} catch (Exception e) {
throw new RuntimeException(e);
}
@@ -58,99 +57,93 @@ public class PEMFileLoaderTest extends BaseX509ParameterizedTestCase {
@Test
public void testLoadKeyStore() throws Exception {
- String path = x509TestContext.getKeyStoreFile(KeyStoreFileType.PEM)
- .getAbsolutePath();
+ String path = x509TestContext.getKeyStoreFile(KeyStoreFileType.PEM).getAbsolutePath();
KeyStore ks = new PEMFileLoader.Builder()
- .setKeyStorePath(path)
- .setKeyStorePassword(x509TestContext.getKeyStorePassword())
- .build()
- .loadKeyStore();
- Assert.assertEquals(1, ks.size());
+ .setKeyStorePath(path)
+ .setKeyStorePassword(x509TestContext.getKeyStorePassword())
+ .build()
+ .loadKeyStore();
+ assertEquals(1, ks.size());
}
@Test(expected = Exception.class)
public void testLoadKeyStoreWithWrongPassword() throws Exception {
- String path = x509TestContext.getKeyStoreFile(KeyStoreFileType.PEM)
- .getAbsolutePath();
+ String path = x509TestContext.getKeyStoreFile(KeyStoreFileType.PEM).getAbsolutePath();
new PEMFileLoader.Builder()
- .setKeyStorePath(path)
- .setKeyStorePassword("wrong password")
- .build()
- .loadKeyStore();
+ .setKeyStorePath(path)
+ .setKeyStorePassword("wrong password")
+ .build()
+ .loadKeyStore();
}
@Test(expected = IOException.class)
public void testLoadKeyStoreWithWrongFilePath() throws Exception {
- String path = x509TestContext.getKeyStoreFile(KeyStoreFileType.PEM)
- .getAbsolutePath();
+ String path = x509TestContext.getKeyStoreFile(KeyStoreFileType.PEM).getAbsolutePath();
new PEMFileLoader.Builder()
- .setKeyStorePath(path + ".does_not_exist")
- .setKeyStorePassword(x509TestContext.getKeyStorePassword())
- .build()
- .loadKeyStore();
+ .setKeyStorePath(path + ".does_not_exist")
+ .setKeyStorePassword(x509TestContext.getKeyStorePassword())
+ .build()
+ .loadKeyStore();
}
@Test(expected = NullPointerException.class)
public void testLoadKeyStoreWithNullFilePath() throws Exception {
new PEMFileLoader.Builder()
- .setKeyStorePassword(x509TestContext.getKeyStorePassword())
- .build()
- .loadKeyStore();
+ .setKeyStorePassword(x509TestContext.getKeyStorePassword())
+ .build()
+ .loadKeyStore();
}
@Test(expected = KeyStoreException.class)
public void testLoadKeyStoreWithWrongFileType() throws Exception {
// Trying to load a JKS file with PEM loader should fail
- String path = x509TestContext.getKeyStoreFile(KeyStoreFileType.JKS)
- .getAbsolutePath();
+ String path = x509TestContext.getKeyStoreFile(KeyStoreFileType.JKS).getAbsolutePath();
new PEMFileLoader.Builder()
- .setKeyStorePath(path)
- .setKeyStorePassword(x509TestContext.getKeyStorePassword())
- .build()
- .loadKeyStore();
+ .setKeyStorePath(path)
+ .setKeyStorePassword(x509TestContext.getKeyStorePassword())
+ .build()
+ .loadKeyStore();
}
@Test
public void testLoadTrustStore() throws Exception {
- String path = x509TestContext.getTrustStoreFile(KeyStoreFileType.PEM)
- .getAbsolutePath();
+ String path = x509TestContext.getTrustStoreFile(KeyStoreFileType.PEM).getAbsolutePath();
KeyStore ts = new PEMFileLoader.Builder()
- .setTrustStorePath(path)
- .setTrustStorePassword(x509TestContext.getTrustStorePassword())
- .build()
- .loadTrustStore();
- Assert.assertEquals(1, ts.size());
+ .setTrustStorePath(path)
+ .setTrustStorePassword(x509TestContext.getTrustStorePassword())
+ .build()
+ .loadTrustStore();
+ assertEquals(1, ts.size());
}
@Test(expected = IOException.class)
public void testLoadTrustStoreWithWrongFilePath() throws Exception {
- String path = x509TestContext.getTrustStoreFile(KeyStoreFileType.PEM)
- .getAbsolutePath();
+ String path = x509TestContext.getTrustStoreFile(KeyStoreFileType.PEM).getAbsolutePath();
new PEMFileLoader.Builder()
- .setTrustStorePath(path + ".does_not_exist")
- .setTrustStorePassword(x509TestContext.getTrustStorePassword())
- .build()
- .loadTrustStore();
+ .setTrustStorePath(path + ".does_not_exist")
+ .setTrustStorePassword(x509TestContext.getTrustStorePassword())
+ .build()
+ .loadTrustStore();
}
@Test(expected = NullPointerException.class)
public void testLoadTrustStoreWithNullFilePath() throws Exception {
new PEMFileLoader.Builder()
- .setTrustStorePassword(x509TestContext.getTrustStorePassword())
- .build()
- .loadTrustStore();
+ .setTrustStorePassword(x509TestContext.getTrustStorePassword())
+ .build()
+ .loadTrustStore();
}
@Test
public void testLoadTrustStoreWithWrongFileType() throws Exception {
// Trying to load a JKS file with PEM loader should fail
- String path = x509TestContext.getTrustStoreFile(KeyStoreFileType.JKS)
- .getAbsolutePath();
+ String path = x509TestContext.getTrustStoreFile(KeyStoreFileType.JKS).getAbsolutePath();
KeyStore ts = new PEMFileLoader.Builder()
- .setTrustStorePath(path)
- .setTrustStorePassword(x509TestContext.getTrustStorePassword())
- .build()
- .loadTrustStore();
- Assert.assertEquals(0, ts.size());
+ .setTrustStorePath(path)
+ .setTrustStorePassword(x509TestContext.getTrustStorePassword())
+ .build()
+ .loadTrustStore();
+ assertEquals(0, ts.size());
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/common/PKCS12FileLoaderTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/common/PKCS12FileLoaderTest.java
index f2b6efa35..63d668315 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/common/PKCS12FileLoaderTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/common/PKCS12FileLoaderTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,11 +18,10 @@
package org.apache.zookeeper.common;
+import static org.junit.Assert.assertEquals;
import java.io.IOException;
import java.security.KeyStore;
import java.util.Collection;
-
-import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
@@ -43,12 +42,12 @@ public class PKCS12FileLoaderTest extends BaseX509ParameterizedTestCase {
super(paramIndex, () -> {
try {
return X509TestContext.newBuilder()
- .setTempDir(tempDir)
- .setKeyStorePassword(keyPassword)
- .setKeyStoreKeyType(certKeyType)
- .setTrustStorePassword(keyPassword)
- .setTrustStoreKeyType(caKeyType)
- .build();
+ .setTempDir(tempDir)
+ .setKeyStorePassword(keyPassword)
+ .setKeyStoreKeyType(certKeyType)
+ .setTrustStorePassword(keyPassword)
+ .setTrustStoreKeyType(caKeyType)
+ .build();
} catch (Exception e) {
throw new RuntimeException(e);
}
@@ -57,20 +56,18 @@ public class PKCS12FileLoaderTest extends BaseX509ParameterizedTestCase {
@Test
public void testLoadKeyStore() throws Exception {
- String path = x509TestContext.getKeyStoreFile(KeyStoreFileType.PKCS12)
- .getAbsolutePath();
+ String path = x509TestContext.getKeyStoreFile(KeyStoreFileType.PKCS12).getAbsolutePath();
KeyStore ks = new PKCS12FileLoader.Builder()
.setKeyStorePath(path)
.setKeyStorePassword(x509TestContext.getKeyStorePassword())
.build()
.loadKeyStore();
- Assert.assertEquals(1, ks.size());
+ assertEquals(1, ks.size());
}
@Test(expected = Exception.class)
public void testLoadKeyStoreWithWrongPassword() throws Exception {
- String path = x509TestContext.getKeyStoreFile(KeyStoreFileType.PKCS12)
- .getAbsolutePath();
+ String path = x509TestContext.getKeyStoreFile(KeyStoreFileType.PKCS12).getAbsolutePath();
new PKCS12FileLoader.Builder()
.setKeyStorePath(path)
.setKeyStorePassword("wrong password")
@@ -80,8 +77,7 @@ public class PKCS12FileLoaderTest extends BaseX509ParameterizedTestCase {
@Test(expected = IOException.class)
public void testLoadKeyStoreWithWrongFilePath() throws Exception {
- String path = x509TestContext.getKeyStoreFile(KeyStoreFileType.PKCS12)
- .getAbsolutePath();
+ String path = x509TestContext.getKeyStoreFile(KeyStoreFileType.PKCS12).getAbsolutePath();
new PKCS12FileLoader.Builder()
.setKeyStorePath(path + ".does_not_exist")
.setKeyStorePassword(x509TestContext.getKeyStorePassword())
@@ -100,8 +96,7 @@ public class PKCS12FileLoaderTest extends BaseX509ParameterizedTestCase {
@Test(expected = IOException.class)
public void testLoadKeyStoreWithWrongFileType() throws Exception {
// Trying to load a PEM file with PKCS12 loader should fail
- String path = x509TestContext.getKeyStoreFile(KeyStoreFileType.PEM)
- .getAbsolutePath();
+ String path = x509TestContext.getKeyStoreFile(KeyStoreFileType.PEM).getAbsolutePath();
new PKCS12FileLoader.Builder()
.setKeyStorePath(path)
.setKeyStorePassword(x509TestContext.getKeyStorePassword())
@@ -111,20 +106,18 @@ public class PKCS12FileLoaderTest extends BaseX509ParameterizedTestCase {
@Test
public void testLoadTrustStore() throws Exception {
- String path = x509TestContext.getTrustStoreFile(KeyStoreFileType.PKCS12)
- .getAbsolutePath();
+ String path = x509TestContext.getTrustStoreFile(KeyStoreFileType.PKCS12).getAbsolutePath();
KeyStore ts = new PKCS12FileLoader.Builder()
.setTrustStorePath(path)
.setTrustStorePassword(x509TestContext.getTrustStorePassword())
.build()
.loadTrustStore();
- Assert.assertEquals(1, ts.size());
+ assertEquals(1, ts.size());
}
@Test(expected = Exception.class)
public void testLoadTrustStoreWithWrongPassword() throws Exception {
- String path = x509TestContext.getTrustStoreFile(KeyStoreFileType.PKCS12)
- .getAbsolutePath();
+ String path = x509TestContext.getTrustStoreFile(KeyStoreFileType.PKCS12).getAbsolutePath();
new PKCS12FileLoader.Builder()
.setTrustStorePath(path)
.setTrustStorePassword("wrong password")
@@ -134,8 +127,7 @@ public class PKCS12FileLoaderTest extends BaseX509ParameterizedTestCase {
@Test(expected = IOException.class)
public void testLoadTrustStoreWithWrongFilePath() throws Exception {
- String path = x509TestContext.getTrustStoreFile(KeyStoreFileType.PKCS12)
- .getAbsolutePath();
+ String path = x509TestContext.getTrustStoreFile(KeyStoreFileType.PKCS12).getAbsolutePath();
new PKCS12FileLoader.Builder()
.setTrustStorePath(path + ".does_not_exist")
.setTrustStorePassword(x509TestContext.getTrustStorePassword())
@@ -154,12 +146,12 @@ public class PKCS12FileLoaderTest extends BaseX509ParameterizedTestCase {
@Test(expected = IOException.class)
public void testLoadTrustStoreWithWrongFileType() throws Exception {
// Trying to load a PEM file with PKCS12 loader should fail
- String path = x509TestContext.getTrustStoreFile(KeyStoreFileType.PEM)
- .getAbsolutePath();
+ String path = x509TestContext.getTrustStoreFile(KeyStoreFileType.PEM).getAbsolutePath();
new PKCS12FileLoader.Builder()
.setTrustStorePath(path)
.setTrustStorePassword(x509TestContext.getTrustStorePassword())
.build()
.loadTrustStore();
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/common/PathTrieTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/common/PathTrieTest.java
index eeaaeb75d..c7661647d 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/common/PathTrieTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/common/PathTrieTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,7 +18,9 @@
package org.apache.zookeeper.common;
-import org.junit.Assert;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
import org.junit.Before;
import org.junit.Test;
@@ -44,7 +46,7 @@ public class PathTrieTest {
@Test
public void addPathToRoot() {
this.pathTrie.addPath("node1");
- Assert.assertTrue(this.pathTrie.existsNode("/node1"));
+ assertTrue(this.pathTrie.existsNode("/node1"));
}
@Test
@@ -52,9 +54,9 @@ public class PathTrieTest {
this.pathTrie.addPath("node1");
this.pathTrie.addPath("node1/node2");
this.pathTrie.addPath("node1/node3");
- Assert.assertTrue(this.pathTrie.existsNode("/node1"));
- Assert.assertTrue(this.pathTrie.existsNode("/node1/node2"));
- Assert.assertTrue(this.pathTrie.existsNode("/node1/node3"));
+ assertTrue(this.pathTrie.existsNode("/node1"));
+ assertTrue(this.pathTrie.existsNode("/node1/node2"));
+ assertTrue(this.pathTrie.existsNode("/node1/node3"));
}
@Test(expected = NullPointerException.class)
@@ -71,28 +73,28 @@ public class PathTrieTest {
public void deletePathFromRoot() {
this.pathTrie.addPath("node1");
this.pathTrie.deletePath("node1");
- Assert.assertFalse(this.pathTrie.existsNode("/node1"));
+ assertFalse(this.pathTrie.existsNode("/node1"));
}
@Test
public void deletePathFromRootLeaves() {
- this.pathTrie.addPath("node1");
- this.pathTrie.addPath("node1/node2");
- this.pathTrie.addPath("node1/node3");
+ this.pathTrie.addPath("node1");
+ this.pathTrie.addPath("node1/node2");
+ this.pathTrie.addPath("node1/node3");
- this.pathTrie.deletePath("node1/node3");
+ this.pathTrie.deletePath("node1/node3");
- Assert.assertTrue(this.pathTrie.existsNode("/node1"));
- Assert.assertTrue(this.pathTrie.existsNode("/node1/node2"));
- Assert.assertFalse(this.pathTrie.existsNode("/node1/node3"));
+ assertTrue(this.pathTrie.existsNode("/node1"));
+ assertTrue(this.pathTrie.existsNode("/node1/node2"));
+ assertFalse(this.pathTrie.existsNode("/node1/node3"));
- this.pathTrie.deletePath("node1/node2");
+ this.pathTrie.deletePath("node1/node2");
- Assert.assertTrue(this.pathTrie.existsNode("/node1"));
- Assert.assertFalse(this.pathTrie.existsNode("/node1/node2"));
+ assertTrue(this.pathTrie.existsNode("/node1"));
+ assertFalse(this.pathTrie.existsNode("/node1/node2"));
- this.pathTrie.deletePath("node1");
- Assert.assertFalse(this.pathTrie.existsNode("/node1"));
+ this.pathTrie.deletePath("node1");
+ assertFalse(this.pathTrie.existsNode("/node1"));
}
@Test
@@ -102,8 +104,8 @@ public class PathTrieTest {
this.pathTrie.deletePath("node1/node3");
- Assert.assertTrue(this.pathTrie.existsNode("/node1"));
- Assert.assertTrue(this.pathTrie.existsNode("/node1/node2"));
+ assertTrue(this.pathTrie.existsNode("/node1"));
+ assertTrue(this.pathTrie.existsNode("/node1/node2"));
}
@Test
@@ -115,9 +117,9 @@ public class PathTrieTest {
// Nodes are only removed from the trie if they are a leaf node
this.pathTrie.deletePath("node1");
- Assert.assertTrue(this.pathTrie.existsNode("/node1"));
- Assert.assertTrue(this.pathTrie.existsNode("/node1/node2"));
- Assert.assertTrue(this.pathTrie.existsNode("/node1/node3"));
+ assertTrue(this.pathTrie.existsNode("/node1"));
+ assertTrue(this.pathTrie.existsNode("/node1/node2"));
+ assertTrue(this.pathTrie.existsNode("/node1/node3"));
}
@Test(expected = NullPointerException.class)
@@ -127,7 +129,7 @@ public class PathTrieTest {
@Test
public void findMaxPrefixRootPath() {
- Assert.assertEquals("/", this.pathTrie.findMaxPrefix("/"));
+ assertEquals("/", this.pathTrie.findMaxPrefix("/"));
}
@Test
@@ -136,17 +138,17 @@ public class PathTrieTest {
this.pathTrie.addPath("node1/node2");
this.pathTrie.addPath("node1/node3");
- Assert.assertEquals("/node1", this.pathTrie.findMaxPrefix("/node1"));
- Assert.assertEquals("/node1/node2", this.pathTrie.findMaxPrefix("/node1/node2"));
- Assert.assertEquals("/node1/node3", this.pathTrie.findMaxPrefix("/node1/node3"));
+ assertEquals("/node1", this.pathTrie.findMaxPrefix("/node1"));
+ assertEquals("/node1/node2", this.pathTrie.findMaxPrefix("/node1/node2"));
+ assertEquals("/node1/node3", this.pathTrie.findMaxPrefix("/node1/node3"));
}
@Test
public void findMaxPrefixChildrenPrefix() {
this.pathTrie.addPath("node1");
- Assert.assertEquals("/node1", this.pathTrie.findMaxPrefix("/node1/node2"));
- Assert.assertEquals("/node1", this.pathTrie.findMaxPrefix("/node1/node3"));
+ assertEquals("/node1", this.pathTrie.findMaxPrefix("/node1/node2"));
+ assertEquals("/node1", this.pathTrie.findMaxPrefix("/node1/node3"));
}
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/common/PathUtilsTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/common/PathUtilsTest.java
index 580445683..0d0828664 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/common/PathUtilsTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/common/PathUtilsTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -28,100 +28,99 @@ public class PathUtilsTest extends ZKTestCase {
PathUtils.validatePath("/this is / a valid/path");
}
- @Test(expected=IllegalArgumentException.class)
+ @Test(expected = IllegalArgumentException.class)
public void testValidatePath_Null() {
PathUtils.validatePath(null);
}
-
- @Test(expected=IllegalArgumentException.class)
+ @Test(expected = IllegalArgumentException.class)
public void testValidatePath_EmptyString() {
PathUtils.validatePath("");
}
- @Test(expected=IllegalArgumentException.class)
+ @Test(expected = IllegalArgumentException.class)
public void testValidatePath_NotAbsolutePath() {
PathUtils.validatePath("not/valid");
}
- @Test(expected=IllegalArgumentException.class)
+ @Test(expected = IllegalArgumentException.class)
public void testValidatePath_EndsWithSlash() {
PathUtils.validatePath("/ends/with/slash/");
}
-
- @Test(expected=IllegalArgumentException.class)
+
+ @Test(expected = IllegalArgumentException.class)
public void testValidatePath_ContainsNullCharacter() {
PathUtils.validatePath("/test\u0000");
}
-
- @Test(expected=IllegalArgumentException.class)
+
+ @Test(expected = IllegalArgumentException.class)
public void testValidatePath_DoubleSlash() {
PathUtils.validatePath("/double//slash");
}
-
- @Test(expected=IllegalArgumentException.class)
+
+ @Test(expected = IllegalArgumentException.class)
public void testValidatePath_SinglePeriod() {
PathUtils.validatePath("/single/./period");
}
-
- @Test(expected=IllegalArgumentException.class)
+
+ @Test(expected = IllegalArgumentException.class)
public void testValidatePath_DoublePeriod() {
PathUtils.validatePath("/double/../period");
}
-
+
@Test
public void testValidatePath_NameContainingPeriod() {
// A period that isn't on its own is ok
PathUtils.validatePath("/name/with.period.");
}
-
- @Test(expected=IllegalArgumentException.class)
+
+ @Test(expected = IllegalArgumentException.class)
public void testValidatePath_0x01() {
PathUtils.validatePath("/test\u0001");
}
-
- @Test(expected=IllegalArgumentException.class)
+
+ @Test(expected = IllegalArgumentException.class)
public void testValidatePath_0x1F() {
PathUtils.validatePath("/test\u001F");
}
-
+
@Test // The first allowable character
public void testValidatePath_0x20() {
PathUtils.validatePath("/test\u0020");
}
-
- @Test
+
+ @Test
public void testValidatePath_0x7e() {
// The last valid ASCII character
PathUtils.validatePath("/test\u007e");
}
-
- @Test(expected=IllegalArgumentException.class)
+
+ @Test(expected = IllegalArgumentException.class)
public void testValidatePath_0x7f() {
PathUtils.validatePath("/test\u007f");
}
-
- @Test(expected=IllegalArgumentException.class)
+
+ @Test(expected = IllegalArgumentException.class)
public void testValidatePath_0x9f() {
PathUtils.validatePath("/test\u009f");
}
-
- @Test(expected=IllegalArgumentException.class)
+
+ @Test(expected = IllegalArgumentException.class)
public void testValidatePath_ud800() {
PathUtils.validatePath("/test\ud800");
}
- @Test(expected=IllegalArgumentException.class)
+ @Test(expected = IllegalArgumentException.class)
public void testValidatePath_uf8ff() {
PathUtils.validatePath("/test\uf8ff");
}
-
+
@Test
public void testValidatePath_HighestAllowableChar() {
PathUtils.validatePath("/test\uffef");
}
-
- @Test(expected=IllegalArgumentException.class)
+
+ @Test(expected = IllegalArgumentException.class)
public void testValidatePath_SupplementaryChar() {
PathUtils.validatePath("/test\ufff0");
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/common/TimeTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/common/TimeTest.java
index c3d03399f..566f3f5df 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/common/TimeTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/common/TimeTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,19 +18,18 @@
package org.apache.zookeeper.common;
+import static org.junit.Assert.assertEquals;
+import java.util.Calendar;
+import java.util.Date;
+import java.util.concurrent.atomic.AtomicInteger;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.test.ClientBase;
-import org.junit.Assert;
import org.junit.Test;
-import java.util.Calendar;
-import java.util.Date;
-import java.util.concurrent.atomic.AtomicInteger;
-
/**
* Command line program for demonstrating robustness to clock
* changes.
@@ -47,24 +46,23 @@ import java.util.concurrent.atomic.AtomicInteger;
* As long as there isn't any expired event, the experiment is successful.
*/
public class TimeTest extends ClientBase {
+
private static final long mt0 = System.currentTimeMillis();
private static final long nt0 = Time.currentElapsedTime();
private static AtomicInteger watchCount = new AtomicInteger(0);
-
public static void main(String[] args) throws Exception {
- System.out.printf("Starting\n");
+ System.out.print("Starting\n");
final TimeTest test = new TimeTest();
- System.out.printf("After construct\n");
+ System.out.print("After construct\n");
test.setUp();
ZooKeeper zk = test.createClient();
- zk.create("/ephemeral", new byte[]{1, 2, 3},
- ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
+ zk.create("/ephemeral", new byte[]{1, 2, 3}, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
while (Time.currentElapsedTime() - nt0 < 100000) {
- System.out.printf("%d\t%s\n", discrepancy(),
- zk.exists("/ephemeral",
- watchCount.get() == 0 ? createWatcher() : null) != null);
+ System.out.printf("%d\t%s\n",
+ discrepancy(),
+ zk.exists("/ephemeral", watchCount.get() == 0 ? createWatcher() : null) != null);
waitByYielding(500);
}
}
@@ -104,6 +102,7 @@ public class TimeTest extends ClientBase {
cal.setTime(new Date(walltime));
int realDate = cal.get(Calendar.HOUR_OF_DAY);
- Assert.assertEquals(calculatedDate, realDate);
+ assertEquals(calculatedDate, realDate);
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/common/X509KeyType.java b/zookeeper-server/src/test/java/org/apache/zookeeper/common/X509KeyType.java
index e2cdc81a4..9c97e9663 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/common/X509KeyType.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/common/X509KeyType.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -22,5 +22,6 @@ package org.apache.zookeeper.common;
* Represents a type of key pair used for X509 certs in tests. The two options are RSA or EC (elliptic curve).
*/
public enum X509KeyType {
- RSA, EC;
+ RSA,
+ EC
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/common/X509TestContext.java b/zookeeper-server/src/test/java/org/apache/zookeeper/common/X509TestContext.java
index 3a899f44c..71fde1e6c 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/common/X509TestContext.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/common/X509TestContext.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,6 +18,7 @@
package org.apache.zookeeper.common;
+import static java.util.Objects.requireNonNull;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
@@ -28,19 +29,17 @@ import java.security.KeyPair;
import java.security.Security;
import java.security.cert.X509Certificate;
import java.util.Arrays;
-
import org.apache.commons.io.FileUtils;
import org.bouncycastle.asn1.x500.X500NameBuilder;
import org.bouncycastle.asn1.x500.style.BCStyle;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.operator.OperatorCreationException;
-import static java.util.Objects.requireNonNull;
-
/**
* This class simplifies the creation of certificates and private keys for SSL/TLS connections.
*/
public class X509TestContext {
+
private static final String TRUST_STORE_PREFIX = "zk_test_ca";
private static final String KEY_STORE_PREFIX = "zk_test_key";
@@ -79,14 +78,7 @@ public class X509TestContext {
* @throws GeneralSecurityException
* @throws OperatorCreationException
*/
- private X509TestContext(File tempDir,
- KeyPair trustStoreKeyPair,
- long trustStoreCertExpirationMillis,
- String trustStorePassword,
- KeyPair keyStoreKeyPair,
- long keyStoreCertExpirationMillis,
- String keyStorePassword,
- Boolean hostnameVerification) throws IOException, GeneralSecurityException, OperatorCreationException {
+ private X509TestContext(File tempDir, KeyPair trustStoreKeyPair, long trustStoreCertExpirationMillis, String trustStorePassword, KeyPair keyStoreKeyPair, long keyStoreCertExpirationMillis, String keyStorePassword, Boolean hostnameVerification) throws IOException, GeneralSecurityException, OperatorCreationException {
if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) {
throw new IllegalStateException("BC Security provider was not found");
}
@@ -105,19 +97,11 @@ public class X509TestContext {
X500NameBuilder caNameBuilder = new X500NameBuilder(BCStyle.INSTANCE);
caNameBuilder.addRDN(BCStyle.CN, MethodHandles.lookup().lookupClass().getCanonicalName() + " Root CA");
- trustStoreCertificate = X509TestHelpers.newSelfSignedCACert(
- caNameBuilder.build(),
- trustStoreKeyPair,
- trustStoreCertExpirationMillis);
+ trustStoreCertificate = X509TestHelpers.newSelfSignedCACert(caNameBuilder.build(), trustStoreKeyPair, trustStoreCertExpirationMillis);
X500NameBuilder nameBuilder = new X500NameBuilder(BCStyle.INSTANCE);
nameBuilder.addRDN(BCStyle.CN, MethodHandles.lookup().lookupClass().getCanonicalName() + " Zookeeper Test");
- keyStoreCertificate = X509TestHelpers.newCert(
- trustStoreCertificate,
- trustStoreKeyPair,
- nameBuilder.build(),
- keyStoreKeyPair.getPublic(),
- keyStoreCertExpirationMillis);
+ keyStoreCertificate = X509TestHelpers.newCert(trustStoreCertificate, trustStoreKeyPair, nameBuilder.build(), keyStoreKeyPair.getPublic(), keyStoreCertExpirationMillis);
trustStorePkcs12File = trustStorePemFile = trustStoreJksFile = null;
keyStorePkcs12File = keyStorePemFile = keyStoreJksFile = null;
@@ -170,22 +154,23 @@ public class X509TestContext {
*/
public File getTrustStoreFile(KeyStoreFileType storeFileType) throws IOException {
switch (storeFileType) {
- case JKS:
- return getTrustStoreJksFile();
- case PEM:
- return getTrustStorePemFile();
- case PKCS12:
- return getTrustStorePkcs12File();
- default:
- throw new IllegalArgumentException("Invalid trust store type: " + storeFileType + ", must be one of: " +
- Arrays.toString(KeyStoreFileType.values()));
+ case JKS:
+ return getTrustStoreJksFile();
+ case PEM:
+ return getTrustStorePemFile();
+ case PKCS12:
+ return getTrustStorePkcs12File();
+ default:
+ throw new IllegalArgumentException("Invalid trust store type: "
+ + storeFileType
+ + ", must be one of: "
+ + Arrays.toString(KeyStoreFileType.values()));
}
}
private File getTrustStoreJksFile() throws IOException {
if (trustStoreJksFile == null) {
- File trustStoreJksFile = File.createTempFile(
- TRUST_STORE_PREFIX, KeyStoreFileType.JKS.getDefaultFileExtension(), tempDir);
+ File trustStoreJksFile = File.createTempFile(TRUST_STORE_PREFIX, KeyStoreFileType.JKS.getDefaultFileExtension(), tempDir);
trustStoreJksFile.deleteOnExit();
try (final FileOutputStream trustStoreOutputStream = new FileOutputStream(trustStoreJksFile)) {
byte[] bytes = X509TestHelpers.certToJavaTrustStoreBytes(trustStoreCertificate, trustStorePassword);
@@ -201,14 +186,9 @@ public class X509TestContext {
private File getTrustStorePemFile() throws IOException {
if (trustStorePemFile == null) {
- File trustStorePemFile = File.createTempFile(
- TRUST_STORE_PREFIX, KeyStoreFileType.PEM.getDefaultFileExtension(), tempDir);
+ File trustStorePemFile = File.createTempFile(TRUST_STORE_PREFIX, KeyStoreFileType.PEM.getDefaultFileExtension(), tempDir);
trustStorePemFile.deleteOnExit();
- FileUtils.writeStringToFile(
- trustStorePemFile,
- X509TestHelpers.pemEncodeX509Certificate(trustStoreCertificate),
- StandardCharsets.US_ASCII,
- false);
+ FileUtils.writeStringToFile(trustStorePemFile, X509TestHelpers.pemEncodeX509Certificate(trustStoreCertificate), StandardCharsets.US_ASCII, false);
this.trustStorePemFile = trustStorePemFile;
}
return trustStorePemFile;
@@ -216,8 +196,7 @@ public class X509TestContext {
private File getTrustStorePkcs12File() throws IOException {
if (trustStorePkcs12File == null) {
- File trustStorePkcs12File = File.createTempFile(
- TRUST_STORE_PREFIX, KeyStoreFileType.PKCS12.getDefaultFileExtension(), tempDir);
+ File trustStorePkcs12File = File.createTempFile(TRUST_STORE_PREFIX, KeyStoreFileType.PKCS12.getDefaultFileExtension(), tempDir);
trustStorePkcs12File.deleteOnExit();
try (final FileOutputStream trustStoreOutputStream = new FileOutputStream(trustStorePkcs12File)) {
byte[] bytes = X509TestHelpers.certToPKCS12TrustStoreBytes(trustStoreCertificate, trustStorePassword);
@@ -264,26 +243,26 @@ public class X509TestContext {
*/
public File getKeyStoreFile(KeyStoreFileType storeFileType) throws IOException {
switch (storeFileType) {
- case JKS:
- return getKeyStoreJksFile();
- case PEM:
- return getKeyStorePemFile();
- case PKCS12:
- return getKeyStorePkcs12File();
- default:
- throw new IllegalArgumentException("Invalid key store type: " + storeFileType + ", must be one of: " +
- Arrays.toString(KeyStoreFileType.values()));
+ case JKS:
+ return getKeyStoreJksFile();
+ case PEM:
+ return getKeyStorePemFile();
+ case PKCS12:
+ return getKeyStorePkcs12File();
+ default:
+ throw new IllegalArgumentException("Invalid key store type: "
+ + storeFileType
+ + ", must be one of: "
+ + Arrays.toString(KeyStoreFileType.values()));
}
}
private File getKeyStoreJksFile() throws IOException {
if (keyStoreJksFile == null) {
- File keyStoreJksFile = File.createTempFile(
- KEY_STORE_PREFIX, KeyStoreFileType.JKS.getDefaultFileExtension(), tempDir);
+ File keyStoreJksFile = File.createTempFile(KEY_STORE_PREFIX, KeyStoreFileType.JKS.getDefaultFileExtension(), tempDir);
keyStoreJksFile.deleteOnExit();
try (final FileOutputStream keyStoreOutputStream = new FileOutputStream(keyStoreJksFile)) {
- byte[] bytes = X509TestHelpers.certAndPrivateKeyToJavaKeyStoreBytes(
- keyStoreCertificate, keyStoreKeyPair.getPrivate(), keyStorePassword);
+ byte[] bytes = X509TestHelpers.certAndPrivateKeyToJavaKeyStoreBytes(keyStoreCertificate, keyStoreKeyPair.getPrivate(), keyStorePassword);
keyStoreOutputStream.write(bytes);
keyStoreOutputStream.flush();
} catch (GeneralSecurityException e) {
@@ -297,15 +276,9 @@ public class X509TestContext {
private File getKeyStorePemFile() throws IOException {
if (keyStorePemFile == null) {
try {
- File keyStorePemFile = File.createTempFile(
- KEY_STORE_PREFIX, KeyStoreFileType.PEM.getDefaultFileExtension(), tempDir);
+ File keyStorePemFile = File.createTempFile(KEY_STORE_PREFIX, KeyStoreFileType.PEM.getDefaultFileExtension(), tempDir);
keyStorePemFile.deleteOnExit();
- FileUtils.writeStringToFile(
- keyStorePemFile,
- X509TestHelpers.pemEncodeCertAndPrivateKey(
- keyStoreCertificate, keyStoreKeyPair.getPrivate(), keyStorePassword),
- StandardCharsets.US_ASCII,
- false);
+ FileUtils.writeStringToFile(keyStorePemFile, X509TestHelpers.pemEncodeCertAndPrivateKey(keyStoreCertificate, keyStoreKeyPair.getPrivate(), keyStorePassword), StandardCharsets.US_ASCII, false);
this.keyStorePemFile = keyStorePemFile;
} catch (OperatorCreationException e) {
throw new IOException(e);
@@ -316,12 +289,10 @@ public class X509TestContext {
private File getKeyStorePkcs12File() throws IOException {
if (keyStorePkcs12File == null) {
- File keyStorePkcs12File = File.createTempFile(
- KEY_STORE_PREFIX, KeyStoreFileType.PKCS12.getDefaultFileExtension(), tempDir);
+ File keyStorePkcs12File = File.createTempFile(KEY_STORE_PREFIX, KeyStoreFileType.PKCS12.getDefaultFileExtension(), tempDir);
keyStorePkcs12File.deleteOnExit();
try (final FileOutputStream keyStoreOutputStream = new FileOutputStream(keyStorePkcs12File)) {
- byte[] bytes = X509TestHelpers.certAndPrivateKeyToPKCS12Bytes(
- keyStoreCertificate, keyStoreKeyPair.getPrivate(), keyStorePassword);
+ byte[] bytes = X509TestHelpers.certAndPrivateKeyToPKCS12Bytes(keyStoreCertificate, keyStoreKeyPair.getPrivate(), keyStorePassword);
keyStoreOutputStream.write(bytes);
keyStoreOutputStream.flush();
} catch (GeneralSecurityException e) {
@@ -347,17 +318,11 @@ public class X509TestContext {
* @param trustStoreFileType the store file type to use for the trust store (JKS or PEM).
* @throws IOException if there is an error creating the key store file or trust store file.
*/
- public void setSystemProperties(X509Util x509Util,
- KeyStoreFileType keyStoreFileType,
- KeyStoreFileType trustStoreFileType) throws IOException {
- System.setProperty(
- x509Util.getSslKeystoreLocationProperty(),
- this.getKeyStoreFile(keyStoreFileType).getAbsolutePath());
+ public void setSystemProperties(X509Util x509Util, KeyStoreFileType keyStoreFileType, KeyStoreFileType trustStoreFileType) throws IOException {
+ System.setProperty(x509Util.getSslKeystoreLocationProperty(), this.getKeyStoreFile(keyStoreFileType).getAbsolutePath());
System.setProperty(x509Util.getSslKeystorePasswdProperty(), this.getKeyStorePassword());
System.setProperty(x509Util.getSslKeystoreTypeProperty(), keyStoreFileType.getPropertyValue());
- System.setProperty(
- x509Util.getSslTruststoreLocationProperty(),
- this.getTrustStoreFile(trustStoreFileType).getAbsolutePath());
+ System.setProperty(x509Util.getSslTruststoreLocationProperty(), this.getTrustStoreFile(trustStoreFileType).getAbsolutePath());
System.setProperty(x509Util.getSslTruststorePasswdProperty(), this.getTrustStorePassword());
System.setProperty(x509Util.getSslTruststoreTypeProperty(), trustStoreFileType.getPropertyValue());
if (hostnameVerification != null) {
@@ -386,6 +351,7 @@ public class X509TestContext {
* Builder class, used for creating new instances of X509TestContext.
*/
public static class Builder {
+
public static final long DEFAULT_CERT_EXPIRATION_MILLIS = 1000L * 60 * 60 * 24; // 1 day
private File tempDir;
private X509KeyType trustStoreKeyType;
@@ -419,15 +385,7 @@ public class X509TestContext {
public X509TestContext build() throws IOException, GeneralSecurityException, OperatorCreationException {
KeyPair trustStoreKeyPair = X509TestHelpers.generateKeyPair(trustStoreKeyType);
KeyPair keyStoreKeyPair = X509TestHelpers.generateKeyPair(keyStoreKeyType);
- return new X509TestContext(
- tempDir,
- trustStoreKeyPair,
- trustStoreCertExpirationMillis,
- trustStorePassword,
- keyStoreKeyPair,
- keyStoreCertExpirationMillis,
- keyStorePassword,
- hostnameVerification);
+ return new X509TestContext(tempDir, trustStoreKeyPair, trustStoreCertExpirationMillis, trustStorePassword, keyStoreKeyPair, keyStoreCertExpirationMillis, keyStorePassword, hostnameVerification);
}
/**
@@ -512,6 +470,7 @@ public class X509TestContext {
this.hostnameVerification = hostnameVerification;
return this;
}
+
}
/**
@@ -521,4 +480,5 @@ public class X509TestContext {
public static Builder newBuilder() {
return new Builder();
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/common/X509TestHelpers.java b/zookeeper-server/src/test/java/org/apache/zookeeper/common/X509TestHelpers.java
index 9e8dcf620..4f1696897 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/common/X509TestHelpers.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/common/X509TestHelpers.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,6 +18,25 @@
package org.apache.zookeeper.common;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.StringWriter;
+import java.math.BigInteger;
+import java.net.InetAddress;
+import java.net.UnknownHostException;
+import java.security.GeneralSecurityException;
+import java.security.KeyPair;
+import java.security.KeyPairGenerator;
+import java.security.KeyStore;
+import java.security.PrivateKey;
+import java.security.PublicKey;
+import java.security.SecureRandom;
+import java.security.cert.Certificate;
+import java.security.cert.CertificateException;
+import java.security.cert.X509Certificate;
+import java.security.spec.ECGenParameterSpec;
+import java.security.spec.RSAKeyGenParameterSpec;
+import java.util.Date;
import org.bouncycastle.asn1.DERIA5String;
import org.bouncycastle.asn1.DEROctetString;
import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers;
@@ -51,31 +70,12 @@ import org.bouncycastle.operator.bc.BcRSAContentSignerBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.io.StringWriter;
-import java.math.BigInteger;
-import java.net.InetAddress;
-import java.net.UnknownHostException;
-import java.security.GeneralSecurityException;
-import java.security.KeyPair;
-import java.security.KeyPairGenerator;
-import java.security.KeyStore;
-import java.security.PrivateKey;
-import java.security.PublicKey;
-import java.security.SecureRandom;
-import java.security.cert.Certificate;
-import java.security.cert.CertificateException;
-import java.security.cert.X509Certificate;
-import java.security.spec.ECGenParameterSpec;
-import java.security.spec.RSAKeyGenParameterSpec;
-import java.util.Date;
-
/**
* This class contains helper methods for creating X509 certificates and key pairs, and for serializing them
* to JKS or PEM files.
*/
public class X509TestHelpers {
+
private static final Logger LOG = LoggerFactory.getLogger(X509TestHelpers.class);
private static final SecureRandom PRNG = new SecureRandom();
@@ -101,21 +101,15 @@ public class X509TestHelpers {
* @throws GeneralSecurityException
*/
public static X509Certificate newSelfSignedCACert(
- X500Name subject,
- KeyPair keyPair,
- long expirationMillis) throws IOException, OperatorCreationException, GeneralSecurityException {
+ X500Name subject, KeyPair keyPair, long expirationMillis) throws IOException, OperatorCreationException, GeneralSecurityException {
Date now = new Date();
- X509v3CertificateBuilder builder = initCertBuilder(
- subject, // for self-signed certs, issuer == subject
- now,
- new Date(now.getTime() + expirationMillis),
- subject,
- keyPair.getPublic());
+ X509v3CertificateBuilder builder = initCertBuilder(subject, // for self-signed certs, issuer == subject
+ now, new Date(now.getTime()
+ + expirationMillis), subject, keyPair.getPublic());
builder.addExtension(Extension.basicConstraints, true, new BasicConstraints(true)); // is a CA
- builder.addExtension(
- Extension.keyUsage,
- true,
- new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyCertSign | KeyUsage.cRLSign));
+ builder.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature
+ | KeyUsage.keyCertSign
+ | KeyUsage.cRLSign));
return buildAndSignCertificate(keyPair.getPrivate(), builder);
}
@@ -135,33 +129,20 @@ public class X509TestHelpers {
* @throws GeneralSecurityException
*/
public static X509Certificate newCert(
- X509Certificate caCert,
- KeyPair caKeyPair,
- X500Name certSubject,
- PublicKey certPublicKey,
- long expirationMillis) throws IOException, OperatorCreationException, GeneralSecurityException {
+ X509Certificate caCert, KeyPair caKeyPair, X500Name certSubject, PublicKey certPublicKey, long expirationMillis) throws IOException, OperatorCreationException, GeneralSecurityException {
if (!caKeyPair.getPublic().equals(caCert.getPublicKey())) {
throw new IllegalArgumentException("CA private key does not match the public key in the CA cert");
}
Date now = new Date();
- X509v3CertificateBuilder builder = initCertBuilder(
- new X500Name(caCert.getIssuerDN().getName()),
- now,
- new Date(now.getTime() + expirationMillis),
- certSubject,
- certPublicKey);
+ X509v3CertificateBuilder builder = initCertBuilder(new X500Name(caCert.getIssuerDN().getName()), now, new Date(
+ now.getTime()
+ + expirationMillis), certSubject, certPublicKey);
builder.addExtension(Extension.basicConstraints, true, new BasicConstraints(false)); // not a CA
- builder.addExtension(
- Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment));
- builder.addExtension(
- Extension.extendedKeyUsage,
- true,
- new ExtendedKeyUsage(new KeyPurposeId[] { KeyPurposeId.id_kp_serverAuth, KeyPurposeId.id_kp_clientAuth }));
+ builder.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature
+ | KeyUsage.keyEncipherment));
+ builder.addExtension(Extension.extendedKeyUsage, true, new ExtendedKeyUsage(new KeyPurposeId[]{KeyPurposeId.id_kp_serverAuth, KeyPurposeId.id_kp_clientAuth}));
- builder.addExtension(
- Extension.subjectAlternativeName,
- false,
- getLocalhostSubjectAltNames());
+ builder.addExtension(Extension.subjectAlternativeName, false, getLocalhostSubjectAltNames());
return buildAndSignCertificate(caKeyPair.getPrivate(), builder);
}
@@ -190,18 +171,8 @@ public class X509TestHelpers {
* @return a X509v3CertificateBuilder that can be further customized to finish creating the new cert.
*/
private static X509v3CertificateBuilder initCertBuilder(
- X500Name issuer,
- Date notBefore,
- Date notAfter,
- X500Name subject,
- PublicKey subjectPublicKey) {
- return new X509v3CertificateBuilder(
- issuer,
- new BigInteger(SERIAL_NUMBER_MAX_BITS, PRNG),
- notBefore,
- notAfter,
- subject,
- SubjectPublicKeyInfo.getInstance(subjectPublicKey.getEncoded()));
+ X500Name issuer, Date notBefore, Date notAfter, X500Name subject, PublicKey subjectPublicKey) {
+ return new X509v3CertificateBuilder(issuer, new BigInteger(SERIAL_NUMBER_MAX_BITS, PRNG), notBefore, notAfter, subject, SubjectPublicKeyInfo.getInstance(subjectPublicKey.getEncoded()));
}
/**
@@ -214,17 +185,14 @@ public class X509TestHelpers {
* @throws CertificateException
*/
private static X509Certificate buildAndSignCertificate(
- PrivateKey privateKey,
- X509v3CertificateBuilder builder) throws IOException, OperatorCreationException, CertificateException {
+ PrivateKey privateKey, X509v3CertificateBuilder builder) throws IOException, OperatorCreationException, CertificateException {
BcContentSignerBuilder signerBuilder;
if (privateKey.getAlgorithm().contains("RSA")) { // a little hacky way to detect key type, but it works
- AlgorithmIdentifier signatureAlgorithm = new DefaultSignatureAlgorithmIdentifierFinder().find(
- "SHA256WithRSAEncryption");
+ AlgorithmIdentifier signatureAlgorithm = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA256WithRSAEncryption");
AlgorithmIdentifier digestAlgorithm = new DefaultDigestAlgorithmIdentifierFinder().find(signatureAlgorithm);
signerBuilder = new BcRSAContentSignerBuilder(signatureAlgorithm, digestAlgorithm);
} else { // if not RSA, assume EC
- AlgorithmIdentifier signatureAlgorithm = new DefaultSignatureAlgorithmIdentifierFinder().find(
- "SHA256withECDSA");
+ AlgorithmIdentifier signatureAlgorithm = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA256withECDSA");
AlgorithmIdentifier digestAlgorithm = new DefaultDigestAlgorithmIdentifierFinder().find(signatureAlgorithm);
signerBuilder = new BcECContentSignerBuilder(signatureAlgorithm, digestAlgorithm);
}
@@ -241,12 +209,12 @@ public class X509TestHelpers {
*/
public static KeyPair generateKeyPair(X509KeyType keyType) throws GeneralSecurityException {
switch (keyType) {
- case RSA:
- return generateRSAKeyPair();
- case EC:
- return generateECKeyPair();
- default:
- throw new IllegalArgumentException("Invalid X509KeyType");
+ case RSA:
+ return generateRSAKeyPair();
+ case EC:
+ return generateECKeyPair();
+ default:
+ throw new IllegalArgumentException("Invalid X509KeyType");
}
}
@@ -256,8 +224,7 @@ public class X509TestHelpers {
*/
public static KeyPair generateRSAKeyPair() throws GeneralSecurityException {
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
- RSAKeyGenParameterSpec keyGenSpec = new RSAKeyGenParameterSpec(
- DEFAULT_RSA_KEY_SIZE_BITS, DEFAULT_RSA_PUB_EXPONENT);
+ RSAKeyGenParameterSpec keyGenSpec = new RSAKeyGenParameterSpec(DEFAULT_RSA_KEY_SIZE_BITS, DEFAULT_RSA_PUB_EXPONENT);
keyGen.initialize(keyGenSpec, PRNG);
return keyGen.generateKeyPair();
}
@@ -284,12 +251,8 @@ public class X509TestHelpers {
* @throws OperatorCreationException if constructing the encryptor from the given password fails.
*/
public static String pemEncodeCertAndPrivateKey(
- X509Certificate cert,
- PrivateKey privateKey,
- String keyPassword) throws IOException, OperatorCreationException {
- return pemEncodeX509Certificate(cert) +
- "\n" +
- pemEncodePrivateKey(privateKey, keyPassword);
+ X509Certificate cert, PrivateKey privateKey, String keyPassword) throws IOException, OperatorCreationException {
+ return pemEncodeX509Certificate(cert) + "\n" + pemEncodePrivateKey(privateKey, keyPassword);
}
/**
@@ -302,17 +265,12 @@ public class X509TestHelpers {
* @throws OperatorCreationException if constructing the encryptor from the given password fails.
*/
public static String pemEncodePrivateKey(
- PrivateKey key,
- String password) throws IOException, OperatorCreationException {
+ PrivateKey key, String password) throws IOException, OperatorCreationException {
StringWriter stringWriter = new StringWriter();
JcaPEMWriter pemWriter = new JcaPEMWriter(stringWriter);
OutputEncryptor encryptor = null;
if (password != null && password.length() > 0) {
- encryptor = new JceOpenSSLPKCS8EncryptorBuilder(PKCSObjectIdentifiers.pbeWithSHAAnd3_KeyTripleDES_CBC)
- .setProvider(BouncyCastleProvider.PROVIDER_NAME)
- .setRandom(PRNG)
- .setPasssword(password.toCharArray())
- .build();
+ encryptor = new JceOpenSSLPKCS8EncryptorBuilder(PKCSObjectIdentifiers.pbeWithSHAAnd3_KeyTripleDES_CBC).setProvider(BouncyCastleProvider.PROVIDER_NAME).setRandom(PRNG).setPasssword(password.toCharArray()).build();
}
pemWriter.writeObject(new JcaPKCS8Generator(key, encryptor));
pemWriter.close();
@@ -345,8 +303,7 @@ public class X509TestHelpers {
* @throws GeneralSecurityException
*/
public static byte[] certToJavaTrustStoreBytes(
- X509Certificate cert,
- String keyPassword) throws IOException, GeneralSecurityException {
+ X509Certificate cert, String keyPassword) throws IOException, GeneralSecurityException {
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
return certToTrustStoreBytes(cert, keyPassword, trustStore);
}
@@ -363,15 +320,12 @@ public class X509TestHelpers {
* @throws GeneralSecurityException
*/
public static byte[] certToPKCS12TrustStoreBytes(
- X509Certificate cert,
- String keyPassword) throws IOException, GeneralSecurityException {
+ X509Certificate cert, String keyPassword) throws IOException, GeneralSecurityException {
KeyStore trustStore = KeyStore.getInstance("PKCS12");
return certToTrustStoreBytes(cert, keyPassword, trustStore);
}
- private static byte[] certToTrustStoreBytes(X509Certificate cert,
- String keyPassword,
- KeyStore trustStore) throws IOException, GeneralSecurityException {
+ private static byte[] certToTrustStoreBytes(X509Certificate cert, String keyPassword, KeyStore trustStore) throws IOException, GeneralSecurityException {
char[] keyPasswordChars = keyPassword == null ? new char[0] : keyPassword.toCharArray();
trustStore.load(null, keyPasswordChars);
trustStore.setCertificateEntry(cert.getSubjectDN().toString(), cert);
@@ -395,9 +349,7 @@ public class X509TestHelpers {
* @throws GeneralSecurityException
*/
public static byte[] certAndPrivateKeyToJavaKeyStoreBytes(
- X509Certificate cert,
- PrivateKey privateKey,
- String keyPassword) throws IOException, GeneralSecurityException {
+ X509Certificate cert, PrivateKey privateKey, String keyPassword) throws IOException, GeneralSecurityException {
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
return certAndPrivateKeyToPKCS12Bytes(cert, privateKey, keyPassword, keyStore);
}
@@ -414,25 +366,16 @@ public class X509TestHelpers {
* @throws GeneralSecurityException
*/
public static byte[] certAndPrivateKeyToPKCS12Bytes(
- X509Certificate cert,
- PrivateKey privateKey,
- String keyPassword) throws IOException, GeneralSecurityException {
+ X509Certificate cert, PrivateKey privateKey, String keyPassword) throws IOException, GeneralSecurityException {
KeyStore keyStore = KeyStore.getInstance("PKCS12");
return certAndPrivateKeyToPKCS12Bytes(cert, privateKey, keyPassword, keyStore);
}
private static byte[] certAndPrivateKeyToPKCS12Bytes(
- X509Certificate cert,
- PrivateKey privateKey,
- String keyPassword,
- KeyStore keyStore) throws IOException, GeneralSecurityException {
+ X509Certificate cert, PrivateKey privateKey, String keyPassword, KeyStore keyStore) throws IOException, GeneralSecurityException {
char[] keyPasswordChars = keyPassword == null ? new char[0] : keyPassword.toCharArray();
keyStore.load(null, keyPasswordChars);
- keyStore.setKeyEntry(
- "key",
- privateKey,
- keyPasswordChars,
- new Certificate[] { cert });
+ keyStore.setKeyEntry("key", privateKey, keyPasswordChars, new Certificate[]{cert});
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
keyStore.store(outputStream, keyPasswordChars);
outputStream.flush();
@@ -450,4 +393,5 @@ public class X509TestHelpers {
public static X509Certificate toX509Cert(X509CertificateHolder certHolder) throws CertificateException {
return new JcaX509CertificateConverter().setProvider(BouncyCastleProvider.PROVIDER_NAME).getCertificate(certHolder);
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/common/X509UtilTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/common/X509UtilTest.java
index ec4567f56..d22b2f1bb 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/common/X509UtilTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/common/X509UtilTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -15,8 +15,13 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
package org.apache.zookeeper.common;
+import static org.junit.Assert.assertArrayEquals;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
@@ -32,7 +37,6 @@ import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Supplier;
-
import javax.net.ssl.HandshakeCompletedEvent;
import javax.net.ssl.HandshakeCompletedListener;
import javax.net.ssl.SSLContext;
@@ -41,12 +45,10 @@ import javax.net.ssl.SSLServerSocket;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.X509KeyManager;
import javax.net.ssl.X509TrustManager;
-
import org.apache.zookeeper.PortAssignment;
import org.apache.zookeeper.client.ZKClientConfig;
import org.apache.zookeeper.server.ServerCnxnFactory;
import org.junit.After;
-import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -54,10 +56,12 @@ import org.junit.runners.Parameterized;
@RunWith(Parameterized.class)
public class X509UtilTest extends BaseX509ParameterizedTestCase {
+
private X509Util x509Util;
private static final String[] customCipherSuites = new String[]{
- "SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA",
- "SSL_DH_anon_EXPORT_WITH_DES40_CBC_SHA"};
+ "SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA",
+ "SSL_DH_anon_EXPORT_WITH_DES40_CBC_SHA"
+ };
@Parameterized.Parameters
public static Collection<Object[]> params() {
@@ -65,19 +69,16 @@ public class X509UtilTest extends BaseX509ParameterizedTestCase {
}
public X509UtilTest(
- X509KeyType caKeyType,
- X509KeyType certKeyType,
- String keyPassword,
- Integer paramIndex) {
+ X509KeyType caKeyType, X509KeyType certKeyType, String keyPassword, Integer paramIndex) {
super(paramIndex, () -> {
try {
return X509TestContext.newBuilder()
- .setTempDir(tempDir)
- .setKeyStorePassword(keyPassword)
- .setKeyStoreKeyType(certKeyType)
- .setTrustStorePassword(keyPassword)
- .setTrustStoreKeyType(caKeyType)
- .build();
+ .setTempDir(tempDir)
+ .setKeyStorePassword(keyPassword)
+ .setKeyStoreKeyType(certKeyType)
+ .setTrustStorePassword(keyPassword)
+ .setTrustStoreKeyType(caKeyType)
+ .build();
} catch (Exception e) {
throw new RuntimeException(e);
}
@@ -114,7 +115,7 @@ public class X509UtilTest extends BaseX509ParameterizedTestCase {
@Test(timeout = 5000)
public void testCreateSSLContextWithoutCustomProtocol() throws Exception {
SSLContext sslContext = x509Util.getDefaultSSLContext();
- Assert.assertEquals(X509Util.DEFAULT_PROTOCOL, sslContext.getProtocol());
+ assertEquals(X509Util.DEFAULT_PROTOCOL, sslContext.getProtocol());
}
@Test(timeout = 5000)
@@ -122,7 +123,7 @@ public class X509UtilTest extends BaseX509ParameterizedTestCase {
final String protocol = "TLSv1.1";
System.setProperty(x509Util.getSslProtocolProperty(), protocol);
SSLContext sslContext = x509Util.getDefaultSSLContext();
- Assert.assertEquals(protocol, sslContext.getProtocol());
+ assertEquals(protocol, sslContext.getProtocol());
}
@Test(timeout = 5000)
@@ -144,7 +145,7 @@ public class X509UtilTest extends BaseX509ParameterizedTestCase {
public void testCreateSSLContextWithCustomCipherSuites() throws Exception {
setCustomCipherSuites();
SSLSocket sslSocket = x509Util.createSSLSocket();
- Assert.assertArrayEquals(customCipherSuites, sslSocket.getEnabledCipherSuites());
+ assertArrayEquals(customCipherSuites, sslSocket.getEnabledCipherSuites());
}
// It would be great to test the value of PKIXBuilderParameters#setRevocationEnabled but it does not appear to be
@@ -153,41 +154,41 @@ public class X509UtilTest extends BaseX509ParameterizedTestCase {
public void testCRLEnabled() throws Exception {
System.setProperty(x509Util.getSslCrlEnabledProperty(), "true");
x509Util.getDefaultSSLContext();
- Assert.assertTrue(Boolean.valueOf(System.getProperty("com.sun.net.ssl.checkRevocation")));
- Assert.assertTrue(Boolean.valueOf(System.getProperty("com.sun.security.enableCRLDP")));
- Assert.assertFalse(Boolean.valueOf(Security.getProperty("ocsp.enable")));
+ assertTrue(Boolean.valueOf(System.getProperty("com.sun.net.ssl.checkRevocation")));
+ assertTrue(Boolean.valueOf(System.getProperty("com.sun.security.enableCRLDP")));
+ assertFalse(Boolean.valueOf(Security.getProperty("ocsp.enable")));
}
@Test(timeout = 5000)
public void testCRLDisabled() throws Exception {
x509Util.getDefaultSSLContext();
- Assert.assertFalse(Boolean.valueOf(System.getProperty("com.sun.net.ssl.checkRevocation")));
- Assert.assertFalse(Boolean.valueOf(System.getProperty("com.sun.security.enableCRLDP")));
- Assert.assertFalse(Boolean.valueOf(Security.getProperty("ocsp.enable")));
+ assertFalse(Boolean.valueOf(System.getProperty("com.sun.net.ssl.checkRevocation")));
+ assertFalse(Boolean.valueOf(System.getProperty("com.sun.security.enableCRLDP")));
+ assertFalse(Boolean.valueOf(Security.getProperty("ocsp.enable")));
}
@Test(timeout = 5000)
public void testOCSPEnabled() throws Exception {
System.setProperty(x509Util.getSslOcspEnabledProperty(), "true");
x509Util.getDefaultSSLContext();
- Assert.assertTrue(Boolean.valueOf(System.getProperty("com.sun.net.ssl.checkRevocation")));
- Assert.assertTrue(Boolean.valueOf(System.getProperty("com.sun.security.enableCRLDP")));
- Assert.assertTrue(Boolean.valueOf(Security.getProperty("ocsp.enable")));
+ assertTrue(Boolean.valueOf(System.getProperty("com.sun.net.ssl.checkRevocation")));
+ assertTrue(Boolean.valueOf(System.getProperty("com.sun.security.enableCRLDP")));
+ assertTrue(Boolean.valueOf(Security.getProperty("ocsp.enable")));
}
@Test(timeout = 5000)
public void testCreateSSLSocket() throws Exception {
setCustomCipherSuites();
SSLSocket sslSocket = x509Util.createSSLSocket();
- Assert.assertArrayEquals(customCipherSuites, sslSocket.getEnabledCipherSuites());
+ assertArrayEquals(customCipherSuites, sslSocket.getEnabledCipherSuites());
}
@Test(timeout = 5000)
public void testCreateSSLServerSocketWithoutPort() throws Exception {
setCustomCipherSuites();
SSLServerSocket sslServerSocket = x509Util.createSSLServerSocket();
- Assert.assertArrayEquals(customCipherSuites, sslServerSocket.getEnabledCipherSuites());
- Assert.assertTrue(sslServerSocket.getNeedClientAuth());
+ assertArrayEquals(customCipherSuites, sslServerSocket.getEnabledCipherSuites());
+ assertTrue(sslServerSocket.getNeedClientAuth());
}
@Test(timeout = 5000)
@@ -195,18 +196,18 @@ public class X509UtilTest extends BaseX509ParameterizedTestCase {
setCustomCipherSuites();
int port = PortAssignment.unique();
SSLServerSocket sslServerSocket = x509Util.createSSLServerSocket(port);
- Assert.assertEquals(sslServerSocket.getLocalPort(), port);
- Assert.assertArrayEquals(customCipherSuites, sslServerSocket.getEnabledCipherSuites());
- Assert.assertTrue(sslServerSocket.getNeedClientAuth());
+ assertEquals(sslServerSocket.getLocalPort(), port);
+ assertArrayEquals(customCipherSuites, sslServerSocket.getEnabledCipherSuites());
+ assertTrue(sslServerSocket.getNeedClientAuth());
}
@Test
public void testLoadPEMKeyStore() throws Exception {
// Make sure we can instantiate a key manager from the PEM file on disk
X509KeyManager km = X509Util.createKeyManager(
- x509TestContext.getKeyStoreFile(KeyStoreFileType.PEM).getAbsolutePath(),
- x509TestContext.getKeyStorePassword(),
- KeyStoreFileType.PEM.getPropertyValue());
+ x509TestContext.getKeyStoreFile(KeyStoreFileType.PEM).getAbsolutePath(),
+ x509TestContext.getKeyStorePassword(),
+ KeyStoreFileType.PEM.getPropertyValue());
}
@Test
@@ -216,40 +217,39 @@ public class X509UtilTest extends BaseX509ParameterizedTestCase {
}
// Make sure that empty password and null password are treated the same
X509KeyManager km = X509Util.createKeyManager(
- x509TestContext.getKeyStoreFile(KeyStoreFileType.PEM).getAbsolutePath(),
- null,
- KeyStoreFileType.PEM.getPropertyValue());
+ x509TestContext.getKeyStoreFile(KeyStoreFileType.PEM).getAbsolutePath(),
+ null,
+ KeyStoreFileType.PEM.getPropertyValue());
}
@Test
public void testLoadPEMKeyStoreAutodetectStoreFileType() throws Exception {
// Make sure we can instantiate a key manager from the PEM file on disk
X509KeyManager km = X509Util.createKeyManager(
- x509TestContext.getKeyStoreFile(KeyStoreFileType.PEM).getAbsolutePath(),
- x509TestContext.getKeyStorePassword(),
- null /* null StoreFileType means 'autodetect from file extension' */);
+ x509TestContext.getKeyStoreFile(KeyStoreFileType.PEM).getAbsolutePath(),
+ x509TestContext.getKeyStorePassword(),
+ null /* null StoreFileType means 'autodetect from file extension' */);
}
@Test(expected = X509Exception.KeyManagerException.class)
public void testLoadPEMKeyStoreWithWrongPassword() throws Exception {
// Attempting to load with the wrong key password should fail
X509KeyManager km = X509Util.createKeyManager(
- x509TestContext.getKeyStoreFile(KeyStoreFileType.PEM).getAbsolutePath(),
- "wrong password", // intentionally use the wrong password
- KeyStoreFileType.PEM.getPropertyValue());
+ x509TestContext.getKeyStoreFile(KeyStoreFileType.PEM).getAbsolutePath(),
+ "wrong password", // intentionally use the wrong password
+ KeyStoreFileType.PEM.getPropertyValue());
}
@Test
public void testLoadPEMTrustStore() throws Exception {
// Make sure we can instantiate a trust manager from the PEM file on disk
X509TrustManager tm = X509Util.createTrustManager(
- x509TestContext.getTrustStoreFile(KeyStoreFileType.PEM).getAbsolutePath(),
- x509TestContext.getTrustStorePassword(),
- KeyStoreFileType.PEM.getPropertyValue(),
- false,
- false,
- true,
- true);
+ x509TestContext.getTrustStoreFile(KeyStoreFileType.PEM).getAbsolutePath(),
+ x509TestContext.getTrustStorePassword(), KeyStoreFileType.PEM.getPropertyValue(),
+ false,
+ false,
+ true,
+ true);
}
@Test
@@ -259,13 +259,13 @@ public class X509UtilTest extends BaseX509ParameterizedTestCase {
}
// Make sure that empty password and null password are treated the same
X509TrustManager tm = X509Util.createTrustManager(
- x509TestContext.getTrustStoreFile(KeyStoreFileType.PEM).getAbsolutePath(),
- null,
- KeyStoreFileType.PEM.getPropertyValue(),
- false,
- false,
- true,
- true);
+ x509TestContext.getTrustStoreFile(KeyStoreFileType.PEM).getAbsolutePath(),
+ null,
+ KeyStoreFileType.PEM.getPropertyValue(),
+ false,
+ false,
+ true,
+ true);
}
@@ -273,22 +273,22 @@ public class X509UtilTest extends BaseX509ParameterizedTestCase {
public void testLoadPEMTrustStoreAutodetectStoreFileType() throws Exception {
// Make sure we can instantiate a trust manager from the PEM file on disk
X509TrustManager tm = X509Util.createTrustManager(
- x509TestContext.getTrustStoreFile(KeyStoreFileType.PEM).getAbsolutePath(),
- x509TestContext.getTrustStorePassword(),
- null, // null StoreFileType means 'autodetect from file extension'
- false,
- false,
- true,
- true);
+ x509TestContext.getTrustStoreFile(KeyStoreFileType.PEM).getAbsolutePath(),
+ x509TestContext.getTrustStorePassword(),
+ null, // null StoreFileType means 'autodetect from file extension'
+ false,
+ false,
+ true,
+ true);
}
@Test
public void testLoadJKSKeyStore() throws Exception {
// Make sure we can instantiate a key manager from the JKS file on disk
X509KeyManager km = X509Util.createKeyManager(
- x509TestContext.getKeyStoreFile(KeyStoreFileType.JKS).getAbsolutePath(),
- x509TestContext.getKeyStorePassword(),
- KeyStoreFileType.JKS.getPropertyValue());
+ x509TestContext.getKeyStoreFile(KeyStoreFileType.JKS).getAbsolutePath(),
+ x509TestContext.getKeyStorePassword(),
+ KeyStoreFileType.JKS.getPropertyValue());
}
@Test
@@ -298,40 +298,40 @@ public class X509UtilTest extends BaseX509ParameterizedTestCase {
}
// Make sure that empty password and null password are treated the same
X509KeyManager km = X509Util.createKeyManager(
- x509TestContext.getKeyStoreFile(KeyStoreFileType.JKS).getAbsolutePath(),
- null,
- KeyStoreFileType.JKS.getPropertyValue());
+ x509TestContext.getKeyStoreFile(KeyStoreFileType.JKS).getAbsolutePath(),
+ null,
+ KeyStoreFileType.JKS.getPropertyValue());
}
@Test
public void testLoadJKSKeyStoreAutodetectStoreFileType() throws Exception {
// Make sure we can instantiate a key manager from the JKS file on disk
X509KeyManager km = X509Util.createKeyManager(
- x509TestContext.getKeyStoreFile(KeyStoreFileType.JKS).getAbsolutePath(),
- x509TestContext.getKeyStorePassword(),
- null /* null StoreFileType means 'autodetect from file extension' */);
+ x509TestContext.getKeyStoreFile(KeyStoreFileType.JKS).getAbsolutePath(),
+ x509TestContext.getKeyStorePassword(),
+ null /* null StoreFileType means 'autodetect from file extension' */);
}
@Test(expected = X509Exception.KeyManagerException.class)
public void testLoadJKSKeyStoreWithWrongPassword() throws Exception {
// Attempting to load with the wrong key password should fail
X509KeyManager km = X509Util.createKeyManager(
- x509TestContext.getKeyStoreFile(KeyStoreFileType.JKS).getAbsolutePath(),
- "wrong password",
- KeyStoreFileType.JKS.getPropertyValue());
+ x509TestContext.getKeyStoreFile(KeyStoreFileType.JKS).getAbsolutePath(),
+ "wrong password",
+ KeyStoreFileType.JKS.getPropertyValue());
}
@Test
public void testLoadJKSTrustStore() throws Exception {
// Make sure we can instantiate a trust manager from the JKS file on disk
X509TrustManager tm = X509Util.createTrustManager(
- x509TestContext.getTrustStoreFile(KeyStoreFileType.JKS).getAbsolutePath(),
- x509TestContext.getTrustStorePassword(),
- KeyStoreFileType.JKS.getPropertyValue(),
- true,
- true,
- true,
- true);
+ x509TestContext.getTrustStoreFile(KeyStoreFileType.JKS).getAbsolutePath(),
+ x509TestContext.getTrustStorePassword(),
+ KeyStoreFileType.JKS.getPropertyValue(),
+ true,
+ true,
+ true,
+ true);
}
@Test
@@ -341,39 +341,39 @@ public class X509UtilTest extends BaseX509ParameterizedTestCase {
}
// Make sure that empty password and null password are treated the same
X509TrustManager tm = X509Util.createTrustManager(
- x509TestContext.getTrustStoreFile(KeyStoreFileType.JKS).getAbsolutePath(),
- null,
- KeyStoreFileType.JKS.getPropertyValue(),
- false,
- false,
- true,
- true);
+ x509TestContext.getTrustStoreFile(KeyStoreFileType.JKS).getAbsolutePath(),
+ null,
+ KeyStoreFileType.JKS.getPropertyValue(),
+ false,
+ false,
+ true,
+ true);
}
@Test
public void testLoadJKSTrustStoreAutodetectStoreFileType() throws Exception {
// Make sure we can instantiate a trust manager from the JKS file on disk
X509TrustManager tm = X509Util.createTrustManager(
- x509TestContext.getTrustStoreFile(KeyStoreFileType.JKS).getAbsolutePath(),
- x509TestContext.getTrustStorePassword(),
- null, // null StoreFileType means 'autodetect from file extension'
- true,
- true,
- true,
- true);
+ x509TestContext.getTrustStoreFile(KeyStoreFileType.JKS).getAbsolutePath(),
+ x509TestContext.getTrustStorePassword(),
+ null, // null StoreFileType means 'autodetect from file extension'
+ true,
+ true,
+ true,
+ true);
}
@Test(expected = X509Exception.TrustManagerException.class)
public void testLoadJKSTrustStoreWithWrongPassword() throws Exception {
// Attempting to load with the wrong key password should fail
X509TrustManager tm = X509Util.createTrustManager(
- x509TestContext.getTrustStoreFile(KeyStoreFileType.JKS).getAbsolutePath(),
- "wrong password",
- KeyStoreFileType.JKS.getPropertyValue(),
- true,
- true,
- true,
- true);
+ x509TestContext.getTrustStoreFile(KeyStoreFileType.JKS).getAbsolutePath(),
+ "wrong password",
+ KeyStoreFileType.JKS.getPropertyValue(),
+ true,
+ true,
+ true,
+ true);
}
@Test
@@ -420,8 +420,7 @@ public class X509UtilTest extends BaseX509ParameterizedTestCase {
// Make sure we can instantiate a trust manager from the PKCS12 file on disk
X509TrustManager tm = X509Util.createTrustManager(
x509TestContext.getTrustStoreFile(KeyStoreFileType.PKCS12).getAbsolutePath(),
- x509TestContext.getTrustStorePassword(),
- KeyStoreFileType.PKCS12.getPropertyValue(),
+ x509TestContext.getTrustStorePassword(), KeyStoreFileType.PKCS12.getPropertyValue(),
true,
true,
true,
@@ -472,30 +471,23 @@ public class X509UtilTest extends BaseX509ParameterizedTestCase {
@Test
public void testGetSslHandshakeDetectionTimeoutMillisProperty() {
- Assert.assertEquals(
- X509Util.DEFAULT_HANDSHAKE_DETECTION_TIMEOUT_MILLIS,
- x509Util.getSslHandshakeTimeoutMillis());
+ assertEquals(X509Util.DEFAULT_HANDSHAKE_DETECTION_TIMEOUT_MILLIS, x509Util.getSslHandshakeTimeoutMillis());
// Note: need to create a new ClientX509Util each time to pick up modified property value
String newPropertyString = Integer.toString(X509Util.DEFAULT_HANDSHAKE_DETECTION_TIMEOUT_MILLIS + 1);
System.setProperty(x509Util.getSslHandshakeDetectionTimeoutMillisProperty(), newPropertyString);
try (X509Util tempX509Util = new ClientX509Util()) {
- Assert.assertEquals(
- X509Util.DEFAULT_HANDSHAKE_DETECTION_TIMEOUT_MILLIS + 1,
- tempX509Util.getSslHandshakeTimeoutMillis());
+ assertEquals(X509Util.DEFAULT_HANDSHAKE_DETECTION_TIMEOUT_MILLIS
+ + 1, tempX509Util.getSslHandshakeTimeoutMillis());
}
// 0 value not allowed, will return the default
System.setProperty(x509Util.getSslHandshakeDetectionTimeoutMillisProperty(), "0");
try (X509Util tempX509Util = new ClientX509Util()) {
- Assert.assertEquals(
- X509Util.DEFAULT_HANDSHAKE_DETECTION_TIMEOUT_MILLIS,
- tempX509Util.getSslHandshakeTimeoutMillis());
+ assertEquals(X509Util.DEFAULT_HANDSHAKE_DETECTION_TIMEOUT_MILLIS, tempX509Util.getSslHandshakeTimeoutMillis());
}
// Negative value not allowed, will return the default
System.setProperty(x509Util.getSslHandshakeDetectionTimeoutMillisProperty(), "-1");
try (X509Util tempX509Util = new ClientX509Util()) {
- Assert.assertEquals(
- X509Util.DEFAULT_HANDSHAKE_DETECTION_TIMEOUT_MILLIS,
- tempX509Util.getSslHandshakeTimeoutMillis());
+ assertEquals(X509Util.DEFAULT_HANDSHAKE_DETECTION_TIMEOUT_MILLIS, tempX509Util.getSslHandshakeTimeoutMillis());
}
}
@@ -513,7 +505,7 @@ public class X509UtilTest extends BaseX509ParameterizedTestCase {
ClientX509Util clientX509Util = new ClientX509Util();
zkConfig.setProperty(clientX509Util.getSslContextSupplierClassProperty(), SslContextSupplier.class.getName());
final SSLContext sslContext = clientX509Util.createSSLContext(zkConfig);
- Assert.assertEquals(SSLContext.getDefault(), sslContext);
+ assertEquals(SSLContext.getDefault(), sslContext);
}
private static void forceClose(Socket s) {
@@ -547,8 +539,7 @@ public class X509UtilTest extends BaseX509ParameterizedTestCase {
SSLSocket serverSocket = null;
final AtomicInteger handshakesCompleted = new AtomicInteger(0);
try {
- InetSocketAddress localServerAddress = new InetSocketAddress(
- InetAddress.getLoopbackAddress(), port);
+ InetSocketAddress localServerAddress = new InetSocketAddress(InetAddress.getLoopbackAddress(), port);
listeningSocket.bind(localServerAddress);
Future<SSLSocket> acceptFuture;
acceptFuture = workerPool.submit(new Callable<SSLSocket>() {
@@ -561,7 +552,7 @@ public class X509UtilTest extends BaseX509ParameterizedTestCase {
handshakesCompleted.getAndIncrement();
}
});
- Assert.assertEquals(1, sslSocket.getInputStream().read());
+ assertEquals(1, sslSocket.getInputStream().read());
try {
// 2nd read is after the renegotiation attempt and will fail
sslSocket.getInputStream().read();
@@ -591,7 +582,7 @@ public class X509UtilTest extends BaseX509ParameterizedTestCase {
workerPool.shutdown();
// Make sure the first handshake completed and only the second
// one failed.
- Assert.assertEquals(1, handshakesCompleted.get());
+ assertEquals(1, handshakesCompleted.get());
}
}
@@ -599,35 +590,35 @@ public class X509UtilTest extends BaseX509ParameterizedTestCase {
public void testGetDefaultCipherSuitesJava8() {
String[] cipherSuites = X509Util.getDefaultCipherSuitesForJavaVersion("1.8");
// Java 8 default should have the CBC suites first
- Assert.assertTrue(cipherSuites[0].contains("CBC"));
+ assertTrue(cipherSuites[0].contains("CBC"));
}
@Test
public void testGetDefaultCipherSuitesJava9() {
String[] cipherSuites = X509Util.getDefaultCipherSuitesForJavaVersion("9");
// Java 9+ default should have the GCM suites first
- Assert.assertTrue(cipherSuites[0].contains("GCM"));
+ assertTrue(cipherSuites[0].contains("GCM"));
}
@Test
public void testGetDefaultCipherSuitesJava10() {
String[] cipherSuites = X509Util.getDefaultCipherSuitesForJavaVersion("10");
// Java 9+ default should have the GCM suites first
- Assert.assertTrue(cipherSuites[0].contains("GCM"));
+ assertTrue(cipherSuites[0].contains("GCM"));
}
@Test
public void testGetDefaultCipherSuitesJava11() {
String[] cipherSuites = X509Util.getDefaultCipherSuitesForJavaVersion("11");
// Java 9+ default should have the GCM suites first
- Assert.assertTrue(cipherSuites[0].contains("GCM"));
+ assertTrue(cipherSuites[0].contains("GCM"));
}
@Test
public void testGetDefaultCipherSuitesUnknownVersion() {
String[] cipherSuites = X509Util.getDefaultCipherSuitesForJavaVersion("notaversion");
// If version can't be parsed, use the more conservative Java 8 default
- Assert.assertTrue(cipherSuites[0].contains("CBC"));
+ assertTrue(cipherSuites[0].contains("CBC"));
}
@Test(expected = NullPointerException.class)
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/common/ZKTrustManagerTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/common/ZKTrustManagerTest.java
index 32f250b41..66fabed7f 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/common/ZKTrustManagerTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/common/ZKTrustManagerTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -15,8 +15,26 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
package org.apache.zookeeper.common;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+import java.math.BigInteger;
+import java.net.InetAddress;
+import java.net.Socket;
+import java.security.KeyPair;
+import java.security.KeyPairGenerator;
+import java.security.Security;
+import java.security.cert.X509Certificate;
+import java.util.ArrayList;
+import java.util.Calendar;
+import java.util.Date;
+import java.util.List;
+import java.util.Random;
+import javax.net.ssl.X509ExtendedTrustManager;
import org.apache.zookeeper.ZKTestCase;
import org.bouncycastle.asn1.x500.X500NameBuilder;
import org.bouncycastle.asn1.x500.style.BCStyle;
@@ -38,25 +56,6 @@ import org.junit.Test;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
-import javax.net.ssl.X509ExtendedTrustManager;
-import java.math.BigInteger;
-import java.net.InetAddress;
-import java.net.Socket;
-import java.security.KeyPair;
-import java.security.KeyPairGenerator;
-import java.security.Security;
-import java.security.cert.X509Certificate;
-import java.util.ArrayList;
-import java.util.Calendar;
-import java.util.Date;
-import java.util.List;
-import java.util.Random;
-
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.times;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
-
// We can only test calls to ZKTrustManager using Sockets (not SSLEngines). This can be fine since the logic is the same.
public class ZKTrustManagerTest extends ZKTestCase {
@@ -120,10 +119,10 @@ public class ZKTrustManagerTest extends ZKTestCase {
Date notAfter = cal.getTime();
BigInteger serialNumber = new BigInteger(128, new Random());
- X509v3CertificateBuilder certificateBuilder =
- new JcaX509v3CertificateBuilder(nameBuilder.build(), serialNumber, notBefore, notAfter, nameBuilder.build(), keyPair.getPublic())
- .addExtension(Extension.basicConstraints, true, new BasicConstraints(0))
- .addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyCertSign | KeyUsage.cRLSign));
+ X509v3CertificateBuilder certificateBuilder = new JcaX509v3CertificateBuilder(nameBuilder.build(), serialNumber, notBefore, notAfter, nameBuilder.build(), keyPair.getPublic()).addExtension(Extension.basicConstraints, true, new BasicConstraints(0)).addExtension(Extension.keyUsage, true, new KeyUsage(
+ KeyUsage.digitalSignature
+ | KeyUsage.keyCertSign
+ | KeyUsage.cRLSign));
List<GeneralName> generalNames = new ArrayList<>();
if (ipAddress != null) {
@@ -134,12 +133,12 @@ public class ZKTrustManagerTest extends ZKTestCase {
}
if (!generalNames.isEmpty()) {
- certificateBuilder.addExtension(Extension.subjectAlternativeName, true, new GeneralNames(generalNames.toArray(new GeneralName[] {})));
+ certificateBuilder.addExtension(Extension.subjectAlternativeName, true, new GeneralNames(generalNames.toArray(new GeneralName[]{})));
}
ContentSigner contentSigner = new JcaContentSignerBuilder("SHA256WithRSAEncryption").build(keyPair.getPrivate());
- return new X509Certificate[] { new JcaX509CertificateConverter().getCertificate(certificateBuilder.build(contentSigner)) };
+ return new X509Certificate[]{new JcaX509CertificateConverter().getCertificate(certificateBuilder.build(contentSigner))};
}
@Test
@@ -245,4 +244,5 @@ public class ZKTrustManagerTest extends ZKTestCase {
verify(mockX509ExtendedTrustManager, times(1)).checkClientTrusted(certificateChain, null, mockSocket);
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/metrics/BaseTestMetricsProvider.java b/zookeeper-server/src/test/java/org/apache/zookeeper/metrics/BaseTestMetricsProvider.java
index 3e2301997..7ce361cfe 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/metrics/BaseTestMetricsProvider.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/metrics/BaseTestMetricsProvider.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -15,6 +15,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
package org.apache.zookeeper.metrics;
import java.util.Properties;
@@ -66,7 +67,7 @@ public abstract class BaseTestMetricsProvider implements MetricsProvider {
stopCalled.set(false);
getRootContextCalled.set(false);
}
-
+
@Override
public void configure(Properties prprts) throws MetricsProviderLifeCycleException {
if (!configureCalled.compareAndSet(false, true)) {
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/metrics/MetricsUtils.java b/zookeeper-server/src/test/java/org/apache/zookeeper/metrics/MetricsUtils.java
index b1b0ecc8e..25883aa16 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/metrics/MetricsUtils.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/metrics/MetricsUtils.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -15,6 +15,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
package org.apache.zookeeper.metrics;
import java.util.HashMap;
@@ -45,7 +46,7 @@ public abstract class MetricsUtils {
metricsProvider.dump(res::put);
return res;
}
-
+
/**
* Collect current {@link ServerMetrics} as a Map.
*
@@ -55,4 +56,5 @@ public abstract class MetricsUtils {
public static Map<String, Object> currentServerMetrics() {
return collect(ServerMetrics.getMetrics().getMetricsProvider());
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/BlueThrottleTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/BlueThrottleTest.java
index aa27a15f7..c3d10bb56 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/BlueThrottleTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/BlueThrottleTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -15,21 +15,24 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
package org.apache.zookeeper.server;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import java.util.Random;
import org.apache.zookeeper.ZKTestCase;
-import org.junit.Assert;
-import org.junit.Rule;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.util.Random;
-
public class BlueThrottleTest extends ZKTestCase {
+
private static final Logger LOG = LoggerFactory.getLogger(BlueThrottleTest.class);
class MockRandom extends Random {
+
int flag = 0;
BlueThrottle throttle;
@@ -42,20 +45,23 @@ public class BlueThrottleTest extends ZKTestCase {
return 1;
}
}
+
}
class BlueThrottleWithMockRandom extends BlueThrottle {
+
public BlueThrottleWithMockRandom(MockRandom random) {
super();
this.rng = random;
random.throttle = this;
}
+
}
@Test
public void testThrottleDisabled() {
BlueThrottle throttler = new BlueThrottle();
- Assert.assertTrue("Throttle should be disabled by default", throttler.checkLimit(1));
+ assertTrue("Throttle should be disabled by default", throttler.checkLimit(1));
}
@Test
@@ -63,8 +69,8 @@ public class BlueThrottleTest extends ZKTestCase {
BlueThrottle throttler = new BlueThrottle();
throttler.setMaxTokens(1);
throttler.setFillTime(2000);
- Assert.assertTrue("First request should be allowed", throttler.checkLimit(1));
- Assert.assertFalse("Second request should be denied", throttler.checkLimit(1));
+ assertTrue("First request should be allowed", throttler.checkLimit(1));
+ assertFalse("Second request should be denied", throttler.checkLimit(1));
}
@Test
@@ -72,12 +78,12 @@ public class BlueThrottleTest extends ZKTestCase {
BlueThrottle throttler = new BlueThrottle();
throttler.setMaxTokens(1);
throttler.setFillTime(500);
- Assert.assertTrue("First request should be allowed", throttler.checkLimit(1));
- Assert.assertFalse("Second request should be denied", throttler.checkLimit(1));
+ assertTrue("First request should be allowed", throttler.checkLimit(1));
+ assertFalse("Second request should be denied", throttler.checkLimit(1));
//wait for the bucket to be refilled
Thread.sleep(750);
- Assert.assertTrue("Third request should be allowed since we've got a new token", throttler.checkLimit(1));
+ assertTrue("Third request should be allowed since we've got a new token", throttler.checkLimit(1));
}
@Test
@@ -88,24 +94,24 @@ public class BlueThrottleTest extends ZKTestCase {
throttler.setFillCount(maxTokens);
throttler.setFillTime(1000);
- for (int i=0;i<maxTokens;i++) {
+ for (int i = 0; i < maxTokens; i++) {
throttler.checkLimit(1);
}
- Assert.assertEquals("All tokens should be used up by now", throttler.getMaxTokens(), throttler.getDeficit());
+ assertEquals("All tokens should be used up by now", throttler.getMaxTokens(), throttler.getDeficit());
Thread.sleep(110);
throttler.checkLimit(1);
- Assert.assertFalse("Dropping probability should still be zero", throttler.getDropChance()>0);
+ assertFalse("Dropping probability should still be zero", throttler.getDropChance() > 0);
//allow bucket to be refilled
Thread.sleep(1500);
- for (int i=0;i<maxTokens;i++) {
- Assert.assertTrue("The first " + maxTokens + " requests should be allowed", throttler.checkLimit(1));
+ for (int i = 0; i < maxTokens; i++) {
+ assertTrue("The first " + maxTokens + " requests should be allowed", throttler.checkLimit(1));
}
- for (int i=0;i<maxTokens;i++) {
- Assert.assertFalse("The latter " + maxTokens + " requests should be denied", throttler.checkLimit(1));
+ for (int i = 0; i < maxTokens; i++) {
+ assertFalse("The latter " + maxTokens + " requests should be denied", throttler.checkLimit(1));
}
}
@@ -119,14 +125,15 @@ public class BlueThrottleTest extends ZKTestCase {
throttler.setFreezeTime(100);
throttler.setDropIncrease(0.5);
- for (int i=0;i<maxTokens;i++)
+ for (int i = 0; i < maxTokens; i++) {
throttler.checkLimit(1);
- Assert.assertEquals("All tokens should be used up by now", throttler.getMaxTokens(), throttler.getDeficit());
+ }
+ assertEquals("All tokens should be used up by now", throttler.getMaxTokens(), throttler.getDeficit());
Thread.sleep(120);
//this will trigger dropping probability being increased
throttler.checkLimit(1);
- Assert.assertTrue("Dropping probability should be increased", throttler.getDropChance()>0);
+ assertTrue("Dropping probability should be increased", throttler.getDropChance() > 0);
LOG.info("Dropping probability is {}", throttler.getDropChance());
//allow bucket to be refilled
@@ -134,24 +141,25 @@ public class BlueThrottleTest extends ZKTestCase {
LOG.info("Bucket is refilled with {} tokens.", maxTokens);
int accepted = 0;
- for (int i=0;i<maxTokens;i++) {
+ for (int i = 0; i < maxTokens; i++) {
if (throttler.checkLimit(1)) {
- accepted ++;
+ accepted++;
}
}
LOG.info("Send {} requests, {} are accepted", maxTokens, accepted);
- Assert.assertTrue("The dropping should be distributed", accepted<maxTokens);
+ assertTrue("The dropping should be distributed", accepted < maxTokens);
accepted = 0;
- for (int i=0;i<maxTokens;i++) {
+ for (int i = 0; i < maxTokens; i++) {
if (throttler.checkLimit(1)) {
- accepted ++;
+ accepted++;
}
}
LOG.info("Send another {} requests, {} are accepted", maxTokens, accepted);
- Assert.assertTrue("Later requests should have a chance", accepted > 0);
+ assertTrue("Later requests should have a chance", accepted > 0);
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/ByteBufferInputStreamTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/ByteBufferInputStreamTest.java
index 80c20e1f8..7e8c3870e 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/ByteBufferInputStreamTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/ByteBufferInputStreamTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -15,23 +15,26 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
package org.apache.zookeeper.server;
+import static org.junit.Assert.assertArrayEquals;
+import static org.junit.Assert.assertEquals;
import java.nio.ByteBuffer;
-import java.nio.charset.Charset;
+import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import org.apache.zookeeper.ZKTestCase;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
-import static org.junit.Assert.*;
public class ByteBufferInputStreamTest extends ZKTestCase {
- private static final byte[] DATA_BYTES_0 =
- "Apache ZooKeeper".getBytes(Charset.forName("UTF-8"));
+
+ private static final byte[] DATA_BYTES_0 = "Apache ZooKeeper".getBytes(StandardCharsets.UTF_8);
private static byte[] DATA_BYTES;
- @BeforeClass public static void setUpClass() {
+ @BeforeClass
+ public static void setUpClass() {
int len = DATA_BYTES_0.length + 2;
DATA_BYTES = new byte[len];
System.arraycopy(DATA_BYTES_0, 0, DATA_BYTES, 0, DATA_BYTES_0.length);
@@ -42,42 +45,42 @@ public class ByteBufferInputStreamTest extends ZKTestCase {
private ByteBuffer bb;
private ByteBufferInputStream in;
private byte[] bs;
- @Before public void setUp() throws Exception {
+ @Before
+ public void setUp() throws Exception {
bb = ByteBuffer.wrap(DATA_BYTES);
in = new ByteBufferInputStream(bb);
- bs = new byte[] { (byte) 1, (byte) 2, (byte) 3, (byte) 4 };
+ bs = new byte[]{(byte) 1, (byte) 2, (byte) 3, (byte) 4};
}
- @Test public void testRead() throws Exception {
+ @Test
+ public void testRead() throws Exception {
for (int i = 0; i < DATA_BYTES.length; i++) {
int b = in.read();
assertEquals(DATA_BYTES[i], (byte) b);
}
assertEquals(-1, in.read());
}
- @Test public void testReadArrayOffsetLength() throws Exception {
+ @Test
+ public void testReadArrayOffsetLength() throws Exception {
assertEquals(1, in.read(bs, 2, 1));
- byte[] expected =
- new byte[] { (byte) 1, (byte) 2, DATA_BYTES[0], (byte) 4 };
+ byte[] expected = new byte[]{(byte) 1, (byte) 2, DATA_BYTES[0], (byte) 4};
assertArrayEquals(expected, bs);
}
- @Test(expected=IndexOutOfBoundsException.class)
+ @Test(expected = IndexOutOfBoundsException.class)
public void testReadArrayOffsetLength_LengthTooLarge() throws Exception {
in.read(bs, 2, 3);
}
- @Test public void testReadArrayOffsetLength_HitEndOfStream()
- throws Exception {
+ @Test
+ public void testReadArrayOffsetLength_HitEndOfStream() throws Exception {
for (int i = 0; i < DATA_BYTES.length - 1; i++) {
in.read();
}
assertEquals(1, in.read(bs, 2, 2));
- byte[] expected =
- new byte[] { (byte) 1, (byte) 2, DATA_BYTES[DATA_BYTES.length - 1],
- (byte) 4 };
+ byte[] expected = new byte[]{(byte) 1, (byte) 2, DATA_BYTES[DATA_BYTES.length - 1], (byte) 4};
assertArrayEquals(expected, bs);
}
- @Test public void testReadArrayOffsetLength_AtEndOfStream()
- throws Exception {
+ @Test
+ public void testReadArrayOffsetLength_AtEndOfStream() throws Exception {
for (int i = 0; i < DATA_BYTES.length; i++) {
in.read();
}
@@ -85,24 +88,28 @@ public class ByteBufferInputStreamTest extends ZKTestCase {
assertEquals(-1, in.read(bs, 2, 2));
assertArrayEquals(expected, bs);
}
- @Test public void testReadArrayOffsetLength_0Length() throws Exception {
+ @Test
+ public void testReadArrayOffsetLength_0Length() throws Exception {
byte[] expected = Arrays.copyOf(bs, bs.length);
assertEquals(0, in.read(bs, 2, 0));
assertArrayEquals(expected, bs);
}
- @Test public void testReadArray() throws Exception {
+ @Test
+ public void testReadArray() throws Exception {
byte[] expected = Arrays.copyOf(DATA_BYTES, 4);
assertEquals(4, in.read(bs));
assertArrayEquals(expected, bs);
}
- @Test public void testSkip() throws Exception {
+ @Test
+ public void testSkip() throws Exception {
in.read();
assertEquals(2L, in.skip(2L));
assertEquals(DATA_BYTES[3], in.read());
assertEquals(DATA_BYTES[4], in.read());
}
- @Test public void testSkip2() throws Exception {
+ @Test
+ public void testSkip2() throws Exception {
for (int i = 0; i < DATA_BYTES.length / 2; i++) {
in.read();
}
@@ -112,20 +119,23 @@ public class ByteBufferInputStreamTest extends ZKTestCase {
assertEquals(DATA_BYTES[idx++], in.read());
assertEquals(DATA_BYTES[idx++], in.read());
}
- @Test public void testNegativeSkip() throws Exception {
+ @Test
+ public void testNegativeSkip() throws Exception {
in.read();
assertEquals(0L, in.skip(-2L));
assertEquals(DATA_BYTES[1], in.read());
assertEquals(DATA_BYTES[2], in.read());
}
- @Test public void testSkip_HitEnd() throws Exception {
- for (int i = 0; i < DATA_BYTES.length - 1; i++) {
+ @Test
+ public void testSkip_HitEnd() throws Exception {
+ for (int i = 0; i < DATA_BYTES.length - 1; i++) {
in.read();
}
assertEquals(1L, in.skip(2L));
assertEquals(-1, in.read());
}
- @Test public void testSkip_AtEnd() throws Exception {
+ @Test
+ public void testSkip_AtEnd() throws Exception {
for (int i = 0; i < DATA_BYTES.length; i++) {
in.read();
}
@@ -133,11 +143,13 @@ public class ByteBufferInputStreamTest extends ZKTestCase {
assertEquals(-1, in.read());
}
- @Test public void testAvailable() throws Exception {
+ @Test
+ public void testAvailable() throws Exception {
for (int i = DATA_BYTES.length; i > 0; i--) {
assertEquals(i, in.available());
in.read();
}
assertEquals(0, in.available());
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/CRCTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/CRCTest.java
index da4ebaffc..bc8840729 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/CRCTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/CRCTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -19,7 +19,7 @@
package org.apache.zookeeper.server;
import static org.apache.zookeeper.test.ClientBase.CONNECTION_TIMEOUT;
-
+import static org.junit.Assert.assertTrue;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
@@ -31,7 +31,6 @@ import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.zip.Adler32;
import java.util.zip.CheckedInputStream;
-
import org.apache.jute.BinaryInputArchive;
import org.apache.jute.InputArchive;
import org.apache.zookeeper.CreateMode;
@@ -43,16 +42,15 @@ import org.apache.zookeeper.server.persistence.FileSnap;
import org.apache.zookeeper.server.persistence.FileTxnLog;
import org.apache.zookeeper.server.persistence.TxnLog.TxnIterator;
import org.apache.zookeeper.test.ClientBase;
-import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-public class CRCTest extends ZKTestCase{
+public class CRCTest extends ZKTestCase {
+
private static final Logger LOG = LoggerFactory.getLogger(CRCTest.class);
- private static final String HOSTPORT =
- "127.0.0.1:" + PortAssignment.unique();
+ private static final String HOSTPORT = "127.0.0.1:" + PortAssignment.unique();
/**
* corrupt a file by writing m at 500 b
* offset
@@ -61,7 +59,7 @@ public class CRCTest extends ZKTestCase{
*/
private void corruptFile(File file) throws IOException {
// corrupt the logfile
- RandomAccessFile raf = new RandomAccessFile(file, "rw");
+ RandomAccessFile raf = new RandomAccessFile(file, "rw");
byte[] b = "mahadev".getBytes();
long writeLen = 500L;
raf.seek(writeLen);
@@ -74,8 +72,7 @@ public class CRCTest extends ZKTestCase{
private boolean getCheckSum(FileSnap snap, File snapFile) throws IOException {
DataTree dt = new DataTree();
Map<Long, Integer> sessions = new ConcurrentHashMap<Long, Integer>();
- InputStream snapIS = new BufferedInputStream(new FileInputStream(
- snapFile));
+ InputStream snapIS = new BufferedInputStream(new FileInputStream(snapFile));
CheckedInputStream crcIn = new CheckedInputStream(snapIS, new Adler32());
InputArchive ia = BinaryInputArchive.getArchive(crcIn);
try {
@@ -113,22 +110,18 @@ public class CRCTest extends ZKTestCase{
ServerCnxnFactory f = ServerCnxnFactory.createFactory(PORT, -1);
f.startup(zks);
LOG.info("starting up the zookeeper server .. waiting");
- Assert.assertTrue("waiting for server being up",
- ClientBase.waitForServerUp(HOSTPORT,CONNECTION_TIMEOUT));
+ assertTrue("waiting for server being up", ClientBase.waitForServerUp(HOSTPORT, CONNECTION_TIMEOUT));
ZooKeeper zk = ClientBase.createZKClient(HOSTPORT);
try {
- for (int i =0; i < 2000; i++) {
- zk.create("/crctest- " + i , ("/crctest- " + i).getBytes(),
- Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
+ for (int i = 0; i < 2000; i++) {
+ zk.create("/crctest- " + i, ("/crctest- " + i).getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
}
} finally {
zk.close();
}
f.shutdown();
zks.shutdown();
- Assert.assertTrue("waiting for server down",
- ClientBase.waitForServerDown(HOSTPORT,
- ClientBase.CONNECTION_TIMEOUT));
+ assertTrue("waiting for server down", ClientBase.waitForServerDown(HOSTPORT, ClientBase.CONNECTION_TIMEOUT));
File versionDir = new File(tmpDir, "version-2");
File[] list = versionDir.listFiles();
@@ -136,7 +129,7 @@ public class CRCTest extends ZKTestCase{
// one the snapshot and the other logFile
File snapFile = null;
File logFile = null;
- for (File file: list) {
+ for (File file : list) {
LOG.info("file is " + file);
if (file.getName().startsWith("log")) {
logFile = file;
@@ -149,8 +142,8 @@ public class CRCTest extends ZKTestCase{
try {
while (itr.next()) {
}
- Assert.assertTrue(false);
- } catch(IOException ie) {
+ assertTrue(false);
+ } catch (IOException ie) {
LOG.info("crc corruption", ie);
}
itr.close();
@@ -162,7 +155,7 @@ public class CRCTest extends ZKTestCase{
boolean cfile = false;
try {
cfile = getCheckSum(snap, snapFile);
- } catch(IOException ie) {
+ } catch (IOException ie) {
//the last snapshot seems incompelte
// corrupt the last but one
// and use that
@@ -170,6 +163,7 @@ public class CRCTest extends ZKTestCase{
corruptFile(snapFile);
cfile = getCheckSum(snap, snapFile);
}
- Assert.assertTrue(cfile);
- }
+ assertTrue(cfile);
+ }
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/ConnectionMetricsTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/ConnectionMetricsTest.java
index 47d406f3c..2b10f9be1 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/ConnectionMetricsTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/ConnectionMetricsTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,19 +18,13 @@
package org.apache.zookeeper.server;
+import static org.apache.zookeeper.server.NIOServerCnxnFactory.ZOOKEEPER_NIO_SESSIONLESS_CNXN_TIMEOUT;
+import static org.junit.Assert.assertEquals;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
import io.netty.channel.Channel;
import io.netty.channel.EventLoop;
-import org.apache.zookeeper.PortAssignment;
-import org.apache.zookeeper.ZKTestCase;
-import org.apache.zookeeper.ZooKeeper;
-import org.apache.zookeeper.metrics.MetricsUtils;
-import org.apache.zookeeper.test.ClientBase;
-import org.apache.zookeeper.test.QuorumUtil;
-import org.junit.Assert;
-import org.junit.Test;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
@@ -41,25 +35,30 @@ import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
-
-import static org.apache.zookeeper.server.NIOServerCnxnFactory.ZOOKEEPER_NIO_SESSIONLESS_CNXN_TIMEOUT;
-import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.when;
+import org.apache.zookeeper.PortAssignment;
+import org.apache.zookeeper.ZKTestCase;
+import org.apache.zookeeper.ZooKeeper;
+import org.apache.zookeeper.metrics.MetricsUtils;
+import org.apache.zookeeper.test.ClientBase;
+import org.apache.zookeeper.test.QuorumUtil;
+import org.junit.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
public class ConnectionMetricsTest extends ZKTestCase {
+
protected static final Logger LOG = LoggerFactory.getLogger(ConnectionMetricsTest.class);
@Test
- public void testRevalidateCount() throws Exception {
+ public void testRevalidateCount() throws Exception {
ServerMetrics.getMetrics().resetAll();
QuorumUtil util = new QuorumUtil(1); // create a quorum of 3 servers
// disable local session to make sure we create a global session
util.enableLocalSession(false);
util.startAll();
- int follower1 = (int)util.getFollowerQuorumPeers().get(0).getId();
- int follower2 = (int)util.getFollowerQuorumPeers().get(1).getId();
+ int follower1 = (int) util.getFollowerQuorumPeers().get(0).getId();
+ int follower2 = (int) util.getFollowerQuorumPeers().get(1).getId();
LOG.info("connecting to server: {}", follower1);
ClientBase.CountdownWatcher watcher = new ClientBase.CountdownWatcher();
// create a connection to follower
@@ -79,18 +78,16 @@ public class ConnectionMetricsTest extends ZKTestCase {
LOG.info("reconnected");
Map<String, Object> values = MetricsUtils.currentServerMetrics();
- Assert.assertEquals(1L, values.get("connection_revalidate_count"));
- Assert.assertEquals(1L, values.get("revalidate_count"));
+ assertEquals(1L, values.get("connection_revalidate_count"));
+ assertEquals(1L, values.get("revalidate_count"));
zk.close();
util.shutdownAll();
}
+ private class MockNIOServerCnxn extends NIOServerCnxn {
- private class MockNIOServerCnxn extends NIOServerCnxn {
- public MockNIOServerCnxn(ZooKeeperServer zk, SocketChannel sock,
- SelectionKey sk, NIOServerCnxnFactory factory,
- NIOServerCnxnFactory.SelectorThread selectorThread) throws IOException {
+ public MockNIOServerCnxn(ZooKeeperServer zk, SocketChannel sock, SelectionKey sk, NIOServerCnxnFactory factory, NIOServerCnxnFactory.SelectorThread selectorThread) throws IOException {
super(zk, sock, sk, factory, selectorThread);
}
@@ -98,6 +95,7 @@ public class ConnectionMetricsTest extends ZKTestCase {
protected boolean isSocketOpen() {
return true;
}
+
}
private static class FakeSK extends SelectionKey {
@@ -160,7 +158,7 @@ public class ConnectionMetricsTest extends ZKTestCase {
cnxn.doIO(new FakeSK());
Map<String, Object> values = MetricsUtils.currentServerMetrics();
- Assert.assertEquals(1L, values.get("connection_drop_count"));
+ assertEquals(1L, values.get("connection_drop_count"));
}
@Test
@@ -182,7 +180,7 @@ public class ConnectionMetricsTest extends ZKTestCase {
cnxn.close();
Map<String, Object> values = MetricsUtils.currentServerMetrics();
- Assert.assertEquals(1L, values.get("connection_drop_count"));
+ assertEquals(1L, values.get("connection_drop_count"));
}
@Test
@@ -190,8 +188,7 @@ public class ConnectionMetricsTest extends ZKTestCase {
ServerCnxnFactory factory = new NIOServerCnxnFactory();
factory.configure(new InetSocketAddress(PortAssignment.unique()), 1000);
factory.start();
- int timeout = Integer.getInteger(
- ZOOKEEPER_NIO_SESSIONLESS_CNXN_TIMEOUT, 10000);
+ int timeout = Integer.getInteger(ZOOKEEPER_NIO_SESSIONLESS_CNXN_TIMEOUT, 10000);
ServerMetrics.getMetrics().resetAll();
// add two connections w/o touching them so they will expire
@@ -200,13 +197,13 @@ public class ConnectionMetricsTest extends ZKTestCase {
Map<String, Object> values = MetricsUtils.currentServerMetrics();
int sleptTime = 0;
- while (values.get("sessionless_connections_expired") == null || sleptTime < 2*timeout){
+ while (values.get("sessionless_connections_expired") == null || sleptTime < 2 * timeout) {
Thread.sleep(100);
sleptTime += 100;
values = MetricsUtils.currentServerMetrics();
}
- Assert.assertEquals(2L, values.get("sessionless_connections_expired"));
+ assertEquals(2L, values.get("sessionless_connections_expired"));
factory.shutdown();
}
@@ -214,8 +211,7 @@ public class ConnectionMetricsTest extends ZKTestCase {
@Test
public void testStaleSessionsExpired() throws Exception {
int tickTime = 1000;
- SessionTrackerImpl tracker = new SessionTrackerImpl(mock(ZooKeeperServer.class),
- new ConcurrentHashMap<>(), tickTime, 1L, null);
+ SessionTrackerImpl tracker = new SessionTrackerImpl(mock(ZooKeeperServer.class), new ConcurrentHashMap<>(), tickTime, 1L, null);
tracker.sessionsById.put(1L, mock(SessionTrackerImpl.SessionImpl.class));
tracker.sessionsById.put(2L, mock(SessionTrackerImpl.SessionImpl.class));
@@ -229,14 +225,15 @@ public class ConnectionMetricsTest extends ZKTestCase {
Map<String, Object> values = MetricsUtils.currentServerMetrics();
int sleptTime = 0;
- while (values.get("stale_sessions_expired") == null || sleptTime < 2*tickTime) {
+ while (values.get("stale_sessions_expired") == null || sleptTime < 2 * tickTime) {
Thread.sleep(100);
sleptTime += 100;
values = MetricsUtils.currentServerMetrics();
}
- Assert.assertEquals(2L, values.get("stale_sessions_expired"));
+ assertEquals(2L, values.get("stale_sessions_expired"));
tracker.shutdown();
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/CreateContainerTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/CreateContainerTest.java
index 4889684f7..83c7f0b3d 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/CreateContainerTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/CreateContainerTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,18 +18,32 @@
package org.apache.zookeeper.server;
-import org.apache.zookeeper.*;
-import org.apache.zookeeper.data.Stat;
-import org.apache.zookeeper.test.ClientBase;
-import org.junit.Assert;
-import org.junit.Test;
-
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
-import java.util.concurrent.*;
+import java.util.concurrent.BlockingQueue;
+import java.util.concurrent.Callable;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.Executors;
+import java.util.concurrent.LinkedBlockingQueue;
+import java.util.concurrent.TimeUnit;
+import org.apache.zookeeper.AsyncCallback;
+import org.apache.zookeeper.CreateMode;
+import org.apache.zookeeper.KeeperException;
+import org.apache.zookeeper.Op;
+import org.apache.zookeeper.ZooDefs;
+import org.apache.zookeeper.ZooKeeper;
+import org.apache.zookeeper.data.Stat;
+import org.apache.zookeeper.test.ClientBase;
+import org.junit.Test;
public class CreateContainerTest extends ClientBase {
+
private ZooKeeper zk;
@Override
@@ -45,89 +59,76 @@ public class CreateContainerTest extends ClientBase {
}
@Test(timeout = 30000)
- public void testCreate()
- throws KeeperException, InterruptedException {
+ public void testCreate() throws KeeperException, InterruptedException {
createNoStatVerifyResult("/foo");
createNoStatVerifyResult("/foo/child");
}
@Test(timeout = 30000)
- public void testCreateWithStat()
- throws KeeperException, InterruptedException {
+ public void testCreateWithStat() throws KeeperException, InterruptedException {
Stat stat = createWithStatVerifyResult("/foo");
Stat childStat = createWithStatVerifyResult("/foo/child");
// Don't expect to get the same stats for different creates.
- Assert.assertFalse(stat.equals(childStat));
+ assertFalse(stat.equals(childStat));
}
@SuppressWarnings("ConstantConditions")
@Test(timeout = 30000)
- public void testCreateWithNullStat()
- throws KeeperException, InterruptedException {
+ public void testCreateWithNullStat() throws KeeperException, InterruptedException {
final String name = "/foo";
- Assert.assertNull(zk.exists(name, false));
+ assertNull(zk.exists(name, false));
Stat stat = null;
// If a null Stat object is passed the create should still
// succeed, but no Stat info will be returned.
zk.create(name, name.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.CONTAINER, stat);
- Assert.assertNull(stat);
- Assert.assertNotNull(zk.exists(name, false));
+ assertNull(stat);
+ assertNotNull(zk.exists(name, false));
}
@Test(timeout = 30000)
- public void testSimpleDeletion()
- throws KeeperException, InterruptedException {
+ public void testSimpleDeletion() throws KeeperException, InterruptedException {
zk.create("/foo", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.CONTAINER);
zk.create("/foo/bar", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
zk.delete("/foo/bar", -1); // should cause "/foo" to get deleted when checkContainers() is called
- ContainerManager containerManager = new ContainerManager(serverFactory.getZooKeeperServer()
- .getZKDatabase(), serverFactory.getZooKeeperServer().firstProcessor, 1, 100);
+ ContainerManager containerManager = new ContainerManager(serverFactory.getZooKeeperServer().getZKDatabase(), serverFactory.getZooKeeperServer().firstProcessor, 1, 100);
containerManager.checkContainers();
Thread.sleep(1000);
- Assert.assertNull("Container should have been deleted", zk.exists("/foo", false));
+ assertNull("Container should have been deleted", zk.exists("/foo", false));
}
@Test(timeout = 30000)
- public void testMultiWithContainerSimple()
- throws KeeperException, InterruptedException {
- Op createContainer = Op.create("/foo", new byte[0],
- ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.CONTAINER);
+ public void testMultiWithContainerSimple() throws KeeperException, InterruptedException {
+ Op createContainer = Op.create("/foo", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.CONTAINER);
zk.multi(Collections.singletonList(createContainer));
DataTree dataTree = serverFactory.getZooKeeperServer().getZKDatabase().getDataTree();
- Assert.assertEquals(dataTree.getContainers().size(), 1);
+ assertEquals(dataTree.getContainers().size(), 1);
}
@Test(timeout = 30000)
- public void testMultiWithContainer()
- throws KeeperException, InterruptedException {
- Op createContainer = Op.create("/foo", new byte[0],
- ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.CONTAINER);
- Op createChild = Op.create("/foo/bar", new byte[0],
- ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
+ public void testMultiWithContainer() throws KeeperException, InterruptedException {
+ Op createContainer = Op.create("/foo", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.CONTAINER);
+ Op createChild = Op.create("/foo/bar", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
zk.multi(Arrays.asList(createContainer, createChild));
DataTree dataTree = serverFactory.getZooKeeperServer().getZKDatabase().getDataTree();
- Assert.assertEquals(dataTree.getContainers().size(), 1);
+ assertEquals(dataTree.getContainers().size(), 1);
zk.delete("/foo/bar", -1); // should cause "/foo" to get deleted when checkContainers() is called
- ContainerManager containerManager = new ContainerManager(serverFactory.getZooKeeperServer()
- .getZKDatabase(), serverFactory.getZooKeeperServer().firstProcessor, 1, 100);
+ ContainerManager containerManager = new ContainerManager(serverFactory.getZooKeeperServer().getZKDatabase(), serverFactory.getZooKeeperServer().firstProcessor, 1, 100);
containerManager.checkContainers();
Thread.sleep(1000);
- Assert.assertNull("Container should have been deleted", zk.exists("/foo", false));
+ assertNull("Container should have been deleted", zk.exists("/foo", false));
- createContainer = Op.create("/foo", new byte[0],
- ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.CONTAINER);
- createChild = Op.create("/foo/bar", new byte[0],
- ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
+ createContainer = Op.create("/foo", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.CONTAINER);
+ createChild = Op.create("/foo/bar", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
Op deleteChild = Op.delete("/foo/bar", -1);
zk.multi(Arrays.asList(createContainer, createChild, deleteChild));
@@ -135,62 +136,55 @@ public class CreateContainerTest extends ClientBase {
Thread.sleep(1000);
- Assert.assertNull("Container should have been deleted", zk.exists("/foo", false));
+ assertNull("Container should have been deleted", zk.exists("/foo", false));
}
@Test(timeout = 30000)
- public void testSimpleDeletionAsync()
- throws KeeperException, InterruptedException {
+ public void testSimpleDeletionAsync() throws KeeperException, InterruptedException {
final CountDownLatch latch = new CountDownLatch(1);
AsyncCallback.Create2Callback cb = new AsyncCallback.Create2Callback() {
@Override
public void processResult(int rc, String path, Object ctx, String name, Stat stat) {
- Assert.assertEquals(ctx, "context");
+ assertEquals(ctx, "context");
latch.countDown();
}
};
zk.create("/foo", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.CONTAINER, cb, "context");
- Assert.assertTrue(latch.await(5, TimeUnit.SECONDS));
+ assertTrue(latch.await(5, TimeUnit.SECONDS));
zk.create("/foo/bar", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
zk.delete("/foo/bar", -1); // should cause "/foo" to get deleted when checkContainers() is called
- ContainerManager containerManager = new ContainerManager(serverFactory.getZooKeeperServer()
- .getZKDatabase(), serverFactory.getZooKeeperServer().firstProcessor, 1, 100);
+ ContainerManager containerManager = new ContainerManager(serverFactory.getZooKeeperServer().getZKDatabase(), serverFactory.getZooKeeperServer().firstProcessor, 1, 100);
containerManager.checkContainers();
Thread.sleep(1000);
- Assert.assertNull("Container should have been deleted", zk.exists("/foo", false));
+ assertNull("Container should have been deleted", zk.exists("/foo", false));
}
@Test(timeout = 30000)
- public void testCascadingDeletion()
- throws KeeperException, InterruptedException {
+ public void testCascadingDeletion() throws KeeperException, InterruptedException {
zk.create("/foo", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.CONTAINER);
zk.create("/foo/bar", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.CONTAINER);
zk.create("/foo/bar/one", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
zk.delete("/foo/bar/one", -1); // should cause "/foo/bar" and "/foo" to get deleted when checkContainers() is called
- ContainerManager containerManager = new ContainerManager(serverFactory.getZooKeeperServer()
- .getZKDatabase(), serverFactory.getZooKeeperServer().firstProcessor, 1, 100);
+ ContainerManager containerManager = new ContainerManager(serverFactory.getZooKeeperServer().getZKDatabase(), serverFactory.getZooKeeperServer().firstProcessor, 1, 100);
containerManager.checkContainers();
Thread.sleep(1000);
- containerManager
- .checkContainers();
+ containerManager.checkContainers();
Thread.sleep(1000);
- Assert.assertNull("Container should have been deleted", zk.exists("/foo/bar", false));
- Assert.assertNull("Container should have been deleted", zk.exists("/foo", false));
+ assertNull("Container should have been deleted", zk.exists("/foo/bar", false));
+ assertNull("Container should have been deleted", zk.exists("/foo", false));
}
@Test(timeout = 30000)
- public void testFalseEmpty()
- throws KeeperException, InterruptedException {
+ public void testFalseEmpty() throws KeeperException, InterruptedException {
zk.create("/foo", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.CONTAINER);
zk.create("/foo/bar", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
- ContainerManager containerManager = new ContainerManager(serverFactory.getZooKeeperServer()
- .getZKDatabase(), serverFactory.getZooKeeperServer().firstProcessor, 1, 100) {
+ ContainerManager containerManager = new ContainerManager(serverFactory.getZooKeeperServer().getZKDatabase(), serverFactory.getZooKeeperServer().firstProcessor, 1, 100) {
@Override
protected Collection<String> getCandidates() {
return Collections.singletonList("/foo");
@@ -199,12 +193,11 @@ public class CreateContainerTest extends ClientBase {
containerManager.checkContainers();
Thread.sleep(1000);
- Assert.assertNotNull("Container should have not been deleted", zk.exists("/foo", false));
+ assertNotNull("Container should have not been deleted", zk.exists("/foo", false));
}
@Test(timeout = 30000)
- public void testMaxPerMinute()
- throws InterruptedException {
+ public void testMaxPerMinute() throws InterruptedException {
final BlockingQueue<String> queue = new LinkedBlockingQueue<String>();
RequestProcessor processor = new RequestProcessor() {
@Override
@@ -216,8 +209,7 @@ public class CreateContainerTest extends ClientBase {
public void shutdown() {
}
};
- final ContainerManager containerManager = new ContainerManager(serverFactory.getZooKeeperServer()
- .getZKDatabase(), processor, 1, 2) {
+ final ContainerManager containerManager = new ContainerManager(serverFactory.getZooKeeperServer().getZKDatabase(), processor, 1, 2) {
@Override
protected long getMinIntervalMs() {
return 1000;
@@ -235,47 +227,45 @@ public class CreateContainerTest extends ClientBase {
return null;
}
});
- Assert.assertEquals(queue.poll(5, TimeUnit.SECONDS), "/one");
- Assert.assertEquals(queue.poll(5, TimeUnit.SECONDS), "/two");
- Assert.assertEquals(queue.size(), 0);
+ assertEquals(queue.poll(5, TimeUnit.SECONDS), "/one");
+ assertEquals(queue.poll(5, TimeUnit.SECONDS), "/two");
+ assertEquals(queue.size(), 0);
Thread.sleep(500);
- Assert.assertEquals(queue.size(), 0);
+ assertEquals(queue.size(), 0);
- Assert.assertEquals(queue.poll(5, TimeUnit.SECONDS), "/three");
- Assert.assertEquals(queue.poll(5, TimeUnit.SECONDS), "/four");
+ assertEquals(queue.poll(5, TimeUnit.SECONDS), "/three");
+ assertEquals(queue.poll(5, TimeUnit.SECONDS), "/four");
}
- private void createNoStatVerifyResult(String newName)
- throws KeeperException, InterruptedException {
- Assert.assertNull("Node existed before created", zk.exists(newName, false));
+ private void createNoStatVerifyResult(String newName) throws KeeperException, InterruptedException {
+ assertNull("Node existed before created", zk.exists(newName, false));
zk.create(newName, newName.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.CONTAINER);
- Assert.assertNotNull("Node was not created as expected",
- zk.exists(newName, false));
+ assertNotNull("Node was not created as expected", zk.exists(newName, false));
}
- private Stat createWithStatVerifyResult(String newName)
- throws KeeperException, InterruptedException {
- Assert.assertNull("Node existed before created", zk.exists(newName, false));
+ private Stat createWithStatVerifyResult(String newName) throws KeeperException, InterruptedException {
+ assertNull("Node existed before created", zk.exists(newName, false));
Stat stat = new Stat();
zk.create(newName, newName.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.CONTAINER, stat);
validateCreateStat(stat, newName);
Stat referenceStat = zk.exists(newName, false);
- Assert.assertNotNull("Node was not created as expected", referenceStat);
- Assert.assertEquals(referenceStat, stat);
+ assertNotNull("Node was not created as expected", referenceStat);
+ assertEquals(referenceStat, stat);
return stat;
}
private void validateCreateStat(Stat stat, String name) {
- Assert.assertEquals(stat.getCzxid(), stat.getMzxid());
- Assert.assertEquals(stat.getCzxid(), stat.getPzxid());
- Assert.assertEquals(stat.getCtime(), stat.getMtime());
- Assert.assertEquals(0, stat.getCversion());
- Assert.assertEquals(0, stat.getVersion());
- Assert.assertEquals(0, stat.getAversion());
- Assert.assertEquals(0, stat.getEphemeralOwner());
- Assert.assertEquals(name.length(), stat.getDataLength());
- Assert.assertEquals(0, stat.getNumChildren());
+ assertEquals(stat.getCzxid(), stat.getMzxid());
+ assertEquals(stat.getCzxid(), stat.getPzxid());
+ assertEquals(stat.getCtime(), stat.getMtime());
+ assertEquals(0, stat.getCversion());
+ assertEquals(0, stat.getVersion());
+ assertEquals(0, stat.getAversion());
+ assertEquals(0, stat.getEphemeralOwner());
+ assertEquals(name.length(), stat.getDataLength());
+ assertEquals(0, stat.getNumChildren());
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/CreateTTLTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/CreateTTLTest.java
index 2440030cc..b4c8fa02b 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/CreateTTLTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/CreateTTLTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,6 +18,15 @@
package org.apache.zookeeper.server;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.fail;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.List;
+import java.util.concurrent.atomic.AtomicLong;
import org.apache.zookeeper.AsyncCallback;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
@@ -32,23 +41,19 @@ import org.apache.zookeeper.proto.CreateTTLRequest;
import org.apache.zookeeper.proto.ReplyHeader;
import org.apache.zookeeper.proto.RequestHeader;
import org.apache.zookeeper.test.ClientBase;
-import org.junit.Assert;
import org.junit.Test;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.List;
-import java.util.concurrent.atomic.AtomicLong;
-
public class CreateTTLTest extends ClientBase {
+
private TestableZooKeeper zk;
private static final Collection<String> disabledTests = Collections.singleton("testDisabled");
@Override
public void setUp() throws Exception {
- System.setProperty(EphemeralType.EXTENDED_TYPES_ENABLED_PROPERTY, disabledTests.contains(getTestName()) ? "false" : "true");
+ System.setProperty(
+ EphemeralType.EXTENDED_TYPES_ENABLED_PROPERTY,
+ disabledTests.contains(getTestName()) ? "false" : "true");
super.setUpWithServerId(254);
zk = createClient();
}
@@ -61,20 +66,19 @@ public class CreateTTLTest extends ClientBase {
}
@Test
- public void testCreate()
- throws KeeperException, InterruptedException {
+ public void testCreate() throws KeeperException, InterruptedException {
Stat stat = new Stat();
zk.create("/foo", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_WITH_TTL, stat, 100);
- Assert.assertEquals(0, stat.getEphemeralOwner());
+ assertEquals(0, stat.getEphemeralOwner());
final AtomicLong fakeElapsed = new AtomicLong(0);
ContainerManager containerManager = newContainerManager(fakeElapsed);
containerManager.checkContainers();
- Assert.assertNotNull("Ttl node should not have been deleted yet", zk.exists("/foo", false));
+ assertNotNull("Ttl node should not have been deleted yet", zk.exists("/foo", false));
fakeElapsed.set(1000);
containerManager.checkContainers();
- Assert.assertNull("Ttl node should have been deleted", zk.exists("/foo", false));
+ assertNull("Ttl node should have been deleted", zk.exists("/foo", false));
}
@Test
@@ -82,23 +86,19 @@ public class CreateTTLTest extends ClientBase {
RequestHeader h = new RequestHeader(1, ZooDefs.OpCode.createTTL);
String path = "/bad_ttl";
- CreateTTLRequest request = new CreateTTLRequest(path, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT_WITH_TTL.toFlag(), -100);
+ CreateTTLRequest request = new CreateTTLRequest(path, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_WITH_TTL.toFlag(), -100);
CreateResponse response = new CreateResponse();
ReplyHeader r = zk.submitRequest(h, request, response, null);
- Assert.assertEquals("An invalid CreateTTLRequest should throw BadArguments",
- r.getErr(), Code.BADARGUMENTS.intValue());
- Assert.assertNull("An invalid CreateTTLRequest should not result in znode creation",
- zk.exists(path, false));
+ assertEquals("An invalid CreateTTLRequest should throw BadArguments", r.getErr(), Code.BADARGUMENTS.intValue());
+ assertNull("An invalid CreateTTLRequest should not result in znode creation", zk.exists(path, false));
- request = new CreateTTLRequest(path, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT_WITH_TTL.toFlag(), EphemeralType.TTL.maxValue() + 1);
+ request = new CreateTTLRequest(path, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_WITH_TTL.toFlag(),
+ EphemeralType.TTL.maxValue()
+ + 1);
response = new CreateResponse();
r = zk.submitRequest(h, request, response, null);
- Assert.assertEquals("An invalid CreateTTLRequest should throw BadArguments",
- r.getErr(), Code.BADARGUMENTS.intValue());
- Assert.assertNull("An invalid CreateTTLRequest should not result in znode creation",
- zk.exists(path, false));
+ assertEquals("An invalid CreateTTLRequest should throw BadArguments", r.getErr(), Code.BADARGUMENTS.intValue());
+ assertNull("An invalid CreateTTLRequest should not result in znode creation", zk.exists(path, false));
}
@Test
@@ -106,36 +106,31 @@ public class CreateTTLTest extends ClientBase {
RequestHeader h = new RequestHeader(1, ZooDefs.OpCode.createTTL);
String path = "/bad_ttl";
- CreateTTLRequest request = new CreateTTLRequest(path, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT_WITH_TTL.toFlag(), EphemeralType.TTL.maxValue());
+ CreateTTLRequest request = new CreateTTLRequest(path, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_WITH_TTL.toFlag(), EphemeralType.TTL.maxValue());
CreateResponse response = new CreateResponse();
ReplyHeader r = zk.submitRequest(h, request, response, null);
- Assert.assertEquals("EphemeralType.getMaxTTL() should succeed",
- r.getErr(), Code.OK.intValue());
- Assert.assertNotNull("Node should exist",
- zk.exists(path, false));
+ assertEquals("EphemeralType.getMaxTTL() should succeed", r.getErr(), Code.OK.intValue());
+ assertNotNull("Node should exist", zk.exists(path, false));
}
@Test
- public void testCreateSequential()
- throws KeeperException, InterruptedException {
+ public void testCreateSequential() throws KeeperException, InterruptedException {
Stat stat = new Stat();
String path = zk.create("/foo", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL_WITH_TTL, stat, 100);
- Assert.assertEquals(0, stat.getEphemeralOwner());
+ assertEquals(0, stat.getEphemeralOwner());
final AtomicLong fakeElapsed = new AtomicLong(0);
ContainerManager containerManager = newContainerManager(fakeElapsed);
containerManager.checkContainers();
- Assert.assertNotNull("Ttl node should not have been deleted yet", zk.exists(path, false));
+ assertNotNull("Ttl node should not have been deleted yet", zk.exists(path, false));
fakeElapsed.set(1000);
containerManager.checkContainers();
- Assert.assertNull("Ttl node should have been deleted", zk.exists(path, false));
+ assertNull("Ttl node should have been deleted", zk.exists(path, false));
}
@Test
- public void testCreateAsync()
- throws KeeperException, InterruptedException {
+ public void testCreateAsync() throws KeeperException, InterruptedException {
AsyncCallback.Create2Callback callback = new AsyncCallback.Create2Callback() {
@Override
public void processResult(int rc, String path, Object ctx, String name, Stat stat) {
@@ -147,78 +142,76 @@ public class CreateTTLTest extends ClientBase {
final AtomicLong fakeElapsed = new AtomicLong(0);
ContainerManager containerManager = newContainerManager(fakeElapsed);
containerManager.checkContainers();
- Assert.assertNotNull("Ttl node should not have been deleted yet", zk.exists("/foo", false));
+ assertNotNull("Ttl node should not have been deleted yet", zk.exists("/foo", false));
fakeElapsed.set(1000);
containerManager.checkContainers();
- Assert.assertNull("Ttl node should have been deleted", zk.exists("/foo", false));
+ assertNull("Ttl node should have been deleted", zk.exists("/foo", false));
}
@Test
- public void testModifying()
- throws KeeperException, InterruptedException {
+ public void testModifying() throws KeeperException, InterruptedException {
Stat stat = new Stat();
zk.create("/foo", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_WITH_TTL, stat, 100);
- Assert.assertEquals(0, stat.getEphemeralOwner());
+ assertEquals(0, stat.getEphemeralOwner());
final AtomicLong fakeElapsed = new AtomicLong(0);
ContainerManager containerManager = newContainerManager(fakeElapsed);
containerManager.checkContainers();
- Assert.assertNotNull("Ttl node should not have been deleted yet", zk.exists("/foo", false));
+ assertNotNull("Ttl node should not have been deleted yet", zk.exists("/foo", false));
- for ( int i = 0; i < 10; ++i ) {
+ for (int i = 0; i < 10; ++i) {
fakeElapsed.set(50);
zk.setData("/foo", new byte[i + 1], -1);
containerManager.checkContainers();
- Assert.assertNotNull("Ttl node should not have been deleted yet", zk.exists("/foo", false));
+ assertNotNull("Ttl node should not have been deleted yet", zk.exists("/foo", false));
}
fakeElapsed.set(200);
containerManager.checkContainers();
- Assert.assertNull("Ttl node should have been deleted", zk.exists("/foo", false));
+ assertNull("Ttl node should have been deleted", zk.exists("/foo", false));
}
@Test
- public void testMulti()
- throws KeeperException, InterruptedException {
+ public void testMulti() throws KeeperException, InterruptedException {
Op createTtl = Op.create("/a", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_WITH_TTL, 100);
Op createTtlSequential = Op.create("/b", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL_WITH_TTL, 200);
Op createNonTtl = Op.create("/c", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
List<OpResult> results = zk.multi(Arrays.asList(createTtl, createTtlSequential, createNonTtl));
- String sequentialPath = ((OpResult.CreateResult)results.get(1)).getPath();
+ String sequentialPath = ((OpResult.CreateResult) results.get(1)).getPath();
final AtomicLong fakeElapsed = new AtomicLong(0);
ContainerManager containerManager = newContainerManager(fakeElapsed);
containerManager.checkContainers();
- Assert.assertNotNull("node should not have been deleted yet", zk.exists("/a", false));
- Assert.assertNotNull("node should not have been deleted yet", zk.exists(sequentialPath, false));
- Assert.assertNotNull("node should never be deleted", zk.exists("/c", false));
+ assertNotNull("node should not have been deleted yet", zk.exists("/a", false));
+ assertNotNull("node should not have been deleted yet", zk.exists(sequentialPath, false));
+ assertNotNull("node should never be deleted", zk.exists("/c", false));
fakeElapsed.set(110);
containerManager.checkContainers();
- Assert.assertNull("node should have been deleted", zk.exists("/a", false));
- Assert.assertNotNull("node should not have been deleted yet", zk.exists(sequentialPath, false));
- Assert.assertNotNull("node should never be deleted", zk.exists("/c", false));
+ assertNull("node should have been deleted", zk.exists("/a", false));
+ assertNotNull("node should not have been deleted yet", zk.exists(sequentialPath, false));
+ assertNotNull("node should never be deleted", zk.exists("/c", false));
fakeElapsed.set(210);
containerManager.checkContainers();
- Assert.assertNull("node should have been deleted", zk.exists("/a", false));
- Assert.assertNull("node should have been deleted", zk.exists(sequentialPath, false));
- Assert.assertNotNull("node should never be deleted", zk.exists("/c", false));
+ assertNull("node should have been deleted", zk.exists("/a", false));
+ assertNull("node should have been deleted", zk.exists(sequentialPath, false));
+ assertNotNull("node should never be deleted", zk.exists("/c", false));
}
@Test
public void testBadUsage() throws KeeperException, InterruptedException {
- for ( CreateMode createMode : CreateMode.values() ) {
+ for (CreateMode createMode : CreateMode.values()) {
try {
zk.create("/foo", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, createMode, new Stat(), createMode.isTTL() ? 0 : 100);
- Assert.fail("should have thrown IllegalArgumentException");
+ fail("should have thrown IllegalArgumentException");
} catch (IllegalArgumentException dummy) {
// correct
}
}
- for ( CreateMode createMode : CreateMode.values() ) {
+ for (CreateMode createMode : CreateMode.values()) {
AsyncCallback.Create2Callback callback = new AsyncCallback.Create2Callback() {
@Override
public void processResult(int rc, String path, Object ctx, String name, Stat stat) {
@@ -227,7 +220,7 @@ public class CreateTTLTest extends ClientBase {
};
try {
zk.create("/foo", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, createMode, callback, null, createMode.isTTL() ? 0 : 100);
- Assert.fail("should have thrown IllegalArgumentException");
+ fail("should have thrown IllegalArgumentException");
} catch (IllegalArgumentException dummy) {
// correct
}
@@ -236,14 +229,14 @@ public class CreateTTLTest extends ClientBase {
try {
Op op = Op.create("/foo", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_WITH_TTL, 0);
zk.multi(Collections.singleton(op));
- Assert.fail("should have thrown IllegalArgumentException");
+ fail("should have thrown IllegalArgumentException");
} catch (IllegalArgumentException dummy) {
// correct
}
try {
Op op = Op.create("/foo", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL_WITH_TTL, 0);
zk.multi(Collections.singleton(op));
- Assert.fail("should have thrown IllegalArgumentException");
+ fail("should have thrown IllegalArgumentException");
} catch (IllegalArgumentException dummy) {
// correct
}
@@ -256,12 +249,12 @@ public class CreateTTLTest extends ClientBase {
}
private ContainerManager newContainerManager(final AtomicLong fakeElapsed) {
- return new ContainerManager(serverFactory.getZooKeeperServer()
- .getZKDatabase(), serverFactory.getZooKeeperServer().firstProcessor, 1, 100) {
+ return new ContainerManager(serverFactory.getZooKeeperServer().getZKDatabase(), serverFactory.getZooKeeperServer().firstProcessor, 1, 100) {
@Override
protected long getElapsed(DataNode node) {
return fakeElapsed.get();
}
};
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/DataNodeTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/DataNodeTest.java
index 628976604..0fb6f6864 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/DataNodeTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/DataNodeTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -15,12 +15,13 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package org.apache.zookeeper.server;
-import static org.junit.Assert.*;
+package org.apache.zookeeper.server;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.fail;
import java.util.Set;
-
import org.junit.Test;
public class DataNodeTest {
@@ -62,4 +63,5 @@ public class DataNodeTest {
// do nothing
}
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/DataTreeTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/DataTreeTest.java
index 5c8fb4183..9ca568647 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/DataTreeTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/DataTreeTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,58 +18,57 @@
package org.apache.zookeeper.server;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotEquals;
+import static org.junit.Assert.assertTrue;
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.DataOutputStream;
+import java.io.IOException;
+import java.io.PrintWriter;
+import java.io.StringWriter;
+import java.lang.reflect.Field;
+import java.util.Map;
+import java.util.concurrent.Semaphore;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import org.apache.jute.BinaryInputArchive;
+import org.apache.jute.BinaryOutputArchive;
+import org.apache.jute.Record;
import org.apache.zookeeper.KeeperException.NoNodeException;
import org.apache.zookeeper.KeeperException.NodeExistsException;
+import org.apache.zookeeper.Quotas;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZKTestCase;
import org.apache.zookeeper.ZooDefs;
-import org.apache.zookeeper.data.ACL;
+import org.apache.zookeeper.common.PathTrie;
import org.apache.zookeeper.data.Stat;
+import org.apache.zookeeper.metrics.MetricsUtils;
import org.apache.zookeeper.server.util.DigestCalculator;
import org.apache.zookeeper.txn.CreateTxn;
import org.apache.zookeeper.txn.TxnHeader;
import org.junit.After;
-import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.DataOutputStream;
-import java.io.IOException;
-import java.io.PrintWriter;
-import java.io.StringWriter;
-
-import org.apache.zookeeper.Quotas;
-import org.apache.jute.BinaryInputArchive;
-import org.apache.jute.BinaryOutputArchive;
-import org.apache.jute.Record;
-import org.apache.zookeeper.common.PathTrie;
-import java.lang.reflect.*;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.concurrent.Semaphore;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.atomic.AtomicBoolean;
-import java.util.List;
-import java.util.ArrayList;
-import org.apache.zookeeper.metrics.MetricsUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
public class DataTreeTest extends ZKTestCase {
+
protected static final Logger LOG = LoggerFactory.getLogger(DataTreeTest.class);
private DataTree dt;
@Before
public void setUp() throws Exception {
- dt=new DataTree();
+ dt = new DataTree();
}
@After
public void tearDown() throws Exception {
- dt=null;
+ dt = null;
}
/**
@@ -84,8 +83,7 @@ public class DataTreeTest extends ZKTestCase {
final DataTree dataTree = new DataTree();
LOG.info("Create {} zkclient sessions and its ephemeral nodes", count);
createEphemeralNode(session, dataTree, count);
- final AtomicBoolean exceptionDuringDumpEphemerals = new AtomicBoolean(
- false);
+ final AtomicBoolean exceptionDuringDumpEphemerals = new AtomicBoolean(false);
final AtomicBoolean running = new AtomicBoolean(true);
Thread thread = new Thread() {
public void run() {
@@ -98,47 +96,47 @@ public class DataTreeTest extends ZKTestCase {
LOG.error("Received exception while dumpEphemerals!", e);
exceptionDuringDumpEphemerals.set(true);
}
- };
+ }
};
thread.start();
LOG.debug("Killing {} zkclient sessions and its ephemeral nodes", count);
killZkClientSession(session, zxid, dataTree, count);
running.set(false);
thread.join();
- Assert.assertFalse("Should have got exception while dumpEphemerals!",
- exceptionDuringDumpEphemerals.get());
+ assertFalse("Should have got exception while dumpEphemerals!", exceptionDuringDumpEphemerals.get());
}
- private void killZkClientSession(long session, long zxid,
- final DataTree dataTree, int count) {
+ private void killZkClientSession(long session, long zxid, final DataTree dataTree, int count) {
for (int i = 0; i < count; i++) {
dataTree.killSession(session + i, zxid);
}
}
- private void createEphemeralNode(long session, final DataTree dataTree,
- int count) throws NoNodeException, NodeExistsException {
+ private void createEphemeralNode(long session, final DataTree dataTree, int count) throws NoNodeException, NodeExistsException {
for (int i = 0; i < count; i++) {
- dataTree.createNode("/test" + i, new byte[0], null, session + i,
- dataTree.getNode("/").stat.getCversion() + 1, 1, 1);
+ dataTree.createNode("/test" + i, new byte[0], null, session + i, dataTree.getNode("/").stat.getCversion()
+ + 1, 1, 1);
}
}
@Test(timeout = 60000)
public void testRootWatchTriggered() throws Exception {
- class MyWatcher implements Watcher{
- boolean fired=false;
+ class MyWatcher implements Watcher {
+
+ boolean fired = false;
public void process(WatchedEvent event) {
- if(event.getPath().equals("/"))
- fired=true;
+ if (event.getPath().equals("/")) {
+ fired = true;
+ }
}
+
}
- MyWatcher watcher=new MyWatcher();
+ MyWatcher watcher = new MyWatcher();
// set a watch on the root node
dt.getChildren("/", new Stat(), watcher);
// add a new node, should trigger a watch
- dt.createNode("/xyz", new byte[0], null, 0, dt.getNode("/").stat.getCversion()+1, 1, 1);
- Assert.assertFalse("Root node watch not triggered",!watcher.fired);
+ dt.createNode("/xyz", new byte[0], null, 0, dt.getNode("/").stat.getCversion() + 1, 1, 1);
+ assertFalse("Root node watch not triggered", !watcher.fired);
}
/**
@@ -149,19 +147,24 @@ public class DataTreeTest extends ZKTestCase {
try {
DigestCalculator.setDigestEnabled(true);
DataTree dt = new DataTree();
- dt.createNode("/test", new byte[0], null, 0, dt.getNode("/").stat.getCversion()+1, 1, 1);
+ dt.createNode("/test", new byte[0], null, 0, dt.getNode("/").stat.getCversion() + 1, 1, 1);
DataNode zk = dt.getNode("/test");
int prevCversion = zk.stat.getCversion();
long prevPzxid = zk.stat.getPzxid();
long digestBefore = dt.getTreeDigest();
- dt.setCversionPzxid("/test/", prevCversion + 1, prevPzxid + 1);
+ dt.setCversionPzxid("/test/", prevCversion + 1, prevPzxid + 1);
int newCversion = zk.stat.getCversion();
long newPzxid = zk.stat.getPzxid();
- Assert.assertTrue("<cversion, pzxid> verification failed. Expected: <" +
- (prevCversion + 1) + ", " + (prevPzxid + 1) + ">, found: <" +
- newCversion + ", " + newPzxid + ">",
- (newCversion == prevCversion + 1 && newPzxid == prevPzxid + 1));
- Assert.assertNotEquals(digestBefore, dt.getTreeDigest());
+ assertTrue("<cversion, pzxid> verification failed. Expected: <"
+ + (prevCversion + 1)
+ + ", "
+ + (prevPzxid + 1)
+ + ">, found: <"
+ + newCversion
+ + ", "
+ + newPzxid
+ + ">", (newCversion == prevCversion + 1 && newPzxid == prevPzxid + 1));
+ assertNotEquals(digestBefore, dt.getTreeDigest());
} finally {
DigestCalculator.setDigestEnabled(false);
}
@@ -177,10 +180,15 @@ public class DataTreeTest extends ZKTestCase {
parent = dt.getNode("/");
int newCversion = parent.stat.getCversion();
long newPzxid = parent.stat.getPzxid();
- Assert.assertTrue("<cversion, pzxid> verification failed. Expected: <" +
- currentCversion + ", " + currentPzxid + ">, found: <" +
- newCversion + ", " + newPzxid + ">",
- (newCversion >= currentCversion && newPzxid >= currentPzxid));
+ assertTrue("<cversion, pzxid> verification failed. Expected: <"
+ + currentCversion
+ + ", "
+ + currentPzxid
+ + ">, found: <"
+ + newCversion
+ + ", "
+ + newPzxid
+ + ">", (newCversion >= currentCversion && newPzxid >= currentPzxid));
}
@Test
@@ -195,7 +203,7 @@ public class DataTreeTest extends ZKTestCase {
} catch (NoNodeException e) { /* expected */ }
root = dt.getNode("/");
currentPzxid = root.stat.getPzxid();
- Assert.assertEquals(currentPzxid, zxid);
+ assertEquals(currentPzxid, zxid);
// pzxid not updated with smaller zxid
long prevPzxid = currentPzxid;
@@ -205,24 +213,22 @@ public class DataTreeTest extends ZKTestCase {
} catch (NoNodeException e) { /* expected */ }
root = dt.getNode("/");
currentPzxid = root.stat.getPzxid();
- Assert.assertEquals(currentPzxid, prevPzxid);
+ assertEquals(currentPzxid, prevPzxid);
}
@Test
public void testDigestUpdatedWhenReplayCreateTxnForExistNode() {
try {
DigestCalculator.setDigestEnabled(true);
- dt.processTxn(new TxnHeader(13, 1000, 1, 30, ZooDefs.OpCode.create),
- new CreateTxn("/foo", "".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, false, 1));
+ dt.processTxn(new TxnHeader(13, 1000, 1, 30, ZooDefs.OpCode.create), new CreateTxn("/foo", "".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, false, 1));
// create the same node with a higher cversion to simulate the
// scenario when replaying a create txn for an existing node due
// to fuzzy snapshot
- dt.processTxn(new TxnHeader(13, 1000, 1, 30, ZooDefs.OpCode.create),
- new CreateTxn("/foo", "".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, false, 2));
+ dt.processTxn(new TxnHeader(13, 1000, 1, 30, ZooDefs.OpCode.create), new CreateTxn("/foo", "".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, false, 2));
// check the current digest value
- Assert.assertEquals(dt.getTreeDigest(), dt.getLastProcessedZxidDigest().digest);
+ assertEquals(dt.getTreeDigest(), dt.getLastProcessedZxidDigest().digest);
} finally {
DigestCalculator.setDigestEnabled(false);
}
@@ -235,7 +241,7 @@ public class DataTreeTest extends ZKTestCase {
DataTree dserTree = new DataTree();
dserTree.createNode("/bug", new byte[20], null, -1, 1, 1, 1);
- dserTree.createNode(Quotas.quotaZookeeper+"/bug", null, null, -1, 1, 1, 1);
+ dserTree.createNode(Quotas.quotaZookeeper + "/bug", null, null, -1, 1, 1, 1);
dserTree.createNode(Quotas.quotaPath("/bug"), new byte[20], null, -1, 1, 1, 1);
dserTree.createNode(Quotas.statPath("/bug"), new byte[20], null, -1, 1, 1, 1);
@@ -253,10 +259,10 @@ public class DataTreeTest extends ZKTestCase {
Field pfield = DataTree.class.getDeclaredField("pTrie");
pfield.setAccessible(true);
- PathTrie pTrie = (PathTrie)pfield.get(dserTree);
+ PathTrie pTrie = (PathTrie) pfield.get(dserTree);
//Check that the node path is removed from pTrie
- Assert.assertEquals("/bug is still in pTrie", "/", pTrie.findMaxPrefix("/bug"));
+ assertEquals("/bug is still in pTrie", "/", pTrie.findMaxPrefix("/bug"));
}
/*
@@ -270,7 +276,7 @@ public class DataTreeTest extends ZKTestCase {
@Test(timeout = 60000)
public void testSerializeDoesntLockDataNodeWhileWriting() throws Exception {
DataTree tree = new DataTree();
- tree.createNode("/marker", new byte[] {42}, null, -1, 1, 1, 1);
+ tree.createNode("/marker", new byte[]{42}, null, -1, 1, 1, 1);
final DataNode markerNode = tree.getNode("/marker");
final AtomicBoolean ranTestCase = new AtomicBoolean();
DataOutputStream out = new DataOutputStream(new ByteArrayOutputStream());
@@ -297,7 +303,7 @@ public class DataTreeTest extends ZKTestCase {
boolean acquired = semaphore.tryAcquire(30, TimeUnit.SECONDS);
//This is the real assertion - could another thread lock
//the DataNode we're currently writing
- Assert.assertTrue("Couldn't acquire a lock on the DataNode while we were calling tree.serialize", acquired);
+ assertTrue("Couldn't acquire a lock on the DataNode while we were calling tree.serialize", acquired);
} catch (InterruptedException e1) {
throw new RuntimeException(e1);
}
@@ -312,7 +318,7 @@ public class DataTreeTest extends ZKTestCase {
tree.serialize(oa, "test");
//Let's make sure that we hit the code that ran the real assertion above
- Assert.assertTrue("Didn't find the expected node", ranTestCase.get());
+ assertTrue("Didn't find the expected node", ranTestCase.get());
}
@Test(timeout = 60000)
@@ -324,12 +330,10 @@ public class DataTreeTest extends ZKTestCase {
tree.deleteNode(ZooDefs.CONFIG_NODE, 1);
tree.getReferenceCountedAclCache().aclIndex = 0;
- Assert.assertEquals(
- "expected to have 1 acl in acl cache map", 0, tree.aclCacheSize());
+ assertEquals("expected to have 1 acl in acl cache map", 0, tree.aclCacheSize());
// serialize the data with one znode with acl
- tree.createNode(
- "/bug", new byte[20], ZooDefs.Ids.OPEN_ACL_UNSAFE, -1, 1, 1, 1);
+ tree.createNode("/bug", new byte[20], ZooDefs.Ids.OPEN_ACL_UNSAFE, -1, 1, 1, 1);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
BinaryOutputArchive oa = BinaryOutputArchive.getArchive(baos);
@@ -340,41 +344,35 @@ public class DataTreeTest extends ZKTestCase {
BinaryInputArchive ia = BinaryInputArchive.getArchive(bais);
tree.deserialize(ia, "test");
- Assert.assertEquals(
- "expected to have 1 acl in acl cache map", 1, tree.aclCacheSize());
- Assert.assertEquals(
- "expected to have the same acl", ZooDefs.Ids.OPEN_ACL_UNSAFE,
- tree.getACL("/bug", new Stat()));
+ assertEquals("expected to have 1 acl in acl cache map", 1, tree.aclCacheSize());
+ assertEquals("expected to have the same acl", ZooDefs.Ids.OPEN_ACL_UNSAFE, tree.getACL("/bug", new Stat()));
// simulate the upgrading case where the config node will be created
// again after leader election
tree.addConfigNode();
- Assert.assertEquals(
- "expected to have 2 acl in acl cache map", 2, tree.aclCacheSize());
- Assert.assertEquals(
- "expected to have the same acl", ZooDefs.Ids.OPEN_ACL_UNSAFE,
- tree.getACL("/bug", new Stat()));
+ assertEquals("expected to have 2 acl in acl cache map", 2, tree.aclCacheSize());
+ assertEquals("expected to have the same acl", ZooDefs.Ids.OPEN_ACL_UNSAFE, tree.getACL("/bug", new Stat()));
}
@Test
public void testCachedApproximateDataSize() throws Exception {
DataTree dt = new DataTree();
long initialSize = dt.approximateDataSize();
- Assert.assertEquals(dt.cachedApproximateDataSize(), dt.approximateDataSize());
+ assertEquals(dt.cachedApproximateDataSize(), dt.approximateDataSize());
// create a node
dt.createNode("/testApproximateDataSize", new byte[20], null, -1, 1, 1, 1);
dt.createNode("/testApproximateDataSize1", new byte[20], null, -1, 1, 1, 1);
- Assert.assertEquals(dt.cachedApproximateDataSize(), dt.approximateDataSize());
+ assertEquals(dt.cachedApproximateDataSize(), dt.approximateDataSize());
// update data
dt.setData("/testApproximateDataSize1", new byte[32], -1, 1, 1);
- Assert.assertEquals(dt.cachedApproximateDataSize(), dt.approximateDataSize());
+ assertEquals(dt.cachedApproximateDataSize(), dt.approximateDataSize());
// delete a node
dt.deleteNode("/testApproximateDataSize", -1);
- Assert.assertEquals(dt.cachedApproximateDataSize(), dt.approximateDataSize());
+ assertEquals(dt.cachedApproximateDataSize(), dt.approximateDataSize());
}
@Test
@@ -386,18 +384,17 @@ public class DataTreeTest extends ZKTestCase {
dt.createNode("/all_children_test/nodes/node1", new byte[20], null, -1, 1, 1, 1);
dt.createNode("/all_children_test/nodes/node2", new byte[20], null, -1, 1, 1, 1);
dt.createNode("/all_children_test/nodes/node3", new byte[20], null, -1, 1, 1, 1);
- Assert.assertEquals(4, dt.getAllChildrenNumber("/all_children_test"));
- Assert.assertEquals(3, dt.getAllChildrenNumber("/all_children_test/nodes"));
- Assert.assertEquals(0, dt.getAllChildrenNumber("/all_children_test/nodes/node1"));
+ assertEquals(4, dt.getAllChildrenNumber("/all_children_test"));
+ assertEquals(3, dt.getAllChildrenNumber("/all_children_test/nodes"));
+ assertEquals(0, dt.getAllChildrenNumber("/all_children_test/nodes/node1"));
//add these three init nodes:/zookeeper,/zookeeper/quota,/zookeeper/config,so the number is 8.
- Assert.assertEquals( 8, dt.getAllChildrenNumber("/"));
+ assertEquals(8, dt.getAllChildrenNumber("/"));
}
@Test
public void testDataTreeMetrics() throws Exception {
ServerMetrics.getMetrics().resetAll();
-
long readBytes1 = 0;
long readBytes2 = 0;
long writeBytes1 = 0;
@@ -437,18 +434,18 @@ public class DataTreeTest extends ZKTestCase {
readBytes1 += TOP1PATH.length() + CHILD1.length() + CHILD2.length() + DataTree.STAT_OVERHEAD_BYTES;
dt.deleteNode(TOP1PATH, 1);
writeBytes1 += TOP1PATH.length();
-
+
Map<String, Object> values = MetricsUtils.currentServerMetrics();
- System.out.println("values:"+values);
- Assert.assertEquals(writeBytes1, values.get("sum_" + TOP1+ "_write_per_namespace"));
- Assert.assertEquals(5L, values.get("cnt_" + TOP1 + "_write_per_namespace"));
- Assert.assertEquals(writeBytes2, values.get("sum_" + TOP2+ "_write_per_namespace"));
- Assert.assertEquals(1L, values.get("cnt_" + TOP2 + "_write_per_namespace"));
-
- Assert.assertEquals(readBytes1, values.get("sum_" + TOP1+ "_read_per_namespace"));
- Assert.assertEquals(3L, values.get("cnt_" + TOP1 + "_read_per_namespace"));
- Assert.assertEquals(readBytes2, values.get("sum_" + TOP2+ "_read_per_namespace"));
- Assert.assertEquals(1L, values.get("cnt_" + TOP2 + "_read_per_namespace"));
+ System.out.println("values:" + values);
+ assertEquals(writeBytes1, values.get("sum_" + TOP1 + "_write_per_namespace"));
+ assertEquals(5L, values.get("cnt_" + TOP1 + "_write_per_namespace"));
+ assertEquals(writeBytes2, values.get("sum_" + TOP2 + "_write_per_namespace"));
+ assertEquals(1L, values.get("cnt_" + TOP2 + "_write_per_namespace"));
+
+ assertEquals(readBytes1, values.get("sum_" + TOP1 + "_read_per_namespace"));
+ assertEquals(3L, values.get("cnt_" + TOP1 + "_read_per_namespace"));
+ assertEquals(readBytes2, values.get("sum_" + TOP2 + "_read_per_namespace"));
+ assertEquals(1L, values.get("cnt_" + TOP2 + "_read_per_namespace"));
}
/**
@@ -466,31 +463,32 @@ public class DataTreeTest extends ZKTestCase {
// create a node and check the digest is updated
long previousDigest = dt.getTreeDigest();
dt.createNode("/digesttest", new byte[0], null, -1, 1, 1, 1);
- Assert.assertNotEquals(dt.getTreeDigest(), previousDigest);
+ assertNotEquals(dt.getTreeDigest(), previousDigest);
// create a child and check the digest is updated
previousDigest = dt.getTreeDigest();
dt.createNode("/digesttest/1", "1".getBytes(), null, -1, 2, 2, 2);
- Assert.assertNotEquals(dt.getTreeDigest(), previousDigest);
-
+ assertNotEquals(dt.getTreeDigest(), previousDigest);
+
// check the digest is not chhanged when creating the same node
previousDigest = dt.getTreeDigest();
try {
dt.createNode("/digesttest/1", "1".getBytes(), null, -1, 2, 2, 2);
} catch (NodeExistsException e) { /* ignore */ }
- Assert.assertEquals(dt.getTreeDigest(), previousDigest);
+ assertEquals(dt.getTreeDigest(), previousDigest);
- // check digest with updated data
+ // check digest with updated data
previousDigest = dt.getTreeDigest();
dt.setData("/digesttest/1", "2".getBytes(), 3, 3, 3);
- Assert.assertNotEquals(dt.getTreeDigest(), previousDigest);
+ assertNotEquals(dt.getTreeDigest(), previousDigest);
// check digest with deleted node
previousDigest = dt.getTreeDigest();
dt.deleteNode("/digesttest/1", 5);
- Assert.assertNotEquals(dt.getTreeDigest(), previousDigest);
+ assertNotEquals(dt.getTreeDigest(), previousDigest);
} finally {
DigestCalculator.setDigestEnabled(false);
}
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/DatadirCleanupManagerTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/DatadirCleanupManagerTest.java
index 9d93013e1..d8b21850e 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/DatadirCleanupManagerTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/DatadirCleanupManagerTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -21,14 +21,11 @@ package org.apache.zookeeper.server;
import static org.apache.zookeeper.server.DatadirCleanupManager.PurgeTaskStatus.COMPLETED;
import static org.apache.zookeeper.server.DatadirCleanupManager.PurgeTaskStatus.NOT_STARTED;
import static org.apache.zookeeper.server.DatadirCleanupManager.PurgeTaskStatus.STARTED;
-
+import static org.junit.Assert.assertEquals;
import java.io.File;
-
-
import org.apache.zookeeper.ZKTestCase;
import org.apache.zookeeper.test.ClientBase;
import org.junit.After;
-import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
@@ -49,38 +46,30 @@ public class DatadirCleanupManagerTest extends ZKTestCase {
public void testPurgeTask() throws Exception {
purgeMgr = new DatadirCleanupManager(snapDir, dataLogDir, 3, 1);
purgeMgr.start();
- Assert.assertEquals("Data log directory is not set as configured",
- dataLogDir, purgeMgr.getDataLogDir());
- Assert.assertEquals("Snapshot directory is not set as configured",
- snapDir, purgeMgr.getSnapDir());
- Assert.assertEquals("Snapshot retain count is not set as configured",
- 3, purgeMgr.getSnapRetainCount());
- Assert.assertEquals("Purge task is not started", STARTED, purgeMgr.getPurgeTaskStatus());
+ assertEquals("Data log directory is not set as configured", dataLogDir, purgeMgr.getDataLogDir());
+ assertEquals("Snapshot directory is not set as configured", snapDir, purgeMgr.getSnapDir());
+ assertEquals("Snapshot retain count is not set as configured", 3, purgeMgr.getSnapRetainCount());
+ assertEquals("Purge task is not started", STARTED, purgeMgr.getPurgeTaskStatus());
purgeMgr.shutdown();
- Assert.assertEquals("Purge task is still running after shutdown", COMPLETED,
- purgeMgr.getPurgeTaskStatus());
+ assertEquals("Purge task is still running after shutdown", COMPLETED, purgeMgr.getPurgeTaskStatus());
}
@Test
public void testWithZeroPurgeInterval() throws Exception {
purgeMgr = new DatadirCleanupManager(snapDir, dataLogDir, 3, 0);
purgeMgr.start();
- Assert.assertEquals("Purge task is scheduled with zero purge interval", NOT_STARTED,
- purgeMgr.getPurgeTaskStatus());
+ assertEquals("Purge task is scheduled with zero purge interval", NOT_STARTED, purgeMgr.getPurgeTaskStatus());
purgeMgr.shutdown();
- Assert.assertEquals("Purge task is scheduled with zero purge interval", NOT_STARTED,
- purgeMgr.getPurgeTaskStatus());
+ assertEquals("Purge task is scheduled with zero purge interval", NOT_STARTED, purgeMgr.getPurgeTaskStatus());
}
@Test
public void testWithNegativePurgeInterval() throws Exception {
purgeMgr = new DatadirCleanupManager(snapDir, dataLogDir, 3, -1);
purgeMgr.start();
- Assert.assertEquals("Purge task is scheduled with negative purge interval",
- NOT_STARTED, purgeMgr.getPurgeTaskStatus());
+ assertEquals("Purge task is scheduled with negative purge interval", NOT_STARTED, purgeMgr.getPurgeTaskStatus());
purgeMgr.shutdown();
- Assert.assertEquals("Purge task is scheduled with negative purge interval", NOT_STARTED,
- purgeMgr.getPurgeTaskStatus());
+ assertEquals("Purge task is scheduled with negative purge interval", NOT_STARTED, purgeMgr.getPurgeTaskStatus());
}
@After
@@ -89,4 +78,5 @@ public class DatadirCleanupManagerTest extends ZKTestCase {
purgeMgr.shutdown();
}
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/DeserializationPerfTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/DeserializationPerfTest.java
index b9f1df8cc..7b12b8452 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/DeserializationPerfTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/DeserializationPerfTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,24 +18,23 @@
package org.apache.zookeeper.server;
+import static org.junit.Assert.assertEquals;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
-
import org.apache.jute.BinaryInputArchive;
import org.apache.jute.BinaryOutputArchive;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZKTestCase;
-import org.junit.Assert;
import org.junit.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
public class DeserializationPerfTest extends ZKTestCase {
+
protected static final Logger LOG = LoggerFactory.getLogger(DeserializationPerfTest.class);
- private static void deserializeTree(int depth, int width, int len)
- throws InterruptedException, IOException, KeeperException.NodeExistsException, KeeperException.NoNodeException {
+ private static void deserializeTree(int depth, int width, int len) throws InterruptedException, IOException, KeeperException.NodeExistsException, KeeperException.NoNodeException {
BinaryInputArchive ia;
int count;
{
@@ -61,58 +60,59 @@ public class DeserializationPerfTest extends ZKTestCase {
long durationms = (end - start) / 1000000L;
long pernodeus = ((end - start) / 1000L) / count;
- Assert.assertEquals(count, dserTree.getNodeCount());
-
- LOG.info("Deserialized " + count + " nodes in " + durationms
- + " ms (" + pernodeus + "us/node), depth=" + depth + " width="
- + width + " datalen=" + len);
+ assertEquals(count, dserTree.getNodeCount());
+
+ LOG.info("Deserialized "
+ + count
+ + " nodes in "
+ + durationms
+ + " ms ("
+ + pernodeus
+ + "us/node), depth="
+ + depth
+ + " width="
+ + width
+ + " datalen="
+ + len);
}
@Test
- public void testSingleDeserialize() throws
- InterruptedException, IOException, KeeperException.NodeExistsException, KeeperException.NoNodeException {
+ public void testSingleDeserialize() throws InterruptedException, IOException, KeeperException.NodeExistsException, KeeperException.NoNodeException {
deserializeTree(1, 0, 20);
}
@Test
- public void testWideDeserialize() throws
- InterruptedException, IOException, KeeperException.NodeExistsException, KeeperException.NoNodeException {
+ public void testWideDeserialize() throws InterruptedException, IOException, KeeperException.NodeExistsException, KeeperException.NoNodeException {
deserializeTree(2, 10000, 20);
}
@Test
- public void testDeepDeserialize() throws
- InterruptedException, IOException, KeeperException.NodeExistsException, KeeperException.NoNodeException {
+ public void testDeepDeserialize() throws InterruptedException, IOException, KeeperException.NodeExistsException, KeeperException.NoNodeException {
deserializeTree(400, 1, 20);
}
@Test
- public void test10Wide5DeepDeserialize() throws
- InterruptedException, IOException, KeeperException.NodeExistsException, KeeperException.NoNodeException {
+ public void test10Wide5DeepDeserialize() throws InterruptedException, IOException, KeeperException.NodeExistsException, KeeperException.NoNodeException {
deserializeTree(5, 10, 20);
}
@Test
- public void test15Wide5DeepDeserialize() throws
- InterruptedException, IOException, KeeperException.NodeExistsException, KeeperException.NoNodeException {
+ public void test15Wide5DeepDeserialize() throws InterruptedException, IOException, KeeperException.NodeExistsException, KeeperException.NoNodeException {
deserializeTree(5, 15, 20);
}
@Test
- public void test25Wide4DeepDeserialize() throws
- InterruptedException, IOException, KeeperException.NodeExistsException, KeeperException.NoNodeException {
+ public void test25Wide4DeepDeserialize() throws InterruptedException, IOException, KeeperException.NodeExistsException, KeeperException.NoNodeException {
deserializeTree(4, 25, 20);
}
@Test
- public void test40Wide4DeepDeserialize() throws
- InterruptedException, IOException, KeeperException.NodeExistsException, KeeperException.NoNodeException {
+ public void test40Wide4DeepDeserialize() throws InterruptedException, IOException, KeeperException.NodeExistsException, KeeperException.NoNodeException {
deserializeTree(4, 40, 20);
}
@Test
- public void test300Wide3DeepDeserialize() throws
- InterruptedException, IOException, KeeperException.NodeExistsException, KeeperException.NoNodeException {
+ public void test300Wide3DeepDeserialize() throws InterruptedException, IOException, KeeperException.NodeExistsException, KeeperException.NoNodeException {
deserializeTree(3, 300, 20);
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/Emulate353TTLTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/Emulate353TTLTest.java
index 286fe4ed3..7967beb2c 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/Emulate353TTLTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/Emulate353TTLTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,20 +18,22 @@
package org.apache.zookeeper.server;
+import static org.hamcrest.CoreMatchers.equalTo;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertThat;
+import java.util.concurrent.atomic.AtomicLong;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.TestableZooKeeper;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.data.Stat;
import org.apache.zookeeper.test.ClientBase;
-import org.junit.Assert;
import org.junit.Test;
-import java.util.concurrent.atomic.AtomicLong;
-
-import static org.hamcrest.CoreMatchers.equalTo;
-
public class Emulate353TTLTest extends ClientBase {
+
private TestableZooKeeper zk;
@Override
@@ -51,57 +53,55 @@ public class Emulate353TTLTest extends ClientBase {
}
@Test
- public void testCreate()
- throws KeeperException, InterruptedException {
+ public void testCreate() throws KeeperException, InterruptedException {
Stat stat = new Stat();
zk.create("/foo", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_WITH_TTL, stat, 100);
- Assert.assertEquals(0, stat.getEphemeralOwner());
+ assertEquals(0, stat.getEphemeralOwner());
final AtomicLong fakeElapsed = new AtomicLong(0);
ContainerManager containerManager = newContainerManager(fakeElapsed);
containerManager.checkContainers();
- Assert.assertNotNull("Ttl node should not have been deleted yet", zk.exists("/foo", false));
+ assertNotNull("Ttl node should not have been deleted yet", zk.exists("/foo", false));
fakeElapsed.set(1000);
containerManager.checkContainers();
- Assert.assertNull("Ttl node should have been deleted", zk.exists("/foo", false));
+ assertNull("Ttl node should have been deleted", zk.exists("/foo", false));
}
@Test
- public void test353TTL()
- throws KeeperException, InterruptedException {
+ public void test353TTL() throws KeeperException, InterruptedException {
DataTree dataTree = serverFactory.zkServer.getZKDatabase().dataTree;
long ephemeralOwner = EphemeralTypeEmulate353.ttlToEphemeralOwner(100);
- dataTree.createNode("/foo", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, ephemeralOwner,
- dataTree.getNode("/").stat.getCversion()+1, 1, 1);
+ dataTree.createNode("/foo", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, ephemeralOwner, dataTree.getNode("/").stat.getCversion()
+ + 1, 1, 1);
final AtomicLong fakeElapsed = new AtomicLong(0);
ContainerManager containerManager = newContainerManager(fakeElapsed);
containerManager.checkContainers();
- Assert.assertNotNull("Ttl node should not have been deleted yet", zk.exists("/foo", false));
+ assertNotNull("Ttl node should not have been deleted yet", zk.exists("/foo", false));
fakeElapsed.set(1000);
containerManager.checkContainers();
- Assert.assertNull("Ttl node should have been deleted", zk.exists("/foo", false));
+ assertNull("Ttl node should have been deleted", zk.exists("/foo", false));
}
@Test
public void testEphemeralOwner_emulationTTL() {
- Assert.assertThat(EphemeralType.get(-1), equalTo(EphemeralType.TTL));
+ assertThat(EphemeralType.get(-1), equalTo(EphemeralType.TTL));
}
@Test
public void testEphemeralOwner_emulationContainer() {
- Assert.assertThat(EphemeralType.get(EphemeralType.CONTAINER_EPHEMERAL_OWNER), equalTo(EphemeralType.CONTAINER));
+ assertThat(EphemeralType.get(EphemeralType.CONTAINER_EPHEMERAL_OWNER), equalTo(EphemeralType.CONTAINER));
}
private ContainerManager newContainerManager(final AtomicLong fakeElapsed) {
- return new ContainerManager(serverFactory.getZooKeeperServer()
- .getZKDatabase(), serverFactory.getZooKeeperServer().firstProcessor, 1, 100) {
+ return new ContainerManager(serverFactory.getZooKeeperServer().getZKDatabase(), serverFactory.getZooKeeperServer().firstProcessor, 1, 100) {
@Override
protected long getElapsed(DataNode node) {
return fakeElapsed.get();
}
};
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/EphemeralTypeTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/EphemeralTypeTest.java
index 15904d0a9..5021f0f7c 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/EphemeralTypeTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/EphemeralTypeTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,15 +18,17 @@
package org.apache.zookeeper.server;
+import static org.hamcrest.CoreMatchers.equalTo;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertThat;
+import static org.junit.Assert.fail;
import org.apache.zookeeper.CreateMode;
import org.junit.After;
-import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
-import static org.hamcrest.CoreMatchers.equalTo;
-
public class EphemeralTypeTest {
+
@Before
public void setUp() {
System.setProperty(EphemeralType.EXTENDED_TYPES_ENABLED_PROPERTY, "true");
@@ -39,11 +41,11 @@ public class EphemeralTypeTest {
@Test
public void testTtls() {
- long ttls[] = {100, 1, EphemeralType.TTL.maxValue()};
+ long[] ttls = {100, 1, EphemeralType.TTL.maxValue()};
for (long ttl : ttls) {
long ephemeralOwner = EphemeralType.TTL.toEphemeralOwner(ttl);
- Assert.assertEquals(EphemeralType.TTL, EphemeralType.get(ephemeralOwner));
- Assert.assertEquals(ttl, EphemeralType.TTL.getValue(ephemeralOwner));
+ assertEquals(EphemeralType.TTL, EphemeralType.get(ephemeralOwner));
+ assertEquals(ttl, EphemeralType.TTL.getValue(ephemeralOwner));
}
EphemeralType.validateTTL(CreateMode.PERSISTENT_WITH_TTL, 100);
@@ -51,7 +53,7 @@ public class EphemeralTypeTest {
try {
EphemeralType.validateTTL(CreateMode.EPHEMERAL, 100);
- Assert.fail("Should have thrown IllegalArgumentException");
+ fail("Should have thrown IllegalArgumentException");
} catch (IllegalArgumentException dummy) {
// expected
}
@@ -59,25 +61,25 @@ public class EphemeralTypeTest {
@Test
public void testContainerValue() {
- Assert.assertEquals(Long.MIN_VALUE, EphemeralType.CONTAINER_EPHEMERAL_OWNER);
- Assert.assertEquals(EphemeralType.CONTAINER, EphemeralType.get(EphemeralType.CONTAINER_EPHEMERAL_OWNER));
+ assertEquals(Long.MIN_VALUE, EphemeralType.CONTAINER_EPHEMERAL_OWNER);
+ assertEquals(EphemeralType.CONTAINER, EphemeralType.get(EphemeralType.CONTAINER_EPHEMERAL_OWNER));
}
@Test
public void testNonSpecial() {
- Assert.assertEquals(EphemeralType.VOID, EphemeralType.get(0));
- Assert.assertEquals(EphemeralType.NORMAL, EphemeralType.get(1));
- Assert.assertEquals(EphemeralType.NORMAL, EphemeralType.get(Long.MAX_VALUE));
+ assertEquals(EphemeralType.VOID, EphemeralType.get(0));
+ assertEquals(EphemeralType.NORMAL, EphemeralType.get(1));
+ assertEquals(EphemeralType.NORMAL, EphemeralType.get(Long.MAX_VALUE));
}
@Test
public void testServerIds() {
- for ( int i = 0; i <= EphemeralType.MAX_EXTENDED_SERVER_ID; ++i ) {
+ for (int i = 0; i <= EphemeralType.MAX_EXTENDED_SERVER_ID; ++i) {
EphemeralType.validateServerId(i);
}
try {
EphemeralType.validateServerId(EphemeralType.MAX_EXTENDED_SERVER_ID + 1);
- Assert.fail("Should have thrown RuntimeException");
+ fail("Should have thrown RuntimeException");
} catch (RuntimeException e) {
// expected
}
@@ -87,7 +89,7 @@ public class EphemeralTypeTest {
public void testEphemeralOwner_extendedFeature_TTL() {
// 0xff = Extended feature is ON
// 0x0000 = Extended type id TTL (0)
- Assert.assertThat(EphemeralType.get(0xff00000000000000L), equalTo(EphemeralType.TTL));
+ assertThat(EphemeralType.get(0xff00000000000000L), equalTo(EphemeralType.TTL));
}
@Test(expected = IllegalArgumentException.class)
@@ -96,4 +98,5 @@ public class EphemeralTypeTest {
// 0x0001 = Unsupported extended type id (1)
EphemeralType.get(0xff00010000000000L);
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/FinalRequestProcessorTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/FinalRequestProcessorTest.java
index dc56f831b..1d4309f04 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/FinalRequestProcessorTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/FinalRequestProcessorTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,6 +18,21 @@
package org.apache.zookeeper.server;
+import static org.hamcrest.Matchers.equalTo;
+import static org.junit.Assert.assertThat;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
import org.apache.jute.BinaryOutputArchive;
import org.apache.jute.Record;
import org.apache.zookeeper.KeeperException;
@@ -33,24 +48,8 @@ import org.junit.Test;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.nio.ByteBuffer;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-
-import static org.hamcrest.Matchers.equalTo;
-import static org.junit.Assert.assertThat;
-import static org.junit.Assert.assertTrue;
-import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.ArgumentMatchers.anyString;
-import static org.mockito.ArgumentMatchers.eq;
-import static org.mockito.Mockito.doAnswer;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.when;
-
public class FinalRequestProcessorTest {
+
private List<ACL> testACLs = new ArrayList<ACL>();
private final Record[] responseRecord = new Record[1];
private final ReplyHeader[] replyHeaders = new ReplyHeader[1];
@@ -62,11 +61,7 @@ public class FinalRequestProcessorTest {
@Before
public void setUp() throws KeeperException.NoNodeException, IOException {
testACLs.clear();
- testACLs.addAll(Arrays.asList(
- new ACL(ZooDefs.Perms.ALL, new Id("digest", "user:secrethash")),
- new ACL(ZooDefs.Perms.ADMIN, new Id("digest", "adminuser:adminsecret")),
- new ACL(ZooDefs.Perms.READ, new Id("world", "anyone"))
- ));
+ testACLs.addAll(Arrays.asList(new ACL(ZooDefs.Perms.ALL, new Id("digest", "user:secrethash")), new ACL(ZooDefs.Perms.ADMIN, new Id("digest", "adminuser:adminsecret")), new ACL(ZooDefs.Perms.READ, new Id("world", "anyone"))));
ZooKeeperServer zks = new ZooKeeperServer();
ZKDatabase db = mock(ZKDatabase.class);
@@ -167,10 +162,7 @@ public class FinalRequestProcessorTest {
public void testACLDigestHashHiding_OnlyAdmin() {
// Arrange
testACLs.clear();
- testACLs.addAll(Arrays.asList(
- new ACL(ZooDefs.Perms.READ, new Id("digest", "user:secrethash")),
- new ACL(ZooDefs.Perms.ADMIN, new Id("digest", "adminuser:adminsecret"))
- ));
+ testACLs.addAll(Arrays.asList(new ACL(ZooDefs.Perms.READ, new Id("digest", "user:secrethash")), new ACL(ZooDefs.Perms.ADMIN, new Id("digest", "adminuser:adminsecret"))));
List<Id> authInfo = new ArrayList<Id>();
authInfo.add(new Id("digest", "adminuser:adminsecret"));
@@ -180,7 +172,7 @@ public class FinalRequestProcessorTest {
// Assert
assertTrue("Not a GetACL response. Auth failed?", responseRecord[0] instanceof GetACLResponse);
- GetACLResponse rsp = (GetACLResponse)responseRecord[0];
+ GetACLResponse rsp = (GetACLResponse) responseRecord[0];
assertThat("Number of ACLs in the response are different", rsp.getAcl().size(), equalTo(2));
// Verify ACLs in the response
@@ -190,7 +182,7 @@ public class FinalRequestProcessorTest {
private void assertMasked(boolean masked) {
assertTrue("Not a GetACL response. Auth failed?", responseRecord[0] instanceof GetACLResponse);
- GetACLResponse rsp = (GetACLResponse)responseRecord[0];
+ GetACLResponse rsp = (GetACLResponse) responseRecord[0];
assertThat("Number of ACLs in the response are different", rsp.getAcl().size(), equalTo(3));
// Verify ACLs in the response
@@ -227,4 +219,5 @@ public class FinalRequestProcessorTest {
assertThat("Original ACL list has been modified", testACLs.get(2).getId().getScheme(), equalTo("world"));
assertThat("Original ACL list has been modified", testACLs.get(2).getId().getId(), equalTo("anyone"));
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/InvalidSnapCountTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/InvalidSnapCountTest.java
index cd5af81d1..a7a4aeabe 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/InvalidSnapCountTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/InvalidSnapCountTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -19,31 +19,30 @@
package org.apache.zookeeper.server;
import static org.apache.zookeeper.test.ClientBase.CONNECTION_TIMEOUT;
-
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZKTestCase;
-import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.common.PathUtils;
import org.apache.zookeeper.test.ClientBase;
-import org.junit.Assert;
import org.junit.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/**
* Test stand-alone server.
*
*/
public class InvalidSnapCountTest extends ZKTestCase implements Watcher {
- protected static final Logger LOG =
- LoggerFactory.getLogger(InvalidSnapCountTest.class);
+
+ protected static final Logger LOG = LoggerFactory.getLogger(InvalidSnapCountTest.class);
public static class MainThread extends Thread {
+
final File confFile;
final TestMain main;
@@ -62,11 +61,11 @@ public class InvalidSnapCountTest extends ZKTestCase implements Watcher {
if (!dataDir.mkdir()) {
throw new IOException("unable to mkdir " + dataDir);
}
-
+
// Convert windows path to UNIX to avoid problems with "\"
String dir = PathUtils.normalizeFileSystemPath(dataDir.toString());
fwriter.write("dataDir=" + dir + "\n");
-
+
fwriter.write("clientPort=" + clientPort + "\n");
fwriter.flush();
fwriter.close();
@@ -75,7 +74,7 @@ public class InvalidSnapCountTest extends ZKTestCase implements Watcher {
}
public void run() {
- String args[] = new String[1];
+ String[] args = new String[1];
args[0] = confFile.toString();
try {
main.initializeAndRun(args);
@@ -88,12 +87,15 @@ public class InvalidSnapCountTest extends ZKTestCase implements Watcher {
public void shutdown() {
main.shutdown();
}
+
}
- public static class TestMain extends ZooKeeperServerMain {
+ public static class TestMain extends ZooKeeperServerMain {
+
public void shutdown() {
super.shutdown();
}
+
}
/**
@@ -107,11 +109,11 @@ public class InvalidSnapCountTest extends ZKTestCase implements Watcher {
MainThread main = new MainThread(CLIENT_PORT);
main.start();
- Assert.assertTrue("waiting for server being up",
- ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT,
- CONNECTION_TIMEOUT));
+ assertTrue(
+ "waiting for server being up",
+ ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT, CONNECTION_TIMEOUT));
- Assert.assertEquals(SyncRequestProcessor.getSnapCount(), 2);
+ assertEquals(SyncRequestProcessor.getSnapCount(), 2);
main.shutdown();
@@ -120,4 +122,5 @@ public class InvalidSnapCountTest extends ZKTestCase implements Watcher {
public void process(WatchedEvent event) {
// ignore for this test
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/InvalidSnapshotTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/InvalidSnapshotTest.java
index 97ad7923e..d3989ca47 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/InvalidSnapshotTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/InvalidSnapshotTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -19,10 +19,8 @@
package org.apache.zookeeper.server;
import static org.junit.Assert.assertTrue;
-
import java.io.File;
import java.io.RandomAccessFile;
-
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;
@@ -37,8 +35,8 @@ import org.slf4j.LoggerFactory;
* snapshot.
*/
public class InvalidSnapshotTest extends ClientBase {
- private static final Logger LOG =
- LoggerFactory.getLogger(InvalidSnapshotTest.class);
+
+ private static final Logger LOG = LoggerFactory.getLogger(InvalidSnapshotTest.class);
public InvalidSnapshotTest() {
SyncRequestProcessor.setSnapCount(100);
@@ -53,13 +51,12 @@ public class InvalidSnapshotTest extends ClientBase {
ZooKeeper zk = createClient();
try {
for (int i = 0; i < 2000; i++) {
- zk.create("/invalidsnap-" + i, new byte[0],
- Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
+ zk.create("/invalidsnap-" + i, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
}
} finally {
zk.close();
}
- NIOServerCnxnFactory factory = (NIOServerCnxnFactory)serverFactory;
+ NIOServerCnxnFactory factory = (NIOServerCnxnFactory) serverFactory;
stopServer();
// now corrupt the snapshot
@@ -75,10 +72,10 @@ public class InvalidSnapshotTest extends ClientBase {
// verify that the expected data exists and wasn't lost
zk = createClient();
try {
- assertTrue("the node should exist",
- (zk.exists("/invalidsnap-1999", false) != null));
+ assertTrue("the node should exist", (zk.exists("/invalidsnap-1999", false) != null));
} finally {
zk.close();
}
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/MockNIOServerCnxn.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/MockNIOServerCnxn.java
index 40eab0a81..7fc1a1693 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/MockNIOServerCnxn.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/MockNIOServerCnxn.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,16 +18,15 @@
package org.apache.zookeeper.server;
+import java.io.IOException;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;
-import java.io.IOException;
import org.apache.zookeeper.server.NIOServerCnxnFactory.SelectorThread;
public class MockNIOServerCnxn extends NIOServerCnxn {
- public MockNIOServerCnxn(ZooKeeperServer zk, SocketChannel sock,
- SelectionKey sk, NIOServerCnxnFactory factory,
- SelectorThread selectorThread) throws IOException {
+ public MockNIOServerCnxn(
+ ZooKeeperServer zk, SocketChannel sock, SelectionKey sk, NIOServerCnxnFactory factory, SelectorThread selectorThread) throws IOException {
super(zk, sock, sk, factory, selectorThread);
}
@@ -42,4 +41,5 @@ public class MockNIOServerCnxn extends NIOServerCnxn {
protected boolean isSocketOpen() {
return true;
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/MockSelectorThread.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/MockSelectorThread.java
index db66bc9e8..2871932f6 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/MockSelectorThread.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/MockSelectorThread.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -22,6 +22,7 @@ import java.io.IOException;
import java.nio.channels.SelectionKey;
public class MockSelectorThread extends NIOServerCnxnFactory.SelectorThread {
+
public MockSelectorThread(NIOServerCnxnFactory fact) throws IOException {
fact.super(0);
}
@@ -29,4 +30,5 @@ public class MockSelectorThread extends NIOServerCnxnFactory.SelectorThread {
public boolean addInterestOpsUpdateRequest(SelectionKey sk) {
return super.addInterestOpsUpdateRequest(sk);
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/MockServerCnxn.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/MockServerCnxn.java
index eb10720f0..831454540 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/MockServerCnxn.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/MockServerCnxn.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -15,6 +15,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
package org.apache.zookeeper.server;
import java.io.IOException;
@@ -23,10 +24,11 @@ import java.nio.ByteBuffer;
import java.security.cert.Certificate;
import org.apache.jute.Record;
import org.apache.zookeeper.WatchedEvent;
-import org.apache.zookeeper.proto.ReplyHeader;
import org.apache.zookeeper.data.Stat;
+import org.apache.zookeeper.proto.ReplyHeader;
public class MockServerCnxn extends ServerCnxn {
+
public Certificate[] clientChain;
public boolean secure;
@@ -44,8 +46,7 @@ public class MockServerCnxn extends ServerCnxn {
}
@Override
- public void sendResponse(ReplyHeader h, Record r, String tag, String cacheKey, Stat stat)
- throws IOException {
+ public void sendResponse(ReplyHeader h, Record r, String tag, String cacheKey, Stat stat) throws IOException {
}
@Override
@@ -115,4 +116,5 @@ public class MockServerCnxn extends ServerCnxn {
public int getInterestOps() {
return 0;
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/MultiOpSessionUpgradeTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/MultiOpSessionUpgradeTest.java
index 0426e2293..6e35d2c57 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/MultiOpSessionUpgradeTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/MultiOpSessionUpgradeTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,6 +18,18 @@
package org.apache.zookeeper.server;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
import org.apache.jute.BinaryOutputArchive;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
@@ -32,19 +44,12 @@ import org.apache.zookeeper.server.quorum.QuorumPeer;
import org.apache.zookeeper.server.quorum.QuorumZooKeeperServer;
import org.apache.zookeeper.server.quorum.UpgradeableSessionTracker;
import org.apache.zookeeper.test.QuorumBase;
-import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.nio.ByteBuffer;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-
public class MultiOpSessionUpgradeTest extends QuorumBase {
+
protected static final Logger LOG = LoggerFactory.getLogger(MultiOpSessionUpgradeTest.class);
@Override
@@ -63,9 +68,9 @@ public class MultiOpSessionUpgradeTest extends QuorumBase {
zk.create(path, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
QuorumZooKeeperServer server = getConnectedServer(zk.getSessionId());
- Assert.assertNotNull("unable to find server interlocutor", server);
- UpgradeableSessionTracker sessionTracker = (UpgradeableSessionTracker)server.getSessionTracker();
- Assert.assertFalse("session already global", sessionTracker.isGlobalSession(zk.getSessionId()));
+ assertNotNull("unable to find server interlocutor", server);
+ UpgradeableSessionTracker sessionTracker = (UpgradeableSessionTracker) server.getSessionTracker();
+ assertFalse("session already global", sessionTracker.isGlobalSession(zk.getSessionId()));
List<OpResult> multi = null;
try {
@@ -73,19 +78,18 @@ public class MultiOpSessionUpgradeTest extends QuorumBase {
Op.setData(path, data.getBytes(), 0),
Op.create(path + "/e", data.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL),
Op.create(path + "/p", data.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT),
- Op.create(path + "/q", data.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL)
- ));
+ Op.create(path + "/q", data.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL)));
} catch (KeeperException.SessionExpiredException e) {
// the scenario that inspired this unit test
- Assert.fail("received session expired for a session promotion in a multi-op");
+ fail("received session expired for a session promotion in a multi-op");
}
- Assert.assertNotNull(multi);
- Assert.assertEquals(4, multi.size());
- Assert.assertEquals(data, new String(zk.getData(path + "/e", false, null)));
- Assert.assertEquals(data, new String(zk.getData(path + "/p", false, null)));
- Assert.assertEquals(data, new String(zk.getData(path + "/q", false, null)));
- Assert.assertTrue("session not promoted", sessionTracker.isGlobalSession(zk.getSessionId()));
+ assertNotNull(multi);
+ assertEquals(4, multi.size());
+ assertEquals(data, new String(zk.getData(path + "/e", false, null)));
+ assertEquals(data, new String(zk.getData(path + "/p", false, null)));
+ assertEquals(data, new String(zk.getData(path + "/q", false, null)));
+ assertTrue("session not promoted", sessionTracker.isGlobalSession(zk.getSessionId()));
}
@Test
@@ -96,14 +100,13 @@ public class MultiOpSessionUpgradeTest extends QuorumBase {
zk.create(path, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
QuorumZooKeeperServer server = getConnectedServer(zk.getSessionId());
- Assert.assertNotNull("unable to find server interlocutor", server);
+ assertNotNull("unable to find server interlocutor", server);
Request readRequest = makeGetDataRequest(path, zk.getSessionId());
Request createRequest = makeCreateRequest(path + "/e", zk.getSessionId());
- Assert.assertNull("tried to upgrade on a read", server.checkUpgradeSession(readRequest));
- Assert.assertNotNull("failed to upgrade on a create", server.checkUpgradeSession(createRequest));
- Assert.assertNull("tried to upgrade after successful promotion",
- server.checkUpgradeSession(createRequest));
+ assertNull("tried to upgrade on a read", server.checkUpgradeSession(readRequest));
+ assertNotNull("failed to upgrade on a create", server.checkUpgradeSession(createRequest));
+ assertNull("tried to upgrade after successful promotion", server.checkUpgradeSession(createRequest));
}
private Request makeGetDataRequest(String path, long sessionId) throws IOException {
@@ -118,8 +121,7 @@ public class MultiOpSessionUpgradeTest extends QuorumBase {
private Request makeCreateRequest(String path, long sessionId) throws IOException {
ByteArrayOutputStream boas = new ByteArrayOutputStream();
BinaryOutputArchive boa = BinaryOutputArchive.getArchive(boas);
- CreateRequest createRequest = new CreateRequest(path,
- "data".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL.toFlag());
+ CreateRequest createRequest = new CreateRequest(path, "data".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL.toFlag());
createRequest.serialize(boa, "request");
ByteBuffer bb = ByteBuffer.wrap(boas.toByteArray());
return new Request(null, sessionId, 1, ZooDefs.OpCode.create2, bb, new ArrayList<Id>());
@@ -128,9 +130,10 @@ public class MultiOpSessionUpgradeTest extends QuorumBase {
private QuorumZooKeeperServer getConnectedServer(long sessionId) {
for (QuorumPeer peer : getPeerList()) {
if (peer.getActiveServer().getSessionTracker().isTrackingSession(sessionId)) {
- return (QuorumZooKeeperServer)peer.getActiveServer();
+ return (QuorumZooKeeperServer) peer.getActiveServer();
}
}
return null;
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/NIOServerCnxnFactoryTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/NIOServerCnxnFactoryTest.java
index 802065792..715c15a83 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/NIOServerCnxnFactoryTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/NIOServerCnxnFactoryTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,17 +18,17 @@
package org.apache.zookeeper.server;
-import org.apache.zookeeper.PortAssignment;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.SocketException;
+import org.apache.zookeeper.PortAssignment;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
public class NIOServerCnxnFactoryTest {
+
private InetSocketAddress listenAddress;
private NIOServerCnxnFactory factory;
@@ -65,4 +65,5 @@ public class NIOServerCnxnFactoryTest {
ServerSocket ss = new ServerSocket(listenAddress.getPort());
ss.close();
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/NIOServerCnxnTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/NIOServerCnxnTest.java
index 8795785e5..fc917e09b 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/NIOServerCnxnTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/NIOServerCnxnTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -15,52 +15,45 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
package org.apache.zookeeper.server;
+import static org.hamcrest.Matchers.equalTo;
+import static org.hamcrest.Matchers.greaterThan;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertThat;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
import java.io.IOException;
-
-
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.server.quorum.BufferStats;
import org.apache.zookeeper.test.ClientBase;
-import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import static org.hamcrest.Matchers.equalTo;
-import static org.hamcrest.Matchers.greaterThan;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertThat;
-
public class NIOServerCnxnTest extends ClientBase {
- private static final Logger LOG = LoggerFactory
- .getLogger(NIOServerCnxnTest.class);
+
+ private static final Logger LOG = LoggerFactory.getLogger(NIOServerCnxnTest.class);
/**
* Test operations on ServerCnxn after socket closure.
*/
@Test(timeout = 60000)
- public void testOperationsAfterCnxnClose() throws IOException,
- InterruptedException, KeeperException {
+ public void testOperationsAfterCnxnClose() throws IOException, InterruptedException, KeeperException {
final ZooKeeper zk = createClient();
final String path = "/a";
try {
// make sure zkclient works
- zk.create(path, "test".getBytes(), Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
- assertNotNull("Didn't create znode:" + path,
- zk.exists(path, false));
+ zk.create(path, "test".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
+ assertNotNull("Didn't create znode:" + path, zk.exists(path, false));
// Defaults ServerCnxnFactory would be instantiated with
// NIOServerCnxnFactory
- Assert.assertTrue(
- "Didn't instantiate ServerCnxnFactory with NIOServerCnxnFactory!",
- serverFactory instanceof NIOServerCnxnFactory);
+ assertTrue("Didn't instantiate ServerCnxnFactory with NIOServerCnxnFactory!", serverFactory instanceof NIOServerCnxnFactory);
Iterable<ServerCnxn> connections = serverFactory.getConnections();
for (ServerCnxn serverCnxn : connections) {
serverCnxn.close(ServerCnxn.DisconnectReason.CHANNEL_CLOSED_EXCEPTION);
@@ -68,8 +61,7 @@ public class NIOServerCnxnTest extends ClientBase {
serverCnxn.toString();
} catch (Exception e) {
LOG.error("Exception while getting connection details!", e);
- Assert.fail("Shouldn't throw exception while "
- + "getting connection details!");
+ fail("Shouldn't throw exception while " + "getting connection details!");
}
}
} finally {
@@ -82,14 +74,12 @@ public class NIOServerCnxnTest extends ClientBase {
public void testClientResponseStatsUpdate() throws IOException, InterruptedException, KeeperException {
try (ZooKeeper zk = createClient()) {
BufferStats clientResponseStats = serverFactory.getZooKeeperServer().serverStats().getClientResponseStats();
- assertThat("Last client response size should be initialized with INIT_VALUE",
- clientResponseStats.getLastBufferSize(), equalTo(BufferStats.INIT_VALUE));
+ assertThat("Last client response size should be initialized with INIT_VALUE", clientResponseStats.getLastBufferSize(), equalTo(BufferStats.INIT_VALUE));
- zk.create("/a", "test".getBytes(), Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk.create("/a", "test".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
- assertThat("Last client response size should be greater then zero after client request was performed",
- clientResponseStats.getLastBufferSize(), greaterThan(0));
+ assertThat("Last client response size should be greater then zero after client request was performed", clientResponseStats.getLastBufferSize(), greaterThan(0));
}
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/NettyServerCnxnTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/NettyServerCnxnTest.java
index 1ce7e055d..646d2051f 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/NettyServerCnxnTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/NettyServerCnxnTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,6 +18,22 @@
package org.apache.zookeeper.server;
+import static org.hamcrest.Matchers.equalTo;
+import static org.hamcrest.Matchers.greaterThan;
+import static org.junit.Assert.assertArrayEquals;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertThat;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+import java.io.IOException;
+import java.net.ProtocolException;
+import java.nio.charset.StandardCharsets;
+import java.util.Random;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
import org.apache.zookeeper.AsyncCallback.DataCallback;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
@@ -25,41 +41,25 @@ import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.common.ClientX509Util;
import org.apache.zookeeper.data.Stat;
-import org.apache.zookeeper.test.TestByteBufAllocator;
import org.apache.zookeeper.server.quorum.BufferStats;
import org.apache.zookeeper.test.ClientBase;
import org.apache.zookeeper.test.SSLAuthTest;
-import org.junit.Assert;
+import org.apache.zookeeper.test.TestByteBufAllocator;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.io.IOException;
-import java.net.ProtocolException;
-import java.nio.charset.StandardCharsets;
-import java.util.Random;
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.atomic.AtomicBoolean;
-import java.util.concurrent.atomic.AtomicInteger;
-
-import static org.hamcrest.Matchers.equalTo;
-import static org.hamcrest.Matchers.greaterThan;
-import static org.junit.Assert.assertArrayEquals;
-import static org.junit.Assert.assertThat;
-
/**
* Test verifies the behavior of NettyServerCnxn which represents a connection
* from a client to the server.
*/
public class NettyServerCnxnTest extends ClientBase {
- private static final Logger LOG = LoggerFactory
- .getLogger(NettyServerCnxnTest.class);
+
+ private static final Logger LOG = LoggerFactory.getLogger(NettyServerCnxnTest.class);
@Override
public void setUp() throws Exception {
- System.setProperty(ServerCnxnFactory.ZOOKEEPER_SERVER_CNXN_FACTORY,
- "org.apache.zookeeper.server.NettyServerCnxnFactory");
+ System.setProperty(ServerCnxnFactory.ZOOKEEPER_SERVER_CNXN_FACTORY, "org.apache.zookeeper.server.NettyServerCnxnFactory");
NettyServerCnxnFactory.setTestAllocator(TestByteBufAllocator.getInstance());
super.maxCnxns = 1;
super.exceptionOnFailedConnect = true;
@@ -83,24 +83,19 @@ public class NettyServerCnxnTest extends ClientBase {
*/
@Test(timeout = 40000)
public void testSendCloseSession() throws Exception {
- Assert.assertTrue(
- "Didn't instantiate ServerCnxnFactory with NettyServerCnxnFactory!",
- serverFactory instanceof NettyServerCnxnFactory);
+ assertTrue("Didn't instantiate ServerCnxnFactory with NettyServerCnxnFactory!", serverFactory instanceof NettyServerCnxnFactory);
final ZooKeeper zk = createClient();
final ZooKeeperServer zkServer = serverFactory.getZooKeeperServer();
final String path = "/a";
try {
// make sure zkclient works
- zk.create(path, "test".getBytes(StandardCharsets.UTF_8), Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk.create(path, "test".getBytes(StandardCharsets.UTF_8), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
// set on watch
- Assert.assertNotNull("Didn't create znode:" + path,
- zk.exists(path, true));
- Assert.assertEquals(1, zkServer.getZKDatabase().getDataTree().getWatchCount());
+ assertNotNull("Didn't create znode:" + path, zk.exists(path, true));
+ assertEquals(1, zkServer.getZKDatabase().getDataTree().getWatchCount());
Iterable<ServerCnxn> connections = serverFactory.getConnections();
- Assert.assertEquals("Mismatch in number of live connections!", 1,
- serverFactory.getNumAliveConnections());
+ assertEquals("Mismatch in number of live connections!", 1, serverFactory.getNumAliveConnections());
for (ServerCnxn serverCnxn : connections) {
serverCnxn.sendCloseSession();
}
@@ -110,11 +105,11 @@ public class NettyServerCnxnTest extends ClientBase {
Thread.sleep(1000);
timeout += 1000;
if (timeout > CONNECTION_TIMEOUT) {
- Assert.fail("The number of live connections should be 0");
+ fail("The number of live connections should be 0");
}
}
// make sure the watch is removed when the connection closed
- Assert.assertEquals(0, zkServer.getZKDatabase().getDataTree().getWatchCount());
+ assertEquals(0, zkServer.getZKDatabase().getDataTree().getWatchCount());
} finally {
zk.close();
}
@@ -127,12 +122,9 @@ public class NettyServerCnxnTest extends ClientBase {
*/
@Test(timeout = 40000, expected = ProtocolException.class)
public void testMaxConnectionPerIpSurpased() throws Exception {
- Assert.assertTrue(
- "Did not instantiate ServerCnxnFactory with NettyServerCnxnFactory!",
- serverFactory instanceof NettyServerCnxnFactory);
+ assertTrue("Did not instantiate ServerCnxnFactory with NettyServerCnxnFactory!", serverFactory instanceof NettyServerCnxnFactory);
- try (final ZooKeeper zk1 = createClient();
- final ZooKeeper zk2 = createClient();) {
+ try (final ZooKeeper zk1 = createClient(); final ZooKeeper zk2 = createClient()) {
}
}
@@ -140,14 +132,11 @@ public class NettyServerCnxnTest extends ClientBase {
public void testClientResponseStatsUpdate() throws IOException, InterruptedException, KeeperException {
try (ZooKeeper zk = createClient()) {
BufferStats clientResponseStats = serverFactory.getZooKeeperServer().serverStats().getClientResponseStats();
- assertThat("Last client response size should be initialized with INIT_VALUE",
- clientResponseStats.getLastBufferSize(), equalTo(BufferStats.INIT_VALUE));
+ assertThat("Last client response size should be initialized with INIT_VALUE", clientResponseStats.getLastBufferSize(), equalTo(BufferStats.INIT_VALUE));
- zk.create("/a", "test".getBytes(StandardCharsets.UTF_8), Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk.create("/a", "test".getBytes(StandardCharsets.UTF_8), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
- assertThat("Last client response size should be greater than 0 after client request was performed",
- clientResponseStats.getLastBufferSize(), greaterThan(0));
+ assertThat("Last client response size should be greater than 0 after client request was performed", clientResponseStats.getLastBufferSize(), greaterThan(0));
byte[] contents = zk.getData("/a", null, null);
assertArrayEquals("unexpected data", "test".getBytes(StandardCharsets.UTF_8), contents);
@@ -158,14 +147,11 @@ public class NettyServerCnxnTest extends ClientBase {
public void testServerSideThrottling() throws IOException, InterruptedException, KeeperException {
try (ZooKeeper zk = createClient()) {
BufferStats clientResponseStats = serverFactory.getZooKeeperServer().serverStats().getClientResponseStats();
- assertThat("Last client response size should be initialized with INIT_VALUE",
- clientResponseStats.getLastBufferSize(), equalTo(BufferStats.INIT_VALUE));
+ assertThat("Last client response size should be initialized with INIT_VALUE", clientResponseStats.getLastBufferSize(), equalTo(BufferStats.INIT_VALUE));
- zk.create("/a", "test".getBytes(StandardCharsets.UTF_8), Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk.create("/a", "test".getBytes(StandardCharsets.UTF_8), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
- assertThat("Last client response size should be greater than 0 after client request was performed",
- clientResponseStats.getLastBufferSize(), greaterThan(0));
+ assertThat("Last client response size should be greater than 0 after client request was performed", clientResponseStats.getLastBufferSize(), greaterThan(0));
for (final ServerCnxn cnxn : serverFactory.cnxns) {
final NettyServerCnxn nettyCnxn = ((NettyServerCnxn) cnxn);
@@ -306,8 +292,7 @@ public class NettyServerCnxnTest extends ClientBase {
while (requestIssued++ < totalRequestsNum) {
zk.getData(path, null, new 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) {
if (rc == 0) {
successResponse.addAndGet(1);
} else {
@@ -323,7 +308,7 @@ public class NettyServerCnxnTest extends ClientBase {
LOG.info("started thread to issue {} async requests", totalRequestsNum);
// and verify the response received is same as what we issued
- Assert.assertTrue(responseReceivedLatch.await(60, TimeUnit.SECONDS));
+ assertTrue(responseReceivedLatch.await(60, TimeUnit.SECONDS));
LOG.info("received all {} responses", totalRequestsNum);
stopped.set(true);
@@ -333,7 +318,7 @@ public class NettyServerCnxnTest extends ClientBase {
// wait another second for the left requests to finish
LOG.info("waiting another 1s for the requests to go through");
Thread.sleep(1000);
- Assert.assertEquals(successResponse.get(), totalRequestsNum);
+ assertEquals(successResponse.get(), totalRequestsNum);
}
} finally {
if (secure) {
@@ -341,4 +326,5 @@ public class NettyServerCnxnTest extends ClientBase {
}
}
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/NodeHashMapImplTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/NodeHashMapImplTest.java
index 4761c0045..4a2fb695a 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/NodeHashMapImplTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/NodeHashMapImplTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,16 +18,15 @@
package org.apache.zookeeper.server;
-import java.util.Set;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotEquals;
import java.util.Map;
-
+import java.util.Set;
import org.apache.zookeeper.ZKTestCase;
import org.apache.zookeeper.data.StatPersisted;
import org.apache.zookeeper.server.util.DigestCalculator;
-
import org.junit.After;
import org.junit.Before;
-import org.junit.Assert;
import org.junit.Test;
public class NodeHashMapImplTest extends ZKTestCase {
@@ -49,42 +48,42 @@ public class NodeHashMapImplTest extends ZKTestCase {
public void testOperations() {
NodeHashMapImpl nodes = new NodeHashMapImpl();
- Assert.assertEquals(0, nodes.size());
- Assert.assertEquals(0L, nodes.getDigest());
+ assertEquals(0, nodes.size());
+ assertEquals(0L, nodes.getDigest());
// add a new node
String p1 = "p1";
DataNode n1 = new DataNode(p1.getBytes(), 0L, new StatPersisted());
nodes.put(p1, n1);
- Assert.assertEquals(n1, nodes.get(p1));
- Assert.assertNotEquals(0L, nodes.getDigest());
- Assert.assertEquals(1, nodes.size());
+ assertEquals(n1, nodes.get(p1));
+ assertNotEquals(0L, nodes.getDigest());
+ assertEquals(1, nodes.size());
// put another node
String p2 = "p2";
nodes.put(p2, new DataNode(p2.getBytes(), 0L, new StatPersisted()));
Set<Map.Entry<String, DataNode>> entries = nodes.entrySet();
- Assert.assertEquals(2, entries.size());
+ assertEquals(2, entries.size());
// remove a node
nodes.remove(p1);
- Assert.assertEquals(1, nodes.size());
+ assertEquals(1, nodes.size());
nodes.remove(p2);
- Assert.assertEquals(0, nodes.size());
- Assert.assertEquals(0L, nodes.getDigest());
+ assertEquals(0, nodes.size());
+ assertEquals(0L, nodes.getDigest());
// test preChange and postChange
String p3 = "p3";
DataNode n3 = new DataNode(p3.getBytes(), 0L, new StatPersisted());
nodes.put(p3, n3);
long preChangeDigest = nodes.getDigest();
- Assert.assertNotEquals(0L, preChangeDigest);
+ assertNotEquals(0L, preChangeDigest);
nodes.preChange(p3, n3);
- Assert.assertEquals(0L, nodes.getDigest());
+ assertEquals(0L, nodes.getDigest());
n3.stat.setMzxid(1);
n3.stat.setMtime(1);
@@ -92,7 +91,8 @@ public class NodeHashMapImplTest extends ZKTestCase {
nodes.postChange(p3, n3);
long postChangeDigest = nodes.getDigest();
- Assert.assertNotEquals(0, postChangeDigest);
- Assert.assertNotEquals(preChangeDigest, postChangeDigest);
+ assertNotEquals(0, postChangeDigest);
+ assertNotEquals(preChangeDigest, postChangeDigest);
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/PrepRequestProcessorMetricsTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/PrepRequestProcessorMetricsTest.java
index 9a130f09c..7aa74d321 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/PrepRequestProcessorMetricsTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/PrepRequestProcessorMetricsTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,9 +18,33 @@
package org.apache.zookeeper.server;
+import static org.hamcrest.number.OrderingComparison.greaterThan;
+import static org.hamcrest.number.OrderingComparison.greaterThanOrEqualTo;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertThat;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyLong;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.when;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
import org.apache.jute.BinaryOutputArchive;
import org.apache.jute.Record;
-import org.apache.zookeeper.*;
+import org.apache.zookeeper.CreateMode;
+import org.apache.zookeeper.WatchedEvent;
+import org.apache.zookeeper.Watcher;
+import org.apache.zookeeper.ZKTestCase;
+import org.apache.zookeeper.ZooDefs;
+import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.StatPersisted;
import org.apache.zookeeper.metrics.MetricsUtils;
import org.apache.zookeeper.proto.DeleteRequest;
@@ -28,29 +52,13 @@ import org.apache.zookeeper.proto.SetDataRequest;
import org.apache.zookeeper.test.ClientBase;
import org.apache.zookeeper.test.QuorumUtil;
import org.junit.After;
-import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.nio.ByteBuffer;
-import java.util.HashSet;
-import java.util.Map;
-import java.util.Set;
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.TimeUnit;
-
-import static org.hamcrest.number.OrderingComparison.greaterThan;
-import static org.hamcrest.number.OrderingComparison.greaterThanOrEqualTo;
-import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.ArgumentMatchers.anyLong;
-import static org.mockito.ArgumentMatchers.anyString;
-import static org.mockito.Mockito.*;
-
public class PrepRequestProcessorMetricsTest extends ZKTestCase {
+
private static final Logger LOG = LoggerFactory.getLogger(PrepRequestProcessorMetricsTest.class);
ZooKeeperServer zks;
@@ -88,21 +96,21 @@ public class PrepRequestProcessorMetricsTest extends ZKTestCase {
BinaryOutputArchive boa = BinaryOutputArchive.getArchive(baos);
record.serialize(boa, "request");
baos.close();
- return new Request(null, 1l, 0, opCode, ByteBuffer.wrap(baos.toByteArray()), null);
+ return new Request(null, 1L, 0, opCode, ByteBuffer.wrap(baos.toByteArray()), null);
}
private Request createRequest(String path, int opCode) throws IOException {
Record record;
switch (opCode) {
- case ZooDefs.OpCode.setData:
- record = new SetDataRequest(path, new byte[0], -1);
- break;
- case ZooDefs.OpCode.delete:
- record = new DeleteRequest(path, -1);
- break;
- default:
- record = new DeleteRequest(path, -1);
- break;
+ case ZooDefs.OpCode.setData:
+ record = new SetDataRequest(path, new byte[0], -1);
+ break;
+ case ZooDefs.OpCode.delete:
+ record = new DeleteRequest(path, -1);
+ break;
+ default:
+ record = new DeleteRequest(path, -1);
+ break;
}
return createRequest(record, opCode);
@@ -117,7 +125,8 @@ public class PrepRequestProcessorMetricsTest extends ZKTestCase {
CountDownLatch threeRequests = new CountDownLatch(3);
doAnswer(invocationOnMock -> {
threeRequests.countDown();
- return null;}).when(nextProcessor).processRequest(any(Request.class));
+ return null;
+ }).when(nextProcessor).processRequest(any(Request.class));
PrepRequestProcessor prepRequestProcessor = new PrepRequestProcessor(zks, nextProcessor);
@@ -129,7 +138,7 @@ public class PrepRequestProcessorMetricsTest extends ZKTestCase {
prepRequestProcessor.processRequest(createRequest(2, ZooDefs.OpCode.closeSession));
Map<String, Object> values = MetricsUtils.currentServerMetrics();
- Assert.assertEquals(3L, values.get("prep_processor_request_queued"));
+ assertEquals(3L, values.get("prep_processor_request_queued"));
// the sleep is just to make sure the requests will stay in the queue for some time
Thread.sleep(20);
@@ -138,21 +147,22 @@ public class PrepRequestProcessorMetricsTest extends ZKTestCase {
threeRequests.await(500, TimeUnit.MILLISECONDS);
values = MetricsUtils.currentServerMetrics();
- Assert.assertEquals(3L, values.get("max_prep_processor_queue_size"));
+ assertEquals(3L, values.get("max_prep_processor_queue_size"));
- Assert.assertThat((long)values.get("min_prep_processor_queue_time_ms"), greaterThan(20l));
- Assert.assertEquals(3L, values.get("cnt_prep_processor_queue_time_ms"));
+ assertThat((long) values.get("min_prep_processor_queue_time_ms"), greaterThan(20L));
+ assertEquals(3L, values.get("cnt_prep_processor_queue_time_ms"));
- Assert.assertEquals(3L, values.get("cnt_prep_process_time"));
- Assert.assertThat((long)values.get("max_prep_process_time"), greaterThan(0l));
+ assertEquals(3L, values.get("cnt_prep_process_time"));
+ assertThat((long) values.get("max_prep_process_time"), greaterThan(0L));
- Assert.assertEquals(1L, values.get("cnt_close_session_prep_time"));
- Assert.assertThat((long)values.get("max_close_session_prep_time"), greaterThanOrEqualTo(0L));
+ assertEquals(1L, values.get("cnt_close_session_prep_time"));
+ assertThat((long) values.get("max_close_session_prep_time"), greaterThanOrEqualTo(0L));
- Assert.assertEquals(5L, values.get("outstanding_changes_queued"));
+ assertEquals(5L, values.get("outstanding_changes_queued"));
}
private class SimpleWatcher implements Watcher {
+
CountDownLatch created;
public SimpleWatcher(CountDownLatch latch) {
this.created = latch;
@@ -161,6 +171,7 @@ public class PrepRequestProcessorMetricsTest extends ZKTestCase {
public void process(WatchedEvent e) {
created.countDown();
}
+
}
@Test
@@ -179,8 +190,9 @@ public class PrepRequestProcessorMetricsTest extends ZKTestCase {
created.await(200, TimeUnit.MILLISECONDS);
Map<String, Object> values = MetricsUtils.currentServerMetrics();
- Assert.assertThat((long)values.get("outstanding_changes_removed"), greaterThan(0L));
+ assertThat((long) values.get("outstanding_changes_removed"), greaterThan(0L));
util.shutdownAll();
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/PrepRequestProcessorTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/PrepRequestProcessorTest.java
index 04d8df475..8aacaac4e 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/PrepRequestProcessorTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/PrepRequestProcessorTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,6 +18,22 @@
package org.apache.zookeeper.server;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.IOException;
+import java.io.PrintWriter;
+import java.nio.ByteBuffer;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
import org.apache.jute.BinaryOutputArchive;
import org.apache.jute.Record;
import org.apache.zookeeper.KeeperException;
@@ -34,26 +50,13 @@ import org.apache.zookeeper.server.ZooKeeperServer.ChangeRecord;
import org.apache.zookeeper.test.ClientBase;
import org.apache.zookeeper.txn.ErrorTxn;
import org.junit.After;
-import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.io.ByteArrayOutputStream;
-import java.io.File;
-import java.io.IOException;
-import java.io.PrintWriter;
-import java.nio.ByteBuffer;
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.TimeUnit;
-
public class PrepRequestProcessorTest extends ClientBase {
+
private static final Logger LOG = LoggerFactory.getLogger(PrepRequestProcessorTest.class);
private static final int CONNECTION_TIMEOUT = 3000;
private static String HOSTPORT = "127.0.0.1:" + PortAssignment.unique();
@@ -74,8 +77,7 @@ public class PrepRequestProcessorTest extends ClientBase {
servcnxnf = ServerCnxnFactory.createFactory(PORT, -1);
servcnxnf.startup(zks);
- Assert.assertTrue("waiting for server being up ",
- ClientBase.waitForServerUp(HOSTPORT, CONNECTION_TIMEOUT));
+ assertTrue("waiting for server being up ", ClientBase.waitForServerUp(HOSTPORT, CONNECTION_TIMEOUT));
zks.sessionTracker = new MySessionTracker();
}
@@ -93,12 +95,11 @@ public class PrepRequestProcessorTest extends ClientBase {
public void testPRequest() throws Exception {
pLatch = new CountDownLatch(1);
processor = new PrepRequestProcessor(zks, new MyRequestProcessor());
- Request foo = new Request(null, 1l, 1, OpCode.create, ByteBuffer.allocate(3), null);
+ Request foo = new Request(null, 1L, 1, OpCode.create, ByteBuffer.allocate(3), null);
processor.pRequest(foo);
- Assert.assertEquals("Request should have marshalling error", new ErrorTxn(KeeperException.Code.MARSHALLINGERROR.intValue()),
- outcome.getTxn());
- Assert.assertTrue("request hasn't been processed in chain", pLatch.await(5, TimeUnit.SECONDS));
+ assertEquals("Request should have marshalling error", new ErrorTxn(KeeperException.Code.MARSHALLINGERROR.intValue()), outcome.getTxn());
+ assertTrue("request hasn't been processed in chain", pLatch.await(5, TimeUnit.SECONDS));
}
private Request createRequest(Record record, int opCode) throws IOException {
@@ -109,7 +110,7 @@ public class PrepRequestProcessorTest extends ClientBase {
baos.close();
// Id
List<Id> ids = Arrays.asList(Ids.ANYONE_ID_UNSAFE);
- return new Request(null, 1l, 0, opCode, ByteBuffer.wrap(baos.toByteArray()), ids);
+ return new Request(null, 1L, 0, opCode, ByteBuffer.wrap(baos.toByteArray()), ids);
}
private void process(List<Op> ops) throws Exception {
@@ -120,7 +121,7 @@ public class PrepRequestProcessorTest extends ClientBase {
Request req = createRequest(record, OpCode.multi);
processor.pRequest(req);
- Assert.assertTrue("request hasn't been processed in chain", pLatch.await(5, TimeUnit.SECONDS));
+ assertTrue("request hasn't been processed in chain", pLatch.await(5, TimeUnit.SECONDS));
}
/**
@@ -131,30 +132,23 @@ public class PrepRequestProcessorTest extends ClientBase {
public void testMultiOutstandingChange() throws Exception {
zks.getZKDatabase().dataTree.createNode("/foo", new byte[0], Ids.OPEN_ACL_UNSAFE, 0, 0, 0, 0);
- Assert.assertNull(zks.outstandingChangesForPath.get("/foo"));
+ assertNull(zks.outstandingChangesForPath.get("/foo"));
- process(Arrays.asList(
- Op.setData("/foo", new byte[0], -1)));
+ process(Arrays.asList(Op.setData("/foo", new byte[0], -1)));
ChangeRecord cr = zks.outstandingChangesForPath.get("/foo");
- Assert.assertNotNull("Change record wasn't set", cr);
- Assert.assertEquals("Record zxid wasn't set correctly",
- 1, cr.zxid);
+ assertNotNull("Change record wasn't set", cr);
+ assertEquals("Record zxid wasn't set correctly", 1, cr.zxid);
- process(Arrays.asList(
- Op.delete("/foo", -1)));
+ process(Arrays.asList(Op.delete("/foo", -1)));
cr = zks.outstandingChangesForPath.get("/foo");
- Assert.assertEquals("Record zxid wasn't set correctly",
- 2, cr.zxid);
-
+ assertEquals("Record zxid wasn't set correctly", 2, cr.zxid);
// It should fail and shouldn't change outstanding record.
- process(Arrays.asList(
- Op.delete("/foo", -1)));
+ process(Arrays.asList(Op.delete("/foo", -1)));
cr = zks.outstandingChangesForPath.get("/foo");
// zxid should still be previous result because record's not changed.
- Assert.assertEquals("Record zxid wasn't set correctly",
- 2, cr.zxid);
+ assertEquals("Record zxid wasn't set correctly", 2, cr.zxid);
}
/**
@@ -168,17 +162,15 @@ public class PrepRequestProcessorTest extends ClientBase {
zks.getZKDatabase().dataTree.createNode("/foo", new byte[0], Ids.OPEN_ACL_UNSAFE, 0, 0, 0, 0);
zks.getZKDatabase().dataTree.createNode("/foo/bar", new byte[0], Ids.OPEN_ACL_UNSAFE, 0, 0, 0, 0);
- Assert.assertNull(zks.outstandingChangesForPath.get("/foo"));
+ assertNull(zks.outstandingChangesForPath.get("/foo"));
// multi record:
// set "/foo" => succeed, leave a outstanding change
// delete "/foo" => fail, roll back change
- process(Arrays.asList(
- Op.setData("/foo", new byte[0], -1),
- Op.delete("/foo", -1)));
+ process(Arrays.asList(Op.setData("/foo", new byte[0], -1), Op.delete("/foo", -1)));
// aborting multi shouldn't leave any record.
- Assert.assertNull(zks.outstandingChangesForPath.get("/foo"));
+ assertNull(zks.outstandingChangesForPath.get("/foo"));
}
/**
@@ -194,11 +186,12 @@ public class PrepRequestProcessorTest extends ClientBase {
Request req = createRequest(record, OpCode.setData);
processor.pRequest(req);
pLatch.await();
- Assert.assertEquals(outcome.getHdr().getType(), OpCode.error);
- Assert.assertEquals(outcome.getException().code(), KeeperException.Code.BADARGUMENTS);
+ assertEquals(outcome.getHdr().getType(), OpCode.error);
+ assertEquals(outcome.getException().code(), KeeperException.Code.BADARGUMENTS);
}
private class MyRequestProcessor implements RequestProcessor {
+
@Override
public void processRequest(Request request) {
// getting called by PrepRequestProcessor
@@ -210,9 +203,11 @@ public class PrepRequestProcessorTest extends ClientBase {
// TODO Auto-generated method stub
}
+
}
private class MySessionTracker implements SessionTracker {
+
@Override
public boolean trackSession(long id, int to) {
// TODO Auto-generated method stub
@@ -224,8 +219,7 @@ public class PrepRequestProcessorTest extends ClientBase {
return false;
}
@Override
- public void checkSession(long sessionId, Object owner)
- throws SessionExpiredException, SessionMovedException {
+ public void checkSession(long sessionId, Object owner) throws SessionExpiredException, SessionMovedException {
// TODO Auto-generated method stub
}
@Override
@@ -238,18 +232,17 @@ public class PrepRequestProcessorTest extends ClientBase {
// TODO Auto-generated method stub
}
- @Override
+ @Override
public void removeSession(long sessionId) {
// TODO Auto-generated method stub
}
public int upgradeSession(long sessionId) {
- // TODO Auto-generated method stub
- return 0;
+ // TODO Auto-generated method stub
+ return 0;
}
@Override
- public void setOwner(long id, Object owner)
- throws SessionExpiredException {
+ public void setOwner(long id, Object owner) throws SessionExpiredException {
// TODO Auto-generated method stub
}
@@ -265,7 +258,7 @@ public class PrepRequestProcessorTest extends ClientBase {
}
@Override
public void setSessionClosing(long sessionId) {
- // TODO Auto-generated method stub
+ // TODO Auto-generated method stub
}
@Override
public boolean isTrackingSession(long sessionId) {
@@ -273,8 +266,7 @@ public class PrepRequestProcessorTest extends ClientBase {
return false;
}
@Override
- public void checkGlobalSession(long sessionId, Object owner)
- throws SessionExpiredException, SessionMovedException {
+ public void checkGlobalSession(long sessionId, Object owner) throws SessionExpiredException, SessionMovedException {
// TODO Auto-generated method stub
}
@Override
@@ -285,5 +277,7 @@ public class PrepRequestProcessorTest extends ClientBase {
public long getLocalSessionCount() {
return 0;
}
+
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/PurgeTxnTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/PurgeTxnTest.java
index 7898e6eaa..f9c3091d5 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/PurgeTxnTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/PurgeTxnTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -19,7 +19,10 @@
package org.apache.zookeeper.server;
import static org.junit.Assert.assertEquals;
-
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
@@ -29,27 +32,22 @@ import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
-import org.apache.zookeeper.data.Stat;
-
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.PortAssignment;
import org.apache.zookeeper.ZKTestCase;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;
-import org.apache.zookeeper.server.PurgeTxnLog;
-import org.apache.zookeeper.server.ServerCnxnFactory;
-import org.apache.zookeeper.server.SyncRequestProcessor;
-import org.apache.zookeeper.server.ZooKeeperServer;
+import org.apache.zookeeper.data.Stat;
import org.apache.zookeeper.server.persistence.FileTxnSnapLog;
import org.apache.zookeeper.server.persistence.Util;
import org.apache.zookeeper.test.ClientBase;
import org.junit.After;
-import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class PurgeTxnTest extends ZKTestCase {
+
private static final Logger LOG = LoggerFactory.getLogger(PurgeTxnTest.class);
private static String HOSTPORT = "127.0.0.1:" + PortAssignment.unique();
private static final int CONNECTION_TIMEOUT = 3000;
@@ -76,32 +74,29 @@ public class PurgeTxnTest extends ZKTestCase {
final int PORT = Integer.parseInt(HOSTPORT.split(":")[1]);
ServerCnxnFactory f = ServerCnxnFactory.createFactory(PORT, -1);
f.startup(zks);
- Assert.assertTrue("waiting for server being up ",
- ClientBase.waitForServerUp(HOSTPORT,CONNECTION_TIMEOUT));
+ assertTrue("waiting for server being up ", ClientBase.waitForServerUp(HOSTPORT, CONNECTION_TIMEOUT));
ZooKeeper zk = ClientBase.createZKClient(HOSTPORT);
try {
- for (int i = 0; i< 2000; i++) {
- zk.create("/invalidsnap-" + i, new byte[0], Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ for (int i = 0; i < 2000; i++) {
+ zk.create("/invalidsnap-" + i, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
}
} finally {
zk.close();
}
f.shutdown();
zks.getTxnLogFactory().close();
- Assert.assertTrue("waiting for server to shutdown",
- ClientBase.waitForServerDown(HOSTPORT, CONNECTION_TIMEOUT));
+ assertTrue("waiting for server to shutdown", ClientBase.waitForServerDown(HOSTPORT, CONNECTION_TIMEOUT));
// now corrupt the snapshot
PurgeTxnLog.purge(tmpDir, tmpDir, 3);
FileTxnSnapLog snaplog = new FileTxnSnapLog(tmpDir, tmpDir);
List<File> listLogs = snaplog.findNRecentSnapshots(4);
int numSnaps = 0;
- for (File ff: listLogs) {
+ for (File ff : listLogs) {
if (ff.getName().startsWith("snapshot")) {
numSnaps++;
}
}
- Assert.assertTrue("exactly 3 snapshots ", (numSnaps == 3));
+ assertTrue("exactly 3 snapshots ", (numSnaps == 3));
snaplog.close();
zks.shutdown();
}
@@ -123,8 +118,7 @@ public class PurgeTxnTest extends ZKTestCase {
final int PORT = Integer.parseInt(HOSTPORT.split(":")[1]);
ServerCnxnFactory f = ServerCnxnFactory.createFactory(PORT, -1);
f.startup(zks);
- Assert.assertTrue("waiting for server being up ",
- ClientBase.waitForServerUp(HOSTPORT, CONNECTION_TIMEOUT));
+ assertTrue("waiting for server being up ", ClientBase.waitForServerUp(HOSTPORT, CONNECTION_TIMEOUT));
final ZooKeeper zk = ClientBase.createZKClient(HOSTPORT);
final CountDownLatch doPurge = new CountDownLatch(1);
final CountDownLatch purgeFinished = new CountDownLatch(1);
@@ -132,8 +126,7 @@ public class PurgeTxnTest extends ZKTestCase {
new Thread() {
public void run() {
try {
- doPurge.await(OP_TIMEOUT_IN_MILLIS / 2,
- TimeUnit.MILLISECONDS);
+ doPurge.await(OP_TIMEOUT_IN_MILLIS / 2, TimeUnit.MILLISECONDS);
PurgeTxnLog.purge(tmpDir, tmpDir, 3);
} catch (IOException ioe) {
LOG.error("Exception when purge", ioe);
@@ -144,20 +137,18 @@ public class PurgeTxnTest extends ZKTestCase {
} finally {
purgeFinished.countDown();
}
- };
+ }
}.start();
final int thCount = 3;
- List<String> znodes = manyClientOps(zk, doPurge, thCount,
- "/invalidsnap");
- Assert.assertTrue("Purging is not finished!", purgeFinished.await(
- OP_TIMEOUT_IN_MILLIS, TimeUnit.MILLISECONDS));
- Assert.assertFalse("Purging failed!", opFailed.get());
+ List<String> znodes = manyClientOps(zk, doPurge, thCount, "/invalidsnap");
+ assertTrue("Purging is not finished!", purgeFinished.await(OP_TIMEOUT_IN_MILLIS, TimeUnit.MILLISECONDS));
+ assertFalse("Purging failed!", opFailed.get());
for (String znode : znodes) {
try {
zk.getData(znode, false, null);
} catch (Exception ke) {
LOG.error("Unexpected exception when visiting znode!", ke);
- Assert.fail("Unexpected exception when visiting znode!");
+ fail("Unexpected exception when visiting znode!");
}
}
zk.close();
@@ -177,8 +168,7 @@ public class PurgeTxnTest extends ZKTestCase {
tmpDir = ClientBase.createTmpDir();
File version2 = new File(tmpDir.toString(), "version-2");
- Assert.assertTrue("Failed to create version_2 dir:" + version2.toString(),
- version2.mkdir());
+ assertTrue("Failed to create version_2 dir:" + version2.toString(), version2.mkdir());
// Test that with no snaps, findNRecentSnapshots returns empty list
FileTxnSnapLog txnLog = new FileTxnSnapLog(tmpDir, tmpDir);
@@ -190,15 +180,12 @@ public class PurgeTxnTest extends ZKTestCase {
for (int i = 0; i < nRecentCount; i++) {
// simulate log file
File logFile = new File(version2 + "/log." + Long.toHexString(--counter));
- Assert.assertTrue("Failed to create log File:" + logFile.toString(),
- logFile.createNewFile());
+ assertTrue("Failed to create log File:" + logFile.toString(), logFile.createNewFile());
// simulate snapshot file
- File snapFile = new File(version2 + "/snapshot."
- + Long.toHexString(--counter));
- Assert.assertTrue("Failed to create snap File:" + snapFile.toString(),
- snapFile.createNewFile());
+ File snapFile = new File(version2 + "/snapshot." + Long.toHexString(--counter));
+ assertTrue("Failed to create snap File:" + snapFile.toString(), snapFile.createNewFile());
// add the n recent snap files for assertion
- if(i < nRecentSnap){
+ if (i < nRecentSnap) {
expectedNRecentSnapFiles.add(snapFile);
}
}
@@ -206,19 +193,17 @@ public class PurgeTxnTest extends ZKTestCase {
// Test that when we ask for recent snaps we get the number we asked for and
// the files we expected
List<File> nRecentSnapFiles = txnLog.findNRecentSnapshots(nRecentSnap);
- Assert.assertEquals("exactly 4 snapshots ", 4,
- nRecentSnapFiles.size());
+ assertEquals("exactly 4 snapshots ", 4, nRecentSnapFiles.size());
expectedNRecentSnapFiles.removeAll(nRecentSnapFiles);
- Assert.assertEquals("Didn't get the recent snap files", 0,
- expectedNRecentSnapFiles.size());
+ assertEquals("Didn't get the recent snap files", 0, expectedNRecentSnapFiles.size());
// Test that when asking for more snaps than we created, we still only get snaps
// not logs or anything else (per ZOOKEEPER-2420)
nRecentSnapFiles = txnLog.findNRecentSnapshots(nRecentCount + 5);
assertEquals(nRecentCount, nRecentSnapFiles.size());
- for (File f: nRecentSnapFiles) {
- Assert.assertTrue("findNRecentSnapshots() returned a non-snapshot: " + f.getPath(),
- (Util.getZxidFromName(f.getName(), "snapshot") != -1));
+ for (File f : nRecentSnapFiles) {
+ assertTrue("findNRecentSnapshots() returned a non-snapshot: "
+ + f.getPath(), (Util.getZxidFromName(f.getName(), "snapshot") != -1));
}
txnLog.close();
@@ -237,20 +222,17 @@ public class PurgeTxnTest extends ZKTestCase {
AtomicInteger offset = new AtomicInteger(0);
tmpDir = ClientBase.createTmpDir();
File version2 = new File(tmpDir.toString(), "version-2");
- Assert.assertTrue("Failed to create version_2 dir:" + version2.toString(),
- version2.mkdir());
+ assertTrue("Failed to create version_2 dir:" + version2.toString(), version2.mkdir());
List<File> snapsToPurge = new ArrayList<File>();
List<File> logsToPurge = new ArrayList<File>();
List<File> snaps = new ArrayList<File>();
List<File> logs = new ArrayList<File>();
List<File> snapsAboveRecentFiles = new ArrayList<File>();
List<File> logsAboveRecentFiles = new ArrayList<File>();
- createDataDirFiles(offset, fileToPurgeCount, false, version2, snapsToPurge,
- logsToPurge);
+ createDataDirFiles(offset, fileToPurgeCount, false, version2, snapsToPurge, logsToPurge);
createDataDirFiles(offset, nRecentCount, false, version2, snaps, logs);
logs.add(logsToPurge.remove(0)); // log that precedes first retained snapshot is also retained
- createDataDirFiles(offset, fileAboveRecentCount, false, version2,
- snapsAboveRecentFiles, logsAboveRecentFiles);
+ createDataDirFiles(offset, fileAboveRecentCount, false, version2, snapsAboveRecentFiles, logsAboveRecentFiles);
/**
* The newest log file preceding the oldest retained snapshot is not removed as it may
@@ -292,8 +274,7 @@ public class PurgeTxnTest extends ZKTestCase {
AtomicInteger offset = new AtomicInteger(0);
tmpDir = ClientBase.createTmpDir();
File version2 = new File(tmpDir.toString(), "version-2");
- Assert.assertTrue("Failed to create version_2 dir:" + version2.toString(),
- version2.mkdir());
+ assertTrue("Failed to create version_2 dir:" + version2.toString(), version2.mkdir());
List<File> snaps = new ArrayList<File>();
List<File> logs = new ArrayList<File>();
createDataDirFiles(offset, nRecentCount, testWithPrecedingLogFile, version2, snaps, logs);
@@ -316,14 +297,12 @@ public class PurgeTxnTest extends ZKTestCase {
AtomicInteger offset = new AtomicInteger(0);
tmpDir = ClientBase.createTmpDir();
File version2 = new File(tmpDir.toString(), "version-2");
- Assert.assertTrue("Failed to create version_2 dir:" + version2.toString(),
- version2.mkdir());
+ assertTrue("Failed to create version_2 dir:" + version2.toString(), version2.mkdir());
List<File> snapsToPurge = new ArrayList<File>();
List<File> logsToPurge = new ArrayList<File>();
List<File> snaps = new ArrayList<File>();
List<File> logs = new ArrayList<File>();
- createDataDirFiles(offset, fileToPurgeCount, false, version2, snapsToPurge,
- logsToPurge);
+ createDataDirFiles(offset, fileToPurgeCount, false, version2, snapsToPurge, logsToPurge);
createDataDirFiles(offset, nRecentCount, false, version2, snaps, logs);
logs.add(logsToPurge.remove(0)); // log that precedes first retained snapshot is also retained
@@ -347,8 +326,7 @@ public class PurgeTxnTest extends ZKTestCase {
* verify these values are parsed properly and functionality works fine
*/
@Test
- public void testPurgeTxnLogWithDataDir()
- throws Exception {
+ public void testPurgeTxnLogWithDataDir() throws Exception {
tmpDir = ClientBase.createTmpDir();
File dataDir = new File(tmpDir, "dataDir");
File dataLogDir = new File(tmpDir, "dataLogDir");
@@ -365,20 +343,16 @@ public class PurgeTxnTest extends ZKTestCase {
// directories
for (int i = 0; i < totalFiles; i++) {
// simulate log file
- File logFile = new File(dataLogDirVersion2, "log."
- + Long.toHexString(i));
+ File logFile = new File(dataLogDirVersion2, "log." + Long.toHexString(i));
logFile.createNewFile();
// simulate snapshot file
- File snapFile = new File(dataDirVersion2, "snapshot."
- + Long.toHexString(i));
+ File snapFile = new File(dataDirVersion2, "snapshot." + Long.toHexString(i));
snapFile.createNewFile();
}
int numberOfSnapFilesToKeep = 10;
// scenario where four parameter are passed
- String[] args = new String[] { dataLogDir.getAbsolutePath(),
- dataDir.getAbsolutePath(), "-n",
- Integer.toString(numberOfSnapFilesToKeep) };
+ String[] args = new String[]{dataLogDir.getAbsolutePath(), dataDir.getAbsolutePath(), "-n", Integer.toString(numberOfSnapFilesToKeep)};
PurgeTxnLog.main(args);
assertEquals(numberOfSnapFilesToKeep, dataDirVersion2.listFiles().length);
@@ -393,8 +367,7 @@ public class PurgeTxnTest extends ZKTestCase {
* these values are parsed properly and functionality works fine
*/
@Test
- public void testPurgeTxnLogWithoutDataDir()
- throws Exception {
+ public void testPurgeTxnLogWithoutDataDir() throws Exception {
tmpDir = ClientBase.createTmpDir();
File dataDir = new File(tmpDir, "dataDir");
File dataLogDir = new File(tmpDir, "dataLogDir");
@@ -410,21 +383,20 @@ public class PurgeTxnTest extends ZKTestCase {
// create transaction and snapshot files in data directory
for (int i = 0; i < totalFiles; i++) {
// simulate log file
- File logFile = new File(dataLogDirVersion2, "log."
- + Long.toHexString(i));
+ File logFile = new File(dataLogDirVersion2, "log." + Long.toHexString(i));
logFile.createNewFile();
// simulate snapshot file
- File snapFile = new File(dataLogDirVersion2, "snapshot."
- + Long.toHexString(i));
+ File snapFile = new File(dataLogDirVersion2, "snapshot." + Long.toHexString(i));
snapFile.createNewFile();
}
int numberOfSnapFilesToKeep = 10;
// scenario where only three parameter are passed
- String[] args = new String[] { dataLogDir.getAbsolutePath(), "-n",
- Integer.toString(numberOfSnapFilesToKeep) };
+ String[] args = new String[]{dataLogDir.getAbsolutePath(), "-n", Integer.toString(numberOfSnapFilesToKeep)};
PurgeTxnLog.main(args);
- assertEquals(numberOfSnapFilesToKeep * 2, // Since for each snapshot we have a log file with same zxid, expect same # logs as snaps to be kept
+ assertEquals(
+ numberOfSnapFilesToKeep
+ * 2, // Since for each snapshot we have a log file with same zxid, expect same # logs as snaps to be kept
dataLogDirVersion2.listFiles().length);
ClientBase.recursiveDelete(tmpDir);
@@ -457,8 +429,7 @@ public class PurgeTxnTest extends ZKTestCase {
final int PORT = Integer.parseInt(HOSTPORT.split(":")[1]);
ServerCnxnFactory f = ServerCnxnFactory.createFactory(PORT, -1);
f.startup(zks);
- Assert.assertTrue("waiting for server being up ",
- ClientBase.waitForServerUp(HOSTPORT,CONNECTION_TIMEOUT));
+ assertTrue("waiting for server being up ", ClientBase.waitForServerUp(HOSTPORT, CONNECTION_TIMEOUT));
ZooKeeper zk = ClientBase.createZKClient(HOSTPORT);
// Unique identifier for each znode that we create.
@@ -469,16 +440,14 @@ public class PurgeTxnTest extends ZKTestCase {
* snapshots. Do not rollover the log.
*/
for (int snapshotCount = 0; snapshotCount < SNAP_RETAIN_COUNT; snapshotCount++) {
- for (int i = 0; i< 100; i++, unique++) {
- zk.create("/snap-" + unique, new byte[0], Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ for (int i = 0; i < 100; i++, unique++) {
+ zk.create("/snap-" + unique, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
}
zks.takeSnapshot();
}
// Create some additional znodes without taking a snapshot afterwards.
- for (int i = 0; i< 100; i++, unique++) {
- zk.create("/snap-" + unique, new byte[0], Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ for (int i = 0; i < 100; i++, unique++) {
+ zk.create("/snap-" + unique, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
}
} finally {
zk.close();
@@ -488,8 +457,7 @@ public class PurgeTxnTest extends ZKTestCase {
f.shutdown();
zks.getTxnLogFactory().close();
zks.shutdown();
- Assert.assertTrue("waiting for server to shutdown",
- ClientBase.waitForServerDown(HOSTPORT, CONNECTION_TIMEOUT));
+ assertTrue("waiting for server to shutdown", ClientBase.waitForServerDown(HOSTPORT, CONNECTION_TIMEOUT));
// Purge snapshot and log files.
PurgeTxnLog.purge(tmpDir, tmpDir, SNAP_RETAIN_COUNT);
@@ -508,7 +476,7 @@ public class PurgeTxnTest extends ZKTestCase {
*/
final String lastZnode = "/snap-" + (unique - 1);
final Stat stat = zk.exists(lastZnode, false);
- Assert.assertNotNull("Last znode does not exist: " + lastZnode, stat);
+ assertNotNull("Last znode does not exist: " + lastZnode, stat);
// Shutdown for the last time.
f.shutdown();
@@ -518,14 +486,11 @@ public class PurgeTxnTest extends ZKTestCase {
private File createDataDirLogFile(File version_2, int Zxid) throws IOException {
File logFile = new File(version_2 + "/log." + Long.toHexString(Zxid));
- Assert.assertTrue("Failed to create log File:" + logFile.toString(),
- logFile.createNewFile());
+ assertTrue("Failed to create log File:" + logFile.toString(), logFile.createNewFile());
return logFile;
}
- private void createDataDirFiles(AtomicInteger offset, int limit, boolean createPrecedingLogFile,
- File version_2, List<File> snaps, List<File> logs)
- throws IOException {
+ private void createDataDirFiles(AtomicInteger offset, int limit, boolean createPrecedingLogFile, File version_2, List<File> snaps, List<File> logs) throws IOException {
int counter = offset.get() + (2 * limit);
if (createPrecedingLogFile) {
counter++;
@@ -535,10 +500,8 @@ public class PurgeTxnTest extends ZKTestCase {
// simulate log file
logs.add(createDataDirLogFile(version_2, --counter));
// simulate snapshot file
- File snapFile = new File(version_2 + "/snapshot."
- + Long.toHexString(--counter));
- Assert.assertTrue("Failed to create snap File:" + snapFile.toString(),
- snapFile.createNewFile());
+ File snapFile = new File(version_2 + "/snapshot." + Long.toHexString(--counter));
+ assertTrue("Failed to create snap File:" + snapFile.toString(), snapFile.createNewFile());
snaps.add(snapFile);
}
if (createPrecedingLogFile) {
@@ -548,16 +511,13 @@ public class PurgeTxnTest extends ZKTestCase {
private void verifyFilesAfterPurge(List<File> logs, boolean exists) {
for (File file : logs) {
- Assert.assertEquals("After purging, file " + file, exists,
- file.exists());
+ assertEquals("After purging, file " + file, exists, file.exists());
}
}
- private List<String> manyClientOps(final ZooKeeper zk,
- final CountDownLatch doPurge, int thCount, final String prefix) {
+ private List<String> manyClientOps(final ZooKeeper zk, final CountDownLatch doPurge, int thCount, final String prefix) {
Thread[] ths = new Thread[thCount];
- final List<String> znodes = Collections
- .synchronizedList(new ArrayList<String>());
+ final List<String> znodes = Collections.synchronizedList(new ArrayList<String>());
final CountDownLatch finished = new CountDownLatch(thCount);
for (int indx = 0; indx < thCount; indx++) {
final String myprefix = prefix + "-" + indx;
@@ -567,8 +527,7 @@ public class PurgeTxnTest extends ZKTestCase {
try {
String mynode = myprefix + "-" + i;
znodes.add(mynode);
- zk.create(mynode, new byte[0], Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk.create(mynode, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
} catch (Exception e) {
LOG.error("Unexpected exception occurred!", e);
}
@@ -577,7 +536,7 @@ public class PurgeTxnTest extends ZKTestCase {
}
}
finished.countDown();
- };
+ }
};
ths[indx] = th;
}
@@ -586,12 +545,12 @@ public class PurgeTxnTest extends ZKTestCase {
thread.start();
}
try {
- Assert.assertTrue("ZkClient ops is not finished!",
- finished.await(OP_TIMEOUT_IN_MILLIS, TimeUnit.MILLISECONDS));
+ assertTrue("ZkClient ops is not finished!", finished.await(OP_TIMEOUT_IN_MILLIS, TimeUnit.MILLISECONDS));
} catch (InterruptedException ie) {
LOG.error("Unexpected exception occurred!", ie);
- Assert.fail("Unexpected exception occurred!");
+ fail("Unexpected exception occurred!");
}
return znodes;
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/ReferenceCountedACLCacheTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/ReferenceCountedACLCacheTest.java
index 795472f14..6bb5d954c 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/ReferenceCountedACLCacheTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/ReferenceCountedACLCacheTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,24 +18,24 @@
package org.apache.zookeeper.server;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.fail;
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
import org.apache.jute.BinaryInputArchive;
import org.apache.jute.BinaryOutputArchive;
-import org.apache.jute.InputArchive;
import org.apache.jute.OutputArchive;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.data.ACL;
import org.apache.zookeeper.data.Id;
import org.junit.Test;
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.List;
-
-import static org.junit.Assert.*;
-
public class ReferenceCountedACLCacheTest {
+
@Test
public void testSameACLGivesSameID() {
List<ACL> testACL = createACL("myid");
@@ -195,7 +195,7 @@ public class ReferenceCountedACLCacheTest {
@Test
public void testNPEInDeserialize() throws IOException {
- ReferenceCountedACLCache serializeCache = new ReferenceCountedACLCache(){
+ ReferenceCountedACLCache serializeCache = new ReferenceCountedACLCache() {
@Override
public synchronized void serialize(OutputArchive oa) throws IOException {
oa.writeInt(1, "map");
@@ -211,15 +211,14 @@ public class ReferenceCountedACLCacheTest {
ReferenceCountedACLCache deserializedCache = new ReferenceCountedACLCache();
try {
deserializedCache.deserialize(inArchive);
- } catch (NullPointerException e){
+ } catch (NullPointerException e) {
fail("should not throw NPE while do deserialized");
} catch (RuntimeException e) {
// do nothing.
}
}
-
- private void assertCachesEqual(ReferenceCountedACLCache expected, ReferenceCountedACLCache actual){
+ private void assertCachesEqual(ReferenceCountedACLCache expected, ReferenceCountedACLCache actual) {
assertEquals(expected.aclIndex, actual.aclIndex);
assertEquals(expected.aclKeyMap, actual.aclKeyMap);
assertEquals(expected.longKeyMap, actual.longKeyMap);
@@ -272,7 +271,7 @@ public class ReferenceCountedACLCacheTest {
return -1L;
}
- for (int i = 0; i < num -1; i++) {
+ for (int i = 0; i < num - 1; i++) {
cache.convertAcls(acl);
}
@@ -284,4 +283,5 @@ public class ReferenceCountedACLCacheTest {
acl1.add(new ACL(ZooDefs.Perms.ADMIN, new Id("scheme", id)));
return acl1;
}
-} \ No newline at end of file
+
+}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/RequestThrottlerTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/RequestThrottlerTest.java
index 9eee9269c..db40d86fd 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/RequestThrottlerTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/RequestThrottlerTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,40 +18,34 @@
package org.apache.zookeeper.server;
+import static org.apache.zookeeper.test.ClientBase.CONNECTION_TIMEOUT;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import java.io.File;
+import java.io.IOException;
+import java.util.Map;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.PortAssignment;
import org.apache.zookeeper.ZKTestCase;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;
-import org.apache.zookeeper.common.Time;
import org.apache.zookeeper.metrics.MetricsUtils;
import org.apache.zookeeper.test.ClientBase;
import org.junit.After;
-import org.junit.AfterClass;
-import org.junit.Assert;
import org.junit.Before;
-import org.junit.BeforeClass;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.io.File;
-import java.io.IOException;
-import java.util.Map;
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.TimeUnit;
-
-import static org.apache.zookeeper.test.ClientBase.CONNECTION_TIMEOUT;
-import static org.hamcrest.Matchers.greaterThan;
-import static org.hamcrest.Matchers.greaterThanOrEqualTo;
-import static org.hamcrest.Matchers.lessThan;
-
public class RequestThrottlerTest extends ZKTestCase {
+
private static final Logger LOG = LoggerFactory.getLogger(RequestThrottlerTest.class);
private static String HOSTPORT = "127.0.0.1:" + PortAssignment.unique();
- private final static int TOTAL_REQUESTS = 5;
- private final static int STALL_TIME = 5000;
+ private static final int TOTAL_REQUESTS = 5;
+ private static final int STALL_TIME = 5000;
// latch to hold requests in the PrepRequestProcessor to
// keep them from going down the pipeline to reach the final
@@ -79,8 +73,7 @@ public class RequestThrottlerTest extends ZKTestCase {
f = ServerCnxnFactory.createFactory(PORT, -1);
f.startup(zks);
LOG.info("starting up the zookeeper server .. waiting");
- Assert.assertTrue("waiting for server being up",
- ClientBase.waitForServerUp(HOSTPORT, CONNECTION_TIMEOUT));
+ assertTrue("waiting for server being up", ClientBase.waitForServerUp(HOSTPORT, CONNECTION_TIMEOUT));
resumeProcess = null;
submitted = null;
@@ -107,6 +100,7 @@ public class RequestThrottlerTest extends ZKTestCase {
// 1. uses our version of PrepRequestProcessor, which can hold the request as long as we want
// 2. count the number of submitted requests
class TestZooKeeperServer extends ZooKeeperServer {
+
public TestZooKeeperServer(File snapDir, File logDir, int tickTime) throws IOException {
super(snapDir, logDir, tickTime);
}
@@ -114,8 +108,7 @@ public class RequestThrottlerTest extends ZKTestCase {
@Override
protected void setupRequestProcessors() {
RequestProcessor finalProcessor = new FinalRequestProcessor(this);
- RequestProcessor syncProcessor = new SyncRequestProcessor(this,
- finalProcessor);
+ RequestProcessor syncProcessor = new SyncRequestProcessor(this, finalProcessor);
((SyncRequestProcessor) syncProcessor).start();
firstProcessor = new TestPrepRequestProcessor(this, syncProcessor);
((TestPrepRequestProcessor) firstProcessor).start();
@@ -128,9 +121,11 @@ public class RequestThrottlerTest extends ZKTestCase {
}
super.submitRequest(si);
}
+
}
class TestPrepRequestProcessor extends PrepRequestProcessor {
+
public TestPrepRequestProcessor(ZooKeeperServer zks, RequestProcessor syncProcessor) {
super(zks, syncProcessor);
}
@@ -152,6 +147,7 @@ public class RequestThrottlerTest extends ZKTestCase {
super.pRequest(request);
}
+
}
@Test
@@ -170,9 +166,10 @@ public class RequestThrottlerTest extends ZKTestCase {
entered = new CountDownLatch(TOTAL_REQUESTS);
// send 5 requests asynchronously
- for (int i =0; i < TOTAL_REQUESTS; i++) {
- zk.create("/request_throttle_test- " + i , ("/request_throttle_test- " + i).getBytes(),
- ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT, (rc, path, ctx, name) -> {}, null);
+ for (int i = 0; i < TOTAL_REQUESTS; i++) {
+ zk.create("/request_throttle_test- " + i, ("/request_throttle_test- "
+ + i).getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT, (rc, path, ctx, name) -> {
+ }, null);
}
// make sure the server received all 5 requests
@@ -180,8 +177,8 @@ public class RequestThrottlerTest extends ZKTestCase {
Map<String, Object> metrics = MetricsUtils.currentServerMetrics();
// but only two requests can get into the pipeline because of the throttler
- Assert.assertEquals(2L, (long)metrics.get("prep_processor_request_queued"));
- Assert.assertEquals(1L, (long)metrics.get("request_throttle_wait_count"));
+ assertEquals(2L, (long) metrics.get("prep_processor_request_queued"));
+ assertEquals(1L, (long) metrics.get("request_throttle_wait_count"));
// let the requests go through the pipeline and the throttler will be waken up to allow more requests
// to enter the pipeline
@@ -189,7 +186,7 @@ public class RequestThrottlerTest extends ZKTestCase {
entered.await(STALL_TIME, TimeUnit.MILLISECONDS);
metrics = MetricsUtils.currentServerMetrics();
- Assert.assertEquals(TOTAL_REQUESTS, (long)metrics.get("prep_processor_request_queued"));
+ assertEquals(TOTAL_REQUESTS, (long) metrics.get("prep_processor_request_queued"));
}
@Test
@@ -208,9 +205,10 @@ public class RequestThrottlerTest extends ZKTestCase {
submitted = new CountDownLatch(TOTAL_REQUESTS);
// send 5 requests asynchronously
- for (int i=0; i<TOTAL_REQUESTS; i++) {
- zk.create("/request_throttle_test- " + i , ("/request_throttle_test- " + i).getBytes(),
- ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT, (rc, path, ctx, name) -> {}, null);
+ for (int i = 0; i < TOTAL_REQUESTS; i++) {
+ zk.create("/request_throttle_test- " + i, ("/request_throttle_test- "
+ + i).getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT, (rc, path, ctx, name) -> {
+ }, null);
}
// make sure the server received all 5 requests
@@ -218,10 +216,10 @@ public class RequestThrottlerTest extends ZKTestCase {
Map<String, Object> metrics = MetricsUtils.currentServerMetrics();
// but only two requests can get into the pipeline because of the throttler
- Assert.assertEquals(2L, (long)metrics.get("prep_processor_request_queued"));
- Assert.assertEquals(1L, (long)metrics.get("request_throttle_wait_count"));
+ assertEquals(2L, (long) metrics.get("prep_processor_request_queued"));
+ assertEquals(1L, (long) metrics.get("request_throttle_wait_count"));
- for (ServerCnxn cnxn : f.cnxns){
+ for (ServerCnxn cnxn : f.cnxns) {
cnxn.setStale();
}
zk = null;
@@ -236,7 +234,8 @@ public class RequestThrottlerTest extends ZKTestCase {
// the rest of the 3 requests will be dropped
// but only the first one for a connection will be counted
metrics = MetricsUtils.currentServerMetrics();
- Assert.assertEquals(2L, (long)metrics.get("prep_processor_request_queued"));
- Assert.assertEquals(1, (long)metrics.get("stale_requests_dropped"));
+ assertEquals(2L, (long) metrics.get("prep_processor_request_queued"));
+ assertEquals(1, (long) metrics.get("stale_requests_dropped"));
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/SerializationPerfTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/SerializationPerfTest.java
index 43982322d..5a0fbef72 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/SerializationPerfTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/SerializationPerfTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -20,25 +20,26 @@ package org.apache.zookeeper.server;
import java.io.IOException;
import java.io.OutputStream;
-
import org.apache.jute.BinaryOutputArchive;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZKTestCase;
import org.junit.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
public class SerializationPerfTest extends ZKTestCase {
+
protected static final Logger LOG = LoggerFactory.getLogger(SerializationPerfTest.class);
private static class NullOutputStream extends OutputStream {
+
public void write(int b) {
// do nothing - exclude persistence from perf
}
+
}
- static int createNodes(DataTree tree, String path, int depth,
- int childcount, int parentCVersion, byte[] data) throws KeeperException.NodeExistsException, KeeperException.NoNodeException {
+ static int createNodes(DataTree tree, String path, int depth, int childcount, int parentCVersion, byte[] data) throws KeeperException.NodeExistsException, KeeperException.NoNodeException {
path += "node" + depth;
tree.createNode(path, data, null, -1, ++parentCVersion, 1, 1);
@@ -56,70 +57,64 @@ public class SerializationPerfTest extends ZKTestCase {
return count;
}
- private static void serializeTree(int depth, int width, int len)
- throws InterruptedException, IOException, KeeperException.NodeExistsException, KeeperException.NoNodeException {
+ private static void serializeTree(int depth, int width, int len) throws InterruptedException, IOException, KeeperException.NodeExistsException, KeeperException.NoNodeException {
DataTree tree = new DataTree();
createNodes(tree, "/", depth, width, tree.getNode("/").stat.getCversion(), new byte[len]);
int count = tree.getNodeCount();
- BinaryOutputArchive oa =
- BinaryOutputArchive.getArchive(new NullOutputStream());
+ BinaryOutputArchive oa = BinaryOutputArchive.getArchive(new NullOutputStream());
System.gc();
long start = System.nanoTime();
tree.serialize(oa, "test");
long end = System.nanoTime();
- long durationms = (end - start)/1000000L;
- long pernodeus = ((end - start)/1000L)/count;
- LOG.info("Serialized " + count + " nodes in "
- + durationms + " ms (" + pernodeus + "us/node), depth="
- + depth + " width=" + width + " datalen=" + len);
+ long durationms = (end - start) / 1000000L;
+ long pernodeus = ((end - start) / 1000L) / count;
+ LOG.info("Serialized "
+ + count + " nodes in "
+ + durationms + " ms ("
+ + pernodeus + "us/node), depth=" + depth
+ + " width=" + width
+ + " datalen=" + len);
}
@Test
- public void testSingleSerialize()
- throws InterruptedException, IOException, KeeperException.NodeExistsException, KeeperException.NoNodeException {
+ public void testSingleSerialize() throws InterruptedException, IOException, KeeperException.NodeExistsException, KeeperException.NoNodeException {
serializeTree(1, 0, 20);
}
@Test
- public void testWideSerialize()
- throws InterruptedException, IOException, KeeperException.NodeExistsException, KeeperException.NoNodeException {
+ public void testWideSerialize() throws InterruptedException, IOException, KeeperException.NodeExistsException, KeeperException.NoNodeException {
serializeTree(2, 10000, 20);
}
@Test
- public void testDeepSerialize()
- throws InterruptedException, IOException, KeeperException.NodeExistsException, KeeperException.NoNodeException {
+ public void testDeepSerialize() throws InterruptedException, IOException, KeeperException.NodeExistsException, KeeperException.NoNodeException {
serializeTree(400, 1, 20);
}
@Test
- public void test10Wide5DeepSerialize()
- throws InterruptedException, IOException, KeeperException.NodeExistsException, KeeperException.NoNodeException {
+ public void test10Wide5DeepSerialize() throws InterruptedException, IOException, KeeperException.NodeExistsException, KeeperException.NoNodeException {
serializeTree(5, 10, 20);
}
@Test
- public void test15Wide5DeepSerialize()
- throws InterruptedException, IOException, KeeperException.NodeExistsException, KeeperException.NoNodeException {
+ public void test15Wide5DeepSerialize() throws InterruptedException, IOException, KeeperException.NodeExistsException, KeeperException.NoNodeException {
serializeTree(5, 15, 20);
}
@Test
- public void test25Wide4DeepSerialize()
- throws InterruptedException, IOException, KeeperException.NodeExistsException, KeeperException.NoNodeException {
+ public void test25Wide4DeepSerialize() throws InterruptedException, IOException, KeeperException.NodeExistsException, KeeperException.NoNodeException {
serializeTree(4, 25, 20);
}
@Test
- public void test40Wide4DeepSerialize()
- throws InterruptedException, IOException, KeeperException.NodeExistsException, KeeperException.NoNodeException {
+ public void test40Wide4DeepSerialize() throws InterruptedException, IOException, KeeperException.NodeExistsException, KeeperException.NoNodeException {
serializeTree(4, 40, 20);
}
@Test
- public void test300Wide3DeepSerialize()
- throws InterruptedException, IOException, KeeperException.NodeExistsException, KeeperException.NoNodeException {
+ public void test300Wide3DeepSerialize() throws InterruptedException, IOException, KeeperException.NodeExistsException, KeeperException.NoNodeException {
serializeTree(3, 300, 20);
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/ServerIdTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/ServerIdTest.java
index a04c37b35..3f3f4964a 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/ServerIdTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/ServerIdTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,6 +18,9 @@
package org.apache.zookeeper.server;
+import static org.junit.Assert.fail;
+import java.util.ArrayList;
+import java.util.List;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.TestableZooKeeper;
@@ -26,21 +29,19 @@ import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.data.Stat;
import org.apache.zookeeper.test.ClientBase;
import org.junit.After;
-import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
-import java.util.ArrayList;
-import java.util.List;
-
@RunWith(Parameterized.class)
@Parameterized.UseParametersRunnerFactory(ZKParameterized.RunnerFactory.class)
public class ServerIdTest extends ClientBase {
+
private final TestType testType;
private static class TestType {
+
final boolean ttlsEnabled;
final int serverId;
@@ -48,13 +49,14 @@ public class ServerIdTest extends ClientBase {
this.ttlsEnabled = ttlsEnabled;
this.serverId = serverId;
}
+
}
@Parameterized.Parameters
public static List<TestType> data() {
List<TestType> testTypes = new ArrayList<>();
- for ( boolean ttlsEnabled : new boolean[]{true, false} ) {
- for ( int serverId = 0; serverId <= 255; ++serverId ) {
+ for (boolean ttlsEnabled : new boolean[]{true, false}) {
+ for (int serverId = 0; serverId <= 255; ++serverId) {
testTypes.add(new TestType(ttlsEnabled, serverId));
}
}
@@ -80,7 +82,7 @@ public class ServerIdTest extends ClientBase {
try {
super.setUpWithServerId(testType.serverId);
} catch (RuntimeException e) {
- if ( testType.ttlsEnabled && (testType.serverId >= EphemeralType.MAX_EXTENDED_SERVER_ID) ) {
+ if (testType.ttlsEnabled && (testType.serverId >= EphemeralType.MAX_EXTENDED_SERVER_ID)) {
return; // expected
}
throw e;
@@ -89,7 +91,7 @@ public class ServerIdTest extends ClientBase {
@Test
public void doTest() throws Exception {
- if ( testType.ttlsEnabled && (testType.serverId >= EphemeralType.MAX_EXTENDED_SERVER_ID) ) {
+ if (testType.ttlsEnabled && (testType.serverId >= EphemeralType.MAX_EXTENDED_SERVER_ID)) {
return;
}
@@ -100,20 +102,21 @@ public class ServerIdTest extends ClientBase {
zk.create("/foo", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
zk.delete("/foo", -1);
- if ( testType.ttlsEnabled ) {
+ if (testType.ttlsEnabled) {
zk.create("/foo", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_WITH_TTL, new Stat(), 1000); // should work
} else {
try {
zk.create("/foo", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_WITH_TTL, new Stat(), 1000);
- Assert.fail("Should have thrown KeeperException.UnimplementedException");
+ fail("Should have thrown KeeperException.UnimplementedException");
} catch (KeeperException.UnimplementedException e) {
// expected
}
}
} finally {
- if ( zk != null ) {
+ if (zk != null) {
zk.close();
}
}
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/ServerMetricsTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/ServerMetricsTest.java
index a71b3e26d..29a9fd96b 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/ServerMetricsTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/ServerMetricsTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,17 +18,17 @@
package org.apache.zookeeper.server;
+import static org.junit.Assert.assertEquals;
+import java.util.Arrays;
+import java.util.Map;
+import java.util.concurrent.ThreadLocalRandom;
import org.apache.zookeeper.ZKTestCase;
import org.apache.zookeeper.server.metric.AvgMinMaxCounter;
import org.apache.zookeeper.server.metric.SimpleCounter;
-import org.junit.Assert;
import org.junit.Test;
-import java.util.Arrays;
-import java.util.Map;
-import java.util.concurrent.ThreadLocalRandom;
-
public class ServerMetricsTest extends ZKTestCase {
+
private static final int RANDOM_TRIALS = 100;
private static final int RANDOM_SIZE = 100;
@@ -67,17 +67,17 @@ public class ServerMetricsTest extends ZKTestCase {
long expectedCnt = values.length;
double expectedAvg = expectedSum / Math.max(1, expectedCnt);
- Assert.assertEquals(expectedAvg, metric.getAvg(), (double)200);
- Assert.assertEquals(expectedMin, metric.getMin());
- Assert.assertEquals(expectedMax, metric.getMax());
- Assert.assertEquals(expectedCnt, metric.getCount());
- Assert.assertEquals(expectedSum, metric.getTotal());
+ assertEquals(expectedAvg, metric.getAvg(), 200);
+ assertEquals(expectedMin, metric.getMin());
+ assertEquals(expectedMax, metric.getMax());
+ assertEquals(expectedCnt, metric.getCount());
+ assertEquals(expectedSum, metric.getTotal());
final Map<String, Object> results = metric.values();
- Assert.assertEquals(expectedMax, (long)results.get("max_test"));
- Assert.assertEquals(expectedMin, (long)results.get("min_test"));
- Assert.assertEquals(expectedCnt, (long)results.get("cnt_test"));
- Assert.assertEquals(expectedAvg, (double)results.get("avg_test"), (double)200);
+ assertEquals(expectedMax, (long) results.get("max_test"));
+ assertEquals(expectedMin, (long) results.get("min_test"));
+ assertEquals(expectedCnt, (long) results.get("cnt_test"));
+ assertEquals(expectedAvg, (double) results.get("avg_test"), 200);
metric.reset();
}
@@ -99,11 +99,12 @@ public class ServerMetricsTest extends ZKTestCase {
}
long expectedCount = Arrays.stream(values).sum();
- Assert.assertEquals(expectedCount, metric.get());
+ assertEquals(expectedCount, metric.get());
final Map<String, Object> results = metric.values();
- Assert.assertEquals(expectedCount, (long)results.get("test"));
+ assertEquals(expectedCount, (long) results.get("test"));
metric.reset();
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/ServerStatsTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/ServerStatsTest.java
index 357b73e18..05a35058e 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/ServerStatsTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/ServerStatsTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,14 +18,14 @@
package org.apache.zookeeper.server;
-import org.apache.zookeeper.ZKTestCase;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
import static org.hamcrest.MatcherAssert.assertThat;
-import static org.mockito.Mockito.mock;
import static org.hamcrest.Matchers.lessThanOrEqualTo;
+import static org.junit.Assert.assertEquals;
+import static org.mockito.Mockito.mock;
+import org.apache.zookeeper.ZKTestCase;
+import org.junit.Before;
+import org.junit.Test;
public class ServerStatsTest extends ZKTestCase {
@@ -50,8 +50,8 @@ public class ServerStatsTest extends ZKTestCase {
}
// Then ...
- Assert.assertEquals(incrementCount, serverStats.getPacketsSent());
- Assert.assertEquals(incrementCount*2, serverStats.getPacketsReceived());
+ assertEquals(incrementCount, serverStats.getPacketsSent());
+ assertEquals(incrementCount * 2, serverStats.getPacketsReceived());
// When reset ...
serverStats.resetRequestCounters();
@@ -72,11 +72,9 @@ public class ServerStatsTest extends ZKTestCase {
serverStats.updateLatency(fakeRequest, fakeRequest.createTime + 2000);
// Then ...
- assertThat("Max latency check", 2000L,
- lessThanOrEqualTo(serverStats.getMaxLatency()));
- assertThat("Min latency check", 1000L,
- lessThanOrEqualTo(serverStats.getMinLatency()));
- Assert.assertEquals((double)1500, serverStats.getAvgLatency(), (double)200);
+ assertThat("Max latency check", 2000L, lessThanOrEqualTo(serverStats.getMaxLatency()));
+ assertThat("Min latency check", 1000L, lessThanOrEqualTo(serverStats.getMinLatency()));
+ assertEquals(1500, serverStats.getAvgLatency(), 200);
// When reset...
serverStats.resetLatency();
@@ -97,7 +95,7 @@ public class ServerStatsTest extends ZKTestCase {
}
// Then ...
- Assert.assertEquals(incrementCount, serverStats.getFsyncThresholdExceedCount());
+ assertEquals(incrementCount, serverStats.getFsyncThresholdExceedCount());
// When reset ...
serverStats.resetFsyncThresholdExceedCount();
@@ -129,17 +127,18 @@ public class ServerStatsTest extends ZKTestCase {
}
private void assertAllPacketsZero(ServerStats serverStats) {
- Assert.assertEquals(0L, serverStats.getPacketsSent());
- Assert.assertEquals(0L, serverStats.getPacketsReceived());
+ assertEquals(0L, serverStats.getPacketsSent());
+ assertEquals(0L, serverStats.getPacketsReceived());
}
private void assertAllLatencyZero(ServerStats serverStats) {
- Assert.assertEquals(0L, serverStats.getMaxLatency());
- Assert.assertEquals(0L, serverStats.getMinLatency());
- Assert.assertEquals((double)0, serverStats.getAvgLatency(), (double)0.00001);
+ assertEquals(0L, serverStats.getMaxLatency());
+ assertEquals(0L, serverStats.getMinLatency());
+ assertEquals(0, serverStats.getAvgLatency(), 0.00001);
}
private void assertFsyncThresholdExceedCountZero(ServerStats serverStats) {
- Assert.assertEquals(0L, serverStats.getFsyncThresholdExceedCount());
+ assertEquals(0L, serverStats.getFsyncThresholdExceedCount());
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/SessionTrackerTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/SessionTrackerTest.java
index c2e0b1200..c00855077 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/SessionTrackerTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/SessionTrackerTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,21 +18,22 @@
package org.apache.zookeeper.server;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
-
-
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZKTestCase;
import org.apache.zookeeper.ZooDefs.OpCode;
import org.apache.zookeeper.server.SessionTrackerImpl.SessionImpl;
import org.apache.zookeeper.test.ClientBase;
-import org.junit.Assert;
import org.junit.Test;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
/**
* Testing zk client session logic in sessiontracker
@@ -56,10 +57,8 @@ public class SessionTrackerTest extends ZKTestCase {
latch = new CountDownLatch(1);
zks.sessionTracker.trackSession(sessionId, sessionTimeout);
SessionTrackerImpl sessionTrackerImpl = (SessionTrackerImpl) zks.sessionTracker;
- SessionImpl sessionImpl = sessionTrackerImpl.sessionsById
- .get(sessionId);
- Assert.assertNotNull("Sessionid:" + sessionId
- + " doesn't exists in sessiontracker", sessionImpl);
+ SessionImpl sessionImpl = sessionTrackerImpl.sessionsById.get(sessionId);
+ assertNotNull("Sessionid:" + sessionId + " doesn't exists in sessiontracker", sessionImpl);
// verify the session existence
Object sessionOwner = new Object();
@@ -74,17 +73,13 @@ public class SessionTrackerTest extends ZKTestCase {
sessionTrackerImpl.trackSession(sessionId, sessionTimeout);
try {
sessionTrackerImpl.checkSession(sessionId, sessionOwner);
- Assert.fail("Should throw session expiry exception "
- + "as the session has expired and closed");
+ fail("Should throw session expiry exception " + "as the session has expired and closed");
} catch (KeeperException.SessionExpiredException e) {
// expected behaviour
}
- Assert.assertTrue("Session didn't expired", sessionImpl.isClosing());
- Assert.assertFalse("Session didn't expired", sessionTrackerImpl
- .touchSession(sessionId, sessionTimeout));
- Assert.assertEquals(
- "Duplicate session expiry request has been generated", 1,
- firstProcessor.getCountOfCloseSessionReq());
+ assertTrue("Session didn't expired", sessionImpl.isClosing());
+ assertFalse("Session didn't expired", sessionTrackerImpl.touchSession(sessionId, sessionTimeout));
+ assertEquals("Duplicate session expiry request has been generated", 1, firstProcessor.getCountOfCloseSessionReq());
}
/**
@@ -98,10 +93,8 @@ public class SessionTrackerTest extends ZKTestCase {
latch = new CountDownLatch(1);
zks.sessionTracker.trackSession(sessionId, sessionTimeout);
SessionTrackerImpl sessionTrackerImpl = (SessionTrackerImpl) zks.sessionTracker;
- SessionImpl sessionImpl = sessionTrackerImpl.sessionsById
- .get(sessionId);
- Assert.assertNotNull("Sessionid:" + sessionId
- + " doesn't exists in sessiontracker", sessionImpl);
+ SessionImpl sessionImpl = sessionTrackerImpl.sessionsById.get(sessionId);
+ assertNotNull("Sessionid:" + sessionId + " doesn't exists in sessiontracker", sessionImpl);
// verify the session existence
Object sessionOwner = new Object();
@@ -113,10 +106,8 @@ public class SessionTrackerTest extends ZKTestCase {
// Simulating close session request: removeSession() will be executed
// while OpCode.closeSession
sessionTrackerImpl.removeSession(sessionId);
- SessionImpl actualSession = sessionTrackerImpl.sessionsById
- .get(sessionId);
- Assert.assertNull("Session:" + sessionId
- + " still exists after removal", actualSession);
+ SessionImpl actualSession = sessionTrackerImpl.sessionsById.get(sessionId);
+ assertNull("Session:" + sessionId + " still exists after removal", actualSession);
}
private ZooKeeperServer setupSessionTracker() throws IOException {
@@ -136,10 +127,10 @@ public class SessionTrackerTest extends ZKTestCase {
// Mock processor used in zookeeper server
private class FirstProcessor extends PrepRequestProcessor {
+
private volatile int countOfCloseSessionReq = 0;
- public FirstProcessor(ZooKeeperServer zks,
- RequestProcessor nextProcessor) {
+ public FirstProcessor(ZooKeeperServer zks, RequestProcessor nextProcessor) {
super(zks, nextProcessor);
}
@@ -156,5 +147,7 @@ public class SessionTrackerTest extends ZKTestCase {
int getCountOfCloseSessionReq() {
return countOfCloseSessionReq;
}
+
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/SnapshotDigestTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/SnapshotDigestTest.java
index f74eb03f1..b3459a159 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/SnapshotDigestTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/SnapshotDigestTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,12 +18,13 @@
package org.apache.zookeeper.server;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNull;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
-
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.Op;
import org.apache.zookeeper.ZooDefs;
@@ -34,21 +35,16 @@ import org.apache.zookeeper.server.persistence.FileTxnSnapLog;
import org.apache.zookeeper.server.quorum.QuorumPeerMainTest;
import org.apache.zookeeper.server.util.DigestCalculator;
import org.apache.zookeeper.test.ClientBase;
-
import org.junit.After;
-import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
-
import org.mockito.Mockito;
-
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class SnapshotDigestTest extends ClientBase {
- private static final Logger LOG = LoggerFactory.getLogger(
- SnapshotDigestTest.class);
+ private static final Logger LOG = LoggerFactory.getLogger(SnapshotDigestTest.class);
private ZooKeeper zk;
private ZooKeeperServer server;
@@ -89,15 +85,14 @@ public class SnapshotDigestTest extends ClientBase {
public void testSnapshotDigest() throws Exception {
// take a empty snapshot without creating any txn and make sure
// there is no digest mismatch issue
- server.takeSnapshot();
+ server.takeSnapshot();
reloadSnapshotAndCheckDigest();
-
+
// trigger various write requests
String pathPrefix = "/testSnapshotDigest";
for (int i = 0; i < 1000; i++) {
String path = pathPrefix + i;
- zk.create(path, path.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk.create(path, path.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
}
// update the data of first node
@@ -111,25 +106,24 @@ public class SnapshotDigestTest extends ClientBase {
List<Op> subTxns = new ArrayList<Op>();
for (int i = 0; i < 3; i++) {
String path = pathPrefix + "-m" + i;
- subTxns.add(Op.create(path, path.getBytes(),
- ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT));
+ subTxns.add(Op.create(path, path.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT));
}
zk.multi(subTxns);
reloadSnapshotAndCheckDigest();
- // Take a snapshot and test the logic when loading a non-fuzzy snapshot
+ // Take a snapshot and test the logic when loading a non-fuzzy snapshot
server = serverFactory.getZooKeeperServer();
- server.takeSnapshot();
+ server.takeSnapshot();
reloadSnapshotAndCheckDigest();
}
/**
- * Make sure the code will skip digest check when it's comparing
- * digest with different version.
+ * Make sure the code will skip digest check when it's comparing
+ * digest with different version.
*
- * This enables us to smoonthly add new fields into digest or using
+ * This enables us to smoonthly add new fields into digest or using
* new digest calculation.
*/
@Test
@@ -139,11 +133,10 @@ public class SnapshotDigestTest extends ClientBase {
// create a node
String path = "/testDifferentDigestVersion";
- zk.create(path, path.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk.create(path, path.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
// take a full snapshot
- server.takeSnapshot();
+ server.takeSnapshot();
// using reflection to change the final static DIGEST_VERSION
int newVersion = currentVersion + 1;
@@ -154,23 +147,21 @@ public class SnapshotDigestTest extends ClientBase {
modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
field.set(null, newVersion);
- Assert.assertEquals(newVersion, (int) DigestCalculator.DIGEST_VERSION);
+ assertEquals(newVersion, (int) DigestCalculator.DIGEST_VERSION);
- // using mock to return different digest value when the way we
+ // using mock to return different digest value when the way we
// calculate digest changed
FileTxnSnapLog txnSnapLog = new FileTxnSnapLog(tmpDir, tmpDir);
DataTree dataTree = Mockito.spy(new DataTree());
- Mockito.when(dataTree.getTreeDigest()).thenReturn(0L);
- txnSnapLog.restore(dataTree, new ConcurrentHashMap<Long, Integer>(),
- Mockito.mock(FileTxnSnapLog.PlayBackListener.class));
+ Mockito.when(dataTree.getTreeDigest()).thenReturn(0L);
+ txnSnapLog.restore(dataTree, new ConcurrentHashMap<Long, Integer>(), Mockito.mock(FileTxnSnapLog.PlayBackListener.class));
// make sure the reportDigestMismatch function is never called
- Mockito.verify(dataTree, Mockito.never())
- .reportDigestMismatch(Mockito.anyLong());
+ Mockito.verify(dataTree, Mockito.never()).reportDigestMismatch(Mockito.anyLong());
}
/**
- * Make sure it's backward compatible, and also we can rollback this
+ * Make sure it's backward compatible, and also we can rollback this
* feature without corrupt the database.
*/
@Test
@@ -187,20 +178,19 @@ public class SnapshotDigestTest extends ClientBase {
// restart the server to cache the option change
reloadSnapshotAndCheckDigest();
-
- // create a node
+
+ // create a node
String path = "/testCompatible" + "-" + enabledBefore + "-" + enabledAfter;
- zk.create(path, path.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk.create(path, path.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
// take a full snapshot
- server.takeSnapshot();
+ server.takeSnapshot();
DigestCalculator.setDigestEnabled(enabledAfter);
-
+
reloadSnapshotAndCheckDigest();
- Assert.assertEquals(path, new String(zk.getData(path, false, null)));
+ assertEquals(path, new String(zk.getData(path, false, null)));
}
private void reloadSnapshotAndCheckDigest() throws Exception {
@@ -213,10 +203,10 @@ public class SnapshotDigestTest extends ClientBase {
QuorumPeerMainTest.waitForOne(zk, States.CONNECTED);
// Snapshot digests always match
- Assert.assertEquals(0L, (long) ServerMetrics.getMetrics().DIGEST_MISMATCHES_COUNT.get());
+ assertEquals(0L, ServerMetrics.getMetrics().DIGEST_MISMATCHES_COUNT.get());
// reset the digestFromLoadedSnapshot after comparing
- Assert.assertNull(server.getZKDatabase().getDataTree()
- .getDigestFromLoadedSnapshot());
+ assertNull(server.getZKDatabase().getDataTree().getDigestFromLoadedSnapshot());
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/ToStringTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/ToStringTest.java
index f19469b17..e1349a3cd 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/ToStringTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/ToStringTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,9 +18,9 @@
package org.apache.zookeeper.server;
+import static org.junit.Assert.assertNotSame;
import org.apache.zookeeper.ZKTestCase;
import org.apache.zookeeper.proto.SetDataRequest;
-import org.junit.Assert;
import org.junit.Test;
/**
@@ -28,11 +28,13 @@ import org.junit.Test;
* fail.
*/
public class ToStringTest extends ZKTestCase {
- /** Verify jute - which we've had particular problems with in the past
+
+ /** Verify jute - which we've had particular problems with in the past
* wrt null fields */
@Test
public void testJuteToString() {
SetDataRequest req = new SetDataRequest(null, null, 0);
- Assert.assertNotSame("ERROR", req.toString());
+ assertNotSame("ERROR", req.toString());
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/ZooKeeperCriticalThreadMetricsTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/ZooKeeperCriticalThreadMetricsTest.java
index ce90936d3..243e17782 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/ZooKeeperCriticalThreadMetricsTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/ZooKeeperCriticalThreadMetricsTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,20 +18,21 @@
package org.apache.zookeeper.server;
-import org.apache.zookeeper.ZKTestCase;
-import org.apache.zookeeper.ZooDefs;
-import org.junit.Assert;
-import org.junit.Test;
-
+import static org.junit.Assert.assertEquals;
import java.nio.ByteBuffer;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
+import org.apache.zookeeper.ZKTestCase;
+import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.metrics.MetricsUtils;
+import org.junit.Test;
public class ZooKeeperCriticalThreadMetricsTest extends ZKTestCase {
+
CountDownLatch processed;
private class MyRequestProcessor implements RequestProcessor {
+
@Override
public void processRequest(Request request) throws RequestProcessorException {
// use this dummy request processor to trigger a unrecoverable ex
@@ -41,9 +42,11 @@ public class ZooKeeperCriticalThreadMetricsTest extends ZKTestCase {
@Override
public void shutdown() {
}
+
}
private class MyPrepRequestProcessor extends PrepRequestProcessor {
+
public MyPrepRequestProcessor() {
super(new ZooKeeperServer(), new MyRequestProcessor());
}
@@ -57,21 +60,20 @@ public class ZooKeeperCriticalThreadMetricsTest extends ZKTestCase {
}
@Test
- public void testUnrecoverableErrorCountFromRequestProcessor() throws Exception{
+ public void testUnrecoverableErrorCountFromRequestProcessor() throws Exception {
ServerMetrics.getMetrics().resetAll();
processed = new CountDownLatch(1);
- PrepRequestProcessor processor =new MyPrepRequestProcessor();
+ PrepRequestProcessor processor = new MyPrepRequestProcessor();
processor.start();
- processor.processRequest(new Request(null, 1L, 1, ZooDefs.OpCode.setData,
- ByteBuffer.wrap(new byte[10]), null));
+ processor.processRequest(new Request(null, 1L, 1, ZooDefs.OpCode.setData, ByteBuffer.wrap(new byte[10]), null));
processed.await();
processor.shutdown();
Map<String, Object> values = MetricsUtils.currentServerMetrics();
- Assert.assertEquals(1L, values.get("unrecoverable_error_count"));
+ assertEquals(1L, values.get("unrecoverable_error_count"));
}
@Test
@@ -84,6 +86,7 @@ public class ZooKeeperCriticalThreadMetricsTest extends ZKTestCase {
thread.handleException("test", new Exception());
Map<String, Object> values = MetricsUtils.currentServerMetrics();
- Assert.assertEquals(1L, values.get("unrecoverable_error_count"));
+ assertEquals(1L, values.get("unrecoverable_error_count"));
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/ZooKeeperServerBeanTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/ZooKeeperServerBeanTest.java
index d268410d8..a8db9e286 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/ZooKeeperServerBeanTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/ZooKeeperServerBeanTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -15,16 +15,15 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
package org.apache.zookeeper.server;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;
-
import java.io.File;
import java.io.IOException;
import java.net.InetSocketAddress;
-
import org.apache.jute.Record;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.server.persistence.FileTxnSnapLog;
@@ -36,10 +35,10 @@ import org.junit.Before;
import org.junit.Test;
public class ZooKeeperServerBeanTest {
+
@Before
public void setup() {
- System.setProperty(ServerCnxnFactory.ZOOKEEPER_SERVER_CNXN_FACTORY,
- "org.apache.zookeeper.server.NettyServerCnxnFactory");
+ System.setProperty(ServerCnxnFactory.ZOOKEEPER_SERVER_CNXN_FACTORY, "org.apache.zookeeper.server.NettyServerCnxnFactory");
}
@After
@@ -51,8 +50,7 @@ public class ZooKeeperServerBeanTest {
public void testTxnLogElapsedSyncTime() throws IOException {
File tmpDir = ClientBase.createEmptyTestDir();
- FileTxnSnapLog fileTxnSnapLog = new FileTxnSnapLog(new File(tmpDir, "data"),
- new File(tmpDir, "data_txnlog"));
+ FileTxnSnapLog fileTxnSnapLog = new FileTxnSnapLog(new File(tmpDir, "data"), new File(tmpDir, "data_txnlog"));
ZooKeeperServer zks = new ZooKeeperServer();
zks.setTxnLogFactory(fileTxnSnapLog);
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/ZooKeeperServerConfTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/ZooKeeperServerConfTest.java
index 6fc257901..2f1c9e3bc 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/ZooKeeperServerConfTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/ZooKeeperServerConfTest.java
@@ -14,20 +14,24 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
package org.apache.zookeeper.server;
+import static org.junit.Assert.assertEquals;
import java.util.Map;
import org.apache.zookeeper.ZKTestCase;
import org.junit.Before;
import org.junit.Test;
-import static org.junit.Assert.*;
public class ZooKeeperServerConfTest extends ZKTestCase {
+
private ZooKeeperServerConf c;
- @Before public void setUp() {
+ @Before
+ public void setUp() {
c = new ZooKeeperServerConf(1, "a", "b", 2, 3, 4, 5, 6L, 7);
}
- @Test public void testGetters() {
+ @Test
+ public void testGetters() {
assertEquals(1, c.getClientPort());
assertEquals("a", c.getDataDir());
assertEquals("b", c.getDataLogDir());
@@ -38,7 +42,8 @@ public class ZooKeeperServerConfTest extends ZKTestCase {
assertEquals(6L, c.getServerId());
assertEquals(7, c.getClientPortListenBacklog());
}
- @Test public void testToMap() {
+ @Test
+ public void testToMap() {
Map<String, Object> m = c.toMap();
assertEquals(9, m.size());
assertEquals(Integer.valueOf(1), m.get(ZooKeeperServerConf.KEY_CLIENT_PORT));
@@ -51,4 +56,5 @@ public class ZooKeeperServerConfTest extends ZKTestCase {
assertEquals(Long.valueOf(6L), m.get(ZooKeeperServerConf.KEY_SERVER_ID));
assertEquals(Integer.valueOf(7), m.get(ZooKeeperServerConf.KEY_CLIENT_PORT_LISTEN_BACKLOG));
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/ZooKeeperServerMainTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/ZooKeeperServerMainTest.java
index 2d7038324..b7df9323f 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/ZooKeeperServerMainTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/ZooKeeperServerMainTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -19,25 +19,25 @@
package org.apache.zookeeper.server;
import static org.apache.zookeeper.test.ClientBase.CONNECTION_TIMEOUT;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
-
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.PortAssignment;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
-import org.apache.zookeeper.ZKTestCase;
-import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.Watcher.Event.KeeperState;
+import org.apache.zookeeper.ZKTestCase;
import org.apache.zookeeper.ZooDefs.Ids;
+import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.common.PathUtils;
import org.apache.zookeeper.metrics.BaseTestMetricsProvider;
import org.apache.zookeeper.metrics.BaseTestMetricsProvider.MetricsProviderCapturingLifecycle;
@@ -48,33 +48,33 @@ import org.apache.zookeeper.metrics.BaseTestMetricsProvider.MetricsProviderWithE
import org.apache.zookeeper.server.persistence.FileTxnSnapLog;
import org.apache.zookeeper.server.quorum.QuorumPeerConfig.ConfigException;
import org.apache.zookeeper.test.ClientBase;
-import org.junit.Assert;
import org.junit.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/**
* Test stand-alone server.
*
*/
public class ZooKeeperServerMainTest extends ZKTestCase implements Watcher {
- protected static final Logger LOG =
- LoggerFactory.getLogger(ZooKeeperServerMainTest.class);
+
+ protected static final Logger LOG = LoggerFactory.getLogger(ZooKeeperServerMainTest.class);
private CountDownLatch clientConnected = new CountDownLatch(1);
public static class MainThread extends Thread {
+
final File confFile;
final TestZKSMain main;
final File tmpDir;
final File dataDir;
final File logDir;
- public MainThread(int clientPort, boolean preCreateDirs, String configs)
- throws IOException {
+ public MainThread(int clientPort, boolean preCreateDirs, String configs) throws IOException {
this(clientPort, preCreateDirs, ClientBase.createTmpDir(), configs);
}
- public MainThread(int clientPort, boolean preCreateDirs, File tmpDir, String configs)
- throws IOException {
+ public MainThread(int clientPort, boolean preCreateDirs, File tmpDir, String configs) throws IOException {
super("Standalone server with clientPort:" + clientPort);
this.tmpDir = tmpDir;
confFile = new File(tmpDir, "zoo.cfg");
@@ -83,7 +83,7 @@ public class ZooKeeperServerMainTest extends ZKTestCase implements Watcher {
fwriter.write("tickTime=2000\n");
fwriter.write("initLimit=10\n");
fwriter.write("syncLimit=5\n");
- if(configs != null){
+ if (configs != null) {
fwriter.write(configs);
}
@@ -98,7 +98,7 @@ public class ZooKeeperServerMainTest extends ZKTestCase implements Watcher {
}
ClientBase.createInitializeFile(logDir);
}
-
+
String normalizedDataDir = PathUtils.normalizeFileSystemPath(dataDir.toString());
String normalizedLogDir = PathUtils.normalizeFileSystemPath(logDir.toString());
fwriter.write("dataDir=" + normalizedDataDir + "\n");
@@ -111,7 +111,7 @@ public class ZooKeeperServerMainTest extends ZKTestCase implements Watcher {
}
public void run() {
- String args[] = new String[1];
+ String[] args = new String[1];
args[0] = confFile.toString();
try {
main.initializeAndRun(args);
@@ -125,31 +125,36 @@ public class ZooKeeperServerMainTest extends ZKTestCase implements Watcher {
main.shutdown();
}
- void deleteDirs() throws IOException{
+ void deleteDirs() throws IOException {
delete(tmpDir);
}
void delete(File f) throws IOException {
if (f.isDirectory()) {
- for (File c : f.listFiles())
+ for (File c : f.listFiles()) {
delete(c);
+ }
}
- if (!f.delete())
+ if (!f.delete()) {
// double check for the file existence
if (f.exists()) {
throw new IOException("Failed to delete file: " + f);
}
+ }
}
ServerCnxnFactory getCnxnFactory() {
return main.getCnxnFactory();
}
+
}
- public static class TestZKSMain extends ZooKeeperServerMain {
+ public static class TestZKSMain extends ZooKeeperServerMain {
+
public void shutdown() {
super.shutdown();
}
+
}
/**
@@ -166,24 +171,19 @@ public class ZooKeeperServerMainTest extends ZKTestCase implements Watcher {
MainThread main = new MainThread(CLIENT_PORT, true, null);
main.start();
- Assert.assertTrue("waiting for server being up",
- ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT,
- CONNECTION_TIMEOUT));
-
+ assertTrue(
+ "waiting for server being up",
+ ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT, CONNECTION_TIMEOUT));
- ZooKeeper zk = new ZooKeeper("127.0.0.1:" + CLIENT_PORT,
- ClientBase.CONNECTION_TIMEOUT, this);
+ ZooKeeper zk = new ZooKeeper("127.0.0.1:" + CLIENT_PORT, ClientBase.CONNECTION_TIMEOUT, this);
- zk.create("/foo1", "foobar".getBytes(), Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
- Assert.assertEquals(new String(zk.getData("/foo1", null, null)), "foobar");
+ zk.create("/foo1", "foobar".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
+ assertEquals(new String(zk.getData("/foo1", null, null)), "foobar");
// inject problem in server
- ZooKeeperServer zooKeeperServer = main.getCnxnFactory()
- .getZooKeeperServer();
+ ZooKeeperServer zooKeeperServer = main.getCnxnFactory().getZooKeeperServer();
FileTxnSnapLog snapLog = zooKeeperServer.getTxnLogFactory();
- FileTxnSnapLog fileTxnSnapLogWithError = new FileTxnSnapLog(
- snapLog.getDataDir(), snapLog.getSnapDir()) {
+ FileTxnSnapLog fileTxnSnapLogWithError = new FileTxnSnapLog(snapLog.getDataDir(), snapLog.getSnapDir()) {
@Override
public void commit() throws IOException {
throw new IOException("Input/output error");
@@ -194,16 +194,15 @@ public class ZooKeeperServerMainTest extends ZKTestCase implements Watcher {
try {
// do create operation, so that injected IOException is thrown
- zk.create("/foo2", "foobar".getBytes(), Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk.create("/foo2", "foobar".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
fail("IOException is expected as error is injected in transaction log commit funtionality");
} catch (Exception e) {
// do nothing
}
zk.close();
- Assert.assertTrue("waiting for server down",
- ClientBase.waitForServerDown("127.0.0.1:" + CLIENT_PORT,
- ClientBase.CONNECTION_TIMEOUT));
+ assertTrue(
+ "waiting for server down",
+ ClientBase.waitForServerDown("127.0.0.1:" + CLIENT_PORT, ClientBase.CONNECTION_TIMEOUT));
fileTxnSnapLogWithError.close();
main.shutdown();
main.deleteDirs();
@@ -225,9 +224,9 @@ public class ZooKeeperServerMainTest extends ZKTestCase implements Watcher {
MainThread main = new MainThread(CLIENT_PORT, true, null);
File tmpDir = main.tmpDir;
main.start();
- Assert.assertTrue("waiting for server being up", ClientBase
- .waitForServerUp("127.0.0.1:" + CLIENT_PORT,
- CONNECTION_TIMEOUT / 2));
+ assertTrue(
+ "waiting for server being up",
+ ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT, CONNECTION_TIMEOUT / 2));
main.shutdown();
// Make the snapshot directory read only
@@ -238,9 +237,9 @@ public class ZooKeeperServerMainTest extends ZKTestCase implements Watcher {
main = new MainThread(CLIENT_PORT, false, tmpDir, null);
main.start();
- Assert.assertFalse("waiting for server being up", ClientBase
- .waitForServerUp("127.0.0.1:" + CLIENT_PORT,
- CONNECTION_TIMEOUT / 2));
+ assertFalse(
+ "waiting for server being up",
+ ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT, CONNECTION_TIMEOUT / 2));
main.shutdown();
@@ -265,9 +264,9 @@ public class ZooKeeperServerMainTest extends ZKTestCase implements Watcher {
MainThread main = new MainThread(CLIENT_PORT, true, null);
File tmpDir = main.tmpDir;
main.start();
- Assert.assertTrue("waiting for server being up", ClientBase
- .waitForServerUp("127.0.0.1:" + CLIENT_PORT,
- CONNECTION_TIMEOUT / 2));
+ assertTrue(
+ "waiting for server being up",
+ ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT, CONNECTION_TIMEOUT / 2));
main.shutdown();
// Make the transaction log directory read only
@@ -278,9 +277,9 @@ public class ZooKeeperServerMainTest extends ZKTestCase implements Watcher {
main = new MainThread(CLIENT_PORT, false, tmpDir, null);
main.start();
- Assert.assertFalse("waiting for server being up", ClientBase
- .waitForServerUp("127.0.0.1:" + CLIENT_PORT,
- CONNECTION_TIMEOUT / 2));
+ assertFalse(
+ "waiting for server being up",
+ ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT, CONNECTION_TIMEOUT / 2));
main.shutdown();
@@ -301,28 +300,25 @@ public class ZooKeeperServerMainTest extends ZKTestCase implements Watcher {
MainThread main = new MainThread(CLIENT_PORT, true, null);
main.start();
- Assert.assertTrue("waiting for server being up",
- ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT,
- CONNECTION_TIMEOUT));
+ assertTrue(
+ "waiting for server being up",
+ ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT, CONNECTION_TIMEOUT));
clientConnected = new CountDownLatch(1);
- ZooKeeper zk = new ZooKeeper("127.0.0.1:" + CLIENT_PORT,
- ClientBase.CONNECTION_TIMEOUT, this);
- Assert.assertTrue("Failed to establish zkclient connection!",
- clientConnected.await(CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS));
-
- zk.create("/foo", "foobar".getBytes(), Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
- Assert.assertEquals(new String(zk.getData("/foo", null, null)), "foobar");
+ ZooKeeper zk = new ZooKeeper("127.0.0.1:" + CLIENT_PORT, ClientBase.CONNECTION_TIMEOUT, this);
+ assertTrue("Failed to establish zkclient connection!", clientConnected.await(CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS));
+
+ zk.create("/foo", "foobar".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
+ assertEquals(new String(zk.getData("/foo", null, null)), "foobar");
zk.close();
main.shutdown();
main.join();
main.deleteDirs();
- Assert.assertTrue("waiting for server down",
- ClientBase.waitForServerDown("127.0.0.1:" + CLIENT_PORT,
- ClientBase.CONNECTION_TIMEOUT));
+ assertTrue(
+ "waiting for server down",
+ ClientBase.waitForServerDown("127.0.0.1:" + CLIENT_PORT, ClientBase.CONNECTION_TIMEOUT));
}
/**
@@ -330,23 +326,25 @@ public class ZooKeeperServerMainTest extends ZKTestCase implements Watcher {
* maxsessiontimeout
*/
@Test
- public void testWithMinSessionTimeoutGreaterThanMaxSessionTimeout()
- throws Exception {
+ public void testWithMinSessionTimeoutGreaterThanMaxSessionTimeout() throws Exception {
ClientBase.setupTestEnv();
final int CLIENT_PORT = PortAssignment.unique();
final int tickTime = 2000;
final int minSessionTimeout = 20 * tickTime + 1000; // min is higher
final int maxSessionTimeout = tickTime * 2 - 100; // max is lower
- final String configs = "maxSessionTimeout=" + maxSessionTimeout + "\n"
- + "minSessionTimeout=" + minSessionTimeout + "\n";
+ final String configs = "maxSessionTimeout="
+ + maxSessionTimeout
+ + "\n"
+ + "minSessionTimeout="
+ + minSessionTimeout
+ + "\n";
MainThread main = new MainThread(CLIENT_PORT, true, configs);
- String args[] = new String[1];
+ String[] args = new String[1];
args[0] = main.confFile.toString();
try {
main.main.initializeAndRun(args);
- Assert.fail("Must throw exception as "
- + "minsessiontimeout > maxsessiontimeout");
+ fail("Must throw exception as " + "minsessiontimeout > maxsessiontimeout");
} catch (ConfigException iae) {
// expected
}
@@ -356,19 +354,17 @@ public class ZooKeeperServerMainTest extends ZKTestCase implements Watcher {
* Test verifies that the server shouldn't boot with an invalid metrics provider
*/
@Test
- public void testInvalidMetricsProvider()
- throws Exception {
+ public void testInvalidMetricsProvider() throws Exception {
ClientBase.setupTestEnv();
final int CLIENT_PORT = PortAssignment.unique();
final String configs = "metricsProvider.className=BadClass\n";
MainThread main = new MainThread(CLIENT_PORT, true, configs);
- String args[] = new String[1];
+ String[] args = new String[1];
args[0] = main.confFile.toString();
try {
main.main.initializeAndRun(args);
- Assert.fail("Must throw exception as metrics provider is not "
- + "well configured");
+ fail("Must throw exception as metrics provider is not " + "well configured");
} catch (ConfigException iae) {
// expected
}
@@ -378,18 +374,17 @@ public class ZooKeeperServerMainTest extends ZKTestCase implements Watcher {
* Test verifies that the server shouldn't boot with a faulty metrics provider
*/
@Test
- public void testFaultyMetricsProviderOnStart()
- throws Exception {
+ public void testFaultyMetricsProviderOnStart() throws Exception {
ClientBase.setupTestEnv();
final int CLIENT_PORT = PortAssignment.unique();
- final String configs = "metricsProvider.className="+MetricsProviderWithErrorInStart.class.getName()+"\n";
+ final String configs = "metricsProvider.className=" + MetricsProviderWithErrorInStart.class.getName() + "\n";
MainThread main = new MainThread(CLIENT_PORT, true, configs);
- String args[] = new String[1];
+ String[] args = new String[1];
args[0] = main.confFile.toString();
try {
main.main.initializeAndRun(args);
- Assert.fail("Must throw exception as metrics provider cannot boot");
+ fail("Must throw exception as metrics provider cannot boot");
} catch (IOException iae) {
// expected
}
@@ -399,18 +394,19 @@ public class ZooKeeperServerMainTest extends ZKTestCase implements Watcher {
* Test verifies that the server shouldn't boot with a faulty metrics provider
*/
@Test
- public void testFaultyMetricsProviderOnConfigure()
- throws Exception {
+ public void testFaultyMetricsProviderOnConfigure() throws Exception {
ClientBase.setupTestEnv();
final int CLIENT_PORT = PortAssignment.unique();
- final String configs = "metricsProvider.className="+MetricsProviderWithErrorInConfigure.class.getName()+"\n";
+ final String configs = "metricsProvider.className="
+ + MetricsProviderWithErrorInConfigure.class.getName()
+ + "\n";
MainThread main = new MainThread(CLIENT_PORT, true, configs);
- String args[] = new String[1];
+ String[] args = new String[1];
args[0] = main.confFile.toString();
try {
main.main.initializeAndRun(args);
- Assert.fail("Must throw exception as metrics provider is cannot boot");
+ fail("Must throw exception as metrics provider is cannot boot");
} catch (IOException iae) {
// expected
}
@@ -420,127 +416,112 @@ public class ZooKeeperServerMainTest extends ZKTestCase implements Watcher {
* Test verifies that the server shouldn't be affected but runtime errors on stop()
*/
@Test
- public void testFaultyMetricsProviderOnStop()
- throws Exception {
+ public void testFaultyMetricsProviderOnStop() throws Exception {
ClientBase.setupTestEnv();
final int CLIENT_PORT = PortAssignment.unique();
MetricsProviderWithErrorInStop.stopCalled.set(false);
- final String configs = "metricsProvider.className="+MetricsProviderWithErrorInStop.class.getName()+"\n";
+ final String configs = "metricsProvider.className=" + MetricsProviderWithErrorInStop.class.getName() + "\n";
MainThread main = new MainThread(CLIENT_PORT, true, configs);
main.start();
- Assert.assertTrue("waiting for server being up",
- ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT,
- CONNECTION_TIMEOUT));
+ assertTrue(
+ "waiting for server being up",
+ ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT, CONNECTION_TIMEOUT));
clientConnected = new CountDownLatch(1);
- ZooKeeper zk = new ZooKeeper("127.0.0.1:" + CLIENT_PORT,
- ClientBase.CONNECTION_TIMEOUT, this);
- Assert.assertTrue("Failed to establish zkclient connection!",
- clientConnected.await(CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS));
-
- zk.create("/foo", "foobar".getBytes(), Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
- Assert.assertEquals(new String(zk.getData("/foo", null, null)), "foobar");
+ ZooKeeper zk = new ZooKeeper("127.0.0.1:" + CLIENT_PORT, ClientBase.CONNECTION_TIMEOUT, this);
+ assertTrue("Failed to establish zkclient connection!", clientConnected.await(CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS));
+
+ zk.create("/foo", "foobar".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
+ assertEquals(new String(zk.getData("/foo", null, null)), "foobar");
zk.close();
main.shutdown();
main.join();
main.deleteDirs();
- Assert.assertTrue("waiting for server down",
- ClientBase.waitForServerDown("127.0.0.1:" + CLIENT_PORT,
- ClientBase.CONNECTION_TIMEOUT));
- Assert.assertTrue(MetricsProviderWithErrorInStop.stopCalled.get());
+ assertTrue(
+ "waiting for server down",
+ ClientBase.waitForServerDown("127.0.0.1:" + CLIENT_PORT, ClientBase.CONNECTION_TIMEOUT));
+ assertTrue(MetricsProviderWithErrorInStop.stopCalled.get());
}
/**
* Test verifies that configuration is passed to the MetricsProvider.
*/
@Test
- public void testMetricsProviderConfiguration()
- throws Exception {
+ public void testMetricsProviderConfiguration() throws Exception {
ClientBase.setupTestEnv();
final int CLIENT_PORT = PortAssignment.unique();
MetricsProviderWithConfiguration.httpPort.set(0);
- final String configs = "metricsProvider.className="+MetricsProviderWithConfiguration.class.getName()+"\n"+
- "metricsProvider.httpPort=1234\n";
+ final String configs = "metricsProvider.className="
+ + MetricsProviderWithConfiguration.class.getName()
+ + "\n"
+ + "metricsProvider.httpPort=1234\n";
MainThread main = new MainThread(CLIENT_PORT, true, configs);
main.start();
- Assert.assertTrue("waiting for server being up",
- ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT,
- CONNECTION_TIMEOUT));
+ assertTrue(
+ "waiting for server being up",
+ ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT, CONNECTION_TIMEOUT));
clientConnected = new CountDownLatch(1);
- ZooKeeper zk = new ZooKeeper("127.0.0.1:" + CLIENT_PORT,
- ClientBase.CONNECTION_TIMEOUT, this);
- Assert.assertTrue("Failed to establish zkclient connection!",
- clientConnected.await(CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS));
-
- zk.create("/foo", "foobar".getBytes(), Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
- Assert.assertEquals(new String(zk.getData("/foo", null, null)), "foobar");
+ ZooKeeper zk = new ZooKeeper("127.0.0.1:" + CLIENT_PORT, ClientBase.CONNECTION_TIMEOUT, this);
+ assertTrue("Failed to establish zkclient connection!", clientConnected.await(CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS));
+
+ zk.create("/foo", "foobar".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
+ assertEquals(new String(zk.getData("/foo", null, null)), "foobar");
zk.close();
main.shutdown();
main.join();
main.deleteDirs();
- Assert.assertTrue("waiting for server down",
- ClientBase.waitForServerDown("127.0.0.1:" + CLIENT_PORT,
- ClientBase.CONNECTION_TIMEOUT));
- Assert.assertEquals(1234, MetricsProviderWithConfiguration.httpPort.get());
+ assertTrue(
+ "waiting for server down",
+ ClientBase.waitForServerDown("127.0.0.1:" + CLIENT_PORT, ClientBase.CONNECTION_TIMEOUT));
+ assertEquals(1234, MetricsProviderWithConfiguration.httpPort.get());
}
/**
* Test verifies that all of the lifecycle methods of the MetricsProvider are called.
*/
@Test
- public void testMetricsProviderLifecycle()
- throws Exception {
+ public void testMetricsProviderLifecycle() throws Exception {
ClientBase.setupTestEnv();
MetricsProviderCapturingLifecycle.reset();
final int CLIENT_PORT = PortAssignment.unique();
- final String configs = "metricsProvider.className="+MetricsProviderCapturingLifecycle.class.getName()+"\n"+
- "metricsProvider.httpPort=1234\n";
+ final String configs = "metricsProvider.className="
+ + MetricsProviderCapturingLifecycle.class.getName()
+ + "\n"
+ + "metricsProvider.httpPort=1234\n";
MainThread main = new MainThread(CLIENT_PORT, true, configs);
main.start();
- Assert.assertTrue("waiting for server being up",
- ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT,
- CONNECTION_TIMEOUT));
+ assertTrue(
+ "waiting for server being up",
+ ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT, CONNECTION_TIMEOUT));
clientConnected = new CountDownLatch(1);
- ZooKeeper zk = new ZooKeeper("127.0.0.1:" + CLIENT_PORT,
- ClientBase.CONNECTION_TIMEOUT, this);
- Assert.assertTrue("Failed to establish zkclient connection!",
- clientConnected.await(CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS));
-
- zk.create("/foo", "foobar".getBytes(), Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
- Assert.assertEquals(new String(zk.getData("/foo", null, null)), "foobar");
+ ZooKeeper zk = new ZooKeeper("127.0.0.1:" + CLIENT_PORT, ClientBase.CONNECTION_TIMEOUT, this);
+ assertTrue("Failed to establish zkclient connection!", clientConnected.await(CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS));
+
+ zk.create("/foo", "foobar".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
+ assertEquals(new String(zk.getData("/foo", null, null)), "foobar");
zk.close();
main.shutdown();
main.join();
main.deleteDirs();
- Assert.assertTrue("waiting for server down",
- ClientBase.waitForServerDown("127.0.0.1:" + CLIENT_PORT,
- ClientBase.CONNECTION_TIMEOUT));
-
- Assert.assertTrue("metrics provider lifecycle error",
- BaseTestMetricsProvider.MetricsProviderCapturingLifecycle.configureCalled.get());
- Assert.assertTrue("metrics provider lifecycle error",
- BaseTestMetricsProvider.MetricsProviderCapturingLifecycle.startCalled.get());
- Assert.assertTrue("metrics provider lifecycle error",
- BaseTestMetricsProvider.MetricsProviderCapturingLifecycle.getRootContextCalled.get());
- Assert.assertTrue("metrics provider lifecycle error",
- BaseTestMetricsProvider.MetricsProviderCapturingLifecycle.stopCalled.get());
+ assertTrue("waiting for server down", ClientBase.waitForServerDown("127.0.0.1:" + CLIENT_PORT, ClientBase.CONNECTION_TIMEOUT));
+ assertTrue("metrics provider lifecycle error", BaseTestMetricsProvider.MetricsProviderCapturingLifecycle.configureCalled.get());
+ assertTrue("metrics provider lifecycle error", BaseTestMetricsProvider.MetricsProviderCapturingLifecycle.startCalled.get());
+ assertTrue("metrics provider lifecycle error", BaseTestMetricsProvider.MetricsProviderCapturingLifecycle.getRootContextCalled.get());
+ assertTrue("metrics provider lifecycle error", BaseTestMetricsProvider.MetricsProviderCapturingLifecycle.stopCalled.get());
}
/**
@@ -560,19 +541,15 @@ public class ZooKeeperServerMainTest extends ZKTestCase implements Watcher {
main.start();
String HOSTPORT = "127.0.0.1:" + CLIENT_PORT;
- Assert.assertTrue("waiting for server being up",
- ClientBase.waitForServerUp(HOSTPORT, CONNECTION_TIMEOUT));
+ assertTrue("waiting for server being up", ClientBase.waitForServerUp(HOSTPORT, CONNECTION_TIMEOUT));
// create session with min value
verifySessionTimeOut(minSessionTimeout, minSessionTimeout, HOSTPORT);
- verifySessionTimeOut(minSessionTimeout - 2000, minSessionTimeout,
- HOSTPORT);
+ verifySessionTimeOut(minSessionTimeout - 2000, minSessionTimeout, HOSTPORT);
// create session with max value
verifySessionTimeOut(maxSessionTimeout, maxSessionTimeout, HOSTPORT);
- verifySessionTimeOut(maxSessionTimeout + 2000, maxSessionTimeout,
- HOSTPORT);
+ verifySessionTimeOut(maxSessionTimeout + 2000, maxSessionTimeout, HOSTPORT);
main.shutdown();
- Assert.assertTrue("waiting for server down", ClientBase
- .waitForServerDown(HOSTPORT, ClientBase.CONNECTION_TIMEOUT));
+ assertTrue("waiting for server down", ClientBase.waitForServerDown(HOSTPORT, ClientBase.CONNECTION_TIMEOUT));
}
/**
@@ -587,37 +564,33 @@ public class ZooKeeperServerMainTest extends ZKTestCase implements Watcher {
final int tickTime = 2000;
final int minSessionTimeout = tickTime * 2 - 100;
final int maxSessionTimeout = 20 * tickTime + 1000;
- final String configs = "maxSessionTimeout=" + maxSessionTimeout + "\n"
- + "minSessionTimeout=" + minSessionTimeout + "\n";
+ final String configs = "maxSessionTimeout="
+ + maxSessionTimeout
+ + "\n"
+ + "minSessionTimeout="
+ + minSessionTimeout
+ + "\n";
MainThread main = new MainThread(CLIENT_PORT, true, configs);
main.start();
String HOSTPORT = "127.0.0.1:" + CLIENT_PORT;
- Assert.assertTrue("waiting for server being up",
- ClientBase.waitForServerUp(HOSTPORT, CONNECTION_TIMEOUT));
+ assertTrue("waiting for server being up", ClientBase.waitForServerUp(HOSTPORT, CONNECTION_TIMEOUT));
// create session with min value
verifySessionTimeOut(minSessionTimeout, minSessionTimeout, HOSTPORT);
- verifySessionTimeOut(minSessionTimeout - 2000, minSessionTimeout,
- HOSTPORT);
+ verifySessionTimeOut(minSessionTimeout - 2000, minSessionTimeout, HOSTPORT);
// create session with max value
verifySessionTimeOut(maxSessionTimeout, maxSessionTimeout, HOSTPORT);
- verifySessionTimeOut(maxSessionTimeout + 2000, maxSessionTimeout,
- HOSTPORT);
+ verifySessionTimeOut(maxSessionTimeout + 2000, maxSessionTimeout, HOSTPORT);
main.shutdown();
- Assert.assertTrue("waiting for server down", ClientBase
- .waitForServerDown(HOSTPORT, ClientBase.CONNECTION_TIMEOUT));
+ assertTrue("waiting for server down", ClientBase.waitForServerDown(HOSTPORT, ClientBase.CONNECTION_TIMEOUT));
}
- private void verifySessionTimeOut(int sessionTimeout,
- int expectedSessionTimeout, String HOSTPORT) throws IOException,
- KeeperException, InterruptedException {
+ private void verifySessionTimeOut(int sessionTimeout, int expectedSessionTimeout, String HOSTPORT) throws IOException, KeeperException, InterruptedException {
clientConnected = new CountDownLatch(1);
ZooKeeper zk = new ZooKeeper(HOSTPORT, sessionTimeout, this);
- Assert.assertTrue("Failed to establish zkclient connection!",
- clientConnected.await(sessionTimeout, TimeUnit.MILLISECONDS));
- Assert.assertEquals("Not able to configure the sessionTimeout values",
- expectedSessionTimeout, zk.getSessionTimeout());
+ assertTrue("Failed to establish zkclient connection!", clientConnected.await(sessionTimeout, TimeUnit.MILLISECONDS));
+ assertEquals("Not able to configure the sessionTimeout values", expectedSessionTimeout, zk.getSessionTimeout());
zk.close();
}
@@ -638,10 +611,8 @@ public class ZooKeeperServerMainTest extends ZKTestCase implements Watcher {
@Test
public void testJMXRegistrationWithNetty() throws Exception {
- String originalServerCnxnFactory = System
- .getProperty(ServerCnxnFactory.ZOOKEEPER_SERVER_CNXN_FACTORY);
- System.setProperty(ServerCnxnFactory.ZOOKEEPER_SERVER_CNXN_FACTORY,
- NettyServerCnxnFactory.class.getName());
+ String originalServerCnxnFactory = System.getProperty(ServerCnxnFactory.ZOOKEEPER_SERVER_CNXN_FACTORY);
+ System.setProperty(ServerCnxnFactory.ZOOKEEPER_SERVER_CNXN_FACTORY, NettyServerCnxnFactory.class.getName());
try {
ClientBase.setupTestEnv();
File tmpDir_1 = ClientBase.createTmpDir();
@@ -656,39 +627,38 @@ public class ZooKeeperServerMainTest extends ZKTestCase implements Watcher {
deleteFile(tmpDir_2);
} finally {
// setting back
- if (originalServerCnxnFactory == null
- || originalServerCnxnFactory.isEmpty()) {
+ if (originalServerCnxnFactory == null || originalServerCnxnFactory.isEmpty()) {
System.clearProperty(ServerCnxnFactory.ZOOKEEPER_SERVER_CNXN_FACTORY);
} else {
- System.setProperty(
- ServerCnxnFactory.ZOOKEEPER_SERVER_CNXN_FACTORY,
- originalServerCnxnFactory);
+ System.setProperty(ServerCnxnFactory.ZOOKEEPER_SERVER_CNXN_FACTORY, originalServerCnxnFactory);
}
}
}
private void deleteFile(File f) throws IOException {
if (f.isDirectory()) {
- for (File c : f.listFiles())
+ for (File c : f.listFiles()) {
deleteFile(c);
+ }
}
- if (!f.delete())
- // double check for the file existence
+ if (!f.delete()) {
+ // double check for the file existence
+
if (f.exists()) {
throw new IOException("Failed to delete file: " + f);
}
+ }
}
- private ServerCnxnFactory startServer(File tmpDir) throws IOException,
- InterruptedException {
+ private ServerCnxnFactory startServer(File tmpDir) throws IOException, InterruptedException {
final int CLIENT_PORT = PortAssignment.unique();
ZooKeeperServer zks = new ZooKeeperServer(tmpDir, tmpDir, 3000);
ServerCnxnFactory f = ServerCnxnFactory.createFactory(CLIENT_PORT, -1);
f.startup(zks);
- Assert.assertNotNull("JMX initialization failed!", zks.jmxServerBean);
- Assert.assertTrue("waiting for server being up",
- ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT,
- CONNECTION_TIMEOUT));
+ assertNotNull("JMX initialization failed!", zks.jmxServerBean);
+ assertTrue(
+ "waiting for server being up",
+ ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT, CONNECTION_TIMEOUT));
return f;
}
@@ -697,4 +667,5 @@ public class ZooKeeperServerMainTest extends ZKTestCase implements Watcher {
clientConnected.countDown();
}
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/ZooKeeperServerStartupTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/ZooKeeperServerStartupTest.java
index bdf763e81..794d6dcf8 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/ZooKeeperServerStartupTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/ZooKeeperServerStartupTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -15,16 +15,18 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
package org.apache.zookeeper.server;
import static org.apache.zookeeper.client.FourLetterWordMain.send4LetterWord;
import static org.apache.zookeeper.server.command.AbstractFourLetterCommand.ZK_NOT_SERVING;
-
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
-
import org.apache.zookeeper.PortAssignment;
import org.apache.zookeeper.ZKTestCase;
import org.apache.zookeeper.ZooKeeper;
@@ -32,7 +34,6 @@ import org.apache.zookeeper.common.X509Exception.SSLContextException;
import org.apache.zookeeper.test.ClientBase;
import org.apache.zookeeper.test.ClientBase.CountdownWatcher;
import org.junit.After;
-import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -41,8 +42,8 @@ import org.slf4j.LoggerFactory;
* This class tests the startup behavior of ZooKeeper server.
*/
public class ZooKeeperServerStartupTest extends ZKTestCase {
- private static final Logger LOG = LoggerFactory
- .getLogger(ZooKeeperServerStartupTest.class);
+
+ private static final Logger LOG = LoggerFactory.getLogger(ZooKeeperServerStartupTest.class);
private static int PORT = PortAssignment.unique();
private static String HOST = "127.0.0.1";
private static String HOSTPORT = HOST + ":" + PORT;
@@ -75,35 +76,25 @@ public class ZooKeeperServerStartupTest extends ZKTestCase {
* https://issues.apache.org/jira/browse/ZOOKEEPER-2383
*/
@Test(timeout = 30000)
- public void testClientConnectionRequestDuringStartupWithNIOServerCnxn()
- throws Exception {
+ public void testClientConnectionRequestDuringStartupWithNIOServerCnxn() throws Exception {
tmpDir = ClientBase.createTmpDir();
ClientBase.setupTestEnv();
startSimpleZKServer(startupDelayLatch);
SimpleZooKeeperServer simplezks = (SimpleZooKeeperServer) zks;
- Assert.assertTrue(
- "Failed to invoke zks#startup() method during server startup",
- simplezks.waitForStartupInvocation(10));
+ assertTrue("Failed to invoke zks#startup() method during server startup", simplezks.waitForStartupInvocation(10));
CountdownWatcher watcher = new CountdownWatcher();
- ZooKeeper zkClient = new ZooKeeper(HOSTPORT,
- ClientBase.CONNECTION_TIMEOUT, watcher);
+ ZooKeeper zkClient = new ZooKeeper(HOSTPORT, ClientBase.CONNECTION_TIMEOUT, watcher);
- Assert.assertFalse(
- "Since server is not fully started, zks#createSession() shouldn't be invoked",
- simplezks.waitForSessionCreation(5));
+ assertFalse("Since server is not fully started, zks#createSession() shouldn't be invoked", simplezks.waitForSessionCreation(5));
- LOG.info(
- "Decrements the count of the latch, so that server will proceed with startup");
+ LOG.info("Decrements the count of the latch, so that server will proceed with startup");
startupDelayLatch.countDown();
- Assert.assertTrue("waiting for server being up ", ClientBase
- .waitForServerUp(HOSTPORT, ClientBase.CONNECTION_TIMEOUT));
+ assertTrue("waiting for server being up ", ClientBase.waitForServerUp(HOSTPORT, ClientBase.CONNECTION_TIMEOUT));
- Assert.assertTrue(
- "Failed to invoke zks#createSession() method during client session creation",
- simplezks.waitForSessionCreation(5));
+ assertTrue("Failed to invoke zks#createSession() method during client session creation", simplezks.waitForSessionCreation(5));
watcher.waitForConnected(ClientBase.CONNECTION_TIMEOUT);
zkClient.close();
}
@@ -113,51 +104,37 @@ public class ZooKeeperServerStartupTest extends ZKTestCase {
* https://issues.apache.org/jira/browse/ZOOKEEPER-2383
*/
@Test(timeout = 30000)
- public void testClientConnectionRequestDuringStartupWithNettyServerCnxn()
- throws Exception {
+ public void testClientConnectionRequestDuringStartupWithNettyServerCnxn() throws Exception {
tmpDir = ClientBase.createTmpDir();
ClientBase.setupTestEnv();
- String originalServerCnxnFactory = System
- .getProperty(ServerCnxnFactory.ZOOKEEPER_SERVER_CNXN_FACTORY);
+ String originalServerCnxnFactory = System.getProperty(ServerCnxnFactory.ZOOKEEPER_SERVER_CNXN_FACTORY);
try {
- System.setProperty(ServerCnxnFactory.ZOOKEEPER_SERVER_CNXN_FACTORY,
- NettyServerCnxnFactory.class.getName());
+ System.setProperty(ServerCnxnFactory.ZOOKEEPER_SERVER_CNXN_FACTORY, NettyServerCnxnFactory.class.getName());
startSimpleZKServer(startupDelayLatch);
SimpleZooKeeperServer simplezks = (SimpleZooKeeperServer) zks;
- Assert.assertTrue(
- "Failed to invoke zks#startup() method during server startup",
- simplezks.waitForStartupInvocation(10));
+ assertTrue("Failed to invoke zks#startup() method during server startup", simplezks.waitForStartupInvocation(10));
CountdownWatcher watcher = new CountdownWatcher();
- ZooKeeper zkClient = new ZooKeeper(HOSTPORT,
- ClientBase.CONNECTION_TIMEOUT, watcher);
+ ZooKeeper zkClient = new ZooKeeper(HOSTPORT, ClientBase.CONNECTION_TIMEOUT, watcher);
- Assert.assertFalse(
- "Since server is not fully started, zks#createSession() shouldn't be invoked",
- simplezks.waitForSessionCreation(5));
+ assertFalse("Since server is not fully started, zks#createSession() shouldn't be invoked", simplezks.waitForSessionCreation(5));
- LOG.info(
- "Decrements the count of the latch, so that server will proceed with startup");
+ LOG.info("Decrements the count of the latch, so that server will proceed with startup");
startupDelayLatch.countDown();
- Assert.assertTrue("waiting for server being up ", ClientBase
- .waitForServerUp(HOSTPORT, ClientBase.CONNECTION_TIMEOUT));
+ assertTrue("waiting for server being up ", ClientBase.waitForServerUp(HOSTPORT, ClientBase.CONNECTION_TIMEOUT));
- Assert.assertTrue(
- "Failed to invoke zks#createSession() method during client session creation",
- simplezks.waitForSessionCreation(5));
+ assertTrue("Failed to invoke zks#createSession() method during client session creation", simplezks.waitForSessionCreation(5));
watcher.waitForConnected(ClientBase.CONNECTION_TIMEOUT);
zkClient.close();
} finally {
// reset cnxn factory
if (originalServerCnxnFactory == null) {
- System.clearProperty(
- ServerCnxnFactory.ZOOKEEPER_SERVER_CNXN_FACTORY);
+ System.clearProperty(ServerCnxnFactory.ZOOKEEPER_SERVER_CNXN_FACTORY);
return;
}
- System.setProperty(ServerCnxnFactory.ZOOKEEPER_SERVER_CNXN_FACTORY,
- originalServerCnxnFactory);
+ System.setProperty(ServerCnxnFactory.ZOOKEEPER_SERVER_CNXN_FACTORY, originalServerCnxnFactory);
}
}
@@ -182,22 +159,18 @@ public class ZooKeeperServerStartupTest extends ZKTestCase {
verify("isro", "null");
}
- private void verify(String cmd, String expected)
- throws IOException, SSLContextException {
+ private void verify(String cmd, String expected) throws IOException, SSLContextException {
String resp = sendRequest(cmd);
LOG.info("cmd " + cmd + " expected " + expected + " got " + resp);
- Assert.assertTrue("Unexpected response", resp.contains(expected));
+ assertTrue("Unexpected response", resp.contains(expected));
}
- private String sendRequest(String cmd)
- throws IOException, SSLContextException {
+ private String sendRequest(String cmd) throws IOException, SSLContextException {
return send4LetterWord(HOST, PORT, cmd);
}
- private void startSimpleZKServer(CountDownLatch startupDelayLatch)
- throws IOException {
- zks = new SimpleZooKeeperServer(tmpDir, tmpDir, 3000,
- startupDelayLatch);
+ private void startSimpleZKServer(CountDownLatch startupDelayLatch) throws IOException {
+ zks = new SimpleZooKeeperServer(tmpDir, tmpDir, 3000, startupDelayLatch);
SyncRequestProcessor.setSnapCount(100);
final int PORT = Integer.parseInt(HOSTPORT.split(":")[1]);
@@ -215,20 +188,19 @@ public class ZooKeeperServerStartupTest extends ZKTestCase {
// Ignoring exception. If there is an interrupted exception
// then one of the following assertion will fail
}
- };
+ }
};
LOG.info("Starting zk server {}", HOSTPORT);
startupThread.start();
}
private static class SimpleZooKeeperServer extends ZooKeeperServer {
+
private CountDownLatch startupDelayLatch;
private CountDownLatch startupInvokedLatch = new CountDownLatch(1);
- private CountDownLatch createSessionInvokedLatch = new CountDownLatch(
- 1);
+ private CountDownLatch createSessionInvokedLatch = new CountDownLatch(1);
- public SimpleZooKeeperServer(File snapDir, File logDir, int tickTime,
- CountDownLatch startupDelayLatch) throws IOException {
+ public SimpleZooKeeperServer(File snapDir, File logDir, int tickTime, CountDownLatch startupDelayLatch) throws IOException {
super(snapDir, logDir, tickTime);
this.startupDelayLatch = startupDelayLatch;
}
@@ -245,8 +217,7 @@ public class ZooKeeperServerStartupTest extends ZKTestCase {
// the startup phase, resulting in NPE.
startupDelayLatch.await();
} catch (InterruptedException e) {
- Assert.fail(
- "Unexpected InterruptedException while startinng up!");
+ fail("Unexpected InterruptedException while startinng up!");
}
super.startup();
}
@@ -257,14 +228,14 @@ public class ZooKeeperServerStartupTest extends ZKTestCase {
return super.createSession(cnxn, passwd, timeout);
}
- boolean waitForStartupInvocation(long timeout)
- throws InterruptedException {
+ boolean waitForStartupInvocation(long timeout) throws InterruptedException {
return startupInvokedLatch.await(timeout, TimeUnit.SECONDS);
}
- boolean waitForSessionCreation(long timeout)
- throws InterruptedException {
+ boolean waitForSessionCreation(long timeout) throws InterruptedException {
return createSessionInvokedLatch.await(timeout, TimeUnit.SECONDS);
}
+
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/ZooKeeperServerTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/ZooKeeperServerTest.java
index 3ba3872b1..81469a8f8 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/ZooKeeperServerTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/ZooKeeperServerTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,19 +18,21 @@
package org.apache.zookeeper.server;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.IOException;
import java.util.List;
-
import org.apache.zookeeper.ZKTestCase;
import org.apache.zookeeper.server.persistence.FileTxnLog;
import org.apache.zookeeper.server.persistence.SnapStream;
import org.apache.zookeeper.server.persistence.Util;
import org.apache.zookeeper.test.ClientBase;
-import org.junit.Assert;
import org.junit.Test;
public class ZooKeeperServerTest extends ZKTestCase {
+
@Test
public void testSortDataDirAscending() {
File[] files = new File[5];
@@ -45,11 +47,11 @@ public class ZooKeeperServerTest extends ZKTestCase {
List<File> filelist = Util.sortDataDir(files, "foo", true);
- Assert.assertEquals(orig[2], filelist.get(0));
- Assert.assertEquals(orig[3], filelist.get(1));
- Assert.assertEquals(orig[0], filelist.get(2));
- Assert.assertEquals(orig[1], filelist.get(3));
- Assert.assertEquals(orig[4], filelist.get(4));
+ assertEquals(orig[2], filelist.get(0));
+ assertEquals(orig[3], filelist.get(1));
+ assertEquals(orig[0], filelist.get(2));
+ assertEquals(orig[1], filelist.get(3));
+ assertEquals(orig[4], filelist.get(4));
}
@Test
@@ -66,11 +68,11 @@ public class ZooKeeperServerTest extends ZKTestCase {
List<File> filelist = Util.sortDataDir(files, "foo", false);
- Assert.assertEquals(orig[4], filelist.get(0));
- Assert.assertEquals(orig[1], filelist.get(1));
- Assert.assertEquals(orig[0], filelist.get(2));
- Assert.assertEquals(orig[3], filelist.get(3));
- Assert.assertEquals(orig[2], filelist.get(4));
+ assertEquals(orig[4], filelist.get(0));
+ assertEquals(orig[1], filelist.get(1));
+ assertEquals(orig[0], filelist.get(2));
+ assertEquals(orig[3], filelist.get(3));
+ assertEquals(orig[2], filelist.get(4));
}
@Test
@@ -85,34 +87,31 @@ public class ZooKeeperServerTest extends ZKTestCase {
File[] orig = files.clone();
- File[] filelist =
- FileTxnLog.getLogFiles(files,
- Long.parseLong("10027c6de", 16));
+ File[] filelist = FileTxnLog.getLogFiles(files, Long.parseLong("10027c6de", 16));
- Assert.assertEquals(3, filelist.length);
- Assert.assertEquals(orig[0], filelist[0]);
- Assert.assertEquals(orig[1], filelist[1]);
- Assert.assertEquals(orig[4], filelist[2]);
+ assertEquals(3, filelist.length);
+ assertEquals(orig[0], filelist[0]);
+ assertEquals(orig[1], filelist[1]);
+ assertEquals(orig[4], filelist[2]);
}
@Test
public void testForceSyncDefaultEnabled() {
File file = new File("foo.10027c6de");
FileTxnLog log = new FileTxnLog(file);
- Assert.assertTrue(log.isForceSync());
+ assertTrue(log.isForceSync());
}
@Test
public void testForceSyncDefaultDisabled() {
try {
File file = new File("foo.10027c6de");
- System.setProperty("zookeeper.forceSync","no");
+ System.setProperty("zookeeper.forceSync", "no");
FileTxnLog log = new FileTxnLog(file);
- Assert.assertFalse(log.isForceSync());
- }
- finally {
+ assertFalse(log.isForceSync());
+ } finally {
//Reset back to default.
- System.setProperty("zookeeper.forceSync","yes");
+ System.setProperty("zookeeper.forceSync", "yes");
}
}
@@ -126,8 +125,8 @@ public class ZooKeeperServerTest extends ZKTestCase {
if (!f.exists()) {
f.createNewFile();
}
- Assert.assertFalse("Snapshot file size is greater than 9 bytes", SnapStream.isValidSnapshot(f));
- Assert.assertTrue("Can't delete file", f.delete());
+ assertFalse("Snapshot file size is greater than 9 bytes", SnapStream.isValidSnapshot(f));
+ assertTrue("Can't delete file", f.delete());
} catch (IOException e) {
} finally {
if (null != tmpFileDir) {
@@ -135,4 +134,5 @@ public class ZooKeeperServerTest extends ZKTestCase {
}
}
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/ZooKeeperThreadTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/ZooKeeperThreadTest.java
index 2c737fc55..fe53f4d12 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/ZooKeeperThreadTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/ZooKeeperThreadTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -15,17 +15,17 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
package org.apache.zookeeper.server;
+import static org.junit.Assert.assertTrue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
-
-
import org.apache.zookeeper.ZKTestCase;
-import org.junit.Assert;
import org.junit.Test;
public class ZooKeeperThreadTest extends ZKTestCase {
+
private CountDownLatch runningLatch = new CountDownLatch(1);
public class MyThread extends ZooKeeperThread {
@@ -42,6 +42,7 @@ public class ZooKeeperThreadTest extends ZKTestCase {
protected void handleException(String thName, Throwable e) {
runningLatch.countDown();
}
+
}
public class MyCriticalThread extends ZooKeeperCriticalThread {
@@ -64,6 +65,7 @@ public class ZooKeeperThreadTest extends ZKTestCase {
protected void handleException(String thName, Throwable e) {
runningLatch.countDown();
}
+
}
/**
@@ -73,13 +75,12 @@ public class ZooKeeperThreadTest extends ZKTestCase {
public void testUncaughtException() throws Exception {
MyThread t1 = new MyThread("Test-Thread");
t1.start();
- Assert.assertTrue("Uncaught exception is not properly handled.",
- runningLatch.await(10000, TimeUnit.MILLISECONDS));
+ assertTrue("Uncaught exception is not properly handled.", runningLatch.await(10000, TimeUnit.MILLISECONDS));
runningLatch = new CountDownLatch(1);
MyCriticalThread t2 = new MyCriticalThread("Test-Critical-Thread");
t2.start();
- Assert.assertTrue("Uncaught exception is not properly handled.",
- runningLatch.await(10000, TimeUnit.MILLISECONDS));
+ assertTrue("Uncaught exception is not properly handled.", runningLatch.await(10000, TimeUnit.MILLISECONDS));
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/ZxidRolloverTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/ZxidRolloverTest.java
index 838b0a809..42e366ec5 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/ZxidRolloverTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/ZxidRolloverTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,7 +18,10 @@
package org.apache.zookeeper.server;
-
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.KeeperException.ConnectionLossException;
@@ -31,7 +34,6 @@ import org.apache.zookeeper.test.ClientTest;
import org.apache.zookeeper.test.QuorumUtil;
import org.apache.zookeeper.test.QuorumUtil.PeerStruct;
import org.junit.After;
-import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
@@ -41,6 +43,7 @@ import org.slf4j.LoggerFactory;
* Verify ZOOKEEPER-1277 - ensure that we handle epoch rollover correctly.
*/
public class ZxidRolloverTest extends ZKTestCase {
+
private static final Logger LOG = LoggerFactory.getLogger(ZxidRolloverTest.class);
private QuorumUtil qu;
@@ -49,9 +52,9 @@ public class ZxidRolloverTest extends ZKTestCase {
private CountdownWatcher[] zkClientWatchers = new CountdownWatcher[3];
private int idxLeader;
private int idxFollower;
-
+
private ZooKeeper getClient(int idx) {
- return zkClients[idx-1];
+ return zkClients[idx - 1];
}
@Before
@@ -70,11 +73,12 @@ public class ZxidRolloverTest extends ZKTestCase {
PeerStruct peer = qu.getPeer(i + 1);
zkClients[i] = new ZooKeeper(
"127.0.0.1:" + peer.clientPort,
- ClientTest.CONNECTION_TIMEOUT, zkClientWatchers[i]);
+ ClientTest.CONNECTION_TIMEOUT,
+ zkClientWatchers[i]);
}
waitForClientsConnected();
}
-
+
private void waitForClientsConnected() throws Exception {
for (int i = 0; i < zkClients.length; i++) {
zkClientWatchers[i].waitForConnected(ClientTest.CONNECTION_TIMEOUT);
@@ -93,7 +97,7 @@ public class ZxidRolloverTest extends ZKTestCase {
/**
* Ensure the client is able to talk to the server.
- *
+ *
* @param idx the idx of the server the client is talking to
*/
private void checkClientConnected(int idx) throws Exception {
@@ -102,7 +106,7 @@ public class ZxidRolloverTest extends ZKTestCase {
return;
}
try {
- Assert.assertNull(zk.exists("/foofoofoo-connected", false));
+ assertNull(zk.exists("/foofoofoo-connected", false));
} catch (ConnectionLossException e) {
// second chance...
// in some cases, leader change in particular, the timing is
@@ -113,10 +117,11 @@ public class ZxidRolloverTest extends ZKTestCase {
// in the try, this catches that case and waits for the server
// to come back
PeerStruct peer = qu.getPeer(idx);
- Assert.assertTrue("Waiting for server down", ClientBase.waitForServerUp(
- "127.0.0.1:" + peer.clientPort, ClientBase.CONNECTION_TIMEOUT));
+ assertTrue(
+ "Waiting for server down",
+ ClientBase.waitForServerUp("127.0.0.1:" + peer.clientPort, ClientBase.CONNECTION_TIMEOUT));
- Assert.assertNull(zk.exists("/foofoofoo-connected", false));
+ assertNull(zk.exists("/foofoofoo-connected", false));
}
}
@@ -131,7 +136,7 @@ public class ZxidRolloverTest extends ZKTestCase {
/**
* Ensure the client is able to talk to the server
- *
+ *
* @param idx the idx of the server the client is talking to
*/
private void checkClientDisconnected(int idx) throws Exception {
@@ -140,8 +145,8 @@ public class ZxidRolloverTest extends ZKTestCase {
return;
}
try {
- Assert.assertNull(zk.exists("/foofoofoo-disconnected", false));
- Assert.fail("expected client to be disconnected");
+ assertNull(zk.exists("/foofoofoo-disconnected", false));
+ fail("expected client to be disconnected");
} catch (KeeperException e) {
// success
}
@@ -156,8 +161,7 @@ public class ZxidRolloverTest extends ZKTestCase {
private void start(int idx) throws Exception {
qu.start(idx);
for (String hp : qu.getConnString().split(",")) {
- Assert.assertTrue("waiting for server up", ClientBase.waitForServerUp(hp,
- ClientTest.CONNECTION_TIMEOUT));
+ assertTrue("waiting for server up", ClientBase.waitForServerUp(hp, ClientTest.CONNECTION_TIMEOUT));
}
checkLeader();
@@ -167,7 +171,7 @@ public class ZxidRolloverTest extends ZKTestCase {
private void checkLeader() {
idxLeader = 1;
- while(qu.getPeer(idxLeader).peer.leader == null) {
+ while (qu.getPeer(idxLeader).peer.leader == null) {
idxLeader++;
}
idxFollower = (idxLeader == 1 ? 2 : 1);
@@ -180,14 +184,15 @@ public class ZxidRolloverTest extends ZKTestCase {
// all clients should be disconnected
checkClientsDisconnected();
}
-
+
private void shutdown(int idx) throws Exception {
qu.shutdown(idx);
// leader will shutdown, remaining followers will elect a new leader
PeerStruct peer = qu.getPeer(idx);
- Assert.assertTrue("Waiting for server down", ClientBase.waitForServerDown(
- "127.0.0.1:" + peer.clientPort, ClientBase.CONNECTION_TIMEOUT));
+ assertTrue(
+ "Waiting for server down",
+ ClientBase.waitForServerDown("127.0.0.1:" + peer.clientPort, ClientBase.CONNECTION_TIMEOUT));
// if idx is the the leader then everyone will get disconnected,
// otherwise if idx is a follower then just that client will get
@@ -228,8 +233,7 @@ public class ZxidRolloverTest extends ZKTestCase {
int j = 0;
try {
for (int i = start; i < start + count; i++) {
- zk.create("/foo" + i, new byte[0], Ids.READ_ACL_UNSAFE,
- CreateMode.EPHEMERAL);
+ zk.create("/foo" + i, new byte[0], Ids.READ_ACL_UNSAFE, CreateMode.EPHEMERAL);
j++;
}
} catch (ConnectionLossException e) {
@@ -245,10 +249,10 @@ public class ZxidRolloverTest extends ZKTestCase {
private void checkNodes(ZooKeeper zk, int start, int count) throws Exception {
LOG.info("Validating nodes {} thru {}", start, (start + count));
for (int i = start; i < start + count; i++) {
- Assert.assertNotNull(zk.exists("/foo" + i, false));
+ assertNotNull(zk.exists("/foo" + i, false));
LOG.error("Exists zxid:{}", Long.toHexString(zk.exists("/foo" + i, false).getCzxid()));
}
- Assert.assertNull(zk.exists("/foo" + (start + count), false));
+ assertNull(zk.exists("/foo" + (start + count), false));
}
/**
@@ -261,7 +265,7 @@ public class ZxidRolloverTest extends ZKTestCase {
ZooKeeper zk = getClient((idxLeader == 1 ? 2 : 1));
int countCreated = createNodes(zk, 0, 10);
-
+
checkNodes(zk, 0, countCreated);
}
@@ -272,11 +276,11 @@ public class ZxidRolloverTest extends ZKTestCase {
@Test
public void testRolloverThenRestart() throws Exception {
ZooKeeper zk = getClient(idxFollower);
-
+
int countCreated = createNodes(zk, 0, 10);
adjustEpochNearEnd();
-
+
countCreated += createNodes(zk, countCreated, 10);
shutdownAll();
@@ -287,7 +291,7 @@ public class ZxidRolloverTest extends ZKTestCase {
countCreated += createNodes(zk, countCreated, 10);
adjustEpochNearEnd();
-
+
checkNodes(zk, 0, countCreated);
countCreated += createNodes(zk, countCreated, 10);
@@ -306,8 +310,8 @@ public class ZxidRolloverTest extends ZKTestCase {
countCreated += createNodes(zk, countCreated, 10);
// sanity check
- Assert.assertTrue(countCreated > 0);
- Assert.assertTrue(countCreated < 60);
+ assertTrue(countCreated > 0);
+ assertTrue(countCreated < 60);
}
/**
@@ -321,7 +325,7 @@ public class ZxidRolloverTest extends ZKTestCase {
int countCreated = createNodes(zk, 0, 10);
adjustEpochNearEnd();
-
+
countCreated += createNodes(zk, countCreated, 10);
shutdown(idxFollower);
@@ -331,7 +335,7 @@ public class ZxidRolloverTest extends ZKTestCase {
countCreated += createNodes(zk, countCreated, 10);
adjustEpochNearEnd();
-
+
checkNodes(zk, 0, countCreated);
countCreated += createNodes(zk, countCreated, 10);
@@ -348,8 +352,8 @@ public class ZxidRolloverTest extends ZKTestCase {
countCreated += createNodes(zk, countCreated, 10);
// sanity check
- Assert.assertTrue(countCreated > 0);
- Assert.assertTrue(countCreated < 60);
+ assertTrue(countCreated > 0);
+ assertTrue(countCreated < 60);
}
/**
@@ -363,7 +367,7 @@ public class ZxidRolloverTest extends ZKTestCase {
int countCreated = createNodes(zk, 0, 10);
adjustEpochNearEnd();
-
+
checkNodes(zk, 0, countCreated);
shutdown(idxLeader);
@@ -374,7 +378,7 @@ public class ZxidRolloverTest extends ZKTestCase {
countCreated += createNodes(zk, countCreated, 10);
adjustEpochNearEnd();
-
+
checkNodes(zk, 0, countCreated);
countCreated += createNodes(zk, countCreated, 10);
@@ -393,8 +397,8 @@ public class ZxidRolloverTest extends ZKTestCase {
countCreated += createNodes(zk, countCreated, 10);
// sanity check
- Assert.assertTrue(countCreated > 0);
- Assert.assertTrue(countCreated < 50);
+ assertTrue(countCreated > 0);
+ assertTrue(countCreated < 50);
}
/**
@@ -408,7 +412,7 @@ public class ZxidRolloverTest extends ZKTestCase {
int countCreated = createNodes(zk, 0, 10);
adjustEpochNearEnd();
-
+
countCreated += createNodes(zk, countCreated, 10);
adjustEpochNearEnd();
@@ -416,7 +420,7 @@ public class ZxidRolloverTest extends ZKTestCase {
countCreated += createNodes(zk, countCreated, 10);
adjustEpochNearEnd();
-
+
countCreated += createNodes(zk, countCreated, 10);
adjustEpochNearEnd();
@@ -440,7 +444,8 @@ public class ZxidRolloverTest extends ZKTestCase {
countCreated += createNodes(zk, countCreated, 10);
// sanity check
- Assert.assertTrue(countCreated > 0);
- Assert.assertTrue(countCreated < 70);
+ assertTrue(countCreated > 0);
+ assertTrue(countCreated < 70);
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/admin/CommandResponseTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/admin/CommandResponseTest.java
index ab8c25860..20dc40792 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/admin/CommandResponseTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/admin/CommandResponseTest.java
@@ -17,26 +17,30 @@
package org.apache.zookeeper.server.admin;
+import static org.junit.Assert.assertEquals;
import java.util.HashMap;
import java.util.Map;
import org.apache.zookeeper.ZKTestCase;
import org.junit.Before;
import org.junit.Test;
-import static org.junit.Assert.assertEquals;
public class CommandResponseTest extends ZKTestCase {
+
private CommandResponse r;
- @Before public void setUp() throws Exception {
+ @Before
+ public void setUp() throws Exception {
r = new CommandResponse("makemeasandwich", "makeityourself");
}
- @Test public void testGetters() {
+ @Test
+ public void testGetters() {
assertEquals("makemeasandwich", r.getCommand());
assertEquals("makeityourself", r.getError());
}
- @Test public void testMap() {
+ @Test
+ public void testMap() {
r.put("missing", "sudo");
Map<String, Object> m = new HashMap<String, Object>();
m.put("origin", "xkcd");
@@ -51,4 +55,5 @@ public class CommandResponseTest extends ZKTestCase {
assertEquals("xkcd", rmap.get("origin"));
assertEquals("http://xkcd.com/149/", rmap.get("url"));
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/admin/CommandsTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/admin/CommandsTest.java
index 86b5207ee..6afbbe2e0 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/admin/CommandsTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/admin/CommandsTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -25,16 +25,13 @@ import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
-
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import org.apache.zookeeper.metrics.MetricsUtils;
-
import org.apache.zookeeper.server.ServerCnxnFactory;
-import org.apache.zookeeper.server.ServerMetrics;
import org.apache.zookeeper.server.ServerStats;
import org.apache.zookeeper.server.ZooKeeperServer;
import org.apache.zookeeper.server.quorum.BufferStats;
@@ -42,6 +39,7 @@ import org.apache.zookeeper.test.ClientBase;
import org.junit.Test;
public class CommandsTest extends ClientBase {
+
/**
* Checks that running a given Command returns the expected Map. Asserts
* that all specified keys are present with values of the specified types
@@ -56,8 +54,7 @@ public class CommandsTest extends ClientBase {
* @throws IOException
* @throws InterruptedException
*/
- public void testCommand(String cmdName, Map<String, String> kwargs, Field... fields)
- throws IOException, InterruptedException {
+ public void testCommand(String cmdName, Map<String, String> kwargs, Field... fields) throws IOException, InterruptedException {
ZooKeeperServer zks = serverFactory.getZooKeeperServer();
Map<String, Object> result = Commands.runCommand(cmdName, zks, kwargs).toMap();
@@ -69,61 +66,56 @@ public class CommandsTest extends ClientBase {
for (Field field : fields) {
String k = field.key;
- assertTrue("Result from command " + cmdName + " missing field \"" + k + "\""
- + "\n" + result,
- result.containsKey(k));
+ assertTrue("Result from command "
+ + cmdName
+ + " missing field \""
+ + k
+ + "\""
+ + "\n"
+ + result, result.containsKey(k));
Class<?> t = field.type;
Object v = result.remove(k);
- assertTrue("\"" + k + "\" field from command " + cmdName + " should be of type " + t
- + ", is actually of type " + v.getClass(),
- t.isAssignableFrom(v.getClass()));
+ assertTrue("\""
+ + k
+ + "\" field from command "
+ + cmdName
+ + " should be of type "
+ + t
+ + ", is actually of type "
+ + v.getClass(), t.isAssignableFrom(v.getClass()));
}
- assertTrue("Result from command " + cmdName + " contains extra fields: " + result,
- result.isEmpty());
+ assertTrue("Result from command " + cmdName + " contains extra fields: " + result, result.isEmpty());
}
- public void testCommand(String cmdName, Field... fields)
- throws IOException, InterruptedException {
+ public void testCommand(String cmdName, Field... fields) throws IOException, InterruptedException {
testCommand(cmdName, new HashMap<String, String>(), fields);
}
private static class Field {
+
String key;
Class<?> type;
Field(String key, Class<?> type) {
this.key = key;
this.type = type;
}
+
}
@Test
public void testConfiguration() throws IOException, InterruptedException {
- testCommand("configuration",
- new Field("client_port", Integer.class),
- new Field("data_dir", String.class),
- new Field("data_log_dir", String.class),
- new Field("tick_time", Integer.class),
- new Field("max_client_cnxns", Integer.class),
- new Field("min_session_timeout", Integer.class),
- new Field("max_session_timeout", Integer.class),
- new Field("server_id", Long.class),
- new Field("client_port_listen_backlog", Integer.class));
+ testCommand("configuration", new Field("client_port", Integer.class), new Field("data_dir", String.class), new Field("data_log_dir", String.class), new Field("tick_time", Integer.class), new Field("max_client_cnxns", Integer.class), new Field("min_session_timeout", Integer.class), new Field("max_session_timeout", Integer.class), new Field("server_id", Long.class), new Field("client_port_listen_backlog", Integer.class));
}
@Test
public void testConnections() throws IOException, InterruptedException {
- testCommand("connections",
- new Field("connections", Iterable.class),
- new Field("secure_connections", Iterable.class)
- );
+ testCommand("connections", new Field("connections", Iterable.class), new Field("secure_connections", Iterable.class));
}
@Test
public void testObservers() throws IOException, InterruptedException {
- testCommand("observers",
- new Field("synced_observers", Integer.class),
- new Field("observers", Iterable.class));
+ testCommand("observers", new Field("synced_observers", Integer.class), new Field("observers", Iterable.class));
}
@Test
@@ -138,98 +130,49 @@ public class CommandsTest extends ClientBase {
@Test
public void testDump() throws IOException, InterruptedException {
- testCommand("dump",
- new Field("expiry_time_to_session_ids", Map.class),
- new Field("session_id_to_ephemeral_paths", Map.class));
+ testCommand("dump", new Field("expiry_time_to_session_ids", Map.class), new Field("session_id_to_ephemeral_paths", Map.class));
}
@Test
public void testEnvironment() throws IOException, InterruptedException {
- testCommand("environment",
- new Field("zookeeper.version", String.class),
- new Field("host.name", String.class),
- new Field("java.version", String.class),
- new Field("java.vendor", String.class),
- new Field("java.home", String.class),
- new Field("java.class.path", String.class),
- new Field("java.library.path", String.class),
- new Field("java.io.tmpdir", String.class),
- new Field("java.compiler", String.class),
- new Field("os.name", String.class),
- new Field("os.arch", String.class),
- new Field("os.version", String.class),
- new Field("user.name", String.class),
- new Field("user.home", String.class),
- new Field("user.dir", String.class),
- new Field("os.memory.free", String.class),
- new Field("os.memory.max", String.class),
- new Field("os.memory.total", String.class));
+ testCommand("environment", new Field("zookeeper.version", String.class), new Field("host.name", String.class), new Field("java.version", String.class), new Field("java.vendor", String.class), new Field("java.home", String.class), new Field("java.class.path", String.class), new Field("java.library.path", String.class), new Field("java.io.tmpdir", String.class), new Field("java.compiler", String.class), new Field("os.name", String.class), new Field("os.arch", String.class), new Field("os.version", String.class), new Field("user.name", String.class), new Field("user.home", String.class), new Field("user.dir", String.class), new Field("os.memory.free", String.class), new Field("os.memory.max", String.class), new Field("os.memory.total", String.class));
}
@Test
public void testGetTraceMask() throws IOException, InterruptedException {
- testCommand("get_trace_mask",
- new Field("tracemask", Long.class));
+ testCommand("get_trace_mask", new Field("tracemask", Long.class));
}
@Test
public void testIsReadOnly() throws IOException, InterruptedException {
- testCommand("is_read_only",
- new Field("read_only", Boolean.class));
+ testCommand("is_read_only", new Field("read_only", Boolean.class));
}
@Test
public void testLastSnapshot() throws IOException, InterruptedException {
- testCommand("last_snapshot",
- new Field("zxid", String.class),
- new Field("timestamp", Long.class));
+ testCommand("last_snapshot", new Field("zxid", String.class), new Field("timestamp", Long.class));
}
@Test
public void testMonitor() throws IOException, InterruptedException {
- ArrayList<Field> fields = new ArrayList<>(Arrays.asList(
- new Field("version", String.class),
- new Field("avg_latency", Double.class),
- new Field("max_latency", Long.class),
- new Field("min_latency", Long.class),
- new Field("packets_received", Long.class),
- new Field("packets_sent", Long.class),
- new Field("num_alive_connections", Integer.class),
- new Field("outstanding_requests", Long.class),
- new Field("server_state", String.class),
- new Field("znode_count", Integer.class),
- new Field("watch_count", Integer.class),
- new Field("ephemerals_count", Integer.class),
- new Field("approximate_data_size", Long.class),
- new Field("open_file_descriptor_count", Long.class),
- new Field("max_file_descriptor_count", Long.class),
- new Field("last_client_response_size", Integer.class),
- new Field("max_client_response_size", Integer.class),
- new Field("min_client_response_size", Integer.class),
- new Field("uptime", Long.class),
- new Field("global_sessions", Long.class),
- new Field("local_sessions", Long.class),
- new Field("connection_drop_probability", Double.class)
- ));
+ ArrayList<Field> fields = new ArrayList<>(Arrays.asList(new Field("version", String.class), new Field("avg_latency", Double.class), new Field("max_latency", Long.class), new Field("min_latency", Long.class), new Field("packets_received", Long.class), new Field("packets_sent", Long.class), new Field("num_alive_connections", Integer.class), new Field("outstanding_requests", Long.class), new Field("server_state", String.class), new Field("znode_count", Integer.class), new Field("watch_count", Integer.class), new Field("ephemerals_count", Integer.class), new Field("approximate_data_size", Long.class), new Field("open_file_descriptor_count", Long.class), new Field("max_file_descriptor_count", Long.class), new Field("last_client_response_size", Integer.class), new Field("max_client_response_size", Integer.class), new Field("min_client_response_size", Integer.class), new Field("uptime", Long.class), new Field("global_sessions", Long.class), new Field("local_sessions", Long.class), new Field("connection_drop_probability", Double.class)));
Map<String, Object> metrics = MetricsUtils.currentServerMetrics();
-
+
for (String metric : metrics.keySet()) {
- boolean alreadyDefined = fields
- .stream()
- .anyMatch(f -> {
- return f.key.equals(metric);
- });
+ boolean alreadyDefined = fields.stream().anyMatch(f -> {
+ return f.key.equals(metric);
+ });
if (alreadyDefined) {
// known metrics are defined statically in the block above
continue;
}
if (metric.startsWith("avg_")) {
- fields.add(new Field(metric, Double.class));
+ fields.add(new Field(metric, Double.class));
} else {
fields.add(new Field(metric, Long.class));
}
}
- Field fieldsArray[] = fields.toArray(new Field[0]);
+ Field[] fieldsArray = fields.toArray(new Field[0]);
testCommand("monitor", fieldsArray);
}
@@ -240,31 +183,19 @@ public class CommandsTest extends ClientBase {
@Test
public void testServerStats() throws IOException, InterruptedException {
- testCommand("server_stats",
- new Field("version", String.class),
- new Field("read_only", Boolean.class),
- new Field("server_stats", ServerStats.class),
- new Field("node_count", Integer.class),
- new Field("client_response", BufferStats.class));
+ testCommand("server_stats", new Field("version", String.class), new Field("read_only", Boolean.class), new Field("server_stats", ServerStats.class), new Field("node_count", Integer.class), new Field("client_response", BufferStats.class));
}
@Test
public void testSetTraceMask() throws IOException, InterruptedException {
Map<String, String> kwargs = new HashMap<String, String>();
kwargs.put("traceMask", "1");
- testCommand("set_trace_mask", kwargs,
- new Field("tracemask", Long.class));
+ testCommand("set_trace_mask", kwargs, new Field("tracemask", Long.class));
}
@Test
public void testStat() throws IOException, InterruptedException {
- testCommand("stats",
- new Field("version", String.class),
- new Field("read_only", Boolean.class),
- new Field("server_stats", ServerStats.class),
- new Field("node_count", Integer.class),
- new Field("connections", Iterable.class),
- new Field("client_response", BufferStats.class));
+ testCommand("stats", new Field("version", String.class), new Field("read_only", Boolean.class), new Field("server_stats", ServerStats.class), new Field("node_count", Integer.class), new Field("connections", Iterable.class), new Field("client_response", BufferStats.class));
}
@Test
@@ -274,22 +205,17 @@ public class CommandsTest extends ClientBase {
@Test
public void testWatches() throws IOException, InterruptedException {
- testCommand("watches",
- new Field("session_id_to_watched_paths", Map.class));
+ testCommand("watches", new Field("session_id_to_watched_paths", Map.class));
}
@Test
public void testWatchesByPath() throws IOException, InterruptedException {
- testCommand("watches_by_path",
- new Field("path_to_session_ids", Map.class));
+ testCommand("watches_by_path", new Field("path_to_session_ids", Map.class));
}
@Test
public void testWatchSummary() throws IOException, InterruptedException {
- testCommand("watch_summary",
- new Field("num_connections", Integer.class),
- new Field("num_paths", Integer.class),
- new Field("num_total_watches", Integer.class));
+ testCommand("watch_summary", new Field("num_connections", Integer.class), new Field("num_paths", Integer.class), new Field("num_total_watches", Integer.class));
}
@Test
@@ -307,4 +233,5 @@ public class CommandsTest extends ClientBase {
assertThat(response.toMap().containsKey("connections"), is(true));
assertThat(response.toMap().containsKey("secure_connections"), is(true));
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/admin/JettyAdminServerTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/admin/JettyAdminServerTest.java
index 26ca2f9e3..71c244684 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/admin/JettyAdminServerTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/admin/JettyAdminServerTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,20 +18,25 @@
package org.apache.zookeeper.server.admin;
+import static org.junit.Assert.assertTrue;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
-import java.net.MalformedURLException;
import java.net.URL;
+import java.security.GeneralSecurityException;
+import java.security.Security;
+import java.security.cert.X509Certificate;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
+import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
-
-import org.apache.zookeeper.common.KeyStoreFileType;
-import org.apache.zookeeper.common.X509Exception.SSLContextException;
+import javax.net.ssl.TrustManager;
+import javax.net.ssl.X509TrustManager;
import org.apache.zookeeper.PortAssignment;
import org.apache.zookeeper.ZKTestCase;
+import org.apache.zookeeper.common.KeyStoreFileType;
+import org.apache.zookeeper.common.X509Exception.SSLContextException;
import org.apache.zookeeper.common.X509KeyType;
import org.apache.zookeeper.common.X509TestContext;
import org.apache.zookeeper.server.ZooKeeperServerMainTest;
@@ -40,20 +45,13 @@ import org.apache.zookeeper.server.quorum.QuorumPeerTestBase;
import org.apache.zookeeper.test.ClientBase;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.junit.After;
-import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import javax.net.ssl.SSLContext;
-import javax.net.ssl.TrustManager;
-import javax.net.ssl.X509TrustManager;
-import java.security.Security;
-import java.security.cert.X509Certificate;
-import java.security.GeneralSecurityException;
+public class JettyAdminServerTest extends ZKTestCase {
-public class JettyAdminServerTest extends ZKTestCase{
protected static final Logger LOG = LoggerFactory.getLogger(JettyAdminServerTest.class);
private static final String URL_FORMAT = "http://localhost:%d/commands";
@@ -75,16 +73,18 @@ public class JettyAdminServerTest extends ZKTestCase{
try {
tmpDir = ClientBase.createEmptyTestDir();
x509TestContext = X509TestContext.newBuilder()
- .setTempDir(tmpDir)
- .setKeyStorePassword("")
- .setKeyStoreKeyType(X509KeyType.EC)
- .setTrustStorePassword("")
- .setTrustStoreKeyType(X509KeyType.EC)
- .build();
- System.setProperty("zookeeper.ssl.quorum.keyStore.location",
- x509TestContext.getKeyStoreFile(KeyStoreFileType.PEM).getAbsolutePath());
- System.setProperty("zookeeper.ssl.quorum.trustStore.location",
- x509TestContext.getTrustStoreFile(KeyStoreFileType.PEM).getAbsolutePath());
+ .setTempDir(tmpDir)
+ .setKeyStorePassword("")
+ .setKeyStoreKeyType(X509KeyType.EC)
+ .setTrustStorePassword("")
+ .setTrustStoreKeyType(X509KeyType.EC)
+ .build();
+ System.setProperty(
+ "zookeeper.ssl.quorum.keyStore.location",
+ x509TestContext.getKeyStoreFile(KeyStoreFileType.PEM).getAbsolutePath());
+ System.setProperty(
+ "zookeeper.ssl.quorum.trustStore.location",
+ x509TestContext.getTrustStoreFile(KeyStoreFileType.PEM).getAbsolutePath());
} catch (Exception e) {
LOG.info("Problems encountered while setting up encryption for Jetty admin server test: " + e);
}
@@ -95,10 +95,14 @@ public class JettyAdminServerTest extends ZKTestCase{
System.setProperty("zookeeper.admin.portUnification", "true");
// Create a trust manager that does not validate certificate chains
- TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
- public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; }
- public void checkClientTrusted(X509Certificate[] certs, String authType) {}
- public void checkServerTrusted(X509Certificate[] certs, String authType) {}
+ TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
+ public java.security.cert.X509Certificate[] getAcceptedIssuers() {
+ return null;
+ }
+ public void checkClientTrusted(X509Certificate[] certs, String authType) {
+ }
+ public void checkServerTrusted(X509Certificate[] certs, String authType) {
+ }
}};
// Create all-trusting trust manager
@@ -106,11 +110,15 @@ public class JettyAdminServerTest extends ZKTestCase{
try {
sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
- } catch (Exception e) { LOG.error("Failed to customize encryption for HTTPS: e"); }
+ } catch (Exception e) {
+ LOG.error("Failed to customize encryption for HTTPS: e");
+ }
// Create all-trusting hostname verifier
HostnameVerifier allValid = new HostnameVerifier() {
- public boolean verify(String hostname, SSLSession session) { return true; }
+ public boolean verify(String hostname, SSLSession session) {
+ return true;
+ }
};
// This is a temporary fix while we do not yet have certificates set up to make
@@ -140,7 +148,7 @@ public class JettyAdminServerTest extends ZKTestCase{
*/
@Test
public void testJettyAdminServer() throws AdminServerException, IOException, SSLContextException, GeneralSecurityException {
- JettyAdminServer server = new JettyAdminServer();;
+ JettyAdminServer server = new JettyAdminServer();
try {
server.start();
queryAdminServer(jettyAdminPort);
@@ -161,17 +169,17 @@ public class JettyAdminServerTest extends ZKTestCase{
ZooKeeperServerMainTest.MainThread main = new ZooKeeperServerMainTest.MainThread(CLIENT_PORT, false, null);
main.start();
- Assert.assertTrue("waiting for server being up",
- ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT,
- ClientBase.CONNECTION_TIMEOUT));
+ assertTrue(
+ "waiting for server being up",
+ ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT, ClientBase.CONNECTION_TIMEOUT));
queryAdminServer(jettyAdminPort);
main.shutdown();
- Assert.assertTrue("waiting for server down",
- ClientBase.waitForServerDown("127.0.0.1:" + CLIENT_PORT,
- ClientBase.CONNECTION_TIMEOUT));
+ assertTrue(
+ "waiting for server down",
+ ClientBase.waitForServerDown("127.0.0.1:" + CLIENT_PORT, ClientBase.CONNECTION_TIMEOUT));
}
/**
@@ -187,13 +195,15 @@ public class JettyAdminServerTest extends ZKTestCase{
final int ADMIN_SERVER_PORT1 = PortAssignment.unique();
final int ADMIN_SERVER_PORT2 = PortAssignment.unique();
- String quorumCfgSection = String.format
- ("server.1=127.0.0.1:%d:%d;%d\nserver.2=127.0.0.1:%d:%d;%d",
- PortAssignment.unique(), PortAssignment.unique(), CLIENT_PORT_QP1,
- PortAssignment.unique(), PortAssignment.unique(), CLIENT_PORT_QP2
- );
- QuorumPeerTestBase.MainThread q1 = new QuorumPeerTestBase.MainThread(
- 1, CLIENT_PORT_QP1, ADMIN_SERVER_PORT1, quorumCfgSection, null);
+ String quorumCfgSection = String.format(
+ "server.1=127.0.0.1:%d:%d;%d\nserver.2=127.0.0.1:%d:%d;%d",
+ PortAssignment.unique(),
+ PortAssignment.unique(),
+ CLIENT_PORT_QP1,
+ PortAssignment.unique(),
+ PortAssignment.unique(),
+ CLIENT_PORT_QP2);
+ QuorumPeerTestBase.MainThread q1 = new QuorumPeerTestBase.MainThread(1, CLIENT_PORT_QP1, ADMIN_SERVER_PORT1, quorumCfgSection, null);
q1.start();
// Since JettyAdminServer reads a system property to determine its port,
@@ -201,18 +211,17 @@ public class JettyAdminServerTest extends ZKTestCase{
// again with the second port number
Thread.sleep(500);
- QuorumPeerTestBase.MainThread q2 = new QuorumPeerTestBase.MainThread(
- 2, CLIENT_PORT_QP2, ADMIN_SERVER_PORT2, quorumCfgSection, null);
+ QuorumPeerTestBase.MainThread q2 = new QuorumPeerTestBase.MainThread(2, CLIENT_PORT_QP2, ADMIN_SERVER_PORT2, quorumCfgSection, null);
q2.start();
Thread.sleep(500);
- Assert.assertTrue("waiting for server 1 being up",
- ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT_QP1,
- ClientBase.CONNECTION_TIMEOUT));
- Assert.assertTrue("waiting for server 2 being up",
- ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT_QP2,
- ClientBase.CONNECTION_TIMEOUT));
+ assertTrue(
+ "waiting for server 1 being up",
+ ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT_QP1, ClientBase.CONNECTION_TIMEOUT));
+ assertTrue(
+ "waiting for server 2 being up",
+ ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT_QP2, ClientBase.CONNECTION_TIMEOUT));
queryAdminServer(ADMIN_SERVER_PORT1);
queryAdminServer(ADMIN_SERVER_PORT2);
@@ -220,19 +229,19 @@ public class JettyAdminServerTest extends ZKTestCase{
q1.shutdown();
q2.shutdown();
- Assert.assertTrue("waiting for server 1 down",
- ClientBase.waitForServerDown("127.0.0.1:" + CLIENT_PORT_QP1,
- ClientBase.CONNECTION_TIMEOUT));
- Assert.assertTrue("waiting for server 2 down",
- ClientBase.waitForServerDown("127.0.0.1:" + CLIENT_PORT_QP2,
- ClientBase.CONNECTION_TIMEOUT));
+ assertTrue(
+ "waiting for server 1 down",
+ ClientBase.waitForServerDown("127.0.0.1:" + CLIENT_PORT_QP1, ClientBase.CONNECTION_TIMEOUT));
+ assertTrue(
+ "waiting for server 2 down",
+ ClientBase.waitForServerDown("127.0.0.1:" + CLIENT_PORT_QP2, ClientBase.CONNECTION_TIMEOUT));
}
/**
* Check that we can load the commands page of an AdminServer running at
* localhost:port. (Note that this should work even if no zk server is set.)
*/
- private void queryAdminServer(int port) throws MalformedURLException, IOException, SSLContextException {
+ private void queryAdminServer(int port) throws IOException, SSLContextException {
queryAdminServer(String.format(URL_FORMAT, port), false);
queryAdminServer(String.format(HTTPS_URL_FORMAT, port), true);
}
@@ -240,7 +249,7 @@ public class JettyAdminServerTest extends ZKTestCase{
/**
* Check that loading urlStr results in a non-zero length response.
*/
- private void queryAdminServer(String urlStr, boolean encrypted) throws MalformedURLException, IOException, SSLContextException {
+ private void queryAdminServer(String urlStr, boolean encrypted) throws IOException, SSLContextException {
URL url = new URL(urlStr);
BufferedReader dis;
if (!encrypted) {
@@ -250,6 +259,7 @@ public class JettyAdminServerTest extends ZKTestCase{
dis = new BufferedReader(new InputStreamReader(conn.getInputStream()));
}
String line = dis.readLine();
- Assert.assertTrue(line.length() > 0);
+ assertTrue(line.length() > 0);
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/metric/AvgMinMaxCounterSetTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/metric/AvgMinMaxCounterSetTest.java
index 308698148..50e3788cc 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/metric/AvgMinMaxCounterSetTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/metric/AvgMinMaxCounterSetTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -15,16 +15,17 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
package org.apache.zookeeper.server.metric;
+import static org.junit.Assert.assertEquals;
+import java.util.Map;
import org.apache.zookeeper.ZKTestCase;
-import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
-import java.util.Map;
-
public class AvgMinMaxCounterSetTest extends ZKTestCase {
+
private AvgMinMaxCounterSet testCounterSet;
@Before
@@ -48,19 +49,19 @@ public class AvgMinMaxCounterSetTest extends ZKTestCase {
Map<String, Object> values = testCounterSet.values();
- Assert.assertEquals("There should be 10 values in the set", 10, values.size());
+ assertEquals("There should be 10 values in the set", 10, values.size());
- Assert.assertEquals("avg_key1_test should =0", 0D, values.get("avg_key1_test"));
- Assert.assertEquals("min_key1_test should =0", 0L, values.get("min_key1_test"));
- Assert.assertEquals("max_key1_test should =0", 0L, values.get("max_key1_test"));
- Assert.assertEquals("cnt_key1_test should =0", 0L, values.get("cnt_key1_test"));
- Assert.assertEquals("sum_key1_test should =0", 0L, values.get("sum_key1_test"));
+ assertEquals("avg_key1_test should =0", 0D, values.get("avg_key1_test"));
+ assertEquals("min_key1_test should =0", 0L, values.get("min_key1_test"));
+ assertEquals("max_key1_test should =0", 0L, values.get("max_key1_test"));
+ assertEquals("cnt_key1_test should =0", 0L, values.get("cnt_key1_test"));
+ assertEquals("sum_key1_test should =0", 0L, values.get("sum_key1_test"));
- Assert.assertEquals("avg_key2_test should =0", 0D, values.get("avg_key2_test"));
- Assert.assertEquals("min_key2_test should =0", 0L, values.get("min_key2_test"));
- Assert.assertEquals("max_key2_test should =0", 0L, values.get("max_key2_test"));
- Assert.assertEquals("cnt_key2_test should =0", 0L, values.get("cnt_key2_test"));
- Assert.assertEquals("sum_key2_test should =0", 0L, values.get("sum_key2_test"));
+ assertEquals("avg_key2_test should =0", 0D, values.get("avg_key2_test"));
+ assertEquals("min_key2_test should =0", 0L, values.get("min_key2_test"));
+ assertEquals("max_key2_test should =0", 0L, values.get("max_key2_test"));
+ assertEquals("cnt_key2_test should =0", 0L, values.get("cnt_key2_test"));
+ assertEquals("sum_key2_test should =0", 0L, values.get("sum_key2_test"));
}
@@ -69,17 +70,18 @@ public class AvgMinMaxCounterSetTest extends ZKTestCase {
addDataPoints();
Map<String, Object> values = testCounterSet.values();
- Assert.assertEquals("There should be 10 values in the set", 10, values.size());
- Assert.assertEquals("avg_key1_test should =0.5", 0.5D, values.get("avg_key1_test"));
- Assert.assertEquals("min_key1_test should =0", 0L, values.get("min_key1_test"));
- Assert.assertEquals("max_key1_test should =1", 1L, values.get("max_key1_test"));
- Assert.assertEquals("cnt_key1_test should =2", 2L, values.get("cnt_key1_test"));
- Assert.assertEquals("sum_key1_test should =1", 1L, values.get("sum_key1_test"));
-
- Assert.assertEquals("avg_key2_test should =3.5", 3.5, values.get("avg_key2_test"));
- Assert.assertEquals("min_key2_test should =2", 2L, values.get("min_key2_test"));
- Assert.assertEquals("max_key2_test should =5", 5L, values.get("max_key2_test"));
- Assert.assertEquals("cnt_key2_test should =4", 4L, values.get("cnt_key2_test"));
- Assert.assertEquals("sum_key2_test should =14", 14L, values.get("sum_key2_test"));
+ assertEquals("There should be 10 values in the set", 10, values.size());
+ assertEquals("avg_key1_test should =0.5", 0.5D, values.get("avg_key1_test"));
+ assertEquals("min_key1_test should =0", 0L, values.get("min_key1_test"));
+ assertEquals("max_key1_test should =1", 1L, values.get("max_key1_test"));
+ assertEquals("cnt_key1_test should =2", 2L, values.get("cnt_key1_test"));
+ assertEquals("sum_key1_test should =1", 1L, values.get("sum_key1_test"));
+
+ assertEquals("avg_key2_test should =3.5", 3.5, values.get("avg_key2_test"));
+ assertEquals("min_key2_test should =2", 2L, values.get("min_key2_test"));
+ assertEquals("max_key2_test should =5", 5L, values.get("max_key2_test"));
+ assertEquals("cnt_key2_test should =4", 4L, values.get("cnt_key2_test"));
+ assertEquals("sum_key2_test should =14", 14L, values.get("sum_key2_test"));
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/metric/AvgMinMaxPercentileCounterSetTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/metric/AvgMinMaxPercentileCounterSetTest.java
index 43d289f4c..e120ac51a 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/metric/AvgMinMaxPercentileCounterSetTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/metric/AvgMinMaxPercentileCounterSetTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -15,16 +15,17 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
package org.apache.zookeeper.server.metric;
+import static org.junit.Assert.assertEquals;
+import java.util.Map;
import org.apache.zookeeper.ZKTestCase;
-import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
-import java.util.Map;
-
public class AvgMinMaxPercentileCounterSetTest extends ZKTestCase {
+
private AvgMinMaxPercentileCounterSet testCounterSet;
@Before
@@ -33,11 +34,11 @@ public class AvgMinMaxPercentileCounterSetTest extends ZKTestCase {
}
private void addDataPoints() {
- for (int i=0; i<1000; i++) {
+ for (int i = 0; i < 1000; i++) {
testCounterSet.add("key1", i);
}
- for (int i=1000; i<2000; i++) {
+ for (int i = 1000; i < 2000; i++) {
testCounterSet.add("key2", i);
}
}
@@ -49,25 +50,25 @@ public class AvgMinMaxPercentileCounterSetTest extends ZKTestCase {
Map<String, Object> values = testCounterSet.values();
- Assert.assertEquals("avg_key1_test should =0", 0D, values.get("avg_key1_test"));
- Assert.assertEquals("min_key1_test should =0", 0L, values.get("min_key1_test"));
- Assert.assertEquals("max_key1_test should =0", 0L, values.get("max_key1_test"));
- Assert.assertEquals("cnt_key1_test should =0", 0L, values.get("cnt_key1_test"));
- Assert.assertEquals("sum_key1_test should =0", 0L, values.get("sum_key1_test"));
- Assert.assertEquals("p50_key1_test should have p50=0", 0L, values.get("p50_key1_test"));
- Assert.assertEquals("p95_key1_test should have p95=0", 0L, values.get("p95_key1_test"));
- Assert.assertEquals("p99_key1_test should have p99=0", 0L, values.get("p99_key1_test"));
- Assert.assertEquals("p999_key1_test should have p999=0", 0L, values.get("p999_key1_test"));
-
- Assert.assertEquals("avg_key2_test should =0", 0D, values.get("avg_key2_test"));
- Assert.assertEquals("min_key2_test should =0", 0L, values.get("min_key2_test"));
- Assert.assertEquals("max_key2_test should =0", 0L, values.get("max_key2_test"));
- Assert.assertEquals("cnt_key2_test should =0", 0L, values.get("cnt_key2_test"));
- Assert.assertEquals("sum_key2_test should =0", 0L, values.get("sum_key2_test"));
- Assert.assertEquals("p50_key2_test should have p50=0", 0L, values.get("p50_key2_test"));
- Assert.assertEquals("p95_key2_test should have p95=0", 0L, values.get("p95_key2_test"));
- Assert.assertEquals("p99_key2_test should have p99=0", 0L, values.get("p99_key2_test"));
- Assert.assertEquals("p999_key2_test should have p999=0", 0L, values.get("p999_key2_test"));
+ assertEquals("avg_key1_test should =0", 0D, values.get("avg_key1_test"));
+ assertEquals("min_key1_test should =0", 0L, values.get("min_key1_test"));
+ assertEquals("max_key1_test should =0", 0L, values.get("max_key1_test"));
+ assertEquals("cnt_key1_test should =0", 0L, values.get("cnt_key1_test"));
+ assertEquals("sum_key1_test should =0", 0L, values.get("sum_key1_test"));
+ assertEquals("p50_key1_test should have p50=0", 0L, values.get("p50_key1_test"));
+ assertEquals("p95_key1_test should have p95=0", 0L, values.get("p95_key1_test"));
+ assertEquals("p99_key1_test should have p99=0", 0L, values.get("p99_key1_test"));
+ assertEquals("p999_key1_test should have p999=0", 0L, values.get("p999_key1_test"));
+
+ assertEquals("avg_key2_test should =0", 0D, values.get("avg_key2_test"));
+ assertEquals("min_key2_test should =0", 0L, values.get("min_key2_test"));
+ assertEquals("max_key2_test should =0", 0L, values.get("max_key2_test"));
+ assertEquals("cnt_key2_test should =0", 0L, values.get("cnt_key2_test"));
+ assertEquals("sum_key2_test should =0", 0L, values.get("sum_key2_test"));
+ assertEquals("p50_key2_test should have p50=0", 0L, values.get("p50_key2_test"));
+ assertEquals("p95_key2_test should have p95=0", 0L, values.get("p95_key2_test"));
+ assertEquals("p99_key2_test should have p99=0", 0L, values.get("p99_key2_test"));
+ assertEquals("p999_key2_test should have p999=0", 0L, values.get("p999_key2_test"));
}
@Test
@@ -75,26 +76,27 @@ public class AvgMinMaxPercentileCounterSetTest extends ZKTestCase {
addDataPoints();
Map<String, Object> values = testCounterSet.values();
- Assert.assertEquals("There should be 18 values in the set", 18, values.size());
-
- Assert.assertEquals("avg_key1_test should =499.5", 999D/2, values.get("avg_key1_test"));
- Assert.assertEquals("min_key1_test should =0", 0L, values.get("min_key1_test"));
- Assert.assertEquals("max_key1_test should =999", 999L, values.get("max_key1_test"));
- Assert.assertEquals("cnt_key1_test should =1000", 1000L, values.get("cnt_key1_test"));
- Assert.assertEquals("sum_key1_test should =999*500", 999*500L, values.get("sum_key1_test"));
- Assert.assertEquals("p50_key1_test should have p50=500", 500L, values.get("p50_key1_test"));
- Assert.assertEquals("p95_key1_test should have p95=950", 950L, values.get("p95_key1_test"));
- Assert.assertEquals("p99_key1_test should have p99=990", 990L, values.get("p99_key1_test"));
- Assert.assertEquals("p999_key1_test should have p999=999", 999L, values.get("p999_key1_test"));
-
- Assert.assertEquals("avg_key2_test should =3.5", 1000+999D/2, values.get("avg_key2_test"));
- Assert.assertEquals("min_key2_test should =2", 1000L, values.get("min_key2_test"));
- Assert.assertEquals("max_key2_test should =5", 1999L, values.get("max_key2_test"));
- Assert.assertEquals("cnt_key2_test should =4", 1000L, values.get("cnt_key2_test"));
- Assert.assertEquals("sum_key2_test should =14", 2999*500L, values.get("sum_key2_test"));
- Assert.assertEquals("p50_key2_test should have p50=1500", 1500L, values.get("p50_key2_test"));
- Assert.assertEquals("p95_key2_test should have p95=1950", 1950L, values.get("p95_key2_test"));
- Assert.assertEquals("p99_key2_test should have p99=1990", 1990L, values.get("p99_key2_test"));
- Assert.assertEquals("p999_key2_test should have p999=1999", 1999L, values.get("p999_key2_test"));
+ assertEquals("There should be 18 values in the set", 18, values.size());
+
+ assertEquals("avg_key1_test should =499.5", 999D / 2, values.get("avg_key1_test"));
+ assertEquals("min_key1_test should =0", 0L, values.get("min_key1_test"));
+ assertEquals("max_key1_test should =999", 999L, values.get("max_key1_test"));
+ assertEquals("cnt_key1_test should =1000", 1000L, values.get("cnt_key1_test"));
+ assertEquals("sum_key1_test should =999*500", 999 * 500L, values.get("sum_key1_test"));
+ assertEquals("p50_key1_test should have p50=500", 500L, values.get("p50_key1_test"));
+ assertEquals("p95_key1_test should have p95=950", 950L, values.get("p95_key1_test"));
+ assertEquals("p99_key1_test should have p99=990", 990L, values.get("p99_key1_test"));
+ assertEquals("p999_key1_test should have p999=999", 999L, values.get("p999_key1_test"));
+
+ assertEquals("avg_key2_test should =3.5", 1000 + 999D / 2, values.get("avg_key2_test"));
+ assertEquals("min_key2_test should =2", 1000L, values.get("min_key2_test"));
+ assertEquals("max_key2_test should =5", 1999L, values.get("max_key2_test"));
+ assertEquals("cnt_key2_test should =4", 1000L, values.get("cnt_key2_test"));
+ assertEquals("sum_key2_test should =14", 2999 * 500L, values.get("sum_key2_test"));
+ assertEquals("p50_key2_test should have p50=1500", 1500L, values.get("p50_key2_test"));
+ assertEquals("p95_key2_test should have p95=1950", 1950L, values.get("p95_key2_test"));
+ assertEquals("p99_key2_test should have p99=1990", 1990L, values.get("p99_key2_test"));
+ assertEquals("p999_key2_test should have p999=1999", 1999L, values.get("p999_key2_test"));
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/metric/AvgMinMaxPercentileCounterTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/metric/AvgMinMaxPercentileCounterTest.java
index f8b16e462..ecfdbbcfb 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/metric/AvgMinMaxPercentileCounterTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/metric/AvgMinMaxPercentileCounterTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -15,15 +15,15 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
package org.apache.zookeeper.server.metric;
+import static org.junit.Assert.assertEquals;
+import java.util.Map;
import org.apache.zookeeper.ZKTestCase;
-import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
-import java.util.Map;
-
public class AvgMinMaxPercentileCounterTest extends ZKTestCase {
private AvgMinMaxPercentileCounter testCounter;
@@ -34,12 +34,11 @@ public class AvgMinMaxPercentileCounterTest extends ZKTestCase {
}
private void addDataPoints() {
- for (int i=0; i<1000; i++) {
+ for (int i = 0; i < 1000; i++) {
testCounter.add(i);
}
}
-
@Test
public void testReset() {
addDataPoints();
@@ -47,17 +46,17 @@ public class AvgMinMaxPercentileCounterTest extends ZKTestCase {
Map<String, Object> values = testCounter.values();
- Assert.assertEquals("There should be 9 values in the set", 9, values.size());
+ assertEquals("There should be 9 values in the set", 9, values.size());
- Assert.assertEquals("should avg=0", 0D, values.get("avg_test"));
- Assert.assertEquals("should have min=0", 0L, values.get("min_test"));
- Assert.assertEquals("should have max=0", 0L, values.get("max_test"));
- Assert.assertEquals("should have cnt=0", 0L, values.get("cnt_test"));
- Assert.assertEquals("should have sum=0", 0L, values.get("sum_test"));
- Assert.assertEquals("should have p50=0", 0L, values.get("p50_test"));
- Assert.assertEquals("should have p95=0", 0L, values.get("p95_test"));
- Assert.assertEquals("should have p99=0", 0L, values.get("p99_test"));
- Assert.assertEquals("should have p999=0", 0L, values.get("p999_test"));
+ assertEquals("should avg=0", 0D, values.get("avg_test"));
+ assertEquals("should have min=0", 0L, values.get("min_test"));
+ assertEquals("should have max=0", 0L, values.get("max_test"));
+ assertEquals("should have cnt=0", 0L, values.get("cnt_test"));
+ assertEquals("should have sum=0", 0L, values.get("sum_test"));
+ assertEquals("should have p50=0", 0L, values.get("p50_test"));
+ assertEquals("should have p95=0", 0L, values.get("p95_test"));
+ assertEquals("should have p99=0", 0L, values.get("p99_test"));
+ assertEquals("should have p999=0", 0L, values.get("p999_test"));
}
@Test
@@ -65,16 +64,17 @@ public class AvgMinMaxPercentileCounterTest extends ZKTestCase {
addDataPoints();
Map<String, Object> values = testCounter.values();
- Assert.assertEquals("There should be 9 values in the set", 9, values.size());
+ assertEquals("There should be 9 values in the set", 9, values.size());
- Assert.assertEquals("should avg=499.5", 999D/2, values.get("avg_test"));
- Assert.assertEquals("should have min=0", 0L, values.get("min_test"));
- Assert.assertEquals("should have max=999", 999L, values.get("max_test"));
- Assert.assertEquals("should have cnt=1000", 1000L, values.get("cnt_test"));
- Assert.assertEquals("should have sum=999*500", 999*500L, values.get("sum_test"));
- Assert.assertEquals("should have p50=500", 500L, values.get("p50_test"));
- Assert.assertEquals("should have p95=950", 950L, values.get("p95_test"));
- Assert.assertEquals("should have p99=990", 990L, values.get("p99_test"));
- Assert.assertEquals("should have p999=999", 999L, values.get("p999_test"));
+ assertEquals("should avg=499.5", 999D / 2, values.get("avg_test"));
+ assertEquals("should have min=0", 0L, values.get("min_test"));
+ assertEquals("should have max=999", 999L, values.get("max_test"));
+ assertEquals("should have cnt=1000", 1000L, values.get("cnt_test"));
+ assertEquals("should have sum=999*500", 999 * 500L, values.get("sum_test"));
+ assertEquals("should have p50=500", 500L, values.get("p50_test"));
+ assertEquals("should have p95=950", 950L, values.get("p95_test"));
+ assertEquals("should have p99=990", 990L, values.get("p99_test"));
+ assertEquals("should have p999=999", 999L, values.get("p999_test"));
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/persistence/EmptySnapshotTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/persistence/EmptySnapshotTest.java
index 4aa8a7b46..7eb6f6003 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/persistence/EmptySnapshotTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/persistence/EmptySnapshotTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,13 +18,14 @@
package org.apache.zookeeper.server.persistence;
-import org.junit.Assert;
-
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
-
import org.apache.zookeeper.server.DataTree;
import org.junit.Test;
@@ -40,45 +41,40 @@ public class EmptySnapshotTest {
super(snapDir);
}
- public synchronized void serialize(DataTree dt, Map<Long, Integer> sessions, File snapShot,
- boolean fsync) throws IOException {
+ public synchronized void serialize(DataTree dt, Map<Long, Integer> sessions, File snapShot, boolean fsync) throws IOException {
// Create empty new file.
- Assert.assertTrue(snapShot.createNewFile());
- throw new IOException("Created empty snapshot file from " +
- "MockFileSnap::serialize()");
+ assertTrue(snapShot.createNewFile());
+ throw new IOException("Created empty snapshot file from " + "MockFileSnap::serialize()");
}
}
@Test
public void testNoEmptySnapshot() throws Exception {
- File tmpFile = File.createTempFile("empty-snapshot-test", ".junit",
- new File(System.getProperty("build.test.dir", "build")));
+ File tmpFile = File.createTempFile("empty-snapshot-test", ".junit", new File(System.getProperty("build.test.dir", "build")));
File tmpDataDir = new File(tmpFile + ".dir");
- Assert.assertFalse(tmpDataDir.exists());
- Assert.assertTrue(tmpDataDir.mkdirs());
+ assertFalse(tmpDataDir.exists());
+ assertTrue(tmpDataDir.mkdirs());
FileTxnSnapLog snapLog = new FileTxnSnapLog(tmpDataDir, tmpDataDir);
snapLog.snapLog = new MockFileSnap(snapLog.dataDir);
- Assert.assertEquals(0,
- ((FileSnap) snapLog.snapLog).findNRecentSnapshots(10).size());
+ assertEquals(0, ((FileSnap) snapLog.snapLog).findNRecentSnapshots(10).size());
DataTree tree = new DataTree();
- tree.createNode("/empty-snapshot-test-1", "data".getBytes(), null, -1,
- -1, 1, 1);
+ tree.createNode("/empty-snapshot-test-1", "data".getBytes(), null, -1, -1, 1, 1);
try {
- snapLog.save(tree, new ConcurrentHashMap<Long, Integer>(), false);
- Assert.fail("Should have thrown an IOException");
+ snapLog.save(tree, new ConcurrentHashMap<>(), false);
+ fail("Should have thrown an IOException");
} catch (IOException e) {
+ // no op
}
- Assert.assertEquals(0,
- ((FileSnap) snapLog.snapLog).findNRecentSnapshots(10).size());
+ assertEquals(0, ((FileSnap) snapLog.snapLog).findNRecentSnapshots(10).size());
snapLog.snapLog = new FileSnap(snapLog.dataDir);
- snapLog.save(tree, new ConcurrentHashMap<Long, Integer>(), false);
- Assert.assertEquals(1,
- ((FileSnap) snapLog.snapLog).findNRecentSnapshots(10).size());
- }
+ snapLog.save(tree, new ConcurrentHashMap<>(), false);
+ assertEquals(1, ((FileSnap) snapLog.snapLog).findNRecentSnapshots(10).size());
+ }
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/persistence/FileTxnLogTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/persistence/FileTxnLogTest.java
index e0d34abe2..4c17ac538 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/persistence/FileTxnLogTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/persistence/FileTxnLogTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -15,9 +15,26 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
package org.apache.zookeeper.server.persistence;
-import org.apache.zookeeper.*;
+import static org.hamcrest.core.Is.is;
+import static org.hamcrest.core.IsEqual.equalTo;
+import static org.junit.Assert.assertArrayEquals;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertThat;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.Mockito.mock;
+import java.io.File;
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.Random;
+import org.apache.zookeeper.CreateMode;
+import org.apache.zookeeper.PortAssignment;
+import org.apache.zookeeper.ZKTestCase;
+import org.apache.zookeeper.ZooDefs;
+import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;
import org.apache.zookeeper.proto.CreateRequest;
import org.apache.zookeeper.server.ServerCnxnFactory;
@@ -27,236 +44,239 @@ import org.apache.zookeeper.server.ZooKeeperServer;
import org.apache.zookeeper.test.ClientBase;
import org.apache.zookeeper.txn.CreateTxn;
import org.apache.zookeeper.txn.TxnHeader;
-import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.io.File;
-import java.io.IOException;
-import java.util.Arrays;
-import java.util.HashSet;
-import java.util.Random;
+public class FileTxnLogTest extends ZKTestCase {
-import static org.hamcrest.core.Is.is;
-import static org.hamcrest.core.IsEqual.equalTo;
-import static org.mockito.Mockito.mock;
+ protected static final Logger LOG = LoggerFactory.getLogger(FileTxnLogTest.class);
+
+ private static final int KB = 1024;
+
+ @Test
+ public void testInvalidPreallocSize() {
+ assertEquals(
+ "file should not be padded",
+ 10 * KB,
+ FilePadding.calculateFileSizeWithPadding(7 * KB, 10 * KB, 0));
+ assertEquals(
+ "file should not be padded",
+ 10 * KB,
+ FilePadding.calculateFileSizeWithPadding(7 * KB, 10 * KB, -1));
+ }
-public class FileTxnLogTest extends ZKTestCase {
- protected static final Logger LOG = LoggerFactory.getLogger(FileTxnLogTest.class);
-
- private static final int KB = 1024;
-
- @Test
- public void testInvalidPreallocSize() {
- Assert.assertEquals("file should not be padded",
- 10 * KB, FilePadding.calculateFileSizeWithPadding(7 * KB, 10 * KB, 0));
- Assert.assertEquals("file should not be padded",
- 10 * KB, FilePadding.calculateFileSizeWithPadding(7 * KB, 10 * KB, -1));
- }
-
- @Test
- public void testCalculateFileSizeWithPaddingWhenNotToCurrentSize() {
- Assert.assertEquals("file should not be padded",
- 10 * KB, FilePadding.calculateFileSizeWithPadding(5 * KB, 10 * KB, 10 * KB));
- }
-
- @Test
- public void testCalculateFileSizeWithPaddingWhenCloseToCurrentSize() {
- Assert.assertEquals("file should be padded an additional 10 KB",
- 20 * KB, FilePadding.calculateFileSizeWithPadding(7 * KB, 10 * KB, 10 * KB));
- }
-
- @Test
- public void testFileSizeGreaterThanPosition() {
- Assert.assertEquals("file should be padded to 40 KB",
- 40 * KB, FilePadding.calculateFileSizeWithPadding(31 * KB, 10 * KB, 10 * KB));
- }
-
- @Test
- public void testPreAllocSizeSmallerThanTxnData() throws IOException {
- File logDir = ClientBase.createTmpDir();
- FileTxnLog fileTxnLog = new FileTxnLog(logDir);
-
- // Set a small preAllocSize (.5 MB)
- final int preAllocSize = 500 * KB;
- FilePadding.setPreallocSize(preAllocSize);
-
- // Create dummy txn larger than preAllocSize
- // Since the file padding inserts a 0, we will fill the data with 0xff to ensure we corrupt the data if we put the 0 in the data
- byte[] data = new byte[2 * preAllocSize];
- Arrays.fill(data, (byte) 0xff);
-
- // Append and commit 2 transactions to the log
- // Prior to ZOOKEEPER-2249, attempting to pad in association with the second transaction will corrupt the first
- fileTxnLog.append(new TxnHeader(1, 1, 1, 1, ZooDefs.OpCode.create),
- new CreateTxn("/testPreAllocSizeSmallerThanTxnData1", data, ZooDefs.Ids.OPEN_ACL_UNSAFE, false, 0));
- fileTxnLog.commit();
- fileTxnLog.append(new TxnHeader(1, 1, 2, 2, ZooDefs.OpCode.create),
- new CreateTxn("/testPreAllocSizeSmallerThanTxnData2", new byte[]{}, ZooDefs.Ids.OPEN_ACL_UNSAFE, false, 0));
- fileTxnLog.commit();
- fileTxnLog.close();
-
- // Read the log back from disk, this will throw a java.io.IOException: CRC check failed prior to ZOOKEEPER-2249
- FileTxnLog.FileTxnIterator fileTxnIterator = new FileTxnLog.FileTxnIterator(logDir, 0);
-
- // Verify the data in the first transaction
- CreateTxn createTxn = (CreateTxn) fileTxnIterator.getTxn();
- Assert.assertTrue(Arrays.equals(createTxn.getData(), data));
-
- // Verify the data in the second transaction
- fileTxnIterator.next();
- createTxn = (CreateTxn) fileTxnIterator.getTxn();
- Assert.assertTrue(Arrays.equals(createTxn.getData(), new byte[]{}));
- }
-
- @Test
- public void testSetPreallocSize() {
- long customPreallocSize = 10101;
- FileTxnLog.setPreallocSize(customPreallocSize);
- Assert.assertThat(FilePadding.getPreAllocSize(), is(equalTo(customPreallocSize)));
- }
-
- public void testSyncThresholdExceedCount() throws IOException {
- // Given ...
-
- // Set threshold to -1, as after the first commit it takes 0ms to commit to disk.
- java.lang.System.setProperty(FileTxnLog.ZOOKEEPER_FSYNC_WARNING_THRESHOLD_MS_PROPERTY, "-1");
- ServerStats.Provider providerMock = mock(ServerStats.Provider.class);
- ServerStats serverStats = new ServerStats(providerMock);
-
- File logDir = ClientBase.createTmpDir();
- FileTxnLog fileTxnLog = new FileTxnLog(logDir);
- fileTxnLog.setServerStats(serverStats);
-
- // Verify serverStats is 0 before any commit
- Assert.assertEquals(0L, serverStats.getFsyncThresholdExceedCount());
-
- // When ...
- for (int i = 0; i < 50; i++) {
- fileTxnLog.append(new TxnHeader(1, 1, 1, 1, ZooDefs.OpCode.create),
- new CreateTxn("/testFsyncThresholdCountIncreased", new byte[]{}, ZooDefs.Ids.OPEN_ACL_UNSAFE, false, 0));
- fileTxnLog.commit(); // only 1 commit, otherwise it will be flaky
- // Then ... verify serverStats is updated to the number of commits (as threshold is set to 0)
- Assert.assertEquals((long) i + 1 , serverStats.getFsyncThresholdExceedCount());
+ @Test
+ public void testCalculateFileSizeWithPaddingWhenNotToCurrentSize() {
+ assertEquals(
+ "file should not be padded",
+ 10 * KB,
+ FilePadding.calculateFileSizeWithPadding(5 * KB, 10 * KB, 10 * KB));
}
- }
-
- private static String HOSTPORT = "127.0.0.1:" + PortAssignment.unique();
- private static final int CONNECTION_TIMEOUT = 3000;
-
- // Overhead is about 150 bytes for txn created in this test
- private static final int NODE_SIZE = 1024;
- private final long PREALLOCATE = 512;
- private final long LOG_SIZE_LIMIT = 1024 * 4;
-
- /**
- * Test that log size get update correctly
- */
- @Test
- public void testGetCurrentLogSize() throws Exception {
- FileTxnLog.setTxnLogSizeLimit(-1);
- File tmpDir = ClientBase.createTmpDir();
- FileTxnLog log = new FileTxnLog(tmpDir);
- FileTxnLog.setPreallocSize(PREALLOCATE);
- CreateRequest record = new CreateRequest(null, new byte[NODE_SIZE],
- ZooDefs.Ids.OPEN_ACL_UNSAFE, 0);
- int zxid = 1;
- for (int i = 0; i < 4; i++) {
- log.append(new TxnHeader(0, 0, zxid++, 0, 0), record);
- LOG.debug("Current log size: " + log.getCurrentLogSize());
+
+ @Test
+ public void testCalculateFileSizeWithPaddingWhenCloseToCurrentSize() {
+ assertEquals(
+ "file should be padded an additional 10 KB",
+ 20 * KB,
+ FilePadding.calculateFileSizeWithPadding(7 * KB, 10 * KB, 10 * KB));
}
- log.commit();
- LOG.info("Current log size: " + log.getCurrentLogSize());
- Assert.assertTrue(log.getCurrentLogSize() > (zxid - 1) * NODE_SIZE);
- for (int i = 0; i < 4; i++) {
- log.append(new TxnHeader(0, 0, zxid++, 0, 0), record);
- LOG.debug("Current log size: " + log.getCurrentLogSize());
+
+ @Test
+ public void testFileSizeGreaterThanPosition() {
+ assertEquals(
+ "file should be padded to 40 KB",
+ 40 * KB,
+ FilePadding.calculateFileSizeWithPadding(31 * KB, 10 * KB, 10 * KB));
}
- log.commit();
- LOG.info("Current log size: " + log.getCurrentLogSize());
- Assert.assertTrue(log.getCurrentLogSize() > (zxid - 1) * NODE_SIZE);
- }
-
- /**
- * Test that the server can correctly load the data when there are multiple
- * txnlogs per snapshot
- */
- @Test
- public void testLogSizeLimit() throws Exception {
- File tmpDir = ClientBase.createTmpDir();
- ClientBase.setupTestEnv();
-
- // Need to override preallocate set by setupTestEnv()
- // We don't need to unset these values since each unit test run in
- // a separate JVM instance
- FileTxnLog.setPreallocSize(PREALLOCATE);
- FileTxnLog.setTxnLogSizeLimit(LOG_SIZE_LIMIT);
-
- ZooKeeperServer zks = new ZooKeeperServer(tmpDir, tmpDir, 3000);
- final int PORT = Integer.parseInt(HOSTPORT.split(":")[1]);
- ServerCnxnFactory f = ServerCnxnFactory.createFactory(PORT, -1);
- f.startup(zks);
- Assert.assertTrue("waiting for server being up ",
- ClientBase.waitForServerUp(HOSTPORT, CONNECTION_TIMEOUT));
- ZooKeeper zk = new ZooKeeper(HOSTPORT, CONNECTION_TIMEOUT, event -> { });
-
- // Generate transactions
- HashSet<Long> zxids = new HashSet<Long>();
- byte[] bytes = new byte[NODE_SIZE];
- Random random = new Random();
- random.nextBytes(bytes);
-
- // We will create enough txn to generate 3 logs
- long txnCount = LOG_SIZE_LIMIT / NODE_SIZE / 2 * 5;
-
- LOG.info("Creating " + txnCount + " txns");
-
- try {
- for (long i = 0; i < txnCount; i++) {
- Stat stat = new Stat();
- zk.create("/node-" + i, bytes, ZooDefs.Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
- zk.getData("/node-" + i, null, stat);
- zxids.add(stat.getCzxid());
- }
-
- } finally {
- zk.close();
+
+ @Test
+ public void testPreAllocSizeSmallerThanTxnData() throws IOException {
+ File logDir = ClientBase.createTmpDir();
+ FileTxnLog fileTxnLog = new FileTxnLog(logDir);
+
+ // Set a small preAllocSize (.5 MB)
+ final int preAllocSize = 500 * KB;
+ FilePadding.setPreallocSize(preAllocSize);
+
+ // Create dummy txn larger than preAllocSize
+ // Since the file padding inserts a 0, we will fill the data with 0xff to ensure we corrupt the data if we put the 0 in the data
+ byte[] data = new byte[2 * preAllocSize];
+ Arrays.fill(data, (byte) 0xff);
+
+ // Append and commit 2 transactions to the log
+ // Prior to ZOOKEEPER-2249, attempting to pad in association with the second transaction will corrupt the first
+ fileTxnLog.append(
+ new TxnHeader(1, 1, 1, 1, ZooDefs.OpCode.create),
+ new CreateTxn("/testPreAllocSizeSmallerThanTxnData1", data, ZooDefs.Ids.OPEN_ACL_UNSAFE, false, 0));
+ fileTxnLog.commit();
+ fileTxnLog.append(
+ new TxnHeader(1, 1, 2, 2, ZooDefs.OpCode.create),
+ new CreateTxn("/testPreAllocSizeSmallerThanTxnData2", new byte[]{}, ZooDefs.Ids.OPEN_ACL_UNSAFE, false, 0));
+ fileTxnLog.commit();
+ fileTxnLog.close();
+
+ // Read the log back from disk, this will throw a java.io.IOException: CRC check failed prior to ZOOKEEPER-2249
+ FileTxnLog.FileTxnIterator fileTxnIterator = new FileTxnLog.FileTxnIterator(logDir, 0);
+
+ // Verify the data in the first transaction
+ CreateTxn createTxn = (CreateTxn) fileTxnIterator.getTxn();
+ assertTrue(Arrays.equals(createTxn.getData(), data));
+
+ // Verify the data in the second transaction
+ fileTxnIterator.next();
+ createTxn = (CreateTxn) fileTxnIterator.getTxn();
+ assertTrue(Arrays.equals(createTxn.getData(), new byte[]{}));
}
- // shutdown
- f.shutdown();
- Assert.assertTrue("waiting for server to shutdown",
+ @Test
+ public void testSetPreallocSize() {
+ long customPreallocSize = 10101;
+ FileTxnLog.setPreallocSize(customPreallocSize);
+ assertThat(FilePadding.getPreAllocSize(), is(equalTo(customPreallocSize)));
+ }
+
+ public void testSyncThresholdExceedCount() throws IOException {
+ // Given ...
+
+ // Set threshold to -1, as after the first commit it takes 0ms to commit to disk.
+ java.lang.System.setProperty(FileTxnLog.ZOOKEEPER_FSYNC_WARNING_THRESHOLD_MS_PROPERTY, "-1");
+ ServerStats.Provider providerMock = mock(ServerStats.Provider.class);
+ ServerStats serverStats = new ServerStats(providerMock);
+
+ File logDir = ClientBase.createTmpDir();
+ FileTxnLog fileTxnLog = new FileTxnLog(logDir);
+ fileTxnLog.setServerStats(serverStats);
+
+ // Verify serverStats is 0 before any commit
+ assertEquals(0L, serverStats.getFsyncThresholdExceedCount());
+
+ // When ...
+ for (int i = 0; i < 50; i++) {
+ fileTxnLog.append(
+ new TxnHeader(1, 1, 1, 1, ZooDefs.OpCode.create),
+ new CreateTxn("/testFsyncThresholdCountIncreased", new byte[]{}, ZooDefs.Ids.OPEN_ACL_UNSAFE, false, 0));
+ fileTxnLog.commit(); // only 1 commit, otherwise it will be flaky
+ // Then ... verify serverStats is updated to the number of commits (as threshold is set to 0)
+ assertEquals((long) i + 1, serverStats.getFsyncThresholdExceedCount());
+ }
+ }
+
+ private static String HOSTPORT = "127.0.0.1:" + PortAssignment.unique();
+ private static final int CONNECTION_TIMEOUT = 3000;
+
+ // Overhead is about 150 bytes for txn created in this test
+ private static final int NODE_SIZE = 1024;
+ private final long PREALLOCATE = 512;
+ private final long LOG_SIZE_LIMIT = 1024 * 4;
+
+ /**
+ * Test that log size get update correctly
+ */
+ @Test
+ public void testGetCurrentLogSize() throws Exception {
+ FileTxnLog.setTxnLogSizeLimit(-1);
+ File tmpDir = ClientBase.createTmpDir();
+ FileTxnLog log = new FileTxnLog(tmpDir);
+ FileTxnLog.setPreallocSize(PREALLOCATE);
+ CreateRequest record = new CreateRequest(null, new byte[NODE_SIZE], ZooDefs.Ids.OPEN_ACL_UNSAFE, 0);
+ int zxid = 1;
+ for (int i = 0; i < 4; i++) {
+ log.append(new TxnHeader(0, 0, zxid++, 0, 0), record);
+ LOG.debug("Current log size: " + log.getCurrentLogSize());
+ }
+ log.commit();
+ LOG.info("Current log size: " + log.getCurrentLogSize());
+ assertTrue(log.getCurrentLogSize() > (zxid - 1) * NODE_SIZE);
+ for (int i = 0; i < 4; i++) {
+ log.append(new TxnHeader(0, 0, zxid++, 0, 0), record);
+ LOG.debug("Current log size: " + log.getCurrentLogSize());
+ }
+ log.commit();
+ LOG.info("Current log size: " + log.getCurrentLogSize());
+ assertTrue(log.getCurrentLogSize() > (zxid - 1) * NODE_SIZE);
+ }
+
+ /**
+ * Test that the server can correctly load the data when there are multiple
+ * txnlogs per snapshot
+ */
+ @Test
+ public void testLogSizeLimit() throws Exception {
+ File tmpDir = ClientBase.createTmpDir();
+ ClientBase.setupTestEnv();
+
+ // Need to override preallocate set by setupTestEnv()
+ // We don't need to unset these values since each unit test run in
+ // a separate JVM instance
+ FileTxnLog.setPreallocSize(PREALLOCATE);
+ FileTxnLog.setTxnLogSizeLimit(LOG_SIZE_LIMIT);
+
+ ZooKeeperServer zks = new ZooKeeperServer(tmpDir, tmpDir, 3000);
+ final int PORT = Integer.parseInt(HOSTPORT.split(":")[1]);
+ ServerCnxnFactory f = ServerCnxnFactory.createFactory(PORT, -1);
+ f.startup(zks);
+ assertTrue("waiting for server being up ", ClientBase.waitForServerUp(HOSTPORT, CONNECTION_TIMEOUT));
+ ZooKeeper zk = new ZooKeeper(HOSTPORT, CONNECTION_TIMEOUT, event -> {
+ });
+
+ // Generate transactions
+ HashSet<Long> zxids = new HashSet<Long>();
+ byte[] bytes = new byte[NODE_SIZE];
+ Random random = new Random();
+ random.nextBytes(bytes);
+
+ // We will create enough txn to generate 3 logs
+ long txnCount = LOG_SIZE_LIMIT / NODE_SIZE / 2 * 5;
+
+ LOG.info("Creating " + txnCount + " txns");
+
+ try {
+ for (long i = 0; i < txnCount; i++) {
+ Stat stat = new Stat();
+ zk.create("/node-" + i, bytes, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
+ zk.getData("/node-" + i, null, stat);
+ zxids.add(stat.getCzxid());
+ }
+
+ } finally {
+ zk.close();
+ }
+
+ // shutdown
+ f.shutdown();
+ assertTrue(
+ "waiting for server to shutdown",
ClientBase.waitForServerDown(HOSTPORT, CONNECTION_TIMEOUT));
- File logDir = new File(tmpDir, FileTxnSnapLog.version + FileTxnSnapLog.VERSION);
- File[] txnLogs = FileTxnLog.getLogFiles(logDir.listFiles(), 0);
+ File logDir = new File(tmpDir, FileTxnSnapLog.version + FileTxnSnapLog.VERSION);
+ File[] txnLogs = FileTxnLog.getLogFiles(logDir.listFiles(), 0);
- Assert.assertEquals("Unexpected number of logs", 3, txnLogs.length);
+ assertEquals("Unexpected number of logs", 3, txnLogs.length);
- // Log size should not exceed limit by more than one node size;
- long threshold = LOG_SIZE_LIMIT + NODE_SIZE;
- LOG.info(txnLogs[0].getAbsolutePath());
- Assert.assertTrue(
+ // Log size should not exceed limit by more than one node size;
+ long threshold = LOG_SIZE_LIMIT + NODE_SIZE;
+ LOG.info(txnLogs[0].getAbsolutePath());
+ assertTrue(
"Exceed log size limit: " + txnLogs[0].length(),
threshold > txnLogs[0].length());
- LOG.info(txnLogs[1].getAbsolutePath());
- Assert.assertTrue(
+ LOG.info(txnLogs[1].getAbsolutePath());
+ assertTrue(
"Exceed log size limit " + txnLogs[1].length(),
threshold > txnLogs[1].length());
- // Start database only
- zks = new ZooKeeperServer(tmpDir, tmpDir, 3000);
- zks.startdata();
+ // Start database only
+ zks = new ZooKeeperServer(tmpDir, tmpDir, 3000);
+ zks.startdata();
- ZKDatabase db = zks.getZKDatabase();
+ ZKDatabase db = zks.getZKDatabase();
- for (long i = 0; i < txnCount; i++) {
- Stat stat = new Stat();
- byte[] data = db.getData("/node-" + i, stat, null);
- Assert.assertArrayEquals("Missmatch data", bytes, data);
- Assert.assertTrue("Unknown zxid ", zxids.contains(stat.getMzxid()));
+ for (long i = 0; i < txnCount; i++) {
+ Stat stat = new Stat();
+ byte[] data = db.getData("/node-" + i, stat, null);
+ assertArrayEquals("Missmatch data", bytes, data);
+ assertTrue("Unknown zxid ", zxids.contains(stat.getMzxid()));
+ }
}
- }
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/persistence/FileTxnSnapLogMetricsTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/persistence/FileTxnSnapLogMetricsTest.java
index 4b4ef7a09..fe075fb49 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/persistence/FileTxnSnapLogMetricsTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/persistence/FileTxnSnapLogMetricsTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,39 +18,41 @@
package org.apache.zookeeper.server.persistence;
-import org.apache.zookeeper.ZooKeeper;
-import org.apache.zookeeper.ZooDefs;
-import org.apache.zookeeper.ZKTestCase;
-import org.apache.zookeeper.Watcher;
-import org.apache.zookeeper.WatchedEvent;
+import static org.hamcrest.number.OrderingComparison.greaterThan;
+import static org.hamcrest.number.OrderingComparison.greaterThanOrEqualTo;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertThat;
+import java.util.Map;
+import java.util.concurrent.CountDownLatch;
import org.apache.zookeeper.CreateMode;
+import org.apache.zookeeper.WatchedEvent;
+import org.apache.zookeeper.Watcher;
+import org.apache.zookeeper.ZKTestCase;
+import org.apache.zookeeper.ZooDefs;
+import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.metrics.MetricsUtils;
import org.apache.zookeeper.server.ServerMetrics;
import org.apache.zookeeper.server.SyncRequestProcessor;
import org.apache.zookeeper.test.ClientBase;
import org.apache.zookeeper.test.QuorumUtil;
-import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.util.Map;
-import java.util.concurrent.CountDownLatch;
-
-import static org.hamcrest.number.OrderingComparison.greaterThan;
-import static org.hamcrest.number.OrderingComparison.greaterThanOrEqualTo;
-
public class FileTxnSnapLogMetricsTest extends ZKTestCase {
+
private static final Logger LOG = LoggerFactory.getLogger(FileTxnSnapLogMetricsTest.class);
CountDownLatch allCreatedLatch;
private class MockWatcher implements Watcher {
+
@Override
public void process(WatchedEvent e) {
LOG.info("all nodes created");
allCreatedLatch.countDown();
}
+
}
@Test
@@ -65,7 +67,7 @@ public class FileTxnSnapLogMetricsTest extends ZKTestCase {
byte[] data = new byte[500];
// make sure a snapshot is taken and some txns are not in a snapshot
ZooKeeper zk = ClientBase.createZKClient(util.getConnString());
- for (int i=0; i<150; i++){
+ for (int i = 0; i < 150; i++) {
zk.create("/path" + i, data, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
}
@@ -81,13 +83,14 @@ public class FileTxnSnapLogMetricsTest extends ZKTestCase {
Map<String, Object> values = MetricsUtils.currentServerMetrics();
LOG.info("txn loaded during start up {}", values.get("max_startup_txns_loaded"));
- Assert.assertEquals(1L, values.get("cnt_startup_txns_loaded"));
- Assert.assertThat((long)values.get("max_startup_txns_loaded"), greaterThan(0L));
- Assert.assertEquals(1L, values.get("cnt_startup_txns_load_time"));
- Assert.assertThat((long)values.get("max_startup_txns_load_time"), greaterThanOrEqualTo(0L));
- Assert.assertEquals(1L, values.get("cnt_startup_snap_load_time"));
- Assert.assertThat((long)values.get("max_startup_snap_load_time"), greaterThan(0L));
+ assertEquals(1L, values.get("cnt_startup_txns_loaded"));
+ assertThat((long) values.get("max_startup_txns_loaded"), greaterThan(0L));
+ assertEquals(1L, values.get("cnt_startup_txns_load_time"));
+ assertThat((long) values.get("max_startup_txns_load_time"), greaterThanOrEqualTo(0L));
+ assertEquals(1L, values.get("cnt_startup_snap_load_time"));
+ assertThat((long) values.get("max_startup_snap_load_time"), greaterThan(0L));
util.shutdownAll();
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/persistence/FileTxnSnapLogTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/persistence/FileTxnSnapLogTest.java
index 63e3f7f04..1412a932b 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/persistence/FileTxnSnapLogTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/persistence/FileTxnSnapLogTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,6 +18,18 @@
package org.apache.zookeeper.server.persistence;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
import org.apache.jute.BinaryInputArchive;
import org.apache.jute.BinaryOutputArchive;
import org.apache.jute.InputArchive;
@@ -34,16 +46,8 @@ import org.apache.zookeeper.txn.SetDataTxn;
import org.apache.zookeeper.txn.TxnHeader;
import org.junit.After;
import org.junit.Before;
-import org.junit.Assert;
import org.junit.Test;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.util.Map;
-import java.util.concurrent.ConcurrentHashMap;
-
public class FileTxnSnapLogTest {
private File tmpDir;
@@ -65,7 +69,7 @@ public class FileTxnSnapLogTest {
@After
public void tearDown() throws Exception {
- if(tmpDir != null){
+ if (tmpDir != null) {
TestUtils.deleteFileRecursively(tmpDir);
}
this.tmpDir = null;
@@ -96,29 +100,32 @@ public class FileTxnSnapLogTest {
snapVersionDir = createVersionDir(snapDir);
// transaction log files in log dir
- createLogFile(logVersionDir,1);
- createLogFile(logVersionDir,2);
+ createLogFile(logVersionDir, 1);
+ createLogFile(logVersionDir, 2);
// snapshot files in snap dir
- createSnapshotFile(snapVersionDir,1);
- createSnapshotFile(snapVersionDir,2);
+ createSnapshotFile(snapVersionDir, 1);
+ createSnapshotFile(snapVersionDir, 2);
}
private void singleDirSetupWithCorrectFiles() throws IOException {
logVersionDir = createVersionDir(logDir);
// transaction log and snapshot files in the same dir
- createLogFile(logVersionDir,1);
- createLogFile(logVersionDir,2);
- createSnapshotFile(logVersionDir,1);
- createSnapshotFile(logVersionDir,2);
+ createLogFile(logVersionDir, 1);
+ createLogFile(logVersionDir, 2);
+ createSnapshotFile(logVersionDir, 1);
+ createSnapshotFile(logVersionDir, 2);
}
private FileTxnSnapLog createFileTxnSnapLogWithNoAutoCreateDataDir(File logDir, File snapDir) throws IOException {
return createFileTxnSnapLogWithAutoCreateDataDir(logDir, snapDir, "false");
}
- private FileTxnSnapLog createFileTxnSnapLogWithAutoCreateDataDir(File logDir, File snapDir, String autoCreateValue) throws IOException {
+ private FileTxnSnapLog createFileTxnSnapLogWithAutoCreateDataDir(
+ File logDir,
+ File snapDir,
+ String autoCreateValue) throws IOException {
String priorAutocreateDirValue = System.getProperty(FileTxnSnapLog.ZOOKEEPER_DATADIR_AUTOCREATE);
System.setProperty(FileTxnSnapLog.ZOOKEEPER_DATADIR_AUTOCREATE, autoCreateValue);
FileTxnSnapLog fileTxnSnapLog;
@@ -134,7 +141,10 @@ public class FileTxnSnapLogTest {
return fileTxnSnapLog;
}
- private FileTxnSnapLog createFileTxnSnapLogWithAutoCreateDB(File logDir, File snapDir, String autoCreateValue) throws IOException {
+ private FileTxnSnapLog createFileTxnSnapLogWithAutoCreateDB(
+ File logDir,
+ File snapDir,
+ String autoCreateValue) throws IOException {
String priorAutocreateDBValue = System.getProperty(FileTxnSnapLog.ZOOKEEPER_DB_AUTOCREATE);
System.setProperty(FileTxnSnapLog.ZOOKEEPER_DB_AUTOCREATE, autoCreateValue);
FileTxnSnapLog fileTxnSnapLog;
@@ -156,15 +166,15 @@ public class FileTxnSnapLogTest {
*/
@Test
public void testWithAutoCreateDataDir() throws IOException {
- Assert.assertFalse("log directory already exists", logDir.exists());
- Assert.assertFalse("snapshot directory already exists", snapDir.exists());
+ assertFalse("log directory already exists", logDir.exists());
+ assertFalse("snapshot directory already exists", snapDir.exists());
FileTxnSnapLog fileTxnSnapLog = createFileTxnSnapLogWithAutoCreateDataDir(logDir, snapDir, "true");
- Assert.assertTrue(logDir.exists());
- Assert.assertTrue(snapDir.exists());
- Assert.assertTrue(fileTxnSnapLog.getDataDir().exists());
- Assert.assertTrue(fileTxnSnapLog.getSnapDir().exists());
+ assertTrue(logDir.exists());
+ assertTrue(snapDir.exists());
+ assertTrue(fileTxnSnapLog.getDataDir().exists());
+ assertTrue(fileTxnSnapLog.getSnapDir().exists());
}
/**
@@ -173,22 +183,26 @@ public class FileTxnSnapLogTest {
*/
@Test(expected = FileTxnSnapLog.DatadirException.class)
public void testWithoutAutoCreateDataDir() throws Exception {
- Assert.assertFalse("log directory already exists", logDir.exists());
- Assert.assertFalse("snapshot directory already exists", snapDir.exists());
+ assertFalse("log directory already exists", logDir.exists());
+ assertFalse("snapshot directory already exists", snapDir.exists());
try {
createFileTxnSnapLogWithAutoCreateDataDir(logDir, snapDir, "false");
} catch (FileTxnSnapLog.DatadirException e) {
- Assert.assertFalse(logDir.exists());
- Assert.assertFalse(snapDir.exists());
+ assertFalse(logDir.exists());
+ assertFalse(snapDir.exists());
// rethrow exception
throw e;
}
- Assert.fail("Expected exception from FileTxnSnapLog");
+ fail("Expected exception from FileTxnSnapLog");
}
- private void attemptAutoCreateDB(File dataDir, File snapDir, Map<Long, Integer> sessions,
- String autoCreateValue, long expectedValue) throws IOException {
+ private void attemptAutoCreateDB(
+ File dataDir,
+ File snapDir,
+ Map<Long, Integer> sessions,
+ String autoCreateValue,
+ long expectedValue) throws IOException {
sessions.clear();
FileTxnSnapLog fileTxnSnapLog = createFileTxnSnapLogWithAutoCreateDB(dataDir, snapDir, autoCreateValue);
@@ -199,23 +213,23 @@ public class FileTxnSnapLogTest {
// empty by default
}
});
- Assert.assertEquals("unexpected zxid", expectedValue, zxid);
+ assertEquals("unexpected zxid", expectedValue, zxid);
}
@Test
public void testAutoCreateDB() throws IOException {
- Assert.assertTrue("cannot create log directory", logDir.mkdir());
- Assert.assertTrue("cannot create snapshot directory", snapDir.mkdir());
+ assertTrue("cannot create log directory", logDir.mkdir());
+ assertTrue("cannot create snapshot directory", snapDir.mkdir());
File initFile = new File(logDir, "initialize");
- Assert.assertFalse("initialize file already exists", initFile.exists());
+ assertFalse("initialize file already exists", initFile.exists());
Map<Long, Integer> sessions = new ConcurrentHashMap<>();
- attemptAutoCreateDB(logDir, snapDir, sessions,"false", -1L);
- attemptAutoCreateDB(logDir, snapDir, sessions,"true", 0L);
+ attemptAutoCreateDB(logDir, snapDir, sessions, "false", -1L);
+ attemptAutoCreateDB(logDir, snapDir, sessions, "true", 0L);
- Assert.assertTrue("cannot create initialize file", initFile.createNewFile());
- attemptAutoCreateDB(logDir, snapDir, sessions,"false", 0L);
+ assertTrue("cannot create initialize file", initFile.createNewFile());
+ attemptAutoCreateDB(logDir, snapDir, sessions, "false", 0L);
}
@Test
@@ -230,7 +244,7 @@ public class FileTxnSnapLogTest {
fileTxnSnapLog.append(req);
fileTxnSnapLog.commit();
long syncElapsedTime = fileTxnSnapLog.getTxnLogElapsedSyncTime();
- Assert.assertNotEquals("Did not update syncElapsedTime!", -1L, syncElapsedTime);
+ assertNotEquals("Did not update syncElapsedTime!", -1L, syncElapsedTime);
} finally {
fileTxnSnapLog.close();
}
@@ -243,7 +257,7 @@ public class FileTxnSnapLogTest {
try {
createFileTxnSnapLogWithNoAutoCreateDataDir(logDir, snapDir);
} catch (FileTxnSnapLog.LogDirContentCheckException | FileTxnSnapLog.SnapDirContentCheckException e) {
- Assert.fail("Should not throw ContentCheckException.");
+ fail("Should not throw ContentCheckException.");
}
}
@@ -254,7 +268,7 @@ public class FileTxnSnapLogTest {
try {
createFileTxnSnapLogWithNoAutoCreateDataDir(logDir, logDir);
} catch (FileTxnSnapLog.LogDirContentCheckException | FileTxnSnapLog.SnapDirContentCheckException e) {
- Assert.fail("Should not throw ContentCheckException.");
+ fail("Should not throw ContentCheckException.");
}
}
@@ -263,8 +277,8 @@ public class FileTxnSnapLogTest {
twoDirSetupWithCorrectFiles();
// add snapshot files to the log version dir
- createSnapshotFile(logVersionDir,3);
- createSnapshotFile(logVersionDir,4);
+ createSnapshotFile(logVersionDir, 3);
+ createSnapshotFile(logVersionDir, 4);
createFileTxnSnapLogWithNoAutoCreateDataDir(logDir, snapDir);
}
@@ -274,8 +288,8 @@ public class FileTxnSnapLogTest {
twoDirSetupWithCorrectFiles();
// add transaction log files to the snap version dir
- createLogFile(snapVersionDir,3);
- createLogFile(snapVersionDir,4);
+ createLogFile(snapVersionDir, 3);
+ createLogFile(snapVersionDir, 4);
createFileTxnSnapLogWithNoAutoCreateDataDir(logDir, snapDir);
}
@@ -333,9 +347,10 @@ public class FileTxnSnapLogTest {
followerDataTree.processTxn(hdr1, txn1);
DataNode a1 = leaderDataTree.getNode("/a1");
- Assert.assertNotNull(a1);
- Assert.assertEquals(ZooDefs.Ids.CREATOR_ALL_ACL, leaderDataTree.getACL(a1));
+ assertNotNull(a1);
+ assertEquals(ZooDefs.Ids.CREATOR_ALL_ACL, leaderDataTree.getACL(a1));
- Assert.assertEquals(ZooDefs.Ids.CREATOR_ALL_ACL, followerDataTree.getACL(a1));
+ assertEquals(ZooDefs.Ids.CREATOR_ALL_ACL, followerDataTree.getACL(a1));
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/persistence/SnapStreamTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/persistence/SnapStreamTest.java
index 3b8cb2a7f..d884d1e06 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/persistence/SnapStreamTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/persistence/SnapStreamTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,12 +18,15 @@
package org.apache.zookeeper.server.persistence;
+import static org.apache.zookeeper.test.ClientBase.createTmpDir;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.zip.CheckedInputStream;
import java.util.zip.CheckedOutputStream;
-
import org.apache.jute.BinaryInputArchive;
import org.apache.jute.BinaryOutputArchive;
import org.apache.jute.InputArchive;
@@ -31,9 +34,6 @@ import org.apache.jute.OutputArchive;
import org.apache.zookeeper.server.persistence.SnapStream.StreamMode;
import org.junit.After;
import org.junit.Test;
-import org.junit.Assert;
-
-import static org.apache.zookeeper.test.ClientBase.createTmpDir;
public class SnapStreamTest {
@@ -45,34 +45,22 @@ public class SnapStreamTest {
@Test
public void testStreamMode() {
- Assert.assertEquals(StreamMode.CHECKED.getName(), "");
- Assert.assertEquals(StreamMode.CHECKED.getFileExtension(), "");
- Assert.assertEquals(StreamMode.CHECKED, StreamMode.fromString("name"));
- Assert.assertEquals(StreamMode.GZIP.getName(), "gz");
- Assert.assertEquals(StreamMode.GZIP.getFileExtension(), ".gz");
- Assert.assertEquals(StreamMode.GZIP, StreamMode.fromString("gz"));
- Assert.assertEquals(StreamMode.SNAPPY.getName(), "snappy");
- Assert.assertEquals(StreamMode.SNAPPY.getFileExtension(), ".snappy");
- Assert.assertEquals(StreamMode.SNAPPY, StreamMode.fromString("snappy"));
+ assertEquals(StreamMode.CHECKED.getName(), "");
+ assertEquals(StreamMode.CHECKED.getFileExtension(), "");
+ assertEquals(StreamMode.CHECKED, StreamMode.fromString("name"));
+ assertEquals(StreamMode.GZIP.getName(), "gz");
+ assertEquals(StreamMode.GZIP.getFileExtension(), ".gz");
+ assertEquals(StreamMode.GZIP, StreamMode.fromString("gz"));
+ assertEquals(StreamMode.SNAPPY.getName(), "snappy");
+ assertEquals(StreamMode.SNAPPY.getFileExtension(), ".snappy");
+ assertEquals(StreamMode.SNAPPY, StreamMode.fromString("snappy"));
}
@Test
public void testGetStreamMode() {
- Assert.assertEquals(
- "expected to return un-compressed stream",
- StreamMode.CHECKED,
- SnapStream.getStreamMode("snapshot.180000e3a2")
- );
- Assert.assertEquals(
- "expected to return snappy stream",
- StreamMode.SNAPPY,
- SnapStream.getStreamMode("snapshot.180000e3a2.snappy")
- );
- Assert.assertEquals(
- "expected to return gzip stream",
- StreamMode.GZIP,
- SnapStream.getStreamMode("snapshot.180000e3a2.gz")
- );
+ assertEquals("expected to return un-compressed stream", StreamMode.CHECKED, SnapStream.getStreamMode("snapshot.180000e3a2"));
+ assertEquals("expected to return snappy stream", StreamMode.SNAPPY, SnapStream.getStreamMode("snapshot.180000e3a2.snappy"));
+ assertEquals("expected to return gzip stream", StreamMode.GZIP, SnapStream.getStreamMode("snapshot.180000e3a2.gz"));
}
@Test
@@ -104,15 +92,14 @@ public class SnapStreamTest {
os.flush();
os.close();
- Assert.assertTrue(SnapStream.isValidSnapshot(file));
+ assertTrue(SnapStream.isValidSnapshot(file));
// deserialize with gzip stream
CheckedInputStream is = SnapStream.getInputStream(file);
InputArchive ia = BinaryInputArchive.getArchive(is);
FileHeader restoredHeader = new FileHeader();
restoredHeader.deserialize(ia, "fileheader");
- Assert.assertEquals(
- "magic not the same", restoredHeader, header);
+ assertEquals("magic not the same", restoredHeader, header);
SnapStream.checkSealIntegrity(is, ia);
}
@@ -127,15 +114,16 @@ public class SnapStreamTest {
os.write(1);
os.flush();
os.close();
- Assert.assertFalse(SnapStream.isValidSnapshot(file));
+ assertFalse(SnapStream.isValidSnapshot(file));
}
@Test
public void testInvalidSnapshot() throws IOException {
- Assert.assertFalse(SnapStream.isValidSnapshot(null));
+ assertFalse(SnapStream.isValidSnapshot(null));
checkInvalidSnapshot("snapshot.180000e3a2");
checkInvalidSnapshot("snapshot.180000e3a2.gz");
checkInvalidSnapshot("snapshot.180000e3a2.snappy");
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/persistence/TxnLogToolkitTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/persistence/TxnLogToolkitTest.java
index 60b3ea6ec..20d6fe8a9 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/persistence/TxnLogToolkitTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/persistence/TxnLogToolkitTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,12 +18,10 @@
package org.apache.zookeeper.server.persistence;
-import org.apache.commons.io.FileUtils;
-import org.apache.zookeeper.test.ClientBase;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-
+import static org.hamcrest.CoreMatchers.containsString;
+import static org.hamcrest.core.IsNot.not;
+import static org.junit.Assert.assertThat;
+import static org.junit.Assert.assertTrue;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
@@ -32,16 +30,15 @@ import java.io.PrintStream;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
-
-import static org.hamcrest.CoreMatchers.containsString;
-import static org.hamcrest.core.IsNot.not;
-import static org.junit.Assert.assertThat;
-import static org.junit.Assert.assertTrue;
-
+import org.apache.commons.io.FileUtils;
+import org.apache.zookeeper.test.ClientBase;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
public class TxnLogToolkitTest {
- private static final File testData = new File(
- System.getProperty("test.data.dir", "src/test/resources/data"));
+
+ private static final File testData = new File(System.getProperty("test.data.dir", "src/test/resources/data"));
private final ByteArrayOutputStream outContent = new ByteArrayOutputStream();
private final ByteArrayOutputStream errContent = new ByteArrayOutputStream();
@@ -152,4 +149,5 @@ public class TxnLogToolkitTest {
output = outContent.toString();
assertThat(output, not(containsString("CRC ERROR")));
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/BufferStatsTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/BufferStatsTest.java
index 8435e856a..9fb9cfb2b 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/BufferStatsTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/BufferStatsTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,11 +18,11 @@
package org.apache.zookeeper.server.quorum;
-import org.junit.Test;
-
import static org.junit.Assert.assertEquals;
+import org.junit.Test;
public class BufferStatsTest {
+
@Test
public void testSetProposalSizeSetMinMax() {
BufferStats stats = new BufferStats();
@@ -55,4 +55,5 @@ public class BufferStatsTest {
assertEquals(-1, stats.getMinBufferSize());
assertEquals(-1, stats.getMaxBufferSize());
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/CnxManagerTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/CnxManagerTest.java
index 276f35f47..013ca53f8 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/CnxManagerTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/CnxManagerTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,6 +18,11 @@
package org.apache.zookeeper.server.quorum;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
@@ -25,6 +30,7 @@ import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.net.InetSocketAddress;
+import java.net.Socket;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
@@ -35,66 +41,55 @@ import java.util.Map;
import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
-import java.net.Socket;
import java.util.concurrent.atomic.AtomicBoolean;
+import javax.net.ssl.HandshakeCompletedListener;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;
-import javax.net.ssl.HandshakeCompletedListener;
-
-import org.apache.zookeeper.common.QuorumX509Util;
-import org.apache.zookeeper.common.Time;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
import org.apache.zookeeper.PortAssignment;
import org.apache.zookeeper.ZKTestCase;
-import org.apache.zookeeper.server.quorum.QuorumCnxManager;
-import org.apache.zookeeper.server.quorum.QuorumCnxManager.Message;
+import org.apache.zookeeper.common.QuorumX509Util;
+import org.apache.zookeeper.common.Time;
import org.apache.zookeeper.server.quorum.QuorumCnxManager.InitialMessage;
-import org.apache.zookeeper.server.quorum.QuorumPeer;
+import org.apache.zookeeper.server.quorum.QuorumCnxManager.Message;
import org.apache.zookeeper.server.quorum.QuorumPeer.LearnerType;
import org.apache.zookeeper.server.quorum.QuorumPeer.QuorumServer;
import org.apache.zookeeper.server.quorum.QuorumPeer.ServerState;
import org.apache.zookeeper.test.ClientBase;
import org.apache.zookeeper.test.FLENewEpochTest;
-import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
public class CnxManagerTest extends ZKTestCase {
+
protected static final Logger LOG = LoggerFactory.getLogger(FLENewEpochTest.class);
protected static final int THRESHOLD = 4;
int count;
- Map<Long,QuorumServer> peers;
- File peerTmpdir[];
- int peerQuorumPort[];
- int peerClientPort[];
+ Map<Long, QuorumServer> peers;
+ File[] peerTmpdir;
+ int[] peerQuorumPort;
+ int[] peerClientPort;
@Before
public void setUp() throws Exception {
this.count = 3;
- this.peers = new HashMap<Long,QuorumServer>(count);
+ this.peers = new HashMap<Long, QuorumServer>(count);
peerTmpdir = new File[count];
peerQuorumPort = new int[count];
peerClientPort = new int[count];
- for(int i = 0; i < count; i++) {
+ for (int i = 0; i < count; i++) {
peerQuorumPort[i] = PortAssignment.unique();
peerClientPort[i] = PortAssignment.unique();
- peers.put(Long.valueOf(i),
- new QuorumServer(i,
- new InetSocketAddress(
- "127.0.0.1", peerQuorumPort[i]),
- new InetSocketAddress(
- "127.0.0.1", PortAssignment.unique()),
- new InetSocketAddress(
- "127.0.0.1", peerClientPort[i])));
+ peers.put((long) i, new QuorumServer(i, new InetSocketAddress("127.0.0.1", peerQuorumPort[i]), new InetSocketAddress("127.0.0.1", PortAssignment.unique()), new InetSocketAddress("127.0.0.1", peerClientPort[i])));
peerTmpdir[i] = ClientBase.createTmpDir();
}
}
- ByteBuffer createMsg(int state, long leader, long zxid, long epoch){
- byte requestBytes[] = new byte[28];
+ ByteBuffer createMsg(int state, long leader, long zxid, long epoch) {
+ byte[] requestBytes = new byte[28];
ByteBuffer requestBuffer = ByteBuffer.wrap(requestBytes);
/*
@@ -113,16 +108,16 @@ public class CnxManagerTest extends ZKTestCase {
class CnxManagerThread extends Thread {
boolean failed;
- CnxManagerThread(){
+ CnxManagerThread() {
failed = false;
}
- public void run(){
+ public void run() {
try {
QuorumPeer peer = new QuorumPeer(peers, peerTmpdir[0], peerTmpdir[0], peerClientPort[0], 3, 0, 1000, 2, 2, 2);
QuorumCnxManager cnxManager = peer.createCnxnManager();
QuorumCnxManager.Listener listener = cnxManager.listener;
- if(listener != null){
+ if (listener != null) {
listener.start();
} else {
LOG.error("Null listener when initializing cnx manager");
@@ -133,12 +128,14 @@ public class CnxManagerTest extends ZKTestCase {
Message m = null;
int numRetries = 1;
- while((m == null) && (numRetries++ <= THRESHOLD)){
+ while ((m == null) && (numRetries++ <= THRESHOLD)) {
m = cnxManager.pollRecvQueue(3000, TimeUnit.MILLISECONDS);
- if(m == null) cnxManager.connectAll();
+ if (m == null) {
+ cnxManager.connectAll();
+ }
}
- if(numRetries > THRESHOLD){
+ if (numRetries > THRESHOLD) {
failed = true;
return;
}
@@ -146,15 +143,15 @@ public class CnxManagerTest extends ZKTestCase {
cnxManager.testInitiateConnection(sid);
m = cnxManager.pollRecvQueue(3000, TimeUnit.MILLISECONDS);
- if(m == null){
+ if (m == null) {
failed = true;
- return;
}
} catch (Exception e) {
LOG.error("Exception while running mock thread", e);
- Assert.fail("Unexpected exception");
+ fail("Unexpected exception");
}
}
+
}
@Test
@@ -166,7 +163,7 @@ public class CnxManagerTest extends ZKTestCase {
QuorumPeer peer = new QuorumPeer(peers, peerTmpdir[1], peerTmpdir[1], peerClientPort[1], 3, 1, 1000, 2, 2, 2);
QuorumCnxManager cnxManager = peer.createCnxnManager();
QuorumCnxManager.Listener listener = cnxManager.listener;
- if(listener != null){
+ if (listener != null) {
listener.start();
} else {
LOG.error("Null listener when initializing cnx manager");
@@ -176,22 +173,25 @@ public class CnxManagerTest extends ZKTestCase {
Message m = null;
int numRetries = 1;
- while((m == null) && (numRetries++ <= THRESHOLD)){
+ while ((m == null) && (numRetries++ <= THRESHOLD)) {
m = cnxManager.pollRecvQueue(3000, TimeUnit.MILLISECONDS);
- if(m == null) cnxManager.connectAll();
+ if (m == null) {
+ cnxManager.connectAll();
+ }
}
- Assert.assertTrue("Exceeded number of retries", numRetries <= THRESHOLD);
+ assertTrue("Exceeded number of retries", numRetries <= THRESHOLD);
thread.join(5000);
if (thread.isAlive()) {
- Assert.fail("Thread didn't join");
+ fail("Thread didn't join");
} else {
- if(thread.failed)
- Assert.fail("Did not receive expected message");
+ if (thread.failed) {
+ fail("Did not receive expected message");
+ }
}
cnxManager.halt();
- Assert.assertFalse(cnxManager.listener.isAlive());
+ assertFalse(cnxManager.listener.isAlive());
}
@Test
@@ -203,17 +203,13 @@ public class CnxManagerTest extends ZKTestCase {
LOG.info("This is the dead address I'm trying: " + deadAddress);
- peers.put(Long.valueOf(2),
- new QuorumServer(2,
- new InetSocketAddress(deadAddress, deadPort),
- new InetSocketAddress(deadAddress, PortAssignment.unique()),
- new InetSocketAddress(deadAddress, PortAssignment.unique())));
+ peers.put(2L, new QuorumServer(2, new InetSocketAddress(deadAddress, deadPort), new InetSocketAddress(deadAddress, PortAssignment.unique()), new InetSocketAddress(deadAddress, PortAssignment.unique())));
peerTmpdir[2] = ClientBase.createTmpDir();
QuorumPeer peer = new QuorumPeer(peers, peerTmpdir[1], peerTmpdir[1], peerClientPort[1], 3, 1, 1000, 2, 2, 2);
QuorumCnxManager cnxManager = peer.createCnxnManager();
QuorumCnxManager.Listener listener = cnxManager.listener;
- if(listener != null){
+ if (listener != null) {
listener.start();
} else {
LOG.error("Null listener when initializing cnx manager");
@@ -223,9 +219,11 @@ public class CnxManagerTest extends ZKTestCase {
cnxManager.toSend(2L, createMsg(ServerState.LOOKING.ordinal(), 1, -1, 1));
long end = Time.currentElapsedTime();
- if((end - begin) > 6000) Assert.fail("Waited more than necessary");
+ if ((end - begin) > 6000) {
+ fail("Waited more than necessary");
+ }
cnxManager.halt();
- Assert.assertFalse(cnxManager.listener.isAlive());
+ assertFalse(cnxManager.listener.isAlive());
}
/**
@@ -241,7 +239,7 @@ public class CnxManagerTest extends ZKTestCase {
QuorumPeer peer = new QuorumPeer(peers, peerTmpdir[1], peerTmpdir[1], peerClientPort[1], 3, 1, 1000, 2, 2, 2);
QuorumCnxManager cnxManager = peer.createCnxnManager();
QuorumCnxManager.Listener listener = cnxManager.listener;
- if(listener != null){
+ if (listener != null) {
listener.start();
} else {
LOG.error("Null listener when initializing cnx manager");
@@ -259,12 +257,11 @@ public class CnxManagerTest extends ZKTestCase {
DataOutputStream dout = new DataOutputStream(sc.socket().getOutputStream());
dout.writeLong(QuorumCnxManager.PROTOCOL_VERSION);
dout.writeLong(2);
- String addr = otherAddr.getHostString()+ ":" + otherAddr.getPort();
+ String addr = otherAddr.getHostString() + ":" + otherAddr.getPort();
byte[] addr_bytes = addr.getBytes();
dout.writeInt(addr_bytes.length);
dout.write(addr_bytes);
dout.flush();
-
ByteBuffer msgBuffer = ByteBuffer.wrap(new byte[4]);
msgBuffer.putInt(-20);
@@ -273,26 +270,26 @@ public class CnxManagerTest extends ZKTestCase {
Thread.sleep(1000);
- try{
+ try {
/*
* Write a number of times until it
* detects that the socket is broken.
*/
- for(int i = 0; i < 100; i++){
+ for (int i = 0; i < 100; i++) {
msgBuffer.position(0);
sc.write(msgBuffer);
}
- Assert.fail("Socket has not been closed");
+ fail("Socket has not been closed");
} catch (Exception e) {
LOG.info("Socket has been closed as expected");
}
peer.shutdown();
cnxManager.halt();
- Assert.assertFalse(cnxManager.listener.isAlive());
+ assertFalse(cnxManager.listener.isAlive());
}
/**
- * Test for bug described in {@link https://issues.apache.org/jira/browse/ZOOKEEPER-3320}.
+ * Test for bug described in https://issues.apache.org/jira/browse/ZOOKEEPER-3320.
* Test create peer with address which contains unresolvable DNS name,
* leader election listener thread should stop after N errors.
*
@@ -300,13 +297,10 @@ public class CnxManagerTest extends ZKTestCase {
*/
@Test
public void testCnxManagerListenerThreadConfigurableRetry() throws Exception {
- final Map<Long,QuorumServer> unresolvablePeers = new HashMap<>();
+ final Map<Long, QuorumServer> unresolvablePeers = new HashMap<>();
final long myid = 1L;
unresolvablePeers.put(myid, new QuorumServer(myid, "unresolvable-domain.org:2182:2183;2181"));
- final QuorumPeer peer = new QuorumPeer(unresolvablePeers,
- ClientBase.createTmpDir(),
- ClientBase.createTmpDir(),
- 2181, 3, myid, 1000, 2, 2, 2);
+ final QuorumPeer peer = new QuorumPeer(unresolvablePeers, ClientBase.createTmpDir(), ClientBase.createTmpDir(), 2181, 3, myid, 1000, 2, 2, 2);
final QuorumCnxManager cnxManager = peer.createCnxnManager();
final QuorumCnxManager.Listener listener = cnxManager.listener;
final AtomicBoolean errorHappend = new AtomicBoolean();
@@ -315,25 +309,25 @@ public class CnxManagerTest extends ZKTestCase {
// listener thread should stop and throws error which notify QuorumPeer about error.
// QuorumPeer should start shutdown process
listener.join(15000); // set wait time, if listener contains bug and thread not stops.
- Assert.assertFalse(listener.isAlive());
- Assert.assertTrue(errorHappend.get());
- Assert.assertFalse(QuorumPeer.class.getSimpleName() + " not stopped after "
- + "listener thread death", listener.isAlive());
+ assertFalse(listener.isAlive());
+ assertTrue(errorHappend.get());
+ assertFalse(QuorumPeer.class.getSimpleName()
+ + " not stopped after "
+ + "listener thread death", listener.isAlive());
}
/**
* Tests a bug in QuorumCnxManager that causes a NPE when a 3.4.6
- * observer connects to a 3.5.0 server.
+ * observer connects to a 3.5.0 server.
* see https://issues.apache.org/jira/browse/ZOOKEEPER-1789
- *
+ *
* @throws Exception
*/
@Test
public void testCnxManagerNPE() throws Exception {
// the connecting peer (id = 2) is a 3.4.6 observer
peers.get(2L).type = LearnerType.OBSERVER;
- QuorumPeer peer = new QuorumPeer(peers, peerTmpdir[1], peerTmpdir[1],
- peerClientPort[1], 3, 1, 1000, 2, 2, 2);
+ QuorumPeer peer = new QuorumPeer(peers, peerTmpdir[1], peerTmpdir[1], peerClientPort[1], 3, 1, 1000, 2, 2, 2);
QuorumCnxManager cnxManager = peer.createCnxnManager();
QuorumCnxManager.Listener listener = cnxManager.listener;
if (listener != null) {
@@ -368,11 +362,11 @@ public class CnxManagerTest extends ZKTestCase {
sc.write(msgBuffer);
Message m = cnxManager.pollRecvQueue(1000, TimeUnit.MILLISECONDS);
- Assert.assertNotNull(m);
+ assertNotNull(m);
peer.shutdown();
cnxManager.halt();
- Assert.assertFalse(cnxManager.listener.isAlive());
+ assertFalse(cnxManager.listener.isAlive());
}
/*
@@ -383,7 +377,7 @@ public class CnxManagerTest extends ZKTestCase {
QuorumPeer peer = new QuorumPeer(peers, peerTmpdir[1], peerTmpdir[1], peerClientPort[1], 3, 1, 2000, 2, 2, 2);
QuorumCnxManager cnxManager = peer.createCnxnManager();
QuorumCnxManager.Listener listener = cnxManager.listener;
- if(listener != null){
+ if (listener != null) {
listener.start();
} else {
LOG.error("Null listener when initializing cnx manager");
@@ -398,9 +392,11 @@ public class CnxManagerTest extends ZKTestCase {
// Read without sending data. Verify timeout.
cnxManager.receiveConnection(sock);
long end = Time.currentElapsedTime();
- if((end - begin) > ((peer.getSyncLimit() * peer.getTickTime()) + 500)) Assert.fail("Waited more than necessary");
+ if ((end - begin) > ((peer.getSyncLimit() * peer.getTickTime()) + 500)) {
+ fail("Waited more than necessary");
+ }
cnxManager.halt();
- Assert.assertFalse(cnxManager.listener.isAlive());
+ assertFalse(cnxManager.listener.isAlive());
}
/**
@@ -416,7 +412,8 @@ public class CnxManagerTest extends ZKTestCase {
return new SSLSocket() {
@Override
- public void connect(SocketAddress endpoint, int timeout) {}
+ public void connect(SocketAddress endpoint, int timeout) {
+ }
@Override
public void startHandshake() throws IOException {
@@ -428,19 +425,19 @@ public class CnxManagerTest extends ZKTestCase {
closeLatch.countDown();
}
- public String [] getSupportedCipherSuites() {
+ public String[] getSupportedCipherSuites() {
throw new UnsupportedOperationException();
}
- public String [] getEnabledCipherSuites() {
+ public String[] getEnabledCipherSuites() {
throw new UnsupportedOperationException();
}
- public String [] getSupportedProtocols() {
+ public String[] getSupportedProtocols() {
throw new UnsupportedOperationException();
}
- public String [] getEnabledProtocols() {
+ public String[] getEnabledProtocols() {
throw new UnsupportedOperationException();
}
@@ -448,24 +445,39 @@ public class CnxManagerTest extends ZKTestCase {
throw new UnsupportedOperationException();
}
- public void setEnabledCipherSuites(String suites []) {}
- public void setEnabledProtocols(String protocols[]) {}
- public void addHandshakeCompletedListener(HandshakeCompletedListener listener) {}
- public void removeHandshakeCompletedListener(HandshakeCompletedListener listener) {}
- public void setUseClientMode(boolean mode) {}
- public boolean getUseClientMode() { return true; }
- public void setNeedClientAuth(boolean need) {}
- public boolean getNeedClientAuth() { return true; }
- public void setWantClientAuth(boolean want) {}
- public boolean getWantClientAuth() { return true; }
- public void setEnableSessionCreation(boolean flag) {}
- public boolean getEnableSessionCreation() { return true; }
+ public void setEnabledCipherSuites(String[] suites) {
+ }
+ public void setEnabledProtocols(String[] protocols) {
+ }
+ public void addHandshakeCompletedListener(HandshakeCompletedListener listener) {
+ }
+ public void removeHandshakeCompletedListener(HandshakeCompletedListener listener) {
+ }
+ public void setUseClientMode(boolean mode) {
+ }
+ public boolean getUseClientMode() {
+ return true;
+ }
+ public void setNeedClientAuth(boolean need) {
+ }
+ public boolean getNeedClientAuth() {
+ return true;
+ }
+ public void setWantClientAuth(boolean want) {
+ }
+ public boolean getWantClientAuth() {
+ return true;
+ }
+ public void setEnableSessionCreation(boolean flag) {
+ }
+ public boolean getEnableSessionCreation() {
+ return true;
+ }
};
}
};
- QuorumPeer peer = new QuorumPeer(peers, peerTmpdir[0], peerTmpdir[0],
- peerClientPort[0], 3, 0, 2000, 2, 2, 2) {
+ QuorumPeer peer = new QuorumPeer(peers, peerTmpdir[0], peerTmpdir[0], peerClientPort[0], 3, 0, 2000, 2, 2, 2) {
@Override
public QuorumX509Util createX509Util() {
return mockedX509Util;
@@ -475,7 +487,7 @@ public class CnxManagerTest extends ZKTestCase {
peer.setSslQuorum(true);
QuorumCnxManager cnxManager = peer.createCnxnManager();
cnxManager.connectOne(1, peers.get(1L).electionAddr);
- Assert.assertTrue(closeLatch.await(1, TimeUnit.SECONDS));
+ assertTrue(closeLatch.await(1, TimeUnit.SECONDS));
}
/*
@@ -486,35 +498,29 @@ public class CnxManagerTest extends ZKTestCase {
ArrayList<QuorumPeer> peerList = new ArrayList<QuorumPeer>();
try {
for (int sid = 0; sid < 3; sid++) {
- QuorumPeer peer = new QuorumPeer(peers, peerTmpdir[sid],
- peerTmpdir[sid], peerClientPort[sid], 3, sid, 1000, 2,
- 2, 2);
+ QuorumPeer peer = new QuorumPeer(peers, peerTmpdir[sid], peerTmpdir[sid], peerClientPort[sid], 3, sid, 1000, 2, 2, 2);
LOG.info("Starting peer {}", peer.getId());
peer.start();
peerList.add(sid, peer);
}
String failure = verifyThreadCount(peerList, 4);
- Assert.assertNull(failure, failure);
+ assertNull(failure, failure);
for (int myid = 0; myid < 3; myid++) {
for (int i = 0; i < 5; i++) {
// halt one of the listeners and verify count
QuorumPeer peer = peerList.get(myid);
- LOG.info("Round {}, halting peer ",
- new Object[] { i, peer.getId() });
+ LOG.info("Round {}, halting peer {}", i, peer.getId());
peer.shutdown();
peerList.remove(myid);
failure = verifyThreadCount(peerList, 2);
- Assert.assertNull(failure, failure);
+ assertNull(failure, failure);
// Restart halted node and verify count
- peer = new QuorumPeer(peers, peerTmpdir[myid],
- peerTmpdir[myid], peerClientPort[myid], 3, myid,
- 1000, 2, 2, 2);
- LOG.info("Round {}, restarting peer ",
- new Object[] { i, peer.getId() });
+ peer = new QuorumPeer(peers, peerTmpdir[myid], peerTmpdir[myid], peerClientPort[myid], 3, myid, 1000, 2, 2, 2);
+ LOG.info("Round {}, restarting peer {}", i, peer.getId());
peer.start();
peerList.add(myid, peer);
failure = verifyThreadCount(peerList, 4);
- Assert.assertNull(failure, failure);
+ assertNull(failure, failure);
}
}
} finally {
@@ -528,9 +534,7 @@ public class CnxManagerTest extends ZKTestCase {
* Returns null on success, otw the message assoc with the failure
* @throws InterruptedException
*/
- public String verifyThreadCount(ArrayList<QuorumPeer> peerList, long ecnt)
- throws InterruptedException
- {
+ public String verifyThreadCount(ArrayList<QuorumPeer> peerList, long ecnt) throws InterruptedException {
String failure = null;
for (int i = 0; i < 480; i++) {
Thread.sleep(500);
@@ -549,8 +553,9 @@ public class CnxManagerTest extends ZKTestCase {
long cnt = cnxManager.getThreadCount();
if (cnt != ecnt) {
return new Date()
- + " Incorrect number of Worker threads for sid=" + myid
- + " expected " + ecnt + " found " + cnt;
+ + " Incorrect number of Worker threads for sid=" + myid
+ + " expected " + ecnt
+ + " found " + cnt;
}
}
return null;
@@ -578,8 +583,9 @@ public class CnxManagerTest extends ZKTestCase {
// now parse it
din = new DataInputStream(new ByteArrayInputStream(bos.toByteArray()));
msg = InitialMessage.parse(-65530L, din);
- Assert.fail("bad protocol version accepted");
- } catch (InitialMessage.InitialMessageException ex) {}
+ fail("bad protocol version accepted");
+ } catch (InitialMessage.InitialMessageException ex) {
+ }
// message too long
try {
@@ -593,8 +599,9 @@ public class CnxManagerTest extends ZKTestCase {
din = new DataInputStream(new ByteArrayInputStream(bos.toByteArray()));
msg = InitialMessage.parse(QuorumCnxManager.PROTOCOL_VERSION, din);
- Assert.fail("long message accepted");
- } catch (InitialMessage.InitialMessageException ex) {}
+ fail("long message accepted");
+ } catch (InitialMessage.InitialMessageException ex) {
+ }
// bad hostport string
try {
@@ -608,8 +615,9 @@ public class CnxManagerTest extends ZKTestCase {
din = new DataInputStream(new ByteArrayInputStream(bos.toByteArray()));
msg = InitialMessage.parse(QuorumCnxManager.PROTOCOL_VERSION, din);
- Assert.fail("bad hostport accepted");
- } catch (InitialMessage.InitialMessageException ex) {}
+ fail("bad hostport accepted");
+ } catch (InitialMessage.InitialMessageException ex) {
+ }
// good message
try {
@@ -625,15 +633,16 @@ public class CnxManagerTest extends ZKTestCase {
din = new DataInputStream(new ByteArrayInputStream(bos.toByteArray()));
msg = InitialMessage.parse(QuorumCnxManager.PROTOCOL_VERSION, din);
} catch (InitialMessage.InitialMessageException ex) {
- Assert.fail(ex.toString());
+ fail(ex.toString());
}
}
private String createLongString(int size) {
StringBuilder sb = new StringBuilder(size);
- for (int i=0; i < size; i++) {
+ for (int i = 0; i < size; i++) {
sb.append('x');
}
return sb.toString();
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/CommitProcessorConcurrencyTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/CommitProcessorConcurrencyTest.java
index 95889ef1d..7d342a0d7 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/CommitProcessorConcurrencyTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/CommitProcessorConcurrencyTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,6 +18,9 @@
package org.apache.zookeeper.server.quorum;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
@@ -28,7 +31,6 @@ import java.util.List;
import java.util.Set;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
-
import org.apache.jute.BinaryOutputArchive;
import org.apache.jute.Record;
import org.apache.zookeeper.CreateMode;
@@ -44,15 +46,14 @@ import org.apache.zookeeper.server.RequestProcessor;
import org.apache.zookeeper.server.WorkerService;
import org.apache.zookeeper.server.ZooKeeperServerListener;
import org.junit.After;
-import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class CommitProcessorConcurrencyTest extends ZKTestCase {
- protected static final Logger LOG = LoggerFactory
- .getLogger(CommitProcessorConcurrencyTest.class);
+
+ protected static final Logger LOG = LoggerFactory.getLogger(CommitProcessorConcurrencyTest.class);
BlockingQueue<Request> processedRequests;
MockCommitProcessor processor;
@@ -74,6 +75,7 @@ public class CommitProcessorConcurrencyTest extends ZKTestCase {
// This queue is infinite if we use "poll" to get requests, but returns a
// finite size when asked.
class MockRequestsQueue extends LinkedBlockingQueue<Request> {
+
private static final long serialVersionUID = 1L;
int readReqId = 0;
@@ -81,12 +83,10 @@ public class CommitProcessorConcurrencyTest extends ZKTestCase {
public Request poll() {
readReqId++;
try {
- return newRequest(new GetDataRequest("/", false),
- OpCode.getData, readReqId % 50, readReqId);
+ return newRequest(new GetDataRequest("/", false), OpCode.getData, readReqId % 50, readReqId);
} catch (IOException e) {
e.printStackTrace();
}
- ;
return null;
}
@@ -94,13 +94,14 @@ public class CommitProcessorConcurrencyTest extends ZKTestCase {
public int size() {
return 42;
}
+
}
class MockCommitProcessor extends CommitProcessor {
+
MockCommitProcessor() {
super(new RequestProcessor() {
- public void processRequest(Request request)
- throws RequestProcessorException {
+ public void processRequest(Request request) throws RequestProcessorException {
processedRequests.offer(request);
}
@@ -110,20 +111,19 @@ public class CommitProcessorConcurrencyTest extends ZKTestCase {
@Override
public void notifyStopping(String threadName, int errorCode) {
- Assert.fail("Commit processor crashed " + errorCode);
+ fail("Commit processor crashed " + errorCode);
}
});
}
public void initThreads(int poolSize) {
this.stopped = false;
- this.workerPool = new WorkerService("CommitProcWork", poolSize,
- true);
+ this.workerPool = new WorkerService("CommitProcWork", poolSize, true);
}
+
}
- private Request newRequest(Record rec, int type, int sessionId, int xid)
- throws IOException {
+ private Request newRequest(Record rec, int type, int sessionId, int xid) throws IOException {
ByteArrayOutputStream boas = new ByteArrayOutputStream();
BinaryOutputArchive boa = BinaryOutputArchive.getArchive(boas);
rec.serialize(boa, "request");
@@ -137,15 +137,11 @@ public class CommitProcessorConcurrencyTest extends ZKTestCase {
* according to the order of the session (first read, then the write).
*/
@Test
- public void committedAndUncommittedOfTheSameSessionRaceTest()
- throws Exception {
+ public void committedAndUncommittedOfTheSameSessionRaceTest() throws Exception {
final String path = "/testCvsUCRace";
- Request readReq = newRequest(new GetDataRequest(path, false),
- OpCode.getData, 0x0, 0);
- Request writeReq = newRequest(
- new SetDataRequest(path, new byte[16], -1), OpCode.setData, 0x0,
- 1);
+ Request readReq = newRequest(new GetDataRequest(path, false), OpCode.getData, 0x0, 0);
+ Request writeReq = newRequest(new SetDataRequest(path, new byte[16], -1), OpCode.setData, 0x0, 1);
processor.committedRequests.add(writeReq);
processor.queuedRequests.add(readReq);
@@ -156,17 +152,13 @@ public class CommitProcessorConcurrencyTest extends ZKTestCase {
processor.stoppedMainLoop = true;
processor.run();
- Assert.assertTrue(
- "Request was not processed " + readReq + " instead "
- + processedRequests.peek(),
- processedRequests.peek() != null
- && processedRequests.peek().equals(readReq));
+ assertTrue(
+ "Request was not processed " + readReq + " instead " + processedRequests.peek(),
+ processedRequests.peek() != null && processedRequests.peek().equals(readReq));
processedRequests.poll();
- Assert.assertTrue(
- "Request was not processed " + writeReq + " instead "
- + processedRequests.peek(),
- processedRequests.peek() != null
- && processedRequests.peek().equals(writeReq));
+ assertTrue(
+ "Request was not processed " + writeReq + " instead " + processedRequests.peek(),
+ processedRequests.peek() != null && processedRequests.peek().equals(writeReq));
}
/**
@@ -178,24 +170,30 @@ public class CommitProcessorConcurrencyTest extends ZKTestCase {
* uncommited requests, followed by the reads are processed.
*/
@Test
- public void processAsMuchUncommittedRequestsAsPossibleTest()
- throws Exception {
+ public void processAsMuchUncommittedRequestsAsPossibleTest() throws Exception {
final String path = "/testAsMuchAsPossible";
List<Request> shouldBeProcessed = new LinkedList<Request>();
Set<Request> shouldNotBeProcessed = new HashSet<Request>();
for (int sessionId = 1; sessionId <= 5; ++sessionId) {
for (int readReqId = 1; readReqId <= sessionId; ++readReqId) {
- Request readReq = newRequest(new GetDataRequest(path, false),
- OpCode.getData, sessionId, readReqId);
+ Request readReq = newRequest(new GetDataRequest(path, false), OpCode.getData, sessionId, readReqId);
shouldBeProcessed.add(readReq);
processor.queuedRequests.add(readReq);
}
Request writeReq = newRequest(
- new CreateRequest(path, new byte[0], Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT_SEQUENTIAL.toFlag()),
- OpCode.create, sessionId, sessionId + 1);
- Request readReq = newRequest(new GetDataRequest(path, false),
- OpCode.getData, sessionId, sessionId + 2);
+ new CreateRequest(
+ path,
+ new byte[0],
+ Ids.OPEN_ACL_UNSAFE,
+ CreateMode.PERSISTENT_SEQUENTIAL.toFlag()),
+ OpCode.create,
+ sessionId,
+ sessionId + 1);
+ Request readReq = newRequest(
+ new GetDataRequest(path, false),
+ OpCode.getData,
+ sessionId,
+ sessionId + 2);
processor.queuedRequests.add(writeReq);
processor.queuedWriteRequests.add(writeReq);
processor.queuedRequests.add(readReq);
@@ -211,10 +209,8 @@ public class CommitProcessorConcurrencyTest extends ZKTestCase {
for (Request r : shouldBeProcessed) {
LOG.error("Did not process " + r);
}
- Assert.assertTrue("Not all requests were processed",
- shouldBeProcessed.isEmpty());
- Assert.assertFalse("Processed a wrong request",
- shouldNotBeProcessed.removeAll(processedRequests));
+ assertTrue("Not all requests were processed", shouldBeProcessed.isEmpty());
+ assertFalse("Processed a wrong request", shouldNotBeProcessed.removeAll(processedRequests));
}
/**
@@ -225,23 +221,22 @@ public class CommitProcessorConcurrencyTest extends ZKTestCase {
* executed after the write, before any other write, along with new reads.
*/
@Test
- public void processAllFollowingUncommittedAfterFirstCommitTest()
- throws Exception {
+ public void processAllFollowingUncommittedAfterFirstCommitTest() throws Exception {
final String path = "/testUncommittedFollowingCommited";
Set<Request> shouldBeInPending = new HashSet<Request>();
Set<Request> shouldBeProcessedAfterPending = new HashSet<Request>();
Request writeReq = newRequest(
- new CreateRequest(path, new byte[0], Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT_SEQUENTIAL.toFlag()),
- OpCode.create, 0x1, 1);
+ new CreateRequest(path, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL.toFlag()),
+ OpCode.create,
+ 0x1,
+ 1);
processor.queuedRequests.add(writeReq);
processor.queuedWriteRequests.add(writeReq);
shouldBeInPending.add(writeReq);
for (int readReqId = 2; readReqId <= 5; ++readReqId) {
- Request readReq = newRequest(new GetDataRequest(path, false),
- OpCode.getData, 0x1, readReqId);
+ Request readReq = newRequest(new GetDataRequest(path, false), OpCode.getData, 0x1, readReqId);
processor.queuedRequests.add(readReq);
shouldBeInPending.add(readReq);
shouldBeProcessedAfterPending.add(readReq);
@@ -250,21 +245,15 @@ public class CommitProcessorConcurrencyTest extends ZKTestCase {
processor.stoppedMainLoop = true;
processor.run();
- Assert.assertTrue("Processed without waiting for commit",
- processedRequests.isEmpty());
- Assert.assertTrue("Did not handled all of queuedRequests' requests",
- processor.queuedRequests.isEmpty());
- Assert.assertTrue("Removed from blockedQueuedRequests before commit",
- !processor.queuedWriteRequests.isEmpty());
-
- shouldBeInPending
- .removeAll(processor.pendingRequests.get(writeReq.sessionId));
+ assertTrue("Processed without waiting for commit", processedRequests.isEmpty());
+ assertTrue("Did not handled all of queuedRequests' requests", processor.queuedRequests.isEmpty());
+ assertTrue("Removed from blockedQueuedRequests before commit", !processor.queuedWriteRequests.isEmpty());
+
+ shouldBeInPending.removeAll(processor.pendingRequests.get(writeReq.sessionId));
for (Request r : shouldBeInPending) {
LOG.error("Should be in pending " + r);
}
- Assert.assertTrue(
- "Not all requests moved to pending from queuedRequests",
- shouldBeInPending.isEmpty());
+ assertTrue("Not all requests moved to pending from queuedRequests", shouldBeInPending.isEmpty());
processor.committedRequests.add(writeReq);
processor.stoppedMainLoop = true;
@@ -272,16 +261,11 @@ public class CommitProcessorConcurrencyTest extends ZKTestCase {
processor.initThreads(defaultSizeOfThreadPool);
Thread.sleep(500);
- Assert.assertTrue("Did not process committed request",
- processedRequests.peek() == writeReq);
- Assert.assertTrue("Did not process following read request",
- processedRequests.containsAll(shouldBeProcessedAfterPending));
- Assert.assertTrue("Did not process committed request",
- processor.committedRequests.isEmpty());
- Assert.assertTrue("Did not process committed request",
- processor.pendingRequests.isEmpty());
- Assert.assertTrue("Did not remove from blockedQueuedRequests",
- processor.queuedWriteRequests.isEmpty());
+ assertTrue("Did not process committed request", processedRequests.peek() == writeReq);
+ assertTrue("Did not process following read request", processedRequests.containsAll(shouldBeProcessedAfterPending));
+ assertTrue("Did not process committed request", processor.committedRequests.isEmpty());
+ assertTrue("Did not process committed request", processor.pendingRequests.isEmpty());
+ assertTrue("Did not remove from blockedQueuedRequests", processor.queuedWriteRequests.isEmpty());
}
/**
@@ -299,30 +283,37 @@ public class CommitProcessorConcurrencyTest extends ZKTestCase {
* in the last iteration, and all lists are empty.
*/
@Test
- public void processAllWritesMaxBatchSize()
- throws Exception {
+ public void processAllWritesMaxBatchSize() throws Exception {
final String path = "/processAllWritesMaxBatchSize";
HashSet<Request> shouldBeProcessedAfterPending = new HashSet<Request>();
Request writeReq = newRequest(
- new CreateRequest(path + "_1", new byte[0], Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT_SEQUENTIAL.toFlag()),
- OpCode.create, 0x1, 1);
+ new CreateRequest(
+ path + "_1",
+ new byte[0],
+ Ids.OPEN_ACL_UNSAFE,
+ CreateMode.PERSISTENT_SEQUENTIAL.toFlag()),
+ OpCode.create,
+ 0x1,
+ 1);
processor.queuedRequests.add(writeReq);
processor.queuedWriteRequests.add(writeReq);
Request writeReq2 = newRequest(
- new CreateRequest(path + "_2", new byte[0], Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT_SEQUENTIAL.toFlag()),
- OpCode.create, 0x2, 1);
+ new CreateRequest(
+ path + "_2",
+ new byte[0],
+ Ids.OPEN_ACL_UNSAFE,
+ CreateMode.PERSISTENT_SEQUENTIAL.toFlag()),
+ OpCode.create,
+ 0x2,
+ 1);
processor.queuedRequests.add(writeReq2);
processor.queuedWriteRequests.add(writeReq2);
for (int readReqId = 2; readReqId <= 5; ++readReqId) {
- Request readReq = newRequest(new GetDataRequest(path, false),
- OpCode.getData, 0x1, readReqId);
- Request readReq2 = newRequest(new GetDataRequest(path, false),
- OpCode.getData, 0x2, readReqId);
+ Request readReq = newRequest(new GetDataRequest(path, false), OpCode.getData, 0x1, readReqId);
+ Request readReq2 = newRequest(new GetDataRequest(path, false), OpCode.getData, 0x2, readReqId);
processor.queuedRequests.add(readReq);
shouldBeProcessedAfterPending.add(readReq);
processor.queuedRequests.add(readReq2);
@@ -330,9 +321,14 @@ public class CommitProcessorConcurrencyTest extends ZKTestCase {
}
Request writeReq3 = newRequest(
- new CreateRequest(path + "_3", new byte[0], Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT_SEQUENTIAL.toFlag()),
- OpCode.create, 0x2, 6);
+ new CreateRequest(
+ path + "_3",
+ new byte[0],
+ Ids.OPEN_ACL_UNSAFE,
+ CreateMode.PERSISTENT_SEQUENTIAL.toFlag()),
+ OpCode.create,
+ 0x2,
+ 6);
processor.queuedRequests.add(writeReq3);
processor.queuedWriteRequests.add(writeReq3);
@@ -341,16 +337,11 @@ public class CommitProcessorConcurrencyTest extends ZKTestCase {
processor.stoppedMainLoop = true;
CommitProcessor.setMaxCommitBatchSize(2);
processor.run();
- Assert.assertTrue("Processed without waiting for commit",
- processedRequests.isEmpty());
- Assert.assertTrue("Did not handled all of queuedRequests' requests",
- processor.queuedRequests.isEmpty());
- Assert.assertTrue("Removed from blockedQueuedRequests before commit",
- !processor.queuedWriteRequests.isEmpty());
- Assert.assertTrue("Missing session 1 in pending queue",
- processor.pendingRequests.containsKey(writeReq.sessionId));
- Assert.assertTrue("Missing session 2 in pending queue",
- processor.pendingRequests.containsKey(writeReq2.sessionId));
+ assertTrue("Processed without waiting for commit", processedRequests.isEmpty());
+ assertTrue("Did not handled all of queuedRequests' requests", processor.queuedRequests.isEmpty());
+ assertTrue("Removed from blockedQueuedRequests before commit", !processor.queuedWriteRequests.isEmpty());
+ assertTrue("Missing session 1 in pending queue", processor.pendingRequests.containsKey(writeReq.sessionId));
+ assertTrue("Missing session 2 in pending queue", processor.pendingRequests.containsKey(writeReq2.sessionId));
processor.committedRequests.add(writeReq);
processor.committedRequests.add(writeReq2);
@@ -361,33 +352,34 @@ public class CommitProcessorConcurrencyTest extends ZKTestCase {
processor.initThreads(defaultSizeOfThreadPool);
Thread.sleep(500);
- Assert.assertTrue("Did not process committed request",
- processedRequests.peek() == writeReq);
- Assert.assertTrue("Did not process following read request",
- processedRequests.containsAll(shouldBeProcessedAfterPending));
- Assert.assertTrue("Processed committed request",
- !processor.committedRequests.isEmpty());
- Assert.assertTrue("Removed commit for write req 3",
- processor.committedRequests.peek() == writeReq3);
- Assert.assertTrue("Processed committed request",
- !processor.pendingRequests.isEmpty());
- Assert.assertTrue("Missing session 2 in pending queue",
- processor.pendingRequests.containsKey(writeReq3.sessionId));
- Assert.assertTrue("Missing write 3 in pending queue",
- processor.pendingRequests.get(writeReq3.sessionId).peek() == writeReq3);
- Assert.assertTrue("Removed from blockedQueuedRequests",
- !processor.queuedWriteRequests.isEmpty());
- Assert.assertTrue("Removed write req 3 from blockedQueuedRequests",
- processor.queuedWriteRequests.peek() == writeReq3);
-
- Request readReq3 = newRequest(new GetDataRequest(path, false),
- OpCode.getData, 0x1, 7);
+ assertTrue("Did not process committed request", processedRequests.peek() == writeReq);
+ assertTrue("Did not process following read request", processedRequests.containsAll(shouldBeProcessedAfterPending));
+ assertTrue("Processed committed request", !processor.committedRequests.isEmpty());
+ assertTrue("Removed commit for write req 3", processor.committedRequests.peek() == writeReq3);
+ assertTrue("Processed committed request", !processor.pendingRequests.isEmpty());
+ assertTrue("Missing session 2 in pending queue", processor.pendingRequests.containsKey(writeReq3.sessionId));
+ assertTrue(
+ "Missing write 3 in pending queue",
+ processor.pendingRequests.get(writeReq3.sessionId).peek() == writeReq3);
+ assertTrue(
+ "Removed from blockedQueuedRequests",
+ !processor.queuedWriteRequests.isEmpty());
+ assertTrue(
+ "Removed write req 3 from blockedQueuedRequests",
+ processor.queuedWriteRequests.peek() == writeReq3);
+
+ Request readReq3 = newRequest(new GetDataRequest(path, false), OpCode.getData, 0x1, 7);
processor.queuedRequests.add(readReq3);
shouldBeProcessedAfterPending.add(readReq3);
Request writeReq4 = newRequest(
- new CreateRequest(path + "_4", new byte[0], Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT_SEQUENTIAL.toFlag()),
- OpCode.create, 0x2, 7);
+ new CreateRequest(
+ path + "_4",
+ new byte[0],
+ Ids.OPEN_ACL_UNSAFE,
+ CreateMode.PERSISTENT_SEQUENTIAL.toFlag()),
+ OpCode.create,
+ 0x2,
+ 7);
processor.queuedRequests.add(writeReq4);
processor.queuedWriteRequests.add(writeReq4);
@@ -399,18 +391,14 @@ public class CommitProcessorConcurrencyTest extends ZKTestCase {
processor.initThreads(defaultSizeOfThreadPool);
Thread.sleep(500);
- Assert.assertTrue("Did not process committed request",
- processedRequests.peek() == writeReq);
- Assert.assertTrue("Did not process following read request",
- processedRequests.containsAll(shouldBeProcessedAfterPending));
- Assert.assertTrue("Processed unexpected committed request",
- !processor.committedRequests.isEmpty());
- Assert.assertTrue("Unexpected pending request",
- processor.pendingRequests.isEmpty());
- Assert.assertTrue("Removed from blockedQueuedRequests",
- !processor.queuedWriteRequests.isEmpty());
- Assert.assertTrue("Removed write req 4 from blockedQueuedRequests",
- processor.queuedWriteRequests.peek() == writeReq4);
+ assertTrue("Did not process committed request", processedRequests.peek() == writeReq);
+ assertTrue("Did not process following read request", processedRequests.containsAll(shouldBeProcessedAfterPending));
+ assertTrue("Processed unexpected committed request", !processor.committedRequests.isEmpty());
+ assertTrue("Unexpected pending request", processor.pendingRequests.isEmpty());
+ assertTrue("Removed from blockedQueuedRequests", !processor.queuedWriteRequests.isEmpty());
+ assertTrue(
+ "Removed write req 4 from blockedQueuedRequests",
+ processor.queuedWriteRequests.peek() == writeReq4);
processor.stoppedMainLoop = true;
CommitProcessor.setMaxCommitBatchSize(3);
@@ -418,16 +406,11 @@ public class CommitProcessorConcurrencyTest extends ZKTestCase {
processor.initThreads(defaultSizeOfThreadPool);
Thread.sleep(500);
- Assert.assertTrue("Did not process committed request",
- processedRequests.peek() == writeReq);
- Assert.assertTrue("Did not process following read request",
- processedRequests.containsAll(shouldBeProcessedAfterPending));
- Assert.assertTrue("Did not process committed request",
- processor.committedRequests.isEmpty());
- Assert.assertTrue("Did not process committed request",
- processor.pendingRequests.isEmpty());
- Assert.assertTrue("Did not remove from blockedQueuedRequests",
- processor.queuedWriteRequests.isEmpty());
+ assertTrue("Did not process committed request", processedRequests.peek() == writeReq);
+ assertTrue("Did not process following read request", processedRequests.containsAll(shouldBeProcessedAfterPending));
+ assertTrue("Did not process committed request", processor.committedRequests.isEmpty());
+ assertTrue("Did not process committed request", processor.pendingRequests.isEmpty());
+ assertTrue("Did not remove from blockedQueuedRequests", processor.queuedWriteRequests.isEmpty());
}
@@ -444,9 +427,10 @@ public class CommitProcessorConcurrencyTest extends ZKTestCase {
Set<Request> nonLocalCommits = new HashSet<Request>();
for (int i = 0; i < 10; i++) {
Request nonLocalCommitReq = newRequest(
- new CreateRequest(path, new byte[0], Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT_SEQUENTIAL.toFlag()),
- OpCode.create, 51, i + 1);
+ new CreateRequest(path, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL.toFlag()),
+ OpCode.create,
+ 51,
+ i + 1);
processor.committedRequests.add(nonLocalCommitReq);
nonLocalCommits.add(nonLocalCommitReq);
}
@@ -455,8 +439,7 @@ public class CommitProcessorConcurrencyTest extends ZKTestCase {
processor.stoppedMainLoop = true;
processor.run();
}
- Assert.assertTrue("commit request was not processed",
- processedRequests.containsAll(nonLocalCommits));
+ assertTrue("commit request was not processed", processedRequests.containsAll(nonLocalCommits));
}
/**
@@ -474,42 +457,47 @@ public class CommitProcessorConcurrencyTest extends ZKTestCase {
// +1 committed requests (also head of queuedRequests)
Request firstCommittedReq = newRequest(
- new CreateRequest(path, new byte[0], Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT_SEQUENTIAL.toFlag()),
- OpCode.create, 0x3, 1);
+ new CreateRequest(path, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL.toFlag()),
+ OpCode.create,
+ 0x3,
+ 1);
processor.queuedRequests.add(firstCommittedReq);
processor.queuedWriteRequests.add(firstCommittedReq);
processor.committedRequests.add(firstCommittedReq);
Set<Request> allReads = new HashSet<Request>();
// +1 read request to queuedRequests
- Request firstRead = newRequest(new GetDataRequest(path, false),
- OpCode.getData, 0x1, 0);
+ Request firstRead = newRequest(new GetDataRequest(path, false), OpCode.getData, 0x1, 0);
allReads.add(firstRead);
processor.queuedRequests.add(firstRead);
// +1 non local commit
Request secondCommittedReq = newRequest(
- new CreateRequest(path, new byte[0], Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT_SEQUENTIAL.toFlag()),
- OpCode.create, 0x99, 2);
+ new CreateRequest(path, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL.toFlag()),
+ OpCode.create,
+ 0x99,
+ 2);
processor.committedRequests.add(secondCommittedReq);
Set<Request> waitingCommittedRequests = new HashSet<Request>();
// +99 non local committed requests
for (int writeReqId = 3; writeReqId < 102; ++writeReqId) {
Request writeReq = newRequest(
- new CreateRequest(path, new byte[0], Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT_SEQUENTIAL.toFlag()),
- OpCode.create, 0x8, writeReqId);
+ new CreateRequest(path, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL.toFlag()),
+ OpCode.create,
+ 0x8,
+ writeReqId);
processor.committedRequests.add(writeReq);
waitingCommittedRequests.add(writeReq);
}
// +50 read requests to queuedRequests
for (int readReqId = 1; readReqId <= 50; ++readReqId) {
- Request readReq = newRequest(new GetDataRequest(path, false),
- OpCode.getData, 0x5, readReqId);
+ Request readReq = newRequest(
+ new GetDataRequest(path, false),
+ OpCode.getData,
+ 0x5,
+ readReqId);
allReads.add(readReq);
processor.queuedRequests.add(readReq);
}
@@ -518,20 +506,15 @@ public class CommitProcessorConcurrencyTest extends ZKTestCase {
processor.stoppedMainLoop = true;
processor.run();
- Assert.assertTrue("Did not process the first write request",
- processedRequests.contains(firstCommittedReq));
+ assertTrue("Did not process the first write request", processedRequests.contains(firstCommittedReq));
for (Request r : allReads) {
- Assert.assertTrue("Processed read request",
- !processedRequests.contains(r));
+ assertTrue("Processed read request", !processedRequests.contains(r));
}
processor.run();
- Assert.assertTrue("did not processed all reads",
- processedRequests.containsAll(allReads));
- Assert.assertTrue("Did not process the second write request",
- processedRequests.contains(secondCommittedReq));
+ assertTrue("did not processed all reads", processedRequests.containsAll(allReads));
+ assertTrue("Did not process the second write request", processedRequests.contains(secondCommittedReq));
for (Request r : waitingCommittedRequests) {
- Assert.assertTrue("Processed additional committed request",
- !processedRequests.contains(r));
+ assertTrue("Processed additional committed request", !processedRequests.contains(r));
}
}
@@ -552,49 +535,50 @@ public class CommitProcessorConcurrencyTest extends ZKTestCase {
HashSet<Request> localRequests = new HashSet<Request>();
// queue the blocking write request to queuedRequests
Request firstCommittedReq = newRequest(
- new CreateRequest(path, new byte[0], Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT_SEQUENTIAL.toFlag()),
- OpCode.create, sessionid, readReqId++);
+ new CreateRequest(path, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL.toFlag()),
+ OpCode.create,
+ sessionid,
+ readReqId++);
processor.queuedRequests.add(firstCommittedReq);
processor.queuedWriteRequests.add(firstCommittedReq);
localRequests.add(firstCommittedReq);
// queue read requests to queuedRequests
- for (; readReqId <= numberofReads+firstCXid; ++readReqId) {
- Request readReq = newRequest(new GetDataRequest(path, false),
- OpCode.getData, sessionid, readReqId);
+ for (; readReqId <= numberofReads + firstCXid; ++readReqId) {
+ Request readReq = newRequest(new GetDataRequest(path, false), OpCode.getData, sessionid, readReqId);
processor.queuedRequests.add(readReq);
localRequests.add(readReq);
}
//run once
- Assert.assertTrue(processor.queuedRequests.containsAll(localRequests));
+ assertTrue(processor.queuedRequests.containsAll(localRequests));
processor.initThreads(defaultSizeOfThreadPool);
processor.run();
Thread.sleep(1000);
//We verify that the processor is waiting for the commit
- Assert.assertTrue(processedRequests.isEmpty());
+ assertTrue(processedRequests.isEmpty());
// We add a commit that belongs to the same session but with smaller cxid,
// i.e., commit of an update from previous connection of this session.
Request preSessionCommittedReq = newRequest(
- new CreateRequest(path, new byte[0], Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT_SEQUENTIAL.toFlag()),
- OpCode.create, sessionid, firstCXid - 2);
+ new CreateRequest(path, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL.toFlag()),
+ OpCode.create,
+ sessionid,
+ firstCXid - 2);
processor.committedRequests.add(preSessionCommittedReq);
processor.committedRequests.add(firstCommittedReq);
processor.run();
Thread.sleep(1000);
//We verify that the commit processor processed the old commit prior to the newer messages
- Assert.assertTrue(processedRequests.peek() == preSessionCommittedReq);
+ assertTrue(processedRequests.peek() == preSessionCommittedReq);
processor.run();
Thread.sleep(1000);
//We verify that the commit processor handle all messages.
- Assert.assertTrue(processedRequests.containsAll(localRequests));
+ assertTrue(processedRequests.containsAll(localRequests));
}
/**
@@ -617,17 +601,17 @@ public class CommitProcessorConcurrencyTest extends ZKTestCase {
// queue the blocking write request to queuedRequests
Request orphanCommittedReq = newRequest(
- new CreateRequest(path, new byte[0], Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT_SEQUENTIAL.toFlag()),
- OpCode.create, sessionid, lastCXid);
+ new CreateRequest(path, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL.toFlag()),
+ OpCode.create,
+ sessionid,
+ lastCXid);
processor.queuedRequests.add(orphanCommittedReq);
processor.queuedWriteRequests.add(orphanCommittedReq);
localRequests.add(orphanCommittedReq);
// queue read requests to queuedRequests
- for (; readReqId <= numberofReads+lastCXid; ++readReqId) {
- Request readReq = newRequest(new GetDataRequest(path, false),
- OpCode.getData, sessionid, readReqId);
+ for (; readReqId <= numberofReads + lastCXid; ++readReqId) {
+ Request readReq = newRequest(new GetDataRequest(path, false), OpCode.getData, sessionid, readReqId);
processor.queuedRequests.add(readReq);
localRequests.add(readReq);
}
@@ -638,27 +622,33 @@ public class CommitProcessorConcurrencyTest extends ZKTestCase {
Thread.sleep(1000);
//We verify that the processor is waiting for the commit
- Assert.assertTrue(processedRequests.isEmpty());
+ assertTrue(processedRequests.isEmpty());
// We add a commit that belongs to the same session but with larger cxid,
// i.e., commit of an update from the next connection of this session.
Request otherSessionCommittedReq = newRequest(
- new CreateRequest(path, new byte[0], Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT_SEQUENTIAL.toFlag()),
- OpCode.create, sessionid, lastCXid+10);
+ new CreateRequest(
+ path,
+ new byte[0],
+ Ids.OPEN_ACL_UNSAFE,
+ CreateMode.PERSISTENT_SEQUENTIAL.toFlag()),
+ OpCode.create,
+ sessionid,
+ lastCXid + 10);
processor.committedRequests.add(otherSessionCommittedReq);
processor.committedRequests.add(orphanCommittedReq);
processor.run();
Thread.sleep(1000);
//We verify that the commit processor processed the old commit prior to the newer messages
- Assert.assertTrue(processedRequests.size() == 1);
- Assert.assertTrue(processedRequests.contains(otherSessionCommittedReq));
+ assertTrue(processedRequests.size() == 1);
+ assertTrue(processedRequests.contains(otherSessionCommittedReq));
processor.run();
Thread.sleep(1000);
//We verify that the commit processor handle all messages.
- Assert.assertTrue(processedRequests.containsAll(localRequests));
+ assertTrue(processedRequests.containsAll(localRequests));
}
-} \ No newline at end of file
+
+}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/CommitProcessorMetricsTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/CommitProcessorMetricsTest.java
index 2bef68843..29fe94b81 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/CommitProcessorMetricsTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/CommitProcessorMetricsTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,27 +18,30 @@
package org.apache.zookeeper.server.quorum;
+import static org.hamcrest.Matchers.greaterThanOrEqualTo;
+import static org.hamcrest.Matchers.lessThanOrEqualTo;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertThat;
+import java.nio.ByteBuffer;
+import java.util.Map;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
import org.apache.zookeeper.ZKTestCase;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.metrics.MetricsUtils;
-import org.apache.zookeeper.server.*;
+import org.apache.zookeeper.server.Request;
+import org.apache.zookeeper.server.RequestProcessor;
+import org.apache.zookeeper.server.ServerMetrics;
+import org.apache.zookeeper.server.WorkerService;
import org.junit.After;
-import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.nio.ByteBuffer;
-import java.util.Map;
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.TimeUnit;
-
-import static org.hamcrest.Matchers.*;
-
public class CommitProcessorMetricsTest extends ZKTestCase {
- protected static final Logger LOG =
- LoggerFactory.getLogger(CommitProcessorMetricsTest.class);
+
+ protected static final Logger LOG = LoggerFactory.getLogger(CommitProcessorMetricsTest.class);
CommitProcessor commitProcessor;
DummyFinalProcessor finalProcessor;
@@ -57,7 +60,7 @@ public class CommitProcessorMetricsTest extends ZKTestCase {
System.clearProperty("zookeeper.commitProcessor.maxCommitBatchSize");
}
- public void setupProcessors(int commitWorkers, int finalProcTime ) {
+ public void setupProcessors(int commitWorkers, int finalProcTime) {
finalProcessor = new DummyFinalProcessor(finalProcTime);
commitProcessor = new TestCommitProcessor(finalProcessor, commitWorkers);
commitProcessor.start();
@@ -72,6 +75,7 @@ public class CommitProcessorMetricsTest extends ZKTestCase {
}
private class TestCommitProcessor extends CommitProcessor {
+
int numWorkerThreads;
public TestCommitProcessor(RequestProcessor finalProcessor, int numWorkerThreads) {
@@ -101,7 +105,7 @@ public class CommitProcessorMetricsTest extends ZKTestCase {
while (state != State.WAITING) {
try {
Thread.sleep(50);
- } catch (Exception e){
+ } catch (Exception e) {
}
state = super.getState();
@@ -126,9 +130,11 @@ public class CommitProcessorMetricsTest extends ZKTestCase {
poolEmpytied.countDown();
}
}
+
}
private class TestWorkerService extends WorkerService {
+
public TestWorkerService(int numWorkerThreads) {
super("CommitProcWork", numWorkerThreads, true);
}
@@ -140,9 +146,11 @@ public class CommitProcessorMetricsTest extends ZKTestCase {
requestScheduled.countDown();
}
}
+
}
private class DummyFinalProcessor implements RequestProcessor {
+
int processTime;
public DummyFinalProcessor(int processTime) {
this.processTime = processTime;
@@ -163,33 +171,32 @@ public class CommitProcessorMetricsTest extends ZKTestCase {
}
@Override
- public void shutdown(){
+ public void shutdown() {
}
+
}
private void checkMetrics(String metricName, long min, long max, double avg, long cnt, long sum) {
Map<String, Object> values = MetricsUtils.currentServerMetrics();
- Assert.assertEquals("expected min is " + min, min, values.get("min_" + metricName));
- Assert.assertEquals("expected max is: " + max, max, values.get("max_" + metricName));
- Assert.assertEquals("expected avg is: " + avg, avg, (Double)values.get("avg_" + metricName), 0.001);
- Assert.assertEquals("expected cnt is: " + cnt, cnt, values.get("cnt_" + metricName));
- Assert.assertEquals("expected sum is: " + sum, sum, values.get("sum_" + metricName));
+ assertEquals("expected min is " + min, min, values.get("min_" + metricName));
+ assertEquals("expected max is: " + max, max, values.get("max_" + metricName));
+ assertEquals("expected avg is: " + avg, avg, (Double) values.get("avg_" + metricName), 0.001);
+ assertEquals("expected cnt is: " + cnt, cnt, values.get("cnt_" + metricName));
+ assertEquals("expected sum is: " + sum, sum, values.get("sum_" + metricName));
}
private void checkTimeMetric(long actual, long lBoundrary, long hBoundrary) {
- Assert.assertThat(actual, greaterThanOrEqualTo(lBoundrary));
- Assert.assertThat(actual, lessThanOrEqualTo(hBoundrary));
+ assertThat(actual, greaterThanOrEqualTo(lBoundrary));
+ assertThat(actual, lessThanOrEqualTo(hBoundrary));
}
private Request createReadRequest(long sessionId, int xid) {
- return new Request(null, sessionId, xid, ZooDefs.OpCode.getData,
- ByteBuffer.wrap(new byte[10]), null);
+ return new Request(null, sessionId, xid, ZooDefs.OpCode.getData, ByteBuffer.wrap(new byte[10]), null);
}
private Request createWriteRequest(long sessionId, int xid) {
- return new Request(null, sessionId, xid, ZooDefs.OpCode.setData,
- ByteBuffer.wrap(new byte[10]), null);
+ return new Request(null, sessionId, xid, ZooDefs.OpCode.setData, ByteBuffer.wrap(new byte[10]), null);
}
private void processRequestWithWait(Request request) throws Exception {
@@ -208,14 +215,14 @@ public class CommitProcessorMetricsTest extends ZKTestCase {
public void testRequestsInSessionQueue() throws Exception {
setupProcessors(0, 0);
- Request req1 = createWriteRequest(1l, 1);
+ Request req1 = createWriteRequest(1L, 1);
processRequestWithWait(req1);
checkMetrics("requests_in_session_queue", 1L, 1L, 1D, 1L, 1L);
//these two read requests will be stuck in the session queue because there is write in front of them
processRequestWithWait(createReadRequest(1L, 2));
- processRequestWithWait(createReadRequest(1L,3));
+ processRequestWithWait(createReadRequest(1L, 3));
checkMetrics("requests_in_session_queue", 1L, 3L, 2D, 3L, 6);
@@ -228,18 +235,18 @@ public class CommitProcessorMetricsTest extends ZKTestCase {
public void testWriteFinalProcTime() throws Exception {
setupProcessors(0, 1000);
- Request req1 = createWriteRequest(1l, 2);
+ Request req1 = createWriteRequest(1L, 2);
processRequestWithWait(req1);
//no request sent to next processor yet
Map<String, Object> values = MetricsUtils.currentServerMetrics();
- Assert.assertEquals(0L, values.get("cnt_write_final_proc_time_ms"));
+ assertEquals(0L, values.get("cnt_write_final_proc_time_ms"));
commitWithWait(req1);
values = MetricsUtils.currentServerMetrics();
- Assert.assertEquals(1L, values.get("cnt_write_final_proc_time_ms"));
- checkTimeMetric((long)values.get("max_write_final_proc_time_ms"), 1000L, 2000L);
+ assertEquals(1L, values.get("cnt_write_final_proc_time_ms"));
+ checkTimeMetric((long) values.get("max_write_final_proc_time_ms"), 1000L, 2000L);
}
@Test
@@ -249,8 +256,8 @@ public class CommitProcessorMetricsTest extends ZKTestCase {
processRequestWithWait(createReadRequest(1L, 1));
Map<String, Object> values = MetricsUtils.currentServerMetrics();
- Assert.assertEquals(1L, values.get("cnt_read_final_proc_time_ms"));
- checkTimeMetric((long)values.get("max_read_final_proc_time_ms"), 1000L, 2000L);
+ assertEquals(1L, values.get("cnt_read_final_proc_time_ms"));
+ checkTimeMetric((long) values.get("max_read_final_proc_time_ms"), 1000L, 2000L);
}
@Test
@@ -259,8 +266,8 @@ public class CommitProcessorMetricsTest extends ZKTestCase {
processRequestWithWait(createReadRequest(1L, 1));
Map<String, Object> values = MetricsUtils.currentServerMetrics();
- Assert.assertEquals(1L, values.get("cnt_commit_process_time"));
- checkTimeMetric((long)values.get("max_commit_process_time"), 0L, 1000L);
+ assertEquals(1L, values.get("cnt_commit_process_time"));
+ checkTimeMetric((long) values.get("max_commit_process_time"), 0L, 1000L);
}
@Test
@@ -270,23 +277,23 @@ public class CommitProcessorMetricsTest extends ZKTestCase {
commitWithWait(createWriteRequest(1L, 1));
Map<String, Object> values = MetricsUtils.currentServerMetrics();
- Assert.assertEquals(1L, values.get("cnt_server_write_committed_time_ms"));
- checkTimeMetric((long)values.get("max_server_write_committed_time_ms"), 0L, 1000L);
+ assertEquals(1L, values.get("cnt_server_write_committed_time_ms"));
+ checkTimeMetric((long) values.get("max_server_write_committed_time_ms"), 0L, 1000L);
}
@Test
public void testLocalWriteCommittedTime() throws Exception {
setupProcessors(0, 0);
- Request req1 = createWriteRequest(1l, 2);
+ Request req1 = createWriteRequest(1L, 2);
processRequestWithWait(req1);
commitWithWait(req1);
Map<String, Object> values = MetricsUtils.currentServerMetrics();
- Assert.assertEquals(1L, values.get("cnt_local_write_committed_time_ms"));
- checkTimeMetric((long)values.get("max_local_write_committed_time_ms"), 0l, 1000l);
+ assertEquals(1L, values.get("cnt_local_write_committed_time_ms"));
+ checkTimeMetric((long) values.get("max_local_write_committed_time_ms"), 0L, 1000L);
- Request req2 = createWriteRequest(1l, 2);
+ Request req2 = createWriteRequest(1L, 2);
processRequestWithWait(req2);
//the second write will be stuck in the session queue for at least one second
//but the LOCAL_WRITE_COMMITTED_TIME is from when the commit is received
@@ -295,24 +302,23 @@ public class CommitProcessorMetricsTest extends ZKTestCase {
commitWithWait(req2);
values = MetricsUtils.currentServerMetrics();
- Assert.assertEquals(2L, values.get("cnt_local_write_committed_time_ms"));
- checkTimeMetric((long)values.get("max_local_write_committed_time_ms"), 0L, 1000L);
+ assertEquals(2L, values.get("cnt_local_write_committed_time_ms"));
+ checkTimeMetric((long) values.get("max_local_write_committed_time_ms"), 0L, 1000L);
}
-
@Test
public void testWriteCommitProcTime() throws Exception {
setupProcessors(0, 0);
- Request req1 = createWriteRequest(1l, 2);
+ Request req1 = createWriteRequest(1L, 2);
processRequestWithWait(req1);
commitWithWait(req1);
Map<String, Object> values = MetricsUtils.currentServerMetrics();
- Assert.assertEquals(1L, values.get("cnt_write_commitproc_time_ms"));
- checkTimeMetric((long)values.get("max_write_commitproc_time_ms"), 0l, 1000l);
+ assertEquals(1L, values.get("cnt_write_commitproc_time_ms"));
+ checkTimeMetric((long) values.get("max_write_commitproc_time_ms"), 0L, 1000L);
- Request req2 = createWriteRequest(1l, 2);
+ Request req2 = createWriteRequest(1L, 2);
processRequestWithWait(req2);
//the second write will be stuck in the session queue for at least one second
Thread.sleep(1000);
@@ -320,57 +326,54 @@ public class CommitProcessorMetricsTest extends ZKTestCase {
commitWithWait(req2);
values = MetricsUtils.currentServerMetrics();
- Assert.assertEquals(2L, values.get("cnt_write_commitproc_time_ms"));
- checkTimeMetric((long)values.get("max_write_commitproc_time_ms"), 1000L, 2000L);
+ assertEquals(2L, values.get("cnt_write_commitproc_time_ms"));
+ checkTimeMetric((long) values.get("max_write_commitproc_time_ms"), 1000L, 2000L);
}
-
@Test
public void testReadCommitProcTime() throws Exception {
setupProcessors(0, 0);
- processRequestWithWait(createReadRequest(1l, 1));
+ processRequestWithWait(createReadRequest(1L, 1));
Map<String, Object> values = MetricsUtils.currentServerMetrics();
- Assert.assertEquals(1L, values.get("cnt_read_commitproc_time_ms"));
- checkTimeMetric((long)values.get("max_read_commitproc_time_ms"), 0l, 1000l);
+ assertEquals(1L, values.get("cnt_read_commitproc_time_ms"));
+ checkTimeMetric((long) values.get("max_read_commitproc_time_ms"), 0L, 1000L);
- Request req1 = createWriteRequest(1l, 2);
+ Request req1 = createWriteRequest(1L, 2);
processRequestWithWait(req1);
- processRequestWithWait(createReadRequest(1l, 3));
+ processRequestWithWait(createReadRequest(1L, 3));
//the second read will be stuck in the session queue for at least one second
Thread.sleep(1000);
commitWithWait(req1);
values = MetricsUtils.currentServerMetrics();
- Assert.assertEquals(2L, values.get("cnt_read_commitproc_time_ms"));
- checkTimeMetric((long)values.get("max_read_commitproc_time_ms"), 1000L, 2000L);
+ assertEquals(2L, values.get("cnt_read_commitproc_time_ms"));
+ checkTimeMetric((long) values.get("max_read_commitproc_time_ms"), 1000L, 2000L);
}
-
@Test
public void testTimeWaitingEmptyPoolInCommitProcessorRead() throws Exception {
setupProcessors(1, 1000);
//three read requests will be scheduled first
requestScheduled = new CountDownLatch(3);
- commitProcessor.processRequest(createReadRequest(0l, 2));
- commitProcessor.processRequest(createReadRequest(1l, 3));
- commitProcessor.processRequest(createReadRequest(2l, 4));
+ commitProcessor.processRequest(createReadRequest(0L, 2));
+ commitProcessor.processRequest(createReadRequest(1L, 3));
+ commitProcessor.processRequest(createReadRequest(2L, 4));
requestScheduled.await(5, TimeUnit.SECONDS);
//add a commit request to trigger waitForEmptyPool
poolEmpytied = new CountDownLatch(1);
- commitProcessor.commit(createWriteRequest(1l, 1));
+ commitProcessor.commit(createWriteRequest(1L, 1));
poolEmpytied.await(5, TimeUnit.SECONDS);
- long actual = (long)MetricsUtils.currentServerMetrics().get("max_time_waiting_empty_pool_in_commit_processor_read_ms");
+ long actual = (long) MetricsUtils.currentServerMetrics().get("max_time_waiting_empty_pool_in_commit_processor_read_ms");
//since each request takes 1000ms to process, so the waiting shouldn't be more than three times of that
checkTimeMetric(actual, 2500L, 3500L);
}
-
@Test
public void testConcurrentRequestProcessingInCommitProcessor() throws Exception {
setupProcessors(3, 1000);
@@ -378,102 +381,100 @@ public class CommitProcessorMetricsTest extends ZKTestCase {
//three read requests will be processed in parallel
commitSeen = new CountDownLatch(1);
requestScheduled = new CountDownLatch(3);
- commitProcessor.processRequest(createReadRequest(1l, 2));
- commitProcessor.processRequest(createReadRequest(1l, 3));
- commitProcessor.processRequest(createReadRequest(1l, 4));
+ commitProcessor.processRequest(createReadRequest(1L, 2));
+ commitProcessor.processRequest(createReadRequest(1L, 3));
+ commitProcessor.processRequest(createReadRequest(1L, 4));
requestScheduled.await(5, TimeUnit.SECONDS);
//add a commit request to trigger waitForEmptyPool, which will record number of requests being proccessed
poolEmpytied = new CountDownLatch(1);
- commitProcessor.commit(createWriteRequest(1l, 1));
+ commitProcessor.commit(createWriteRequest(1L, 1));
poolEmpytied.await(5, TimeUnit.SECONDS);
//this will change after we upstream batch write in CommitProcessor
Map<String, Object> values = MetricsUtils.currentServerMetrics();
- Assert.assertEquals(3L, values.get("max_concurrent_request_processing_in_commit_processor"));
+ assertEquals(3L, values.get("max_concurrent_request_processing_in_commit_processor"));
}
@Test
public void testReadsAfterWriteInSessionQueue() throws Exception {
setupProcessors(0, 0);
//this read request is before write
- processRequestWithWait(createReadRequest(1l, 1));
+ processRequestWithWait(createReadRequest(1L, 1));
//one write request
- Request req1 = createWriteRequest(1l, 1);
+ Request req1 = createWriteRequest(1L, 1);
processRequestWithWait(req1);
-
//three read requests after the write
- processRequestWithWait(createReadRequest(1l, 2));
- processRequestWithWait(createReadRequest(1l, 3));
- processRequestWithWait(createReadRequest(1l, 4));
+ processRequestWithWait(createReadRequest(1L, 2));
+ processRequestWithWait(createReadRequest(1L, 3));
+ processRequestWithWait(createReadRequest(1L, 4));
//commit the write
commitWithWait(req1);
- checkMetrics("reads_after_write_in_session_queue", 3l, 3l, 3d, 1, 3);
+ checkMetrics("reads_after_write_in_session_queue", 3L, 3L, 3d, 1, 3);
}
-
@Test
public void testReadsQueuedInCommitProcessor() throws Exception {
setupProcessors(0, 0);
- processRequestWithWait(createReadRequest(1l, 1));
- processRequestWithWait(createReadRequest(1l, 2));
+ processRequestWithWait(createReadRequest(1L, 1));
+ processRequestWithWait(createReadRequest(1L, 2));
//recorded reads in the queue are 1, 1
- checkMetrics("read_commit_proc_req_queued", 1l, 1l, 1d, 2, 2);
+ checkMetrics("read_commit_proc_req_queued", 1L, 1L, 1d, 2, 2);
}
@Test
public void testWritesQueuedInCommitProcessor() throws Exception {
setupProcessors(0, 0);
- Request req1 = createWriteRequest(1l, 1);
+ Request req1 = createWriteRequest(1L, 1);
processRequestWithWait(req1);
- Request req2 = createWriteRequest(1l, 2);
+ Request req2 = createWriteRequest(1L, 2);
processRequestWithWait(req2);
//since we haven't got any commit request, the write request stays in the queue
//recorded writes in the queue are 1, 2
- checkMetrics("write_commit_proc_req_queued", 1l, 2l, 1.5d, 2, 3);
+ checkMetrics("write_commit_proc_req_queued", 1L, 2L, 1.5d, 2, 3);
commitWithWait(req1);
//recording is done before commit request is processed, so writes in the queue are: 1, 2, 2
- checkMetrics("write_commit_proc_req_queued", 1l, 2l, 1.6667d, 3, 5);
+ checkMetrics("write_commit_proc_req_queued", 1L, 2L, 1.6667d, 3, 5);
commitWithWait(req2);
//writes in the queue are 1, 2, 2, 1
- checkMetrics("write_commit_proc_req_queued", 1l, 2l, 1.5d, 4, 6);
+ checkMetrics("write_commit_proc_req_queued", 1L, 2L, 1.5d, 4, 6);
//send a read request to trigger the recording, this time the write queue should be empty
//writes in the queue are 1, 2, 2, 1, 0
- processRequestWithWait(createReadRequest(1l, 1));
+ processRequestWithWait(createReadRequest(1L, 1));
- checkMetrics("write_commit_proc_req_queued", 0l, 2l, 1.2d, 5, 6);
+ checkMetrics("write_commit_proc_req_queued", 0L, 2L, 1.2d, 5, 6);
}
@Test
public void testCommitsQueuedInCommitProcessor() throws Exception {
setupProcessors(0, 0);
- commitWithWait(createWriteRequest(1l, 1));
- commitWithWait(createWriteRequest(1l, 2));
+ commitWithWait(createWriteRequest(1L, 1));
+ commitWithWait(createWriteRequest(1L, 2));
//recorded commits in the queue are 1, 1
- checkMetrics("commit_commit_proc_req_queued", 1l, 1l, 1d, 2, 2);
+ checkMetrics("commit_commit_proc_req_queued", 1L, 1L, 1d, 2, 2);
}
@Test
public void testCommitsQueued() throws Exception {
setupProcessors(0, 0);
- commitWithWait(createWriteRequest(1l, 1));
- commitWithWait(createWriteRequest(1l, 2));
+ commitWithWait(createWriteRequest(1L, 1));
+ commitWithWait(createWriteRequest(1L, 2));
Map<String, Object> values = MetricsUtils.currentServerMetrics();
- Assert.assertEquals(2l, (long)values.get("request_commit_queued"));
+ assertEquals(2L, (long) values.get("request_commit_queued"));
}
@Test
@@ -481,25 +482,26 @@ public class CommitProcessorMetricsTest extends ZKTestCase {
setupProcessors(0, 0);
//one write request for session 1
- Request req1 = createWriteRequest(1l, 1);
+ Request req1 = createWriteRequest(1L, 1);
processRequestWithWait(req1);
//two write requests for session 2
- Request req2 = createWriteRequest(2l, 2);
+ Request req2 = createWriteRequest(2L, 2);
processRequestWithWait(req2);
- Request req3 = createWriteRequest(2l, 3);
+ Request req3 = createWriteRequest(2L, 3);
processRequestWithWait(req3);
commitWithWait(req1);
//there are two sessions with pending requests
- checkMetrics("pending_session_queue_size", 2l, 2l, 2d, 1, 2);
+ checkMetrics("pending_session_queue_size", 2L, 2L, 2d, 1, 2);
commitWithWait(req2);
//there is on session with pending requests
- checkMetrics("pending_session_queue_size", 1l, 2l, 1.5d, 2, 3);
+ checkMetrics("pending_session_queue_size", 1L, 2L, 1.5d, 2, 3);
commitWithWait(req3);
//there is one session with pending requests
- checkMetrics("pending_session_queue_size", 1l, 2l, 1.333d, 3, 4);
+ checkMetrics("pending_session_queue_size", 1L, 2L, 1.333d, 3, 4);
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/CommitProcessorTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/CommitProcessorTest.java
index c6ee230ac..ae439db08 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/CommitProcessorTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/CommitProcessorTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,6 +18,9 @@
package org.apache.zookeeper.server.quorum;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
@@ -28,7 +31,6 @@ import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
-
import org.apache.jute.BinaryOutputArchive;
import org.apache.zookeeper.ZKTestCase;
import org.apache.zookeeper.ZooDefs.Ids;
@@ -43,7 +45,6 @@ import org.apache.zookeeper.server.RequestProcessor;
import org.apache.zookeeper.server.ZooKeeperServer;
import org.apache.zookeeper.test.ClientBase;
import org.junit.After;
-import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -68,8 +69,8 @@ import org.slf4j.LoggerFactory;
* 4. No in-flight write requests while processing a read request.
*/
public class CommitProcessorTest extends ZKTestCase {
- protected static final Logger LOG =
- LoggerFactory.getLogger(CommitProcessorTest.class);
+
+ protected static final Logger LOG = LoggerFactory.getLogger(CommitProcessorTest.class);
// The amount of ms each test case should run
static final int TEST_RUN_TIME_IN_MS = 5000;
@@ -79,43 +80,40 @@ public class CommitProcessorTest extends ZKTestCase {
boolean stopped;
TestZooKeeperServer zks;
File tmpDir;
- ArrayList<TestClientThread> testClients =
- new ArrayList<TestClientThread>();
+ ArrayList<TestClientThread> testClients = new ArrayList<TestClientThread>();
CommitProcessor commitProcessor;
- public void setUp(int numCommitThreads, int numClientThreads, int writePercent)
- throws Exception {
+ public void setUp(int numCommitThreads, int numClientThreads, int writePercent) throws Exception {
stopped = false;
- System.setProperty(
- CommitProcessor.ZOOKEEPER_COMMIT_PROC_NUM_WORKER_THREADS,
- Integer.toString(numCommitThreads));
+ System.setProperty(CommitProcessor.ZOOKEEPER_COMMIT_PROC_NUM_WORKER_THREADS, Integer.toString(numCommitThreads));
tmpDir = ClientBase.createTmpDir();
ClientBase.setupTestEnv();
zks = new TestZooKeeperServer(tmpDir, tmpDir, 4000);
zks.startup();
- for(int i=0; i<numClientThreads; ++i) {
+ for (int i = 0; i < numClientThreads; ++i) {
TestClientThread client = new TestClientThread(writePercent);
testClients.add(client);
client.start();
}
}
-
- public void setUp(int numCommitThreads, int numReadOnlyClientThreads, int mixWorkloadClientThreads, int writePercent)
- throws Exception {
+
+ public void setUp(
+ int numCommitThreads,
+ int numReadOnlyClientThreads,
+ int mixWorkloadClientThreads,
+ int writePercent) throws Exception {
stopped = false;
- System.setProperty(
- CommitProcessor.ZOOKEEPER_COMMIT_PROC_NUM_WORKER_THREADS,
- Integer.toString(numCommitThreads));
+ System.setProperty(CommitProcessor.ZOOKEEPER_COMMIT_PROC_NUM_WORKER_THREADS, Integer.toString(numCommitThreads));
tmpDir = ClientBase.createTmpDir();
ClientBase.setupTestEnv();
zks = new TestZooKeeperServer(tmpDir, tmpDir, 4000);
zks.startup();
- for(int i=0; i<mixWorkloadClientThreads; ++i) {
+ for (int i = 0; i < mixWorkloadClientThreads; ++i) {
TestClientThread client = new TestClientThread(writePercent);
testClients.add(client);
client.start();
}
- for(int i=0; i<numReadOnlyClientThreads; ++i) {
+ for (int i = 0; i < numReadOnlyClientThreads; ++i) {
TestClientThread client = new TestClientThread(0);
testClients.add(client);
client.start();
@@ -128,13 +126,12 @@ public class CommitProcessorTest extends ZKTestCase {
stopped = true;
zks.shutdown();
- for(TestClientThread client : testClients) {
+ for (TestClientThread client : testClients) {
client.interrupt();
client.join();
}
if (tmpDir != null) {
- Assert.assertTrue("delete " + tmpDir.toString(),
- ClientBase.recursiveDelete(tmpDir));
+ assertTrue("delete " + tmpDir.toString(), ClientBase.recursiveDelete(tmpDir));
}
processedReadRequests.set(0);
processedWriteRequests.set(0);
@@ -143,6 +140,7 @@ public class CommitProcessorTest extends ZKTestCase {
}
private class TestClientThread extends Thread {
+
long sessionId;
int cxid;
int nodeId;
@@ -156,13 +154,13 @@ public class CommitProcessorTest extends ZKTestCase {
public void sendWriteRequest() throws Exception {
ByteArrayOutputStream boas = new ByteArrayOutputStream();
BinaryOutputArchive boa = BinaryOutputArchive.getArchive(boas);
- CreateRequest createReq = new CreateRequest(
- "/session" + Long.toHexString(sessionId) + "-" + (++nodeId),
- new byte[0], Ids.OPEN_ACL_UNSAFE, 1);
+ CreateRequest createReq = new CreateRequest("/session"
+ + Long.toHexString(sessionId)
+ + "-"
+ + (++nodeId), new byte[0], Ids.OPEN_ACL_UNSAFE, 1);
createReq.serialize(boa, "request");
ByteBuffer bb = ByteBuffer.wrap(boas.toByteArray());
- Request req = new Request(null, sessionId, ++cxid, OpCode.create,
- bb, new ArrayList<Id>());
+ Request req = new Request(null, sessionId, ++cxid, OpCode.create, bb, new ArrayList<Id>());
zks.getFirstProcessor().processRequest(req);
}
@@ -170,12 +168,13 @@ public class CommitProcessorTest extends ZKTestCase {
public void sendReadRequest() throws Exception {
ByteArrayOutputStream boas = new ByteArrayOutputStream();
BinaryOutputArchive boa = BinaryOutputArchive.getArchive(boas);
- GetDataRequest getDataRequest = new GetDataRequest(
- "/session" + Long.toHexString(sessionId) + "-" + nodeId, false);
+ GetDataRequest getDataRequest = new GetDataRequest("/session"
+ + Long.toHexString(sessionId)
+ + "-"
+ + nodeId, false);
getDataRequest.serialize(boa, "request");
ByteBuffer bb = ByteBuffer.wrap(boas.toByteArray());
- Request req = new Request(null, sessionId, ++cxid, OpCode.getData,
- bb, new ArrayList<Id>());
+ Request req = new Request(null, sessionId, ++cxid, OpCode.getData, bb, new ArrayList<Id>());
zks.getFirstProcessor().processRequest(req);
}
@@ -183,7 +182,7 @@ public class CommitProcessorTest extends ZKTestCase {
Random rand = new Random(Thread.currentThread().getId());
try {
sendWriteRequest();
- while(!stopped) {
+ while (!stopped) {
if (rand.nextInt(100) < writePercent) {
sendWriteRequest();
} else {
@@ -195,6 +194,7 @@ public class CommitProcessorTest extends ZKTestCase {
LOG.error("Uncaught exception in test: ", e);
}
}
+
}
@Test
@@ -205,12 +205,12 @@ public class CommitProcessorTest extends ZKTestCase {
synchronized (this) {
wait(TEST_RUN_TIME_IN_MS);
}
- Assert.assertFalse(fail);
- Assert.assertTrue("No read requests processed", processedReadRequests.get() > 0);
+ assertFalse(fail);
+ assertTrue("No read requests processed", processedReadRequests.get() > 0);
// processedWriteRequests.get() == numClients since each client performs one write at the beginning (creates a znode)
- Assert.assertTrue("Write requests processed", processedWriteRequests.get() == numClients);
+ assertTrue("Write requests processed", processedWriteRequests.get() == numClients);
}
-
+
@Test
public void testNoCommitWorkersMixedWorkload() throws Exception {
int numClients = 10;
@@ -219,10 +219,10 @@ public class CommitProcessorTest extends ZKTestCase {
synchronized (this) {
wait(TEST_RUN_TIME_IN_MS);
}
- Assert.assertFalse(fail);
+ assertFalse(fail);
checkProcessedRequest();
}
-
+
@Test
public void testOneCommitWorkerReadOnlyWorkload() throws Exception {
int numClients = 10;
@@ -231,68 +231,67 @@ public class CommitProcessorTest extends ZKTestCase {
synchronized (this) {
wait(TEST_RUN_TIME_IN_MS);
}
- Assert.assertFalse(fail);
- Assert.assertTrue("No read requests processed", processedReadRequests.get() > 0);
+ assertFalse(fail);
+ assertTrue("No read requests processed", processedReadRequests.get() > 0);
// processedWriteRequests.get() == numClients since each client performs one write at the beginning (creates a znode)
- Assert.assertTrue("Write requests processed", processedWriteRequests.get() == numClients);
+ assertTrue("Write requests processed", processedWriteRequests.get() == numClients);
}
@Test
public void testOneCommitWorkerMixedWorkload() throws Exception {
setUp(1, 10, 25);
LOG.info("testOneCommitWorkerMixedWorkload 25w/75r workload test");
- synchronized(this) {
+ synchronized (this) {
wait(TEST_RUN_TIME_IN_MS);
}
- Assert.assertFalse(fail);
+ assertFalse(fail);
checkProcessedRequest();
}
-
-
+
@Test
public void testManyCommitWorkersReadOnly() throws Exception {
int numClients = 10;
LOG.info("testManyCommitWorkersReadOnly");
setUp(10, numClients, 0);
- synchronized(this) {
+ synchronized (this) {
wait(TEST_RUN_TIME_IN_MS);
}
- Assert.assertFalse(fail);
- Assert.assertTrue("No read requests processed", processedReadRequests.get() > 0);
+ assertFalse(fail);
+ assertTrue("No read requests processed", processedReadRequests.get() > 0);
// processedWriteRequests.get() == numClients since each client performs one write at the beginning (creates a znode)
- Assert.assertTrue("Write requests processed", processedWriteRequests.get() == numClients);
+ assertTrue("Write requests processed", processedWriteRequests.get() == numClients);
}
-
+
@Test
public void testManyCommitWorkersMixedWorkload() throws Exception {
- setUp(16, 8 , 8, 25);
+ setUp(16, 8, 8, 25);
LOG.info("testManyCommitWorkersMixedWorkload 8X0w/100r + 8X25w/75r workload test");
- synchronized(this) {
+ synchronized (this) {
wait(TEST_RUN_TIME_IN_MS);
}
- Assert.assertFalse(fail);
+ assertFalse(fail);
checkProcessedRequest();
}
private void checkProcessedRequest() {
- Assert.assertTrue("No read requests processed", processedReadRequests.get() > 0);
- Assert.assertTrue("No write requests processed", processedWriteRequests.get() > 0);
+ assertTrue("No read requests processed", processedReadRequests.get() > 0);
+ assertTrue("No write requests processed", processedWriteRequests.get() > 0);
}
volatile boolean fail = false;
- synchronized private void failTest(String reason) {
+ private synchronized void failTest(String reason) {
fail = true;
notifyAll();
- Assert.fail(reason);
+ fail(reason);
}
private class TestZooKeeperServer extends ZooKeeperServer {
- public TestZooKeeperServer(File snapDir, File logDir, int tickTime)
- throws IOException {
+
+ public TestZooKeeperServer(File snapDir, File logDir, int tickTime) throws IOException {
super(snapDir, logDir, tickTime);
}
- public PrepRequestProcessor getFirstProcessor(){
+ public PrepRequestProcessor getFirstProcessor() {
return (PrepRequestProcessor) firstProcessor;
}
@@ -303,24 +302,22 @@ public class CommitProcessorTest extends ZKTestCase {
RequestProcessor finalProcessor = new FinalRequestProcessor(zks);
// ValidateProcessor is set up in a similar fashion to ToBeApplied
// processor, so it can do pre/post validating of requests
- ValidateProcessor validateProcessor =
- new ValidateProcessor(finalProcessor);
+ ValidateProcessor validateProcessor = new ValidateProcessor(finalProcessor);
commitProcessor = new CommitProcessor(validateProcessor, "1", true, null);
validateProcessor.setCommitProcessor(commitProcessor);
commitProcessor.start();
- MockProposalRequestProcessor proposalProcessor =
- new MockProposalRequestProcessor(commitProcessor);
+ MockProposalRequestProcessor proposalProcessor = new MockProposalRequestProcessor(commitProcessor);
proposalProcessor.start();
firstProcessor = new PrepRequestProcessor(zks, proposalProcessor);
getFirstProcessor().start();
}
+
}
-
- private class MockProposalRequestProcessor extends Thread
- implements RequestProcessor {
+
+ private class MockProposalRequestProcessor extends Thread implements RequestProcessor {
+
private final CommitProcessor commitProcessor;
- private final LinkedBlockingQueue<Request> proposals =
- new LinkedBlockingQueue<Request>();
+ private final LinkedBlockingQueue<Request> proposals = new LinkedBlockingQueue<Request>();
public MockProposalRequestProcessor(CommitProcessor commitProcessor) {
this.commitProcessor = commitProcessor;
@@ -330,9 +327,9 @@ public class CommitProcessorTest extends ZKTestCase {
public void run() {
Random rand = new Random(Thread.currentThread().getId());
try {
- while(true) {
+ while (true) {
// If it is a read-only test, there will be no proposals..
- if (!proposals.isEmpty()){
+ if (!proposals.isEmpty()) {
Request request = proposals.take();
Thread.sleep(5 + rand.nextInt(95));
commitProcessor.commit(request);
@@ -344,8 +341,7 @@ public class CommitProcessorTest extends ZKTestCase {
}
@Override
- public void processRequest(Request request)
- throws RequestProcessorException {
+ public void processRequest(Request request) throws RequestProcessorException {
commitProcessor.processRequest(request);
if (request.getHdr() != null) {
// fake propose request
@@ -361,16 +357,16 @@ public class CommitProcessorTest extends ZKTestCase {
commitProcessor.shutdown();
}
}
+
}
-
private class ValidateProcessor implements RequestProcessor {
+
Random rand = new Random(Thread.currentThread().getId());
RequestProcessor nextProcessor;
CommitProcessor commitProcessor;
AtomicLong expectedZxid = new AtomicLong(1);
- ConcurrentHashMap<Long, AtomicInteger> cxidMap =
- new ConcurrentHashMap<Long, AtomicInteger>();
+ ConcurrentHashMap<Long, AtomicInteger> cxidMap = new ConcurrentHashMap<Long, AtomicInteger>();
AtomicInteger outstandingReadRequests = new AtomicInteger(0);
AtomicInteger outstandingWriteRequests = new AtomicInteger(0);
@@ -383,13 +379,12 @@ public class CommitProcessorTest extends ZKTestCase {
this.commitProcessor = commitProcessor;
}
-
@Override
- public void processRequest(Request request)
- throws RequestProcessorException {
- if (stopped)
+ public void processRequest(Request request) throws RequestProcessorException {
+ if (stopped) {
return;
- if (request.type == OpCode.closeSession){
+ }
+ if (request.type == OpCode.closeSession) {
LOG.debug("ValidateProcessor got closeSession request=" + request);
nextProcessor.processRequest(request);
return;
@@ -399,19 +394,20 @@ public class CommitProcessorTest extends ZKTestCase {
if (isWriteRequest) {
outstandingWriteRequests.incrementAndGet();
validateWriteRequestVariant(request);
- LOG.debug("Starting write request zxid=" + request.zxid);
+ LOG.debug("Starting write request zxid={}", request.zxid);
} else {
- LOG.debug("Starting read request cxid="
- + request.cxid + " for session 0x"
- + Long.toHexString(request.sessionId));
+ LOG.debug(
+ "Starting read request cxid={} for session 0x{}",
+ request.cxid,
+ Long.toHexString(request.sessionId));
outstandingReadRequests.incrementAndGet();
validateReadRequestVariant(request);
}
-
+
// Insert random delay to test thread race conditions
try {
Thread.sleep(5 + rand.nextInt(25));
- } catch(InterruptedException e) {
+ } catch (InterruptedException e) {
// ignore
}
nextProcessor.processRequest(request);
@@ -422,13 +418,14 @@ public class CommitProcessorTest extends ZKTestCase {
*/
if (isWriteRequest) {
outstandingWriteRequests.decrementAndGet();
- LOG.debug("Done write request zxid=" + request.zxid);
+ LOG.debug("Done write request zxid={}", request.zxid);
processedWriteRequests.incrementAndGet();
} else {
outstandingReadRequests.decrementAndGet();
- LOG.debug("Done read request cxid="
- + request.cxid + " for session 0x"
- + Long.toHexString(request.sessionId));
+ LOG.debug(
+ "Done read request cxid={} for session 0x{}",
+ request.cxid,
+ Long.toHexString(request.sessionId));
processedReadRequests.incrementAndGet();
}
validateRequest(request);
@@ -438,20 +435,20 @@ public class CommitProcessorTest extends ZKTestCase {
* Validate that this is the only request in the pipeline
*/
private void validateWriteRequestVariant(Request request) {
- if (stopped)
+ if (stopped) {
return;
+ }
long zxid = request.getHdr().getZxid();
int readRequests = outstandingReadRequests.get();
if (readRequests != 0) {
failTest("There are " + readRequests + " outstanding"
- + " read requests while issuing a write request zxid="
- + zxid);
+ + " read requests while issuing a write request zxid=" + zxid);
}
int writeRequests = outstandingWriteRequests.get();
if (writeRequests > 1) {
failTest("There are " + writeRequests + " outstanding"
- + " write requests while issuing a write request zxid="
- + zxid + " (expected one)");
+ + " write requests while issuing a write request zxid=" + zxid
+ + " (expected one)");
}
}
@@ -463,9 +460,8 @@ public class CommitProcessorTest extends ZKTestCase {
int writeRequests = outstandingWriteRequests.get();
if (writeRequests != 0) {
failTest("There are " + writeRequests + " outstanding"
- + " write requests while issuing a read request cxid="
- + request.cxid + " for session 0x"
- + Long.toHexString(request.sessionId));
+ + " write requests while issuing a read request cxid=" + request.cxid
+ + " for session 0x" + Long.toHexString(request.sessionId));
}
}
@@ -478,8 +474,7 @@ public class CommitProcessorTest extends ZKTestCase {
if (request.getHdr() != null) {
long zxid = request.getHdr().getZxid();
if (!expectedZxid.compareAndSet(zxid, zxid + 1)) {
- failTest("Write request, expected_zxid="
- + expectedZxid.get() + "; req_zxid=" + zxid);
+ failTest("Write request, expected_zxid=" + expectedZxid.get() + "; req_zxid=" + zxid);
}
}
@@ -487,19 +482,18 @@ public class CommitProcessorTest extends ZKTestCase {
AtomicInteger sessionCxid = cxidMap.get(request.sessionId);
if (sessionCxid == null) {
sessionCxid = new AtomicInteger(request.cxid + 1);
- AtomicInteger existingSessionCxid =
- cxidMap.putIfAbsent(request.sessionId, sessionCxid);
+ AtomicInteger existingSessionCxid = cxidMap.putIfAbsent(request.sessionId, sessionCxid);
if (existingSessionCxid != null) {
- failTest("Race condition adding cxid=" + request.cxid
+ failTest("Race condition adding cxid="
+ + request.cxid
+ " for session 0x"
+ Long.toHexString(request.sessionId)
- + " with other_cxid=" + existingSessionCxid.get());
+ + " with other_cxid="
+ + existingSessionCxid.get());
}
} else {
- if (!sessionCxid.compareAndSet(
- request.cxid, request.cxid + 1)) {
- failTest("Expected_cxid=" + sessionCxid.get()
- + "; req_cxid=" + request.cxid);
+ if (!sessionCxid.compareAndSet(request.cxid, request.cxid + 1)) {
+ failTest("Expected_cxid=" + sessionCxid.get() + "; req_cxid=" + request.cxid);
}
}
}
@@ -509,9 +503,11 @@ public class CommitProcessorTest extends ZKTestCase {
LOG.info("shutdown validateReadRequestVariant");
cxidMap.clear();
expectedZxid = new AtomicLong(1);
- if (nextProcessor!=null){
+ if (nextProcessor != null) {
nextProcessor.shutdown();
}
}
+
}
-} \ No newline at end of file
+
+}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/DelayRequestProcessor.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/DelayRequestProcessor.java
index aeb4e0fee..c092c6cd6 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/DelayRequestProcessor.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/DelayRequestProcessor.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,11 +18,10 @@
package org.apache.zookeeper.server.quorum;
+import java.util.concurrent.LinkedBlockingQueue;
import org.apache.zookeeper.server.Request;
import org.apache.zookeeper.server.RequestProcessor;
-import java.util.concurrent.LinkedBlockingQueue;
-
/**
* Allows the blocking of the request processor queue on a ZooKeeperServer.
*
@@ -74,4 +73,5 @@ public class DelayRequestProcessor implements RequestProcessor {
zooKeeperServer.commitProcessor.nextProcessor = delayRequestProcessor;
return delayRequestProcessor;
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/EagerACLFilterTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/EagerACLFilterTest.java
index 0c869a234..fa18bf0e2 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/EagerACLFilterTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/EagerACLFilterTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,10 +18,12 @@
package org.apache.zookeeper.server.quorum;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotSame;
+import static org.junit.Assert.fail;
import java.util.Arrays;
import java.util.Collection;
import java.util.concurrent.CountDownLatch;
-
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.TestableZooKeeper;
@@ -30,7 +32,6 @@ import org.apache.zookeeper.server.ZooKeeperServer;
import org.apache.zookeeper.server.quorum.QuorumPeer.ServerState;
import org.apache.zookeeper.test.QuorumBase;
import org.junit.After;
-import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -38,16 +39,17 @@ import org.junit.runners.Parameterized;
@RunWith(Parameterized.class)
public class EagerACLFilterTest extends QuorumBase {
+
protected boolean checkEnabled;
protected ServerState serverState;
protected final CountDownLatch callComplete = new CountDownLatch(1);
protected boolean complete = false;
- protected final static String PARENT_PATH = "/foo";
- protected final static String CHILD_PATH = "/foo/bar";
- protected final static String AUTH_PROVIDER = "digest";
- protected final static byte[] AUTH = "hello".getBytes();
- protected final static byte[] AUTHB = "goodbye".getBytes();
- protected final static byte[] DATA = "Hint Water".getBytes();
+ protected static final String PARENT_PATH = "/foo";
+ protected static final String CHILD_PATH = "/foo/bar";
+ protected static final String AUTH_PROVIDER = "digest";
+ protected static final byte[] AUTH = "hello".getBytes();
+ protected static final byte[] AUTHB = "goodbye".getBytes();
+ protected static final byte[] DATA = "Hint Water".getBytes();
protected TestableZooKeeper zkClient;
protected TestableZooKeeper zkClientB;
protected QuorumPeer zkLeader;
@@ -55,14 +57,7 @@ public class EagerACLFilterTest extends QuorumBase {
@Parameterized.Parameters
public static Collection<Object[]> data() {
- return Arrays.asList(
- new Object[][] {
- {ServerState.LEADING, true},
- {ServerState.LEADING, false},
- {ServerState.FOLLOWING, true},
- {ServerState.FOLLOWING, false},
- {ServerState.OBSERVING, true},
- {ServerState.OBSERVING, false}});
+ return Arrays.asList(new Object[][]{{ServerState.LEADING, true}, {ServerState.LEADING, false}, {ServerState.FOLLOWING, true}, {ServerState.FOLLOWING, false}, {ServerState.OBSERVING, true}, {ServerState.OBSERVING, false}});
}
public EagerACLFilterTest(ServerState state, boolean checkEnabled) {
@@ -113,17 +108,11 @@ public class EagerACLFilterTest extends QuorumBase {
}
private void assertTransactionState(String condition, long lastxid) {
- String assertion =
- String.format(
- "Server State: %s Check Enabled: %s %s",
- serverState,
- checkEnabled,
- condition);
+ String assertion = String.format("Server State: %s Check Enabled: %s %s", serverState, checkEnabled, condition);
if (checkEnabled) {
- Assert.assertEquals(assertion, lastxid, zkLeader.getLastLoggedZxid());
- }
- else {
- Assert.assertNotSame(assertion, lastxid, zkLeader.getLastLoggedZxid());
+ assertEquals(assertion, lastxid, zkLeader.getLastLoggedZxid());
+ } else {
+ assertNotSame(assertion, lastxid, zkLeader.getLastLoggedZxid());
}
}
@@ -133,9 +122,7 @@ public class EagerACLFilterTest extends QuorumBase {
zkClient.create(PARENT_PATH, DATA, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
zkClientB.create(CHILD_PATH, DATA, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
- Assert.assertEquals("OutstandingRequests not decremented",
- 0,
- connectedServer.getInProcess());
+ assertEquals("OutstandingRequests not decremented", 0, connectedServer.getInProcess());
}
@Test
@@ -143,9 +130,7 @@ public class EagerACLFilterTest extends QuorumBase {
zkClient.create(PARENT_PATH, DATA, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT, null);
zkClientB.create(CHILD_PATH, DATA, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT, null);
- Assert.assertEquals("OutstandingRequests not decremented",
- 0,
- connectedServer.getInProcess());
+ assertEquals("OutstandingRequests not decremented", 0, connectedServer.getInProcess());
}
@Test
@@ -154,12 +139,10 @@ public class EagerACLFilterTest extends QuorumBase {
long lastxid = zkLeader.getLastLoggedZxid();
try {
zkClientB.create(CHILD_PATH, DATA, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
+ } catch (KeeperException.NoAuthException e) {
}
- catch (KeeperException.NoAuthException e) {}
- Assert.assertEquals("OutstandingRequests not decremented",
- 0,
- connectedServer.getInProcess());
+ assertEquals("OutstandingRequests not decremented", 0, connectedServer.getInProcess());
assertTransactionState("Transaction state on Leader after failed create", lastxid);
}
@@ -170,12 +153,10 @@ public class EagerACLFilterTest extends QuorumBase {
long lastxid = zkLeader.getLastLoggedZxid();
try {
zkClientB.create(CHILD_PATH, DATA, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT, null);
+ } catch (KeeperException.NoAuthException e) {
}
- catch (KeeperException.NoAuthException e) {}
- Assert.assertEquals("OutstandingRequests not decremented",
- 0,
- connectedServer.getInProcess());
+ assertEquals("OutstandingRequests not decremented", 0, connectedServer.getInProcess());
assertTransactionState("Transaction state on Leader after failed create2", lastxid);
}
@@ -185,9 +166,7 @@ public class EagerACLFilterTest extends QuorumBase {
zkClient.create(PARENT_PATH, DATA, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
zkClientB.delete(PARENT_PATH, -1);
- Assert.assertEquals("OutstandingRequests not decremented",
- 0,
- connectedServer.getInProcess());
+ assertEquals("OutstandingRequests not decremented", 0, connectedServer.getInProcess());
}
@Test
@@ -197,12 +176,10 @@ public class EagerACLFilterTest extends QuorumBase {
long lastxid = zkLeader.getLastLoggedZxid();
try {
zkClientB.delete(CHILD_PATH, -1);
+ } catch (KeeperException.NoAuthException e) {
}
- catch (KeeperException.NoAuthException e) {}
- Assert.assertEquals("OutstandingRequests not decremented",
- 0,
- connectedServer.getInProcess());
+ assertEquals("OutstandingRequests not decremented", 0, connectedServer.getInProcess());
assertTransactionState("Transaction state on Leader after failed delete", lastxid);
}
@@ -219,12 +196,10 @@ public class EagerACLFilterTest extends QuorumBase {
long lastxid = zkLeader.getLastLoggedZxid();
try {
zkClientB.setData(PARENT_PATH, DATA, -1);
+ } catch (KeeperException.NoAuthException e) {
}
- catch (KeeperException.NoAuthException e) {}
- Assert.assertEquals("OutstandingRequests not decremented",
- 0,
- connectedServer.getInProcess());
+ assertEquals("OutstandingRequests not decremented", 0, connectedServer.getInProcess());
assertTransactionState("Transaction state on Leader after failed setData", lastxid);
}
@@ -234,9 +209,7 @@ public class EagerACLFilterTest extends QuorumBase {
zkClient.create(PARENT_PATH, null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT, null);
zkClientB.setACL(PARENT_PATH, Ids.READ_ACL_UNSAFE, -1);
- Assert.assertEquals("OutstandingRequests not decremented",
- 0,
- connectedServer.getInProcess());
+ assertEquals("OutstandingRequests not decremented", 0, connectedServer.getInProcess());
}
@Test
@@ -245,12 +218,10 @@ public class EagerACLFilterTest extends QuorumBase {
long lastxid = zkLeader.getLastLoggedZxid();
try {
zkClientB.setACL(PARENT_PATH, Ids.READ_ACL_UNSAFE, -1);
+ } catch (KeeperException.NoAuthException e) {
}
- catch (KeeperException.NoAuthException e) {}
- Assert.assertEquals("OutstandingRequests not decremented",
- 0,
- connectedServer.getInProcess());
+ assertEquals("OutstandingRequests not decremented", 0, connectedServer.getInProcess());
assertTransactionState("Transaction state on Leader after failed setACL", lastxid);
}
@@ -266,15 +237,14 @@ public class EagerACLFilterTest extends QuorumBase {
lastxid = zkLeader.getLastLoggedZxid();
try {
- zk.create("/acltest", new byte[0], Ids.CREATOR_ALL_ACL,
- CreateMode.PERSISTENT);
- Assert.fail("Should have received an invalid acl error");
- } catch (KeeperException.InvalidACLException e) {}
+ zk.create("/acltest", new byte[0], Ids.CREATOR_ALL_ACL, CreateMode.PERSISTENT);
+ fail("Should have received an invalid acl error");
+ } catch (KeeperException.InvalidACLException e) {
+ }
- Assert.assertEquals("OutstandingRequests not decremented",
- 0,
- connectedServer.getInProcess());
+ assertEquals("OutstandingRequests not decremented", 0, connectedServer.getInProcess());
assertTransactionState("zxid after invalid ACL", lastxid);
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/EphemeralNodeDeletionTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/EphemeralNodeDeletionTest.java
index 9546c25cc..749eb8047 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/EphemeralNodeDeletionTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/EphemeralNodeDeletionTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -15,18 +15,19 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
package org.apache.zookeeper.server.quorum;
import static org.apache.zookeeper.test.ClientBase.CONNECTION_TIMEOUT;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
-
+import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.net.SocketTimeoutException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
-
+import javax.security.sasl.SaslException;
import org.apache.zookeeper.AsyncCallback;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.PortAssignment;
@@ -38,12 +39,10 @@ import org.apache.zookeeper.server.quorum.QuorumPeer.ServerState;
import org.apache.zookeeper.test.ClientBase;
import org.apache.zookeeper.test.ClientBase.CountdownWatcher;
import org.junit.After;
-import org.junit.Assert;
import org.junit.Test;
-import javax.security.sasl.SaslException;
-
public class EphemeralNodeDeletionTest extends QuorumPeerTestBase {
+
private static int SERVER_COUNT = 3;
private MainThread[] mt = new MainThread[SERVER_COUNT];
@@ -55,22 +54,20 @@ public class EphemeralNodeDeletionTest extends QuorumPeerTestBase {
@Test(timeout = 120000)
public void testEphemeralNodeDeletion() throws Exception {
- final int clientPorts[] = new int[SERVER_COUNT];
+ final int[] clientPorts = new int[SERVER_COUNT];
StringBuilder sb = new StringBuilder();
String server;
for (int i = 0; i < SERVER_COUNT; i++) {
clientPorts[i] = PortAssignment.unique();
- server = "server." + i + "=127.0.0.1:" + PortAssignment.unique()
- + ":" + PortAssignment.unique() + ":participant;127.0.0.1:"
- + clientPorts[i];
+ server = "server." + i + "=127.0.0.1:" + PortAssignment.unique() + ":" + PortAssignment.unique()
+ + ":participant;127.0.0.1:" + clientPorts[i];
sb.append(server + "\n");
}
String currentQuorumCfgSection = sb.toString();
// start all the servers
for (int i = 0; i < SERVER_COUNT; i++) {
- mt[i] = new MainThread(i, clientPorts[i], currentQuorumCfgSection,
- false) {
+ mt[i] = new MainThread(i, clientPorts[i], currentQuorumCfgSection, false) {
@Override
public TestQPMain getTestQPMain() {
return new MockTestQPMain();
@@ -81,14 +78,13 @@ public class EphemeralNodeDeletionTest extends QuorumPeerTestBase {
// ensure all servers started
for (int i = 0; i < SERVER_COUNT; i++) {
- Assert.assertTrue("waiting for server " + i + " being up",
- ClientBase.waitForServerUp("127.0.0.1:" + clientPorts[i],
- CONNECTION_TIMEOUT));
+ assertTrue(
+ "waiting for server " + i + " being up",
+ ClientBase.waitForServerUp("127.0.0.1:" + clientPorts[i], CONNECTION_TIMEOUT));
}
CountdownWatcher watch = new CountdownWatcher();
- ZooKeeper zk = new ZooKeeper("127.0.0.1:" + clientPorts[1],
- ClientBase.CONNECTION_TIMEOUT, watch);
+ ZooKeeper zk = new ZooKeeper("127.0.0.1:" + clientPorts[1], ClientBase.CONNECTION_TIMEOUT, watch);
watch.waitForConnected(ClientBase.CONNECTION_TIMEOUT);
/**
@@ -99,14 +95,14 @@ public class EphemeralNodeDeletionTest extends QuorumPeerTestBase {
// 1: create ephemeral node
String nodePath = "/e1";
- zk.create(nodePath, "1".getBytes(), Ids.OPEN_ACL_UNSAFE,
- CreateMode.EPHEMERAL, firstEphemeralNode);
- assertEquals("Current session and ephemeral owner should be same",
- zk.getSessionId(), firstEphemeralNode.getEphemeralOwner());
+ zk.create(nodePath, "1".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL, firstEphemeralNode);
+ assertEquals(
+ "Current session and ephemeral owner should be same",
+ zk.getSessionId(),
+ firstEphemeralNode.getEphemeralOwner());
// 2: inject network problem in one of the follower
- CustomQuorumPeer follower = (CustomQuorumPeer) getByServerState(mt,
- ServerState.FOLLOWING);
+ CustomQuorumPeer follower = (CustomQuorumPeer) getByServerState(mt, ServerState.FOLLOWING);
follower.setInjectError(true);
// 3: close the session so that ephemeral node is deleted
@@ -115,19 +111,18 @@ public class EphemeralNodeDeletionTest extends QuorumPeerTestBase {
// remove the error
follower.setInjectError(false);
- Assert.assertTrue("Faulted Follower should have joined quorum by now",
- ClientBase.waitForServerUp(
- "127.0.0.1:" + follower.getClientPort(),
- CONNECTION_TIMEOUT));
+ assertTrue(
+ "Faulted Follower should have joined quorum by now",
+ ClientBase.waitForServerUp("127.0.0.1:" + follower.getClientPort(), CONNECTION_TIMEOUT));
QuorumPeer leader = getByServerState(mt, ServerState.LEADING);
assertNotNull("Leader should not be null", leader);
- Assert.assertTrue("Leader must be running", ClientBase.waitForServerUp(
- "127.0.0.1:" + leader.getClientPort(), CONNECTION_TIMEOUT));
+ assertTrue(
+ "Leader must be running",
+ ClientBase.waitForServerUp("127.0.0.1:" + leader.getClientPort(), CONNECTION_TIMEOUT));
watch = new CountdownWatcher();
- zk = new ZooKeeper("127.0.0.1:" + leader.getClientPort(),
- ClientBase.CONNECTION_TIMEOUT, watch);
+ zk = new ZooKeeper("127.0.0.1:" + leader.getClientPort(), ClientBase.CONNECTION_TIMEOUT, watch);
watch.waitForConnected(ClientBase.CONNECTION_TIMEOUT);
Stat exists = zk.exists(nodePath, false);
@@ -135,8 +130,9 @@ public class EphemeralNodeDeletionTest extends QuorumPeerTestBase {
CountdownWatcher followerWatch = new CountdownWatcher();
ZooKeeper followerZK = new ZooKeeper(
- "127.0.0.1:" + follower.getClientPort(),
- ClientBase.CONNECTION_TIMEOUT, followerWatch);
+ "127.0.0.1:" + follower.getClientPort(),
+ ClientBase.CONNECTION_TIMEOUT,
+ followerWatch);
followerWatch.waitForConnected(ClientBase.CONNECTION_TIMEOUT);
Stat nodeAtFollower = followerZK.exists(nodePath, false);
@@ -145,23 +141,21 @@ public class EphemeralNodeDeletionTest extends QuorumPeerTestBase {
// Create the node with another session
Stat currentEphemeralNode = new Stat();
- zk.create(nodePath, "2".getBytes(), Ids.OPEN_ACL_UNSAFE,
- CreateMode.EPHEMERAL, currentEphemeralNode);
+ zk.create(nodePath, "2".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL, currentEphemeralNode);
// close the session and newly created ephemeral node should be deleted
zk.close();
-
+
SyncCallback cb = new SyncCallback();
followerZK.sync(nodePath, cb, null);
cb.sync.await(CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS);
-
+
nodeAtFollower = followerZK.exists(nodePath, false);
// Problem 2: Before fix, after session close the ephemeral node
// was not getting deleted. But now after the fix after session close
// ephemeral node is getting deleted.
- assertNull("After session close ephemeral node must be deleted",
- nodeAtFollower);
+ assertNull("After session close ephemeral node must be deleted", nodeAtFollower);
followerZK.close();
}
@@ -188,6 +182,7 @@ public class EphemeralNodeDeletionTest extends QuorumPeerTestBase {
}
static class CustomQuorumPeer extends QuorumPeer {
+
private boolean injectError = false;
public CustomQuorumPeer() throws SaslException {
@@ -195,10 +190,8 @@ public class EphemeralNodeDeletionTest extends QuorumPeerTestBase {
}
@Override
- protected Follower makeFollower(FileTxnSnapLog logFactory)
- throws IOException {
- return new Follower(this, new FollowerZooKeeperServer(logFactory,
- this, this.getZkDb())) {
+ protected Follower makeFollower(FileTxnSnapLog logFactory) throws IOException {
+ return new Follower(this, new FollowerZooKeeperServer(logFactory, this, this.getZkDb())) {
@Override
void readPacket(QuorumPacket pp) throws IOException {
@@ -211,9 +204,8 @@ public class EphemeralNodeDeletionTest extends QuorumPeerTestBase {
super.readPacket(pp);
if (injectError && pp.getType() == Leader.PROPOSAL) {
String type = LearnerHandler.packetToString(pp);
- throw new SocketTimeoutException(
- "Socket timeout while reading the packet for operation "
- + type);
+ throw new SocketTimeoutException("Socket timeout while reading the packet for operation "
+ + type);
}
}
@@ -227,18 +219,23 @@ public class EphemeralNodeDeletionTest extends QuorumPeerTestBase {
}
static class MockTestQPMain extends TestQPMain {
+
@Override
protected QuorumPeer getQuorumPeer() throws SaslException {
return new CustomQuorumPeer();
}
+
}
-
+
private static class SyncCallback implements AsyncCallback.VoidCallback {
+
private final CountDownLatch sync = new CountDownLatch(1);
-
+
@Override
public void processResult(int rc, String path, Object ctx) {
- sync.countDown();
+ sync.countDown();
}
+
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/FLEBackwardElectionRoundTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/FLEBackwardElectionRoundTest.java
index 09adbc4d3..84e20311f 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/FLEBackwardElectionRoundTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/FLEBackwardElectionRoundTest.java
@@ -17,43 +17,39 @@
package org.apache.zookeeper.server.quorum;
+import static org.junit.Assert.fail;
import java.io.File;
-import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.util.HashMap;
import java.util.Map;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
import org.apache.zookeeper.PortAssignment;
import org.apache.zookeeper.ZKTestCase;
-import org.apache.zookeeper.server.quorum.QuorumCnxManager;
-import org.apache.zookeeper.server.quorum.QuorumPeer;
-import org.apache.zookeeper.server.quorum.Vote;
import org.apache.zookeeper.server.quorum.QuorumPeer.QuorumServer;
import org.apache.zookeeper.server.quorum.QuorumPeer.ServerState;
import org.apache.zookeeper.test.ClientBase;
import org.junit.After;
-import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
public class FLEBackwardElectionRoundTest extends ZKTestCase {
+
protected static final Logger LOG = LoggerFactory.getLogger(FLELostMessageTest.class);
int count;
- Map<Long,QuorumServer> peers;
- File tmpdir[];
- int port[];
+ Map<Long, QuorumServer> peers;
+ File[] tmpdir;
+ int[] port;
- QuorumCnxManager cnxManagers[];
+ QuorumCnxManager[] cnxManagers;
@Before
public void setUp() throws Exception {
count = 3;
- peers = new HashMap<Long,QuorumServer>(count);
+ peers = new HashMap<Long, QuorumServer>(count);
tmpdir = new File[count];
port = new int[count];
cnxManagers = new QuorumCnxManager[count - 1];
@@ -61,8 +57,8 @@ public class FLEBackwardElectionRoundTest extends ZKTestCase {
@After
public void tearDown() throws Exception {
- for(int i = 0; i < (count - 1); i++){
- if(cnxManagers[i] != null){
+ for (int i = 0; i < (count - 1); i++) {
+ if (cnxManagers[i] != null) {
cnxManagers[i].halt();
}
}
@@ -90,12 +86,9 @@ public class FLEBackwardElectionRoundTest extends ZKTestCase {
@Test
public void testBackwardElectionRound() throws Exception {
LOG.info("TestLE: {}, {}", getTestName(), count);
- for(int i = 0; i < count; i++) {
+ for (int i = 0; i < count; i++) {
int clientport = PortAssignment.unique();
- peers.put(Long.valueOf(i),
- new QuorumServer(i,
- new InetSocketAddress(clientport),
- new InetSocketAddress(PortAssignment.unique())));
+ peers.put(Long.valueOf(i), new QuorumServer(i, new InetSocketAddress(clientport), new InetSocketAddress(PortAssignment.unique())));
tmpdir[i] = ClientBase.createTmpDir();
port[i] = clientport;
}
@@ -118,7 +111,7 @@ public class FLEBackwardElectionRoundTest extends ZKTestCase {
cnxManagers[0] = mockPeer.createCnxnManager();
cnxManagers[0].listener.start();
- cnxManagers[0].toSend(0l, initialMsg0);
+ cnxManagers[0].toSend(0L, initialMsg0);
/*
* Start mock server 2
@@ -127,7 +120,7 @@ public class FLEBackwardElectionRoundTest extends ZKTestCase {
cnxManagers[1] = mockPeer.createCnxnManager();
cnxManagers[1].listener.start();
- cnxManagers[1].toSend(0l, initialMsg1);
+ cnxManagers[1].toSend(0L, initialMsg1);
/*
* Run another instance of leader election.
@@ -139,13 +132,13 @@ public class FLEBackwardElectionRoundTest extends ZKTestCase {
/*
* Send the same messages, this time should not make 0 the leader.
*/
- cnxManagers[0].toSend(0l, initialMsg0);
- cnxManagers[1].toSend(0l, initialMsg1);
+ cnxManagers[0].toSend(0L, initialMsg0);
+ cnxManagers[1].toSend(0L, initialMsg1);
thread.join(5000);
if (!thread.isAlive()) {
- Assert.fail("Should not have joined");
+ fail("Should not have joined");
}
}
@@ -153,4 +146,5 @@ public class FLEBackwardElectionRoundTest extends ZKTestCase {
private ByteBuffer getMsg() {
return FLETestUtils.createMsg(ServerState.FOLLOWING.ordinal(), 0, 0, 1);
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/FLELostMessageTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/FLELostMessageTest.java
index ad2b180cd..5c6ffb5b7 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/FLELostMessageTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/FLELostMessageTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,33 +18,30 @@
package org.apache.zookeeper.server.quorum;
+import static org.junit.Assert.fail;
import java.io.File;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.HashMap;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
import org.apache.zookeeper.PortAssignment;
import org.apache.zookeeper.ZKTestCase;
-import org.apache.zookeeper.server.quorum.FastLeaderElection;
-import org.apache.zookeeper.server.quorum.QuorumCnxManager;
-import org.apache.zookeeper.server.quorum.QuorumPeer;
import org.apache.zookeeper.server.quorum.QuorumPeer.QuorumServer;
import org.apache.zookeeper.server.quorum.QuorumPeer.ServerState;
import org.apache.zookeeper.test.ClientBase;
import org.junit.After;
-import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
public class FLELostMessageTest extends ZKTestCase {
+
protected static final Logger LOG = LoggerFactory.getLogger(FLELostMessageTest.class);
int count;
- HashMap<Long,QuorumServer> peers;
- File tmpdir[];
- int port[];
+ HashMap<Long, QuorumServer> peers;
+ File[] tmpdir;
+ int[] port;
QuorumCnxManager cnxManager;
@@ -52,7 +49,7 @@ public class FLELostMessageTest extends ZKTestCase {
public void setUp() throws Exception {
count = 3;
- peers = new HashMap<Long,QuorumServer>(count);
+ peers = new HashMap<Long, QuorumServer>(count);
tmpdir = new File[count];
port = new int[count];
}
@@ -65,12 +62,9 @@ public class FLELostMessageTest extends ZKTestCase {
@Test
public void testLostMessage() throws Exception {
LOG.info("TestLE: {}, {}", getTestName(), count);
- for(int i = 0; i < count; i++) {
+ for (int i = 0; i < count; i++) {
int clientport = PortAssignment.unique();
- peers.put(Long.valueOf(i),
- new QuorumServer(i,
- new InetSocketAddress(clientport),
- new InetSocketAddress(PortAssignment.unique())));
+ peers.put(Long.valueOf(i), new QuorumServer(i, new InetSocketAddress(clientport), new InetSocketAddress(PortAssignment.unique())));
tmpdir[i] = ClientBase.createTmpDir();
port[i] = clientport;
}
@@ -89,7 +83,7 @@ public class FLELostMessageTest extends ZKTestCase {
mockServer();
thread.join(5000);
if (thread.isAlive()) {
- Assert.fail("Threads didn't join");
+ fail("Threads didn't join");
}
}
@@ -98,8 +92,9 @@ public class FLELostMessageTest extends ZKTestCase {
cnxManager = peer.createCnxnManager();
cnxManager.listener.start();
- cnxManager.toSend(1l, FLETestUtils.createMsg(ServerState.LOOKING.ordinal(), 0, 0, 0));
+ cnxManager.toSend(1L, FLETestUtils.createMsg(ServerState.LOOKING.ordinal(), 0, 0, 0));
cnxManager.recvQueue.take();
cnxManager.toSend(1L, FLETestUtils.createMsg(ServerState.FOLLOWING.ordinal(), 1, 0, 0));
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/FLEOutOfElectionTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/FLEOutOfElectionTest.java
index d856b79a6..b1b666278 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/FLEOutOfElectionTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/FLEOutOfElectionTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -15,24 +15,21 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
package org.apache.zookeeper.server.quorum;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
import java.io.File;
import java.net.InetSocketAddress;
import java.util.HashMap;
import java.util.Map;
-
import org.apache.zookeeper.PortAssignment;
-import org.apache.zookeeper.server.quorum.QuorumPeer;
import org.apache.zookeeper.server.quorum.FastLeaderElection.Notification;
-import org.apache.zookeeper.server.quorum.Vote;
import org.apache.zookeeper.server.quorum.QuorumPeer.QuorumServer;
import org.apache.zookeeper.server.quorum.QuorumPeer.ServerState;
import org.apache.zookeeper.server.util.ZxidUtils;
import org.apache.zookeeper.test.ClientBase;
-import org.apache.zookeeper.test.FLETest;
-import org.junit.After;
-import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
@@ -46,13 +43,11 @@ public class FLEOutOfElectionTest {
@Before
public void setUp() throws Exception {
File tmpdir = ClientBase.createTmpDir();
- Map<Long, QuorumServer> peers = new HashMap<Long,QuorumServer>();
- for(int i = 0; i < 5; i++) {
- peers.put(Long.valueOf(i), new QuorumServer(Long.valueOf(i),
- new InetSocketAddress("127.0.0.1", PortAssignment.unique())));
+ Map<Long, QuorumServer> peers = new HashMap<Long, QuorumServer>();
+ for (int i = 0; i < 5; i++) {
+ peers.put(Long.valueOf(i), new QuorumServer(Long.valueOf(i), new InetSocketAddress("127.0.0.1", PortAssignment.unique())));
}
- QuorumPeer peer = new QuorumPeer(peers, tmpdir, tmpdir,
- PortAssignment.unique(), 3, 3, 1000, 2, 2, 2);
+ QuorumPeer peer = new QuorumPeer(peers, tmpdir, tmpdir, PortAssignment.unique(), 3, 3, 1000, 2, 2, 2);
fle = new FastLeaderElection(peer, peer.createCnxnManager());
}
@@ -64,8 +59,7 @@ public class FLEOutOfElectionTest {
votes.put(3L, new Vote(0x1, 4L, ZxidUtils.makeZxid(2, 1), 2, 2, ServerState.FOLLOWING));
votes.put(4L, new Vote(0x1, 4L, ZxidUtils.makeZxid(2, 1), 2, 2, ServerState.LEADING));
- Assert.assertTrue(fle.getVoteTracker(votes,
- new Vote(4L, ZxidUtils.makeZxid(2, 1), 2, 2, ServerState.FOLLOWING)).hasAllQuorums());
+ assertTrue(fle.getVoteTracker(votes, new Vote(4L, ZxidUtils.makeZxid(2, 1), 2, 2, ServerState.FOLLOWING)).hasAllQuorums());
}
@Test
@@ -76,8 +70,7 @@ public class FLEOutOfElectionTest {
votes.put(3L, new Vote(4L, ZxidUtils.makeZxid(2, 1), 2, 2, ServerState.FOLLOWING));
votes.put(4L, new Vote(4L, ZxidUtils.makeZxid(2, 1), 2, 2, ServerState.LEADING));
- Assert.assertTrue(fle.getVoteTracker(votes,
- new Vote(4L, ZxidUtils.makeZxid(2, 1), 2, 2, ServerState.FOLLOWING)).hasAllQuorums());
+ assertTrue(fle.getVoteTracker(votes, new Vote(4L, ZxidUtils.makeZxid(2, 1), 2, 2, ServerState.FOLLOWING)).hasAllQuorums());
}
@Test
@@ -88,8 +81,7 @@ public class FLEOutOfElectionTest {
votes.put(3L, new Vote(4L, ZxidUtils.makeZxid(2, 1), 1, 1, ServerState.LOOKING));
votes.put(4L, new Vote(4L, ZxidUtils.makeZxid(2, 1), 1, 1, ServerState.LEADING));
- Assert.assertTrue(fle.getVoteTracker(votes,
- new Vote(4L, ZxidUtils.makeZxid(2, 1), 1, 1, ServerState.LOOKING)).hasAllQuorums());
+ assertTrue(fle.getVoteTracker(votes, new Vote(4L, ZxidUtils.makeZxid(2, 1), 1, 1, ServerState.LOOKING)).hasAllQuorums());
}
@Test
@@ -100,13 +92,12 @@ public class FLEOutOfElectionTest {
votes.put(3L, new Vote(4L, ZxidUtils.makeZxid(2, 1), 3, 2, ServerState.LOOKING));
votes.put(4L, new Vote(4L, ZxidUtils.makeZxid(2, 1), 3, 2, ServerState.LEADING));
- Assert.assertFalse(fle.getVoteTracker(votes,
- new Vote(4L, ZxidUtils.makeZxid(2, 1), 2, 2, ServerState.LOOKING)).hasAllQuorums());
+ assertFalse(fle.getVoteTracker(votes, new Vote(4L, ZxidUtils.makeZxid(2, 1), 2, 2, ServerState.LOOKING)).hasAllQuorums());
}
@Test
public void testOutofElection() {
- HashMap<Long,Vote> outofelection = new HashMap<Long,Vote>();
+ HashMap<Long, Vote> outofelection = new HashMap<Long, Vote>();
outofelection.put(1L, new Vote(0x0, 5, ZxidUtils.makeZxid(15, 0), 0xa, 0x17, ServerState.FOLLOWING));
outofelection.put(2L, new Vote(0x0, 5, ZxidUtils.makeZxid(15, 0), 0xa, 0x17, ServerState.FOLLOWING));
@@ -122,15 +113,13 @@ public class FLEOutOfElectionTest {
n.state = vote.getState();
n.peerEpoch = vote.getPeerEpoch();
n.sid = 5L;
-
+
// Set the logical clock to 1 on fle instance of server 3.
fle.logicalclock.set(0x1);
- Assert.assertTrue("Quorum check failed",
- fle.getVoteTracker(outofelection, new Vote(n.version, n.leader,
- n.zxid, n.electionEpoch, n.peerEpoch, n.state)).hasAllQuorums());
+ assertTrue("Quorum check failed", fle.getVoteTracker(outofelection, new Vote(n.version, n.leader, n.zxid, n.electionEpoch, n.peerEpoch, n.state)).hasAllQuorums());
- Assert.assertTrue("Leader check failed", fle.checkLeader(outofelection,
- n.leader, n.electionEpoch));
+ assertTrue("Leader check failed", fle.checkLeader(outofelection, n.leader, n.electionEpoch));
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/FLETestUtils.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/FLETestUtils.java
index a907abdb9..45ce2baea 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/FLETestUtils.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/FLETestUtils.java
@@ -17,27 +17,24 @@
package org.apache.zookeeper.server.quorum;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
import java.nio.ByteBuffer;
-
import org.apache.zookeeper.ZKTestCase;
-import org.apache.zookeeper.server.quorum.FastLeaderElection;
-import org.apache.zookeeper.server.quorum.QuorumPeer;
-import org.apache.zookeeper.server.quorum.Vote;
-
+import org.apache.zookeeper.server.quorum.QuorumPeer.ServerState;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import org.junit.Assert;
-
-import org.apache.zookeeper.server.quorum.QuorumPeer.ServerState;
public class FLETestUtils extends ZKTestCase {
+
protected static final Logger LOG = LoggerFactory.getLogger(FLETestUtils.class);
/*
- * Thread to run an instance of leader election for
+ * Thread to run an instance of leader election for
* a given quorum peer.
*/
static class LEThread extends Thread {
+
private int i;
private QuorumPeer peer;
@@ -56,7 +53,7 @@ public class FLETestUtils extends ZKTestCase {
v = peer.getElectionAlg().lookForLeader();
if (v == null) {
- Assert.fail("Thread " + i + " got a null vote");
+ fail("Thread " + i + " got a null vote");
}
/*
@@ -67,18 +64,19 @@ public class FLETestUtils extends ZKTestCase {
LOG.info("Finished election: {}, {}", i, v.getId());
- Assert.assertTrue("State is not leading.", peer.getPeerState() == ServerState.LEADING);
+ assertTrue("State is not leading.", peer.getPeerState() == ServerState.LEADING);
} catch (Exception e) {
e.printStackTrace();
}
LOG.info("Joining");
}
+
}
/*
* Creates a leader election notification message.
*/
- static ByteBuffer createMsg(int state, long leader, long zxid, long epoch){
+ static ByteBuffer createMsg(int state, long leader, long zxid, long epoch) {
return FastLeaderElection.buildMsg(state, leader, zxid, 1, epoch);
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/FuzzySnapshotRelatedTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/FuzzySnapshotRelatedTest.java
index 4005dbeb8..5cd825947 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/FuzzySnapshotRelatedTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/FuzzySnapshotRelatedTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,6 +18,8 @@
package org.apache.zookeeper.server.quorum;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
@@ -25,14 +27,11 @@ import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.security.sasl.SaslException;
-
import org.apache.jute.OutputArchive;
-
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException.NoNodeException;
import org.apache.zookeeper.KeeperException.NodeExistsException;
import org.apache.zookeeper.Op;
-
import org.apache.zookeeper.PortAssignment;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;
@@ -45,8 +44,6 @@ import org.apache.zookeeper.server.ZKDatabase;
import org.apache.zookeeper.server.ZooKeeperServer;
import org.apache.zookeeper.server.persistence.FileTxnSnapLog;
import org.apache.zookeeper.test.ClientBase;
-
-import org.junit.Assert;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
@@ -76,9 +73,8 @@ public class FuzzySnapshotRelatedTest extends QuorumPeerTestBase {
for (int i = 0; i < ENSEMBLE_SERVERS; i++) {
clientPorts[i] = PortAssignment.unique();
- server = "server." + i + "=127.0.0.1:" + PortAssignment.unique()
- + ":" + PortAssignment.unique() + ":participant;127.0.0.1:"
- + clientPorts[i];
+ server = "server." + i + "=127.0.0.1:" + PortAssignment.unique() + ":" + PortAssignment.unique()
+ + ":participant;127.0.0.1:" + clientPorts[i];
sb.append(server + "\n");
}
String currentQuorumCfgSection = sb.toString();
@@ -87,16 +83,14 @@ public class FuzzySnapshotRelatedTest extends QuorumPeerTestBase {
mt = new MainThread[ENSEMBLE_SERVERS];
zk = new ZooKeeper[ENSEMBLE_SERVERS];
for (int i = 0; i < ENSEMBLE_SERVERS; i++) {
- mt[i] = new MainThread(i, clientPorts[i], currentQuorumCfgSection,
- false) {
+ mt[i] = new MainThread(i, clientPorts[i], currentQuorumCfgSection, false) {
@Override
public TestQPMain getTestQPMain() {
return new CustomizedQPMain();
}
};
mt[i].start();
- zk[i] = new ZooKeeper("127.0.0.1:" + clientPorts[i],
- ClientBase.CONNECTION_TIMEOUT, this);
+ zk[i] = new ZooKeeper("127.0.0.1:" + clientPorts[i], ClientBase.CONNECTION_TIMEOUT, this);
}
QuorumPeerMainTest.waitForAll(zk, States.CONNECTED);
LOG.info("all servers started");
@@ -115,13 +109,13 @@ public class FuzzySnapshotRelatedTest extends QuorumPeerTestBase {
@After
public void tearDown() throws Exception {
if (mt != null) {
- for (MainThread t: mt) {
+ for (MainThread t : mt) {
t.shutdown();
}
}
if (zk != null) {
- for (ZooKeeper z: zk) {
+ for (ZooKeeper z : zk) {
z.close();
}
}
@@ -134,8 +128,7 @@ public class FuzzySnapshotRelatedTest extends QuorumPeerTestBase {
createEmptyNode(zk[followerA], path);
LOG.info("Hook to catch the 2nd sub create node txn in multi-op");
- CustomDataTree dt =
- (CustomDataTree) mt[followerA].main.quorumPeer.getZkDb().getDataTree();
+ CustomDataTree dt = (CustomDataTree) mt[followerA].main.quorumPeer.getZkDb().getDataTree();
final ZooKeeperServer zkServer = mt[followerA].main.quorumPeer.getActiveServer();
@@ -152,11 +145,8 @@ public class FuzzySnapshotRelatedTest extends QuorumPeerTestBase {
LOG.info("Issue a multi op to create 2 nodes");
zk[followerA].multi(Arrays.asList(
- Op.create(node1, node1.getBytes(),
- Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT),
- Op.create(node2, node2.getBytes(),
- Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT))
- );
+ Op.create(node1, node1.getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT),
+ Op.create(node2, node2.getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT)));
LOG.info("Restart the server");
mt[followerA].shutdown();
@@ -166,7 +156,8 @@ public class FuzzySnapshotRelatedTest extends QuorumPeerTestBase {
QuorumPeerMainTest.waitForOne(zk[followerA], States.CONNECTED);
LOG.info("Make sure the node consistent with leader");
- Assert.assertEquals(new String(zk[leaderId].getData(node2, null, null)),
+ assertEquals(
+ new String(zk[leaderId].getData(node2, null, null)),
new String(zk[followerA].getData(node2, null, null)));
}
@@ -198,8 +189,7 @@ public class FuzzySnapshotRelatedTest extends QuorumPeerTestBase {
mt[followerA].start();
QuorumPeerMainTest.waitForOne(zk[followerA], States.CONNECTED);
- LOG.info("Check and make sure the pzxid of the parent is the same " +
- "on leader and follower A");
+ LOG.info("Check and make sure the pzxid of the parent is the same " + "on leader and follower A");
compareStat(parent, leaderId, followerA);
}
@@ -231,15 +221,13 @@ public class FuzzySnapshotRelatedTest extends QuorumPeerTestBase {
mt[followerA].start();
QuorumPeerMainTest.waitForOne(zk[followerA], States.CONNECTED);
- LOG.info("Check and make sure the pzxid of the parent is the same " +
- "on leader and follower A");
+ LOG.info("Check and make sure the pzxid of the parent is the same " + "on leader and follower A");
compareStat(parent, leaderId, followerA);
}
private void addSerializeListener(int sid, String parent, String child) {
final ZooKeeper zkClient = zk[followerA];
- CustomDataTree dt =
- (CustomDataTree) mt[sid].main.quorumPeer.getZkDb().getDataTree();
+ CustomDataTree dt = (CustomDataTree) mt[sid].main.quorumPeer.getZkDb().getDataTree();
dt.addListener(parent, new NodeSerializeListener() {
@Override
public void nodeSerialized(String path) {
@@ -253,14 +241,14 @@ public class FuzzySnapshotRelatedTest extends QuorumPeerTestBase {
});
}
- private void compareStat(String path, int sid, int compareWithSid) throws Exception{
+ private void compareStat(String path, int sid, int compareWithSid) throws Exception {
Stat stat1 = new Stat();
zk[sid].getData(path, null, stat1);
Stat stat2 = new Stat();
zk[compareWithSid].getData(path, null, stat2);
- Assert.assertEquals(stat1, stat2);
+ assertEquals(stat1, stat2);
}
@Test
@@ -284,7 +272,8 @@ public class FuzzySnapshotRelatedTest extends QuorumPeerTestBase {
LOG.info("Create a global session");
ZooKeeper globalClient = new ZooKeeper(
"127.0.0.1:" + clientPorts[followerA],
- ClientBase.CONNECTION_TIMEOUT, this);
+ ClientBase.CONNECTION_TIMEOUT,
+ this);
QuorumPeerMainTest.waitForOne(globalClient, States.CONNECTED);
LOG.info("Restart followerA to load the data from disk");
@@ -296,40 +285,35 @@ public class FuzzySnapshotRelatedTest extends QuorumPeerTestBase {
LOG.info("Make sure the global sessions are consistent with leader");
- Map<Long, Integer> globalSessionsOnLeader =
- mt[leaderId].main.quorumPeer.getZkDb().getSessionWithTimeOuts();
+ Map<Long, Integer> globalSessionsOnLeader = mt[leaderId].main.quorumPeer.getZkDb().getSessionWithTimeOuts();
if (mt[followerA].main.quorumPeer == null) {
LOG.info("quorumPeer is null");
}
if (mt[followerA].main.quorumPeer.getZkDb() == null) {
LOG.info("zkDb is null");
}
- Map<Long, Integer> globalSessionsOnFollowerA =
- mt[followerA].main.quorumPeer.getZkDb().getSessionWithTimeOuts();
- LOG.info("sessions are {}, {}", globalSessionsOnLeader.keySet(),
- globalSessionsOnFollowerA.keySet());
- Assert.assertTrue(globalSessionsOnFollowerA.keySet().containsAll(
- globalSessionsOnLeader.keySet()));
+ Map<Long, Integer> globalSessionsOnFollowerA = mt[followerA].main.quorumPeer.getZkDb().getSessionWithTimeOuts();
+ LOG.info("sessions are {}, {}", globalSessionsOnLeader.keySet(), globalSessionsOnFollowerA.keySet());
+ assertTrue(globalSessionsOnFollowerA.keySet().containsAll(globalSessionsOnLeader.keySet()));
}
private void createEmptyNode(ZooKeeper zk, String path) throws Exception {
zk.create(path, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
}
- static interface NodeCreateListener {
- public void process(String path);
+ interface NodeCreateListener {
+
+ void process(String path);
}
static class CustomDataTree extends DataTree {
- Map<String, NodeCreateListener> nodeCreateListeners =
- new HashMap<String, NodeCreateListener>();
- Map<String, NodeSerializeListener> listeners =
- new HashMap<String, NodeSerializeListener>();
+
+ Map<String, NodeCreateListener> nodeCreateListeners = new HashMap<String, NodeCreateListener>();
+ Map<String, NodeSerializeListener> listeners = new HashMap<String, NodeSerializeListener>();
@Override
- public void serializeNodeData(OutputArchive oa, String path,
- DataNode node) throws IOException {
+ public void serializeNodeData(OutputArchive oa, String path, DataNode node) throws IOException {
super.serializeNodeData(oa, path, node);
NodeSerializeListener listener = listeners.get(path);
if (listener != null) {
@@ -342,32 +326,42 @@ public class FuzzySnapshotRelatedTest extends QuorumPeerTestBase {
}
@Override
- public void createNode(final String path, byte data[], List<ACL> acl,
- long ephemeralOwner, int parentCVersion, long zxid,
- long time, Stat outputStat)
- throws NoNodeException, NodeExistsException {
+ public void createNode(
+ final String path,
+ byte[] data,
+ List<ACL> acl,
+ long ephemeralOwner,
+ int parentCVersion,
+ long zxid,
+ long time,
+ Stat outputStat) throws NoNodeException, NodeExistsException {
NodeCreateListener listener = nodeCreateListeners.get(path);
if (listener != null) {
listener.process(path);
}
- super.createNode(path, data, acl, ephemeralOwner, parentCVersion,
- zxid, time, outputStat);
+ super.createNode(path, data, acl, ephemeralOwner, parentCVersion, zxid, time, outputStat);
}
public void addNodeCreateListener(String path, NodeCreateListener listener) {
nodeCreateListeners.put(path, listener);
}
+
}
- static interface NodeSerializeListener {
- public void nodeSerialized(String path);
+ interface NodeSerializeListener {
+
+ void nodeSerialized(String path);
+
}
- static interface CommitSessionListener {
- public void process(long sessionId);
+ interface CommitSessionListener {
+
+ void process(long sessionId);
+
}
static class CustomizedQPMain extends TestQPMain {
+
CommitSessionListener commitSessionListener;
public void setCommitSessionListener(CommitSessionListener listener) {
@@ -388,15 +382,15 @@ public class FuzzySnapshotRelatedTest extends QuorumPeerTestBase {
}
@Override
- protected Follower makeFollower(FileTxnSnapLog logFactory)
- throws IOException {
- return new Follower(this, new FollowerZooKeeperServer(
- logFactory, this, this.getZkDb()) {
+ protected Follower makeFollower(FileTxnSnapLog logFactory) throws IOException {
+ return new Follower(this, new FollowerZooKeeperServer(logFactory, this, this.getZkDb()) {
@Override
public void createSessionTracker() {
sessionTracker = new LearnerSessionTracker(
- this, getZKDatabase().getSessionWithTimeOuts(),
- this.tickTime, self.getId(),
+ this,
+ getZKDatabase().getSessionWithTimeOuts(),
+ this.tickTime,
+ self.getId(),
self.areLocalSessionsEnabled(),
getZooKeeperServerListener()) {
@@ -413,5 +407,7 @@ public class FuzzySnapshotRelatedTest extends QuorumPeerTestBase {
}
};
}
+
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/LeaderBeanTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/LeaderBeanTest.java
index a6a5ec759..7ce583d58 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/LeaderBeanTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/LeaderBeanTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,16 +18,30 @@
package org.apache.zookeeper.server.quorum;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotEquals;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+import java.io.File;
+import java.io.IOException;
+import java.net.InetAddress;
+import java.net.InetSocketAddress;
+import java.util.HashMap;
+import java.util.Map;
import org.apache.jute.OutputArchive;
import org.apache.jute.Record;
-import org.apache.zookeeper.common.X509Exception;
import org.apache.zookeeper.PortAssignment;
+import org.apache.zookeeper.common.X509Exception;
import org.apache.zookeeper.server.Request;
import org.apache.zookeeper.server.ZKDatabase;
import org.apache.zookeeper.server.persistence.FileTxnSnapLog;
-import org.apache.zookeeper.server.quorum.flexible.QuorumVerifier;
import org.apache.zookeeper.server.quorum.QuorumPeer.LearnerType;
import org.apache.zookeeper.server.quorum.QuorumPeer.QuorumServer;
+import org.apache.zookeeper.server.quorum.flexible.QuorumVerifier;
import org.apache.zookeeper.server.util.SerializeUtils;
import org.apache.zookeeper.test.ClientBase;
import org.apache.zookeeper.txn.TxnHeader;
@@ -37,23 +51,8 @@ import org.junit.Test;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
-import java.io.File;
-import java.io.IOException;
-import java.net.InetAddress;
-import java.net.InetSocketAddress;
-import java.util.HashMap;
-import java.util.Map;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.assertNotEquals;
-import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.ArgumentMatchers.anyString;
-import static org.mockito.Mockito.doAnswer;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.when;
-
public class LeaderBeanTest {
+
private Leader leader;
private LeaderBean leaderBean;
private FileTxnSnapLog fileTxnSnapLog;
@@ -70,18 +69,14 @@ public class LeaderBeanTest {
Map<Long, QuorumServer> peersView = new HashMap<Long, QuorumServer>();
InetAddress clientIP = InetAddress.getLoopbackAddress();
- peersView.put(Long.valueOf(myId),
- new QuorumServer(myId, new InetSocketAddress(clientIP, PortAssignment.unique()),
- new InetSocketAddress(clientIP, PortAssignment.unique()),
- new InetSocketAddress(clientIP, clientPort), LearnerType.PARTICIPANT));
+ peersView.put(Long.valueOf(myId), new QuorumServer(myId, new InetSocketAddress(clientIP, PortAssignment.unique()), new InetSocketAddress(clientIP, PortAssignment.unique()), new InetSocketAddress(clientIP, clientPort), LearnerType.PARTICIPANT));
quorumVerifierMock = mock(QuorumVerifier.class);
when(quorumVerifierMock.getAllMembers()).thenReturn(peersView);
qp.setQuorumVerifier(quorumVerifierMock, false);
File tmpDir = ClientBase.createEmptyTestDir();
- fileTxnSnapLog = new FileTxnSnapLog(new File(tmpDir, "data"),
- new File(tmpDir, "data_txnlog"));
+ fileTxnSnapLog = new FileTxnSnapLog(new File(tmpDir, "data"), new File(tmpDir, "data_txnlog"));
ZKDatabase zkDb = new ZKDatabase(fileTxnSnapLog);
zks = new LeaderZooKeeperServer(fileTxnSnapLog, qp, zkDb);
@@ -211,4 +206,5 @@ public class LeaderBeanTest {
assertTrue(followerInfo.contains("5"));
assertEquals("5\n", leaderBean.nonVotingFollowerInfo());
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/LeaderMetricsTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/LeaderMetricsTest.java
index bf741f4ca..40ddfe6f3 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/LeaderMetricsTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/LeaderMetricsTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,33 +18,38 @@
package org.apache.zookeeper.server.quorum;
-import org.apache.zookeeper.*;
+import static org.hamcrest.number.OrderingComparison.greaterThan;
+import static org.hamcrest.number.OrderingComparison.greaterThanOrEqualTo;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertThat;
+import java.util.Map;
+import java.util.concurrent.CountDownLatch;
+import org.apache.zookeeper.CreateMode;
+import org.apache.zookeeper.WatchedEvent;
+import org.apache.zookeeper.Watcher;
+import org.apache.zookeeper.ZKTestCase;
+import org.apache.zookeeper.ZooDefs;
+import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.metrics.MetricsUtils;
import org.apache.zookeeper.server.ServerMetrics;
import org.apache.zookeeper.test.ClientBase;
import org.apache.zookeeper.test.QuorumUtil;
import org.junit.After;
-import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
-import java.lang.reflect.Field;
-import java.lang.reflect.Modifier;
-import java.util.Map;
-import java.util.concurrent.CountDownLatch;
-
-import static org.hamcrest.number.OrderingComparison.greaterThan;
-import static org.hamcrest.number.OrderingComparison.greaterThanOrEqualTo;
-
public class LeaderMetricsTest extends ZKTestCase {
+
CountDownLatch createdLatch;
int oldLoggingFeq;
private class MyWatcher implements Watcher {
+
@Override
- public void process(WatchedEvent e){
+ public void process(WatchedEvent e) {
createdLatch.countDown();
}
+
}
@Before
@@ -56,7 +61,7 @@ public class LeaderMetricsTest extends ZKTestCase {
public void teardown() {
Leader.setAckLoggingFrequency(oldLoggingFeq);
}
-
+
@Test
public void testLeaderMetrics() throws Exception {
// set the logging frequency to one so we log the ack latency for every ack
@@ -75,25 +80,26 @@ public class LeaderMetricsTest extends ZKTestCase {
Map<String, Object> values = MetricsUtils.currentServerMetrics();
- Assert.assertEquals(2L, values.get("proposal_count"));
+ assertEquals(2L, values.get("proposal_count"));
// Quorum ack latency is per txn
- Assert.assertEquals(2L, values.get("cnt_quorum_ack_latency"));
- Assert.assertThat((long)values.get("min_quorum_ack_latency"), greaterThan(0L));
+ assertEquals(2L, values.get("cnt_quorum_ack_latency"));
+ assertThat((long) values.get("min_quorum_ack_latency"), greaterThan(0L));
int numberOfAckServers = 0;
// ack latency is per server
- for (int sid = 1; sid<=3; sid++) {
+ for (int sid = 1; sid <= 3; sid++) {
String metricName = "min_" + sid + "_ack_latency";
if (values.get(metricName) != null) {
numberOfAckServers++;
- Assert.assertThat((long) values.get("min_" + sid + "_ack_latency"), greaterThanOrEqualTo(0L));
+ assertThat((long) values.get("min_" + sid + "_ack_latency"), greaterThanOrEqualTo(0L));
}
}
// at least two servers should have send ACKs
- Assert.assertThat(numberOfAckServers, greaterThanOrEqualTo(2));
+ assertThat(numberOfAckServers, greaterThanOrEqualTo(2));
zk.close();
util.shutdownAll();
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/LeaderWithObserverTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/LeaderWithObserverTest.java
index 2548acad1..91292de77 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/LeaderWithObserverTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/LeaderWithObserverTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,21 +18,22 @@
package org.apache.zookeeper.server.quorum;
+import static org.apache.zookeeper.server.quorum.ZabUtils.createLeader;
+import static org.apache.zookeeper.server.quorum.ZabUtils.createQuorumPeer;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+import java.io.File;
+import java.net.InetSocketAddress;
+import java.util.Map;
+import java.util.Set;
import org.apache.zookeeper.PortAssignment;
import org.apache.zookeeper.test.ClientBase;
import org.junit.After;
-import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
-import java.io.File;
-import java.net.InetSocketAddress;
-import java.util.Map;
-import java.util.Set;
-
-import static org.apache.zookeeper.server.quorum.ZabUtils.createLeader;
-import static org.apache.zookeeper.server.quorum.ZabUtils.createQuorumPeer;
-
public class LeaderWithObserverTest {
QuorumPeer peer;
@@ -50,18 +51,14 @@ public class LeaderWithObserverTest {
observerId = peers.size();
leader = createLeader(tmpDir, peer);
peer.leader = leader;
- peers.put(observerId, new QuorumPeer.QuorumServer(
- observerId, new InetSocketAddress("127.0.0.1", PortAssignment.unique()),
- new InetSocketAddress("127.0.0.1", PortAssignment.unique()),
- new InetSocketAddress("127.0.0.1", PortAssignment.unique()),
- QuorumPeer.LearnerType.OBSERVER));
+ peers.put(observerId, new QuorumPeer.QuorumServer(observerId, new InetSocketAddress("127.0.0.1", PortAssignment.unique()), new InetSocketAddress("127.0.0.1", PortAssignment.unique()), new InetSocketAddress("127.0.0.1", PortAssignment.unique()), QuorumPeer.LearnerType.OBSERVER));
// these tests are serial, we can speed up InterruptedException
peer.tickTime = 1;
}
@After
- public void tearDown(){
+ public void tearDown() {
leader.shutdown("end of test");
tmpDir.delete();
}
@@ -71,8 +68,8 @@ public class LeaderWithObserverTest {
long lastAcceptedEpoch = 5;
peer.setAcceptedEpoch(5);
- Assert.assertEquals("Unexpected vote in connectingFollowers", 0, leader.connectingFollowers.size());
- Assert.assertTrue(leader.waitingForNewEpoch);
+ assertEquals("Unexpected vote in connectingFollowers", 0, leader.connectingFollowers.size());
+ assertTrue(leader.waitingForNewEpoch);
try {
// Leader asks for epoch (mocking Leader.lead behavior)
// First add to connectingFollowers
@@ -81,10 +78,9 @@ public class LeaderWithObserverTest {
// ignore timeout
}
- Assert.assertEquals("Unexpected vote in connectingFollowers", 1, leader.connectingFollowers.size());
- Assert.assertEquals("Leader shouldn't set new epoch until quorum of participants is in connectingFollowers",
- lastAcceptedEpoch, peer.getAcceptedEpoch());
- Assert.assertTrue(leader.waitingForNewEpoch);
+ assertEquals("Unexpected vote in connectingFollowers", 1, leader.connectingFollowers.size());
+ assertEquals("Leader shouldn't set new epoch until quorum of participants is in connectingFollowers", lastAcceptedEpoch, peer.getAcceptedEpoch());
+ assertTrue(leader.waitingForNewEpoch);
try {
// Observer asks for epoch (mocking LearnerHandler behavior)
leader.getEpochToPropose(observerId, lastAcceptedEpoch);
@@ -92,21 +88,20 @@ public class LeaderWithObserverTest {
// ignore timeout
}
- Assert.assertEquals("Unexpected vote in connectingFollowers", 1, leader.connectingFollowers.size());
- Assert.assertEquals("Leader shouldn't set new epoch after observer asks for epoch",
- lastAcceptedEpoch, peer.getAcceptedEpoch());
- Assert.assertTrue(leader.waitingForNewEpoch);
+ assertEquals("Unexpected vote in connectingFollowers", 1, leader.connectingFollowers.size());
+ assertEquals("Leader shouldn't set new epoch after observer asks for epoch", lastAcceptedEpoch, peer.getAcceptedEpoch());
+ assertTrue(leader.waitingForNewEpoch);
try {
// Now participant asks for epoch (mocking LearnerHandler behavior). Second add to connectingFollowers.
// Triggers verifier.containsQuorum = true
leader.getEpochToPropose(participantId, lastAcceptedEpoch);
} catch (Exception e) {
- Assert.fail("Timed out in getEpochToPropose");
+ fail("Timed out in getEpochToPropose");
}
- Assert.assertEquals("Unexpected vote in connectingFollowers", 2, leader.connectingFollowers.size());
- Assert.assertEquals("Leader should record next epoch", lastAcceptedEpoch + 1, peer.getAcceptedEpoch());
- Assert.assertFalse(leader.waitingForNewEpoch);
+ assertEquals("Unexpected vote in connectingFollowers", 2, leader.connectingFollowers.size());
+ assertEquals("Leader should record next epoch", lastAcceptedEpoch + 1, peer.getAcceptedEpoch());
+ assertFalse(leader.waitingForNewEpoch);
}
@Test
@@ -114,33 +109,33 @@ public class LeaderWithObserverTest {
// things needed for waitForEpochAck to run (usually in leader.lead(), but we're not running leader here)
leader.leaderStateSummary = new StateSummary(leader.self.getCurrentEpoch(), leader.zk.getLastProcessedZxid());
- Assert.assertEquals("Unexpected vote in electingFollowers", 0, leader.electingFollowers.size());
- Assert.assertFalse(leader.electionFinished);
+ assertEquals("Unexpected vote in electingFollowers", 0, leader.electingFollowers.size());
+ assertFalse(leader.electionFinished);
try {
// leader calls waitForEpochAck, first add to electingFollowers
leader.waitForEpochAck(peer.getId(), new StateSummary(0, 0));
- } catch (InterruptedException e) {
+ } catch (InterruptedException e) {
// ignore timeout
}
- Assert.assertEquals("Unexpected vote in electingFollowers", 1, leader.electingFollowers.size());
- Assert.assertFalse(leader.electionFinished);
+ assertEquals("Unexpected vote in electingFollowers", 1, leader.electingFollowers.size());
+ assertFalse(leader.electionFinished);
try {
// observer calls waitForEpochAck, should fail verifier.containsQuorum
leader.waitForEpochAck(observerId, new StateSummary(0, 0));
- } catch (InterruptedException e) {
+ } catch (InterruptedException e) {
// ignore timeout
}
- Assert.assertEquals("Unexpected vote in electingFollowers", 1, leader.electingFollowers.size());
- Assert.assertFalse(leader.electionFinished);
+ assertEquals("Unexpected vote in electingFollowers", 1, leader.electingFollowers.size());
+ assertFalse(leader.electionFinished);
try {
// second add to electingFollowers, verifier.containsQuorum=true, waitForEpochAck returns without exceptions
leader.waitForEpochAck(participantId, new StateSummary(0, 0));
- Assert.assertEquals("Unexpected vote in electingFollowers", 2, leader.electingFollowers.size());
- Assert.assertTrue(leader.electionFinished);
+ assertEquals("Unexpected vote in electingFollowers", 2, leader.electingFollowers.size());
+ assertTrue(leader.electionFinished);
} catch (Exception e) {
- Assert.fail("Timed out in waitForEpochAck");
+ fail("Timed out in waitForEpochAck");
}
}
@@ -153,33 +148,34 @@ public class LeaderWithObserverTest {
leader.newLeaderProposal.addQuorumVerifier(peer.getQuorumVerifier());
Set<Long> ackSet = leader.newLeaderProposal.qvAcksetPairs.get(0).getAckset();
- Assert.assertEquals("Unexpected vote in ackSet", 0, ackSet.size());
- Assert.assertFalse(leader.quorumFormed);
+ assertEquals("Unexpected vote in ackSet", 0, ackSet.size());
+ assertFalse(leader.quorumFormed);
try {
// leader calls waitForNewLeaderAck, first add to ackSet
leader.waitForNewLeaderAck(peer.getId(), zxid);
- } catch (InterruptedException e) {
+ } catch (InterruptedException e) {
// ignore timeout
}
- Assert.assertEquals("Unexpected vote in ackSet", 1, ackSet.size());
- Assert.assertFalse(leader.quorumFormed);
+ assertEquals("Unexpected vote in ackSet", 1, ackSet.size());
+ assertFalse(leader.quorumFormed);
try {
// observer calls waitForNewLeaderAck, should fail verifier.containsQuorum
leader.waitForNewLeaderAck(observerId, zxid);
- } catch (InterruptedException e) {
+ } catch (InterruptedException e) {
// ignore timeout
}
- Assert.assertEquals("Unexpected vote in ackSet", 1, ackSet.size());
- Assert.assertFalse(leader.quorumFormed);
+ assertEquals("Unexpected vote in ackSet", 1, ackSet.size());
+ assertFalse(leader.quorumFormed);
try {
// second add to ackSet, verifier.containsQuorum=true, waitForNewLeaderAck returns without exceptions
leader.waitForNewLeaderAck(participantId, zxid);
- Assert.assertEquals("Unexpected vote in ackSet", 2, ackSet.size());
- Assert.assertTrue(leader.quorumFormed);
+ assertEquals("Unexpected vote in ackSet", 2, ackSet.size());
+ assertTrue(leader.quorumFormed);
} catch (Exception e) {
- Assert.fail("Timed out in waitForEpochAck");
+ fail("Timed out in waitForEpochAck");
}
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/LearnerHandlerMetricsTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/LearnerHandlerMetricsTest.java
index f3ebb6936..b6699d806 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/LearnerHandlerMetricsTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/LearnerHandlerMetricsTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,13 +18,14 @@
package org.apache.zookeeper.server.quorum;
-import org.apache.jute.BinaryOutputArchive;
-import org.apache.zookeeper.metrics.MetricsUtils;
-import org.apache.zookeeper.server.ServerMetrics;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
-
+import static org.hamcrest.number.OrderingComparison.greaterThan;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertThat;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
@@ -32,23 +33,24 @@ import java.net.Socket;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
-
-import static org.hamcrest.number.OrderingComparison.greaterThan;
-import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.ArgumentMatchers.anyString;
-import static org.mockito.Mockito.doAnswer;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.when;
+import org.apache.jute.BinaryOutputArchive;
+import org.apache.zookeeper.metrics.MetricsUtils;
+import org.apache.zookeeper.server.ServerMetrics;
+import org.junit.Before;
+import org.junit.Test;
public class LearnerHandlerMetricsTest {
+
private MockLearnerHandler learnerHandler;
private long sid = 5;
private volatile CountDownLatch allSentLatch = null;
class MockLearnerHandler extends LearnerHandler {
+
MockLearnerHandler(Socket socket, Leader leader) throws IOException {
super(socket, null, leader);
}
+
}
@Before
@@ -61,9 +63,10 @@ public class LearnerHandlerMetricsTest {
//adding 5ms artificial delay when sending each packet
BinaryOutputArchive oa = mock(BinaryOutputArchive.class);
- doAnswer(invocationOnMock -> {Thread.sleep(5); return null;})
- .when(oa).writeRecord(any(QuorumPacket.class), anyString());
-
+ doAnswer(invocationOnMock -> {
+ Thread.sleep(5);
+ return null;
+ }).when(oa).writeRecord(any(QuorumPacket.class), anyString());
BufferedOutputStream bos = mock(BufferedOutputStream.class);
// flush is called when all packets are sent and the queue is empty
@@ -85,7 +88,7 @@ public class LearnerHandlerMetricsTest {
ServerMetrics.getMetrics().resetAll();
//adding 1001 packets in the queue, two marker packets will be added since the interval is every 1000 packets
- for (int i=0; i<1001; i++) {
+ for (int i = 0; i < 1001; i++) {
learnerHandler.queuePacket(new QuorumPacket());
}
@@ -99,20 +102,21 @@ public class LearnerHandlerMetricsTest {
String sidStr = Long.toString(sid);
//we record time for each marker packet and we have two marker packets
- Assert.assertEquals(2L, values.get("cnt_" + sidStr + "_learner_handler_qp_time_ms"));
+ assertEquals(2L, values.get("cnt_" + sidStr + "_learner_handler_qp_time_ms"));
//the second marker has 1000 packets in front of it and each takes 5 ms to send so the time in queue should be
//longer than 5*1000
- Assert.assertThat((long)values.get("max_" + sidStr + "_learner_handler_qp_time_ms"), greaterThan(5000L));
+ assertThat((long) values.get("max_" + sidStr + "_learner_handler_qp_time_ms"), greaterThan(5000L));
//we send 1001 packets + 2 marker packets so the queue size is recorded 1003 times
- Assert.assertEquals(1003L, values.get("cnt_" + sidStr + "_learner_handler_qp_size"));
+ assertEquals(1003L, values.get("cnt_" + sidStr + "_learner_handler_qp_size"));
//the longest queue size is recorded when we are sending the first packet
- Assert.assertEquals(1002L, values.get("max_" + sidStr + "_learner_handler_qp_size"));
+ assertEquals(1002L, values.get("max_" + sidStr + "_learner_handler_qp_size"));
//this is when the queue is emptied
- Assert.assertEquals(0L, values.get("min_" + sidStr + "_learner_handler_qp_size"));
+ assertEquals(0L, values.get("min_" + sidStr + "_learner_handler_qp_size"));
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/LearnerHandlerTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/LearnerHandlerTest.java
index f1dc7cc28..79b454a66 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/LearnerHandlerTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/LearnerHandlerTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -23,16 +23,15 @@ import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
-
import java.io.BufferedInputStream;
import java.io.IOException;
import java.net.Socket;
+import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.locks.ReentrantReadWriteLock;
-
import org.apache.zookeeper.ZKTestCase;
import org.apache.zookeeper.server.TxnLogProposalIterator;
import org.apache.zookeeper.server.ZKDatabase;
@@ -48,10 +47,11 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class LearnerHandlerTest extends ZKTestCase {
- protected static final Logger LOG = LoggerFactory
- .getLogger(LearnerHandlerTest.class);
+
+ protected static final Logger LOG = LoggerFactory.getLogger(LearnerHandlerTest.class);
class MockLearnerHandler extends LearnerHandler {
+
boolean threadStarted = false;
MockLearnerHandler(Socket sock, Leader leader) throws IOException {
@@ -66,9 +66,11 @@ public class LearnerHandlerTest extends ZKTestCase {
protected boolean shouldSendMarkerPacketForLogging() {
return false;
}
+
}
class MockZKDatabase extends ZKDatabase {
+
long lastProcessedZxid;
ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
LinkedList<Proposal> committedLog = new LinkedList<Leader.Proposal>();
@@ -104,12 +106,11 @@ public class LearnerHandlerTest extends ZKTestCase {
return lock;
}
- public Iterator<Proposal> getProposalsFromTxnLog(long peerZxid,
- long limit) {
+ public Iterator<Proposal> getProposalsFromTxnLog(long peerZxid, long limit) {
if (peerZxid >= txnLog.peekFirst().packet.getZxid()) {
return txnLog.iterator();
} else {
- return (new LinkedList<Proposal>()).iterator();
+ return Collections.emptyIterator();
}
}
@@ -117,6 +118,7 @@ public class LearnerHandlerTest extends ZKTestCase {
public long calculateTxnLogSizeLimit() {
return 1;
}
+
}
private MockLearnerHandler learnerHandler;
@@ -136,9 +138,7 @@ public class LearnerHandlerTest extends ZKTestCase {
// Intercept when startForwarding is called
leader = mock(Leader.class);
- when(
- leader.startForwarding(ArgumentMatchers.any(LearnerHandler.class),
- ArgumentMatchers.anyLong())).thenAnswer(new Answer<Long>() {
+ when(leader.startForwarding(ArgumentMatchers.any(LearnerHandler.class), ArgumentMatchers.anyLong())).thenAnswer(new Answer<Long>() {
public Long answer(InvocationOnMock invocation) {
currentZxid = invocation.getArgument(1);
return 0L;
@@ -194,8 +194,10 @@ public class LearnerHandlerTest extends ZKTestCase {
}
void assertZxidEquals(long expected, long value) {
- assertEquals("Expected 0x" + Long.toHexString(expected) + " but was 0x"
- + Long.toHexString(value), expected, value);
+ assertEquals("Expected 0x"
+ + Long.toHexString(expected)
+ + " but was 0x"
+ + Long.toHexString(value), expected, value);
}
/**
@@ -258,18 +260,17 @@ public class LearnerHandlerTest extends ZKTestCase {
assertOpType(Leader.TRUNC, 3, 5);
// DIFF + 1 proposals + 1 commit
assertEquals(3, learnerHandler.getQueuedPackets().size());
- queuedPacketMatches(new long[] { 5 });
+ queuedPacketMatches(new long[]{5});
reset();
// Peer is within committedLog range
peerZxid = 2;
assertFalse(learnerHandler.syncFollower(peerZxid, leader));
// We send DIFF and forward any packet starting lastProcessedZxid
- assertOpType(Leader.DIFF, db.getmaxCommittedLog(),
- db.getmaxCommittedLog());
+ assertOpType(Leader.DIFF, db.getmaxCommittedLog(), db.getmaxCommittedLog());
// DIFF + 2 proposals + 2 commit
assertEquals(5, learnerHandler.getQueuedPackets().size());
- queuedPacketMatches(new long[] { 3, 5 });
+ queuedPacketMatches(new long[]{3, 5});
reset();
// Peer miss the committedLog and txnlog is disabled
@@ -307,18 +308,17 @@ public class LearnerHandlerTest extends ZKTestCase {
assertOpType(Leader.TRUNC, 3, db.getmaxCommittedLog());
// DIFF + 4 proposals + 4 commit
assertEquals(9, learnerHandler.getQueuedPackets().size());
- queuedPacketMatches(new long[] { 5, 6, 7, 8 });
+ queuedPacketMatches(new long[]{5, 6, 7, 8});
reset();
// Peer zxid is in txnlog range
peerZxid = 3;
assertFalse(learnerHandler.syncFollower(peerZxid, leader));
// We send DIFF and forward any packet starting at maxCommittedLog
- assertOpType(Leader.DIFF, db.getmaxCommittedLog(),
- db.getmaxCommittedLog());
+ assertOpType(Leader.DIFF, db.getmaxCommittedLog(), db.getmaxCommittedLog());
// DIFF + 4 proposals + 4 commit
assertEquals(9, learnerHandler.getQueuedPackets().size());
- queuedPacketMatches(new long[] { 5, 6, 7, 8 });
+ queuedPacketMatches(new long[]{5, 6, 7, 8});
reset();
}
@@ -333,8 +333,7 @@ public class LearnerHandlerTest extends ZKTestCase {
// CommmitedLog is empty, we will use txnlog up to lastProcessZxid
db = new MockZKDatabase(null) {
@Override
- public Iterator<Proposal> getProposalsFromTxnLog(long peerZxid,
- long limit) {
+ public Iterator<Proposal> getProposalsFromTxnLog(long peerZxid, long limit) {
return TxnLogProposalIterator.EMPTY_ITERATOR;
}
};
@@ -345,8 +344,7 @@ public class LearnerHandlerTest extends ZKTestCase {
// Peer zxid
peerZxid = 4;
- assertTrue("Couldn't identify snapshot transfer!",
- learnerHandler.syncFollower(peerZxid, leader));
+ assertTrue("Couldn't identify snapshot transfer!", learnerHandler.syncFollower(peerZxid, leader));
reset();
}
@@ -374,7 +372,7 @@ public class LearnerHandlerTest extends ZKTestCase {
assertOpType(Leader.TRUNC, 3, db.lastProcessedZxid);
// DIFF + 3 proposals + 3 commit
assertEquals(7, learnerHandler.getQueuedPackets().size());
- queuedPacketMatches(new long[] { 5, 6, 7 });
+ queuedPacketMatches(new long[]{5, 6, 7});
reset();
// Peer has zxid in txnlog range
@@ -384,7 +382,7 @@ public class LearnerHandlerTest extends ZKTestCase {
assertOpType(Leader.DIFF, db.lastProcessedZxid, db.lastProcessedZxid);
// DIFF + 4 proposals + 4 commit
assertEquals(9, learnerHandler.getQueuedPackets().size());
- queuedPacketMatches(new long[] { 3, 5, 6, 7 });
+ queuedPacketMatches(new long[]{3, 5, 6, 7});
reset();
// Peer miss the txnlog
@@ -395,7 +393,7 @@ public class LearnerHandlerTest extends ZKTestCase {
reset();
}
- long getZxid(long epoch, long counter){
+ long getZxid(long epoch, long counter) {
return ZxidUtils.makeZxid(epoch, counter);
}
@@ -425,20 +423,17 @@ public class LearnerHandlerTest extends ZKTestCase {
assertOpType(Leader.TRUNC, getZxid(0xf, 3), db.getmaxCommittedLog());
// DIFF + 4 proposals + 4 commit
assertEquals(9, learnerHandler.getQueuedPackets().size());
- queuedPacketMatches(new long[] { getZxid(0xf, 5),
- getZxid(0xf, 6), getZxid(0xf, 7), getZxid(0xf, 8) });
+ queuedPacketMatches(new long[]{getZxid(0xf, 5), getZxid(0xf, 6), getZxid(0xf, 7), getZxid(0xf, 8)});
reset();
// Peer zxid is in txnlog range
peerZxid = getZxid(0xf, 3);
assertFalse(learnerHandler.syncFollower(peerZxid, leader));
// We send DIFF and forward any packet starting at maxCommittedLog
- assertOpType(Leader.DIFF, db.getmaxCommittedLog(),
- db.getmaxCommittedLog());
+ assertOpType(Leader.DIFF, db.getmaxCommittedLog(), db.getmaxCommittedLog());
// DIFF + 4 proposals + 4 commit
assertEquals(9, learnerHandler.getQueuedPackets().size());
- queuedPacketMatches(new long[] { getZxid(0xf, 5),
- getZxid(0xf, 6), getZxid(0xf, 7), getZxid(0xf, 8) });
+ queuedPacketMatches(new long[]{getZxid(0xf, 5), getZxid(0xf, 6), getZxid(0xf, 7), getZxid(0xf, 8)});
reset();
}
@@ -473,7 +468,7 @@ public class LearnerHandlerTest extends ZKTestCase {
assertOpType(Leader.DIFF, getZxid(1, 2), getZxid(1, 2));
// DIFF + 2 proposals + 2 commit
assertEquals(5, learnerHandler.getQueuedPackets().size());
- queuedPacketMatches(new long[] { getZxid(1, 1), getZxid(1, 2)});
+ queuedPacketMatches(new long[]{getZxid(1, 1), getZxid(1, 2)});
reset();
// Peer has zxid of epoch 2, so it is already sync
@@ -515,7 +510,7 @@ public class LearnerHandlerTest extends ZKTestCase {
assertOpType(Leader.DIFF, getZxid(1, 2), getZxid(1, 2));
// DIFF + 2 proposals + 2 commit
assertEquals(5, learnerHandler.getQueuedPackets().size());
- queuedPacketMatches(new long[] { getZxid(1, 1), getZxid(1, 2)});
+ queuedPacketMatches(new long[]{getZxid(1, 1), getZxid(1, 2)});
reset();
}
@@ -563,4 +558,5 @@ public class LearnerHandlerTest extends ZKTestCase {
assertTrue(learnerHandler.syncFollower(peerZxid, leader));
reset();
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/LearnerMetricsTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/LearnerMetricsTest.java
index b3df3ca53..b7b8c5aa4 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/LearnerMetricsTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/LearnerMetricsTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,6 +18,10 @@
package org.apache.zookeeper.server.quorum;
+import static org.hamcrest.core.Is.is;
+import static org.hamcrest.number.OrderingComparison.greaterThanOrEqualTo;
+import java.util.HashMap;
+import java.util.Map;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.PortAssignment;
import org.apache.zookeeper.ZooDefs;
@@ -29,12 +33,6 @@ import org.hamcrest.Matcher;
import org.junit.After;
import org.junit.Test;
-import java.util.HashMap;
-import java.util.Map;
-
-import static org.hamcrest.core.Is.is;
-import static org.hamcrest.number.OrderingComparison.greaterThanOrEqualTo;
-
public class LearnerMetricsTest extends QuorumPeerTestBase {
private static final int TIMEOUT_SECONDS = 30;
@@ -51,17 +49,17 @@ public class LearnerMetricsTest extends QuorumPeerTestBase {
final byte[] data = new byte[512];
final int[] clientPorts = new int[SERVER_COUNT];
StringBuilder sb = new StringBuilder();
- int observer = 0 ;
+ int observer = 0;
clientPorts[observer] = PortAssignment.unique();
- sb.append("server."+observer+"=127.0.0.1:"+PortAssignment.unique()+":"+PortAssignment.unique()+":observer\n");
- for(int i = 1; i < SERVER_COUNT; i++) {
+ sb.append("server." + observer + "=127.0.0.1:" + PortAssignment.unique() + ":" + PortAssignment.unique() + ":observer\n");
+ for (int i = 1; i < SERVER_COUNT; i++) {
clientPorts[i] = PortAssignment.unique();
- sb.append("server."+i+"=127.0.0.1:"+PortAssignment.unique()+":"+PortAssignment.unique()+"\n");
+ sb.append("server." + i + "=127.0.0.1:" + PortAssignment.unique() + ":" + PortAssignment.unique() + "\n");
}
// start the participants
String quorumCfgSection = sb.toString();
- for(int i = 1; i < SERVER_COUNT; i++) {
+ for (int i = 1; i < SERVER_COUNT; i++) {
mt[i] = new QuorumPeerTestBase.MainThread(i, clientPorts[i], quorumCfgSection);
mt[i].start();
}
@@ -92,23 +90,22 @@ public class LearnerMetricsTest extends QuorumPeerTestBase {
private void waitForMetric(final String metricKey, final Matcher<Long> matcher) throws InterruptedException {
final String errorMessage = String.format("unable to match on metric: %s", metricKey);
- waitFor(errorMessage,
- () -> {
- long actual = (long) MetricsUtils.currentServerMetrics().get(metricKey);
- if(!matcher.matches(actual)) {
- LOG.info(String.format("match failed on %s, actual value: %d", metricKey, actual));
- return false;
- }
- return true;
- },
- TIMEOUT_SECONDS);
+ waitFor(errorMessage, () -> {
+ long actual = (long) MetricsUtils.currentServerMetrics().get(metricKey);
+ if (!matcher.matches(actual)) {
+ LOG.info(String.format("match failed on %s, actual value: %d", metricKey, actual));
+ return false;
+ }
+ return true;
+ }, TIMEOUT_SECONDS);
}
@After
public void tearDown() throws Exception {
zk_client.close();
- for(int i = 0; i < SERVER_COUNT; i++) {
+ for (int i = 0; i < SERVER_COUNT; i++) {
mt[i].shutdown();
}
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/LearnerSyncThrottlerTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/LearnerSyncThrottlerTest.java
index d3ce47b2d..9c6385e41 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/LearnerSyncThrottlerTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/LearnerSyncThrottlerTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,6 +18,9 @@
package org.apache.zookeeper.server.quorum;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
@@ -27,9 +30,7 @@ import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
-
import org.apache.zookeeper.ZKTestCase;
-import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
@@ -38,22 +39,21 @@ import org.slf4j.LoggerFactory;
@RunWith(Parameterized.class)
public class LearnerSyncThrottlerTest extends ZKTestCase {
+
private static final Logger LOG = LoggerFactory.getLogger(LearnerSyncThrottlerTest.class);
private LearnerSyncThrottler.SyncType syncType;
- public LearnerSyncThrottlerTest(LearnerSyncThrottler.SyncType syncType){
+ public LearnerSyncThrottlerTest(LearnerSyncThrottler.SyncType syncType) {
this.syncType = syncType;
}
@Parameterized.Parameters
public static Collection syncTypes() {
- return Arrays.asList(new Object[][]{
- {LearnerSyncThrottler.SyncType.DIFF}, {LearnerSyncThrottler.SyncType.SNAP}});
+ return Arrays.asList(new Object[][]{{LearnerSyncThrottler.SyncType.DIFF}, {LearnerSyncThrottler.SyncType.SNAP}});
}
@Test(expected = SyncThrottleException.class)
public void testTooManySyncsNonessential() throws Exception {
- LearnerSyncThrottler throttler =
- new LearnerSyncThrottler(5, syncType);
+ LearnerSyncThrottler throttler = new LearnerSyncThrottler(5, syncType);
for (int i = 0; i < 6; i++) {
throttler.beginSync(false);
}
@@ -61,14 +61,13 @@ public class LearnerSyncThrottlerTest extends ZKTestCase {
@Test(expected = SyncThrottleException.class)
public void testTooManySyncsEssential() throws Exception {
- LearnerSyncThrottler throttler =
- new LearnerSyncThrottler(5, syncType);
+ LearnerSyncThrottler throttler = new LearnerSyncThrottler(5, syncType);
try {
for (int i = 0; i < 6; i++) {
throttler.beginSync(true);
}
} catch (SyncThrottleException ex) {
- Assert.fail("essential syncs should not be throttled");
+ fail("essential syncs should not be throttled");
}
throttler.endSync();
throttler.beginSync(false);
@@ -76,32 +75,29 @@ public class LearnerSyncThrottlerTest extends ZKTestCase {
@Test
public void testNoThrottle() throws Exception {
- LearnerSyncThrottler throttler =
- new LearnerSyncThrottler(5, syncType);
+ LearnerSyncThrottler throttler = new LearnerSyncThrottler(5, syncType);
try {
for (int i = 0; i < 6; i++) {
throttler.beginSync(true);
}
- }
- catch (SyncThrottleException ex) {
- Assert.fail("essential syncs should not be throttled");
+ } catch (SyncThrottleException ex) {
+ fail("essential syncs should not be throttled");
}
throttler.endSync();
for (int i = 0; i < 5; i++) {
throttler.endSync();
throttler.beginSync(false);
}
- Assert.assertTrue("should get here without exception", true);
+ assertTrue("should get here without exception", true);
}
@Test
public void testTryWithResourceNoThrottle() throws Exception {
- LearnerSyncThrottler throttler =
- new LearnerSyncThrottler(1, syncType);
+ LearnerSyncThrottler throttler = new LearnerSyncThrottler(1, syncType);
for (int i = 0; i < 3; i++) {
throttler.beginSync(false);
try {
- Assert.assertEquals(1, throttler.getSyncInProgress());
+ assertEquals(1, throttler.getSyncInProgress());
} finally {
throttler.endSync();
}
@@ -110,18 +106,17 @@ public class LearnerSyncThrottlerTest extends ZKTestCase {
@Test
public void testTryWithResourceThrottle() throws Exception {
- LearnerSyncThrottler throttler =
- new LearnerSyncThrottler(1, syncType);
+ LearnerSyncThrottler throttler = new LearnerSyncThrottler(1, syncType);
try {
throttler.beginSync(true);
try {
throttler.beginSync(false);
- Assert.fail("shouldn't be able to have both syncs open");
+ fail("shouldn't be able to have both syncs open");
} catch (SyncThrottleException e) {
}
throttler.endSync();
} catch (SyncThrottleException e) {
- Assert.fail("First sync shouldn't be throttled");
+ fail("First sync shouldn't be throttled");
}
}
@@ -129,8 +124,7 @@ public class LearnerSyncThrottlerTest extends ZKTestCase {
public void testParallelNoThrottle() {
final int numThreads = 50;
- final LearnerSyncThrottler throttler =
- new LearnerSyncThrottler(numThreads, syncType);
+ final LearnerSyncThrottler throttler = new LearnerSyncThrottler(numThreads, syncType);
ExecutorService threadPool = Executors.newFixedThreadPool(numThreads);
final CountDownLatch threadStartLatch = new CountDownLatch(numThreads);
final CountDownLatch syncProgressLatch = new CountDownLatch(numThreads);
@@ -162,12 +156,13 @@ public class LearnerSyncThrottlerTest extends ZKTestCase {
try {
for (Future<Boolean> result : results) {
- Assert.assertTrue(result.get());
+ assertTrue(result.get());
}
- } catch (Exception e){
+ } catch (Exception e) {
} finally {
threadPool.shutdown();
}
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/LearnerTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/LearnerTest.java
index 7eccf6089..88647a22b 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/LearnerTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/LearnerTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,6 +18,9 @@
package org.apache.zookeeper.server.quorum;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
@@ -27,7 +30,6 @@ import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.ArrayList;
-
import org.apache.jute.BinaryInputArchive;
import org.apache.jute.BinaryOutputArchive;
import org.apache.zookeeper.ZKTestCase;
@@ -38,19 +40,17 @@ import org.apache.zookeeper.server.persistence.FileTxnSnapLog;
import org.apache.zookeeper.test.TestUtils;
import org.apache.zookeeper.txn.CreateTxn;
import org.apache.zookeeper.txn.TxnHeader;
-import org.junit.Assert;
import org.junit.Test;
public class LearnerTest extends ZKTestCase {
- private static final File testData = new File(
- System.getProperty("test.data.dir", "src/test/resources/data"));
+
+ private static final File testData = new File(System.getProperty("test.data.dir", "src/test/resources/data"));
static class SimpleLearnerZooKeeperServer extends LearnerZooKeeperServer {
Learner learner;
- public SimpleLearnerZooKeeperServer(FileTxnSnapLog ftsl, QuorumPeer self)
- throws IOException {
+ public SimpleLearnerZooKeeperServer(FileTxnSnapLog ftsl, QuorumPeer self) throws IOException {
super(ftsl, 2000, 2000, 2000, -1, new ZKDatabase(ftsl), self);
}
@@ -58,17 +58,21 @@ public class LearnerTest extends ZKTestCase {
public Learner getLearner() {
return learner;
}
+
}
static class SimpleLearner extends Learner {
+
SimpleLearner(FileTxnSnapLog ftsl) throws IOException {
self = new QuorumPeer();
zk = new SimpleLearnerZooKeeperServer(ftsl, self);
((SimpleLearnerZooKeeperServer) zk).learner = this;
}
+
}
static class TimeoutLearner extends Learner {
+
int passSocketConnectOnAttempt = 10;
int socketConnectAttempt = 0;
long timeMultiplier = 0;
@@ -84,21 +88,21 @@ public class LearnerTest extends ZKTestCase {
protected long nanoTime() {
return socketConnectAttempt * timeMultiplier;
}
-
+
protected int getSockConnectAttempt() {
return socketConnectAttempt;
}
@Override
- protected void sockConnect(Socket sock, InetSocketAddress addr, int timeout)
- throws IOException {
- if (++socketConnectAttempt < passSocketConnectOnAttempt) {
+ protected void sockConnect(Socket sock, InetSocketAddress addr, int timeout) throws IOException {
+ if (++socketConnectAttempt < passSocketConnectOnAttempt) {
throw new IOException("Test injected Socket.connect() error.");
}
}
+
}
- @Test(expected=IOException.class)
+ @Test(expected = IOException.class)
public void connectionRetryTimeoutTest() throws Exception {
Learner learner = new TimeoutLearner();
learner.self = new QuorumPeer();
@@ -122,43 +126,43 @@ public class LearnerTest extends ZKTestCase {
// this addr won't even be used since we fake the Socket.connect
InetSocketAddress addr = new InetSocketAddress(1111);
-
+
// pretend each connect attempt takes 4000 milliseconds
- learner.setTimeMultiplier((long)4000 * 1000000);
-
+ learner.setTimeMultiplier((long) 4000 * 1000000);
+
learner.setPassConnectAttempt(5);
// we expect this to throw an IOException since we're faking socket connect errors every time
try {
learner.connectToLeader(addr, "");
- Assert.fail("should have thrown IOException!");
+ fail("should have thrown IOException!");
} catch (IOException e) {
//good, wanted to see that, let's make sure we ran out of time
- Assert.assertTrue(learner.nanoTime() > 2000*5*1000000);
- Assert.assertEquals(3, learner.getSockConnectAttempt());
+ assertTrue(learner.nanoTime() > 2000 * 5 * 1000000);
+ assertEquals(3, learner.getSockConnectAttempt());
}
}
@Test
public void connectToLearnerMasterLimitTest() throws Exception {
- TimeoutLearner learner = new TimeoutLearner();
- learner.self = new QuorumPeer();
- learner.self.setTickTime(2000);
- learner.self.setInitLimit(2);
- learner.self.setSyncLimit(2);
- learner.self.setConnectToLearnerMasterLimit(5);
-
- InetSocketAddress addr = new InetSocketAddress(1111);
- learner.setTimeMultiplier((long)4000 * 1000000);
- learner.setPassConnectAttempt(5);
-
- try {
- learner.connectToLeader(addr, "");
- Assert.fail("should have thrown IOException!");
- } catch (IOException e) {
- Assert.assertTrue(learner.nanoTime() > 2000*5*1000000);
- Assert.assertEquals(3, learner.getSockConnectAttempt());
- }
+ TimeoutLearner learner = new TimeoutLearner();
+ learner.self = new QuorumPeer();
+ learner.self.setTickTime(2000);
+ learner.self.setInitLimit(2);
+ learner.self.setSyncLimit(2);
+ learner.self.setConnectToLearnerMasterLimit(5);
+
+ InetSocketAddress addr = new InetSocketAddress(1111);
+ learner.setTimeMultiplier((long) 4000 * 1000000);
+ learner.setPassConnectAttempt(5);
+
+ try {
+ learner.connectToLeader(addr, "");
+ fail("should have thrown IOException!");
+ } catch (IOException e) {
+ assertTrue(learner.nanoTime() > 2000 * 5 * 1000000);
+ assertEquals(3, learner.getSockConnectAttempt());
+ }
}
@Test
@@ -199,13 +203,15 @@ public class LearnerTest extends ZKTestCase {
try {
sl.syncWithLeader(3);
- } catch (EOFException e) {}
+ } catch (EOFException e) {
+ }
sl.zk.shutdown();
sl = new SimpleLearner(ftsl);
- Assert.assertEquals(startZxid, sl.zk.getLastProcessedZxid());
+ assertEquals(startZxid, sl.zk.getLastProcessedZxid());
} finally {
TestUtils.deleteFileRecursively(tmpFile);
}
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/LocalPeerBeanTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/LocalPeerBeanTest.java
index 3554aac56..c15fd5b9e 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/LocalPeerBeanTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/LocalPeerBeanTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -19,13 +19,12 @@
package org.apache.zookeeper.server.quorum;
import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
-
import java.net.InetAddress;
import java.net.InetSocketAddress;
import org.apache.zookeeper.PortAssignment;
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/QuorumBeanTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/QuorumBeanTest.java
index 650dc8286..0f9a8accb 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/QuorumBeanTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/QuorumBeanTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,14 +18,14 @@
package org.apache.zookeeper.server.quorum;
-import org.junit.Test;
-
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
+import org.junit.Test;
public class QuorumBeanTest {
+
@Test
public void testGetNameProperty() {
QuorumPeer qpMock = mock(QuorumPeer.class);
@@ -72,4 +72,5 @@ public class QuorumBeanTest {
when(qpMock.shouldUsePortUnification()).thenReturn(false);
assertThat("isPortUnification property should return value of peer.shouldUsePortUnification()", qb.isPortUnification(), equalTo(false));
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/QuorumPeerConfigTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/QuorumPeerConfigTest.java
index 0bfb17dc5..0d7e7cce0 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/QuorumPeerConfigTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/QuorumPeerConfigTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,26 +18,26 @@
package org.apache.zookeeper.server.quorum;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
import java.io.File;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.Properties;
-
import org.apache.zookeeper.common.ClientX509Util;
-import org.apache.zookeeper.server.quorum.QuorumPeerConfig.ConfigException;
import org.apache.zookeeper.server.quorum.QuorumPeer.QuorumServer;
+import org.apache.zookeeper.server.quorum.QuorumPeerConfig.ConfigException;
import org.junit.Test;
-import static org.junit.Assert.*;
-
public class QuorumPeerConfigTest {
/**
* test case for https://issues.apache.org/jira/browse/ZOOKEEPER-2264
*/
@Test
- public void testErrorMessageWhensecureClientPortNotSetButsecureClientPortAddressSet()
- throws IOException, ConfigException {
+ public void testErrorMessageWhensecureClientPortNotSetButsecureClientPortAddressSet() throws IOException, ConfigException {
QuorumPeerConfig quorumPeerConfig = new QuorumPeerConfig();
try {
Properties zkProp = getDefaultZKProperties();
@@ -51,12 +51,11 @@ public class QuorumPeerConfigTest {
}
/**
- *
+ *
* Test case for https://issues.apache.org/jira/browse/ZOOKEEPER-2264
*/
@Test
- public void testErrorMessageWhenclientPortNotSetButclientPortAddressSet()
- throws IOException, ConfigException {
+ public void testErrorMessageWhenclientPortNotSetButclientPortAddressSet() throws IOException, ConfigException {
QuorumPeerConfig quorumPeerConfig = new QuorumPeerConfig();
try {
Properties zkProp = getDefaultZKProperties();
@@ -73,8 +72,7 @@ public class QuorumPeerConfigTest {
* https://issues.apache.org/jira/browse/ZOOKEEPER-2297
*/
@Test
- public void testConfigureSSLAuthGetsConfiguredIfSecurePortConfigured()
- throws IOException, ConfigException {
+ public void testConfigureSSLAuthGetsConfiguredIfSecurePortConfigured() throws IOException, ConfigException {
String sslAuthProp = "zookeeper.authProvider.x509";
QuorumPeerConfig quorumPeerConfig = new QuorumPeerConfig();
Properties zkProp = getDefaultZKProperties();
@@ -82,7 +80,7 @@ public class QuorumPeerConfigTest {
quorumPeerConfig.parseProperties(zkProp);
String expected = "org.apache.zookeeper.server.auth.X509AuthenticationProvider";
String result = System.getProperty(sslAuthProp);
- assertEquals(expected, result);
+ assertEquals(expected, result);
}
/**
@@ -119,17 +117,18 @@ public class QuorumPeerConfigTest {
* Extend the existing QuorumPeerConfig to set the server id.
*/
public static class MockQuorumPeerConfig extends QuorumPeerConfig {
+
public MockQuorumPeerConfig(long serverId) {
this.serverId = serverId;
}
+
}
/**
* Test case for https://issues.apache.org/jira/browse/ZOOKEEPER-2847
*/
@Test
- public void testClientAddrFromClientPort()
- throws IOException, ConfigException {
+ public void testClientAddrFromClientPort() throws IOException, ConfigException {
long serverId = 1;
QuorumPeerConfig quorumPeerConfig = new MockQuorumPeerConfig(serverId);
Properties zkProp = getDefaultZKProperties();
@@ -138,17 +137,14 @@ public class QuorumPeerConfigTest {
zkProp.setProperty("server.1", "127.0.0.1:2889:3889:participant");
quorumPeerConfig.parseProperties(zkProp);
- QuorumServer qs =
- quorumPeerConfig.getQuorumVerifier().getAllMembers().get(serverId);
- InetSocketAddress expectedAddress =
- new InetSocketAddress("0.0.0.0", clientPort);
+ QuorumServer qs = quorumPeerConfig.getQuorumVerifier().getAllMembers().get(serverId);
+ InetSocketAddress expectedAddress = new InetSocketAddress("0.0.0.0", clientPort);
assertEquals(expectedAddress, quorumPeerConfig.getClientPortAddress());
assertEquals(quorumPeerConfig.getClientPortAddress(), qs.clientAddr);
}
@Test
- public void testJvmPauseMonitorConfigured()
- throws IOException, ConfigException {
+ public void testJvmPauseMonitorConfigured() throws IOException, ConfigException {
final Long sleepTime = 444L;
final Long warnTH = 5555L;
final Long infoTH = 555L;
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/QuorumPeerMainTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/QuorumPeerMainTest.java
index a0bbc09de..a5cf9b8a9 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/QuorumPeerMainTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/QuorumPeerMainTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -20,16 +20,22 @@ package org.apache.zookeeper.server.quorum;
import static org.apache.zookeeper.test.ClientBase.CONNECTION_TIMEOUT;
import static org.apache.zookeeper.test.ClientBase.createEmptyTestDir;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doCallRealMethod;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
-
import java.io.ByteArrayOutputStream;
import java.io.File;
+import java.io.IOException;
import java.io.LineNumberReader;
import java.io.StringReader;
-import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
@@ -40,7 +46,6 @@ import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.regex.Pattern;
import javax.security.sasl.SaslException;
-
import org.apache.commons.io.FileUtils;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
@@ -50,9 +55,9 @@ import org.apache.zookeeper.AsyncCallback;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.PortAssignment;
+import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooDefs.OpCode;
import org.apache.zookeeper.ZooKeeper;
-import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper.States;
import org.apache.zookeeper.common.Time;
import org.apache.zookeeper.common.X509Exception;
@@ -62,7 +67,6 @@ import org.apache.zookeeper.metrics.impl.NullMetricsProvider;
import org.apache.zookeeper.server.persistence.FileTxnSnapLog;
import org.apache.zookeeper.server.quorum.Leader.Proposal;
import org.apache.zookeeper.test.ClientBase;
-import org.junit.Assert;
import org.junit.Test;
/**
@@ -80,63 +84,55 @@ public class QuorumPeerMainTest extends QuorumPeerTestBase {
final int CLIENT_PORT_QP1 = PortAssignment.unique();
final int CLIENT_PORT_QP2 = PortAssignment.unique();
- String quorumCfgSection = String.format("server.1=%1$s:%2$s:%3$s;%4$s",
- addr,
- PortAssignment.unique(),
- PortAssignment.unique(),
- CLIENT_PORT_QP1) + "\n" +
- String.format("server.2=%1$s:%2$s:%3$s;%4$s",
- addr,
- PortAssignment.unique(),
- PortAssignment.unique(),
- CLIENT_PORT_QP2);
+ String server1 = String.format("server.1=%1$s:%2$s:%3$s;%4$s", addr, PortAssignment.unique(), PortAssignment.unique(), CLIENT_PORT_QP1);
+ String server2 = String.format("server.2=%1$s:%2$s:%3$s;%4$s", addr, PortAssignment.unique(), PortAssignment.unique(), CLIENT_PORT_QP2);
+
+ String quorumCfgSection = server1 + "\n" + server2;
MainThread q1 = new MainThread(1, CLIENT_PORT_QP1, quorumCfgSection);
MainThread q2 = new MainThread(2, CLIENT_PORT_QP2, quorumCfgSection);
q1.start();
q2.start();
- Assert.assertTrue("waiting for server 1 being up",
- ClientBase.waitForServerUp(addr + ":" + CLIENT_PORT_QP1,
- CONNECTION_TIMEOUT));
- Assert.assertTrue("waiting for server 2 being up",
- ClientBase.waitForServerUp(addr + ":" + CLIENT_PORT_QP2,
- CONNECTION_TIMEOUT));
+ assertTrue(
+ "waiting for server 1 being up",
+ ClientBase.waitForServerUp(addr + ":" + CLIENT_PORT_QP1, CONNECTION_TIMEOUT));
+ assertTrue(
+ "waiting for server 2 being up",
+ ClientBase.waitForServerUp(addr + ":" + CLIENT_PORT_QP2, CONNECTION_TIMEOUT));
QuorumPeer quorumPeer = q1.main.quorumPeer;
int tickTime = quorumPeer.getTickTime();
- Assert.assertEquals(
+ assertEquals(
"Default value of minimumSessionTimeOut is not considered",
- tickTime * 2, quorumPeer.getMinSessionTimeout());
- Assert.assertEquals(
+ tickTime * 2,
+ quorumPeer.getMinSessionTimeout());
+ assertEquals(
"Default value of maximumSessionTimeOut is not considered",
- tickTime * 20, quorumPeer.getMaxSessionTimeout());
+ tickTime * 20,
+ quorumPeer.getMaxSessionTimeout());
- ZooKeeper zk = new ZooKeeper(addr + ":" + CLIENT_PORT_QP1,
- ClientBase.CONNECTION_TIMEOUT, this);
+ ZooKeeper zk = new ZooKeeper(addr + ":" + CLIENT_PORT_QP1, ClientBase.CONNECTION_TIMEOUT, this);
waitForOne(zk, States.CONNECTED);
- zk.create("/foo_q1", "foobar1".getBytes(), Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
- Assert.assertEquals(new String(zk.getData("/foo_q1", null, null)), "foobar1");
+ zk.create("/foo_q1", "foobar1".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
+ assertEquals(new String(zk.getData("/foo_q1", null, null)), "foobar1");
zk.close();
- zk = new ZooKeeper(addr + ":" + CLIENT_PORT_QP2,
- ClientBase.CONNECTION_TIMEOUT, this);
+ zk = new ZooKeeper(addr + ":" + CLIENT_PORT_QP2, ClientBase.CONNECTION_TIMEOUT, this);
waitForOne(zk, States.CONNECTED);
- zk.create("/foo_q2", "foobar2".getBytes(), Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
- Assert.assertEquals(new String(zk.getData("/foo_q2", null, null)), "foobar2");
+ zk.create("/foo_q2", "foobar2".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
+ assertEquals(new String(zk.getData("/foo_q2", null, null)), "foobar2");
zk.close();
q1.shutdown();
q2.shutdown();
- Assert.assertTrue("waiting for server 1 down",
- ClientBase.waitForServerDown(addr + ":" + CLIENT_PORT_QP1,
- ClientBase.CONNECTION_TIMEOUT));
- Assert.assertTrue("waiting for server 2 down",
- ClientBase.waitForServerDown(addr + ":" + CLIENT_PORT_QP2,
- ClientBase.CONNECTION_TIMEOUT));
+ assertTrue(
+ "waiting for server 1 down",
+ ClientBase.waitForServerDown(addr + ":" + CLIENT_PORT_QP1, ClientBase.CONNECTION_TIMEOUT));
+ assertTrue(
+ "waiting for server 2 down",
+ ClientBase.waitForServerDown(addr + ":" + CLIENT_PORT_QP2, ClientBase.CONNECTION_TIMEOUT));
}
/**
@@ -162,16 +158,16 @@ public class QuorumPeerMainTest extends QuorumPeerTestBase {
public void testEarlyLeaderAbandonment() throws Exception {
ClientBase.setupTestEnv();
final int SERVER_COUNT = 3;
- final int clientPorts[] = new int[SERVER_COUNT];
+ final int[] clientPorts = new int[SERVER_COUNT];
StringBuilder sb = new StringBuilder();
- for(int i = 0; i < SERVER_COUNT; i++) {
- clientPorts[i] = PortAssignment.unique();
- sb.append("server."+i+"=127.0.0.1:"+PortAssignment.unique()+":"+PortAssignment.unique()+";"+clientPorts[i]+"\n");
+ for (int i = 0; i < SERVER_COUNT; i++) {
+ clientPorts[i] = PortAssignment.unique();
+ sb.append("server." + i + "=127.0.0.1:" + PortAssignment.unique() + ":" + PortAssignment.unique() + ";" + clientPorts[i] + "\n");
}
String quorumCfgSection = sb.toString();
- MainThread mt[] = new MainThread[SERVER_COUNT];
- ZooKeeper zk[] = new ZooKeeper[SERVER_COUNT];
+ MainThread[] mt = new MainThread[SERVER_COUNT];
+ ZooKeeper[] zk = new ZooKeeper[SERVER_COUNT];
for (int i = 0; i < SERVER_COUNT; i++) {
mt[i] = new MainThread(i, clientPorts[i], quorumCfgSection);
mt[i].start();
@@ -192,11 +188,10 @@ public class QuorumPeerMainTest extends QuorumPeerTestBase {
mt[i].start();
// Recreate a client session since the previous session was not persisted.
zk[i] = new ZooKeeper("127.0.0.1:" + clientPorts[i], ClientBase.CONNECTION_TIMEOUT, this);
- }
+ }
waitForAll(zk, States.CONNECTED);
-
// ok lets find the leader and kill everything else, we have a few
// seconds, so it should be plenty of time
int leader = -1;
@@ -211,15 +206,15 @@ public class QuorumPeerMainTest extends QuorumPeerTestBase {
}
try {
- zk[leader].create("/zk" + leader, "zk".getBytes(), Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
- Assert.fail("create /zk" + leader + " should have failed");
- } catch (KeeperException e) {}
+ zk[leader].create("/zk" + leader, "zk".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
+ fail("create /zk" + leader + " should have failed");
+ } catch (KeeperException e) {
+ }
// just make sure that we actually did get it in process at the
// leader
- Assert.assertTrue(outstanding.size() == 1);
- Assert.assertTrue(((Proposal) outstanding.values().iterator().next()).request.getHdr().getType() == OpCode.create);
+ assertTrue(outstanding.size() == 1);
+ assertTrue(outstanding.values().iterator().next().request.getHdr().getType() == OpCode.create);
// make sure it has a chance to write it to disk
Thread.sleep(1000);
mt[leader].shutdown();
@@ -244,9 +239,13 @@ public class QuorumPeerMainTest extends QuorumPeerTestBase {
for (int i = 0; i < SERVER_COUNT; i++) {
for (int j = 0; j < SERVER_COUNT; j++) {
if (i == leader) {
- Assert.assertTrue((j == leader ? ("Leader (" + leader + ")") : ("Follower " + j)) + " should not have /zk" + i, zk[j].exists("/zk" + i, false) == null);
+ assertTrue((j == leader ? ("Leader (" + leader + ")") : ("Follower " + j))
+ + " should not have /zk"
+ + i, zk[j].exists("/zk" + i, false) == null);
} else {
- Assert.assertTrue((j == leader ? ("Leader (" + leader + ")") : ("Follower " + j)) + " does not have /zk" + i, zk[j].exists("/zk" + i, false) != null);
+ assertTrue((j == leader ? ("Leader (" + leader + ")") : ("Follower " + j))
+ + " does not have /zk"
+ + i, zk[j].exists("/zk" + i, false) != null);
}
}
}
@@ -271,7 +270,7 @@ public class QuorumPeerMainTest extends QuorumPeerTestBase {
int leader = servers.findLeader();
// make sure there is a leader
- Assert.assertTrue("There should be a leader", leader >= 0);
+ assertTrue("There should be a leader", leader >= 0);
int nonleader = (leader + 1) % numServers;
@@ -322,9 +321,7 @@ public class QuorumPeerMainTest extends QuorumPeerTestBase {
// validate that the old value is there and not the new one
output = servers.zk[nonleader].getData(path + leader, false, null);
- Assert.assertEquals(
- "Expecting old value 1 since 2 isn't committed yet",
- output[0], 1);
+ assertEquals("Expecting old value 1 since 2 isn't committed yet", output[0], 1);
// Do some other update, so we bump the maxCommttedZxid
// by setting the value to 2
@@ -338,15 +335,11 @@ public class QuorumPeerMainTest extends QuorumPeerTestBase {
// make sure it doesn't have the new value that it alone had logged
output = servers.zk[leader].getData(path + leader, false, null);
- Assert.assertEquals(
- "Validating that the deposed leader has rolled back that change it had written",
- output[0], 1);
+ assertEquals("Validating that the deposed leader has rolled back that change it had written", output[0], 1);
// make sure the leader has the subsequent changes that were made while it was offline
output = servers.zk[leader].getData(path + nonleader, false, null);
- Assert.assertEquals(
- "Validating that the deposed leader caught up on changes it missed",
- output[0], 2);
+ assertEquals("Validating that the deposed leader caught up on changes it missed", output[0], 2);
}
/**
@@ -372,68 +365,72 @@ public class QuorumPeerMainTest extends QuorumPeerTestBase {
boolean foundFollowing = false;
try {
- // spin up a quorum, we use a small ticktime to make the test run faster
- servers = LaunchServers(numServers, 500);
-
- // find the leader
- int trueLeader = servers.findLeader();
- Assert.assertTrue("There should be a leader", trueLeader >= 0);
-
- // find a follower
- int falseLeader = (trueLeader + 1) % numServers;
- Assert.assertTrue("All servers should join the quorum", servers.mt[falseLeader].main.quorumPeer.follower != null);
-
- // to keep the quorum peer running and force it to go into the looking state, we kill leader election
- // and close the connection to the leader
- servers.mt[falseLeader].main.quorumPeer.electionAlg.shutdown();
- servers.mt[falseLeader].main.quorumPeer.follower.getSocket().close();
-
- // wait for the falseLeader to disconnect
- waitForOne(servers.zk[falseLeader], States.CONNECTING);
-
- // convince falseLeader that it is the leader
- servers.mt[falseLeader].main.quorumPeer.setPeerState(QuorumPeer.ServerState.LEADING);
-
- // provide time for the falseleader to realize no followers have connected
- // (this is twice the timeout used in Leader#getEpochToPropose)
- Thread.sleep(2 * servers.mt[falseLeader].main.quorumPeer.initLimit * servers.mt[falseLeader].main.quorumPeer.tickTime);
-
- // Restart leader election
- servers.mt[falseLeader].main.quorumPeer.startLeaderElection();
-
- // The previous client connection to falseLeader likely closed, create a new one
- servers.zk[falseLeader] = new ZooKeeper("127.0.0.1:" + servers.mt[falseLeader].getClientPort(), ClientBase.CONNECTION_TIMEOUT, this);
-
- // Wait for falseLeader to rejoin the quorum
- waitForOne(servers.zk[falseLeader], States.CONNECTED);
-
- // and ensure trueLeader is still the leader
- Assert.assertTrue(servers.mt[trueLeader].main.quorumPeer.leader != null);
-
- // Look through the logs for output that indicates the falseLeader is LEADING, then LOOKING, then FOLLOWING
- LineNumberReader r = new LineNumberReader(new StringReader(os.toString()));
- Pattern leading = Pattern.compile(".*myid=" + falseLeader + ".*LEADING.*");
- Pattern looking = Pattern.compile(".*myid=" + falseLeader + ".*LOOKING.*");
- Pattern following = Pattern.compile(".*myid=" + falseLeader + ".*FOLLOWING.*");
-
- String line;
- while ((line = r.readLine()) != null) {
- if (!foundLeading) {
- foundLeading = leading.matcher(line).matches();
- } else if(!foundLooking) {
- foundLooking = looking.matcher(line).matches();
- } else if (following.matcher(line).matches()){
- foundFollowing = true;
- break;
+ // spin up a quorum, we use a small ticktime to make the test run faster
+ servers = LaunchServers(numServers, 500);
+
+ // find the leader
+ int trueLeader = servers.findLeader();
+ assertTrue("There should be a leader", trueLeader >= 0);
+
+ // find a follower
+ int falseLeader = (trueLeader + 1) % numServers;
+ assertTrue("All servers should join the quorum", servers.mt[falseLeader].main.quorumPeer.follower
+ != null);
+
+ // to keep the quorum peer running and force it to go into the looking state, we kill leader election
+ // and close the connection to the leader
+ servers.mt[falseLeader].main.quorumPeer.electionAlg.shutdown();
+ servers.mt[falseLeader].main.quorumPeer.follower.getSocket().close();
+
+ // wait for the falseLeader to disconnect
+ waitForOne(servers.zk[falseLeader], States.CONNECTING);
+
+ // convince falseLeader that it is the leader
+ servers.mt[falseLeader].main.quorumPeer.setPeerState(QuorumPeer.ServerState.LEADING);
+
+ // provide time for the falseleader to realize no followers have connected
+ // (this is twice the timeout used in Leader#getEpochToPropose)
+ Thread.sleep(2 * servers.mt[falseLeader].main.quorumPeer.initLimit * servers.mt[falseLeader].main.quorumPeer.tickTime);
+
+ // Restart leader election
+ servers.mt[falseLeader].main.quorumPeer.startLeaderElection();
+
+ // The previous client connection to falseLeader likely closed, create a new one
+ servers.zk[falseLeader] = new ZooKeeper(
+ "127.0.0.1:" + servers.mt[falseLeader].getClientPort(),
+ ClientBase.CONNECTION_TIMEOUT,
+ this);
+
+ // Wait for falseLeader to rejoin the quorum
+ waitForOne(servers.zk[falseLeader], States.CONNECTED);
+
+ // and ensure trueLeader is still the leader
+ assertTrue(servers.mt[trueLeader].main.quorumPeer.leader != null);
+
+ // Look through the logs for output that indicates the falseLeader is LEADING, then LOOKING, then FOLLOWING
+ LineNumberReader r = new LineNumberReader(new StringReader(os.toString()));
+ Pattern leading = Pattern.compile(".*myid=" + falseLeader + ".*LEADING.*");
+ Pattern looking = Pattern.compile(".*myid=" + falseLeader + ".*LOOKING.*");
+ Pattern following = Pattern.compile(".*myid=" + falseLeader + ".*FOLLOWING.*");
+
+ String line;
+ while ((line = r.readLine()) != null) {
+ if (!foundLeading) {
+ foundLeading = leading.matcher(line).matches();
+ } else if (!foundLooking) {
+ foundLooking = looking.matcher(line).matches();
+ } else if (following.matcher(line).matches()) {
+ foundFollowing = true;
+ break;
+ }
}
- }
} finally {
- qlogger.removeAppender(appender);
+ qlogger.removeAppender(appender);
}
- Assert.assertTrue("falseLeader never attempts to become leader", foundLeading);
- Assert.assertTrue("falseLeader never gives up on leadership", foundLooking);
- Assert.assertTrue("falseLeader never rejoins the quorum", foundFollowing);
+ assertTrue("falseLeader never attempts to become leader", foundLeading);
+ assertTrue("falseLeader never gives up on leadership", foundLooking);
+ assertTrue("falseLeader never rejoins the quorum", foundFollowing);
}
/**
@@ -453,26 +450,21 @@ public class QuorumPeerMainTest extends QuorumPeerTestBase {
final int CLIENT_PORT_QP1 = PortAssignment.unique();
final int CLIENT_PORT_QP2 = PortAssignment.unique();
- String quorumCfgSection =
- "server.1=127.0.0.1:" + PortAssignment.unique()
- + ":" + PortAssignment.unique() + ";" + CLIENT_PORT_QP1
- + "\nserver.2=fee.fii.foo.fum:" + PortAssignment.unique()
- + ":" + PortAssignment.unique() + ";" + CLIENT_PORT_QP2;
+ String quorumCfgSection = "server.1=127.0.0.1:" + PortAssignment.unique() + ":" + PortAssignment.unique() + ";" + CLIENT_PORT_QP1
+ + "\nserver.2=fee.fii.foo.fum:" + PortAssignment.unique() + ":" + PortAssignment.unique() + ";" + CLIENT_PORT_QP2;
MainThread q1 = new MainThread(1, CLIENT_PORT_QP1, quorumCfgSection);
q1.start();
- boolean isup =
- ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT_QP1,
- 30000);
+ boolean isup = ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT_QP1, 30000);
- Assert.assertFalse("Server never came up", isup);
+ assertFalse("Server never came up", isup);
q1.shutdown();
- Assert.assertTrue("waiting for server 1 down",
- ClientBase.waitForServerDown("127.0.0.1:" + CLIENT_PORT_QP1,
- ClientBase.CONNECTION_TIMEOUT));
+ assertTrue(
+ "waiting for server 1 down",
+ ClientBase.waitForServerDown("127.0.0.1:" + CLIENT_PORT_QP1, ClientBase.CONNECTION_TIMEOUT));
} finally {
qlogger.removeAppender(appender);
@@ -481,15 +473,14 @@ public class QuorumPeerMainTest extends QuorumPeerTestBase {
LineNumberReader r = new LineNumberReader(new StringReader(os.toString()));
String line;
boolean found = false;
- Pattern p =
- Pattern.compile(".*Cannot open channel to .* at election address .*");
+ Pattern p = Pattern.compile(".*Cannot open channel to .* at election address .*");
while ((line = r.readLine()) != null) {
found = p.matcher(line).matches();
if (found) {
break;
}
}
- Assert.assertTrue("complains about host", found);
+ assertTrue("complains about host", found);
}
/**
@@ -512,13 +503,9 @@ public class QuorumPeerMainTest extends QuorumPeerTestBase {
final int CLIENT_PORT_QP2 = PortAssignment.unique();
final int CLIENT_PORT_QP3 = PortAssignment.unique();
- String quorumCfgSection =
- "server.1=127.0.0.1:" + PortAssignment.unique()
- + ":" + PortAssignment.unique() + ";" + CLIENT_PORT_QP1
- + "\nserver.2=127.0.0.1:" + PortAssignment.unique()
- + ":" + PortAssignment.unique() + ";" + CLIENT_PORT_QP2
- + "\nserver.3=127.0.0.1:" + PortAssignment.unique()
- + ":" + PortAssignment.unique() + ":observer" + ";" + CLIENT_PORT_QP3;
+ String quorumCfgSection = "server.1=127.0.0.1:" + PortAssignment.unique() + ":" + PortAssignment.unique() + ";" + CLIENT_PORT_QP1
+ + "\nserver.2=127.0.0.1:" + PortAssignment.unique() + ":" + PortAssignment.unique() + ";" + CLIENT_PORT_QP2
+ + "\nserver.3=127.0.0.1:" + PortAssignment.unique() + ":" + PortAssignment.unique() + ":observer" + ";" + CLIENT_PORT_QP3;
MainThread q1 = new MainThread(1, CLIENT_PORT_QP1, quorumCfgSection);
MainThread q2 = new MainThread(2, CLIENT_PORT_QP2, quorumCfgSection);
@@ -527,29 +514,29 @@ public class QuorumPeerMainTest extends QuorumPeerTestBase {
q2.start();
q3.start();
- Assert.assertTrue("waiting for server 1 being up",
- ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT_QP1,
- CONNECTION_TIMEOUT));
- Assert.assertTrue("waiting for server 2 being up",
- ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT_QP2,
- CONNECTION_TIMEOUT));
- Assert.assertTrue("waiting for server 3 being up",
- ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT_QP3,
- CONNECTION_TIMEOUT));
+ assertTrue(
+ "waiting for server 1 being up",
+ ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT_QP1, CONNECTION_TIMEOUT));
+ assertTrue(
+ "waiting for server 2 being up",
+ ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT_QP2, CONNECTION_TIMEOUT));
+ assertTrue(
+ "waiting for server 3 being up",
+ ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT_QP3, CONNECTION_TIMEOUT));
q1.shutdown();
q2.shutdown();
q3.shutdown();
- Assert.assertTrue("waiting for server 1 down",
- ClientBase.waitForServerDown("127.0.0.1:" + CLIENT_PORT_QP1,
- ClientBase.CONNECTION_TIMEOUT));
- Assert.assertTrue("waiting for server 2 down",
- ClientBase.waitForServerDown("127.0.0.1:" + CLIENT_PORT_QP2,
- ClientBase.CONNECTION_TIMEOUT));
- Assert.assertTrue("waiting for server 3 down",
- ClientBase.waitForServerDown("127.0.0.1:" + CLIENT_PORT_QP3,
- ClientBase.CONNECTION_TIMEOUT));
+ assertTrue(
+ "waiting for server 1 down",
+ ClientBase.waitForServerDown("127.0.0.1:" + CLIENT_PORT_QP1, ClientBase.CONNECTION_TIMEOUT));
+ assertTrue(
+ "waiting for server 2 down",
+ ClientBase.waitForServerDown("127.0.0.1:" + CLIENT_PORT_QP2, ClientBase.CONNECTION_TIMEOUT));
+ assertTrue(
+ "waiting for server 3 down",
+ ClientBase.waitForServerDown("127.0.0.1:" + CLIENT_PORT_QP3, ClientBase.CONNECTION_TIMEOUT));
} finally {
qlogger.removeAppender(appender);
@@ -559,8 +546,7 @@ public class QuorumPeerMainTest extends QuorumPeerTestBase {
String line;
boolean warningPresent = false;
boolean defaultedToObserver = false;
- Pattern pWarn =
- Pattern.compile(".*Peer type from servers list.* doesn't match peerType.*");
+ Pattern pWarn = Pattern.compile(".*Peer type from servers list.* doesn't match peerType.*");
Pattern pObserve = Pattern.compile(".*OBSERVING.*");
while ((line = r.readLine()) != null) {
if (pWarn.matcher(line).matches()) {
@@ -573,8 +559,7 @@ public class QuorumPeerMainTest extends QuorumPeerTestBase {
break;
}
}
- Assert.assertTrue("Should warn about inconsistent peer type",
- warningPresent && defaultedToObserver);
+ assertTrue("Should warn about inconsistent peer type", warningPresent && defaultedToObserver);
}
/**
@@ -589,23 +574,20 @@ public class QuorumPeerMainTest extends QuorumPeerTestBase {
final int CLIENT_PORT_QP2 = PortAssignment.unique();
int electionPort1 = PortAssignment.unique();
int electionPort2 = PortAssignment.unique();
- String quorumCfgSection =
- "server.1=127.0.0.1:" + PortAssignment.unique()
- + ":" + electionPort1 + ";" + CLIENT_PORT_QP1
- + "\nserver.2=127.0.0.1:" + PortAssignment.unique()
- + ":" + electionPort2 + ";" + CLIENT_PORT_QP2;
+ String quorumCfgSection = "server.1=127.0.0.1:" + PortAssignment.unique() + ":" + electionPort1 + ";" + CLIENT_PORT_QP1
+ + "\nserver.2=127.0.0.1:" + PortAssignment.unique() + ":" + electionPort2 + ";" + CLIENT_PORT_QP2;
MainThread q1 = new MainThread(1, CLIENT_PORT_QP1, quorumCfgSection);
MainThread q2 = new MainThread(2, CLIENT_PORT_QP2, quorumCfgSection);
q1.start();
q2.start();
- Assert.assertTrue("waiting for server 1 being up",
- ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT_QP1,
- CONNECTION_TIMEOUT));
- Assert.assertTrue("waiting for server 2 being up",
- ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT_QP2,
- CONNECTION_TIMEOUT));
+ assertTrue(
+ "waiting for server 1 being up",
+ ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT_QP1, CONNECTION_TIMEOUT));
+ assertTrue(
+ "waiting for server 2 being up",
+ ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT_QP2, CONNECTION_TIMEOUT));
byte[] b = new byte[4];
int length = 1024 * 1024 * 1024;
@@ -620,12 +602,10 @@ public class QuorumPeerMainTest extends QuorumPeerTestBase {
s.write(buff);
s.close();
- ZooKeeper zk = new ZooKeeper("127.0.0.1:" + CLIENT_PORT_QP1,
- ClientBase.CONNECTION_TIMEOUT, this);
+ ZooKeeper zk = new ZooKeeper("127.0.0.1:" + CLIENT_PORT_QP1, ClientBase.CONNECTION_TIMEOUT, this);
waitForOne(zk, States.CONNECTED);
- zk.create("/foo_q1", "foobar1".getBytes(), Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
- Assert.assertEquals(new String(zk.getData("/foo_q1", null, null)), "foobar1");
+ zk.create("/foo_q1", "foobar1".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
+ assertEquals(new String(zk.getData("/foo_q1", null, null)), "foobar1");
zk.close();
q1.shutdown();
q2.shutdown();
@@ -650,33 +630,30 @@ public class QuorumPeerMainTest extends QuorumPeerTestBase {
final int CLIENT_PORT_QP1 = PortAssignment.unique();
final int CLIENT_PORT_QP2 = PortAssignment.unique();
- String quorumCfgSection =
- "server.1=127.0.0.1:" + PortAssignment.unique()
- + ":" + PortAssignment.unique() + ";" + CLIENT_PORT_QP1
- + "\nserver.2=127.0.0.1:" + PortAssignment.unique()
- + ":" + PortAssignment.unique() + ";" + CLIENT_PORT_QP2;
+ String quorumCfgSection = "server.1=127.0.0.1:" + PortAssignment.unique() + ":" + PortAssignment.unique() + ";" + CLIENT_PORT_QP1
+ + "\nserver.2=127.0.0.1:" + PortAssignment.unique() + ":" + PortAssignment.unique() + ";" + CLIENT_PORT_QP2;
MainThread q1 = new MainThread(1, CLIENT_PORT_QP1, quorumCfgSection);
MainThread q2 = new MainThread(2, CLIENT_PORT_QP2, quorumCfgSection);
q1.start();
q2.start();
- Assert.assertTrue("waiting for server 1 being up",
- ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT_QP1,
- CONNECTION_TIMEOUT));
- Assert.assertTrue("waiting for server 2 being up",
- ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT_QP2,
- CONNECTION_TIMEOUT));
+ assertTrue(
+ "waiting for server 1 being up",
+ ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT_QP1, CONNECTION_TIMEOUT));
+ assertTrue(
+ "waiting for server 2 being up",
+ ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT_QP2, CONNECTION_TIMEOUT));
q1.shutdown();
q2.shutdown();
- Assert.assertTrue("waiting for server 1 down",
- ClientBase.waitForServerDown("127.0.0.1:" + CLIENT_PORT_QP1,
- ClientBase.CONNECTION_TIMEOUT));
- Assert.assertTrue("waiting for server 2 down",
- ClientBase.waitForServerDown("127.0.0.1:" + CLIENT_PORT_QP2,
- ClientBase.CONNECTION_TIMEOUT));
+ assertTrue(
+ "waiting for server 1 down",
+ ClientBase.waitForServerDown("127.0.0.1:" + CLIENT_PORT_QP1, ClientBase.CONNECTION_TIMEOUT));
+ assertTrue(
+ "waiting for server 2 down",
+ ClientBase.waitForServerDown("127.0.0.1:" + CLIENT_PORT_QP2, ClientBase.CONNECTION_TIMEOUT));
} finally {
zlogger.removeAppender(appender);
@@ -685,15 +662,14 @@ public class QuorumPeerMainTest extends QuorumPeerTestBase {
LineNumberReader r = new LineNumberReader(new StringReader(os.toString()));
String line;
boolean found = false;
- Pattern p =
- Pattern.compile(".*FastLeaderElection.*");
+ Pattern p = Pattern.compile(".*FastLeaderElection.*");
while ((line = r.readLine()) != null) {
found = p.matcher(line).matches();
if (found) {
break;
}
}
- Assert.assertTrue("fastleaderelection used", found);
+ assertTrue("fastleaderelection used", found);
}
/**
@@ -703,11 +679,8 @@ public class QuorumPeerMainTest extends QuorumPeerTestBase {
public void testQuorumPeerExitTime() throws Exception {
long maxwait = 3000;
final int CLIENT_PORT_QP1 = PortAssignment.unique();
- String quorumCfgSection =
- "server.1=127.0.0.1:" + PortAssignment.unique()
- + ":" + PortAssignment.unique() + ";" + CLIENT_PORT_QP1
- + "\nserver.2=127.0.0.1:" + PortAssignment.unique()
- + ":" + PortAssignment.unique() + ";" + PortAssignment.unique();
+ String quorumCfgSection = "server.1=127.0.0.1:" + PortAssignment.unique() + ":" + PortAssignment.unique() + ";" + CLIENT_PORT_QP1
+ + "\nserver.2=127.0.0.1:" + PortAssignment.unique() + ":" + PortAssignment.unique() + ";" + PortAssignment.unique();
MainThread q1 = new MainThread(1, CLIENT_PORT_QP1, quorumCfgSection);
q1.start();
// Let the notifications timeout
@@ -716,8 +689,7 @@ public class QuorumPeerMainTest extends QuorumPeerTestBase {
q1.shutdown();
long end = Time.currentElapsedTime();
if ((end - start) > maxwait) {
- Assert.fail("QuorumPeer took " + (end - start) +
- " to shutdown, expected " + maxwait);
+ fail("QuorumPeer took " + (end - start) + " to shutdown, expected " + maxwait);
}
}
@@ -732,36 +704,30 @@ public class QuorumPeerMainTest extends QuorumPeerTestBase {
final int CLIENT_PORT_QP1 = PortAssignment.unique();
final int CLIENT_PORT_QP2 = PortAssignment.unique();
- String quorumCfgSection = "server.1=127.0.0.1:"
- + PortAssignment.unique() + ":" + PortAssignment.unique()
- + "\nserver.2=127.0.0.1:" + PortAssignment.unique() + ":"
- + PortAssignment.unique();
+ String quorumCfgSection = "server.1=127.0.0.1:" + PortAssignment.unique() + ":" + PortAssignment.unique()
+ + "\nserver.2=127.0.0.1:" + PortAssignment.unique() + ":" + PortAssignment.unique();
final int minSessionTimeOut = 10000;
final int maxSessionTimeOut = 15000;
final String configs = "maxSessionTimeout=" + maxSessionTimeOut + "\n"
- + "minSessionTimeout=" + minSessionTimeOut + "\n";
+ + "minSessionTimeout=" + minSessionTimeOut + "\n";
- MainThread q1 = new MainThread(1, CLIENT_PORT_QP1, quorumCfgSection,
- configs);
- MainThread q2 = new MainThread(2, CLIENT_PORT_QP2, quorumCfgSection,
- configs);
+ MainThread q1 = new MainThread(1, CLIENT_PORT_QP1, quorumCfgSection, configs);
+ MainThread q2 = new MainThread(2, CLIENT_PORT_QP2, quorumCfgSection, configs);
q1.start();
q2.start();
- Assert.assertTrue("waiting for server 1 being up", ClientBase
- .waitForServerUp("127.0.0.1:" + CLIENT_PORT_QP1,
- CONNECTION_TIMEOUT));
- Assert.assertTrue("waiting for server 2 being up", ClientBase
- .waitForServerUp("127.0.0.1:" + CLIENT_PORT_QP2,
- CONNECTION_TIMEOUT));
+ assertTrue(
+ "waiting for server 1 being up",
+ ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT_QP1, CONNECTION_TIMEOUT));
+ assertTrue(
+ "waiting for server 2 being up",
+ ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT_QP2, CONNECTION_TIMEOUT));
QuorumPeer quorumPeer = q1.main.quorumPeer;
- Assert.assertEquals("minimumSessionTimeOut is not considered",
- minSessionTimeOut, quorumPeer.getMinSessionTimeout());
- Assert.assertEquals("maximumSessionTimeOut is not considered",
- maxSessionTimeOut, quorumPeer.getMaxSessionTimeout());
+ assertEquals("minimumSessionTimeOut is not considered", minSessionTimeOut, quorumPeer.getMinSessionTimeout());
+ assertEquals("maximumSessionTimeOut is not considered", maxSessionTimeOut, quorumPeer.getMaxSessionTimeout());
}
/**
@@ -775,35 +741,29 @@ public class QuorumPeerMainTest extends QuorumPeerTestBase {
final int CLIENT_PORT_QP1 = PortAssignment.unique();
final int CLIENT_PORT_QP2 = PortAssignment.unique();
- String quorumCfgSection = "server.1=127.0.0.1:"
- + PortAssignment.unique() + ":" + PortAssignment.unique()
- + "\nserver.2=127.0.0.1:" + PortAssignment.unique() + ":"
- + PortAssignment.unique();
+ String quorumCfgSection = "server.1=127.0.0.1:" + PortAssignment.unique() + ":" + PortAssignment.unique()
+ + "\nserver.2=127.0.0.1:" + PortAssignment.unique() + ":" + PortAssignment.unique();
final int minSessionTimeOut = 15000;
final String configs = "minSessionTimeout=" + minSessionTimeOut + "\n";
- MainThread q1 = new MainThread(1, CLIENT_PORT_QP1, quorumCfgSection,
- configs);
- MainThread q2 = new MainThread(2, CLIENT_PORT_QP2, quorumCfgSection,
- configs);
+ MainThread q1 = new MainThread(1, CLIENT_PORT_QP1, quorumCfgSection, configs);
+ MainThread q2 = new MainThread(2, CLIENT_PORT_QP2, quorumCfgSection, configs);
q1.start();
q2.start();
- Assert.assertTrue("waiting for server 1 being up", ClientBase
- .waitForServerUp("127.0.0.1:" + CLIENT_PORT_QP1,
- CONNECTION_TIMEOUT));
- Assert.assertTrue("waiting for server 2 being up", ClientBase
- .waitForServerUp("127.0.0.1:" + CLIENT_PORT_QP2,
- CONNECTION_TIMEOUT));
+ assertTrue(
+ "waiting for server 1 being up",
+ ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT_QP1, CONNECTION_TIMEOUT));
+ assertTrue(
+ "waiting for server 2 being up",
+ ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT_QP2, CONNECTION_TIMEOUT));
QuorumPeer quorumPeer = q1.main.quorumPeer;
final int maxSessionTimeOut = quorumPeer.tickTime * 20;
- Assert.assertEquals("minimumSessionTimeOut is not considered",
- minSessionTimeOut, quorumPeer.getMinSessionTimeout());
- Assert.assertEquals("maximumSessionTimeOut is wrong",
- maxSessionTimeOut, quorumPeer.getMaxSessionTimeout());
+ assertEquals("minimumSessionTimeOut is not considered", minSessionTimeOut, quorumPeer.getMinSessionTimeout());
+ assertEquals("maximumSessionTimeOut is wrong", maxSessionTimeOut, quorumPeer.getMaxSessionTimeout());
}
@Test
@@ -825,7 +785,7 @@ public class QuorumPeerMainTest extends QuorumPeerTestBase {
// 2. kill all followers
int leader = servers.findLeader();
- Map<Long, Proposal> outstanding = servers.mt[leader].main.quorumPeer.leader.outstandingProposals;
+ Map<Long, Proposal> outstanding = servers.mt[leader].main.quorumPeer.leader.outstandingProposals;
// increase the tick time to delay the leader going to looking
int previousTick = servers.mt[leader].main.quorumPeer.tickTime;
servers.mt[leader].main.quorumPeer.tickTime = LEADER_TIMEOUT_MS;
@@ -858,27 +818,25 @@ public class QuorumPeerMainTest extends QuorumPeerTestBase {
// 5. send a create request to old leader and make sure it's synced to disk,
// which means it acked from itself
try {
- servers.zk[leader].create("/zk" + leader, "zk".getBytes(), Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
- Assert.fail("create /zk" + leader + " should have failed");
+ servers.zk[leader].create("/zk" + leader, "zk".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
+ fail("create /zk" + leader + " should have failed");
} catch (KeeperException e) {
}
// just make sure that we actually did get it in process at the
// leader
// there can be extra sessionClose proposals
- Assert.assertTrue(outstanding.size() > 0);
+ assertTrue(outstanding.size() > 0);
Proposal p = findProposalOfType(outstanding, OpCode.create);
LOG.info(String.format("Old leader id: %d. All proposals: %s", leader, outstanding));
- Assert.assertNotNull("Old leader doesn't have 'create' proposal", p);
+ assertNotNull("Old leader doesn't have 'create' proposal", p);
// make sure it has a chance to write it to disk
int sleepTime = 0;
Long longLeader = Long.valueOf(leader);
while (!p.qvAcksetPairs.get(0).getAckset().contains(longLeader)) {
if (sleepTime > 2000) {
- Assert.fail("Transaction not synced to disk within 1 second " + p.qvAcksetPairs.get(0).getAckset()
- + " expected " + leader);
+ fail("Transaction not synced to disk within 1 second " + p.qvAcksetPairs.get(0).getAckset() + " expected " + leader);
}
Thread.sleep(100);
sleepTime += 100;
@@ -890,7 +848,8 @@ public class QuorumPeerMainTest extends QuorumPeerTestBase {
Follower f = servers.mt[leader].main.quorumPeer.follower;
while (f == null || !f.isRunning()) {
if (sleepTime > LEADER_TIMEOUT_MS * 2) {
- Assert.fail("Took too long for old leader to time out " + servers.mt[leader].main.quorumPeer.getPeerState());
+ fail("Took too long for old leader to time out "
+ + servers.mt[leader].main.quorumPeer.getPeerState());
}
Thread.sleep(100);
sleepTime += 100;
@@ -899,7 +858,7 @@ public class QuorumPeerMainTest extends QuorumPeerTestBase {
int newLeader = servers.findLeader();
// make sure a different leader was elected
- Assert.assertNotEquals(leader, newLeader);
+ assertNotEquals(leader, newLeader);
// 7. restart the previous leader to force it to replay the edits and possibly come up in a bad state
servers.mt[leader].shutdown();
@@ -911,7 +870,9 @@ public class QuorumPeerMainTest extends QuorumPeerTestBase {
// 8. check the node exist in previous leader but not others
// make sure everything is consistent
for (int i = 0; i < SERVER_COUNT; i++) {
- Assert.assertNull("server " + i + " should not have /zk" + leader, servers.zk[i].exists("/zk" + leader, false));
+ assertNull(
+ "server " + i + " should not have /zk" + leader,
+ servers.zk[i].exists("/zk" + leader, false));
}
}
@@ -954,13 +915,13 @@ public class QuorumPeerMainTest extends QuorumPeerTestBase {
// Node 1 must be started first, before quorum is formed, to trigger the attempted invalid connection to 3
svrs.mt[0].start();
QuorumPeer quorumPeer1 = waitForQuorumPeer(svrs.mt[0], CONNECTION_TIMEOUT);
- Assert.assertTrue(quorumPeer1.getPeerState() == QuorumPeer.ServerState.LOOKING);
+ assertTrue(quorumPeer1.getPeerState() == QuorumPeer.ServerState.LOOKING);
// Node 3 started second to avoid 1 and 2 forming a quorum before 3 starts up
int highestServerIndex = numServers - 1;
svrs.mt[highestServerIndex].start();
QuorumPeer quorumPeer3 = waitForQuorumPeer(svrs.mt[highestServerIndex], CONNECTION_TIMEOUT);
- Assert.assertTrue(quorumPeer3.getPeerState() == QuorumPeer.ServerState.LOOKING);
+ assertTrue(quorumPeer3.getPeerState() == QuorumPeer.ServerState.LOOKING);
// Node 2 started last, kicks off leader election
for (int i = 1; i < highestServerIndex; i++) {
@@ -969,14 +930,16 @@ public class QuorumPeerMainTest extends QuorumPeerTestBase {
// Nodes 2 and 3 now form quorum and fully start. 1 attempts to vote for 3, fails, returns to LOOKING state
for (int i = 1; i < numServers; i++) {
- Assert.assertTrue("waiting for server to start",
- ClientBase.waitForServerUp("127.0.0.1:" + svrs.clientPorts[i], CONNECTION_TIMEOUT));
+ assertTrue(
+ "waiting for server to start",
+ ClientBase.waitForServerUp("127.0.0.1:" + svrs.clientPorts[i], CONNECTION_TIMEOUT));
}
- Assert.assertTrue(svrs.mt[0].getQuorumPeer().getPeerState() == QuorumPeer.ServerState.LOOKING);
- Assert.assertTrue(svrs.mt[highestServerIndex].getQuorumPeer().getPeerState() == QuorumPeer.ServerState.LEADING);
+ assertTrue(svrs.mt[0].getQuorumPeer().getPeerState() == QuorumPeer.ServerState.LOOKING);
+ assertTrue(svrs.mt[highestServerIndex].getQuorumPeer().getPeerState()
+ == QuorumPeer.ServerState.LEADING);
for (int i = 1; i < highestServerIndex; i++) {
- Assert.assertTrue(svrs.mt[i].getQuorumPeer().getPeerState() == QuorumPeer.ServerState.FOLLOWING);
+ assertTrue(svrs.mt[i].getQuorumPeer().getPeerState() == QuorumPeer.ServerState.FOLLOWING);
}
// Look through the logs for output that indicates Node 1 is LEADING or FOLLOWING
@@ -994,8 +957,8 @@ public class QuorumPeerMainTest extends QuorumPeerTestBase {
qlogger.removeAppender(appender);
}
- Assert.assertFalse("Corrupt peer should never become leader", foundLeading);
- Assert.assertFalse("Corrupt peer should not attempt connection to out of view leader", foundFollowing);
+ assertFalse("Corrupt peer should never become leader", foundLeading);
+ assertFalse("Corrupt peer should not attempt connection to out of view leader", foundFollowing);
}
@Test
@@ -1008,8 +971,7 @@ public class QuorumPeerMainTest extends QuorumPeerTestBase {
QuorumPeerConfig configMock = mock(QuorumPeerConfig.class);
when(configMock.getDataDir()).thenReturn(dataDir);
when(configMock.getDataLogDir()).thenReturn(dataLogDir);
- when(configMock.getMetricsProviderClassName())
- .thenReturn(NullMetricsProvider.class.getName());
+ when(configMock.getMetricsProviderClassName()).thenReturn(NullMetricsProvider.class.getName());
QuorumPeer qpMock = mock(QuorumPeer.class);
@@ -1022,8 +984,8 @@ public class QuorumPeerMainTest extends QuorumPeerTestBase {
// Assert
FileTxnSnapLog txnFactory = qpMain.getQuorumPeer().getTxnFactory();
- Assert.assertEquals(Paths.get(dataLogDir.getAbsolutePath(), "version-2").toString(), txnFactory.getDataDir().getAbsolutePath());
- Assert.assertEquals(Paths.get(dataDir.getAbsolutePath(), "version-2").toString(), txnFactory.getSnapDir().getAbsolutePath());
+ assertEquals(Paths.get(dataLogDir.getAbsolutePath(), "version-2").toString(), txnFactory.getDataDir().getAbsolutePath());
+ assertEquals(Paths.get(dataDir.getAbsolutePath(), "version-2").toString(), txnFactory.getSnapDir().getAbsolutePath());
} finally {
FileUtils.deleteDirectory(dataDir);
FileUtils.deleteDirectory(dataLogDir);
@@ -1031,6 +993,7 @@ public class QuorumPeerMainTest extends QuorumPeerTestBase {
}
private class InjectableQuorumPeerMain extends QuorumPeerMain {
+
QuorumPeer qp;
InjectableQuorumPeerMain(QuorumPeer qp) {
@@ -1041,6 +1004,7 @@ public class QuorumPeerMainTest extends QuorumPeerTestBase {
protected QuorumPeer getQuorumPeer() {
return qp;
}
+
}
private WriterAppender getConsoleAppender(ByteArrayOutputStream os, Level level) {
@@ -1109,36 +1073,33 @@ public class QuorumPeerMainTest extends QuorumPeerTestBase {
// 1. set up an ensemble with 3 servers
final int ENSEMBLE_SERVERS = 3;
- final int clientPorts[] = new int[ENSEMBLE_SERVERS];
+ final int[] clientPorts = new int[ENSEMBLE_SERVERS];
StringBuilder sb = new StringBuilder();
String server;
for (int i = 0; i < ENSEMBLE_SERVERS; i++) {
clientPorts[i] = PortAssignment.unique();
- server = "server." + i + "=127.0.0.1:" + PortAssignment.unique()
- + ":" + PortAssignment.unique() + ":participant;127.0.0.1:"
- + clientPorts[i];
+ server = "server." + i + "=127.0.0.1:" + PortAssignment.unique() + ":" + PortAssignment.unique()
+ + ":participant;127.0.0.1:" + clientPorts[i];
sb.append(server + "\n");
}
String currentQuorumCfgSection = sb.toString();
// start servers
MainThread[] mt = new MainThread[ENSEMBLE_SERVERS];
- ZooKeeper zk[] = new ZooKeeper[ENSEMBLE_SERVERS];
- Context contexts[] = new Context[ENSEMBLE_SERVERS];
+ ZooKeeper[] zk = new ZooKeeper[ENSEMBLE_SERVERS];
+ Context[] contexts = new Context[ENSEMBLE_SERVERS];
for (int i = 0; i < ENSEMBLE_SERVERS; i++) {
final Context context = new Context();
contexts[i] = context;
- mt[i] = new MainThread(i, clientPorts[i], currentQuorumCfgSection,
- false) {
+ mt[i] = new MainThread(i, clientPorts[i], currentQuorumCfgSection, false) {
@Override
public TestQPMain getTestQPMain() {
return new CustomizedQPMain(context);
}
};
mt[i].start();
- zk[i] = new ZooKeeper("127.0.0.1:" + clientPorts[i],
- ClientBase.CONNECTION_TIMEOUT, this);
+ zk[i] = new ZooKeeper("127.0.0.1:" + clientPorts[i], ClientBase.CONNECTION_TIMEOUT, this);
}
waitForAll(zk, States.CONNECTED);
LOG.info("all servers started");
@@ -1166,19 +1127,16 @@ public class QuorumPeerMainTest extends QuorumPeerTestBase {
// 3. create a node
String initialValue = "1";
final ZooKeeper leaderZk = zk[leaderId];
- leaderZk.create(nodePath, initialValue.getBytes(), Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ leaderZk.create(nodePath, initialValue.getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
LOG.info("created node {} with value {}", nodePath, initialValue);
- CustomQuorumPeer leaderQuorumPeer =
- (CustomQuorumPeer) mt[leaderId].main.quorumPeer;
+ CustomQuorumPeer leaderQuorumPeer = (CustomQuorumPeer) mt[leaderId].main.quorumPeer;
// 4. on the customized leader catch the startForwarding call
// (without synchronized), set the node to value v1, then
// call the super.startForwarding to generate the ongoing
// txn proposal and commit for v1 value update
- leaderQuorumPeer.setStartForwardingListener(
- new StartForwardingListener() {
+ leaderQuorumPeer.setStartForwardingListener(new StartForwardingListener() {
@Override
public void start() {
if (!Boolean.getBoolean(LearnerHandler.FORCE_SNAP_SYNC)) {
@@ -1189,10 +1147,9 @@ public class QuorumPeerMainTest extends QuorumPeerTestBase {
// use async, otherwise it will block the logLock in
// ZKDatabase and the setData request will timeout
try {
- leaderZk.setData(nodePath, value.getBytes(), -1,
- new AsyncCallback.StatCallback() {
- public void processResult(int rc, String path,
- Object ctx, Stat stat) {}
+ leaderZk.setData(nodePath, value.getBytes(), -1, new AsyncCallback.StatCallback() {
+ public void processResult(int rc, String path, Object ctx, Stat stat) {
+ }
}, null);
// wait for the setData txn being populated
Thread.sleep(1000);
@@ -1209,8 +1166,7 @@ public class QuorumPeerMainTest extends QuorumPeerTestBase {
@Override
public void start() {
String value = "3";
- LOG.info("before sending snapshot, set {} to {}",
- nodePath, value);
+ LOG.info("before sending snapshot, set {} to {}", nodePath, value);
try {
leaderZk.setData(nodePath, value.getBytes(), -1);
LOG.info("successfully set {} to {}", nodePath, value);
@@ -1221,8 +1177,7 @@ public class QuorumPeerMainTest extends QuorumPeerTestBase {
});
// 6. exit follower A after taking snapshot
- CustomQuorumPeer followerAQuorumPeer =
- ((CustomQuorumPeer) mt[followerA].main.quorumPeer);
+ CustomQuorumPeer followerAQuorumPeer = ((CustomQuorumPeer) mt[followerA].main.quorumPeer);
LOG.info("set exit when ack new leader packet on {}", followerA);
contexts[followerA].exitWhenAckNewLeader = true;
CountDownLatch latch = new CountDownLatch(1);
@@ -1233,14 +1188,15 @@ public class QuorumPeerMainTest extends QuorumPeerTestBase {
try {
latch.countDown();
followerAMT.shutdown();
- } catch (Exception e) {}
+ } catch (Exception e) {
+ }
}
};
// 7. start follower A to do snapshot sync
LOG.info("starting follower {}", followerA);
mt[followerA].start();
- Assert.assertTrue(latch.await(30, TimeUnit.SECONDS));
+ assertTrue(latch.await(30, TimeUnit.SECONDS));
// 8. now we have invalid data on disk, let's load it and verify
LOG.info("disable exit when ack new leader packet on {}", followerA);
@@ -1252,16 +1208,14 @@ public class QuorumPeerMainTest extends QuorumPeerTestBase {
mt[followerA].start();
zk[followerA].close();
- zk[followerA] = new ZooKeeper("127.0.0.1:" + clientPorts[followerA],
- ClientBase.CONNECTION_TIMEOUT, this);
+ zk[followerA] = new ZooKeeper("127.0.0.1:" + clientPorts[followerA], ClientBase.CONNECTION_TIMEOUT, this);
// 9. start follower A, after it's in broadcast state, make sure
// the node value is same as what we have on leader
waitForOne(zk[followerA], States.CONNECTED);
- Assert.assertEquals(
+ assertEquals(
new String(zk[followerA].getData(nodePath, null, null)),
- new String(zk[leaderId].getData(nodePath, null, null))
- );
+ new String(zk[leaderId].getData(nodePath, null, null)));
} finally {
System.clearProperty(LearnerHandler.FORCE_SNAP_SYNC);
for (int i = 0; i < ENSEMBLE_SERVERS; i++) {
@@ -1290,28 +1244,24 @@ public class QuorumPeerMainTest extends QuorumPeerTestBase {
* 2s to confirm this.
*/
@Test
- public void testLeaderElectionWithDisloyalVoter_stillHasMajority()
- throws IOException {
+ public void testLeaderElectionWithDisloyalVoter_stillHasMajority() throws IOException {
testLeaderElection(5, 5, 3000, 20000);
}
- void testLeaderElection(int totalServers, int serversToStart,
- int maxTimeToWaitForEpoch, int maxTimeWaitForServerUp)
- throws IOException {
+ void testLeaderElection(int totalServers, int serversToStart, int maxTimeToWaitForEpoch, int maxTimeWaitForServerUp) throws IOException {
Leader.setMaxTimeToWaitForEpoch(maxTimeToWaitForEpoch);
// set up config for an ensemble with given number of servers
servers = new Servers();
int ENSEMBLE_SERVERS = totalServers;
- final int clientPorts[] = new int[ENSEMBLE_SERVERS];
+ final int[] clientPorts = new int[ENSEMBLE_SERVERS];
StringBuilder sb = new StringBuilder();
String server;
for (int i = 0; i < ENSEMBLE_SERVERS; i++) {
clientPorts[i] = PortAssignment.unique();
- server = "server." + i + "=127.0.0.1:" + PortAssignment.unique()
- + ":" + PortAssignment.unique() + ":participant;127.0.0.1:"
- + clientPorts[i];
+ server = "server." + i + "=127.0.0.1:" + PortAssignment.unique() + ":" + PortAssignment.unique()
+ + ":participant;127.0.0.1:" + clientPorts[i];
sb.append(server + "\n");
}
String currentQuorumCfgSection = sb.toString();
@@ -1330,8 +1280,7 @@ public class QuorumPeerMainTest extends QuorumPeerTestBase {
context.quitFollowing = true;
}
contexts[i] = context;
- mt[i] = new MainThread(i, clientPorts[i], currentQuorumCfgSection,
- false) {
+ mt[i] = new MainThread(i, clientPorts[i], currentQuorumCfgSection, false) {
@Override
public TestQPMain getTestQPMain() {
return new CustomizedQPMain(context);
@@ -1343,10 +1292,9 @@ public class QuorumPeerMainTest extends QuorumPeerTestBase {
// make sure the quorum can be formed within initLimit * tickTime
// the default setting is 10 * 4000 = 40000 ms
for (int i = 0; i < SERVERS_TO_START; i++) {
- Assert.assertTrue(
+ assertTrue(
"Server " + i + " should have joined quorum by now",
- ClientBase.waitForServerUp(
- "127.0.0.1:" + clientPorts[i], maxTimeWaitForServerUp));
+ ClientBase.waitForServerUp("127.0.0.1:" + clientPorts[i], maxTimeWaitForServerUp));
}
}
@@ -1368,53 +1316,41 @@ public class QuorumPeerMainTest extends QuorumPeerTestBase {
final int CLIENT_PORT_QP1 = PortAssignment.unique();
final int CLIENT_PORT_QP2 = PortAssignment.unique();
- String quorumCfgSectionServer
- = "server.1=127.0.0.1:" + PortAssignment.unique()
- + ":" + PortAssignment.unique() + ";" + CLIENT_PORT_QP1 + "\n"
- + "server.2=127.0.0.1:" + PortAssignment.unique()
- + ":" + PortAssignment.unique() + ";" + CLIENT_PORT_QP2 + "\n";
+ String quorumCfgSectionServer = "server.1=127.0.0.1:" + PortAssignment.unique() + ":" + PortAssignment.unique() + ";" + CLIENT_PORT_QP1
+ + "\nserver.2=127.0.0.1:" + PortAssignment.unique() + ":" + PortAssignment.unique() + ";" + CLIENT_PORT_QP2 + "\n";
// server 1 boots with a MetricsProvider
- String quorumCfgSectionServer1 =
- quorumCfgSectionServer
- + "metricsProvider.className=" + BaseTestMetricsProvider.MetricsProviderCapturingLifecycle.class.getName() + "\n";
+ String quorumCfgSectionServer1 = quorumCfgSectionServer
+ + "metricsProvider.className=" + BaseTestMetricsProvider.MetricsProviderCapturingLifecycle.class.getName() + "\n";
MainThread q1 = new MainThread(1, CLIENT_PORT_QP1, quorumCfgSectionServer1);
MainThread q2 = new MainThread(2, CLIENT_PORT_QP2, quorumCfgSectionServer);
q1.start();
q2.start();
- boolean isup1
- = ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT_QP1,
- 30000);
- boolean isup2
- = ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT_QP2,
- 30000);
- Assert.assertTrue("Server 1 never came up", isup1);
- Assert.assertTrue("Server 2 never came up", isup2);
+ boolean isup1 = ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT_QP1, 30000);
+ boolean isup2 = ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT_QP2, 30000);
+ assertTrue("Server 1 never came up", isup1);
+ assertTrue("Server 2 never came up", isup2);
q1.shutdown();
q2.shutdown();
- Assert.assertTrue("waiting for server 1 down",
- ClientBase.waitForServerDown("127.0.0.1:" + CLIENT_PORT_QP1,
- ClientBase.CONNECTION_TIMEOUT));
+ assertTrue(
+ "waiting for server 1 down",
+ ClientBase.waitForServerDown("127.0.0.1:" + CLIENT_PORT_QP1, ClientBase.CONNECTION_TIMEOUT));
- Assert.assertTrue("waiting for server 2 down",
- ClientBase.waitForServerDown("127.0.0.1:" + CLIENT_PORT_QP2,
- ClientBase.CONNECTION_TIMEOUT));
+ assertTrue(
+ "waiting for server 2 down",
+ ClientBase.waitForServerDown("127.0.0.1:" + CLIENT_PORT_QP2, ClientBase.CONNECTION_TIMEOUT));
} finally {
qlogger.removeAppender(appender);
}
- Assert.assertTrue("metrics provider lifecycle error",
- BaseTestMetricsProvider.MetricsProviderCapturingLifecycle.configureCalled.get());
- Assert.assertTrue("metrics provider lifecycle error",
- BaseTestMetricsProvider.MetricsProviderCapturingLifecycle.startCalled.get());
- Assert.assertTrue("metrics provider lifecycle error",
- BaseTestMetricsProvider.MetricsProviderCapturingLifecycle.getRootContextCalled.get());
- Assert.assertTrue("metrics provider lifecycle error",
- BaseTestMetricsProvider.MetricsProviderCapturingLifecycle.stopCalled.get());
+ assertTrue("metrics provider lifecycle error", BaseTestMetricsProvider.MetricsProviderCapturingLifecycle.configureCalled.get());
+ assertTrue("metrics provider lifecycle error", BaseTestMetricsProvider.MetricsProviderCapturingLifecycle.startCalled.get());
+ assertTrue("metrics provider lifecycle error", BaseTestMetricsProvider.MetricsProviderCapturingLifecycle.getRootContextCalled.get());
+ assertTrue("metrics provider lifecycle error", BaseTestMetricsProvider.MetricsProviderCapturingLifecycle.stopCalled.get());
}
/**
@@ -1435,48 +1371,40 @@ public class QuorumPeerMainTest extends QuorumPeerTestBase {
final int CLIENT_PORT_QP1 = PortAssignment.unique();
final int CLIENT_PORT_QP2 = PortAssignment.unique();
- String quorumCfgSectionServer
- = "server.1=127.0.0.1:" + PortAssignment.unique()
- + ":" + PortAssignment.unique() + ";" + CLIENT_PORT_QP1 + "\n"
- + "server.2=127.0.0.1:" + PortAssignment.unique()
- + ":" + PortAssignment.unique() + ";" + CLIENT_PORT_QP2 + "\n";
+ String quorumCfgSectionServer = "server.1=127.0.0.1:" + PortAssignment.unique() + ":" + PortAssignment.unique() + ";" + CLIENT_PORT_QP1 + "\n"
+ + "server.2=127.0.0.1:" + PortAssignment.unique() + ":" + PortAssignment.unique() + ";" + CLIENT_PORT_QP2 + "\n";
// server 1 boots with a MetricsProvider
- String quorumCfgSectionServer1 =
- quorumCfgSectionServer
- + "metricsProvider.className=" + BaseTestMetricsProvider.MetricsProviderWithConfiguration.class.getName() + "\n"
- + "metricsProvider.httpPort=1234";
+ String quorumCfgSectionServer1 = quorumCfgSectionServer
+ + "metricsProvider.className="
+ + BaseTestMetricsProvider.MetricsProviderWithConfiguration.class.getName()
+ + "\n" + "metricsProvider.httpPort=1234";
MainThread q1 = new MainThread(1, CLIENT_PORT_QP1, quorumCfgSectionServer1);
MainThread q2 = new MainThread(2, CLIENT_PORT_QP2, quorumCfgSectionServer);
q1.start();
q2.start();
- boolean isup1
- = ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT_QP1,
- 30000);
- boolean isup2
- = ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT_QP2,
- 30000);
- Assert.assertTrue("Server 1 never came up", isup1);
- Assert.assertTrue("Server 2 never came up", isup2);
+ boolean isup1 = ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT_QP1, 30000);
+ boolean isup2 = ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT_QP2, 30000);
+ assertTrue("Server 1 never came up", isup1);
+ assertTrue("Server 2 never came up", isup2);
q1.shutdown();
q2.shutdown();
- Assert.assertTrue("waiting for server 1 down",
- ClientBase.waitForServerDown("127.0.0.1:" + CLIENT_PORT_QP1,
- ClientBase.CONNECTION_TIMEOUT));
+ assertTrue(
+ "waiting for server 1 down",
+ ClientBase.waitForServerDown("127.0.0.1:" + CLIENT_PORT_QP1, ClientBase.CONNECTION_TIMEOUT));
- Assert.assertTrue("waiting for server 2 down",
- ClientBase.waitForServerDown("127.0.0.1:" + CLIENT_PORT_QP2,
- ClientBase.CONNECTION_TIMEOUT));
+ assertTrue(
+ "waiting for server 2 down",
+ ClientBase.waitForServerDown("127.0.0.1:" + CLIENT_PORT_QP2, ClientBase.CONNECTION_TIMEOUT));
} finally {
qlogger.removeAppender(appender);
}
- Assert.assertEquals(1234,
- BaseTestMetricsProvider.MetricsProviderWithConfiguration.httpPort.get());
+ assertEquals(1234, BaseTestMetricsProvider.MetricsProviderWithConfiguration.httpPort.get());
}
/**
@@ -1497,60 +1425,52 @@ public class QuorumPeerMainTest extends QuorumPeerTestBase {
final int CLIENT_PORT_QP1 = PortAssignment.unique();
final int CLIENT_PORT_QP2 = PortAssignment.unique();
- String quorumCfgSectionServer
- = "server.1=127.0.0.1:" + PortAssignment.unique()
- + ":" + PortAssignment.unique() + ";" + CLIENT_PORT_QP1 + "\n"
- + "server.2=127.0.0.1:" + PortAssignment.unique()
- + ":" + PortAssignment.unique() + ";" + CLIENT_PORT_QP2 + "\n";
+ String quorumCfgSectionServer = "server.1=127.0.0.1:" + PortAssignment.unique() + ":" + PortAssignment.unique() + ";" + CLIENT_PORT_QP1 + "\n"
+ + "server.2=127.0.0.1:" + PortAssignment.unique() + ":" + PortAssignment.unique() + ";" + CLIENT_PORT_QP2 + "\n";
// server 1 boots with a MetricsProvider
- String quorumCfgSectionServer1 =
- quorumCfgSectionServer
- + "metricsProvider.className=" + BaseTestMetricsProvider.MetricsProviderWithErrorInStop.class.getName() + "\n";
+ String quorumCfgSectionServer1 = quorumCfgSectionServer
+ + "metricsProvider.className="
+ + BaseTestMetricsProvider.MetricsProviderWithErrorInStop.class.getName()
+ + "\n";
MainThread q1 = new MainThread(1, CLIENT_PORT_QP1, quorumCfgSectionServer1);
MainThread q2 = new MainThread(2, CLIENT_PORT_QP2, quorumCfgSectionServer);
q1.start();
q2.start();
- boolean isup1
- = ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT_QP1,
- 30000);
- boolean isup2
- = ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT_QP2,
- 30000);
- Assert.assertTrue("Server 1 never came up", isup1);
- Assert.assertTrue("Server 2 never came up", isup2);
+ boolean isup1 = ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT_QP1, 30000);
+ boolean isup2 = ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT_QP2, 30000);
+ assertTrue("Server 1 never came up", isup1);
+ assertTrue("Server 2 never came up", isup2);
q1.shutdown();
q2.shutdown();
- Assert.assertTrue("waiting for server 1 down",
- ClientBase.waitForServerDown("127.0.0.1:" + CLIENT_PORT_QP1,
- ClientBase.CONNECTION_TIMEOUT));
+ assertTrue(
+ "waiting for server 1 down",
+ ClientBase.waitForServerDown("127.0.0.1:" + CLIENT_PORT_QP1, ClientBase.CONNECTION_TIMEOUT));
- Assert.assertTrue("waiting for server 2 down",
- ClientBase.waitForServerDown("127.0.0.1:" + CLIENT_PORT_QP2,
- ClientBase.CONNECTION_TIMEOUT));
+ assertTrue(
+ "waiting for server 2 down",
+ ClientBase.waitForServerDown("127.0.0.1:" + CLIENT_PORT_QP2, ClientBase.CONNECTION_TIMEOUT));
} finally {
qlogger.removeAppender(appender);
}
- Assert.assertTrue("metrics provider lifecycle error",
- BaseTestMetricsProvider.MetricsProviderWithErrorInStop.stopCalled.get());
+ assertTrue("metrics provider lifecycle error", BaseTestMetricsProvider.MetricsProviderWithErrorInStop.stopCalled.get());
LineNumberReader r = new LineNumberReader(new StringReader(os.toString()));
String line;
boolean found = false;
- Pattern p
- = Pattern.compile(".*Error while stopping metrics.*");
+ Pattern p = Pattern.compile(".*Error while stopping metrics.*");
while ((line = r.readLine()) != null) {
found = p.matcher(line).matches();
if (found) {
break;
}
}
- Assert.assertTrue("complains about metrics provider", found);
+ assertTrue("complains about metrics provider", found);
}
/**
@@ -1569,27 +1489,22 @@ public class QuorumPeerMainTest extends QuorumPeerTestBase {
try {
final int CLIENT_PORT_QP1 = PortAssignment.unique();
- String quorumCfgSection
- = "server.1=127.0.0.1:" + PortAssignment.unique()
- + ":" + PortAssignment.unique() + ";" + CLIENT_PORT_QP1 + "\n"
- + "server.2=127.0.0.1:" + PortAssignment.unique()
- + ":" + PortAssignment.unique() + ";" + CLIENT_PORT_QP1 + "\n"
- + "metricsProvider.className=BadClass\n";
+ String quorumCfgSection = "server.1=127.0.0.1:" + PortAssignment.unique() + ":" + PortAssignment.unique() + ";" + CLIENT_PORT_QP1
+ + "\n" + "server.2=127.0.0.1:" + PortAssignment.unique() + ":" + PortAssignment.unique() + ";" + CLIENT_PORT_QP1
+ + "\n" + "metricsProvider.className=BadClass\n";
MainThread q1 = new MainThread(1, CLIENT_PORT_QP1, quorumCfgSection);
q1.start();
- boolean isup
- = ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT_QP1,
- 5000);
+ boolean isup = ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT_QP1, 5000);
- Assert.assertFalse("Server never came up", isup);
+ assertFalse("Server never came up", isup);
q1.shutdown();
- Assert.assertTrue("waiting for server 1 down",
- ClientBase.waitForServerDown("127.0.0.1:" + CLIENT_PORT_QP1,
- ClientBase.CONNECTION_TIMEOUT));
+ assertTrue(
+ "waiting for server 1 down",
+ ClientBase.waitForServerDown("127.0.0.1:" + CLIENT_PORT_QP1, ClientBase.CONNECTION_TIMEOUT));
} finally {
qlogger.removeAppender(appender);
@@ -1598,15 +1513,14 @@ public class QuorumPeerMainTest extends QuorumPeerTestBase {
LineNumberReader r = new LineNumberReader(new StringReader(os.toString()));
String line;
boolean found = false;
- Pattern p
- = Pattern.compile(".*BadClass.*");
+ Pattern p = Pattern.compile(".*BadClass.*");
while ((line = r.readLine()) != null) {
found = p.matcher(line).matches();
if (found) {
break;
}
}
- Assert.assertTrue("complains about metrics provider", found);
+ assertTrue("complains about metrics provider", found);
}
/**
@@ -1625,27 +1539,23 @@ public class QuorumPeerMainTest extends QuorumPeerTestBase {
try {
final int CLIENT_PORT_QP1 = PortAssignment.unique();
- String quorumCfgSection
- = "server.1=127.0.0.1:" + PortAssignment.unique()
- + ":" + PortAssignment.unique() + ";" + CLIENT_PORT_QP1 + "\n"
- + "server.2=127.0.0.1:" + PortAssignment.unique()
- + ":" + PortAssignment.unique() + ";" + CLIENT_PORT_QP1 + "\n"
- + "metricsProvider.className=" + BaseTestMetricsProvider.MetricsProviderWithErrorInStart.class.getName() + "\n";
+ String quorumCfgSection = "server.1=127.0.0.1:" + PortAssignment.unique() + ":" + PortAssignment.unique() + ";" + CLIENT_PORT_QP1
+ + "\n" + "server.2=127.0.0.1:" + PortAssignment.unique() + ":" + PortAssignment.unique() + ";" + CLIENT_PORT_QP1
+ + "\n" + "metricsProvider.className=" + BaseTestMetricsProvider.MetricsProviderWithErrorInStart.class.getName()
+ + "\n";
MainThread q1 = new MainThread(1, CLIENT_PORT_QP1, quorumCfgSection);
q1.start();
- boolean isup
- = ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT_QP1,
- 5000);
+ boolean isup = ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT_QP1, 5000);
- Assert.assertFalse("Server never came up", isup);
+ assertFalse("Server never came up", isup);
q1.shutdown();
- Assert.assertTrue("waiting for server 1 down",
- ClientBase.waitForServerDown("127.0.0.1:" + CLIENT_PORT_QP1,
- ClientBase.CONNECTION_TIMEOUT));
+ assertTrue(
+ "waiting for server 1 down",
+ ClientBase.waitForServerDown("127.0.0.1:" + CLIENT_PORT_QP1, ClientBase.CONNECTION_TIMEOUT));
} finally {
qlogger.removeAppender(appender);
@@ -1654,15 +1564,14 @@ public class QuorumPeerMainTest extends QuorumPeerTestBase {
LineNumberReader r = new LineNumberReader(new StringReader(os.toString()));
String line;
boolean found = false;
- Pattern p
- = Pattern.compile(".*MetricsProviderLifeCycleException.*");
+ Pattern p = Pattern.compile(".*MetricsProviderLifeCycleException.*");
while ((line = r.readLine()) != null) {
found = p.matcher(line).matches();
if (found) {
break;
}
}
- Assert.assertTrue("complains about metrics provider MetricsProviderLifeCycleException", found);
+ assertTrue("complains about metrics provider MetricsProviderLifeCycleException", found);
}
/**
@@ -1681,27 +1590,23 @@ public class QuorumPeerMainTest extends QuorumPeerTestBase {
try {
final int CLIENT_PORT_QP1 = PortAssignment.unique();
- String quorumCfgSection
- = "server.1=127.0.0.1:" + PortAssignment.unique()
- + ":" + PortAssignment.unique() + ";" + CLIENT_PORT_QP1 + "\n"
- + "server.2=127.0.0.1:" + PortAssignment.unique()
- + ":" + PortAssignment.unique() + ";" + CLIENT_PORT_QP1 + "\n"
- + "metricsProvider.className=" + BaseTestMetricsProvider.MetricsProviderWithErrorInConfigure.class.getName() + "\n";
+ String quorumCfgSection = "server.1=127.0.0.1:" + PortAssignment.unique() + ":" + PortAssignment.unique() + ";" + CLIENT_PORT_QP1
+ + "\n" + "server.2=127.0.0.1:" + PortAssignment.unique() + ":" + PortAssignment.unique() + ";" + CLIENT_PORT_QP1
+ + "\n" + "metricsProvider.className=" + BaseTestMetricsProvider.MetricsProviderWithErrorInConfigure.class.getName()
+ + "\n";
MainThread q1 = new MainThread(1, CLIENT_PORT_QP1, quorumCfgSection);
q1.start();
- boolean isup
- = ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT_QP1,
- 5000);
+ boolean isup = ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT_QP1, 5000);
- Assert.assertFalse("Server never came up", isup);
+ assertFalse("Server never came up", isup);
q1.shutdown();
- Assert.assertTrue("waiting for server 1 down",
- ClientBase.waitForServerDown("127.0.0.1:" + CLIENT_PORT_QP1,
- ClientBase.CONNECTION_TIMEOUT));
+ assertTrue(
+ "waiting for server 1 down",
+ ClientBase.waitForServerDown("127.0.0.1:" + CLIENT_PORT_QP1, ClientBase.CONNECTION_TIMEOUT));
} finally {
qlogger.removeAppender(appender);
@@ -1710,33 +1615,40 @@ public class QuorumPeerMainTest extends QuorumPeerTestBase {
LineNumberReader r = new LineNumberReader(new StringReader(os.toString()));
String line;
boolean found = false;
- Pattern p
- = Pattern.compile(".*MetricsProviderLifeCycleException.*");
+ Pattern p = Pattern.compile(".*MetricsProviderLifeCycleException.*");
while ((line = r.readLine()) != null) {
found = p.matcher(line).matches();
if (found) {
break;
}
}
- Assert.assertTrue("complains about metrics provider MetricsProviderLifeCycleException", found);
+ assertTrue("complains about metrics provider MetricsProviderLifeCycleException", found);
}
static class Context {
+
boolean quitFollowing = false;
boolean exitWhenAckNewLeader = false;
NewLeaderAckCallback newLeaderAckCallback = null;
+
}
- static interface NewLeaderAckCallback {
- public void start();
+ interface NewLeaderAckCallback {
+
+ void start();
+
}
- static interface StartForwardingListener {
- public void start();
+ interface StartForwardingListener {
+
+ void start();
+
}
- static interface BeginSnapshotListener {
- public void start();
+ interface BeginSnapshotListener {
+
+ void start();
+
}
static class CustomizedQPMain extends TestQPMain {
@@ -1751,17 +1663,18 @@ public class QuorumPeerMainTest extends QuorumPeerTestBase {
protected QuorumPeer getQuorumPeer() throws SaslException {
return new CustomQuorumPeer(context);
}
+
}
static class CustomQuorumPeer extends QuorumPeer {
+
private Context context;
private LearnerSyncThrottler throttler = null;
private StartForwardingListener startForwardingListener;
private BeginSnapshotListener beginSnapshotListener;
- public CustomQuorumPeer(Context context)
- throws SaslException {
+ public CustomQuorumPeer(Context context) throws SaslException {
this.context = context;
}
@@ -1776,10 +1689,8 @@ public class QuorumPeerMainTest extends QuorumPeerTestBase {
}
@Override
- protected Follower makeFollower(FileTxnSnapLog logFactory)
- throws IOException {
- return new Follower(this, new FollowerZooKeeperServer(logFactory,
- this, this.getZkDb())) {
+ protected Follower makeFollower(FileTxnSnapLog logFactory) throws IOException {
+ return new Follower(this, new FollowerZooKeeperServer(logFactory, this, this.getZkDb())) {
@Override
void followLeader() throws InterruptedException {
if (context.quitFollowing) {
@@ -1794,8 +1705,7 @@ public class QuorumPeerMainTest extends QuorumPeerTestBase {
@Override
void writePacket(QuorumPacket pp, boolean flush) throws IOException {
- if (pp != null && pp.getType() == Leader.ACK
- && context.exitWhenAckNewLeader) {
+ if (pp != null && pp.getType() == Leader.ACK && context.exitWhenAckNewLeader) {
if (context.newLeaderAckCallback != null) {
context.newLeaderAckCallback.start();
}
@@ -1807,11 +1717,9 @@ public class QuorumPeerMainTest extends QuorumPeerTestBase {
@Override
protected Leader makeLeader(FileTxnSnapLog logFactory) throws IOException, X509Exception {
- return new Leader(this, new LeaderZooKeeperServer(logFactory,
- this, this.getZkDb())) {
+ return new Leader(this, new LeaderZooKeeperServer(logFactory, this, this.getZkDb())) {
@Override
- public long startForwarding(LearnerHandler handler,
- long lastSeenZxid) {
+ public long startForwarding(LearnerHandler handler, long lastSeenZxid) {
if (startForwardingListener != null) {
startForwardingListener.start();
}
@@ -1820,12 +1728,10 @@ public class QuorumPeerMainTest extends QuorumPeerTestBase {
@Override
public LearnerSyncThrottler getLearnerSnapSyncThrottler() {
- if (throttler == null){
- throttler = new LearnerSyncThrottler(getMaxConcurrentSnapSyncs(),
- LearnerSyncThrottler.SyncType.SNAP){
+ if (throttler == null) {
+ throttler = new LearnerSyncThrottler(getMaxConcurrentSnapSyncs(), LearnerSyncThrottler.SyncType.SNAP) {
@Override
- public void beginSync(boolean essential)
- throws SyncThrottleException, InterruptedException {
+ public void beginSync(boolean essential) throws SyncThrottleException, InterruptedException {
if (beginSnapshotListener != null) {
beginSnapshotListener.start();
}
@@ -1837,5 +1743,7 @@ public class QuorumPeerMainTest extends QuorumPeerTestBase {
}
};
}
+
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/QuorumPeerTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/QuorumPeerTest.java
index d6b3774a8..03cb6f06a 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/QuorumPeerTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/QuorumPeerTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,15 +18,15 @@
package org.apache.zookeeper.server.quorum;
-import static org.junit.Assert.*;
-
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.util.HashMap;
import java.util.Map;
-
import org.apache.zookeeper.PortAssignment;
import org.apache.zookeeper.server.quorum.QuorumPeer.LearnerType;
import org.apache.zookeeper.server.quorum.QuorumPeer.QuorumServer;
@@ -52,16 +52,12 @@ public class QuorumPeerTest {
Map<Long, QuorumServer> peersView = new HashMap<Long, QuorumServer>();
InetAddress clientIP = InetAddress.getLoopbackAddress();
- peersView.put(Long.valueOf(myId),
- new QuorumServer(myId, new InetSocketAddress(clientIP, PortAssignment.unique()),
- new InetSocketAddress(clientIP, PortAssignment.unique()),
- new InetSocketAddress(clientIP, clientPort), LearnerType.PARTICIPANT));
+ peersView.put(Long.valueOf(myId), new QuorumServer(myId, new InetSocketAddress(clientIP, PortAssignment.unique()), new InetSocketAddress(clientIP, PortAssignment.unique()), new InetSocketAddress(clientIP, clientPort), LearnerType.PARTICIPANT));
/**
* QuorumPeer constructor without QuorumVerifier
*/
- QuorumPeer peer1 = new QuorumPeer(peersView, dataDir, dataDir, clientPort, electionAlg, myId, tickTime,
- initLimit, syncLimit, connectToLearnerMasterLimit);
+ QuorumPeer peer1 = new QuorumPeer(peersView, dataDir, dataDir, clientPort, electionAlg, myId, tickTime, initLimit, syncLimit, connectToLearnerMasterLimit);
String hostString1 = peer1.cnxnFactory.getLocalAddress().getHostString();
assertEquals(clientIP.getHostAddress(), hostString1);
@@ -73,12 +69,8 @@ public class QuorumPeerTest {
*/
peersView.clear();
clientPort = PortAssignment.unique();
- peersView.put(Long.valueOf(myId),
- new QuorumServer(myId, new InetSocketAddress(clientIP, PortAssignment.unique()),
- new InetSocketAddress(clientIP, PortAssignment.unique()),
- new InetSocketAddress(clientIP, clientPort), LearnerType.PARTICIPANT));
- QuorumPeer peer2 = new QuorumPeer(peersView, dataDir, dataDir, clientPort, electionAlg, myId, tickTime,
- initLimit, syncLimit, connectToLearnerMasterLimit);
+ peersView.put(Long.valueOf(myId), new QuorumServer(myId, new InetSocketAddress(clientIP, PortAssignment.unique()), new InetSocketAddress(clientIP, PortAssignment.unique()), new InetSocketAddress(clientIP, clientPort), LearnerType.PARTICIPANT));
+ QuorumPeer peer2 = new QuorumPeer(peersView, dataDir, dataDir, clientPort, electionAlg, myId, tickTime, initLimit, syncLimit, connectToLearnerMasterLimit);
String hostString2 = peer2.cnxnFactory.getLocalAddress().getHostString();
assertEquals(clientIP.getHostAddress(), hostString2);
// cleanup
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/QuorumPeerTestBase.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/QuorumPeerTestBase.java
index 456a3ef9a..fe4d455e1 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/QuorumPeerTestBase.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/QuorumPeerTestBase.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -17,8 +17,9 @@
*/
/**
- *
+ *
*/
+
package org.apache.zookeeper.server.quorum;
import java.io.File;
@@ -29,30 +30,28 @@ import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
-import java.util.Set;
import java.util.Properties;
-
+import java.util.Set;
import org.apache.zookeeper.PortAssignment;
-import org.apache.zookeeper.ZooKeeper;
-import org.junit.After;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZKTestCase;
+import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.common.PathUtils;
-import org.apache.zookeeper.server.admin.AdminServer.AdminServerException;
import org.apache.zookeeper.server.admin.JettyAdminServer;
import org.apache.zookeeper.test.ClientBase;
import org.apache.zookeeper.test.QuorumBase;
+import org.junit.After;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/**
* Has some common functionality for tests that work with QuorumPeers. Override
* process(WatchedEvent) to implement the Watcher interface
*/
public class QuorumPeerTestBase extends ZKTestCase implements Watcher {
- protected static final Logger LOG = LoggerFactory
- .getLogger(QuorumPeerTestBase.class);
+
+ protected static final Logger LOG = LoggerFactory.getLogger(QuorumPeerTestBase.class);
public static final int TIMEOUT = 5000;
@@ -77,15 +76,18 @@ public class QuorumPeerTestBase extends ZKTestCase implements Watcher {
}
public static class TestQPMain extends QuorumPeerMain {
+
public void shutdown() {
// ensure it closes - in particular wait for thread to exit
if (quorumPeer != null) {
QuorumBase.shutdown(quorumPeer);
}
}
+
}
-
+
public static class MainThread implements Runnable {
+
final File confFile;
final File tmpDir;
@@ -111,15 +113,13 @@ public class QuorumPeerTestBase extends ZKTestCase implements Watcher {
* @param tickTime initLimit will be 10 and syncLimit will be 5
* @throws IOException
*/
- public MainThread(int myid, int clientPort, String quorumCfgSection,
- Map<String, String> otherConfigs, int tickTime) throws IOException {
+ public MainThread(int myid, int clientPort, String quorumCfgSection, Map<String, String> otherConfigs, int tickTime) throws IOException {
baseDir = ClientBase.createTmpDir();
this.myid = myid;
this.clientPort = clientPort;
this.quorumCfgSection = quorumCfgSection;
this.otherConfigs = otherConfigs;
- LOG.info("id = " + myid + " tmpDir = " + baseDir + " clientPort = "
- + clientPort);
+ LOG.info("id = " + myid + " tmpDir = " + baseDir + " clientPort = " + clientPort);
confFile = new File(baseDir, "zoo.cfg");
FileWriter fwriter = new FileWriter(confFile);
@@ -164,60 +164,48 @@ public class QuorumPeerTestBase extends ZKTestCase implements Watcher {
this(myid, quorumCfgSection, true);
}
- public MainThread(int myid, String quorumCfgSection, Integer secureClientPort, boolean writeDynamicConfigFile)
- throws IOException {
- this(myid, UNSET_STATIC_CLIENTPORT, JettyAdminServer.DEFAULT_PORT, secureClientPort,
- quorumCfgSection, null, null, writeDynamicConfigFile, null);
+ public MainThread(int myid, String quorumCfgSection, Integer secureClientPort, boolean writeDynamicConfigFile) throws IOException {
+ this(myid, UNSET_STATIC_CLIENTPORT, JettyAdminServer.DEFAULT_PORT, secureClientPort, quorumCfgSection, null, null, writeDynamicConfigFile, null);
}
- public MainThread(int myid, String quorumCfgSection, boolean writeDynamicConfigFile)
- throws IOException {
+ public MainThread(int myid, String quorumCfgSection, boolean writeDynamicConfigFile) throws IOException {
this(myid, UNSET_STATIC_CLIENTPORT, quorumCfgSection, writeDynamicConfigFile);
}
- public MainThread(int myid, int clientPort, String quorumCfgSection, boolean writeDynamicConfigFile)
- throws IOException {
+ public MainThread(int myid, int clientPort, String quorumCfgSection, boolean writeDynamicConfigFile) throws IOException {
this(myid, clientPort, JettyAdminServer.DEFAULT_PORT, quorumCfgSection, null, null, writeDynamicConfigFile);
}
-
- public MainThread(int myid, int clientPort, String quorumCfgSection, String peerType, boolean writeDynamicConfigFile)
- throws IOException {
+
+ public MainThread(int myid, int clientPort, String quorumCfgSection, String peerType, boolean writeDynamicConfigFile) throws IOException {
this(myid, clientPort, JettyAdminServer.DEFAULT_PORT, quorumCfgSection, null, peerType, writeDynamicConfigFile);
}
- public MainThread(int myid, int clientPort, String quorumCfgSection, boolean writeDynamicConfigFile,
- String version) throws IOException {
- this(myid, clientPort, JettyAdminServer.DEFAULT_PORT, quorumCfgSection, null,
- null, writeDynamicConfigFile, version);
+ public MainThread(int myid, int clientPort, String quorumCfgSection, boolean writeDynamicConfigFile, String version) throws IOException {
+ this(myid, clientPort, JettyAdminServer.DEFAULT_PORT, quorumCfgSection, null, null, writeDynamicConfigFile, version);
}
- public MainThread(int myid, int clientPort, String quorumCfgSection, String configs)
- throws IOException {
+ public MainThread(int myid, int clientPort, String quorumCfgSection, String configs) throws IOException {
this(myid, clientPort, JettyAdminServer.DEFAULT_PORT, quorumCfgSection, configs, null, true);
}
- public MainThread(int myid, int clientPort, int adminServerPort, String quorumCfgSection,
- String configs) throws IOException {
+ public MainThread(int myid, int clientPort, int adminServerPort, String quorumCfgSection, String configs) throws IOException {
this(myid, clientPort, adminServerPort, quorumCfgSection, configs, null, true);
}
- public MainThread(int myid, int clientPort, int adminServerPort, String quorumCfgSection,
- String configs, String peerType, boolean writeDynamicConfigFile)
- throws IOException {
+ public MainThread(int myid, int clientPort, int adminServerPort, String quorumCfgSection, String configs, String peerType, boolean writeDynamicConfigFile) throws IOException {
this(myid, clientPort, adminServerPort, quorumCfgSection, configs, peerType, writeDynamicConfigFile, null);
}
- public MainThread(int myid, int clientPort, int adminServerPort, String quorumCfgSection,
- String configs, String peerType, boolean writeDynamicConfigFile, String version) throws IOException {
+ public MainThread(int myid, int clientPort, int adminServerPort, String quorumCfgSection, String configs, String peerType, boolean writeDynamicConfigFile, String version) throws IOException {
this(myid, clientPort, adminServerPort, null, quorumCfgSection, configs, peerType, writeDynamicConfigFile, version);
}
- public MainThread(int myid, int clientPort, int adminServerPort, Integer secureClientPort,
- String quorumCfgSection, String configs, String peerType, boolean writeDynamicConfigFile, String version)
- throws IOException {
+ public MainThread(int myid, int clientPort, int adminServerPort, Integer secureClientPort, String quorumCfgSection, String configs, String peerType, boolean writeDynamicConfigFile, String version) throws IOException {
tmpDir = ClientBase.createTmpDir();
- LOG.info("id = " + myid + " tmpDir = " + tmpDir + " clientPort = "
- + clientPort + " adminServerPort = " + adminServerPort);
+ LOG.info("id = " + myid
+ + " tmpDir = " + tmpDir
+ + " clientPort = " + clientPort
+ + " adminServerPort = " + adminServerPort);
File dataDir = new File(tmpDir, "data");
if (!dataDir.mkdir()) {
@@ -231,7 +219,7 @@ public class QuorumPeerTestBase extends ZKTestCase implements Watcher {
fwriter.write("initLimit=10\n");
fwriter.write("syncLimit=5\n");
fwriter.write("connectToLearnerMasterLimit=5\n");
- if(configs != null){
+ if (configs != null) {
fwriter.write(configs);
}
@@ -251,7 +239,7 @@ public class QuorumPeerTestBase extends ZKTestCase implements Watcher {
if (secureClientPort != null) {
fwriter.write("secureClientPort=" + secureClientPort + "\n");
}
-
+
if (peerType != null) {
fwriter.write("peerType=" + peerType + "\n");
}
@@ -274,10 +262,9 @@ public class QuorumPeerTestBase extends ZKTestCase implements Watcher {
ClientBase.createInitializeFile(dataDir);
}
- private String createDynamicFile(String quorumCfgSection, String version)
- throws IOException {
+ private String createDynamicFile(String quorumCfgSection, String version) throws IOException {
String filename = "zoo.cfg.dynamic";
- if( version != null ){
+ if (version != null) {
filename = filename + "." + version;
}
@@ -297,11 +284,12 @@ public class QuorumPeerTestBase extends ZKTestCase implements Watcher {
}
public File[] getFilesWithPrefix(final String prefix) {
- return tmpDir.listFiles(new FilenameFilter() {
+ return tmpDir.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.startsWith(prefix);
- }});
+ }
+ });
}
public File getFileByName(String filename) {
@@ -309,32 +297,25 @@ public class QuorumPeerTestBase extends ZKTestCase implements Watcher {
return f.isFile() ? f : null;
}
- public void writeTempDynamicConfigFile(String nextQuorumCfgSection, String version)
- throws IOException {
- File nextDynamicConfigFile = new File(tmpDir,
- "zoo.cfg" + QuorumPeerConfig.nextDynamicConfigFileSuffix);
+ public void writeTempDynamicConfigFile(String nextQuorumCfgSection, String version) throws IOException {
+ File nextDynamicConfigFile = new File(tmpDir, "zoo.cfg" + QuorumPeerConfig.nextDynamicConfigFileSuffix);
FileWriter fwriter = new FileWriter(nextDynamicConfigFile);
- fwriter.write(nextQuorumCfgSection
- + "\n"
- + "version=" + version);
+ fwriter.write(nextQuorumCfgSection + "\n" + "version=" + version);
fwriter.flush();
fwriter.close();
}
- public MainThread(int myid, int clientPort, String quorumCfgSection)
- throws IOException {
- this(myid, clientPort, quorumCfgSection,
- new HashMap<String, String>());
+ public MainThread(int myid, int clientPort, String quorumCfgSection) throws IOException {
+ this(myid, clientPort, quorumCfgSection, new HashMap<String, String>());
}
- public MainThread(int myid, int clientPort, String quorumCfgSection,
- Map<String, String> otherConfigs) throws IOException {
+ public MainThread(int myid, int clientPort, String quorumCfgSection, Map<String, String> otherConfigs) throws IOException {
this(myid, clientPort, quorumCfgSection, otherConfigs, 4000);
}
Thread currentThread;
- synchronized public void start() {
+ public synchronized void start() {
main = getTestQPMain();
currentThread = new Thread(this);
currentThread.start();
@@ -345,7 +326,7 @@ public class QuorumPeerTestBase extends ZKTestCase implements Watcher {
}
public void run() {
- String args[] = new String[1];
+ String[] args = new String[1];
args[0] = confFile.toString();
try {
main.initializeAndRun(args);
@@ -397,7 +378,6 @@ public class QuorumPeerTestBase extends ZKTestCase implements Watcher {
return main.quorumPeer;
}
-
public void deleteBaseDir() {
ClientBase.recursiveDelete(baseDir);
}
@@ -426,12 +406,13 @@ public class QuorumPeerTestBase extends ZKTestCase implements Watcher {
// This class holds the servers and clients for those servers
protected static class Servers {
- MainThread mt[];
- ZooKeeper zk[];
+
+ MainThread[] mt;
+ ZooKeeper[] zk;
int[] clientPorts;
public void shutDownAllServers() throws InterruptedException {
- for (MainThread t: mt) {
+ for (MainThread t : mt) {
t.shutdown();
}
}
@@ -451,7 +432,10 @@ public class QuorumPeerTestBase extends ZKTestCase implements Watcher {
if (zk[clientIndex] != null) {
zk[clientIndex].close();
}
- zk[clientIndex] = new ZooKeeper("127.0.0.1:" + clientPorts[clientIndex], ClientBase.CONNECTION_TIMEOUT, watcher);
+ zk[clientIndex] = new ZooKeeper(
+ "127.0.0.1:" + clientPorts[clientIndex],
+ ClientBase.CONNECTION_TIMEOUT,
+ watcher);
}
public int findLeader() {
@@ -462,6 +446,7 @@ public class QuorumPeerTestBase extends ZKTestCase implements Watcher {
}
return -1;
}
+
}
protected Servers LaunchServers(int numServers) throws IOException, InterruptedException {
@@ -481,15 +466,15 @@ public class QuorumPeerTestBase extends ZKTestCase implements Watcher {
QuorumPeerMainTest.Servers svrs = new QuorumPeerMainTest.Servers();
svrs.clientPorts = new int[SERVER_COUNT];
StringBuilder sb = new StringBuilder();
- for(int i = 0; i < SERVER_COUNT; i++) {
+ for (int i = 0; i < SERVER_COUNT; i++) {
svrs.clientPorts[i] = PortAssignment.unique();
- sb.append("server."+i+"=127.0.0.1:"+PortAssignment.unique()+":"+PortAssignment.unique()+";"+svrs.clientPorts[i]+"\n");
+ sb.append("server." + i + "=127.0.0.1:" + PortAssignment.unique() + ":" + PortAssignment.unique() + ";" + svrs.clientPorts[i] + "\n");
}
String quorumCfgSection = sb.toString();
svrs.mt = new MainThread[SERVER_COUNT];
svrs.zk = new ZooKeeper[SERVER_COUNT];
- for(int i = 0; i < SERVER_COUNT; i++) {
+ for (int i = 0; i < SERVER_COUNT; i++) {
if (tickTime != null) {
svrs.mt[i] = new MainThread(i, svrs.clientPorts[i], quorumCfgSection, new HashMap<String, String>(), tickTime);
} else {
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/QuorumRequestPipelineTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/QuorumRequestPipelineTest.java
index 5fce0b4ec..3565c562a 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/QuorumRequestPipelineTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/QuorumRequestPipelineTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,50 +18,48 @@
package org.apache.zookeeper.server.quorum;
+import static org.junit.Assert.assertArrayEquals;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
-
-import org.junit.After;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.Parameterized;
-
import org.apache.zookeeper.AsyncCallback.VoidCallback;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.TestableZooKeeper;
+import org.apache.zookeeper.ZKParameterized;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.data.Stat;
import org.apache.zookeeper.server.quorum.QuorumPeer.ServerState;
import org.apache.zookeeper.test.QuorumBase;
-import org.apache.zookeeper.ZKParameterized;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
@RunWith(Parameterized.class)
@Parameterized.UseParametersRunnerFactory(ZKParameterized.RunnerFactory.class)
public class QuorumRequestPipelineTest extends QuorumBase {
+
protected ServerState serverState;
protected final CountDownLatch callComplete = new CountDownLatch(1);
protected boolean complete = false;
- protected final static String PARENT_PATH = "/foo";
- protected final static Set<String> CHILDREN = new HashSet<String>(Arrays.asList("1", "2", "3"));
- protected final static String AUTH_PROVIDER = "digest";
- protected final static byte[] AUTH = "hello".getBytes();
- protected final static byte[] DATA = "Hint Water".getBytes();
+ protected static final String PARENT_PATH = "/foo";
+ protected static final Set<String> CHILDREN = new HashSet<String>(Arrays.asList("1", "2", "3"));
+ protected static final String AUTH_PROVIDER = "digest";
+ protected static final byte[] AUTH = "hello".getBytes();
+ protected static final byte[] DATA = "Hint Water".getBytes();
protected TestableZooKeeper zkClient;
@Parameterized.Parameters
public static Collection<Object[]> data() {
- return Arrays.asList(
- new Object[][] {
- {ServerState.LEADING},
- {ServerState.FOLLOWING},
- {ServerState.OBSERVING}});
+ return Arrays.asList(new Object[][]{{ServerState.LEADING}, {ServerState.FOLLOWING}, {ServerState.OBSERVING}});
}
public QuorumRequestPipelineTest(ServerState state) {
@@ -92,61 +90,41 @@ public class QuorumRequestPipelineTest extends QuorumBase {
@Test
public void testCreate() throws Exception {
zkClient.create(PARENT_PATH, DATA, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
- Assert.assertArrayEquals(
- String.format("%s Node created (create) with expected value", serverState),
- DATA,
- zkClient.getData(PARENT_PATH, false, null));
+ assertArrayEquals(String.format("%s Node created (create) with expected value", serverState), DATA, zkClient.getData(PARENT_PATH, false, null));
}
@Test
public void testCreate2() throws Exception {
zkClient.create(PARENT_PATH, DATA, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT, null);
- Assert.assertArrayEquals(
- String.format("%s Node created (create2) with expected value", serverState),
- DATA,
- zkClient.getData(PARENT_PATH, false, null));
+ assertArrayEquals(String.format("%s Node created (create2) with expected value", serverState), DATA, zkClient.getData(PARENT_PATH, false, null));
}
@Test
public void testDelete() throws Exception {
create2EmptyNode(zkClient, PARENT_PATH);
zkClient.delete(PARENT_PATH, -1);
- Assert.assertNull(
- String.format("%s Node no longer exists", serverState),
- zkClient.exists(PARENT_PATH, false));
+ assertNull(String.format("%s Node no longer exists", serverState), zkClient.exists(PARENT_PATH, false));
}
@Test
public void testExists() throws Exception {
Stat stat = create2EmptyNode(zkClient, PARENT_PATH);
- Assert.assertEquals(
- String.format("%s Exists returns correct node stat", serverState),
- stat,
- zkClient.exists(PARENT_PATH, false));
+ assertEquals(String.format("%s Exists returns correct node stat", serverState), stat, zkClient.exists(PARENT_PATH, false));
}
@Test
public void testSetAndGetData() throws Exception {
create2EmptyNode(zkClient, PARENT_PATH);
zkClient.setData(PARENT_PATH, DATA, -1);
- Assert.assertArrayEquals(
- String.format("%s Node updated with expected value", serverState),
- DATA,
- zkClient.getData(PARENT_PATH, false, null));
+ assertArrayEquals(String.format("%s Node updated with expected value", serverState), DATA, zkClient.getData(PARENT_PATH, false, null));
}
@Test
public void testSetAndGetACL() throws Exception {
create2EmptyNode(zkClient, PARENT_PATH);
- Assert.assertEquals(
- String.format("%s Node has open ACL", serverState),
- Ids.OPEN_ACL_UNSAFE,
- zkClient.getACL(PARENT_PATH, new Stat()));
+ assertEquals(String.format("%s Node has open ACL", serverState), Ids.OPEN_ACL_UNSAFE, zkClient.getACL(PARENT_PATH, new Stat()));
zkClient.setACL(PARENT_PATH, Ids.READ_ACL_UNSAFE, -1);
- Assert.assertEquals(
- String.format("%s Node has world read-only ACL", serverState),
- Ids.READ_ACL_UNSAFE,
- zkClient.getACL(PARENT_PATH, new Stat()));
+ assertEquals(String.format("%s Node has world read-only ACL", serverState), Ids.READ_ACL_UNSAFE, zkClient.getACL(PARENT_PATH, new Stat()));
}
@Test
@@ -155,10 +133,7 @@ public class QuorumRequestPipelineTest extends QuorumBase {
for (String child : CHILDREN) {
create2EmptyNode(zkClient, PARENT_PATH + "/" + child);
}
- Assert.assertEquals(
- String.format("%s Parent has expected children", serverState),
- CHILDREN,
- new HashSet<String>(zkClient.getChildren(PARENT_PATH, false)));
+ assertEquals(String.format("%s Parent has expected children", serverState), CHILDREN, new HashSet<String>(zkClient.getChildren(PARENT_PATH, false)));
}
@Test
@@ -167,10 +142,7 @@ public class QuorumRequestPipelineTest extends QuorumBase {
for (String child : CHILDREN) {
create2EmptyNode(zkClient, PARENT_PATH + "/" + child);
}
- Assert.assertEquals(
- String.format("%s Parent has expected children", serverState),
- CHILDREN,
- new HashSet<String>(zkClient.getChildren(PARENT_PATH, false, null)));
+ assertEquals(String.format("%s Parent has expected children", serverState), CHILDREN, new HashSet<String>(zkClient.getChildren(PARENT_PATH, false, null)));
}
@Test
@@ -186,8 +158,7 @@ public class QuorumRequestPipelineTest extends QuorumBase {
};
zkClient.sync(PARENT_PATH, onSync, null);
callComplete.await(30, TimeUnit.SECONDS);
- Assert.assertTrue(
- String.format("%s Sync completed", serverState),
- complete);
+ assertTrue(String.format("%s Sync completed", serverState), complete);
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/QuorumSSLTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/QuorumSSLTest.java
index e47b7ef58..dcd9fcee6 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/QuorumSSLTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/QuorumSSLTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,9 +18,41 @@
package org.apache.zookeeper.server.quorum;
+import static org.apache.zookeeper.test.ClientBase.CONNECTION_TIMEOUT;
+import static org.apache.zookeeper.test.ClientBase.createTmpDir;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
+import java.io.FileOutputStream;
+import java.io.FileWriter;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.math.BigInteger;
+import java.net.InetSocketAddress;
+import java.security.KeyPair;
+import java.security.KeyPairGenerator;
+import java.security.KeyStore;
+import java.security.NoSuchAlgorithmException;
+import java.security.NoSuchProviderException;
+import java.security.PrivateKey;
+import java.security.Security;
+import java.security.cert.Certificate;
+import java.security.cert.CertificateEncodingException;
+import java.security.cert.X509Certificate;
+import java.util.ArrayList;
+import java.util.Calendar;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Random;
+import java.util.concurrent.TimeUnit;
+import javax.net.ssl.SSLServerSocketFactory;
import org.apache.zookeeper.PortAssignment;
import org.apache.zookeeper.client.ZKClientConfig;
import org.apache.zookeeper.common.QuorumX509Util;
@@ -78,43 +110,11 @@ import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder;
import org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder;
import org.bouncycastle.util.io.pem.PemWriter;
import org.junit.After;
-import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.Timeout;
-import javax.net.ssl.SSLServerSocketFactory;
-import java.io.FileOutputStream;
-import java.io.FileWriter;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.math.BigInteger;
-import java.net.InetSocketAddress;
-import java.security.KeyPair;
-import java.security.KeyPairGenerator;
-import java.security.KeyStore;
-import java.security.NoSuchAlgorithmException;
-import java.security.NoSuchProviderException;
-import java.security.PrivateKey;
-import java.security.Security;
-import java.security.cert.Certificate;
-import java.security.cert.CertificateEncodingException;
-import java.security.cert.X509Certificate;
-import java.util.ArrayList;
-import java.util.Calendar;
-import java.util.Date;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Random;
-import java.util.concurrent.TimeUnit;
-
-import static org.apache.zookeeper.test.ClientBase.CONNECTION_TIMEOUT;
-import static org.apache.zookeeper.test.ClientBase.createTmpDir;
-import static org.junit.Assert.fail;
-
public class QuorumSSLTest extends QuorumPeerTestBase {
private static final String SSL_QUORUM_ENABLED = "sslQuorum=true\n";
@@ -151,8 +151,7 @@ public class QuorumSSLTest extends QuorumPeerTestBase {
private Date certEndTime;
@Rule
- public Timeout timeout = Timeout.builder().withTimeout(5, TimeUnit.MINUTES)
- .withLookingForStuckThread(true).build();
+ public Timeout timeout = Timeout.builder().withTimeout(5, TimeUnit.MINUTES).withLookingForStuckThread(true).build();
@Before
public void setup() throws Exception {
@@ -192,8 +191,14 @@ public class QuorumSSLTest extends QuorumPeerTestBase {
outputStream.close();
defaultKeyPair = createKeyPair();
- X509Certificate validCertificate = buildEndEntityCert(defaultKeyPair, rootCertificate, rootKeyPair.getPrivate(),
- HOSTNAME, "127.0.0.1", null, null);
+ X509Certificate validCertificate = buildEndEntityCert(
+ defaultKeyPair,
+ rootCertificate,
+ rootKeyPair.getPrivate(),
+ HOSTNAME,
+ "127.0.0.1",
+ null,
+ null);
writeKeystore(validCertificate, defaultKeyPair, validKeystorePath);
setSSLSystemProperties();
@@ -202,7 +207,7 @@ public class QuorumSSLTest extends QuorumPeerTestBase {
private void writeKeystore(X509Certificate certificate, KeyPair entityKeyPair, String path) throws Exception {
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
keyStore.load(null, PASSWORD);
- keyStore.setKeyEntry("alias", entityKeyPair.getPrivate(), PASSWORD, new Certificate[] { certificate });
+ keyStore.setKeyEntry("alias", entityKeyPair.getPrivate(), PASSWORD, new Certificate[]{certificate});
FileOutputStream outputStream = new FileOutputStream(path);
keyStore.store(outputStream, PASSWORD);
outputStream.flush();
@@ -230,15 +235,12 @@ public class QuorumSSLTest extends QuorumPeerTestBase {
OCSPReq ocspRequest = new OCSPReq(requestBytes);
Req[] requestList = ocspRequest.getRequestList();
- DigestCalculator digestCalculator = new JcaDigestCalculatorProviderBuilder().build()
- .get(CertificateID.HASH_SHA1);
+ DigestCalculator digestCalculator = new JcaDigestCalculatorProviderBuilder().build().get(CertificateID.HASH_SHA1);
- BasicOCSPRespBuilder responseBuilder =
- new JcaBasicOCSPRespBuilder(rootKeyPair.getPublic(), digestCalculator);
- for ( Req req : requestList ) {
+ BasicOCSPRespBuilder responseBuilder = new JcaBasicOCSPRespBuilder(rootKeyPair.getPublic(), digestCalculator);
+ for (Req req : requestList) {
CertificateID certId = req.getCertID();
- CertificateID revokedCertId =
- new JcaCertificateID(digestCalculator, rootCertificate, revokedCert.getSerialNumber());
+ CertificateID revokedCertId = new JcaCertificateID(digestCalculator, rootCertificate, revokedCert.getSerialNumber());
CertificateStatus certificateStatus;
if (revokedCertId.equals(certId)) {
certificateStatus = new UnknownStatus();
@@ -246,20 +248,16 @@ public class QuorumSSLTest extends QuorumPeerTestBase {
certificateStatus = CertificateStatus.GOOD;
}
- responseBuilder.addResponse(certId, certificateStatus,null);
+ responseBuilder.addResponse(certId, certificateStatus, null);
}
- X509CertificateHolder[] chain = new X509CertificateHolder[] {
- new JcaX509CertificateHolder(rootCertificate)
- };
- ContentSigner signer = new JcaContentSignerBuilder("SHA1withRSA").setProvider("BC")
- .build(rootKeyPair.getPrivate());
- BasicOCSPResp ocspResponse = responseBuilder.build(signer, chain, Calendar.getInstance().getTime() );
+ X509CertificateHolder[] chain = new X509CertificateHolder[]{new JcaX509CertificateHolder(rootCertificate)};
+ ContentSigner signer = new JcaContentSignerBuilder("SHA1withRSA").setProvider("BC").build(rootKeyPair.getPrivate());
+ BasicOCSPResp ocspResponse = responseBuilder.build(signer, chain, Calendar.getInstance().getTime());
responseBytes = new OCSPRespBuilder().build(OCSPRespBuilder.SUCCESSFUL, ocspResponse).getEncoded();
} catch (OperatorException | CertificateEncodingException | OCSPException exception) {
- responseBytes = new OCSPResp(new OCSPResponse(
- new OCSPResponseStatus(OCSPRespBuilder.INTERNAL_ERROR), null)).getEncoded();
+ responseBytes = new OCSPResp(new OCSPResponse(new OCSPResponseStatus(OCSPRespBuilder.INTERNAL_ERROR), null)).getEncoded();
}
Headers rh = httpExchange.getResponseHeaders();
@@ -270,6 +268,7 @@ public class QuorumSSLTest extends QuorumPeerTestBase {
os.write(responseBytes);
os.close();
}
+
}
private X509Certificate createSelfSignedCertifcate(KeyPair keyPair) throws Exception {
@@ -277,12 +276,16 @@ public class QuorumSSLTest extends QuorumPeerTestBase {
nameBuilder.addRDN(BCStyle.CN, HOSTNAME);
BigInteger serialNumber = new BigInteger(128, new Random());
- X509v3CertificateBuilder certificateBuilder =
- new JcaX509v3CertificateBuilder(nameBuilder.build(), serialNumber, certStartTime, certEndTime,
- nameBuilder.build(), keyPair.getPublic())
- .addExtension(Extension.basicConstraints, true, new BasicConstraints(0))
- .addExtension(Extension.keyUsage, true,
- new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyCertSign | KeyUsage.cRLSign));
+ JcaX509v3CertificateBuilder jcaX509v3CertificateBuilder = new JcaX509v3CertificateBuilder(
+ nameBuilder.build(),
+ serialNumber,
+ certStartTime,
+ certEndTime,
+ nameBuilder.build(),
+ keyPair.getPublic());
+ X509v3CertificateBuilder certificateBuilder = jcaX509v3CertificateBuilder
+ .addExtension(Extension.basicConstraints, true, new BasicConstraints(0))
+ .addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyCertSign | KeyUsage.cRLSign));
return new JcaX509CertificateConverter().getCertificate(certificateBuilder.build(contentSigner));
}
@@ -291,8 +294,7 @@ public class QuorumSSLTest extends QuorumPeerTestBase {
X509v2CRLBuilder builder = new JcaX509v2CRLBuilder(x509Certificate.getIssuerX500Principal(), certStartTime);
builder.addCRLEntry(x509Certificate.getSerialNumber(), certStartTime, CRLReason.cACompromise);
builder.setNextUpdate(certEndTime);
- builder.addExtension(Extension.authorityKeyIdentifier, false, new JcaX509ExtensionUtils()
- .createAuthorityKeyIdentifier(rootCertificate));
+ builder.addExtension(Extension.authorityKeyIdentifier, false, new JcaX509ExtensionUtils().createAuthorityKeyIdentifier(rootCertificate));
builder.addExtension(Extension.cRLNumber, false, new CRLNumber(new BigInteger("1000")));
X509CRLHolder cRLHolder = builder.build(contentSigner);
@@ -303,11 +305,16 @@ public class QuorumSSLTest extends QuorumPeerTestBase {
pemWriter.close();
}
- public X509Certificate buildEndEntityCert(KeyPair keyPair, X509Certificate caCert, PrivateKey caPrivateKey,
- String hostname, String ipAddress, String crlPath, Integer ocspPort)
- throws Exception {
+ public X509Certificate buildEndEntityCert(
+ KeyPair keyPair,
+ X509Certificate caCert,
+ PrivateKey caPrivateKey,
+ String hostname,
+ String ipAddress,
+ String crlPath,
+ Integer ocspPort) throws Exception {
X509CertificateHolder holder = new JcaX509CertificateHolder(caCert);
- ContentSigner signer =new JcaContentSignerBuilder("SHA256WithRSAEncryption").build(caPrivateKey);
+ ContentSigner signer = new JcaContentSignerBuilder("SHA256WithRSAEncryption").build(caPrivateKey);
List<GeneralName> generalNames = new ArrayList<>();
if (hostname != null) {
@@ -318,49 +325,53 @@ public class QuorumSSLTest extends QuorumPeerTestBase {
generalNames.add(new GeneralName(GeneralName.iPAddress, ipAddress));
}
- SubjectPublicKeyInfo entityKeyInfo =
- SubjectPublicKeyInfoFactory.createSubjectPublicKeyInfo(PublicKeyFactory.createKey(keyPair.getPublic()
- .getEncoded()));
+ SubjectPublicKeyInfo entityKeyInfo = SubjectPublicKeyInfoFactory.createSubjectPublicKeyInfo(
+ PublicKeyFactory.createKey(keyPair.getPublic().getEncoded()));
X509ExtensionUtils extensionUtils = new BcX509ExtensionUtils();
- X509v3CertificateBuilder certificateBuilder =
- new JcaX509v3CertificateBuilder(holder.getSubject(), new BigInteger(128, new Random()),
- certStartTime, certEndTime, new X500Name("CN=Test End Entity Certificate"), keyPair.getPublic())
- .addExtension(Extension.authorityKeyIdentifier, false,
- extensionUtils.createAuthorityKeyIdentifier(holder))
- .addExtension(Extension.subjectKeyIdentifier, false,
- extensionUtils.createSubjectKeyIdentifier(entityKeyInfo))
- .addExtension(Extension.basicConstraints, true, new BasicConstraints(false))
- .addExtension(Extension.keyUsage, true,
- new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment));
+ JcaX509v3CertificateBuilder jcaX509v3CertificateBuilder = new JcaX509v3CertificateBuilder(
+ holder.getSubject(),
+ new BigInteger(128, new Random()),
+ certStartTime,
+ certEndTime,
+ new X500Name("CN=Test End Entity Certificate"),
+ keyPair.getPublic());
+ X509v3CertificateBuilder certificateBuilder = jcaX509v3CertificateBuilder
+ .addExtension(Extension.authorityKeyIdentifier, false, extensionUtils.createAuthorityKeyIdentifier(holder))
+ .addExtension(Extension.subjectKeyIdentifier, false, extensionUtils.createSubjectKeyIdentifier(entityKeyInfo))
+ .addExtension(Extension.basicConstraints, true, new BasicConstraints(false))
+ .addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment));
if (!generalNames.isEmpty()) {
- certificateBuilder.addExtension(Extension.subjectAlternativeName, true,
- new GeneralNames(generalNames.toArray(new GeneralName[] {})));
+ certificateBuilder.addExtension(
+ Extension.subjectAlternativeName,
+ true,
+ new GeneralNames(generalNames.toArray(new GeneralName[]{})));
}
if (crlPath != null) {
- DistributionPointName distPointOne = new DistributionPointName(new GeneralNames(
- new GeneralName(GeneralName.uniformResourceIdentifier,"file://" + crlPath)));
+ DistributionPointName distPointOne = new DistributionPointName(
+ new GeneralNames(new GeneralName(GeneralName.uniformResourceIdentifier, "file://" + crlPath)));
- certificateBuilder.addExtension(Extension.cRLDistributionPoints, false,
- new CRLDistPoint(new DistributionPoint[] {
- new DistributionPoint(distPointOne, null, null)
- }));
+ certificateBuilder.addExtension(
+ Extension.cRLDistributionPoints,
+ false,
+ new CRLDistPoint(new DistributionPoint[]{new DistributionPoint(distPointOne, null, null)}));
}
if (ocspPort != null) {
- certificateBuilder.addExtension(Extension.authorityInfoAccess, false,
- new AuthorityInformationAccess(X509ObjectIdentifiers.ocspAccessMethod,
+ certificateBuilder.addExtension(
+ Extension.authorityInfoAccess,
+ false,
+ new AuthorityInformationAccess(
+ X509ObjectIdentifiers.ocspAccessMethod,
new GeneralName(GeneralName.uniformResourceIdentifier, "http://" + hostname + ":" + ocspPort)));
}
return new JcaX509CertificateConverter().getCertificate(certificateBuilder.build(signer));
}
-
private KeyPair createKeyPair() throws NoSuchProviderException, NoSuchAlgorithmException {
- KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA",
- BouncyCastleProvider.PROVIDER_NAME);
+ KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA", BouncyCastleProvider.PROVIDER_NAME);
keyPairGenerator.initialize(4096);
KeyPair keyPair = keyPairGenerator.genKeyPair();
return keyPair;
@@ -375,17 +386,13 @@ public class QuorumSSLTest extends QuorumPeerTestBase {
int portLe2 = PortAssignment.unique();
int portLe3 = PortAssignment.unique();
-
-
- return "server.1=127.0.0.1:" + (portQp1) + ":" + (portLe1) + ";" + clientPortQp1 + "\n" +
- "server.2=127.0.0.1:" + (portQp2) + ":" + (portLe2) + ";" + clientPortQp2 + "\n" +
- "server.3=127.0.0.1:" + (portQp3) + ":" + (portLe3) + ";" + clientPortQp3;
+ return "server.1=127.0.0.1:" + (portQp1) + ":" + (portLe1) + ";" + clientPortQp1
+ + "\n" + "server.2=127.0.0.1:" + (portQp2) + ":" + (portLe2) + ";" + clientPortQp2
+ + "\n" + "server.3=127.0.0.1:" + (portQp3) + ":" + (portLe3) + ";" + clientPortQp3;
}
-
public void setSSLSystemProperties() {
- System.setProperty(ServerCnxnFactory.ZOOKEEPER_SERVER_CNXN_FACTORY,
- "org.apache.zookeeper.server.NettyServerCnxnFactory");
+ System.setProperty(ServerCnxnFactory.ZOOKEEPER_SERVER_CNXN_FACTORY, "org.apache.zookeeper.server.NettyServerCnxnFactory");
System.setProperty(ZKClientConfig.ZOOKEEPER_CLIENT_CNXN_SOCKET, "org.apache.zookeeper.ClientCnxnSocketNetty");
System.setProperty(quorumX509Util.getSslKeystoreLocationProperty(), validKeystorePath);
System.setProperty(quorumX509Util.getSslKeystorePasswdProperty(), "testpass");
@@ -427,12 +434,11 @@ public class QuorumSSLTest extends QuorumPeerTestBase {
q1 = new MainThread(1, clientPortQp1, quorumConfiguration, SSL_QUORUM_ENABLED);
q2 = new MainThread(2, clientPortQp2, quorumConfiguration, SSL_QUORUM_ENABLED);
-
q1.start();
q2.start();
- Assert.assertTrue(ClientBase.waitForServerUp("127.0.0.1:" + clientPortQp1, CONNECTION_TIMEOUT));
- Assert.assertTrue(ClientBase.waitForServerUp("127.0.0.1:" + clientPortQp2, CONNECTION_TIMEOUT));
+ assertTrue(ClientBase.waitForServerUp("127.0.0.1:" + clientPortQp1, CONNECTION_TIMEOUT));
+ assertTrue(ClientBase.waitForServerUp("127.0.0.1:" + clientPortQp2, CONNECTION_TIMEOUT));
clearSSLSystemProperties();
@@ -440,7 +446,7 @@ public class QuorumSSLTest extends QuorumPeerTestBase {
q3 = new MainThread(3, clientPortQp3, quorumConfiguration);
q3.start();
- Assert.assertFalse(ClientBase.waitForServerUp("127.0.0.1:" + clientPortQp3, CONNECTION_TIMEOUT));
+ assertFalse(ClientBase.waitForServerUp("127.0.0.1:" + clientPortQp3, CONNECTION_TIMEOUT));
}
@Test
@@ -450,7 +456,6 @@ public class QuorumSSLTest extends QuorumPeerTestBase {
q2 = new MainThread(2, clientPortQp2, quorumConfiguration);
q3 = new MainThread(3, clientPortQp3, quorumConfiguration);
-
Map<Integer, MainThread> members = new HashMap<>();
members.put(clientPortQp1, q1);
members.put(clientPortQp2, q2);
@@ -461,7 +466,7 @@ public class QuorumSSLTest extends QuorumPeerTestBase {
}
for (int clientPort : members.keySet()) {
- Assert.assertTrue(ClientBase.waitForServerUp("127.0.0.1:" + clientPort, CONNECTION_TIMEOUT));
+ assertTrue(ClientBase.waitForServerUp("127.0.0.1:" + clientPort, CONNECTION_TIMEOUT));
}
// Set SSL system properties and port unification, begin restarting servers
@@ -478,7 +483,7 @@ public class QuorumSSLTest extends QuorumPeerTestBase {
MainThread member = entry.getValue();
member.shutdown();
- Assert.assertTrue(ClientBase.waitForServerDown("127.0.0.1:" + clientPort, CONNECTION_TIMEOUT));
+ assertTrue(ClientBase.waitForServerDown("127.0.0.1:" + clientPort, CONNECTION_TIMEOUT));
FileWriter fileWriter = new FileWriter(member.getConfFile(), true);
fileWriter.write(config);
@@ -487,15 +492,21 @@ public class QuorumSSLTest extends QuorumPeerTestBase {
member.start();
- Assert.assertTrue(ClientBase.waitForServerUp("127.0.0.1:" + clientPort, CONNECTION_TIMEOUT));
+ assertTrue(ClientBase.waitForServerUp("127.0.0.1:" + clientPort, CONNECTION_TIMEOUT));
}
}
@Test
public void testHostnameVerificationWithInvalidHostname() throws Exception {
String badhostnameKeystorePath = tmpDir + "/badhost.jks";
- X509Certificate badHostCert = buildEndEntityCert(defaultKeyPair, rootCertificate, rootKeyPair.getPrivate(),
- "bleepbloop", null, null, null);
+ X509Certificate badHostCert = buildEndEntityCert(
+ defaultKeyPair,
+ rootCertificate,
+ rootKeyPair.getPrivate(),
+ "bleepbloop",
+ null,
+ null,
+ null);
writeKeystore(badHostCert, defaultKeyPair, badhostnameKeystorePath);
testHostnameVerification(badhostnameKeystorePath, false);
@@ -504,8 +515,14 @@ public class QuorumSSLTest extends QuorumPeerTestBase {
@Test
public void testHostnameVerificationWithInvalidIPAddress() throws Exception {
String badhostnameKeystorePath = tmpDir + "/badhost.jks";
- X509Certificate badHostCert = buildEndEntityCert(defaultKeyPair, rootCertificate, rootKeyPair.getPrivate(),
- null, "140.211.11.105",null, null);
+ X509Certificate badHostCert = buildEndEntityCert(
+ defaultKeyPair,
+ rootCertificate,
+ rootKeyPair.getPrivate(),
+ null,
+ "140.211.11.105",
+ null,
+ null);
writeKeystore(badHostCert, defaultKeyPair, badhostnameKeystorePath);
testHostnameVerification(badhostnameKeystorePath, false);
@@ -514,8 +531,14 @@ public class QuorumSSLTest extends QuorumPeerTestBase {
@Test
public void testHostnameVerificationWithInvalidIpAddressAndInvalidHostname() throws Exception {
String badhostnameKeystorePath = tmpDir + "/badhost.jks";
- X509Certificate badHostCert = buildEndEntityCert(defaultKeyPair, rootCertificate, rootKeyPair.getPrivate(),
- "bleepbloop", "140.211.11.105", null, null);
+ X509Certificate badHostCert = buildEndEntityCert(
+ defaultKeyPair,
+ rootCertificate,
+ rootKeyPair.getPrivate(),
+ "bleepbloop",
+ "140.211.11.105",
+ null,
+ null);
writeKeystore(badHostCert, defaultKeyPair, badhostnameKeystorePath);
testHostnameVerification(badhostnameKeystorePath, false);
@@ -524,8 +547,14 @@ public class QuorumSSLTest extends QuorumPeerTestBase {
@Test
public void testHostnameVerificationWithInvalidIpAddressAndValidHostname() throws Exception {
String badhostnameKeystorePath = tmpDir + "/badhost.jks";
- X509Certificate badHostCert = buildEndEntityCert(defaultKeyPair, rootCertificate, rootKeyPair.getPrivate(),
- "localhost", "140.211.11.105", null, null);
+ X509Certificate badHostCert = buildEndEntityCert(
+ defaultKeyPair,
+ rootCertificate,
+ rootKeyPair.getPrivate(),
+ "localhost",
+ "140.211.11.105",
+ null,
+ null);
writeKeystore(badHostCert, defaultKeyPair, badhostnameKeystorePath);
testHostnameVerification(badhostnameKeystorePath, true);
@@ -534,8 +563,14 @@ public class QuorumSSLTest extends QuorumPeerTestBase {
@Test
public void testHostnameVerificationWithValidIpAddressAndInvalidHostname() throws Exception {
String badhostnameKeystorePath = tmpDir + "/badhost.jks";
- X509Certificate badHostCert = buildEndEntityCert(defaultKeyPair, rootCertificate, rootKeyPair.getPrivate(),
- "bleepbloop", "127.0.0.1", null, null);
+ X509Certificate badHostCert = buildEndEntityCert(
+ defaultKeyPair,
+ rootCertificate,
+ rootKeyPair.getPrivate(),
+ "bleepbloop",
+ "127.0.0.1",
+ null,
+ null);
writeKeystore(badHostCert, defaultKeyPair, badhostnameKeystorePath);
testHostnameVerification(badhostnameKeystorePath, true);
@@ -555,8 +590,8 @@ public class QuorumSSLTest extends QuorumPeerTestBase {
q1.start();
q2.start();
- Assert.assertTrue(ClientBase.waitForServerUp("127.0.0.1:" + clientPortQp1, CONNECTION_TIMEOUT));
- Assert.assertTrue(ClientBase.waitForServerUp("127.0.0.1:" + clientPortQp2, CONNECTION_TIMEOUT));
+ assertTrue(ClientBase.waitForServerUp("127.0.0.1:" + clientPortQp1, CONNECTION_TIMEOUT));
+ assertTrue(ClientBase.waitForServerUp("127.0.0.1:" + clientPortQp2, CONNECTION_TIMEOUT));
System.setProperty(quorumX509Util.getSslKeystoreLocationProperty(), keystorePath);
@@ -564,15 +599,15 @@ public class QuorumSSLTest extends QuorumPeerTestBase {
q3 = new MainThread(3, clientPortQp3, quorumConfiguration, SSL_QUORUM_ENABLED);
q3.start();
- Assert.assertTrue(ClientBase.waitForServerUp("127.0.0.1:" + clientPortQp3, CONNECTION_TIMEOUT));
+ assertTrue(ClientBase.waitForServerUp("127.0.0.1:" + clientPortQp3, CONNECTION_TIMEOUT));
q1.shutdown();
q2.shutdown();
q3.shutdown();
- Assert.assertTrue(ClientBase.waitForServerDown("127.0.0.1:" + clientPortQp1, CONNECTION_TIMEOUT));
- Assert.assertTrue(ClientBase.waitForServerDown("127.0.0.1:" + clientPortQp2, CONNECTION_TIMEOUT));
- Assert.assertTrue(ClientBase.waitForServerDown("127.0.0.1:" + clientPortQp3, CONNECTION_TIMEOUT));
+ assertTrue(ClientBase.waitForServerDown("127.0.0.1:" + clientPortQp1, CONNECTION_TIMEOUT));
+ assertTrue(ClientBase.waitForServerDown("127.0.0.1:" + clientPortQp2, CONNECTION_TIMEOUT));
+ assertTrue(ClientBase.waitForServerDown("127.0.0.1:" + clientPortQp3, CONNECTION_TIMEOUT));
setSSLSystemProperties();
System.clearProperty(quorumX509Util.getSslHostnameVerificationEnabledProperty());
@@ -580,17 +615,17 @@ public class QuorumSSLTest extends QuorumPeerTestBase {
q1.start();
q2.start();
- Assert.assertTrue(ClientBase.waitForServerUp("127.0.0.1:" + clientPortQp1, CONNECTION_TIMEOUT));
- Assert.assertTrue(ClientBase.waitForServerUp("127.0.0.1:" + clientPortQp2, CONNECTION_TIMEOUT));
+ assertTrue(ClientBase.waitForServerUp("127.0.0.1:" + clientPortQp1, CONNECTION_TIMEOUT));
+ assertTrue(ClientBase.waitForServerUp("127.0.0.1:" + clientPortQp2, CONNECTION_TIMEOUT));
System.setProperty(quorumX509Util.getSslKeystoreLocationProperty(), keystorePath);
q3.start();
- Assert.assertEquals(expectSuccess, ClientBase.waitForServerUp("127.0.0.1:" + clientPortQp3,
- CONNECTION_TIMEOUT));
+ assertEquals(
+ expectSuccess,
+ ClientBase.waitForServerUp("127.0.0.1:" + clientPortQp3, CONNECTION_TIMEOUT));
}
-
@Test
public void testCertificateRevocationList() throws Exception {
q1 = new MainThread(1, clientPortQp1, quorumConfiguration, SSL_QUORUM_ENABLED);
@@ -599,13 +634,19 @@ public class QuorumSSLTest extends QuorumPeerTestBase {
q1.start();
q2.start();
- Assert.assertTrue(ClientBase.waitForServerUp("127.0.0.1:" + clientPortQp1, CONNECTION_TIMEOUT));
- Assert.assertTrue(ClientBase.waitForServerUp("127.0.0.1:" + clientPortQp2, CONNECTION_TIMEOUT));
+ assertTrue(ClientBase.waitForServerUp("127.0.0.1:" + clientPortQp1, CONNECTION_TIMEOUT));
+ assertTrue(ClientBase.waitForServerUp("127.0.0.1:" + clientPortQp2, CONNECTION_TIMEOUT));
String revokedInCRLKeystorePath = tmpDir + "/crl_revoked.jks";
String crlPath = tmpDir + "/crl.pem";
- X509Certificate revokedInCRLCert = buildEndEntityCert(defaultKeyPair, rootCertificate, rootKeyPair.getPrivate(),
- HOSTNAME, null, crlPath, null);
+ X509Certificate revokedInCRLCert = buildEndEntityCert(
+ defaultKeyPair,
+ rootCertificate,
+ rootKeyPair.getPrivate(),
+ HOSTNAME,
+ null,
+ crlPath,
+ null);
writeKeystore(revokedInCRLCert, defaultKeyPair, revokedInCRLKeystorePath);
buildCRL(revokedInCRLCert, crlPath);
@@ -615,34 +656,39 @@ public class QuorumSSLTest extends QuorumPeerTestBase {
q3 = new MainThread(3, clientPortQp3, quorumConfiguration, SSL_QUORUM_ENABLED);
q3.start();
- Assert.assertTrue(ClientBase.waitForServerUp("127.0.0.1:" + clientPortQp3, CONNECTION_TIMEOUT));
-
+ assertTrue(ClientBase.waitForServerUp("127.0.0.1:" + clientPortQp3, CONNECTION_TIMEOUT));
q1.shutdown();
q2.shutdown();
q3.shutdown();
- Assert.assertTrue(ClientBase.waitForServerDown("127.0.0.1:" + clientPortQp1, CONNECTION_TIMEOUT));
- Assert.assertTrue(ClientBase.waitForServerDown("127.0.0.1:" + clientPortQp2, CONNECTION_TIMEOUT));
- Assert.assertTrue(ClientBase.waitForServerDown("127.0.0.1:" + clientPortQp3, CONNECTION_TIMEOUT));
+ assertTrue(ClientBase.waitForServerDown("127.0.0.1:" + clientPortQp1, CONNECTION_TIMEOUT));
+ assertTrue(ClientBase.waitForServerDown("127.0.0.1:" + clientPortQp2, CONNECTION_TIMEOUT));
+ assertTrue(ClientBase.waitForServerDown("127.0.0.1:" + clientPortQp3, CONNECTION_TIMEOUT));
setSSLSystemProperties();
System.setProperty(quorumX509Util.getSslCrlEnabledProperty(), "true");
- X509Certificate validCertificate = buildEndEntityCert(defaultKeyPair, rootCertificate, rootKeyPair.getPrivate(),
- HOSTNAME, null, crlPath, null);
+ X509Certificate validCertificate = buildEndEntityCert(
+ defaultKeyPair,
+ rootCertificate,
+ rootKeyPair.getPrivate(),
+ HOSTNAME,
+ null,
+ crlPath,
+ null);
writeKeystore(validCertificate, defaultKeyPair, validKeystorePath);
q1.start();
q2.start();
- Assert.assertTrue(ClientBase.waitForServerUp("127.0.0.1:" + clientPortQp1, CONNECTION_TIMEOUT));
- Assert.assertTrue(ClientBase.waitForServerUp("127.0.0.1:" + clientPortQp2, CONNECTION_TIMEOUT));
+ assertTrue(ClientBase.waitForServerUp("127.0.0.1:" + clientPortQp1, CONNECTION_TIMEOUT));
+ assertTrue(ClientBase.waitForServerUp("127.0.0.1:" + clientPortQp2, CONNECTION_TIMEOUT));
System.setProperty(quorumX509Util.getSslKeystoreLocationProperty(), revokedInCRLKeystorePath);
q3.start();
- Assert.assertFalse(ClientBase.waitForServerUp("127.0.0.1:" + clientPortQp3, CONNECTION_TIMEOUT));
+ assertFalse(ClientBase.waitForServerUp("127.0.0.1:" + clientPortQp3, CONNECTION_TIMEOUT));
}
@Test
@@ -655,12 +701,18 @@ public class QuorumSSLTest extends QuorumPeerTestBase {
q1.start();
q2.start();
- Assert.assertTrue(ClientBase.waitForServerUp("127.0.0.1:" + clientPortQp1, CONNECTION_TIMEOUT));
- Assert.assertTrue(ClientBase.waitForServerUp("127.0.0.1:" + clientPortQp2, CONNECTION_TIMEOUT));
+ assertTrue(ClientBase.waitForServerUp("127.0.0.1:" + clientPortQp1, CONNECTION_TIMEOUT));
+ assertTrue(ClientBase.waitForServerUp("127.0.0.1:" + clientPortQp2, CONNECTION_TIMEOUT));
String revokedInOCSPKeystorePath = tmpDir + "/ocsp_revoked.jks";
- X509Certificate revokedInOCSPCert = buildEndEntityCert(defaultKeyPair, rootCertificate, rootKeyPair.getPrivate(),
- HOSTNAME, null,null, ocspPort);
+ X509Certificate revokedInOCSPCert = buildEndEntityCert(
+ defaultKeyPair,
+ rootCertificate,
+ rootKeyPair.getPrivate(),
+ HOSTNAME,
+ null,
+ null,
+ ocspPort);
writeKeystore(revokedInOCSPCert, defaultKeyPair, revokedInOCSPKeystorePath);
HttpServer ocspServer = HttpServer.create(new InetSocketAddress(ocspPort), 0);
@@ -674,34 +726,39 @@ public class QuorumSSLTest extends QuorumPeerTestBase {
q3 = new MainThread(3, clientPortQp3, quorumConfiguration, SSL_QUORUM_ENABLED);
q3.start();
- Assert.assertTrue(ClientBase.waitForServerUp("127.0.0.1:" + clientPortQp3, CONNECTION_TIMEOUT));
+ assertTrue(ClientBase.waitForServerUp("127.0.0.1:" + clientPortQp3, CONNECTION_TIMEOUT));
q1.shutdown();
q2.shutdown();
q3.shutdown();
- Assert.assertTrue(ClientBase.waitForServerDown("127.0.0.1:" + clientPortQp1, CONNECTION_TIMEOUT));
- Assert.assertTrue(ClientBase.waitForServerDown("127.0.0.1:" + clientPortQp2, CONNECTION_TIMEOUT));
- Assert.assertTrue(ClientBase.waitForServerDown("127.0.0.1:" + clientPortQp3, CONNECTION_TIMEOUT));
+ assertTrue(ClientBase.waitForServerDown("127.0.0.1:" + clientPortQp1, CONNECTION_TIMEOUT));
+ assertTrue(ClientBase.waitForServerDown("127.0.0.1:" + clientPortQp2, CONNECTION_TIMEOUT));
+ assertTrue(ClientBase.waitForServerDown("127.0.0.1:" + clientPortQp3, CONNECTION_TIMEOUT));
setSSLSystemProperties();
System.setProperty(quorumX509Util.getSslOcspEnabledProperty(), "true");
- X509Certificate validCertificate = buildEndEntityCert(defaultKeyPair, rootCertificate,
- rootKeyPair.getPrivate(),
- HOSTNAME, null,null, ocspPort);
+ X509Certificate validCertificate = buildEndEntityCert(
+ defaultKeyPair,
+ rootCertificate,
+ rootKeyPair.getPrivate(),
+ HOSTNAME,
+ null,
+ null,
+ ocspPort);
writeKeystore(validCertificate, defaultKeyPair, validKeystorePath);
q1.start();
q2.start();
- Assert.assertTrue(ClientBase.waitForServerUp("127.0.0.1:" + clientPortQp1, CONNECTION_TIMEOUT));
- Assert.assertTrue(ClientBase.waitForServerUp("127.0.0.1:" + clientPortQp2, CONNECTION_TIMEOUT));
+ assertTrue(ClientBase.waitForServerUp("127.0.0.1:" + clientPortQp1, CONNECTION_TIMEOUT));
+ assertTrue(ClientBase.waitForServerUp("127.0.0.1:" + clientPortQp2, CONNECTION_TIMEOUT));
System.setProperty(quorumX509Util.getSslKeystoreLocationProperty(), revokedInOCSPKeystorePath);
q3.start();
- Assert.assertFalse(ClientBase.waitForServerUp("127.0.0.1:" + clientPortQp3, CONNECTION_TIMEOUT));
+ assertFalse(ClientBase.waitForServerUp("127.0.0.1:" + clientPortQp3, CONNECTION_TIMEOUT));
} finally {
ocspServer.stop(0);
}
@@ -710,7 +767,7 @@ public class QuorumSSLTest extends QuorumPeerTestBase {
@Test
public void testCipherSuites() throws Exception {
// Get default cipher suites from JDK
- SSLServerSocketFactory ssf = (SSLServerSocketFactory)SSLServerSocketFactory.getDefault();
+ SSLServerSocketFactory ssf = (SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
List<String> defaultCiphers = new ArrayList<String>();
for (String cipher : ssf.getDefaultCipherSuites()) {
if (!cipher.matches(".*EMPTY.*") && cipher.startsWith("TLS") && cipher.contains("RSA")) {
@@ -732,8 +789,8 @@ public class QuorumSSLTest extends QuorumPeerTestBase {
q1.start();
q2.start();
- Assert.assertTrue(ClientBase.waitForServerUp("127.0.0.1:" + clientPortQp1, CONNECTION_TIMEOUT));
- Assert.assertTrue(ClientBase.waitForServerUp("127.0.0.1:" + clientPortQp2, CONNECTION_TIMEOUT));
+ assertTrue(ClientBase.waitForServerUp("127.0.0.1:" + clientPortQp1, CONNECTION_TIMEOUT));
+ assertTrue(ClientBase.waitForServerUp("127.0.0.1:" + clientPortQp2, CONNECTION_TIMEOUT));
// Use the odd one out for the client
String suiteOfClient = defaultCiphers.get(0);
@@ -744,7 +801,7 @@ public class QuorumSSLTest extends QuorumPeerTestBase {
q3 = new MainThread(3, clientPortQp3, quorumConfiguration, SSL_QUORUM_ENABLED);
q3.start();
- Assert.assertFalse(ClientBase.waitForServerUp("127.0.0.1:" + clientPortQp3, CONNECTION_TIMEOUT));
+ assertFalse(ClientBase.waitForServerUp("127.0.0.1:" + clientPortQp3, CONNECTION_TIMEOUT));
}
@Test
@@ -757,8 +814,8 @@ public class QuorumSSLTest extends QuorumPeerTestBase {
q1.start();
q2.start();
- Assert.assertTrue(ClientBase.waitForServerUp("127.0.0.1:" + clientPortQp1, CONNECTION_TIMEOUT));
- Assert.assertTrue(ClientBase.waitForServerUp("127.0.0.1:" + clientPortQp2, CONNECTION_TIMEOUT));
+ assertTrue(ClientBase.waitForServerUp("127.0.0.1:" + clientPortQp1, CONNECTION_TIMEOUT));
+ assertTrue(ClientBase.waitForServerUp("127.0.0.1:" + clientPortQp2, CONNECTION_TIMEOUT));
System.setProperty(quorumX509Util.getSslProtocolProperty(), "TLSv1.1");
@@ -766,6 +823,7 @@ public class QuorumSSLTest extends QuorumPeerTestBase {
q3 = new MainThread(3, clientPortQp3, quorumConfiguration, SSL_QUORUM_ENABLED);
q3.start();
- Assert.assertFalse(ClientBase.waitForServerUp("127.0.0.1:" + clientPortQp3, CONNECTION_TIMEOUT));
+ assertFalse(ClientBase.waitForServerUp("127.0.0.1:" + clientPortQp3, CONNECTION_TIMEOUT));
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/QuorumServerTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/QuorumServerTest.java
index 62d9a7ba4..c8cbadac5 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/QuorumServerTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/QuorumServerTest.java
@@ -14,20 +14,19 @@
* License for the specific language governing permissions and limitations under
* the License.
*/
+
package org.apache.zookeeper.server.quorum;
import static org.junit.Assert.assertEquals;
-
+import java.net.InetSocketAddress;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZKTestCase;
import org.apache.zookeeper.server.quorum.QuorumPeer.QuorumServer;
import org.apache.zookeeper.server.quorum.QuorumPeerConfig.ConfigException;
-import org.junit.Assert;
import org.junit.Test;
-import java.net.InetSocketAddress;
-
public class QuorumServerTest extends ZKTestCase {
+
private String ipv6n1 = "[2500:0:0:0:0:0:1:0]";
private String ipv6n2 = "[2600:0:0:0:0:0:1:0]";
private String ipv4config = "127.0.0.1:1234:1236";
@@ -37,34 +36,32 @@ public class QuorumServerTest extends ZKTestCase {
String provided = ipv4config + ":participant;0.0.0.0:1237";
String expected = ipv4config + ":participant;0.0.0.0:1237";
QuorumServer qs = new QuorumServer(0, provided);
- Assert.assertEquals("Use IP address", expected, qs.toString());
+ assertEquals("Use IP address", expected, qs.toString());
provided = ipv4config + ";0.0.0.0:1237";
expected = ipv4config + ":participant;0.0.0.0:1237";
qs = new QuorumServer(0, provided);
- Assert.assertEquals("Type unspecified", expected, qs.toString());
+ assertEquals("Type unspecified", expected, qs.toString());
provided = ipv4config + ":observer;0.0.0.0:1237";
expected = ipv4config + ":observer;0.0.0.0:1237";
qs = new QuorumServer(0, provided);
- Assert.assertEquals("Observer type", expected, qs.toString());
+ assertEquals("Observer type", expected, qs.toString());
provided = ipv4config + ":participant;1237";
expected = ipv4config + ":participant;0.0.0.0:1237";
qs = new QuorumServer(0, provided);
- Assert.assertEquals("Client address unspecified",
- expected, qs.toString());
+ assertEquals("Client address unspecified", expected, qs.toString());
provided = ipv4config + ":participant;1.2.3.4:1237";
expected = ipv4config + ":participant;1.2.3.4:1237";
qs = new QuorumServer(0, provided);
- Assert.assertEquals("Client address specified",
- expected, qs.toString());
+ assertEquals("Client address specified", expected, qs.toString());
provided = "example.com:1234:1236:participant;1237";
expected = "example.com:1234:1236:participant;0.0.0.0:1237";
qs = new QuorumServer(0, provided);
- Assert.assertEquals("Use hostname", expected, qs.toString());
+ assertEquals("Use hostname", expected, qs.toString());
}
@Test
@@ -96,18 +93,14 @@ public class QuorumServerTest extends ZKTestCase {
String[] addrs = new String[]{"127.0.0.1", "[0:0:0:0:0:0:0:1]", "0.0.0.0", "[::]"};
for (int i = 0; i < addrs.length; i++) {
for (int j = i; j < addrs.length; j++) {
- QuorumPeer.QuorumServer server1 =
- new QuorumPeer.QuorumServer(1,
- new InetSocketAddress(ipv6n1, 1234), // peer
- new InetSocketAddress(ipv6n1, 1236), // election
- new InetSocketAddress(addrs[i], 1237) // client
- );
- QuorumPeer.QuorumServer server2 =
- new QuorumPeer.QuorumServer(2,
- new InetSocketAddress(ipv6n2, 1234), // peer
- new InetSocketAddress(ipv6n2, 1236), // election
- new InetSocketAddress(addrs[j], 1237) // client
- );
+ QuorumPeer.QuorumServer server1 = new QuorumPeer.QuorumServer(1, new InetSocketAddress(ipv6n1, 1234), // peer
+ new InetSocketAddress(ipv6n1, 1236), // election
+ new InetSocketAddress(addrs[i], 1237) // client
+ );
+ QuorumPeer.QuorumServer server2 = new QuorumPeer.QuorumServer(2, new InetSocketAddress(ipv6n2, 1234), // peer
+ new InetSocketAddress(ipv6n2, 1236), // election
+ new InetSocketAddress(addrs[j], 1237) // client
+ );
server1.checkAddressDuplicate(server2);
}
}
@@ -115,18 +108,15 @@ public class QuorumServerTest extends ZKTestCase {
@Test(expected = KeeperException.BadArgumentsException.class)
public void testDuplicate() throws KeeperException.BadArgumentsException {
- QuorumPeer.QuorumServer server1 =
- new QuorumPeer.QuorumServer(1,
- new InetSocketAddress(ipv6n1, 1234), // peer
- new InetSocketAddress(ipv6n1, 1236), // election
- new InetSocketAddress(ipv6n1, 1237) // client
- );
- QuorumPeer.QuorumServer server2 =
- new QuorumPeer.QuorumServer(2,
- new InetSocketAddress(ipv6n2, 1234), // peer
- new InetSocketAddress(ipv6n2, 1236), // election
- new InetSocketAddress(ipv6n1, 1237) // client
- );
+ QuorumPeer.QuorumServer server1 = new QuorumPeer.QuorumServer(1, new InetSocketAddress(ipv6n1, 1234), // peer
+ new InetSocketAddress(ipv6n1, 1236), // election
+ new InetSocketAddress(ipv6n1, 1237) // client
+ );
+ QuorumPeer.QuorumServer server2 = new QuorumPeer.QuorumServer(2, new InetSocketAddress(ipv6n2, 1234), // peer
+ new InetSocketAddress(ipv6n2, 1236), // election
+ new InetSocketAddress(ipv6n1, 1237) // client
+ );
server1.checkAddressDuplicate(server2);
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/RaceConditionTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/RaceConditionTest.java
index ea2a4d385..38739a1f2 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/RaceConditionTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/RaceConditionTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -15,16 +15,16 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
package org.apache.zookeeper.server.quorum;
import static org.apache.zookeeper.test.ClientBase.CONNECTION_TIMEOUT;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
-
import java.io.IOException;
import java.net.SocketException;
import java.nio.ByteBuffer;
-
+import javax.security.sasl.SaslException;
import org.apache.zookeeper.PortAssignment;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.common.X509Exception;
@@ -38,18 +38,16 @@ import org.apache.zookeeper.server.persistence.FileTxnSnapLog;
import org.apache.zookeeper.server.quorum.QuorumPeer.ServerState;
import org.apache.zookeeper.test.ClientBase;
import org.junit.After;
-import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import javax.security.sasl.SaslException;
-
/**
* This test class contains test cases related to race condition in complete
* ZooKeeper
*/
public class RaceConditionTest extends QuorumPeerTestBase {
+
protected static final Logger LOG = LoggerFactory.getLogger(RaceConditionTest.class);
private static int SERVER_COUNT = 3;
private MainThread[] mt;
@@ -77,15 +75,15 @@ public class RaceConditionTest extends QuorumPeerTestBase {
* after the leader election, not the old LEADING state.
* </pre>
*/
- boolean leaderStateChanged = ClientBase.waitForServerState(leader, 15000,
- QuorumStats.Provider.LOOKING_STATE, QuorumStats.Provider.FOLLOWING_STATE);
+ boolean leaderStateChanged = ClientBase.waitForServerState(leader, 15000, QuorumStats.Provider.LOOKING_STATE, QuorumStats.Provider.FOLLOWING_STATE);
// Wait for the old leader to start completely
- Assert.assertTrue("Failed to bring up the old leader server", ClientBase
- .waitForServerUp("127.0.0.1:" + leader.getClientPort(), CONNECTION_TIMEOUT));
assertTrue(
- "Leader failed to transition to new state. Current state is "
- + leader.getServerState(),
- leaderStateChanged || (leader.getCurrentEpoch() > oldLeaderCurrentEpoch));
+ "Failed to bring up the old leader server",
+ ClientBase.waitForServerUp("127.0.0.1:" + leader.getClientPort(), CONNECTION_TIMEOUT));
+ assertTrue(
+ "Leader failed to transition to new state. Current state is " + leader.getServerState(),
+ leaderStateChanged
+ || (leader.getCurrentEpoch() > oldLeaderCurrentEpoch));
}
@After
@@ -105,18 +103,18 @@ public class RaceConditionTest extends QuorumPeerTestBase {
}
private MainThread[] startQuorum() throws IOException {
- final int clientPorts[] = new int[SERVER_COUNT];
+ final int[] clientPorts = new int[SERVER_COUNT];
StringBuilder sb = new StringBuilder();
String server;
for (int i = 0; i < SERVER_COUNT; i++) {
clientPorts[i] = PortAssignment.unique();
server = "server." + i + "=127.0.0.1:" + PortAssignment.unique() + ":" + PortAssignment.unique()
- + ":participant;127.0.0.1:" + clientPorts[i];
+ + ":participant;127.0.0.1:" + clientPorts[i];
sb.append(server + "\n");
}
String currentQuorumCfgSection = sb.toString();
- MainThread mt[] = new MainThread[SERVER_COUNT];
+ MainThread[] mt = new MainThread[SERVER_COUNT];
// start all the servers
for (int i = 0; i < SERVER_COUNT; i++) {
@@ -131,7 +129,8 @@ public class RaceConditionTest extends QuorumPeerTestBase {
// ensure all servers started
for (int i = 0; i < SERVER_COUNT; i++) {
- Assert.assertTrue("waiting for server " + i + " being up",
+ assertTrue(
+ "waiting for server " + i + " being up",
ClientBase.waitForServerUp("127.0.0.1:" + clientPorts[i], CONNECTION_TIMEOUT));
}
return mt;
@@ -157,6 +156,7 @@ public class RaceConditionTest extends QuorumPeerTestBase {
}
private static class CustomQuorumPeer extends QuorumPeer {
+
private boolean stopPing;
public CustomQuorumPeer() throws SaslException {
@@ -192,13 +192,10 @@ public class RaceConditionTest extends QuorumPeerTestBase {
* MockSyncRequestProcessor
*/
RequestProcessor finalProcessor = new FinalRequestProcessor(this);
- RequestProcessor toBeAppliedProcessor = new Leader.ToBeAppliedRequestProcessor(finalProcessor,
- getLeader());
- commitProcessor = new CommitProcessor(toBeAppliedProcessor, Long.toString(getServerId()), false,
- getZooKeeperServerListener());
+ RequestProcessor toBeAppliedProcessor = new Leader.ToBeAppliedRequestProcessor(finalProcessor, getLeader());
+ commitProcessor = new CommitProcessor(toBeAppliedProcessor, Long.toString(getServerId()), false, getZooKeeperServerListener());
commitProcessor.start();
- ProposalRequestProcessor proposalProcessor = new MockProposalRequestProcessor(this,
- commitProcessor);
+ ProposalRequestProcessor proposalProcessor = new MockProposalRequestProcessor(this, commitProcessor);
proposalProcessor.initialize();
prepRequestProcessor = new PrepRequestProcessor(this, proposalProcessor);
prepRequestProcessor.start();
@@ -208,6 +205,7 @@ public class RaceConditionTest extends QuorumPeerTestBase {
};
return new Leader(this, zk);
}
+
}
private static class MockSyncRequestProcessor extends SyncRequestProcessor {
@@ -222,14 +220,15 @@ public class RaceConditionTest extends QuorumPeerTestBase {
* Add a request so that something is there for SyncRequestProcessor
* to process, while we are in shutdown flow
*/
- Request request = new Request(null, 0, 0, ZooDefs.OpCode.delete,
- ByteBuffer.wrap("/deadLockIssue".getBytes()), null);
+ Request request = new Request(null, 0, 0, ZooDefs.OpCode.delete, ByteBuffer.wrap("/deadLockIssue".getBytes()), null);
processRequest(request);
super.shutdown();
}
+
}
private static class MockProposalRequestProcessor extends ProposalRequestProcessor {
+
public MockProposalRequestProcessor(LeaderZooKeeperServer zks, RequestProcessor nextProcessor) {
super(zks, nextProcessor);
@@ -240,6 +239,7 @@ public class RaceConditionTest extends QuorumPeerTestBase {
AckRequestProcessor ackProcessor = new AckRequestProcessor(zks.getLeader());
syncProcessor = new MockSyncRequestProcessor(zks, ackProcessor);
}
+
}
private static class MockTestQPMain extends TestQPMain {
@@ -248,5 +248,7 @@ public class RaceConditionTest extends QuorumPeerTestBase {
protected QuorumPeer getQuorumPeer() throws SaslException {
return new CustomQuorumPeer();
}
+
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/ReconfigBackupTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/ReconfigBackupTest.java
index 581cb506b..8efb9d7cc 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/ReconfigBackupTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/ReconfigBackupTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,16 +18,11 @@
package org.apache.zookeeper.server.quorum;
-import org.apache.zookeeper.PortAssignment;
-import org.apache.zookeeper.ZooKeeper;
-import org.apache.zookeeper.admin.ZooKeeperAdmin;
-import org.apache.zookeeper.common.StringUtils;
-import org.apache.zookeeper.test.ClientBase;
-import org.apache.zookeeper.test.ReconfigTest;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
-
+import static org.apache.zookeeper.test.ClientBase.CONNECTION_TIMEOUT;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
@@ -38,8 +33,14 @@ import java.util.Collections;
import java.util.List;
import java.util.Properties;
import java.util.Scanner;
-
-import static org.apache.zookeeper.test.ClientBase.CONNECTION_TIMEOUT;
+import org.apache.zookeeper.PortAssignment;
+import org.apache.zookeeper.ZooKeeper;
+import org.apache.zookeeper.admin.ZooKeeperAdmin;
+import org.apache.zookeeper.common.StringUtils;
+import org.apache.zookeeper.test.ClientBase;
+import org.apache.zookeeper.test.ReconfigTest;
+import org.junit.Before;
+import org.junit.Test;
public class ReconfigBackupTest extends QuorumPeerTestBase {
@@ -62,8 +63,7 @@ public class ReconfigBackupTest extends QuorumPeerTestBase {
@Before
public void setup() {
ClientBase.setupTestEnv();
- System.setProperty("zookeeper.DigestAuthenticationProvider.superDigest",
- "super:D/InIHSb7yEEbrWz8b9l71RjZJU="/* password is 'test'*/);
+ System.setProperty("zookeeper.DigestAuthenticationProvider.superDigest", "super:D/InIHSb7yEEbrWz8b9l71RjZJU="/* password is 'test'*/);
}
/**
@@ -72,41 +72,39 @@ public class ReconfigBackupTest extends QuorumPeerTestBase {
@Test
public void testBackupStatic() throws Exception {
final int SERVER_COUNT = 3;
- final int clientPorts[] = new int[SERVER_COUNT];
+ final int[] clientPorts = new int[SERVER_COUNT];
StringBuilder sb = new StringBuilder();
String server;
for (int i = 0; i < SERVER_COUNT; i++) {
clientPorts[i] = PortAssignment.unique();
- server = "server." + i + "=localhost:" + PortAssignment.unique()
- + ":" + PortAssignment.unique() + ":participant;localhost:"
- + clientPorts[i];
+ server = "server." + i + "=localhost:" + PortAssignment.unique() + ":" + PortAssignment.unique()
+ + ":participant;localhost:" + clientPorts[i];
sb.append(server + "\n");
}
String currentQuorumCfgSection = sb.toString();
- MainThread mt[] = new MainThread[SERVER_COUNT];
+ MainThread[] mt = new MainThread[SERVER_COUNT];
String[] staticFileContent = new String[SERVER_COUNT];
String[] staticBackupContent = new String[SERVER_COUNT];
for (int i = 0; i < SERVER_COUNT; i++) {
mt[i] = new MainThread(i, clientPorts[i], currentQuorumCfgSection, false);
// check that a dynamic configuration file doesn't exist
- Assert.assertNull("static file backup shouldn't exist before bootup",
- mt[i].getFileByName("zoo.cfg.bak"));
+ assertNull("static file backup shouldn't exist before bootup", mt[i].getFileByName("zoo.cfg.bak"));
staticFileContent[i] = getFileContent(mt[i].confFile);
mt[i].start();
}
for (int i = 0; i < SERVER_COUNT; i++) {
- Assert.assertTrue("waiting for server " + i + " being up",
- ClientBase.waitForServerUp("127.0.0.1:" + clientPorts[i],
- CONNECTION_TIMEOUT));
+ assertTrue(
+ "waiting for server " + i + " being up",
+ ClientBase.waitForServerUp("127.0.0.1:" + clientPorts[i], CONNECTION_TIMEOUT));
File backupFile = mt[i].getFileByName("zoo.cfg.bak");
- Assert.assertNotNull("static file backup should exist", backupFile);
+ assertNotNull("static file backup should exist", backupFile);
staticBackupContent[i] = getFileContent(backupFile);
- Assert.assertEquals(staticFileContent[i], staticBackupContent[i]);
+ assertEquals(staticFileContent[i], staticBackupContent[i]);
}
for (int i = 0; i < SERVER_COUNT; i++) {
@@ -124,10 +122,10 @@ public class ReconfigBackupTest extends QuorumPeerTestBase {
final int SERVER_COUNT = 3;
final int NEW_SERVER_COUNT = 5;
- final int clientPorts[] = new int[NEW_SERVER_COUNT];
- final int quorumPorts[] = new int[NEW_SERVER_COUNT];
- final int electionPorts[] = new int[NEW_SERVER_COUNT];
- final String servers[] = new String[NEW_SERVER_COUNT];
+ final int[] clientPorts = new int[NEW_SERVER_COUNT];
+ final int[] quorumPorts = new int[NEW_SERVER_COUNT];
+ final int[] electionPorts = new int[NEW_SERVER_COUNT];
+ final String[] servers = new String[NEW_SERVER_COUNT];
StringBuilder sb = new StringBuilder();
ArrayList<String> oldServers = new ArrayList<String>();
@@ -137,9 +135,7 @@ public class ReconfigBackupTest extends QuorumPeerTestBase {
clientPorts[i] = PortAssignment.unique();
quorumPorts[i] = PortAssignment.unique();
electionPorts[i] = PortAssignment.unique();
- servers[i] = "server." + i + "=localhost:" + quorumPorts[i]
- + ":" + electionPorts[i] + ":participant;localhost:"
- + clientPorts[i];
+ servers[i] = "server." + i + "=localhost:" + quorumPorts[i] + ":" + electionPorts[i] + ":participant;localhost:" + clientPorts[i];
newServers.add(servers[i]);
@@ -152,9 +148,9 @@ public class ReconfigBackupTest extends QuorumPeerTestBase {
String quorumCfgSection = sb.toString();
- MainThread mt[] = new MainThread[NEW_SERVER_COUNT];
- ZooKeeper zk[] = new ZooKeeper[NEW_SERVER_COUNT];
- ZooKeeperAdmin zkAdmin[] = new ZooKeeperAdmin[NEW_SERVER_COUNT];
+ MainThread[] mt = new MainThread[NEW_SERVER_COUNT];
+ ZooKeeper[] zk = new ZooKeeper[NEW_SERVER_COUNT];
+ ZooKeeperAdmin[] zkAdmin = new ZooKeeperAdmin[NEW_SERVER_COUNT];
// start old cluster
for (int i = 0; i < SERVER_COUNT; i++) {
@@ -166,32 +162,30 @@ public class ReconfigBackupTest extends QuorumPeerTestBase {
// test old cluster
for (int i = 0; i < SERVER_COUNT; i++) {
- Assert.assertTrue("waiting for server " + i + " being up",
- ClientBase.waitForServerUp("127.0.0.1:" + clientPorts[i],
- CONNECTION_TIMEOUT));
+ assertTrue(
+ "waiting for server " + i + " being up",
+ ClientBase.waitForServerUp("127.0.0.1:" + clientPorts[i], CONNECTION_TIMEOUT));
zk[i] = ClientBase.createZKClient("127.0.0.1:" + clientPorts[i]);
- zkAdmin[i] = new ZooKeeperAdmin("127.0.0.1:" + clientPorts[i],
- ClientBase.CONNECTION_TIMEOUT, this);
+ zkAdmin[i] = new ZooKeeperAdmin("127.0.0.1:" + clientPorts[i], ClientBase.CONNECTION_TIMEOUT, this);
zkAdmin[i].addAuthInfo("digest", "super:test".getBytes());
Properties cfg = ReconfigLegacyTest.readPropertiesFromFile(mt[i].confFile);
String filename = cfg.getProperty("dynamicConfigFile", "");
String version = QuorumPeerConfig.getVersionFromFilename(filename);
- Assert.assertNotNull(version);
+ assertNotNull(version);
- String configStr = ReconfigTest.testServerHasConfig(
- zk[i], oldServers, null);
+ String configStr = ReconfigTest.testServerHasConfig(zk[i], oldServers, null);
String configVersion = getVersionFromConfigStr(configStr);
// the version appended to filename should be the same as
// the one of quorum verifier.
- Assert.assertEquals(version, configVersion);
+ assertEquals(version, configVersion);
if (i == 0) {
firstVersion = version;
} else {
- Assert.assertEquals(firstVersion, version);
+ assertEquals(firstVersion, version);
}
}
@@ -205,9 +199,9 @@ public class ReconfigBackupTest extends QuorumPeerTestBase {
// wait for new servers to be up running
for (int i = SERVER_COUNT; i < NEW_SERVER_COUNT; i++) {
- Assert.assertTrue("waiting for server " + i + " being up",
- ClientBase.waitForServerUp("127.0.0.1:" + clientPorts[i],
- CONNECTION_TIMEOUT));
+ assertTrue(
+ "waiting for server " + i + " being up",
+ ClientBase.waitForServerUp("127.0.0.1:" + clientPorts[i], CONNECTION_TIMEOUT));
zk[i] = ClientBase.createZKClient("127.0.0.1:" + clientPorts[i]);
}
@@ -218,21 +212,18 @@ public class ReconfigBackupTest extends QuorumPeerTestBase {
String filename = cfg.getProperty("dynamicConfigFile", "");
String version = QuorumPeerConfig.getVersionFromFilename(filename);
- Assert.assertNotNull(version);
+ assertNotNull(version);
- String configStr = ReconfigTest.testServerHasConfig(zk[i],
- newServers, null);
+ String configStr = ReconfigTest.testServerHasConfig(zk[i], newServers, null);
String quorumVersion = getVersionFromConfigStr(configStr);
- Assert.assertEquals(version, quorumVersion);
+ assertEquals(version, quorumVersion);
if (i == 0) {
secondVersion = version;
- Assert.assertTrue(
- Long.parseLong(secondVersion, 16)
- > Long.parseLong(firstVersion, 16));
+ assertTrue(Long.parseLong(secondVersion, 16) > Long.parseLong(firstVersion, 16));
} else {
- Assert.assertEquals(secondVersion, version);
+ assertEquals(secondVersion, version);
}
}
@@ -256,18 +247,16 @@ public class ReconfigBackupTest extends QuorumPeerTestBase {
final int SERVER_COUNT = 5;
final int oldServerCount = 3;
final int lagOffServerId = 0;
- final int clientPorts[] = new int[SERVER_COUNT];
+ final int[] clientPorts = new int[SERVER_COUNT];
StringBuilder sb = new StringBuilder();
String server;
StringBuilder oldSb = new StringBuilder();
ArrayList<String> allServers = new ArrayList<String>();
-
for (int i = 0; i < SERVER_COUNT; i++) {
clientPorts[i] = PortAssignment.unique();
- server = "server." + i + "=localhost:" + PortAssignment.unique()
- + ":" + PortAssignment.unique() + ":participant;localhost:"
- + clientPorts[i];
+ server = "server." + i + "=localhost:" + PortAssignment.unique() + ":" + PortAssignment.unique()
+ + ":participant;localhost:" + clientPorts[i];
sb.append(server + "\n");
allServers.add(server);
@@ -281,34 +270,25 @@ public class ReconfigBackupTest extends QuorumPeerTestBase {
String oldQuorumCfg = oldSb.toString();
- MainThread mt[] = new MainThread[SERVER_COUNT];
-
+ MainThread[] mt = new MainThread[SERVER_COUNT];
for (int i = 0; i < SERVER_COUNT; i++) {
if (i == lagOffServerId) {
mt[i] = new MainThread(i, clientPorts[i], oldQuorumCfg, true, "100000000");
} else {
- mt[i] = new MainThread(i, clientPorts[i], currentQuorumCfgSection,
- true, "200000000");
+ mt[i] = new MainThread(i, clientPorts[i], currentQuorumCfgSection, true, "200000000");
}
// before connecting to quorum, servers should have set up dynamic file
// version and pointer. And the lag-off server is using the older
// version dynamic file.
if (i == lagOffServerId) {
- Assert.assertNotNull(
- mt[i].getFileByName("zoo.cfg.dynamic.100000000"));
- Assert.assertNull(
- mt[i].getFileByName("zoo.cfg.dynamic.200000000"));
- Assert.assertTrue(
- mt[i].getPropFromStaticFile("dynamicConfigFile")
- .endsWith(".100000000"));
+ assertNotNull(mt[i].getFileByName("zoo.cfg.dynamic.100000000"));
+ assertNull(mt[i].getFileByName("zoo.cfg.dynamic.200000000"));
+ assertTrue(mt[i].getPropFromStaticFile("dynamicConfigFile").endsWith(".100000000"));
} else {
- Assert.assertNotNull(
- mt[i].getFileByName("zoo.cfg.dynamic.200000000"));
- Assert.assertTrue(
- mt[i].getPropFromStaticFile("dynamicConfigFile")
- .endsWith(".200000000"));
+ assertNotNull(mt[i].getFileByName("zoo.cfg.dynamic.200000000"));
+ assertTrue(mt[i].getPropFromStaticFile("dynamicConfigFile").endsWith(".200000000"));
}
mt[i].start();
@@ -317,32 +297,31 @@ public class ReconfigBackupTest extends QuorumPeerTestBase {
String dynamicFileContent = null;
for (int i = 0; i < SERVER_COUNT; i++) {
- Assert.assertTrue("waiting for server " + i + " being up",
- ClientBase.waitForServerUp("127.0.0.1:" + clientPorts[i],
- CONNECTION_TIMEOUT));
+ assertTrue(
+ "waiting for server " + i + " being up",
+ ClientBase.waitForServerUp("127.0.0.1:" + clientPorts[i], CONNECTION_TIMEOUT));
ZooKeeper zk = ClientBase.createZKClient("127.0.0.1:" + clientPorts[i]);
// we should see that now all servers have the same config of 5 servers
// including the lag-off server.
String configStr = ReconfigTest.testServerHasConfig(zk, allServers, null);
- Assert.assertEquals("200000000", getVersionFromConfigStr(configStr));
-
+ assertEquals("200000000", getVersionFromConfigStr(configStr));
+
List<String> configLines = Arrays.asList(configStr.split("\n"));
Collections.sort(configLines);
String sortedConfigStr = StringUtils.joinStrings(configLines, "\n");
-
- File dynamicConfigFile = mt[i].getFileByName("zoo.cfg.dynamic.200000000");
- Assert.assertNotNull(dynamicConfigFile);
+
+ File dynamicConfigFile = mt[i].getFileByName("zoo.cfg.dynamic.200000000");
+ assertNotNull(dynamicConfigFile);
// All dynamic files created with the same version should have
// same configs, and they should be equal to the config we get from QuorumPeer.
if (i == 0) {
- dynamicFileContent = getFileContent(dynamicConfigFile);
- Assert.assertEquals(sortedConfigStr, dynamicFileContent +
- "version=200000000");
+ dynamicFileContent = getFileContent(dynamicConfigFile);
+ assertEquals(sortedConfigStr, dynamicFileContent + "version=200000000");
} else {
String otherDynamicFileContent = getFileContent(dynamicConfigFile);
- Assert.assertEquals(dynamicFileContent, otherDynamicFileContent);
+ assertEquals(dynamicFileContent, otherDynamicFileContent);
}
zk.close();
@@ -350,12 +329,11 @@ public class ReconfigBackupTest extends QuorumPeerTestBase {
// finally, we should also check that the lag-off server has updated
// the dynamic file pointer.
- Assert.assertTrue(
- mt[lagOffServerId].getPropFromStaticFile("dynamicConfigFile")
- .endsWith(".200000000"));
+ assertTrue(mt[lagOffServerId].getPropFromStaticFile("dynamicConfigFile").endsWith(".200000000"));
for (int i = 0; i < SERVER_COUNT; i++) {
mt[i].shutdown();
}
}
-} \ No newline at end of file
+
+}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/ReconfigDuringLeaderSyncTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/ReconfigDuringLeaderSyncTest.java
index 4d07ffa71..bff6cbf0e 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/ReconfigDuringLeaderSyncTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/ReconfigDuringLeaderSyncTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -15,17 +15,17 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
package org.apache.zookeeper.server.quorum;
import static org.apache.zookeeper.test.ClientBase.CONNECTION_TIMEOUT;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
-
+import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.Map;
-
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.PortAssignment;
import org.apache.zookeeper.ZooDefs;
@@ -38,21 +38,20 @@ import org.apache.zookeeper.server.quorum.flexible.QuorumMaj;
import org.apache.zookeeper.test.ClientBase;
import org.apache.zookeeper.test.ClientBase.CountdownWatcher;
import org.junit.After;
-import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ReconfigDuringLeaderSyncTest extends QuorumPeerTestBase {
+
protected static final Logger LOG = LoggerFactory.getLogger(ReconfigDuringLeaderSyncTest.class);
private static int SERVER_COUNT = 3;
private MainThread[] mt;
@Before
public void setup() {
- System.setProperty("zookeeper.DigestAuthenticationProvider.superDigest",
- "super:D/InIHSb7yEEbrWz8b9l71RjZJU="/* password is 'test'*/);
+ System.setProperty("zookeeper.DigestAuthenticationProvider.superDigest", "super:D/InIHSb7yEEbrWz8b9l71RjZJU="/* password is 'test'*/);
QuorumPeerConfig.setReconfigEnabled(true);
}
@@ -70,14 +69,14 @@ public class ReconfigDuringLeaderSyncTest extends QuorumPeerTestBase {
@Test
public void testDuringLeaderSync() throws Exception {
- final int clientPorts[] = new int[SERVER_COUNT + 1];
+ final int[] clientPorts = new int[SERVER_COUNT + 1];
StringBuilder sb = new StringBuilder();
String[] serverConfig = new String[SERVER_COUNT + 1];
for (int i = 0; i < SERVER_COUNT; i++) {
clientPorts[i] = PortAssignment.unique();
serverConfig[i] = "server." + i + "=127.0.0.1:" + PortAssignment.unique() + ":" + PortAssignment.unique()
- + ":participant;127.0.0.1:" + clientPorts[i];
+ + ":participant;127.0.0.1:" + clientPorts[i];
sb.append(serverConfig[i] + "\n");
}
String currentQuorumCfgSection = sb.toString();
@@ -91,20 +90,23 @@ public class ReconfigDuringLeaderSyncTest extends QuorumPeerTestBase {
// ensure all servers started
for (int i = 0; i < SERVER_COUNT; i++) {
- Assert.assertTrue("waiting for server " + i + " being up",
- ClientBase.waitForServerUp("127.0.0.1:" + clientPorts[i], CONNECTION_TIMEOUT));
+ assertTrue(
+ "waiting for server " + i + " being up",
+ ClientBase.waitForServerUp("127.0.0.1:" + clientPorts[i], CONNECTION_TIMEOUT));
}
CountdownWatcher watch = new CountdownWatcher();
- ZooKeeperAdmin preReconfigClient = new ZooKeeperAdmin("127.0.0.1:" + clientPorts[0],
- ClientBase.CONNECTION_TIMEOUT, watch);
+ ZooKeeperAdmin preReconfigClient = new ZooKeeperAdmin(
+ "127.0.0.1:" + clientPorts[0],
+ ClientBase.CONNECTION_TIMEOUT,
+ watch);
preReconfigClient.addAuthInfo("digest", "super:test".getBytes());
watch.waitForConnected(ClientBase.CONNECTION_TIMEOUT);
// new server joining
int joinerId = SERVER_COUNT;
clientPorts[joinerId] = PortAssignment.unique();
- serverConfig[joinerId] = "server." + joinerId + "=127.0.0.1:" + PortAssignment.unique() + ":"
- + PortAssignment.unique() + ":participant;127.0.0.1:" + clientPorts[joinerId];
+ serverConfig[joinerId] = "server." + joinerId + "=127.0.0.1:" + PortAssignment.unique() + ":" + PortAssignment.unique()
+ + ":participant;127.0.0.1:" + clientPorts[joinerId];
// Find leader id.
int leaderId = -1;
@@ -157,8 +159,10 @@ public class ReconfigDuringLeaderSyncTest extends QuorumPeerTestBase {
}
}
watch = new CountdownWatcher();
- ZooKeeper postReconfigClient = new ZooKeeper("127.0.0.1:" + clientPorts[joinerId],
- ClientBase.CONNECTION_TIMEOUT, watch);
+ ZooKeeper postReconfigClient = new ZooKeeper(
+ "127.0.0.1:" + clientPorts[joinerId],
+ ClientBase.CONNECTION_TIMEOUT,
+ watch);
watch.waitForConnected(ClientBase.CONNECTION_TIMEOUT);
// do one successful operation on the newly added node
postReconfigClient.create("/reconfigIssue", "".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
@@ -166,8 +170,9 @@ public class ReconfigDuringLeaderSyncTest extends QuorumPeerTestBase {
// verify that joiner has up-to-date config, including all four servers.
for (long j = 0; j <= SERVER_COUNT; j++) {
- assertNotNull("server " + j + " is not present in the new quorum",
- qp.getQuorumVerifier().getVotingMembers().get(j));
+ assertNotNull(
+ "server " + j + " is not present in the new quorum",
+ qp.getQuorumVerifier().getVotingMembers().get(j));
}
// close clients
@@ -205,13 +210,11 @@ public class ReconfigDuringLeaderSyncTest extends QuorumPeerTestBase {
}
private static class CustomQuorumPeer extends QuorumPeer {
+
private boolean newLeaderMessage = false;
- public CustomQuorumPeer(Map<Long, QuorumServer> quorumPeers, File snapDir, File logDir, int clientPort,
- int electionAlg, long myid, int tickTime, int initLimit, int syncLimit, int connectToLearnerMasterLimit)
- throws IOException {
- super(quorumPeers, snapDir, logDir, electionAlg, myid, tickTime, initLimit, syncLimit, connectToLearnerMasterLimit, false,
- ServerCnxnFactory.createFactory(new InetSocketAddress(clientPort), -1), new QuorumMaj(quorumPeers));
+ public CustomQuorumPeer(Map<Long, QuorumServer> quorumPeers, File snapDir, File logDir, int clientPort, int electionAlg, long myid, int tickTime, int initLimit, int syncLimit, int connectToLearnerMasterLimit) throws IOException {
+ super(quorumPeers, snapDir, logDir, electionAlg, myid, tickTime, initLimit, syncLimit, connectToLearnerMasterLimit, false, ServerCnxnFactory.createFactory(new InetSocketAddress(clientPort), -1), new QuorumMaj(quorumPeers));
}
/**
@@ -248,16 +251,14 @@ public class ReconfigDuringLeaderSyncTest extends QuorumPeerTestBase {
}
};
}
+
}
private static class MockTestQPMain extends TestQPMain {
+
@Override
- public void runFromConfig(QuorumPeerConfig config)
- throws IOException, AdminServerException {
- quorumPeer = new CustomQuorumPeer(config.getQuorumVerifier().getAllMembers(), config.getDataDir(),
- config.getDataLogDir(), config.getClientPortAddress().getPort(), config.getElectionAlg(),
- config.getServerId(), config.getTickTime(), config.getInitLimit(), config.getSyncLimit(),
- config.getConnectToLearnerMasterLimit());
+ public void runFromConfig(QuorumPeerConfig config) throws IOException, AdminServerException {
+ quorumPeer = new CustomQuorumPeer(config.getQuorumVerifier().getAllMembers(), config.getDataDir(), config.getDataLogDir(), config.getClientPortAddress().getPort(), config.getElectionAlg(), config.getServerId(), config.getTickTime(), config.getInitLimit(), config.getSyncLimit(), config.getConnectToLearnerMasterLimit());
quorumPeer.setConfigFileName(config.getConfigFilename());
quorumPeer.start();
try {
@@ -266,5 +267,7 @@ public class ReconfigDuringLeaderSyncTest extends QuorumPeerTestBase {
LOG.warn("Quorum Peer interrupted", e);
}
}
+
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/ReconfigFailureCasesTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/ReconfigFailureCasesTest.java
index bd9e5881c..f28979bf7 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/ReconfigFailureCasesTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/ReconfigFailureCasesTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -19,13 +19,13 @@
package org.apache.zookeeper.server.quorum;
import static org.apache.zookeeper.test.ClientBase.CONNECTION_TIMEOUT;
-
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
-
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.KeeperException.NewConfigNoQuorum;
import org.apache.zookeeper.ZooKeeper;
@@ -35,7 +35,6 @@ import org.apache.zookeeper.test.ClientBase;
import org.apache.zookeeper.test.QuorumUtil;
import org.apache.zookeeper.test.ReconfigTest;
import org.junit.After;
-import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
@@ -46,8 +45,7 @@ public class ReconfigFailureCasesTest extends QuorumPeerTestBase {
@Before
public void setup() {
QuorumPeerConfig.setReconfigEnabled(true);
- System.setProperty("zookeeper.DigestAuthenticationProvider.superDigest",
- "super:D/InIHSb7yEEbrWz8b9l71RjZJU="/* password is 'test'*/);
+ System.setProperty("zookeeper.DigestAuthenticationProvider.superDigest", "super:D/InIHSb7yEEbrWz8b9l71RjZJU="/* password is 'test'*/);
}
@After
@@ -79,9 +77,10 @@ public class ReconfigFailureCasesTest extends QuorumPeerTestBase {
for (int i = 1; i <= 5; i++) {
members.add("server." + i + "=127.0.0.1:"
- + qu.getPeer(i).peer.getQuorumAddress().getPort() + ":"
- + qu.getPeer(i).peer.getElectionAddress().getPort() + ";"
- + "127.0.0.1:" + qu.getPeer(i).peer.getClientPort());
+ + qu.getPeer(i).peer.getQuorumAddress().getPort()
+ + ":" + qu.getPeer(i).peer.getElectionAddress().getPort()
+ + ";" + "127.0.0.1:"
+ + qu.getPeer(i).peer.getClientPort());
}
// Change the quorum system from majority to hierarchical.
@@ -92,12 +91,12 @@ public class ReconfigFailureCasesTest extends QuorumPeerTestBase {
List<String> leavingServers = new ArrayList<String>();
leavingServers.add("3");
try {
- zkAdminArr[1].reconfigure(null, leavingServers, null, -1, null);
- Assert.fail("Reconfig should have failed since the current config isn't Majority QS");
+ zkAdminArr[1].reconfigure(null, leavingServers, null, -1, null);
+ fail("Reconfig should have failed since the current config isn't Majority QS");
} catch (KeeperException.BadArgumentsException e) {
// We expect this to happen.
} catch (Exception e) {
- Assert.fail("Should have been BadArgumentsException!");
+ fail("Should have been BadArgumentsException!");
}
ReconfigTest.closeAllHandles(zkArr, zkAdminArr);
@@ -122,12 +121,12 @@ public class ReconfigFailureCasesTest extends QuorumPeerTestBase {
leavingServers.add("2");
leavingServers.add("3");
try {
- zkAdminArr[1].reconfigure(null, leavingServers, null, -1, null);
- Assert.fail("Reconfig should have failed since the current config version is not 8");
+ zkAdminArr[1].reconfigure(null, leavingServers, null, -1, null);
+ fail("Reconfig should have failed since the current config version is not 8");
} catch (KeeperException.BadArgumentsException e) {
// We expect this to happen.
} catch (Exception e) {
- Assert.fail("Should have been BadArgumentsException!");
+ fail("Should have been BadArgumentsException!");
}
ReconfigTest.closeAllHandles(zkArr, zkAdminArr);
@@ -148,12 +147,12 @@ public class ReconfigFailureCasesTest extends QuorumPeerTestBase {
List<String> leavingServers = new ArrayList<String>();
leavingServers.add("3");
try {
- zkAdminArr[1].reconfigure(null, leavingServers, null, 8, null);
- Assert.fail("Reconfig should have failed since the current config version is not 8");
+ zkAdminArr[1].reconfigure(null, leavingServers, null, 8, null);
+ fail("Reconfig should have failed since the current config version is not 8");
} catch (KeeperException.BadVersionException e) {
// We expect this to happen.
} catch (Exception e) {
- Assert.fail("Should have been BadVersionException!");
+ fail("Should have been BadVersionException!");
}
ReconfigTest.closeAllHandles(zkArr, zkAdminArr);
@@ -190,36 +189,33 @@ public class ReconfigFailureCasesTest extends QuorumPeerTestBase {
String currentQuorumCfgSection = sb.toString();
String nextQuorumCfgSection = currentQuorumCfgSection.replace("observer", "participant");
- MainThread mt[] = new MainThread[SERVER_COUNT];
- ZooKeeper zk[] = new ZooKeeper[SERVER_COUNT];
- ZooKeeperAdmin zkAdmin[] = new ZooKeeperAdmin[SERVER_COUNT];
+ MainThread[] mt = new MainThread[SERVER_COUNT];
+ ZooKeeper[] zk = new ZooKeeper[SERVER_COUNT];
+ ZooKeeperAdmin[] zkAdmin = new ZooKeeperAdmin[SERVER_COUNT];
// Server 0 stays down
for (int i = 1; i < SERVER_COUNT; i++) {
- mt[i] = new MainThread(i, ports[i][2], currentQuorumCfgSection,
- true, "100000000");
+ mt[i] = new MainThread(i, ports[i][2], currentQuorumCfgSection, true, "100000000");
mt[i].start();
- zk[i] = new ZooKeeper("127.0.0.1:" + ports[i][2],
- ClientBase.CONNECTION_TIMEOUT, this);
- zkAdmin[i] = new ZooKeeperAdmin("127.0.0.1:" + ports[i][2],
- ClientBase.CONNECTION_TIMEOUT, this);
+ zk[i] = new ZooKeeper("127.0.0.1:" + ports[i][2], ClientBase.CONNECTION_TIMEOUT, this);
+ zkAdmin[i] = new ZooKeeperAdmin("127.0.0.1:" + ports[i][2], ClientBase.CONNECTION_TIMEOUT, this);
zkAdmin[i].addAuthInfo("digest", "super:test".getBytes());
}
for (int i = 1; i < SERVER_COUNT; i++) {
- Assert.assertTrue("waiting for server " + i + " being up",
- ClientBase.waitForServerUp("127.0.0.1:" + ports[i][2],
- CONNECTION_TIMEOUT * 2));
+ assertTrue(
+ "waiting for server " + i + " being up",
+ ClientBase.waitForServerUp("127.0.0.1:" + ports[i][2], CONNECTION_TIMEOUT * 2));
}
try {
zkAdmin[1].reconfigure("", "", nextQuorumCfgSection, -1, new Stat());
- Assert.fail("Reconfig should have failed with NewConfigNoQuorum");
+ fail("Reconfig should have failed with NewConfigNoQuorum");
} catch (NewConfigNoQuorum e) {
// This is expected case since server 0 is down and 3 can't vote
// (observer in current role) and we need 3 votes from 0, 1, 2, 3,
} catch (Exception e) {
- Assert.fail("Reconfig should have failed with NewConfigNoQuorum");
+ fail("Reconfig should have failed with NewConfigNoQuorum");
}
// In this scenario to change 3's role to participant we need to remove it first
ArrayList<String> leavingServers = new ArrayList<String>();
@@ -241,4 +237,5 @@ public class ReconfigFailureCasesTest extends QuorumPeerTestBase {
mt[i].shutdown();
}
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/ReconfigLegacyTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/ReconfigLegacyTest.java
index db399b71b..d6eba89a3 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/ReconfigLegacyTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/ReconfigLegacyTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -20,13 +20,13 @@ package org.apache.zookeeper.server.quorum;
import static org.apache.zookeeper.test.ClientBase.CONNECTION_TIMEOUT;
import static org.junit.Assert.assertEquals;
-
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Properties;
-
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.PortAssignment;
import org.apache.zookeeper.ZooDefs.Ids;
@@ -34,7 +34,6 @@ import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.admin.ZooKeeperAdmin;
import org.apache.zookeeper.test.ClientBase;
import org.apache.zookeeper.test.ReconfigTest;
-import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
@@ -46,8 +45,7 @@ public class ReconfigLegacyTest extends QuorumPeerTestBase {
public void setup() {
ClientBase.setupTestEnv();
QuorumPeerConfig.setReconfigEnabled(true);
- System.setProperty("zookeeper.DigestAuthenticationProvider.superDigest",
- "super:D/InIHSb7yEEbrWz8b9l71RjZJU="/* password is 'test'*/);
+ System.setProperty("zookeeper.DigestAuthenticationProvider.superDigest", "super:D/InIHSb7yEEbrWz8b9l71RjZJU="/* password is 'test'*/);
}
/**
@@ -58,62 +56,60 @@ public class ReconfigLegacyTest extends QuorumPeerTestBase {
*/
@Test
public void testConfigFileBackwardCompatibility() throws Exception {
- final int clientPorts[] = new int[SERVER_COUNT];
+ final int[] clientPorts = new int[SERVER_COUNT];
StringBuilder sb = new StringBuilder();
String server;
ArrayList<String> allServers = new ArrayList<String>();
for (int i = 0; i < SERVER_COUNT; i++) {
clientPorts[i] = PortAssignment.unique();
- server = "server." + i + "=localhost:" + PortAssignment.unique()
- + ":" + PortAssignment.unique() + ":participant;localhost:"
- + clientPorts[i];
+ server = "server." + i + "=localhost:" + PortAssignment.unique() + ":" + PortAssignment.unique()
+ + ":participant;localhost:" + clientPorts[i];
allServers.add(server);
sb.append(server + "\n");
}
String currentQuorumCfgSection = sb.toString();
- MainThread mt[] = new MainThread[SERVER_COUNT];
- ZooKeeper zk[] = new ZooKeeper[SERVER_COUNT];
+ MainThread[] mt = new MainThread[SERVER_COUNT];
+ ZooKeeper[] zk = new ZooKeeper[SERVER_COUNT];
// Start the servers with a static config file, without a dynamic
// config file.
for (int i = 0; i < SERVER_COUNT; i++) {
mt[i] = new MainThread(i, clientPorts[i], currentQuorumCfgSection, "participant", false);
// check that a dynamic configuration file doesn't exist
- Assert.assertEquals( mt[i].getDynamicFiles().length, 0 );
+ assertEquals(mt[i].getDynamicFiles().length, 0);
mt[i].start();
}
// Check that the servers are up, have the right config and can process operations.
// Check that the static config was split into static and dynamic files correctly.
for (int i = 0; i < SERVER_COUNT; i++) {
- Assert.assertTrue("waiting for server " + i + " being up",
- ClientBase.waitForServerUp("127.0.0.1:" + clientPorts[i],
- CONNECTION_TIMEOUT));
+ assertTrue(
+ "waiting for server " + i + " being up",
+ ClientBase.waitForServerUp("127.0.0.1:" + clientPorts[i], CONNECTION_TIMEOUT));
zk[i] = ClientBase.createZKClient("127.0.0.1:" + clientPorts[i]);
File[] dynamicFiles = mt[i].getDynamicFiles();
- Assert.assertTrue( dynamicFiles.length== 1 );
+ assertTrue(dynamicFiles.length == 1);
ReconfigTest.testServerHasConfig(zk[i], allServers, null);
// check that static config file doesn't include membership info
// and has a pointer to the dynamic configuration file
// check that static config file doesn't include peerType info
Properties cfg = readPropertiesFromFile(mt[i].confFile);
for (int j = 0; j < SERVER_COUNT; j++) {
- Assert.assertFalse(cfg.containsKey("server." + j));
+ assertFalse(cfg.containsKey("server." + j));
}
- Assert.assertFalse(cfg.containsKey("peerType"));
- Assert.assertTrue(cfg.containsKey("dynamicConfigFile"));
- Assert.assertFalse(cfg.containsKey("clientPort"));
+ assertFalse(cfg.containsKey("peerType"));
+ assertTrue(cfg.containsKey("dynamicConfigFile"));
+ assertFalse(cfg.containsKey("clientPort"));
// check that the dynamic configuration file contains the membership info
cfg = readPropertiesFromFile(dynamicFiles[0]);
for (int j = 0; j < SERVER_COUNT; j++) {
String serverLine = cfg.getProperty("server." + j, "");
- Assert.assertEquals(allServers.get(j), "server." + j + "="
- + serverLine);
+ assertEquals(allServers.get(j), "server." + j + "=" + serverLine);
}
- Assert.assertFalse(cfg.containsKey("dynamicConfigFile"));
+ assertFalse(cfg.containsKey("dynamicConfigFile"));
}
ReconfigTest.testNormalOperation(zk[0], zk[1]);
@@ -126,9 +122,9 @@ public class ReconfigLegacyTest extends QuorumPeerTestBase {
mt[i].start();
}
for (int i = 0; i < SERVER_COUNT; i++) {
- Assert.assertTrue("waiting for server " + i + " being up",
- ClientBase.waitForServerUp("127.0.0.1:" + clientPorts[i],
- CONNECTION_TIMEOUT));
+ assertTrue(
+ "waiting for server " + i + " being up",
+ ClientBase.waitForServerUp("127.0.0.1:" + clientPorts[i], CONNECTION_TIMEOUT));
zk[i] = ClientBase.createZKClient("127.0.0.1:" + clientPorts[i]);
ReconfigTest.testServerHasConfig(zk[i], allServers, null);
}
@@ -149,9 +145,9 @@ public class ReconfigLegacyTest extends QuorumPeerTestBase {
*/
@Test
public void testReconfigRemoveClientFromStatic() throws Exception {
- final int clientPorts[] = new int[SERVER_COUNT];
- final int quorumPorts[] = new int[SERVER_COUNT];
- final int electionPorts[] = new int[SERVER_COUNT];
+ final int[] clientPorts = new int[SERVER_COUNT];
+ final int[] quorumPorts = new int[SERVER_COUNT];
+ final int[] electionPorts = new int[SERVER_COUNT];
final int changedServerId = 0;
final int newClientPort = PortAssignment.unique();
@@ -165,12 +161,11 @@ public class ReconfigLegacyTest extends QuorumPeerTestBase {
quorumPorts[i] = PortAssignment.unique();
electionPorts[i] = PortAssignment.unique();
- String server = "server." + i + "=localhost:" + quorumPorts[i]
- +":" + electionPorts[i] + ":participant";
+ String server = "server." + i + "=localhost:" + quorumPorts[i] + ":" + electionPorts[i] + ":participant";
allServers.add(server);
sb.append(server + "\n");
- if(i == changedServerId) {
+ if (i == changedServerId) {
newServers.add(server + ";0.0.0.0:" + newClientPort);
} else {
newServers.add(server);
@@ -178,9 +173,9 @@ public class ReconfigLegacyTest extends QuorumPeerTestBase {
}
String quorumCfgSection = sb.toString();
- MainThread mt[] = new MainThread[SERVER_COUNT];
- ZooKeeper zk[] = new ZooKeeper[SERVER_COUNT];
- ZooKeeperAdmin zkAdmin[] = new ZooKeeperAdmin[SERVER_COUNT];
+ MainThread[] mt = new MainThread[SERVER_COUNT];
+ ZooKeeper[] zk = new ZooKeeper[SERVER_COUNT];
+ ZooKeeperAdmin[] zkAdmin = new ZooKeeperAdmin[SERVER_COUNT];
// Start the servers with a static config file, without a dynamic config file.
for (int i = 0; i < SERVER_COUNT; i++) {
@@ -191,19 +186,18 @@ public class ReconfigLegacyTest extends QuorumPeerTestBase {
// Check that when a server starts from old style config, it should keep the client
// port in static config file.
for (int i = 0; i < SERVER_COUNT; i++) {
- Assert.assertTrue("waiting for server " + i + " being up",
- ClientBase.waitForServerUp("127.0.0.1:" + clientPorts[i],
- CONNECTION_TIMEOUT));
+ assertTrue(
+ "waiting for server " + i + " being up",
+ ClientBase.waitForServerUp("127.0.0.1:" + clientPorts[i], CONNECTION_TIMEOUT));
zk[i] = ClientBase.createZKClient("127.0.0.1:" + clientPorts[i]);
- zkAdmin[i] = new ZooKeeperAdmin("127.0.0.1:" + clientPorts[i],
- ClientBase.CONNECTION_TIMEOUT, this);
+ zkAdmin[i] = new ZooKeeperAdmin("127.0.0.1:" + clientPorts[i], ClientBase.CONNECTION_TIMEOUT, this);
zkAdmin[i].addAuthInfo("digest", "super:test".getBytes());
ReconfigTest.testServerHasConfig(zk[i], allServers, null);
Properties cfg = readPropertiesFromFile(mt[i].confFile);
- Assert.assertTrue(cfg.containsKey("dynamicConfigFile"));
- Assert.assertTrue(cfg.containsKey("clientPort"));
+ assertTrue(cfg.containsKey("dynamicConfigFile"));
+ assertTrue(cfg.containsKey("clientPort"));
}
ReconfigTest.testNormalOperation(zk[0], zk[1]);
@@ -221,9 +215,9 @@ public class ReconfigLegacyTest extends QuorumPeerTestBase {
ReconfigTest.testServerHasConfig(zk[i], newServers, null);
Properties staticCfg = readPropertiesFromFile(mt[i].confFile);
if (i == changedServerId) {
- Assert.assertFalse(staticCfg.containsKey("clientPort"));
+ assertFalse(staticCfg.containsKey("clientPort"));
} else {
- Assert.assertTrue(staticCfg.containsKey("clientPort"));
+ assertTrue(staticCfg.containsKey("clientPort"));
}
}
@@ -252,39 +246,36 @@ public class ReconfigLegacyTest extends QuorumPeerTestBase {
*/
@Test(timeout = 120000)
public void testRestartZooKeeperServer() throws Exception {
- final int clientPorts[] = new int[SERVER_COUNT];
+ final int[] clientPorts = new int[SERVER_COUNT];
StringBuilder sb = new StringBuilder();
String server;
for (int i = 0; i < SERVER_COUNT; i++) {
clientPorts[i] = PortAssignment.unique();
- server = "server." + i + "=127.0.0.1:" + PortAssignment.unique()
- + ":" + PortAssignment.unique() + ":participant;127.0.0.1:"
- + clientPorts[i];
+ server = "server." + i + "=127.0.0.1:" + PortAssignment.unique() + ":" + PortAssignment.unique()
+ + ":participant;127.0.0.1:" + clientPorts[i];
sb.append(server + "\n");
}
String currentQuorumCfgSection = sb.toString();
- MainThread mt[] = new MainThread[SERVER_COUNT];
+ MainThread[] mt = new MainThread[SERVER_COUNT];
for (int i = 0; i < SERVER_COUNT; i++) {
- mt[i] = new MainThread(i, clientPorts[i], currentQuorumCfgSection,
- false);
+ mt[i] = new MainThread(i, clientPorts[i], currentQuorumCfgSection, false);
mt[i].start();
}
// ensure server started
for (int i = 0; i < SERVER_COUNT; i++) {
- Assert.assertTrue("waiting for server " + i + " being up",
- ClientBase.waitForServerUp("127.0.0.1:" + clientPorts[i],
- CONNECTION_TIMEOUT));
+ assertTrue(
+ "waiting for server " + i + " being up",
+ ClientBase.waitForServerUp("127.0.0.1:" + clientPorts[i], CONNECTION_TIMEOUT));
}
ZooKeeper zk = ClientBase.createZKClient("127.0.0.1:" + clientPorts[0]);
- String zNodePath="/serverRestartTest";
+ String zNodePath = "/serverRestartTest";
String data = "originalData";
- zk.create(zNodePath, data.getBytes(), Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk.create(zNodePath, data.getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
zk.close();
/**
@@ -296,9 +287,9 @@ public class ReconfigLegacyTest extends QuorumPeerTestBase {
mt[1].start();
// ensure server started
for (int i = 0; i < SERVER_COUNT; i++) {
- Assert.assertTrue("waiting for server " + i + " being up",
- ClientBase.waitForServerUp("127.0.0.1:" + clientPorts[i],
- CONNECTION_TIMEOUT));
+ assertTrue(
+ "waiting for server " + i + " being up",
+ ClientBase.waitForServerUp("127.0.0.1:" + clientPorts[i], CONNECTION_TIMEOUT));
}
zk = ClientBase.createZKClient("127.0.0.1:" + clientPorts[0]);
@@ -310,4 +301,5 @@ public class ReconfigLegacyTest extends QuorumPeerTestBase {
mt[i].shutdown();
}
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/ReconfigRecoveryTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/ReconfigRecoveryTest.java
index 261ff6c82..ee0fb4a03 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/ReconfigRecoveryTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/ReconfigRecoveryTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -19,20 +19,21 @@
package org.apache.zookeeper.server.quorum;
import static org.apache.zookeeper.test.ClientBase.CONNECTION_TIMEOUT;
-
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
-
import org.apache.zookeeper.PortAssignment;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.test.ClientBase;
import org.apache.zookeeper.test.ReconfigTest;
-import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
public class ReconfigRecoveryTest extends QuorumPeerTestBase {
+
@Before
public void setup() {
QuorumPeerConfig.setReconfigEnabled(true);
@@ -48,7 +49,7 @@ public class ReconfigRecoveryTest extends QuorumPeerTestBase {
// 2 servers in current config, 3 in next config
final int SERVER_COUNT = 3;
- final int clientPorts[] = new int[SERVER_COUNT];
+ final int[] clientPorts = new int[SERVER_COUNT];
StringBuilder sb = new StringBuilder();
String server;
ArrayList<String> allServers = new ArrayList<String>();
@@ -57,40 +58,37 @@ public class ReconfigRecoveryTest extends QuorumPeerTestBase {
for (int i = 0; i < SERVER_COUNT; i++) {
clientPorts[i] = PortAssignment.unique();
- server = "server." + i + "=localhost:" + PortAssignment.unique()
- + ":" + PortAssignment.unique() + ":participant;localhost:"
- + clientPorts[i];
+ server = "server." + i + "=localhost:" + PortAssignment.unique() + ":" + PortAssignment.unique()
+ + ":participant;localhost:" + clientPorts[i];
allServers.add(server);
sb.append(server + "\n");
- if (i == 1)
+ if (i == 1) {
currentQuorumCfgSection = sb.toString();
+ }
}
nextQuorumCfgSection = sb.toString();
// Both servers 0 and 1 will have the .next config file, which means
// for them that a reconfiguration was in progress when they failed
// and the leader will complete it
- MainThread mt[] = new MainThread[SERVER_COUNT];
- ZooKeeper zk[] = new ZooKeeper[SERVER_COUNT];
+ MainThread[] mt = new MainThread[SERVER_COUNT];
+ ZooKeeper[] zk = new ZooKeeper[SERVER_COUNT];
for (int i = 0; i < SERVER_COUNT - 1; i++) {
- mt[i] = new MainThread(i, clientPorts[i], currentQuorumCfgSection,
- true, "100000000");
+ mt[i] = new MainThread(i, clientPorts[i], currentQuorumCfgSection, true, "100000000");
// note that we should run the server, shut it down and only then
// simulate a reconfig in progress by writing the temp file, but here no
// other server is competing with them in FLE, so we can skip this step
// (server 2 is booted after FLE ends)
mt[i].writeTempDynamicConfigFile(nextQuorumCfgSection, "200000000");
mt[i].start();
- zk[i] = new ZooKeeper("127.0.0.1:" + clientPorts[i],
- ClientBase.CONNECTION_TIMEOUT, this);
+ zk[i] = new ZooKeeper("127.0.0.1:" + clientPorts[i], ClientBase.CONNECTION_TIMEOUT, this);
}
- Assert.assertTrue("waiting for server 0 being up", ClientBase
- .waitForServerUp("127.0.0.1:" + clientPorts[0],
- CONNECTION_TIMEOUT));
- Assert.assertTrue("waiting for server 1 being up", ClientBase
- .waitForServerUp("127.0.0.1:" + clientPorts[1],
- CONNECTION_TIMEOUT));
+ assertTrue(
+ "waiting for server 0 being up",
+ ClientBase.waitForServerUp("127.0.0.1:" + clientPorts[0], CONNECTION_TIMEOUT));
+ assertTrue(
+ "waiting for server 1 being up", ClientBase.waitForServerUp("127.0.0.1:" + clientPorts[1], CONNECTION_TIMEOUT));
int leader = mt[0].main.quorumPeer.leader == null ? 1 : 0;
@@ -103,12 +101,11 @@ public class ReconfigRecoveryTest extends QuorumPeerTestBase {
String newServerInitialConfig = sb.toString();
mt[2] = new MainThread(2, clientPorts[2], newServerInitialConfig);
mt[2].start();
- zk[2] = new ZooKeeper("127.0.0.1:" + clientPorts[2],
- ClientBase.CONNECTION_TIMEOUT, this);
+ zk[2] = new ZooKeeper("127.0.0.1:" + clientPorts[2], ClientBase.CONNECTION_TIMEOUT, this);
- Assert.assertTrue("waiting for server 2 being up", ClientBase
- .waitForServerUp("127.0.0.1:" + clientPorts[2],
- CONNECTION_TIMEOUT));
+ assertTrue(
+ "waiting for server 2 being up",
+ ClientBase.waitForServerUp("127.0.0.1:" + clientPorts[2], CONNECTION_TIMEOUT));
ReconfigTest.testServerHasConfig(zk[0], allServers, null);
ReconfigTest.testServerHasConfig(zk[1], allServers, null);
@@ -134,8 +131,8 @@ public class ReconfigRecoveryTest extends QuorumPeerTestBase {
// 2 servers in current config, 5 in next config
final int SERVER_COUNT = 5;
- final int clientPorts[] = new int[SERVER_COUNT];
- final int oldClientPorts[] = new int[2];
+ final int[] clientPorts = new int[SERVER_COUNT];
+ final int[] oldClientPorts = new int[2];
StringBuilder sb = new StringBuilder();
String server;
@@ -145,9 +142,8 @@ public class ReconfigRecoveryTest extends QuorumPeerTestBase {
for (int i = 0; i < 2; i++) {
oldClientPorts[i] = PortAssignment.unique();
- server = "server." + i + "=localhost:" + PortAssignment.unique()
- + ":" + PortAssignment.unique() + ":participant;localhost:"
- + oldClientPorts[i];
+ server = "server." + i + "=localhost:" + PortAssignment.unique() + ":" + PortAssignment.unique()
+ + ":participant;localhost:" + oldClientPorts[i];
sb.append(server + "\n");
}
@@ -162,31 +158,28 @@ public class ReconfigRecoveryTest extends QuorumPeerTestBase {
} else {
role = "participant";
}
- server = "server." + i + "=localhost:" + PortAssignment.unique()
- + ":" + PortAssignment.unique() + ":" + role
- + ";localhost:" + clientPorts[i];
+ server = "server." + i + "=localhost:" + PortAssignment.unique() + ":" + PortAssignment.unique() + ":"
+ + role + ";localhost:" + clientPorts[i];
allServersNext.add(server);
sb.append(server + "\n");
}
nextQuorumCfgSection = sb.toString();
- MainThread mt[] = new MainThread[SERVER_COUNT];
- ZooKeeper zk[] = new ZooKeeper[SERVER_COUNT];
+ MainThread[] mt = new MainThread[SERVER_COUNT];
+ ZooKeeper[] zk = new ZooKeeper[SERVER_COUNT];
// run servers 0 and 1 normally
for (int i = 0; i < 2; i++) {
- mt[i] = new MainThread(i, oldClientPorts[i], currentQuorumCfg,
- true, "100000000");
+ mt[i] = new MainThread(i, oldClientPorts[i], currentQuorumCfg, true, "100000000");
mt[i].start();
- zk[i] = new ZooKeeper("127.0.0.1:" + oldClientPorts[i],
- ClientBase.CONNECTION_TIMEOUT, this);
+ zk[i] = new ZooKeeper("127.0.0.1:" + oldClientPorts[i], ClientBase.CONNECTION_TIMEOUT, this);
}
for (int i = 0; i < 2; i++) {
- Assert.assertTrue("waiting for server " + i + " being up",
- ClientBase.waitForServerUp(
- "127.0.0.1:" + oldClientPorts[i],
- CONNECTION_TIMEOUT * 2));
+ assertTrue(
+ "waiting for server " + i + " being up",
+ ClientBase.waitForServerUp("127.0.0.1:" + oldClientPorts[i], CONNECTION_TIMEOUT
+ * 2));
}
ReconfigTest.testNormalOperation(zk[0], zk[1]);
@@ -198,32 +191,29 @@ public class ReconfigRecoveryTest extends QuorumPeerTestBase {
}
for (int i = 0; i < 2; i++) {
- Assert.assertTrue(
- "waiting for server " + i + " being up",
- ClientBase.waitForServerDown("127.0.0.1:"
- + oldClientPorts[i], CONNECTION_TIMEOUT * 2));
+ assertTrue("waiting for server " + i + " being up", ClientBase.waitForServerDown(
+ "127.0.0.1:"
+ + oldClientPorts[i], CONNECTION_TIMEOUT
+ * 2));
}
for (int i = 0; i < 2; i++) {
mt[i].writeTempDynamicConfigFile(nextQuorumCfgSection, "200000000");
mt[i].start();
- zk[i] = new ZooKeeper("127.0.0.1:" + clientPorts[i],
- ClientBase.CONNECTION_TIMEOUT, this);
+ zk[i] = new ZooKeeper("127.0.0.1:" + clientPorts[i], ClientBase.CONNECTION_TIMEOUT, this);
}
// new members are initialized with current config + the new server
for (int i = 2; i < SERVER_COUNT; i++) {
- mt[i] = new MainThread(i, clientPorts[i], currentQuorumCfg
- + allServersNext.get(i));
+ mt[i] = new MainThread(i, clientPorts[i], currentQuorumCfg + allServersNext.get(i));
mt[i].start();
- zk[i] = new ZooKeeper("127.0.0.1:" + clientPorts[i],
- ClientBase.CONNECTION_TIMEOUT, this);
+ zk[i] = new ZooKeeper("127.0.0.1:" + clientPorts[i], ClientBase.CONNECTION_TIMEOUT, this);
}
for (int i = 0; i < SERVER_COUNT; i++) {
- Assert.assertTrue("waiting for server " + i + " being up",
- ClientBase.waitForServerUp("127.0.0.1:" + clientPorts[i],
- CONNECTION_TIMEOUT * 2));
+ assertTrue(
+ "waiting for server " + i + " being up",
+ ClientBase.waitForServerUp("127.0.0.1:" + clientPorts[i], CONNECTION_TIMEOUT * 2));
ReconfigTest.testServerHasConfig(zk[i], allServersNext, null);
}
@@ -248,7 +238,7 @@ public class ReconfigRecoveryTest extends QuorumPeerTestBase {
// 2 servers in current config, 5 in next config
final int SERVER_COUNT = 5;
- final int clientPorts[] = new int[SERVER_COUNT];
+ final int[] clientPorts = new int[SERVER_COUNT];
StringBuilder sb = new StringBuilder();
String server;
@@ -256,30 +246,28 @@ public class ReconfigRecoveryTest extends QuorumPeerTestBase {
for (int i = 0; i < SERVER_COUNT; i++) {
clientPorts[i] = PortAssignment.unique();
- server = "server." + i + "=localhost:" + PortAssignment.unique()
- + ":" + PortAssignment.unique() + ":participant;localhost:"
- + clientPorts[i];
+ server = "server." + i + "=localhost:" + PortAssignment.unique() + ":" + PortAssignment.unique()
+ + ":participant;localhost:" + clientPorts[i];
sb.append(server + "\n");
- if (i == 1)
+ if (i == 1) {
currentQuorumCfgSection = sb.toString();
+ }
}
nextQuorumCfgSection = sb.toString();
- MainThread mt[] = new MainThread[SERVER_COUNT];
- ZooKeeper zk[] = new ZooKeeper[SERVER_COUNT];
+ MainThread[] mt = new MainThread[SERVER_COUNT];
+ ZooKeeper[] zk = new ZooKeeper[SERVER_COUNT];
// Both servers 0 and 1 will have the .next config file, which means
// for them that a reconfiguration was in progress when they failed
for (int i = 0; i < 2; i++) {
- mt[i] = new MainThread(i, clientPorts[i], currentQuorumCfgSection,
- true, "100000000");
+ mt[i] = new MainThread(i, clientPorts[i], currentQuorumCfgSection, true, "100000000");
// note that we should run the server, shut it down and only then
// simulate a reconfig in progress by writing the temp file, but here no
// other server is competing with them in FLE, so we can skip this step
mt[i].writeTempDynamicConfigFile(nextQuorumCfgSection, "200000000");
mt[i].start();
- zk[i] = new ZooKeeper("127.0.0.1:" + clientPorts[i],
- ClientBase.CONNECTION_TIMEOUT, this);
+ zk[i] = new ZooKeeper("127.0.0.1:" + clientPorts[i], ClientBase.CONNECTION_TIMEOUT, this);
}
Thread.sleep(CONNECTION_TIMEOUT * 2);
@@ -287,9 +275,9 @@ public class ReconfigRecoveryTest extends QuorumPeerTestBase {
// make sure servers 0, 1 don't come online - this should be the case
// since they can't complete the reconfig
for (int i = 0; i < 2; i++) {
- Assert.assertFalse("server " + i + " is up but shouldn't be",
- ClientBase.waitForServerUp("127.0.0.1:" + clientPorts[i],
- CONNECTION_TIMEOUT / 10));
+ assertFalse(
+ "server " + i + " is up but shouldn't be",
+ ClientBase.waitForServerUp("127.0.0.1:" + clientPorts[i], CONNECTION_TIMEOUT / 10));
}
for (int i = 0; i < 2; i++) {
@@ -308,7 +296,7 @@ public class ReconfigRecoveryTest extends QuorumPeerTestBase {
// 2 servers in current config, 5 in next config
final int SERVER_COUNT = 5;
- final int clientPorts[] = new int[SERVER_COUNT];
+ final int[] clientPorts = new int[SERVER_COUNT];
StringBuilder sb = new StringBuilder();
String server;
@@ -317,29 +305,28 @@ public class ReconfigRecoveryTest extends QuorumPeerTestBase {
ArrayList<String> allServers = new ArrayList<String>();
for (int i = 0; i < SERVER_COUNT; i++) {
clientPorts[i] = PortAssignment.unique();
- server = "server." + i + "=localhost:" + PortAssignment.unique()
- + ":" + PortAssignment.unique() + ":participant;localhost:"
- + clientPorts[i];
+ server = "server." + i + "=localhost:" + PortAssignment.unique() + ":" + PortAssignment.unique()
+ + ":participant;localhost:" + clientPorts[i];
allServers.add(server);
sb.append(server + "\n");
- if (i == 1) currentQuorumCfgSection = sb.toString();
+ if (i == 1) {
+ currentQuorumCfgSection = sb.toString();
+ }
}
nextQuorumCfgSection = sb.toString();
// lets start servers 2, 3, 4 with the new config
- MainThread mt[] = new MainThread[SERVER_COUNT];
- ZooKeeper zk[] = new ZooKeeper[SERVER_COUNT];
+ MainThread[] mt = new MainThread[SERVER_COUNT];
+ ZooKeeper[] zk = new ZooKeeper[SERVER_COUNT];
for (int i = 2; i < SERVER_COUNT; i++) {
- mt[i] = new MainThread(i, clientPorts[i], nextQuorumCfgSection,
- true, "200000000");
+ mt[i] = new MainThread(i, clientPorts[i], nextQuorumCfgSection, true, "200000000");
mt[i].start();
- zk[i] = new ZooKeeper("127.0.0.1:" + clientPorts[i],
- ClientBase.CONNECTION_TIMEOUT, this);
+ zk[i] = new ZooKeeper("127.0.0.1:" + clientPorts[i], ClientBase.CONNECTION_TIMEOUT, this);
}
for (int i = 2; i < SERVER_COUNT; i++) {
- Assert.assertTrue("waiting for server " + i + " being up",
- ClientBase.waitForServerUp("127.0.0.1:" + clientPorts[i],
- CONNECTION_TIMEOUT));
+ assertTrue(
+ "waiting for server " + i + " being up",
+ ClientBase.waitForServerUp("127.0.0.1:" + clientPorts[i], CONNECTION_TIMEOUT));
}
ReconfigTest.testNormalOperation(zk[2], zk[3]);
@@ -350,26 +337,24 @@ public class ReconfigRecoveryTest extends QuorumPeerTestBase {
// for them that a reconfiguration was in progress when they failed
// and the leader will complete it.
for (int i = 0; i < 2; i++) {
- mt[i] = new MainThread(i, clientPorts[i], currentQuorumCfgSection,
- true, "100000000");
+ mt[i] = new MainThread(i, clientPorts[i], currentQuorumCfgSection, true, "100000000");
mt[i].writeTempDynamicConfigFile(nextQuorumCfgSection, "200000000");
mt[i].start();
- zk[i] = new ZooKeeper("127.0.0.1:" + clientPorts[i],
- ClientBase.CONNECTION_TIMEOUT, this);
+ zk[i] = new ZooKeeper("127.0.0.1:" + clientPorts[i], ClientBase.CONNECTION_TIMEOUT, this);
}
// servers 0 and 1 should connect to all servers, including the one in
// their .next file during startup, and will find the next config and join it
for (int i = 0; i < 2; i++) {
- Assert.assertTrue("waiting for server " + i + " being up",
- ClientBase.waitForServerUp("127.0.0.1:" + clientPorts[i],
- CONNECTION_TIMEOUT * 2));
+ assertTrue(
+ "waiting for server " + i + " being up",
+ ClientBase.waitForServerUp("127.0.0.1:" + clientPorts[i], CONNECTION_TIMEOUT * 2));
}
// make sure they joined the new config without any change to it
- Assert.assertEquals(epoch, mt[0].main.quorumPeer.getAcceptedEpoch());
- Assert.assertEquals(epoch, mt[1].main.quorumPeer.getAcceptedEpoch());
- Assert.assertEquals(epoch, mt[2].main.quorumPeer.getAcceptedEpoch());
+ assertEquals(epoch, mt[0].main.quorumPeer.getAcceptedEpoch());
+ assertEquals(epoch, mt[1].main.quorumPeer.getAcceptedEpoch());
+ assertEquals(epoch, mt[2].main.quorumPeer.getAcceptedEpoch());
ReconfigTest.testServerHasConfig(zk[0], allServers, null);
ReconfigTest.testServerHasConfig(zk[1], allServers, null);
@@ -409,41 +394,39 @@ public class ReconfigRecoveryTest extends QuorumPeerTestBase {
ArrayList<String> allServersNext = new ArrayList<String>();
sb = new StringBuilder();
for (int i = 2; i < SERVER_COUNT; i++) {
- String server = "server." + i + "=localhost:" + ports[i][0] + ":"
- + ports[i][1] + ":participant;localhost:" + ports[i][2];
+ String server = "server." + i + "=localhost:" + ports[i][0] + ":" + ports[i][1]
+ + ":participant;localhost:" + ports[i][2];
allServersNext.add(server);
sb.append(server + "\n");
}
nextQuorumCfgSection = sb.toString();
- MainThread mt[] = new MainThread[SERVER_COUNT];
- ZooKeeper zk[] = new ZooKeeper[SERVER_COUNT];
+ MainThread[] mt = new MainThread[SERVER_COUNT];
+ ZooKeeper[] zk = new ZooKeeper[SERVER_COUNT];
// start server 2 with old config, where it is an observer
- mt[2] = new MainThread(2, ports[2][2], currentQuorumCfgSection,
- true, "100000000");
+ mt[2] = new MainThread(2, ports[2][2], currentQuorumCfgSection, true, "100000000");
mt[2].start();
- zk[2] = new ZooKeeper("127.0.0.1:" + ports[2][2],
- ClientBase.CONNECTION_TIMEOUT, this);
+ zk[2] = new ZooKeeper("127.0.0.1:" + ports[2][2], ClientBase.CONNECTION_TIMEOUT, this);
// start server 3 with new config
- mt[3] = new MainThread(3, ports[3][2], nextQuorumCfgSection,
- true, "200000000");
+ mt[3] = new MainThread(3, ports[3][2], nextQuorumCfgSection, true, "200000000");
mt[3].start();
- zk[3] = new ZooKeeper("127.0.0.1:" + ports[3][2],
- ClientBase.CONNECTION_TIMEOUT, this);
+ zk[3] = new ZooKeeper("127.0.0.1:" + ports[3][2], ClientBase.CONNECTION_TIMEOUT, this);
for (int i = 2; i < SERVER_COUNT; i++) {
- Assert.assertTrue("waiting for server " + i + " being up",
- ClientBase.waitForServerUp("127.0.0.1:" + ports[i][2],
- CONNECTION_TIMEOUT * 2));
+ assertTrue(
+ "waiting for server " + i + " being up",
+ ClientBase.waitForServerUp("127.0.0.1:" + ports[i][2], CONNECTION_TIMEOUT * 2));
ReconfigTest.testServerHasConfig(zk[i], allServersNext, null);
}
- Assert.assertEquals(nextQuorumCfgSection + "version=200000000",
- ReconfigTest.testServerHasConfig(zk[2], null, null));
- Assert.assertEquals(nextQuorumCfgSection + "version=200000000",
- ReconfigTest.testServerHasConfig(zk[3], null, null));
+ assertEquals(
+ nextQuorumCfgSection + "version=200000000",
+ ReconfigTest.testServerHasConfig(zk[2], null, null));
+ assertEquals(
+ nextQuorumCfgSection + "version=200000000",
+ ReconfigTest.testServerHasConfig(zk[3], null, null));
ReconfigTest.testNormalOperation(zk[2], zk[2]);
ReconfigTest.testNormalOperation(zk[3], zk[2]);
@@ -481,22 +464,20 @@ public class ReconfigRecoveryTest extends QuorumPeerTestBase {
currentQuorumCfg = sb.toString();
// Run servers 0..2 for a while
- MainThread mt[] = new MainThread[SERVER_COUNT];
- ZooKeeper zk[] = new ZooKeeper[SERVER_COUNT];
+ MainThread[] mt = new MainThread[SERVER_COUNT];
+ ZooKeeper[] zk = new ZooKeeper[SERVER_COUNT];
for (int i = 0; i <= 2; i++) {
- mt[i] = new MainThread(i, ports[i][2], currentQuorumCfg
- , true, "100000000");
+ mt[i] = new MainThread(i, ports[i][2], currentQuorumCfg, true, "100000000");
mt[i].start();
- zk[i] = new ZooKeeper("127.0.0.1:" + ports[i][2],
- ClientBase.CONNECTION_TIMEOUT, this);
+ zk[i] = new ZooKeeper("127.0.0.1:" + ports[i][2], ClientBase.CONNECTION_TIMEOUT, this);
}
ReconfigTest.testNormalOperation(zk[0], zk[2]);
for (int i = 0; i <= 2; i++) {
- Assert.assertTrue("waiting for server " + i + " being up",
- ClientBase.waitForServerUp("127.0.0.1:" + ports[i][2],
- CONNECTION_TIMEOUT * 2));
+ assertTrue(
+ "waiting for server " + i + " being up",
+ ClientBase.waitForServerUp("127.0.0.1:" + ports[i][2], CONNECTION_TIMEOUT * 2));
}
// shut servers 0..2 down
@@ -509,8 +490,8 @@ public class ReconfigRecoveryTest extends QuorumPeerTestBase {
ArrayList<String> allServersNext = new ArrayList<String>();
sb = new StringBuilder();
for (int i = 2; i < SERVER_COUNT; i++) {
- String server = "server." + i + "=localhost:" + ports[i][0] + ":"
- + ports[i][1] + ":participant;localhost:" + ports[i][2];
+ String server = "server." + i + "=localhost:" + ports[i][0] + ":" + ports[i][1]
+ + ":participant;localhost:" + ports[i][2];
allServersNext.add(server);
sb.append(server + "\n");
}
@@ -521,30 +502,29 @@ public class ReconfigRecoveryTest extends QuorumPeerTestBase {
for (int i = 0; i <= 2; i++) {
mt[i].writeTempDynamicConfigFile(nextQuorumCfgSection, "200000000");
mt[i].start();
- zk[i] = new ZooKeeper("127.0.0.1:" + ports[i][2],
- ClientBase.CONNECTION_TIMEOUT, this);
+ zk[i] = new ZooKeeper("127.0.0.1:" + ports[i][2], ClientBase.CONNECTION_TIMEOUT, this);
}
// new server 3 has still its invalid joiner config - everyone in old
// config + itself
- mt[3] = new MainThread(3, ports[3][2], currentQuorumCfg
- + allServersNext.get(1));
+ mt[3] = new MainThread(3, ports[3][2], currentQuorumCfg + allServersNext.get(1));
mt[3].start();
- zk[3] = new ZooKeeper("127.0.0.1:" + ports[3][2],
- ClientBase.CONNECTION_TIMEOUT, this);
+ zk[3] = new ZooKeeper("127.0.0.1:" + ports[3][2], ClientBase.CONNECTION_TIMEOUT, this);
for (int i = 2; i < SERVER_COUNT; i++) {
- Assert.assertTrue("waiting for server " + i + " being up",
- ClientBase.waitForServerUp("127.0.0.1:" + ports[i][2],
- CONNECTION_TIMEOUT * 3));
+ assertTrue(
+ "waiting for server " + i + " being up",
+ ClientBase.waitForServerUp("127.0.0.1:" + ports[i][2], CONNECTION_TIMEOUT * 3));
ReconfigTest.testServerHasConfig(zk[i], allServersNext, null);
}
ReconfigTest.testNormalOperation(zk[0], zk[2]);
ReconfigTest.testNormalOperation(zk[3], zk[1]);
- Assert.assertEquals(nextQuorumCfgSection + "version=200000000",
- ReconfigTest.testServerHasConfig(zk[2], null, null));
- Assert.assertEquals(nextQuorumCfgSection + "version=200000000",
- ReconfigTest.testServerHasConfig(zk[3], null, null));
+ assertEquals(
+ nextQuorumCfgSection + "version=200000000",
+ ReconfigTest.testServerHasConfig(zk[2], null, null));
+ assertEquals(
+ nextQuorumCfgSection + "version=200000000",
+ ReconfigTest.testServerHasConfig(zk[3], null, null));
for (int i = 0; i < SERVER_COUNT; i++) {
zk[i].close();
@@ -570,16 +550,15 @@ public class ReconfigRecoveryTest extends QuorumPeerTestBase {
* Creates a configuration string for servers 0..numServers-1 Ids in
* observerIds correspond to observers, other ids are for participants.
*/
- public static StringBuilder generateConfig(int numServers, int[][] ports,
- Set<Integer> observerIds) {
+ public static StringBuilder generateConfig(int numServers, int[][] ports, Set<Integer> observerIds) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < numServers; i++) {
- String server = "server." + i + "=localhost:" + ports[i][0] + ":"
- + ports[i][1] + ":"
- + (observerIds.contains(i) ? "observer" : "participant")
- + ";localhost:" + ports[i][2];
+ String server = "server." + i + "=localhost:" + ports[i][0] + ":" + ports[i][1] + ":"
+ + (observerIds.contains(i) ? "observer" : "participant")
+ + ";localhost:" + ports[i][2];
sb.append(server + "\n");
}
return sb;
}
-} \ No newline at end of file
+
+}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/ReconfigRollingRestartCompatibilityTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/ReconfigRollingRestartCompatibilityTest.java
index 65ec469ee..c4d2bd7ea 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/ReconfigRollingRestartCompatibilityTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/ReconfigRollingRestartCompatibilityTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,26 +18,26 @@
package org.apache.zookeeper.server.quorum;
+import static org.apache.zookeeper.test.ClientBase.CONNECTION_TIMEOUT;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
+import java.util.ArrayList;
import java.util.Arrays;
-import java.util.Map;
-import java.util.Set;
-import java.util.List;
import java.util.HashMap;
import java.util.HashSet;
-import java.util.ArrayList;
-
-import org.apache.zookeeper.ZooKeeper;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
import org.apache.zookeeper.PortAssignment;
+import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.test.ClientBase;
import org.apache.zookeeper.test.ReconfigTest;
-import org.junit.Assert;
import org.junit.Test;
-import static org.apache.zookeeper.test.ClientBase.CONNECTION_TIMEOUT;
-
/**
* ReconfigRollingRestartCompatibilityTest - we want to make sure that users
* can continue using the rolling restart approach when reconfig feature is disabled.
@@ -49,6 +49,7 @@ import static org.apache.zookeeper.test.ClientBase.CONNECTION_TIMEOUT;
* See ZOOKEEPER-2819 for more details.
*/
public class ReconfigRollingRestartCompatibilityTest extends QuorumPeerTestBase {
+
private static final String ZOO_CFG_BAK_FILE = "zoo.cfg.bak";
Map<Integer, Integer> clientPorts = new HashMap<>(5);
@@ -59,9 +60,8 @@ public class ReconfigRollingRestartCompatibilityTest extends QuorumPeerTestBase
String server;
for (int i = 0; i < serverCount; i++) {
clientPorts.put(i, PortAssignment.unique());
- server = "server." + i + "=localhost:" + PortAssignment.unique()
- + ":" + PortAssignment.unique() + ":participant;localhost:"
- + clientPorts.get(i);
+ server = "server." + i + "=localhost:" + PortAssignment.unique() + ":" + PortAssignment.unique()
+ + ":participant;localhost:" + clientPorts.get(i);
serverAddress.put(i, server);
sb.append(server + "\n");
}
@@ -72,9 +72,8 @@ public class ReconfigRollingRestartCompatibilityTest extends QuorumPeerTestBase
StringBuilder sb = new StringBuilder();
for (Integer sid : sidsToAdd) {
clientPorts.put(sid, PortAssignment.unique());
- serverAddress.put(sid, "server." + sid + "=localhost:" + PortAssignment.unique()
- + ":" + PortAssignment.unique() + ":participant;localhost:"
- + clientPorts.get(sid));
+ serverAddress.put(sid, "server." + sid + "=localhost:" + PortAssignment.unique() + ":" + PortAssignment.unique()
+ + ":participant;localhost:" + clientPorts.get(sid));
}
for (Integer sid : sidsToRemove) {
@@ -92,30 +91,23 @@ public class ReconfigRollingRestartCompatibilityTest extends QuorumPeerTestBase
@Test(timeout = 60000)
// Verify no zoo.cfg.dynamic and zoo.cfg.bak files existing locally
// when reconfig feature flag is off by default.
- public void testNoLocalDynamicConfigAndBackupFiles()
- throws InterruptedException, IOException {
+ public void testNoLocalDynamicConfigAndBackupFiles() throws InterruptedException, IOException {
int serverCount = 3;
String config = generateNewQuorumConfig(serverCount);
- QuorumPeerTestBase.MainThread mt[] = new QuorumPeerTestBase.MainThread[serverCount];
+ QuorumPeerTestBase.MainThread[] mt = new QuorumPeerTestBase.MainThread[serverCount];
String[] staticFileContent = new String[serverCount];
for (int i = 0; i < serverCount; i++) {
- mt[i] = new QuorumPeerTestBase.MainThread(i, clientPorts.get(i),
- config, false);
+ mt[i] = new QuorumPeerTestBase.MainThread(i, clientPorts.get(i), config, false);
mt[i].start();
}
for (int i = 0; i < serverCount; i++) {
- Assert.assertTrue("waiting for server " + i + " being up",
- ClientBase.waitForServerUp("127.0.0.1:" + clientPorts.get(i),
- CONNECTION_TIMEOUT));
- Assert.assertNull("static file backup (zoo.cfg.bak) shouldn't exist!",
- mt[i].getFileByName(ZOO_CFG_BAK_FILE));
- Assert.assertNull("dynamic configuration file (zoo.cfg.dynamic.*) shouldn't exist!",
- mt[i].getFileByName(mt[i].getQuorumPeer().getNextDynamicConfigFilename()));
+ assertTrue("waiting for server " + i + " being up", ClientBase.waitForServerUp("127.0.0.1:" + clientPorts.get(i), CONNECTION_TIMEOUT));
+ assertNull("static file backup (zoo.cfg.bak) shouldn't exist!", mt[i].getFileByName(ZOO_CFG_BAK_FILE));
+ assertNull("dynamic configuration file (zoo.cfg.dynamic.*) shouldn't exist!", mt[i].getFileByName(mt[i].getQuorumPeer().getNextDynamicConfigFilename()));
staticFileContent[i] = Files.readAllLines(mt[i].confFile.toPath(), StandardCharsets.UTF_8).toString();
- Assert.assertTrue("static config file should contain server entry " + serverAddress.get(i),
- staticFileContent[i].contains(serverAddress.get(i)));
+ assertTrue("static config file should contain server entry " + serverAddress.get(i), staticFileContent[i].contains(serverAddress.get(i)));
}
for (int i = 0; i < serverCount; i++) {
@@ -132,18 +124,15 @@ public class ReconfigRollingRestartCompatibilityTest extends QuorumPeerTestBase
int serverCount = 3;
String config = generateNewQuorumConfig(serverCount);
List<String> joiningServers = new ArrayList<>();
- QuorumPeerTestBase.MainThread mt[] = new QuorumPeerTestBase.MainThread[serverCount];
+ QuorumPeerTestBase.MainThread[] mt = new QuorumPeerTestBase.MainThread[serverCount];
for (int i = 0; i < serverCount; ++i) {
- mt[i] = new QuorumPeerTestBase.MainThread(i, clientPorts.get(i),
- config, false);
+ mt[i] = new QuorumPeerTestBase.MainThread(i, clientPorts.get(i), config, false);
mt[i].start();
joiningServers.add(serverAddress.get(i));
}
for (int i = 0; i < serverCount; ++i) {
- Assert.assertTrue("waiting for server " + i + " being up",
- ClientBase.waitForServerUp("127.0.0.1:" + clientPorts.get(i),
- CONNECTION_TIMEOUT));
+ assertTrue("waiting for server " + i + " being up", ClientBase.waitForServerUp("127.0.0.1:" + clientPorts.get(i), CONNECTION_TIMEOUT));
}
for (int i = 0; i < serverCount; ++i) {
@@ -166,19 +155,16 @@ public class ReconfigRollingRestartCompatibilityTest extends QuorumPeerTestBase
public void testRollingRestartWithMembershipChange() throws Exception {
int serverCount = 3;
String config = generateNewQuorumConfig(serverCount);
- QuorumPeerTestBase.MainThread mt[] = new QuorumPeerTestBase.MainThread[serverCount];
+ QuorumPeerTestBase.MainThread[] mt = new QuorumPeerTestBase.MainThread[serverCount];
List<String> joiningServers = new ArrayList<>();
for (int i = 0; i < serverCount; ++i) {
- mt[i] = new QuorumPeerTestBase.MainThread(i, clientPorts.get(i),
- config, false);
+ mt[i] = new QuorumPeerTestBase.MainThread(i, clientPorts.get(i), config, false);
mt[i].start();
joiningServers.add(serverAddress.get(i));
}
for (int i = 0; i < serverCount; ++i) {
- Assert.assertTrue("waiting for server " + i + " being up",
- ClientBase.waitForServerUp("127.0.0.1:" + clientPorts.get(i),
- CONNECTION_TIMEOUT));
+ assertTrue("waiting for server " + i + " being up", ClientBase.waitForServerUp("127.0.0.1:" + clientPorts.get(i), CONNECTION_TIMEOUT));
}
for (int i = 0; i < serverCount; ++i) {
@@ -189,9 +175,10 @@ public class ReconfigRollingRestartCompatibilityTest extends QuorumPeerTestBase
Map<Integer, String> oldServerAddress = new HashMap<>(serverAddress);
List<String> newServers = new ArrayList<>(joiningServers);
config = updateExistingQuorumConfig(Arrays.asList(3, 4), new ArrayList<Integer>());
- newServers.add(serverAddress.get(3)); newServers.add(serverAddress.get(4));
+ newServers.add(serverAddress.get(3));
+ newServers.add(serverAddress.get(4));
serverCount = serverAddress.size();
- Assert.assertEquals("Server count should be 5 after config update.", serverCount, 5);
+ assertEquals("Server count should be 5 after config update.", serverCount, 5);
// We are adding two new servers to the ensemble. These two servers should have the config which includes
// all five servers (the old three servers, plus the two servers added). The old three servers should only
@@ -199,12 +186,9 @@ public class ReconfigRollingRestartCompatibilityTest extends QuorumPeerTestBase
// peers.
mt = Arrays.copyOf(mt, mt.length + 2);
for (int i = 3; i < 5; ++i) {
- mt[i] = new QuorumPeerTestBase.MainThread(i, clientPorts.get(i),
- config, false);
+ mt[i] = new QuorumPeerTestBase.MainThread(i, clientPorts.get(i), config, false);
mt[i].start();
- Assert.assertTrue("waiting for server " + i + " being up",
- ClientBase.waitForServerUp("127.0.0.1:" + clientPorts.get(i),
- CONNECTION_TIMEOUT));
+ assertTrue("waiting for server " + i + " being up", ClientBase.waitForServerUp("127.0.0.1:" + clientPorts.get(i), CONNECTION_TIMEOUT));
verifyQuorumConfig(i, newServers, null);
verifyQuorumMembers(mt[i]);
}
@@ -243,18 +227,16 @@ public class ReconfigRollingRestartCompatibilityTest extends QuorumPeerTestBase
}
private void verifyQuorumMembers(QuorumPeerTestBase.MainThread mt, Set<String> expectedConfigs) {
- Map<Long, QuorumPeer.QuorumServer> members =
- mt.getQuorumPeer().getQuorumVerifier().getAllMembers();
+ Map<Long, QuorumPeer.QuorumServer> members = mt.getQuorumPeer().getQuorumVerifier().getAllMembers();
- Assert.assertTrue("Quorum member should not change.",
- members.size() == expectedConfigs.size());
+ assertTrue("Quorum member should not change.", members.size() == expectedConfigs.size());
for (QuorumPeer.QuorumServer qs : members.values()) {
String actualConfig = qs.toString();
- Assert.assertTrue("Unexpected config " + actualConfig + " found!",
- expectedConfigs.contains(actualConfig));
+ assertTrue("Unexpected config " + actualConfig + " found!", expectedConfigs.contains(actualConfig));
}
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/RemotePeerBeanTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/RemotePeerBeanTest.java
index 08dff63fb..97aa763ef 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/RemotePeerBeanTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/RemotePeerBeanTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -22,12 +22,10 @@ import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
-import static org.mockito.ArgumentMatchers.eq;
-
import java.net.InetSocketAddress;
-
import org.apache.zookeeper.server.quorum.QuorumPeer.QuorumServer;
import org.junit.Test;
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/SessionUpgradeQuorumTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/SessionUpgradeQuorumTest.java
index 7bfe4bdc0..7fc2f423e 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/SessionUpgradeQuorumTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/SessionUpgradeQuorumTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,46 +18,45 @@
package org.apache.zookeeper.server.quorum;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.concurrent.ConcurrentHashMap;
import javax.security.sasl.SaslException;
-
import org.apache.jute.BinaryOutputArchive;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.PortAssignment;
-import org.apache.zookeeper.ZKTestCase;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.ZooKeeper.States;
import org.apache.zookeeper.data.Id;
import org.apache.zookeeper.proto.CreateRequest;
-import org.apache.zookeeper.test.ClientBase;
-import org.apache.zookeeper.test.ClientBase.CountdownWatcher;
-import org.apache.zookeeper.server.persistence.FileTxnSnapLog;
import org.apache.zookeeper.server.ByteBufferInputStream;
import org.apache.zookeeper.server.Request;
+import org.apache.zookeeper.server.persistence.FileTxnSnapLog;
+import org.apache.zookeeper.test.ClientBase;
import org.junit.After;
-import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import org.apache.zookeeper.test.QuorumBase;
-import org.apache.zookeeper.test.DisconnectableZooKeeper;
-
public class SessionUpgradeQuorumTest extends QuorumPeerTestBase {
+
protected static final Logger LOG = LoggerFactory.getLogger(SessionUpgradeQuorumTest.class);
public static final int CONNECTION_TIMEOUT = ClientBase.CONNECTION_TIMEOUT;
public static final int SERVER_COUNT = 3;
- private MainThread mt[];
- private int clientPorts[];
- private TestQPMainDropSessionUpgrading qpMain[];
+ private MainThread[] mt;
+ private int[] clientPorts;
+ private TestQPMainDropSessionUpgrading[] qpMain;
@Before
public void setUp() throws Exception {
@@ -70,9 +69,7 @@ public class SessionUpgradeQuorumTest extends QuorumPeerTestBase {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < SERVER_COUNT; i++) {
clientPorts[i] = PortAssignment.unique();
- sb.append("server.").append(i).append("=127.0.0.1:")
- .append(PortAssignment.unique()).append(":")
- .append(PortAssignment.unique()).append("\n");
+ sb.append("server.").append(i).append("=127.0.0.1:").append(PortAssignment.unique()).append(":").append(PortAssignment.unique()).append("\n");
}
sb.append("localSessionsEnabled=true\n");
sb.append("localSessionsUpgradingEnabled=true\n");
@@ -93,9 +90,7 @@ public class SessionUpgradeQuorumTest extends QuorumPeerTestBase {
}
for (int i = 0; i < SERVER_COUNT; i++) {
- Assert.assertTrue("waiting for server " + i + " being up",
- ClientBase.waitForServerUp("127.0.0.1:" + clientPorts[i],
- CONNECTION_TIMEOUT));
+ assertTrue("waiting for server " + i + " being up", ClientBase.waitForServerUp("127.0.0.1:" + clientPorts[i], CONNECTION_TIMEOUT));
}
}
@@ -126,8 +121,7 @@ public class SessionUpgradeQuorumTest extends QuorumPeerTestBase {
// create a client, and create an ephemeral node to trigger the
// upgrading process
final String node = "/node-1";
- ZooKeeper zk = new ZooKeeper("127.0.0.1:" + clientPorts[followerA],
- ClientBase.CONNECTION_TIMEOUT, this);
+ ZooKeeper zk = new ZooKeeper("127.0.0.1:" + clientPorts[followerA], ClientBase.CONNECTION_TIMEOUT, this);
waitForOne(zk, States.CONNECTED);
@@ -136,12 +130,11 @@ public class SessionUpgradeQuorumTest extends QuorumPeerTestBase {
// should fail because of the injection
try {
- zk.create(node, new byte[2], ZooDefs.Ids.OPEN_ACL_UNSAFE,
- CreateMode.EPHEMERAL);
- Assert.fail("expect to failed to upgrade session due to the " +
- "TestQPMainDropSessionUpgrading is being used");
+ zk.create(node, new byte[2], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
+ fail("expect to failed to upgrade session due to the "
+ + "TestQPMainDropSessionUpgrading is being used");
} catch (KeeperException e) {
- LOG.info("KeeperException when create ephemeral node, {}", e);
+ LOG.info("KeeperException when create ephemeral node.", e);
}
// force to take snapshot
@@ -155,7 +148,7 @@ public class SessionUpgradeQuorumTest extends QuorumPeerTestBase {
mt[i].shutdown();
}
- ArrayList<States> waitStates =new ArrayList<States>();
+ ArrayList<States> waitStates = new ArrayList<States>();
waitStates.add(States.CONNECTING);
waitStates.add(States.CLOSED);
waitForOne(zk, waitStates);
@@ -167,42 +160,36 @@ public class SessionUpgradeQuorumTest extends QuorumPeerTestBase {
}
for (int i = 0; i < SERVER_COUNT; i++) {
- Assert.assertTrue("waiting for server " + i + " being up",
- ClientBase.waitForServerUp("127.0.0.1:" + clientPorts[i],
- CONNECTION_TIMEOUT));
+ assertTrue("waiting for server " + i + " being up", ClientBase.waitForServerUp("127.0.0.1:" + clientPorts[i], CONNECTION_TIMEOUT));
}
// check global session not exist on follower A
for (int i = 0; i < SERVER_COUNT; i++) {
- ConcurrentHashMap<Long, Integer> sessions =
- mt[i].main.quorumPeer.getZkDb().getSessionWithTimeOuts();
- Assert.assertFalse("server " + i + " should not have global " +
- "session " + sessionId, sessions.containsKey(sessionId));
+ ConcurrentHashMap<Long, Integer> sessions = mt[i].main.quorumPeer.getZkDb().getSessionWithTimeOuts();
+ assertFalse(
+ "server " + i + " should not have global " + "session " + sessionId,
+ sessions.containsKey(sessionId));
}
zk.close();
}
@Test
- public void testOnlyUpgradeSessionOnce()
- throws IOException, InterruptedException, KeeperException {
+ public void testOnlyUpgradeSessionOnce() throws IOException, InterruptedException, KeeperException {
// create a client, and create an ephemeral node to trigger the
// upgrading process
final String node = "/node-1";
- ZooKeeper zk = new ZooKeeper("127.0.0.1:" + clientPorts[0],
- ClientBase.CONNECTION_TIMEOUT, this);
+ ZooKeeper zk = new ZooKeeper("127.0.0.1:" + clientPorts[0], ClientBase.CONNECTION_TIMEOUT, this);
waitForOne(zk, States.CONNECTED);
long sessionId = zk.getSessionId();
- QuorumZooKeeperServer server =
- (QuorumZooKeeperServer) mt[0].main.quorumPeer.getActiveServer();
+ QuorumZooKeeperServer server = (QuorumZooKeeperServer) mt[0].main.quorumPeer.getActiveServer();
Request create1 = createEphemeralRequest("/data-1", sessionId);
Request create2 = createEphemeralRequest("/data-2", sessionId);
- Assert.assertNotNull("failed to upgrade on a ephemeral create",
- server.checkUpgradeSession(create1));
- Assert.assertNull("tried to upgrade again", server.checkUpgradeSession(create2));
+ assertNotNull("failed to upgrade on a ephemeral create", server.checkUpgradeSession(create1));
+ assertNull("tried to upgrade again", server.checkUpgradeSession(create2));
// clean al the setups and close the zk
zk.close();
@@ -221,15 +208,12 @@ public class SessionUpgradeQuorumTest extends QuorumPeerTestBase {
return new QuorumPeer() {
@Override
- protected Follower makeFollower(FileTxnSnapLog logFactory)
- throws IOException {
+ protected Follower makeFollower(FileTxnSnapLog logFactory) throws IOException {
- return new Follower(this, new FollowerZooKeeperServer(
- logFactory, this, this.getZkDb())) {
+ return new Follower(this, new FollowerZooKeeperServer(logFactory, this, this.getZkDb())) {
@Override
- protected void request(Request request)
- throws IOException {
+ protected void request(Request request) throws IOException {
if (!shouldDrop) {
super.request(request);
return;
@@ -241,20 +225,18 @@ public class SessionUpgradeQuorumTest extends QuorumPeerTestBase {
return;
}
- if (request.type == ZooDefs.OpCode.create &&
- request.cnxn != null) {
+ if (request.type == ZooDefs.OpCode.create && request.cnxn != null) {
CreateRequest createRequest = new CreateRequest();
request.request.rewind();
- ByteBufferInputStream.byteBuffer2Record(
- request.request, createRequest);
+ ByteBufferInputStream.byteBuffer2Record(request.request, createRequest);
request.request.rewind();
try {
- CreateMode createMode =
- CreateMode.fromFlag(createRequest.getFlags());
+ CreateMode createMode = CreateMode.fromFlag(createRequest.getFlags());
if (createMode.isEphemeral()) {
request.cnxn.sendCloseSession();
}
- } catch (KeeperException e) {}
+ } catch (KeeperException e) {
+ }
return;
}
@@ -264,6 +246,7 @@ public class SessionUpgradeQuorumTest extends QuorumPeerTestBase {
}
};
}
+
}
private void waitForOne(ZooKeeper zk, ArrayList<States> states) throws InterruptedException {
@@ -280,13 +263,10 @@ public class SessionUpgradeQuorumTest extends QuorumPeerTestBase {
private Request createEphemeralRequest(String path, long sessionId) throws IOException {
ByteArrayOutputStream boas = new ByteArrayOutputStream();
BinaryOutputArchive boa = BinaryOutputArchive.getArchive(boas);
- CreateRequest createRequest = new CreateRequest(path,
- "data".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE,
- CreateMode.EPHEMERAL.toFlag());
+ CreateRequest createRequest = new CreateRequest(path, "data".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL.toFlag());
createRequest.serialize(boa, "request");
ByteBuffer bb = ByteBuffer.wrap(boas.toByteArray());
- return new Request(null, sessionId, 1, ZooDefs.OpCode.create2, bb,
- new ArrayList<Id>());
+ return new Request(null, sessionId, 1, ZooDefs.OpCode.create2, bb, new ArrayList<Id>());
}
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/StandaloneDisabledTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/StandaloneDisabledTest.java
index 82b959a14..a4fcd8293 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/StandaloneDisabledTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/StandaloneDisabledTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -19,28 +19,28 @@
package org.apache.zookeeper.server.quorum;
import static org.apache.zookeeper.test.ClientBase.CONNECTION_TIMEOUT;
-
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;
-
import org.apache.zookeeper.KeeperException;
-import org.apache.zookeeper.data.Stat;
import org.apache.zookeeper.PortAssignment;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.admin.ZooKeeperAdmin;
import org.apache.zookeeper.client.FourLetterWordMain;
+import org.apache.zookeeper.data.Stat;
import org.apache.zookeeper.test.ClientBase;
import org.apache.zookeeper.test.ReconfigTest;
-import org.junit.Assert;
import org.junit.Test;
public class StandaloneDisabledTest extends QuorumPeerTestBase {
private final int NUM_SERVERS = 5;
- private MainThread peers[];
- private ZooKeeper zkHandles[];
- private ZooKeeperAdmin zkAdminHandles[];
- private int clientPorts[];
+ private MainThread[] peers;
+ private ZooKeeper[] zkHandles;
+ private ZooKeeperAdmin[] zkAdminHandles;
+ private int[] clientPorts;
private final int leaderId = 0;
private final int follower1 = 1;
private final int follower2 = 2;
@@ -60,14 +60,13 @@ public class StandaloneDisabledTest extends QuorumPeerTestBase {
//start one server
startServer(leaderId, serverStrings.get(leaderId) + "\n");
ReconfigTest.testServerHasConfig(zkHandles[leaderId], null, null);
- LOG.info("Initial Configuration:\n"
- + new String(zkHandles[leaderId].getConfig(this, new Stat())));
+ LOG.info("Initial Configuration:\n" + new String(zkHandles[leaderId].getConfig(this, new Stat())));
//start and add 2 followers
startFollowers();
testReconfig(leaderId, true, reconfigServers);
LOG.info("Configuration after adding 2 followers:\n"
- + new String(zkHandles[leaderId].getConfig(this, new Stat())));
+ + new String(zkHandles[leaderId].getConfig(this, new Stat())));
//shutdown leader- quorum should still exist
shutDownServer(leaderId);
@@ -79,8 +78,9 @@ public class StandaloneDisabledTest extends QuorumPeerTestBase {
reconfigServers.add(Integer.toString(follower2));
try {
ReconfigTest.reconfig(zkAdminHandles[follower1], null, reconfigServers, null, -1);
- Assert.fail("reconfig completed successfully even though there is no quorum up in new config!");
- } catch (KeeperException.NewConfigNoQuorum e) { }
+ fail("reconfig completed successfully even though there is no quorum up in new config!");
+ } catch (KeeperException.NewConfigNoQuorum e) {
+ }
//reconfigure out leader and follower 1. Remaining follower
//2 should elect itself as leader and run by itself
@@ -88,8 +88,7 @@ public class StandaloneDisabledTest extends QuorumPeerTestBase {
reconfigServers.add(Integer.toString(leaderId));
reconfigServers.add(Integer.toString(follower1));
testReconfig(follower2, false, reconfigServers);
- LOG.info("Configuration after removing leader and follower 1:\n"
- + new String(zkHandles[follower2].getConfig(this, new Stat())));
+ LOG.info("Configuration after removing leader and follower 1:\n" + new String(zkHandles[follower2].getConfig(this, new Stat())));
// Kill server 1 to avoid it interferences with FLE of the quorum {2, 3, 4}.
shutDownServer(follower1);
@@ -99,11 +98,11 @@ public class StandaloneDisabledTest extends QuorumPeerTestBase {
reconfigServers.add(Integer.toString(follower2));
try {
zkAdminHandles[follower2].reconfigure(null, reconfigServers, null, -1, new Stat());
- Assert.fail("reconfig completed successfully even though there is no quorum up in new config!");
+ fail("reconfig completed successfully even though there is no quorum up in new config!");
} catch (KeeperException.BadArgumentsException e) {
// This is expected.
} catch (Exception e) {
- Assert.fail("Should have been BadArgumentsException!");
+ fail("Should have been BadArgumentsException!");
}
//Add two participants and change them to observers to check
@@ -113,7 +112,7 @@ public class StandaloneDisabledTest extends QuorumPeerTestBase {
testReconfig(follower2, true, reconfigServers); //add partcipants
testReconfig(follower2, true, observerStrings); //change to observers
LOG.info("Configuration after adding two observers:\n"
- + new String(zkHandles[follower2].getConfig(this, new Stat())));
+ + new String(zkHandles[follower2].getConfig(this, new Stat())));
shutDownData();
}
@@ -131,8 +130,7 @@ public class StandaloneDisabledTest extends QuorumPeerTestBase {
clientPorts = new int[NUM_SERVERS];
serverStrings = buildServerStrings();
reconfigServers = new ArrayList<String>();
- System.setProperty("zookeeper.DigestAuthenticationProvider.superDigest",
- "super:D/InIHSb7yEEbrWz8b9l71RjZJU="/* password is 'test'*/);
+ System.setProperty("zookeeper.DigestAuthenticationProvider.superDigest", "super:D/InIHSb7yEEbrWz8b9l71RjZJU="/* password is 'test'*/);
}
/**
@@ -155,11 +153,10 @@ public class StandaloneDisabledTest extends QuorumPeerTestBase {
private ArrayList<String> buildServerStrings() {
ArrayList<String> serverStrings = new ArrayList<String>();
- for(int i = 0; i < NUM_SERVERS; i++) {
+ for (int i = 0; i < NUM_SERVERS; i++) {
clientPorts[i] = PortAssignment.unique();
- String server = "server." + i + "=localhost:" + PortAssignment.unique()
- +":"+PortAssignment.unique() + ":participant;"
- + "localhost:" + clientPorts[i];
+ String server = "server." + i + "=localhost:" + PortAssignment.unique() + ":" + PortAssignment.unique() + ":participant;"
+ + "localhost:" + clientPorts[i];
serverStrings.add(server);
}
return serverStrings;
@@ -173,16 +170,15 @@ public class StandaloneDisabledTest extends QuorumPeerTestBase {
private void startServer(int id, String config) throws Exception {
peers[id] = new MainThread(id, clientPorts[id], config);
peers[id].start();
- Assert.assertTrue("Server " + id + " is not up",
- ClientBase.waitForServerUp("127.0.0.1:" + clientPorts[id], CONNECTION_TIMEOUT));
- Assert.assertTrue("Error- Server started in Standalone Mode!",
- peers[id].isQuorumPeerRunning());
+ assertTrue(
+ "Server " + id + " is not up",
+ ClientBase.waitForServerUp("127.0.0.1:" + clientPorts[id], CONNECTION_TIMEOUT));
+ assertTrue("Error- Server started in Standalone Mode!", peers[id].isQuorumPeerRunning());
zkHandles[id] = ClientBase.createZKClient("127.0.0.1:" + clientPorts[id]);
zkAdminHandles[id] = new ZooKeeperAdmin("127.0.0.1:" + clientPorts[id], CONNECTION_TIMEOUT, this);
zkAdminHandles[id].addAuthInfo("digest", "super:test".getBytes());
String statCommandOut = FourLetterWordMain.send4LetterWord("127.0.0.1", clientPorts[id], "stat");
- LOG.info(String.format("Started server id %d with config:\n%s\nStat output:\n%s",
- id, config, statCommandOut));
+ LOG.info(String.format("Started server id %d with config:\n%s\nStat output:\n%s", id, config, statCommandOut));
}
/**
@@ -203,15 +199,18 @@ public class StandaloneDisabledTest extends QuorumPeerTestBase {
*/
private void startFollowers() throws Exception {
reconfigServers.clear();
- for(int i = 1; i <= 2; i++) {
- String config = serverStrings.get(leaderId) + "\n"
- + serverStrings.get(i) + "\n"
- + serverStrings.get(i % 2 + 1) + "\n";
+ for (int i = 1; i <= 2; i++) {
+ String config = serverStrings.get(leaderId)
+ + "\n"
+ + serverStrings.get(i)
+ + "\n"
+ + serverStrings.get(i % 2 + 1)
+ + "\n";
startServer(i, config);
reconfigServers.add(serverStrings.get(i));
}
}
- /**
+ /**
* Starts servers 1 and 2 as participants,
* adds them to the list to be reconfigured
* into the ensemble, and adds an observer
@@ -220,9 +219,8 @@ public class StandaloneDisabledTest extends QuorumPeerTestBase {
*/
private void startObservers(ArrayList<String> observerStrings) throws Exception {
reconfigServers.clear();
- for(int i = observer1; i <= observer2; i++) {
- String config = serverStrings.get(follower2) + "\n"
- + serverStrings.get(i) + "\n";
+ for (int i = observer1; i <= observer2; i++) {
+ String config = serverStrings.get(follower2) + "\n" + serverStrings.get(i) + "\n";
startServer(i, config);
reconfigServers.add(serverStrings.get(i));
observerStrings.add(serverStrings.get(i).replace("participant", "observer"));
@@ -234,8 +232,7 @@ public class StandaloneDisabledTest extends QuorumPeerTestBase {
* the given servers. Tests appropriately to make sure the
* reconfig succeeded.
*/
- private void testReconfig(int id, boolean adding,
- ArrayList<String> servers) throws Exception {
+ private void testReconfig(int id, boolean adding, ArrayList<String> servers) throws Exception {
if (adding) {
ReconfigTest.reconfig(zkAdminHandles[id], servers, null, null, -1);
for (String server : servers) {
@@ -250,18 +247,19 @@ public class StandaloneDisabledTest extends QuorumPeerTestBase {
}
- /**
- * Ensure observer cannot start by itself
- **/
+ /**
+ * Ensure observer cannot start by itself
+ **/
@Test
public void startObserver() throws Exception {
int clientPort = PortAssignment.unique();
- String config = "server." + observer1 + "=localhost:"+ PortAssignment.unique()
- + ":" + clientPort + ":observer;"
- + "localhost:" + PortAssignment.unique();
+ String config = "server." + observer1 + "=localhost:" + PortAssignment.unique() + ":" + clientPort
+ + ":observer;" + "localhost:" + PortAssignment.unique();
MainThread observer = new MainThread(observer1, clientPort, config);
observer.start();
- Assert.assertFalse("Observer was able to start by itself!",
- ClientBase.waitForServerUp("127.0.0.1:" + clientPort, CONNECTION_TIMEOUT));
+ assertFalse(
+ "Observer was able to start by itself!",
+ ClientBase.waitForServerUp("127.0.0.1:" + clientPort, CONNECTION_TIMEOUT));
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/StatCommandTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/StatCommandTest.java
index eccb6b184..7a46bac05 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/StatCommandTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/StatCommandTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,6 +18,14 @@
package org.apache.zookeeper.server.quorum;
+import static org.hamcrest.CoreMatchers.containsString;
+import static org.junit.Assert.assertThat;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+import java.io.PrintWriter;
+import java.io.StringWriter;
+import java.util.ArrayList;
+import java.util.List;
import org.apache.zookeeper.server.ServerCnxn;
import org.apache.zookeeper.server.ServerCnxnFactory;
import org.apache.zookeeper.server.ServerStats;
@@ -27,17 +35,8 @@ import org.apache.zookeeper.server.command.StatCommand;
import org.junit.Before;
import org.junit.Test;
-import java.io.PrintWriter;
-import java.io.StringWriter;
-import java.util.ArrayList;
-import java.util.List;
-
-import static org.hamcrest.CoreMatchers.containsString;
-import static org.junit.Assert.assertThat;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.when;
-
public class StatCommandTest {
+
private StringWriter outputWriter;
private StatCommand statCommand;
private ServerStats.Provider providerMock;
@@ -102,4 +101,5 @@ public class StatCommandTest {
assertThat(output, containsString("Zookeeper version:"));
assertThat(output, containsString("Node count:"));
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/StatResetCommandTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/StatResetCommandTest.java
index 0c20c5887..850c4d81f 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/StatResetCommandTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/StatResetCommandTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,24 +18,23 @@
package org.apache.zookeeper.server.quorum;
-import org.apache.zookeeper.server.ServerCnxn;
-import org.apache.zookeeper.server.ServerStats;
-import org.apache.zookeeper.server.ZooKeeperServer;
-import org.apache.zookeeper.server.command.StatResetCommand;
-import org.junit.Before;
-import org.junit.Test;
-
-import java.io.PrintWriter;
-import java.io.StringWriter;
-
import static org.apache.zookeeper.server.command.AbstractFourLetterCommand.ZK_NOT_SERVING;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
+import java.io.PrintWriter;
+import java.io.StringWriter;
+import org.apache.zookeeper.server.ServerCnxn;
+import org.apache.zookeeper.server.ServerStats;
+import org.apache.zookeeper.server.ZooKeeperServer;
+import org.apache.zookeeper.server.command.StatResetCommand;
+import org.junit.Before;
+import org.junit.Test;
public class StatResetCommandTest {
+
private StatResetCommand statResetCommand;
private StringWriter outputWriter;
private ZooKeeperServer zks;
@@ -108,4 +107,5 @@ public class StatResetCommandTest {
verify(serverStats, times(1)).reset();
verify(bufferStats, times(1)).reset();
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/SyncRequestProcessorMetricTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/SyncRequestProcessorMetricTest.java
index 843dfabfb..c00362219 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/SyncRequestProcessorMetricTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/SyncRequestProcessorMetricTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,26 +18,30 @@
package org.apache.zookeeper.server.quorum;
-import org.apache.zookeeper.ZooDefs;
-import org.apache.zookeeper.metrics.MetricsUtils;
-import org.apache.zookeeper.server.*;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
-
-import java.nio.ByteBuffer;
-import java.util.Map;
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.TimeUnit;
-
import static org.hamcrest.number.OrderingComparison.greaterThan;
import static org.hamcrest.number.OrderingComparison.greaterThanOrEqualTo;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
+import java.nio.ByteBuffer;
+import java.util.Map;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import org.apache.zookeeper.ZooDefs;
+import org.apache.zookeeper.metrics.MetricsUtils;
+import org.apache.zookeeper.server.Request;
+import org.apache.zookeeper.server.RequestProcessor;
+import org.apache.zookeeper.server.SyncRequestProcessor;
+import org.apache.zookeeper.server.ZKDatabase;
+import org.apache.zookeeper.server.ZooKeeperServer;
+import org.junit.Before;
+import org.junit.Test;
public class SyncRequestProcessorMetricTest {
+
ZooKeeperServer zks;
RequestProcessor nextProcessor;
CountDownLatch allRequestsFlushed;
@@ -46,7 +50,7 @@ public class SyncRequestProcessorMetricTest {
public void setup() throws Exception {
ZKDatabase db = mock(ZKDatabase.class);
when(db.append(any(Request.class))).thenReturn(true);
- doAnswer(invocation->{
+ doAnswer(invocation -> {
Thread.sleep(100);
return null;
}).when(db).commit();
@@ -61,19 +65,18 @@ public class SyncRequestProcessorMetricTest {
}
private Request createRquest(long sessionId, int xid) {
- return new Request(null, sessionId, xid, ZooDefs.OpCode.setData,
- ByteBuffer.wrap(new byte[10]), null);
+ return new Request(null, sessionId, xid, ZooDefs.OpCode.setData, ByteBuffer.wrap(new byte[10]), null);
}
@Test
- public void testSyncProcessorMetrics() throws Exception{
+ public void testSyncProcessorMetrics() throws Exception {
SyncRequestProcessor syncProcessor = new SyncRequestProcessor(zks, nextProcessor);
- for (int i=0; i<500; i++) {
+ for (int i = 0; i < 500; i++) {
syncProcessor.processRequest(createRquest(1, i));
}
Map<String, Object> values = MetricsUtils.currentServerMetrics();
- Assert.assertEquals(500L, values.get("sync_processor_request_queued"));
+ assertEquals(500L, values.get("sync_processor_request_queued"));
allRequestsFlushed = new CountDownLatch(500);
syncProcessor.start();
@@ -82,23 +85,24 @@ public class SyncRequestProcessorMetricTest {
values = MetricsUtils.currentServerMetrics();
- Assert.assertEquals(501L, values.get("cnt_sync_processor_queue_size"));
- Assert.assertEquals(500L, values.get("max_sync_processor_queue_size"));
- Assert.assertEquals(0L, values.get("min_sync_processor_queue_size"));
+ assertEquals(501L, values.get("cnt_sync_processor_queue_size"));
+ assertEquals(500L, values.get("max_sync_processor_queue_size"));
+ assertEquals(0L, values.get("min_sync_processor_queue_size"));
- Assert.assertEquals(500L, values.get("cnt_sync_processor_queue_time_ms"));
- Assert.assertThat((long)values.get("max_sync_processor_queue_time_ms"), greaterThan(0L));
+ assertEquals(500L, values.get("cnt_sync_processor_queue_time_ms"));
+ assertThat((long) values.get("max_sync_processor_queue_time_ms"), greaterThan(0L));
- Assert.assertEquals(500L, values.get("cnt_sync_processor_queue_and_flush_time_ms"));
- Assert.assertThat((long)values.get("max_sync_processor_queue_and_flush_time_ms"), greaterThan(0L));
+ assertEquals(500L, values.get("cnt_sync_processor_queue_and_flush_time_ms"));
+ assertThat((long) values.get("max_sync_processor_queue_and_flush_time_ms"), greaterThan(0L));
- Assert.assertEquals(500L, values.get("cnt_sync_process_time"));
- Assert.assertThat((long)values.get("max_sync_process_time"), greaterThan(0L));
+ assertEquals(500L, values.get("cnt_sync_process_time"));
+ assertThat((long) values.get("max_sync_process_time"), greaterThan(0L));
- Assert.assertEquals(500L, values.get("max_sync_processor_batch_size"));
- Assert.assertEquals(1L, values.get("cnt_sync_processor_queue_flush_time_ms"));
- Assert.assertThat((long)values.get("max_sync_processor_queue_flush_time_ms"), greaterThanOrEqualTo(100L));
+ assertEquals(500L, values.get("max_sync_processor_batch_size"));
+ assertEquals(1L, values.get("cnt_sync_processor_queue_flush_time_ms"));
+ assertThat((long) values.get("max_sync_processor_queue_flush_time_ms"), greaterThanOrEqualTo(100L));
syncProcessor.shutdown();
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/UnifiedServerSocketModeDetectionTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/UnifiedServerSocketModeDetectionTest.java
index e9267b9ef..d02c11438 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/UnifiedServerSocketModeDetectionTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/UnifiedServerSocketModeDetectionTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -15,8 +15,12 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
package org.apache.zookeeper.server.quorum;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
@@ -32,7 +36,6 @@ import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
-
import org.apache.commons.io.FileUtils;
import org.apache.zookeeper.PortAssignment;
import org.apache.zookeeper.ZKTestCase;
@@ -45,7 +48,6 @@ import org.apache.zookeeper.test.ClientBase;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.junit.After;
import org.junit.AfterClass;
-import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
@@ -61,14 +63,14 @@ import org.slf4j.LoggerFactory;
*/
@RunWith(Parameterized.class)
public class UnifiedServerSocketModeDetectionTest extends ZKTestCase {
- private static final Logger LOG = LoggerFactory.getLogger(
- UnifiedServerSocketModeDetectionTest.class);
+
+ private static final Logger LOG = LoggerFactory.getLogger(UnifiedServerSocketModeDetectionTest.class);
@Parameterized.Parameters
public static Collection<Object[]> params() {
ArrayList<Object[]> result = new ArrayList<>();
- result.add(new Object[] { true });
- result.add(new Object[] { false });
+ result.add(new Object[]{true});
+ result.add(new Object[]{false});
return result;
}
@@ -88,11 +90,7 @@ public class UnifiedServerSocketModeDetectionTest extends ZKTestCase {
public static void setUpClass() throws Exception {
Security.addProvider(new BouncyCastleProvider());
tempDir = ClientBase.createEmptyTestDir();
- x509TestContext = X509TestContext.newBuilder()
- .setTempDir(tempDir)
- .setKeyStoreKeyType(X509KeyType.EC)
- .setTrustStoreKeyType(X509KeyType.EC)
- .build();
+ x509TestContext = X509TestContext.newBuilder().setTempDir(tempDir).setKeyStoreKeyType(X509KeyType.EC).setTrustStoreKeyType(X509KeyType.EC).build();
}
@AfterClass
@@ -157,7 +155,7 @@ public class UnifiedServerSocketModeDetectionTest extends ZKTestCase {
} else {
clientSocket = new Socket();
clientSocket.connect(localServerAddress);
- clientSocket.getOutputStream().write(new byte[] { 1, 2, 3, 4, 5 });
+ clientSocket.getOutputStream().write(new byte[]{1, 2, 3, 4, 5});
}
serverSideSocket = acceptFuture.get();
}
@@ -177,55 +175,55 @@ public class UnifiedServerSocketModeDetectionTest extends ZKTestCase {
@Test
public void testGetInetAddress() {
serverSideSocket.getInetAddress();
- Assert.assertFalse(serverSideSocket.isModeKnown());
+ assertFalse(serverSideSocket.isModeKnown());
}
@Test
public void testGetLocalAddress() {
serverSideSocket.getLocalAddress();
- Assert.assertFalse(serverSideSocket.isModeKnown());
+ assertFalse(serverSideSocket.isModeKnown());
}
@Test
public void testGetPort() {
serverSideSocket.getPort();
- Assert.assertFalse(serverSideSocket.isModeKnown());
+ assertFalse(serverSideSocket.isModeKnown());
}
@Test
public void testGetLocalPort() {
serverSideSocket.getLocalPort();
- Assert.assertFalse(serverSideSocket.isModeKnown());
+ assertFalse(serverSideSocket.isModeKnown());
}
@Test
public void testGetRemoteSocketAddress() {
serverSideSocket.getRemoteSocketAddress();
- Assert.assertFalse(serverSideSocket.isModeKnown());
+ assertFalse(serverSideSocket.isModeKnown());
}
@Test
public void testGetLocalSocketAddress() {
serverSideSocket.getLocalSocketAddress();
- Assert.assertFalse(serverSideSocket.isModeKnown());
+ assertFalse(serverSideSocket.isModeKnown());
}
@Test
public void testGetInputStream() throws IOException {
serverSideSocket.getInputStream();
- Assert.assertFalse(serverSideSocket.isModeKnown());
+ assertFalse(serverSideSocket.isModeKnown());
}
@Test
public void testGetOutputStream() throws IOException {
serverSideSocket.getOutputStream();
- Assert.assertFalse(serverSideSocket.isModeKnown());
+ assertFalse(serverSideSocket.isModeKnown());
}
@Test
public void testGetTcpNoDelay() throws IOException {
serverSideSocket.getTcpNoDelay();
- Assert.assertFalse(serverSideSocket.isModeKnown());
+ assertFalse(serverSideSocket.isModeKnown());
}
@Test
@@ -233,14 +231,14 @@ public class UnifiedServerSocketModeDetectionTest extends ZKTestCase {
boolean tcpNoDelay = serverSideSocket.getTcpNoDelay();
tcpNoDelay = !tcpNoDelay;
serverSideSocket.setTcpNoDelay(tcpNoDelay);
- Assert.assertFalse(serverSideSocket.isModeKnown());
- Assert.assertEquals(tcpNoDelay, serverSideSocket.getTcpNoDelay());
+ assertFalse(serverSideSocket.isModeKnown());
+ assertEquals(tcpNoDelay, serverSideSocket.getTcpNoDelay());
}
@Test
public void testGetSoLinger() throws IOException {
serverSideSocket.getSoLinger();
- Assert.assertFalse(serverSideSocket.isModeKnown());
+ assertFalse(serverSideSocket.isModeKnown());
}
@Test
@@ -249,20 +247,20 @@ public class UnifiedServerSocketModeDetectionTest extends ZKTestCase {
if (soLinger == -1) {
// enable it if disabled
serverSideSocket.setSoLinger(true, 1);
- Assert.assertFalse(serverSideSocket.isModeKnown());
- Assert.assertEquals(1, serverSideSocket.getSoLinger());
+ assertFalse(serverSideSocket.isModeKnown());
+ assertEquals(1, serverSideSocket.getSoLinger());
} else {
// disable it if enabled
serverSideSocket.setSoLinger(false, -1);
- Assert.assertFalse(serverSideSocket.isModeKnown());
- Assert.assertEquals(-1, serverSideSocket.getSoLinger());
+ assertFalse(serverSideSocket.isModeKnown());
+ assertEquals(-1, serverSideSocket.getSoLinger());
}
}
@Test
public void testGetSoTimeout() throws IOException {
serverSideSocket.getSoTimeout();
- Assert.assertFalse(serverSideSocket.isModeKnown());
+ assertFalse(serverSideSocket.isModeKnown());
}
@Test
@@ -270,20 +268,20 @@ public class UnifiedServerSocketModeDetectionTest extends ZKTestCase {
int timeout = serverSideSocket.getSoTimeout();
timeout = timeout + 10;
serverSideSocket.setSoTimeout(timeout);
- Assert.assertFalse(serverSideSocket.isModeKnown());
- Assert.assertEquals(timeout, serverSideSocket.getSoTimeout());
+ assertFalse(serverSideSocket.isModeKnown());
+ assertEquals(timeout, serverSideSocket.getSoTimeout());
}
@Test
public void testGetSendBufferSize() throws IOException {
serverSideSocket.getSendBufferSize();
- Assert.assertFalse(serverSideSocket.isModeKnown());
+ assertFalse(serverSideSocket.isModeKnown());
}
@Test
public void testSetSendBufferSize() throws IOException {
serverSideSocket.setSendBufferSize(serverSideSocket.getSendBufferSize() + 1024);
- Assert.assertFalse(serverSideSocket.isModeKnown());
+ assertFalse(serverSideSocket.isModeKnown());
// Note: the new buffer size is a hint and socket implementation
// is free to ignore it, so we don't verify that we get back the
// same value.
@@ -293,13 +291,13 @@ public class UnifiedServerSocketModeDetectionTest extends ZKTestCase {
@Test
public void testGetReceiveBufferSize() throws IOException {
serverSideSocket.getReceiveBufferSize();
- Assert.assertFalse(serverSideSocket.isModeKnown());
+ assertFalse(serverSideSocket.isModeKnown());
}
@Test
public void testSetReceiveBufferSize() throws IOException {
serverSideSocket.setReceiveBufferSize(serverSideSocket.getReceiveBufferSize() + 1024);
- Assert.assertFalse(serverSideSocket.isModeKnown());
+ assertFalse(serverSideSocket.isModeKnown());
// Note: the new buffer size is a hint and socket implementation
// is free to ignore it, so we don't verify that we get back the
// same value.
@@ -309,7 +307,7 @@ public class UnifiedServerSocketModeDetectionTest extends ZKTestCase {
@Test
public void testGetKeepAlive() throws IOException {
serverSideSocket.getKeepAlive();
- Assert.assertFalse(serverSideSocket.isModeKnown());
+ assertFalse(serverSideSocket.isModeKnown());
}
@Test
@@ -317,20 +315,20 @@ public class UnifiedServerSocketModeDetectionTest extends ZKTestCase {
boolean keepAlive = serverSideSocket.getKeepAlive();
keepAlive = !keepAlive;
serverSideSocket.setKeepAlive(keepAlive);
- Assert.assertFalse(serverSideSocket.isModeKnown());
- Assert.assertEquals(keepAlive, serverSideSocket.getKeepAlive());
+ assertFalse(serverSideSocket.isModeKnown());
+ assertEquals(keepAlive, serverSideSocket.getKeepAlive());
}
@Test
public void testGetTrafficClass() throws IOException {
serverSideSocket.getTrafficClass();
- Assert.assertFalse(serverSideSocket.isModeKnown());
+ assertFalse(serverSideSocket.isModeKnown());
}
@Test
public void testSetTrafficClass() throws IOException {
serverSideSocket.setTrafficClass(SocketOptions.IP_TOS);
- Assert.assertFalse(serverSideSocket.isModeKnown());
+ assertFalse(serverSideSocket.isModeKnown());
// Note: according to the Socket javadocs, setTrafficClass() may be
// ignored by socket implementations, so we don't check that the value
// we set is returned.
@@ -339,7 +337,7 @@ public class UnifiedServerSocketModeDetectionTest extends ZKTestCase {
@Test
public void testGetReuseAddress() throws IOException {
serverSideSocket.getReuseAddress();
- Assert.assertFalse(serverSideSocket.isModeKnown());
+ assertFalse(serverSideSocket.isModeKnown());
}
@Test
@@ -347,59 +345,60 @@ public class UnifiedServerSocketModeDetectionTest extends ZKTestCase {
boolean reuseAddress = serverSideSocket.getReuseAddress();
reuseAddress = !reuseAddress;
serverSideSocket.setReuseAddress(reuseAddress);
- Assert.assertFalse(serverSideSocket.isModeKnown());
- Assert.assertEquals(reuseAddress, serverSideSocket.getReuseAddress());
+ assertFalse(serverSideSocket.isModeKnown());
+ assertEquals(reuseAddress, serverSideSocket.getReuseAddress());
}
@Test
public void testClose() throws IOException {
serverSideSocket.close();
- Assert.assertFalse(serverSideSocket.isModeKnown());
+ assertFalse(serverSideSocket.isModeKnown());
}
@Test
public void testShutdownInput() throws IOException {
serverSideSocket.shutdownInput();
- Assert.assertFalse(serverSideSocket.isModeKnown());
+ assertFalse(serverSideSocket.isModeKnown());
}
@Test
public void testShutdownOutput() throws IOException {
serverSideSocket.shutdownOutput();
- Assert.assertFalse(serverSideSocket.isModeKnown());
+ assertFalse(serverSideSocket.isModeKnown());
}
@Test
public void testIsConnected() {
serverSideSocket.isConnected();
- Assert.assertFalse(serverSideSocket.isModeKnown());
+ assertFalse(serverSideSocket.isModeKnown());
}
@Test
public void testIsBound() {
serverSideSocket.isBound();
- Assert.assertFalse(serverSideSocket.isModeKnown());
+ assertFalse(serverSideSocket.isModeKnown());
}
@Test
public void testIsClosed() {
serverSideSocket.isClosed();
- Assert.assertFalse(serverSideSocket.isModeKnown());
+ assertFalse(serverSideSocket.isModeKnown());
}
@Test
public void testIsInputShutdown() throws IOException {
serverSideSocket.isInputShutdown();
- Assert.assertFalse(serverSideSocket.isModeKnown());
+ assertFalse(serverSideSocket.isModeKnown());
serverSideSocket.shutdownInput();
- Assert.assertTrue(serverSideSocket.isInputShutdown());
+ assertTrue(serverSideSocket.isInputShutdown());
}
@Test
public void testIsOutputShutdown() throws IOException {
serverSideSocket.isOutputShutdown();
- Assert.assertFalse(serverSideSocket.isModeKnown());
+ assertFalse(serverSideSocket.isModeKnown());
serverSideSocket.shutdownOutput();
- Assert.assertTrue(serverSideSocket.isOutputShutdown());
+ assertTrue(serverSideSocket.isOutputShutdown());
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/UnifiedServerSocketTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/UnifiedServerSocketTest.java
index b74fcda98..7e4fa69ad 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/UnifiedServerSocketTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/UnifiedServerSocketTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -15,8 +15,15 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
package org.apache.zookeeper.server.quorum;
+import static org.junit.Assert.assertArrayEquals;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.net.ConnectException;
@@ -32,11 +39,9 @@ import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
-
import javax.net.ssl.HandshakeCompletedEvent;
import javax.net.ssl.HandshakeCompletedListener;
import javax.net.ssl.SSLSocket;
-
import org.apache.zookeeper.PortAssignment;
import org.apache.zookeeper.common.BaseX509ParameterizedTestCase;
import org.apache.zookeeper.common.ClientX509Util;
@@ -46,7 +51,6 @@ import org.apache.zookeeper.common.X509KeyType;
import org.apache.zookeeper.common.X509TestContext;
import org.apache.zookeeper.common.X509Util;
import org.junit.After;
-import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -61,13 +65,8 @@ public class UnifiedServerSocketTest extends BaseX509ParameterizedTestCase {
int paramIndex = 0;
for (X509KeyType caKeyType : X509KeyType.values()) {
for (X509KeyType certKeyType : X509KeyType.values()) {
- for (Boolean hostnameVerification : new Boolean[] { true, false }) {
- result.add(new Object[]{
- caKeyType,
- certKeyType,
- hostnameVerification,
- paramIndex++
- });
+ for (Boolean hostnameVerification : new Boolean[]{true, false}) {
+ result.add(new Object[]{caKeyType, certKeyType, hostnameVerification, paramIndex++});
}
}
}
@@ -86,18 +85,10 @@ public class UnifiedServerSocketTest extends BaseX509ParameterizedTestCase {
private boolean handshakeCompleted = false;
public UnifiedServerSocketTest(
- final X509KeyType caKeyType,
- final X509KeyType certKeyType,
- final Boolean hostnameVerification,
- final Integer paramIndex) {
+ final X509KeyType caKeyType, final X509KeyType certKeyType, final Boolean hostnameVerification, final Integer paramIndex) {
super(paramIndex, () -> {
try {
- return X509TestContext.newBuilder()
- .setTempDir(tempDir)
- .setKeyStoreKeyType(certKeyType)
- .setTrustStoreKeyType(caKeyType)
- .setHostnameVerification(hostnameVerification)
- .build();
+ return X509TestContext.newBuilder().setTempDir(tempDir).setKeyStoreKeyType(certKeyType).setTrustStoreKeyType(caKeyType).setHostnameVerification(hostnameVerification).build();
} catch (Exception e) {
throw new RuntimeException(e);
}
@@ -138,15 +129,13 @@ public class UnifiedServerSocketTest extends BaseX509ParameterizedTestCase {
}
private static final class UnifiedServerThread extends Thread {
+
private final byte[] dataToClient;
private List<byte[]> dataFromClients;
private ExecutorService workerPool;
private UnifiedServerSocket serverSocket;
- UnifiedServerThread(X509Util x509Util,
- InetSocketAddress bindAddress,
- boolean allowInsecureConnection,
- byte[] dataToClient) throws IOException {
+ UnifiedServerThread(X509Util x509Util, InetSocketAddress bindAddress, boolean allowInsecureConnection, byte[] dataToClient) throws IOException {
this.dataToClient = dataToClient;
dataFromClients = new ArrayList<>();
workerPool = Executors.newCachedThreadPool();
@@ -175,9 +164,9 @@ public class UnifiedServerSocketTest extends BaseX509ParameterizedTestCase {
int bytesRead = unifiedSocket.getInputStream().read(buf, 0, 1024);
// Make sure the settings applied above before the socket was potentially upgraded to
// TLS still apply.
- Assert.assertEquals(tcpNoDelay, unifiedSocket.getTcpNoDelay());
- Assert.assertEquals(TIMEOUT, unifiedSocket.getSoTimeout());
- Assert.assertEquals(keepAlive, unifiedSocket.getKeepAlive());
+ assertEquals(tcpNoDelay, unifiedSocket.getTcpNoDelay());
+ assertEquals(TIMEOUT, unifiedSocket.getSoTimeout());
+ assertEquals(keepAlive, unifiedSocket.getKeepAlive());
if (bytesRead > 0) {
byte[] dataFromClient = new byte[bytesRead];
System.arraycopy(buf, 0, dataFromClient, 0, bytesRead);
@@ -216,6 +205,7 @@ public class UnifiedServerSocketTest extends BaseX509ParameterizedTestCase {
synchronized boolean receivedAnyDataFromClient() {
return !dataFromClients.isEmpty();
}
+
}
private SSLSocket connectWithSSL() throws IOException, X509Exception, InterruptedException {
@@ -245,7 +235,7 @@ public class UnifiedServerSocketTest extends BaseX509ParameterizedTestCase {
retries++;
}
- Assert.assertNotNull("Failed to connect to server with SSL", sslSocket);
+ assertNotNull("Failed to connect to server with SSL", sslSocket);
return sslSocket;
}
@@ -266,7 +256,7 @@ public class UnifiedServerSocketTest extends BaseX509ParameterizedTestCase {
}
retries++;
}
- Assert.assertNotNull("Failed to connect to server without SSL", socket);
+ assertNotNull("Failed to connect to server without SSL", socket);
return socket;
}
@@ -280,8 +270,7 @@ public class UnifiedServerSocketTest extends BaseX509ParameterizedTestCase {
*/
@Test
public void testConnectWithSSLToNonStrictServer() throws Exception {
- UnifiedServerThread serverThread = new UnifiedServerThread(
- x509Util, localServerAddress, true, DATA_TO_CLIENT);
+ UnifiedServerThread serverThread = new UnifiedServerThread(x509Util, localServerAddress, true, DATA_TO_CLIENT);
serverThread.start();
Socket sslSocket = connectWithSSL();
@@ -290,16 +279,16 @@ public class UnifiedServerSocketTest extends BaseX509ParameterizedTestCase {
sslSocket.getOutputStream().flush();
byte[] buf = new byte[DATA_TO_CLIENT.length];
int bytesRead = sslSocket.getInputStream().read(buf, 0, buf.length);
- Assert.assertEquals(buf.length, bytesRead);
- Assert.assertArrayEquals(DATA_TO_CLIENT, buf);
+ assertEquals(buf.length, bytesRead);
+ assertArrayEquals(DATA_TO_CLIENT, buf);
synchronized (handshakeCompletedLock) {
if (!handshakeCompleted) {
handshakeCompletedLock.wait(TIMEOUT);
}
- Assert.assertTrue(handshakeCompleted);
+ assertTrue(handshakeCompleted);
}
- Assert.assertArrayEquals(DATA_FROM_CLIENT, serverThread.getDataFromClient(0));
+ assertArrayEquals(DATA_FROM_CLIENT, serverThread.getDataFromClient(0));
} finally {
forceClose(sslSocket);
serverThread.shutdown(TIMEOUT);
@@ -311,8 +300,7 @@ public class UnifiedServerSocketTest extends BaseX509ParameterizedTestCase {
*/
@Test
public void testConnectWithSSLToStrictServer() throws Exception {
- UnifiedServerThread serverThread = new UnifiedServerThread(
- x509Util, localServerAddress, false, DATA_TO_CLIENT);
+ UnifiedServerThread serverThread = new UnifiedServerThread(x509Util, localServerAddress, false, DATA_TO_CLIENT);
serverThread.start();
Socket sslSocket = connectWithSSL();
@@ -321,17 +309,17 @@ public class UnifiedServerSocketTest extends BaseX509ParameterizedTestCase {
sslSocket.getOutputStream().flush();
byte[] buf = new byte[DATA_TO_CLIENT.length];
int bytesRead = sslSocket.getInputStream().read(buf, 0, buf.length);
- Assert.assertEquals(buf.length, bytesRead);
- Assert.assertArrayEquals(DATA_TO_CLIENT, buf);
+ assertEquals(buf.length, bytesRead);
+ assertArrayEquals(DATA_TO_CLIENT, buf);
synchronized (handshakeCompletedLock) {
if (!handshakeCompleted) {
handshakeCompletedLock.wait(TIMEOUT);
}
- Assert.assertTrue(handshakeCompleted);
+ assertTrue(handshakeCompleted);
}
- Assert.assertArrayEquals(DATA_FROM_CLIENT, serverThread.getDataFromClient(0));
+ assertArrayEquals(DATA_FROM_CLIENT, serverThread.getDataFromClient(0));
} finally {
forceClose(sslSocket);
serverThread.shutdown(TIMEOUT);
@@ -343,8 +331,7 @@ public class UnifiedServerSocketTest extends BaseX509ParameterizedTestCase {
*/
@Test
public void testConnectWithoutSSLToNonStrictServer() throws Exception {
- UnifiedServerThread serverThread = new UnifiedServerThread(
- x509Util, localServerAddress, true, DATA_TO_CLIENT);
+ UnifiedServerThread serverThread = new UnifiedServerThread(x509Util, localServerAddress, true, DATA_TO_CLIENT);
serverThread.start();
Socket socket = connectWithoutSSL();
@@ -353,9 +340,9 @@ public class UnifiedServerSocketTest extends BaseX509ParameterizedTestCase {
socket.getOutputStream().flush();
byte[] buf = new byte[DATA_TO_CLIENT.length];
int bytesRead = socket.getInputStream().read(buf, 0, buf.length);
- Assert.assertEquals(buf.length, bytesRead);
- Assert.assertArrayEquals(DATA_TO_CLIENT, buf);
- Assert.assertArrayEquals(DATA_FROM_CLIENT, serverThread.getDataFromClient(0));
+ assertEquals(buf.length, bytesRead);
+ assertArrayEquals(DATA_TO_CLIENT, buf);
+ assertArrayEquals(DATA_FROM_CLIENT, serverThread.getDataFromClient(0));
} finally {
forceClose(socket);
serverThread.shutdown(TIMEOUT);
@@ -370,8 +357,7 @@ public class UnifiedServerSocketTest extends BaseX509ParameterizedTestCase {
*/
@Test
public void testConnectWithoutSSLToNonStrictServerPartialWrite() throws Exception {
- UnifiedServerThread serverThread = new UnifiedServerThread(
- x509Util, localServerAddress, true, DATA_TO_CLIENT);
+ UnifiedServerThread serverThread = new UnifiedServerThread(x509Util, localServerAddress, true, DATA_TO_CLIENT);
serverThread.start();
Socket socket = connectWithoutSSL();
@@ -386,9 +372,9 @@ public class UnifiedServerSocketTest extends BaseX509ParameterizedTestCase {
socket.getOutputStream().flush();
byte[] buf = new byte[DATA_TO_CLIENT.length];
int bytesRead = socket.getInputStream().read(buf, 0, buf.length);
- Assert.assertEquals(buf.length, bytesRead);
- Assert.assertArrayEquals(DATA_TO_CLIENT, buf);
- Assert.assertArrayEquals(DATA_FROM_CLIENT, serverThread.getDataFromClient(0));
+ assertEquals(buf.length, bytesRead);
+ assertArrayEquals(DATA_TO_CLIENT, buf);
+ assertArrayEquals(DATA_FROM_CLIENT, serverThread.getDataFromClient(0));
} finally {
forceClose(socket);
serverThread.shutdown(TIMEOUT);
@@ -400,8 +386,7 @@ public class UnifiedServerSocketTest extends BaseX509ParameterizedTestCase {
*/
@Test
public void testConnectWithoutSSLToStrictServer() throws Exception {
- UnifiedServerThread serverThread = new UnifiedServerThread(
- x509Util, localServerAddress, false, DATA_TO_CLIENT);
+ UnifiedServerThread serverThread = new UnifiedServerThread(x509Util, localServerAddress, false, DATA_TO_CLIENT);
serverThread.start();
Socket socket = connectWithoutSSL();
@@ -410,7 +395,7 @@ public class UnifiedServerSocketTest extends BaseX509ParameterizedTestCase {
byte[] buf = new byte[DATA_TO_CLIENT.length];
try {
int bytesRead = socket.getInputStream().read(buf, 0, buf.length);
- if(bytesRead == -1) {
+ if (bytesRead == -1) {
// Using the NioSocketImpl after JDK 13, the expected behaviour on the client side
// is to reach the end of the stream (bytesRead == -1), without a socket exception.
return;
@@ -424,10 +409,9 @@ public class UnifiedServerSocketTest extends BaseX509ParameterizedTestCase {
// independently of the client socket implementation details, we always make sure the
// server didn't receive any data during the test
- Assert.assertFalse("The strict server accepted connection without SSL.",
- serverThread.receivedAnyDataFromClient());
+ assertFalse("The strict server accepted connection without SSL.", serverThread.receivedAnyDataFromClient());
}
- Assert.fail("Expected server to hang up the connection. Read from server succeeded unexpectedly.");
+ fail("Expected server to hang up the connection. Read from server succeeded unexpectedly.");
}
/**
@@ -446,8 +430,7 @@ public class UnifiedServerSocketTest extends BaseX509ParameterizedTestCase {
Socket badClientSocket = null;
Socket clientSocket = null;
Socket secureClientSocket = null;
- UnifiedServerThread serverThread = new UnifiedServerThread(
- x509Util, localServerAddress, true, DATA_TO_CLIENT);
+ UnifiedServerThread serverThread = new UnifiedServerThread(x509Util, localServerAddress, true, DATA_TO_CLIENT);
serverThread.start();
try {
@@ -458,12 +441,12 @@ public class UnifiedServerSocketTest extends BaseX509ParameterizedTestCase {
clientSocket.getOutputStream().flush();
byte[] buf = new byte[DATA_TO_CLIENT.length];
int bytesRead = clientSocket.getInputStream().read(buf, 0, buf.length);
- Assert.assertEquals(buf.length, bytesRead);
- Assert.assertArrayEquals(DATA_TO_CLIENT, buf);
- Assert.assertArrayEquals(DATA_FROM_CLIENT, serverThread.getDataFromClient(0));
+ assertEquals(buf.length, bytesRead);
+ assertArrayEquals(DATA_TO_CLIENT, buf);
+ assertArrayEquals(DATA_FROM_CLIENT, serverThread.getDataFromClient(0));
synchronized (handshakeCompletedLock) {
- Assert.assertFalse(handshakeCompleted);
+ assertFalse(handshakeCompleted);
}
secureClientSocket = connectWithSSL();
@@ -471,15 +454,15 @@ public class UnifiedServerSocketTest extends BaseX509ParameterizedTestCase {
secureClientSocket.getOutputStream().flush();
buf = new byte[DATA_TO_CLIENT.length];
bytesRead = secureClientSocket.getInputStream().read(buf, 0, buf.length);
- Assert.assertEquals(buf.length, bytesRead);
- Assert.assertArrayEquals(DATA_TO_CLIENT, buf);
- Assert.assertArrayEquals(DATA_FROM_CLIENT, serverThread.getDataFromClient(1));
+ assertEquals(buf.length, bytesRead);
+ assertArrayEquals(DATA_TO_CLIENT, buf);
+ assertArrayEquals(DATA_FROM_CLIENT, serverThread.getDataFromClient(1));
synchronized (handshakeCompletedLock) {
if (!handshakeCompleted) {
handshakeCompletedLock.wait(TIMEOUT);
}
- Assert.assertTrue(handshakeCompleted);
+ assertTrue(handshakeCompleted);
}
} finally {
forceClose(badClientSocket);
@@ -497,8 +480,7 @@ public class UnifiedServerSocketTest extends BaseX509ParameterizedTestCase {
public void testTLSDetectionNonBlockingStrictServerIdleClient() throws Exception {
Socket badClientSocket = null;
Socket secureClientSocket = null;
- UnifiedServerThread serverThread = new UnifiedServerThread(
- x509Util, localServerAddress, false, DATA_TO_CLIENT);
+ UnifiedServerThread serverThread = new UnifiedServerThread(x509Util, localServerAddress, false, DATA_TO_CLIENT);
serverThread.start();
try {
@@ -509,16 +491,16 @@ public class UnifiedServerSocketTest extends BaseX509ParameterizedTestCase {
secureClientSocket.getOutputStream().flush();
byte[] buf = new byte[DATA_TO_CLIENT.length];
int bytesRead = secureClientSocket.getInputStream().read(buf, 0, buf.length);
- Assert.assertEquals(buf.length, bytesRead);
- Assert.assertArrayEquals(DATA_TO_CLIENT, buf);
+ assertEquals(buf.length, bytesRead);
+ assertArrayEquals(DATA_TO_CLIENT, buf);
synchronized (handshakeCompletedLock) {
if (!handshakeCompleted) {
handshakeCompletedLock.wait(TIMEOUT);
}
- Assert.assertTrue(handshakeCompleted);
+ assertTrue(handshakeCompleted);
}
- Assert.assertArrayEquals(DATA_FROM_CLIENT, serverThread.getDataFromClient(0));
+ assertArrayEquals(DATA_FROM_CLIENT, serverThread.getDataFromClient(0));
} finally {
forceClose(badClientSocket);
forceClose(secureClientSocket);
@@ -534,8 +516,7 @@ public class UnifiedServerSocketTest extends BaseX509ParameterizedTestCase {
public void testTLSDetectionNonBlockingNonStrictServerDisconnectedClient() throws Exception {
Socket clientSocket = null;
Socket secureClientSocket = null;
- UnifiedServerThread serverThread = new UnifiedServerThread(
- x509Util, localServerAddress, true, DATA_TO_CLIENT);
+ UnifiedServerThread serverThread = new UnifiedServerThread(x509Util, localServerAddress, true, DATA_TO_CLIENT);
serverThread.start();
try {
@@ -547,12 +528,12 @@ public class UnifiedServerSocketTest extends BaseX509ParameterizedTestCase {
clientSocket.getOutputStream().flush();
byte[] buf = new byte[DATA_TO_CLIENT.length];
int bytesRead = clientSocket.getInputStream().read(buf, 0, buf.length);
- Assert.assertEquals(buf.length, bytesRead);
- Assert.assertArrayEquals(DATA_TO_CLIENT, buf);
- Assert.assertArrayEquals(DATA_FROM_CLIENT, serverThread.getDataFromClient(0));
+ assertEquals(buf.length, bytesRead);
+ assertArrayEquals(DATA_TO_CLIENT, buf);
+ assertArrayEquals(DATA_FROM_CLIENT, serverThread.getDataFromClient(0));
synchronized (handshakeCompletedLock) {
- Assert.assertFalse(handshakeCompleted);
+ assertFalse(handshakeCompleted);
}
secureClientSocket = connectWithSSL();
@@ -560,15 +541,15 @@ public class UnifiedServerSocketTest extends BaseX509ParameterizedTestCase {
secureClientSocket.getOutputStream().flush();
buf = new byte[DATA_TO_CLIENT.length];
bytesRead = secureClientSocket.getInputStream().read(buf, 0, buf.length);
- Assert.assertEquals(buf.length, bytesRead);
- Assert.assertArrayEquals(DATA_TO_CLIENT, buf);
- Assert.assertArrayEquals(DATA_FROM_CLIENT, serverThread.getDataFromClient(1));
+ assertEquals(buf.length, bytesRead);
+ assertArrayEquals(DATA_TO_CLIENT, buf);
+ assertArrayEquals(DATA_FROM_CLIENT, serverThread.getDataFromClient(1));
synchronized (handshakeCompletedLock) {
if (!handshakeCompleted) {
handshakeCompletedLock.wait(TIMEOUT);
}
- Assert.assertTrue(handshakeCompleted);
+ assertTrue(handshakeCompleted);
}
} finally {
forceClose(clientSocket);
@@ -584,8 +565,7 @@ public class UnifiedServerSocketTest extends BaseX509ParameterizedTestCase {
@Test
public void testTLSDetectionNonBlockingStrictServerDisconnectedClient() throws Exception {
Socket secureClientSocket = null;
- UnifiedServerThread serverThread = new UnifiedServerThread(
- x509Util, localServerAddress, false, DATA_TO_CLIENT);
+ UnifiedServerThread serverThread = new UnifiedServerThread(x509Util, localServerAddress, false, DATA_TO_CLIENT);
serverThread.start();
try {
@@ -597,19 +577,20 @@ public class UnifiedServerSocketTest extends BaseX509ParameterizedTestCase {
secureClientSocket.getOutputStream().flush();
byte[] buf = new byte[DATA_TO_CLIENT.length];
int bytesRead = secureClientSocket.getInputStream().read(buf, 0, buf.length);
- Assert.assertEquals(buf.length, bytesRead);
- Assert.assertArrayEquals(DATA_TO_CLIENT, buf);
+ assertEquals(buf.length, bytesRead);
+ assertArrayEquals(DATA_TO_CLIENT, buf);
synchronized (handshakeCompletedLock) {
if (!handshakeCompleted) {
handshakeCompletedLock.wait(TIMEOUT);
}
- Assert.assertTrue(handshakeCompleted);
+ assertTrue(handshakeCompleted);
}
- Assert.assertArrayEquals(DATA_FROM_CLIENT, serverThread.getDataFromClient(0));
+ assertArrayEquals(DATA_FROM_CLIENT, serverThread.getDataFromClient(0));
} finally {
forceClose(secureClientSocket);
serverThread.shutdown(TIMEOUT);
}
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/WatchLeakTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/WatchLeakTest.java
index 4eebcf343..cdc3b8304 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/WatchLeakTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/WatchLeakTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with this
* work for additional information regarding copyright ownership. The ASF
@@ -17,15 +17,10 @@
package org.apache.zookeeper.server.quorum;
+import static org.junit.Assert.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
-import static org.junit.Assert.*;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.List;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
@@ -40,29 +35,32 @@ import java.nio.channels.SelectableChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
import java.util.Collections;
+import java.util.List;
import java.util.Random;
-import org.junit.runner.RunWith;
-import org.junit.runners.Parameterized;
-import org.junit.runners.Parameterized.Parameters;
-
import org.apache.jute.InputArchive;
import org.apache.jute.OutputArchive;
import org.apache.zookeeper.MockPacket;
+import org.apache.zookeeper.ZKParameterized;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.proto.ConnectRequest;
import org.apache.zookeeper.proto.ReplyHeader;
import org.apache.zookeeper.proto.RequestHeader;
import org.apache.zookeeper.proto.SetWatches;
import org.apache.zookeeper.server.MockNIOServerCnxn;
+import org.apache.zookeeper.server.MockSelectorThread;
import org.apache.zookeeper.server.NIOServerCnxn;
import org.apache.zookeeper.server.NIOServerCnxnFactory;
-import org.apache.zookeeper.server.MockSelectorThread;
import org.apache.zookeeper.server.ZKDatabase;
import org.apache.zookeeper.server.persistence.FileTxnSnapLog;
-import org.apache.zookeeper.ZKParameterized;
import org.junit.Before;
import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
+import org.junit.runners.Parameterized.Parameters;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.slf4j.Logger;
@@ -75,8 +73,7 @@ import org.slf4j.LoggerFactory;
@Parameterized.UseParametersRunnerFactory(ZKParameterized.RunnerFactory.class)
public class WatchLeakTest {
- protected static final Logger LOG = LoggerFactory
- .getLogger(WatchLeakTest.class);
+ protected static final Logger LOG = LoggerFactory.getLogger(WatchLeakTest.class);
final long SESSION_ID = 0xBABEL;
@@ -93,9 +90,7 @@ public class WatchLeakTest {
@Parameters
public static Collection<Object[]> configs() {
- return Arrays.asList(new Object[][] {
- { false }, { true },
- });
+ return Arrays.asList(new Object[][]{{false}, {true}});
}
/**
@@ -111,8 +106,8 @@ public class WatchLeakTest {
when(selectorThread.addInterestOpsUpdateRequest(any(SelectionKey.class))).thenAnswer(new Answer<Boolean>() {
@Override
public Boolean answer(InvocationOnMock invocation) throws Throwable {
- SelectionKey sk = (SelectionKey)invocation.getArguments()[0];
- NIOServerCnxn nioSrvCnx = (NIOServerCnxn)sk.attachment();
+ SelectionKey sk = (SelectionKey) invocation.getArguments()[0];
+ NIOServerCnxn nioSrvCnx = (NIOServerCnxn) sk.attachment();
sk.interestOps(nioSrvCnx.getInterestOps());
return true;
}
@@ -137,8 +132,7 @@ public class WatchLeakTest {
// Simulate a socket channel between a client and a follower
final SocketChannel socketChannel = createClientSocketChannel();
// Create the NIOServerCnxn that will handle the client requests
- final MockNIOServerCnxn nioCnxn = new MockNIOServerCnxn(fzks,
- socketChannel, sk, serverCnxnFactory, selectorThread);
+ final MockNIOServerCnxn nioCnxn = new MockNIOServerCnxn(fzks, socketChannel, sk, serverCnxnFactory, selectorThread);
sk.attach(nioCnxn);
// Send the connection request as a client do
nioCnxn.doIO(sk);
@@ -175,6 +169,7 @@ public class WatchLeakTest {
* A follower with no real leader connection
*/
public static class MyFollower extends Follower {
+
/**
* Create a follower with a mocked leader connection
*
@@ -187,6 +182,7 @@ public class WatchLeakTest {
leaderIs = mock(InputArchive.class);
bufferedOutput = mock(BufferedOutputStream.class);
}
+
}
/**
@@ -252,8 +248,7 @@ public class WatchLeakTest {
dataWatches.add("/");
List<String> existWatches = Collections.emptyList();
List<String> childWatches = Collections.emptyList();
- SetWatches sw = new SetWatches(1L, dataWatches, existWatches,
- childWatches);
+ SetWatches sw = new SetWatches(1L, dataWatches, existWatches, childWatches);
RequestHeader h = new RequestHeader();
h.setType(ZooDefs.OpCode.setWatches);
h.setXid(-8);
@@ -265,7 +260,7 @@ public class WatchLeakTest {
* This is the secret that we use to generate passwords, for the moment it
* is more of a sanity check.
*/
- static final private long superSecret = 0XB3415C00L;
+ private static final long superSecret = 0XB3415C00L;
/**
* Create a connection request
@@ -274,7 +269,7 @@ public class WatchLeakTest {
*/
private ByteBuffer createConnRequest() {
Random r = new Random(SESSION_ID ^ superSecret);
- byte p[] = new byte[16];
+ byte[] p = new byte[16];
r.nextBytes(p);
ConnectRequest conReq = new ConnectRequest(0, 1L, 30000, SESSION_ID, p);
MockPacket packet = new MockPacket(null, null, conReq, null, null, false);
@@ -299,8 +294,7 @@ public class WatchLeakTest {
// Send watches packet to server connection
final ByteBuffer connRequest = createConnRequest();
final ByteBuffer watchesMessage = createWatchesMessage();
- final ByteBuffer request = ByteBuffer.allocate(connRequest.limit()
- + watchesMessage.limit());
+ final ByteBuffer request = ByteBuffer.allocate(connRequest.limit() + watchesMessage.limit());
request.put(connRequest);
request.put(watchesMessage);
@@ -355,8 +349,7 @@ public class WatchLeakTest {
dos.writeLong(SESSION_ID);
dos.writeInt(3000);
dos.close();
- QuorumPacket qp = new QuorumPacket(Leader.REVALIDATE, -1,
- baos.toByteArray(), null);
+ QuorumPacket qp = new QuorumPacket(Leader.REVALIDATE, -1, baos.toByteArray(), null);
return qp;
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/Zab1_0Test.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/Zab1_0Test.java
index 1aa0d24f5..037f81f26 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/Zab1_0Test.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/Zab1_0Test.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,30 +18,30 @@
package org.apache.zookeeper.server.quorum;
-import static org.apache.zookeeper.server.quorum.ZabUtils.createQuorumPeer;
-import static org.apache.zookeeper.server.quorum.ZabUtils.createMockLeader;
import static org.apache.zookeeper.server.quorum.ZabUtils.MockLeader;
import static org.apache.zookeeper.server.quorum.ZabUtils.createLeader;
-
+import static org.apache.zookeeper.server.quorum.ZabUtils.createMockLeader;
+import static org.apache.zookeeper.server.quorum.ZabUtils.createQuorumPeer;
import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
-
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
+import java.io.EOFException;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
-import java.io.EOFException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.util.concurrent.ConcurrentHashMap;
-
import org.apache.jute.BinaryInputArchive;
import org.apache.jute.BinaryOutputArchive;
import org.apache.jute.InputArchive;
@@ -49,6 +49,7 @@ import org.apache.jute.OutputArchive;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.Watcher.Event.EventType;
+import org.apache.zookeeper.ZKTestCase;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.data.Stat;
import org.apache.zookeeper.server.ByteBufferInputStream;
@@ -58,7 +59,6 @@ import org.apache.zookeeper.server.Request;
import org.apache.zookeeper.server.ZKDatabase;
import org.apache.zookeeper.server.persistence.FileTxnSnapLog;
import org.apache.zookeeper.server.quorum.QuorumPeer.QuorumServer;
-
import org.apache.zookeeper.server.util.ZxidUtils;
import org.apache.zookeeper.test.TestUtils;
import org.apache.zookeeper.txn.CreateSessionTxn;
@@ -66,8 +66,6 @@ import org.apache.zookeeper.txn.CreateTxn;
import org.apache.zookeeper.txn.ErrorTxn;
import org.apache.zookeeper.txn.SetDataTxn;
import org.apache.zookeeper.txn.TxnHeader;
-import org.apache.zookeeper.ZKTestCase;
-import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
@@ -77,8 +75,7 @@ public class Zab1_0Test extends ZKTestCase {
private static final Logger LOG = LoggerFactory.getLogger(Zab1_0Test.class);
- private static final File testData = new File(
- System.getProperty("test.data.dir", "src/test/resources/data"));
+ private static final File testData = new File(System.getProperty("test.data.dir", "src/test/resources/data"));
@Before
public void setUp() {
@@ -86,6 +83,7 @@ public class Zab1_0Test extends ZKTestCase {
}
private static final class LeadThread extends Thread {
+
private final Leader leader;
private LeadThread(Leader leader) {
@@ -103,16 +101,18 @@ public class Zab1_0Test extends ZKTestCase {
leader.shutdown("lead ended");
}
}
+
}
-
- public static final class FollowerMockThread extends Thread {
- private final Leader leader;
- private final long followerSid;
- public long epoch = -1;
- public String msg = null;
- private boolean onlyGetEpochToPropose;
-
- private FollowerMockThread(long followerSid, Leader leader, boolean onlyGetEpochToPropose) {
+
+ public static final class FollowerMockThread extends Thread {
+
+ private final Leader leader;
+ private final long followerSid;
+ public long epoch = -1;
+ public String msg = null;
+ private boolean onlyGetEpochToPropose;
+
+ private FollowerMockThread(long followerSid, Leader leader, boolean onlyGetEpochToPropose) {
this.leader = leader;
this.followerSid = followerSid;
this.onlyGetEpochToPropose = onlyGetEpochToPropose;
@@ -120,21 +120,22 @@ public class Zab1_0Test extends ZKTestCase {
public void run() {
if (onlyGetEpochToPropose) {
- try {
- epoch = leader.getEpochToPropose(followerSid, 0);
- } catch (Exception e) {
- }
- } else {
- try{
- leader.waitForEpochAck(followerSid, new StateSummary(0, 0));
- msg = "FollowerMockThread (id = " + followerSid + ") returned from waitForEpochAck";
- } catch (Exception e) {
- }
+ try {
+ epoch = leader.getEpochToPropose(followerSid, 0);
+ } catch (Exception e) {
+ }
+ } else {
+ try {
+ leader.waitForEpochAck(followerSid, new StateSummary(0, 0));
+ msg = "FollowerMockThread (id = " + followerSid + ") returned from waitForEpochAck";
+ } catch (Exception e) {
+ }
}
- }
+ }
+
}
@Test
- public void testLeaderInConnectingFollowers() throws Exception {
+ public void testLeaderInConnectingFollowers() throws Exception {
File tmpDir = File.createTempFile("test", "dir", testData);
tmpDir.delete();
tmpDir.mkdir();
@@ -144,26 +145,26 @@ public class Zab1_0Test extends ZKTestCase {
leader = createLeader(tmpDir, peer);
peer.leader = leader;
peer.setAcceptedEpoch(5);
-
+
FollowerMockThread f1 = new FollowerMockThread(1, leader, true);
FollowerMockThread f2 = new FollowerMockThread(2, leader, true);
f1.start();
f2.start();
-
+
// wait until followers time out in getEpochToPropose - they shouldn't return
// normally because the leader didn't execute getEpochToPropose and so its epoch was not
// accounted for
- f1.join(leader.self.getInitLimit()*leader.self.getTickTime() + 5000);
- f2.join(leader.self.getInitLimit()*leader.self.getTickTime() + 5000);
-
+ f1.join(leader.self.getInitLimit() * leader.self.getTickTime() + 5000);
+ f2.join(leader.self.getInitLimit() * leader.self.getTickTime() + 5000);
+
// even though followers timed out, their ids are in connectingFollowers, and their
- // epoch were accounted for, so the leader should not block and since it started with
+ // epoch were accounted for, so the leader should not block and since it started with
// accepted epoch = 5 it should now have 6
try {
- long epoch = leader.getEpochToPropose(leader.self.getId(), leader.self.getAcceptedEpoch());
- Assert.assertEquals("leader got wrong epoch from getEpochToPropose", 6, epoch);
- } catch (Exception e){
- Assert.fail("leader timed out in getEpochToPropose");
+ long epoch = leader.getEpochToPropose(leader.self.getId(), leader.self.getAcceptedEpoch());
+ assertEquals("leader got wrong epoch from getEpochToPropose", 6, epoch);
+ } catch (Exception e) {
+ fail("leader timed out in getEpochToPropose");
}
} finally {
if (leader != null) {
@@ -172,23 +173,23 @@ public class Zab1_0Test extends ZKTestCase {
TestUtils.deleteFileRecursively(tmpDir);
}
}
-
+
/**
* In this test, the leader sets the last accepted epoch to 5. The call
- * to getEpochToPropose should set epoch to 6 and wait until another
+ * to getEpochToPropose should set epoch to 6 and wait until another
* follower executes it. If in getEpochToPropose we don't check if
* lastAcceptedEpoch == epoch, then the call from the subsequent
* follower with lastAcceptedEpoch = 6 doesn't change the value
* of epoch, and the test fails. It passes with the fix to predicate.
- *
+ *
* https://issues.apache.org/jira/browse/ZOOKEEPER-1343
- *
- *
+ *
+ *
* @throws Exception
*/
-
+
@Test
- public void testLastAcceptedEpoch() throws Exception {
+ public void testLastAcceptedEpoch() throws Exception {
File tmpDir = File.createTempFile("test", "dir", testData);
tmpDir.delete();
tmpDir.mkdir();
@@ -199,20 +200,20 @@ public class Zab1_0Test extends ZKTestCase {
leader = createMockLeader(tmpDir, peer);
peer.leader = leader;
peer.setAcceptedEpoch(5);
- leadThread = new LeadThread(leader);
+ leadThread = new LeadThread(leader);
leadThread.start();
-
- while(((MockLeader) leader).getCurrentEpochToPropose() != 6){
+
+ while (((MockLeader) leader).getCurrentEpochToPropose() != 6) {
Thread.sleep(20);
}
-
+
try {
long epoch = leader.getEpochToPropose(1, 6);
- Assert.assertEquals("New proposed epoch is wrong", 7, epoch);
- } catch (Exception e){
- Assert.fail("Timed out in getEpochToPropose");
+ assertEquals("New proposed epoch is wrong", 7, epoch);
+ } catch (Exception e) {
+ fail("Timed out in getEpochToPropose");
}
-
+
} finally {
if (leader != null) {
leader.shutdown("end of test");
@@ -224,10 +225,9 @@ public class Zab1_0Test extends ZKTestCase {
TestUtils.deleteFileRecursively(tmpDir);
}
}
-
-
+
@Test
- public void testLeaderInElectingFollowers() throws Exception {
+ public void testLeaderInElectingFollowers() throws Exception {
File tmpDir = File.createTempFile("test", "dir", testData);
tmpDir.delete();
tmpDir.mkdir();
@@ -235,25 +235,25 @@ public class Zab1_0Test extends ZKTestCase {
try {
QuorumPeer peer = createQuorumPeer(tmpDir);
leader = createLeader(tmpDir, peer);
- peer.leader = leader;
-
+ peer.leader = leader;
+
FollowerMockThread f1 = new FollowerMockThread(1, leader, false);
FollowerMockThread f2 = new FollowerMockThread(2, leader, false);
// things needed for waitForEpochAck to run (usually in leader.lead(), but we're not running leader here)
leader.leaderStateSummary = new StateSummary(leader.self.getCurrentEpoch(), leader.zk.getLastProcessedZxid());
-
+
f1.start();
- f2.start();
-
+ f2.start();
+
// wait until followers time out in waitForEpochAck - they shouldn't return
// normally because the leader didn't execute waitForEpochAck
- f1.join(leader.self.getInitLimit()*leader.self.getTickTime() + 5000);
- f2.join(leader.self.getInitLimit()*leader.self.getTickTime() + 5000);
-
- // make sure that they timed out and didn't return normally
- Assert.assertTrue(f1.msg + " without waiting for leader", f1.msg == null);
- Assert.assertTrue(f2.msg + " without waiting for leader", f2.msg == null);
+ f1.join(leader.self.getInitLimit() * leader.self.getTickTime() + 5000);
+ f2.join(leader.self.getInitLimit() * leader.self.getTickTime() + 5000);
+
+ // make sure that they timed out and didn't return normally
+ assertTrue(f1.msg + " without waiting for leader", f1.msg == null);
+ assertTrue(f2.msg + " without waiting for leader", f2.msg == null);
} finally {
if (leader != null) {
leader.shutdown("end of test");
@@ -263,39 +263,46 @@ public class Zab1_0Test extends ZKTestCase {
}
static Socket[] getSocketPair() throws IOException {
- ServerSocket ss =
- new ServerSocket(0, 50, InetAddress.getByName("127.0.0.1"));
+ ServerSocket ss = new ServerSocket(0, 50, InetAddress.getByName("127.0.0.1"));
InetSocketAddress endPoint = (InetSocketAddress) ss.getLocalSocketAddress();
Socket s = new Socket(endPoint.getAddress(), endPoint.getPort());
- return new Socket[] { s, ss.accept() };
+ return new Socket[]{s, ss.accept()};
}
static void readPacketSkippingPing(InputArchive ia, QuorumPacket qp) throws IOException {
- while(true) {
+ while (true) {
ia.readRecord(qp, null);
if (qp.getType() != Leader.PING) {
return;
}
}
}
-
- static public interface LeaderConversation {
+
+ public interface LeaderConversation {
+
void converseWithLeader(InputArchive ia, OutputArchive oa, Leader l) throws Exception;
+
}
-
- static public interface PopulatedLeaderConversation {
+
+ public interface PopulatedLeaderConversation {
+
void converseWithLeader(InputArchive ia, OutputArchive oa, Leader l, long zxid) throws Exception;
+
}
-
- static public interface FollowerConversation {
+
+ public interface FollowerConversation {
+
void converseWithFollower(InputArchive ia, OutputArchive oa, Follower f) throws Exception;
+
}
-
- static public interface ObserverConversation {
+
+ public interface ObserverConversation {
+
void converseWithObserver(InputArchive ia, OutputArchive oa, Observer o) throws Exception;
+
}
public void testLeaderConversation(LeaderConversation conversation) throws Exception {
- Socket pair[] = getSocketPair();
+ Socket[] pair = getSocketPair();
Socket leaderSocket = pair[0];
Socket followerSocket = pair[1];
File tmpDir = File.createTempFile("test", "dir", testData);
@@ -310,20 +317,16 @@ public class Zab1_0Test extends ZKTestCase {
leadThread = new LeadThread(leader);
leadThread.start();
- while(leader.cnxAcceptor == null || !leader.cnxAcceptor.isAlive()) {
+ while (leader.cnxAcceptor == null || !leader.cnxAcceptor.isAlive()) {
Thread.sleep(20);
}
-
- LearnerHandler lh = new LearnerHandler(leaderSocket,
- new BufferedInputStream(leaderSocket.getInputStream()),
- leader);
+
+ LearnerHandler lh = new LearnerHandler(leaderSocket, new BufferedInputStream(leaderSocket.getInputStream()), leader);
lh.start();
leaderSocket.setSoTimeout(4000);
- InputArchive ia = BinaryInputArchive.getArchive(followerSocket
- .getInputStream());
- OutputArchive oa = BinaryOutputArchive.getArchive(followerSocket
- .getOutputStream());
+ InputArchive ia = BinaryInputArchive.getArchive(followerSocket.getInputStream());
+ OutputArchive oa = BinaryOutputArchive.getArchive(followerSocket.getOutputStream());
conversation.converseWithLeader(ia, oa, leader);
} finally {
@@ -337,9 +340,9 @@ public class Zab1_0Test extends ZKTestCase {
TestUtils.deleteFileRecursively(tmpDir);
}
}
-
+
public void testPopulatedLeaderConversation(PopulatedLeaderConversation conversation, int ops) throws Exception {
- Socket pair[] = getSocketPair();
+ Socket[] pair = getSocketPair();
Socket leaderSocket = pair[0];
Socket followerSocket = pair[1];
File tmpDir = File.createTempFile("test", "dir", testData);
@@ -347,54 +350,49 @@ public class Zab1_0Test extends ZKTestCase {
tmpDir.mkdir();
LeadThread leadThread = null;
Leader leader = null;
- try {
+ try {
// Setup a database with two znodes
FileTxnSnapLog snapLog = new FileTxnSnapLog(tmpDir, tmpDir);
ZKDatabase zkDb = new ZKDatabase(snapLog);
-
- Assert.assertTrue(ops >= 1);
- long zxid = ZxidUtils.makeZxid(1, 0);
- for(int i = 1; i <= ops; i++){
+
+ assertTrue(ops >= 1);
+ long zxid = ZxidUtils.makeZxid(1, 0);
+ for (int i = 1; i <= ops; i++) {
zxid = ZxidUtils.makeZxid(1, i);
- String path = "/foo-"+ i;
- zkDb.processTxn(new TxnHeader(13,1000+i,zxid,30+i,ZooDefs.OpCode.create),
- new CreateTxn(path, "fpjwasalsohere".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, false, 1));
+ String path = "/foo-" + i;
+ zkDb.processTxn(new TxnHeader(13, 1000 + i, zxid, 30
+ + i, ZooDefs.OpCode.create), new CreateTxn(path, "fpjwasalsohere".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, false, 1));
Stat stat = new Stat();
- Assert.assertEquals("fpjwasalsohere", new String(zkDb.getData(path, stat, null)));
- }
- Assert.assertTrue(zxid > ZxidUtils.makeZxid(1, 0));
-
+ assertEquals("fpjwasalsohere", new String(zkDb.getData(path, stat, null)));
+ }
+ assertTrue(zxid > ZxidUtils.makeZxid(1, 0));
+
// Generate snapshot and close files.
snapLog.save(zkDb.getDataTree(), zkDb.getSessionWithTimeOuts(), false);
snapLog.close();
-
+
QuorumPeer peer = createQuorumPeer(tmpDir);
-
+
leader = createLeader(tmpDir, peer);
peer.leader = leader;
-
+
// Set the last accepted epoch and current epochs to be 1
peer.setAcceptedEpoch(1);
peer.setCurrentEpoch(1);
-
leadThread = new LeadThread(leader);
leadThread.start();
- while(leader.cnxAcceptor == null || !leader.cnxAcceptor.isAlive()) {
+ while (leader.cnxAcceptor == null || !leader.cnxAcceptor.isAlive()) {
Thread.sleep(20);
}
- LearnerHandler lh = new LearnerHandler(leaderSocket,
- new BufferedInputStream(leaderSocket.getInputStream()),
- leader);
+ LearnerHandler lh = new LearnerHandler(leaderSocket, new BufferedInputStream(leaderSocket.getInputStream()), leader);
lh.start();
leaderSocket.setSoTimeout(4000);
- InputArchive ia = BinaryInputArchive.getArchive(followerSocket
- .getInputStream());
- OutputArchive oa = BinaryOutputArchive.getArchive(followerSocket
- .getOutputStream());
+ InputArchive ia = BinaryInputArchive.getArchive(followerSocket.getInputStream());
+ OutputArchive oa = BinaryOutputArchive.getArchive(followerSocket.getOutputStream());
conversation.converseWithLeader(ia, oa, leader, zxid);
} finally {
@@ -408,7 +406,7 @@ public class Zab1_0Test extends ZKTestCase {
TestUtils.deleteFileRecursively(tmpDir);
}
}
-
+
public void testFollowerConversation(FollowerConversation conversation) throws Exception {
File tmpDir = File.createTempFile("test", "dir", testData);
tmpDir.delete();
@@ -420,14 +418,12 @@ public class Zab1_0Test extends ZKTestCase {
peer = createQuorumPeer(tmpDir);
follower = createFollower(tmpDir, peer);
peer.follower = follower;
-
- ServerSocket ss =
- new ServerSocket(0, 50, InetAddress.getByName("127.0.0.1"));
- QuorumServer leaderQS = new QuorumServer(1,
- (InetSocketAddress) ss.getLocalSocketAddress());
+
+ ServerSocket ss = new ServerSocket(0, 50, InetAddress.getByName("127.0.0.1"));
+ QuorumServer leaderQS = new QuorumServer(1, (InetSocketAddress) ss.getLocalSocketAddress());
follower.setLeaderQuorumServer(leaderQS);
final Follower followerForThread = follower;
-
+
followerThread = new Thread() {
public void run() {
try {
@@ -441,11 +437,9 @@ public class Zab1_0Test extends ZKTestCase {
};
followerThread.start();
Socket leaderSocket = ss.accept();
-
- InputArchive ia = BinaryInputArchive.getArchive(leaderSocket
- .getInputStream());
- OutputArchive oa = BinaryOutputArchive.getArchive(leaderSocket
- .getOutputStream());
+
+ InputArchive ia = BinaryInputArchive.getArchive(leaderSocket.getInputStream());
+ OutputArchive oa = BinaryOutputArchive.getArchive(leaderSocket.getOutputStream());
conversation.converseWithFollower(ia, oa, follower);
} finally {
@@ -476,8 +470,7 @@ public class Zab1_0Test extends ZKTestCase {
observer = createObserver(tmpDir, peer);
peer.observer = observer;
- ServerSocket ss =
- new ServerSocket(0, 50, InetAddress.getByName("127.0.0.1"));
+ ServerSocket ss = new ServerSocket(0, 50, InetAddress.getByName("127.0.0.1"));
QuorumServer leaderQS = new QuorumServer(1, (InetSocketAddress) ss.getLocalSocketAddress());
observer.setLeaderQuorumServer(leaderQS);
final Observer observerForThread = observer;
@@ -486,7 +479,7 @@ public class Zab1_0Test extends ZKTestCase {
public void run() {
try {
observerForThread.observeLeader();
- } catch(Exception e) {
+ } catch (Exception e) {
e.printStackTrace();
}
}
@@ -494,10 +487,8 @@ public class Zab1_0Test extends ZKTestCase {
observerThread.start();
Socket leaderSocket = ss.accept();
- InputArchive ia = BinaryInputArchive.getArchive(leaderSocket
- .getInputStream());
- OutputArchive oa = BinaryOutputArchive.getArchive(leaderSocket
- .getOutputStream());
+ InputArchive ia = BinaryInputArchive.getArchive(leaderSocket.getInputStream());
+ OutputArchive oa = BinaryOutputArchive.getArchive(leaderSocket.getOutputStream());
conversation.converseWithObserver(ia, oa, observer);
} finally {
@@ -519,71 +510,67 @@ public class Zab1_0Test extends ZKTestCase {
public void testUnnecessarySnap() throws Exception {
testPopulatedLeaderConversation(new PopulatedLeaderConversation() {
@Override
- public void converseWithLeader(InputArchive ia, OutputArchive oa,
- Leader l, long zxid) throws Exception {
+ public void converseWithLeader(InputArchive ia, OutputArchive oa, Leader l, long zxid) throws Exception {
- Assert.assertEquals(1, l.self.getAcceptedEpoch());
- Assert.assertEquals(1, l.self.getCurrentEpoch());
+ assertEquals(1, l.self.getAcceptedEpoch());
+ assertEquals(1, l.self.getCurrentEpoch());
/* we test a normal run. everything should work out well. */
LearnerInfo li = new LearnerInfo(1, 0x10000, 0);
- byte liBytes[] = new byte[20];
- ByteBufferOutputStream.record2ByteBuffer(li,
- ByteBuffer.wrap(liBytes));
- QuorumPacket qp = new QuorumPacket(Leader.FOLLOWERINFO, 1,
- liBytes, null);
+ byte[] liBytes = new byte[20];
+ ByteBufferOutputStream.record2ByteBuffer(li, ByteBuffer.wrap(liBytes));
+ QuorumPacket qp = new QuorumPacket(Leader.FOLLOWERINFO, 1, liBytes, null);
oa.writeRecord(qp, null);
readPacketSkippingPing(ia, qp);
- Assert.assertEquals(Leader.LEADERINFO, qp.getType());
- Assert.assertEquals(ZxidUtils.makeZxid(2, 0), qp.getZxid());
- Assert.assertEquals(ByteBuffer.wrap(qp.getData()).getInt(),
- 0x10000);
- Assert.assertEquals(2, l.self.getAcceptedEpoch());
- Assert.assertEquals(1, l.self.getCurrentEpoch());
-
- byte epochBytes[] = new byte[4];
+ assertEquals(Leader.LEADERINFO, qp.getType());
+ assertEquals(ZxidUtils.makeZxid(2, 0), qp.getZxid());
+ assertEquals(ByteBuffer.wrap(qp.getData()).getInt(), 0x10000);
+ assertEquals(2, l.self.getAcceptedEpoch());
+ assertEquals(1, l.self.getCurrentEpoch());
+
+ byte[] epochBytes = new byte[4];
final ByteBuffer wrappedEpochBytes = ByteBuffer.wrap(epochBytes);
wrappedEpochBytes.putInt(1);
qp = new QuorumPacket(Leader.ACKEPOCH, zxid, epochBytes, null);
oa.writeRecord(qp, null);
readPacketSkippingPing(ia, qp);
- Assert.assertEquals(Leader.DIFF, qp.getType());
+ assertEquals(Leader.DIFF, qp.getType());
}
}, 2);
}
-
+
// We want to track the change with a callback rather than depending on timing
class TrackerWatcher implements Watcher {
+
boolean changed;
synchronized void waitForChange() throws InterruptedException {
- while(!changed) {
+ while (!changed) {
wait();
}
}
@Override
public void process(WatchedEvent event) {
if (event.getType() == EventType.NodeDataChanged) {
- synchronized(this) {
+ synchronized (this) {
changed = true;
notifyAll();
}
}
}
- synchronized public boolean changed() {
+ public synchronized boolean changed() {
return changed;
}
- };
-
+ }
+
@Test
public void testNormalFollowerRun() throws Exception {
testFollowerConversation(new FollowerConversation() {
@Override
- public void converseWithFollower(InputArchive ia, OutputArchive oa,
- Follower f) throws Exception {
+ public void converseWithFollower(InputArchive ia, OutputArchive oa, Follower f) throws Exception {
File tmpDir = File.createTempFile("test", "dir", testData);
tmpDir.delete();
tmpDir.mkdir();
@@ -592,40 +579,40 @@ public class Zab1_0Test extends ZKTestCase {
//Spy on ZK so we can check if a snapshot happened or not.
f.zk = spy(f.zk);
try {
- Assert.assertEquals(0, f.self.getAcceptedEpoch());
- Assert.assertEquals(0, f.self.getCurrentEpoch());
+ assertEquals(0, f.self.getAcceptedEpoch());
+ assertEquals(0, f.self.getCurrentEpoch());
// Setup a database with a single /foo node
ZKDatabase zkDb = new ZKDatabase(new FileTxnSnapLog(tmpDir, tmpDir));
final long firstZxid = ZxidUtils.makeZxid(1, 1);
zkDb.processTxn(new TxnHeader(13, 1313, firstZxid, 33, ZooDefs.OpCode.create), new CreateTxn("/foo", "data1".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, false, 1));
Stat stat = new Stat();
- Assert.assertEquals("data1", new String(zkDb.getData("/foo", stat, null)));
+ assertEquals("data1", new String(zkDb.getData("/foo", stat, null)));
QuorumPacket qp = new QuorumPacket();
readPacketSkippingPing(ia, qp);
- Assert.assertEquals(Leader.FOLLOWERINFO, qp.getType());
- Assert.assertEquals(qp.getZxid(), 0);
+ assertEquals(Leader.FOLLOWERINFO, qp.getType());
+ assertEquals(qp.getZxid(), 0);
LearnerInfo learnInfo = new LearnerInfo();
ByteBufferInputStream.byteBuffer2Record(ByteBuffer.wrap(qp.getData()), learnInfo);
- Assert.assertEquals(learnInfo.getProtocolVersion(), 0x10000);
- Assert.assertEquals(learnInfo.getServerid(), 0);
-
+ assertEquals(learnInfo.getProtocolVersion(), 0x10000);
+ assertEquals(learnInfo.getServerid(), 0);
+
// We are simulating an established leader, so the epoch is 1
qp.setType(Leader.LEADERINFO);
qp.setZxid(ZxidUtils.makeZxid(1, 0));
- byte protoBytes[] = new byte[4];
+ byte[] protoBytes = new byte[4];
ByteBuffer.wrap(protoBytes).putInt(0x10000);
qp.setData(protoBytes);
oa.writeRecord(qp, null);
-
+
readPacketSkippingPing(ia, qp);
- Assert.assertEquals(Leader.ACKEPOCH, qp.getType());
- Assert.assertEquals(0, qp.getZxid());
- Assert.assertEquals(ZxidUtils.makeZxid(0, 0), ByteBuffer.wrap(qp.getData()).getInt());
- Assert.assertEquals(1, f.self.getAcceptedEpoch());
- Assert.assertEquals(0, f.self.getCurrentEpoch());
-
+ assertEquals(Leader.ACKEPOCH, qp.getType());
+ assertEquals(0, qp.getZxid());
+ assertEquals(ZxidUtils.makeZxid(0, 0), ByteBuffer.wrap(qp.getData()).getInt());
+ assertEquals(1, f.self.getAcceptedEpoch());
+ assertEquals(0, f.self.getCurrentEpoch());
+
// Send the snapshot we created earlier
qp.setType(Leader.SNAP);
qp.setData(new byte[0]);
@@ -643,60 +630,60 @@ public class Zab1_0Test extends ZKTestCase {
// Get the ack of the new leader
readPacketSkippingPing(ia, qp);
- Assert.assertEquals(Leader.ACK, qp.getType());
- Assert.assertEquals(ZxidUtils.makeZxid(1, 0), qp.getZxid());
- Assert.assertEquals(1, f.self.getAcceptedEpoch());
- Assert.assertEquals(1, f.self.getCurrentEpoch());
+ assertEquals(Leader.ACK, qp.getType());
+ assertEquals(ZxidUtils.makeZxid(1, 0), qp.getZxid());
+ assertEquals(1, f.self.getAcceptedEpoch());
+ assertEquals(1, f.self.getCurrentEpoch());
//Make sure that we did take the snapshot now
verify(f.zk).takeSnapshot(true);
- Assert.assertEquals(firstZxid, f.fzk.getLastProcessedZxid());
-
+ assertEquals(firstZxid, f.fzk.getLastProcessedZxid());
+
// Make sure the data was recorded in the filesystem ok
ZKDatabase zkDb2 = new ZKDatabase(new FileTxnSnapLog(logDir, snapDir));
long lastZxid = zkDb2.loadDataBase();
- Assert.assertEquals("data1", new String(zkDb2.getData("/foo", stat, null)));
- Assert.assertEquals(firstZxid, lastZxid);
+ assertEquals("data1", new String(zkDb2.getData("/foo", stat, null)));
+ assertEquals(firstZxid, lastZxid);
// Propose an update
long proposalZxid = ZxidUtils.makeZxid(1, 1000);
proposeSetData(qp, proposalZxid, "data2", 2);
oa.writeRecord(qp, null);
-
+
TrackerWatcher watcher = new TrackerWatcher();
-
+
// The change should not have happened yet, since we haven't committed
- Assert.assertEquals("data1", new String(f.fzk.getZKDatabase().getData("/foo", stat, watcher)));
-
+ assertEquals("data1", new String(f.fzk.getZKDatabase().getData("/foo", stat, watcher)));
+
// The change should happen now
qp.setType(Leader.COMMIT);
qp.setZxid(proposalZxid);
oa.writeRecord(qp, null);
-
+
qp.setType(Leader.UPTODATE);
qp.setZxid(0);
oa.writeRecord(qp, null);
-
+
// Read the uptodate ack
readPacketSkippingPing(ia, qp);
- Assert.assertEquals(Leader.ACK, qp.getType());
- Assert.assertEquals(ZxidUtils.makeZxid(1, 0), qp.getZxid());
-
+ assertEquals(Leader.ACK, qp.getType());
+ assertEquals(ZxidUtils.makeZxid(1, 0), qp.getZxid());
+
readPacketSkippingPing(ia, qp);
- Assert.assertEquals(Leader.ACK, qp.getType());
- Assert.assertEquals(proposalZxid, qp.getZxid());
-
+ assertEquals(Leader.ACK, qp.getType());
+ assertEquals(proposalZxid, qp.getZxid());
+
watcher.waitForChange();
- Assert.assertEquals("data2", new String(f.fzk.getZKDatabase().getData("/foo", stat, null)));
-
+ assertEquals("data2", new String(f.fzk.getZKDatabase().getData("/foo", stat, null)));
+
// check and make sure the change is persisted
zkDb2 = new ZKDatabase(new FileTxnSnapLog(logDir, snapDir));
lastZxid = zkDb2.loadDataBase();
- Assert.assertEquals("data2", new String(zkDb2.getData("/foo", stat, null)));
- Assert.assertEquals(proposalZxid, lastZxid);
+ assertEquals("data2", new String(zkDb2.getData("/foo", stat, null)));
+ assertEquals(proposalZxid, lastZxid);
} finally {
TestUtils.deleteFileRecursively(tmpDir);
}
-
+
}
private void proposeSetData(QuorumPacket qp, long zxid, String data, int version) throws IOException {
@@ -712,13 +699,12 @@ public class Zab1_0Test extends ZKTestCase {
}
});
}
-
+
@Test
public void testNormalFollowerRunWithDiff() throws Exception {
testFollowerConversation(new FollowerConversation() {
@Override
- public void converseWithFollower(InputArchive ia, OutputArchive oa,
- Follower f) throws Exception {
+ public void converseWithFollower(InputArchive ia, OutputArchive oa, Follower f) throws Exception {
File tmpDir = File.createTempFile("test", "dir", testData);
tmpDir.delete();
tmpDir.mkdir();
@@ -727,40 +713,40 @@ public class Zab1_0Test extends ZKTestCase {
//Spy on ZK so we can check if a snapshot happened or not.
f.zk = spy(f.zk);
try {
- Assert.assertEquals(0, f.self.getAcceptedEpoch());
- Assert.assertEquals(0, f.self.getCurrentEpoch());
+ assertEquals(0, f.self.getAcceptedEpoch());
+ assertEquals(0, f.self.getCurrentEpoch());
// Setup a database with a single /foo node
ZKDatabase zkDb = new ZKDatabase(new FileTxnSnapLog(tmpDir, tmpDir));
final long firstZxid = ZxidUtils.makeZxid(1, 1);
zkDb.processTxn(new TxnHeader(13, 1313, firstZxid, 33, ZooDefs.OpCode.create), new CreateTxn("/foo", "data1".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, false, 1));
Stat stat = new Stat();
- Assert.assertEquals("data1", new String(zkDb.getData("/foo", stat, null)));
+ assertEquals("data1", new String(zkDb.getData("/foo", stat, null)));
QuorumPacket qp = new QuorumPacket();
readPacketSkippingPing(ia, qp);
- Assert.assertEquals(Leader.FOLLOWERINFO, qp.getType());
- Assert.assertEquals(qp.getZxid(), 0);
+ assertEquals(Leader.FOLLOWERINFO, qp.getType());
+ assertEquals(qp.getZxid(), 0);
LearnerInfo learnInfo = new LearnerInfo();
ByteBufferInputStream.byteBuffer2Record(ByteBuffer.wrap(qp.getData()), learnInfo);
- Assert.assertEquals(learnInfo.getProtocolVersion(), 0x10000);
- Assert.assertEquals(learnInfo.getServerid(), 0);
-
+ assertEquals(learnInfo.getProtocolVersion(), 0x10000);
+ assertEquals(learnInfo.getServerid(), 0);
+
// We are simulating an established leader, so the epoch is 1
qp.setType(Leader.LEADERINFO);
qp.setZxid(ZxidUtils.makeZxid(1, 0));
- byte protoBytes[] = new byte[4];
+ byte[] protoBytes = new byte[4];
ByteBuffer.wrap(protoBytes).putInt(0x10000);
qp.setData(protoBytes);
oa.writeRecord(qp, null);
-
+
readPacketSkippingPing(ia, qp);
- Assert.assertEquals(Leader.ACKEPOCH, qp.getType());
- Assert.assertEquals(0, qp.getZxid());
- Assert.assertEquals(ZxidUtils.makeZxid(0, 0), ByteBuffer.wrap(qp.getData()).getInt());
- Assert.assertEquals(1, f.self.getAcceptedEpoch());
- Assert.assertEquals(0, f.self.getCurrentEpoch());
-
+ assertEquals(Leader.ACKEPOCH, qp.getType());
+ assertEquals(0, qp.getZxid());
+ assertEquals(ZxidUtils.makeZxid(0, 0), ByteBuffer.wrap(qp.getData()).getInt());
+ assertEquals(1, f.self.getAcceptedEpoch());
+ assertEquals(0, f.self.getCurrentEpoch());
+
// Send a diff
qp.setType(Leader.DIFF);
qp.setData(new byte[0]);
@@ -779,29 +765,29 @@ public class Zab1_0Test extends ZKTestCase {
qp.setType(Leader.UPTODATE);
qp.setZxid(0);
oa.writeRecord(qp, null);
-
+
// Read the uptodate ack
readPacketSkippingPing(ia, qp);
- Assert.assertEquals(Leader.ACK, qp.getType());
- Assert.assertEquals(ZxidUtils.makeZxid(1, 0), qp.getZxid());
-
-
+ assertEquals(Leader.ACK, qp.getType());
+ assertEquals(ZxidUtils.makeZxid(1, 0), qp.getZxid());
+
// Get the ack of the new leader
readPacketSkippingPing(ia, qp);
- Assert.assertEquals(Leader.ACK, qp.getType());
- Assert.assertEquals(ZxidUtils.makeZxid(1, 0), qp.getZxid());
- Assert.assertEquals(1, f.self.getAcceptedEpoch());
- Assert.assertEquals(1, f.self.getCurrentEpoch());
-
+ assertEquals(Leader.ACK, qp.getType());
+ assertEquals(ZxidUtils.makeZxid(1, 0), qp.getZxid());
+ assertEquals(1, f.self.getAcceptedEpoch());
+ assertEquals(1, f.self.getCurrentEpoch());
+
//Wait for the transactions to be written out. The thread that writes them out
// does not send anything back when it is done.
long start = System.currentTimeMillis();
- while (createSessionZxid != f.fzk.getLastProcessedZxid() && (System.currentTimeMillis() - start) < 50) {
+ while (createSessionZxid != f.fzk.getLastProcessedZxid()
+ && (System.currentTimeMillis() - start) < 50) {
Thread.sleep(1);
}
-
- Assert.assertEquals(createSessionZxid, f.fzk.getLastProcessedZxid());
-
+
+ assertEquals(createSessionZxid, f.fzk.getLastProcessedZxid());
+
// Make sure the data was recorded in the filesystem ok
ZKDatabase zkDb2 = new ZKDatabase(new FileTxnSnapLog(logDir, snapDir));
start = System.currentTimeMillis();
@@ -812,13 +798,13 @@ public class Zab1_0Test extends ZKTestCase {
}
LOG.info("zkdb2 sessions:" + zkDb2.getSessions());
LOG.info("zkdb2 with timeouts:" + zkDb2.getSessionWithTimeOuts());
- Assert.assertNotNull(zkDb2.getSessionWithTimeOuts().get(4L));
+ assertNotNull(zkDb2.getSessionWithTimeOuts().get(4L));
//Snapshot was never taken during very simple sync
verify(f.zk, never()).takeSnapshot();
} finally {
TestUtils.deleteFileRecursively(tmpDir);
}
-
+
}
private void proposeNewSession(QuorumPacket qp, long zxid, long sessionId) throws IOException {
@@ -834,49 +820,45 @@ public class Zab1_0Test extends ZKTestCase {
}
});
}
-
+
@Test
public void testNormalRun() throws Exception {
testLeaderConversation(new LeaderConversation() {
- public void converseWithLeader(InputArchive ia, OutputArchive oa, Leader l)
- throws IOException {
- Assert.assertEquals(0, l.self.getAcceptedEpoch());
- Assert.assertEquals(0, l.self.getCurrentEpoch());
-
+ public void converseWithLeader(InputArchive ia, OutputArchive oa, Leader l) throws IOException {
+ assertEquals(0, l.self.getAcceptedEpoch());
+ assertEquals(0, l.self.getCurrentEpoch());
+
/* we test a normal run. everything should work out well. */
LearnerInfo li = new LearnerInfo(1, 0x10000, 0);
- byte liBytes[] = new byte[20];
- ByteBufferOutputStream.record2ByteBuffer(li,
- ByteBuffer.wrap(liBytes));
- QuorumPacket qp = new QuorumPacket(Leader.FOLLOWERINFO, 0,
- liBytes, null);
+ byte[] liBytes = new byte[20];
+ ByteBufferOutputStream.record2ByteBuffer(li, ByteBuffer.wrap(liBytes));
+ QuorumPacket qp = new QuorumPacket(Leader.FOLLOWERINFO, 0, liBytes, null);
oa.writeRecord(qp, null);
-
+
readPacketSkippingPing(ia, qp);
- Assert.assertEquals(Leader.LEADERINFO, qp.getType());
- Assert.assertEquals(ZxidUtils.makeZxid(1, 0), qp.getZxid());
- Assert.assertEquals(ByteBuffer.wrap(qp.getData()).getInt(),
- 0x10000);
- Assert.assertEquals(1, l.self.getAcceptedEpoch());
- Assert.assertEquals(0, l.self.getCurrentEpoch());
-
+ assertEquals(Leader.LEADERINFO, qp.getType());
+ assertEquals(ZxidUtils.makeZxid(1, 0), qp.getZxid());
+ assertEquals(ByteBuffer.wrap(qp.getData()).getInt(), 0x10000);
+ assertEquals(1, l.self.getAcceptedEpoch());
+ assertEquals(0, l.self.getCurrentEpoch());
+
qp = new QuorumPacket(Leader.ACKEPOCH, 0, new byte[4], null);
oa.writeRecord(qp, null);
-
+
readPacketSkippingPing(ia, qp);
- Assert.assertEquals(Leader.DIFF, qp.getType());
+ assertEquals(Leader.DIFF, qp.getType());
readPacketSkippingPing(ia, qp);
- Assert.assertEquals(Leader.NEWLEADER, qp.getType());
- Assert.assertEquals(ZxidUtils.makeZxid(1, 0), qp.getZxid());
- Assert.assertEquals(1, l.self.getAcceptedEpoch());
- Assert.assertEquals(1, l.self.getCurrentEpoch());
-
+ assertEquals(Leader.NEWLEADER, qp.getType());
+ assertEquals(ZxidUtils.makeZxid(1, 0), qp.getZxid());
+ assertEquals(1, l.self.getAcceptedEpoch());
+ assertEquals(1, l.self.getCurrentEpoch());
+
qp = new QuorumPacket(Leader.ACK, qp.getZxid(), null, null);
oa.writeRecord(qp, null);
readPacketSkippingPing(ia, qp);
- Assert.assertEquals(Leader.UPTODATE, qp.getType());
+ assertEquals(Leader.UPTODATE, qp.getType());
}
});
}
@@ -884,52 +866,46 @@ public class Zab1_0Test extends ZKTestCase {
@Test
public void testTxnTimeout() throws Exception {
testLeaderConversation(new LeaderConversation() {
- public void converseWithLeader(InputArchive ia, OutputArchive oa, Leader l)
- throws IOException, InterruptedException, org.apache.zookeeper.server.quorum.Leader.XidRolloverException {
- Assert.assertEquals(0, l.self.getAcceptedEpoch());
- Assert.assertEquals(0, l.self.getCurrentEpoch());
-
+ public void converseWithLeader(InputArchive ia, OutputArchive oa, Leader l) throws IOException, InterruptedException, org.apache.zookeeper.server.quorum.Leader.XidRolloverException {
+ assertEquals(0, l.self.getAcceptedEpoch());
+ assertEquals(0, l.self.getCurrentEpoch());
+
LearnerInfo li = new LearnerInfo(1, 0x10000, 0);
- byte liBytes[] = new byte[20];
- ByteBufferOutputStream.record2ByteBuffer(li,
- ByteBuffer.wrap(liBytes));
- QuorumPacket qp = new QuorumPacket(Leader.FOLLOWERINFO, 0,
- liBytes, null);
+ byte[] liBytes = new byte[20];
+ ByteBufferOutputStream.record2ByteBuffer(li, ByteBuffer.wrap(liBytes));
+ QuorumPacket qp = new QuorumPacket(Leader.FOLLOWERINFO, 0, liBytes, null);
oa.writeRecord(qp, null);
-
+
readPacketSkippingPing(ia, qp);
- Assert.assertEquals(Leader.LEADERINFO, qp.getType());
- Assert.assertEquals(ZxidUtils.makeZxid(1, 0), qp.getZxid());
- Assert.assertEquals(ByteBuffer.wrap(qp.getData()).getInt(),
- 0x10000);
- Assert.assertEquals(1, l.self.getAcceptedEpoch());
- Assert.assertEquals(0, l.self.getCurrentEpoch());
-
+ assertEquals(Leader.LEADERINFO, qp.getType());
+ assertEquals(ZxidUtils.makeZxid(1, 0), qp.getZxid());
+ assertEquals(ByteBuffer.wrap(qp.getData()).getInt(), 0x10000);
+ assertEquals(1, l.self.getAcceptedEpoch());
+ assertEquals(0, l.self.getCurrentEpoch());
+
qp = new QuorumPacket(Leader.ACKEPOCH, 0, new byte[4], null);
oa.writeRecord(qp, null);
-
+
readPacketSkippingPing(ia, qp);
- Assert.assertEquals(Leader.DIFF, qp.getType());
+ assertEquals(Leader.DIFF, qp.getType());
readPacketSkippingPing(ia, qp);
- Assert.assertEquals(Leader.NEWLEADER, qp.getType());
- Assert.assertEquals(ZxidUtils.makeZxid(1, 0), qp.getZxid());
- Assert.assertEquals(1, l.self.getAcceptedEpoch());
- Assert.assertEquals(1, l.self.getCurrentEpoch());
-
+ assertEquals(Leader.NEWLEADER, qp.getType());
+ assertEquals(ZxidUtils.makeZxid(1, 0), qp.getZxid());
+ assertEquals(1, l.self.getAcceptedEpoch());
+ assertEquals(1, l.self.getCurrentEpoch());
+
qp = new QuorumPacket(Leader.ACK, qp.getZxid(), null, null);
oa.writeRecord(qp, null);
readPacketSkippingPing(ia, qp);
- Assert.assertEquals(Leader.UPTODATE, qp.getType());
+ assertEquals(Leader.UPTODATE, qp.getType());
long zxid = l.zk.getZxid();
- l.propose(new Request(1, 1, ZooDefs.OpCode.create,
- new TxnHeader(1, 1, zxid, 1, ZooDefs.OpCode.create),
- new CreateTxn("/test", "hola".getBytes(), null, true, 0), zxid));
+ l.propose(new Request(1, 1, ZooDefs.OpCode.create, new TxnHeader(1, 1, zxid, 1, ZooDefs.OpCode.create), new CreateTxn("/test", "hola".getBytes(), null, true, 0), zxid));
readPacketSkippingPing(ia, qp);
- Assert.assertEquals(Leader.PROPOSAL, qp.getType());
+ assertEquals(Leader.PROPOSAL, qp.getType());
LOG.info("Proposal sent.");
@@ -937,19 +913,18 @@ public class Zab1_0Test extends ZKTestCase {
try {
ia.readRecord(qp, null);
LOG.info("Ping received: " + i);
- qp = new QuorumPacket(Leader.PING, qp.getZxid(), "".getBytes(), null);
+ qp = new QuorumPacket(Leader.PING, qp.getZxid(), "".getBytes(), null);
oa.writeRecord(qp, null);
} catch (EOFException e) {
return;
}
}
- Assert.fail("Connection hasn't been closed by leader after transaction times out.");
+ fail("Connection hasn't been closed by leader after transaction times out.");
}
});
}
- private void deserializeSnapshot(InputArchive ia)
- throws IOException {
+ private void deserializeSnapshot(InputArchive ia) throws IOException {
ZKDatabase zkdb = new ZKDatabase(null);
zkdb.deserializeSnapshot(ia);
String signature = ia.readString("signature");
@@ -960,60 +935,49 @@ public class Zab1_0Test extends ZKTestCase {
public void testNormalObserverRun() throws Exception {
testObserverConversation(new ObserverConversation() {
@Override
- public void converseWithObserver(InputArchive ia, OutputArchive oa,
- Observer o) throws Exception {
+ public void converseWithObserver(InputArchive ia, OutputArchive oa, Observer o) throws Exception {
File tmpDir = File.createTempFile("test", "dir", testData);
tmpDir.delete();
tmpDir.mkdir();
File logDir = o.zk.getTxnLogFactory().getDataDir().getParentFile();
File snapDir = o.zk.getTxnLogFactory().getSnapDir().getParentFile();
try {
- Assert.assertEquals(0, o.self.getAcceptedEpoch());
- Assert.assertEquals(0, o.self.getCurrentEpoch());
+ assertEquals(0, o.self.getAcceptedEpoch());
+ assertEquals(0, o.self.getCurrentEpoch());
// Setup a database with a single /foo node
ZKDatabase zkDb = new ZKDatabase(new FileTxnSnapLog(tmpDir, tmpDir));
final long foo1Zxid = ZxidUtils.makeZxid(1, 1);
final long foo2Zxid = ZxidUtils.makeZxid(1, 2);
- zkDb.processTxn(new TxnHeader(13, 1313, foo1Zxid, 33,
- ZooDefs.OpCode.create), new CreateTxn("/foo1",
- "data1".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE,
- false, 1));
- zkDb.processTxn(new TxnHeader(13, 1313, foo2Zxid, 33,
- ZooDefs.OpCode.create), new CreateTxn("/foo2",
- "data1".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE,
- false, 1));
+ zkDb.processTxn(new TxnHeader(13, 1313, foo1Zxid, 33, ZooDefs.OpCode.create), new CreateTxn("/foo1", "data1".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, false, 1));
+ zkDb.processTxn(new TxnHeader(13, 1313, foo2Zxid, 33, ZooDefs.OpCode.create), new CreateTxn("/foo2", "data1".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, false, 1));
Stat stat = new Stat();
- Assert.assertEquals("data1",
- new String(zkDb.getData("/foo1", stat, null)));
- Assert.assertEquals("data1",
- new String(zkDb.getData("/foo2", stat, null)));
+ assertEquals("data1", new String(zkDb.getData("/foo1", stat, null)));
+ assertEquals("data1", new String(zkDb.getData("/foo2", stat, null)));
QuorumPacket qp = new QuorumPacket();
readPacketSkippingPing(ia, qp);
- Assert.assertEquals(Leader.OBSERVERINFO, qp.getType());
- Assert.assertEquals(qp.getZxid(), 0);
+ assertEquals(Leader.OBSERVERINFO, qp.getType());
+ assertEquals(qp.getZxid(), 0);
LearnerInfo learnInfo = new LearnerInfo();
- ByteBufferInputStream.byteBuffer2Record(
- ByteBuffer.wrap(qp.getData()), learnInfo);
- Assert.assertEquals(learnInfo.getProtocolVersion(), 0x10000);
- Assert.assertEquals(learnInfo.getServerid(), 0);
+ ByteBufferInputStream.byteBuffer2Record(ByteBuffer.wrap(qp.getData()), learnInfo);
+ assertEquals(learnInfo.getProtocolVersion(), 0x10000);
+ assertEquals(learnInfo.getServerid(), 0);
// We are simulating an established leader, so the epoch is 1
qp.setType(Leader.LEADERINFO);
qp.setZxid(ZxidUtils.makeZxid(1, 0));
- byte protoBytes[] = new byte[4];
+ byte[] protoBytes = new byte[4];
ByteBuffer.wrap(protoBytes).putInt(0x10000);
qp.setData(protoBytes);
oa.writeRecord(qp, null);
readPacketSkippingPing(ia, qp);
- Assert.assertEquals(Leader.ACKEPOCH, qp.getType());
- Assert.assertEquals(0, qp.getZxid());
- Assert.assertEquals(ZxidUtils.makeZxid(0, 0), ByteBuffer
- .wrap(qp.getData()).getInt());
- Assert.assertEquals(1, o.self.getAcceptedEpoch());
- Assert.assertEquals(0, o.self.getCurrentEpoch());
+ assertEquals(Leader.ACKEPOCH, qp.getType());
+ assertEquals(0, qp.getZxid());
+ assertEquals(ZxidUtils.makeZxid(0, 0), ByteBuffer.wrap(qp.getData()).getInt());
+ assertEquals(1, o.self.getAcceptedEpoch());
+ assertEquals(0, o.self.getCurrentEpoch());
// Send the snapshot we created earlier
qp.setType(Leader.SNAP);
@@ -1028,25 +992,22 @@ public class Zab1_0Test extends ZKTestCase {
// Get the ack of the new leader
readPacketSkippingPing(ia, qp);
- Assert.assertEquals(Leader.ACK, qp.getType());
- Assert.assertEquals(ZxidUtils.makeZxid(1, 0), qp.getZxid());
- Assert.assertEquals(1, o.self.getAcceptedEpoch());
- Assert.assertEquals(1, o.self.getCurrentEpoch());
+ assertEquals(Leader.ACK, qp.getType());
+ assertEquals(ZxidUtils.makeZxid(1, 0), qp.getZxid());
+ assertEquals(1, o.self.getAcceptedEpoch());
+ assertEquals(1, o.self.getCurrentEpoch());
- Assert.assertEquals(foo2Zxid, o.zk.getLastProcessedZxid());
+ assertEquals(foo2Zxid, o.zk.getLastProcessedZxid());
// Make sure the data was recorded in the filesystem ok
- ZKDatabase zkDb2 = new ZKDatabase(new FileTxnSnapLog(
- logDir, snapDir));
+ ZKDatabase zkDb2 = new ZKDatabase(new FileTxnSnapLog(logDir, snapDir));
long lastZxid = zkDb2.loadDataBase();
- Assert.assertEquals("data1",
- new String(zkDb2.getData("/foo1", stat, null)));
- Assert.assertEquals(foo2Zxid, lastZxid);
+ assertEquals("data1", new String(zkDb2.getData("/foo1", stat, null)));
+ assertEquals(foo2Zxid, lastZxid);
// Register watch
TrackerWatcher watcher = new TrackerWatcher();
- Assert.assertEquals("data1", new String(o.zk
- .getZKDatabase().getData("/foo2", stat, watcher)));
+ assertEquals("data1", new String(o.zk.getZKDatabase().getData("/foo2", stat, watcher)));
// Propose /foo1 update
long proposalZxid = ZxidUtils.makeZxid(1, 1000);
@@ -1070,15 +1031,13 @@ public class Zab1_0Test extends ZKTestCase {
// Read the uptodate ack
readPacketSkippingPing(ia, qp);
- Assert.assertEquals(Leader.ACK, qp.getType());
- Assert.assertEquals(ZxidUtils.makeZxid(1, 0), qp.getZxid());
+ assertEquals(Leader.ACK, qp.getType());
+ assertEquals(ZxidUtils.makeZxid(1, 0), qp.getZxid());
// Data should get updated
watcher.waitForChange();
- Assert.assertEquals("data2", new String(o.zk
- .getZKDatabase().getData("/foo1", stat, null)));
- Assert.assertEquals("data2", new String(o.zk
- .getZKDatabase().getData("/foo2", stat, null)));
+ assertEquals("data2", new String(o.zk.getZKDatabase().getData("/foo1", stat, null)));
+ assertEquals("data2", new String(o.zk.getZKDatabase().getData("/foo2", stat, null)));
// Shutdown sequence guarantee that all pending requests
// in sync request processor get flush to disk
@@ -1086,21 +1045,19 @@ public class Zab1_0Test extends ZKTestCase {
zkDb2 = new ZKDatabase(new FileTxnSnapLog(logDir, snapDir));
lastZxid = zkDb2.loadDataBase();
- Assert.assertEquals("data2", new String(zkDb2.getData("/foo1", stat, null)));
- Assert.assertEquals("data2", new String(zkDb2.getData("/foo2", stat, null)));
- Assert.assertEquals(informZxid, lastZxid);
+ assertEquals("data2", new String(zkDb2.getData("/foo1", stat, null)));
+ assertEquals("data2", new String(zkDb2.getData("/foo2", stat, null)));
+ assertEquals(informZxid, lastZxid);
} finally {
TestUtils.deleteFileRecursively(tmpDir);
}
}
- private void proposeSetData(QuorumPacket qp, String path,
- long zxid, String data, int version) throws IOException {
+ private void proposeSetData(QuorumPacket qp, String path, long zxid, String data, int version) throws IOException {
qp.setType(Leader.PROPOSAL);
qp.setZxid(zxid);
- TxnHeader hdr = new TxnHeader(4, 1414, qp.getZxid(), 55,
- ZooDefs.OpCode.setData);
+ TxnHeader hdr = new TxnHeader(4, 1414, qp.getZxid(), 55, ZooDefs.OpCode.setData);
SetDataTxn sdt = new SetDataTxn(path, data.getBytes(), version);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
OutputArchive boa = BinaryOutputArchive.getArchive(baos);
@@ -1114,35 +1071,31 @@ public class Zab1_0Test extends ZKTestCase {
@Test
public void testLeaderBehind() throws Exception {
testLeaderConversation(new LeaderConversation() {
- public void converseWithLeader(InputArchive ia, OutputArchive oa, Leader l)
- throws IOException {
+ public void converseWithLeader(InputArchive ia, OutputArchive oa, Leader l) throws IOException {
/* we test a normal run. everything should work out well. */
LearnerInfo li = new LearnerInfo(1, 0x10000, 0);
- byte liBytes[] = new byte[20];
- ByteBufferOutputStream.record2ByteBuffer(li,
- ByteBuffer.wrap(liBytes));
+ byte[] liBytes = new byte[20];
+ ByteBufferOutputStream.record2ByteBuffer(li, ByteBuffer.wrap(liBytes));
/* we are going to say we last acked epoch 20 */
- QuorumPacket qp = new QuorumPacket(Leader.FOLLOWERINFO, ZxidUtils.makeZxid(20, 0),
- liBytes, null);
+ QuorumPacket qp = new QuorumPacket(Leader.FOLLOWERINFO, ZxidUtils.makeZxid(20, 0), liBytes, null);
oa.writeRecord(qp, null);
readPacketSkippingPing(ia, qp);
- Assert.assertEquals(Leader.LEADERINFO, qp.getType());
- Assert.assertEquals(ZxidUtils.makeZxid(21, 0), qp.getZxid());
- Assert.assertEquals(ByteBuffer.wrap(qp.getData()).getInt(),
- 0x10000);
+ assertEquals(Leader.LEADERINFO, qp.getType());
+ assertEquals(ZxidUtils.makeZxid(21, 0), qp.getZxid());
+ assertEquals(ByteBuffer.wrap(qp.getData()).getInt(), 0x10000);
qp = new QuorumPacket(Leader.ACKEPOCH, 0, new byte[4], null);
oa.writeRecord(qp, null);
readPacketSkippingPing(ia, qp);
- Assert.assertEquals(Leader.DIFF, qp.getType());
+ assertEquals(Leader.DIFF, qp.getType());
readPacketSkippingPing(ia, qp);
- Assert.assertEquals(Leader.NEWLEADER, qp.getType());
- Assert.assertEquals(ZxidUtils.makeZxid(21, 0), qp.getZxid());
+ assertEquals(Leader.NEWLEADER, qp.getType());
+ assertEquals(ZxidUtils.makeZxid(21, 0), qp.getZxid());
qp = new QuorumPacket(Leader.ACK, qp.getZxid(), null, null);
oa.writeRecord(qp, null);
readPacketSkippingPing(ia, qp);
- Assert.assertEquals(Leader.UPTODATE, qp.getType());
+ assertEquals(Leader.UPTODATE, qp.getType());
}
});
}
@@ -1156,29 +1109,25 @@ public class Zab1_0Test extends ZKTestCase {
@Test
public void testAbandonBeforeACKEpoch() throws Exception {
testLeaderConversation(new LeaderConversation() {
- public void converseWithLeader(InputArchive ia, OutputArchive oa, Leader l)
- throws IOException, InterruptedException {
- /* we test a normal run. everything should work out well. */
+ public void converseWithLeader(InputArchive ia, OutputArchive oa, Leader l) throws IOException, InterruptedException {
+ /* we test a normal run. everything should work out well. */
LearnerInfo li = new LearnerInfo(1, 0x10000, 0);
- byte liBytes[] = new byte[20];
- ByteBufferOutputStream.record2ByteBuffer(li,
- ByteBuffer.wrap(liBytes));
- QuorumPacket qp = new QuorumPacket(Leader.FOLLOWERINFO, 0,
- liBytes, null);
+ byte[] liBytes = new byte[20];
+ ByteBufferOutputStream.record2ByteBuffer(li, ByteBuffer.wrap(liBytes));
+ QuorumPacket qp = new QuorumPacket(Leader.FOLLOWERINFO, 0, liBytes, null);
oa.writeRecord(qp, null);
readPacketSkippingPing(ia, qp);
- Assert.assertEquals(Leader.LEADERINFO, qp.getType());
- Assert.assertEquals(ZxidUtils.makeZxid(1, 0), qp.getZxid());
- Assert.assertEquals(ByteBuffer.wrap(qp.getData()).getInt(),
- 0x10000);
- Thread.sleep(l.self.getInitLimit()*l.self.getTickTime() + 5000);
-
+ assertEquals(Leader.LEADERINFO, qp.getType());
+ assertEquals(ZxidUtils.makeZxid(1, 0), qp.getZxid());
+ assertEquals(ByteBuffer.wrap(qp.getData()).getInt(), 0x10000);
+ Thread.sleep(l.self.getInitLimit() * l.self.getTickTime() + 5000);
+
// The leader didn't get a quorum of acks - make sure that leader's current epoch is not advanced
- Assert.assertEquals(0, l.self.getCurrentEpoch());
+ assertEquals(0, l.self.getCurrentEpoch());
}
});
}
-
+
static class ConversableFollower extends Follower {
ConversableFollower(QuorumPeer self, FollowerZooKeeperServer zk) {
@@ -1189,14 +1138,14 @@ public class Zab1_0Test extends ZKTestCase {
public void setLeaderQuorumServer(QuorumServer quorumServer) {
leaderQuorumServer = quorumServer;
}
-
+
@Override
protected QuorumServer findLeader() {
return leaderQuorumServer;
}
+
}
- private ConversableFollower createFollower(File tmpDir, QuorumPeer peer)
- throws IOException {
+ private ConversableFollower createFollower(File tmpDir, QuorumPeer peer) throws IOException {
FileTxnSnapLog logFactory = new FileTxnSnapLog(tmpDir, tmpDir);
peer.setTxnFactory(logFactory);
ZKDatabase zkDb = new ZKDatabase(logFactory);
@@ -1220,10 +1169,10 @@ public class Zab1_0Test extends ZKTestCase {
protected QuorumServer findLeader() {
return leaderQuorumServer;
}
+
}
- private ConversableObserver createObserver(File tmpDir, QuorumPeer peer)
- throws IOException {
+ private ConversableObserver createObserver(File tmpDir, QuorumPeer peer) throws IOException {
FileTxnSnapLog logFactory = new FileTxnSnapLog(tmpDir, tmpDir);
peer.setTxnFactory(logFactory);
ZKDatabase zkDb = new ZKDatabase(logFactory);
@@ -1247,25 +1196,20 @@ public class Zab1_0Test extends ZKTestCase {
version2.mkdir();
logFactory.save(new DataTree(), new ConcurrentHashMap<Long, Integer>(), false);
long zxid = ZxidUtils.makeZxid(3, 3);
- logFactory.append(new Request(1, 1, ZooDefs.OpCode.error,
- new TxnHeader(1, 1, zxid, 1, ZooDefs.OpCode.error),
- new ErrorTxn(1), zxid));
+ logFactory.append(new Request(1, 1, ZooDefs.OpCode.error, new TxnHeader(1, 1, zxid, 1, ZooDefs.OpCode.error), new ErrorTxn(1), zxid));
logFactory.commit();
ZKDatabase zkDb = new ZKDatabase(logFactory);
QuorumPeer peer = QuorumPeer.testingQuorumPeer();
peer.setZKDatabase(zkDb);
peer.setTxnFactory(logFactory);
peer.getLastLoggedZxid();
- Assert.assertEquals(3, peer.getAcceptedEpoch());
- Assert.assertEquals(3, peer.getCurrentEpoch());
- Assert.assertEquals(3, Integer
- .parseInt(readContentsOfFile(new File(version2,
- QuorumPeer.CURRENT_EPOCH_FILENAME))));
- Assert.assertEquals(3, Integer
- .parseInt(readContentsOfFile(new File(version2,
- QuorumPeer.ACCEPTED_EPOCH_FILENAME))));
+ assertEquals(3, peer.getAcceptedEpoch());
+ assertEquals(3, peer.getCurrentEpoch());
+ assertEquals(3, Integer.parseInt(readContentsOfFile(new File(version2, QuorumPeer.CURRENT_EPOCH_FILENAME))));
+ assertEquals(3, Integer.parseInt(readContentsOfFile(new File(version2, QuorumPeer.ACCEPTED_EPOCH_FILENAME))));
} finally {
TestUtils.deleteFileRecursively(tmpDir);
}
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/ZabUtils.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/ZabUtils.java
index 09bcde80e..fff5e62de 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/ZabUtils.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/ZabUtils.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,6 +18,12 @@
package org.apache.zookeeper.server.quorum;
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.net.InetSocketAddress;
+import java.util.HashMap;
+import java.util.Map;
import org.apache.zookeeper.PortAssignment;
import org.apache.zookeeper.common.X509Exception;
import org.apache.zookeeper.server.ServerCnxn;
@@ -28,39 +34,23 @@ import org.apache.zookeeper.server.persistence.FileTxnSnapLog;
import org.apache.zookeeper.server.quorum.flexible.QuorumMaj;
import org.apache.zookeeper.test.ClientBase;
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.net.InetSocketAddress;
-import java.util.HashMap;
-import java.util.Map;
-
public class ZabUtils {
- private ZabUtils() {}
+ private ZabUtils() {
+ }
public static final int SYNC_LIMIT = 2;
- public static QuorumPeer createQuorumPeer(File tmpDir) throws IOException, FileNotFoundException {
+ public static QuorumPeer createQuorumPeer(File tmpDir) throws IOException {
HashMap<Long, QuorumPeer.QuorumServer> peers = new HashMap<Long, QuorumPeer.QuorumServer>();
QuorumPeer peer = QuorumPeer.testingQuorumPeer();
peer.syncLimit = SYNC_LIMIT;
peer.initLimit = 2;
peer.tickTime = 2000;
- peers.put(0L, new QuorumPeer.QuorumServer(
- 0, new InetSocketAddress("127.0.0.1", PortAssignment.unique()),
- new InetSocketAddress("127.0.0.1", PortAssignment.unique()),
- new InetSocketAddress("127.0.0.1", PortAssignment.unique())));
- peers.put(1L, new QuorumPeer.QuorumServer(
- 1, new InetSocketAddress("127.0.0.1", PortAssignment.unique()),
- new InetSocketAddress("127.0.0.1", PortAssignment.unique()),
- new InetSocketAddress("127.0.0.1", PortAssignment.unique())));
- peers.put(2L, new QuorumPeer.QuorumServer(
- 2, new InetSocketAddress("127.0.0.1", PortAssignment.unique()),
- new InetSocketAddress("127.0.0.1", PortAssignment.unique()),
- new InetSocketAddress("127.0.0.1", PortAssignment.unique())));
+ peers.put(0L, new QuorumPeer.QuorumServer(0, new InetSocketAddress("127.0.0.1", PortAssignment.unique()), new InetSocketAddress("127.0.0.1", PortAssignment.unique()), new InetSocketAddress("127.0.0.1", PortAssignment.unique())));
+ peers.put(1L, new QuorumPeer.QuorumServer(1, new InetSocketAddress("127.0.0.1", PortAssignment.unique()), new InetSocketAddress("127.0.0.1", PortAssignment.unique()), new InetSocketAddress("127.0.0.1", PortAssignment.unique())));
+ peers.put(2L, new QuorumPeer.QuorumServer(2, new InetSocketAddress("127.0.0.1", PortAssignment.unique()), new InetSocketAddress("127.0.0.1", PortAssignment.unique()), new InetSocketAddress("127.0.0.1", PortAssignment.unique())));
peer.setQuorumVerifier(new QuorumMaj(peers), false);
peer.setCnxnFactory(new NullServerCnxnFactory());
@@ -76,20 +66,17 @@ public class ZabUtils {
return peer;
}
- public static Leader createLeader(File tmpDir, QuorumPeer peer)
- throws IOException, NoSuchFieldException, IllegalAccessException, X509Exception {
+ public static Leader createLeader(File tmpDir, QuorumPeer peer) throws IOException, NoSuchFieldException, IllegalAccessException, X509Exception {
LeaderZooKeeperServer zk = prepareLeader(tmpDir, peer);
return new Leader(peer, zk);
}
- public static Leader createMockLeader(File tmpDir, QuorumPeer peer)
- throws IOException, NoSuchFieldException, IllegalAccessException, X509Exception {
+ public static Leader createMockLeader(File tmpDir, QuorumPeer peer) throws IOException, NoSuchFieldException, IllegalAccessException, X509Exception {
LeaderZooKeeperServer zk = prepareLeader(tmpDir, peer);
return new MockLeader(peer, zk);
}
- private static LeaderZooKeeperServer prepareLeader(File tmpDir, QuorumPeer peer)
- throws IOException, NoSuchFieldException, IllegalAccessException {
+ private static LeaderZooKeeperServer prepareLeader(File tmpDir, QuorumPeer peer) throws IOException, NoSuchFieldException, IllegalAccessException {
FileTxnSnapLog logFactory = new FileTxnSnapLog(tmpDir, tmpDir);
peer.setTxnFactory(logFactory);
ZKDatabase zkDb = new ZKDatabase(logFactory);
@@ -98,8 +85,8 @@ public class ZabUtils {
}
private static final class NullServerCnxnFactory extends ServerCnxnFactory {
- public void startup(ZooKeeperServer zkServer, boolean startServer)
- throws IOException, InterruptedException {
+
+ public void startup(ZooKeeperServer zkServer, boolean startServer) throws IOException, InterruptedException {
}
public void start() {
}
@@ -124,8 +111,7 @@ public class ZabUtils {
public Iterable<ServerCnxn> getConnections() {
return null;
}
- public void configure(InetSocketAddress addr, int maxcc, int listenBacklog,
- boolean secure) throws IOException {
+ public void configure(InetSocketAddress addr, int maxcc, int listenBacklog, boolean secure) throws IOException {
}
@Override
@@ -149,12 +135,12 @@ public class ZabUtils {
public Iterable<Map<String, Object>> getAllConnectionInfo(boolean brief) {
return null;
}
+
}
public static final class MockLeader extends Leader {
- MockLeader(QuorumPeer qp, LeaderZooKeeperServer zk)
- throws IOException, X509Exception {
+ MockLeader(QuorumPeer qp, LeaderZooKeeperServer zk) throws IOException, X509Exception {
super(qp, zk);
}
@@ -168,5 +154,7 @@ public class ZabUtils {
public long getCurrentEpochToPropose() {
return epoch;
}
+
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/auth/KerberosSecurityTestcase.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/auth/KerberosSecurityTestcase.java
index 9617c70b3..cc6af7be5 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/auth/KerberosSecurityTestcase.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/auth/KerberosSecurityTestcase.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -15,18 +15,17 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package org.apache.zookeeper.server.quorum.auth;
-import org.apache.commons.io.FileUtils;
-import org.junit.After;
-import org.junit.AfterClass;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.BeforeClass;
+package org.apache.zookeeper.server.quorum.auth;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.IOException;
import java.util.Properties;
+import org.apache.commons.io.FileUtils;
+import org.junit.AfterClass;
+import org.junit.BeforeClass;
/*
* This code is originally from HDFS, see the similarly named file there
@@ -47,6 +46,7 @@ import java.util.Properties;
* createMiniKdcConf() to provide new settings.
*/
public class KerberosSecurityTestcase extends QuorumAuthTestBase {
+
private static MiniKdc kdc;
private static File workDir;
private static Properties conf;
@@ -78,8 +78,7 @@ public class KerberosSecurityTestcase extends QuorumAuthTestBase {
* @throws IOException
*/
public static void createTestDir() throws IOException {
- workDir = createTmpDir(
- new File(System.getProperty("build.test.dir", "build")));
+ workDir = createTmpDir(new File(System.getProperty("build.test.dir", "build")));
}
static File createTmpDir(File parentDir) throws IOException {
@@ -88,8 +87,8 @@ public class KerberosSecurityTestcase extends QuorumAuthTestBase {
// a tmpDir with a duplicate name
File tmpDir = new File(tmpFile + ".dir");
// never true if tmpfile does it's job
- Assert.assertFalse(tmpDir.exists());
- Assert.assertTrue(tmpDir.mkdirs());
+ assertFalse(tmpDir.exists());
+ assertTrue(tmpDir.mkdirs());
return tmpDir;
}
@@ -117,4 +116,5 @@ public class KerberosSecurityTestcase extends QuorumAuthTestBase {
public static Properties getConf() {
return conf;
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/auth/KerberosTestUtils.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/auth/KerberosTestUtils.java
index 41609fa77..30dd3e4db 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/auth/KerberosTestUtils.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/auth/KerberosTestUtils.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -20,12 +20,11 @@ package org.apache.zookeeper.server.quorum.auth;
import java.io.File;
import java.util.UUID;
-
import org.apache.zookeeper.util.SecurityUtils;
public class KerberosTestUtils {
- private static String keytabFile = new File(System.getProperty("build.test.dir", "build"), UUID.randomUUID().toString())
- .getAbsolutePath();
+
+ private static String keytabFile = new File(System.getProperty("build.test.dir", "build"), UUID.randomUUID().toString()).getAbsolutePath();
public static String getRealm() {
return "EXAMPLE.COM";
@@ -57,8 +56,9 @@ public class KerberosTestUtils {
public static String replaceHostPattern(String principal) {
String[] components = principal.split("[/@]");
- if (components == null || components.length < 2
- || !components[1].equals(SecurityUtils.QUORUM_HOSTNAME_PATTERN)) {
+ if (components == null
+ || components.length < 2
+ || !components[1].equals(SecurityUtils.QUORUM_HOSTNAME_PATTERN)) {
return principal;
} else {
return replacePattern(components, "localhost");
@@ -67,10 +67,10 @@ public class KerberosTestUtils {
public static String replacePattern(String[] components, String hostname) {
if (components.length == 3) {
- return components[0] + "/" + hostname.toLowerCase() + "@"
- + components[2];
+ return components[0] + "/" + hostname.toLowerCase() + "@" + components[2];
} else {
return components[0] + "/" + hostname.toLowerCase();
}
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/auth/MiniKdc.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/auth/MiniKdc.java
index 244735ee1..56902d778 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/auth/MiniKdc.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/auth/MiniKdc.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -17,20 +17,12 @@
*/
package org.apache.zookeeper.server.quorum.auth;
-import org.apache.kerby.kerberos.kerb.KrbException;
-import org.apache.kerby.kerberos.kerb.server.KdcConfigKey;
-import org.apache.kerby.kerberos.kerb.server.SimpleKdcServer;
-import org.apache.kerby.util.IOUtil;
-import org.apache.kerby.util.NetworkUtil;
-import org.apache.zookeeper.server.ExitCode;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.FileInputStream;
+import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
-import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.HashSet;
@@ -38,6 +30,14 @@ import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
+import org.apache.kerby.kerberos.kerb.KrbException;
+import org.apache.kerby.kerberos.kerb.server.KdcConfigKey;
+import org.apache.kerby.kerberos.kerb.server.SimpleKdcServer;
+import org.apache.kerby.util.IOUtil;
+import org.apache.kerby.util.NetworkUtil;
+import org.apache.zookeeper.server.ExitCode;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/**
* Mini KDC based on Apache Directory Server that can be embedded in testcases
@@ -78,27 +78,22 @@ import java.util.Set;
*/
public class MiniKdc {
- public static final String JAVA_SECURITY_KRB5_CONF =
- "java.security.krb5.conf";
- public static final String SUN_SECURITY_KRB5_DEBUG =
- "sun.security.krb5.debug";
+ public static final String JAVA_SECURITY_KRB5_CONF = "java.security.krb5.conf";
+ public static final String SUN_SECURITY_KRB5_DEBUG = "sun.security.krb5.debug";
public static void main(String[] args) throws Exception {
if (args.length < 4) {
- System.out.println("Arguments: <WORKDIR> <MINIKDCPROPERTIES> " +
- "<KEYTABFILE> [<PRINCIPALS>]+");
+ System.out.println("Arguments: <WORKDIR> <MINIKDCPROPERTIES> " + "<KEYTABFILE> [<PRINCIPALS>]+");
System.exit(ExitCode.UNEXPECTED_ERROR.getValue());
}
File workDir = new File(args[0]);
if (!workDir.exists()) {
- throw new RuntimeException("Specified work directory does not exists: "
- + workDir.getAbsolutePath());
+ throw new RuntimeException("Specified work directory does not exists: " + workDir.getAbsolutePath());
}
Properties conf = createConf();
File file = new File(args[1]);
if (!file.exists()) {
- throw new RuntimeException("Specified configuration does not exists: "
- + file.getAbsolutePath());
+ throw new RuntimeException("Specified configuration does not exists: " + file.getAbsolutePath());
}
Properties userConf = new Properties();
InputStreamReader r = null;
@@ -125,8 +120,7 @@ public class MiniKdc {
System.out.println("Standalone MiniKdc Running");
System.out.println("---------------------------------------------------");
System.out.println(" Realm : " + miniKdc.getRealm());
- System.out.println(" Running at : " + miniKdc.getHost() + ":" +
- miniKdc.getHost());
+ System.out.println(" Running at : " + miniKdc.getHost() + ":" + miniKdc.getHost());
System.out.println(" krb5conf : " + krb5conf);
System.out.println();
System.out.println(" created keytab : " + keytabFile);
@@ -142,8 +136,7 @@ public class MiniKdc {
}
});
} else {
- throw new RuntimeException("Cannot rename KDC's krb5conf to "
- + krb5conf.getAbsolutePath());
+ throw new RuntimeException("Cannot rename KDC's krb5conf to " + krb5conf.getAbsolutePath());
}
}
@@ -220,12 +213,10 @@ public class MiniKdc {
if (!conf.keySet().containsAll(PROPERTIES)) {
Set<String> missingProperties = new HashSet<String>(PROPERTIES);
missingProperties.removeAll(conf.keySet());
- throw new IllegalArgumentException("Missing configuration properties: "
- + missingProperties);
+ throw new IllegalArgumentException("Missing configuration properties: " + missingProperties);
}
this.workDir = new File(workDir, Long.toString(System.currentTimeMillis()));
- if (!this.workDir.exists()
- && !this.workDir.mkdirs()) {
+ if (!this.workDir.exists() && !this.workDir.mkdirs()) {
throw new RuntimeException("Cannot create directory " + this.workDir);
}
LOG.info("Configuration:");
@@ -236,10 +227,9 @@ public class MiniKdc {
LOG.info("---------------------------------------------------------------");
this.conf = conf;
port = Integer.parseInt(conf.getProperty(KDC_PORT));
- String orgName= conf.getProperty(ORG_NAME);
+ String orgName = conf.getProperty(ORG_NAME);
String orgDomain = conf.getProperty(ORG_DOMAIN);
- realm = orgName.toUpperCase(Locale.ENGLISH) + "."
- + orgDomain.toUpperCase(Locale.ENGLISH);
+ realm = orgName.toUpperCase(Locale.ENGLISH) + "." + orgDomain.toUpperCase(Locale.ENGLISH);
}
/**
@@ -292,11 +282,9 @@ public class MiniKdc {
}
private void resetDefaultRealm() throws IOException {
- InputStream templateResource = new FileInputStream(
- getKrb5conf().getAbsolutePath());
+ InputStream templateResource = new FileInputStream(getKrb5conf().getAbsolutePath());
String content = IOUtil.readInput(templateResource);
- content = content.replaceAll("default_realm = .*\n",
- "default_realm = " + getRealm() + "\n");
+ content = content.replaceAll("default_realm = .*\n", "default_realm = " + getRealm() + "\n");
IOUtil.writeFile(content, getKrb5conf());
}
@@ -324,8 +312,7 @@ public class MiniKdc {
} else {
throw new IllegalArgumentException("Need to set transport!");
}
- simpleKdc.getKdcConfig().setString(KdcConfigKey.KDC_SERVICE_NAME,
- conf.getProperty(INSTANCE));
+ simpleKdc.getKdcConfig().setString(KdcConfigKey.KDC_SERVICE_NAME, conf.getProperty(INSTANCE));
if (conf.getProperty(DEBUG) != null) {
krb5Debug = getAndSet(SUN_SECURITY_KRB5_DEBUG, conf.getProperty(DEBUG));
}
@@ -341,9 +328,8 @@ public class MiniKdc {
} catch (KrbException e) {
e.printStackTrace();
} finally {
- if(conf.getProperty(DEBUG) != null) {
- System.setProperty(SUN_SECURITY_KRB5_DEBUG,
- Boolean.toString(krb5Debug));
+ if (conf.getProperty(DEBUG) != null) {
+ System.setProperty(SUN_SECURITY_KRB5_DEBUG, Boolean.toString(krb5Debug));
}
}
}
@@ -359,14 +345,14 @@ public class MiniKdc {
private void delete(File f) {
if (f.isFile()) {
- if (! f.delete()) {
+ if (!f.delete()) {
LOG.warn("WARNING: cannot delete file " + f.getAbsolutePath());
}
} else {
- for (File c: f.listFiles()) {
+ for (File c : f.listFiles()) {
delete(c);
}
- if (! f.delete()) {
+ if (!f.delete()) {
LOG.warn("WARNING: cannot delete directory " + f.getAbsolutePath());
}
}
@@ -379,8 +365,7 @@ public class MiniKdc {
* @param password password.
* @throws Exception thrown if the principal could not be created.
*/
- public synchronized void createPrincipal(String principal, String password)
- throws Exception {
+ public synchronized void createPrincipal(String principal, String password) throws Exception {
simpleKdc.createPrincipal(principal, password);
}
@@ -392,9 +377,7 @@ public class MiniKdc {
* @throws Exception thrown if the principals or the keytab file could not be
* created.
*/
- public synchronized void createPrincipal(File keytabFile,
- String ... principals)
- throws Exception {
+ public synchronized void createPrincipal(File keytabFile, String... principals) throws Exception {
simpleKdc.createPrincipals(principals);
if (keytabFile.exists() && !keytabFile.delete()) {
LOG.error("Failed to delete keytab file: " + keytabFile);
@@ -416,4 +399,5 @@ public class MiniKdc {
System.setProperty(sysprop, debug);
return old;
}
-} \ No newline at end of file
+
+}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/auth/MiniKdcTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/auth/MiniKdcTest.java
index 69dbcd1e5..659551558 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/auth/MiniKdcTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/auth/MiniKdcTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,24 +18,24 @@
package org.apache.zookeeper.server.quorum.auth;
-import org.apache.kerby.kerberos.kerb.keytab.Keytab;
-import org.apache.kerby.kerberos.kerb.type.base.PrincipalName;
-import org.junit.Assert;
-import org.junit.Test;
-
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotSame;
+import java.io.File;
+import java.security.Principal;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
import javax.security.auth.Subject;
import javax.security.auth.kerberos.KerberosPrincipal;
import javax.security.auth.login.AppConfigurationEntry;
import javax.security.auth.login.Configuration;
import javax.security.auth.login.LoginContext;
-import java.io.File;
-import java.security.Principal;
-import java.util.List;
-import java.util.Set;
-import java.util.Map;
-import java.util.HashSet;
-import java.util.HashMap;
-import java.util.Arrays;
+import org.apache.kerby.kerberos.kerb.keytab.Keytab;
+import org.apache.kerby.kerberos.kerb.type.base.PrincipalName;
+import org.junit.Test;
/*
* This code is originally from HDFS, see the file name TestMiniKdc there
@@ -45,13 +45,13 @@ import java.util.Arrays;
* Github Revision: 916140604ffef59466ba30832478311d3e6249bd
*/
public class MiniKdcTest extends KerberosSecurityTestcase {
- private static final boolean IBM_JAVA = System.getProperty("java.vendor")
- .contains("IBM");
+
+ private static final boolean IBM_JAVA = System.getProperty("java.vendor").contains("IBM");
@Test(timeout = 60000)
public void testMiniKdcStart() {
MiniKdc kdc = getKdc();
- Assert.assertNotSame(0, kdc.getPort());
+ assertNotSame(0, kdc.getPort());
}
@Test(timeout = 60000)
@@ -60,45 +60,42 @@ public class MiniKdcTest extends KerberosSecurityTestcase {
File workDir = getWorkDir();
kdc.createPrincipal(new File(workDir, "keytab"), "foo/bar", "bar/foo");
- List<PrincipalName> principalNameList =
- Keytab.loadKeytab(new File(workDir, "keytab")).getPrincipals();
+ List<PrincipalName> principalNameList = Keytab.loadKeytab(new File(workDir, "keytab")).getPrincipals();
Set<String> principals = new HashSet<String>();
for (PrincipalName principalName : principalNameList) {
- principals.add(principalName.getName());
+ principals.add(principalName.getName());
}
- Assert.assertEquals(new HashSet<String>(Arrays.asList(
- "foo/bar@" + kdc.getRealm(), "bar/foo@" + kdc.getRealm())),
- principals);
- }
+ assertEquals(
+ new HashSet<>(Arrays.asList("foo/bar@" + kdc.getRealm(), "bar/foo@" + kdc.getRealm())),
+ principals);
+ }
private static class KerberosConfiguration extends Configuration {
+
private String principal;
private String keytab;
private boolean isInitiator;
- private KerberosConfiguration(String principal, File keytab,
- boolean client) {
+ private KerberosConfiguration(String principal, File keytab, boolean client) {
this.principal = principal;
this.keytab = keytab.getAbsolutePath();
this.isInitiator = client;
}
- public static Configuration createClientConfig(String principal,
- File keytab) {
+ public static Configuration createClientConfig(String principal, File keytab) {
return new KerberosConfiguration(principal, keytab, true);
}
- public static Configuration createServerConfig(String principal,
- File keytab) {
+ public static Configuration createServerConfig(String principal, File keytab) {
return new KerberosConfiguration(principal, keytab, false);
}
private static String getKrb5LoginModuleName() {
return System.getProperty("java.vendor").contains("IBM")
- ? "com.ibm.security.auth.module.Krb5LoginModule"
- : "com.sun.security.auth.module.Krb5LoginModule";
+ ? "com.ibm.security.auth.module.Krb5LoginModule"
+ : "com.sun.security.auth.module.Krb5LoginModule";
}
@Override
@@ -124,11 +121,9 @@ public class MiniKdcTest extends KerberosSecurityTestcase {
}
options.put("debug", "true");
- return new AppConfigurationEntry[] {
- new AppConfigurationEntry(getKrb5LoginModuleName(),
- AppConfigurationEntry.LoginModuleControlFlag.REQUIRED,
- options) };
+ return new AppConfigurationEntry[]{new AppConfigurationEntry(getKrb5LoginModuleName(), AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, options)};
}
+
}
@Test(timeout = 60000)
@@ -145,38 +140,29 @@ public class MiniKdcTest extends KerberosSecurityTestcase {
principals.add(new KerberosPrincipal(principal));
// client login
- Subject subject = new Subject(false, principals,
- new HashSet<Object>(), new HashSet<Object>());
- loginContext = new LoginContext("", subject, null,
- KerberosConfiguration.createClientConfig(principal,
- keytab));
+ Subject subject = new Subject(false, principals, new HashSet<Object>(), new HashSet<Object>());
+ loginContext = new LoginContext("", subject, null, KerberosConfiguration.createClientConfig(principal, keytab));
loginContext.login();
subject = loginContext.getSubject();
- Assert.assertEquals(1, subject.getPrincipals().size());
- Assert.assertEquals(KerberosPrincipal.class,
- subject.getPrincipals().iterator().next().getClass());
- Assert.assertEquals(principal + "@" + kdc.getRealm(),
- subject.getPrincipals().iterator().next().getName());
+ assertEquals(1, subject.getPrincipals().size());
+ assertEquals(KerberosPrincipal.class, subject.getPrincipals().iterator().next().getClass());
+ assertEquals(principal + "@" + kdc.getRealm(), subject.getPrincipals().iterator().next().getName());
loginContext.logout();
// server login
- subject = new Subject(false, principals, new HashSet<Object>(),
- new HashSet<Object>());
- loginContext = new LoginContext("", subject, null,
- KerberosConfiguration.createServerConfig(principal,
- keytab));
+ subject = new Subject(false, principals, new HashSet<Object>(), new HashSet<Object>());
+ loginContext = new LoginContext("", subject, null, KerberosConfiguration.createServerConfig(principal, keytab));
loginContext.login();
subject = loginContext.getSubject();
- Assert.assertEquals(1, subject.getPrincipals().size());
- Assert.assertEquals(KerberosPrincipal.class,
- subject.getPrincipals().iterator().next().getClass());
- Assert.assertEquals(principal + "@" + kdc.getRealm(),
- subject.getPrincipals().iterator().next().getName());
+ assertEquals(1, subject.getPrincipals().size());
+ assertEquals(KerberosPrincipal.class, subject.getPrincipals().iterator().next().getClass());
+ assertEquals(principal + "@" + kdc.getRealm(), subject.getPrincipals().iterator().next().getName());
loginContext.logout();
} finally {
- if (loginContext != null && loginContext.getSubject() != null
- && !loginContext.getSubject().getPrincipals().isEmpty()) {
+ if (loginContext != null
+ && loginContext.getSubject() != null
+ && !loginContext.getSubject().getPrincipals().isEmpty()) {
loginContext.logout();
}
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/auth/QuorumAuthTestBase.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/auth/QuorumAuthTestBase.java
index 8978d170f..db5d39da6 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/auth/QuorumAuthTestBase.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/auth/QuorumAuthTestBase.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,19 +18,18 @@
package org.apache.zookeeper.server.quorum.auth;
+import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
-
import org.apache.commons.io.FileUtils;
import org.apache.zookeeper.PortAssignment;
import org.apache.zookeeper.ZKTestCase;
import org.apache.zookeeper.server.quorum.QuorumPeerTestBase.MainThread;
import org.apache.zookeeper.test.ClientBase;
-import org.junit.Assert;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -39,6 +38,7 @@ import org.slf4j.LoggerFactory;
* authentication using SASL mechanisms.
*/
public class QuorumAuthTestBase extends ZKTestCase {
+
protected static final Logger LOG = LoggerFactory.getLogger(QuorumAuthTestBase.class);
protected List<MainThread> mt = new ArrayList<MainThread>();
protected static File jaasConfigDir;
@@ -50,8 +50,7 @@ public class QuorumAuthTestBase extends ZKTestCase {
FileWriter fwriter = new FileWriter(saslConfFile);
fwriter.write(jaasEntries);
fwriter.close();
- System.setProperty("java.security.auth.login.config",
- saslConfFile.getAbsolutePath());
+ System.setProperty("java.security.auth.login.config", saslConfFile.getAbsolutePath());
} catch (IOException ioe) {
LOG.error("Failed to create tmp directory to hold JAAS conf file", ioe);
// could not create tmp directory to hold JAAS conf file : test will
@@ -65,28 +64,30 @@ public class QuorumAuthTestBase extends ZKTestCase {
}
}
- protected String startQuorum(final int serverCount,
- Map<String, String> authConfigs, int authServerCount) throws IOException {
+ protected String startQuorum(
+ final int serverCount,
+ Map<String, String> authConfigs,
+ int authServerCount) throws IOException {
StringBuilder connectStr = new StringBuilder();
- final int[] clientPorts = startQuorum(serverCount, connectStr,
- authConfigs, authServerCount);
+ final int[] clientPorts = startQuorum(serverCount, connectStr, authConfigs, authServerCount);
for (int i = 0; i < serverCount; i++) {
- Assert.assertTrue("waiting for server " + i + " being up",
- ClientBase.waitForServerUp("127.0.0.1:" + clientPorts[i],
- ClientBase.CONNECTION_TIMEOUT));
+ assertTrue(
+ "waiting for server " + i + " being up",
+ ClientBase.waitForServerUp("127.0.0.1:" + clientPorts[i], ClientBase.CONNECTION_TIMEOUT));
}
return connectStr.toString();
}
- protected int[] startQuorum(final int serverCount, StringBuilder connectStr,
- Map<String, String> authConfigs, int authServerCount) throws IOException {
- final int clientPorts[] = new int[serverCount];
+ protected int[] startQuorum(
+ final int serverCount,
+ StringBuilder connectStr,
+ Map<String, String> authConfigs,
+ int authServerCount) throws IOException {
+ final int[] clientPorts = new int[serverCount];
StringBuilder sb = new StringBuilder();
for (int i = 0; i < serverCount; i++) {
clientPorts[i] = PortAssignment.unique();
- String server = String.format(
- "server.%d=localhost:%d:%d:participant", i,
- PortAssignment.unique(), PortAssignment.unique());
+ String server = String.format("server.%d=localhost:%d:%d:participant", i, PortAssignment.unique(), PortAssignment.unique());
sb.append(server + "\n");
connectStr.append("127.0.0.1:" + clientPorts[i]);
if (i < serverCount - 1) {
@@ -108,20 +109,18 @@ public class QuorumAuthTestBase extends ZKTestCase {
return clientPorts;
}
- private void startServer(Map<String, String> authConfigs,
- final int[] clientPorts, String quorumCfg, int i)
- throws IOException {
- MainThread mthread = new MainThread(i, clientPorts[i], quorumCfg,
- authConfigs);
+ private void startServer(
+ Map<String, String> authConfigs,
+ final int[] clientPorts,
+ String quorumCfg,
+ int i) throws IOException {
+ MainThread mthread = new MainThread(i, clientPorts[i], quorumCfg, authConfigs);
mt.add(mthread);
mthread.start();
}
- protected void startServer(MainThread restartPeer,
- Map<String, String> authConfigs) throws IOException {
- MainThread mthread = new MainThread(restartPeer.getMyid(),
- restartPeer.getClientPort(), restartPeer.getQuorumCfgSection(),
- authConfigs);
+ protected void startServer(MainThread restartPeer, Map<String, String> authConfigs) throws IOException {
+ MainThread mthread = new MainThread(restartPeer.getMyid(), restartPeer.getClientPort(), restartPeer.getQuorumCfgSection(), authConfigs);
mt.add(mthread);
mthread.start();
}
@@ -137,10 +136,12 @@ public class QuorumAuthTestBase extends ZKTestCase {
try {
mainThread.shutdown();
} catch (InterruptedException e) {
+ // no op
} finally {
mt.remove(index);
}
mainThread.deleteBaseDir();
return mainThread;
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/auth/QuorumAuthUpgradeTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/auth/QuorumAuthUpgradeTest.java
index c54accadc..05f5a88d6 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/auth/QuorumAuthUpgradeTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/auth/QuorumAuthUpgradeTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,22 +18,22 @@
package org.apache.zookeeper.server.quorum.auth;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeoutException;
-
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.server.quorum.QuorumPeerTestBase.MainThread;
import org.apache.zookeeper.test.ClientBase;
-import org.apache.zookeeper.test.ClientTest;
import org.apache.zookeeper.test.ClientBase.CountdownWatcher;
+import org.apache.zookeeper.test.ClientTest;
import org.junit.After;
import org.junit.AfterClass;
-import org.junit.Assert;
import org.junit.Test;
/**
@@ -52,14 +52,17 @@ import org.junit.Test;
* Now, all the servers are fully upgraded and running in secured mode.
*/
public class QuorumAuthUpgradeTest extends QuorumAuthTestBase {
+
static {
- String jaasEntries = new String("" + "QuorumServer {\n"
- + " org.apache.zookeeper.server.auth.DigestLoginModule required\n"
- + " user_test=\"mypassword\";\n" + "};\n"
- + "QuorumLearner {\n"
- + " org.apache.zookeeper.server.auth.DigestLoginModule required\n"
- + " username=\"test\"\n"
- + " password=\"mypassword\";\n" + "};\n");
+ String jaasEntries = "QuorumServer {\n"
+ + " org.apache.zookeeper.server.auth.DigestLoginModule required\n"
+ + " user_test=\"mypassword\";\n"
+ + "};\n"
+ + "QuorumLearner {\n"
+ + " org.apache.zookeeper.server.auth.DigestLoginModule required\n"
+ + " username=\"test\"\n"
+ + " password=\"mypassword\";\n"
+ + "};\n";
setupJaasConfig(jaasEntries);
}
@@ -85,11 +88,9 @@ public class QuorumAuthUpgradeTest extends QuorumAuthTestBase {
String connectStr = startQuorum(2, authConfigs, 0);
CountdownWatcher watcher = new CountdownWatcher();
- ZooKeeper zk = new ZooKeeper(connectStr, ClientBase.CONNECTION_TIMEOUT,
- watcher);
+ ZooKeeper zk = new ZooKeeper(connectStr, ClientBase.CONNECTION_TIMEOUT, watcher);
watcher.waitForConnected(ClientBase.CONNECTION_TIMEOUT);
- zk.create("/foo", new byte[0], Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk.create("/foo", new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
zk.close();
}
@@ -105,11 +106,9 @@ public class QuorumAuthUpgradeTest extends QuorumAuthTestBase {
String connectStr = startQuorum(2, authConfigs, 1);
CountdownWatcher watcher = new CountdownWatcher();
- ZooKeeper zk = new ZooKeeper(connectStr, ClientBase.CONNECTION_TIMEOUT,
- watcher);
+ ZooKeeper zk = new ZooKeeper(connectStr, ClientBase.CONNECTION_TIMEOUT, watcher);
watcher.waitForConnected(ClientBase.CONNECTION_TIMEOUT);
- zk.create("/foo", new byte[0], Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk.create("/foo", new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
zk.close();
}
@@ -125,11 +124,9 @@ public class QuorumAuthUpgradeTest extends QuorumAuthTestBase {
String connectStr = startQuorum(2, authConfigs, 2);
CountdownWatcher watcher = new CountdownWatcher();
- ZooKeeper zk = new ZooKeeper(connectStr, ClientBase.CONNECTION_TIMEOUT,
- watcher);
+ ZooKeeper zk = new ZooKeeper(connectStr, ClientBase.CONNECTION_TIMEOUT, watcher);
watcher.waitForConnected(ClientBase.CONNECTION_TIMEOUT);
- zk.create("/foo", new byte[0], Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk.create("/foo", new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
zk.close();
}
@@ -147,11 +144,9 @@ public class QuorumAuthUpgradeTest extends QuorumAuthTestBase {
String connectStr = startQuorum(2, authConfigs, 2);
CountdownWatcher watcher = new CountdownWatcher();
- ZooKeeper zk = new ZooKeeper(connectStr, ClientBase.CONNECTION_TIMEOUT,
- watcher);
+ ZooKeeper zk = new ZooKeeper(connectStr, ClientBase.CONNECTION_TIMEOUT, watcher);
watcher.waitForConnected(ClientBase.CONNECTION_TIMEOUT);
- zk.create("/foo", new byte[0], Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk.create("/foo", new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
zk.close();
}
@@ -180,11 +175,9 @@ public class QuorumAuthUpgradeTest extends QuorumAuthTestBase {
String connectStr = startQuorum(3, authConfigs, 0);
CountdownWatcher watcher = new CountdownWatcher();
- ZooKeeper zk = new ZooKeeper(connectStr, ClientBase.CONNECTION_TIMEOUT,
- watcher);
+ ZooKeeper zk = new ZooKeeper(connectStr, ClientBase.CONNECTION_TIMEOUT, watcher);
watcher.waitForConnected(ClientBase.CONNECTION_TIMEOUT);
- zk.create("/foo", new byte[0], Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT_SEQUENTIAL);
+ zk.create("/foo", new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL);
//1. Upgrade peer0,1,2 with quorum.auth.enableSasl=true and
// quorum.auth.learnerRequireSasl=false, quorum.auth.serverRequireSasl=false
@@ -219,21 +212,24 @@ public class QuorumAuthUpgradeTest extends QuorumAuthTestBase {
authConfigs.put(QuorumAuth.QUORUM_SASL_AUTH_ENABLED, "false");
MainThread m = shutdown(2);
startServer(m, authConfigs);
- Assert.assertFalse("waiting for server 2 being up", ClientBase
- .waitForServerUp("127.0.0.1:" + m.getClientPort(), 5000));
+ assertFalse(
+ "waiting for server 2 being up",
+ ClientBase.waitForServerUp("127.0.0.1:" + m.getClientPort(), 5000));
}
- private void restartServer(Map<String, String> authConfigs, int index,
- ZooKeeper zk, CountdownWatcher watcher) throws IOException,
- KeeperException, InterruptedException, TimeoutException {
+ private void restartServer(
+ Map<String, String> authConfigs,
+ int index,
+ ZooKeeper zk,
+ CountdownWatcher watcher) throws IOException, KeeperException, InterruptedException, TimeoutException {
LOG.info("Restarting server myid=" + index);
MainThread m = shutdown(index);
startServer(m, authConfigs);
- Assert.assertTrue("waiting for server" + index + "being up",
- ClientBase.waitForServerUp("127.0.0.1:" + m.getClientPort(),
- ClientBase.CONNECTION_TIMEOUT));
+ assertTrue(
+ "waiting for server" + index + "being up",
+ ClientBase.waitForServerUp("127.0.0.1:" + m.getClientPort(), ClientBase.CONNECTION_TIMEOUT));
watcher.waitForConnected(ClientTest.CONNECTION_TIMEOUT);
- zk.create("/foo", new byte[0], Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT_SEQUENTIAL);
+ zk.create("/foo", new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL);
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/auth/QuorumDigestAuthTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/auth/QuorumDigestAuthTest.java
index 5eebdb335..ed86607c4 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/auth/QuorumDigestAuthTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/auth/QuorumDigestAuthTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,41 +18,44 @@
package org.apache.zookeeper.server.quorum.auth;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.fail;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
-
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.PortAssignment;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.server.admin.AdminServer;
+import org.apache.zookeeper.server.quorum.QuorumPeerConfig.ConfigException;
import org.apache.zookeeper.server.quorum.QuorumPeerMain;
import org.apache.zookeeper.server.quorum.QuorumPeerTestBase;
-import org.apache.zookeeper.server.quorum.QuorumPeerConfig.ConfigException;
import org.apache.zookeeper.server.quorum.QuorumPeerTestBase.MainThread;
import org.apache.zookeeper.test.ClientBase;
import org.apache.zookeeper.test.ClientBase.CountdownWatcher;
import org.junit.After;
import org.junit.AfterClass;
-import org.junit.Assert;
import org.junit.Test;
public class QuorumDigestAuthTest extends QuorumAuthTestBase {
static {
- String jaasEntries = new String(""
- + "QuorumServer {\n"
- + " org.apache.zookeeper.server.auth.DigestLoginModule required\n"
- + " user_test=\"mypassword\";\n" + "};\n"
- + "QuorumLearner {\n"
- + " org.apache.zookeeper.server.auth.DigestLoginModule required\n"
- + " username=\"test\"\n"
- + " password=\"mypassword\";\n" + "};\n"
- + "QuorumLearnerInvalid {\n"
- + " org.apache.zookeeper.server.auth.DigestLoginModule required\n"
- + " username=\"test\"\n"
- + " password=\"invalid\";\n" + "};" + "\n");
+ String jaasEntries = "QuorumServer {\n"
+ + " org.apache.zookeeper.server.auth.DigestLoginModule required\n"
+ + " user_test=\"mypassword\";\n"
+ + "};\n"
+ + "QuorumLearner {\n"
+ + " org.apache.zookeeper.server.auth.DigestLoginModule required\n"
+ + " username=\"test\"\n"
+ + " password=\"mypassword\";\n"
+ + "};\n"
+ + "QuorumLearnerInvalid {\n"
+ + " org.apache.zookeeper.server.auth.DigestLoginModule required\n"
+ + " username=\"test\"\n"
+ + " password=\"invalid\";\n"
+ + "};"
+ + "\n";
setupJaasConfig(jaasEntries);
}
@@ -65,7 +68,7 @@ public class QuorumDigestAuthTest extends QuorumAuthTestBase {
}
@AfterClass
- public static void cleanup(){
+ public static void cleanup() {
cleanupJaasConfig();
}
@@ -81,12 +84,10 @@ public class QuorumDigestAuthTest extends QuorumAuthTestBase {
String connectStr = startQuorum(3, authConfigs, 3);
CountdownWatcher watcher = new CountdownWatcher();
- ZooKeeper zk = new ZooKeeper(connectStr, ClientBase.CONNECTION_TIMEOUT,
- watcher);
+ ZooKeeper zk = new ZooKeeper(connectStr, ClientBase.CONNECTION_TIMEOUT, watcher);
watcher.waitForConnected(ClientBase.CONNECTION_TIMEOUT);
for (int i = 0; i < 10; i++) {
- zk.create("/" + i, new byte[0], Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk.create("/" + i, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
}
zk.close();
}
@@ -104,12 +105,10 @@ public class QuorumDigestAuthTest extends QuorumAuthTestBase {
authConfigs.put(QuorumAuth.QUORUM_SERVER_SASL_AUTH_REQUIRED, "false");
String connectStr = startQuorum(3, authConfigs, 3);
CountdownWatcher watcher = new CountdownWatcher();
- ZooKeeper zk = new ZooKeeper(connectStr, ClientBase.CONNECTION_TIMEOUT,
- watcher);
+ ZooKeeper zk = new ZooKeeper(connectStr, ClientBase.CONNECTION_TIMEOUT, watcher);
watcher.waitForConnected(ClientBase.CONNECTION_TIMEOUT);
for (int i = 0; i < 10; i++) {
- zk.create("/" + i, new byte[0], Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk.create("/" + i, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
}
zk.close();
}
@@ -127,13 +126,10 @@ public class QuorumDigestAuthTest extends QuorumAuthTestBase {
authConfigs.put(QuorumAuth.QUORUM_SERVER_SASL_AUTH_REQUIRED, "true");
authConfigs.put(QuorumAuth.QUORUM_LEARNER_SASL_AUTH_REQUIRED, "true");
int serverCount = 2;
- final int[] clientPorts = startQuorum(serverCount, new StringBuilder(),
- authConfigs, serverCount);
+ final int[] clientPorts = startQuorum(serverCount, new StringBuilder(), authConfigs, serverCount);
for (int i = 0; i < serverCount; i++) {
- boolean waitForServerUp = ClientBase.waitForServerUp(
- "127.0.0.1:" + clientPorts[i], QuorumPeerTestBase.TIMEOUT);
- Assert.assertFalse("Shouldn't start server with invalid credentials",
- waitForServerUp);
+ boolean waitForServerUp = ClientBase.waitForServerUp("127.0.0.1:" + clientPorts[i], QuorumPeerTestBase.TIMEOUT);
+ assertFalse("Shouldn't start server with invalid credentials", waitForServerUp);
}
}
@@ -143,62 +139,53 @@ public class QuorumDigestAuthTest extends QuorumAuthTestBase {
* enabled while enabling quorum server require sasl.
*/
@Test(timeout = 10000)
- public void testEnableQuorumServerRequireSaslWithoutQuorumLearnerRequireSasl()
- throws Exception {
+ public void testEnableQuorumServerRequireSaslWithoutQuorumLearnerRequireSasl() throws Exception {
Map<String, String> authConfigs = new HashMap<String, String>();
- authConfigs.put(QuorumAuth.QUORUM_LEARNER_SASL_LOGIN_CONTEXT,
- "QuorumLearner");
+ authConfigs.put(QuorumAuth.QUORUM_LEARNER_SASL_LOGIN_CONTEXT, "QuorumLearner");
authConfigs.put(QuorumAuth.QUORUM_SASL_AUTH_ENABLED, "true");
authConfigs.put(QuorumAuth.QUORUM_SERVER_SASL_AUTH_REQUIRED, "true");
authConfigs.put(QuorumAuth.QUORUM_LEARNER_SASL_AUTH_REQUIRED, "false");
- MainThread mthread = new MainThread(1, PortAssignment.unique(), "",
- authConfigs);
- String args[] = new String[1];
+ MainThread mthread = new MainThread(1, PortAssignment.unique(), "", authConfigs);
+ String[] args = new String[1];
args[0] = mthread.getConfFile().toString();
try {
new QuorumPeerMain() {
@Override
- protected void initializeAndRun(String[] args)
- throws ConfigException, IOException, AdminServer.AdminServerException {
+ protected void initializeAndRun(String[] args) throws ConfigException, IOException, AdminServer.AdminServerException {
super.initializeAndRun(args);
}
}.initializeAndRun(args);
- Assert.fail("Must throw exception as quorumpeer learner is not enabled!");
+ fail("Must throw exception as quorumpeer learner is not enabled!");
} catch (ConfigException e) {
// expected
}
}
-
/**
* If quorumpeer learner is not auth enabled then self won't be able to join
* quorum. So this test is ensuring that the quorumpeer learner is also auth
* enabled while enabling quorum server require sasl.
*/
@Test(timeout = 10000)
- public void testEnableQuorumAuthenticationConfigurations()
- throws Exception {
+ public void testEnableQuorumAuthenticationConfigurations() throws Exception {
Map<String, String> authConfigs = new HashMap<String, String>();
- authConfigs.put(QuorumAuth.QUORUM_LEARNER_SASL_LOGIN_CONTEXT,
- "QuorumLearner");
+ authConfigs.put(QuorumAuth.QUORUM_LEARNER_SASL_LOGIN_CONTEXT, "QuorumLearner");
authConfigs.put(QuorumAuth.QUORUM_SASL_AUTH_ENABLED, "false");
// case-1) 'quorum.auth.enableSasl' is off. Tries to enable server sasl.
authConfigs.put(QuorumAuth.QUORUM_SERVER_SASL_AUTH_REQUIRED, "true");
authConfigs.put(QuorumAuth.QUORUM_LEARNER_SASL_AUTH_REQUIRED, "false");
- MainThread mthread = new MainThread(1, PortAssignment.unique(), "",
- authConfigs);
- String args[] = new String[1];
+ MainThread mthread = new MainThread(1, PortAssignment.unique(), "", authConfigs);
+ String[] args = new String[1];
args[0] = mthread.getConfFile().toString();
try {
new QuorumPeerMain() {
@Override
- protected void initializeAndRun(String[] args)
- throws ConfigException, IOException, AdminServer.AdminServerException {
+ protected void initializeAndRun(String[] args) throws ConfigException, IOException, AdminServer.AdminServerException {
super.initializeAndRun(args);
}
}.initializeAndRun(args);
- Assert.fail("Must throw exception as quorum sasl is not enabled!");
+ fail("Must throw exception as quorum sasl is not enabled!");
} catch (ConfigException e) {
// expected
}
@@ -209,14 +196,14 @@ public class QuorumDigestAuthTest extends QuorumAuthTestBase {
try {
new QuorumPeerMain() {
@Override
- protected void initializeAndRun(String[] args)
- throws ConfigException, IOException, AdminServer.AdminServerException {
+ protected void initializeAndRun(String[] args) throws ConfigException, IOException, AdminServer.AdminServerException {
super.initializeAndRun(args);
}
}.initializeAndRun(args);
- Assert.fail("Must throw exception as quorum sasl is not enabled!");
+ fail("Must throw exception as quorum sasl is not enabled!");
} catch (ConfigException e) {
// expected
}
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/auth/QuorumKerberosAuthTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/auth/QuorumKerberosAuthTest.java
index 2cc56a767..092d04353 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/auth/QuorumKerberosAuthTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/auth/QuorumKerberosAuthTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -21,7 +21,6 @@ package org.apache.zookeeper.server.quorum.auth;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
-
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.zookeeper.CreateMode;
@@ -36,26 +35,38 @@ import org.junit.Before;
import org.junit.Test;
public class QuorumKerberosAuthTest extends KerberosSecurityTestcase {
+
private static File keytabFile;
+
static {
String keytabFilePath = FilenameUtils.normalize(KerberosTestUtils.getKeytabFile(), true);
- String jaasEntries = new String(""
- + "QuorumServer {\n"
- + " com.sun.security.auth.module.Krb5LoginModule required\n"
- + " useKeyTab=true\n"
- + " keyTab=\"" + keytabFilePath + "\"\n"
- + " storeKey=true\n"
- + " useTicketCache=false\n"
- + " debug=false\n"
- + " principal=\"" + KerberosTestUtils.getServerPrincipal() + "\";\n" + "};\n"
- + "QuorumLearner {\n"
- + " com.sun.security.auth.module.Krb5LoginModule required\n"
- + " useKeyTab=true\n"
- + " keyTab=\"" + keytabFilePath + "\"\n"
- + " storeKey=true\n"
- + " useTicketCache=false\n"
- + " debug=false\n"
- + " principal=\"" + KerberosTestUtils.getLearnerPrincipal() + "\";\n" + "};\n");
+ String jaasEntries = ""
+ + "QuorumServer {\n"
+ + " com.sun.security.auth.module.Krb5LoginModule required\n"
+ + " useKeyTab=true\n"
+ + " keyTab=\""
+ + keytabFilePath
+ + "\"\n"
+ + " storeKey=true\n"
+ + " useTicketCache=false\n"
+ + " debug=false\n"
+ + " principal=\""
+ + KerberosTestUtils.getServerPrincipal()
+ + "\";\n"
+ + "};\n"
+ + "QuorumLearner {\n"
+ + " com.sun.security.auth.module.Krb5LoginModule required\n"
+ + " useKeyTab=true\n"
+ + " keyTab=\""
+ + keytabFilePath
+ + "\"\n"
+ + " storeKey=true\n"
+ + " useTicketCache=false\n"
+ + " debug=false\n"
+ + " principal=\""
+ + KerberosTestUtils.getLearnerPrincipal()
+ + "\";\n"
+ + "};\n";
setupJaasConfig(jaasEntries);
}
@@ -80,7 +91,7 @@ public class QuorumKerberosAuthTest extends KerberosSecurityTestcase {
@AfterClass
public static void cleanup() {
- if(keytabFile != null){
+ if (keytabFile != null) {
FileUtils.deleteQuietly(keytabFile);
}
cleanupJaasConfig();
@@ -107,4 +118,5 @@ public class QuorumKerberosAuthTest extends KerberosSecurityTestcase {
}
zk.close();
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/auth/QuorumKerberosHostBasedAuthTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/auth/QuorumKerberosHostBasedAuthTest.java
index b38462b04..574bfe4ee 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/auth/QuorumKerberosHostBasedAuthTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/quorum/auth/QuorumKerberosHostBasedAuthTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,11 +18,11 @@
package org.apache.zookeeper.server.quorum.auth;
+import static org.junit.Assert.fail;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeoutException;
-
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.zookeeper.CreateMode;
@@ -34,47 +34,58 @@ import org.apache.zookeeper.test.ClientBase;
import org.apache.zookeeper.test.ClientBase.CountdownWatcher;
import org.junit.After;
import org.junit.AfterClass;
-import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
public class QuorumKerberosHostBasedAuthTest extends KerberosSecurityTestcase {
+
private static File keytabFile;
private static String hostServerPrincipal = KerberosTestUtils.getHostServerPrincipal();
private static String hostLearnerPrincipal = KerberosTestUtils.getHostLearnerPrincipal();
private static String hostNamedLearnerPrincipal = KerberosTestUtils.getHostNamedLearnerPrincipal("myHost");
+
static {
setupJaasConfigEntries(hostServerPrincipal, hostLearnerPrincipal, hostNamedLearnerPrincipal);
}
- private static void setupJaasConfigEntries(String hostServerPrincipal,
- String hostLearnerPrincipal, String hostNamedLearnerPrincipal) {
+ private static void setupJaasConfigEntries(
+ String hostServerPrincipal,
+ String hostLearnerPrincipal,
+ String hostNamedLearnerPrincipal) {
String keytabFilePath = FilenameUtils.normalize(KerberosTestUtils.getKeytabFile(), true);
- String jaasEntries = new String(""
- + "QuorumServer {\n"
- + " com.sun.security.auth.module.Krb5LoginModule required\n"
- + " useKeyTab=true\n"
- + " keyTab=\"" + keytabFilePath + "\"\n"
- + " storeKey=true\n"
- + " useTicketCache=false\n"
- + " debug=false\n"
- + " principal=\"" + KerberosTestUtils.replaceHostPattern(hostServerPrincipal) + "\";\n" + "};\n"
- + "QuorumLearner {\n"
- + " com.sun.security.auth.module.Krb5LoginModule required\n"
- + " useKeyTab=true\n"
- + " keyTab=\"" + keytabFilePath + "\"\n"
- + " storeKey=true\n"
- + " useTicketCache=false\n"
- + " debug=false\n"
- + " principal=\"" + KerberosTestUtils.replaceHostPattern(hostLearnerPrincipal) + "\";\n" + "};\n"
- + "QuorumLearnerMyHost {\n"
- + " com.sun.security.auth.module.Krb5LoginModule required\n"
- + " useKeyTab=true\n"
- + " keyTab=\"" + keytabFilePath + "\"\n"
- + " storeKey=true\n"
- + " useTicketCache=false\n"
- + " debug=false\n"
- + " principal=\"" + hostNamedLearnerPrincipal + "\";\n" + "};\n");
+ String jaasEntries = "QuorumServer {\n"
+ + " com.sun.security.auth.module.Krb5LoginModule required\n"
+ + " useKeyTab=true\n"
+ + " keyTab=\"" + keytabFilePath
+ + "\"\n"
+ + " storeKey=true\n"
+ + " useTicketCache=false\n"
+ + " debug=false\n"
+ + " principal=\"" + KerberosTestUtils.replaceHostPattern(hostServerPrincipal)
+ + "\";\n"
+ + "};\n"
+ + "QuorumLearner {\n"
+ + " com.sun.security.auth.module.Krb5LoginModule required\n"
+ + " useKeyTab=true\n"
+ + " keyTab=\"" + keytabFilePath
+ + "\"\n"
+ + " storeKey=true\n"
+ + " useTicketCache=false\n"
+ + " debug=false\n"
+ + " principal=\"" + KerberosTestUtils.replaceHostPattern(hostLearnerPrincipal)
+ + "\";\n"
+ + "};\n"
+ + "QuorumLearnerMyHost {\n"
+ + " com.sun.security.auth.module.Krb5LoginModule required\n"
+ + " useKeyTab=true\n"
+ + " keyTab=\"" + keytabFilePath
+ + "\"\n"
+ + " storeKey=true\n"
+ + " useTicketCache=false\n"
+ + " debug=false\n"
+ + " principal=\"" + hostNamedLearnerPrincipal
+ + "\";\n"
+ + "};\n";
setupJaasConfig(jaasEntries);
}
@@ -104,7 +115,7 @@ public class QuorumKerberosHostBasedAuthTest extends KerberosSecurityTestcase {
@AfterClass
public static void cleanup() {
- if(keytabFile != null){
+ if (keytabFile != null) {
FileUtils.deleteQuietly(keytabFile);
}
cleanupJaasConfig();
@@ -157,22 +168,19 @@ public class QuorumKerberosHostBasedAuthTest extends KerberosSecurityTestcase {
int myid = mt.size() + 1;
final int clientPort = PortAssignment.unique();
- String server = String.format("server.%d=localhost:%d:%d:participant",
- myid, PortAssignment.unique(), PortAssignment.unique());
+ String server = String.format("server.%d=localhost:%d:%d:participant", myid, PortAssignment.unique(), PortAssignment.unique());
sb.append(server + "\n");
quorumCfgSection = sb.toString();
- authConfigs.put(QuorumAuth.QUORUM_LEARNER_SASL_LOGIN_CONTEXT,
- "QuorumLearnerMyHost");
- MainThread badServer = new MainThread(myid, clientPort, quorumCfgSection,
- authConfigs);
+ authConfigs.put(QuorumAuth.QUORUM_LEARNER_SASL_LOGIN_CONTEXT, "QuorumLearnerMyHost");
+ MainThread badServer = new MainThread(myid, clientPort, quorumCfgSection, authConfigs);
badServer.start();
watcher = new CountdownWatcher();
connectStr = "127.0.0.1:" + clientPort;
zk = new ZooKeeper(connectStr, ClientBase.CONNECTION_TIMEOUT, watcher);
- try{
- watcher.waitForConnected(ClientBase.CONNECTION_TIMEOUT/3);
- Assert.fail("Must throw exception as the myHost is not an authorized one!");
- } catch (TimeoutException e){
+ try {
+ watcher.waitForConnected(ClientBase.CONNECTION_TIMEOUT / 3);
+ fail("Must throw exception as the myHost is not an authorized one!");
+ } catch (TimeoutException e) {
// expected
} finally {
zk.close();
@@ -180,4 +188,5 @@ public class QuorumKerberosHostBasedAuthTest extends KerberosSecurityTestcase {
badServer.deleteBaseDir();
}
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/util/AdHashTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/util/AdHashTest.java
index 1af5f29dc..e88301199 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/util/AdHashTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/util/AdHashTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,15 +18,13 @@
package org.apache.zookeeper.server.util;
-import org.apache.zookeeper.ZKTestCase;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
-
-import org.junit.Test;
-
+import org.apache.zookeeper.ZKTestCase;
import org.junit.Test;
-import org.junit.Assert;
public class AdHashTest extends ZKTestCase {
@@ -42,13 +40,13 @@ public class AdHashTest extends ZKTestCase {
}
private static void addListOfDigests(AdHash hash, List<Long> digests) {
- for (long b: digests) {
+ for (long b : digests) {
hash.addDigest(b);
}
}
private static void removeListOfDigests(AdHash hash, List<Long> digests) {
- for (long b: digests) {
+ for (long b : digests) {
hash.removeDigest(b);
}
}
@@ -57,7 +55,7 @@ public class AdHashTest extends ZKTestCase {
* Test thhe add and remove digest from AdHash is working as expected.
*/
@Test
- public void testAdHash() throws Exception{
+ public void testAdHash() throws Exception {
List<Long> bucket1 = generateRandomHashes(50);
List<Long> bucket2 = generateRandomHashes(3);
List<Long> bucket3 = generateRandomHashes(30);
@@ -72,7 +70,7 @@ public class AdHashTest extends ZKTestCase {
AdHash hash21 = new AdHash();
addListOfDigests(hash21, bucket2);
addListOfDigests(hash21, bucket1);
- Assert.assertEquals(hash12, hash21);
+ assertEquals(hash12, hash21);
AdHash hashall = new AdHash();
addListOfDigests(hashall, bucket1);
@@ -80,17 +78,16 @@ public class AdHashTest extends ZKTestCase {
addListOfDigests(hashall, bucket3);
addListOfDigests(hashall, bucket4);
addListOfDigests(hashall, bucket5);
- Assert.assertFalse("digest of different set not different", hashall.equals(hash21));
+ assertFalse("digest of different set not different", hashall.equals(hash21));
removeListOfDigests(hashall, bucket4);
removeListOfDigests(hashall, bucket5);
addListOfDigests(hash21, bucket3);
- Assert.assertEquals("hashall with 4 & 5 removed should match hash21 with 3 added",
- hashall, hash21);
+ assertEquals("hashall with 4 & 5 removed should match hash21 with 3 added", hashall, hash21);
removeListOfDigests(hashall, bucket3);
removeListOfDigests(hashall, bucket2);
removeListOfDigests(hashall, bucket1);
- Assert.assertEquals("empty hashall's digest should be 0", hashall.toHexString(), "0");
+ assertEquals("empty hashall's digest should be 0", hashall.toHexString(), "0");
AdHash hash45 = new AdHash();
addListOfDigests(hash45, bucket4);
@@ -98,6 +95,7 @@ public class AdHashTest extends ZKTestCase {
addListOfDigests(hashall, bucket4);
addListOfDigests(hashall, bucket5);
- Assert.assertEquals("empty hashall + 4&5 should equal hash45", hashall, hash45);
+ assertEquals("empty hashall + 4&5 should equal hash45", hashall, hash45);
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/util/BitHashSetTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/util/BitHashSetTest.java
index a70eaa526..ff67c4e66 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/util/BitHashSetTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/util/BitHashSetTest.java
@@ -14,16 +14,17 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
package org.apache.zookeeper.server.util;
-import java.util.Set;
-import java.util.HashSet;
-import java.util.List;
+import static org.junit.Assert.assertArrayEquals;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
import java.util.ArrayList;
-
+import java.util.List;
import org.apache.zookeeper.ZKTestCase;
import org.junit.Test;
-import org.junit.Assert;
public class BitHashSetTest extends ZKTestCase {
@@ -31,38 +32,34 @@ public class BitHashSetTest extends ZKTestCase {
public void testAddWatchBit() {
int watcherCacheSize = 1;
BitHashSet ws = new BitHashSet(watcherCacheSize);
- Assert.assertTrue(ws.add(1));
- Assert.assertEquals(1, ws.size());
- Assert.assertEquals(1, ws.cachedSize());
+ assertTrue(ws.add(1));
+ assertEquals(1, ws.size());
+ assertEquals(1, ws.cachedSize());
List<Integer> actualBits = new ArrayList<Integer>();
- for (int bit: ws) {
+ for (int bit : ws) {
actualBits.add(bit);
}
- Assert.assertArrayEquals(
- new Integer[] {1},
- actualBits.toArray(new Integer[actualBits.size()]));
+ assertArrayEquals(new Integer[]{1}, actualBits.toArray(new Integer[actualBits.size()]));
// add the same bit again
- Assert.assertFalse(ws.add(1));
- Assert.assertEquals(1, ws.size());
- Assert.assertEquals(1, ws.cachedSize());
+ assertFalse(ws.add(1));
+ assertEquals(1, ws.size());
+ assertEquals(1, ws.cachedSize());
// add another bit, make sure there there is only 1 bit cached
- Assert.assertTrue(ws.add(2));
- Assert.assertEquals(2, ws.size());
- Assert.assertEquals(1, ws.cachedSize());
+ assertTrue(ws.add(2));
+ assertEquals(2, ws.size());
+ assertEquals(1, ws.cachedSize());
- Assert.assertTrue(ws.contains(1));
+ assertTrue(ws.contains(1));
actualBits.clear();
- for (int bit: ws) {
+ for (int bit : ws) {
actualBits.add(bit);
}
- Assert.assertArrayEquals(
- new Integer[] {1, 2},
- actualBits.toArray(new Integer[actualBits.size()]));
+ assertArrayEquals(new Integer[]{1, 2}, actualBits.toArray(new Integer[actualBits.size()]));
}
@Test
@@ -72,39 +69,36 @@ public class BitHashSetTest extends ZKTestCase {
ws.add(1);
ws.add(2);
- Assert.assertTrue(ws.contains(1));
- Assert.assertTrue(ws.contains(2));
+ assertTrue(ws.contains(1));
+ assertTrue(ws.contains(2));
ws.remove(1);
- Assert.assertFalse(ws.contains(1));
- Assert.assertEquals(1, ws.size());
- Assert.assertEquals(0, ws.cachedSize());
+ assertFalse(ws.contains(1));
+ assertEquals(1, ws.size());
+ assertEquals(0, ws.cachedSize());
List<Integer> actualBits = new ArrayList<Integer>();
- for (int bit: ws) {
+ for (int bit : ws) {
actualBits.add(bit);
}
- Assert.assertArrayEquals(
- new Integer[] {2},
- actualBits.toArray(new Integer[actualBits.size()]));
+ assertArrayEquals(new Integer[]{2}, actualBits.toArray(new Integer[actualBits.size()]));
ws.add(3);
- Assert.assertEquals(2, ws.size());
- Assert.assertEquals(1, ws.cachedSize());
+ assertEquals(2, ws.size());
+ assertEquals(1, ws.cachedSize());
actualBits.clear();
- for (int bit: ws) {
+ for (int bit : ws) {
actualBits.add(bit);
}
- Assert.assertArrayEquals(
- new Integer[] {2, 3},
- actualBits.toArray(new Integer[actualBits.size()]));
+ assertArrayEquals(new Integer[]{2, 3}, actualBits.toArray(new Integer[actualBits.size()]));
ws.remove(2);
ws.remove(3);
- Assert.assertEquals(0, ws.size());
- Assert.assertEquals(0, ws.cachedSize());
+ assertEquals(0, ws.size());
+ assertEquals(0, ws.cachedSize());
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/util/BitMapTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/util/BitMapTest.java
index eca0f2d25..799a78662 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/util/BitMapTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/util/BitMapTest.java
@@ -14,46 +14,50 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
package org.apache.zookeeper.server.util;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotEquals;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
import org.apache.zookeeper.ZKTestCase;
import org.junit.Test;
-import org.junit.Assert;
public class BitMapTest extends ZKTestCase {
@Test
public void testAddAndRemove() {
BitMap<String> bitMap = new BitMap<String>();
- String v1 = new String("v1");
+ String v1 = "v1";
Integer bit = bitMap.add(v1);
- Assert.assertEquals(1, bitMap.size());
- Assert.assertTrue(bit >= 0);
- Assert.assertEquals(v1, bitMap.get(bit));
- Assert.assertEquals(bit, bitMap.getBit(v1));
+ assertEquals(1, bitMap.size());
+ assertTrue(bit >= 0);
+ assertEquals(v1, bitMap.get(bit));
+ assertEquals(bit, bitMap.getBit(v1));
// add the same value again
Integer newBit = bitMap.add(v1);
- Assert.assertEquals(bit, newBit);
- Assert.assertEquals(1, bitMap.size());
+ assertEquals(bit, newBit);
+ assertEquals(1, bitMap.size());
- String v2 = new String("v2");
+ String v2 = "v2";
Integer v2Bit = bitMap.add(v2);
- Assert.assertEquals(2, bitMap.size());
- Assert.assertNotEquals(v2Bit, bit);
+ assertEquals(2, bitMap.size());
+ assertNotEquals(v2Bit, bit);
// remove by value
bitMap.remove(v1);
- Assert.assertEquals(1, bitMap.size());
- Assert.assertNull(bitMap.get(bit));
- Assert.assertNull(bitMap.getBit(v1));
+ assertEquals(1, bitMap.size());
+ assertNull(bitMap.get(bit));
+ assertNull(bitMap.getBit(v1));
// remove by bit
bitMap.remove(v2Bit);
- Assert.assertEquals(0, bitMap.size());
- Assert.assertNull(bitMap.get(v2Bit));
- Assert.assertNull(bitMap.getBit(v2));
+ assertEquals(0, bitMap.size());
+ assertNull(bitMap.get(v2Bit));
+ assertNull(bitMap.getBit(v2));
}
@Test
@@ -66,6 +70,7 @@ public class BitMapTest extends ZKTestCase {
int v4Bit = bitMap.add("v4");
- Assert.assertEquals(v4Bit, v2Bit);
+ assertEquals(v4Bit, v2Bit);
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/util/ConfigUtilsTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/util/ConfigUtilsTest.java
index 41c450d8c..ba68b229e 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/util/ConfigUtilsTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/util/ConfigUtilsTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,9 +18,9 @@
package org.apache.zookeeper.server.util;
-import org.junit.Test;
import static org.junit.Assert.assertEquals;
import org.apache.zookeeper.server.quorum.QuorumPeerConfig.ConfigException;
+import org.junit.Test;
public class ConfigUtilsTest {
@@ -29,7 +29,7 @@ public class ConfigUtilsTest {
String[] nsa = ConfigUtils.getHostAndPort("[2001:db8:85a3:8d3:1319:8a2e:370:7348]:443");
assertEquals(nsa[0], "2001:db8:85a3:8d3:1319:8a2e:370:7348");
assertEquals(nsa[1], "443");
-
+
nsa = ConfigUtils.getHostAndPort("[2001:db8:1::242:ac11:2]:2888:3888");
assertEquals(nsa[0], "2001:db8:1::242:ac11:2");
assertEquals(nsa[1], "2888");
@@ -41,7 +41,7 @@ public class ConfigUtilsTest {
String[] nsa = ConfigUtils.getHostAndPort("127.0.0.1:443");
assertEquals(nsa[0], "127.0.0.1");
assertEquals(nsa[1], "443");
-
+
nsa = ConfigUtils.getHostAndPort("127.0.0.1:2888:3888");
assertEquals(nsa[0], "127.0.0.1");
assertEquals(nsa[1], "2888");
@@ -52,21 +52,21 @@ public class ConfigUtilsTest {
public void testGetHostAndPortWithoutBracket() throws ConfigException {
String[] nsa = ConfigUtils.getHostAndPort("[2001:db8:85a3:8d3:1319:8a2e:370:7348");
}
-
+
@Test(expected = ConfigException.class)
public void testGetHostAndPortWithoutPortAfterColon() throws ConfigException {
String[] nsa = ConfigUtils.getHostAndPort("[2001:db8:1::242:ac11:2]:");
}
-
+
@Test
public void testGetHostAndPortWithoutPort() throws ConfigException {
- String[] nsa = ConfigUtils.getHostAndPort("127.0.0.1");
- assertEquals(nsa[0], "127.0.0.1");
- assertEquals(nsa.length, 1);
-
- nsa = ConfigUtils.getHostAndPort("[2001:db8:1::242:ac11:2]");
- assertEquals(nsa[0], "2001:db8:1::242:ac11:2");
- assertEquals(nsa.length, 1);
+ String[] nsa = ConfigUtils.getHostAndPort("127.0.0.1");
+ assertEquals(nsa[0], "127.0.0.1");
+ assertEquals(nsa.length, 1);
+
+ nsa = ConfigUtils.getHostAndPort("[2001:db8:1::242:ac11:2]");
+ assertEquals(nsa[0], "2001:db8:1::242:ac11:2");
+ assertEquals(nsa.length, 1);
}
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/util/JvmPauseMonitorTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/util/JvmPauseMonitorTest.java
index 4e701b83d..58b1902a2 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/util/JvmPauseMonitorTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/util/JvmPauseMonitorTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,14 +18,13 @@
package org.apache.zookeeper.server.util;
+import static org.junit.Assert.assertEquals;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
import org.apache.zookeeper.server.quorum.QuorumPeerConfig;
import org.junit.After;
-import org.junit.Assert;
import org.junit.Test;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.when;
-
public class JvmPauseMonitorTest {
private final Long sleepTime = 100L;
@@ -33,7 +32,7 @@ public class JvmPauseMonitorTest {
private final Long warnTH = -1L;
private JvmPauseMonitor pauseMonitor;
- @Test(timeout=5000)
+ @Test(timeout = 5000)
public void testJvmPauseMonitorExceedInfoThreshold() throws InterruptedException {
QuorumPeerConfig qpConfig = mock(QuorumPeerConfig.class);
when(qpConfig.getJvmPauseSleepTimeMs()).thenReturn(sleepTime);
@@ -42,15 +41,15 @@ public class JvmPauseMonitorTest {
pauseMonitor = new JvmPauseMonitor(qpConfig);
pauseMonitor.serviceStart();
- Assert.assertEquals(sleepTime, Long.valueOf(pauseMonitor.sleepTimeMs));
- Assert.assertEquals(infoTH, Long.valueOf(pauseMonitor.infoThresholdMs));
+ assertEquals(sleepTime, Long.valueOf(pauseMonitor.sleepTimeMs));
+ assertEquals(infoTH, Long.valueOf(pauseMonitor.infoThresholdMs));
- while(pauseMonitor.getNumGcInfoThresholdExceeded() == 0) {
+ while (pauseMonitor.getNumGcInfoThresholdExceeded() == 0) {
Thread.sleep(200);
}
}
- @Test(timeout=5000)
+ @Test(timeout = 5000)
public void testJvmPauseMonitorExceedWarnThreshold() throws InterruptedException {
QuorumPeerConfig qpConfig = mock(QuorumPeerConfig.class);
when(qpConfig.getJvmPauseSleepTimeMs()).thenReturn(sleepTime);
@@ -59,10 +58,10 @@ public class JvmPauseMonitorTest {
pauseMonitor = new JvmPauseMonitor(qpConfig);
pauseMonitor.serviceStart();
- Assert.assertEquals(sleepTime, Long.valueOf(pauseMonitor.sleepTimeMs));
- Assert.assertEquals(warnTH, Long.valueOf(pauseMonitor.warnThresholdMs));
+ assertEquals(sleepTime, Long.valueOf(pauseMonitor.sleepTimeMs));
+ assertEquals(warnTH, Long.valueOf(pauseMonitor.warnThresholdMs));
- while(pauseMonitor.getNumGcWarnThresholdExceeded() == 0) {
+ while (pauseMonitor.getNumGcWarnThresholdExceeded() == 0) {
Thread.sleep(200);
}
@@ -72,4 +71,5 @@ public class JvmPauseMonitorTest {
public void teardown() {
pauseMonitor.serviceStop();
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/util/PortForwarder.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/util/PortForwarder.java
index 84868498c..c66dcc869 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/util/PortForwarder.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/util/PortForwarder.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -31,7 +31,6 @@ import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
-
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -39,15 +38,15 @@ import org.slf4j.LoggerFactory;
* A utility that does bi-directional forwarding between two ports.
* Useful, for example, to simulate network failures.
* Example:
- *
+ *
* Server 1 config file:
- *
+ *
* server.1=127.0.0.1:7301:7401;8201
* server.2=127.0.0.1:7302:7402;8202
* server.3=127.0.0.1:7303:7403;8203
- *
+ *
* Server 2 and 3 config files:
- *
+ *
* server.1=127.0.0.1:8301:8401;8201
* server.2=127.0.0.1:8302:8402;8202
* server.3=127.0.0.1:8303:8403;8203
@@ -55,13 +54,13 @@ import org.slf4j.LoggerFactory;
* Initially forward traffic between 730x and 830x and between 740x and 830x
* This way server 1 can communicate with servers 2 and 3
* ....
- *
+ *
* List&lt;PortForwarder&gt; pfs = startForwarding();
* ....
* // simulate a network interruption for server 1
* stopForwarding(pfs);
* ....
- * // restore connection
+ * // restore connection
* pfs = startForwarding();
*
*
@@ -75,18 +74,18 @@ import org.slf4j.LoggerFactory;
* res.add(new PortForwarder(7403, 8403));
* return res;
* }
- *
+ *
* private void stopForwarding(List&lt;PortForwarder&gt; pfs) throws Exception {
* for (PortForwarder pf : pfs) {
* pf.shutdown();
* }
* }
- *
+ *
*
*/
public class PortForwarder extends Thread {
- private static final Logger LOG = LoggerFactory
- .getLogger(PortForwarder.class);
+
+ private static final Logger LOG = LoggerFactory.getLogger(PortForwarder.class);
private static class PortForwardWorker implements Runnable {
@@ -96,8 +95,7 @@ public class PortForwarder extends Thread {
private final Socket toClose2;
private boolean isFinished = false;
- PortForwardWorker(Socket toClose, Socket toClose2, InputStream in,
- OutputStream out) {
+ PortForwardWorker(Socket toClose, Socket toClose2, InputStream in, OutputStream out) {
this.toClose = toClose;
this.toClose2 = toClose2;
this.in = in;
@@ -106,8 +104,7 @@ public class PortForwarder extends Thread {
}
public void run() {
- Thread.currentThread().setName(toClose.toString() + "-->"
- + toClose2.toString());
+ Thread.currentThread().setName(toClose.toString() + "-->" + toClose2.toString());
byte[] buf = new byte[1024];
try {
while (true) {
@@ -146,7 +143,7 @@ public class PortForwarder extends Thread {
boolean waitForShutdown(long timeoutMs) throws InterruptedException {
synchronized (this) {
if (!isFinished) {
- this.wait(timeoutMs);
+ this.wait(timeoutMs);
}
}
return isFinished;
@@ -164,6 +161,7 @@ public class PortForwarder extends Thread {
// ignore silently
}
}
+
}
private volatile boolean stopped = false;
@@ -185,56 +183,58 @@ public class PortForwarder extends Thread {
while (!stopped) {
Socket sock = null;
try {
- LOG.info("accepting socket local:"
- + serverSocket.getLocalPort() + " to:" + to);
+ LOG.info("accepting socket local:" + serverSocket.getLocalPort() + " to:" + to);
sock = serverSocket.accept();
- LOG.info("accepted: local:" + sock.getLocalPort()
- + " from:" + sock.getPort()
- + " to:" + to);
+ LOG.info("accepted: local:" + sock.getLocalPort() + " from:" + sock.getPort() + " to:" + to);
Socket target = null;
int retry = 10;
- while(sock.isConnected()) {
+ while (sock.isConnected()) {
try {
target = new Socket("localhost", to);
break;
} catch (IOException e) {
if (retry == 0) {
- throw e;
+ throw e;
}
- LOG.warn("connection failed, retrying(" + retry
- + "): local:" + sock.getLocalPort()
- + " from:" + sock.getPort()
- + " to:" + to, e);
+ LOG.warn("connection failed, retrying("
+ + retry
+ + "): local:"
+ + sock.getLocalPort()
+ + " from:"
+ + sock.getPort()
+ + " to:"
+ + to, e);
}
Thread.sleep(TimeUnit.SECONDS.toMillis(1));
retry--;
}
- LOG.info("connected: local:" + sock.getLocalPort()
- + " from:" + sock.getPort()
- + " to:" + to);
+ LOG.info("connected: local:" + sock.getLocalPort() + " from:" + sock.getPort() + " to:" + to);
sock.setSoTimeout(30000);
target.setSoTimeout(30000);
-
- workers.add(new PortForwardWorker(sock, target,
- sock.getInputStream(), target.getOutputStream()));
- workers.add(new PortForwardWorker(target, sock,
- target.getInputStream(), sock.getOutputStream()));
- for (PortForwardWorker worker: workers) {
+ workers.add(new PortForwardWorker(sock, target, sock.getInputStream(), target.getOutputStream()));
+ workers.add(new PortForwardWorker(target, sock, target.getInputStream(), sock.getOutputStream()));
+ for (PortForwardWorker worker : workers) {
workerExecutor.submit(worker);
}
} catch (SocketTimeoutException e) {
LOG.warn("socket timed out", e);
} catch (ConnectException e) {
- LOG.warn("connection exception local:" + sock.getLocalPort()
- + " from:" + sock.getPort()
- + " to:" + to, e);
+ LOG.warn("connection exception local:"
+ + sock.getLocalPort()
+ + " from:"
+ + sock.getPort()
+ + " to:"
+ + to, e);
sock.close();
} catch (IOException e) {
if (!"Socket closed".equals(e.getMessage())) {
- LOG.warn("unexpected exception local:" + sock.getLocalPort()
- + " from:" + sock.getPort()
- + " to:" + to, e);
+ LOG.warn("unexpected exception local:"
+ + sock.getLocalPort()
+ + " from:"
+ + sock.getPort()
+ + " to:"
+ + to, e);
throw e;
}
}
@@ -252,14 +252,15 @@ public class PortForwarder extends Thread {
this.serverSocket.close();
this.join();
this.workerExecutor.shutdownNow();
- for (PortForwardWorker worker: workers) {
+ for (PortForwardWorker worker : workers) {
worker.shutdown();
}
- for (PortForwardWorker worker: workers) {
+ for (PortForwardWorker worker : workers) {
if (!worker.waitForShutdown(5000)) {
throw new Exception("Failed to stop forwarding within 5 seconds");
}
}
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/util/RequestPathMetricsCollectorTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/util/RequestPathMetricsCollectorTest.java
index 7440b193c..ecfc92c00 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/util/RequestPathMetricsCollectorTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/util/RequestPathMetricsCollectorTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,18 +18,6 @@
package org.apache.zookeeper.server.util;
-import java.util.Map;
-import java.util.Random;
-import java.util.concurrent.Executors;
-import java.util.concurrent.ThreadPoolExecutor;
-import java.util.concurrent.TimeUnit;
-
-import org.junit.Before;
-import org.junit.After;
-import org.junit.Ignore;
-import org.junit.Test;
-import org.junit.Assert;
-
import static org.apache.zookeeper.ZooDefs.OpCode.create;
import static org.apache.zookeeper.ZooDefs.OpCode.create2;
import static org.apache.zookeeper.ZooDefs.OpCode.delete;
@@ -38,6 +26,17 @@ import static org.apache.zookeeper.ZooDefs.OpCode.getChildren;
import static org.apache.zookeeper.ZooDefs.OpCode.getChildren2;
import static org.apache.zookeeper.ZooDefs.OpCode.getData;
import static org.apache.zookeeper.ZooDefs.OpCode.setData;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import java.util.Map;
+import java.util.Random;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ThreadPoolExecutor;
+import java.util.concurrent.TimeUnit;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Ignore;
+import org.junit.Test;
public class RequestPathMetricsCollectorTest {
@@ -63,366 +62,355 @@ public class RequestPathMetricsCollectorTest {
public void testTrimPath() {
//normal cases
String trimedPath = RequestPathMetricsCollector.trimPathDepth("/p1/p2/p3", 1);
- Assert.assertTrue(trimedPath.equalsIgnoreCase("/p1"));
+ assertTrue(trimedPath.equalsIgnoreCase("/p1"));
trimedPath = RequestPathMetricsCollector.trimPathDepth("/p1/p2/p3", 2);
- Assert.assertTrue(trimedPath.equalsIgnoreCase("/p1/p2"));
+ assertTrue(trimedPath.equalsIgnoreCase("/p1/p2"));
trimedPath = RequestPathMetricsCollector.trimPathDepth("/p1/p2/p3", 3);
- Assert.assertTrue(trimedPath.equalsIgnoreCase("/p1/p2/p3"));
+ assertTrue(trimedPath.equalsIgnoreCase("/p1/p2/p3"));
trimedPath = RequestPathMetricsCollector.trimPathDepth("/p1/p2/p3", 4);
- Assert.assertTrue(trimedPath.equalsIgnoreCase("/p1/p2/p3"));
+ assertTrue(trimedPath.equalsIgnoreCase("/p1/p2/p3"));
//some extra symbols
- trimedPath = RequestPathMetricsCollector.trimPathDepth("//p1 next/p2.index/p3:next",
- 3);
- Assert.assertTrue(trimedPath.equalsIgnoreCase("/p1 next/p2.index/p3:next"));
- trimedPath = RequestPathMetricsCollector.trimPathDepth("//p1 next/p2.index/p3:next",
- 2);
- Assert.assertTrue(trimedPath.equalsIgnoreCase("/p1 next/p2.index"));
- trimedPath = RequestPathMetricsCollector.trimPathDepth("//p1 next/p2.index/p3:next",
- 6);
- Assert.assertTrue(trimedPath.equalsIgnoreCase("/p1 next/p2.index/p3:next"));
+ trimedPath = RequestPathMetricsCollector.trimPathDepth("//p1 next/p2.index/p3:next", 3);
+ assertTrue(trimedPath.equalsIgnoreCase("/p1 next/p2.index/p3:next"));
+ trimedPath = RequestPathMetricsCollector.trimPathDepth("//p1 next/p2.index/p3:next", 2);
+ assertTrue(trimedPath.equalsIgnoreCase("/p1 next/p2.index"));
+ trimedPath = RequestPathMetricsCollector.trimPathDepth("//p1 next/p2.index/p3:next", 6);
+ assertTrue(trimedPath.equalsIgnoreCase("/p1 next/p2.index/p3:next"));
}
@Test
public void testQueueMapReduce() throws InterruptedException {
RequestPathMetricsCollector requestPathMetricsCollector = new RequestPathMetricsCollector();
- RequestPathMetricsCollector.PathStatsQueue pathStatsQueue =
- requestPathMetricsCollector.new PathStatsQueue(create2);
+ RequestPathMetricsCollector.PathStatsQueue pathStatsQueue = requestPathMetricsCollector.new PathStatsQueue(create2);
Thread path7 = new Thread(() -> {
for (int i = 0; i < 1000000; i++) {
- pathStatsQueue.registerRequest("/path1/path2/path3/path4/path5/path6/path7" +
- "_" + i);
+ pathStatsQueue.registerRequest("/path1/path2/path3/path4/path5/path6/path7" + "_" + i);
}
});
path7.start();
Thread path6 = new Thread(() -> {
pathStatsQueue.registerRequest("/path1/path2/path3/path4/path5/path6");
- for(int i = 1; i < 100000; i++) {
- pathStatsQueue.registerRequest("/path1/path2/path3/path4/path5/path6"+"_"+i);
+ for (int i = 1; i < 100000; i++) {
+ pathStatsQueue.registerRequest("/path1/path2/path3/path4/path5/path6" + "_" + i);
}
});
path6.start();
- for(int i = 0; i < 1; i++) {
+ for (int i = 0; i < 1; i++) {
pathStatsQueue.registerRequest("/path1");
}
- for(int i = 0; i < 10; i++) {
- pathStatsQueue.registerRequest("/path1/path2"+"_"+i);
+ for (int i = 0; i < 10; i++) {
+ pathStatsQueue.registerRequest("/path1/path2" + "_" + i);
}
- for(int i = 0; i < 100; i++) {
- pathStatsQueue.registerRequest("/path1/path2/path3"+"_"+i);
+ for (int i = 0; i < 100; i++) {
+ pathStatsQueue.registerRequest("/path1/path2/path3" + "_" + i);
}
- for(int i = 0; i < 1000; i++) {
- pathStatsQueue.registerRequest("/path1/path2/path3/path4"+"_"+i);
+ for (int i = 0; i < 1000; i++) {
+ pathStatsQueue.registerRequest("/path1/path2/path3/path4" + "_" + i);
}
- for(int i = 0; i < 10000; i++) {
- pathStatsQueue.registerRequest("/path1/path2/path3/path4/path5"+"_"+i);
+ for (int i = 0; i < 10000; i++) {
+ pathStatsQueue.registerRequest("/path1/path2/path3/path4/path5" + "_" + i);
}
path6.join();
path7.join();
- Map<String, Integer> newSlot = pathStatsQueue.mapReducePaths(1,
- pathStatsQueue.getCurrentSlot());
- Assert.assertTrue(newSlot.size() == 1);
- Assert.assertTrue(newSlot.get("/path1").compareTo(1111111) == 0);
+ Map<String, Integer> newSlot = pathStatsQueue.mapReducePaths(1, pathStatsQueue.getCurrentSlot());
+ assertTrue(newSlot.size() == 1);
+ assertTrue(newSlot.get("/path1").compareTo(1111111) == 0);
//cut up to 2
newSlot = pathStatsQueue.mapReducePaths(2, pathStatsQueue.getCurrentSlot());
- Assert.assertTrue(newSlot.size() == 12);
- Assert.assertTrue(newSlot.get("/path1").compareTo(1) == 0);
- Assert.assertTrue(newSlot.get("/path1/path2").compareTo(1111100) == 0);
+ assertTrue(newSlot.size() == 12);
+ assertTrue(newSlot.get("/path1").compareTo(1) == 0);
+ assertTrue(newSlot.get("/path1/path2").compareTo(1111100) == 0);
//cut up to 3
newSlot = pathStatsQueue.mapReducePaths(3, pathStatsQueue.getCurrentSlot());
- Assert.assertTrue(newSlot.size() == 112);
- Assert.assertTrue(newSlot.get("/path1").compareTo(1) == 0);
- Assert.assertTrue(newSlot.get("/path1/path2/path3").compareTo(1111000) == 0);
+ assertTrue(newSlot.size() == 112);
+ assertTrue(newSlot.get("/path1").compareTo(1) == 0);
+ assertTrue(newSlot.get("/path1/path2/path3").compareTo(1111000) == 0);
//cut up to 4
newSlot = pathStatsQueue.mapReducePaths(4, pathStatsQueue.getCurrentSlot());
- Assert.assertTrue(newSlot.size() == 1112);
- Assert.assertTrue(newSlot.get("/path1/path2/path3/path4").compareTo(1110000) == 0);
+ assertTrue(newSlot.size() == 1112);
+ assertTrue(newSlot.get("/path1/path2/path3/path4").compareTo(1110000) == 0);
//cut up to 5
newSlot = pathStatsQueue.mapReducePaths(5, pathStatsQueue.getCurrentSlot());
- Assert.assertTrue(newSlot.size() == 11112);
- Assert.assertTrue(newSlot.get("/path1/path2/path3/path4/path5").compareTo(1100000) == 0);
+ assertTrue(newSlot.size() == 11112);
+ assertTrue(newSlot.get("/path1/path2/path3/path4/path5").compareTo(1100000) == 0);
//cut up to 6
newSlot = pathStatsQueue.mapReducePaths(6, pathStatsQueue.getCurrentSlot());
- Assert.assertTrue(newSlot.size() == 111111);
- Assert.assertTrue(newSlot.get("/path1/path2/path3/path4/path5/path6").compareTo(1000001) == 0);
+ assertTrue(newSlot.size() == 111111);
+ assertTrue(newSlot.get("/path1/path2/path3/path4/path5/path6").compareTo(1000001) == 0);
//cut up to 7
newSlot = pathStatsQueue.mapReducePaths(7, pathStatsQueue.getCurrentSlot());
- Assert.assertTrue(newSlot.size() == 1111111);
+ assertTrue(newSlot.size() == 1111111);
}
@Test
public void testCollectEmptyStats() throws InterruptedException {
RequestPathMetricsCollector requestPathMetricsCollector = new RequestPathMetricsCollector();
- RequestPathMetricsCollector.PathStatsQueue pathStatsQueue =
- requestPathMetricsCollector.new PathStatsQueue(getChildren);
+ RequestPathMetricsCollector.PathStatsQueue pathStatsQueue = requestPathMetricsCollector.new PathStatsQueue(getChildren);
Thread.sleep(5000);
- Map<String, Integer> newSlot = pathStatsQueue.mapReducePaths(3,
- pathStatsQueue.getCurrentSlot());
- Assert.assertTrue(newSlot.isEmpty());
+ Map<String, Integer> newSlot = pathStatsQueue.mapReducePaths(3, pathStatsQueue.getCurrentSlot());
+ assertTrue(newSlot.isEmpty());
pathStatsQueue.start();
Thread.sleep(15000);
newSlot = pathStatsQueue.collectStats(1);
- Assert.assertTrue(newSlot.size() == 0);
+ assertTrue(newSlot.size() == 0);
newSlot = pathStatsQueue.collectStats(2);
- Assert.assertTrue(newSlot.size() == 0);
+ assertTrue(newSlot.size() == 0);
newSlot = pathStatsQueue.collectStats(5);
- Assert.assertTrue(newSlot.size() == 0);
+ assertTrue(newSlot.size() == 0);
}
@Test
@Ignore
public void testCollectStats() throws InterruptedException {
- RequestPathMetricsCollector requestPathMetricsCollector =
- new RequestPathMetricsCollector(true);
- RequestPathMetricsCollector.PathStatsQueue pathStatsQueue =
- requestPathMetricsCollector.new PathStatsQueue(getChildren);
+ RequestPathMetricsCollector requestPathMetricsCollector = new RequestPathMetricsCollector(true);
+ RequestPathMetricsCollector.PathStatsQueue pathStatsQueue = requestPathMetricsCollector.new PathStatsQueue(getChildren);
pathStatsQueue.start();
Thread path7 = new Thread(() -> {
- for(int i = 0; i < 10; i++) {
+ for (int i = 0; i < 10; i++) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
for (int j = 0; j < 100000; j++) {
- pathStatsQueue.registerRequest("/path1/path2/path3/path4/path5/path6/path7"
- + "_" + i + "_" + j);
+ pathStatsQueue.registerRequest("/path1/path2/path3/path4/path5/path6/path7" + "_" + i + "_" + j);
}
}
});
path7.start();
Thread path6 = new Thread(() -> {
pathStatsQueue.registerRequest("/path1/path2/path3/path4/path5/path6");
- for(int i = 0; i < 10; i++) {
+ for (int i = 0; i < 10; i++) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
for (int j = 0; j < 10000; j++) {
- pathStatsQueue.registerRequest("/path1/path2/path3/path4/path5/path6"
- + "_" + i + "_" + j);
+ pathStatsQueue.registerRequest("/path1/path2/path3/path4/path5/path6" + "_" + i + "_" + j);
}
}
});
path6.start();
- for(int i = 0; i < 1; i++) {
+ for (int i = 0; i < 1; i++) {
pathStatsQueue.registerRequest("/path1");
- }
- for(int i = 0; i < 10; i++) {
- pathStatsQueue.registerRequest("/path1/path2"+"_"+i);
}
- for(int i = 0; i < 100; i++) {
- pathStatsQueue.registerRequest("/path1/path2/path3"+"_"+i);
+ for (int i = 0; i < 10; i++) {
+ pathStatsQueue.registerRequest("/path1/path2" + "_" + i);
+ }
+ for (int i = 0; i < 100; i++) {
+ pathStatsQueue.registerRequest("/path1/path2/path3" + "_" + i);
}
- for(int i = 0; i < 1000; i++) {
- pathStatsQueue.registerRequest("/path1/path2/path3/path4"+"_"+i);
+ for (int i = 0; i < 1000; i++) {
+ pathStatsQueue.registerRequest("/path1/path2/path3/path4" + "_" + i);
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
- for(int i = 0; i < 10000; i++) {
- pathStatsQueue.registerRequest("/path1/path2/path3/path4/path5"+"_"+i);
+ for (int i = 0; i < 10000; i++) {
+ pathStatsQueue.registerRequest("/path1/path2/path3/path4/path5" + "_" + i);
}
path6.join();
path7.join();
Map<String, Integer> newSlot = pathStatsQueue.collectStats(1);
- Assert.assertEquals(newSlot.size(), 1);
- Assert.assertEquals(newSlot.get("/path1").intValue(), 1111112);
+ assertEquals(newSlot.size(), 1);
+ assertEquals(newSlot.get("/path1").intValue(), 1111112);
//cut up to 2
newSlot = pathStatsQueue.collectStats(2);
- Assert.assertEquals(newSlot.size(), 12);
- Assert.assertEquals(newSlot.get("/path1").intValue(), 1);
- Assert.assertEquals(newSlot.get("/path1/path2").intValue(), 1111101);
+ assertEquals(newSlot.size(), 12);
+ assertEquals(newSlot.get("/path1").intValue(), 1);
+ assertEquals(newSlot.get("/path1/path2").intValue(), 1111101);
//cut up to 3
newSlot = pathStatsQueue.collectStats(3);
- Assert.assertEquals(newSlot.size(), 112);
- Assert.assertEquals(newSlot.get("/path1").intValue(), 1);
- Assert.assertEquals(newSlot.get("/path1/path2/path3").intValue(), 1111001);
+ assertEquals(newSlot.size(), 112);
+ assertEquals(newSlot.get("/path1").intValue(), 1);
+ assertEquals(newSlot.get("/path1/path2/path3").intValue(), 1111001);
//cut up to 4
newSlot = pathStatsQueue.collectStats(4);
- Assert.assertEquals(newSlot.size(), 1112);
- Assert.assertEquals(newSlot.get("/path1/path2/path3/path4").intValue(), 1110001);
+ assertEquals(newSlot.size(), 1112);
+ assertEquals(newSlot.get("/path1/path2/path3/path4").intValue(), 1110001);
//cut up to 5
newSlot = pathStatsQueue.collectStats(5);
- Assert.assertEquals(newSlot.size(), 11112);
- Assert.assertEquals(newSlot.get("/path1/path2/path3/path4/path5").intValue(), 1100001);
+ assertEquals(newSlot.size(), 11112);
+ assertEquals(newSlot.get("/path1/path2/path3/path4/path5").intValue(), 1100001);
//cut up to 6
newSlot = pathStatsQueue.collectStats(6);
- Assert.assertEquals(newSlot.size(), 111112);
- Assert.assertEquals(newSlot.get("/path1/path2/path3/path4/path5/path6").intValue(),
- 1000001);
+ assertEquals(newSlot.size(), 111112);
+ assertEquals(newSlot.get("/path1/path2/path3/path4/path5/path6").intValue(), 1000001);
}
-
+
@Test
public void testAggregate() throws InterruptedException {
- RequestPathMetricsCollector requestPathMetricsCollector =
- new RequestPathMetricsCollector(true);
+ RequestPathMetricsCollector requestPathMetricsCollector = new RequestPathMetricsCollector(true);
Thread path7 = new Thread(() -> {
- for(int i = 0; i < 10; i++) {
+ for (int i = 0; i < 10; i++) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
for (int j = 0; j < 100000; j++) {
- requestPathMetricsCollector.registerRequest(getData,
- "/path1/path2/path3/path4/path5/path6/path7" + "_" + i + "_" + j);
+ requestPathMetricsCollector.registerRequest(getData, "/path1/path2/path3/path4/path5/path6/path7"
+ + "_"
+ + i
+ + "_"
+ + j);
}
}
});
path7.start();
Thread path6 = new Thread(() -> {
- requestPathMetricsCollector.registerRequest(getChildren2,
- "/path1/path2/path3/path4/path5/path6");
- for(int i = 0; i < 10; i++) {
+ requestPathMetricsCollector.registerRequest(getChildren2, "/path1/path2/path3/path4/path5/path6");
+ for (int i = 0; i < 10; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
for (int j = 0; j < 10000; j++) {
- requestPathMetricsCollector.registerRequest(getChildren,
- "/path1/path2/path3/path4/path5/path6" + "_" + i + "_" + j);
+ requestPathMetricsCollector.registerRequest(getChildren, "/path1/path2/path3/path4/path5/path6"
+ + "_"
+ + i
+ + "_"
+ + j);
}
}
});
path6.start();
- for(int i = 0; i < 1; i++) {
- requestPathMetricsCollector.registerRequest(create2,
- "/path1");
+ for (int i = 0; i < 1; i++) {
+ requestPathMetricsCollector.registerRequest(create2, "/path1");
}
- for(int i = 0; i < 10; i++) {
- requestPathMetricsCollector.registerRequest(create,
- "/path1/path2"+"_"+i);
+ for (int i = 0; i < 10; i++) {
+ requestPathMetricsCollector.registerRequest(create, "/path1/path2" + "_" + i);
}
- for(int i = 0; i < 100; i++) {
- requestPathMetricsCollector.registerRequest(delete,
- "/path1/path2/path3"+"_"+i);
+ for (int i = 0; i < 100; i++) {
+ requestPathMetricsCollector.registerRequest(delete, "/path1/path2/path3" + "_" + i);
}
- for(int i = 0; i < 1000; i++) {
- requestPathMetricsCollector.registerRequest(setData,
- "/path1/path2/path3/path4"+"_"+i);
+ for (int i = 0; i < 1000; i++) {
+ requestPathMetricsCollector.registerRequest(setData, "/path1/path2/path3/path4" + "_" + i);
}
- for(int i = 0; i < 10000; i++) {
- requestPathMetricsCollector.registerRequest(exists,
- "/path1/path2/path3/path4/path5"+"_"+i);
+ for (int i = 0; i < 10000; i++) {
+ requestPathMetricsCollector.registerRequest(exists, "/path1/path2/path3/path4/path5" + "_" + i);
}
path6.join();
path7.join();
- Map<String, Integer> newSlot = requestPathMetricsCollector.aggregatePaths(2,
- queue -> true);
- Assert.assertEquals(newSlot.size(), 12);
- Assert.assertEquals(newSlot.get("/path1").intValue(), 1);
- Assert.assertEquals(newSlot.get("/path1/path2").intValue(), 1111101);
+ Map<String, Integer> newSlot = requestPathMetricsCollector.aggregatePaths(2, queue -> true);
+ assertEquals(newSlot.size(), 12);
+ assertEquals(newSlot.get("/path1").intValue(), 1);
+ assertEquals(newSlot.get("/path1/path2").intValue(), 1111101);
//cut up to 3
newSlot = requestPathMetricsCollector.aggregatePaths(3, queue -> true);
- Assert.assertEquals(newSlot.size(), 112);
- Assert.assertEquals(newSlot.get("/path1").intValue(), 1);
- Assert.assertEquals(newSlot.get("/path1/path2/path3").intValue(), 1111001);
+ assertEquals(newSlot.size(), 112);
+ assertEquals(newSlot.get("/path1").intValue(), 1);
+ assertEquals(newSlot.get("/path1/path2/path3").intValue(), 1111001);
//cut up to 4
newSlot = requestPathMetricsCollector.aggregatePaths(4, queue -> true);
- Assert.assertEquals(newSlot.size(), 1112);
- Assert.assertEquals(newSlot.get("/path1/path2/path3/path4").intValue(), 1110001);
+ assertEquals(newSlot.size(), 1112);
+ assertEquals(newSlot.get("/path1/path2/path3/path4").intValue(), 1110001);
//cut up to 5
newSlot = requestPathMetricsCollector.aggregatePaths(5, queue -> true);
- Assert.assertEquals(newSlot.size(), 11112);
- Assert.assertEquals(newSlot.get("/path1/path2/path3/path4/path5").intValue(), 1100001);
+ assertEquals(newSlot.size(), 11112);
+ assertEquals(newSlot.get("/path1/path2/path3/path4/path5").intValue(), 1100001);
//cut up to 6
newSlot = requestPathMetricsCollector.aggregatePaths(6, queue -> true);
- Assert.assertEquals(newSlot.size(), 111112);
- Assert.assertEquals(newSlot.get("/path1/path2/path3/path4/path5/path6").intValue(), 1000001);
+ assertEquals(newSlot.size(), 111112);
+ assertEquals(newSlot.get("/path1/path2/path3/path4/path5/path6").intValue(), 1000001);
//cut up to 7 but the initial mapReduce kept only 6
newSlot = requestPathMetricsCollector.aggregatePaths(7, queue -> true);
- Assert.assertEquals(newSlot.size(), 111112);
- Assert.assertEquals(newSlot.get("/path1/path2/path3/path4/path5/path6").intValue(), 1000001);
+ assertEquals(newSlot.size(), 111112);
+ assertEquals(newSlot.get("/path1/path2/path3/path4/path5/path6").intValue(), 1000001);
//test predicate
//cut up to 4 for all the reads
newSlot = requestPathMetricsCollector.aggregatePaths(4, queue -> !queue.isWriteOperation());
- Assert.assertEquals(newSlot.size(), 1);
- Assert.assertEquals(newSlot.get("/path1/path2/path3/path4").intValue(), 1110001);
+ assertEquals(newSlot.size(), 1);
+ assertEquals(newSlot.get("/path1/path2/path3/path4").intValue(), 1110001);
//cut up to 4 for all the write
newSlot = requestPathMetricsCollector.aggregatePaths(4, queue -> queue.isWriteOperation());
- Assert.assertEquals(newSlot.size(), 1111);
+ assertEquals(newSlot.size(), 1111);
//cut up to 3 for all the write
newSlot = requestPathMetricsCollector.aggregatePaths(3, queue -> queue.isWriteOperation());
- Assert.assertEquals(newSlot.size(), 112);
- Assert.assertEquals(newSlot.get("/path1/path2/path3").intValue(), 1000);
+ assertEquals(newSlot.size(), 112);
+ assertEquals(newSlot.get("/path1/path2/path3").intValue(), 1000);
}
@Test
public void testTopPath() throws InterruptedException {
RequestPathMetricsCollector requestPathMetricsCollector = new RequestPathMetricsCollector(true);
Thread path7 = new Thread(() -> {
- for(int i = 0; i < 10; i++) {
+ for (int i = 0; i < 10; i++) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
for (int j = 0; j < 100000; j++) {
- requestPathMetricsCollector.registerRequest(getData,
- "/path1/path2/path3/path4/path5/path6/path7" + "_" + i + "_" + j);
+ requestPathMetricsCollector.registerRequest(getData, "/path1/path2/path3/path4/path5/path6/path7"
+ + "_"
+ + i
+ + "_"
+ + j);
}
}
});
path7.start();
Thread path6 = new Thread(() -> {
- requestPathMetricsCollector.registerRequest(getChildren2,
- "/path1/path2/path3/path4/path5/path6");
- for(int i = 0; i < 10; i++) {
+ requestPathMetricsCollector.registerRequest(getChildren2, "/path1/path2/path3/path4/path5/path6");
+ for (int i = 0; i < 10; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
for (int j = 0; j < 10000; j++) {
- requestPathMetricsCollector.registerRequest(getChildren,
- "/path1/path2/path3/path4/path5/path6" + "_" + i + "_" + j);
+ requestPathMetricsCollector.registerRequest(getChildren, "/path1/path2/path3/path4/path5/path6"
+ + "_"
+ + i
+ + "_"
+ + j);
}
}
});
path6.start();
- for(int i = 0; i < 1; i++) {
- requestPathMetricsCollector.registerRequest(create2,
- "/path1");
+ for (int i = 0; i < 1; i++) {
+ requestPathMetricsCollector.registerRequest(create2, "/path1");
}
- for(int i = 0; i < 10; i++) {
- requestPathMetricsCollector.registerRequest(create,
- "/path1/path2"+"_"+i);
+ for (int i = 0; i < 10; i++) {
+ requestPathMetricsCollector.registerRequest(create, "/path1/path2" + "_" + i);
}
- for(int i = 0; i < 100; i++) {
- requestPathMetricsCollector.registerRequest(delete,
- "/path1/path2/path3"+"_"+i);
+ for (int i = 0; i < 100; i++) {
+ requestPathMetricsCollector.registerRequest(delete, "/path1/path2/path3" + "_" + i);
}
- for(int i = 0; i < 1000; i++) {
- requestPathMetricsCollector.registerRequest(setData,
- "/path1/path2/path3/path4"+"_"+i);
+ for (int i = 0; i < 1000; i++) {
+ requestPathMetricsCollector.registerRequest(setData, "/path1/path2/path3/path4" + "_" + i);
}
- for(int i = 0; i < 10000; i++) {
- requestPathMetricsCollector.registerRequest(exists,
- "/path1/path2/path3/path4/path5"+"_"+i);
+ for (int i = 0; i < 10000; i++) {
+ requestPathMetricsCollector.registerRequest(exists, "/path1/path2/path3/path4/path5" + "_" + i);
}
path6.join();
path7.join();
- StringBuilder sb1= new StringBuilder();
- Map<String, Integer> newSlot = requestPathMetricsCollector.aggregatePaths(3,
- queue -> queue.isWriteOperation());
- requestPathMetricsCollector.logTopPaths(newSlot,
- entry -> sb1.append(entry.getKey() + " : " + entry.getValue() + "\n"));
- Assert.assertTrue(sb1.toString().startsWith("/path1/path2/path3 : 1000"));
- StringBuilder sb2= new StringBuilder();
- newSlot = requestPathMetricsCollector.aggregatePaths(3,
- queue -> !queue.isWriteOperation());
- requestPathMetricsCollector.logTopPaths(newSlot,
- entry -> sb2.append(entry.getKey() + " : " + entry.getValue() + "\n"));
- Assert.assertTrue(sb2.toString().startsWith("/path1/path2/path3 : 1110001"));
- StringBuilder sb3= new StringBuilder();
+ StringBuilder sb1 = new StringBuilder();
+ Map<String, Integer> newSlot = requestPathMetricsCollector.aggregatePaths(3, queue -> queue.isWriteOperation());
+ requestPathMetricsCollector.logTopPaths(newSlot, entry -> sb1.append(entry.getKey()
+ + " : "
+ + entry.getValue()
+ + "\n"));
+ assertTrue(sb1.toString().startsWith("/path1/path2/path3 : 1000"));
+ StringBuilder sb2 = new StringBuilder();
+ newSlot = requestPathMetricsCollector.aggregatePaths(3, queue -> !queue.isWriteOperation());
+ requestPathMetricsCollector.logTopPaths(newSlot, entry -> sb2.append(entry.getKey()
+ + " : "
+ + entry.getValue()
+ + "\n"));
+ assertTrue(sb2.toString().startsWith("/path1/path2/path3 : 1110001"));
+ StringBuilder sb3 = new StringBuilder();
newSlot = requestPathMetricsCollector.aggregatePaths(4, queue -> true);
- requestPathMetricsCollector.logTopPaths(newSlot,
- entry -> sb3.append(entry.getKey() + " : " + entry.getValue() + "\n"));
- Assert.assertTrue(sb3.toString().startsWith("/path1/path2/path3/path4 : 1110001"));
+ requestPathMetricsCollector.logTopPaths(newSlot, entry -> sb3.append(entry.getKey()
+ + " : "
+ + entry.getValue()
+ + "\n"));
+ assertTrue(sb3.toString().startsWith("/path1/path2/path3/path4 : 1110001"));
}
@Test
@@ -430,37 +418,34 @@ public class RequestPathMetricsCollectorTest {
RequestPathMetricsCollector requestPathMetricsCollector = new RequestPathMetricsCollector();
Random rand = new Random(System.currentTimeMillis());
Long startTime = System.currentTimeMillis();
- ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newCachedThreadPool();
+ ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newCachedThreadPool();
//call 100k get Data
- for(int i = 0; i < 100000; i++) {
- executor.submit( new Thread(() ->
- requestPathMetricsCollector.registerRequest(getData,
- "/path1/path2/path"+rand.nextInt(10))));
+ for (int i = 0; i < 100000; i++) {
+ executor.submit(new Thread(() -> requestPathMetricsCollector.registerRequest(getData, "/path1/path2/path"
+ + rand.nextInt(10))));
}
//5K create
- for(int i = 0; i < 5000; i++) {
- executor.submit( new Thread(() ->
- requestPathMetricsCollector.registerRequest(create2,
- "/path1/path2/path"+rand.nextInt(10) )));
+ for (int i = 0; i < 5000; i++) {
+ executor.submit(new Thread(() -> requestPathMetricsCollector.registerRequest(create2, "/path1/path2/path"
+ + rand.nextInt(10))));
}
//5K delete
- for(int i = 0; i < 5000; i++) {
- executor.submit( new Thread(() ->
- requestPathMetricsCollector.registerRequest(delete,
- "/path1/path2/path"+rand.nextInt(10) )));
+ for (int i = 0; i < 5000; i++) {
+ executor.submit(new Thread(() -> requestPathMetricsCollector.registerRequest(delete, "/path1/path2/path"
+ + rand.nextInt(10))));
}
//40K getChildren
- for(int i = 0; i < 40000; i++) {
- executor.submit( new Thread(() ->
- requestPathMetricsCollector.registerRequest(getChildren,
- "/path1/path2/path"+rand.nextInt(10) )));
+ for (int i = 0; i < 40000; i++) {
+ executor.submit(new Thread(() -> requestPathMetricsCollector.registerRequest(getChildren, "/path1/path2/path"
+ + rand.nextInt(10))));
}
executor.shutdown();
//wait for at most 10 mill seconds
executor.awaitTermination(10, TimeUnit.MILLISECONDS);
- Assert.assertTrue(executor.isTerminated());
+ assertTrue(executor.isTerminated());
Long endTime = System.currentTimeMillis();
//less than 2 seconds total time
- Assert.assertTrue(TimeUnit.MILLISECONDS.toSeconds(endTime-startTime) < 3);
+ assertTrue(TimeUnit.MILLISECONDS.toSeconds(endTime - startTime) < 3);
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/util/SerializeUtilsTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/util/SerializeUtilsTest.java
index b2d563006..5caa71800 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/util/SerializeUtilsTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/util/SerializeUtilsTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,19 +18,6 @@
package org.apache.zookeeper.server.util;
-import org.apache.jute.BinaryOutputArchive;
-import org.apache.jute.OutputArchive;
-import org.apache.jute.Record;
-import org.apache.zookeeper.server.Request;
-import org.apache.zookeeper.txn.TxnHeader;
-import org.junit.Test;
-import org.mockito.InOrder;
-import org.mockito.invocation.InvocationOnMock;
-import org.mockito.stubbing.Answer;
-
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
@@ -41,6 +28,17 @@ import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import org.apache.jute.BinaryOutputArchive;
+import org.apache.jute.OutputArchive;
+import org.apache.jute.Record;
+import org.apache.zookeeper.server.Request;
+import org.apache.zookeeper.txn.TxnHeader;
+import org.junit.Test;
+import org.mockito.InOrder;
+import org.mockito.invocation.InvocationOnMock;
+import org.mockito.stubbing.Answer;
public class SerializeUtilsTest {
@@ -125,4 +123,5 @@ public class SerializeUtilsTest {
baos.close();
assertArrayEquals(baos.toByteArray(), data);
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/util/VerifyingFileFactoryTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/util/VerifyingFileFactoryTest.java
index 0bf5b61db..925b01fea 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/util/VerifyingFileFactoryTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/util/VerifyingFileFactoryTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,10 +18,8 @@
package org.apache.zookeeper.server.util;
-import static org.junit.Assert.*;
-
+import static org.junit.Assert.assertEquals;
import java.io.File;
-
import org.apache.zookeeper.ZKTestCase;
import org.junit.Before;
import org.junit.Test;
@@ -33,30 +31,27 @@ public class VerifyingFileFactoryTest extends ZKTestCase {
private Logger log;
@Before
- public void setUp(){
+ public void setUp() {
log = LoggerFactory.getLogger("TODO: Mock Logging");
}
@Test
public void testForWarningOnRelativePath() {
- VerifyingFileFactory vff = new VerifyingFileFactory.Builder(log)
- .warnForRelativePath().build();
+ VerifyingFileFactory vff = new VerifyingFileFactory.Builder(log).warnForRelativePath().build();
vff.create("a/relative/path");
// assertTrue(log.hasWarned);
}
@Test
public void testForNoWarningOnIntendedRelativePath() {
- VerifyingFileFactory vff = new VerifyingFileFactory.Builder(log)
- .warnForRelativePath().build();
+ VerifyingFileFactory vff = new VerifyingFileFactory.Builder(log).warnForRelativePath().build();
vff.create("./an/intended/relative/path");
// assertFalse(log.hasWarned);
}
- @Test(expected=IllegalArgumentException.class)
+ @Test(expected = IllegalArgumentException.class)
public void testForFailForNonExistingPath() {
- VerifyingFileFactory vff = new VerifyingFileFactory.Builder(log)
- .failForNonExistingPath().build();
+ VerifyingFileFactory vff = new VerifyingFileFactory.Builder(log).failForNonExistingPath().build();
vff.create("/I/H0p3/this/path/d035/n0t/ex15t");
}
@@ -66,4 +61,5 @@ public class VerifyingFileFactoryTest extends ZKTestCase {
VerifyingFileFactory vff = new VerifyingFileFactory.Builder(log).build();
assertEquals(file, vff.create(file.getPath()));
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/watch/WatchManagerTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/watch/WatchManagerTest.java
index b106d073b..0ce0a59a0 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/watch/WatchManagerTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/watch/WatchManagerTest.java
@@ -14,39 +14,39 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
package org.apache.zookeeper.server.watch;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
import java.io.IOException;
-import java.util.Arrays;
import java.util.ArrayList;
-import java.util.HashMap;
+import java.util.Arrays;
+import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
-import java.util.HashSet;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
-
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.Watcher.Event.EventType;
-import org.apache.zookeeper.server.DumbWatcher;
-import org.apache.zookeeper.server.ServerCnxn;
-
import org.apache.zookeeper.ZKTestCase;
import org.apache.zookeeper.metrics.MetricsUtils;
+import org.apache.zookeeper.server.DumbWatcher;
+import org.apache.zookeeper.server.ServerCnxn;
import org.apache.zookeeper.server.ServerMetrics;
-import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
-
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@RunWith(Parameterized.class)
public class WatchManagerTest extends ZKTestCase {
+
protected static final Logger LOG = LoggerFactory.getLogger(WatchManagerTest.class);
private static final String PATH_PREFIX = "path";
@@ -60,11 +60,8 @@ public class WatchManagerTest extends ZKTestCase {
}
@Parameterized.Parameters
- public static List<Object []> data() {
- return Arrays.asList(new Object [][] {
- {WatchManager.class.getName()},
- {WatchManagerOptimized.class.getName()}
- });
+ public static List<Object[]> data() {
+ return Arrays.asList(new Object[][]{{WatchManager.class.getName()}, {WatchManagerOptimized.class.getName()}});
}
@Before
@@ -95,8 +92,8 @@ public class WatchManagerTest extends ZKTestCase {
private final AtomicInteger watchesAdded;
private volatile boolean stopped = false;
- public AddWatcherWorker(IWatchManager manager,
- int paths, int watchers, AtomicInteger watchesAdded) {
+ public AddWatcherWorker(
+ IWatchManager manager, int paths, int watchers, AtomicInteger watchesAdded) {
this.manager = manager;
this.paths = paths;
this.watchers = watchers;
@@ -117,6 +114,7 @@ public class WatchManagerTest extends ZKTestCase {
public void shutdown() {
stopped = true;
}
+
}
public class WatcherTriggerWorker extends Thread {
@@ -126,8 +124,8 @@ public class WatchManagerTest extends ZKTestCase {
private final AtomicInteger triggeredCount;
private volatile boolean stopped = false;
- public WatcherTriggerWorker(IWatchManager manager,
- int paths, AtomicInteger triggeredCount) {
+ public WatcherTriggerWorker(
+ IWatchManager manager, int paths, AtomicInteger triggeredCount) {
this.manager = manager;
this.paths = paths;
this.triggeredCount = triggeredCount;
@@ -137,20 +135,21 @@ public class WatchManagerTest extends ZKTestCase {
public void run() {
while (!stopped) {
String path = PATH_PREFIX + r.nextInt(paths);
- WatcherOrBitSet s = manager.triggerWatch(
- path, EventType.NodeDeleted);
+ WatcherOrBitSet s = manager.triggerWatch(path, EventType.NodeDeleted);
if (s != null) {
triggeredCount.addAndGet(s.size());
}
try {
Thread.sleep(r.nextInt(10));
- } catch (InterruptedException e) {}
+ } catch (InterruptedException e) {
+ }
}
}
public void shutdown() {
stopped = true;
}
+
}
public class RemoveWatcherWorker extends Thread {
@@ -161,8 +160,8 @@ public class WatchManagerTest extends ZKTestCase {
private final AtomicInteger watchesRemoved;
private volatile boolean stopped = false;
- public RemoveWatcherWorker(IWatchManager manager,
- int paths, int watchers, AtomicInteger watchesRemoved) {
+ public RemoveWatcherWorker(
+ IWatchManager manager, int paths, int watchers, AtomicInteger watchesRemoved) {
this.manager = manager;
this.paths = paths;
this.watchers = watchers;
@@ -179,7 +178,8 @@ public class WatchManagerTest extends ZKTestCase {
}
try {
Thread.sleep(r.nextInt(10));
- } catch (InterruptedException e) {}
+ } catch (InterruptedException e) {
+ }
}
}
@@ -196,8 +196,8 @@ public class WatchManagerTest extends ZKTestCase {
private final Set<Watcher> removedWatchers;
private volatile boolean stopped = false;
- public CreateDeadWatchersWorker(IWatchManager manager,
- int watchers, Set<Watcher> removedWatchers) {
+ public CreateDeadWatchersWorker(
+ IWatchManager manager, int watchers, Set<Watcher> removedWatchers) {
this.manager = manager;
this.watchers = watchers;
this.removedWatchers = removedWatchers;
@@ -214,7 +214,8 @@ public class WatchManagerTest extends ZKTestCase {
}
try {
Thread.sleep(r.nextInt(10));
- } catch (InterruptedException e) {}
+ } catch (InterruptedException e) {
+ }
}
}
@@ -237,11 +238,9 @@ public class WatchManagerTest extends ZKTestCase {
// 1. start 5 workers to trigger watchers on that path
// count all the watchers have been fired
AtomicInteger watchTriggered = new AtomicInteger();
- List<WatcherTriggerWorker> triggerWorkers =
- new ArrayList<WatcherTriggerWorker>();
+ List<WatcherTriggerWorker> triggerWorkers = new ArrayList<WatcherTriggerWorker>();
for (int i = 0; i < 5; i++) {
- WatcherTriggerWorker worker =
- new WatcherTriggerWorker(manager, paths, watchTriggered);
+ WatcherTriggerWorker worker = new WatcherTriggerWorker(manager, paths, watchTriggered);
triggerWorkers.add(worker);
worker.start();
}
@@ -251,8 +250,7 @@ public class WatchManagerTest extends ZKTestCase {
AtomicInteger watchesAdded = new AtomicInteger();
List<AddWatcherWorker> addWorkers = new ArrayList<AddWatcherWorker>();
for (int i = 0; i < 5; i++) {
- AddWatcherWorker worker = new AddWatcherWorker(
- manager, paths, watchers, watchesAdded);
+ AddWatcherWorker worker = new AddWatcherWorker(manager, paths, watchers, watchesAdded);
addWorkers.add(worker);
worker.start();
}
@@ -260,11 +258,12 @@ public class WatchManagerTest extends ZKTestCase {
while (watchesAdded.get() < 100000) {
try {
Thread.sleep(100);
- } catch (InterruptedException e) {}
+ } catch (InterruptedException e) {
+ }
}
// 3. stop all the addWorkers
- for (AddWatcherWorker worker: addWorkers) {
+ for (AddWatcherWorker worker : addWorkers) {
worker.shutdown();
}
@@ -272,16 +271,17 @@ public class WatchManagerTest extends ZKTestCase {
// all watchers added are fired
try {
Thread.sleep(500);
- } catch (InterruptedException e) {}
+ } catch (InterruptedException e) {
+ }
// 5. stop all triggerWorkers
- for (WatcherTriggerWorker worker: triggerWorkers) {
+ for (WatcherTriggerWorker worker : triggerWorkers) {
worker.shutdown();
}
// 6. make sure the total watch triggered is same as added
- Assert.assertTrue(watchesAdded.get() > 0);
- Assert.assertEquals(watchesAdded.get(), watchTriggered.get());
+ assertTrue(watchesAdded.get() > 0);
+ assertEquals(watchesAdded.get(), watchTriggered.get());
}
/**
@@ -297,11 +297,9 @@ public class WatchManagerTest extends ZKTestCase {
// 1. start 5 workers to remove watchers on those path
// record the watchers have been removed
AtomicInteger watchesRemoved = new AtomicInteger();
- List<RemoveWatcherWorker> removeWorkers =
- new ArrayList<RemoveWatcherWorker>();
+ List<RemoveWatcherWorker> removeWorkers = new ArrayList<RemoveWatcherWorker>();
for (int i = 0; i < 5; i++) {
- RemoveWatcherWorker worker =
- new RemoveWatcherWorker(manager, paths, watchers, watchesRemoved);
+ RemoveWatcherWorker worker = new RemoveWatcherWorker(manager, paths, watchers, watchesRemoved);
removeWorkers.add(worker);
worker.start();
}
@@ -311,8 +309,7 @@ public class WatchManagerTest extends ZKTestCase {
AtomicInteger watchesAdded = new AtomicInteger();
List<AddWatcherWorker> addWorkers = new ArrayList<AddWatcherWorker>();
for (int i = 0; i < 5; i++) {
- AddWatcherWorker worker = new AddWatcherWorker(
- manager, paths, watchers, watchesAdded);
+ AddWatcherWorker worker = new AddWatcherWorker(manager, paths, watchers, watchesAdded);
addWorkers.add(worker);
worker.start();
}
@@ -320,28 +317,29 @@ public class WatchManagerTest extends ZKTestCase {
while (watchesAdded.get() < 100000) {
try {
Thread.sleep(100);
- } catch (InterruptedException e) {}
+ } catch (InterruptedException e) {
+ }
}
// 3. stop all workers
- for (RemoveWatcherWorker worker: removeWorkers) {
+ for (RemoveWatcherWorker worker : removeWorkers) {
worker.shutdown();
}
- for (AddWatcherWorker worker: addWorkers) {
+ for (AddWatcherWorker worker : addWorkers) {
worker.shutdown();
}
// 4. sleep for a while to make sure all the thread exited
try {
Thread.sleep(500);
- } catch (InterruptedException e) {}
+ } catch (InterruptedException e) {
+ }
// 5. make sure left watches + removed watches = added watches
- Assert.assertTrue(watchesAdded.get() > 0);
- Assert.assertTrue(watchesRemoved.get() > 0);
- Assert.assertTrue(manager.size() > 0);
- Assert.assertEquals(
- watchesAdded.get(), watchesRemoved.get() + manager.size());
+ assertTrue(watchesAdded.get() > 0);
+ assertTrue(watchesRemoved.get() > 0);
+ assertTrue(manager.size() > 0);
+ assertEquals(watchesAdded.get(), watchesRemoved.get() + manager.size());
}
/**
@@ -360,11 +358,9 @@ public class WatchManagerTest extends ZKTestCase {
// 1. start 5 workers to randomly mark those watcher as dead
// and remove them from watch manager
Set<Watcher> deadWatchers = new HashSet<Watcher>();
- List<CreateDeadWatchersWorker> deadWorkers =
- new ArrayList<CreateDeadWatchersWorker>();
+ List<CreateDeadWatchersWorker> deadWorkers = new ArrayList<CreateDeadWatchersWorker>();
for (int i = 0; i < 5; i++) {
- CreateDeadWatchersWorker worker = new CreateDeadWatchersWorker(
- manager, watchers, deadWatchers);
+ CreateDeadWatchersWorker worker = new CreateDeadWatchersWorker(manager, watchers, deadWatchers);
deadWorkers.add(worker);
worker.start();
}
@@ -373,8 +369,7 @@ public class WatchManagerTest extends ZKTestCase {
AtomicInteger watchesAdded = new AtomicInteger();
List<AddWatcherWorker> addWorkers = new ArrayList<AddWatcherWorker>();
for (int i = 0; i < 5; i++) {
- AddWatcherWorker worker = new AddWatcherWorker(
- manager, paths, watchers, watchesAdded);
+ AddWatcherWorker worker = new AddWatcherWorker(manager, paths, watchers, watchesAdded);
addWorkers.add(worker);
worker.start();
}
@@ -382,14 +377,15 @@ public class WatchManagerTest extends ZKTestCase {
while (watchesAdded.get() < 50000) {
try {
Thread.sleep(100);
- } catch (InterruptedException e) {}
+ } catch (InterruptedException e) {
+ }
}
// 3. stop all workers
- for (CreateDeadWatchersWorker worker: deadWorkers) {
+ for (CreateDeadWatchersWorker worker : deadWorkers) {
worker.shutdown();
}
- for (AddWatcherWorker worker: addWorkers) {
+ for (AddWatcherWorker worker : addWorkers) {
worker.shutdown();
}
@@ -398,24 +394,24 @@ public class WatchManagerTest extends ZKTestCase {
// So need to sleep as least that long
try {
Thread.sleep(2000);
- } catch (InterruptedException e) {}
+ } catch (InterruptedException e) {
+ }
// 5. make sure the dead watchers are not in the existing watchers
WatchesReport existingWatchers = manager.getWatches();
- for (Watcher w: deadWatchers) {
- Assert.assertFalse(
- existingWatchers.hasPaths(((ServerCnxn) w).getSessionId()));
+ for (Watcher w : deadWatchers) {
+ assertFalse(existingWatchers.hasPaths(((ServerCnxn) w).getSessionId()));
}
}
- private void checkMetrics(String metricName, long min, long max, double avg, long cnt, long sum){
+ private void checkMetrics(String metricName, long min, long max, double avg, long cnt, long sum) {
Map<String, Object> values = MetricsUtils.currentServerMetrics();
- Assert.assertEquals(min, values.get("min_" + metricName));
- Assert.assertEquals(max, values.get("max_" + metricName));
- Assert.assertEquals(avg, (Double)values.get("avg_" + metricName), 0.000001);
- Assert.assertEquals(cnt, values.get("cnt_" + metricName));
- Assert.assertEquals(sum, values.get("sum_" + metricName));
+ assertEquals(min, values.get("min_" + metricName));
+ assertEquals(max, values.get("max_" + metricName));
+ assertEquals(avg, (Double) values.get("avg_" + metricName), 0.000001);
+ assertEquals(cnt, values.get("cnt_" + metricName));
+ assertEquals(sum, values.get("sum_" + metricName));
}
@Test
@@ -470,4 +466,5 @@ public class WatchManagerTest extends ZKTestCase {
//make sure that node created watch count is not impacted by the fire of other event types
checkMetrics("node_created_watch_count", 1L, 2L, 1.5D, 2L, 3L);
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/watch/WatcherCleanerTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/watch/WatcherCleanerTest.java
index cf0a5f435..5152b5eb2 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/watch/WatcherCleanerTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/watch/WatcherCleanerTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
@@ -14,28 +14,29 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
package org.apache.zookeeper.server.watch;
-import java.util.HashMap;
+import static org.hamcrest.number.OrderingComparison.greaterThan;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertThat;
+import static org.junit.Assert.assertTrue;
+import java.util.HashSet;
import java.util.Map;
import java.util.Set;
-import java.util.HashSet;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
-
import org.apache.zookeeper.ZKTestCase;
import org.apache.zookeeper.common.Time;
import org.apache.zookeeper.metrics.MetricsUtils;
-import org.apache.zookeeper.metrics.impl.DefaultMetricsProvider;
import org.apache.zookeeper.server.ServerMetrics;
import org.junit.Test;
-import org.junit.Assert;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import static org.hamcrest.number.OrderingComparison.greaterThan;
-
public class WatcherCleanerTest extends ZKTestCase {
+
private static final Logger LOG = LoggerFactory.getLogger(WatcherCleanerTest.class);
public static class MyDeadWatcherListener implements IDeadWatcherListener {
@@ -57,7 +58,8 @@ public class WatcherCleanerTest extends ZKTestCase {
if (delayMs > 0) {
try {
Thread.sleep(delayMs);
- } catch (InterruptedException e) {}
+ } catch (InterruptedException e) {
+ }
}
this.deadWatchers.clear();
this.deadWatchers.addAll(deadWatchers);
@@ -71,9 +73,11 @@ public class WatcherCleanerTest extends ZKTestCase {
public boolean wait(int maxWaitMs) {
try {
return latch.await(maxWaitMs, TimeUnit.MILLISECONDS);
- } catch (InterruptedException e) {}
+ } catch (InterruptedException e) {
+ }
return false;
}
+
}
@Test
@@ -88,13 +92,13 @@ public class WatcherCleanerTest extends ZKTestCase {
cleaner.addDeadWatcher(i);
}
// not trigger processDeadWatchers yet
- Assert.assertEquals(0, listener.getDeadWatchers().size());
+ assertEquals(0, listener.getDeadWatchers().size());
listener.setCountDownLatch(new CountDownLatch(1));
// add another dead watcher to trigger the process
cleaner.addDeadWatcher(i);
- Assert.assertTrue(listener.wait(1000));
- Assert.assertEquals(threshold, listener.getDeadWatchers().size());
+ assertTrue(listener.wait(1000));
+ assertEquals(threshold, listener.getDeadWatchers().size());
}
@Test
@@ -105,15 +109,15 @@ public class WatcherCleanerTest extends ZKTestCase {
cleaner.addDeadWatcher(1);
// not trigger processDeadWatchers yet
- Assert.assertEquals(0, listener.getDeadWatchers().size());
+ assertEquals(0, listener.getDeadWatchers().size());
listener.setCountDownLatch(new CountDownLatch(1));
- Assert.assertTrue(listener.wait(2000));
- Assert.assertEquals(1, listener.getDeadWatchers().size());
+ assertTrue(listener.wait(2000));
+ assertEquals(1, listener.getDeadWatchers().size());
// won't trigger event if there is no dead watchers
listener.setCountDownLatch(new CountDownLatch(1));
- Assert.assertFalse(listener.wait(2000));
+ assertFalse(listener.wait(2000));
}
@Test
@@ -131,8 +135,8 @@ public class WatcherCleanerTest extends ZKTestCase {
cleaner.addDeadWatcher(2);
long time = Time.currentElapsedTime() - startTime;
System.out.println("time used " + time);
- Assert.assertTrue(Time.currentElapsedTime() - startTime >= delayMs);
- Assert.assertTrue(listener.wait(5000));
+ assertTrue(Time.currentElapsedTime() - startTime >= delayMs);
+ assertTrue(listener.wait(5000));
}
@Test
@@ -149,23 +153,22 @@ public class WatcherCleanerTest extends ZKTestCase {
cleaner.addDeadWatcher(2);
cleaner.addDeadWatcher(3);
- Assert.assertTrue(listener.wait(5000));
-
+ assertTrue(listener.wait(5000));
+
Map<String, Object> values = MetricsUtils.currentServerMetrics();
- Assert.assertThat("Adding dead watcher should be stalled twice",
- (Long)values.get("add_dead_watcher_stall_time"),
- greaterThan(0L));
- Assert.assertEquals("Total dead watchers added to the queue should be 3", 3L, values.get("dead_watchers_queued"));
- Assert.assertEquals("Total dead watchers cleared should be 3", 3L, values.get("dead_watchers_cleared"));
+ assertThat("Adding dead watcher should be stalled twice", (Long) values.get("add_dead_watcher_stall_time"), greaterThan(0L));
+ assertEquals("Total dead watchers added to the queue should be 3", 3L, values.get("dead_watchers_queued"));
+ assertEquals("Total dead watchers cleared should be 3", 3L, values.get("dead_watchers_cleared"));
- Assert.assertEquals(3L, values.get("cnt_dead_watchers_cleaner_latency"));
+ assertEquals(3L, values.get("cnt_dead_watchers_cleaner_latency"));
//Each latency should be a little over 20 ms, allow 5 ms deviation
- Assert.assertEquals(20D, (Double)values.get("avg_dead_watchers_cleaner_latency"), 5);
- Assert.assertEquals(20D, ((Long)values.get("min_dead_watchers_cleaner_latency")).doubleValue(), 5);
- Assert.assertEquals(20D, ((Long)values.get("max_dead_watchers_cleaner_latency")).doubleValue(), 5);
- Assert.assertEquals(20D, ((Long)values.get("p50_dead_watchers_cleaner_latency")).doubleValue(), 5);
- Assert.assertEquals(20D, ((Long)values.get("p95_dead_watchers_cleaner_latency")).doubleValue(), 5);
- Assert.assertEquals(20D, ((Long)values.get("p99_dead_watchers_cleaner_latency")).doubleValue(), 5);
+ assertEquals(20D, (Double) values.get("avg_dead_watchers_cleaner_latency"), 5);
+ assertEquals(20D, ((Long) values.get("min_dead_watchers_cleaner_latency")).doubleValue(), 5);
+ assertEquals(20D, ((Long) values.get("max_dead_watchers_cleaner_latency")).doubleValue(), 5);
+ assertEquals(20D, ((Long) values.get("p50_dead_watchers_cleaner_latency")).doubleValue(), 5);
+ assertEquals(20D, ((Long) values.get("p95_dead_watchers_cleaner_latency")).doubleValue(), 5);
+ assertEquals(20D, ((Long) values.get("p99_dead_watchers_cleaner_latency")).doubleValue(), 5);
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/watch/WatcherOrBitSetTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/watch/WatcherOrBitSetTest.java
index 03334a33b..ee105dfa6 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/watch/WatcherOrBitSetTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/watch/WatcherOrBitSetTest.java
@@ -14,18 +14,19 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
package org.apache.zookeeper.server.watch;
-import java.util.Set;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
import java.util.HashSet;
-
+import java.util.Set;
import org.apache.zookeeper.Watcher;
+import org.apache.zookeeper.ZKTestCase;
import org.apache.zookeeper.server.DumbWatcher;
import org.apache.zookeeper.server.util.BitHashSet;
-
-import org.apache.zookeeper.ZKTestCase;
import org.junit.Test;
-import org.junit.Assert;
public class WatcherOrBitSetTest extends ZKTestCase {
@@ -33,29 +34,30 @@ public class WatcherOrBitSetTest extends ZKTestCase {
public void testWatcherSet() {
Set<Watcher> wset = new HashSet<Watcher>();
WatcherOrBitSet hashSet = new WatcherOrBitSet(wset);
- Assert.assertEquals(0, hashSet.size());
+ assertEquals(0, hashSet.size());
DumbWatcher w1 = new DumbWatcher();
- Assert.assertFalse(hashSet.contains(w1));
+ assertFalse(hashSet.contains(w1));
wset.add(w1);
- Assert.assertTrue(hashSet.contains(w1));
- Assert.assertEquals(1, hashSet.size());
- Assert.assertFalse(hashSet.contains(1));
+ assertTrue(hashSet.contains(w1));
+ assertEquals(1, hashSet.size());
+ assertFalse(hashSet.contains(1));
}
@Test
public void testBitSet() {
BitHashSet bset = new BitHashSet(0);
WatcherOrBitSet bitSet = new WatcherOrBitSet(bset);
- Assert.assertEquals(0, bitSet.size());
+ assertEquals(0, bitSet.size());
Integer bit = 1;
- Assert.assertFalse(bitSet.contains(1));
- Assert.assertFalse(bitSet.contains(bit));
+ assertFalse(bitSet.contains(1));
+ assertFalse(bitSet.contains(bit));
bset.add(bit);
- Assert.assertTrue(bitSet.contains(1));
- Assert.assertTrue(bitSet.contains(bit));
- Assert.assertEquals(1, bitSet.size());
+ assertTrue(bitSet.contains(1));
+ assertTrue(bitSet.contains(bit));
+ assertEquals(1, bitSet.size());
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/watch/WatchesPathReportTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/watch/WatchesPathReportTest.java
index 34e378952..123b49bd5 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/watch/WatchesPathReportTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/watch/WatchesPathReportTest.java
@@ -14,8 +14,13 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
package org.apache.zookeeper.server.watch;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
@@ -23,12 +28,13 @@ import java.util.Set;
import org.apache.zookeeper.ZKTestCase;
import org.junit.Before;
import org.junit.Test;
-import static org.junit.Assert.*;
public class WatchesPathReportTest extends ZKTestCase {
+
private Map<String, Set<Long>> m;
private WatchesPathReport r;
- @Before public void setUp() {
+ @Before
+ public void setUp() {
m = new HashMap<String, Set<Long>>();
Set<Long> s = new HashSet<Long>();
s.add(101L);
@@ -39,12 +45,14 @@ public class WatchesPathReportTest extends ZKTestCase {
m.put("path2", s);
r = new WatchesPathReport(m);
}
- @Test public void testHasSessions() {
+ @Test
+ public void testHasSessions() {
assertTrue(r.hasSessions("path1"));
assertTrue(r.hasSessions("path2"));
assertFalse(r.hasSessions("path3"));
}
- @Test public void testGetSessions() {
+ @Test
+ public void testGetSessions() {
Set<Long> s = r.getSessions("path1");
assertEquals(2, s.size());
assertTrue(s.contains(101L));
@@ -54,7 +62,9 @@ public class WatchesPathReportTest extends ZKTestCase {
assertTrue(s.contains(201L));
assertNull(r.getSessions("path3"));
}
- @Test public void testToMap() {
+ @Test
+ public void testToMap() {
assertEquals(m, r.toMap());
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/watch/WatchesReportTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/watch/WatchesReportTest.java
index 237583a46..05c0547d9 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/watch/WatchesReportTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/watch/WatchesReportTest.java
@@ -14,8 +14,13 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
package org.apache.zookeeper.server.watch;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
@@ -23,12 +28,13 @@ import java.util.Set;
import org.apache.zookeeper.ZKTestCase;
import org.junit.Before;
import org.junit.Test;
-import static org.junit.Assert.*;
public class WatchesReportTest extends ZKTestCase {
+
private Map<Long, Set<String>> m;
private WatchesReport r;
- @Before public void setUp() {
+ @Before
+ public void setUp() {
m = new HashMap<Long, Set<String>>();
Set<String> s = new HashSet<String>();
s.add("path1a");
@@ -39,12 +45,14 @@ public class WatchesReportTest extends ZKTestCase {
m.put(2L, s);
r = new WatchesReport(m);
}
- @Test public void testHasPaths() {
+ @Test
+ public void testHasPaths() {
assertTrue(r.hasPaths(1L));
assertTrue(r.hasPaths(2L));
assertFalse(r.hasPaths(3L));
}
- @Test public void testGetPaths() {
+ @Test
+ public void testGetPaths() {
Set<String> s = r.getPaths(1L);
assertEquals(2, s.size());
assertTrue(s.contains("path1a"));
@@ -54,7 +62,9 @@ public class WatchesReportTest extends ZKTestCase {
assertTrue(s.contains("path2a"));
assertNull(r.getPaths(3L));
}
- @Test public void testToMap() {
+ @Test
+ public void testToMap() {
assertEquals(m, r.toMap());
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/watch/WatchesSummaryTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/watch/WatchesSummaryTest.java
index 35956f185..9d53281ed 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/watch/WatchesSummaryTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/watch/WatchesSummaryTest.java
@@ -14,29 +14,35 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
package org.apache.zookeeper.server.watch;
+import static org.junit.Assert.assertEquals;
import java.util.Map;
import org.apache.zookeeper.ZKTestCase;
import org.junit.Before;
import org.junit.Test;
-import static org.junit.Assert.*;
public class WatchesSummaryTest extends ZKTestCase {
+
private WatchesSummary s;
- @Before public void setUp() {
+ @Before
+ public void setUp() {
s = new WatchesSummary(1, 2, 3);
}
- @Test public void testGetters() {
+ @Test
+ public void testGetters() {
assertEquals(1, s.getNumConnections());
assertEquals(2, s.getNumPaths());
assertEquals(3, s.getTotalWatches());
}
- @Test public void testToMap() {
+ @Test
+ public void testToMap() {
Map<String, Object> m = s.toMap();
assertEquals(3, m.size());
assertEquals(Integer.valueOf(1), m.get(WatchesSummary.KEY_NUM_CONNECTIONS));
assertEquals(Integer.valueOf(2), m.get(WatchesSummary.KEY_NUM_PATHS));
assertEquals(Integer.valueOf(3), m.get(WatchesSummary.KEY_NUM_TOTAL_WATCHES));
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/ACLCountTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/ACLCountTest.java
index 6c876cbb4..6b8f9ff38 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/ACLCountTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/ACLCountTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -19,31 +19,30 @@
package org.apache.zookeeper.test;
import static org.apache.zookeeper.test.ClientBase.CONNECTION_TIMEOUT;
-
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.PortAssignment;
import org.apache.zookeeper.ZKTestCase;
-import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooDefs.Ids;
+import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.ACL;
import org.apache.zookeeper.data.Stat;
import org.apache.zookeeper.server.ServerCnxnFactory;
import org.apache.zookeeper.server.SyncRequestProcessor;
import org.apache.zookeeper.server.ZooKeeperServer;
-import org.junit.Assert;
import org.junit.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class ACLCountTest extends ZKTestCase {
-public class ACLCountTest extends ZKTestCase{
private static final Logger LOG = LoggerFactory.getLogger(ACLCountTest.class);
- private static final String HOSTPORT =
- "127.0.0.1:" + PortAssignment.unique();
+ private static final String HOSTPORT = "127.0.0.1:" + PortAssignment.unique();
/**
*
@@ -69,18 +68,18 @@ public class ACLCountTest extends ZKTestCase{
f.startup(zks);
ZooKeeper zk;
- final ArrayList<ACL> CREATOR_ALL_AND_WORLD_READABLE =
- new ArrayList<ACL>() { {
- add(new ACL(ZooDefs.Perms.READ,ZooDefs.Ids.ANYONE_ID_UNSAFE));
- add(new ACL(ZooDefs.Perms.ALL,ZooDefs.Ids.AUTH_IDS));
- add(new ACL(ZooDefs.Perms.READ,ZooDefs.Ids.ANYONE_ID_UNSAFE));
- add(new ACL(ZooDefs.Perms.ALL,ZooDefs.Ids.AUTH_IDS));
- }};
+ final ArrayList<ACL> CREATOR_ALL_AND_WORLD_READABLE = new ArrayList<ACL>() {
+ {
+ add(new ACL(ZooDefs.Perms.READ, ZooDefs.Ids.ANYONE_ID_UNSAFE));
+ add(new ACL(ZooDefs.Perms.ALL, ZooDefs.Ids.AUTH_IDS));
+ add(new ACL(ZooDefs.Perms.READ, ZooDefs.Ids.ANYONE_ID_UNSAFE));
+ add(new ACL(ZooDefs.Perms.ALL, ZooDefs.Ids.AUTH_IDS));
+ }
+ };
try {
LOG.info("starting up the zookeeper server .. waiting");
- Assert.assertTrue("waiting for server being up",
- ClientBase.waitForServerUp(HOSTPORT, CONNECTION_TIMEOUT));
+ assertTrue("waiting for server being up", ClientBase.waitForServerUp(HOSTPORT, CONNECTION_TIMEOUT));
zk = ClientBase.createZKClient(HOSTPORT);
zk.addAuthInfo("digest", "pat:test".getBytes());
@@ -89,23 +88,22 @@ public class ACLCountTest extends ZKTestCase{
String path = "/path";
try {
- Assert.assertEquals(4,CREATOR_ALL_AND_WORLD_READABLE.size());
- }
- catch (Exception e) {
- LOG.error("Something is fundamentally wrong with ArrayList's add() method. add()ing four times to an empty ArrayList should result in an ArrayList with 4 members.");
- throw e;
+ assertEquals(4, CREATOR_ALL_AND_WORLD_READABLE.size());
+ } catch (Exception e) {
+ LOG.error("Something is fundamentally wrong with ArrayList's add() method. add()ing four times to an empty ArrayList should result in an ArrayList with 4 members.");
+ throw e;
}
- zk.create(path,path.getBytes(),CREATOR_ALL_AND_WORLD_READABLE,CreateMode.PERSISTENT);
+ zk.create(path, path.getBytes(), CREATOR_ALL_AND_WORLD_READABLE, CreateMode.PERSISTENT);
List<ACL> acls = zk.getACL("/path", new Stat());
- Assert.assertEquals(2,acls.size());
- }
- catch (Exception e) {
- // test failed somehow.
- Assert.assertTrue(false);
+ assertEquals(2, acls.size());
+ } catch (Exception e) {
+ // test failed somehow.
+ assertTrue(false);
}
f.shutdown();
zks.shutdown();
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/ACLRootTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/ACLRootTest.java
index 15c7cef2b..3f4b9d40a 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/ACLRootTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/ACLRootTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,14 +18,15 @@
package org.apache.zookeeper.test;
+import static org.junit.Assert.fail;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
-import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.ZooDefs.Ids;
-import org.junit.Assert;
+import org.apache.zookeeper.ZooKeeper;
import org.junit.Test;
public class ACLRootTest extends ClientBase {
+
@Test
public void testRootAcl() throws Exception {
ZooKeeper zk = createClient();
@@ -39,22 +40,20 @@ public class ACLRootTest extends ClientBase {
zk = createClient();
try {
zk.getData("/", false, null);
- Assert.fail("validate auth");
+ fail("validate auth");
} catch (KeeperException.NoAuthException e) {
// expected
}
try {
- zk.create("/apps", null, Ids.CREATOR_ALL_ACL,
- CreateMode.PERSISTENT);
- Assert.fail("validate auth");
+ zk.create("/apps", null, Ids.CREATOR_ALL_ACL, CreateMode.PERSISTENT);
+ fail("validate auth");
} catch (KeeperException.InvalidACLException e) {
// expected
}
zk.addAuthInfo("digest", "world:anyone".getBytes());
try {
- zk.create("/apps", null, Ids.CREATOR_ALL_ACL,
- CreateMode.PERSISTENT);
- Assert.fail("validate auth");
+ zk.create("/apps", null, Ids.CREATOR_ALL_ACL, CreateMode.PERSISTENT);
+ fail("validate auth");
} catch (KeeperException.NoAuthException e) {
// expected
}
@@ -63,27 +62,23 @@ public class ACLRootTest extends ClientBase {
zk = createClient();
zk.addAuthInfo("digest", "pat:test".getBytes());
zk.getData("/", false, null);
- zk.create("/apps", null, Ids.CREATOR_ALL_ACL,
- CreateMode.PERSISTENT);
+ zk.create("/apps", null, Ids.CREATOR_ALL_ACL, CreateMode.PERSISTENT);
zk.delete("/apps", -1);
// reset acl (back to open) and verify accessible again
zk.setACL("/", Ids.OPEN_ACL_UNSAFE, -1);
zk.close();
zk = createClient();
zk.getData("/", false, null);
- zk.create("/apps", null, Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk.create("/apps", null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
try {
- zk.create("/apps", null, Ids.CREATOR_ALL_ACL,
- CreateMode.PERSISTENT);
- Assert.fail("validate auth");
+ zk.create("/apps", null, Ids.CREATOR_ALL_ACL, CreateMode.PERSISTENT);
+ fail("validate auth");
} catch (KeeperException.InvalidACLException e) {
// expected
}
zk.delete("/apps", -1);
zk.addAuthInfo("digest", "world:anyone".getBytes());
- zk.create("/apps", null, Ids.CREATOR_ALL_ACL,
- CreateMode.PERSISTENT);
+ zk.create("/apps", null, Ids.CREATOR_ALL_ACL, CreateMode.PERSISTENT);
zk.close();
zk = createClient();
zk.delete("/apps", -1);
@@ -91,4 +86,5 @@ public class ACLRootTest extends ClientBase {
zk.close();
}
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/ACLTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/ACLTest.java
index 8b83d9fed..1bab53437 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/ACLTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/ACLTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -19,15 +19,13 @@
package org.apache.zookeeper.test;
import static org.apache.zookeeper.test.ClientBase.CONNECTION_TIMEOUT;
-
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
-
-import org.apache.zookeeper.server.ServerCnxn;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException.InvalidACLException;
import org.apache.zookeeper.PortAssignment;
@@ -35,38 +33,39 @@ import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.Watcher.Event.KeeperState;
import org.apache.zookeeper.ZKTestCase;
-import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.ZooDefs.Ids;
+import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.ACL;
import org.apache.zookeeper.data.Id;
+import org.apache.zookeeper.server.ServerCnxn;
import org.apache.zookeeper.server.ServerCnxnFactory;
import org.apache.zookeeper.server.SyncRequestProcessor;
import org.apache.zookeeper.server.ZooKeeperServer;
import org.apache.zookeeper.server.auth.IPAuthenticationProvider;
-import org.junit.Assert;
import org.junit.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
public class ACLTest extends ZKTestCase implements Watcher {
+
private static final Logger LOG = LoggerFactory.getLogger(ACLTest.class);
- private static final String HOSTPORT =
- "127.0.0.1:" + PortAssignment.unique();
+ private static final String HOSTPORT = "127.0.0.1:" + PortAssignment.unique();
private volatile CountDownLatch startSignal;
@Test
public void testIPAuthenticationIsValidCIDR() throws Exception {
IPAuthenticationProvider prov = new IPAuthenticationProvider();
- Assert.assertTrue("testing no netmask", prov.isValid("127.0.0.1"));
- Assert.assertTrue("testing single ip netmask", prov.isValid("127.0.0.1/32"));
- Assert.assertTrue("testing lowest netmask possible", prov.isValid("127.0.0.1/0"));
- Assert.assertFalse("testing netmask too high", prov.isValid("127.0.0.1/33"));
- Assert.assertFalse("testing netmask too low", prov.isValid("10.0.0.1/-1"));
+ assertTrue("testing no netmask", prov.isValid("127.0.0.1"));
+ assertTrue("testing single ip netmask", prov.isValid("127.0.0.1/32"));
+ assertTrue("testing lowest netmask possible", prov.isValid("127.0.0.1/0"));
+ assertFalse("testing netmask too high", prov.isValid("127.0.0.1/33"));
+ assertFalse("testing netmask too low", prov.isValid("10.0.0.1/-1"));
}
@Test
public void testNettyIpAuthDefault() throws Exception {
String HOSTPORT = "127.0.0.1:" + PortAssignment.unique();
- System.setProperty(ServerCnxnFactory.ZOOKEEPER_SERVER_CNXN_FACTORY,
- "org.apache.zookeeper.server.NettyServerCnxnFactory");
+ System.setProperty(ServerCnxnFactory.ZOOKEEPER_SERVER_CNXN_FACTORY, "org.apache.zookeeper.server.NettyServerCnxnFactory");
ClientBase.setupTestEnv();
File tmpDir = ClientBase.createTmpDir();
ZooKeeperServer zks = new ZooKeeperServer(tmpDir, tmpDir, 3000);
@@ -76,8 +75,7 @@ public class ACLTest extends ZKTestCase implements Watcher {
f.startup(zks);
try {
LOG.info("starting up the zookeeper server .. waiting");
- Assert.assertTrue("waiting for server being up",
- ClientBase.waitForServerUp(HOSTPORT, CONNECTION_TIMEOUT));
+ assertTrue("waiting for server being up", ClientBase.waitForServerUp(HOSTPORT, CONNECTION_TIMEOUT));
ClientBase.createZKClient(HOSTPORT);
for (ServerCnxn cnxn : f.getConnections()) {
boolean foundID = false;
@@ -87,13 +85,12 @@ public class ACLTest extends ZKTestCase implements Watcher {
break;
}
}
- Assert.assertTrue(foundID);
+ assertTrue(foundID);
}
} finally {
f.shutdown();
zks.shutdown();
- Assert.assertTrue("waiting for server down",
- ClientBase.waitForServerDown(HOSTPORT, CONNECTION_TIMEOUT));
+ assertTrue("waiting for server down", ClientBase.waitForServerDown(HOSTPORT, CONNECTION_TIMEOUT));
System.clearProperty(ServerCnxnFactory.ZOOKEEPER_SERVER_CNXN_FACTORY);
}
}
@@ -109,8 +106,7 @@ public class ACLTest extends ZKTestCase implements Watcher {
f.startup(zks);
try {
LOG.info("starting up the zookeeper server .. waiting");
- Assert.assertTrue("waiting for server being up",
- ClientBase.waitForServerUp(HOSTPORT, CONNECTION_TIMEOUT));
+ assertTrue("waiting for server being up", ClientBase.waitForServerUp(HOSTPORT, CONNECTION_TIMEOUT));
ZooKeeper zk = ClientBase.createZKClient(HOSTPORT);
try {
zk.addAuthInfo("digest", "pat:test".getBytes());
@@ -121,9 +117,7 @@ public class ACLTest extends ZKTestCase implements Watcher {
} finally {
f.shutdown();
zks.shutdown();
- Assert.assertTrue("waiting for server down",
- ClientBase.waitForServerDown(HOSTPORT,
- ClientBase.CONNECTION_TIMEOUT));
+ assertTrue("waiting for server down", ClientBase.waitForServerDown(HOSTPORT, ClientBase.CONNECTION_TIMEOUT));
}
}
@@ -145,36 +139,33 @@ public class ACLTest extends ZKTestCase implements Watcher {
String path;
try {
LOG.info("starting up the zookeeper server .. waiting");
- Assert.assertTrue("waiting for server being up",
- ClientBase.waitForServerUp(HOSTPORT, CONNECTION_TIMEOUT));
+ assertTrue("waiting for server being up", ClientBase.waitForServerUp(HOSTPORT, CONNECTION_TIMEOUT));
zk = ClientBase.createZKClient(HOSTPORT);
LOG.info("starting creating acls");
for (int i = 0; i < 100; i++) {
path = "/" + i;
- zk.create(path, path.getBytes(), Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk.create(path, path.getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
}
int size = zks.getZKDatabase().getAclSize();
- Assert.assertTrue("size of the acl map ", (2 == zks.getZKDatabase().getAclSize()));
+ assertTrue("size of the acl map ", (2 == zks.getZKDatabase().getAclSize()));
for (int j = 100; j < 200; j++) {
path = "/" + j;
ACL acl = new ACL();
acl.setPerms(0);
Id id = new Id();
- id.setId("1.1.1."+j);
+ id.setId("1.1.1." + j);
id.setScheme("ip");
acl.setId(id);
List<ACL> list = new ArrayList<ACL>();
list.add(acl);
zk.create(path, path.getBytes(), list, CreateMode.PERSISTENT);
}
- Assert.assertTrue("size of the acl map ", (102 == zks.getZKDatabase().getAclSize()));
+ assertTrue("size of the acl map ", (102 == zks.getZKDatabase().getAclSize()));
} finally {
// now shutdown the server and restart it
f.shutdown();
zks.shutdown();
- Assert.assertTrue("waiting for server down",
- ClientBase.waitForServerDown(HOSTPORT, CONNECTION_TIMEOUT));
+ assertTrue("waiting for server down", ClientBase.waitForServerDown(HOSTPORT, CONNECTION_TIMEOUT));
}
zks = new ZooKeeperServer(tmpDir, tmpDir, 3000);
@@ -182,31 +173,28 @@ public class ACLTest extends ZKTestCase implements Watcher {
f.startup(zks);
try {
- Assert.assertTrue("waiting for server up",
- ClientBase.waitForServerUp(HOSTPORT, CONNECTION_TIMEOUT));
+ assertTrue("waiting for server up", ClientBase.waitForServerUp(HOSTPORT, CONNECTION_TIMEOUT));
zk = ClientBase.createZKClient(HOSTPORT);
- Assert.assertTrue("acl map ", (102 == zks.getZKDatabase().getAclSize()));
+ assertTrue("acl map ", (102 == zks.getZKDatabase().getAclSize()));
for (int j = 200; j < 205; j++) {
path = "/" + j;
ACL acl = new ACL();
acl.setPerms(0);
Id id = new Id();
- id.setId("1.1.1."+j);
+ id.setId("1.1.1." + j);
id.setScheme("ip");
acl.setId(id);
ArrayList<ACL> list = new ArrayList<ACL>();
list.add(acl);
zk.create(path, path.getBytes(), list, CreateMode.PERSISTENT);
}
- Assert.assertTrue("acl map ", (107 == zks.getZKDatabase().getAclSize()));
-
+ assertTrue("acl map ", (107 == zks.getZKDatabase().getAclSize()));
+
zk.close();
} finally {
f.shutdown();
zks.shutdown();
- Assert.assertTrue("waiting for server down",
- ClientBase.waitForServerDown(HOSTPORT,
- ClientBase.CONNECTION_TIMEOUT));
+ assertTrue("waiting for server down", ClientBase.waitForServerDown(HOSTPORT, ClientBase.CONNECTION_TIMEOUT));
}
}
@@ -217,8 +205,7 @@ public class ACLTest extends ZKTestCase implements Watcher {
* @see org.apache.zookeeper.Watcher#process(org.apache.zookeeper.WatcherEvent)
*/
public void process(WatchedEvent event) {
- LOG.info("Event:" + event.getState() + " " + event.getType() + " "
- + event.getPath());
+ LOG.info("Event:" + event.getState() + " " + event.getType() + " " + event.getPath());
if (event.getState() == KeeperState.SyncConnected) {
if (startSignal != null && startSignal.getCount() > 0) {
LOG.info("startsignal.countDown()");
@@ -228,7 +215,7 @@ public class ACLTest extends ZKTestCase implements Watcher {
}
}
}
-
+
@Test
public void testNullACL() throws Exception {
File tmpDir = ClientBase.createTmpDir();
@@ -242,7 +229,7 @@ public class ACLTest extends ZKTestCase implements Watcher {
// case 1 : null ACL with create
try {
zk.create("/foo", "foo".getBytes(), null, CreateMode.PERSISTENT);
- Assert.fail("Expected InvalidACLException for null ACL parameter");
+ fail("Expected InvalidACLException for null ACL parameter");
} catch (InvalidACLException e) {
// Expected. Do nothing
}
@@ -250,15 +237,15 @@ public class ACLTest extends ZKTestCase implements Watcher {
// case 2 : null ACL with other create API
try {
zk.create("/foo", "foo".getBytes(), null, CreateMode.PERSISTENT, null);
- Assert.fail("Expected InvalidACLException for null ACL parameter");
+ fail("Expected InvalidACLException for null ACL parameter");
} catch (InvalidACLException e) {
// Expected. Do nothing
}
-
+
// case 3 : null ACL with setACL
try {
zk.setACL("/foo", null, 0);
- Assert.fail("Expected InvalidACLException for null ACL parameter");
+ fail("Expected InvalidACLException for null ACL parameter");
} catch (InvalidACLException e) {
// Expected. Do nothing
}
@@ -266,8 +253,7 @@ public class ACLTest extends ZKTestCase implements Watcher {
zk.close();
f.shutdown();
zks.shutdown();
- Assert.assertTrue("waiting for server down",
- ClientBase.waitForServerDown(HOSTPORT, ClientBase.CONNECTION_TIMEOUT));
+ assertTrue("waiting for server down", ClientBase.waitForServerDown(HOSTPORT, ClientBase.CONNECTION_TIMEOUT));
}
}
@@ -288,7 +274,7 @@ public class ACLTest extends ZKTestCase implements Watcher {
// case 1 : null value in ACL list with create
try {
zk.create("/foo", "foo".getBytes(), acls, CreateMode.PERSISTENT);
- Assert.fail("Expected InvalidACLException for null value in ACL List");
+ fail("Expected InvalidACLException for null value in ACL List");
} catch (InvalidACLException e) {
// Expected. Do nothing
}
@@ -296,7 +282,7 @@ public class ACLTest extends ZKTestCase implements Watcher {
// case 2 : null value in ACL list with other create API
try {
zk.create("/foo", "foo".getBytes(), acls, CreateMode.PERSISTENT, null);
- Assert.fail("Expected InvalidACLException for null value in ACL List");
+ fail("Expected InvalidACLException for null value in ACL List");
} catch (InvalidACLException e) {
// Expected. Do nothing
}
@@ -304,7 +290,7 @@ public class ACLTest extends ZKTestCase implements Watcher {
// case 3 : null value in ACL list with setACL
try {
zk.setACL("/foo", acls, -1);
- Assert.fail("Expected InvalidACLException for null value in ACL List");
+ fail("Expected InvalidACLException for null value in ACL List");
} catch (InvalidACLException e) {
// Expected. Do nothing
}
@@ -312,8 +298,8 @@ public class ACLTest extends ZKTestCase implements Watcher {
zk.close();
f.shutdown();
zks.shutdown();
- Assert.assertTrue("waiting for server down",
- ClientBase.waitForServerDown(HOSTPORT, ClientBase.CONNECTION_TIMEOUT));
+ assertTrue("waiting for server down", ClientBase.waitForServerDown(HOSTPORT, ClientBase.CONNECTION_TIMEOUT));
}
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/AsyncHammerTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/AsyncHammerTest.java
index 1ccdc0bc0..69d006a4e 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/AsyncHammerTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/AsyncHammerTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -20,28 +20,26 @@ package org.apache.zookeeper.test;
import static org.apache.zookeeper.test.ClientBase.CONNECTION_TIMEOUT;
import static org.apache.zookeeper.test.ClientBase.verifyThreadTerminated;
-
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
import java.util.LinkedList;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
+import org.apache.zookeeper.AsyncCallback.DataCallback;
+import org.apache.zookeeper.AsyncCallback.StringCallback;
+import org.apache.zookeeper.AsyncCallback.VoidCallback;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.TestableZooKeeper;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.ZKTestCase;
-import org.apache.zookeeper.AsyncCallback.DataCallback;
-import org.apache.zookeeper.AsyncCallback.StringCallback;
-import org.apache.zookeeper.AsyncCallback.VoidCallback;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.data.Stat;
import org.apache.zookeeper.test.ClientBase.CountdownWatcher;
-import org.junit.Assert;
import org.junit.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class AsyncHammerTest extends ZKTestCase implements StringCallback, VoidCallback, DataCallback {
-public class AsyncHammerTest extends ZKTestCase
- implements StringCallback, VoidCallback, DataCallback
-{
private static final Logger LOG = LoggerFactory.getLogger(AsyncHammerTest.class);
private QuorumBase qb = new QuorumBase();
@@ -70,6 +68,7 @@ public class AsyncHammerTest extends ZKTestCase
* Create /test- sequence nodes asynchronously, max 30 outstanding
*/
class HammerThread extends Thread implements StringCallback, VoidCallback {
+
private static final int MAX_OUTSTANDING = 30;
private TestableZooKeeper zk;
@@ -84,21 +83,19 @@ public class AsyncHammerTest extends ZKTestCase
public void run() {
try {
CountdownWatcher watcher = new CountdownWatcher();
- zk = new TestableZooKeeper(qb.hostPort, CONNECTION_TIMEOUT,
- watcher);
+ zk = new TestableZooKeeper(qb.hostPort, CONNECTION_TIMEOUT, watcher);
watcher.waitForConnected(CONNECTION_TIMEOUT);
- while(bang) {
+ while (bang) {
incOutstanding(); // before create otw race
- zk.create("/test-", new byte[0], Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT_SEQUENTIAL, this, null);
+ zk.create("/test-", new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL, this, null);
}
} catch (InterruptedException e) {
if (bang) {
- LOG.error("sanity check Assert.failed!!!"); // sanity check
+ LOG.error("sanity check failed!!!"); // sanity check
return;
}
} catch (Exception e) {
- LOG.error("Client create operation Assert.failed", e);
+ LOG.error("Client create operation failed", e);
return;
} finally {
if (zk != null) {
@@ -116,14 +113,14 @@ public class AsyncHammerTest extends ZKTestCase
private synchronized void incOutstanding() throws InterruptedException {
outstanding++;
- while(outstanding > MAX_OUTSTANDING) {
+ while (outstanding > MAX_OUTSTANDING) {
wait();
}
}
private synchronized void decOutstanding() {
outstanding--;
- Assert.assertTrue("outstanding >= 0", outstanding >= 0);
+ assertTrue("outstanding >= 0", outstanding >= 0);
notifyAll();
}
@@ -135,9 +132,12 @@ public class AsyncHammerTest extends ZKTestCase
if (rc != KeeperException.Code.OK.intValue()) {
if (bang) {
failed = true;
- LOG.error("Create Assert.failed for 0x"
- + Long.toHexString(zk.getSessionId())
- + "with rc:" + rc + " path:" + path);
+ LOG.error("Create failed for 0x"
+ + Long.toHexString(zk.getSessionId())
+ + "with rc:"
+ + rc
+ + " path:"
+ + path);
}
decOutstanding();
return;
@@ -148,7 +148,7 @@ public class AsyncHammerTest extends ZKTestCase
} catch (Exception e) {
if (bang) {
failed = true;
- LOG.error("Client delete Assert.failed", e);
+ LOG.error("Client delete failed", e);
}
}
}
@@ -157,12 +157,16 @@ public class AsyncHammerTest extends ZKTestCase
if (rc != KeeperException.Code.OK.intValue()) {
if (bang) {
failed = true;
- LOG.error("Delete Assert.failed for 0x"
- + Long.toHexString(zk.getSessionId())
- + "with rc:" + rc + " path:" + path);
+ LOG.error("Delete failed for 0x"
+ + Long.toHexString(zk.getSessionId())
+ + "with rc:"
+ + rc
+ + " path:"
+ + path);
}
}
}
+
}
@Test
@@ -182,7 +186,7 @@ public class AsyncHammerTest extends ZKTestCase
for (int i = 0; i < hammers.length; i++) {
hammers[i].interrupt();
verifyThreadTerminated(hammers[i], 60000);
- Assert.assertFalse(hammers[i].failed);
+ assertFalse(hammers[i].failed);
}
// before restart
@@ -219,26 +223,26 @@ public class AsyncHammerTest extends ZKTestCase
@SuppressWarnings("unchecked")
public void processResult(int rc, String path, Object ctx, String name) {
- synchronized(ctx) {
- ((LinkedList<Integer>)ctx).add(rc);
+ synchronized (ctx) {
+ ((LinkedList<Integer>) ctx).add(rc);
ctx.notifyAll();
}
}
@SuppressWarnings("unchecked")
public void processResult(int rc, String path, Object ctx) {
- synchronized(ctx) {
- ((LinkedList<Integer>)ctx).add(rc);
+ synchronized (ctx) {
+ ((LinkedList<Integer>) ctx).add(rc);
ctx.notifyAll();
}
}
@SuppressWarnings("unchecked")
- public void processResult(int rc, String path, Object ctx, byte[] data,
- Stat stat) {
- synchronized(ctx) {
- ((LinkedList<Integer>)ctx).add(rc);
+ public void processResult(int rc, String path, Object ctx, byte[] data, Stat stat) {
+ synchronized (ctx) {
+ ((LinkedList<Integer>) ctx).add(rc);
ctx.notifyAll();
}
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/AsyncOps.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/AsyncOps.java
index f44e684db..d5f2310c3 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/AsyncOps.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/AsyncOps.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,39 +18,43 @@
package org.apache.zookeeper.test;
-import java.lang.Exception;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertSame;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
-
-import org.apache.zookeeper.CreateMode;
-import org.apache.zookeeper.KeeperException;
-import org.apache.zookeeper.Op;
-import org.apache.zookeeper.OpResult;
-import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.AsyncCallback.ACLCallback;
import org.apache.zookeeper.AsyncCallback.Children2Callback;
import org.apache.zookeeper.AsyncCallback.ChildrenCallback;
import org.apache.zookeeper.AsyncCallback.Create2Callback;
import org.apache.zookeeper.AsyncCallback.DataCallback;
+import org.apache.zookeeper.AsyncCallback.MultiCallback;
import org.apache.zookeeper.AsyncCallback.StatCallback;
import org.apache.zookeeper.AsyncCallback.StringCallback;
import org.apache.zookeeper.AsyncCallback.VoidCallback;
-import org.apache.zookeeper.AsyncCallback.MultiCallback;
+import org.apache.zookeeper.CreateMode;
+import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.KeeperException.Code;
+import org.apache.zookeeper.Op;
+import org.apache.zookeeper.OpResult;
import org.apache.zookeeper.ZooDefs.Ids;
+import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.ACL;
import org.apache.zookeeper.data.Stat;
-import org.junit.Assert;
public class AsyncOps {
+
/**
* This is the base class for all of the async callback classes. It will
* verify the expected value against the actual value.
- *
+ *
* Basic operation is that the subclasses will generate an "expected" value
* which is defined by the "toString" method of the subclass. This is
* passed through to the verify clause by specifying it as the ctx object
@@ -59,93 +63,94 @@ public class AsyncOps {
* instance fields with matching parameter arguments to the processResult
* method. The cb instance can then compare the expected to the
* actual value by again calling toString and comparing the two.
- *
+ *
* The format of each expected value differs (is defined) by subclass.
* Generally the expected value starts with the result code (rc) and path
* of the node being operated on, followed by the fields specific to
* each operation type (cb subclass). For example ChildrenCB specifies
* a list of the expected children suffixed onto the rc and path. See
- * the toString() method of each subclass for details of it's format.
+ * the toString() method of each subclass for details of it's format.
*/
- public static abstract class AsyncCB {
+ public abstract static class AsyncCB {
+
protected final ZooKeeper zk;
protected long defaultTimeoutMillis = 30000;
-
+
/** the latch is used to await the results from the server */
CountDownLatch latch;
Code rc = Code.OK;
String path = "/foo";
String expected;
-
+
public AsyncCB(ZooKeeper zk, CountDownLatch latch) {
this.zk = zk;
this.latch = latch;
}
-
+
public void setRC(Code rc) {
this.rc = rc;
}
-
+
public void setPath(String path) {
this.path = path;
}
-
- public void processResult(Code rc, String path, Object ctx)
- {
+
+ public void processResult(Code rc, String path, Object ctx) {
this.rc = rc;
this.path = path;
- this.expected = (String)ctx;
+ this.expected = (String) ctx;
latch.countDown();
}
-
+
/** String format is rc:path:&lt;suffix&gt; where &lt;suffix&gt; is defined by each
* subclass individually. */
@Override
public String toString() {
- return rc + ":" + path + ":";
+ return rc + ":" + path + ":";
}
protected void verify() {
try {
latch.await(defaultTimeoutMillis, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
- Assert.fail("unexpected interrupt");
+ fail("unexpected interrupt");
}
// on the lookout for timeout
- Assert.assertSame(0L, latch.getCount());
-
+ assertSame(0L, latch.getCount());
+
String actual = toString();
-
- Assert.assertEquals(expected, actual);
+
+ assertEquals(expected, actual);
}
+
}
-
+
public static class StringCB extends AsyncCB implements StringCallback {
+
byte[] data = new byte[10];
List<ACL> acl = Ids.CREATOR_ALL_ACL;
CreateMode flags = CreateMode.PERSISTENT;
String name = path;
-
+
StringCB(ZooKeeper zk) {
this(zk, new CountDownLatch(1));
}
-
+
StringCB(ZooKeeper zk, CountDownLatch latch) {
super(zk, latch);
}
-
+
public void setPath(String path) {
super.setPath(path);
this.name = path;
}
-
+
public String nodeName() {
return path.substring(path.lastIndexOf('/') + 1);
}
-
- public void processResult(int rc, String path, Object ctx, String name)
- {
+
+ public void processResult(int rc, String path, Object ctx, String name) {
this.name = name;
super.processResult(Code.get(rc), path, ctx);
}
@@ -159,7 +164,7 @@ public class AsyncOps {
zk.create(path, data, acl, CreateMode.EPHEMERAL, this, toString());
return this;
}
-
+
public void verifyCreate() {
create();
verify();
@@ -169,10 +174,10 @@ public class AsyncOps {
createEphemeral();
verify();
}
-
+
public void verifyCreateFailure_NodeExists() {
new StringCB(zk).verifyCreate();
-
+
rc = Code.NODEEXISTS;
name = null;
zk.create(path, data, acl, flags, this, toString());
@@ -202,16 +207,18 @@ public class AsyncOps {
@Override
public String toString() {
- return super.toString() + name;
+ return super.toString() + name;
}
+
}
public static class ACLCB extends AsyncCB implements ACLCallback {
+
List<ACL> acl = Ids.CREATOR_ALL_ACL;
int version = 0;
Stat stat = new Stat();
byte[] data = "testing".getBytes();
-
+
ACLCB(ZooKeeper zk) {
this(zk, new CountDownLatch(1));
}
@@ -224,14 +231,12 @@ public class AsyncOps {
stat.setVersion(0);
}
- public void processResult(int rc, String path, Object ctx,
- List<ACL> acl, Stat stat)
- {
+ public void processResult(int rc, String path, Object ctx, List<ACL> acl, Stat stat) {
this.acl = acl;
this.stat = stat;
super.processResult(Code.get(rc), path, ctx);
}
-
+
public void verifyGetACL() {
new StringCB(zk).verifyCreate();
@@ -239,7 +244,7 @@ public class AsyncOps {
verify();
}
- public void verifyGetACLFailure_NoNode(){
+ public void verifyGetACLFailure_NoNode() {
rc = Code.NONODE;
stat = null;
acl = null;
@@ -247,32 +252,37 @@ public class AsyncOps {
verify();
}
-
+
public String toString(List<ACL> acls) {
if (acls == null) {
return "";
}
StringBuilder result = new StringBuilder();
- for(ACL acl : acls) {
+ for (ACL acl : acls) {
result.append(acl.getPerms()).append("::");
}
return result.toString();
}
-
+
@Override
public String toString() {
- return super.toString() + toString(acl) + ":"
- + ":" + version + ":" + new String(data)
- + ":" + (stat == null ? "null" : stat.getAversion() + ":"
- + stat.getCversion() + ":" + stat.getEphemeralOwner()
- + ":" + stat.getVersion());
+ return super.toString()
+ + toString(acl) + ":"
+ + ":" + version
+ + ":" + new String(data)
+ + ":" + (stat == null ? "null" : stat.getAversion()
+ + ":" + stat.getCversion()
+ + ":" + stat.getEphemeralOwner()
+ + ":" + stat.getVersion());
}
+
}
public static class ChildrenCB extends AsyncCB implements ChildrenCallback {
+
List<String> children = new ArrayList<String>();
-
+
ChildrenCB(ZooKeeper zk) {
this(zk, new CountDownLatch(1));
}
@@ -280,23 +290,20 @@ public class AsyncOps {
ChildrenCB(ZooKeeper zk, CountDownLatch latch) {
super(zk, latch);
}
-
- public void processResult(int rc, String path, Object ctx,
- List<String> children)
- {
- this.children =
- (children == null ? new ArrayList<String>() : children);
+
+ public void processResult(int rc, String path, Object ctx, List<String> children) {
+ this.children = (children == null ? new ArrayList<String>() : children);
Collections.sort(this.children);
super.processResult(Code.get(rc), path, ctx);
}
-
+
public StringCB createNode() {
StringCB parent = new StringCB(zk);
parent.verifyCreate();
return parent;
}
-
+
public StringCB createNode(StringCB parent) {
String childName = "bar";
@@ -307,10 +314,10 @@ public class AsyncOps {
StringCB child = new StringCB(zk);
child.setPath(parent.path + "/" + childName);
child.verifyCreate();
-
+
return child;
}
-
+
public void verifyGetChildrenEmpty() {
StringCB parent = createNode();
path = parent.path;
@@ -323,27 +330,27 @@ public class AsyncOps {
path = parent.path;
children.add(child.nodeName());
-
+
verify();
}
-
+
public void verifyGetChildrenTwo() {
StringCB parent = createNode();
StringCB child1 = createNode(parent, "child1");
StringCB child2 = createNode(parent, "child2");
-
+
path = parent.path;
children.add(child1.nodeName());
children.add(child2.nodeName());
-
+
verify();
}
-
+
public void verifyGetChildrenFailure_NoNode() {
rc = KeeperException.Code.NONODE;
verify();
}
-
+
@Override
public void verify() {
zk.getChildren(path, false, this, toString());
@@ -354,9 +361,11 @@ public class AsyncOps {
public String toString() {
return super.toString() + children.toString();
}
+
}
public static class Children2CB extends AsyncCB implements Children2Callback {
+
List<String> children = new ArrayList<String>();
Children2CB(ZooKeeper zk) {
@@ -367,22 +376,19 @@ public class AsyncOps {
super(zk, latch);
}
- public void processResult(int rc, String path, Object ctx,
- List<String> children, Stat stat)
- {
- this.children =
- (children == null ? new ArrayList<String>() : children);
+ public void processResult(int rc, String path, Object ctx, List<String> children, Stat stat) {
+ this.children = (children == null ? new ArrayList<String>() : children);
Collections.sort(this.children);
super.processResult(Code.get(rc), path, ctx);
}
-
+
public StringCB createNode() {
StringCB parent = new StringCB(zk);
parent.verifyCreate();
return parent;
}
-
+
public StringCB createNode(StringCB parent) {
String childName = "bar";
@@ -393,10 +399,10 @@ public class AsyncOps {
StringCB child = new StringCB(zk);
child.setPath(parent.path + "/" + childName);
child.verifyCreate();
-
+
return child;
}
-
+
public void verifyGetChildrenEmpty() {
StringCB parent = createNode();
path = parent.path;
@@ -409,41 +415,43 @@ public class AsyncOps {
path = parent.path;
children.add(child.nodeName());
-
+
verify();
}
-
+
public void verifyGetChildrenTwo() {
StringCB parent = createNode();
StringCB child1 = createNode(parent, "child1");
StringCB child2 = createNode(parent, "child2");
-
+
path = parent.path;
children.add(child1.nodeName());
children.add(child2.nodeName());
-
+
verify();
}
-
+
public void verifyGetChildrenFailure_NoNode() {
rc = KeeperException.Code.NONODE;
verify();
}
-
+
@Override
public void verify() {
zk.getChildren(path, false, this, toString());
super.verify();
}
-
+
@Override
public String toString() {
- return super.toString() + children.toString();
+ return super.toString() + children.toString();
}
+
}
public static class Create2CB extends AsyncCB implements Create2Callback {
- byte[] data = new byte[10];
+
+ byte[] data = new byte[10];
List<ACL> acl = Ids.CREATOR_ALL_ACL;
CreateMode flags = CreateMode.PERSISTENT;
String name = path;
@@ -466,8 +474,7 @@ public class AsyncOps {
return path.substring(path.lastIndexOf('/') + 1);
}
- public void processResult(int rc, String path, Object ctx,
- String name, Stat stat) {
+ public void processResult(int rc, String path, Object ctx, String name, Stat stat) {
this.name = name;
this.stat = stat;
super.processResult(Code.get(rc), path, ctx);
@@ -516,17 +523,23 @@ public class AsyncOps {
@Override
public String toString() {
- return super.toString() + name + ":" +
- (stat == null ? "null" : stat.getAversion() + ":" +
- stat.getCversion() + ":" + stat.getEphemeralOwner() +
- ":" + stat.getVersion());
+ return super.toString()
+ + name + ":"
+ + (stat == null
+ ? "null"
+ : stat.getAversion()
+ + ":" + stat.getCversion()
+ + ":" + stat.getEphemeralOwner()
+ + ":" + stat.getVersion());
}
+
}
public static class DataCB extends AsyncCB implements DataCallback {
+
byte[] data = new byte[10];
Stat stat = new Stat();
-
+
DataCB(ZooKeeper zk) {
this(zk, new CountDownLatch(1));
}
@@ -538,22 +551,20 @@ public class AsyncOps {
stat.setEphemeralOwner(0);
stat.setVersion(0);
}
-
- 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) {
this.data = data;
this.stat = stat;
super.processResult(Code.get(rc), path, ctx);
}
-
+
public void verifyGetData() {
new StringCB(zk).verifyCreate();
zk.getData(path, false, this, toString());
verify();
}
-
+
public void verifyGetDataFailure_NoNode() {
rc = KeeperException.Code.NONODE;
data = null;
@@ -561,23 +572,26 @@ public class AsyncOps {
zk.getData(path, false, this, toString());
verify();
}
-
+
@Override
public String toString() {
return super.toString()
- + ":" + (data == null ? "null" : new String(data))
- + ":" + (stat == null ? "null" : stat.getAversion() + ":"
- + stat.getCversion() + ":" + stat.getEphemeralOwner()
- + ":" + stat.getVersion());
+ + ":" + (data == null ? "null" : new String(data))
+ + ":" + (stat == null ? "null" : stat.getAversion()
+ + ":" + stat.getCversion()
+ + ":" + stat.getEphemeralOwner()
+ + ":" + stat.getVersion());
}
+
}
public static class StatCB extends AsyncCB implements StatCallback {
+
List<ACL> acl = Ids.CREATOR_ALL_ACL;
int version = 0;
Stat stat = new Stat();
byte[] data = "testing".getBytes();
-
+
StatCB(ZooKeeper zk) {
this(zk, new CountDownLatch(1));
}
@@ -589,12 +603,12 @@ public class AsyncOps {
stat.setEphemeralOwner(0);
stat.setVersion(0);
}
-
+
public void processResult(int rc, String path, Object ctx, Stat stat) {
this.stat = stat;
super.processResult(Code.get(rc), path, ctx);
}
-
+
public void verifySetACL() {
stat.setAversion(1);
new StringCB(zk).verifyCreate();
@@ -602,7 +616,7 @@ public class AsyncOps {
zk.setACL(path, acl, version, this, toString());
verify();
}
-
+
public void verifySetACLFailure_NoNode() {
rc = KeeperException.Code.NONODE;
stat = null;
@@ -619,11 +633,11 @@ public class AsyncOps {
verify();
}
-
+
public void setData() {
zk.setData(path, data, version, this, toString());
}
-
+
public void verifySetData() {
stat.setVersion(1);
new StringCB(zk).verifyCreate();
@@ -631,7 +645,7 @@ public class AsyncOps {
setData();
verify();
}
-
+
public void verifySetDataFailure_NoNode() {
rc = KeeperException.Code.NONODE;
stat = null;
@@ -648,42 +662,45 @@ public class AsyncOps {
verify();
}
-
+
public void verifyExists() {
new StringCB(zk).verifyCreate();
zk.exists(path, false, this, toString());
verify();
}
-
+
public void verifyExistsFailure_NoNode() {
rc = KeeperException.Code.NONODE;
stat = null;
zk.exists(path, false, this, toString());
verify();
}
-
+
@Override
public String toString() {
return super.toString() + version
- + ":" + new String(data)
- + ":" + (stat == null ? "null" : stat.getAversion() + ":"
- + stat.getCversion() + ":" + stat.getEphemeralOwner()
- + ":" + stat.getVersion());
+ + ":" + new String(data)
+ + ":" + (stat == null ? "null" : stat.getAversion()
+ + ":" + stat.getCversion()
+ + ":" + stat.getEphemeralOwner()
+ + ":" + stat.getVersion());
}
+
}
public static class VoidCB extends AsyncCB implements VoidCallback {
+
int version = 0;
-
+
VoidCB(ZooKeeper zk) {
this(zk, new CountDownLatch(1));
}
-
+
VoidCB(ZooKeeper zk, CountDownLatch latch) {
super(zk, latch);
}
-
+
public void processResult(int rc, String path, Object ctx) {
super.processResult(Code.get(rc), path, ctx);
}
@@ -691,14 +708,14 @@ public class AsyncOps {
public void delete() {
zk.delete(path, version, this, toString());
}
-
+
public void verifyDelete() {
new StringCB(zk).verifyCreate();
delete();
verify();
}
-
+
public void verifyDeleteFailure_NoNode() {
rc = Code.NONODE;
zk.delete(path, version, this, toString());
@@ -722,23 +739,25 @@ public class AsyncOps {
zk.delete(path, version, this, toString());
verify();
}
-
+
public void sync() {
zk.sync(path, this, toString());
}
-
+
public void verifySync() {
sync();
verify();
}
-
+
@Override
public String toString() {
- return super.toString() + version;
+ return super.toString() + version;
}
+
}
public static class MultiCB implements MultiCallback {
+
ZooKeeper zk;
int rc;
List<OpResult> opResults;
@@ -748,80 +767,76 @@ public class AsyncOps {
this.zk = zk;
}
- public void processResult(int rc, String path, Object ctx,
- List<OpResult> opResults) {
+ public void processResult(int rc, String path, Object ctx, List<OpResult> opResults) {
this.rc = rc;
this.opResults = opResults;
latch.countDown();
}
- void latch_await(){
+ void latch_await() {
try {
latch.await(10000, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
- Assert.fail("unexpected interrupt");
+ fail("unexpected interrupt");
}
- Assert.assertSame(0L, latch.getCount());
+ assertSame(0L, latch.getCount());
}
public void verifyMulti() {
List<Op> ops = Arrays.asList(
- Op.create("/multi", new byte[0],
- Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT),
- Op.delete("/multi", -1));
+ Op.create("/multi", new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT),
+ Op.delete("/multi", -1));
zk.multi(ops, this, null);
latch_await();
- Assert.assertEquals(this.rc, KeeperException.Code.OK.intValue());
- Assert.assertTrue(this.opResults.get(0) instanceof OpResult.CreateResult);
- Assert.assertTrue(this.opResults.get(1) instanceof OpResult.DeleteResult);
+ assertEquals(this.rc, KeeperException.Code.OK.intValue());
+ assertTrue(this.opResults.get(0) instanceof OpResult.CreateResult);
+ assertTrue(this.opResults.get(1) instanceof OpResult.DeleteResult);
}
public void verifyMultiFailure_AllErrorResult() {
List<Op> ops = Arrays.asList(
- Op.create("/multi", new byte[0],
- Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT),
- Op.delete("/nonexist1", -1),
- Op.setData("/multi", "test".getBytes(), -1));
+ Op.create("/multi", new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT),
+ Op.delete("/nonexist1", -1), Op.setData("/multi", "test".getBytes(), -1));
zk.multi(ops, this, null);
latch_await();
- Assert.assertTrue(this.opResults.get(0) instanceof OpResult.ErrorResult);
- Assert.assertTrue(this.opResults.get(1) instanceof OpResult.ErrorResult);
- Assert.assertTrue(this.opResults.get(2) instanceof OpResult.ErrorResult);
+ assertTrue(this.opResults.get(0) instanceof OpResult.ErrorResult);
+ assertTrue(this.opResults.get(1) instanceof OpResult.ErrorResult);
+ assertTrue(this.opResults.get(2) instanceof OpResult.ErrorResult);
}
public void verifyMultiFailure_NoSideEffect() throws KeeperException, InterruptedException {
List<Op> ops = Arrays.asList(
- Op.create("/multi", new byte[0],
- Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT),
- Op.delete("/nonexist1", -1));
+ Op.create("/multi", new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT),
+ Op.delete("/nonexist1", -1));
zk.multi(ops, this, null);
latch_await();
- Assert.assertTrue(this.opResults.get(0) instanceof OpResult.ErrorResult);
- Assert.assertNull(zk.exists("/multi", false));
+ assertTrue(this.opResults.get(0) instanceof OpResult.ErrorResult);
+ assertNull(zk.exists("/multi", false));
}
- public void verifyMultiSequential_NoSideEffect() throws Exception{
+ public void verifyMultiSequential_NoSideEffect() throws Exception {
StringCB scb = new StringCB(zk);
scb.verifyCreate();
String path = scb.path + "-";
String seqPath = path + "0000000002";
zk.create(path, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL);
- Assert.assertNotNull(zk.exists(path + "0000000001", false));
+ assertNotNull(zk.exists(path + "0000000001", false));
List<Op> ops = Arrays.asList(
- Op.create(path , new byte[0],
- Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL),
- Op.delete("/nonexist", -1));
+ Op.create(path, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL),
+ Op.delete("/nonexist", -1));
zk.multi(ops, this, null);
latch_await();
- Assert.assertNull(zk.exists(seqPath, false));
+ assertNull(zk.exists(seqPath, false));
zk.create(path, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL);
- Assert.assertNotNull(zk.exists(seqPath, false));
+ assertNotNull(zk.exists(seqPath, false));
}
+
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/AsyncOpsTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/AsyncOpsTest.java
index 037ea2f19..e94fa9283 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/AsyncOpsTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/AsyncOpsTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,26 +18,25 @@
package org.apache.zookeeper.test;
-import java.lang.Exception;
import java.util.concurrent.CountDownLatch;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.test.AsyncOps.ACLCB;
import org.apache.zookeeper.test.AsyncOps.Children2CB;
import org.apache.zookeeper.test.AsyncOps.ChildrenCB;
import org.apache.zookeeper.test.AsyncOps.Create2CB;
import org.apache.zookeeper.test.AsyncOps.DataCB;
+import org.apache.zookeeper.test.AsyncOps.MultiCB;
import org.apache.zookeeper.test.AsyncOps.StatCB;
import org.apache.zookeeper.test.AsyncOps.StringCB;
import org.apache.zookeeper.test.AsyncOps.VoidCB;
-import org.apache.zookeeper.test.AsyncOps.MultiCB;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
public class AsyncOpsTest extends ClientBase {
+
private static final Logger LOG = LoggerFactory.getLogger(AsyncOpsTest.class);
private ZooKeeper zk;
@@ -118,7 +117,6 @@ public class AsyncOpsTest extends ClientBase {
new Create2CB(zk).verifyCreateFailure_NoNode();
}
-
@Test
public void testAsyncCreate2Failure_NoChildForEphemeral() {
new Create2CB(zk).verifyCreateFailure_NoChildForEphemeral();
@@ -260,12 +258,13 @@ public class AsyncOpsTest extends ClientBase {
}
@Test
- public void testAsyncMultiFailure_NoSideEffect() throws Exception{
+ public void testAsyncMultiFailure_NoSideEffect() throws Exception {
new MultiCB(zk).verifyMultiFailure_NoSideEffect();
}
@Test
- public void testAsyncMultiSequential_NoSideEffect() throws Exception{
+ public void testAsyncMultiSequential_NoSideEffect() throws Exception {
new MultiCB(zk).verifyMultiSequential_NoSideEffect();
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/AsyncTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/AsyncTest.java
index b8581004b..26db2702d 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/AsyncTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/AsyncTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,10 +18,10 @@
package org.apache.zookeeper.test;
-
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.fail;
import java.util.LinkedList;
import java.util.List;
-
import org.apache.zookeeper.AsyncCallback.DataCallback;
import org.apache.zookeeper.AsyncCallback.StringCallback;
import org.apache.zookeeper.AsyncCallback.VoidCallback;
@@ -33,15 +33,13 @@ import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;
import org.junit.After;
-import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-public class AsyncTest extends ZKTestCase
- implements StringCallback, VoidCallback, DataCallback
-{
+public class AsyncTest extends ZKTestCase implements StringCallback, VoidCallback, DataCallback {
+
private static final Logger LOG = LoggerFactory.getLogger(AsyncTest.class);
private QuorumBase qb = new QuorumBase();
@@ -57,13 +55,11 @@ public class AsyncTest extends ZKTestCase
qb.tearDown();
}
- private ZooKeeper createClient() throws Exception,InterruptedException {
+ private ZooKeeper createClient() throws Exception {
return createClient(qb.hostPort);
}
- private ZooKeeper createClient(String hp)
- throws Exception, InterruptedException
- {
+ private ZooKeeper createClient(String hp) throws Exception {
ZooKeeper zk = ClientBase.createZKClient(hp);
return zk;
}
@@ -71,8 +67,7 @@ public class AsyncTest extends ZKTestCase
List<Integer> results = new LinkedList<Integer>();
@Test
- public void testAsync() throws Exception
- {
+ public void testAsync() throws Exception {
ZooKeeper zk = null;
zk = createClient();
try {
@@ -87,11 +82,11 @@ public class AsyncTest extends ZKTestCase
results.wait();
}
}
- Assert.assertEquals(0, (int) results.get(0));
- Assert.assertEquals(Code.NOAUTH, Code.get(results.get(1)));
- Assert.assertEquals(0, (int) results.get(2));
- Assert.assertEquals(0, (int) results.get(3));
- Assert.assertEquals(0, (int) results.get(4));
+ assertEquals(0, (int) results.get(0));
+ assertEquals(Code.NOAUTH, Code.get(results.get(1)));
+ assertEquals(0, (int) results.get(2));
+ assertEquals(0, (int) results.get(3));
+ assertEquals(0, (int) results.get(4));
} finally {
zk.close();
}
@@ -101,9 +96,9 @@ public class AsyncTest extends ZKTestCase
zk.addAuthInfo("digest", "ben:passwd2".getBytes());
try {
zk.getData("/ben2", false, new Stat());
- Assert.fail("Should have received a permission error");
+ fail("Should have received a permission error");
} catch (KeeperException e) {
- Assert.assertEquals(Code.NOAUTH, e.code());
+ assertEquals(Code.NOAUTH, e.code());
}
} finally {
zk.close();
@@ -120,26 +115,27 @@ public class AsyncTest extends ZKTestCase
@SuppressWarnings("unchecked")
public void processResult(int rc, String path, Object ctx, String name) {
- synchronized(ctx) {
- ((LinkedList<Integer>)ctx).add(rc);
+ synchronized (ctx) {
+ ((LinkedList<Integer>) ctx).add(rc);
ctx.notifyAll();
}
}
@SuppressWarnings("unchecked")
public void processResult(int rc, String path, Object ctx) {
- synchronized(ctx) {
- ((LinkedList<Integer>)ctx).add(rc);
+ synchronized (ctx) {
+ ((LinkedList<Integer>) ctx).add(rc);
ctx.notifyAll();
}
}
@SuppressWarnings("unchecked")
- public void processResult(int rc, String path, Object ctx, byte[] data,
- Stat stat) {
- synchronized(ctx) {
- ((LinkedList<Integer>)ctx).add(rc);
+ public void processResult(
+ int rc, String path, Object ctx, byte[] data, Stat stat) {
+ synchronized (ctx) {
+ ((LinkedList<Integer>) ctx).add(rc);
ctx.notifyAll();
}
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/AtomicFileOutputStreamTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/AtomicFileOutputStreamTest.java
index cbd2b7700..a91bf3559 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/AtomicFileOutputStreamTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/AtomicFileOutputStreamTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -15,19 +15,18 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
package org.apache.zookeeper.test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
-
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
-
import org.apache.zookeeper.ZKTestCase;
import org.apache.zookeeper.common.AtomicFileOutputStream;
import org.junit.After;
@@ -35,6 +34,7 @@ import org.junit.Before;
import org.junit.Test;
public class AtomicFileOutputStreamTest extends ZKTestCase {
+
private static final String TEST_STRING = "hello world";
private static final String TEST_STRING_2 = "goodbye world";
@@ -114,8 +114,7 @@ public class AtomicFileOutputStreamTest extends ZKTestCase {
// Should not have touched original file
assertEquals(TEST_STRING_2, ClientBase.readFile(dstFile));
- assertEquals("Temporary file should have been cleaned up",
- dstFile.getName(), ClientBase.join(",", testDir.list()));
+ assertEquals("Temporary file should have been cleaned up", dstFile.getName(), ClientBase.join(",", testDir.list()));
}
/**
@@ -197,4 +196,5 @@ public class AtomicFileOutputStreamTest extends ZKTestCase {
assertEquals(TEST_STRING, ClientBase.readFile(dstFile));
assertEquals(1, testDir.list().length);
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/AuthTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/AuthTest.java
index 60e3453bb..c78f6202b 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/AuthTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/AuthTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,10 +18,10 @@
package org.apache.zookeeper.test;
+import static org.junit.Assert.fail;
import java.io.IOException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
-
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.TestableZooKeeper;
@@ -29,37 +29,35 @@ import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher.Event.KeeperState;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;
-import org.junit.Assert;
import org.junit.Test;
public class AuthTest extends ClientBase {
+
static {
// password is test
- System.setProperty("zookeeper.DigestAuthenticationProvider.superDigest",
- "super:D/InIHSb7yEEbrWz8b9l71RjZJU=");
+ System.setProperty("zookeeper.DigestAuthenticationProvider.superDigest", "super:D/InIHSb7yEEbrWz8b9l71RjZJU=");
System.setProperty("zookeeper.authProvider.1", "org.apache.zookeeper.test.InvalidAuthProvider");
}
private final CountDownLatch authFailed = new CountDownLatch(1);
@Override
- protected TestableZooKeeper createClient(String hp)
- throws IOException, InterruptedException
- {
+ protected TestableZooKeeper createClient(String hp) throws IOException, InterruptedException {
MyWatcher watcher = new MyWatcher();
return createClient(watcher, hp);
}
private class MyWatcher extends CountdownWatcher {
+
@Override
public synchronized void process(WatchedEvent event) {
if (event.getState() == KeeperState.AuthFailed) {
authFailed.countDown();
- }
- else {
+ } else {
super.process(event);
}
}
+
}
@Test
@@ -68,73 +66,65 @@ public class AuthTest extends ClientBase {
try {
zk.addAuthInfo("FOO", "BAR".getBytes());
zk.getData("/path1", false, null);
- Assert.fail("Should get auth state error");
- } catch(KeeperException.AuthFailedException e) {
- if(!authFailed.await(CONNECTION_TIMEOUT,
- TimeUnit.MILLISECONDS))
- {
- Assert.fail("Should have called my watcher");
+ fail("Should get auth state error");
+ } catch (KeeperException.AuthFailedException e) {
+ if (!authFailed.await(CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS)) {
+ fail("Should have called my watcher");
}
- }
- finally {
+ } finally {
zk.close();
}
}
-
+
@Test
public void testBadAuthThenSendOtherCommands() throws Exception {
- ZooKeeper zk = createClient();
- try {
+ ZooKeeper zk = createClient();
+ try {
zk.addAuthInfo("INVALID", "BAR".getBytes());
- zk.exists("/foobar", false);
+ zk.exists("/foobar", false);
zk.getData("/path1", false, null);
- Assert.fail("Should get auth state error");
- } catch(KeeperException.AuthFailedException e) {
- if(!authFailed.await(CONNECTION_TIMEOUT,
- TimeUnit.MILLISECONDS))
- {
- Assert.fail("Should have called my watcher");
+ fail("Should get auth state error");
+ } catch (KeeperException.AuthFailedException e) {
+ if (!authFailed.await(CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS)) {
+ fail("Should have called my watcher");
}
- }
- finally {
- zk.close();
+ } finally {
+ zk.close();
}
}
-
@Test
public void testSuper() throws Exception {
ZooKeeper zk = createClient();
try {
zk.addAuthInfo("digest", "pat:pass".getBytes());
- zk.create("/path1", null, Ids.CREATOR_ALL_ACL,
- CreateMode.PERSISTENT);
+ zk.create("/path1", null, Ids.CREATOR_ALL_ACL, CreateMode.PERSISTENT);
zk.close();
// verify no auth
zk = createClient();
try {
zk.getData("/path1", false, null);
- Assert.fail("auth verification");
+ fail("auth verification");
} catch (KeeperException.NoAuthException e) {
// expected
}
zk.close();
- // verify bad pass Assert.fails
+ // verify bad pass fails
zk = createClient();
zk.addAuthInfo("digest", "pat:pass2".getBytes());
try {
zk.getData("/path1", false, null);
- Assert.fail("auth verification");
+ fail("auth verification");
} catch (KeeperException.NoAuthException e) {
// expected
}
zk.close();
- // verify super with bad pass Assert.fails
+ // verify super with bad pass fails
zk = createClient();
zk.addAuthInfo("digest", "super:test2".getBytes());
try {
zk.getData("/path1", false, null);
- Assert.fail("auth verification");
+ fail("auth verification");
} catch (KeeperException.NoAuthException e) {
// expected
}
@@ -147,28 +137,27 @@ public class AuthTest extends ClientBase {
zk.close();
}
}
-
+
@Test
public void testSuperACL() throws Exception {
- ZooKeeper zk = createClient();
- try {
- zk.addAuthInfo("digest", "pat:pass".getBytes());
- zk.create("/path1", null, Ids.CREATOR_ALL_ACL,
- CreateMode.PERSISTENT);
- zk.close();
- // verify super can do anything and ignores ACLs
- zk = createClient();
- zk.addAuthInfo("digest", "super:test".getBytes());
- zk.getData("/path1", false, null);
-
- zk.setACL("/path1", Ids.READ_ACL_UNSAFE, -1);
- zk.create("/path1/foo", null, Ids.CREATOR_ALL_ACL, CreateMode.PERSISTENT);
-
-
- zk.setACL("/path1", Ids.OPEN_ACL_UNSAFE, -1);
-
- } finally {
- zk.close();
- }
+ ZooKeeper zk = createClient();
+ try {
+ zk.addAuthInfo("digest", "pat:pass".getBytes());
+ zk.create("/path1", null, Ids.CREATOR_ALL_ACL, CreateMode.PERSISTENT);
+ zk.close();
+ // verify super can do anything and ignores ACLs
+ zk = createClient();
+ zk.addAuthInfo("digest", "super:test".getBytes());
+ zk.getData("/path1", false, null);
+
+ zk.setACL("/path1", Ids.READ_ACL_UNSAFE, -1);
+ zk.create("/path1/foo", null, Ids.CREATOR_ALL_ACL, CreateMode.PERSISTENT);
+
+ zk.setACL("/path1", Ids.OPEN_ACL_UNSAFE, -1);
+
+ } finally {
+ zk.close();
+ }
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/BufferSizeTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/BufferSizeTest.java
index 79502cb79..c5656a0de 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/BufferSizeTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/BufferSizeTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -20,10 +20,8 @@ package org.apache.zookeeper.test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
-
import java.io.File;
import java.io.IOException;
-
import org.apache.jute.BinaryInputArchive;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
@@ -33,11 +31,10 @@ import org.junit.Before;
import org.junit.Test;
public class BufferSizeTest extends ClientBase {
+
public static final int TEST_MAXBUFFER = 100;
- private static final File TEST_DATA = new File(
- System.getProperty("test.data.dir", "src/test/resources/data"),
- "buffersize");
-
+ private static final File TEST_DATA = new File(System.getProperty("test.data.dir", "src/test/resources/data"), "buffersize");
+
private ZooKeeper zk;
@Before
@@ -46,7 +43,7 @@ public class BufferSizeTest extends ClientBase {
assertEquals("Can't set jute.maxbuffer!", TEST_MAXBUFFER, BinaryInputArchive.maxBuffer);
zk = createClient();
}
-
+
@Test
public void testCreatesReqs() throws Exception {
testRequests(new ClientOp() {
@@ -56,7 +53,7 @@ public class BufferSizeTest extends ClientBase {
}
});
}
-
+
@Test
public void testSetReqs() throws Exception {
final String path = "/set_test";
@@ -68,7 +65,7 @@ public class BufferSizeTest extends ClientBase {
}
});
}
-
+
/** Issues requests containing data smaller, equal, and greater than TEST_MAXBUFFER. */
private void testRequests(ClientOp clientOp) throws Exception {
clientOp.execute(new byte[TEST_MAXBUFFER - 60]);
@@ -76,15 +73,19 @@ public class BufferSizeTest extends ClientBase {
// This should fail since the buffer size > the data size due to extra fields
clientOp.execute(new byte[TEST_MAXBUFFER]);
fail("Request exceeding jute.maxbuffer succeeded!");
- } catch (KeeperException.ConnectionLossException e) {}
+ } catch (KeeperException.ConnectionLossException e) {
+ }
try {
clientOp.execute(new byte[TEST_MAXBUFFER + 10]);
fail("Request exceeding jute.maxbuffer succeeded!");
- } catch (KeeperException.ConnectionLossException e) {}
+ } catch (KeeperException.ConnectionLossException e) {
+ }
}
private interface ClientOp {
+
void execute(byte[] data) throws Exception;
+
}
@Test
@@ -96,28 +97,25 @@ public class BufferSizeTest extends ClientBase {
stopServer();
startServer();
}
-
+
@Test
public void testStartupFailureCreate() throws Exception {
// Empty snapshot and logfile containing a 5000-byte create
- testStartupFailure(new File(TEST_DATA, "create"),
- "Server started despite create exceeding jute.maxbuffer!");
+ testStartupFailure(new File(TEST_DATA, "create"), "Server started despite create exceeding jute.maxbuffer!");
}
-
+
@Test
public void testStartupFailureSet() throws Exception {
// Empty snapshot and logfile containing a 1-byte create and 5000-byte set
- testStartupFailure(new File(TEST_DATA, "set"),
- "Server started despite set exceeding jute.maxbuffer!");
+ testStartupFailure(new File(TEST_DATA, "set"), "Server started despite set exceeding jute.maxbuffer!");
}
-
+
@Test
public void testStartupFailureSnapshot() throws Exception {
// Snapshot containing 5000-byte znode and logfile containing create txn
- testStartupFailure(new File(TEST_DATA, "snapshot"),
- "Server started despite znode exceeding jute.maxbuffer!");
+ testStartupFailure(new File(TEST_DATA, "snapshot"), "Server started despite znode exceeding jute.maxbuffer!");
}
-
+
private void testStartupFailure(File testDir, String failureMsg) throws Exception {
stopServer();
// Point server at testDir
@@ -132,4 +130,5 @@ public class BufferSizeTest extends ClientBase {
tmpDir = oldTmpDir;
}
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/ChrootAsyncTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/ChrootAsyncTest.java
index e60ea049a..3366f60cf 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/ChrootAsyncTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/ChrootAsyncTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,13 +18,14 @@
package org.apache.zookeeper.test;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
import org.apache.zookeeper.CreateMode;
-import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.ZooDefs.Ids;
+import org.apache.zookeeper.ZooKeeper;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
public class ChrootAsyncTest extends AsyncOpsTest {
+
private static final Logger LOG = LoggerFactory.getLogger(ChrootAsyncTest.class);
@Override
@@ -38,10 +39,10 @@ public class ChrootAsyncTest extends AsyncOpsTest {
ZooKeeper zk = createClient(hp);
try {
- zk.create("/chrootasynctest", null, Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk.create("/chrootasynctest", null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
} finally {
zk.close();
}
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/ChrootClientTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/ChrootClientTest.java
index e0286e16e..170686877 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/ChrootClientTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/ChrootClientTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,14 +18,15 @@
package org.apache.zookeeper.test;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
import org.apache.zookeeper.CreateMode;
-import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.ZooDefs.Ids;
+import org.apache.zookeeper.ZooKeeper;
import org.junit.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
public class ChrootClientTest extends ClientTest {
+
private static final Logger LOG = LoggerFactory.getLogger(ChrootClientTest.class);
@Override
@@ -40,15 +41,15 @@ public class ChrootClientTest extends ClientTest {
ZooKeeper zk = createClient(hp);
try {
- zk.create("/chrootclienttest", null, Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk.create("/chrootclienttest", null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
} finally {
zk.close();
}
}
-
+
@Test
public void testPing() throws Exception {
// not necessary to repeat this, expensive and not chroot related
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/ChrootTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/ChrootTest.java
index d65ed8dd5..ddf206324 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/ChrootTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/ChrootTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,22 +18,27 @@
package org.apache.zookeeper.test;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
import java.io.IOException;
import java.util.Arrays;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
-
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
-import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.ZooDefs.Ids;
-import org.junit.Assert;
+import org.apache.zookeeper.ZooKeeper;
import org.junit.Test;
public class ChrootTest extends ClientBase {
+
private static class MyWatcher implements Watcher {
+
private final String path;
private String eventPath;
private CountDownLatch latch = new CountDownLatch(1);
@@ -48,32 +53,30 @@ public class ChrootTest extends ClientBase {
}
public boolean matches() throws InterruptedException {
if (!latch.await(CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS)) {
- Assert.fail("No watch received within timeout period " + path);
+ fail("No watch received within timeout period " + path);
}
return path.equals(eventPath);
}
+
}
@Test
- public void testChrootSynchronous()
- throws IOException, InterruptedException, KeeperException
- {
+ public void testChrootSynchronous() throws IOException, InterruptedException, KeeperException {
ZooKeeper zk1 = createClient();
try {
- zk1.create("/ch1", null, Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk1.create("/ch1", null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
} finally {
- if(zk1 != null)
+ if (zk1 != null) {
zk1.close();
+ }
}
ZooKeeper zk2 = createClient(hostPort + "/ch1");
try {
- Assert.assertEquals("/ch2",
- zk2.create("/ch2", null, Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT));
+ assertEquals("/ch2", zk2.create("/ch2", null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT));
} finally {
- if(zk2 != null)
+ if (zk2 != null) {
zk2.close();
+ }
}
zk1 = createClient();
@@ -81,56 +84,56 @@ public class ChrootTest extends ClientBase {
try {
// check get
MyWatcher w1 = new MyWatcher("/ch1");
- Assert.assertNotNull(zk1.exists("/ch1", w1));
+ assertNotNull(zk1.exists("/ch1", w1));
MyWatcher w2 = new MyWatcher("/ch1/ch2");
- Assert.assertNotNull(zk1.exists("/ch1/ch2", w2));
+ assertNotNull(zk1.exists("/ch1/ch2", w2));
MyWatcher w3 = new MyWatcher("/ch2");
- Assert.assertNotNull(zk2.exists("/ch2", w3));
+ assertNotNull(zk2.exists("/ch2", w3));
// set watches on child
MyWatcher w4 = new MyWatcher("/ch1");
- zk1.getChildren("/ch1",w4);
+ zk1.getChildren("/ch1", w4);
MyWatcher w5 = new MyWatcher("/");
- zk2.getChildren("/",w5);
+ zk2.getChildren("/", w5);
// check set
zk1.setData("/ch1", "1".getBytes(), -1);
zk2.setData("/ch2", "2".getBytes(), -1);
// check watches
- Assert.assertTrue(w1.matches());
- Assert.assertTrue(w2.matches());
- Assert.assertTrue(w3.matches());
+ assertTrue(w1.matches());
+ assertTrue(w2.matches());
+ assertTrue(w3.matches());
// check exceptions
try {
zk2.setData("/ch3", "3".getBytes(), -1);
} catch (KeeperException.NoNodeException e) {
- Assert.assertEquals("/ch3", e.getPath());
+ assertEquals("/ch3", e.getPath());
}
- Assert.assertTrue(Arrays.equals("1".getBytes(),
- zk1.getData("/ch1", false, null)));
- Assert.assertTrue(Arrays.equals("2".getBytes(),
- zk1.getData("/ch1/ch2", false, null)));
- Assert.assertTrue(Arrays.equals("2".getBytes(),
- zk2.getData("/ch2", false, null)));
+ assertTrue(Arrays.equals("1".getBytes(), zk1.getData("/ch1", false, null)));
+ assertTrue(Arrays.equals("2".getBytes(), zk1.getData("/ch1/ch2", false, null)));
+ assertTrue(Arrays.equals("2".getBytes(), zk2.getData("/ch2", false, null)));
// check delete
zk2.delete("/ch2", -1);
- Assert.assertTrue(w4.matches());
- Assert.assertTrue(w5.matches());
+ assertTrue(w4.matches());
+ assertTrue(w5.matches());
zk1.delete("/ch1", -1);
- Assert.assertNull(zk1.exists("/ch1", false));
- Assert.assertNull(zk1.exists("/ch1/ch2", false));
- Assert.assertNull(zk2.exists("/ch2", false));
+ assertNull(zk1.exists("/ch1", false));
+ assertNull(zk1.exists("/ch1/ch2", false));
+ assertNull(zk2.exists("/ch2", false));
} finally {
- if(zk1 != null)
+ if (zk1 != null) {
zk1.close();
- if(zk2 != null)
+ }
+ if (zk2 != null) {
zk2.close();
+ }
}
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/ClientBase.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/ClientBase.java
index 2638053c7..7fa7060e9 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/ClientBase.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/ClientBase.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -19,7 +19,10 @@
package org.apache.zookeeper.test;
import static org.apache.zookeeper.client.FourLetterWordMain.send4LetterWord;
-
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
@@ -38,13 +41,8 @@ import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
-
import javax.management.MBeanServerConnection;
import javax.management.ObjectName;
-
-
-import org.apache.zookeeper.common.Time;
-import org.apache.zookeeper.common.X509Exception.SSLContextException;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.PortAssignment;
import org.apache.zookeeper.TestableZooKeeper;
@@ -54,6 +52,8 @@ import org.apache.zookeeper.Watcher.Event.KeeperState;
import org.apache.zookeeper.ZKTestCase;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.common.IOUtils;
+import org.apache.zookeeper.common.Time;
+import org.apache.zookeeper.common.X509Exception.SSLContextException;
import org.apache.zookeeper.server.ServerCnxnFactory;
import org.apache.zookeeper.server.ZKDatabase;
import org.apache.zookeeper.server.ZooKeeperServer;
@@ -61,17 +61,16 @@ import org.apache.zookeeper.server.persistence.FilePadding;
import org.apache.zookeeper.server.quorum.QuorumPeer;
import org.apache.zookeeper.server.util.OSMXBean;
import org.junit.After;
-import org.junit.Assert;
import org.junit.Before;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public abstract class ClientBase extends ZKTestCase {
+
protected static final Logger LOG = LoggerFactory.getLogger(ClientBase.class);
public static int CONNECTION_TIMEOUT = 30000;
- static final File BASETEST =
- new File(System.getProperty("build.test.dir", "build"));
+ static final File BASETEST = new File(System.getProperty("build.test.dir", "build"));
protected String hostPort = "127.0.0.1:" + PortAssignment.unique();
protected int maxCnxns = 0;
@@ -92,11 +91,14 @@ public abstract class ClientBase extends ZKTestCase {
*
*/
protected static class NullWatcher implements Watcher {
+
public void process(WatchedEvent event) { /* nada */ }
+
}
public static class CountdownWatcher implements Watcher {
- // XXX this doesn't need to be volatile! (Should probably be final)
+
+ // TODO this doesn't need to be volatile! (Should probably be final)
volatile CountDownLatch clientConnected;
// Set to true when connected to a read-only server, or a read-write (quorum) server.
volatile boolean connected;
@@ -108,13 +110,13 @@ public abstract class ClientBase extends ZKTestCase {
public CountdownWatcher() {
reset();
}
- synchronized public void reset() {
+ public synchronized void reset() {
clientConnected = new CountDownLatch(1);
connected = false;
syncConnected = false;
readOnlyConnected = false;
}
- synchronized public void process(WatchedEvent event) {
+ public synchronized void process(WatchedEvent event) {
KeeperState state = event.getState();
if (state == KeeperState.SyncConnected) {
connected = true;
@@ -135,15 +137,13 @@ public abstract class ClientBase extends ZKTestCase {
clientConnected.countDown();
}
}
- synchronized public boolean isConnected() {
+ public synchronized boolean isConnected() {
return connected;
}
- synchronized public void waitForConnected(long timeout)
- throws InterruptedException, TimeoutException
- {
+ public synchronized void waitForConnected(long timeout) throws InterruptedException, TimeoutException {
long expire = Time.currentElapsedTime() + timeout;
long left = timeout;
- while(!connected && left > 0) {
+ while (!connected && left > 0) {
wait(left);
left = expire - Time.currentElapsedTime();
}
@@ -152,12 +152,10 @@ public abstract class ClientBase extends ZKTestCase {
}
}
- synchronized public void waitForSyncConnected(long timeout)
- throws InterruptedException, TimeoutException
- {
+ public synchronized void waitForSyncConnected(long timeout) throws InterruptedException, TimeoutException {
long expire = Time.currentElapsedTime() + timeout;
long left = timeout;
- while(!syncConnected && left > 0) {
+ while (!syncConnected && left > 0) {
wait(left);
left = expire - Time.currentElapsedTime();
}
@@ -165,12 +163,10 @@ public abstract class ClientBase extends ZKTestCase {
throw new TimeoutException("Failed to connect to read-write ZooKeeper server.");
}
}
- synchronized public void waitForReadOnlyConnected(long timeout)
- throws InterruptedException, TimeoutException
- {
+ public synchronized void waitForReadOnlyConnected(long timeout) throws InterruptedException, TimeoutException {
long expire = System.currentTimeMillis() + timeout;
long left = timeout;
- while(!readOnlyConnected && left > 0) {
+ while (!readOnlyConnected && left > 0) {
wait(left);
left = expire - System.currentTimeMillis();
}
@@ -178,12 +174,10 @@ public abstract class ClientBase extends ZKTestCase {
throw new TimeoutException("Failed to connect in read-only mode to ZooKeeper server.");
}
}
- synchronized public void waitForDisconnected(long timeout)
- throws InterruptedException, TimeoutException
- {
+ public synchronized void waitForDisconnected(long timeout) throws InterruptedException, TimeoutException {
long expire = Time.currentElapsedTime() + timeout;
long left = timeout;
- while(connected && left > 0) {
+ while (connected && left > 0) {
wait(left);
left = expire - Time.currentElapsedTime();
}
@@ -192,53 +186,42 @@ public abstract class ClientBase extends ZKTestCase {
}
}
+
}
- protected TestableZooKeeper createClient()
- throws IOException, InterruptedException
- {
+ protected TestableZooKeeper createClient() throws IOException, InterruptedException {
return createClient(hostPort);
}
- protected TestableZooKeeper createClient(String hp)
- throws IOException, InterruptedException
- {
+ protected TestableZooKeeper createClient(String hp) throws IOException, InterruptedException {
CountdownWatcher watcher = new CountdownWatcher();
return createClient(watcher, hp);
}
- protected TestableZooKeeper createClient(CountdownWatcher watcher)
- throws IOException, InterruptedException
- {
+ protected TestableZooKeeper createClient(CountdownWatcher watcher) throws IOException, InterruptedException {
return createClient(watcher, hostPort);
}
private List<ZooKeeper> allClients;
private boolean allClientsSetup = false;
- protected TestableZooKeeper createClient(CountdownWatcher watcher, String hp)
- throws IOException, InterruptedException
- {
+ protected TestableZooKeeper createClient(CountdownWatcher watcher, String hp) throws IOException, InterruptedException {
return createClient(watcher, hp, CONNECTION_TIMEOUT);
}
- protected TestableZooKeeper createClient(CountdownWatcher watcher,
- String hp, int timeout)
- throws IOException, InterruptedException
- {
+ protected TestableZooKeeper createClient(CountdownWatcher watcher, String hp, int timeout) throws IOException, InterruptedException {
watcher.reset();
TestableZooKeeper zk = new TestableZooKeeper(hp, timeout, watcher);
- if (!watcher.clientConnected.await(timeout, TimeUnit.MILLISECONDS))
- {
+ if (!watcher.clientConnected.await(timeout, TimeUnit.MILLISECONDS)) {
if (exceptionOnFailedConnect) {
- throw new ProtocolException("Unable to connect to server");
+ throw new ProtocolException("Unable to connect to server");
}
- Assert.fail("Unable to connect to server");
+ fail("Unable to connect to server");
}
- synchronized(this) {
+ synchronized (this) {
if (!allClientsSetup) {
LOG.error("allClients never setup");
- Assert.fail("allClients never setup");
+ fail("allClients never setup");
}
if (allClients != null) {
allClients.add(zk);
@@ -253,25 +236,27 @@ public abstract class ClientBase extends ZKTestCase {
}
public static class HostPort {
+
String host;
int port;
public HostPort(String host, int port) {
this.host = host;
this.port = port;
}
+
}
public static List<HostPort> parseHostPortList(String hplist) {
ArrayList<HostPort> alist = new ArrayList<HostPort>();
- for (String hp: hplist.split(",")) {
+ for (String hp : hplist.split(",")) {
int idx = hp.lastIndexOf(':');
String host = hp.substring(0, idx);
int port;
try {
port = Integer.parseInt(hp.substring(idx + 1));
- } catch(RuntimeException e) {
+ } catch (RuntimeException e) {
throw new RuntimeException("Problem parsing " + hp + e.toString());
}
- alist.add(new HostPort(host,port));
+ alist.add(new HostPort(host, port));
}
return alist;
}
@@ -287,8 +272,7 @@ public abstract class ClientBase extends ZKTestCase {
// if there are multiple hostports, just take the first one
HostPort hpobj = parseHostPortList(hp).get(0);
String result = send4LetterWord(hpobj.host, hpobj.port, "stat", secure);
- if (result.startsWith("Zookeeper version:") &&
- !result.contains("READ-ONLY")) {
+ if (result.startsWith("Zookeeper version:") && !result.contains("READ-ONLY")) {
return true;
}
} catch (ConnectException e) {
@@ -344,8 +328,7 @@ public abstract class ClientBase extends ZKTestCase {
/**
* Return true if any of the states is achieved
*/
- public static boolean waitForServerState(QuorumPeer qp, int timeout,
- String... serverStates) {
+ public static boolean waitForServerState(QuorumPeer qp, int timeout, String... serverStates) {
long start = Time.currentElapsedTime();
while (true) {
try {
@@ -364,15 +347,11 @@ public abstract class ClientBase extends ZKTestCase {
}
}
- static void verifyThreadTerminated(Thread thread, long millis)
- throws InterruptedException
- {
+ static void verifyThreadTerminated(Thread thread, long millis) throws InterruptedException {
thread.join(millis);
if (thread.isAlive()) {
- LOG.error("Thread " + thread.getName() + " : "
- + Arrays.toString(thread.getStackTrace()));
- Assert.assertFalse("thread " + thread.getName()
- + " still alive after join", true);
+ LOG.error("Thread " + thread.getName() + " : " + Arrays.toString(thread.getStackTrace()));
+ assertFalse("thread " + thread.getName() + " still alive after join", true);
}
}
@@ -389,8 +368,8 @@ public abstract class ClientBase extends ZKTestCase {
// don't delete tmpFile - this ensures we don't attempt to create
// a tmpDir with a duplicate name
File tmpDir = new File(tmpFile + ".dir");
- Assert.assertFalse(tmpDir.exists()); // never true if tmpfile does it's job
- Assert.assertTrue(tmpDir.mkdirs());
+ assertFalse(tmpDir.exists()); // never true if tmpfile does it's job
+ assertTrue(tmpDir.mkdirs());
// todo not every tmp directory needs this file
if (createInitFile) {
@@ -403,13 +382,13 @@ public abstract class ClientBase extends ZKTestCase {
public static void createInitializeFile(File dir) throws IOException {
File initFile = new File(dir, "initialize");
if (!initFile.exists()) {
- Assert.assertTrue(initFile.createNewFile());
+ assertTrue(initFile.createNewFile());
}
}
private static int getPort(String hostPort) {
String[] split = hostPort.split(":");
- String portstr = split[split.length-1];
+ String portstr = split[split.length - 1];
String[] pc = portstr.split("/");
if (pc.length > 1) {
portstr = pc[0];
@@ -420,16 +399,19 @@ public abstract class ClientBase extends ZKTestCase {
/**
* Starting the given server instance
*/
- public static void startServerInstance(File dataDir,
- ServerCnxnFactory factory, String hostPort, int serverId) throws IOException,
- InterruptedException {
+ public static void startServerInstance(
+ File dataDir,
+ ServerCnxnFactory factory,
+ String hostPort,
+ int serverId) throws IOException, InterruptedException {
final int port = getPort(hostPort);
LOG.info("STARTING server instance 127.0.0.1:{}", port);
ZooKeeperServer zks = new ZooKeeperServer(dataDir, dataDir, 3000);
zks.setCreateSessionTrackerServerId(serverId);
factory.startup(zks);
- Assert.assertTrue("waiting for server up", ClientBase.waitForServerUp(
- "127.0.0.1:" + port, CONNECTION_TIMEOUT, factory.isSecure()));
+ assertTrue(
+ "waiting for server up",
+ ClientBase.waitForServerUp("127.0.0.1:" + port, CONNECTION_TIMEOUT, factory.isSecure()));
}
/**
@@ -447,8 +429,9 @@ public abstract class ClientBase extends ZKTestCase {
* for more information.
*/
public static ServerCnxnFactory createNewServerInstance(
- ServerCnxnFactory factory, String hostPort, int maxCnxns)
- throws IOException, InterruptedException {
+ ServerCnxnFactory factory,
+ String hostPort,
+ int maxCnxns) throws IOException, InterruptedException {
final int port = getPort(hostPort);
LOG.info("CREATING server instance 127.0.0.1:{}", port);
if (factory == null) {
@@ -457,9 +440,7 @@ public abstract class ClientBase extends ZKTestCase {
return factory;
}
- static void shutdownServerInstance(ServerCnxnFactory factory,
- String hostPort)
- {
+ static void shutdownServerInstance(ServerCnxnFactory factory, String hostPort) {
if (factory != null) {
ZKDatabase zkDb = null;
{
@@ -478,10 +459,9 @@ public abstract class ClientBase extends ZKTestCase {
}
final int PORT = getPort(hostPort);
- Assert.assertTrue("waiting for server down",
- ClientBase.waitForServerDown("127.0.0.1:" + PORT,
- CONNECTION_TIMEOUT,
- factory.isSecure()));
+ assertTrue(
+ "waiting for server down",
+ ClientBase.waitForServerDown("127.0.0.1:" + PORT, CONNECTION_TIMEOUT, factory.isSecure()));
}
}
@@ -491,7 +471,7 @@ public abstract class ClientBase extends ZKTestCase {
public static void setupTestEnv() {
// during the tests we run with 100K prealloc in the logs.
// on windows systems prealloc of 64M was seen to take ~15seconds
- // resulting in test Assert.failure (client timeout on first session).
+ // resulting in test failure (client timeout on first session).
// set env and directly in order to handle static init/gc issues
System.setProperty("zookeeper.preAllocSize", "100");
FilePadding.setPreallocSize(100 * 1024);
@@ -514,10 +494,9 @@ public abstract class ClientBase extends ZKTestCase {
* only place sun has implemented as part of the mgmt bean api.
*/
OSMXBean osMbean = new OSMXBean();
- if (osMbean.getUnix() == true) {
+ if (osMbean.getUnix()) {
initialFdCount = osMbean.getOpenFileDescriptorCount();
- LOG.info("Initial fdcount is: "
- + initialFdCount);
+ LOG.info("Initial fdcount is: " + initialFdCount);
}
setupTestEnv();
@@ -546,12 +525,10 @@ public abstract class ClientBase extends ZKTestCase {
private void startServer(int serverId) throws Exception {
LOG.info("STARTING server");
- serverFactory = createNewServerInstance(serverFactory, hostPort,
- maxCnxns);
+ serverFactory = createNewServerInstance(serverFactory, hostPort, maxCnxns);
startServerInstance(tmpDir, serverFactory, hostPort, serverId);
// ensure that server and data bean are registered
- Set<ObjectName> children = JMXEnv.ensureParent("InMemoryDataTree",
- "StandaloneServer_port");
+ Set<ObjectName> children = JMXEnv.ensureParent("InMemoryDataTree", "StandaloneServer_port");
// Remove beans which are related to zk client sessions. Strong
// assertions cannot be done for these client sessions because
// registeration of these beans with server will happen only on their
@@ -565,10 +542,8 @@ public abstract class ClientBase extends ZKTestCase {
Iterator<ObjectName> childItr = children.iterator();
while (childItr.hasNext()) {
ObjectName clientBean = childItr.next();
- if (clientBean.toString().contains(
- getHexSessionId(zkc.getSessionId()))) {
- LOG.info("found name:" + zkc.getSessionId()
- + " client bean:" + clientBean.toString());
+ if (clientBean.toString().contains(getHexSessionId(zkc.getSessionId()))) {
+ LOG.info("found name:" + zkc.getSessionId() + " client bean:" + clientBean.toString());
childItr.remove();
}
}
@@ -577,7 +552,7 @@ public abstract class ClientBase extends ZKTestCase {
for (ObjectName bean : children) {
LOG.info("unexpected:" + bean.toString());
}
- Assert.assertEquals("Unexpected bean exists!", 0, children.size());
+ assertEquals("Unexpected bean exists!", 0, children.size());
}
/**
@@ -601,12 +576,15 @@ public abstract class ClientBase extends ZKTestCase {
protected void tearDownAll() throws Exception {
synchronized (this) {
- if (allClients != null) for (ZooKeeper zk : allClients) {
- try {
- if (zk != null)
- zk.close();
- } catch (InterruptedException e) {
- LOG.warn("ignoring interrupt", e);
+ if (allClients != null) {
+ for (ZooKeeper zk : allClients) {
+ try {
+ if (zk != null) {
+ zk.close();
+ }
+ } catch (InterruptedException e) {
+ LOG.warn("ignoring interrupt", e);
+ }
}
}
allClients = null;
@@ -622,7 +600,7 @@ public abstract class ClientBase extends ZKTestCase {
stopServer();
if (tmpDir != null) {
- Assert.assertTrue("delete " + tmpDir.toString(), recursiveDelete(tmpDir));
+ assertTrue("delete " + tmpDir.toString(), recursiveDelete(tmpDir));
}
// This has to be set to null when the same instance of this class is reused between test cases
@@ -636,10 +614,9 @@ public abstract class ClientBase extends ZKTestCase {
* only place sun has implemented as part of the mgmt bean api.
*/
OSMXBean osMbean = new OSMXBean();
- if (osMbean.getUnix() == true) {
+ if (osMbean.getUnix()) {
long fdCount = osMbean.getOpenFileDescriptorCount();
- String message = "fdcount after test is: "
- + fdCount + " at start it was " + initialFdCount;
+ String message = "fdcount after test is: " + fdCount + " at start it was " + initialFdCount;
LOG.info(message);
if (fdCount > initialFdCount) {
LOG.info("sleeping for 20 secs");
@@ -658,16 +635,16 @@ public abstract class ClientBase extends ZKTestCase {
}
public static boolean recursiveDelete(File d) {
- return TestUtils.deleteFileRecursively(d, true);
+ return TestUtils.deleteFileRecursively(d, true);
}
public static void logAllStackTraces() {
StringBuilder sb = new StringBuilder();
sb.append("Starting logAllStackTraces()\n");
Map<Thread, StackTraceElement[]> threads = Thread.getAllStackTraces();
- for (Entry<Thread, StackTraceElement[]> e: threads.entrySet()) {
+ for (Entry<Thread, StackTraceElement[]> e : threads.entrySet()) {
sb.append("Thread " + e.getKey().getName() + "\n");
- for (StackTraceElement elem: e.getValue()) {
+ for (StackTraceElement elem : e.getValue()) {
sb.append("\tat " + elem + "\n");
}
}
@@ -679,17 +656,15 @@ public abstract class ClientBase extends ZKTestCase {
* Verify that all of the servers see the same number of nodes
* at the root
*/
- void verifyRootOfAllServersMatch(String hostPort)
- throws InterruptedException, KeeperException, IOException
- {
- String parts[] = hostPort.split(",");
+ void verifyRootOfAllServersMatch(String hostPort) throws InterruptedException, KeeperException, IOException {
+ String[] parts = hostPort.split(",");
// run through till the counts no longer change on each server
// max 15 tries, with 2 second sleeps, so approx 30 seconds
int[] counts = new int[parts.length];
int failed = 0;
for (int j = 0; j < 100; j++) {
- int newcounts[] = new int[parts.length];
+ int[] newcounts = new int[parts.length];
int i = 0;
for (String hp : parts) {
try {
@@ -702,15 +677,14 @@ public abstract class ClientBase extends ZKTestCase {
}
} catch (Throwable t) {
failed++;
- // if session creation Assert.fails dump the thread stack
+ // if session creation fails dump the thread stack
// and try the next server
logAllStackTraces();
}
}
if (Arrays.equals(newcounts, counts)) {
- LOG.info("Found match with array:"
- + Arrays.toString(newcounts));
+ LOG.info("Found match with array:" + Arrays.toString(newcounts));
counts = newcounts;
break;
} else {
@@ -718,7 +692,7 @@ public abstract class ClientBase extends ZKTestCase {
Thread.sleep(10000);
}
- // don't keep this up too long, will Assert.assert false below
+ // don't keep this up too long, will assert false below
if (failed > 10) {
break;
}
@@ -727,10 +701,10 @@ public abstract class ClientBase extends ZKTestCase {
// verify all the servers reporting same number of nodes
String logmsg = "node count not consistent{} {}";
for (int i = 1; i < parts.length; i++) {
- if (counts[i-1] != counts[i]) {
- LOG.error(logmsg, Integer.valueOf(counts[i-1]), Integer.valueOf(counts[i]));
+ if (counts[i - 1] != counts[i]) {
+ LOG.error(logmsg, Integer.valueOf(counts[i - 1]), Integer.valueOf(counts[i]));
} else {
- LOG.info(logmsg, Integer.valueOf(counts[i-1]), Integer.valueOf(counts[i]));
+ LOG.info(logmsg, Integer.valueOf(counts[i - 1]), Integer.valueOf(counts[i]));
}
}
}
@@ -779,8 +753,9 @@ public abstract class ClientBase extends ZKTestCase {
try {
watcher.waitForConnected(CONNECTION_TIMEOUT);
} catch (InterruptedException | TimeoutException e) {
- Assert.fail("ZooKeeper client can not connect to " + cxnString);
+ fail("ZooKeeper client can not connect to " + cxnString);
}
return zk;
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/ClientHammerTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/ClientHammerTest.java
index 01cdf2780..a3ca3929a 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/ClientHammerTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/ClientHammerTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,26 +18,27 @@
package org.apache.zookeeper.test;
+import static org.junit.Assert.assertEquals;
import java.io.IOException;
import java.util.Date;
import java.util.List;
-
-import org.apache.zookeeper.common.Time;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
-import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.ZooDefs.Ids;
-import org.junit.Assert;
+import org.apache.zookeeper.ZooKeeper;
+import org.apache.zookeeper.common.Time;
import org.junit.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
public class ClientHammerTest extends ClientBase {
+
protected static final Logger LOG = LoggerFactory.getLogger(ClientHammerTest.class);
private static final long HAMMERTHREAD_LATENCY = 5;
- private static abstract class HammerThread extends Thread {
+ private abstract static class HammerThread extends Thread {
+
protected final int count;
protected volatile int current = 0;
@@ -45,9 +46,11 @@ public class ClientHammerTest extends ClientBase {
super(name);
this.count = count;
}
+
}
private static class BasicHammerThread extends HammerThread {
+
private final ZooKeeper zk;
private final String prefix;
@@ -58,7 +61,7 @@ public class ClientHammerTest extends ClientBase {
}
public void run() {
- byte b[] = new byte[256];
+ byte[] b = new byte[256];
try {
for (; current < count; current++) {
// Simulate a bit of network latency...
@@ -66,7 +69,7 @@ public class ClientHammerTest extends ClientBase {
zk.create(prefix + current, b, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
}
} catch (Throwable t) {
- LOG.error("Client create operation Assert.failed", t);
+ LOG.error("Client create operation failed", t);
} finally {
try {
zk.close();
@@ -75,22 +78,22 @@ public class ClientHammerTest extends ClientBase {
}
}
}
+
}
private static class SuperHammerThread extends HammerThread {
+
private final ClientHammerTest parent;
private final String prefix;
- SuperHammerThread(String name, ClientHammerTest parent, String prefix,
- int count)
- {
+ SuperHammerThread(String name, ClientHammerTest parent, String prefix, int count) {
super(name, count);
this.parent = parent;
this.prefix = prefix;
}
public void run() {
- byte b[] = new byte[256];
+ byte[] b = new byte[256];
try {
for (; current < count; current++) {
ZooKeeper zk = parent.createClient();
@@ -105,9 +108,10 @@ public class ClientHammerTest extends ClientBase {
}
}
} catch (Throwable t) {
- LOG.error("Client create operation Assert.failed", t);
+ LOG.error("Client create operation failed", t);
}
}
+
}
/**
@@ -120,9 +124,7 @@ public class ClientHammerTest extends ClientBase {
runHammer(10, 1000);
}
- public void runHammer(final int threadCount, final int childCount)
- throws Throwable
- {
+ public void runHammer(final int threadCount, final int childCount) throws Throwable {
try {
HammerThread[] threads = new HammerThread[threadCount];
long start = Time.currentElapsedTime();
@@ -131,9 +133,7 @@ public class ClientHammerTest extends ClientBase {
String prefix = "/test-" + i;
zk.create(prefix, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
prefix += "/";
- HammerThread thread =
- new BasicHammerThread("BasicHammerThread-" + i, zk, prefix,
- childCount);
+ HammerThread thread = new BasicHammerThread("BasicHammerThread-" + i, zk, prefix, childCount);
thread.start();
threads[i] = thread;
@@ -141,7 +141,7 @@ public class ClientHammerTest extends ClientBase {
verifyHammer(start, threads, childCount);
} catch (Throwable t) {
- LOG.error("test Assert.failed", t);
+ LOG.error("test failed", t);
throw t;
}
}
@@ -170,9 +170,7 @@ public class ClientHammerTest extends ClientBase {
}
}
prefix += "/";
- HammerThread thread =
- new SuperHammerThread("SuperHammerThread-" + i, this,
- prefix, childCount);
+ HammerThread thread = new SuperHammerThread("SuperHammerThread-" + i, this, prefix, childCount);
thread.start();
threads[i] = thread;
@@ -180,14 +178,12 @@ public class ClientHammerTest extends ClientBase {
verifyHammer(start, threads, childCount);
} catch (Throwable t) {
- LOG.error("test Assert.failed", t);
+ LOG.error("test failed", t);
throw t;
}
}
- public void verifyHammer(long start, HammerThread[] threads, int childCount)
- throws IOException, InterruptedException, KeeperException
- {
+ public void verifyHammer(long start, HammerThread[] threads, int childCount) throws IOException, InterruptedException, KeeperException {
// look for the clients to finish their create operations
LOG.info("Starting check for completed hammers");
int workingCount = threads.length;
@@ -205,8 +201,7 @@ public class ClientHammerTest extends ClientBase {
}
if (workingCount > 0) {
for (HammerThread h : threads) {
- LOG.warn(h.getName() + " never finished creation, current:"
- + h.current);
+ LOG.warn(h.getName() + " never finished creation, current:" + h.current);
}
} else {
LOG.info("Hammer threads completed creation operations");
@@ -214,33 +209,32 @@ public class ClientHammerTest extends ClientBase {
for (HammerThread h : threads) {
final int safetyFactor = 3;
- verifyThreadTerminated(h,
- (long)threads.length * (long)childCount
- * HAMMERTHREAD_LATENCY * (long)safetyFactor);
+ verifyThreadTerminated(h, (long) threads.length
+ * (long) childCount
+ * HAMMERTHREAD_LATENCY
+ * (long) safetyFactor);
}
- LOG.info(new Date() + " Total time "
- + (Time.currentElapsedTime() - start));
+ LOG.info(new Date() + " Total time " + (Time.currentElapsedTime() - start));
ZooKeeper zk = createClient();
try {
LOG.info("******************* Connected to ZooKeeper" + new Date());
for (int i = 0; i < threads.length; i++) {
LOG.info("Doing thread: " + i + " " + new Date());
- List<String> children =
- zk.getChildren("/test-" + i, false);
- Assert.assertEquals(childCount, children.size());
+ List<String> children = zk.getChildren("/test-" + i, false);
+ assertEquals(childCount, children.size());
children = zk.getChildren("/test-" + i, false, null);
- Assert.assertEquals(childCount, children.size());
+ assertEquals(childCount, children.size());
}
for (int i = 0; i < threads.length; i++) {
- List<String> children =
- zk.getChildren("/test-" + i, false);
- Assert.assertEquals(childCount, children.size());
+ List<String> children = zk.getChildren("/test-" + i, false);
+ assertEquals(childCount, children.size());
children = zk.getChildren("/test-" + i, false, null);
- Assert.assertEquals(childCount, children.size());
+ assertEquals(childCount, children.size());
}
} finally {
zk.close();
}
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/ClientPortBindTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/ClientPortBindTest.java
index 15dc891eb..528e3ea0f 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/ClientPortBindTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/ClientPortBindTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -19,7 +19,7 @@
package org.apache.zookeeper.test;
import static org.apache.zookeeper.test.ClientBase.CONNECTION_TIMEOUT;
-
+import static org.junit.Assert.assertTrue;
import java.io.File;
import java.net.Inet6Address;
import java.net.InetAddress;
@@ -27,20 +27,18 @@ import java.net.InetSocketAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
import org.apache.zookeeper.PortAssignment;
import org.apache.zookeeper.ZKTestCase;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.server.ServerCnxnFactory;
import org.apache.zookeeper.server.ZooKeeperServer;
-import org.junit.Assert;
import org.junit.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class ClientPortBindTest extends ZKTestCase {
-public class ClientPortBindTest extends ZKTestCase{
- protected static final Logger LOG =
- LoggerFactory.getLogger(ClientPortBindTest.class);
+ protected static final Logger LOG = LoggerFactory.getLogger(ClientPortBindTest.class);
/**
* Verify that the server binds to the specified address
@@ -48,24 +46,23 @@ public class ClientPortBindTest extends ZKTestCase{
@Test
public void testBindByAddress() throws Exception {
String bindAddress = null;
- Enumeration<NetworkInterface> intfs =
- NetworkInterface.getNetworkInterfaces();
+ Enumeration<NetworkInterface> intfs = NetworkInterface.getNetworkInterfaces();
// if we have a loopback and it has an address use it
- while(intfs.hasMoreElements()) {
+ while (intfs.hasMoreElements()) {
NetworkInterface i = intfs.nextElement();
try {
if (i.isLoopback()) {
- Enumeration<InetAddress> addrs = i.getInetAddresses();
- while (addrs.hasMoreElements()) {
- InetAddress a = addrs.nextElement();
- if(a.isLoopbackAddress()) {
- bindAddress = a.getHostAddress();
- if (a instanceof Inet6Address) {
- bindAddress = "[" + bindAddress + "]";
- }
- break;
+ Enumeration<InetAddress> addrs = i.getInetAddresses();
+ while (addrs.hasMoreElements()) {
+ InetAddress a = addrs.nextElement();
+ if (a.isLoopbackAddress()) {
+ bindAddress = a.getHostAddress();
+ if (a instanceof Inet6Address) {
+ bindAddress = "[" + bindAddress + "]";
+ }
+ break;
+ }
}
- }
}
} catch (SocketException se) {
LOG.warn("Couldn't find loopback interface: " + se.getMessage());
@@ -81,20 +78,16 @@ public class ClientPortBindTest extends ZKTestCase{
final String HOSTPORT = bindAddress + ":" + PORT;
LOG.info("Using " + HOSTPORT + " as the host/port");
-
File tmpDir = ClientBase.createTmpDir();
ClientBase.setupTestEnv();
ZooKeeperServer zks = new ZooKeeperServer(tmpDir, tmpDir, 3000);
- ServerCnxnFactory f = ServerCnxnFactory.createFactory(
- new InetSocketAddress(bindAddress, PORT), -1);
+ ServerCnxnFactory f = ServerCnxnFactory.createFactory(new InetSocketAddress(bindAddress, PORT), -1);
f.startup(zks);
LOG.info("starting up the the server, waiting");
- Assert.assertTrue("waiting for server up",
- ClientBase.waitForServerUp(HOSTPORT,
- CONNECTION_TIMEOUT));
+ assertTrue("waiting for server up", ClientBase.waitForServerUp(HOSTPORT, CONNECTION_TIMEOUT));
ZooKeeper zk = ClientBase.createZKClient(HOSTPORT);
try {
zk.close();
@@ -102,9 +95,8 @@ public class ClientPortBindTest extends ZKTestCase{
f.shutdown();
zks.shutdown();
- Assert.assertTrue("waiting for server down",
- ClientBase.waitForServerDown(HOSTPORT,
- CONNECTION_TIMEOUT));
+ assertTrue("waiting for server down", ClientBase.waitForServerDown(HOSTPORT, CONNECTION_TIMEOUT));
}
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/ClientRetryTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/ClientRetryTest.java
index e53d911ef..48c018221 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/ClientRetryTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/ClientRetryTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -15,14 +15,14 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
package org.apache.zookeeper.test;
+import static org.junit.Assert.assertSame;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
-
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.ZooKeeper.States;
-import org.junit.Assert;
import org.junit.Test;
public class ClientRetryTest extends ClientBase {
@@ -45,7 +45,7 @@ public class ClientRetryTest extends ClientBase {
* obvious way to detect the difference.
*/
@Test
- public void testClientRetry() throws IOException, InterruptedException, TimeoutException{
+ public void testClientRetry() throws IOException, InterruptedException, TimeoutException {
CountdownWatcher cdw1 = new CountdownWatcher();
CountdownWatcher cdw2 = new CountdownWatcher();
ZooKeeper zk = new ZooKeeper(hostPort, 10000, cdw1);
@@ -55,13 +55,13 @@ public class ClientRetryTest extends ClientBase {
try {
States s1 = zk.getState();
States s2 = zk2.getState();
- Assert.assertSame(s1,States.CONNECTED);
- Assert.assertSame(s2,States.CONNECTING);
+ assertSame(s1, States.CONNECTED);
+ assertSame(s2, States.CONNECTING);
cdw1.reset();
zk.close();
cdw1.waitForDisconnected(CONNECTION_TIMEOUT);
cdw2.waitForConnected(CONNECTION_TIMEOUT);
- Assert.assertSame(zk2.getState(),States.CONNECTED);
+ assertSame(zk2.getState(), States.CONNECTED);
} finally {
zk2.close();
}
@@ -69,5 +69,6 @@ public class ClientRetryTest extends ClientBase {
zk.close();
}
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/ClientSSLTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/ClientSSLTest.java
index 7902ea40f..1d3233fe6 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/ClientSSLTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/ClientSSLTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -19,9 +19,10 @@
/**
*
*/
-package org.apache.zookeeper.test;
+package org.apache.zookeeper.test;
+import static org.junit.Assert.assertTrue;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.PortAssignment;
import org.apache.zookeeper.ZooDefs;
@@ -32,7 +33,6 @@ import org.apache.zookeeper.server.NettyServerCnxnFactory;
import org.apache.zookeeper.server.ServerCnxnFactory;
import org.apache.zookeeper.server.quorum.QuorumPeerTestBase;
import org.junit.After;
-import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
@@ -95,19 +95,17 @@ public class ClientSSLTest extends QuorumPeerTestBase {
public void testClientServerSSL(boolean useSecurePort) throws Exception {
final int SERVER_COUNT = 3;
- final int clientPorts[] = new int[SERVER_COUNT];
- final Integer secureClientPorts[] = new Integer[SERVER_COUNT];
+ final int[] clientPorts = new int[SERVER_COUNT];
+ final Integer[] secureClientPorts = new Integer[SERVER_COUNT];
StringBuilder sb = new StringBuilder();
for (int i = 0; i < SERVER_COUNT; i++) {
clientPorts[i] = PortAssignment.unique();
secureClientPorts[i] = PortAssignment.unique();
- String server = String.format("server.%d=127.0.0.1:%d:%d:participant;127.0.0.1:%d%n",
- i, PortAssignment.unique(), PortAssignment.unique(), clientPorts[i]);
+ String server = String.format("server.%d=127.0.0.1:%d:%d:participant;127.0.0.1:%d%n", i, PortAssignment.unique(), PortAssignment.unique(), clientPorts[i]);
sb.append(server);
}
String quorumCfg = sb.toString();
-
MainThread[] mt = new MainThread[SERVER_COUNT];
for (int i = 0; i < SERVER_COUNT; i++) {
if (useSecurePort) {
@@ -124,7 +122,8 @@ public class ClientSSLTest extends QuorumPeerTestBase {
// Servers have been set up. Now go test if secure connection is successful.
for (int i = 0; i < SERVER_COUNT; i++) {
- Assert.assertTrue("waiting for server " + i + " being up",
+ assertTrue(
+ "waiting for server " + i + " being up",
ClientBase.waitForServerUp("127.0.0.1:" + clientPorts[i], TIMEOUT));
final int port = useSecurePort ? secureClientPorts[i] : clientPorts[i];
ZooKeeper zk = ClientBase.createZKClient("127.0.0.1:" + port, TIMEOUT);
@@ -139,7 +138,6 @@ public class ClientSSLTest extends QuorumPeerTestBase {
}
}
-
/**
* Developers might use standalone mode (which is the default for one server).
* This test checks SSL works in standalone mode of ZK server.
@@ -158,4 +156,5 @@ public class ClientSSLTest extends QuorumPeerTestBase {
zk.close();
mt.shutdown();
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/ClientSkipACLTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/ClientSkipACLTest.java
index 2c57ff7a4..d9b8cdddd 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/ClientSkipACLTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/ClientSkipACLTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -22,13 +22,15 @@ import org.junit.AfterClass;
import org.junit.BeforeClass;
public class ClientSkipACLTest extends ClientTest {
+
@BeforeClass
- static public void setup() {
+ public static void setup() {
System.setProperty("zookeeper.skipACL", "yes");
}
@AfterClass
- static public void teardown() {
+ public static void teardown() {
System.clearProperty("zookeeper.skipACL");
}
-} \ No newline at end of file
+
+}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/ClientTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/ClientTest.java
index abff8e1da..3fe2f5d5e 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/ClientTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/ClientTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,6 +18,12 @@
package org.apache.zookeeper.test;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNotSame;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
@@ -25,7 +31,6 @@ import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
-
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.zookeeper.AsyncCallback;
import org.apache.zookeeper.CreateMode;
@@ -49,13 +54,12 @@ import org.apache.zookeeper.proto.ReplyHeader;
import org.apache.zookeeper.proto.RequestHeader;
import org.apache.zookeeper.server.PrepRequestProcessor;
import org.apache.zookeeper.server.util.OSMXBean;
-import static org.apache.zookeeper.test.ClientBase.CONNECTION_TIMEOUT;
-import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ClientTest extends ClientBase {
+
protected static final Logger LOG = LoggerFactory.getLogger(ClientTest.class);
private boolean skipACL = System.getProperty("zookeeper.skipACL", "no").equals("yes");
@@ -71,8 +75,7 @@ public class ClientTest extends ClientBase {
zkWatchCreator = createClient();
for (int i = 0; i < 10; i++) {
- zkWatchCreator.create("/" + i, new byte[0], Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zkWatchCreator.create("/" + i, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
}
for (int i = 0; i < 10; i++) {
zkIdle.exists("/" + i, true);
@@ -94,16 +97,12 @@ public class ClientTest extends ClientBase {
}
@Test
- public void testClientwithoutWatcherObj() throws IOException,
- InterruptedException, KeeperException
- {
+ public void testClientwithoutWatcherObj() throws IOException, InterruptedException, KeeperException {
performClientTest(false);
}
@Test
- public void testClientWithWatcherObj() throws IOException,
- InterruptedException, KeeperException
- {
+ public void testClientWithWatcherObj() throws IOException, InterruptedException, KeeperException {
performClientTest(true);
}
@@ -112,14 +111,14 @@ public class ClientTest extends ClientBase {
public void testTestability() throws Exception {
TestableZooKeeper zk = createClient();
try {
- LOG.info("{}",zk.testableLocalSocketAddress());
- LOG.info("{}",zk.testableRemoteSocketAddress());
- LOG.info("{}",zk.toString());
+ LOG.info("{}", zk.testableLocalSocketAddress());
+ LOG.info("{}", zk.testableRemoteSocketAddress());
+ LOG.info("{}", zk.toString());
} finally {
zk.close(CONNECTION_TIMEOUT);
- LOG.info("{}",zk.testableLocalSocketAddress());
- LOG.info("{}",zk.testableRemoteSocketAddress());
- LOG.info("{}",zk.toString());
+ LOG.info("{}", zk.testableLocalSocketAddress());
+ LOG.info("{}", zk.testableRemoteSocketAddress());
+ LOG.info("{}", zk.toString());
}
}
@@ -130,33 +129,30 @@ public class ClientTest extends ClientBase {
zk = createClient();
try {
zk.create("/acltest", new byte[0], Ids.CREATOR_ALL_ACL, CreateMode.PERSISTENT);
- Assert.fail("Should have received an invalid acl error");
- } catch(InvalidACLException e) {
- LOG.info("Test successful, invalid acl received : "
- + e.getMessage());
+ fail("Should have received an invalid acl error");
+ } catch (InvalidACLException e) {
+ LOG.info("Test successful, invalid acl received : " + e.getMessage());
}
try {
ArrayList<ACL> testACL = new ArrayList<ACL>();
testACL.add(new ACL(Perms.ALL | Perms.ADMIN, Ids.AUTH_IDS));
testACL.add(new ACL(Perms.ALL | Perms.ADMIN, new Id("ip", "127.0.0.1/8")));
zk.create("/acltest", new byte[0], testACL, CreateMode.PERSISTENT);
- Assert.fail("Should have received an invalid acl error");
- } catch(InvalidACLException e) {
- LOG.info("Test successful, invalid acl received : "
- + e.getMessage());
+ fail("Should have received an invalid acl error");
+ } catch (InvalidACLException e) {
+ LOG.info("Test successful, invalid acl received : " + e.getMessage());
}
try {
ArrayList<ACL> testACL = new ArrayList<ACL>();
testACL.add(new ACL(Perms.ALL | Perms.ADMIN, new Id()));
zk.create("/nullidtest", new byte[0], testACL, CreateMode.PERSISTENT);
- Assert.fail("Should have received an invalid acl error");
- } catch(InvalidACLException e) {
- LOG.info("Test successful, invalid acl received : "
- + e.getMessage());
+ fail("Should have received an invalid acl error");
+ } catch (InvalidACLException e) {
+ LOG.info("Test successful, invalid acl received : " + e.getMessage());
}
zk.addAuthInfo("digest", "ben:passwd".getBytes());
ArrayList<ACL> testACL = new ArrayList<ACL>();
- testACL.add(new ACL(Perms.ALL, new Id("auth","")));
+ testACL.add(new ACL(Perms.ALL, new Id("auth", "")));
testACL.add(new ACL(Perms.WRITE, new Id("ip", "127.0.0.1")));
zk.create("/acltest", new byte[0], testACL, CreateMode.PERSISTENT);
zk.close();
@@ -166,14 +162,14 @@ public class ClientTest extends ClientBase {
try {
zk.getData("/acltest", false, null);
} catch (KeeperException e) {
- Assert.fail("Badauth reads should succeed with skipACL.");
+ fail("Badauth reads should succeed with skipACL.");
}
} else {
try {
zk.getData("/acltest", false, null);
- Assert.fail("Should have received a permission error");
+ fail("Should have received a permission error");
} catch (KeeperException e) {
- Assert.assertEquals(Code.NOAUTH, e.code());
+ assertEquals(Code.NOAUTH, e.code());
}
}
zk.addAuthInfo("digest", "ben:passwd".getBytes());
@@ -183,13 +179,13 @@ public class ClientTest extends ClientBase {
zk = createClient();
zk.getData("/acltest", false, null);
List<ACL> acls = zk.getACL("/acltest", new Stat());
- Assert.assertEquals(1, acls.size());
- Assert.assertEquals(Ids.OPEN_ACL_UNSAFE, acls);
+ assertEquals(1, acls.size());
+ assertEquals(Ids.OPEN_ACL_UNSAFE, acls);
// The stat parameter should be optional.
acls = zk.getACL("/acltest", null);
- Assert.assertEquals(1, acls.size());
- Assert.assertEquals(Ids.OPEN_ACL_UNSAFE, acls);
+ assertEquals(1, acls.size());
+ assertEquals(Ids.OPEN_ACL_UNSAFE, acls);
zk.close();
} finally {
@@ -215,14 +211,14 @@ public class ClientTest extends ClientBase {
try {
zk.getData("/acltest", false, null);
} catch (KeeperException e) {
- Assert.fail("Badauth reads should succeed with skipACL.");
+ fail("Badauth reads should succeed with skipACL.");
}
} else {
try {
zk.getData("/acltest", false, null);
- Assert.fail("Should have received a permission error");
+ fail("Should have received a permission error");
} catch (KeeperException e) {
- Assert.assertEquals(Code.NOAUTH, e.code());
+ assertEquals(Code.NOAUTH, e.code());
}
}
zk.addAuthInfo("digest", "ben:passwd".getBytes());
@@ -232,8 +228,8 @@ public class ClientTest extends ClientBase {
zk = createClient();
zk.getData("/acltest", false, null);
List<ACL> acls = zk.getACL("/acltest", new Stat());
- Assert.assertEquals(1, acls.size());
- Assert.assertEquals(Ids.OPEN_ACL_UNSAFE, acls);
+ assertEquals(1, acls.size());
+ assertEquals(Ids.OPEN_ACL_UNSAFE, acls);
} finally {
if (zk != null) {
zk.close();
@@ -242,8 +238,8 @@ public class ClientTest extends ClientBase {
}
private class MyWatcher extends CountdownWatcher {
- LinkedBlockingQueue<WatchedEvent> events =
- new LinkedBlockingQueue<WatchedEvent>();
+
+ LinkedBlockingQueue<WatchedEvent> events = new LinkedBlockingQueue<WatchedEvent>();
public void process(WatchedEvent event) {
super.process(event);
@@ -255,6 +251,7 @@ public class ClientTest extends ClientBase {
}
}
}
+
}
/**
@@ -262,18 +259,15 @@ public class ClientTest extends ClientBase {
* in the right order.
*/
@Test
- public void testMutipleWatcherObjs()
- throws IOException, InterruptedException, KeeperException
- {
+ public void testMutipleWatcherObjs() throws IOException, InterruptedException, KeeperException {
ZooKeeper zk = createClient(new CountdownWatcher(), hostPort);
try {
- MyWatcher watchers[] = new MyWatcher[100];
- MyWatcher watchers2[] = new MyWatcher[watchers.length];
+ MyWatcher[] watchers = new MyWatcher[100];
+ MyWatcher[] watchers2 = new MyWatcher[watchers.length];
for (int i = 0; i < watchers.length; i++) {
watchers[i] = new MyWatcher();
watchers2[i] = new MyWatcher();
- zk.create("/foo-" + i, ("foodata" + i).getBytes(),
- Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
+ zk.create("/foo-" + i, ("foodata" + i).getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
}
Stat stat = new Stat();
@@ -282,10 +276,10 @@ public class ClientTest extends ClientBase {
// get all, then exists all
//
for (int i = 0; i < watchers.length; i++) {
- Assert.assertNotNull(zk.getData("/foo-" + i, watchers[i], stat));
+ assertNotNull(zk.getData("/foo-" + i, watchers[i], stat));
}
for (int i = 0; i < watchers.length; i++) {
- Assert.assertNotNull(zk.exists("/foo-" + i, watchers[i]));
+ assertNotNull(zk.exists("/foo-" + i, watchers[i]));
}
// trigger the watches
for (int i = 0; i < watchers.length; i++) {
@@ -293,16 +287,15 @@ public class ClientTest extends ClientBase {
zk.setData("/foo-" + i, ("foodata3-" + i).getBytes(), -1);
}
for (int i = 0; i < watchers.length; i++) {
- WatchedEvent event =
- watchers[i].events.poll(10, TimeUnit.SECONDS);
- Assert.assertEquals("/foo-" + i, event.getPath());
- Assert.assertEquals(EventType.NodeDataChanged, event.getType());
- Assert.assertEquals(KeeperState.SyncConnected, event.getState());
+ WatchedEvent event = watchers[i].events.poll(10, TimeUnit.SECONDS);
+ assertEquals("/foo-" + i, event.getPath());
+ assertEquals(EventType.NodeDataChanged, event.getType());
+ assertEquals(KeeperState.SyncConnected, event.getState());
// small chance that an unexpected message was delivered
// after this check, but we would catch that next time
// we check events
- Assert.assertEquals(0, watchers[i].events.size());
+ assertEquals(0, watchers[i].events.size());
}
//
@@ -310,8 +303,8 @@ public class ClientTest extends ClientBase {
// get/exists together
//
for (int i = 0; i < watchers.length; i++) {
- Assert.assertNotNull(zk.getData("/foo-" + i, watchers[i], stat));
- Assert.assertNotNull(zk.exists("/foo-" + i, watchers[i]));
+ assertNotNull(zk.getData("/foo-" + i, watchers[i], stat));
+ assertNotNull(zk.exists("/foo-" + i, watchers[i]));
}
// trigger the watches
for (int i = 0; i < watchers.length; i++) {
@@ -319,24 +312,23 @@ public class ClientTest extends ClientBase {
zk.setData("/foo-" + i, ("foodata5-" + i).getBytes(), -1);
}
for (int i = 0; i < watchers.length; i++) {
- WatchedEvent event =
- watchers[i].events.poll(10, TimeUnit.SECONDS);
- Assert.assertEquals("/foo-" + i, event.getPath());
- Assert.assertEquals(EventType.NodeDataChanged, event.getType());
- Assert.assertEquals(KeeperState.SyncConnected, event.getState());
+ WatchedEvent event = watchers[i].events.poll(10, TimeUnit.SECONDS);
+ assertEquals("/foo-" + i, event.getPath());
+ assertEquals(EventType.NodeDataChanged, event.getType());
+ assertEquals(KeeperState.SyncConnected, event.getState());
// small chance that an unexpected message was delivered
// after this check, but we would catch that next time
// we check events
- Assert.assertEquals(0, watchers[i].events.size());
+ assertEquals(0, watchers[i].events.size());
}
//
// test get/exists with two sets of watchers
//
for (int i = 0; i < watchers.length; i++) {
- Assert.assertNotNull(zk.getData("/foo-" + i, watchers[i], stat));
- Assert.assertNotNull(zk.exists("/foo-" + i, watchers2[i]));
+ assertNotNull(zk.getData("/foo-" + i, watchers[i], stat));
+ assertNotNull(zk.exists("/foo-" + i, watchers2[i]));
}
// trigger the watches
for (int i = 0; i < watchers.length; i++) {
@@ -344,28 +336,26 @@ public class ClientTest extends ClientBase {
zk.setData("/foo-" + i, ("foodata7-" + i).getBytes(), -1);
}
for (int i = 0; i < watchers.length; i++) {
- WatchedEvent event =
- watchers[i].events.poll(10, TimeUnit.SECONDS);
- Assert.assertEquals("/foo-" + i, event.getPath());
- Assert.assertEquals(EventType.NodeDataChanged, event.getType());
- Assert.assertEquals(KeeperState.SyncConnected, event.getState());
+ WatchedEvent event = watchers[i].events.poll(10, TimeUnit.SECONDS);
+ assertEquals("/foo-" + i, event.getPath());
+ assertEquals(EventType.NodeDataChanged, event.getType());
+ assertEquals(KeeperState.SyncConnected, event.getState());
// small chance that an unexpected message was delivered
// after this check, but we would catch that next time
// we check events
- Assert.assertEquals(0, watchers[i].events.size());
+ assertEquals(0, watchers[i].events.size());
// watchers2
- WatchedEvent event2 =
- watchers2[i].events.poll(10, TimeUnit.SECONDS);
- Assert.assertEquals("/foo-" + i, event2.getPath());
- Assert.assertEquals(EventType.NodeDataChanged, event2.getType());
- Assert.assertEquals(KeeperState.SyncConnected, event2.getState());
+ WatchedEvent event2 = watchers2[i].events.poll(10, TimeUnit.SECONDS);
+ assertEquals("/foo-" + i, event2.getPath());
+ assertEquals(EventType.NodeDataChanged, event2.getType());
+ assertEquals(KeeperState.SyncConnected, event2.getState());
// small chance that an unexpected message was delivered
// after this check, but we would catch that next time
// we check events
- Assert.assertEquals(0, watchers2[i].events.size());
+ assertEquals(0, watchers2[i].events.size());
}
} finally {
@@ -375,24 +365,21 @@ public class ClientTest extends ClientBase {
}
}
- private void performClientTest(boolean withWatcherObj)
- throws IOException, InterruptedException, KeeperException
- {
+ private void performClientTest(boolean withWatcherObj) throws IOException, InterruptedException, KeeperException {
ZooKeeper zk = null;
try {
MyWatcher watcher = new MyWatcher();
zk = createClient(watcher, hostPort);
LOG.info("Before create /benwashere");
- zk.create("/benwashere", "".getBytes(), Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk.create("/benwashere", "".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
LOG.info("After create /benwashere");
try {
zk.setData("/benwashere", "hi".getBytes(), 57);
- Assert.fail("Should have gotten BadVersion exception");
- } catch(KeeperException.BadVersionException e) {
+ fail("Should have gotten BadVersion exception");
+ } catch (KeeperException.BadVersionException e) {
// expected that
} catch (KeeperException e) {
- Assert.fail("Should have gotten BadVersion exception");
+ fail("Should have gotten BadVersion exception");
}
LOG.info("Before delete /benwashere");
zk.delete("/benwashere", 0);
@@ -407,99 +394,92 @@ public class ClientTest extends ClientBase {
try {
zk.delete("/", -1);
- Assert.fail("deleted root!");
- } catch(KeeperException.BadArgumentsException e) {
+ fail("deleted root!");
+ } catch (KeeperException.BadArgumentsException e) {
// good, expected that
}
Stat stat = new Stat();
// Test basic create, ls, and getData
- zk.create("/pat", "Pat was here".getBytes(), Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk.create("/pat", "Pat was here".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
LOG.info("Before create /ben");
- zk.create("/pat/ben", "Ben was here".getBytes(),
- Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
+ zk.create("/pat/ben", "Ben was here".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
LOG.info("Before getChildren /pat");
List<String> children = zk.getChildren("/pat", false);
- Assert.assertEquals(1, children.size());
- Assert.assertEquals("ben", children.get(0));
+ assertEquals(1, children.size());
+ assertEquals("ben", children.get(0));
List<String> children2 = zk.getChildren("/pat", false, null);
- Assert.assertEquals(children, children2);
+ assertEquals(children, children2);
String value = new String(zk.getData("/pat/ben", false, stat));
- Assert.assertEquals("Ben was here", value);
+ assertEquals("Ben was here", value);
// Test stat and watch of non existent node
try {
if (withWatcherObj) {
- Assert.assertEquals(null, zk.exists("/frog", watcher));
+ assertEquals(null, zk.exists("/frog", watcher));
} else {
- Assert.assertEquals(null, zk.exists("/frog", true));
+ assertEquals(null, zk.exists("/frog", true));
}
LOG.info("Comment: asseting passed for frog setting /");
} catch (KeeperException.NoNodeException e) {
// OK, expected that
}
- zk.create("/frog", "hi".getBytes(), Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk.create("/frog", "hi".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
// the first poll is just a session delivery
- LOG.info("Comment: checking for events length "
- + watcher.events.size());
+ LOG.info("Comment: checking for events length " + watcher.events.size());
WatchedEvent event = watcher.events.poll(10, TimeUnit.SECONDS);
- Assert.assertEquals("/frog", event.getPath());
- Assert.assertEquals(EventType.NodeCreated, event.getType());
- Assert.assertEquals(KeeperState.SyncConnected, event.getState());
+ assertEquals("/frog", event.getPath());
+ assertEquals(EventType.NodeCreated, event.getType());
+ assertEquals(KeeperState.SyncConnected, event.getState());
// Test child watch and create with sequence
zk.getChildren("/pat/ben", true);
for (int i = 0; i < 10; i++) {
- zk.create("/pat/ben/" + i + "-", Integer.toString(i).getBytes(),
- Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL);
+ zk.create("/pat/ben/"
+ + i
+ + "-", Integer.toString(i).getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL);
}
children = zk.getChildren("/pat/ben", false);
Collections.sort(children);
- Assert.assertEquals(10, children.size());
+ assertEquals(10, children.size());
for (int i = 0; i < 10; i++) {
final String name = children.get(i);
- Assert.assertTrue("starts with -", name.startsWith(i + "-"));
- byte b[];
+ assertTrue("starts with -", name.startsWith(i + "-"));
+ byte[] b;
if (withWatcherObj) {
b = zk.getData("/pat/ben/" + name, watcher, stat);
} else {
b = zk.getData("/pat/ben/" + name, true, stat);
}
- Assert.assertEquals(Integer.toString(i), new String(b));
- zk.setData("/pat/ben/" + name, "new".getBytes(),
- stat.getVersion());
+ assertEquals(Integer.toString(i), new String(b));
+ zk.setData("/pat/ben/" + name, "new".getBytes(), stat.getVersion());
if (withWatcherObj) {
stat = zk.exists("/pat/ben/" + name, watcher);
} else {
- stat = zk.exists("/pat/ben/" + name, true);
+ stat = zk.exists("/pat/ben/" + name, true);
}
zk.delete("/pat/ben/" + name, stat.getVersion());
}
event = watcher.events.poll(10, TimeUnit.SECONDS);
- Assert.assertEquals("/pat/ben", event.getPath());
- Assert.assertEquals(EventType.NodeChildrenChanged, event.getType());
- Assert.assertEquals(KeeperState.SyncConnected, event.getState());
+ assertEquals("/pat/ben", event.getPath());
+ assertEquals(EventType.NodeChildrenChanged, event.getType());
+ assertEquals(KeeperState.SyncConnected, event.getState());
for (int i = 0; i < 10; i++) {
event = watcher.events.poll(10, TimeUnit.SECONDS);
final String name = children.get(i);
- Assert.assertEquals("/pat/ben/" + name, event.getPath());
- Assert.assertEquals(EventType.NodeDataChanged, event.getType());
- Assert.assertEquals(KeeperState.SyncConnected, event.getState());
+ assertEquals("/pat/ben/" + name, event.getPath());
+ assertEquals(EventType.NodeDataChanged, event.getType());
+ assertEquals(KeeperState.SyncConnected, event.getState());
event = watcher.events.poll(10, TimeUnit.SECONDS);
- Assert.assertEquals("/pat/ben/" + name, event.getPath());
- Assert.assertEquals(EventType.NodeDeleted, event.getType());
- Assert.assertEquals(KeeperState.SyncConnected, event.getState());
+ assertEquals("/pat/ben/" + name, event.getPath());
+ assertEquals(EventType.NodeDeleted, event.getType());
+ assertEquals(KeeperState.SyncConnected, event.getState());
}
- zk.create("/good\u0040path", "".getBytes(), Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk.create("/good\u0040path", "".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
- zk.create("/duplicate", "".getBytes(), Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk.create("/duplicate", "".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
try {
- zk.create("/duplicate", "".getBytes(), Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
- Assert.fail("duplicate create allowed");
- } catch(KeeperException.NodeExistsException e) {
+ zk.create("/duplicate", "".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
+ fail("duplicate create allowed");
+ } catch (KeeperException.NodeExistsException e) {
// OK, expected that
}
} finally {
@@ -508,13 +488,11 @@ public class ClientTest extends ClientBase {
}
}
}
-
+
// Test that sequential filenames are being created correctly,
// with 0-padding in the filename
@Test
- public void testSequentialNodeNames()
- throws IOException, InterruptedException, KeeperException
- {
+ public void testSequentialNodeNames() throws IOException, InterruptedException, KeeperException {
String path = "/SEQUENCE";
String file = "TEST";
String filepath = path + "/" + file;
@@ -525,69 +503,63 @@ public class ClientTest extends ClientBase {
zk.create(path, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
zk.create(filepath, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL);
List<String> children = zk.getChildren(path, false);
- Assert.assertEquals(1, children.size());
- Assert.assertEquals(file + "0000000000", children.get(0));
+ assertEquals(1, children.size());
+ assertEquals(file + "0000000000", children.get(0));
zk.create(filepath, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL);
children = zk.getChildren(path, false);
- Assert.assertEquals(2, children.size());
- Assert.assertTrue("contains child 1", children.contains(file + "0000000001"));
+ assertEquals(2, children.size());
+ assertTrue("contains child 1", children.contains(file + "0000000001"));
zk.create(filepath, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL);
children = zk.getChildren(path, false);
- Assert.assertEquals(3, children.size());
- Assert.assertTrue("contains child 2",
- children.contains(file + "0000000002"));
+ assertEquals(3, children.size());
+ assertTrue("contains child 2", children.contains(file + "0000000002"));
// The pattern is holding so far. Let's run the counter a bit
// to be sure it continues to spit out the correct answer
- for(int i = children.size(); i < 105; i++)
- zk.create(filepath, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL);
+ for (int i = children.size(); i < 105; i++) {
+ zk.create(filepath, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL);
+ }
children = zk.getChildren(path, false);
- Assert.assertTrue("contains child 104",
- children.contains(file + "0000000104"));
+ assertTrue("contains child 104", children.contains(file + "0000000104"));
- }
- finally {
- if(zk != null)
+ } finally {
+ if (zk != null) {
zk.close();
+ }
}
}
-
- // Test that data provided when
+
+ // Test that data provided when
// creating sequential nodes is stored properly
@Test
public void testSequentialNodeData() throws Exception {
- ZooKeeper zk= null;
+ ZooKeeper zk = null;
String queue_handle = "/queue";
try {
zk = createClient();
- zk.create(queue_handle, new byte[0], Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
- zk.create(queue_handle + "/element", "0".getBytes(),
- Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL);
- zk.create(queue_handle + "/element", "1".getBytes(),
- Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL);
+ zk.create(queue_handle, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
+ zk.create(queue_handle + "/element", "0".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL);
+ zk.create(queue_handle + "/element", "1".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL);
List<String> children = zk.getChildren(queue_handle, true);
- Assert.assertEquals(children.size(), 2);
+ assertEquals(children.size(), 2);
String child1 = children.get(0);
String child2 = children.get(1);
int compareResult = child1.compareTo(child2);
- Assert.assertNotSame(compareResult, 0);
+ assertNotSame(compareResult, 0);
if (compareResult < 0) {
} else {
String temp = child1;
child1 = child2;
child2 = temp;
}
- String child1data = new String(zk.getData(queue_handle
- + "/" + child1, false, null));
- String child2data = new String(zk.getData(queue_handle
- + "/" + child2, false, null));
- Assert.assertEquals(child1data, "0");
- Assert.assertEquals(child2data, "1");
+ String child1data = new String(zk.getData(queue_handle + "/" + child1, false, null));
+ String child2data = new String(zk.getData(queue_handle + "/" + child2, false, null));
+ assertEquals(child1data, "0");
+ assertEquals(child2data, "1");
} finally {
if (zk != null) {
zk.close();
@@ -598,13 +570,12 @@ public class ClientTest extends ClientBase {
@Test
public void testLargeNodeData() throws Exception {
- ZooKeeper zk= null;
+ ZooKeeper zk = null;
String queue_handle = "/large";
try {
zk = createClient();
- zk.create(queue_handle, new byte[500000], Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk.create(queue_handle, new byte[500000], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
} finally {
if (zk != null) {
zk.close();
@@ -620,7 +591,7 @@ public class ClientTest extends ClientBase {
// this is good
return;
}
- Assert.fail("bad path \"" + path + "\" not caught");
+ fail("bad path \"" + path + "\" not caught");
}
// Test that the path string is validated
@@ -651,54 +622,45 @@ public class ClientTest extends ClientBase {
verifyCreateFails("foo", zk);
verifyCreateFails("a", zk);
- zk.create("/createseqpar", null, Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk.create("/createseqpar", null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
// next two steps - related to sequential processing
- // 1) verify that empty child name Assert.fails if not sequential
+ // 1) verify that empty child name fails if not sequential
try {
- zk.create("/createseqpar/", null, Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
- Assert.assertTrue(false);
- } catch(IllegalArgumentException be) {
+ zk.create("/createseqpar/", null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
+ assertTrue(false);
+ } catch (IllegalArgumentException be) {
// catch this.
}
- // 2) verify that empty child name success if sequential
- zk.create("/createseqpar/", null, Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT_SEQUENTIAL);
- zk.create("/createseqpar/.", null, Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT_SEQUENTIAL);
- zk.create("/createseqpar/..", null, Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT_SEQUENTIAL);
+ // 2) verify that empty child name success if sequential
+ zk.create("/createseqpar/", null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL);
+ zk.create("/createseqpar/.", null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL);
+ zk.create("/createseqpar/..", null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL);
try {
- zk.create("/createseqpar//", null, Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT_SEQUENTIAL);
- Assert.assertTrue(false);
- } catch(IllegalArgumentException be) {
+ zk.create("/createseqpar//", null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL);
+ assertTrue(false);
+ } catch (IllegalArgumentException be) {
// catch this.
}
try {
- zk.create("/createseqpar/./", null, Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT_SEQUENTIAL);
- Assert.assertTrue(false);
- } catch(IllegalArgumentException be) {
+ zk.create("/createseqpar/./", null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL);
+ assertTrue(false);
+ } catch (IllegalArgumentException be) {
// catch this.
}
try {
- zk.create("/createseqpar/../", null, Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT_SEQUENTIAL);
- Assert.assertTrue(false);
- } catch(IllegalArgumentException be) {
+ zk.create("/createseqpar/../", null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL);
+ assertTrue(false);
+ } catch (IllegalArgumentException be) {
// catch this.
}
-
//check for the code path that throws at server
PrepRequestProcessor.setFailCreate(true);
try {
zk.create("/m", null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
- Assert.assertTrue(false);
- } catch(KeeperException.BadArgumentsException be) {
+ assertTrue(false);
+ } catch (KeeperException.BadArgumentsException be) {
// catch this.
}
PrepRequestProcessor.setFailCreate(false);
@@ -717,20 +679,20 @@ public class ClientTest extends ClientBase {
zk.create("/f/f./f", null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
}
-// private void notestConnections()
-// throws IOException, InterruptedException, KeeperException
-// {
-// ZooKeeper zk;
-// for(int i = 0; i < 2000; i++) {
-// if (i % 100 == 0) {
-// LOG.info("Testing " + i + " connections");
-// }
-// // We want to make sure socket descriptors are going away
-// zk = new ZooKeeper(hostPort, 30000, this);
-// zk.getData("/", false, new Stat());
-// zk.close();
-// }
-// }
+ // private void notestConnections()
+ // throws IOException, InterruptedException, KeeperException
+ // {
+ // ZooKeeper zk;
+ // for(int i = 0; i < 2000; i++) {
+ // if (i % 100 == 0) {
+ // LOG.info("Testing " + i + " connections");
+ // }
+ // // We want to make sure socket descriptors are going away
+ // zk = new ZooKeeper(hostPort, 30000, this);
+ // zk.getData("/", false, new Stat());
+ // zk.close();
+ // }
+ // }
@Test
public void testDeleteWithChildren() throws Exception {
@@ -739,9 +701,9 @@ public class ClientTest extends ClientBase {
zk.create("/parent/child", new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
try {
zk.delete("/parent", -1);
- Assert.fail("Should have received a not equals message");
+ fail("Should have received a not equals message");
} catch (KeeperException e) {
- Assert.assertEquals(KeeperException.Code.NOTEMPTY, e.code());
+ assertEquals(KeeperException.Code.NOTEMPTY, e.code());
}
zk.delete("/parent/child", -1);
zk.delete("/parent", -1);
@@ -749,6 +711,7 @@ public class ClientTest extends ClientBase {
}
private class VerifyClientCleanup extends Thread {
+
int count;
int current = 0;
@@ -763,13 +726,14 @@ public class ClientTest extends ClientBase {
TestableZooKeeper zk = createClient();
// we've asked to close, wait for it to finish closing
// all the sub-threads otw the selector may not be
- // closed when we check (false positive on test Assert.failure
+ // closed when we check (false positive on test failure
zk.close(CONNECTION_TIMEOUT);
}
} catch (Throwable t) {
- LOG.error("test Assert.failed", t);
+ LOG.error("test failed", t);
}
}
+
}
/**
@@ -782,7 +746,7 @@ public class ClientTest extends ClientBase {
@Test
public void testClientCleanup() throws Throwable {
OSMXBean osMbean = new OSMXBean();
- if (osMbean.getUnix() == false) {
+ if (!osMbean.getUnix()) {
LOG.warn("skipping testClientCleanup, only available on Unix");
return;
}
@@ -797,7 +761,7 @@ public class ClientTest extends ClientBase {
*/
long initialFdCount = osMbean.getOpenFileDescriptorCount();
- VerifyClientCleanup threads[] = new VerifyClientCleanup[threadCount];
+ VerifyClientCleanup[] threads = new VerifyClientCleanup[threadCount];
for (int i = 0; i < threads.length; i++) {
threads[i] = new VerifyClientCleanup("VCC" + i, clientCount);
@@ -806,29 +770,28 @@ public class ClientTest extends ClientBase {
for (int i = 0; i < threads.length; i++) {
threads[i].join(CONNECTION_TIMEOUT);
- Assert.assertTrue(threads[i].current == threads[i].count);
+ assertTrue(threads[i].current == threads[i].count);
}
- // if this Assert.fails it means we are not cleaning up after the closed
+ // if this fails it means we are not cleaning up after the closed
// sessions.
long currentCount = osMbean.getOpenFileDescriptorCount();
final String logmsg = "open fds after test ({}) are not significantly higher than before ({})";
-
+
if (currentCount > initialFdCount + 10) {
// consider as error
- LOG.error(logmsg,Long.valueOf(currentCount),Long.valueOf(initialFdCount));
+ LOG.error(logmsg, Long.valueOf(currentCount), Long.valueOf(initialFdCount));
} else {
- LOG.info(logmsg,Long.valueOf(currentCount),Long.valueOf(initialFdCount));
+ LOG.info(logmsg, Long.valueOf(currentCount), Long.valueOf(initialFdCount));
}
}
-
/**
* We create a perfectly valid 'exists' request, except that the opcode is wrong.
* @throws Exception
*/
@Test
- public void testNonExistingOpCode() throws Exception {
+ public void testNonExistingOpCode() throws Exception {
final CountDownLatch clientDisconnected = new CountDownLatch(1);
Watcher watcher = new Watcher() {
@Override
@@ -851,11 +814,10 @@ public class ClientTest extends ClientBase {
ReplyHeader r = zk.submitRequest(h, request, response, null);
- Assert.assertEquals(r.getErr(), Code.UNIMPLEMENTED.intValue());
+ assertEquals(r.getErr(), Code.UNIMPLEMENTED.intValue());
// Sending a nonexisting opcode should cause the server to disconnect
- Assert.assertTrue("failed to disconnect",
- clientDisconnected.await(5000, TimeUnit.MILLISECONDS));
+ assertTrue("failed to disconnect", clientDisconnected.await(5000, TimeUnit.MILLISECONDS));
zk.close();
}
@@ -864,10 +826,10 @@ public class ClientTest extends ClientBase {
ZooKeeper zooKeeper;
try (ZooKeeper zk = createClient()) {
zooKeeper = zk;
- Assert.assertTrue(zooKeeper.getState().isAlive());
+ assertTrue(zooKeeper.getState().isAlive());
}
- Assert.assertFalse(zooKeeper.getState().isAlive());
+ assertFalse(zooKeeper.getState().isAlive());
}
@Test
@@ -877,29 +839,27 @@ public class ClientTest extends ClientBase {
zk = createClient();
zk.setXid(Integer.MAX_VALUE - 10);
- zk.create("/testnode", "".getBytes(), Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk.create("/testnode", "".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
for (int i = 0; i < 20; ++i) {
final CountDownLatch latch = new CountDownLatch(1);
final AtomicInteger rc = new AtomicInteger(0);
- zk.setData("/testnode", "".getBytes(), -1,
- new AsyncCallback.StatCallback() {
- @Override
- public void processResult(int retcode, String path, Object ctx, Stat stat) {
- rc.set(retcode);
- latch.countDown();
- }
- }, null);
- Assert.assertTrue("setData should complete within 5s",
- latch.await(zk.getSessionTimeout(), TimeUnit.MILLISECONDS));
- Assert.assertEquals("setData should have succeeded", Code.OK.intValue(), rc.get());
+ zk.setData("/testnode", "".getBytes(), -1, new AsyncCallback.StatCallback() {
+ @Override
+ public void processResult(int retcode, String path, Object ctx, Stat stat) {
+ rc.set(retcode);
+ latch.countDown();
+ }
+ }, null);
+ assertTrue("setData should complete within 5s", latch.await(zk.getSessionTimeout(), TimeUnit.MILLISECONDS));
+ assertEquals("setData should have succeeded", Code.OK.intValue(), rc.get());
}
zk.delete("/testnode", -1);
- Assert.assertTrue("xid should be positive", zk.checkXid() > 0);
+ assertTrue("xid should be positive", zk.checkXid() > 0);
} finally {
if (zk != null) {
zk.close();
}
}
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/ConnectStringParserTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/ConnectStringParserTest.java
index aa0df8672..066e0f358 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/ConnectStringParserTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/ConnectStringParserTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,73 +18,71 @@
package org.apache.zookeeper.test;
+import static org.junit.Assert.assertEquals;
import org.apache.zookeeper.ZKTestCase;
import org.apache.zookeeper.client.ConnectStringParser;
-import org.junit.Assert;
import org.junit.Test;
-public class ConnectStringParserTest extends ZKTestCase{
- private static final int DEFAULT_PORT = 2181;
-
+public class ConnectStringParserTest extends ZKTestCase {
+
+ private static final int DEFAULT_PORT = 2181;
+
@Test
- public void testSingleServerChrootPath(){
+ public void testSingleServerChrootPath() {
String chrootPath = "/hallo/welt";
String servers = "10.10.10.1";
- assertChrootPath(chrootPath,
- new ConnectStringParser(servers+chrootPath));
-
+ assertChrootPath(chrootPath, new ConnectStringParser(servers + chrootPath));
+
servers = "[2001:db8:1::242:ac11:2]";
- assertChrootPath(chrootPath,
- new ConnectStringParser(servers+chrootPath));
+ assertChrootPath(chrootPath, new ConnectStringParser(servers + chrootPath));
}
@Test
- public void testMultipleServersChrootPath(){
+ public void testMultipleServersChrootPath() {
String chrootPath = "/hallo/welt";
String servers = "10.10.10.1,10.10.10.2";
- assertChrootPath(chrootPath,
- new ConnectStringParser(servers+chrootPath));
-
+ assertChrootPath(chrootPath, new ConnectStringParser(servers + chrootPath));
+
servers = "[2001:db8:1::242:ac11:2]:2181,[2001:db8:85a3:8d3:1319:8a2e:370:7348]:5678";
- assertChrootPath(chrootPath,
- new ConnectStringParser(servers+chrootPath));
+ assertChrootPath(chrootPath, new ConnectStringParser(servers + chrootPath));
}
@Test
- public void testParseServersWithoutPort(){
+ public void testParseServersWithoutPort() {
String servers = "10.10.10.1,10.10.10.2";
ConnectStringParser parser = new ConnectStringParser(servers);
- Assert.assertEquals("10.10.10.1", parser.getServerAddresses().get(0).getHostString());
- Assert.assertEquals(DEFAULT_PORT, parser.getServerAddresses().get(0).getPort());
- Assert.assertEquals("10.10.10.2", parser.getServerAddresses().get(1).getHostString());
- Assert.assertEquals(DEFAULT_PORT, parser.getServerAddresses().get(1).getPort());
-
+ assertEquals("10.10.10.1", parser.getServerAddresses().get(0).getHostString());
+ assertEquals(DEFAULT_PORT, parser.getServerAddresses().get(0).getPort());
+ assertEquals("10.10.10.2", parser.getServerAddresses().get(1).getHostString());
+ assertEquals(DEFAULT_PORT, parser.getServerAddresses().get(1).getPort());
+
servers = "[2001:db8:1::242:ac11:2],[2001:db8:85a3:8d3:1319:8a2e:370:7348]";
parser = new ConnectStringParser(servers);
- Assert.assertEquals("2001:db8:1::242:ac11:2", parser.getServerAddresses().get(0).getHostString());
- Assert.assertEquals(DEFAULT_PORT, parser.getServerAddresses().get(0).getPort());
- Assert.assertEquals("2001:db8:85a3:8d3:1319:8a2e:370:7348", parser.getServerAddresses().get(1).getHostString());
- Assert.assertEquals(DEFAULT_PORT, parser.getServerAddresses().get(1).getPort());
+ assertEquals("2001:db8:1::242:ac11:2", parser.getServerAddresses().get(0).getHostString());
+ assertEquals(DEFAULT_PORT, parser.getServerAddresses().get(0).getPort());
+ assertEquals("2001:db8:85a3:8d3:1319:8a2e:370:7348", parser.getServerAddresses().get(1).getHostString());
+ assertEquals(DEFAULT_PORT, parser.getServerAddresses().get(1).getPort());
}
@Test
- public void testParseServersWithPort(){
+ public void testParseServersWithPort() {
String servers = "10.10.10.1:112,10.10.10.2:110";
ConnectStringParser parser = new ConnectStringParser(servers);
- Assert.assertEquals("10.10.10.1", parser.getServerAddresses().get(0).getHostString());
- Assert.assertEquals("10.10.10.2", parser.getServerAddresses().get(1).getHostString());
- Assert.assertEquals(112, parser.getServerAddresses().get(0).getPort());
- Assert.assertEquals(110, parser.getServerAddresses().get(1).getPort());
-
+ assertEquals("10.10.10.1", parser.getServerAddresses().get(0).getHostString());
+ assertEquals("10.10.10.2", parser.getServerAddresses().get(1).getHostString());
+ assertEquals(112, parser.getServerAddresses().get(0).getPort());
+ assertEquals(110, parser.getServerAddresses().get(1).getPort());
+
servers = "[2001:db8:1::242:ac11:2]:1234,[2001:db8:85a3:8d3:1319:8a2e:370:7348]:5678";
parser = new ConnectStringParser(servers);
- Assert.assertEquals("2001:db8:1::242:ac11:2", parser.getServerAddresses().get(0).getHostString());
- Assert.assertEquals("2001:db8:85a3:8d3:1319:8a2e:370:7348", parser.getServerAddresses().get(1).getHostString());
- Assert.assertEquals(1234, parser.getServerAddresses().get(0).getPort());
- Assert.assertEquals(5678, parser.getServerAddresses().get(1).getPort());
+ assertEquals("2001:db8:1::242:ac11:2", parser.getServerAddresses().get(0).getHostString());
+ assertEquals("2001:db8:85a3:8d3:1319:8a2e:370:7348", parser.getServerAddresses().get(1).getHostString());
+ assertEquals(1234, parser.getServerAddresses().get(0).getPort());
+ assertEquals(5678, parser.getServerAddresses().get(1).getPort());
}
- private void assertChrootPath(String expected, ConnectStringParser parser){
- Assert.assertEquals(expected, parser.getChrootPath());
+ private void assertChrootPath(String expected, ConnectStringParser parser) {
+ assertEquals(expected, parser.getChrootPath());
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/CreateModeTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/CreateModeTest.java
index fc61adff1..d2e908b58 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/CreateModeTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/CreateModeTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,57 +18,59 @@
package org.apache.zookeeper.test;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
import java.util.EnumSet;
-
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
-import org.apache.zookeeper.ZKTestCase;
import org.apache.zookeeper.KeeperException.Code;
-import org.junit.Assert;
+import org.apache.zookeeper.ZKTestCase;
import org.junit.Test;
public class CreateModeTest extends ZKTestCase {
-
+
@Test
public void testBasicCreateMode() {
CreateMode cm = CreateMode.PERSISTENT;
- Assert.assertEquals(cm.toFlag(), 0);
- Assert.assertFalse(cm.isEphemeral());
- Assert.assertFalse(cm.isSequential());
- Assert.assertFalse(cm.isContainer());
+ assertEquals(cm.toFlag(), 0);
+ assertFalse(cm.isEphemeral());
+ assertFalse(cm.isSequential());
+ assertFalse(cm.isContainer());
cm = CreateMode.EPHEMERAL;
- Assert.assertEquals(cm.toFlag(), 1);
- Assert.assertTrue(cm.isEphemeral());
- Assert.assertFalse(cm.isSequential());
- Assert.assertFalse(cm.isContainer());
+ assertEquals(cm.toFlag(), 1);
+ assertTrue(cm.isEphemeral());
+ assertFalse(cm.isSequential());
+ assertFalse(cm.isContainer());
cm = CreateMode.PERSISTENT_SEQUENTIAL;
- Assert.assertEquals(cm.toFlag(), 2);
- Assert.assertFalse(cm.isEphemeral());
- Assert.assertTrue(cm.isSequential());
- Assert.assertFalse(cm.isContainer());
+ assertEquals(cm.toFlag(), 2);
+ assertFalse(cm.isEphemeral());
+ assertTrue(cm.isSequential());
+ assertFalse(cm.isContainer());
cm = CreateMode.EPHEMERAL_SEQUENTIAL;
- Assert.assertEquals(cm.toFlag(), 3);
- Assert.assertTrue(cm.isEphemeral());
- Assert.assertTrue(cm.isSequential());
- Assert.assertFalse(cm.isContainer());
+ assertEquals(cm.toFlag(), 3);
+ assertTrue(cm.isEphemeral());
+ assertTrue(cm.isSequential());
+ assertFalse(cm.isContainer());
cm = CreateMode.CONTAINER;
- Assert.assertEquals(cm.toFlag(), 4);
- Assert.assertFalse(cm.isEphemeral());
- Assert.assertFalse(cm.isSequential());
- Assert.assertTrue(cm.isContainer());
+ assertEquals(cm.toFlag(), 4);
+ assertFalse(cm.isEphemeral());
+ assertFalse(cm.isSequential());
+ assertTrue(cm.isContainer());
}
-
+
@Test
public void testFlagConversion() throws KeeperException {
// Ensure we get the same value back after round trip conversion
EnumSet<CreateMode> allModes = EnumSet.allOf(CreateMode.class);
- for(CreateMode cm : allModes) {
- Assert.assertEquals(cm, CreateMode.fromFlag( cm.toFlag() ) );
+ for (CreateMode cm : allModes) {
+ assertEquals(cm, CreateMode.fromFlag(cm.toFlag()));
}
}
@@ -76,16 +78,17 @@ public class CreateModeTest extends ZKTestCase {
public void testInvalidFlagConversion() throws KeeperException {
try {
CreateMode.fromFlag(99);
- Assert.fail("Shouldn't be able to convert 99 to a CreateMode.");
- } catch(KeeperException ke) {
- Assert.assertEquals(Code.BADARGUMENTS, ke.code());
+ fail("Shouldn't be able to convert 99 to a CreateMode.");
+ } catch (KeeperException ke) {
+ assertEquals(Code.BADARGUMENTS, ke.code());
}
try {
CreateMode.fromFlag(-1);
- Assert.fail("Shouldn't be able to convert -1 to a CreateMode.");
- } catch(KeeperException ke) {
- Assert.assertEquals(Code.BADARGUMENTS, ke.code());
+ fail("Shouldn't be able to convert -1 to a CreateMode.");
+ } catch (KeeperException ke) {
+ assertEquals(Code.BADARGUMENTS, ke.code());
}
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/CreateTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/CreateTest.java
index 1b427a18a..a3d5ccf8c 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/CreateTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/CreateTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -15,101 +15,99 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
package org.apache.zookeeper.test;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
import java.io.IOException;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
-import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.ZooDefs.Ids;
+import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;
-import org.junit.Assert;
import org.junit.Test;
+
/**
* Test suite for validating the Create API.
*/
public class CreateTest extends ClientBase {
- private ZooKeeper zk;
-
- @Override
- public void setUp() throws Exception {
- super.setUp();
- zk = createClient();
- }
-
- @Override
- public void tearDown() throws Exception {
- super.tearDown();
- zk.close();
- }
-
- @Test
- public void testCreate()
- throws IOException, KeeperException, InterruptedException {
- createNoStatVerifyResult("/foo");
- createNoStatVerifyResult("/foo/child");
- }
-
- @Test
- public void testCreateWithStat()
- throws IOException, KeeperException, InterruptedException {
- String name = "/foo";
- Stat stat = createWithStatVerifyResult("/foo");
- Stat childStat = createWithStatVerifyResult("/foo/child");
- // Don't expect to get the same stats for different creates.
- Assert.assertFalse(stat.equals(childStat));
- }
-
- @Test
- public void testCreateWithNullStat()
- throws IOException, KeeperException, InterruptedException {
- String name = "/foo";
- Assert.assertNull(zk.exists(name, false));
-
- Stat stat = null;
- // If a null Stat object is passed the create should still
- // succeed, but no Stat info will be returned.
- String path = zk.create(name, name.getBytes(),
- Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT, stat);
- Assert.assertNull(stat);
- Assert.assertNotNull(zk.exists(name, false));
- }
-
- private void createNoStatVerifyResult(String newName)
- throws KeeperException, InterruptedException {
- Assert.assertNull("Node existed before created", zk.exists(newName, false));
- String path = zk.create(newName, newName.getBytes(),
- Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
- Assert.assertEquals(path, newName);
- Assert.assertNotNull("Node was not created as expected",
- zk.exists(newName, false));
- }
-
- private Stat createWithStatVerifyResult(String newName)
- throws KeeperException, InterruptedException {
- Assert.assertNull("Node existed before created", zk.exists(newName, false));
- Stat stat = new Stat();
- String path = zk.create(newName, newName.getBytes(),
- Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT, stat);
- Assert.assertEquals(path, newName);
- validateCreateStat(stat, newName);
-
- Stat referenceStat = zk.exists(newName, false);
- Assert.assertNotNull("Node was not created as expected", referenceStat);
- Assert.assertEquals(referenceStat, stat);
-
- return stat;
- }
-
- private void validateCreateStat(Stat stat, String name) {
- Assert.assertEquals(stat.getCzxid(), stat.getMzxid());
- Assert.assertEquals(stat.getCzxid(), stat.getPzxid());
- Assert.assertEquals(stat.getCtime(), stat.getMtime());
- Assert.assertEquals(0, stat.getCversion());
- Assert.assertEquals(0, stat.getVersion());
- Assert.assertEquals(0, stat.getAversion());
- Assert.assertEquals(0, stat.getEphemeralOwner());
- Assert.assertEquals(name.length(), stat.getDataLength());
- Assert.assertEquals(0, stat.getNumChildren());
- }
+
+ private ZooKeeper zk;
+
+ @Override
+ public void setUp() throws Exception {
+ super.setUp();
+ zk = createClient();
+ }
+
+ @Override
+ public void tearDown() throws Exception {
+ super.tearDown();
+ zk.close();
+ }
+
+ @Test
+ public void testCreate() throws IOException, KeeperException, InterruptedException {
+ createNoStatVerifyResult("/foo");
+ createNoStatVerifyResult("/foo/child");
+ }
+
+ @Test
+ public void testCreateWithStat() throws IOException, KeeperException, InterruptedException {
+ String name = "/foo";
+ Stat stat = createWithStatVerifyResult("/foo");
+ Stat childStat = createWithStatVerifyResult("/foo/child");
+ // Don't expect to get the same stats for different creates.
+ assertFalse(stat.equals(childStat));
+ }
+
+ @Test
+ public void testCreateWithNullStat() throws IOException, KeeperException, InterruptedException {
+ String name = "/foo";
+ assertNull(zk.exists(name, false));
+
+ Stat stat = null;
+ // If a null Stat object is passed the create should still
+ // succeed, but no Stat info will be returned.
+ String path = zk.create(name, name.getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT, stat);
+ assertNull(stat);
+ assertNotNull(zk.exists(name, false));
+ }
+
+ private void createNoStatVerifyResult(String newName) throws KeeperException, InterruptedException {
+ assertNull("Node existed before created", zk.exists(newName, false));
+ String path = zk.create(newName, newName.getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
+ assertEquals(path, newName);
+ assertNotNull("Node was not created as expected", zk.exists(newName, false));
+ }
+
+ private Stat createWithStatVerifyResult(String newName) throws KeeperException, InterruptedException {
+ assertNull("Node existed before created", zk.exists(newName, false));
+ Stat stat = new Stat();
+ String path = zk.create(newName, newName.getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT, stat);
+ assertEquals(path, newName);
+ validateCreateStat(stat, newName);
+
+ Stat referenceStat = zk.exists(newName, false);
+ assertNotNull("Node was not created as expected", referenceStat);
+ assertEquals(referenceStat, stat);
+
+ return stat;
+ }
+
+ private void validateCreateStat(Stat stat, String name) {
+ assertEquals(stat.getCzxid(), stat.getMzxid());
+ assertEquals(stat.getCzxid(), stat.getPzxid());
+ assertEquals(stat.getCtime(), stat.getMtime());
+ assertEquals(0, stat.getCversion());
+ assertEquals(0, stat.getVersion());
+ assertEquals(0, stat.getAversion());
+ assertEquals(0, stat.getEphemeralOwner());
+ assertEquals(name.length(), stat.getDataLength());
+ assertEquals(0, stat.getNumChildren());
+ }
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/DisconnectableZooKeeper.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/DisconnectableZooKeeper.java
index 619bdc68e..e429f2a77 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/DisconnectableZooKeeper.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/DisconnectableZooKeeper.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -19,21 +19,17 @@
package org.apache.zookeeper.test;
import java.io.IOException;
-
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
public class DisconnectableZooKeeper extends ZooKeeper {
- public DisconnectableZooKeeper(String host, int sessionTimeout, Watcher watcher)
- throws IOException
- {
+
+ public DisconnectableZooKeeper(String host, int sessionTimeout, Watcher watcher) throws IOException {
super(host, sessionTimeout, watcher);
}
-
- public DisconnectableZooKeeper(String host, int sessionTimeout, Watcher watcher,
- long sessionId, byte[] sessionPasswd)
- throws IOException
- {
+
+ public DisconnectableZooKeeper(
+ String host, int sessionTimeout, Watcher watcher, long sessionId, byte[] sessionPasswd) throws IOException {
super(host, sessionTimeout, watcher, sessionId, sessionPasswd);
}
@@ -55,4 +51,5 @@ public class DisconnectableZooKeeper extends ZooKeeper {
f.setAccessible(true);
f.setBoolean(cnxn, true);
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/DisconnectedWatcherTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/DisconnectedWatcherTest.java
index f459919ed..dcff76cca 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/DisconnectedWatcherTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/DisconnectedWatcherTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,30 +18,31 @@
package org.apache.zookeeper.test;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
-
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.WatchedEvent;
-import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.Watcher.Event.EventType;
import org.apache.zookeeper.ZooDefs.Ids;
+import org.apache.zookeeper.ZooKeeper;
import org.junit.After;
-import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class DisconnectedWatcherTest extends ClientBase {
+
protected static final Logger LOG = LoggerFactory.getLogger(DisconnectedWatcherTest.class);
final int TIMEOUT = 5000;
private class MyWatcher extends CountdownWatcher {
- LinkedBlockingQueue<WatchedEvent> events =
- new LinkedBlockingQueue<WatchedEvent>();
+
+ LinkedBlockingQueue<WatchedEvent> events = new LinkedBlockingQueue<WatchedEvent>();
public void process(WatchedEvent event) {
super.process(event);
@@ -53,6 +54,7 @@ public class DisconnectedWatcherTest extends ClientBase {
}
}
}
+
}
private CountdownWatcher watcher1;
@@ -80,30 +82,27 @@ public class DisconnectedWatcherTest extends ClientBase {
}
// @see jira issue ZOOKEEPER-961
-
+
@Test
public void testChildWatcherAutoResetWithChroot() throws Exception {
- zk1.create("/ch1", null, Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk1.create("/ch1", null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
zk2 = createClient(watcher2, hostPort + "/ch1");
- zk2.getChildren("/", true );
+ zk2.getChildren("/", true);
// this call shouldn't trigger any error or watch
- zk1.create("/youdontmatter1", null, Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk1.create("/youdontmatter1", null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
// this should trigger the watch
- zk1.create("/ch1/youshouldmatter1", null, Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk1.create("/ch1/youshouldmatter1", null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
WatchedEvent e = watcher2.events.poll(TIMEOUT, TimeUnit.MILLISECONDS);
- Assert.assertNotNull(e);
- Assert.assertEquals(EventType.NodeChildrenChanged, e.getType());
- Assert.assertEquals("/", e.getPath());
+ assertNotNull(e);
+ assertEquals(EventType.NodeChildrenChanged, e.getType());
+ assertEquals("/", e.getPath());
MyWatcher childWatcher = new MyWatcher();
zk2.getChildren("/", childWatcher);
-
+
stopServer();
watcher2.waitForDisconnected(3000);
startServer();
@@ -111,35 +110,31 @@ public class DisconnectedWatcherTest extends ClientBase {
watcher1.waitForConnected(3000);
// this should trigger the watch
- zk1.create("/ch1/youshouldmatter2", null, Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk1.create("/ch1/youshouldmatter2", null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
e = childWatcher.events.poll(TIMEOUT, TimeUnit.MILLISECONDS);
- Assert.assertNotNull(e);
- Assert.assertEquals(EventType.NodeChildrenChanged, e.getType());
- Assert.assertEquals("/", e.getPath());
+ assertNotNull(e);
+ assertEquals(EventType.NodeChildrenChanged, e.getType());
+ assertEquals("/", e.getPath());
}
-
+
@Test
public void testDefaultWatcherAutoResetWithChroot() throws Exception {
- zk1.create("/ch1", null, Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk1.create("/ch1", null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
zk2 = createClient(watcher2, hostPort + "/ch1");
- zk2.getChildren("/", true );
+ zk2.getChildren("/", true);
// this call shouldn't trigger any error or watch
- zk1.create("/youdontmatter1", null, Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk1.create("/youdontmatter1", null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
// this should trigger the watch
- zk1.create("/ch1/youshouldmatter1", null, Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk1.create("/ch1/youshouldmatter1", null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
WatchedEvent e = watcher2.events.poll(TIMEOUT, TimeUnit.MILLISECONDS);
- Assert.assertNotNull(e);
- Assert.assertEquals(EventType.NodeChildrenChanged, e.getType());
- Assert.assertEquals("/", e.getPath());
+ assertNotNull(e);
+ assertEquals(EventType.NodeChildrenChanged, e.getType());
+ assertEquals("/", e.getPath());
- zk2.getChildren("/", true );
+ zk2.getChildren("/", true);
stopServer();
watcher2.waitForDisconnected(3000);
@@ -148,39 +143,33 @@ public class DisconnectedWatcherTest extends ClientBase {
watcher1.waitForConnected(3000);
// this should trigger the watch
- zk1.create("/ch1/youshouldmatter2", null, Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk1.create("/ch1/youshouldmatter2", null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
e = watcher2.events.poll(TIMEOUT, TimeUnit.MILLISECONDS);
- Assert.assertNotNull(e);
- Assert.assertEquals(EventType.NodeChildrenChanged, e.getType());
- Assert.assertEquals("/", e.getPath());
+ assertNotNull(e);
+ assertEquals(EventType.NodeChildrenChanged, e.getType());
+ assertEquals("/", e.getPath());
}
-
+
@Test
public void testDeepChildWatcherAutoResetWithChroot() throws Exception {
- zk1.create("/ch1", null, Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
- zk1.create("/ch1/here", null, Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
- zk1.create("/ch1/here/we", null, Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
- zk1.create("/ch1/here/we/are", null, Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk1.create("/ch1", null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
+ zk1.create("/ch1/here", null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
+ zk1.create("/ch1/here/we", null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
+ zk1.create("/ch1/here/we/are", null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
zk2 = createClient(watcher2, hostPort + "/ch1/here/we");
- zk2.getChildren("/are", true );
+ zk2.getChildren("/are", true);
// this should trigger the watch
- zk1.create("/ch1/here/we/are/now", null, Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk1.create("/ch1/here/we/are/now", null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
WatchedEvent e = watcher2.events.poll(TIMEOUT, TimeUnit.MILLISECONDS);
- Assert.assertNotNull(e);
- Assert.assertEquals(EventType.NodeChildrenChanged, e.getType());
- Assert.assertEquals("/are", e.getPath());
+ assertNotNull(e);
+ assertEquals(EventType.NodeChildrenChanged, e.getType());
+ assertEquals("/are", e.getPath());
MyWatcher childWatcher = new MyWatcher();
zk2.getChildren("/are", childWatcher);
-
+
stopServer();
watcher2.waitForDisconnected(3000);
startServer();
@@ -188,12 +177,11 @@ public class DisconnectedWatcherTest extends ClientBase {
watcher1.waitForConnected(3000);
// this should trigger the watch
- zk1.create("/ch1/here/we/are/again", null, Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk1.create("/ch1/here/we/are/again", null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
e = childWatcher.events.poll(TIMEOUT, TimeUnit.MILLISECONDS);
- Assert.assertNotNull(e);
- Assert.assertEquals(EventType.NodeChildrenChanged, e.getType());
- Assert.assertEquals("/are", e.getPath());
+ assertNotNull(e);
+ assertEquals(EventType.NodeChildrenChanged, e.getType());
+ assertEquals("/are", e.getPath());
}
// @see jira issue ZOOKEEPER-706. Test auto reset of a large number of
@@ -204,7 +192,7 @@ public class DisconnectedWatcherTest extends ClientBase {
// 110 character base path
String pathBase = "/long-path-000000000-111111111-222222222-333333333-444444444-"
- + "555555555-666666666-777777777-888888888-999999999";
+ + "555555555-666666666-777777777-888888888-999999999";
zk1.create(pathBase, null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
@@ -212,8 +200,7 @@ public class DisconnectedWatcherTest extends ClientBase {
// watches set below exceeds 1MB.
List<String> paths = new ArrayList<String>();
for (int i = 0; i < 10000; i++) {
- String path = zk1.create(pathBase + "/ch-", null, Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT_SEQUENTIAL);
+ String path = zk1.create(pathBase + "/ch-", null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL);
paths.add(path);
}
LOG.info("Created 10,000 nodes.");
@@ -247,23 +234,23 @@ public class DisconnectedWatcherTest extends ClientBase {
zk1.create(path + "/ch", null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
WatchedEvent e = childWatcher.events.poll(TIMEOUT, TimeUnit.MILLISECONDS);
- Assert.assertNotNull(e);
- Assert.assertEquals(EventType.NodeChildrenChanged, e.getType());
- Assert.assertEquals(path, e.getPath());
+ assertNotNull(e);
+ assertEquals(EventType.NodeChildrenChanged, e.getType());
+ assertEquals(path, e.getPath());
} else if (i % 3 == 1) {
zk1.create(path + "/foo", null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
WatchedEvent e = childWatcher.events.poll(TIMEOUT, TimeUnit.MILLISECONDS);
- Assert.assertNotNull(e);
- Assert.assertEquals(EventType.NodeCreated, e.getType());
- Assert.assertEquals(path + "/foo", e.getPath());
+ assertNotNull(e);
+ assertEquals(EventType.NodeCreated, e.getType());
+ assertEquals(path + "/foo", e.getPath());
} else if (i % 3 == 2) {
zk1.setData(path, new byte[]{1, 2, 3}, -1);
WatchedEvent e = childWatcher.events.poll(TIMEOUT, TimeUnit.MILLISECONDS);
- Assert.assertNotNull(e);
- Assert.assertEquals(EventType.NodeDataChanged, e.getType());
- Assert.assertEquals(path, e.getPath());
+ assertNotNull(e);
+ assertEquals(EventType.NodeDataChanged, e.getType());
+ assertEquals(path, e.getPath());
}
i++;
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/DuplicateLocalSessionUpgradeTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/DuplicateLocalSessionUpgradeTest.java
index a21acdc20..d7639cce2 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/DuplicateLocalSessionUpgradeTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/DuplicateLocalSessionUpgradeTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,6 +18,9 @@
package org.apache.zookeeper.test;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.ZKTestCase;
import org.apache.zookeeper.ZooDefs;
@@ -25,7 +28,6 @@ import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;
import org.apache.zookeeper.test.ClientBase.CountdownWatcher;
import org.junit.After;
-import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
@@ -38,8 +40,8 @@ import org.slf4j.LoggerFactory;
* necessary.
*/
public class DuplicateLocalSessionUpgradeTest extends ZKTestCase {
- protected static final Logger LOG = LoggerFactory
- .getLogger(DuplicateLocalSessionUpgradeTest.class);
+
+ protected static final Logger LOG = LoggerFactory.getLogger(DuplicateLocalSessionUpgradeTest.class);
private final QuorumBase qb = new QuorumBase();
@@ -73,41 +75,39 @@ public class DuplicateLocalSessionUpgradeTest extends ZKTestCase {
private void testLocalSessionUpgrade(boolean testLeader) throws Exception {
int leaderIdx = qb.getLeaderIndex();
- Assert.assertFalse("No leader in quorum?", leaderIdx == -1);
+ assertFalse("No leader in quorum?", leaderIdx == -1);
int followerIdx = (leaderIdx + 1) % 5;
int testPeerIdx = testLeader ? leaderIdx : followerIdx;
- String hostPorts[] = qb.hostPort.split(",");
+ String[] hostPorts = qb.hostPort.split(",");
CountdownWatcher watcher = new CountdownWatcher();
- ZooKeeper zk = qb.createClient(watcher, hostPorts[testPeerIdx],
- CONNECTION_TIMEOUT);
+ ZooKeeper zk = qb.createClient(watcher, hostPorts[testPeerIdx], CONNECTION_TIMEOUT);
watcher.waitForConnected(CONNECTION_TIMEOUT);
final String firstPath = "/first";
final String secondPath = "/ephemeral";
// Just create some node so that we know the current zxid
- zk.create(firstPath, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk.create(firstPath, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
// Now, try an ephemeral node. This will trigger session upgrade
// so there will be createSession request inject into the pipeline
// prior to this request
- zk.create(secondPath, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE,
- CreateMode.EPHEMERAL);
+ zk.create(secondPath, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
Stat firstStat = zk.exists(firstPath, null);
- Assert.assertNotNull(firstStat);
+ assertNotNull(firstStat);
Stat secondStat = zk.exists(secondPath, null);
- Assert.assertNotNull(secondStat);
+ assertNotNull(secondStat);
long zxidDiff = secondStat.getCzxid() - firstStat.getCzxid();
// If there is only one createSession request in between, zxid diff
// will be exactly 2. The alternative way of checking is to actually
// read txnlog but this should be sufficient
- Assert.assertEquals(2L, zxidDiff);
+ assertEquals(2L, zxidDiff);
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/EmptiedSnapshotRecoveryTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/EmptiedSnapshotRecoveryTest.java
index 5b2f8a481..571636c60 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/EmptiedSnapshotRecoveryTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/EmptiedSnapshotRecoveryTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,33 +18,32 @@
package org.apache.zookeeper.test;
-import java.io.IOException;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
import java.io.File;
+import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
-import java.util.LinkedList;
-
import org.apache.log4j.Logger;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.PortAssignment;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZKTestCase;
-import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.ZooDefs.Ids;
-import org.apache.zookeeper.server.quorum.Leader.Proposal;
+import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.server.ServerCnxnFactory;
import org.apache.zookeeper.server.SyncRequestProcessor;
import org.apache.zookeeper.server.ZooKeeperServer;
import org.apache.zookeeper.server.persistence.FileTxnSnapLog;
-import org.junit.Assert;
import org.junit.Test;
-/** If snapshots are corrupted to the empty file or deleted, Zookeeper should
+/** If snapshots are corrupted to the empty file or deleted, Zookeeper should
* not proceed to read its transactiong log files
* Test that zxid == -1 in the presence of emptied/deleted snapshots
*/
-public class EmptiedSnapshotRecoveryTest extends ZKTestCase implements Watcher {
+public class EmptiedSnapshotRecoveryTest extends ZKTestCase implements Watcher {
+
private static final Logger LOG = Logger.getLogger(RestoreCommittedLogTest.class);
private static String HOSTPORT = "127.0.0.1:" + PortAssignment.unique();
private static final int CONNECTION_TIMEOUT = 3000;
@@ -53,44 +52,41 @@ public class EmptiedSnapshotRecoveryTest extends ZKTestCase implements Watcher
public void runTest(boolean leaveEmptyFile) throws Exception {
File tmpSnapDir = ClientBase.createTmpDir();
- File tmpLogDir = ClientBase.createTmpDir();
+ File tmpLogDir = ClientBase.createTmpDir();
ClientBase.setupTestEnv();
ZooKeeperServer zks = new ZooKeeperServer(tmpSnapDir, tmpLogDir, 3000);
SyncRequestProcessor.setSnapCount(SNAP_COUNT);
final int PORT = Integer.parseInt(HOSTPORT.split(":")[1]);
ServerCnxnFactory f = ServerCnxnFactory.createFactory(PORT, -1);
f.startup(zks);
- Assert.assertTrue("waiting for server being up ",
- ClientBase.waitForServerUp(HOSTPORT,CONNECTION_TIMEOUT));
+ assertTrue("waiting for server being up ", ClientBase.waitForServerUp(HOSTPORT, CONNECTION_TIMEOUT));
ZooKeeper zk = new ZooKeeper(HOSTPORT, CONNECTION_TIMEOUT, this);
try {
- for (int i = 0; i< N_TRANSACTIONS; i++) {
- zk.create("/node-" + i, new byte[0], Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ for (int i = 0; i < N_TRANSACTIONS; i++) {
+ zk.create("/node-" + i, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
}
} finally {
zk.close();
}
f.shutdown();
zks.shutdown();
- Assert.assertTrue("waiting for server to shutdown",
- ClientBase.waitForServerDown(HOSTPORT, CONNECTION_TIMEOUT));
+ assertTrue("waiting for server to shutdown", ClientBase.waitForServerDown(HOSTPORT, CONNECTION_TIMEOUT));
// start server again with intact database
zks = new ZooKeeperServer(tmpSnapDir, tmpLogDir, 3000);
zks.startdata();
long zxid = zks.getZKDatabase().getDataTreeLastProcessedZxid();
LOG.info("After clean restart, zxid = " + zxid);
- Assert.assertTrue("zxid > 0", zxid > 0);
+ assertTrue("zxid > 0", zxid > 0);
zks.shutdown();
// Make all snapshots empty
FileTxnSnapLog txnLogFactory = zks.getTxnLogFactory();
List<File> snapshots = txnLogFactory.findNRecentSnapshots(10);
- Assert.assertTrue("We have a snapshot to corrupt", snapshots.size() > 0);
- for (File file: snapshots) {
+ assertTrue("We have a snapshot to corrupt", snapshots.size() > 0);
+ for (File file : snapshots) {
if (leaveEmptyFile) {
- new PrintWriter(file).close ();
+ new PrintWriter(file).close();
} else {
file.delete();
}
@@ -101,10 +97,10 @@ public class EmptiedSnapshotRecoveryTest extends ZKTestCase implements Watcher
try {
zks.startdata();
zxid = zks.getZKDatabase().loadDataBase();
- Assert.fail("Should have gotten exception for corrupted database");
+ fail("Should have gotten exception for corrupted database");
} catch (IOException e) {
// expected behavior
- }
+ }
zks.shutdown();
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/EnsembleAuthTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/EnsembleAuthTest.java
index 6724573dc..dcd7ee6f1 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/EnsembleAuthTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/EnsembleAuthTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,6 +18,7 @@
package org.apache.zookeeper.test;
+import java.io.IOException;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.server.auth.EnsembleAuthenticationProvider;
@@ -26,8 +27,6 @@ import org.junit.After;
import org.junit.Before;
import org.junit.Test;
-import java.io.IOException;
-
public class EnsembleAuthTest extends ClientBase {
@Before
@@ -44,7 +43,6 @@ public class EnsembleAuthTest extends ClientBase {
ProviderRegistry.removeProvider("ensemble");
}
-
@Test
public void noAuth() throws Exception {
resetEnsembleAuth(null, false);
@@ -90,7 +88,6 @@ public class EnsembleAuthTest extends ClientBase {
connectToEnsemble("goo");
}
-
private void connectToEnsemble(final String auth) throws IOException, InterruptedException, KeeperException {
try (ZooKeeper zk = createClient()) {
// pass auth check
@@ -109,8 +106,7 @@ public class EnsembleAuthTest extends ClientBase {
System.setProperty(EnsembleAuthenticationProvider.ENSEMBLE_PROPERTY, auth);
}
if (useAuth) {
- System.setProperty("zookeeper.authProvider.1",
- "org.apache.zookeeper.server.auth.EnsembleAuthenticationProvider");
+ System.setProperty("zookeeper.authProvider.1", "org.apache.zookeeper.server.auth.EnsembleAuthenticationProvider");
} else {
System.clearProperty("zookeeper.authProvider.1");
}
@@ -118,4 +114,5 @@ public class EnsembleAuthTest extends ClientBase {
ProviderRegistry.initialize();
startServer();
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/EventTypeTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/EventTypeTest.java
index 0c96c839b..cf9807dd3 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/EventTypeTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/EventTypeTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,22 +18,22 @@
package org.apache.zookeeper.test;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.fail;
import java.util.EnumSet;
-
-import org.apache.zookeeper.ZKTestCase;
import org.apache.zookeeper.Watcher.Event.EventType;
-import org.junit.Assert;
+import org.apache.zookeeper.ZKTestCase;
import org.junit.Test;
public class EventTypeTest extends ZKTestCase {
-
+
@Test
public void testIntConversion() {
// Ensure that we can convert all valid integers to EventTypes
EnumSet<EventType> allTypes = EnumSet.allOf(EventType.class);
- for(EventType et : allTypes) {
- Assert.assertEquals(et, EventType.fromInt( et.getIntValue() ) );
+ for (EventType et : allTypes) {
+ assertEquals(et, EventType.fromInt(et.getIntValue()));
}
}
@@ -41,10 +41,11 @@ public class EventTypeTest extends ZKTestCase {
public void testInvalidIntConversion() {
try {
EventType.fromInt(324242);
- Assert.fail("Was able to create an invalid EventType via an integer");
- } catch(RuntimeException re) {
+ fail("Was able to create an invalid EventType via an integer");
+ } catch (RuntimeException re) {
// we're good.
}
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/FLENewEpochTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/FLENewEpochTest.java
index 2766c297d..7527757df 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/FLENewEpochTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/FLENewEpochTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,35 +18,34 @@
package org.apache.zookeeper.test;
+import static org.junit.Assert.fail;
import java.io.File;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.concurrent.Semaphore;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
import org.apache.zookeeper.PortAssignment;
import org.apache.zookeeper.ZKTestCase;
-import org.apache.zookeeper.server.quorum.FastLeaderElection;
import org.apache.zookeeper.server.quorum.QuorumPeer;
-import org.apache.zookeeper.server.quorum.Vote;
import org.apache.zookeeper.server.quorum.QuorumPeer.QuorumServer;
import org.apache.zookeeper.server.quorum.QuorumPeer.ServerState;
+import org.apache.zookeeper.server.quorum.Vote;
import org.junit.After;
-import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
public class FLENewEpochTest extends ZKTestCase {
+
protected static final Logger LOG = LoggerFactory.getLogger(FLENewEpochTest.class);
int count;
- HashMap<Long,QuorumServer> peers;
+ HashMap<Long, QuorumServer> peers;
ArrayList<LEThread> threads;
- File tmpdir[];
- int port[];
- volatile int [] round;
+ File[] tmpdir;
+ int[] port;
+ volatile int[] round;
Semaphore start0;
Semaphore finish3, finish0;
@@ -55,7 +54,7 @@ public class FLENewEpochTest extends ZKTestCase {
public void setUp() throws Exception {
count = 3;
- peers = new HashMap<Long,QuorumServer>(count);
+ peers = new HashMap<Long, QuorumServer>(count);
threads = new ArrayList<LEThread>(count);
tmpdir = new File[count];
port = new int[count];
@@ -72,13 +71,13 @@ public class FLENewEpochTest extends ZKTestCase {
@After
public void tearDown() throws Exception {
- for(int i = 0; i < threads.size(); i++) {
- ((FastLeaderElection) threads.get(i).peer.getElectionAlg()).shutdown();
+ for (int i = 0; i < threads.size(); i++) {
+ threads.get(i).peer.getElectionAlg().shutdown();
}
}
-
class LEThread extends Thread {
+
int i;
QuorumPeer peer;
@@ -89,17 +88,17 @@ public class FLENewEpochTest extends ZKTestCase {
}
- public void run(){
+ public void run() {
boolean flag = true;
- try{
- while(flag){
+ try {
+ while (flag) {
Vote v = null;
peer.setPeerState(ServerState.LOOKING);
LOG.info("Going to call leader election again: " + i);
v = peer.getElectionAlg().lookForLeader();
- if (v == null){
- Assert.fail("Thread " + i + " got a null vote");
+ if (v == null) {
+ fail("Thread " + i + " got a null vote");
}
/*
@@ -114,15 +113,15 @@ public class FLENewEpochTest extends ZKTestCase {
switch (i) {
case 0:
LOG.info("First peer, do nothing, just join");
- if(finish0.tryAcquire(1000, java.util.concurrent.TimeUnit.MILLISECONDS)){
- //if(threads.get(0).peer.getPeerState() == ServerState.LEADING ){
+ if (finish0.tryAcquire(1000, java.util.concurrent.TimeUnit.MILLISECONDS)) {
+ //if(threads.get(0).peer.getPeerState() == ServerState.LEADING ){
LOG.info("Setting flag to false");
flag = false;
}
break;
case 1:
LOG.info("Second entering case");
- if(round[1] != 0){
+ if (round[1] != 0) {
finish0.release();
flag = false;
} else {
@@ -146,48 +145,45 @@ public class FLENewEpochTest extends ZKTestCase {
e.printStackTrace();
}
}
+
}
+ @Test
+ public void testLENewEpoch() throws Exception {
+
+ LOG.info("TestLE: " + getTestName() + ", " + count);
+ for (int i = 0; i < count; i++) {
+ peers.put(Long.valueOf(i), new QuorumServer(i, new InetSocketAddress("127.0.0.1", PortAssignment.unique()), new InetSocketAddress("127.0.0.1", PortAssignment.unique())));
+ tmpdir[i] = ClientBase.createTmpDir();
+ port[i] = PortAssignment.unique();
+ }
+
+ for (int i = 1; i < count; i++) {
+ QuorumPeer peer = new QuorumPeer(peers, tmpdir[i], tmpdir[i], port[i], 3, i, 1000, 2, 2, 2);
+ peer.startLeaderElection();
+ LEThread thread = new LEThread(peer, i);
+ thread.start();
+ threads.add(thread);
+ }
+ if (!start0.tryAcquire(4000, java.util.concurrent.TimeUnit.MILLISECONDS)) {
+ fail("First leader election failed");
+ }
+
+ QuorumPeer peer = new QuorumPeer(peers, tmpdir[0], tmpdir[0], port[0], 3, 0, 1000, 2, 2, 2);
+ peer.startLeaderElection();
+ LEThread thread = new LEThread(peer, 0);
+ thread.start();
+ threads.add(thread);
+
+ LOG.info("Started threads " + getTestName());
+
+ for (int i = 0; i < threads.size(); i++) {
+ threads.get(i).join(10000);
+ if (threads.get(i).isAlive()) {
+ fail("Threads didn't join");
+ }
+
+ }
+ }
- @Test
- public void testLENewEpoch() throws Exception {
-
- LOG.info("TestLE: " + getTestName()+ ", " + count);
- for(int i = 0; i < count; i++) {
- peers.put(Long.valueOf(i),
- new QuorumServer(i,
- new InetSocketAddress(
- "127.0.0.1", PortAssignment.unique()),
- new InetSocketAddress(
- "127.0.0.1", PortAssignment.unique())));
- tmpdir[i] = ClientBase.createTmpDir();
- port[i] = PortAssignment.unique();
- }
-
- for(int i = 1; i < count; i++) {
- QuorumPeer peer = new QuorumPeer(peers, tmpdir[i], tmpdir[i], port[i], 3, i, 1000, 2, 2, 2);
- peer.startLeaderElection();
- LEThread thread = new LEThread(peer, i);
- thread.start();
- threads.add(thread);
- }
- if(!start0.tryAcquire(4000, java.util.concurrent.TimeUnit.MILLISECONDS))
- Assert.fail("First leader election failed");
-
- QuorumPeer peer = new QuorumPeer(peers, tmpdir[0], tmpdir[0], port[0], 3, 0, 1000, 2, 2, 2);
- peer.startLeaderElection();
- LEThread thread = new LEThread(peer, 0);
- thread.start();
- threads.add(thread);
-
- LOG.info("Started threads " + getTestName());
-
- for(int i = 0; i < threads.size(); i++) {
- threads.get(i).join(10000);
- if (threads.get(i).isAlive()) {
- Assert.fail("Threads didn't join");
- }
-
- }
- }
- }
+}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/FLEPredicateTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/FLEPredicateTest.java
index 4e252deb5..3fcb83bed 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/FLEPredicateTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/FLEPredicateTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -15,94 +15,89 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
package org.apache.zookeeper.test;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
import java.io.File;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.HashMap;
-
+import org.apache.zookeeper.PortAssignment;
+import org.apache.zookeeper.ZKTestCase;
import org.apache.zookeeper.server.quorum.FastLeaderElection;
-import org.apache.zookeeper.server.quorum.QuorumCnxManager;
import org.apache.zookeeper.server.quorum.QuorumPeer;
import org.apache.zookeeper.server.quorum.QuorumPeer.QuorumServer;
-import org.apache.zookeeper.PortAssignment;
-import org.apache.zookeeper.ZKTestCase;
-
+import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import org.junit.Assert;
-import org.junit.Test;
-
public class FLEPredicateTest extends ZKTestCase {
-
+
protected static final Logger LOG = LoggerFactory.getLogger(FLEPredicateTest.class);
-
+
class MockFLE extends FastLeaderElection {
- MockFLE(QuorumPeer peer){
+
+ MockFLE(QuorumPeer peer) {
super(peer, peer.createCnxnManager());
}
-
- boolean predicate(long newId, long newZxid, long newEpoch, long curId, long curZxid, long curEpoch){
+
+ boolean predicate(long newId, long newZxid, long newEpoch, long curId, long curZxid, long curEpoch) {
return this.totalOrderPredicate(newId, newZxid, newEpoch, curId, curZxid, curEpoch);
}
+
}
-
-
- HashMap<Long,QuorumServer> peers;
-
+
+ HashMap<Long, QuorumServer> peers;
+
@Test
public void testPredicate() throws IOException {
-
- peers = new HashMap<Long,QuorumServer>(3);
-
+
+ peers = new HashMap<Long, QuorumServer>(3);
+
/*
* Creates list of peers.
*/
- for(int i = 0; i < 3; i++) {
- peers.put(Long.valueOf(i),
- new QuorumServer(i,
- new InetSocketAddress(
- "127.0.0.1", PortAssignment.unique()),
- new InetSocketAddress(
- "127.0.0.1", PortAssignment.unique())));
+ for (int i = 0; i < 3; i++) {
+ peers.put(Long.valueOf(i), new QuorumServer(i, new InetSocketAddress("127.0.0.1", PortAssignment.unique()), new InetSocketAddress("127.0.0.1", PortAssignment.unique())));
}
/*
* Creating peer.
*/
- try{
+ try {
File tmpDir = ClientBase.createTmpDir();
- QuorumPeer peer = new QuorumPeer(peers, tmpDir, tmpDir,
- PortAssignment.unique(), 3, 0, 1000, 2, 2, 2);
-
+ QuorumPeer peer = new QuorumPeer(peers, tmpDir, tmpDir, PortAssignment.unique(), 3, 0, 1000, 2, 2, 2);
+
MockFLE mock = new MockFLE(peer);
mock.start();
-
+
/*
* Lower epoch must return false
*/
-
- Assert.assertFalse (mock.predicate(4L, 0L, 0L, 3L, 0L, 2L));
-
+
+ assertFalse(mock.predicate(4L, 0L, 0L, 3L, 0L, 2L));
+
/*
* Later epoch
*/
- Assert.assertTrue (mock.predicate(0L, 0L, 1L, 1L, 0L, 0L));
-
+ assertTrue(mock.predicate(0L, 0L, 1L, 1L, 0L, 0L));
+
/*
* Higher zxid
*/
- Assert.assertTrue(mock.predicate(0L, 1L, 0L, 1L, 0L, 0L));
-
+ assertTrue(mock.predicate(0L, 1L, 0L, 1L, 0L, 0L));
+
/*
* Higher id
*/
- Assert.assertTrue(mock.predicate(1L, 1L, 0L, 0L, 1L, 0L));
+ assertTrue(mock.predicate(1L, 1L, 0L, 0L, 1L, 0L));
} catch (IOException e) {
LOG.error("Exception while creating quorum peer", e);
- Assert.fail("Exception while creating quorum peer");
+ fail("Exception while creating quorum peer");
}
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/FLERestartTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/FLERestartTest.java
index f930391eb..5d8a917df 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/FLERestartTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/FLERestartTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,6 +18,7 @@
package org.apache.zookeeper.test;
+import static org.junit.Assert.fail;
import java.io.File;
import java.net.InetSocketAddress;
import java.util.ArrayList;
@@ -26,43 +27,45 @@ import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Semaphore;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
import org.apache.zookeeper.PortAssignment;
import org.apache.zookeeper.ZKTestCase;
-import org.apache.zookeeper.server.quorum.FastLeaderElection;
import org.apache.zookeeper.server.quorum.QuorumPeer;
-import org.apache.zookeeper.server.quorum.Vote;
import org.apache.zookeeper.server.quorum.QuorumPeer.QuorumServer;
import org.apache.zookeeper.server.quorum.QuorumPeer.ServerState;
+import org.apache.zookeeper.server.quorum.Vote;
import org.junit.After;
-import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
public class FLERestartTest extends ZKTestCase {
+
protected static final Logger LOG = LoggerFactory.getLogger(FLETest.class);
private int count;
- private Map<Long,QuorumServer> peers;
+ private Map<Long, QuorumServer> peers;
private List<FLERestartThread> restartThreads;
- private File tmpdir[];
- private int port[];
+ private File[] tmpdir;
+ private int[] port;
private Semaphore finish;
static class TestVote {
+
long leader;
TestVote(int id, long leader) {
this.leader = leader;
}
+
}
int countVotes(HashSet<TestVote> hs, long id) {
int counter = 0;
- for(TestVote v : hs){
- if(v.leader == id) counter++;
+ for (TestVote v : hs) {
+ if (v.leader == id) {
+ counter++;
+ }
}
return counter;
@@ -71,7 +74,7 @@ public class FLERestartTest extends ZKTestCase {
@Before
public void setUp() throws Exception {
count = 3;
- peers = new HashMap<Long,QuorumServer>(count);
+ peers = new HashMap<Long, QuorumServer>(count);
restartThreads = new ArrayList<FLERestartThread>(count);
tmpdir = new File[count];
port = new int[count];
@@ -80,12 +83,13 @@ public class FLERestartTest extends ZKTestCase {
@After
public void tearDown() throws Exception {
- for(int i = 0; i < restartThreads.size(); i++) {
- ((FastLeaderElection) restartThreads.get(i).peer.getElectionAlg()).shutdown();
+ for (int i = 0; i < restartThreads.size(); i++) {
+ restartThreads.get(i).peer.getElectionAlg().shutdown();
}
}
class FLERestartThread extends Thread {
+
int i;
QuorumPeer peer;
int peerRound = 0;
@@ -98,11 +102,11 @@ public class FLERestartTest extends ZKTestCase {
public void run() {
try {
Vote v = null;
- while(true) {
+ while (true) {
peer.setPeerState(ServerState.LOOKING);
LOG.info("Going to call leader election again.");
v = peer.getElectionAlg().lookForLeader();
- if(v == null){
+ if (v == null) {
LOG.info("Thread " + i + " got a null vote");
break;
}
@@ -116,12 +120,12 @@ public class FLERestartTest extends ZKTestCase {
LOG.info("Finished election: " + i + ", " + v.getId());
//votes[i] = v;
- switch(i){
+ switch (i) {
case 0:
- if(peerRound == 0){
+ if (peerRound == 0) {
LOG.info("First peer, shutting it down");
QuorumBase.shutdown(peer);
- ((FastLeaderElection) restartThreads.get(i).peer.getElectionAlg()).shutdown();
+ restartThreads.get(i).peer.getElectionAlg().shutdown();
peer = new QuorumPeer(peers, tmpdir[i], tmpdir[i], port[i], 3, i, 1000, 2, 2, 2);
peer.startLeaderElection();
@@ -148,29 +152,24 @@ public class FLERestartTest extends ZKTestCase {
return;
}
}
- } catch (Exception e){
+ } catch (Exception e) {
e.printStackTrace();
}
}
- }
+ }
@Test
public void testLERestart() throws Exception {
- LOG.info("TestLE: " + getTestName()+ ", " + count);
- for(int i = 0; i < count; i++) {
- peers.put(Long.valueOf(i),
- new QuorumServer(i,
- new InetSocketAddress(
- "127.0.0.1", PortAssignment.unique()),
- new InetSocketAddress(
- "127.0.0.1", PortAssignment.unique())));
+ LOG.info("TestLE: " + getTestName() + ", " + count);
+ for (int i = 0; i < count; i++) {
+ peers.put(Long.valueOf(i), new QuorumServer(i, new InetSocketAddress("127.0.0.1", PortAssignment.unique()), new InetSocketAddress("127.0.0.1", PortAssignment.unique())));
tmpdir[i] = ClientBase.createTmpDir();
port[i] = PortAssignment.unique();
}
- for(int i = 0; i < count; i++) {
+ for (int i = 0; i < count; i++) {
QuorumPeer peer = new QuorumPeer(peers, tmpdir[i], tmpdir[i], port[i], 3, i, 1000, 2, 2, 2);
peer.startLeaderElection();
FLERestartThread thread = new FLERestartThread(peer, i);
@@ -178,12 +177,13 @@ public class FLERestartTest extends ZKTestCase {
restartThreads.add(thread);
}
LOG.info("Started threads " + getTestName());
- for(int i = 0; i < restartThreads.size(); i++) {
+ for (int i = 0; i < restartThreads.size(); i++) {
restartThreads.get(i).join(10000);
if (restartThreads.get(i).isAlive()) {
- Assert.fail("Threads didn't join");
+ fail("Threads didn't join");
}
}
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/FLETest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/FLETest.java
index f6dc51321..c5ccf8d69 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/FLETest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/FLETest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,6 +18,10 @@
package org.apache.zookeeper.test;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
import java.io.File;
import java.net.InetSocketAddress;
import java.util.ArrayList;
@@ -27,65 +31,68 @@ import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
import org.apache.zookeeper.PortAssignment;
import org.apache.zookeeper.ZKTestCase;
import org.apache.zookeeper.server.quorum.FastLeaderElection;
import org.apache.zookeeper.server.quorum.QuorumPeer;
-import org.apache.zookeeper.server.quorum.Vote;
import org.apache.zookeeper.server.quorum.QuorumPeer.QuorumServer;
import org.apache.zookeeper.server.quorum.QuorumPeer.ServerState;
+import org.apache.zookeeper.server.quorum.Vote;
import org.junit.After;
-import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
public class FLETest extends ZKTestCase {
+
protected static final Logger LOG = LoggerFactory.getLogger(FLETest.class);
private final int MAX_LOOP_COUNTER = 300;
private FLETest.LEThread leThread;
static class TestVote {
+
TestVote(int id, long leader) {
this.leader = leader;
}
long leader;
+
}
int countVotes(HashSet<TestVote> hs, long id) {
int counter = 0;
- for(TestVote v : hs){
- if(v.leader == id) counter++;
+ for (TestVote v : hs) {
+ if (v.leader == id) {
+ counter++;
+ }
}
return counter;
}
int count;
- Map<Long,QuorumServer> peers;
+ Map<Long, QuorumServer> peers;
ArrayList<LEThread> threads;
- Map<Integer, HashSet<TestVote> > voteMap;
+ Map<Integer, HashSet<TestVote>> voteMap;
Map<Long, LEThread> quora;
- File tmpdir[];
- int port[];
+ File[] tmpdir;
+ int[] port;
int successCount;
- volatile Vote votes[];
+ volatile Vote[] votes;
volatile long leader = -1;
//volatile int round = 1;
Random rand = new Random();
Set<Long> joinedThreads;
-
+
@Before
public void setUp() throws Exception {
count = 7;
- peers = new HashMap<Long,QuorumServer>(count);
+ peers = new HashMap<Long, QuorumServer>(count);
threads = new ArrayList<LEThread>(count);
- voteMap = new HashMap<Integer, HashSet<TestVote> >();
+ voteMap = new HashMap<Integer, HashSet<TestVote>>();
votes = new Vote[count];
tmpdir = new File[count];
port = new int[count];
@@ -101,40 +108,40 @@ public class FLETest extends ZKTestCase {
}
}
-
/**
* Implements the behavior of a peer during the leader election rounds
* of tests.
*/
class LEThread extends Thread {
+
FLETest self;
int i;
QuorumPeer peer;
int totalRounds;
- ConcurrentHashMap<Long, HashSet<Integer> > quora;
+ ConcurrentHashMap<Long, HashSet<Integer>> quora;
- LEThread(FLETest self, QuorumPeer peer, int i, int rounds, ConcurrentHashMap<Long, HashSet<Integer> > quora) {
+ LEThread(FLETest self, QuorumPeer peer, int i, int rounds, ConcurrentHashMap<Long, HashSet<Integer>> quora) {
this.self = self;
this.i = i;
this.peer = peer;
this.totalRounds = rounds;
this.quora = quora;
-
+
LOG.info("Constructor: " + getName());
}
-
+
public void run() {
try {
Vote v = null;
- while(true) {
-
+ while (true) {
+
/*
* Set the state of the peer to LOOKING and look for leader
*/
peer.setPeerState(ServerState.LOOKING);
LOG.info("Going to call leader election again.");
v = peer.getElectionAlg().lookForLeader();
- if(v == null){
+ if (v == null) {
LOG.info("Thread " + i + " got a null vote");
break;
}
@@ -154,177 +161,161 @@ public class FLETest extends ZKTestCase {
* so that we know in which round this peer has executed.
*/
int lc = (int) ((FastLeaderElection) peer.getElectionAlg()).getLogicalClock();
-
+
/*
* The leader executes the following block, which essentially shuts down
- * the peer if it is not the last round.
+ * the peer if it is not the last round.
*/
if (v.getId() == i) {
LOG.info("I'm the leader: " + i);
if (lc < this.totalRounds) {
LOG.info("Leader " + i + " dying");
- FastLeaderElection election =
- (FastLeaderElection) peer.getElectionAlg();
+ FastLeaderElection election = (FastLeaderElection) peer.getElectionAlg();
election.shutdown();
// Make sure the vote is reset to -1 after shutdown.
- Assert.assertEquals(-1, election.getVote().getId());
+ assertEquals(-1, election.getVote().getId());
LOG.info("Leader " + i + " dead");
-
+
break;
- }
+ }
}
-
+
/*
* If the peer has done enough rounds, then consider joining. The thread
- * will only join if it is part of a quorum supporting the current
+ * will only join if it is part of a quorum supporting the current
* leader. Otherwise it will try again.
*/
if (lc >= this.totalRounds) {
/*
- * quora keeps the supporters of a given leader, so
+ * quora keeps the supporters of a given leader, so
* we first update it with the vote of this peer.
*/
- if(quora.get(v.getId()) == null) quora.put(v.getId(), new HashSet<Integer>());
+ if (quora.get(v.getId()) == null) {
+ quora.put(v.getId(), new HashSet<Integer>());
+ }
quora.get(v.getId()).add(i);
-
+
/*
* we now wait until a quorum supports the same leader.
*/
- if(waitForQuorum(v.getId())){
- synchronized(self){
-
+ if (waitForQuorum(v.getId())) {
+ synchronized (self) {
+
/*
* Assert that the state of the thread is the one expected.
*/
- if(v.getId() == i){
- Assert.assertTrue("Wrong state" + peer.getPeerState(),
- peer.getPeerState() == ServerState.LEADING);
+ if (v.getId() == i) {
+ assertTrue("Wrong state" + peer.getPeerState(), peer.getPeerState()
+ == ServerState.LEADING);
leader = i;
} else {
- Assert.assertTrue("Wrong state" + peer.getPeerState(),
- peer.getPeerState() == ServerState.FOLLOWING);
+ assertTrue("Wrong state" + peer.getPeerState(), peer.getPeerState()
+ == ServerState.FOLLOWING);
}
-
+
/*
- * Global variable keeping track of
- * how many peers have successfully
+ * Global variable keeping track of
+ * how many peers have successfully
* joined.
*/
successCount++;
- joinedThreads.add((long)i);
+ joinedThreads.add((long) i);
self.notify();
}
-
+
/*
- * I'm done so joining.
+ * I'm done so joining.
*/
break;
} else {
quora.get(v.getId()).remove(i);
}
- }
-
+ }
+
/*
* This sleep time represents the time a follower
* would take to declare the leader dead and start
* a new leader election.
*/
Thread.sleep(100);
-
+
}
LOG.debug("Thread " + i + " votes " + v);
} catch (InterruptedException e) {
- Assert.fail(e.toString());
+ fail(e.toString());
}
}
-
+
/**
* Auxiliary method to make sure that enough followers terminated.
- *
+ *
* @return boolean followers successfully joined.
*/
- boolean waitForQuorum(long id)
- throws InterruptedException {
+ boolean waitForQuorum(long id) throws InterruptedException {
int loopCounter = 0;
- while((quora.get(id).size() <= count/2) && (loopCounter < MAX_LOOP_COUNTER)){
+ while ((quora.get(id).size() <= count / 2) && (loopCounter < MAX_LOOP_COUNTER)) {
Thread.sleep(100);
loopCounter++;
}
-
- if((loopCounter >= MAX_LOOP_COUNTER) && (quora.get(id).size() <= count/2)){
- return false;
- } else {
- return true;
- }
+
+ return (loopCounter < MAX_LOOP_COUNTER) || (quora.get(id).size() > count / 2);
}
-
+
}
-
-
@Test
public void testSingleElection() throws Exception {
- try{
+ try {
runElection(1);
} catch (Exception e) {
- Assert.fail(e.toString());
+ fail(e.toString());
}
}
-
-
+
@Test
public void testDoubleElection() throws Exception {
- try{
+ try {
runElection(2);
} catch (Exception e) {
- Assert.fail(e.toString());
+ fail(e.toString());
}
}
-
+
@Test
public void testTripleElection() throws Exception {
- try{
+ try {
runElection(3);
} catch (Exception e) {
- Assert.fail(e.toString());
+ fail(e.toString());
}
}
/**
* Test leader election for a number of rounds. In all rounds but the last one
* we kill the leader.
- *
+ *
* @param rounds
* @throws Exception
*/
private void runElection(int rounds) throws Exception {
- ConcurrentHashMap<Long, HashSet<Integer> > quora =
- new ConcurrentHashMap<Long, HashSet<Integer> >();
+ ConcurrentHashMap<Long, HashSet<Integer>> quora = new ConcurrentHashMap<Long, HashSet<Integer>>();
- LOG.info("TestLE: " + getTestName()+ ", " + count);
+ LOG.info("TestLE: " + getTestName() + ", " + count);
/*
* Creates list of peers.
*/
- for(int i = 0; i < count; i++) {
+ for (int i = 0; i < count; i++) {
port[i] = PortAssignment.unique();
- peers.put(Long.valueOf(i),
- new QuorumServer(i,
- new InetSocketAddress(
- "127.0.0.1", PortAssignment.unique()),
- new InetSocketAddress(
- "127.0.0.1", PortAssignment.unique()),
- new InetSocketAddress(
- "127.0.0.1", port[i])));
- tmpdir[i] = ClientBase.createTmpDir();
+ peers.put(Long.valueOf(i), new QuorumServer(i, new InetSocketAddress("127.0.0.1", PortAssignment.unique()), new InetSocketAddress("127.0.0.1", PortAssignment.unique()), new InetSocketAddress("127.0.0.1", port[i])));
+ tmpdir[i] = ClientBase.createTmpDir();
}
/*
* Start one LEThread for each peer we want to run.
*/
- for(int i = 0; i < count; i++) {
- QuorumPeer peer = new QuorumPeer(peers, tmpdir[i], tmpdir[i],
- port[i], 3, i, 1000, 2, 2, 2);
+ for (int i = 0; i < count; i++) {
+ QuorumPeer peer = new QuorumPeer(peers, tmpdir[i], tmpdir[i], port[i], 3, i, 1000, 2, 2, 2);
peer.startLeaderElection();
LEThread thread = new LEThread(this, peer, i, rounds, quora);
thread.start();
@@ -333,10 +324,8 @@ public class FLETest extends ZKTestCase {
LOG.info("Started threads " + getTestName());
int waitCounter = 0;
- synchronized(this){
- while(((successCount <= count/2) || (leader == -1))
- && (waitCounter < MAX_LOOP_COUNTER))
- {
+ synchronized (this) {
+ while (((successCount <= count / 2) || (leader == -1)) && (waitCounter < MAX_LOOP_COUNTER)) {
this.wait(200);
waitCounter++;
}
@@ -344,38 +333,38 @@ public class FLETest extends ZKTestCase {
LOG.info("Success count: " + successCount);
/*
- * Lists what threads haven't joined. A thread doesn't join if
- * it hasn't decided upon a leader yet. It can happen that a
- * peer is slow or disconnected, and it can take longer to
- * nominate and connect to the current leader.
- */
- for (int i = 0; i < threads.size(); i++) {
+ * Lists what threads haven't joined. A thread doesn't join if
+ * it hasn't decided upon a leader yet. It can happen that a
+ * peer is slow or disconnected, and it can take longer to
+ * nominate and connect to the current leader.
+ */
+ for (int i = 0; i < threads.size(); i++) {
if (threads.get(i).isAlive()) {
LOG.info("Threads didn't join: " + i);
}
}
- /*
- * If we have a majority, then we are good to go.
- */
- if(successCount <= count/2){
- Assert.fail("Fewer than a a majority has joined");
- }
-
- /*
- * I'm done so joining.
- */
- if(!joinedThreads.contains(leader)){
- Assert.fail("Leader hasn't joined: " + leader);
- }
+ /*
+ * If we have a majority, then we are good to go.
+ */
+ if (successCount <= count / 2) {
+ fail("Fewer than a a majority has joined");
+ }
+
+ /*
+ * I'm done so joining.
+ */
+ if (!joinedThreads.contains(leader)) {
+ fail("Leader hasn't joined: " + leader);
+ }
}
-
-
+
/*
* Class to verify of the thread has become a follower
*/
static class VerifyState extends Thread {
- volatile private boolean success = false;
+
+ private volatile boolean success = false;
private QuorumPeer peer;
public VerifyState(QuorumPeer peer) {
this.peer = peer;
@@ -383,7 +372,7 @@ public class FLETest extends ZKTestCase {
public void run() {
setName("VerifyState-" + peer.getId());
while (true) {
- if(peer.getPeerState() == ServerState.FOLLOWING) {
+ if (peer.getPeerState() == ServerState.FOLLOWING) {
LOG.info("I am following");
success = true;
break;
@@ -402,6 +391,7 @@ public class FLETest extends ZKTestCase {
public boolean isSuccess() {
return success;
}
+
}
/*
@@ -414,22 +404,14 @@ public class FLETest extends ZKTestCase {
QuorumPeer peer;
int waitTime = 10 * 1000;
ArrayList<QuorumPeer> peerList = new ArrayList<QuorumPeer>();
- for(sid = 0; sid < 3; sid++) {
+ for (sid = 0; sid < 3; sid++) {
port[sid] = PortAssignment.unique();
- peers.put(Long.valueOf(sid),
- new QuorumServer(sid,
- new InetSocketAddress(
- "127.0.0.1", PortAssignment.unique()),
- new InetSocketAddress(
- "127.0.0.1", PortAssignment.unique()),
- new InetSocketAddress(
- "127.0.0.1", port[sid])));
- tmpdir[sid] = ClientBase.createTmpDir();
+ peers.put(Long.valueOf(sid), new QuorumServer(sid, new InetSocketAddress("127.0.0.1", PortAssignment.unique()), new InetSocketAddress("127.0.0.1", PortAssignment.unique()), new InetSocketAddress("127.0.0.1", port[sid])));
+ tmpdir[sid] = ClientBase.createTmpDir();
}
// start 2 peers and verify if they form the cluster
for (sid = 0; sid < 2; sid++) {
- peer = new QuorumPeer(peers, tmpdir[sid], tmpdir[sid],
- port[sid], 3, sid, 2000, 2, 2, 2);
+ peer = new QuorumPeer(peers, tmpdir[sid], tmpdir[sid], port[sid], 3, sid, 2000, 2, 2, 2);
LOG.info("Starting peer " + peer.getId());
peer.start();
peerList.add(sid, peer);
@@ -438,12 +420,9 @@ public class FLETest extends ZKTestCase {
VerifyState v1 = new VerifyState(peerList.get(0));
v1.start();
v1.join(waitTime);
- Assert.assertFalse("Unable to form cluster in " +
- waitTime + " ms",
- !v1.isSuccess());
+ assertFalse("Unable to form cluster in " + waitTime + " ms", !v1.isSuccess());
// Start 3rd peer and check if it goes in LEADING state
- peer = new QuorumPeer(peers, tmpdir[sid], tmpdir[sid],
- port[sid], 3, sid, 2000, 2, 2, 2);
+ peer = new QuorumPeer(peers, tmpdir[sid], tmpdir[sid], port[sid], 3, sid, 2000, 2, 2, 2);
LOG.info("Starting peer " + peer.getId());
peer.start();
peerList.add(sid, peer);
@@ -451,10 +430,9 @@ public class FLETest extends ZKTestCase {
v1.start();
v1.join(waitTime);
if (v1.isAlive()) {
- Assert.fail("Peer " + peer.getId() + " failed to join the cluster " +
- "within " + waitTime + " ms");
+ fail("Peer " + peer.getId() + " failed to join the cluster " + "within " + waitTime + " ms");
} else if (!v1.isSuccess()) {
- Assert.fail("Incorrect LEADING state for peer " + peer.getId());
+ fail("Incorrect LEADING state for peer " + peer.getId());
}
// cleanup
for (int id = 0; id < 3; id++) {
@@ -475,20 +453,14 @@ public class FLETest extends ZKTestCase {
QuorumPeer peer;
int waitTime = 10 * 1000;
ArrayList<QuorumPeer> peerList = new ArrayList<QuorumPeer>();
- for(sid = 0; sid < 3; sid++) {
- peers.put(Long.valueOf(sid),
- new QuorumServer(sid,
- new InetSocketAddress(
- "127.0.0.1", PortAssignment.unique()),
- new InetSocketAddress(
- "127.0.0.1", PortAssignment.unique())));
+ for (sid = 0; sid < 3; sid++) {
+ peers.put(Long.valueOf(sid), new QuorumServer(sid, new InetSocketAddress("127.0.0.1", PortAssignment.unique()), new InetSocketAddress("127.0.0.1", PortAssignment.unique())));
tmpdir[sid] = ClientBase.createTmpDir();
port[sid] = PortAssignment.unique();
}
// start 2 peers and verify if they form the cluster
for (sid = 0; sid < 2; sid++) {
- peer = new QuorumPeer(peers, tmpdir[sid], tmpdir[sid],
- port[sid], 3, sid, 2000, 2, 2, 2);
+ peer = new QuorumPeer(peers, tmpdir[sid], tmpdir[sid], port[sid], 3, sid, 2000, 2, 2, 2);
LOG.info("Starting peer " + peer.getId());
peer.start();
peerList.add(sid, peer);
@@ -497,20 +469,17 @@ public class FLETest extends ZKTestCase {
VerifyState v1 = new VerifyState(peerList.get(0));
v1.start();
v1.join(waitTime);
- Assert.assertFalse("Unable to form cluster in " +
- waitTime + " ms",
- !v1.isSuccess());
+ assertFalse("Unable to form cluster in " + waitTime + " ms", !v1.isSuccess());
// Change the election round for one of the members of the ensemble
long leaderSid = peer.getCurrentVote().getId();
long zxid = peer.getCurrentVote().getZxid();
long electionEpoch = peer.getCurrentVote().getElectionEpoch();
ServerState state = peer.getCurrentVote().getState();
long peerEpoch = peer.getCurrentVote().getPeerEpoch();
- Vote newVote = new Vote(leaderSid, zxid+100, electionEpoch+100, peerEpoch, state);
+ Vote newVote = new Vote(leaderSid, zxid + 100, electionEpoch + 100, peerEpoch, state);
peer.setCurrentVote(newVote);
// Start 3rd peer and check if it joins the quorum
- peer = new QuorumPeer(peers, tmpdir[2], tmpdir[2],
- port[2], 3, 2, 2000, 2, 2, 2);
+ peer = new QuorumPeer(peers, tmpdir[2], tmpdir[2], port[2], 3, 2, 2000, 2, 2, 2);
LOG.info("Starting peer " + peer.getId());
peer.start();
peerList.add(sid, peer);
@@ -518,8 +487,7 @@ public class FLETest extends ZKTestCase {
v1.start();
v1.join(waitTime);
if (v1.isAlive()) {
- Assert.fail("Peer " + peer.getId() + " failed to join the cluster " +
- "within " + waitTime + " ms");
+ fail("Peer " + peer.getId() + " failed to join the cluster " + "within " + waitTime + " ms");
}
// cleanup
for (int id = 0; id < 3; id++) {
@@ -532,6 +500,7 @@ public class FLETest extends ZKTestCase {
@Test
public void testElectionTimeUnit() throws Exception {
- Assert.assertEquals("MS", QuorumPeer.FLE_TIME_UNIT);
+ assertEquals("MS", QuorumPeer.FLE_TIME_UNIT);
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/FLEZeroWeightTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/FLEZeroWeightTest.java
index 65d436da3..043ba4694 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/FLEZeroWeightTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/FLEZeroWeightTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -17,6 +17,8 @@
*/
package org.apache.zookeeper.test;
+
+import static org.junit.Assert.fail;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.net.InetSocketAddress;
@@ -24,56 +26,55 @@ import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
import org.apache.zookeeper.PortAssignment;
import org.apache.zookeeper.ZKTestCase;
-import org.apache.zookeeper.server.quorum.FastLeaderElection;
import org.apache.zookeeper.server.quorum.QuorumPeer;
-import org.apache.zookeeper.server.quorum.Vote;
import org.apache.zookeeper.server.quorum.QuorumPeer.QuorumServer;
import org.apache.zookeeper.server.quorum.QuorumPeer.ServerState;
+import org.apache.zookeeper.server.quorum.Vote;
import org.apache.zookeeper.server.quorum.flexible.QuorumHierarchical;
import org.junit.After;
-import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
public class FLEZeroWeightTest extends ZKTestCase {
+
private static final Logger LOG = LoggerFactory.getLogger(HierarchicalQuorumTest.class);
Properties qp;
int count;
- Map<Long,QuorumServer> peers;
+ Map<Long, QuorumServer> peers;
ArrayList<LEThread> threads;
- File tmpdir[];
- int port[];
+ File[] tmpdir;
+ int[] port;
- volatile Vote votes[];
+ volatile Vote[] votes;
@Before
public void setUp() throws Exception {
count = 9;
- peers = new HashMap<Long,QuorumServer>(count);
+ peers = new HashMap<Long, QuorumServer>(count);
threads = new ArrayList<LEThread>(count);
votes = new Vote[count];
tmpdir = new File[count];
port = new int[count];
- String config = "group.1=0:1:2\n" +
- "group.2=3:4:5\n" +
- "group.3=6:7:8\n" +
- "weight.0=1\n" +
- "weight.1=1\n" +
- "weight.2=1\n" +
- "weight.3=0\n" +
- "weight.4=0\n" +
- "weight.5=0\n" +
- "weight.6=0\n" +
- "weight.7=0\n" +
- "weight.8=0";
+ String config = "group.1=0:1:2\n"
+ + "group.2=3:4:5\n"
+ + "group.3=6:7:8\n"
+ + "weight.0=1\n"
+ + "weight.1=1\n"
+ + "weight.2=1\n"
+ + "weight.3=0\n"
+ + "weight.4=0\n"
+ + "weight.5=0\n"
+ + "weight.6=0\n"
+ + "weight.7=0\n"
+ + "weight.8=0";
ByteArrayInputStream is = new ByteArrayInputStream(config.getBytes());
this.qp = new Properties();
@@ -82,7 +83,7 @@ public class FLEZeroWeightTest extends ZKTestCase {
@After
public void tearDown() throws Exception {
- for(int i = 0; i < threads.size(); i++) {
+ for (int i = 0; i < threads.size(); i++) {
LEThread leThread = threads.get(i);
// shutdown() has to be explicitly called for every thread to
// make sure that resources are freed properly and all fixed network ports
@@ -92,6 +93,7 @@ public class FLEZeroWeightTest extends ZKTestCase {
}
class LEThread extends Thread {
+
int i;
QuorumPeer peer;
boolean fail;
@@ -106,13 +108,13 @@ public class FLEZeroWeightTest extends ZKTestCase {
try {
Vote v = null;
fail = false;
- while(true){
+ while (true) {
//while(true) {
peer.setPeerState(ServerState.LOOKING);
LOG.info("Going to call leader election.");
v = peer.getElectionAlg().lookForLeader();
- if(v == null){
+ if (v == null) {
LOG.info("Thread " + i + " got a null vote");
return;
}
@@ -126,33 +128,37 @@ public class FLEZeroWeightTest extends ZKTestCase {
LOG.info("Finished election: " + i + ", " + v.getId());
votes[i] = v;
- if((peer.getPeerState() == ServerState.LEADING) &&
- (peer.getId() > 2)) fail = true;
+ if ((peer.getPeerState() == ServerState.LEADING) && (peer.getId() > 2)) {
+ fail = true;
+ }
- if((peer.getPeerState() == ServerState.FOLLOWING) ||
- (peer.getPeerState() == ServerState.LEADING)) break;
+ if ((peer.getPeerState() == ServerState.FOLLOWING) || (peer.getPeerState()
+ == ServerState.LEADING)) {
+ break;
+ }
}
LOG.debug("Thread " + i + " votes " + v);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
+
}
@Test
public void testZeroWeightQuorum() throws Exception {
- LOG.info("TestZeroWeightQuorum: " + getTestName()+ ", " + count);
- for(int i = 0; i < count; i++) {
- InetSocketAddress addr1 = new InetSocketAddress("127.0.0.1",PortAssignment.unique());
- InetSocketAddress addr2 = new InetSocketAddress("127.0.0.1",PortAssignment.unique());
- InetSocketAddress addr3 = new InetSocketAddress("127.0.0.1",PortAssignment.unique());
+ LOG.info("TestZeroWeightQuorum: " + getTestName() + ", " + count);
+ for (int i = 0; i < count; i++) {
+ InetSocketAddress addr1 = new InetSocketAddress("127.0.0.1", PortAssignment.unique());
+ InetSocketAddress addr2 = new InetSocketAddress("127.0.0.1", PortAssignment.unique());
+ InetSocketAddress addr3 = new InetSocketAddress("127.0.0.1", PortAssignment.unique());
port[i] = addr3.getPort();
- qp.setProperty("server."+i, "127.0.0.1:"+addr1.getPort()+":"+addr2.getPort()+";"+port[i]);
+ qp.setProperty("server." + i, "127.0.0.1:" + addr1.getPort() + ":" + addr2.getPort() + ";" + port[i]);
peers.put(Long.valueOf(i), new QuorumServer(i, addr1, addr2, addr3));
tmpdir[i] = ClientBase.createTmpDir();
}
- for(int i = 0; i < count; i++) {
+ for (int i = 0; i < count; i++) {
QuorumHierarchical hq = new QuorumHierarchical(qp);
QuorumPeer peer = new QuorumPeer(peers, tmpdir[i], tmpdir[i], port[i], 3, i, 1000, 2, 2, 2, hq);
peer.startLeaderElection();
@@ -162,14 +168,16 @@ public class FLEZeroWeightTest extends ZKTestCase {
}
LOG.info("Started threads " + getTestName());
- for(int i = 0; i < threads.size(); i++) {
+ for (int i = 0; i < threads.size(); i++) {
threads.get(i).join(15000);
if (threads.get(i).isAlive()) {
- Assert.fail("Threads didn't join");
+ fail("Threads didn't join");
} else {
- if(threads.get(i).fail)
- Assert.fail("Elected zero-weight server");
+ if (threads.get(i).fail) {
+ fail("Elected zero-weight server");
+ }
}
}
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/FollowerResyncConcurrencyTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/FollowerResyncConcurrencyTest.java
index c27e9a92f..963d8b437 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/FollowerResyncConcurrencyTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/FollowerResyncConcurrencyTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -24,7 +24,6 @@ import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
-
import java.io.IOException;
import java.util.Collection;
import java.util.Set;
@@ -34,7 +33,6 @@ import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
-
import org.apache.zookeeper.AsyncCallback;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
@@ -48,14 +46,13 @@ import org.apache.zookeeper.server.ZKDatabase;
import org.apache.zookeeper.server.quorum.Leader;
import org.apache.zookeeper.test.ClientBase.CountdownWatcher;
import org.junit.After;
-import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-
public class FollowerResyncConcurrencyTest extends ZKTestCase {
+
private static final Logger LOG = LoggerFactory.getLogger(FollowerResyncConcurrencyTest.class);
public static final long CONNECTION_TIMEOUT = ClientTest.CONNECTION_TIMEOUT;
@@ -76,18 +73,18 @@ public class FollowerResyncConcurrencyTest extends ZKTestCase {
@After
public void tearDown() throws Exception {
- LOG.info("Error count {}" , errors.get());
+ LOG.info("Error count {}", errors.get());
}
/**
* See ZOOKEEPER-1319 - verify that a lagging follwer resyncs correctly
- *
+ *
* 1) start with down quorum
* 2) start leader/follower1, add some data
* 3) restart leader/follower1
* 4) start follower2
* 5) verify data consistency across the ensemble
- *
+ *
* @throws Exception
*/
@Test
@@ -101,13 +98,14 @@ public class FollowerResyncConcurrencyTest extends ZKTestCase {
qu.start(1);
qu.start(2);
- Assert.assertTrue("Waiting for server up", ClientBase.waitForServerUp("127.0.0.1:"
- + qu.getPeer(1).clientPort, ClientBase.CONNECTION_TIMEOUT));
- Assert.assertTrue("Waiting for server up", ClientBase.waitForServerUp("127.0.0.1:"
- + qu.getPeer(2).clientPort, ClientBase.CONNECTION_TIMEOUT));
-
- ZooKeeper zk1 =
- createClient(qu.getPeer(1).peer.getClientPort(), watcher1);
+ assertTrue(
+ "Waiting for server up",
+ ClientBase.waitForServerUp("127.0.0.1:" + qu.getPeer(1).clientPort, ClientBase.CONNECTION_TIMEOUT));
+ assertTrue(
+ "Waiting for server up",
+ ClientBase.waitForServerUp("127.0.0.1:" + qu.getPeer(2).clientPort, ClientBase.CONNECTION_TIMEOUT));
+
+ ZooKeeper zk1 = createClient(qu.getPeer(1).peer.getClientPort(), watcher1);
LOG.info("zk1 has session id 0x{}", Long.toHexString(zk1.getSessionId()));
final String resyncPath = "/resyncundernewepoch";
@@ -116,35 +114,38 @@ public class FollowerResyncConcurrencyTest extends ZKTestCase {
qu.shutdown(1);
qu.shutdown(2);
- Assert.assertTrue("Waiting for server down", ClientBase.waitForServerDown("127.0.0.1:"
- + qu.getPeer(1).clientPort, ClientBase.CONNECTION_TIMEOUT));
- Assert.assertTrue("Waiting for server down", ClientBase.waitForServerDown("127.0.0.1:"
- + qu.getPeer(2).clientPort, ClientBase.CONNECTION_TIMEOUT));
-
+ assertTrue(
+ "Waiting for server down",
+ ClientBase.waitForServerDown("127.0.0.1:" + qu.getPeer(1).clientPort, ClientBase.CONNECTION_TIMEOUT));
+ assertTrue(
+ "Waiting for server down",
+ ClientBase.waitForServerDown("127.0.0.1:" + qu.getPeer(2).clientPort, ClientBase.CONNECTION_TIMEOUT));
+
qu.start(1);
qu.start(2);
- Assert.assertTrue("Waiting for server up", ClientBase.waitForServerUp("127.0.0.1:"
- + qu.getPeer(1).clientPort, ClientBase.CONNECTION_TIMEOUT));
- Assert.assertTrue("Waiting for server up", ClientBase.waitForServerUp("127.0.0.1:"
- + qu.getPeer(2).clientPort, ClientBase.CONNECTION_TIMEOUT));
+ assertTrue(
+ "Waiting for server up",
+ ClientBase.waitForServerUp("127.0.0.1:" + qu.getPeer(1).clientPort, ClientBase.CONNECTION_TIMEOUT));
+ assertTrue(
+ "Waiting for server up",
+ ClientBase.waitForServerUp("127.0.0.1:" + qu.getPeer(2).clientPort, ClientBase.CONNECTION_TIMEOUT));
qu.start(3);
- Assert.assertTrue("Waiting for server up", ClientBase.waitForServerUp("127.0.0.1:"
- + qu.getPeer(3).clientPort, ClientBase.CONNECTION_TIMEOUT));
+ assertTrue(
+ "Waiting for server up",
+ ClientBase.waitForServerUp("127.0.0.1:" + qu.getPeer(3).clientPort, ClientBase.CONNECTION_TIMEOUT));
zk1 = createClient(qu.getPeer(1).peer.getClientPort(), watcher1);
LOG.info("zk1 has session id 0x{}", Long.toHexString(zk1.getSessionId()));
-
+
assertNotNull("zk1 has data", zk1.exists(resyncPath, false));
- final ZooKeeper zk2 =
- createClient(qu.getPeer(2).peer.getClientPort(), watcher2);
+ final ZooKeeper zk2 = createClient(qu.getPeer(2).peer.getClientPort(), watcher2);
LOG.info("zk2 has session id 0x{}", Long.toHexString(zk2.getSessionId()));
assertNotNull("zk2 has data", zk2.exists(resyncPath, false));
- final ZooKeeper zk3 =
- createClient(qu.getPeer(3).peer.getClientPort(), watcher3);
+ final ZooKeeper zk3 = createClient(qu.getPeer(3).peer.getClientPort(), watcher3);
LOG.info("zk3 has session id 0x{}", Long.toHexString(zk3.getSessionId()));
assertNotNull("zk3 has data", zk3.exists(resyncPath, false));
@@ -152,9 +153,9 @@ public class FollowerResyncConcurrencyTest extends ZKTestCase {
zk1.close();
zk2.close();
zk3.close();
-
+
qu.shutdownAll();
- }
+ }
/**
* See ZOOKEEPER-962. This tests for one of the bugs hit while fixing this,
@@ -170,12 +171,10 @@ public class FollowerResyncConcurrencyTest extends ZKTestCase {
* @throws KeeperException
*/
@Test
- public void testResyncBySnapThenDiffAfterFollowerCrashes()
- throws IOException, InterruptedException, KeeperException, Throwable
- {
+ public void testResyncBySnapThenDiffAfterFollowerCrashes() throws Throwable {
followerResyncCrashTest(false);
}
-
+
/**
* Same as testResyncBySnapThenDiffAfterFollowerCrashes() but we resync
* follower using txnlog
@@ -185,15 +184,11 @@ public class FollowerResyncConcurrencyTest extends ZKTestCase {
* @throws KeeperException
*/
@Test
- public void testResyncByTxnlogThenDiffAfterFollowerCrashes()
- throws IOException, InterruptedException, KeeperException, Throwable
- {
+ public void testResyncByTxnlogThenDiffAfterFollowerCrashes() throws Throwable {
followerResyncCrashTest(true);
}
-
- public void followerResyncCrashTest(boolean useTxnLogResync)
- throws IOException, InterruptedException, KeeperException, Throwable
- {
+
+ public void followerResyncCrashTest(boolean useTxnLogResync) throws Throwable {
final Semaphore sem = new Semaphore(0);
QuorumUtil qu = new QuorumUtil(1);
@@ -203,23 +198,21 @@ public class FollowerResyncConcurrencyTest extends ZKTestCase {
CountdownWatcher watcher3 = new CountdownWatcher();
int index = 1;
- while(qu.getPeer(index).peer.leader == null) {
+ while (qu.getPeer(index).peer.leader == null) {
index++;
}
Leader leader = qu.getPeer(index).peer.leader;
assertNotNull(leader);
-
+
if (useTxnLogResync) {
// Set the factor to high value so that this test case always
// resync using txnlog
- qu.getPeer(index).peer.getActiveServer().getZKDatabase()
- .setSnapshotSizeFactor(1000);
+ qu.getPeer(index).peer.getActiveServer().getZKDatabase().setSnapshotSizeFactor(1000);
} else {
// Disable sending DIFF using txnlog, so that this test still
// testing the ZOOKEEPER-962 bug
- qu.getPeer(index).peer.getActiveServer().getZKDatabase()
- .setSnapshotSizeFactor(-1);
+ qu.getPeer(index).peer.getActiveServer().getZKDatabase().setSnapshotSizeFactor(-1);
}
/* Reusing the index variable to select a follower to connect to */
@@ -228,29 +221,26 @@ public class FollowerResyncConcurrencyTest extends ZKTestCase {
qu.shutdown(index);
- final ZooKeeper zk3 =
- createClient(qu.getPeer(3).peer.getClientPort(), watcher3);
+ final ZooKeeper zk3 = createClient(qu.getPeer(3).peer.getClientPort(), watcher3);
LOG.info("zk3 has session id 0x{}", Long.toHexString(zk3.getSessionId()));
zk3.create("/mybar", null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
qu.restart(index);
- final ZooKeeper zk1 =
- createClient(qu.getPeer(index).peer.getClientPort(), watcher1);
+ final ZooKeeper zk1 = createClient(qu.getPeer(index).peer.getClientPort(), watcher1);
LOG.info("zk1 has session id 0x{}", Long.toHexString(zk1.getSessionId()));
- final ZooKeeper zk2 =
- createClient(qu.getPeer(index).peer.getClientPort(), watcher2);
+ final ZooKeeper zk2 = createClient(qu.getPeer(index).peer.getClientPort(), watcher2);
LOG.info("zk2 has session id 0x{}", Long.toHexString(zk2.getSessionId()));
zk1.create("/first", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
-
+
// Prepare a thread that will create znodes.
Thread mytestfooThread = new Thread(new Runnable() {
@Override
public void run() {
- for(int i = 0; i < 3000; i++) {
+ for (int i = 0; i < 3000; i++) {
// Here we create 3000 znodes
zk3.create("/mytestfoo", null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL, new AsyncCallback.StringCallback() {
@@ -261,13 +251,13 @@ public class FollowerResyncConcurrencyTest extends ZKTestCase {
if (rc != 0) {
errors.incrementAndGet();
}
- if(counter.get() == 16200){
+ if (counter.get() == 16200) {
sem.release();
}
}
}, null);
pending.incrementAndGet();
- if(i%10==0){
+ if (i % 10 == 0) {
try {
Thread.sleep(100);
} catch (Exception e) {
@@ -281,7 +271,7 @@ public class FollowerResyncConcurrencyTest extends ZKTestCase {
// Here we start populating the server and shutdown the follower after
// initial data is written.
- for(int i = 0; i < 13000; i++) {
+ for (int i = 0; i < 13000; i++) {
// Here we create 13000 znodes
zk3.create("/mybar", null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL, new AsyncCallback.StringCallback() {
@@ -292,18 +282,18 @@ public class FollowerResyncConcurrencyTest extends ZKTestCase {
if (rc != 0) {
errors.incrementAndGet();
}
- if(counter.get() == 16200){
+ if (counter.get() == 16200) {
sem.release();
}
}
}, null);
pending.incrementAndGet();
- if(i == 5000){
+ if (i == 5000) {
qu.shutdown(index);
LOG.info("Shutting down s1");
}
- if(i == 12000){
+ if (i == 12000) {
// Start the prepared thread so that it is writing znodes while
// the follower is restarting. On the first restart, the follow
// should use txnlog to catchup. For subsequent restart, the
@@ -319,11 +309,11 @@ public class FollowerResyncConcurrencyTest extends ZKTestCase {
qu.restart(index);
LOG.info("Setting up server: {}", index);
}
- if((i % 1000) == 0){
+ if ((i % 1000) == 0) {
Thread.sleep(1000);
}
- if(i%50 == 0) {
+ if (i % 50 == 0) {
zk2.create("/newbaz", null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL, new AsyncCallback.StringCallback() {
@Override
public void processResult(int rc, String path, Object ctx, String name) {
@@ -332,7 +322,7 @@ public class FollowerResyncConcurrencyTest extends ZKTestCase {
if (rc != 0) {
errors.incrementAndGet();
}
- if(counter.get() == 16200){
+ if (counter.get() == 16200) {
sem.release();
}
}
@@ -342,7 +332,7 @@ public class FollowerResyncConcurrencyTest extends ZKTestCase {
}
// Wait until all updates return
- if(!sem.tryAcquire(ClientBase.CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS)) {
+ if (!sem.tryAcquire(ClientBase.CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS)) {
LOG.warn("Did not aquire semaphore fast enough");
}
mytestfooThread.join(ClientBase.CONNECTION_TIMEOUT);
@@ -353,11 +343,11 @@ public class FollowerResyncConcurrencyTest extends ZKTestCase {
assertTrue(waitForSync(qu, index, 10));
verifyState(qu, index, leader);
-
+
zk1.close();
zk2.close();
zk3.close();
-
+
qu.shutdownAll();
}
@@ -386,9 +376,7 @@ public class FollowerResyncConcurrencyTest extends ZKTestCase {
*/
@Test
- public void testResyncByDiffAfterFollowerCrashes()
- throws IOException, InterruptedException, KeeperException, Throwable
- {
+ public void testResyncByDiffAfterFollowerCrashes() throws IOException, InterruptedException, KeeperException, Throwable {
final Semaphore sem = new Semaphore(0);
QuorumUtil qu = new QuorumUtil(1);
@@ -398,7 +386,7 @@ public class FollowerResyncConcurrencyTest extends ZKTestCase {
CountdownWatcher watcher3 = new CountdownWatcher();
int index = 1;
- while(qu.getPeer(index).peer.leader == null) {
+ while (qu.getPeer(index).peer.leader == null) {
index++;
}
@@ -409,16 +397,13 @@ public class FollowerResyncConcurrencyTest extends ZKTestCase {
index = (index == 1) ? 2 : 1;
LOG.info("Connecting to follower: {}", index);
- final ZooKeeper zk1 =
- createClient(qu.getPeer(index).peer.getClientPort(), watcher1);
+ final ZooKeeper zk1 = createClient(qu.getPeer(index).peer.getClientPort(), watcher1);
LOG.info("zk1 has session id 0x{}", Long.toHexString(zk1.getSessionId()));
- final ZooKeeper zk2 =
- createClient(qu.getPeer(index).peer.getClientPort(), watcher2);
+ final ZooKeeper zk2 = createClient(qu.getPeer(index).peer.getClientPort(), watcher2);
LOG.info("zk2 has session id 0x{}", Long.toHexString(zk2.getSessionId()));
- final ZooKeeper zk3 =
- createClient(qu.getPeer(3).peer.getClientPort(), watcher3);
+ final ZooKeeper zk3 = createClient(qu.getPeer(3).peer.getClientPort(), watcher3);
LOG.info("zk3 has session id 0x{}", Long.toHexString(zk3.getSessionId()));
zk1.create("/first", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
@@ -430,8 +415,8 @@ public class FollowerResyncConcurrencyTest extends ZKTestCase {
@Override
public void run() {
int inSyncCounter = 0;
- while(inSyncCounter < 400) {
- if(runNow.get()) {
+ while (inSyncCounter < 400) {
+ if (runNow.get()) {
zk3.create("/mytestfoo", null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL, new AsyncCallback.StringCallback() {
@Override
@@ -439,9 +424,9 @@ public class FollowerResyncConcurrencyTest extends ZKTestCase {
pending.decrementAndGet();
counter.incrementAndGet();
if (rc != 0) {
- errors.incrementAndGet();;
+ errors.incrementAndGet();
}
- if(counter.get() > 7300){
+ if (counter.get() > 7300) {
sem.release();
}
}
@@ -461,7 +446,7 @@ public class FollowerResyncConcurrencyTest extends ZKTestCase {
});
mytestfooThread.start();
- for(int i = 0; i < 5000; i++) {
+ for (int i = 0; i < 5000; i++) {
zk2.create("/mybar", null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL, new AsyncCallback.StringCallback() {
@Override
@@ -469,31 +454,31 @@ public class FollowerResyncConcurrencyTest extends ZKTestCase {
pending.decrementAndGet();
counter.incrementAndGet();
if (rc != 0) {
- errors.incrementAndGet();;
+ errors.incrementAndGet();
}
- if(counter.get() > 7300){
+ if (counter.get() > 7300) {
sem.release();
}
}
}, null);
pending.incrementAndGet();
- if(i == 1000){
+ if (i == 1000) {
qu.shutdown(index);
Thread.sleep(1100);
LOG.info("Shutting down s1");
}
- if(i == 1100 || i == 1150 || i == 1200) {
+ if (i == 1100 || i == 1150 || i == 1200) {
Thread.sleep(1000);
}
- if(i == 1200){
+ if (i == 1200) {
qu.startThenShutdown(index);
runNow.set(true);
qu.restart(index);
LOG.info("Setting up server: {}", index);
}
- if(i>=1000 && i%2== 0) {
+ if (i >= 1000 && i % 2 == 0) {
zk3.create("/newbaz", null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL, new AsyncCallback.StringCallback() {
@Override
@@ -503,20 +488,20 @@ public class FollowerResyncConcurrencyTest extends ZKTestCase {
if (rc != 0) {
errors.incrementAndGet();
}
- if(counter.get() > 7300){
+ if (counter.get() > 7300) {
sem.release();
}
}
}, null);
pending.incrementAndGet();
}
- if(i == 1050 || i == 1100 || i == 1150) {
+ if (i == 1050 || i == 1100 || i == 1150) {
Thread.sleep(1000);
}
}
// Wait until all updates return
- if(!sem.tryAcquire(ClientBase.CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS)) {
+ if (!sem.tryAcquire(ClientBase.CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS)) {
LOG.warn("Did not aquire semaphore fast enough");
}
mytestfooThread.join(ClientBase.CONNECTION_TIMEOUT);
@@ -533,21 +518,20 @@ public class FollowerResyncConcurrencyTest extends ZKTestCase {
zk1.close();
zk2.close();
zk3.close();
-
+
qu.shutdownAll();
}
- private static DisconnectableZooKeeper createClient(int port,
- CountdownWatcher watcher)
- throws IOException, TimeoutException, InterruptedException
- {
+ private static DisconnectableZooKeeper createClient(int port, CountdownWatcher watcher) throws IOException, TimeoutException, InterruptedException {
DisconnectableZooKeeper zk = new DisconnectableZooKeeper(
- "127.0.0.1:" + port, ClientBase.CONNECTION_TIMEOUT, watcher);
+ "127.0.0.1:" + port,
+ ClientBase.CONNECTION_TIMEOUT,
+ watcher);
watcher.waitForConnected(CONNECTION_TIMEOUT);
return zk;
}
-
+
/**
* Wait for all async operation to return. So we know that we can start
* verifying the state
@@ -567,11 +551,11 @@ public class FollowerResyncConcurrencyTest extends ZKTestCase {
/**
* Wait for all server to have the same lastProccessedZxid. Timeout in seconds
*/
- private boolean waitForSync(QuorumUtil qu, int index, int timeout) throws InterruptedException{
+ private boolean waitForSync(QuorumUtil qu, int index, int timeout) throws InterruptedException {
LOG.info("Wait for server to sync");
int leaderIndex = (index == 1) ? 2 : 1;
ZKDatabase restartedDb = qu.getPeer(index).peer.getActiveServer().getZKDatabase();
- ZKDatabase cleanDb = qu.getPeer(3).peer.getActiveServer().getZKDatabase();
+ ZKDatabase cleanDb = qu.getPeer(3).peer.getActiveServer().getZKDatabase();
ZKDatabase leadDb = qu.getPeer(leaderIndex).peer.getActiveServer().getZKDatabase();
long leadZxid = 0;
long cleanZxid = 0;
@@ -585,83 +569,77 @@ public class FollowerResyncConcurrencyTest extends ZKTestCase {
}
Thread.sleep(1000);
}
- LOG.info("Timeout waiting for zxid to sync: leader 0x{}" +
- "clean 0x{}" +
- "restarted 0x{}", Long.toHexString(leadZxid), Long.toHexString(cleanZxid),
- Long.toHexString(restartedZxid));
+ LOG.info("Timeout waiting for zxid to sync: leader 0x{}"
+ + "clean 0x{}"
+ + "restarted 0x{}", Long.toHexString(leadZxid), Long.toHexString(cleanZxid), Long.toHexString(restartedZxid));
return false;
}
- private static TestableZooKeeper createTestableClient(String hp)
- throws IOException, TimeoutException, InterruptedException
- {
+ private static TestableZooKeeper createTestableClient(String hp) throws IOException, TimeoutException, InterruptedException {
CountdownWatcher watcher = new CountdownWatcher();
return createTestableClient(watcher, hp);
}
private static TestableZooKeeper createTestableClient(
- CountdownWatcher watcher, String hp)
- throws IOException, TimeoutException, InterruptedException
- {
- TestableZooKeeper zk = new TestableZooKeeper(
- hp, ClientBase.CONNECTION_TIMEOUT, watcher);
-
- watcher.waitForConnected(CONNECTION_TIMEOUT);
- return zk;
- }
+ CountdownWatcher watcher, String hp) throws IOException, TimeoutException, InterruptedException {
+ TestableZooKeeper zk = new TestableZooKeeper(hp, ClientBase.CONNECTION_TIMEOUT, watcher);
+
+ watcher.waitForConnected(CONNECTION_TIMEOUT);
+ return zk;
+ }
private void verifyState(QuorumUtil qu, int index, Leader leader) {
LOG.info("Verifying state");
assertTrue("Not following", qu.getPeer(index).peer.follower != null);
long epochF = (qu.getPeer(index).peer.getActiveServer().getZxid() >> 32L);
long epochL = (leader.getEpoch() >> 32L);
- assertTrue("Zxid: " + qu.getPeer(index).peer.getActiveServer().getZKDatabase().getDataTreeLastProcessedZxid() +
- "Current epoch: " + epochF, epochF == epochL);
+ assertTrue("Zxid: "
+ + qu.getPeer(index).peer.getActiveServer().getZKDatabase().getDataTreeLastProcessedZxid()
+ + "Current epoch: "
+ + epochF, epochF == epochL);
int leaderIndex = (index == 1) ? 2 : 1;
Collection<Long> sessionsRestarted = qu.getPeer(index).peer.getActiveServer().getZKDatabase().getSessions();
Collection<Long> sessionsNotRestarted = qu.getPeer(leaderIndex).peer.getActiveServer().getZKDatabase().getSessions();
- for(Long l : sessionsRestarted) {
- assertTrue("Should have same set of sessions in both servers, did not expect: " + l, sessionsNotRestarted.contains(l));
+ for (Long l : sessionsRestarted) {
+ assertTrue("Should have same set of sessions in both servers, did not expect: "
+ + l, sessionsNotRestarted.contains(l));
}
assertEquals("Should have same number of sessions", sessionsNotRestarted.size(), sessionsRestarted.size());
ZKDatabase restarted = qu.getPeer(index).peer.getActiveServer().getZKDatabase();
- ZKDatabase clean = qu.getPeer(3).peer.getActiveServer().getZKDatabase();
+ ZKDatabase clean = qu.getPeer(3).peer.getActiveServer().getZKDatabase();
ZKDatabase lead = qu.getPeer(leaderIndex).peer.getActiveServer().getZKDatabase();
- for(Long l : sessionsRestarted) {
+ for (Long l : sessionsRestarted) {
LOG.info("Validating ephemeral for session id 0x{}", Long.toHexString(l));
- assertTrue("Should have same set of sessions in both servers, did not expect: " + l, sessionsNotRestarted.contains(l));
+ assertTrue("Should have same set of sessions in both servers, did not expect: "
+ + l, sessionsNotRestarted.contains(l));
Set<String> ephemerals = restarted.getEphemerals(l);
Set<String> cleanEphemerals = clean.getEphemerals(l);
- for(String o : cleanEphemerals) {
- if(!ephemerals.contains(o)) {
- LOG.info("Restarted follower doesn't contain ephemeral {} zxid 0x{}",
- o, Long.toHexString(clean.getDataTree().getNode(o).stat.getMzxid()));
+ for (String o : cleanEphemerals) {
+ if (!ephemerals.contains(o)) {
+ LOG.info("Restarted follower doesn't contain ephemeral {} zxid 0x{}", o, Long.toHexString(clean.getDataTree().getNode(o).stat.getMzxid()));
}
}
- for(String o : ephemerals) {
- if(!cleanEphemerals.contains(o)) {
- LOG.info("Restarted follower has extra ephemeral {} zxid 0x{}",
- o, Long.toHexString(restarted.getDataTree().getNode(o).stat.getMzxid()));
+ for (String o : ephemerals) {
+ if (!cleanEphemerals.contains(o)) {
+ LOG.info("Restarted follower has extra ephemeral {} zxid 0x{}", o, Long.toHexString(restarted.getDataTree().getNode(o).stat.getMzxid()));
}
}
Set<String> leadEphemerals = lead.getEphemerals(l);
- for(String o : leadEphemerals) {
- if(!cleanEphemerals.contains(o)) {
- LOG.info("Follower doesn't contain ephemeral from leader {} zxid 0x{}",
- o, Long.toHexString(lead.getDataTree().getNode(o).stat.getMzxid()));
+ for (String o : leadEphemerals) {
+ if (!cleanEphemerals.contains(o)) {
+ LOG.info("Follower doesn't contain ephemeral from leader {} zxid 0x{}", o, Long.toHexString(lead.getDataTree().getNode(o).stat.getMzxid()));
}
}
- for(String o : cleanEphemerals) {
- if(!leadEphemerals.contains(o)) {
- LOG.info("Leader doesn't contain ephemeral from follower {} zxid 0x{}",
- o, Long.toHexString(clean.getDataTree().getNode(o).stat.getMzxid()));
+ for (String o : cleanEphemerals) {
+ if (!leadEphemerals.contains(o)) {
+ LOG.info("Leader doesn't contain ephemeral from follower {} zxid 0x{}", o, Long.toHexString(clean.getDataTree().getNode(o).stat.getMzxid()));
}
}
assertEquals("Should have same number of ephemerals in both followers", ephemerals.size(), cleanEphemerals.size());
assertEquals("Leader should equal follower", lead.getEphemerals(l).size(), cleanEphemerals.size());
}
- }
+ }
/**
* Verify that the server is sending the proper zxid. See ZOOKEEPER-1412.
@@ -672,13 +650,12 @@ public class FollowerResyncConcurrencyTest extends ZKTestCase {
qu.startAll();
int index = 1;
- while(qu.getPeer(index).peer.follower == null) {
+ while (qu.getPeer(index).peer.follower == null) {
index++;
}
LOG.info("Connecting to follower: {}", index);
- TestableZooKeeper zk =
- createTestableClient("localhost:" + qu.getPeer(index).peer.getClientPort());
+ TestableZooKeeper zk = createTestableClient("localhost:" + qu.getPeer(index).peer.getClientPort());
assertEquals(0L, zk.testableLastZxid());
zk.exists("/", false);
@@ -689,8 +666,8 @@ public class FollowerResyncConcurrencyTest extends ZKTestCase {
}
private class MyWatcher extends CountdownWatcher {
- LinkedBlockingQueue<WatchedEvent> events =
- new LinkedBlockingQueue<WatchedEvent>();
+
+ LinkedBlockingQueue<WatchedEvent> events = new LinkedBlockingQueue<WatchedEvent>();
public void process(WatchedEvent event) {
super.process(event);
@@ -702,6 +679,7 @@ public class FollowerResyncConcurrencyTest extends ZKTestCase {
}
}
}
+
}
/**
@@ -714,26 +692,22 @@ public class FollowerResyncConcurrencyTest extends ZKTestCase {
qu.startAll();
int index = 1;
- while(qu.getPeer(index).peer.follower == null) {
+ while (qu.getPeer(index).peer.follower == null) {
index++;
}
LOG.info("Connecting to follower: {}", index);
- TestableZooKeeper zk1 = createTestableClient(
- "localhost:" + qu.getPeer(index).peer.getClientPort());
- zk1.create("/foo", "foo".getBytes(), Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ TestableZooKeeper zk1 = createTestableClient("localhost:" + qu.getPeer(index).peer.getClientPort());
+ zk1.create("/foo", "foo".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
MyWatcher watcher = new MyWatcher();
- TestableZooKeeper zk2 = createTestableClient(watcher,
- "localhost:" + qu.getPeer(index).peer.getClientPort());
+ TestableZooKeeper zk2 = createTestableClient(watcher, "localhost:" + qu.getPeer(index).peer.getClientPort());
zk2.exists("/foo", true);
watcher.reset();
zk2.testableConnloss();
- if (!watcher.clientConnected.await(CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS))
- {
+ if (!watcher.clientConnected.await(CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS)) {
fail("Unable to connect to server");
}
assertArrayEquals("foo".getBytes(), zk2.getData("/foo", false, null));
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/FourLetterWordsQuorumTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/FourLetterWordsQuorumTest.java
index 28fbde5f6..37365fd12 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/FourLetterWordsQuorumTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/FourLetterWordsQuorumTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,26 +18,23 @@
package org.apache.zookeeper.test;
+import static org.apache.zookeeper.client.FourLetterWordMain.send4LetterWord;
+import static org.junit.Assert.assertTrue;
import java.io.IOException;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
import org.apache.zookeeper.TestableZooKeeper;
import org.apache.zookeeper.common.X509Exception.SSLContextException;
-
-import static org.apache.zookeeper.client.FourLetterWordMain.send4LetterWord;
-
-import org.junit.Assert;
import org.junit.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
public class FourLetterWordsQuorumTest extends QuorumBase {
- protected static final Logger LOG =
- LoggerFactory.getLogger(FourLetterWordsQuorumTest.class);
+
+ protected static final Logger LOG = LoggerFactory.getLogger(FourLetterWordsQuorumTest.class);
/** Test the various four letter words */
@Test
public void testFourLetterWords() throws Exception {
- String servers[] = hostPort.split(",");
+ String[] servers = hostPort.split(",");
for (String hp : servers) {
verify(hp, "ruok", "imok");
verify(hp, "envi", "java.version");
@@ -102,18 +99,16 @@ public class FourLetterWordsQuorumTest extends QuorumBase {
}
}
- private void verify(String hp, String cmd, String expected)
- throws IOException, SSLContextException
- {
- for(HostPort hpobj: parseHostPortList(hp)) {
+ private void verify(String hp, String cmd, String expected) throws IOException, SSLContextException {
+ for (HostPort hpobj : parseHostPortList(hp)) {
String resp = send4LetterWord(hpobj.host, hpobj.port, cmd);
LOG.info("cmd " + cmd + " expected " + expected + " got " + resp);
if (cmd.equals("dump")) {
- Assert.assertTrue(resp.contains(expected)
- || resp.contains("Sessions with Ephemerals"));
+ assertTrue(resp.contains(expected) || resp.contains("Sessions with Ephemerals"));
} else {
- Assert.assertTrue(resp.contains(expected));
+ assertTrue(resp.contains(expected));
}
}
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/FourLetterWordsTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/FourLetterWordsTest.java
index 30f0eeb53..e4ce49710 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/FourLetterWordsTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/FourLetterWordsTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,21 +18,20 @@
package org.apache.zookeeper.test;
+import static org.apache.zookeeper.client.FourLetterWordMain.send4LetterWord;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.StringReader;
import java.util.regex.Pattern;
-
import org.apache.zookeeper.TestableZooKeeper;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.common.IOUtils;
import org.apache.zookeeper.common.X509Exception.SSLContextException;
-
-import static org.apache.zookeeper.client.FourLetterWordMain.send4LetterWord;
-
-import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.Timeout;
@@ -40,8 +39,8 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class FourLetterWordsTest extends ClientBase {
- protected static final Logger LOG =
- LoggerFactory.getLogger(FourLetterWordsTest.class);
+
+ protected static final Logger LOG = LoggerFactory.getLogger(FourLetterWordsTest.class);
@Rule
public Timeout timeout = Timeout.millis(30000);
@@ -116,58 +115,58 @@ public class FourLetterWordsTest extends ClientBase {
}
private String sendRequest(String cmd) throws IOException, SSLContextException {
- HostPort hpobj = ClientBase.parseHostPortList(hostPort).get(0);
- return send4LetterWord(hpobj.host, hpobj.port, cmd);
+ HostPort hpobj = ClientBase.parseHostPortList(hostPort).get(0);
+ return send4LetterWord(hpobj.host, hpobj.port, cmd);
}
private String sendRequest(String cmd, int timeout) throws IOException, SSLContextException {
HostPort hpobj = ClientBase.parseHostPortList(hostPort).get(0);
return send4LetterWord(hpobj.host, hpobj.port, cmd, false, timeout);
- }
+ }
private void verify(String cmd, String expected) throws IOException, SSLContextException {
String resp = sendRequest(cmd);
LOG.info("cmd " + cmd + " expected " + expected + " got " + resp);
- Assert.assertTrue(resp.contains(expected));
+ assertTrue(resp.contains(expected));
}
-
+
@Test
public void testValidateStatOutput() throws Exception {
ZooKeeper zk1 = createClient();
ZooKeeper zk2 = createClient();
-
+
String resp = sendRequest("stat");
BufferedReader in = new BufferedReader(new StringReader(resp));
String line;
// first line should be version info
line = in.readLine();
- Assert.assertTrue(Pattern.matches("^.*\\s\\d+\\.\\d+\\.\\d+-.*$", line));
- Assert.assertTrue(Pattern.matches("^Clients:$", in.readLine()));
+ assertTrue(Pattern.matches("^.*\\s\\d+\\.\\d+\\.\\d+-.*$", line));
+ assertTrue(Pattern.matches("^Clients:$", in.readLine()));
int count = 0;
while ((line = in.readLine()).length() > 0) {
count++;
- Assert.assertTrue(Pattern.matches("^ /.*:\\d+\\[\\d+\\]\\(queued=\\d+,recved=\\d+,sent=\\d+\\)$", line));
+ assertTrue(Pattern.matches("^ /.*:\\d+\\[\\d+\\]\\(queued=\\d+,recved=\\d+,sent=\\d+\\)$", line));
}
// ensure at least the two clients we created are accounted for
- Assert.assertTrue(count >= 2);
+ assertTrue(count >= 2);
line = in.readLine();
- Assert.assertTrue(Pattern.matches("^Latency min/avg/max: \\d+/-?[0-9]*.?[0-9]*/\\d+$", line));
+ assertTrue(Pattern.matches("^Latency min/avg/max: \\d+/-?[0-9]*.?[0-9]*/\\d+$", line));
line = in.readLine();
- Assert.assertTrue(Pattern.matches("^Received: \\d+$", line));
+ assertTrue(Pattern.matches("^Received: \\d+$", line));
line = in.readLine();
- Assert.assertTrue(Pattern.matches("^Sent: \\d+$", line));
+ assertTrue(Pattern.matches("^Sent: \\d+$", line));
line = in.readLine();
- Assert.assertTrue(Pattern.matches("^Connections: \\d+$", line));
+ assertTrue(Pattern.matches("^Connections: \\d+$", line));
line = in.readLine();
- Assert.assertTrue(Pattern.matches("^Outstanding: \\d+$", line));
+ assertTrue(Pattern.matches("^Outstanding: \\d+$", line));
line = in.readLine();
- Assert.assertTrue(Pattern.matches("^Zxid: 0x[\\da-fA-F]+$", line));
+ assertTrue(Pattern.matches("^Zxid: 0x[\\da-fA-F]+$", line));
line = in.readLine();
- Assert.assertTrue(Pattern.matches("^Mode: .*$", line));
+ assertTrue(Pattern.matches("^Mode: .*$", line));
line = in.readLine();
- Assert.assertTrue(Pattern.matches("^Node count: \\d+$", line));
+ assertTrue(Pattern.matches("^Node count: \\d+$", line));
zk1.close();
zk2.close();
@@ -177,7 +176,7 @@ public class FourLetterWordsTest extends ClientBase {
public void testValidateConsOutput() throws Exception {
ZooKeeper zk1 = createClient();
ZooKeeper zk2 = createClient();
-
+
String resp = sendRequest("cons");
BufferedReader in = new BufferedReader(new StringReader(resp));
@@ -185,31 +184,31 @@ public class FourLetterWordsTest extends ClientBase {
int count = 0;
while ((line = in.readLine()) != null && line.length() > 0) {
count++;
- Assert.assertTrue(line, Pattern.matches("^ /.*:\\d+\\[\\d+\\]\\(queued=\\d+,recved=\\d+,sent=\\d+.*\\)$", line));
+ assertTrue(line, Pattern.matches("^ /.*:\\d+\\[\\d+\\]\\(queued=\\d+,recved=\\d+,sent=\\d+.*\\)$", line));
}
// ensure at least the two clients we created are accounted for
- Assert.assertTrue(count >= 2);
+ assertTrue(count >= 2);
zk1.close();
zk2.close();
}
- @Test(timeout=60000)
+ @Test(timeout = 60000)
public void testValidateSocketTimeout() throws Exception {
/**
* testing positive scenario that even with timeout parameter the
* functionality works fine
*/
String resp = sendRequest("isro", 2000);
- Assert.assertTrue(resp.contains("rw"));
+ assertTrue(resp.contains("rw"));
}
@Test
public void testSetTraceMask() throws Exception {
String gtmkResp = sendRequest("gtmk");
- Assert.assertNotNull(gtmkResp);
+ assertNotNull(gtmkResp);
gtmkResp = gtmkResp.trim();
- Assert.assertFalse(gtmkResp.isEmpty());
+ assertFalse(gtmkResp.isEmpty());
long formerMask = Long.valueOf(gtmkResp);
try {
verify(buildSetTraceMaskRequest(0), "0");
@@ -242,4 +241,5 @@ public class FourLetterWordsTest extends ClientBase {
}
return new String(baos.toByteArray());
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/FourLetterWordsWhiteListTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/FourLetterWordsWhiteListTest.java
index f5d69673e..ddb288ce5 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/FourLetterWordsWhiteListTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/FourLetterWordsWhiteListTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,22 +18,19 @@
package org.apache.zookeeper.test;
+import static org.apache.zookeeper.client.FourLetterWordMain.send4LetterWord;
+import static org.junit.Assert.assertTrue;
import java.io.IOException;
-
import org.apache.zookeeper.TestableZooKeeper;
import org.apache.zookeeper.common.X509Exception.SSLContextException;
-
-import static org.apache.zookeeper.client.FourLetterWordMain.send4LetterWord;
-
import org.apache.zookeeper.server.command.FourLetterCommands;
-import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class FourLetterWordsWhiteListTest extends ClientBase {
- protected static final Logger LOG =
- LoggerFactory.getLogger(FourLetterWordsWhiteListTest.class);
+
+ protected static final Logger LOG = LoggerFactory.getLogger(FourLetterWordsWhiteListTest.class);
/*
* ZOOKEEPER-2693: test white list of four letter words.
@@ -41,7 +38,7 @@ public class FourLetterWordsWhiteListTest extends ClientBase {
* the case (except 'stat' command which is enabled in ClientBase
* which other tests depend on.).
*/
- @Test(timeout=30000)
+ @Test(timeout = 30000)
public void testFourLetterWordsAllDisabledByDefault() throws Exception {
stopServer();
FourLetterCommands.resetWhiteList();
@@ -65,7 +62,7 @@ public class FourLetterWordsWhiteListTest extends ClientBase {
verifyAllCommandsFail();
}
- @Test(timeout=30000)
+ @Test(timeout = 30000)
public void testFourLetterWordsEnableSomeCommands() throws Exception {
stopServer();
FourLetterCommands.resetWhiteList();
@@ -92,7 +89,7 @@ public class FourLetterWordsWhiteListTest extends ClientBase {
verifyExactMatch("mntr", generateExpectedMessage("mntr"));
}
- @Test(timeout=30000)
+ @Test(timeout = 30000)
public void testISROEnabledWhenReadOnlyModeEnabled() throws Exception {
stopServer();
FourLetterCommands.resetWhiteList();
@@ -103,13 +100,13 @@ public class FourLetterWordsWhiteListTest extends ClientBase {
System.clearProperty("readonlymode.enabled");
}
- @Test(timeout=30000)
+ @Test(timeout = 30000)
public void testFourLetterWordsInvalidConfiguration() throws Exception {
stopServer();
FourLetterCommands.resetWhiteList();
- System.setProperty("zookeeper.4lw.commands.whitelist", "foo bar" +
- " foo,,, " +
- "bar :.,@#$%^&*() , , , , bar, bar, stat, ");
+ System.setProperty("zookeeper.4lw.commands.whitelist", "foo bar"
+ + " foo,,, "
+ + "bar :.,@#$%^&*() , , , , bar, bar, stat, ");
startServer();
// Just make sure we are good when admin made some mistakes in config file.
@@ -118,7 +115,7 @@ public class FourLetterWordsWhiteListTest extends ClientBase {
verifyFuzzyMatch("stat", "Outstanding");
}
- @Test(timeout=30000)
+ @Test(timeout = 30000)
public void testFourLetterWordsEnableAllCommandsThroughAsterisk() throws Exception {
stopServer();
FourLetterCommands.resetWhiteList();
@@ -127,19 +124,17 @@ public class FourLetterWordsWhiteListTest extends ClientBase {
verifyAllCommandsSuccess();
}
- @Test(timeout=30000)
+ @Test(timeout = 30000)
public void testFourLetterWordsEnableAllCommandsThroughExplicitList() throws Exception {
stopServer();
FourLetterCommands.resetWhiteList();
- System.setProperty("zookeeper.4lw.commands.whitelist",
- "ruok, envi, conf, stat, srvr, cons, dump," +
- "wchs, wchp, wchc, srst, crst, " +
- "dirs, mntr, gtmk, isro, stmk");
+ System.setProperty("zookeeper.4lw.commands.whitelist", "ruok, envi, conf, stat, srvr, cons, dump,"
+ + "wchs, wchp, wchc, srst, crst, "
+ + "dirs, mntr, gtmk, isro, stmk");
startServer();
verifyAllCommandsSuccess();
}
-
private void verifyAllCommandsSuccess() throws Exception {
verifyExactMatch("ruok", "imok");
verifyFuzzyMatch("envi", "java.version");
@@ -229,14 +224,14 @@ public class FourLetterWordsWhiteListTest extends ClientBase {
}
private String sendRequest(String cmd) throws IOException, SSLContextException {
- HostPort hpobj = ClientBase.parseHostPortList(hostPort).get(0);
- return send4LetterWord(hpobj.host, hpobj.port, cmd);
+ HostPort hpobj = ClientBase.parseHostPortList(hostPort).get(0);
+ return send4LetterWord(hpobj.host, hpobj.port, cmd);
}
private void verifyFuzzyMatch(String cmd, String expected) throws IOException, SSLContextException {
String resp = sendRequest(cmd);
LOG.info("cmd " + cmd + " expected " + expected + " got " + resp);
- Assert.assertTrue(resp.contains(expected));
+ assertTrue(resp.contains(expected));
}
private String generateExpectedMessage(String command) {
@@ -246,6 +241,7 @@ public class FourLetterWordsWhiteListTest extends ClientBase {
private void verifyExactMatch(String cmd, String expected) throws IOException, SSLContextException {
String resp = sendRequest(cmd);
LOG.info("cmd " + cmd + " expected an exact match of " + expected + "; got " + resp);
- Assert.assertTrue(resp.trim().equals(expected));
+ assertTrue(resp.trim().equals(expected));
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/GetChildren2Test.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/GetChildren2Test.java
index e41fffe08..1d8c0fd3d 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/GetChildren2Test.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/GetChildren2Test.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,20 +18,20 @@
package org.apache.zookeeper.test;
+import static org.junit.Assert.assertEquals;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
-
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
-import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.ZooDefs.Ids;
+import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;
-import org.junit.Assert;
import org.junit.Test;
public class GetChildren2Test extends ClientBase {
+
private ZooKeeper zk;
@Override
@@ -49,52 +49,45 @@ public class GetChildren2Test extends ClientBase {
}
@Test
- public void testChild()
- throws IOException, KeeperException, InterruptedException
- {
+ public void testChild() throws IOException, KeeperException, InterruptedException {
String name = "/foo";
- zk.create(name, name.getBytes(), Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk.create(name, name.getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
String childname = name + "/bar";
- zk.create(childname, childname.getBytes(), Ids.OPEN_ACL_UNSAFE,
- CreateMode.EPHEMERAL);
+ zk.create(childname, childname.getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
Stat stat = new Stat();
List<String> s = zk.getChildren(name, false, stat);
- Assert.assertEquals(stat.getCzxid(), stat.getMzxid());
- Assert.assertEquals(stat.getCzxid() + 1, stat.getPzxid());
- Assert.assertEquals(stat.getCtime(), stat.getMtime());
- Assert.assertEquals(1, stat.getCversion());
- Assert.assertEquals(0, stat.getVersion());
- Assert.assertEquals(0, stat.getAversion());
- Assert.assertEquals(0, stat.getEphemeralOwner());
- Assert.assertEquals(name.length(), stat.getDataLength());
- Assert.assertEquals(1, stat.getNumChildren());
- Assert.assertEquals(s.size(), stat.getNumChildren());
+ assertEquals(stat.getCzxid(), stat.getMzxid());
+ assertEquals(stat.getCzxid() + 1, stat.getPzxid());
+ assertEquals(stat.getCtime(), stat.getMtime());
+ assertEquals(1, stat.getCversion());
+ assertEquals(0, stat.getVersion());
+ assertEquals(0, stat.getAversion());
+ assertEquals(0, stat.getEphemeralOwner());
+ assertEquals(name.length(), stat.getDataLength());
+ assertEquals(1, stat.getNumChildren());
+ assertEquals(s.size(), stat.getNumChildren());
s = zk.getChildren(childname, false, stat);
- Assert.assertEquals(stat.getCzxid(), stat.getMzxid());
- Assert.assertEquals(stat.getCzxid(), stat.getPzxid());
- Assert.assertEquals(stat.getCtime(), stat.getMtime());
- Assert.assertEquals(0, stat.getCversion());
- Assert.assertEquals(0, stat.getVersion());
- Assert.assertEquals(0, stat.getAversion());
- Assert.assertEquals(zk.getSessionId(), stat.getEphemeralOwner());
- Assert.assertEquals(childname.length(), stat.getDataLength());
- Assert.assertEquals(0, stat.getNumChildren());
- Assert.assertEquals(s.size(), stat.getNumChildren());
+ assertEquals(stat.getCzxid(), stat.getMzxid());
+ assertEquals(stat.getCzxid(), stat.getPzxid());
+ assertEquals(stat.getCtime(), stat.getMtime());
+ assertEquals(0, stat.getCversion());
+ assertEquals(0, stat.getVersion());
+ assertEquals(0, stat.getAversion());
+ assertEquals(zk.getSessionId(), stat.getEphemeralOwner());
+ assertEquals(childname.length(), stat.getDataLength());
+ assertEquals(0, stat.getNumChildren());
+ assertEquals(s.size(), stat.getNumChildren());
}
@Test
- public void testChildren()
- throws IOException, KeeperException, InterruptedException
- {
+ public void testChildren() throws IOException, KeeperException, InterruptedException {
String name = "/foo";
- zk.create(name, name.getBytes(), Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk.create(name, name.getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
List<String> children = new ArrayList<String>();
List<String> children_s = new ArrayList<String>();
@@ -106,31 +99,31 @@ public class GetChildren2Test extends ClientBase {
children_s.add(childname_s);
}
- for(int i = 0; i < children.size(); i++) {
+ for (int i = 0; i < children.size(); i++) {
String childname = children.get(i);
- zk.create(childname, childname.getBytes(), Ids.OPEN_ACL_UNSAFE,
- CreateMode.EPHEMERAL);
+ zk.create(childname, childname.getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
Stat stat = new Stat();
List<String> s = zk.getChildren(name, false, stat);
- Assert.assertEquals(stat.getCzxid(), stat.getMzxid());
- Assert.assertEquals(stat.getCzxid() + i + 1, stat.getPzxid());
- Assert.assertEquals(stat.getCtime(), stat.getMtime());
- Assert.assertEquals(i + 1, stat.getCversion());
- Assert.assertEquals(0, stat.getVersion());
- Assert.assertEquals(0, stat.getAversion());
- Assert.assertEquals(0, stat.getEphemeralOwner());
- Assert.assertEquals(name.length(), stat.getDataLength());
- Assert.assertEquals(i + 1, stat.getNumChildren());
- Assert.assertEquals(s.size(), stat.getNumChildren());
+ assertEquals(stat.getCzxid(), stat.getMzxid());
+ assertEquals(stat.getCzxid() + i + 1, stat.getPzxid());
+ assertEquals(stat.getCtime(), stat.getMtime());
+ assertEquals(i + 1, stat.getCversion());
+ assertEquals(0, stat.getVersion());
+ assertEquals(0, stat.getAversion());
+ assertEquals(0, stat.getEphemeralOwner());
+ assertEquals(name.length(), stat.getDataLength());
+ assertEquals(i + 1, stat.getNumChildren());
+ assertEquals(s.size(), stat.getNumChildren());
}
List<String> p = zk.getChildren(name, false, null);
List<String> c_a = children_s;
List<String> c_b = p;
Collections.sort(c_a);
Collections.sort(c_b);
- Assert.assertEquals(c_a.size(), 10);
- Assert.assertEquals(c_a, c_b);
+ assertEquals(c_a.size(), 10);
+ assertEquals(c_a, c_b);
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/GetProposalFromTxnTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/GetProposalFromTxnTest.java
index 660980afe..41109916f 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/GetProposalFromTxnTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/GetProposalFromTxnTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,11 +18,12 @@
package org.apache.zookeeper.test;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
-
import org.apache.jute.Record;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.PortAssignment;
@@ -38,14 +39,14 @@ import org.apache.zookeeper.server.ZooKeeperServer;
import org.apache.zookeeper.server.quorum.Leader.Proposal;
import org.apache.zookeeper.server.util.SerializeUtils;
import org.apache.zookeeper.txn.TxnHeader;
-import org.junit.Assert;
import org.junit.Test;
/**
* Test loading committed proposal from txnlog. Learner uses these proposals to
* catch-up with leader
*/
-public class GetProposalFromTxnTest extends ZKTestCase{
+public class GetProposalFromTxnTest extends ZKTestCase {
+
private static String HOSTPORT = "127.0.0.1:" + PortAssignment.unique();
private static final int CONNECTION_TIMEOUT = 3000;
@@ -66,8 +67,7 @@ public class GetProposalFromTxnTest extends ZKTestCase{
final int PORT = Integer.parseInt(HOSTPORT.split(":")[1]);
ServerCnxnFactory f = ServerCnxnFactory.createFactory(PORT, -1);
f.startup(zks);
- Assert.assertTrue("waiting for server being up ",
- ClientBase.waitForServerUp(HOSTPORT, CONNECTION_TIMEOUT));
+ assertTrue("waiting for server being up ", ClientBase.waitForServerUp(HOSTPORT, CONNECTION_TIMEOUT));
ZooKeeper zk = ClientBase.createZKClient(HOSTPORT);
// Generate transaction so we will have some txnlog
@@ -77,8 +77,7 @@ public class GetProposalFromTxnTest extends ZKTestCase{
byte[] bytes = data.getBytes();
for (int i = 0; i < MSG_COUNT; i++) {
Stat stat = new Stat();
- zk.create("/invalidsnap-" + i, bytes, Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk.create("/invalidsnap-" + i, bytes, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
zk.getData("/invalidsnap-" + i, null, stat);
zxids[i] = stat.getCzxid();
}
@@ -90,8 +89,7 @@ public class GetProposalFromTxnTest extends ZKTestCase{
// shutdown and start zookeeper again
f.shutdown();
zks.shutdown();
- Assert.assertTrue("waiting for server to shutdown",
- ClientBase.waitForServerDown(HOSTPORT, CONNECTION_TIMEOUT));
+ assertTrue("waiting for server to shutdown", ClientBase.waitForServerDown(HOSTPORT, CONNECTION_TIMEOUT));
zks = new ZooKeeperServer(tmpDir, tmpDir, 3000);
zks.startdata();
@@ -108,8 +106,7 @@ public class GetProposalFromTxnTest extends ZKTestCase{
while (itr.hasNext()) {
Proposal proposal = itr.next();
TxnHeader hdr = new TxnHeader();
- Record rec = SerializeUtils.deserializeTxn(
- proposal.packet.getData(), hdr);
+ Record rec = SerializeUtils.deserializeTxn(proposal.packet.getData(), hdr);
if (hdr.getType() == OpCode.create) {
retrievedZxids.add(hdr.getZxid());
createCount++;
@@ -117,12 +114,10 @@ public class GetProposalFromTxnTest extends ZKTestCase{
}
// All zxid should match what we created
- Assert.assertTrue("Zxids missmatches",
- Arrays.equals(zxids, retrievedZxids.toArray(new Long[0])));
+ assertTrue("Zxids missmatches", Arrays.equals(zxids, retrievedZxids.toArray(new Long[0])));
// There should be 2000 create requests
- Assert.assertTrue("create proposal count == " + MSG_COUNT,
- (createCount == MSG_COUNT));
+ assertTrue("create proposal count == " + MSG_COUNT, (createCount == MSG_COUNT));
// We are requesting half the number of transaction from the snapshot
// this should exceed threshold (ZKDatabase.snapshotSizeFactor)
@@ -130,8 +125,9 @@ public class GetProposalFromTxnTest extends ZKTestCase{
long sizeLimit = db.calculateTxnLogSizeLimit();
itr = db.getProposalsFromTxnLog(zxids[MSG_COUNT / 2], sizeLimit);
- Assert.assertFalse("Expect empty proposal", (itr.hasNext()));
+ assertFalse("Expect empty proposal", (itr.hasNext()));
f.shutdown();
zks.shutdown();
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/HierarchicalQuorumTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/HierarchicalQuorumTest.java
index bc746e5d6..20f257b73 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/HierarchicalQuorumTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/HierarchicalQuorumTest.java
@@ -17,6 +17,8 @@
package org.apache.zookeeper.test;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
@@ -25,19 +27,17 @@ import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.Properties;
import java.util.Set;
-
-import org.apache.zookeeper.jmx.MBeanRegistry;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
import org.apache.zookeeper.PortAssignment;
import org.apache.zookeeper.TestableZooKeeper;
+import org.apache.zookeeper.jmx.MBeanRegistry;
import org.apache.zookeeper.server.quorum.QuorumPeer;
import org.apache.zookeeper.server.quorum.QuorumPeer.QuorumServer;
import org.apache.zookeeper.server.quorum.flexible.QuorumHierarchical;
-import org.junit.Assert;
import org.junit.Test;
-
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
public class HierarchicalQuorumTest extends ClientBase {
+
private static final Logger LOG = LoggerFactory.getLogger(QuorumBase.class);
File s1dir, s2dir, s3dir, s4dir, s5dir;
@@ -59,11 +59,10 @@ public class HierarchicalQuorumTest extends ClientBase {
protected int clientport3;
protected int clientport4;
protected int clientport5;
-
-
+
Properties qp;
protected final ClientHammerTest cht = new ClientHammerTest();
-
+
@Override
public void setUp() throws Exception {
setupTestEnv();
@@ -87,12 +86,12 @@ public class HierarchicalQuorumTest extends ClientBase {
clientport3 = PortAssignment.unique();
clientport4 = PortAssignment.unique();
clientport5 = PortAssignment.unique();
-
- hostPort = "127.0.0.1:" + clientport1
- + ",127.0.0.1:" + clientport2
- + ",127.0.0.1:" + clientport3
- + ",127.0.0.1:" + clientport4
- + ",127.0.0.1:" + clientport5;
+
+ hostPort = "127.0.0.1:" + clientport1
+ + ",127.0.0.1:" + clientport2
+ + ",127.0.0.1:" + clientport3
+ + ",127.0.0.1:" + clientport4
+ + ",127.0.0.1:" + clientport5;
LOG.info("Ports are: " + hostPort);
s1dir = ClientBase.createTmpDir();
@@ -101,40 +100,41 @@ public class HierarchicalQuorumTest extends ClientBase {
s4dir = ClientBase.createTmpDir();
s5dir = ClientBase.createTmpDir();
- String config = "group.1=1:2:3\n" +
- "group.2=4:5\n" +
- "weight.1=1\n" +
- "weight.2=1\n" +
- "weight.3=1\n" +
- "weight.4=0\n" +
- "weight.5=0\n" +
- "server.1=127.0.0.1:" + port1 + ":" + leport1 + ";" + clientport1 + "\n" +
- "server.2=127.0.0.1:" + port2 + ":" + leport2 + ";" + clientport2 + "\n" +
- "server.3=127.0.0.1:" + port3 + ":" + leport3 + ";" + clientport3 + "\n" +
- "server.4=127.0.0.1:" + port4 + ":" + leport4 + ";" + clientport4 + "\n" +
- "server.5=127.0.0.1:" + port5 + ":" + leport5 + ";" + clientport5 + "\n";
+ String config = "group.1=1:2:3\n"
+ + "group.2=4:5\n"
+ + "weight.1=1\n"
+ + "weight.2=1\n"
+ + "weight.3=1\n"
+ + "weight.4=0\n"
+ + "weight.5=0\n"
+ + "server.1=127.0.0.1:" + port1 + ":" + leport1 + ";" + clientport1
+ + "\n" + "server.2=127.0.0.1:" + port2 + ":" + leport2 + ";" + clientport2
+ + "\n" + "server.3=127.0.0.1:" + port3 + ":" + leport3 + ";" + clientport3
+ + "\n" + "server.4=127.0.0.1:" + port4 + ":" + leport4 + ";" + clientport4
+ + "\n" + "server.5=127.0.0.1:" + port5 + ":" + leport5 + ";" + clientport5
+ + "\n";
ByteArrayInputStream is = new ByteArrayInputStream(config.getBytes());
this.qp = new Properties();
-
+
qp.load(is);
startServers();
cht.hostPort = hostPort;
cht.setUpAll();
-
+
LOG.info("Setup finished");
}
-
+
/**
- * This method is here to keep backwards compatibility with the test code
- * written before observers.
+ * This method is here to keep backwards compatibility with the test code
+ * written before observers.
* @throws Exception
*/
void startServers() throws Exception {
startServers(false);
}
-
+
/**
* Starts 5 Learners. When withObservers == false, all 5 are Followers.
* When withObservers == true, 3 are Followers and 2 Observers.
@@ -146,67 +146,49 @@ public class HierarchicalQuorumTest extends ClientBase {
int initLimit = 3;
int syncLimit = 3;
int connectToLearnerMasterLimit = 3;
- HashMap<Long,QuorumServer> peers = new HashMap<Long,QuorumServer>();
- peers.put(Long.valueOf(1), new QuorumServer(1,
- new InetSocketAddress("127.0.0.1", port1),
- new InetSocketAddress("127.0.0.1", leport1),
- new InetSocketAddress("127.0.0.1", clientport1)));
- peers.put(Long.valueOf(2), new QuorumServer(2,
- new InetSocketAddress("127.0.0.1", port2),
- new InetSocketAddress("127.0.0.1", leport2),
- new InetSocketAddress("127.0.0.1", clientport2)));
- peers.put(Long.valueOf(3), new QuorumServer(3,
- new InetSocketAddress("127.0.0.1", port3),
- new InetSocketAddress("127.0.0.1", leport3),
- new InetSocketAddress("127.0.0.1", clientport3)));
- peers.put(Long.valueOf(4), new QuorumServer(4,
- new InetSocketAddress("127.0.0.1", port4),
- new InetSocketAddress("127.0.0.1", leport4),
- new InetSocketAddress("127.0.0.1", clientport4),
- withObservers ? QuorumPeer.LearnerType.OBSERVER
- : QuorumPeer.LearnerType.PARTICIPANT));
- peers.put(Long.valueOf(5), new QuorumServer(5,
- new InetSocketAddress("127.0.0.1", port5),
- new InetSocketAddress("127.0.0.1", leport5),
- new InetSocketAddress("127.0.0.1", clientport5),
- withObservers ? QuorumPeer.LearnerType.OBSERVER
- : QuorumPeer.LearnerType.PARTICIPANT));
+ HashMap<Long, QuorumServer> peers = new HashMap<>();
+
+ peers.put(Long.valueOf(1), new QuorumServer(1, new InetSocketAddress("127.0.0.1", port1), new InetSocketAddress("127.0.0.1", leport1), new InetSocketAddress("127.0.0.1", clientport1)));
+ peers.put(Long.valueOf(2), new QuorumServer(2, new InetSocketAddress("127.0.0.1", port2), new InetSocketAddress("127.0.0.1", leport2), new InetSocketAddress("127.0.0.1", clientport2)));
+ peers.put(Long.valueOf(3), new QuorumServer(3, new InetSocketAddress("127.0.0.1", port3), new InetSocketAddress("127.0.0.1", leport3), new InetSocketAddress("127.0.0.1", clientport3)));
+ peers.put(Long.valueOf(4), new QuorumServer(4, new InetSocketAddress("127.0.0.1", port4), new InetSocketAddress("127.0.0.1", leport4), new InetSocketAddress("127.0.0.1", clientport4), withObservers ? QuorumPeer.LearnerType.OBSERVER : QuorumPeer.LearnerType.PARTICIPANT));
+ peers.put(Long.valueOf(5), new QuorumServer(5, new InetSocketAddress("127.0.0.1", port5), new InetSocketAddress("127.0.0.1", leport5), new InetSocketAddress("127.0.0.1", clientport5), withObservers ? QuorumPeer.LearnerType.OBSERVER : QuorumPeer.LearnerType.PARTICIPANT));
LOG.info("creating QuorumPeer 1 port " + clientport1);
-
+
if (withObservers) {
- qp.setProperty("server.4", "127.0.0.1:" + port4 + ":" + leport4 + ":observer" + ";" + clientport4);
- qp.setProperty("server.5", "127.0.0.1:" + port5 + ":" + leport5 + ":observer" + ";" + clientport5);
+ qp.setProperty("server.4", "127.0.0.1:" + port4 + ":" + leport4 + ":observer" + ";" + clientport4);
+ qp.setProperty("server.5", "127.0.0.1:" + port5 + ":" + leport5 + ":observer" + ";" + clientport5);
}
- QuorumHierarchical hq1 = new QuorumHierarchical(qp);
+ QuorumHierarchical hq1 = new QuorumHierarchical(qp);
s1 = new QuorumPeer(peers, s1dir, s1dir, clientport1, 3, 1, tickTime, initLimit, syncLimit, connectToLearnerMasterLimit, hq1);
- Assert.assertEquals(clientport1, s1.getClientPort());
-
+ assertEquals(clientport1, s1.getClientPort());
+
LOG.info("creating QuorumPeer 2 port " + clientport2);
- QuorumHierarchical hq2 = new QuorumHierarchical(qp);
+ QuorumHierarchical hq2 = new QuorumHierarchical(qp);
s2 = new QuorumPeer(peers, s2dir, s2dir, clientport2, 3, 2, tickTime, initLimit, syncLimit, connectToLearnerMasterLimit, hq2);
- Assert.assertEquals(clientport2, s2.getClientPort());
-
+ assertEquals(clientport2, s2.getClientPort());
+
LOG.info("creating QuorumPeer 3 port " + clientport3);
- QuorumHierarchical hq3 = new QuorumHierarchical(qp);
+ QuorumHierarchical hq3 = new QuorumHierarchical(qp);
s3 = new QuorumPeer(peers, s3dir, s3dir, clientport3, 3, 3, tickTime, initLimit, syncLimit, connectToLearnerMasterLimit, hq3);
- Assert.assertEquals(clientport3, s3.getClientPort());
-
+ assertEquals(clientport3, s3.getClientPort());
+
LOG.info("creating QuorumPeer 4 port " + clientport4);
- QuorumHierarchical hq4 = new QuorumHierarchical(qp);
+ QuorumHierarchical hq4 = new QuorumHierarchical(qp);
s4 = new QuorumPeer(peers, s4dir, s4dir, clientport4, 3, 4, tickTime, initLimit, syncLimit, connectToLearnerMasterLimit, hq4);
if (withObservers) {
s4.setLearnerType(QuorumPeer.LearnerType.OBSERVER);
}
- Assert.assertEquals(clientport4, s4.getClientPort());
-
+ assertEquals(clientport4, s4.getClientPort());
+
LOG.info("creating QuorumPeer 5 port " + clientport5);
- QuorumHierarchical hq5 = new QuorumHierarchical(qp);
+ QuorumHierarchical hq5 = new QuorumHierarchical(qp);
s5 = new QuorumPeer(peers, s5dir, s5dir, clientport5, 3, 5, tickTime, initLimit, syncLimit, connectToLearnerMasterLimit, hq5);
if (withObservers) {
s5.setLearnerType(QuorumPeer.LearnerType.OBSERVER);
}
- Assert.assertEquals(clientport5, s5.getClientPort());
+ assertEquals(clientport5, s5.getClientPort());
LOG.info("start QuorumPeer 1");
s1.start();
@@ -220,11 +202,9 @@ public class HierarchicalQuorumTest extends ClientBase {
s5.start();
LOG.info("started QuorumPeer 5");
- LOG.info ("Closing ports " + hostPort);
+ LOG.info("Closing ports " + hostPort);
for (String hp : hostPort.split(",")) {
- Assert.assertTrue("waiting for server up",
- ClientBase.waitForServerUp(hp,
- CONNECTION_TIMEOUT));
+ assertTrue("waiting for server up", ClientBase.waitForServerUp(hp, CONNECTION_TIMEOUT));
LOG.info(hp + " is accepting client connections");
}
final int numberOfPeers = 5;
@@ -236,13 +216,11 @@ public class HierarchicalQuorumTest extends ClientBase {
ensureNames.add("InMemoryDataTree");
}
for (int i = 1; i <= numberOfPeers; i++) {
- ensureNames.add("name0=ReplicatedServer_id" + i
- + ",name1=replica." + i + ",name2=");
+ ensureNames.add("name0=ReplicatedServer_id" + i + ",name1=replica." + i + ",name2=");
}
for (int i = 1; i <= numberOfPeers; i++) {
for (int j = 1; j <= numberOfPeers; j++) {
- ensureNames.add("name0=ReplicatedServer_id" + i
- + ",name1=replica." + j);
+ ensureNames.add("name0=ReplicatedServer_id" + i + ",name1=replica." + j);
}
}
for (int i = 1; i <= numberOfPeers; i++) {
@@ -251,8 +229,7 @@ public class HierarchicalQuorumTest extends ClientBase {
JMXEnv.ensureAll(ensureNames.toArray(new String[ensureNames.size()]));
for (int i = 1; i <= numberOfPeers; i++) {
// LocalPeerBean
- String bean = MBeanRegistry.DOMAIN + ":name0=ReplicatedServer_id" + i
- + ",name1=replica." + i;
+ String bean = MBeanRegistry.DOMAIN + ":name0=ReplicatedServer_id" + i + ",name1=replica." + i;
JMXEnv.ensureBeanAttribute(bean, "ConfigVersion");
JMXEnv.ensureBeanAttribute(bean, "LearnerType");
JMXEnv.ensureBeanAttribute(bean, "ClientAddress");
@@ -265,8 +242,7 @@ public class HierarchicalQuorumTest extends ClientBase {
for (int j = 1; j <= numberOfPeers; j++) {
if (j != i) {
// RemotePeerBean
- String bean = MBeanRegistry.DOMAIN + ":name0=ReplicatedServer_id" + i
- + ",name1=replica." + j;
+ String bean = MBeanRegistry.DOMAIN + ":name0=ReplicatedServer_id" + i + ",name1=replica." + j;
JMXEnv.ensureBeanAttribute(bean, "Name");
JMXEnv.ensureBeanAttribute(bean, "LearnerType");
JMXEnv.ensureBeanAttribute(bean, "ClientAddress");
@@ -293,11 +269,9 @@ public class HierarchicalQuorumTest extends ClientBase {
shutdown(s4);
LOG.info("Shutting down server 5");
shutdown(s5);
-
+
for (String hp : hostPort.split(",")) {
- Assert.assertTrue("waiting for server down",
- ClientBase.waitForServerDown(hp,
- ClientBase.CONNECTION_TIMEOUT));
+ assertTrue("waiting for server down", ClientBase.waitForServerDown(hp, ClientBase.CONNECTION_TIMEOUT));
LOG.info(hp + " is no longer accepting client connections");
}
@@ -308,15 +282,11 @@ public class HierarchicalQuorumTest extends ClientBase {
QuorumBase.shutdown(qp);
}
- protected TestableZooKeeper createClient()
- throws IOException, InterruptedException
- {
+ protected TestableZooKeeper createClient() throws IOException, InterruptedException {
return createClient(hostPort);
}
- protected TestableZooKeeper createClient(String hp)
- throws IOException, InterruptedException
- {
+ protected TestableZooKeeper createClient(String hp) throws IOException, InterruptedException {
CountdownWatcher watcher = new CountdownWatcher();
return createClient(watcher, hp);
}
@@ -325,4 +295,5 @@ public class HierarchicalQuorumTest extends ClientBase {
public void testHierarchicalQuorum() throws Throwable {
cht.runHammer(5, 10);
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/IntegrityCheck.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/IntegrityCheck.java
index 80e1399f5..be67827d3 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/IntegrityCheck.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/IntegrityCheck.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -31,22 +31,23 @@ package org.apache.zookeeper.test;
* a value that we have previously read or set. (Each time we set a value, the
* value will be one more than the previous set.)
*/
+
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
-
-import org.apache.zookeeper.server.ExitCode;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
+import org.apache.zookeeper.AsyncCallback.DataCallback;
+import org.apache.zookeeper.AsyncCallback.StatCallback;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;
-import org.apache.zookeeper.AsyncCallback.DataCallback;
-import org.apache.zookeeper.AsyncCallback.StatCallback;
import org.apache.zookeeper.data.Stat;
+import org.apache.zookeeper.server.ExitCode;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
public class IntegrityCheck implements StatCallback, DataCallback {
+
private static final Logger LOG = LoggerFactory.getLogger(IntegrityCheck.class);
ZooKeeper zk;
@@ -78,28 +79,27 @@ public class IntegrityCheck implements StatCallback, DataCallback {
}
}
- IntegrityCheck(String hostPort, String path, int count) throws
- Exception {
+ IntegrityCheck(String hostPort, String path, int count) throws Exception {
zk = ClientBase.createZKClient(hostPort);
this.path = path;
this.count = count;
}
public void run() throws InterruptedException, KeeperException {
- try{
- LOG.warn("Creating znodes for "+path);
+ try {
+ LOG.warn("Creating znodes for " + path);
doCreate();
- LOG.warn("Staring the test loop for "+path);
+ LOG.warn("Staring the test loop for " + path);
while (true) {
- LOG.warn("Staring write cycle for "+path);
+ LOG.warn("Staring write cycle for " + path);
doPopulate();
waitOutstanding();
- LOG.warn("Staring read cycle for "+path);
+ LOG.warn("Staring read cycle for " + path);
readAll();
waitOutstanding();
}
- }finally{
- LOG.warn("Test loop terminated for "+path);
+ } finally {
+ LOG.warn("Test loop terminated for " + path);
}
}
@@ -114,21 +114,22 @@ public class IntegrityCheck implements StatCallback, DataCallback {
void doCreate() throws InterruptedException, KeeperException {
// create top level znode
- try{
+ try {
zk.create(path, null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
- }catch(KeeperException.NodeExistsException e){
+ } catch (KeeperException.NodeExistsException e) {
// ignore duplicate create
}
iteration++;
- byte v[] = ("" + iteration).getBytes();
+ byte[] v = ("" + iteration).getBytes();
// create child znodes
for (int i = 0; i < count; i++) {
String cpath = path + "/" + i;
- try{
- if(i%10==0)
- LOG.warn("Creating znode "+cpath);
+ try {
+ if (i % 10 == 0) {
+ LOG.warn("Creating znode " + cpath);
+ }
zk.create(cpath, v, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
- }catch(KeeperException.NodeExistsException e){
+ } catch (KeeperException.NodeExistsException e) {
// ignore duplicate create
}
lastValue.put(cpath, v);
@@ -137,7 +138,7 @@ public class IntegrityCheck implements StatCallback, DataCallback {
void doPopulate() {
iteration++;
- byte v[] = ("" + iteration).getBytes();
+ byte[] v = ("" + iteration).getBytes();
for (int i = 0; i < count; i++) {
String cpath = path + "/" + i;
zk.setData(cpath, v, -1, this, v);
@@ -145,8 +146,8 @@ public class IntegrityCheck implements StatCallback, DataCallback {
}
}
- synchronized void ensureConnected(){
- while(zk.getState()!=ZooKeeper.States.CONNECTED){
+ synchronized void ensureConnected() {
+ while (zk.getState() != ZooKeeper.States.CONNECTED) {
try {
wait();
} catch (InterruptedException e) {
@@ -163,23 +164,23 @@ public class IntegrityCheck implements StatCallback, DataCallback {
System.err.println("USAGE: IntegrityCheck zookeeperHostPort znode #children");
return;
}
- int childrenCount=0;
+ int childrenCount = 0;
try {
- childrenCount=Integer.parseInt(args[2]);
+ childrenCount = Integer.parseInt(args[2]);
} catch (NumberFormatException e) {
e.printStackTrace();
System.exit(ExitCode.UNEXPECTED_ERROR.getValue());
}
- try{
- final IntegrityCheck ctest = new IntegrityCheck(args[0], args[1],childrenCount);
+ try {
+ final IntegrityCheck ctest = new IntegrityCheck(args[0], args[1], childrenCount);
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
- System.out.println(new Date().toString()+": Error count = " + ctest.errorCount);
+ System.out.println(new Date().toString() + ": Error count = " + ctest.errorCount);
}
});
- while(true){
- try{
+ while (true) {
+ try {
ctest.ensureConnected();
ctest.run();
} catch (Exception e) {
@@ -199,8 +200,8 @@ public class IntegrityCheck implements StatCallback, DataCallback {
decOutstanding();
}
- 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) {
if (rc == 0) {
String string = new String(data);
String lastString = null;
@@ -208,14 +209,13 @@ public class IntegrityCheck implements StatCallback, DataCallback {
if (v != null) {
lastString = new String(v);
}
- if (lastString != null
- && Integer.parseInt(string) < Integer.parseInt(lastString)) {
- LOG.error("ERROR: Got " + string + " expected >= "
- + lastString);
+ if (lastString != null && Integer.parseInt(string) < Integer.parseInt(lastString)) {
+ LOG.error("ERROR: Got " + string + " expected >= " + lastString);
errorCount++;
}
lastValue.put(path, (byte[]) ctx);
}
decOutstanding();
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/InvalidSnapshotTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/InvalidSnapshotTest.java
index 7de4c175f..9f458cb77 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/InvalidSnapshotTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/InvalidSnapshotTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -19,9 +19,8 @@
package org.apache.zookeeper.test;
import static org.apache.zookeeper.test.ClientBase.CONNECTION_TIMEOUT;
-
+import static org.junit.Assert.assertTrue;
import java.io.File;
-
import org.apache.zookeeper.PortAssignment;
import org.apache.zookeeper.ZKTestCase;
import org.apache.zookeeper.ZooKeeper;
@@ -29,18 +28,16 @@ import org.apache.zookeeper.server.ServerCnxnFactory;
import org.apache.zookeeper.server.SnapshotFormatter;
import org.apache.zookeeper.server.SyncRequestProcessor;
import org.apache.zookeeper.server.ZooKeeperServer;
-import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-public class InvalidSnapshotTest extends ZKTestCase{
- private final static Logger LOG = LoggerFactory.getLogger(InvalidSnapshotTest.class);
- private static final String HOSTPORT =
- "127.0.0.1:" + PortAssignment.unique();
+public class InvalidSnapshotTest extends ZKTestCase {
+
+ private static final Logger LOG = LoggerFactory.getLogger(InvalidSnapshotTest.class);
+ private static final String HOSTPORT = "127.0.0.1:" + PortAssignment.unique();
- private static final File testData = new File(
- System.getProperty("test.data.dir", "src/test/resources/data"));
+ private static final File testData = new File(System.getProperty("test.data.dir", "src/test/resources/data"));
/**
* Verify the LogFormatter by running it on a known file.
@@ -64,7 +61,7 @@ public class InvalidSnapshotTest extends ZKTestCase{
String[] args = {snapfile.getCanonicalFile().toString()};
SnapshotFormatter.main(args);
}
-
+
/**
* Verify the SnapshotFormatter by running it on a known file with one null data.
*/
@@ -75,7 +72,7 @@ public class InvalidSnapshotTest extends ZKTestCase{
String[] args = {snapfile.getCanonicalFile().toString()};
SnapshotFormatter.main(args);
}
-
+
/**
* test the snapshot
* @throws Exception an exception could be expected
@@ -89,22 +86,20 @@ public class InvalidSnapshotTest extends ZKTestCase{
ServerCnxnFactory f = ServerCnxnFactory.createFactory(PORT, -1);
f.startup(zks);
LOG.info("starting up the zookeeper server .. waiting");
- Assert.assertTrue("waiting for server being up",
- ClientBase.waitForServerUp(HOSTPORT, CONNECTION_TIMEOUT));
+ assertTrue("waiting for server being up", ClientBase.waitForServerUp(HOSTPORT, CONNECTION_TIMEOUT));
ZooKeeper zk = ClientBase.createZKClient(HOSTPORT);
try {
// we know this from the data files
// this node is the last node in the snapshot
- Assert.assertTrue(zk.exists("/9/9/8", false) != null);
+ assertTrue(zk.exists("/9/9/8", false) != null);
} finally {
zk.close();
}
f.shutdown();
zks.shutdown();
- Assert.assertTrue("waiting for server down",
- ClientBase.waitForServerDown(HOSTPORT,
- ClientBase.CONNECTION_TIMEOUT));
+ assertTrue("waiting for server down", ClientBase.waitForServerDown(HOSTPORT, ClientBase.CONNECTION_TIMEOUT));
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/JMXEnv.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/JMXEnv.java
index bec8580b2..9761f33f7 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/JMXEnv.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/JMXEnv.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,6 +18,8 @@
package org.apache.zookeeper.test;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.fail;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
@@ -25,7 +27,6 @@ import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Pattern;
-
import javax.management.MBeanServer;
import javax.management.MBeanServerConnection;
import javax.management.MalformedObjectNameException;
@@ -35,14 +36,12 @@ import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXConnectorServer;
import javax.management.remote.JMXConnectorServerFactory;
import javax.management.remote.JMXServiceURL;
-
-
import org.apache.zookeeper.jmx.MBeanRegistry;
-import org.junit.Assert;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class JMXEnv {
+
protected static final Logger LOG = LoggerFactory.getLogger(JMXEnv.class);
private static JMXConnectorServer cs;
@@ -50,16 +49,16 @@ public class JMXEnv {
public static void setUp() throws IOException {
MBeanServer mbs = MBeanRegistry.getInstance().getPlatformMBeanServer();
-
+
JMXServiceURL url = new JMXServiceURL("service:jmx:rmi://127.0.0.1");
cs = JMXConnectorServerFactory.newJMXConnectorServer(url, null, mbs);
cs.start();
- JMXServiceURL addr = cs.getAddress();
-
- cc = JMXConnectorFactory.connect(addr);
+ JMXServiceURL addr = cs.getAddress();
+
+ cc = JMXConnectorFactory.connect(addr);
}
-
+
public static void tearDown() {
try {
if (cc != null) {
@@ -67,7 +66,7 @@ public class JMXEnv {
}
} catch (IOException e) {
LOG.warn("Unexpected, ignoring", e);
-
+
}
cc = null;
try {
@@ -76,11 +75,11 @@ public class JMXEnv {
}
} catch (IOException e) {
LOG.warn("Unexpected, ignoring", e);
-
+
}
cs = null;
}
-
+
public static MBeanServerConnection conn() throws IOException {
return cc.getMBeanServerConnection();
}
@@ -97,9 +96,7 @@ public class JMXEnv {
* @throws IOException
* @throws InterruptedException
*/
- public static Set<ObjectName> ensureAll(String... expectedNames)
- throws IOException, InterruptedException
- {
+ public static Set<ObjectName> ensureAll(String... expectedNames) throws IOException, InterruptedException {
Set<ObjectName> beans;
Set<ObjectName> found;
int nTry = 0;
@@ -108,12 +105,11 @@ public class JMXEnv {
Thread.sleep(100);
}
try {
- beans = conn().queryNames(
- new ObjectName(MBeanRegistry.DOMAIN + ":*"), null);
+ beans = conn().queryNames(new ObjectName(MBeanRegistry.DOMAIN + ":*"), null);
} catch (MalformedObjectNameException e) {
throw new RuntimeException(e);
}
-
+
found = new HashSet<ObjectName>();
for (String name : expectedNames) {
LOG.info("expect:" + name);
@@ -127,8 +123,7 @@ public class JMXEnv {
beans.removeAll(found);
}
} while ((expectedNames.length != found.size()) && (nTry < 600));
- Assert.assertEquals("expected " + Arrays.toString(expectedNames),
- expectedNames.length, found.size());
+ assertEquals("expected " + Arrays.toString(expectedNames), expectedNames.length, found.size());
return beans;
}
@@ -142,21 +137,17 @@ public class JMXEnv {
* @throws IOException
* @throws InterruptedException
*/
- public static Set<ObjectName> ensureOnly(String... expectedNames)
- throws IOException, InterruptedException
- {
+ public static Set<ObjectName> ensureOnly(String... expectedNames) throws IOException, InterruptedException {
LOG.info("ensureOnly:" + Arrays.toString(expectedNames));
Set<ObjectName> beans = ensureAll(expectedNames);
for (ObjectName bean : beans) {
LOG.info("unexpected:" + bean.toString());
}
- Assert.assertEquals(0, beans.size());
+ assertEquals(0, beans.size());
return beans;
}
-
- public static void ensureNone(String... expectedNames)
- throws IOException, InterruptedException
- {
+
+ public static void ensureNone(String... expectedNames) throws IOException, InterruptedException {
Set<ObjectName> beans;
int nTry = 0;
boolean foundUnexpected = false;
@@ -166,13 +157,12 @@ public class JMXEnv {
Thread.sleep(100);
}
try {
- beans = conn().queryNames(
- new ObjectName(MBeanRegistry.DOMAIN + ":*"), null);
+ beans = conn().queryNames(new ObjectName(MBeanRegistry.DOMAIN + ":*"), null);
} catch (MalformedObjectNameException e) {
throw new RuntimeException(e);
}
-
- foundUnexpected = false;
+
+ foundUnexpected = false;
for (String name : expectedNames) {
for (ObjectName bean : beans) {
if (bean.toString().contains(name)) {
@@ -192,7 +182,7 @@ public class JMXEnv {
for (ObjectName bean : beans) {
LOG.info("bean:" + bean.toString());
}
- Assert.fail(unexpectedName);
+ fail(unexpectedName);
}
}
@@ -200,8 +190,7 @@ public class JMXEnv {
LOG.info("JMXEnv.dump() follows");
Set<ObjectName> beans;
try {
- beans = conn().queryNames(
- new ObjectName(MBeanRegistry.DOMAIN + ":*"), null);
+ beans = conn().queryNames(new ObjectName(MBeanRegistry.DOMAIN + ":*"), null);
} catch (MalformedObjectNameException e) {
throw new RuntimeException(e);
}
@@ -215,18 +204,17 @@ public class JMXEnv {
* are components of the name. It waits in a loop up to 60 seconds before
* failing if there is a mismatch. This will return the beans which are not
* matched.
- *
+ *
* https://issues.apache.org/jira/browse/ZOOKEEPER-1858
- *
+ *
* @param expectedNames
* - expected beans
* @return the beans which are not matched with the given expected names
- *
+ *
* @throws IOException
* @throws InterruptedException
*/
- public static Set<ObjectName> ensureParent(String... expectedNames)
- throws IOException, InterruptedException {
+ public static Set<ObjectName> ensureParent(String... expectedNames) throws IOException, InterruptedException {
LOG.info("ensureParent:" + Arrays.toString(expectedNames));
Set<ObjectName> beans;
@@ -237,8 +225,7 @@ public class JMXEnv {
Thread.sleep(500);
}
try {
- beans = conn().queryNames(
- new ObjectName(MBeanRegistry.DOMAIN + ":*"), null);
+ beans = conn().queryNames(new ObjectName(MBeanRegistry.DOMAIN + ":*"), null);
} catch (MalformedObjectNameException e) {
throw new RuntimeException(e);
}
@@ -256,8 +243,7 @@ public class JMXEnv {
beans.removeAll(found);
}
} while (expectedNames.length != found.size() && nTry < 120);
- Assert.assertEquals("expected " + Arrays.toString(expectedNames),
- expectedNames.length, found.size());
+ assertEquals("expected " + Arrays.toString(expectedNames), expectedNames.length, found.size());
return beans;
}
@@ -275,11 +261,9 @@ public class JMXEnv {
*
* @throws Exception
*/
- public static Object ensureBeanAttribute(String expectedName,
- String expectedAttribute) throws Exception {
+ public static Object ensureBeanAttribute(String expectedName, String expectedAttribute) throws Exception {
String value = "";
- LOG.info("ensure bean:{}, attribute:{}", new Object[] { expectedName,
- expectedAttribute });
+ LOG.info("ensure bean:{}, attribute:{}", new Object[]{expectedName, expectedAttribute});
Set<ObjectName> beans;
int nTry = 0;
@@ -288,8 +272,7 @@ public class JMXEnv {
Thread.sleep(500);
}
try {
- beans = conn().queryNames(
- new ObjectName(MBeanRegistry.DOMAIN + ":*"), null);
+ beans = conn().queryNames(new ObjectName(MBeanRegistry.DOMAIN + ":*"), null);
} catch (MalformedObjectNameException e) {
throw new RuntimeException(e);
}
@@ -297,50 +280,39 @@ public class JMXEnv {
for (ObjectName bean : beans) {
// check the existence of name in bean
if (bean.toString().equals(expectedName)) {
- LOG.info("found:{} {}", new Object[] { expectedName, bean });
+ LOG.info("found:{} {}", new Object[]{expectedName, bean});
return conn().getAttribute(bean, expectedAttribute);
}
}
} while (nTry < 120);
- Assert.fail("Failed to find bean:" + expectedName + ", attribute:"
- + expectedAttribute);
+ fail("Failed to find bean:" + expectedName + ", attribute:" + expectedAttribute);
return value;
}
/**
* Comparing that the given name exists in the bean. For component beans,
* the component name will be present at the end of the bean name
- *
+ *
* For example 'StandaloneServer' will present in the bean name like
* 'org.apache.ZooKeeperService:name0=StandaloneServer_port-1'
*/
private static boolean compare(String bean, String name) {
String[] names = bean.split("=");
- if (names.length > 0 && names[names.length - 1].contains(name)) {
- return true;
- }
- return false;
+ return names.length > 0 && names[names.length - 1].contains(name);
}
- static Pattern standaloneRegEx = Pattern.compile(
- "^org.apache.ZooKeeperService:name0=StandaloneServer_port-?\\d+$"
- );
- static Pattern instanceRegEx = Pattern.compile(
- "^org.apache.ZooKeeperService:name0=ReplicatedServer_id(\\d+)" +
- ",name1=replica.(\\d+),name2=(Follower|Leader)$"
- );
- static Pattern observerRegEx = Pattern.compile(
- "^org.apache.ZooKeeperService:name0=ReplicatedServer_id(-?\\d+)" +
- ",name1=replica.(-?\\d+),name2=(StandaloneServer_port-?\\d+)$"
- );
+ static Pattern standaloneRegEx = Pattern.compile("^org.apache.ZooKeeperService:name0=StandaloneServer_port-?\\d+$");
+ static Pattern instanceRegEx = Pattern.compile("^org.apache.ZooKeeperService:name0=ReplicatedServer_id(\\d+)"
+ + ",name1=replica.(\\d+),name2=(Follower|Leader)$");
+ static Pattern observerRegEx = Pattern.compile("^org.apache.ZooKeeperService:name0=ReplicatedServer_id(-?\\d+)"
+ + ",name1=replica.(-?\\d+),name2=(StandaloneServer_port-?\\d+)$");
static List<Pattern> beanPatterns = Arrays.asList(standaloneRegEx, instanceRegEx, observerRegEx);
public static List<ObjectName> getServerBeans() throws IOException {
ArrayList<ObjectName> serverBeans = new ArrayList<>();
Set<ObjectName> beans;
try {
- beans = conn().queryNames(
- new ObjectName(MBeanRegistry.DOMAIN + ":*"), null);
+ beans = conn().queryNames(new ObjectName(MBeanRegistry.DOMAIN + ":*"), null);
} catch (MalformedObjectNameException e) {
throw new RuntimeException(e);
}
@@ -363,4 +335,5 @@ public class JMXEnv {
}
return serverBeans.get(0);
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/KeeperStateTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/KeeperStateTest.java
index f849eab3e..15b945566 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/KeeperStateTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/KeeperStateTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,23 +18,24 @@
package org.apache.zookeeper.test;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
import java.util.EnumSet;
-
-import org.apache.zookeeper.ZKTestCase;
import org.apache.zookeeper.KeeperException.Code;
import org.apache.zookeeper.Watcher.Event.KeeperState;
-import org.junit.Assert;
+import org.apache.zookeeper.ZKTestCase;
import org.junit.Test;
public class KeeperStateTest extends ZKTestCase {
-
+
@Test
public void testIntConversion() {
// Ensure that we can convert all valid integers to KeeperStates
EnumSet<KeeperState> allStates = EnumSet.allOf(KeeperState.class);
- for(KeeperState as : allStates) {
- Assert.assertEquals(as, KeeperState.fromInt( as.getIntValue() ) );
+ for (KeeperState as : allStates) {
+ assertEquals(as, KeeperState.fromInt(as.getIntValue()));
}
}
@@ -42,8 +43,8 @@ public class KeeperStateTest extends ZKTestCase {
public void testInvalidIntConversion() {
try {
KeeperState.fromInt(324142);
- Assert.fail("Was able to create an invalid KeeperState via an integer");
- } catch(RuntimeException re) {
+ fail("Was able to create an invalid KeeperState via an integer");
+ } catch (RuntimeException re) {
// we're good.
}
@@ -58,7 +59,7 @@ public class KeeperStateTest extends ZKTestCase {
int test = 1;
switch (test) {
case Code.Ok:
- Assert.assertTrue(true);
+ assertTrue(true);
break;
}
}
@@ -69,8 +70,9 @@ public class KeeperStateTest extends ZKTestCase {
Code test = Code.OK;
switch (test) {
case OK:
- Assert.assertTrue(true);
+ assertTrue(true);
break;
}
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/KeyAuthClientTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/KeyAuthClientTest.java
index d685cf535..8618cfb93 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/KeyAuthClientTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/KeyAuthClientTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,19 +18,19 @@
package org.apache.zookeeper.test;
+import static org.junit.Assert.fail;
+import java.util.List;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.ACL;
-import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.util.List;
-
public class KeyAuthClientTest extends ClientBase {
+
private static final Logger LOG = LoggerFactory.getLogger(KeyAuthClientTest.class);
static {
@@ -64,7 +64,7 @@ public class KeyAuthClientTest extends ClientBase {
zk.setData("/key", "5".getBytes(), -1);
Thread.sleep(1000);
} catch (KeeperException e) {
- Assert.fail("test failed :" + e);
+ fail("test failed :" + e);
} finally {
zk.close();
}
@@ -74,13 +74,13 @@ public class KeyAuthClientTest extends ClientBase {
ZooKeeper zk = createClient();
try {
zk.getData("/abc", false, null);
- Assert.fail("Should not be able to get data");
+ fail("Should not be able to get data");
} catch (KeeperException correct) {
// correct
}
try {
zk.setData("/abc", "testData2".getBytes(), -1);
- Assert.fail("Should not be able to set data");
+ fail("Should not be able to set data");
} catch (KeeperException correct) {
// correct
} finally {
@@ -97,7 +97,7 @@ public class KeyAuthClientTest extends ClientBase {
zk.getData("/abc", false, null);
zk.setData("/abc", "testData3".getBytes(), -1);
} catch (KeeperException.AuthFailedException e) {
- Assert.fail("test failed :" + e);
+ fail("test failed :" + e);
} finally {
zk.close();
}
@@ -112,7 +112,7 @@ public class KeyAuthClientTest extends ClientBase {
zk.getData("/abc", false, null);
zk.setData("/abc", "testData3".getBytes(), -1);
} catch (KeeperException.AuthFailedException e) {
- Assert.fail("test failed :" + e);
+ fail("test failed :" + e);
} finally {
zk.close();
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/LeaderSessionTrackerTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/LeaderSessionTrackerTest.java
index a45b9cbff..cc92efae4 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/LeaderSessionTrackerTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/LeaderSessionTrackerTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,11 +18,11 @@
package org.apache.zookeeper.test;
-
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
import java.io.ByteArrayOutputStream;
import java.nio.ByteBuffer;
import java.util.ArrayList;
-
import org.apache.jute.BinaryOutputArchive;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.ZKTestCase;
@@ -35,7 +35,6 @@ import org.apache.zookeeper.proto.CreateRequest;
import org.apache.zookeeper.server.Request;
import org.apache.zookeeper.server.quorum.QuorumPeer;
import org.junit.After;
-import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
@@ -48,8 +47,7 @@ import org.slf4j.LoggerFactory;
*/
public class LeaderSessionTrackerTest extends ZKTestCase {
- protected static final Logger LOG = LoggerFactory
- .getLogger(LeaderSessionTrackerTest.class);
+ protected static final Logger LOG = LoggerFactory.getLogger(LeaderSessionTrackerTest.class);
QuorumUtil qu;
@@ -90,32 +88,28 @@ public class LeaderSessionTrackerTest extends ZKTestCase {
ZooKeeper zk = ClientBase.createZKClient(qu.getConnectString(leader));
- CreateRequest createRequest = new CreateRequest("/impossible",
- new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL.toFlag());
+ CreateRequest createRequest = new CreateRequest("/impossible", new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL.toFlag());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
BinaryOutputArchive boa = BinaryOutputArchive.getArchive(baos);
createRequest.serialize(boa, "request");
ByteBuffer bb = ByteBuffer.wrap(baos.toByteArray());
// Mimic sessionId generated by follower's local session tracker
- long sid = qu.getFollowerQuorumPeers().get(0).getActiveServer()
- .getServerId();
+ long sid = qu.getFollowerQuorumPeers().get(0).getActiveServer().getServerId();
long fakeSessionId = (sid << 56) + 1;
LOG.info("Fake session Id: " + Long.toHexString(fakeSessionId));
- Request request = new Request(null, fakeSessionId, 0, OpCode.create,
- bb, new ArrayList<Id>());
+ Request request = new Request(null, fakeSessionId, 0, OpCode.create, bb, new ArrayList<Id>());
// Submit request directly to leader
leader.getActiveServer().submitRequest(request);
// Make sure that previous request is finished
- zk.create("/ok", new byte[0], Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk.create("/ok", new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
Stat stat = zk.exists("/impossible", null);
- Assert.assertEquals("Node from fake session get created", null, stat);
+ assertEquals("Node from fake session get created", null, stat);
}
@@ -132,32 +126,29 @@ public class LeaderSessionTrackerTest extends ZKTestCase {
ZooKeeper zk = ClientBase.createZKClient(qu.getConnectString(leader));
- CreateRequest createRequest = new CreateRequest("/success",
- new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT.toFlag());
+ CreateRequest createRequest = new CreateRequest("/success", new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT.toFlag());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
BinaryOutputArchive boa = BinaryOutputArchive.getArchive(baos);
createRequest.serialize(boa, "request");
ByteBuffer bb = ByteBuffer.wrap(baos.toByteArray());
// Mimic sessionId generated by follower's local session tracker
- long sid = qu.getFollowerQuorumPeers().get(0).getActiveServer()
- .getServerId();
+ long sid = qu.getFollowerQuorumPeers().get(0).getActiveServer().getServerId();
long locallSession = (sid << 56) + 1;
LOG.info("Local session Id: " + Long.toHexString(locallSession));
- Request request = new Request(null, locallSession, 0, OpCode.create,
- bb, new ArrayList<Id>());
+ Request request = new Request(null, locallSession, 0, OpCode.create, bb, new ArrayList<Id>());
// Submit request directly to leader
leader.getActiveServer().submitRequest(request);
// Make sure that previous request is finished
- zk.create("/ok", new byte[0], Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk.create("/ok", new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
Stat stat = zk.exists("/success", null);
- Assert.assertTrue("Request from local sesson failed", stat != null);
+ assertTrue("Request from local sesson failed", stat != null);
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/LoadFromLogNoServerTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/LoadFromLogNoServerTest.java
index bf0efd7b9..6cb79c666 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/LoadFromLogNoServerTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/LoadFromLogNoServerTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,6 +18,14 @@
package org.apache.zookeeper.test;
+import static org.junit.Assert.assertNotEquals;
+import static org.junit.Assert.assertTrue;
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.FileInputStream;
+import java.nio.ByteBuffer;
+import java.util.ArrayList;
+import java.util.List;
import org.apache.jute.BinaryInputArchive;
import org.apache.jute.BinaryOutputArchive;
import org.apache.jute.Record;
@@ -35,19 +43,12 @@ import org.apache.zookeeper.txn.DeleteTxn;
import org.apache.zookeeper.txn.MultiTxn;
import org.apache.zookeeper.txn.Txn;
import org.apache.zookeeper.txn.TxnHeader;
-import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.io.ByteArrayOutputStream;
-import java.io.File;
-import java.io.FileInputStream;
-import java.nio.ByteBuffer;
-import java.util.ArrayList;
-import java.util.List;
-
public class LoadFromLogNoServerTest extends ZKTestCase {
+
protected static final Logger LOG = LoggerFactory.getLogger(LoadFromLogNoServerTest.class);
/**
@@ -65,8 +66,7 @@ public class LoadFromLogNoServerTest extends ZKTestCase {
DataTree dt = new DataTree();
dt.createNode("/test", new byte[0], null, 0, -1, 1, 1);
for (count = 1; count <= 3; count++) {
- dt.createNode("/test/" + count, new byte[0], null, 0, -1, count,
- Time.currentElapsedTime());
+ dt.createNode("/test/" + count, new byte[0], null, 0, -1, count, Time.currentElapsedTime());
}
long digestBefore = dt.getTreeDigest();
@@ -75,25 +75,22 @@ public class LoadFromLogNoServerTest extends ZKTestCase {
// Make create to fail, then verify cversion.
LOG.info("Attempting to create " + "/test/" + (count - 1));
doOp(logFile, ZooDefs.OpCode.create, "/test/" + (count - 1), dt, zk, -1);
- Assert.assertNotEquals(digestBefore, dt.getTreeDigest());
+ assertNotEquals(digestBefore, dt.getTreeDigest());
LOG.info("Attempting to create " + "/test/" + (count - 1));
digestBefore = dt.getTreeDigest();
- doOp(logFile, ZooDefs.OpCode.create, "/test/" + (count - 1), dt, zk,
- zk.stat.getCversion() + 1);
- Assert.assertNotEquals(digestBefore, dt.getTreeDigest());
+ doOp(logFile, ZooDefs.OpCode.create, "/test/" + (count - 1), dt, zk, zk.stat.getCversion() + 1);
+ assertNotEquals(digestBefore, dt.getTreeDigest());
LOG.info("Attempting to create " + "/test/" + (count - 1));
digestBefore = dt.getTreeDigest();
- doOp(logFile, ZooDefs.OpCode.multi, "/test/" + (count - 1), dt, zk,
- zk.stat.getCversion() + 1);
- Assert.assertNotEquals(digestBefore, dt.getTreeDigest());
+ doOp(logFile, ZooDefs.OpCode.multi, "/test/" + (count - 1), dt, zk, zk.stat.getCversion() + 1);
+ assertNotEquals(digestBefore, dt.getTreeDigest());
LOG.info("Attempting to create " + "/test/" + (count - 1));
digestBefore = dt.getTreeDigest();
- doOp(logFile, ZooDefs.OpCode.multi, "/test/" + (count - 1), dt, zk,
- -1);
- Assert.assertNotEquals(digestBefore, dt.getTreeDigest());
+ doOp(logFile, ZooDefs.OpCode.multi, "/test/" + (count - 1), dt, zk, -1);
+ assertNotEquals(digestBefore, dt.getTreeDigest());
// Make delete fo fail, then verify cversion.
// this doesn't happen anymore, we only set the cversion on create
@@ -108,8 +105,7 @@ public class LoadFromLogNoServerTest extends ZKTestCase {
* Does create/delete depending on the type and verifies
* if cversion before the operation is 1 less than cversion afer.
*/
- private void doOp(FileTxnSnapLog logFile, int type, String path,
- DataTree dt, DataNode parent, int cversion) throws Exception {
+ private void doOp(FileTxnSnapLog logFile, int type, String path, DataTree dt, DataNode parent, int cversion) throws Exception {
int lastSlash = path.lastIndexOf('/');
String parentName = path.substring(0, lastSlash);
@@ -127,27 +123,22 @@ public class LoadFromLogNoServerTest extends ZKTestCase {
TxnHeader txnHeader = null;
if (type == ZooDefs.OpCode.delete) {
txn = new DeleteTxn(path);
- txnHeader = new TxnHeader(0xabcd, 0x123, prevPzxid + 1,
- Time.currentElapsedTime(), ZooDefs.OpCode.delete);
+ txnHeader = new TxnHeader(0xabcd, 0x123, prevPzxid + 1, Time.currentElapsedTime(), ZooDefs.OpCode.delete);
} else if (type == ZooDefs.OpCode.create) {
- txnHeader = new TxnHeader(0xabcd, 0x123, prevPzxid + 1,
- Time.currentElapsedTime(), ZooDefs.OpCode.create);
+ txnHeader = new TxnHeader(0xabcd, 0x123, prevPzxid + 1, Time.currentElapsedTime(), ZooDefs.OpCode.create);
txn = new CreateTxn(path, new byte[0], null, false, cversion);
- }
- else if (type == ZooDefs.OpCode.multi) {
- txnHeader = new TxnHeader(0xabcd, 0x123, prevPzxid + 1,
- Time.currentElapsedTime(), ZooDefs.OpCode.create);
+ } else if (type == ZooDefs.OpCode.multi) {
+ txnHeader = new TxnHeader(0xabcd, 0x123, prevPzxid + 1, Time.currentElapsedTime(), ZooDefs.OpCode.create);
txn = new CreateTxn(path, new byte[0], null, false, cversion);
List<Txn> txnList = new ArrayList<Txn>();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
BinaryOutputArchive boa = BinaryOutputArchive.getArchive(baos);
- txn.serialize(boa, "request") ;
+ txn.serialize(boa, "request");
ByteBuffer bb = ByteBuffer.wrap(baos.toByteArray());
- Txn txact = new Txn(ZooDefs.OpCode.create, bb.array());
+ Txn txact = new Txn(ZooDefs.OpCode.create, bb.array());
txnList.add(txact);
txn = new MultiTxn(txnList);
- txnHeader = new TxnHeader(0xabcd, 0x123, prevPzxid + 1,
- Time.currentElapsedTime(), ZooDefs.OpCode.multi);
+ txnHeader = new TxnHeader(0xabcd, 0x123, prevPzxid + 1, Time.currentElapsedTime(), ZooDefs.OpCode.multi);
}
logFile.processTransaction(txnHeader, dt, null, txn);
@@ -159,11 +150,18 @@ public class LoadFromLogNoServerTest extends ZKTestCase {
childStr.append(s).append(" ");
}
LOG.info("Children: " + childStr + " for " + parentName);
- LOG.info("(cverions, pzxid): " +newCversion + ", " + newPzxid);
- Assert.assertTrue(type + " <cversion, pzxid> verification failed. Expected: <" +
- (prevCversion + 1) + ", " + (prevPzxid + 1) + ">, found: <" +
- newCversion + ", " + newPzxid + ">",
- (newCversion == prevCversion + 1 && newPzxid == prevPzxid + 1));
+ LOG.info("(cverions, pzxid): " + newCversion + ", " + newPzxid);
+ assertTrue(type
+ + " <cversion, pzxid> verification failed. Expected: <"
+ + (prevCversion + 1)
+ + ", "
+ + (prevPzxid
+ + 1)
+ + ">, found: <"
+ + newCversion
+ + ", "
+ + newPzxid
+ + ">", (newCversion == prevCversion + 1 && newPzxid == prevPzxid + 1));
}
/**
@@ -174,19 +172,15 @@ public class LoadFromLogNoServerTest extends ZKTestCase {
public void testPad() throws Exception {
File tmpDir = ClientBase.createTmpDir();
FileTxnLog txnLog = new FileTxnLog(tmpDir);
- TxnHeader txnHeader = new TxnHeader(0xabcd, 0x123, 0x123,
- Time.currentElapsedTime(), ZooDefs.OpCode.create);
+ TxnHeader txnHeader = new TxnHeader(0xabcd, 0x123, 0x123, Time.currentElapsedTime(), ZooDefs.OpCode.create);
Record txn = new CreateTxn("/Test", new byte[0], null, false, 1);
txnLog.append(txnHeader, txn);
- FileInputStream in = new FileInputStream(tmpDir.getPath() + "/log." +
- Long.toHexString(txnHeader.getZxid()));
- BinaryInputArchive ia = BinaryInputArchive.getArchive(in);
+ FileInputStream in = new FileInputStream(tmpDir.getPath() + "/log." + Long.toHexString(txnHeader.getZxid()));
+ BinaryInputArchive ia = BinaryInputArchive.getArchive(in);
FileHeader header = new FileHeader();
header.deserialize(ia, "fileheader");
- LOG.info("Received magic : " + header.getMagic() +
- " Expected : " + FileTxnLog.TXNLOG_MAGIC);
- Assert.assertTrue("Missing magic number ",
- header.getMagic() == FileTxnLog.TXNLOG_MAGIC);
+ LOG.info("Received magic : " + header.getMagic() + " Expected : " + FileTxnLog.TXNLOG_MAGIC);
+ assertTrue("Missing magic number ", header.getMagic() == FileTxnLog.TXNLOG_MAGIC);
}
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/LoadFromLogTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/LoadFromLogTest.java
index 800ebeefb..ee416ae1c 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/LoadFromLogTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/LoadFromLogTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,6 +18,11 @@
package org.apache.zookeeper.test;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+import java.io.File;
+import java.io.IOException;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException.NoNodeException;
import org.apache.zookeeper.ZooDefs.Ids;
@@ -31,16 +36,13 @@ import org.apache.zookeeper.server.persistence.FileTxnSnapLog;
import org.apache.zookeeper.server.persistence.TxnLog.TxnIterator;
import org.apache.zookeeper.server.persistence.Util;
import org.apache.zookeeper.txn.TxnHeader;
-import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.io.File;
-import java.io.IOException;
-
public class LoadFromLogTest extends ClientBase {
+
private static final int NUM_MESSAGES = 300;
protected static final Logger LOG = LoggerFactory.getLogger(LoadFromLogTest.class);
@@ -63,9 +65,8 @@ public class LoadFromLogTest extends ClientBase {
// generate some transactions that will get logged
ZooKeeper zk = createZKClient(hostPort);
try {
- for (int i = 0; i< NUM_MESSAGES; i++) {
- zk.create("/invalidsnap-" + i, new byte[0], Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ for (int i = 0; i < NUM_MESSAGES; i++) {
+ zk.create("/invalidsnap-" + i, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
}
} finally {
zk.close();
@@ -76,26 +77,29 @@ public class LoadFromLogTest extends ClientBase {
File logDir = new File(tmpDir, FileTxnSnapLog.version + FileTxnSnapLog.VERSION);
FileTxnLog txnLog = new FileTxnLog(logDir);
TxnIterator itr = txnLog.read(0);
-
+
// Check that storage space return some value
FileTxnIterator fileItr = (FileTxnIterator) itr;
long storageSize = fileItr.getStorageSize();
LOG.info("Txnlog size: " + storageSize + " bytes");
- Assert.assertTrue("Storage size is greater than zero ",
- (storageSize > 0));
-
+ assertTrue("Storage size is greater than zero ", (storageSize > 0));
+
long expectedZxid = 0;
long lastZxid = 0;
TxnHeader hdr;
do {
hdr = itr.getHeader();
expectedZxid++;
- Assert.assertTrue("not the same transaction. lastZxid=" + lastZxid + ", zxid=" + hdr.getZxid(), lastZxid != hdr.getZxid());
- Assert.assertTrue("excepting next transaction. expected=" + expectedZxid + ", retrieved=" + hdr.getZxid(), (hdr.getZxid() == expectedZxid));
+ assertTrue("not the same transaction. lastZxid=" + lastZxid + ", zxid=" + hdr.getZxid(), lastZxid
+ != hdr.getZxid());
+ assertTrue("excepting next transaction. expected=" + expectedZxid + ", retrieved=" + hdr.getZxid(), (
+ hdr.getZxid()
+ == expectedZxid));
lastZxid = hdr.getZxid();
- }while(itr.next());
+ } while (itr.next());
- Assert.assertTrue("processed all transactions. " + expectedZxid + " == " + TOTAL_TRANSACTIONS, (expectedZxid == TOTAL_TRANSACTIONS));
+ assertTrue("processed all transactions. " + expectedZxid + " == " + TOTAL_TRANSACTIONS, (expectedZxid
+ == TOTAL_TRANSACTIONS));
}
/**
@@ -108,9 +112,8 @@ public class LoadFromLogTest extends ClientBase {
// generate some transactions that will get logged
ZooKeeper zk = createZKClient(hostPort);
try {
- for (int i = 0; i< NUM_MESSAGES; i++) {
- zk.create("/data-", new byte[0], Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT_SEQUENTIAL);
+ for (int i = 0; i < NUM_MESSAGES; i++) {
+ zk.create("/data-", new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL);
}
} finally {
zk.close();
@@ -120,9 +123,9 @@ public class LoadFromLogTest extends ClientBase {
File logDir = new File(tmpDir, FileTxnSnapLog.version + FileTxnSnapLog.VERSION);
File[] logFiles = FileTxnLog.getLogFiles(logDir.listFiles(), 0);
// Verify that we have at least NUM_MESSAGES / SNAPCOUNT txnlog
- Assert.assertTrue(logFiles.length > NUM_MESSAGES / 100);
+ assertTrue(logFiles.length > NUM_MESSAGES / 100);
// Delete the first log file, so we will fail to read it back from disk
- Assert.assertTrue("delete the first log file", logFiles[0].delete());
+ assertTrue("delete the first log file", logFiles[0].delete());
// Find zxid for the second log
long secondStartZxid = Util.getZxidFromName(logFiles[1].getName(), "log");
@@ -132,29 +135,29 @@ public class LoadFromLogTest extends ClientBase {
// Oldest log is already remove, so this should point to the start of
// of zxid on the second log
- Assert.assertEquals(secondStartZxid, itr.getHeader().getZxid());
+ assertEquals(secondStartZxid, itr.getHeader().getZxid());
itr = txnLog.read(secondStartZxid, false);
- Assert.assertEquals(secondStartZxid, itr.getHeader().getZxid());
- Assert.assertTrue(itr.next());
+ assertEquals(secondStartZxid, itr.getHeader().getZxid());
+ assertTrue(itr.next());
// Trying to get a second txn on second txnlog give us the
// the start of second log, since the first one is removed
long nextZxid = itr.getHeader().getZxid();
itr = txnLog.read(nextZxid, false);
- Assert.assertEquals(secondStartZxid, itr.getHeader().getZxid());
+ assertEquals(secondStartZxid, itr.getHeader().getZxid());
// Trying to get a first txn on the third give us the
// the start of second log, since the first one is removed
long thirdStartZxid = Util.getZxidFromName(logFiles[2].getName(), "log");
itr = txnLog.read(thirdStartZxid, false);
- Assert.assertEquals(secondStartZxid, itr.getHeader().getZxid());
- Assert.assertTrue(itr.next());
+ assertEquals(secondStartZxid, itr.getHeader().getZxid());
+ assertTrue(itr.next());
nextZxid = itr.getHeader().getZxid();
itr = txnLog.read(nextZxid, false);
- Assert.assertEquals(secondStartZxid, itr.getHeader().getZxid());
+ assertEquals(secondStartZxid, itr.getHeader().getZxid());
}
/**
@@ -167,26 +170,20 @@ public class LoadFromLogTest extends ClientBase {
ZooKeeper zk = createZKClient(hostPort);
String lastPath = null;
try {
- zk.create("/invalidsnap", new byte[0], Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk.create("/invalidsnap", new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
for (int i = 0; i < NUM_MESSAGES; i++) {
- lastPath = zk.create("/invalidsnap/test-", new byte[0],
- Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL);
+ lastPath = zk.create("/invalidsnap/test-", new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL);
}
} finally {
zk.close();
}
String[] tokens = lastPath.split("-");
- String expectedPath = "/invalidsnap/test-"
- + String.format("%010d",
- (Integer.parseInt(tokens[1])) + 1);
+ String expectedPath = "/invalidsnap/test-" + String.format("%010d", (Integer.parseInt(tokens[1])) + 1);
ZooKeeperServer zks = serverFactory.getZooKeeperServer();
long eZxid = zks.getZKDatabase().getDataTreeLastProcessedZxid();
// force the zxid to be behind the content
- zks.getZKDatabase().setlastProcessedZxid(
- zks.getZKDatabase().getDataTreeLastProcessedZxid() - 10);
- LOG.info("Set lastProcessedZxid to "
- + zks.getZKDatabase().getDataTreeLastProcessedZxid());
+ zks.getZKDatabase().setlastProcessedZxid(zks.getZKDatabase().getDataTreeLastProcessedZxid() - 10);
+ LOG.info("Set lastProcessedZxid to " + zks.getZKDatabase().getDataTreeLastProcessedZxid());
// Force snapshot and restore
zks.takeSnapshot();
zks.shutdown();
@@ -197,8 +194,7 @@ public class LoadFromLogTest extends ClientBase {
long fZxid = zks.getZKDatabase().getDataTreeLastProcessedZxid();
// Verify lastProcessedZxid is set correctly
- Assert.assertTrue("Restore failed expected zxid=" + eZxid + " found="
- + fZxid, fZxid == eZxid);
+ assertTrue("Restore failed expected zxid=" + eZxid + " found=" + fZxid, fZxid == eZxid);
zk = createZKClient(hostPort);
// Verify correctness of data and whether sequential znode creation
@@ -206,19 +202,21 @@ public class LoadFromLogTest extends ClientBase {
String[] children;
String path;
try {
- children = zk.getChildren("/invalidsnap", false).toArray(
- new String[0]);
- path = zk.create("/invalidsnap/test-", new byte[0],
- Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL);
+ children = zk.getChildren("/invalidsnap", false).toArray(new String[0]);
+ path = zk.create("/invalidsnap/test-", new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL);
} finally {
zk.close();
}
LOG.info("Expected " + expectedPath + " found " + path);
- Assert.assertTrue("Error in sequential znode creation expected "
- + expectedPath + " found " + path, path.equals(expectedPath));
- Assert.assertTrue("Unexpected number of children " + children.length
- + " expected " + NUM_MESSAGES,
- (children.length == NUM_MESSAGES));
+ assertTrue("Error in sequential znode creation expected "
+ + expectedPath
+ + " found "
+ + path, path.equals(expectedPath));
+ assertTrue("Unexpected number of children "
+ + children.length
+ + " expected "
+ + NUM_MESSAGES, (children.length
+ == NUM_MESSAGES));
}
/**
@@ -232,9 +230,8 @@ public class LoadFromLogTest extends ClientBase {
try {
for (int i = 0; i < NUM_MESSAGES; i++) {
try {
- zk.create("/invaliddir/test-", new byte[0],
- Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL);
- } catch(NoNodeException e) {
+ zk.create("/invaliddir/test-", new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL);
+ } catch (NoNodeException e) {
//Expected
}
}
@@ -244,10 +241,8 @@ public class LoadFromLogTest extends ClientBase {
// force the zxid to be behind the content
ZooKeeperServer zks = serverFactory.getZooKeeperServer();
- zks.getZKDatabase().setlastProcessedZxid(
- zks.getZKDatabase().getDataTreeLastProcessedZxid() - 10);
- LOG.info("Set lastProcessedZxid to "
- + zks.getZKDatabase().getDataTreeLastProcessedZxid());
+ zks.getZKDatabase().setlastProcessedZxid(zks.getZKDatabase().getDataTreeLastProcessedZxid() - 10);
+ LOG.info("Set lastProcessedZxid to " + zks.getZKDatabase().getDataTreeLastProcessedZxid());
// Force snapshot and restore
zks.takeSnapshot();
@@ -270,12 +265,11 @@ public class LoadFromLogTest extends ClientBase {
System.setProperty(FileTxnSnapLog.ZOOKEEPER_DATADIR_AUTOCREATE, "false");
tmpDir = createTmpDir();
startServer();
- Assert.fail("Server should not have started without datadir");
+ fail("Server should not have started without datadir");
} catch (IOException e) {
LOG.info("Server failed to start - correct behavior " + e);
} finally {
- System.setProperty(FileTxnSnapLog.ZOOKEEPER_DATADIR_AUTOCREATE,
- FileTxnSnapLog.ZOOKEEPER_DATADIR_AUTOCREATE_DEFAULT);
+ System.setProperty(FileTxnSnapLog.ZOOKEEPER_DATADIR_AUTOCREATE, FileTxnSnapLog.ZOOKEEPER_DATADIR_AUTOCREATE_DEFAULT);
}
}
@@ -287,19 +281,16 @@ public class LoadFromLogTest extends ClientBase {
public void testReloadSnapshotWithMissingParent() throws Exception {
// create transactions to create the snapshot with create/delete pattern
ZooKeeper zk = createZKClient(hostPort);
- zk.create("/a", "".getBytes(), Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk.create("/a", "".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
Stat stat = zk.exists("/a", false);
long createZxId = stat.getMzxid();
- zk.create("/a/b", "".getBytes(), Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk.create("/a/b", "".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
zk.delete("/a/b", -1);
zk.delete("/a", -1);
// force the zxid to be behind the content
ZooKeeperServer zks = serverFactory.getZooKeeperServer();
zks.getZKDatabase().setlastProcessedZxid(createZxId);
- LOG.info("Set lastProcessedZxid to {}", zks.getZKDatabase()
- .getDataTreeLastProcessedZxid());
+ LOG.info("Set lastProcessedZxid to {}", zks.getZKDatabase().getDataTreeLastProcessedZxid());
// Force snapshot and restore
zks.takeSnapshot();
zks.shutdown();
@@ -307,4 +298,5 @@ public class LoadFromLogTest extends ClientBase {
startServer();
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/LocalSessionRequestTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/LocalSessionRequestTest.java
index 603cd159f..156a3a780 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/LocalSessionRequestTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/LocalSessionRequestTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,6 +18,7 @@
package org.apache.zookeeper.test;
+import static org.junit.Assert.assertFalse;
import org.apache.zookeeper.ZKTestCase;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.server.TraceFormatter;
@@ -26,7 +27,6 @@ import org.apache.zookeeper.server.quorum.Leader.Proposal;
import org.apache.zookeeper.server.quorum.QuorumPeer;
import org.apache.zookeeper.test.ClientBase.CountdownWatcher;
import org.junit.After;
-import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
@@ -38,8 +38,8 @@ import org.slf4j.LoggerFactory;
* these request doesn't show up in committedLog on other machines.
*/
public class LocalSessionRequestTest extends ZKTestCase {
- protected static final Logger LOG = LoggerFactory
- .getLogger(LocalSessionRequestTest.class);
+
+ protected static final Logger LOG = LoggerFactory.getLogger(LocalSessionRequestTest.class);
// Need to be short since we need to wait for session to expire
public static final int CONNECTION_TIMEOUT = 4000;
@@ -77,17 +77,17 @@ public class LocalSessionRequestTest extends ZKTestCase {
*/
private void validateRequestLog(long sessionId, int peerId) {
String session = Long.toHexString(sessionId);
- LOG.info("Searching for txn of session 0x " + session +
- " on peer " + peerId);
+ LOG.info("Searching for txn of session 0x " + session + " on peer " + peerId);
String peerType = peerId == qb.getLeaderIndex() ? "leader" : "follower";
QuorumPeer peer = qb.getPeerList().get(peerId);
ZKDatabase db = peer.getActiveServer().getZKDatabase();
for (Proposal p : db.getCommittedLog()) {
- Assert.assertFalse("Should not see " +
- TraceFormatter.op2String(p.request.type) +
- " request from local session 0x" + session +
- " on the " + peerType,
- p.request.sessionId == sessionId);
+ assertFalse("Should not see "
+ + TraceFormatter.op2String(p.request.type)
+ + " request from local session 0x"
+ + session
+ + " on the "
+ + peerType, p.request.sessionId == sessionId);
}
}
@@ -98,16 +98,15 @@ public class LocalSessionRequestTest extends ZKTestCase {
*/
public void testOpenCloseSession(boolean onLeader) throws Exception {
int leaderIdx = qb.getLeaderIndex();
- Assert.assertFalse("No leader in quorum?", leaderIdx == -1);
+ assertFalse("No leader in quorum?", leaderIdx == -1);
int followerIdx = (leaderIdx + 1) % 5;
int testPeerIdx = onLeader ? leaderIdx : followerIdx;
int verifyPeerIdx = onLeader ? followerIdx : leaderIdx;
- String hostPorts[] = qb.hostPort.split(",");
+ String[] hostPorts = qb.hostPort.split(",");
CountdownWatcher watcher = new CountdownWatcher();
- DisconnectableZooKeeper client = new DisconnectableZooKeeper(
- hostPorts[testPeerIdx], CONNECTION_TIMEOUT, watcher);
+ DisconnectableZooKeeper client = new DisconnectableZooKeeper(hostPorts[testPeerIdx], CONNECTION_TIMEOUT, watcher);
watcher.waitForConnected(CONNECTION_TIMEOUT);
long localSessionId1 = client.getSessionId();
@@ -120,8 +119,7 @@ public class LocalSessionRequestTest extends ZKTestCase {
// We don't validate right away, will do another session create first
- ZooKeeper zk = qb.createClient(watcher, hostPorts[testPeerIdx],
- CONNECTION_TIMEOUT);
+ ZooKeeper zk = qb.createClient(watcher, hostPorts[testPeerIdx], CONNECTION_TIMEOUT);
watcher.waitForConnected(CONNECTION_TIMEOUT);
long localSessionId2 = zk.getSessionId();
@@ -145,4 +143,5 @@ public class LocalSessionRequestTest extends ZKTestCase {
qb.shutdownServers();
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/LocalSessionsOnlyTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/LocalSessionsOnlyTest.java
index 44c40af5e..c2ea5731f 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/LocalSessionsOnlyTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/LocalSessionsOnlyTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,10 +18,13 @@
package org.apache.zookeeper.test;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.fail;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
-
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZKTestCase;
@@ -29,7 +32,6 @@ import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.test.ClientBase.CountdownWatcher;
import org.junit.After;
-import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
@@ -42,8 +44,8 @@ import org.slf4j.LoggerFactory;
* creation of ephemeral nodes) will fail with an error.
*/
public class LocalSessionsOnlyTest extends ZKTestCase {
- protected static final Logger LOG = LoggerFactory
- .getLogger(LocalSessionsOnlyTest.class);
+
+ protected static final Logger LOG = LoggerFactory.getLogger(LocalSessionsOnlyTest.class);
public static final int CONNECTION_TIMEOUT = ClientBase.CONNECTION_TIMEOUT;
private final QuorumBase qb = new QuorumBase();
@@ -74,33 +76,29 @@ public class LocalSessionsOnlyTest extends ZKTestCase {
}
private void testLocalSessions(boolean testLeader) throws Exception {
- String nodePrefix = "/testLocalSessions-"
- + (testLeader ? "leaderTest-" : "followerTest-");
+ String nodePrefix = "/testLocalSessions-" + (testLeader ? "leaderTest-" : "followerTest-");
int leaderIdx = qb.getLeaderIndex();
- Assert.assertFalse("No leader in quorum?", leaderIdx == -1);
+ assertFalse("No leader in quorum?", leaderIdx == -1);
int followerIdx = (leaderIdx + 1) % 5;
int testPeerIdx = testLeader ? leaderIdx : followerIdx;
- String hostPorts[] = qb.hostPort.split(",");
+ String[] hostPorts = qb.hostPort.split(",");
CountdownWatcher watcher = new CountdownWatcher();
- ZooKeeper zk = qb.createClient(watcher, hostPorts[testPeerIdx],
- CONNECTION_TIMEOUT);
+ ZooKeeper zk = qb.createClient(watcher, hostPorts[testPeerIdx], CONNECTION_TIMEOUT);
watcher.waitForConnected(CONNECTION_TIMEOUT);
long localSessionId = zk.getSessionId();
// Try creating some data.
for (int i = 0; i < 5; i++) {
- zk.create(nodePrefix + i, new byte[0],
- ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
+ zk.create(nodePrefix + i, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
}
// Now, try an ephemeral node. This should fail since we
// cannot create ephemeral nodes on a local session.
try {
- zk.create(nodePrefix + "ephemeral", new byte[0],
- ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
- Assert.fail("Ephemeral node creation should fail.");
+ zk.create(nodePrefix + "ephemeral", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
+ fail("Ephemeral node creation should fail.");
} catch (KeeperException.EphemeralOnLocalSessionException e) {
}
@@ -111,28 +109,26 @@ public class LocalSessionsOnlyTest extends ZKTestCase {
Map<String, Integer> peers = new HashMap<String, Integer>();
peers.put("leader", leaderIdx);
peers.put("follower", followerIdx);
- for (Entry<String, Integer> entry: peers.entrySet()) {
+ for (Entry<String, Integer> entry : peers.entrySet()) {
watcher.reset();
// Try reconnecting with a new session.
// The data should be persisted, even though the session was not.
- zk = qb.createClient(watcher, hostPorts[entry.getValue()],
- CONNECTION_TIMEOUT);
+ zk = qb.createClient(watcher, hostPorts[entry.getValue()], CONNECTION_TIMEOUT);
watcher.waitForConnected(CONNECTION_TIMEOUT);
long newSessionId = zk.getSessionId();
- Assert.assertFalse(newSessionId == localSessionId);
+ assertFalse(newSessionId == localSessionId);
for (int i = 0; i < 5; i++) {
- Assert.assertNotNull("Data not exists in " + entry.getKey(),
- zk.exists(nodePrefix + i, null));
+ assertNotNull("Data not exists in " + entry.getKey(), zk.exists(nodePrefix + i, null));
}
// We may get the correct exception but the txn may go through
- Assert.assertNull("Data exists in " + entry.getKey(),
- zk.exists(nodePrefix + "ephemeral", null));
+ assertNull("Data exists in " + entry.getKey(), zk.exists(nodePrefix + "ephemeral", null));
zk.close();
}
qb.shutdownServers();
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/LogChopperTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/LogChopperTest.java
index 6ce5139d0..c836e8314 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/LogChopperTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/LogChopperTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -15,17 +15,12 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package org.apache.zookeeper.test;
-import org.apache.zookeeper.ZooDefs;
-import org.apache.zookeeper.server.persistence.FileTxnLog;
-import org.apache.zookeeper.server.persistence.TxnLog;
-import org.apache.zookeeper.server.util.LogChopper;
-import org.apache.zookeeper.txn.DeleteTxn;
-import org.apache.zookeeper.txn.TxnHeader;
-import org.junit.Assert;
-import org.junit.Test;
+package org.apache.zookeeper.test;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
@@ -35,8 +30,16 @@ import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
+import org.apache.zookeeper.ZooDefs;
+import org.apache.zookeeper.server.persistence.FileTxnLog;
+import org.apache.zookeeper.server.persistence.TxnLog;
+import org.apache.zookeeper.server.util.LogChopper;
+import org.apache.zookeeper.txn.DeleteTxn;
+import org.apache.zookeeper.txn.TxnHeader;
+import org.junit.Test;
class Pair<V1, V2> {
+
private V1 v1;
private V2 v2;
Pair(V1 v1, V2 v2) {
@@ -49,6 +52,7 @@ class Pair<V1, V2> {
public V2 getSecond() {
return v2;
}
+
}
public class LogChopperTest extends ClientBase {
@@ -109,21 +113,18 @@ public class LogChopperTest extends ClientBase {
// now find the log we just created.
final File logFile = new File(tmpDir, "log." + Integer.toHexString(1001));
Pair<Long, Long> firstLast = getFirstLastZxid(logFile);
- Assert.assertEquals(1001, (long)firstLast.getFirst());
- Assert.assertEquals(1110, (long)firstLast.getSecond());
+ assertEquals(1001, (long) firstLast.getFirst());
+ assertEquals(1110, (long) firstLast.getSecond());
File choppedFile = new File(tmpDir, "chopped_failed");
- Assert.assertFalse(LogChopper.chop(
- new FileInputStream(logFile),
- new FileOutputStream(choppedFile), 1107));
+ assertFalse(LogChopper.chop(new FileInputStream(logFile), new FileOutputStream(choppedFile), 1107));
choppedFile = new File(tmpDir, "chopped");
- Assert.assertTrue(LogChopper.chop(
- new FileInputStream(logFile),
- new FileOutputStream(choppedFile), 1017));
+ assertTrue(LogChopper.chop(new FileInputStream(logFile), new FileOutputStream(choppedFile), 1017));
firstLast = getFirstLastZxid(choppedFile);
- Assert.assertEquals(1001, (long)firstLast.getFirst());
- Assert.assertEquals(1017, (long)firstLast.getSecond());
+ assertEquals(1001, (long) firstLast.getFirst());
+ assertEquals(1017, (long) firstLast.getSecond());
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/MaxCnxnsTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/MaxCnxnsTest.java
index a96e5a8e2..a927e3ef9 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/MaxCnxnsTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/MaxCnxnsTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,20 +18,20 @@
package org.apache.zookeeper.test;
+import static org.junit.Assert.assertSame;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.concurrent.atomic.AtomicInteger;
-
import org.apache.jute.BinaryOutputArchive;
import org.apache.zookeeper.proto.ConnectRequest;
-import org.junit.Assert;
import org.junit.Test;
public class MaxCnxnsTest extends ClientBase {
- final private static int numCnxns = 30;
+
+ private static final int numCnxns = 30;
AtomicInteger numConnected = new AtomicInteger(0);
String host;
int port;
@@ -45,7 +45,7 @@ public class MaxCnxnsTest extends ClientBase {
class CnxnThread extends Thread {
public CnxnThread(int i) {
- super("CnxnThread-"+i);
+ super("CnxnThread-" + i);
}
public void run() {
@@ -58,10 +58,9 @@ public class MaxCnxnsTest extends ClientBase {
* this for loop.
*/
sChannel = SocketChannel.open();
- sChannel.connect(new InetSocketAddress(host,port));
+ sChannel.connect(new InetSocketAddress(host, port));
// Construct a connection request
- ConnectRequest conReq = new ConnectRequest(0, 0,
- 10000, 0, "password".getBytes());
+ ConnectRequest conReq = new ConnectRequest(0, 0, 10000, 0, "password".getBytes());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
BinaryOutputArchive boa = BinaryOutputArchive.getArchive(baos);
boa.writeInt(-1, "len");
@@ -83,17 +82,16 @@ public class MaxCnxnsTest extends ClientBase {
*/
int eof = sChannel.write(bb);
- // If the socket times out, we count that as Assert.failed -
+ // If the socket times out, we count that as failed -
// the server should respond within 10s
sChannel.socket().setSoTimeout(10000);
- if (!sChannel.socket().isClosed()){
+ if (!sChannel.socket().isClosed()) {
eof = sChannel.socket().getInputStream().read();
if (eof != -1) {
numConnected.incrementAndGet();
}
}
- }
- catch (IOException io) {
+ } catch (IOException io) {
// "Connection reset by peer"
} finally {
if (sChannel != null) {
@@ -105,6 +103,7 @@ public class MaxCnxnsTest extends ClientBase {
}
}
}
+
}
/**
@@ -113,24 +112,25 @@ public class MaxCnxnsTest extends ClientBase {
* @throws InterruptedException
*/
@Test
- public void testMaxCnxns() throws IOException, InterruptedException{
- String split[] = hostPort.split(":");
+ public void testMaxCnxns() throws IOException, InterruptedException {
+ String[] split = hostPort.split(":");
host = split[0];
port = Integer.parseInt(split[1]);
int numThreads = numCnxns + 5;
CnxnThread[] threads = new CnxnThread[numThreads];
- for (int i=0;i<numCnxns;++i) {
- threads[i] = new CnxnThread(i);
+ for (int i = 0; i < numCnxns; ++i) {
+ threads[i] = new CnxnThread(i);
}
- for (int i=0;i<numCnxns;++i) {
+ for (int i = 0; i < numCnxns; ++i) {
threads[i].start();
}
- for (int i=0;i<numCnxns;++i) {
+ for (int i = 0; i < numCnxns; ++i) {
threads[i].join();
}
- Assert.assertSame(numCnxns,numConnected.get());
+ assertSame(numCnxns, numConnected.get());
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/MultiAsyncTransactionTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/MultiAsyncTransactionTest.java
index 822b9c528..5a94649de 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/MultiAsyncTransactionTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/MultiAsyncTransactionTest.java
@@ -19,12 +19,10 @@ package org.apache.zookeeper.test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
-
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
-
import org.apache.zookeeper.AsyncCallback.MultiCallback;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
@@ -38,6 +36,7 @@ import org.junit.Before;
import org.junit.Test;
public class MultiAsyncTransactionTest extends ClientBase {
+
private ZooKeeper zk;
private final AtomicInteger pendingOps = new AtomicInteger(0);
@@ -49,8 +48,10 @@ public class MultiAsyncTransactionTest extends ClientBase {
}
private static class MultiResult {
+
int rc;
List<OpResult> results;
+
}
private void finishPendingOps() {
@@ -62,8 +63,8 @@ public class MultiAsyncTransactionTest extends ClientBase {
}
private void waitForPendingOps(int timeout) throws Exception {
- synchronized(pendingOps) {
- while(pendingOps.get() > 0) {
+ synchronized (pendingOps) {
+ while (pendingOps.get() > 0) {
pendingOps.wait(timeout);
}
}
@@ -85,18 +86,12 @@ public class MultiAsyncTransactionTest extends ClientBase {
pendingOps.set(iteration);
- List<Op> ops = Arrays.asList(
- Op.create("/node-", new byte[0], Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT_SEQUENTIAL),
- Op.create("/dup", new byte[0], Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT));
-
+ List<Op> ops = Arrays.asList(Op.create("/node-", new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL), Op.create("/dup", new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT));
for (int i = 0; i < iteration; ++i) {
zk.multi(ops, new MultiCallback() {
@Override
- public void processResult(int rc, String path, Object ctx,
- List<OpResult> opResults) {
+ public void processResult(int rc, String path, Object ctx, List<OpResult> opResults) {
MultiResult result = new MultiResult();
result.results = opResults;
result.rc = rc;
@@ -116,20 +111,15 @@ public class MultiAsyncTransactionTest extends ClientBase {
// Check that the first operation is successful in all request
assertTrue(results.get(0).results.get(0) instanceof CreateResult);
- assertEquals(KeeperException.Code.OK.intValue(),
- ((ErrorResult) results.get(1).results.get(0)).getErr());
- assertEquals(KeeperException.Code.OK.intValue(),
- ((ErrorResult) results.get(2).results.get(0)).getErr());
- assertEquals(KeeperException.Code.OK.intValue(),
- ((ErrorResult) results.get(3).results.get(0)).getErr());
+ assertEquals(KeeperException.Code.OK.intValue(), ((ErrorResult) results.get(1).results.get(0)).getErr());
+ assertEquals(KeeperException.Code.OK.intValue(), ((ErrorResult) results.get(2).results.get(0)).getErr());
+ assertEquals(KeeperException.Code.OK.intValue(), ((ErrorResult) results.get(3).results.get(0)).getErr());
// Check that the second operation failed after the first request
- assertEquals(KeeperException.Code.NODEEXISTS.intValue(),
- ((ErrorResult) results.get(1).results.get(1)).getErr());
- assertEquals(KeeperException.Code.NODEEXISTS.intValue(),
- ((ErrorResult) results.get(2).results.get(1)).getErr());
- assertEquals(KeeperException.Code.NODEEXISTS.intValue(),
- ((ErrorResult) results.get(3).results.get(1)).getErr());
+ assertEquals(KeeperException.Code.NODEEXISTS.intValue(), ((ErrorResult) results.get(1).results.get(1)).getErr());
+ assertEquals(KeeperException.Code.NODEEXISTS.intValue(), ((ErrorResult) results.get(2).results.get(1)).getErr());
+ assertEquals(KeeperException.Code.NODEEXISTS.intValue(), ((ErrorResult) results.get(3).results.get(1)).getErr());
}
-} \ No newline at end of file
+
+}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/MultiOperationTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/MultiOperationTest.java
index 041f07738..2e48600da 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/MultiOperationTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/MultiOperationTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,8 +18,14 @@
package org.apache.zookeeper.test;
-import static org.junit.Assert.*;
-
+import static org.junit.Assert.assertArrayEquals;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertSame;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
@@ -31,30 +37,28 @@ import java.util.TreeSet;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
-
import org.apache.zookeeper.AsyncCallback;
import org.apache.zookeeper.AsyncCallback.MultiCallback;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.Op;
import org.apache.zookeeper.OpResult;
-import org.apache.zookeeper.Transaction;
-import org.apache.zookeeper.WatchedEvent;
-import org.apache.zookeeper.Watcher;
-import org.apache.zookeeper.ZooDefs;
-import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.OpResult.CheckResult;
import org.apache.zookeeper.OpResult.CreateResult;
import org.apache.zookeeper.OpResult.DeleteResult;
import org.apache.zookeeper.OpResult.ErrorResult;
import org.apache.zookeeper.OpResult.SetDataResult;
+import org.apache.zookeeper.Transaction;
+import org.apache.zookeeper.WatchedEvent;
+import org.apache.zookeeper.Watcher;
+import org.apache.zookeeper.ZKParameterized;
+import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooDefs.Ids;
+import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.ACL;
import org.apache.zookeeper.data.Id;
import org.apache.zookeeper.data.Stat;
import org.apache.zookeeper.server.SyncRequestProcessor;
-import org.apache.zookeeper.ZKParameterized;
-import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -66,6 +70,7 @@ import org.slf4j.LoggerFactory;
@RunWith(Parameterized.class)
@Parameterized.UseParametersRunnerFactory(ZKParameterized.RunnerFactory.class)
public class MultiOperationTest extends ClientBase {
+
private static final Logger LOG = LoggerFactory.getLogger(MultiOperationTest.class);
private ZooKeeper zk;
private ZooKeeper zk_chroot;
@@ -78,9 +83,7 @@ public class MultiOperationTest extends ClientBase {
@Parameters
public static Collection<Object[]> configs() {
- return Arrays.asList(new Object[][] {
- { false }, { true },
- });
+ return Arrays.asList(new Object[][]{{false}, {true}});
}
@Before
@@ -91,19 +94,19 @@ public class MultiOperationTest extends ClientBase {
}
static class MultiResult {
+
int rc;
List<OpResult> results;
boolean finished = false;
+
}
- private List<OpResult> multi(ZooKeeper zk, Iterable<Op> ops)
- throws KeeperException, InterruptedException {
+ private List<OpResult> multi(ZooKeeper zk, Iterable<Op> ops) throws KeeperException, InterruptedException {
if (useAsync) {
final MultiResult res = new MultiResult();
zk.multi(ops, new MultiCallback() {
@Override
- public void processResult(int rc, String path, Object ctx,
- List<OpResult> opResults) {
+ public void processResult(int rc, String path, Object ctx, List<OpResult> opResults) {
synchronized (res) {
res.rc = rc;
res.results = opResults;
@@ -128,15 +131,12 @@ public class MultiOperationTest extends ClientBase {
}
}
- private void multiHavingErrors(ZooKeeper zk, Iterable<Op> ops,
- List<Integer> expectedResultCodes, String expectedErr)
- throws KeeperException, InterruptedException {
+ private void multiHavingErrors(ZooKeeper zk, Iterable<Op> ops, List<Integer> expectedResultCodes, String expectedErr) throws KeeperException, InterruptedException {
if (useAsync) {
final MultiResult res = new MultiResult();
zk.multi(ops, new MultiCallback() {
@Override
- public void processResult(int rc, String path, Object ctx,
- List<OpResult> opResults) {
+ public void processResult(int rc, String path, Object ctx, List<OpResult> opResults) {
synchronized (res) {
res.rc = rc;
res.results = opResults;
@@ -152,34 +152,28 @@ public class MultiOperationTest extends ClientBase {
}
for (int i = 0; i < res.results.size(); i++) {
OpResult opResult = res.results.get(i);
- Assert.assertTrue("Did't receive proper error response",
- opResult instanceof ErrorResult);
+ assertTrue("Did't receive proper error response", opResult instanceof ErrorResult);
ErrorResult errRes = (ErrorResult) opResult;
- Assert.assertEquals("Did't receive proper error code",
- expectedResultCodes.get(i).intValue(), errRes.getErr());
+ assertEquals("Did't receive proper error code", expectedResultCodes.get(i).intValue(), errRes.getErr());
}
} else {
try {
zk.multi(ops);
- Assert.fail("Shouldn't have validated in ZooKeeper client!");
+ fail("Shouldn't have validated in ZooKeeper client!");
} catch (KeeperException e) {
- Assert.assertEquals("Wrong exception", expectedErr, e.code()
- .name());
+ assertEquals("Wrong exception", expectedErr, e.code().name());
} catch (IllegalArgumentException e) {
- Assert.assertEquals("Wrong exception", expectedErr,
- e.getMessage());
+ assertEquals("Wrong exception", expectedErr, e.getMessage());
}
}
}
- private List<OpResult> commit(Transaction txn)
- throws KeeperException, InterruptedException {
+ private List<OpResult> commit(Transaction txn) throws KeeperException, InterruptedException {
if (useAsync) {
final MultiResult res = new MultiResult();
txn.commit(new MultiCallback() {
@Override
- public void processResult(int rc, String path, Object ctx,
- List<OpResult> opResults) {
+ public void processResult(int rc, String path, Object ctx, List<OpResult> opResults) {
synchronized (res) {
res.rc = rc;
res.results = opResults;
@@ -209,45 +203,45 @@ public class MultiOperationTest extends ClientBase {
@Test(timeout = 90000)
public void testInvalidPath() throws Exception {
List<Integer> expectedResultCodes = new ArrayList<Integer>();
- expectedResultCodes.add(KeeperException.Code.RUNTIMEINCONSISTENCY
- .intValue());
+ expectedResultCodes.add(KeeperException.Code.RUNTIMEINCONSISTENCY.intValue());
expectedResultCodes.add(KeeperException.Code.BADARGUMENTS.intValue());
- expectedResultCodes.add(KeeperException.Code.RUNTIMEINCONSISTENCY
- .intValue());
+ expectedResultCodes.add(KeeperException.Code.RUNTIMEINCONSISTENCY.intValue());
// create with CreateMode
- List<Op> opList = Arrays.asList(Op.create("/multi0", new byte[0],
- Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT), Op.create(
- "/multi1/", new byte[0], Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT), Op.create("/multi2", new byte[0],
- Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT));
+ List<Op> opList = Arrays.asList(
+ Op.create("/multi0", new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT),
+ Op.create("/multi1/", new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT),
+ Op.create("/multi2", new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT));
String expectedErr = "Path must not end with / character";
multiHavingErrors(zk, opList, expectedResultCodes, expectedErr);
// create with valid sequential flag
- opList = Arrays.asList(Op.create("/multi0", new byte[0],
- Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT), Op.create(
- "multi1/", new byte[0], Ids.OPEN_ACL_UNSAFE,
- CreateMode.EPHEMERAL_SEQUENTIAL.toFlag()), Op.create("/multi2",
- new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT));
+ opList = Arrays.asList(
+ Op.create("/multi0", new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT),
+ Op.create("multi1/", new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL.toFlag()),
+ Op.create("/multi2", new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT));
expectedErr = "Path must start with / character";
multiHavingErrors(zk, opList, expectedResultCodes, expectedErr);
// check
- opList = Arrays.asList(Op.check("/multi0", -1),
- Op.check("/multi1/", 100), Op.check("/multi2", 5));
+ opList = Arrays.asList(
+ Op.check("/multi0", -1), Op.check("/multi1/", 100),
+ Op.check("/multi2", 5));
expectedErr = "Path must not end with / character";
multiHavingErrors(zk, opList, expectedResultCodes, expectedErr);
// delete
- opList = Arrays.asList(Op.delete("/multi0", -1),
- Op.delete("/multi1/", 100), Op.delete("/multi2", 5));
+ opList = Arrays.asList(
+ Op.delete("/multi0", -1),
+ Op.delete("/multi1/", 100),
+ Op.delete("/multi2", 5));
multiHavingErrors(zk, opList, expectedResultCodes, expectedErr);
// Multiple bad arguments
expectedResultCodes.add(KeeperException.Code.BADARGUMENTS.intValue());
// setdata
- opList = Arrays.asList(Op.setData("/multi0", new byte[0], -1),
+ opList = Arrays.asList(
+ Op.setData("/multi0", new byte[0], -1),
Op.setData("/multi1/", new byte[0], -1),
Op.setData("/multi2", new byte[0], -1),
Op.setData("multi3", new byte[0], -1));
@@ -272,7 +266,7 @@ public class MultiOperationTest extends ClientBase {
List<Op> opList = Arrays.asList(Op.delete("/foo", -1));
try {
zk.multi(opList);
- Assert.fail("multi delete should failed for not empty directory");
+ fail("multi delete should failed for not empty directory");
} catch (KeeperException.NotEmptyException e) {
}
@@ -281,7 +275,7 @@ public class MultiOperationTest extends ClientBase {
zk.exists("/foo/bar", new Watcher() {
@Override
public void process(WatchedEvent event) {
- if (event.getType() == Event.EventType.NodeDeleted){
+ if (event.getType() == Event.EventType.NodeDeleted) {
latch.countDown();
}
}
@@ -293,7 +287,7 @@ public class MultiOperationTest extends ClientBase {
try {
zk.getData("/foo/bar", false, null);
- Assert.fail("ephemeral node should have been deleted");
+ fail("ephemeral node should have been deleted");
} catch (KeeperException.NoNodeException e) {
}
@@ -301,7 +295,7 @@ public class MultiOperationTest extends ClientBase {
try {
zk.getData("/foo", false, null);
- Assert.fail("persistent node should have been deleted after multi");
+ fail("persistent node should have been deleted after multi");
} catch (KeeperException.NoNodeException e) {
}
}
@@ -312,17 +306,17 @@ public class MultiOperationTest extends ClientBase {
@Test(timeout = 90000)
public void testBlankPath() throws Exception {
List<Integer> expectedResultCodes = new ArrayList<Integer>();
- expectedResultCodes.add(KeeperException.Code.RUNTIMEINCONSISTENCY
- .intValue());
+ expectedResultCodes.add(KeeperException.Code.RUNTIMEINCONSISTENCY.intValue());
expectedResultCodes.add(KeeperException.Code.BADARGUMENTS.intValue());
- expectedResultCodes.add(KeeperException.Code.RUNTIMEINCONSISTENCY
- .intValue());
+ expectedResultCodes.add(KeeperException.Code.RUNTIMEINCONSISTENCY.intValue());
expectedResultCodes.add(KeeperException.Code.BADARGUMENTS.intValue());
// delete
String expectedErr = "Path cannot be null";
- List<Op> opList = Arrays.asList(Op.delete("/multi0", -1),
- Op.delete(null, 100), Op.delete("/multi2", 5),
+ List<Op> opList = Arrays.asList(
+ Op.delete("/multi0", -1),
+ Op.delete(null, 100),
+ Op.delete("/multi2", 5),
Op.delete("", -1));
multiHavingErrors(zk, opList, expectedResultCodes, expectedErr);
}
@@ -333,18 +327,15 @@ public class MultiOperationTest extends ClientBase {
@Test(timeout = 90000)
public void testInvalidCreateModeFlag() throws Exception {
List<Integer> expectedResultCodes = new ArrayList<Integer>();
- expectedResultCodes.add(KeeperException.Code.RUNTIMEINCONSISTENCY
- .intValue());
+ expectedResultCodes.add(KeeperException.Code.RUNTIMEINCONSISTENCY.intValue());
expectedResultCodes.add(KeeperException.Code.BADARGUMENTS.intValue());
- expectedResultCodes.add(KeeperException.Code.RUNTIMEINCONSISTENCY
- .intValue());
+ expectedResultCodes.add(KeeperException.Code.RUNTIMEINCONSISTENCY.intValue());
int createModeFlag = 6789;
- List<Op> opList = Arrays.asList(Op.create("/multi0", new byte[0],
- Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT), Op.create(
- "/multi1", new byte[0], Ids.OPEN_ACL_UNSAFE, createModeFlag),
- Op.create("/multi2", new byte[0], Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT));
+ List<Op> opList = Arrays.asList(
+ Op.create("/multi0", new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT),
+ Op.create("/multi1", new byte[0], Ids.OPEN_ACL_UNSAFE, createModeFlag),
+ Op.create("/multi2", new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT));
String expectedErr = KeeperException.Code.BADARGUMENTS.name();
multiHavingErrors(zk, opList, expectedResultCodes, expectedErr);
}
@@ -355,24 +346,18 @@ public class MultiOperationTest extends ClientBase {
String chRoot = createNameSpace();
// Creating child using chRoot client.
zk_chroot = createClient(this.hostPort + chRoot);
- Op createChild = Op.create("/myid", new byte[0],
- Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
+ Op createChild = Op.create("/myid", new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
multi(zk_chroot, Arrays.asList(createChild));
-
- Assert.assertNotNull("zNode is not created under chroot:" + chRoot, zk
- .exists(chRoot + "/myid", false));
- Assert.assertNotNull("zNode is not created under chroot:" + chRoot,
- zk_chroot.exists("/myid", false));
- Assert.assertNull("zNode is created directly under '/', ignored configured chroot",
- zk.exists("/myid", false));
-
+
+ assertNotNull("zNode is not created under chroot:" + chRoot, zk.exists(chRoot + "/myid", false));
+ assertNotNull("zNode is not created under chroot:" + chRoot, zk_chroot.exists("/myid", false));
+ assertNull("zNode is created directly under '/', ignored configured chroot", zk.exists("/myid", false));
+
// Deleting child using chRoot client.
Op deleteChild = Op.delete("/myid", 0);
multi(zk_chroot, Arrays.asList(deleteChild));
- Assert.assertNull("zNode exists under chroot:" + chRoot, zk.exists(
- chRoot + "/myid", false));
- Assert.assertNull("zNode exists under chroot:" + chRoot, zk_chroot
- .exists("/myid", false));
+ assertNull("zNode exists under chroot:" + chRoot, zk.exists(chRoot + "/myid", false));
+ assertNull("zNode exists under chroot:" + chRoot, zk_chroot.exists("/myid", false));
}
@Test
@@ -385,16 +370,14 @@ public class MultiOperationTest extends ClientBase {
List<Op> ops = new ArrayList<Op>();
for (int i = 0; i < names.length; i++) {
- ops.add(Op.create(names[i], new byte[0], Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT));
+ ops.add(Op.create(names[i], new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT));
ops.add(Op.setData(names[i], names[i].getBytes(), 0));
}
- multi(zk_chroot, ops) ;
+ multi(zk_chroot, ops);
for (int i = 0; i < names.length; i++) {
- Assert.assertArrayEquals("zNode data not matching", names[i]
- .getBytes(), zk_chroot.getData(names[i], false, null));
+ assertArrayEquals("zNode data not matching", names[i].getBytes(), zk_chroot.getData(names[i], false, null));
}
}
@@ -408,13 +391,12 @@ public class MultiOperationTest extends ClientBase {
List<Op> ops = new ArrayList<Op>();
for (int i = 0; i < names.length; i++) {
- zk.create(chRoot + names[i], new byte[0], Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk.create(chRoot + names[i], new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
}
for (int i = 0; i < names.length; i++) {
ops.add(Op.check(names[i], 0));
}
- multi(zk_chroot, ops) ;
+ multi(zk_chroot, ops);
}
@Test
@@ -425,50 +407,39 @@ public class MultiOperationTest extends ClientBase {
zk_chroot = createClient(this.hostPort + chRoot);
String childPath = "/myid";
Transaction transaction = zk_chroot.transaction();
- transaction.create(childPath, new byte[0], Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ transaction.create(childPath, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
transaction.check(childPath, 0);
transaction.setData(childPath, childPath.getBytes(), 0);
commit(transaction);
- Assert.assertNotNull("zNode is not created under chroot:" + chRoot, zk
- .exists(chRoot + childPath, false));
- Assert.assertNotNull("zNode is not created under chroot:" + chRoot,
- zk_chroot.exists(childPath, false));
- Assert.assertNull("zNode is created directly under '/', ignored configured chroot",
- zk.exists(childPath, false));
- Assert.assertArrayEquals("zNode data not matching", childPath
- .getBytes(), zk_chroot.getData(childPath, false, null));
+ assertNotNull("zNode is not created under chroot:" + chRoot, zk.exists(chRoot + childPath, false));
+ assertNotNull("zNode is not created under chroot:" + chRoot, zk_chroot.exists(childPath, false));
+ assertNull("zNode is created directly under '/', ignored configured chroot", zk.exists(childPath, false));
+ assertArrayEquals("zNode data not matching", childPath.getBytes(), zk_chroot.getData(childPath, false, null));
transaction = zk_chroot.transaction();
// Deleting child using chRoot client.
transaction.delete(childPath, 1);
commit(transaction);
- Assert.assertNull("chroot:" + chRoot + " exists after delete", zk
- .exists(chRoot + "/myid", false));
- Assert.assertNull("chroot:" + chRoot + " exists after delete",
- zk_chroot.exists("/myid", false));
+ assertNull("chroot:" + chRoot + " exists after delete", zk.exists(chRoot + "/myid", false));
+ assertNull("chroot:" + chRoot + " exists after delete", zk_chroot.exists("/myid", false));
}
- private String createNameSpace() throws InterruptedException,
- KeeperException {
+ private String createNameSpace() throws InterruptedException, KeeperException {
// creating the subtree for chRoot clients.
String chRoot = "/appsX";
- Op createChRoot = Op.create(chRoot, new byte[0], Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ Op createChRoot = Op.create(chRoot, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
multi(zk, Arrays.asList(createChRoot));
return chRoot;
}
-
@Test
public void testCreate() throws Exception {
multi(zk, Arrays.asList(
Op.create("/multi0", new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT),
Op.create("/multi1", new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT),
- Op.create("/multi2", new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT)
- ));
+ Op.create("/multi2", new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT)));
zk.getData("/multi0", false, null);
zk.getData("/multi1", false, null);
zk.getData("/multi2", false, null);
@@ -479,11 +450,10 @@ public class MultiOperationTest extends ClientBase {
multi(zk, Arrays.asList(
Op.create("/multi", new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT),
- Op.delete("/multi", 0)
- ));
+ Op.delete("/multi", 0)));
// '/multi' should have been deleted
- Assert.assertNull(zk.exists("/multi", null));
+ assertNull(zk.exists("/multi", null));
}
@Test
@@ -492,9 +462,8 @@ public class MultiOperationTest extends ClientBase {
try {
multi(zk, Arrays.asList(
Op.create("/multi", new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT),
- Op.delete("/multi", 1)
- ));
- Assert.fail("delete /multi should have failed");
+ Op.delete("/multi", 1)));
+ fail("delete /multi should have failed");
} catch (KeeperException e) {
/* PASS */
}
@@ -505,20 +474,15 @@ public class MultiOperationTest extends ClientBase {
multi(zk, Arrays.asList(
/* Create */
- Op.create("/multi", new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT),
- Op.create("/multi/a", new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT),
- Op.create("/multi/a/1", new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT),
+ Op.create("/multi", new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT), Op.create("/multi/a", new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT), Op.create("/multi/a/1", new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT),
/* Delete */
- Op.delete("/multi/a/1", 0),
- Op.delete("/multi/a", 0),
- Op.delete("/multi", 0)
- ));
+ Op.delete("/multi/a/1", 0), Op.delete("/multi/a", 0), Op.delete("/multi", 0)));
//Verify tree deleted
- Assert.assertNull(zk.exists("/multi/a/1", null));
- Assert.assertNull(zk.exists("/multi/a", null));
- Assert.assertNull(zk.exists("/multi", null));
+ assertNull(zk.exists("/multi/a/1", null));
+ assertNull(zk.exists("/multi/a", null));
+ assertNull(zk.exists("/multi", null));
}
@Test
@@ -532,40 +496,38 @@ public class MultiOperationTest extends ClientBase {
ops.add(Op.setData(names[i], names[i].getBytes(), 0));
}
- multi(zk, ops) ;
+ multi(zk, ops);
for (int i = 0; i < names.length; i++) {
- Assert.assertArrayEquals(names[i].getBytes(), zk.getData(names[i], false, null));
+ assertArrayEquals(names[i].getBytes(), zk.getData(names[i], false, null));
}
}
@Test
public void testUpdateConflict() throws Exception {
- Assert.assertNull(zk.exists("/multi", null));
+ assertNull(zk.exists("/multi", null));
try {
multi(zk, Arrays.asList(
Op.create("/multi", new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT),
Op.setData("/multi", "X".getBytes(), 0),
- Op.setData("/multi", "Y".getBytes(), 0)
- ));
- Assert.fail("Should have thrown a KeeperException for invalid version");
+ Op.setData("/multi", "Y".getBytes(), 0)));
+ fail("Should have thrown a KeeperException for invalid version");
} catch (KeeperException e) {
//PASS
LOG.error("STACKTRACE: ", e);
}
- Assert.assertNull(zk.exists("/multi", null));
+ assertNull(zk.exists("/multi", null));
//Updating version solves conflict -- order matters
multi(zk, Arrays.asList(
Op.create("/multi", new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT),
Op.setData("/multi", "X".getBytes(), 0),
- Op.setData("/multi", "Y".getBytes(), 1)
- ));
+ Op.setData("/multi", "Y".getBytes(), 1)));
- Assert.assertArrayEquals(zk.getData("/multi", false, null), "Y".getBytes());
+ assertArrayEquals(zk.getData("/multi", false, null), "Y".getBytes());
}
@Test
@@ -574,17 +536,16 @@ public class MultiOperationTest extends ClientBase {
/* Delete of a node folowed by an update of the (now) deleted node */
try {
multi(zk, Arrays.asList(
- Op.create("/multi", new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT),
- Op.delete("/multi", 0),
- Op.setData("/multi", "Y".getBytes(), 0)
- ));
- Assert.fail("/multi should have been deleted so setData should have failed");
+ Op.create("/multi", new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT),
+ Op.delete("/multi", 0),
+ Op.setData("/multi", "Y".getBytes(), 0)));
+ fail("/multi should have been deleted so setData should have failed");
} catch (KeeperException e) {
/* PASS */
}
// '/multi' should never have been created as entire op should fail
- Assert.assertNull(zk.exists("/multi", null)) ;
+ assertNull(zk.exists("/multi", null));
}
@Test
@@ -594,15 +555,13 @@ public class MultiOperationTest extends ClientBase {
Op.create("/multi", new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT),
Op.delete("/multi", 0),
Op.setData("/multi", "Y".getBytes(), 0),
- Op.create("/foo", new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT)
- );
+ Op.create("/foo", new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT));
List<OpResult> results = null;
if (useAsync) {
final MultiResult res = new MultiResult();
zk.multi(ops, new MultiCallback() {
@Override
- public void processResult(int rc, String path, Object ctx,
- List<OpResult> opResults) {
+ public void processResult(int rc, String path, Object ctx, List<OpResult> opResults) {
synchronized (res) {
res.rc = rc;
res.results = opResults;
@@ -616,22 +575,22 @@ public class MultiOperationTest extends ClientBase {
res.wait();
}
}
- Assert.assertFalse("/multi should have been deleted so setData should have failed",
- KeeperException.Code.OK.intValue() == res.rc);
- Assert.assertNull(zk.exists("/multi", null));
+ assertFalse("/multi should have been deleted so setData should have failed", KeeperException.Code.OK.intValue()
+ == res.rc);
+ assertNull(zk.exists("/multi", null));
results = res.results;
} else {
try {
zk.multi(ops);
- Assert.fail("/multi should have been deleted so setData should have failed");
+ fail("/multi should have been deleted so setData should have failed");
} catch (KeeperException e) {
// '/multi' should never have been created as entire op should fail
- Assert.assertNull(zk.exists("/multi", null));
+ assertNull(zk.exists("/multi", null));
results = e.getResults();
}
}
- Assert.assertNotNull(results);
+ assertNotNull(results);
for (OpResult r : results) {
LOG.info("RESULT==> {}", r);
if (r instanceof ErrorResult) {
@@ -646,49 +605,30 @@ public class MultiOperationTest extends ClientBase {
*/
@Test
public void testOpResultEquals() {
- opEquals(new CreateResult("/foo"),
- new CreateResult("/foo"),
- new CreateResult("nope"));
-
- opEquals(new CreateResult("/foo"),
- new CreateResult("/foo"),
- new CreateResult("/foo", new Stat(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11)));
-
- opEquals(new CreateResult("/foo", new Stat(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11)),
- new CreateResult("/foo", new Stat(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11)),
- new CreateResult("nope", new Stat(11, 12, 13, 14, 15, 16, 17, 18, 19, 110, 111)));
-
- opEquals(new CreateResult("/foo", new Stat(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11)),
- new CreateResult("/foo", new Stat(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11)),
- new CreateResult("/foo"));
-
- opEquals(new CheckResult(),
- new CheckResult(),
- null);
-
- opEquals(new SetDataResult(new Stat(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11)),
- new SetDataResult(new Stat(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11)),
- new SetDataResult(new Stat(11, 12, 13, 14, 15, 16, 17, 18, 19, 110, 111)));
-
- opEquals(new ErrorResult(1),
- new ErrorResult(1),
- new ErrorResult(2));
-
- opEquals(new DeleteResult(),
- new DeleteResult(),
- null);
-
- opEquals(new ErrorResult(1),
- new ErrorResult(1),
- new ErrorResult(2));
+ opEquals(new CreateResult("/foo"), new CreateResult("/foo"), new CreateResult("nope"));
+
+ opEquals(new CreateResult("/foo"), new CreateResult("/foo"), new CreateResult("/foo", new Stat(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11)));
+
+ opEquals(new CreateResult("/foo", new Stat(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11)), new CreateResult("/foo", new Stat(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11)), new CreateResult("nope", new Stat(11, 12, 13, 14, 15, 16, 17, 18, 19, 110, 111)));
+
+ opEquals(new CreateResult("/foo", new Stat(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11)), new CreateResult("/foo", new Stat(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11)), new CreateResult("/foo"));
+
+ opEquals(new CheckResult(), new CheckResult(), null);
+
+ opEquals(new SetDataResult(new Stat(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11)), new SetDataResult(new Stat(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11)), new SetDataResult(new Stat(11, 12, 13, 14, 15, 16, 17, 18, 19, 110, 111)));
+
+ opEquals(new ErrorResult(1), new ErrorResult(1), new ErrorResult(2));
+
+ opEquals(new DeleteResult(), new DeleteResult(), null);
+
+ opEquals(new ErrorResult(1), new ErrorResult(1), new ErrorResult(2));
}
private void opEquals(OpResult expected, OpResult value, OpResult near) {
assertEquals(value, value);
assertFalse(value.equals(new Object()));
assertFalse(value.equals(near));
- assertFalse(value.equals(value instanceof CreateResult ?
- new ErrorResult(1) : new CreateResult("nope2")));
+ assertFalse(value.equals(value instanceof CreateResult ? new ErrorResult(1) : new CreateResult("nope2")));
assertTrue(value.equals(expected));
}
@@ -698,8 +638,7 @@ public class MultiOperationTest extends ClientBase {
zk.getChildren("/", watcher);
multi(zk, Arrays.asList(
Op.create("/t", new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT),
- Op.delete("/t", -1)
- ));
+ Op.delete("/t", -1)));
assertTrue(watcher.triggered.await(CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS));
}
@@ -710,8 +649,7 @@ public class MultiOperationTest extends ClientBase {
try {
multi(zk, Arrays.asList(
Op.create("/t", new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT),
- Op.delete("/nonexisting", -1)
- ));
+ Op.delete("/nonexisting", -1)));
fail("expected previous multi op to fail!");
} catch (KeeperException.NoNodeException e) {
// expected
@@ -723,72 +661,54 @@ public class MultiOperationTest extends ClientBase {
cb.done.await(CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS);
assertEquals(1, watcher.triggered.getCount());
}
-
+
@Test
public void testTransactionBuilder() throws Exception {
- List<OpResult> results = commit(zk.transaction()
- .create("/t1", new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT)
- .create("/t1/child", new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT)
- .create("/t2", null, Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL));
+ List<OpResult> results = commit(zk.transaction().create("/t1", new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT).create("/t1/child", new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT).create("/t2", null, Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL));
assertEquals(3, results.size());
for (OpResult r : results) {
- CreateResult c = (CreateResult)r;
+ CreateResult c = (CreateResult) r;
assertTrue(c.getPath().startsWith("/t"));
assertNotNull(c.toString());
}
assertNotNull(zk.exists("/t1", false));
assertNotNull(zk.exists("/t1/child", false));
assertNotNull(zk.exists("/t2", false));
-
- results = commit(zk.transaction()
- .check("/t1", 0)
- .check("/t1/child", 0)
- .check("/t2", 0));
+
+ results = commit(zk.transaction().check("/t1", 0).check("/t1/child", 0).check("/t2", 0));
assertEquals(3, results.size());
for (OpResult r : results) {
- CheckResult c = (CheckResult)r;
+ CheckResult c = (CheckResult) r;
assertNotNull(c.toString());
}
-
+
try {
- results = commit(zk.transaction()
- .check("/t1", 0)
- .check("/t1/child", 0)
- .check("/t2", 1));
+ results = commit(zk.transaction().check("/t1", 0).check("/t1/child", 0).check("/t2", 1));
fail();
} catch (KeeperException.BadVersionException e) {
// expected
}
-
- results = commit(zk.transaction()
- .check("/t1", 0)
- .setData("/t1", new byte[0], 0));
+
+ results = commit(zk.transaction().check("/t1", 0).setData("/t1", new byte[0], 0));
assertEquals(2, results.size());
for (OpResult r : results) {
assertNotNull(r.toString());
}
try {
- results = commit(zk.transaction()
- .check("/t1", 1)
- .setData("/t1", new byte[0], 2));
+ results = commit(zk.transaction().check("/t1", 1).setData("/t1", new byte[0], 2));
fail();
} catch (KeeperException.BadVersionException e) {
// expected
}
-
- results = commit(zk.transaction()
- .check("/t1", 1)
- .check("/t1/child", 0)
- .check("/t2", 0));
+
+ results = commit(zk.transaction().check("/t1", 1).check("/t1/child", 0).check("/t2", 0));
assertEquals(3, results.size());
- results = commit(zk.transaction()
- .delete("/t2", -1)
- .delete("/t1/child", -1));
+ results = commit(zk.transaction().delete("/t2", -1).delete("/t1/child", -1));
assertEquals(2, results.size());
for (OpResult r : results) {
- DeleteResult d = (DeleteResult)r;
+ DeleteResult d = (DeleteResult) r;
assertNotNull(d.toString());
}
assertNotNull(zk.exists("/t1", false));
@@ -803,31 +723,27 @@ public class MultiOperationTest extends ClientBase {
// Creating a database where '/fooX' nodes has 'barXY' named children.
for (int i = 0; i < 10; i++) {
String name = "/foo" + i;
- zk.create(name, name.getBytes(), Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk.create(name, name.getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
topLevelNodes.add(name);
childrenNodes.put(name, new ArrayList<>());
for (int j = 0; j < 10; j++) {
String childname = name + "/bar" + i + j;
String childname_s = "bar" + i + j;
- zk.create(childname, childname.getBytes(), Ids.OPEN_ACL_UNSAFE,
- CreateMode.EPHEMERAL);
+ zk.create(childname, childname.getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
childrenNodes.get(name).add(childname_s);
}
}
// Create a multi operation, which queries the children of the nodes in topLevelNodes.
- List<OpResult> multiChildrenList =
- multi(zk, topLevelNodes.stream().map(Op::getChildren).collect(Collectors.toList()));
+ List<OpResult> multiChildrenList = multi(zk, topLevelNodes.stream().map(Op::getChildren).collect(Collectors.toList()));
for (int i = 0; i < topLevelNodes.size(); i++) {
String nodeName = topLevelNodes.get(i);
- Assert.assertTrue(multiChildrenList.get(i) instanceof OpResult.GetChildrenResult);
+ assertTrue(multiChildrenList.get(i) instanceof OpResult.GetChildrenResult);
List<String> childrenList = ((OpResult.GetChildrenResult) multiChildrenList.get(i)).getChildren();
// In general, we do not demand an order from the children list but to contain every child.
- Assert.assertEquals(new TreeSet<String>(childrenList),
- new TreeSet<String>(childrenNodes.get(nodeName)));
+ assertEquals(new TreeSet<String>(childrenList), new TreeSet<String>(childrenNodes.get(nodeName)));
List<String> children = zk.getChildren(nodeName, false);
- Assert.assertEquals(childrenList, children);
+ assertEquals(childrenList, children);
}
}
@@ -836,13 +752,11 @@ public class MultiOperationTest extends ClientBase {
List<String> childrenNodes = new ArrayList<String>();
// Creating a database where '/foo' node has 'barX' named children.
String topLevelNode = "/foo";
- zk.create(topLevelNode, topLevelNode.getBytes(), Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk.create(topLevelNode, topLevelNode.getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
for (int i = 0; i < 10; i++) {
String childname = topLevelNode + "/bar" + i;
String childname_s = "bar" + i;
- zk.create(childname, childname.getBytes(), Ids.OPEN_ACL_UNSAFE,
- CreateMode.EPHEMERAL);
+ zk.create(childname, childname.getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
childrenNodes.add(childname_s);
}
@@ -851,46 +765,42 @@ public class MultiOperationTest extends ClientBase {
Op.getChildren(topLevelNode),
Op.getChildren(topLevelNode)));
// The response should contain two elements which are the same.
- Assert.assertEquals(sameChildrenList.size(), 2);
- Assert.assertEquals(sameChildrenList.get(0), sameChildrenList.get(1));
+ assertEquals(sameChildrenList.size(), 2);
+ assertEquals(sameChildrenList.get(0), sameChildrenList.get(1));
// Check the actual result.
- Assert.assertTrue(sameChildrenList.get(0) instanceof OpResult.GetChildrenResult);
+ assertTrue(sameChildrenList.get(0) instanceof OpResult.GetChildrenResult);
OpResult.GetChildrenResult gcr = (OpResult.GetChildrenResult) sameChildrenList.get(0);
// In general, we do not demand an order from the children list but to contain every child.
- Assert.assertEquals(new TreeSet<String>(gcr.getChildren()),
- new TreeSet<String>(childrenNodes));
+ assertEquals(new TreeSet<String>(gcr.getChildren()), new TreeSet<String>(childrenNodes));
}
@Test
public void testMultiGetChildrenAuthentication() throws KeeperException, InterruptedException {
- List<ACL> writeOnly = Collections.singletonList(new ACL(ZooDefs.Perms.WRITE,
- new Id("world", "anyone")));
+ List<ACL> writeOnly = Collections.singletonList(new ACL(ZooDefs.Perms.WRITE, new Id("world", "anyone")));
zk.create("/foo_auth", null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
zk.create("/foo_auth/bar", null, Ids.READ_ACL_UNSAFE, CreateMode.PERSISTENT);
zk.create("/foo_no_auth", null, writeOnly, CreateMode.PERSISTENT);
// Check for normal behaviour.
List<OpResult> multiChildrenList = multi(zk, Arrays.asList(Op.getChildren("/foo_auth")));
- Assert.assertEquals(multiChildrenList.size(), 1);
- Assert.assertTrue(multiChildrenList.get(0) instanceof OpResult.GetChildrenResult);
+ assertEquals(multiChildrenList.size(), 1);
+ assertTrue(multiChildrenList.get(0) instanceof OpResult.GetChildrenResult);
List<String> childrenList = ((OpResult.GetChildrenResult) multiChildrenList.get(0)).getChildren();
- Assert.assertEquals(childrenList.size(), 1);
- Assert.assertEquals(childrenList.get(0), "bar");
+ assertEquals(childrenList.size(), 1);
+ assertEquals(childrenList.get(0), "bar");
// Check for authentication violation.
multiChildrenList = multi(zk, Arrays.asList(Op.getChildren("/foo_no_auth")));
- Assert.assertEquals(multiChildrenList.size(), 1);
- Assert.assertTrue(multiChildrenList.get(0) instanceof OpResult.ErrorResult);
- Assert.assertEquals("Expected NoAuthException for getting the children of a write only node",
- ((OpResult.ErrorResult) multiChildrenList.get(0)).getErr(), KeeperException.Code.NOAUTH.intValue());
+ assertEquals(multiChildrenList.size(), 1);
+ assertTrue(multiChildrenList.get(0) instanceof OpResult.ErrorResult);
+ assertEquals("Expected NoAuthException for getting the children of a write only node", ((OpResult.ErrorResult) multiChildrenList.get(0)).getErr(), KeeperException.Code.NOAUTH.intValue());
}
@Test
public void testMultiGetChildrenMixedAuthenticationErrorFirst() throws KeeperException, InterruptedException {
- List<ACL> writeOnly = Collections.singletonList(new ACL(ZooDefs.Perms.WRITE,
- new Id("world", "anyone")));
+ List<ACL> writeOnly = Collections.singletonList(new ACL(ZooDefs.Perms.WRITE, new Id("world", "anyone")));
zk.create("/foo_auth", null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
zk.create("/foo_auth/bar", null, Ids.READ_ACL_UNSAFE, CreateMode.PERSISTENT);
zk.create("/foo_no_auth", null, writeOnly, CreateMode.PERSISTENT);
@@ -899,21 +809,19 @@ public class MultiOperationTest extends ClientBase {
// Mixed nodes, the operation after the error should return RuntimeInconsistency error.
multiChildrenList = multi(zk, Arrays.asList(Op.getChildren("/foo_no_auth"), Op.getChildren("/foo_auth")));
- Assert.assertEquals(multiChildrenList.size(), 2);
- Assert.assertTrue(multiChildrenList.get(0) instanceof OpResult.ErrorResult);
- Assert.assertEquals("Expected NoAuthException for getting the children of a write only node",
- ((OpResult.ErrorResult) multiChildrenList.get(0)).getErr(), KeeperException.Code.NOAUTH.intValue());
+ assertEquals(multiChildrenList.size(), 2);
+ assertTrue(multiChildrenList.get(0) instanceof OpResult.ErrorResult);
+ assertEquals("Expected NoAuthException for getting the children of a write only node", ((OpResult.ErrorResult) multiChildrenList.get(0)).getErr(), KeeperException.Code.NOAUTH.intValue());
- Assert.assertTrue(multiChildrenList.get(1) instanceof OpResult.GetChildrenResult);
+ assertTrue(multiChildrenList.get(1) instanceof OpResult.GetChildrenResult);
List<String> childrenList = ((OpResult.GetChildrenResult) multiChildrenList.get(1)).getChildren();
- Assert.assertEquals(childrenList.size(), 1);
- Assert.assertEquals(childrenList.get(0), "bar");
+ assertEquals(childrenList.size(), 1);
+ assertEquals(childrenList.get(0), "bar");
}
@Test
public void testMultiGetChildrenMixedAuthenticationCorrectFirst() throws KeeperException, InterruptedException {
- List<ACL> writeOnly = Collections.singletonList(new ACL(ZooDefs.Perms.WRITE,
- new Id("world", "anyone")));
+ List<ACL> writeOnly = Collections.singletonList(new ACL(ZooDefs.Perms.WRITE, new Id("world", "anyone")));
zk.create("/foo_auth", null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
zk.create("/foo_auth/bar", null, Ids.READ_ACL_UNSAFE, CreateMode.PERSISTENT);
zk.create("/foo_no_auth", null, writeOnly, CreateMode.PERSISTENT);
@@ -922,16 +830,15 @@ public class MultiOperationTest extends ClientBase {
// The getChildren operation returns GetChildrenResult if it happened before the error.
List<OpResult> multiChildrenList;
multiChildrenList = multi(zk, Arrays.asList(Op.getChildren("/foo_auth"), Op.getChildren("/foo_no_auth")));
- Assert.assertSame(multiChildrenList.size(), 2);
+ assertSame(multiChildrenList.size(), 2);
- Assert.assertTrue(multiChildrenList.get(0) instanceof OpResult.GetChildrenResult);
+ assertTrue(multiChildrenList.get(0) instanceof OpResult.GetChildrenResult);
List<String> childrenList = ((OpResult.GetChildrenResult) multiChildrenList.get(0)).getChildren();
- Assert.assertEquals(childrenList.size(), 1);
- Assert.assertEquals(childrenList.get(0), "bar");
+ assertEquals(childrenList.size(), 1);
+ assertEquals(childrenList.get(0), "bar");
- Assert.assertTrue(multiChildrenList.get(1) instanceof OpResult.ErrorResult);
- Assert.assertEquals("Expected NoAuthException for getting the children of a write only node",
- ((OpResult.ErrorResult) multiChildrenList.get(1)).getErr(), KeeperException.Code.NOAUTH.intValue());
+ assertTrue(multiChildrenList.get(1) instanceof OpResult.ErrorResult);
+ assertEquals("Expected NoAuthException for getting the children of a write only node", ((OpResult.ErrorResult) multiChildrenList.get(1)).getErr(), KeeperException.Code.NOAUTH.intValue());
}
@Test
@@ -940,9 +847,9 @@ public class MultiOperationTest extends ClientBase {
zk.create("/node2", "data2".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
List<OpResult> multiData = multi(zk, Arrays.asList(Op.getData("/node1"), Op.getData("/node2")));
- Assert.assertEquals(multiData.size(), 2);
- Assert.assertArrayEquals(((OpResult.GetDataResult) multiData.get(0)).getData(),"data1".getBytes());
- Assert.assertArrayEquals(((OpResult.GetDataResult) multiData.get(1)).getData(),"data2".getBytes());
+ assertEquals(multiData.size(), 2);
+ assertArrayEquals(((OpResult.GetDataResult) multiData.get(0)).getData(), "data1".getBytes());
+ assertArrayEquals(((OpResult.GetDataResult) multiData.get(1)).getData(), "data2".getBytes());
}
@Test
@@ -952,69 +859,78 @@ public class MultiOperationTest extends ClientBase {
zk.create("/node1/node1", "data11".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
zk.create("/node1/node2", "data12".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
- List<OpResult> multiRead = multi(zk, Arrays.asList(Op.getChildren("/node1"), Op.getData("/node1"),
- Op.getChildren("/node2"), Op.getData("/node2")));
- Assert.assertEquals(multiRead.size(), 4);
- Assert.assertTrue(multiRead.get(0) instanceof OpResult.GetChildrenResult);
+ List<OpResult> multiRead = multi(zk, Arrays.asList(
+ Op.getChildren("/node1"),
+ Op.getData("/node1"),
+ Op.getChildren("/node2"),
+ Op.getData("/node2")));
+ assertEquals(multiRead.size(), 4);
+ assertTrue(multiRead.get(0) instanceof OpResult.GetChildrenResult);
List<String> childrenList = ((OpResult.GetChildrenResult) multiRead.get(0)).getChildren();
- Assert.assertEquals(childrenList.size(), 2);
- Assert.assertEquals(new TreeSet<String>(childrenList), new TreeSet<String>(Arrays.asList("node1", "node2")));
+ assertEquals(childrenList.size(), 2);
+ assertEquals(new TreeSet<String>(childrenList), new TreeSet<String>(Arrays.asList("node1", "node2")));
- Assert.assertArrayEquals(((OpResult.GetDataResult) multiRead.get(1)).getData(),"data1".getBytes());
+ assertArrayEquals(((OpResult.GetDataResult) multiRead.get(1)).getData(), "data1".getBytes());
Stat stat = ((OpResult.GetDataResult) multiRead.get(1)).getStat();
- Assert.assertEquals(stat.getMzxid(), stat.getCzxid());
- Assert.assertEquals(stat.getCtime(), stat.getMtime());
- Assert.assertEquals(2, stat.getCversion());
- Assert.assertEquals(0, stat.getVersion());
- Assert.assertEquals(0, stat.getAversion());
- Assert.assertEquals(0, stat.getEphemeralOwner());
- Assert.assertEquals(5, stat.getDataLength());
- Assert.assertEquals(2, stat.getNumChildren());
-
- Assert.assertTrue(multiRead.get(2) instanceof OpResult.GetChildrenResult);
+ assertEquals(stat.getMzxid(), stat.getCzxid());
+ assertEquals(stat.getCtime(), stat.getMtime());
+ assertEquals(2, stat.getCversion());
+ assertEquals(0, stat.getVersion());
+ assertEquals(0, stat.getAversion());
+ assertEquals(0, stat.getEphemeralOwner());
+ assertEquals(5, stat.getDataLength());
+ assertEquals(2, stat.getNumChildren());
+
+ assertTrue(multiRead.get(2) instanceof OpResult.GetChildrenResult);
childrenList = ((OpResult.GetChildrenResult) multiRead.get(2)).getChildren();
- Assert.assertTrue(childrenList.isEmpty());
+ assertTrue(childrenList.isEmpty());
- Assert.assertArrayEquals(((OpResult.GetDataResult) multiRead.get(3)).getData(),"data2".getBytes());
+ assertArrayEquals(((OpResult.GetDataResult) multiRead.get(3)).getData(), "data2".getBytes());
stat = ((OpResult.GetDataResult) multiRead.get(3)).getStat();
- Assert.assertEquals(stat.getMzxid(), stat.getCzxid());
- Assert.assertEquals(stat.getMzxid(), stat.getPzxid());
- Assert.assertEquals(stat.getCtime(), stat.getMtime());
- Assert.assertEquals(0, stat.getCversion());
- Assert.assertEquals(0, stat.getVersion());
- Assert.assertEquals(0, stat.getAversion());
- Assert.assertEquals(zk.getSessionId(), stat.getEphemeralOwner());
- Assert.assertEquals(5, stat.getDataLength());
- Assert.assertEquals(0, stat.getNumChildren());
+ assertEquals(stat.getMzxid(), stat.getCzxid());
+ assertEquals(stat.getMzxid(), stat.getPzxid());
+ assertEquals(stat.getCtime(), stat.getMtime());
+ assertEquals(0, stat.getCversion());
+ assertEquals(0, stat.getVersion());
+ assertEquals(0, stat.getAversion());
+ assertEquals(zk.getSessionId(), stat.getEphemeralOwner());
+ assertEquals(5, stat.getDataLength());
+ assertEquals(0, stat.getNumChildren());
}
-
@Test
public void testMixedReadAndTransaction() throws Exception {
zk.create("/node", null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
try {
- List<OpResult> multiRead = multi(zk, Arrays.asList(Op.setData("/node1", "data1".getBytes(), -1),
- Op.getData("/node1")));
- fail("Mixed kind of operations are not allowed");
+ List<OpResult> multiRead = multi(zk, Arrays.asList(
+ Op.setData("/node1", "data1".getBytes(), -1),
+ Op.getData("/node1")));
+ fail("Mixed kind of operations are not allowed");
} catch (IllegalArgumentException e) {
// expected
}
}
private static class HasTriggeredWatcher implements Watcher {
+
private final CountDownLatch triggered = new CountDownLatch(1);
@Override
public void process(WatchedEvent event) {
triggered.countDown();
}
+
}
+
private static class SyncCallback implements AsyncCallback.VoidCallback {
+
private final CountDownLatch done = new CountDownLatch(1);
@Override
public void processResult(int rc, String path, Object ctx) {
done.countDown();
}
+
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/NIOConnectionFactoryFdLeakTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/NIOConnectionFactoryFdLeakTest.java
index d11f71e3e..e9b104f5e 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/NIOConnectionFactoryFdLeakTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/NIOConnectionFactoryFdLeakTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,13 +18,12 @@
package org.apache.zookeeper.test;
+import static org.junit.Assert.assertTrue;
import java.net.InetSocketAddress;
-
import org.apache.zookeeper.PortAssignment;
import org.apache.zookeeper.ZKTestCase;
import org.apache.zookeeper.server.NIOServerCnxnFactory;
import org.apache.zookeeper.server.util.OSMXBean;
-import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -34,14 +33,14 @@ import org.slf4j.LoggerFactory;
* causing fd leakage
*/
public class NIOConnectionFactoryFdLeakTest extends ZKTestCase {
- private static final Logger LOG = LoggerFactory
- .getLogger(NIOConnectionFactoryFdLeakTest.class);
+
+ private static final Logger LOG = LoggerFactory.getLogger(NIOConnectionFactoryFdLeakTest.class);
@Test
public void testFileDescriptorLeak() throws Exception {
OSMXBean osMbean = new OSMXBean();
- if (osMbean.getUnix() != true) {
+ if (!osMbean.getUnix()) {
LOG.info("Unable to run test on non-unix system");
return;
}
@@ -51,9 +50,7 @@ public class NIOConnectionFactoryFdLeakTest extends ZKTestCase {
for (int i = 0; i < 50; ++i) {
NIOServerCnxnFactory factory = new NIOServerCnxnFactory();
- factory.configure(
- new InetSocketAddress(
- "127.0.0.1", PortAssignment.unique()), 10);
+ factory.configure(new InetSocketAddress("127.0.0.1", PortAssignment.unique()), 10);
factory.start();
Thread.sleep(100);
factory.shutdown();
@@ -63,7 +60,7 @@ public class NIOConnectionFactoryFdLeakTest extends ZKTestCase {
LOG.info("End fdcount is: " + endFdCount);
// On my box, if selector.close() is not called fd diff is > 700.
- Assert.assertTrue("Possible fd leakage",
- ((endFdCount - startFdCount) < 50));
+ assertTrue("Possible fd leakage", ((endFdCount - startFdCount) < 50));
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/NettyNettySuiteBase.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/NettyNettySuiteBase.java
index bbcf869e1..ffc2b7613 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/NettyNettySuiteBase.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/NettyNettySuiteBase.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -34,12 +34,11 @@ import org.junit.runners.Suite;
*/
@RunWith(Suite.class)
public class NettyNettySuiteBase {
+
@BeforeClass
public static void setUp() {
- System.setProperty(ServerCnxnFactory.ZOOKEEPER_SERVER_CNXN_FACTORY,
- NettyServerCnxnFactory.class.getName());
- System.setProperty(ZKClientConfig.ZOOKEEPER_CLIENT_CNXN_SOCKET,
- ClientCnxnSocketNetty.class.getName());
+ System.setProperty(ServerCnxnFactory.ZOOKEEPER_SERVER_CNXN_FACTORY, NettyServerCnxnFactory.class.getName());
+ System.setProperty(ZKClientConfig.ZOOKEEPER_CLIENT_CNXN_SOCKET, ClientCnxnSocketNetty.class.getName());
System.setProperty("zookeeper.admin.enableServer", "false");
}
@@ -59,4 +58,5 @@ public class NettyNettySuiteBase {
TestByteBufAllocatorTestHelper.clearTestAllocator();
TestByteBufAllocator.checkForLeaks();
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/NettyNettySuiteHammerTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/NettyNettySuiteHammerTest.java
index 586e5844d..97f4ee161 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/NettyNettySuiteHammerTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/NettyNettySuiteHammerTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -23,8 +23,7 @@ import org.junit.runners.Suite;
/**
* Run tests with: Netty Client against Netty server
*/
-@Suite.SuiteClasses({
- AsyncHammerTest.class
-})
+@Suite.SuiteClasses({AsyncHammerTest.class})
public class NettyNettySuiteHammerTest extends NettyNettySuiteBase {
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/NettyNettySuiteTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/NettyNettySuiteTest.java
index 35710ba3b..074d5868b 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/NettyNettySuiteTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/NettyNettySuiteTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -23,16 +23,7 @@ import org.junit.runners.Suite;
/**
* Run tests with: Netty Client against Netty server
*/
-@Suite.SuiteClasses({
- ACLTest.class,
- AsyncOpsTest.class,
- ChrootClientTest.class,
- ClientTest.class,
- FourLetterWordsTest.class,
- NullDataTest.class,
- ReconfigTest.class,
- SessionTest.class,
- WatcherTest.class
-})
+@Suite.SuiteClasses({ACLTest.class, AsyncOpsTest.class, ChrootClientTest.class, ClientTest.class, FourLetterWordsTest.class, NullDataTest.class, ReconfigTest.class, SessionTest.class, WatcherTest.class})
public class NettyNettySuiteTest extends NettyNettySuiteBase {
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/NioNettySuiteBase.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/NioNettySuiteBase.java
index 836eaa097..1d6b82183 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/NioNettySuiteBase.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/NioNettySuiteBase.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -32,10 +32,10 @@ import org.junit.runners.Suite;
*/
@RunWith(Suite.class)
public class NioNettySuiteBase {
+
@BeforeClass
public static void setUp() {
- System.setProperty(ServerCnxnFactory.ZOOKEEPER_SERVER_CNXN_FACTORY,
- NettyServerCnxnFactory.class.getName());
+ System.setProperty(ServerCnxnFactory.ZOOKEEPER_SERVER_CNXN_FACTORY, NettyServerCnxnFactory.class.getName());
System.setProperty("zookeeper.admin.enableServer", "false");
}
@@ -54,4 +54,5 @@ public class NioNettySuiteBase {
TestByteBufAllocatorTestHelper.clearTestAllocator();
TestByteBufAllocator.checkForLeaks();
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/NioNettySuiteHammerTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/NioNettySuiteHammerTest.java
index 96e7b0caa..1c1a6cc27 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/NioNettySuiteHammerTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/NioNettySuiteHammerTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -23,8 +23,7 @@ import org.junit.runners.Suite;
/**
* Run tests with: Nio Client against Netty server
*/
-@Suite.SuiteClasses({
- AsyncHammerTest.class
- })
+@Suite.SuiteClasses({AsyncHammerTest.class})
public class NioNettySuiteHammerTest extends NioNettySuiteBase {
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/NioNettySuiteTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/NioNettySuiteTest.java
index a1ef33db5..397eb4870 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/NioNettySuiteTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/NioNettySuiteTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -23,16 +23,7 @@ import org.junit.runners.Suite;
/**
* Run tests with: Nio Client against Netty server
*/
-@Suite.SuiteClasses({
- ACLTest.class,
- AsyncOpsTest.class,
- ChrootClientTest.class,
- ClientTest.class,
- FourLetterWordsTest.class,
- NullDataTest.class,
- ReconfigTest.class,
- SessionTest.class,
- WatcherTest.class
- })
+@Suite.SuiteClasses({ACLTest.class, AsyncOpsTest.class, ChrootClientTest.class, ClientTest.class, FourLetterWordsTest.class, NullDataTest.class, ReconfigTest.class, SessionTest.class, WatcherTest.class})
public class NioNettySuiteTest extends NioNettySuiteBase {
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/NonRecoverableErrorTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/NonRecoverableErrorTest.java
index 332a7a31f..f729920e4 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/NonRecoverableErrorTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/NonRecoverableErrorTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -15,34 +15,34 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
package org.apache.zookeeper.test;
import static org.apache.zookeeper.test.ClientBase.CONNECTION_TIMEOUT;
import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
-
import java.io.IOException;
import java.util.UUID;
-
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.PortAssignment;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;
-import org.apache.zookeeper.server.ServerMetrics;
import org.apache.zookeeper.server.ZKDatabase;
import org.apache.zookeeper.server.persistence.FileTxnSnapLog;
import org.apache.zookeeper.server.quorum.QuorumPeer;
import org.apache.zookeeper.server.quorum.QuorumPeer.ServerState;
import org.apache.zookeeper.server.quorum.QuorumPeerTestBase;
import org.apache.zookeeper.test.ClientBase.CountdownWatcher;
-import org.junit.Assert;
import org.junit.Test;
/**
* This class tests the non-recoverable error behavior of quorum server.
*/
public class NonRecoverableErrorTest extends QuorumPeerTestBase {
+
private static final String NODE_PATH = "/noLeaderIssue";
/**
@@ -53,41 +53,37 @@ public class NonRecoverableErrorTest extends QuorumPeerTestBase {
@Test(timeout = 30000)
public void testZooKeeperServiceAvailableOnLeader() throws Exception {
int SERVER_COUNT = 3;
- final int clientPorts[] = new int[SERVER_COUNT];
+ final int[] clientPorts = new int[SERVER_COUNT];
StringBuilder sb = new StringBuilder();
String server;
for (int i = 0; i < SERVER_COUNT; i++) {
clientPorts[i] = PortAssignment.unique();
- server = "server." + i + "=127.0.0.1:" + PortAssignment.unique()
- + ":" + PortAssignment.unique() + ":participant;127.0.0.1:"
- + clientPorts[i];
+ server = "server." + i + "=127.0.0.1:" + PortAssignment.unique() + ":" + PortAssignment.unique()
+ + ":participant;127.0.0.1:" + clientPorts[i];
sb.append(server + "\n");
}
String currentQuorumCfgSection = sb.toString();
- MainThread mt[] = new MainThread[SERVER_COUNT];
+ MainThread[] mt = new MainThread[SERVER_COUNT];
for (int i = 0; i < SERVER_COUNT; i++) {
- mt[i] = new MainThread(i, clientPorts[i], currentQuorumCfgSection,
- false);
+ mt[i] = new MainThread(i, clientPorts[i], currentQuorumCfgSection, false);
mt[i].start();
}
// ensure server started
for (int i = 0; i < SERVER_COUNT; i++) {
- Assert.assertTrue("waiting for server " + i + " being up",
- ClientBase.waitForServerUp("127.0.0.1:" + clientPorts[i],
- CONNECTION_TIMEOUT));
+ assertTrue(
+ "waiting for server " + i + " being up",
+ ClientBase.waitForServerUp("127.0.0.1:" + clientPorts[i], CONNECTION_TIMEOUT));
}
CountdownWatcher watcher = new CountdownWatcher();
- ZooKeeper zk = new ZooKeeper("127.0.0.1:" + clientPorts[0],
- ClientBase.CONNECTION_TIMEOUT, watcher);
+ ZooKeeper zk = new ZooKeeper("127.0.0.1:" + clientPorts[0], ClientBase.CONNECTION_TIMEOUT, watcher);
watcher.waitForConnected(ClientBase.CONNECTION_TIMEOUT);
String data = "originalData";
- zk.create(NODE_PATH, data.getBytes(), Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk.create(NODE_PATH, data.getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
// get information of current leader
QuorumPeer leader = getLeaderQuorumPeer(mt);
@@ -95,15 +91,13 @@ public class NonRecoverableErrorTest extends QuorumPeerTestBase {
// inject problem in leader
FileTxnSnapLog snapLog = leader.getActiveServer().getTxnLogFactory();
- FileTxnSnapLog fileTxnSnapLogWithError = new FileTxnSnapLog(
- snapLog.getDataDir(), snapLog.getSnapDir()) {
+ FileTxnSnapLog fileTxnSnapLogWithError = new FileTxnSnapLog(snapLog.getDataDir(), snapLog.getSnapDir()) {
@Override
public void commit() throws IOException {
throw new IOException("Input/output error");
}
};
- ZKDatabase originalZKDatabase = leader.getActiveServer()
- .getZKDatabase();
+ ZKDatabase originalZKDatabase = leader.getActiveServer().getZKDatabase();
long leaderCurrentEpoch = leader.getCurrentEpoch();
ZKDatabase newDB = new ZKDatabase(fileTxnSnapLogWithError);
@@ -111,8 +105,7 @@ public class NonRecoverableErrorTest extends QuorumPeerTestBase {
try {
// do create operation, so that injected IOException is thrown
- zk.create(uniqueZnode(), data.getBytes(), Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk.create(uniqueZnode(), data.getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
fail("IOException is expected due to error injected to transaction log commit");
} catch (Exception e) {
// do nothing
@@ -127,9 +120,9 @@ public class NonRecoverableErrorTest extends QuorumPeerTestBase {
// ensure server started, give enough time, so that new leader election
// takes place
for (int i = 0; i < SERVER_COUNT; i++) {
- Assert.assertTrue("waiting for server " + i + " being up",
- ClientBase.waitForServerUp("127.0.0.1:" + clientPorts[i],
- CONNECTION_TIMEOUT));
+ assertTrue(
+ "waiting for server " + i + " being up",
+ ClientBase.waitForServerUp("127.0.0.1:" + clientPorts[i], CONNECTION_TIMEOUT));
}
// revert back the error
@@ -141,8 +134,7 @@ public class NonRecoverableErrorTest extends QuorumPeerTestBase {
String uniqueNode = uniqueZnode();
watcher.waitForConnected(ClientBase.CONNECTION_TIMEOUT);
- String createNode = zk.create(uniqueNode, data.getBytes(),
- Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
+ String createNode = zk.create(uniqueNode, data.getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
// if node is created successfully then it means that ZooKeeper service
// is available
assertEquals("Failed to create znode", uniqueNode, createNode);
@@ -153,8 +145,7 @@ public class NonRecoverableErrorTest extends QuorumPeerTestBase {
}
}
- private void waitForNewLeaderElection(QuorumPeer peer,
- long leaderCurrentEpoch) throws IOException, InterruptedException {
+ private void waitForNewLeaderElection(QuorumPeer peer, long leaderCurrentEpoch) throws IOException, InterruptedException {
LOG.info("Waiting for new LE cycle..");
int count = 100; // giving a grace period of 10seconds
while (count > 0) {
@@ -163,15 +154,13 @@ public class NonRecoverableErrorTest extends QuorumPeerTestBase {
}
count--;
}
- Assert.assertNotEquals("New LE cycle must have triggered",
- leaderCurrentEpoch, peer.getCurrentEpoch());
+ assertNotEquals("New LE cycle must have triggered", leaderCurrentEpoch, peer.getCurrentEpoch());
}
private QuorumPeer getLeaderQuorumPeer(MainThread[] mt) {
for (int i = mt.length - 1; i >= 0; i--) {
QuorumPeer quorumPeer = mt[i].getQuorumPeer();
- if (null != quorumPeer
- && ServerState.LEADING == quorumPeer.getPeerState()) {
+ if (null != quorumPeer && ServerState.LEADING == quorumPeer.getPeerState()) {
return quorumPeer;
}
}
@@ -183,4 +172,5 @@ public class NonRecoverableErrorTest extends QuorumPeerTestBase {
String node = NODE_PATH + "/" + randomUUID.toString();
return node;
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/NullDataTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/NullDataTest.java
index 8f1a1bb0f..9356ee47d 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/NullDataTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/NullDataTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,23 +18,23 @@
package org.apache.zookeeper.test;
+import static org.junit.Assert.assertSame;
import java.io.IOException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
-
+import org.apache.zookeeper.AsyncCallback.StatCallback;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
-import org.apache.zookeeper.ZooKeeper;
-import org.apache.zookeeper.AsyncCallback.StatCallback;
import org.apache.zookeeper.ZooDefs.Ids;
+import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;
-import org.junit.Assert;
import org.junit.Test;
public class NullDataTest extends ClientBase implements StatCallback {
+
String snapCount;
CountDownLatch cn = new CountDownLatch(1);
-
+
@Override
public void setUp() throws Exception {
// Change the snapcount to happen more often
@@ -42,34 +42,35 @@ public class NullDataTest extends ClientBase implements StatCallback {
System.setProperty("zookeeper.snapCount", "10");
super.setUp();
}
-
+
@Override
public void tearDown() throws Exception {
System.setProperty("zookeeper.snapCount", snapCount);
super.tearDown();
}
-
+
@Test
- public void testNullData() throws IOException,
- InterruptedException, KeeperException {
+ public void testNullData() throws IOException, InterruptedException, KeeperException {
String path = "/SIZE";
ZooKeeper zk = null;
zk = createClient();
try {
zk.create(path, null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
- // try sync zk exists
+ // try sync zk exists
zk.exists(path, false);
- zk.exists(path, false, this , null);
+ zk.exists(path, false, this, null);
cn.await(10, TimeUnit.SECONDS);
- Assert.assertSame(0L, cn.getCount());
+ assertSame(0L, cn.getCount());
} finally {
- if(zk != null)
+ if (zk != null) {
zk.close();
+ }
}
-
+
}
public void processResult(int rc, String path, Object ctx, Stat stat) {
cn.countDown();
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/OOMTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/OOMTest.java
index e8e76839b..ed56e9b02 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/OOMTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/OOMTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -19,32 +19,32 @@
package org.apache.zookeeper.test;
import static org.apache.zookeeper.test.ClientBase.CONNECTION_TIMEOUT;
-
+import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
-
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.PortAssignment;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZKTestCase;
-import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.ZooDefs.Ids;
+import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;
import org.apache.zookeeper.server.ServerCnxnFactory;
import org.apache.zookeeper.server.ZooKeeperServer;
-import org.junit.Assert;
import org.junit.Test;
public class OOMTest extends ZKTestCase implements Watcher {
+
@Test
public void testOOM() throws IOException, InterruptedException, KeeperException {
// This test takes too long tos run!
- if (true)
+ if (true) {
return;
+ }
File tmpDir = ClientBase.createTmpDir();
// Grab some memory so that it is easier to cause an
// OOM condition;
@@ -63,75 +63,76 @@ public class OOMTest extends ZKTestCase implements Watcher {
final int PORT = PortAssignment.unique();
ServerCnxnFactory f = ServerCnxnFactory.createFactory(PORT, -1);
f.startup(zks);
- Assert.assertTrue("waiting for server up",
- ClientBase.waitForServerUp("127.0.0.1:" + PORT,
- CONNECTION_TIMEOUT));
+ assertTrue("waiting for server up", ClientBase.waitForServerUp("127.0.0.1:" + PORT, CONNECTION_TIMEOUT));
System.err.println("OOM Stage 0");
utestPrep(PORT);
- System.out.println("Free = " + Runtime.getRuntime().freeMemory()
- + " total = " + Runtime.getRuntime().totalMemory() + " max = "
- + Runtime.getRuntime().maxMemory());
+ System.out.println("Free = "
+ + Runtime.getRuntime().freeMemory()
+ + " total = "
+ + Runtime.getRuntime().totalMemory()
+ + " max = "
+ + Runtime.getRuntime().maxMemory());
System.err.println("OOM Stage 1");
for (int i = 0; i < 1000; i++) {
System.out.println(i);
utestExists(PORT);
}
- System.out.println("Free = " + Runtime.getRuntime().freeMemory()
- + " total = " + Runtime.getRuntime().totalMemory() + " max = "
- + Runtime.getRuntime().maxMemory());
+ System.out.println("Free = "
+ + Runtime.getRuntime().freeMemory()
+ + " total = "
+ + Runtime.getRuntime().totalMemory()
+ + " max = "
+ + Runtime.getRuntime().maxMemory());
System.err.println("OOM Stage 2");
for (int i = 0; i < 1000; i++) {
System.out.println(i);
utestGet(PORT);
}
- System.out.println("Free = " + Runtime.getRuntime().freeMemory()
- + " total = " + Runtime.getRuntime().totalMemory() + " max = "
- + Runtime.getRuntime().maxMemory());
+ System.out.println("Free = "
+ + Runtime.getRuntime().freeMemory()
+ + " total = "
+ + Runtime.getRuntime().totalMemory()
+ + " max = "
+ + Runtime.getRuntime().maxMemory());
System.err.println("OOM Stage 3");
for (int i = 0; i < 1000; i++) {
System.out.println(i);
utestChildren(PORT);
}
- System.out.println("Free = " + Runtime.getRuntime().freeMemory()
- + " total = " + Runtime.getRuntime().totalMemory() + " max = "
- + Runtime.getRuntime().maxMemory());
+ System.out.println("Free = "
+ + Runtime.getRuntime().freeMemory()
+ + " total = "
+ + Runtime.getRuntime().totalMemory()
+ + " max = "
+ + Runtime.getRuntime().maxMemory());
hog.get(0)[0] = (byte) 1;
f.shutdown();
zks.shutdown();
- Assert.assertTrue("waiting for server down",
- ClientBase.waitForServerDown("127.0.0.1:" + PORT,
- CONNECTION_TIMEOUT));
+ assertTrue(
+ "waiting for server down",
+ ClientBase.waitForServerDown("127.0.0.1:" + PORT, CONNECTION_TIMEOUT));
}
- private void utestExists(int port)
- throws IOException, InterruptedException, KeeperException
- {
- ZooKeeper zk =
- new ZooKeeper("127.0.0.1:" + port, CONNECTION_TIMEOUT, this);
+ private void utestExists(int port) throws IOException, InterruptedException, KeeperException {
+ ZooKeeper zk = new ZooKeeper("127.0.0.1:" + port, CONNECTION_TIMEOUT, this);
for (int i = 0; i < 10000; i++) {
zk.exists("/this/path/doesnt_exist!", true);
}
zk.close();
}
- private void utestPrep(int port)
- throws IOException, InterruptedException, KeeperException
- {
- ZooKeeper zk =
- new ZooKeeper("127.0.0.1:" + port, CONNECTION_TIMEOUT, this);
+ private void utestPrep(int port) throws IOException, InterruptedException, KeeperException {
+ ZooKeeper zk = new ZooKeeper("127.0.0.1:" + port, CONNECTION_TIMEOUT, this);
for (int i = 0; i < 10000; i++) {
zk.create("/" + i, null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
}
zk.close();
}
- private void utestGet(int port)
- throws IOException, InterruptedException, KeeperException
- {
- ZooKeeper zk =
- new ZooKeeper("127.0.0.1:" + port, CONNECTION_TIMEOUT, this);
+ private void utestGet(int port) throws IOException, InterruptedException, KeeperException {
+ ZooKeeper zk = new ZooKeeper("127.0.0.1:" + port, CONNECTION_TIMEOUT, this);
for (int i = 0; i < 10000; i++) {
Stat stat = new Stat();
zk.getData("/" + i, true, stat);
@@ -139,11 +140,8 @@ public class OOMTest extends ZKTestCase implements Watcher {
zk.close();
}
- private void utestChildren(int port)
- throws IOException, InterruptedException, KeeperException
- {
- ZooKeeper zk =
- new ZooKeeper("127.0.0.1:" + port, CONNECTION_TIMEOUT, this);
+ private void utestChildren(int port) throws IOException, InterruptedException, KeeperException {
+ ZooKeeper zk = new ZooKeeper("127.0.0.1:" + port, CONNECTION_TIMEOUT, this);
for (int i = 0; i < 10000; i++) {
zk.getChildren("/" + i, true);
}
@@ -156,7 +154,7 @@ public class OOMTest extends ZKTestCase implements Watcher {
* @see org.apache.zookeeper.Watcher#process(org.apache.zookeeper.proto.WatcherEvent)
*/
public void process(WatchedEvent event) {
- System.err.println("Got event " + event.getType() + " "
- + event.getState() + " " + event.getPath());
+ System.err.println("Got event " + event.getType() + " " + event.getState() + " " + event.getPath());
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/OSMXBeanTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/OSMXBeanTest.java
index 371c9021d..21b02c5c8 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/OSMXBeanTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/OSMXBeanTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,17 +18,17 @@
package org.apache.zookeeper.test;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
import org.apache.zookeeper.ZKTestCase;
-import org.junit.Assert;
-import org.junit.Test;
+import org.apache.zookeeper.server.util.OSMXBean;
import org.junit.Before;
+import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import org.apache.zookeeper.server.util.OSMXBean;
-
public class OSMXBeanTest extends ZKTestCase {
-
+
private OSMXBean osMbean;
private Long ofdc = 0L;
private Long mfdc = 0L;
@@ -37,35 +37,35 @@ public class OSMXBeanTest extends ZKTestCase {
@Before
public void initialize() {
this.osMbean = new OSMXBean();
- Assert.assertNotNull("Could not initialize OSMXBean object!", osMbean);
+ assertNotNull("Could not initialize OSMXBean object!", osMbean);
}
-
+
@Test
public final void testGetUnix() {
boolean isUnix = osMbean.getUnix();
if (!isUnix) {
- LOG.info("Running in a Windows system! Output won't be printed!");
+ LOG.info("Running in a Windows system! Output won't be printed!");
} else {
- LOG.info("Running in a Unix or Linux system!");
+ LOG.info("Running in a Unix or Linux system!");
}
}
@Test
public final void testGetOpenFileDescriptorCount() {
- if (osMbean != null && osMbean.getUnix() == true) {
+ if (osMbean != null && osMbean.getUnix()) {
ofdc = osMbean.getOpenFileDescriptorCount();
LOG.info("open fdcount is: " + ofdc);
- }
- Assert.assertFalse("The number of open file descriptor is negative",(ofdc < 0));
+ }
+ assertFalse("The number of open file descriptor is negative", (ofdc < 0));
}
@Test
public final void testGetMaxFileDescriptorCount() {
- if (osMbean != null && osMbean.getUnix() == true) {
+ if (osMbean != null && osMbean.getUnix()) {
mfdc = osMbean.getMaxFileDescriptorCount();
LOG.info("max fdcount is: " + mfdc);
}
- Assert.assertFalse("The max file descriptor number is negative",(mfdc < 0));
+ assertFalse("The max file descriptor number is negative", (mfdc < 0));
}
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/ObserverHierarchicalQuorumTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/ObserverHierarchicalQuorumTest.java
index acd7d8608..fd1609118 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/ObserverHierarchicalQuorumTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/ObserverHierarchicalQuorumTest.java
@@ -21,13 +21,14 @@ import org.apache.zookeeper.server.quorum.QuorumPeer;
import org.junit.Test;
public class ObserverHierarchicalQuorumTest extends HierarchicalQuorumTest {
+
/**
* startServers(true) puts two observers into a 5 peer ensemble
*/
void startServers() throws Exception {
startServers(true);
}
-
+
protected void shutdown(QuorumPeer qp) {
QuorumBase.shutdown(qp);
}
@@ -36,4 +37,5 @@ public class ObserverHierarchicalQuorumTest extends HierarchicalQuorumTest {
public void testHierarchicalQuorum() throws Throwable {
cht.runHammer(5, 10);
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/ObserverLETest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/ObserverLETest.java
index 123ba0be0..273b05e53 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/ObserverLETest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/ObserverLETest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -15,12 +15,12 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package org.apache.zookeeper.test;
-import static org.junit.Assert.*;
+package org.apache.zookeeper.test;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
import java.util.Arrays;
-
import org.apache.zookeeper.ZKTestCase;
import org.apache.zookeeper.server.quorum.QuorumPeer;
import org.apache.zookeeper.server.quorum.QuorumStats;
@@ -29,6 +29,7 @@ import org.junit.Before;
import org.junit.Test;
public class ObserverLETest extends ZKTestCase {
+
final QuorumBase qb = new QuorumBase();
final ClientTest ct = new ClientTest();
@@ -56,21 +57,19 @@ public class ObserverLETest extends ZKTestCase {
public void testLEWithObserver() throws Exception {
QuorumPeer leader = null;
for (QuorumPeer server : Arrays.asList(qb.s1, qb.s2, qb.s3)) {
- if (server.getServerState().equals(
- QuorumStats.Provider.FOLLOWING_STATE)) {
+ if (server.getServerState().equals(QuorumStats.Provider.FOLLOWING_STATE)) {
server.shutdown();
- assertTrue("Waiting for server down", ClientBase
- .waitForServerDown("127.0.0.1:"
- + server.getClientPort(),
- ClientBase.CONNECTION_TIMEOUT));
+ assertTrue(
+ "Waiting for server down",
+ ClientBase.waitForServerDown("127.0.0.1:" + server.getClientPort(), ClientBase.CONNECTION_TIMEOUT));
} else {
assertNull("More than one leader found", leader);
leader = server;
}
}
- assertTrue("Leader is not in Looking state", ClientBase
- .waitForServerState(leader, ClientBase.CONNECTION_TIMEOUT,
- QuorumStats.Provider.LOOKING_STATE));
+ assertTrue(
+ "Leader is not in Looking state",
+ ClientBase.waitForServerState(leader, ClientBase.CONNECTION_TIMEOUT, QuorumStats.Provider.LOOKING_STATE));
}
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/ObserverMasterTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/ObserverMasterTest.java
index f72063418..1bcf5835e 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/ObserverMasterTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/ObserverMasterTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -19,7 +19,13 @@
package org.apache.zookeeper.test;
import static org.apache.zookeeper.test.ClientBase.CONNECTION_TIMEOUT;
-
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNotSame;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
@@ -30,9 +36,27 @@ import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
-
+import javax.management.Attribute;
+import javax.management.AttributeNotFoundException;
+import javax.management.InstanceNotFoundException;
+import javax.management.InvalidAttributeValueException;
+import javax.management.MBeanException;
+import javax.management.MalformedObjectNameException;
+import javax.management.ObjectName;
+import javax.management.ReflectionException;
+import javax.management.RuntimeMBeanException;
import org.apache.zookeeper.AsyncCallback;
+import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
+import org.apache.zookeeper.KeeperException.ConnectionLossException;
+import org.apache.zookeeper.PortAssignment;
+import org.apache.zookeeper.WatchedEvent;
+import org.apache.zookeeper.Watcher;
+import org.apache.zookeeper.Watcher.Event.KeeperState;
+import org.apache.zookeeper.ZooDefs.Ids;
+import org.apache.zookeeper.ZooKeeper;
+import org.apache.zookeeper.ZooKeeper.States;
+import org.apache.zookeeper.admin.ZooKeeperAdmin;
import org.apache.zookeeper.jmx.MBeanRegistry;
import org.apache.zookeeper.jmx.ZKMBeanInfo;
import org.apache.zookeeper.server.admin.Commands;
@@ -41,35 +65,15 @@ import org.apache.zookeeper.server.quorum.FollowerZooKeeperServer;
import org.apache.zookeeper.server.quorum.QuorumPeerConfig;
import org.apache.zookeeper.server.quorum.QuorumPeerTestBase;
import org.apache.zookeeper.server.util.PortForwarder;
+import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import org.apache.zookeeper.CreateMode;
-import org.apache.zookeeper.KeeperException.ConnectionLossException;
-import org.apache.zookeeper.PortAssignment;
-import org.apache.zookeeper.WatchedEvent;
-import org.apache.zookeeper.Watcher;
-import org.apache.zookeeper.Watcher.Event.KeeperState;
-import org.apache.zookeeper.ZooDefs.Ids;
-import org.apache.zookeeper.ZooKeeper;
-import org.apache.zookeeper.ZooKeeper.States;
-import org.apache.zookeeper.admin.ZooKeeperAdmin;
-import org.junit.Assert;
-import org.junit.Test;
-
-import javax.management.Attribute;
-import javax.management.AttributeNotFoundException;
-import javax.management.InstanceNotFoundException;
-import javax.management.InvalidAttributeValueException;
-import javax.management.MBeanException;
-import javax.management.MalformedObjectNameException;
-import javax.management.ObjectName;
-import javax.management.ReflectionException;
-import javax.management.RuntimeMBeanException;
@RunWith(Parameterized.class)
-public class ObserverMasterTest extends QuorumPeerTestBase implements Watcher{
+public class ObserverMasterTest extends QuorumPeerTestBase implements Watcher {
+
protected static final Logger LOG = LoggerFactory.getLogger(ObserverMasterTest.class);
public ObserverMasterTest(Boolean testObserverMaster) {
@@ -77,9 +81,8 @@ public class ObserverMasterTest extends QuorumPeerTestBase implements Watcher{
}
@Parameterized.Parameters
- public static List<Object []> data() { return Arrays.asList(new Object [][] {
- {Boolean.TRUE},
- {Boolean.FALSE}});
+ public static List<Object[]> data() {
+ return Arrays.asList(new Object[][]{{Boolean.TRUE}, {Boolean.FALSE}});
}
private Boolean testObserverMaster;
@@ -112,15 +115,15 @@ public class ObserverMasterTest extends QuorumPeerTestBase implements Watcher{
OM_PORT = PortAssignment.unique();
- String quorumCfgSection =
- "server.1=127.0.0.1:" + (PORT_QP1)
- + ":" + (PORT_QP_LE1) + ";" + CLIENT_PORT_QP1
- + "\nserver.2=127.0.0.1:" + (PORT_QP2)
- + ":" + (PORT_QP_LE2) + ";" + CLIENT_PORT_QP2
- + "\nserver.3=127.0.0.1:"
- + (PORT_OBS)+ ":" + (PORT_OBS_LE) + ":observer" + ";" + CLIENT_PORT_OBS;
- String extraCfgs = testObserverMaster ? String.format("observerMasterPort=%d%n", OM_PORT) : "";
- String extraCfgsObs = testObserverMaster ? String.format("observerMasterPort=%d%n", omProxyPort <= 0 ? OM_PORT : omProxyPort) : "";
+ String quorumCfgSection = "server.1=127.0.0.1:" + (PORT_QP1) + ":" + (PORT_QP_LE1) + ";" + CLIENT_PORT_QP1
+ + "\nserver.2=127.0.0.1:" + (PORT_QP2) + ":" + (PORT_QP_LE2) + ";" + CLIENT_PORT_QP2
+ + "\nserver.3=127.0.0.1:" + (PORT_OBS) + ":" + (PORT_OBS_LE) + ":observer" + ";" + CLIENT_PORT_OBS;
+ String extraCfgs = testObserverMaster
+ ? String.format("observerMasterPort=%d%n", OM_PORT)
+ : "";
+ String extraCfgsObs = testObserverMaster
+ ? String.format("observerMasterPort=%d%n", omProxyPort <= 0 ? OM_PORT : omProxyPort)
+ : "";
PortForwarder forwarder = null;
if (testObserverMaster && omProxyPort >= 0) {
@@ -132,12 +135,12 @@ public class ObserverMasterTest extends QuorumPeerTestBase implements Watcher{
q3 = new MainThread(3, CLIENT_PORT_OBS, quorumCfgSection, extraCfgsObs);
q1.start();
q2.start();
- Assert.assertTrue("waiting for server 1 being up",
- ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT_QP1,
- CONNECTION_TIMEOUT));
- Assert.assertTrue("waiting for server 2 being up",
- ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT_QP2,
- CONNECTION_TIMEOUT));
+ assertTrue(
+ "waiting for server 1 being up",
+ ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT_QP1, CONNECTION_TIMEOUT));
+ assertTrue(
+ "waiting for server 2 being up",
+ ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT_QP2, CONNECTION_TIMEOUT));
return forwarder;
}
@@ -149,15 +152,15 @@ public class ObserverMasterTest extends QuorumPeerTestBase implements Watcher{
q2.shutdown();
q3.shutdown();
- Assert.assertTrue("Waiting for server 1 to shut down",
- ClientBase.waitForServerDown("127.0.0.1:"+CLIENT_PORT_QP1,
- ClientBase.CONNECTION_TIMEOUT));
- Assert.assertTrue("Waiting for server 2 to shut down",
- ClientBase.waitForServerDown("127.0.0.1:"+CLIENT_PORT_QP2,
- ClientBase.CONNECTION_TIMEOUT));
- Assert.assertTrue("Waiting for server 3 to shut down",
- ClientBase.waitForServerDown("127.0.0.1:"+CLIENT_PORT_OBS,
- ClientBase.CONNECTION_TIMEOUT));
+ assertTrue(
+ "Waiting for server 1 to shut down",
+ ClientBase.waitForServerDown("127.0.0.1:" + CLIENT_PORT_QP1, ClientBase.CONNECTION_TIMEOUT));
+ assertTrue(
+ "Waiting for server 2 to shut down",
+ ClientBase.waitForServerDown("127.0.0.1:" + CLIENT_PORT_QP2, ClientBase.CONNECTION_TIMEOUT));
+ assertTrue(
+ "Waiting for server 3 to shut down",
+ ClientBase.waitForServerDown("127.0.0.1:" + CLIENT_PORT_OBS, ClientBase.CONNECTION_TIMEOUT));
}
@Test
@@ -182,23 +185,21 @@ public class ObserverMasterTest extends QuorumPeerTestBase implements Watcher{
}
// ensure the observer master has commits in the queue before observer sync
- zk = new ZooKeeper("127.0.0.1:" + leaderPort,
- ClientBase.CONNECTION_TIMEOUT, this);
+ zk = new ZooKeeper("127.0.0.1:" + leaderPort, ClientBase.CONNECTION_TIMEOUT, this);
for (int i = 0; i < 10; i++) {
zk.create("/bulk" + i, ("initial data of some size").getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
}
zk.close();
q3.start();
- Assert.assertTrue("waiting for server 3 being up",
- ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT_OBS,
- CONNECTION_TIMEOUT));
+ assertTrue(
+ "waiting for server 3 being up",
+ ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT_OBS, CONNECTION_TIMEOUT));
latch = new CountDownLatch(1);
- zk = new ZooKeeper("127.0.0.1:" + leaderPort,
- ClientBase.CONNECTION_TIMEOUT, this);
+ zk = new ZooKeeper("127.0.0.1:" + leaderPort, ClientBase.CONNECTION_TIMEOUT, this);
latch.await();
- Assert.assertEquals(zk.getState(), States.CONNECTED);
+ assertEquals(zk.getState(), States.CONNECTED);
zk.create("/init", "first".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
final long lastLoggedZxid = leader.getQuorumPeer().getLastLoggedZxid();
@@ -216,8 +217,7 @@ public class ObserverMasterTest extends QuorumPeerTestBase implements Watcher{
}
for (int i = 0; i < 10; i++) {
- zk.create("/basic" + i, "second".getBytes(),Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk.create("/basic" + i, "second".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
}
DelayRequestProcessor delayRequestProcessor = null;
@@ -226,37 +226,34 @@ public class ObserverMasterTest extends QuorumPeerTestBase implements Watcher{
delayRequestProcessor = DelayRequestProcessor.injectDelayRequestProcessor(followerZooKeeperServer);
}
- zk.create("/target1", "third".getBytes(),Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
- zk.create("/target2", "third".getBytes(),Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk.create("/target1", "third".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
+ zk.create("/target2", "third".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
- LOG.info("observer zxid " + Long.toHexString(q3.getQuorumPeer().getLastLoggedZxid()) +
- (testObserverMaster ? "" : " observer master zxid " +
- Long.toHexString(follower.getQuorumPeer().getLastLoggedZxid())) +
- " leader zxid " + Long.toHexString(leader.getQuorumPeer().getLastLoggedZxid()));
+ LOG.info("observer zxid "
+ + Long.toHexString(q3.getQuorumPeer().getLastLoggedZxid())
+ + (testObserverMaster ? "" : " observer master zxid " + Long.toHexString(follower.getQuorumPeer().getLastLoggedZxid()))
+ + " leader zxid "
+ + Long.toHexString(leader.getQuorumPeer().getLastLoggedZxid()));
// restore network
forwarder = testObserverMaster ? new PortForwarder(OM_PROXY_PORT, OM_PORT) : null;
- Assert.assertTrue("waiting for server 3 being up",
- ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT_OBS,
- CONNECTION_TIMEOUT));
- Assert.assertNotNull("Leader switched", leader.getQuorumPeer().leader);
+ assertTrue(
+ "waiting for server 3 being up",
+ ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT_OBS, CONNECTION_TIMEOUT));
+ assertNotNull("Leader switched", leader.getQuorumPeer().leader);
if (delayRequestProcessor != null) {
delayRequestProcessor.unblockQueue();
}
latch = new CountDownLatch(1);
- ZooKeeper obsZk = new ZooKeeper("127.0.0.1:" + CLIENT_PORT_OBS,
- ClientBase.CONNECTION_TIMEOUT, this);
+ ZooKeeper obsZk = new ZooKeeper("127.0.0.1:" + CLIENT_PORT_OBS, ClientBase.CONNECTION_TIMEOUT, this);
latch.await();
- zk.create("/finalop", "fourth".getBytes(),Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk.create("/finalop", "fourth".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
- Assert.assertEquals("first", new String(obsZk.getData("/init", null, null)));
- Assert.assertEquals("third", new String(obsZk.getData("/target1", null, null)));
+ assertEquals("first", new String(obsZk.getData("/init", null, null)));
+ assertEquals("third", new String(obsZk.getData("/target1", null, null)));
obsZk.close();
shutdown();
@@ -283,53 +280,48 @@ public class ObserverMasterTest extends QuorumPeerTestBase implements Watcher{
latch = new CountDownLatch(2);
setUp(-1);
q3.start();
- Assert.assertTrue("waiting for server 3 being up",
- ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT_OBS,
- CONNECTION_TIMEOUT));
+ assertTrue(
+ "waiting for server 3 being up",
+ ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT_OBS, CONNECTION_TIMEOUT));
if (testObserverMaster) {
int masterPort = q3.getQuorumPeer().observer.getSocket().getPort();
LOG.info("port " + masterPort + " " + OM_PORT);
- Assert.assertEquals("observer failed to connect to observer master", masterPort, OM_PORT);
+ assertEquals("observer failed to connect to observer master", masterPort, OM_PORT);
}
- zk = new ZooKeeper("127.0.0.1:" + CLIENT_PORT_OBS,
- ClientBase.CONNECTION_TIMEOUT, this);
- zk.create("/obstest", "test".getBytes(),Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk = new ZooKeeper("127.0.0.1:" + CLIENT_PORT_OBS, ClientBase.CONNECTION_TIMEOUT, this);
+ zk.create("/obstest", "test".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
// Assert that commands are getting forwarded correctly
- Assert.assertEquals(new String(zk.getData("/obstest", null, null)), "test");
+ assertEquals(new String(zk.getData("/obstest", null, null)), "test");
// Now check that other commands don't blow everything up
zk.sync("/", null, null);
zk.setData("/obstest", "test2".getBytes(), -1);
zk.getChildren("/", false);
- Assert.assertEquals(zk.getState(), States.CONNECTED);
+ assertEquals(zk.getState(), States.CONNECTED);
LOG.info("Shutting down server 2");
// Now kill one of the other real servers
q2.shutdown();
- Assert.assertTrue("Waiting for server 2 to shut down",
- ClientBase.waitForServerDown("127.0.0.1:"+CLIENT_PORT_QP2,
- ClientBase.CONNECTION_TIMEOUT));
+ assertTrue(
+ "Waiting for server 2 to shut down",
+ ClientBase.waitForServerDown("127.0.0.1:" + CLIENT_PORT_QP2, ClientBase.CONNECTION_TIMEOUT));
LOG.info("Server 2 down");
// Now the resulting ensemble shouldn't be quorate
latch.await();
- Assert.assertNotSame("Client is still connected to non-quorate cluster",
- KeeperState.SyncConnected,lastEvent.getState());
+ assertNotSame("Client is still connected to non-quorate cluster", KeeperState.SyncConnected, lastEvent.getState());
LOG.info("Latch returned");
try {
- Assert.assertNotEquals("Shouldn't get a response when cluster not quorate!",
- "test", new String(zk.getData("/obstest", null, null)));
- }
- catch (ConnectionLossException c) {
+ assertNotEquals("Shouldn't get a response when cluster not quorate!", "test", new String(zk.getData("/obstest", null, null)));
+ } catch (ConnectionLossException c) {
LOG.info("Connection loss exception caught - ensemble not quorate (this is expected)");
}
@@ -342,19 +334,19 @@ public class ObserverMasterTest extends QuorumPeerTestBase implements Watcher{
q2.start();
LOG.info("Waiting for server 2 to come up");
- Assert.assertTrue("waiting for server 2 being up",
- ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT_QP2,
- CONNECTION_TIMEOUT));
+ assertTrue(
+ "waiting for server 2 being up",
+ ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT_QP2, CONNECTION_TIMEOUT));
LOG.info("Server 2 started, waiting for latch");
latch.await();
// It's possible our session expired - but this is ok, shows we
// were able to talk to the ensemble
- Assert.assertTrue("Client didn't reconnect to quorate ensemble (state was" +
- lastEvent.getState() + ")",
- (KeeperState.SyncConnected==lastEvent.getState() ||
- KeeperState.Expired==lastEvent.getState()));
+ assertTrue("Client didn't reconnect to quorate ensemble (state was"
+ + lastEvent.getState()
+ + ")", (KeeperState.SyncConnected == lastEvent.getState()
+ || KeeperState.Expired == lastEvent.getState()));
LOG.info("perform a revalidation test");
int leaderProxyPort = PortAssignment.unique();
@@ -363,12 +355,10 @@ public class ObserverMasterTest extends QuorumPeerTestBase implements Watcher{
PortForwarder leaderPF = new PortForwarder(leaderProxyPort, leaderPort);
latch = new CountDownLatch(1);
- ZooKeeper client = new ZooKeeper(String.format("127.0.0.1:%d,127.0.0.1:%d", leaderProxyPort, obsProxyPort),
- ClientBase.CONNECTION_TIMEOUT, this);
+ ZooKeeper client = new ZooKeeper(String.format("127.0.0.1:%d,127.0.0.1:%d", leaderProxyPort, obsProxyPort), ClientBase.CONNECTION_TIMEOUT, this);
latch.await();
- client.create("/revalidtest", "test".getBytes(),Ids.OPEN_ACL_UNSAFE,
- CreateMode.EPHEMERAL);
- Assert.assertNotNull("Read-after write failed", client.exists("/revalidtest", null));
+ client.create("/revalidtest", "test".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
+ assertNotNull("Read-after write failed", client.exists("/revalidtest", null));
latch = new CountDownLatch(2);
PortForwarder obsPF = new PortForwarder(obsProxyPort, CLIENT_PORT_OBS);
@@ -378,7 +368,7 @@ public class ObserverMasterTest extends QuorumPeerTestBase implements Watcher{
// ignore?
}
latch.await();
- Assert.assertEquals(new String(client.getData("/revalidtest", null, null)), "test");
+ assertEquals(new String(client.getData("/revalidtest", null, null)), "test");
client.close();
obsPF.shutdown();
@@ -389,9 +379,9 @@ public class ObserverMasterTest extends QuorumPeerTestBase implements Watcher{
public void testRevalidation() throws Exception {
setUp(-1);
q3.start();
- Assert.assertTrue("waiting for server 3 being up",
- ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT_OBS,
- CONNECTION_TIMEOUT));
+ assertTrue(
+ "waiting for server 3 being up",
+ ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT_OBS, CONNECTION_TIMEOUT));
final int leaderProxyPort = PortAssignment.unique();
final int obsProxyPort = PortAssignment.unique();
@@ -399,12 +389,10 @@ public class ObserverMasterTest extends QuorumPeerTestBase implements Watcher{
PortForwarder leaderPF = new PortForwarder(leaderProxyPort, leaderPort);
latch = new CountDownLatch(1);
- zk = new ZooKeeper(String.format("127.0.0.1:%d,127.0.0.1:%d", leaderProxyPort, obsProxyPort),
- ClientBase.CONNECTION_TIMEOUT, this);
+ zk = new ZooKeeper(String.format("127.0.0.1:%d,127.0.0.1:%d", leaderProxyPort, obsProxyPort), ClientBase.CONNECTION_TIMEOUT, this);
latch.await();
- zk.create("/revalidtest", "test".getBytes(),Ids.OPEN_ACL_UNSAFE,
- CreateMode.EPHEMERAL);
- Assert.assertNotNull("Read-after write failed", zk.exists("/revalidtest", null));
+ zk.create("/revalidtest", "test".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
+ assertNotNull("Read-after write failed", zk.exists("/revalidtest", null));
latch = new CountDownLatch(2);
PortForwarder obsPF = new PortForwarder(obsProxyPort, CLIENT_PORT_OBS);
@@ -414,7 +402,7 @@ public class ObserverMasterTest extends QuorumPeerTestBase implements Watcher{
// ignore?
}
latch.await();
- Assert.assertEquals(new String(zk.getData("/revalidtest", null, null)), "test");
+ assertEquals(new String(zk.getData("/revalidtest", null, null)), "test");
obsPF.shutdown();
shutdown();
@@ -424,23 +412,22 @@ public class ObserverMasterTest extends QuorumPeerTestBase implements Watcher{
public void testInOrderCommits() throws Exception {
setUp(-1);
- zk = new ZooKeeper("127.0.0.1:" + CLIENT_PORT_QP1,
- ClientBase.CONNECTION_TIMEOUT, null);
+ zk = new ZooKeeper("127.0.0.1:" + CLIENT_PORT_QP1, ClientBase.CONNECTION_TIMEOUT, null);
for (int i = 0; i < 10; i++) {
- zk.create("/bulk" + i, ("Initial data of some size").getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
+ zk.create("/bulk"
+ + i, ("Initial data of some size").getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
}
zk.close();
q3.start();
- Assert.assertTrue("waiting for observer to be up",
- ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT_OBS,
- CONNECTION_TIMEOUT));
+ assertTrue(
+ "waiting for observer to be up",
+ ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT_OBS, CONNECTION_TIMEOUT));
latch = new CountDownLatch(1);
- zk = new ZooKeeper("127.0.0.1:" + CLIENT_PORT_QP1,
- ClientBase.CONNECTION_TIMEOUT, this);
+ zk = new ZooKeeper("127.0.0.1:" + CLIENT_PORT_QP1, ClientBase.CONNECTION_TIMEOUT, this);
latch.await();
- Assert.assertEquals(zk.getState(), States.CONNECTED);
+ assertEquals(zk.getState(), States.CONNECTED);
zk.create("/init", "first".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
final long zxid = q1.getQuorumPeer().getLastLoggedZxid();
@@ -452,11 +439,9 @@ public class ObserverMasterTest extends QuorumPeerTestBase implements Watcher{
}
}, 30);
- ZooKeeper obsZk = new ZooKeeper("127.0.0.1:" + CLIENT_PORT_OBS,
- ClientBase.CONNECTION_TIMEOUT, this);
+ ZooKeeper obsZk = new ZooKeeper("127.0.0.1:" + CLIENT_PORT_OBS, ClientBase.CONNECTION_TIMEOUT, this);
int followerPort = q1.getQuorumPeer().leader == null ? CLIENT_PORT_QP1 : CLIENT_PORT_QP2;
- ZooKeeper fZk = new ZooKeeper("127.0.0.1:" + followerPort,
- ClientBase.CONNECTION_TIMEOUT, this);
+ ZooKeeper fZk = new ZooKeeper("127.0.0.1:" + followerPort, ClientBase.CONNECTION_TIMEOUT, this);
final int numTransactions = 10001;
CountDownLatch gate = new CountDownLatch(1);
CountDownLatch oAsyncLatch = new CountDownLatch(numTransactions);
@@ -488,9 +473,7 @@ public class ObserverMasterTest extends QuorumPeerTestBase implements Watcher{
}
@Test
- public void testAdminCommands() throws IOException, MBeanException,
- InstanceNotFoundException, ReflectionException, InterruptedException, MalformedObjectNameException,
- AttributeNotFoundException, InvalidAttributeValueException, KeeperException {
+ public void testAdminCommands() throws IOException, MBeanException, InstanceNotFoundException, ReflectionException, InterruptedException, MalformedObjectNameException, AttributeNotFoundException, InvalidAttributeValueException, KeeperException {
// flush all beans, then start
for (ZKMBeanInfo beanInfo : MBeanRegistry.getInstance().getRegisteredBeans()) {
MBeanRegistry.getInstance().unregister(beanInfo);
@@ -499,76 +482,72 @@ public class ObserverMasterTest extends QuorumPeerTestBase implements Watcher{
JMXEnv.setUp();
setUp(-1);
q3.start();
- Assert.assertTrue("waiting for observer to be up",
- ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT_OBS,
- CONNECTION_TIMEOUT));
+ assertTrue(
+ "waiting for observer to be up",
+ ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT_OBS, CONNECTION_TIMEOUT));
// Assert that commands are getting forwarded correctly
- zk = new ZooKeeper("127.0.0.1:" + CLIENT_PORT_OBS,
- ClientBase.CONNECTION_TIMEOUT, this);
- zk.create("/obstest", "test".getBytes(),Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
- Assert.assertEquals(new String(zk.getData("/obstest", null, null)), "test");
+ zk = new ZooKeeper("127.0.0.1:" + CLIENT_PORT_OBS, ClientBase.CONNECTION_TIMEOUT, this);
+ zk.create("/obstest", "test".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
+ assertEquals(new String(zk.getData("/obstest", null, null)), "test");
// test stats collection
final Map<String, String> emptyMap = Collections.emptyMap();
Map<String, Object> stats = Commands.runCommand("mntr", q3.getQuorumPeer().getActiveServer(), emptyMap).toMap();
- Assert.assertTrue("observer not emitting observer_master_id", stats.containsKey("observer_master_id"));
+ assertTrue("observer not emitting observer_master_id", stats.containsKey("observer_master_id"));
// check the stats for the first peer
if (testObserverMaster) {
if (q1.getQuorumPeer().leader == null) {
- Assert.assertEquals(Integer.valueOf(1), q1.getQuorumPeer().getSynced_observers_metric());
+ assertEquals(Integer.valueOf(1), q1.getQuorumPeer().getSynced_observers_metric());
} else {
- Assert.assertEquals(Integer.valueOf(0), q1.getQuorumPeer().getSynced_observers_metric());
+ assertEquals(Integer.valueOf(0), q1.getQuorumPeer().getSynced_observers_metric());
}
} else {
if (q1.getQuorumPeer().leader == null) {
- Assert.assertNull(q1.getQuorumPeer().getSynced_observers_metric());
+ assertNull(q1.getQuorumPeer().getSynced_observers_metric());
} else {
- Assert.assertEquals(Integer.valueOf(1), q1.getQuorumPeer().getSynced_observers_metric());
+ assertEquals(Integer.valueOf(1), q1.getQuorumPeer().getSynced_observers_metric());
}
}
// check the stats for the second peer
if (testObserverMaster) {
if (q2.getQuorumPeer().leader == null) {
- Assert.assertEquals(Integer.valueOf(1), q2.getQuorumPeer().getSynced_observers_metric());
+ assertEquals(Integer.valueOf(1), q2.getQuorumPeer().getSynced_observers_metric());
} else {
- Assert.assertEquals(Integer.valueOf(0), q2.getQuorumPeer().getSynced_observers_metric());
+ assertEquals(Integer.valueOf(0), q2.getQuorumPeer().getSynced_observers_metric());
}
} else {
if (q2.getQuorumPeer().leader == null) {
- Assert.assertNull(q2.getQuorumPeer().getSynced_observers_metric());
+ assertNull(q2.getQuorumPeer().getSynced_observers_metric());
} else {
- Assert.assertEquals(Integer.valueOf(1), q2.getQuorumPeer().getSynced_observers_metric());
+ assertEquals(Integer.valueOf(1), q2.getQuorumPeer().getSynced_observers_metric());
}
}
// test admin commands for disconnection
ObjectName connBean = null;
for (ObjectName bean : JMXEnv.conn().queryNames(new ObjectName(MBeanRegistry.DOMAIN + ":*"), null)) {
- if (bean.getCanonicalName().contains("Learner_Connections") &&
- bean.getCanonicalName().contains("id:" + q3.getQuorumPeer().getId())) {
+ if (bean.getCanonicalName().contains("Learner_Connections") && bean.getCanonicalName().contains("id:"
+ + q3.getQuorumPeer().getId())) {
connBean = bean;
break;
}
}
- Assert.assertNotNull("could not find connection bean", connBean);
+ assertNotNull("could not find connection bean", connBean);
latch = new CountDownLatch(1);
JMXEnv.conn().invoke(connBean, "terminateConnection", new Object[0], null);
- Assert.assertTrue("server failed to disconnect on terminate",
- latch.await(CONNECTION_TIMEOUT/2, TimeUnit.MILLISECONDS));
- Assert.assertTrue("waiting for server 3 being up",
- ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT_OBS,
- CONNECTION_TIMEOUT));
-
- final String obsBeanName =
- String.format("org.apache.ZooKeeperService:name0=ReplicatedServer_id%d,name1=replica.%d,name2=Observer",
- q3.getQuorumPeer().getId(), q3.getQuorumPeer().getId());
+ assertTrue("server failed to disconnect on terminate", latch.await(CONNECTION_TIMEOUT
+ / 2, TimeUnit.MILLISECONDS));
+ assertTrue(
+ "waiting for server 3 being up",
+ ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT_OBS, CONNECTION_TIMEOUT));
+
+ final String obsBeanName = String.format("org.apache.ZooKeeperService:name0=ReplicatedServer_id%d,name1=replica.%d,name2=Observer", q3.getQuorumPeer().getId(), q3.getQuorumPeer().getId());
Set<ObjectName> names = JMXEnv.conn().queryNames(new ObjectName(obsBeanName), null);
- Assert.assertEquals("expecting singular observer bean", 1, names.size());
+ assertEquals("expecting singular observer bean", 1, names.size());
ObjectName obsBean = names.iterator().next();
if (testObserverMaster) {
@@ -576,20 +555,18 @@ public class ObserverMasterTest extends QuorumPeerTestBase implements Watcher{
long observerMasterId = q3.getQuorumPeer().observer.getLearnerMasterId();
latch = new CountDownLatch(1);
JMXEnv.conn().setAttribute(obsBean, new Attribute("LearnerMaster", Long.toString(3 - observerMasterId)));
- Assert.assertTrue("server failed to disconnect on terminate",
- latch.await(CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS));
- Assert.assertTrue("waiting for server 3 being up",
- ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT_OBS,
- CONNECTION_TIMEOUT));
+ assertTrue("server failed to disconnect on terminate", latch.await(CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS));
+ assertTrue(
+ "waiting for server 3 being up",
+ ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT_OBS, CONNECTION_TIMEOUT));
} else {
// show we get an error
final long leaderId = q1.getQuorumPeer().leader == null ? 2 : 1;
try {
JMXEnv.conn().setAttribute(obsBean, new Attribute("LearnerMaster", Long.toString(3 - leaderId)));
- Assert.fail("should have seen an exception on previous command");
+ fail("should have seen an exception on previous command");
} catch (RuntimeMBeanException e) {
- Assert.assertEquals("mbean failed for the wrong reason",
- IllegalArgumentException.class, e.getCause().getClass());
+ assertEquals("mbean failed for the wrong reason", IllegalArgumentException.class, e.getCause().getClass());
}
}
@@ -598,26 +575,26 @@ public class ObserverMasterTest extends QuorumPeerTestBase implements Watcher{
}
private String createServerString(String type, long serverId, int clientPort) {
- return "server." + serverId + "=127.0.0.1:" +
- PortAssignment.unique() + ":" +
- PortAssignment.unique() + ":" +
- type + ";" + clientPort;
+ return "server." + serverId + "=127.0.0.1:" + PortAssignment.unique() + ":" + PortAssignment.unique() + ":" + type + ";" + clientPort;
}
private void waitServerUp(int clientPort) {
- Assert.assertTrue("waiting for server being up",
- ClientBase.waitForServerUp("127.0.0.1:" + clientPort,
- CONNECTION_TIMEOUT));
+ assertTrue(
+ "waiting for server being up",
+ ClientBase.waitForServerUp("127.0.0.1:" + clientPort, CONNECTION_TIMEOUT));
}
private ZooKeeperAdmin createAdmin(int clientPort) throws IOException {
- System.setProperty("zookeeper.DigestAuthenticationProvider.superDigest",
- "super:D/InIHSb7yEEbrWz8b9l71RjZJU="/* password is 'test'*/);
+ System.setProperty("zookeeper.DigestAuthenticationProvider.superDigest", "super:D/InIHSb7yEEbrWz8b9l71RjZJU="/* password is 'test'*/);
QuorumPeerConfig.setReconfigEnabled(true);
- ZooKeeperAdmin admin = new ZooKeeperAdmin("127.0.0.1:" + clientPort,
- ClientBase.CONNECTION_TIMEOUT, new Watcher() {
- public void process(WatchedEvent event) {}
- });
+ ZooKeeperAdmin admin = new ZooKeeperAdmin(
+ "127.0.0.1:" + clientPort,
+ ClientBase.CONNECTION_TIMEOUT,
+ new Watcher() {
+ public void process(WatchedEvent event) {
+
+ }
+ });
admin.addAuthInfo("digest", "super:test".getBytes());
return admin;
}
@@ -625,8 +602,7 @@ public class ObserverMasterTest extends QuorumPeerTestBase implements Watcher{
// This test is known to be flaky and fail due to "reconfig already in progress".
// TODO: Investigate intermittent testDynamicReconfig failures.
// @Test
- public void testDynamicReconfig() throws InterruptedException, IOException,
- KeeperException {
+ public void testDynamicReconfig() throws InterruptedException, IOException, KeeperException {
if (!testObserverMaster) {
return;
}
@@ -643,57 +619,53 @@ public class ObserverMasterTest extends QuorumPeerTestBase implements Watcher{
int clientPort2 = PortAssignment.unique();
int omPort1 = PortAssignment.unique();
int omPort2 = PortAssignment.unique();
- String quorumCfgSection =
- createServerString("participant", 1, clientPort1) + "\n" +
- createServerString("participant", 2, clientPort2);
-
- MainThread s1 = new MainThread(1, clientPort1, quorumCfgSection,
- String.format("observerMasterPort=%d%n",omPort1));
- MainThread s2 = new MainThread(2, clientPort2, quorumCfgSection,
- String.format("observerMasterPort=%d%n", omPort2));
+ String quorumCfgSection = createServerString("participant", 1, clientPort1)
+ + "\n"
+ + createServerString("participant", 2, clientPort2);
+
+ MainThread s1 = new MainThread(1, clientPort1, quorumCfgSection, String.format("observerMasterPort=%d%n", omPort1));
+ MainThread s2 = new MainThread(2, clientPort2, quorumCfgSection, String.format("observerMasterPort=%d%n", omPort2));
s1.start();
s2.start();
waitServerUp(clientPort1);
waitServerUp(clientPort2);
// create observer to follow non-leader observer master
- long nonLeaderOMPort = s1.getQuorumPeer().leader == null ? omPort1
- : omPort2;
+ long nonLeaderOMPort = s1.getQuorumPeer().leader == null ? omPort1 : omPort2;
int observerClientPort = PortAssignment.unique();
int observerId = 10;
MainThread observer = new MainThread(
- observerId,
- observerClientPort, quorumCfgSection + "\n" +
- createServerString("observer", observerId,
- observerClientPort),
- String.format("observerMasterPort=%d%n", nonLeaderOMPort));
+ observerId,
+ observerClientPort,
+ quorumCfgSection + "\n" + createServerString("observer", observerId, observerClientPort),
+ String.format("observerMasterPort=%d%n", nonLeaderOMPort));
LOG.info("starting observer");
observer.start();
waitServerUp(observerClientPort);
// create a client to the observer
- final LinkedBlockingQueue<KeeperState> states =
- new LinkedBlockingQueue<KeeperState>();
+ final LinkedBlockingQueue<KeeperState> states = new LinkedBlockingQueue<KeeperState>();
ZooKeeper observerClient = new ZooKeeper(
- "127.0.0.1:" + observerClientPort,
- ClientBase.CONNECTION_TIMEOUT, new Watcher() {
- @Override
- public void process(WatchedEvent event) {
- try {
- states.put(event.getState());
- } catch (InterruptedException e) {}
+ "127.0.0.1:" + observerClientPort,
+ ClientBase.CONNECTION_TIMEOUT,
+ new Watcher() {
+ @Override
+ public void process(WatchedEvent event) {
+ try {
+ states.put(event.getState());
+ } catch (InterruptedException e) {
+
}
- });
+ }
+ });
// wait for connected
KeeperState state = states.poll(1000, TimeUnit.MILLISECONDS);
- Assert.assertEquals(KeeperState.SyncConnected, state);
+ assertEquals(KeeperState.SyncConnected, state);
// issue reconfig command
ArrayList<String> newServers = new ArrayList<String>();
- String server = "server.3=127.0.0.1:" + PortAssignment.unique()
- + ":" + PortAssignment.unique() + ":participant;localhost:"
- + PortAssignment.unique();
+ String server = "server.3=127.0.0.1:" + PortAssignment.unique() + ":" + PortAssignment.unique() + ":participant;localhost:" + PortAssignment.unique();
newServers.add(server);
ZooKeeperAdmin admin = createAdmin(clientPort1);
ReconfigTest.reconfig(admin, newServers, null, null, -1);
@@ -704,7 +676,7 @@ public class ObserverMasterTest extends QuorumPeerTestBase implements Watcher{
// shouldn't be disconnected during reconfig, so expect to not
// receive any new event
state = states.poll(1000, TimeUnit.MILLISECONDS);
- Assert.assertNull(state);
+ assertNull(state);
admin.close();
observerClient.close();
@@ -725,6 +697,7 @@ public class ObserverMasterTest extends QuorumPeerTestBase implements Watcher{
}
class AsyncWriter implements Runnable {
+
private final ZooKeeper client;
private final int numTransactions;
private final boolean issueSync;
@@ -732,8 +705,7 @@ public class ObserverMasterTest extends QuorumPeerTestBase implements Watcher{
private final String root;
private final CountDownLatch gate;
- AsyncWriter(ZooKeeper client, int numTransactions, boolean issueSync, CountDownLatch writerLatch,
- String root, CountDownLatch gate) {
+ AsyncWriter(ZooKeeper client, int numTransactions, boolean issueSync, CountDownLatch writerLatch, String root, CountDownLatch gate) {
this.client = client;
this.numTransactions = numTransactions;
this.issueSync = issueSync;
@@ -754,17 +726,16 @@ public class ObserverMasterTest extends QuorumPeerTestBase implements Watcher{
}
for (int i = 0; i < numTransactions; i++) {
final boolean pleaseLog = i % 100 == 0;
- client.create(root + i, "inner thread".getBytes(), Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT, new AsyncCallback.StringCallback() {
- @Override
- public void processResult(int rc, String path,
- Object ctx, String name) {
- writerLatch.countDown();
- if (pleaseLog) {
- LOG.info("wrote {}", path);
- }
- }
- }, null);
+ client.create(root
+ + i, "inner thread".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT, new AsyncCallback.StringCallback() {
+ @Override
+ public void processResult(int rc, String path, Object ctx, String name) {
+ writerLatch.countDown();
+ if (pleaseLog) {
+ LOG.info("wrote {}", path);
+ }
+ }
+ }, null);
if (pleaseLog) {
LOG.info("async wrote {}{}", root, i);
if (issueSync) {
@@ -773,5 +744,7 @@ public class ObserverMasterTest extends QuorumPeerTestBase implements Watcher{
}
}
}
+
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/ObserverQuorumHammerTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/ObserverQuorumHammerTest.java
index 03b400092..7f81e48ec 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/ObserverQuorumHammerTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/ObserverQuorumHammerTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -17,13 +17,14 @@
*/
package org.apache.zookeeper.test;
+
import org.junit.Before;
import org.junit.Test;
public class ObserverQuorumHammerTest extends QuorumHammerTest {
+
public static final long CONNECTION_TIMEOUT = ClientTest.CONNECTION_TIMEOUT;
-
@Before
@Override
public void setUp() throws Exception {
@@ -31,9 +32,10 @@ public class ObserverQuorumHammerTest extends QuorumHammerTest {
cht.hostPort = qb.hostPort;
cht.setUpAll();
}
-
+
@Test
public void testHammerBasic() throws Throwable {
cht.testHammerBasic();
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/ObserverTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/ObserverTest.java
index a51dea4e0..a083c0d2d 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/ObserverTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/ObserverTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,18 +18,18 @@
package org.apache.zookeeper.test;
+import static org.junit.Assert.assertFalse;
import org.apache.zookeeper.PortAssignment;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.server.quorum.QuorumPeerTestBase;
-import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-public class ObserverTest extends QuorumPeerTestBase implements Watcher{
- protected static final Logger LOG =
- LoggerFactory.getLogger(ObserverTest.class);
+public class ObserverTest extends QuorumPeerTestBase implements Watcher {
+
+ protected static final Logger LOG = LoggerFactory.getLogger(ObserverTest.class);
ZooKeeper zk;
@@ -41,18 +41,16 @@ public class ObserverTest extends QuorumPeerTestBase implements Watcher{
@Test
public void testObserverOnly() throws Exception {
ClientBase.setupTestEnv();
- final int CLIENT_PORT_QP1 = PortAssignment.unique();
-
- String quorumCfgSection =
- "server.1=127.0.0.1:" + (PortAssignment.unique())
- + ":" + (PortAssignment.unique()) + ":observer;" + CLIENT_PORT_QP1 + "\n";
-
+ final int CLIENT_PORT_QP1 = PortAssignment.unique();
+
+ String quorumCfgSection = "server.1=127.0.0.1:" + (PortAssignment.unique()) + ":" + (PortAssignment.unique()) + ":observer;" + CLIENT_PORT_QP1 + "\n";
+
MainThread q1 = new MainThread(1, CLIENT_PORT_QP1, quorumCfgSection);
q1.start();
q1.join(ClientBase.CONNECTION_TIMEOUT);
- Assert.assertFalse(q1.isAlive());
- }
-
+ assertFalse(q1.isAlive());
+ }
+
/**
* Ensure that observer only comes up when a proper ensemble is configured.
* (and will not come up with standalone server).
@@ -60,18 +58,15 @@ public class ObserverTest extends QuorumPeerTestBase implements Watcher{
@Test
public void testObserverWithStandlone() throws Exception {
ClientBase.setupTestEnv();
- final int CLIENT_PORT_QP1 = PortAssignment.unique();
+ final int CLIENT_PORT_QP1 = PortAssignment.unique();
- String quorumCfgSection =
- "server.1=127.0.0.1:" + (PortAssignment.unique())
- + ":" + (PortAssignment.unique()) + ":observer\n"
- + "server.2=127.0.0.1:" + (PortAssignment.unique())
- + ":" + (PortAssignment.unique()) + "\npeerType=observer\n";
+ String quorumCfgSection = "server.1=127.0.0.1:" + (PortAssignment.unique()) + ":" + (PortAssignment.unique()) + ":observer\n"
+ + "server.2=127.0.0.1:" + (PortAssignment.unique()) + ":" + (PortAssignment.unique()) + "\npeerType=observer\n";
MainThread q1 = new MainThread(1, CLIENT_PORT_QP1, quorumCfgSection);
q1.start();
q1.join(ClientBase.CONNECTION_TIMEOUT);
- Assert.assertFalse(q1.isAlive());
- }
+ assertFalse(q1.isAlive());
+ }
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/QuorumBase.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/QuorumBase.java
index 83c5d4355..734e5935f 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/QuorumBase.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/QuorumBase.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,6 +18,9 @@
package org.apache.zookeeper.test;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
import java.io.File;
import java.io.IOException;
import java.net.InetSocketAddress;
@@ -26,9 +29,6 @@ import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
import org.apache.zookeeper.PortAssignment;
import org.apache.zookeeper.TestableZooKeeper;
import org.apache.zookeeper.server.quorum.Election;
@@ -37,11 +37,12 @@ import org.apache.zookeeper.server.quorum.QuorumPeer.LearnerType;
import org.apache.zookeeper.server.quorum.QuorumPeer.QuorumServer;
import org.apache.zookeeper.server.quorum.QuorumPeer.ServerState;
import org.apache.zookeeper.server.util.OSMXBean;
-import org.junit.Assert;
import org.junit.Test;
-
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
public class QuorumBase extends ClientBase {
+
private static final Logger LOG = LoggerFactory.getLogger(QuorumBase.class);
private static final String LOCALADDR = "127.0.0.1";
@@ -105,11 +106,16 @@ public class QuorumBase extends ClientBase {
portClient4 = PortAssignment.unique();
portClient5 = PortAssignment.unique();
- hostPort = "127.0.0.1:" + portClient1
- + ",127.0.0.1:" + portClient2
- + ",127.0.0.1:" + portClient3
- + ",127.0.0.1:" + portClient4
- + ",127.0.0.1:" + portClient5;
+ hostPort = "127.0.0.1:"
+ + portClient1
+ + ",127.0.0.1:"
+ + portClient2
+ + ",127.0.0.1:"
+ + portClient3
+ + ",127.0.0.1:"
+ + portClient4
+ + ",127.0.0.1:"
+ + portClient5;
LOG.info("Ports are: " + hostPort);
s1dir = ClientBase.createTmpDir();
@@ -121,9 +127,8 @@ public class QuorumBase extends ClientBase {
startServers(withObservers);
OSMXBean osMbean = new OSMXBean();
- if (osMbean.getUnix() == true) {
- LOG.info("Initial fdcount is: "
- + osMbean.getOpenFileDescriptorCount());
+ if (osMbean.getUnix()) {
+ LOG.info("Initial fdcount is: " + osMbean.getOpenFileDescriptorCount());
}
LOG.info("Setup finished");
@@ -138,32 +143,12 @@ public class QuorumBase extends ClientBase {
int initLimit = 3;
int syncLimit = 3;
int connectToLearnerMasterLimit = 3;
- Map<Long,QuorumServer> peers = new HashMap<Long,QuorumServer>();
- peers.put(Long.valueOf(1), new QuorumServer(1,
- new InetSocketAddress(LOCALADDR, port1),
- new InetSocketAddress(LOCALADDR, portLE1),
- new InetSocketAddress(LOCALADDR, portClient1),
- LearnerType.PARTICIPANT));
- peers.put(Long.valueOf(2), new QuorumServer(2,
- new InetSocketAddress(LOCALADDR, port2),
- new InetSocketAddress(LOCALADDR, portLE2),
- new InetSocketAddress(LOCALADDR, portClient2),
- LearnerType.PARTICIPANT));
- peers.put(Long.valueOf(3), new QuorumServer(3,
- new InetSocketAddress(LOCALADDR, port3),
- new InetSocketAddress(LOCALADDR, portLE3),
- new InetSocketAddress(LOCALADDR, portClient3),
- LearnerType.PARTICIPANT));
- peers.put(Long.valueOf(4), new QuorumServer(4,
- new InetSocketAddress(LOCALADDR, port4),
- new InetSocketAddress(LOCALADDR, portLE4),
- new InetSocketAddress(LOCALADDR, portClient4),
- LearnerType.PARTICIPANT));
- peers.put(Long.valueOf(5), new QuorumServer(5,
- new InetSocketAddress(LOCALADDR, port5),
- new InetSocketAddress(LOCALADDR, portLE5),
- new InetSocketAddress(LOCALADDR, portClient5),
- LearnerType.PARTICIPANT));
+ Map<Long, QuorumServer> peers = new HashMap<Long, QuorumServer>();
+ peers.put(Long.valueOf(1), new QuorumServer(1, new InetSocketAddress(LOCALADDR, port1), new InetSocketAddress(LOCALADDR, portLE1), new InetSocketAddress(LOCALADDR, portClient1), LearnerType.PARTICIPANT));
+ peers.put(Long.valueOf(2), new QuorumServer(2, new InetSocketAddress(LOCALADDR, port2), new InetSocketAddress(LOCALADDR, portLE2), new InetSocketAddress(LOCALADDR, portClient2), LearnerType.PARTICIPANT));
+ peers.put(Long.valueOf(3), new QuorumServer(3, new InetSocketAddress(LOCALADDR, port3), new InetSocketAddress(LOCALADDR, portLE3), new InetSocketAddress(LOCALADDR, portClient3), LearnerType.PARTICIPANT));
+ peers.put(Long.valueOf(4), new QuorumServer(4, new InetSocketAddress(LOCALADDR, port4), new InetSocketAddress(LOCALADDR, portLE4), new InetSocketAddress(LOCALADDR, portClient4), LearnerType.PARTICIPANT));
+ peers.put(Long.valueOf(5), new QuorumServer(5, new InetSocketAddress(LOCALADDR, port5), new InetSocketAddress(LOCALADDR, portLE5), new InetSocketAddress(LOCALADDR, portClient5), LearnerType.PARTICIPANT));
if (withObservers) {
peers.get(Long.valueOf(4)).type = LearnerType.OBSERVER;
@@ -172,19 +157,19 @@ public class QuorumBase extends ClientBase {
LOG.info("creating QuorumPeer 1 port " + portClient1);
s1 = new QuorumPeer(peers, s1dir, s1dir, portClient1, 3, 1, tickTime, initLimit, syncLimit, connectToLearnerMasterLimit);
- Assert.assertEquals(portClient1, s1.getClientPort());
+ assertEquals(portClient1, s1.getClientPort());
LOG.info("creating QuorumPeer 2 port " + portClient2);
s2 = new QuorumPeer(peers, s2dir, s2dir, portClient2, 3, 2, tickTime, initLimit, syncLimit, connectToLearnerMasterLimit);
- Assert.assertEquals(portClient2, s2.getClientPort());
+ assertEquals(portClient2, s2.getClientPort());
LOG.info("creating QuorumPeer 3 port " + portClient3);
s3 = new QuorumPeer(peers, s3dir, s3dir, portClient3, 3, 3, tickTime, initLimit, syncLimit, connectToLearnerMasterLimit);
- Assert.assertEquals(portClient3, s3.getClientPort());
+ assertEquals(portClient3, s3.getClientPort());
LOG.info("creating QuorumPeer 4 port " + portClient4);
s4 = new QuorumPeer(peers, s4dir, s4dir, portClient4, 3, 4, tickTime, initLimit, syncLimit, connectToLearnerMasterLimit);
- Assert.assertEquals(portClient4, s4.getClientPort());
+ assertEquals(portClient4, s4.getClientPort());
LOG.info("creating QuorumPeer 5 port " + portClient5);
s5 = new QuorumPeer(peers, s5dir, s5dir, portClient5, 3, 5, tickTime, initLimit, syncLimit, connectToLearnerMasterLimit);
- Assert.assertEquals(portClient5, s5.getClientPort());
+ assertEquals(portClient5, s5.getClientPort());
if (withObservers) {
s4.setLearnerType(LearnerType.OBSERVER);
@@ -220,11 +205,9 @@ public class QuorumBase extends ClientBase {
s5.start();
LOG.info("started QuorumPeer 5");
- LOG.info ("Checking ports " + hostPort);
+ LOG.info("Checking ports " + hostPort);
for (String hp : hostPort.split(",")) {
- Assert.assertTrue("waiting for server up",
- ClientBase.waitForServerUp(hp,
- CONNECTION_TIMEOUT));
+ assertTrue("waiting for server up", ClientBase.waitForServerUp(hp, CONNECTION_TIMEOUT));
LOG.info(hp + " is accepting client connections");
}
@@ -236,13 +219,11 @@ public class QuorumBase extends ClientBase {
ensureNames.add("InMemoryDataTree");
}
for (int i = 1; i <= 5; i++) {
- ensureNames.add("name0=ReplicatedServer_id" + i
- + ",name1=replica." + i + ",name2=");
+ ensureNames.add("name0=ReplicatedServer_id" + i + ",name1=replica." + i + ",name2=");
}
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= 5; j++) {
- ensureNames.add("name0=ReplicatedServer_id" + i
- + ",name1=replica." + j);
+ ensureNames.add("name0=ReplicatedServer_id" + i + ",name1=replica." + j);
}
}
for (int i = 1; i <= 5; i++) {
@@ -252,18 +233,18 @@ public class QuorumBase extends ClientBase {
}
public int getLeaderIndex() {
- if (s1.getPeerState() == ServerState.LEADING) {
- return 0;
- } else if (s2.getPeerState() == ServerState.LEADING) {
- return 1;
- } else if (s3.getPeerState() == ServerState.LEADING) {
- return 2;
- } else if (s4.getPeerState() == ServerState.LEADING) {
- return 3;
- } else if (s5.getPeerState() == ServerState.LEADING) {
- return 4;
- }
- return -1;
+ if (s1.getPeerState() == ServerState.LEADING) {
+ return 0;
+ } else if (s2.getPeerState() == ServerState.LEADING) {
+ return 1;
+ } else if (s3.getPeerState() == ServerState.LEADING) {
+ return 2;
+ } else if (s4.getPeerState() == ServerState.LEADING) {
+ return 3;
+ } else if (s5.getPeerState() == ServerState.LEADING) {
+ return 4;
+ }
+ return -1;
}
public String getPeersMatching(ServerState state) {
@@ -304,68 +285,48 @@ public class QuorumBase extends ClientBase {
setupServer(5);
}
- Map<Long,QuorumServer> peers = null;
+ Map<Long, QuorumServer> peers = null;
public void setupServer(int i) throws IOException {
int tickTime = 2000;
int initLimit = 3;
int syncLimit = 3;
int connectToLearnerMasterLimit = 3;
- if(peers == null){
- peers = new HashMap<Long,QuorumServer>();
-
- peers.put(Long.valueOf(1), new QuorumServer(1,
- new InetSocketAddress(LOCALADDR, port1),
- new InetSocketAddress(LOCALADDR, portLE1),
- new InetSocketAddress(LOCALADDR, portClient1),
- LearnerType.PARTICIPANT));
- peers.put(Long.valueOf(2), new QuorumServer(2,
- new InetSocketAddress(LOCALADDR, port2),
- new InetSocketAddress(LOCALADDR, portLE2),
- new InetSocketAddress(LOCALADDR, portClient2),
- LearnerType.PARTICIPANT));
- peers.put(Long.valueOf(3), new QuorumServer(3,
- new InetSocketAddress(LOCALADDR, port3),
- new InetSocketAddress(LOCALADDR, portLE3),
- new InetSocketAddress(LOCALADDR, portClient3),
- LearnerType.PARTICIPANT));
- peers.put(Long.valueOf(4), new QuorumServer(4,
- new InetSocketAddress(LOCALADDR, port4),
- new InetSocketAddress(LOCALADDR, portLE4),
- new InetSocketAddress(LOCALADDR, portClient4),
- LearnerType.PARTICIPANT));
- peers.put(Long.valueOf(5), new QuorumServer(5,
- new InetSocketAddress(LOCALADDR, port5),
- new InetSocketAddress(LOCALADDR, portLE5),
- new InetSocketAddress(LOCALADDR, portClient5),
- LearnerType.PARTICIPANT));
+ if (peers == null) {
+ peers = new HashMap<Long, QuorumServer>();
+
+ peers.put(Long.valueOf(1), new QuorumServer(1, new InetSocketAddress(LOCALADDR, port1), new InetSocketAddress(LOCALADDR, portLE1), new InetSocketAddress(LOCALADDR, portClient1), LearnerType.PARTICIPANT));
+ peers.put(Long.valueOf(2), new QuorumServer(2, new InetSocketAddress(LOCALADDR, port2), new InetSocketAddress(LOCALADDR, portLE2), new InetSocketAddress(LOCALADDR, portClient2), LearnerType.PARTICIPANT));
+ peers.put(Long.valueOf(3), new QuorumServer(3, new InetSocketAddress(LOCALADDR, port3), new InetSocketAddress(LOCALADDR, portLE3), new InetSocketAddress(LOCALADDR, portClient3), LearnerType.PARTICIPANT));
+ peers.put(Long.valueOf(4), new QuorumServer(4, new InetSocketAddress(LOCALADDR, port4), new InetSocketAddress(LOCALADDR, portLE4), new InetSocketAddress(LOCALADDR, portClient4), LearnerType.PARTICIPANT));
+ peers.put(Long.valueOf(5), new QuorumServer(5, new InetSocketAddress(LOCALADDR, port5), new InetSocketAddress(LOCALADDR, portLE5), new InetSocketAddress(LOCALADDR, portClient5), LearnerType.PARTICIPANT));
}
- switch(i){
+ switch (i) {
case 1:
LOG.info("creating QuorumPeer 1 port " + portClient1);
s1 = new QuorumPeer(peers, s1dir, s1dir, portClient1, 3, 1, tickTime, initLimit, syncLimit, connectToLearnerMasterLimit);
- Assert.assertEquals(portClient1, s1.getClientPort());
+ assertEquals(portClient1, s1.getClientPort());
break;
case 2:
LOG.info("creating QuorumPeer 2 port " + portClient2);
s2 = new QuorumPeer(peers, s2dir, s2dir, portClient2, 3, 2, tickTime, initLimit, syncLimit, connectToLearnerMasterLimit);
- Assert.assertEquals(portClient2, s2.getClientPort());
+ assertEquals(portClient2, s2.getClientPort());
break;
case 3:
LOG.info("creating QuorumPeer 3 port " + portClient3);
s3 = new QuorumPeer(peers, s3dir, s3dir, portClient3, 3, 3, tickTime, initLimit, syncLimit, connectToLearnerMasterLimit);
- Assert.assertEquals(portClient3, s3.getClientPort());
+ assertEquals(portClient3, s3.getClientPort());
break;
case 4:
LOG.info("creating QuorumPeer 4 port " + portClient4);
s4 = new QuorumPeer(peers, s4dir, s4dir, portClient4, 3, 4, tickTime, initLimit, syncLimit, connectToLearnerMasterLimit);
- Assert.assertEquals(portClient4, s4.getClientPort());
+ assertEquals(portClient4, s4.getClientPort());
break;
case 5:
LOG.info("creating QuorumPeer 5 port " + portClient5);
s5 = new QuorumPeer(peers, s5dir, s5dir, portClient5, 3, 5, tickTime, initLimit, syncLimit, connectToLearnerMasterLimit);
- Assert.assertEquals(portClient5, s5.getClientPort());
+ assertEquals(portClient5, s5.getClientPort());
}
}
@@ -374,17 +335,14 @@ public class QuorumBase extends ClientBase {
LOG.info("TearDown started");
OSMXBean osMbean = new OSMXBean();
- if (osMbean.getUnix() == true) {
- LOG.info("fdcount after test is: "
- + osMbean.getOpenFileDescriptorCount());
+ if (osMbean.getUnix()) {
+ LOG.info("fdcount after test is: " + osMbean.getOpenFileDescriptorCount());
}
shutdownServers();
for (String hp : hostPort.split(",")) {
- Assert.assertTrue("waiting for server down",
- ClientBase.waitForServerDown(hp,
- ClientBase.CONNECTION_TIMEOUT));
+ assertTrue("waiting for server down", ClientBase.waitForServerDown(hp, ClientBase.CONNECTION_TIMEOUT));
LOG.info(hp + " is no longer accepting client connections");
}
@@ -419,29 +377,24 @@ public class QuorumBase extends ClientBase {
maxTimeout = Math.max(maxTimeout, ClientBase.CONNECTION_TIMEOUT);
qp.join(maxTimeout * 2);
if (qp.isAlive()) {
- Assert.fail("QP failed to shutdown in " + (maxTimeout * 2) + " seconds: " + qp.getName());
+ fail("QP failed to shutdown in " + (maxTimeout * 2) + " seconds: " + qp.getName());
}
} catch (InterruptedException e) {
LOG.debug("QP interrupted: " + qp.getName(), e);
}
}
- protected TestableZooKeeper createClient()
- throws IOException, InterruptedException
- {
+ protected TestableZooKeeper createClient() throws IOException, InterruptedException {
return createClient(hostPort);
}
- protected TestableZooKeeper createClient(String hp)
- throws IOException, InterruptedException
- {
+ protected TestableZooKeeper createClient(String hp) throws IOException, InterruptedException {
CountdownWatcher watcher = new CountdownWatcher();
return createClient(watcher, hp);
}
- protected TestableZooKeeper createClient(CountdownWatcher watcher, ServerState state)
- throws IOException, InterruptedException
- {
+ protected TestableZooKeeper createClient(CountdownWatcher watcher, ServerState state) throws IOException, InterruptedException {
return createClient(watcher, getPeersMatching(state));
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/QuorumHammerTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/QuorumHammerTest.java
index e5b377eab..57446ee37 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/QuorumHammerTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/QuorumHammerTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -17,6 +17,7 @@
*/
package org.apache.zookeeper.test;
+
import org.apache.zookeeper.ZKTestCase;
import org.junit.After;
import org.junit.Before;
@@ -25,6 +26,7 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class QuorumHammerTest extends ZKTestCase {
+
protected static final Logger LOG = LoggerFactory.getLogger(QuorumHammerTest.class);
public static final long CONNECTION_TIMEOUT = ClientTest.CONNECTION_TIMEOUT;
@@ -48,4 +50,5 @@ public class QuorumHammerTest extends ZKTestCase {
public void testHammerBasic() throws Throwable {
cht.testHammerBasic();
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/QuorumMajorityTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/QuorumMajorityTest.java
index db40f318b..9516d0165 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/QuorumMajorityTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/QuorumMajorityTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -17,18 +17,20 @@
*/
package org.apache.zookeeper.test;
-import java.util.ArrayList;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import java.util.ArrayList;
import org.apache.zookeeper.jmx.MBeanRegistry;
import org.apache.zookeeper.server.quorum.Leader.Proposal;
import org.apache.zookeeper.server.quorum.QuorumPeer;
import org.apache.zookeeper.server.quorum.QuorumPeer.ServerState;
-import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class QuorumMajorityTest extends QuorumBase {
+
protected static final Logger LOG = LoggerFactory.getLogger(QuorumMajorityTest.class);
public static final long CONNECTION_TIMEOUT = ClientTest.CONNECTION_TIMEOUT;
@@ -46,61 +48,56 @@ public class QuorumMajorityTest extends QuorumBase {
Long electionTimeTaken = -1L;
String bean = "";
if (qp.getPeerState() == ServerState.FOLLOWING) {
- bean = String.format(
- "%s:name0=ReplicatedServer_id%d,name1=replica.%d,name2=Follower",
- MBeanRegistry.DOMAIN, i, i);
+ bean = String.format("%s:name0=ReplicatedServer_id%d,name1=replica.%d,name2=Follower", MBeanRegistry.DOMAIN, i, i);
} else if (qp.getPeerState() == ServerState.LEADING) {
- bean = String.format(
- "%s:name0=ReplicatedServer_id%d,name1=replica.%d,name2=Leader",
- MBeanRegistry.DOMAIN, i, i);
+ bean = String.format("%s:name0=ReplicatedServer_id%d,name1=replica.%d,name2=Leader", MBeanRegistry.DOMAIN, i, i);
}
- electionTimeTaken = (Long) JMXEnv.ensureBeanAttribute(bean,
- "ElectionTimeTaken");
- Assert.assertTrue("Wrong electionTimeTaken value!",
- electionTimeTaken >= 0);
+ electionTimeTaken = (Long) JMXEnv.ensureBeanAttribute(bean, "ElectionTimeTaken");
+ assertTrue("Wrong electionTimeTaken value!", electionTimeTaken >= 0);
}
- //setup servers 1-5 to be followers
- setUp(false);
-
- Proposal p = new Proposal();
-
+ //setup servers 1-5 to be followers
+ setUp(false);
+
+ Proposal p = new Proposal();
+
p.addQuorumVerifier(s1.getQuorumVerifier());
-
+
// 2 followers out of 5 is not a majority
p.addAck(Long.valueOf(1));
- p.addAck(Long.valueOf(2));
- Assert.assertEquals(false, p.hasAllQuorums());
-
+ p.addAck(Long.valueOf(2));
+ assertEquals(false, p.hasAllQuorums());
+
// 6 is not in the view - its vote shouldn't count
- p.addAck(Long.valueOf(6));
- Assert.assertEquals(false, p.hasAllQuorums());
-
+ p.addAck(Long.valueOf(6));
+ assertEquals(false, p.hasAllQuorums());
+
// 3 followers out of 5 are a majority of the voting view
- p.addAck(Long.valueOf(3));
- Assert.assertEquals(true, p.hasAllQuorums());
-
- //setup servers 1-3 to be followers and 4 and 5 to be observers
- setUp(true);
-
- p = new Proposal();
- p.addQuorumVerifier(s1.getQuorumVerifier());
-
+ p.addAck(Long.valueOf(3));
+ assertEquals(true, p.hasAllQuorums());
+
+ //setup servers 1-3 to be followers and 4 and 5 to be observers
+ setUp(true);
+
+ p = new Proposal();
+ p.addQuorumVerifier(s1.getQuorumVerifier());
+
// 1 follower out of 3 is not a majority
- p.addAck(Long.valueOf(1));
- Assert.assertEquals(false, p.hasAllQuorums());
-
+ p.addAck(Long.valueOf(1));
+ assertEquals(false, p.hasAllQuorums());
+
// 4 and 5 are observers, their vote shouldn't count
p.addAck(Long.valueOf(4));
p.addAck(Long.valueOf(5));
- Assert.assertEquals(false, p.hasAllQuorums());
-
+ assertEquals(false, p.hasAllQuorums());
+
// 6 is not in the view - its vote shouldn't count
p.addAck(Long.valueOf(6));
- Assert.assertEquals(false, p.hasAllQuorums());
-
+ assertEquals(false, p.hasAllQuorums());
+
// 2 followers out of 3 are a majority of the voting view
p.addAck(Long.valueOf(2));
- Assert.assertEquals(true, p.hasAllQuorums());
+ assertEquals(true, p.hasAllQuorums());
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/QuorumQuotaTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/QuorumQuotaTest.java
index 4391ce955..6025a158a 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/QuorumQuotaTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/QuorumQuotaTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,15 +18,14 @@
package org.apache.zookeeper.test;
+import static org.junit.Assert.assertTrue;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.Quotas;
import org.apache.zookeeper.StatsTrack;
-import org.apache.zookeeper.ZooKeeper;
-import org.apache.zookeeper.ZooKeeperMain;
import org.apache.zookeeper.ZooDefs.Ids;
+import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.cli.SetQuotaCommand;
import org.apache.zookeeper.data.Stat;
-import org.junit.Assert;
import org.junit.Test;
public class QuorumQuotaTest extends QuorumBase {
@@ -35,26 +34,24 @@ public class QuorumQuotaTest extends QuorumBase {
public void testQuotaWithQuorum() throws Exception {
ZooKeeper zk = createClient();
zk.setData("/", "some".getBytes(), -1);
- zk.create("/a", "some".getBytes(), Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk.create("/a", "some".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
int i = 0;
- for (i=0; i < 300;i++) {
- zk.create("/a/" + i, "some".getBytes(), Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ for (i = 0; i < 300; i++) {
+ zk.create("/a/" + i, "some".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
}
SetQuotaCommand.createQuota(zk, "/a", 1000L, 5000);
- String statPath = Quotas.quotaZookeeper + "/a"+ "/" + Quotas.statNode;
+ String statPath = Quotas.quotaZookeeper + "/a" + "/" + Quotas.statNode;
byte[] data = zk.getData(statPath, false, new Stat());
StatsTrack st = new StatsTrack(new String(data));
- Assert.assertTrue("bytes are set", st.getBytes() == 1204L);
- Assert.assertTrue("num count is set", st.getCount() == 301);
- for (i=300; i < 600; i++) {
- zk.create("/a/" + i, "some".getBytes(), Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ assertTrue("bytes are set", st.getBytes() == 1204L);
+ assertTrue("num count is set", st.getCount() == 301);
+ for (i = 300; i < 600; i++) {
+ zk.create("/a/" + i, "some".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
}
data = zk.getData(statPath, false, new Stat());
st = new StatsTrack(new String(data));
- Assert.assertTrue("bytes are set", st.getBytes() == 2404L);
- Assert.assertTrue("num count is set", st.getCount() == 601);
+ assertTrue("bytes are set", st.getBytes() == 2404L);
+ assertTrue("num count is set", st.getCount() == 601);
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/QuorumTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/QuorumTest.java
index 20388d890..f39548b02 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/QuorumTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/QuorumTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -17,13 +17,16 @@
*/
package org.apache.zookeeper.test;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
-import java.util.concurrent.Semaphore;
-import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
-
import org.apache.zookeeper.AsyncCallback;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
@@ -40,7 +43,6 @@ import org.apache.zookeeper.server.quorum.Leader;
import org.apache.zookeeper.server.quorum.LearnerHandler;
import org.apache.zookeeper.test.ClientBase.CountdownWatcher;
import org.junit.After;
-import org.junit.Assert;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
@@ -48,6 +50,7 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class QuorumTest extends ZKTestCase {
+
private static final Logger LOG = LoggerFactory.getLogger(QuorumTest.class);
public static final long CONNECTION_TIMEOUT = ClientTest.CONNECTION_TIMEOUT;
@@ -82,9 +85,7 @@ public class QuorumTest extends ZKTestCase {
}
@Test
- public void testSequentialNodeNames()
- throws IOException, InterruptedException, KeeperException
- {
+ public void testSequentialNodeNames() throws IOException, InterruptedException, KeeperException {
ct.testSequentialNodeNames();
}
@@ -94,38 +95,34 @@ public class QuorumTest extends ZKTestCase {
}
@Test
- public void testClientwithoutWatcherObj() throws IOException,
- InterruptedException, KeeperException
- {
+ public void testClientwithoutWatcherObj() throws IOException, InterruptedException, KeeperException {
ct.testClientwithoutWatcherObj();
}
@Test
- public void testClientWithWatcherObj() throws IOException,
- InterruptedException, KeeperException
- {
+ public void testClientWithWatcherObj() throws IOException, InterruptedException, KeeperException {
ct.testClientWithWatcherObj();
}
@Test
public void testGetView() {
- Assert.assertEquals(5,qb.s1.getView().size());
- Assert.assertEquals(5,qb.s2.getView().size());
- Assert.assertEquals(5,qb.s3.getView().size());
- Assert.assertEquals(5,qb.s4.getView().size());
- Assert.assertEquals(5,qb.s5.getView().size());
+ assertEquals(5, qb.s1.getView().size());
+ assertEquals(5, qb.s2.getView().size());
+ assertEquals(5, qb.s3.getView().size());
+ assertEquals(5, qb.s4.getView().size());
+ assertEquals(5, qb.s5.getView().size());
}
@Test
public void testViewContains() {
// Test view contains self
- Assert.assertTrue(qb.s1.viewContains(qb.s1.getId()));
+ assertTrue(qb.s1.viewContains(qb.s1.getId()));
// Test view contains other servers
- Assert.assertTrue(qb.s1.viewContains(qb.s2.getId()));
+ assertTrue(qb.s1.viewContains(qb.s2.getId()));
// Test view does not contain non-existant servers
- Assert.assertFalse(qb.s1.viewContains(-1L));
+ assertFalse(qb.s1.viewContains(-1L));
}
volatile int counter = 0;
@@ -134,19 +131,27 @@ public class QuorumTest extends ZKTestCase {
public void testLeaderShutdown() throws IOException, InterruptedException, KeeperException {
ZooKeeper zk = new DisconnectableZooKeeper(qb.hostPort, ClientBase.CONNECTION_TIMEOUT, new Watcher() {
public void process(WatchedEvent event) {
- }});
+ }
+ });
zk.create("/blah", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
zk.create("/blah/blah", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
Leader leader = qb.s1.leader;
- if (leader == null) leader = qb.s2.leader;
- if (leader == null) leader = qb.s3.leader;
- if (leader == null) leader = qb.s4.leader;
- if (leader == null) leader = qb.s5.leader;
- Assert.assertNotNull(leader);
- for(int i = 0; i < 5000; i++) {
+ if (leader == null) {
+ leader = qb.s2.leader;
+ }
+ if (leader == null) {
+ leader = qb.s3.leader;
+ }
+ if (leader == null) {
+ leader = qb.s4.leader;
+ }
+ if (leader == null) {
+ leader = qb.s5.leader;
+ }
+ assertNotNull(leader);
+ for (int i = 0; i < 5000; i++) {
zk.setData("/blah/blah", new byte[0], -1, new AsyncCallback.StatCallback() {
- public void processResult(int rc, String path, Object ctx,
- Stat stat) {
+ public void processResult(int rc, String path, Object ctx, Stat stat) {
counter++;
if (rc != 0) {
errors++;
@@ -154,13 +159,12 @@ public class QuorumTest extends ZKTestCase {
}
}, null);
}
- for(LearnerHandler f : leader.getForwardingFollowers()) {
+ for (LearnerHandler f : leader.getForwardingFollowers()) {
f.getSocket().shutdownInput();
}
- for(int i = 0; i < 5000; i++) {
+ for (int i = 0; i < 5000; i++) {
zk.setData("/blah/blah", new byte[0], -1, new AsyncCallback.StatCallback() {
- public void processResult(int rc, String path, Object ctx,
- Stat stat) {
+ public void processResult(int rc, String path, Object ctx, Stat stat) {
counter++;
if (rc != 0) {
errors++;
@@ -169,18 +173,16 @@ public class QuorumTest extends ZKTestCase {
}, null);
}
// check if all the followers are alive
- Assert.assertTrue(qb.s1.isAlive());
- Assert.assertTrue(qb.s2.isAlive());
- Assert.assertTrue(qb.s3.isAlive());
- Assert.assertTrue(qb.s4.isAlive());
- Assert.assertTrue(qb.s5.isAlive());
+ assertTrue(qb.s1.isAlive());
+ assertTrue(qb.s2.isAlive());
+ assertTrue(qb.s3.isAlive());
+ assertTrue(qb.s4.isAlive());
+ assertTrue(qb.s5.isAlive());
zk.close();
}
@Test
- public void testMultipleWatcherObjs() throws IOException,
- InterruptedException, KeeperException
- {
+ public void testMultipleWatcherObjs() throws IOException, InterruptedException, KeeperException {
ct.testMutipleWatcherObjs();
}
@@ -194,42 +196,43 @@ public class QuorumTest extends ZKTestCase {
*/
@Test
public void testSessionMoved() throws Exception {
- String hostPorts[] = qb.hostPort.split(",");
- DisconnectableZooKeeper zk = new DisconnectableZooKeeper(hostPorts[0],
- ClientBase.CONNECTION_TIMEOUT, new Watcher() {
+ String[] hostPorts = qb.hostPort.split(",");
+ DisconnectableZooKeeper zk = new DisconnectableZooKeeper(hostPorts[0], ClientBase.CONNECTION_TIMEOUT, new Watcher() {
public void process(WatchedEvent event) {
- }});
+ }
+ });
zk.create("/sessionMoveTest", new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
// we want to loop through the list twice
- for(int i = 0; i < hostPorts.length*2; i++) {
+ for (int i = 0; i < hostPorts.length * 2; i++) {
zk.dontReconnect();
// This should stomp the zk handle
- DisconnectableZooKeeper zknew =
- new DisconnectableZooKeeper(hostPorts[(i+1)%hostPorts.length],
- ClientBase.CONNECTION_TIMEOUT,
- new Watcher() {public void process(WatchedEvent event) {
- }},
- zk.getSessionId(),
- zk.getSessionPasswd());
+ DisconnectableZooKeeper zknew = new DisconnectableZooKeeper(hostPorts[(i + 1)
+ % hostPorts.length], ClientBase.CONNECTION_TIMEOUT, new Watcher() {
+ public void process(WatchedEvent event) {
+ }
+ }, zk.getSessionId(), zk.getSessionPasswd());
zknew.setData("/", new byte[1], -1);
- final int result[] = new int[1];
+ final int[] result = new int[1];
result[0] = Integer.MAX_VALUE;
zknew.sync("/", new AsyncCallback.VoidCallback() {
- public void processResult(int rc, String path, Object ctx) {
- synchronized(result) { result[0] = rc; result.notify(); }
+ public void processResult(int rc, String path, Object ctx) {
+ synchronized (result) {
+ result[0] = rc;
+ result.notify();
}
- }, null);
- synchronized(result) {
- if(result[0] == Integer.MAX_VALUE) {
+ }
+ }, null);
+ synchronized (result) {
+ if (result[0] == Integer.MAX_VALUE) {
result.wait(5000);
}
}
- LOG.info(hostPorts[(i+1)%hostPorts.length] + " Sync returned " + result[0]);
- Assert.assertTrue(result[0] == KeeperException.Code.OK.intValue());
+ LOG.info(hostPorts[(i + 1) % hostPorts.length] + " Sync returned " + result[0]);
+ assertTrue(result[0] == KeeperException.Code.OK.intValue());
try {
zk.setData("/", new byte[1], -1);
- Assert.fail("Should have lost the connection");
- } catch(KeeperException.ConnectionLossException e) {
+ fail("Should have lost the connection");
+ } catch (KeeperException.ConnectionLossException e) {
}
zk = zknew;
}
@@ -237,12 +240,14 @@ public class QuorumTest extends ZKTestCase {
}
private static class DiscoWatcher implements Watcher {
+
volatile boolean zkDisco = false;
public void process(WatchedEvent event) {
if (event.getState() == KeeperState.Disconnected) {
zkDisco = true;
}
}
+
}
/**
@@ -255,35 +260,26 @@ public class QuorumTest extends ZKTestCase {
*/
@Test
public void testSessionMovedWithMultiOp() throws Exception {
- String hostPorts[] = qb.hostPort.split(",");
- DisconnectableZooKeeper zk = new DisconnectableZooKeeper(hostPorts[0],
- ClientBase.CONNECTION_TIMEOUT, new Watcher() {
+ String[] hostPorts = qb.hostPort.split(",");
+ DisconnectableZooKeeper zk = new DisconnectableZooKeeper(hostPorts[0], ClientBase.CONNECTION_TIMEOUT, new Watcher() {
public void process(WatchedEvent event) {
- }});
- zk.multi(Arrays.asList(
- Op.create("/testSessionMovedWithMultiOp", new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL)
- ));
+ }
+ });
+ zk.multi(Arrays.asList(Op.create("/testSessionMovedWithMultiOp", new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL)));
// session moved to the next server
- ZooKeeper zknew = new ZooKeeper(hostPorts[1],
- ClientBase.CONNECTION_TIMEOUT,
- new Watcher() {public void process(WatchedEvent event) {
- }},
- zk.getSessionId(),
- zk.getSessionPasswd());
- zknew.multi(Arrays.asList(
- Op.create("/testSessionMovedWithMultiOp-1", new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL)
- ));
+ ZooKeeper zknew = new ZooKeeper(hostPorts[1], ClientBase.CONNECTION_TIMEOUT, new Watcher() {
+ public void process(WatchedEvent event) {
+ }
+ }, zk.getSessionId(), zk.getSessionPasswd());
+ zknew.multi(Arrays.asList(Op.create("/testSessionMovedWithMultiOp-1", new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL)));
// try to issue the multi op again from the old connection
// expect to have ConnectionLossException instead of keep
// getting SessionMovedException
try {
- zk.multi(Arrays.asList(
- Op.create("/testSessionMovedWithMultiOp-Failed",
- new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL)
- ));
- Assert.fail("Should have lost the connection");
+ zk.multi(Arrays.asList(Op.create("/testSessionMovedWithMultiOp-Failed", new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL)));
+ fail("Should have lost the connection");
} catch (KeeperException.ConnectionLossException e) {
}
@@ -298,22 +294,19 @@ public class QuorumTest extends ZKTestCase {
@Test
@Ignore
public void testSessionMove() throws Exception {
- String hps[] = qb.hostPort.split(",");
+ String[] hps = qb.hostPort.split(",");
DiscoWatcher oldWatcher = new DiscoWatcher();
- DisconnectableZooKeeper zk = new DisconnectableZooKeeper(hps[0],
- ClientBase.CONNECTION_TIMEOUT, oldWatcher);
+ DisconnectableZooKeeper zk = new DisconnectableZooKeeper(hps[0], ClientBase.CONNECTION_TIMEOUT, oldWatcher);
zk.create("/t1", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
zk.dontReconnect();
// This should stomp the zk handle
DiscoWatcher watcher = new DiscoWatcher();
- DisconnectableZooKeeper zknew = new DisconnectableZooKeeper(hps[1],
- ClientBase.CONNECTION_TIMEOUT, watcher, zk.getSessionId(),
- zk.getSessionPasswd());
+ DisconnectableZooKeeper zknew = new DisconnectableZooKeeper(hps[1], ClientBase.CONNECTION_TIMEOUT, watcher, zk.getSessionId(), zk.getSessionPasswd());
zknew.create("/t2", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
try {
zk.create("/t3", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
- Assert.fail("Should have lost the connection");
- } catch(KeeperException.ConnectionLossException e) {
+ fail("Should have lost the connection");
+ } catch (KeeperException.ConnectionLossException e) {
// wait up to 30 seconds for the disco to be delivered
for (int i = 0; i < 30; i++) {
if (oldWatcher.zkDisco) {
@@ -321,21 +314,19 @@ public class QuorumTest extends ZKTestCase {
}
Thread.sleep(1000);
}
- Assert.assertTrue(oldWatcher.zkDisco);
+ assertTrue(oldWatcher.zkDisco);
}
ArrayList<ZooKeeper> toClose = new ArrayList<ZooKeeper>();
toClose.add(zknew);
// Let's just make sure it can still move
- for(int i = 0; i < 10; i++) {
+ for (int i = 0; i < 10; i++) {
zknew.dontReconnect();
- zknew = new DisconnectableZooKeeper(hps[1],
- ClientBase.CONNECTION_TIMEOUT, new DiscoWatcher(),
- zk.getSessionId(), zk.getSessionPasswd());
+ zknew = new DisconnectableZooKeeper(hps[1], ClientBase.CONNECTION_TIMEOUT, new DiscoWatcher(), zk.getSessionId(), zk.getSessionPasswd());
toClose.add(zknew);
- zknew.create("/t-"+i, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
+ zknew.create("/t-" + i, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
}
- for (ZooKeeper z: toClose) {
+ for (ZooKeeper z : toClose) {
z.close();
}
zk.close();
@@ -351,8 +342,9 @@ public class QuorumTest extends ZKTestCase {
qu.startQuorum();
int index = 1;
- while(qu.getPeer(index).peer.leader == null)
+ while (qu.getPeer(index).peer.leader == null) {
index++;
+ }
// break the quorum
qu.shutdown(index);
@@ -363,13 +355,14 @@ public class QuorumTest extends ZKTestCase {
// Connect the client after services are restarted (otherwise we would get
// SessionExpiredException as the previous local session was not persisted).
ZooKeeper zk = new ZooKeeper(
- "127.0.0.1:" + qu.getPeer((index == 1)?2:1).peer.getClientPort(),
- ClientBase.CONNECTION_TIMEOUT, watcher);
+ "127.0.0.1:" + qu.getPeer((index == 1) ? 2 : 1).peer.getClientPort(),
+ ClientBase.CONNECTION_TIMEOUT,
+ watcher);
- try{
+ try {
watcher.waitForConnected(CONNECTION_TIMEOUT);
- } catch(TimeoutException e) {
- Assert.fail("client could not connect to reestablished quorum: giving up after 30+ seconds.");
+ } catch (TimeoutException e) {
+ fail("client could not connect to reestablished quorum: giving up after 30+ seconds.");
}
zk.close();
@@ -393,23 +386,25 @@ public class QuorumTest extends ZKTestCase {
qu.startQuorum();
int index = 1;
- while(qu.getPeer(index).peer.leader == null)
+ while (qu.getPeer(index).peer.leader == null) {
index++;
+ }
ZooKeeper zk = new ZooKeeper(
- "127.0.0.1:" + qu.getPeer((index == 1)?2:1).peer.getClientPort(),
- ClientBase.CONNECTION_TIMEOUT, watcher);
+ "127.0.0.1:" + qu.getPeer((index == 1) ? 2 : 1).peer.getClientPort(),
+ ClientBase.CONNECTION_TIMEOUT,
+ watcher);
watcher.waitForConnected(CONNECTION_TIMEOUT);
zk.multi(Arrays.asList(
Op.create("/multi0", new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT),
Op.create("/multi1", new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT),
- Op.create("/multi2", new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT)
- ));
+ Op.create("/multi2", new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT)));
zk.getData("/multi0", false, null);
zk.getData("/multi1", false, null);
zk.getData("/multi2", false, null);
zk.close();
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/QuorumUtil.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/QuorumUtil.java
index 6d711fc91..46511ebd9 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/QuorumUtil.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/QuorumUtil.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,6 +18,9 @@
package org.apache.zookeeper.test;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
import java.io.File;
import java.io.IOException;
import java.net.InetSocketAddress;
@@ -28,14 +31,12 @@ import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
-
import org.apache.zookeeper.PortAssignment;
import org.apache.zookeeper.server.quorum.Election;
import org.apache.zookeeper.server.quorum.QuorumPeer;
import org.apache.zookeeper.server.quorum.QuorumPeer.LearnerType;
import org.apache.zookeeper.server.quorum.QuorumPeer.QuorumServer;
import org.apache.zookeeper.server.util.OSMXBean;
-import org.junit.Assert;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -52,10 +53,12 @@ public class QuorumUtil {
private static final Logger LOG = LoggerFactory.getLogger(QuorumUtil.class);
public static class PeerStruct {
+
public int id;
public QuorumPeer peer;
public File dataDir;
public int clientPort;
+
}
private final Map<Long, QuorumServer> peersView = new HashMap<Long, QuorumServer>();
@@ -73,7 +76,7 @@ public class QuorumUtil {
private int initLimit;
private int syncLimit;
-
+
private int connectToLearnerMasterLimit;
private int electionAlg;
@@ -107,19 +110,14 @@ public class QuorumUtil {
ps.clientPort = PortAssignment.unique();
peers.put(i, ps);
- peersView.put(Long.valueOf(i), new QuorumServer(i,
- new InetSocketAddress("127.0.0.1", PortAssignment.unique()),
- new InetSocketAddress("127.0.0.1", PortAssignment.unique()),
- new InetSocketAddress("127.0.0.1", ps.clientPort),
- LearnerType.PARTICIPANT));
+ peersView.put(Long.valueOf(i), new QuorumServer(i, new InetSocketAddress("127.0.0.1", PortAssignment.unique()), new InetSocketAddress("127.0.0.1", PortAssignment.unique()), new InetSocketAddress("127.0.0.1", ps.clientPort), LearnerType.PARTICIPANT));
hostPort += "127.0.0.1:" + ps.clientPort + ((i == ALL) ? "" : ",");
}
for (int i = 1; i <= ALL; ++i) {
PeerStruct ps = peers.get(i);
LOG.info("Creating QuorumPeer " + i + "; public port " + ps.clientPort);
- ps.peer = new QuorumPeer(peersView, ps.dataDir, ps.dataDir, ps.clientPort,
- electionAlg, ps.id, tickTime, initLimit, syncLimit, connectToLearnerMasterLimit);
- Assert.assertEquals(ps.clientPort, ps.peer.getClientPort());
+ ps.peer = new QuorumPeer(peersView, ps.dataDir, ps.dataDir, ps.clientPort, electionAlg, ps.id, tickTime, initLimit, syncLimit, connectToLearnerMasterLimit);
+ assertEquals(ps.clientPort, ps.peer.getClientPort());
}
} catch (Exception e) {
throw new RuntimeException(e);
@@ -136,7 +134,6 @@ public class QuorumUtil {
// This was added to avoid running into the problem of ZOOKEEPER-1539
public boolean disableJMXTest = false;
-
public void enableLocalSession(boolean localSessionEnabled) {
this.localSessionEnabled = localSessionEnabled;
@@ -151,14 +148,15 @@ public class QuorumUtil {
LOG.info("Checking ports " + hostPort);
for (String hp : hostPort.split(",")) {
- Assert.assertTrue("waiting for server up", ClientBase.waitForServerUp(hp,
- ClientBase.CONNECTION_TIMEOUT));
+ assertTrue("waiting for server up", ClientBase.waitForServerUp(hp, ClientBase.CONNECTION_TIMEOUT));
LOG.info(hp + " is accepting client connections");
}
// This was added to avoid running into the problem of ZOOKEEPER-1539
- if (disableJMXTest) return;
-
+ if (disableJMXTest) {
+ return;
+ }
+
// interesting to see what's there...
try {
JMXEnv.dump();
@@ -168,8 +166,7 @@ public class QuorumUtil {
ensureNames.add("InMemoryDataTree");
}
for (int i = 1; i <= ALL; ++i) {
- ensureNames
- .add("name0=ReplicatedServer_id" + i + ",name1=replica." + i + ",name2=");
+ ensureNames.add("name0=ReplicatedServer_id" + i + ",name1=replica." + i + ",name2=");
}
for (int i = 1; i <= ALL; ++i) {
for (int j = 1; j <= ALL; ++j) {
@@ -196,43 +193,44 @@ public class QuorumUtil {
start(i);
}
for (int i = 1; i <= N + 1; ++i) {
- Assert.assertTrue("Waiting for server up", ClientBase.waitForServerUp("127.0.0.1:"
- + getPeer(i).clientPort, ClientBase.CONNECTION_TIMEOUT));
+ assertTrue(
+ "Waiting for server up",
+ ClientBase.waitForServerUp("127.0.0.1:" + getPeer(i).clientPort, ClientBase.CONNECTION_TIMEOUT));
}
}
public void start(int id) throws IOException {
PeerStruct ps = getPeer(id);
LOG.info("Creating QuorumPeer " + ps.id + "; public port " + ps.clientPort);
- ps.peer = new QuorumPeer(peersView, ps.dataDir, ps.dataDir, ps.clientPort, electionAlg,
- ps.id, tickTime, initLimit, syncLimit, connectToLearnerMasterLimit);
+ ps.peer = new QuorumPeer(peersView, ps.dataDir, ps.dataDir, ps.clientPort, electionAlg, ps.id, tickTime, initLimit, syncLimit, connectToLearnerMasterLimit);
if (localSessionEnabled) {
ps.peer.enableLocalSessions(true);
}
- Assert.assertEquals(ps.clientPort, ps.peer.getClientPort());
+ assertEquals(ps.clientPort, ps.peer.getClientPort());
ps.peer.start();
}
public void restart(int id) throws IOException {
start(id);
- Assert.assertTrue("Waiting for server up", ClientBase.waitForServerUp("127.0.0.1:"
- + getPeer(id).clientPort, ClientBase.CONNECTION_TIMEOUT));
+ assertTrue(
+ "Waiting for server up",
+ ClientBase.waitForServerUp("127.0.0.1:" + getPeer(id).clientPort, ClientBase.CONNECTION_TIMEOUT));
}
public void startThenShutdown(int id) throws IOException {
PeerStruct ps = getPeer(id);
LOG.info("Creating QuorumPeer " + ps.id + "; public port " + ps.clientPort);
- ps.peer = new QuorumPeer(peersView, ps.dataDir, ps.dataDir, ps.clientPort, electionAlg,
- ps.id, tickTime, initLimit, syncLimit, connectToLearnerMasterLimit);
+ ps.peer = new QuorumPeer(peersView, ps.dataDir, ps.dataDir, ps.clientPort, electionAlg, ps.id, tickTime, initLimit, syncLimit, connectToLearnerMasterLimit);
if (localSessionEnabled) {
ps.peer.enableLocalSessions(true);
}
- Assert.assertEquals(ps.clientPort, ps.peer.getClientPort());
+ assertEquals(ps.clientPort, ps.peer.getClientPort());
ps.peer.start();
- Assert.assertTrue("Waiting for server up", ClientBase.waitForServerUp("127.0.0.1:"
- + getPeer(id).clientPort, ClientBase.CONNECTION_TIMEOUT));
+ assertTrue(
+ "Waiting for server up",
+ ClientBase.waitForServerUp("127.0.0.1:" + getPeer(id).clientPort, ClientBase.CONNECTION_TIMEOUT));
shutdown(id);
}
@@ -241,8 +239,7 @@ public class QuorumUtil {
shutdown(i);
}
for (String hp : hostPort.split(",")) {
- Assert.assertTrue("Waiting for server down", ClientBase.waitForServerDown(hp,
- ClientBase.CONNECTION_TIMEOUT));
+ assertTrue("Waiting for server down", ClientBase.waitForServerDown(hp, ClientBase.CONNECTION_TIMEOUT));
LOG.info(hp + " is no longer accepting client connections");
}
}
@@ -262,7 +259,7 @@ public class QuorumUtil {
LOG.info("Waiting for " + qp.getName() + " to exit thread");
qp.join(30000);
if (qp.isAlive()) {
- Assert.fail("QP failed to shutdown in 30 seconds: " + qp.getName());
+ fail("QP failed to shutdown in 30 seconds: " + qp.getName());
}
} catch (InterruptedException e) {
LOG.debug("QP interrupted: " + qp.getName(), e);
@@ -278,20 +275,20 @@ public class QuorumUtil {
}
public QuorumPeer getLeaderQuorumPeer() {
- for (PeerStruct ps: peers.values()) {
+ for (PeerStruct ps : peers.values()) {
if (ps.peer.leader != null) {
- return ps.peer;
+ return ps.peer;
}
}
throw new RuntimeException("Unable to find a leader peer");
}
public List<QuorumPeer> getFollowerQuorumPeers() {
- List<QuorumPeer> peerList = new ArrayList<QuorumPeer>(ALL - 1);
+ List<QuorumPeer> peerList = new ArrayList<QuorumPeer>(ALL - 1);
- for (PeerStruct ps: peers.values()) {
+ for (PeerStruct ps : peers.values()) {
if (ps.peer.leader == null) {
- peerList.add(ps.peer);
+ peerList.add(ps.peer);
}
}
@@ -302,7 +299,7 @@ public class QuorumUtil {
LOG.info("TearDown started");
OSMXBean osMbean = new OSMXBean();
- if (osMbean.getUnix() == true) {
+ if (osMbean.getUnix()) {
LOG.info("fdcount after test is: " + osMbean.getOpenFileDescriptorCount());
}
@@ -319,11 +316,12 @@ public class QuorumUtil {
}
}
- Assert.assertTrue("Leader server not found.", index > 0);
+ assertTrue("Leader server not found.", index > 0);
return index;
}
public String getConnectionStringForServer(final int index) {
return "127.0.0.1:" + getPeer(index).clientPort;
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/QuorumUtilTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/QuorumUtilTest.java
index 76e6df015..d02fbd693 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/QuorumUtilTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/QuorumUtilTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or morecontributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -15,16 +15,17 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
package org.apache.zookeeper.test;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
import java.io.IOException;
import java.util.Set;
-
import org.apache.zookeeper.ZKTestCase;
import org.apache.zookeeper.jmx.MBeanRegistry;
import org.apache.zookeeper.jmx.ZKMBeanInfo;
import org.apache.zookeeper.server.quorum.QuorumPeer;
-import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -34,8 +35,8 @@ import org.slf4j.LoggerFactory;
* {@link QuorumUtil} helper.
*/
public class QuorumUtilTest extends ZKTestCase {
- private static final Logger LOG = LoggerFactory
- .getLogger(QuorumUtilTest.class);
+
+ private static final Logger LOG = LoggerFactory.getLogger(QuorumUtilTest.class);
/**
* <p>
@@ -72,7 +73,7 @@ public class QuorumUtilTest extends ZKTestCase {
break;
default:
- Assert.fail("Unexpected leaderIndex value: " + leaderIndex);
+ fail("Unexpected leaderIndex value: " + leaderIndex);
break;
}
@@ -86,9 +87,8 @@ public class QuorumUtilTest extends ZKTestCase {
qU.restart(secondFollowerIndex);
qU.shutdownAll();
- Set<ZKMBeanInfo> pending = MBeanRegistry.getInstance()
- .getRegisteredBeans();
- Assert.assertTrue("The following beans should have been unregistered: "
- + pending, pending.isEmpty());
+ Set<ZKMBeanInfo> pending = MBeanRegistry.getInstance().getRegisteredBeans();
+ assertTrue("The following beans should have been unregistered: " + pending, pending.isEmpty());
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/QuorumZxidSyncTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/QuorumZxidSyncTest.java
index 61556bf7e..0cdeb0d18 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/QuorumZxidSyncTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/QuorumZxidSyncTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,9 +18,10 @@
package org.apache.zookeeper.test;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.IOException;
-
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
@@ -28,11 +29,11 @@ import org.apache.zookeeper.ZKTestCase;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;
import org.junit.After;
-import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
public class QuorumZxidSyncTest extends ZKTestCase {
+
QuorumBase qb = new QuorumBase();
@Before
@@ -50,7 +51,8 @@ public class QuorumZxidSyncTest extends ZKTestCase {
ClientBase.waitForServerUp(qb.hostPort, 10000);
ZooKeeper zk = new ZooKeeper(qb.hostPort, 10000, new Watcher() {
public void process(WatchedEvent event) {
- }});
+ }
+ });
zk.create("/0", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
zk.close();
qb.shutdownServers();
@@ -61,7 +63,8 @@ public class QuorumZxidSyncTest extends ZKTestCase {
ClientBase.waitForServerUp(qb.hostPort, 10000);
zk = new ZooKeeper(qb.hostPort, 10000, new Watcher() {
public void process(WatchedEvent event) {
- }});
+ }
+ });
zk.create("/1", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
zk.close();
qb.shutdownServers();
@@ -72,7 +75,8 @@ public class QuorumZxidSyncTest extends ZKTestCase {
ClientBase.waitForServerUp(qb.hostPort, 10000);
zk = new ZooKeeper(qb.hostPort, 10000, new Watcher() {
public void process(WatchedEvent event) {
- }});
+ }
+ });
zk.create("/2", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
zk.close();
qb.shutdownServers();
@@ -85,16 +89,15 @@ public class QuorumZxidSyncTest extends ZKTestCase {
qb.s2.start();
qb.s3.start();
qb.s4.start();
- Assert.assertTrue("Servers didn't come up", ClientBase.waitForServerUp(qb.hostPort, 10000));
+ assertTrue("Servers didn't come up", ClientBase.waitForServerUp(qb.hostPort, 10000));
qb.s5.start();
String hostPort = "127.0.0.1:" + qb.s5.getClientPort();
- Assert.assertFalse("Servers came up, but shouldn't have since it's ahead of leader",
- ClientBase.waitForServerUp(hostPort, 10000));
+ assertFalse("Servers came up, but shouldn't have since it's ahead of leader", ClientBase.waitForServerUp(hostPort, 10000));
}
private void cleanAndInitializeDataDir(File f) throws IOException {
File v = new File(f, "version-2");
- for(File c: v.listFiles()) {
+ for (File c : v.listFiles()) {
c.delete();
}
ClientBase.createInitializeFile(f);
@@ -111,7 +114,8 @@ public class QuorumZxidSyncTest extends ZKTestCase {
ClientBase.waitForServerUp(qb.hostPort, 10000);
ZooKeeper zk = new ZooKeeper(qb.hostPort, 10000, new Watcher() {
public void process(WatchedEvent event) {
- }});
+ }
+ });
zk.create("/0", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
zk.close();
qb.shutdownServers();
@@ -122,7 +126,8 @@ public class QuorumZxidSyncTest extends ZKTestCase {
ClientBase.waitForServerUp(qb.hostPort, 10000);
zk = new ZooKeeper(qb.hostPort, 10000, new Watcher() {
public void process(WatchedEvent event) {
- }});
+ }
+ });
zk.create("/1", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
zk.close();
qb.shutdownServers();
@@ -138,7 +143,8 @@ public class QuorumZxidSyncTest extends ZKTestCase {
ClientBase.waitForServerUp(qb.hostPort, 10000);
zk = new ZooKeeper(qb.hostPort, 10000, new Watcher() {
public void process(WatchedEvent event) {
- }});
+ }
+ });
zk.create("/2", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
zk.close();
qb.shutdownServers();
@@ -146,20 +152,21 @@ public class QuorumZxidSyncTest extends ZKTestCase {
ClientBase.waitForServerUp(qb.hostPort, 10000);
zk = new ZooKeeper(qb.hostPort, 10000, new Watcher() {
public void process(WatchedEvent event) {
- }});
+ }
+ });
boolean saw2 = false;
- for(String child: zk.getChildren("/", false)) {
+ for (String child : zk.getChildren("/", false)) {
if (child.equals("2")) {
saw2 = true;
}
}
zk.close();
- Assert.assertTrue("Didn't see /2 (went back in time)", saw2);
+ assertTrue("Didn't see /2 (went back in time)", saw2);
}
private void deleteLogs(File f) {
File v = new File(f, "version-2");
- for(File c: v.listFiles()) {
+ for (File c : v.listFiles()) {
if (c.getName().startsWith("log")) {
c.delete();
}
@@ -170,4 +177,5 @@ public class QuorumZxidSyncTest extends ZKTestCase {
public void tearDown() throws Exception {
qb.tearDown();
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/ReadOnlyModeTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/ReadOnlyModeTest.java
index 68c718240..0bef4c14a 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/ReadOnlyModeTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/ReadOnlyModeTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,14 +18,16 @@
package org.apache.zookeeper.test;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertSame;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
import java.io.ByteArrayOutputStream;
import java.io.LineNumberReader;
import java.io.StringReader;
-import java.util.ArrayList;
-import java.util.List;
import java.util.regex.Pattern;
-
-
import org.apache.log4j.Layout;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
@@ -34,9 +36,6 @@ import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.KeeperException.NotReadOnlyException;
import org.apache.zookeeper.Transaction;
-import org.apache.zookeeper.WatchedEvent;
-import org.apache.zookeeper.Watcher;
-import org.apache.zookeeper.Watcher.Event.KeeperState;
import org.apache.zookeeper.ZKTestCase;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;
@@ -44,14 +43,13 @@ import org.apache.zookeeper.ZooKeeper.States;
import org.apache.zookeeper.common.Time;
import org.apache.zookeeper.test.ClientBase.CountdownWatcher;
import org.junit.After;
-import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.LoggerFactory;
public class ReadOnlyModeTest extends ZKTestCase {
- private static final org.slf4j.Logger LOG = LoggerFactory
- .getLogger(ReadOnlyModeTest.class);
+
+ private static final org.slf4j.Logger LOG = LoggerFactory.getLogger(ReadOnlyModeTest.class);
private static int CONNECTION_TIMEOUT = QuorumBase.CONNECTION_TIMEOUT;
private QuorumUtil qu = new QuorumUtil(1);
@@ -73,42 +71,36 @@ public class ReadOnlyModeTest extends ZKTestCase {
@Test(timeout = 90000)
public void testMultiTransaction() throws Exception {
CountdownWatcher watcher = new CountdownWatcher();
- ZooKeeper zk = new ZooKeeper(qu.getConnString(), CONNECTION_TIMEOUT,
- watcher, true);
+ ZooKeeper zk = new ZooKeeper(qu.getConnString(), CONNECTION_TIMEOUT, watcher, true);
watcher.waitForConnected(CONNECTION_TIMEOUT); // ensure zk got connected
final String data = "Data to be read in RO mode";
final String node1 = "/tnode1";
final String node2 = "/tnode2";
- zk.create(node1, data.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk.create(node1, data.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
watcher.reset();
qu.shutdown(2);
watcher.waitForConnected(CONNECTION_TIMEOUT);
- Assert.assertEquals("Should be in r-o mode", States.CONNECTEDREADONLY,
- zk.getState());
+ assertEquals("Should be in r-o mode", States.CONNECTEDREADONLY, zk.getState());
// read operation during r/o mode
String remoteData = new String(zk.getData(node1, false, null));
- Assert.assertEquals("Failed to read data in r-o mode", data, remoteData);
+ assertEquals("Failed to read data in r-o mode", data, remoteData);
try {
Transaction transaction = zk.transaction();
transaction.setData(node1, "no way".getBytes(), -1);
- transaction.create(node2, data.getBytes(),
- ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
+ transaction.create(node2, data.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
transaction.commit();
- Assert.fail("Write operation using multi-transaction"
- + " api has succeeded during RO mode");
+ fail("Write operation using multi-transaction" + " api has succeeded during RO mode");
} catch (NotReadOnlyException e) {
// ok
}
- Assert.assertNull("Should have created the znode:" + node2,
- zk.exists(node2, false));
+ assertNull("Should have created the znode:" + node2, zk.exists(node2, false));
}
-
+
/**
* Basic test of read-only client functionality. Tries to read and write
* during read-only mode, then regains a quorum and tries to write again.
@@ -116,14 +108,12 @@ public class ReadOnlyModeTest extends ZKTestCase {
@Test(timeout = 90000)
public void testReadOnlyClient() throws Exception {
CountdownWatcher watcher = new CountdownWatcher();
- ZooKeeper zk = new ZooKeeper(qu.getConnString(), CONNECTION_TIMEOUT,
- watcher, true);
+ ZooKeeper zk = new ZooKeeper(qu.getConnString(), CONNECTION_TIMEOUT, watcher, true);
watcher.waitForConnected(CONNECTION_TIMEOUT); // ensure zk got connected
final String data = "Data to be read in RO mode";
final String node = "/tnode";
- zk.create(node, data.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk.create(node, data.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
watcher.reset();
qu.shutdown(2);
@@ -131,32 +121,31 @@ public class ReadOnlyModeTest extends ZKTestCase {
// Re-connect the client (in case we were connected to the shut down
// server and the local session was not persisted).
- zk = new ZooKeeper(qu.getConnString(), CONNECTION_TIMEOUT,
- watcher, true);
+ zk = new ZooKeeper(qu.getConnString(), CONNECTION_TIMEOUT, watcher, true);
watcher.waitForConnected(CONNECTION_TIMEOUT);
// read operation during r/o mode
String remoteData = new String(zk.getData(node, false, null));
- Assert.assertEquals(data, remoteData);
+ assertEquals(data, remoteData);
try {
zk.setData(node, "no way".getBytes(), -1);
- Assert.fail("Write operation has succeeded during RO mode");
+ fail("Write operation has succeeded during RO mode");
} catch (NotReadOnlyException e) {
// ok
}
watcher.reset();
qu.start(2);
- Assert.assertTrue("waiting for server up", ClientBase.waitForServerUp(
- "127.0.0.1:" + qu.getPeer(2).clientPort, CONNECTION_TIMEOUT));
+ assertTrue(
+ "waiting for server up",
+ ClientBase.waitForServerUp("127.0.0.1:" + qu.getPeer(2).clientPort, CONNECTION_TIMEOUT));
zk.close();
watcher.reset();
// Re-connect the client (in case we were connected to the shut down
// server and the local session was not persisted).
- zk = new ZooKeeper(qu.getConnString(), CONNECTION_TIMEOUT,
- watcher, true);
+ zk = new ZooKeeper(qu.getConnString(), CONNECTION_TIMEOUT, watcher, true);
watcher.waitForConnected(CONNECTION_TIMEOUT);
zk.setData(node, "We're in the quorum now".getBytes(), -1);
@@ -170,21 +159,19 @@ public class ReadOnlyModeTest extends ZKTestCase {
@Test(timeout = 90000)
public void testConnectionEvents() throws Exception {
CountdownWatcher watcher = new CountdownWatcher();
- ZooKeeper zk = new ZooKeeper(qu.getConnString(), CONNECTION_TIMEOUT,
- watcher, true);
+ ZooKeeper zk = new ZooKeeper(qu.getConnString(), CONNECTION_TIMEOUT, watcher, true);
boolean success = false;
for (int i = 0; i < 30; i++) {
try {
- zk.create("/test", "test".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
- success=true;
+ zk.create("/test", "test".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
+ success = true;
break;
- } catch(KeeperException.ConnectionLossException e) {
- Thread.sleep(1000);
- }
+ } catch (KeeperException.ConnectionLossException e) {
+ Thread.sleep(1000);
+ }
}
- Assert.assertTrue("Did not succeed in connecting in 30s", success);
- Assert.assertFalse("The connection should not be read-only yet", watcher.readOnlyConnected);
+ assertTrue("Did not succeed in connecting in 30s", success);
+ assertFalse("The connection should not be read-only yet", watcher.readOnlyConnected);
// kill peer and wait no more than 5 seconds for read-only server
// to be started (which should take one tickTime (2 seconds))
@@ -196,9 +183,8 @@ public class ReadOnlyModeTest extends ZKTestCase {
long start = Time.currentElapsedTime();
while (!(zk.getState() == States.CONNECTEDREADONLY)) {
Thread.sleep(200);
- // FIXME this was originally 5 seconds, but realistically, on random/slow/virt hosts, there is no way to guarantee this
- Assert.assertTrue("Can't connect to the server",
- Time.currentElapsedTime() - start < 30000);
+ // TODO this was originally 5 seconds, but realistically, on random/slow/virt hosts, there is no way to guarantee this
+ assertTrue("Can't connect to the server", Time.currentElapsedTime() - start < 30000);
}
watcher.waitForReadOnlyConnected(5000);
@@ -215,19 +201,17 @@ public class ReadOnlyModeTest extends ZKTestCase {
qu.shutdown(2);
CountdownWatcher watcher = new CountdownWatcher();
- ZooKeeper zk = new ZooKeeper(qu.getConnString(), CONNECTION_TIMEOUT,
- watcher, true);
+ ZooKeeper zk = new ZooKeeper(qu.getConnString(), CONNECTION_TIMEOUT, watcher, true);
watcher.waitForConnected(CONNECTION_TIMEOUT);
- Assert.assertSame("should be in r/o mode", States.CONNECTEDREADONLY, zk
- .getState());
+ assertSame("should be in r/o mode", States.CONNECTEDREADONLY, zk.getState());
long fakeId = zk.getSessionId();
- LOG.info("Connected as r/o mode with state {} and session id {}",
- zk.getState(), fakeId);
+ LOG.info("Connected as r/o mode with state {} and session id {}", zk.getState(), fakeId);
watcher.reset();
qu.start(2);
- Assert.assertTrue("waiting for server up", ClientBase.waitForServerUp(
- "127.0.0.1:" + qu.getPeer(2).clientPort, CONNECTION_TIMEOUT));
+ assertTrue(
+ "waiting for server up",
+ ClientBase.waitForServerUp("127.0.0.1:" + qu.getPeer(2).clientPort, CONNECTION_TIMEOUT));
LOG.info("Server 127.0.0.1:{} is up", qu.getPeer(2).clientPort);
// ZOOKEEPER-2722: wait until we can connect to a read-write server after the quorum
// is formed. Otherwise, it is possible that client first connects to a read-only server,
@@ -236,14 +220,10 @@ public class ReadOnlyModeTest extends ZKTestCase {
// server. If we happen to execute the zk.create after the read-only server is shutdown and
// before the quorum is formed, we will get a ConnectLossException.
watcher.waitForSyncConnected(CONNECTION_TIMEOUT);
- Assert.assertEquals("Should be in read-write mode", States.CONNECTED,
- zk.getState());
- LOG.info("Connected as rw mode with state {} and session id {}",
- zk.getState(), zk.getSessionId());
- zk.create("/test", "test".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
- Assert.assertFalse("fake session and real session have same id", zk
- .getSessionId() == fakeId);
+ assertEquals("Should be in read-write mode", States.CONNECTED, zk.getState());
+ LOG.info("Connected as rw mode with state {} and session id {}", zk.getState(), zk.getSessionId());
+ zk.create("/test", "test".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
+ assertFalse("fake session and real session have same id", zk.getSessionId() == fakeId);
zk.close();
}
@@ -255,8 +235,7 @@ public class ReadOnlyModeTest extends ZKTestCase {
@Test(timeout = 90000)
public void testSeekForRwServer() throws Exception {
// setup the logger to capture all logs
- Layout layout = Logger.getRootLogger().getAppender("CONSOLE")
- .getLayout();
+ Layout layout = Logger.getRootLogger().getAppender("CONSOLE").getLayout();
ByteArrayOutputStream os = new ByteArrayOutputStream();
WriterAppender appender = new WriterAppender(layout, os);
appender.setImmediateFlush(true);
@@ -267,8 +246,7 @@ public class ReadOnlyModeTest extends ZKTestCase {
try {
qu.shutdown(2);
CountdownWatcher watcher = new CountdownWatcher();
- ZooKeeper zk = new ZooKeeper(qu.getConnString(),
- CONNECTION_TIMEOUT, watcher, true);
+ ZooKeeper zk = new ZooKeeper(qu.getConnString(), CONNECTION_TIMEOUT, watcher, true);
watcher.waitForConnected(CONNECTION_TIMEOUT);
// if we don't suspend a peer it will rejoin a quorum
@@ -281,8 +259,7 @@ public class ReadOnlyModeTest extends ZKTestCase {
qu.start(3);
ClientBase.waitForServerUp(qu.getConnString(), 2000);
watcher.waitForConnected(CONNECTION_TIMEOUT);
- zk.create("/test", "test".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk.create("/test", "test".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
// resume poor fellow
qu.getPeer(1).peer.resume();
@@ -291,8 +268,7 @@ public class ReadOnlyModeTest extends ZKTestCase {
}
os.close();
- LineNumberReader r = new LineNumberReader(new StringReader(os
- .toString()));
+ LineNumberReader r = new LineNumberReader(new StringReader(os.toString()));
String line;
Pattern p = Pattern.compile(".*Majority server found.*");
boolean found = false;
@@ -302,8 +278,7 @@ public class ReadOnlyModeTest extends ZKTestCase {
break;
}
}
- Assert.assertTrue(
- "Majority server wasn't found while connected to r/o server",
- found);
+ assertTrue("Majority server wasn't found while connected to r/o server", found);
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/ReconfigExceptionTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/ReconfigExceptionTest.java
index 5eda4b0f4..0c40c0f25 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/ReconfigExceptionTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/ReconfigExceptionTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,31 +18,31 @@
package org.apache.zookeeper.test;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeoutException;
-
-import org.apache.zookeeper.ZKTestCase;
import org.apache.zookeeper.KeeperException;
-import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.PortAssignment;
+import org.apache.zookeeper.ZKTestCase;
+import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.admin.ZooKeeperAdmin;
import org.apache.zookeeper.data.ACL;
import org.apache.zookeeper.data.Id;
import org.apache.zookeeper.data.Stat;
import org.apache.zookeeper.server.quorum.QuorumPeerConfig;
import org.junit.After;
-import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ReconfigExceptionTest extends ZKTestCase {
- private static final Logger LOG = LoggerFactory
- .getLogger(ReconfigExceptionTest.class);
+
+ private static final Logger LOG = LoggerFactory.getLogger(ReconfigExceptionTest.class);
private static String authProvider = "zookeeper.DigestAuthenticationProvider.superDigest";
// Use DigestAuthenticationProvider.base64Encode or
// run ZooKeeper jar with org.apache.zookeeper.server.auth.DigestAuthenticationProvider to generate password.
@@ -66,7 +66,7 @@ public class ReconfigExceptionTest extends ZKTestCase {
try {
qu.startAll();
} catch (IOException e) {
- Assert.fail("Fail to start quorum servers.");
+ fail("Fail to start quorum servers.");
}
resetZKAdmin();
@@ -92,9 +92,9 @@ public class ReconfigExceptionTest extends ZKTestCase {
QuorumPeerConfig.setReconfigEnabled(false);
try {
reconfigPort();
- Assert.fail("Reconfig should be disabled.");
+ fail("Reconfig should be disabled.");
} catch (KeeperException e) {
- Assert.assertTrue(e.code() == KeeperException.Code.RECONFIGDISABLED);
+ assertTrue(e.code() == KeeperException.Code.RECONFIGDISABLED);
}
}
@@ -102,10 +102,10 @@ public class ReconfigExceptionTest extends ZKTestCase {
public void testReconfigFailWithoutAuth() throws InterruptedException {
try {
reconfigPort();
- Assert.fail("Reconfig should fail without auth.");
+ fail("Reconfig should fail without auth.");
} catch (KeeperException e) {
// However a failure is still expected as user is not authenticated, so ACL check will fail.
- Assert.assertTrue(e.code() == KeeperException.Code.NOAUTH);
+ assertTrue(e.code() == KeeperException.Code.NOAUTH);
}
}
@@ -113,9 +113,9 @@ public class ReconfigExceptionTest extends ZKTestCase {
public void testReconfigEnabledWithSuperUser() throws InterruptedException {
try {
zkAdmin.addAuthInfo("digest", "super:test".getBytes());
- Assert.assertTrue(reconfigPort());
+ assertTrue(reconfigPort());
} catch (KeeperException e) {
- Assert.fail("Reconfig should not fail, but failed with exception : " + e.getMessage());
+ fail("Reconfig should not fail, but failed with exception : " + e.getMessage());
}
}
@@ -126,10 +126,10 @@ public class ReconfigExceptionTest extends ZKTestCase {
try {
zkAdmin.addAuthInfo("digest", "user:test".getBytes());
reconfigPort();
- Assert.fail("Reconfig should fail without a valid ACL associated with user.");
+ fail("Reconfig should fail without a valid ACL associated with user.");
} catch (KeeperException e) {
// Again failure is expected because no ACL is associated with this user.
- Assert.assertTrue(e.code() == KeeperException.Code.NOAUTH);
+ assertTrue(e.code() == KeeperException.Code.NOAUTH);
}
}
@@ -140,17 +140,14 @@ public class ReconfigExceptionTest extends ZKTestCase {
try {
zkAdmin.addAuthInfo("digest", "super:test".getBytes());
// There is ACL however the permission is wrong - need WRITE permission at leaste.
- ArrayList<ACL> acls = new ArrayList<ACL>(
- Collections.singletonList(
- new ACL(ZooDefs.Perms.READ,
- new Id("digest", "user:tl+z3z0vO6PfPfEENfLF96E6pM0="/* password is test */))));
+ ArrayList<ACL> acls = new ArrayList<ACL>(Collections.singletonList(new ACL(ZooDefs.Perms.READ, new Id("digest", "user:tl+z3z0vO6PfPfEENfLF96E6pM0="/* password is test */))));
zkAdmin.setACL(ZooDefs.CONFIG_NODE, acls, -1);
resetZKAdmin();
zkAdmin.addAuthInfo("digest", "user:test".getBytes());
reconfigPort();
- Assert.fail("Reconfig should fail with an ACL that is read only!");
+ fail("Reconfig should fail with an ACL that is read only!");
} catch (KeeperException e) {
- Assert.assertTrue(e.code() == KeeperException.Code.NOAUTH);
+ assertTrue(e.code() == KeeperException.Code.NOAUTH);
}
}
@@ -160,16 +157,13 @@ public class ReconfigExceptionTest extends ZKTestCase {
try {
zkAdmin.addAuthInfo("digest", "super:test".getBytes());
- ArrayList<ACL> acls = new ArrayList<ACL>(
- Collections.singletonList(
- new ACL(ZooDefs.Perms.WRITE,
- new Id("digest", "user:tl+z3z0vO6PfPfEENfLF96E6pM0="/* password is test */))));
+ ArrayList<ACL> acls = new ArrayList<ACL>(Collections.singletonList(new ACL(ZooDefs.Perms.WRITE, new Id("digest", "user:tl+z3z0vO6PfPfEENfLF96E6pM0="/* password is test */))));
zkAdmin.setACL(ZooDefs.CONFIG_NODE, acls, -1);
resetZKAdmin();
zkAdmin.addAuthInfo("digest", "user:test".getBytes());
- Assert.assertTrue(reconfigPort());
+ assertTrue(reconfigPort());
} catch (KeeperException e) {
- Assert.fail("Reconfig should not fail, but failed with exception : " + e.getMessage());
+ fail("Reconfig should not fail, but failed with exception : " + e.getMessage());
}
}
@@ -183,31 +177,34 @@ public class ReconfigExceptionTest extends ZKTestCase {
if (zkAdmin != null) {
zkAdmin.close();
}
- zkAdmin = new ZooKeeperAdmin(cnxString,
- ClientBase.CONNECTION_TIMEOUT, watcher);
+ zkAdmin = new ZooKeeperAdmin(cnxString, ClientBase.CONNECTION_TIMEOUT, watcher);
} catch (IOException e) {
- Assert.fail("Fail to create ZooKeeperAdmin handle.");
+ fail("Fail to create ZooKeeperAdmin handle.");
return;
}
try {
watcher.waitForConnected(ClientBase.CONNECTION_TIMEOUT);
} catch (InterruptedException | TimeoutException e) {
- Assert.fail("ZooKeeper admin client can not connect to " + cnxString);
+ fail("ZooKeeper admin client can not connect to " + cnxString);
}
}
private boolean reconfigPort() throws KeeperException, InterruptedException {
List<String> joiningServers = new ArrayList<String>();
int leaderId = 1;
- while (qu.getPeer(leaderId).peer.leader == null)
+ while (qu.getPeer(leaderId).peer.leader == null) {
leaderId++;
+ }
int followerId = leaderId == 1 ? 2 : 1;
joiningServers.add("server." + followerId + "=localhost:"
- + qu.getPeer(followerId).peer.getQuorumAddress().getPort() /*quorum port*/
- + ":" + qu.getPeer(followerId).peer.getElectionAddress().getPort() /*election port*/
- + ":participant;localhost:" + PortAssignment.unique()/* new client port */);
+ + qu.getPeer(followerId).peer.getQuorumAddress().getPort() /*quorum port*/
+ + ":"
+ + qu.getPeer(followerId).peer.getElectionAddress().getPort() /*election port*/
+ + ":participant;localhost:"
+ + PortAssignment.unique()/* new client port */);
zkAdmin.reconfigure(joiningServers, null, null, -1, new Stat());
return true;
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/ReconfigMisconfigTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/ReconfigMisconfigTest.java
index 219981e10..fa4e547f9 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/ReconfigMisconfigTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/ReconfigMisconfigTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,30 +18,31 @@
package org.apache.zookeeper.test;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeoutException;
-
-import org.apache.zookeeper.ZKTestCase;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.PortAssignment;
+import org.apache.zookeeper.ZKTestCase;
import org.apache.zookeeper.admin.ZooKeeperAdmin;
import org.apache.zookeeper.data.Stat;
import org.apache.zookeeper.server.quorum.QuorumPeerConfig;
import org.junit.After;
-import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ReconfigMisconfigTest extends ZKTestCase {
+
private static final Logger LOG = LoggerFactory.getLogger(ReconfigMisconfigTest.class);
private QuorumUtil qu;
private ZooKeeperAdmin zkAdmin;
- private static String errorMsg = "Reconfig should fail without configuring the super " +
- "user's password on server side first.";
+ private static String errorMsg = "Reconfig should fail without configuring the super "
+ + "user's password on server side first.";
@Before
public void setup() throws InterruptedException {
@@ -52,7 +53,7 @@ public class ReconfigMisconfigTest extends ZKTestCase {
try {
qu.startAll();
} catch (IOException e) {
- Assert.fail("Fail to start quorum servers.");
+ fail("Fail to start quorum servers.");
}
instantiateZKAdmin();
@@ -79,17 +80,17 @@ public class ReconfigMisconfigTest extends ZKTestCase {
// zookeeper.DigestAuthenticationProvider.superDigest.
try {
reconfigPort();
- Assert.fail(errorMsg);
+ fail(errorMsg);
} catch (KeeperException e) {
- Assert.assertTrue(e.code() == KeeperException.Code.NOAUTH);
+ assertTrue(e.code() == KeeperException.Code.NOAUTH);
}
try {
zkAdmin.addAuthInfo("digest", "super:".getBytes());
reconfigPort();
- Assert.fail(errorMsg);
+ fail(errorMsg);
} catch (KeeperException e) {
- Assert.assertTrue(e.code() == KeeperException.Code.NOAUTH);
+ assertTrue(e.code() == KeeperException.Code.NOAUTH);
}
}
@@ -98,32 +99,36 @@ public class ReconfigMisconfigTest extends ZKTestCase {
ClientBase.CountdownWatcher watcher = new ClientBase.CountdownWatcher();
try {
cnxString = "127.0.0.1:" + qu.getPeer(1).peer.getClientPort();
- zkAdmin = new ZooKeeperAdmin(cnxString,
- ClientBase.CONNECTION_TIMEOUT, watcher);
+ zkAdmin = new ZooKeeperAdmin(cnxString, ClientBase.CONNECTION_TIMEOUT, watcher);
} catch (IOException e) {
- Assert.fail("Fail to create ZooKeeperAdmin handle.");
+ fail("Fail to create ZooKeeperAdmin handle.");
return;
}
try {
watcher.waitForConnected(ClientBase.CONNECTION_TIMEOUT);
} catch (InterruptedException | TimeoutException e) {
- Assert.fail("ZooKeeper admin client can not connect to " + cnxString);
+ fail("ZooKeeper admin client can not connect to " + cnxString);
}
}
private boolean reconfigPort() throws KeeperException, InterruptedException {
List<String> joiningServers = new ArrayList<String>();
int leaderId = 1;
- while (qu.getPeer(leaderId).peer.leader == null)
+ while (qu.getPeer(leaderId).peer.leader == null) {
leaderId++;
+ }
int followerId = leaderId == 1 ? 2 : 1;
- joiningServers.add("server." + followerId + "=localhost:"
- + qu.getPeer(followerId).peer.getQuorumAddress().getPort() /*quorum port*/
- + ":" + qu.getPeer(followerId).peer.getElectionAddress().getPort() /*election port*/
- + ":participant;localhost:" + PortAssignment.unique()/* new client port */);
+ joiningServers.add("server." + followerId
+ + "=localhost:"
+ + qu.getPeer(followerId).peer.getQuorumAddress().getPort() /*quorum port*/
+ + ":"
+ + qu.getPeer(followerId).peer.getElectionAddress().getPort() /*election port*/
+ + ":participant;localhost:"
+ + PortAssignment.unique()/* new client port */);
zkAdmin.reconfigure(joiningServers, null, null, -1, new Stat());
return true;
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/ReconfigTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/ReconfigTest.java
index 39da2eb20..d3cb1ac0f 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/ReconfigTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/ReconfigTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -19,7 +19,10 @@
package org.apache.zookeeper.test;
import static java.net.InetAddress.getLoopbackAddress;
-
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
@@ -28,10 +31,16 @@ import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
-
+import org.apache.zookeeper.AsyncCallback.DataCallback;
+import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
+import org.apache.zookeeper.PortAssignment;
+import org.apache.zookeeper.WatchedEvent;
+import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZKTestCase;
-import org.apache.zookeeper.AsyncCallback.DataCallback;
+import org.apache.zookeeper.ZooDefs;
+import org.apache.zookeeper.ZooKeeper;
+import org.apache.zookeeper.admin.ZooKeeperAdmin;
import org.apache.zookeeper.data.Stat;
import org.apache.zookeeper.jmx.MBeanRegistry;
import org.apache.zookeeper.server.quorum.QuorumPeer;
@@ -41,23 +50,15 @@ import org.apache.zookeeper.server.quorum.QuorumPeerConfig;
import org.apache.zookeeper.server.quorum.flexible.QuorumHierarchical;
import org.apache.zookeeper.server.quorum.flexible.QuorumMaj;
import org.apache.zookeeper.server.quorum.flexible.QuorumVerifier;
-import org.apache.zookeeper.ZooKeeper;
-import org.apache.zookeeper.admin.ZooKeeperAdmin;
-import org.apache.zookeeper.Watcher;
-import org.apache.zookeeper.WatchedEvent;
-import org.apache.zookeeper.ZooDefs;
-import org.apache.zookeeper.CreateMode;
-import org.apache.zookeeper.PortAssignment;
import org.junit.After;
-import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-public class ReconfigTest extends ZKTestCase implements DataCallback{
- private static final Logger LOG = LoggerFactory
- .getLogger(ReconfigTest.class);
+public class ReconfigTest extends ZKTestCase implements DataCallback {
+
+ private static final Logger LOG = LoggerFactory.getLogger(ReconfigTest.class);
private QuorumUtil qu;
private ZooKeeper[] zkArr;
@@ -65,8 +66,7 @@ public class ReconfigTest extends ZKTestCase implements DataCallback{
@Before
public void setup() {
- System.setProperty("zookeeper.DigestAuthenticationProvider.superDigest",
- "super:D/InIHSb7yEEbrWz8b9l71RjZJU="/* password is 'test'*/);
+ System.setProperty("zookeeper.DigestAuthenticationProvider.superDigest", "super:D/InIHSb7yEEbrWz8b9l71RjZJU="/* password is 'test'*/);
QuorumPeerConfig.setReconfigEnabled(true);
}
@@ -78,15 +78,17 @@ public class ReconfigTest extends ZKTestCase implements DataCallback{
}
}
- public static String reconfig(ZooKeeperAdmin zkAdmin, List<String> joiningServers,
- List<String> leavingServers, List<String> newMembers, long fromConfig)
- throws KeeperException, InterruptedException {
+ public static String reconfig(
+ ZooKeeperAdmin zkAdmin,
+ List<String> joiningServers,
+ List<String> leavingServers,
+ List<String> newMembers,
+ long fromConfig) throws KeeperException, InterruptedException {
byte[] config = null;
String failure = null;
for (int j = 0; j < 30; j++) {
try {
- config = zkAdmin.reconfigure(joiningServers, leavingServers,
- newMembers, fromConfig, new Stat());
+ config = zkAdmin.reconfigure(joiningServers, leavingServers, newMembers, fromConfig, new Stat());
failure = null;
break;
} catch (KeeperException.ConnectionLossException e) {
@@ -97,25 +99,28 @@ public class ReconfigTest extends ZKTestCase implements DataCallback{
Thread.sleep(1000);
}
if (failure != null) {
- Assert.fail(failure);
+ fail(failure);
}
String configStr = new String(config);
if (joiningServers != null) {
- for (String joiner : joiningServers)
- Assert.assertTrue(configStr.contains(joiner));
+ for (String joiner : joiningServers) {
+ assertTrue(configStr.contains(joiner));
+ }
}
if (leavingServers != null) {
- for (String leaving : leavingServers)
- Assert.assertFalse(configStr.contains("server.".concat(leaving)));
+ for (String leaving : leavingServers) {
+ assertFalse(configStr.contains("server.".concat(leaving)));
+ }
}
return configStr;
}
- public static String testServerHasConfig(ZooKeeper zk,
- List<String> joiningServers, List<String> leavingServers)
- throws KeeperException, InterruptedException {
+ public static String testServerHasConfig(
+ ZooKeeper zk,
+ List<String> joiningServers,
+ List<String> leavingServers) throws KeeperException, InterruptedException {
boolean testNodeExists = false;
byte[] config = null;
for (int j = 0; j < 30; j++) {
@@ -135,7 +140,7 @@ public class ReconfigTest extends ZKTestCase implements DataCallback{
} else {
// test fails if we still can't connect to the quorum after
// 30 seconds.
- Assert.fail("client could not connect to reestablished quorum: giving up after 30+ seconds.");
+ fail("client could not connect to reestablished quorum: giving up after 30+ seconds.");
}
}
}
@@ -143,19 +148,21 @@ public class ReconfigTest extends ZKTestCase implements DataCallback{
String configStr = new String(config);
if (joiningServers != null) {
for (String joiner : joiningServers) {
- Assert.assertTrue(configStr.contains(joiner));
+ assertTrue(configStr.contains(joiner));
}
}
if (leavingServers != null) {
- for (String leaving : leavingServers)
- Assert.assertFalse(configStr.contains("server.".concat(leaving)));
+ for (String leaving : leavingServers) {
+ assertFalse(configStr.contains("server.".concat(leaving)));
+ }
}
return configStr;
}
- public static void testNormalOperation(ZooKeeper writer, ZooKeeper reader)
- throws KeeperException, InterruptedException {
+ public static void testNormalOperation(
+ ZooKeeper writer,
+ ZooKeeper reader) throws KeeperException, InterruptedException {
boolean testReaderNodeExists = false;
boolean testWriterNodeExists = false;
@@ -177,7 +184,7 @@ public class ReconfigTest extends ZKTestCase implements DataCallback{
// Check ZOOKEEPER-2137 for details.
reader.setData("/dummy", "dummy".getBytes(), -1);
byte[] res = reader.getData("/test", null, new Stat());
- Assert.assertEquals(data, new String(res));
+ assertEquals(data, new String(res));
break;
} catch (KeeperException.ConnectionLossException e) {
if (j < 29) {
@@ -185,25 +192,27 @@ public class ReconfigTest extends ZKTestCase implements DataCallback{
} else {
// test fails if we still can't connect to the quorum after
// 30 seconds.
- Assert.fail("client could not connect to reestablished quorum: giving up after 30+ seconds.");
+ fail("client could not connect to reestablished quorum: giving up after 30+ seconds.");
}
}
}
}
- private static void createZNode(ZooKeeper zk, String path, String data)
- throws KeeperException, InterruptedException {
- try{
- zk.create(path, data.getBytes(),
- ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
+ private static void createZNode(
+ ZooKeeper zk,
+ String path,
+ String data) throws KeeperException, InterruptedException {
+ try {
+ zk.create(path, data.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
} catch (KeeperException.NodeExistsException e) {
}
}
-
+
private int getLeaderId(QuorumUtil qu) {
int leaderId = 1;
- while (qu.getPeer(leaderId).peer.leader == null)
+ while (qu.getPeer(leaderId).peer.leader == null) {
leaderId++;
+ }
return leaderId;
}
@@ -214,11 +223,13 @@ public class ReconfigTest extends ZKTestCase implements DataCallback{
zkArr[0] = null; // not used.
for (int i = 1; i <= qu.ALL; i++) {
// server ids are 1, 2 and 3
- zkArr[i] = new ZooKeeper("127.0.0.1:"
- + qu.getPeer(i).peer.getClientPort(),
- ClientBase.CONNECTION_TIMEOUT, new Watcher() {
+ zkArr[i] = new ZooKeeper(
+ "127.0.0.1:" + qu.getPeer(i).peer.getClientPort(),
+ ClientBase.CONNECTION_TIMEOUT,
+ new Watcher() {
public void process(WatchedEvent event) {
- }});
+ }
+ });
}
return zkArr;
}
@@ -230,11 +241,13 @@ public class ReconfigTest extends ZKTestCase implements DataCallback{
zkAdminArr[0] = null; // not used.
for (int i = 1; i <= qu.ALL; i++) {
// server ids are 1, 2 and 3
- zkAdminArr[i] = new ZooKeeperAdmin("127.0.0.1:"
- + qu.getPeer(i).peer.getClientPort(),
- ClientBase.CONNECTION_TIMEOUT, new Watcher() {
- public void process(WatchedEvent event) {
- }});
+ zkAdminArr[i] = new ZooKeeperAdmin(
+ "127.0.0.1:" + qu.getPeer(i).peer.getClientPort(),
+ ClientBase.CONNECTION_TIMEOUT,
+ new Watcher() {
+ public void process(WatchedEvent event) {
+ }
+ });
zkAdminArr[i].addAuthInfo("digest", "super:test".getBytes());
}
@@ -243,14 +256,18 @@ public class ReconfigTest extends ZKTestCase implements DataCallback{
public static void closeAllHandles(ZooKeeper[] zkArr, ZooKeeperAdmin[] zkAdminArr) throws InterruptedException {
if (zkArr != null) {
- for (ZooKeeper zk : zkArr)
- if (zk != null)
+ for (ZooKeeper zk : zkArr) {
+ if (zk != null) {
zk.close();
+ }
+ }
}
if (zkAdminArr != null) {
- for (ZooKeeperAdmin zkAdmin : zkAdminArr)
- if (zkAdmin != null)
+ for (ZooKeeperAdmin zkAdmin : zkAdminArr) {
+ if (zkAdmin != null) {
zkAdmin.close();
+ }
+ }
}
}
@@ -278,27 +295,25 @@ public class ReconfigTest extends ZKTestCase implements DataCallback{
// server.
// when we're removing the leader, zk1 will be the client connected
// to removed server
- ZooKeeper zk1 = (leavingIndex == leaderIndex) ? zkArr[leaderIndex]
- : zkArr[(leaderIndex % qu.ALL) + 1];
- ZooKeeper zk2 = (leavingIndex == leaderIndex) ? zkArr[(leaderIndex % qu.ALL) + 1]
- : zkArr[leaderIndex];
- ZooKeeperAdmin zkAdmin1 = (leavingIndex == leaderIndex) ? zkAdminArr[leaderIndex]
- : zkAdminArr[(leaderIndex % qu.ALL) + 1];
- ZooKeeperAdmin zkAdmin2 = (leavingIndex == leaderIndex) ? zkAdminArr[(leaderIndex % qu.ALL) + 1]
- : zkAdminArr[leaderIndex];
+ ZooKeeper zk1 = (leavingIndex == leaderIndex) ? zkArr[leaderIndex] : zkArr[(leaderIndex % qu.ALL) + 1];
+ ZooKeeper zk2 = (leavingIndex == leaderIndex) ? zkArr[(leaderIndex % qu.ALL) + 1] : zkArr[leaderIndex];
+ ZooKeeperAdmin zkAdmin1 = (leavingIndex == leaderIndex)
+ ? zkAdminArr[leaderIndex]
+ : zkAdminArr[(leaderIndex % qu.ALL) + 1];
+ ZooKeeperAdmin zkAdmin2 = (leavingIndex == leaderIndex)
+ ? zkAdminArr[(leaderIndex % qu.ALL) + 1]
+ : zkAdminArr[leaderIndex];
leavingServers.add(Integer.toString(leavingIndex));
// remember this server so we can add it back later
- joiningServers.add("server."
- + leavingIndex
- + "=localhost:"
- + qu.getPeer(leavingIndex).peer.getQuorumAddress()
- .getPort()
- + ":"
- + qu.getPeer(leavingIndex).peer.getElectionAddress()
- .getPort() + ":participant;localhost:"
- + qu.getPeer(leavingIndex).peer.getClientPort());
+ joiningServers.add("server." + leavingIndex
+ + "=localhost:"
+ + qu.getPeer(leavingIndex).peer.getQuorumAddress().getPort()
+ + ":"
+ + qu.getPeer(leavingIndex).peer.getElectionAddress().getPort()
+ + ":participant;localhost:"
+ + qu.getPeer(leavingIndex).peer.getClientPort());
String configStr = reconfig(zkAdmin1, null, leavingServers, null, -1);
testServerHasConfig(zk2, null, leavingServers);
@@ -310,7 +325,7 @@ public class ReconfigTest extends ZKTestCase implements DataCallback{
// checks that conditioning on version works properly
try {
reconfig(zkAdmin2, joiningServers, null, null, version + 1);
- Assert.fail("reconfig succeeded even though version condition was incorrect!");
+ fail("reconfig succeeded even though version condition was incorrect!");
} catch (KeeperException.BadVersionException e) {
}
@@ -353,43 +368,50 @@ public class ReconfigTest extends ZKTestCase implements DataCallback{
// find some server that's staying
int stayingIndex1 = 1, stayingIndex2 = 1, stayingIndex3 = 1;
- while (stayingIndex1 == leavingIndex1 || stayingIndex1 == leavingIndex2)
+ while (stayingIndex1 == leavingIndex1 || stayingIndex1 == leavingIndex2) {
stayingIndex1++;
+ }
- while (stayingIndex2 == leavingIndex1 || stayingIndex2 == leavingIndex2
- || stayingIndex2 == stayingIndex1)
+ while (stayingIndex2 == leavingIndex1 || stayingIndex2 == leavingIndex2 || stayingIndex2 == stayingIndex1) {
stayingIndex2++;
+ }
- while (stayingIndex3 == leavingIndex1 || stayingIndex3 == leavingIndex2
- || stayingIndex3 == stayingIndex1
- || stayingIndex3 == stayingIndex2)
+ while (stayingIndex3 == leavingIndex1
+ || stayingIndex3 == leavingIndex2
+ || stayingIndex3 == stayingIndex1
+ || stayingIndex3 == stayingIndex2) {
stayingIndex3++;
+ }
leavingServers.add(Integer.toString(leavingIndex1));
leavingServers.add(Integer.toString(leavingIndex2));
// remember these servers so we can add them back later
- joiningServers.add("server." + leavingIndex1 + "=localhost:"
- + qu.getPeer(leavingIndex1).peer.getQuorumAddress().getPort()
- + ":"
- + qu.getPeer(leavingIndex1).peer.getElectionAddress().getPort()
- + ":participant;localhost:"
- + qu.getPeer(leavingIndex1).peer.getClientPort());
+ joiningServers.add("server."
+ + leavingIndex1
+ + "=localhost:"
+ + qu.getPeer(leavingIndex1).peer.getQuorumAddress().getPort()
+ + ":"
+ + qu.getPeer(leavingIndex1).peer.getElectionAddress().getPort()
+ + ":participant;localhost:"
+ + qu.getPeer(leavingIndex1).peer.getClientPort());
// this server will be added back as an observer
- joiningServers.add("server." + leavingIndex2 + "=localhost:"
- + qu.getPeer(leavingIndex2).peer.getQuorumAddress().getPort()
- + ":"
- + qu.getPeer(leavingIndex2).peer.getElectionAddress().getPort()
- + ":observer;localhost:"
- + qu.getPeer(leavingIndex2).peer.getClientPort());
+ joiningServers.add("server."
+ + leavingIndex2
+ + "=localhost:"
+ + qu.getPeer(leavingIndex2).peer.getQuorumAddress().getPort()
+ + ":"
+ + qu.getPeer(leavingIndex2).peer.getElectionAddress().getPort()
+ + ":observer;localhost:"
+ + qu.getPeer(leavingIndex2).peer.getClientPort());
qu.shutdown(leavingIndex1);
qu.shutdown(leavingIndex2);
// 3 servers still up so this should work
reconfig(zkAdminArr[stayingIndex2], null, leavingServers, null, -1);
-
+
qu.shutdown(stayingIndex2);
// the following commands would not work in the original
@@ -399,22 +421,22 @@ public class ReconfigTest extends ZKTestCase implements DataCallback{
testServerHasConfig(zkArr[stayingIndex1], null, leavingServers);
testServerHasConfig(zkArr[stayingIndex3], null, leavingServers);
testNormalOperation(zkArr[stayingIndex1], zkArr[stayingIndex3]);
-
+
// this is a test that a reconfig will only succeed
// if there is a quorum up in new config. Below there is no
// quorum so it should fail
-
+
// the sleep is necessary so that the leader figures out
// that the switched off servers are down
Thread.sleep(10000);
try {
reconfig(zkAdminArr[stayingIndex1], joiningServers, null, null, -1);
- Assert.fail("reconfig completed successfully even though there is no quorum up in new config!");
+ fail("reconfig completed successfully even though there is no quorum up in new config!");
} catch (KeeperException.NewConfigNoQuorum e) {
}
-
+
// now start the third server so that new config has quorum
qu.restart(stayingIndex2);
@@ -427,7 +449,7 @@ public class ReconfigTest extends ZKTestCase implements DataCallback{
// about the change and becomes an observer.
qu.restart(leavingIndex2);
- Assert.assertTrue(qu.getPeer(leavingIndex2).peer.getPeerState() == ServerState.OBSERVING);
+ assertTrue(qu.getPeer(leavingIndex2).peer.getPeerState() == ServerState.OBSERVING);
testNormalOperation(zkArr[stayingIndex2], zkArr[leavingIndex2]);
testServerHasConfig(zkArr[leavingIndex2], joiningServers, null);
}
@@ -445,69 +467,67 @@ public class ReconfigTest extends ZKTestCase implements DataCallback{
ArrayList<String> newServers = new ArrayList<String>();
for (int i = 1; i <= 5; i++) {
String server = "server." + i + "=localhost:" + PortAssignment.unique()
- + ":" + PortAssignment.unique() + ":"
- + ((i == 4 || i == 5) ? "observer" : "participant")
- + ";localhost:" + qu.getPeer(i).peer.getClientPort();
+ + ":" + PortAssignment.unique() + ":" + ((i == 4 || i == 5) ? "observer" : "participant")
+ + ";localhost:" + qu.getPeer(i).peer.getClientPort();
newServers.add(server);
}
qu.shutdown(3);
qu.shutdown(6);
qu.shutdown(7);
-
+
reconfig(zkAdminArr[1], null, null, newServers, -1);
testNormalOperation(zkArr[1], zkArr[2]);
-
+
testServerHasConfig(zkArr[1], newServers, null);
testServerHasConfig(zkArr[2], newServers, null);
testServerHasConfig(zkArr[4], newServers, null);
testServerHasConfig(zkArr[5], newServers, null);
-
+
qu.shutdown(5);
qu.shutdown(4);
-
+
testNormalOperation(zkArr[1], zkArr[2]);
}
@Test
public void testRemoveOneAsynchronous() throws Exception {
- qu = new QuorumUtil(2);
+ qu = new QuorumUtil(2);
qu.disableJMXTest = true;
qu.startAll();
zkArr = createHandles(qu);
zkAdminArr = createAdminHandles(qu);
List<String> leavingServers = new ArrayList<String>();
-
+
// lets remove someone who's not the leader
- leavingServers.add(getLeaderId(qu) == 5 ? "4": "5");
-
+ leavingServers.add(getLeaderId(qu) == 5 ? "4" : "5");
+
List<Integer> results = new LinkedList<Integer>();
-
+
zkAdminArr[1].reconfigure(null, leavingServers, null, -1, this, results);
-
+
synchronized (results) {
while (results.size() < 1) {
- results.wait();
+ results.wait();
}
- }
- Assert.assertEquals(0, (int) results.get(0));
-
- testNormalOperation(zkArr[1], zkArr[2]);
- for (int i=1; i<=5; i++)
+ }
+ assertEquals(0, (int) results.get(0));
+
+ testNormalOperation(zkArr[1], zkArr[2]);
+ for (int i = 1; i <= 5; i++) {
testServerHasConfig(zkArr[i], null, leavingServers);
+ }
}
@SuppressWarnings("unchecked")
- public void processResult(int rc, String path, Object ctx, byte[] data,
- Stat stat) {
- synchronized(ctx) {
- ((LinkedList<Integer>)ctx).add(rc);
+ public void processResult(int rc, String path, Object ctx, byte[] data, Stat stat) {
+ synchronized (ctx) {
+ ((LinkedList<Integer>) ctx).add(rc);
ctx.notifyAll();
}
}
-
-
+
@Test
public void testRoleChange() throws Exception {
qu = new QuorumUtil(1); // create 3 servers
@@ -539,36 +559,37 @@ public class ReconfigTest extends ZKTestCase implements DataCallback{
// server.
// when we're removing the leader, zk1 will be the client connected
// to removed server
- ZooKeeper zk1 = (changingIndex == leaderIndex) ? zkArr[leaderIndex]
- : zkArr[(leaderIndex % qu.ALL) + 1];
- ZooKeeperAdmin zkAdmin1 = (changingIndex == leaderIndex) ? zkAdminArr[leaderIndex]
- : zkAdminArr[(leaderIndex % qu.ALL) + 1];
+ ZooKeeper zk1 = (changingIndex == leaderIndex) ? zkArr[leaderIndex] : zkArr[(leaderIndex % qu.ALL) + 1];
+ ZooKeeperAdmin zkAdmin1 = (changingIndex == leaderIndex)
+ ? zkAdminArr[leaderIndex]
+ : zkAdminArr[(leaderIndex % qu.ALL) + 1];
// exactly as it is now, except for role change
joiningServers.add("server."
- + changingIndex
- + "=localhost:"
- + qu.getPeer(changingIndex).peer.getQuorumAddress()
- .getPort()
- + ":"
- + qu.getPeer(changingIndex).peer.getElectionAddress()
- .getPort() + ":" + newRole + ";localhost:"
- + qu.getPeer(changingIndex).peer.getClientPort());
+ + changingIndex
+ + "=localhost:"
+ + qu.getPeer(changingIndex).peer.getQuorumAddress().getPort()
+ + ":"
+ + qu.getPeer(changingIndex).peer.getElectionAddress().getPort()
+ + ":"
+ + newRole
+ + ";localhost:"
+ + qu.getPeer(changingIndex).peer.getClientPort());
reconfig(zkAdmin1, joiningServers, null, null, -1);
testNormalOperation(zkArr[changingIndex], zk1);
if (newRole.equals("observer")) {
- Assert.assertTrue(qu.getPeer(changingIndex).peer.observer != null
- && qu.getPeer(changingIndex).peer.follower == null
- && qu.getPeer(changingIndex).peer.leader == null);
- Assert.assertTrue(qu.getPeer(changingIndex).peer.getPeerState() == ServerState.OBSERVING);
+ assertTrue(qu.getPeer(changingIndex).peer.observer != null
+ && qu.getPeer(changingIndex).peer.follower == null
+ && qu.getPeer(changingIndex).peer.leader == null);
+ assertTrue(qu.getPeer(changingIndex).peer.getPeerState() == ServerState.OBSERVING);
} else {
- Assert.assertTrue(qu.getPeer(changingIndex).peer.observer == null
- && (qu.getPeer(changingIndex).peer.follower != null || qu
- .getPeer(changingIndex).peer.leader != null));
- Assert.assertTrue(qu.getPeer(changingIndex).peer.getPeerState() == ServerState.FOLLOWING
- || qu.getPeer(changingIndex).peer.getPeerState() == ServerState.LEADING);
+ assertTrue(qu.getPeer(changingIndex).peer.observer == null
+ && (qu.getPeer(changingIndex).peer.follower != null
+ || qu.getPeer(changingIndex).peer.leader != null));
+ assertTrue(qu.getPeer(changingIndex).peer.getPeerState() == ServerState.FOLLOWING
+ || qu.getPeer(changingIndex).peer.getPeerState() == ServerState.LEADING);
}
joiningServers.clear();
@@ -600,11 +621,17 @@ public class ReconfigTest extends ZKTestCase implements DataCallback{
// modify follower's client port
int quorumPort = qu.getPeer(followerIndex).peer.getQuorumAddress().getPort();
- int electionPort = qu.getPeer(followerIndex).peer.getElectionAddress().getPort();
+ int electionPort = qu.getPeer(followerIndex).peer.getElectionAddress().getPort();
int oldClientPort = qu.getPeer(followerIndex).peer.getClientPort();
int newClientPort = PortAssignment.unique();
- joiningServers.add("server." + followerIndex + "=localhost:" + quorumPort
- + ":" + electionPort + ":participant;localhost:" + newClientPort);
+ joiningServers.add("server."
+ + followerIndex
+ + "=localhost:"
+ + quorumPort
+ + ":"
+ + electionPort
+ + ":participant;localhost:"
+ + newClientPort);
// create a /test znode and check that read/write works before
// any reconfig is invoked
@@ -613,52 +640,65 @@ public class ReconfigTest extends ZKTestCase implements DataCallback{
reconfig(zkAdminArr[followerIndex], joiningServers, null, null, -1);
try {
- for (int i=0; i < 20; i++) {
- Thread.sleep(1000);
- zkArr[followerIndex].setData("/test", "teststr".getBytes(), -1);
- }
+ for (int i = 0; i < 20; i++) {
+ Thread.sleep(1000);
+ zkArr[followerIndex].setData("/test", "teststr".getBytes(), -1);
+ }
} catch (KeeperException.ConnectionLossException e) {
- Assert.fail("Existing client disconnected when client port changed!");
+ fail("Existing client disconnected when client port changed!");
}
zkArr[followerIndex].close();
- zkArr[followerIndex] = new ZooKeeper("127.0.0.1:"
- + oldClientPort,
- ClientBase.CONNECTION_TIMEOUT, new Watcher() {
- public void process(WatchedEvent event) {}});
+ zkArr[followerIndex] = new ZooKeeper(
+ "127.0.0.1:" + oldClientPort,
+ ClientBase.CONNECTION_TIMEOUT,
+ new Watcher() {
+ public void process(WatchedEvent event) {
+ }
+ });
zkAdminArr[followerIndex].close();
- zkAdminArr[followerIndex] = new ZooKeeperAdmin("127.0.0.1:"
- + oldClientPort,
- ClientBase.CONNECTION_TIMEOUT, new Watcher() {
- public void process(WatchedEvent event) {}});
+ zkAdminArr[followerIndex] = new ZooKeeperAdmin(
+ "127.0.0.1:" + oldClientPort,
+ ClientBase.CONNECTION_TIMEOUT,
+ new Watcher() {
+ public void process(WatchedEvent event) {
+ }
+ });
zkAdminArr[followerIndex].addAuthInfo("digest", "super:test".getBytes());
for (int i = 0; i < 10; i++) {
try {
Thread.sleep(1000);
zkArr[followerIndex].setData("/test", "teststr".getBytes(), -1);
- Assert.fail("New client connected to old client port!");
+ fail("New client connected to old client port!");
} catch (KeeperException.ConnectionLossException e) {
}
}
zkArr[followerIndex].close();
- zkArr[followerIndex] = new ZooKeeper("127.0.0.1:"
- + newClientPort,
- ClientBase.CONNECTION_TIMEOUT, new Watcher() {
- public void process(WatchedEvent event) {}});
+ zkArr[followerIndex] = new ZooKeeper(
+ "127.0.0.1:" + newClientPort,
+ ClientBase.CONNECTION_TIMEOUT,
+ new Watcher() {
+ public void process(WatchedEvent event) {
+
+ }
+ });
zkAdminArr[followerIndex].close();
- zkAdminArr[followerIndex] = new ZooKeeperAdmin("127.0.0.1:"
- + newClientPort,
- ClientBase.CONNECTION_TIMEOUT, new Watcher() {
- public void process(WatchedEvent event) {}});
+ zkAdminArr[followerIndex] = new ZooKeeperAdmin(
+ "127.0.0.1:" + newClientPort,
+ ClientBase.CONNECTION_TIMEOUT,
+ new Watcher() {
+ public void process(WatchedEvent event) {
+ }
+ });
zkAdminArr[followerIndex].addAuthInfo("digest", "super:test".getBytes());
testNormalOperation(zkArr[followerIndex], zkArr[leaderIndex]);
testServerHasConfig(zkArr[followerIndex], joiningServers, null);
- Assert.assertEquals(newClientPort, qu.getPeer(followerIndex).peer.getClientPort());
+ assertEquals(newClientPort, qu.getPeer(followerIndex).peer.getClientPort());
joiningServers.clear();
@@ -666,18 +706,17 @@ public class ReconfigTest extends ZKTestCase implements DataCallback{
int newQuorumPort = PortAssignment.unique();
joiningServers.add("server." + leaderIndex + "=localhost:"
- + newQuorumPort
- + ":"
- + qu.getPeer(leaderIndex).peer.getElectionAddress().getPort()
- + ":participant;localhost:"
- + qu.getPeer(leaderIndex).peer.getClientPort());
+ + newQuorumPort
+ + ":"
+ + qu.getPeer(leaderIndex).peer.getElectionAddress().getPort()
+ + ":participant;localhost:"
+ + qu.getPeer(leaderIndex).peer.getClientPort());
reconfig(zkAdminArr[leaderIndex], joiningServers, null, null, -1);
testNormalOperation(zkArr[followerIndex], zkArr[leaderIndex]);
- Assert.assertTrue(qu.getPeer(leaderIndex).peer.getQuorumAddress()
- .getPort() == newQuorumPort);
+ assertTrue(qu.getPeer(leaderIndex).peer.getQuorumAddress().getPort() == newQuorumPort);
joiningServers.clear();
@@ -685,9 +724,11 @@ public class ReconfigTest extends ZKTestCase implements DataCallback{
for (int i = 1; i <= 3; i++) {
joiningServers.add("server." + i + "=localhost:"
- + qu.getPeer(i).peer.getQuorumAddress().getPort() + ":"
- + PortAssignment.unique() + ":participant;localhost:"
- + qu.getPeer(i).peer.getClientPort());
+ + qu.getPeer(i).peer.getQuorumAddress().getPort()
+ + ":"
+ + PortAssignment.unique()
+ + ":participant;localhost:"
+ + qu.getPeer(i).peer.getClientPort());
}
reconfig(zkAdminArr[1], joiningServers, null, null, -1);
@@ -695,8 +736,9 @@ public class ReconfigTest extends ZKTestCase implements DataCallback{
leaderIndex = getLeaderId(qu);
int follower1 = leaderIndex == 1 ? 2 : 1;
int follower2 = 1;
- while (follower2 == leaderIndex || follower2 == follower1)
+ while (follower2 == leaderIndex || follower2 == follower1) {
follower2++;
+ }
// lets kill the leader and see if a new one is elected
@@ -736,11 +778,10 @@ public class ReconfigTest extends ZKTestCase implements DataCallback{
int oldClientPort = qu.getPeer(serverIndex).peer.getClientPort();
int newClientPort = PortAssignment.unique();
- try(ServerSocket ss = new ServerSocket()) {
+ try (ServerSocket ss = new ServerSocket()) {
ss.bind(new InetSocketAddress(getLoopbackAddress(), newClientPort));
- joiningServers.add("server." + serverIndex + "=localhost:" + quorumPort
- + ":" + electionPort + ":participant;localhost:" + newClientPort);
+ joiningServers.add("server." + serverIndex + "=localhost:" + quorumPort + ":" + electionPort + ":participant;localhost:" + newClientPort);
// create a /test znode and check that read/write works before
// any reconfig is invoked
@@ -752,21 +793,27 @@ public class ReconfigTest extends ZKTestCase implements DataCallback{
// The follower reconfiguration will have failed
zkArr[serverIndex].close();
- zkArr[serverIndex] = new ZooKeeper("127.0.0.1:"
- + newClientPort,
- ClientBase.CONNECTION_TIMEOUT, new Watcher() {
- public void process(WatchedEvent event) {}});
+ zkArr[serverIndex] = new ZooKeeper(
+ "127.0.0.1:" + newClientPort,
+ ClientBase.CONNECTION_TIMEOUT,
+ new Watcher() {
+ public void process(WatchedEvent event) {
+ }
+ });
zkAdminArr[serverIndex].close();
- zkAdminArr[serverIndex] = new ZooKeeperAdmin("127.0.0.1:"
- + newClientPort,
- ClientBase.CONNECTION_TIMEOUT, new Watcher() {
- public void process(WatchedEvent event) {}});
+ zkAdminArr[serverIndex] = new ZooKeeperAdmin(
+ "127.0.0.1:" + newClientPort,
+ ClientBase.CONNECTION_TIMEOUT,
+ new Watcher() {
+ public void process(WatchedEvent event) {
+ }
+ });
try {
Thread.sleep(1000);
zkArr[serverIndex].setData("/test", "teststr".getBytes(), -1);
- Assert.fail("New client connected to new client port!");
+ fail("New client connected to new client port!");
} catch (KeeperException.ConnectionLossException e) {
// Exception is expected
}
@@ -779,37 +826,36 @@ public class ReconfigTest extends ZKTestCase implements DataCallback{
// Move back to the old port
joiningServers.clear();
- joiningServers.add("server." + serverIndex + "=localhost:" + quorumPort
- + ":" + electionPort + ":participant;localhost:" + oldClientPort);
+ joiningServers.add("server." + serverIndex + "=localhost:" + quorumPort + ":" + electionPort
+ + ":participant;localhost:" + oldClientPort);
reconfig(zkAdminArr[reconfigIndex], joiningServers, null, null, -1);
zkArr[serverIndex].close();
- zkArr[serverIndex] = new ZooKeeper("127.0.0.1:"
- + oldClientPort,
- ClientBase.CONNECTION_TIMEOUT, new Watcher() {
- public void process(WatchedEvent event) {}});
+ zkArr[serverIndex] = new ZooKeeper(
+ "127.0.0.1:" + oldClientPort,
+ ClientBase.CONNECTION_TIMEOUT,
+ new Watcher() {
+ public void process(WatchedEvent event) {
+ }
+ });
testNormalOperation(zkArr[followerIndex], zkArr[leaderIndex]);
testServerHasConfig(zkArr[serverIndex], joiningServers, null);
- Assert.assertEquals(oldClientPort, qu.getPeer(serverIndex).peer.getClientPort());
+ assertEquals(oldClientPort, qu.getPeer(serverIndex).peer.getClientPort());
}
}
@Test
public void testUnspecifiedClientAddress() throws Exception {
- int[] ports = {
- PortAssignment.unique(),
- PortAssignment.unique(),
- PortAssignment.unique()
- };
-
- String server = "server.0=localhost:" + ports[0] + ":" + ports[1] + ";" + ports[2];
- QuorumServer qs = new QuorumServer(0, server);
- Assert.assertEquals(qs.clientAddr.getHostString(), "0.0.0.0");
- Assert.assertEquals(qs.clientAddr.getPort(), ports[2]);
+ int[] ports = {PortAssignment.unique(), PortAssignment.unique(), PortAssignment.unique()};
+
+ String server = "server.0=localhost:" + ports[0] + ":" + ports[1] + ";" + ports[2];
+ QuorumServer qs = new QuorumServer(0, server);
+ assertEquals(qs.clientAddr.getHostString(), "0.0.0.0");
+ assertEquals(qs.clientAddr.getPort(), ports[2]);
}
-
+
@Test
public void testQuorumSystemChange() throws Exception {
qu = new QuorumUtil(3); // create 7 servers
@@ -818,7 +864,7 @@ public class ReconfigTest extends ZKTestCase implements DataCallback{
zkArr = createHandles(qu);
zkAdminArr = createAdminHandles(qu);
- ArrayList<String> members = new ArrayList<String>();
+ ArrayList<String> members = new ArrayList<>();
members.add("group.1=3:4:5");
members.add("group.2=1:2");
members.add("weight.1=0");
@@ -829,9 +875,12 @@ public class ReconfigTest extends ZKTestCase implements DataCallback{
for (int i = 1; i <= 5; i++) {
members.add("server." + i + "=127.0.0.1:"
- + qu.getPeer(i).peer.getQuorumAddress().getPort() + ":"
- + qu.getPeer(i).peer.getElectionAddress().getPort() + ";"
- + "127.0.0.1:" + qu.getPeer(i).peer.getClientPort());
+ + qu.getPeer(i).peer.getQuorumAddress().getPort()
+ + ":"
+ + qu.getPeer(i).peer.getElectionAddress().getPort()
+ + ";"
+ + "127.0.0.1:"
+ + qu.getPeer(i).peer.getClientPort());
}
reconfig(zkAdminArr[1], null, null, members, -1);
@@ -841,9 +890,9 @@ public class ReconfigTest extends ZKTestCase implements DataCallback{
testNormalOperation(zkArr[4], zkArr[5]);
for (int i = 1; i <= 5; i++) {
- if (!(qu.getPeer(i).peer.getQuorumVerifier() instanceof QuorumHierarchical))
- Assert.fail("peer " + i
- + " doesn't think the quorum system is Hieararchical!");
+ if (!(qu.getPeer(i).peer.getQuorumVerifier() instanceof QuorumHierarchical)) {
+ fail("peer " + i + " doesn't think the quorum system is Hieararchical!");
+ }
}
qu.shutdown(1);
@@ -861,9 +910,12 @@ public class ReconfigTest extends ZKTestCase implements DataCallback{
members.clear();
for (int i = 1; i <= 3; i++) {
members.add("server." + i + "=127.0.0.1:"
- + qu.getPeer(i).peer.getQuorumAddress().getPort() + ":"
- + qu.getPeer(i).peer.getElectionAddress().getPort() + ";"
- + "127.0.0.1:" + qu.getPeer(i).peer.getClientPort());
+ + qu.getPeer(i).peer.getQuorumAddress().getPort()
+ + ":"
+ + qu.getPeer(i).peer.getElectionAddress().getPort()
+ + ";"
+ + "127.0.0.1:"
+ + qu.getPeer(i).peer.getClientPort());
}
reconfig(zkAdminArr[1], null, null, members, -1);
@@ -878,13 +930,12 @@ public class ReconfigTest extends ZKTestCase implements DataCallback{
testNormalOperation(zkArr[1], zkArr[2]);
for (int i = 1; i <= 2; i++) {
- if (!(qu.getPeer(i).peer.getQuorumVerifier() instanceof QuorumMaj))
- Assert.fail("peer "
- + i
- + " doesn't think the quorum system is a majority quorum system!");
+ if (!(qu.getPeer(i).peer.getQuorumVerifier() instanceof QuorumMaj)) {
+ fail("peer " + i + " doesn't think the quorum system is a majority quorum system!");
+ }
}
}
-
+
@Test
public void testInitialConfigHasPositiveVersion() throws Exception {
qu = new QuorumUtil(1); // create 3 servers
@@ -892,11 +943,11 @@ public class ReconfigTest extends ZKTestCase implements DataCallback{
qu.startAll();
zkArr = createHandles(qu);
testNormalOperation(zkArr[1], zkArr[2]);
- for (int i=1; i<4; i++) {
+ for (int i = 1; i < 4; i++) {
String configStr = testServerHasConfig(zkArr[i], null, null);
QuorumVerifier qv = qu.getPeer(i).peer.configFromString(configStr);
long version = qv.getVersion();
- Assert.assertTrue(version == 0x100000000L);
+ assertTrue(version == 0x100000000L);
}
}
@@ -921,8 +972,10 @@ public class ReconfigTest extends ZKTestCase implements DataCallback{
QuorumPeer peer2 = qu.getPeer(replica2).peer;
QuorumServer leavingQS2 = peer2.getView().get(Long.valueOf(leavingIndex));
String remotePeerBean2 = MBeanRegistry.DOMAIN
- + ":name0=ReplicatedServer_id" + replica2 + ",name1=replica."
- + leavingIndex;
+ + ":name0=ReplicatedServer_id"
+ + replica2
+ + ",name1=replica."
+ + leavingIndex;
assertRemotePeerMXBeanAttributes(leavingQS2, remotePeerBean2);
// assert remotePeerBean.1 of ReplicatedServer_3
@@ -930,8 +983,10 @@ public class ReconfigTest extends ZKTestCase implements DataCallback{
QuorumPeer peer3 = qu.getPeer(replica3).peer;
QuorumServer leavingQS3 = peer3.getView().get(Long.valueOf(leavingIndex));
String remotePeerBean3 = MBeanRegistry.DOMAIN
- + ":name0=ReplicatedServer_id" + replica3 + ",name1=replica."
- + leavingIndex;
+ + ":name0=ReplicatedServer_id"
+ + replica3
+ + ",name1=replica."
+ + leavingIndex;
assertRemotePeerMXBeanAttributes(leavingQS3, remotePeerBean3);
ZooKeeper zk = zkArr[leavingIndex];
@@ -941,11 +996,11 @@ public class ReconfigTest extends ZKTestCase implements DataCallback{
// remember this server so we can add it back later
joiningServers.add("server." + leavingIndex + "=127.0.0.1:"
- + qu.getPeer(leavingIndex).peer.getQuorumAddress().getPort()
- + ":"
- + qu.getPeer(leavingIndex).peer.getElectionAddress().getPort()
- + ":participant;127.0.0.1:"
- + qu.getPeer(leavingIndex).peer.getClientPort());
+ + qu.getPeer(leavingIndex).peer.getQuorumAddress().getPort()
+ + ":"
+ + qu.getPeer(leavingIndex).peer.getElectionAddress().getPort()
+ + ":participant;127.0.0.1:"
+ + qu.getPeer(leavingIndex).peer.getClientPort());
// Remove ReplicatedServer_1 from the ensemble
reconfig(zkAdmin, null, leavingServers, null, -1);
@@ -953,8 +1008,10 @@ public class ReconfigTest extends ZKTestCase implements DataCallback{
// localPeerBean.1 of ReplicatedServer_1
QuorumPeer removedPeer = qu.getPeer(leavingIndex).peer;
String localPeerBean = MBeanRegistry.DOMAIN
- + ":name0=ReplicatedServer_id" + leavingIndex
- + ",name1=replica." + leavingIndex;
+ + ":name0=ReplicatedServer_id"
+ + leavingIndex
+ + ",name1=replica."
+ + leavingIndex;
assertLocalPeerMXBeanAttributes(removedPeer, localPeerBean, false);
// remotePeerBean.1 shouldn't exists in ReplicatedServer_2
@@ -999,8 +1056,10 @@ public class ReconfigTest extends ZKTestCase implements DataCallback{
QuorumPeer peer2 = qu.getPeer(replica2).peer;
QuorumServer changingQS2 = peer2.getView().get(Long.valueOf(changingIndex));
String remotePeerBean2 = MBeanRegistry.DOMAIN
- + ":name0=ReplicatedServer_id" + replica2 + ",name1=replica."
- + changingIndex;
+ + ":name0=ReplicatedServer_id"
+ + replica2
+ + ",name1=replica."
+ + changingIndex;
assertRemotePeerMXBeanAttributes(changingQS2, remotePeerBean2);
// assert remotePeerBean.1 of ReplicatedServer_3
@@ -1008,8 +1067,10 @@ public class ReconfigTest extends ZKTestCase implements DataCallback{
QuorumPeer peer3 = qu.getPeer(replica3).peer;
QuorumServer changingQS3 = peer3.getView().get(Long.valueOf(changingIndex));
String remotePeerBean3 = MBeanRegistry.DOMAIN
- + ":name0=ReplicatedServer_id" + replica3 + ",name1=replica."
- + changingIndex;
+ + ":name0=ReplicatedServer_id"
+ + replica3
+ + ",name1=replica."
+ + changingIndex;
assertRemotePeerMXBeanAttributes(changingQS3, remotePeerBean3);
String newRole = "observer";
@@ -1019,24 +1080,28 @@ public class ReconfigTest extends ZKTestCase implements DataCallback{
// exactly as it is now, except for role change
joiningServers.add("server." + changingIndex + "=127.0.0.1:"
- + qu.getPeer(changingIndex).peer.getQuorumAddress().getPort()
- + ":"
- + qu.getPeer(changingIndex).peer.getElectionAddress().getPort()
- + ":" + newRole + ";127.0.0.1:"
- + qu.getPeer(changingIndex).peer.getClientPort());
+ + qu.getPeer(changingIndex).peer.getQuorumAddress().getPort()
+ + ":"
+ + qu.getPeer(changingIndex).peer.getElectionAddress().getPort()
+ + ":"
+ + newRole
+ + ";127.0.0.1:"
+ + qu.getPeer(changingIndex).peer.getClientPort());
reconfig(zkAdmin, joiningServers, null, null, -1);
testNormalOperation(zkArr[changingIndex], zk);
- Assert.assertTrue(qu.getPeer(changingIndex).peer.observer != null
- && qu.getPeer(changingIndex).peer.follower == null
- && qu.getPeer(changingIndex).peer.leader == null);
- Assert.assertTrue(qu.getPeer(changingIndex).peer.getPeerState() == ServerState.OBSERVING);
+ assertTrue(qu.getPeer(changingIndex).peer.observer != null
+ && qu.getPeer(changingIndex).peer.follower == null
+ && qu.getPeer(changingIndex).peer.leader == null);
+ assertTrue(qu.getPeer(changingIndex).peer.getPeerState() == ServerState.OBSERVING);
QuorumPeer qp = qu.getPeer(changingIndex).peer;
String localPeerBeanName = MBeanRegistry.DOMAIN
- + ":name0=ReplicatedServer_id" + changingIndex
- + ",name1=replica." + changingIndex;
+ + ":name0=ReplicatedServer_id"
+ + changingIndex
+ + ",name1=replica."
+ + changingIndex;
// localPeerBean.1 of ReplicatedServer_1
assertLocalPeerMXBeanAttributes(qp, localPeerBeanName, true);
@@ -1050,31 +1115,40 @@ public class ReconfigTest extends ZKTestCase implements DataCallback{
assertRemotePeerMXBeanAttributes(changingQS3, remotePeerBean3);
}
- private void assertLocalPeerMXBeanAttributes(QuorumPeer qp,
- String beanName, Boolean isPartOfEnsemble) throws Exception {
- Assert.assertEquals("Mismatches LearnerType!", qp.getLearnerType()
- .name(), JMXEnv.ensureBeanAttribute(beanName, "LearnerType"));
- Assert.assertEquals("Mismatches ClientAddress!",
- qp.getClientAddress().getHostString() + ":" + qp.getClientAddress().getPort(),
- JMXEnv.ensureBeanAttribute(beanName, "ClientAddress"));
- Assert.assertEquals("Mismatches LearnerType!",
- qp.getElectionAddress().getHostString() + ":" + qp.getElectionAddress().getPort(),
- JMXEnv.ensureBeanAttribute(beanName, "ElectionAddress"));
- Assert.assertEquals("Mismatches PartOfEnsemble!", isPartOfEnsemble,
- JMXEnv.ensureBeanAttribute(beanName, "PartOfEnsemble"));
- Assert.assertEquals("Mismatches ConfigVersion!", qp.getQuorumVerifier()
- .getVersion(), JMXEnv.ensureBeanAttribute(beanName,
- "ConfigVersion"));
- Assert.assertEquals("Mismatches QuorumSystemInfo!", qp
- .getQuorumVerifier().toString(), JMXEnv.ensureBeanAttribute(
- beanName, "QuorumSystemInfo"));
+ private void assertLocalPeerMXBeanAttributes(
+ QuorumPeer qp,
+ String beanName,
+ Boolean isPartOfEnsemble) throws Exception {
+ assertEquals(
+ "Mismatches LearnerType!",
+ qp.getLearnerType().name(),
+ JMXEnv.ensureBeanAttribute(beanName, "LearnerType"));
+ assertEquals(
+ "Mismatches ClientAddress!",
+ qp.getClientAddress().getHostString() + ":" + qp.getClientAddress().getPort(),
+ JMXEnv.ensureBeanAttribute(beanName, "ClientAddress"));
+ assertEquals(
+ "Mismatches LearnerType!",
+ qp.getElectionAddress().getHostString() + ":" + qp.getElectionAddress().getPort(),
+ JMXEnv.ensureBeanAttribute(beanName, "ElectionAddress"));
+ assertEquals(
+ "Mismatches PartOfEnsemble!",
+ isPartOfEnsemble,
+ JMXEnv.ensureBeanAttribute(beanName, "PartOfEnsemble"));
+ assertEquals(
+ "Mismatches ConfigVersion!",
+ qp.getQuorumVerifier().getVersion(),
+ JMXEnv.ensureBeanAttribute(beanName, "ConfigVersion"));
+ assertEquals(
+ "Mismatches QuorumSystemInfo!",
+ qp.getQuorumVerifier().toString(),
+ JMXEnv.ensureBeanAttribute(beanName, "QuorumSystemInfo"));
}
String getAddrPortFromBean(String beanName, String attribute) throws Exception {
- String name = (String) JMXEnv.ensureBeanAttribute(
- beanName, attribute);
+ String name = (String) JMXEnv.ensureBeanAttribute(beanName, attribute);
- if ( ! name.contains(":") ) {
+ if (!name.contains(":")) {
return name;
}
@@ -1088,18 +1162,23 @@ public class ReconfigTest extends ZKTestCase implements DataCallback{
return addr + ":" + port;
}
- private void assertRemotePeerMXBeanAttributes(QuorumServer qs,
- String beanName) throws Exception {
- Assert.assertEquals("Mismatches LearnerType!", qs.type.name(),
- JMXEnv.ensureBeanAttribute(beanName, "LearnerType"));
- Assert.assertEquals("Mismatches ClientAddress!",
- getNumericalAddrPort(qs.clientAddr.getHostString() + ":" + qs.clientAddr.getPort()),
- getAddrPortFromBean(beanName, "ClientAddress") );
- Assert.assertEquals("Mismatches ElectionAddress!",
- getNumericalAddrPort(qs.electionAddr.getHostString() + ":" + qs.electionAddr.getPort()),
- getAddrPortFromBean(beanName, "ElectionAddress") );
- Assert.assertEquals("Mismatches QuorumAddress!",
- getNumericalAddrPort(qs.addr.getHostString() + ":" + qs.addr.getPort()),
- getAddrPortFromBean(beanName, "QuorumAddress") );
+ private void assertRemotePeerMXBeanAttributes(QuorumServer qs, String beanName) throws Exception {
+ assertEquals(
+ "Mismatches LearnerType!",
+ qs.type.name(),
+ JMXEnv.ensureBeanAttribute(beanName, "LearnerType"));
+ assertEquals(
+ "Mismatches ClientAddress!",
+ getNumericalAddrPort(qs.clientAddr.getHostString() + ":" + qs.clientAddr.getPort()),
+ getAddrPortFromBean(beanName, "ClientAddress"));
+ assertEquals(
+ "Mismatches ElectionAddress!",
+ getNumericalAddrPort(qs.electionAddr.getHostString() + ":" + qs.electionAddr.getPort()),
+ getAddrPortFromBean(beanName, "ElectionAddress"));
+ assertEquals(
+ "Mismatches QuorumAddress!",
+ getNumericalAddrPort(qs.addr.getHostString() + ":" + qs.addr.getPort()),
+ getAddrPortFromBean(beanName, "QuorumAddress"));
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/RecoveryTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/RecoveryTest.java
index c084a68fc..d6773b7e0 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/RecoveryTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/RecoveryTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -19,33 +19,32 @@
package org.apache.zookeeper.test;
import static org.apache.zookeeper.test.ClientBase.CONNECTION_TIMEOUT;
-
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
import java.io.File;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.PortAssignment;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
-import org.apache.zookeeper.ZKTestCase;
-import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.Watcher.Event.KeeperState;
+import org.apache.zookeeper.ZKTestCase;
import org.apache.zookeeper.ZooDefs.Ids;
+import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;
import org.apache.zookeeper.server.ServerCnxnFactory;
import org.apache.zookeeper.server.SyncRequestProcessor;
import org.apache.zookeeper.server.ZooKeeperServer;
-import org.junit.Assert;
import org.junit.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
public class RecoveryTest extends ZKTestCase implements Watcher {
+
protected static final Logger LOG = LoggerFactory.getLogger(RecoveryTest.class);
- private static final String HOSTPORT =
- "127.0.0.1:" + PortAssignment.unique();
+ private static final String HOSTPORT = "127.0.0.1:" + PortAssignment.unique();
private volatile CountDownLatch startSignal;
@@ -76,39 +75,31 @@ public class RecoveryTest extends ZKTestCase implements Watcher {
f.startup(zks);
LOG.info("starting up the the server, waiting");
- Assert.assertTrue("waiting for server up",
- ClientBase.waitForServerUp(HOSTPORT,
- CONNECTION_TIMEOUT));
+ assertTrue("waiting for server up", ClientBase.waitForServerUp(HOSTPORT, CONNECTION_TIMEOUT));
startSignal = new CountDownLatch(1);
ZooKeeper zk = new ZooKeeper(HOSTPORT, CONNECTION_TIMEOUT, this);
- startSignal.await(CONNECTION_TIMEOUT,
- TimeUnit.MILLISECONDS);
- Assert.assertTrue("count == 0", startSignal.getCount() == 0);
+ startSignal.await(CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS);
+ assertTrue("count == 0", startSignal.getCount() == 0);
String path;
LOG.info("starting creating nodes");
for (int i = 0; i < 10; i++) {
path = "/" + i;
- zk.create(path,
- (path + "!").getBytes(),
- Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
+ zk.create(path, (path + "!").getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
for (int j = 0; j < 10; j++) {
String subpath = path + "/" + j;
- zk.create(subpath, (subpath + "!").getBytes(),
- Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
+ zk.create(subpath, (subpath + "!").getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
for (int k = 0; k < 20; k++) {
String subsubpath = subpath + "/" + k;
- zk.create(subsubpath, (subsubpath + "!").getBytes(),
- Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
+ zk.create(subsubpath, (subsubpath
+ + "!").getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
}
}
}
f.shutdown();
zks.shutdown();
- Assert.assertTrue("waiting for server down",
- ClientBase.waitForServerDown(HOSTPORT,
- CONNECTION_TIMEOUT));
+ assertTrue("waiting for server down", ClientBase.waitForServerDown(HOSTPORT, CONNECTION_TIMEOUT));
zks = new ZooKeeperServer(tmpDir, tmpDir, 3000);
f = ServerCnxnFactory.createFactory(PORT, -1);
@@ -117,37 +108,29 @@ public class RecoveryTest extends ZKTestCase implements Watcher {
f.startup(zks);
- Assert.assertTrue("waiting for server up",
- ClientBase.waitForServerUp(HOSTPORT,
- CONNECTION_TIMEOUT));
+ assertTrue("waiting for server up", ClientBase.waitForServerUp(HOSTPORT, CONNECTION_TIMEOUT));
- startSignal.await(CONNECTION_TIMEOUT,
- TimeUnit.MILLISECONDS);
- Assert.assertTrue("count == 0", startSignal.getCount() == 0);
+ startSignal.await(CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS);
+ assertTrue("count == 0", startSignal.getCount() == 0);
Stat stat = new Stat();
for (int i = 0; i < 10; i++) {
path = "/" + i;
LOG.info("Checking " + path);
- Assert.assertEquals(new String(zk.getData(path, false, stat)), path
- + "!");
+ assertEquals(new String(zk.getData(path, false, stat)), path + "!");
for (int j = 0; j < 10; j++) {
String subpath = path + "/" + j;
- Assert.assertEquals(new String(zk.getData(subpath, false, stat)),
- subpath + "!");
+ assertEquals(new String(zk.getData(subpath, false, stat)), subpath + "!");
for (int k = 0; k < 20; k++) {
String subsubpath = subpath + "/" + k;
- Assert.assertEquals(new String(zk.getData(subsubpath, false,
- stat)), subsubpath + "!");
+ assertEquals(new String(zk.getData(subsubpath, false, stat)), subsubpath + "!");
}
}
}
f.shutdown();
zks.shutdown();
- Assert.assertTrue("waiting for server down",
- ClientBase.waitForServerDown(HOSTPORT,
- ClientBase.CONNECTION_TIMEOUT));
+ assertTrue("waiting for server down", ClientBase.waitForServerDown(HOSTPORT, ClientBase.CONNECTION_TIMEOUT));
zks = new ZooKeeperServer(tmpDir, tmpDir, 3000);
f = ServerCnxnFactory.createFactory(PORT, -1);
@@ -156,27 +139,22 @@ public class RecoveryTest extends ZKTestCase implements Watcher {
f.startup(zks);
- Assert.assertTrue("waiting for server up",
- ClientBase.waitForServerUp(HOSTPORT,
- CONNECTION_TIMEOUT));
+ assertTrue("waiting for server up", ClientBase.waitForServerUp(HOSTPORT, CONNECTION_TIMEOUT));
startSignal.await(CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS);
- Assert.assertTrue("count == 0", startSignal.getCount() == 0);
+ assertTrue("count == 0", startSignal.getCount() == 0);
stat = new Stat();
LOG.info("Check 2");
for (int i = 0; i < 10; i++) {
path = "/" + i;
- Assert.assertEquals(new String(zk.getData(path, false, stat)),
- path + "!");
+ assertEquals(new String(zk.getData(path, false, stat)), path + "!");
for (int j = 0; j < 10; j++) {
String subpath = path + "/" + j;
- Assert.assertEquals(new String(zk.getData(subpath, false, stat)),
- subpath + "!");
+ assertEquals(new String(zk.getData(subpath, false, stat)), subpath + "!");
for (int k = 0; k < 20; k++) {
String subsubpath = subpath + "/" + k;
- Assert.assertEquals(new String(zk.getData(subsubpath, false,
- stat)), subsubpath + "!");
+ assertEquals(new String(zk.getData(subsubpath, false, stat)), subsubpath + "!");
}
}
}
@@ -185,9 +163,7 @@ public class RecoveryTest extends ZKTestCase implements Watcher {
f.shutdown();
zks.shutdown();
- Assert.assertTrue("waiting for server down",
- ClientBase.waitForServerDown(HOSTPORT,
- CONNECTION_TIMEOUT));
+ assertTrue("waiting for server down", ClientBase.waitForServerDown(HOSTPORT, CONNECTION_TIMEOUT));
} finally {
SyncRequestProcessor.setSnapCount(oldSnapCount);
}
@@ -200,10 +176,9 @@ public class RecoveryTest extends ZKTestCase implements Watcher {
*/
public void process(WatchedEvent event) {
LOG.info("Event:" + event.getState() + " " + event.getType() + " " + event.getPath());
- if (event.getState() == KeeperState.SyncConnected
- && startSignal != null && startSignal.getCount() > 0)
- {
+ if (event.getState() == KeeperState.SyncConnected && startSignal != null && startSignal.getCount() > 0) {
startSignal.countDown();
}
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/RepeatStartupTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/RepeatStartupTest.java
index 419cfe9ad..27fa4a9da 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/RepeatStartupTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/RepeatStartupTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,13 +18,13 @@
package org.apache.zookeeper.test;
+import static org.junit.Assert.assertTrue;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.ZKTestCase;
-import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.ZooDefs.Ids;
+import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.server.ServerCnxnFactory;
import org.apache.zookeeper.server.ZooKeeperServer;
-import org.junit.Assert;
import org.junit.Test;
public class RepeatStartupTest extends ZKTestCase {
@@ -49,21 +49,21 @@ public class RepeatStartupTest extends ZKTestCase {
QuorumBase.shutdown(qb.s4);
QuorumBase.shutdown(qb.s5);
String hp = qb.hostPort.split(",")[0];
- ZooKeeperServer zks = new ZooKeeperServer(qb.s1.getTxnFactory().getSnapDir(),
- qb.s1.getTxnFactory().getDataDir(), 3000);
+ ZooKeeperServer zks = new ZooKeeperServer(qb.s1.getTxnFactory().getSnapDir(), qb.s1.getTxnFactory().getDataDir(), 3000);
final int PORT = Integer.parseInt(hp.split(":")[1]);
ServerCnxnFactory factory = ServerCnxnFactory.createFactory(PORT, -1);
factory.startup(zks);
System.out.println("Comment: starting factory");
- Assert.assertTrue("waiting for server up",
- ClientBase.waitForServerUp("127.0.0.1:" + PORT,
- QuorumTest.CONNECTION_TIMEOUT));
+ assertTrue(
+ "waiting for server up",
+ ClientBase.waitForServerUp("127.0.0.1:" + PORT, QuorumTest.CONNECTION_TIMEOUT));
factory.shutdown();
zks.shutdown();
- Assert.assertTrue("waiting for server down",
- ClientBase.waitForServerDown("127.0.0.1:" + PORT,
- QuorumTest.CONNECTION_TIMEOUT));
+ assertTrue(
+ "waiting for server down",
+ ClientBase.waitForServerDown("127.0.0.1:" + PORT, QuorumTest.CONNECTION_TIMEOUT));
System.out.println("Comment: shutting down standalone");
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/ResponseCacheTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/ResponseCacheTest.java
index ead8fed33..9831e875b 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/ResponseCacheTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/ResponseCacheTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,22 +18,23 @@
package org.apache.zookeeper.test;
+import static org.junit.Assert.assertArrayEquals;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotSame;
import java.util.Map;
-
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;
import org.apache.zookeeper.metrics.MetricsUtils;
import org.apache.zookeeper.server.ServerMetrics;
-import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ResponseCacheTest extends ClientBase {
- protected static final Logger LOG =
- LoggerFactory.getLogger(ResponseCacheTest.class);
+
+ protected static final Logger LOG = LoggerFactory.getLogger(ResponseCacheTest.class);
@Test
public void testResponseCache() throws Exception {
@@ -42,17 +43,16 @@ public class ResponseCacheTest extends ClientBase {
try {
performCacheTest(zk, "/cache", true);
performCacheTest(zk, "/nocache", false);
- }
- finally {
+ } finally {
zk.close();
}
}
private void checkCacheStatus(long expectedHits, long expectedMisses) {
-
+
Map<String, Object> metrics = MetricsUtils.currentServerMetrics();
- Assert.assertEquals(expectedHits, metrics.get("response_packet_cache_hits"));
- Assert.assertEquals(expectedMisses, metrics.get("response_packet_cache_misses"));
+ assertEquals(expectedHits, metrics.get("response_packet_cache_hits"));
+ assertEquals(expectedMisses, metrics.get("response_packet_cache_misses"));
}
public void performCacheTest(ZooKeeper zk, String path, boolean useCache) throws Exception {
@@ -68,12 +68,11 @@ public class ResponseCacheTest extends ClientBase {
LOG.info("caching: {}", useCache);
byte[] writeData = "test1".getBytes();
- zk.create(path, writeData, ZooDefs.Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT, writeStat);
+ zk.create(path, writeData, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT, writeStat);
for (int i = 0; i < reads; ++i) {
readData = zk.getData(path, false, readStat);
- Assert.assertArrayEquals(writeData, readData);
- Assert.assertEquals(writeStat, readStat);
+ assertArrayEquals(writeData, readData);
+ assertEquals(writeStat, readStat);
}
if (useCache) {
expectedMisses += 1;
@@ -85,8 +84,8 @@ public class ResponseCacheTest extends ClientBase {
writeStat = zk.setData(path, writeData, -1);
for (int i = 0; i < 10; ++i) {
readData = zk.getData(path, false, readStat);
- Assert.assertArrayEquals(writeData, readData);
- Assert.assertEquals(writeStat, readStat);
+ assertArrayEquals(writeData, readData);
+ assertEquals(writeStat, readStat);
}
if (useCache) {
expectedMisses += 1;
@@ -98,14 +97,14 @@ public class ResponseCacheTest extends ClientBase {
// the tested node, but will change it's pzxid. The next read of the tested
// node should miss in the cache. The data should still match what was written
// before, but the stat information should not.
- zk.create(path + "/child", "child".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT, null);
+ zk.create(path + "/child", "child".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT, null);
readData = zk.getData(path, false, readStat);
if (useCache) {
expectedMisses++;
}
- Assert.assertArrayEquals(writeData, readData);
- Assert.assertNotSame(writeStat, readStat);
+ assertArrayEquals(writeData, readData);
+ assertNotSame(writeStat, readStat);
checkCacheStatus(expectedHits, expectedMisses);
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/RestoreCommittedLogTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/RestoreCommittedLogTest.java
index 742556188..188396f1f 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/RestoreCommittedLogTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/RestoreCommittedLogTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,20 +18,18 @@
package org.apache.zookeeper.test;
+import static org.junit.Assert.assertTrue;
import java.io.File;
import java.util.Collection;
-import java.util.List;
-
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.PortAssignment;
import org.apache.zookeeper.ZKTestCase;
-import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.ZooDefs.Ids;
-import org.apache.zookeeper.server.quorum.Leader.Proposal;
+import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.server.ServerCnxnFactory;
import org.apache.zookeeper.server.SyncRequestProcessor;
import org.apache.zookeeper.server.ZooKeeperServer;
-import org.junit.Assert;
+import org.apache.zookeeper.server.quorum.Leader.Proposal;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -39,7 +37,8 @@ import org.slf4j.LoggerFactory;
/** After a replica starts, it should load commits in its committedLog list.
* This test checks if committedLog != 0 after replica restarted.
*/
-public class RestoreCommittedLogTest extends ZKTestCase{
+public class RestoreCommittedLogTest extends ZKTestCase {
+
private static final Logger LOG = LoggerFactory.getLogger(RestoreCommittedLogTest.class);
private static final String HOSTPORT = "127.0.0.1:" + PortAssignment.unique();
private static final int CONNECTION_TIMEOUT = 3000;
@@ -56,7 +55,7 @@ public class RestoreCommittedLogTest extends ZKTestCase{
final int minTxnsToSnap = 256;
final int numTransactions = minExpectedSnapshots * minTxnsToSnap;
final StringBuilder sb = new StringBuilder();
- for (int i = 0; i < 4*1024; i++) {
+ for (int i = 0; i < 4 * 1024; i++) {
sb.append("0");
}
final byte[] data = sb.toString().getBytes();
@@ -99,13 +98,11 @@ public class RestoreCommittedLogTest extends ZKTestCase{
final int PORT = Integer.parseInt(HOSTPORT.split(":")[1]);
ServerCnxnFactory f = ServerCnxnFactory.createFactory(PORT, -1);
f.startup(zks);
- Assert.assertTrue("waiting for server being up ",
- ClientBase.waitForServerUp(HOSTPORT,CONNECTION_TIMEOUT));
+ assertTrue("waiting for server being up ", ClientBase.waitForServerUp(HOSTPORT, CONNECTION_TIMEOUT));
ZooKeeper zk = ClientBase.createZKClient(HOSTPORT);
try {
- for (int i = 0; i< totalTransactions; i++) {
- zk.create("/invalidsnap-" + i, data, Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ for (int i = 0; i < totalTransactions; i++) {
+ zk.create("/invalidsnap-" + i, data, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
}
} finally {
zk.close();
@@ -115,11 +112,10 @@ public class RestoreCommittedLogTest extends ZKTestCase{
f.shutdown();
zks.shutdown();
- Assert.assertTrue("waiting for server to shutdown",
- ClientBase.waitForServerDown(HOSTPORT, CONNECTION_TIMEOUT));
+ assertTrue("waiting for server to shutdown", ClientBase.waitForServerDown(HOSTPORT, CONNECTION_TIMEOUT));
- Assert.assertTrue("too few snapshot files", numSnaps > minExpectedSnapshots);
- Assert.assertTrue("too many snapshot files", numSnaps <= minExpectedSnapshots * 2);
+ assertTrue("too few snapshot files", numSnaps > minExpectedSnapshots);
+ assertTrue("too many snapshot files", numSnaps <= minExpectedSnapshots * 2);
// start server again
zks = new ZooKeeperServer(tmpDir, tmpDir, 3000);
@@ -127,7 +123,8 @@ public class RestoreCommittedLogTest extends ZKTestCase{
Collection<Proposal> committedLog = zks.getZKDatabase().getCommittedLog();
int logsize = committedLog.size();
LOG.info("committedLog size = {}", logsize);
- Assert.assertTrue("log size != 0", (logsize != 0));
+ assertTrue("log size != 0", (logsize != 0));
zks.shutdown();
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/SSLAuthTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/SSLAuthTest.java
index cd360c190..ddfa48dd3 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/SSLAuthTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/SSLAuthTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -15,26 +15,26 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
package org.apache.zookeeper.test;
+import static org.junit.Assert.assertFalse;
import java.net.InetSocketAddress;
import java.util.concurrent.TimeUnit;
-
import org.apache.zookeeper.PortAssignment;
import org.apache.zookeeper.TestableZooKeeper;
import org.apache.zookeeper.client.ZKClientConfig;
import org.apache.zookeeper.common.ClientX509Util;
import org.apache.zookeeper.server.ServerCnxnFactory;
import org.junit.After;
-import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
public class SSLAuthTest extends ClientBase {
-
+
private ClientX509Util clientX509Util;
- public static ClientX509Util setUpSecure() throws Exception{
+ public static ClientX509Util setUpSecure() throws Exception {
ClientX509Util x509Util = new ClientX509Util();
String testDataPath = System.getProperty("test.data.dir", "src/test/resources/data");
System.setProperty(ServerCnxnFactory.ZOOKEEPER_SERVER_CNXN_FACTORY, "org.apache.zookeeper.server.NettyServerCnxnFactory");
@@ -63,7 +63,7 @@ public class SSLAuthTest extends ClientBase {
System.clearProperty("zookeeper.authProvider.x509");
clientX509Util.close();
}
-
+
@Before
public void setUp() throws Exception {
clientX509Util = setUpSecure();
@@ -88,15 +88,15 @@ public class SSLAuthTest extends ClientBase {
String testDataPath = System.getProperty("test.data.dir", "src/test/resources/data");
// Replace trusted keys with a valid key that is not trusted by the server
- System.setProperty(clientX509Util.getSslKeystoreLocationProperty(), testDataPath + "/ssl/testUntrustedKeyStore.jks");
+ System.setProperty(clientX509Util.getSslKeystoreLocationProperty(), testDataPath
+ + "/ssl/testUntrustedKeyStore.jks");
System.setProperty(clientX509Util.getSslKeystorePasswdProperty(), "testpass");
CountdownWatcher watcher = new CountdownWatcher();
// Handshake will take place, and then X509AuthenticationProvider should reject the untrusted cert
new TestableZooKeeper(hostPort, CONNECTION_TIMEOUT, watcher);
- Assert.assertFalse("Untrusted certificate should not result in successful connection",
- watcher.clientConnected.await(1000, TimeUnit.MILLISECONDS));
+ assertFalse("Untrusted certificate should not result in successful connection", watcher.clientConnected.await(1000, TimeUnit.MILLISECONDS));
}
@Test
@@ -109,7 +109,7 @@ public class SSLAuthTest extends ClientBase {
CountdownWatcher watcher = new CountdownWatcher();
new TestableZooKeeper(hostPort, CONNECTION_TIMEOUT, watcher);
- Assert.assertFalse("Missing SSL configuration should not result in successful connection",
- watcher.clientConnected.await(1000, TimeUnit.MILLISECONDS));
+ assertFalse("Missing SSL configuration should not result in successful connection", watcher.clientConnected.await(1000, TimeUnit.MILLISECONDS));
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/SaslAuthDesignatedClientTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/SaslAuthDesignatedClientTest.java
index c007022c0..95db15086 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/SaslAuthDesignatedClientTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/SaslAuthDesignatedClientTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,56 +18,61 @@
package org.apache.zookeeper.test;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertSame;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
-
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
-import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooDefs.Perms;
+import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.client.ZKClientConfig;
import org.apache.zookeeper.client.ZooKeeperSaslClient;
import org.apache.zookeeper.data.ACL;
import org.apache.zookeeper.data.Id;
-import org.junit.Assert;
import org.junit.Test;
public class SaslAuthDesignatedClientTest extends ClientBase {
+
static {
- System.setProperty("zookeeper.authProvider.1","org.apache.zookeeper.server.auth.SASLAuthenticationProvider");
- System.setProperty(ZKClientConfig.LOGIN_CONTEXT_NAME_KEY,
- "MyZookeeperClient");
+ System.setProperty("zookeeper.authProvider.1", "org.apache.zookeeper.server.auth.SASLAuthenticationProvider");
+ System.setProperty(ZKClientConfig.LOGIN_CONTEXT_NAME_KEY, "MyZookeeperClient");
try {
File tmpDir = createTmpDir();
File saslConfFile = new File(tmpDir, "jaas.conf");
FileWriter fwriter = new FileWriter(saslConfFile);
- fwriter.write("" +
- "Server {\n" +
- " org.apache.zookeeper.server.auth.DigestLoginModule required\n" +
- " user_myuser=\"mypassword\";\n" +
- "};\n" +
- "Client {\n" + /* this 'Client' section has an incorrect password, but we're not configured
- to use it (we're configured by the above System.setProperty(...LOGIN_CONTEXT_NAME_KEY...) to
+ fwriter.write(""
+ + "Server {\n"
+ + " org.apache.zookeeper.server.auth.DigestLoginModule required\n"
+ + " user_myuser=\"mypassword\";\n"
+ + "};\n"
+ + "Client {\n"
+ + /* this 'Client' section has an incorrect password, but we're not configured
+ to use it (we're configured by the above System.setProperty(...LOGIN_CONTEXT_NAME_KEY...) to
use the 'MyZookeeperClient' section below, which has the correct password).*/
- " org.apache.zookeeper.server.auth.DigestLoginModule required\n" +
- " username=\"myuser\"\n" +
- " password=\"wrongpassword\";\n" +
- "};" +
- "MyZookeeperClient {\n" +
- " org.apache.zookeeper.server.auth.DigestLoginModule required\n" +
- " username=\"myuser\"\n" +
- " password=\"mypassword\";\n" +
- "};" + "\n");
+ " org.apache.zookeeper.server.auth.DigestLoginModule required\n"
+ + " username=\"myuser\"\n"
+ + " password=\"wrongpassword\";\n"
+ + "};"
+ + "MyZookeeperClient {\n"
+ + " org.apache.zookeeper.server.auth.DigestLoginModule required\n"
+ + " username=\"myuser\"\n"
+ + " password=\"mypassword\";\n"
+ + "};"
+ + "\n");
fwriter.close();
- System.setProperty("java.security.auth.login.config",saslConfFile.getAbsolutePath());
- }
- catch (IOException e) {
+ System.setProperty("java.security.auth.login.config", saslConfFile.getAbsolutePath());
+ } catch (IOException e) {
// could not create tmp directory to hold JAAS conf file : test will fail now.
}
}
@@ -79,9 +84,8 @@ public class SaslAuthDesignatedClientTest extends ClientBase {
zk.create("/path1", null, Ids.CREATOR_ALL_ACL, CreateMode.PERSISTENT);
Thread.sleep(1000);
} catch (KeeperException e) {
- Assert.fail("test failed :" + e);
- }
- finally {
+ fail("test failed :" + e);
+ } finally {
zk.close();
}
}
@@ -91,17 +95,14 @@ public class SaslAuthDesignatedClientTest extends ClientBase {
ZooKeeper zk = createClient();
try {
zk.getChildren("/", false);
- Assert.assertFalse(zk.getSaslClient().
- clientTunneledAuthenticationInProgress());
- Assert.assertEquals(zk.getSaslClient().getSaslState(),
- ZooKeeperSaslClient.SaslState.COMPLETE);
- Assert.assertNotNull(
- javax.security.auth.login.Configuration.getConfiguration().
- getAppConfigurationEntry("MyZookeeperClient"));
- Assert.assertSame(zk.getSaslClient().getLoginContext(),
- "MyZookeeperClient");
+ assertFalse(zk.getSaslClient().
+ clientTunneledAuthenticationInProgress());
+ assertEquals(zk.getSaslClient().getSaslState(), ZooKeeperSaslClient.SaslState.COMPLETE);
+ assertNotNull(javax.security.auth.login.Configuration.getConfiguration().
+ getAppConfigurationEntry("MyZookeeperClient"));
+ assertSame(zk.getSaslClient().getLoginContext(), "MyZookeeperClient");
} catch (KeeperException e) {
- Assert.fail("test failed :" + e);
+ fail("test failed :" + e);
} finally {
zk.close();
}
@@ -109,58 +110,58 @@ public class SaslAuthDesignatedClientTest extends ClientBase {
@Test
public void testReadAccessUser() throws Exception {
- System.setProperty("zookeeper.letAnySaslUserDoX","anyone");
- ZooKeeper zk = createClient();
- List<ACL> aclList = new ArrayList<ACL>();
- ACL acl = new ACL(Perms.ADMIN | Perms.CREATE | Perms.WRITE | Perms.DELETE, new Id("sasl", "fakeuser"));
- ACL acl1 = new ACL(Perms.READ, new Id("sasl", "anyone"));
- aclList.add(acl);
- aclList.add(acl1);
- try {
- zk.create("/abc", "testData".getBytes(), aclList, CreateMode.PERSISTENT);
- } catch (KeeperException e) {
- Assert.fail("Unable to create znode");
- }
- zk.close();
- Thread.sleep(100);
-
- // try to access it with different user (myuser)
- zk = createClient();
-
- try {
- zk.setData("/abc", "testData1".getBytes(), -1);
- Assert.fail("Should not be able to set data");
- } catch (KeeperException.NoAuthException e) {
- // success
- }
-
- try {
- byte [] bytedata = zk.getData("/abc", null, null);
- String data = new String(bytedata);
- Assert.assertTrue("testData".equals(data));
- } catch (KeeperException e) {
- Assert.fail("failed to get data");
- }
-
- zk.close();
- Thread.sleep(100);
-
- // disable Client Sasl
- System.setProperty(ZKClientConfig.ENABLE_CLIENT_SASL_KEY, "false");
-
- try {
+ System.setProperty("zookeeper.letAnySaslUserDoX", "anyone");
+ ZooKeeper zk = createClient();
+ List<ACL> aclList = new ArrayList<ACL>();
+ ACL acl = new ACL(Perms.ADMIN | Perms.CREATE | Perms.WRITE | Perms.DELETE, new Id("sasl", "fakeuser"));
+ ACL acl1 = new ACL(Perms.READ, new Id("sasl", "anyone"));
+ aclList.add(acl);
+ aclList.add(acl1);
+ try {
+ zk.create("/abc", "testData".getBytes(), aclList, CreateMode.PERSISTENT);
+ } catch (KeeperException e) {
+ fail("Unable to create znode");
+ }
+ zk.close();
+ Thread.sleep(100);
+
+ // try to access it with different user (myuser)
zk = createClient();
+
try {
- zk.getData("/abc", null, null);
- Assert.fail("Should not be able to read data when not authenticated");
+ zk.setData("/abc", "testData1".getBytes(), -1);
+ fail("Should not be able to set data");
} catch (KeeperException.NoAuthException e) {
- // success
+ // success
}
+
+ try {
+ byte[] bytedata = zk.getData("/abc", null, null);
+ String data = new String(bytedata);
+ assertTrue("testData".equals(data));
+ } catch (KeeperException e) {
+ fail("failed to get data");
+ }
+
zk.close();
- } finally {
- // enable Client Sasl
- System.setProperty(ZKClientConfig.ENABLE_CLIENT_SASL_KEY,
- "true");
- }
+ Thread.sleep(100);
+
+ // disable Client Sasl
+ System.setProperty(ZKClientConfig.ENABLE_CLIENT_SASL_KEY, "false");
+
+ try {
+ zk = createClient();
+ try {
+ zk.getData("/abc", null, null);
+ fail("Should not be able to read data when not authenticated");
+ } catch (KeeperException.NoAuthException e) {
+ // success
+ }
+ zk.close();
+ } finally {
+ // enable Client Sasl
+ System.setProperty(ZKClientConfig.ENABLE_CLIENT_SASL_KEY, "true");
+ }
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/SaslAuthDesignatedServerTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/SaslAuthDesignatedServerTest.java
index aa30870da..bbe12c927 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/SaslAuthDesignatedServerTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/SaslAuthDesignatedServerTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,29 +18,27 @@
package org.apache.zookeeper.test;
-import java.io.File;
-import java.io.FileWriter;
-import java.io.IOException;
-import java.util.concurrent.atomic.AtomicInteger;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.fail;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
-
+import java.util.concurrent.atomic.AtomicInteger;
import org.apache.zookeeper.CreateMode;
+import org.apache.zookeeper.JaasConfiguration;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
-import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.Watcher.Event.KeeperState;
import org.apache.zookeeper.ZooDefs.Ids;
+import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.server.ZooKeeperSaslServer;
-import org.apache.zookeeper.JaasConfiguration;
-import org.junit.Assert;
import org.junit.Test;
public class SaslAuthDesignatedServerTest extends ClientBase {
+
public static int AUTHENTICATION_TIMEOUT = 30000;
static {
- System.setProperty("zookeeper.authProvider.1","org.apache.zookeeper.server.auth.SASLAuthenticationProvider");
+ System.setProperty("zookeeper.authProvider.1", "org.apache.zookeeper.server.auth.SASLAuthenticationProvider");
System.setProperty(ZooKeeperSaslServer.LOGIN_CONTEXT_NAME_KEY, "MyZookeeperServer");
JaasConfiguration conf = new JaasConfiguration();
@@ -49,14 +47,11 @@ public class SaslAuthDesignatedServerTest extends ClientBase {
* to use it (we're configured by the above System.setProperty(...LOGIN_CONTEXT_NAME_KEY...)
* to use the 'MyZookeeperServer' section below, which has the correct password).
*/
- conf.addSection("Server", "org.apache.zookeeper.server.auth.DigestLoginModule",
- "user_myuser", "wrongpassword");
+ conf.addSection("Server", "org.apache.zookeeper.server.auth.DigestLoginModule", "user_myuser", "wrongpassword");
- conf.addSection("MyZookeeperServer", "org.apache.zookeeper.server.auth.DigestLoginModule",
- "user_myuser", "mypassword");
+ conf.addSection("MyZookeeperServer", "org.apache.zookeeper.server.auth.DigestLoginModule", "user_myuser", "mypassword");
- conf.addSection("Client", "org.apache.zookeeper.server.auth.DigestLoginModule",
- "username", "myuser", "password", "mypassword");
+ conf.addSection("Client", "org.apache.zookeeper.server.auth.DigestLoginModule", "username", "myuser", "password", "mypassword");
javax.security.auth.login.Configuration.setConfiguration(conf);
}
@@ -64,10 +59,11 @@ public class SaslAuthDesignatedServerTest extends ClientBase {
private AtomicInteger authFailed = new AtomicInteger(0);
private class MyWatcher extends CountdownWatcher {
+
volatile CountDownLatch authCompleted;
@Override
- synchronized public void reset() {
+ public synchronized void reset() {
authCompleted = new CountDownLatch(1);
super.reset();
}
@@ -83,6 +79,7 @@ public class SaslAuthDesignatedServerTest extends ClientBase {
super.process(event);
}
}
+
}
@Test
@@ -90,15 +87,15 @@ public class SaslAuthDesignatedServerTest extends ClientBase {
MyWatcher watcher = new MyWatcher();
ZooKeeper zk = createClient(watcher);
watcher.authCompleted.await(AUTHENTICATION_TIMEOUT, TimeUnit.MILLISECONDS);
- Assert.assertEquals(authFailed.get(), 0);
+ assertEquals(authFailed.get(), 0);
try {
zk.create("/path1", null, Ids.CREATOR_ALL_ACL, CreateMode.PERSISTENT);
} catch (KeeperException e) {
- Assert.fail("test failed :" + e);
- }
- finally {
+ fail("test failed :" + e);
+ } finally {
zk.close();
}
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/SaslAuthFailDesignatedClientTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/SaslAuthFailDesignatedClientTest.java
index df8c9033b..241d7861b 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/SaslAuthFailDesignatedClientTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/SaslAuthFailDesignatedClientTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,75 +18,72 @@
package org.apache.zookeeper.test;
+import static org.junit.Assert.fail;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
-
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.TestableZooKeeper;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.client.ZKClientConfig;
-import org.junit.Assert;
import org.junit.Test;
public class SaslAuthFailDesignatedClientTest extends ClientBase {
+
static {
- System.setProperty("zookeeper.authProvider.1","org.apache.zookeeper.server.auth.SASLAuthenticationProvider");
- System.setProperty(ZKClientConfig.LOGIN_CONTEXT_NAME_KEY,
- "MyZookeeperClient");
+ System.setProperty("zookeeper.authProvider.1", "org.apache.zookeeper.server.auth.SASLAuthenticationProvider");
+ System.setProperty(ZKClientConfig.LOGIN_CONTEXT_NAME_KEY, "MyZookeeperClient");
try {
File tmpDir = createTmpDir();
File saslConfFile = new File(tmpDir, "jaas.conf");
FileWriter fwriter = new FileWriter(saslConfFile);
- fwriter.write("" +
- "Server {\n" +
- " org.apache.zookeeper.server.auth.DigestLoginModule required\n" +
- " user_myuser=\"mypassword\";\n" +
- "};\n" +
- "Client {\n" + /* this 'Client' section has the correct password, but we're not configured
- to use it (we're configured by the above System.setProperty(...LOGIN_CONTEXT_NAME_KEY...) to
- use the 'MyZookeeperClient' section, which has an incorrect password).*/
- " org.apache.zookeeper.server.auth.DigestLoginModule required\n" +
- " username=\"myuser\"\n" +
- " password=\"mypassword\";\n" +
- "};" +
- "MyZookeeperClient {\n" +
- " org.apache.zookeeper.server.auth.DigestLoginModule required\n" +
- " username=\"myuser\"\n" +
- " password=\"wrongpassword\";\n" +
- "};" + "\n");
+ fwriter.write("Server {\n"
+ + " org.apache.zookeeper.server.auth.DigestLoginModule required\n"
+ + " user_myuser=\"mypassword\";\n"
+ + "};\n"
+ + "Client {\n"
+ + /* this 'Client' section has the correct password, but we're not configured
+ to use it (we're configured by the above System.setProperty(...LOGIN_CONTEXT_NAME_KEY...) to
+ use the 'MyZookeeperClient' section, which has an incorrect password).*/
+ " org.apache.zookeeper.server.auth.DigestLoginModule required\n"
+ + " username=\"myuser\"\n"
+ + " password=\"mypassword\";\n"
+ + "};"
+ + "MyZookeeperClient {\n"
+ + " org.apache.zookeeper.server.auth.DigestLoginModule required\n"
+ + " username=\"myuser\"\n"
+ + " password=\"wrongpassword\";\n"
+ + "};"
+ + "\n");
fwriter.close();
- System.setProperty("java.security.auth.login.config",saslConfFile.getAbsolutePath());
- }
- catch (IOException e) {
+ System.setProperty("java.security.auth.login.config", saslConfFile.getAbsolutePath());
+ } catch (IOException e) {
// could not create tmp directory to hold JAAS conf file : test will fail now.
}
}
-
@Test
public void testAuth() throws Exception {
- // Cannot use createClient here because server may close session before
+ // Cannot use createClient here because server may close session before
// JMXEnv.ensureAll is called which will fail the test case
CountdownWatcher watcher = new CountdownWatcher();
TestableZooKeeper zk = new TestableZooKeeper(hostPort, CONNECTION_TIMEOUT, watcher);
- if (!watcher.clientConnected.await(CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS))
- {
- Assert.fail("Unable to connect to server");
+ if (!watcher.clientConnected.await(CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS)) {
+ fail("Unable to connect to server");
}
try {
zk.create("/path1", null, Ids.CREATOR_ALL_ACL, CreateMode.PERSISTENT);
- Assert.fail("Should have gotten exception.");
+ fail("Should have gotten exception.");
} catch (KeeperException e) {
// ok, exception as expected.
LOG.info("Got exception as expected: " + e);
- }
- finally {
+ } finally {
zk.close();
}
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/SaslAuthFailTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/SaslAuthFailTest.java
index d0847fb09..8a6bd957f 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/SaslAuthFailTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/SaslAuthFailTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,43 +18,44 @@
package org.apache.zookeeper.test;
+import static org.junit.Assert.fail;
+import java.io.File;
+import java.io.FileWriter;
+import java.io.IOException;
+import java.util.concurrent.CountDownLatch;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher.Event.KeeperState;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;
-import org.junit.Assert;
import org.junit.Test;
-import java.io.File;
-import java.io.FileWriter;
-import java.io.IOException;
-import java.util.concurrent.CountDownLatch;
-
public class SaslAuthFailTest extends ClientBase {
+
static {
- System.setProperty("zookeeper.authProvider.1","org.apache.zookeeper.server.auth.SASLAuthenticationProvider");
- System.setProperty("zookeeper.allowSaslFailedClients","true");
+ System.setProperty("zookeeper.authProvider.1", "org.apache.zookeeper.server.auth.SASLAuthenticationProvider");
+ System.setProperty("zookeeper.allowSaslFailedClients", "true");
try {
File tmpDir = createTmpDir();
File saslConfFile = new File(tmpDir, "jaas.conf");
FileWriter fwriter = new FileWriter(saslConfFile);
- fwriter.write("" +
- "Server {\n" +
- " org.apache.zookeeper.server.auth.DigestLoginModule required\n" +
- " user_super=\"test\";\n" +
- "};\n" +
- "Client {\n" +
- " org.apache.zookeeper.server.auth.DigestLoginModule required\n" +
- " username=\"super\"\n" +
- " password=\"test1\";\n" + // NOTE: wrong password ('test' != 'test1') : this is to test SASL authentication failure.
- "};" + "\n");
+ fwriter.write("Server {\n"
+ + " org.apache.zookeeper.server.auth.DigestLoginModule required\n"
+ + " user_super=\"test\";\n"
+ + "};\n"
+ + "Client {\n"
+ + " org.apache.zookeeper.server.auth.DigestLoginModule required\n"
+ + " username=\"super\"\n"
+ + " password=\"test1\";\n"
+ +
+ // NOTE: wrong password ('test' != 'test1') : this is to test SASL authentication failure.
+ "};"
+ + "\n");
fwriter.close();
- System.setProperty("java.security.auth.login.config",saslConfFile.getAbsolutePath());
- }
- catch (IOException e) {
+ System.setProperty("java.security.auth.login.config", saslConfFile.getAbsolutePath());
+ } catch (IOException e) {
// could not create tmp directory to hold JAAS conf file.
}
}
@@ -62,22 +63,23 @@ public class SaslAuthFailTest extends ClientBase {
private CountDownLatch authFailed = new CountDownLatch(1);
private class MyWatcher extends CountdownWatcher {
+
@Override
public synchronized void process(WatchedEvent event) {
if (event.getState() == KeeperState.AuthFailed) {
authFailed.countDown();
- }
- else {
+ } else {
super.process(event);
}
}
+
}
-
+
@Test
public void testAuthFail() {
try (ZooKeeper zk = createClient()) {
zk.create("/path1", null, Ids.CREATOR_ALL_ACL, CreateMode.PERSISTENT);
- Assert.fail("Should have gotten exception.");
+ fail("Should have gotten exception.");
} catch (Exception e) {
// ok, exception as expected.
LOG.info("Got exception as expected: " + e);
@@ -91,4 +93,5 @@ public class SaslAuthFailTest extends ClientBase {
authFailed.await();
}
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/SaslAuthMissingClientConfigTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/SaslAuthMissingClientConfigTest.java
index ee013872f..efe52d6fb 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/SaslAuthMissingClientConfigTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/SaslAuthMissingClientConfigTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,48 +18,47 @@
package org.apache.zookeeper.test;
+import static org.junit.Assert.fail;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
-
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.client.ZKClientConfig;
-import org.junit.Assert;
import org.junit.Test;
public class SaslAuthMissingClientConfigTest extends ClientBase {
+
static {
- System.setProperty("zookeeper.authProvider.1","org.apache.zookeeper.server.auth.SASLAuthenticationProvider");
+ System.setProperty("zookeeper.authProvider.1", "org.apache.zookeeper.server.auth.SASLAuthenticationProvider");
// This configuration section 'MyZookeeperClient', is missing from the JAAS configuration.
// As a result, SASL authentication should fail, which is tested by this test (testAuth()).
- System.setProperty(ZKClientConfig.LOGIN_CONTEXT_NAME_KEY,
- "MyZookeeperClient");
+ System.setProperty(ZKClientConfig.LOGIN_CONTEXT_NAME_KEY, "MyZookeeperClient");
try {
File tmpDir = createTmpDir();
File saslConfFile = new File(tmpDir, "jaas.conf");
FileWriter fwriter = new FileWriter(saslConfFile);
- fwriter.write("" +
- "Server {\n" +
- " org.apache.zookeeper.server.auth.DigestLoginModule required\n" +
- " user_myuser=\"mypassword\";\n" +
- "};\n" +
- "Client {\n" + /* this 'Client' section has the correct password, but we're not configured
+ fwriter.write(""
+ + "Server {\n"
+ + " org.apache.zookeeper.server.auth.DigestLoginModule required\n"
+ + " user_myuser=\"mypassword\";\n"
+ + "};\n"
+ + "Client {\n"
+ + /* this 'Client' section has the correct password, but we're not configured
to use it - we're configured instead by the above
System.setProperty(...LOGIN_CONTEXT_NAME_KEY...) to
use the (nonexistent) 'MyZookeeperClient' section. */
- " org.apache.zookeeper.server.auth.DigestLoginModule required\n" +
- " username=\"myuser\"\n" +
- " password=\"mypassword\";\n" +
- "};\n");
+ " org.apache.zookeeper.server.auth.DigestLoginModule required\n"
+ + " username=\"myuser\"\n"
+ + " password=\"mypassword\";\n"
+ + "};\n");
fwriter.close();
- System.setProperty("java.security.auth.login.config",saslConfFile.getAbsolutePath());
- }
- catch (IOException e) {
+ System.setProperty("java.security.auth.login.config", saslConfFile.getAbsolutePath());
+ } catch (IOException e) {
// could not create tmp directory to hold JAAS conf file : test will fail now.
}
}
@@ -69,13 +68,13 @@ public class SaslAuthMissingClientConfigTest extends ClientBase {
ZooKeeper zk = createClient();
try {
zk.create("/path1", null, Ids.CREATOR_ALL_ACL, CreateMode.PERSISTENT);
- Assert.fail("Should have gotten exception.");
+ fail("Should have gotten exception.");
} catch (KeeperException e) {
// ok, exception as expected.
LOG.info("Got exception as expected: " + e);
- }
- finally {
+ } finally {
zk.close();
}
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/SaslAuthRequiredFailNoSASLTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/SaslAuthRequiredFailNoSASLTest.java
index 1bb59d15b..e60fcc452 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/SaslAuthRequiredFailNoSASLTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/SaslAuthRequiredFailNoSASLTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,45 +18,47 @@
package org.apache.zookeeper.test;
-import org.apache.zookeeper.ZooKeeper;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooDefs.Ids;
+import org.apache.zookeeper.ZooKeeper;
import org.junit.After;
-import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
public class SaslAuthRequiredFailNoSASLTest extends ClientBase {
- @Before
- public void setup() {
- System.setProperty(SaslTestUtil.requireSASLAuthProperty, "true");
- }
-
- @After
- public void tearDown() throws Exception {
- System.clearProperty(SaslTestUtil.requireSASLAuthProperty);
- }
-
- @Test
- public void testClientOpWithoutSASLConfigured() throws Exception {
- ZooKeeper zk = null;
- CountdownWatcher watcher = new CountdownWatcher();
- try {
- zk = createClient(watcher);
- zk.create("/foo", null, Ids.CREATOR_ALL_ACL, CreateMode.PERSISTENT);
- Assert.fail("Client is not configured with SASL authentication, so zk.create operation should fail.");
- } catch(KeeperException e) {
- Assert.assertTrue(e.code() == KeeperException.Code.SESSIONCLOSEDREQUIRESASLAUTH);
- // Verify that "eventually" (within the bound of timeouts)
- // this client closes the connection between itself and the server.
- watcher.waitForDisconnected(SaslTestUtil.CLIENT_DISCONNECT_TIMEOUT);
- } finally {
- if (zk != null) {
- zk.close();
- }
+
+ @Before
+ public void setup() {
+ System.setProperty(SaslTestUtil.requireSASLAuthProperty, "true");
+ }
+
+ @After
+ public void tearDown() throws Exception {
+ System.clearProperty(SaslTestUtil.requireSASLAuthProperty);
+ }
+
+ @Test
+ public void testClientOpWithoutSASLConfigured() throws Exception {
+ ZooKeeper zk = null;
+ CountdownWatcher watcher = new CountdownWatcher();
+ try {
+ zk = createClient(watcher);
+ zk.create("/foo", null, Ids.CREATOR_ALL_ACL, CreateMode.PERSISTENT);
+ fail("Client is not configured with SASL authentication, so zk.create operation should fail.");
+ } catch (KeeperException e) {
+ assertTrue(e.code() == KeeperException.Code.SESSIONCLOSEDREQUIRESASLAUTH);
+ // Verify that "eventually" (within the bound of timeouts)
+ // this client closes the connection between itself and the server.
+ watcher.waitForDisconnected(SaslTestUtil.CLIENT_DISCONNECT_TIMEOUT);
+ } finally {
+ if (zk != null) {
+ zk.close();
+ }
+ }
}
- }
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/SaslAuthRequiredFailWrongSASLTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/SaslAuthRequiredFailWrongSASLTest.java
index f6c6e33a8..1fed4d93c 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/SaslAuthRequiredFailWrongSASLTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/SaslAuthRequiredFailWrongSASLTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,47 +18,49 @@
package org.apache.zookeeper.test;
-import org.apache.zookeeper.ZooKeeper;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooDefs.Ids;
-import org.junit.Assert;
+import org.apache.zookeeper.ZooKeeper;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
public class SaslAuthRequiredFailWrongSASLTest extends ClientBase {
- @BeforeClass
- public static void setUpBeforeClass() {
- System.setProperty(SaslTestUtil.requireSASLAuthProperty, "true");
- System.setProperty(SaslTestUtil.authProviderProperty, SaslTestUtil.authProvider);
- System.setProperty(SaslTestUtil.jaasConfig,
- SaslTestUtil.createJAASConfigFile("jaas_wrong.conf", "test1"));
- }
- @AfterClass
- public static void tearDownAfterClass() {
- System.clearProperty(SaslTestUtil.requireSASLAuthProperty);
- System.clearProperty(SaslTestUtil.authProviderProperty);
- System.clearProperty(SaslTestUtil.jaasConfig);
- }
+ @BeforeClass
+ public static void setUpBeforeClass() {
+ System.setProperty(SaslTestUtil.requireSASLAuthProperty, "true");
+ System.setProperty(SaslTestUtil.authProviderProperty, SaslTestUtil.authProvider);
+ System.setProperty(SaslTestUtil.jaasConfig, SaslTestUtil.createJAASConfigFile("jaas_wrong.conf", "test1"));
+ }
+
+ @AfterClass
+ public static void tearDownAfterClass() {
+ System.clearProperty(SaslTestUtil.requireSASLAuthProperty);
+ System.clearProperty(SaslTestUtil.authProviderProperty);
+ System.clearProperty(SaslTestUtil.jaasConfig);
+ }
- @Test
- public void testClientOpWithFailedSASLAuth() throws Exception {
- ZooKeeper zk = null;
- CountdownWatcher watcher = new CountdownWatcher();
- try {
- zk = createClient(watcher);
- zk.create("/bar", null, Ids.CREATOR_ALL_ACL, CreateMode.PERSISTENT);
- Assert.fail("Client with wrong SASL config should not pass SASL authentication.");
- } catch(KeeperException e) {
- Assert.assertTrue(e.code() == KeeperException.Code.AUTHFAILED);
- // Verify that "eventually" this client closes the connection between itself and the server.
- watcher.waitForDisconnected(SaslTestUtil.CLIENT_DISCONNECT_TIMEOUT);
- } finally {
- if (zk != null) {
- zk.close();
- }
+ @Test
+ public void testClientOpWithFailedSASLAuth() throws Exception {
+ ZooKeeper zk = null;
+ CountdownWatcher watcher = new CountdownWatcher();
+ try {
+ zk = createClient(watcher);
+ zk.create("/bar", null, Ids.CREATOR_ALL_ACL, CreateMode.PERSISTENT);
+ fail("Client with wrong SASL config should not pass SASL authentication.");
+ } catch (KeeperException e) {
+ assertTrue(e.code() == KeeperException.Code.AUTHFAILED);
+ // Verify that "eventually" this client closes the connection between itself and the server.
+ watcher.waitForDisconnected(SaslTestUtil.CLIENT_DISCONNECT_TIMEOUT);
+ } finally {
+ if (zk != null) {
+ zk.close();
+ }
+ }
}
- }
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/SaslAuthRequiredTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/SaslAuthRequiredTest.java
index 54b0c5830..173a3cbf3 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/SaslAuthRequiredTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/SaslAuthRequiredTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,45 +18,45 @@
package org.apache.zookeeper.test;
-import org.apache.zookeeper.ZooKeeper;
+import static org.junit.Assert.fail;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooDefs.Ids;
+import org.apache.zookeeper.ZooKeeper;
import org.junit.AfterClass;
-import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
public class SaslAuthRequiredTest extends ClientBase {
- @BeforeClass
- public static void setUpBeforeClass() {
- System.setProperty(SaslTestUtil.requireSASLAuthProperty, "true");
- System.setProperty(SaslTestUtil.authProviderProperty, SaslTestUtil.authProvider);
- System.setProperty(SaslTestUtil.jaasConfig,
- SaslTestUtil.createJAASConfigFile("jaas.conf", "test"));
- }
- @AfterClass
- public static void tearDownAfterClass() {
- System.clearProperty(SaslTestUtil.requireSASLAuthProperty);
- System.clearProperty(SaslTestUtil.authProviderProperty);
- System.clearProperty(SaslTestUtil.jaasConfig);
- }
+ @BeforeClass
+ public static void setUpBeforeClass() {
+ System.setProperty(SaslTestUtil.requireSASLAuthProperty, "true");
+ System.setProperty(SaslTestUtil.authProviderProperty, SaslTestUtil.authProvider);
+ System.setProperty(SaslTestUtil.jaasConfig, SaslTestUtil.createJAASConfigFile("jaas.conf", "test"));
+ }
+
+ @AfterClass
+ public static void tearDownAfterClass() {
+ System.clearProperty(SaslTestUtil.requireSASLAuthProperty);
+ System.clearProperty(SaslTestUtil.authProviderProperty);
+ System.clearProperty(SaslTestUtil.jaasConfig);
+ }
- @Test
- public void testClientOpWithValidSASLAuth() throws Exception {
- ZooKeeper zk = null;
- CountdownWatcher watcher = new CountdownWatcher();
- try {
- zk = createClient(watcher);
- zk.create("/foobar", null, Ids.CREATOR_ALL_ACL, CreateMode.PERSISTENT);
- } catch(KeeperException e) {
- Assert.fail("Client operation should succeed with valid SASL configuration.");
- } finally {
- if (zk != null) {
- zk.close();
- }
+ @Test
+ public void testClientOpWithValidSASLAuth() throws Exception {
+ ZooKeeper zk = null;
+ CountdownWatcher watcher = new CountdownWatcher();
+ try {
+ zk = createClient(watcher);
+ zk.create("/foobar", null, Ids.CREATOR_ALL_ACL, CreateMode.PERSISTENT);
+ } catch (KeeperException e) {
+ fail("Client operation should succeed with valid SASL configuration.");
+ } finally {
+ if (zk != null) {
+ zk.close();
+ }
+ }
}
- }
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/SaslClientTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/SaslClientTest.java
index 95bf2f6af..adc690275 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/SaslClientTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/SaslClientTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,52 +18,46 @@
package org.apache.zookeeper.test;
-
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import java.util.Arrays;
import org.apache.zookeeper.ZKTestCase;
import org.apache.zookeeper.client.ZKClientConfig;
import org.junit.After;
-import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
-import java.util.Arrays;
public class SaslClientTest extends ZKTestCase {
private String existingPropertyValue = null;
@Before
public void setUp() {
- existingPropertyValue = System
- .getProperty(ZKClientConfig.ENABLE_CLIENT_SASL_KEY);
+ existingPropertyValue = System.getProperty(ZKClientConfig.ENABLE_CLIENT_SASL_KEY);
}
@After
public void tearDown() {
// Restore the System property if it was set previously
if (existingPropertyValue != null) {
- System.setProperty(ZKClientConfig.ENABLE_CLIENT_SASL_KEY,
- existingPropertyValue);
+ System.setProperty(ZKClientConfig.ENABLE_CLIENT_SASL_KEY, existingPropertyValue);
}
}
@Test
public void testSaslClientDisabled() {
System.clearProperty(ZKClientConfig.ENABLE_CLIENT_SASL_KEY);
- Assert.assertTrue("SASL client disabled",
- new ZKClientConfig().isSaslClientEnabled());
+ assertTrue("SASL client disabled", new ZKClientConfig().isSaslClientEnabled());
for (String value : Arrays.asList("true", "TRUE")) {
- System.setProperty(ZKClientConfig.ENABLE_CLIENT_SASL_KEY,
- value);
- Assert.assertTrue("SASL client disabled",
- new ZKClientConfig().isSaslClientEnabled());
+ System.setProperty(ZKClientConfig.ENABLE_CLIENT_SASL_KEY, value);
+ assertTrue("SASL client disabled", new ZKClientConfig().isSaslClientEnabled());
}
for (String value : Arrays.asList("false", "FALSE")) {
- System.setProperty(ZKClientConfig.ENABLE_CLIENT_SASL_KEY,
- value);
- Assert.assertFalse("SASL client disabled",
- new ZKClientConfig().isSaslClientEnabled());
+ System.setProperty(ZKClientConfig.ENABLE_CLIENT_SASL_KEY, value);
+ assertFalse("SASL client disabled", new ZKClientConfig().isSaslClientEnabled());
}
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/SaslSuperUserTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/SaslSuperUserTest.java
index 894c0f5d1..426eeb16f 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/SaslSuperUserTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/SaslSuperUserTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,28 +18,28 @@
package org.apache.zookeeper.test;
+import static org.junit.Assert.assertEquals;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Arrays;
import java.util.concurrent.atomic.AtomicInteger;
-
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.TestableZooKeeper;
import org.apache.zookeeper.WatchedEvent;
-import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.Watcher.Event.KeeperState;
import org.apache.zookeeper.ZooDefs.Perms;
+import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.ACL;
import org.apache.zookeeper.data.Id;
import org.apache.zookeeper.server.auth.DigestAuthenticationProvider;
-import org.junit.Assert;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
public class SaslSuperUserTest extends ClientBase {
- private static Id otherSaslUser = new Id ("sasl", "joe");
+
+ private static Id otherSaslUser = new Id("sasl", "joe");
private static Id otherDigestUser;
private static String oldAuthProvider;
private static String oldLoginConfig;
@@ -47,72 +47,72 @@ public class SaslSuperUserTest extends ClientBase {
@BeforeClass
public static void setupStatic() throws Exception {
- oldAuthProvider = System.setProperty("zookeeper.authProvider.1","org.apache.zookeeper.server.auth.SASLAuthenticationProvider");
+ oldAuthProvider = System.setProperty("zookeeper.authProvider.1", "org.apache.zookeeper.server.auth.SASLAuthenticationProvider");
File tmpDir = createTmpDir();
File saslConfFile = new File(tmpDir, "jaas.conf");
FileWriter fwriter = new FileWriter(saslConfFile);
- fwriter.write("" +
- "Server {\n" +
- " org.apache.zookeeper.server.auth.DigestLoginModule required\n" +
- " user_super_duper=\"test\";\n" +
- "};\n" +
- "Client {\n" +
- " org.apache.zookeeper.server.auth.DigestLoginModule required\n" +
- " username=\"super_duper\"\n" +
- " password=\"test\";\n" +
- "};" + "\n");
+ fwriter.write(""
+ + "Server {\n"
+ + " org.apache.zookeeper.server.auth.DigestLoginModule required\n"
+ + " user_super_duper=\"test\";\n"
+ + "};\n"
+ + "Client {\n"
+ + " org.apache.zookeeper.server.auth.DigestLoginModule required\n"
+ + " username=\"super_duper\"\n"
+ + " password=\"test\";\n"
+ + "};"
+ + "\n");
fwriter.close();
- oldLoginConfig = System.setProperty("java.security.auth.login.config",saslConfFile.getAbsolutePath());
- oldSuperUser = System.setProperty("zookeeper.superUser","super_duper");
- otherDigestUser = new Id ("digest", DigestAuthenticationProvider.generateDigest("jack:jack"));
+ oldLoginConfig = System.setProperty("java.security.auth.login.config", saslConfFile.getAbsolutePath());
+ oldSuperUser = System.setProperty("zookeeper.superUser", "super_duper");
+ otherDigestUser = new Id("digest", DigestAuthenticationProvider.generateDigest("jack:jack"));
}
@AfterClass
public static void cleanupStatic() {
if (oldAuthProvider != null) {
System.setProperty("zookeeper.authProvider.1", oldAuthProvider);
- } else {
+ } else {
System.clearProperty("zookeeper.authProvider.1");
- }
- oldAuthProvider = null;
+ }
+ oldAuthProvider = null;
if (oldLoginConfig != null) {
System.setProperty("java.security.auth.login.config", oldLoginConfig);
- } else {
+ } else {
System.clearProperty("java.security.auth.login.config");
- }
- oldLoginConfig = null;
+ }
+ oldLoginConfig = null;
if (oldSuperUser != null) {
System.setProperty("zookeeper.superUser", oldSuperUser);
- } else {
+ } else {
System.clearProperty("zookeeper.superUser");
- }
- oldSuperUser = null;
+ }
+ oldSuperUser = null;
}
private AtomicInteger authFailed = new AtomicInteger(0);
-
+
@Override
- protected TestableZooKeeper createClient(String hp)
- throws IOException, InterruptedException
- {
+ protected TestableZooKeeper createClient(String hp) throws IOException, InterruptedException {
MyWatcher watcher = new MyWatcher();
return createClient(watcher, hp);
}
private class MyWatcher extends CountdownWatcher {
+
@Override
public synchronized void process(WatchedEvent event) {
if (event.getState() == KeeperState.AuthFailed) {
authFailed.incrementAndGet();
- }
- else {
+ } else {
super.process(event);
}
}
+
}
@Test
@@ -128,9 +128,10 @@ public class SaslSuperUserTest extends ClientBase {
zk.delete("/sasl_read/sub", -1);
zk.delete("/sasl_read", -1);
//If the test failes it will most likely fail with a NoAuth exception before it ever gets to this assertion
- Assert.assertEquals(authFailed.get(), 0);
+ assertEquals(authFailed.get(), 0);
} finally {
zk.close();
}
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/SaslTestUtil.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/SaslTestUtil.java
index 4e0a337de..f787fb20c 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/SaslTestUtil.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/SaslTestUtil.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,44 +18,52 @@
package org.apache.zookeeper.test;
+import static org.junit.Assert.fail;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
-import org.junit.Assert;
-
public class SaslTestUtil extends ClientBase {
- // The maximum time (in milliseconds) a client should take to observe
- // a disconnect event of the same client from server.
- static Integer CLIENT_DISCONNECT_TIMEOUT = 3000;
- static String requireSASLAuthProperty = "zookeeper.sessionRequireClientSASLAuth";
- static String authProviderProperty = "zookeeper.authProvider.1";
- static String authProvider = "org.apache.zookeeper.server.auth.SASLAuthenticationProvider";
- static String digestLoginModule = "org.apache.zookeeper.server.auth.DigestLoginModule";
- static String jaasConfig = "java.security.auth.login.config";
- static String createJAASConfigFile(String fileName, String password) {
- String ret = null;
- try {
- File tmpDir = createTmpDir();
- File jaasFile = new File(tmpDir, fileName);
- FileWriter fwriter = new FileWriter(jaasFile);
- fwriter.write("" +
- "Server {\n" +
- " " + digestLoginModule + " required\n" +
- " user_super=\"test\";\n" +
- "};\n" +
- "Client {\n" +
- " " + digestLoginModule + " required\n" +
- " username=\"super\"\n" +
- " password=\"" + password + "\";\n" +
- "};" + "\n");
- fwriter.close();
- ret = jaasFile.getAbsolutePath();
- } catch (IOException e) {
- Assert.fail("Unable to create JaaS configuration file!");
+ // The maximum time (in milliseconds) a client should take to observe
+ // a disconnect event of the same client from server.
+ static Integer CLIENT_DISCONNECT_TIMEOUT = 3000;
+ static String requireSASLAuthProperty = "zookeeper.sessionRequireClientSASLAuth";
+ static String authProviderProperty = "zookeeper.authProvider.1";
+ static String authProvider = "org.apache.zookeeper.server.auth.SASLAuthenticationProvider";
+ static String digestLoginModule = "org.apache.zookeeper.server.auth.DigestLoginModule";
+ static String jaasConfig = "java.security.auth.login.config";
+
+ static String createJAASConfigFile(String fileName, String password) {
+ String ret = null;
+ try {
+ File tmpDir = createTmpDir();
+ File jaasFile = new File(tmpDir, fileName);
+ FileWriter fwriter = new FileWriter(jaasFile);
+ fwriter.write(""
+ + "Server {\n"
+ + " "
+ + digestLoginModule
+ + " required\n"
+ + " user_super=\"test\";\n"
+ + "};\n"
+ + "Client {\n"
+ + " "
+ + digestLoginModule
+ + " required\n"
+ + " username=\"super\"\n"
+ + " password=\""
+ + password
+ + "\";\n"
+ + "};"
+ + "\n");
+ fwriter.close();
+ ret = jaasFile.getAbsolutePath();
+ } catch (IOException e) {
+ fail("Unable to create JaaS configuration file!");
+ }
+
+ return ret;
}
- return ret;
- }
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/ServerCnxnTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/ServerCnxnTest.java
index 67ece2a30..dba9f8c93 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/ServerCnxnTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/ServerCnxnTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,40 +18,36 @@
package org.apache.zookeeper.test;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
-
import org.apache.zookeeper.server.NIOServerCnxnFactory;
import org.junit.After;
-import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-
public class ServerCnxnTest extends ClientBase {
- protected static final Logger LOG =
- LoggerFactory.getLogger(ServerCnxnTest.class);
+
+ protected static final Logger LOG = LoggerFactory.getLogger(ServerCnxnTest.class);
private static int cnxnTimeout = 1000;
@Before
public void setUp() throws Exception {
- System.setProperty(
- NIOServerCnxnFactory.ZOOKEEPER_NIO_SESSIONLESS_CNXN_TIMEOUT,
- Integer.toString(cnxnTimeout));
+ System.setProperty(NIOServerCnxnFactory.ZOOKEEPER_NIO_SESSIONLESS_CNXN_TIMEOUT, Integer.toString(cnxnTimeout));
super.setUp();
}
@After
public void tearDown() throws Exception {
super.tearDown();
- System.clearProperty(
- NIOServerCnxnFactory.ZOOKEEPER_NIO_SESSIONLESS_CNXN_TIMEOUT);
+ System.clearProperty(NIOServerCnxnFactory.ZOOKEEPER_NIO_SESSIONLESS_CNXN_TIMEOUT);
}
@Test
@@ -62,14 +58,13 @@ public class ServerCnxnTest extends ClientBase {
// Range is (now + cnxnTimeout) to (now + 2*cnxnTimeout)
// Add 1s buffer to be safe.
String resp = sendRequest("ruok", 2 * cnxnTimeout + 1000);
- Assert.assertEquals("Connection should have closed", "", resp);
+ assertEquals("Connection should have closed", "", resp);
}
-
private void verify(String cmd, String expected) throws IOException {
String resp = sendRequest(cmd, 0);
LOG.info("cmd " + cmd + " expected " + expected + " got " + resp);
- Assert.assertTrue(resp.contains(expected));
+ assertTrue(resp.contains(expected));
}
private String sendRequest(String cmd, int delay) throws IOException {
@@ -78,8 +73,7 @@ public class ServerCnxnTest extends ClientBase {
}
private static String send4LetterWord(
- String host, int port, String cmd, int delay) throws IOException
- {
+ String host, int port, String cmd, int delay) throws IOException {
LOG.info("connecting to " + host + " " + port);
Socket sock = new Socket(host, port);
BufferedReader reader = null;
@@ -97,9 +91,7 @@ public class ServerCnxnTest extends ClientBase {
// this replicates NC - close the output stream before reading
sock.shutdownOutput();
- reader =
- new BufferedReader(
- new InputStreamReader(sock.getInputStream()));
+ reader = new BufferedReader(new InputStreamReader(sock.getInputStream()));
StringBuilder sb = readLine(reader);
return sb.toString();
} finally {
@@ -114,7 +106,7 @@ public class ServerCnxnTest extends ClientBase {
StringBuilder sb = new StringBuilder();
String line;
try {
- while((line = reader.readLine()) != null) {
+ while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException ioe) {
@@ -126,4 +118,5 @@ public class ServerCnxnTest extends ClientBase {
}
return sb;
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/SessionInvalidationTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/SessionInvalidationTest.java
index 22a1518d0..0177e8660 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/SessionInvalidationTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/SessionInvalidationTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,12 +18,11 @@
package org.apache.zookeeper.test;
+import static org.junit.Assert.assertEquals;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
-
-
import org.apache.jute.BinaryOutputArchive;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooDefs.Ids;
@@ -32,14 +31,14 @@ import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.proto.ConnectRequest;
import org.apache.zookeeper.proto.CreateRequest;
import org.apache.zookeeper.proto.RequestHeader;
-import org.junit.Assert;
import org.junit.Test;
public class SessionInvalidationTest extends ClientBase {
+
/**
* Test solution for ZOOKEEPER-1208. Verify that operations are not
* accepted after a close session.
- *
+ *
* We're using our own marshalling here in order to force an operation
* after the session is closed (ZooKeeper.class will not allow this). Also
* by filling the pipe with operations it increases the likelyhood that
@@ -66,14 +65,13 @@ public class SessionInvalidationTest extends ClientBase {
boa.writeInt(52, "len"); // We'll fill this in later
RequestHeader header = new RequestHeader(2, OpCode.create);
header.serialize(boa, "header");
- CreateRequest createReq = new CreateRequest("/foo" + i, new byte[0],
- Ids.OPEN_ACL_UNSAFE, 1);
+ CreateRequest createReq = new CreateRequest("/foo" + i, new byte[0], Ids.OPEN_ACL_UNSAFE, 1);
createReq.serialize(boa, "request");
baos.close();
-
+
System.out.println("Length:" + baos.toByteArray().length);
-
- String hp[] = hostPort.split(":");
+
+ String[] hp = hostPort.split(":");
Socket sock = new Socket(hp[0], Integer.parseInt(hp[1]));
InputStream resultStream = null;
try {
@@ -81,7 +79,7 @@ public class SessionInvalidationTest extends ClientBase {
byte[] data = baos.toByteArray();
outstream.write(data);
outstream.flush();
-
+
resultStream = sock.getInputStream();
byte[] b = new byte[10000];
int len;
@@ -96,10 +94,11 @@ public class SessionInvalidationTest extends ClientBase {
sock.close();
}
}
-
+
ZooKeeper zk = createClient();
- Assert.assertEquals(1, zk.getChildren("/", false).size());
+ assertEquals(1, zk.getChildren("/", false).size());
zk.close();
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/SessionTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/SessionTest.java
index e82c0a643..ffb896a23 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/SessionTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/SessionTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -19,16 +19,16 @@
package org.apache.zookeeper.test;
import static org.apache.zookeeper.test.ClientBase.CONNECTION_TIMEOUT;
-
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
import java.io.File;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
import org.apache.zookeeper.AsyncCallback;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
@@ -44,15 +44,16 @@ import org.apache.zookeeper.data.Stat;
import org.apache.zookeeper.server.ServerCnxnFactory;
import org.apache.zookeeper.server.ZooKeeperServer;
import org.junit.After;
-import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
public class SessionTest extends ZKTestCase {
+
protected static final Logger LOG = LoggerFactory.getLogger(SessionTest.class);
- private static final String HOSTPORT = "127.0.0.1:" +
- PortAssignment.unique();
+ private static final String HOSTPORT = "127.0.0.1:" + PortAssignment.unique();
private ServerCnxnFactory serverFactory;
private ZooKeeperServer zs;
@@ -76,21 +77,18 @@ public class SessionTest extends ZKTestCase {
serverFactory = ServerCnxnFactory.createFactory(PORT, -1);
serverFactory.startup(zs);
- Assert.assertTrue("waiting for server up",
- ClientBase.waitForServerUp(HOSTPORT,
- CONNECTION_TIMEOUT));
+ assertTrue("waiting for server up", ClientBase.waitForServerUp(HOSTPORT, CONNECTION_TIMEOUT));
}
@After
public void tearDown() throws Exception {
serverFactory.shutdown();
zs.shutdown();
- Assert.assertTrue("waiting for server down",
- ClientBase.waitForServerDown(HOSTPORT,
- CONNECTION_TIMEOUT));
+ assertTrue("waiting for server down", ClientBase.waitForServerDown(HOSTPORT, CONNECTION_TIMEOUT));
}
private static class CountdownWatcher implements Watcher {
+
volatile CountDownLatch clientConnected = new CountDownLatch(1);
public void process(WatchedEvent event) {
@@ -98,81 +96,73 @@ public class SessionTest extends ZKTestCase {
clientConnected.countDown();
}
}
+
}
- private DisconnectableZooKeeper createClient()
- throws IOException, InterruptedException
- {
+ private DisconnectableZooKeeper createClient() throws IOException, InterruptedException {
CountdownWatcher watcher = new CountdownWatcher();
return createClient(CONNECTION_TIMEOUT, watcher);
}
- private DisconnectableZooKeeper createClient(int timeout)
- throws IOException, InterruptedException
- {
+ private DisconnectableZooKeeper createClient(int timeout) throws IOException, InterruptedException {
CountdownWatcher watcher = new CountdownWatcher();
return createClient(timeout, watcher);
}
- private DisconnectableZooKeeper createClient(int timeout,
- CountdownWatcher watcher)
- throws IOException, InterruptedException
- {
- DisconnectableZooKeeper zk =
- new DisconnectableZooKeeper(HOSTPORT, timeout, watcher);
- if(!watcher.clientConnected.await(timeout, TimeUnit.MILLISECONDS)) {
- Assert.fail("Unable to connect to server");
+ private DisconnectableZooKeeper createClient(int timeout, CountdownWatcher watcher) throws IOException, InterruptedException {
+ DisconnectableZooKeeper zk = new DisconnectableZooKeeper(HOSTPORT, timeout, watcher);
+ if (!watcher.clientConnected.await(timeout, TimeUnit.MILLISECONDS)) {
+ fail("Unable to connect to server");
}
return zk;
}
-// FIXME this test is Assert.failing due to client close race condition fixing in separate patch for ZOOKEEPER-63
-// /**
-// * this test checks to see if the sessionid that was created for the
-// * first zookeeper client can be reused for the second one immidiately
-// * after the first client closes and the new client resues them.
-// * @throws IOException
-// * @throws InterruptedException
-// * @throws KeeperException
-// */
-// public void testSessionReuse() throws IOException, InterruptedException {
-// ZooKeeper zk = createClient();
-//
-// long sessionId = zk.getSessionId();
-// byte[] passwd = zk.getSessionPasswd();
-// zk.close();
-//
-// zk.close();
-//
-// LOG.info("Closed first session");
-//
-// startSignal = new CountDownLatch(1);
-// zk = new ZooKeeper(HOSTPORT, CONNECTION_TIMEOUT, this,
-// sessionId, passwd);
-// startSignal.await();
-//
-// LOG.info("Opened reuse");
-//
-// Assert.assertEquals(sessionId, zk.getSessionId());
-//
-// zk.close();
-// }
+ // TODO this test is failing due to client close race condition fixing in separate patch for ZOOKEEPER-63
+ // /**
+ // * this test checks to see if the sessionid that was created for the
+ // * first zookeeper client can be reused for the second one immidiately
+ // * after the first client closes and the new client resues them.
+ // * @throws IOException
+ // * @throws InterruptedException
+ // * @throws KeeperException
+ // */
+ // public void testSessionReuse() throws IOException, InterruptedException {
+ // ZooKeeper zk = createClient();
+ //
+ // long sessionId = zk.getSessionId();
+ // byte[] passwd = zk.getSessionPasswd();
+ // zk.close();
+ //
+ // zk.close();
+ //
+ // LOG.info("Closed first session");
+ //
+ // startSignal = new CountDownLatch(1);
+ // zk = new ZooKeeper(HOSTPORT, CONNECTION_TIMEOUT, this,
+ // sessionId, passwd);
+ // startSignal.await();
+ //
+ // LOG.info("Opened reuse");
+ //
+ // assertEquals(sessionId, zk.getSessionId());
+ //
+ // zk.close();
+ // }
private class MyWatcher implements Watcher {
+
private String name;
public MyWatcher(String name) {
this.name = name;
}
public void process(WatchedEvent event) {
- LOG.info(name + " event:" + event.getState() + " "
- + event.getType() + " " + event.getPath());
- if (event.getState() == KeeperState.SyncConnected
- && startSignal != null && startSignal.getCount() > 0)
- {
+ LOG.info(name + " event:" + event.getState() + " " + event.getType() + " " + event.getPath());
+ if (event.getState() == KeeperState.SyncConnected && startSignal != null && startSignal.getCount() > 0) {
startSignal.countDown();
}
}
+
}
/**
@@ -181,14 +171,10 @@ public class SessionTest extends ZKTestCase {
* will remove ephemeral nodes created by the original session.
*/
@Test
- public void testSession()
- throws IOException, InterruptedException, KeeperException
- {
+ public void testSession() throws IOException, InterruptedException, KeeperException {
DisconnectableZooKeeper zk = createClient();
- zk.create("/e", new byte[0], Ids.OPEN_ACL_UNSAFE,
- CreateMode.EPHEMERAL);
- LOG.info("zk with session id 0x" + Long.toHexString(zk.getSessionId())
- + " was destroyed!");
+ zk.create("/e", new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
+ LOG.info("zk with session id 0x" + Long.toHexString(zk.getSessionId()) + " was destroyed!");
// disconnect the client by killing the socket, not sending the
// session disconnect to the server as usual. This allows the test
@@ -197,41 +183,43 @@ public class SessionTest extends ZKTestCase {
Stat stat = new Stat();
startSignal = new CountDownLatch(1);
- zk = new DisconnectableZooKeeper(HOSTPORT, CONNECTION_TIMEOUT,
- new MyWatcher("testSession"), zk.getSessionId(),
- zk.getSessionPasswd());
+ zk = new DisconnectableZooKeeper(HOSTPORT, CONNECTION_TIMEOUT, new MyWatcher("testSession"), zk.getSessionId(), zk.getSessionPasswd());
startSignal.await();
- LOG.info("zk with session id 0x" + Long.toHexString(zk.getSessionId())
- + " was created!");
+ LOG.info("zk with session id 0x" + Long.toHexString(zk.getSessionId()) + " was created!");
zk.getData("/e", false, stat);
LOG.info("After get data /e");
zk.close();
zk = createClient();
- Assert.assertEquals(null, zk.exists("/e", false));
- LOG.info("before close zk with session id 0x"
- + Long.toHexString(zk.getSessionId()) + "!");
+ assertEquals(null, zk.exists("/e", false));
+ LOG.info("before close zk with session id 0x" + Long.toHexString(zk.getSessionId()) + "!");
zk.close();
try {
zk.getData("/e", false, stat);
- Assert.fail("Should have received a SessionExpiredException");
- } catch(KeeperException.SessionExpiredException e) {}
+ fail("Should have received a SessionExpiredException");
+ } catch (KeeperException.SessionExpiredException e) {
+ }
AsyncCallback.DataCallback cb = new AsyncCallback.DataCallback() {
String status = "not done";
public void processResult(int rc, String p, Object c, byte[] b, Stat s) {
- synchronized(this) { status = KeeperException.Code.get(rc).toString(); this.notify(); }
+ synchronized (this) {
+ status = KeeperException.Code.get(rc).toString();
+ this.notify();
+ }
+ }
+ public String toString() {
+ return status;
}
- public String toString() { return status; }
};
zk.getData("/e", false, cb, null);
- synchronized(cb) {
+ synchronized (cb) {
if (cb.toString().equals("not done")) {
cb.wait(1000);
}
}
- Assert.assertEquals(KeeperException.Code.SESSIONEXPIRED.toString(), cb.toString());
+ assertEquals(KeeperException.Code.SESSIONEXPIRED.toString(), cb.toString());
}
/**
@@ -244,40 +232,39 @@ public class SessionTest extends ZKTestCase {
*/
@Test
public void testSessionMove() throws Exception {
- String hostPorts[] = HOSTPORT.split(",");
- DisconnectableZooKeeper zk = new DisconnectableZooKeeper(hostPorts[0],
- CONNECTION_TIMEOUT, new MyWatcher("0"));
- zk.create("/sessionMoveTest", new byte[0], Ids.OPEN_ACL_UNSAFE,
- CreateMode.EPHEMERAL);
+ String[] hostPorts = HOSTPORT.split(",");
+ DisconnectableZooKeeper zk = new DisconnectableZooKeeper(hostPorts[0], CONNECTION_TIMEOUT, new MyWatcher("0"));
+ zk.create("/sessionMoveTest", new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
// we want to loop through the list twice
- for(int i = 0; i < hostPorts.length*2; i++) {
+ for (int i = 0; i < hostPorts.length * 2; i++) {
zk.dontReconnect();
// This should stomp the zk handle
- DisconnectableZooKeeper zknew = new DisconnectableZooKeeper(
- hostPorts[(i+1)%hostPorts.length],
- CONNECTION_TIMEOUT,
- new MyWatcher(Integer.toString(i+1)),
- zk.getSessionId(),
- zk.getSessionPasswd());
- final int result[] = new int[1];
+ DisconnectableZooKeeper zknew = new DisconnectableZooKeeper(hostPorts[(i + 1)
+ % hostPorts.length], CONNECTION_TIMEOUT, new MyWatcher(Integer.toString(
+ i
+ + 1)), zk.getSessionId(), zk.getSessionPasswd());
+ final int[] result = new int[1];
result[0] = Integer.MAX_VALUE;
zknew.sync("/", new AsyncCallback.VoidCallback() {
- public void processResult(int rc, String path, Object ctx) {
- synchronized(result) { result[0] = rc; result.notify(); }
+ public void processResult(int rc, String path, Object ctx) {
+ synchronized (result) {
+ result[0] = rc;
+ result.notify();
}
- }, null);
- synchronized(result) {
- if(result[0] == Integer.MAX_VALUE) {
+ }
+ }, null);
+ synchronized (result) {
+ if (result[0] == Integer.MAX_VALUE) {
result.wait(5000);
}
}
- LOG.info(hostPorts[(i+1)%hostPorts.length] + " Sync returned " + result[0]);
- Assert.assertTrue(result[0] == KeeperException.Code.OK.intValue());
+ LOG.info(hostPorts[(i + 1) % hostPorts.length] + " Sync returned " + result[0]);
+ assertTrue(result[0] == KeeperException.Code.OK.intValue());
zknew.setData("/", new byte[1], -1);
try {
zk.setData("/", new byte[1], -1);
- Assert.fail("Should have lost the connection");
- } catch(KeeperException.ConnectionLossException e) {
+ fail("Should have lost the connection");
+ } catch (KeeperException.ConnectionLossException e) {
LOG.info("Got connection loss exception as expected");
}
//zk.close();
@@ -293,9 +280,7 @@ public class SessionTest extends ZKTestCase {
* not "None" (ie non-None communicates an event).
*/
@Test
- public void testSessionStateNoDupStateReporting()
- throws IOException, InterruptedException, KeeperException
- {
+ public void testSessionStateNoDupStateReporting() throws IOException, InterruptedException, KeeperException {
final int TIMEOUT = 3000;
DupWatcher watcher = new DupWatcher();
ZooKeeper zk = createClient(TIMEOUT, watcher);
@@ -312,8 +297,8 @@ public class SessionTest extends ZKTestCase {
// verify that the size is just 2 - ie connect then disconnect
// if the client attempts reconnect and we are not handling current
// state correctly (ie eventing on duplicate disconnects) then we'll
- // see a disconnect for each Assert.failed connection attempt
- Assert.assertEquals(2, watcher.states.size());
+ // see a disconnect for each failed connection attempt
+ assertEquals(2, watcher.states.size());
zk.close();
}
@@ -325,7 +310,7 @@ public class SessionTest extends ZKTestCase {
public void testSessionTimeoutAccess() throws Exception {
// validate typical case - requested == negotiated
DisconnectableZooKeeper zk = createClient(TICK_TIME * 4);
- Assert.assertEquals(TICK_TIME * 4, zk.getSessionTimeout());
+ assertEquals(TICK_TIME * 4, zk.getSessionTimeout());
// make sure tostring works in both cases
LOG.info(zk.toString());
zk.close();
@@ -333,20 +318,21 @@ public class SessionTest extends ZKTestCase {
// validate lower limit
zk = createClient(TICK_TIME);
- Assert.assertEquals(TICK_TIME * 2, zk.getSessionTimeout());
+ assertEquals(TICK_TIME * 2, zk.getSessionTimeout());
LOG.info(zk.toString());
zk.close();
LOG.info(zk.toString());
// validate upper limit
zk = createClient(TICK_TIME * 30);
- Assert.assertEquals(TICK_TIME * 20, zk.getSessionTimeout());
+ assertEquals(TICK_TIME * 20, zk.getSessionTimeout());
LOG.info(zk.toString());
zk.close();
LOG.info(zk.toString());
}
private class DupWatcher extends CountdownWatcher {
+
public List<WatchedEvent> states = new LinkedList<WatchedEvent>();
public void process(WatchedEvent event) {
super.process(event);
@@ -354,6 +340,7 @@ public class SessionTest extends ZKTestCase {
states.add(event);
}
}
+
}
@Test
@@ -370,22 +357,22 @@ public class SessionTest extends ZKTestCase {
// validate typical case - requested == negotiated
int timeout = 120000;
DisconnectableZooKeeper zk = createClient(timeout);
- Assert.assertEquals(timeout, zk.getSessionTimeout());
+ assertEquals(timeout, zk.getSessionTimeout());
// make sure tostring works in both cases
LOG.info(zk.toString());
zk.close();
LOG.info(zk.toString());
// validate lower limit
- zk = createClient(MINSESS/2);
- Assert.assertEquals(MINSESS, zk.getSessionTimeout());
+ zk = createClient(MINSESS / 2);
+ assertEquals(MINSESS, zk.getSessionTimeout());
LOG.info(zk.toString());
zk.close();
LOG.info(zk.toString());
// validate upper limit
zk = createClient(MAXSESS * 2);
- Assert.assertEquals(MAXSESS, zk.getSessionTimeout());
+ assertEquals(MAXSESS, zk.getSessionTimeout());
LOG.info(zk.toString());
zk.close();
LOG.info(zk.toString());
@@ -403,10 +390,11 @@ public class SessionTest extends ZKTestCase {
clients[i] = new DisconnectableZooKeeper(HOSTPORT, timeout, watcher);
boolean result = watcher.clientConnected.await(timeout, TimeUnit.MILLISECONDS);
if (i >= maxClientCnxnsPerIP) {
- Assert.assertFalse(result);
+ assertFalse(result);
} else {
- Assert.assertTrue(result);
+ assertTrue(result);
}
}
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/SessionTimeoutTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/SessionTimeoutTest.java
index f3b3e5de4..6052f8f86 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/SessionTimeoutTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/SessionTimeoutTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,26 +18,26 @@
package org.apache.zookeeper.test;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+import java.io.IOException;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.TestableZooKeeper;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooDefs;
-import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.io.IOException;
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.TimeUnit;
-
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-
public class SessionTimeoutTest extends ClientBase {
+
protected static final Logger LOG = LoggerFactory.getLogger(SessionTimeoutTest.class);
private TestableZooKeeper zk;
@@ -49,13 +49,12 @@ public class SessionTimeoutTest extends ClientBase {
}
@Test
- public void testSessionExpiration() throws InterruptedException,
- KeeperException {
+ public void testSessionExpiration() throws InterruptedException, KeeperException {
final CountDownLatch expirationLatch = new CountDownLatch(1);
Watcher watcher = new Watcher() {
@Override
public void process(WatchedEvent event) {
- if ( event.getState() == Event.KeeperState.Expired ) {
+ if (event.getState() == Event.KeeperState.Expired) {
expirationLatch.countDown();
}
}
@@ -63,28 +62,27 @@ public class SessionTimeoutTest extends ClientBase {
zk.exists("/foo", watcher);
zk.getTestable().injectSessionExpiration();
- Assert.assertTrue(expirationLatch.await(5, TimeUnit.SECONDS));
+ assertTrue(expirationLatch.await(5, TimeUnit.SECONDS));
boolean gotException = false;
try {
zk.exists("/foo", false);
- Assert.fail("Should have thrown a SessionExpiredException");
+ fail("Should have thrown a SessionExpiredException");
} catch (KeeperException.SessionExpiredException e) {
// correct
gotException = true;
}
- Assert.assertTrue(gotException);
+ assertTrue(gotException);
}
@Test
- public void testQueueEvent() throws InterruptedException,
- KeeperException {
+ public void testQueueEvent() throws InterruptedException, KeeperException {
final CountDownLatch eventLatch = new CountDownLatch(1);
Watcher watcher = new Watcher() {
@Override
public void process(WatchedEvent event) {
- if ( event.getType() == Event.EventType.NodeDataChanged ) {
- if ( event.getPath().equals("/foo/bar") ) {
+ if (event.getType() == Event.EventType.NodeDataChanged) {
+ if (event.getPath().equals("/foo/bar")) {
eventLatch.countDown();
}
}
@@ -92,10 +90,9 @@ public class SessionTimeoutTest extends ClientBase {
};
zk.exists("/foo/bar", watcher);
- WatchedEvent event = new WatchedEvent(Watcher.Event.EventType.NodeDataChanged,
- Watcher.Event.KeeperState.SyncConnected, "/foo/bar");
+ WatchedEvent event = new WatchedEvent(Watcher.Event.EventType.NodeDataChanged, Watcher.Event.KeeperState.SyncConnected, "/foo/bar");
zk.getTestable().queueEvent(event);
- Assert.assertTrue(eventLatch.await(5, TimeUnit.SECONDS));
+ assertTrue(eventLatch.await(5, TimeUnit.SECONDS));
}
/**
@@ -103,8 +100,7 @@ public class SessionTimeoutTest extends ClientBase {
*/
@Test
public void testSessionDisconnect() throws KeeperException, InterruptedException, IOException {
- zk.create("/sdisconnect", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE,
- CreateMode.EPHEMERAL);
+ zk.create("/sdisconnect", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
assertNotNull("Ephemeral node has not been created", zk.exists("/sdisconnect", null));
zk.close();
@@ -118,8 +114,7 @@ public class SessionTimeoutTest extends ClientBase {
*/
@Test
public void testSessionRestore() throws KeeperException, InterruptedException, IOException {
- zk.create("/srestore", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE,
- CreateMode.EPHEMERAL);
+ zk.create("/srestore", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
assertNotNull("Ephemeral node has not been created", zk.exists("/srestore", null));
zk.disconnect();
@@ -134,8 +129,7 @@ public class SessionTimeoutTest extends ClientBase {
*/
@Test
public void testSessionSurviveServerRestart() throws Exception {
- zk.create("/sdeath", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE,
- CreateMode.EPHEMERAL);
+ zk.create("/sdeath", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
assertNotNull("Ephemeral node has not been created", zk.exists("/sdeath", null));
zk.disconnect();
@@ -145,4 +139,5 @@ public class SessionTimeoutTest extends ClientBase {
assertNotNull("Ephemeral node should be present when server restarted", zk.exists("/sdeath", null));
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/SessionTrackerCheckTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/SessionTrackerCheckTest.java
index d8c9bb9b9..a0d5c915e 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/SessionTrackerCheckTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/SessionTrackerCheckTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,8 +18,8 @@
package org.apache.zookeeper.test;
+import static org.junit.Assert.fail;
import java.util.concurrent.ConcurrentHashMap;
-
import org.apache.zookeeper.KeeperException.SessionExpiredException;
import org.apache.zookeeper.ZKTestCase;
import org.apache.zookeeper.server.SessionTracker.Session;
@@ -28,7 +28,6 @@ import org.apache.zookeeper.server.ZooKeeperServerListener;
import org.apache.zookeeper.server.quorum.LeaderSessionTracker;
import org.apache.zookeeper.server.quorum.LearnerSessionTracker;
import org.junit.After;
-import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
@@ -40,15 +39,14 @@ import org.slf4j.LoggerFactory;
*/
public class SessionTrackerCheckTest extends ZKTestCase {
- protected static final Logger LOG = LoggerFactory
- .getLogger(SessionTrackerCheckTest.class);
+ protected static final Logger LOG = LoggerFactory.getLogger(SessionTrackerCheckTest.class);
public static final int TICK_TIME = 1000;
public static final int CONNECTION_TIMEOUT = TICK_TIME * 10;
- private ConcurrentHashMap<Long, Integer> sessionsWithTimeouts =
- new ConcurrentHashMap<Long, Integer>();
+ private ConcurrentHashMap<Long, Integer> sessionsWithTimeouts = new ConcurrentHashMap<Long, Integer>();
private class Expirer implements SessionExpirer {
+
long sid;
public Expirer(long sid) {
@@ -61,6 +59,7 @@ public class SessionTrackerCheckTest extends ZKTestCase {
public long getServerId() {
return sid;
}
+
}
@Before
@@ -76,15 +75,13 @@ public class SessionTrackerCheckTest extends ZKTestCase {
public void testLearnerSessionTracker() throws Exception {
Expirer expirer = new Expirer(1);
// With local session on
- LearnerSessionTracker tracker = new LearnerSessionTracker(expirer,
- sessionsWithTimeouts, TICK_TIME, expirer.sid, true,
- testZKSListener());
+ LearnerSessionTracker tracker = new LearnerSessionTracker(expirer, sessionsWithTimeouts, TICK_TIME, expirer.sid, true, testZKSListener());
// Unknown session
long sessionId = 0xb100ded;
try {
tracker.checkSession(sessionId, null);
- Assert.fail("Unknown session should have failed");
+ fail("Unknown session should have failed");
} catch (SessionExpiredException e) {
// Get expected exception
}
@@ -94,7 +91,7 @@ public class SessionTrackerCheckTest extends ZKTestCase {
try {
tracker.checkSession(sessionId, null);
} catch (Exception e) {
- Assert.fail("Global session should not fail");
+ fail("Global session should not fail");
}
// Local session
@@ -102,7 +99,7 @@ public class SessionTrackerCheckTest extends ZKTestCase {
try {
tracker.checkSession(sessionId, null);
} catch (Exception e) {
- Assert.fail("Local session should not fail");
+ fail("Local session should not fail");
}
// During session upgrade
@@ -110,19 +107,18 @@ public class SessionTrackerCheckTest extends ZKTestCase {
try {
tracker.checkSession(sessionId, null);
} catch (Exception e) {
- Assert.fail("Session during upgrade should not fail");
+ fail("Session during upgrade should not fail");
}
// With local session off
- tracker = new LearnerSessionTracker(expirer, sessionsWithTimeouts,
- TICK_TIME, expirer.sid, false, testZKSListener());
+ tracker = new LearnerSessionTracker(expirer, sessionsWithTimeouts, TICK_TIME, expirer.sid, false, testZKSListener());
// Should be noop
sessionId = 0xdeadbeef;
try {
tracker.checkSession(sessionId, null);
} catch (Exception e) {
- Assert.fail("Should not get any exception");
+ fail("Should not get any exception");
}
}
@@ -131,16 +127,14 @@ public class SessionTrackerCheckTest extends ZKTestCase {
public void testLeaderSessionTracker() throws Exception {
Expirer expirer = new Expirer(2);
// With local session on
- LeaderSessionTracker tracker = new LeaderSessionTracker(expirer,
- sessionsWithTimeouts, TICK_TIME, expirer.sid, true,
- testZKSListener());
+ LeaderSessionTracker tracker = new LeaderSessionTracker(expirer, sessionsWithTimeouts, TICK_TIME, expirer.sid, true, testZKSListener());
// Local session from other server
long sessionId = ((expirer.sid + 1) << 56) + 1;
try {
tracker.checkSession(sessionId, null);
} catch (Exception e) {
- Assert.fail("local session from other server should not fail");
+ fail("local session from other server should not fail");
}
// Track global session
@@ -148,12 +142,12 @@ public class SessionTrackerCheckTest extends ZKTestCase {
try {
tracker.checkSession(sessionId, null);
} catch (Exception e) {
- Assert.fail("Global session should not fail");
+ fail("Global session should not fail");
}
try {
tracker.checkGlobalSession(sessionId, null);
} catch (Exception e) {
- Assert.fail("Global session should not fail " + e);
+ fail("Global session should not fail " + e);
}
// Local session from the leader
@@ -161,7 +155,7 @@ public class SessionTrackerCheckTest extends ZKTestCase {
try {
tracker.checkSession(sessionId, null);
} catch (Exception e) {
- Assert.fail("Local session on the leader should not fail");
+ fail("Local session on the leader should not fail");
}
// During session upgrade
@@ -169,17 +163,16 @@ public class SessionTrackerCheckTest extends ZKTestCase {
try {
tracker.checkSession(sessionId, null);
} catch (Exception e) {
- Assert.fail("Session during upgrade should not fail");
+ fail("Session during upgrade should not fail");
}
try {
tracker.checkGlobalSession(sessionId, null);
} catch (Exception e) {
- Assert.fail("Global session should not fail " + e);
+ fail("Global session should not fail " + e);
}
// With local session off
- tracker = new LeaderSessionTracker(expirer, sessionsWithTimeouts,
- TICK_TIME, expirer.sid, false, testZKSListener());
+ tracker = new LeaderSessionTracker(expirer, sessionsWithTimeouts, TICK_TIME, expirer.sid, false, testZKSListener());
// Global session
sessionId = 0xdeadbeef;
@@ -187,19 +180,19 @@ public class SessionTrackerCheckTest extends ZKTestCase {
try {
tracker.checkSession(sessionId, null);
} catch (Exception e) {
- Assert.fail("Global session should not fail");
+ fail("Global session should not fail");
}
try {
tracker.checkGlobalSession(sessionId, null);
} catch (Exception e) {
- Assert.fail("Global session should not fail");
+ fail("Global session should not fail");
}
// Local session from other server
sessionId = ((expirer.sid + 1) << 56) + 2;
try {
tracker.checkSession(sessionId, null);
- Assert.fail("local session from other server should fail");
+ fail("local session from other server should fail");
} catch (SessionExpiredException e) {
// Got expected exception
}
@@ -208,7 +201,7 @@ public class SessionTrackerCheckTest extends ZKTestCase {
sessionId = ((expirer.sid) << 56) + 2;
try {
tracker.checkSession(sessionId, null);
- Assert.fail("local session from the leader should fail");
+ fail("local session from the leader should fail");
} catch (SessionExpiredException e) {
// Got expected exception
}
@@ -224,4 +217,5 @@ public class SessionTrackerCheckTest extends ZKTestCase {
}
};
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/SessionUpgradeTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/SessionUpgradeTest.java
index be9ecb577..3b8c5836f 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/SessionUpgradeTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/SessionUpgradeTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,13 +18,16 @@
package org.apache.zookeeper.test;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.fail;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZKTestCase;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.test.ClientBase.CountdownWatcher;
import org.junit.After;
-import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
@@ -39,6 +42,7 @@ import org.slf4j.LoggerFactory;
* persistence, i.e. creating an ephemeral node.
*/
public class SessionUpgradeTest extends ZKTestCase {
+
protected static final Logger LOG = LoggerFactory.getLogger(SessionUpgradeTest.class);
public static final int CONNECTION_TIMEOUT = ClientBase.CONNECTION_TIMEOUT;
@@ -69,25 +73,21 @@ public class SessionUpgradeTest extends ZKTestCase {
testLocalSessionsWithoutEphemeral(true);
}
- private void testLocalSessionsWithoutEphemeral(boolean testLeader)
- throws Exception {
- String nodePrefix = "/testLocalSessions-"
- + (testLeader ? "leaderTest-" : "followerTest-");
+ private void testLocalSessionsWithoutEphemeral(boolean testLeader) throws Exception {
+ String nodePrefix = "/testLocalSessions-" + (testLeader ? "leaderTest-" : "followerTest-");
int leaderIdx = qb.getLeaderIndex();
- Assert.assertFalse("No leader in quorum?", leaderIdx == -1);
+ assertFalse("No leader in quorum?", leaderIdx == -1);
int followerIdx = (leaderIdx + 1) % 5;
int otherFollowerIdx = (leaderIdx + 2) % 5;
int testPeerIdx = testLeader ? leaderIdx : followerIdx;
- String hostPorts[] = qb.hostPort.split(",");
+ String[] hostPorts = qb.hostPort.split(",");
CountdownWatcher watcher = new CountdownWatcher();
- DisconnectableZooKeeper zk = new DisconnectableZooKeeper(
- hostPorts[testPeerIdx], CONNECTION_TIMEOUT, watcher);
+ DisconnectableZooKeeper zk = new DisconnectableZooKeeper(hostPorts[testPeerIdx], CONNECTION_TIMEOUT, watcher);
watcher.waitForConnected(CONNECTION_TIMEOUT);
// Try creating some data.
for (int i = 0; i < 5; i++) {
- zk.create(nodePrefix + i, new byte[0],
- ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
+ zk.create(nodePrefix + i, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
}
long localSessionId = zk.getSessionId();
@@ -97,13 +97,10 @@ public class SessionUpgradeTest extends ZKTestCase {
// server. This should fail since it is a local sesion.
try {
watcher.reset();
- DisconnectableZooKeeper zknew = new DisconnectableZooKeeper(
- hostPorts[otherFollowerIdx], CONNECTION_TIMEOUT, watcher,
- localSessionId, localSessionPwd);
+ DisconnectableZooKeeper zknew = new DisconnectableZooKeeper(hostPorts[otherFollowerIdx], CONNECTION_TIMEOUT, watcher, localSessionId, localSessionPwd);
- zknew.create(nodePrefix + "5", new byte[0],
- ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
- Assert.fail("Connection on the same session ID should fail.");
+ zknew.create(nodePrefix + "5", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
+ fail("Connection on the same session ID should fail.");
} catch (KeeperException.SessionExpiredException e) {
} catch (KeeperException.ConnectionLossException e) {
}
@@ -113,14 +110,10 @@ public class SessionUpgradeTest extends ZKTestCase {
if (!testLeader) {
try {
watcher.reset();
- DisconnectableZooKeeper zknew = new DisconnectableZooKeeper(
- hostPorts[leaderIdx], CONNECTION_TIMEOUT,
- watcher, localSessionId, localSessionPwd);
-
- zknew.create(nodePrefix + "5", new byte[0],
- ZooDefs.Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
- Assert.fail("Connection on the same session ID should fail.");
+ DisconnectableZooKeeper zknew = new DisconnectableZooKeeper(hostPorts[leaderIdx], CONNECTION_TIMEOUT, watcher, localSessionId, localSessionPwd);
+
+ zknew.create(nodePrefix + "5", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
+ fail("Connection on the same session ID should fail.");
} catch (KeeperException.SessionExpiredException e) {
} catch (KeeperException.ConnectionLossException e) {
}
@@ -132,26 +125,20 @@ public class SessionUpgradeTest extends ZKTestCase {
zk.disconnect();
watcher.reset();
- zk = new DisconnectableZooKeeper(
- hostPorts[testPeerIdx], CONNECTION_TIMEOUT, watcher,
- localSessionId, localSessionPwd);
+ zk = new DisconnectableZooKeeper(hostPorts[testPeerIdx], CONNECTION_TIMEOUT, watcher, localSessionId, localSessionPwd);
watcher.waitForConnected(CONNECTION_TIMEOUT);
- zk.create(nodePrefix + "6", new byte[0],
- ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
+ zk.create(nodePrefix + "6", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
// If we explicitly close the session, then the session id should no
// longer be valid.
zk.close();
try {
watcher.reset();
- zk = new DisconnectableZooKeeper(
- hostPorts[testPeerIdx], CONNECTION_TIMEOUT, watcher,
- localSessionId, localSessionPwd);
+ zk = new DisconnectableZooKeeper(hostPorts[testPeerIdx], CONNECTION_TIMEOUT, watcher, localSessionId, localSessionPwd);
- zk.create(nodePrefix + "7", new byte[0],
- ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
- Assert.fail("Reconnecting to a closed session ID should fail.");
+ zk.create(nodePrefix + "7", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
+ fail("Reconnecting to a closed session ID should fail.");
} catch (KeeperException.SessionExpiredException e) {
}
}
@@ -166,27 +153,23 @@ public class SessionUpgradeTest extends ZKTestCase {
testUpgradeWithEphemeral(true);
}
- private void testUpgradeWithEphemeral(boolean testLeader)
- throws Exception {
- String nodePrefix = "/testUpgrade-"
- + (testLeader ? "leaderTest-" : "followerTest-");
+ private void testUpgradeWithEphemeral(boolean testLeader) throws Exception {
+ String nodePrefix = "/testUpgrade-" + (testLeader ? "leaderTest-" : "followerTest-");
int leaderIdx = qb.getLeaderIndex();
- Assert.assertFalse("No leader in quorum?", leaderIdx == -1);
+ assertFalse("No leader in quorum?", leaderIdx == -1);
int followerIdx = (leaderIdx + 1) % 5;
int otherFollowerIdx = (leaderIdx + 2) % 5;
int testPeerIdx = testLeader ? leaderIdx : followerIdx;
- String hostPorts[] = qb.hostPort.split(",");
+ String[] hostPorts = qb.hostPort.split(",");
CountdownWatcher watcher = new CountdownWatcher();
- DisconnectableZooKeeper zk = new DisconnectableZooKeeper(
- hostPorts[testPeerIdx], CONNECTION_TIMEOUT, watcher);
+ DisconnectableZooKeeper zk = new DisconnectableZooKeeper(hostPorts[testPeerIdx], CONNECTION_TIMEOUT, watcher);
watcher.waitForConnected(CONNECTION_TIMEOUT);
// Create some ephemeral nodes. This should force the session to
// be propagated to the other servers in the ensemble.
for (int i = 0; i < 5; i++) {
- zk.create(nodePrefix + i, new byte[0],
- ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
+ zk.create(nodePrefix + i, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
}
// We should be able to reconnect with the same session id on a
@@ -196,14 +179,12 @@ public class SessionUpgradeTest extends ZKTestCase {
zk.disconnect();
watcher.reset();
- zk = new DisconnectableZooKeeper(
- hostPorts[otherFollowerIdx], CONNECTION_TIMEOUT, watcher,
- localSessionId, localSessionPwd);
+ zk = new DisconnectableZooKeeper(hostPorts[otherFollowerIdx], CONNECTION_TIMEOUT, watcher, localSessionId, localSessionPwd);
watcher.waitForConnected(CONNECTION_TIMEOUT);
// The created ephemeral nodes are still around.
for (int i = 0; i < 5; i++) {
- Assert.assertNotNull(zk.exists(nodePrefix + i, null));
+ assertNotNull(zk.exists(nodePrefix + i, null));
}
// When we explicitly close the session, we should not be able to
@@ -212,21 +193,19 @@ public class SessionUpgradeTest extends ZKTestCase {
try {
watcher.reset();
- zk = new DisconnectableZooKeeper(
- hostPorts[otherFollowerIdx], CONNECTION_TIMEOUT, watcher,
- localSessionId, localSessionPwd);
+ zk = new DisconnectableZooKeeper(hostPorts[otherFollowerIdx], CONNECTION_TIMEOUT, watcher, localSessionId, localSessionPwd);
zk.exists(nodePrefix + "0", null);
- Assert.fail("Reconnecting to a closed session ID should fail.");
+ fail("Reconnecting to a closed session ID should fail.");
} catch (KeeperException.SessionExpiredException e) {
}
watcher.reset();
// And the ephemeral nodes will be gone since the session died.
- zk = new DisconnectableZooKeeper(
- hostPorts[testPeerIdx], CONNECTION_TIMEOUT, watcher);
+ zk = new DisconnectableZooKeeper(hostPorts[testPeerIdx], CONNECTION_TIMEOUT, watcher);
watcher.waitForConnected(CONNECTION_TIMEOUT);
for (int i = 0; i < 5; i++) {
- Assert.assertNull(zk.exists(nodePrefix + i, null));
+ assertNull(zk.exists(nodePrefix + i, null));
}
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/SledgeHammer.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/SledgeHammer.java
index 9b163388f..8190797e4 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/SledgeHammer.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/SledgeHammer.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -21,23 +21,22 @@ package org.apache.zookeeper.test;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
-
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
-import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.ZooDefs.Ids;
+import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;
import org.apache.zookeeper.server.ExitCode;
-public class SledgeHammer extends Thread{
+public class SledgeHammer extends Thread {
+
ZooKeeper zk;
int count;
int readsPerWrite;
- public SledgeHammer(String hosts, int count, int readsPerWrite)
- throws Exception {
+ public SledgeHammer(String hosts, int count, int readsPerWrite) throws Exception {
zk = ClientBase.createZKClient(hosts, 10000);
this.count = count;
this.readsPerWrite = readsPerWrite;
@@ -46,9 +45,8 @@ public class SledgeHammer extends Thread{
public void run() {
try {
Stat stat = new Stat();
- String path = zk.create("/hammers/hammer-", new byte[0],
- Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL);
- byte tag[] = (path + " was here!").getBytes();
+ String path = zk.create("/hammers/hammer-", new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL);
+ byte[] tag = (path + " was here!").getBytes();
synchronized (this) {
String startPath = "/hammers/start";
System.out.println("Waiting for " + startPath);
@@ -60,8 +58,7 @@ public class SledgeHammer extends Thread{
for (int i = 0; i < count; i++) {
try {
System.out.print(i + "\r");
- List<String> childs =
- zk.getChildren("/hammers", false);
+ List<String> childs = zk.getChildren("/hammers", false);
Collections.shuffle(childs);
for (String s : childs) {
if (s.startsWith("hammer-")) {
@@ -96,16 +93,14 @@ public class SledgeHammer extends Thread{
* @throws KeeperException
* @throws NumberFormatException
*/
- public static void main(String[] args) throws NumberFormatException,
- Exception {
+ public static void main(String[] args) throws Exception {
if (args.length != 3) {
- System.err
- .println("USAGE: SledgeHammer zookeeper_server reps reads_per_rep");
+ System.err.println("USAGE: SledgeHammer zookeeper_server reps reads_per_rep");
System.exit(ExitCode.UNABLE_TO_ACCESS_DATADIR.getValue());
}
- SledgeHammer h = new SledgeHammer(args[0], Integer.parseInt(args[1]),
- Integer.parseInt(args[2]));
+ SledgeHammer h = new SledgeHammer(args[0], Integer.parseInt(args[1]), Integer.parseInt(args[2]));
h.start();
System.exit(ExitCode.EXECUTION_FINISHED.getValue());
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/StandaloneTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/StandaloneTest.java
index 3d57b6c5c..8541d7abd 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/StandaloneTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/StandaloneTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -19,45 +19,44 @@
package org.apache.zookeeper.test;
import static org.apache.zookeeper.test.ClientBase.CONNECTION_TIMEOUT;
-
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
-
-import org.apache.zookeeper.Watcher;
-import org.apache.zookeeper.PortAssignment;
import org.apache.zookeeper.KeeperException;
-import org.apache.zookeeper.server.quorum.QuorumPeerConfig;
+import org.apache.zookeeper.PortAssignment;
+import org.apache.zookeeper.Watcher;
+import org.apache.zookeeper.ZooKeeper;
+import org.apache.zookeeper.admin.ZooKeeperAdmin;
import org.apache.zookeeper.data.Stat;
import org.apache.zookeeper.server.ServerCnxnFactory;
import org.apache.zookeeper.server.ZooKeeperServer;
+import org.apache.zookeeper.server.quorum.QuorumPeerConfig;
import org.apache.zookeeper.server.quorum.QuorumPeerTestBase;
import org.apache.zookeeper.test.ClientBase.CountdownWatcher;
-import org.apache.zookeeper.ZooKeeper;
-import org.apache.zookeeper.admin.ZooKeeperAdmin;
import org.junit.Before;
+import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import org.junit.Assert;
-import org.junit.Test;
/**
* Standalone server tests.
*/
-public class StandaloneTest extends QuorumPeerTestBase implements Watcher{
- protected static final Logger LOG =
- LoggerFactory.getLogger(StandaloneTest.class);
+public class StandaloneTest extends QuorumPeerTestBase implements Watcher {
+
+ protected static final Logger LOG = LoggerFactory.getLogger(StandaloneTest.class);
@Before
public void setup() {
- System.setProperty("zookeeper.DigestAuthenticationProvider.superDigest",
- "super:D/InIHSb7yEEbrWz8b9l71RjZJU="/* password is 'test'*/);
+ System.setProperty("zookeeper.DigestAuthenticationProvider.superDigest", "super:D/InIHSb7yEEbrWz8b9l71RjZJU="/* password is 'test'*/);
QuorumPeerConfig.setReconfigEnabled(true);
}
/**
* This test wouldn't create any dynamic config.
- * However, it adds a "clientPort=XXX" in static config file.
+ * However, it adds a "clientPort=xxx" in static config file.
* It checks the standard way of standalone mode.
*/
@Test
@@ -65,8 +64,7 @@ public class StandaloneTest extends QuorumPeerTestBase implements Watcher{
ClientBase.setupTestEnv();
final int CLIENT_PORT = PortAssignment.unique();
- MainThread mt = new MainThread(
- MainThread.UNSET_MYID, CLIENT_PORT, "", false);
+ MainThread mt = new MainThread(MainThread.UNSET_MYID, CLIENT_PORT, "", false);
verifyStandalone(mt, CLIENT_PORT);
}
@@ -83,9 +81,7 @@ public class StandaloneTest extends QuorumPeerTestBase implements Watcher{
ClientBase.setupTestEnv();
final int CLIENT_PORT = PortAssignment.unique();
- String quorumCfgSection = "server.1=127.0.0.1:" +
- (PortAssignment.unique()) + ":" + (PortAssignment.unique())
- + ":participant;" + CLIENT_PORT + "\n";
+ String quorumCfgSection = "server.1=127.0.0.1:" + (PortAssignment.unique()) + ":" + (PortAssignment.unique()) + ":participant;" + CLIENT_PORT + "\n";
MainThread mt = new MainThread(1, quorumCfgSection);
verifyStandalone(mt, CLIENT_PORT);
@@ -101,9 +97,7 @@ public class StandaloneTest extends QuorumPeerTestBase implements Watcher{
ClientBase.setupTestEnv();
final int CLIENT_PORT = PortAssignment.unique();
- String quorumCfgSection = "server.1=127.0.0.1:" +
- (PortAssignment.unique()) + ":" + (PortAssignment.unique())
- + ":participant;" + CLIENT_PORT + "\n";
+ String quorumCfgSection = "server.1=127.0.0.1:" + (PortAssignment.unique()) + ":" + (PortAssignment.unique()) + ":participant;" + CLIENT_PORT + "\n";
MainThread mt = new MainThread(1, quorumCfgSection, false);
verifyStandalone(mt, CLIENT_PORT);
@@ -112,12 +106,11 @@ public class StandaloneTest extends QuorumPeerTestBase implements Watcher{
void verifyStandalone(MainThread mt, int clientPort) throws InterruptedException {
mt.start();
try {
- Assert.assertTrue("waiting for server 1 being up",
- ClientBase.waitForServerUp("127.0.0.1:" + clientPort,
- CONNECTION_TIMEOUT));
+ assertTrue(
+ "waiting for server 1 being up",
+ ClientBase.waitForServerUp("127.0.0.1:" + clientPort, CONNECTION_TIMEOUT));
} finally {
- Assert.assertFalse("Error- MainThread started in Quorum Mode!",
- mt.isQuorumPeerRunning());
+ assertFalse("Error- MainThread started in Quorum Mode!", mt.isQuorumPeerRunning());
mt.shutdown();
}
}
@@ -138,8 +131,7 @@ public class StandaloneTest extends QuorumPeerTestBase implements Watcher{
ServerCnxnFactory f = ServerCnxnFactory.createFactory(CLIENT_PORT, -1);
f.startup(zks);
- Assert.assertTrue("waiting for server being up ", ClientBase
- .waitForServerUp(HOSTPORT, CONNECTION_TIMEOUT));
+ assertTrue("waiting for server being up ", ClientBase.waitForServerUp(HOSTPORT, CONNECTION_TIMEOUT));
CountdownWatcher watcher = new CountdownWatcher();
ZooKeeper zk = new ZooKeeper(HOSTPORT, CONNECTION_TIMEOUT, watcher);
@@ -152,8 +144,7 @@ public class StandaloneTest extends QuorumPeerTestBase implements Watcher{
try {
zkAdmin.addAuthInfo("digest", "super:test".getBytes());
zkAdmin.reconfigure(joiners, null, null, -1, new Stat());
- Assert.fail("Reconfiguration in standalone should trigger " +
- "UnimplementedException");
+ fail("Reconfiguration in standalone should trigger " + "UnimplementedException");
} catch (KeeperException.UnimplementedException ex) {
// expected
}
@@ -161,7 +152,7 @@ public class StandaloneTest extends QuorumPeerTestBase implements Watcher{
zks.shutdown();
f.shutdown();
- Assert.assertTrue("waiting for server being down ", ClientBase
- .waitForServerDown(HOSTPORT, CONNECTION_TIMEOUT));
+ assertTrue("waiting for server being down ", ClientBase.waitForServerDown(HOSTPORT, CONNECTION_TIMEOUT));
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/StatTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/StatTest.java
index f4c01aa5c..cf575139b 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/StatTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/StatTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,17 +18,18 @@
package org.apache.zookeeper.test;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotSame;
import java.io.IOException;
-
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
-import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.ZooDefs.Ids;
+import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;
-import org.junit.Assert;
import org.junit.Test;
public class StatTest extends ClientBase {
+
private ZooKeeper zk;
@Override
@@ -46,7 +47,7 @@ public class StatTest extends ClientBase {
}
/**
- * Create a new Stat, fill in dummy values trying to catch Assert.failure
+ * Create a new Stat, fill in dummy values trying to catch failure
* to copy in client or server code.
*
* @return a new stat with dummy values
@@ -70,136 +71,123 @@ public class StatTest extends ClientBase {
}
@Test
- public void testBasic()
- throws IOException, KeeperException, InterruptedException
- {
+ public void testBasic() throws IOException, KeeperException, InterruptedException {
String name = "/foo";
- zk.create(name, name.getBytes(), Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk.create(name, name.getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
Stat stat;
stat = newStat();
zk.getData(name, false, stat);
- Assert.assertEquals(stat.getCzxid(), stat.getMzxid());
- Assert.assertEquals(stat.getCzxid(), stat.getPzxid());
- Assert.assertEquals(stat.getCtime(), stat.getMtime());
- Assert.assertEquals(0, stat.getCversion());
- Assert.assertEquals(0, stat.getVersion());
- Assert.assertEquals(0, stat.getAversion());
- Assert.assertEquals(0, stat.getEphemeralOwner());
- Assert.assertEquals(name.length(), stat.getDataLength());
- Assert.assertEquals(0, stat.getNumChildren());
+ assertEquals(stat.getCzxid(), stat.getMzxid());
+ assertEquals(stat.getCzxid(), stat.getPzxid());
+ assertEquals(stat.getCtime(), stat.getMtime());
+ assertEquals(0, stat.getCversion());
+ assertEquals(0, stat.getVersion());
+ assertEquals(0, stat.getAversion());
+ assertEquals(0, stat.getEphemeralOwner());
+ assertEquals(name.length(), stat.getDataLength());
+ assertEquals(0, stat.getNumChildren());
}
@Test
- public void testChild()
- throws IOException, KeeperException, InterruptedException
- {
+ public void testChild() throws IOException, KeeperException, InterruptedException {
String name = "/foo";
- zk.create(name, name.getBytes(), Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk.create(name, name.getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
String childname = name + "/bar";
- zk.create(childname, childname.getBytes(), Ids.OPEN_ACL_UNSAFE,
- CreateMode.EPHEMERAL);
+ zk.create(childname, childname.getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
Stat stat;
stat = newStat();
zk.getData(name, false, stat);
- Assert.assertEquals(stat.getCzxid(), stat.getMzxid());
- Assert.assertEquals(stat.getCzxid() + 1, stat.getPzxid());
- Assert.assertEquals(stat.getCtime(), stat.getMtime());
- Assert.assertEquals(1, stat.getCversion());
- Assert.assertEquals(0, stat.getVersion());
- Assert.assertEquals(0, stat.getAversion());
- Assert.assertEquals(0, stat.getEphemeralOwner());
- Assert.assertEquals(name.length(), stat.getDataLength());
- Assert.assertEquals(1, stat.getNumChildren());
+ assertEquals(stat.getCzxid(), stat.getMzxid());
+ assertEquals(stat.getCzxid() + 1, stat.getPzxid());
+ assertEquals(stat.getCtime(), stat.getMtime());
+ assertEquals(1, stat.getCversion());
+ assertEquals(0, stat.getVersion());
+ assertEquals(0, stat.getAversion());
+ assertEquals(0, stat.getEphemeralOwner());
+ assertEquals(name.length(), stat.getDataLength());
+ assertEquals(1, stat.getNumChildren());
stat = newStat();
zk.getData(childname, false, stat);
- Assert.assertEquals(stat.getCzxid(), stat.getMzxid());
- Assert.assertEquals(stat.getCzxid(), stat.getPzxid());
- Assert.assertEquals(stat.getCtime(), stat.getMtime());
- Assert.assertEquals(0, stat.getCversion());
- Assert.assertEquals(0, stat.getVersion());
- Assert.assertEquals(0, stat.getAversion());
- Assert.assertEquals(zk.getSessionId(), stat.getEphemeralOwner());
- Assert.assertEquals(childname.length(), stat.getDataLength());
- Assert.assertEquals(0, stat.getNumChildren());
+ assertEquals(stat.getCzxid(), stat.getMzxid());
+ assertEquals(stat.getCzxid(), stat.getPzxid());
+ assertEquals(stat.getCtime(), stat.getMtime());
+ assertEquals(0, stat.getCversion());
+ assertEquals(0, stat.getVersion());
+ assertEquals(0, stat.getAversion());
+ assertEquals(zk.getSessionId(), stat.getEphemeralOwner());
+ assertEquals(childname.length(), stat.getDataLength());
+ assertEquals(0, stat.getNumChildren());
}
@Test
- public void testChildren()
- throws IOException, KeeperException, InterruptedException
- {
+ public void testChildren() throws IOException, KeeperException, InterruptedException {
String name = "/foo";
- zk.create(name, name.getBytes(), Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk.create(name, name.getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
- for(int i = 0; i < 10; i++) {
+ for (int i = 0; i < 10; i++) {
String childname = name + "/bar" + i;
- zk.create(childname, childname.getBytes(), Ids.OPEN_ACL_UNSAFE,
- CreateMode.EPHEMERAL);
+ zk.create(childname, childname.getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
Stat stat;
stat = newStat();
zk.getData(name, false, stat);
- Assert.assertEquals(stat.getCzxid(), stat.getMzxid());
- Assert.assertEquals(stat.getCzxid() + i + 1, stat.getPzxid());
- Assert.assertEquals(stat.getCtime(), stat.getMtime());
- Assert.assertEquals(i + 1, stat.getCversion());
- Assert.assertEquals(0, stat.getVersion());
- Assert.assertEquals(0, stat.getAversion());
- Assert.assertEquals(0, stat.getEphemeralOwner());
- Assert.assertEquals(name.length(), stat.getDataLength());
- Assert.assertEquals(i + 1, stat.getNumChildren());
+ assertEquals(stat.getCzxid(), stat.getMzxid());
+ assertEquals(stat.getCzxid() + i + 1, stat.getPzxid());
+ assertEquals(stat.getCtime(), stat.getMtime());
+ assertEquals(i + 1, stat.getCversion());
+ assertEquals(0, stat.getVersion());
+ assertEquals(0, stat.getAversion());
+ assertEquals(0, stat.getEphemeralOwner());
+ assertEquals(name.length(), stat.getDataLength());
+ assertEquals(i + 1, stat.getNumChildren());
}
}
@Test
- public void testDataSizeChange()
- throws IOException, KeeperException, InterruptedException
- {
+ public void testDataSizeChange() throws IOException, KeeperException, InterruptedException {
String name = "/foo";
- zk.create(name, name.getBytes(), Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk.create(name, name.getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
Stat stat;
stat = newStat();
zk.getData(name, false, stat);
- Assert.assertEquals(stat.getCzxid(), stat.getMzxid());
- Assert.assertEquals(stat.getCzxid(), stat.getPzxid());
- Assert.assertEquals(stat.getCtime(), stat.getMtime());
- Assert.assertEquals(0, stat.getCversion());
- Assert.assertEquals(0, stat.getVersion());
- Assert.assertEquals(0, stat.getAversion());
- Assert.assertEquals(0, stat.getEphemeralOwner());
- Assert.assertEquals(name.length(), stat.getDataLength());
- Assert.assertEquals(0, stat.getNumChildren());
+ assertEquals(stat.getCzxid(), stat.getMzxid());
+ assertEquals(stat.getCzxid(), stat.getPzxid());
+ assertEquals(stat.getCtime(), stat.getMtime());
+ assertEquals(0, stat.getCversion());
+ assertEquals(0, stat.getVersion());
+ assertEquals(0, stat.getAversion());
+ assertEquals(0, stat.getEphemeralOwner());
+ assertEquals(name.length(), stat.getDataLength());
+ assertEquals(0, stat.getNumChildren());
zk.setData(name, (name + name).getBytes(), -1);
stat = newStat();
zk.getData(name, false, stat);
- Assert.assertNotSame(stat.getCzxid(), stat.getMzxid());
- Assert.assertEquals(stat.getCzxid(), stat.getPzxid());
- Assert.assertNotSame(stat.getCtime(), stat.getMtime());
- Assert.assertEquals(0, stat.getCversion());
- Assert.assertEquals(1, stat.getVersion());
- Assert.assertEquals(0, stat.getAversion());
- Assert.assertEquals(0, stat.getEphemeralOwner());
- Assert.assertEquals(name.length() * 2, stat.getDataLength());
- Assert.assertEquals(0, stat.getNumChildren());
+ assertNotSame(stat.getCzxid(), stat.getMzxid());
+ assertEquals(stat.getCzxid(), stat.getPzxid());
+ assertNotSame(stat.getCtime(), stat.getMtime());
+ assertEquals(0, stat.getCversion());
+ assertEquals(1, stat.getVersion());
+ assertEquals(0, stat.getAversion());
+ assertEquals(0, stat.getEphemeralOwner());
+ assertEquals(name.length() * 2, stat.getDataLength());
+ assertEquals(0, stat.getNumChildren());
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/StaticHostProviderTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/StaticHostProviderTest.java
index 998d6e59f..7095c14f0 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/StaticHostProviderTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/StaticHostProviderTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,22 +18,6 @@
package org.apache.zookeeper.test;
-import org.apache.zookeeper.ZKTestCase;
-import org.apache.zookeeper.client.HostProvider;
-import org.apache.zookeeper.client.StaticHostProvider;
-import org.apache.zookeeper.common.Time;
-import org.junit.Test;
-
-import java.net.InetAddress;
-import java.net.InetSocketAddress;
-import java.net.UnknownHostException;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.List;
-import java.util.Random;
-
import static org.hamcrest.CoreMatchers.anyOf;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.hasItems;
@@ -50,8 +34,23 @@ import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
+import java.net.InetAddress;
+import java.net.InetSocketAddress;
+import java.net.UnknownHostException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.List;
+import java.util.Random;
+import org.apache.zookeeper.ZKTestCase;
+import org.apache.zookeeper.client.HostProvider;
+import org.apache.zookeeper.client.StaticHostProvider;
+import org.apache.zookeeper.common.Time;
+import org.junit.Test;
public class StaticHostProviderTest extends ZKTestCase {
+
private Random r = new Random(1);
@Test
@@ -147,7 +146,7 @@ public class StaticHostProviderTest extends ZKTestCase {
boolean disconnectRequired = hostProvider.updateServerList(newList, myServer);
assertFalse(disconnectRequired);
hostProvider.onConnected();
-
+
// Number of machines stayed the same, my server is in the new cluster
disconnectRequired = hostProvider.updateServerList(newList, myServer);
assertFalse(disconnectRequired);
@@ -187,8 +186,9 @@ public class StaticHostProviderTest extends ZKTestCase {
for (int i = 0; i < numClients; i++) {
hostProviderArray[i] = getHostProvider((byte) 9);
disconnectRequired = hostProviderArray[i].updateServerList(newList, myServer);
- if (disconnectRequired)
+ if (disconnectRequired) {
numDisconnects++;
+ }
}
hostProvider.onConnected();
@@ -202,7 +202,7 @@ public class StaticHostProviderTest extends ZKTestCase {
// old list (just the ports): 1238, 1237, 1236, 1235
Collection<InetSocketAddress> newList = new ArrayList<InetSocketAddress>(10);
for (byte i = 12; i > 2; i--) { // 1246, 1245, 1244, 1243, 1242, 1241,
- // 1240, 1239, 1238, 1237
+ // 1240, 1239, 1238, 1237
newList.add(new InetSocketAddress(InetAddress.getByAddress(new byte[]{10, 10, 10, i}), 1234 + i));
}
@@ -285,7 +285,9 @@ public class StaticHostProviderTest extends ZKTestCase {
for (int i = 0; i < numClients; i++) {
disconnectRequired = hostProviderArray[i].updateServerList(newList, curHostForEachClient[i]);
- if (disconnectRequired) curHostForEachClient[i] = hostProviderArray[i].next(0);
+ if (disconnectRequired) {
+ curHostForEachClient[i] = hostProviderArray[i].next(0);
+ }
numClientsPerHost[curHostForEachClient[i].getPort() - 1235]++;
hostProviderArray[i].onConnected();
}
@@ -302,7 +304,9 @@ public class StaticHostProviderTest extends ZKTestCase {
for (int i = 0; i < numClients; i++) {
disconnectRequired = hostProviderArray[i].updateServerList(newList, curHostForEachClient[i]);
- if (disconnectRequired) curHostForEachClient[i] = hostProviderArray[i].next(0);
+ if (disconnectRequired) {
+ curHostForEachClient[i] = hostProviderArray[i].next(0);
+ }
numClientsPerHost[curHostForEachClient[i].getPort() - 1235]++;
hostProviderArray[i].onConnected();
}
@@ -325,7 +329,9 @@ public class StaticHostProviderTest extends ZKTestCase {
for (int i = 0; i < numClients; i++) {
disconnectRequired = hostProviderArray[i].updateServerList(newList, curHostForEachClient[i]);
- if (disconnectRequired) curHostForEachClient[i] = hostProviderArray[i].next(0);
+ if (disconnectRequired) {
+ curHostForEachClient[i] = hostProviderArray[i].next(0);
+ }
numClientsPerHost[curHostForEachClient[i].getPort() - 1235]++;
hostProviderArray[i].onConnected();
}
@@ -343,7 +349,9 @@ public class StaticHostProviderTest extends ZKTestCase {
for (int i = 0; i < numClients; i++) {
disconnectRequired = hostProviderArray[i].updateServerList(newList, curHostForEachClient[i]);
- if (disconnectRequired) curHostForEachClient[i] = hostProviderArray[i].next(0);
+ if (disconnectRequired) {
+ curHostForEachClient[i] = hostProviderArray[i].next(0);
+ }
numClientsPerHost[curHostForEachClient[i].getPort() - 1235]++;
hostProviderArray[i].onConnected();
}
@@ -380,14 +388,12 @@ public class StaticHostProviderTest extends ZKTestCase {
for (int i = 0; i < numClients; i++) {
// tests the case currentHost == null && lastIndex == -1
// calls next for clients with index < numClients/2
- disconnectRequired = hostProviderArray[i].updateServerList(newList,
- curHostForEachClient[i]);
- if (disconnectRequired)
+ disconnectRequired = hostProviderArray[i].updateServerList(newList, curHostForEachClient[i]);
+ if (disconnectRequired) {
curHostForEachClient[i] = hostProviderArray[i].next(0);
- else if (curHostForEachClient[i] == null) {
+ } else if (curHostForEachClient[i] == null) {
// (*) setting it to what it should be
- curHostForEachClient[i] = hostProviderArray[i]
- .getServerAtIndex(0);
+ curHostForEachClient[i] = hostProviderArray[i].getServerAtIndex(0);
}
numClientsPerHost[curHostForEachClient[i].getPort() - 1235]++;
// sets lastIndex, resets reconfigMode
@@ -406,13 +412,12 @@ public class StaticHostProviderTest extends ZKTestCase {
newList = getServerAddresses((byte) 8);
for (int i = 0; i < numClients; i++) {
- InetSocketAddress myServer = (i < (numClients / 2)) ? null
- : curHostForEachClient[i];
+ InetSocketAddress myServer = (i < (numClients / 2)) ? null : curHostForEachClient[i];
// tests the case currentHost == null && lastIndex >= 0
- disconnectRequired = hostProviderArray[i].updateServerList(newList,
- myServer);
- if (disconnectRequired)
+ disconnectRequired = hostProviderArray[i].updateServerList(newList, myServer);
+ if (disconnectRequired) {
curHostForEachClient[i] = hostProviderArray[i].next(0);
+ }
numClientsPerHost[curHostForEachClient[i].getPort() - 1235]++;
hostProviderArray[i].onConnected();
}
@@ -442,8 +447,7 @@ public class StaticHostProviderTest extends ZKTestCase {
for (int i = 0; i < numClients; i++) {
// sets reconfigMode
- hostProviderArray[i].updateServerList(newList,
- curHostForEachClient[i]);
+ hostProviderArray[i].updateServerList(newList, curHostForEachClient[i]);
}
// add back servers 7 and 8 while still in reconfigMode (we didn't call
@@ -451,21 +455,18 @@ public class StaticHostProviderTest extends ZKTestCase {
newList = getServerAddresses((byte) 9);
for (int i = 0; i < numClients; i++) {
- InetSocketAddress myServer = (i < (numClients / 2)) ? null
- : curHostForEachClient[i];
+ InetSocketAddress myServer = (i < (numClients / 2)) ? null : curHostForEachClient[i];
// for i < (numClients/2) this tests the case currentHost == null &&
// reconfigMode = true
// for i >= (numClients/2) this tests the case currentHost!=null &&
// reconfigMode = true
- disconnectRequired = hostProviderArray[i].updateServerList(newList,
- myServer);
- if (disconnectRequired)
+ disconnectRequired = hostProviderArray[i].updateServerList(newList, myServer);
+ if (disconnectRequired) {
curHostForEachClient[i] = hostProviderArray[i].next(0);
- else {
+ } else {
// currentIndex was set by the call to updateServerList, which
// called next
- curHostForEachClient[i] = hostProviderArray[i]
- .getServerAtCurrentIndex();
+ curHostForEachClient[i] = hostProviderArray[i].getServerAtCurrentIndex();
}
numClientsPerHost[curHostForEachClient[i].getPort() - 1235]++;
hostProviderArray[i].onConnected();
@@ -481,9 +482,8 @@ public class StaticHostProviderTest extends ZKTestCase {
return new StaticHostProvider(getServerAddresses(size), r.nextLong());
}
- private Collection<InetSocketAddress> getServerAddresses(byte size) {
- ArrayList<InetSocketAddress> list = new ArrayList<InetSocketAddress>(
- size);
+ private Collection<InetSocketAddress> getServerAddresses(byte size) {
+ ArrayList<InetSocketAddress> list = new ArrayList<InetSocketAddress>(size);
while (size > 0) {
try {
list.add(new InetSocketAddress(InetAddress.getByAddress(new byte[]{10, 10, 10, size}), 1234 + size));
@@ -582,21 +582,15 @@ public class StaticHostProviderTest extends ZKTestCase {
public void testUpdateServerList_ResolvedWithUnResolvedAddress_ForceDisconnect() {
// Arrange
// Create a HostProvider with a list of unresolved server address(es)
- List<InetSocketAddress> addresses = Collections.singletonList(
- InetSocketAddress.createUnresolved("testhost-1.resolvable.zk", 1235)
- );
+ List<InetSocketAddress> addresses = Collections.singletonList(InetSocketAddress.createUnresolved("testhost-1.resolvable.zk", 1235));
HostProvider hostProvider = new StaticHostProvider(addresses, new TestResolver());
InetSocketAddress currentHost = hostProvider.next(100);
- assertThat("CurrentHost is which the client is currently connecting to, it should be resolved",
- currentHost.isUnresolved(), is(false));
+ assertThat("CurrentHost is which the client is currently connecting to, it should be resolved", currentHost.isUnresolved(), is(false));
// Act
InetSocketAddress replaceHost = InetSocketAddress.createUnresolved("testhost-1.resolvable.zk", 1235);
assertThat("Replace host must be unresolved in this test case", replaceHost.isUnresolved(), is(true));
- boolean disconnect = hostProvider.updateServerList(new ArrayList<>(
- Collections.singletonList(replaceHost)),
- currentHost
- );
+ boolean disconnect = hostProvider.updateServerList(new ArrayList<>(Collections.singletonList(replaceHost)), currentHost);
// Assert
assertThat(disconnect, is(false));
@@ -606,23 +600,15 @@ public class StaticHostProviderTest extends ZKTestCase {
public void testUpdateServerList_ResolvedWithResolvedAddress_NoDisconnect() throws UnknownHostException {
// Arrange
// Create a HostProvider with a list of unresolved server address(es)
- List<InetSocketAddress> addresses = Collections.singletonList(
- InetSocketAddress.createUnresolved("testhost-1.resolvable.zk", 1235)
- );
+ List<InetSocketAddress> addresses = Collections.singletonList(InetSocketAddress.createUnresolved("testhost-1.resolvable.zk", 1235));
HostProvider hostProvider = new StaticHostProvider(addresses, new TestResolver());
InetSocketAddress currentHost = hostProvider.next(100);
- assertThat("CurrentHost is which the client is currently connecting to, it should be resolved",
- currentHost.isUnresolved(), is(false));
+ assertThat("CurrentHost is which the client is currently connecting to, it should be resolved", currentHost.isUnresolved(), is(false));
// Act
- InetSocketAddress replaceHost =
- new InetSocketAddress(InetAddress.getByAddress(currentHost.getHostString(),
- currentHost.getAddress().getAddress()), currentHost.getPort());
+ InetSocketAddress replaceHost = new InetSocketAddress(InetAddress.getByAddress(currentHost.getHostString(), currentHost.getAddress().getAddress()), currentHost.getPort());
assertThat("Replace host must be resolved in this test case", replaceHost.isUnresolved(), is(false));
- boolean disconnect = hostProvider.updateServerList(new ArrayList<>(
- Collections.singletonList(replaceHost)),
- currentHost
- );
+ boolean disconnect = hostProvider.updateServerList(new ArrayList<>(Collections.singletonList(replaceHost)), currentHost);
// Assert
assertThat(disconnect, equalTo(false));
@@ -632,21 +618,15 @@ public class StaticHostProviderTest extends ZKTestCase {
public void testUpdateServerList_UnResolvedWithUnResolvedAddress_ForceDisconnect() {
// Arrange
// Create a HostProvider with a list of unresolved server address(es)
- List<InetSocketAddress> addresses = Collections.singletonList(
- InetSocketAddress.createUnresolved("testhost-1.zookeepertest.zk", 1235)
- );
+ List<InetSocketAddress> addresses = Collections.singletonList(InetSocketAddress.createUnresolved("testhost-1.zookeepertest.zk", 1235));
HostProvider hostProvider = new StaticHostProvider(addresses, new TestResolver());
InetSocketAddress currentHost = hostProvider.next(100);
- assertThat("CurrentHost is not resolvable in this test case",
- currentHost.isUnresolved(), is(true));
+ assertThat("CurrentHost is not resolvable in this test case", currentHost.isUnresolved(), is(true));
// Act
InetSocketAddress replaceHost = InetSocketAddress.createUnresolved("testhost-1.resolvable.zk", 1235);
assertThat("Replace host must be unresolved in this test case", replaceHost.isUnresolved(), is(true));
- boolean disconnect = hostProvider.updateServerList(new ArrayList<>(
- Collections.singletonList(replaceHost)),
- currentHost
- );
+ boolean disconnect = hostProvider.updateServerList(new ArrayList<>(Collections.singletonList(replaceHost)), currentHost);
// Assert
assertThat(disconnect, is(true));
@@ -656,48 +636,42 @@ public class StaticHostProviderTest extends ZKTestCase {
public void testUpdateServerList_UnResolvedWithResolvedAddress_ForceDisconnect() throws UnknownHostException {
// Arrange
// Create a HostProvider with a list of unresolved server address(es)
- List<InetSocketAddress> addresses = Collections.singletonList(
- InetSocketAddress.createUnresolved("testhost-1.zookeepertest.zk", 1235)
- );
+ List<InetSocketAddress> addresses = Collections.singletonList(InetSocketAddress.createUnresolved("testhost-1.zookeepertest.zk", 1235));
HostProvider hostProvider = new StaticHostProvider(addresses, new TestResolver());
InetSocketAddress currentHost = hostProvider.next(100);
- assertThat("CurrentHost not resolvable in this test case",
- currentHost.isUnresolved(), is(true));
+ assertThat("CurrentHost not resolvable in this test case", currentHost.isUnresolved(), is(true));
// Act
- byte[] addr = new byte[] { 10, 0, 0, 1 };
- InetSocketAddress replaceHost =
- new InetSocketAddress(InetAddress.getByAddress(currentHost.getHostString(), addr),
- currentHost.getPort());
+ byte[] addr = new byte[]{10, 0, 0, 1};
+ InetSocketAddress replaceHost = new InetSocketAddress(InetAddress.getByAddress(currentHost.getHostString(), addr), currentHost.getPort());
assertThat("Replace host must be resolved in this test case", replaceHost.isUnresolved(), is(false));
- boolean disconnect = hostProvider.updateServerList(new ArrayList<>(
- Collections.singletonList(replaceHost)),
- currentHost
- );
+ boolean disconnect = hostProvider.updateServerList(new ArrayList<>(Collections.singletonList(replaceHost)), currentHost);
// Assert
assertThat(disconnect, equalTo(false));
}
private class TestResolver implements StaticHostProvider.Resolver {
+
private byte counter = 1;
@Override
public InetAddress[] getAllByName(String name) throws UnknownHostException {
if (name.contains("resolvable")) {
- byte[] addr = new byte[] { 10, 0, 0, (byte)(counter++ % 10) };
- return new InetAddress[] { InetAddress.getByAddress(name, addr) };
+ byte[] addr = new byte[]{10, 0, 0, (byte) (counter++ % 10)};
+ return new InetAddress[]{InetAddress.getByAddress(name, addr)};
}
throw new UnknownHostException();
}
+
}
private double lowerboundCPS(int numClients, int numServers) {
- return (1 - slackPercent/100.0) * numClients / numServers;
+ return (1 - slackPercent / 100.0) * numClients / numServers;
}
private double upperboundCPS(int numClients, int numServers) {
- return (1 + slackPercent/100.0) * numClients / numServers;
+ return (1 + slackPercent / 100.0) * numClients / numServers;
}
/* DNS resolution tests */
@@ -735,9 +709,7 @@ public class StaticHostProviderTest extends ZKTestCase {
StaticHostProvider.Resolver resolver = new StaticHostProvider.Resolver() {
@Override
public InetAddress[] getAllByName(String name) {
- return new InetAddress[] {
- issuesApacheOrg
- };
+ return new InetAddress[]{issuesApacheOrg};
}
};
StaticHostProvider.Resolver spyResolver = spy(resolver);
@@ -805,10 +777,10 @@ public class StaticHostProviderTest extends ZKTestCase {
final List<String> ipList = new ArrayList<String>();
final List<InetAddress> resolvedAddresses = new ArrayList<InetAddress>();
for (int i = 0; i < 3; i++) {
- ipList.add(String.format("192.168.1.%d", i+1));
+ ipList.add(String.format("192.168.1.%d", i + 1));
final InetAddress apacheOrg = mock(InetAddress.class);
- when(apacheOrg.getHostAddress()).thenReturn(String.format("192.168.1.%d", i+1));
- when(apacheOrg.toString()).thenReturn(String.format("192.168.1.%d", i+1));
+ when(apacheOrg.getHostAddress()).thenReturn(String.format("192.168.1.%d", i + 1));
+ when(apacheOrg.toString()).thenReturn(String.format("192.168.1.%d", i + 1));
when(apacheOrg.getHostName()).thenReturn("www.apache.org");
resolvedAddresses.add(apacheOrg);
}
@@ -899,8 +871,11 @@ public class StaticHostProviderTest extends ZKTestCase {
int sizeBefore = hostProvider.size();
InetSocketAddress next = hostProvider.next(0);
next = hostProvider.next(0);
- assertTrue("Different number of addresses in the list: " + hostProvider.size() +
- " (after), " + sizeBefore + " (before)", hostProvider.size() == sizeBefore);
+ assertTrue("Different number of addresses in the list: "
+ + hostProvider.size()
+ + " (after), "
+ + sizeBefore
+ + " (before)", hostProvider.size() == sizeBefore);
}
private StaticHostProvider getHostProviderUnresolved(byte size) {
@@ -923,10 +898,12 @@ public class StaticHostProviderTest extends ZKTestCase {
private Collection<InetSocketAddress> getUnresolvedHostnames(int size) {
ArrayList<InetSocketAddress> list = new ArrayList<>(size);
while (size > 0) {
- list.add(InetSocketAddress.createUnresolved(String.format("testhost-%d.testdomain.com", size), 1234 + size));
+ list.add(InetSocketAddress.createUnresolved(String.format("testhost-%d.testdomain.com", size), 1234
+ + size));
--size;
}
System.out.println(Arrays.toString(list.toArray()));
return list;
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/StringUtilTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/StringUtilTest.java
index 29d197fd4..caa3db631 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/StringUtilTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/StringUtilTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -15,17 +15,14 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package org.apache.zookeeper.test;
+package org.apache.zookeeper.test;
+import static org.junit.Assert.assertEquals;
import org.apache.zookeeper.ZKTestCase;
import org.apache.zookeeper.common.StringUtils;
import org.junit.Test;
-import java.util.Arrays;
-
-import static org.junit.Assert.assertEquals;
-
public class StringUtilTest extends ZKTestCase {
@Test
@@ -41,4 +38,5 @@ public class StringUtilTest extends ZKTestCase {
assertEquals("[1, 2]", StringUtils.split(s3, ",").toString());
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/SyncCallTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/SyncCallTest.java
index 7e6188c5a..6817fec67 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/SyncCallTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/SyncCallTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,34 +18,32 @@
package org.apache.zookeeper.test;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.fail;
import java.io.IOException;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
-
-import org.apache.zookeeper.CreateMode;
-import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.AsyncCallback.Children2Callback;
import org.apache.zookeeper.AsyncCallback.ChildrenCallback;
import org.apache.zookeeper.AsyncCallback.Create2Callback;
import org.apache.zookeeper.AsyncCallback.StringCallback;
import org.apache.zookeeper.AsyncCallback.VoidCallback;
+import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.ZooDefs.Ids;
+import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;
-import org.junit.Assert;
import org.junit.Test;
-public class SyncCallTest extends ClientBase
- implements ChildrenCallback, Children2Callback,
- StringCallback, VoidCallback, Create2Callback
-{
+public class SyncCallTest extends ClientBase implements ChildrenCallback, Children2Callback, StringCallback, VoidCallback, Create2Callback {
+
private CountDownLatch opsCount;
-
+
List<Integer> results = new LinkedList<Integer>();
Integer limit = 100 + 1 + 100 + 100;
-
+
@Test
public void testSync() throws Exception {
try {
@@ -54,71 +52,72 @@ public class SyncCallTest extends ClientBase
ZooKeeper zk = createClient();
LOG.info("Beginning test:" + (new Date()).toString());
- for(int i = 0; i < 50; i++)
- zk.create("/test" + i, new byte[0], Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT, (StringCallback)this, results);
+ for (int i = 0; i < 50; i++) {
+ zk.create("/test"
+ + i, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT, (StringCallback) this, results);
+ }
- for(int i = 50; i < 100; i++) {
- zk.create("/test" + i, new byte[0], Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT, (Create2Callback)this, results);
+ for (int i = 50; i < 100; i++) {
+ zk.create("/test"
+ + i, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT, (Create2Callback) this, results);
}
zk.sync("/test", this, results);
- for(int i = 0; i < 100; i++)
+ for (int i = 0; i < 100; i++) {
zk.delete("/test" + i, 0, this, results);
- for(int i = 0; i < 100; i++)
- zk.getChildren("/", new NullWatcher(), (ChildrenCallback)this,
- results);
- for(int i = 0; i < 100; i++)
- zk.getChildren("/", new NullWatcher(), (Children2Callback)this,
- results);
+ }
+ for (int i = 0; i < 100; i++) {
+ zk.getChildren("/", new NullWatcher(), (ChildrenCallback) this, results);
+ }
+ for (int i = 0; i < 100; i++) {
+ zk.getChildren("/", new NullWatcher(), (Children2Callback) this, results);
+ }
LOG.info("Submitted all operations:" + (new Date()).toString());
-
- if(!opsCount.await(10000, TimeUnit.MILLISECONDS))
- Assert.fail("Haven't received all confirmations" + opsCount.getCount());
- for(int i = 0; i < limit ; i++){
- Assert.assertEquals(0, (int) results.get(i));
+ if (!opsCount.await(10000, TimeUnit.MILLISECONDS)) {
+ fail("Haven't received all confirmations" + opsCount.getCount());
}
-
+
+ for (int i = 0; i < limit; i++) {
+ assertEquals(0, (int) results.get(i));
+ }
+
} catch (IOException e) {
System.out.println(e.toString());
- }
+ }
}
@SuppressWarnings("unchecked")
- public void processResult(int rc, String path, Object ctx,
- List<String> children) {
- ((List<Integer>)ctx).add(rc);
+ public void processResult(int rc, String path, Object ctx, List<String> children) {
+ ((List<Integer>) ctx).add(rc);
opsCount.countDown();
}
@SuppressWarnings("unchecked")
- public void processResult(int rc, String path, Object ctx,
- List<String> children, Stat stat) {
- ((List<Integer>)ctx).add(rc);
+ public void processResult(int rc, String path, Object ctx, List<String> children, Stat stat) {
+ ((List<Integer>) ctx).add(rc);
opsCount.countDown();
}
@SuppressWarnings("unchecked")
- public void processResult(int rc, String path, Object ctx, String name){
+ public void processResult(int rc, String path, Object ctx, String name) {
((List<Integer>) ctx).add(rc);
opsCount.countDown();
-
+
}
@SuppressWarnings("unchecked")
@Override
- public void processResult(int rc, String path, Object ctx){
- ((List<Integer>) ctx).add(rc);
+ public void processResult(int rc, String path, Object ctx) {
+ ((List<Integer>) ctx).add(rc);
opsCount.countDown();
-
+
}
@SuppressWarnings("unchecked")
@Override
- public void processResult(int rc, String path, Object ctx, String name,
- Stat stat) {
- ((List<Integer>) ctx).add(rc);
- opsCount.countDown();
+ public void processResult(int rc, String path, Object ctx, String name, Stat stat) {
+ ((List<Integer>) ctx).add(rc);
+ opsCount.countDown();
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/TestByteBufAllocator.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/TestByteBufAllocator.java
index dc1322278..a6b3251ad 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/TestByteBufAllocator.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/TestByteBufAllocator.java
@@ -18,15 +18,14 @@
package org.apache.zookeeper.test;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Objects;
-import java.util.concurrent.atomic.AtomicReference;
-
import io.netty.buffer.ByteBuf;
import io.netty.buffer.CompositeByteBuf;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.util.ResourceLeakDetector;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Objects;
+import java.util.concurrent.atomic.AtomicReference;
/**
* This is a custom ByteBufAllocator that tracks outstanding allocations and
@@ -46,8 +45,8 @@ import io.netty.util.ResourceLeakDetector;
*
*/
public class TestByteBufAllocator extends PooledByteBufAllocator {
- private static AtomicReference<TestByteBufAllocator> INSTANCE =
- new AtomicReference<>(null);
+
+ private static AtomicReference<TestByteBufAllocator> INSTANCE = new AtomicReference<>(null);
/**
* Get the singleton testing allocator.
@@ -84,56 +83,46 @@ public class TestByteBufAllocator extends PooledByteBufAllocator {
private final List<ByteBuf> trackedBuffers = new ArrayList<>();
private final ResourceLeakDetector.Level oldLevel;
- private TestByteBufAllocator(ResourceLeakDetector.Level oldLevel)
- {
+ private TestByteBufAllocator(ResourceLeakDetector.Level oldLevel) {
super(false);
this.oldLevel = oldLevel;
}
@Override
- protected ByteBuf newHeapBuffer(int initialCapacity, int maxCapacity)
- {
+ protected ByteBuf newHeapBuffer(int initialCapacity, int maxCapacity) {
return track(super.newHeapBuffer(initialCapacity, maxCapacity));
}
@Override
- protected ByteBuf newDirectBuffer(int initialCapacity, int maxCapacity)
- {
+ protected ByteBuf newDirectBuffer(int initialCapacity, int maxCapacity) {
return track(super.newDirectBuffer(initialCapacity, maxCapacity));
}
@Override
- public CompositeByteBuf compositeHeapBuffer(int maxNumComponents)
- {
+ public CompositeByteBuf compositeHeapBuffer(int maxNumComponents) {
return track(super.compositeHeapBuffer(maxNumComponents));
}
@Override
- public CompositeByteBuf compositeDirectBuffer(int maxNumComponents)
- {
+ public CompositeByteBuf compositeDirectBuffer(int maxNumComponents) {
return track(super.compositeDirectBuffer(maxNumComponents));
}
- private synchronized CompositeByteBuf track(CompositeByteBuf byteBuf)
- {
+ private synchronized CompositeByteBuf track(CompositeByteBuf byteBuf) {
trackedBuffers.add(Objects.requireNonNull(byteBuf));
return byteBuf;
}
- private synchronized ByteBuf track(ByteBuf byteBuf)
- {
+ private synchronized ByteBuf track(ByteBuf byteBuf) {
trackedBuffers.add(Objects.requireNonNull(byteBuf));
return byteBuf;
}
- private void checkInstanceForLeaks()
- {
+ private void checkInstanceForLeaks() {
try {
long referencedBuffersCount = 0;
synchronized (this) {
- referencedBuffersCount = trackedBuffers.stream()
- .filter(byteBuf -> byteBuf.refCnt() > 0)
- .count();
+ referencedBuffersCount = trackedBuffers.stream().filter(byteBuf -> byteBuf.refCnt() > 0).count();
// Make tracked buffers eligible for GC
trackedBuffers.clear();
}
@@ -149,4 +138,5 @@ public class TestByteBufAllocator extends PooledByteBufAllocator {
ResourceLeakDetector.setLevel(oldLevel);
}
}
-} \ No newline at end of file
+
+}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/TestByteBufAllocatorTestHelper.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/TestByteBufAllocatorTestHelper.java
index de5e751f2..2fa40da14 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/TestByteBufAllocatorTestHelper.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/TestByteBufAllocatorTestHelper.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,10 +18,9 @@
package org.apache.zookeeper.test;
+import io.netty.buffer.ByteBufAllocator;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
-
-import io.netty.buffer.ByteBufAllocator;
import org.apache.zookeeper.ClientCnxnSocketNetty;
import org.apache.zookeeper.server.NettyServerCnxnFactory;
@@ -30,8 +29,8 @@ import org.apache.zookeeper.server.NettyServerCnxnFactory;
* to set/clear the test ByteBufAllocator.
*/
public class TestByteBufAllocatorTestHelper {
- public static void setTestAllocator(ByteBufAllocator allocator)
- throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
+
+ public static void setTestAllocator(ByteBufAllocator allocator) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
Method m1 = NettyServerCnxnFactory.class.getDeclaredMethod("setTestAllocator", ByteBufAllocator.class);
m1.setAccessible(true);
m1.invoke(null, allocator);
@@ -40,8 +39,7 @@ public class TestByteBufAllocatorTestHelper {
m2.invoke(null, allocator);
}
- public static void clearTestAllocator()
- throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
+ public static void clearTestAllocator() throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
Method m1 = NettyServerCnxnFactory.class.getDeclaredMethod("clearTestAllocator");
m1.setAccessible(true);
m1.invoke(null);
@@ -49,4 +47,5 @@ public class TestByteBufAllocatorTestHelper {
m2.setAccessible(true);
m2.invoke(null);
}
-} \ No newline at end of file
+
+}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/TestHammer.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/TestHammer.java
index f73f1918a..162b9e435 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/TestHammer.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/TestHammer.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,36 +18,34 @@
package org.apache.zookeeper.test;
-
-import org.apache.zookeeper.CreateMode;
-import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.AsyncCallback.VoidCallback;
+import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.ZooDefs.Ids;
+import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.common.Time;
public class TestHammer implements VoidCallback {
static int REPS = 50000;
public static void main(String[] args) {
- long startTime = Time.currentElapsedTime();
- ZooKeeper zk = null;
+ long startTime = Time.currentElapsedTime();
+ ZooKeeper zk = null;
+ try {
+ zk = ClientBase.createZKClient(args[0], 10000);
+ } catch (Exception e1) {
+ e1.printStackTrace();
+ throw new RuntimeException(e1);
+ }
+ for (int i = 0; i < REPS; i++) {
try {
- zk = ClientBase.createZKClient(args[0], 10000);
- } catch (Exception e1) {
- e1.printStackTrace();
- throw new RuntimeException(e1);
- }
- for(int i = 0; i < REPS; i++) {
- try {
- String name = zk.create("/testFile-", new byte[16], Ids.OPEN_ACL_UNSAFE,
- CreateMode.EPHEMERAL_SEQUENTIAL);
- zk.delete(name, -1, new TestHammer(), null);
- } catch(Exception e) {
- i--;
- e.printStackTrace();
- }
+ String name = zk.create("/testFile-", new byte[16], Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
+ zk.delete(name, -1, new TestHammer(), null);
+ } catch (Exception e) {
+ i--;
+ e.printStackTrace();
}
- System.out.println("creates/sec=" + (REPS*1000/(Time.currentElapsedTime()-startTime)));
+ }
+ System.out.println("creates/sec=" + (REPS * 1000 / (Time.currentElapsedTime() - startTime)));
}
public void processResult(int rc, String path, Object ctx) {
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/TestUtils.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/TestUtils.java
index 95f02eeb2..a38d49e48 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/TestUtils.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/TestUtils.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -15,12 +15,12 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
package org.apache.zookeeper.test;
+import static org.junit.Assert.fail;
import java.io.File;
-import org.junit.Assert;
-
/**
* This class contains test utility methods
*/
@@ -28,14 +28,14 @@ public class TestUtils {
/**
* deletes a folder recursively
- *
+ *
* @param file
* folder to be deleted
* @param failOnError
* if true file deletion success is ensured
*/
- public static boolean deleteFileRecursively(File file,
- final boolean failOnError) {
+ public static boolean deleteFileRecursively(
+ File file, final boolean failOnError) {
if (file != null) {
if (file.isDirectory()) {
File[] files = file.listFiles();
@@ -43,9 +43,8 @@ public class TestUtils {
for (int i = 0; i < size; i++) {
File f = files[i];
boolean deleted = deleteFileRecursively(files[i], failOnError);
- if(!deleted && failOnError)
- {
- Assert.fail("file '" + f.getAbsolutePath()+"' deletion failed");
+ if (!deleted && failOnError) {
+ fail("file '" + f.getAbsolutePath() + "' deletion failed");
}
}
}
@@ -57,4 +56,5 @@ public class TestUtils {
public static boolean deleteFileRecursively(File file) {
return deleteFileRecursively(file, false);
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/TruncateTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/TruncateTest.java
index 2290a3445..f7a448e38 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/TruncateTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/TruncateTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,12 +18,14 @@
package org.apache.zookeeper.test;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
import java.io.File;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.HashMap;
import java.util.Map;
-
import org.apache.jute.Record;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
@@ -44,23 +46,23 @@ import org.apache.zookeeper.server.quorum.QuorumPeer.QuorumServer;
import org.apache.zookeeper.txn.SetDataTxn;
import org.apache.zookeeper.txn.TxnHeader;
import org.junit.After;
-import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class TruncateTest extends ZKTestCase {
- private static final Logger LOG = LoggerFactory.getLogger(TruncateTest.class);
+
+ private static final Logger LOG = LoggerFactory.getLogger(TruncateTest.class);
File dataDir1, dataDir2, dataDir3;
-
+
@Before
public void setUp() throws IOException {
dataDir1 = ClientBase.createTmpDir();
dataDir2 = ClientBase.createTmpDir();
dataDir3 = ClientBase.createTmpDir();
}
-
+
@After
public void tearDown() {
ClientBase.recursiveDelete(dataDir1);
@@ -68,7 +70,6 @@ public class TruncateTest extends ZKTestCase {
ClientBase.recursiveDelete(dataDir3);
}
-
@Test
public void testTruncationStreamReset() throws Exception {
File tmpdir = ClientBase.createTmpDir();
@@ -95,15 +96,15 @@ public class TruncateTest extends ZKTestCase {
TxnHeader hdr = iter.getHeader();
Record txn = iter.getTxn();
- Assert.assertEquals(1, hdr.getZxid());
- Assert.assertTrue(txn instanceof SetDataTxn);
+ assertEquals(1, hdr.getZxid());
+ assertTrue(txn instanceof SetDataTxn);
iter.next();
hdr = iter.getHeader();
txn = iter.getTxn();
- Assert.assertEquals(200, hdr.getZxid());
- Assert.assertTrue(txn instanceof SetDataTxn);
+ assertEquals(200, hdr.getZxid());
+ assertTrue(txn instanceof SetDataTxn);
iter.close();
ClientBase.recursiveDelete(tmpdir);
}
@@ -119,21 +120,19 @@ public class TruncateTest extends ZKTestCase {
}
zkdb.close();
File[] logs = snaplog.getDataDir().listFiles();
- for(int i = 0; i < logs.length; i++) {
+ for (int i = 0; i < logs.length; i++) {
LOG.debug("Deleting: {}", logs[i].getName());
- Assert.assertTrue("Failed to delete log file: " + logs[i].getName(), logs[i].delete());
+ assertTrue("Failed to delete log file: " + logs[i].getName(), logs[i].delete());
}
try {
zkdb.truncateLog(1);
- Assert.assertTrue("Should not get here", false);
- }
- catch(IOException e) {
- Assert.assertTrue("Should have received an IOException", true);
+ assertTrue("Should not get here", false);
+ } catch (IOException e) {
+ assertTrue("Should have received an IOException", true);
+ } catch (NullPointerException npe) {
+ fail("This should not throw NPE!");
}
- catch(NullPointerException npe) {
- Assert.fail("This should not throw NPE!");
- }
-
+
ClientBase.recursiveDelete(tmpdir);
}
@@ -151,8 +150,7 @@ public class TruncateTest extends ZKTestCase {
// Prime the server that is going to come in late with 50 txns
String hostPort = "127.0.0.1:" + PortAssignment.unique();
int maxCnxns = 100;
- ServerCnxnFactory factory = ClientBase.createNewServerInstance(null,
- hostPort, maxCnxns);
+ ServerCnxnFactory factory = ClientBase.createNewServerInstance(null, hostPort, maxCnxns);
ClientBase.startServerInstance(dataDir1, factory, hostPort, 1);
ClientBase.shutdownServerInstance(factory, hostPort);
@@ -165,15 +163,15 @@ public class TruncateTest extends ZKTestCase {
ClientBase.startServerInstance(dataDir1, factory, hostPort, 1);
ZooKeeper zk = ClientBase.createZKClient(hostPort, 15000);
- for(int i = 0; i < 50; i++) {
+ for (int i = 0; i < 50; i++) {
zk.create("/" + i, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
}
zk.close();
-
+
ZKDatabase zkDb;
{
ZooKeeperServer zs = factory.getZooKeeperServer();
-
+
zkDb = zs.getZKDatabase();
}
factory.shutdown();
@@ -185,26 +183,17 @@ public class TruncateTest extends ZKTestCase {
int tickTime = 2000;
int initLimit = 3;
int syncLimit = 3;
- int connectToLearnerMasterLimit = 3;
+ int connectToLearnerMasterLimit = 3;
int port1 = PortAssignment.unique();
int port2 = PortAssignment.unique();
int port3 = PortAssignment.unique();
-
+
// Start up two of the quorum and add 10 txns
- Map<Long,QuorumServer> peers = new HashMap<Long,QuorumServer>();
- peers.put(Long.valueOf(1), new QuorumServer(1,
- new InetSocketAddress("127.0.0.1", PortAssignment.unique()),
- new InetSocketAddress("127.0.0.1", PortAssignment.unique()),
- new InetSocketAddress("127.0.0.1", port1)));
- peers.put(Long.valueOf(2), new QuorumServer(2,
- new InetSocketAddress("127.0.0.1", PortAssignment.unique()),
- new InetSocketAddress("127.0.0.1", PortAssignment.unique()),
- new InetSocketAddress("127.0.0.1", port2)));
- peers.put(Long.valueOf(3), new QuorumServer(3,
- new InetSocketAddress("127.0.0.1", PortAssignment.unique()),
- new InetSocketAddress("127.0.0.1", PortAssignment.unique()),
- new InetSocketAddress("127.0.0.1", port3)));
+ Map<Long, QuorumServer> peers = new HashMap<Long, QuorumServer>();
+ peers.put(Long.valueOf(1), new QuorumServer(1, new InetSocketAddress("127.0.0.1", PortAssignment.unique()), new InetSocketAddress("127.0.0.1", PortAssignment.unique()), new InetSocketAddress("127.0.0.1", port1)));
+ peers.put(Long.valueOf(2), new QuorumServer(2, new InetSocketAddress("127.0.0.1", PortAssignment.unique()), new InetSocketAddress("127.0.0.1", PortAssignment.unique()), new InetSocketAddress("127.0.0.1", port2)));
+ peers.put(Long.valueOf(3), new QuorumServer(3, new InetSocketAddress("127.0.0.1", PortAssignment.unique()), new InetSocketAddress("127.0.0.1", PortAssignment.unique()), new InetSocketAddress("127.0.0.1", port3)));
QuorumPeer s2 = new QuorumPeer(peers, dataDir2, dataDir2, port2, 3, 2, tickTime, initLimit, syncLimit, connectToLearnerMasterLimit);
s2.start();
@@ -212,7 +201,7 @@ public class TruncateTest extends ZKTestCase {
s3.start();
zk = ClientBase.createZKClient("127.0.0.1:" + port2, 15000);
- for(int i = 0; i < 10; i++) {
+ for (int i = 0; i < 10; i++) {
zk.create("/" + i, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
}
zk.close();
@@ -220,8 +209,8 @@ public class TruncateTest extends ZKTestCase {
zk2.getData("/9", false, new Stat());
try {
zk2.getData("/10", false, new Stat());
- Assert.fail("Should have gotten an error");
- } catch(KeeperException.NoNodeException e) {
+ fail("Should have gotten an error");
+ } catch (KeeperException.NoNodeException e) {
// this is what we want
}
QuorumPeer s1 = new QuorumPeer(peers, dataDir1, dataDir1, port1, 3, 1, tickTime, initLimit, syncLimit, connectToLearnerMasterLimit);
@@ -236,8 +225,8 @@ public class TruncateTest extends ZKTestCase {
// /11 is the last entry in the log for the xid
// as a result /12 is the first of the truncated znodes to check for
zk1.getData("/12", false, new Stat());
- Assert.fail("Should have gotten an error");
- } catch(KeeperException.NoNodeException e) {
+ fail("Should have gotten an error");
+ } catch (KeeperException.NoNodeException e) {
// this is what we want
}
zk1.close();
@@ -245,4 +234,5 @@ public class TruncateTest extends ZKTestCase {
QuorumBase.shutdown(s2);
QuorumBase.shutdown(s3);
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/WatchEventWhenAutoResetTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/WatchEventWhenAutoResetTest.java
index 33e0f128c..005b525f5 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/WatchEventWhenAutoResetTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/WatchEventWhenAutoResetTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,30 +18,30 @@
package org.apache.zookeeper.test;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.fail;
import java.io.IOException;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
-
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.WatchedEvent;
+import org.apache.zookeeper.Watcher.Event.EventType;
+import org.apache.zookeeper.ZKTestCase;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;
-import org.apache.zookeeper.Watcher.Event.EventType;
import org.apache.zookeeper.data.Stat;
import org.apache.zookeeper.test.ClientBase.CountdownWatcher;
-import org.apache.zookeeper.ZKTestCase;
import org.junit.After;
-import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-
public class WatchEventWhenAutoResetTest extends ZKTestCase {
- protected static final Logger LOG = LoggerFactory
- .getLogger(WatchEventWhenAutoResetTest.class);
+
+ protected static final Logger LOG = LoggerFactory.getLogger(WatchEventWhenAutoResetTest.class);
// waiting time for expected condition
private static final int TIMEOUT = 30000;
@@ -49,7 +49,8 @@ public class WatchEventWhenAutoResetTest extends ZKTestCase {
private EventsWatcher watcher;
private ZooKeeper zk1, zk2;
- static public class EventsWatcher extends CountdownWatcher {
+ public static class EventsWatcher extends CountdownWatcher {
+
private LinkedBlockingQueue<WatchedEvent> dataEvents = new LinkedBlockingQueue<WatchedEvent>();
@Override
@@ -66,18 +67,17 @@ public class WatchEventWhenAutoResetTest extends ZKTestCase {
public void assertEvent(long timeout, EventType eventType) {
try {
- WatchedEvent event = dataEvents.poll(timeout,
- TimeUnit.MILLISECONDS);
- Assert.assertNotNull("do not receive a " + eventType, event);
- Assert.assertEquals(eventType, event.getType());
+ WatchedEvent event = dataEvents.poll(timeout, TimeUnit.MILLISECONDS);
+ assertNotNull("do not receive a " + eventType, event);
+ assertEquals(eventType, event.getType());
} catch (InterruptedException e) {
LOG.warn("ignoring interrupt during EventsWatcher assertEvent");
}
}
+
}
- private ZooKeeper createClient(QuorumUtil qu, int id, EventsWatcher watcher)
- throws IOException {
+ private ZooKeeper createClient(QuorumUtil qu, int id, EventsWatcher watcher) throws IOException {
String hostPort = "127.0.0.1:" + qu.getPeer(id).clientPort;
ZooKeeper zk = new ZooKeeper(hostPort, TIMEOUT, watcher);
try {
@@ -85,7 +85,7 @@ public class WatchEventWhenAutoResetTest extends ZKTestCase {
} catch (InterruptedException e) {
// ignoring the interrupt
} catch (TimeoutException e) {
- Assert.fail("can not connect to " + hostPort);
+ fail("can not connect to " + hostPort);
}
return zk;
}
@@ -128,8 +128,7 @@ public class WatchEventWhenAutoResetTest extends ZKTestCase {
@Test
public void testNodeDataChanged() throws Exception {
String path = "/test-changed";
- zk1.create(path, new byte[1], ZooDefs.Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk1.create(path, new byte[1], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
Stat stat1 = zk1.exists(path, watcher);
qu.shutdown(1);
zk2.setData(path, new byte[2], stat1.getVersion());
@@ -144,8 +143,7 @@ public class WatchEventWhenAutoResetTest extends ZKTestCase {
zk1.exists(path, watcher);
qu.shutdown(1);
- zk2.create(path, new byte[2], ZooDefs.Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk2.create(path, new byte[2], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
qu.start(1);
watcher.waitForConnected(TIMEOUT * 1000L);
watcher.assertEvent(TIMEOUT, EventType.NodeCreated);
@@ -155,8 +153,7 @@ public class WatchEventWhenAutoResetTest extends ZKTestCase {
public void testNodeDeleted() throws Exception {
String path = "/test-deleted";
- zk1.create(path, new byte[1], ZooDefs.Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk1.create(path, new byte[1], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
zk1.getData(path, watcher, null);
qu.shutdown(1);
zk2.delete(path, -1);
@@ -164,8 +161,7 @@ public class WatchEventWhenAutoResetTest extends ZKTestCase {
watcher.waitForConnected(TIMEOUT * 1000L);
watcher.assertEvent(TIMEOUT, EventType.NodeDeleted);
- zk1.create(path, new byte[1], ZooDefs.Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk1.create(path, new byte[1], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
zk1.exists(path, watcher);
qu.shutdown(1);
zk2.delete(path, -1);
@@ -173,8 +169,7 @@ public class WatchEventWhenAutoResetTest extends ZKTestCase {
watcher.waitForConnected(TIMEOUT * 1000L);
watcher.assertEvent(TIMEOUT, EventType.NodeDeleted);
- zk1.create(path, new byte[1], ZooDefs.Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk1.create(path, new byte[1], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
zk1.getChildren(path, watcher);
qu.shutdown(1);
zk2.delete(path, -1);
@@ -187,15 +182,14 @@ public class WatchEventWhenAutoResetTest extends ZKTestCase {
public void testNodeChildrenChanged() throws Exception {
String path = "/test-children-changed";
- zk1.create(path, new byte[1], ZooDefs.Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk1.create(path, new byte[1], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
zk1.getChildren(path, watcher);
qu.shutdown(1);
- zk2.create(path + "/children-1", new byte[2],
- ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
+ zk2.create(path + "/children-1", new byte[2], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
qu.start(1);
watcher.waitForConnected(TIMEOUT * 1000L);
watcher.assertEvent(TIMEOUT, EventType.NodeChildrenChanged);
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/WatchedEventTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/WatchedEventTest.java
index 75ec3dd3e..17d351032 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/WatchedEventTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/WatchedEventTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,14 +18,14 @@
package org.apache.zookeeper.test;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.fail;
import java.util.EnumSet;
-
import org.apache.zookeeper.WatchedEvent;
-import org.apache.zookeeper.ZKTestCase;
import org.apache.zookeeper.Watcher.Event.EventType;
import org.apache.zookeeper.Watcher.Event.KeeperState;
+import org.apache.zookeeper.ZKTestCase;
import org.apache.zookeeper.proto.WatcherEvent;
-import org.junit.Assert;
import org.junit.Test;
public class WatchedEventTest extends ZKTestCase {
@@ -33,19 +33,19 @@ public class WatchedEventTest extends ZKTestCase {
@Test
public void testCreatingWatchedEvent() {
// EventWatch is a simple, immutable type, so all we need to do
- // is make sure we can create all possible combinations of values.
+ // is make sure we can create all possible combinations of values.
EnumSet<EventType> allTypes = EnumSet.allOf(EventType.class);
- EnumSet<KeeperState> allStates = EnumSet.allOf(KeeperState.class);
- WatchedEvent we;
+ EnumSet<KeeperState> allStates = EnumSet.allOf(KeeperState.class);
+ WatchedEvent we;
- for(EventType et : allTypes) {
- for(KeeperState ks : allStates) {
- we = new WatchedEvent(et, ks, "blah");
- Assert.assertEquals(et, we.getType());
- Assert.assertEquals(ks, we.getState());
- Assert.assertEquals("blah", we.getPath());
- }
+ for (EventType et : allTypes) {
+ for (KeeperState ks : allStates) {
+ we = new WatchedEvent(et, ks, "blah");
+ assertEquals(et, we.getType());
+ assertEquals(ks, we.getState());
+ assertEquals("blah", we.getPath());
+ }
}
}
@@ -54,18 +54,18 @@ public class WatchedEventTest extends ZKTestCase {
// Make sure we can handle any type of correct wrapper
EnumSet<EventType> allTypes = EnumSet.allOf(EventType.class);
- EnumSet<KeeperState> allStates = EnumSet.allOf(KeeperState.class);
- WatchedEvent we;
- WatcherEvent wep;
+ EnumSet<KeeperState> allStates = EnumSet.allOf(KeeperState.class);
+ WatchedEvent we;
+ WatcherEvent wep;
- for(EventType et : allTypes) {
- for(KeeperState ks : allStates) {
- wep = new WatcherEvent(et.getIntValue(), ks.getIntValue(), "blah");
- we = new WatchedEvent(wep);
- Assert.assertEquals(et, we.getType());
- Assert.assertEquals(ks, we.getState());
- Assert.assertEquals("blah", we.getPath());
- }
+ for (EventType et : allTypes) {
+ for (KeeperState ks : allStates) {
+ wep = new WatcherEvent(et.getIntValue(), ks.getIntValue(), "blah");
+ we = new WatchedEvent(wep);
+ assertEquals(et, we.getType());
+ assertEquals(ks, we.getState());
+ assertEquals("blah", we.getPath());
+ }
}
}
@@ -73,22 +73,23 @@ public class WatchedEventTest extends ZKTestCase {
public void testCreatingWatchedEventFromInvalidWrapper() {
// Make sure we can't convert from an invalid wrapper
- try {
- WatcherEvent wep = new WatcherEvent(-2342, -252352, "foo");
- new WatchedEvent(wep);
- Assert.fail("Was able to create WatchedEvent from bad wrapper");
- } catch (RuntimeException re) {
- // we're good
- }
+ try {
+ WatcherEvent wep = new WatcherEvent(-2342, -252352, "foo");
+ new WatchedEvent(wep);
+ fail("Was able to create WatchedEvent from bad wrapper");
+ } catch (RuntimeException re) {
+ // we're good
+ }
}
- @Test
- public void testConvertingToEventWrapper() {
- WatchedEvent we = new WatchedEvent(EventType.NodeCreated, KeeperState.Expired, "blah");
- WatcherEvent wew = we.getWrapper();
+ @Test
+ public void testConvertingToEventWrapper() {
+ WatchedEvent we = new WatchedEvent(EventType.NodeCreated, KeeperState.Expired, "blah");
+ WatcherEvent wew = we.getWrapper();
+
+ assertEquals(EventType.NodeCreated.getIntValue(), wew.getType());
+ assertEquals(KeeperState.Expired.getIntValue(), wew.getState());
+ assertEquals("blah", wew.getPath());
+ }
- Assert.assertEquals(EventType.NodeCreated.getIntValue(), wew.getType());
- Assert.assertEquals(KeeperState.Expired.getIntValue(), wew.getState());
- Assert.assertEquals("blah", wew.getPath());
- }
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/WatcherFuncTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/WatcherFuncTest.java
index a6c62e4bb..5a274b53b 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/WatcherFuncTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/WatcherFuncTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,28 +18,32 @@
package org.apache.zookeeper.test;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
-
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
-import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.Watcher.Event.EventType;
import org.apache.zookeeper.Watcher.Event.KeeperState;
import org.apache.zookeeper.ZooDefs.Ids;
-import org.junit.Assert;
+import org.apache.zookeeper.ZooKeeper;
import org.junit.Test;
public class WatcherFuncTest extends ClientBase {
+
private static class SimpleWatcher implements Watcher {
- private LinkedBlockingQueue<WatchedEvent> events =
- new LinkedBlockingQueue<WatchedEvent>();
+
+ private LinkedBlockingQueue<WatchedEvent> events = new LinkedBlockingQueue<WatchedEvent>();
private CountDownLatch latch;
public SimpleWatcher(CountDownLatch latch) {
@@ -59,22 +63,22 @@ public class WatcherFuncTest extends ClientBase {
try {
events.put(event);
} catch (InterruptedException e) {
- Assert.assertTrue("interruption unexpected", false);
+ assertTrue("interruption unexpected", false);
}
}
- public void verify(List<EventType> expected) throws InterruptedException{
+ public void verify(List<EventType> expected) throws InterruptedException {
WatchedEvent event;
int count = 0;
- while (count < expected.size()
- && (event = events.poll(30, TimeUnit.SECONDS)) != null)
- {
- Assert.assertEquals(expected.get(count), event.getType());
+ while (count < expected.size() && (event = events.poll(30, TimeUnit.SECONDS)) != null) {
+ assertEquals(expected.get(count), event.getType());
count++;
}
- Assert.assertEquals(expected.size(), count);
+ assertEquals(expected.size(), count);
events.clear();
}
+
}
+
private SimpleWatcher client_dwatch;
private volatile CountDownLatch client_latch;
private ZooKeeper client;
@@ -106,12 +110,10 @@ public class WatcherFuncTest extends ClientBase {
super.tearDown();
}
- protected ZooKeeper createClient(Watcher watcher, CountDownLatch latch)
- throws IOException, InterruptedException
- {
+ protected ZooKeeper createClient(Watcher watcher, CountDownLatch latch) throws IOException, InterruptedException {
ZooKeeper zk = new ZooKeeper(hostPort, CONNECTION_TIMEOUT, watcher);
- if(!latch.await(CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS)){
- Assert.fail("Unable to connect to server");
+ if (!latch.await(CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS)) {
+ fail("Unable to connect to server");
}
return zk;
}
@@ -122,11 +124,9 @@ public class WatcherFuncTest extends ClientBase {
}
@Test
- public void testExistsSync()
- throws IOException, InterruptedException, KeeperException
- {
- Assert.assertNull(lsnr.exists("/foo", true));
- Assert.assertNull(lsnr.exists("/foo/bar", true));
+ public void testExistsSync() throws IOException, InterruptedException, KeeperException {
+ assertNull(lsnr.exists("/foo", true));
+ assertNull(lsnr.exists("/foo/bar", true));
client.create("/foo", "parent".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
expected.add(EventType.NodeCreated);
@@ -135,25 +135,25 @@ public class WatcherFuncTest extends ClientBase {
verify();
- Assert.assertNotNull(lsnr.exists("/foo", true));
- Assert.assertNotNull(lsnr.exists("/foo/bar", true));
+ assertNotNull(lsnr.exists("/foo", true));
+ assertNotNull(lsnr.exists("/foo/bar", true));
try {
- Assert.assertNull(lsnr.exists("/car", true));
+ assertNull(lsnr.exists("/car", true));
client.setData("/car", "missing".getBytes(), -1);
- Assert.fail();
+ fail();
} catch (KeeperException e) {
- Assert.assertEquals(KeeperException.Code.NONODE, e.code());
- Assert.assertEquals("/car", e.getPath());
+ assertEquals(KeeperException.Code.NONODE, e.code());
+ assertEquals("/car", e.getPath());
}
try {
- Assert.assertNull(lsnr.exists("/foo/car", true));
+ assertNull(lsnr.exists("/foo/car", true));
client.setData("/foo/car", "missing".getBytes(), -1);
- Assert.fail();
+ fail();
} catch (KeeperException e) {
- Assert.assertEquals(KeeperException.Code.NONODE, e.code());
- Assert.assertEquals("/foo/car", e.getPath());
+ assertEquals(KeeperException.Code.NONODE, e.code());
+ assertEquals("/foo/car", e.getPath());
}
client.setData("/foo", "parent".getBytes(), -1);
@@ -163,8 +163,8 @@ public class WatcherFuncTest extends ClientBase {
verify();
- Assert.assertNotNull(lsnr.exists("/foo", true));
- Assert.assertNotNull(lsnr.exists("/foo/bar", true));
+ assertNotNull(lsnr.exists("/foo", true));
+ assertNotNull(lsnr.exists("/foo/bar", true));
client.delete("/foo/bar", -1);
expected.add(EventType.NodeDeleted);
@@ -175,28 +175,26 @@ public class WatcherFuncTest extends ClientBase {
}
@Test
- public void testGetDataSync()
- throws IOException, InterruptedException, KeeperException
- {
+ public void testGetDataSync() throws IOException, InterruptedException, KeeperException {
try {
lsnr.getData("/foo", true, null);
- Assert.fail();
+ fail();
} catch (KeeperException e) {
- Assert.assertEquals(KeeperException.Code.NONODE, e.code());
- Assert.assertEquals("/foo", e.getPath());
+ assertEquals(KeeperException.Code.NONODE, e.code());
+ assertEquals("/foo", e.getPath());
}
try {
lsnr.getData("/foo/bar", true, null);
- Assert.fail();
+ fail();
} catch (KeeperException e) {
- Assert.assertEquals(KeeperException.Code.NONODE, e.code());
- Assert.assertEquals("/foo/bar", e.getPath());
+ assertEquals(KeeperException.Code.NONODE, e.code());
+ assertEquals("/foo/bar", e.getPath());
}
client.create("/foo", "parent".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
- Assert.assertNotNull(lsnr.getData("/foo", true, null));
+ assertNotNull(lsnr.getData("/foo", true, null));
client.create("/foo/bar", "child".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
- Assert.assertNotNull(lsnr.getData("/foo/bar", true, null));
+ assertNotNull(lsnr.getData("/foo/bar", true, null));
client.setData("/foo", "parent".getBytes(), -1);
expected.add(EventType.NodeDataChanged);
@@ -205,8 +203,8 @@ public class WatcherFuncTest extends ClientBase {
verify();
- Assert.assertNotNull(lsnr.getData("/foo", true, null));
- Assert.assertNotNull(lsnr.getData("/foo/bar", true, null));
+ assertNotNull(lsnr.getData("/foo", true, null));
+ assertNotNull(lsnr.getData("/foo/bar", true, null));
client.delete("/foo/bar", -1);
expected.add(EventType.NodeDeleted);
@@ -217,40 +215,36 @@ public class WatcherFuncTest extends ClientBase {
}
@Test
- public void testGetChildrenSync()
- throws IOException, InterruptedException, KeeperException
- {
+ public void testGetChildrenSync() throws IOException, InterruptedException, KeeperException {
try {
lsnr.getChildren("/foo", true);
- Assert.fail();
+ fail();
} catch (KeeperException e) {
- Assert.assertEquals(KeeperException.Code.NONODE, e.code());
- Assert.assertEquals("/foo", e.getPath());
+ assertEquals(KeeperException.Code.NONODE, e.code());
+ assertEquals("/foo", e.getPath());
}
try {
lsnr.getChildren("/foo/bar", true);
- Assert.fail();
+ fail();
} catch (KeeperException e) {
- Assert.assertEquals(KeeperException.Code.NONODE, e.code());
- Assert.assertEquals("/foo/bar", e.getPath());
+ assertEquals(KeeperException.Code.NONODE, e.code());
+ assertEquals("/foo/bar", e.getPath());
}
client.create("/foo", "parent".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
- Assert.assertNotNull(lsnr.getChildren("/foo", true));
+ assertNotNull(lsnr.getChildren("/foo", true));
client.create("/foo/bar", "child".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
expected.add(EventType.NodeChildrenChanged); // /foo
- Assert.assertNotNull(lsnr.getChildren("/foo/bar", true));
-
+ assertNotNull(lsnr.getChildren("/foo/bar", true));
client.setData("/foo", "parent".getBytes(), -1);
client.setData("/foo/bar", "child".getBytes(), -1);
+ assertNotNull(lsnr.exists("/foo", true));
- Assert.assertNotNull(lsnr.exists("/foo", true));
-
- Assert.assertNotNull(lsnr.getChildren("/foo", true));
- Assert.assertNotNull(lsnr.getChildren("/foo/bar", true));
+ assertNotNull(lsnr.getChildren("/foo", true));
+ assertNotNull(lsnr.getChildren("/foo/bar", true));
client.delete("/foo/bar", -1);
expected.add(EventType.NodeDeleted); // /foo/bar childwatch
@@ -262,9 +256,7 @@ public class WatcherFuncTest extends ClientBase {
}
@Test
- public void testExistsSyncWObj()
- throws IOException, InterruptedException, KeeperException
- {
+ public void testExistsSyncWObj() throws IOException, InterruptedException, KeeperException {
SimpleWatcher w1 = new SimpleWatcher(null);
SimpleWatcher w2 = new SimpleWatcher(null);
SimpleWatcher w3 = new SimpleWatcher(null);
@@ -272,13 +264,13 @@ public class WatcherFuncTest extends ClientBase {
List<EventType> e2 = new ArrayList<EventType>();
- Assert.assertNull(lsnr.exists("/foo", true));
- Assert.assertNull(lsnr.exists("/foo", w1));
+ assertNull(lsnr.exists("/foo", true));
+ assertNull(lsnr.exists("/foo", w1));
- Assert.assertNull(lsnr.exists("/foo/bar", w2));
- Assert.assertNull(lsnr.exists("/foo/bar", w3));
- Assert.assertNull(lsnr.exists("/foo/bar", w3));
- Assert.assertNull(lsnr.exists("/foo/bar", w4));
+ assertNull(lsnr.exists("/foo/bar", w2));
+ assertNull(lsnr.exists("/foo/bar", w3));
+ assertNull(lsnr.exists("/foo/bar", w3));
+ assertNull(lsnr.exists("/foo/bar", w4));
client.create("/foo", "parent".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
expected.add(EventType.NodeCreated);
@@ -294,12 +286,12 @@ public class WatcherFuncTest extends ClientBase {
e2.clear();
// default not registered
- Assert.assertNotNull(lsnr.exists("/foo", w1));
+ assertNotNull(lsnr.exists("/foo", w1));
- Assert.assertNotNull(lsnr.exists("/foo/bar", w2));
- Assert.assertNotNull(lsnr.exists("/foo/bar", w3));
- Assert.assertNotNull(lsnr.exists("/foo/bar", w4));
- Assert.assertNotNull(lsnr.exists("/foo/bar", w4));
+ assertNotNull(lsnr.exists("/foo/bar", w2));
+ assertNotNull(lsnr.exists("/foo/bar", w3));
+ assertNotNull(lsnr.exists("/foo/bar", w4));
+ assertNotNull(lsnr.exists("/foo/bar", w4));
client.setData("/foo", "parent".getBytes(), -1);
expected.add(EventType.NodeDataChanged);
@@ -314,14 +306,14 @@ public class WatcherFuncTest extends ClientBase {
expected.clear();
e2.clear();
- Assert.assertNotNull(lsnr.exists("/foo", true));
- Assert.assertNotNull(lsnr.exists("/foo", w1));
- Assert.assertNotNull(lsnr.exists("/foo", w1));
+ assertNotNull(lsnr.exists("/foo", true));
+ assertNotNull(lsnr.exists("/foo", w1));
+ assertNotNull(lsnr.exists("/foo", w1));
- Assert.assertNotNull(lsnr.exists("/foo/bar", w2));
- Assert.assertNotNull(lsnr.exists("/foo/bar", w2));
- Assert.assertNotNull(lsnr.exists("/foo/bar", w3));
- Assert.assertNotNull(lsnr.exists("/foo/bar", w4));
+ assertNotNull(lsnr.exists("/foo/bar", w2));
+ assertNotNull(lsnr.exists("/foo/bar", w2));
+ assertNotNull(lsnr.exists("/foo/bar", w3));
+ assertNotNull(lsnr.exists("/foo/bar", w4));
client.delete("/foo/bar", -1);
expected.add(EventType.NodeDeleted);
@@ -339,9 +331,7 @@ public class WatcherFuncTest extends ClientBase {
}
@Test
- public void testGetDataSyncWObj()
- throws IOException, InterruptedException, KeeperException
- {
+ public void testGetDataSyncWObj() throws IOException, InterruptedException, KeeperException {
SimpleWatcher w1 = new SimpleWatcher(null);
SimpleWatcher w2 = new SimpleWatcher(null);
SimpleWatcher w3 = new SimpleWatcher(null);
@@ -351,27 +341,27 @@ public class WatcherFuncTest extends ClientBase {
try {
lsnr.getData("/foo", w1, null);
- Assert.fail();
+ fail();
} catch (KeeperException e) {
- Assert.assertEquals(KeeperException.Code.NONODE, e.code());
- Assert.assertEquals("/foo", e.getPath());
+ assertEquals(KeeperException.Code.NONODE, e.code());
+ assertEquals("/foo", e.getPath());
}
try {
lsnr.getData("/foo/bar", w2, null);
- Assert.fail();
+ fail();
} catch (KeeperException e) {
- Assert.assertEquals(KeeperException.Code.NONODE, e.code());
- Assert.assertEquals("/foo/bar", e.getPath());
+ assertEquals(KeeperException.Code.NONODE, e.code());
+ assertEquals("/foo/bar", e.getPath());
}
client.create("/foo", "parent".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
- Assert.assertNotNull(lsnr.getData("/foo", true, null));
- Assert.assertNotNull(lsnr.getData("/foo", w1, null));
+ assertNotNull(lsnr.getData("/foo", true, null));
+ assertNotNull(lsnr.getData("/foo", w1, null));
client.create("/foo/bar", "child".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
- Assert.assertNotNull(lsnr.getData("/foo/bar", w2, null));
- Assert.assertNotNull(lsnr.getData("/foo/bar", w3, null));
- Assert.assertNotNull(lsnr.getData("/foo/bar", w4, null));
- Assert.assertNotNull(lsnr.getData("/foo/bar", w4, null));
+ assertNotNull(lsnr.getData("/foo/bar", w2, null));
+ assertNotNull(lsnr.getData("/foo/bar", w3, null));
+ assertNotNull(lsnr.getData("/foo/bar", w4, null));
+ assertNotNull(lsnr.getData("/foo/bar", w4, null));
client.setData("/foo", "parent".getBytes(), -1);
expected.add(EventType.NodeDataChanged);
@@ -386,12 +376,12 @@ public class WatcherFuncTest extends ClientBase {
expected.clear();
e2.clear();
- Assert.assertNotNull(lsnr.getData("/foo", true, null));
- Assert.assertNotNull(lsnr.getData("/foo", w1, null));
- Assert.assertNotNull(lsnr.getData("/foo/bar", w2, null));
- Assert.assertNotNull(lsnr.getData("/foo/bar", w3, null));
- Assert.assertNotNull(lsnr.getData("/foo/bar", w3, null));
- Assert.assertNotNull(lsnr.getData("/foo/bar", w4, null));
+ assertNotNull(lsnr.getData("/foo", true, null));
+ assertNotNull(lsnr.getData("/foo", w1, null));
+ assertNotNull(lsnr.getData("/foo/bar", w2, null));
+ assertNotNull(lsnr.getData("/foo/bar", w3, null));
+ assertNotNull(lsnr.getData("/foo/bar", w3, null));
+ assertNotNull(lsnr.getData("/foo/bar", w4, null));
client.delete("/foo/bar", -1);
expected.add(EventType.NodeDeleted);
@@ -408,9 +398,7 @@ public class WatcherFuncTest extends ClientBase {
}
@Test
- public void testGetChildrenSyncWObj()
- throws IOException, InterruptedException, KeeperException
- {
+ public void testGetChildrenSyncWObj() throws IOException, InterruptedException, KeeperException {
SimpleWatcher w1 = new SimpleWatcher(null);
SimpleWatcher w2 = new SimpleWatcher(null);
SimpleWatcher w3 = new SimpleWatcher(null);
@@ -420,46 +408,44 @@ public class WatcherFuncTest extends ClientBase {
try {
lsnr.getChildren("/foo", true);
- Assert.fail();
+ fail();
} catch (KeeperException e) {
- Assert.assertEquals(KeeperException.Code.NONODE, e.code());
- Assert.assertEquals("/foo", e.getPath());
+ assertEquals(KeeperException.Code.NONODE, e.code());
+ assertEquals("/foo", e.getPath());
}
try {
lsnr.getChildren("/foo/bar", true);
- Assert.fail();
+ fail();
} catch (KeeperException e) {
- Assert.assertEquals(KeeperException.Code.NONODE, e.code());
- Assert.assertEquals("/foo/bar", e.getPath());
+ assertEquals(KeeperException.Code.NONODE, e.code());
+ assertEquals("/foo/bar", e.getPath());
}
client.create("/foo", "parent".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
- Assert.assertNotNull(lsnr.getChildren("/foo", true));
- Assert.assertNotNull(lsnr.getChildren("/foo", w1));
+ assertNotNull(lsnr.getChildren("/foo", true));
+ assertNotNull(lsnr.getChildren("/foo", w1));
client.create("/foo/bar", "child".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
expected.add(EventType.NodeChildrenChanged); // /foo
- Assert.assertNotNull(lsnr.getChildren("/foo/bar", w2));
- Assert.assertNotNull(lsnr.getChildren("/foo/bar", w2));
- Assert.assertNotNull(lsnr.getChildren("/foo/bar", w3));
- Assert.assertNotNull(lsnr.getChildren("/foo/bar", w4));
-
+ assertNotNull(lsnr.getChildren("/foo/bar", w2));
+ assertNotNull(lsnr.getChildren("/foo/bar", w2));
+ assertNotNull(lsnr.getChildren("/foo/bar", w3));
+ assertNotNull(lsnr.getChildren("/foo/bar", w4));
client.setData("/foo", "parent".getBytes(), -1);
client.setData("/foo/bar", "child".getBytes(), -1);
+ assertNotNull(lsnr.exists("/foo", true));
+ assertNotNull(lsnr.exists("/foo", w1));
+ assertNotNull(lsnr.exists("/foo", true));
+ assertNotNull(lsnr.exists("/foo", w1));
- Assert.assertNotNull(lsnr.exists("/foo", true));
- Assert.assertNotNull(lsnr.exists("/foo", w1));
- Assert.assertNotNull(lsnr.exists("/foo", true));
- Assert.assertNotNull(lsnr.exists("/foo", w1));
-
- Assert.assertNotNull(lsnr.getChildren("/foo", true));
- Assert.assertNotNull(lsnr.getChildren("/foo", w1));
- Assert.assertNotNull(lsnr.getChildren("/foo/bar", w2));
- Assert.assertNotNull(lsnr.getChildren("/foo/bar", w3));
- Assert.assertNotNull(lsnr.getChildren("/foo/bar", w4));
- Assert.assertNotNull(lsnr.getChildren("/foo/bar", w4));
+ assertNotNull(lsnr.getChildren("/foo", true));
+ assertNotNull(lsnr.getChildren("/foo", w1));
+ assertNotNull(lsnr.getChildren("/foo/bar", w2));
+ assertNotNull(lsnr.getChildren("/foo/bar", w3));
+ assertNotNull(lsnr.getChildren("/foo/bar", w4));
+ assertNotNull(lsnr.getChildren("/foo/bar", w4));
client.delete("/foo/bar", -1);
e2.add(EventType.NodeDeleted); // /foo/bar childwatch
@@ -475,4 +461,5 @@ public class WatcherFuncTest extends ClientBase {
expected.clear();
e2.clear();
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/WatcherTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/WatcherTest.java
index 3b2906488..b6117911e 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/WatcherTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/WatcherTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,47 +18,52 @@
package org.apache.zookeeper.test;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
import java.io.IOException;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
+import org.apache.zookeeper.AsyncCallback.StatCallback;
+import org.apache.zookeeper.AsyncCallback.VoidCallback;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.TestableZooKeeper;
import org.apache.zookeeper.WatchedEvent;
-import org.apache.zookeeper.ZooKeeper;
-import org.apache.zookeeper.AsyncCallback.StatCallback;
-import org.apache.zookeeper.AsyncCallback.VoidCallback;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.Watcher.Event;
import org.apache.zookeeper.Watcher.Event.EventType;
import org.apache.zookeeper.ZooDefs.Ids;
+import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.client.ZKClientConfig;
import org.apache.zookeeper.data.Stat;
-import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
public class WatcherTest extends ClientBase {
+
protected static final Logger LOG = LoggerFactory.getLogger(WatcherTest.class);
private long timeOfLastWatcherInvocation;
- private final static class MyStatCallback implements StatCallback {
+ private static final class MyStatCallback implements StatCallback {
+
int rc;
public void processResult(int rc, String path, Object ctx, Stat stat) {
- ((int[])ctx)[0]++;
+ ((int[]) ctx)[0]++;
this.rc = rc;
}
+
}
private class MyWatcher extends CountdownWatcher {
- LinkedBlockingQueue<WatchedEvent> events =
- new LinkedBlockingQueue<WatchedEvent>();
+
+ LinkedBlockingQueue<WatchedEvent> events = new LinkedBlockingQueue<WatchedEvent>();
public void process(WatchedEvent event) {
super.process(event);
@@ -71,6 +76,7 @@ public class WatcherTest extends ClientBase {
}
}
}
+
}
@Before
@@ -92,17 +98,14 @@ public class WatcherTest extends ClientBase {
* @throws KeeperException
*/
@Test
- public void testWatcherCorrectness()
- throws IOException, InterruptedException, KeeperException
- {
+ public void testWatcherCorrectness() throws IOException, InterruptedException, KeeperException {
ZooKeeper zk = null;
try {
MyWatcher watcher = new MyWatcher();
zk = createClient(watcher, hostPort);
StatCallback scb = new StatCallback() {
- public void processResult(int rc, String path, Object ctx,
- Stat stat) {
+ public void processResult(int rc, String path, Object ctx, Stat stat) {
// don't do anything
}
};
@@ -112,10 +115,9 @@ public class WatcherTest extends ClientBase {
}
};
- String names[] = new String[10];
+ String[] names = new String[10];
for (int i = 0; i < names.length; i++) {
- String name = zk.create("/tc-", "initialvalue".getBytes(),
- Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL);
+ String name = zk.create("/tc-", "initialvalue".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL);
names[i] = name;
Stat stat = new Stat();
@@ -128,13 +130,13 @@ public class WatcherTest extends ClientBase {
for (int i = 0; i < names.length; i++) {
String name = names[i];
WatchedEvent event = watcher.events.poll(10, TimeUnit.SECONDS);
- Assert.assertEquals(name, event.getPath());
- Assert.assertEquals(Event.EventType.NodeDataChanged, event.getType());
- Assert.assertEquals(Event.KeeperState.SyncConnected, event.getState());
+ assertEquals(name, event.getPath());
+ assertEquals(Event.EventType.NodeDataChanged, event.getType());
+ assertEquals(Event.KeeperState.SyncConnected, event.getState());
event = watcher.events.poll(10, TimeUnit.SECONDS);
- Assert.assertEquals(name, event.getPath());
- Assert.assertEquals(Event.EventType.NodeDeleted, event.getType());
- Assert.assertEquals(Event.KeeperState.SyncConnected, event.getState());
+ assertEquals(name, event.getPath());
+ assertEquals(Event.EventType.NodeDeleted, event.getType());
+ assertEquals(Event.KeeperState.SyncConnected, event.getState());
}
} finally {
if (zk != null) {
@@ -142,18 +144,16 @@ public class WatcherTest extends ClientBase {
}
}
}
-
+
@Test
- public void testWatcherDisconnectOnClose()
- throws IOException, InterruptedException, KeeperException
- {
+ public void testWatcherDisconnectOnClose() throws IOException, InterruptedException, KeeperException {
ZooKeeper zk = null;
try {
final BlockingQueue<WatchedEvent> queue = new LinkedBlockingQueue<>();
-
+
MyWatcher connWatcher = new MyWatcher();
-
- Watcher watcher = new Watcher(){
+
+ Watcher watcher = new Watcher() {
@Override
public void process(WatchedEvent event) {
try {
@@ -162,30 +162,28 @@ public class WatcherTest extends ClientBase {
// Oh well, never mind
}
}
-
+
};
-
+
zk = createClient(connWatcher, hostPort);
-
+
StatCallback scb = new StatCallback() {
- public void processResult(int rc, String path, Object ctx,
- Stat stat) {
+ public void processResult(int rc, String path, Object ctx, Stat stat) {
// don't do anything
}
};
-
+
// Register a watch on the node
zk.exists("/missing", watcher, scb, null);
-
+
// Close the client without changing the node
zk.close();
-
-
+
WatchedEvent event = queue.poll(10, TimeUnit.SECONDS);
-
- Assert.assertNotNull("No watch event was received after closing the Zookeeper client. A 'Closed' event should have occurred", event);
- Assert.assertEquals("Closed events are not generated by the server, and so should have a type of 'None'", Event.EventType.None, event.getType());
- Assert.assertEquals("A 'Closed' event was expected as the Zookeeper client was closed without altering the node it was watching", Event.KeeperState.Closed, event.getState());
+
+ assertNotNull("No watch event was received after closing the Zookeeper client. A 'Closed' event should have occurred", event);
+ assertEquals("Closed events are not generated by the server, and so should have a type of 'None'", Event.EventType.None, event.getType());
+ assertEquals("A 'Closed' event was expected as the Zookeeper client was closed without altering the node it was watching", Event.KeeperState.Closed, event.getState());
} finally {
if (zk != null) {
zk.close();
@@ -195,8 +193,7 @@ public class WatcherTest extends ClientBase {
}
@Test
- public void testWatcherCount()
- throws IOException, InterruptedException, KeeperException {
+ public void testWatcherCount() throws IOException, InterruptedException, KeeperException {
ZooKeeper zk1 = null, zk2 = null;
try {
MyWatcher w1 = new MyWatcher();
@@ -213,21 +210,20 @@ public class WatcherTest extends ClientBase {
zk1.getData("/watch-count-test-2", w1, stat);
zk2.getData("/watch-count-test", w2, stat);
- Assert.assertEquals(serverFactory.getZooKeeperServer()
- .getZKDatabase().getDataTree().getWatchCount(), 3);
+ assertEquals(serverFactory.getZooKeeperServer().getZKDatabase().getDataTree().getWatchCount(), 3);
} finally {
- if(zk1 != null) {
+ if (zk1 != null) {
zk1.close();
}
- if(zk2 != null) {
+ if (zk2 != null) {
zk2.close();
}
}
}
- final static int COUNT = 100;
+ static final int COUNT = 100;
/**
* This test checks that watches for pending requests do not get triggered,
* but watches set by previous requests do.
@@ -236,44 +232,44 @@ public class WatcherTest extends ClientBase {
*/
@Test
public void testWatchAutoResetWithPending() throws Exception {
- MyWatcher watches[] = new MyWatcher[COUNT];
- MyStatCallback cbs[] = new MyStatCallback[COUNT];
- MyWatcher watcher = new MyWatcher();
- int count[] = new int[1];
- TestableZooKeeper zk = createClient(watcher, hostPort, 6000);
- ZooKeeper zk2 = createClient(watcher, hostPort, 5000);
- zk2.create("/test", new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
- for(int i = 0; i < COUNT/2; i++) {
- watches[i] = new MyWatcher();
- cbs[i] = new MyStatCallback();
- zk.exists("/test", watches[i], cbs[i], count);
- }
- zk.exists("/test", false);
- Assert.assertTrue("Failed to pause the connection!", zk.pauseCnxn(3000));
- zk2.close();
- stopServer();
- watches[0].waitForDisconnected(60000);
- for(int i = COUNT/2; i < COUNT; i++) {
- watches[i] = new MyWatcher();
- cbs[i] = new MyStatCallback();
- zk.exists("/test", watches[i], cbs[i], count);
- }
- startServer();
- watches[COUNT/2-1].waitForConnected(60000);
- Assert.assertEquals(null, zk.exists("/test", false));
- waitForAllWatchers();
- for(int i = 0; i < COUNT/2; i++) {
- Assert.assertEquals("For " + i, 1, watches[i].events.size());
- }
- for(int i = COUNT/2; i < COUNT; i++) {
- if (cbs[i].rc == 0) {
- Assert.assertEquals("For " +i, 1, watches[i].events.size());
- } else {
- Assert.assertEquals("For " +i, 0, watches[i].events.size());
- }
- }
- Assert.assertEquals(COUNT, count[0]);
- zk.close();
+ MyWatcher[] watches = new MyWatcher[COUNT];
+ MyStatCallback[] cbs = new MyStatCallback[COUNT];
+ MyWatcher watcher = new MyWatcher();
+ int[] count = new int[1];
+ TestableZooKeeper zk = createClient(watcher, hostPort, 6000);
+ ZooKeeper zk2 = createClient(watcher, hostPort, 5000);
+ zk2.create("/test", new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
+ for (int i = 0; i < COUNT / 2; i++) {
+ watches[i] = new MyWatcher();
+ cbs[i] = new MyStatCallback();
+ zk.exists("/test", watches[i], cbs[i], count);
+ }
+ zk.exists("/test", false);
+ assertTrue("Failed to pause the connection!", zk.pauseCnxn(3000));
+ zk2.close();
+ stopServer();
+ watches[0].waitForDisconnected(60000);
+ for (int i = COUNT / 2; i < COUNT; i++) {
+ watches[i] = new MyWatcher();
+ cbs[i] = new MyStatCallback();
+ zk.exists("/test", watches[i], cbs[i], count);
+ }
+ startServer();
+ watches[COUNT / 2 - 1].waitForConnected(60000);
+ assertEquals(null, zk.exists("/test", false));
+ waitForAllWatchers();
+ for (int i = 0; i < COUNT / 2; i++) {
+ assertEquals("For " + i, 1, watches[i].events.size());
+ }
+ for (int i = COUNT / 2; i < COUNT; i++) {
+ if (cbs[i].rc == 0) {
+ assertEquals("For " + i, 1, watches[i].events.size());
+ } else {
+ assertEquals("For " + i, 0, watches[i].events.size());
+ }
+ }
+ assertEquals(COUNT, count[0]);
+ zk.close();
}
/**
@@ -282,10 +278,10 @@ public class WatcherTest extends ClientBase {
* @throws Exception
*/
private void waitForAllWatchers() throws Exception {
- timeOfLastWatcherInvocation = System.currentTimeMillis();
- while (System.currentTimeMillis() - timeOfLastWatcherInvocation < 1000) {
- Thread.sleep(1000);
- }
+ timeOfLastWatcherInvocation = System.currentTimeMillis();
+ while (System.currentTimeMillis() - timeOfLastWatcherInvocation < 1000) {
+ Thread.sleep(1000);
+ }
}
final int TIMEOUT = 5000;
@@ -323,14 +319,11 @@ public class WatcherTest extends ClientBase {
testWatcherAutoResetWithLocal();
}
- private void testWatcherAutoReset(ZooKeeper zk, MyWatcher globalWatcher,
- MyWatcher localWatcher) throws Exception {
+ private void testWatcherAutoReset(ZooKeeper zk, MyWatcher globalWatcher, MyWatcher localWatcher) throws Exception {
boolean isGlobal = (localWatcher == globalWatcher);
// First test to see if the watch survives across reconnects
- zk.create("/watchtest", new byte[0], Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
- zk.create("/watchtest/child", new byte[0], Ids.OPEN_ACL_UNSAFE,
- CreateMode.EPHEMERAL);
+ zk.create("/watchtest", new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
+ zk.create("/watchtest/child", new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
if (isGlobal) {
zk.getChildren("/watchtest", true);
zk.getData("/watchtest/child", true, new Stat());
@@ -341,7 +334,7 @@ public class WatcherTest extends ClientBase {
zk.exists("/watchtest/child2", localWatcher);
}
- Assert.assertTrue(localWatcher.events.isEmpty());
+ assertTrue(localWatcher.events.isEmpty());
stopServer();
globalWatcher.waitForDisconnected(3000);
@@ -353,16 +346,15 @@ public class WatcherTest extends ClientBase {
localWatcher.waitForConnected(500);
}
- Assert.assertTrue(localWatcher.events.isEmpty());
+ assertTrue(localWatcher.events.isEmpty());
zk.setData("/watchtest/child", new byte[1], -1);
- zk.create("/watchtest/child2", new byte[0], Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk.create("/watchtest/child2", new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
WatchedEvent e;
if (!disableAutoWatchReset) {
e = localWatcher.events.poll(TIMEOUT, TimeUnit.MILLISECONDS);
- Assert.assertEquals(e.getPath(), EventType.NodeDataChanged, e.getType());
- Assert.assertEquals("/watchtest/child", e.getPath());
+ assertEquals(e.getPath(), EventType.NodeDataChanged, e.getType());
+ assertEquals("/watchtest/child", e.getPath());
} else {
// we'll catch this later if it does happen after timeout, so
// why waste the time on poll
@@ -372,8 +364,8 @@ public class WatcherTest extends ClientBase {
e = localWatcher.events.poll(TIMEOUT, TimeUnit.MILLISECONDS);
// The create will trigger the get children and the exist
// watches
- Assert.assertEquals(EventType.NodeCreated, e.getType());
- Assert.assertEquals("/watchtest/child2", e.getPath());
+ assertEquals(EventType.NodeCreated, e.getType());
+ assertEquals("/watchtest/child2", e.getPath());
} else {
// we'll catch this later if it does happen after timeout, so
// why waste the time on poll
@@ -381,25 +373,25 @@ public class WatcherTest extends ClientBase {
if (!disableAutoWatchReset) {
e = localWatcher.events.poll(TIMEOUT, TimeUnit.MILLISECONDS);
- Assert.assertEquals(EventType.NodeChildrenChanged, e.getType());
- Assert.assertEquals("/watchtest", e.getPath());
+ assertEquals(EventType.NodeChildrenChanged, e.getType());
+ assertEquals("/watchtest", e.getPath());
} else {
// we'll catch this later if it does happen after timeout, so
// why waste the time on poll
}
- Assert.assertTrue(localWatcher.events.isEmpty()); // ensure no late arrivals
+ assertTrue(localWatcher.events.isEmpty()); // ensure no late arrivals
stopServer();
globalWatcher.waitForDisconnected(TIMEOUT);
try {
try {
localWatcher.waitForDisconnected(500);
if (!isGlobal && !disableAutoWatchReset) {
- Assert.fail("Got an event when I shouldn't have");
+ fail("Got an event when I shouldn't have");
}
- } catch(TimeoutException toe) {
+ } catch (TimeoutException toe) {
if (disableAutoWatchReset) {
- Assert.fail("Didn't get an event when I should have");
+ fail("Didn't get an event when I should have");
}
// Else what we are expecting since there are no outstanding watches
}
@@ -425,14 +417,14 @@ public class WatcherTest extends ClientBase {
zk.delete("/watchtest/child2", -1);
e = localWatcher.events.poll(TIMEOUT, TimeUnit.MILLISECONDS);
- Assert.assertEquals(EventType.NodeDeleted, e.getType());
- Assert.assertEquals("/watchtest/child2", e.getPath());
+ assertEquals(EventType.NodeDeleted, e.getType());
+ assertEquals("/watchtest/child2", e.getPath());
e = localWatcher.events.poll(TIMEOUT, TimeUnit.MILLISECONDS);
- Assert.assertEquals(EventType.NodeChildrenChanged, e.getType());
- Assert.assertEquals("/watchtest", e.getPath());
+ assertEquals(EventType.NodeChildrenChanged, e.getType());
+ assertEquals("/watchtest", e.getPath());
- Assert.assertTrue(localWatcher.events.isEmpty());
+ assertTrue(localWatcher.events.isEmpty());
stopServer();
globalWatcher.waitForDisconnected(TIMEOUT);
@@ -448,8 +440,8 @@ public class WatcherTest extends ClientBase {
if (!disableAutoWatchReset) {
e = localWatcher.events.poll(TIMEOUT, TimeUnit.MILLISECONDS);
- Assert.assertEquals(EventType.NodeDeleted, e.getType());
- Assert.assertEquals("/watchtest/child", e.getPath());
+ assertEquals(EventType.NodeDeleted, e.getType());
+ assertEquals("/watchtest/child", e.getPath());
} else {
// we'll catch this later if it does happen after timeout, so
// why waste the time on poll
@@ -457,7 +449,7 @@ public class WatcherTest extends ClientBase {
// Make sure nothing is straggling!
Thread.sleep(1000);
- Assert.assertTrue(localWatcher.events.isEmpty());
+ assertTrue(localWatcher.events.isEmpty());
}
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/X509AuthTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/X509AuthTest.java
index 2574dd675..62dabccf0 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/X509AuthTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/X509AuthTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -15,8 +15,10 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
package org.apache.zookeeper.test;
+import static org.junit.Assert.assertEquals;
import java.math.BigInteger;
import java.net.Socket;
import java.security.InvalidKeyException;
@@ -34,33 +36,27 @@ import java.security.cert.X509Certificate;
import java.util.Arrays;
import java.util.Date;
import java.util.Set;
-
import javax.net.ssl.X509KeyManager;
import javax.net.ssl.X509TrustManager;
import javax.security.auth.x500.X500Principal;
-
-
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZKTestCase;
import org.apache.zookeeper.server.MockServerCnxn;
import org.apache.zookeeper.server.auth.X509AuthenticationProvider;
-import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
public class X509AuthTest extends ZKTestCase {
+
private static TestCertificate clientCert;
private static TestCertificate superCert;
private static TestCertificate unknownCert;
@Before
public void setUp() {
- System.setProperty("zookeeper.X509AuthenticationProvider.superUser",
- "CN=SUPER");
- System.setProperty("zookeeper.ssl.keyManager",
- "org.apache.zookeeper.test.X509AuthTest.TestKeyManager");
- System.setProperty("zookeeper.ssl.trustManager",
- "org.apache.zookeeper.test.X509AuthTest.TestTrustManager");
+ System.setProperty("zookeeper.X509AuthenticationProvider.superUser", "CN=SUPER");
+ System.setProperty("zookeeper.ssl.keyManager", "org.apache.zookeeper.test.X509AuthTest.TestKeyManager");
+ System.setProperty("zookeeper.ssl.trustManager", "org.apache.zookeeper.test.X509AuthTest.TestTrustManager");
clientCert = new TestCertificate("CLIENT");
superCert = new TestCertificate("SUPER");
@@ -71,28 +67,29 @@ public class X509AuthTest extends ZKTestCase {
public void testTrustedAuth() {
X509AuthenticationProvider provider = createProvider(clientCert);
MockServerCnxn cnxn = new MockServerCnxn();
- cnxn.clientChain = new X509Certificate[] { clientCert };
- Assert.assertEquals(KeeperException.Code.OK, provider.handleAuthentication(cnxn, null));
+ cnxn.clientChain = new X509Certificate[]{clientCert};
+ assertEquals(KeeperException.Code.OK, provider.handleAuthentication(cnxn, null));
}
@Test
public void testSuperAuth() {
X509AuthenticationProvider provider = createProvider(superCert);
MockServerCnxn cnxn = new MockServerCnxn();
- cnxn.clientChain = new X509Certificate[] { superCert };
- Assert.assertEquals(KeeperException.Code.OK, provider.handleAuthentication(cnxn, null));
- Assert.assertEquals("super", cnxn.getAuthInfo().get(0).getScheme());
+ cnxn.clientChain = new X509Certificate[]{superCert};
+ assertEquals(KeeperException.Code.OK, provider.handleAuthentication(cnxn, null));
+ assertEquals("super", cnxn.getAuthInfo().get(0).getScheme());
}
@Test
public void testUntrustedAuth() {
X509AuthenticationProvider provider = createProvider(clientCert);
MockServerCnxn cnxn = new MockServerCnxn();
- cnxn.clientChain = new X509Certificate[] { unknownCert };
- Assert.assertEquals(KeeperException.Code.AUTHFAILED, provider.handleAuthentication(cnxn, null));
+ cnxn.clientChain = new X509Certificate[]{unknownCert};
+ assertEquals(KeeperException.Code.AUTHFAILED, provider.handleAuthentication(cnxn, null));
}
private static class TestPublicKey implements PublicKey {
+
private static final long serialVersionUID = 1L;
@Override
public String getAlgorithm() {
@@ -106,8 +103,11 @@ public class X509AuthTest extends ZKTestCase {
public byte[] getEncoded() {
return null;
}
+
}
+
private static class TestCertificate extends X509Certificate {
+
private byte[] encoded;
private X500Principal principal;
private PublicKey publicKey;
@@ -133,13 +133,10 @@ public class X509AuthTest extends ZKTestCase {
return null;
}
@Override
- public void checkValidity() throws CertificateExpiredException,
- CertificateNotYetValidException {
+ public void checkValidity() throws CertificateExpiredException, CertificateNotYetValidException {
}
@Override
- public void checkValidity(Date date)
- throws CertificateExpiredException,
- CertificateNotYetValidException {
+ public void checkValidity(Date date) throws CertificateExpiredException, CertificateNotYetValidException {
}
@Override
public int getVersion() {
@@ -206,15 +203,10 @@ public class X509AuthTest extends ZKTestCase {
return encoded;
}
@Override
- public void verify(PublicKey key) throws CertificateException,
- NoSuchAlgorithmException, InvalidKeyException,
- NoSuchProviderException, SignatureException {
+ public void verify(PublicKey key) throws CertificateException, NoSuchAlgorithmException, InvalidKeyException, NoSuchProviderException, SignatureException {
}
@Override
- public void verify(PublicKey key, String sigProvider)
- throws CertificateException, NoSuchAlgorithmException,
- InvalidKeyException, NoSuchProviderException,
- SignatureException {
+ public void verify(PublicKey key, String sigProvider) throws CertificateException, NoSuchAlgorithmException, InvalidKeyException, NoSuchProviderException, SignatureException {
}
@Override
public String toString() {
@@ -228,16 +220,17 @@ public class X509AuthTest extends ZKTestCase {
public X500Principal getSubjectX500Principal() {
return principal;
}
+
}
+
public static class TestKeyManager implements X509KeyManager {
+
@Override
- public String chooseClientAlias(String[] keyType, Principal[] issuers,
- Socket socket) {
+ public String chooseClientAlias(String[] keyType, Principal[] issuers, Socket socket) {
return null;
}
@Override
- public String chooseServerAlias(String keyType, Principal[] issuers,
- Socket socket) {
+ public String chooseServerAlias(String keyType, Principal[] issuers, Socket socket) {
return null;
}
@Override
@@ -256,22 +249,23 @@ public class X509AuthTest extends ZKTestCase {
public String[] getServerAliases(String keyType, Principal[] issuers) {
return null;
}
+
}
+
public static class TestTrustManager implements X509TrustManager {
+
X509Certificate cert;
public TestTrustManager(X509Certificate testCert) {
cert = testCert;
}
@Override
- public void checkClientTrusted(X509Certificate[] chain, String authType)
- throws CertificateException {
+ public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
if (!Arrays.equals(cert.getEncoded(), chain[0].getEncoded())) {
throw new CertificateException("Client cert not trusted");
}
}
@Override
- public void checkServerTrusted(X509Certificate[] chain, String authType)
- throws CertificateException {
+ public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
if (!Arrays.equals(cert.getEncoded(), chain[0].getEncoded())) {
throw new CertificateException("Server cert not trusted");
}
@@ -280,11 +274,11 @@ public class X509AuthTest extends ZKTestCase {
public X509Certificate[] getAcceptedIssuers() {
return null;
}
+
}
protected X509AuthenticationProvider createProvider(X509Certificate trustedCert) {
- return new X509AuthenticationProvider(
- new TestTrustManager(trustedCert),
- new TestKeyManager());
+ return new X509AuthenticationProvider(new TestTrustManager(trustedCert), new TestKeyManager());
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/ZkDatabaseCorruptionTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/ZkDatabaseCorruptionTest.java
index c757fc3ea..9f0ac7ebd 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/ZkDatabaseCorruptionTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/ZkDatabaseCorruptionTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,11 +18,13 @@
package org.apache.zookeeper.test;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Arrays;
-
import org.apache.zookeeper.AsyncCallback;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.ZKTestCase;
@@ -34,15 +36,13 @@ import org.apache.zookeeper.server.persistence.FileTxnSnapLog;
import org.apache.zookeeper.server.quorum.QuorumPeer;
import org.apache.zookeeper.server.quorum.QuorumPeer.ServerState;
import org.junit.After;
-import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import static org.junit.Assert.assertEquals;
-
public class ZkDatabaseCorruptionTest extends ZKTestCase {
+
protected static final Logger LOG = LoggerFactory.getLogger(ZkDatabaseCorruptionTest.class);
public static final long CONNECTION_TIMEOUT = ClientTest.CONNECTION_TIMEOUT;
@@ -67,7 +67,7 @@ public class ZkDatabaseCorruptionTest extends ZKTestCase {
private void corruptAllSnapshots(File snapDir) throws IOException {
File[] listFiles = snapDir.listFiles();
- for (File f: listFiles) {
+ for (File f : listFiles) {
if (f.getName().startsWith("snapshot")) {
corruptFile(f);
}
@@ -75,10 +75,11 @@ public class ZkDatabaseCorruptionTest extends ZKTestCase {
}
private class NoopStringCallback implements AsyncCallback.StringCallback {
+
@Override
- public void processResult(int rc, String path, Object ctx,
- String name) {
+ public void processResult(int rc, String path, Object ctx, String name) {
}
+
}
@Test
@@ -88,8 +89,8 @@ public class ZkDatabaseCorruptionTest extends ZKTestCase {
ZooKeeper zk = ClientBase.createZKClient(qb.hostPort, 10000);
SyncRequestProcessor.setSnapCount(100);
for (int i = 0; i < 2000; i++) {
- zk.create("/0-" + i, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT, new NoopStringCallback(), null);
+ zk.create("/0-"
+ + i, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT, new NoopStringCallback(), null);
}
zk.close();
@@ -104,37 +105,55 @@ public class ZkDatabaseCorruptionTest extends ZKTestCase {
++leaderSid;
}
- Assert.assertNotNull("Cannot find the leader.", leader);
+ assertNotNull("Cannot find the leader.", leader);
leader.shutdown();
// now corrupt the leader's database
FileTxnSnapLog snapLog = leader.getTxnFactory();
- File snapDir= snapLog.getSnapDir();
+ File snapDir = snapLog.getSnapDir();
//corrupt all the snapshot in the snapshot directory
corruptAllSnapshots(snapDir);
qb.shutdownServers();
qb.setupServers();
- if (leaderSid != 1)qb.s1.start(); else leader = qb.s1;
- if (leaderSid != 2)qb.s2.start(); else leader = qb.s2;
- if (leaderSid != 3)qb.s3.start(); else leader = qb.s3;
- if (leaderSid != 4)qb.s4.start(); else leader = qb.s4;
- if (leaderSid != 5)qb.s5.start(); else leader = qb.s5;
+ if (leaderSid != 1) {
+ qb.s1.start();
+ } else {
+ leader = qb.s1;
+ }
+ if (leaderSid != 2) {
+ qb.s2.start();
+ } else {
+ leader = qb.s2;
+ }
+ if (leaderSid != 3) {
+ qb.s3.start();
+ } else {
+ leader = qb.s3;
+ }
+ if (leaderSid != 4) {
+ qb.s4.start();
+ } else {
+ leader = qb.s4;
+ }
+ if (leaderSid != 5) {
+ qb.s5.start();
+ } else {
+ leader = qb.s5;
+ }
try {
leader.start();
- Assert.assertTrue(false);
- } catch(RuntimeException re) {
+ assertTrue(false);
+ } catch (RuntimeException re) {
LOG.info("Got an error: expected", re);
}
//wait for servers to be up
String[] list = qb.hostPort.split(",");
for (int i = 0; i < 5; i++) {
- if(leaderSid != (i + 1)) {
+ if (leaderSid != (i + 1)) {
String hp = list[i];
- Assert.assertTrue("waiting for server up",
- ClientBase.waitForServerUp(hp,
- CONNECTION_TIMEOUT));
+ assertTrue("waiting for server up", ClientBase.waitForServerUp(hp, CONNECTION_TIMEOUT));
LOG.info("{} is accepting client connections", hp);
} else {
LOG.info("Skipping the leader");
@@ -144,21 +163,31 @@ public class ZkDatabaseCorruptionTest extends ZKTestCase {
zk = qb.createClient();
SyncRequestProcessor.setSnapCount(100);
for (int i = 2000; i < 4000; i++) {
- zk.create("/0-" + i, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT, new NoopStringCallback(), null);
+ zk.create("/0-"
+ + i, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT, new NoopStringCallback(), null);
}
zk.close();
- if (leaderSid != 1)QuorumBase.shutdown(qb.s1);
- if (leaderSid != 2)QuorumBase.shutdown(qb.s2);
- if (leaderSid != 3)QuorumBase.shutdown(qb.s3);
- if (leaderSid != 4)QuorumBase.shutdown(qb.s4);
- if (leaderSid != 5)QuorumBase.shutdown(qb.s5);
+ if (leaderSid != 1) {
+ QuorumBase.shutdown(qb.s1);
+ }
+ if (leaderSid != 2) {
+ QuorumBase.shutdown(qb.s2);
+ }
+ if (leaderSid != 3) {
+ QuorumBase.shutdown(qb.s3);
+ }
+ if (leaderSid != 4) {
+ QuorumBase.shutdown(qb.s4);
+ }
+ if (leaderSid != 5) {
+ QuorumBase.shutdown(qb.s5);
+ }
}
@Test
public void testAbsentRecentSnapshot() throws IOException {
- ZKDatabase zkDatabase = new ZKDatabase(new FileTxnSnapLog(new File("foo"), new File("bar")){
+ ZKDatabase zkDatabase = new ZKDatabase(new FileTxnSnapLog(new File("foo"), new File("bar")) {
@Override
public File findMostRecentSnapshot() throws IOException {
return null;
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/ZooKeeperQuotaTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/ZooKeeperQuotaTest.java
index 8c18d78aa..2eb2c6caa 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/ZooKeeperQuotaTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/ZooKeeperQuotaTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,55 +18,51 @@
package org.apache.zookeeper.test;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
import java.io.IOException;
-
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.Quotas;
import org.apache.zookeeper.StatsTrack;
-import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.ZooDefs.Ids;
+import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.cli.MalformedPathException;
import org.apache.zookeeper.cli.SetQuotaCommand;
import org.apache.zookeeper.data.Stat;
import org.apache.zookeeper.server.ZooKeeperServer;
-import org.junit.Assert;
import org.junit.Test;
public class ZooKeeperQuotaTest extends ClientBase {
@Test
- public void testQuota() throws IOException,
- InterruptedException, KeeperException, Exception {
+ public void testQuota() throws Exception {
final ZooKeeper zk = createClient();
final String path = "/a/b/v";
// making sure setdata works on /
zk.setData("/", "some".getBytes(), -1);
- zk.create("/a", "some".getBytes(), Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk.create("/a", "some".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
- zk.create("/a/b", "some".getBytes(), Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk.create("/a/b", "some".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
- zk.create("/a/b/v", "some".getBytes(), Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk.create("/a/b/v", "some".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
- zk.create("/a/b/v/d", "some".getBytes(), Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk.create("/a/b/v/d", "some".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
SetQuotaCommand.createQuota(zk, path, 5L, 10);
// see if its set
String absolutePath = Quotas.quotaZookeeper + path + "/" + Quotas.limitNode;
byte[] data = zk.getData(absolutePath, false, new Stat());
StatsTrack st = new StatsTrack(new String(data));
- Assert.assertTrue("bytes are set", st.getBytes() == 5L);
- Assert.assertTrue("num count is set", st.getCount() == 10);
+ assertTrue("bytes are set", st.getBytes() == 5L);
+ assertTrue("num count is set", st.getCount() == 10);
String statPath = Quotas.quotaZookeeper + path + "/" + Quotas.statNode;
byte[] qdata = zk.getData(statPath, false, new Stat());
StatsTrack qst = new StatsTrack(new String(qdata));
- Assert.assertTrue("bytes are set", qst.getBytes() == 8L);
- Assert.assertTrue("count is set", qst.getCount() == 2);
+ assertTrue("bytes are set", qst.getBytes() == 8L);
+ assertTrue("count is set", qst.getCount() == 2);
//force server to restart and load from snapshot, not txn log
stopServer();
@@ -74,19 +70,17 @@ public class ZooKeeperQuotaTest extends ClientBase {
stopServer();
startServer();
ZooKeeperServer server = serverFactory.getZooKeeperServer();
- Assert.assertNotNull("Quota is still set",
- server.getZKDatabase().getDataTree().getMaxPrefixWithQuota(path) != null);
+ assertNotNull("Quota is still set", server.getZKDatabase().getDataTree().getMaxPrefixWithQuota(path)
+ != null);
}
@Test
- public void testSetQuota() throws IOException,
- InterruptedException, KeeperException, MalformedPathException {
+ public void testSetQuota() throws IOException, InterruptedException, KeeperException, MalformedPathException {
final ZooKeeper zk = createClient();
String path = "/c1";
String nodeData = "foo";
- zk.create(path, nodeData.getBytes(), Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk.create(path, nodeData.getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
int count = 10;
long bytes = 5L;
@@ -96,44 +90,37 @@ public class ZooKeeperQuotaTest extends ClientBase {
String absoluteLimitPath = Quotas.quotaZookeeper + path + "/" + Quotas.limitNode;
byte[] data = zk.getData(absoluteLimitPath, false, null);
StatsTrack st = new StatsTrack(new String(data));
- Assert.assertEquals(bytes, st.getBytes());
- Assert.assertEquals(count, st.getCount());
+ assertEquals(bytes, st.getBytes());
+ assertEquals(count, st.getCount());
//check the stats
String absoluteStatPath = Quotas.quotaZookeeper + path + "/" + Quotas.statNode;
data = zk.getData(absoluteStatPath, false, null);
st = new StatsTrack(new String(data));
- Assert.assertEquals(nodeData.length(), st.getBytes());
- Assert.assertEquals(1, st.getCount());
+ assertEquals(nodeData.length(), st.getBytes());
+ assertEquals(1, st.getCount());
//create another node
String path2 = "/c1/c2";
String nodeData2 = "bar";
- zk.create(path2, nodeData2.getBytes(), Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk.create(path2, nodeData2.getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
absoluteStatPath = Quotas.quotaZookeeper + path + "/" + Quotas.statNode;
data = zk.getData(absoluteStatPath, false, null);
st = new StatsTrack(new String(data));
//check the stats
- Assert.assertEquals(nodeData.length() + nodeData2.length(), st.getBytes());
- Assert.assertEquals(2, st.getCount());
+ assertEquals(nodeData.length() + nodeData2.length(), st.getBytes());
+ assertEquals(2, st.getCount());
}
@Test
- public void testSetQuotaWhenSetQuotaOnParentOrChildPath() throws IOException,
- InterruptedException, KeeperException, MalformedPathException {
+ public void testSetQuotaWhenSetQuotaOnParentOrChildPath() throws IOException, InterruptedException, KeeperException, MalformedPathException {
final ZooKeeper zk = createClient();
- zk.create("/c1", "some".getBytes(), Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
- zk.create("/c1/c2", "some".getBytes(), Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
- zk.create("/c1/c2/c3", "some".getBytes(), Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
- zk.create("/c1/c2/c3/c4", "some".getBytes(), Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
- zk.create("/c1/c2/c3/c4/c5", "some".getBytes(), Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
+ zk.create("/c1", "some".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
+ zk.create("/c1/c2", "some".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
+ zk.create("/c1/c2/c3", "some".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
+ zk.create("/c1/c2/c3/c4", "some".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
+ zk.create("/c1/c2/c3/c4/c5", "some".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
//set the quota on the path:/c1/c2/c3
SetQuotaCommand.createQuota(zk, "/c1/c2/c3", 5L, 10);
@@ -141,13 +128,14 @@ public class ZooKeeperQuotaTest extends ClientBase {
try {
SetQuotaCommand.createQuota(zk, "/c1", 5L, 10);
} catch (IllegalArgumentException e) {
- Assert.assertEquals("/c1 has a child /c1/c2/c3 which has a quota", e.getMessage());
+ assertEquals("/c1 has a child /c1/c2/c3 which has a quota", e.getMessage());
}
try {
SetQuotaCommand.createQuota(zk, "/c1/c2/c3/c4/c5", 5L, 10);
} catch (IllegalArgumentException e) {
- Assert.assertEquals("/c1/c2/c3/c4/c5 has a parent /c1/c2/c3 which has a quota", e.getMessage());
+ assertEquals("/c1/c2/c3/c4/c5 has a parent /c1/c2/c3 which has a quota", e.getMessage());
}
}
+
}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/ZooKeeperTestClient.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/ZooKeeperTestClient.java
index a0cba912c..42f0ebee7 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/ZooKeeperTestClient.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/ZooKeeperTestClient.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,450 +18,437 @@
package org.apache.zookeeper.test;
-import java.io.File;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
-
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
+import org.apache.zookeeper.KeeperException.Code;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
-import org.apache.zookeeper.ZKTestCase;
-import org.apache.zookeeper.ZooKeeper;
-import org.apache.zookeeper.KeeperException.Code;
import org.apache.zookeeper.Watcher.Event.EventType;
+import org.apache.zookeeper.ZKTestCase;
import org.apache.zookeeper.ZooDefs.Ids;
+import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.common.Time;
import org.apache.zookeeper.data.Stat;
-import org.apache.zookeeper.server.ServerCnxnFactory;
-import org.apache.zookeeper.server.ZooKeeperServer;
-import org.junit.Assert;
public class ZooKeeperTestClient extends ZKTestCase implements Watcher {
- protected String hostPort = "127.0.0.1:22801";
- protected static final String dirOnZK = "/test_dir";
+ protected String hostPort = "127.0.0.1:22801";
+
+ protected static final String dirOnZK = "/test_dir";
+
+ protected String testDirOnZK = dirOnZK + "/" + Time.currentElapsedTime();
- protected String testDirOnZK = dirOnZK + "/" + Time.currentElapsedTime();
+ LinkedBlockingQueue<WatchedEvent> events = new LinkedBlockingQueue<WatchedEvent>();
- LinkedBlockingQueue<WatchedEvent> events = new LinkedBlockingQueue<WatchedEvent>();
+ private WatchedEvent getEvent(int numTries) throws InterruptedException {
+ WatchedEvent event = null;
+ for (int i = 0; i < numTries; i++) {
+ System.out.println("i = " + i);
+ event = events.poll(10, TimeUnit.SECONDS);
+ if (event != null) {
+ break;
+ }
+ Thread.sleep(5000);
+ }
+ return event;
- private WatchedEvent getEvent(int numTries) throws InterruptedException {
- WatchedEvent event = null;
- for (int i = 0; i < numTries; i++) {
- System.out.println("i = " + i);
- event = events.poll(10, TimeUnit.SECONDS);
- if (event != null) {
- break;
- }
- Thread.sleep(5000);
}
- return event;
- }
+ private void deleteZKDir(ZooKeeper zk, String nodeName) throws IOException, InterruptedException, KeeperException {
- private void deleteZKDir(ZooKeeper zk, String nodeName)
- throws IOException, InterruptedException, KeeperException {
+ Stat stat = zk.exists(nodeName, false);
+ if (stat == null) {
+ return;
+ }
- Stat stat = zk.exists(nodeName, false);
- if (stat == null) {
- return;
- }
+ List<String> children1 = zk.getChildren(nodeName, false);
+ List<String> c2 = zk.getChildren(nodeName, false, stat);
- List<String> children1 = zk.getChildren(nodeName, false);
- List<String> c2 = zk.getChildren(nodeName, false, stat);
+ if (!children1.equals(c2)) {
+ fail("children lists from getChildren()/getChildren2() do not match");
+ }
- if (!children1.equals(c2)) {
- Assert.fail("children lists from getChildren()/getChildren2() do not match");
- }
+ if (!stat.equals(stat)) {
+ fail("stats from exists()/getChildren2() do not match");
+ }
- if (!stat.equals(stat)) {
- Assert.fail("stats from exists()/getChildren2() do not match");
+ if (children1.size() == 0) {
+ zk.delete(nodeName, -1);
+ return;
+ }
+ for (String n : children1) {
+ deleteZKDir(zk, n);
+ }
}
- if (children1.size() == 0) {
- zk.delete(nodeName, -1);
- return;
- }
- for (String n : children1) {
- deleteZKDir(zk, n);
- }
- }
-
- private void checkRoot() throws IOException,
- InterruptedException {
- ZooKeeper zk = new ZooKeeper(hostPort, 10000, this);
-
- try {
- zk.create(dirOnZK, null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
- } catch (KeeperException.NodeExistsException ke) {
- // expected, sort of
- } catch (KeeperException ke) {
- Assert.fail("Unexpected exception code for create " + dirOnZK + ": "
- + ke.getMessage());
- }
+ private void checkRoot() throws IOException, InterruptedException {
+ ZooKeeper zk = new ZooKeeper(hostPort, 10000, this);
- try {
- zk.create(testDirOnZK, null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
- } catch (KeeperException.NodeExistsException ke) {
- // expected, sort of
- } catch (KeeperException ke) {
- Assert.fail("Unexpected exception code for create " + testDirOnZK + ": "
- + ke.getMessage());
- }
+ try {
+ zk.create(dirOnZK, null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
+ } catch (KeeperException.NodeExistsException ke) {
+ // expected, sort of
+ } catch (KeeperException ke) {
+ fail("Unexpected exception code for create " + dirOnZK + ": " + ke.getMessage());
+ }
- zk.close();
- }
-
- private void enode_test_1() throws IOException,
- InterruptedException, KeeperException {
- checkRoot();
- String parentName = testDirOnZK;
- String nodeName = parentName + "/enode_abc";
- ZooKeeper zk = new ZooKeeper(hostPort, 10000, this);
-
- Stat stat = zk.exists(parentName, false);
- if (stat == null) {
- try {
- zk.create(parentName, null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
- } catch (KeeperException ke) {
- Assert.fail("Creating node " + parentName + ke.getMessage());
- }
- }
+ try {
+ zk.create(testDirOnZK, null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
+ } catch (KeeperException.NodeExistsException ke) {
+ // expected, sort of
+ } catch (KeeperException ke) {
+ fail("Unexpected exception code for create " + testDirOnZK + ": " + ke.getMessage());
+ }
- try {
- zk.create(nodeName, null, Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
- } catch (KeeperException ke) {
- Code code = ke.code();
- boolean valid = code == KeeperException.Code.NODEEXISTS;
- if (!valid) {
- Assert.fail("Unexpected exception code for createin: " + ke.getMessage());
- }
+ zk.close();
}
- stat = zk.exists(nodeName, false);
- if (stat == null) {
- Assert.fail("node " + nodeName + " should exist");
- }
- System.out.println("Closing client with sessionid: 0x"
- + Long.toHexString(zk.getSessionId()));
- zk.close();
- zk = new ZooKeeper(hostPort, 10000, this);
-
- for (int i = 0; i < 10; i++) {
- System.out.println("i = " + i);
- stat = zk.exists(nodeName, false);
- if (stat != null) {
- System.out.println("node " + nodeName
- + " should not exist after reconnection close");
- } else {
- System.out.println("node " + nodeName
- + " is gone after reconnection close!");
- break;
- }
- Thread.sleep(5000);
- }
- deleteZKDir(zk, nodeName);
- zk.close();
-
- }
-
- private void enode_test_2() throws IOException,
- InterruptedException, KeeperException {
- checkRoot();
- String parentName = testDirOnZK;
- String nodeName = parentName + "/enode_abc";
- ZooKeeper zk = new ZooKeeper(hostPort, 10000, this);
- ZooKeeper zk_1 = new ZooKeeper(hostPort, 10000, this);
-
- Stat stat_parent = zk_1.exists(parentName, false);
- if (stat_parent == null) {
- try {
- zk.create(parentName, null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
- } catch (KeeperException ke) {
- Assert.fail("Creating node " + parentName + ke.getMessage());
- }
- }
+ private void enode_test_1() throws IOException, InterruptedException, KeeperException {
+ checkRoot();
+ String parentName = testDirOnZK;
+ String nodeName = parentName + "/enode_abc";
+ ZooKeeper zk = new ZooKeeper(hostPort, 10000, this);
- Stat stat_node = zk_1.exists(nodeName, false);
- if (stat_node != null) {
+ Stat stat = zk.exists(parentName, false);
+ if (stat == null) {
+ try {
+ zk.create(parentName, null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
+ } catch (KeeperException ke) {
+ fail("Creating node " + parentName + ke.getMessage());
+ }
+ }
- try {
- zk.delete(nodeName, -1);
- } catch (KeeperException ke) {
- Code code = ke.code();
- boolean valid = code == KeeperException.Code.NONODE
- || code == KeeperException.Code.NOTEMPTY;
- if (!valid) {
- Assert.fail("Unexpected exception code for delete: " + ke.getMessage());
+ try {
+ zk.create(nodeName, null, Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
+ } catch (KeeperException ke) {
+ Code code = ke.code();
+ boolean valid = code == KeeperException.Code.NODEEXISTS;
+ if (!valid) {
+ fail("Unexpected exception code for createin: " + ke.getMessage());
+ }
}
- }
- }
- List<String> firstGen1 = zk_1.getChildren(parentName, true);
- Stat stat = new Stat();
- List<String> firstGen2 = zk_1.getChildren(parentName, true, stat);
+ stat = zk.exists(nodeName, false);
+ if (stat == null) {
+ fail("node " + nodeName + " should exist");
+ }
+ System.out.println("Closing client with sessionid: 0x" + Long.toHexString(zk.getSessionId()));
+ zk.close();
+ zk = new ZooKeeper(hostPort, 10000, this);
+
+ for (int i = 0; i < 10; i++) {
+ System.out.println("i = " + i);
+ stat = zk.exists(nodeName, false);
+ if (stat != null) {
+ System.out.println("node " + nodeName + " should not exist after reconnection close");
+ } else {
+ System.out.println("node " + nodeName + " is gone after reconnection close!");
+ break;
+ }
+ Thread.sleep(5000);
+ }
+ deleteZKDir(zk, nodeName);
+ zk.close();
- if (!firstGen1.equals(firstGen2)) {
- Assert.fail("children lists from getChildren()/getChildren2() do not match");
}
- if (!stat_parent.equals(stat)) {
- Assert.fail("stat from exists()/getChildren() do not match");
- }
+ private void enode_test_2() throws IOException, InterruptedException, KeeperException {
+ checkRoot();
+ String parentName = testDirOnZK;
+ String nodeName = parentName + "/enode_abc";
+ ZooKeeper zk = new ZooKeeper(hostPort, 10000, this);
+ ZooKeeper zk_1 = new ZooKeeper(hostPort, 10000, this);
- try {
- zk.create(nodeName, null, Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
- } catch (KeeperException ke) {
- Code code = ke.code();
- boolean valid = code == KeeperException.Code.NODEEXISTS;
- if (!valid) {
- Assert.fail("Unexpected exception code for createin: " + ke.getMessage());
- }
- }
+ Stat stat_parent = zk_1.exists(parentName, false);
+ if (stat_parent == null) {
+ try {
+ zk.create(parentName, null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
+ } catch (KeeperException ke) {
+ fail("Creating node " + parentName + ke.getMessage());
+ }
+ }
- Thread.sleep(5000);
- WatchedEvent event = events.poll(10, TimeUnit.SECONDS);
- if (event == null) {
- throw new IOException("No event was delivered promptly");
- }
- if (event.getType() != EventType.NodeChildrenChanged
- || !event.getPath().equalsIgnoreCase(parentName)) {
- Assert.fail("Unexpected event was delivered: " + event.toString());
- }
+ Stat stat_node = zk_1.exists(nodeName, false);
+ if (stat_node != null) {
+
+ try {
+ zk.delete(nodeName, -1);
+ } catch (KeeperException ke) {
+ Code code = ke.code();
+ boolean valid = code == KeeperException.Code.NONODE || code == KeeperException.Code.NOTEMPTY;
+ if (!valid) {
+ fail("Unexpected exception code for delete: " + ke.getMessage());
+ }
+ }
+ }
- stat_node = zk_1.exists(nodeName, false);
- if (stat_node == null) {
- Assert.fail("node " + nodeName + " should exist");
- }
+ List<String> firstGen1 = zk_1.getChildren(parentName, true);
+ Stat stat = new Stat();
+ List<String> firstGen2 = zk_1.getChildren(parentName, true, stat);
- try {
- zk.delete(parentName, -1);
- Assert.fail("Should be impossible to delete a non-empty node " + parentName);
- } catch (KeeperException ke) {
- Code code = ke.code();
- boolean valid = code == KeeperException.Code.NOTEMPTY;
- if (!valid) {
- Assert.fail("Unexpected exception code for delete: " + code);
- }
- }
+ if (!firstGen1.equals(firstGen2)) {
+ fail("children lists from getChildren()/getChildren2() do not match");
+ }
- try {
- zk.create(nodeName + "/def", null, Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
- Assert.fail("Should be impossible to create child off Ephemeral node " + nodeName);
- } catch (KeeperException ke) {
- Code code = ke.code();
- boolean valid = code == KeeperException.Code.NOCHILDRENFOREPHEMERALS;
- if (!valid) {
- Assert.fail("Unexpected exception code for createin: " + code);
- }
- }
+ if (!stat_parent.equals(stat)) {
+ fail("stat from exists()/getChildren() do not match");
+ }
- try {
- List<String> children1 = zk.getChildren(nodeName, false);
- List<String> children2 = zk.getChildren(nodeName, false, null);
-
- if (!children1.equals(children2)) {
- Assert.fail("children lists from getChildren()/getChildren2() does not match");
- }
-
- if (children1.size() > 0) {
- Assert.fail("ephemeral node " + nodeName + " should not have children");
- }
- } catch (KeeperException ke) {
- Code code = ke.code();
- boolean valid = code == KeeperException.Code.NONODE;
- if (!valid) {
- Assert.fail("Unexpected exception code for createin: " + code);
- }
- }
- firstGen1 = zk_1.getChildren(parentName, true);
- firstGen2 = zk_1.getChildren(parentName, true, null);
+ try {
+ zk.create(nodeName, null, Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
+ } catch (KeeperException ke) {
+ Code code = ke.code();
+ boolean valid = code == KeeperException.Code.NODEEXISTS;
+ if (!valid) {
+ fail("Unexpected exception code for createin: " + ke.getMessage());
+ }
+ }
- if (!firstGen1.equals(firstGen2)) {
- Assert.fail("children list from getChildren()/getChildren2() does not match");
- }
+ Thread.sleep(5000);
+ WatchedEvent event = events.poll(10, TimeUnit.SECONDS);
+ if (event == null) {
+ throw new IOException("No event was delivered promptly");
+ }
+ if (event.getType() != EventType.NodeChildrenChanged || !event.getPath().equalsIgnoreCase(parentName)) {
+ fail("Unexpected event was delivered: " + event.toString());
+ }
- stat_node = zk_1.exists(nodeName, true);
- if (stat_node == null) {
- Assert.fail("node " + nodeName + " should exist");
- }
- System.out.println("session id of zk: " + zk.getSessionId());
- System.out.println("session id of zk_1: " + zk_1.getSessionId());
- zk.close();
+ stat_node = zk_1.exists(nodeName, false);
+ if (stat_node == null) {
+ fail("node " + nodeName + " should exist");
+ }
- zk_1.exists("nosuchnode", false);
+ try {
+ zk.delete(parentName, -1);
+ fail("Should be impossible to delete a non-empty node " + parentName);
+ } catch (KeeperException ke) {
+ Code code = ke.code();
+ boolean valid = code == KeeperException.Code.NOTEMPTY;
+ if (!valid) {
+ fail("Unexpected exception code for delete: " + code);
+ }
+ }
- event = this.getEvent(10);
- if (event == null) {
- throw new Error("First event was not delivered promptly");
- }
- if (!((event.getType() == EventType.NodeChildrenChanged &&
- event.getPath().equalsIgnoreCase(parentName)) ||
- (event.getType() == EventType.NodeDeleted &&
- event.getPath().equalsIgnoreCase(nodeName)))) {
- System.out.print(parentName + " "
- + EventType.NodeChildrenChanged + " " + nodeName + " " + EventType.NodeDeleted);
- Assert.fail("Unexpected first event was delivered: " + event.toString());
- }
+ try {
+ zk.create(nodeName + "/def", null, Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
+ fail("Should be impossible to create child off Ephemeral node " + nodeName);
+ } catch (KeeperException ke) {
+ Code code = ke.code();
+ boolean valid = code == KeeperException.Code.NOCHILDRENFOREPHEMERALS;
+ if (!valid) {
+ fail("Unexpected exception code for createin: " + code);
+ }
+ }
- event = this.getEvent(10);
+ try {
+ List<String> children1 = zk.getChildren(nodeName, false);
+ List<String> children2 = zk.getChildren(nodeName, false, null);
+
+ if (!children1.equals(children2)) {
+ fail("children lists from getChildren()/getChildren2() does not match");
+ }
+
+ if (children1.size() > 0) {
+ fail("ephemeral node " + nodeName + " should not have children");
+ }
+ } catch (KeeperException ke) {
+ Code code = ke.code();
+ boolean valid = code == KeeperException.Code.NONODE;
+ if (!valid) {
+ fail("Unexpected exception code for createin: " + code);
+ }
+ }
+ firstGen1 = zk_1.getChildren(parentName, true);
+ firstGen2 = zk_1.getChildren(parentName, true, null);
- if (event == null) {
- throw new Error("Second event was not delivered promptly");
- }
- if (!((event.getType() == EventType.NodeChildrenChanged &&
- event.getPath().equalsIgnoreCase(parentName)) ||
- (event.getType() == EventType.NodeDeleted &&
- event.getPath().equalsIgnoreCase(nodeName)))) {
- System.out.print(parentName + " "
- + EventType.NodeChildrenChanged + " " + nodeName + " " + EventType.NodeDeleted);
- Assert.fail("Unexpected second event was delivered: " + event.toString());
- }
+ if (!firstGen1.equals(firstGen2)) {
+ fail("children list from getChildren()/getChildren2() does not match");
+ }
- firstGen1 = zk_1.getChildren(parentName, false);
- stat_node = zk_1.exists(nodeName, false);
- if (stat_node != null) {
- Assert.fail("node " + nodeName + " should have been deleted");
- }
- if (firstGen1.contains(nodeName)) {
- Assert.fail("node " + nodeName + " should not be a children");
- }
- deleteZKDir(zk_1, nodeName);
- zk_1.close();
- }
-
- private void delete_create_get_set_test_1() throws
- IOException, InterruptedException, KeeperException {
- checkRoot();
- ZooKeeper zk = new ZooKeeper(hostPort, 10000, this);
- String parentName = testDirOnZK;
- String nodeName = parentName + "/benwashere";
- try {
- zk.delete(nodeName, -1);
- } catch (KeeperException ke) {
- Code code = ke.code();
- boolean valid = code == KeeperException.Code.NONODE
- || code == KeeperException.Code.NOTEMPTY;
- if (!valid) {
- Assert.fail("Unexpected exception code for delete: " + ke.getMessage());
- }
- }
- try {
- zk.create(nodeName, null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
- } catch (KeeperException ke) {
- Code code = ke.code();
- boolean valid = code == KeeperException.Code.NODEEXISTS;
- if (!valid) {
- Assert.fail("Unexpected exception code for create: " + ke.getMessage());
- }
- }
- try {
- zk.setData(nodeName, "hi".getBytes(), 5700);
- Assert.fail("Should have gotten BadVersion exception");
- } catch (KeeperException ke) {
- if (ke.code() != Code.BADVERSION) {
- Assert.fail("Should have gotten BadVersion exception");
- }
- }
- zk.setData(nodeName, "hi".getBytes(), -1);
- Stat st = new Stat();
- byte[] bytes = zk.getData(nodeName, false, st);
- String retrieved = new String(bytes);
- if (!"hi".equals(retrieved)) {
- Assert.fail("The retrieved data [" + retrieved
- + "] is differented than the expected [hi]");
- }
- try {
- zk.delete(nodeName, 6800);
- Assert.fail("Should have gotten BadVersion exception");
- } catch (KeeperException ke) {
- Code code = ke.code();
- boolean valid = code == KeeperException.Code.NOTEMPTY
- || code == KeeperException.Code.BADVERSION;
- if (!valid) {
- Assert.fail("Unexpected exception code for delete: " + ke.getMessage());
- }
- }
- try {
- zk.delete(nodeName, -1);
- } catch (KeeperException ke) {
- Code code = ke.code();
- boolean valid = code == KeeperException.Code.NOTEMPTY;
- if (!valid) {
- Assert.fail("Unexpected exception code for delete: " + code);
- }
- }
- deleteZKDir(zk, nodeName);
- zk.close();
- }
-
- private void deleteNodeIfExists(ZooKeeper zk, String nodeName)
- throws InterruptedException {
- try {
- zk.delete(nodeName, -1);
- } catch (KeeperException ke) {
- Code code = ke.code();
- boolean valid = code == KeeperException.Code.NONODE ||
- code == KeeperException.Code.NOTEMPTY;
- if (!valid) {
- Assert.fail("Unexpected exception code for delete: " + ke.getMessage());
- }
+ stat_node = zk_1.exists(nodeName, true);
+ if (stat_node == null) {
+ fail("node " + nodeName + " should exist");
+ }
+ System.out.println("session id of zk: " + zk.getSessionId());
+ System.out.println("session id of zk_1: " + zk_1.getSessionId());
+ zk.close();
+
+ zk_1.exists("nosuchnode", false);
+
+ event = this.getEvent(10);
+ if (event == null) {
+ throw new Error("First event was not delivered promptly");
+ }
+ if (!((event.getType() == EventType.NodeChildrenChanged && event.getPath().equalsIgnoreCase(parentName)) || (
+ event.getType() == EventType.NodeDeleted
+ && event.getPath().equalsIgnoreCase(nodeName)))) {
+ System.out.print(parentName
+ + " "
+ + EventType.NodeChildrenChanged
+ + " "
+ + nodeName
+ + " "
+ + EventType.NodeDeleted);
+ fail("Unexpected first event was delivered: " + event.toString());
+ }
+
+ event = this.getEvent(10);
+
+ if (event == null) {
+ throw new Error("Second event was not delivered promptly");
+ }
+ if (!((event.getType() == EventType.NodeChildrenChanged && event.getPath().equalsIgnoreCase(parentName)) || (
+ event.getType() == EventType.NodeDeleted
+ && event.getPath().equalsIgnoreCase(nodeName)))) {
+ System.out.print(parentName
+ + " "
+ + EventType.NodeChildrenChanged
+ + " "
+ + nodeName
+ + " "
+ + EventType.NodeDeleted);
+ fail("Unexpected second event was delivered: " + event.toString());
+ }
+
+ firstGen1 = zk_1.getChildren(parentName, false);
+ stat_node = zk_1.exists(nodeName, false);
+ if (stat_node != null) {
+ fail("node " + nodeName + " should have been deleted");
+ }
+ if (firstGen1.contains(nodeName)) {
+ fail("node " + nodeName + " should not be a children");
+ }
+ deleteZKDir(zk_1, nodeName);
+ zk_1.close();
+ }
+
+ private void delete_create_get_set_test_1() throws IOException, InterruptedException, KeeperException {
+ checkRoot();
+ ZooKeeper zk = new ZooKeeper(hostPort, 10000, this);
+ String parentName = testDirOnZK;
+ String nodeName = parentName + "/benwashere";
+ try {
+ zk.delete(nodeName, -1);
+ } catch (KeeperException ke) {
+ Code code = ke.code();
+ boolean valid = code == KeeperException.Code.NONODE || code == KeeperException.Code.NOTEMPTY;
+ if (!valid) {
+ fail("Unexpected exception code for delete: " + ke.getMessage());
+ }
+ }
+ try {
+ zk.create(nodeName, null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
+ } catch (KeeperException ke) {
+ Code code = ke.code();
+ boolean valid = code == KeeperException.Code.NODEEXISTS;
+ if (!valid) {
+ fail("Unexpected exception code for create: " + ke.getMessage());
+ }
+ }
+ try {
+ zk.setData(nodeName, "hi".getBytes(), 5700);
+ fail("Should have gotten BadVersion exception");
+ } catch (KeeperException ke) {
+ if (ke.code() != Code.BADVERSION) {
+ fail("Should have gotten BadVersion exception");
+ }
+ }
+ zk.setData(nodeName, "hi".getBytes(), -1);
+ Stat st = new Stat();
+ byte[] bytes = zk.getData(nodeName, false, st);
+ String retrieved = new String(bytes);
+ if (!"hi".equals(retrieved)) {
+ fail("The retrieved data [" + retrieved + "] is differented than the expected [hi]");
+ }
+ try {
+ zk.delete(nodeName, 6800);
+ fail("Should have gotten BadVersion exception");
+ } catch (KeeperException ke) {
+ Code code = ke.code();
+ boolean valid = code == KeeperException.Code.NOTEMPTY || code == KeeperException.Code.BADVERSION;
+ if (!valid) {
+ fail("Unexpected exception code for delete: " + ke.getMessage());
+ }
+ }
+ try {
+ zk.delete(nodeName, -1);
+ } catch (KeeperException ke) {
+ Code code = ke.code();
+ boolean valid = code == KeeperException.Code.NOTEMPTY;
+ if (!valid) {
+ fail("Unexpected exception code for delete: " + code);
+ }
+ }
+ deleteZKDir(zk, nodeName);
+ zk.close();
+ }
+
+ private void deleteNodeIfExists(ZooKeeper zk, String nodeName) throws InterruptedException {
+ try {
+ zk.delete(nodeName, -1);
+ } catch (KeeperException ke) {
+ Code code = ke.code();
+ boolean valid = code == KeeperException.Code.NONODE || code == KeeperException.Code.NOTEMPTY;
+ if (!valid) {
+ fail("Unexpected exception code for delete: " + ke.getMessage());
+ }
+ }
}
- }
-
- private void create_get_stat_test()
- throws IOException, InterruptedException, KeeperException {
- checkRoot();
- ZooKeeper zk = new ZooKeeper(hostPort, 10000, this);
- String parentName = testDirOnZK;
- String nodeName = parentName + "/create_with_stat_tmp";
- deleteNodeIfExists(zk, nodeName);
- deleteNodeIfExists(zk, nodeName + "_2");
- Stat stat = new Stat();
- zk.create(nodeName, null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT,
- stat);
- Assert.assertNotNull(stat);
- Assert.assertTrue(stat.getCzxid() > 0);
- Assert.assertTrue(stat.getCtime() > 0);
-
- Stat stat2 = new Stat();
- zk.create(nodeName + "_2", null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT,
- stat2);
- Assert.assertNotNull(stat2);
- Assert.assertTrue(stat2.getCzxid() > stat.getCzxid());
- Assert.assertTrue(stat2.getCtime() > stat.getCtime());
-
- deleteNodeIfExists(zk, nodeName);
- deleteNodeIfExists(zk, nodeName + "_2");
- zk.close();
- }
-
- public void my_test_1() throws IOException,
- InterruptedException, KeeperException {
- enode_test_1();
- enode_test_2();
- delete_create_get_set_test_1();
- create_get_stat_test();
- }
-
- synchronized public void process(WatchedEvent event) {
- try {
- System.out.println("Got an event " + event.toString());
- events.put(event);
- } catch (InterruptedException e) {
- e.printStackTrace();
+
+ private void create_get_stat_test() throws IOException, InterruptedException, KeeperException {
+ checkRoot();
+ ZooKeeper zk = new ZooKeeper(hostPort, 10000, this);
+ String parentName = testDirOnZK;
+ String nodeName = parentName + "/create_with_stat_tmp";
+ deleteNodeIfExists(zk, nodeName);
+ deleteNodeIfExists(zk, nodeName + "_2");
+ Stat stat = new Stat();
+ zk.create(nodeName, null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT, stat);
+ assertNotNull(stat);
+ assertTrue(stat.getCzxid() > 0);
+ assertTrue(stat.getCtime() > 0);
+
+ Stat stat2 = new Stat();
+ zk.create(nodeName + "_2", null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT, stat2);
+ assertNotNull(stat2);
+ assertTrue(stat2.getCzxid() > stat.getCzxid());
+ assertTrue(stat2.getCtime() > stat.getCtime());
+
+ deleteNodeIfExists(zk, nodeName);
+ deleteNodeIfExists(zk, nodeName + "_2");
+ zk.close();
+ }
+
+ public void my_test_1() throws IOException, InterruptedException, KeeperException {
+ enode_test_1();
+ enode_test_2();
+ delete_create_get_set_test_1();
+ create_get_stat_test();
+ }
+
+ public synchronized void process(WatchedEvent event) {
+ try {
+ System.out.println("Got an event " + event.toString());
+ events.put(event);
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
}
- }
-
- public static void main(String[] args) {
- ZooKeeperTestClient zktc = new ZooKeeperTestClient();
- try {
- zktc.my_test_1();
- } catch (Exception e) {
- e.printStackTrace();
+
+ public static void main(String[] args) {
+ ZooKeeperTestClient zktc = new ZooKeeperTestClient();
+ try {
+ zktc.my_test_1();
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
}
- }
-} \ No newline at end of file
+
+}
diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/util/PemReaderTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/util/PemReaderTest.java
index d0d3dc7ee..423b38bb4 100644
--- a/zookeeper-server/src/test/java/org/apache/zookeeper/util/PemReaderTest.java
+++ b/zookeeper-server/src/test/java/org/apache/zookeeper/util/PemReaderTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -18,6 +18,7 @@
package org.apache.zookeeper.util;
+import static org.junit.Assert.assertEquals;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.security.KeyStoreException;
@@ -26,12 +27,10 @@ import java.security.cert.X509Certificate;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
-
import org.apache.zookeeper.common.BaseX509ParameterizedTestCase;
import org.apache.zookeeper.common.KeyStoreFileType;
import org.apache.zookeeper.common.X509KeyType;
import org.apache.zookeeper.common.X509TestContext;
-import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
@@ -45,10 +44,7 @@ public class PemReaderTest extends BaseX509ParameterizedTestCase {
}
public PemReaderTest(
- X509KeyType caKeyType,
- X509KeyType certKeyType,
- String keyPassword,
- Integer paramIndex) {
+ X509KeyType caKeyType, X509KeyType certKeyType, String keyPassword, Integer paramIndex) {
super(paramIndex, () -> {
try {
return X509TestContext.newBuilder()
@@ -67,11 +63,10 @@ public class PemReaderTest extends BaseX509ParameterizedTestCase {
@Test
public void testLoadPrivateKeyFromKeyStore() throws IOException, GeneralSecurityException {
Optional<String> optPassword = x509TestContext.getKeyStorePassword().length() > 0
- ? Optional.of(x509TestContext.getKeyStorePassword())
- : Optional.empty();
- PrivateKey privateKey = PemReader.loadPrivateKey(
- x509TestContext.getKeyStoreFile(KeyStoreFileType.PEM), optPassword);
- Assert.assertEquals(x509TestContext.getKeyStoreKeyPair().getPrivate(), privateKey);
+ ? Optional.of(x509TestContext.getKeyStorePassword())
+ : Optional.empty();
+ PrivateKey privateKey = PemReader.loadPrivateKey(x509TestContext.getKeyStoreFile(KeyStoreFileType.PEM), optPassword);
+ assertEquals(x509TestContext.getKeyStoreKeyPair().getPrivate(), privateKey);
}
// Try to load a password-protected private key without providing a password
@@ -89,9 +84,7 @@ public class PemReaderTest extends BaseX509ParameterizedTestCase {
if (!x509TestContext.isKeyStoreEncrypted()) {
throw new GeneralSecurityException(); // this case is not tested so throw the expected exception
}
- PemReader.loadPrivateKey(
- x509TestContext.getKeyStoreFile(KeyStoreFileType.PEM),
- Optional.of("wrong password"));
+ PemReader.loadPrivateKey(x509TestContext.getKeyStoreFile(KeyStoreFileType.PEM), Optional.of("wrong password"));
}
// Try to load a non-protected private key while providing a password
@@ -100,38 +93,33 @@ public class PemReaderTest extends BaseX509ParameterizedTestCase {
if (x509TestContext.isKeyStoreEncrypted()) {
throw new IOException();
}
- PemReader.loadPrivateKey(
- x509TestContext.getKeyStoreFile(KeyStoreFileType.PEM),
- Optional.of("wrong password"));
+ PemReader.loadPrivateKey(x509TestContext.getKeyStoreFile(KeyStoreFileType.PEM), Optional.of("wrong password"));
}
// Expect this to fail, the trust store does not contain a private key
@Test(expected = KeyStoreException.class)
public void testLoadPrivateKeyFromTrustStore() throws IOException, GeneralSecurityException {
- PemReader.loadPrivateKey(
- x509TestContext.getTrustStoreFile(KeyStoreFileType.PEM), Optional.empty());
+ PemReader.loadPrivateKey(x509TestContext.getTrustStoreFile(KeyStoreFileType.PEM), Optional.empty());
}
// Expect this to fail, the trust store does not contain a private key
@Test(expected = KeyStoreException.class)
public void testLoadPrivateKeyFromTrustStoreWithPassword() throws IOException, GeneralSecurityException {
- PemReader.loadPrivateKey(
- x509TestContext.getTrustStoreFile(KeyStoreFileType.PEM), Optional.of("foobar"));
+ PemReader.loadPrivateKey(x509TestContext.getTrustStoreFile(KeyStoreFileType.PEM), Optional.of("foobar"));
}
@Test
public void testLoadCertificateFromKeyStore() throws IOException, GeneralSecurityException {
- List<X509Certificate> certs = PemReader.readCertificateChain(
- x509TestContext.getKeyStoreFile(KeyStoreFileType.PEM));
- Assert.assertEquals(1, certs.size());
- Assert.assertEquals(x509TestContext.getKeyStoreCertificate(), certs.get(0));
+ List<X509Certificate> certs = PemReader.readCertificateChain(x509TestContext.getKeyStoreFile(KeyStoreFileType.PEM));
+ assertEquals(1, certs.size());
+ assertEquals(x509TestContext.getKeyStoreCertificate(), certs.get(0));
}
@Test
public void testLoadCertificateFromTrustStore() throws IOException, GeneralSecurityException {
- List<X509Certificate> certs = PemReader.readCertificateChain(
- x509TestContext.getTrustStoreFile(KeyStoreFileType.PEM));
- Assert.assertEquals(1, certs.size());
- Assert.assertEquals(x509TestContext.getTrustStoreCertificate(), certs.get(0));
+ List<X509Certificate> certs = PemReader.readCertificateChain(x509TestContext.getTrustStoreFile(KeyStoreFileType.PEM));
+ assertEquals(1, certs.size());
+ assertEquals(x509TestContext.getTrustStoreCertificate(), certs.get(0));
}
+
}