Java Code Examples for org.asynchttpclient.Response#getStatusCode()

The following examples show how to use org.asynchttpclient.Response#getStatusCode() . 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: Zendesk.java    From zendesk-java-client with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
protected <T> ZendeskAsyncCompletionHandler<T> handle(final Class<T> clazz) {
    return new ZendeskAsyncCompletionHandler<T>() {
        @Override
        public T onCompleted(Response response) throws Exception {
            logResponse(response);
            if (isStatus2xx(response)) {
                return (T) mapper.readerFor(clazz).readValue(response.getResponseBodyAsStream());
            } else if (isRateLimitResponse(response)) {
                throw new ZendeskResponseRateLimitException(response);
            }
            if (response.getStatusCode() == 404) {
                return null;
            }
            throw new ZendeskResponseException(response);
        }
    };
}
 
Example 2
Source File: RecurlyClient.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
private void parseErrorResponse(final Response response, final SettableFuture<?> future) {
    try {
        RecurlyErrors errors = new RecurlyErrors();
        errors = deserializer.parse(response.getResponseBodyAsStream(), RecurlyErrors.class);
        if (!errors.isEmpty()) {
            // If we encountered a transaction error, the deserializer only puts that error in the object.
            // So we can safely call get(0) since the errors object is not empty.
            if (errors.hasTransactionError()) {
                future.setException(new TransactionErrorException(errors.getTransactionErrors().get(0)));
            } else {
                RecurlyAPIErrorException reculryException = new RecurlyAPIErrorException("APIError", errors);
                if(response.getStatusCode()==404){
                    future.setException(new BillingEntityNotFoundException("Recurly account or subscription not found",reculryException));
                }else{
                    future.setException(reculryException);
                }
            }
        } else {
            future.setException(new UnknownError("Unknown error. Received " + response.getStatusCode() + " From Recurly"));
        }
    } catch (Exception e) {
        future.setException(e);
    }
}
 
Example 3
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 4
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 5
Source File: IndicesAdminClient.java    From flummi with Apache License 2.0 6 votes vote down vote up
public List<String> getAllIndexNames() {
    try {
        Response response = httpClient.prepareGet("/_all")
                .addHeader(CONTENT_TYPE, APPL_JSON)
                .execute().get();
        if (response.getStatusCode() != 200) {
            throw RequestBuilderUtil.toHttpServerErrorException(response);
        }
        String jsonString = response.getResponseBody();
        JsonObject responseObject = gson.fromJson(jsonString, JsonObject.class);

        return responseObject.entrySet().stream()
                .map(Map.Entry::getKey)
                .collect(toList());
    } catch (InterruptedException | ExecutionException e) {
        throw new RuntimeException(e);
    }
}
 
Example 6
Source File: IndicesAdminClient.java    From flummi with Apache License 2.0 6 votes vote down vote up
public JsonObject getIndexSettings() {
    try {

        Response response = httpClient.prepareGet("/_all/_settings")
                .addHeader(CONTENT_TYPE, APPL_JSON)
                .execute().get();
        if (response.getStatusCode() != 200) {
            throw RequestBuilderUtil.toHttpServerErrorException(response);
        }
        String jsonString = null;
        jsonString = response.getResponseBody();
        return gson.fromJson(jsonString, JsonObject.class);
    } catch (InterruptedException | ExecutionException e) {
        throw new RuntimeException(e);
    }
}
 
Example 7
Source File: MessageServiceImpl.java    From qmq with Apache License 2.0 6 votes vote down vote up
private byte[] getMessageBytesWithMeta(String brokerGroup, String subject, List<BackupMessageMeta> metas) {
    final String backupAddress = metaSupplier.resolveServerAddress(brokerGroup);
    if (Strings.isNullOrEmpty(backupAddress)) return new byte[]{};
    String url = MESSAGE_QUERY_PROTOCOL + backupAddress + MESSAGE_QUERY_URL;

    try {
        BoundRequestBuilder boundRequestBuilder = ASYNC_HTTP_CLIENT.prepareGet(url);
        boundRequestBuilder.addQueryParam("backupQuery", serializer.serialize(getQuery(subject, metas)));

        final Response response = boundRequestBuilder.execute().get();
        if (response.getStatusCode() != HttpResponseStatus.OK.code()) {
            return new byte[]{};
        }

        final ByteBuffer buffer = response.getResponseBodyAsByteBuffer();


        return buffer.array();
    } catch (InterruptedException | ExecutionException e) {
        LOG.error("get message byte with meta failed.", e);
        throw new RuntimeException("get message byte failed.");
    }
}
 
