Java Code Examples for org.apache.curator.utils.CloseableUtils#closeQuietly()

The following examples show how to use org.apache.curator.utils.CloseableUtils#closeQuietly() . 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 xian 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();

        Assert.assertNull(client.checkExists().forPath("/one/two"));
        client.create().creatingParentContainersIfNeeded().forPath("/one/two/three");
        Assert.assertNotNull(client.checkExists().forPath("/one/two"));

        client.delete().deletingChildrenIfNeeded().forPath("/one");
        Assert.assertNull(client.checkExists().forPath("/one"));

        Assert.assertNull(client.checkExists().forPath("/one/two"));
        client.checkExists().creatingParentContainersIfNeeded().forPath("/one/two/three");
        Assert.assertNotNull(client.checkExists().forPath("/one/two"));
        Assert.assertNull(client.checkExists().forPath("/one/two/three"));
    }
    finally
    {
        CloseableUtils.closeQuietly(client);
    }
}
 
Example 2
Source File: TestFramework.java    From xian 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
    {
        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 3
Source File: TestFramework.java    From xian with Apache License 2.0 6 votes vote down vote up
@Test
public void testCreateContainersWithNamespace() throws Exception
{
    final String namespace = "container1";
    CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder();
    CuratorFramework client = builder.connectString(server.getConnectString()).retryPolicy(new RetryOneTime(1)).namespace(namespace).build();
    try
    {
        client.start();
        String path = "/path1/path2";
        client.createContainers(path);
        Assert.assertNotNull(client.checkExists().forPath(path));
        Assert.assertNotNull(client.getZookeeperClient().getZooKeeper().exists("/" + namespace + path, false));
    }
    finally
    {
        CloseableUtils.closeQuietly(client);
    }
}
 
Example 4
Source File: BaseTestTreeCache.java    From xian with 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 5
Source File: TestFramework.java    From xian with Apache License 2.0 6 votes vote down vote up
@Test
public void testDeleteWithChildren() 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/four/five/six", "foo".getBytes());
        client.delete().deletingChildrenIfNeeded().forPath("/one/two/three/four/five");
        Assert.assertNull(client.checkExists().forPath("/one/two/three/four/five"));
        client.delete().deletingChildrenIfNeeded().forPath("/one/two");
        Assert.assertNull(client.checkExists().forPath("/one/two"));
    }
    finally
    {
        CloseableUtils.closeQuietly(client);
    }
}
 
Example 6
Source File: TestWatcherIdentity.java    From xian with Apache License 2.0 6 votes vote down vote up
@Test
public void testCuratorWatcher() throws Exception
{
    Timing timing = new Timing();
    CountCuratorWatcher watcher = new CountCuratorWatcher();
    CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1));
    try
    {
        client.start();
        client.create().forPath(PATH);
        // Add twice the same watcher on the same path
        client.getData().usingWatcher(watcher).forPath(PATH);
        client.getData().usingWatcher(watcher).forPath(PATH);
        // Ok, let's test it
        client.setData().forPath(PATH, new byte[]{});
        timing.sleepABit();
        Assert.assertEquals(1, watcher.count.get());
    }
    finally
    {
        CloseableUtils.closeQuietly(client);
    }
}
 
Example 7
Source File: ZookeeperSyncToNacosServiceImpl.java    From nacos-sync with Apache License 2.0 6 votes vote down vote up
@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 8
Source File: TestWatcherIdentity.java    From xian with 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 9
Source File: TestSimpleDistributedQueue.java    From xian with Apache License 2.0 5 votes vote down vote up
private void closeAll(CuratorFramework[] clients)
{
    if ( clients != null )
    {
        for ( CuratorFramework c : clients )
        {
            CloseableUtils.closeQuietly(c);
        }
    }
}
 
