org.apache.curator.x.async.AsyncCuratorFramework Java Examples

The following examples show how to use org.apache.curator.x.async.AsyncCuratorFramework. 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: TestFramework.java    From curator with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetSequentialChildren() throws Exception
{
    CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1));
    client.start();
    try
    {
        Semaphore semaphore = new Semaphore(0);
        AsyncCuratorFramework async = AsyncCuratorFramework.wrap(client);
        async.create().forPath("/head").thenRun(() -> {
            for ( int i = 0; i < 10; ++i )
            {
                async.create().withMode(CreateMode.EPHEMERAL_SEQUENTIAL).forPath("/head/child").thenRun(semaphore::release);
            }
        });

        Assert.assertTrue(new Timing().acquireSemaphore(semaphore, 10));
        List<String> children = async.getChildren().forPath("/head").toCompletableFuture().get();
        Assert.assertEquals(children.size(), 10);
    }
    finally
    {
        CloseableUtils.closeQuietly(client);
    }
}
 
Example #2
Source File: TestFramework.java    From curator with Apache License 2.0 6 votes vote down vote up
@Test
public void testCreateParents() throws Exception
{
    CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder();
    CuratorFramework client = builder.connectString(server.getConnectString()).retryPolicy(new RetryOneTime(1)).build();
    client.start();
    try
    {
        AsyncCuratorFramework async = AsyncCuratorFramework.wrap(client);
        async.create().withOptions(EnumSet.of(CreateOption.createParentsIfNeeded)).forPath("/one/two/three", "foo".getBytes()).toCompletableFuture().get();
        byte[] data = async.getData().forPath("/one/two/three").toCompletableFuture().get();
        Assert.assertEquals(data, "foo".getBytes());

        async.create().withOptions(EnumSet.of(CreateOption.createParentsIfNeeded)).forPath("/one/two/another", "bar".getBytes());
        data = async.getData().forPath("/one/two/another").toCompletableFuture().get();
        Assert.assertEquals(data, "bar".getBytes());
    }
    finally
    {
        CloseableUtils.closeQuietly(client);
    }
}
 
Example #3
Source File: TestFrameworkBackground.java    From curator with Apache License 2.0 6 votes vote down vote up
/**
 * Attempt a background operation while Zookeeper server is down.
 * Return code must be {@link org.apache.zookeeper.KeeperException.Code#CONNECTIONLOSS}
 */
@Test
public void testCuratorCallbackOnError() throws Exception
{
    Timing timing = new Timing();
    final CountDownLatch latch = new CountDownLatch(1);
    try ( CuratorFramework client = CuratorFrameworkFactory.builder().connectString(server.getConnectString()).sessionTimeoutMs(timing.session()).connectionTimeoutMs(timing.connection()).retryPolicy(new RetryOneTime(1000)).build() )
    {
        client.start();
        AsyncCuratorFramework async = AsyncCuratorFramework.wrap(client);
        // Stop the Zookeeper server
        server.stop();
        // Attempt to retrieve children list
        async.getChildren().forPath("/").handle((children, e) -> {
            if ( e instanceof KeeperException.ConnectionLossException )
            {
                latch.countDown();
            }
            return null;
        });
        // Check if the callback has been called with a correct return code
        Assert.assertTrue(timing.awaitLatch(latch), "Callback has not been called by curator !");
    }
}
 
Example #4
Source File: TestFramework.java    From curator with Apache License 2.0 6 votes vote down vote up
@Test
public void testCreateWithProtection() throws ExecutionException, InterruptedException
{
    CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1));
    try
    {
        client.start();
        AsyncCuratorFramework async = AsyncCuratorFramework.wrap(client);
        String path = async.create().withOptions(Collections.singleton(CreateOption.doProtected)).forPath("/yo").toCompletableFuture().get();
        String node = ZKPaths.getNodeFromPath(path);
        // CURATOR-489: confirm that the node contains a valid UUID, eg '_c_53345f98-9423-4e0c-a7b5-9f819e3ec2e1-yo'
        Assert.assertTrue(ProtectedUtils.isProtectedZNode(node));
        Assert.assertEquals(ProtectedUtils.normalize(node), "yo");
    }
    finally
    {
        CloseableUtils.closeQuietly(client);
    }
}
 
