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

The following examples show how to use org.apache.curator.framework.api.CuratorEvent. 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: PersistentNode.java    From xian with Apache License 2.0 6 votes vote down vote up
private void processBackgroundCallbackClosedState(CuratorEvent event)
{
    String path = null;
    if ( event.getResultCode() == KeeperException.Code.NODEEXISTS.intValue() )
    {
        path = event.getPath();
    }
    else if ( event.getResultCode() == KeeperException.Code.OK.intValue() )
    {
        path = event.getName();
    }

    if ( path != null )
    {
        try
        {
            client.delete().guaranteed().inBackground().forPath(path);
        }
        catch ( Exception e )
        {
            log.error("Could not delete node after close", e);
        }
    }
}
 
Example #2
Source File: PersistentNode.java    From curator with Apache License 2.0 6 votes vote down vote up
private void processBackgroundCallbackClosedState(CuratorEvent event)
{
    String path = null;
    if ( event.getResultCode() == KeeperException.Code.NODEEXISTS.intValue() )
    {
        path = event.getPath();
    }
    else if ( event.getResultCode() == KeeperException.Code.OK.intValue() )
    {
        path = event.getName();
    }

    if ( path != null )
    {
        try
        {
            client.delete().guaranteed().inBackground().forPath(path);
        }
        catch ( Exception e )
        {
            log.error("Could not delete node after close", e);
        }
    }
}
 
Example #3
Source File: ModeledFrameworkImpl.java    From curator with Apache License 2.0 6 votes vote down vote up
public static <T> ModeledFrameworkImpl<T> build(AsyncCuratorFramework client, ModelSpec<T> model, WatchMode watchMode, UnaryOperator<WatchedEvent> watcherFilter, UnhandledErrorListener unhandledErrorListener, UnaryOperator<CuratorEvent> resultFilter, Set<ModeledOptions> modeledOptions)
{
    boolean isWatched = (watchMode != null);

    Objects.requireNonNull(client, "client cannot be null");
    Objects.requireNonNull(model, "model cannot be null");
    modeledOptions = ImmutableSet.copyOf(Objects.requireNonNull(modeledOptions, "modeledOptions cannot be null"));

    watchMode = (watchMode != null) ? watchMode : WatchMode.stateChangeAndSuccess;

    AsyncCuratorFrameworkDsl dslClient = client.with(watchMode, unhandledErrorListener, resultFilter, watcherFilter);
    WatchableAsyncCuratorFramework watchableClient = isWatched ? dslClient.watched() : dslClient;

    return new ModeledFrameworkImpl<>(
        client,
        dslClient,
        watchableClient,
        model,
        watchMode,
        watcherFilter,
        unhandledErrorListener,
        resultFilter,
        isWatched,
        modeledOptions
    );
}
 
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 StoreException translateErrorCode(String path, CuratorEvent event) {
    StoreException ex;
    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()) {
        ex = StoreException.create(StoreException.Type.CONNECTION_ERROR, path);
    } else if (event.getResultCode() == KeeperException.Code.NODEEXISTS.intValue()) {
        ex = StoreException.create(StoreException.Type.DATA_EXISTS, path);
    } else if (event.getResultCode() == KeeperException.Code.BADVERSION.intValue()) {
        ex = StoreException.create(StoreException.Type.WRITE_CONFLICT, path);
    } else if (event.getResultCode() == KeeperException.Code.NONODE.intValue()) {
        ex = StoreException.create(StoreException.Type.DATA_NOT_FOUND, path);
    } else if (event.getResultCode() == KeeperException.Code.NOTEMPTY.intValue()) {
        ex = StoreException.create(StoreException.Type.DATA_CONTAINS_ELEMENTS, path);
    } else {
        ex = StoreException.create(StoreException.Type.UNKNOWN,
                KeeperException.create(KeeperException.Code.get(event.getResultCode()), path));
    }
    return ex;
}
 
