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

The following examples show how to use org.apache.curator.framework.CuratorFramework#start() . 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: TestNamespaceFacade.java    From xian 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));
    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 2
Source File: BaragonServiceModule.java    From Baragon with Apache License 2.0 6 votes vote down vote up
@Singleton
@Provides
public CuratorFramework provideCurator(ZooKeeperConfiguration config, BaragonConnectionStateListener connectionStateListener) {
  CuratorFramework client = CuratorFrameworkFactory.builder()
    .connectString(config.getQuorum())
    .sessionTimeoutMs(config.getSessionTimeoutMillis())
    .connectionTimeoutMs(config.getConnectTimeoutMillis())
    .retryPolicy(new ExponentialBackoffRetry(config.getRetryBaseSleepTimeMilliseconds(), config.getRetryMaxTries()))
    .defaultData(new byte[0])
    .build();

  client.getConnectionStateListenable().addListener(connectionStateListener);

  client.start();

  return client.usingNamespace(config.getZkNamespace());
}
 
Example 3
Source File: CuratorZookeeperConfigure.java    From cicada with MIT License 6 votes vote down vote up
/**
 * 如果zk中cicada的namespace不存在,则创建.
 */

@SneakyThrows
private void createNamespaceIfNotExists() {
  final CuratorFramework client = ZookeeperUtil.getClient(props.getZkAddr());
      
  String namespace = props.getZkNamespase();
  if (namespace.charAt(0) != PATH_SEPARATOR) {
    final StringBuilder sb = new StringBuilder();
    sb.append(PATH_SEPARATOR).append(namespace);
    namespace = sb.toString();
  }

  client.start();
  try {
    if (!ZookeeperUtil.exists(client, namespace)) {
      ZookeeperUtil.create(client, namespace, CICADA_NAMESPACE_NODE_CONTENT);
    }
  } finally {
    client.close();
  }
}
 
Example 4
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 5
Source File: TestFramework.java    From curator 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: TestSharedCount.java    From curator with Apache License 2.0 6 votes vote down vote up
@Test
public void testMultiClientDifferentSeed() throws Exception
{
    CuratorFramework client1 = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1));
    CuratorFramework client2 = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1));
    SharedCount count1 = new SharedCount(client1, "/count", 10);
    SharedCount count2 = new SharedCount(client2, "/count", 20);
    try
    {
        client1.start();
        client2.start();
        count1.start();
        count2.start();

        Assert.assertEquals(count1.getCount(), 10);
        Assert.assertEquals(count2.getCount(), 10);
    }
    finally
    {
        CloseableUtils.closeQuietly(count2);
        CloseableUtils.closeQuietly(count1);
        CloseableUtils.closeQuietly(client2);
        CloseableUtils.closeQuietly(client1);
    }
}
 
Example 7
Source File: TestChildReaper.java    From xian with Apache License 2.0 5 votes vote down vote up
@Test
public void testSimple() throws Exception
{
    Timing timing = new Timing();
    ChildReaper reaper = null;
    CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1));
    try
    {
        client.start();

        for ( int i = 0; i < 10; ++i )
        {
            client.create().creatingParentsIfNeeded().forPath("/test/" + Integer.toString(i));
        }

        reaper = new ChildReaper(client, "/test", Reaper.Mode.REAP_UNTIL_DELETE, 1);
        reaper.start();

        timing.forWaiting().sleepABit();

        Stat stat = client.checkExists().forPath("/test");
        Assert.assertEquals(stat.getNumChildren(), 0);
    }
    finally
    {
        CloseableUtils.closeQuietly(reaper);
        CloseableUtils.closeQuietly(client);
    }
}
 
Example 8
Source File: CuratorClientMgr.java    From fastjgame with Apache License 2.0 5 votes vote down vote up
private static CuratorFramework newStartedClient(final CuratorFrameworkFactory.Builder builder) throws InterruptedException {
    checkThreadFactory(builder);

    final CuratorFramework client = builder.build();
    client.start();
    client.blockUntilConnected();
    return client;
}
 
