org.asynchttpclient.Response Java Examples

The following examples show how to use org.asynchttpclient.Response. 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: HttpAPIPinsAsyncClientTest.java    From blynk-server with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void testChangeLabelPropertyViaGet() throws Exception {
    Future<Response> f = httpclient.prepareGet(httpsServerUrl + clientPair.token + "/update/v4?label=My-New-Label").execute();
    Response response = f.get();

    assertEquals(200, response.getStatusCode());
    verify(clientPair.appClient.responseMock, timeout(500)).channelRead(any(), eq(setProperty(111, "1-0 4 label My-New-Label")));

    clientPair.appClient.reset();

    clientPair.appClient.send("loadProfileGzipped");
    Profile profile = clientPair.appClient.parseProfile(1);

    Widget widget = profile.dashBoards[0].findWidgetByPin(0, (short) 4, PinType.VIRTUAL);
    assertNotNull(widget);
    assertEquals("My-New-Label", widget.label);
}
 
Example #2
Source File: AsyncCompletionHandlerWithTracingAndMdcSupportTest.java    From riposte with Apache License 2.0 6 votes vote down vote up
@Test
public void onCompleted_handles_circuit_breaker_but_does_nothing_else_if_completableFutureResponse_is_already_completed()
    throws Throwable {
    // given
    CompletableFuture<String> cfMock = mock(CompletableFuture.class);
    Whitebox.setInternalState(handlerSpy, "completableFutureResponse", cfMock);
    doReturn(true).when(cfMock).isDone();

    // when
    Response ignoredResult = handlerSpy.onCompleted(responseMock);

    // then
    verify(circuitBreakerManualTaskMock).handleEvent(responseMock);

    verify(cfMock).isDone();
    verifyNoMoreInteractions(cfMock);

    assertThat(ignoredResult).isEqualTo(responseMock);
    verifyNoInteractions(responseMock);
}
 
Example #3
Source File: HttpAPIPinsAsyncClientTest.java    From blynk-server with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void testChangeOffLabelPropertyViaGet() throws Exception {
    clientPair.appClient.reset();
    clientPair.appClient.updateWidget(1, "{\"id\":1, \"width\":1, \"height\":1, \"x\":1, \"y\":1, \"label\":\"Some Text\", \"type\":\"BUTTON\",         \"pinType\":\"VIRTUAL\", \"pin\":1, \"value\":\"1\"}");
    clientPair.appClient.verifyResult(ok(1));

    Future<Response> f = httpclient.prepareGet(httpsServerUrl + clientPair.token + "/update/v1?offLabel=newOffButtonLabel").execute();
    Response response = f.get();

    assertEquals(200, response.getStatusCode());
    verify(clientPair.appClient.responseMock, timeout(500)).channelRead(any(), eq(setProperty(111, "1-0 1 offLabel newOffButtonLabel")));

    clientPair.appClient.reset();
    clientPair.appClient.send("loadProfileGzipped");
    Profile profile = clientPair.appClient.parseProfile(1);

    Button button = (Button) profile.dashBoards[0].findWidgetByPin(0, (short) 1, PinType.VIRTUAL);
    assertNotNull(button);
    assertEquals("newOffButtonLabel", button.offLabel);
}
 
Example #4
Source File: RecurlyClient.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
protected <T extends BaseRecurlyModel> ListenableFuture<T> doPOST(String resourcePath, final Class<T> clazz, RecurlyObjectSerializer serializer, @Nullable String apiVersion) {
    final SettableFuture<T> future = SettableFuture.create();

    try {
        post(baseURL + resourcePath, apiVersion)
                .setBody(serializer.serialize())
                .execute(new AsyncCompletionHandler<Void>() {
                    @Override
                    public Void onCompleted(Response response) throws Exception {
                        setResponse(response, future, clazz);
                        return null;
                    }
                });
    } catch (Exception ex) {
        future.setException(ex);
    }

    return future;
}
 
