Example usage for org.apache.zookeeper WatchedEvent getState

List of usage examples for org.apache.zookeeper WatchedEvent getState

Introduction

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

Prototype

public KeeperState getState() 

Source Link

Usage

From source file:org.eclipse.ecf.provider.zookeeper.node.internal.NodeReader.java

License:Open Source License

public void process(WatchedEvent event) {

    if (this.isDisposed) {
        // Already disposed
        return;//from  w w  w . ja v a 2  s  . c o  m
    }
    if (event.getState() == KeeperState.Disconnected || event.getState() == KeeperState.Expired
            || event.getType() == EventType.NodeDeleted) {
        /*
         * This node is deleted or the connection with the server we're
         * reading from is down. This discovered service wrapped by this
         * node is no more available.
         */
        dispose();
    }

}

From source file:org.eclipse.ecf.provider.zookeeper.node.internal.ReadRoot.java

License:Open Source License

public void process(final WatchedEvent event) {
    ZooDiscoveryContainer.CACHED_THREAD_POOL.execute(new Runnable() {
        public void run() {
            synchronized (connectionLock) {
                if (watchManager.isDisposed())
                    return;

                switch (event.getState()) {
                case Disconnected:
                    ReadRoot.this.isConnected = false;
                    connect();/* w ww  . j  ava  2s . c om*/
                    break;
                case Expired:
                    ReadRoot.this.isConnected = false;
                    connect();
                    break;
                case SyncConnected:
                    if (!ReadRoot.this.isConnected) {
                        ReadRoot.this.isConnected = true;
                        ReadRoot.this.watchManager.addZooKeeper(ReadRoot.this.readKeeper);
                        ReadRoot.this.readKeeper.exists(INode.ROOT, ReadRoot.this, null, null);
                        ReadRoot.this.readKeeper.getChildren(INode.ROOT, ReadRoot.this, ReadRoot.this, null);
                    }
                    break;

                // ignore @deprecated cases
                }
                switch (event.getType()) {
                case NodeDeleted:
                    if (event.getPath() == null || event.getPath().equals(INode.ROOT))
                        break;
                    ReadRoot.this.nodeReaders.remove(event.getPath());
                    break;
                case NodeChildrenChanged:
                    if (ReadRoot.this.isConnected) {
                        ReadRoot.this.readKeeper.exists(INode.ROOT, ReadRoot.this, null, null);
                        ReadRoot.this.readKeeper.getChildren(INode.ROOT, ReadRoot.this, ReadRoot.this, null);
                    }
                    break;
                }
            }
        }
    });
}

From source file:org.eclipse.ecf.provider.zookeeper.node.internal.WriteRoot.java

License:Open Source License

@SuppressWarnings({ "incomplete-switch" })
public void process(final WatchedEvent event) {
    ZooDiscoveryContainer.CACHED_THREAD_POOL.execute(new Runnable() {
        public void run() {
            synchronized (connectionLock) {
                switch (event.getState()) {
                case Disconnected:
                    isConnected = false;
                    watchManager.unpublishAll();
                    connect();/*from   ww w.j  ava 2 s  .c o m*/
                    break;
                case Expired:
                    isConnected = false;
                    watchManager.unpublishAll();
                    connect();
                    break;
                case SyncConnected:
                    if (!isConnected) {
                        isConnected = true;
                        watchManager.addZooKeeper(writeKeeper);
                        watchManager.republishAll();
                    }
                    break;
                // ignore @deprecated cases
                }
            }
        }
    });
}

From source file:org.eclipse.gyrex.cloud.internal.admin.NodeConfigurer.java

License:Open Source License

