org.apache.curator.framework.api.CreateBuilder Java Examples

The following examples show how to use org.apache.curator.framework.api.CreateBuilder. 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: CuratorZookeeperClient.java    From pinpoint with Apache License 2.0 6 votes vote down vote up
private void createNode0(CreateNodeMessage message, boolean orSet) throws PinpointZookeeperException {
    checkState();

    try {
        CuratorFramework client = connectionManager.getZookeeperClient();

        CreateBuilder createBuilder = client.create();
        if (message.isCreatingParentPathsIfNeeded()) {
            createBuilder.creatingParentsIfNeeded();
        }
        if (orSet) {
            createBuilder.orSetData();
        }

        String nodePath = message.getNodePath();
        byte[] data = message.getData();
        createBuilder.withMode(CreateMode.EPHEMERAL).forPath(nodePath, data);
    } catch (Exception e) {
        PinpointZookeeperException exception = ZookeeperExceptionResolver.resolve(e);
        throw exception;
    }
}
 
Example #2
Source File: SetupStepsTest.java    From atlas with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldCreateSetupInProgressNode() throws Exception {
    Set<SetupStep> steps = new LinkedHashSet<>();
    SetupStep setupStep1 = mock(SetupStep.class);
    steps.add(setupStep1);

    when(configuration.
            getString(HAConfiguration.ATLAS_SERVER_HA_ZK_ROOT_KEY, HAConfiguration.ATLAS_SERVER_ZK_ROOT_DEFAULT)).
            thenReturn(HAConfiguration.ATLAS_SERVER_ZK_ROOT_DEFAULT);
    when(configuration.getString(HAConfiguration.HA_ZOOKEEPER_ACL)).thenReturn("digest:user:pwd");

    List<ACL> aclList = Arrays.asList(new ACL(ZooDefs.Perms.ALL, new Id("digest", "user:pwd")));
    setupServerIdSelectionMocks();
    CreateBuilder createBuilder = setupSetupInProgressPathMocks(aclList).getLeft();

    InterProcessMutex lock = mock(InterProcessMutex.class);
    when(curatorFactory.lockInstance(HAConfiguration.ATLAS_SERVER_ZK_ROOT_DEFAULT)).
            thenReturn(lock);
    SetupSteps setupSteps = new SetupSteps(steps, curatorFactory, configuration);
    setupSteps.runSetup();

    verify(createBuilder).withACL(aclList);
    verify(createBuilder).forPath(HAConfiguration.ATLAS_SERVER_ZK_ROOT_DEFAULT+SetupSteps.SETUP_IN_PROGRESS_NODE,
            "id2".getBytes(Charsets.UTF_8));
}
 
Example #3
Source File: SetupStepsTest.java    From incubator-atlas with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldCreateSetupInProgressNode() throws Exception {
    Set<SetupStep> steps = new LinkedHashSet<>();
    SetupStep setupStep1 = mock(SetupStep.class);
    steps.add(setupStep1);

    when(configuration.
            getString(HAConfiguration.ATLAS_SERVER_HA_ZK_ROOT_KEY, HAConfiguration.ATLAS_SERVER_ZK_ROOT_DEFAULT)).
            thenReturn(HAConfiguration.ATLAS_SERVER_ZK_ROOT_DEFAULT);
    when(configuration.getString(HAConfiguration.HA_ZOOKEEPER_ACL)).thenReturn("digest:user:pwd");

    List<ACL> aclList = Arrays.asList(new ACL(ZooDefs.Perms.ALL, new Id("digest", "user:pwd")));
    setupServerIdSelectionMocks();
    CreateBuilder createBuilder = setupSetupInProgressPathMocks(aclList).getLeft();

    InterProcessMutex lock = mock(InterProcessMutex.class);
    when(curatorFactory.lockInstance(HAConfiguration.ATLAS_SERVER_ZK_ROOT_DEFAULT)).
            thenReturn(lock);
    SetupSteps setupSteps = new SetupSteps(steps, curatorFactory, configuration);
    setupSteps.runSetup();

    verify(createBuilder).withACL(aclList);
    verify(createBuilder).forPath(HAConfiguration.ATLAS_SERVER_ZK_ROOT_DEFAULT+SetupSteps.SETUP_IN_PROGRESS_NODE,
            "id2".getBytes(Charsets.UTF_8));
}
 
