Example usage for org.apache.zookeeper KeeperException code

List of usage examples for org.apache.zookeeper KeeperException code

Introduction

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

Prototype

Code code

To view the source code for org.apache.zookeeper KeeperException code.

Click Source Link

Usage

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

License:Apache License

@Test
public void testErrors() throws Exception {
    CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1));
    try {//from  w w w  .j  av a 2 s . c  o m
        client.start();
        CuratorOp createOp1 = client.transactionOp().create().forPath("/bar");
        CuratorOp createOp2 = client.transactionOp().create().forPath("/z/blue");
        final BlockingQueue<CuratorEvent> callbackQueue = new LinkedBlockingQueue<>();
        BackgroundCallback callback = new BackgroundCallback() {
            @Override
            public void processResult(CuratorFramework client, CuratorEvent event) throws Exception {
                callbackQueue.add(event);
            }
        };
        client.transaction().inBackground(callback).forOperations(createOp1, createOp2);
        CuratorEvent event = callbackQueue.poll(new Timing().milliseconds(), TimeUnit.MILLISECONDS);
        Assert.assertNotNull(event);
        Assert.assertNotNull(event.getOpResults());
        Assert.assertEquals(event.getOpResults().size(), 2);
        Assert.assertEquals(event.getOpResults().get(0).getError(), KeeperException.Code.OK.intValue());
        Assert.assertEquals(event.getOpResults().get(1).getError(), KeeperException.Code.NONODE.intValue());
    } finally {
        CloseableUtils.closeQuietly(client);
    }
}

From source file:org.apache.curator.framework.recipes.cache.PathChildrenCache.java

License:Apache License

void refresh(final RefreshMode mode) throws Exception {
    ensurePath();/*from  www  .ja v a 2 s .  co m*/

    final BackgroundCallback callback = new BackgroundCallback() {
        @Override
        public void processResult(CuratorFramework client, CuratorEvent event) throws Exception {
            if (PathChildrenCache.this.state.get().equals(State.CLOSED)) {
                // This ship is closed, don't handle the callback
                return;
            }
            if (event.getResultCode() == KeeperException.Code.OK.intValue()) {
                processChildren(event.getChildren(), mode);
            }
        }
    };

    client.getChildren().usingWatcher(childrenWatcher).inBackground(callback).forPath(path);
}

From source file:org.apache.curator.framework.recipes.cache.PathChildrenCache.java

License:Apache License

private void applyNewData(String fullPath, int resultCode, Stat stat, byte[] bytes) {
    if (resultCode == KeeperException.Code.OK.intValue()) // otherwise - node must have dropped or something - we should be getting another event
    {//from   w ww .j  a v  a  2  s  . c o m
        ChildData data = new ChildData(fullPath, stat, bytes);
        ChildData previousData = currentData.put(fullPath, data);
        if (previousData == null) // i.e. new
        {
            offerOperation(new EventOperation(this,
                    new PathChildrenCacheEvent(PathChildrenCacheEvent.Type.CHILD_ADDED, data)));
        } else if (stat.getMzxid() != previousData.getStat().getMzxid()) {
            offerOperation(new EventOperation(this,
                    new PathChildrenCacheEvent(PathChildrenCacheEvent.Type.CHILD_UPDATED, data)));
        }
        updateInitialSet(ZKPaths.getNodeFromPath(fullPath), data);
    }
}

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

License:Apache License

@VisibleForTesting
void reset() throws Exception {
    setLeadership(false);/*from   w w w.j av a  2 s . c  om*/
    setNode(null);

    BackgroundCallback callback = new BackgroundCallback() {
        @Override
        public void processResult(CuratorFramework client, CuratorEvent event) throws Exception {
            if (debugResetWaitLatch != null) {
                debugResetWaitLatch.await();
                debugResetWaitLatch = null;
            }

            if (event.getResultCode() == KeeperException.Code.OK.intValue()) {
                setNode(event.getName());
                if (state.get() == State.CLOSED) {
                    setNode(null);
                } else {
                    getChildren();
                }
            } else {
                log.error("getChildren() failed. rc = " + event.getResultCode());
            }
        }
    };
    client.create().creatingParentContainersIfNeeded().withProtection()
            .withMode(CreateMode.EPHEMERAL_SEQUENTIAL).inBackground(callback)
            .forPath(ZKPaths.makePath(latchPath, LOCK_NAME), LeaderSelector.getIdBytes(id));
}

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   ww  w . j a  v  a 2  s.  c om
    } 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.leader.LeaderLatch.java

License:Apache License

private void getChildren() throws Exception {
    BackgroundCallback callback = new BackgroundCallback() {
        @Override/*from   w  w  w  . j  av  a  2 s .  c om*/
        public void processResult(CuratorFramework client, CuratorEvent event) throws Exception {
            if (event.getResultCode() == KeeperException.Code.OK.intValue()) {
                checkLeadership(event.getChildren());
            }
        }
    };
    client.getChildren().inBackground(callback).forPath(ZKPaths.makePath(latchPath, null));
}

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

License:Apache License

