org.apache.curator.framework.api.BackgroundCallback Java Examples

The following examples show how to use org.apache.curator.framework.api.BackgroundCallback. 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: PathChildrenCache.java    From xian with Apache License 2.0 6 votes vote down vote up
void refresh(final RefreshMode mode) throws Exception
{
    ensurePath();

    final BackgroundCallback callback = new BackgroundCallback()
    {
        @Override
        public void processResult(CuratorFramework client, CuratorEvent event) throws Exception
        {
            if (PathChildrenCache.this.state.get().equals(State.CLOSED)) {
                // This ship is closed, don't handle the callback
                return;
            }
            if ( event.getResultCode() == KeeperException.Code.OK.intValue() )
            {
                processChildren(event.getChildren(), mode);
            }
        }
    };

    client.getChildren().usingWatcher(childrenWatcher).inBackground(callback).forPath(path);
}
 
Example #2
Source File: TestRegistryRMOperations.java    From big-c with Apache License 2.0 6 votes vote down vote up
/**
 *
 * trigger a purge operation
 * @param path pathn
 * @param id yarn ID
 * @param policyMatch policy to match ID on
 * @param purgePolicy policy when there are children under a match
 * @param callback optional callback
 * @return the number purged
 * @throws IOException
 */
public int purge(String path,
    String id,
    String policyMatch,
    RegistryAdminService.PurgePolicy purgePolicy,
    BackgroundCallback callback) throws
    IOException,
    ExecutionException,
    InterruptedException {

  Future<Integer> future = registry.purgeRecordsAsync(path,
      id, policyMatch, purgePolicy, callback);
  try {
    return future.get();
  } catch (ExecutionException e) {
    if (e.getCause() instanceof IOException) {
      throw (IOException) e.getCause();
    } else {
      throw e;
    }
  }
}
 
Example #3
Source File: TestRegistryRMOperations.java    From hadoop with Apache License 2.0 6 votes vote down vote up
/**
 *
 * trigger a purge operation
 * @param path pathn
 * @param id yarn ID
 * @param policyMatch policy to match ID on
 * @param purgePolicy policy when there are children under a match
 * @param callback optional callback
 * @return the number purged
 * @throws IOException
 */
public int purge(String path,
    String id,
    String policyMatch,
    RegistryAdminService.PurgePolicy purgePolicy,
    BackgroundCallback callback) throws
    IOException,
    ExecutionException,
    InterruptedException {

  Future<Integer> future = registry.purgeRecordsAsync(path,
      id, policyMatch, purgePolicy, callback);
  try {
    return future.get();
  } catch (ExecutionException e) {
    if (e.getCause() instanceof IOException) {
      throw (IOException) e.getCause();
    } else {
      throw e;
    }
  }
}
 
Example #4
Source File: ZKStoreHelper.java    From pravega with Apache License 2.0 6 votes vote down vote up
private BackgroundCallback callback(Consumer<CuratorEvent> result, Consumer<Throwable> exception, String path) {
    return (client, event) -> {
        if (event.getResultCode() == KeeperException.Code.OK.intValue()) {
            result.accept(event);
        } else if (event.getResultCode() == KeeperException.Code.CONNECTIONLOSS.intValue() ||
                event.getResultCode() == KeeperException.Code.SESSIONEXPIRED.intValue() ||
                event.getResultCode() == KeeperException.Code.SESSIONMOVED.intValue() ||
                event.getResultCode() == KeeperException.Code.OPERATIONTIMEOUT.intValue()) {
            exception.accept(StoreException.create(StoreException.Type.CONNECTION_ERROR, path));
        } else if (event.getResultCode() == KeeperException.Code.NODEEXISTS.intValue()) {
            exception.accept(StoreException.create(StoreException.Type.DATA_EXISTS, path));
        } else if (event.getResultCode() == KeeperException.Code.BADVERSION.intValue()) {
            exception.accept(StoreException.create(StoreException.Type.WRITE_CONFLICT, path));
        } else if (event.getResultCode() == KeeperException.Code.NONODE.intValue()) {
            exception.accept(StoreException.create(StoreException.Type.DATA_NOT_FOUND, path));
        } else if (event.getResultCode() == KeeperException.Code.NOTEMPTY.intValue()) {
            exception.accept(StoreException.create(StoreException.Type.DATA_CONTAINS_ELEMENTS, path));
        } else {
            exception.accept(StoreException.create(StoreException.Type.UNKNOWN,
                    KeeperException.create(KeeperException.Code.get(event.getResultCode()), path)));
        }
    };
}
 
