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.seyren.core.service.notification.HubotNotificationService.java

@Override
public void sendNotification(Check check, Subscription subscription, List<Alert> alerts)
        throws NotificationFailedException {
    String hubotUrl = StringUtils.trimToNull(seyrenConfig.getHubotUrl());

    if (hubotUrl == null) {
        LOGGER.warn("Hubot URL needs to be set before sending notifications to Hubot");
        return;//from w  w  w.j a  va2 s .c o m
    }

    Map<String, Object> body = new HashMap<String, Object>();
    body.put("seyrenUrl", seyrenConfig.getBaseUrl());
    body.put("check", check);
    body.put("subscription", subscription);
    body.put("alerts", alerts);
    body.put("rooms", subscription.getTarget().split(","));

    HttpClient client = HttpClientBuilder.create().useSystemProperties().build();

    HttpPost post = new HttpPost(hubotUrl + "/seyren/alert");
    try {
        HttpEntity entity = new StringEntity(MAPPER.writeValueAsString(body), ContentType.APPLICATION_JSON);
        post.setEntity(entity);
        client.execute(post);
    } catch (IOException e) {
        throw new NotificationFailedException("Sending notification to Hubot at " + hubotUrl + " failed.", e);
    } finally {
        HttpClientUtils.closeQuietly(client);
    }
}

From source file:cf.client.DefaultUaa.java

