Example usage for org.apache.zookeeper Watcher process

List of usage examples for org.apache.zookeeper Watcher process

Introduction

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

Prototype

void process(WatchedEvent event);

Source Link

Usage

From source file:org.apache.accumulo.fate.zookeeper.ZooCacheTest.java

License:Apache License

private void testWatchChildrenNode(List<String> initialChildren, Watcher.Event.EventType eventType,
        boolean stillCached) throws Exception {
    WatchedEvent event = new WatchedEvent(eventType, Watcher.Event.KeeperState.SyncConnected, ZPATH);
    TestWatcher exw = new TestWatcher(event);
    zc = new ZooCache(zr, exw);

    Watcher w = watchChildren(initialChildren);
    w.process(event);
    assertTrue(exw.wasCalled());/*from  ww w.j av  a 2  s . c  o m*/
    assertEquals(stillCached, zc.childrenCached(ZPATH));
}

From source file:org.apache.aurora.common.zookeeper.ZooKeeperClient.java

License:Apache License

/**
 * Creates an unconnected client that will lazily attempt to connect on the first call to
 * {@link #get}.  All successful connections will be authenticated with the given
 * {@code credentials}./*from  w  w w .ja v  a2  s .  c o  m*/
 *
 * @param sessionTimeout the ZK session timeout
 * @param credentials the credentials to authenticate with
 * @param chrootPath an optional chroot path
 * @param zooKeeperServers the set of servers forming the ZK cluster
 */
public ZooKeeperClient(Amount<Integer, Time> sessionTimeout, Optional<Credentials> credentials,
        Optional<String> chrootPath, Iterable<InetSocketAddress> zooKeeperServers) {
    this.sessionTimeoutMs = Preconditions.checkNotNull(sessionTimeout).as(Time.MILLISECONDS);
    this.credentials = Preconditions.checkNotNull(credentials);

    if (chrootPath.isPresent()) {
        PathUtils.validatePath(chrootPath.get());
    }

    Preconditions.checkNotNull(zooKeeperServers);
    Preconditions.checkArgument(!Iterables.isEmpty(zooKeeperServers), "Must present at least 1 ZK server");

    Thread watcherProcessor = new Thread("ZookeeperClient-watcherProcessor") {
        @Override
        public void run() {
            while (true) {
                try {
                    WatchedEvent event = eventQueue.take();
                    for (Watcher watcher : watchers) {
                        watcher.process(event);
                    }
                } catch (InterruptedException e) {
                    /* ignore */ }
            }
        }
    };
    watcherProcessor.setDaemon(true);
    watcherProcessor.start();

    Iterable<String> servers = Iterables.transform(ImmutableSet.copyOf(zooKeeperServers),
            InetSocketAddressHelper::toString);
    this.zooKeeperServers = Joiner.on(',').join(servers).concat(chrootPath.or(""));
}

From source file:org.apache.bookkeeper.util.SubTreeCache.java

License:Apache License

private synchronized void handleEvent(WatchedEvent event) {
    Set<Watcher> toReturn = pendingWatchers;
    for (Watcher watcher : pendingWatchers) {
        watcher.process(event);
    }//from w  ww .  j  av  a 2  s .  c  o m
    pendingWatchers.clear();
}

From source file:org.apache.bookkeeper.zookeeper.MockZooKeeperTestCase.java

License:Apache License

protected boolean notifyWatchedEvent(EventType eventType, KeeperState keeperState, String path) {
    Set<Watcher> watcherSet = watchers.remove(path);
    if (null == watcherSet) {
        return false;
    }//  w  ww .j  a  va  2  s .c om
    WatchedEvent event = new WatchedEvent(eventType, keeperState, path);
    for (Watcher watcher : watcherSet) {
        watcher.process(event);
    }
    return true;
}

From source file:org.apache.bookkeeper.zookeeper.ZooKeeperWatcherBase.java

License:Apache License

/**
 * Notify Event to child watchers.//from w w w . j a  va  2 s .  c o  m
 *
 * @param event
 *          Watched event received from ZooKeeper.
 */
private void notifyEvent(WatchedEvent event) {
    // notify child watchers
    for (Watcher w : childWatchers) {
        try {
            w.process(event);
        } catch (Exception t) {
            LOG.warn("Encountered unexpected exception from watcher {} : ", w, t);
        }
    }
}

From source file:org.apache.curator.ConnectionState.java

License:Apache License

@Override
public void process(WatchedEvent event) {
    if (LOG_EVENTS) {
        log.debug("ConnectState watcher: " + event);
    }//w w  w  .  j a  va2s .  co  m

    final boolean eventTypeNone = event.getType() == Watcher.Event.EventType.None;

    if (eventTypeNone) {
        boolean wasConnected = isConnected.get();
        boolean newIsConnected = checkState(event.getState(), wasConnected);
        if (newIsConnected != wasConnected) {
            isConnected.set(newIsConnected);
            connectionStartMs = System.currentTimeMillis();
        }
    }

    // only wait during tests
    if (debugWaitOnExpiredEvent && event.getState() == Event.KeeperState.Expired) {
        waitOnExpiredEvent();
    }

    for (Watcher parentWatcher : parentWatchers) {
        OperationTrace trace = new OperationTrace("connection-state-parent-process", tracer.get(),
                getSessionId());
        parentWatcher.process(event);
        trace.commit();
    }

    if (eventTypeNone)
        handleState(event.getState());
}