Example 8
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 9
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 10
Source File: DRPCQueryResultPubscriber.java    From bullet-storm with Apache License 2.0 5 votes vote down vote up
private void handleResponse(String id, Response response) {
    if (response == null || response.getStatusCode() != OK_200) {
        log.error("Handling error for id {} with response {}", id, response);
        responses.offer(new PubSubMessage(id, DRPCError.CANNOT_REACH_DRPC.asJSONClip()));
        return;
    }
    log.info("Received for id {}: {} {}", response.getStatusCode(), id, response.getStatusText());
    String body = response.getResponseBody();
    PubSubMessage message = PubSubMessage.fromJSON(body);
    log.debug("Received for id {}:\n{}", message.getId(), message.getContent());
    responses.offer(message);
}
 
Example 11
Source File: SearchScrollRequestBuilder.java    From flummi with Apache License 2.0 5 votes vote down vote up
@Override
public SearchResponse execute() {
    JsonObject requestBody = object(
            "scroll_id", scrollId,
            "scroll", scroll
    );
    try {
        Response response = httpClient.preparePost("/_search/scroll")
                .setBody(gson.toJson(requestBody))
                .addHeader(CONTENT_TYPE, APPL_JSON)
                .execute()
                .get();

        //Did not find an entry
        if (response.getStatusCode() == 404) {
            return emptyResponse();
        }

        //Server Error
        if (response.getStatusCode() >= 300) {
            throw toHttpServerErrorException(response);
        }

        JsonObject jsonResponse = gson.fromJson(response.getResponseBody(), JsonObject.class);
        SearchResponse.Builder searchResponse = parseResponse(jsonResponse, null, null);

        return searchResponse.build();
    } catch (InterruptedException | ExecutionException e) {
        throw new RuntimeException(e);
    }

}
 