Example #5
Source File: ZKHostIndex.java    From pravega with Apache License 2.0 6 votes vote down vote up
private CompletableFuture<Void> createNode(CreateMode createMode, boolean createParents, String path, byte[] data) {
    CompletableFuture<Void> result = new CompletableFuture<>();
    try {
        BackgroundCallback callback = (cli, event) -> {
            if (event.getResultCode() == KeeperException.Code.OK.intValue() ||
                    event.getResultCode() == KeeperException.Code.NODEEXISTS.intValue()) {
                result.complete(null);
            } else {
                result.completeExceptionally(translateErrorCode(path, event));
            }
        };
        if (createParents) {
            client.create().creatingParentsIfNeeded().withMode(createMode).inBackground(callback, executor)
                    .forPath(path, data);
        } else {
            client.create().withMode(createMode).inBackground(callback, executor).forPath(path, data);
        }
    } catch (Exception e) {
        result.completeExceptionally(StoreException.create(StoreException.Type.UNKNOWN, e));
    }
    return result;
}
 
Example #6
Source File: PersistentWatcher.java    From curator with Apache License 2.0 6 votes vote down vote up
private void reset()
{
    if ( state.get() != State.STARTED )
    {
        return;
    }
    
    try
    {
        BackgroundCallback callback = (__, event) -> {
            if ( event.getResultCode() == KeeperException.Code.OK.intValue() )
            {
                resetListeners.forEach(Runnable::run);
            }
            else
            {
                reset();
            }
        };
        client.watchers().add().withMode(recursive ? AddWatchMode.PERSISTENT_RECURSIVE : AddWatchMode.PERSISTENT).inBackground(callback).usingWatcher(watcher).forPath(basePath);
    }
    catch ( Exception e )
    {
        log.error("Could not reset persistent watch at path: " + basePath, e);
    }
}
 
Example #7
Source File: CuratorInBackground.java    From yuzhouwan with Apache License 2.0 6 votes vote down vote up
public void createEphemeralNodeRecursionInBackground(String path) throws Exception {
    curatorFramework.create()
            .creatingParentsIfNeeded()
            .withMode(CreateMode.PERSISTENT)
            .inBackground(new BackgroundCallback() {
                @Override
                public void processResult(CuratorFramework client, CuratorEvent event) {

                    LOG.info("event's result code: {}, type: {}", event.getResultCode(), event.getType());

                    showCurrentThreadName();

                    countDownLatch.countDown();
                }
            }).forPath(path);
}
 
Example #8
Source File: TestWatchesBuilder.java    From curator with Apache License 2.0 6 votes vote down vote up
@Test(groups = CuratorTestBase.zk36Group)
public void testPersistentRecursiveWatchInBackground() throws Exception
{
    try ( CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)) )
    {
        client.start();
        client.blockUntilConnected();

        CountDownLatch backgroundLatch = new CountDownLatch(1);
        BackgroundCallback backgroundCallback = (__, ___) -> backgroundLatch.countDown();
        CountDownLatch latch = new CountDownLatch(5);
        Watcher watcher = event -> latch.countDown();
        client.watchers().add().withMode(AddWatchMode.PERSISTENT_RECURSIVE).inBackground(backgroundCallback).usingWatcher(watcher).forPath("/test");

        client.create().forPath("/test");
        client.create().forPath("/test/a");
        client.create().forPath("/test/a/b");
        client.create().forPath("/test/a/b/c");
        client.create().forPath("/test/a/b/c/d");

        Assert.assertTrue(timing.awaitLatch(backgroundLatch));
        Assert.assertTrue(timing.awaitLatch(latch));
    }
}
 
