Example usage for org.apache.http.client.methods HttpRequestBase releaseConnection

List of usage examples for org.apache.http.client.methods HttpRequestBase releaseConnection

Introduction

In this page you can find the example usage for org.apache.http.client.methods HttpRequestBase releaseConnection.

Prototype

public void releaseConnection() 

Source Link

Document

A convenience method to simplify migration from HttpClient 3.1 API.

Usage

From source file:com.liferay.ide.core.remote.RemoteConnection.java

protected Object httpJSONAPI(Object... args) throws APIException {
    if (!(args[0] instanceof HttpRequestBase)) {
        throw new IllegalArgumentException("First argument must be a HttpRequestBase."); //$NON-NLS-1$
    }//from ww  w. j  a v a 2  s .  co  m

    Object retval = null;
    String api = null;
    Object[] params = new Object[0];

    final HttpRequestBase request = (HttpRequestBase) args[0];

    final boolean isPostRequest = request instanceof HttpPost;

    if (args[1] instanceof String) {
        api = args[1].toString();
    } else if (args[1] instanceof Object[]) {
        params = (Object[]) args[1];
        api = params[0].toString();
    } else {
        throw new IllegalArgumentException("2nd argument must be either String or Object[]"); //$NON-NLS-1$
    }

    try {
        final URIBuilder builder = new URIBuilder();
        builder.setScheme("http"); //$NON-NLS-1$
        builder.setHost(getHost());
        builder.setPort(getHttpPort());
        builder.setPath(api);

        List<NameValuePair> postParams = new ArrayList<NameValuePair>();

        if (params.length >= 3) {
            for (int i = 1; i < params.length; i += 2) {
                String name = null;
                String value = StringPool.EMPTY;

                if (params[i] != null) {
                    name = params[i].toString();
                }

                if (params[i + 1] != null) {
                    value = params[i + 1].toString();
                }

                if (isPostRequest) {
                    postParams.add(new BasicNameValuePair(name, value));
                } else {
                    builder.setParameter(name, value);
                }
            }
        }

        if (isPostRequest) {
            HttpPost postRequest = ((HttpPost) request);

            if (postRequest.getEntity() == null) {
                postRequest.setEntity(new UrlEncodedFormEntity(postParams));
            }
        }

        request.setURI(builder.build());

        String response = getHttpResponse(request);

        if (response != null && response.length() > 0) {
            Object jsonResponse = getJSONResponse(response);

            if (jsonResponse == null) {
                throw new APIException(api, "Unable to get response: " + response); //$NON-NLS-1$
            } else {
                retval = jsonResponse;
            }
        }
    } catch (APIException e) {
        throw e;
    } catch (Exception e) {
        throw new APIException(api, e);
    } finally {
        try {
            request.releaseConnection();
        } finally {
            // no need to log error
        }
    }

    return retval;
}

From source file:com.intuit.tank.httpclient4.TankHttpClient4.java

private void sendRequest(BaseRequest request, @Nonnull HttpRequestBase method, String requestBody) {
    String uri = null;//  ww w .  j  a v a2 s.  c  om
    long waitTime = 0L;
    CloseableHttpResponse response = null;
    try {
        uri = method.getURI().toString();
        LOG.debug(request.getLogUtil().getLogMessage(
                "About to " + method.getMethod() + " request to " + uri + " with requestBody  " + requestBody,
                LogEventType.Informational));
        List<String> cookies = new ArrayList<String>();
        if (context.getCookieStore().getCookies() != null) {
            for (Cookie cookie : context.getCookieStore().getCookies()) {
                cookies.add("REQUEST COOKIE: " + cookie.toString());
            }
        }
        request.logRequest(uri, requestBody, method.getMethod(), request.getHeaderInformation(), cookies,
                false);
        setHeaders(request, method, request.getHeaderInformation());
        long startTime = System.currentTimeMillis();
        request.setTimestamp(new Date(startTime));
        response = httpclient.execute(method, context);

        // read response body
        byte[] responseBody = new byte[0];
        // check for no content headers
        if (response.getStatusLine().getStatusCode() != 203 && response.getStatusLine().getStatusCode() != 202
                && response.getStatusLine().getStatusCode() != 204) {
            try {
                InputStream httpInputStream = response.getEntity().getContent();
                responseBody = IOUtils.toByteArray(httpInputStream);
            } catch (Exception e) {
                LOG.warn("could not get response body: " + e);
            }
        }
        long endTime = System.currentTimeMillis();
        processResponse(responseBody, startTime, endTime, request, response.getStatusLine().getReasonPhrase(),
                response.getStatusLine().getStatusCode(), response.getAllHeaders());
        waitTime = endTime - startTime;
    } catch (Exception ex) {
        LOG.error(request.getLogUtil().getLogMessage(
                "Could not do " + method.getMethod() + " to url " + uri + " |  error: " + ex.toString(),
                LogEventType.IO), ex);
        throw new RuntimeException(ex);
    } finally {
        try {
            method.releaseConnection();
            if (response != null) {
                response.close();
            }
        } catch (Exception e) {
            LOG.warn("Could not release connection: " + e, e);
        }
        if (method.getMethod().equalsIgnoreCase("post")
                && request.getLogUtil().getAgentConfig().getLogPostResponse()) {
            LOG.info(request.getLogUtil()
                    .getLogMessage("Response from POST to " + request.getRequestUrl() + " got status code "
                            + request.getResponse().getHttpCode() + " BODY { " + request.getResponse().getBody()
                            + " }", LogEventType.Informational));
        }
    }
    if (waitTime != 0) {
        doWaitDueToLongResponse(request, waitTime, uri);
    }
}

