Example usage for org.apache.zookeeper WatchedEvent getType

List of usage examples for org.apache.zookeeper WatchedEvent getType

Introduction

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

Prototype

public EventType getType() 

Source Link

Usage

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

License:Apache License

@Test
public void testRemoveCuratorWatch() throws Exception {
    Timing timing = new Timing();
    CuratorFrameworkImpl client = (CuratorFrameworkImpl) CuratorFrameworkFactory.builder()
            .connectString(server.getConnectString()).retryPolicy(new RetryOneTime(1)).build();
    try {/*from   w  w  w.j  a  va 2 s  .c om*/
        client.start();

        final CountDownLatch removedLatch = new CountDownLatch(1);

        final String path = "/";
        CuratorWatcher watcher = new CuratorWatcher() {

            @Override
            public void process(WatchedEvent event) throws Exception {
                if (event.getPath().equals(path) && event.getType() == EventType.DataWatchRemoved) {
                    removedLatch.countDown();
                }
            }
        };

        client.checkExists().usingWatcher(watcher).forPath(path);

        client.watches().remove(watcher).forPath(path);

        Assert.assertTrue(timing.awaitLatch(removedLatch), "Timed out waiting for watch removal");
    } finally {
        CloseableUtils.closeQuietly(client);
    }
}

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

License:Apache License

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

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

        final CountDownLatch latch = new CountDownLatch(1);
        Watcher watcher = new Watcher() {
            @Override
            public void process(WatchedEvent event) {
                if (event.getType() == Event.EventType.NodeCreated) {
                    latch.countDown();
                }
            }
        };

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

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

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

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 w w  .  j  a  va2 s  .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/*from   ww  w  . ja v  a 2s .c o  m*/
        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();//from   www .  java  2  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.locks.TestInterProcessSemaphore.java

License:Apache License

@Test
public void testNoOrphanedNodes() throws Exception {
    final Timing timing = new Timing();
    final ExecutorService executor = Executors.newFixedThreadPool(1);
    CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(),
            timing.connection(), new RetryOneTime(1));
    client.start();/*from   ww w  .ja v a  2 s.co m*/
    try {
        final InterProcessSemaphoreV2 semaphore = new InterProcessSemaphoreV2(client, "/test", 1);
        Lease lease = semaphore.acquire(timing.forWaiting().seconds(), TimeUnit.SECONDS);
        Assert.assertNotNull(lease);
        final List<String> childNodes = client.getChildren().forPath("/test/leases");
        Assert.assertEquals(childNodes.size(), 1);

        final CountDownLatch nodeCreatedLatch = new CountDownLatch(1);
        client.getChildren().usingWatcher(new CuratorWatcher() {
            @Override
            public void process(WatchedEvent event) throws Exception {
                if (event.getType() == Watcher.Event.EventType.NodeCreated) {
                    nodeCreatedLatch.countDown();
                }
            }
        }).forPath("/test/leases");

        final Future<Lease> leaseFuture = executor.submit(new Callable<Lease>() {
            @Override
            public Lease call() throws Exception {
                return semaphore.acquire(timing.forWaiting().multiple(2).seconds(), TimeUnit.SECONDS);
            }
        });

        // wait for second lease to create its node
        timing.awaitLatch(nodeCreatedLatch);
        String newNode = null;
        for (String c : client.getChildren().forPath("/test/leases")) {
            if (!childNodes.contains(c)) {
                newNode = c;
            }
        }
        Assert.assertNotNull(newNode);

        // delete the ephemeral node to trigger a retry
        client.delete().forPath("/test/leases/" + newNode);

        // release first lease so second one can be acquired
        lease.close();
        lease = leaseFuture.get();
        Assert.assertNotNull(lease);
        lease.close();
        Assert.assertEquals(client.getChildren().forPath("/test/leases").size(), 0);

        // no more lease exist. must be possible to acquire a new one
        Assert.assertNotNull(semaphore.acquire(timing.forWaiting().seconds(), TimeUnit.SECONDS));
    } finally {
        client.close();
        executor.shutdownNow();
    }
}

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);/*  w ww . j av  a2 s .  c om*/
    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.x.async.details.InternalWatcher.java

License:Apache License

@Override
public void process(WatchedEvent event) {
    final WatchedEvent localEvent = (watcherFilter != null) ? watcherFilter.apply(event) : event;
    switch (localEvent.getState()) {
    default: {//ww w. j a v a  2s.c o m
        if ((watchMode != WatchMode.stateChangeOnly) && (localEvent.getType() != Event.EventType.None)) {
            if (!future.complete(localEvent)) {
                future.obtrudeValue(localEvent);
            }
        }
        break;
    }

    case Disconnected:
    case AuthFailed:
    case Expired: {
        if (watchMode != WatchMode.successOnly) {
            AsyncEventException exception = new AsyncEventException() {
                private final AtomicBoolean isReset = new AtomicBoolean(false);

                @Override
                public Event.KeeperState getKeeperState() {
                    return localEvent.getState();
                }

                @Override
                public CompletionStage<WatchedEvent> reset() {
                    Preconditions.checkState(isReset.compareAndSet(false, true), "Already reset");
                    future = new CompletableFuture<>();
                    return future;
                }
            };
            future.completeExceptionally(exception);
        }
        break;
    }
    }
}

From source file:org.apache.curator.x.rpc.idl.structs.RpcCuratorEvent.java

License:Apache License

public RpcCuratorEvent(WatchedEvent event) {
    this.type = RpcCuratorEventType.WATCHED;
    this.resultCode = 0;
    this.path = event.getPath();
    this.context = null;
    this.stat = null;
    this.data = null;
    this.name = null;
    this.children = null;
    this.aclList = null;
    this.watchedEvent = new RpcWatchedEvent(RpcKeeperState.valueOf(event.getState().name()),
            RpcEventType.valueOf(event.getType().name()), event.getPath());
    this.leaderEvent = null;
    this.childrenCacheEvent = null;
}

From source file:org.apache.curator.x.rpc.idl.structs.RpcWatchedEvent.java

License:Apache License

public RpcWatchedEvent(WatchedEvent watchedEvent) {
    keeperState = RpcKeeperState.valueOf(watchedEvent.getState().name());
    eventType = RpcEventType.valueOf(watchedEvent.getType().name());
    path = watchedEvent.getPath();//from  ww w.  j  a v a 2  s .  co  m
}