Example #5
Source File: WebhookTest.java    From blynk-server with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void testWebhookWorksWithBlynkHttpApiWithPlaceholder() throws Exception {
    WebHook webHook = new WebHook();
    webHook.url = httpServerUrl + "4ae3851817194e2596cf1b7103603ef8/update/V124";
    webHook.method = PUT;
    webHook.headers = new Header[] {new Header("Content-Type", "application/json")};
    webHook.body = "[%s]";
    webHook.pin = 123;
    webHook.pinType = PinType.VIRTUAL;
    webHook.width = 2;
    webHook.height = 1;

    clientPair.appClient.createWidget(1, webHook);
    clientPair.appClient.verifyResult(ok(1));

    clientPair.hardwareClient.send("hardware vw 123 10");
    verify(clientPair.hardwareClient.responseMock, after(1000).times(0)).channelRead(any(), any());

    Future<Response> f = httpclient.prepareGet(httpServerUrl + "4ae3851817194e2596cf1b7103603ef8/get/V124").execute();
    Response response = f.get();

    assertEquals(200, response.getStatusCode());
    List<String> values = consumeJsonPinValues(response.getResponseBody());
    assertEquals(1, values.size());
    assertEquals("10", values.get(0));
}
 
Example #6
Source File: HttpAPIPinsAsyncClientTest.java    From blynk-server with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void testPutViaGetRequestSingleValue() throws Exception {
    Future<Response> f = httpclient.prepareGet(httpsServerUrl + "4ae3851817194e2596cf1b7103603ef8/update/v11?value=10").execute();
    Response response = f.get();
    assertEquals(200, response.getStatusCode());
    assertEquals("*", response.getHeader(ACCESS_CONTROL_ALLOW_ORIGIN));


    f = httpclient.prepareGet(httpsServerUrl + "4ae3851817194e2596cf1b7103603ef8/get/v11").execute();
    response = f.get();

    assertEquals(200, response.getStatusCode());
    List<String> values = TestUtil.consumeJsonPinValues(response.getResponseBody());
    assertEquals(1, values.size());
    assertEquals("10", values.get(0));
    assertEquals("*", response.getHeader(ACCESS_CONTROL_ALLOW_ORIGIN));
}
 
Example #7
Source File: AsyncHttpConnector.java    From pulsar with Apache License 2.0 6 votes vote down vote up
@Override
public Future<?> apply(ClientRequest jerseyRequest, AsyncConnectorCallback callback) {
    CompletableFuture<Response> responseFuture = retryOrTimeOut(jerseyRequest);
    responseFuture.whenComplete(((response, throwable) -> {
        if (throwable != null) {
            callback.failure(throwable);
        } else {
            ClientResponse jerseyResponse =
                    new ClientResponse(Status.fromStatusCode(response.getStatusCode()), jerseyRequest);
            response.getHeaders().forEach(e -> jerseyResponse.header(e.getKey(), e.getValue()));
            if (response.hasResponseBody()) {
                jerseyResponse.setEntityStream(response.getResponseBodyAsStream());
            }
            callback.response(jerseyResponse);
        }
    }));
    return responseFuture;
}
 
Example #8
Source File: TacPublishTestService.java    From tac with MIT License 6 votes vote down vote up
/**
 * test with http .
 *
 * @param instId
 * @param msCode
 * @param params
 * @return
 */
private TacResult<?> onlinePublishTestHttp(Long instId, String msCode, Map<String, Object> params) {

    AsyncHttpClient asyncHttpClient = asyncHttpClient();

    ListenableFuture<Response> execute = asyncHttpClient.preparePost(containerWebApi + "/" + msCode)
        .addHeader("Content-Type", "application/json;charset=UTF-8").setBody(JSONObject.toJSONString(params))
        .execute();
    Response response;
    try {
        response = execute.get(10, TimeUnit.SECONDS);
        if (response.getStatusCode() == HttpConstants.ResponseStatusCodes.OK_200) {
            TacResult tacResult = JSONObject.parseObject(response.getResponseBody(), TacResult.class);
            return tacResult;
        }
        log.error("onlinePublishTestHttp msCode:{} params:{} {}", msCode, params, response);
        throw new IllegalStateException("request engine error " + msCode);
    } catch (Exception e) {
        throw new IllegalStateException(e.getMessage(), e);
    }

}
 
