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:ar.edu.ubp.das.src.chat.actions.DashboardAction.java

@Override
public ForwardConfig execute(ActionMapping mapping, DynaActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws SQLException, RuntimeException {
    try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
        String url = "http://25.136.78.82:8080/salas";
        HttpGet getRequest = new HttpGet(url);
        String authToken = String.valueOf(request.getSession().getAttribute("token"));

        getRequest.addHeader("Authorization", "BEARER " + authToken);
        getRequest.addHeader("accept", "application/json; charset=ISO-8859-1");

        CloseableHttpResponse getResponse = httpClient.execute(getRequest);
        HttpEntity responseEntity = getResponse.getEntity();
        StatusLine responseStatus = getResponse.getStatusLine();
        String restResp = EntityUtils.toString(responseEntity);

        if (responseStatus.getStatusCode() != 200) {
            throw new RuntimeException(restResp);
        }/*from   w ww. j av a 2  s .c  o m*/

        Gson gson = new Gson();
        Type listType = new TypeToken<LinkedList<SalaBean>>() {
        }.getType();
        List<SalaBean> salas = gson.fromJson(restResp, listType);
        request.getSession().setAttribute("salas", salas);
        return mapping.getForwardByName("success");

    } catch (IOException | RuntimeException e) {
        request.setAttribute("message", "Error al intentar listar Salas " + e.getMessage());
        response.setStatus(400);
        return mapping.getForwardByName("failure");
    }
}

From source file:org.activiti.rest.dmn.service.api.repository.DecisionTableResourceTest.java

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

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

    HttpGet httpGet = new HttpGet(SERVER_URL_PREFIX
            + DmnRestUrls.createRelativeResourceUrl(DmnRestUrls.URL_DECISION_TABLE, decisionTable.getId()));
    CloseableHttpResponse response = executeRequest(httpGet, HttpStatus.SC_OK);
    JsonNode responseNode = objectMapper.readTree(response.getEntity().getContent());
    closeResponse(response);//  w ww  .  j  av  a2  s.c  o  m
    assertEquals(decisionTable.getId(), responseNode.get("id").textValue());
    assertEquals(decisionTable.getKey(), responseNode.get("key").textValue());
    assertEquals(decisionTable.getCategory(), responseNode.get("category").textValue());
    assertEquals(decisionTable.getVersion(), responseNode.get("version").intValue());
    assertEquals(decisionTable.getDescription(), responseNode.get("description").textValue());
    assertEquals(decisionTable.getName(), responseNode.get("name").textValue());

    // Check URL's
    assertEquals(httpGet.getURI().toString(), responseNode.get("url").asText());
    assertEquals(decisionTable.getDeploymentId(), responseNode.get("deploymentId").textValue());
}

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

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

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

    HttpGet httpGet = new HttpGet(SERVER_URL_PREFIX
            + DmnRestUrls.createRelativeResourceUrl(DmnRestUrls.URL_DECISION_TABLE, decisionTable.getId()));
    CloseableHttpResponse response = executeRequest(httpGet, HttpStatus.SC_OK);
    JsonNode responseNode = objectMapper.readTree(response.getEntity().getContent());
    closeResponse(response);//from  www  .  j  a v a  2s. co  m
    assertEquals(decisionTable.getId(), responseNode.get("id").textValue());
    assertEquals(decisionTable.getKey(), responseNode.get("key").textValue());
    assertEquals(decisionTable.getCategory(), responseNode.get("category").textValue());
    assertEquals(decisionTable.getVersion(), responseNode.get("version").intValue());
    assertEquals(decisionTable.getDescription(), responseNode.get("description").textValue());
    assertEquals(decisionTable.getName(), responseNode.get("name").textValue());

    // Check URL's
    assertEquals(httpGet.getURI().toString(), responseNode.get("url").asText());
    assertEquals(decisionTable.getDeploymentId(), responseNode.get("deploymentId").textValue());
}

From source file:jatoo.weather.openweathermap.JaTooWeatherOpenWeatherMap.java

@Override
protected final String getJSONResponse(final String city) throws IOException {

    CloseableHttpClient client = HttpClientBuilder.create().setSSLHostnameVerifier(new NoopHostnameVerifier())
            .build();// w ww  .j a  v  a 2  s  .  c  om
    HttpGet request = new HttpGet(URL_CURRENT_WEATHER + "?appid=" + appid + "&id=" + city + "&units=metric");
    CloseableHttpResponse response = client.execute(request);
    BufferedHttpEntity entity = new BufferedHttpEntity(response.getEntity());

    return EntityUtils.toString(entity, "UTF-8");
}

From source file:org.activiti.rest.dmn.service.api.repository.DecisionTableResourceDataResourceTest.java

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

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

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

    // Check "OK" status
    String content = IOUtils.toString(response.getEntity().getContent());
    closeResponse(response);/* ww  w  .  java 2s  . c  o m*/
    assertNotNull(content);
    assertTrue(content.contains("Full Decision"));
}

From source file:org.callimachusproject.client.AutoClosingHttpClient.java

@Override
protected CloseableHttpResponse doExecute(final HttpHost host, final HttpRequest request, HttpContext ctx)
        throws IOException, ClientProtocolException {
    if (++numberOfClientCalls % 100 == 0) {
        // Deletes the (no longer used) temporary cache files from disk.
        cleanResources();/*www. j a va  2 s.co m*/
    }
    CloseableHttpResponse resp = client.execute(host, request, ctx);
    HttpEntity entity = resp.getEntity();
    if (entity != null) {
        resp.setEntity(new CloseableEntity(entity, new Closeable() {
            public void close() throws IOException {
                // this also keeps this object from being finalized
                // until all its response entities are consumed
                String uri = request.getRequestLine().getUri();
                logger.debug("Remote {}{} closed", host, uri);
            }
        }));
    }
    return resp;
}

