List of usage examples for org.apache.zookeeper Watcher Watcher
Watcher
From source file:blazingcache.zookeeper.ZKCacheServerLocator.java
License:Apache License
@Override protected ServerHostData getServer() { String leaderPath = basePath + "/leader"; try {/* www.j a v a 2 s . c om*/ byte[] data; if (ownedZk) { CountDownLatch connection = new CountDownLatch(1); try { LOGGER.finest("creating temp ZK client for discovery"); ZooKeeper client = new ZooKeeper(zkAddress, zkSessiontimeout, new Watcher() { @Override public void process(WatchedEvent event) { if (event.getState() == Event.KeeperState.SyncConnected || event.getState() == Event.KeeperState.ConnectedReadOnly) { connection.countDown(); } LOGGER.severe("process ZK event " + event.getState() + " " + event.getType() + " " + event.getPath()); } }); try { connection.await(connectTimeout, TimeUnit.MILLISECONDS); LOGGER.finest("ZK client is " + client); // se la connessione non sar stabilita in tempo o c' qualche problem troveremo un ConnectionLoss ad esempio data = client.getData(leaderPath, false, null); } finally { client.close(); } } catch (IOException err) { LOGGER.log(Level.SEVERE, "zookeeper client not available: " + err); return null; } } else { ZooKeeper client = zkSupplier.get(); if (client == null) { LOGGER.log(Level.SEVERE, "zookeeper client available"); return null; } data = client.getData(leaderPath, false, null); } lastKnownServer = ServerHostData.parseHostdata(data); return lastKnownServer; } catch (KeeperException.NoNodeException nobroker) { LOGGER.log(Level.SEVERE, "zookeeper client error", nobroker); return null; } catch (KeeperException | InterruptedException err) { LOGGER.log(Level.SEVERE, "zookeeper client error", err); return null; } }
From source file:co.cask.cdap.common.zookeeper.coordination.ResourceCoordinator.java
License:Apache License
/** * Wraps a given Watcher so that it only get triggered if {@link #shouldProcess()} returns true. *///from w w w .ja v a 2 s .c o m private Watcher wrapWatcher(final Watcher watcher) { return new Watcher() { @Override public void process(WatchedEvent event) { if (!shouldProcess()) { return; } watcher.process(event); } }; }
From source file:co.cask.cdap.common.zookeeper.coordination.ResourceCoordinatorClient.java
License:Apache License
/** * Wraps a ZK watcher so that it only get triggered if this service is running. * * @param watcher The Watcher to wrap./*from ww w . j ava 2s.c o m*/ * @return A wrapped Watcher. */ private Watcher wrapWatcher(final Watcher watcher) { return new Watcher() { @Override public void process(WatchedEvent event) { if (isRunning()) { watcher.process(event); } } }; }
From source file:co.cask.cdap.common.zookeeper.store.ZKPropertyStore.java
License:Apache License
private void getDataAndWatch(final String name) { Futures.addCallback(zkClient.getData(getPath(name), new Watcher() { @Override// w w w . j av a 2s . c om public void process(WatchedEvent event) { if (isClosed()) { return; } if (event.getType() == Event.EventType.NodeDeleted) { existsAndWatch(name); } else { getDataAndWatch(name); } } }), new FutureCallback<NodeData>() { @Override public void onSuccess(NodeData result) { byte[] data = result.getData(); if (data == null) { updateAndNotify(name, null); } else { try { updateAndNotify(name, codec.decode(data)); } catch (IOException e) { LOG.error("Failed to decode property data for {}: {}", name, Bytes.toStringBinary(data), e); notifyError(name, e); } } } @Override public void onFailure(Throwable t) { if (t instanceof KeeperException.NoNodeException) { // If node not exists, watch for exists. existsAndWatch(name); } else { LOG.error("Failed to get property data for {}", name, t); notifyError(name, t); } } }, Threads.SAME_THREAD_EXECUTOR); }
From source file:co.cask.cdap.common.zookeeper.store.ZKPropertyStore.java
License:Apache License
private void existsAndWatch(final String name) { Futures.addCallback(zkClient.exists(getPath(name), new Watcher() { @Override/*from w w w . j a v a 2s . c om*/ public void process(WatchedEvent event) { if (isClosed()) { return; } // If the event is not node created, meaning the node was existed. // Hence getDataAndWatch should be handling that case already if (event.getType() == Event.EventType.NodeCreated) { getDataAndWatch(name); } } }), new FutureCallback<Stat>() { @Override public void onSuccess(Stat result) { // If the node exists, call getData. Otherwise, the watcher should handle the case when the node is created if (result != null) { getDataAndWatch(name); } } @Override public void onFailure(Throwable t) { LOG.error("Failed to check exists for property data for {}", name, t); notifyError(name, t); } }, Threads.SAME_THREAD_EXECUTOR); }
From source file:co.cask.cdap.route.store.ZKRouteStore.java
License:Apache License
private void existsAndWatch(final ProgramId serviceId, final SettableFuture<RouteConfig> oldSettableFuture) { Futures.addCallback(zkClient.exists(getZKPath(serviceId), new Watcher() { @Override//from w ww . j a v a 2 s .c o m public void process(WatchedEvent event) { // If service name doesn't exist in the map, then don't rewatch it. if (!routeConfigMap.containsKey(serviceId)) { return; } if (event.getType() == Event.EventType.NodeCreated) { getAndWatchData(serviceId, SettableFuture.<RouteConfig>create(), oldSettableFuture, new ZKRouteWatcher(serviceId)); } } }), new FutureCallback<Stat>() { @Override public void onSuccess(@Nullable Stat result) { if (result != null) { getAndWatchData(serviceId, SettableFuture.<RouteConfig>create(), oldSettableFuture, new ZKRouteWatcher(serviceId)); } } @Override public void onFailure(Throwable t) { routeConfigMap.remove(serviceId); LOG.debug("Failed to check exists for property data for {}", serviceId, t); } }); }
From source file:co.cask.tephra.distributed.ThriftTransactionServerTest.java
License:Apache License
private void expireZkSession(ZKClientService zkClientService) throws Exception { ZooKeeper zooKeeper = zkClientService.getZooKeeperSupplier().get(); final SettableFuture<?> connectFuture = SettableFuture.create(); Watcher watcher = new Watcher() { @Override/* w w w .ja v a2 s . co m*/ public void process(WatchedEvent event) { if (event.getState() == Event.KeeperState.SyncConnected) { connectFuture.set(null); } } }; // Create another Zookeeper session with the same sessionId so that the original one expires. final ZooKeeper dupZookeeper = new ZooKeeper(zkClientService.getConnectString(), zooKeeper.getSessionTimeout(), watcher, zooKeeper.getSessionId(), zooKeeper.getSessionPasswd()); connectFuture.get(30, TimeUnit.SECONDS); Assert.assertEquals("Failed to re-create current session", dupZookeeper.getState(), ZooKeeper.States.CONNECTED); dupZookeeper.close(); }
From source file:co.cask.tephra.zookeeper.TephraZKClientService.java
License:Apache License
/** * Wraps the given watcher to be called from the event executor. * @param watcher Watcher to be wrapped/*from w w w.ja va 2s. c o m*/ * @return The wrapped Watcher */ private Watcher wrapWatcher(final Watcher watcher) { if (watcher == null) { return null; } return new Watcher() { @Override public void process(final WatchedEvent event) { if (eventExecutor.isShutdown()) { LOG.debug("Already shutdown. Discarding event: {}", event); return; } eventExecutor.execute(new Runnable() { @Override public void run() { try { watcher.process(event); } catch (Throwable t) { LOG.error("Watcher throws exception.", t); } } }); } }; }
From source file:com.alibaba.otter.shared.arbitrate.zookeeper.ZooKeeperClientTest.java
License:Apache License
@Test public void testClient() { ZkClientx zk = ZooKeeperClient.getInstance(); // ?zk??/*from ww w . ja v a 2 s . com*/ final ZooKeeper zkp = ((ZooKeeperx) zk.getConnection()).getZookeeper(); ClientCnxn cnxn = (ClientCnxn) ReflectionUtils.getField(clientCnxnField, zkp); HostProvider hostProvider = (HostProvider) ReflectionUtils.getField(hostProviderField, cnxn); List<InetSocketAddress> serverAddrs = (List<InetSocketAddress>) ReflectionUtils .getField(serverAddressesField, hostProvider); want.number(serverAddrs.size()).isEqualTo(3); String s1 = serverAddrs.get(0).getAddress().getHostAddress() + ":" + serverAddrs.get(0).getPort(); want.string(s1).isEqualTo(cluster1); Stat stat = new Stat(); try { zkp.getChildren("/otter/channel/304/388", false, stat); System.out.println(stat.getCversion()); } catch (KeeperException e2) { // TODO Auto-generated catch block e2.printStackTrace(); } catch (InterruptedException e2) { // TODO Auto-generated catch block e2.printStackTrace(); } // session timeout final CountDownLatch latch = new CountDownLatch(1); new Thread() { public void run() { try { zkp.getChildren("/", false); } catch (KeeperException e1) { want.fail(); } catch (InterruptedException e1) { want.fail(); } int sessionTimeout = zkp.getSessionTimeout(); long sessionId = zkp.getSessionId(); byte[] passwd = zkp.getSessionPasswd(); try { ZooKeeper newZk = new ZooKeeper(cluster1, sessionTimeout, new Watcher() { public void process(WatchedEvent event) { // do nothing } }, sessionId, passwd); // ?sessionIdclose??SESSION_EXPIRED newZk.close(); } catch (IOException e) { want.fail(); } catch (InterruptedException e) { want.fail(); } latch.countDown(); } }.start(); try { latch.await(); } catch (InterruptedException e) { want.fail(); } zk.getChildren("/"); }
From source file:com.andyadc.menagerie.latches.ZkCountDownLatchTest.java
License:Apache License
private static ZooKeeper newZooKeeper() throws IOException { return new ZooKeeper("localhost:2181", timeout, new Watcher() { @Override//from w w w.j a v a 2 s . co m public void process(WatchedEvent event) { System.out.println(event); } }); }