Search in sources :

Example 16 with BoundRequestBuilder

use of org.apache.apex.shaded.ning19.com.ning.http.client.AsyncHttpClient.BoundRequestBuilder in project new-cloud by xie-summer.

the class AsyncHttpUtils method getUrlAsString.

/**
 * 通过GET方法请求url
 *
 * @param url
 * @param params
 */
public static void getUrlAsString(String url, Map<String, String> params, HttpResultCallback callback) {
    if (StringUtils.isBlank(url)) {
        return;
    }
    String gurl = getFullUrl(url, params, "utf-8");
    try {
        BoundRequestBuilder rb = getDefault().prepareGet(gurl);
        rb.setHeader("Accept-Encoding", "gzip,deflate");
        rb.execute(new AsynchHandler(callback));
    } catch (IOException e) {
        DB_LOGGER.error(e, 30);
    }
}
Also used : BoundRequestBuilder(com.ning.http.client.AsyncHttpClient.BoundRequestBuilder) IOException(java.io.IOException)

Example 17 with BoundRequestBuilder

use of org.apache.apex.shaded.ning19.com.ning.http.client.AsyncHttpClient.BoundRequestBuilder in project new-cloud by xie-summer.

the class AsyncHttpUtils method postUrlAsString.

/**
 * 通过POST方法请求url
 *
 * @param url
 * @param params
 */
public static void postUrlAsString(String url, Map<String, String> params, int reqTimeout, HttpResultCallback callback) {
    try {
        BoundRequestBuilder rb = getAsyncHttpClient(reqTimeout).preparePost(url);
        rb.setHeader("Accept-Encoding", "gzip,deflate");
        rb.setBodyEncoding("utf-8");
        setPostParams(params, rb);
        rb.execute(new AsynchHandler(callback));
    } catch (IOException e) {
        DB_LOGGER.error(e, 30);
    }
}
Also used : BoundRequestBuilder(com.ning.http.client.AsyncHttpClient.BoundRequestBuilder) IOException(java.io.IOException)

Example 18 with BoundRequestBuilder

use of org.apache.apex.shaded.ning19.com.ning.http.client.AsyncHttpClient.BoundRequestBuilder in project new-cloud by xie-summer.

the class AsyncHttpUtils method uploadFile.

public static void uploadFile(String url, Map<String, String> params, byte[] bytes, String inputName, String fileName, HttpResultCallback callback) {
    try {
        BoundRequestBuilder rb = getDefault().preparePost(url);
        setPostParams(params, rb);
        ByteArrayPart part = new ByteArrayPart(inputName, fileName, bytes, null, "utf-8");
        rb.addBodyPart(part);
        rb.execute(new AsynchHandler(callback));
    } catch (IOException e) {
        DB_LOGGER.error(e, 30);
    }
}
Also used : BoundRequestBuilder(com.ning.http.client.AsyncHttpClient.BoundRequestBuilder) IOException(java.io.IOException)

Example 19 with BoundRequestBuilder

use of org.apache.apex.shaded.ning19.com.ning.http.client.AsyncHttpClient.BoundRequestBuilder in project Singularity by HubSpot.

the class AbstractLeaderAwareResource method maybeProxyToLeader.

protected <T, Q> T maybeProxyToLeader(HttpServletRequest request, Class<T> clazz, Q body, Supplier<T> runnable) {
    if (leaderLatch.hasLeadership()) {
        return runnable.get();
    }
    String leaderUri;
    try {
        leaderUri = leaderLatch.getLeader().getId();
    } catch (Exception e) {
        throw new RuntimeException("Could not get leader uri to proxy request");
    }
    if (leaderUri.equals(leaderLatch.getId())) {
        LOG.warn("Got own leader id when not the leader! There is likely no leader, will not proxy");
        return runnable.get();
    }
    String url = "http://" + leaderUri + request.getContextPath() + request.getPathInfo();
    LOG.debug("Not the leader, proxying request to {}", url);
    BoundRequestBuilder requestBuilder;
    switch(request.getMethod().toUpperCase()) {
        case "POST":
            requestBuilder = httpClient.preparePost(url);
            // necessary to ensure POST requests without bodies work (will hit 30 second timeout otherwise)
            requestBuilder.setBody("");
            break;
        case "PUT":
            requestBuilder = httpClient.preparePut(url);
            break;
        case "DELETE":
            requestBuilder = httpClient.prepareDelete(url);
            break;
        default:
            throw new WebApplicationException(String.format("Not meant to proxy request of method %s", request.getMethod()), 400);
    }
    try {
        if (body != null) {
            requestBuilder.setBody(objectMapper.writeValueAsBytes(body));
            LOG.trace("Added body {} to reqeust", body);
        }
    } catch (JsonProcessingException jpe) {
        LOG.error("Could not write body from object {}", body);
        throw new WebApplicationException(jpe, 500);
    }
    copyHeadersAndParams(requestBuilder, request);
    Request httpRequest = requestBuilder.build();
    Response response;
    try {
        LOG.trace("Sending request to leader: {}", httpRequest);
        response = httpClient.executeRequest(httpRequest).get();
    } catch (ExecutionException | InterruptedException e) {
        LOG.error("Could not proxy request {} to leader", e);
        throw new WebApplicationException(e, 500);
    }
    try {
        if (clazz.isAssignableFrom(javax.ws.rs.core.Response.class)) {
            return (T) javax.ws.rs.core.Response.status(response.getStatusCode()).entity(response.getResponseBody()).build();
        }
        if (response.getStatusCode() > 399) {
            throw new WebApplicationException(response.getResponseBody(Charsets.UTF_8.toString()), response.getStatusCode());
        } else {
            return objectMapper.readValue(response.getResponseBodyAsStream(), clazz);
        }
    } catch (IOException ioe) {
        String message = String.format("Request to leader succeeded with status %s, but could not interpret response", response.getStatusCode());
        LOG.error(message, ioe);
        throw new WebApplicationException(message, ioe, 500);
    }
}
Also used : WebApplicationException(javax.ws.rs.WebApplicationException) Request(com.ning.http.client.Request) HttpServletRequest(javax.servlet.http.HttpServletRequest) IOException(java.io.IOException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) WebApplicationException(javax.ws.rs.WebApplicationException) Response(com.ning.http.client.Response) BoundRequestBuilder(com.ning.http.client.AsyncHttpClient.BoundRequestBuilder) ExecutionException(java.util.concurrent.ExecutionException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException)

