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:com.tremolosecurity.provisioning.customTasks.CallRemoteWorkflow.java

@Override
public boolean doTask(User user, Map<String, Object> request) throws ProvisioningException {

    HashMap<String, Object> newRequest = new HashMap<String, Object>();
    for (String name : this.fromRequest) {
        newRequest.put(name, request.get(name));
    }//from   w  w w .  j  av  a  2s. co m

    for (String key : this.staticRequest.keySet()) {
        newRequest.put(key, this.staticRequest.get(key));
    }

    WFCall wfCall = new WFCall();
    wfCall.setName(this.workflowName);
    wfCall.setRequestParams(newRequest);
    wfCall.setUser(new TremoloUser());
    wfCall.getUser().setUid(user.getUserID());
    wfCall.getUser().setUserPassword(user.getPassword());
    wfCall.getUser().setGroups(user.getGroups());
    wfCall.getUser().setAttributes(new ArrayList<Attribute>());
    wfCall.getUser().getAttributes().addAll(user.getAttribs().values());
    wfCall.setUidAttributeName(uidAttributeName);
    wfCall.setReason(task.getWorkflow().getUser().getRequestReason());
    if (task.getWorkflow().getRequester() != null) {
        wfCall.setRequestor(task.getWorkflow().getRequester().getUserID());
    } else {
        wfCall.setRequestor(this.lastMileUser);
    }

    DateTime notBefore = new DateTime();
    notBefore = notBefore.minusSeconds(timeSkew);
    DateTime notAfter = new DateTime();
    notAfter = notAfter.plusSeconds(timeSkew);

    com.tremolosecurity.lastmile.LastMile lastmile = null;

    try {
        lastmile = new com.tremolosecurity.lastmile.LastMile(this.uri, notBefore, notAfter, 0, "oauth2");

    } catch (URISyntaxException e) {
        throw new ProvisioningException("Could not generate lastmile", e);
    }

    Attribute attrib = new Attribute(this.lastMileUid, this.lastMileUser);
    lastmile.getAttributes().add(attrib);
    String encryptedXML = null;

    try {
        encryptedXML = lastmile
                .generateLastMileToken(this.task.getConfigManager().getSecretKey(this.lastmileKeyName));
    } catch (Exception e) {
        throw new ProvisioningException("Could not generate lastmile", e);
    }

    StringBuffer header = new StringBuffer();
    header.append("Bearer ").append(encryptedXML);

    BasicHttpClientConnectionManager bhcm = null;
    CloseableHttpClient http = null;

    try {
        bhcm = new BasicHttpClientConnectionManager(this.task.getConfigManager().getHttpClientSocketRegistry());

        RequestConfig rc = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).setRedirectsEnabled(false)
                .build();

        http = HttpClients.custom().setConnectionManager(bhcm).setDefaultRequestConfig(rc).build();

        HttpPost post = new HttpPost(this.url);
        post.addHeader(new BasicHeader("Authorization", header.toString()));

        Gson gson = new Gson();
        StringEntity str = new StringEntity(gson.toJson(wfCall), ContentType.APPLICATION_JSON);
        post.setEntity(str);

        HttpResponse resp = http.execute(post);
        if (resp.getStatusLine().getStatusCode() != 200) {
            throw new ProvisioningException("Call failed");
        }

    } catch (IOException e) {
        throw new ProvisioningException("Could not make call", e);
    } finally {
        if (http != null) {
            try {
                http.close();
            } catch (IOException e) {
                logger.warn(e);
            }
        }

        if (bhcm != null) {
            bhcm.close();
        }

    }

    return true;
}

From source file:org.gradle.cache.tasks.http.HttpTaskOutputCache.java

@Override
public void store(TaskCacheKey key, final TaskOutputWriter output) throws IOException {
    CloseableHttpClient httpClient = HttpClients.createDefault();
    try {/* ww w. j  a va 2  s .com*/
        final URI uri = root.resolve(key.getHashCode());
        HttpPut httpPut = new HttpPut(uri);
        httpPut.setEntity(new AbstractHttpEntity() {
            @Override
            public boolean isRepeatable() {
                return true;
            }

            @Override
            public long getContentLength() {
                return -1;
            }

            @Override
            public InputStream getContent() throws IOException, UnsupportedOperationException {
                throw new UnsupportedOperationException();
            }

            @Override
            public void writeTo(OutputStream outstream) throws IOException {
                output.writeTo(outstream);
            }

            @Override
            public boolean isStreaming() {
                return false;
            }
        });
        CloseableHttpResponse response = httpClient.execute(httpPut);
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Response for PUT {}: {}", uri, response.getStatusLine());
        }
    } finally {
        httpClient.close();
    }
}

From source file:com.vmware.identity.openidconnect.client.OIDCClientUtils.java

