Example usage for org.apache.zookeeper ZooKeeper ZooKeeper

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

Introduction

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

Prototype

public ZooKeeper(String connectString, int sessionTimeout, Watcher watcher) throws IOException 

Source Link

Document

To create a ZooKeeper client object, the application needs to pass a connection string containing a comma separated list of host:port pairs, each corresponding to a ZooKeeper server.

Usage

From source file:ZooKeeperSetAcls.java

License:Apache License

public ZooKeeperSetAcls(String args[]) {
    if (!cl.parseOptions(args)) {
        System.exit(1);/*ww  w.  jav  a2  s  . c o m*/
    }

    Watcher watcher = new MyWatcher();
    System.out.println("Connecting to " + cl.getOption("server"));
    try {
        zk = new ZooKeeper(cl.getOption("server"), Integer.parseInt(cl.getOption("timeout")), watcher);
    } catch (IOException e) {
        System.err.println("IOError: " + e.getMessage());
        System.exit(2);
    }

    for (MyPathWithACLs pwa : cl.getPathsWithACLs()) {
        try {
            zk.setACL(pwa.getPath(), pwa.getACLs(), -1);
        } catch (NoNodeException e) {
            // if node doesn't exist yet, try to create it with the given
            // ACL
            try {
                zk.create(pwa.getPath(), new byte[0], pwa.getACLs(), CreateMode.PERSISTENT);
            } catch (InterruptedException f) {
                System.err.println("create interrupted: " + f.getMessage());
                System.exit(5);
            } catch (KeeperException f) {
                System.err.println("create operation error: " + f.getMessage());
                System.exit(6);
            }
        } catch (InterruptedException e) {
            System.err.println("setACL interrupted: " + e.getMessage());
            System.exit(3);
        } catch (KeeperException e) {
            System.err.println("setACL operation error: " + e.getMessage());
            System.exit(4);
        }
    }
}

From source file:accismus.benchmark.BenchTestIT.java

License:Apache License

@BeforeClass
public static void setUp() throws Exception {
    String instanceName = "plugin-it-instance";
    instance = new MiniAccumuloInstance(instanceName, new File("target/accumulo-maven-plugin/" + instanceName));
    zk = new ZooKeeper(instance.getZooKeepers(), 30000, null);
}

From source file:akka.cluster.LocalBookKeeper.java

License:Open Source License

