Example usage for org.apache.zookeeper Watcher Watcher

List of usage examples for org.apache.zookeeper Watcher Watcher

Introduction

In this page you can find the example usage for org.apache.zookeeper Watcher Watcher.

Prototype

Watcher

Source Link

Usage

From source file:org.apache.curator.framework.imps.TestWatcherRemovalManager.java

License:Apache License

@Test
public void testResetFromWatcher() throws Exception {
    Timing timing = new Timing();
    CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1));
    try {/*from w  ww  . j a  v a  2s . c o m*/
        client.start();

        final WatcherRemovalFacade removerClient = (WatcherRemovalFacade) client
                .newWatcherRemoveCuratorFramework();

        final CountDownLatch createdLatch = new CountDownLatch(1);
        final CountDownLatch deletedLatch = new CountDownLatch(1);
        Watcher watcher = new Watcher() {
            @Override
            public void process(WatchedEvent event) {
                if (event.getType() == Event.EventType.NodeCreated) {
                    try {
                        removerClient.checkExists().usingWatcher(this).forPath("/yo");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    createdLatch.countDown();
                } else if (event.getType() == Event.EventType.NodeDeleted) {
                    deletedLatch.countDown();
                }
            }
        };

        removerClient.checkExists().usingWatcher(watcher).forPath("/yo");
        Assert.assertEquals(removerClient.getRemovalManager().getEntries().size(), 1);
        removerClient.create().forPath("/yo");

        Assert.assertTrue(timing.awaitLatch(createdLatch));
        Assert.assertEquals(removerClient.getRemovalManager().getEntries().size(), 1);

        removerClient.delete().forPath("/yo");

        Assert.assertTrue(timing.awaitLatch(deletedLatch));

        Assert.assertEquals(removerClient.getRemovalManager().getEntries().size(), 0);
    } finally {
        TestCleanState.closeAndTestClean(client);
    }
}

From source file:org.apache.curator.framework.imps.TestWatcherRemovalManager.java

License:Apache License

private void internalTryBasic(CuratorFramework client) throws Exception {
    WatcherRemoveCuratorFramework removerClient = client.newWatcherRemoveCuratorFramework();

    final CountDownLatch latch = new CountDownLatch(1);
    Watcher watcher = new Watcher() {
        @Override/* w  w  w.j ava  2 s .c om*/
        public void process(WatchedEvent event) {
            if (event.getType() == Event.EventType.DataWatchRemoved) {
                latch.countDown();
            }
        }
    };
    removerClient.checkExists().usingWatcher(watcher).forPath("/hey");

    List<String> existWatches = WatchersDebug.getExistWatches(client.getZookeeperClient().getZooKeeper());
    Assert.assertEquals(existWatches.size(), 1);

    removerClient.removeWatchers();

    Assert.assertTrue(new Timing().awaitLatch(latch));

    existWatches = WatchersDebug.getExistWatches(client.getZookeeperClient().getZooKeeper());
    Assert.assertEquals(existWatches.size(), 0);
}

From source file:org.apache.curator.framework.recipes.leader.LeaderLatch.java

License:Apache License

