Java Code Examples for org.apache.curator.utils.ZKPaths#getNodeFromPath()

The following examples show how to use org.apache.curator.utils.ZKPaths#getNodeFromPath() . 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: TestFramework.java    From curator with Apache License 2.0 6 votes vote down vote up
@Test
public void testCreateWithProtection() throws ExecutionException, InterruptedException
{
    CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1));
    try
    {
        client.start();
        AsyncCuratorFramework async = AsyncCuratorFramework.wrap(client);
        String path = async.create().withOptions(Collections.singleton(CreateOption.doProtected)).forPath("/yo").toCompletableFuture().get();
        String node = ZKPaths.getNodeFromPath(path);
        // CURATOR-489: confirm that the node contains a valid UUID, eg '_c_53345f98-9423-4e0c-a7b5-9f819e3ec2e1-yo'
        Assert.assertTrue(ProtectedUtils.isProtectedZNode(node));
        Assert.assertEquals(ProtectedUtils.normalize(node), "yo");
    }
    finally
    {
        CloseableUtils.closeQuietly(client);
    }
}
 
Example 3
Source File: ZookeeperConfigGroup.java    From config-toolkit with Apache License 2.0 6 votes vote down vote up
private Tuple<String, String> loadKey(final String nodePath) throws Exception {
    final String nodeName = ZKPaths.getNodeFromPath(nodePath);
    final Set<String> keysSpecified = configProfile.getKeysSpecified();
    switch (configProfile.getKeyLoadingMode()) {
        case INCLUDE:
            if (keysSpecified == null || !keysSpecified.contains(nodeName)) {
                return null;
            }
            break;
        case EXCLUDE:
            if (keysSpecified.contains(nodeName)) {
                return null;
            }
            break;
        case ALL:
            break;
        default:
            break;
    }

    final GetDataBuilder data = client.getData();
    final String value = new String(data.watched().forPath(nodePath), "UTF-8");
    return new Tuple<>(nodeName, value);
}
 
Example 4
Source File: ClusterPathChildrenCacheListener.java    From Decision with Apache License 2.0 6 votes vote down vote up
@Override
public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception
{
    String node;
    String nodeId;

    try {
        node = ZKPaths.getNodeFromPath(event.getData().getPath());
        nodeId = node.substring(node.indexOf("_") + 1);

        clusterSyncManagerInstance.updateNodeStatus(nodeId, event.getType());

    }catch (Exception e){
        logger.error("Exception receiving event {}: {}", event, e.getMessage());
    }

}
 
Example 5
Source File: PluginCacheSyncUtil.java    From incubator-sentry with Apache License 2.0 5 votes vote down vote up
public static void setUpdateFromChildEvent(PathChildrenCacheEvent cacheEvent,
    Update update) throws IOException {
  byte eventData[] = cacheEvent.getData().getData();
  update.deserialize(eventData);
  String seqNum = ZKPaths.getNodeFromPath(cacheEvent.getData().getPath());
  update.setSeqNum(Integer.valueOf(seqNum));
}
 
Example 6
Source File: PersistentPathChildrenCache.java    From helios with Apache License 2.0 5 votes vote down vote up
@Override
public void process(final WatchedEvent event) throws Exception {
  log.debug("data event: {}", event);
  if (event.getType() == NodeDataChanged) {
    final String child = ZKPaths.getNodeFromPath(event.getPath());
    changes.add(child);
    reactor.signal();
  }
}
 