Example #6
Source File: CuratorMultiTransactionImpl.java    From curator with Apache License 2.0 6 votes vote down vote up
@Override
public void performBackgroundOperation(final OperationAndData<CuratorMultiTransactionRecord> operationAndData) throws Exception
{
    try
    {
        final TimeTrace trace = client.getZookeeperClient().startTracer("CuratorMultiTransactionImpl-Background");
        AsyncCallback.MultiCallback callback = new AsyncCallback.MultiCallback()
        {
            @Override
            public void processResult(int rc, String path, Object ctx, List<OpResult> opResults)
            {
                trace.commit();
                List<CuratorTransactionResult> curatorResults = (opResults != null) ? CuratorTransactionImpl.wrapResults(client, opResults, operationAndData.getData()) : null;
                CuratorEvent event = new CuratorEventImpl(client, CuratorEventType.TRANSACTION, rc, path, null, ctx, null, null, null, null, null, curatorResults);
                client.processBackgroundOperation(operationAndData, event);
            }
        };
        client.getZooKeeper().multi(operationAndData.getData(), callback, backgrounding.getContext());
    }
    catch ( Throwable e )
    {
        backgrounding.checkError(e, null);
    }
}
 
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: ZkParallelFetcher.java    From Baragon with Apache License 2.0 6 votes vote down vote up
@Override
public void processResult(CuratorFramework client, CuratorEvent event) throws Exception {
  try {
    KeeperException.Code code = KeeperException.Code.get(event.getResultCode());

    switch (code) {
      case OK:
        T data = event.getData() == null ? null : transformFunction.apply(event.getData());
        dataMap.put(ZKPaths.getNodeFromPath(event.getPath()), data);
        break;
      case NONODE:
        // In this case there was a race condition in which the child node was deleted before we asked for data.
        break;
      default:
        exceptions.add(KeeperException.create(code, event.getPath()));
    }
  } finally {
    countDownLatch.countDown();
  }
}
 
Example #9
Source File: ZkParallelFetcher.java    From Baragon with Apache License 2.0 6 votes vote down vote up
@Override
public void processResult(CuratorFramework client, CuratorEvent event) throws Exception {
  try {
    KeeperException.Code code = KeeperException.Code.get(event.getResultCode());

    switch (code) {
      case OK:
        childMap.put(ZKPaths.getNodeFromPath(event.getPath()), new HashSet<>(event.getChildren()));
        break;
      case NONODE:
        // In this case there was a race condition in which the child node was deleted before we asked for data.
        break;
      default:
        exceptions.add(KeeperException.create(code, event.getPath()));
    }
  } finally {
    countDownLatch.countDown();
  }
}
 
Example #10
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 #11
Source File: CuratorEventCatcher.java    From hadoop with Apache License 2.0 5 votes vote down vote up
@Override
public void processResult(CuratorFramework client,
    CuratorEvent event) throws
    Exception {
  LOG.info("received {}", event);
  eventCounter.incrementAndGet();
  events.put(event);
}
 
Example #12
Source File: DeleteCompletionCallback.java    From hadoop with Apache License 2.0 5 votes vote down vote up
@Override
public void processResult(CuratorFramework client,
    CuratorEvent event) throws
    Exception {
  if (LOG.isDebugEnabled()) {
    LOG.debug("Delete event {}", event);
  }
  events.incrementAndGet();
}
 
Example #13
Source File: TestCuratorService.java    From hadoop with Apache License 2.0 5 votes vote down vote up
@Test
public void testBackgroundDelete() throws Throwable {
  mkPath("/rm", CreateMode.PERSISTENT);
  mkPath("/rm/child", CreateMode.PERSISTENT);
  CuratorEventCatcher events = new CuratorEventCatcher();
  curatorService.zkDelete("/rm", true, events);
  CuratorEvent taken = events.take();
  LOG.info("took {}", taken);
  assertEquals(1, events.getCount());
}
 
Example #14
Source File: Zookeeper.java    From jstorm with Apache License 2.0 5 votes vote down vote up
/**
 * connect ZK, register watchers
 */
