Example usage for org.apache.http.impl.client CloseableHttpClient close

List of usage examples for org.apache.http.impl.client CloseableHttpClient close

Introduction

In this page you can find the example usage for org.apache.http.impl.client CloseableHttpClient close.

Prototype

public void close() throws IOException;

Source Link

Document

Closes this stream and releases any system resources associated with it.

Usage

From source file:org.flowable.admin.service.engine.ProcessDefinitionService.java

protected BpmnModel executeRequestForXML(HttpUriRequest request, ServerConfig serverConfig,
        int expectedStatusCode) {

    FlowableServiceException exception = null;
    CloseableHttpClient client = clientUtil.getHttpClient(serverConfig);
    try {//from   ww w .  j  a v a 2s .c  o m
        CloseableHttpResponse response = client.execute(request);

        try {
            InputStream responseContent = response.getEntity().getContent();
            XMLInputFactory xif = XMLInputFactory.newInstance();
            InputStreamReader in = new InputStreamReader(responseContent, "UTF-8");
            XMLStreamReader xtr = xif.createXMLStreamReader(in);
            BpmnModel bpmnModel = new BpmnXMLConverter().convertToBpmnModel(xtr);

            boolean success = response.getStatusLine() != null
                    && response.getStatusLine().getStatusCode() == expectedStatusCode;

            if (success) {
                return bpmnModel;
            } else {
                exception = new FlowableServiceException(
                        "An error occurred while calling Flowable: " + response.getStatusLine());
            }
        } catch (Exception e) {
            log.warn("Error consuming response from uri {}", request.getURI(), e);
            exception = clientUtil.wrapException(e, request);
        } finally {
            response.close();
        }

    } catch (Exception e) {
        log.error("Error executing request to uri {}", request.getURI(), e);
        exception = clientUtil.wrapException(e, request);

    } finally {
        try {
            client.close();
        } catch (Exception e) {
            log.warn("Error closing http client instance", e);
        }
    }

    if (exception != null) {
        throw exception;
    }

    return null;
}

From source file:net.ymate.framework.commons.HttpClientHelper.java

public IHttpResponse post(String url, ContentType contentType, Map<String, String> params, Header[] headers,
        final String defaultResponseCharset) throws Exception {
    CloseableHttpClient _httpClient = __doBuildHttpClient();
    try {/*from   w  w  w  . ja va 2s .  c o  m*/
        RequestBuilder _reqBuilder = RequestBuilder.post().setUri(url).setEntity(EntityBuilder.create()
                .setContentType(contentType)
                .setContentEncoding(contentType == null || contentType.getCharset() == null ? DEFAULT_CHARSET
                        : contentType.getCharset().name())
                .setParameters(__doBuildNameValuePairs(params)).build());
        if (headers != null && headers.length > 0) {
            for (Header _header : headers) {
                _reqBuilder.addHeader(_header);
            }
        }
        return _httpClient.execute(_reqBuilder.build(), new ResponseHandler<IHttpResponse>() {

            public IHttpResponse handleResponse(HttpResponse response) throws IOException {
                if (StringUtils.isNotBlank(defaultResponseCharset)) {
                    return new IHttpResponse.NEW(response, defaultResponseCharset);
                }
                return new IHttpResponse.NEW(response);
            }

        });
    } finally {
        _httpClient.close();
    }
}

From source file:org.opendaylight.infrautils.diagstatus.shell.HttpClient.java

