@Test public void testIt() throws Exception { final ZooKeeperPlus zk = getZk(); final String nodePath = ZkPath.append(getRoot(), "watchedNode"); zk.create(nodePath, "1".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); final WatchedInt wi = new WatchedInt(zk, nodePath, true); assertEquals(Integer.valueOf(1), wi.get()); zk.setData(nodePath, "55".getBytes(), -1); WaitUntil.orDie(() -> { Integer v = wi.get(); return v != null && v == 55; }); assertEquals(Integer.valueOf(55), wi.get()); zk.setData(nodePath, null, -1); WaitUntil.orDie(() -> wi.get() == null); assertNull(wi.get()); final WatchedInt wi2 = new WatchedInt(zk, nodePath, true); WaitUntil.orDie(() -> wi2.get() == null); assertNull(wi2.get()); wi2.set(22); WaitUntil.orDie(() -> { Integer v = wi.get(); Integer v2 = wi2.get(); return v2 != null && v2 == 22 && v != null && v == 22; }); assertEquals(Integer.valueOf(22), wi2.get()); assertEquals(Integer.valueOf(22), wi.get()); }
@Test public void testWaitForCreation() throws InterruptedException, KeeperException { final ZooKeeperPlus zk = getZk(); final String nodePath = ZkPath.append(getRoot(), "watchedNode"); WatchedInt wi = new WatchedInt(zk, nodePath, false); assertNull(wi.get()); Thread t = new Thread(() -> { try { // Wait before creating it Thread.sleep(2000); } catch (InterruptedException e) { throw new RuntimeException(e); } try { zk.create(nodePath, "42".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); } catch (KeeperException | InterruptedException e) { throw new RuntimeException(e); } }); // Try waiting t.start(); wi = new WatchedInt(zk, nodePath, true); assertEquals(Integer.valueOf(42), wi.get()); }
@Test public void testUpdate() throws InterruptedException, KeeperException { final ZooKeeperPlus zk = getZk(); final String nodePath = ZkPath.append(getRoot(), "watchedNode"); zk.create(nodePath, "0".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); final WatchedInt wi = new WatchedInt(zk, nodePath, true); assertEquals(Integer.valueOf(0), wi.get()); WatchedNodeUpdater<Integer> incrementer = current -> { if (current == null) { return 0; } else { return current + 1; } }; final int finalValue = 64; for (int i = 0; i < finalValue; ++i) { wi.update(incrementer); } WaitUntil.orDie(() -> Integer.valueOf(finalValue).equals(wi.get())); assertEquals(Integer.valueOf(finalValue), wi.get()); }
@Test public void testCreateAndWaitForCreation() throws InterruptedException, KeeperException { final ZooKeeperPlus zk = getZk(); final String nodePath = ZkPath.append(getRoot(), "watchedNode"); WatchedInt wi = new WatchedInt(zk, nodePath, true, CreateMode.PERSISTENT, 84, 0); assertEquals(Integer.valueOf(84), wi.get()); } }