Example 10
Source File: TestServiceProvider.java    From xian with 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 11
Source File: TestServiceDiscovery.java    From xian with Apache License 2.0 5 votes vote down vote up
@Test
public void testCrashedInstance() throws Exception
{
    List<Closeable> closeables = Lists.newArrayList();
    try
    {
        Timing timing = new Timing();

        CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1));
        closeables.add(client);
        client.start();

        ServiceInstance<String> instance = ServiceInstance.<String>builder().payload("thing").name("test").port(10064).build();
        ServiceDiscovery<String> discovery = new ServiceDiscoveryImpl<String>(client, "/test", new JsonInstanceSerializer<String>(String.class), new FastjsonServiceDefinitionSerializer<>(String.class), instance, false);
        closeables.add(discovery);
        discovery.start();

        Assert.assertEquals(discovery.queryForInstances("test").size(), 1);

        KillSession.kill(client.getZookeeperClient().getZooKeeper(), server.getConnectString());
        Thread.sleep(timing.multiple(1.5).session());

        Assert.assertEquals(discovery.queryForInstances("test").size(), 1);
    }
    finally
    {
        Collections.reverse(closeables);
        for ( Closeable c : closeables )
        {
            CloseableUtils.closeQuietly(c);
        }
    }
}
 
Example 12
Source File: ZookeeperRuleConfigSource.java    From ratelimiter4j with Apache License 2.0 5 votes vote down vote up
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 13
Source File: TestQueueSharder.java    From xian with Apache License 2.0 5 votes vote down vote up
@Test
public void     testSharderWatchSync() throws Exception
{
    Timing                  timing = new Timing();
    CuratorFramework        client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1));

    final BlockingQueueConsumer<String>     consumer = makeConsumer(null);
    QueueAllocator<String, DistributedQueue<String>>    distributedQueueAllocator = makeAllocator(consumer);
    QueueSharderPolicies        policies = QueueSharderPolicies.builder().newQueueThreshold(2).thresholdCheckMs(1).build();

    QueueSharder<String, DistributedQueue<String>>  sharder1 = new QueueSharder<String, DistributedQueue<String>>(client, distributedQueueAllocator, "/queues", "/leader", policies);
    QueueSharder<String, DistributedQueue<String>>  sharder2 = new QueueSharder<String, DistributedQueue<String>>(client, distributedQueueAllocator, "/queues", "/leader", policies);
    try
    {
        client.start();
        sharder1.start();
        sharder2.start();

        for ( int i = 0; i < 20; ++i )
        {
            sharder1.getQueue().put(Integer.toString(i));
        }
        timing.sleepABit();

        Assert.assertTrue((sharder1.getShardQty() > 1) || (sharder2.getShardQty() > 1));
        timing.forWaiting().sleepABit();
        Assert.assertEquals(sharder1.getShardQty(), sharder2.getShardQty());
    }
    finally
    {
        timing.sleepABit(); // let queues clear
        CloseableUtils.closeQuietly(sharder1);
        CloseableUtils.closeQuietly(sharder2);
        CloseableUtils.closeQuietly(client);
    }
}
 
Example 14
Source File: TestSharedCount.java    From xian with Apache License 2.0 5 votes vote down vote up
@Test
public void testDisconnectEventOnWatcherDoesNotRetry() throws Exception
{
    final CountDownLatch gotSuspendEvent = new CountDownLatch(1);

    CuratorFramework curatorFramework = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryNTimes(10, 1000));
    curatorFramework.start();
    curatorFramework.blockUntilConnected();

    SharedCount sharedCount = new SharedCount(curatorFramework, "/count", 10);
    sharedCount.start();

    curatorFramework.getConnectionStateListenable().addListener(new ConnectionStateListener() {
        @Override
        public void stateChanged(CuratorFramework client, ConnectionState newState) {
            if (newState == ConnectionState.SUSPENDED) {
                gotSuspendEvent.countDown();
            }
        }
    });

    try
    {
        server.stop();
        // if watcher goes into 10second retry loop we won't get timely notification
        Assert.assertTrue(gotSuspendEvent.await(5, TimeUnit.SECONDS));
    }
    finally
    {
        CloseableUtils.closeQuietly(sharedCount);
        CloseableUtils.closeQuietly(curatorFramework);
    }
}
 