public CuratorFramework mkClient(Map conf, List<String> servers, Object port,
                                 String root, final WatcherCallBack watcher) {

    CuratorFramework fk = Utils.newCurator(conf, servers, port, root);

    fk.getCuratorListenable().addListener(new CuratorListener() {
        @Override
        public void eventReceived(CuratorFramework _fk, CuratorEvent e) throws Exception {
            if (e.getType().equals(CuratorEventType.WATCHED)) {
                WatchedEvent event = e.getWatchedEvent();

                watcher.execute(event.getState(), event.getType(), event.getPath());
            }

        }
    });

    fk.getUnhandledErrorListenable().addListener(new UnhandledErrorListener() {
        @Override
        public void unhandledError(String msg, Throwable error) {
            String errmsg = "Unrecoverable zookeeper error, halting process: " + msg;
            LOG.error(errmsg, error);
            JStormUtils.halt_process(1, "Unrecoverable zookeeper error");

        }
    });
    fk.start();
    return fk;
}
 
Example #15
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 #16
Source File: ModeledFrameworkImpl.java    From curator with Apache License 2.0 5 votes vote down vote up
private ModeledFrameworkImpl(AsyncCuratorFramework client, AsyncCuratorFrameworkDsl dslClient, WatchableAsyncCuratorFramework watchableClient, ModelSpec<T> modelSpec, WatchMode watchMode, UnaryOperator<WatchedEvent> watcherFilter, UnhandledErrorListener unhandledErrorListener, UnaryOperator<CuratorEvent> resultFilter, boolean isWatched, Set<ModeledOptions> modeledOptions)
{
    this.client = client;
    this.dslClient = dslClient;
    this.watchableClient = watchableClient;
    this.modelSpec = modelSpec;
    this.watchMode = watchMode;
    this.watcherFilter = watcherFilter;
    this.unhandledErrorListener = unhandledErrorListener;
    this.resultFilter = resultFilter;
    this.isWatched = isWatched;
    this.modeledOptions = modeledOptions;
}
 
Example #17
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 #18
Source File: BackgroundProcs.java    From curator with Apache License 2.0 5 votes vote down vote up
static <T> BackgroundProc<T> makeProc(Function<CuratorEvent, T> proc)
{
    return (event, future) -> {
        if ( event.getResultCode() == 0 )
        {
            future.complete(proc.apply(event));
        }
        else
        {
            future.completeExceptionally(KeeperException.create(KeeperException.Code.get(event.getResultCode()), event.getPath()));
        }
        return null;
    };
}
 
Example #19
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 #20
Source File: PersistentNode.java    From curator with Apache License 2.0 5 votes vote down vote up
private void processBackgroundCallback(CuratorEvent event) throws Exception
{
    String path = null;
    boolean nodeExists = false;
    if ( event.getResultCode() == KeeperException.Code.NODEEXISTS.intValue() )
    {
        path = event.getPath();
        nodeExists = true;
    }
    else if ( event.getResultCode() == KeeperException.Code.OK.intValue() )
    {
        path = event.getName();
    }
    else if ( event.getResultCode() == KeeperException.Code.NOAUTH.intValue() )
    {
        log.warn("Client does not have authorisation to create node at path {}", event.getPath());
        authFailure.set(true);
        return;
    }
    if ( path != null )
    {
        authFailure.set(false);
        nodePath.set(path);
        watchNode();

        if ( nodeExists )
        {
            client.setData().inBackground(setDataCallback).forPath(getActualPath(), getData());
        }
        else
        {
            initialisationComplete();
            notifyListeners();
        }
    }
    else
    {
        createNode();
    }
}
 
