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:org.openmhealth.shim.fitbit.FitbitShim.java

private ShimDataResponse executeRequest(String endPointUrl, String accessToken, String tokenSecret,
        boolean normalize, FitbitDataType fitbitDataType) throws ShimException {

    ApplicationAccessParameters parameters = findApplicationAccessParameters();
    HttpRequestBase dataRequest = OAuth1Utils.getSignedRequest(HttpMethod.GET, endPointUrl,
            parameters.getClientId(), parameters.getClientSecret(), accessToken, tokenSecret, null);

    HttpResponse response;//  w w w. j  a  v a2  s  .  c om
    try {
        response = httpClient.execute(dataRequest);
        HttpEntity responseEntity = response.getEntity();

        StringWriter writer = new StringWriter();
        IOUtils.copy(responseEntity.getContent(), writer);

        String jsonContent = writer.toString();

        ObjectMapper objectMapper = new ObjectMapper();
        if (normalize) {

            IOUtils.copy(responseEntity.getContent(), writer);

            JsonNode jsonNode = objectMapper.readValue(writer.toString(), JsonNode.class);

            FitbitDataPointMapper dataPointMapper;

            switch (fitbitDataType) {
            case STEPS:
                dataPointMapper = new FitbitStepCountDataPointMapper();
                break;
            case ACTIVITY:
                dataPointMapper = new FitbitPhysicalActivityDataPointMapper();
                break;
            case WEIGHT:
                dataPointMapper = new FitbitBodyWeightDataPointMapper();
                break;
            case SLEEP:
                dataPointMapper = new FitbitSleepDurationDataPointMapper();
                break;
            case BODY_MASS_INDEX:
                dataPointMapper = new FitbitBodyMassIndexDataPointMapper();
                break;
            default:
                throw new UnsupportedOperationException();
            }

            return ShimDataResponse.result(FitbitShim.SHIM_KEY,
                    dataPointMapper.asDataPoints(singletonList(jsonNode)));

        } else {

            return ShimDataResponse.result(FitbitShim.SHIM_KEY, objectMapper.readTree(jsonContent));
        }
    } catch (IOException e) {
        throw new ShimException("Could not fetch data", e);
    } finally {
        dataRequest.releaseConnection();
    }
}

From source file:org.openmhealth.shim.fitbit.FitbitShim.java

private ShimDataResponse getDaysData(OffsetDateTime dateTime, FitbitDataType fitbitDataType, boolean normalize,
        String accessToken, String tokenSecret) throws ShimException {

    String dateString = dateTime.toLocalDate().toString();

    UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder.fromUriString(DATA_URL)
            .path("/1/user/-/{fitbitDataTypeEndpoint}/date/{dateString}{stepTimeSeries}.json");
    String endpointUrl = uriComponentsBuilder.buildAndExpand(fitbitDataType.getEndPoint(), dateString,
            (fitbitDataType == FitbitDataType.STEPS ? "/1d/1min" : "")).encode().toString();

    ApplicationAccessParameters parameters = findApplicationAccessParameters();
    HttpRequestBase dataRequest = OAuth1Utils.getSignedRequest(HttpMethod.GET, endpointUrl,
            parameters.getClientId(), parameters.getClientSecret(), accessToken, tokenSecret, null);

    HttpResponse response;// ww  w. j a va  2s.  c  o m
    try {
        response = httpClient.execute(dataRequest);
        HttpEntity responseEntity = response.getEntity();

        StringWriter writer = new StringWriter();
        IOUtils.copy(responseEntity.getContent(), writer);

        ObjectMapper objectMapper = new ObjectMapper();

        if (normalize) {

            JsonNode jsonNode = objectMapper.readValue(writer.toString(), JsonNode.class);

            FitbitDataPointMapper dataPointMapper;

            switch (fitbitDataType) {
            case STEPS:
                dataPointMapper = new FitbitStepCountDataPointMapper();
                break;
            case ACTIVITY:
                dataPointMapper = new FitbitPhysicalActivityDataPointMapper();
                break;
            case WEIGHT:
                dataPointMapper = new FitbitBodyWeightDataPointMapper();
                break;
            case SLEEP:
                dataPointMapper = new FitbitSleepDurationDataPointMapper();
                break;
            case BODY_MASS_INDEX:
                dataPointMapper = new FitbitBodyMassIndexDataPointMapper();
                break;
            default:
                throw new UnsupportedOperationException();
            }

            return ShimDataResponse.result(FitbitShim.SHIM_KEY,
                    dataPointMapper.asDataPoints(singletonList(jsonNode)));

        } else {
            /**
             * The fitbit API's system works by retrieving each day's
             * data. The date captured is not returned in the data from fitbit because
             * it's implicit so we create a JSON wrapper that includes it.
             */
            String jsonContent = "{\"result\": {\"date\": \"" + dateString + "\" " + ",\"content\": "
                    + writer.toString() + "}}";

            return ShimDataResponse.result(FitbitShim.SHIM_KEY, objectMapper.readTree(jsonContent));
        }
    } catch (IOException e) {
        throw new ShimException("Could not fetch data", e);
    } finally {
        dataRequest.releaseConnection();
    }
}

From source file:org.openrepose.nodeservice.httpcomponent.RequestProxyServiceImpl.java

private ServiceClientResponse execute(HttpRequestBase base) {
    HttpClientResponse httpClientResponse = getClient();
    try {/*www .  j a  v  a2 s .c om*/
        HttpResponse httpResponse = httpClientResponse.getHttpClient().execute(base);
        HttpEntity entity = httpResponse.getEntity();
        HttpComponentResponseCodeProcessor responseCode = new HttpComponentResponseCodeProcessor(
                httpResponse.getStatusLine().getStatusCode());

        InputStream stream = null;
        if (entity != null) {
            stream = new ByteArrayInputStream(RawInputStreamReader.instance().readFully(entity.getContent()));
            EntityUtils.consume(entity);
        }

        return new ServiceClientResponse(responseCode.getCode(), stream);
    } catch (IOException ex) {
        LOG.error("Error executing request to {}", base.getURI().toString(), ex);
    } finally {
        base.releaseConnection();
        httpClientService.releaseClient(httpClientResponse);
    }

    return new ServiceClientResponse(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, null);
}

From source file:org.wso2.carbon.apimgt.hybrid.gateway.common.util.HttpRequestUtil.java

/**
 * Executes the HTTPMethod with retry.//from  w ww  . jav  a  2  s.co  m
 *
 * @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.getConfigManager()
            .getProperty(OnPremiseGatewayConstants.API_REQUEST_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;
}

From source file:org.wso2.carbon.apimgt.hybrid.gateway.common.util.HttpRequestUtil.java

/**
 * Executes HTTPMethod without retry//from   w  w  w . ja v  a2 s . c o m
 *
 * @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.getConfigManager()
            .getProperty(OnPremiseGatewayConstants.API_REQUEST_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;
}