Example #4
Source File: CuratorStateManagerTest.java    From incubator-heron with Apache License 2.0 5 votes vote down vote up
/**
 * test createNode method
 * @throws Exception
 */
@Test
public void testCreateNode() throws Exception {
  CuratorStateManager spyStateManager = spy(new CuratorStateManager());
  CuratorFramework mockClient = mock(CuratorFramework.class);
  CreateBuilder mockCreateBuilder = mock(CreateBuilder.class);
  // Mockito doesn't support mock type-parametrized class, thus suppress the warning
  @SuppressWarnings("rawtypes")
  ACLBackgroundPathAndBytesable mockPath = spy(ACLBackgroundPathAndBytesable.class);

  final byte[] data = new byte[10];

  doReturn(mockClient)
      .when(spyStateManager).getCuratorClient();
  doReturn(true)
      .when(mockClient).blockUntilConnected(anyInt(), any(TimeUnit.class));
  doReturn(mockCreateBuilder)
      .when(mockClient).create();
  doReturn(mockPath)
      .when(mockCreateBuilder).withMode(any(CreateMode.class));

  spyStateManager.initialize(config);

  // Verify the node is created successfully
  ListenableFuture<Boolean> result = spyStateManager.createNode(PATH, data, false);
  verify(mockCreateBuilder).withMode(any(CreateMode.class));
  verify(mockPath).forPath(PATH, data);
  assertTrue(result.get());
}
 
