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:com.hp.octane.integrations.services.rest.OctaneRestClientImpl.java

@Override
public void shutdown() {
    logger.info("starting REST client shutdown sequence...");
    abortAllRequests();//  w  w w .ja v  a2 s . com
    logger.info("closing the client...");
    HttpClientUtils.closeQuietly(httpClient);
    logger.info("REST client shutdown done");
}

From source file:org.alfresco.selenium.FetchUtil.java

/**
 * Download all external files to local directory.
 * @param files collection to download/*  www .j a  va  2  s.  c  om*/
 * @param driver {@link WebDriver}
 * @throws IOException 
 */
public static void getFiles(List<String> files, WebDriver driver) throws IOException {
    if (null == files) {
        throw new IllegalArgumentException("Collections of url's are required");
    }
    //Create a client to get content.
    CloseableHttpClient client = FetchHttpClient.getHttpClient(driver);
    try {
        for (String source : files) {
            File file = getFile(source, client);
            if (source.endsWith("css")) {
                FetchCSS.getCSSFiles(file, driver);
            }
        }
    } finally {
        HttpClientUtils.closeQuietly(client);
    }
}

From source file:com.hp.octane.integrations.services.rest.SSCRestClientImpl.java

private AuthToken.AuthTokenData sendReqAuth(SSCProjectConfiguration sscProjectConfiguration) {
    //"/{SSC Server Context}/api/v1"
    //String url = "http://" + serverURL + "/ssc/api/v1/projects?q=id:2743&fulltextsearch=true";
    String url = sscProjectConfiguration.getSSCUrl() + "/api/v1/tokens";
    HttpPost request = new HttpPost(url);
    request.addHeader("Authorization", sscProjectConfiguration.getSSCBaseAuthToken());
    request.addHeader("Accept", "application/json");
    request.addHeader("Host", getNetHost(sscProjectConfiguration.getSSCUrl()));
    request.addHeader("Content-Type", "application/json;charset=UTF-8");

    String body = "{\"type\": \"UnifiedLoginToken\"}";
    CloseableHttpResponse response = null;
    try {//  w  w w .j av  a2  s.  c  o  m
        HttpEntity entity = new ByteArrayEntity(body.getBytes(StandardCharsets.UTF_8));
        request.setEntity(entity);
        response = httpClient.execute(request);
        if (succeeded(response.getStatusLine().getStatusCode())) {
            String toString = CIPluginSDKUtils.inputStreamToUTF8String(response.getEntity().getContent());
            AuthToken authToken = new ObjectMapper().readValue(toString,
                    TypeFactory.defaultInstance().constructType(AuthToken.class));
            return authToken.getData();
        } else {
            throw new PermanentException(
                    "Couldn't Authenticate SSC user, need to check SSC configuration in Octane plugin");
        }
    } catch (Throwable t) {
        throw new PermanentException(t);
    } finally {
        if (response != null) {
            EntityUtils.consumeQuietly(response.getEntity());
            HttpClientUtils.closeQuietly(response);
        }
    }
}

From source file:com.hp.mqm.clt.RestClient.java

public long postTestResult(HttpEntity entity) throws IOException, ValidationException {
    HttpPost request = new HttpPost(createWorkspaceApiUri(URI_TEST_RESULT_PUSH, settings.isSkipErrors()));
    request.setEntity(entity);//  www .j  a  v a  2 s. co m
    CloseableHttpResponse response = null;
    try {
        response = execute(request);
        if (response.getStatusLine().getStatusCode() != HttpStatus.SC_ACCEPTED) {
            String json = IOUtils.toString(response.getEntity().getContent(), "UTF-8");
            JSONObject jsonObject = new JSONObject(json);
            String description = "";
            if (jsonObject.has("description")) {
                description = ": " + jsonObject.getString("description");
            }
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_BAD_REQUEST
                    && settings.isInternal()) {
                // Error was probably caused by XSD validation failure
                throw new ValidationException("Test result XML was refused by server" + description);
            }
            throw new RuntimeException("Test result post failed with status code ("
                    + response.getStatusLine().getStatusCode() + ")" + description);
        }
        String json = IOUtils.toString(response.getEntity().getContent());
        JSONObject jsonObject = new JSONObject(json);
        return jsonObject.getLong("id");
    } finally {
        HttpClientUtils.closeQuietly(response);
    }
}

From source file:org.apache.vxquery.rest.AbstractRestServerTest.java