Example #9
Source File: HttpClientTest.java    From tac with MIT License 6 votes vote down vote up
@Test
public void test() throws InterruptedException, ExecutionException, TimeoutException {

    JSONObject data = new JSONObject();
    data.put("name", "ljinshuan");

    AsyncHttpClient asyncHttpClient = asyncHttpClient();

    ListenableFuture<Response> execute = asyncHttpClient.preparePost("http://localhost:8001/api/tac/execute/shuan")
        .addHeader("Content-Type", "application/json;charset=UTF-8").setBody(data.toJSONString()).execute();
    Response response = execute.get(10, TimeUnit.SECONDS);

    if (response.getStatusCode() == HttpConstants.ResponseStatusCodes.OK_200) {
        TacResult tacResult = JSONObject.parseObject(response.getResponseBody(), TacResult.class);

        System.out.println(tacResult);
    }
    System.out.println(response);
}
 
Example #10
Source File: AsyncHttpClientITest.java    From java-specialagent with Apache License 2.0 6 votes vote down vote up
public static void main(final String[] args) throws Exception {
  try (final AsyncHttpClient client = new DefaultAsyncHttpClient()) {
    final Request request = new RequestBuilder(HttpConstants.Methods.GET).setUrl("http://www.google.com").build();
    final int statusCode = client.executeRequest(request, new AsyncCompletionHandler<Response>() {
      @Override
      public Response onCompleted(final Response response) {
        TestUtil.checkActiveSpan();
        return response;
      }
    }).get(10, TimeUnit.SECONDS).getStatusCode();

    if (200 != statusCode)
      throw new AssertionError("ERROR: response: " + statusCode);

    TestUtil.checkSpan(true, new ComponentSpanCount("java-asynchttpclient", 1), new ComponentSpanCount("netty", 1));
  }
}
 
Example #11
Source File: DRPCQueryResultPubscriberTest.java    From bullet-storm with Apache License 2.0 6 votes vote down vote up
@Test(timeOut = 5000L)
public void testReadingOkResponse() throws Exception {
    PubSubMessage expected = new PubSubMessage("foo", "response");

    CompletableFuture<Response> response = getOkFuture(getOkResponse(expected.asJSON()));
    AsyncHttpClient mockClient = mockClientWith(response);
    pubscriber.setClient(mockClient);

    pubscriber.send(new PubSubMessage("foo", "bar"));
    // This is async (but practically still very fast since we mocked the response), so need a timeout.
    PubSubMessage actual = fetchAsync().get();

    Assert.assertNotNull(actual);
    Assert.assertEquals(actual.getId(), expected.getId());
    Assert.assertEquals(actual.getContent(), expected.getContent());
}
 
Example #12
Source File: AsyncTrelloHttpClient2.java    From trello-java-wrapper with Apache License 2.0 6 votes vote down vote up
@Override
public <T> T putForObject(String url, Object object, final Class<T> responseType, String... params) {
    try {
        byte[] body = this.writer.writeValueAsBytes(object);
        Future<T> f = asyncHttpClient.preparePut(expandUrl(url, params)).setBody(body).execute(
                new AsyncCompletionHandler<T>() {

                    @Override
                    public T onCompleted(Response response) throws Exception {
                        return reader.forType(responseType).readValue(response.getResponseBody());
                    }

                    @Override
                    public void onThrowable(Throwable t) {
                        throw new TrelloHttpException(t);
                    }
                });
        return f.get();
    } catch (IOException | InterruptedException | ExecutionException e) {
        throw new TrelloHttpException(e);
    }
}
 
