org.asynchttpclient.HttpResponseStatus Java Examples

The following examples show how to use org.asynchttpclient.HttpResponseStatus. 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: AbstractAsyncHttpClientInstrumentation.java    From apm-agent-java with Apache License 2.0 5 votes vote down vote up
@Advice.OnMethodEnter(suppress = Throwable.class)
private static void onMethodEnter(@Advice.This AsyncHandler<?> asyncHandler, @Advice.Local("span") Span span, @Advice.Argument(0) HttpResponseStatus status) {
    span = handlerSpanMap.get(asyncHandler);
    if (span != null) {
        span.activate();
    }
}
 
Example #2
Source File: AbstractAsyncHttpClientInstrumentation.java    From apm-agent-java with Apache License 2.0 5 votes vote down vote up
@Advice.OnMethodExit(suppress = Throwable.class)
private static void onMethodExit(@Nullable @Advice.Local("span") Span span, @Advice.Argument(0) HttpResponseStatus status) {
    if (span != null) {
        span.getContext().getHttp().withStatusCode(status.getStatusCode());
        span.deactivate();
    }
}
 
Example #3
Source File: AdlsAsyncFileReader.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
@Override
public State onStatusReceived(HttpResponseStatus status) throws Exception {
  // The REST service provides error information as part of the response
  // body when the response code is 400 or greater, and not a 401 (auth error).
  if (status.getStatusCode() >= io.netty.handler.codec.http.HttpResponseStatus.BAD_REQUEST.code() &&
      status.getStatusCode() != HttpConstants.ResponseStatusCodes.UNAUTHORIZED_401) {
    isErrorResponse = true;
    errCode = status.getStatusCode();
  }
  return super.onStatusReceived(status);
}
 
Example #4
Source File: BufferBasedCompletionHandler.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
@Override
public State onStatusReceived(HttpResponseStatus status) throws Exception {
  // The REST service provides error information as part of the response
  // body when the response code is 400 or greater, and not a 401 (auth error).
  requestFailed = (status.getStatusCode() >= 400);
  return super.onStatusReceived(status);
}
 
Example #5
Source File: TestAzureAsyncReader.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
private AzureAsyncReader prepareAsyncReader(final String responseBody, final int responseCode) {
  // Prepare response
  AsyncHttpClient client = mock(AsyncHttpClient.class);
  Response response = mock(Response.class);
  HttpResponseStatus status = mock(HttpResponseStatus.class);
  when(status.getStatusCode()).thenReturn(responseCode);
  when(response.getResponseBody()).thenReturn(responseBody);

  CompletableFuture<Response> future = new CompletableFuture<>(); //CompletableFuture.completedFuture(response);
  ListenableFuture<Response> resFuture = mock(ListenableFuture.class);
  when(resFuture.toCompletableFuture()).thenReturn(future);
  LocalDateTime versionDate = LocalDateTime.now(ZoneId.of("GMT")).minusDays(2);

  when(client.executeRequest(any(Request.class), any(AsyncCompletionHandler.class))).then(invocationOnMock -> {
    AsyncCompletionHandler<Response> responseHandler = invocationOnMock.getArgument(1, AsyncCompletionHandler.class);
    assertEquals(responseHandler.getClass(), BufferBasedCompletionHandler.class);
    responseHandler.onStatusReceived(status);
    try {
      responseHandler.onCompleted(response);
    } catch (Exception e) {
      future.completeExceptionally(e);
    }
    return resFuture;
  });

  AzureAsyncReader azureAsyncReader = spy(new AzureAsyncReader(
    "account", new Path("container/directory/file_00.parquet"),
    getMockAuthTokenProvider(), String.valueOf(versionDate.atZone(ZoneId.of("GMT")).toInstant().toEpochMilli()),
    true, client
  ));
  return azureAsyncReader;

}
 
Example #6
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 #7
Source File: TracingAsyncHandler.java    From java-specialagent with Apache License 2.0 4 votes vote down vote up
@Override
public State onStatusReceived(final HttpResponseStatus responseStatus) throws Exception {
  span.setTag(Tags.HTTP_STATUS.getKey(), responseStatus.getStatusCode());
  return handler.onStatusReceived(responseStatus);
}
 
Example #8
Source File: BAOSBasedCompletionHandler.java    From dremio-oss with Apache License 2.0 4 votes vote down vote up
@Override
public State onStatusReceived(final HttpResponseStatus status) throws Exception {
  requestFailed = (status.getStatusCode() >= 400);
  return super.onStatusReceived(status);
}
 