Example #5
Source File: TestModeledFramework.java    From curator with Apache License 2.0 6 votes vote down vote up
@Test
public void testAcl() throws NoSuchAlgorithmException
{
    List<ACL> aclList = Collections.singletonList(new ACL(ZooDefs.Perms.WRITE, new Id("digest", DigestAuthenticationProvider.generateDigest("test:test"))));
    ModelSpec<TestModel> aclModelSpec = ModelSpec.builder(modelSpec.path(), modelSpec.serializer()).withAclList(aclList).build();
    ModeledFramework<TestModel> client = ModeledFramework.wrap(async, aclModelSpec);
    complete(client.set(new TestModel("John", "Galt", "Galt's Gulch", 21, BigInteger.valueOf(1010101))));
    complete(client.update(new TestModel("John", "Galt", "Galt's Gulch", 54, BigInteger.valueOf(88))), (__, e) -> Assert.assertNotNull(e, "Should've gotten an auth failure"));

    try (CuratorFramework authCurator = CuratorFrameworkFactory.builder().connectString(server.getConnectString()).retryPolicy(new RetryOneTime(1)).authorization("digest", "test:test".getBytes()).build())
    {
        authCurator.start();
        ModeledFramework<TestModel> authClient = ModeledFramework.wrap(AsyncCuratorFramework.wrap(authCurator), aclModelSpec);
        complete(authClient.update(new TestModel("John", "Galt", "Galt's Gulch", 42, BigInteger.valueOf(66))), (__, e) -> Assert.assertNull(e, "Should've succeeded"));
    }
}
 
Example #6
Source File: TestModeledFramework.java    From curator with Apache License 2.0 6 votes vote down vote up
@Test
public void testSchema() throws Exception
{
    Schema schema = modelSpec.schema();
    try (CuratorFramework schemaClient = CuratorFrameworkFactory.builder().connectString(server.getConnectString()).retryPolicy(new RetryOneTime(1)).schemaSet(new SchemaSet(Collections.singletonList(schema), false)).build())
    {
        schemaClient.start();

        try
        {
            schemaClient.create().forPath(modelSpec.path().fullPath(), "asflasfas".getBytes());
            Assert.fail("Should've thrown SchemaViolation");
        }
        catch ( SchemaViolation dummy )
        {
            // expected
        }

        ModeledFramework<TestModel> modeledSchemaClient = ModeledFramework.wrap(AsyncCuratorFramework.wrap(schemaClient), modelSpec);
        complete(modeledSchemaClient.set(new TestModel("one", "two", "three", 4, BigInteger.ONE)), (dummy, e) -> Assert.assertNull(e));
    }
}
 
Example #7
Source File: TestModeledFrameworkBase.java    From curator with Apache License 2.0 6 votes vote down vote up
@BeforeMethod
@Override
public void setup() throws Exception
{
    super.setup();

    rawClient = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1));
    rawClient.start();
    async = AsyncCuratorFramework.wrap(rawClient);

    JacksonModelSerializer<TestModel> serializer = JacksonModelSerializer.build(TestModel.class);
    JacksonModelSerializer<TestNewerModel> newSerializer = JacksonModelSerializer.build(TestNewerModel.class);

    modelSpec = ModelSpec.builder(path, serializer).build();
    newModelSpec = ModelSpec.builder(path, newSerializer).build();
}
 
