Java Code Examples for org.apache.zookeeper.Watcher.Event.EventType

The following examples show how to use org.apache.zookeeper.Watcher.Event.EventType. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: DDMQ   Source File: ZkClient.java    License: Apache License 2.0 6 votes vote down vote up
private void processDataOrChildChange(WatchedEvent event) {
    final String path = event.getPath();

    if (event.getType() == EventType.NodeChildrenChanged || event.getType() == EventType.NodeCreated || event.getType() == EventType.NodeDeleted) {
        Set<IZkChildListener> childListeners = _childListener.get(path);
        if (childListeners != null && !childListeners.isEmpty()) {
            fireChildChangedEvents(path, childListeners);
        }
    }

    if (event.getType() == EventType.NodeDataChanged || event.getType() == EventType.NodeDeleted || event.getType() == EventType.NodeCreated) {
        Set<IZkDataListener> listeners = _dataListener.get(path);
        if (listeners != null && !listeners.isEmpty()) {
            fireDataChangedEvents(event.getPath(), listeners);
        }
    }
}
 
Example 2
Source Project: zookeeper-book-example   Source File: Client.java    License: Apache License 2.0 6 votes vote down vote up
public void process(WatchedEvent e) { 
    System.out.println(e);
    if(e.getType() == Event.EventType.None){
        switch (e.getState()) {
        case SyncConnected:
            connected = true;
            break;
        case Disconnected:
            connected = false;
            break;
        case Expired:
            expired = true;
            connected = false;
            System.out.println("Exiting due to session expiration");
        default:
            break;
        }
    }
}
 
Example 3
Source Project: Distributed-KV   Source File: ZookeeperRegistry.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void process(WatchedEvent event) {
	// 传来NONE类型事件,一般是连接事件等
	if(event.getType() == EventType.None) {
		// 事件状态为:连接中
		if(event.getState() == KeeperState.SyncConnected) {
			// 唤醒等待连接成功的线程
			mutex.lock();
			try {
				// 唤醒等待连接成功的线程
				connCondition.signalAll();
			} finally {
				mutex.unlock();
			}
		}
	}
	
}
 
Example 4
Source Project: helix   Source File: ZkCallbackCache.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void handleDataDeleted(String dataPath) throws Exception {
  // System.out.println("handleDataDeleted: " + dataPath);

  try {
    _lock.writeLock().lock();
    _accessor.unsubscribeDataChanges(dataPath, this);
    _accessor.unsubscribeChildChanges(dataPath, this);

    String parentPath = HelixUtil.getZkParentPath(dataPath);
    String name = HelixUtil.getZkName(dataPath);
    removeFromParentChildSet(parentPath, name);
    _cache.remove(dataPath);

    fireEvents(dataPath, EventType.NodeDeleted);
  } finally {
    _lock.writeLock().unlock();
  }
}
 
Example 5
Source Project: dremio-oss   Source File: ZkDistributedSemaphore.java    License: Apache License 2.0 6 votes vote down vote up
private void onEvent(WatchedEvent event) {

    if(event.getType() == Watcher.Event.EventType.NodeChildrenChanged) {
      Collection<UpdateListener> col = new ArrayList<>(listeners.keySet());
      for(UpdateListener l : col) {
        l.updated();
      }
    } else if (event.getType() == EventType.None && event.getState() == KeeperState.SyncConnected){
      // re set the watcher after a disconnect.
      try {
        setWatcher();
      } catch (Exception e) {
        logger.error("Failure while re-setting watcher after reconnect.", e);
      }
    }
  }
 
Example 6
Source Project: zkclient   Source File: WatcherProcess.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 节点数据变化处理函数
 *
 * @param path 变化的节点
 */
public void dataChange(String path) throws ZkClientException {
    try {
        if (dataListenerPool.containsKey(path)) {
            byte[] data = this.zkClient.getData(path, true);
            ListenerManager manager = dataListenerPool.get(path);
            ListenerManager lm = new ListenerManager(manager.getListener());
            lm.setData(data);
            lm.setEventType(EventType.NodeDataChanged);
            listenerPool.invoker(path, lm);
            LOGGER.debug("node:{} data change.", path);
        }
    } catch (Exception e) {
        throw new ZkClientException("Listener data change error.", e);
    }
}
 