/**
 * Fetch the {@link QueryResultResponse} from query result endpoint once the
 * corresponding {@link QueryResultRequest} is given.
 *
 * @param resultRequest/*from   w  ww  .j  a  v  a2  s . c o  m*/
 *            {@link QueryResultRequest}
 * @param accepts
 *            expected
 * 
 *            <pre>
 *            Accepts
 *            </pre>
 * 
 *            header in responses
 * @param method
 *            Http Method to be used to send the request
 * @return query result response received
 * @throws Exception
 */
protected static QueryResultResponse getQueryResultResponse(QueryResultRequest resultRequest, String accepts,
        String method) throws Exception {
    URI uri = RestUtils.buildQueryResultURI(resultRequest, restIpAddress, restPort);
    CloseableHttpClient httpClient = HttpClients.custom().setConnectionTimeToLive(20, TimeUnit.SECONDS).build();
    try {
        HttpUriRequest request = getRequest(uri, method);

        if (accepts != null) {
            request.setHeader(HttpHeaders.ACCEPT, accepts);
        }

        try (CloseableHttpResponse httpResponse = httpClient.execute(request)) {
            if (accepts != null) {
                Assert.assertEquals(accepts, httpResponse.getFirstHeader(HttpHeaders.CONTENT_TYPE).getValue());
            }
            Assert.assertEquals(httpResponse.getStatusLine().getStatusCode(), HttpResponseStatus.OK.code());

            HttpEntity entity = httpResponse.getEntity();
            Assert.assertNotNull(entity);

            String response = RestUtils.readEntity(entity);
            return RestUtils.mapEntity(response, QueryResultResponse.class, accepts);
        }
    } finally {
        HttpClientUtils.closeQuietly(httpClient);
    }
}

From source file:net.staticsnow.nexus.repository.apt.internal.proxy.AptProxyFacet.java

private Optional<SnapshotItem> fetchLatest(ContentSpecifier spec) throws IOException {
    AptFacet aptFacet = getRepository().facet(AptFacet.class);
    ProxyFacet proxyFacet = facet(ProxyFacet.class);
    HttpClientFacet httpClientFacet = facet(HttpClientFacet.class);
    HttpClient httpClient = httpClientFacet.getHttpClient();
    CacheController cacheController = cacheControllerHolder.getMetadataCacheController();
    CacheInfo cacheInfo = cacheController.current();
    Content oldVersion = aptFacet.get(spec.path);

    URI fetchUri = proxyFacet.getRemoteUrl().resolve(spec.path);
    HttpGet getRequest = buildFetchRequest(oldVersion, fetchUri);

    HttpResponse response = httpClient.execute(getRequest);
    StatusLine status = response.getStatusLine();

    if (status.getStatusCode() == HttpStatus.SC_OK) {
        HttpEntity entity = response.getEntity();
        Content fetchedContent = new Content(new HttpEntityPayload(response, entity));
        AttributesMap contentAttrs = fetchedContent.getAttributes();
        contentAttrs.set(Content.CONTENT_LAST_MODIFIED, getDateHeader(response, HttpHeaders.LAST_MODIFIED));
        contentAttrs.set(Content.CONTENT_ETAG, getQuotedStringHeader(response, HttpHeaders.ETAG));
        contentAttrs.set(CacheInfo.class, cacheInfo);
        Content storedContent = getAptFacet().put(spec.path, fetchedContent);
        return Optional.of(new SnapshotItem(spec, storedContent));
    }// w  w w.j  a  va2  s .com

    try {
        if (status.getStatusCode() == HttpStatus.SC_NOT_MODIFIED) {
            checkState(oldVersion != null, "Received 304 without conditional GET (bad server?) from %s",
                    fetchUri);
            doIndicateVerified(oldVersion, cacheInfo, spec.path);
            return Optional.of(new SnapshotItem(spec, oldVersion));
        }
        throwProxyExceptionForStatus(response);
    } finally {
        HttpClientUtils.closeQuietly(response);
    }

    return Optional.empty();
}

From source file:cf.client.DefaultCloudController.java

