Example usage for org.apache.http.client.methods CloseableHttpResponse getEntity

List of usage examples for org.apache.http.client.methods CloseableHttpResponse getEntity

Introduction

In this page you can find the example usage for org.apache.http.client.methods CloseableHttpResponse getEntity.

Prototype

HttpEntity getEntity();

Source Link

Usage

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

@Override
public Response prepareStream(URL pUrl) throws IOException {
    try {/* w  w w .j a v a 2s . com*/
        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.wuspba.ctams.ws.ITRosterController.java

protected static void delete() throws Exception {
    List<String> ids = new ArrayList<>();

    CloseableHttpClient httpclient = HttpClients.createDefault();

    URI uri = new URIBuilder().setScheme(PROTOCOL).setHost(HOST).setPort(PORT).setPath(PATH).build();

    HttpGet httpGet = new HttpGet(uri);

    try (CloseableHttpResponse response = httpclient.execute(httpGet)) {
        assertEquals(response.getStatusLine().toString(), IntegrationTestUtils.OK_STRING);

        HttpEntity entity = response.getEntity();

        CTAMSDocument doc = IntegrationTestUtils.convertEntity(entity);

        for (Roster r : doc.getRosters()) {
            ids.add(r.getId());//w  ww  . j av  a2  s  .com
        }

        EntityUtils.consume(entity);
    }

    for (String id : ids) {
        httpclient = HttpClients.createDefault();

        uri = new URIBuilder().setScheme(PROTOCOL).setHost(HOST).setPort(PORT).setPath(PATH)
                .setParameter("id", id).build();

        HttpDelete httpDelete = new HttpDelete(uri);

        CloseableHttpResponse response = null;

        try {
            response = httpclient.execute(httpDelete);

            assertEquals(IntegrationTestUtils.OK_STRING, response.getStatusLine().toString());

            HttpEntity responseEntity = response.getEntity();

            EntityUtils.consume(responseEntity);
        } catch (UnsupportedEncodingException ex) {
            LOG.error("Unsupported coding", ex);
        } catch (IOException ioex) {
            LOG.error("IOException", ioex);
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException ex) {
                    LOG.error("Could not close response", ex);
                }
            }
        }
    }

    ITBandRegistrationController.delete();
    ITBandMemberController.delete();
}

From source file:HelloWorld.BaseTest.java

public <T> T responseToEntity(CloseableHttpResponse response, Class<T> type) throws IOException {
    Gson gson = new GsonBuilder().setDateFormat("MM/dd/yyyy").create();
    return gson.fromJson(EntityUtils.toString(response.getEntity(), "UTF-8"), type);
}

From source file:org.flowable.rest.dmn.service.api.repository.DecisionTableModelResourceTest.java

@DmnDeploymentAnnotation(resources = { "org/flowable/rest/dmn/service/api/repository/simple.dmn" })
public void testGetDecisionTableModel() throws Exception {

    DmnDecisionTable decisionTable = dmnRepositoryService.createDecisionTableQuery().singleResult();

    HttpGet httpGet = new HttpGet(SERVER_URL_PREFIX + DmnRestUrls
            .createRelativeResourceUrl(DmnRestUrls.URL_DECISION_TABLE_MODEL, decisionTable.getId()));
    CloseableHttpResponse response = executeRequest(httpGet, HttpStatus.SC_OK);

    // Check "OK" status
    JsonNode resultNode = objectMapper.readTree(response.getEntity().getContent());
    closeResponse(response);//  w  ww .  j a  v a 2s  .c  o m
    assertNotNull(resultNode);
    JsonNode firstDecision = resultNode.get("decisions").get(0);
    assertNotNull(firstDecision);

    JsonNode decisionTableNode = firstDecision.get("expression");
    assertEquals("decisionTable", decisionTableNode.get("id").textValue());
}

From source file:com.ccc.crest.servlet.auth.CrestAuthCallback.java

private void getVerifyData(Base20ClientInfo clientInfo) throws Exception {
    Properties properties = CoreController.getController().getProperties();
    String verifyUrl = properties.getProperty(CrestController.OauthVerifyUrlKey,
            CrestController.OauthVerifyUrlDefault);
    String userAgent = properties.getProperty(CrestController.UserAgentKey, CrestController.UserAgentDefault);
    //@formatter:off
    CloseableHttpClient httpclient = HttpClients.custom().setUserAgent(userAgent).build();
    //@formatter:on

    String accessToken = ((OAuth2AccessToken) clientInfo.getAccessToken()).getAccessToken();
    HttpGet httpGet = new HttpGet(verifyUrl);
    httpGet.addHeader("Authorization", "Bearer " + accessToken);
    CloseableHttpResponse response1 = httpclient.execute(httpGet);
    try {//w  ww  .  j  av a 2  s  . c  o  m
        HttpEntity entity1 = response1.getEntity();
        InputStream is = entity1.getContent();
        String json = IOUtils.toString(is, "UTF-8");
        is.close();
        ((CrestClientInfo) clientInfo).setVerifyData(OauthVerify.getOauthVerifyData(json));
        EntityUtils.consume(entity1);
    } finally {
        response1.close();
    }
}

From source file:com.tremolosecurity.unison.proxy.auth.openidconnect.loadUser.LoadAttributesFromWS.java