Example #9
Source File: TestAzureAsyncContainerProvider.java    From dremio-oss with Apache License 2.0 4 votes vote down vote up
@Test
public void testListContainers() throws IOException, ExecutionException, InterruptedException {
  AsyncHttpClient client = mock(AsyncHttpClient.class);
  Response response = mock(Response.class);
  when(response.getHeader(any(String.class))).thenReturn("");
  HttpResponseStatus status = mock(HttpResponseStatus.class);
  when(status.getStatusCode()).thenReturn(206);

  byte[] dfsCoreResponseBodyBytesPage1 = readStaticResponse("dfs-core-container-response-page1.json");
  RandomBytesResponseDispatcher dfsCoreResponseDispatcherPage1 = new RandomBytesResponseDispatcher(dfsCoreResponseBodyBytesPage1);

  byte[] dfsCoreResponseBodyBytesPage2 = readStaticResponse("dfs-core-container-response-page2.json");
  RandomBytesResponseDispatcher dfsCoreResponseDispatcherPage2 = new RandomBytesResponseDispatcher(dfsCoreResponseBodyBytesPage2);

  byte[] dfsCoreEmptyResponseBytes = readStaticResponse("dfs-core-container-empty.json");
  RandomBytesResponseDispatcher dfsCoreEmptyResponseDispatcher = new RandomBytesResponseDispatcher(dfsCoreEmptyResponseBytes);

  CompletableFuture<Response> future = CompletableFuture.completedFuture(response);
  ListenableFuture<Response> resFuture = mock(ListenableFuture.class);
  when(resFuture.toCompletableFuture()).thenReturn(future);
  when(resFuture.get()).thenReturn(response);

  when(client.executeRequest(any(Request.class), any(AsyncCompletionHandler.class))).then(invocationOnMock -> {
    Request req = invocationOnMock.getArgument(0, Request.class);
    AsyncCompletionHandler handler = invocationOnMock.getArgument(1, AsyncCompletionHandler.class);

    assertTrue(req.getUrl().startsWith("https://azurestoragev2hier.dfs.core.windows.net"));
    assertNotNull(req.getHeaders().get("Date"));
    assertNotNull(req.getHeaders().get("x-ms-client-request-id"));
    assertEquals("2019-07-07", req.getHeaders().get("x-ms-version")); // edit only if you're upgrading client
    assertEquals("Bearer testtoken", req.getHeaders().get("Authorization"));
    List<NameValuePair> queryParams = URLEncodedUtils.parse(new URI(req.getUrl()), StandardCharsets.UTF_8);
    String continuationKey = queryParams.stream()
      .filter(param -> param.getName().equalsIgnoreCase("continuation")).findAny()
      .map(NameValuePair::getValue).orElse("");

    // Return empty response if continuation key is not present. Return data in continuation call.
    // This is to ensure that the plugin makes another call when there's no data but continuation key present.
    if ("page1container1".equals(continuationKey)) {
      when(response.getHeader("x-ms-continuation")).thenReturn("page2container1");
      while (dfsCoreResponseDispatcherPage1.isNotFinished()) {
        handler.onBodyPartReceived(dfsCoreResponseDispatcherPage1.getNextBodyPart());
      }
    } else if ("page2container1".equals(continuationKey)) {
      when(response.getHeader("x-ms-continuation")).thenReturn("");
      while (dfsCoreResponseDispatcherPage2.isNotFinished()) {
        handler.onBodyPartReceived(dfsCoreResponseDispatcherPage2.getNextBodyPart());
      }
    } else {
      when(response.getHeader("x-ms-continuation")).thenReturn("page1container1");
      while (dfsCoreEmptyResponseDispatcher.isNotFinished()) {
        handler.onBodyPartReceived(dfsCoreEmptyResponseDispatcher.getNextBodyPart());
      }
    }

    handler.onStatusReceived(status);
    handler.onCompleted(response);
    return resFuture;
  });

  AzureStorageFileSystem parentClass = mock(AzureStorageFileSystem.class);
  AzureAuthTokenProvider authTokenProvider = getMockAuthTokenProvider();
  AzureAsyncContainerProvider containerProvider = new AzureAsyncContainerProvider(
    client, "azurestoragev2hier", authTokenProvider, parentClass, true);

  List<String> receivedContainers = containerProvider.getContainerCreators()
    .map(AzureStorageFileSystem.ContainerCreatorImpl.class::cast)
    .map(AzureStorageFileSystem.ContainerCreatorImpl::getName)
    .collect(Collectors.toList());

  List<String> expectedContainers = Arrays.asList("page1container1", "page1container2", "page1container3", "page2container1", "page2container2", "page2container3");
  assertEquals(expectedContainers, receivedContainers);
}
 