Example 9
Source File: LeaderLatchTest.java    From BigData-In-Practice with Apache License 2.0 5 votes vote down vote up
private static synchronized CuratorFramework getClient() {
    CuratorFramework client = CuratorFrameworkFactory.builder().connectString(zkServerIps)
            .sessionTimeoutMs(6000).connectionTimeoutMs(3000) //.namespace("LeaderLatchTest")
            .retryPolicy(new ExponentialBackoffRetry(1000, 3)).build();
    client.start();
    return client;
}
 
Example 10
Source File: TestServiceDiscovery.java    From xian with Apache License 2.0 5 votes vote down vote up
@Test
public void testCleaning() 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();
        discovery.unregisterService(instance);

        Assert.assertEquals(((ServiceDiscoveryImpl)discovery).debugServicesQty(), 0);
    }
    finally
    {
        Collections.reverse(closeables);
        for ( Closeable c : closeables )
        {
            CloseableUtils.closeQuietly(c);
        }
    }
}
 
Example 11
Source File: TestTransactionsNew.java    From curator with Apache License 2.0 5 votes vote down vote up
@Test
public void testCheckVersion() throws Exception
{
    CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1));
    try
    {
        client.start();
        client.create().forPath("/foo");
        Stat stat = client.setData().forPath("/foo", "new".getBytes());  // up the version

        CuratorOp statOp = client.transactionOp().check().withVersion(stat.getVersion() + 1).forPath("/foo");
        CuratorOp createOp = client.transactionOp().create().forPath("/bar");
        try
        {
            client.transaction().forOperations(statOp, createOp);
            Assert.fail();
        }
        catch ( KeeperException.BadVersionException correct )
        {
            // correct
        }

        Assert.assertNull(client.checkExists().forPath("/bar"));
    }
    finally
    {
        CloseableUtils.closeQuietly(client);
    }
}
 
Example 12
Source File: ZookeeperRegistryCenterForAuthTest.java    From shardingsphere-elasticjob-cloud with Apache License 2.0 5 votes vote down vote up
@Test
public void assertInitWithDigestSuccess() throws Exception {
    CuratorFramework client = CuratorFrameworkFactory.builder()
        .connectString(EmbedTestingServer.getConnectionString())
        .retryPolicy(new RetryOneTime(2000))
        .authorization("digest", "digest:password".getBytes()).build();
    client.start();
    client.blockUntilConnected();
    assertThat(client.getData().forPath("/" + ZookeeperRegistryCenterForAuthTest.class.getName() + "/test/deep/nested"), is("deepNested".getBytes()));
}
 
Example 13
Source File: ConfigUploadComponent.java    From metron with Apache License 2.0 5 votes vote down vote up
public SensorParserConfig getSensorParserConfig(String sensorType) {
  SensorParserConfig sensorParserConfig = new SensorParserConfig();
  CuratorFramework client = getClient(topologyProperties.getProperty(ZKServerComponent.ZOOKEEPER_PROPERTY));
  client.start();
  try {
    sensorParserConfig = readSensorParserConfigFromZookeeper(sensorType, client);
  } catch (Exception e) {
    e.printStackTrace();
  } finally {
    client.close();
  }
  return sensorParserConfig;
}
 
Example 14
Source File: TestFrameworkBackground.java    From xian with Apache License 2.0 4 votes vote down vote up
/**
 * CURATOR-126
 * Shutdown the Curator client while there are still background operations running.
 */
@Test
public void testShutdown() throws Exception
{
    Timing timing = new Timing();
    CuratorFramework client = CuratorFrameworkFactory
        .builder()
        .connectString(server.getConnectString())
        .sessionTimeoutMs(timing.session())
        .connectionTimeoutMs(timing.connection()).retryPolicy(new RetryOneTime(1))
        .maxCloseWaitMs(timing.forWaiting().milliseconds())
        .build();
    try
    {
        final AtomicBoolean hadIllegalStateException = new AtomicBoolean(false);
        ((CuratorFrameworkImpl)client).debugUnhandledErrorListener = new UnhandledErrorListener()
        {
            @Override
            public void unhandledError(String message, Throwable e)
            {
                if ( e instanceof IllegalStateException )
                {
                    hadIllegalStateException.set(true);
                }
            }
        };
        client.start();

        final CountDownLatch operationReadyLatch = new CountDownLatch(1);
        ((CuratorFrameworkImpl)client).debugListener = new CuratorFrameworkImpl.DebugBackgroundListener()
        {
            @Override
            public void listen(OperationAndData<?> data)
            {
                try
                {
                    operationReadyLatch.await();
                }
                catch ( InterruptedException e )
                {
                    Thread.currentThread().interrupt();
                }
            }
        };

        // queue a background operation that will block due to the debugListener
        client.create().inBackground().forPath("/hey");
        timing.sleepABit();

        // close the client while the background is still blocked
        client.close();

        // unblock the background
        operationReadyLatch.countDown();
        timing.sleepABit();

        // should not generate an exception
        Assert.assertFalse(hadIllegalStateException.get());
    }
    finally
    {
        CloseableUtils.closeQuietly(client);
    }
}
 