public HttpResponse sendRequest(HttpRequest request) throws Exception {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    if (httpclient == null) {
        throw new ClientProtocolException("Couldn't create an HTTP client");
    }// ww w .  java  2 s  .c o  m
    RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(request.getTimeout())
            .setConnectTimeout(request.getTimeout()).build();
    HttpRequestBase httprequest;
    String method = request.getMethod();
    if (method.equalsIgnoreCase("GET")) {
        httprequest = new HttpGet(request.getUri());
    } else if (method.equalsIgnoreCase("POST")) {
        httprequest = new HttpPost(request.getUri());
        if (request.getEntity() != null) {
            StringEntity sentEntity = new StringEntity(request.getEntity());
            sentEntity.setContentType(request.getContentType());
            ((HttpEntityEnclosingRequestBase) httprequest).setEntity(sentEntity);
        }
    } else if (method.equalsIgnoreCase("PUT")) {
        httprequest = new HttpPut(request.getUri());
        if (request.getEntity() != null) {
            StringEntity sentEntity = new StringEntity(request.getEntity());
            sentEntity.setContentType(request.getContentType());
            ((HttpEntityEnclosingRequestBase) httprequest).setEntity(sentEntity);
        }
    } else if (method.equalsIgnoreCase("DELETE")) {
        httprequest = new HttpDelete(request.getUri());
    } else {
        httpclient.close();
        throw new IllegalArgumentException(
                "This profile class only supports GET, POST, PUT, and DELETE methods");
    }
    httprequest.setConfig(requestConfig);
    // add request headers
    Iterator<String> headerIterator = request.getHeaders().keySet().iterator();
    while (headerIterator.hasNext()) {
        String header = headerIterator.next();
        Iterator<String> valueIterator = request.getHeaders().get(header).iterator();
        while (valueIterator.hasNext()) {
            httprequest.addHeader(header, valueIterator.next());
        }
    }
    CloseableHttpResponse response = httpclient.execute(httprequest);
    try {
        int httpResponseCode = response.getStatusLine().getStatusCode();
        HashMap<String, List<String>> headerMap = new HashMap<>();
        // copy response headers
        HeaderIterator it = response.headerIterator();
        while (it.hasNext()) {
            Header nextHeader = it.nextHeader();
            String name = nextHeader.getName();
            String value = nextHeader.getValue();
            if (headerMap.containsKey(name)) {
                headerMap.get(name).add(value);
            } else {
                List<String> list = new ArrayList<>();
                list.add(value);
                headerMap.put(name, list);
            }
        }
        if (httpResponseCode > 299) {
            return new HttpResponse(httpResponseCode, response.getStatusLine().getReasonPhrase(), headerMap);
        }
        Optional<HttpEntity> receivedEntity = Optional.ofNullable(response.getEntity());
        String httpBody = receivedEntity.isPresent() ? EntityUtils.toString(receivedEntity.get()) : null;
        return new HttpResponse(response.getStatusLine().getStatusCode(), httpBody, headerMap);
    } finally {
        response.close();
    }
}

From source file:com.esri.geoevent.test.performance.provision.GeoEventProvisioner.java

private void refreshToken() throws IOException {
    //System.out.println("Refreshing token with username=" + userName + " and password=" + password);
    long now = System.currentTimeMillis();
    if (now < expiration) {
        return;/*from w  w w.  j a va2  s  . c  om*/
    }

    System.out.print(ImplMessages.getMessage("PROVISIONER_FETCHING_TOKEN_MSG"));
    referer = "https://" + hostName + ":6143/geoevent/admin";
    String serverTokenUrl = "http://" + hostName + ":6080/arcgis/tokens/generateToken";
    CloseableHttpClient httpClient = HttpClients.createDefault();

    try {
        HttpUriRequest postRequest = RequestBuilder.post().setUri(new URI(serverTokenUrl))
                .addParameter("username", userName).addParameter("password", password)
                .addParameter("client", "referer").addParameter("referer", referer).addParameter("f", "json")
                .build();
        HttpResponse tokenGenerationResponse = httpClient.execute(postRequest);
        ObjectMapper mapper = new ObjectMapper();
        JsonNode schema = mapper.readTree(tokenGenerationResponse.getEntity().getContent());

        if (!schema.has("token")) {
            System.out.println(ImplMessages.getMessage("PROVISIONER_TOKEN_ERROR_RESPONSE", schema.toString()));
            throw new IOException(ImplMessages.getMessage("PROVISIONER_TOKEN_ERROR"));
        }
        token = schema.get("token").asText();
        expiration = schema.get("expires").asLong();
        System.out.println(ImplMessages.getMessage("DONE"));
    } catch (UnsupportedEncodingException | ClientProtocolException | URISyntaxException e) {
        System.err.println(ImplMessages.getMessage("PROVISIONER_TOKEN_EXCEPTION_ERROR", e.getMessage()));
        e.printStackTrace();
        throw new IOException(e.getMessage());
    } finally {
        try {
            httpClient.close();
        } catch (Throwable t) {
            throw new IOException(t.getMessage());
        }
    }
}

From source file:org.skfiy.typhon.spi.auth.p.Four399Authenticator.java

@Override
public UserInfo authentic(OAuth2 oauth) {
    CloseableHttpClient hc = HC_BUILDER.build();
    HttpPost httpPost = new HttpPost("http://dev.sj.4399api.net/Rest?ac=checkToken");

    List<NameValuePair> nvps = new ArrayList<>();
    nvps.add(new BasicNameValuePair("uid", oauth.getUid()));
    nvps.add(new BasicNameValuePair("access_token", oauth.getCode()));
    nvps.add(new BasicNameValuePair("app_key", "100979"));
    nvps.add(new BasicNameValuePair("app_secret", "da7be84d18a8aec8a5a45bbc6e5889e9"));

    try {/*from   ww  w  . j  a va 2 s .c  o m*/

        httpPost.setEntity(new UrlEncodedFormEntity(nvps));
        JSONObject json = hc.execute(httpPost, new ResponseHandler<JSONObject>() {

            @Override
            public JSONObject handleResponse(HttpResponse response)
                    throws ClientProtocolException, IOException {
                String str = StreamUtils.copyToString(response.getEntity().getContent(),
                        StandardCharsets.UTF_8);
                return JSON.parseObject(str);
            }
        });

        if (json.getIntValue("code") != 10000) {
            throw new OAuth2Exception(json.getString("message"));
        }

        UserInfo info = new UserInfo();
        info.setUsername(getPlatform().getLabel() + "-" + json.getJSONObject("data").getString("username"));
        info.setPlatform(getPlatform());
        return info;
    } catch (IOException ex) {
        throw new OAuth2Exception("4399?", ex);
    } finally {
        try {
            hc.close();
        } catch (IOException ex) {
        }
    }
}

