List of usage examples for org.apache.zookeeper Watcher Watcher
Watcher
From source file:org.deeplearning4j.zookeeper.TestZookeeperRegister.java
License:Apache License
@Test public void testZookeeper() throws Exception { String host = "localhost"; register.register();/*from ww w.j a v a 2s .c om*/ String path = new ZookeeperPathBuilder().setHost(host).setPort(2181).addPaths(Arrays.asList("tmp", "test")) .build(); assumeNotNull(keeper.getData(path, new Watcher() { @Override public void process(WatchedEvent event) { log.info("Event " + event); } }, new Stat())); Configuration retrieve = retriever.retrieve(); assumeNotNull(retrieve); keeper.delete(path, -1); }
From source file:org.eclipse.gyrex.cloud.internal.admin.NodeConfigurer.java
License:Open Source License
@Override public IStatus configureConnection(final String connectString) { ZooKeeper zk = null;/* w w w . j av a2s .c o m*/ try { if (connectString != null) { // try connect // TODO: not sure if this makes sense when configuring a remote system final CountDownLatch connected = new CountDownLatch(1); zk = new ZooKeeper(connectString, 5000, new Watcher() { @Override public void process(final WatchedEvent event) { if ((event.getType() == EventType.None) && (event.getState() == KeeperState.SyncConnected)) { connected.countDown(); } } }); // wait at most 5 seconds for a connection connected.await(5000, TimeUnit.MILLISECONDS); if (zk.getState() != States.CONNECTED) { throw new IllegalStateException(String.format( "Timeout waiting for a connection to '%s'. Please verify the connect string.", connectString)); } // try reading some information from the cloud if (null == zk.exists(IZooKeeperLayout.PATH_GYREX_ROOT.toString(), false)) { // maybe a new cloud, try initialization final String path = IZooKeeperLayout.PATH_GYREX_ROOT.toString(); final String createdPath = zk.create(path, null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); if (!path.equals(createdPath)) { throw new IllegalStateException(String .format("created path does not match expected path (%s != %s)", path, createdPath)); } } // at this point the connect string seems to be ok // TODO: store it in ZooKeeper and implement ZK to local sync } // store in instance preferences if local if (new NodeInfo().getNodeId().equals(nodeId)) { final Preferences preferences = InstanceScope.INSTANCE.getNode(CloudActivator.SYMBOLIC_NAME) .node(ZooKeeperGateConfig.PREF_NODE_ZOOKEEPER); if (connectString != null) { preferences.put(ZooKeeperGateConfig.PREF_KEY_CLIENT_CONNECT_STRING, connectString); } else { preferences.remove(ZooKeeperGateConfig.PREF_KEY_CLIENT_CONNECT_STRING); } preferences.flush(); // remove connection to cloud CloudState.unregisterNode(); // bring down ZooKeeper Gate ZooKeeperGateApplication.reconnect(); // register with new cloud CloudState.registerNode(); } } catch (final Exception e) { LOG.debug("Exception connecting to cloud using connect string {}.", connectString, e); return new Status(IStatus.ERROR, CloudActivator.SYMBOLIC_NAME, "Unable to connect to ZooKeeper. " + ExceptionUtils.getRootCauseMessage(e), e); } finally { if (zk != null) { try { zk.close(); } catch (final InterruptedException e) { Thread.currentThread().interrupt(); } } } return Status.OK_STATUS; }
From source file:org.fusesource.meshkeeper.distribution.registry.zk.ZooKeeperChildWatcher.java
License:Open Source License
public ZooKeeperChildWatcher(ZooKeeper zk, String path) { this.zk = zk; this.path = path; this.watcher = new Watcher() { public void process(WatchedEvent event) { switch (event.getType()) { case NodeChildrenChanged: { //System.out.println("NodeChildrenChangedEvent"); watch();/*from w w w . ja v a 2s . c o m*/ break; } default: { System.out.println("WARNING Got:" + event); } } } }; this.callback = new ChildrenCallback() { public void processResult(int rc, String path, Object ctx, List<String> children) { handleChildUpdate(path, children); } }; }
From source file:org.fusesource.meshkeeper.distribution.registry.zk.ZooKeeperRegistry.java
License:Open Source License
public void start() throws Exception { synchronized (this) { if (zk == null) { //ZK doesn't like schemes, so just take host and port URI uri = new URI(connectUrl); zk = new ZooKeeper(uri.getHost() + ":" + uri.getPort(), sessionTimeout, new Watcher() { public void process(WatchedEvent event) { switch (event.getState()) { case SyncConnected: connected.countDown(); break; }/*from ww w . j a va2 s. co m*/ } }); zk.addAuthInfo("digest", (userid + ":" + password).getBytes()); } } // Wait for the client to establish a connection. if (connectTimeout > 0) { if (!connected.await(connectTimeout, TimeUnit.MILLISECONDS)) { throw new IOException("Failed to connect to ZooKeeper at " + connectUrl + " within " + connectTimeout + " milliseconds."); } } else { connected.await(); } }
From source file:org.glassfish.grizzly.memcached.zookeeper.ZKClient.java
License:Open Source License
/** * Connect this client to the zookeeper server * <p/>//from ww w . j a v a2s . c o m * this method will wait for {@link Watcher.Event.KeeperState#SyncConnected} from the zookeeper server. * * @throws IOException the io exception of internal ZooKeeper * @throws InterruptedException the interrupted exception of internal ZooKeeper */ public boolean connect() throws IOException, InterruptedException { lock.lock(); try { if (connected) { return true; } zooKeeper = new ZooKeeper(zooKeeperServerList, (int) sessionTimeoutInMillis, new InternalWatcher(new Watcher() { @Override public void process(WatchedEvent event) { } })); if (!ensureConnected(connectTimeoutInMillis)) { zooKeeper.close(); currentState = Watcher.Event.KeeperState.Disconnected; connected = false; } else { connected = true; if (logger.isLoggable(Level.FINE)) { logger.log(Level.FINE, "connected the zookeeper server successfully"); } } return connected; } finally { lock.unlock(); } }
From source file:org.goldenorb.zookeeper.OrbSimpleZKTest.java
License:Apache License
/** * //ww w . jav a 2 s .co m */ @Test public void connectToZooKeeper() throws IOException, InterruptedException { ZooKeeper zk = new ZooKeeper("localhost:21810", 5000, new Watcher() { @Override public void process(WatchedEvent event) { System.out.println(event); } }); zk.close(); }
From source file:org.lable.oss.uniqueid.zookeeper.connection.ZooKeeperConnection.java
License:Apache License
/** * Connect to the ZooKeeper quorum, or timeout if it is unreachable. * * @throws IOException Thrown when connecting to the ZooKeeper quorum fails. *//* ww w . j av a 2s. c om*/ private static void connect() throws IOException { final CountDownLatch latch = new CountDownLatch(1); ZooKeeper zookeeper; // Connect to the quorum and wait for the successful connection callback.; zookeeper = new ZooKeeper(quorumAddresses, (int) SECONDS.toMillis(10), new Watcher() { @Override public void process(WatchedEvent watchedEvent) { if (watchedEvent.getState() == Event.KeeperState.SyncConnected) { // Signal that the Zookeeper connection is established. latch.countDown(); } } }); boolean successfullyConnected = false; try { successfullyConnected = latch.await(11, SECONDS); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } if (!successfullyConnected) { throw new IOException(String.format("Connection to ZooKeeper quorum timed out after %d seconds.", CONNECTION_TIMEOUT)); } zookeeper.register(new ConnectionWatcher()); INSTANCE.zookeeper = zookeeper; }
From source file:org.lable.oss.uniqueid.zookeeper.ResourceClaim.java
License:Apache License
/** * Wait in the queue until the znode in front of us changes. * * @param zookeeper ZooKeeper connection to use. * @param lockNode Path to the znode representing the locking queue. * @param placeInLine Name of our current position in the queue. * @return Name of the first node in the queue, when we are it. * @throws KeeperException/* w ww . ja v a 2 s. c o m*/ * @throws InterruptedException */ static String waitInLine(ZooKeeper zookeeper, String lockNode, String placeInLine) throws KeeperException, InterruptedException { // Get the list of nodes in the queue, and find out what our position is. List<String> children = zookeeper.getChildren(lockNode, false); // The list returned is unsorted. Collections.sort(children); if (children.size() == 0) { // Only possible if some other process cancelled our ticket. logger.warn("getChildren() returned empty list, but we created a ticket."); return acquireLock(zookeeper, lockNode); } boolean lockingTicketExists = children.get(0).equals(LOCKING_TICKET); if (lockingTicketExists) { children.remove(0); } // Where are we in the queue? int positionInQueue = -1; int i = 0; for (String child : children) { if (child.equals(placeInLine)) { positionInQueue = i; break; } i++; } if (positionInQueue < 0) { // Theoretically not possible. throw new RuntimeException("Created node (" + placeInLine + ") not found in getChildren()."); } String placeBeforeUs; if (positionInQueue == 0) { // Lowest number in the queue, go for the lock. if (grabTicket(zookeeper, lockNode, LOCKING_TICKET)) { releaseTicket(zookeeper, lockNode, placeInLine); return LOCKING_TICKET; } else { placeBeforeUs = LOCKING_TICKET; } } else { // We are not in front of the queue, so we keep an eye on the znode right in front of us. When it is // deleted, that means it has reached the front of the queue, acquired the lock, did its business, // and released the lock. placeBeforeUs = children.get(positionInQueue - 1); } final CountDownLatch latch = new CountDownLatch(1); Stat stat = zookeeper.exists(lockNode + "/" + placeBeforeUs, new Watcher() { @Override public void process(WatchedEvent event) { // If *anything* changes, reevaluate out position in the queue. latch.countDown(); } }); // If stat is null, the znode in front of use got deleted during our inspection of the queue. If that happens, // simply reevaluate our position in the queue again. If there *is* a znode in front of us, // watch it for changes: if (stat != null) { logger.debug("Watching place in queue before us ({})", placeBeforeUs); latch.await(); } return waitInLine(zookeeper, lockNode, placeInLine); }
From source file:org.lable.oss.uniqueid.zookeeper.ResourceClaim.java
License:Apache License
/** * Try to claim an available resource from the resource pool. * * @param zookeeper ZooKeeper connection to use. * @param poolNode Path to the znode representing the resource pool. * @param poolSize Size of the resource pool. * @return The claimed resource.//from ww w.j av a 2 s. c o m * @throws KeeperException * @throws InterruptedException */ static int claimResource(ZooKeeper zookeeper, String poolNode, int poolSize) throws KeeperException, InterruptedException { logger.debug("Trying to claim a resource."); List<String> claimedResources = zookeeper.getChildren(poolNode, false); if (claimedResources.size() >= poolSize) { logger.debug("No resources available at the moment (poolsize: {}), waiting.", poolSize); // No resources available. Wait for a resource to become available. final CountDownLatch latch = new CountDownLatch(1); zookeeper.getChildren(poolNode, new Watcher() { @Override public void process(WatchedEvent event) { latch.countDown(); } }); latch.await(); return claimResource(zookeeper, poolNode, poolSize); } // Try to claim an available resource. for (int i = 0; i < poolSize; i++) { String resourcePath = Integer.toString(i); if (!claimedResources.contains(resourcePath)) { try { logger.debug("Trying to claim seemingly available resource {}.", resourcePath); zookeeper.create(poolNode + "/" + resourcePath, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL); } catch (KeeperException e) { if (e.code() == KeeperException.Code.NODEEXISTS) { // Failed to claim this resource for some reason. continue; } else { // Unexpected failure. throw e; } } logger.debug("Successfully claimed resource {}.", resourcePath); return i; } } return claimResource(zookeeper, poolNode, poolSize); }
From source file:org.lable.oss.uniqueid.zookeeper.ZooKeeperInstance.java
License:Apache License
@Override protected void before() throws Throwable { tempFolder = createTempDir();/* w ww . ja v a2s .co m*/ String zookeeperHost = "localhost:" + serverPort; ServerConfig config = new ServerConfig(); config.parse(new String[] { serverPort, tempFolder.getAbsolutePath() }); zkThread = new ZooKeeperThread(config); new Thread(zkThread).start(); final CountDownLatch latch = new CountDownLatch(1); // Connect to the quorum and wait for the successful connection callback. zookeeper = new ZooKeeper(zookeeperHost, (int) TimeUnit.SECONDS.toMillis(10), new Watcher() { @Override public void process(WatchedEvent watchedEvent) { if (watchedEvent.getState() == Event.KeeperState.SyncConnected) { // Signal that the Zookeeper connection is established. latch.countDown(); } } }); // Wait for the connection to be established. boolean successfullyConnected = latch.await(12, TimeUnit.SECONDS); if (!successfullyConnected) { tempFolder.delete(); throw new Exception("Could not start a local ZooKeeper quorum for testing."); } }