Search in sources :

Example 26 with CuratorEvent

use of org.apache.curator.framework.api.CuratorEvent 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 27 with CuratorEvent

use of org.apache.curator.framework.api.CuratorEvent 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 28 with CuratorEvent

use of org.apache.curator.framework.api.CuratorEvent 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 29 with CuratorEvent

use of org.apache.curator.framework.api.CuratorEvent 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)

Example 30 with CuratorEvent

use of org.apache.curator.framework.api.CuratorEvent in project curator by Netflix.

the class CuratorZKClientBridge method connect.

@Override
public void connect(final Watcher watcher) {
    if (watcher != null) {
        CuratorListener localListener = new CuratorListener() {

            @Override
            public void eventReceived(CuratorFramework client, CuratorEvent event) throws Exception {
                if (event.getWatchedEvent() != null) {
                    watcher.process(event.getWatchedEvent());
                }
            }
        };
        curator.getCuratorListenable().addListener(localListener);
        listener.set(localListener);
        try {
            BackgroundCallback callback = new BackgroundCallback() {

                @Override
                public void processResult(CuratorFramework client, CuratorEvent event) throws Exception {
                    WatchedEvent fakeEvent = new WatchedEvent(Watcher.Event.EventType.None, curator.getZookeeperClient().isConnected() ? Watcher.Event.KeeperState.SyncConnected : Watcher.Event.KeeperState.Disconnected, null);
                    watcher.process(fakeEvent);
                }
            };
            curator.checkExists().inBackground(callback).forPath("/foo");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
Also used : WatchedEvent(org.apache.zookeeper.WatchedEvent) CuratorFramework(org.apache.curator.framework.CuratorFramework) CuratorListener(org.apache.curator.framework.api.CuratorListener) CuratorEvent(org.apache.curator.framework.api.CuratorEvent) BackgroundCallback(org.apache.curator.framework.api.BackgroundCallback) KeeperException(org.apache.zookeeper.KeeperException)

Aggregations

CuratorEvent (org.apache.curator.framework.api.CuratorEvent)60 CuratorFramework (org.apache.curator.framework.CuratorFramework)57 BackgroundCallback (org.apache.curator.framework.api.BackgroundCallback)36 CountDownLatch (java.util.concurrent.CountDownLatch)34 CuratorListener (org.apache.curator.framework.api.CuratorListener)23 Test (org.testng.annotations.Test)21 RetryOneTime (org.apache.curator.retry.RetryOneTime)18 KeeperException (org.apache.zookeeper.KeeperException)14 Test (org.junit.Test)11 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)8 Watcher (org.apache.zookeeper.Watcher)8 ArrayList (java.util.ArrayList)4 Timing (org.apache.curator.test.Timing)4 WatchedEvent (org.apache.zookeeper.WatchedEvent)4 InvocationOnMock (org.mockito.invocation.InvocationOnMock)4 Message (com.google.protobuf.Message)3 IOException (java.io.IOException)3 Map (java.util.Map)3 ExecutionException (java.util.concurrent.ExecutionException)3 TimeUnit (java.util.concurrent.TimeUnit)3