mousio.etcd4j.promises.EtcdResponsePromise Java Examples

The following examples show how to use mousio.etcd4j.promises.EtcdResponsePromise. 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: TestFunctionality.java    From etcd4j with Apache License 2.0 6 votes vote down vote up
@Test
public void testIfCleanClose() throws IOException, EtcdException, EtcdAuthenticationException, TimeoutException {
  etcd.setRetryHandler(new RetryWithExponentialBackOff(20, 4, 1000));

  EtcdResponsePromise<EtcdKeysResponse> p = etcd.get("etcd4j_test/test").waitForChange().send();
  etcd.close();

  try {
    p.get();
    fail();
  } catch (IOException e){
    // should be catched because connection was canceled
    if (!(e.getCause() instanceof CancellationException)) {
      fail();
    }
  }
}
 
Example #2
Source File: EtcdConfigWatcherRegister.java    From skywalking with Apache License 2.0 6 votes vote down vote up
private void registerKeyListeners(final Set<String> keys) {
    for (final String key : keys) {
        String dataId = "/" + settings.getGroup() + "/" + key;
        if (listenersByKey.containsKey(dataId)) {
            continue;
        }

        listenersByKey.putIfAbsent(dataId, p -> {
            onDataValueChanged(p, dataId);
        });

        try {
            EtcdResponsePromise<EtcdKeysResponse> responsePromise = client.get(dataId).waitForChange().send();
            responsePromise.addListener(listenersByKey.get(dataId));
            responsePromiseByKey.putIfAbsent(dataId, responsePromise);

            // the key is newly added, read the config for the first time
            EtcdResponsePromise<EtcdKeysResponse> promise = client.get(dataId).send();
            onDataValueChanged(promise, dataId);
        } catch (Exception e) {
            throw new EtcdConfigException("wait for etcd value change fail", e);
        }
    }
}
 
Example #3
Source File: TestFunctionality.java    From etcd4j with Apache License 2.0 6 votes vote down vote up
/**
 * In order key tests
 */
@Test
public void testWait() throws IOException, EtcdException, EtcdAuthenticationException, InterruptedException, TimeoutException {
  EtcdResponsePromise<EtcdKeysResponse> p = etcd.get("etcd4j_test/test").waitForChange().send();

  // Ensure the change is received after the listen command is received.
  new Timer().schedule(new TimerTask() {
    @Override
    public void run() {
      try {
        etcd.put("etcd4j_test/test", "changed").send().get();
      } catch (IOException | EtcdException | EtcdAuthenticationException | TimeoutException e) {
        fail();
      }
    }
  }, 20);

  EtcdKeysResponse r = p.get();
  assertEquals("changed", r.node.value);
}
 
Example #4
Source File: EtcdClientRetryPolicyTest.java    From etcd4j with Apache License 2.0 6 votes vote down vote up
@Test
public void testSuccessAfterRetrying() throws Exception {

    whenHttp(server)
            .match(get("/v2/keys/foo"))
            .then(sequence(FAILURE, SUCCESS));

    try (EtcdClient etcd = new EtcdClient(serverURI)) {

        EtcdResponsePromise<EtcdKeysResponse> promise = etcd.get("foo")
                .setRetryPolicy(new RetryNTimes(1, 10))
                .send();

        EtcdKeysResponse resp = promise.get();

        assertThat(resp.node.value).isEqualTo("bar");
        assertThat(promise.getException()).isNull();

    }

    verifyHttp(server).times(2,
            method(Method.GET),
            uri("/v2/keys/foo")
    );
}
 
Example #5
Source File: EtcdClientRetryPolicyTest.java    From etcd4j with Apache License 2.0 6 votes vote down vote up
@Test
public void testSuccessWithoutRetrying() throws Exception {

    whenHttp(server)
            .match(get("/v2/keys/foo"))
            .then(SUCCESS);

    try (EtcdClient etcd = new EtcdClient(serverURI)) {

        EtcdResponsePromise<EtcdKeysResponse> promise = etcd.get("foo")
                .setRetryPolicy(new RetryNTimes(1, 10))
                .send();

        EtcdKeysResponse resp = promise.get();

        assertThat(resp.node.value).isEqualTo("bar");
        assertThat(promise.getException()).isNull();

    }

    verifyHttp(server).once(
            method(Method.GET),
            uri("/v2/keys/foo")
    );
}
 
Example #6
Source File: EtcdFlagFieldUpdater.java    From java-flagz with MIT License 5 votes vote down vote up
private List<EtcdNode> fetchAllFlagzNodes() {
  try {
    EtcdResponsePromise<EtcdKeysResponse> promise = client
        .get(this.directoryPrefix)
        .dir()
        .send();
    EtcdKeysResponse response = promise.get();
    // NOTE: We use etcdIndex here, because we know we got latest data up to this point.
    lastKnownFlagzModificationIndex = response.etcdIndex;
    return MoreObjects.firstNonNull(response.node.nodes, ImmutableList.<EtcdNode>of());
  } catch (IOException | EtcdException
      | TimeoutException | EtcdAuthenticationException exception) {
    throw new EtcdFlagFieldUpdaterException.EtcdFetchingFailed(exception);
  }
}
 
