Java Code Examples for org.apache.curator.utils.CloseableUtils

The following examples show how to use org.apache.curator.utils.CloseableUtils. These examples are extracted from open source projects. 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 Project: xian   Source File: TestNamespaceFacade.java    License: Apache License 2.0 6 votes vote down vote up
@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 2
@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 3
@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 4
Source Project: xian   Source File: TestFramework.java    License: Apache License 2.0 6 votes vote down vote up
@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 5
Source Project: xian   Source File: TestWatcherIdentity.java    License: Apache License 2.0 6 votes vote down vote up
@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 6
Source Project: xian   Source File: TestNamespaceFacade.java    License: Apache License 2.0 6 votes vote down vote up
@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 7
Source Project: xian   Source File: TestFramework.java    License: 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
    {
        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 8
Source Project: xian   Source File: TestTempFramework.java    License: Apache License 2.0 6 votes vote down vote up
@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 9
Source Project: xian   Source File: TestSharedCount.java    License: Apache License 2.0 6 votes vote down vote up
@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 10
Source Project: xian   Source File: TestEnsureContainers.java    License: Apache License 2.0 6 votes vote down vote up
@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 11
Source Project: xian   Source File: TestDistributedAtomicLong.java    License: Apache License 2.0 6 votes vote down vote up
@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 12
Source Project: xian   Source File: TestPersistentNode.java    License: Apache License 2.0 6 votes vote down vote up
@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 13
Source Project: xian   Source File: BaseTestTreeCache.java    License: Apache License 2.0 6 votes vote down vote up
@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 Project: xian   Source File: DiscoveryExample.java    License: Apache License 2.0 6 votes vote down vote up
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 Project: xian   Source File: ServiceCacheLeakTester.java    License: Apache License 2.0 6 votes vote down vote up
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 16
Source Project: xian   Source File: TestFrameworkEdges.java    License: Apache License 2.0 6 votes vote down vote up
@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 17
Source Project: xian   Source File: TestBlockUntilConnected.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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 18
Source Project: xian   Source File: ConnectionState.java    License: Apache License 2.0 6 votes vote down vote up
@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 19
Source Project: xian   Source File: TestFramework.java    License: Apache License 2.0 6 votes vote down vote up
@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 Project: xian   Source File: TestFramework.java    License: 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
    {
        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 21
Source Project: xian   Source File: TestNamespaceFacade.java    License: Apache License 2.0 6 votes vote down vote up
@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 22
Source Project: xian   Source File: TestInterProcessReadWriteLock.java    License: Apache License 2.0 6 votes vote down vote up
@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 23
Source Project: xian   Source File: TestBlockUntilConnected.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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 24
Source Project: xian   Source File: TestFrameworkEdges.java    License: Apache License 2.0 6 votes vote down vote up
@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 25
Source Project: xian   Source File: TestServiceProvider.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testBasic() throws Exception
{
    List<Closeable> closeables = Lists.newArrayList();
    try
    {
        CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1));
        closeables.add(client);
        client.start();

        ServiceInstance<String> instance = ServiceInstance.<String>builder().payload("thing").name("test").port(10064).build();
        ServiceDiscovery<String> discovery = ServiceDiscoveryBuilder.builder(String.class).basePath("/test").client(client).thisInstance(instance).build();
        closeables.add(discovery);
        discovery.start();

        ServiceProvider<String> provider = discovery.serviceProviderBuilder().serviceName("test").build();
        closeables.add(provider);
        provider.start();

        Assert.assertEquals(provider.getInstance(), instance);

        List<ServiceInstance<String>> list = Lists.newArrayList();
        list.add(instance);
        Assert.assertEquals(provider.getAllInstances(), list);
    }
    finally
    {
        Collections.reverse(closeables);
        for ( Closeable c : closeables )
        {
            CloseableUtils.closeQuietly(c);
        }
    }
}
 
Example 26
Source Project: mykit-delay   Source File: SimpleLeaderManager.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void stop() {
    if (isLatch.compareAndSet(true, false)) {
        try {
            BlockUtils.sleep(500);
            LOGGER.info("stop latch....");
            CloseableUtils.closeQuietly(leaderLatch);
            //CloseableUtils.closeQuietly(framework);
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            throw new RuntimeException(e);
        }
    }
}
 
Example 27
Source Project: sdmq   Source File: SimpleLeaderManager.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void stop() {
    if (isLatch.compareAndSet(true, false)) {
        try {
            BlockUtils.sleep(500);
            LOGGER.info("stop latch....");
            CloseableUtils.closeQuietly(leaderLatch);
            //CloseableUtils.closeQuietly(framework);
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            throw new RuntimeException(e);
        }
    }
}
 
Example 28
Source Project: xian   Source File: GroupMember.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Have thisId leave the group and stop caching membership
 */
@Override
public void close()
{
    CloseableUtils.closeQuietly(cache);
    CloseableUtils.closeQuietly(pen);
}
 
Example 29
Source Project: xian   Source File: TestServiceDiscovery.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testNoServerOnStart() throws Exception
{
    server.stop();
    List<Closeable> closeables = Lists.newArrayList();
    try
    {
        CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1));
        closeables.add(client);
        client.start();

        ServiceInstance<String> instance = ServiceInstance.<String>builder().payload("thing").name("test").port(10064).build();
        ServiceDiscovery<String> discovery = ServiceDiscoveryBuilder.builder(String.class).basePath("/test").client(client).thisInstance(instance).build();
        closeables.add(discovery);
        discovery.start();

        server.restart();
        Assert.assertEquals(discovery.queryForNames(), Collections.singletonList("test"));

        List<ServiceInstance<String>> list = Lists.newArrayList();
        list.add(instance);
        Assert.assertEquals(discovery.queryForInstances("test"), list);
    }
    finally
    {
        Collections.reverse(closeables);
        for ( Closeable c : closeables )
        {
            CloseableUtils.closeQuietly(c);
        }
    }
}
 
Example 30
Source Project: xian   Source File: TestFrameworkEdges.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testProtectedCreateNodeDeletion() throws Exception
{
    CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), 1, new RetryNTimes(0, 0));
    try
    {
        client.start();

        for ( int i = 0; i < 2; ++i )
        {
            CuratorFramework localClient = (i == 0) ? client : client.usingNamespace("nm");
            localClient.create().forPath("/parent");
            Assert.assertEquals(localClient.getChildren().forPath("/parent").size(), 0);

            CreateBuilderImpl createBuilder = (CreateBuilderImpl)localClient.create();
            createBuilder.failNextCreateForTesting = true;
            FindAndDeleteProtectedNodeInBackground.debugInsertError.set(true);
            try
            {
                createBuilder.withProtection().forPath("/parent/test");
                Assert.fail("failNextCreateForTesting should have caused a ConnectionLossException");
            }
            catch ( KeeperException.ConnectionLossException e )
            {
                // ignore, correct
            }

            timing.sleepABit();
            List<String> children = localClient.getChildren().forPath("/parent");
            Assert.assertEquals(children.size(), 0, children.toString()); // protected mode should have deleted the node

            localClient.delete().forPath("/parent");
        }
    }
    finally
    {
        CloseableUtils.closeQuietly(client);
    }
}