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.sap.core.odata.testutil.tool.core.SupaController.java

private String call(final String supaCommand) {
    HttpRequestBase request = null;
    try {/*w  ww  . j a  v a2s  .c  o  m*/
        request = new HttpGet(baseUri + supaCommand);

        LOG.debug("Call for request line '{}'", request.getRequestLine());

        final HttpHost targetHost = new HttpHost(baseUri.getHost(), baseUri.getPort());
        final HttpResponse response = httpClient.execute(targetHost, request);

        //
        return extractSupaInformation(response.getEntity());
    } catch (final IOException e) {
        LOG.debug("Got exception for calling supa command '" + supaCommand + "'.");
        return "Exception";
    } finally {
        if (request != null) {
            request.releaseConnection();
        }
    }
}

From source file:com.thoughtworks.go.agent.service.TokenRequester.java

public String getToken() throws IOException {
    LOGGER.debug("[Agent Registration] Using URL {} to get a token.", tokenURL);

    HttpRequestBase getTokenRequest = (HttpRequestBase) RequestBuilder.get(tokenURL)
            .addParameter("uuid", agentRegistry.uuid()).build();

    try {/*w  ww .  ja va2s .  c  om*/
        CloseableHttpResponse response = httpClient.execute(getTokenRequest);
        final String responseBody = responseBody(response);
        if (response.getStatusLine().getStatusCode() == SC_OK) {
            LOGGER.info("The server has generated token for the agent.");
            return responseBody;
        } else {
            LOGGER.error("Received status code from server {}", response.getStatusLine().getStatusCode());
            LOGGER.error("Reason for failure {} ", responseBody);
            throw new RuntimeException(responseBody);
        }
    } finally {
        getTokenRequest.releaseConnection();
    }
}

From source file:uk.co.visalia.brightpearl.apiclient.http.httpclient4.HttpClient4Client.java

/**
 * {@inheritDoc}/*from  w  w w  .  ja va 2 s .c  o  m*/
 * @param request The request to be executed.
 * @return Response from the Brightpearl API.
 */
@Override
public Response execute(Request request) {

    if (httpClient == null) {
        throw new IllegalStateException("HttpClient has been shut down");
    }

    HttpRequestBase clientRequest = buildRequest(request);

    try {
        HttpResponse clientResponse = httpClient.execute(clientRequest);

        int status = clientResponse.getStatusLine().getStatusCode();
        Map<String, String> headers = new HashMap<String, String>();
        for (Header header : clientResponse.getAllHeaders()) {
            headers.put(header.getName(), header.getValue());
        }
        String body = EntityUtils.toString(clientResponse.getEntity());

        return ResponseBuilder.newResponse().withStatus(status).withHeaders(headers).withBody(body).build();

    } catch (Exception e) {
        throw resolveException(e);
    } finally {
        clientRequest.releaseConnection();
    }

}

From source file:org.riotfamily.linkcheck.HttpStatusChecker.java

public boolean isOkay(BrokenLink link) {
    try {// w w  w.j a  v a 2  s. co m
        HttpRequestBase http = createMethod(link.getDestination());

        try {
            HttpResponse httpResponse = client.execute(http);
            int statusCode = httpResponse.getStatusLine().getStatusCode();
            if (log.isDebugEnabled()) {
                if (log.isDebugEnabled()) {
                    log.debug("Check: " + link + " [" + statusCode + "]");
                }
            }
            link.setStatusCode(statusCode);
            if (statusCode == HttpStatus.SC_OK) {
                return true;
            } else {
                link.setStatusText(httpResponse.getStatusLine().getReasonPhrase());
            }
        } catch (IOException e) {
            log.info(e.getMessage());
        } finally {
            http.releaseConnection();
        }
    } catch (IllegalArgumentException e) {
    } catch (IllegalStateException e) {
    }
    return false;
}

From source file:net.javacrumbs.restfire.httpcomponents.HttpComponentsResponse.java

public HttpComponentsResponse(HttpClient httpClient, HttpRequestBase method) {
    try {// ww  w.ja v a  2 s.  com
        long executionStart = System.currentTimeMillis();
        HttpResponse response = httpClient.execute(method);
        duration = System.currentTimeMillis() - executionStart;

        HttpEntity responseEntity = response.getEntity();
        if (responseEntity != null) {
            responseBody = EntityUtils.toByteArray(responseEntity);
            charset = getCharset(responseEntity);
        } else {
            responseBody = null;
            charset = null;
        }
        headers = buildHeaderMap(response);
        statusCode = response.getStatusLine().getStatusCode();
    } catch (IOException e) {
        throw new IllegalArgumentException("Can not execute method", e);
    } finally {
        method.releaseConnection();
    }
}

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

private void release(HttpRequestBase method) {
    method.releaseConnection();
    connectionManager.closeExpiredConnections();
}

From source file:org.openmhealth.shim.OAuth1ShimBase.java