Example 12
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 13
Source File: ClickhouseWriterTest.java    From flink-clickhouse-sink with MIT License 5 votes vote down vote up
private void send(String data, String url, String basicCredentials, AtomicInteger counter) {
    String query = String.format("INSERT INTO %s VALUES %s ", "groot3.events", data);
    BoundRequestBuilder requestBuilder = asyncHttpClient.preparePost(url).setHeader("Authorization", basicCredentials);
    requestBuilder.setBody(query);
    ListenableFuture<Response> whenResponse = asyncHttpClient.executeRequest(requestBuilder.build());
    Runnable callback = () -> {
        try {
            Response response = whenResponse.get();
            System.out.println(Thread.currentThread().getName() + " " + response);

            if (response.getStatusCode() != 200) {
                System.out.println(Thread.currentThread().getName() + " try to retry...");
                int attempt = counter.incrementAndGet();
                if (attempt > MAX_ATTEMPT) {
                    System.out.println("Failed ");
                } else {
                    send(data, url, basicCredentials, counter);
                }
            }
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
    };

    Executor executor = ForkJoinPool.commonPool();
    whenResponse.addListener(callback, executor);
}
 
Example 14
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 15
Source File: SlaveMetaSupplier.java    From qmq with Apache License 2.0 5 votes vote down vote up
private String getServerAddress(String groupName) {
    try {
        Response response = ASYNC_HTTP_CLIENT.prepareGet(serverMetaAcquiredUrl).addQueryParam("groupName", groupName).execute().get();
        if (response.getStatusCode() == HttpResponseStatus.OK.code()) {
            String address = response.getResponseBody();
            if (!Strings.isNullOrEmpty(address)) {
                return address;
            }
        }
    } catch (Exception e) {
        LOG.error("Get server address error.", e);
    }
    return null;
}
 
Example 16
Source File: AsyncHttpClientService.java    From mutual-tls-ssl with Apache License 2.0 5 votes vote down vote up
@Override
public ClientResponse executeRequest(String url) throws Exception {
    RequestBuilder requestBuilder = new RequestBuilder()
            .setUrl(url)
            .setHeader(HEADER_KEY_CLIENT_TYPE, getClientType().getValue());

    Response response = httpClient.executeRequest(requestBuilder)
            .toCompletableFuture()
            .get(TIMEOUT_AMOUNT_IN_SECONDS, TimeUnit.SECONDS);

    return new ClientResponse(response.getResponseBody(), response.getStatusCode());
}
 
Example 17
Source File: SearchRequestBuilder.java    From flummi with Apache License 2.0 4 votes vote down vote up
@Override
public SearchResponse execute() {
    JsonObject body = new JsonObject();
    try {
        String url = RequestBuilderUtil.buildUrl(indices, types, "_search");
        if (query != null) {
            body.add("query", query);
        }
        if (storedFields != null) {
            body.add("stored_fields", storedFields);
        }
        if (sourceFilters != null) {
            body.add("_source", sourceFilters);
        }
        if (from != null) {
            body.add("from", new JsonPrimitive(from));
        }
        if (size != null) {
            body.add("size", new JsonPrimitive(size));
        }
        if (sorts != null) {
            body.add("sort", sorts);
        }
        if (postFilter != null) {
            body.add("post_filter", postFilter.build());
        }
        if (aggregations != null) {
            JsonObject jsonObject = aggregations
                    .stream()
                    .collect(toJsonObject());

            body.add("aggregations", jsonObject);
        }
        BoundRequestBuilder boundRequestBuilder = httpClient
                .preparePost(url)
                .setCharset(Charset.forName("UTF-8"));
        if (timeoutMillis != null) {
            boundRequestBuilder.setRequestTimeout(timeoutMillis);
        }
        if (scroll != null) {
            boundRequestBuilder.addQueryParam("scroll", scroll);
        }

        Response response = boundRequestBuilder.setBody(gson.toJson(body))
                .addHeader(CONTENT_TYPE, APPL_JSON)
                .execute()
                .get();

        //Did not find an entry
        if (response.getStatusCode() == 404) {
            return emptyResponse();
        }

        //Server Error
        if (response.getStatusCode() >= 300) {
            throw toHttpServerErrorException(response);
        }

        JsonObject jsonResponse = gson.fromJson(response.getResponseBody(), JsonObject.class);
        SearchResponse.Builder searchResponse = parseResponse(jsonResponse, scroll, httpClient);

        JsonElement aggregationsJsonElement = jsonResponse.get("aggregations");
        if (aggregationsJsonElement != null) {
            final JsonObject aggregationsJsonObject = aggregationsJsonElement.getAsJsonObject();

            aggregations.forEach(a -> {
                JsonElement aggregationElement = aggregationsJsonObject.get(a.getName());
                if (aggregationElement != null) {
                    AggregationResult aggregation = a.parseResponse(aggregationElement.getAsJsonObject());
                    searchResponse.addAggregation(a.getName(), aggregation);
                }
            });
        }
        return searchResponse.build();
    } catch (InterruptedException | ExecutionException e) {
        throw new RuntimeException(body.toString(), e);
    }
}
 
Example 18
Source File: RequestBuilderUtil.java    From flummi with Apache License 2.0 4 votes vote down vote up
public static HttpServerErrorException toHttpServerErrorException(Response response) {
    return new HttpServerErrorException(response.getStatusCode(), response.getStatusText() , new String(response.getResponseBodyAsBytes()));
}
 
Example 19
Source File: ZendeskResponseException.java    From zendesk-java-client with Apache License 2.0 4 votes vote down vote up
public ZendeskResponseException(Response resp) throws IOException {
    this(resp.getStatusCode(), resp.getStatusText(), resp.getResponseBody());
}
 
Example 20
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");
}