Example 7
Source File: DistributedDoubleBarrier.java    From xian with Apache License 2.0 4 votes vote down vote up
private boolean internalLeave(long startMs, boolean hasMaxWait, long maxWaitMs) throws Exception
{
    String          ourPathName = ZKPaths.getNodeFromPath(ourPath);
    boolean         ourNodeShouldExist = true;
    boolean         result = true;
    for(;;)
    {
        if ( connectionLost.get() )
        {
            throw new KeeperException.ConnectionLossException();
        }

        List<String> children;
        try
        {
            children = client.getChildren().forPath(barrierPath);
        }
        catch ( KeeperException.NoNodeException dummy )
        {
            children = Lists.newArrayList();
        }
        children = filterAndSortChildren(children);
        if ( (children == null) || (children.size() == 0) )
        {
            break;
        }

        int                 ourIndex = children.indexOf(ourPathName);
        if ( (ourIndex < 0) && ourNodeShouldExist )
        {
            if ( connectionLost.get() )
            {
                break;  // connection was lost but we've reconnected. However, our ephemeral node is gone
            }
            else
            {
                throw new IllegalStateException(String.format("Our path (%s) is missing", ourPathName));
            }
        }

        if ( children.size() == 1 )
        {
            if ( ourNodeShouldExist && !children.get(0).equals(ourPathName) )
            {
                throw new IllegalStateException(String.format("Last path (%s) is not ours (%s)", children.get(0), ourPathName));
            }
            checkDeleteOurPath(ourNodeShouldExist);
            break;
        }

        Stat            stat;
        boolean         IsLowestNode = (ourIndex == 0);
        if ( IsLowestNode )
        {
            String  highestNodePath = ZKPaths.makePath(barrierPath, children.get(children.size() - 1));
            stat = client.checkExists().usingWatcher(watcher).forPath(highestNodePath);
        }
        else
        {
            String  lowestNodePath = ZKPaths.makePath(barrierPath, children.get(0));
            stat = client.checkExists().usingWatcher(watcher).forPath(lowestNodePath);

            checkDeleteOurPath(ourNodeShouldExist);
            ourNodeShouldExist = false;
        }

        if ( stat != null )
        {
            if ( hasMaxWait )
            {
                long        elapsed = System.currentTimeMillis() - startMs;
                long        thisWaitMs = maxWaitMs - elapsed;
                if ( thisWaitMs <= 0 )
                {
                    result = false;
                }
                else
                {
                    wait(thisWaitMs);
                }
            }
            else
            {
                wait();
            }
        }
    }

    try
    {
        client.delete().forPath(readyPath);
    }
    catch ( KeeperException.NoNodeException ignore )
    {
        // ignore
    }

    return result;
}
 
Example 8
Source File: ServiceCacheImpl.java    From xian with Apache License 2.0 4 votes vote down vote up
private String instanceIdFromData(ChildData childData) {
    return ZKPaths.getNodeFromPath(childData.getPath());
}
 
Example 9
Source File: AbstractResourceConfigFactoryBean.java    From cloud-config with MIT License 4 votes vote down vote up
protected String safeGetNodeNameFromEvent(PathChildrenCacheEvent event) {
    return event.getData() != null ?
            ZKPaths.getNodeFromPath(event.getData().getPath()) : "";
}
 
Example 10
Source File: RoutingAwareResourceConfigFactoryBean.java    From cloud-config with MIT License 4 votes vote down vote up
@Override
protected void handleChildAdded(CuratorFramework client, PathChildrenCacheEvent event) throws Exception {
    String nodeName = event.getData()!=null ?
            ZKPaths.getNodeFromPath(event.getData().getPath()) : "";
    buildResourceConfig(nodeName);
}
 
Example 11
Source File: ZooKeeperConstants.java    From workflow with Apache License 2.0 4 votes vote down vote up
public static String getTaskIdFromCompletedTasksPath(String path)
{
    String n = ZKPaths.getNodeFromPath(path);
    return Splitter.on(SEPARATOR).splitToList(n).get(1);
}
 
