判断是否存在

@param path

@return

@throws InterruptedException
@throws KeeperException
320422
public boolean exists(String path) throws InterruptedException, KeeperException {

        int retries = 0;
        while (true) {

            try {

                Stat stat = zk.exists(path, false);

                if (stat == null) {

                    return false;

                } else {

                    return true;
                }

            } catch (KeeperException.SessionExpiredException e) {

                throw e;

            } catch (KeeperException e) {

                LOGGER.warn("exists connect lost... will retry " + retries + "\t" + e.toString());

                if (retries++ == MAX_RETRIES) {
                    LOGGER.error("connect final failed");
                    throw e;
                }

                // sleep then retry
                int sec = RETRY_PERIOD_SECONDS * retries;
                LOGGER.warn("sleep " + sec);
                TimeUnit.SECONDS.sleep(sec);
            }
        }
    }
831213
public <T extends Normalizer> T restore(@NonNull String path) throws Exception {
        try (InputStream in = new BufferedInputStream(new FileInputStream(path))) {
            return restore(in);
        }
    }
763513
private Set<Long> writeToNode(String path, long uuid, OutputStream out)
            throws KeeperException.NodeExistsException, IOException, UnknownTableException, DroppedTableException {
        ByteArrayOutputStream bufferOut = new ByteArrayOutputStream();
        byte[] tableContent;
        Set<Long> uuids;
        Exception exception = null;

        try {
            // Load the table content from the source
            uuids = _source.loadAndSerialize(uuid, bufferOut);
            tableContent = bufferOut.toByteArray();
        } catch (UnknownTableException | DroppedTableException e) {
            // Record the exception and store the JSON serialized exception as the table content
            exception = e;
            tableContent = JsonHelper.asJson(e).getBytes(Charsets.UTF_8);
            uuids = ImmutableSet.of();
        }

        int nodeContentLength = 4 + 8 * uuids.size() + tableContent.length;  // 4 byte uuid count + 8 bytes per uuid + tableContent
        bufferOut = new ByteArrayOutputStream(nodeContentLength);
        DataOutputStream nodeOut = new DataOutputStream(bufferOut);

        if (exception == null) {
            // Write the actual number of UUIDs associated with the table
            nodeOut.writeInt(uuids.size());
            for (long sourceUuid : uuids) {
                nodeOut.writeLong(sourceUuid);
            }
        } else {
            // Write the exception code (no UUIDs will be written so no size is required)
            nodeOut.writeInt(exception instanceof UnknownTableException ? UNKNOWN_TABLE : DROPPED_TABLE);
        }

        nodeOut.write(tableContent);

        byte[] nodeContent = bufferOut.toByteArray();

        try {
            // Write the content to ZooKeeper
            _curator.create().withMode(CreateMode.PERSISTENT).forPath(path, nodeContent);
            _log.debug("Wrote table for UUID {} to {}", uuid, path);
        } catch (Throwable t) {
            // If the node exists then there was a race condition with another server caching the same table.  Pass
            // to the caller so they can retry reading the value.
            Throwables.propagateIfInstanceOf(t, KeeperException.NodeExistsException.class);
            Throwables.propagateIfInstanceOf(t, IOException.class);
            throw Throwables.propagate(t);
        }

        if (exception != null) {
            // This will always raise the exception
            Throwables.propagateIfPossible(exception, UnknownTableException.class, DroppedTableException.class);
        }

        out.write(tableContent);
        return uuids;
    }
431195
public boolean leave() throws KeeperException, InterruptedException{
		zooKeeper.delete(rootPath + "/" + name, 0);
		while (true) {
			synchronized (mutex) {
				List<String> list = zooKeeper.getChildren(rootPath, true);
				if (list.size() > 0) {
					mutex.wait();
				} else {
					return true;
				}
			}
		}
	}
