org.asynchttpclient.util.HttpConstants Java Examples

The following examples show how to use org.asynchttpclient.util.HttpConstants. 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: 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 #2
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 #3
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 #4
Source File: AsyncHttpClientTest.java    From java-specialagent with Apache License 2.0 5 votes vote down vote up
@Test
public void testNoHandler(final MockTracer tracer) throws IOException {
  try (final AsyncHttpClient client = new DefaultAsyncHttpClient()) {
    final Request request = new RequestBuilder(HttpConstants.Methods.GET).setUrl("http://localhost:12345").build();
    try {
      client.executeRequest(request).get(10, TimeUnit.SECONDS);
    }
    catch (final Exception ignore) {
    }
  }

  await().atMost(15, TimeUnit.SECONDS).until(TestUtil.reportedSpansSize(tracer), equalTo(1));
  assertEquals(1, tracer.finishedSpans().size());
  assertNull(tracer.activeSpan());
}
 
Example #5
Source File: AsyncHttpClientTest.java    From java-specialagent with Apache License 2.0 5 votes vote down vote up
@Test
public void testWithHandler(final MockTracer tracer) throws IOException {
  final AtomicInteger counter = new AtomicInteger();
  try (final AsyncHttpClient client = new DefaultAsyncHttpClient()) {
    final Request request = new RequestBuilder(HttpConstants.Methods.GET).setUrl("http://localhost:12345").build();
    try {
      client.executeRequest(request, new AsyncCompletionHandler<Object>() {
        @Override
        public Object onCompleted(final Response response) {
          assertNotNull(tracer.activeSpan());
          counter.incrementAndGet();
          return response;
        }

        @Override
        public void onThrowable(final Throwable t) {
          assertNotNull(tracer.activeSpan());
          counter.incrementAndGet();
        }
      }).get(10, TimeUnit.SECONDS);
    }
    catch (final Exception ignore) {
    }
  }

  await().atMost(15, TimeUnit.SECONDS).until(TestUtil.reportedSpansSize(tracer), equalTo(1));
  assertEquals(1, tracer.finishedSpans().size());
  assertEquals(1, counter.get());
  assertNull(tracer.activeSpan());
}
 
Example #6
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 #7
Source File: AzureAsyncContainerProvider.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
@Override
public boolean doesContainerExists(final String containerName) {
  // API: https://docs.microsoft.com/en-gb/rest/api/storageservices/datalakestoragegen2/filesystem/getproperties
  logger.debug("Checking for missing azure container " + account + ":" + containerName);
  final Request req = new RequestBuilder(HttpConstants.Methods.HEAD)
    .addHeader("x-ms-date", toHttpDateFormat(System.currentTimeMillis()))
    .addHeader("x-ms-version", XMS_VERSION)
    .addHeader("Content-Length", 0)
    .addHeader("x-ms-client-request-id", UUID.randomUUID().toString())
    .setUrl(AzureAsyncHttpClientUtils.getBaseEndpointURL(account, true) + "/" + containerName)
    .addQueryParam("resource", "filesystem")
    .addQueryParam("timeout", String.valueOf(requestTimeoutSeconds)).build();

  req.getHeaders().add("Authorization", authProvider.getAuthzHeaderValue(req));
  final AtomicBoolean containerExists = new AtomicBoolean(false);
  retryer.call(() -> {
    int status = asyncHttpClient.executeRequest(req).get().getStatusCode();
    if (status != 200 && status != 404) {
      logger.error("Error while checking for azure container " + account + ":" + containerName + " status code " + status);
      throw new RuntimeException(String.format("Error response %d while checking for existence of container %s", status, containerName));
    }
    if (status == 200) {
      logger.debug("Azure container is found valid " + account + ":" + containerName);
      containerExists.set(true);
    }
    return true;
  });

  return containerExists.get();
}
 
Example #8
Source File: AzureAsyncHttpClientUtils.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
public static RequestBuilder newDefaultRequestBuilder() {
  return new RequestBuilder(HttpConstants.Methods.GET)
    .addHeader("Date", toHttpDateFormat(System.currentTimeMillis()))
    .addHeader("Content-Length", 0)
    .addHeader("x-ms-version", XMS_VERSION)
    .addHeader("x-ms-client-request-id", UUID.randomUUID().toString())
    .addHeader("User-Agent", USER_AGENT_VAL);
}
 
Example #9
Source File: TestAzureSharedKeyAuthTokenProvider.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
private Request prepareTestRequest() {
  return new RequestBuilder(HttpConstants.Methods.GET)
    .addHeader("Date", "Tue, 31 Dec 2019 07:18:50 GMT")
    .addHeader("Content-Length", 0)
    .addHeader("x-ms-version", "2019-02-02")
    .addHeader("x-ms-client-request-id", "b2a11e2a-65a7-48ed-a643-229255139452")
    .addHeader("User-Agent", "azsdk-java-azure-storage-blob/12.1.0 (1.8.0_231; Mac OS X 10.14.5)")
    .addHeader("x-ms-range", String.format("bytes=%d-%d", 25, 125))
    .addHeader("If-Unmodified-Since", "Tue, 15 Dec 2019 07:18:50 GMT")
    .setUrl("https://account.blob.core.windows.net/container/directory%2Ffile_00.parquet")
    .build();
}
 
Example #10
Source File: SlaManager.java    From attic-aurora with Apache License 2.0 4 votes vote down vote up
private boolean coordinatorAllows(
    IScheduledTask task,
    String taskKey,
    ICoordinatorSlaPolicy slaPolicy,
    Map<String, String> params)
    throws InterruptedException, ExecutionException, TException {

  LOG.info("Checking coordinator: {} for task: {}", slaPolicy.getCoordinatorUrl(), taskKey);

  String taskConfig = new TSerializer(new TSimpleJSONProtocol.Factory())
      .toString(task.newBuilder());
  JsonObject jsonBody = new JsonObject();
  jsonBody.add("taskConfig", new JsonParser().parse(taskConfig));
  jsonBody.addProperty(TASK_PARAM, taskKey);
  params.forEach(jsonBody::addProperty);

  Response response = httpClient.preparePost(slaPolicy.getCoordinatorUrl())
      .setQueryParams(ImmutableList.of(new Param(TASK_PARAM, taskKey)))
      .setBody(new Gson().toJson(jsonBody))
      .execute()
      .get();

  if (response.getStatusCode() != HttpConstants.ResponseStatusCodes.OK_200) {
    LOG.error("Request failed to coordinator: {} for task: {}. Response: {}",
        slaPolicy.getCoordinatorUrl(),
        taskKey,
        response.getStatusCode());
    incrementErrorCount(USER_ERRORS_STAT_NAME, taskKey);
    return false;
  }

  successCounter.incrementAndGet();
  String json = response.getResponseBody();
  LOG.info("Got response: {} from {} for task: {}",
      json,
      slaPolicy.getCoordinatorUrl(),
      taskKey);

  Map<String, Boolean> result = new Gson().fromJson(
      json,
      new TypeReference<Map<String, Boolean>>() { }.getType());

  return result.get(slaPolicy.isSetStatusKey() ? slaPolicy.getStatusKey() : "drain");
}
 
Example #11
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();
    }
  }
}