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.hedwig.server.netty.TestPubSubServer.java

License:Apache License

@Test(timeout = 60000)
public void testUncaughtExceptionInZKThread() throws Exception {

    SynchronousQueue<Throwable> queue = new SynchronousQueue<Throwable>();
    RecordingUncaughtExceptionHandler uncaughtExceptionHandler = new RecordingUncaughtExceptionHandler(queue);
    final int port = PortManager.nextFreePort();
    final String hostPort = "127.0.0.1:" + PortManager.nextFreePort();

    PubSubServer server = startServer(uncaughtExceptionHandler, port, new TopicManagerInstantiator() {

        @Override/*  w ww.  jav a2s. c  om*/
        public TopicManager instantiateTopicManager() throws IOException {
            return new AbstractTopicManager(new ServerConfiguration(),
                    Executors.newSingleThreadScheduledExecutor()) {

                @Override
                protected void realGetOwner(ByteString topic, boolean shouldClaim,
                        Callback<HedwigSocketAddress> cb, Object ctx) {
                    ZooKeeper zookeeper;
                    try {
                        zookeeper = new ZooKeeper(hostPort, 60000, new Watcher() {
                            @Override
                            public void process(WatchedEvent event) {
                                // TODO Auto-generated method stub

                            }
                        });
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }

                    zookeeper.getData("/fake", false, new SafeAsyncZKCallback.DataCallback() {
                        @Override
                        public void safeProcessResult(int rc, String path, Object ctx, byte[] data,
                                org.apache.zookeeper.data.Stat stat) {
                            throw new RuntimeException("This should go to the uncaught exception handler");
                        }

                    }, null);
                }

                @Override
                protected void postReleaseCleanup(ByteString topic, Callback<Void> cb, Object ctx) {
                }
            };
        }
    });

    runPublishRequest(port);
    assertEquals(RuntimeException.class, queue.take().getClass());
    server.shutdown();
}

From source file:org.apache.helix.manager.zk.TestZkClient.java

License:Apache License

@Test()
void testSessionExpire() throws Exception {
    IZkStateListener listener = new IZkStateListener() {

        @Override//  ww w.j  ava 2 s  . co  m
        public void handleStateChanged(KeeperState state) throws Exception {
            System.out.println("In Old connection New state " + state);
        }

        @Override
        public void handleNewSession() throws Exception {
            System.out.println("In Old connection New session");
        }

        @Override
        public void handleSessionEstablishmentError(Throwable var1) throws Exception {
        }
    };

    _zkClient.subscribeStateChanges(listener);
    ZkConnection connection = ((ZkConnection) _zkClient.getConnection());
    ZooKeeper zookeeper = connection.getZookeeper();
    System.out.println("old sessionId= " + zookeeper.getSessionId());
    Watcher watcher = new Watcher() {
        @Override
        public void process(WatchedEvent event) {
            System.out.println("In New connection In process event:" + event);
        }
    };
    ZooKeeper newZookeeper = new ZooKeeper(connection.getServers(), zookeeper.getSessionTimeout(), watcher,
            zookeeper.getSessionId(), zookeeper.getSessionPasswd());
    Thread.sleep(3000);
    System.out.println("New sessionId= " + newZookeeper.getSessionId());
    Thread.sleep(3000);
    newZookeeper.close();
    Thread.sleep(10000);
    connection = ((ZkConnection) _zkClient.getConnection());
    zookeeper = connection.getZookeeper();
    System.out.println("After session expiry sessionId= " + zookeeper.getSessionId());
}

From source file:org.apache.helix.TestZkClientWrapper.java

License:Apache License

