org.apache.curator.framework.recipes.cache.TreeCacheListener Java Examples

The following examples show how to use org.apache.curator.framework.recipes.cache.TreeCacheListener. 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 check out the related API usage on the sidebar.
Example #1
Source File: LogSearchConfigZKHelper.java    From ambari-logsearch with Apache License 2.0 6 votes vote down vote up
/**
 * Create listener for znode of log level filters - can be used for Log Feeder as it can be useful if it's monitoring the log level changes
 * @param clusterName name of the cluster
 * @param gson object to be used for json serialization
 * @param logLevelFilterMonitor log level filter monitor object that can be used to do something during znode chagne
 * @return listener response
 */
public static TreeCacheListener createTreeCacheListener(String clusterName, Gson gson, LogLevelFilterMonitor logLevelFilterMonitor) {
  return new TreeCacheListener() {
    private final Set<TreeCacheEvent.Type> nodeEvents = ImmutableSet.of(TreeCacheEvent.Type.NODE_ADDED, TreeCacheEvent.Type.NODE_UPDATED, TreeCacheEvent.Type.NODE_REMOVED);
    public void childEvent(CuratorFramework client, TreeCacheEvent event) throws Exception {
      if (!nodeEvents.contains(event.getType())) {
        return;
      }
      String nodeName = ZKPaths.getNodeFromPath(event.getData().getPath());
      String nodeData = new String(event.getData().getData());
      TreeCacheEvent.Type eventType = event.getType();

      String configPathStab = String.format("/%s/", clusterName);

      if (event.getData().getPath().startsWith(configPathStab + "loglevelfilter/")) {
        handleLogLevelFilterChange(eventType, nodeName, nodeData, gson, logLevelFilterMonitor);
      }
    }
  };
}
 
Example #2
Source File: LogLevelFilterHandler.java    From ambari-logsearch with Apache License 2.0 6 votes vote down vote up
@PostConstruct
public void init() throws Exception {
  if (logFeederProps.isZkFilterStorage() && logFeederProps.isUseLocalConfigs()) {
    LogLevelFilterManagerZK filterManager = (LogLevelFilterManagerZK) config.getLogLevelFilterManager();
    CuratorFramework client = filterManager.getClient();
    client.start();
    Gson gson = filterManager.getGson();
    LogSearchConfigZKHelper.waitUntilRootAvailable(client);
    TreeCache clusterCache = LogSearchConfigZKHelper.createClusterCache(client, logFeederProps.getClusterName());
    TreeCacheListener listener = LogSearchConfigZKHelper.createTreeCacheListener(
      logFeederProps.getClusterName(), gson, this);
    LogSearchConfigZKHelper.addAndStartListenersOnCluster(clusterCache, listener);
  }
  if (config.getLogLevelFilterManager() != null) {
    TreeMap<String, LogLevelFilter> sortedFilters = config.getLogLevelFilterManager()
      .getLogLevelFilters(logFeederProps.getClusterName())
      .getFilter();
    filters = new ConcurrentHashMap<>(sortedFilters);
  }
}
 
Example #3
Source File: ZookeeperAppSubscriber.java    From sofa-dashboard-client with Apache License 2.0 5 votes vote down vote up
@Override
public void beforeStart(CuratorFramework client) {
    // Add listeners to manage local cache
    TreeCache cache = new TreeCache(client,
        ZookeeperConstants.SOFA_BOOT_CLIENT_INSTANCE);
    TreeCacheListener listener = (cli, event) -> {
        String dataPath = event.getData() == null ? null : event.getData().getPath();
        LOGGER
            .info("Dashboard client event type = {}, path= {}", event.getType(),
                dataPath);
        switch (event.getType()) {
            case NODE_ADDED:
            case NODE_UPDATED:
                runInSafe(() -> doCreateOrUpdateApplications(event));
                break;
            case NODE_REMOVED:
            case CONNECTION_LOST:
                runInSafe(() -> doRemoveApplications(event));
                break;
            case CONNECTION_RECONNECTED: // Try to recover data while reconnected
                doRebuildCache();
                break;
            default:
                break;
        }
    };
    cache.getListenable().addListener(listener);
    try {
        cache.start();
    } catch (Exception e) {
        LOGGER.error("Start cache error.", e);
    }
}
 
Example #4
Source File: JobNodeStorageTest.java    From shardingsphere-elasticjob-lite with Apache License 2.0 5 votes vote down vote up
@Test
public void assertAddDataListener() {
    TreeCache treeCache = mock(TreeCache.class);
    @SuppressWarnings("unchecked")
    Listenable<TreeCacheListener> listeners = mock(Listenable.class);
    TreeCacheListener listener = mock(TreeCacheListener.class);
    when(treeCache.getListenable()).thenReturn(listeners);
    when(regCenter.getRawCache("/test_job")).thenReturn(treeCache);
    jobNodeStorage.addDataListener(listener);
    verify(listeners).addListener(listener);
}
 
Example #5
Source File: ZkSubscriptionHandler.java    From seldon-server with Apache License 2.0 5 votes vote down vote up
public void addSubscription(String location, TreeCacheListener listener) throws Exception {
    CuratorFramework client = curator.getCurator();
    EnsurePath ensureMvTestPath = new EnsurePath(location);
    ensureMvTestPath.ensure(client.getZookeeperClient());
    TreeCache cache = new TreeCache(client, location);
    cache.getListenable().addListener(listener);
    cache.start();
    caches.put(location, cache);
    logger.info("Added ZooKeeper subscriber for " + location + " children.");
}
 
