Example usage for org.apache.http.client.utils HttpClientUtils closeQuietly

List of usage examples for org.apache.http.client.utils HttpClientUtils closeQuietly

Introduction

In this page you can find the example usage for org.apache.http.client.utils HttpClientUtils closeQuietly.

Prototype

public static void closeQuietly(final HttpClient httpClient) 

Source Link

Document

Unconditionally close a httpClient.

Usage

From source file:org.wso2.appcloud.integration.test.utils.clients.BaseClient.java

public HttpResponse doGetRequest(String endpoint, Header[] headers) throws AppCloudIntegrationTestException {
    HttpClient httpclient = null;//from   w  w  w .  j  ava 2  s . c o m
    int timeout = (int) AppCloudIntegrationTestUtils.getTimeOutPeriod();
    try {
        httpclient = HttpClients.custom().setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE).build();
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout)
                .setConnectTimeout(timeout).build();
        HttpGet httpGet = new HttpGet(endpoint);
        httpGet.setConfig(requestConfig);
        httpGet.setHeaders(headers);

        httpGet.setHeader(HEADER_COOKIE, getRequestHeaders().get(HEADER_COOKIE));
        org.apache.http.HttpResponse httpResponse = (httpclient.execute(httpGet));
        return new HttpResponse(EntityUtils.toString(httpResponse.getEntity()),
                httpResponse.getStatusLine().getStatusCode());
    } catch (IOException e) {
        log.error("Failed to invoke API endpoint:" + endpoint, e);
        throw new AppCloudIntegrationTestException("Failed to invoke API endpoint:" + endpoint, e);
    } finally {
        HttpClientUtils.closeQuietly(httpclient);
    }
}

From source file:org.jboss.quickstarts.wfk.travelplan.TravelPlanTest.java

@Test
@InSequence(3)// w  ww . j a  v a2  s  .c  o  m
public void TestCancel() throws Exception {
    TravelSketch ts1 = new TravelSketch();
    ts1.setFlightId(10001L);
    ts1.setHotelId(1099L);
    ts1.setTaxiId(101L);
    ts1.setBookingDate("2018-03-29");
    ts1.setCustomerId(createTestCustomer());

    Response response = travelPlanRESTService.createTravelPlan(ts1);

    assertEquals("Unexpected response", 201, response.getStatus());

    long flightId = 0;
    long hotelId = 0;
    long taxiId = 0;
    long bId = 0;

    Response r1 = travelPlanRESTService.retrieveAllTravelPlans();
    String responseBody = EntityUtils.toString((HttpEntity) r1.getEntity());
    JSONArray responseJSON = new JSONArray(responseBody);
    for (int i = 0; i < responseJSON.length(); i++) {
        JSONObject jo = responseJSON.getJSONObject(i);
        if (jo.getJSONObject("customer").getLong("id") == createTestCustomer()) {
            bId = jo.getLong("id");
            flightId = jo.getLong("flightBookingId");
            hotelId = jo.getLong("hotelBookingId");
            taxiId = jo.getLong("taxiBookingId");
        }
    }
    assertNotEquals("Flight did not book", 0L, flightId);
    assertNotEquals("Taxi did not book", 0L, taxiId);
    assertNotEquals("Hotel did not book", 0L, hotelId);

    Response ree = travelPlanRESTService.deleteTravelPlan(bId);
    assertEquals("Cancellation was not successful", 204, ree.getStatus());

    URI uri = new URIBuilder().setScheme("http").setHost("travel.gsp8181.co.uk")
            .setPath("/rest/bookings/" + hotelId).build();
    HttpGet req = new HttpGet(uri);
    CloseableHttpResponse response2 = httpClient.execute(req);
    assertEquals("Hotel did not cancel", 404, response2.getStatusLine().getStatusCode());

    HttpClientUtils.closeQuietly(response2);

    URI uri1 = new URIBuilder().setScheme("http").setHost("jbosscontactsangularjs-110336260.rhcloud.com")
            .setPath("/rest/bookings/" + flightId).build();
    HttpGet req1 = new HttpGet(uri1);
    CloseableHttpResponse response3 = httpClient.execute(req1);
    assertEquals("Flight did not cancel", 404, response3.getStatusLine().getStatusCode());
    HttpClientUtils.closeQuietly(response3);

    URI uri2 = new URIBuilder().setScheme("http").setHost("jbosscontactsangularjs-110060653.rhcloud.com")
            .setPath("/rest/bookings/" + taxiId).build();
    HttpGet req2 = new HttpGet(uri2);
    CloseableHttpResponse response4 = httpClient.execute(req2);
    assertEquals("Taxi did not cancel", 404, response4.getStatusLine().getStatusCode());
    HttpClientUtils.closeQuietly(response4);

}