From source file:ar.edu.ubp.das.src.chat.actions.EliminarMensajeAction.java

@Override
public ForwardConfig execute(ActionMapping mapping, DynaActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws SQLException, RuntimeException {
    try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {

        //get request data
        String id_mensaje = form.getItem("id_mensaje");
        String authToken = String.valueOf(request.getSession().getAttribute("token"));

        URIBuilder builder = new URIBuilder();
        builder.setScheme("http").setHost("25.136.78.82").setPort(8080).setPath("/mensajes/" + id_mensaje);

        HttpDelete delete = new HttpDelete();
        delete.setURI(builder.build());//from  ww w  .ja v  a 2  s .c  o  m
        delete.addHeader("Authorization", "BEARER " + authToken);
        delete.addHeader("accept", "application/json");

        CloseableHttpResponse deleteResponse = httpClient.execute(delete);

        HttpEntity responseEntity = deleteResponse.getEntity();
        StatusLine responseStatus = deleteResponse.getStatusLine();
        String restResp = EntityUtils.toString(responseEntity);

        if (responseStatus.getStatusCode() != 200) {
            throw new RuntimeException(restResp);
        }

        return mapping.getForwardByName("success");

    } catch (IOException | URISyntaxException | RuntimeException e) {
        String id_mensaje = form.getItem("id_mensaje");
        request.setAttribute("message",
                "Error al intentar eliminar mensaje " + id_mensaje + "; " + e.getMessage());
        response.setStatus(400);
        return mapping.getForwardByName("failure");
    }
}

From source file:edu.mit.scratch.ScratchStatistics.java

protected static JSONObject getStatisticsJSONObject() throws ScratchStatisticalException {
    try {//from www  . j  a v a  2s. co m
        final RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.DEFAULT).build();

        final CookieStore cookieStore = new BasicCookieStore();
        final BasicClientCookie lang = new BasicClientCookie("scratchlanguage", "en");
        final BasicClientCookie debug = new BasicClientCookie("DEBUG", "true");
        debug.setDomain(".scratch.mit.edu");
        debug.setPath("/");
        lang.setDomain(".scratch.mit.edu");
        lang.setPath("/");
        cookieStore.addCookie(debug);
        cookieStore.addCookie(lang);

        final CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(globalConfig)
                .setUserAgent(Scratch.USER_AGENT).setDefaultCookieStore(cookieStore).build();
        CloseableHttpResponse resp;

        final HttpUriRequest update = RequestBuilder.get()
                .setUri("https://scratch.mit.edu/statistics/data/daily/")
                .addHeader("Accept",
                        "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8")
                .addHeader("Referer", "https://scratch.mit.edu").addHeader("Origin", "https://scratch.mit.edu")
                .addHeader("Accept-Encoding", "gzip, deflate, sdch")
                .addHeader("Accept-Language", "en-US,en;q=0.8").addHeader("Content-Type", "application/json")
                .addHeader("X-Requested-With", "XMLHttpRequest").build();
        try {
            resp = httpClient.execute(update);
        } catch (final IOException e) {
            e.printStackTrace();
            throw new ScratchStatisticalException();
        }

        BufferedReader rd;
        try {
            rd = new BufferedReader(new InputStreamReader(resp.getEntity().getContent()));
        } catch (UnsupportedOperationException | IOException e) {
            e.printStackTrace();
            throw new ScratchStatisticalException();
        }

        final StringBuffer result = new StringBuffer();
        String line = "";
        while ((line = rd.readLine()) != null)
            result.append(line);
        return new JSONObject(result.toString().trim());
    } catch (final UnsupportedEncodingException e) {
        e.printStackTrace();
        throw new ScratchStatisticalException();
    } catch (final Exception e) {
        e.printStackTrace();
        throw new ScratchStatisticalException();
    }
}

From source file:org.activiti.rest.dmn.service.api.repository.DmnDeploymentResourceDataResourceTest.java

public void testGetDmnDeploymentResource() throws Exception {

    try {// w w w .  j  a v  a2s  .c o m
        DmnDeployment deployment = dmnRepositoryService.createDeployment().name("Deployment 1")
                .addInputStream("test.txt", new ByteArrayInputStream("Test content".getBytes())).deploy();

        HttpGet httpGet = new HttpGet(SERVER_URL_PREFIX + DmnRestUrls.createRelativeResourceUrl(
                DmnRestUrls.URL_DEPLOYMENT_RESOURCE_CONTENT, deployment.getId(), "test.txt"));
        httpGet.addHeader(new BasicHeader(HttpHeaders.ACCEPT, "text/plain"));
        CloseableHttpResponse response = executeRequest(httpGet, HttpStatus.SC_OK);
        String responseAsString = IOUtils.toString(response.getEntity().getContent());
        closeResponse(response);
        assertNotNull(responseAsString);
        assertEquals("Test content", responseAsString);
    } finally {
        // Always cleanup any created deployments, even if the test failed
        List<DmnDeployment> deployments = dmnRepositoryService.createDeploymentQuery().list();
        for (DmnDeployment deployment : deployments) {
            dmnRepositoryService.deleteDeployment(deployment.getId());
        }
    }
}

From source file:org.jboss.pnc.integration.BuildTasksRestTest.java

private String printEntity(CloseableHttpResponse response) throws IOException {
    InputStream stream = response.getEntity().getContent();
    return IOUtils.toString(stream);
}