Example #8
Source File: TestFramework.java    From curator with Apache License 2.0 6 votes vote down vote up
@Test
public void testCreatingParentsTheSame() throws Exception
{
    CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1));
    try
    {
        client.start();
        AsyncCuratorFramework async = AsyncCuratorFramework.wrap(client);

        Assert.assertNull(client.checkExists().forPath("/one/two"));
        async.create().withOptions(EnumSet.of(CreateOption.createParentsAsContainers)).forPath("/one/two/three").toCompletableFuture().get();
        Assert.assertNotNull(async.checkExists().forPath("/one/two").toCompletableFuture().get());

        async.delete().withOptions(EnumSet.of(DeleteOption.deletingChildrenIfNeeded)).forPath("/one").toCompletableFuture().get();
        Assert.assertNull(client.checkExists().forPath("/one"));

        Assert.assertNull(async.checkExists().forPath("/one/two").toCompletableFuture().get());
        async.checkExists().withOptions(EnumSet.of(ExistsOption.createParentsAsContainers)).forPath("/one/two/three").toCompletableFuture().get();
        Assert.assertNotNull(async.checkExists().forPath("/one/two").toCompletableFuture().get());
        Assert.assertNull(async.checkExists().forPath("/one/two/three").toCompletableFuture().get());
    }
    finally
    {
        CloseableUtils.closeQuietly(client);
    }
}
 
Example #9
Source File: TestFramework.java    From curator with Apache License 2.0 6 votes vote down vote up
@Test
public void testExistsCreatingParents() throws Exception
{
    CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1));
    try
    {
        client.start();
        AsyncCuratorFramework async = AsyncCuratorFramework.wrap(client);

        Assert.assertNull(async.checkExists().forPath("/one/two").toCompletableFuture().get());
        async.checkExists().withOptions(EnumSet.of(ExistsOption.createParentsAsContainers)).forPath("/one/two/three").toCompletableFuture().get();
        Assert.assertNotNull(async.checkExists().forPath("/one/two").toCompletableFuture().get());
        Assert.assertNull(async.checkExists().forPath("/one/two/three").toCompletableFuture().get());
        Assert.assertNull(async.checkExists().withOptions(EnumSet.of(ExistsOption.createParentsAsContainers)).forPath("/one/two/three").toCompletableFuture().get());
    }
    finally
    {
        CloseableUtils.closeQuietly(client);
    }
}
 
Example #10
Source File: TestFramework.java    From curator with Apache License 2.0 6 votes vote down vote up
@Test
public void testSyncNew() throws Exception
{
    CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1));
    client.start();
    try
    {
        client.create().forPath("/head");
        Assert.assertNotNull(client.checkExists().forPath("/head"));

        final CountDownLatch latch = new CountDownLatch(1);
        AsyncCuratorFramework async = AsyncCuratorFramework.wrap(client);
        async.sync().forPath("/head").handle((v, e) -> {
            Assert.assertNull(v);
            Assert.assertNull(e);
            latch.countDown();
            return null;
        });
        Assert.assertTrue(latch.await(10, TimeUnit.SECONDS));
    }
    finally
    {
        CloseableUtils.closeQuietly(client);
    }
}
 
Example #11
Source File: TestFramework.java    From curator with Apache License 2.0 6 votes vote down vote up
@Test
public void testBackgroundDelete() throws Exception
{
    CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1));
    client.start();
    try
    {
        AsyncCuratorFramework async = AsyncCuratorFramework.wrap(client);
        CountDownLatch latch = new CountDownLatch(1);
        async.create().forPath("/head").thenRun(() ->
            async.delete().forPath("/head").handle((v, e) -> {
                Assert.assertNull(v);
                Assert.assertNull(e);
                latch.countDown();
                return null;
            })
        );
        Assert.assertTrue(latch.await(10, TimeUnit.SECONDS));
        Assert.assertNull(client.checkExists().forPath("/head"));
    }
    finally
    {
        CloseableUtils.closeQuietly(client);
    }
}
 