Example #10
Source File: TestAzureAsyncContainerProvider.java    From dremio-oss with Apache License 2.0 4 votes vote down vote up
@Test
public void testListContainersWithRetry() throws IOException, ExecutionException, InterruptedException {
  AsyncHttpClient client = mock(AsyncHttpClient.class);
  Response response = mock(Response.class);
  when(response.getHeader(any(String.class))).thenReturn("");
  HttpResponseStatus status = mock(HttpResponseStatus.class);
  when(status.getStatusCode()).thenReturn(206);
  HttpResponseStatus failedStatus = mock(HttpResponseStatus.class);
  when(failedStatus.getStatusCode()).thenReturn(500);

  byte[] dfsCoreResponseBodyBytes = readStaticResponse("dfs-core-container-response-page1.json");
  RandomBytesResponseDispatcher dfsCoreResponseDispatcher = new RandomBytesResponseDispatcher(dfsCoreResponseBodyBytes);

  CompletableFuture<Response> future = CompletableFuture.completedFuture(response);
  ListenableFuture<Response> resFuture = mock(ListenableFuture.class);
  when(resFuture.toCompletableFuture()).thenReturn(future);
  when(resFuture.get()).thenReturn(response);

  AtomicInteger retryAttemptNo = new AtomicInteger(0);
  when(client.executeRequest(any(Request.class), any(AsyncCompletionHandler.class))).then(invocationOnMock -> {
    AsyncCompletionHandler handler = invocationOnMock.getArgument(1, AsyncCompletionHandler.class);
    if (retryAttemptNo.incrementAndGet() < 10) {
      handler.onStatusReceived(failedStatus);
    } else {
      while (dfsCoreResponseDispatcher.isNotFinished()) {
        handler.onBodyPartReceived(dfsCoreResponseDispatcher.getNextBodyPart());
      }
      handler.onStatusReceived(status);
    }
    handler.onCompleted(response);
    return resFuture;
  });

  AzureStorageFileSystem parentClass = mock(AzureStorageFileSystem.class);
  AzureAuthTokenProvider authTokenProvider = getMockAuthTokenProvider();
  AzureAsyncContainerProvider containerProvider = new AzureAsyncContainerProvider(
    client, "azurestoragev2hier", authTokenProvider, parentClass, true);

  List<String> receivedContainers = containerProvider.getContainerCreators()
    .map(AzureStorageFileSystem.ContainerCreatorImpl.class::cast)
    .map(AzureStorageFileSystem.ContainerCreatorImpl::getName)
    .collect(Collectors.toList());

  List<String> expectedContainers = Arrays.asList("page1container1", "page1container2", "page1container3");
  assertEquals(expectedContainers, receivedContainers);
}
 
Example #11
Source File: TestAzureAsyncReader.java    From dremio-oss with Apache License 2.0 4 votes vote down vote up
private void testSuccessHttpMode(boolean isSecure) {
  // Prepare response
  AsyncHttpClient client = mock(AsyncHttpClient.class);
  Response response = mock(Response.class);
  HttpResponseStatus status = mock(HttpResponseStatus.class);
  when(status.getStatusCode()).thenReturn(206);

  CompletableFuture<Response> future = CompletableFuture.completedFuture(response);
  ListenableFuture<Response> resFuture = mock(ListenableFuture.class);
  when(resFuture.toCompletableFuture()).thenReturn(future);
  LocalDateTime versionDate = LocalDateTime.now(ZoneId.of("GMT")).minusDays(2);

  byte[] responseBytes = getRandomBytes(20);
  HttpResponseBodyPart responsePart = mock(HttpResponseBodyPart.class);
  when(responsePart.getBodyByteBuffer()).thenReturn(ByteBuffer.wrap(responseBytes));

  when(client.executeRequest(any(Request.class), any(AsyncCompletionHandler.class))).then(invocationOnMock -> {
    // Validate URL
    Request req = invocationOnMock.getArgument(0, Request.class);
    String expectedPrefix = isSecure ? "https" : "http";
    assertEquals("Invalid request url",
      expectedPrefix + "://account.dfs.core.windows.net/container/directory%2Ffile_00.parquet", req.getUrl());

    // Validate Headers
    assertEquals("Invalid blob range header", "bytes=0-19", req.getHeaders().get("Range"));
    LocalDateTime dateHeaderVal = LocalDateTime.parse(req.getHeaders().get("Date"), DATE_RFC1123_FORMATTER);
    long dateHeaderDiffInSecs = Math.abs(dateHeaderVal.until(LocalDateTime.now(ZoneId.of("GMT")), ChronoUnit.SECONDS));
    assertTrue("Date header not set correctly", dateHeaderDiffInSecs < 2);

    LocalDateTime versionHeaderVal = LocalDateTime.parse(req.getHeaders().get("If-Unmodified-Since"), DATE_RFC1123_FORMATTER);
    assertEquals("Version header not set correctly", 0, versionHeaderVal.until(versionDate, ChronoUnit.SECONDS));

    assertEquals("Authz header not set correctly", req.getHeaders().get("Authorization"), "Bearer testtoken");
    assertNotNull(req.getHeaders().get("x-ms-client-request-id"));

    // Fill in response
    AsyncCompletionHandler<Response> responseHandler = invocationOnMock.getArgument(1, AsyncCompletionHandler.class);
    assertEquals(responseHandler.getClass(), BufferBasedCompletionHandler.class);

    responseHandler.onBodyPartReceived(responsePart);
    responseHandler.onStatusReceived(status);
    responseHandler.onCompleted(response);
    return resFuture;
  });

  AzureAsyncReader azureAsyncReader = spy(new AzureAsyncReader(
    "account", new Path("container/directory/file_00.parquet"),
    getMockAuthTokenProvider(), String.valueOf(versionDate.atZone(ZoneId.of("GMT")).toInstant().toEpochMilli()),
    isSecure, client
  ));

  try {
    ByteBuf buf = Unpooled.buffer(20);
    azureAsyncReader.readFully(0, buf, 0, 20).get();
    assertEquals(new String(buf.array()), new String(responseBytes));
    verify(azureAsyncReader).read(0, buf, 0, 20, 0);
  } catch (Exception e) {
    fail(e.getMessage());
  }
}
 
