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:com.sonian.elasticsearch.zookeeper.client.ZooKeeperClientService.java

License:Apache License

@Override
public Set<String> listNodes(final String path, final NodeListChangedListener nodeListChangedListener)
        throws InterruptedException {
    if (!lifecycle.started()) {
        throw new ZooKeeperClientException("listNodes is called after service was stopped");
    }//from  w ww  . j  a v  a2  s . com
    Set<String> res = new HashSet<String>();
    final Watcher watcher = (nodeListChangedListener != null) ? new Watcher() {
        @Override
        public void process(WatchedEvent event) {
            if (event.getType() == Watcher.Event.EventType.NodeChildrenChanged) {
                nodeListChangedListener.onNodeListChanged();
            }
        }
    } : null;
    try {

        List<String> children = zooKeeperCall("Cannot list nodes", new Callable<List<String>>() {
            @Override
            public List<String> call() throws Exception {
                return zooKeeper.getChildren(path, watcher);
            }
        });

        if (children == null) {
            return null;
        }
        for (String childPath : children) {
            res.add(extractLastPart(childPath));
        }
        return res;
    } catch (KeeperException e) {
        throw new ZooKeeperClientException("Cannot list nodes", e);
    }
}

From source file:com.sonian.elasticsearch.zookeeper.client.ZooKeeperClientService.java

License:Apache License

private Watcher wrapNodeListener(final NodeListener nodeListener) {
    if (nodeListener != null) {
        return new Watcher() {
            @Override/*from  w  ww.  j  a v a 2  s  . c  om*/
            public void process(WatchedEvent event) {
                switch (event.getType()) {
                case NodeCreated:
                    nodeListener.onNodeCreated(event.getPath());
                    break;
                case NodeDeleted:
                    nodeListener.onNodeDeleted(event.getPath());
                    break;
                case NodeDataChanged:
                    nodeListener.onNodeDataChanged(event.getPath());
                    break;
                }
            }
        };
    } else {
        return null;
    }
}

From source file:com.splicemachine.ddl.ZooKeeperDDLWatchChecker.java

License:Apache License

@Override
public boolean initialize(final CommunicationListener changeIdListener) throws IOException {

    this.id = zkClient.registerThisServer();
    if (id == null)
        return false; //not a server, so inform the world
    if (id.startsWith("/"))
        id = id.substring(1); //strip the leading / to make sure that we register properly
    changeIdWatcher = new Watcher() {
        @Override// ww  w.  j a v a2s . com
        public void process(WatchedEvent watchedEvent) {
            if (watchedEvent.getType().equals(Event.EventType.NodeChildrenChanged)) {
                if (LOG.isTraceEnabled())
                    LOG.trace("Received watch event, signalling refresh");
                changeIdListener.onCommunicationEvent(watchedEvent.getPath());
            }
        }
    };

    return true;
}

From source file:com.spotify.helios.servicescommon.coordination.DefaultZooKeeperClient.java

License:Apache License

public DefaultZooKeeperClient(final CuratorFramework client, final String clusterId) {
    this.client = client;
    this.clusterId = clusterId;

    if (clusterId == null) {
        this.clusterIdExists = null;
        this.watcher = null;
        this.connectionStateListener = null;
        return;/*from   w w w  . j av  a  2s  . c o  m*/
    }

    this.clusterIdExists = new AtomicBoolean(false);

    this.watcher = new Watcher() {
        @Override
        public void process(WatchedEvent event) {
            log.info("DefaultZooKeeperClient processing WatchedEvent - {}", event);
            checkClusterIdExists(clusterId, "watcher");
        }
    };

    connectionStateListener = new ConnectionStateListener() {
        @Override
        public void stateChanged(CuratorFramework client, ConnectionState newState) {
            log.info("DefaultZooKeeperClient connection state change - {}", newState);
            if (newState == ConnectionState.RECONNECTED) {
                checkClusterIdExists(clusterId, "connectionStateListener");
            }
        }
    };
}

From source file:com.taobao.adfs.zookeeper.ZookeeperClientManager.java

License:Apache License