private void checkLeadership(List<String> children) throws Exception {
    final String localOurPath = ourPath.get();
    List<String> sortedChildren = LockInternals.getSortedChildren(LOCK_NAME, sorter, children);
    int ourIndex = (localOurPath != null) ? sortedChildren.indexOf(ZKPaths.getNodeFromPath(localOurPath)) : -1;
    if (ourIndex < 0) {
        log.error("Can't find our node. Resetting. Index: " + ourIndex);
        reset();/*  w ww . j a v a2 s. c o m*/
    } else if (ourIndex == 0) {
        setLeadership(true);
    } else {
        String watchPath = sortedChildren.get(ourIndex - 1);
        Watcher watcher = new Watcher() {
            @Override
            public void process(WatchedEvent event) {
                if ((state.get() == State.STARTED) && (event.getType() == Event.EventType.NodeDeleted)
                        && (localOurPath != null)) {
                    try {
                        getChildren();
                    } catch (Exception ex) {
                        ThreadUtils.checkInterrupted(ex);
                        log.error("An error occurred checking the leadership.", ex);
                    }
                }
            }
        };

        BackgroundCallback callback = new BackgroundCallback() {
            @Override
            public void processResult(CuratorFramework client, CuratorEvent event) throws Exception {
                if (event.getResultCode() == KeeperException.Code.NONODE.intValue()) {
                    // previous node is gone - reset
                    reset();
                }
            }
        };
        // use getData() instead of exists() to avoid leaving unneeded watchers which is a type of resource leak
        client.getData().usingWatcher(watcher).inBackground(callback)
                .forPath(ZKPaths.makePath(latchPath, watchPath));
    }
}

From source file:org.apache.curator.framework.recipes.nodes.TestPersistentEphemeralNode.java

License:Apache License

protected void setDataTest(PersistentEphemeralNode.Mode mode) throws Exception {
    PersistentEphemeralNode node = null;
    CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(),
            timing.connection(), new RetryOneTime(1));
    try {/*from  w  w w.j a v  a 2s . c  om*/
        client.start();
        node = new PersistentEphemeralNode(client, mode, PATH, "a".getBytes());
        node.start();
        Assert.assertTrue(node.waitForInitialCreate(timing.forWaiting().seconds(), TimeUnit.SECONDS));

        Assert.assertEquals(client.getData().forPath(node.getActualPath()), "a".getBytes());

        final Semaphore semaphore = new Semaphore(0);
        Watcher watcher = new Watcher() {
            @Override
            public void process(WatchedEvent arg0) {
                semaphore.release();
            }
        };
        client.checkExists().usingWatcher(watcher).forPath(node.getActualPath());
        node.setData("b".getBytes());
        Assert.assertTrue(timing.acquireSemaphore(semaphore));
        Assert.assertEquals(node.getActualPath(), node.getActualPath());
        Assert.assertEquals(client.getData().usingWatcher(watcher).forPath(node.getActualPath()),
                "b".getBytes());
        node.setData("c".getBytes());
        Assert.assertTrue(timing.acquireSemaphore(semaphore));
        Assert.assertEquals(node.getActualPath(), node.getActualPath());
        Assert.assertEquals(client.getData().usingWatcher(watcher).forPath(node.getActualPath()),
                "c".getBytes());
        node.close();
        Assert.assertTrue(timing.acquireSemaphore(semaphore));
    } finally {
        if (node != null) {
            node.close();
        }
        client.close();
    }
}

From source file:org.apache.curator.framework.recipes.nodes.TestPersistentEphemeralNode.java

License:Apache License

@Test
public void testSetDataWhenDisconnected() throws Exception {
    CuratorFramework curator = newCurator();

    byte[] initialData = "Hello World".getBytes();
    byte[] updatedData = "Updated".getBytes();

    PersistentEphemeralNode node = new PersistentEphemeralNode(curator, PersistentEphemeralNode.Mode.EPHEMERAL,
            PATH, initialData);/*  ww  w .  java 2s .  c o m*/
    node.start();
    try {
        node.waitForInitialCreate(timing.forWaiting().seconds(), TimeUnit.SECONDS);
        assertTrue(Arrays.equals(curator.getData().forPath(node.getActualPath()), initialData));

        server.stop();

        final CountDownLatch dataUpdateLatch = new CountDownLatch(1);

        Watcher watcher = new Watcher() {
            @Override
            public void process(WatchedEvent event) {
                if (event.getType() == EventType.NodeDataChanged) {
                    dataUpdateLatch.countDown();
                }
            }
        };

        curator.getData().usingWatcher(watcher).inBackground().forPath(node.getActualPath());

        node.setData(updatedData);
        server.restart();

        assertTrue(timing.awaitLatch(dataUpdateLatch));

        assertTrue(Arrays.equals(curator.getData().forPath(node.getActualPath()), updatedData));
    } finally {
        node.close();
    }
}