Example 15
Source File: TestZKDelegationTokenSecretManager.java    From big-c with Apache License 2.0 4 votes vote down vote up
@Test
public void testACLs() throws Exception {
  DelegationTokenManager tm1;
  String connectString = zkServer.getConnectString();
  Configuration conf = getSecretConf(connectString);
  RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
  String userPass = "myuser:mypass";
  final ACL digestACL = new ACL(ZooDefs.Perms.ALL, new Id("digest",
    DigestAuthenticationProvider.generateDigest(userPass)));
  ACLProvider digestAclProvider = new ACLProvider() {
    @Override
    public List<ACL> getAclForPath(String path) { return getDefaultAcl(); }

    @Override
    public List<ACL> getDefaultAcl() {
      List<ACL> ret = new ArrayList<ACL>();
      ret.add(digestACL);
      return ret;
    }
  };

  CuratorFramework curatorFramework =
    CuratorFrameworkFactory.builder()
      .connectString(connectString)
      .retryPolicy(retryPolicy)
      .aclProvider(digestAclProvider)
      .authorization("digest", userPass.getBytes("UTF-8"))
      .build();
  curatorFramework.start();
  ZKDelegationTokenSecretManager.setCurator(curatorFramework);
  tm1 = new DelegationTokenManager(conf, new Text("bla"));
  tm1.init();

  // check ACL
  String workingPath = conf.get(ZKDelegationTokenSecretManager.ZK_DTSM_ZNODE_WORKING_PATH);
  verifyACL(curatorFramework, "/" + workingPath, digestACL);

  tm1.destroy();
  ZKDelegationTokenSecretManager.setCurator(null);
  curatorFramework.close();
}
 
Example 16
Source File: TestServiceCache.java    From xian with Apache License 2.0 4 votes vote down vote up
@Test
public void testViaProvider() throws Exception
{
    Timing timing = new Timing();

    List<Closeable> closeables = Lists.newArrayList();
    try
    {
        CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1));
        closeables.add(client);
        client.start();

        ServiceDiscovery<String> discovery = ServiceDiscoveryBuilder.builder(String.class).basePath("/discovery").client(client).build();
        closeables.add(discovery);
        discovery.start();

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

        ServiceInstance<String> instance = ServiceInstance.<String>builder().payload("thing").name("test").port(10064).build();
        discovery.registerService(instance);

        int count = 0;
        ServiceInstance<String> foundInstance = null;
        while ( foundInstance == null )
        {
            Assert.assertTrue(count++ < 5);
            foundInstance = serviceProvider.getInstance();
            timing.sleepABit();
        }
        Assert.assertEquals(foundInstance, instance);

        ServiceInstance<String> instance2 = ServiceInstance.<String>builder().address("foo").payload("thing").name("test").port(10064).build();
        discovery.registerService(instance2);
        timing.sleepABit();
        Collection<ServiceInstance<String>> allInstances = serviceProvider.getAllInstances();
        Assert.assertEquals(allInstances.size(), 2);
    }
    finally
    {
        Collections.reverse(closeables);
        for ( Closeable c : closeables )
        {
            CloseableUtils.closeQuietly(c);
        }
    }
}
 