From source file:com.twosigma.cook.jobclient.JobClient.java

/**
 * Query a group for its status.//from www.  j  a v  a  2 s .  c  o  m
 * @param group specifies the group to be queried.
 * @return a {@link Group} status.
 * @throws JobClientException
 */
public Group queryGroup(UUID guuid) throws JobClientException {
    if (_groupURI == null) {
        throw groupEndpointMissingException("Cannot query groups if the jobclient's group endpoint is null");
    }
    final List<NameValuePair> allParams = new ArrayList<NameValuePair>();
    allParams.add(new BasicNameValuePair("detailed", "true"));
    allParams.add(new BasicNameValuePair("uuid", guuid.toString()));

    Group result;
    HttpResponse httpResponse;
    HttpRequestBase httpRequest;
    try {
        URIBuilder uriBuilder = new URIBuilder(_groupURI);
        uriBuilder.addParameters(allParams);
        httpRequest = new HttpGet(uriBuilder.build());
        httpResponse = _httpClient.execute(httpRequest);
    } catch (IOException | URISyntaxException e) {
        throw releaseAndCreateException(null, null,
                "Can not submit GET request " + allParams + " via uri " + _jobURI, e);
    }

    // Check status code.
    final StatusLine statusLine = httpResponse.getStatusLine();
    // Base on the decision graph
    // http://clojure-liberator.github.io/liberator/tutorial/decision-graph.html
    // The status code for the proper GET response is 200.
    if (statusLine.getStatusCode() != HttpStatus.SC_OK) {
        throw releaseAndCreateException(httpRequest, httpResponse,
                "The response of GET request " + allParams + " via uri " + _jobURI + ": "
                        + statusLine.getReasonPhrase() + ", " + statusLine.getStatusCode(),
                null);
    }
    // Parse the response.
    String response = null;
    try {
        // parse the response to string.
        final HttpEntity entity = httpResponse.getEntity();
        response = EntityUtils.toString(entity);
        // Ensure that the entity content has been fully consumed and the underlying stream has been closed.
        EntityUtils.consume(entity);
        result = Group.parseFromJSON(response, _instanceDecorator).get(0);
    } catch (JSONException | ParseException | IOException | IndexOutOfBoundsException e) {
        throw new JobClientException("Can not parse the response = " + response + " for GET request "
                + allParams + " via uri " + _jobURI, e);
    } finally {
        httpRequest.releaseConnection();
    }
    return result;
}

From source file:com.twosigma.cook.jobclient.JobClient.java

/**
 * Query jobs for a given list of job {@link UUID}s. If the list size is larger that the
 * {@code _batchRequestSize}, it will partition the list into smaller lists and query them
 * respectively and return all query results together.
 *
 * @param uuids specifies a list of job {@link UUID}s expected to query.
 * @return a {@link ImmutableMap} from job {@link UUID} to {@link Job}.
 * @throws JobClientException/*  w w w .j a v a 2 s .co m*/
 */
