Java Code Examples for org.apache.curator.framework.CuratorFrameworkFactory#builder()

The following examples show how to use org.apache.curator.framework.CuratorFrameworkFactory#builder() . 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: HelloClientConfig.java    From jigsaw-payment with Apache License 2.0 6 votes vote down vote up
@Bean(initMethod = "start", destroyMethod = "close")
public CuratorFramework curatorFramework() {
    CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory
            .builder();
    int sessionTimeoutMs = Integer.parseInt(env.getProperty(
            "rpc.client.zookeeper.session.timeout.ms", "5000"));
    int connectionTimeoutMs = Integer.parseInt(env.getProperty(
            "rpc.client.zookeeper.connection.timeout.ms", "5000"));
    builder.connectString(
            env.getProperty("rpc.client.zookeeper.connect.string"))
            .sessionTimeoutMs(sessionTimeoutMs)
            .connectionTimeoutMs(connectionTimeoutMs)	               
            .retryPolicy(this.retryPolicy())
            .aclProvider(this.aclProvider()).authorization(this.authInfo());
    return builder.build();
}
 
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: HelloClientConfig.java    From jigsaw-payment with Apache License 2.0 6 votes vote down vote up
@Bean(initMethod = "start", destroyMethod = "close")
@Lazy(false)
public CuratorFramework curatorFramework() {
    CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory
            .builder();
    int sessionTimeoutMs = Integer.parseInt(env.getProperty(
            "rpc.client.zookeeper.session.timeout.ms", "5000"));
    int connectionTimeoutMs = Integer.parseInt(env.getProperty(
            "rpc.client.zookeeper.connection.timeout.ms", "5000"));
    builder.connectString(
            env.getProperty("rpc.client.zookeeper.connect.string"))
            .sessionTimeoutMs(sessionTimeoutMs)
            .connectionTimeoutMs(connectionTimeoutMs)
           
            .retryPolicy(this.retryPolicy());
            //.aclProvider(this.aclProvider()).authorization(this.authInfo());
    return builder.build();
}
 
Example 4
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 5
Source File: TestFramework.java    From xian with Apache License 2.0 6 votes vote down vote up
@Test
public void testCreateContainersUsingNamespace() throws Exception
{
    final String namespace = "container2";
    CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder();
    CuratorFramework client = builder.connectString(server.getConnectString()).retryPolicy(new RetryOneTime(1)).build();
    try
    {
        client.start();
        CuratorFramework nsClient = client.usingNamespace(namespace);
        String path = "/path1/path2";
        nsClient.createContainers(path);
        Assert.assertNotNull(nsClient.checkExists().forPath(path));
        Assert.assertNotNull(nsClient.getZookeeperClient().getZooKeeper().exists("/" + namespace + path, false));
    }
    finally
    {
        CloseableUtils.closeQuietly(client);
    }
}
 
Example 6
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 7
Source File: TestFramework.java    From xian with Apache License 2.0 6 votes vote down vote up
@Test
public void testDeleteGuaranteedWithChildren() 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().guaranteed().deletingChildrenIfNeeded().forPath("/one/two/three/four/five");
        Assert.assertNull(client.checkExists().forPath("/one/two/three/four/five"));
        client.delete().guaranteed().deletingChildrenIfNeeded().forPath("/one/two");
        Assert.assertNull(client.checkExists().forPath("/one/two"));
    }
    finally
    {
        CloseableUtils.closeQuietly(client);
    }
}
 
Example 8
Source File: ZKSuppportTestCase.java    From hermes with Apache License 2.0 6 votes vote down vote up
protected void configureCurator() throws Exception {

		Builder builder = CuratorFrameworkFactory.builder();

		builder.connectionTimeoutMs(50);
		builder.connectString(getZkConnectionString());
		builder.maxCloseWaitMs(50);
		builder.namespace("hermes");
		builder.retryPolicy(new ExponentialBackoffRetry(5, 3));
		builder.sessionTimeoutMs(50);

		m_curator = builder.build();
		m_curator.start();
		try {
			m_curator.blockUntilConnected();
		} catch (InterruptedException e) {
			throw new InitializationException(e.getMessage(), e);
		}

	}
 
