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

private OctaneResponse login(OctaneConfiguration config) throws IOException {
    OctaneResponse result;/*from   w w w  .  j  a  va2 s .co  m*/
    HttpResponse response = null;

    try {
        HttpUriRequest loginRequest = buildLoginRequest(config);
        HttpClientContext context = createHttpContext(loginRequest.getURI().toString(), true);
        response = httpClient.execute(loginRequest, context);

        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            refreshSecurityToken(context, true);
        } else {
            logger.warn("failed to login to " + config + "; response status: "
                    + response.getStatusLine().getStatusCode());
        }
        result = createNGAResponse(response);
    } catch (IOException ioe) {
        logger.debug("failed to login to " + config, ioe);
        throw ioe;
    } finally {
        if (response != null) {
            EntityUtils.consumeQuietly(response.getEntity());
            HttpClientUtils.closeQuietly(response);
        }
    }

    return result;
}

From source file:com.mirth.connect.connectors.ws.WebServiceDispatcher.java

/**
 * Returns the URL for the passed in String. If the URL requires authentication, then the WSDL
 * is saved as a temp file and the URL for that file is returned.
 * //from  ww  w .j av a 2s .c  om
 * @param wsdlUrl
 * @param username
 * @param password
 * @return
 * @throws Exception
 */
private URL getWsdlUrl(DispatchContainer dispatchContainer) throws Exception {
    URI uri = new URI(dispatchContainer.getCurrentWsdlUrl());

    // If the URL points to file, just return it
    if (!uri.getScheme().equalsIgnoreCase("file")) {
        BasicHttpClientConnectionManager httpClientConnectionManager = new BasicHttpClientConnectionManager(
                socketFactoryRegistry.build());
        httpClientConnectionManager.setSocketConfig(SocketConfig.custom().setSoTimeout(timeout).build());
        HttpClientBuilder clientBuilder = HttpClients.custom()
                .setConnectionManager(httpClientConnectionManager);
        HttpUtil.configureClientBuilder(clientBuilder);
        CloseableHttpClient client = clientBuilder.build();

        try {
            clients.add(client);
            HttpClientContext context = HttpClientContext.create();

            if (dispatchContainer.getCurrentUsername() != null
                    && dispatchContainer.getCurrentPassword() != null) {
                CredentialsProvider credsProvider = new BasicCredentialsProvider();
                AuthScope authScope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT,
                        AuthScope.ANY_REALM);
                Credentials credentials = new UsernamePasswordCredentials(
                        dispatchContainer.getCurrentUsername(), dispatchContainer.getCurrentPassword());
                credsProvider.setCredentials(authScope, credentials);
                AuthCache authCache = new BasicAuthCache();
                RegistryBuilder<AuthSchemeProvider> registryBuilder = RegistryBuilder
                        .<AuthSchemeProvider>create();
                registryBuilder.register(AuthSchemes.BASIC, new BasicSchemeFactory());

                context.setCredentialsProvider(credsProvider);
                context.setAuthSchemeRegistry(registryBuilder.build());
                context.setAuthCache(authCache);
            }

            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(timeout)
                    .setSocketTimeout(timeout).setStaleConnectionCheckEnabled(true).build();
            context.setRequestConfig(requestConfig);

            return getWsdl(client, context, dispatchContainer, new HashMap<String, File>(),
                    dispatchContainer.getCurrentWsdlUrl()).toURI().toURL();
        } finally {
            HttpClientUtils.closeQuietly(client);
            clients.remove(client);
        }
    }

    return uri.toURL();
}

From source file:com.baidu.rigel.biplatform.ac.util.HttpRequest.java

/**
 * ?HttpClient/*from   ww w. j a  va  2s  .c om*/
 * @param client HttpClient30X??
 * @param response 
 * @param params ?
 * @param isGet ?get?
 * @return 
 * @throws ParseException ?
 * @throws IOException
 */
