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:zookeeper.recipes.leader.LeaderLatch.java

License:Apache License

private void checkLeadership(List<String> children) throws Exception {
    List<String> sortedChildren = LockInternals.getSortedChildren(LOCK_NAME, sorter, children);
    int ourIndex = (ourPath != null) ? sortedChildren.indexOf(ZKPaths.getNodeFromPath(ourPath)) : -1;
    if (ourIndex < 0) {
        log.error("Can't find our node. Resetting. Index: " + ourIndex);
        reset();// w ww .  j  a v  a2s  .  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)
                        && (ourPath != null)) {
                    try {
                        getChildren();
                    } catch (Exception 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();
                }
            }
        };
        client.checkExists().usingWatcher(watcher).inBackground(callback)
                .forPath(ZKPaths.makePath(latchPath, watchPath));
    }
}