Example 9
Source File: Test.java    From hermes with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {

		Builder builder = CuratorFrameworkFactory.builder();

		builder.connectionTimeoutMs(1000);
		builder.connectString("127.0.0.1:2181,127.0.0.1:2182,127.0.0.1:2183");
		builder.retryPolicy(new RetryNTimes(1, 1000));
		builder.sessionTimeoutMs(5000);

		CuratorFramework framework = builder.build();
		framework.start();
		try {
			framework.blockUntilConnected();
		} catch (InterruptedException e) {
			throw new InitializationException(e.getMessage(), e);
		}

		System.in.read();
	}
 
Example 10
Source File: TestFramework.java    From xian with Apache License 2.0 5 votes vote down vote up
@Test
public void testNamespaceWithWatcher() throws Exception
{
    CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder();
    CuratorFramework client = builder.connectString(server.getConnectString()).namespace("aisa").retryPolicy(new RetryOneTime(1)).build();
    client.start();
    try
    {
        final BlockingQueue<String> queue = new LinkedBlockingQueue<String>();
        Watcher watcher = new Watcher()
        {
            @Override
            public void process(WatchedEvent event)
            {
                try
                {
                    queue.put(event.getPath());
                }
                catch ( InterruptedException e )
                {
                    throw new Error(e);
                }
            }
        };
        client.create().forPath("/base");
        client.getChildren().usingWatcher(watcher).forPath("/base");
        client.create().forPath("/base/child");

        String path = queue.take();
        Assert.assertEquals(path, "/base");
    }
    finally
    {
        CloseableUtils.closeQuietly(client);
    }
}
 
Example 11
Source File: ZKClient.java    From hermes with Apache License 2.0 5 votes vote down vote up
private void startCuratorFramework(ZookeeperEnsemble primaryEnsemble) throws InitializationException {
	Builder builder = CuratorFrameworkFactory.builder();

	builder.connectionTimeoutMs(m_config.getZkConnectionTimeoutMillis());
	builder.maxCloseWaitMs(m_config.getZkCloseWaitMillis());
	builder.namespace(m_config.getZkNamespace());
	builder.retryPolicy(new RetryNTimes(m_config.getZkRetries(), m_config.getSleepMsBetweenRetries()));
	builder.sessionTimeoutMs(m_config.getZkSessionTimeoutMillis());
	builder.threadFactory(HermesThreadFactory.create("Broker-Zk", true));
	builder.ensembleProvider(new EnsembleProvider() {

		@Override
		public void start() throws Exception {
		}

		@Override
		public String getConnectionString() {
			return m_primaryZookeeperEnsemble.get().getConnectionString();
		}

		@Override
		public void close() throws IOException {
		}
	});

	m_client = builder.build();
	m_client.start();
	try {
		m_client.blockUntilConnected();
		log.info("Conneted to zookeeper({}).", JSON.toJSONString(primaryEnsemble));
	} catch (InterruptedException e) {
		throw new InitializationException(e.getMessage(), e);
	}
}
 
Example 12
Source File: ZKClient.java    From hermes with Apache License 2.0 5 votes vote down vote up
private void startCuratorFramework(ZookeeperEnsemble primaryEnsemble) throws InitializationException {
	Builder builder = CuratorFrameworkFactory.builder();

	builder.connectionTimeoutMs(m_config.getZkConnectionTimeoutMillis());
	builder.maxCloseWaitMs(m_config.getZkCloseWaitMillis());
	builder.namespace(m_config.getZkNamespace());
	builder.retryPolicy(new RetryNTimes(m_config.getZkRetries(), m_config.getSleepMsBetweenRetries()));
	builder.sessionTimeoutMs(m_config.getZkSessionTimeoutMillis());
	builder.threadFactory(HermesThreadFactory.create("MetaService-Zk", true));
	builder.ensembleProvider(new EnsembleProvider() {

		@Override
		public void start() throws Exception {
		}

		@Override
		public String getConnectionString() {
			return m_primaryZookeeperEnsemble.get().getConnectionString();
		}

		@Override
		public void close() throws IOException {
		}
	});

	m_client = builder.build();
	m_client.start();
	try {
		m_client.blockUntilConnected();
		log.info("Conneted to zookeeper({}).", JSON.toJSONString(primaryEnsemble));
	} catch (InterruptedException e) {
		throw new InitializationException(e.getMessage(), e);
	}
}
 
