Example usage for org.apache.zookeeper WatchedEvent getPath

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

Introduction

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

Prototype

public String getPath() 

Source Link

Usage

From source file:com.edmunds.zookeeper.treewatcher.ZooKeeperTreeWatcher.java

License:Apache License

private void processEvent(WatchedEvent event, ZooKeeperTreeState state) {
    final String path = event.getPath();
    final ZooKeeperTreeNode node = state.getNode(path);
    final Event.EventType eventType = event.getType();

    switch (eventType) {
    case NodeCreated:
        if (rootPath.equals(path)) {
            scanRootNode();/*  w ww.  java  2s.  co m*/
        } else {
            recoverableError(path, eventType, "Unexpected node Created");
        }
        break;
    case NodeDataChanged:
        if (node != null) {
            state.setFlags(path, false, node.isChildListConsistent());
            getData(path, null);
        } else {
            recoverableError(path, eventType, "Path is not tracked");
        }
        break;
    case NodeChildrenChanged:
        if (node != null) {
            state.setFlags(path, node.isDataConsistent(), false);
            getChildren(path, null);
        } else {
            recoverableError(path, eventType, "Path is not tracked");
        }
        break;
    case NodeDeleted:
        // Apply deletions immediately.
        if (node != null) {
            safeDelete(path);
        }
        break;
    default:
        unexpectedEventError(event);
        break;
    }
}

From source file:com.ery.estorm.zk.ZooKeeperWatcher.java

License:Apache License

/**
 * Method called from ZooKeeper for events and connection status.
 * <p>//from w  ww  .ja v  a2 s  . c om
 * Valid events are passed along to listeners. Connection status changes are
 * dealt with locally.
 */
