Search in sources :

Example 21 with BackgroundCallback

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

the class TestDistributedQueue method testFlush.

@Test
public void testFlush() throws Exception {
    final Timing timing = new Timing();
    final CountDownLatch latch = new CountDownLatch(1);
    DistributedQueue<TestQueueItem> queue = null;
    final CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1));
    client.start();
    try {
        final AtomicBoolean firstTime = new AtomicBoolean(true);
        queue = new DistributedQueue<TestQueueItem>(client, null, serializer, "/test", new ThreadFactoryBuilder().build(), MoreExecutors.directExecutor(), 10, true, null, QueueBuilder.NOT_SET, true, 0) {

            @Override
            void internalCreateNode(final String path, final byte[] bytes, final BackgroundCallback callback) throws Exception {
                if (firstTime.compareAndSet(true, false)) {
                    Executors.newSingleThreadExecutor().submit(new Callable<Object>() {

                        @Override
                        public Object call() throws Exception {
                            latch.await();
                            timing.sleepABit();
                            client.create().withMode(CreateMode.PERSISTENT_SEQUENTIAL).inBackground(callback).forPath(path, bytes);
                            return null;
                        }
                    });
                } else {
                    super.internalCreateNode(path, bytes, callback);
                }
            }
        };
        queue.start();
        queue.put(new TestQueueItem("1"));
        Assert.assertFalse(queue.flushPuts(timing.forWaiting().seconds(), TimeUnit.SECONDS));
        latch.countDown();
        Assert.assertTrue(queue.flushPuts(timing.forWaiting().seconds(), TimeUnit.SECONDS));
    } finally {
        if (latch.getCount() > 0) {
            latch.countDown();
        }
        CloseableUtils.closeQuietly(queue);
        CloseableUtils.closeQuietly(client);
    }
}
Also used : RetryOneTime(org.apache.curator.retry.RetryOneTime) BackgroundCallback(org.apache.curator.framework.api.BackgroundCallback) CountDownLatch(java.util.concurrent.CountDownLatch) Callable(java.util.concurrent.Callable) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) CuratorFramework(org.apache.curator.framework.CuratorFramework) ThreadFactoryBuilder(com.google.common.util.concurrent.ThreadFactoryBuilder) Timing(org.apache.curator.test.Timing) Test(org.testng.annotations.Test)

Example 22 with BackgroundCallback

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

the class TestSharedCount method testDisconnectReconnectEventDoesNotFireValueWatcher.

@Test
public void testDisconnectReconnectEventDoesNotFireValueWatcher() throws Exception {
    final CountDownLatch gotSuspendEvent = new CountDownLatch(1);
    final CountDownLatch gotChangeEvent = new CountDownLatch(1);
    final CountDownLatch getReconnectEvent = new CountDownLatch(1);
    final AtomicInteger numChangeEvents = new AtomicInteger(0);
    CuratorFramework curatorFramework = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryNTimes(10, 500));
    curatorFramework.start();
    curatorFramework.blockUntilConnected();
    SharedCount sharedCount = new SharedCount(curatorFramework, "/count", 10);
    sharedCount.addListener(new SharedCountListener() {

        @Override
        public void countHasChanged(SharedCountReader sharedCount, int newCount) throws Exception {
            numChangeEvents.incrementAndGet();
            gotChangeEvent.countDown();
        }

        @Override
        public void stateChanged(CuratorFramework client, ConnectionState newState) {
            if (newState == ConnectionState.SUSPENDED) {
                gotSuspendEvent.countDown();
            } else if (newState == ConnectionState.RECONNECTED) {
                getReconnectEvent.countDown();
            }
        }
    });
    sharedCount.start();
    try {
        sharedCount.setCount(11);
        Assert.assertTrue(gotChangeEvent.await(2, TimeUnit.SECONDS));
        server.stop();
        Assert.assertTrue(gotSuspendEvent.await(2, TimeUnit.SECONDS));
        server.restart();
        Assert.assertTrue(getReconnectEvent.await(2, TimeUnit.SECONDS));
        sharedCount.trySetCount(sharedCount.getVersionedValue(), 12);
        // flush background task queue
        final CountDownLatch flushDone = new CountDownLatch(1);
        curatorFramework.getData().inBackground(new BackgroundCallback() {

            @Override
            public void processResult(CuratorFramework client, CuratorEvent event) throws Exception {
                flushDone.countDown();
            }
        }).forPath("/count");
        flushDone.await(5, TimeUnit.SECONDS);
        Assert.assertEquals(2, numChangeEvents.get());
    } finally {
        CloseableUtils.closeQuietly(sharedCount);
        CloseableUtils.closeQuietly(curatorFramework);
    }
}
Also used : RetryNTimes(org.apache.curator.retry.RetryNTimes) BackgroundCallback(org.apache.curator.framework.api.BackgroundCallback) CuratorEvent(org.apache.curator.framework.api.CuratorEvent) CountDownLatch(java.util.concurrent.CountDownLatch) CuratorFramework(org.apache.curator.framework.CuratorFramework) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ConnectionState(org.apache.curator.framework.state.ConnectionState) Test(org.testng.annotations.Test)