Example 7
Source Project: zookeeper-book-example   Source File: Worker.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Deals with session events like connecting
 * and disconnecting.
 * 
 * @param e new event generated
 */
public void process(WatchedEvent e) { 
    LOG.info(e.toString() + ", " + hostPort);
    if(e.getType() == Event.EventType.None){
        switch (e.getState()) {
        case SyncConnected:
            /*
             * Registered with ZooKeeper
             */
            connected = true;
            break;
        case Disconnected:
            connected = false;
            break;
        case Expired:
            expired = true;
            connected = false;
            LOG.error("Session expired");
        default:
            break;
        }
    }
}
 
Example 8
Source Project: lucene-solr   Source File: ZkStateReader.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void process(WatchedEvent event) {
  // session events are not change events, and do not remove the watcher
  if (EventType.None.equals(event.getType())) {
    return;
  }

  boolean expired = System.nanoTime() > watchUntilNs;
  if (!collectionPropsObservers.containsKey(coll) && expired) {
    // No one can be notified of the change, we can ignore it and "unset" the watch
    log.debug("Ignoring property change for collection {}", coll);
    return;
  }

  log.info("A collection property change: [{}] for collection [{}] has occurred - updating...",
      event, coll);

  refreshAndWatch(true);
}
 
Example 9
Source Project: lucene-solr   Source File: ZkStateReader.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void process(WatchedEvent event) {
  if (ZkStateReader.this.closed) {
    return;
  }

  // session events are not change events, and do not remove the watcher
  if (EventType.None.equals(event.getType())) {
    return;
  }
  log.debug("A collections change: [{}], has occurred - updating...", event);
  refreshAndWatch();
  synchronized (getUpdateLock()) {
    constructState(Collections.emptySet());
  }
}
 
Example 10
Source Project: distributedlog   Source File: ZooKeeperClient.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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.
 */
public Watcher registerExpirationHandler(final ZooKeeperSessionExpireNotifier onExpired) {
    Watcher watcher = new Watcher() {
        @Override
        public void process(WatchedEvent event) {
            if (event.getType() == EventType.None && event.getState() == KeeperState.Expired) {
                try {
                    onExpired.notifySessionExpired();
                } catch (Exception exc) {
                    // do nothing
                }
            }
        }
    };
    register(watcher);
    return watcher;
}
 
Example 11
Source Project: pinpoint   Source File: ZookeeperClusterService.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void process(WatchedEvent event) {
    logger.debug("Process Zookeeper Event({})", event);

    EventType eventType = event.getType();

    if (serviceState.isStarted() && client.isConnected()) {
        // duplicate event possible - but the logic does not change
        if (eventType == EventType.NodeChildrenChanged) {
            String path = event.getPath();

            if (ZookeeperConstants.PINPOINT_WEB_CLUSTER_PATH.equals(path)) {
                webClusterManager.handleAndRegisterWatcher(path);
            } else {
                logger.warn("Unknown Path ChildrenChanged {}.", path);
            }
        }
    }
}
 
Example 12
Source Project: zkclient   Source File: ZKWatcherProcess.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 处理数据改变事件
 * @param event 
 * @return void
 */
public void processNodeChanged(final WatchedEvent event){
    final String path = event.getPath();
    final EventType eventType = event.getType();
    final Set<ZKListener> listeners = client.getNodeListenerMap().get(path);
    if (listeners == null || listeners.isEmpty()) {
        return;
    }
    
    //如果listeners中如果有ZKChildDataListener类型的监听器,
    //证明是此节点是某个节点的子节点,并监听此节点的数据变化
    //这里要单独拿出来,用于触发ZKChildDataListener
    final Set<ZKListener> childDataChangeListners = new CopyOnWriteArraySet<>();
    final Set<ZKListener> nodeListners = new CopyOnWriteArraySet<>();
    
    classifyListeners(listeners,nodeListners,childDataChangeListners);
    
    //提交事件监听进行处理
    submitNodeEvent(nodeListners,childDataChangeListners,path,eventType);
    
    //当前节点作为子节点数据变化
    if(eventType == EventType.NodeDataChanged){
        //提交事件监听进行处理
        submitChildDataEvent(childDataChangeListners,path,eventType);
    }
}
 