@Override
public void process(WatchedEvent event) {

    String path = event.getPath();
    if (path != null || EventType.NodeDeleted == event.getType()) {
        try {
            ZKUtil.watchAndCheckExists(this, path);
        } catch (KeeperException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    LOG.debug(prefix("Received ZooKeeper Event, " + "type=" + event.getType() + ", " + "state="
            + event.getState() + ", " + "path=" + path));
    switch (event.getType()) {

    // If event type is NONE, this is a connection status change
    case None: {
        connectionEvent(event);
        break;
    }

    // Otherwise pass along to the listeners

    case NodeCreated: {
        for (ZooKeeperListener listener : listeners) {
            listener.nodeCreated(path);
        }
        break;
    }

    case NodeDeleted: {
        for (ZooKeeperListener listener : listeners) {
            listener.nodeDeleted(path);
        }
        break;
    }

    case NodeDataChanged: {
        for (ZooKeeperListener listener : listeners) {
            listener.nodeDataChanged(path);
        }
        break;
    }

    case NodeChildrenChanged: {
        for (ZooKeeperListener listener : listeners) {
            listener.nodeChildrenChanged(path);
        }
        break;
    }
    }
}

From source file:com.facebook.infrastructure.service.StorageService.java

License:Apache License

private void reportToZookeeper() throws Throwable {
    try {//from   w w  w.j  a v a 2s  .c om
        zk_ = new ZooKeeper(DatabaseDescriptor.getZkAddress(), DatabaseDescriptor.getZkSessionTimeout(),
                new Watcher() {
                    public void process(WatchedEvent we) {
                        String path = "/Cassandra/" + DatabaseDescriptor.getClusterName() + "/Leader";
                        String eventPath = we.getPath();
                        logger_.debug("PROCESS EVENT : " + eventPath);
                        if (eventPath != null && (eventPath.indexOf(path) != -1)) {
                            logger_.debug("Signalling the leader instance ...");
                            LeaderElector.instance().signal();
                        }
                    }
                });

        Stat stat = zk_.exists("/", false);
        if (stat != null) {
            stat = zk_.exists("/Cassandra", false);
            if (stat == null) {
                logger_.debug("Creating the Cassandra znode ...");
                zk_.create("/Cassandra", new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
            }

            String path = "/Cassandra/" + DatabaseDescriptor.getClusterName();
            stat = zk_.exists(path, false);
            if (stat == null) {
                logger_.debug("Creating the cluster znode " + path);
                zk_.create(path, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
            }

            /* Create the Leader, Locks and Misc znode */
            stat = zk_.exists(path + "/Leader", false);
            if (stat == null) {
                logger_.debug("Creating the leader znode " + path);
                zk_.create(path + "/Leader", new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
            }

            stat = zk_.exists(path + "/Locks", false);
            if (stat == null) {
                logger_.debug("Creating the locks znode " + path);
                zk_.create(path + "/Locks", new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
            }

            stat = zk_.exists(path + "/Misc", false);
            if (stat == null) {
                logger_.debug("Creating the misc znode " + path);
                zk_.create(path + "/Misc", new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
            }
        }
    } catch (KeeperException ke) {
        LogUtil.throwableToString(ke);
        /* do the re-initialize again. */
        reportToZookeeper();
    }
}

From source file:com.facebook.zookeeper.election.TestZkLeaderElection.java

License:Apache License

@Test(groups = "fast")
public void testEnter() throws Exception {
    // Verify no candidates
    MockWatcher mockWatcher = new MockWatcher();
    List<String> candidates = zk1.getChildren(electionRoot, mockWatcher);
    Assert.assertTrue(candidates.isEmpty());

    // Enter the candidate and run any callbacks
    zkLeaderElection1.enter();/*from  w ww . j  a v  a 2s .co m*/
    mockExecutor1.drain();

    // Check that candidate is created
    candidates = zk1.getChildren(electionRoot, null);
    Assert.assertEquals(candidates.size(), 1);

    // Check that candidate is elected
    Assert.assertTrue(mockLeaderElectionCallback1.isElected());
    mockLeaderElectionCallback1.resetElected();
    Assert.assertEquals(zkLeaderElection1.getLeader(), candidates.get(0));

    // Check data contents
    String data = VariablePayload.decode(zk1.getData(electionRoot + "/" + candidates.get(0), null, null));
    Assert.assertEquals(data, testData1);

    // Check that external watch was notified of candidate creation
    Assert.assertEquals(mockWatcher.getEventQueue().size(), 1);
    WatchedEvent watchedEvent = mockWatcher.getEventQueue().remove();
    Assert.assertEquals(watchedEvent.getType(), EventType.NodeChildrenChanged);
    Assert.assertEquals(watchedEvent.getPath(), electionRoot);
}

From source file:com.facebook.zookeeper.election.TestZkLeaderElection.java

License:Apache License

@Test(groups = "fast")
public void testWithdraw() throws Exception {
    zkLeaderElection1.enter();/*w  ww  . j a  v a 2 s  .  c  o  m*/
    mockExecutor1.drain();

    // Verify candidate
    MockWatcher mockWatcher = new MockWatcher();
    List<String> candidates = zk1.getChildren(electionRoot, mockWatcher);
    Assert.assertEquals(candidates.size(), 1);
    Assert.assertTrue(mockLeaderElectionCallback1.isElected());
    mockLeaderElectionCallback1.resetElected();

    zkLeaderElection1.withdraw();
    mockExecutor1.drain();

    candidates = zk1.getChildren(electionRoot, null);
    Assert.assertTrue(candidates.isEmpty());
    Assert.assertEquals(zkLeaderElection1.getLeader(), null);
    // Manual withdraw should not trigger a "removed" callback
    Assert.assertFalse(mockLeaderElectionCallback1.isRemoved());
    Assert.assertEquals(mockWatcher.getEventQueue().size(), 1);
    WatchedEvent watchedEvent = mockWatcher.getEventQueue().remove();
    Assert.assertEquals(watchedEvent.getType(), EventType.NodeChildrenChanged);
    Assert.assertEquals(watchedEvent.getPath(), electionRoot);
}

From source file:com.fjn.helper.frameworkex.apache.zookeeper.dispatcher.Dispatcher.java

License:Apache License

@Override
public void process(WatchedEvent event) {
    event.getPath();
    event.getState();
    event.getType();

}

From source file:com.fjn.helper.frameworkex.apache.zookeeper.dispatcher.Dispatcher.java

License:Apache License

void accept(WatchedEvent event) {
    boolean stateChanged = event.getPath() == null;
    boolean znodeChanged = event.getPath() != null;
    boolean dataChanged = event.getType() == EventType.NodeDataChanged
            || event.getType() == EventType.NodeDeleted || event.getType() == EventType.NodeCreated
            || event.getType() == EventType.NodeChildrenChanged;

    if (stateChanged) {
        if (event.getState() == KeeperState.Expired) {
            selector.addEvent(new Event(ServiceType.SESSION, new SourceWrapper(event)));
        }//from  w  w  w  .  j a va2s .  c om
    }

    if (znodeChanged) {

    }

    if (dataChanged) {

    }
}

From source file:com.github.liyp.zk.demo.ZkElector.java

License:Apache License

@Override
public void process(WatchedEvent event) {
    logger.info("ZK path ,state , type: {}",
            event.getPath() + " " + event.getState() + " " + event.getType() + "    #" + zookeeper.hashCode());
    switch (event.getType()) {
    case NodeChildrenChanged:
    case NodeCreated:
    case NodeDataChanged:
        break;//from w  ww  . j  av  a2 s.  co m
    case NodeDeleted:
        try {
            newLeaderElection();
        } catch (KeeperException | InterruptedException e) {
            logger.error("New leader election failed.", e);
        }
        break;
    case None:
        switch (event.getState()) {
        case Disconnected:
            logger.info("ZK path {} Disconnected.", event.getPath());
            break;
        case Expired:
            logger.info("ZK path {} Expired.", event.getPath());

            taskServer.shutdown();
            try {
                this.zookeeper = new ZooKeeper(zkAddress, zkTimeout, this);
                elected.set(true);
            } catch (IOException e) {
                logger.info("{}", this.hashCode(), e);
            }
            break;
        case SyncConnected:
            logger.info("ZK path {} SyncConnected.", event.getPath());
            try {
                if (elected.get()) {
                    leaderElection();
                    elected.set(false);
                }
            } catch (KeeperException | InterruptedException e) {
                logger.error("ZK path rebuild error.", e);
            } catch (Exception e) {
                logger.info("{}", this.hashCode(), e);
            }
            break;
        default:
            logger.info("ZK path {}, state {}", event.getPath(), event.getState());
            break;
        }
        break;
    }
}

From source file:com.github.zkclient.ZkClient.java

License:Apache License

public void process(WatchedEvent event) {
    LOG.debug("Received event: " + event);
    _zookeeperEventThread = Thread.currentThread();

    boolean stateChanged = event.getPath() == null;
    boolean znodeChanged = event.getPath() != null;
    boolean dataChanged = event.getType() == EventType.NodeDataChanged || //
            event.getType() == EventType.NodeDeleted || event.getType() == EventType.NodeCreated || //
            event.getType() == EventType.NodeChildrenChanged;

    getEventLock().lock();//from  w  w w.  j  av a 2s. c  om
    try {

        // We might have to install child change event listener if a new node was created
        if (getShutdownTrigger()) {
            LOG.debug("ignoring event '{" + event.getType() + " | " + event.getPath()
                    + "}' since shutdown triggered");
            return;
        }
        if (stateChanged) {
            processStateChanged(event);
        }
        if (dataChanged) {
            processDataOrChildChange(event);
        }
    } finally {
        if (stateChanged) {
            getEventLock().getStateChangedCondition().signalAll();

            // If the session expired we have to signal all conditions, because watches might have been removed and
            // there is no guarantee that those
            // conditions will be signaled at all after an Expired event
            if (event.getState() == KeeperState.Expired) {
                getEventLock().getZNodeEventCondition().signalAll();
                getEventLock().getDataChangedCondition().signalAll();
                // We also have to notify all listeners that something might have changed
                fireAllEvents();
            }
        }
        if (znodeChanged) {
            getEventLock().getZNodeEventCondition().signalAll();
        }
        if (dataChanged) {
            getEventLock().getDataChangedCondition().signalAll();
        }
        getEventLock().unlock();
        LOG.debug("Leaving process event");
    }
}

From source file:com.glaf.cluster.catalina.session.ZooKeeperClientImpl.java

License:Apache License

private Watcher wrapNodeListener(final NodeListener nodeListener) {
    if (nodeListener != null) {
        return new Watcher() {
            @Override// w  ww.  j  av  a2  s .  com
            public void process(WatchedEvent event) {
                switch (event.getType()) {
                case NodeCreated:
                    nodeListener.onNodeCreated(event.getPath());
                    break;
                case NodeDeleted:
                    nodeListener.onNodeDeleted(event.getPath());
                    break;
                case NodeDataChanged:
                    nodeListener.onNodeDataChanged(event.getPath());
                    break;
                default:
                    break;
                }
            }
        };
    } else {
        return null;
    }
}