Example 15
Source File: TestDistributedPriorityQueue.java    From xian with Apache License 2.0 5 votes vote down vote up
@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 16
Source File: PathCacheExample.java    From xian with Apache License 2.0 4 votes vote down vote up
private static void processCommands(CuratorFramework client, PathChildrenCache cache) throws Exception
{
    // More scaffolding that does a simple command line processor

    printHelp();

    List<ExampleServer> servers = Lists.newArrayList();
    try
    {
        addListener(cache);

        BufferedReader  in = new BufferedReader(new InputStreamReader(System.in));
        boolean         done = false;
        while ( !done )
        {
            System.out.print("> ");

            String      line = in.readLine();
            if ( line == null )
            {
                break;
            }

            String      command = line.trim();
            String[]    parts = command.split("\\s");
            if ( parts.length == 0 )
            {
                continue;
            }
            String      operation = parts[0];
            String      args[] = Arrays.copyOfRange(parts, 1, parts.length);

            if ( operation.equalsIgnoreCase("help") || operation.equalsIgnoreCase("?") )
            {
                printHelp();
            }
            else if ( operation.equalsIgnoreCase("q") || operation.equalsIgnoreCase("quit") )
            {
                done = true;
            }
            else if ( operation.equals("set") )
            {
                setValue(client, command, args);
            }
            else if ( operation.equals("remove") )
            {
                remove(client, command, args);
            }
            else if ( operation.equals("list") )
            {
                list(cache);
            }

            Thread.sleep(1000); // just to allow the console output to catch up
        }
    }
    finally
    {
        for ( ExampleServer server : servers )
        {
            CloseableUtils.closeQuietly(server);
        }
    }
}
 
Example 17
Source File: TestLeaderLatch.java    From xian with Apache License 2.0 4 votes vote down vote up
@Test
public void testProperCloseWithoutConnectionEstablished() throws Exception
{
    server.stop();

    Timing timing = new Timing();
    LeaderLatch latch = null;
    CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1));
    try
    {
        client.start();

        final AtomicBoolean resetCalled = new AtomicBoolean(false);
        final CountDownLatch cancelStartTaskLatch = new CountDownLatch(1);
        latch = new LeaderLatch(client, PATH_NAME)
        {
            @Override
            void reset() throws Exception
            {
                resetCalled.set(true);
                super.reset();
            }

            @Override
            protected boolean cancelStartTask()
            {
                if ( super.cancelStartTask() )
                {
                    cancelStartTaskLatch.countDown();
                    return true;
                }
                return false;
            }
        };

        latch.start();
        latch.close();
        latch = null;

        Assert.assertTrue(timing.awaitLatch(cancelStartTaskLatch));
        Assert.assertFalse(resetCalled.get());
    }
    finally
    {
        CloseableUtils.closeQuietly(latch);
        CloseableUtils.closeQuietly(client);
    }
}
 