Example 13
Source Project: zkclient   Source File: ZKChildDataListener.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void handle(String path, EventType eventType, Object data) throws Exception {
    //子节点个数变化
    if (eventType == EventType.NodeChildrenChanged 
            || eventType == EventType.NodeCreated 
            || eventType == EventType.NodeDeleted) {
        handleChildCountChanged(path,(List<String>)data);
    }
    //子节点数据变化
    if(eventType == EventType.NodeDataChanged){
        handleChildDataChanged(path,data);
    }
    //Session失效
    if(eventType == eventType.None){
        handleSessionExpired(path,data);
    }
}
 
Example 14
Source Project: zkclient   Source File: ZKNodeListener.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void handle(String path, EventType eventType, Object data) throws Exception {
    
    if (eventType == EventType.NodeCreated) {
        handleDataCreated(path,data);
    }
    
    if (eventType == EventType.NodeDataChanged) {
        handleDataChanged(path,data);
    }
    
    if(eventType == EventType.NodeDeleted ){
        handleDataDeleted(path);
    }
    
    if(eventType == eventType.None){
        handleSessionExpired(path);
    }
}
 
Example 15
Source Project: pinpoint   Source File: FlinkClusterService.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void process(WatchedEvent event) {
    logger.debug("Process Zookeeper Event({})", event);

    EventType eventType = event.getType();

    if (serviceState.isStarted() && client.isConnected()) {
        // duplicate event possible - but the logic does not change
        if (eventType == EventType.NodeChildrenChanged) {
            String eventPath = event.getPath();

            if (pinpointFlinkClusterPath.equals(eventPath)) {
                zookeeperClusterManager.handleAndRegisterWatcher(eventPath);
            } else {
                logger.warn("Unknown Path ChildrenChanged {}.", eventPath);
            }
        }
    }
}
 
Example 16
Source Project: distributedlog   Source File: ZooKeeperClient.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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.
 */
public Watcher registerExpirationHandler(final ZooKeeperSessionExpireNotifier onExpired) {
    Watcher watcher = new Watcher() {
        @Override
        public void process(WatchedEvent event) {
            if (event.getType() == EventType.None && event.getState() == KeeperState.Expired) {
                try {
                    onExpired.notifySessionExpired();
                } catch (Exception exc) {
                    // do nothing
                }
            }
        }
    };
    register(watcher);
    return watcher;
}
 
Example 17
Source Project: distributedlog   Source File: TestZooKeeperClient.java    License: Apache License 2.0 6 votes vote down vote up
private void expireZooKeeperSession(ZooKeeper zk, int timeout)
        throws IOException, InterruptedException, KeeperException {
    final CountDownLatch latch = new CountDownLatch(1);

    ZooKeeper newZk = new ZooKeeper(zkServers, timeout, new Watcher() {
        @Override
        public void process(WatchedEvent event) {
            if (event.getType() == EventType.None && event.getState() == KeeperState.SyncConnected) {
                latch.countDown();
            }
        }},
        zk.getSessionId(),
        zk.getSessionPasswd());

    if (!latch.await(timeout, TimeUnit.MILLISECONDS)) {
        throw KeeperException.create(KeeperException.Code.CONNECTIONLOSS);
    }

    newZk.close();
}
 
Example 18
Source Project: bidder   Source File: ZkConnect.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void callBack(String target, EventType etype) throws Exception {
	System.out.println(target + " got event " + etype.name() + ", num=" + etype.getIntValue());
	if (etype.getIntValue() == ZkConnect.DATACHANGED)
		System.out.println(zk.getObject(target));
	zk.addWatch(target, this);
}
 