Example #9
Source File: OperationAndData.java    From xian with Apache License 2.0 5 votes vote down vote up
OperationAndData(BackgroundOperation<T> operation, T data, BackgroundCallback callback, ErrorCallback<T> errorCallback, Object context)
{
    this.operation = operation;
    this.data = data;
    this.callback = callback;
    this.errorCallback = errorCallback;
    this.context = context;
    reset();
}
 
Example #10
Source File: PersistentNode.java    From curator with Apache License 2.0 5 votes vote down vote up
/**
 * @param givenClient        client instance
 * @param mode          creation mode
 * @param useProtection if true, call {@link CreateBuilder#withProtection()}
 * @param basePath the base path for the node
 * @param initData data for the node
 * @param ttl for ttl modes, the ttl to use
 */
public PersistentNode(CuratorFramework givenClient, final CreateMode mode, boolean useProtection, final String basePath, byte[] initData, long ttl)
{
    this.useProtection = useProtection;
    this.client = Preconditions.checkNotNull(givenClient, "client cannot be null").newWatcherRemoveCuratorFramework();
    this.basePath = PathUtils.validatePath(basePath);
    this.mode = Preconditions.checkNotNull(mode, "mode cannot be null");
    this.ttl = ttl;
    final byte[] data = Preconditions.checkNotNull(initData, "data cannot be null");

    backgroundCallback = new BackgroundCallback()
    {
        @Override
        public void processResult(CuratorFramework dummy, CuratorEvent event) throws Exception
        {
            if ( isActive() )
            {
                processBackgroundCallback(event);
            }
            else
            {
                processBackgroundCallbackClosedState(event);
            }
        }
    };

    this.data.set(Arrays.copyOf(data, data.length));
}
 
Example #11
Source File: Backgrounding.java    From xian with Apache License 2.0 5 votes vote down vote up
private static BackgroundCallback wrapCallback(final CuratorFrameworkImpl client, final BackgroundCallback callback, final Executor executor)
{
    return new BackgroundCallback()
    {
        @Override
        public void processResult(CuratorFramework dummy, final CuratorEvent event) throws Exception
        {
            executor.execute
                (
                    new Runnable()
                    {
                        @Override
                        public void run()
                        {
                            try
                            {
                                callback.processResult(client, event);
                            }
                            catch ( Exception e )
                            {
                                ThreadUtils.checkInterrupted(e);
                                if ( e instanceof KeeperException )
                                {
                                    client.validateConnection(client.codeToState(((KeeperException)e).code()));
                                }
                                client.logError("Background operation result handling threw exception", e);
                            }
                        }
                    }
                );
        }
    };
}
 
Example #12
Source File: ZKUtil.java    From PoseidonX with Apache License 2.0 5 votes vote down vote up
/**
 * 删除节点
 * @param curator
 * @param path
 * @param recursive
 * @param backgroundCallback
 * @throws Exception
 */
public static void zkDelete(CuratorFramework curator, String path, boolean recursive, BackgroundCallback backgroundCallback) throws Exception {
    DeleteBuilder delete = curator.delete();
    if(recursive) {
        delete.deletingChildrenIfNeeded();
    }
    if(backgroundCallback != null) {
        delete.inBackground(backgroundCallback);
    }
    delete.forPath(path);
}
 
Example #13
Source File: LeaderLatch.java    From xian with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
void reset() throws Exception
{
    setLeadership(false);
    setNode(null);

    BackgroundCallback callback = new BackgroundCallback()
    {
        @Override
        public void processResult(CuratorFramework client, CuratorEvent event) throws Exception
        {
            if ( debugResetWaitLatch != null )
            {
                debugResetWaitLatch.await();
                debugResetWaitLatch = null;
            }

            if ( event.getResultCode() == KeeperException.Code.OK.intValue() )
            {
                setNode(event.getName());
                if ( state.get() == State.CLOSED )
                {
                    setNode(null);
                }
                else
                {
                    getChildren();
                }
            }
            else
            {
                log.error("getChildren() failed. rc = " + event.getResultCode());
            }
        }
    };
    client.create().creatingParentContainersIfNeeded().withProtection().withMode(CreateMode.EPHEMERAL_SEQUENTIAL).inBackground(callback).forPath(ZKPaths.makePath(latchPath, LOCK_NAME), LeaderSelector.getIdBytes(id));
}
 