@Override
public IStatus configureConnection(final String connectString) {
    ZooKeeper zk = null;//  ww  w. j a v  a2s  . c om
    try {
        if (connectString != null) {
            // try connect
            // TODO: not sure if this makes sense when configuring a remote system
            final CountDownLatch connected = new CountDownLatch(1);
            zk = new ZooKeeper(connectString, 5000, new Watcher() {

                @Override
                public void process(final WatchedEvent event) {
                    if ((event.getType() == EventType.None)
                            && (event.getState() == KeeperState.SyncConnected)) {
                        connected.countDown();
                    }
                }
            });

            // wait at most 5 seconds for a connection
            connected.await(5000, TimeUnit.MILLISECONDS);

            if (zk.getState() != States.CONNECTED) {
                throw new IllegalStateException(String.format(
                        "Timeout waiting for a connection to '%s'. Please verify the connect string.",
                        connectString));
            }

            // try reading some information from the cloud
            if (null == zk.exists(IZooKeeperLayout.PATH_GYREX_ROOT.toString(), false)) {
                // maybe a new cloud, try initialization
                final String path = IZooKeeperLayout.PATH_GYREX_ROOT.toString();
                final String createdPath = zk.create(path, null, ZooDefs.Ids.OPEN_ACL_UNSAFE,
                        CreateMode.PERSISTENT);
                if (!path.equals(createdPath)) {
                    throw new IllegalStateException(String
                            .format("created path does not match expected path (%s != %s)", path, createdPath));
                }
            }

            // at this point the connect string seems to be ok
            // TODO: store it in ZooKeeper and implement ZK to local sync
        }

        // store in instance preferences if local
        if (new NodeInfo().getNodeId().equals(nodeId)) {
            final Preferences preferences = InstanceScope.INSTANCE.getNode(CloudActivator.SYMBOLIC_NAME)
                    .node(ZooKeeperGateConfig.PREF_NODE_ZOOKEEPER);
            if (connectString != null) {
                preferences.put(ZooKeeperGateConfig.PREF_KEY_CLIENT_CONNECT_STRING, connectString);
            } else {
                preferences.remove(ZooKeeperGateConfig.PREF_KEY_CLIENT_CONNECT_STRING);
            }
            preferences.flush();

            // remove connection to cloud
            CloudState.unregisterNode();

            // bring down ZooKeeper Gate
            ZooKeeperGateApplication.reconnect();

            // register with new cloud
            CloudState.registerNode();
        }
    } catch (final Exception e) {
        LOG.debug("Exception connecting to cloud using connect string {}.", connectString, e);
        return new Status(IStatus.ERROR, CloudActivator.SYMBOLIC_NAME,
                "Unable to connect to ZooKeeper. " + ExceptionUtils.getRootCauseMessage(e), e);
    } finally {
        if (zk != null) {
            try {
                zk.close();
            } catch (final InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }
    }

    return Status.OK_STATUS;
}

From source file:org.fusesource.ide.zk.zookeeper.data.ZooKeeperConnection.java

License:Apache License

@Override
public void process(WatchedEvent event) {
    KeeperState state = event.getState();

    if (state == KeeperState.SyncConnected) {
        ZooKeeperConnectionDescriptor zooKeeperConnectionDescriptor = getDescriptor();
        List<AuthInfo> authInfos = zooKeeperConnectionDescriptor.getAuthInfos();
        if (authInfos != null && !authInfos.isEmpty()) {

            for (AuthInfo authInfo : authInfos) {
                String scheme = authInfo.getScheme();
                byte[] auth;

                try {
                    auth = authInfo.getAuth();
                } catch (IOException e) {
                    e.printStackTrace();
                    continue;
                }//from   www . j av  a 2  s  .c  o  m

                // TODO: Is the lack of thread saftey of this method a concern here?
                addAuthInfo(scheme, auth);
            }
        }
    }

    fireConnectionStateChanged();
}

From source file:org.fusesource.meshkeeper.distribution.registry.zk.ZooKeeperRegistry.java

License:Open Source License

public void start() throws Exception {
    synchronized (this) {
        if (zk == null) {
            //ZK doesn't like schemes, so just take host and port
            URI uri = new URI(connectUrl);

            zk = new ZooKeeper(uri.getHost() + ":" + uri.getPort(), sessionTimeout, new Watcher() {
                public void process(WatchedEvent event) {
                    switch (event.getState()) {
                    case SyncConnected:
                        connected.countDown();
                        break;

                    }//  ww w. j a v  a  2 s .  co m
                }
            });
            zk.addAuthInfo("digest", (userid + ":" + password).getBytes());

        }
    }

    // Wait for the client to establish a connection.
    if (connectTimeout > 0) {
        if (!connected.await(connectTimeout, TimeUnit.MILLISECONDS)) {
            throw new IOException("Failed to connect to ZooKeeper at " + connectUrl + " within "
                    + connectTimeout + " milliseconds.");
        }
    } else {
        connected.await();
    }
}

From source file:org.glassfish.grizzly.memcached.zookeeper.ZKClient.java

License:Open Source License

private boolean processStateChanged(final WatchedEvent event) {
    if (event == null) {
        throw new IllegalArgumentException("event must not be null");
    }/*from  w  w w .  j  ava  2s .c o m*/
    final Watcher.Event.KeeperState eventState = event.getState();
    final String eventPath = event.getPath();
    final boolean isStateChangedEvent;
    // state changed
    if (eventPath == null) {
        lock.lock();
        try {
            currentState = eventState;
            lockCondition.signalAll();
        } finally {
            lock.unlock();
        }
        isStateChangedEvent = true;
    } else {
        isStateChangedEvent = false;
    }
    if (eventState == Watcher.Event.KeeperState.Expired) {
        try {
            reconnect();
        } catch (Exception e) {
            if (logger.isLoggable(Level.SEVERE)) {
                logger.log(Level.SEVERE, "failed to reconnect the zookeeper server", e);
            }
        }
    }
    return isStateChangedEvent;
}

From source file:org.goldenorb.zookeeper.ConnectWatcher.java

License:Apache License

/**
 * This method executes its content given a Watcher event.
 * /* w w  w . j  av a 2s. c om*/
 * @param event
 *          - WatchedEvent
 */
public void process(WatchedEvent event) {
    if (event.getState() == KeeperState.SyncConnected) {
        connectedSignal.countDown();
    }
}

From source file:org.hummer.config.WatcherAdapter.java

License:Apache License

public void process(WatchedEvent event) {
    WatchEvent evt = new WatchEvent();
    evt.setState(event.getState().getIntValue());
    evt.setType(event.getType().getIntValue());
    evt.setArg(event.getPath());/*from  w w  w .ja v  a  2 s  .  c o m*/
    innerWatcher.onEvent(evt);
}

From source file:org.inria.myriads.snoozenode.groupmanager.leadelection.api.impl.ZooKeeperLeaderElection.java

License:Open Source License

/**
 * Processes the watcher event.//from   w  w w. j ava  2 s.c o m
 * 
 * @param event     The watched event
 */
public void process(WatchedEvent event) {
    Guard.check(event);
    log_.debug("Processing the watch event");

    KeeperState state = event.getState();
    try {
        switch (state) {
        case Disconnected:
            log_.debug("Received disconnected event!");
            initializeZooKeeper();
            break;

        case Expired:
            log_.debug("Received expired event!");
            initializeZooKeeper();
            break;

        case SyncConnected:
            log_.debug("Connection estabilished!");
            break;

        default:
            log_.debug(String.format("Unknown keeper state received: %s", state));
        }
    } catch (Exception exception) {
        log_.debug("Exception during zookeeper initialization", exception);
    }
}