Example 19
Source Project: bidder   Source File: ZkConnect.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void callBackR(String target, EventType etype) throws Exception {
	System.out.println(target + " got event " + etype.name() + ", num=" + etype.getIntValue());
	// System.out.println(zk.getObject(target));
	if (etype.getIntValue() == ZkConnect.NODECREATED) {
		zk.addRecursiveWatch(target, this, true); // if it's not deleted,
													// then anything under
													// here is added
	} else {
		if (etype.getIntValue() == ZkConnect.NODEDELETED)
			System.out.println("GOT THE DELETION");
	}
}
 
Example 20
Source Project: helix   Source File: ZKHelixManager.java    License: Apache License 2.0 5 votes vote down vote up
void handleNewSessionAsController() {
  if (_leaderElectionHandler != null) {
    _leaderElectionHandler.init();
  } else {
    _leaderElectionHandler =
        new CallbackHandler(this, _zkclient, _keyBuilder.controller(),
            new DistributedLeaderElection(this, _controller, _controllerTimerTasks),
            new EventType[] {
                EventType.NodeChildrenChanged, EventType.NodeDeleted, EventType.NodeCreated
            }, ChangeType.CONTROLLER, _callbackMonitors.get(ChangeType.CONTROLLER));
  }
}
 
Example 21
Source Project: XRTB   Source File: ZkConnect.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void callBackR(String target, EventType etype) throws Exception {
	System.out.println(target + " got event " + etype.name() + ", num=" + etype.getIntValue());
	// System.out.println(zk.getObject(target));
	if (etype.getIntValue() == ZkConnect.NODECREATED) {
		zk.addRecursiveWatch(target, this, true); // if it's not deleted,
													// then anything under
													// here is added
	} else {
		if (etype.getIntValue() == ZkConnect.NODEDELETED)
			System.out.println("GOT THE DELETION");
	}
}
 
Example 22
Source Project: xian   Source File: TestPersistentEphemeralNode.java    License: Apache License 2.0 5 votes vote down vote up
public Trigger(Event.EventType type)
{
    assertNotNull(type);

    this.type = type;
    this.latch = new CountDownLatch(1);
}
 
Example 23
Source Project: helix   Source File: ZKHelixManager.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void addConfigChangeListener(ScopedConfigChangeListener listener, ConfigScopeProperty scope)
    throws Exception {
  Builder keyBuilder = new Builder(_clusterName);

  PropertyKey propertyKey = null;
  switch (scope) {
  case CLUSTER:
    propertyKey = keyBuilder.clusterConfigs();
    break;
  case PARTICIPANT:
    propertyKey = keyBuilder.instanceConfigs();
    break;
  case RESOURCE:
    propertyKey = keyBuilder.resourceConfigs();
    break;
  default:
    break;
  }

  if (propertyKey != null) {
    addListener(listener, propertyKey, ChangeType.CONFIG, new EventType[] {
      EventType.NodeChildrenChanged
    });
  } else {
    LOG.error("Can't add listener to config scope: " + scope);
  }
}
 
Example 24
Source Project: helix   Source File: ZKHelixManager.java    License: Apache License 2.0 5 votes vote down vote up
@Deprecated
@Override
public void addIdealStateChangeListener(final org.apache.helix.IdealStateChangeListener listener)
    throws Exception {
  addListener(listener, new Builder(_clusterName).idealStates(), ChangeType.IDEAL_STATE,
      new EventType[] { EventType.NodeChildrenChanged });
}
 
Example 25
Source Project: hbase-indexer   Source File: LeaderElection.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void process(WatchedEvent event) {
    if (stopped) {
        return;
    }

    if (event.getType() == EventType.NodeChildrenChanged && event.getPath().equals(electionPath)) {
        watchLeaders();
    }
}
 