Example #7
Source File: ITEtcdConfigurationTest.java    From skywalking with Apache License 2.0 5 votes vote down vote up
private boolean publishConfig(String key, String group, String value) {
    try {
        client.putDir(group).send().get();
        EtcdResponsePromise<EtcdKeysResponse> promise = client.put(generateKey(key, group), value).send();
        promise.get();
        return true;
    } catch (Exception e) {
        return false;
    }
}
 
Example #8
Source File: EtcdCoordinator.java    From skywalking with Apache License 2.0 5 votes vote down vote up
@Override
public void registerRemote(RemoteInstance remoteInstance) throws ServiceRegisterException {

    if (needUsingInternalAddr()) {
        remoteInstance = new RemoteInstance(new Address(config.getInternalComHost(), config.getInternalComPort(), true));
    }

    this.selfAddress = remoteInstance.getAddress();
    TelemetryRelatedContext.INSTANCE.setId(selfAddress.toString());

    EtcdEndpoint endpoint = new EtcdEndpoint.Builder().serviceName(serviceName)
                                                      .host(selfAddress.getHost())
                                                      .port(selfAddress.getPort())
                                                      .build();
    try {
        client.putDir(serviceName).send();
        String key = buildKey(serviceName, selfAddress, remoteInstance);
        String json = new Gson().toJson(endpoint);
        EtcdResponsePromise<EtcdKeysResponse> promise = client.put(key, json).ttl(KEY_TTL).send();
        //check register.
        promise.get();
        renew(client, key, json);
    } catch (Exception e) {
        throw new ServiceRegisterException(e.getMessage());
    }

}
 
Example #9
Source File: EtcdClientRetryPolicyTest.java    From etcd4j with Apache License 2.0 5 votes vote down vote up
@Test
public void testFailureAfterRetrying() throws Exception {

    whenHttp(server)
            .match(get("/v2/keys/foo"))
            .then(FAILURE);

    try (EtcdClient etcd = new EtcdClient(serverURI)) {

        EtcdResponsePromise<EtcdKeysResponse> promise = etcd.get("foo")
                .setRetryPolicy(new RetryNTimes(1, 3))
                .send();

        Exception err = null;

        try {
            promise.get();
        } catch (Exception e) {
            err = e;
        }

        assertThat(err).isNotNull();
        assertThat(err).isEqualTo(promise.getException());

    }

    verifyHttp(server).times(4,
            method(Method.GET),
            uri("/v2/keys/foo")
    );
}
 
Example #10
Source File: EtcdClientWrapper.java    From haven-platform with Apache License 2.0 5 votes vote down vote up
@Override
public KvNode set(String key, String value) {
    try {
        EtcdResponsePromise<EtcdKeysResponse> send = etcd.put(key, value).send();
        EtcdKeysResponse resp = send.get();
        log.debug("set value {} for key {}", resp.node.value, resp.node.key);
        return toNode(resp);
    } catch (Exception e) {
        throw Throwables.asRuntime(e);
    }
}
 
Example #11
Source File: EtcdClientRetryPolicyTest.java    From etcd4j with Apache License 2.0 5 votes vote down vote up
@Test
public void testFailureWithoutRetrying() throws Exception {

    whenHttp(server)
            .match(get("/v2/keys/foo"))
            .then(FAILURE);

    try (EtcdClient etcd = new EtcdClient(serverURI)) {

        EtcdResponsePromise<EtcdKeysResponse> promise = etcd.get("foo")
                .setRetryPolicy(new RetryNTimes(1, 0))
                .send();

        Exception err = null;

        try {
            promise.get();
        } catch (Exception e) {
            err = e;
        }

        assertThat(err).isNotNull();
        assertThat(err).isEqualTo(promise.getException());

    }

    verifyHttp(server).once(
            method(Method.GET),
            uri("/v2/keys/foo")
    );

}
 
Example #12
Source File: EtcdKeyRequest.java    From etcd4j with Apache License 2.0 4 votes vote down vote up
@Override
public EtcdResponsePromise<EtcdKeysResponse> send() throws IOException {
  return this.clientImpl.send(this);
}
 
Example #13
Source File: AbstractEtcdRequest.java    From etcd4j with Apache License 2.0 4 votes vote down vote up
@Override
public EtcdResponsePromise<R> send() throws IOException {
  return clientImpl.send(this);
}
 