Example 13
Source File: ZKUtil.java    From PoseidonX with Apache License 2.0 5 votes vote down vote up
/**
 * 初始化一个Curator
 * @param zkConnetcionStrings
 * @return
 */
private static CuratorFramework createCurator(String zkConnetcionStrings) {
    FixedEnsembleProvider ensembleProvider = new FixedEnsembleProvider(zkConnetcionStrings);
    int sessionTimeout = 60000;
    int connectionTimeout = 15000;
    int retryTimes = 5;
    int retryInterval = 1000;
    int retryCeiling = 60000;
    CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder();
    RetryPolicy retryPolicy = new BoundedExponentialBackoffRetry(retryInterval, retryCeiling, retryTimes);
    builder.ensembleProvider(ensembleProvider).connectionTimeoutMs(connectionTimeout).sessionTimeoutMs(sessionTimeout).retryPolicy(retryPolicy);
    CuratorFramework framework = builder.build();
    return framework;
}
 
Example 14
Source File: CuratorService.java    From kafka-monitor with Apache License 2.0 5 votes vote down vote up
public static CuratorFramework getInstance() {
    if (curator == null) {
        JSONObject zkConfig = configObject.getJSONObject("zookeeper");
        CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder();
        builder.connectString(zkConfig.getString("host"));
        builder.sessionTimeoutMs(zkConfig.getInteger("SessionTimeoutMs"));
        builder.connectionTimeoutMs(zkConfig.getInteger("ConnectionTimeoutMs"));
        builder.retryPolicy(new RetryOneTime(zkConfig.getInteger("RetryOneTime")));

        curator = builder.build();
        curator.start();
    }
    return curator;
}
 
Example 15
Source File: ZookeeperClient.java    From kafka-monitor with Apache License 2.0 5 votes vote down vote up
private void buildCurator(JSONObject zkConfig, boolean isAsync) {
    CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder();
    builder.connectString(zkConfig.getString("host"));
    builder.sessionTimeoutMs(zkConfig.getInteger("SessionTimeoutMs"));
    builder.connectionTimeoutMs(zkConfig.getInteger("ConnectionTimeoutMs"));
    builder.retryPolicy(new RetryOneTime(zkConfig.getInteger("RetryOneTime")));
    curator = builder.build();
    curator.start();
    if (!isAsync) {
        waitingConnect();
    }
}
 
Example 16
Source File: TestFramework.java    From xian with Apache License 2.0 5 votes vote down vote up
@Test
public void testNamespace() throws Exception
{
    final String namespace = "TestNamespace";

    CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder();
    CuratorFramework client = builder.connectString(server.getConnectString()).retryPolicy(new RetryOneTime(1)).namespace(namespace).build();
    client.start();
    try
    {
        String actualPath = client.create().forPath("/test");
        Assert.assertEquals(actualPath, "/test");
        Assert.assertNotNull(client.getZookeeperClient().getZooKeeper().exists("/" + namespace + "/test", false));
        Assert.assertNull(client.getZookeeperClient().getZooKeeper().exists("/test", false));

        actualPath = client.usingNamespace(null).create().forPath("/non");
        Assert.assertEquals(actualPath, "/non");
        Assert.assertNotNull(client.getZookeeperClient().getZooKeeper().exists("/non", false));

        client.create().forPath("/test/child", "hey".getBytes());
        byte[] bytes = client.getData().forPath("/test/child");
        Assert.assertEquals(bytes, "hey".getBytes());

        bytes = client.usingNamespace(null).getData().forPath("/" + namespace + "/test/child");
        Assert.assertEquals(bytes, "hey".getBytes());
    }
    finally
    {
        CloseableUtils.closeQuietly(client);
    }
}
 
Example 17
Source File: Utils.java    From leaf-snowflake with Apache License 2.0 5 votes vote down vote up
public static CuratorFramework newCurator(Map conf , List<String> servers , Object port, String root, ZookeeperAuthInfo info)
{
	List<String> serverPorts = new ArrayList<>();
	for(String zkServer : servers)
	{
		serverPorts.add(zkServer + ":" + Utils.getInt(port));
	}
	String zkStr = StringUtils.join(serverPorts,',') + PathUtils.normalize_path(root);
	CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder();

	setupBuilder(builder,zkStr,conf,info);

	return builder.build();
}
 