public void initializeZookeper() {
    //initialize the zk client with values
    try {//from  ww  w.  j a  v a 2  s.c  om
        zkc = new ZooKeeper("127.0.0.1", ZooKeeperDefaultPort, new emptyWatcher());
        zkc.create("/ledgers", new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        zkc.create("/ledgers/available", new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        // No need to create an entry for each requested bookie anymore as the
        // BookieServers will register themselves with ZooKeeper on startup.
    } catch (KeeperException e) {
    } catch (InterruptedException e) {
    } catch (IOException e) {
    }
}

From source file:at.salzburgresearch.kmt.zkconfig.ZookeeperConfiguration.java

License:Apache License

private void zkInit() throws IOException {
    sync.raiseBarrier();/*from w  w w  .ja va2 s .co m*/
    final CountDownLatch connected = new CountDownLatch(1);
    log.debug("zkInit - connecting");
    // if (zk != null) zk.close();
    zk = new ZooKeeper(zkConnectionString, zkTimeout, new ZKWatcher(connected, sync));

    log.info("zkInit - ensure root node exists");
    try {
        if (connected.await(zkTimeout, TimeUnit.MILLISECONDS)) {
            for (int i = zkRoot.indexOf('/', 1); i > 0; i = zkRoot.indexOf('/', i + 1)) {
                final String path = zkRoot.substring(0, i);
                log.trace("zkInit - checking existence of {}", path);
                if (zk.exists(path, false) == null) {
                    zk.create(path, new byte[] {}, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
                }
            }
            log.debug("zkInit - zkRoot {} exists", zkRoot);
        } else {
            throw new IOException("Timeout while establishing ZooKeeper connection");
        }
    } catch (InterruptedException e) {
        throw new IOException("Could not connect", e);
    } catch (KeeperException e) {
        throw new IOException("Initial Connection failed - is zookeeper available?", e);
    }
    log.info("zkInit - connected");
    sync.lowerBarrier();
}

From source file:blazingcache.zookeeper.ZKCacheServerLocator.java

License:Apache License

@Override
protected ServerHostData getServer() {

    String leaderPath = basePath + "/leader";
    try {//from w w  w . ja  va  2s .  c  om
        byte[] data;
        if (ownedZk) {
            CountDownLatch connection = new CountDownLatch(1);
            try {
                LOGGER.finest("creating temp ZK client for discovery");
                ZooKeeper client = new ZooKeeper(zkAddress, zkSessiontimeout, new Watcher() {

                    @Override
                    public void process(WatchedEvent event) {
                        if (event.getState() == Event.KeeperState.SyncConnected
                                || event.getState() == Event.KeeperState.ConnectedReadOnly) {
                            connection.countDown();
                        }
                        LOGGER.severe("process ZK event " + event.getState() + " " + event.getType() + " "
                                + event.getPath());
                    }
                });
                try {
                    connection.await(connectTimeout, TimeUnit.MILLISECONDS);
                    LOGGER.finest("ZK client is " + client);
                    // se la connessione non sar stabilita in tempo o c' qualche problem troveremo un ConnectionLoss ad esempio                                        
                    data = client.getData(leaderPath, false, null);
                } finally {
                    client.close();
                }
            } catch (IOException err) {
                LOGGER.log(Level.SEVERE, "zookeeper client not available: " + err);
                return null;
            }

        } else {
            ZooKeeper client = zkSupplier.get();
            if (client == null) {
                LOGGER.log(Level.SEVERE, "zookeeper client available");
                return null;
            }
            data = client.getData(leaderPath, false, null);
        }
        lastKnownServer = ServerHostData.parseHostdata(data);
        return lastKnownServer;
    } catch (KeeperException.NoNodeException nobroker) {
        LOGGER.log(Level.SEVERE, "zookeeper client error", nobroker);
        return null;
    } catch (KeeperException | InterruptedException err) {
        LOGGER.log(Level.SEVERE, "zookeeper client error", err);
        return null;
    }
}

From source file:blazingcache.zookeeper.ZKClusterManager.java

License:Apache License

/**
 * Creates a new ZooKeeper-based cluster manager.
 *
 * @param zkAddress/*from   www .ja  va 2 s.  co  m*/
 * @param zkTimeout     
 * @param basePath
 * @param listener
 * @param localhostdata
 * @throws Exception
 */
public ZKClusterManager(String zkAddress, int zkTimeout, String basePath, LeaderShipChangeListener listener,
        byte[] localhostdata) throws Exception {
    this.zk = new ZooKeeper(zkAddress, zkTimeout, new SystemWatcher());
    this.zkAddress = zkAddress;
    this.zkTimeout = zkTimeout;
    this.basePath = basePath;
    this.listener = listener;
    this.localhostdata = localhostdata;
    this.leaderpath = basePath + "/leader";
    this.discoverypath = basePath + "/discoverypath";
    this.connectionTimeout = zkTimeout;
}

From source file:blazingcache.zookeeper.ZKClusterManager.java

License:Apache License

/**
*
* Actually creates the ZooKeeper session.
*
* @throws IOException in case of network issues to connect to ZooKeeper
* service//from   w  w w .  j  a  va  2 s  .c o m
*/
public final void restartZK() throws IOException {
    LOGGER.log(Level.SEVERE, "Restarting ZooKeeper client after session expired");
    this.zk = new ZooKeeper(this.zkAddress, this.zkTimeout, new SystemWatcher());
}

From source file:camelagent.util.ZookeeperContainerNamingStrategy.java

License:Open Source License

/**
 * @param path/*w  ww .j  av a 2 s.  c  o m*/
 * @param createMode
 * @throws IOException
 * @throws KeeperException
 * @throws InterruptedException
 * Connects to the Zookeepr server and create a node using the given path
 */
public ZookeeperContainerNamingStrategy(String path, CreateMode createMode)
        throws IOException, KeeperException, InterruptedException {
    prop = new Properties();
    try {
        prop.load(new FileInputStream("config.properties"));
    } catch (Exception e) {

    }
    HOST = prop.getProperty("zookeeper_server");
    zk = new ZooKeeper(HOST, 3000, new ZooKeeperWatcher());

    if (zk.exists(path, false) == null)
        containerId = zk.create(path, NO_DATA, Ids.OPEN_ACL_UNSAFE, createMode);
}

From source file:cc.alessandro.zookeeper.example.SyncPrimitive.java

License:Open Source License

public SyncPrimitive(final String address, final String root) throws IOException {

    if (zk == null) {
        LOG.debug("Starting ZooKeeper ...");
        zk = new ZooKeeper(Preconditions.checkNotNull(address), 3000, this);
        mutex = new Integer(-1);
        LOG.debug("Finished starting ZooKeeper: {}", zk);
    } else {/*from w ww  . j a va 2s . c o  m*/
        mutex = new Integer(-1);
    }

    Preconditions.checkArgument(!Strings.isNullOrEmpty(root));
    this.root = root;
}

From source file:ch.usi.da.dlog.Client.java

License:Open Source License

/**
 * @param args//www .j  a  va2  s .c  om
 */
public static void main(String[] args) {
    String zoo_host = "127.0.0.1:2181";
    if (args.length > 1) {
        zoo_host = args[1];
    }
    if (args.length < 1) {
        System.err.println("Plese use \"Client\" \"ring ID,node ID;global ring ID,node ID\"");
    } else {
        final Map<Integer, Integer> connectMap = parseConnectMap(args[0]);
        try {
            final Client client = new Client(new ZooKeeper(zoo_host, 3000, new DummyWatcher()), connectMap);
            Runtime.getRuntime().addShutdownHook(new Thread("ShutdownHook") {
                @Override
                public void run() {
                    client.stop();
                }
            });
            client.init();
            client.readStdin();
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(1);
        }
    }
}