@Override
public UUID createService(Token token, Service service) {
    try {/*from  www  .  j a  va 2 s. com*/
        final String requestString = mapper.writeValueAsString(service);
        final HttpPost post = new HttpPost(target.resolve(V2_SERVICES));
        post.addHeader(token.toAuthorizationHeader());
        post.setEntity(new StringEntity(requestString, ContentType.APPLICATION_JSON));
        final HttpResponse response = httpClient.execute(post);
        try {
            validateResponse(response, 201);
            final JsonNode json = mapper.readTree(response.getEntity().getContent());
            return UUID.fromString(json.get("metadata").get("guid").asText());
        } finally {
            HttpClientUtils.closeQuietly(response);
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.jboss.as.test.clustering.tunnel.singleton.SingletonTunnelTestCase.java

private static String getSingletonNode(URI serviceUri) throws IOException {
    CloseableHttpClient client = org.jboss.as.test.http.util.TestHttpClientUtils.promiscuousCookieHttpClient();
    HttpResponse response = client.execute(new HttpGet(serviceUri));
    try {//from  w ww  .  j a v a2  s  .  c o m
        Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
        Header header = response.getFirstHeader("node");
        Assert.assertNotNull("No provider detected.", header);
        return header.getValue();
    } finally {
        HttpClientUtils.closeQuietly(response);
        HttpClientUtils.closeQuietly(client);
    }
}

From source file:org.mobicents.servlet.restcomm.cache.DiskCache.java

private URI cache(final Object message) throws IOException, URISyntaxException {
    final DiskCacheRequest request = (DiskCacheRequest) message;

    if (request.hash() == null) {
        if (request.uri().getScheme().equalsIgnoreCase("file")) {
            File origFile = new File(request.uri());
            File destFile = new File(location + origFile.getName());
            if (!destFile.exists())
                FileUtils.moveFile(origFile, destFile);

            return URI.create(this.uri + destFile.getName());

        } else {//from  ww w  . j a v  a 2 s .  c om
            //Handle all the rest
            // This is a request to cache a URI
            String hash = null;
            URI uri = null;
            if (request.uri().toString().contains("hash")) {
                String fragment = request.uri().getFragment();
                hash = fragment.replace("hash=", "");
                String uriStr = ((request.uri().toString()).replace(fragment, "")).replace("#", "");
                uri = URI.create(uriStr);
            } else {
                uri = request.uri();
                hash = new Sha256Hash(uri.toString()).toHex();
            }

            final String extension = extension(uri).toLowerCase();
            final File path = new File(location + hash + "." + extension);
            if (!path.exists()) {
                final File tmp = new File(path + "." + "tmp");
                InputStream input = null;
                OutputStream output = null;
                HttpClient client = null;
                HttpResponse httpResponse = null;
                try {
                    if (request.uri().getScheme().equalsIgnoreCase("https")) {
                        //Handle the HTTPS URIs
                        client = CustomHttpClientBuilder.build(RestcommConfiguration.getInstance().getMain());
                        URI result = new URIBuilder().setScheme(uri.getScheme()).setHost(uri.getHost())
                                .setPort(uri.getPort()).setPath(uri.getPath()).build();

                        HttpGet httpRequest = new HttpGet(result);
                        httpResponse = client.execute((HttpUriRequest) httpRequest);
                        int code = httpResponse.getStatusLine().getStatusCode();

                        if (code >= 400) {
                            String requestUrl = httpRequest.getRequestLine().getUri();
                            String errorReason = httpResponse.getStatusLine().getReasonPhrase();
                            String httpErrorMessage = String.format(
                                    "Error while fetching http resource: %s \n Http error code: %d \n Http error message: %s",
                                    requestUrl, code, errorReason);
                            logger.warning(httpErrorMessage);
                        }
                        input = httpResponse.getEntity().getContent();
                    } else {
                        input = uri.toURL().openStream();
                    }
                    output = new FileOutputStream(tmp);
                    final byte[] buffer = new byte[4096];
                    int read = 0;
                    do {
                        read = input.read(buffer, 0, 4096);
                        if (read > 0) {
                            output.write(buffer, 0, read);
                        }
                    } while (read != -1);
                    tmp.renameTo(path);
                } finally {
                    if (input != null) {
                        input.close();
                    }
                    if (output != null) {
                        output.close();
                    }
                    if (httpResponse != null) {
                        ((CloseableHttpResponse) httpResponse).close();
                        httpResponse = null;
                    }
                    if (client != null) {
                        HttpClientUtils.closeQuietly(client);
                        client = null;
                    }
                }
            }
            URI result = URI.create(this.uri + hash + "." + extension);
            return result;
        }
    } else {
        // This is a check cache request
        final String extension = "wav";
        final String hash = request.hash();
        final String filename = hash + "." + extension;
        Path p = Paths.get(location + filename);

        if (Files.exists(p)) {
            // return URI.create(matchedFile.getAbsolutePath());
            return URI.create(this.uri + filename);
        } else {
            throw new FileNotFoundException(filename);
        }
    }
}