Example 17
Source File: TestDistributedPriorityQueue.java    From curator with Apache License 2.0 4 votes vote down vote up
@Test
public void     testAdditions() throws Exception
{
    DistributedPriorityQueue<Integer>   queue = null;
    CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1));
    client.start();
    try
    {
        final CountDownLatch        latch = new CountDownLatch(1);
        QueueSerializer<Integer>    serializer = new IntSerializer()
        {
            @Override
            public Integer deserialize(byte[] bytes)
            {
                // gets called in the Queue's event processing thread
                try
                {
                    latch.await();
                }
                catch ( InterruptedException e )
                {
                    // ignore
                }
                return super.deserialize(bytes);
            }
        };
        BlockingQueueConsumer<Integer> consumer = new BlockingQueueConsumer<Integer>(Mockito.mock(ConnectionStateListener.class));
        queue = QueueBuilder.builder(client, consumer, serializer, "/test").buildPriorityQueue(1);
        queue.start();

        for ( int i = 0; i < 10; ++i )
        {
            queue.put(10, 10);
            if ( i == 0 )
            {
                queue.put(1, 1);
                latch.countDown();
            }
        }

        assertOrdering(consumer, 10);
    }
    finally
    {
        CloseableUtils.closeQuietly(queue);
        CloseableUtils.closeQuietly(client);
    }
}
 
Example 18
Source File: TestWatchesBuilder.java    From curator with Apache License 2.0 4 votes vote down vote up
@Test
public void testGuaranteedRemoveWatchInBackground() throws Exception {
    Timing timing = new Timing();
    CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(),
                                                                new ExponentialBackoffRetry(100, 3));
    try
    {
        client.start();
        
        AtomicReference<ConnectionState> stateRef = registerConnectionStateListener(client);
                    
        final CountDownLatch guaranteeAddedLatch = new CountDownLatch(1);
        
        ((CuratorFrameworkImpl)client).getFailedRemoveWatcherManager().debugListener = new FailedOperationManager.FailedOperationManagerListener<FailedRemoveWatchManager.FailedRemoveWatchDetails>()
        {

            @Override
            public void pathAddedForGuaranteedOperation(
                    FailedRemoveWatchDetails detail)
            {
                guaranteeAddedLatch.countDown();
            }
        };
        
        String path = "/";
        
        CountDownLatch removeLatch = new CountDownLatch(1);
        
        Watcher watcher = new CountDownWatcher(path, removeLatch, EventType.DataWatchRemoved);            
        client.checkExists().usingWatcher(watcher).forPath(path);
        
        server.stop();           
        Assert.assertTrue(blockUntilDesiredConnectionState(stateRef, timing, ConnectionState.SUSPENDED));
        
        //Remove the watch while we're not connected
        client.watches().remove(watcher).guaranteed().inBackground().forPath(path);
        
        timing.awaitLatch(guaranteeAddedLatch);
        
        server.restart();
        
        timing.awaitLatch(removeLatch);            
    }
    finally
    {
        CloseableUtils.closeQuietly(client);
    }
}
 
Example 19
Source File: TestNodeCache.java    From curator with Apache License 2.0 4 votes vote down vote up
@Test
public void     testBasics() throws Exception
{
    NodeCache           cache = null;
    Timing              timing = new Timing();
    CuratorFramework    client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1));
    client.start();
    try
    {
        client.create().forPath("/test");

        cache = new NodeCache(client, "/test/node");
        cache.start(true);

        final Semaphore     semaphore = new Semaphore(0);
        cache.getListenable().addListener
        (
            new NodeCacheListener()
            {
                @Override
                public void nodeChanged() throws Exception
                {
                    semaphore.release();
                }
            }
        );

        Assert.assertNull(cache.getCurrentData());

        client.create().forPath("/test/node", "a".getBytes());
        Assert.assertTrue(timing.acquireSemaphore(semaphore));
        Assert.assertEquals(cache.getCurrentData().getData(), "a".getBytes());

        client.setData().forPath("/test/node", "b".getBytes());
        Assert.assertTrue(timing.acquireSemaphore(semaphore));
        Assert.assertEquals(cache.getCurrentData().getData(), "b".getBytes());

        client.delete().forPath("/test/node");
        Assert.assertTrue(timing.acquireSemaphore(semaphore));
        Assert.assertNull(cache.getCurrentData());
    }
    finally
    {
        CloseableUtils.closeQuietly(cache);
        TestCleanState.closeAndTestClean(client);
    }
}
 
Example 20
Source File: TestLeaderLatch.java    From curator 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);
        TestCleanState.closeAndTestClean(client);
    }
}