List of usage examples for org.apache.zookeeper Watcher Watcher
Watcher
From source file:com.example.directorio.ZooKeeperMannager.java
public String getData(String path2) throws InterruptedException, KeeperException, UnsupportedEncodingException { final String path = path2; Stat stat = znode_exists(path);//from ww w. j av a2 s. c o m byte[] b = null; if (stat != null) { b = zk.getData(path, new Watcher() { public void process(WatchedEvent we) { if (we.getType() == Event.EventType.None) { switch (we.getState()) { case Expired: zkConnection.getConnectedSignal().countDown(); break; } } else { try { byte[] bn = zk.getData(path, false, null); String data = new String(bn, "UTF-8"); System.out.println(data); zkConnection.getConnectedSignal().countDown(); } catch (Exception ex) { ex.printStackTrace(); } } } }, null); String data = new String(b, "UTF-8"); //System.out.println(data); zkConnection.getConnectedSignal().await(); } else { System.out.println("Node does not exists"); } return new String(b); }
From source file:com.facebook.infrastructure.service.StorageService.java
License:Apache License
private void reportToZookeeper() throws Throwable { try {/*from ww w . ja v a 2 s.c o m*/ 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.convenience.ZkQuickConnection.java
License:Apache License
private ZkQuickConnection(ZooKeeperFactory zooKeeperFactory, int connectionTimeoutMillis) throws IOException, InterruptedException, TimeoutException { final CountDownLatch latch = new CountDownLatch(1); zk = zooKeeperFactory.create(new Watcher() { @Override/*from ww w. j ava 2 s.co m*/ public void process(WatchedEvent event) { if (event.getState() == Watcher.Event.KeeperState.SyncConnected) { latch.countDown(); } } }); if (!latch.await(connectionTimeoutMillis, TimeUnit.MILLISECONDS)) { zk.close(); throw new TimeoutException("Failed to connect to ZooKeeper"); } }
From source file:com.facebook.zookeeper.mock.MockZkConnectionManager.java
License:Apache License
public void refreshClient() { try {//from ww w . j av a 2 s . c o m if (zk != null) { zk.close(); } zk = zooKeeperFactory.create(new Watcher() { @Override public void process(WatchedEvent event) { for (Watcher watcher : watchers) { watcher.process(event); } } }); } catch (Exception e) { throw new RuntimeException(e); } }
From source file:com.github.mosuka.zookeeper.nicli.util.ZooKeeperConnection.java
License:Apache License
public void connect(String server, int timeout) throws IOException, InterruptedException { zookeeper = new ZooKeeper(server, timeout, new Watcher() { public void process(WatchedEvent event) { if (event.getState() == KeeperState.SyncConnected) { connSignal.countDown();//from w w w . j a v a 2s. c o m } } }); connSignal.await(); }
From source file:com.glaf.cluster.catalina.session.ZooKeeperClientImpl.java
License:Apache License
protected void doStart() { try {// w ww .j a v a 2s . c o m final Watcher watcher = new Watcher() { @Override public void process(WatchedEvent event) { switch (event.getState()) { case Expired: resetSession(); break; case SyncConnected: notifySessionConnected(); break; case Disconnected: notifySessionDisconnected(); break; default: break; } } }; zooKeeper = zooKeeperFactory.newZooKeeper(watcher); createPersistentNode(GROUP_NAME); } catch (InterruptedException e) { throw new RuntimeException("Cannot start ZooKeeper client", e); } }
From source file:com.glaf.cluster.catalina.session.ZooKeeperClientImpl.java
License:Apache License
public Set<String> listNodes(final String path, final NodeListChangedListener nodeListChangedListener) throws InterruptedException { Set<String> res = new HashSet<String>(); final Watcher watcher = (nodeListChangedListener != null) ? new Watcher() { @Override/*www. java 2 s. c om*/ public void process(WatchedEvent event) { if (event.getType() == Watcher.Event.EventType.NodeChildrenChanged) { nodeListChangedListener.onNodeListChanged(); } } } : null; try { List<String> children = zooKeeperCall("Cannot list nodes", new Callable<List<String>>() { @Override public List<String> call() throws Exception { return zooKeeper.getChildren(path, watcher); } }); if (children == null) { return null; } for (String childPath : children) { res.add(extractLastPart(childPath)); } return res; } catch (KeeperException e) { throw new RuntimeException("Cannot list nodes", e); } }
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/*from w ww . jav a 2 s .c o m*/ 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; } }
From source file:com.glaf.cluster.catalina.session.ZooKeeperFactory.java
License:Apache License
public ZooKeeper newZooKeeper() { return newZooKeeper(new Watcher() { @Override/*from ww w . j a va 2 s . c o m*/ public void process(WatchedEvent event) { } }); }
From source file:com.greplin.zookeeper.RobustZooKeeper.java
License:Apache License
private void lockRecipeStepTwo(final String fullPath, final String relativePath, final String lockName, final Runnable action) throws IOException, InterruptedException, KeeperException { log.info("Client " + clientNumber + " at start of lockRecipeStepTwo with relativePath = " + relativePath); if (shutdown.get()) { log.warn("Client " + clientNumber + " is shutdown - so I'm going to give up my attempt to lock"); return;/*from w w w. j av a 2s . c o m*/ } // step 2 final List<String> children = getClient().getChildren(getLockParent(lockName), false); assert children.size() > 0; // at the ver least, my node should be there. Collections.sort(children); // step 3 if (relativePath.equals(children.get(0))) { log.info("Client " + clientNumber + " has the lowest number lock attempt (" + relativePath + "), so it holds the lock"); try { action.run(); } finally { log.info("Client " + clientNumber + " finished doing my work with " + relativePath + ", so I'm giving up the lock."); try { getClient().delete(fullPath, -1); } catch (KeeperException.NoNodeException e) { log.warn("After I finished running an action with lock " + lockName + " the actions lock node (" + fullPath + ") no longer exists. This should only happen if you manually deleted " + fullPath + " or there was an underlying network failure, and we had to reconnect"); } } return; } // step 4 final int indexOfNodeBefore = children.indexOf(relativePath) - 1; if (indexOfNodeBefore < 0) { throw new IllegalStateException( "indexOfNodeBefore is " + indexOfNodeBefore + ", and children are: " + children); } final String nodeBeforeMine = children.get(indexOfNodeBefore); log.info("Client " + clientNumber + " (at " + relativePath + ") is setting a watch on the node before me (" + nodeBeforeMine + ")"); final Stat exists = getClient().exists(getLockParent(lockName) + "/" + nodeBeforeMine, new Watcher() { @Override public void process(WatchedEvent event) { try { log.info("Client " + clientNumber + ", when watching " + nodeBeforeMine + ", got notified: " + event); lockRecipeStepTwo(fullPath, relativePath, lockName, action); } catch (Exception e) { log.warn("Unable to execute action with lock " + lockName, e); } } }); // step 5 if (exists == null) { log.info("Client " + clientNumber + " expected " + nodeBeforeMine + " to exist - but it doesn't so re-running step 2"); lockRecipeStepTwo(fullPath, relativePath, lockName, action); } }