public Map loadUserAttributesFromIdP(HttpServletRequest request, HttpServletResponse response,
        ConfigManager cfg, HashMap<String, Attribute> authParams, Map accessToken) throws Exception {
    String bearerTokenName = authParams.get("bearerTokenName").getValues().get(0);
    String url = authParams.get("restURL").getValues().get(0);

    BasicHttpClientConnectionManager bhcm = new BasicHttpClientConnectionManager(
            GlobalEntries.getGlobalEntries().getConfigManager().getHttpClientSocketRegistry());
    RequestConfig rc = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build();
    CloseableHttpClient http = HttpClients.custom().setConnectionManager(bhcm).setDefaultRequestConfig(rc)
            .build();/*from ww  w .  j  a v  a 2 s .  c  om*/

    HttpGet get = new HttpGet(url);

    get.addHeader("Authorization", "Bearer " + request.getSession().getAttribute(bearerTokenName));

    CloseableHttpResponse httpResp = http.execute(get);

    BufferedReader in = new BufferedReader(new InputStreamReader(httpResp.getEntity().getContent()));

    StringBuffer token = new StringBuffer();

    String line = null;
    while ((line = in.readLine()) != null) {
        token.append(line);
    }

    httpResp.close();
    bhcm.close();

    Map jwtNVP = com.cedarsoftware.util.io.JsonReader.jsonToMaps(token.toString());

    return jwtNVP;

}

From source file:org.elasticsearch.river.solr.support.SolrIndexer.java

public void indexDocuments(Map<String, Map<String, Object>> documents) throws IOException {
    StringBuilder jsonBuilder = new StringBuilder("[");
    int i = 0;/*from   w  w w.ja  va 2s .c  o m*/
    for (Map<String, Object> doc : documents.values()) {
        jsonBuilder.append(objectMapper.writeValueAsString(doc));

        if (i < documents.values().size() - 1) {
            jsonBuilder.append(",");
        }
        i++;
    }
    jsonBuilder.append("]");

    HttpPost httpPost = new HttpPost(solrUrl + "?commit=true");
    httpPost.setHeader("Content-type", "application/json");
    httpPost.setEntity(new StringEntity(jsonBuilder.toString()));

    CloseableHttpResponse response = httpClient.execute(httpPost);
    try {
        EntityUtils.consume(response.getEntity());
        if (response.getStatusLine().getStatusCode() != 200) {
            throw new RuntimeException("documents were not properly indexed");
        }
    } finally {
        EntityUtils.consume(response.getEntity());
        response.close();
    }
}

From source file:org.activiti.rest.content.service.api.content.ContentItemResourceTest.java

public void testGetContentItem() throws Exception {
    String contentItemId = createContentItem("test.pdf", "application/pdf", null, "12345", null, "test",
            "test2");

    ContentItem contentItem = contentService.createContentItemQuery().singleResult();

    try {/*from   www .  j  a v  a 2s  .c o  m*/
        HttpGet httpGet = new HttpGet(SERVER_URL_PREFIX
                + ContentRestUrls.createRelativeResourceUrl(ContentRestUrls.URL_CONTENT_ITEM, contentItemId));
        CloseableHttpResponse response = executeRequest(httpGet, HttpStatus.SC_OK);
        JsonNode responseNode = objectMapper.readTree(response.getEntity().getContent());
        closeResponse(response);

        assertEquals(contentItem.getId(), responseNode.get("id").asText());
        assertEquals(contentItem.getName(), responseNode.get("name").asText());
        assertEquals(contentItem.getMimeType(), responseNode.get("mimeType").asText());
        assertTrue(responseNode.get("taskId").isNull());
        assertEquals(contentItem.getProcessInstanceId(), responseNode.get("processInstanceId").asText());
        assertEquals("", responseNode.get("tenantId").asText());
        assertEquals(contentItem.getCreatedBy(), responseNode.get("createdBy").asText());
        assertEquals(contentItem.getLastModifiedBy(), responseNode.get("lastModifiedBy").asText());
        assertEquals(contentItem.getCreated(), getDateFromISOString(responseNode.get("created").asText()));
        assertEquals(contentItem.getLastModified(),
                getDateFromISOString(responseNode.get("lastModified").asText()));

        // Check URL's
        assertEquals(httpGet.getURI().toString(), responseNode.get("url").asText());

    } finally {
        contentService.deleteContentItem(contentItemId);
    }
}

From source file:org.jboss.quickstarts.wfk.travelagent.flight.FlightService.java

/**
 * <p>Returns a List of all persisted {@link Contact} objects, sorted alphabetically by last name.<p/>
 * //w ww.  jav a2s .  c  om
 * @return List of Contact objects
 */
JSONArray findAllOrderedByName() {
    try {
        URI uri = new URIBuilder().setScheme("http").setHost("jbosscontactsangularjs-110336260.rhcloud.com")
                .setPath("/rest/flights").build();
        HttpGet req = new HttpGet(uri);
        CloseableHttpResponse response = httpClient.execute(req);
        String responseBody = EntityUtils.toString(response.getEntity());
        JSONArray responseJson = new JSONArray(responseBody);

        HttpClientUtils.closeQuietly(response);
        return responseJson;
    } catch (Exception e) {
        log.info(e.toString());
        return null;
    }
}