Java Code Examples for org.apache.curator.framework.CuratorFramework#close()

The following examples show how to use org.apache.curator.framework.CuratorFramework#close() . 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: TestCachedAtomicCounter.java    From curator with 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));
    client.start();
    try
    {
        DistributedAtomicLong dal = new DistributedAtomicLong(client, "/counter", new RetryOneTime(1));
        CachedAtomicLong cachedLong = new CachedAtomicLong(dal, 100);
        for ( long i = 0; i < 200; ++i )
        {
            AtomicValue<Long>       value = cachedLong.next();
            Assert.assertTrue(value.succeeded());
            Assert.assertEquals(value.preValue().longValue(), i);
            Assert.assertEquals(value.postValue().longValue(), i + 1);
        }
    }
    finally
    {
        client.close();
    }
}
 
Example 2
Source File: TestInterProcessSemaphore.java    From xian with Apache License 2.0 6 votes vote down vote up
@Test
public void testSimple() throws Exception
{
    Timing timing = new Timing();
    CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1));
    client.start();
    try
    {
        InterProcessSemaphoreV2 semaphore = new InterProcessSemaphoreV2(client, "/test", 1);
        Assert.assertNotNull(semaphore.acquire(timing.forWaiting().seconds(), TimeUnit.SECONDS));
        Assert.assertNull(semaphore.acquire(timing.forWaiting().seconds(), TimeUnit.SECONDS));
    }
    finally
    {
        client.close();
    }
}
 
Example 3
Source File: TestPathChildrenCache.java    From xian with Apache License 2.0 6 votes vote down vote up
@Test
public void testModes() throws Exception
{
    Timing timing = new Timing();
    CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1));
    client.start();
    try
    {
        client.create().forPath("/test");

        for ( boolean cacheData : new boolean[]{false, true} )
        {
            internalTestMode(client, cacheData);

            client.delete().forPath("/test/one");
            client.delete().forPath("/test/two");
        }
    }
    finally
    {
        client.close();
    }
}
 
Example 4
Source File: TestInterProcessMutexBase.java    From xian with Apache License 2.0 6 votes vote down vote up
@Test
public void testWithNamespace() throws Exception
{
    CuratorFramework client = CuratorFrameworkFactory.builder().
        connectString(server.getConnectString()).
        retryPolicy(new ExponentialBackoffRetry(100, 3)).
        namespace("test").
        build();
    client.start();
    try
    {
        InterProcessLock mutex = makeLock(client);
        mutex.acquire(10, TimeUnit.SECONDS);
        Thread.sleep(100);
        mutex.release();
    }
    finally
    {
        client.close();
    }
}
 
Example 5
Source File: TestInterProcessMutexBase.java    From xian with Apache License 2.0 6 votes vote down vote up
@Test
public void testReentrant() throws Exception
{
    CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new ExponentialBackoffRetry(100, 3));
    client.start();
    try
    {
        InterProcessLock mutex = makeLock(client);
        foo(mutex);
        Assert.assertFalse(mutex.isAcquiredInThisProcess());
    }
    finally
    {
        client.close();
    }
}
 
Example 6
Source File: ZookeeperCrusherTest.java    From netcrusher-java with Apache License 2.0 5 votes vote down vote up
private byte[] read(String connection, String path) throws Exception {
    RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
    CuratorFramework client = CuratorFrameworkFactory.newClient(connection, retryPolicy);

    client.start();
    try {
        return client.getData()
                .forPath(path);
    } finally {
        LOGGER.info("Closing client");
        client.close();
    }
}
 
Example 7
Source File: CuratorConnector.java    From jumbune with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Gets the data.
 *
 * @param path the path
 * @return the data
 * @throws Exception the exception
 */
public String getData(String path) throws Exception {
	CuratorFramework client = getOrCreateClient();
	client.start();
	String data = new String(client.getData().forPath(path), StandardCharsets.UTF_8);
	client.close();
	return data;
}
 