Example #14
Source File: TestPersistentEphemeralNode.java    From xian with Apache License 2.0 5 votes vote down vote up
@Test
public void testSetUpdatedDataWhenReconnected() throws Exception
{
    CuratorFramework curator = newCurator();

    byte[] initialData = "Hello World".getBytes();
    byte[] updatedData = "Updated".getBytes();

    PersistentEphemeralNode node = new PersistentEphemeralNode(curator, PersistentEphemeralNode.Mode.EPHEMERAL, PATH, initialData);
    node.start();
    try
    {
        node.waitForInitialCreate(timing.forWaiting().seconds(), TimeUnit.SECONDS);
        assertTrue(Arrays.equals(curator.getData().forPath(node.getActualPath()), initialData));

        node.setData(updatedData);
        assertTrue(Arrays.equals(curator.getData().forPath(node.getActualPath()), updatedData));

        server.restart();

        final CountDownLatch dataUpdateLatch = new CountDownLatch(1);
        curator.getData().inBackground(new BackgroundCallback() {

            @Override
            public void processResult(CuratorFramework client, CuratorEvent event) throws Exception {
                dataUpdateLatch.countDown();
            }
        }).forPath(node.getActualPath());

        assertTrue(timing.awaitLatch(dataUpdateLatch));

        assertTrue(Arrays.equals(curator.getData().forPath(node.getActualPath()), updatedData));
    }
    finally
    {
        node.close();
    }
}
 
Example #15
Source File: RegistryAdminService.java    From hadoop with Apache License 2.0 5 votes vote down vote up
public AsyncPurge(String path,
    NodeSelector selector,
    PurgePolicy purgePolicy,
    BackgroundCallback callback) {
  this.callback = callback;
  this.selector = selector;
  this.path = path;
  this.purgePolicy = purgePolicy;
}
 
Example #16
Source File: PathChildrenCache.java    From xian with Apache License 2.0 5 votes vote down vote up
void getDataAndStat(final String fullPath) throws Exception
{
    BackgroundCallback callback = new BackgroundCallback()
    {
        @Override
        public void processResult(CuratorFramework client, CuratorEvent event) throws Exception
        {
            applyNewData(fullPath, event.getResultCode(), event.getStat(), cacheData ? event.getData() : null);
        }
    };

    if ( USE_EXISTS && !cacheData )
    {
        client.checkExists().usingWatcher(dataWatcher).inBackground(callback).forPath(fullPath);
    }
    else
    {
        // always use getData() instead of exists() to avoid leaving unneeded watchers which is a type of resource leak
        if ( dataIsCompressed && cacheData )
        {
            client.getData().decompressed().usingWatcher(dataWatcher).inBackground(callback).forPath(fullPath);
        }
        else
        {
            client.getData().usingWatcher(dataWatcher).inBackground(callback).forPath(fullPath);
        }
    }
}
 
Example #17
Source File: RegistryAdminService.java    From big-c with Apache License 2.0 5 votes vote down vote up
public AsyncPurge(String path,
    NodeSelector selector,
    PurgePolicy purgePolicy,
    BackgroundCallback callback) {
  this.callback = callback;
  this.selector = selector;
  this.path = path;
  this.purgePolicy = purgePolicy;
}
 
Example #18
Source File: LeaderLatch.java    From xian with Apache License 2.0 5 votes vote down vote up
private void getChildren() throws Exception
{
    BackgroundCallback callback = new BackgroundCallback()
    {
        @Override
        public void processResult(CuratorFramework client, CuratorEvent event) throws Exception
        {
            if ( event.getResultCode() == KeeperException.Code.OK.intValue() )
            {
                checkLeadership(event.getChildren());
            }
        }
    };
    client.getChildren().inBackground(callback).forPath(ZKPaths.makePath(latchPath, null));
}
 