From source file:atc.otn.ckan.client.CKANClient.java

/***
 * /*ww  w  .  j  a  v a 2s .  com*/
 */
public JSONArray getLicenses() {

    //********************** Variables **********************

    CloseableHttpClient httpclient = HttpClients.createDefault();
    ;

    HttpGet httpGet;

    CloseableHttpResponse response = null;

    JSONObject jsonResp;

    JSONArray licenses = new JSONArray();

    //************************ Action *************************  

    try {

        //prepare http post
        httpGet = new HttpGet(CKAN_BASEURL + "license_list");
        httpGet.setHeader("Content-Type", "application/json");
        httpGet.setHeader("Accept", "application/json");

        //call the service
        response = httpclient.execute(httpGet);

        //get the response and convert it to json
        jsonResp = new JSONObject(EntityUtils.toString(response.getEntity()));

        licenses = jsonResp.getJSONArray("result");

        logger.info("licences:" + jsonResp);

    } catch (Exception e) {

        logger.error(e.getMessage());

    } finally {

        if (response != null) {

            try {

                response.close();

                httpclient.close();

            } catch (IOException e) {
                // TODO Auto-generated catch block
                logger.error(e.getMessage());
            }

        } //end if

    } //end finally

    return licenses;

}

From source file:net.maritimecloud.identityregistry.keycloak.spi.eventprovider.McEventListenerProvider.java

private void sendUserUpdate(User user, String orgShortName) {
    CloseableHttpClient client = buildHttpClient();
    if (client == null) {
        return;// w  w w  .  ja v a2  s  . c  om
    }
    HttpPost post = new HttpPost(serverRoot + "/x509/api/org/" + orgShortName + "/user-sync/");
    CloseableHttpResponse response = null;
    try {
        String serializedUser = JsonSerialization.writeValueAsString(user);
        StringEntity input = new StringEntity(serializedUser, ContentType.APPLICATION_JSON);
        input.setContentType("application/json");
        post.setEntity(input);
        log.info("user json: " + serializedUser);
        response = client.execute(post);
        int status = response.getStatusLine().getStatusCode();
        HttpEntity entity = response.getEntity();
        if (status != 200) {
            String json = getContent(entity);
            String error = "User sync failed. Bad status: " + status + " response: " + json;
            log.error(error);
        } else {
            log.info("User sync'ed!");
        }
    } catch (ClientProtocolException e) {
        log.error("Threw exception", e);
    } catch (IOException e) {
        log.error("Threw exception", e);
    } finally {
        try {
            if (response != null) {
                response.close();
            }
            client.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            log.error("Threw exception", e);
        }
    }
}

From source file:org.fao.geonet.api.records.editing.InspireValidatorUtils.java

/**
 * Gets the tests./*from  ww  w. j a  va2s . c  o  m*/
 *
 * @param endPoint the end point
 * @param client the client (optional)
 * @return the tests
 */
private static List<String> getTests(String endPoint, CloseableHttpClient client) {

    boolean close = false;
    if (client == null) {
        client = HttpClients.createDefault();
        close = true;
    }

    try {

        HttpGet request = new HttpGet(endPoint + ExecutableTestSuites_URL);

        request.addHeader("User-Agent", USER_AGENT);
        request.addHeader("Accept", ACCEPT);
        HttpResponse response;

        response = client.execute(request);

        if (response.getStatusLine().getStatusCode() == 200) {

            List<String> testList = new ArrayList<>();

            ResponseHandler<String> handler = new BasicResponseHandler();
            String body = handler.handleResponse(response);

            JSONObject jsonRoot = new JSONObject(body);

            JSONObject etfItemCollection = jsonRoot.getJSONObject("EtfItemCollection");
            JSONObject executableTestSuites = etfItemCollection.getJSONObject("executableTestSuites");
            JSONArray executableTestSuiteArray = executableTestSuites.getJSONArray("ExecutableTestSuite");

            for (int i = 0; i < executableTestSuiteArray.length(); i++) {
                JSONObject test = executableTestSuiteArray.getJSONObject(i);

                boolean ok = false;

                for (String testToRun : TESTS_TO_RUN) {
                    ok = ok || testToRun.equals(test.getString("label"));
                }

                if (ok) {
                    testList.add(test.getString("id"));
                }
            }

            return testList;
        } else {
            Log.warning(Log.SERVICE, "WARNING: INSPIRE service HTTP response: "
                    + response.getStatusLine().getStatusCode() + " for " + ExecutableTestSuites_URL);
            return null;
        }
    } catch (Exception e) {
        Log.error(Log.SERVICE, "Exception in INSPIRE service: " + endPoint, e);
        return null;
    } finally {
        if (close) {
            try {
                client.close();
            } catch (IOException e) {
                Log.error(Log.SERVICE, "Error closing CloseableHttpClient: " + endPoint, e);
            }
        }
    }
}