Example #13
Source File: DeleteIndexRequestBuilder.java    From flummi with Apache License 2.0 6 votes vote down vote up
public Void execute() {
        if (indexNames.length == 0) {
            throw new RuntimeException("index names are missing");
        }
        try {
            String url = RequestBuilderUtil.buildUrl(indexNames, null, null);
            Response response = httpClient.prepareDelete(url)
.addHeader(CONTENT_TYPE,APPL_JSON)
                    .execute().get();
            if (response.getStatusCode() >= 300 && response.getStatusCode() != 404) {
                throw RequestBuilderUtil.toHttpServerErrorException(response);
            }
            return null;
        } catch (InterruptedException | ExecutionException e) {
            throw new RuntimeException(e);
        }
    }
 
Example #14
Source File: WebhookTest.java    From blynk-server with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void testWebhookWorksWithBlynkHttpApiWithArrayPlaceholder2() throws Exception {
    WebHook webHook = new WebHook();
    webHook.url = httpServerUrl + "4ae3851817194e2596cf1b7103603ef8/update/V124";
    webHook.method = PUT;
    webHook.headers = new Header[] {new Header("Content-Type", "application/json")};
    webHook.body = "[/pin[0]/]";
    webHook.pin = 123;
    webHook.pinType = PinType.VIRTUAL;
    webHook.width = 2;
    webHook.height = 1;

    clientPair.appClient.createWidget(1, webHook);
    clientPair.appClient.verifyResult(ok(1));

    clientPair.hardwareClient.send("hardware vw 123 10");
    verify(clientPair.hardwareClient.responseMock, after(1000).times(0)).channelRead(any(), any());

    Future<Response> f = httpclient.prepareGet(httpServerUrl + "4ae3851817194e2596cf1b7103603ef8/get/V124").execute();
    Response response = f.get();

    assertEquals(200, response.getStatusCode());
    List<String> values = consumeJsonPinValues(response.getResponseBody());
    assertEquals(1, values.size());
    assertEquals("10", values.get(0));
}
 
Example #15
Source File: HttpAPIPinsAsyncClientTest.java    From blynk-server with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void testPutViaGetRequestMultipleValue() throws Exception {
    Future<Response> f = httpclient.prepareGet(httpsServerUrl + "4ae3851817194e2596cf1b7103603ef8/update/v11?value=10&value=11").execute();
    Response response = f.get();
    assertEquals(200, response.getStatusCode());
    assertEquals("*", response.getHeader(ACCESS_CONTROL_ALLOW_ORIGIN));


    f = httpclient.prepareGet(httpsServerUrl + "4ae3851817194e2596cf1b7103603ef8/get/v11").execute();
    response = f.get();

    assertEquals(200, response.getStatusCode());
    List<String> values = TestUtil.consumeJsonPinValues(response.getResponseBody());
    assertEquals(2, values.size());
    assertEquals("10", values.get(0));
    assertEquals("11", values.get(1));
    assertEquals("*", response.getHeader(ACCESS_CONTROL_ALLOW_ORIGIN));
}
 
Example #16
Source File: WebhookTest.java    From blynk-server with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void testReservedREgexCharForReplaceArgumentsInWebhook() throws Exception {
    WebHook webHook = new WebHook();
    webHook.url = httpServerUrl + "4ae3851817194e2596cf1b7103603ef8/update/V124";
    webHook.method = PUT;
    webHook.headers = new Header[] {new Header("Content-Type", "application/json")};
    webHook.body = "[\"/pin/\"]";
    webHook.pin = 123;
    webHook.pinType = PinType.VIRTUAL;
    webHook.width = 2;
    webHook.height = 1;

    clientPair.appClient.createWidget(1, webHook);
    clientPair.appClient.verifyResult(ok(1));

    clientPair.hardwareClient.send("hardware vw 123 $$");
    verify(clientPair.hardwareClient.responseMock, after(1000).times(0)).channelRead(any(), any());

    Future<Response> f = httpclient.prepareGet(httpServerUrl + "4ae3851817194e2596cf1b7103603ef8/get/V124").execute();
    Response response = f.get();

    assertEquals(200, response.getStatusCode());
    List<String> values = consumeJsonPinValues(response.getResponseBody());
    assertEquals(1, values.size());
    assertEquals("$$", values.get(0));
}
 