@Test()
void testSessioExpire() throws Exception {
    IZkStateListener listener = new IZkStateListener() {

        @Override/*from  w  w  w .  j  av a2 s.  c  o  m*/
        public void handleStateChanged(KeeperState state) throws Exception {
            System.out.println("In Old connection New state " + state);
        }

        @Override
        public void handleNewSession() throws Exception {
            System.out.println("In Old connection New session");
        }
    };

    _zkClient.subscribeStateChanges(listener);
    ZkConnection connection = ((ZkConnection) _zkClient.getConnection());
    ZooKeeper zookeeper = connection.getZookeeper();
    System.out.println("old sessionId= " + zookeeper.getSessionId());
    Watcher watcher = new Watcher() {
        @Override
        public void process(WatchedEvent event) {
            System.out.println("In New connection In process event:" + event);
        }
    };
    ZooKeeper newZookeeper = new ZooKeeper(connection.getServers(), zookeeper.getSessionTimeout(), watcher,
            zookeeper.getSessionId(), zookeeper.getSessionPasswd());
    Thread.sleep(3000);
    System.out.println("New sessionId= " + newZookeeper.getSessionId());
    Thread.sleep(3000);
    newZookeeper.close();
    Thread.sleep(10000);
    connection = ((ZkConnection) _zkClient.getConnection());
    zookeeper = connection.getZookeeper();
    System.out.println("After session expiry sessionId= " + zookeeper.getSessionId());
}

From source file:org.apache.helix.ZkTestHelper.java

License:Apache License

public static void disconnectSession(final ZkClient zkClient) throws Exception {
    IZkStateListener listener = new IZkStateListener() {
        @Override//from   ww w .java 2s. c  om
        public void handleStateChanged(KeeperState state) throws Exception {
            // System.err.println("disconnectSession handleStateChanged. state: " + state);
        }

        @Override
        public void handleNewSession() throws Exception {
            // make sure zkclient is connected again
            zkClient.waitUntilConnected();

            ZkConnection connection = ((ZkConnection) zkClient.getConnection());
            ZooKeeper curZookeeper = connection.getZookeeper();

            LOG.info("handleNewSession. sessionId: " + Long.toHexString(curZookeeper.getSessionId()));
        }
    };

    zkClient.subscribeStateChanges(listener);
    ZkConnection connection = ((ZkConnection) zkClient.getConnection());
    ZooKeeper curZookeeper = connection.getZookeeper();
    LOG.info("Before expiry. sessionId: " + Long.toHexString(curZookeeper.getSessionId()));

    Watcher watcher = new Watcher() {
        @Override
        public void process(WatchedEvent event) {
            LOG.info("Process watchEvent: " + event);
        }
    };

    final ZooKeeper dupZookeeper = new ZooKeeper(connection.getServers(), curZookeeper.getSessionTimeout(),
            watcher, curZookeeper.getSessionId(), curZookeeper.getSessionPasswd());
    // wait until connected, then close
    while (dupZookeeper.getState() != States.CONNECTED) {
        Thread.sleep(10);
    }
    dupZookeeper.close();

    connection = (ZkConnection) zkClient.getConnection();
    curZookeeper = connection.getZookeeper();
    zkClient.unsubscribeStateChanges(listener);

    // System.err.println("zk: " + oldZookeeper);
    LOG.info("After expiry. sessionId: " + Long.toHexString(curZookeeper.getSessionId()));
}

From source file:org.apache.helix.ZkTestHelper.java

License:Apache License

/**
 * Expire current zk session and wait for {@link IZkStateListener#handleNewSession()} invoked
 * @param zkClient// ww w .ja v a  2 s. c om
 * @throws Exception
 */
public static void expireSession(final ZkClient zkClient) throws Exception {
    final CountDownLatch waitNewSession = new CountDownLatch(1);

    IZkStateListener listener = new IZkStateListener() {
        @Override
        public void handleStateChanged(KeeperState state) throws Exception {
            LOG.info("IZkStateListener#handleStateChanged, state: " + state);
        }

        @Override
        public void handleNewSession() throws Exception {
            // make sure zkclient is connected again
            zkClient.waitUntilConnected();

            ZkConnection connection = ((ZkConnection) zkClient.getConnection());
            ZooKeeper curZookeeper = connection.getZookeeper();

            LOG.info("handleNewSession. sessionId: " + Long.toHexString(curZookeeper.getSessionId()));
            waitNewSession.countDown();
        }
    };

    zkClient.subscribeStateChanges(listener);

    ZkConnection connection = ((ZkConnection) zkClient.getConnection());
    ZooKeeper curZookeeper = connection.getZookeeper();
    String oldSessionId = Long.toHexString(curZookeeper.getSessionId());
    LOG.info("Before session expiry. sessionId: " + oldSessionId + ", zk: " + curZookeeper);

    Watcher watcher = new Watcher() {
        @Override
        public void process(WatchedEvent event) {
            LOG.info("Watcher#process, event: " + event);
        }
    };

    final ZooKeeper dupZookeeper = new ZooKeeper(connection.getServers(), curZookeeper.getSessionTimeout(),
            watcher, curZookeeper.getSessionId(), curZookeeper.getSessionPasswd());
    // wait until connected, then close
    while (dupZookeeper.getState() != States.CONNECTED) {
        Thread.sleep(10);
    }
    Assert.assertEquals(dupZookeeper.getState(), States.CONNECTED,
            "Fail to connect to zk using current session info");
    dupZookeeper.close();

    // make sure session expiry really happens
    waitNewSession.await();
    zkClient.unsubscribeStateChanges(listener);

    connection = (ZkConnection) zkClient.getConnection();
    curZookeeper = connection.getZookeeper();

    String newSessionId = Long.toHexString(curZookeeper.getSessionId());
    LOG.info("After session expiry. sessionId: " + newSessionId + ", zk: " + curZookeeper);
    Assert.assertNotSame(newSessionId, oldSessionId, "Fail to expire current session, zk: " + curZookeeper);
}

