Example usage for org.apache.zookeeper ZooKeeper exists

List of usage examples for org.apache.zookeeper ZooKeeper exists

Introduction

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

Prototype

public void exists(String path, boolean watch, StatCallback cb, Object ctx) 

Source Link

Document

The asynchronous version of exists.

Usage

From source file:com.alibaba.wasp.master.OfflineCallback.java

License:Apache License

@Override
public void processResult(int rc, String path, Object ctx, String name) {
    if (rc == KeeperException.Code.NODEEXISTS.intValue()) {
        LOG.warn("Node for " + path + " already exists");
    } else if (rc != 0) {
        // This is result code. If non-zero, need to resubmit.
        LOG.warn("rc != 0 for " + path + " -- retryable connectionloss -- "
                + "FIX see http://wiki.apache.org/hadoop/ZooKeeper/FAQ#A2");
        this.counter.addAndGet(1);
        return;/*from   w  w w .ja  va 2 s.com*/
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("rs=" + ctx + ", server=" + destination);
    }
    // Async exists to set a watcher so we'll get triggered when
    // unassigned node changes.
    ZooKeeper zk = this.zkw.getRecoverableZooKeeper().getZooKeeper();
    zk.exists(path, this.zkw, callBack, ctx);
}

From source file:com.anteam.demo.zookeeper.DataMonitor.java

License:Apache License

public DataMonitor(ZooKeeper zk, String znode, Watcher chainedWatcher, DataMonitorListener listener) {
    this.zk = zk;
    this.znode = znode;
    this.chainedWatcher = chainedWatcher;
    this.listener = listener;
    // Get things started by checking if the node exists. We are going
    // to be completely event driven
    zk.exists(znode, true, this, null);
}

From source file:com.jkoolcloud.tnt4j.streams.configure.zookeeper.ZKConfigManager.java

License:Apache License

/**
 * Initializes ZK ensemble node data monitoring (over {@link org.apache.zookeeper.Watcher}) and initial data
 * loading./*from  w w w  . j a  v a2 s  .c o  m*/
 * 
 * @param zk
 *            ZooKeeper instance
 * @param path
 *            node path
 * @param zkCfgChangeListener
 *            zookeeper node data change listener instance
 */
public static void handleZKStoredConfiguration(final ZooKeeper zk, final String path,
        final ZKConfigChangeListener zkCfgChangeListener) {
    Watcher watch = new Watcher() {
        @Override
        public void process(WatchedEvent watchedEvent) {
            if (path.equals(watchedEvent.getPath())) {
                if (watchedEvent.getType() == Event.EventType.NodeDataChanged) {
                    LOGGER.log(OpLevel.DEBUG, StreamsResources.getString(StreamsResources.RESOURCE_BUNDLE_NAME,
                            "ZKConfigManager.node.changed"), path);
                    zkCfgChangeListener.reconfigure(zk, path, this);
                } else if (watchedEvent.getType() == Event.EventType.NodeDeleted) {
                    LOGGER.log(OpLevel.DEBUG, StreamsResources.getString(StreamsResources.RESOURCE_BUNDLE_NAME,
                            "ZKConfigManager.node.deleted"), path);
                    zk.exists(path, this, null, null);
                } else if (watchedEvent.getType() == Event.EventType.NodeCreated) {
                    LOGGER.log(OpLevel.DEBUG, StreamsResources.getString(StreamsResources.RESOURCE_BUNDLE_NAME,
                            "ZKConfigManager.node.created"), path);
                    zkCfgChangeListener.reconfigure(zk, path, this);
                }
            }
        }
    };

    Stat nStat = null;

    try {
        nStat = zk.exists(path, false);
    } catch (Exception exc) {
        LOGGER.log(OpLevel.WARNING, StreamsResources.getString(StreamsResources.RESOURCE_BUNDLE_NAME,
                "ZKConfigManager.node.exists.failed"), path, exc);
    }

    if (nStat == null) {
        LOGGER.log(OpLevel.DEBUG, StreamsResources.getString(StreamsResources.RESOURCE_BUNDLE_NAME,
                "ZKConfigManager.node.create.wait"), path);
        zk.exists(path, watch, null, null);
    } else {
        zkCfgChangeListener.reconfigure(zk, path, watch);
    }
}

From source file:com.linkedin.d2.discovery.stores.zk.ZKConnection.java

License:Apache License