From source file:org.apache.distributedlog.zk.TestZKWatcherManager.java

License:Apache License

@Test(timeout = 60000)
public void testRegisterUnregisterWatcher() throws Exception {
    ZKWatcherManager watcherManager = ZKWatcherManager.newBuilder().name("test-register-unregister-watcher")
            .zkc(null).statsLogger(NullStatsLogger.INSTANCE).build();
    String path = "/test-register-unregister-watcher";
    final List<WatchedEvent> events = new LinkedList<WatchedEvent>();
    final CountDownLatch latch = new CountDownLatch(2);
    Watcher watcher = new Watcher() {
        @Override// ww  w  . j  a v a2s.  c o  m
        public void process(WatchedEvent event) {
            events.add(event);
            latch.countDown();
        }
    };
    watcherManager.registerChildWatcher(path, watcher);

    // fire the event
    WatchedEvent event0 = new WatchedEvent(Watcher.Event.EventType.NodeCreated,
            Watcher.Event.KeeperState.SyncConnected, path);
    WatchedEvent event1 = new WatchedEvent(Watcher.Event.EventType.None,
            Watcher.Event.KeeperState.SyncConnected, path);
    WatchedEvent event2 = new WatchedEvent(Watcher.Event.EventType.NodeChildrenChanged,
            Watcher.Event.KeeperState.SyncConnected, path);
    watcher.process(event1);
    watcher.process(event2);

    latch.await();

    assertEquals(2, events.size());
    assertEquals(event1, events.get(0));
    assertEquals(event2, events.get(1));

    // unregister watcher
    watcherManager.unregisterChildWatcher(path, watcher, true);
    // unregister gauges
    watcherManager.unregisterGauges();
    assertEquals(0, watcherManager.childWatches.size());
}

From source file:org.apache.hadoop.hbase.zookeeper.ZooKeeperWrapper.java

License:Apache License

/**
 * This is the primary ZK watcher/*w  w w  .j av a2s .c  om*/
 * @see org.apache.zookeeper.Watcher#process(org.apache.zookeeper.WatchedEvent)
 */
@Override
public synchronized void process(WatchedEvent event) {
    LOG.debug("<" + instanceName + "> Received ZK WatchedEvent: " + "[path=" + event.getPath() + "] "
            + "[state=" + event.getState().toString() + "] " + "[type=" + event.getType().toString() + "]");
    if (event.getType() == EventType.None) {
        if (event.getState() == KeeperState.Expired) {
            this.abort("ZooKeeper Session Expiration, aborting server",
                    new KeeperException.SessionExpiredException());
        } else if (event.getState() == KeeperState.Disconnected) {
            LOG.warn("Disconnected from ZooKeeper");
        } else if (event.getState() == KeeperState.SyncConnected) {
            LOG.info("Reconnected to ZooKeeper");
        }
        return;
    }
    for (Watcher w : listeners) {
        try {
            w.process(event);
        } catch (Throwable t) {
            LOG.error("<" + instanceName + ">" + " Sub-ZK Watcher threw an exception " + "in process()", t);
        }
    }
}

From source file:org.linkedin.zookeeper.client.WatcherChain.java

License:Apache License

@Override
public void process(WatchedEvent event) {
    for (Watcher watcher : _watchers) {
        watcher.process(event);
    }
}

From source file:org.midonet.cluster.backend.MockDirectory.java

License:Apache License

@Override
public List<OpResult> multi(List<Op> ops) throws InterruptedException, KeeperException {
    List<OpResult> results = new ArrayList<>();
    // Fire watchers after finishing multi operation.
    // Copy to the local Set to avoid concurrent access.
    Map<Watcher, WatchedEvent> watchers = new HashMap<>();
    try {/*from w ww . j a  v  a  2  s . c om*/
        for (Op op : ops) {
            Record record = op.toRequestRecord();
            if (record instanceof CreateRequest) {
                // TODO(pino, ryu): should we use the try/catch and create
                // new ErrorResult? Don't for now, but this means that the
                // unit tests can't purposely make a bad Op.
                // try {
                CreateRequest req = CreateRequest.class.cast(record);
                String path = this.add(req.getPath(), req.getData(), CreateMode.fromFlag(req.getFlags()), true);
                results.add(new OpResult.CreateResult(path));
                // } catch (KeeperException e) {
                // e.printStackTrace();
                // results.add(
                // new OpResult.ErrorResult(e.code().intValue()));
                // }
            } else if (record instanceof SetDataRequest) {
                SetDataRequest req = SetDataRequest.class.cast(record);
                this.update(req.getPath(), req.getData(), true);
                // We create the SetDataResult with Stat=null. The
                // Directory interface doesn't provide the Stat object.
                results.add(new OpResult.SetDataResult(null));
            } else if (record instanceof DeleteRequest) {
                DeleteRequest req = DeleteRequest.class.cast(record);
                this.delete(req.getPath(), true);
                results.add(new OpResult.DeleteResult());
            } else {
                // might be CheckVersionRequest or some new type we miss.
                throw new IllegalArgumentException(
                        "This mock implementation only supports Create, " + "SetData and Delete operations");
            }
        }
    } finally {
        synchronized (multiDataWatchers) {
            watchers.putAll(multiDataWatchers);
            multiDataWatchers.clear();
        }
    }

    for (Watcher watcher : watchers.keySet()) {
        watcher.process(watchers.get(watcher));
    }

    return results;
}