From source file:org.apache.helix.ZkTestHelper.java

License:Apache License

/**
 * expire zk session asynchronously//w  ww  .ja v a2 s  .  co m
 * @param zkClient
 * @throws Exception
 */
public static void asyncExpireSession(final ZkClient zkClient) throws Exception {
    ZkConnection connection = ((ZkConnection) zkClient.getConnection());
    ZooKeeper curZookeeper = connection.getZookeeper();
    LOG.info("Before expiry. sessionId: " + Long.toHexString(curZookeeper.getSessionId()));

    Watcher watcher = new Watcher() {
        @Override
        public void process(WatchedEvent event) {
            LOG.info("Process watchEvent: " + event);
        }
    };

    final ZooKeeper dupZookeeper = new ZooKeeper(connection.getServers(), curZookeeper.getSessionTimeout(),
            watcher, curZookeeper.getSessionId(), curZookeeper.getSessionPasswd());
    // wait until connected, then close
    while (dupZookeeper.getState() != States.CONNECTED) {
        Thread.sleep(10);
    }
    dupZookeeper.close();

    connection = (ZkConnection) zkClient.getConnection();
    curZookeeper = connection.getZookeeper();

    // System.err.println("zk: " + oldZookeeper);
    LOG.info("After expiry. sessionId: " + Long.toHexString(curZookeeper.getSessionId()));
}

From source file:org.apache.nifi.cluster.coordination.node.CuratorNodeProtocolSender.java

License:Apache License

@Override
protected synchronized InetSocketAddress getServiceAddress() throws IOException {
    if (coordinatorAddress != null) {
        return coordinatorAddress;
    }//from w  w  w  .ja  va 2  s. c om

    final RetryPolicy retryPolicy = new RetryNTimes(0, 0);
    final CuratorFramework curatorClient = CuratorFrameworkFactory.newClient(zkConfig.getConnectString(),
            zkConfig.getSessionTimeoutMillis(), zkConfig.getConnectionTimeoutMillis(), retryPolicy);
    curatorClient.start();

    try {
        // Get coordinator address and add watcher to change who we are heartbeating to if the value changes.
        final byte[] coordinatorAddressBytes = curatorClient.getData().usingWatcher(new Watcher() {
            @Override
            public void process(final WatchedEvent event) {
                coordinatorAddress = null;
            }
        }).forPath(coordinatorPath);

        if (coordinatorAddressBytes == null || coordinatorAddressBytes.length == 0) {
            throw new NoClusterCoordinatorException(
                    "No node has yet been elected Cluster Coordinator. Cannot establish connection to cluster yet.");
        }

        final String address = new String(coordinatorAddressBytes, StandardCharsets.UTF_8);

        final String[] splits = address.split(":");
        if (splits.length != 2) {
            final String message = String.format(
                    "Attempted to determine Cluster Coordinator address. Zookeeper indicates "
                            + "that address is %s, but this is not in the expected format of <hostname>:<port>",
                    address);
            logger.error(message);
            throw new ProtocolException(message);
        }

        logger.info(
                "Determined that Cluster Coordinator is located at {}; will use this address for sending heartbeat messages",
                address);

        final String hostname = splits[0];
        final int port;
        try {
            port = Integer.parseInt(splits[1]);
            if (port < 1 || port > 65535) {
                throw new NumberFormatException("Port must be in the range of 1 - 65535 but got " + port);
            }
        } catch (final NumberFormatException nfe) {
            final String message = String
                    .format("Attempted to determine Cluster Coordinator address. Zookeeper indicates "
                            + "that address is %s, but the port is not a valid port number", address);
            logger.error(message);
            throw new ProtocolException(message);
        }

        final InetSocketAddress socketAddress = InetSocketAddress.createUnresolved(hostname, port);
        coordinatorAddress = socketAddress;
        return socketAddress;
    } catch (final NoNodeException nne) {
        logger.info(
                "No node has yet been elected Cluster Coordinator. Cannot establish connection to cluster yet.");
        throw new NoClusterCoordinatorException(
                "No node has yet been elected Cluster Coordinator. Cannot establish connection to cluster yet.");
    } catch (final NoClusterCoordinatorException ncce) {
        throw ncce;
    } catch (Exception e) {
        throw new IOException("Unable to determine Cluster Coordinator from ZooKeeper", e);
    } finally {
        curatorClient.close();
    }
}

