http://git-wip-us.apache.org/repos/asf/zookeeper/blob/c0aa3b3f/src/java/test/org/apache/zookeeper/common/TimeTest.java
----------------------------------------------------------------------
diff --git a/src/java/test/org/apache/zookeeper/common/TimeTest.java b/src/java/test/org/apache/zookeeper/common/TimeTest.java
deleted file mode 100644
index d938556..0000000
--- a/src/java/test/org/apache/zookeeper/common/TimeTest.java
+++ /dev/null
@@ -1,109 +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.common;
-
-import org.apache.zookeeper.CreateMode;
-import org.apache.zookeeper.WatchedEvent;
-import org.apache.zookeeper.Watcher;
-import org.apache.zookeeper.ZooDefs;
-import org.apache.zookeeper.ZooKeeper;
-import org.apache.zookeeper.test.ClientBase;
-import org.junit.Assert;
-import org.junit.Test;
-
-import java.util.Calendar;
-import java.util.Date;
-import java.util.concurrent.atomic.AtomicInteger;
-
-/**
- * Command line program for demonstrating robustness to clock
- * changes.
- * <p/>
- * How to run:
- * ant clean compile-test
- * echo build/test/lib/*.jar build/lib/*.jar build/classes build/test/classes | sed -e 's/ /:/g' > cp
- * java -cp $(cat cp) org.apache.zookeeper.common.TimeTest | tee log-without-patch
- * <p/>
- * After test program starts, in another window, do commands:
- * date -s '+1hour'
- * date -s '-1hour'
- * <p/>
- * As long as there isn't any expired event, the experiment is successful.
- */
-public class TimeTest extends ClientBase {
- private static final long mt0 = System.currentTimeMillis();
- private static final long nt0 = Time.currentElapsedTime();
-
- private static AtomicInteger watchCount = new AtomicInteger(0);
-
-
- public static void main(String[] args) throws Exception {
- System.out.printf("Starting\n");
- final TimeTest test = new TimeTest();
- System.out.printf("After construct\n");
- test.setUp();
- ZooKeeper zk = test.createClient();
- zk.create("/ephemeral", new byte[]{1, 2, 3},
- ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
- while (Time.currentElapsedTime() - nt0 < 100000) {
- System.out.printf("%d\t%s\n", discrepancy(),
- zk.exists("/ephemeral",
- watchCount.get() == 0 ? createWatcher() : null) != null);
- waitByYielding(500);
- }
- }
-
- private static Watcher createWatcher() {
- watchCount.incrementAndGet();
- return new Watcher() {
- @Override
- public void process(WatchedEvent event) {
- watchCount.decrementAndGet();
- System.out.printf("%d event = %s\n", discrepancy(), event);
- }
- };
-
- }
-
- private static void waitByYielding(long delay) {
- long t0 = Time.currentElapsedTime();
- while (Time.currentElapsedTime() < t0 + delay) {
- Thread.yield();
- }
- }
-
- private static long discrepancy() {
- return (System.currentTimeMillis() - mt0) - (Time.currentElapsedTime() - nt0);
- }
-
- @Test
- public void testElapsedTimeToDate() throws Exception {
- long walltime = Time.currentWallTime();
- long elapsedTime = Time.currentElapsedTime();
- Thread.sleep(200);
-
- Calendar cal = Calendar.getInstance();
- cal.setTime(Time.elapsedTimeToDate(elapsedTime));
- int calculatedDate = cal.get(Calendar.HOUR_OF_DAY);
- cal.setTime(new Date(walltime));
- int realDate = cal.get(Calendar.HOUR_OF_DAY);
-
- Assert.assertEquals(calculatedDate, realDate);
- }
-}
http://git-wip-us.apache.org/repos/asf/zookeeper/blob/c0aa3b3f/src/java/test/org/apache/zookeeper/server/CRCTest.java
----------------------------------------------------------------------
diff --git a/src/java/test/org/apache/zookeeper/server/CRCTest.java b/src/java/test/org/apache/zookeeper/server/CRCTest.java
deleted file mode 100644
index 2b7fb46..0000000
--- a/src/java/test/org/apache/zookeeper/server/CRCTest.java
+++ /dev/null
@@ -1,190 +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.server;
-
-import static org.apache.zookeeper.test.ClientBase.CONNECTION_TIMEOUT;
-
-import java.io.BufferedInputStream;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.RandomAccessFile;
-import java.util.List;
-import java.util.Map;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.CountDownLatch;
-import java.util.zip.Adler32;
-import java.util.zip.CheckedInputStream;
-
-import org.apache.jute.BinaryInputArchive;
-import org.apache.jute.InputArchive;
-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.server.persistence.FileSnap;
-import org.apache.zookeeper.server.persistence.FileTxnLog;
-import org.apache.zookeeper.server.persistence.TxnLog.TxnIterator;
-import org.apache.zookeeper.test.ClientBase;
-import org.junit.Assert;
-import org.junit.Test;
-
-public class CRCTest extends ZKTestCase implements Watcher {
- private static final Logger LOG = LoggerFactory.getLogger(CRCTest.class);
-
- private static final String HOSTPORT =
- "127.0.0.1:" + PortAssignment.unique();
- private volatile CountDownLatch startSignal;
-
- /**
- * corrupt a file by writing m at 500 b
- * offset
- * @param file the file to be corrupted
- * @throws IOException
- */
- private void corruptFile(File file) throws IOException {
- // corrupt the logfile
- RandomAccessFile raf = new RandomAccessFile(file, "rw");
- byte[] b = "mahadev".getBytes();
- long writeLen = 500L;
- raf.seek(writeLen);
- //corrupting the data
- raf.write(b);
- raf.close();
- }
-
- /** return if checksum matches for a snapshot **/
- private boolean getCheckSum(FileSnap snap, File snapFile) throws IOException {
- DataTree dt = new DataTree();
- Map<Long, Integer> sessions = new ConcurrentHashMap<Long, Integer>();
- InputStream snapIS = new BufferedInputStream(new FileInputStream(
- snapFile));
- CheckedInputStream crcIn = new CheckedInputStream(snapIS, new Adler32());
- InputArchive ia = BinaryInputArchive.getArchive(crcIn);
- try {
- snap.deserialize(dt, sessions, ia);
- } catch (IOException ie) {
- // we failed on the most recent snapshot
- // must be incomplete
- // try reading the next one
- // after corrupting
- snapIS.close();
- crcIn.close();
- throw ie;
- }
-
- long checksum = crcIn.getChecksum().getValue();
- long val = ia.readLong("val");
- snapIS.close();
- crcIn.close();
- return (val != checksum);
- }
-
- /** test checksums for the logs and snapshots.
- * the reader should fail on reading
- * a corrupt snapshot and a corrupt log
- * file
- * @throws Exception
- */
- @Test
- public void testChecksums() throws Exception {
- File tmpDir = ClientBase.createTmpDir();
- ClientBase.setupTestEnv();
- ZooKeeperServer zks = new ZooKeeperServer(tmpDir, tmpDir, 3000);
- SyncRequestProcessor.setSnapCount(150);
- 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);
- try {
- for (int i =0; i < 2000; i++) {
- zk.create("/crctest- " + i , ("/crctest- " + i).getBytes(),
- Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
- }
- } finally {
- zk.close();
- }
- f.shutdown();
- zks.shutdown();
- Assert.assertTrue("waiting for server down",
- ClientBase.waitForServerDown(HOSTPORT,
- ClientBase.CONNECTION_TIMEOUT));
-
- File versionDir = new File(tmpDir, "version-2");
- File[] list = versionDir.listFiles();
- //there should be only two files
- // one the snapshot and the other logFile
- File snapFile = null;
- File logFile = null;
- for (File file: list) {
- LOG.info("file is " + file);
- if (file.getName().startsWith("log")) {
- logFile = file;
- corruptFile(logFile);
- }
- }
- FileTxnLog flog = new FileTxnLog(versionDir);
- TxnIterator itr = flog.read(1);
- //we will get a checksum failure
- try {
- while (itr.next()) {
- }
- Assert.assertTrue(false);
- } catch(IOException ie) {
- LOG.info("crc corruption", ie);
- }
- itr.close();
- // find the last snapshot
- FileSnap snap = new FileSnap(versionDir);
- List<File> snapFiles = snap.findNRecentSnapshots(2);
- snapFile = snapFiles.get(0);
- corruptFile(snapFile);
- boolean cfile = false;
- try {
- cfile = getCheckSum(snap, snapFile);
- } catch(IOException ie) {
- //the last snapshot seems incompelte
- // corrupt the last but one
- // and use that
- snapFile = snapFiles.get(1);
- corruptFile(snapFile);
- cfile = getCheckSum(snap, snapFile);
- }
- Assert.assertTrue(cfile);
- }
-
- 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/server/DataNodeTest.java
----------------------------------------------------------------------
diff --git a/src/java/test/org/apache/zookeeper/server/DataNodeTest.java b/src/java/test/org/apache/zookeeper/server/DataNodeTest.java
deleted file mode 100644
index 6289766..0000000
--- a/src/java/test/org/apache/zookeeper/server/DataNodeTest.java
+++ /dev/null
@@ -1,65 +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.server;
-
-import static org.junit.Assert.*;
-
-import java.util.Set;
-
-import org.junit.Test;
-
-public class DataNodeTest {
-
- @Test
- public void testGetChildrenShouldReturnEmptySetWhenThereAreNoChidren() {
- // create DataNode and call getChildren
- DataNode dataNode = new DataNode();
- Set<String> children = dataNode.getChildren();
- assertNotNull(children);
- assertEquals(0, children.size());
-
- // add child,remove child and then call getChildren
- String child = "child";
- dataNode.addChild(child);
- dataNode.removeChild(child);
- children = dataNode.getChildren();
- assertNotNull(children);
- assertEquals(0, children.size());
-
- // Returned empty set must not be modifiable
- children = dataNode.getChildren();
- try {
- children.add("new child");
- fail("UnsupportedOperationException is expected");
- } catch (UnsupportedOperationException e) {
- // do nothing
- }
- }
-
- @Test
- public void testGetChildrenReturnsImmutableEmptySet() {
- DataNode dataNode = new DataNode();
- Set<String> children = dataNode.getChildren();
- try {
- children.add("new child");
- fail("UnsupportedOperationException is expected");
- } catch (UnsupportedOperationException e) {
- // do nothing
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/zookeeper/blob/c0aa3b3f/src/java/test/org/apache/zookeeper/server/DataTreeTest.java
----------------------------------------------------------------------
diff --git a/src/java/test/org/apache/zookeeper/server/DataTreeTest.java b/src/java/test/org/apache/zookeeper/server/DataTreeTest.java
deleted file mode 100644
index a484cf5..0000000
--- a/src/java/test/org/apache/zookeeper/server/DataTreeTest.java
+++ /dev/null
@@ -1,235 +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.server;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.apache.zookeeper.KeeperException.NoNodeException;
-import org.apache.zookeeper.KeeperException.NodeExistsException;
-import org.apache.zookeeper.WatchedEvent;
-import org.apache.zookeeper.Watcher;
-import org.apache.zookeeper.ZKTestCase;
-import org.apache.zookeeper.data.Stat;
-import org.apache.zookeeper.server.DataTree;
-import org.junit.After;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
-import org.apache.zookeeper.server.DataNode;
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.DataOutputStream;
-import java.io.IOException;
-import java.io.PrintWriter;
-import java.io.StringWriter;
-
-import org.apache.zookeeper.Quotas;
-import org.apache.jute.BinaryInputArchive;
-import org.apache.jute.BinaryOutputArchive;
-import org.apache.jute.Record;
-import org.apache.zookeeper.common.PathTrie;
-import java.lang.reflect.*;
-import java.util.concurrent.Semaphore;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.atomic.AtomicBoolean;
-
-public class DataTreeTest extends ZKTestCase {
- protected static final Logger LOG = LoggerFactory.getLogger(DataTreeTest.class);
-
- private DataTree dt;
-
- @Before
- public void setUp() throws Exception {
- dt=new DataTree();
- }
-
- @After
- public void tearDown() throws Exception {
- dt=null;
- }
-
- /**
- * For ZOOKEEPER-1755 - Test race condition when taking dumpEphemerals and
- * removing the session related ephemerals from DataTree structure
- */
- @Test(timeout = 60000)
- public void testDumpEphemerals() throws Exception {
- int count = 1000;
- long session = 1000;
- long zxid = 2000;
- final DataTree dataTree = new DataTree();
- LOG.info("Create {} zkclient sessions and its ephemeral nodes", count);
- createEphemeralNode(session, dataTree, count);
- final AtomicBoolean exceptionDuringDumpEphemerals = new AtomicBoolean(
- false);
- final AtomicBoolean running = new AtomicBoolean(true);
- Thread thread = new Thread() {
- public void run() {
- PrintWriter pwriter = new PrintWriter(new StringWriter());
- try {
- while (running.get()) {
- dataTree.dumpEphemerals(pwriter);
- }
- } catch (Exception e) {
- LOG.error("Received exception while dumpEphemerals!", e);
- exceptionDuringDumpEphemerals.set(true);
- }
- };
- };
- thread.start();
- LOG.debug("Killing {} zkclient sessions and its ephemeral nodes", count);
- killZkClientSession(session, zxid, dataTree, count);
- running.set(false);
- thread.join();
- Assert.assertFalse("Should have got exception while dumpEphemerals!",
- exceptionDuringDumpEphemerals.get());
- }
-
- private void killZkClientSession(long session, long zxid,
- final DataTree dataTree, int count) {
- for (int i = 0; i < count; i++) {
- dataTree.killSession(session + i, zxid);
- }
- }
-
- private void createEphemeralNode(long session, final DataTree dataTree,
- int count) throws NoNodeException, NodeExistsException {
- for (int i = 0; i < count; i++) {
- dataTree.createNode("/test" + i, new byte[0], null, session + i,
- dataTree.getNode("/").stat.getCversion() + 1, 1, 1);
- }
- }
-
- @Test(timeout = 60000)
- public void testRootWatchTriggered() throws Exception {
- class MyWatcher implements Watcher{
- boolean fired=false;
- public void process(WatchedEvent event) {
- if(event.getPath().equals("/"))
- fired=true;
- }
- }
- MyWatcher watcher=new MyWatcher();
- // set a watch on the root node
- dt.getChildren("/", new Stat(), watcher);
- // add a new node, should trigger a watch
- dt.createNode("/xyz", new byte[0], null, 0, dt.getNode("/").stat.getCversion()+1, 1, 1);
- Assert.assertFalse("Root node watch not triggered",!watcher.fired);
- }
-
- /**
- * For ZOOKEEPER-1046 test if cversion is getting incremented correctly.
- */
- @Test(timeout = 60000)
- public void testIncrementCversion() throws Exception {
- dt.createNode("/test", new byte[0], null, 0, dt.getNode("/").stat.getCversion()+1, 1, 1);
- DataNode zk = dt.getNode("/test");
- int prevCversion = zk.stat.getCversion();
- long prevPzxid = zk.stat.getPzxid();
- dt.setCversionPzxid("/test/", prevCversion + 1, prevPzxid + 1);
- int newCversion = zk.stat.getCversion();
- long newPzxid = zk.stat.getPzxid();
- Assert.assertTrue("<cversion, pzxid> verification failed. Expected: <" +
- (prevCversion + 1) + ", " + (prevPzxid + 1) + ">, found: <" +
- newCversion + ", " + newPzxid + ">",
- (newCversion == prevCversion + 1 && newPzxid == prevPzxid + 1));
- }
-
- @Test(timeout = 60000)
- public void testPathTrieClearOnDeserialize() throws Exception {
-
- //Create a DataTree with quota nodes so PathTrie get updated
- DataTree dserTree = new DataTree();
-
- dserTree.createNode("/bug", new byte[20], null, -1, 1, 1, 1);
- dserTree.createNode(Quotas.quotaZookeeper+"/bug", null, null, -1, 1, 1, 1);
- dserTree.createNode(Quotas.quotaPath("/bug"), new byte[20], null, -1, 1, 1, 1);
- dserTree.createNode(Quotas.statPath("/bug"), new byte[20], null, -1, 1, 1, 1);
-
- //deserialize a DataTree; this should clear the old /bug nodes and pathTrie
- DataTree tree = new DataTree();
-
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- BinaryOutputArchive oa = BinaryOutputArchive.getArchive(baos);
- tree.serialize(oa, "test");
- baos.flush();
-
- ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
- BinaryInputArchive ia = BinaryInputArchive.getArchive(bais);
- dserTree.deserialize(ia, "test");
-
- Field pfield = DataTree.class.getDeclaredField("pTrie");
- pfield.setAccessible(true);
- PathTrie pTrie = (PathTrie)pfield.get(dserTree);
-
- //Check that the node path is removed from pTrie
- Assert.assertEquals("/bug is still in pTrie", "", pTrie.findMaxPrefix("/bug"));
- }
-
- /*
- * ZOOKEEPER-2201 - OutputArchive.writeRecord can block for long periods of
- * time, we must call it outside of the node lock.
- * We call tree.serialize, which calls our modified writeRecord method that
- * blocks until it can verify that a separate thread can lock the DataNode
- * currently being written, i.e. that DataTree.serializeNode does not hold
- * the DataNode lock while calling OutputArchive.writeRecord.
- */
- @Test(timeout = 60000)
- public void testSerializeDoesntLockDataNodeWhileWriting() throws Exception {
- DataTree tree = new DataTree();
- tree.createNode("/marker", new byte[] {42}, null, -1, 1, 1, 1);
- final DataNode markerNode = tree.getNode("/marker");
- final AtomicBoolean ranTestCase = new AtomicBoolean();
- DataOutputStream out = new DataOutputStream(new ByteArrayOutputStream());
- BinaryOutputArchive oa = new BinaryOutputArchive(out) {
- @Override
- public void writeRecord(Record r, String tag) throws IOException {
- DataNode node = (DataNode) r;
- if (node.data.length == 1 && node.data[0] == 42) {
- final Semaphore semaphore = new Semaphore(0);
- new Thread(new Runnable() {
- @Override
- public void run() {
- synchronized (markerNode) {
- //When we lock markerNode, allow writeRecord to continue
- semaphore.release();
- }
- }
- }).start();
-
- try {
- boolean acquired = semaphore.tryAcquire(30, TimeUnit.SECONDS);
- //This is the real assertion - could another thread lock
- //the DataNode we're currently writing
- Assert.assertTrue("Couldn't acquire a lock on the DataNode while we were calling tree.serialize", acquired);
- } catch (InterruptedException e1) {
- throw new RuntimeException(e1);
- }
- ranTestCase.set(true);
- }
- super.writeRecord(r, tag);
- }
- };
-
- tree.serialize(oa, "test");
-
- //Let's make sure that we hit the code that ran the real assertion above
- Assert.assertTrue("Didn't find the expected node", ranTestCase.get());
- }
-}
http://git-wip-us.apache.org/repos/asf/zookeeper/blob/c0aa3b3f/src/java/test/org/apache/zookeeper/server/DataTreeUnitTest.java
----------------------------------------------------------------------
diff --git a/src/java/test/org/apache/zookeeper/server/DataTreeUnitTest.java b/src/java/test/org/apache/zookeeper/server/DataTreeUnitTest.java
deleted file mode 100644
index 287c384..0000000
--- a/src/java/test/org/apache/zookeeper/server/DataTreeUnitTest.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.server;
-
-import org.apache.zookeeper.WatchedEvent;
-import org.apache.zookeeper.Watcher;
-import org.apache.zookeeper.ZKTestCase;
-import org.apache.zookeeper.data.Stat;
-import org.junit.After;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
-
-public class DataTreeUnitTest extends ZKTestCase {
- DataTree dt;
-
- @Before
- public void setUp() throws Exception {
- dt=new DataTree();
- }
-
- @After
- public void tearDown() throws Exception {
- dt=null;
- }
-
- @Test
- public void testRootWatchTriggered() throws Exception {
- class MyWatcher implements Watcher{
- boolean fired=false;
- public void process(WatchedEvent event) {
- if(event.getPath().equals("/"))
- fired=true;
- }
- }
- MyWatcher watcher=new MyWatcher();
- // set a watch on the root node
- dt.getChildren("/", new Stat(), watcher);
- // add a new node, should trigger a watch
- dt.createNode("/xyz", new byte[0], null, 0, dt.getNode("/").stat.getCversion()+1, 1, 1);
- Assert.assertFalse("Root node watch not triggered",!watcher.fired);
- }
-
-}
http://git-wip-us.apache.org/repos/asf/zookeeper/blob/c0aa3b3f/src/java/test/org/apache/zookeeper/server/DatadirCleanupManagerTest.java
----------------------------------------------------------------------
diff --git a/src/java/test/org/apache/zookeeper/server/DatadirCleanupManagerTest.java b/src/java/test/org/apache/zookeeper/server/DatadirCleanupManagerTest.java
deleted file mode 100644
index 6b2f45f..0000000
--- a/src/java/test/org/apache/zookeeper/server/DatadirCleanupManagerTest.java
+++ /dev/null
@@ -1,91 +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.server;
-
-import static org.apache.zookeeper.server.DatadirCleanupManager.PurgeTaskStatus.COMPLETED;
-import static org.apache.zookeeper.server.DatadirCleanupManager.PurgeTaskStatus.NOT_STARTED;
-import static org.apache.zookeeper.server.DatadirCleanupManager.PurgeTaskStatus.STARTED;
-
-import java.io.File;
-
-import junit.framework.Assert;
-
-import org.apache.zookeeper.test.ClientBase;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-
-public class DatadirCleanupManagerTest {
-
- private DatadirCleanupManager purgeMgr;
- private String snapDir;
- private String dataLogDir;
-
- @Before
- public void setUp() throws Exception {
- File dataDir = ClientBase.createTmpDir();
- snapDir = dataDir.getAbsolutePath();
- dataLogDir = dataDir.getAbsolutePath();
- }
-
- @Test
- public void testPurgeTask() throws Exception {
- purgeMgr = new DatadirCleanupManager(snapDir, dataLogDir, 3, 1);
- purgeMgr.start();
- Assert.assertEquals("Data log directory is not set as configured",
- dataLogDir, purgeMgr.getDataLogDir());
- Assert.assertEquals("Snapshot directory is not set as configured",
- snapDir, purgeMgr.getSnapDir());
- Assert.assertEquals("Snapshot retain count is not set as configured",
- 3, purgeMgr.getSnapRetainCount());
- Assert.assertEquals("Purge task is not started", STARTED, purgeMgr.getPurgeTaskStatus());
- purgeMgr.shutdown();
- Assert.assertEquals("Purge task is still running after shutdown", COMPLETED,
- purgeMgr.getPurgeTaskStatus());
- }
-
- @Test
- public void testWithZeroPurgeInterval() throws Exception {
- purgeMgr = new DatadirCleanupManager(snapDir, dataLogDir, 3, 0);
- purgeMgr.start();
- Assert.assertEquals("Purge task is scheduled with zero purge interval", NOT_STARTED,
- purgeMgr.getPurgeTaskStatus());
- purgeMgr.shutdown();
- Assert.assertEquals("Purge task is scheduled with zero purge interval", NOT_STARTED,
- purgeMgr.getPurgeTaskStatus());
- }
-
- @Test
- public void testWithNegativePurgeInterval() throws Exception {
- purgeMgr = new DatadirCleanupManager(snapDir, dataLogDir, 3, -1);
- purgeMgr.start();
- Assert.assertEquals("Purge task is scheduled with negative purge interval",
- NOT_STARTED, purgeMgr.getPurgeTaskStatus());
- purgeMgr.shutdown();
- Assert.assertEquals("Purge task is scheduled with negative purge interval", NOT_STARTED,
- purgeMgr.getPurgeTaskStatus());
- }
-
- @After
- public void tearDown() throws Exception {
- if (purgeMgr != null) {
- purgeMgr.shutdown();
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/zookeeper/blob/c0aa3b3f/src/java/test/org/apache/zookeeper/server/DeserializationPerfTest.java
----------------------------------------------------------------------
diff --git a/src/java/test/org/apache/zookeeper/server/DeserializationPerfTest.java b/src/java/test/org/apache/zookeeper/server/DeserializationPerfTest.java
deleted file mode 100644
index fd850e7..0000000
--- a/src/java/test/org/apache/zookeeper/server/DeserializationPerfTest.java
+++ /dev/null
@@ -1,119 +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.server;
-
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-
-import org.apache.jute.BinaryInputArchive;
-import org.apache.jute.BinaryOutputArchive;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.apache.zookeeper.KeeperException;
-import org.apache.zookeeper.ZKTestCase;
-import org.junit.Assert;
-import org.junit.Test;
-
-public class DeserializationPerfTest extends ZKTestCase {
- protected static final Logger LOG = LoggerFactory.getLogger(DeserializationPerfTest.class);
-
- private static void deserializeTree(int depth, int width, int len)
- throws InterruptedException, IOException, KeeperException.NodeExistsException, KeeperException.NoNodeException {
- BinaryInputArchive ia;
- int count;
- {
- DataTree tree = new DataTree();
- SerializationPerfTest.createNodes(tree, "/", depth, tree.getNode("/").stat.getCversion(), width, new byte[len]);
- count = tree.getNodeCount();
-
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- BinaryOutputArchive oa = BinaryOutputArchive.getArchive(baos);
- tree.serialize(oa, "test");
- baos.flush();
-
- ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
- ia = BinaryInputArchive.getArchive(bais);
- }
-
- DataTree dserTree = new DataTree();
-
- System.gc();
- long start = System.nanoTime();
- dserTree.deserialize(ia, "test");
- long end = System.nanoTime();
- long durationms = (end - start) / 1000000L;
- long pernodeus = ((end - start) / 1000L) / count;
-
- Assert.assertEquals(count, dserTree.getNodeCount());
-
- LOG.info("Deserialized " + count + " nodes in " + durationms
- + " ms (" + pernodeus + "us/node), depth=" + depth + " width="
- + width + " datalen=" + len);
- }
-
- @Test
- public void testSingleDeserialize() throws
- InterruptedException, IOException, KeeperException.NodeExistsException, KeeperException.NoNodeException {
- deserializeTree(1, 0, 20);
- }
-
- @Test
- public void testWideDeserialize() throws
- InterruptedException, IOException, KeeperException.NodeExistsException, KeeperException.NoNodeException {
- deserializeTree(2, 10000, 20);
- }
-
- @Test
- public void testDeepDeserialize() throws
- InterruptedException, IOException, KeeperException.NodeExistsException, KeeperException.NoNodeException {
- deserializeTree(400, 1, 20);
- }
-
- @Test
- public void test10Wide5DeepDeserialize() throws
- InterruptedException, IOException, KeeperException.NodeExistsException, KeeperException.NoNodeException {
- deserializeTree(5, 10, 20);
- }
-
- @Test
- public void test15Wide5DeepDeserialize() throws
- InterruptedException, IOException, KeeperException.NodeExistsException, KeeperException.NoNodeException {
- deserializeTree(5, 15, 20);
- }
-
- @Test
- public void test25Wide4DeepDeserialize() throws
- InterruptedException, IOException, KeeperException.NodeExistsException, KeeperException.NoNodeException {
- deserializeTree(4, 25, 20);
- }
-
- @Test
- public void test40Wide4DeepDeserialize() throws
- InterruptedException, IOException, KeeperException.NodeExistsException, KeeperException.NoNodeException {
- deserializeTree(4, 40, 20);
- }
-
- @Test
- public void test300Wide3DeepDeserialize() throws
- InterruptedException, IOException, KeeperException.NodeExistsException, KeeperException.NoNodeException {
- deserializeTree(3, 300, 20);
- }
-
-}
http://git-wip-us.apache.org/repos/asf/zookeeper/blob/c0aa3b3f/src/java/test/org/apache/zookeeper/server/InvalidSnapCountTest.java
----------------------------------------------------------------------
diff --git a/src/java/test/org/apache/zookeeper/server/InvalidSnapCountTest.java b/src/java/test/org/apache/zookeeper/server/InvalidSnapCountTest.java
deleted file mode 100644
index 3a66164..0000000
--- a/src/java/test/org/apache/zookeeper/server/InvalidSnapCountTest.java
+++ /dev/null
@@ -1,126 +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.server;
-
-import static org.apache.zookeeper.test.ClientBase.CONNECTION_TIMEOUT;
-
-import java.io.File;
-import java.io.FileWriter;
-import java.io.IOException;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.apache.zookeeper.WatchedEvent;
-import org.apache.zookeeper.Watcher;
-import org.apache.zookeeper.ZKTestCase;
-import org.apache.zookeeper.ZooKeeper;
-import org.apache.zookeeper.test.ClientBase;
-import org.junit.Assert;
-import org.junit.Test;
-
-/**
- * Test stand-alone server.
- *
- */
-public class InvalidSnapCountTest extends ZKTestCase implements Watcher {
- protected static final Logger LOG =
- LoggerFactory.getLogger(InvalidSnapCountTest.class);
-
- public static class MainThread extends Thread {
- final File confFile;
- final TestMain main;
-
- public MainThread(int clientPort) throws IOException {
- super("Standalone server with clientPort:" + clientPort);
- File tmpDir = ClientBase.createTmpDir();
- confFile = new File(tmpDir, "zoo.cfg");
-
- FileWriter fwriter = new FileWriter(confFile);
- fwriter.write("tickTime=2000\n");
- fwriter.write("initLimit=10\n");
- fwriter.write("syncLimit=5\n");
- fwriter.write("snapCount=1\n");
-
- File dataDir = new File(tmpDir, "data");
- if (!dataDir.mkdir()) {
- throw new IOException("unable to mkdir " + dataDir);
- }
-
- // Convert windows path to UNIX to avoid problems with "\"
- String dir = dataDir.toString();
- String osname = java.lang.System.getProperty("os.name");
- if (osname.toLowerCase().contains("windows")) {
- dir = dir.replace('\\', '/');
- }
- fwriter.write("dataDir=" + dir + "\n");
-
- fwriter.write("clientPort=" + clientPort + "\n");
- fwriter.flush();
- fwriter.close();
-
- main = new TestMain();
- }
-
- public void run() {
- String args[] = new String[1];
- args[0] = confFile.toString();
- try {
- main.initializeAndRun(args);
- } catch (Exception e) {
- // test will still fail even though we just log/ignore
- LOG.error("unexpected exception in run", e);
- }
- }
-
- public void shutdown() {
- main.shutdown();
- }
- }
-
- public static class TestMain extends ZooKeeperServerMain {
- public void shutdown() {
- super.shutdown();
- }
- }
-
- /**
- * Verify the ability to start a standalone server instance.
- */
- @Test
- public void testInvalidSnapCount() throws Exception {
-
- final int CLIENT_PORT = 3181;
-
- MainThread main = new MainThread(CLIENT_PORT);
- main.start();
-
- Assert.assertTrue("waiting for server being up",
- ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT,
- CONNECTION_TIMEOUT));
-
- Assert.assertEquals(SyncRequestProcessor.getSnapCount(), 2);
-
- main.shutdown();
-
- }
-
- public void process(WatchedEvent event) {
- // ignore for this test
- }
-}
http://git-wip-us.apache.org/repos/asf/zookeeper/blob/c0aa3b3f/src/java/test/org/apache/zookeeper/server/InvalidSnapshotTest.java
----------------------------------------------------------------------
diff --git a/src/java/test/org/apache/zookeeper/server/InvalidSnapshotTest.java b/src/java/test/org/apache/zookeeper/server/InvalidSnapshotTest.java
deleted file mode 100644
index 97ad792..0000000
--- a/src/java/test/org/apache/zookeeper/server/InvalidSnapshotTest.java
+++ /dev/null
@@ -1,84 +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.server;
-
-import static org.junit.Assert.assertTrue;
-
-import java.io.File;
-import java.io.RandomAccessFile;
-
-import org.apache.zookeeper.CreateMode;
-import org.apache.zookeeper.ZooDefs.Ids;
-import org.apache.zookeeper.ZooKeeper;
-import org.apache.zookeeper.test.ClientBase;
-import org.junit.Test;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * This test checks that the server works even if the last snapshot is
- * invalidated by corruption or if the server crashes while generating the
- * snapshot.
- */
-public class InvalidSnapshotTest extends ClientBase {
- private static final Logger LOG =
- LoggerFactory.getLogger(InvalidSnapshotTest.class);
-
- public InvalidSnapshotTest() {
- SyncRequestProcessor.setSnapCount(100);
- }
-
- /**
- * Validate that the server can come up on an invalid snapshot - by
- * reverting to a prior snapshot + associated logs.
- */
- @Test
- public void testInvalidSnapshot() throws Exception {
- ZooKeeper zk = createClient();
- try {
- for (int i = 0; i < 2000; i++) {
- zk.create("/invalidsnap-" + i, new byte[0],
- Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
- }
- } finally {
- zk.close();
- }
- NIOServerCnxnFactory factory = (NIOServerCnxnFactory)serverFactory;
- stopServer();
-
- // now corrupt the snapshot
- File snapFile = factory.zkServer.getTxnLogFactory().findMostRecentSnapshot();
- LOG.info("Corrupting " + snapFile);
- RandomAccessFile raf = new RandomAccessFile(snapFile, "rws");
- raf.setLength(3);
- raf.close();
-
- // now restart the server
- startServer();
-
- // verify that the expected data exists and wasn't lost
- zk = createClient();
- try {
- assertTrue("the node should exist",
- (zk.exists("/invalidsnap-1999", false) != null));
- } finally {
- zk.close();
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/zookeeper/blob/c0aa3b3f/src/java/test/org/apache/zookeeper/server/MockNIOServerCnxn.java
----------------------------------------------------------------------
diff --git a/src/java/test/org/apache/zookeeper/server/MockNIOServerCnxn.java b/src/java/test/org/apache/zookeeper/server/MockNIOServerCnxn.java
deleted file mode 100644
index 53ad1f6..0000000
--- a/src/java/test/org/apache/zookeeper/server/MockNIOServerCnxn.java
+++ /dev/null
@@ -1,45 +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.server;
-
-import java.nio.channels.SelectionKey;
-import java.nio.channels.SocketChannel;
-import java.io.IOException;
-
-public class MockNIOServerCnxn extends NIOServerCnxn {
-
- public MockNIOServerCnxn(ZooKeeperServer zk, SocketChannel sock,
- SelectionKey sk, NIOServerCnxnFactory factory)
- throws IOException {
- super(zk, sock, sk, factory);
- }
-
- /**
- * Handles read/write IO on connection.
- */
- public void doIO(SelectionKey k) throws InterruptedException {
- super.doIO(k);
- }
-
- @Override
- protected boolean isSocketOpen() {
- return true;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/zookeeper/blob/c0aa3b3f/src/java/test/org/apache/zookeeper/server/NIOServerCnxnTest.java
----------------------------------------------------------------------
diff --git a/src/java/test/org/apache/zookeeper/server/NIOServerCnxnTest.java b/src/java/test/org/apache/zookeeper/server/NIOServerCnxnTest.java
deleted file mode 100644
index bdee20f..0000000
--- a/src/java/test/org/apache/zookeeper/server/NIOServerCnxnTest.java
+++ /dev/null
@@ -1,106 +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.server;
-
-import java.io.IOException;
-import java.nio.ByteBuffer;
-import java.nio.channels.CancelledKeyException;
-
-import org.apache.zookeeper.CreateMode;
-import org.apache.zookeeper.KeeperException;
-import org.apache.zookeeper.ZooDefs.Ids;
-import org.apache.zookeeper.ZooKeeper;
-import org.apache.zookeeper.test.ClientBase;
-import org.junit.Assert;
-import org.junit.Test;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class NIOServerCnxnTest extends ClientBase {
- private static final Logger LOG = LoggerFactory
- .getLogger(NIOServerCnxnTest.class);
- /**
- * Test operations on ServerCnxn after socket closure.
- */
- @Test(timeout = 60000)
- public void testOperationsAfterCnxnClose() throws IOException,
- InterruptedException, KeeperException {
- final ZooKeeper zk = createClient();
-
- final String path = "/a";
- try {
- // make sure zkclient works
- zk.create(path, "test".getBytes(), Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
- Assert.assertNotNull("Didn't create znode:" + path,
- zk.exists(path, false));
- // Defaults ServerCnxnFactory would be instantiated with
- // NIOServerCnxnFactory
- Assert.assertTrue(
- "Didn't instantiate ServerCnxnFactory with NIOServerCnxnFactory!",
- serverFactory instanceof NIOServerCnxnFactory);
- Iterable<ServerCnxn> connections = serverFactory.getConnections();
- for (ServerCnxn serverCnxn : connections) {
- serverCnxn.close();
- try {
- serverCnxn.toString();
- } catch (Exception e) {
- LOG.error("Exception while getting connection details!", e);
- Assert.fail("Shouldn't throw exception while "
- + "getting connection details!");
- }
- }
- } finally {
- zk.close();
- }
- }
-
- /**
- * Mock extension of NIOServerCnxn to test for
- * CancelledKeyException (ZOOKEEPER-2044).
- */
- private static class MockNIOServerCnxn extends NIOServerCnxn {
- public MockNIOServerCnxn(NIOServerCnxn cnxn)
- throws IOException {
- super(cnxn.zkServer, cnxn.sock, cnxn.sk, cnxn.factory);
- }
-
- public void mockSendBuffer(ByteBuffer bb) throws Exception {
- super.internalSendBuffer(bb);
- }
- }
-
- @Test(timeout = 30000)
- public void testValidSelectionKey() throws Exception {
- final ZooKeeper zk = createZKClient(hostPort, 3000);
- try {
- Iterable<ServerCnxn> connections = serverFactory.getConnections();
- for (ServerCnxn serverCnxn : connections) {
- MockNIOServerCnxn mock = new MockNIOServerCnxn((NIOServerCnxn) serverCnxn);
- // Cancel key
- ((NIOServerCnxn) serverCnxn).sock.keyFor(((NIOServerCnxnFactory) serverFactory).selector).cancel();;
- mock.mockSendBuffer(ByteBuffer.allocate(8));
- }
- } catch (CancelledKeyException e) {
- LOG.error("Exception while sending bytes!", e);
- Assert.fail(e.toString());
- } finally {
- zk.close();
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/zookeeper/blob/c0aa3b3f/src/java/test/org/apache/zookeeper/server/NettyServerCnxnTest.java
----------------------------------------------------------------------
diff --git a/src/java/test/org/apache/zookeeper/server/NettyServerCnxnTest.java b/src/java/test/org/apache/zookeeper/server/NettyServerCnxnTest.java
deleted file mode 100644
index 52265c6..0000000
--- a/src/java/test/org/apache/zookeeper/server/NettyServerCnxnTest.java
+++ /dev/null
@@ -1,103 +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.server;
-
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.TimeUnit;
-
-import junit.framework.Assert;
-
-import org.apache.zookeeper.CreateMode;
-import org.apache.zookeeper.ZooDefs.Ids;
-import org.apache.zookeeper.ZooKeeper;
-import org.apache.zookeeper.server.NettyServerCnxnFactory.CnxnChannelHandler;
-import org.apache.zookeeper.test.ClientBase;
-import org.jboss.netty.channel.ChannelHandlerContext;
-import org.jboss.netty.channel.ChannelStateEvent;
-import org.junit.Test;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * Test verifies the behavior of NettyServerCnxn which represents a connection
- * from a client to the server.
- */
-public class NettyServerCnxnTest extends ClientBase {
- private static final Logger LOG = LoggerFactory
- .getLogger(NettyServerCnxnTest.class);
-
- @Override
- public void setUp() throws Exception {
- System.setProperty(ServerCnxnFactory.ZOOKEEPER_SERVER_CNXN_FACTORY,
- "org.apache.zookeeper.server.NettyServerCnxnFactory");
- super.setUp();
- }
-
- /**
- * Test verifies the channel closure - while closing the channel
- * servercnxnfactory should remove all channel references to avoid
- * duplicate channel closure. Duplicate closure may result in
- * indefinite hanging due to netty open issue.
- *
- * @see <a href="https://issues.jboss.org/browse/NETTY-412">NETTY-412</a>
- */
- @Test(timeout = 30000)
- public void testSendCloseSession() throws Exception {
- Assert.assertTrue(
- "Didn't instantiate ServerCnxnFactory with NettyServerCnxnFactory!",
- serverFactory instanceof NettyServerCnxnFactory);
-
- NettyServerCnxnFactory nettyServerFactory = (NettyServerCnxnFactory) serverFactory;
- final CountDownLatch channelLatch = new CountDownLatch(1);
- CnxnChannelHandler channelHandler = nettyServerFactory.new CnxnChannelHandler() {
- @Override
- public void channelDisconnected(ChannelHandlerContext ctx,
- ChannelStateEvent e) throws Exception {
- LOG.info("Recieves channel disconnected event");
- channelLatch.countDown();
- }
- };
- LOG.info("Adding custom channel handler for simulation");
- nettyServerFactory.bootstrap.getPipeline().remove("servercnxnfactory");
- nettyServerFactory.bootstrap.getPipeline().addLast("servercnxnfactory",
- channelHandler);
-
- final ZooKeeper zk = createClient();
- final String path = "/a";
- try {
- // make sure zkclient works
- zk.create(path, "test".getBytes(), Ids.OPEN_ACL_UNSAFE,
- CreateMode.PERSISTENT);
- Assert.assertNotNull("Didn't create znode:" + path,
- zk.exists(path, false));
- Iterable<ServerCnxn> connections = serverFactory.getConnections();
- Assert.assertEquals("Mismatch in number of live connections!", 1,
- serverFactory.getNumAliveConnections());
- for (ServerCnxn serverCnxn : connections) {
- serverCnxn.sendCloseSession();
- }
- LOG.info("Waiting for the channel disconnected event");
- channelLatch.await(CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS);
- Assert.assertEquals("Mismatch in number of live connections!", 0,
- serverFactory.getNumAliveConnections());
- } finally {
- zk.close();
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/zookeeper/blob/c0aa3b3f/src/java/test/org/apache/zookeeper/server/PrepRequestProcessorTest.java
----------------------------------------------------------------------
diff --git a/src/java/test/org/apache/zookeeper/server/PrepRequestProcessorTest.java b/src/java/test/org/apache/zookeeper/server/PrepRequestProcessorTest.java
deleted file mode 100644
index d86cf2a..0000000
--- a/src/java/test/org/apache/zookeeper/server/PrepRequestProcessorTest.java
+++ /dev/null
@@ -1,262 +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.server;
-
-import org.apache.jute.BinaryOutputArchive;
-import org.apache.jute.Record;
-import org.apache.zookeeper.KeeperException;
-import org.apache.zookeeper.KeeperException.SessionExpiredException;
-import org.apache.zookeeper.KeeperException.SessionMovedException;
-import org.apache.zookeeper.MultiTransactionRecord;
-import org.apache.zookeeper.Op;
-import org.apache.zookeeper.PortAssignment;
-import org.apache.zookeeper.ZooDefs.Ids;
-import org.apache.zookeeper.ZooDefs.OpCode;
-import org.apache.zookeeper.data.Id;
-import org.apache.zookeeper.proto.SetDataRequest;
-import org.apache.zookeeper.server.ZooKeeperServer.ChangeRecord;
-import org.apache.zookeeper.test.ClientBase;
-import org.apache.zookeeper.txn.ErrorTxn;
-import org.junit.After;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.io.ByteArrayOutputStream;
-import java.io.File;
-import java.io.IOException;
-import java.io.PrintWriter;
-import java.nio.ByteBuffer;
-import java.util.Arrays;
-import java.util.List;
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.TimeUnit;
-
-public class PrepRequestProcessorTest extends ClientBase {
- private static final Logger LOG = LoggerFactory.getLogger(PrepRequestProcessorTest.class);
- private static final int CONNECTION_TIMEOUT = 3000;
- private static String HOSTPORT = "127.0.0.1:" + PortAssignment.unique();
- private CountDownLatch pLatch;
-
- private ZooKeeperServer zks;
- private ServerCnxnFactory servcnxnf;
- private PrepRequestProcessor processor;
- private Request outcome;
-
- @Before
- public void setup() throws Exception {
- File tmpDir = ClientBase.createTmpDir();
- ClientBase.setupTestEnv();
- zks = new ZooKeeperServer(tmpDir, tmpDir, 3000);
- SyncRequestProcessor.setSnapCount(100);
- final int PORT = Integer.parseInt(HOSTPORT.split(":")[1]);
-
- servcnxnf = ServerCnxnFactory.createFactory(PORT, -1);
- servcnxnf.startup(zks);
- Assert.assertTrue("waiting for server being up ",
- ClientBase.waitForServerUp(HOSTPORT, CONNECTION_TIMEOUT));
- zks.sessionTracker = new MySessionTracker();
- }
-
- @After
- public void teardown() throws Exception {
- if (servcnxnf != null) {
- servcnxnf.shutdown();
- }
- if (zks != null) {
- zks.shutdown();
- }
- }
-
- @Test
- public void testPRequest() throws Exception {
- pLatch = new CountDownLatch(1);
- processor = new PrepRequestProcessor(zks, new MyRequestProcessor());
- Request foo = new Request(null, 1l, 1, OpCode.create, ByteBuffer.allocate(3), null);
- processor.pRequest(foo);
-
- Assert.assertEquals("Request should have marshalling error", new ErrorTxn(KeeperException.Code.MARSHALLINGERROR.intValue()),
- outcome.txn);
- Assert.assertTrue("request hasn't been processed in chain", pLatch.await(5, TimeUnit.SECONDS));
- }
-
- private Request createRequest(Record record, int opCode) throws IOException {
- // encoding
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- BinaryOutputArchive boa = BinaryOutputArchive.getArchive(baos);
- record.serialize(boa, "request");
- baos.close();
-
- // Id
- List<Id> ids = Arrays.asList(Ids.ANYONE_ID_UNSAFE);
-
- return new Request(null, 1l, 0, opCode, ByteBuffer.wrap(baos.toByteArray()), ids);
- }
-
- private void process(List<Op> ops) throws Exception {
- pLatch = new CountDownLatch(1);
- processor = new PrepRequestProcessor(zks, new MyRequestProcessor());
-
- Record record = new MultiTransactionRecord(ops);
- Request req = createRequest(record, OpCode.multi);
-
- processor.pRequest(req);
- Assert.assertTrue("request hasn't been processed in chain", pLatch.await(5, TimeUnit.SECONDS));
- }
-
- /**
- * This test checks that a successful multi will change outstanding record
- * and failed multi shouldn't change outstanding record.
- */
- @Test
- public void testMultiOutstandingChange() throws Exception {
- zks.getZKDatabase().dataTree.createNode("/foo", new byte[0], Ids.OPEN_ACL_UNSAFE, 0, 0, 0, 0);
-
- Assert.assertNull(zks.outstandingChangesForPath.get("/foo"));
-
- process(Arrays.asList(
- Op.setData("/foo", new byte[0], -1)));
-
- ChangeRecord cr = zks.outstandingChangesForPath.get("/foo");
- Assert.assertNotNull("Change record wasn't set", cr);
- Assert.assertEquals("Record zxid wasn't set correctly",
- 1, cr.zxid);
-
- process(Arrays.asList(
- Op.delete("/foo", -1)));
- cr = zks.outstandingChangesForPath.get("/foo");
- Assert.assertEquals("Record zxid wasn't set correctly",
- 2, cr.zxid);
-
-
- // It should fail and shouldn't change outstanding record.
- process(Arrays.asList(
- Op.delete("/foo", -1)));
- cr = zks.outstandingChangesForPath.get("/foo");
- // zxid should still be previous result because record's not changed.
- Assert.assertEquals("Record zxid wasn't set correctly",
- 2, cr.zxid);
- }
-
- /**
- * ZOOKEEPER-2052:
- * This test checks that if a multi operation aborted, and during the multi there is side effect
- * that changed outstandingChangesForPath, after aborted the side effect should be removed and
- * everything should be restored correctly.
- */
- @Test
- public void testMultiRollbackNoLastChange() throws Exception {
- zks.getZKDatabase().dataTree.createNode("/foo", new byte[0], Ids.OPEN_ACL_UNSAFE, 0, 0, 0, 0);
- zks.getZKDatabase().dataTree.createNode("/foo/bar", new byte[0], Ids.OPEN_ACL_UNSAFE, 0, 0, 0, 0);
-
- Assert.assertNull(zks.outstandingChangesForPath.get("/foo"));
-
- // multi record:
- // set "/foo" => succeed, leave a outstanding change
- // delete "/foo" => fail, roll back change
- process(Arrays.asList(
- Op.setData("/foo", new byte[0], -1),
- Op.delete("/foo", -1)));
-
- // aborting multi shouldn't leave any record.
- Assert.assertNull(zks.outstandingChangesForPath.get("/foo"));
- }
-
- /**
- * It tests that PrepRequestProcessor will return BadArgument KeeperException
- * if the request path (if it exists) is not valid, e.g. empty string.
- */
- @Test
- public void testInvalidPath() throws Exception {
- pLatch = new CountDownLatch(1);
- processor = new PrepRequestProcessor(zks, new MyRequestProcessor());
-
- SetDataRequest record = new SetDataRequest("", new byte[0], -1);
- Request req = createRequest(record, OpCode.setData);
- processor.pRequest(req);
- pLatch.await();
- Assert.assertEquals(outcome.hdr.getType(), OpCode.error);
- Assert.assertEquals(outcome.getException().code(), KeeperException.Code.BADARGUMENTS);
- }
-
- private class MyRequestProcessor implements RequestProcessor {
- @Override
- public void processRequest(Request request) {
- // getting called by PrepRequestProcessor
- outcome = request;
- pLatch.countDown();
- }
-
- @Override
- public void shutdown() {
- // TODO Auto-generated method stub
- }
- }
-
- private class MySessionTracker implements SessionTracker {
- @Override
- public void addSession(long id, int to) {
- // TODO Auto-generated method stub
-
- }
- @Override
- public void checkSession(long sessionId, Object owner)
- throws SessionExpiredException, SessionMovedException {
- // TODO Auto-generated method stub
-
- }
- @Override
- public long createSession(int sessionTimeout) {
- // TODO Auto-generated method stub
- return 0;
- }
- @Override
- public void dumpSessions(PrintWriter pwriter) {
- // TODO Auto-generated method stub
-
- }
- @Override
- public void removeSession(long sessionId) {
- // TODO Auto-generated method stub
-
- }
- @Override
- public void setOwner(long id, Object owner)
- throws SessionExpiredException {
- // TODO Auto-generated method stub
-
- }
- @Override
- public void shutdown() {
- // TODO Auto-generated method stub
-
- }
- @Override
- public boolean touchSession(long sessionId, int sessionTimeout) {
- // TODO Auto-generated method stub
- return false;
- }
- @Override
- public void setSessionClosing(long sessionId) {
- // TODO Auto-generated method stub
- }
- }
-}
|