/**
 * Create a protected node in background with a retry policy
 *///from w ww . j  a  va  2  s. co  m
@Test
public void createProtectedNodeInBackgroundTest() throws Exception {
    final CuratorFramework client = CuratorFrameworkFactory.builder().connectString(server.getConnectString())
            .retryPolicy(new RetryNTimes(2, 1)).connectionTimeoutMs(100).sessionTimeoutMs(60000).build();
    final CountDownLatch latch = new CountDownLatch(1);
    client.start();
    try {
        client.create().forPath(ChaosMonkeyCnxnFactory.CHAOS_ZNODE);
        client.create().withProtection().withMode(CreateMode.EPHEMERAL_SEQUENTIAL)
                .inBackground(new BackgroundCallback() {
                    public void processResult(CuratorFramework client, CuratorEvent event) throws Exception {
                        log.info("Receive event {}", event.toString());
                        if (event.getResultCode() == KeeperException.Code.CONNECTIONLOSS.intValue()) {
                            latch.countDown();
                        }
                    }
                }).forPath(ChaosMonkeyCnxnFactory.CHAOS_ZNODE_PREFIX + "foo-");

        Assert.assertTrue(latch.await(30, TimeUnit.SECONDS), "Callback has not been called");
        // Wait for the znode to be deleted
        Thread.sleep(ChaosMonkeyCnxnFactory.LOCKOUT_DURATION_MS * 2);
        // Check that there is no znode
        final int children = client.getChildren().forPath(ChaosMonkeyCnxnFactory.CHAOS_ZNODE).size();
        Assert.assertEquals(children, 0,
                "Still " + children + " znodes under " + ChaosMonkeyCnxnFactory.CHAOS_ZNODE + " lock");
    } finally {
        client.close();
    }

}

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

License:Apache License

/**
 * Same test as above but without a retry policy
 */// www.j  a va2s  .c  o m
@Test
public void createProtectedNodeInBackgroundTestNoRetry() throws Exception {
    final CuratorFramework client = CuratorFrameworkFactory.builder().connectString(server.getConnectString())
            .retryPolicy(new RetryNTimes(0, 0)).connectionTimeoutMs(100).sessionTimeoutMs(60000).build();
    final CountDownLatch latch = new CountDownLatch(1);
    client.start();
    try {
        client.create().forPath(ChaosMonkeyCnxnFactory.CHAOS_ZNODE);
        client.create().withProtection().withMode(CreateMode.EPHEMERAL_SEQUENTIAL)
                .inBackground(new BackgroundCallback() {
                    public void processResult(CuratorFramework client, CuratorEvent event) throws Exception {
                        log.info("Receive event {}", event.toString());
                        if (event.getResultCode() == KeeperException.Code.CONNECTIONLOSS.intValue()) {
                            latch.countDown();
                        }
                    }
                }).forPath(ChaosMonkeyCnxnFactory.CHAOS_ZNODE_PREFIX + "foo-");

        Assert.assertTrue(latch.await(30, TimeUnit.SECONDS), "Callback has not been called");
        // Wait for the znode to be deleted
        Thread.sleep(ChaosMonkeyCnxnFactory.LOCKOUT_DURATION_MS * 2);
        // Check that there is no znode
        final int children = client.getChildren().forPath(ChaosMonkeyCnxnFactory.CHAOS_ZNODE).size();
        Assert.assertEquals(children, 0,
                "Still " + children + " znodes under " + ChaosMonkeyCnxnFactory.CHAOS_ZNODE + " lock");
    } finally {
        client.close();
    }

}

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

License:Apache License

private void processBackgroundCallbackClosedState(CuratorEvent event) {
    String path = null;/*from   ww  w .  j a va 2  s  .  co  m*/
    if (event.getResultCode() == KeeperException.Code.NODEEXISTS.intValue()) {
        path = event.getPath();
    } else if (event.getResultCode() == KeeperException.Code.OK.intValue()) {
        path = event.getName();
    }

    if (path != null) {
        try {
            client.delete().guaranteed().inBackground().forPath(path);
        } catch (Exception e) {
            log.error("Could not delete node after close", e);
        }
    }
}

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

License:Apache License

private void processBackgroundCallback(CuratorEvent event) throws Exception {
    String path = null;//from   w w  w. j av a  2  s .  c  o  m
    boolean nodeExists = false;
    if (event.getResultCode() == KeeperException.Code.NODEEXISTS.intValue()) {
        path = event.getPath();
        nodeExists = true;
    } else if (event.getResultCode() == KeeperException.Code.OK.intValue()) {
        path = event.getName();
    } else if (event.getResultCode() == KeeperException.Code.NOAUTH.intValue()) {
        log.warn("Client does not have authorisation to create node at path {}", event.getPath());
        authFailure.set(true);
        return;
    }
    if (path != null) {
        authFailure.set(false);
        nodePath.set(path);
        watchNode();

        if (nodeExists) {
            client.setData().inBackground(setDataCallback).forPath(getActualPath(), getData());
        } else {
            initialisationComplete();
        }
    } else {
        createNode();
    }
}