Example 23 with BackgroundCallback

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

the class TestPersistentEphemeralNode method testSetUpdatedDataWhenReconnected.

@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();
    }
}
Also used : 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 24 with BackgroundCallback

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

the class CuratorStateManagerTest method testGetNodeData.

/**
 * Test getNodeData method
 * @throws Exception
 */
@Test
public void testGetNodeData() throws Exception {
    CuratorStateManager spyStateManager = spy(new CuratorStateManager());
    final CuratorFramework mockClient = mock(CuratorFramework.class);
    GetDataBuilder mockGetBuilder = mock(GetDataBuilder.class);
    // Mockito doesn't support mock type-parametrized class, thus suppress the warning
    @SuppressWarnings("rawtypes") BackgroundPathable mockBackPathable = mock(BackgroundPathable.class);
    final CuratorEvent mockEvent = mock(CuratorEvent.class);
    Message.Builder mockBuilder = mock(Message.Builder.class);
    Message mockMessage = mock(Message.class);
    final byte[] data = "wy_1989".getBytes();
    doReturn(mockMessage).when(mockBuilder).build();
    doReturn(data).when(mockEvent).getData();
    doReturn(PATH).when(mockEvent).getPath();
    doReturn(mockClient).when(spyStateManager).getCuratorClient();
    doReturn(true).when(mockClient).blockUntilConnected(anyInt(), any(TimeUnit.class));
    doReturn(mockGetBuilder).when(mockClient).getData();
    doReturn(mockBackPathable).when(mockGetBuilder).usingWatcher(any(Watcher.class));
    doAnswer(new Answer<Object>() {

        @Override
        public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
            Object[] objests = invocationOnMock.getArguments();
            // the first object is the BackgroundCallback
            ((BackgroundCallback) objests[0]).processResult(mockClient, mockEvent);
            return null;
        }
    }).when(mockBackPathable).inBackground(any(BackgroundCallback.class));
    spyStateManager.initialize(config);
    // Verify the data on node is fetched correctly
    ListenableFuture<Message> result = spyStateManager.getNodeData(null, PATH, mockBuilder);
    assertTrue(result.get().equals(mockMessage));
}
Also used : Message(com.google.protobuf.Message) Watcher(org.apache.zookeeper.Watcher) CuratorEvent(org.apache.curator.framework.api.CuratorEvent) BackgroundCallback(org.apache.curator.framework.api.BackgroundCallback) GetDataBuilder(org.apache.curator.framework.api.GetDataBuilder) CuratorFramework(org.apache.curator.framework.CuratorFramework) InvocationOnMock(org.mockito.invocation.InvocationOnMock) TimeUnit(java.util.concurrent.TimeUnit) BackgroundPathable(org.apache.curator.framework.api.BackgroundPathable) Test(org.junit.Test)

Example 25 with BackgroundCallback

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

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);
                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", 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)

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