Java Code Examples for org.apache.http.client.methods.HttpRequestBase#releaseConnection()

The following examples show how to use org.apache.http.client.methods.HttpRequestBase#releaseConnection() . 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: BrocadeVcsApi.java    From cloudstack with Apache License 2.0 6 votes vote down vote up
protected HttpResponse executeMethod(HttpRequestBase method) throws BrocadeVcsApiException {
    HttpResponse response = null;
    try {
        response = _client.execute(method);
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
            method.releaseConnection();
            response = _client.execute(method);
        }
    } catch (final IOException e) {
        s_logger.error("IOException caught while trying to connect to the Brocade Switch", e);
        method.releaseConnection();
        throw new BrocadeVcsApiException("API call to Brocade Switch Failed", e);
    }

    return response;
}
 
Example 2
Source File: TokenRequester.java    From gocd with Apache License 2.0 6 votes vote down vote up
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 (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();
    }
}
 
Example 3
Source File: HttpRequestUtil.java    From spark-jobs-rest-client with Apache License 2.0 6 votes vote down vote up
static <T extends SparkResponse>  T executeHttpMethodAndGetResponse(HttpClient client, HttpRequestBase httpRequest, Class<T> responseClass) throws FailedSparkRequestException {
    T response;
    try {
        final String stringResponse = client.execute(httpRequest, new BasicResponseHandler());
        if (stringResponse != null) {
            response = MapperWrapper.MAPPER.readValue(stringResponse, responseClass);
        } else {
            throw new FailedSparkRequestException("Received empty string response");
        }
    } catch (IOException e) {
        throw new FailedSparkRequestException(e);
    } finally {
        httpRequest.releaseConnection();
    }

    if (response == null) {
        throw new FailedSparkRequestException("An issue occured with the cluster's response.");
    }

    return response;
}
 
Example 4
Source File: JettyWebappTest.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
public void testAdminUI() throws Exception
{
  // Currently not an extensive test, but it does fire up the JSP pages and make
  // sure they compile ok

  String adminPath = "http://127.0.0.1:"+port+context+"/";
  byte[] bytes = IOUtils.toByteArray( new URL(adminPath).openStream() );
  assertNotNull( bytes ); // real error will be an exception

  HttpClient client = HttpClients.createDefault();
  HttpRequestBase m = new HttpGet(adminPath);
  HttpResponse response = client.execute(m, HttpClientUtil.createNewHttpClientRequestContext());
  assertEquals(200, response.getStatusLine().getStatusCode());
  Header header = response.getFirstHeader("X-Frame-Options");
  assertEquals("DENY", header.getValue().toUpperCase(Locale.ROOT));
  m.releaseConnection();
}
 
Example 5
Source File: DefaultHttpClient.java    From wc-api-java with MIT License 6 votes vote down vote up
private <T> T getEntityAndReleaseConnection(HttpRequestBase httpRequest, Class<T> objectClass) {
    try {
        HttpResponse httpResponse = httpClient.execute(httpRequest);
        HttpEntity httpEntity = httpResponse.getEntity();
        if (httpEntity == null) {
            throw new RuntimeException("Error retrieving results from http request");
        }
        Object result = mapper.readValue(httpEntity.getContent(), Object.class);
        if (objectClass.isInstance(result)) {
            return objectClass.cast(result);
        }
        throw new RuntimeException("Can't parse retrieved object: " + result.toString());
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        httpRequest.releaseConnection();
    }
}
 
Example 6
Source File: HttpRequestUtil.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * Executes HTTPMethod without retry
 *
 * @param httpClient HTTPClient
 * @param httpMethod HTTPMethod
 * @return response. it will return an empty string if response body is null
 * @throws OnPremiseGatewayException throws {@link OnPremiseGatewayException}
 */
public static String executeHTTPMethod(HttpClient httpClient, HttpRequestBase httpMethod)
        throws OnPremiseGatewayException {

    String result;
    HttpResponse response;
    String uri = getURI(httpMethod);
    String methodName = httpMethod.getMethod();

    //Add an unique identifier as an custom header for distinguishing requests from different micro gateways.
    String token = ConfigManager.getConfigurationDTO().getStatus_unique_identifier();
    if (StringUtils.isNotBlank(token) && !(OnPremiseGatewayConstants.API_REQUEST_UNIQUE_IDENTIFIER_HOLDER
            .equals(token))) {
        if (log.isDebugEnabled()) {
            log.debug("Adding unique identifier as an header to the http " + methodName + " request.");
        }
        httpMethod.addHeader(OnPremiseGatewayConstants.APT_REQUEST_TOKEN_HEADER, token);
    }
    try {
        response = httpClient.execute(httpMethod);
        if (log.isDebugEnabled()) {
            log.debug("HTTP response code for the " + methodName + " request: " + uri + " is " + response);
        }
        result = handleResponse(response, methodName, false, 0, 0, uri);
    } catch (IOException e) {
        throw new OnPremiseGatewayException(methodName + " request failed for URI: " + uri, e);
    } finally {
        httpMethod.releaseConnection();
    }
    return result;
}
 