Example #12
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 #13
Source File: TestFramework.java    From curator with Apache License 2.0 6 votes vote down vote up
@Test
public void testDeleteGuaranteedWithChildren() throws Exception
{
    CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder();
    CuratorFramework client = builder.connectString(server.getConnectString()).retryPolicy(new RetryOneTime(1)).build();
    client.start();
    try
    {
        AsyncCuratorFramework async = AsyncCuratorFramework.wrap(client);
        async.create().withOptions(EnumSet.of(CreateOption.createParentsIfNeeded)).forPath("/one/two/three/four/five/six", "foo".getBytes()).toCompletableFuture().get();
        async.delete().withOptions(EnumSet.of(DeleteOption.guaranteed, DeleteOption.deletingChildrenIfNeeded)).forPath("/one/two/three/four/five").toCompletableFuture().get();
        Assert.assertNull(async.checkExists().forPath("/one/two/three/four/five").toCompletableFuture().get());
        async.delete().withOptions(EnumSet.of(DeleteOption.guaranteed, DeleteOption.deletingChildrenIfNeeded)).forPath("/one/two").toCompletableFuture().get();
        Assert.assertNull(async.checkExists().forPath("/one/two").toCompletableFuture().get());
    }
    finally
    {
        CloseableUtils.closeQuietly(client);
    }
}
 
Example #14
Source File: AsyncExamples.java    From curator with Apache License 2.0 6 votes vote down vote up
public static void create(CuratorFramework client, String path, byte[] payload)
{
    AsyncCuratorFramework async = AsyncCuratorFramework.wrap(client);   // normally you'd wrap early in your app and reuse the instance

    // create a node at the given path with the given payload asynchronously
    async.create().forPath(path, payload).whenComplete((name, exception) -> {
        if ( exception != null )
        {
            // there was a problem
            exception.printStackTrace();
        }
        else
        {
            System.out.println("Created node name is: " + name);
        }
    });
}
 
Example #15
Source File: ConnectionManagementManualTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void givenRunningZookeeper_whenOpenConnectionUsingAsyncBlocking_thenClientIsOpened()
    throws InterruptedException {
    int sleepMsBetweenRetries = 100;
    int maxRetries = 3;
    RetryPolicy retryPolicy = new RetryNTimes(maxRetries,
        sleepMsBetweenRetries);

    try (CuratorFramework client = CuratorFrameworkFactory
        .newClient("127.0.0.1:2181", retryPolicy)) {
        client.start();
        AsyncCuratorFramework async = AsyncCuratorFramework.wrap(client);

        AtomicBoolean exists = new AtomicBoolean(false);

        async.checkExists()
            .forPath("/")
            .thenAccept(s -> exists.set(s != null));

        await().until(() -> assertThat(exists.get()).isTrue());
    }
}
 
Example #16
Source File: ConnectionManagementManualTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void givenRunningZookeeper_whenOpenConnectionUsingAsyncNotBlocking_thenClientIsOpened()
    throws InterruptedException {
    int sleepMsBetweenRetries = 100;
    int maxRetries = 3;
    RetryPolicy retryPolicy = new RetryNTimes(maxRetries,
        sleepMsBetweenRetries);

    try (CuratorFramework client = CuratorFrameworkFactory
        .newClient("127.0.0.1:2181", retryPolicy)) {
        client.start();
        AsyncCuratorFramework async = AsyncCuratorFramework.wrap(client);

        AtomicBoolean exists = new AtomicBoolean(false);

        async.checkExists()
            .forPath("/")
            .thenAcceptAsync(s -> exists.set(s != null));

        await().until(() -> assertThat(exists.get()).isTrue());
    }
}
 
Example #17
Source File: ConfigurationManagementManualTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void givenPath_whenCreateKey_thenValueIsStored() throws Exception {
    try (CuratorFramework client = newClient()) {
        client.start();
        AsyncCuratorFramework async = AsyncCuratorFramework.wrap(client);
        String key = getKey();
        String expected = "my_value";

        // Create key nodes structure
        client.create()
            .forPath(key);

        // Set data value for our key
        async.setData()
            .forPath(key, expected.getBytes());

        // Get data value
        AtomicBoolean isEquals = new AtomicBoolean();
        async.getData()
            .forPath(key)
            .thenAccept(
                data -> isEquals.set(new String(data).equals(expected)));

        await().until(() -> assertThat(isEquals.get()).isTrue());
    }
}
 