From source file:org.wso2.appcloud.integration.test.utils.clients.ApplicationClient.java

public void createNewApplication(String applicationName, String runtime, String appTypeName,
        String applicationRevision, String applicationDescription, String uploadedFileName,
        String runtimeProperties, String tags, File uploadArtifact, boolean isNewVersion,
        String applicationContext, String conSpec, boolean setDefaultVersion, String appCreationMethod,
        String gitRepoUrl, String gitRepoBranch, String projectRoot) throws AppCloudIntegrationTestException {

    HttpClient httpclient = null;//from  ww  w  . ja  v a 2  s.  co  m
    org.apache.http.HttpResponse response = null;
    int timeout = (int) AppCloudIntegrationTestUtils.getTimeOutPeriod();
    try {
        httpclient = HttpClients.custom().setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE).build();
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout)
                .setConnectTimeout(timeout).build();
        HttpPost httppost = new HttpPost(this.endpoint);
        httppost.setConfig(requestConfig);

        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

        builder.addPart(PARAM_NAME_ACTION, new StringBody(CREATE_APPLICATION_ACTION, ContentType.TEXT_PLAIN));
        builder.addPart(PARAM_NAME_APP_CREATION_METHOD,
                new StringBody(appCreationMethod, ContentType.TEXT_PLAIN));
        if (GITHUB.equals(appCreationMethod)) {
            builder.addPart(PARAM_NAME_GIT_REPO_URL, new StringBody(gitRepoUrl, ContentType.TEXT_PLAIN));
            builder.addPart(PARAM_NAME_GIT_REPO_BRANCH, new StringBody(gitRepoBranch, ContentType.TEXT_PLAIN));
            builder.addPart(PARAM_NAME_PROJECT_ROOT, new StringBody(projectRoot, ContentType.TEXT_PLAIN));
        } else if (DEFAULT.equals(appCreationMethod)) {
            builder.addPart(PARAM_NAME_FILE_UPLOAD, new FileBody(uploadArtifact));
            builder.addPart(PARAM_NAME_UPLOADED_FILE_NAME,
                    new StringBody(uploadedFileName, ContentType.TEXT_PLAIN));
            builder.addPart(PARAM_NAME_IS_FILE_ATTACHED,
                    new StringBody(Boolean.TRUE.toString(), ContentType.TEXT_PLAIN));//Setting true to send the file in request
        }
        builder.addPart(PARAM_NAME_CONTAINER_SPEC, new StringBody(conSpec, ContentType.TEXT_PLAIN));
        builder.addPart(PARAM_NAME_APPLICATION_NAME, new StringBody(applicationName, ContentType.TEXT_PLAIN));
        builder.addPart(PARAM_NAME_APPLICATION_DESCRIPTION,
                new StringBody(applicationDescription, ContentType.TEXT_PLAIN));
        builder.addPart(PARAM_NAME_RUNTIME, new StringBody(runtime, ContentType.TEXT_PLAIN));
        builder.addPart(PARAM_NAME_APP_TYPE_NAME, new StringBody(appTypeName, ContentType.TEXT_PLAIN));
        builder.addPart(PARAM_NAME_APP_CONTEXT, new StringBody(applicationContext, ContentType.TEXT_PLAIN));
        builder.addPart(PARAM_NAME_APPLICATION_REVISION,
                new StringBody(applicationRevision, ContentType.TEXT_PLAIN));

        builder.addPart(PARAM_NAME_PROPERTIES, new StringBody(runtimeProperties, ContentType.TEXT_PLAIN));
        builder.addPart(PARAM_NAME_TAGS, new StringBody(tags, ContentType.TEXT_PLAIN));

        builder.addPart(PARAM_NAME_IS_NEW_VERSION,
                new StringBody(Boolean.toString(isNewVersion), ContentType.TEXT_PLAIN));
        builder.addPart(PARAM_NAME_SET_DEFAULT_VERSION,
                new StringBody(Boolean.toString(setDefaultVersion), ContentType.TEXT_PLAIN));

        httppost.setEntity(builder.build());
        httppost.setHeader(HEADER_COOKIE, getRequestHeaders().get(HEADER_COOKIE));
        response = httpclient.execute(httppost);

        if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            String result = EntityUtils.toString(response.getEntity());
            throw new AppCloudIntegrationTestException("CreateNewApplication failed " + result);
        }

    } catch (ConnectTimeoutException | java.net.SocketTimeoutException e1) {
        // In most of the cases, even though connection is timed out, actual activity is completed.
        // If application is not created, in next test case, it will be identified.
        log.warn("Failed to get 200 ok response from endpoint:" + endpoint, e1);
    } catch (IOException e) {
        log.error("Failed to invoke application creation API.", e);
        throw new AppCloudIntegrationTestException("Failed to invoke application creation API.", e);
    } finally {
        HttpClientUtils.closeQuietly(response);
        HttpClientUtils.closeQuietly(httpclient);
    }
}