public synchronized ZooKeeper create(String connectString, int sessionTimeout) throws IOException {
    ZooKeeper zookeeper = zookeeperRepository.get(connectString);
    if (zookeeper != null) {
        Utilities.logDebug(logger, "reuse zookeeper client, address=", connectString);
        return zookeeper;
    }//w  w  w.j a  v  a 2 s. c om
    this.timeout = sessionTimeout;

    Watcher watcher = new Watcher() {
        public void process(WatchedEvent event) {
            switch (event.getType()) {
            case None: {
                connectionEvent(event);
                break;
            }
            }
        }
    };
    zookeeper = new ZooKeeper(connectString, sessionTimeout, watcher);
    try {
        connectedSignal.await();
    } catch (InterruptedException e) {
        Utilities.logDebug(logger, "notify by SynConnected.");
    }
    zookeeperRepository.put(connectString, zookeeper);
    Utilities.logDebug(logger, "create zookeeper client, address=", connectString);
    return zookeeper;
}

From source file:com.taobao.common.tedis.replicator.ZKTest.java

License:Open Source License

@Test
public void testConfig() throws Exception {
    final ZKClient client = new ZKClient("localhost:2181", 500000);
    client.init();/*  w w  w. j  av a 2 s  .c  o  m*/

    String path = ZKUtil.contact("tedis", "replicator-config");
    path = ZKUtil.contact(ZKUtil.MUTEXLOCK_ROOT, path);
    path = ZKUtil.normalize(path);

    if (client.useAble()) {
        client.delete(path);

        new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
                String path = ZKUtil.contact("tedis", "replicator-config");
                path = ZKUtil.contact(ZKUtil.MUTEXLOCK_ROOT, path);
                path = ZKUtil.normalize(path);
                try {
                    client.rcreate(path, "word".getBytes());
                } catch (ZKException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }).start();

        if (!client.exists(path)) {
            client.rcreate(path, "test".getBytes());
            System.out.println("create path");
        }
        System.out.println(path);
        System.out.println(new String(client.getData(path, new Watcher() {

            @Override
            public void process(WatchedEvent event) {
                System.out.println(event.getPath());
                try {
                    System.out.println(new String(client.getData(event.getPath())));
                } catch (ZKException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        })));

        Thread.sleep(10000);
    }

}

From source file:com.test.sharksharding.use.resource.ZkSetData.java

License:Apache License

public @Test void testSetData() {
    try (BufferedReader reader = new BufferedReader(new FileReader("c:/shark-datasource.xml"))) {
        StringBuffer str = new StringBuffer();
        String value = "";
        while (null != (value = reader.readLine()))
            str.append(value);/*from w  w  w. ja va2 s.c o  m*/
        final CountDownLatch countDownLatch = new CountDownLatch(1);
        ZooKeeper zk_client = new ZooKeeper("ip:port", 30000, new Watcher() {
            @Override
            public void process(WatchedEvent event) {
                final KeeperState STATE = event.getState();
                switch (STATE) {
                case SyncConnected:
                    countDownLatch.countDown();
                    logger.info("connection zookeeper success");
                    break;
                case Disconnected:
                    logger.warn("zookeeper connection is disconnected");
                    break;
                case Expired:
                    logger.error("zookeeper session expired");
                    break;
                case AuthFailed:
                    logger.error("authentication failure");
                default:
                    break;
                }
            }
        });
        countDownLatch.await();
        zk_client.setData("/info/datasource", str.toString().getBytes(), -1);
        logger.info("insert success");
    } catch (Exception e) {
        logger.error("insert fail", e);
    }
}

From source file:com.twitter.common.zookeeper.SingletonServiceTest.java

License:Apache License

@Test
public void testNonLeaderDisconnect() throws Exception {
    CountDownLatch elected = new CountDownLatch(1);
    listener.onLeading(EasyMock.<LeaderControl>anyObject());
    expectLastCall().andAnswer(countDownAnswer(elected));
    listener.onDefeated(null);/*  ww w. ja  v  a2s. c o m*/
    expectLastCall().anyTimes();

    control.replay();

    ZooKeeperClient zkClient = createZkClient();
    String path = "/fake/path";
    // Create a fake leading candidate node to ensure that the leader in this test is never
    // elected.
    ZooKeeperUtils.ensurePath(zkClient, ZooKeeperUtils.OPEN_ACL_UNSAFE, path);
    String leaderNode = zkClient.get().create(path + "/" + SingletonService.LEADER_ELECT_NODE_PREFIX,
            "fake_leader".getBytes(), ZooKeeperUtils.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL);

    serverSet = new ServerSetImpl(zkClient, path);
    candidate = SingletonService.createSingletonCandidate(zkClient, path, ZooKeeperUtils.OPEN_ACL_UNSAFE);
    DefeatOnDisconnectLeader leader = new DefeatOnDisconnectLeader(zkClient, listener);
    service = new SingletonService(serverSet, candidate);
    service.lead(InetSocketAddress.createUnresolved("foo", PORT_A),
            ImmutableMap.of("http-admin", InetSocketAddress.createUnresolved("foo", PORT_B)), leader);

    final CountDownLatch disconnected = new CountDownLatch(1);
    zkClient.register(new Watcher() {
        @Override
        public void process(WatchedEvent event) {
            if ((event.getType() == EventType.None) && (event.getState() == KeeperState.Disconnected)) {
                disconnected.countDown();
            }
        }
    });

    shutdownNetwork();
    disconnected.await();

    restartNetwork();
    zkClient.get().delete(leaderNode, ZooKeeperUtils.ANY_VERSION);
    // Upon deletion of the fake leader node, the candidate should become leader.
    elected.await();
}

From source file:com.twitter.common.zookeeper.ZooKeeperClient.java

License:Apache License

/**
 * Returns the current active ZK connection or establishes a new one if none has yet been
 * established or a previous connection was disconnected or had its session time out.  This
 * method will attempt to re-use sessions when possible.
 *
 * @param connectionTimeout the maximum amount of time to wait for the connection to the ZK
 *     cluster to be established; 0 to wait forever
 * @return a connected ZooKeeper client//from   w  w w  .  j  a v a 2  s  .  com
 * @throws ZooKeeperConnectionException if there was a problem connecting to the ZK cluster
 * @throws InterruptedException if interrupted while waiting for a connection to be established
 * @throws TimeoutException if a connection could not be established within the configured
 *     session timeout
 */
public synchronized ZooKeeper get(Amount<Long, Time> connectionTimeout)
        throws ZooKeeperConnectionException, InterruptedException, TimeoutException {

    if (zooKeeper == null) {
        final CountDownLatch connected = new CountDownLatch(1);
        Watcher watcher = new Watcher() {
            @Override
            public void process(WatchedEvent event) {
                switch (event.getType()) {
                // Guard the None type since this watch may be used as the default watch on calls by
                // the client outside our control.
                case None:
                    switch (event.getState()) {
                    case Expired:
                        LOG.info("Zookeeper session expired. Event: " + event);
                        close();
                        break;
                    case SyncConnected:
                        connected.countDown();
                        break;
                    }
                }

                eventQueue.offer(event);
            }
        };

        try {
            zooKeeper = (sessionState != null)
                    ? new ZooKeeper(zooKeeperServers, sessionTimeoutMs, watcher, sessionState.sessionId,
                            sessionState.sessionPasswd)
                    : new ZooKeeper(zooKeeperServers, sessionTimeoutMs, watcher);
        } catch (IOException e) {
            throw new ZooKeeperConnectionException("Problem connecting to servers: " + zooKeeperServers, e);
        }

        if (connectionTimeout.getValue() > 0) {
            if (!connected.await(connectionTimeout.as(Time.MILLISECONDS), TimeUnit.MILLISECONDS)) {
                close();
                throw new TimeoutException("Timed out waiting for a ZK connection after " + connectionTimeout);
            }
        } else {
            try {
                connected.await();
            } catch (InterruptedException ex) {
                LOG.info("Interrupted while waiting to connect to zooKeeper");
                close();
                throw ex;
            }
        }
        credentials.authenticate(zooKeeper);

        sessionState = new SessionState(zooKeeper.getSessionId(), zooKeeper.getSessionPasswd());
    }
    return zooKeeper;
}

From source file:com.twitter.common.zookeeper.ZooKeeperClient.java

License:Apache License

/**
 * Clients that need to re-establish state after session expiration can register an
 * {@code onExpired} command to execute.
 *
 * @param onExpired the {@code Command} to register
 * @return the new {@link Watcher} which can later be passed to {@link #unregister} for
 *     removal.//from w ww. j  a  va2 s.c o  m
 */
public Watcher registerExpirationHandler(final Command onExpired) {
    Watcher watcher = new Watcher() {
        @Override
        public void process(WatchedEvent event) {
            if (event.getType() == EventType.None && event.getState() == KeeperState.Expired) {
                onExpired.execute();
            }
        }
    };
    register(watcher);
    return watcher;
}