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/10 10:30:07 UTC
[08/51] [partial] zookeeper git commit: ZOOKEEPER-3032: MAVEN
MIGRATION - branch 3.4 move java server, client
http://git-wip-us.apache.org/repos/asf/zookeeper/blob/c0aa3b3f/src/java/test/org/apache/zookeeper/test/StaticHostProviderTest.java
----------------------------------------------------------------------
diff --git a/src/java/test/org/apache/zookeeper/test/StaticHostProviderTest.java b/src/java/test/org/apache/zookeeper/test/StaticHostProviderTest.java
deleted file mode 100644
index a4107a5..0000000
--- a/src/java/test/org/apache/zookeeper/test/StaticHostProviderTest.java
+++ /dev/null
@@ -1,362 +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.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 org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.net.InetAddress;
-import java.net.InetSocketAddress;
-import java.net.UnknownHostException;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.List;
-
-import static org.hamcrest.CoreMatchers.anyOf;
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.hamcrest.core.Is.is;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotSame;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertThat;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
-import static org.junit.matchers.JUnitMatchers.hasItems;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.spy;
-import static org.mockito.Mockito.times;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
-
-public class StaticHostProviderTest extends ZKTestCase {
- private static final Logger LOG = LoggerFactory.getLogger(StaticHostProviderTest.class);
-
- @Test
- public void testNextGoesRound() {
- HostProvider hostProvider = getHostProvider((byte) 2);
- InetSocketAddress first = hostProvider.next(0);
- assertTrue(first instanceof InetSocketAddress);
- hostProvider.next(0);
- assertEquals(first, hostProvider.next(0));
- }
-
- @Test
- public void testNextGoesRoundAndSleeps() {
- byte size = 2;
- HostProvider hostProvider = getHostProvider(size);
- while (size > 0) {
- hostProvider.next(0);
- --size;
- }
- long start = Time.currentElapsedTime();
- hostProvider.next(1000);
- long stop = Time.currentElapsedTime();
- assertTrue(900 <= stop - start);
- }
-
- @Test
- public void testNextDoesNotSleepForZero() {
- byte size = 2;
- HostProvider hostProvider = getHostProvider(size);
- while (size > 0) {
- hostProvider.next(0);
- --size;
- }
- long start = Time.currentElapsedTime();
- hostProvider.next(0);
- long stop = Time.currentElapsedTime();
- assertTrue(5 > stop - start);
- }
-
- @Test
- public void testTwoConsequitiveCallsToNextReturnDifferentElement() {
- HostProvider hostProvider = getHostProvider((byte) 2);
- assertNotSame(hostProvider.next(0), hostProvider.next(0));
- }
-
- @Test
- public void testOnConnectDoesNotReset() {
- HostProvider hostProvider = getHostProvider((byte) 2);
- InetSocketAddress first = hostProvider.next(0);
- hostProvider.onConnected();
- InetSocketAddress second = hostProvider.next(0);
- assertNotSame(first, second);
- }
-
- @Test
- public void testLiteralIPNoReverseNS() {
- byte size = 30;
- HostProvider hostProvider = getHostProviderUnresolved(size);
- for (int i = 0; i < size; i++) {
- InetSocketAddress next = hostProvider.next(0);
- assertTrue(next instanceof InetSocketAddress);
- assertTrue(!next.isUnresolved());
- assertTrue("InetSocketAddress must not have hostname part " +
- next.toString(), next.toString().startsWith("/"));
- // Do NOT trigger the reverse name service lookup.
- String hostname = next.getHostName();
- // In this case, the hostname equals literal IP address.
- hostname.equals(next.getAddress().getHostAddress());
- }
- }
-
- @Test(expected = IllegalArgumentException.class)
- public void testEmptyServerAddressesList() {
- HostProvider hp = new StaticHostProvider(new ArrayList<InetSocketAddress>());
- }
-
- @Test
- public void testInvalidHostAddresses() {
- // Arrange
- final List<InetSocketAddress> invalidAddresses = new ArrayList<InetSocketAddress>();
- InetSocketAddress unresolved = InetSocketAddress.createUnresolved("a", 1234);
- invalidAddresses.add(unresolved);
- StaticHostProvider.Resolver resolver = new StaticHostProvider.Resolver() {
- @Override
- public InetAddress[] getAllByName(String name) throws UnknownHostException {
- throw new UnknownHostException();
- }
- };
- StaticHostProvider sp = new StaticHostProvider(invalidAddresses, resolver);
-
- // Act & Assert
- InetSocketAddress n1 = sp.next(0);
- assertTrue("Provider should return unresolved address is host is unresolvable", n1.isUnresolved());
- assertSame("Provider should return original address is host is unresolvable", unresolved, n1);
- }
-
- @Test
- public void testReResolvingSingle() throws UnknownHostException {
- // Arrange
- byte size = 1;
- ArrayList<InetSocketAddress> list = new ArrayList<InetSocketAddress>(size);
-
- // Test a hostname that resolves to a single address
- list.add(InetSocketAddress.createUnresolved("issues.apache.org", 1234));
-
- final InetAddress issuesApacheOrg = mock(InetAddress.class);
- when(issuesApacheOrg.getHostAddress()).thenReturn("192.168.1.1");
- when(issuesApacheOrg.toString()).thenReturn("issues.apache.org");
- when(issuesApacheOrg.getHostName()).thenReturn("issues.apache.org");
-
- StaticHostProvider.Resolver resolver = new StaticHostProvider.Resolver() {
- @Override
- public InetAddress[] getAllByName(String name) {
- return new InetAddress[] {
- issuesApacheOrg
- };
- }
- };
- StaticHostProvider.Resolver spyResolver = spy(resolver);
-
- // Act
- StaticHostProvider hostProvider = new StaticHostProvider(list, spyResolver);
- for (int i = 0; i < 10; i++) {
- InetSocketAddress next = hostProvider.next(0);
- assertEquals(issuesApacheOrg, next.getAddress());
- }
-
- // Assert
- // Resolver called 10 times, because we shouldn't cache the resolved addresses
- verify(spyResolver, times(10)).getAllByName("issues.apache.org"); // resolution occurred
- }
-
- @Test
- public void testReResolvingMultiple() throws UnknownHostException {
- // Arrange
- byte size = 1;
- ArrayList<InetSocketAddress> list = new ArrayList<InetSocketAddress>(size);
-
- // Test a hostname that resolves to multiple addresses
- list.add(InetSocketAddress.createUnresolved("www.apache.org", 1234));
-
- final InetAddress apacheOrg1 = mock(InetAddress.class);
- when(apacheOrg1.getHostAddress()).thenReturn("192.168.1.1");
- when(apacheOrg1.toString()).thenReturn("www.apache.org");
- when(apacheOrg1.getHostName()).thenReturn("www.apache.org");
-
- final InetAddress apacheOrg2 = mock(InetAddress.class);
- when(apacheOrg2.getHostAddress()).thenReturn("192.168.1.2");
- when(apacheOrg2.toString()).thenReturn("www.apache.org");
- when(apacheOrg2.getHostName()).thenReturn("www.apache.org");
-
- final List<InetAddress> resolvedAddresses = new ArrayList<InetAddress>();
- resolvedAddresses.add(apacheOrg1);
- resolvedAddresses.add(apacheOrg2);
- StaticHostProvider.Resolver resolver = new StaticHostProvider.Resolver() {
- @Override
- public InetAddress[] getAllByName(String name) {
- return resolvedAddresses.toArray(new InetAddress[resolvedAddresses.size()]);
- }
- };
- StaticHostProvider.Resolver spyResolver = spy(resolver);
-
- // Act & Assert
- StaticHostProvider hostProvider = new StaticHostProvider(list, spyResolver);
- assertEquals(1, hostProvider.size()); // single address not extracted
-
- for (int i = 0; i < 10; i++) {
- InetSocketAddress next = hostProvider.next(0);
- assertThat("Bad IP address returned", next.getAddress().getHostAddress(), anyOf(equalTo(apacheOrg1.getHostAddress()), equalTo(apacheOrg2.getHostAddress())));
- assertEquals(1, hostProvider.size()); // resolve() call keeps the size of provider
- }
- // Resolver called 10 times, because we shouldn't cache the resolved addresses
- verify(spyResolver, times(10)).getAllByName("www.apache.org"); // resolution occurred
- }
-
- @Test
- public void testReResolveMultipleOneFailing() throws UnknownHostException {
- // Arrange
- final List<InetSocketAddress> list = new ArrayList<InetSocketAddress>();
- list.add(InetSocketAddress.createUnresolved("www.apache.org", 1234));
- 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));
- 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.getHostName()).thenReturn("www.apache.org");
- resolvedAddresses.add(apacheOrg);
- }
-
- StaticHostProvider.Resolver resolver = new StaticHostProvider.Resolver() {
- @Override
- public InetAddress[] getAllByName(String name) {
- return resolvedAddresses.toArray(new InetAddress[resolvedAddresses.size()]);
- }
- };
- StaticHostProvider.Resolver spyResolver = spy(resolver);
- StaticHostProvider hostProvider = new StaticHostProvider(list, spyResolver);
-
- // Act & Assert
- InetSocketAddress resolvedFirst = hostProvider.next(0);
- assertFalse("HostProvider should return resolved addresses", resolvedFirst.isUnresolved());
- assertThat("Bad IP address returned", ipList, hasItems(resolvedFirst.getAddress().getHostAddress()));
-
- hostProvider.onConnected(); // first address worked
-
- InetSocketAddress resolvedSecond = hostProvider.next(0);
- assertFalse("HostProvider should return resolved addresses", resolvedSecond.isUnresolved());
- assertThat("Bad IP address returned", ipList, hasItems(resolvedSecond.getAddress().getHostAddress()));
-
- // Second address doesn't work, so we don't call onConnected() this time
- // StaticHostProvider should try to re-resolve the address in this case
-
- InetSocketAddress resolvedThird = hostProvider.next(0);
- assertFalse("HostProvider should return resolved addresses", resolvedThird.isUnresolved());
- assertThat("Bad IP address returned", ipList, hasItems(resolvedThird.getAddress().getHostAddress()));
-
- verify(spyResolver, times(3)).getAllByName("www.apache.org"); // resolution occured every time
- }
-
- @Test
- public void testEmptyResolution() throws UnknownHostException {
- // Arrange
- final List<InetSocketAddress> list = new ArrayList<InetSocketAddress>();
- list.add(InetSocketAddress.createUnresolved("www.apache.org", 1234));
- list.add(InetSocketAddress.createUnresolved("www.google.com", 1234));
- final List<InetAddress> resolvedAddresses = new ArrayList<InetAddress>();
-
- final InetAddress apacheOrg1 = mock(InetAddress.class);
- when(apacheOrg1.getHostAddress()).thenReturn("192.168.1.1");
- when(apacheOrg1.toString()).thenReturn("www.apache.org");
- when(apacheOrg1.getHostName()).thenReturn("www.apache.org");
-
- resolvedAddresses.add(apacheOrg1);
-
- StaticHostProvider.Resolver resolver = new StaticHostProvider.Resolver() {
- @Override
- public InetAddress[] getAllByName(String name) {
- if ("www.apache.org".equalsIgnoreCase(name)) {
- return resolvedAddresses.toArray(new InetAddress[resolvedAddresses.size()]);
- } else {
- return new InetAddress[0];
- }
- }
- };
- StaticHostProvider.Resolver spyResolver = spy(resolver);
- StaticHostProvider hostProvider = new StaticHostProvider(list, spyResolver);
-
- // Act & Assert
- for (int i = 0; i < 10; i++) {
- InetSocketAddress resolved = hostProvider.next(0);
- hostProvider.onConnected();
- if (resolved.getHostName().equals("www.google.com")) {
- assertTrue("HostProvider should return unresolved address if host is unresolvable", resolved.isUnresolved());
- } else {
- assertFalse("HostProvider should return resolved addresses", resolved.isUnresolved());
- assertEquals("192.168.1.1", resolved.getAddress().getHostAddress());
- }
- }
-
- verify(spyResolver, times(5)).getAllByName("www.apache.org");
- verify(spyResolver, times(5)).getAllByName("www.google.com");
- }
-
- @Test
- public void testReResolvingLocalhost() {
- byte size = 2;
- ArrayList<InetSocketAddress> list = new ArrayList<InetSocketAddress>(size);
-
- // Test a hostname that resolves to multiple addresses
- list.add(InetSocketAddress.createUnresolved("localhost", 1234));
- list.add(InetSocketAddress.createUnresolved("localhost", 1235));
- StaticHostProvider hostProvider = new StaticHostProvider(list);
- 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);
- }
-
- private StaticHostProvider getHostProviderUnresolved(byte size) {
- return new StaticHostProvider(getUnresolvedServerAddresses(size));
- }
-
- private Collection<InetSocketAddress> getUnresolvedServerAddresses(byte size) {
- ArrayList<InetSocketAddress> list = new ArrayList<InetSocketAddress>(size);
- while (size > 0) {
- list.add(InetSocketAddress.createUnresolved("192.0.2." + size, 1234 + size));
- --size;
- }
- return list;
- }
-
- private StaticHostProvider getHostProvider(byte size) {
- ArrayList<InetSocketAddress> list = new ArrayList<InetSocketAddress>(
- size);
- while (size > 0) {
- try {
- list.add(new InetSocketAddress(InetAddress.getByAddress(new byte[]{-64, 0, 2, size}), 1234 + size));
- } catch (UnknownHostException e) {
- LOG.error("Exception while resolving address", e);
- fail("Failed to resolve address");
- }
- --size;
- }
- return new StaticHostProvider(list);
- }
-}
http://git-wip-us.apache.org/repos/asf/zookeeper/blob/c0aa3b3f/src/java/test/org/apache/zookeeper/test/SyncCallTest.java
----------------------------------------------------------------------
diff --git a/src/java/test/org/apache/zookeeper/test/SyncCallTest.java b/src/java/test/org/apache/zookeeper/test/SyncCallTest.java
deleted file mode 100644
index 4fb006a..0000000
--- a/src/java/test/org/apache/zookeeper/test/SyncCallTest.java
+++ /dev/null
@@ -1,108 +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.test;
-
-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.StringCallback;
-import org.apache.zookeeper.AsyncCallback.VoidCallback;
-import org.apache.zookeeper.ZooDefs.Ids;
-import org.apache.zookeeper.data.Stat;
-import org.junit.Assert;
-import org.junit.Test;
-
-public class SyncCallTest extends ClientBase
- implements ChildrenCallback, Children2Callback, StringCallback, VoidCallback
-{
- private CountDownLatch opsCount;
-
- List<Integer> results = new LinkedList<Integer>();
- Integer limit = 100 + 1 + 100 + 100;
-
- @Test
- public void testSync() throws Exception {
- try {
- LOG.info("Starting ZK:" + (new Date()).toString());
- opsCount = new CountDownLatch(limit);
- ZooKeeper zk = createClient();
-
- LOG.info("Beginning test:" + (new Date()).toString());
- for(int i = 0; i < 100; i++)
- zk.create("/test" + i, new byte[0], Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT, this, results);
- zk.sync("/test", this, results);
- 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);
- 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));
- }
-
- } 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);
- opsCount.countDown();
- }
-
- @SuppressWarnings("unchecked")
- 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){
- ((List<Integer>) ctx).add(rc);
- opsCount.countDown();
-
- }
-
- @SuppressWarnings("unchecked")
- public void processResult(int rc, String path, Object ctx){
- ((List<Integer>) ctx).add(rc);
- opsCount.countDown();
-
- }
-}
http://git-wip-us.apache.org/repos/asf/zookeeper/blob/c0aa3b3f/src/java/test/org/apache/zookeeper/test/TestHammer.java
----------------------------------------------------------------------
diff --git a/src/java/test/org/apache/zookeeper/test/TestHammer.java b/src/java/test/org/apache/zookeeper/test/TestHammer.java
deleted file mode 100644
index a73d6df..0000000
--- a/src/java/test/org/apache/zookeeper/test/TestHammer.java
+++ /dev/null
@@ -1,63 +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.test;
-
-import java.io.IOException;
-
-import org.apache.zookeeper.CreateMode;
-import org.apache.zookeeper.ZooKeeper;
-import org.apache.zookeeper.AsyncCallback.VoidCallback;
-import org.apache.zookeeper.ZooDefs.Ids;
-import org.apache.zookeeper.common.Time;
-
-public class TestHammer implements VoidCallback {
-
- /**
- * @param args
- */
- static int REPS = 50000;
- public static void main(String[] args) {
- long startTime = Time.currentElapsedTime();
- ZooKeeper zk = null;
- try {
- zk = new ZooKeeper(args[0], 10000, null);
- } catch (IOException e1) {
- // TODO Auto-generated catch block
- 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();
- }
- }
- System.out.println("creates/sec=" + (REPS*1000/(Time.currentElapsedTime()-startTime)));
- }
-
- public void processResult(int rc, String path, Object ctx) {
- // TODO Auto-generated method stub
-
- }
-
-}
http://git-wip-us.apache.org/repos/asf/zookeeper/blob/c0aa3b3f/src/java/test/org/apache/zookeeper/test/TestUtils.java
----------------------------------------------------------------------
diff --git a/src/java/test/org/apache/zookeeper/test/TestUtils.java b/src/java/test/org/apache/zookeeper/test/TestUtils.java
deleted file mode 100644
index fa08b82..0000000
--- a/src/java/test/org/apache/zookeeper/test/TestUtils.java
+++ /dev/null
@@ -1,60 +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.test;
-
-import java.io.File;
-
-import org.junit.Assert;
-
-/**
- * This class contains test utility methods
- */
-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) {
- if (file != null) {
- if (file.isDirectory()) {
- File[] files = file.listFiles();
- int size = files.length;
- 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");
- }
- }
- }
- return file.delete();
- }
- return true;
- }
-
- public static boolean deleteFileRecursively(File file) {
- return deleteFileRecursively(file, false);
- }
-}
http://git-wip-us.apache.org/repos/asf/zookeeper/blob/c0aa3b3f/src/java/test/org/apache/zookeeper/test/TruncateTest.java
----------------------------------------------------------------------
diff --git a/src/java/test/org/apache/zookeeper/test/TruncateTest.java b/src/java/test/org/apache/zookeeper/test/TruncateTest.java
deleted file mode 100644
index 66ff63d..0000000
--- a/src/java/test/org/apache/zookeeper/test/TruncateTest.java
+++ /dev/null
@@ -1,256 +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.test;
-
-import java.io.File;
-import java.io.IOException;
-import java.net.InetSocketAddress;
-import java.util.HashMap;
-
-import junit.framework.Assert;
-
-import org.apache.jute.Record;
-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.ZooDefs;
-import org.apache.zookeeper.ZooKeeper;
-import org.apache.zookeeper.data.Stat;
-import org.apache.zookeeper.server.Request;
-import org.apache.zookeeper.server.ServerCnxnFactory;
-import org.apache.zookeeper.server.ZKDatabase;
-import org.apache.zookeeper.server.ZooKeeperServer;
-import org.apache.zookeeper.server.persistence.FileTxnLog;
-import org.apache.zookeeper.server.persistence.FileTxnSnapLog;
-import org.apache.zookeeper.server.persistence.TxnLog.TxnIterator;
-import org.apache.zookeeper.server.quorum.QuorumPeer;
-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.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);
- File dataDir1, dataDir2, dataDir3;
- final int baseHostPort = PortAssignment.unique();
-
- @Before
- public void setUp() throws IOException {
- dataDir1 = ClientBase.createTmpDir();
- dataDir2 = ClientBase.createTmpDir();
- dataDir3 = ClientBase.createTmpDir();
- }
-
- @After
- public void tearDown() {
- ClientBase.recursiveDelete(dataDir1);
- ClientBase.recursiveDelete(dataDir2);
- ClientBase.recursiveDelete(dataDir3);
- }
-
- volatile boolean connected;
- Watcher nullWatcher = new Watcher() {
- @Override
- public void process(WatchedEvent event) {
- connected = event.getState() == Watcher.Event.KeeperState.SyncConnected;
- }
- };
-
- @Test
- public void testTruncationStreamReset() throws Exception {
- File tmpdir = ClientBase.createTmpDir();
- FileTxnSnapLog snaplog = new FileTxnSnapLog(tmpdir, tmpdir);
- ZKDatabase zkdb = new ZKDatabase(snaplog);
-
- for (int i = 1; i <= 100; i++) {
- append(zkdb, i);
- }
-
- zkdb.truncateLog(1);
-
- append(zkdb, 200);
-
- zkdb.close();
-
- // verify that the truncation and subsequent append were processed
- // correctly
- FileTxnLog txnlog = new FileTxnLog(new File(tmpdir, "version-2"));
- TxnIterator iter = txnlog.read(1);
-
- TxnHeader hdr = iter.getHeader();
- Record txn = iter.getTxn();
- Assert.assertEquals(1, hdr.getZxid());
- Assert.assertTrue(txn instanceof SetDataTxn);
-
- iter.next();
-
- hdr = iter.getHeader();
- txn = iter.getTxn();
- Assert.assertEquals(200, hdr.getZxid());
- Assert.assertTrue(txn instanceof SetDataTxn);
- iter.close();
- ClientBase.recursiveDelete(tmpdir);
- }
-
- private void append(ZKDatabase zkdb, int i) throws IOException {
- TxnHeader hdr = new TxnHeader(1, 1, i, 1, ZooDefs.OpCode.setData);
- Record txn = new SetDataTxn("/foo" + i, new byte[0], 1);
- Request req = new Request(null, 0, 0, 0, null, null);
- req.hdr = hdr;
- req.txn = txn;
-
- zkdb.append(req);
- zkdb.commit();
- }
-
-
- @Test
- public void testTruncationNullLog() throws Exception {
- File tmpdir = ClientBase.createTmpDir();
- FileTxnSnapLog snaplog = new FileTxnSnapLog(tmpdir, tmpdir);
- ZKDatabase zkdb = new ZKDatabase(snaplog);
-
- for (int i = 1; i <= 100; i++) {
- append(zkdb, i);
- }
- zkdb.close();
- File[] logs = snaplog.getDataDir().listFiles();
- 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());
- }
- try {
- zkdb.truncateLog(1);
- Assert.assertTrue("Should not get here", false);
- }
- catch(IOException e) {
- Assert.assertTrue("Should have received an IOException", true);
- }
- catch(NullPointerException npe) {
- Assert.fail("This should not throw NPE!");
- }
-
- ClientBase.recursiveDelete(tmpdir);
- }
-
- @Test
- public void testTruncate() throws IOException, InterruptedException, KeeperException {
- // Prime the server that is going to come in late with 50 txns
- String hostPort = "127.0.0.1:" + baseHostPort;
- int maxCnxns = 100;
- ServerCnxnFactory factory = ClientBase.createNewServerInstance(null,
- hostPort, maxCnxns);
- ClientBase.startServerInstance(dataDir1, factory, hostPort);
- ClientBase.shutdownServerInstance(factory, hostPort);
-
- // standalone starts with 0 epoch while quorum starts with 1
- File origfile = new File(new File(dataDir1, "version-2"), "snapshot.0");
- File newfile = new File(new File(dataDir1, "version-2"), "snapshot.100000000");
- origfile.renameTo(newfile);
-
- factory = ClientBase.createNewServerInstance(null, hostPort, maxCnxns);
- ClientBase.startServerInstance(dataDir1, factory, hostPort);
-
- ZooKeeper zk = new ZooKeeper(hostPort, 15000, nullWatcher);
- 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 = ClientBase.getServer(factory);
-
- zkDb = zs.getZKDatabase();
- }
- factory.shutdown();
- try {
- zkDb.close();
- } catch (IOException ie) {
- LOG.warn("Error closing logs ", ie);
- }
- int tickTime = 2000;
- int initLimit = 3;
- int syncLimit = 3;
- int port1 = baseHostPort+1;
- int port2 = baseHostPort+2;
- int port3 = baseHostPort+3;
-
- // Start up two of the quorum and add 10 txns
- HashMap<Long,QuorumServer> peers = new HashMap<Long,QuorumServer>();
- peers.put(Long.valueOf(1), new QuorumServer(1, "127.0.0.1", port1 + 1000, 0, null));
- peers.put(Long.valueOf(2), new QuorumServer(2, "127.0.0.1", port2 + 1000, 0, null));
- peers.put(Long.valueOf(3), new QuorumServer(3, "127.0.0.1", port3 + 1000, 0, null));
-
- QuorumPeer s2 = new QuorumPeer(peers, dataDir2, dataDir2, port2, 0, 2, tickTime, initLimit, syncLimit);
- s2.start();
- QuorumPeer s3 = new QuorumPeer(peers, dataDir3, dataDir3, port3, 0, 3, tickTime, initLimit, syncLimit);
- s3.start();
- connected = false;
- zk = new ZooKeeper("127.0.0.1:" + port2, 15000, nullWatcher);
- while(!connected) {
- Thread.sleep(1000);
- }
- for(int i = 0; i < 10; i++) {
- zk.create("/" + i, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
- }
- zk.close();
-
- final ZooKeeper zk2 = new ZooKeeper("127.0.0.1:" + port2, 15000, nullWatcher);
- zk2.getData("/9", false, new Stat());
- try {
- zk2.getData("/10", false, new Stat());
- Assert.fail("Should have gotten an error");
- } catch(KeeperException.NoNodeException e) {
- // this is what we want
- }
- QuorumPeer s1 = new QuorumPeer(peers, dataDir1, dataDir1, port1, 0, 1, tickTime, initLimit, syncLimit);
- s1.start();
-
- connected = false;
- ZooKeeper zk1 = new ZooKeeper("127.0.0.1:" + port1, 15000, nullWatcher);
- while(!connected) {
- Thread.sleep(1000);
- }
- zk1.getData("/9", false, new Stat());
- try {
- // /10 wont work because the session expiration
- // will match the zxid for /10 and so we wont
- // actually truncate the zxid for /10 creation
- // due to an artifact of switching the xid of the standalone
- // /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) {
- // this is what we want
- }
- zk1.close();
- QuorumBase.shutdown(s1);
- QuorumBase.shutdown(s2);
- QuorumBase.shutdown(s3);
- }
-}
http://git-wip-us.apache.org/repos/asf/zookeeper/blob/c0aa3b3f/src/java/test/org/apache/zookeeper/test/UpgradeTest.java
----------------------------------------------------------------------
diff --git a/src/java/test/org/apache/zookeeper/test/UpgradeTest.java b/src/java/test/org/apache/zookeeper/test/UpgradeTest.java
deleted file mode 100644
index b8db0da..0000000
--- a/src/java/test/org/apache/zookeeper/test/UpgradeTest.java
+++ /dev/null
@@ -1,105 +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.test;
-
-import static org.apache.zookeeper.test.ClientBase.CONNECTION_TIMEOUT;
-
-import java.io.File;
-import java.util.Collections;
-import java.util.List;
-import java.util.concurrent.CountDownLatch;
-
-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.ZooDefs.Ids;
-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.apache.zookeeper.server.upgrade.UpgradeMain;
-import org.junit.Assert;
-import org.junit.Test;
-
-public class UpgradeTest extends ZKTestCase implements Watcher {
- private final static Logger LOG = LoggerFactory.getLogger(UpgradeTest.class);
-
- private static String HOSTPORT = "127.0.0.1:" + PortAssignment.unique();
- private static final File testData = new File(
- System.getProperty("test.data.dir", "build/test/data"));
- private CountDownLatch startSignal;
-
- /**
- * test the upgrade
- * @throws Exception
- */
- @Test
- public void testUpgrade() throws Exception {
- File upgradeDir = new File(testData, "upgrade");
- UpgradeMain upgrade = new UpgradeMain(upgradeDir, upgradeDir);
- upgrade.runUpgrade();
- ZooKeeperServer zks = new ZooKeeperServer(upgradeDir, upgradeDir, 3000);
- SyncRequestProcessor.setSnapCount(1000);
- final int PORT = Integer.parseInt(HOSTPORT.split(":")[1]);
- 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));
- ZooKeeper zk = new ZooKeeper(HOSTPORT, CONNECTION_TIMEOUT, this);
- Stat stat = zk.exists("/", false);
- List<String> children = zk.getChildren("/", false);
- Collections.sort(children);
- for (int i = 0; i < 10; i++) {
- Assert.assertTrue("data tree sanity check",
- ("test-" + i).equals(children.get(i)));
- }
- //try creating one node
- zk.create("/upgrade", "upgrade".getBytes(), Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
- // check if its there
- if (zk.exists("/upgrade", false) == null) {
- Assert.assertTrue(false);
- }
-
- zk.close();
-
- // bring down the server
- f.shutdown();
- Assert.assertTrue("waiting for server down",
- ClientBase.waitForServerDown(HOSTPORT,
- ClientBase.CONNECTION_TIMEOUT));
-
- }
-
- public void process(WatchedEvent event) {
- LOG.info("Event:" + event.getState() + " " + event.getType() + " " + event.getPath());
- if (event.getState() == KeeperState.SyncConnected
- && startSignal != null && startSignal.getCount() > 0)
- {
- startSignal.countDown();
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/zookeeper/blob/c0aa3b3f/src/java/test/org/apache/zookeeper/test/WatchEventWhenAutoReset.java
----------------------------------------------------------------------
diff --git a/src/java/test/org/apache/zookeeper/test/WatchEventWhenAutoReset.java b/src/java/test/org/apache/zookeeper/test/WatchEventWhenAutoReset.java
deleted file mode 100644
index eed02c5..0000000
--- a/src/java/test/org/apache/zookeeper/test/WatchEventWhenAutoReset.java
+++ /dev/null
@@ -1,212 +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.test;
-
-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.ZooDefs;
-import org.apache.zookeeper.ZooKeeper;
-import org.apache.zookeeper.Watcher.Event.EventType;
-import org.apache.zookeeper.test.ClientBase.CountdownWatcher;
-import org.junit.Assert;
-import org.junit.Test;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import junit.framework.TestCase;
-
-public class WatchEventWhenAutoReset extends TestCase {
- protected static final Logger LOG = LoggerFactory
- .getLogger(WatchEventWhenAutoReset.class);
-
- // waiting time for expected condition
- private static final int TIMEOUT = 30000;
-
- static public class EventsWatcher extends CountdownWatcher {
- private LinkedBlockingQueue<WatchedEvent> dataEvents = new LinkedBlockingQueue<WatchedEvent>();
-
- @Override
- public void process(WatchedEvent event) {
- super.process(event);
- try {
- if (event.getType() != Event.EventType.None) {
- dataEvents.put(event);
- }
- } catch (InterruptedException e) {
- LOG.warn("ignoring interrupt during EventsWatcher process");
- }
- }
-
- 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());
- } catch (InterruptedException e) {
- LOG.warn("ignoring interrupt during EventsWatcher assertEvent");
- }
- }
- }
-
- 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 {
- watcher.waitForConnected(TIMEOUT);
- } catch (InterruptedException e) {
- // ignoring the interrupt
- } catch (TimeoutException e) {
- fail("can not connect to " + hostPort);
- }
- return zk;
- }
-
- private ZooKeeper createClient(QuorumUtil qu, int id) throws IOException {
- return createClient(qu, id, new EventsWatcher());
- }
-
- @Test
- public void testNodeDataChanged() throws Exception {
- QuorumUtil qu = new QuorumUtil(1);
- qu.startAll();
-
- EventsWatcher watcher = new EventsWatcher();
- ZooKeeper zk1 = createClient(qu, 1, watcher);
- ZooKeeper zk2 = createClient(qu, 2);
-
- String path = "/test-changed";
-
- 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);
- zk2.create(path, new byte[2], ZooDefs.Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
- qu.start(1);
- watcher.waitForConnected(TIMEOUT);
- watcher.assertEvent(TIMEOUT, EventType.NodeDataChanged);
-
- zk1.exists(path, watcher);
- qu.shutdown(1);
- zk2.delete(path, -1);
- zk2.create(path, new byte[2], ZooDefs.Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
- qu.start(1);
- watcher.waitForConnected(TIMEOUT * 1000L);
- watcher.assertEvent(TIMEOUT, EventType.NodeDataChanged);
-
- qu.shutdownAll();
- }
-
- @Test
- public void testNodeCreated() throws Exception {
- QuorumUtil qu = new QuorumUtil(1);
- qu.startAll();
-
- EventsWatcher watcher = new EventsWatcher();
- ZooKeeper zk1 = createClient(qu, 1, watcher);
- ZooKeeper zk2 = createClient(qu, 2);
-
- String path = "/test1-created";
-
- zk1.exists(path, watcher);
- qu.shutdown(1);
- 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);
-
- qu.shutdownAll();
- }
-
- @Test
- public void testNodeDeleted() throws Exception {
- QuorumUtil qu = new QuorumUtil(1);
- qu.startAll();
-
- EventsWatcher watcher = new EventsWatcher();
- ZooKeeper zk1 = createClient(qu, 1, watcher);
- ZooKeeper zk2 = createClient(qu, 2);
-
- String path = "/test-deleted";
-
- 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);
- qu.start(1);
- watcher.waitForConnected(TIMEOUT * 1000L);
- watcher.assertEvent(TIMEOUT, EventType.NodeDeleted);
-
- zk1.create(path, new byte[1], ZooDefs.Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
- zk1.exists(path, watcher);
- qu.shutdown(1);
- zk2.delete(path, -1);
- qu.start(1);
- watcher.waitForConnected(TIMEOUT * 1000L);
- watcher.assertEvent(TIMEOUT, EventType.NodeDeleted);
-
- zk1.create(path, new byte[1], ZooDefs.Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
- zk1.getChildren(path, watcher);
- qu.shutdown(1);
- zk2.delete(path, -1);
- qu.start(1);
- watcher.waitForConnected(TIMEOUT * 1000L);
- watcher.assertEvent(TIMEOUT, EventType.NodeDeleted);
-
- qu.shutdownAll();
- }
-
- @Test
- public void testNodeChildrenChanged() throws Exception {
- QuorumUtil qu = new QuorumUtil(1);
- qu.startAll();
-
- EventsWatcher watcher = new EventsWatcher();
- ZooKeeper zk1 = createClient(qu, 1, watcher);
- ZooKeeper zk2 = createClient(qu, 2);
-
- String path = "/test-children-changed";
-
- 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);
- qu.start(1);
- watcher.waitForConnected(TIMEOUT * 1000L);
- watcher.assertEvent(TIMEOUT, EventType.NodeChildrenChanged);
-
- qu.shutdownAll();
- }
-}
-
http://git-wip-us.apache.org/repos/asf/zookeeper/blob/c0aa3b3f/src/java/test/org/apache/zookeeper/test/WatchedEventTest.java
----------------------------------------------------------------------
diff --git a/src/java/test/org/apache/zookeeper/test/WatchedEventTest.java b/src/java/test/org/apache/zookeeper/test/WatchedEventTest.java
deleted file mode 100644
index 0eaea67..0000000
--- a/src/java/test/org/apache/zookeeper/test/WatchedEventTest.java
+++ /dev/null
@@ -1,95 +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.test;
-
-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.proto.WatcherEvent;
-import org.junit.Assert;
-import org.junit.Test;
-
-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.
-
- EnumSet<EventType> allTypes = EnumSet.allOf(EventType.class);
- 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());
- }
-
- }
- }
-
- @Test
- public void testCreatingWatchedEventFromWrapper() {
- // 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;
-
- 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());
- }
- }
- }
-
- @Test
- public void testCreatingWatchedEventFromInvalidWrapper() {
- // Make sure we can't convert from an invalid wrapper
-
- try {
- WatcherEvent wep = new WatcherEvent(-2342, -252352, "foo");
- WatchedEvent we = new WatchedEvent(wep);
- Assert.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();
-
- Assert.assertEquals(EventType.NodeCreated.getIntValue(), wew.getType());
- Assert.assertEquals(KeeperState.Expired.getIntValue(), wew.getState());
- Assert.assertEquals("blah", wew.getPath());
- }
-}
http://git-wip-us.apache.org/repos/asf/zookeeper/blob/c0aa3b3f/src/java/test/org/apache/zookeeper/test/WatcherFuncTest.java
----------------------------------------------------------------------
diff --git a/src/java/test/org/apache/zookeeper/test/WatcherFuncTest.java b/src/java/test/org/apache/zookeeper/test/WatcherFuncTest.java
deleted file mode 100644
index a6c62e4..0000000
--- a/src/java/test/org/apache/zookeeper/test/WatcherFuncTest.java
+++ /dev/null
@@ -1,478 +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.test;
-
-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.junit.Test;
-
-public class WatcherFuncTest extends ClientBase {
- private static class SimpleWatcher implements Watcher {
- private LinkedBlockingQueue<WatchedEvent> events =
- new LinkedBlockingQueue<WatchedEvent>();
- private CountDownLatch latch;
-
- public SimpleWatcher(CountDownLatch latch) {
- this.latch = latch;
- }
-
- public void process(WatchedEvent event) {
- if (event.getState() == KeeperState.SyncConnected) {
- if (latch != null) {
- latch.countDown();
- }
- }
-
- if (event.getType() == EventType.None) {
- return;
- }
- try {
- events.put(event);
- } catch (InterruptedException e) {
- Assert.assertTrue("interruption unexpected", false);
- }
- }
- 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());
- count++;
- }
- Assert.assertEquals(expected.size(), count);
- events.clear();
- }
- }
- private SimpleWatcher client_dwatch;
- private volatile CountDownLatch client_latch;
- private ZooKeeper client;
- private SimpleWatcher lsnr_dwatch;
- private volatile CountDownLatch lsnr_latch;
- private ZooKeeper lsnr;
-
- private List<EventType> expected;
-
- @Override
- public void setUp() throws Exception {
- super.setUp();
-
- client_latch = new CountDownLatch(1);
- client_dwatch = new SimpleWatcher(client_latch);
- client = createClient(client_dwatch, client_latch);
-
- lsnr_latch = new CountDownLatch(1);
- lsnr_dwatch = new SimpleWatcher(lsnr_latch);
- lsnr = createClient(lsnr_dwatch, lsnr_latch);
-
- expected = new ArrayList<EventType>();
- }
-
- @Override
- public void tearDown() throws Exception {
- client.close();
- lsnr.close();
- super.tearDown();
- }
-
- 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");
- }
- return zk;
- }
-
- private void verify() throws InterruptedException {
- lsnr_dwatch.verify(expected);
- expected.clear();
- }
-
- @Test
- public void testExistsSync()
- throws IOException, InterruptedException, KeeperException
- {
- Assert.assertNull(lsnr.exists("/foo", true));
- Assert.assertNull(lsnr.exists("/foo/bar", true));
-
- client.create("/foo", "parent".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
- expected.add(EventType.NodeCreated);
- client.create("/foo/bar", "child".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
- expected.add(EventType.NodeCreated);
-
- verify();
-
- Assert.assertNotNull(lsnr.exists("/foo", true));
- Assert.assertNotNull(lsnr.exists("/foo/bar", true));
-
- try {
- Assert.assertNull(lsnr.exists("/car", true));
- client.setData("/car", "missing".getBytes(), -1);
- Assert.fail();
- } catch (KeeperException e) {
- Assert.assertEquals(KeeperException.Code.NONODE, e.code());
- Assert.assertEquals("/car", e.getPath());
- }
-
- try {
- Assert.assertNull(lsnr.exists("/foo/car", true));
- client.setData("/foo/car", "missing".getBytes(), -1);
- Assert.fail();
- } catch (KeeperException e) {
- Assert.assertEquals(KeeperException.Code.NONODE, e.code());
- Assert.assertEquals("/foo/car", e.getPath());
- }
-
- client.setData("/foo", "parent".getBytes(), -1);
- expected.add(EventType.NodeDataChanged);
- client.setData("/foo/bar", "child".getBytes(), -1);
- expected.add(EventType.NodeDataChanged);
-
- verify();
-
- Assert.assertNotNull(lsnr.exists("/foo", true));
- Assert.assertNotNull(lsnr.exists("/foo/bar", true));
-
- client.delete("/foo/bar", -1);
- expected.add(EventType.NodeDeleted);
- client.delete("/foo", -1);
- expected.add(EventType.NodeDeleted);
-
- verify();
- }
-
- @Test
- public void testGetDataSync()
- throws IOException, InterruptedException, KeeperException
- {
- try {
- lsnr.getData("/foo", true, null);
- Assert.fail();
- } catch (KeeperException e) {
- Assert.assertEquals(KeeperException.Code.NONODE, e.code());
- Assert.assertEquals("/foo", e.getPath());
- }
- try {
- lsnr.getData("/foo/bar", true, null);
- Assert.fail();
- } catch (KeeperException e) {
- Assert.assertEquals(KeeperException.Code.NONODE, e.code());
- Assert.assertEquals("/foo/bar", e.getPath());
- }
-
- client.create("/foo", "parent".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
- Assert.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));
-
- client.setData("/foo", "parent".getBytes(), -1);
- expected.add(EventType.NodeDataChanged);
- client.setData("/foo/bar", "child".getBytes(), -1);
- expected.add(EventType.NodeDataChanged);
-
- verify();
-
- Assert.assertNotNull(lsnr.getData("/foo", true, null));
- Assert.assertNotNull(lsnr.getData("/foo/bar", true, null));
-
- client.delete("/foo/bar", -1);
- expected.add(EventType.NodeDeleted);
- client.delete("/foo", -1);
- expected.add(EventType.NodeDeleted);
-
- verify();
- }
-
- @Test
- public void testGetChildrenSync()
- throws IOException, InterruptedException, KeeperException
- {
- try {
- lsnr.getChildren("/foo", true);
- Assert.fail();
- } catch (KeeperException e) {
- Assert.assertEquals(KeeperException.Code.NONODE, e.code());
- Assert.assertEquals("/foo", e.getPath());
- }
- try {
- lsnr.getChildren("/foo/bar", true);
- Assert.fail();
- } catch (KeeperException e) {
- Assert.assertEquals(KeeperException.Code.NONODE, e.code());
- Assert.assertEquals("/foo/bar", e.getPath());
- }
-
- client.create("/foo", "parent".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
- Assert.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));
-
-
- client.setData("/foo", "parent".getBytes(), -1);
- client.setData("/foo/bar", "child".getBytes(), -1);
-
-
- Assert.assertNotNull(lsnr.exists("/foo", true));
-
- Assert.assertNotNull(lsnr.getChildren("/foo", true));
- Assert.assertNotNull(lsnr.getChildren("/foo/bar", true));
-
- client.delete("/foo/bar", -1);
- expected.add(EventType.NodeDeleted); // /foo/bar childwatch
- expected.add(EventType.NodeChildrenChanged); // /foo
- client.delete("/foo", -1);
- expected.add(EventType.NodeDeleted);
-
- verify();
- }
-
- @Test
- public void testExistsSyncWObj()
- throws IOException, InterruptedException, KeeperException
- {
- SimpleWatcher w1 = new SimpleWatcher(null);
- SimpleWatcher w2 = new SimpleWatcher(null);
- SimpleWatcher w3 = new SimpleWatcher(null);
- SimpleWatcher w4 = new SimpleWatcher(null);
-
- List<EventType> e2 = new ArrayList<EventType>();
-
- Assert.assertNull(lsnr.exists("/foo", true));
- Assert.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));
-
- client.create("/foo", "parent".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
- expected.add(EventType.NodeCreated);
- client.create("/foo/bar", "child".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
- e2.add(EventType.NodeCreated);
-
- lsnr_dwatch.verify(expected);
- w1.verify(expected);
- w2.verify(e2);
- w3.verify(e2);
- w4.verify(e2);
- expected.clear();
- e2.clear();
-
- // default not registered
- Assert.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));
-
- client.setData("/foo", "parent".getBytes(), -1);
- expected.add(EventType.NodeDataChanged);
- client.setData("/foo/bar", "child".getBytes(), -1);
- e2.add(EventType.NodeDataChanged);
-
- lsnr_dwatch.verify(new ArrayList<EventType>()); // not reg so should = 0
- w1.verify(expected);
- w2.verify(e2);
- w3.verify(e2);
- w4.verify(e2);
- expected.clear();
- e2.clear();
-
- Assert.assertNotNull(lsnr.exists("/foo", true));
- Assert.assertNotNull(lsnr.exists("/foo", w1));
- Assert.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));
-
- client.delete("/foo/bar", -1);
- expected.add(EventType.NodeDeleted);
- client.delete("/foo", -1);
- e2.add(EventType.NodeDeleted);
-
- lsnr_dwatch.verify(expected);
- w1.verify(expected);
- w2.verify(e2);
- w3.verify(e2);
- w4.verify(e2);
- expected.clear();
- e2.clear();
-
- }
-
- @Test
- public void testGetDataSyncWObj()
- throws IOException, InterruptedException, KeeperException
- {
- SimpleWatcher w1 = new SimpleWatcher(null);
- SimpleWatcher w2 = new SimpleWatcher(null);
- SimpleWatcher w3 = new SimpleWatcher(null);
- SimpleWatcher w4 = new SimpleWatcher(null);
-
- List<EventType> e2 = new ArrayList<EventType>();
-
- try {
- lsnr.getData("/foo", w1, null);
- Assert.fail();
- } catch (KeeperException e) {
- Assert.assertEquals(KeeperException.Code.NONODE, e.code());
- Assert.assertEquals("/foo", e.getPath());
- }
- try {
- lsnr.getData("/foo/bar", w2, null);
- Assert.fail();
- } catch (KeeperException e) {
- Assert.assertEquals(KeeperException.Code.NONODE, e.code());
- Assert.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));
- 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));
-
- client.setData("/foo", "parent".getBytes(), -1);
- expected.add(EventType.NodeDataChanged);
- client.setData("/foo/bar", "child".getBytes(), -1);
- e2.add(EventType.NodeDataChanged);
-
- lsnr_dwatch.verify(expected);
- w1.verify(expected);
- w2.verify(e2);
- w3.verify(e2);
- w4.verify(e2);
- 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));
-
- client.delete("/foo/bar", -1);
- expected.add(EventType.NodeDeleted);
- client.delete("/foo", -1);
- e2.add(EventType.NodeDeleted);
-
- lsnr_dwatch.verify(expected);
- w1.verify(expected);
- w2.verify(e2);
- w3.verify(e2);
- w4.verify(e2);
- expected.clear();
- e2.clear();
- }
-
- @Test
- public void testGetChildrenSyncWObj()
- throws IOException, InterruptedException, KeeperException
- {
- SimpleWatcher w1 = new SimpleWatcher(null);
- SimpleWatcher w2 = new SimpleWatcher(null);
- SimpleWatcher w3 = new SimpleWatcher(null);
- SimpleWatcher w4 = new SimpleWatcher(null);
-
- List<EventType> e2 = new ArrayList<EventType>();
-
- try {
- lsnr.getChildren("/foo", true);
- Assert.fail();
- } catch (KeeperException e) {
- Assert.assertEquals(KeeperException.Code.NONODE, e.code());
- Assert.assertEquals("/foo", e.getPath());
- }
- try {
- lsnr.getChildren("/foo/bar", true);
- Assert.fail();
- } catch (KeeperException e) {
- Assert.assertEquals(KeeperException.Code.NONODE, e.code());
- Assert.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));
-
- 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));
-
-
- client.setData("/foo", "parent".getBytes(), -1);
- client.setData("/foo/bar", "child".getBytes(), -1);
-
-
- 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));
-
- client.delete("/foo/bar", -1);
- e2.add(EventType.NodeDeleted); // /foo/bar childwatch
- expected.add(EventType.NodeChildrenChanged); // /foo
- client.delete("/foo", -1);
- expected.add(EventType.NodeDeleted);
-
- lsnr_dwatch.verify(expected);
- w1.verify(expected);
- w2.verify(e2);
- w3.verify(e2);
- w4.verify(e2);
- expected.clear();
- e2.clear();
- }
-}
http://git-wip-us.apache.org/repos/asf/zookeeper/blob/c0aa3b3f/src/java/test/org/apache/zookeeper/test/WatcherTest.java
----------------------------------------------------------------------
diff --git a/src/java/test/org/apache/zookeeper/test/WatcherTest.java b/src/java/test/org/apache/zookeeper/test/WatcherTest.java
deleted file mode 100644
index 1c06690..0000000
--- a/src/java/test/org/apache/zookeeper/test/WatcherTest.java
+++ /dev/null
@@ -1,408 +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.test;
-
-import java.io.IOException;
-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.ClientCnxn;
-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.ZooKeeper;
-import org.apache.zookeeper.AsyncCallback.StatCallback;
-import org.apache.zookeeper.AsyncCallback.VoidCallback;
-import org.apache.zookeeper.Watcher.Event;
-import org.apache.zookeeper.Watcher.Event.EventType;
-import org.apache.zookeeper.ZooDefs.Ids;
-import org.apache.zookeeper.data.Stat;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
-
-public class WatcherTest extends ClientBase {
- protected static final Logger LOG = LoggerFactory.getLogger(WatcherTest.class);
-
- private long timeOfLastWatcherInvocation;
-
- private final class MyStatCallback implements StatCallback {
- int rc;
- public void processResult(int rc, String path, Object ctx, Stat stat) {
- ((int[])ctx)[0]++;
- this.rc = rc;
- }
- }
-
- private class MyWatcher extends CountdownWatcher {
- LinkedBlockingQueue<WatchedEvent> events =
- new LinkedBlockingQueue<WatchedEvent>();
-
- public void process(WatchedEvent event) {
- super.process(event);
- if (event.getType() != Event.EventType.None) {
- timeOfLastWatcherInvocation = System.currentTimeMillis();
- try {
- events.put(event);
- } catch (InterruptedException e) {
- LOG.warn("ignoring interrupt during event.put");
- }
- }
- }
- }
-
- @Before
- public void setUp() throws Exception {
- super.setUp();
- // Reset to default value since some test cases set this to true.
- // Needed for JDK7 since unit test can run is random order
- ClientCnxn.setDisableAutoResetWatch(false);
- }
-
- /**
- * Verify that we get all of the events we expect to get. This particular
- * case verifies that we see all of the data events on a particular node.
- * There was a bug (ZOOKEEPER-137) that resulted in events being dropped
- * in some cases (timing).
- *
- * @throws IOException
- * @throws InterruptedException
- * @throws KeeperException
- */
- @Test
- 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) {
- // don't do anything
- }
- };
- VoidCallback vcb = new VoidCallback() {
- public void processResult(int rc, String path, Object ctx) {
- // don't do anything
- }
- };
-
- 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);
- names[i] = name;
-
- Stat stat = new Stat();
- zk.getData(name, watcher, stat);
- zk.setData(name, "new".getBytes(), stat.getVersion(), scb, null);
- stat = zk.exists(name, watcher);
- zk.delete(name, stat.getVersion(), vcb, null);
- }
-
- 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());
- 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());
- }
- } finally {
- if (zk != null) {
- zk.close();
- }
- }
- }
-
- @Test
- public void testWatcherCount()
- throws IOException, InterruptedException, KeeperException {
- ZooKeeper zk1 = null, zk2 = null;
- try {
- MyWatcher w1 = new MyWatcher();
- zk1 = createClient(w1, hostPort);
-
- MyWatcher w2 = new MyWatcher();
- zk2 = createClient(w2, hostPort);
-
- Stat stat = new Stat();
- zk1.create("/watch-count-test", "value".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
- zk1.create("/watch-count-test-2", "value".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
-
- zk1.getData("/watch-count-test", w1, stat);
- zk1.getData("/watch-count-test-2", w1, stat);
- zk2.getData("/watch-count-test", w2, stat);
-
- Assert.assertEquals(ClientBase.getServer(serverFactory)
- .getZKDatabase().getDataTree().getWatchCount(), 3);
-
- } finally {
- if(zk1 != null) {
- zk1.close();
- }
- if(zk2 != null) {
- zk2.close();
- }
- }
-
- }
-
- final static int COUNT = 100;
- /**
- * This test checks that watches for pending requests do not get triggered,
- * but watches set by previous requests do.
- *
- * @throws Exception
- */
- @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();
- }
-
- /**
- * Wait until no watcher has been fired in the last second to ensure that all watches
- * that are waiting to be fired have been fired
- * @throws Exception
- */
- private void waitForAllWatchers() throws Exception {
- timeOfLastWatcherInvocation = System.currentTimeMillis();
- while (System.currentTimeMillis() - timeOfLastWatcherInvocation < 1000) {
- Thread.sleep(1000);
- }
- }
-
- final int TIMEOUT = 5000;
-
- @Test
- public void testWatcherAutoResetWithGlobal() throws Exception {
- ZooKeeper zk = null;
- MyWatcher watcher = new MyWatcher();
- zk = createClient(watcher, hostPort, TIMEOUT);
- testWatcherAutoReset(zk, watcher, watcher);
- zk.close();
- }
-
- @Test
- public void testWatcherAutoResetWithLocal() throws Exception {
- ZooKeeper zk = null;
- MyWatcher watcher = new MyWatcher();
- zk = createClient(watcher, hostPort, TIMEOUT);
- testWatcherAutoReset(zk, watcher, new MyWatcher());
- zk.close();
- }
-
- @Test
- public void testWatcherAutoResetDisabledWithGlobal() throws Exception {
- ClientCnxn.setDisableAutoResetWatch(true);
- testWatcherAutoResetWithGlobal();
- }
-
- @Test
- public void testWatcherAutoResetDisabledWithLocal() throws Exception {
- ClientCnxn.setDisableAutoResetWatch(true);
- testWatcherAutoResetWithLocal();
- }
-
- 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);
- if (isGlobal) {
- zk.getChildren("/watchtest", true);
- zk.getData("/watchtest/child", true, new Stat());
- zk.exists("/watchtest/child2", true);
- } else {
- zk.getChildren("/watchtest", localWatcher);
- zk.getData("/watchtest/child", localWatcher, new Stat());
- zk.exists("/watchtest/child2", localWatcher);
- }
-
- Assert.assertTrue(localWatcher.events.isEmpty());
-
- stopServer();
- globalWatcher.waitForDisconnected(3000);
- localWatcher.waitForDisconnected(500);
- startServer();
- globalWatcher.waitForConnected(3000);
- if (!isGlobal && !ClientCnxn.getDisableAutoResetWatch()) {
- localWatcher.waitForConnected(500);
- }
-
- Assert.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);
-
- WatchedEvent e;
- if (!ClientCnxn.getDisableAutoResetWatch()) {
- e = localWatcher.events.poll(TIMEOUT, TimeUnit.MILLISECONDS);
- Assert.assertEquals(e.getPath(), EventType.NodeDataChanged, e.getType());
- Assert.assertEquals("/watchtest/child", e.getPath());
- } else {
- // we'll catch this later if it does happen after timeout, so
- // why waste the time on poll
- }
-
- if (!ClientCnxn.getDisableAutoResetWatch()) {
- 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());
- } else {
- // we'll catch this later if it does happen after timeout, so
- // why waste the time on poll
- }
-
- if (!ClientCnxn.getDisableAutoResetWatch()) {
- e = localWatcher.events.poll(TIMEOUT, TimeUnit.MILLISECONDS);
- Assert.assertEquals(EventType.NodeChildrenChanged, e.getType());
- Assert.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
- stopServer();
- globalWatcher.waitForDisconnected(TIMEOUT);
- try {
- try {
- localWatcher.waitForDisconnected(500);
- if (!isGlobal && !ClientCnxn.getDisableAutoResetWatch()) {
- Assert.fail("Got an event when I shouldn't have");
- }
- } catch(TimeoutException toe) {
- if (ClientCnxn.getDisableAutoResetWatch()) {
- Assert.fail("Didn't get an event when I should have");
- }
- // Else what we are expecting since there are no outstanding watches
- }
- } catch (Exception e1) {
- LOG.error("bad", e1);
- throw new RuntimeException(e1);
- }
- startServer();
- globalWatcher.waitForConnected(TIMEOUT);
-
- if (isGlobal) {
- zk.getChildren("/watchtest", true);
- zk.getData("/watchtest/child", true, new Stat());
- zk.exists("/watchtest/child2", true);
- } else {
- zk.getChildren("/watchtest", localWatcher);
- zk.getData("/watchtest/child", localWatcher, new Stat());
- zk.exists("/watchtest/child2", localWatcher);
- }
-
- // Do trigger an event to make sure that we do not get
- // it later
- zk.delete("/watchtest/child2", -1);
-
- e = localWatcher.events.poll(TIMEOUT, TimeUnit.MILLISECONDS);
- Assert.assertEquals(EventType.NodeDeleted, e.getType());
- Assert.assertEquals("/watchtest/child2", e.getPath());
-
- e = localWatcher.events.poll(TIMEOUT, TimeUnit.MILLISECONDS);
- Assert.assertEquals(EventType.NodeChildrenChanged, e.getType());
- Assert.assertEquals("/watchtest", e.getPath());
-
- Assert.assertTrue(localWatcher.events.isEmpty());
-
- stopServer();
- globalWatcher.waitForDisconnected(TIMEOUT);
- localWatcher.waitForDisconnected(500);
- startServer();
- globalWatcher.waitForConnected(TIMEOUT);
- if (!isGlobal && !ClientCnxn.getDisableAutoResetWatch()) {
- localWatcher.waitForConnected(500);
- }
-
- zk.delete("/watchtest/child", -1);
- zk.delete("/watchtest", -1);
-
- if (!ClientCnxn.getDisableAutoResetWatch()) {
- e = localWatcher.events.poll(TIMEOUT, TimeUnit.MILLISECONDS);
- Assert.assertEquals(EventType.NodeDeleted, e.getType());
- Assert.assertEquals("/watchtest/child", e.getPath());
- } else {
- // we'll catch this later if it does happen after timeout, so
- // why waste the time on poll
- }
-
- // Make sure nothing is straggling!
- Thread.sleep(1000);
- Assert.assertTrue(localWatcher.events.isEmpty());
-
- }
-
-}