From source file:atc.otn.ckan.client.CKANClient.java

/***
 * //from   w  ww.ja  v a2  s  .  c  o  m
 * @param liferayID
 */
private String getUserAPIKey(long liferayID) {

    //********************** Variables **********************

    CloseableHttpClient httpclient = HttpClients.createDefault();
    ;

    HttpGet httpGet;

    CloseableHttpResponse response = null;

    JSONObject jsonResp;

    String ckanAPIKey = "";

    //************************ Action *************************  

    try {

        //prepare http post
        httpGet = new HttpGet(PLATFORM_BASEURL + "/ckanservices/" + "apikeys/" + liferayID);
        httpGet.setHeader("Content-Type", "application/json");
        httpGet.setHeader("Accept", "application/json");

        //call the service
        response = httpclient.execute(httpGet);

        //get the response and convert it to json
        jsonResp = new JSONObject(EntityUtils.toString(response.getEntity()));

        //extract the user's api key
        ckanAPIKey = jsonResp.getString("ckanApikey");

    } catch (Exception e) {

        logger.error(e.getMessage());

    } finally {

        if (response != null) {

            try {

                response.close();

                httpclient.close();

            } catch (IOException e) {
                // TODO Auto-generated catch block
                logger.error(e.getMessage());
            }

        } //end if

    } //end finally

    return ckanAPIKey;

}

From source file:tv.arte.resteventapi.core.clients.RestEventApiRestClient.java

/**
 * Executes the REST request described by the {@link RestEvent}
 * //from  w w  w.  ja  va2 s . c  o  m
 * @param restEvent The {@link RestEvent} to process
 * @return A result of the execution
 * @throws RestEventApiRuntimeException In case of non managed errors
 */
public static RestClientExecutionResult execute(final RestEvent restEvent) throws RestEventApiRuntimeException {
    RestClientExecutionResult result = new RestClientExecutionResult();
    String url = restEvent.getUrl();
    CloseableHttpClient client = null;
    HttpUriRequest request = null;
    Integer responseCode = null;

    try {
        //Request custom configs
        RequestConfig.Builder requestBuilder = RequestConfig.custom();
        requestBuilder = requestBuilder.setConnectTimeout(restEvent.getTimeout());
        requestBuilder = requestBuilder.setConnectionRequestTimeout(restEvent.getTimeout());

        client = HttpClientBuilder.create().setDefaultRequestConfig(requestBuilder.build()).build();

        //Determine the method to execute
        switch (restEvent.getMethod()) {
        case GET:
            request = new HttpGet(url);
            break;
        case POST:
            request = new HttpPost(url);
            break;
        case PUT:
            request = new HttpPut(url);
            break;
        case DELETE:
            request = new HttpDelete(url);
            break;
        case PATCH:
            request = new HttpPatch(url);
            break;
        case HEAD:
            request = new HttpHead(url);
            break;
        default:
            throw new RestEventApiRuntimeException("RestEventAPI unsupported HTTP method");
        }

        //Set the body for eligible methods
        if (restEvent.getBody() != null && request instanceof HttpEntityEnclosingRequestBase) {
            ((HttpEntityEnclosingRequestBase) request).setEntity(new StringEntity(restEvent.getBody()));
        }

        //Set headers
        if (CollectionUtils.isNotEmpty(restEvent.getHeaders())) {
            for (String strHeader : restEvent.getHeaders()) {
                CharArrayBuffer headerBuffer = new CharArrayBuffer(strHeader.length() + 1);
                headerBuffer.append(strHeader);
                request.addHeader(new BufferedHeader(headerBuffer));
            }
        }

        HttpResponse response = client.execute(request);
        responseCode = response.getStatusLine().getStatusCode();

        result.setState(RestClientCallState.OK);
    } catch (ConnectTimeoutException e) {
        result.setState(RestClientCallState.TIMEOUT);
    } catch (Exception e) {
        throw new RestEventApiRuntimeException("Un error occured while processing rest event", e);
    } finally {
        result.setResponseCode(responseCode);

        try {
            client.close();
        } catch (Exception e2) {
            logger.warn("Unable to close HTTP client", e2);
        }
    }

    return result;
}