Search in sources :

Example 1 with BackgroundCallback

use of org.apache.curator.framework.api.BackgroundCallback in project heron by twitter.

the class CuratorStateManager method getNodeData.

@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
        // we don't know what M is until runtime
        @SuppressWarnings("unchecked")
        public void processResult(CuratorFramework aClient, CuratorEvent event) throws Exception {
            byte[] data;
            if (event != null & (data = event.getData()) != null) {
                builder.mergeFrom(data);
                future.set((M) builder.build());
            } else {
                future.setException(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) {
        future.setException(new RuntimeException("Could not getNodeData", e));
    }
    return future;
}
Also used : CuratorFramework(org.apache.curator.framework.CuratorFramework) Watcher(org.apache.zookeeper.Watcher) BackgroundCallback(org.apache.curator.framework.api.BackgroundCallback) CuratorEvent(org.apache.curator.framework.api.CuratorEvent) KeeperException(org.apache.zookeeper.KeeperException) ExecutionException(java.util.concurrent.ExecutionException)

Example 2 with BackgroundCallback

use of org.apache.curator.framework.api.BackgroundCallback in project flink by apache.

the class ZooKeeperStateHandleStoreITCase method testRemoveWithCallback.

/**
	 * Tests that state handles are correctly removed with a callback.
	 */
@Test
public void testRemoveWithCallback() throws Exception {
    // Setup
    LongStateStorage stateHandleProvider = new LongStateStorage();
    ZooKeeperStateHandleStore<Long> store = new ZooKeeperStateHandleStore<>(ZooKeeper.getClient(), stateHandleProvider, Executors.directExecutor());
    // Config
    final String pathInZooKeeper = "/testRemoveWithCallback";
    final Long state = 27255442L;
    store.add(pathInZooKeeper, state);
    final CountDownLatch sync = new CountDownLatch(1);
    BackgroundCallback callback = mock(BackgroundCallback.class);
    doAnswer(new Answer<Void>() {

        @Override
        public Void answer(InvocationOnMock invocation) throws Throwable {
            sync.countDown();
            return null;
        }
    }).when(callback).processResult(eq(ZooKeeper.getClient()), any(CuratorEvent.class));
    // Test
    store.remove(pathInZooKeeper, callback);
    // Verify discarded and callback called
    assertEquals(0, ZooKeeper.getClient().getChildren().forPath("/").size());
    sync.await();
    verify(callback, times(1)).processResult(eq(ZooKeeper.getClient()), any(CuratorEvent.class));
}
Also used : BackgroundCallback(org.apache.curator.framework.api.BackgroundCallback) CuratorEvent(org.apache.curator.framework.api.CuratorEvent) CountDownLatch(java.util.concurrent.CountDownLatch) InvocationOnMock(org.mockito.invocation.InvocationOnMock) Test(org.junit.Test)

Example 3 with BackgroundCallback

use of org.apache.curator.framework.api.BackgroundCallback in project pravega by pravega.

the class ZKStoreHelper method createZNodeIfNotExist.

CompletableFuture<Void> createZNodeIfNotExist(final String path, final boolean createParent) {
    final CompletableFuture<Void> result = new CompletableFuture<>();
    try {
        CreateBuilder createBuilder = client.create();
        BackgroundCallback callback = callback(x -> result.complete(null), e -> {
            if (e instanceof StoreException.DataExistsException) {
                result.complete(null);
            } else {
                result.completeExceptionally(e);
            }
        }, path);
        if (createParent) {
            createBuilder.creatingParentsIfNeeded().inBackground(callback, executor).forPath(path);
        } else {
            createBuilder.inBackground(callback, executor).forPath(path);
        }
    } catch (Exception e) {
        result.completeExceptionally(StoreException.create(StoreException.Type.UNKNOWN, e, path));
    }
    return result;
}
Also used : CompletableFuture(java.util.concurrent.CompletableFuture) CreateBuilder(org.apache.curator.framework.api.CreateBuilder) BackgroundCallback(org.apache.curator.framework.api.BackgroundCallback) KeeperException(org.apache.zookeeper.KeeperException)

Example 4 with BackgroundCallback

use of org.apache.curator.framework.api.BackgroundCallback in project pravega by pravega.

the class ZKStoreHelper method createEphemeralZNode.

CompletableFuture<Boolean> createEphemeralZNode(final String path, byte[] data) {
    final CompletableFuture<Boolean> result = new CompletableFuture<>();
    try {
        CreateBuilder createBuilder = client.create();
        BackgroundCallback callback = callback(x -> result.complete(true), e -> {
            if (e instanceof StoreException.DataExistsException) {
                result.complete(false);
            } else {
                result.completeExceptionally(e);
            }
        }, path);
        createBuilder.creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL).inBackground(callback, executor).forPath(path, data);
    } catch (Exception e) {
        result.completeExceptionally(StoreException.create(StoreException.Type.UNKNOWN, e, path));
    }
    return result;
}
Also used : CompletableFuture(java.util.concurrent.CompletableFuture) CreateBuilder(org.apache.curator.framework.api.CreateBuilder) BackgroundCallback(org.apache.curator.framework.api.BackgroundCallback) KeeperException(org.apache.zookeeper.KeeperException)