public ImmutableMap<UUID, Job> queryJobs(Collection<UUID> uuids) throws JobClientException {
    final List<NameValuePair> allParams = new ArrayList<NameValuePair>(uuids.size());
    for (UUID uuid : uuids) {
        allParams.add(new BasicNameValuePair("job", uuid.toString()));
    }
    final ImmutableMap.Builder<UUID, Job> UUIDToJob = ImmutableMap.builder();
    // Partition a large query into small queries.
    for (final List<NameValuePair> params : Lists.partition(allParams, _batchRequestSize)) {
        HttpResponse httpResponse;
        HttpRequestBase httpRequest;
        try {
            URIBuilder uriBuilder = new URIBuilder(_jobURI);
            uriBuilder.addParameters(params);
            httpRequest = new HttpGet(uriBuilder.build());
            httpResponse = _httpClient.execute(httpRequest);
        } catch (IOException | URISyntaxException e) {
            throw releaseAndCreateException(null, null,
                    "Can not submit GET request " + params + " via uri " + _jobURI, e);
        }
        // Check status code.
        final StatusLine statusLine = httpResponse.getStatusLine();
        // Base on the decision graph
        // http://clojure-liberator.github.io/liberator/tutorial/decision-graph.html
        // The status code for the proper GET response is 200.
        if (statusLine.getStatusCode() != HttpStatus.SC_OK) {
            throw releaseAndCreateException(httpRequest, httpResponse,
                    "The response of GET request " + params + " via uri " + _jobURI + ": "
                            + statusLine.getReasonPhrase() + ", " + statusLine.getStatusCode(),
                    null);
        }
        // Parse the response.
        String response = null;
        try {
            // parse the response to string.
            final HttpEntity entity = httpResponse.getEntity();
            response = EntityUtils.toString(entity);
            // Ensure that the entity content has been fully consumed and the underlying stream has been closed.
            EntityUtils.consume(entity);
            for (Job job : Job.parseFromJSON(response, _instanceDecorator)) {
                UUIDToJob.put(job.getUUID(), job);
            }
        } catch (JSONException | ParseException | IOException e) {
            throw new JobClientException("Can not parse the response = " + response + " for GET request "
                    + params + " via uri " + _jobURI, e);
        } finally {
            httpRequest.releaseConnection();
        }
    }
    return UUIDToJob.build();
}

From source file:com.twosigma.cook.jobclient.JobClient.java

/**
 * Query a collection of groups for their status.
 * @param guuids specifies the uuids of the {@link Group}s to be queried.
 * @return a map of {@link UUID}s to {@link Group}s.
 * @throws JobClientException//from  w w w  .  jav  a2s .  c o m
 */
public ImmutableMap<UUID, Group> queryGroups(Collection<UUID> guuids) throws JobClientException {
    if (_groupURI == null) {
        throw groupEndpointMissingException("Cannot query groups if the jobclient's group endpoint is null");
    }
    final List<NameValuePair> allParams = new ArrayList<NameValuePair>(guuids.size());
    for (UUID guuid : guuids) {
        allParams.add(new BasicNameValuePair("uuid", guuid.toString()));
    }
    allParams.add(new BasicNameValuePair("detailed", "true"));
    final ImmutableMap.Builder<UUID, Group> UUIDToGroup = ImmutableMap.builder();
    // Partition a large query into small queries.
    for (final List<NameValuePair> params : Lists.partition(allParams, _batchRequestSize)) {
        HttpResponse httpResponse;
        HttpRequestBase httpRequest;
        try {
            URIBuilder uriBuilder = new URIBuilder(_groupURI);
            uriBuilder.addParameters(params);
            httpRequest = new HttpGet(uriBuilder.build());
            httpResponse = _httpClient.execute(httpRequest);
        } catch (IOException | URISyntaxException e) {
            throw releaseAndCreateException(null, null,
                    "Can not submit GET request " + params + " via uri " + _jobURI, e);
        }
        // Check status code.
        final StatusLine statusLine = httpResponse.getStatusLine();
        // Base on the decision graph
        // http://clojure-liberator.github.io/liberator/tutorial/decision-graph.html
        // The status code for the proper GET response is 200.
        if (statusLine.getStatusCode() != HttpStatus.SC_OK) {
            throw releaseAndCreateException(httpRequest, httpResponse,
                    "The response of GET request " + params + " via uri " + _jobURI + ": "
                            + statusLine.getReasonPhrase() + ", " + statusLine.getStatusCode(),
                    null);
        }
        // Parse the response.
        String response = null;
        try {
            // parse the response to string.
            final HttpEntity entity = httpResponse.getEntity();
            response = EntityUtils.toString(entity);
            // Ensure that the entity content has been fully consumed and the underlying stream has been closed.
            EntityUtils.consume(entity);
            for (Group group : Group.parseFromJSON(response, _instanceDecorator)) {
                UUIDToGroup.put(group.getUUID(), group);
            }
        } catch (JSONException | ParseException | IOException e) {
            throw new JobClientException("Can not parse the response = " + response + " for GET request "
                    + params + " via uri " + _jobURI, e);
        } finally {
            httpRequest.releaseConnection();
        }
    }
    return UUIDToGroup.build();

}