Example #12
Source File: AsyncHttpClientLiveTest.java    From tutorials with MIT License 4 votes vote down vote up
@Test
public void givenHttpClient_executeAsyncGetRequestWithAsyncHandler() {

    // execute an unbound GET request
    Request unboundGetRequest = Dsl.get("http://www.baeldung.com").build();

    HTTP_CLIENT.executeRequest(unboundGetRequest, new AsyncHandler<Integer>() {

        int responseStatusCode = -1;

        @Override
        public State onStatusReceived(HttpResponseStatus responseStatus) {
            responseStatusCode = responseStatus.getStatusCode();
            return State.CONTINUE;
        }

        @Override
        public State onHeadersReceived(HttpHeaders headers) {
            return State.CONTINUE;
        }

        @Override
        public State onBodyPartReceived(HttpResponseBodyPart bodyPart) {
            return State.CONTINUE;
        }

        @Override
        public void onThrowable(Throwable t) {

        }

        @Override
        public Integer onCompleted() {
            assertEquals(200, responseStatusCode);
            return responseStatusCode;
        }
    });

    try {
        Thread.sleep(5000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}
 
Example #13
Source File: Webhook.java    From attic-aurora with Apache License 2.0 4 votes vote down vote up
/**
 * Watches all TaskStateChanges and send them best effort to a configured endpoint.
 * <p>
 * This is used to expose an external event bus.
 *
 * @param stateChange State change notification.
 */
@Subscribe
public void taskChangedState(TaskStateChange stateChange) {
  LOG.debug("Got an event: {}", stateChange);
  // Ensure that this state change event is a transition, and not an event from when the scheduler
  // first initializes. In that case we do not want to resend the entire state. This check also
  // ensures that only whitelisted statuses will be sent to the configured endpoint.
  if (stateChange.isTransition() && isWhitelisted.apply(stateChange.getNewState())) {
    attemptsCounter.incrementAndGet();
    try {
      // We don't care about the response body, so only listen for the HTTP status code.
      createRequest(stateChange).execute(new AsyncCompletionHandler<Integer>() {
        @Override
        public void onThrowable(Throwable t) {
          errorsCounter.incrementAndGet();
          LOG.error("Error sending a Webhook event", t);
        }

        @Override
        public State onStatusReceived(HttpResponseStatus status) throws Exception {
          if (status.getStatusCode() == HttpConstants.ResponseStatusCodes.OK_200) {
            successCounter.incrementAndGet();
          } else {
            userErrorsCounter.incrementAndGet();
          }

          // Abort after we get the status because that is all we use for processing.
          return State.ABORT;
        }

        @Override
        public Integer onCompleted(Response response) throws Exception {
          // We do not care about the full response.
          return 0;
        }
      });
    } catch (Exception e) {
      LOG.error("Error making Webhook request", e);
      errorsCounter.incrementAndGet();
    }
  }
}
 
Example #14
Source File: WebhookTest.java    From attic-aurora with Apache License 2.0 4 votes vote down vote up
@Override
public State onStatusReceived(HttpResponseStatus responseStatus) throws Exception {
  return handler.onStatusReceived(responseStatus);
}