Example #5
Source File: ZkState.java    From jstorm with Apache License 2.0 5 votes vote down vote up
public void writeBytes(String path, byte[] bytes) {
    try {
        if (_curator.checkExists().forPath(path) == null) {
            CreateBuilder builder = _curator.create();
            ProtectACLCreateModePathAndBytesable<String> createAble = (ProtectACLCreateModePathAndBytesable<String>) builder
                    .creatingParentsIfNeeded();
            createAble.withMode(CreateMode.PERSISTENT).forPath(path, bytes);
        } else {
            _curator.setData().forPath(path, bytes);
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example #6
Source File: ActiveInstanceStateTest.java    From incubator-atlas with Apache License 2.0 5 votes vote down vote up
@Test
public void testSharedPathIsCreatedWithRightACLIfNotExists() throws Exception {

    when(configuration.getString(HAConfiguration.ATLAS_SERVER_ADDRESS_PREFIX +"id1")).thenReturn(HOST_PORT);
    when(configuration.getString(HAConfiguration.HA_ZOOKEEPER_ACL)).thenReturn("sasl:[email protected]");
    when(configuration.getString(
            HAConfiguration.ATLAS_SERVER_HA_ZK_ROOT_KEY, HAConfiguration.ATLAS_SERVER_ZK_ROOT_DEFAULT)).
            thenReturn(HAConfiguration.ATLAS_SERVER_ZK_ROOT_DEFAULT);


    when(curatorFactory.clientInstance()).thenReturn(curatorFramework);

    ExistsBuilder existsBuilder = mock(ExistsBuilder.class);
    when(curatorFramework.checkExists()).thenReturn(existsBuilder);
    when(existsBuilder.forPath(getPath())).thenReturn(null);

    CreateBuilder createBuilder = mock(CreateBuilder.class);
    when(curatorFramework.create()).thenReturn(createBuilder);
    when(createBuilder.withMode(CreateMode.EPHEMERAL)).thenReturn(createBuilder);
    ACL expectedAcl = new ACL(ZooDefs.Perms.ALL, new Id("sasl", "[email protected]"));
    when(createBuilder.
            withACL(Arrays.asList(new ACL[]{expectedAcl}))).thenReturn(createBuilder);

    SetDataBuilder setDataBuilder = mock(SetDataBuilder.class);
    when(curatorFramework.setData()).thenReturn(setDataBuilder);

    ActiveInstanceState activeInstanceState = new ActiveInstanceState(configuration, curatorFactory);
    activeInstanceState.update("id1");

    verify(createBuilder).forPath(getPath());
}
 
Example #7
Source File: ActiveInstanceStateTest.java    From incubator-atlas with Apache License 2.0 5 votes vote down vote up
@Test
public void testSharedPathIsCreatedIfNotExists() throws Exception {

    when(configuration.getString(HAConfiguration.ATLAS_SERVER_ADDRESS_PREFIX +"id1")).thenReturn(HOST_PORT);
    when(configuration.getString(
            HAConfiguration.ATLAS_SERVER_HA_ZK_ROOT_KEY, HAConfiguration.ATLAS_SERVER_ZK_ROOT_DEFAULT)).
            thenReturn(HAConfiguration.ATLAS_SERVER_ZK_ROOT_DEFAULT);

    when(curatorFactory.clientInstance()).thenReturn(curatorFramework);

    ExistsBuilder existsBuilder = mock(ExistsBuilder.class);
    when(curatorFramework.checkExists()).thenReturn(existsBuilder);
    when(existsBuilder.forPath(getPath())).thenReturn(null);

    CreateBuilder createBuilder = mock(CreateBuilder.class);
    when(curatorFramework.create()).thenReturn(createBuilder);
    when(createBuilder.withMode(CreateMode.EPHEMERAL)).thenReturn(createBuilder);
    when(createBuilder.withACL(ZooDefs.Ids.OPEN_ACL_UNSAFE)).thenReturn(createBuilder);

    SetDataBuilder setDataBuilder = mock(SetDataBuilder.class);
    when(curatorFramework.setData()).thenReturn(setDataBuilder);

    ActiveInstanceState activeInstanceState = new ActiveInstanceState(configuration, curatorFactory);
    activeInstanceState.update("id1");

    verify(createBuilder).forPath(getPath());
}
 
Example #8
Source File: SetupStepsTest.java    From incubator-atlas with Apache License 2.0 5 votes vote down vote up
private Pair<CreateBuilder, DeleteBuilder> setupSetupInProgressPathMocks(List<ACL> acls, Stat stat) throws Exception {
    when(curatorFactory.clientInstance()).thenReturn(client);
    CreateBuilder createBuilder = mock(CreateBuilder.class);
    when(createBuilder.withACL(acls)).thenReturn(createBuilder);
    when(client.create()).thenReturn(createBuilder);
    DeleteBuilder deleteBuilder = mock(DeleteBuilder.class);
    when(client.delete()).thenReturn(deleteBuilder);
    Pair<CreateBuilder, DeleteBuilder> pair = Pair.of(createBuilder, deleteBuilder);
    ExistsBuilder existsBuilder = mock(ExistsBuilder.class);
    when(client.checkExists()).thenReturn(existsBuilder);
    when(existsBuilder.forPath(HAConfiguration.ATLAS_SERVER_ZK_ROOT_DEFAULT+SetupSteps.SETUP_IN_PROGRESS_NODE)).
            thenReturn(stat);
    return pair;
}
 
Example #9
Source File: DistributedLockServiceCuratorImplTest.java    From micro-server with Apache License 2.0 5 votes vote down vote up
@Test
public void createNonExisting2() throws Exception {
	CuratorFramework client = mock(CuratorFramework.class);
	ExistsBuilder builder = mock(ExistsBuilder.class);
	CreateBuilder createBuilder = mock(CreateBuilder.class);
	
	ProtectACLCreateModeStatPathAndBytesable<String> protector = mock(ProtectACLCreateModeStatPathAndBytesable.class);
	when(builder.forPath(anyString())).thenReturn(new Stat());
	when(client.checkExists()).thenReturn(builder);
	when(client.create()).thenReturn(createBuilder);
	when(createBuilder.creatingParentContainersIfNeeded()).thenReturn(protector);
	new DistributedLockServiceCuratorImpl(client, "/", 0);
	verify(protector, times(0)).forPath(anyString(), anyObject());
}
 
Example #10
Source File: DistributedLockServiceCuratorImplTest.java    From micro-server with Apache License 2.0 5 votes vote down vote up
@Test
public void createNonExisting() throws Exception {
	CuratorFramework client = mock(CuratorFramework.class);
	ExistsBuilder builder = mock(ExistsBuilder.class);
	CreateBuilder createBuilder = mock(CreateBuilder.class);
	
	
	ProtectACLCreateModeStatPathAndBytesable<String> protector = mock(ProtectACLCreateModeStatPathAndBytesable.class);
	when(builder.forPath(anyString())).thenReturn(null);
	when(client.checkExists()).thenReturn(builder);
	when(client.create()).thenReturn(createBuilder);
	when(createBuilder.creatingParentContainersIfNeeded()).thenReturn((ProtectACLCreateModeStatPathAndBytesable<String>)protector);
	new DistributedLockServiceCuratorImpl(client, "/", 0);
	verify(protector).forPath(anyString(), anyObject());
}
 
Example #11
Source File: ZKStoreHelper.java    From pravega with Apache License 2.0 5 votes vote down vote up
CompletableFuture<String> createPersistentSequentialZNode(final String path, final byte[] data) {
    final CompletableFuture<String> result = new CompletableFuture<>();

    try {
        CreateBuilder createBuilder = client.create();
        BackgroundCallback callback = callback(x -> result.complete(x.getName()),
                result::completeExceptionally, path);
        createBuilder.creatingParentsIfNeeded().withMode(CreateMode.PERSISTENT_SEQUENTIAL)
                     .inBackground(callback, executor).forPath(path, data);
    } catch (Exception e) {
        result.completeExceptionally(StoreException.create(StoreException.Type.UNKNOWN, e, path));
    }

    return result;
}
 
Example #12
Source File: ZKStoreHelper.java    From pravega with Apache License 2.0 5 votes vote down vote up
CompletableFuture<String> createEphemeralSequentialZNode(final String path) {
    final CompletableFuture<String> result = new CompletableFuture<>();

    try {
        CreateBuilder createBuilder = client.create();
        BackgroundCallback callback = callback(x -> result.complete(x.getName()),
                result::completeExceptionally, path);
        createBuilder.creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL_SEQUENTIAL)
                     .inBackground(callback, executor).forPath(path);
    } catch (Exception e) {
        result.completeExceptionally(StoreException.create(StoreException.Type.UNKNOWN, e, path));
    }

    return result;
}
 
Example #13
Source File: ActiveInstanceStateTest.java    From atlas with Apache License 2.0 5 votes vote down vote up
@Test
   public void testSharedPathIsCreatedWithRightACLIfNotExists() throws Exception {

       when(configuration.getString(HAConfiguration.ATLAS_SERVER_ADDRESS_PREFIX +"id1")).thenReturn(HOST_PORT);
       when(configuration.getString(HAConfiguration.HA_ZOOKEEPER_ACL)).thenReturn("sasl:[email protected]");
       when(configuration.getString(
               HAConfiguration.ATLAS_SERVER_HA_ZK_ROOT_KEY, HAConfiguration.ATLAS_SERVER_ZK_ROOT_DEFAULT)).
               thenReturn(HAConfiguration.ATLAS_SERVER_ZK_ROOT_DEFAULT);


       when(curatorFactory.clientInstance()).thenReturn(curatorFramework);

       ExistsBuilder existsBuilder = mock(ExistsBuilder.class);
       when(curatorFramework.checkExists()).thenReturn(existsBuilder);
       when(existsBuilder.forPath(getPath())).thenReturn(null);

       CreateBuilder createBuilder = mock(CreateBuilder.class);
       when(curatorFramework.create()).thenReturn(createBuilder);
       when(createBuilder.withMode(CreateMode.EPHEMERAL)).thenReturn(createBuilder);
ACL expectedAcl = new ACL(ZooDefs.Perms.ALL, new Id("sasl", "[email protected]"));
ACL expectedAcl1 = new ACL(ZooDefs.Perms.READ, new Id("world", "anyone"));
       when(createBuilder.
               withACL(Arrays.asList(new ACL[]{expectedAcl,expectedAcl1}))).thenReturn(createBuilder);


       SetDataBuilder setDataBuilder = mock(SetDataBuilder.class);
       when(curatorFramework.setData()).thenReturn(setDataBuilder);

       ActiveInstanceState activeInstanceState = new ActiveInstanceState(configuration, curatorFactory);
       activeInstanceState.update("id1");

       verify(createBuilder).forPath(getPath());
   }
 
Example #14
Source File: ActiveInstanceStateTest.java    From atlas with Apache License 2.0 5 votes vote down vote up
@Test
public void testSharedPathIsCreatedIfNotExists() throws Exception {

    when(configuration.getString(HAConfiguration.ATLAS_SERVER_ADDRESS_PREFIX +"id1")).thenReturn(HOST_PORT);
    when(configuration.getString(
            HAConfiguration.ATLAS_SERVER_HA_ZK_ROOT_KEY, HAConfiguration.ATLAS_SERVER_ZK_ROOT_DEFAULT)).
            thenReturn(HAConfiguration.ATLAS_SERVER_ZK_ROOT_DEFAULT);

    when(curatorFactory.clientInstance()).thenReturn(curatorFramework);

    ExistsBuilder existsBuilder = mock(ExistsBuilder.class);
    when(curatorFramework.checkExists()).thenReturn(existsBuilder);
    when(existsBuilder.forPath(getPath())).thenReturn(null);

    CreateBuilder createBuilder = mock(CreateBuilder.class);
    when(curatorFramework.create()).thenReturn(createBuilder);
    when(createBuilder.withMode(CreateMode.EPHEMERAL)).thenReturn(createBuilder);
    when(createBuilder.withACL(ZooDefs.Ids.OPEN_ACL_UNSAFE)).thenReturn(createBuilder);

    SetDataBuilder setDataBuilder = mock(SetDataBuilder.class);
    when(curatorFramework.setData()).thenReturn(setDataBuilder);

    ActiveInstanceState activeInstanceState = new ActiveInstanceState(configuration, curatorFactory);
    activeInstanceState.update("id1");

    verify(createBuilder).forPath(getPath());
}
 
Example #15
Source File: SetupStepsTest.java    From atlas with Apache License 2.0 5 votes vote down vote up
private Pair<CreateBuilder, DeleteBuilder> setupSetupInProgressPathMocks(List<ACL> acls, Stat stat) throws Exception {
    when(curatorFactory.clientInstance()).thenReturn(client);
    CreateBuilder createBuilder = mock(CreateBuilder.class);
    when(createBuilder.withACL(acls)).thenReturn(createBuilder);
    when(client.create()).thenReturn(createBuilder);
    DeleteBuilder deleteBuilder = mock(DeleteBuilder.class);
    when(client.delete()).thenReturn(deleteBuilder);
    Pair<CreateBuilder, DeleteBuilder> pair = Pair.of(createBuilder, deleteBuilder);
    ExistsBuilder existsBuilder = mock(ExistsBuilder.class);
    when(client.checkExists()).thenReturn(existsBuilder);
    when(existsBuilder.forPath(HAConfiguration.ATLAS_SERVER_ZK_ROOT_DEFAULT+SetupSteps.SETUP_IN_PROGRESS_NODE)).
            thenReturn(stat);
    return pair;
}
 
Example #16
Source File: ZooKeeperLeaderElectionTest.java    From Flink-CEPplus with Apache License 2.0 4 votes vote down vote up
/**
 *  Test that errors in the {@link LeaderElectionService} are correctly forwarded to the
 *  {@link LeaderContender}.
 */
@Test
public void testExceptionForwarding() throws Exception {
	ZooKeeperLeaderElectionService leaderElectionService = null;
	ZooKeeperLeaderRetrievalService leaderRetrievalService = null;
	TestingListener listener = new TestingListener();
	TestingContender testingContender;

	CuratorFramework client;
	final CreateBuilder mockCreateBuilder = mock(CreateBuilder.class, Mockito.RETURNS_DEEP_STUBS);
	final Exception testException = new Exception("Test exception");

	try {
		client = spy(ZooKeeperUtils.startCuratorFramework(configuration));

		Answer<CreateBuilder> answer = new Answer<CreateBuilder>() {
			private int counter = 0;

			@Override
			public CreateBuilder answer(InvocationOnMock invocation) throws Throwable {
				counter++;

				// at first we have to create the leader latch, there it mustn't fail yet
				if (counter < 2) {
					return (CreateBuilder) invocation.callRealMethod();
				} else {
					return mockCreateBuilder;
				}
			}
		};

		doAnswer(answer).when(client).create();

		when(
			mockCreateBuilder
			.creatingParentsIfNeeded()
			.withMode(Matchers.any(CreateMode.class))
			.forPath(anyString(), any(byte[].class))).thenThrow(testException);

		leaderElectionService = new ZooKeeperLeaderElectionService(client, "/latch", "/leader");
		leaderRetrievalService = ZooKeeperUtils.createLeaderRetrievalService(client, configuration);

		testingContender = new TestingContender(TEST_URL, leaderElectionService);

		leaderElectionService.start(testingContender);
		leaderRetrievalService.start(listener);

		testingContender.waitForError(timeout);

		assertNotNull(testingContender.getError());
		assertEquals(testException, testingContender.getError().getCause());
	} finally {
		if (leaderElectionService != null) {
			leaderElectionService.stop();
		}

		if (leaderRetrievalService != null) {
			leaderRetrievalService.stop();
		}
	}
}
 
Example #17
Source File: MockCurator.java    From vespa with Apache License 2.0 4 votes vote down vote up
@Override
public CreateBuilder create() {
    return new MockCreateBuilder();
}
 
Example #18
Source File: SetupStepsTest.java    From incubator-atlas with Apache License 2.0 4 votes vote down vote up
private Pair<CreateBuilder, DeleteBuilder> setupSetupInProgressPathMocks(List<ACL> acls) throws Exception {
    return setupSetupInProgressPathMocks(acls, null);
}
 
Example #19
Source File: SetupStepsTest.java    From atlas with Apache License 2.0 4 votes vote down vote up
private Pair<CreateBuilder, DeleteBuilder> setupSetupInProgressPathMocks(List<ACL> acls) throws Exception {
    return setupSetupInProgressPathMocks(acls, null);
}
 
Example #20
Source File: ZooKeeperLeaderElectionTest.java    From flink with Apache License 2.0 4 votes vote down vote up
/**
 *  Test that errors in the {@link LeaderElectionService} are correctly forwarded to the
 *  {@link LeaderContender}.
 */
@Test
public void testExceptionForwarding() throws Exception {
	ZooKeeperLeaderElectionService leaderElectionService = null;
	ZooKeeperLeaderRetrievalService leaderRetrievalService = null;
	TestingListener listener = new TestingListener();
	TestingContender testingContender;

	CuratorFramework client;
	final CreateBuilder mockCreateBuilder = mock(CreateBuilder.class, Mockito.RETURNS_DEEP_STUBS);
	final Exception testException = new Exception("Test exception");

	try {
		client = spy(ZooKeeperUtils.startCuratorFramework(configuration));

		Answer<CreateBuilder> answer = new Answer<CreateBuilder>() {
			private int counter = 0;

			@Override
			public CreateBuilder answer(InvocationOnMock invocation) throws Throwable {
				counter++;

				// at first we have to create the leader latch, there it mustn't fail yet
				if (counter < 2) {
					return (CreateBuilder) invocation.callRealMethod();
				} else {
					return mockCreateBuilder;
				}
			}
		};

		doAnswer(answer).when(client).create();

		when(
			mockCreateBuilder
			.creatingParentsIfNeeded()
			.withMode(Matchers.any(CreateMode.class))
			.forPath(anyString(), any(byte[].class))).thenThrow(testException);

		leaderElectionService = new ZooKeeperLeaderElectionService(client, "/latch", "/leader");
		leaderRetrievalService = ZooKeeperUtils.createLeaderRetrievalService(client, configuration);

		testingContender = new TestingContender(TEST_URL, leaderElectionService);

		leaderElectionService.start(testingContender);
		leaderRetrievalService.start(listener);

		testingContender.waitForError(timeout);

		assertNotNull(testingContender.getError());
		assertEquals(testException, testingContender.getError().getCause());
	} finally {
		if (leaderElectionService != null) {
			leaderElectionService.stop();
		}

		if (leaderRetrievalService != null) {
			leaderRetrievalService.stop();
		}
	}
}