@Override
public Token getClientToken(String client, String clientSecret) {
    try {//  w w w  . j ava  2s .  co  m
        final HttpPost post = new HttpPost(uaa.resolve(OAUTH_TOKEN_URI));

        post.setHeader(ACCEPT_JSON);

        post.setHeader(createClientCredentialsHeader(client, clientSecret));

        // TODO Do we need to make the grant type configurable?
        final BasicNameValuePair nameValuePair = new BasicNameValuePair("grant_type", "client_credentials");
        post.setEntity(new UrlEncodedFormEntity(Arrays.asList(nameValuePair)));

        final HttpResponse response = httpClient.execute(post);
        try {
            validateResponse(response);
            final HttpEntity entity = response.getEntity();
            final InputStream content = entity.getContent();
            return Token.parseJson(content);
        } finally {
            HttpClientUtils.closeQuietly(response);
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.jive.myco.seyren.core.service.notification.HubotNotificationService.java

@Override
public void sendNotification(Check check, Subscription subscription, List<Alert> alerts)
        throws NotificationFailedException {
    String hubotUrl = StringUtils.trimToNull(seyrenConfig.getHubotUrl());

    if (hubotUrl == null) {
        LOGGER.warn("Hubot URL needs to be set before sending notifications to Hubot");
        return;//w  w w  . j a v a2  s .  co m
    }

    Map<String, Object> body = new HashMap<String, Object>();
    body.put("seyrenUrl", seyrenConfig.getBaseUrl());
    body.put("check", check);
    body.put("subscription", subscription);
    body.put("alerts", alerts);
    body.put("rooms", subscription.getTarget().split(","));

    HttpClient client = HttpClientBuilder.create().build();

    HttpPost post = new HttpPost(hubotUrl + "/seyren/alert");
    try {
        HttpEntity entity = new StringEntity(MAPPER.writeValueAsString(body), ContentType.APPLICATION_JSON);
        post.setEntity(entity);
        client.execute(post);
    } catch (IOException e) {
        throw new NotificationFailedException("Sending notification to Hubot at " + hubotUrl + " failed.", e);
    } finally {
        HttpClientUtils.closeQuietly(client);
    }
}

From source file:com.flipkart.flux.client.runtime.FluxRuntimeConnectorHttpImpl.java

@Override
public void submitNewWorkflow(StateMachineDefinition stateMachineDef) {
    CloseableHttpResponse httpResponse = null;
    try {//from  w  ww .j av a2  s  .c om
        httpResponse = postOverHttp(stateMachineDef, "");
    } finally {
        HttpClientUtils.closeQuietly(httpResponse);
    }
}

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

public static void registerUser(String serverId, String mirthVersion, User user, String[] protocols,
        String[] cipherSuites) throws ClientException {
    CloseableHttpClient httpClient = null;
    CloseableHttpResponse httpResponse = null;
    NameValuePair[] params = { new BasicNameValuePair("serverId", serverId),
            new BasicNameValuePair("version", mirthVersion),
            new BasicNameValuePair("user", ObjectXMLSerializer.getInstance().serialize(user)) };

    HttpPost post = new HttpPost();
    post.setURI(URI.create(URL_CONNECT_SERVER + URL_REGISTRATION_SERVLET));
    post.setEntity(new UrlEncodedFormEntity(Arrays.asList(params), Charset.forName("UTF-8")));
    RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(TIMEOUT)
            .setConnectionRequestTimeout(TIMEOUT).setSocketTimeout(TIMEOUT).build();

    try {/*  ww  w .  java  2 s  .co m*/
        HttpClientContext postContext = HttpClientContext.create();
        postContext.setRequestConfig(requestConfig);
        httpClient = getClient(protocols, cipherSuites);
        httpResponse = httpClient.execute(post, postContext);
        StatusLine statusLine = httpResponse.getStatusLine();
        int statusCode = statusLine.getStatusCode();
        if ((statusCode != HttpStatus.SC_OK) && (statusCode != HttpStatus.SC_MOVED_TEMPORARILY)) {
            throw new Exception("Failed to connect to update server: " + statusLine);
        }
    } catch (Exception e) {
        throw new ClientException(e);
    } finally {
        HttpClientUtils.closeQuietly(httpResponse);
        HttpClientUtils.closeQuietly(httpClient);
    }
}

From source file:com.naver.timetable.bo.HttpClientBO.java

public String getHttpBody(String url, String method, List<NameValuePair> param) {
    HttpClient httpClient = null;// ww w .ja va 2  s.co  m
    HttpResponse httpResponse = null;
    HttpRequestBase httpRequest;

    try {
        if (StringUtils.upperCase(method).equals("POST")) {
            httpRequest = new HttpPost(url);
            ((HttpPost) httpRequest).setEntity(new UrlEncodedFormEntity(param));
        } else {
            httpRequest = new HttpGet(url);
        }

        TrustManager[] trustManagers = new TrustManager[1];
        trustManagers[0] = new DefaultTrustManager();

        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(new KeyManager[0], trustManagers, new SecureRandom());
        SSLContext.setDefault(sslContext);

        sslContext.init(null, trustManagers, null);
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,
                SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).build();

        //         httpClient = HttpClientBuilder.create().build();
        httpResponse = httpClient.execute(httpRequest);
        return EntityUtils.toString(httpResponse.getEntity());
    } catch (ClientProtocolException e) {
        LOG.error("Client protocol error : ", e);
    } catch (IOException e) {
        LOG.error("IO error : ", e);
    } catch (KeyManagementException e) {
        LOG.error("IO error : ", e);
    } catch (NoSuchAlgorithmException e) {
        LOG.error("IO error : ", e);
    } finally {
        // ?
        HttpClientUtils.closeQuietly(httpResponse);
        HttpClientUtils.closeQuietly(httpClient);
    }

    return null;
}

From source file:org.eclipse.rdf4j.http.client.SharedHttpClientSessionManager.java

/**
 * @param httpClient/*  w w w . ja  v a2 s  . c  om*/
 *        The httpClient to use for remote/service calls.
 */
public void setHttpClient(HttpClient httpClient) {
    synchronized (this) {
        this.httpClient = Objects.requireNonNull(httpClient, "HTTP Client cannot be null");
        // If they set a client, we need to check whether we need to
        // close any existing dependentClient
        CloseableHttpClient toCloseDependentClient = dependentClient;
        dependentClient = null;
        if (toCloseDependentClient != null) {
            HttpClientUtils.closeQuietly(toCloseDependentClient);
        }
    }
}

From source file:com.elastic.support.util.RestModule.java

public String submitRequest(String protocol, String host, int port, String request, String queryName,
        String destination) {/*from  ww  w.  j  a v a  2  s  .  co m*/

    HttpResponse response = null;
    InputStream responseStream = null;
    String result = null;
    String url = protocol + "://" + host + ":" + port + "/" + request;

    try {
        HttpHost httpHost = new HttpHost(host, port, protocol);
        HttpGet httpget = new HttpGet(url);
        response = client.execute(httpHost, httpget, getLocalContext(httpHost));
        try {
            org.apache.http.HttpEntity entity = response.getEntity();
            if (entity != null) {
                if (queryName == null || queryName.equals("")) {
                    checkResponseCode(url, response);
                    result = EntityUtils.toString(entity);
                    logger.info(request + " was submitted");
                } else {
                    checkResponseCode(queryName, response);
                    responseStream = entity.getContent();
                    FileOutputStream fos = new FileOutputStream(destination);
                    IOUtils.copy(responseStream, fos);
                    logger.info("Diagnostic query: " + queryName + " was retrieved and saved to disk.");
                }
            } else {
                Files.write(Paths.get(destination), ("No results for:" + queryName).getBytes());
            }
        } catch (Exception e) {
            logger.error("Error writing response for " + queryName + " to disk.", e);
        } finally {
            HttpClientUtils.closeQuietly(response);
        }
    } catch (HttpHostConnectException e) {
        throw new RuntimeException("Error connecting to host " + url, e);
    } catch (Exception e) {
        if (request.contains("_license")) {
            logger.info("There were no licenses installed");
        } else if (e.getMessage().contains("401 Unauthorized")) {
            logger.error("Auth failure", e);
            throw new RuntimeException("Authentication failure: invalid login credentials.", e);
        } else {
            logger.error("Diagnostic query: " + queryName + "failed.", e);
        }
    }

    return result;

}

From source file:com.elastic.support.util.RestExec.java

public void execConfiguredQuery(String url, String destination) {

    HttpResponse response = null;//from w  w w  . j a v  a2s .  c o  m
    boolean ret = true;
    response = exec(url);
    streamResponseToFile(response, destination);
    HttpClientUtils.closeQuietly(response);
}