Example 7
Source File: HttpRequestUtil.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * Executes the HTTPMethod with retry.
 *
 * @param httpClient     HTTPClient
 * @param httpMethod     HTTPMethod
 * @param retryCount No of retries
 * @return response. it will return an empty string if response body is null
 * @throws OnPremiseGatewayException throws {@link OnPremiseGatewayException}
 */
public static String executeHTTPMethodWithRetry(HttpClient httpClient, HttpRequestBase httpMethod, int retryCount)
        throws OnPremiseGatewayException {

    String result = OnPremiseGatewayConstants.EMPTY_STRING;
    HttpResponse response;
    int executionCount = 0;
    String methodName = httpMethod.getMethod();
    String uri = getURI(httpMethod);

    //Add an unique identifier as a custom header for distinguishing requests from different micro gateways.
    String token = ConfigManager.getConfigurationDTO().getStatus_unique_identifier();
    if (StringUtils.isNotBlank(token) && !(OnPremiseGatewayConstants.API_REQUEST_UNIQUE_IDENTIFIER_HOLDER
            .equals(token))) {
        if (log.isDebugEnabled()) {
            log.debug("Adding unique identifier as an header to the http " + methodName + " request.");
        }
        httpMethod.addHeader(OnPremiseGatewayConstants.APT_REQUEST_TOKEN_HEADER, token);
    }
    do {
        try {
            executionCount++;
            response = httpClient.execute(httpMethod);
            if (log.isDebugEnabled()) {
                log.debug(
                        "HTTP response code for the " + methodName + " request to URL: " + uri + " is " + response);
            }
            result = handleResponse(response, methodName, true, executionCount, retryCount, uri);
            if (!OnPremiseGatewayConstants.EMPTY_STRING.equals(result)) {
                return result;
            }
        } catch (IOException e) {
            handleExceptionWithRetry(executionCount, retryCount, methodName, uri, e);
        } finally {
            httpMethod.releaseConnection();
        }
    } while (executionCount < retryCount);
    return result;
}
 
Example 8
Source File: AbstractContentNegotiationTest.java    From olingo-odata2 with Apache License 2.0 5 votes vote down vote up
public void execute(final URI serviceEndpoint) throws Exception {
  HttpRequestBase request = null;

  try {
    String endpoint = serviceEndpoint.toASCIIString();
    String requestUrl = endpoint.substring(0, endpoint.length() - 1) + path;
    if (queryOptions != null) {
      requestUrl += queryOptions;
    }
    request = this.request.createRequest(requestUrl);

    requestLine = request.getRequestLine().toString();
    HttpClient httpClient = new DefaultHttpClient();

    LOG.debug("Execute test for [" + requestLine + "]");
    final HttpResponse response = httpClient.execute(request);
    LOG.debug("Got response for request [" + requestLine + "]");

    int resultStatusCode = response.getStatusLine().getStatusCode();
    assertEquals("Unexpected status code for " + toString(), expectedStatusCode.getStatusCode(), resultStatusCode);

    final String contentType = response.getFirstHeader(HttpHeaders.CONTENT_TYPE).getValue();
    assertEquals("Unexpected content type for " + toString(), ContentType.create(expectedContentType), ContentType
        .create(contentType));

    if (isContentExpected) {
      assertNotNull("Unexpected content for " + toString(), StringHelper.inputStreamToString(response.getEntity()
          .getContent()));
    }
    LOG.trace("Test passed [" + toString() + "]");
  } finally {
    if (request != null) {
      request.releaseConnection();
      LOG.debug("Released connection [" + requestLine + "]");
    }
  }
}
 
Example 9
Source File: RestClient.java    From kylin with Apache License 2.0 5 votes vote down vote up
private void cleanup(HttpRequestBase request, HttpResponse response) {
    try {
        if (response != null)
            EntityUtils.consume(response.getEntity());
    } catch (Exception ex) {
        logger.error("Error during HTTP connection cleanup", ex);
    }
    request.releaseConnection();
}
 