Example 8
Source File: ZookeeperCurator.java    From micro-service with MIT License 5 votes vote down vote up
private static void process() throws Exception {

        CuratorFramework client = CuratorFrameworkFactory.newClient("127.0.0.1:2181",
                new RetryNTimes(10, 5000));
        client.start();

        // monitor child node
        List<String> children = client.getChildren().usingWatcher(new CuratorWatcher() {
            @Override
            public void process(WatchedEvent event) throws Exception {
                logger.info("monitor: {}", event);
            }
        }).forPath("/");
        logger.info("children: {}", children);

        addListener(client);

        // create node
        String result = client.create().withMode(CreateMode.PERSISTENT).withACL(ZooDefs.Ids.OPEN_ACL_UNSAFE)
                .forPath("/test", "Data".getBytes());
        logger.info("result: {}", result);

        // set node
        client.setData().forPath("/test", "111".getBytes());
        client.setData().forPath("/test", "222".getBytes());

        // delete node
        logger.info("path: {}", client.checkExists().forPath("/test"));
        client.delete().withVersion(-1).forPath("/test");
        logger.info("path: {}", client.checkExists().forPath("/test"));

        client.close();
        logger.info("client close");
    }
 
Example 9
Source File: CuratorConnector.java    From jumbune with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Creates the path.
 *
 * @param path the path
 * @throws Exception the exception
 */
public void createPath(String path) throws Exception {
	CuratorFramework client = getOrCreateClient();
	client.start();		
	client.create().creatingParentsIfNeeded().forPath(path);
	client.close();
}
 
Example 10
Source File: TestTransactions.java    From xian with Apache License 2.0 5 votes vote down vote up
@Test
public void     testWithNamespace() throws Exception
{
    CuratorFramework        client = CuratorFrameworkFactory.builder().connectString(server.getConnectString()).retryPolicy(new RetryOneTime(1)).namespace("galt").build();
    client.start();
    try
    {
        Collection<CuratorTransactionResult>    results =
            client.inTransaction()
                .create().forPath("/foo", "one".getBytes())
            .and()
                .create().withMode(CreateMode.PERSISTENT_SEQUENTIAL).forPath("/test-", "one".getBytes())
            .and()
                .setData().forPath("/foo", "two".getBytes())
            .and()
                .create().forPath("/foo/bar")
            .and()
                .delete().forPath("/foo/bar")
            .and()
                .commit();

        Assert.assertTrue(client.checkExists().forPath("/foo") != null);
        Assert.assertTrue(client.usingNamespace(null).checkExists().forPath("/galt/foo") != null);
        Assert.assertEquals(client.getData().forPath("/foo"), "two".getBytes());
        Assert.assertTrue(client.checkExists().forPath("/foo/bar") == null);

        CuratorTransactionResult    ephemeralResult = Iterables.find(results, CuratorTransactionResult.ofTypeAndPath(OperationType.CREATE, "/test-"));
        Assert.assertNotNull(ephemeralResult);
        Assert.assertNotEquals(ephemeralResult.getResultPath(), "/test-");
        Assert.assertTrue(ephemeralResult.getResultPath().startsWith("/test-"));
    }
    finally
    {
        client.close();
    }
}
 
Example 11
Source File: ZkService.java    From binlake with Apache License 2.0 5 votes vote down vote up
public void close() {
    logger.info("close zk client");
    CuratorFramework client = this.client;
    if (client != null) {
        client.close();
    }
    this.client = null;
}
 
Example 12
Source File: ZKSegmentContainerManagerTest.java    From pravega with Apache License 2.0 5 votes vote down vote up
/**
 * Tests if we cannot connect to ZooKeeper (the exception must be propagated to the caller).
 *
 * @throws Exception if an error occurred.
 */
@Test
public void testInitializeError() throws Exception {
    @Cleanup
    CuratorFramework zkClient = startClient();
    @Cleanup
    ZKSegmentContainerManager segManager = createContainerManager(createMockContainerRegistry(), zkClient);
    zkClient.close();

    AssertExtensions.assertThrows(
            "initialize() did not throw an exception when ZooKeeper could not be accessed.",
            segManager::initialize,
            ex -> true); // Any exception will do, as long as it is propagated.
}
 