Example 26
Source Project: curator   Source File: TestWatchesBuilder.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testRemoveWatch() throws Exception
{       
    Timing timing = new Timing();
    CuratorFrameworkImpl client = (CuratorFrameworkImpl)CuratorFrameworkFactory.builder().
            connectString(server.getConnectString()).
            retryPolicy(new RetryOneTime(1)).
            build();
    try
    {
        client.start();
        
        final CountDownLatch removedLatch = new CountDownLatch(1);
        
        final String path = "/";    
        Watcher watcher = new CountDownWatcher(path, removedLatch, EventType.DataWatchRemoved);
        
        client.checkExists().usingWatcher(watcher).forPath(path);

        client.watches().remove(watcher).forPath(path);

        Assert.assertTrue(timing.awaitLatch(removedLatch), "Timed out waiting for watch removal");
    }
    finally
    {
        CloseableUtils.closeQuietly(client);
    }
}
 
Example 27
Source Project: azeroth   Source File: ZkDistributeLock.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * zookeeper节点的监视器
 */
public void process(WatchedEvent event) {
    if (this.latch != null) {
        if (event.getType() == EventType.NodeDeleted) {
            this.latch.countDown();
        }
    }
}
 
Example 28
Source Project: curator   Source File: TestWatchesBuilder.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testRemoveLocalWatchInBackground() throws Exception {
    Timing timing = new Timing();
    CuratorFrameworkImpl client = (CuratorFrameworkImpl)CuratorFrameworkFactory.builder().
            connectString(server.getConnectString()).
            retryPolicy(new RetryOneTime(1)).
            build();
    try
    {
        client.start();
        
        AtomicReference<ConnectionState> stateRef = registerConnectionStateListener(client);
        
        final String path = "/";
        
        final CountDownLatch removedLatch = new CountDownLatch(1);
        
        Watcher watcher = new CountDownWatcher(path, removedLatch, EventType.DataWatchRemoved);        
        
        client.checkExists().usingWatcher(watcher).forPath(path);

        //Stop the server so we can check if we can remove watches locally when offline
        server.stop();
        
        Assert.assertTrue(blockUntilDesiredConnectionState(stateRef, timing, ConnectionState.SUSPENDED));
                   
        client.watches().removeAll().locally().inBackground().forPath(path);

        Assert.assertTrue(timing.awaitLatch(removedLatch), "Timed out waiting for watch removal");
    }
    finally
    {
        CloseableUtils.closeQuietly(client);
    }
}
 
Example 29
Source Project: curator   Source File: TestWatchesBuilder.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testRemoveAllChildWatches() throws Exception
{       
    Timing timing = new Timing();
    CuratorFramework client = CuratorFrameworkFactory.builder().
            connectString(server.getConnectString()).
            retryPolicy(new RetryOneTime(1)).
            build();
    try
    {
        client.start();
        
        final String path = "/";
        final AtomicBoolean removedFlag = new AtomicBoolean(false);
        final CountDownLatch removedLatch = new CountDownLatch(1);
        
        Watcher watcher1 = new BooleanWatcher(path, removedFlag, EventType.DataWatchRemoved);            
        Watcher watcher2 = new CountDownWatcher(path, removedLatch, EventType.ChildWatchRemoved);                        
                    
        client.checkExists().usingWatcher(watcher1).forPath(path);
        client.getChildren().usingWatcher(watcher2).forPath(path);
        
        client.watches().removeAll().ofType(WatcherType.Children).forPath(path);
        
        Assert.assertTrue(timing.awaitLatch(removedLatch), "Timed out waiting for watch removal");
        Assert.assertEquals(removedFlag.get(), false);
    }
    finally
    {
        CloseableUtils.closeQuietly(client);
    }
}
 
Example 30
Source Project: Mario   Source File: ZooKeeperClientTest.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void process(WatchedEvent event) {
	System.err.println("MyWatcher " + event.getType() + " | "
			+ event.getState());
	if (event.getType() == EventType.None) {
		if (event.getState().equals(KeeperState.SyncConnected)) {
			coutCountDownLatch.countDown();
		}
	}
}