Example 10
Source File: ElasticsearchClient.java    From elasticsearch-maven-plugin with Apache License 2.0 5 votes vote down vote up
protected String executeRequest(HttpRequestBase request) throws ElasticsearchClientException
{
    Validate.notNull(httpClient, "Has the ElasticsearchClient been initialized?");
    
    try
    {
        HttpResponse response = httpClient.execute(request);

        int statusCode = response.getStatusLine().getStatusCode();
        String content = readContent(response.getEntity());
        log.debug(String.format(
                "Response with status code %d and content: %s", statusCode, content));

        // some PUT requests return 200, some 201 :-O
        if (statusCode != 200 && statusCode != 201)
        {
            throw new ElasticsearchClientException(request.getMethod(), statusCode, content);
        }

        return content;
    }
    catch (IOException e)
    {
        throw new ElasticsearchClientException(e);
    }
    finally
    {
        request.releaseConnection();
    }
}
 
Example 11
Source File: HttpClient.java    From embedded-elasticsearch with Apache License 2.0 5 votes vote down vote up
<T> T execute(HttpRequestBase request, Function<CloseableHttpResponse, T> block) {
    try (CloseableHttpResponse response = internalHttpClient.execute(request)) {
        return block.apply(response);
    } catch (IOException e) {
        throw new HttpRequestException(e);
    } finally {
        request.releaseConnection();
    }
}
 
Example 12
Source File: HttpClientService.java    From cs-actions with Apache License 2.0 5 votes vote down vote up
private void checkKeepAlive(HttpRequestBase httpRequestBase, PoolingHttpClientConnectionManager connManager,
                            String keepAliveInput, CloseableHttpResponse httpResponse) {
    boolean keepAlive = StringUtils.isBlank(keepAliveInput) || Boolean.parseBoolean(keepAliveInput);
    if (keepAlive) {
        httpRequestBase.releaseConnection();
    } else {
        try {
            httpResponse.close();
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
        httpRequestBase.releaseConnection();
        connManager.closeExpiredConnections();
    }
}
 
Example 13
Source File: AbstractContentNegotiationTest.java    From cloud-odata-java with Apache License 2.0 5 votes vote down vote up
public void execute(final URI serviceEndpoint) throws Exception {
  HttpRequestBase request = null;

  try {
    String endpoint = serviceEndpoint.toASCIIString();
    String requestUrl = endpoint.substring(0, endpoint.length() - 1) + path;
    if (queryOptions != null) {
      requestUrl += queryOptions;
    }
    request = this.request.createRequest(requestUrl);

    requestLine = request.getRequestLine().toString();
    HttpClient httpClient = new DefaultHttpClient();

    LOG.debug("Execute test for [" + requestLine + "]");
    final HttpResponse response = httpClient.execute(request);
    LOG.debug("Got response for request [" + requestLine + "]");

    int resultStatusCode = response.getStatusLine().getStatusCode();
    assertEquals("Unexpected status code for " + toString(), expectedStatusCode.getStatusCode(), resultStatusCode);

    final String contentType = response.getFirstHeader(HttpHeaders.CONTENT_TYPE).getValue();
    assertEquals("Unexpected content type for " + toString(), ContentType.create(expectedContentType), ContentType.create(contentType));

    if (isContentExpected) {
      assertNotNull("Unexpected content for " + toString(), StringHelper.inputStreamToString(response.getEntity().getContent()));
    }
    LOG.trace("Test passed [" + toString() + "]");
  } finally {
    if (request != null) {
      request.releaseConnection();
      LOG.debug("Released connection [" + requestLine + "]");
    }
  }
}
 
Example 14
Source File: RestService.java    From kylin-on-parquet-v2 with Apache License 2.0 5 votes vote down vote up
public String execRequest(HttpRequestBase request, int connectionTimeout, int readTimeout) throws IOException {
    HttpClient httpClient = getHttpClient(connectionTimeout, readTimeout);
    try {
        HttpResponse response = httpClient.execute(request);
        String msg = EntityUtils.toString(response.getEntity());
        int code = response.getStatusLine().getStatusCode();
        if (logger.isTraceEnabled()) {
            String displayMessage;
            if (msg.length() > 500) {
                displayMessage = msg.substring(0, 500);
            } else {
                displayMessage = msg;
            }
            logger.trace("Send request: {}. And receive response[{}] which lenght is {}, and content is {}.", code,
                    request.getRequestLine(), msg.length(), displayMessage);
        }
        if (code != 200)
            throw new IOException("Invalid http response " + code + " when send request: "
                    + request.getURI().toString() + "\n" + msg);
        return msg;
    } catch (IOException e) {
        logger.error("error when send http request:" + request.getURI().toString(), e);
        throw e;
    } finally {
        request.releaseConnection();
    }
}
 
Example 15
Source File: HttpClientUtil.java    From feiqu-opensource with Apache License 2.0 5 votes vote down vote up
/**
 * @param encoding 字符编码
 * @return 网页内容
 */
public static String getWebPage(HttpRequestBase request
        , String encoding) throws IOException {
    CloseableHttpResponse response = null;
    response = getResponse(request);
    logger.info("status---" + response.getStatusLine().getStatusCode());
    String content = EntityUtils.toString(response.getEntity(),encoding);
    request.releaseConnection();
    return content;
}
 
Example 16
Source File: JenkinsHttpClient.java    From jenkins-client-java with MIT License 4 votes vote down vote up
private void releaseConnection(HttpRequestBase httpRequestBase) {
    httpRequestBase.releaseConnection();
}
 
Example 17
Source File: OAuth1Shim.java    From shimmer with Apache License 2.0 4 votes vote down vote up
@Override
public AuthorizationResponse processRedirect(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");
    }

    // 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(getAccessTokenUrl(),
                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");
    }

    AccessParameters accessParameters = new AccessParameters();
    accessParameters.setClientId(getClientSettings().getClientId());
    accessParameters.setClientSecret(getClientSettings().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);
}
 