Example 13
Source File: TestPersistentNode.java    From curator with Apache License 2.0 5 votes vote down vote up
@Test
public void testBasic() throws Exception
{
    final byte[] TEST_DATA = "hey".getBytes();

    Timing2 timing = new Timing2();
    PersistentNode pen = null;
    CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1));
    try
    {
        client.start();
        pen = new PersistentNode(client, CreateMode.PERSISTENT, false, "/test", TEST_DATA);
        pen.debugWaitMsForBackgroundBeforeClose.set(timing.forSleepingABit().milliseconds());
        pen.start();
        Assert.assertTrue(pen.waitForInitialCreate(timing.milliseconds(), TimeUnit.MILLISECONDS));
        client.close(); // cause session to end - force checks that node is persistent

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

        byte[] bytes = client.getData().forPath("/test");
        Assert.assertEquals(bytes, TEST_DATA);
    }
    finally
    {
        CloseableUtils.closeQuietly(pen);
        CloseableUtils.closeQuietly(client);
    }
}
 
Example 14
Source File: TestPersistentEphemeralNode.java    From xian with Apache License 2.0 4 votes vote down vote up
protected void setDataTest(PersistentEphemeralNode.Mode mode) throws Exception
{
    PersistentEphemeralNode node = null;
    CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1));
    try
    {
        client.start();
        node = new PersistentEphemeralNode(client, mode, PATH, "a".getBytes());
        node.start();
        Assert.assertTrue(node.waitForInitialCreate(timing.forWaiting().seconds(), TimeUnit.SECONDS));

        Assert.assertEquals(client.getData().forPath(node.getActualPath()), "a".getBytes());

        final Semaphore semaphore = new Semaphore(0);
        Watcher watcher = new Watcher()
        {
            @Override
            public void process(WatchedEvent arg0)
            {
                semaphore.release();
            }
        };
        client.checkExists().usingWatcher(watcher).forPath(node.getActualPath());
        node.setData("b".getBytes());
        Assert.assertTrue(timing.acquireSemaphore(semaphore));
        Assert.assertEquals(node.getActualPath(), node.getActualPath());
        Assert.assertEquals(client.getData().usingWatcher(watcher).forPath(node.getActualPath()), "b".getBytes());
        node.setData("c".getBytes());
        Assert.assertTrue(timing.acquireSemaphore(semaphore));
        Assert.assertEquals(node.getActualPath(), node.getActualPath());
        Assert.assertEquals(client.getData().usingWatcher(watcher).forPath(node.getActualPath()), "c".getBytes());
        node.close();
        Assert.assertTrue(timing.acquireSemaphore(semaphore));
    }
    finally
    {
        if ( node != null )
        {
            node.close();
        }
        client.close();
    }
}
 
Example 15
Source File: DistributedClusterStat.java    From leaf-snowflake with Apache License 2.0 4 votes vote down vote up
public DistributedClusterStat(Map<Object,Object> _conf ) throws Exception
{
	this.conf = _conf;
	CuratorFramework _zk = mkZk();//创建Zookeeper连接及重试策略
	String path = String.valueOf(conf.get(Config.LEAF_ZOOKEEPER_ROOT));
	zkobj.mkdirs(_zk,path);// 创建一个永久目录
	_zk.close();

	active = new AtomicBoolean(true);



	watcher = new WatcherCallBack() {
		@Override
		public void execute(KeeperState state, EventType type, String path) {
			if ( active.get())
			{
				if(!(state.equals(KeeperState.SyncConnected)))
				{
					LOG.warn("Received event " + state + ": " + type + ": " + path + "with disconnected  from Zookeeper.");
					//System.out.println("Received event " + state + ":" + type + ":" + path + "with disconnected Zookeeper.");
				}
				else
				{
					LOG.info("Received event " + state + ":" + type + ":" + path);
					//System.out.println("Received event " + state + ":" + type + ":" + path);
					if(type.equals(EventType.NodeChildrenChanged)) //leaf 的临时node节点发生了变化(server上线或者下线)
					{
						LOG.info("Node childrens changed at path: " + path);
						//重新注册watcher事件
						try {
							List<String> children = get_childern(path,true);
							LOG.info("children list at path : " + path + " is " + children);
						} catch (Exception e)
						{
							LOG.warn("faild to get children in path: " + path,e);
						}
					}
				}

				if (!type.equals(EventType.None))
				{
					//System.out.println("Received event " + state + ":" + type + ":" + path);
					LOG.info("Received event " + state + ":" + type + ":" + path);
					for (Map.Entry<UUID,ClusterStateCallback> e: callbacks.entrySet())
					{
						ClusterStateCallback fn = e.getValue();
						fn.execute(type,path);
					}
				}

			}
		}
	};
	zk = null;
	try {
		zk = mkZk(watcher);
	}
	catch (Exception e)
	{
		LOG.error(e.getMessage(),e);
	}
}
 