private void setDataUnsafe(final String path, final byte[] data, final Callback<None> callback,
        final int count) {
    final ZooKeeper zk = zk();
    final AsyncCallback.StatCallback dataCallback = new AsyncCallback.StatCallback() {
        @Override/*from ww w .j  a  va 2 s .c o  m*/
        public void processResult(int rc, String path, Object ctx, Stat stat) {
            KeeperException.Code code = KeeperException.Code.get(rc);
            switch (code) {
            case OK:
                callback.onSuccess(None.none());
                break;
            case BADVERSION:
                if (count < MAX_RETRIES) {
                    LOG.info("setDataUnsafe: ignored BADVERSION for {}", path);
                    setDataUnsafe(path, data, callback, count + 1);
                } else {
                    callback.onError(KeeperException.create(code));
                }
                break;
            default:
                callback.onError(KeeperException.create(code));
                break;
            }
        }
    };
    final AsyncCallback.StatCallback statCallback = new AsyncCallback.StatCallback() {
        @Override
        public void processResult(int rc, String path, Object ctx, Stat stat) {
            KeeperException.Code code = KeeperException.Code.get(rc);
            switch (code) {
            case OK:
                zk.setData(path, data, stat.getVersion(), dataCallback, null);
                break;
            default:
                callback.onError(KeeperException.create(code));
                break;
            }
        }
    };
    try {
        zk.exists(path, false, statCallback, null);
    } catch (Exception e) {
        callback.onError(e);
    }
}

From source file:com.linkedin.d2.discovery.stores.zk.ZKConnection.java

License:Apache License

private void removeNodeUnsafe(final String path, final Callback<None> callback, final int count) {
    final ZooKeeper zk = zk();

    final AsyncCallback.VoidCallback deleteCallback = new AsyncCallback.VoidCallback() {
        @Override//from  www. j  a  v a 2 s.  co m
        public void processResult(int rc, String path, Object ctx) {
            KeeperException.Code code = KeeperException.Code.get(rc);
            switch (code) {
            case OK:
                callback.onSuccess(None.none());
                break;
            case BADVERSION:
                // Need to retry
                if (count < MAX_RETRIES) {
                    LOG.info("removeNodeUnsafe: retrying after ignoring BADVERSION for {}", path);
                    removeNodeUnsafe(path, callback, count + 1);
                } else {
                    callback.onError(KeeperException.create(code));
                }
                break;
            default:
                callback.onError(KeeperException.create(code));
                break;
            }
        }
    };

    final AsyncCallback.StatCallback existsCallback = new AsyncCallback.StatCallback() {
        @Override
        public void processResult(int rc, String path, Object ctx, Stat stat) {
            KeeperException.Code code = KeeperException.Code.get(rc);
            switch (code) {
            case OK:
                zk.delete(path, stat.getVersion(), deleteCallback, null);
                break;
            case NONODE:
                callback.onSuccess(None.none());
                break;
            default:
                callback.onError(KeeperException.create(code));
                break;
            }
        }
    };

    try {
        zk.exists(path, false, existsCallback, null);
    } catch (Exception e) {
        callback.onError(e);
    }
}

From source file:com.proofpoint.zookeeper.ZookeeperClient.java

License:Apache License

@Override
public Stat exists(final String path) throws Exception {
    if (inBackground) {
        RetryHandler.Call<Void> backgroundCall = new RetryHandler.Call<Void>() {
            @Override/*from  ww w  .j a va2 s  . c om*/
            public Void call(ZooKeeper client, final RetryHandler retryHandler) {
                if (overrideWatcher != null) {
                    client.exists(path, overrideWatcher, new RetryStatCallback(retryHandler), context);
                } else {
                    client.exists(path, watched, new RetryStatCallback(retryHandler), context);
                }
                return null;
            }
        };
        RetryHandler.makeAndStart(this, retryPolicy, backgroundCall);
        return null;
    }

    RetryHandler.Call<Stat> backgroundCall = new RetryHandler.Call<Stat>() {
        @Override
        public Stat call(ZooKeeper client, RetryHandler<Stat> statRetryHandler) throws Exception {
            return (overrideWatcher != null) ? client.exists(path, overrideWatcher)
                    : client.exists(path, watched);
        }
    };
    return RetryHandler.makeAndStart(this, retryPolicy, backgroundCall);
}

From source file:com.thjug.Demo.java

License:Creative Commons License

public void run() throws IOException, KeeperException, InterruptedException {

    final ZooKeeper zk = ZooKeeperFactory.createZooKeeper(new LogWatcher());

    final String createresult = zk.create("/javaapi", "Hello World".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE,
            CreateMode.PERSISTENT_SEQUENTIAL);
    LOG.info("Create Result : {}", createresult);

    zk.exists(createresult, true, new LogStatCallback(), null);

    final Stat existsresult = zk.exists(createresult, true);
    LOG.info("Exists Result : {}", existsresult.toString());

    final Stat setresult = zk.setData(createresult, "Yoyo Land".getBytes(), existsresult.getVersion());
    LOG.info("Set Result : {}", setresult.toString());
}

From source file:com.twitter.distributedlog.BKLogHandler.java

License:Apache License