Example #6
Source File: ZKCache.java    From metron with Apache License 2.0 5 votes vote down vote up
private ZKCache(CuratorFramework client, List<TreeCacheListener> listeners, String zkRoot, boolean ownClient) {
  this.client = client;
  this.listeners = listeners;
  this.ownClient = ownClient;
  if(zkRoot == null) {
    throw new IllegalArgumentException("Zookeeper root must not be null.");
  }
  this.zkRoot = zkRoot;
}
 
Example #7
Source File: ZKCache.java    From metron with Apache License 2.0 5 votes vote down vote up
/**
 * Start the cache.
 * @throws Exception If unable to be started.
 */
public void start() throws Exception {
  if(cache == null) {
    if(ownClient) {
      client.start();
    }
    TreeCache.Builder builder = TreeCache.newBuilder(client, zkRoot);
    builder.setCacheData(true);
    cache = builder.build();
    for(TreeCacheListener l : listeners) {
      cache.getListenable().addListener(l);
    }
    cache.start();
  }
}
 
Example #8
Source File: TreeCacheExample.java    From ZKRecipesByExample with Apache License 2.0 5 votes vote down vote up
private static void addListener(final TreeCache cache) {
	TreeCacheListener listener = new TreeCacheListener() {

		@Override
		public void childEvent(CuratorFramework client, TreeCacheEvent event) throws Exception {
			switch (event.getType()) {
			case NODE_ADDED: {
				System.out.println("TreeNode added: " + ZKPaths.getNodeFromPath(event.getData().getPath()) + ", value: "
						+ new String(event.getData().getData()));
				break;
			}
			case NODE_UPDATED: {
				System.out.println("TreeNode changed: " + ZKPaths.getNodeFromPath(event.getData().getPath()) + ", value: "
						+ new String(event.getData().getData()));
				break;
			}
			case NODE_REMOVED: {
				System.out.println("TreeNode removed: " + ZKPaths.getNodeFromPath(event.getData().getPath()));
				break;
			}
			default:
				System.out.println("Other event: " + event.getType().name());
			}
		}

	};

	cache.getListenable().addListener(listener);
}
 
Example #9
Source File: DubboServiceDiscoveryAutoConfiguration.java    From spring-cloud-alibaba with Apache License 2.0 4 votes vote down vote up
/**
 * Re-attach the {@link TreeCacheListener TreeCacheListeners}.
 */
private void reattachTreeCacheListeners() {

	TreeCache treeCache = zookeeperServiceWatch.getCache();

	Listenable<TreeCacheListener> listenable = treeCache.getListenable();

	/**
	 * All registered TreeCacheListeners except {@link ZookeeperServiceWatch}.
	 * Usually, "otherListeners" will be empty because Spring Cloud Zookeeper only
	 * adds "zookeeperServiceWatch" bean as {@link TreeCacheListener}.
	 */
	List<TreeCacheListener> otherListeners = new LinkedList<>();

	if (listenable instanceof ListenerContainer) {
		ListenerContainer<TreeCacheListener> listenerContainer = (ListenerContainer) listenable;
		listenerContainer.forEach(listener -> {
			/**
			 * Even though "listener" is an instance of
			 * {@link ZookeeperServiceWatch}, "zookeeperServiceWatch" bean that
			 * was enhanced by AOP is different from the former, thus it's
			 * required to exclude "listener".
			 */
			if (!(listener instanceof ZookeeperServiceWatch)) {
				otherListeners.add(listener);
			}
			return null;
		});

		// remove all TreeCacheListeners temporarily
		listenerContainer.clear();
		// re-store zookeeperServiceWatch, and make sure it's first one
		// now "beforeChildEvent" is available for Spring AOP
		listenerContainer.addListener(zookeeperServiceWatch);
		// re-store others
		otherListeners.forEach(listenerContainer::addListener);
	}
	else {
		if (logger.isWarnEnabled()) {
			logger.warn(
					"Tell me which version Curator framework current application used? I will do better :D");
		}
	}
}
 
Example #10
Source File: ZKClient.java    From mpush with Apache License 2.0 4 votes vote down vote up
public void registerListener(TreeCacheListener listener) {
    cache.getListenable().addListener(listener);
}
 
Example #11
Source File: AbstractListenerManager.java    From shardingsphere-elasticjob-lite with Apache License 2.0 4 votes vote down vote up
protected void addDataListener(final TreeCacheListener listener) {
    jobNodeStorage.addDataListener(listener);
}
 
Example #12
Source File: LogSearchConfigZKHelper.java    From ambari-logsearch with Apache License 2.0 2 votes vote down vote up
/**
 * Assign listener to cluster cache and start to use that listener
 * @param clusterCache zookeeper znode cache (cluster)
 * @param listener znode cache listener - trigger on events
 * @throws Exception error during assinging the listener to the cache
 */
public static void addAndStartListenersOnCluster(TreeCache clusterCache, TreeCacheListener listener) throws Exception {
  clusterCache.getListenable().addListener(listener);
  clusterCache.start();
}
 
Example #13
Source File: JobNodeStorage.java    From shardingsphere-elasticjob-lite with Apache License 2.0 2 votes vote down vote up
/**
 * Add data listener.
 * 
 * @param listener data listener
 */
public void addDataListener(final TreeCacheListener listener) {
    TreeCache cache = (TreeCache) regCenter.getRawCache("/" + jobName);
    cache.getListenable().addListener(listener);
}
 
Example #14
Source File: ZKCache.java    From metron with Apache License 2.0 2 votes vote down vote up
/**
 * Specify the treecache listener, which will be called when changes happen to the zookeeper root.
 *
 * @param listener The callback which is called when changes happen in zookeeper.
 * @return The Builder
 */
public Builder withListener(TreeCacheListener listener) {
  this.listener.add(listener);
  return this;
}