@Override
public AuthorizationResponse handleAuthorizationResponse(HttpServletRequest servletRequest)
        throws ShimException {

    // Fetch the access token.
    String stateKey = servletRequest.getParameter("state");
    String requestToken = servletRequest.getParameter(OAuth.OAUTH_TOKEN);
    final String requestVerifier = servletRequest.getParameter(OAuth.OAUTH_VERIFIER);

    AuthorizationRequestParameters authParams = authorizationRequestParametersRepo.findByStateKey(stateKey);
    if (authParams == null) {
        throw new ShimException("Invalid state, could not find corresponding auth parameters");
    }//from   ww  w  .j a v a 2 s .co  m

    // Get the token secret from the original access request.
    String requestTokenSecret = authParams.getRequestParams().get(OAuth.OAUTH_TOKEN_SECRET);

    HttpResponse response;
    HttpRequestBase accessTokenRequest = null;
    try {
        accessTokenRequest = getAccessTokenRequest(getBaseTokenUrl(), requestToken, requestTokenSecret,
                new HashMap<String, String>() {
                    {
                        put(OAuth.OAUTH_VERIFIER, requestVerifier);
                    }
                });
        response = httpClient.execute(accessTokenRequest);
    } catch (IOException e) {
        e.printStackTrace();
        throw new ShimException("Could not retrieve response from token URL");
    } finally {
        if (accessTokenRequest != null) {
            accessTokenRequest.releaseConnection();
        }
    }
    Map<String, String> accessTokenParameters = OAuth1Utils.parseRequestTokenResponse(response);
    String accessToken = accessTokenParameters.get(OAuth.OAUTH_TOKEN);
    String accessTokenSecret = accessTokenParameters.get(OAuth.OAUTH_TOKEN_SECRET);

    if (accessToken == null) {
        throw new ShimException("Access token could not be retrieved");
    }

    ApplicationAccessParameters parameters = findApplicationAccessParameters();
    AccessParameters accessParameters = new AccessParameters();
    accessParameters.setClientId(parameters.getClientId());
    accessParameters.setClientSecret(parameters.getClientSecret());
    accessParameters.setStateKey(stateKey);
    accessParameters.setUsername(authParams.getUsername());
    accessParameters.setAccessToken(accessToken);
    accessParameters.setTokenSecret(accessTokenSecret);
    accessParameters.setAdditionalParameters(new HashMap<String, Object>() {
        {
            put(OAuth.OAUTH_VERIFIER, requestVerifier);
        }
    });
    loadAdditionalAccessParameters(servletRequest, accessParameters);
    return AuthorizationResponse.authorized(accessParameters);
}

From source file:mobi.jenkinsci.ci.client.JenkinsHttpClient.java

public HttpResponse execute(final HttpRequestBase req) throws IOException {
    LOG.debug("Executing '" + req.getMethod() + " " + req.getURI() + "'");

    if (!(httpClient instanceof JenkinsFormAuthHttpClient) && config.getUsername() != null
            && config.getUsername().trim().length() > 0) {
        ensurePreemptiveAuthRequest(req);
    }/* w  w w  . j a v a 2  s .com*/

    HttpResponse response = httpContext == null ? httpClient.execute(req)
            : httpClient.execute(req, httpContext);
    if (response == null) {
        throw new IOException("Cannot contact URL " + req.getURI());
    }

    final int responseStatus = response.getStatusLine().getStatusCode();
    if ((responseStatus == HttpURLConnection.HTTP_UNAUTHORIZED
            || responseStatus == HttpURLConnection.HTTP_FORBIDDEN)) {
        req.releaseConnection();

        httpClient = new JenkinsFormAuthHttpClient(httpClientFactory.getHttpClient(), config.getUrl(),
                config.getUsername(), config.getPassword(),
                req.getFirstHeader(Constants.X_AUTH_OTP_HEADER) != null
                        ? req.getFirstHeader(Constants.X_AUTH_OTP_HEADER).getValue()
                        : null);
        response = httpClient.execute(req);
        httpContext = null;
    }

    return elaborateResponse(response);
}

From source file:org.neo4j.ogm.drivers.http.driver.HttpDriver.java

public CloseableHttpResponse executeHttpRequest(HttpRequestBase request) throws HttpRequestException {

    try (CloseableHttpResponse response = HttpRequest.execute(httpClient(), request,
            configuration.getCredentials())) {
        HttpEntity responseEntity = response.getEntity();
        if (responseEntity != null) {
            JsonNode responseNode = mapper.readTree(EntityUtils.toString(responseEntity));
            LOGGER.debug("Response: {}", responseNode);
            JsonNode errors = responseNode.findValue("errors");
            if (errors.elements().hasNext()) {
                JsonNode errorNode = errors.elements().next();
                throw new CypherException("Error executing Cypher", errorNode.findValue("code").asText(),
                        errorNode.findValue("message").asText());
            }/*from w ww  .ja  v  a 2  s . com*/
        }
        return response;
    } catch (IOException ioe) {
        throw new HttpRequestException(request, ioe);
    } finally {
        request.releaseConnection();
        LOGGER.debug("Thread: {}, Connection released", Thread.currentThread().getId());
    }
}