1297479
public Response unLock(Session session, String path, List<String> tokens)
   {
      try
      {
         try
         {
            Node node = (Node)session.getItem(path);

            if (node.isLocked())
            {
               node.unlock();
               session.save();
            }

            return Response.status(HTTPStatus.NO_CONTENT).build();
         }
         catch (PathNotFoundException exc)
         {
            if (nullResourceLocks.isLocked(session, path))
            {
               nullResourceLocks.checkLock(session, path, tokens);
               nullResourceLocks.removeLock(session, path);
               return Response.status(HTTPStatus.NO_CONTENT).build();
            }

            return Response.status(HTTPStatus.NOT_FOUND).entity(exc.getMessage()).build();
         }

      }
      catch (LockException exc)
      {
         return Response.status(HTTPStatus.LOCKED).entity(exc.getMessage()).build();
      }
      catch (Exception exc)
      {
         log.error(exc.getMessage(), exc);
         return Response.serverError().entity(exc.getMessage()).build();
      }

   }
608979
@Override
  public Stat createOrSetWithParents(String path, String data, List<ACL> acl, CreateMode createMode)
    throws InterruptedException, KeeperException

  {
    if(exists(path) != null)
      return setData(path, data);

    try
    {
      createWithParents(path, data, acl, createMode);
      return null;
    }
    catch(KeeperException.NodeExistsException e)
    {
      // this should not happen very often (race condition)
      return setData(path, data);
    }
  }
1337343
private ZkDisconfData getDisconfData(String path, String keyName, ZooKeeper zooKeeper)
            throws KeeperException, InterruptedException {

        String curPath = path + "/" + keyName;

        if (zooKeeper.exists(curPath, false) == null) {
            return null;
        }

        ZkDisconfData zkDisconfData = new ZkDisconfData();
        zkDisconfData.setKey(keyName);

        List<String> secChiList = zooKeeper.getChildren(curPath, false);
        List<ZkDisconfData.ZkDisconfDataItem> zkDisconfDataItems = new ArrayList<ZkDisconfData.ZkDisconfDataItem>();

        // list
        for (String secKey : secChiList) {

            // machine
            ZkDisconfData.ZkDisconfDataItem zkDisconfDataItem = new ZkDisconfData.ZkDisconfDataItem();
            zkDisconfDataItem.setMachine(secKey);

            String thirdPath = curPath + "/" + secKey;

            // value
            byte[] data = zooKeeper.getData(thirdPath, null, null);
            if (data != null) {
                zkDisconfDataItem.setValue(new String(data, CHARSET));
            }

            // add
            zkDisconfDataItems.add(zkDisconfDataItem);
        }

        zkDisconfData.setData(zkDisconfDataItems);

        return zkDisconfData;
    }
281788
@Override
  public ZKData<String> getZKStringData(String path, Watcher watcher)
    throws InterruptedException, KeeperException

  {
    ZKData<byte[]> zkData = getZKByteData(path, watcher);

    return new ZKData<String>(toStringData(zkData.getData()), zkData.getStat());
  }
245010
public synchronized boolean lock() throws KeeperException, InterruptedException {
        if (isClosed()) {
            return false;
        }
        ensurePathExists(dir);

        return (Boolean) retryOperation(zop);
    }
177808
public AbstractObjectAssert<?, Object> jsonPath(String path) {
        return Assertions.assertThat(actual.read(path, Object.class));
    }
195428
@SuppressWarnings("PMD.GuardLogStatement")
    public W acquire() throws InterruptedException {
        // Stop draining, because we obviously need this kind of buffers
        Optional.ofNullable(idleTimer.getAndSet(null)).ifPresent(
            timer -> timer.cancel());
        if (createdBufs.get() < maximumBufs) {
            // Haven't reached maximum, so if no buffer is queued, create one.
            W buffer = queue.poll();
            if (buffer != null) {
                buffer.lockBuffer();
                return buffer;
            }
            return createBuffer();
        }
        // Wait for buffer to become available.
        if (logger.isLoggable(Level.FINE)) {
            // If configured, log message after waiting some time.
            W buffer = queue.poll(acquireWarningLimit, TimeUnit.MILLISECONDS);
            if (buffer != null) {
                buffer.lockBuffer();
                return buffer;
            }
            logger.log(Level.FINE, new Throwable(),
                () -> Thread.currentThread().getName() + " waiting > "
                    + acquireWarningLimit + "ms for buffer, while executing:");
        }
        W buffer = queue.take();
        buffer.lockBuffer();
        return buffer;
    }