Example 16
Source File: TestInterProcessSemaphore.java    From xian with Apache License 2.0 4 votes vote down vote up
@Test
public void testThreads() throws Exception
{
    final int THREAD_QTY = 10;

    Timing timing = new Timing();
    CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1));
    client.start();
    try
    {
        final InterProcessSemaphoreV2 semaphore = new InterProcessSemaphoreV2(client, "/test", 1);
        ExecutorService service = Executors.newFixedThreadPool(THREAD_QTY);
        for ( int i = 0; i < THREAD_QTY; ++i )
        {
            service.submit
                (
                    new Callable<Object>()
                    {
                        @Override
                        public Object call() throws Exception
                        {
                            Lease lease = semaphore.acquire();
                            try
                            {
                                Thread.sleep(1);
                            }
                            finally
                            {
                                lease.close();
                            }
                            return null;
                        }
                    }
                );
        }
        service.shutdown();
        Assert.assertTrue(service.awaitTermination(10, TimeUnit.SECONDS));
    }
    finally
    {
        client.close();
    }
}
 
Example 17
Source File: TestInterProcessSemaphore.java    From xian with Apache License 2.0 4 votes vote down vote up
@Test
public void testNoOrphanedNodes() throws Exception
{
    final Timing timing = new Timing();
    final ExecutorService executor = Executors.newFixedThreadPool(1);
    CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1));
    client.start();
    try
    {
        final InterProcessSemaphoreV2 semaphore = new InterProcessSemaphoreV2(client, "/test", 1);
        Lease lease = semaphore.acquire(timing.forWaiting().seconds(), TimeUnit.SECONDS);
        Assert.assertNotNull(lease);
        final List<String> childNodes = client.getChildren().forPath("/test/leases");
        Assert.assertEquals(childNodes.size(), 1);

        final CountDownLatch nodeCreatedLatch = new CountDownLatch(1);
        client.getChildren().usingWatcher(new CuratorWatcher()
        {
            @Override
            public void process(WatchedEvent event) throws Exception
            {
                if ( event.getType() == Watcher.Event.EventType.NodeCreated )
                {
                    nodeCreatedLatch.countDown();
                }
            }
        }).forPath("/test/leases");

        final Future<Lease> leaseFuture = executor.submit(new Callable<Lease>()
        {
            @Override
            public Lease call() throws Exception
            {
                return semaphore.acquire(timing.forWaiting().multiple(2).seconds(), TimeUnit.SECONDS);
            }
        });

        // wait for second lease to create its node
        timing.awaitLatch(nodeCreatedLatch);
        String newNode = null;
        for ( String c : client.getChildren().forPath("/test/leases") )
        {
            if ( !childNodes.contains(c) )
            {
                newNode = c;
            }
        }
        Assert.assertNotNull(newNode);

        // delete the ephemeral node to trigger a retry
        client.delete().forPath("/test/leases/" + newNode);

        // release first lease so second one can be acquired
        lease.close();
        lease = leaseFuture.get();
        Assert.assertNotNull(lease);
        lease.close();
        Assert.assertEquals(client.getChildren().forPath("/test/leases").size(), 0);

        // no more lease exist. must be possible to acquire a new one
        Assert.assertNotNull(semaphore.acquire(timing.forWaiting().seconds(), TimeUnit.SECONDS));
    }
    finally
    {
        client.close();
        executor.shutdownNow();
    }
}
 