Example #21
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 #22
Source File: PathChildrenCache.java    From curator 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
        {
            if ( reRemoveWatchersOnBackgroundClosed() )
            {
                return;
            }
            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 #23
Source File: NodeCache.java    From curator with Apache License 2.0 5 votes vote down vote up
private void processBackgroundResult(CuratorEvent event) throws Exception
{
    switch ( event.getType() )
    {
        case GET_DATA:
        {
            if ( event.getResultCode() == KeeperException.Code.OK.intValue() )
            {
                ChildData childData = new ChildData(path, event.getStat(), event.getData());
                setNewData(childData);
            }
            break;
        }

        case EXISTS:
        {
            if ( event.getResultCode() == KeeperException.Code.NONODE.intValue() )
            {
                setNewData(null);
            }
            else if ( event.getResultCode() == KeeperException.Code.OK.intValue() )
            {
                if ( dataIsCompressed )
                {
                    client.getData().decompressed().usingWatcher(watcher).inBackground(backgroundCallback).forPath(path);
                }
                else
                {
                    client.getData().usingWatcher(watcher).inBackground(backgroundCallback).forPath(path);
                }
            }
            break;
        }
    }
}
 
Example #24
Source File: ChildrenCache.java    From curator with Apache License 2.0 5 votes vote down vote up
@Override
public void processResult(CuratorFramework client, CuratorEvent event) throws Exception
{
    if ( event.getResultCode() == KeeperException.Code.OK.intValue() )
    {
        setNewChildren(event.getChildren());
    }
}
 
Example #25
Source File: DistributedQueue.java    From curator with Apache License 2.0 5 votes vote down vote up
private void doPutInBackground(final T item, String path, final MultiItem<T> givenMultiItem, byte[] bytes) throws Exception
{
    BackgroundCallback callback = new BackgroundCallback()
    {
        @Override
        public void processResult(CuratorFramework client, CuratorEvent event) throws Exception
        {
            if ( event.getResultCode() != KeeperException.Code.OK.intValue() )
            {
                return;
            }

            if ( event.getType() == CuratorEventType.CREATE )
            {
                synchronized(putCount)
                {
                    putCount.decrementAndGet();
                    putCount.notifyAll();
                }
            }

            putListenerContainer.forEach(listener -> {
                if ( item != null )
                {
                    listener.putCompleted(item);
                }
                else
                {
                    listener.putMultiCompleted(givenMultiItem);
                }
            });
        }
    };
    internalCreateNode(path, bytes, callback);
}
 
Example #26
Source File: LeaderLatch.java    From curator 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 #27
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 #28
Source File: TestPersistentEphemeralNode.java    From curator 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);
    try
    {
        node.debugWaitMsForBackgroundBeforeClose.set(timing.forSleepingABit().milliseconds());
        node.start();
        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
    {
        CloseableUtils.closeQuietly(node);
    }
}
 
Example #29
Source File: CuratorAsyncManager.java    From Singularity with Apache License 2.0 5 votes vote down vote up
private <T extends SingularityId> List<T> notExistsThrows(
  final String pathNameforLogs,
  final Map<String, T> pathsMap
)
  throws Exception {
  if (pathsMap.isEmpty()) {
    return Collections.emptyList();
  }

  final List<T> objects = Lists.newArrayListWithCapacity(pathsMap.size());

  final CountDownLatch latch = new CountDownLatch(pathsMap.size());

  final BackgroundCallback callback = new BackgroundCallback() {

    @Override
    public void processResult(CuratorFramework client, CuratorEvent event)
      throws Exception {
      try {
        if (event.getStat() == null) {
          objects.add(pathsMap.get(event.getPath()));
        }
      } finally {
        latch.countDown();
      }
    }
  };

  return queryAndReturnResultsThrows(
    objects,
    pathsMap.keySet(),
    callback,
    latch,
    pathNameforLogs,
    new AtomicInteger(),
    CuratorQueryMethod.CHECK_EXISTS
  );
}
 
Example #30
Source File: DefaultBaragonStateFetcher.java    From Baragon with Apache License 2.0 5 votes vote down vote up
private void syncStateNode() throws Exception {
  final CountDownLatch latch = new CountDownLatch(1);
  curatorReference.get().sync().inBackground(new BackgroundCallback() {

    @Override
    public void processResult(CuratorFramework client, CuratorEvent event) throws Exception {
      latch.countDown();
    }
  }).forPath("/state");

  latch.await();
}