Example #17
Source File: IndicesAdminClientTest.java    From flummi with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldPrepareExists() throws ExecutionException, InterruptedException, IOException {
    //Given
    when(httpClient.prepareHead(anyString())).thenReturn(boundRequestBuilder);
    when(boundRequestBuilder.setBody(anyString())).thenReturn(boundRequestBuilder);
    when(boundRequestBuilder.addHeader(anyString(),anyString())).thenReturn(boundRequestBuilder);
    final ListenableFuture<Response> listenableFuture = mock(ListenableFuture.class);
    when(boundRequestBuilder.execute()).thenReturn(listenableFuture);
    final Response response = mock(Response.class);
    when(listenableFuture.get()).thenReturn(response);
    when(response.getStatusCode()).thenReturn(200);
    final IndicesExistsRequestBuilder indicesExistsRequestBuilder = indicesAdminClient.prepareExists("someIndexName");

    //When
    indicesExistsRequestBuilder.execute();

    //Then
    verify(httpClient).prepareHead("/someIndexName");
}
 
Example #18
Source File: Zendesk.java    From zendesk-java-client with Apache License 2.0 6 votes vote down vote up
@Override
public T onCompleted(Response response) throws Exception {
    logResponse(response);
    if (isStatus2xx(response)) {
        if (typeParams.length > 0) {
            JavaType type = mapper.getTypeFactory().constructParametricType(clazz, typeParams);
            return mapper.convertValue(mapper.readTree(response.getResponseBodyAsStream()).get(name), type);
        }
        return mapper.convertValue(mapper.readTree(response.getResponseBodyAsStream()).get(name), clazz);
    } else if (isRateLimitResponse(response)) {
        throw new ZendeskResponseRateLimitException(response);
    }
    if (response.getStatusCode() == 404) {
        return null;
    }
    throw new ZendeskResponseException(response);
}
 
Example #19
Source File: NettyMessages.java    From selenium with Apache License 2.0 5 votes vote down vote up
public static HttpResponse toSeleniumResponse(Response response) {
  HttpResponse toReturn = new HttpResponse();

  toReturn.setStatus(response.getStatusCode());

  toReturn.setContent(! response.hasResponseBody()
                      ? empty()
                      : memoize(response::getResponseBodyAsStream));

  response.getHeaders().names().forEach(
      name -> response.getHeaders(name).forEach(value -> toReturn.addHeader(name, value)));

  return toReturn;
}
 
Example #20
Source File: DRPCQueryResultPubscriberTest.java    From bullet-storm with Apache License 2.0 5 votes vote down vote up
private CompletableFuture<Response> getOkFuture(Response response) {
    CompletableFuture<Response> finished = CompletableFuture.completedFuture(response);
    CompletableFuture<Response> mock = mock(CompletableFuture.class);
    // This is the weird bit. We mock the call to exceptionally to return the finished response so that chaining
    // a thenAcceptAsync on it will call the consumer of it with the finished response. This is why it looks
    // weird: mocking the exceptionally to take the "good" path.
    doReturn(finished).when(mock).exceptionally(any());
    // So if we do get to thenAccept on our mock, we should throw an exception because we shouldn't get there.
    doThrow(new RuntimeException("Good futures don't throw")).when(mock).thenAcceptAsync(any());
    return mock;
}
 