Example 18
Source File: TestFramework.java    From xian with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateParentContainers() throws Exception
{
    if ( !checkForContainers() )
    {
        return;
    }

    CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder();
    CuratorFramework client = builder.connectString(server.getConnectString()).retryPolicy(new RetryOneTime(1)).build();
    try
    {
        client.start();
        client.create().creatingParentContainersIfNeeded().forPath("/one/two/three", "foo".getBytes());
        byte[] data = client.getData().forPath("/one/two/three");
        Assert.assertEquals(data, "foo".getBytes());

        client.delete().forPath("/one/two/three");
        new Timing().sleepABit();

        Assert.assertNull(client.checkExists().forPath("/one/two"));
        new Timing().sleepABit();
        Assert.assertNull(client.checkExists().forPath("/one"));
    }
    finally
    {
        CloseableUtils.closeQuietly(client);
    }
}
 
Example 19
Source File: TestPersistentEphemeralNode.java    From xian with Apache License 2.0 5 votes vote down vote up
@Test
public void testNoWritePermission() throws Exception
{
    CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder();
    CuratorFramework client = builder
        .connectString(server.getConnectString())
        .authorization("digest", "me1:pass1".getBytes())
        .retryPolicy(new RetryOneTime(1))
        .build();
    client.start();
    
    ACL acl = new ACL(ZooDefs.Perms.WRITE, ZooDefs.Ids.AUTH_IDS);
    List<ACL> aclList = Lists.newArrayList(acl);
    client.create().withACL(aclList).forPath(DIR, new byte[0]);
    client.close();
    
    PersistentEphemeralNode node = null;
    try {
    	//New client without authentication
    	client = newCurator();
    
    	node = new PersistentEphemeralNode(client, PersistentEphemeralNode.Mode.EPHEMERAL, PATH,
                                                               new byte[0]);
    	node.start();
    
        node.waitForInitialCreate(timing.seconds(), TimeUnit.SECONDS);
        assertNodeDoesNotExist(client, PATH);
        assertTrue(node.isAuthFailure());
    } finally {
    	if(node != null) {
    	    node.close();
    	}
    	
    	client.close();
    }
}
 
Example 20
Source File: CuratorService.java    From hadoop with Apache License 2.0 4 votes vote down vote up
/**
 * Create a new curator instance off the root path; using configuration
 * options provided in the service configuration to set timeouts and
 * retry policy.
 * @return the newly created creator
 */
private CuratorFramework createCurator() throws IOException {
  Configuration conf = getConfig();
  createEnsembleProvider();
  int sessionTimeout = conf.getInt(KEY_REGISTRY_ZK_SESSION_TIMEOUT,
      DEFAULT_ZK_SESSION_TIMEOUT);
  int connectionTimeout = conf.getInt(KEY_REGISTRY_ZK_CONNECTION_TIMEOUT,
      DEFAULT_ZK_CONNECTION_TIMEOUT);
  int retryTimes = conf.getInt(KEY_REGISTRY_ZK_RETRY_TIMES,
      DEFAULT_ZK_RETRY_TIMES);
  int retryInterval = conf.getInt(KEY_REGISTRY_ZK_RETRY_INTERVAL,
      DEFAULT_ZK_RETRY_INTERVAL);
  int retryCeiling = conf.getInt(KEY_REGISTRY_ZK_RETRY_CEILING,
      DEFAULT_ZK_RETRY_CEILING);

  if (LOG.isDebugEnabled()) {
    LOG.debug("Creating CuratorService with connection {}",
        connectionDescription);
  }
  CuratorFramework framework;

  synchronized (CuratorService.class) {
    // set the security options

    // build up the curator itself
    CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder();
    builder.ensembleProvider(ensembleProvider)
     .connectionTimeoutMs(connectionTimeout)
     .sessionTimeoutMs(sessionTimeout)

     .retryPolicy(new BoundedExponentialBackoffRetry(retryInterval,
         retryCeiling,
         retryTimes));

    // set up the builder AND any JVM context
    registrySecurity.applySecurityEnvironment(builder);
    //log them
    securityConnectionDiagnostics = buildSecurityDiagnostics();
    framework = builder.build();
    framework.start();
  }

  return framework;
}