From source file:org.apache.curator.framework.recipes.queue.SimpleDistributedQueue.java

License:Apache License

private byte[] internalPoll(long timeout, TimeUnit unit) throws Exception {
    ensurePath();//from www .j av  a 2  s .c o m

    long startMs = System.currentTimeMillis();
    boolean hasTimeout = (unit != null);
    long maxWaitMs = hasTimeout ? TimeUnit.MILLISECONDS.convert(timeout, unit) : Long.MAX_VALUE;
    for (;;) {
        final CountDownLatch latch = new CountDownLatch(1);
        Watcher watcher = new Watcher() {
            @Override
            public void process(WatchedEvent event) {
                latch.countDown();
            }
        };
        byte[] bytes = internalElement(true, watcher);
        if (bytes != null) {
            return bytes;
        }

        if (hasTimeout) {
            long elapsedMs = System.currentTimeMillis() - startMs;
            long thisWaitMs = maxWaitMs - elapsedMs;
            if (thisWaitMs <= 0) {
                return null;
            }
            latch.await(thisWaitMs, TimeUnit.MILLISECONDS);
        } else {
            latch.await();
        }
    }
}

From source file:org.apache.curator.framework.recipes.queue.TestBoundedDistributedQueue.java

License:Apache License

@SuppressWarnings("SynchronizationOnLocalVariableOrMethodParameter")
@Test//from w w w  .j a  v a  2s  .co m
public void testMulti() throws Exception {
    final String PATH = "/queue";
    final int CLIENT_QTY = 4;
    final int MAX_ITEMS = 10;
    final int ADD_ITEMS = MAX_ITEMS * 100;

    final QueueConsumer<String> consumer = new QueueConsumer<String>() {
        @Override
        public void consumeMessage(String message) throws Exception {
            Thread.sleep(10);
        }

        @Override
        public void stateChanged(CuratorFramework client, ConnectionState newState) {
        }
    };

    final Timing timing = new Timing();
    final ExecutorService executor = Executors.newCachedThreadPool();
    ExecutorCompletionService<Void> completionService = new ExecutorCompletionService<Void>(executor);

    final CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(),
            timing.session(), timing.connection(), new RetryOneTime(1));
    try {
        client.start();
        client.create().forPath(PATH);

        final CountDownLatch isWaitingLatch = new CountDownLatch(1);
        final AtomicBoolean isDone = new AtomicBoolean(false);
        final List<Integer> counts = new CopyOnWriteArrayList<Integer>();
        final Object lock = new Object();
        executor.submit(new Callable<Void>() {
            @Override
            public Void call() throws Exception {
                Watcher watcher = new Watcher() {
                    @Override
                    public void process(WatchedEvent event) {
                        synchronized (lock) {
                            lock.notifyAll();
                        }
                    }
                };

                while (!Thread.currentThread().isInterrupted()
                        && client.getState() == CuratorFrameworkState.STARTED && !isDone.get()) {
                    synchronized (lock) {
                        int size = client.getChildren().usingWatcher(watcher).forPath(PATH).size();
                        counts.add(size);
                        isWaitingLatch.countDown();
                        lock.wait();
                    }
                }
                return null;
            }
        });
        isWaitingLatch.await();

        for (int i = 0; i < CLIENT_QTY; ++i) {
            final int index = i;
            completionService.submit(new Callable<Void>() {
                @Override
                public Void call() throws Exception {
                    CuratorFramework client = null;
                    DistributedQueue<String> queue = null;

                    try {
                        client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(),
                                timing.connection(), new RetryOneTime(1));
                        client.start();
                        queue = QueueBuilder.builder(client, consumer, serializer, PATH).executor(executor)
                                .maxItems(MAX_ITEMS).putInBackground(false).lockPath("/locks").buildQueue();
                        queue.start();

                        for (int i = 0; i < ADD_ITEMS; ++i) {
                            queue.put("" + index + "-" + i);
                        }
                    } finally {
                        CloseableUtils.closeQuietly(queue);
                        CloseableUtils.closeQuietly(client);
                    }
                    return null;
                }
            });
        }

        for (int i = 0; i < CLIENT_QTY; ++i) {
            completionService.take().get();
        }

        isDone.set(true);
        synchronized (lock) {
            lock.notifyAll();
        }

        for (int count : counts) {
            Assert.assertTrue(count <= (MAX_ITEMS * CLIENT_QTY), counts.toString());
        }
    } finally {
        executor.shutdownNow();
        CloseableUtils.closeQuietly(client);
    }
}

