org.apache.curator.utils.CloseableUtils Java Examples
The following examples show how to use
org.apache.curator.utils.CloseableUtils.
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: TestFrameworkEdges.java From xian with Apache License 2.0 | 6 votes |
@Test public void testFailure() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), 100, 100, new RetryOneTime(1)); client.start(); try { client.checkExists().forPath("/hey"); client.checkExists().inBackground().forPath("/hey"); server.stop(); client.checkExists().forPath("/hey"); Assert.fail(); } catch ( KeeperException.ConnectionLossException e ) { // correct } finally { CloseableUtils.closeQuietly(client); } }
Example #2
Source File: TestNamespaceFacade.java From xian with Apache License 2.0 | 6 votes |
@Test public void testCache() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); try { client.start(); Assert.assertSame(client.usingNamespace("foo"), client.usingNamespace("foo")); Assert.assertNotSame(client.usingNamespace("foo"), client.usingNamespace("bar")); } finally { CloseableUtils.closeQuietly(client); } }
Example #3
Source File: TestFramework.java From xian with Apache License 2.0 | 6 votes |
@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 { client.create().creatingParentsIfNeeded().forPath("/one/two/three", "foo".getBytes()); byte[] data = client.getData().forPath("/one/two/three"); Assert.assertEquals(data, "foo".getBytes()); client.create().creatingParentsIfNeeded().forPath("/one/two/another", "bar".getBytes()); data = client.getData().forPath("/one/two/another"); Assert.assertEquals(data, "bar".getBytes()); } finally { CloseableUtils.closeQuietly(client); } }
Example #4
Source File: TestNamespaceFacade.java From xian with Apache License 2.0 | 6 votes |
@Test public void testGetNamespace() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); CuratorFramework client2 = CuratorFrameworkFactory.builder().namespace("snafu").retryPolicy(new RetryOneTime(1)).connectString("").build(); try { client.start(); CuratorFramework fooClient = client.usingNamespace("foo"); CuratorFramework barClient = client.usingNamespace("bar"); Assert.assertEquals(client.getNamespace(), ""); Assert.assertEquals(client2.getNamespace(), "snafu"); Assert.assertEquals(fooClient.getNamespace(), "foo"); Assert.assertEquals(barClient.getNamespace(), "bar"); } finally { CloseableUtils.closeQuietly(client2); CloseableUtils.closeQuietly(client); } }
Example #5
Source File: ZookeeperSyncToNacosServiceImpl.java From nacos-sync with Apache License 2.0 | 6 votes |
@Override public boolean delete(TaskDO taskDO) { try { CloseableUtils.closeQuietly(pathChildrenCacheMap.get(taskDO.getTaskId())); NamingService destNamingService = nacosServerHolder.get(taskDO.getDestClusterId(), null); if (nacosServiceNameMap.containsKey(taskDO.getTaskId())) { List<Instance> allInstances = destNamingService.getAllInstances(nacosServiceNameMap.get(taskDO.getTaskId())); for (Instance instance : allInstances) { if (needDelete(instance.getMetadata(), taskDO)) { destNamingService.deregisterInstance(instance.getServiceName(), instance.getIp(), instance.getPort()); } nacosServiceNameMap.remove(taskDO.getTaskId()); } } } catch (Exception e) { log.error("delete task from zookeeper to nacos was failed, taskId:{}", taskDO.getTaskId(), e); metricsManager.recordError(MetricsStatisticsType.DELETE_ERROR); return false; } return true; }
Example #6
Source File: TestWatcherIdentity.java From xian with Apache License 2.0 | 6 votes |
@Test public void testSimpleId() { CountCuratorWatcher curatorWatcher = new CountCuratorWatcher(); CountZKWatcher zkWatcher = new CountZKWatcher(); CuratorFrameworkImpl client = (CuratorFrameworkImpl)CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); try { Assert.assertSame(client.getNamespaceWatcherMap().getNamespaceWatcher(curatorWatcher), client.getNamespaceWatcherMap().getNamespaceWatcher(curatorWatcher)); Assert.assertSame(client.getNamespaceWatcherMap().getNamespaceWatcher(zkWatcher), client.getNamespaceWatcherMap().getNamespaceWatcher(zkWatcher)); Assert.assertNotSame(client.getNamespaceWatcherMap().getNamespaceWatcher(curatorWatcher), client.getNamespaceWatcherMap().getNamespaceWatcher(zkWatcher)); } finally { CloseableUtils.closeQuietly(client); } }
Example #7
Source File: TestFramework.java From xian with Apache License 2.0 | 6 votes |
@Test public void testEnsurePathWithNamespace() throws Exception { final String namespace = "jz"; CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder(); CuratorFramework client = builder.connectString(server.getConnectString()).retryPolicy(new RetryOneTime(1)).namespace(namespace).build(); client.start(); try { EnsurePath ensurePath = new EnsurePath("/pity/the/fool"); ensurePath.ensure(client.getZookeeperClient()); Assert.assertNull(client.getZookeeperClient().getZooKeeper().exists("/jz/pity/the/fool", false)); ensurePath = client.newNamespaceAwareEnsurePath("/pity/the/fool"); ensurePath.ensure(client.getZookeeperClient()); Assert.assertNotNull(client.getZookeeperClient().getZooKeeper().exists("/jz/pity/the/fool", false)); } finally { CloseableUtils.closeQuietly(client); } }
Example #8
Source File: NacosSyncToZookeeperServiceImpl.java From nacos-sync with Apache License 2.0 | 6 votes |
@Override public boolean delete(TaskDO taskDO) { try { NamingService sourceNamingService = nacosServerHolder.get(taskDO.getSourceClusterId(), taskDO.getGroupName()); EventListener eventListener = nacosListenerMap.remove(taskDO.getTaskId()); PathChildrenCache pathChildrenCache = pathChildrenCacheMap.get(taskDO.getTaskId()); sourceNamingService.unsubscribe(taskDO.getServiceName(), eventListener); CloseableUtils.closeQuietly(pathChildrenCache); Set<String> instanceUrlSet = instanceBackupMap.get(taskDO.getTaskId()); CuratorFramework client = zookeeperServerHolder.get(taskDO.getDestClusterId(), taskDO.getGroupName()); for (String instanceUrl : instanceUrlSet) { client.delete().quietly().forPath(instanceUrl); } } catch (Exception e) { log.error("delete task from nacos to zk was failed, taskId:{}", taskDO.getTaskId(), e); metricsManager.recordError(MetricsStatisticsType.DELETE_ERROR); return false; } return true; }
Example #9
Source File: TestTempFramework.java From xian with Apache License 2.0 | 6 votes |
@Test public void testBasic() throws Exception { CuratorTempFramework client = CuratorFrameworkFactory.builder().connectString(server.getConnectString()).retryPolicy(new RetryOneTime(1)).buildTemp(); try { client.inTransaction().create().forPath("/foo", "data".getBytes()).and().commit(); byte[] bytes = client.getData().forPath("/foo"); Assert.assertEquals(bytes, "data".getBytes()); } finally { CloseableUtils.closeQuietly(client); } }
Example #10
Source File: TestSharedCount.java From xian with Apache License 2.0 | 6 votes |
@Test public void testSimple() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); SharedCount count = new SharedCount(client, "/count", 0); try { client.start(); count.start(); Assert.assertTrue(count.trySetCount(1)); Assert.assertTrue(count.trySetCount(2)); Assert.assertTrue(count.trySetCount(10)); Assert.assertEquals(count.getCount(), 10); } finally { CloseableUtils.closeQuietly(count); CloseableUtils.closeQuietly(client); } }
Example #11
Source File: TestEnsureContainers.java From xian with Apache License 2.0 | 6 votes |
@Test public void testSingleExecution() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); try { client.start(); EnsureContainers ensureContainers = new EnsureContainers(client, "/one/two/three"); ensureContainers.ensure(); Assert.assertNotNull(client.checkExists().forPath("/one/two/three")); client.delete().forPath("/one/two/three"); ensureContainers.ensure(); Assert.assertNull(client.checkExists().forPath("/one/two/three")); } finally { CloseableUtils.closeQuietly(client); } }
Example #12
Source File: TestDistributedAtomicLong.java From xian with Apache License 2.0 | 6 votes |
@Test public void testCompareAndSetWithFreshInstance() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); try { client.start(); DistributedAtomicLong dal = new DistributedAtomicLong(client, "/counter", new RetryOneTime(1)); AtomicValue<Long> result = dal.compareAndSet(0L, 1L); Assert.assertFalse(result.succeeded()); Assert.assertTrue(dal.initialize(0L)); result = dal.compareAndSet(0L, 1L); Assert.assertTrue(result.succeeded()); Assert.assertFalse(dal.initialize(0L)); } finally { CloseableUtils.closeQuietly(client); } }
Example #13
Source File: BaseTestTreeCache.java From xian with Apache License 2.0 | 6 votes |
@Override @AfterMethod public void teardown() throws Exception { try { try { Assert.assertFalse(hadBackgroundException.get(), "Background exceptions were thrown, see stderr for details"); assertNoMoreEvents(); } finally { CloseableUtils.closeQuietly(cache); CloseableUtils.closeQuietly(client); } } finally { super.teardown(); } }
Example #14
Source File: DiscoveryExample.java From xian with Apache License 2.0 | 6 votes |
private static void listInstances(ServiceDiscovery<InstanceDetails> serviceDiscovery) throws Exception { // This shows how to query all the instances in group discovery try { Collection<String> serviceNames = serviceDiscovery.queryForNames(); System.out.println(serviceNames.size() + " type(s)"); for ( String serviceName : serviceNames ) { Collection<ServiceInstance<InstanceDetails>> instances = serviceDiscovery.queryForInstances(serviceName); System.out.println(serviceName); for ( ServiceInstance<InstanceDetails> instance : instances ) { outputInstance(instance); } } } finally { CloseableUtils.closeQuietly(serviceDiscovery); } }
Example #15
Source File: TestBlockUntilConnected.java From xian with Apache License 2.0 | 6 votes |
/** * Test the case where we are not currently connected and time out before a * connection becomes available. */ @Test public void testBlockUntilConnectedConnectTimeout() { //Kill the server CloseableUtils.closeQuietly(server); CuratorFramework client = CuratorFrameworkFactory.builder(). connectString(server.getConnectString()). retryPolicy(new RetryOneTime(1)). build(); try { client.start(); Assert.assertFalse(client.blockUntilConnected(5, TimeUnit.SECONDS), "Connected"); } catch ( InterruptedException e ) { Assert.fail("Unexpected interruption"); } finally { CloseableUtils.closeQuietly(client); } }
Example #16
Source File: TestInterProcessReadWriteLock.java From xian with Apache License 2.0 | 6 votes |
@Test public void testDowngrading() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); try { client.start(); InterProcessReadWriteLock lock = new InterProcessReadWriteLock(client, "/lock"); lock.writeLock().acquire(); Assert.assertTrue(lock.readLock().acquire(5, TimeUnit.SECONDS)); lock.writeLock().release(); lock.readLock().release(); } finally { CloseableUtils.closeQuietly(client); } }
Example #17
Source File: TestNamespaceFacade.java From xian with Apache License 2.0 | 6 votes |
@Test public void testBasic() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); try { client.start(); client.create().forPath("/one"); Assert.assertNotNull(client.getZookeeperClient().getZooKeeper().exists("/one", false)); client.usingNamespace("space").create().forPath("/one"); Assert.assertNotNull(client.getZookeeperClient().getZooKeeper().exists("/space", false)); client.usingNamespace("name").create().forPath("/one"); Assert.assertNotNull(client.getZookeeperClient().getZooKeeper().exists("/name", false)); Assert.assertNotNull(client.getZookeeperClient().getZooKeeper().exists("/name/one", false)); } finally { CloseableUtils.closeQuietly(client); } }
Example #18
Source File: TestFramework.java From xian 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 { client.create().forPath("/head"); for ( int i = 0; i < 10; ++i ) { client.create().withMode(CreateMode.EPHEMERAL_SEQUENTIAL).forPath("/head/child"); } List<String> children = client.getChildren().forPath("/head"); Assert.assertEquals(children.size(), 10); } finally { CloseableUtils.closeQuietly(client); } }
Example #19
Source File: TestFramework.java From xian with Apache License 2.0 | 6 votes |
@Test public void testDelete() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client.start(); try { client.create().forPath("/head"); Assert.assertNotNull(client.checkExists().forPath("/head")); client.delete().forPath("/head"); Assert.assertNull(client.checkExists().forPath("/head")); } finally { CloseableUtils.closeQuietly(client); } }
Example #20
Source File: ConnectionState.java From xian with Apache License 2.0 | 6 votes |
@Override public void close() throws IOException { log.debug("Closing"); CloseableUtils.closeQuietly(ensembleProvider); try { zooKeeper.closeAndClear(); } catch ( Exception e ) { ThreadUtils.checkInterrupted(e); throw new IOException(e); } finally { isConnected.set(false); } }
Example #21
Source File: TestBlockUntilConnected.java From xian with Apache License 2.0 | 6 votes |
/** * Test the case where we are not currently connected and never have been */ @Test public void testBlockUntilConnectedCurrentlyNeverConnected() { CuratorFramework client = CuratorFrameworkFactory.builder(). connectString(server.getConnectString()). retryPolicy(new RetryOneTime(1)). build(); try { client.start(); Assert.assertTrue(client.blockUntilConnected(5, TimeUnit.SECONDS), "Not connected"); } catch ( InterruptedException e ) { Assert.fail("Unexpected interruption"); } finally { CloseableUtils.closeQuietly(client); } }
Example #22
Source File: TestFrameworkEdges.java From xian with Apache License 2.0 | 6 votes |
@Test public void testGetAclNoStat() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); client.start(); try { try { client.getACL().forPath("/"); } catch ( NullPointerException e ) { Assert.fail(); } } finally { CloseableUtils.closeQuietly(client); } }
Example #23
Source File: ServiceCacheLeakTester.java From xian with Apache License 2.0 | 6 votes |
public static void main(String[] args) throws Exception { TestingServer testingServer = new TestingServer(); final CuratorFramework curatorFramework = CuratorFrameworkFactory.newClient(testingServer.getConnectString(), new RetryOneTime(1)); try { curatorFramework.start(); doWork(curatorFramework); System.gc(); System.out.println("Done - get dump"); Thread.currentThread().join(); } finally { CloseableUtils.closeQuietly(curatorFramework); CloseableUtils.closeQuietly(testingServer); } }
Example #24
Source File: TestPersistentNode.java From xian with Apache License 2.0 | 6 votes |
@Test public void testQuickCloseNodeExists() throws Exception { Timing timing = new Timing(); PersistentNode pen = null; CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); try { client.start(); client.create().creatingParentsIfNeeded().forPath("/test/one/two"); pen = new PersistentNode(client, CreateMode.PERSISTENT, false, "/test/one/two", new byte[0]); pen.start(); pen.close(); timing.sleepABit(); Assert.assertNull(client.checkExists().forPath("/test/one/two")); } finally { CloseableUtils.closeQuietly(pen); CloseableUtils.closeQuietly(client); } }
Example #25
Source File: TestLeaderLatch.java From xian with Apache License 2.0 | 5 votes |
@Test public void testResetRace() throws Exception { Timing timing = new Timing(); LeaderLatch latch = null; CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); try { client.start(); latch = new LeaderLatch(client, PATH_NAME); latch.debugResetWaitLatch = new CountDownLatch(1); latch.start(); // will call reset() latch.reset(); // should not result in two nodes timing.sleepABit(); latch.debugResetWaitLatch.countDown(); timing.sleepABit(); Assert.assertEquals(client.getChildren().forPath(PATH_NAME).size(), 1); } finally { CloseableUtils.closeQuietly(latch); CloseableUtils.closeQuietly(client); } }
Example #26
Source File: TestInterProcessReadWriteLock.java From xian with Apache License 2.0 | 5 votes |
@Test public void testSetNodeData() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); try { client.start(); final byte[] nodeData = new byte[] { 1, 2, 3, 4 }; InterProcessReadWriteLock lock = new InterProcessReadWriteLock(client, "/lock", nodeData); // mutate passed-in node data, lock has made copy nodeData[0] = 5; lock.writeLock().acquire(); List<String> children = client.getChildren().forPath("/lock"); Assert.assertEquals(1, children.size()); byte dataInZk[] = client.getData().forPath("/lock/" + children.get(0)); Assert.assertNotNull(dataInZk); Assert.assertEquals(new byte[] { 1, 2, 3, 4 }, dataInZk); lock.writeLock().release(); } finally { CloseableUtils.closeQuietly(client); } }
Example #27
Source File: TestLeaderSelectorWithExecutor.java From xian with Apache License 2.0 | 5 votes |
@Test public void test() throws Exception { Timing timing = new Timing(); LeaderSelector leaderSelector = null; CuratorFramework client = CuratorFrameworkFactory.builder() .retryPolicy(new ExponentialBackoffRetry(100, 3)) .connectString(server.getConnectString()) .sessionTimeoutMs(timing.session()) .connectionTimeoutMs(timing.connection()) .build(); try { client.start(); MyLeaderSelectorListener listener = new MyLeaderSelectorListener(); ExecutorService executorPool = Executors.newFixedThreadPool(20); leaderSelector = new LeaderSelector(client, "/test", threadFactory, executorPool, listener); leaderSelector.autoRequeue(); leaderSelector.start(); timing.sleepABit(); Assert.assertEquals(listener.getLeaderCount(), 1); } finally { CloseableUtils.closeQuietly(leaderSelector); CloseableUtils.closeQuietly(client); } }
Example #28
Source File: TestDistributedPriorityQueue.java From xian with Apache License 2.0 | 5 votes |
@Test public void testMinItemsBeforeRefresh() throws Exception { DistributedPriorityQueue<Integer> queue = null; CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client.start(); try { final int minItemsBeforeRefresh = 3; BlockingQueueConsumer<Integer> consumer = new BlockingQueueConsumer<Integer>(Mockito.mock(ConnectionStateListener.class)); queue = QueueBuilder.builder(client, consumer, new IntSerializer(), "/test").buildPriorityQueue(minItemsBeforeRefresh); queue.start(); for ( int i = 0; i < 10; ++i ) { queue.put(i, 10 + i); } Assert.assertEquals(consumer.take(1, TimeUnit.SECONDS), new Integer(0)); queue.put(1000, 1); // lower priority int count = 0; while ( consumer.take(1, TimeUnit.SECONDS) < 1000 ) { ++count; } Assert.assertTrue(Math.abs(minItemsBeforeRefresh - count) < minItemsBeforeRefresh, String.format("Diff: %d - min: %d", Math.abs(minItemsBeforeRefresh - count), minItemsBeforeRefresh)); // allows for some slack - testing that within a slop value the newly inserted item with lower priority comes out } finally { CloseableUtils.closeQuietly(queue); CloseableUtils.closeQuietly(client); } }
Example #29
Source File: ZookeeperRuleConfigSource.java From ratelimiter4j with Apache License 2.0 | 5 votes |
private void initialClient() { if (!isInitialized.compareAndSet(false, true)) { return; } if (client == null && StringUtils.isEmpty(address)) { throw new RuntimeException("zookeeper server address is not set."); } boolean connected = false; try { if (client == null) { RetryPolicy retryPolicy = new ExponentialBackoffRetry(baseSleepTimeMs, maxRetries); client = CuratorFrameworkFactory.builder().connectString(address).retryPolicy(retryPolicy) .connectionTimeoutMs(connectionTimeout).sessionTimeoutMs(sessionTimeout).build(); } client.start(); connected = client.blockUntilConnected(connectionTimeout, TimeUnit.MILLISECONDS); if (!connected) { throw new RuntimeException("connect zookeeper failed."); } } catch (Exception e) { CloseableUtils.closeQuietly(client); isInitialized.compareAndSet(true, false); throw new RuntimeException("init zookeeper client error.", e); } }
Example #30
Source File: TestSimpleDistributedQueue.java From xian with Apache License 2.0 | 5 votes |
private void closeAll(CuratorFramework[] clients) { if ( clients != null ) { for ( CuratorFramework c : clients ) { CloseableUtils.closeQuietly(c); } } }