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:org.apache.bookkeeper.tools.BookKeeperTools.java

License:Apache License

/**
 * Constructor that takes in a ZooKeeper servers connect string so we know
 * how to connect to ZooKeeper to retrieve information about the BookKeeper
 * cluster. We need this before we can do any type of admin operations on
 * the BookKeeper cluster.// ww w  .ja  v a2s  . c  o  m
 * 
 * @param zkServers
 *            Comma separated list of hostname:port pairs for the ZooKeeper
 *            servers cluster.
 * @throws IOException
 *             Throws this exception if there is an error instantiating the
 *             ZooKeeper client.
 * @throws InterruptedException
 *             Throws this exception if there is an error instantiating the
 *             BookKeeper client.
 * @throws KeeperException
 *             Throws this exception if there is an error instantiating the
 *             BookKeeper client.
 */
public BookKeeperTools(String zkServers) throws IOException, InterruptedException, KeeperException {
    // Create the ZooKeeper client instance
    zk = new ZooKeeper(zkServers, 10000, new Watcher() {
        @Override
        public void process(WatchedEvent event) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Process: " + event.getType() + " " + event.getPath());
            }
        }
    });
    // Create the BookKeeper client instance
    bkc = new BookKeeper(zk);
}

From source file:org.apache.bookkeeper.zookeeper.TestZooKeeperClient.java

License:Apache License

@Test(timeout = 12000)
public void testReconnectAfterExipred() throws Exception {
    final CountDownLatch expireLatch = new CountDownLatch(1);
    Watcher testWatcher = new Watcher() {

        @Override//  ww w . j  av a 2  s . co m
        public void process(WatchedEvent event) {
            if (event.getType() == EventType.None && event.getState() == KeeperState.Expired) {
                expireLatch.countDown();
            }
        }

    };
    final int timeout = 2000;
    ZooKeeperWatcherBase watcherManager = new ZooKeeperWatcherBase(timeout).addChildWatcher(testWatcher);
    List<Watcher> watchers = new ArrayList<Watcher>(1);
    watchers.add(testWatcher);
    ZooKeeperClient client = new ShutdownZkServerClient(zkUtil.getZooKeeperConnectString(), timeout,
            watcherManager, new BoundExponentialBackoffRetryPolicy(timeout, timeout, 0));
    client.waitForConnection();
    Assert.assertTrue("Client failed to connect an alive ZooKeeper.", client.getState().isConnected());
    logger.info("Expire zookeeper client");
    expireZooKeeperSession(client, timeout);

    // wait until session expire
    Assert.assertTrue("Client registered watcher should receive expire event.",
            expireLatch.await(2 * timeout, TimeUnit.MILLISECONDS));

    Assert.assertFalse("Client doesn't receive expire event from ZooKeeper.", client.getState().isConnected());

    try {
        client.exists("/tmp", false);
        Assert.fail("Should fail due to connection loss.");
    } catch (KeeperException.ConnectionLossException cle) {
        // expected
    } catch (KeeperException.SessionExpiredException cle) {
        // expected
    }

    zkUtil.restartServer();

    // wait for a reconnect cycle
    Thread.sleep(2 * timeout);
    Assert.assertTrue("Client failed to connect zookeeper even it was back.", client.getState().isConnected());
    try {
        client.exists("/tmp", false);
    } catch (KeeperException.ConnectionLossException cle) {
        Assert.fail("Should not throw ConnectionLossException");
    } catch (KeeperException.SessionExpiredException cle) {
        Assert.fail("Should not throw SessionExpiredException");
    }
}

From source file:org.apache.brooklyn.entity.messaging.zookeeper.ZooKeeperTestSupport.java

License:Apache License

public ZooKeeperTestSupport(final HostAndPort hostAndPort) throws Exception {
    final int sessionTimeout = 3000;
    zk = new ZooKeeper(hostAndPort.toString(), sessionTimeout, new Watcher() {
        @Override//from  www .  j  a  va2  s .c o  m
        public void process(WatchedEvent event) {
            if (event.getState() == Event.KeeperState.SyncConnected) {
                LOG.debug("Connected to ZooKeeper at {}", hostAndPort);
                connSignal.countDown();
            } else {
                LOG.info("WatchedEvent at {}: {}", hostAndPort, event.getState());
            }
        }
    });
    connSignal.await();
}

From source file:org.apache.cassandra.service.StorageService.java

License:Apache License