Example #19
Source File: ZKStoreHelper.java    From pravega with Apache License 2.0 5 votes vote down vote up
CompletableFuture<String> createEphemeralSequentialZNode(final String path) {
    final CompletableFuture<String> result = new CompletableFuture<>();

    try {
        CreateBuilder createBuilder = client.create();
        BackgroundCallback callback = callback(x -> result.complete(x.getName()),
                result::completeExceptionally, path);
        createBuilder.creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL_SEQUENTIAL)
                     .inBackground(callback, executor).forPath(path);
    } catch (Exception e) {
        result.completeExceptionally(StoreException.create(StoreException.Type.UNKNOWN, e, path));
    }

    return result;
}
 
Example #20
Source File: ZKStoreHelper.java    From pravega with Apache License 2.0 5 votes vote down vote up
CompletableFuture<String> createPersistentSequentialZNode(final String path, final byte[] data) {
    final CompletableFuture<String> result = new CompletableFuture<>();

    try {
        CreateBuilder createBuilder = client.create();
        BackgroundCallback callback = callback(x -> result.complete(x.getName()),
                result::completeExceptionally, path);
        createBuilder.creatingParentsIfNeeded().withMode(CreateMode.PERSISTENT_SEQUENTIAL)
                     .inBackground(callback, executor).forPath(path, data);
    } catch (Exception e) {
        result.completeExceptionally(StoreException.create(StoreException.Type.UNKNOWN, e, path));
    }

    return result;
}
 
Example #21
Source File: ZKStoreHelper.java    From pravega with Apache License 2.0 5 votes vote down vote up
CompletableFuture<Void> sync(final String path) {
    final CompletableFuture<Void> result = new CompletableFuture<>();

    try {
        BackgroundCallback callback = callback(x -> result.complete(null),
                result::completeExceptionally, path);
        client.sync().inBackground(callback, executor).forPath(path);
    } catch (Exception e) {
        result.completeExceptionally(StoreException.create(StoreException.Type.UNKNOWN, e, path));
    }

    return result;
}
 
Example #22
Source File: CuratorCacheImpl.java    From curator with Apache License 2.0 5 votes vote down vote up
private void checkChildrenChanged(String fromPath, Stat oldStat, Stat newStat)
{
    if ( (state.get() != State.STARTED) || !recursive )
    {
        return;
    }

    if ( (oldStat != null) && (oldStat.getCversion() == newStat.getCversion()) )
    {
        return; // children haven't changed
    }

    try
    {
        BackgroundCallback callback = (__, event) -> {
            if ( event.getResultCode() == OK.intValue() )
            {
                event.getChildren().forEach(child -> nodeChanged(ZKPaths.makePath(fromPath, child)));
            }
            else if ( event.getResultCode() == NONODE.intValue() )
            {
                removeStorage(event.getPath());
            }
            else
            {
                handleException(event);
            }
            outstandingOps.decrement();
        };

        outstandingOps.increment();
        client.getChildren().inBackground(callback).forPath(fromPath);
    }
    catch ( Exception e )
    {
        handleException(e);
    }
}
 
Example #23
Source File: CuratorStateManager.java    From incubator-heron with Apache License 2.0 5 votes vote down vote up
@Override
protected <M extends Message> ListenableFuture<M> getNodeData(
    WatchCallback watcher,
    String path,
    final Message.Builder builder) {
  final SettableFuture<M> future = SettableFuture.create();

  Watcher wc = ZkWatcherCallback.makeZkWatcher(watcher);

  BackgroundCallback cb = new BackgroundCallback() {
    @Override
    @SuppressWarnings("unchecked") // we don't know what M is until runtime
    public void processResult(CuratorFramework aClient, CuratorEvent event) throws Exception {
      byte[] data;
      if (event != null & (data = event.getData()) != null) {
        builder.mergeFrom(data);
        safeSetFuture(future, (M) builder.build());
      } else {
        safeSetException(future, new RuntimeException("Failed to fetch data from path: "
            + event.getPath()));
      }
    }
  };

  try {
    client.getData().usingWatcher(wc).inBackground(cb).forPath(path);

    // Suppress it since forPath() throws Exception
    // SUPPRESS CHECKSTYLE IllegalCatch
  } catch (Exception e) {
    safeSetException(future, new RuntimeException(
        "Could not getNodeData using watcher for path: " + path, e));
  }

  return future;
}
 
