Search in sources :

Example 36 with BackgroundCallback

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

the class TestLeaderSelectorEdges method createProtectedNodeInBackgroundTest.

/**
 * Create a protected node in background with a retry policy
 */
@Test
public void createProtectedNodeInBackgroundTest() throws Exception {
    final CuratorFramework client = CuratorFrameworkFactory.builder().connectString(server.getConnectString()).retryPolicy(new RetryNTimes(2, 1)).connectionTimeoutMs(100).sessionTimeoutMs(60000).build();
    final CountDownLatch latch = new CountDownLatch(1);
    client.start();
    try {
        client.create().forPath(ChaosMonkeyCnxnFactory.CHAOS_ZNODE);
        client.create().withProtection().withMode(CreateMode.EPHEMERAL_SEQUENTIAL).inBackground(new BackgroundCallback() {

            public void processResult(CuratorFramework client, CuratorEvent event) throws Exception {
                log.info("Receive event {}", event.toString());
                if (event.getResultCode() == KeeperException.Code.CONNECTIONLOSS.intValue()) {
                    latch.countDown();
                }
            }
        }).forPath(ChaosMonkeyCnxnFactory.CHAOS_ZNODE_PREFIX + "foo-");
        Assert.assertTrue(latch.await(30, TimeUnit.SECONDS), "Callback has not been called");
        // Wait for the znode to be deleted
        Thread.sleep(ChaosMonkeyCnxnFactory.LOCKOUT_DURATION_MS * 2);
        // Check that there is no znode
        final int children = client.getChildren().forPath(ChaosMonkeyCnxnFactory.CHAOS_ZNODE).size();
        Assert.assertEquals(children, 0, "Still " + children + " znodes under " + ChaosMonkeyCnxnFactory.CHAOS_ZNODE + " lock");
    } finally {
        client.close();
    }
}
Also used : RetryNTimes(org.apache.curator.retry.RetryNTimes) CuratorFramework(org.apache.curator.framework.CuratorFramework) BackgroundCallback(org.apache.curator.framework.api.BackgroundCallback) CuratorEvent(org.apache.curator.framework.api.CuratorEvent) CountDownLatch(java.util.concurrent.CountDownLatch) Test(org.testng.annotations.Test)

Example 37 with BackgroundCallback

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

the class CuratorAsyncManager method getAsyncThrows.

private <T> Map<String, T> getAsyncThrows(final String pathNameForLogs, final Collection<String> paths, final Transcoder<T> transcoder, final Optional<ZkCache<T>> cache) throws Exception {
    final Map<String, T> objects = new HashMap<>(paths.size());
    if (cache.isPresent()) {
        for (Iterator<String> itr = paths.iterator(); itr.hasNext(); ) {
            final String path = itr.next();
            final Optional<T> fromCache = cache.get().get(path);
            if (fromCache.isPresent()) {
                objects.put(path, fromCache.get());
                itr.remove();
            }
        }
    }
    if (paths.isEmpty()) {
        return objects;
    }
    final Map<String, T> synchronizedObjects = Collections.synchronizedMap(objects);
    final CountDownLatch latch = new CountDownLatch(paths.size());
    final AtomicInteger bytes = new AtomicInteger();
    final BackgroundCallback callback = new BackgroundCallback() {

        @Override
        public void processResult(CuratorFramework client, CuratorEvent event) throws Exception {
            try {
                if (event.getData() == null || event.getData().length == 0) {
                    LOG.trace("Expected active node {} but it wasn't there", event.getPath());
                    return;
                }
                bytes.getAndAdd(event.getData().length);
                final T object = transcoder.fromBytes(event.getData());
                synchronizedObjects.put(event.getPath(), object);
                if (cache.isPresent()) {
                    cache.get().set(event.getPath(), object);
                }
            } finally {
                latch.countDown();
            }
        }
    };
    return queryAndReturnResultsThrows(objects, paths, callback, latch, pathNameForLogs, bytes, CuratorQueryMethod.GET_DATA);
}
Also used : CuratorFramework(org.apache.curator.framework.CuratorFramework) HashMap(java.util.HashMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) BackgroundCallback(org.apache.curator.framework.api.BackgroundCallback) CuratorEvent(org.apache.curator.framework.api.CuratorEvent) CountDownLatch(java.util.concurrent.CountDownLatch)

Aggregations

BackgroundCallback (org.apache.curator.framework.api.BackgroundCallback)37 CuratorFramework (org.apache.curator.framework.CuratorFramework)33 CuratorEvent (org.apache.curator.framework.api.CuratorEvent)33 CountDownLatch (java.util.concurrent.CountDownLatch)18 Test (org.testng.annotations.Test)14 RetryOneTime (org.apache.curator.retry.RetryOneTime)11 KeeperException (org.apache.zookeeper.KeeperException)7 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)6 Watcher (org.apache.zookeeper.Watcher)6 Timing (org.apache.curator.test.Timing)4 Test (org.junit.Test)4 InvocationOnMock (org.mockito.invocation.InvocationOnMock)4 CompletableFuture (java.util.concurrent.CompletableFuture)3 CreateBuilder (org.apache.curator.framework.api.CreateBuilder)3 RetryNTimes (org.apache.curator.retry.RetryNTimes)3 WatchedEvent (org.apache.zookeeper.WatchedEvent)3 Message (com.google.protobuf.Message)2 ArrayList (java.util.ArrayList)2 HashMap (java.util.HashMap)2 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)2