Example 12
Source File: DistributedDoubleBarrier.java    From curator with Apache License 2.0 4 votes vote down vote up
private boolean internalLeave(long startMs, boolean hasMaxWait, long maxWaitMs) throws Exception
{
    String          ourPathName = ZKPaths.getNodeFromPath(ourPath);
    boolean         ourNodeShouldExist = true;
    boolean         result = true;
    for(;;)
    {
        if ( connectionLost.get() )
        {
            throw new KeeperException.ConnectionLossException();
        }

        List<String> children;
        try
        {
            children = client.getChildren().forPath(barrierPath);
        }
        catch ( KeeperException.NoNodeException dummy )
        {
            children = Lists.newArrayList();
        }
        children = filterAndSortChildren(children);
        if ( (children == null) || (children.size() == 0) )
        {
            break;
        }

        int                 ourIndex = children.indexOf(ourPathName);
        if ( (ourIndex < 0) && ourNodeShouldExist )
        {
            if ( connectionLost.get() )
            {
                break;  // connection was lost but we've reconnected. However, our ephemeral node is gone
            }
            else
            {
                throw new IllegalStateException(String.format("Our path (%s) is missing", ourPathName));
            }
        }

        if ( children.size() == 1 )
        {
            if ( ourNodeShouldExist && !children.get(0).equals(ourPathName) )
            {
                throw new IllegalStateException(String.format("Last path (%s) is not ours (%s)", children.get(0), ourPathName));
            }
            checkDeleteOurPath(ourNodeShouldExist);
            break;
        }

        Stat            stat;
        boolean         IsLowestNode = (ourIndex == 0);
        if ( IsLowestNode )
        {
            String  highestNodePath = ZKPaths.makePath(barrierPath, children.get(children.size() - 1));
            stat = client.checkExists().usingWatcher(watcher).forPath(highestNodePath);
        }
        else
        {
            String  lowestNodePath = ZKPaths.makePath(barrierPath, children.get(0));
            stat = client.checkExists().usingWatcher(watcher).forPath(lowestNodePath);

            checkDeleteOurPath(ourNodeShouldExist);
            ourNodeShouldExist = false;
        }

        if ( stat != null )
        {
            if ( hasMaxWait )
            {
                long        elapsed = System.currentTimeMillis() - startMs;
                long        thisWaitMs = maxWaitMs - elapsed;
                if ( thisWaitMs <= 0 )
                {
                    result = false;
                    break;
                }
                else
                {
                    wait(thisWaitMs);
                }
            }
            else
            {
                wait();
            }
        }
    }

    try
    {
        client.delete().forPath(readyPath);
    }
    catch ( KeeperException.NoNodeException ignore )
    {
        // ignore
    }

    return result;
}
 
Example 13
Source File: ServiceCacheImpl.java    From curator with Apache License 2.0 4 votes vote down vote up
private String instanceIdFromData(ChildData childData)
{
    return ZKPaths.getNodeFromPath(childData.getPath());
}
 
Example 14
Source File: ZooKeeperConstants.java    From workflow with Apache License 2.0 4 votes vote down vote up
public static String getRunIdFromCompletedTasksPath(String path)
{
    String n = ZKPaths.getNodeFromPath(path);
    return Splitter.on(SEPARATOR).splitToList(n).get(0);
}
 
Example 15
Source File: GroupMember.java    From curator with Apache License 2.0 2 votes vote down vote up
/**
 * Given a full ZNode path, return the member ID
 *
 * @param path full ZNode path
 * @return id
 */
public String idFromPath(String path)
{
    return ZKPaths.getNodeFromPath(path);
}
 
Example 16
Source File: ZKPathUtils.java    From fastjgame with Apache License 2.0 2 votes vote down vote up
/**
 * 给定一个全路径,返回节点名字。
 * i.e. "/one/two/three" will return "three"
 */
public static String findNodeName(String fullPath) {
    return ZKPaths.getNodeFromPath(fullPath);
}
 
Example 17
Source File: GroupMember.java    From xian with Apache License 2.0 2 votes vote down vote up
/**
 * Given a full ZNode path, return the member ID
 *
 * @param path full ZNode path
 * @return id
 */
public String idFromPath(String path)
{
    return ZKPaths.getNodeFromPath(path);
}