From source file:com.hp.mqm.client.AbstractMqmRestClient.java

private void checkAuthorization() {
    HttpGet request = new HttpGet(createSharedSpaceInternalApiUri(CONNECTIVITY_API_URI));
    HttpResponse response = null;/*w w w  .  j a v  a  2  s. c om*/
    try {
        response = execute(request);
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_FOUND) {
            throw new SharedSpaceNotExistException("Cannot connect to given shared space.");
        } else if (response.getStatusLine().getStatusCode() == HttpStatus.SC_FORBIDDEN) {
            throw new AuthorizationException("Provided credentials are not sufficient for requested resource");
        } else if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            throw new AuthorizationException("Authorization failed with unexpected response "
                    + response.getStatusLine().getStatusCode());
        }
    } catch (IOException e) {
        throw new RequestErrorException("Shared space check failed", e);
    } finally {
        HttpClientUtils.closeQuietly(response);
    }
}

From source file:org.jboss.quickstarts.wfk.travelagent.travelplan.TravelPlanService.java

/**
 * <p>//w  w  w .  j  a  v  a 2 s  .c  o m
 * Deletes the provided TravelPlan object from the application database if
 * found there.
 * <p/>
 * 
 * @param travelPlan
 *            The TravelPlan object to be removed from the application
 *            database
 * @return The TravelPlan object that has been successfully removed from the
 *         application database; or null
 * @throws Exception
 */
TravelPlan delete(TravelPlan travelPlan) throws Exception {
    // log.info("TravelPlanService.delete() - Deleting " +
    // travelPlan.getFirstName() + " " + travelPlan.getLastName());

    if (travelPlan.getId() == null) {

        log.info("TravelPlanService.delete() - No ID was found so can't Delete.");
        return null;
    }

    URI uriH = new URIBuilder().setScheme("http").setHost("travel.gsp8181.co.uk")
            .setPath("/rest/bookings/" + travelPlan.getHotelBookingId())
            // .setHost("localhost")
            // .setPort(8080)
            // .setPath("/travel/rest/bookings/" +
            // travelPlan.getHotelBookingId())
            .build();
    HttpDelete reqH = new HttpDelete(uriH);
    CloseableHttpResponse responseH = httpClient.execute(reqH);
    if (responseH.getStatusLine().getStatusCode() != 204) {

    }
    // String responseBody = EntityUtils.toString(response.getEntity());
    HttpClientUtils.closeQuietly(responseH);

    URI uriF = new URIBuilder().setScheme("http").setHost("jbosscontactsangularjs-110336260.rhcloud.com")
            .setPath("/rest/bookings/" + travelPlan.getFlightBookingId()).build();
    HttpDelete reqF = new HttpDelete(uriF);
    CloseableHttpResponse responseF = httpClient.execute(reqF);
    if (responseF.getStatusLine().getStatusCode() != 204) {

    }
    // String responseBody = EntityUtils.toString(response.getEntity());
    HttpClientUtils.closeQuietly(responseF);

    URI uri = new URIBuilder().setScheme("http").setHost("jbosscontactsangularjs-110060653.rhcloud.com")
            .setPath("/rest/bookings/" + travelPlan.getTaxiBookingId()).build();
    HttpDelete req = new HttpDelete(uri);
    CloseableHttpResponse response = httpClient.execute(req);
    if (response.getStatusLine().getStatusCode() != 204) {

    }
    // String responseBody = EntityUtils.toString(response.getEntity());
    HttpClientUtils.closeQuietly(response);

    TravelPlan deletedTravelPlan = null;
    deletedTravelPlan = crud.delete(travelPlan);
    return deletedTravelPlan;

}

