Example usage for org.apache.zookeeper Watcher Watcher

List of usage examples for org.apache.zookeeper Watcher Watcher

Introduction

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

Prototype

Watcher

Source Link

Usage

From source file:herddb.cluster.ZookeeperMetadataStorageManager.java

License:Apache License

private synchronized void restartZooKeeper() throws IOException, InterruptedException {
    ZooKeeper old = zooKeeper;/*from w ww.  j  av a2s  . c  om*/
    if (old != null) {
        old.close();
    }
    CountDownLatch firstConnectionLatch = new CountDownLatch(1);

    ZooKeeper zk = new ZooKeeper(zkAddress, zkSessionTimeout, new Watcher() {
        @Override
        public void process(WatchedEvent event) {
            switch (event.getState()) {
            case SyncConnected:
            case SaslAuthenticated:
                firstConnectionLatch.countDown();
                notifyMetadataChanged();
                break;
            default:
                // ignore
                break;
            }
        }
    });
    if (!firstConnectionLatch.await(zkSessionTimeout, TimeUnit.SECONDS)) {
        zk.close();
        throw new IOException(
                "Could not connect to zookeeper at " + zkAddress + " within " + zkSessionTimeout + " ms");
    }
    this.zooKeeper = zk;
    LOGGER.info("Connected to ZK " + zk);
}

From source file:herddb.cluster.ZookeeperMetadataStorageManagerTest.java

License:Apache License

private void expireZkSession(long sessionId, byte[] passwd) throws InterruptedException, IOException {
    CountDownLatch waitConnection = new CountDownLatch(1);
    try (ZooKeeper zooKeeper = new ZooKeeper(testEnv.getAddress(), testEnv.getTimeout(), new Watcher() {
        @Override/* w  w  w  .  j  a v a 2  s  . c  om*/
        public void process(WatchedEvent event) {
            switch (event.getState()) {
            case SyncConnected:
                waitConnection.countDown();
                break;
            }
        }
    }, sessionId, passwd)) {
        assertTrue(waitConnection.await(1, TimeUnit.MINUTES));
    }
}

From source file:hws.util.ZkDataMonitor.java

License:Apache License

public ZkClient(String serverAddr, int sessionTimeout) throws IOException, InterruptedException {
    final CountDownLatch connectedSignal = new CountDownLatch(1);
    this.zk = new ZooKeeper(serverAddr, sessionTimeout, new Watcher() {
        @Override//from   w w  w .j  a  v a  2 s . co m
        public void process(WatchedEvent event) {
            if (event.getState() == Watcher.Event.KeeperState.SyncConnected) {
                connectedSignal.countDown();
            }
        }
    });
    connectedSignal.await();
}

From source file:io.fabric8.itests.basic.git.GitUtils.java

License:Apache License

/**
 * Wait until the version znode gets updated (indicating that entries has been bridge from/to git).
 * @param curator       The {@link CuratorFramework} instance to use for looking up the registry.
 * @param branch        The name of the branch/version.
 * @throws Exception/*from   www  . j a va  2 s.co  m*/
 */
public static void waitForBranchUpdate(CuratorFramework curator, String branch) throws Exception {
    final CountDownLatch latch = new CountDownLatch(1);
    final Watcher watcher = new Watcher() {
        @Override
        public void process(WatchedEvent watchedEvent) {
            latch.countDown();
        }
    };

    for (int i = 0; curator.checkExists().usingWatcher(watcher)
            .forPath(ZkPath.CONFIG_VERSION.getPath(branch)) == null && i < 3; i++) {
        Thread.sleep(1000);
    }

    latch.await(10, TimeUnit.SECONDS);
}

From source file:io.flood.registry.zk.ZookeeperRegistry.java

License:Apache License

@Override
public void subscribe(final String name, final String group, final NotifyListener listener) {
    try {/*w w  w  . java2 s. co m*/
        String serviceDir = Paths.get(name, group);
        client.getChildren().usingWatcher(new Watcher() {
            @Override
            public void process(WatchedEvent watchedEvent) {
                switch (watchedEvent.getType()) {
                case NodeChildrenChanged: {

                    try {
                        final List<String> nodes = client.getChildren().forPath(serviceDir);
                        List<Resource> services = Lists.newArrayListWithCapacity(nodes.size());
                        String servicePath = null;
                        for (String node : nodes) {
                            servicePath = Paths.get(name, group, node);
                            byte[] buffer = client.getData().forPath(servicePath);
                            Resource resource = GsonFactory.fromJson(buffer, Resource.class);
                            if (!localService.containsKey(servicePath)) {
                                LOG.info("new serice {},{}", servicePath, resource);
                                listener.notifyResourceCreated(resource);
                                subscribeRealService(resource, listener);
                                localService.put(servicePath, resource);
                            }
                        }

                        Maps.filterEntries(localService, entry -> {
                            if (nodes.contains(entry.getKey())) {
                                return true;
                            }
                            listener.notifyResourceDeleted(entry.getValue());
                            return false;
                        });
                    } catch (Exception e) {
                        LOG.warn("node child changed ,but process error ", e);
                    }

                }
                }
            }
        }).forPath(Paths.get(name, group));
        LOG.info("subscribe {}", Paths.get(name, group));
    } catch (Exception e) {
        throw new IllegalStateException(e);
    }
}

From source file:io.pivotal.cf.servicebroker.Util.java

License:Open Source License

ZooKeeper getZooKeeper() throws IOException {
    return new ZooKeeper(env.getProperty("ZOOKEEPER_HOST"),
            Integer.parseInt(env.getProperty("ZOOKEEPER_TIMEOUT")), new Watcher() {
                @Override/*from  www . ja v  a 2 s .  c om*/
                public void process(WatchedEvent event) {
                    log.info("watching: " + event.toString());
                }
            });
}

