Java Code Examples for com.ning.http.client.Response#getStatusCode()

The following examples show how to use com.ning.http.client.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: ProxyServiceImpl.java    From bistoury with GNU General Public License v3.0 6 votes vote down vote up
private boolean existAgent(String url, @RequestParam String agentIp) {
    try {
        AsyncHttpClient.BoundRequestBuilder builder = httpClient.prepareGet(url);
        builder.addQueryParam("ip", agentIp);
        Response response = httpClient.executeRequest(builder.build()).get();
        if (response.getStatusCode() == 200) {
            ApiResult<AgentInfo> result = JacksonSerializer.deSerialize(response.getResponseBody("utf8"), AGENT_TYPE_REFERENCE);
            if (result.getStatus() == 0) {
                return true;
            }
        }
    } catch (Exception e) {
        logger.error("query exist agent error, agent ip [{}], url [{}]", agentIp, url, e);
    }
    return false;
}
 
Example 2
Source File: Zendesk.java    From scava with Eclipse Public License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
protected <T> AsyncCompletionHandler<T> handle(final Class<T> clazz) {
    return new AsyncCompletionHandler<T>() {
        @Override
        public T onCompleted(Response response) throws Exception {
            logResponse(response);
            if (isStatus2xx(response)) {
                return (T) mapper.reader(clazz).readValue(response.getResponseBodyAsStream());
            }
            if (response.getStatusCode() == 404) {
                return null;
            }
            throw new ZendeskResponseException(response);
        }
    };
}
 
Example 3
Source File: WrappedUserResponseParser.java    From Singularity with Apache License 2.0 6 votes vote down vote up
SingularityUserPermissionsResponse parse(Response response) throws IOException {
  if (response.getStatusCode() > 299) {
    throw WebExceptions.unauthorized(
      String.format("Got status code %d when verifying jwt", response.getStatusCode())
    );
  } else {
    String responseBody = response.getResponseBody();
    SingularityUserPermissionsResponse permissionsResponse = objectMapper.readValue(
      responseBody,
      SingularityUserPermissionsResponse.class
    );
    if (!permissionsResponse.getUser().isPresent()) {
      throw WebExceptions.unauthorized(
        String.format("No user present in response %s", permissionsResponse)
      );
    }
    if (!permissionsResponse.getUser().get().isAuthenticated()) {
      throw WebExceptions.unauthorized(
        String.format("User not authenticated (response: %s)", permissionsResponse)
      );
    }
    return permissionsResponse;
  }
}
 
Example 4
Source File: Configs.java    From bistoury with GNU General Public License v3.0 6 votes vote down vote up
private static ProxyConfig getProxyConfig(String bistouryHost) {
    String url = "http://" + bistouryHost + PROXY_URI;
    try {
        AsyncHttpClient client = AsyncHttpClientHolder.getInstance();
        AsyncHttpClient.BoundRequestBuilder builder = client.prepareGet(url);
        builder.setHeader("content-type", "application/json;charset=utf-8");
        Response response = client.executeRequest(builder.build()).get();
        if (response.getStatusCode() != 200) {
            logger.error("get proxy config error, http code [{}], url [{}]", response.getStatusCode(), url);
            return null;
        }

        JsonResult<ProxyConfig> result = JacksonSerializer.deSerialize(response.getResponseBody("utf8"), PROXY_REFERENCE);
        if (!result.isOK()) {
            logger.error("get proxy config error, status code [{}], url [{}]", result.getStatus(), url);
            return null;
        }

        return result.getData();
    } catch (Throwable e) {
        logger.error("get proxy config error, url [{}]", url, e);
        return null;
    }
}
 
Example 5
Source File: RawUserResponseParser.java    From Singularity with Apache License 2.0 6 votes vote down vote up
SingularityUserPermissionsResponse parse(Response response) throws IOException {
  if (response.getStatusCode() > 299) {
    throw WebExceptions.unauthorized(
      String.format("Got status code %d when verifying jwt", response.getStatusCode())
    );
  } else {
    String responseBody = response.getResponseBody();
    WebhookAuthUser user = objectMapper.readValue(responseBody, WebhookAuthUser.class);
    return new SingularityUserPermissionsResponse(
      Optional.of(
        new SingularityUser(
          user.getUid(),
          Optional.of(user.getUid()),
          authConfiguration
            .getDefaultEmailDomain()
            .map(d -> String.format("%s@%s", user.getUid(), d)),
          user.getGroups(),
          user.getScopes(),
          true
        )
      ),
      Optional.empty()
    );
  }
}
 