Example #18
Source File: AsyncExamples.java    From curator with Apache License 2.0 6 votes vote down vote up
public static void createThenWatchSimple(CuratorFramework client, String path)
{
    AsyncCuratorFramework async = AsyncCuratorFramework.wrap(client);   // normally you'd wrap early in your app and reuse the instance

    // create a node at the given path with the given payload asynchronously
    // then watch the created node
    async.create().forPath(path).whenComplete((name, exception) -> {
        if ( exception != null )
        {
            // there was a problem creating the node
            exception.printStackTrace();
        }
        else
        {
            // because "WatchMode.successOnly" is used the watch stage is only triggered when
            // the EventType is a node event
            async.with(WatchMode.successOnly).watched().checkExists().forPath(path).event().thenAccept(event -> {
                System.out.println(event.getType());
                System.out.println(event);
            });
        }
    });
}
 
Example #19
Source File: AsyncExamples.java    From curator with Apache License 2.0 6 votes vote down vote up
public static void createThenWatch(CuratorFramework client, String path)
{
    AsyncCuratorFramework async = AsyncCuratorFramework.wrap(client);   // normally you'd wrap early in your app and reuse the instance

    // this example shows to asynchronously use watchers for both event
    // triggering and connection problems. If you don't need to be notified
    // of connection problems, use the simpler approach shown in createThenWatchSimple()

    // create a node at the given path with the given payload asynchronously
    // then watch the created node
    async.create().forPath(path).whenComplete((name, exception) -> {
        if ( exception != null )
        {
            // there was a problem creating the node
            exception.printStackTrace();
        }
        else
        {
            handleWatchedStage(async.watched().checkExists().forPath(path).event());
        }
    });
}
 
Example #20
Source File: TestAddWatch.java    From curator with Apache License 2.0 6 votes vote down vote up
@Test
public void testPersistentRecursiveWatch() throws Exception
{
    try ( CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)) )
    {
        client.start();
        client.blockUntilConnected();

        CountDownLatch latch = new CountDownLatch(5);
        Watcher watcher = event -> latch.countDown();
        AsyncCuratorFramework async = AsyncCuratorFramework.wrap(client);
        async.addWatch().withMode(AddWatchMode.PERSISTENT_RECURSIVE).usingWatcher(watcher).forPath("/test").toCompletableFuture().get();

        client.create().forPath("/test");
        client.create().forPath("/test/a");
        client.create().forPath("/test/a/b");
        client.create().forPath("/test/a/b/c");
        client.create().forPath("/test/a/b/c/d");

        Assert.assertTrue(timing.awaitLatch(latch));
    }
}
 
Example #21
Source File: PersonModelSpec.java    From curator with Apache License 2.0 5 votes vote down vote up
public PersonModelSpec(AsyncCuratorFramework client)
{
    this.client = client;

    JacksonModelSerializer<PersonModel> serializer = JacksonModelSerializer.build(PersonModel.class);
    ZPath path = ZPath.parseWithIds("/example/{id}/path/{id}");
    modelSpec = ModelSpec.builder(path, serializer).build();
}
 
Example #22
Source File: ModeledCuratorExamples.java    From curator with Apache License 2.0 5 votes vote down vote up
public static ModeledFramework<PersonModel> wrap(AsyncCuratorFramework client)
{
    JacksonModelSerializer<PersonModel> serializer = JacksonModelSerializer.build(PersonModel.class);

    // build a model specification - you can pre-build all the model specifications for your app at startup
    ModelSpec<PersonModel> modelSpec = ModelSpec.builder(ZPath.parse("/example/path"), serializer).build();

    // wrap a CuratorFramework instance so that it can be used "modeled".
    // do this once and re-use the returned ModeledFramework instance.
    // ModeledFramework instances are tied to a given path
    return ModeledFramework.wrap(client, modelSpec);
}
 
Example #23
Source File: TestCompatibility.java    From curator with Apache License 2.0 5 votes vote down vote up
@Test(expectedExceptions = IllegalStateException.class)
public void testPersistentWatchesNotAvailableAsync()
{
    try ( CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)) )
    {
        client.start();

        AsyncCuratorFramework async = AsyncCuratorFramework.wrap(client);
        async.addWatch().forPath("/foo");
    }
}
 