722027
private static List<String> loadAndWatchDir(Path path, ResourceLoader resourceLoader, String resourcePaths) {
        final List<String> result = new ArrayList<>();
        try {
            Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
                        throws IOException {
                    result.addAll(load(file.toAbsolutePath().toString()));
                    return FileVisitResult.CONTINUE;
                }
            });
        } catch (IOException ex) {
            LOGGER.error("加载资源失败："+path, ex);
        }
        DirectoryWatcher.WatcherCallback watcherCallback = new DirectoryWatcher.WatcherCallback(){

            private long lastExecute = System.currentTimeMillis();
            @Override
            public void execute(WatchEvent.Kind<?> kind, String path) {
                //一秒内发生的多个相同事件认定为一次，防止短时间内多次加载资源
                if(System.currentTimeMillis() - lastExecute > 1000){
                    lastExecute = System.currentTimeMillis();
                    LOGGER.info("事件："+kind.name()+" ,路径："+path);
                    synchronized(AutoDetector.class){
                        DirectoryWatcher dw = WATCHER_CALLBACKS.get(this);
                        String paths = RESOURCES.get(dw);
                        ResourceLoader loader = RESOURCE_LOADERS.get(dw);
                        LOGGER.info("重新加载数据");
                        loadAndWatch(loader, paths);
                    }
                }
            }

        };
        DirectoryWatcher directoryWatcher = DirectoryWatcher.getDirectoryWatcher(watcherCallback,
                StandardWatchEventKinds.ENTRY_CREATE,
                    StandardWatchEventKinds.ENTRY_MODIFY,
                    StandardWatchEventKinds.ENTRY_DELETE);
        directoryWatcher.watchDirectoryTree(path);

        WATCHER_CALLBACKS.put(watcherCallback, directoryWatcher);
        RESOURCES.put(directoryWatcher, resourcePaths);
        RESOURCE_LOADERS.put(directoryWatcher, resourceLoader);

        return result;
    }
711572
public static List<String> readListResource(String path)
    {
        Class<?> callerClass = resolveCaller();
        if (callerClass == null)
        {
            return null;
        }

        return readListResource(resolveCaller(), path);
    }
1296579
public JCRPath parseJCRPath(String path) throws RepositoryException
   {
      if (isAbsPathParseable(path))
      {
         return parseAbsPath(path);
      }
      else
      {
         return parseRelPath(path);
      }
   }
288975
public String addLock(Session session, String path) throws LockException
   {

      String repoPath = session.getRepository().hashCode() + "/" + session.getWorkspace().getName() + "/" + path;

      if (!nullResourceLocks.containsKey(repoPath))
      {
         String newLockToken = IdGenerator.generate();
         session.addLockToken(newLockToken);
         nullResourceLocks.put(repoPath, newLockToken);
         return newLockToken;
      }

      // check if lock owned by this session
      String currentToken = nullResourceLocks.get(repoPath);
      for (String t : session.getLockTokens())
      {
         if (t.equals(currentToken))
            return t;
      }
      throw new LockException("Resource already locked " + repoPath);
   }
797646
private String createNonSequential(String path, byte[] data, List<ACL> acl, CreateMode createMode)
      throws KeeperException, InterruptedException {
    RetryCounter retryCounter = retryCounterFactory.create();
    while (true) {
      try {
        return zk.create(path, data, acl, createMode);
      } catch (KeeperException e) {
        switch (e.code()) {
          case NODEEXISTS:
            // Non-sequential node was successfully created
            return path;

          case CONNECTIONLOSS:
          case OPERATIONTIMEOUT:
            LOG.warn("Possibly transient ZooKeeper exception: " + e);
            if (!retryCounter.shouldRetry()) {
              LOG.error("ZooKeeper create failed after "
                  + retryCounter.getMaxRetries() + " retries");
              throw e;
            }
            break;

          default:
            throw e;
        }
      }
      LOG.info("Retrying ZooKeeper after sleeping...");
      retryCounter.sleepUntilNextRetry();
      retryCounter.useRetry();
    }
  }
491727
public RFuture<String> getText (final String path) {
    final RPromise<String> result = exec.deferredPromise();
    exec.invokeAsync(new Runnable() {
      public void run () {
        try {
          result.succeed(getTextSync(path));
        } catch (Throwable t) {
          result.fail(t);
        }
      }
    });
    return result;
  }