From source file:org.apache.nifi.cluster.coordination.node.NodeClusterCoordinator.java

License:Apache License

private String getElectedActiveCoordinatorAddress() throws IOException {
    final String curAddress = coordinatorAddress;
    if (curAddress != null) {
        return curAddress;
    }/*from   w ww .j  a v a 2s  . c  om*/

    try {
        // Get coordinator address and add watcher to change who we are heartbeating to if the value changes.
        final byte[] coordinatorAddressBytes = curatorClient.getData().usingWatcher(new Watcher() {
            @Override
            public void process(final WatchedEvent event) {
                coordinatorAddress = null;
            }
        }).forPath(coordinatorPath);
        final String address = coordinatorAddress = new String(coordinatorAddressBytes, StandardCharsets.UTF_8);

        logger.info(
                "Determined that Cluster Coordinator is located at {}; will use this address for sending heartbeat messages",
                address);
        return address;
    } catch (Exception e) {
        throw new IOException("Unable to determine Cluster Coordinator from ZooKeeper", e);
    }
}

From source file:org.apache.nifi.controller.cluster.ClusterProtocolHeartbeater.java

License:Apache License

@Override
public String getHeartbeatAddress() throws IOException {
    final String curAddress = coordinatorAddress;
    if (curAddress != null) {
        return curAddress;
    }// ww  w .j a v  a2s . c  om

    try {
        // Get coordinator address and add watcher to change who we are heartbeating to if the value changes.
        final byte[] coordinatorAddressBytes = curatorClient.getData().usingWatcher(new Watcher() {
            @Override
            public void process(final WatchedEvent event) {
                coordinatorAddress = null;
            }
        }).forPath(coordinatorPath);
        final String address = coordinatorAddress = new String(coordinatorAddressBytes, StandardCharsets.UTF_8);

        logger.info(
                "Determined that Cluster Coordinator is located at {}; will use this address for sending heartbeat messages",
                address);
        return address;
    } catch (Exception e) {
        throw new IOException("Unable to determine Cluster Coordinator from ZooKeeper", e);
    }
}

From source file:org.apache.nifi.controller.cluster.ZooKeeperHeartbeater.java

License:Apache License

private String getHeartbeatAddress() throws IOException {
    final String curAddress = coordinatorAddress;
    if (curAddress != null) {
        return curAddress;
    }/*  ww  w  .ja  va2 s.co  m*/

    try {
        // Get coordinator address and add watcher to change who we are heartbeating to if the value changes.
        final byte[] coordinatorAddressBytes = curatorClient.getData().usingWatcher(new Watcher() {
            @Override
            public void process(final WatchedEvent event) {
                coordinatorAddress = null;
            }
        }).forPath(coordinatorPath);
        final String address = coordinatorAddress = new String(coordinatorAddressBytes, StandardCharsets.UTF_8);

        logger.info(
                "Determined that Cluster Coordinator is located at {}; will use this address for sending heartbeat messages",
                address);
        return address;
    } catch (Exception e) {
        throw new IOException("Unable to determine Cluster Coordinator from ZooKeeper", e);
    }
}