static HttpResponse sendSecureRequest(HttpRequest httpRequest, SSLContext sslContext)
        throws OIDCClientException, SSLConnectionException {
    Validate.notNull(httpRequest, "httpRequest");
    Validate.notNull(sslContext, "sslContext");

    RequestConfig config = RequestConfig.custom().setConnectTimeout(HTTP_CLIENT_TIMEOUT_MILLISECS)
            .setConnectionRequestTimeout(HTTP_CLIENT_TIMEOUT_MILLISECS)
            .setSocketTimeout(HTTP_CLIENT_TIMEOUT_MILLISECS).build();

    CloseableHttpClient client = HttpClients.custom().setSSLContext(sslContext).setDefaultRequestConfig(config)
            .build();/* ww  w .j a  v  a 2s.  c o m*/

    CloseableHttpResponse closeableHttpResponse = null;

    try {
        HttpRequestBase httpTask = httpRequest.toHttpTask();
        closeableHttpResponse = client.execute(httpTask);

        int statusCodeInt = closeableHttpResponse.getStatusLine().getStatusCode();
        StatusCode statusCode;
        try {
            statusCode = StatusCode.parse(statusCodeInt);
        } catch (ParseException e) {
            throw new OIDCClientException("failed to parse status code", e);
        }
        JSONObject jsonContent = null;
        HttpEntity httpEntity = closeableHttpResponse.getEntity();
        if (httpEntity != null) {
            ContentType contentType;
            try {
                contentType = ContentType.get(httpEntity);
            } catch (UnsupportedCharsetException | org.apache.http.ParseException e) {
                throw new OIDCClientException("Error in setting content type in HTTP response.");
            }
            if (!StandardCharsets.UTF_8.equals(contentType.getCharset())) {
                throw new OIDCClientException("unsupported charset: " + contentType.getCharset());
            }
            if (!ContentType.APPLICATION_JSON.getMimeType().equalsIgnoreCase(contentType.getMimeType())) {
                throw new OIDCClientException("unsupported mime type: " + contentType.getMimeType());
            }
            String content = EntityUtils.toString(httpEntity);
            try {
                jsonContent = JSONUtils.parseJSONObject(content);
            } catch (ParseException e) {
                throw new OIDCClientException("failed to parse json response", e);
            }
        }

        closeableHttpResponse.close();
        client.close();

        return HttpResponse.createJsonResponse(statusCode, jsonContent);
    } catch (IOException e) {
        throw new OIDCClientException("IOException caught in HTTP communication:" + e.getMessage(), e);
    }
}

From source file:io.fabric8.elasticsearch.ElasticsearchIntegrationTest.java

protected String executeSimpleRequest(final String request) throws Exception {

    CloseableHttpClient httpClient = null;
    CloseableHttpResponse response = null;
    try {//ww  w.  j a va  2  s  .com
        httpClient = getHttpClient();
        response = httpClient.execute(new HttpGet(getHttpServerUri() + "/" + request));

        if (response.getStatusLine().getStatusCode() >= 300) {
            throw new Exception("Statuscode " + response.getStatusLine().getStatusCode());
        }

        return IOUtils.toString(response.getEntity().getContent(), StandardCharsets.UTF_8.toString());
    } finally {

        if (response != null) {
            response.close();
        }

        if (httpClient != null) {
            httpClient.close();
        }
    }
}

From source file:edu.kit.dama.rest.dataorganization.services.impl.util.HttpDownloadHandler.java

@Override
public Response prepareStream(URL pUrl) throws IOException {
    try {//  ww w  .  jav  a  2s .c om
        final CloseableHttpClient httpclient = HttpClients.custom()
                .setRedirectStrategy(new LaxRedirectStrategy()) // adds HTTP REDIRECT support to GET and POST methods 
                .build();

        HttpGet httpget = new HttpGet(pUrl.toURI());

        final CloseableHttpResponse response = httpclient.execute(httpget);

        HttpEntity entity = response.getEntity();
        String contentType = entity.getContentType().getValue();
        if (contentType == null) {
            contentType = MediaType.APPLICATION_OCTET_STREAM;
        }

        LOGGER.debug("Using content type '{}' to stream URL content to client.", contentType);
        final InputStream is = entity.getContent();

        final StreamingOutput stream = new StreamingOutput() {
            @Override
            public void write(OutputStream os) throws IOException, WebApplicationException {
                try {
                    byte[] data = new byte[1024];
                    int bytesRead;
                    while ((bytesRead = is.read(data)) != -1) {
                        os.write(data, 0, bytesRead);
                    }
                } finally {
                    response.close();
                    httpclient.close();
                }
            }
        };
        return Response.ok(stream, contentType).build();
    } catch (URISyntaxException ex) {
        throw new IOException("Failed to prepare download stream for URL " + pUrl, ex);
    }
}