Example #24
Source File: TestFramework.java    From curator with Apache License 2.0 5 votes vote down vote up
@Test
public void testBackgroundDeleteWithChildren() throws Exception
{
    CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1));
    client.start();
    try
    {
        client.getCuratorListenable().addListener
            ((client1, event) ->
            {
                if ( event.getType() == CuratorEventType.DELETE )
                {
                    Assert.assertEquals(event.getPath(), "/one/two");
                    ((CountDownLatch)event.getContext()).countDown();
                }
            });

        CountDownLatch latch = new CountDownLatch(1);
        AsyncCuratorFramework async = AsyncCuratorFramework.wrap(client);
        async.create().withOptions(EnumSet.of(CreateOption.createParentsIfNeeded)).forPath("/one/two/three/four").thenRun(() ->
            async.delete().withOptions(EnumSet.of(DeleteOption.deletingChildrenIfNeeded)).forPath("/one/two").handle((v, e) -> {
                Assert.assertNull(v);
                Assert.assertNull(e);
                latch.countDown();
                return null;
            })
        );
        Assert.assertTrue(latch.await(10, TimeUnit.SECONDS));
        Assert.assertNull(client.checkExists().forPath("/one/two"));
    }
    finally
    {
        CloseableUtils.closeQuietly(client);
    }
}
 
Example #25
Source File: ModelTypedExamplesManualTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void givenPath_whenStoreAModel_thenNodesAreCreated()
    throws InterruptedException {

    ModelSpec<HostConfig> mySpec = ModelSpec
        .builder(ZPath.parseWithIds("/config/dev"),
            JacksonModelSerializer.build(HostConfig.class))
        .build();

    try (CuratorFramework client = newClient()) {
        client.start();
        AsyncCuratorFramework async = AsyncCuratorFramework.wrap(client);
        ModeledFramework<HostConfig> modeledClient = ModeledFramework
            .wrap(async, mySpec);

        modeledClient.set(new HostConfig("host-name", 8080));

        modeledClient.read()
            .whenComplete((value, e) -> {
                if (e != null) {
                    fail("Cannot read host config", e);
                } else {
                    assertThat(value).isNotNull();
                    assertThat(value.getHostname()).isEqualTo("host-name");
                    assertThat(value.getPort()).isEqualTo(8080);
                }

            });
    }

}
 
Example #26
Source File: TestAddWatch.java    From curator with Apache License 2.0 5 votes vote down vote up
@Test
public void testPersistentRecursiveDefaultWatch() throws Exception
{
    CountDownLatch latch = new CountDownLatch(6);   // 5 creates plus the initial sync
    ZookeeperFactory zookeeperFactory = (connectString, sessionTimeout, watcher, canBeReadOnly) -> {
        Watcher actualWatcher = event -> {
            watcher.process(event);
            latch.countDown();
        };
        return new ZooKeeper(connectString, sessionTimeout, actualWatcher);
    };
    try (CuratorFramework client = CuratorFrameworkFactory.builder().connectString(server.getConnectString()).retryPolicy(new RetryOneTime(1)).zookeeperFactory(zookeeperFactory).build() )
    {
        client.start();
        client.blockUntilConnected();

        AsyncCuratorFramework async = AsyncCuratorFramework.wrap(client);
        async.addWatch().withMode(AddWatchMode.PERSISTENT_RECURSIVE).forPath("/test");

        client.create().forPath("/test");
        client.create().forPath("/test/a");
        client.create().forPath("/test/a/b");
        client.create().forPath("/test/a/b/c");
        client.create().forPath("/test/a/b/c/d");

        Assert.assertTrue(timing.awaitLatch(latch));
    }
}
 
Example #27
Source File: ConfigurationManagementManualTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void givenPath_whenWatchAKeyAndStoreAValue_thenWatcherIsTriggered()
    throws Exception {
    try (CuratorFramework client = newClient()) {
        client.start();
        AsyncCuratorFramework async = AsyncCuratorFramework.wrap(client);
        String key = getKey();
        String expected = "my_value";

        // Create key structure
        async.create()
            .forPath(key);

        List<String> changes = new ArrayList<>();

        // Watch data value
        async.watched()
            .getData()
            .forPath(key)
            .event()
            .thenAccept(watchedEvent -> {
                try {
                    changes.add(new String(client.getData()
                        .forPath(watchedEvent.getPath())));
                } catch (Exception e) {
                    // fail ...
                }
            });

        // Set data value for our key
        async.setData()
            .forPath(key, expected.getBytes());

        await().until(() -> assertThat(changes.size() > 0).isTrue());
    }
}
 