private static String processHttpResponse(HttpClient client, HttpResponse response, Map<String, String> params,
        boolean isGet) throws ParseException, IOException {
    try {
        StatusLine statusLine = response.getStatusLine();
        // 301 302 ???
        if (statusLine.getStatusCode() == 301 || statusLine.getStatusCode() == 302) {
            Header header = response.getFirstHeader(HttpHeaders.LOCATION);
            LOGGER.info("get status code:" + statusLine.getStatusCode() + " redirect:" + header.getValue());
            if (isGet) {
                return sendGet(client, header.getValue(), params);
            } else {
                return sendPost(client, header.getValue(), params);
            }
        }
        if (statusLine.getStatusCode() != 200) {
            throw new IllegalStateException("Server internal error[" + statusLine.getStatusCode() + "]");
        }

        HttpEntity entity = response.getEntity();
        return EntityUtils.toString(entity, "utf-8");
    } catch (Exception e) {
        LOGGER.warn(e.getMessage(), e);
        throw e;
    } finally {
        HttpClientUtils.closeQuietly(response);
    }

}

From source file:cf.client.DefaultCloudController.java

private UUID postJsonToUri(Token token, Object json, String uri) {
    try {//from w  w  w. ja va  2  s  .  c  o  m
        final String requestString = mapper.writeValueAsString(json);
        final HttpPost post = new HttpPost(target.resolve(uri));
        post.addHeader(token.toAuthorizationHeader());
        post.setEntity(new StringEntity(requestString, ContentType.APPLICATION_JSON));
        final HttpResponse response = httpClient.execute(post);
        try {
            validateResponse(response, 201);
            final JsonNode responseJson = mapper.readTree(response.getEntity().getContent());
            return UUID.fromString(responseJson.get("metadata").get("guid").asText());
        } finally {
            HttpClientUtils.closeQuietly(response);
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:fi.laverca.util.CommonsHTTPSender.java

private InputStream createConnectionReleasingInputStream(final HttpPost post, final HttpResponse response)
        throws IOException {
    return new FilterInputStream(response.getEntity().getContent()) {
        @Override/*from   w w w.  ja v  a 2s.  c o  m*/
        public void close() throws IOException {
            if (log.isDebugEnabled())
                log.debug("Close http response, and release post method connection");
            try {
                super.close();
            } finally {
                HttpClientUtils.closeQuietly(response);
                post.releaseConnection();
            }
        }
    };
}

From source file:com.mirth.connect.connectors.ws.WebServiceDispatcher.java

private File getWsdl(CloseableHttpClient client, HttpContext context, DispatchContainer dispatchContainer,
        Map<String, File> visitedUrls, String wsdlUrl) throws Exception {
    if (visitedUrls.containsKey(wsdlUrl)) {
        return visitedUrls.get(wsdlUrl);
    }/* w  w  w  . j av  a 2s .  c  om*/

    String wsdl = null;
    StatusLine responseStatusLine = null;
    CloseableHttpResponse response = client.execute(new HttpGet(wsdlUrl), context);

    try {
        responseStatusLine = response.getStatusLine();

        if (responseStatusLine.getStatusCode() == HttpStatus.SC_OK) {
            ContentType responseContentType = ContentType.get(response.getEntity());
            if (responseContentType == null) {
                responseContentType = ContentType.TEXT_XML;
            }

            Charset responseCharset = responseContentType.getCharset();
            if (responseContentType.getCharset() == null) {
                responseCharset = ContentType.TEXT_XML.getCharset();
            }

            wsdl = IOUtils.toString(response.getEntity().getContent(), responseCharset);
        }
    } finally {
        HttpClientUtils.closeQuietly(response);
    }

    if (StringUtils.isNotBlank(wsdl)) {
        File tempFile = File.createTempFile("WebServiceSender", ".wsdl");
        tempFile.deleteOnExit();
        visitedUrls.put(wsdlUrl, tempFile);

        try {
            DonkeyElement element = new DonkeyElement(wsdl);
            for (DonkeyElement child : element.getChildElements()) {
                if (child.getLocalName().equals("import") && child.hasAttribute("location")) {
                    String location = new URI(wsdlUrl).resolve(child.getAttribute("location")).toString();
                    child.setAttribute("location",
                            getWsdl(client, context, dispatchContainer, visitedUrls, location).toURI().toURL()
                                    .toString());
                }
            }

            wsdl = element.toXml();
        } catch (Exception e) {
            logger.warn("Unable to cache imports for WSDL at URL: " + wsdlUrl, e);
        }

        FileUtils.writeStringToFile(tempFile, wsdl);
        dispatchContainer.getTempFiles().add(tempFile);

        return tempFile;
    } else {
        throw new Exception(
                "Unable to load WSDL at URL \"" + wsdlUrl + "\": " + String.valueOf(responseStatusLine));
    }
}

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

@Override
public Pipeline updatePipeline(String serverIdentity, String jobName, Pipeline pipeline) {
    HttpPut request = new HttpPut(
            createSharedSpaceInternalApiUri(URI_JOB_CONFIGURATION, serverIdentity, jobName));

    JSONObject pipelineObject = new JSONObject();
    pipelineObject.put("contextEntityType", "pipeline");
    pipelineObject.put("contextEntityId", pipeline.getId());
    pipelineObject.put("workspaceId", pipeline.getWorkspaceId());
    if (pipeline.getName() != null) {
        pipelineObject.put("contextEntityName", pipeline.getName());
    }//  ww w. ja  va  2  s  . c o m
    if (pipeline.getReleaseId() != null) {
        if (pipeline.getReleaseId() == -1) {
            pipelineObject.put("releaseId", JSONNull.getInstance());
        } else {
            pipelineObject.put("releaseId", pipeline.getReleaseId());
        }
    }
    if (pipeline.getIgnoreTests() != null) {
        pipelineObject.put("ignoreTests", pipeline.getIgnoreTests());
    }
    if (pipeline.getTaxonomies() != null) {
        JSONArray taxonomies = taxonomiesArray(pipeline.getTaxonomies());
        pipelineObject.put("taxonomies", taxonomies);
    }

    if (pipeline.getFields() != null) {
        JSONObject listFields = listFieldsObject(pipeline.getFields());
        pipelineObject.put("listFields", listFields);
    }

    JSONArray data = new JSONArray();
    data.add(pipelineObject);
    JSONObject payload = new JSONObject();
    payload.put("data", data);

    request.setEntity(new StringEntity(payload.toString(), ContentType.APPLICATION_JSON));
    request.setHeader(HEADER_ACCEPT, ContentType.APPLICATION_JSON.getMimeType());
    HttpResponse response = null;
    try {
        response = execute(request);
        if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            throw createRequestException("Pipeline update failed", response);
        }
        String json = IOUtils.toString(response.getEntity().getContent(), "UTF-8");
        return getPipelineById(json, pipeline.getId());
    } catch (IOException e) {
        throw new RequestErrorException("Cannot update pipeline.", e);
    } finally {
        HttpClientUtils.closeQuietly(response);
    }
}

From source file:cf.client.DefaultCloudController.java

private void deleteUri(Token token, String uri) {
    try {/*from w  w w  .j a va  2  s. co  m*/
        final HttpDelete delete = new HttpDelete(target.resolve(uri));
        delete.addHeader(token.toAuthorizationHeader());
        final HttpResponse response = httpClient.execute(delete);
        try {
            validateResponse(response, 204);
        } finally {
            HttpClientUtils.closeQuietly(response);
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

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

/**
 * Invokes {@link org.apache.http.client.HttpClient#execute(org.apache.http.client.methods.HttpUriRequest)}
 * with given request and it does login if it is necessary.
 *
 * Method does not support request with non-repeatable entity (see {@link HttpEntity#isRepeatable()}).
 *
 * @param request which should be executed
 * @return response for given request/*from  w  w w .  j  av  a2s . co  m*/
 * @throws IllegalArgumentException when request entity is not repeatable
 */
protected HttpResponse execute(HttpUriRequest request) throws IOException {
    HttpResponse response;

    if (LWSSO_TOKEN == null) {
        login();
    }
    HttpContext localContext = new BasicHttpContext();
    CookieStore localCookies = new BasicCookieStore();
    localCookies.addCookie(LWSSO_TOKEN);
    localContext.setAttribute(HttpClientContext.COOKIE_STORE, localCookies);

    addRequestHeaders(request);
    response = httpClient.execute(request, localContext);
    if (response.getStatusLine().getStatusCode() == 401) {
        HttpClientUtils.closeQuietly(response);
        login();
        localCookies.clear();
        localCookies.addCookie(LWSSO_TOKEN);
        localContext.setAttribute(HttpClientContext.COOKIE_STORE, localCookies);
        addRequestHeaders(request);
        response = httpClient.execute(request, localContext);
    }
    return response;
}