From source file:com.cloudbees.jenkins.plugins.bitbucket.server.client.BitbucketServerAPIClient.java

private String doRequest(HttpRequestBase request) throws IOException {
    if (authenticator != null) {
        authenticator.configureRequest(request);
    }/*from w  w w.j  a  v  a  2s . co m*/

    try (CloseableHttpClient client = getHttpClient(request);
            CloseableHttpResponse response = client.execute(request, context)) {
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_NO_CONTENT) {
            EntityUtils.consume(response.getEntity());
            // 204, no content
            return "";
        }
        String content;
        long len = -1L;
        Header[] headers = request.getHeaders("Content-Length");
        if (headers != null && headers.length > 0) {
            int i = headers.length - 1;
            len = -1L;
            while (i >= 0) {
                Header header = headers[i];
                try {
                    len = Long.parseLong(header.getValue());
                    break;
                } catch (NumberFormatException var5) {
                    --i;
                }
            }
        }
        if (len == 0) {
            content = "";
        } else {
            ByteArrayOutputStream buf;
            if (len > 0 && len <= Integer.MAX_VALUE / 2) {
                buf = new ByteArrayOutputStream((int) len);
            } else {
                buf = new ByteArrayOutputStream();
            }
            try (InputStream is = response.getEntity().getContent()) {
                IOUtils.copy(is, buf);
            }
            content = new String(buf.toByteArray(), StandardCharsets.UTF_8);
        }
        EntityUtils.consume(response.getEntity());
        if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK
                && response.getStatusLine().getStatusCode() != HttpStatus.SC_CREATED) {
            throw new BitbucketRequestException(response.getStatusLine().getStatusCode(),
                    "HTTP request error. Status: " + response.getStatusLine().getStatusCode() + ": "
                            + response.getStatusLine().getReasonPhrase() + ".\n" + response);
        }
        return content;
    } finally {
        request.releaseConnection();
    }
}

From source file:com.twosigma.cook.jobclient.JobClient.java

/**
 * Abort jobs for a given list of job {@link UUID}s. If the size of the list is larger that the
 * {@code _batchRequestSize}, it will partition the list into smaller lists to abort separately.
 *
 * @param uuids specifies a list of job {@link UUID}s expected to abort.
 * @throws JobClientException/*  w  ww.  j av  a2  s  .  co  m*/
 */
public void abort(Collection<UUID> uuids) throws JobClientException {
    final List<NameValuePair> allParams = new ArrayList<NameValuePair>(uuids.size());
    for (UUID uuid : uuids) {
        allParams.add(new BasicNameValuePair("job", uuid.toString()));
    }
    // Partition a large query into small queries.
    for (final List<NameValuePair> params : Lists.partition(allParams, _batchRequestSize)) {
        HttpRequestBase httpRequest;
        try {
            URIBuilder uriBuilder = new URIBuilder(_jobURI);
            uriBuilder.addParameters(params);
            httpRequest = new HttpDelete(uriBuilder.build());
        } catch (URISyntaxException e) {
            throw releaseAndCreateException(null, null,
                    "Can not submit DELETE request " + params + " via uri " + _jobURI, e);
        }
        HttpResponse httpResponse;
        try {
            httpResponse = _httpClient.execute(httpRequest);
        } catch (IOException e) {
            throw releaseAndCreateException(httpRequest, null,
                    "Can not submit DELETE request " + params + " via uri " + _jobURI, e);
        }
        // Check status code.
        final StatusLine statusLine = httpResponse.getStatusLine();
        // Base on the decision graph
        // http://clojure-liberator.github.io/liberator/tutorial/decision-graph.html
        // If jobs are aborted successfully, the returned status code is 204.
        if (statusLine.getStatusCode() != HttpStatus.SC_NO_CONTENT) {
            throw releaseAndCreateException(
                    httpRequest, httpResponse, "The response of DELETE request " + params + " via uri "
                            + _jobURI + ": " + statusLine.getReasonPhrase() + ", " + statusLine.getStatusCode(),
                    null);
        }
        // Parse the response.
        try {
            // Parse the response to string.
            final HttpEntity entity = httpResponse.getEntity();
            if (null != entity) {
                final String response = EntityUtils.toString(entity);
                if (_log.isDebugEnabled()) {
                    _log.debug("Response String for aborting jobs " + uuids + " is " + response);
                }
            }
        } catch (ParseException | IOException e) {
            throw new JobClientException(
                    "Can not parse the response for DELETE request " + params + " via uri " + _jobURI, e);
        } finally {
            httpRequest.releaseConnection();
        }
    }
}