Example 20 with BoundRequestBuilder

use of org.apache.apex.shaded.ning19.com.ning.http.client.AsyncHttpClient.BoundRequestBuilder in project Singularity by HubSpot.

the class HttpLocalDownloadServiceFetcher method downloadFiles.

@Override
public void downloadFiles(List<? extends S3Artifact> s3Artifacts, SingularityExecutorTask task) throws InterruptedException {
    final List<FutureHolder> futures = Lists.newArrayListWithCapacity(s3Artifacts.size());
    for (S3Artifact s3Artifact : s3Artifacts) {
        String destination = task.getArtifactPath(s3Artifact, task.getTaskDefinition().getTaskDirectoryPath()).toString();
        ArtifactDownloadRequest artifactDownloadRequest = new ArtifactDownloadRequest(destination, s3Artifact, Optional.of(executorConfiguration.getLocalDownloadServiceTimeoutMillis()));
        task.getLog().debug("Requesting {} from {}", artifactDownloadRequest, localDownloadUri);
        BoundRequestBuilder postRequestBldr = httpClient.preparePost(localDownloadUri);
        try {
            postRequestBldr.setBody(objectMapper.writeValueAsBytes(artifactDownloadRequest));
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        try {
            ListenableFuture<Response> future = httpClient.executeRequest(postRequestBldr.build());
            futures.add(new FutureHolder(future, System.currentTimeMillis(), s3Artifact));
        } catch (Throwable t) {
            throw new RuntimeException(t);
        }
    }
    for (FutureHolder future : futures) {
        Response response = future.getResponse();
        task.getLog().debug("Future for {} got status code {} after {}", future.s3Artifact.getName(), response.getStatusCode(), JavaUtils.duration(future.start));
        if (response.getStatusCode() != 200) {
            throw new IllegalStateException("Got status code:" + response.getStatusCode());
        }
    }
}
Also used : Response(com.ning.http.client.Response) BoundRequestBuilder(com.ning.http.client.AsyncHttpClient.BoundRequestBuilder) ArtifactDownloadRequest(com.hubspot.singularity.s3.base.ArtifactDownloadRequest) S3Artifact(com.hubspot.deploy.S3Artifact) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException)

Aggregations

BoundRequestBuilder (com.ning.http.client.AsyncHttpClient.BoundRequestBuilder)21 IOException (java.io.IOException)13 Response (com.ning.http.client.Response)6 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)4 ExecutionException (java.util.concurrent.ExecutionException)3 SingularityLoadBalancerUpdate (com.hubspot.singularity.SingularityLoadBalancerUpdate)2 FluentCaseInsensitiveStringsMap (com.ning.http.client.FluentCaseInsensitiveStringsMap)2 Request (com.ning.http.client.Request)2 CompletableFuture (java.util.concurrent.CompletableFuture)2 BoundRequestBuilder (org.apache.apex.shaded.ning19.com.ning.http.client.AsyncHttpClient.BoundRequestBuilder)2 Response (org.apache.apex.shaded.ning19.com.ning.http.client.Response)2 Cookie (org.apache.apex.shaded.ning19.com.ning.http.client.cookie.Cookie)2 WebSocketUpgradeHandler (org.apache.apex.shaded.ning19.com.ning.http.client.ws.WebSocketUpgradeHandler)2 JsonParseException (org.codehaus.jackson.JsonParseException)2 JsonMappingException (org.codehaus.jackson.map.JsonMappingException)2 JSONException (org.codehaus.jettison.json.JSONException)2 JSONObject (org.codehaus.jettison.json.JSONObject)2 BaragonRequest (com.hubspot.baragon.models.BaragonRequest)1 BaragonResponse (com.hubspot.baragon.models.BaragonResponse)1 BaragonServiceState (com.hubspot.baragon.models.BaragonServiceState)1