Example 18
Source File: IntegrationMockClient.java    From attic-stratos with Apache License 2.0 4 votes vote down vote up
private void releaseConnection(HttpRequestBase request) {
    if (request != null) {
        request.releaseConnection();
    }
}
 
Example 19
Source File: SslInfrastructureService.java    From gocd with Apache License 2.0 4 votes vote down vote up
protected boolean requestRegistration(String agentHostName, AgentAutoRegistrationProperties agentAutoRegisterProperties) throws IOException {
    LOGGER.debug("[Agent Registration] Using URL {} to register.", serverUrl);

    HttpRequestBase postMethod = (HttpRequestBase) RequestBuilder.post(serverUrl)
            .addParameter("hostname", agentHostName)
            .addParameter("uuid", agentRegistry.uuid())
            .addParameter("location", SystemUtil.currentWorkingDirectory())
            .addParameter("usablespace", String.valueOf(AgentRuntimeInfo.usableSpace(SystemUtil.currentWorkingDirectory())))
            .addParameter("operatingSystem", new SystemEnvironment().getOperatingSystemCompleteName())
            .addParameter("agentAutoRegisterKey", agentAutoRegisterProperties.agentAutoRegisterKey())
            .addParameter("agentAutoRegisterResources", agentAutoRegisterProperties.agentAutoRegisterResources())
            .addParameter("agentAutoRegisterEnvironments", agentAutoRegisterProperties.agentAutoRegisterEnvironments())
            .addParameter("agentAutoRegisterHostname", agentAutoRegisterProperties.agentAutoRegisterHostname())
            .addParameter("elasticAgentId", agentAutoRegisterProperties.agentAutoRegisterElasticAgentId())
            .addParameter("elasticPluginId", agentAutoRegisterProperties.agentAutoRegisterElasticPluginId())
            .addParameter("token", agentRegistry.token())
            .build();

    try (CloseableHttpResponse response = httpClient.execute(postMethod)) {
        switch (getStatusCode(response)) {
            case SC_ACCEPTED:
                LOGGER.debug("The server has accepted the registration request.");
                break;
            case SC_FORBIDDEN:
                LOGGER.debug("Server denied registration request due to invalid token. Deleting existing token from disk.");
                agentRegistry.deleteToken();
                break;
            case SC_OK:
                LOGGER.info("This agent is now approved by the server.");
                return true;
            case SC_UNPROCESSABLE_ENTITY:
                LOGGER.error("Error occurred during agent registration process: {}", responseBody(response));
                break;
            default:
                LOGGER.warn("The server sent a response that we could not understand. The HTTP status was {}. The response body was:\n{}", response.getStatusLine(), responseBody(response));
        }
    } finally {
        postMethod.releaseConnection();
    }
    return false;
}
 
Example 20
Source File: IntegrationMockClient.java    From product-private-paas with Apache License 2.0 4 votes vote down vote up
private void releaseConnection(HttpRequestBase request) {
    if (request != null) {
        request.releaseConnection();
    }
}