Example #24
Source File: ZookeeperCallbackWatcher.java    From Thunder with Apache License 2.0 5 votes vote down vote up
public ZookeeperCallbackWatcher(CuratorFramework client, BackgroundCallback callback, Object context, Executor executor) {
    super(client);

    this.callback = callback;
    this.context = context;
    this.executor = executor;
}
 
Example #25
Source File: LeaderLatch.java    From curator with Apache License 2.0 5 votes vote down vote up
private void getChildren() throws Exception
{
    BackgroundCallback callback = new BackgroundCallback()
    {
        @Override
        public void processResult(CuratorFramework client, CuratorEvent event) throws Exception
        {
            if ( event.getResultCode() == KeeperException.Code.OK.intValue() )
            {
                checkLeadership(event.getChildren());
            }
        }
    };
    client.getChildren().inBackground(callback).forPath(ZKPaths.makePath(latchPath, null));
}
 
Example #26
Source File: Backgrounding.java    From curator with Apache License 2.0 5 votes vote down vote up
Backgrounding(BackgroundCallback callback)
{
    this.inBackground = true;
    this.context = null;
    this.callback = callback;
    errorListener = null;
}
 
Example #27
Source File: Backgrounding.java    From curator with Apache License 2.0 5 votes vote down vote up
public Backgrounding(BackgroundCallback callback, UnhandledErrorListener errorListener)
{
    this.callback = callback;
    this.errorListener = errorListener;
    inBackground = true;
    context = null;
}
 
Example #28
Source File: Backgrounding.java    From curator with Apache License 2.0 5 votes vote down vote up
private static BackgroundCallback wrapCallback(final CuratorFrameworkImpl client, final BackgroundCallback callback, final Executor executor)
{
    return new BackgroundCallback()
    {
        @Override
        public void processResult(CuratorFramework dummy, final CuratorEvent event) throws Exception
        {
            executor.execute
                (
                    new Runnable()
                    {
                        @Override
                        public void run()
                        {
                            try
                            {
                                callback.processResult(client, event);
                            }
                            catch ( Exception e )
                            {
                                ThreadUtils.checkInterrupted(e);
                                if ( e instanceof KeeperException )
                                {
                                    client.validateConnection(client.codeToState(((KeeperException)e).code()));
                                }
                                client.logError("Background operation result handling threw exception", e);
                            }
                        }
                    }
                );
        }
    };
}
 
Example #29
Source File: PathChildrenCache.java    From curator with Apache License 2.0 5 votes vote down vote up
void refresh(final RefreshMode mode) throws Exception
{
    ensurePath();

    final BackgroundCallback callback = new BackgroundCallback()
    {
        @Override
        public void processResult(CuratorFramework client, CuratorEvent event) throws Exception
        {
            if ( reRemoveWatchersOnBackgroundClosed() )
            {
                return;
            }
            if ( event.getResultCode() == KeeperException.Code.OK.intValue() )
            {
                processChildren(event.getChildren(), mode);
            }
            else if ( event.getResultCode() == KeeperException.Code.NONODE.intValue() )
            {
                if ( mode == RefreshMode.NO_NODE_EXCEPTION )
                {
                    log.debug("KeeperException.NoNodeException received for getChildren() and refresh has failed. Resetting ensureContainers but not refreshing. Path: [{}]", path);
                    ensureContainers.reset();
                }
                else
                {
                    log.debug("KeeperException.NoNodeException received for getChildren(). Resetting ensureContainers. Path: [{}]", path);
                    ensureContainers.reset();
                    offerOperation(new RefreshOperation(PathChildrenCache.this, RefreshMode.NO_NODE_EXCEPTION));
                }
            }
        }
    };

    client.getChildren().usingWatcher(childrenWatcher).inBackground(callback).forPath(path);
}
 
Example #30
Source File: OperationAndData.java    From curator with Apache License 2.0 5 votes vote down vote up
OperationAndData(BackgroundOperation<T> operation, T data, BackgroundCallback callback, ErrorCallback<T> errorCallback, Object context, boolean connectionRequired)
{
    this.operation = operation;
    this.data = data;
    this.callback = callback;
    this.errorCallback = errorCallback;
    this.context = context;
    this.connectionRequired = connectionRequired;
    reset();
}