Example #28
Source File: TestFramework.java    From curator with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateParentContainers() throws Exception
{
    if ( !checkForContainers() )
    {
        return;
    }

    CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder();
    CuratorFramework client = builder.connectString(server.getConnectString()).retryPolicy(new RetryOneTime(1)).build();
    try
    {
        client.start();
        AsyncCuratorFramework async = AsyncCuratorFramework.wrap(client);
        async.create().withOptions(EnumSet.of(CreateOption.createParentsAsContainers)).forPath("/one/two/three", "foo".getBytes()).toCompletableFuture().get();
        byte[] data = async.getData().forPath("/one/two/three").toCompletableFuture().get();
        Assert.assertEquals(data, "foo".getBytes());

        async.delete().forPath("/one/two/three").toCompletableFuture().get();
        new Timing().sleepABit();

        Assert.assertNull(async.checkExists().forPath("/one/two").toCompletableFuture().get());
        new Timing().sleepABit();
        Assert.assertNull(async.checkExists().forPath("/one").toCompletableFuture().get());
    }
    finally
    {
        CloseableUtils.closeQuietly(client);
    }
}
 
Example #29
Source File: TestFramework.java    From curator with Apache License 2.0 5 votes vote down vote up
@Test
public void testNamespaceWithWatcher() throws Exception
{
    CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder();
    CuratorFramework client = builder.connectString(server.getConnectString()).namespace("aisa").retryPolicy(new RetryOneTime(1)).build();
    client.start();
    try
    {
        AsyncCuratorFramework async = AsyncCuratorFramework.wrap(client);
        BlockingQueue<String> queue = new LinkedBlockingQueue<String>();
        async.create().forPath("/base").
            thenRun(() -> async.watched().getChildren().forPath("/base").event().handle((event, x) -> {
                try
                {
                    queue.put(event.getPath());
                }
                catch ( InterruptedException e )
                {
                    throw new Error(e);
                }
                return null;
            }))
            .thenRun(() -> async.create().forPath("/base/child"));

        String path = queue.take();
        Assert.assertEquals(path, "/base");
    }
    finally
    {
        CloseableUtils.closeQuietly(client);
    }
}
 
Example #30
Source File: TestFramework.java    From curator with Apache License 2.0 5 votes vote down vote up
@Test
public void testBackgroundGetDataWithWatch() throws Exception
{
    final byte[] data1 = {1, 2, 3};
    final byte[] data2 = {4, 5, 6, 7};

    CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1));
    client.start();
    try
    {
        AsyncCuratorFramework async = AsyncCuratorFramework.wrap(client);
        async.create().forPath("/test", data1).toCompletableFuture().get();

        CountDownLatch watchedLatch = new CountDownLatch(1);
        CountDownLatch backgroundLatch = new CountDownLatch(1);
        AsyncStage<byte[]> stage = async.watched().getData().forPath("/test");
        stage.event().handle((event, x) -> {
            Assert.assertEquals(event.getPath(), "/test");
            watchedLatch.countDown();
            return null;
        });
        stage.handle((d, x) -> {
            Assert.assertEquals(d, data1);
            backgroundLatch.countDown();
            return null;
        });

        Assert.assertTrue(backgroundLatch.await(10, TimeUnit.SECONDS));

        async.setData().forPath("/test", data2);
        Assert.assertTrue(watchedLatch.await(10, TimeUnit.SECONDS));
        byte[] checkData = async.getData().forPath("/test").toCompletableFuture().get();
        Assert.assertEquals(checkData, data2);
    }
    finally
    {
        CloseableUtils.closeQuietly(client);
    }
}