Example 18
Source File: TestDistributedAtomicLong.java    From xian with Apache License 2.0 4 votes vote down vote up
@Test
public void     testCompareAndSet() throws Exception
{
    final CuratorFramework      client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1));
    client.start();
    try
    {
        final AtomicBoolean         doIncrement = new AtomicBoolean(false);
        DistributedAtomicLong dal = new DistributedAtomicLong(client, "/counter", new RetryOneTime(1))
        {
            @Override
            public byte[] valueToBytes(Long newValue)
            {
                if ( doIncrement.get() )
                {
                    DistributedAtomicLong inc = new DistributedAtomicLong(client, "/counter", new RetryOneTime(1));
                    try
                    {
                        // this will force a bad version exception
                        inc.increment();
                    }
                    catch ( Exception e )
                    {
                        throw new Error(e);
                    }
                }

                return super.valueToBytes(newValue);
            }
        };
        dal.forceSet(1L);

        Assert.assertTrue(dal.compareAndSet(1L, 5L).succeeded());
        Assert.assertFalse(dal.compareAndSet(1L, 5L).succeeded());

        doIncrement.set(true);
        Assert.assertFalse(dal.compareAndSet(5L, 10L).succeeded());
    }
    finally
    {
        client.close();
    }
}
 
Example 19
Source File: ZookeeperDataSourceTest.java    From Sentinel with Apache License 2.0 4 votes vote down vote up
@Test
public void testZooKeeperDataSourceAuthorization() throws Exception {
    TestingServer server = new TestingServer(21812);
    server.start();

    final String remoteAddress = server.getConnectString();
    final String groupId = "sentinel-zk-ds-demo";
    final String dataId = "flow-HK";
    final String path = "/" + groupId + "/" + dataId;
    final String scheme = "digest";
    final String auth = "root:123456";

    AuthInfo authInfo = new AuthInfo(scheme, auth.getBytes());
    List<AuthInfo> authInfoList = Collections.singletonList(authInfo);

    CuratorFramework zkClient = CuratorFrameworkFactory.builder().
            connectString(remoteAddress).
            retryPolicy(new ExponentialBackoffRetry(3, 100)).
            authorization(authInfoList).
            build();
    zkClient.start();
    Stat stat = zkClient.checkExists().forPath(path);
    if (stat == null) {
        ACL acl = new ACL(ZooDefs.Perms.ALL, new Id(scheme, DigestAuthenticationProvider.generateDigest(auth)));
        zkClient.create().creatingParentContainersIfNeeded().withACL(Collections.singletonList(acl)).forPath(path, null);
    }

    ReadableDataSource<String, List<FlowRule>> flowRuleDataSource = new ZookeeperDataSource<List<FlowRule>>(remoteAddress,
            authInfoList, groupId, dataId,
            new Converter<String, List<FlowRule>>() {
                @Override
                public List<FlowRule> convert(String source) {
                    return JSON.parseObject(source, new TypeReference<List<FlowRule>>() {
                    });
                }
            });
    FlowRuleManager.register2Property(flowRuleDataSource.getProperty());


    final String resourceName = "HK";
    publishThenTestFor(zkClient, path, resourceName, 10);
    publishThenTestFor(zkClient, path, resourceName, 15);

    zkClient.close();
    server.stop();
}
 
Example 20
Source File: TestDistributedBarrier.java    From curator with Apache License 2.0 4 votes vote down vote up
@Test
public void     testServerCrash() throws Exception
{
    final int                         TIMEOUT = 1000;

    final CuratorFramework            client = CuratorFrameworkFactory.builder().connectString(server.getConnectString()).connectionTimeoutMs(TIMEOUT).retryPolicy(new RetryOneTime(1)).build();
    try
    {
        client.start();

        final DistributedBarrier      barrier = new DistributedBarrier(client, "/barrier");
        barrier.setBarrier();

        final ExecutorService        service = Executors.newSingleThreadExecutor();
        Future<Object>               future = service.submit
        (
            new Callable<Object>()
            {
                @Override
                public Object call() throws Exception
                {
                    Thread.sleep(TIMEOUT / 2);
                    server.stop();
                    return null;
                }
            }
        );

        barrier.waitOnBarrier(TIMEOUT * 2, TimeUnit.SECONDS);
        future.get();
        Assert.fail();
    }
    catch ( KeeperException.ConnectionLossException expected )
    {
        // expected
    }
    finally
    {
        client.close();
    }
}