From source file:io.s4.comm.test.TestTaskSetupApp.java

License:Open Source License

public void testTaskSetup1() throws Exception {
    String address = "effortfell.greatamerica.corp.yahoo.com:2181";
    Watcher watcher = new Watcher() {

        @Override//from   www.  ja v a 2 s.com
        public void process(WatchedEvent event) {

        }

    };
    // setup
    ZooKeeper zk = new ZooKeeper(address, 30000, watcher);
    String root = "/tasksetup_app_test";
    ZkTaskSetup zkSetup = new ZkTaskSetup(address, root, ClusterType.S4);
    Map<String, String> task1 = new HashMap<String, String>();
    task1.put("name", "task-1");

    Map<String, String> task2 = new HashMap<String, String>();
    task2.put("name", "task-2");
    String tasksListRoot = root + "/tasks";
    zkSetup.cleanUp();
    Stat exists = zk.exists(tasksListRoot, false);
    myassert(exists == null);
    Object[] data = new Object[] { task1, task2 };
    zkSetup.setUpTasks(data);

    // verify that tasks are created
    exists = zk.exists(tasksListRoot, false);
    myassert(exists != null);
    List<String> children = zk.getChildren(tasksListRoot, false);
    myassert(children.size() == data.length);
    boolean[] matched = new boolean[data.length];
    for (String child : children) {
        System.out.println(child);
        String childPath = tasksListRoot + "/" + child;
        Stat sTemp = zk.exists(childPath, false);
        byte[] tempData = zk.getData(tasksListRoot + "/" + child, false, sTemp);
        Map<String, Object> map = (Map<String, Object>) JSONUtil.getMapFromJson(new String(tempData));
        // check if it matches any of the data
        for (int i = 0; i < data.length; i++) {
            Map<String, Object> newData = (Map<String, Object>) data[i];
            if (!matched[i] && CommUtil.compareMaps(newData, map)) {
                matched[i] = true;
                break;
            }
        }
    }
    for (int i = 0; i < matched.length; i++) {
        myassert(matched[i]);
    }

    // try running again and make verify new node is not created
    Stat oldStat = zk.exists(tasksListRoot, false);
    System.out.println("oldStat=" + oldStat);
    zkSetup.setUpTasks(data);
    Stat newStat = zk.exists(tasksListRoot, false);
    System.out.println("newstat=" + newStat);
    myassert(oldStat.getMtime() == newStat.getMtime());

    // make change to task config and try running again and verify new
    // config is uploaded
    oldStat = zk.exists(tasksListRoot, false);
    System.out.println("oldStat=" + oldStat.getVersion());
    ((Map<String, String>) data[data.length - 1]).put("name", "changedname");
    zkSetup.setUpTasks(data);
    newStat = zk.exists(tasksListRoot, false);
    System.out.println("newstat=" + newStat.getVersion());
    System.out.println();
    myassert(oldStat.getMtime() != newStat.getMtime());

    // ensure version change is working
    zkSetup.setUpTasks("1.0.0.0", data);
}

From source file:io.s4.zeno.config.ZKConfigTest.java

License:Open Source License

/**
 * The main method.//from   w  w w .j a v  a 2  s .  c o m
 * 
 * @param arg
 *            the arguments
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
public static void main(String[] arg) throws IOException {
    PropertyConfigurator.configure("log4j.properties");

    String connect = "localhost:2181";
    int timeout = 1000;
    ZooKeeper zk = new ZooKeeper(connect, timeout, new Watcher() {
        public void process(WatchedEvent e) {
            System.out.println("Got Notification: " + e);
        }
    });

    ZooKeeperHelper zookeeper = new ZooKeeperHelper(zk, 3, 5000);

    ZKWritableConfigMap conf = new ZKWritableConfigMap(zookeeper, "/tmp/test-config");

    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

    String cmd;
    while ((cmd = in.readLine()) != null) {
        if (cmd.equals("get")) {
            String key = in.readLine();
            System.out.println("got '" + key + "': " + conf.get(key));
        } else {
            String key = in.readLine();
            String val = in.readLine();
            conf.set(key, val);
        }
    }
}

From source file:io.s4.zeno.console.Main.java

License:Open Source License

public static void main(String[] argv) throws IOException, KeeperException {
    PropertyConfigurator.configure("log4j.properties");

    String zkserver = argv[0];// w  w w.j a  va  2 s .  c  om
    String base = argv[1];

    logger.info("connecting to zookeeper: " + zkserver);

    int timeout = 1000;
    ZooKeeper zookeeper = new ZooKeeper(zkserver, timeout, new Watcher() {
        public void process(WatchedEvent e) {
            logger.info("Got Notification: " + e);
        }
    });

    logger.info("connected to zookeeper");

    Main cli = new Main(zookeeper, base);
    cli.run();
}

From source file:io.s4.zeno.route.RouterTest.java

License:Open Source License

/**
 * The main method./*  w  w  w.  j a  va 2  s . co  m*/
 * 
 * @param arg
 *            the arguments
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
public static void main(String[] arg) throws IOException {
    PropertyConfigurator.configure("log4j.properties");

    String connect = arg[0];
    int timeout = 1000;
    ZooKeeper zk = new ZooKeeper(connect, timeout, new Watcher() {
        public void process(WatchedEvent e) {
            System.out.println("Got ZK Notification: " + e);
        }
    });

    RouterTest test = new RouterTest(zk, arg[1]);

    test.dump();
    // test.test1();
    test.loadGen(arg[2]);
}