From source file:org.jboss.additional.testsuite.jdkall.present.web.servlet.buffersize.ResponseBufferSizeTestCase.java

@Test
@OperateOnDeployment(DEPLOYMENT)//www .  java2s.  c  o  m
public void increaseBufferSizeTest(@ArquillianResource URL url) throws Exception {
    URL testURL = new URL(
            url.toString() + "ResponseBufferSizeServlet?" + ResponseBufferSizeServlet.SIZE_CHANGE_PARAM_NAME
                    + "=1.5" + "&" + ResponseBufferSizeServlet.DATA_LENGTH_IN_PERCENTS_PARAM_NAME + "=0.8"); // more than original size, less than new buffer size

    final HttpGet request = new HttpGet(testURL.toString());
    CloseableHttpClient httpClient = HttpClientBuilder.create().build();
    CloseableHttpResponse response = null;

    try {
        response = httpClient.execute(request);
        Assert.assertEquals("Failed to access " + testURL, HttpURLConnection.HTTP_OK,
                response.getStatusLine().getStatusCode());
        String content = EntityUtils.toString(response.getEntity());
        Assert.assertFalse(content.contains(ResponseBufferSizeServlet.RESPONSE_COMMITED_MESSAGE));
        final Header[] transferEncodingHeaders = response.getHeaders("Transfer-Encoding");
        final Header[] contentLengthHeader = response.getHeaders("Content-Length");

        for (Header transferEncodingHeader : transferEncodingHeaders) {
            Assert.assertNotEquals(
                    "Transfer-Encoding shouldn't be chunked as set BufferSize shouldn't be filled yet, "
                            + "probably caused due https://bugzilla.redhat.com/show_bug.cgi?id=1212566",
                    "chunked", transferEncodingHeader.getValue());
        }

        Assert.assertFalse("Content-Length header not specified", contentLengthHeader.length == 0);
    } finally {
        IOUtils.closeQuietly(response);
        httpClient.close();
    }
}

From source file:org.muhia.app.psi.config.http.CustomHttpClientUtilities.java

public String doGetWithResponseHandler(String url) {
    String result;/*from   ww  w  . j a  va  2 s .  c om*/
    // CloseableHttpResponse response = null;
    CloseableHttpClient client = null;
    try {

        RequestConfig config = RequestConfig.custom().setConnectTimeout(hcp.getConnectionTimeout())
                .setConnectionRequestTimeout(hcp.getConnectionRequestTimeout())
                .setSocketTimeout(hcp.getSockectTimeout()).build();

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

        HttpGet getMethod = new HttpGet(url);

        ResponseHandler<String> responseHandler = (final HttpResponse response) -> {
            int status = response.getStatusLine().getStatusCode();
            if (status >= hcp.getLowerStatusLimit() && status <= hcp.getUpperStatusLimit()) {
                HttpEntity entity = response.getEntity();
                return entity != null ? EntityUtils.toString(entity) : null;
            } else {
                throw new ClientProtocolException(hcp.getExceptionMessage() + status);
            }
        };

        result = client.execute(getMethod, responseHandler);
        client.close();

    } catch (SocketTimeoutException ex) {
        result = hcp.getTimeoutMessage();
        Logger.getLogger(CustomHttpClientUtilities.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        result = hcp.getFailMessage();
        Logger.getLogger(CustomHttpClientUtilities.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        try {
            if (client != null) {
                client.close();
            }

        } catch (IOException ex) {
            Logger.getLogger(CustomHttpClientUtilities.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    return result;
}

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

public IHttpResponse post(String url, ContentType contentType, byte[] content, Header[] headers)
        throws Exception {
    CloseableHttpClient _httpClient = __doBuildHttpClient();
    try {//from   ww  w  .  java  2 s .  c o m
        RequestBuilder _reqBuilder = RequestBuilder.post().setUri(url).setEntity(EntityBuilder.create()
                .setContentEncoding(contentType == null || contentType.getCharset() == null ? DEFAULT_CHARSET
                        : contentType.getCharset().name())
                .setContentType(contentType).setBinary(content).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 {
                return new IHttpResponse.NEW(response);
            }

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

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

public IHttpResponse upload(String url, String fieldName, ContentBody uploadFile, Header[] headers,
        final String defaultResponseCharset) throws Exception {
    CloseableHttpClient _httpClient = __doBuildHttpClient();
    try {/*from  w  ww. j  a v a  2s .c  o  m*/
        RequestBuilder _reqBuilder = RequestBuilder.post().setUri(url)
                .setEntity(MultipartEntityBuilder.create().addPart(fieldName, uploadFile).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();
    }
}