Java Code Examples for org.apache.curator.x.async.AsyncCuratorFramework#wrap()
The following examples show how to use
org.apache.curator.x.async.AsyncCuratorFramework#wrap() .
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: AsyncExamples.java From curator with Apache License 2.0 | 6 votes |
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 2
Source File: TestAddWatch.java From curator with Apache License 2.0 | 6 votes |
@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 3
Source File: TestFramework.java From curator with Apache License 2.0 | 6 votes |
@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 4
Source File: AsyncExamples.java From curator with Apache License 2.0 | 6 votes |
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 5
Source File: TestFramework.java From curator with Apache License 2.0 | 6 votes |
@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 6
Source File: TestFramework.java From curator with Apache License 2.0 | 6 votes |
@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 7
Source File: TestFramework.java From curator with Apache License 2.0 | 6 votes |
@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 8
Source File: TestFramework.java From curator with Apache License 2.0 | 6 votes |
@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 9
Source File: ConfigurationManagementManualTest.java From tutorials with MIT License | 6 votes |
@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 10
Source File: TestFrameworkBackground.java From curator with Apache License 2.0 | 6 votes |
/** * 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 11
Source File: ConnectionManagementManualTest.java From tutorials with MIT License | 6 votes |
@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 12
Source File: TestFramework.java From curator with Apache License 2.0 | 5 votes |
@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 13
Source File: TestFramework.java From curator with Apache License 2.0 | 5 votes |
@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 14
Source File: TestFramework.java From curator with Apache License 2.0 | 5 votes |
@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 15
Source File: TestFramework.java From curator with Apache License 2.0 | 5 votes |
@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); } }
Example 16
Source File: TestCompatibility.java From curator with Apache License 2.0 | 5 votes |
@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 17
Source File: TestFrameworkBackground.java From curator with Apache License 2.0 | 4 votes |
@Test public void testListenerConnectedAtStart() throws Exception { server.stop(); Timing timing = new Timing(2); CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryNTimes(0, 0)); try { client.start(); AsyncCuratorFramework async = AsyncCuratorFramework.wrap(client); final CountDownLatch connectedLatch = new CountDownLatch(1); final AtomicBoolean firstListenerAction = new AtomicBoolean(true); final AtomicReference<ConnectionState> firstListenerState = new AtomicReference<>(); ConnectionStateListener listener = (client1, newState) -> { if ( firstListenerAction.compareAndSet(true, false) ) { firstListenerState.set(newState); System.out.println("First listener state is " + newState); } if ( newState == ConnectionState.CONNECTED ) { connectedLatch.countDown(); } }; client.getConnectionStateListenable().addListener(listener); // due to CURATOR-72, this was causing a LOST event to precede the CONNECTED event async.create().forPath("/foo"); server.restart(); Assert.assertTrue(timing.awaitLatch(connectedLatch)); Assert.assertFalse(firstListenerAction.get()); ConnectionState firstconnectionState = firstListenerState.get(); Assert.assertEquals(firstconnectionState, ConnectionState.CONNECTED, "First listener state MUST BE CONNECTED but is " + firstconnectionState); } finally { CloseableUtils.closeQuietly(client); } }
Example 18
Source File: SubPubTest.java From curator with Apache License 2.0 | 4 votes |
public SubPubTest() throws Exception { this.testingServer = new TestingServer(); client = AsyncCuratorFramework.wrap(CuratorFrameworkFactory.newClient(testingServer.getConnectString(), new RetryOneTime(1))); executorService = Executors.newSingleThreadScheduledExecutor(); }
Example 19
Source File: TestFrameworkBackground.java From curator with Apache License 2.0 | 4 votes |
@Test public void testErrorListener() throws Exception { //The first call to the ACL provider will return a reasonable //value. The second will throw an error. This is because the ACL //provider is accessed prior to the backgrounding call. final AtomicBoolean aclProviderCalled = new AtomicBoolean(false); ACLProvider badAclProvider = new ACLProvider() { @Override public List<ACL> getDefaultAcl() { if(aclProviderCalled.getAndSet(true)) { throw new UnsupportedOperationException(); } else { return new ArrayList<>(); } } @Override public List<ACL> getAclForPath(String path) { if(aclProviderCalled.getAndSet(true)) { throw new UnsupportedOperationException(); } else { return new ArrayList<>(); } } }; CuratorFramework client = CuratorFrameworkFactory.builder() .connectString(server.getConnectString()) .retryPolicy(new RetryOneTime(1)) .aclProvider(badAclProvider) .build(); try { client.start(); AsyncCuratorFramework async = AsyncCuratorFramework.wrap(client); final CountDownLatch errorLatch = new CountDownLatch(1); UnhandledErrorListener listener = (message, e) -> { if ( e instanceof UnsupportedOperationException ) { errorLatch.countDown(); } }; async.with(listener).create().forPath("/foo"); Assert.assertTrue(new Timing().awaitLatch(errorLatch)); } finally { CloseableUtils.closeQuietly(client); } }
Example 20
Source File: AsyncExamples.java From curator with Apache License 2.0 | 4 votes |
public static AsyncCuratorFramework wrap(CuratorFramework client) { // wrap a CuratorFramework instance so that it can be used async. // do this once and re-use the returned AsyncCuratorFramework instance return AsyncCuratorFramework.wrap(client); }