Example 6
Source File: ProfilerController.java    From bistoury with GNU General Public License v3.0 5 votes vote down vote up
private String getAnalyzerResult(String url) {
    Request request = httpClient.preparePost(url).build();
    try {
        Response response = httpClient.executeRequest(request).get();
        if (response.getStatusCode() != 200) {
            LOGGER.warn("analyze profiler result code is {}", response.getStatusCode());
            return null;
        }
        return response.getResponseBody();
    } catch (Exception e) {
        LOGGER.error("get analyzer result.", e);
        throw new RuntimeException("get analyzer result error. " + e.getMessage());
    }
}
 
Example 7
Source File: AggregatorEventHandler.java    From blog-non-blocking-rest-service-with-spring-mvc with Apache License 2.0 5 votes vote down vote up
public void onResult(int id, Response response) {

        try {
            // TODO: Handle status codes other than 200...
            int httpStatus = response.getStatusCode();
            log.logEndProcessingStepNonBlocking(id, httpStatus);

            // If many requests completes at the same time the following code must be executed in sequence for one thread at a time
            // Since we don't have any Actor-like mechanism to rely on (for the time being...) we simply ensure that the code block is executed by one thread at a time by an old school synchronized block
            // Since the processing in the block is very limited it will not cause a bottleneck.
            synchronized (result) {
                // Count down, aggregate answer and return if all answers (also cancel timer)...
                int noOfRes = noOfResults.incrementAndGet();

                // Perform the aggregation...
                log.logMessage("Safely adding response #" + id);
                result += response.getResponseBody() + '\n';

                if (noOfRes >= noOfCalls) {
                    onAllCompleted();
                }
            }



        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
 
Example 8
Source File: SSEConnection.java    From blueocean-plugin with MIT License 5 votes vote down vote up
private Response ensureSuccess(Response rsp) throws IOException {
    // TODO: am I supposed to check the error here or does it happen on its own?
    if (rsp.getStatusCode() != 200) {
        throw new IOException("Failed to connect to " + rsp.getUri() + ": " + rsp.getStatusCode() + " " + rsp.getStatusText());
    }
    return rsp;
}
 
Example 9
Source File: LoggingAsyncHandlerWrapper.java    From parsec-libraries with Apache License 2.0 5 votes vote down vote up
@Override
public T onCompleted() throws Exception {
    final Response ningResponse = builder.build();

    ParsecAsyncProgressTimer.progressTime(progress, ParsecAsyncProgressTimer.TimerOpCode.TIMER_TOTAL);
    logResponseOrThrowable(ningRequest, ningResponse, null, progress);
    progress.reset();
    int lastRespCode = ningResponse.getStatusCode();
    ningRequest.getHeaders().replaceWith(ParsecClientDefine.HEADER_PROFILING_LAST_RESPONSE_CODE, String.valueOf(lastRespCode));

    return asyncHandler.onCompleted();
}
 
Example 10
Source File: RouterCallback.java    From blog-non-blocking-rest-service-with-spring-mvc with Apache License 2.0 5 votes vote down vote up
@Override
public Response onCompleted(Response response) throws Exception{

    // TODO: Handle status codes other than 200...
    int httpStatus = response.getStatusCode();

    if (deferredResult.isSetOrExpired()) {
        log.logAlreadyExpiredNonBlocking();

    } else {
        boolean deferredStatus = deferredResult.setResult(response.getResponseBody());
        log.logEndNonBlocking(httpStatus, deferredStatus);
    }
    return response;
}
 
Example 11
Source File: HttpWorker.java    From restcommander with Apache License 2.0 5 votes vote down vote up
public MyResponse onComplete(Response response) {

		cancelCancellable();
		try {

			String statusCode = response.getStatusCode() + " " + response.getStatusText();
			
			reply(response.getResponseBody(), false, null, null, statusCode);
		} catch (IOException e) {
			e.printStackTrace();
		}

		return null;
	}
 
Example 12
Source File: Zendesk.java    From scava with Eclipse Public License 2.0 5 votes vote down vote up
protected <T> AsyncCompletionHandler<T> handle(final Class<T> clazz, final String name) {
    return new AsyncCompletionHandler<T>() {
        @Override
        public T onCompleted(Response response) throws Exception {
            logResponse(response);
            if (isStatus2xx(response)) {
                return mapper.convertValue(mapper.readTree(response.getResponseBodyAsStream()).get(name), clazz);
            }
            if (response.getStatusCode() == 404) {
                return null;
            }
            throw new ZendeskResponseException(response);
        }
    };
}
 
Example 13
Source File: GithubRepositoryApiImpl.java    From bistoury with GNU General Public License v3.0 5 votes vote down vote up
private ApiResult doFile(final String project, final String ref, final String path) {
    Optional<PrivateToken> privateToken = privateTokenService.queryToken(LoginContext.getLoginContext().getLoginUser());
    if (!privateToken.isPresent()) {
        return ResultHelper.fail(-1, "尚未设置 Github Private Token");
    }

    String fileUrl = buildFileUrl(project, path);
    Request request = client.prepareGet(fileUrl)
            .addQueryParam("ref", ref)
            .addHeader("Accept", "application/json")
            .addHeader("'content-type", "application/json")
            .addHeader("Authorization", "token " + privateToken.get().getPrivateToken())
            .build();
    try {
        Response response = client.executeRequest(request).get();
        int statusCode = response.getStatusCode();
        switch (statusCode) {
            case 200:
                String responseBody = response.getResponseBody(Charsets.UTF_8.name());
                return ResultHelper.success(JacksonSerializer.deSerialize(responseBody, GitHubFile.class));
            case 401:
                return ResultHelper.fail("拒绝访问,请检查private token");
            case 404:
                return ResultHelper.fail("文件不存在,请检查链接:" + fileUrl);
            default:
                return ResultHelper.fail("请求github失败,位置的状态码:" + statusCode);
        }
    } catch (Exception e) {
        Metrics.counter("connect_github_error").inc();
        logger.error("connect github fail", e);
        return ResultHelper.fail("连接 github 失败" + e.getMessage());
    }
}
 
Example 14
Source File: CommonG.java    From bdt with Apache License 2.0 5 votes vote down vote up
public void setResponse(String endpoint, Response response) throws IOException {

        Integer statusCode = response.getStatusCode();
        String httpResponse = response.getResponseBody();
        List<Cookie> cookies = response.getCookies();
        this.response = new HttpResponse(statusCode, httpResponse, cookies);
    }
 
Example 15
Source File: QConfigHttpServerClient.java    From qconfig with MIT License 5 votes vote down vote up
@Override
protected boolean process(Response response) {
    if (response.getStatusCode() == HttpStatus.SC_OK) {
        set(null);
        return true;
    }
    logger.warn("response status code is {}", response.getStatusCode());
    return false;
}
 
Example 16
Source File: ServerListServiceImpl.java    From qconfig with MIT License 5 votes vote down vote up
private void updateOnlineServers() {
        AsyncHttpClient.BoundRequestBuilder builder = httpClient.prepareGet(qConfigServerUrl);
        ListenableFuture<Response> future = HttpListenableFuture.wrap(httpClient.executeRequest(builder.build()));

        try {
            Response response = future.get();
            if (response.getStatusCode() == HttpStatus.OK.value()) {
                Iterable<String> it = SPLITTER.split(response.getResponseBody());
                envOnlineServers = Lists.newArrayList(it);
            }

        } catch (Exception e) {
//            throw new RuntimeException("access /entrypoint?type=all failed", e);
        }
    }
 
Example 17
Source File: ParsecClientProfilingLogUtil.java    From parsec-libraries with Apache License 2.0 4 votes vote down vote up
public static String formatMessage(final Request request,
                                   final Response response,
                                   final String requestStatus,
                                   final ParsecAsyncProgress progress,
                                   final Map<String, String> msgMap) {

    //
    // prepare log data
    //
    long now = System.currentTimeMillis();
    BigDecimal timeInSecond = new BigDecimal(now).divide(BigDecimal.valueOf(DateUtils.MILLIS_PER_SECOND));
    String contentLength = "";
    String origin = "";
    int respCode = -1;

    String reqUrl = request.getUri().toUrl();
    String reqMethod = request.getMethod();
    String reqHostHeader = request.getHeaders().getFirstValue(ParsecClientDefine.HEADER_HOST);

    if (response != null) {
        contentLength = response.getHeader(ParsecClientDefine.HEADER_CONTENT_LENGTH);
        respCode = response.getStatusCode();
    }

    String executeInfo;
    try {
        executeInfo = OBJECT_MAPPER.writeValueAsString(progress);
    } catch (JsonProcessingException e) {
        executeInfo = "unable to parse executeInfo. " + e.getMessage();
    }

    //
    // FIXME: should implement a servlet filter to set $_SERVER['REQUEST_URI']
    //
    String srcUrl = "";

    StringBuilder stringBuilder = new StringBuilder()
            .append("time=").append(timeInSecond).append(", ")
            .append("req_url=").append(reqUrl).append(", ")
            .append("req_host_header=").append(reqHostHeader).append(", ")
            .append("req_method=").append(reqMethod).append(", ")
            .append("exec_info=").append(executeInfo).append(", ")
            .append("resp_code=").append(respCode).append(", ")
            .append("src_url=").append(srcUrl).append(", ")
            .append("req_status=").append(requestStatus).append(", ")
            .append("content_length=").append(contentLength).append(", ")
            .append("origin=").append(origin).append(", ");

    if(msgMap != null){
        for (Map.Entry<String, String> entry : msgMap.entrySet()){
            stringBuilder.append(entry.getKey()).append("=").append(entry.getValue()).append(", ");
        }
    }

    return stringBuilder.toString();


}
 
Example 18
Source File: TestServerFixture.java    From fixd with Apache License 2.0 4 votes vote down vote up
public Integer onCompleted(Response r) throws Exception {
    return r.getStatusCode();
}
 
Example 19
Source File: AsyncUtilTest.java    From httpsig-java with The Unlicense 4 votes vote down vote up
@Override
public Boolean onCompleted(Response response) throws Exception {
    return response.getStatusCode() == 200;
}
 
Example 20
Source File: HttpWorker.java    From parallec with Apache License 2.0 4 votes vote down vote up
/**
 * On complete.
 * Save response headers when needed.
 *
 * @param response
 *            the response
 * @return the response on single request
 */
public ResponseOnSingeRequest onComplete(Response response) {

    cancelCancellable();
    try {
        
        Map<String, List<String>> responseHeaders = null;
        if (responseHeaderMeta != null) {
            responseHeaders = new LinkedHashMap<String, List<String>>();
            if (responseHeaderMeta.isGetAll()) {
                for (Map.Entry<String, List<String>> header : response
                        .getHeaders()) {
                    responseHeaders.put(header.getKey().toLowerCase(Locale.ROOT), header.getValue());
                }
            } else {
                for (String key : responseHeaderMeta.getKeys()) {
                    if (response.getHeaders().containsKey(key)) {
                        responseHeaders.put(key.toLowerCase(Locale.ROOT),
                                response.getHeaders().get(key));
                    }
                }
            }
        }

        int statusCodeInt = response.getStatusCode();
        String statusCode = statusCodeInt + " " + response.getStatusText();
        String charset = ParallecGlobalConfig.httpResponseBodyCharsetUsesResponseContentType &&
                response.getContentType()!=null ? 
                AsyncHttpProviderUtils.parseCharset(response.getContentType())
                : ParallecGlobalConfig.httpResponseBodyDefaultCharset;
        if(charset == null){
            getLogger().error("charset is not provided from response content type. Use default");
            charset = ParallecGlobalConfig.httpResponseBodyDefaultCharset; 
        }
        reply(response.getResponseBody(charset), false, null, null, statusCode,
                statusCodeInt, responseHeaders);
    } catch (IOException e) {
        getLogger().error("fail response.getResponseBody " + e);
    }

    return null;
}