Future<Void> checkLogStreamExistsAsync() {
    final Promise<Void> promise = new Promise<Void>();
    try {/*from  w w  w  .j  a v  a2s.c  o  m*/
        final ZooKeeper zk = zooKeeperClient.get();
        zk.sync(logMetadata.getLogSegmentsPath(), new AsyncCallback.VoidCallback() {
            @Override
            public void processResult(int syncRc, String path, Object syncCtx) {
                if (KeeperException.Code.NONODE.intValue() == syncRc) {
                    promise.setException(new LogNotFoundException(String
                            .format("Log %s does not exist or has been deleted", getFullyQualifiedName())));
                    return;
                } else if (KeeperException.Code.OK.intValue() != syncRc) {
                    promise.setException(
                            new ZKException("Error on checking log existence for " + getFullyQualifiedName(),
                                    KeeperException.create(KeeperException.Code.get(syncRc))));
                    return;
                }
                zk.exists(logMetadata.getLogSegmentsPath(), false, new AsyncCallback.StatCallback() {
                    @Override
                    public void processResult(int rc, String path, Object ctx, Stat stat) {
                        if (KeeperException.Code.OK.intValue() == rc) {
                            promise.setValue(null);
                        } else if (KeeperException.Code.NONODE.intValue() == rc) {
                            promise.setException(new LogNotFoundException(String.format(
                                    "Log %s does not exist or has been deleted", getFullyQualifiedName())));
                        } else {
                            promise.setException(new ZKException(
                                    "Error on checking log existence for " + getFullyQualifiedName(),
                                    KeeperException.create(KeeperException.Code.get(rc))));
                        }
                    }
                }, null);
            }
        }, null);

    } catch (InterruptedException ie) {
        LOG.error("Interrupted while reading {}", logMetadata.getLogSegmentsPath(), ie);
        promise.setException(new DLInterruptedException(
                "Interrupted while checking " + logMetadata.getLogSegmentsPath(), ie));
    } catch (ZooKeeperClient.ZooKeeperConnectionException e) {
        promise.setException(e);
    }
    return promise;
}

From source file:io.confluent.admin.utils.ClusterStatus.java

License:Apache License

/**
 * Checks whether /brokers/ids is present. This signifies that at least one Kafka broker has
 * registered in ZK./* ww  w .  j a v  a2 s . co m*/
 * @param timeoutMs timeout in ms.
 * @param zookeeper Zookeeper client.
 * @return True if /brokers/ids is present.
 * @throws InterruptedException
 */
private static boolean isKafkaRegisteredInZookeeper(ZooKeeper zookeeper, int timeoutMs)
        throws InterruptedException {
    // Make sure /brokers/ids exists. Countdown when one of the following happen:
    // 1. node created event is triggered (this happens when /brokers/ids is created after the call is made).
    // 2. StatCallback gets a non-null callback (this happens when /brokers/ids exists when the call is made) .
    CountDownLatch kafkaRegistrationSignal = new CountDownLatch(1);
    zookeeper.exists(BROKERS_IDS_PATH, (event) -> {
        log.debug("Got event when checking for existence of /brokers/ids. type={} path={}", event.getType(),
                event.getPath());
        if (event.getType() == Watcher.Event.EventType.NodeCreated) {
            kafkaRegistrationSignal.countDown();
        }
    }, (rc, path, ctx, stat) -> {
        log.debug("StatsCallback got data for path={}, stat={}", path, stat);
        if (stat != null) {
            kafkaRegistrationSignal.countDown();
        }
    }, null);

    boolean kafkaRegistrationTimedOut = !kafkaRegistrationSignal.await(timeoutMs, TimeUnit.MILLISECONDS);
    if (kafkaRegistrationTimedOut) {
        String message = String.format(
                "Timed out waiting for Kafka to create /brokers/ids in Zookeeper. " + "timeout (ms) = %s",
                timeoutMs);
        throw new TimeoutException(message);
    }

    return true;
}

From source file:org.apache.aries.rsa.discovery.zookeeper.subscribe.InterfaceMonitorTest.java

License:Apache License

public void testInterfaceMonitor() throws KeeperException, InterruptedException {
    IMocksControl c = EasyMock.createControl();

    ZooKeeper zk = c.createMock(ZooKeeper.class);
    expect(zk.getState()).andReturn(ZooKeeper.States.CONNECTED).anyTimes();

    String scope = "(myProp=test)";
    String interf = "es.schaaf.test";
    String node = Utils.getZooKeeperPath(interf);

    EndpointListener endpointListener = c.createMock(EndpointListener.class);
    InterfaceMonitor im = new InterfaceMonitor(zk, interf, endpointListener, scope);
    zk.exists(eq(node), eq(im), eq(im), EasyMock.anyObject());
    EasyMock.expectLastCall().once();/*from  ww w .j  a v  a 2 s.  co  m*/

    expect(zk.exists(eq(node), eq(false))).andReturn(new Stat()).anyTimes();
    expect(zk.getChildren(eq(node), eq(false))).andReturn(Collections.<String>emptyList()).once();
    expect(zk.getChildren(eq(node), eq(im))).andReturn(Collections.<String>emptyList()).once();

    c.replay();
    im.start();
    // simulate a zk callback
    WatchedEvent we = new WatchedEvent(EventType.NodeCreated, KeeperState.SyncConnected, node);
    im.process(we);
    c.verify();
}