From source file:com.twosigma.cook.jobclient.JobClient.java

/**
 * Submit a list of jobs to Cook scheduler and start to track these jobs until they complete. Note that jobs
 * submitted through this API will not be listened by any listener.
 *
 * @param jobs specifies a list of {@link Job}s to be submitted.
 * @return the response string from Cook scheduler rest endpoint.
 * @throws JobClientException//  ww w . j  a  v a2s.  c  om
 */
public void submit(List<Job> jobs) throws JobClientException {
    JSONObject json;
    try {
        json = Job.jsonizeJob(jobs);
    } catch (JSONException e) {
        throw new JobClientException("Can not jsonize jobs to submit.", e);
    }
    HttpResponse httpResponse;
    HttpRequestBase httpRequest = makeHttpPost(_jobURI, json);
    try {
        httpResponse = executeWithRetries(httpRequest, 5, 10);
    } catch (IOException e) {
        throw releaseAndCreateException(httpRequest, null,
                "Can not submit POST request " + json + " via uri " + _jobURI, e);
    }

    // Get the response string.
    StatusLine statusLine = httpResponse.getStatusLine();
    HttpEntity entity = httpResponse.getEntity();
    if (entity == null) {
        throw releaseAndCreateException(httpRequest, null, "The response entity is null!", null);
    }
    String response = null;
    try {
        response = EntityUtils.toString(entity);
        // Ensure that the entity content has been fully consumed and the underlying stream has been closed.
        EntityUtils.consume(entity);
    } catch (ParseException | IOException e) {
        throw releaseAndCreateException(httpRequest, null,
                "Can not parse the response for POST request " + json + " via uri " + _jobURI, e);
    }
    if (_log.isDebugEnabled()) {
        _log.debug("Response String for submitting jobs" + json.toString() + " is " + response);
    }

    // Base on the decision graph
    // http://clojure-liberator.github.io/liberator/tutorial/decision-graph.html
    // If the jobs are submitted successfully, the status code is 201.
    // If a job uses a UUID which has been used before, the returned status code is 400 and the
    // return message is something like:
    // clojure.lang.ExceptionInfo: UUID 26719da8-194f-44f9-9e6d-8a17500f5109 already used {:uuid
    // #uuid "26719da8-194f-44f9-9e6d-8a17500f5109"}

    // A flag to indicate if the submission is successful.
    boolean isSuccess = false;
    if (null != statusLine && statusLine.getStatusCode() == HttpStatus.SC_CREATED) {
        isSuccess = true;
        _log.info("Successfully execute POST request with data " + json + " via uri " + _jobURI);
    } else if (null != statusLine && statusLine.getStatusCode() >= HttpStatus.SC_BAD_REQUEST) {
        final Pattern patternUUID = Pattern
                .compile("[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89aAbB][a-f0-9]{3}-[a-f0-9]{12} already used");
        final Matcher matchUUID = patternUUID.matcher(response);
        if (matchUUID.find()) {
            _log.info("Successfully execute POST request with several retries " + json + " via uri " + _jobURI);
            isSuccess = true;
        } else {
            _log.warn("Failed to execute POST request with several retries " + json + " via uri " + _jobURI);
        }
    }
    if (null != httpRequest) {
        httpRequest.releaseConnection();
    }
    if (isSuccess) {
        // Update status map.
        for (Job job : jobs) {
            _activeUUIDToJob.put(job.getUUID(), job);
        }
    } else {
        _log.error("Failed to submit jobs " + json.toString());
        throw new JobClientException("The response of POST request " + json + " via uri " + _jobURI + ": "
                + statusLine.getReasonPhrase() + ", " + statusLine.getStatusCode() + ", response is: "
                + response);
    }
}