Example 5 with BackgroundCallback

use of org.apache.curator.framework.api.BackgroundCallback in project weicoder by wdcode.

the class ZookeeperClient method getDataAsync.

/**
 * 异步获取ZK节点数据,同时自动重新注册Watcher.
 * @param path 路径
 * @param callback 回调
 */
public static void getDataAsync(final String path, final Callback callback) {
    // 异步读取数据回调
    final BackgroundCallback background = (CuratorFramework client, CuratorEvent event) -> {
        try {
            callback.callBack(event.getData());
        } catch (Exception e) {
            Logs.error(e);
        }
    };
    // 每次接收ZK事件都要重新注册Watcher,然后才异步读数据
    final Watcher watcher = new Watcher() {

        @Override
        public void process(WatchedEvent event) {
            if (event.getType() == Event.EventType.NodeDataChanged) {
                try {
                    curatorFramework.getData().usingWatcher(this).inBackground(background).forPath(path);
                } catch (Exception e) {
                    Logs.error(e);
                }
            }
        }
    };
    // 这里首次注册Watcher并异步读数据
    try {
        curatorFramework.getData().usingWatcher(watcher).inBackground(background).forPath(path);
    } catch (Exception e) {
        Logs.error(e);
    }
}
Also used : WatchedEvent(org.apache.zookeeper.WatchedEvent) CuratorFramework(org.apache.curator.framework.CuratorFramework) Watcher(org.apache.zookeeper.Watcher) BackgroundCallback(org.apache.curator.framework.api.BackgroundCallback) CuratorEvent(org.apache.curator.framework.api.CuratorEvent)

Aggregations

BackgroundCallback (org.apache.curator.framework.api.BackgroundCallback)39 CuratorFramework (org.apache.curator.framework.CuratorFramework)35 CuratorEvent (org.apache.curator.framework.api.CuratorEvent)35 CountDownLatch (java.util.concurrent.CountDownLatch)18 Test (org.testng.annotations.Test)14 RetryOneTime (org.apache.curator.retry.RetryOneTime)11 KeeperException (org.apache.zookeeper.KeeperException)8 Watcher (org.apache.zookeeper.Watcher)8 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)6 Test (org.junit.Test)5 InvocationOnMock (org.mockito.invocation.InvocationOnMock)5 Timing (org.apache.curator.test.Timing)4 Message (com.google.protobuf.Message)3 CompletableFuture (java.util.concurrent.CompletableFuture)3 ExecutionException (java.util.concurrent.ExecutionException)3 TimeUnit (java.util.concurrent.TimeUnit)3 BackgroundPathable (org.apache.curator.framework.api.BackgroundPathable)3 CreateBuilder (org.apache.curator.framework.api.CreateBuilder)3 GetDataBuilder (org.apache.curator.framework.api.GetDataBuilder)3 RetryNTimes (org.apache.curator.retry.RetryNTimes)3