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.mqm.client.MqmRestClientImpl.java

@Override
public void deleteTestsFromPipelineNodes(String jobName, Long pipelineId, Long workspaceId) {
    HttpDelete request = new HttpDelete(
            createWorkspaceInternalApiUriMap(URI_DELETE_NODES_TESTS, workspaceId, pipelineId, jobName));

    HttpResponse response = null;/*from  w w w.ja  v  a 2  s .c o  m*/
    try {
        response = execute(request);
        if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            throw createRequestException("delete tests failed", response);
        }

    } catch (IOException e) {
        throw new RequestErrorException("Cannot delete tests.", e);
    } finally {
        HttpClientUtils.closeQuietly(response);
    }
}

From source file:cf.client.DefaultCloudController.java

private void fetchInfo() {
    try {/*w  ww.  j  a va 2  s  .c o  m*/
        final HttpGet get = new HttpGet(target.resolve("/info"));
        // TODO Standardize on error handling
        // TODO Throw exception if non version 2 Cloud Controller
        final HttpResponse response = httpClient.execute(get);
        try {
            synchronized (lock) {
                info = mapper.readValue(response.getEntity().getContent(), Info.class);
            }
        } finally {
            HttpClientUtils.closeQuietly(response);
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

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

<E> PagedList<E> getEntities(URI uri, int offset, EntityFactory<E> factory) {
    HttpGet request = new HttpGet(uri);
    HttpResponse response = null;/*w w w . j  a  v  a  2 s  . c o  m*/
    try {
        response = execute(request);
        if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            throw createRequestException("Entity retrieval failed", response);
        }
        return convertResponceToPagedList(factory, offset, response);
    } catch (IOException e) {
        throw new RequestErrorException("Cannot retrieve entities from MQM.", e);
    } finally {
        HttpClientUtils.closeQuietly(response);
    }
}

From source file:cf.client.DefaultCloudController.java

private JsonNode fetchResource(Token token, String uri) {
    LOGGER.debug("GET {}", uri);
    try {/*w  ww. jav a2 s  .  c o  m*/
        final HttpGet httpGet = new HttpGet(target.resolve(uri));
        httpGet.setHeader(token.toAuthorizationHeader());
        final HttpResponse response = httpClient.execute(httpGet);
        try {
            validateResponse(response, 200);
            return mapper.readTree(response.getEntity().getContent());
        } finally {
            HttpClientUtils.closeQuietly(response);
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

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

protected <E> PagedList<E> deleteEntities(URI uri, EntityFactory<E> factory) {
    HttpDelete request = new HttpDelete(uri);
    HttpResponse response = null;//from   w  ww  . jav  a2  s. c o m
    try {
        response = execute(request);
        if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            throw createRequestException("Entity delete failed", response);
        }
        return convertResponceToPagedList(factory, 0, response);
    } catch (IOException e) {
        throw new RequestErrorException("Cannot delete entities from MQM.", e);
    } finally {
        HttpClientUtils.closeQuietly(response);
    }
}

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

protected <E> PagedList<E> updateEntities(URI uri, EntityFactory<E> factory) {
    HttpPut request = new HttpPut(uri);
    HttpResponse response = null;//from  w  w  w . j  a  v  a  2s . c  om
    try {
        response = execute(request);
        if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            throw createRequestException("Entity update failed", response);
        }
        return convertResponceToPagedList(factory, 0, response);
    } catch (IOException e) {
        throw new RequestErrorException("Cannot update entity.", e);
    } finally {
        HttpClientUtils.closeQuietly(response);
    }
}

From source file:com.mirth.connect.connectors.http.HttpDispatcher.java

@Override
public Response send(ConnectorProperties connectorProperties, ConnectorMessage connectorMessage) {
    HttpDispatcherProperties httpDispatcherProperties = (HttpDispatcherProperties) connectorProperties;
    eventController.dispatchEvent(new ConnectionStatusEvent(getChannelId(), getMetaDataId(),
            getDestinationName(), ConnectionStatusEventType.WRITING));

    String responseData = null;/*from  w  w  w .j ava  2 s . co  m*/
    String responseError = null;
    String responseStatusMessage = null;
    Status responseStatus = Status.QUEUED;
    boolean validateResponse = false;

    CloseableHttpClient client = null;
    HttpRequestBase httpMethod = null;
    CloseableHttpResponse httpResponse = null;
    File tempFile = null;
    int socketTimeout = NumberUtils.toInt(httpDispatcherProperties.getSocketTimeout(), 30000);

    try {
        configuration.configureDispatcher(this, httpDispatcherProperties);

        long dispatcherId = getDispatcherId();
        client = clients.get(dispatcherId);
        if (client == null) {
            BasicHttpClientConnectionManager httpClientConnectionManager = new BasicHttpClientConnectionManager(
                    socketFactoryRegistry.build());
            httpClientConnectionManager
                    .setSocketConfig(SocketConfig.custom().setSoTimeout(socketTimeout).build());
            HttpClientBuilder clientBuilder = HttpClients.custom()
                    .setConnectionManager(httpClientConnectionManager);
            HttpUtil.configureClientBuilder(clientBuilder);

            if (httpDispatcherProperties.isUseProxyServer()) {
                clientBuilder.setRoutePlanner(new DynamicProxyRoutePlanner());
            }

            client = clientBuilder.build();
            clients.put(dispatcherId, client);
        }

        URI hostURI = new URI(httpDispatcherProperties.getHost());
        String host = hostURI.getHost();
        String scheme = hostURI.getScheme();
        int port = hostURI.getPort();
        if (port == -1) {
            if (scheme.equalsIgnoreCase("https")) {
                port = 443;
            } else {
                port = 80;
            }
        }

        // Parse the content type field first, and then add the charset if needed
        ContentType contentType = ContentType.parse(httpDispatcherProperties.getContentType());
        Charset charset = null;
        if (contentType.getCharset() == null) {
            charset = Charset.forName(CharsetUtils.getEncoding(httpDispatcherProperties.getCharset()));
        } else {
            charset = contentType.getCharset();
        }

        if (httpDispatcherProperties.isMultipart()) {
            tempFile = File.createTempFile(UUID.randomUUID().toString(), ".tmp");
        }

        HttpHost target = new HttpHost(host, port, scheme);

        httpMethod = buildHttpRequest(hostURI, httpDispatcherProperties, connectorMessage, tempFile,
                contentType, charset);

        HttpClientContext context = HttpClientContext.create();

        // authentication
        if (httpDispatcherProperties.isUseAuthentication()) {
            CredentialsProvider credsProvider = new BasicCredentialsProvider();
            AuthScope authScope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM);
            Credentials credentials = new UsernamePasswordCredentials(httpDispatcherProperties.getUsername(),
                    httpDispatcherProperties.getPassword());
            credsProvider.setCredentials(authScope, credentials);
            AuthCache authCache = new BasicAuthCache();
            RegistryBuilder<AuthSchemeProvider> registryBuilder = RegistryBuilder.<AuthSchemeProvider>create();

            if (AuthSchemes.DIGEST.equalsIgnoreCase(httpDispatcherProperties.getAuthenticationType())) {
                logger.debug("using Digest authentication");
                registryBuilder.register(AuthSchemes.DIGEST, new DigestSchemeFactory(charset));

                if (httpDispatcherProperties.isUsePreemptiveAuthentication()) {
                    processDigestChallenge(authCache, target, credentials, httpMethod, context);
                }
            } else {
                logger.debug("using Basic authentication");
                registryBuilder.register(AuthSchemes.BASIC, new BasicSchemeFactory(charset));

                if (httpDispatcherProperties.isUsePreemptiveAuthentication()) {
                    authCache.put(target, new BasicScheme());
                }
            }

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

            logger.debug("using authentication with credentials: " + credentials);
        }

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

        // Set proxy information
        if (httpDispatcherProperties.isUseProxyServer()) {
            context.setAttribute(PROXY_CONTEXT_KEY, new HttpHost(httpDispatcherProperties.getProxyAddress(),
                    Integer.parseInt(httpDispatcherProperties.getProxyPort())));
        }

        // execute the method
        logger.debug(
                "executing method: type=" + httpMethod.getMethod() + ", uri=" + httpMethod.getURI().toString());
        httpResponse = client.execute(target, httpMethod, context);
        StatusLine statusLine = httpResponse.getStatusLine();
        int statusCode = statusLine.getStatusCode();
        logger.debug("received status code: " + statusCode);

        Map<String, List<String>> headers = new HashMap<String, List<String>>();
        for (Header header : httpResponse.getAllHeaders()) {
            List<String> list = headers.get(header.getName());

            if (list == null) {
                list = new ArrayList<String>();
                headers.put(header.getName(), list);
            }

            list.add(header.getValue());
        }

        connectorMessage.getConnectorMap().put("responseStatusLine", statusLine.toString());
        connectorMessage.getConnectorMap().put("responseHeaders",
                new MessageHeaders(new CaseInsensitiveMap(headers)));

        ContentType responseContentType = ContentType.get(httpResponse.getEntity());
        if (responseContentType == null) {
            responseContentType = ContentType.TEXT_PLAIN;
        }

        Charset responseCharset = charset;
        if (responseContentType.getCharset() != null) {
            responseCharset = responseContentType.getCharset();
        }

        final String responseBinaryMimeTypes = httpDispatcherProperties.getResponseBinaryMimeTypes();
        BinaryContentTypeResolver binaryContentTypeResolver = new BinaryContentTypeResolver() {
            @Override
            public boolean isBinaryContentType(ContentType contentType) {
                return HttpDispatcher.this.isBinaryContentType(responseBinaryMimeTypes, contentType);
            }
        };

        /*
         * First parse out the body of the HTTP response. Depending on the connector settings,
         * this could end up being a string encoded with the response charset, a byte array
         * representing the raw response payload, or a MimeMultipart object.
         */
        Object responseBody = "";

        // The entity could be null in certain cases such as 204 responses
        if (httpResponse.getEntity() != null) {
            // Only parse multipart if XML Body is selected and Parse Multipart is enabled
            if (httpDispatcherProperties.isResponseXmlBody()
                    && httpDispatcherProperties.isResponseParseMultipart()
                    && responseContentType.getMimeType().startsWith(FileUploadBase.MULTIPART)) {
                responseBody = new MimeMultipart(new ByteArrayDataSource(httpResponse.getEntity().getContent(),
                        responseContentType.toString()));
            } else if (binaryContentTypeResolver.isBinaryContentType(responseContentType)) {
                responseBody = IOUtils.toByteArray(httpResponse.getEntity().getContent());
            } else {
                responseBody = IOUtils.toString(httpResponse.getEntity().getContent(), responseCharset);
            }
        }

        /*
         * Now that we have the response body, we need to create the actual Response message
         * data. Depending on the connector settings this could be our custom serialized XML, a
         * Base64 string encoded from the raw response payload, or a string encoded from the
         * payload with the request charset.
         */
        if (httpDispatcherProperties.isResponseXmlBody()) {
            responseData = HttpMessageConverter.httpResponseToXml(statusLine.toString(), headers, responseBody,
                    responseContentType, httpDispatcherProperties.isResponseParseMultipart(),
                    httpDispatcherProperties.isResponseIncludeMetadata(), binaryContentTypeResolver);
        } else if (responseBody instanceof byte[]) {
            responseData = new String(Base64Util.encodeBase64((byte[]) responseBody), "US-ASCII");
        } else {
            responseData = (String) responseBody;
        }

        validateResponse = httpDispatcherProperties.getDestinationConnectorProperties().isValidateResponse();

        if (statusCode < HttpStatus.SC_BAD_REQUEST) {
            responseStatus = Status.SENT;
        } else {
            eventController.dispatchEvent(new ErrorEvent(getChannelId(), getMetaDataId(),
                    connectorMessage.getMessageId(), ErrorEventType.DESTINATION_CONNECTOR, getDestinationName(),
                    connectorProperties.getName(), "Received error response from HTTP server.", null));
            responseStatusMessage = ErrorMessageBuilder
                    .buildErrorResponse("Received error response from HTTP server.", null);
            responseError = ErrorMessageBuilder.buildErrorMessage(connectorProperties.getName(), responseData,
                    null);
        }
    } catch (Exception e) {
        eventController.dispatchEvent(new ErrorEvent(getChannelId(), getMetaDataId(),
                connectorMessage.getMessageId(), ErrorEventType.DESTINATION_CONNECTOR, getDestinationName(),
                connectorProperties.getName(), "Error connecting to HTTP server.", e));
        responseStatusMessage = ErrorMessageBuilder.buildErrorResponse("Error connecting to HTTP server", e);
        responseError = ErrorMessageBuilder.buildErrorMessage(connectorProperties.getName(),
                "Error connecting to HTTP server", e);
    } finally {
        try {
            HttpClientUtils.closeQuietly(httpResponse);

            // Delete temp files if we created them
            if (tempFile != null) {
                tempFile.delete();
                tempFile = null;
            }
        } finally {
            eventController.dispatchEvent(new ConnectionStatusEvent(getChannelId(), getMetaDataId(),
                    getDestinationName(), ConnectionStatusEventType.IDLE));
        }
    }

    return new Response(responseStatus, responseData, responseStatusMessage, responseError, validateResponse);
}

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

public void changeAppIcon(String applicationHash, File appIcon) throws AppCloudIntegrationTestException {
    HttpClient httpclient = null;//  www . ja v a2  s.c  o  m
    org.apache.http.HttpResponse response = null;
    try {
        httpclient = HttpClients.custom().setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE).build();
        int timeout = (int) AppCloudIntegrationTestUtils.getTimeOutPeriod();
        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_CHANGE_ICON, new FileBody(appIcon));
        builder.addPart(PARAM_NAME_ACTION, new StringBody(CHANGE_APP_ICON_ACTION, ContentType.TEXT_PLAIN));
        builder.addPart(PARAM_NAME_APPLICATION_HASH_ID,
                new StringBody(applicationHash, 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("Update app icon failed " + result);
        }
    } catch (ConnectTimeoutException | java.net.SocketTimeoutException e1) {
        // In most of the cases, even though connection is timed out, actual activity is completed.
        // And this will be asserted so if it failed due to a valid case, it will be captured.
        log.warn("Failed to get 200 ok response from endpoint:" + endpoint, e1);
    } catch (IOException e) {
        log.error("Failed to invoke app icon update API.", e);
        throw new AppCloudIntegrationTestException("Failed to invoke app icon update API.", e);
    } finally {
        HttpClientUtils.closeQuietly(response);
        HttpClientUtils.closeQuietly(httpclient);
    }
}

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

private long postTestResult(ByteArrayEntity entity, boolean skipErrors) {
    HttpPost request = new HttpPost(createSharedSpaceInternalApiUri(URI_TEST_RESULT_PUSH, skipErrors));
    request.setHeader(HTTP.CONTENT_ENCODING, CONTENT_ENCODING_GZIP);
    request.setEntity(entity);//from   w ww .ja v  a2  s. c  om
    HttpResponse response = null;
    try {
        response = execute(request);
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode == HttpStatus.SC_SERVICE_UNAVAILABLE) {
            throw new TemporarilyUnavailableException("Service not available");
        }
        if (statusCode != HttpStatus.SC_ACCEPTED) {
            throw createRequestException("Test result post failed", response);
        }
        String json = IOUtils.toString(response.getEntity().getContent());
        JSONObject jsonObject = JSONObject.fromObject(json);
        return jsonObject.getLong("id");
    } catch (java.io.FileNotFoundException e) {
        throw new FileNotFoundException("Cannot find test result file.", e);
    } catch (IOException e) {
        throw new RequestErrorException("Cannot post test results to MQM.", e);
    } finally {
        HttpClientUtils.closeQuietly(response);
    }
}