Example #21
Source File: DRPCQueryResultPubscriberTest.java    From bullet-storm with Apache License 2.0 5 votes vote down vote up
@Test(timeOut = 5000L)
public void testReadingNullResponse() throws Exception {
    CompletableFuture<Response> response = getOkFuture(null);
    AsyncHttpClient mockClient = mockClientWith(response);
    pubscriber.setClient(mockClient);

    pubscriber.send(new PubSubMessage("foo", "bar"));
    // This is async (but practically still very fast since we mocked the response), so need a timeout.
    PubSubMessage actual = fetchAsync().get();

    Assert.assertNotNull(actual);
    Assert.assertEquals(actual.getId(), "foo");
    Assert.assertEquals(actual.getContent(), CANNOT_REACH_DRPC.asJSONClip());
}
 
Example #22
Source File: HttpAPIPinsAsyncClientTest.java    From blynk-server with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void testGetWithNonExistingPin() throws Exception {
    Future<Response> f = httpclient.prepareGet(httpsServerUrl + "4ae3851817194e2596cf1b7103603ef8/get/v11").execute();
    Response response = f.get();
    assertEquals(400, response.getStatusCode());
    assertEquals("Requested pin doesn't exist in the app.", response.getResponseBody());
    assertEquals("*", response.getHeader(ACCESS_CONTROL_ALLOW_ORIGIN));
}
 
Example #23
Source File: AsyncHttpClientHelperTagAdapter.java    From riposte with Apache License 2.0 5 votes vote down vote up
@Nullable
@Override
public String getSpanHandlerTagValue(
    @Nullable RequestBuilderWrapper request, @Nullable Response response
) {
    return "riposte.asynchttpclienthelper";
}
 
Example #24
Source File: Zendesk.java    From zendesk-java-client with Apache License 2.0 5 votes vote down vote up
private void logResponse(Response response) throws IOException {
    if (logger.isDebugEnabled()) {
        logger.debug("Response HTTP/{} {}\n{}", response.getStatusCode(), response.getStatusText(),
                response.getResponseBody());
    }
    if (logger.isTraceEnabled()) {
        logger.trace("Response headers {}", response.getHeaders());
    }
}
 
Example #25
Source File: CarreraAsyncRequest.java    From DDMQ with Apache License 2.0 5 votes vote down vote up
@Override
public Response onCompleted(Response response) {
    inflightRequests.remove(this);
    job.setState("HTTP.onComplete");
    MetricUtils.httpRequestLatencyMetric(job, TimeUtils.getElapseTime(startTime));
    if (response.getStatusCode() != HttpStatus.SC_OK) {
        MetricUtils.httpRequestFailureMetric(job, Integer.toString(response.getStatusCode()));
        LOGGER.info("Action Result: HttpAccess[result:exception,code:{},url:{},request:{},used:{}ms]",
                response.getStatusCode(), getUrl(), this, TimeUtils.getElapseTime(startTime));
        delayRetryRequest(DEFAULT_RETRY_DELAY << Math.min(job.getErrorRetryCnt(), MAX_RETRY_DELAY_FACTOR));
        job.incErrorRetryCnt();
    } else {
        ProcessResult result = processResponseContent(response.getResponseBody(), job);
        long elapse = TimeUtils.getElapseTime(startTime);
        MetricUtils.httpRequestSuccessMetric(job, result == ProcessResult.OK, lastRequestErrno);
        if (result == ProcessResult.OK) {
            LOGGER.info("Action Result: HttpAccess[result:success,request:{},used:{}ms,url:{}]", this, elapse, getUrl());
            job.onFinished(true);
        } else if (result == ProcessResult.FAIL) {
            LOGGER.info("Action Result: HttpAccess[result:failure,request:{},used:{}ms,response:{}]",
                    this, elapse, response.getResponseBody());
            DROP_LOGGER.info("[request:{},url:{},response:{},used:{}ms,httpParams:{},msg:{}]",
                    this, getUrl(), response.getResponseBody(), elapse, job.getHttpParams(),
                    StringUtils.newString(job.getCommonMessage().getValue()));
            job.onFinished(true);
        } else { //DELAY_RETRY
            LOGGER.info("Action Result: HttpAccess[result:retry,url:{},request:{},response:{},used:{}ms]",
                    getUrl(), this, response.getResponseBody(), elapse);
        }
    }
    return response;
}
 