From source file:org.apache.curator.HandleHolder.java

License:Apache License

private void internalClose() throws Exception {
    try {/* w  ww .  ja v a2s  . c  o m*/
        ZooKeeper zooKeeper = (helper != null) ? helper.getZooKeeper() : null;
        if (zooKeeper != null) {
            Watcher dummyWatcher = new Watcher() {
                @Override
                public void process(WatchedEvent event) {
                }
            };
            zooKeeper.register(dummyWatcher); // clear the default watcher so that no new events get processed by mistake
            zooKeeper.close();
        }
    } catch (InterruptedException dummy) {
        Thread.currentThread().interrupt();
    }
}

From source file:org.apache.curator.x.rpc.RpcTests.java

License:Apache License

@Test
public void testEphemeralCleanup() throws Exception {
    CuratorProjection curatorProjection = curatorServiceClient.newCuratorProjection("test");
    CreateSpec spec = new CreateSpec();
    spec.path = "/test";
    spec.data = ByteBuffer.wrap("value".getBytes());
    spec.mode = CreateMode.EPHEMERAL;//from   ww  w .j  av  a2  s.c  om
    OptionalPath node = curatorServiceClient.createNode(curatorProjection, spec);
    System.out.println(node);

    final CountDownLatch latch = new CountDownLatch(1);
    CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1));
    try {
        client.start();
        Watcher watcher = new Watcher() {
            @Override
            public void process(WatchedEvent event) {
                if (event.getType() == Event.EventType.NodeDeleted) {
                    latch.countDown();
                }
            }
        };
        client.checkExists().usingWatcher(watcher).forPath("/test");

        curatorServiceClient.closeCuratorProjection(curatorProjection);

        Assert.assertTrue(timing.awaitLatch(latch));
    } finally {
        CloseableUtils.closeQuietly(client);
    }
}

From source file:org.apache.distributedlog.service.placement.ZKPlacementStateManager.java

License:Apache License

@Override
public synchronized void watch(final PlacementCallback callback) {
    if (watching) {
        return; // do not double watch
    }//from w w w .j a v a 2 s  . c  om
    watching = true;

    try {
        ZooKeeper zk = zkClient.get();
        try {
            zk.getData(serverLoadPath, new Watcher() {
                @Override
                public void process(WatchedEvent watchedEvent) {
                    try {
                        callback.callback(loadOwnership());
                    } catch (StateManagerLoadException e) {
                        logger.error("Watch of Ownership failed", e);
                    } finally {
                        watching = false;
                        watch(callback);
                    }
                }
            }, new Stat());
        } catch (KeeperException.NoNodeException nee) {
            byte[] timestamp = ByteBuffer.allocate(8).putLong(System.currentTimeMillis()).array();
            createServerLoadPathIfNoExists(timestamp);
            watching = false;
            watch(callback);
        }
    } catch (InterruptedException | IOException | KeeperException e) {
        logger.error("Watch of Ownership failed", e);
        watching = false;
        watch(callback);
    }
}