From source file:org.switchyard.component.http.OutboundHandler.java

/**
 * The handler method that invokes the actual HTTP service when the
 * component is used as a HTTP consumer.
 * @param exchange the Exchange/*from   w  w  w  .j  a  v a 2 s .  c o m*/
 * @throws HandlerException handler exception
 */
@Override
public void handleMessage(final Exchange exchange) throws HandlerException {
    // identify ourselves
    exchange.getContext().setProperty(ExchangeCompletionEvent.GATEWAY_NAME, _bindingName, Scope.EXCHANGE)
            .addLabels(BehaviorLabel.TRANSIENT.label());
    if (getState() != State.STARTED) {
        final String m = HttpMessages.MESSAGES.bindingNotStarted(_referenceName, _bindingName);
        LOGGER.error(m);
        throw new HandlerException(m);
    }

    HttpClient httpclient = new DefaultHttpClient();
    if (_timeout != null) {
        HttpParams httpParams = httpclient.getParams();
        HttpConnectionParams.setConnectionTimeout(httpParams, _timeout);
        HttpConnectionParams.setSoTimeout(httpParams, _timeout);
    }
    try {
        if (_credentials != null) {
            ((DefaultHttpClient) httpclient).getCredentialsProvider().setCredentials(_authScope, _credentials);
            List<String> authpref = new ArrayList<String>();
            authpref.add(AuthPolicy.NTLM);
            authpref.add(AuthPolicy.BASIC);
            httpclient.getParams().setParameter(AuthPNames.TARGET_AUTH_PREF, authpref);
        }
        if (_proxyHost != null) {
            httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, _proxyHost);
        }
        HttpBindingData httpRequest = _messageComposer.decompose(exchange, new HttpRequestBindingData());
        HttpRequestBase request = null;
        if (_httpMethod.equals(HTTP_GET)) {
            request = new HttpGet(_baseAddress);
        } else if (_httpMethod.equals(HTTP_POST)) {
            request = new HttpPost(_baseAddress);
            ((HttpPost) request).setEntity(new BufferedHttpEntity(
                    new InputStreamEntity(httpRequest.getBodyBytes(), httpRequest.getBodyBytes().available())));
        } else if (_httpMethod.equals(HTTP_DELETE)) {
            request = new HttpDelete(_baseAddress);
        } else if (_httpMethod.equals(HTTP_HEAD)) {
            request = new HttpHead(_baseAddress);
        } else if (_httpMethod.equals(HTTP_PUT)) {
            request = new HttpPut(_baseAddress);
            ((HttpPut) request).setEntity(new BufferedHttpEntity(
                    new InputStreamEntity(httpRequest.getBodyBytes(), httpRequest.getBodyBytes().available())));
        } else if (_httpMethod.equals(HTTP_OPTIONS)) {
            request = new HttpOptions(_baseAddress);
        }
        Iterator<Map.Entry<String, List<String>>> entries = httpRequest.getHeaders().entrySet().iterator();
        while (entries.hasNext()) {
            Map.Entry<String, List<String>> entry = entries.next();
            String name = entry.getKey();
            if (REQUEST_HEADER_BLACKLIST.contains(name)) {
                HttpLogger.ROOT_LOGGER.removingProhibitedRequestHeader(name);
                continue;
            }
            List<String> values = entry.getValue();
            for (String value : values) {
                request.addHeader(name, value);
            }
        }
        if (_contentType != null) {
            request.addHeader("Content-Type", _contentType);
        }

        HttpResponse response = null;
        if ((_credentials != null) && (_credentials instanceof NTCredentials)) {
            // Send a request for the Negotiation
            response = httpclient.execute(new HttpGet(_baseAddress));
            HttpClientUtils.closeQuietly(response);
        }
        if (_authCache != null) {
            BasicHttpContext context = new BasicHttpContext();
            context.setAttribute(ClientContext.AUTH_CACHE, _authCache);
            response = httpclient.execute(request, context);
        } else {
            response = httpclient.execute(request);
        }
        int status = response.getStatusLine().getStatusCode();

        HttpEntity entity = response.getEntity();
        HttpResponseBindingData httpResponse = new HttpResponseBindingData();
        Header[] headers = response.getAllHeaders();
        for (Header header : headers) {
            httpResponse.addHeader(header.getName(), header.getValue());
        }
        if (entity != null) {
            if (entity.getContentType() != null) {
                httpResponse.setContentType(new ContentType(entity.getContentType().getValue()));
            } else {
                httpResponse.setContentType(new ContentType());
            }
            httpResponse.setBodyFromStream(entity.getContent());
        }
        httpResponse.setStatus(status);
        Message out = _messageComposer.compose(httpResponse, exchange);
        if (httpResponse.getStatus() < 400) {
            exchange.send(out);
        } else {
            exchange.sendFault(out);
        }
    } catch (Exception e) {
        final String m = HttpMessages.MESSAGES.unexpectedExceptionHandlingHTTPMessage();
        LOGGER.error(m, e);
        throw new HandlerException(m, e);
    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();
    }
}