Example #26
Source File: AsyncHttpClientHelperTagAdapter.java    From riposte with Apache License 2.0 5 votes vote down vote up
@Nullable
@Override
public Integer getResponseHttpStatus(@Nullable Response response) {
    if (response == null) {
        return null;
    }

    return response.getStatusCode();
}
 
Example #27
Source File: DRPCQueryResultPubscriberTest.java    From bullet-storm with Apache License 2.0 5 votes vote down vote up
private Response getResponse(int status, String statusText, String body) {
    Response mock = mock(Response.class);
    doReturn(status).when(mock).getStatusCode();
    doReturn(statusText).when(mock).getStatusText();
    doReturn(body).when(mock).getResponseBody();
    return mock;
}
 
Example #28
Source File: EventorProcessor.java    From blynk-server with GNU General Public License v3.0 5 votes vote down vote up
private void twit(DashBoard dash, String body) {
    if (Twitter.isWrongBody(body)) {
        log.debug("Wrong twit body.");
        return;
    }

    Twitter twitterWidget = dash.getTwitterWidget();

    if (twitterWidget == null
            || twitterWidget.token == null
            || twitterWidget.token.isEmpty()
            || twitterWidget.secret == null
            || twitterWidget.secret.isEmpty()) {
        log.debug("User has no access token provided for eventor twit.");
        return;
    }

    twitterWrapper.send(twitterWidget.token, twitterWidget.secret, body,
            new AsyncCompletionHandler<>() {
                @Override
                public Response onCompleted(Response response) {
                    if (response.getStatusCode() != HttpResponseStatus.OK.code()) {
                        log.debug("Error sending twit from eventor. Reason : {}.", response.getResponseBody());
                    }
                    return response;
                }

                @Override
                public void onThrowable(Throwable t) {
                    log.debug("Error sending twit from eventor.", t);
                }
            }
    );
}
 
Example #29
Source File: AsyncHttpClientPluginIT.java    From glowroot with Apache License 2.0 5 votes vote down vote up
@Override
public void transactionMarker() throws Exception {
    AsyncHttpClient asyncHttpClient = new DefaultAsyncHttpClient();
    final CountDownLatch latch = new CountDownLatch(1);
    final AtomicInteger statusCode = new AtomicInteger();
    asyncHttpClient.prepareGet("http://localhost:" + getPort() + "/hello3/")
            .execute(new AsyncCompletionHandler<Response>() {
                @Override
                public Response onCompleted(Response response) throws Exception {
                    latch.countDown();
                    return null;
                }
                @Override
                public State onStatusReceived(HttpResponseStatus status) {
                    statusCode.set(status.getStatusCode());
                    return null;
                }
                @Override
                public void onThrowable(Throwable t) {
                    t.printStackTrace();
                }
            });
    latch.await();
    asyncHttpClient.close();
    if (statusCode.get() != 200) {
        throw new IllegalStateException("Unexpected status code: " + statusCode);
    }
}
 
Example #30
Source File: DefaultAsyncHttpClientHelperSpanNamingAndTaggingStrategy.java    From riposte with Apache License 2.0 5 votes vote down vote up
@Override
public void doHandleResponseTaggingAndFinalSpanName(
    @NotNull Span span,
    @Nullable RequestBuilderWrapper request,
    @Nullable Response response,
    @Nullable Throwable error
) {
    tagAndNamingStrategy.handleResponseTaggingAndFinalSpanName(
        span, request, response, error, tagAndNamingAdapter
    );
}