Example #14
Source File: EtcdConfigWatcherRegisterTest.java    From skywalking with Apache License 2.0 4 votes vote down vote up
@Before
@Test
public void shouldReadConfigs() throws Exception {
    final String group = "skywalking";
    final String testKey1 = "receiver-trace.default.slowDBAccessThreshold";
    final String testVal1 = "test";
    final String testKey2 = "testKey";
    final String testVal2 = "testVal";

    final EtcdServerSettings mockSettings = mock(EtcdServerSettings.class);
    when(mockSettings.getGroup()).thenReturn(group);
    mockStatic(EtcdUtils.class);

    List<URI> uris = mock(List.class);
    when(EtcdUtils.parse(any())).thenReturn(uris);

    final EtcdClient client = PowerMockito.mock(EtcdClient.class);
    whenNew(EtcdClient.class).withAnyArguments().thenReturn(client);

    String port = System.getProperty("etcd.port");
    URI uri = new URI("http://localhost:" + port);
    List<URI> urisArray = spy(ArrayList.class);
    urisArray.add(uri);
    URI[] array = urisArray.toArray(new URI[] {});
    when(uris.toArray(new URI[] {})).thenReturn(array);

    final EtcdConfigWatcherRegister mockRegister = spy(new EtcdConfigWatcherRegister(mockSettings));

    Whitebox.setInternalState(mockRegister, "client", client);
    Whitebox.setInternalState(mockRegister, "settings", mockSettings);

    final EtcdKeysResponse response = PowerMockito.mock(EtcdKeysResponse.class);
    final EtcdKeysResponse response1 = PowerMockito.mock(EtcdKeysResponse.class);

    final EtcdKeyGetRequest request = PowerMockito.mock(EtcdKeyGetRequest.class);

    when(client.get("/skywalking/receiver-trace.default.slowDBAccessThreshold")).thenReturn(request);
    when(request.waitForChange()).thenReturn(request);

    final EtcdResponsePromise<EtcdKeysResponse> promise = mock(EtcdResponsePromise.class);
    final ResponsePromise<EtcdKeysResponse> responseResponsePromise = mock(ResponsePromise.class);
    when(request.send()).thenReturn(promise);
    when(promise.get()).thenReturn(response);
    when(responseResponsePromise.get()).thenReturn(response);

    final EtcdKeysResponse.EtcdNode node = mock(EtcdKeysResponse.EtcdNode.class);
    when(response.getNode()).thenReturn(node);
    when(node.getKey()).thenReturn("/skywalking/receiver-trace.default.slowDBAccessThreshold");
    when(node.getValue()).thenReturn("test");

    final EtcdKeyGetRequest request1 = mock(EtcdKeyGetRequest.class);
    when(client.get("/skywalking/testKey")).thenReturn(request1);
    when(request1.waitForChange()).thenReturn(request1);
    final EtcdResponsePromise<EtcdKeysResponse> promise1 = mock(EtcdResponsePromise.class);
    final ResponsePromise<EtcdKeysResponse> responseResponsePromise1 = mock(ResponsePromise.class);
    when(request1.send()).thenReturn(promise1);
    when(promise1.get()).thenReturn(response1);
    when(responseResponsePromise1.get()).thenReturn(response1);

    final EtcdKeysResponse.EtcdNode node1 = mock(EtcdKeysResponse.EtcdNode.class);
    when(response1.getNode()).thenReturn(node1);
    when(node1.getKey()).thenReturn("/skywalking/testKey");
    when(node1.getValue()).thenReturn("testVal");

    final ConfigTable configTable = mockRegister.readConfig(Sets.newHashSet(testKey1, testKey2)).get();

    assertEquals(2, configTable.getItems().size());
    Map<String, String> kvs = new HashMap<>();
    for (ConfigTable.ConfigItem item : configTable.getItems()) {
        kvs.put(item.getName(), item.getValue());
    }
    assertEquals(testVal1, kvs.get(testKey1));
    assertEquals(testVal2, kvs.get(testKey2));
}
 
Example #15
Source File: EtcdClientWrapper.java    From haven-platform with Apache License 2.0 4 votes vote down vote up
private EtcdKeysResponse executeRequest(EtcdKeyRequest req) throws Exception {
    EtcdResponsePromise<EtcdKeysResponse> send = req.send();
    return send.get();
}
 
Example #16
Source File: EtcdRequest.java    From etcd4j with Apache License 2.0 2 votes vote down vote up
/**
 * Get promise for request
 *
 * @return promise
 */
public EtcdResponsePromise<R> getPromise() {
  return promise;
}
 
Example #17
Source File: EtcdRequest.java    From etcd4j with Apache License 2.0 2 votes vote down vote up
/**
 * Set promise on request
 *
 * @param promise to set
 */
public void setPromise(EtcdResponsePromise<R> promise) {
  this.promise = promise;
}
 
Example #18
Source File: EtcdRequest.java    From etcd4j with Apache License 2.0 2 votes vote down vote up
/**
 * Send request to etcd server
 *
 * @return Promise
 * @throws java.io.IOException if sending fails
 */
public abstract EtcdResponsePromise<R> send() throws IOException;
 
Example #19
Source File: EtcdClientImpl.java    From etcd4j with Apache License 2.0 2 votes vote down vote up
/**
 * Sends a request to the server
 *
 * @param request to send
 * @param <R>     Type of response
 * @return A Promise
 * @throws java.io.IOException if IO failure while sending
 */
public <R> EtcdResponsePromise<R> send(EtcdRequest<R> request) throws IOException;