From source file:com.hp.mqm.client.MqmRestClientImpl.java

@Override
public TestResultStatus getTestResultStatus(long id) {
    HttpGet request = new HttpGet(createSharedSpaceInternalApiUri(URI_TEST_RESULT_STATUS, id));

    HttpResponse response = null;/*from  w  ww  . j  av a2  s .  co  m*/
    try {
        response = execute(request);
        if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            throw createRequestException("Result status retrieval failed", response);
        }
        String json = IOUtils.toString(response.getEntity().getContent(), "UTF-8");
        JSONObject jsonObject = JSONObject.fromObject(json);
        Date until = null;
        if (jsonObject.has("until")) {
            try {
                until = parseDatetime(jsonObject.getString("until"));
            } catch (ParseException e) {
                throw new RequestErrorException("Cannot obtain status", e);
            }
        }
        return new TestResultStatus(jsonObject.getString("status"), until);
    } catch (IOException e) {
        throw new RequestErrorException("Cannot obtain status.", e);
    } finally {
        HttpClientUtils.closeQuietly(response);
    }
}

From source file:com.mirth.connect.client.core.ServerConnection.java

/**
 * The requests sent through this channel will be aborted on the client side when a new request
 * arrives. Currently there is no guarantee of the order that pending requests will be sent.
 *//*from  www.ja v  a 2  s.c  o  m*/
private ClientResponse executeAbortPending(ClientRequest request) throws ClientException {
    // TODO: Make order sequential
    abortTask.incrementRequestsInQueue();

    synchronized (abortExecutor) {
        if (!abortExecutor.isShutdown() && !abortTask.isRunning()) {
            abortExecutor.execute(abortTask);
        }

        HttpRequestBase requestBase = null;
        CloseableHttpResponse response = null;
        boolean shouldClose = true;

        try {
            abortPendingClientContext = HttpClientContext.create();
            abortPendingClientContext.setRequestConfig(requestConfig);

            requestBase = setupRequestBase(request, ExecuteType.ABORT_PENDING);

            abortTask.setAbortAllowed(true);
            response = client.execute(requestBase, abortPendingClientContext);
            abortTask.setAbortAllowed(false);

            ClientResponse responseContext = handleResponse(request, requestBase, response);
            if (responseContext.hasEntity()) {
                shouldClose = false;
            }
            return responseContext;
        } catch (Exception e) {
            if (requestBase != null && requestBase.isAborted()) {
                return new ClientResponse(Status.NO_CONTENT, request);
            } else if (e instanceof ClientException) {
                throw (ClientException) e;
            }
            throw new ClientException(e);
        } finally {
            abortTask.decrementRequestsInQueue();
            if (shouldClose) {
                HttpClientUtils.closeQuietly(response);
            }
        }
    }
}

From source file:com.hp.mqm.client.MqmRestClientImpl.java

@Override
public void getTestResultLog(long id, LogOutput output) {
    HttpGet request = new HttpGet(createSharedSpaceInternalApiUri(URI_TEST_RESULT_LOG, id));
    HttpResponse response = null;/*ww  w.ja  v a2s  .co m*/
    try {
        response = execute(request);
        if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            throw createRequestException("Log retrieval failed", response);
        }
        output.setContentType(response.getFirstHeader("Content-type").getValue());
        InputStream is = response.getEntity().getContent();
        IOUtils.copy(is, output.getOutputStream());
        IOUtils.closeQuietly(is);
    } catch (IOException e) {
        throw new RequestErrorException("Cannot obtain log.", e);
    } finally {
        HttpClientUtils.closeQuietly(response);
    }
}