You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@zookeeper.apache.org by an...@apache.org on 2018/10/05 12:26:08 UTC
[15/51] [partial] zookeeper git commit: ZOOKEEPER-3032: MAVEN
MIGRATION - move java server, client
http://git-wip-us.apache.org/repos/asf/zookeeper/blob/faa7cec7/src/java/test/org/apache/zookeeper/JaasConfiguration.java
----------------------------------------------------------------------
diff --git a/src/java/test/org/apache/zookeeper/JaasConfiguration.java b/src/java/test/org/apache/zookeeper/JaasConfiguration.java
deleted file mode 100644
index bf145d0..0000000
--- a/src/java/test/org/apache/zookeeper/JaasConfiguration.java
+++ /dev/null
@@ -1,75 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-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;
-
-/**
- * This helper class allows to programmatically create a JAAS configuration.
- * Each section must have a name and a login module, and a set of key/values
- * to describe login options.
- *
- * Example:
- * jaas = new JaasConfiguration();
- * jaas.addSection("Server", "org.apache.zookeeper.server.auth.DigestLoginModule",
- * "username", "passowrd");
- */
-public class JaasConfiguration extends javax.security.auth.login.Configuration {
- private final Map<String, AppConfigurationEntry[]> sections =
- new HashMap<String, AppConfigurationEntry[]>();
-
- public JaasConfiguration() {
- }
-
- /**
- * Add a section to the jaas.conf
- * @param name Section name
- * @param loginModuleName Login module name
- * @param args login key/value args
- */
- public void addSection(String name, String loginModuleName, String... args) {
- Map<String, String> conf = new HashMap<String, String>();
- // loop through the args (must be key/value sequence)
- for (int i = 0; i < args.length - 1; i += 2) {
- conf.put(args[i], args[i + 1]);
- }
- addSection(name, loginModuleName, conf);
- }
-
- /**
- * Add a section to the jaas.conf
- * @param name Section name
- * @param loginModuleName Login module name
- * @param conf login key/value args
- */
- 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);
- }
-
- @Override
- public AppConfigurationEntry[] getAppConfigurationEntry(String appName) {
- return sections.get(appName);
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/zookeeper/blob/faa7cec7/src/java/test/org/apache/zookeeper/MockPacket.java
----------------------------------------------------------------------
diff --git a/src/java/test/org/apache/zookeeper/MockPacket.java b/src/java/test/org/apache/zookeeper/MockPacket.java
deleted file mode 100644
index f4bb19a..0000000
--- a/src/java/test/org/apache/zookeeper/MockPacket.java
+++ /dev/null
@@ -1,46 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.zookeeper;
-
-import org.apache.zookeeper.proto.RequestHeader;
-import org.apache.zookeeper.proto.ReplyHeader;
-import org.apache.jute.Record;
-import org.apache.zookeeper.ZooKeeper.WatchRegistration;
-import java.nio.ByteBuffer;
-
-public class MockPacket extends ClientCnxn.Packet {
-
- 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) {
- super(requestHeader, replyHeader, request, response, watchRegistration, readOnly);
- }
-
- public ByteBuffer createAndReturnBB() {
- createBB();
- return this.bb;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/zookeeper/blob/faa7cec7/src/java/test/org/apache/zookeeper/MultiResponseTest.java
----------------------------------------------------------------------
diff --git a/src/java/test/org/apache/zookeeper/MultiResponseTest.java b/src/java/test/org/apache/zookeeper/MultiResponseTest.java
deleted file mode 100644
index 75d9a12..0000000
--- a/src/java/test/org/apache/zookeeper/MultiResponseTest.java
+++ /dev/null
@@ -1,72 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.zookeeper;
-
-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();
-
- response.add(new OpResult.CheckResult());
- response.add(new OpResult.CreateResult("foo-bar"));
- response.add(new OpResult.DeleteResult());
-
- Stat s = new Stat();
- s.setCzxid(546);
- response.add(new OpResult.SetDataResult(s));
-
- MultiResponse decodedResponse = codeDecode(response);
-
- Assert.assertEquals(response, decodedResponse);
- Assert.assertEquals(response.hashCode(), decodedResponse.hashCode());
- }
-
- @Test
- public void testEmptyRoundTrip() throws IOException {
- MultiResponse result = new MultiResponse();
- MultiResponse decodedResult = codeDecode(result);
-
- Assert.assertEquals(result, decodedResult);
- Assert.assertEquals(result.hashCode(), decodedResult.hashCode());
- }
-
- private MultiResponse codeDecode(MultiResponse request) throws IOException {
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- BinaryOutputArchive boa = BinaryOutputArchive.getArchive(baos);
- request.serialize(boa, "result");
- baos.close();
- ByteBuffer bb = ByteBuffer.wrap(baos.toByteArray());
- bb.rewind();
-
- BinaryInputArchive bia = BinaryInputArchive.getArchive(new ByteBufferInputStream(bb));
- MultiResponse decodedRequest = new MultiResponse();
- decodedRequest.deserialize(bia, "result");
- return decodedRequest;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/zookeeper/blob/faa7cec7/src/java/test/org/apache/zookeeper/MultiTransactionRecordTest.java
----------------------------------------------------------------------
diff --git a/src/java/test/org/apache/zookeeper/MultiTransactionRecordTest.java b/src/java/test/org/apache/zookeeper/MultiTransactionRecordTest.java
deleted file mode 100644
index d33a3d7..0000000
--- a/src/java/test/org/apache/zookeeper/MultiTransactionRecordTest.java
+++ /dev/null
@@ -1,68 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.zookeeper;
-
-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 MultiTransactionRecordTest extends ZKTestCase {
- @Test
- public void testRoundTrip() throws IOException {
- MultiTransactionRecord request = new MultiTransactionRecord();
- request.add(Op.check("check", 1));
- request.add(Op.create("create", "create data".getBytes(), ZooDefs.Ids.CREATOR_ALL_ACL, ZooDefs.Perms.ALL));
- request.add(Op.delete("delete", 17));
- request.add(Op.setData("setData", "set data".getBytes(), 19));
-
- MultiTransactionRecord decodedRequest = codeDecode(request);
-
- Assert.assertEquals(request, decodedRequest);
- Assert.assertEquals(request.hashCode(), decodedRequest.hashCode());
- }
-
- @Test
- public void testEmptyRoundTrip() throws IOException {
- MultiTransactionRecord request = new MultiTransactionRecord();
- MultiTransactionRecord decodedRequest = codeDecode(request);
-
- Assert.assertEquals(request, decodedRequest);
- Assert.assertEquals(request.hashCode(), decodedRequest.hashCode());
- }
-
- private MultiTransactionRecord codeDecode(MultiTransactionRecord request) throws IOException {
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- BinaryOutputArchive boa = BinaryOutputArchive.getArchive(baos);
- request.serialize(boa, "request");
- baos.close();
- ByteBuffer bb = ByteBuffer.wrap(baos.toByteArray());
- bb.rewind();
-
- BinaryInputArchive bia = BinaryInputArchive.getArchive(new ByteBufferInputStream(bb));
- MultiTransactionRecord decodedRequest = new MultiTransactionRecord();
- decodedRequest.deserialize(bia, "request");
- return decodedRequest;
- }
-}
http://git-wip-us.apache.org/repos/asf/zookeeper/blob/faa7cec7/src/java/test/org/apache/zookeeper/PortAssignment.java
----------------------------------------------------------------------
diff --git a/src/java/test/org/apache/zookeeper/PortAssignment.java b/src/java/test/org/apache/zookeeper/PortAssignment.java
deleted file mode 100644
index 5c5b093..0000000
--- a/src/java/test/org/apache/zookeeper/PortAssignment.java
+++ /dev/null
@@ -1,210 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.zookeeper;
-
-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
- // range, which the OS will assign to client socket connections. We can't
- // coordinate with the OS on the assignment of those ports, so it's best to
- // stay out of that range to avoid conflicts. Typical ranges for ephemeral
- // ports are:
- // - IANA suggests 49152 - 65535
- // - Linux typically uses 32768 - 61000
- // - FreeBSD modern versions typically use the IANA suggested range
- // - Windows modern versions typically use the IANA suggested range
- private static final int GLOBAL_BASE_PORT = 11221;
- private static final int GLOBAL_MAX_PORT = 32767;
-
- private static PortRange portRange = null;
- private static int nextPort;
-
- /**
- * Assign a new, unique port to the test. This method works by assigning
- * ports from a valid port range as identified by the total number of
- * concurrent test processes and the ID of this test process. Each
- * concurrent test process uses an isolated range, so it's not possible for
- * multiple test processes to collide on the same port. Within the port
- * range, ports are assigned in monotonic increasing order, wrapping around
- * to the beginning of the range if needed. As an extra precaution, the
- * method attempts to bind to the port and immediately close it before
- * returning it to the caller. If the port cannot be bound, then it tries
- * the next one in the range. This provides some resiliency in case the port
- * is otherwise occupied, such as a developer running other servers on the
- * machine running the tests.
- *
- * @return port
- */
- public synchronized static int unique() {
- if (portRange == null) {
- portRange = setupPortRange(System.getProperty("test.junit.threads"),
- System.getProperty("sun.java.command"));
- nextPort = portRange.getMinimum();
- }
- int candidatePort = nextPort;
- 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));
- }
- try {
- ServerSocket s = new ServerSocket(candidatePort);
- s.close();
- nextPort = candidatePort;
- 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);
- }
- }
- }
-
- /**
- * Sets up the port range to be used. In typical usage, Ant invokes JUnit,
- * possibly using multiple JUnit processes to execute multiple test suites
- * concurrently. The count of JUnit processes is passed from Ant as a system
- * property named "test.junit.threads". Ant's JUnit runner receives the
- * thread ID as a command line argument of the form threadid=N, where N is an
- * integer in the range [1, ${test.junit.threads}]. It's not otherwise
- * accessible, so we need to parse it from the command line. This method
- * uses these 2 pieces of information to split the available ports into
- * disjoint ranges. Each JUnit process only assigns ports from its own range
- * in order to prevent bind errors during concurrent test runs. If any of
- * this information is unavailable or unparseable, then the default behavior
- * is for this process to use the entire available port range. This is
- * expected when running tests outside of Ant.
- *
- * @param strProcessCount string representation of integer process count,
- * typically taken from system property test.junit.threads
- * @param cmdLine command line containing threadid=N argument, typically
- * taken from system property sun.java.command
- * @return port range to use
- */
- static PortRange setupPortRange(String strProcessCount, String cmdLine) {
- Integer processCount = null;
- if (strProcessCount != null && !strProcessCount.isEmpty()) {
- try {
- processCount = Integer.valueOf(strProcessCount);
- } catch (NumberFormatException e) {
- LOG.warn("Error parsing test.junit.threads = {}.",
- strProcessCount, e);
- }
- }
-
- Integer threadId = null;
- if (processCount != null) {
- if (cmdLine != null && !cmdLine.isEmpty()) {
- Matcher m = Pattern.compile("threadid=(\\d+)").matcher(cmdLine);
- if (m.find()) {
- try {
- threadId = Integer.valueOf(m.group(1));
- } catch (NumberFormatException e) {
- LOG.warn("Error parsing threadid from {}.", cmdLine, e);
- }
- }
- }
- }
-
- final PortRange newPortRange;
- if (processCount != null && processCount > 1 && threadId != null) {
- // We know the total JUnit process count and this test process's ID.
- // 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 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);
- } else {
- // If running outside the context of Ant or Ant is using a single
- // test process, then use all valid ports.
- newPortRange = new PortRange(GLOBAL_BASE_PORT, GLOBAL_MAX_PORT);
- LOG.info("Single test process using ports from {}.", newPortRange);
- }
-
- return newPortRange;
- }
-
- /**
- * Contains the minimum and maximum (both inclusive) in a range of ports.
- */
- static final class PortRange {
- private final int minimum;
- private final int maximum;
-
- /**
- * Creates a new PortRange.
- *
- * @param minimum lower bound port number
- * @param maximum upper bound port number
- */
- PortRange(int minimum, int maximum) {
- this.minimum = minimum;
- this.maximum = maximum;
- }
-
- /**
- * Returns maximum port in the range.
- *
- * @return maximum
- */
- int getMaximum() {
- return maximum;
- }
-
- /**
- * Returns minimum port in the range.
- *
- * @return minimum
- */
- int getMinimum() {
- return minimum;
- }
-
- @Override
- public String toString() {
- return String.format("%d - %d", minimum, maximum);
- }
- }
-
- /**
- * There is no reason to instantiate this class.
- */
- private PortAssignment() {
- }
-}
http://git-wip-us.apache.org/repos/asf/zookeeper/blob/faa7cec7/src/java/test/org/apache/zookeeper/PortAssignmentTest.java
----------------------------------------------------------------------
diff --git a/src/java/test/org/apache/zookeeper/PortAssignmentTest.java b/src/java/test/org/apache/zookeeper/PortAssignmentTest.java
deleted file mode 100644
index 28691c6..0000000
--- a/src/java/test/org/apache/zookeeper/PortAssignmentTest.java
+++ /dev/null
@@ -1,80 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.zookeeper;
-
-import static org.junit.Assert.assertEquals;
-
-import java.util.Arrays;
-import java.util.Collection;
-
-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)
-public class PortAssignmentTest {
-
- private final String strProcessCount;
- private final String cmdLine;
- private final int expectedMinimumPort;
- private final int expectedMaximumPort;
-
- @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 });
- }
-
- public PortAssignmentTest(String strProcessCount, String cmdLine,
- int expectedMinimumPort, int expectedMaximumPort) {
- this.strProcessCount = strProcessCount;
- this.cmdLine = cmdLine;
- this.expectedMinimumPort = expectedMinimumPort;
- this.expectedMaximumPort = expectedMaximumPort;
- }
-
- @Test
- public void testSetupPortRange() {
- 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);
- }
-}
http://git-wip-us.apache.org/repos/asf/zookeeper/blob/faa7cec7/src/java/test/org/apache/zookeeper/RemoveWatchesCmdTest.java
----------------------------------------------------------------------
diff --git a/src/java/test/org/apache/zookeeper/RemoveWatchesCmdTest.java b/src/java/test/org/apache/zookeeper/RemoveWatchesCmdTest.java
deleted file mode 100644
index c239404..0000000
--- a/src/java/test/org/apache/zookeeper/RemoveWatchesCmdTest.java
+++ /dev/null
@@ -1,345 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.zookeeper;
-
-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;
-
-/**
- * Testing remove watches using command line
- */
-public class RemoveWatchesCmdTest extends ClientBase {
- private static final Logger LOG = LoggerFactory
- .getLogger(RemoveWatchesCmdTest.class);
- private ZooKeeper zk;
- private ZooKeeperMain zkMain;
-
- @Override
- public void setUp() throws Exception {
- super.setUp();
- zk = createClient();
- zkMain = new ZooKeeperMain(zk);
- }
-
- @Override
- public void tearDown() throws Exception {
- if (zk != null) {
- zk.close();
- }
- super.tearDown();
- }
-
- /**
- * Test verifies default options. When there is no passed options,
- * removewatches command will use default options - WatcherType.ANY and
- * local=false
- */
- @Test(timeout = 30000)
- public void testRemoveWatchesWithNoPassedOptions() throws Exception {
- List<EventType> expectedEvents = new ArrayList<Watcher.Event.EventType>();
- expectedEvents.add(EventType.ChildWatchRemoved);
- 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);
-
- LOG.info("Adding childwatcher to /testnode1 and /testnode2");
- zk.getChildren("/testnode1", myWatcher);
- zk.getChildren("/testnode2", myWatcher);
-
- LOG.info("Adding datawatcher to /testnode1 and /testnode2");
- zk.getData("/testnode1", myWatcher, null);
- zk.getData("/testnode2", myWatcher, null);
-
- 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));
- 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"));
- }
-
- /**
- * Test verifies deletion of NodeDataChanged watches
- */
- @Test(timeout = 30000)
- public void testRemoveNodeDataChangedWatches() throws Exception {
- LOG.info("Adding data watcher using getData()");
- List<EventType> expectedEvents = new ArrayList<Watcher.Event.EventType>();
- expectedEvents.add(EventType.DataWatchRemoved);
- MyWatcher myWatcher = new MyWatcher("/testnode1", expectedEvents, 1);
-
- 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));
-
- 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());
- }
-
- /**
- * Test verifies deletion of NodeCreated data watches
- */
- @Test(timeout = 30000)
- public void testRemoveNodeCreatedWatches() throws Exception {
- 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);
- // Adding pre-created watcher
- LOG.info("Adding NodeCreated watcher");
- zk.exists("/testnode1", myWatcher1);
- zk.exists("/testnode1/testnode2", myWatcher2);
-
- 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));
- 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"));
-
- 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));
-
- myWatcher2.matches();
- Assert.assertEquals(
- "Failed to remove pre-create watches : " + zk.getExistWatches(),
- 0, zk.getExistWatches().size());
- }
-
- /**
- * Test verifies deletion of NodeChildrenChanged watches
- */
- @Test(timeout = 30000)
- public void testRemoveNodeChildrenChangedWatches() throws Exception {
- List<EventType> expectedEvents = new ArrayList<Watcher.Event.EventType>();
- expectedEvents.add(EventType.ChildWatchRemoved);
- MyWatcher myWatcher = new MyWatcher("/testnode1", expectedEvents, 1);
-
- 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));
- myWatcher.matches();
- Assert.assertEquals(
- "Failed to remove child watches : " + zk.getChildWatches(), 0,
- zk.getChildWatches().size());
- }
-
- /**
- * Test verifies deletion of NodeDeleted watches
- */
- @Test(timeout = 30000)
- public void testRemoveNodeDeletedWatches() throws Exception {
- LOG.info("Adding NodeDeleted watcher");
- List<EventType> expectedEvents = new ArrayList<Watcher.Event.EventType>();
- expectedEvents.add(EventType.ChildWatchRemoved);
- 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.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));
- LOG.info("Waiting for the ChildWatchRemoved event");
- myWatcher.matches();
- Assert.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"));
-
- // verify node delete watcher
- zk.delete("/testnode1/testnode2", -1);
- myWatcher.matches();
- }
-
- /**
- * Test verifies deletion of any watches
- */
- @Test(timeout = 30000)
- public void testRemoveAnyWatches() throws Exception {
- verifyRemoveAnyWatches(false);
- }
-
- /**
- * Test verifies deletion of watches locally when there is no server
- * connection
- */
- @Test(timeout = 30000)
- public void testRemoveWatchesLocallyWhenNoServerConnection()
- throws Exception {
- verifyRemoveAnyWatches(true);
- }
-
- private void verifyRemoveAnyWatches(boolean local) throws Exception {
- final Map<String, List<EventType>> pathVsEvent = new HashMap<String, List<EventType>>();
- LOG.info("Adding NodeChildrenChanged, NodeDataChanged watchers");
- final CountDownLatch watcherLatch = new CountDownLatch(2);
- Watcher watcher = new Watcher() {
-
- @Override
- public void process(WatchedEvent event) {
- switch (event.getType()) {
- case ChildWatchRemoved:
- case DataWatchRemoved: {
- addWatchNotifications(pathVsEvent, event);
- watcherLatch.countDown();
- break;
- }
- case NodeChildrenChanged:
- case NodeDataChanged: {
- addWatchNotifications(pathVsEvent, event);
- break;
- }
- }
- }
-
- private void addWatchNotifications(
- final Map<String, List<EventType>> pathVsEvent,
- WatchedEvent event) {
- List<EventType> events = pathVsEvent.get(event.getPath());
- if (null == events) {
- events = new ArrayList<Watcher.Event.EventType>();
- pathVsEvent.put(event.getPath(), events);
- }
- events.add(event.getType());
- }
- };
- 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";
- if (local) {
- LOG.info("Stopping ZK server to verify deletion of watches locally");
- stopServer();
- cmdstring = "removewatches /testnode1 -a -l";
- }
-
- 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));
- 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));
- }
-
- private class MyWatcher implements Watcher {
- private final String path;
- private String eventPath;
- private final CountDownLatch latch;
- private final List<EventType> expectedEvents = new ArrayList<EventType>();
-
- public MyWatcher(String path, List<EventType> expectedEvents, int count) {
- this.path = path;
- this.latch = new CountDownLatch(count);
- this.expectedEvents.addAll(expectedEvents);
- }
-
- public void process(WatchedEvent event) {
- LOG.debug("Event path : {}, eventPath : {}"
- + new Object[] { path, event.getPath() });
- this.eventPath = event.getPath();
- if (expectedEvents.contains(event.getType())) {
- latch.countDown();
- }
- }
-
- public boolean matches() throws InterruptedException {
- if (!latch.await(CONNECTION_TIMEOUT / 3, TimeUnit.MILLISECONDS)) {
- LOG.error("Failed to get watch notifications!");
- return false;
- }
- LOG.debug("Client path : {} eventPath : {}", new Object[] { path,
- eventPath });
- return path.equals(eventPath);
- }
- }
-
-}