Example 18
Source File: TestDistributedDoubleBarrier.java    From xian with Apache License 2.0 4 votes vote down vote up
@Test
public void     testBasic() throws Exception
{
    final Timing              timing = new Timing();
    final List<Closeable>     closeables = Lists.newArrayList();
    final CuratorFramework    client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1));
    try
    {
        closeables.add(client);
        client.start();

        final CountDownLatch    postEnterLatch = new CountDownLatch(QTY);
        final CountDownLatch    postLeaveLatch = new CountDownLatch(QTY);
        final AtomicInteger     count = new AtomicInteger(0);
        final AtomicInteger     max = new AtomicInteger(0);
        List<Future<Void>>      futures = Lists.newArrayList();
        ExecutorService         service = Executors.newCachedThreadPool();
        for ( int i = 0; i < QTY; ++i )
        {
            Future<Void>    future = service.submit
            (
                new Callable<Void>()
                {
                    @Override
                    public Void call() throws Exception
                    {
                        DistributedDoubleBarrier        barrier = new DistributedDoubleBarrier(client, "/barrier", QTY);

                        Assert.assertTrue(barrier.enter(timing.seconds(), TimeUnit.SECONDS));

                        synchronized(TestDistributedDoubleBarrier.this)
                        {
                            int     thisCount = count.incrementAndGet();
                            if ( thisCount > max.get() )
                            {
                                max.set(thisCount);
                            }
                        }

                        postEnterLatch.countDown();
                        Assert.assertTrue(timing.awaitLatch(postEnterLatch));

                        Assert.assertEquals(count.get(), QTY);

                        Assert.assertTrue(barrier.leave(10, TimeUnit.SECONDS));
                        count.decrementAndGet();

                        postLeaveLatch.countDown();
                        Assert.assertTrue(timing.awaitLatch(postLeaveLatch));

                        return null;
                    }
                }
            );
            futures.add(future);
        }

        for ( Future<Void> f : futures )
        {
            f.get();
        }
        Assert.assertEquals(count.get(), 0);
        Assert.assertEquals(max.get(), QTY);
    }
    finally
    {
        for ( Closeable c : closeables )
        {
            CloseableUtils.closeQuietly(c);
        }
    }
}
 
Example 19
Source File: TestReaper.java    From xian with Apache License 2.0 4 votes vote down vote up
@Test
public void testUsingLeaderPath() throws Exception
{
    final Timing timing = new Timing();
    CuratorFramework client = makeClient(timing, null);
    Reaper reaper1 = null;
    Reaper reaper2 = null;
    try
    {
        final AtomicInteger reaper1Count = new AtomicInteger();
        reaper1 = new Reaper(client, Reaper.newExecutorService(), 1, "/reaper/leader")
        {
            @Override
            protected void reap(PathHolder holder)
            {
                reaper1Count.incrementAndGet();
                super.reap(holder);
            }
        };

        final AtomicInteger reaper2Count = new AtomicInteger();
        reaper2 = new Reaper(client, Reaper.newExecutorService(), 1, "/reaper/leader")
        {
            @Override
            protected void reap(PathHolder holder)
            {
                reaper2Count.incrementAndGet();
                super.reap(holder);
            }
        };

        client.start();
        client.create().creatingParentsIfNeeded().forPath("/one/two/three");

        reaper1.start();
        reaper2.start();

        reaper1.addPath("/one/two/three");
        reaper2.addPath("/one/two/three");

        timing.sleepABit();

        Assert.assertTrue((reaper1Count.get() == 0) || (reaper2Count.get() == 0));
        Assert.assertTrue((reaper1Count.get() > 0) || (reaper2Count.get() > 0));

        Reaper activeReaper;
        AtomicInteger inActiveReaperCount;
        if ( reaper1Count.get() > 0 )
        {
            activeReaper = reaper1;
            inActiveReaperCount = reaper2Count;
        }
        else
        {
            activeReaper = reaper2;
            inActiveReaperCount = reaper1Count;
        }
        Assert.assertEquals(inActiveReaperCount.get(), 0);
        activeReaper.close();
        timing.sleepABit();
        Assert.assertTrue(inActiveReaperCount.get() > 0);
    }
    finally
    {
        CloseableUtils.closeQuietly(reaper1);
        CloseableUtils.closeQuietly(reaper2);
        CloseableUtils.closeQuietly(client);
    }
}
 
Example 20
Source File: ZKUtil.java    From PoseidonX with Apache License 2.0 2 votes vote down vote up
/**
 * 关闭
 * @param curator
 */
public static void closeClient(CuratorFramework curator){
    CloseableUtils.closeQuietly(curator);
}