private void reportToZookeeper() throws Throwable {
    try {/*from   w  ww .  ja va  2 s.co 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.contains(path))) {
                            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:org.apache.curator.framework.imps.CuratorFrameworkImpl.java

License:Apache License

public CuratorFrameworkImpl(CuratorFrameworkFactory.Builder builder) {
    ZookeeperFactory localZookeeperFactory = makeZookeeperFactory(builder.getZookeeperFactory());
    this.client = new CuratorZookeeperClient(localZookeeperFactory, builder.getEnsembleProvider(),
            builder.getSessionTimeoutMs(), builder.getConnectionTimeoutMs(), new Watcher() {
                @Override/* w  w w  .j  ava 2  s .c  om*/
                public void process(WatchedEvent watchedEvent) {
                    CuratorEvent event = new CuratorEventImpl(CuratorFrameworkImpl.this,
                            CuratorEventType.WATCHED, watchedEvent.getState().getIntValue(),
                            unfixForNamespace(watchedEvent.getPath()), null, null, null, null, null,
                            watchedEvent, null);
                    processEvent(event);
                }
            }, builder.getRetryPolicy(), builder.canBeReadOnly());

    listeners = new ListenerContainer<CuratorListener>();
    unhandledErrorListeners = new ListenerContainer<UnhandledErrorListener>();
    backgroundOperations = new DelayQueue<OperationAndData<?>>();
    namespace = new NamespaceImpl(this, builder.getNamespace());
    threadFactory = getThreadFactory(builder);
    maxCloseWaitMs = builder.getMaxCloseWaitMs();
    connectionStateManager = new ConnectionStateManager(this, builder.getThreadFactory());
    compressionProvider = builder.getCompressionProvider();
    aclProvider = builder.getAclProvider();
    state = new AtomicReference<CuratorFrameworkState>(CuratorFrameworkState.LATENT);
    useContainerParentsIfAvailable = builder.useContainerParentsIfAvailable();

    byte[] builderDefaultData = builder.getDefaultData();
    defaultData = (builderDefaultData != null) ? Arrays.copyOf(builderDefaultData, builderDefaultData.length)
            : new byte[0];
    authInfos = buildAuths(builder);

    failedDeleteManager = new FailedDeleteManager(this);
    namespaceFacadeCache = new NamespaceFacadeCache(this);
}

From source file:org.apache.curator.framework.imps.TestEnabledSessionExpiredState.java

License:Apache License

@Test
public void testInjectedWatchedEvent() throws Exception {
    Assert.assertEquals(states.poll(timing.milliseconds(), TimeUnit.MILLISECONDS), ConnectionState.CONNECTED);

    final CountDownLatch latch = new CountDownLatch(1);
    Watcher watcher = new Watcher() {
        @Override/*w  w w.  j  ava2  s .c  o m*/
        public void process(WatchedEvent event) {
            if (event.getType() == Event.EventType.None) {
                if (event.getState() == Event.KeeperState.Expired) {
                    latch.countDown();
                }
            }
        }
    };
    client.checkExists().usingWatcher(watcher).forPath("/");
    server.stop();
    Assert.assertTrue(timing.forSessionSleep().awaitLatch(latch));
}

From source file:org.apache.curator.framework.imps.TestFramework.java

License:Apache License

@Test
public void testNamespaceWithWatcher() throws Exception {
    CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder();
    CuratorFramework client = builder.connectString(server.getConnectString()).namespace("aisa")
            .retryPolicy(new RetryOneTime(1)).build();
    client.start();/*  w  ww  .  j a  va  2  s.com*/
    try {
        final BlockingQueue<String> queue = new LinkedBlockingQueue<String>();
        Watcher watcher = new Watcher() {
            @Override
            public void process(WatchedEvent event) {
                try {
                    queue.put(event.getPath());
                } catch (InterruptedException e) {
                    throw new Error(e);
                }
            }
        };
        client.create().forPath("/base");
        client.getChildren().usingWatcher(watcher).forPath("/base");
        client.create().forPath("/base/child");

        String path = queue.take();
        Assert.assertEquals(path, "/base");
    } finally {
        CloseableUtils.closeQuietly(client);
    }
}

From source file:org.apache.curator.framework.imps.TestFrameworkEdges.java

License:Apache License

@Test
public void testSessionKilled() throws Exception {
    CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(),
            timing.connection(), new RetryOneTime(1));
    client.start();//from   w  w w  .j  av  a  2  s  . c  o m
    try {
        client.create().forPath("/sessionTest");

        final AtomicBoolean sessionDied = new AtomicBoolean(false);
        Watcher watcher = new Watcher() {
            @Override
            public void process(WatchedEvent event) {
                if (event.getState() == Event.KeeperState.Expired) {
                    sessionDied.set(true);
                }
            }
        };
        client.checkExists().usingWatcher(watcher).forPath("/sessionTest");
        KillSession.kill(client.getZookeeperClient().getZooKeeper(), server.getConnectString());
        Assert.assertNotNull(client.checkExists().forPath("/sessionTest"));
        Assert.assertTrue(sessionDied.get());
    } finally {
        CloseableUtils.closeQuietly(client);
    }
}

From source file:org.apache.curator.framework.imps.TestReconfiguration.java

License:Apache License

private CountDownLatch setChangeWaiter(CuratorFramework client) throws Exception {
    final CountDownLatch latch = new CountDownLatch(1);
    Watcher watcher = new Watcher() {
        @Override// w w w.  j  a v  a2 s. c  om
        public void process(WatchedEvent event) {
            if (event.getType() == Event.EventType.NodeDataChanged) {
                latch.countDown();
            }
        }
    };
    client.getConfig().usingWatcher(watcher).forEnsemble();
    return latch;
}

From source file:org.apache.curator.framework.imps.TestRemoveWatches.java

License:Apache License

/**
 * Test the case where we try and remove an unregistered watcher. In this case we expect a NoWatcherException to
 * be thrown. /*from   w ww . j  ava 2 s  .c o  m*/
 * @throws Exception
 */
@Test(expectedExceptions = KeeperException.NoWatcherException.class)
public void testRemoveUnregisteredWatcher() throws Exception {
    CuratorFramework client = CuratorFrameworkFactory.builder().connectString(server.getConnectString())
            .retryPolicy(new RetryOneTime(1)).build();
    try {
        client.start();

        final String path = "/";
        Watcher watcher = new Watcher() {
            @Override
            public void process(WatchedEvent event) {
            }
        };

        client.watches().remove(watcher).forPath(path);
    } finally {
        CloseableUtils.closeQuietly(client);
    }
}