Example usage for org.apache.http.util EntityUtils consume

List of usage examples for org.apache.http.util EntityUtils consume

Introduction

In this page you can find the example usage for org.apache.http.util EntityUtils consume.

Prototype

public static void consume(HttpEntity httpEntity) throws IOException 

Source Link

Usage

From source file:org.eclipse.lyo.testsuite.oslcv2.CoreResourceXmlTests.java

@Parameters
protected static Collection<Object[]> getAllDescriptionUrls(String eval)
        throws IOException, ParserConfigurationException, SAXException, XPathException {
    ArrayList<String> results = new ArrayList<String>();

    //Checks the ServiceProviderCatalog at the specified baseUrl of the REST service in order to grab all urls
    //to other ServiceProvidersCatalogs contained within it, recursively, in order to find the URLs of all
    //query factories of the REST service.

    String v = "//oslc_v2:QueryCapability/oslc_v2:queryBase/@rdf:resource";

    ArrayList<String> serviceUrls = getServiceProviderURLsUsingXML(null);
    ArrayList<String> capabilityURLsUsingXML = TestsBase.getCapabilityURLsUsingXML(v, getxpathSubStmt(),
            getResourceTypeQuery(), serviceUrls, true);

    // Once we have the query URL, look for a resource to validate
    String where = setupProps.getProperty("changeRequestsWhere");
    if (where == null) {
        String queryProperty = setupProps.getProperty("queryEqualityProperty");
        String queryPropertyValue = setupProps.getProperty("queryEqualityValue");
        where = queryProperty + "=\"" + queryPropertyValue + "\"";
    }//from  w  ww. j  ava2s  .  co m

    String additionalParameters = setupProps.getProperty("queryAdditionalParameters", "");
    String query = (additionalParameters.length() == 0) ? "?" : "?" + additionalParameters + "&";
    query = query + "oslc.where=" + URLEncoder.encode(where, "UTF-8") + "&oslc.pageSize=1";

    for (String queryBase : capabilityURLsUsingXML) {
        String queryUrl = OSLCUtils.addQueryStringToURL(queryBase, query);
        HttpResponse resp = OSLCUtils.getResponseFromUrl(setupBaseUrl, queryUrl, creds, OSLCConstants.CT_XML,
                headers);
        String respBody = EntityUtils.toString(resp.getEntity());
        EntityUtils.consume(resp.getEntity());
        assertTrue("Received " + resp.getStatusLine(),
                (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK));

        //Get XML Doc from response
        Document doc = OSLCUtils.createXMLDocFromResponseBody(respBody);

        //Check for results by reference (rdf:resource)
        Node result = (Node) OSLCUtils.getXPath().evaluate(eval, doc, XPathConstants.NODE);

        if (result == null)
            //No results by reference. Check for inline results (rdf:about)
            result = (Node) OSLCUtils.getXPath().evaluate("//rdfs:member/oslc_cm_v2:ChangeRequest/@rdf:about",
                    doc, XPathConstants.NODE);
        if (result != null)
            results.add(result.getNodeValue());
        if (onlyOnce)
            break;
    }

    return toCollection(results);
}

From source file:org.openstack.burrow.backend.http.BaseHttp.java

/**
 * Processes an HttpResponse. First gets all necessary information from the
 * response's JSONObject and then builds the List of Accounts
 * /*www.  java2 s. c om*/
 * @param response An HttpResponse from the server that should contain
 *          requested Accounts
 * @return A List of Accounts requested
 * @throws HttpProtocolException Thrown if an issue with processes
 *           HttpResponse occurs
 * @throws AccountNotFoundException Thrown if the requested Account was not
 *           found
 */
static List<Account> handleMultipleAccountHttpResponse(HttpResponse response)
        throws HttpProtocolException, AccountNotFoundException {
    StatusLine status = response.getStatusLine();
    HttpEntity entity = response.getEntity();
    if (entity == null)
        return null; // Is this actually the right thing to do?
    String mimeType = EntityUtils.getContentMimeType(entity);
    switch (status.getStatusCode()) {
    case SC_OK:
        if (mimeType.equals("application/json")) {
            try {
                String body = EntityUtils.toString(entity);
                JSONArray arrayJson = new JSONArray(body);
                List<Account> accounts = new ArrayList<Account>(arrayJson.length());
                try {
                    // Assume the response is an array of JSON Objects.
                    for (int idx = 0; idx < arrayJson.length(); idx++) {
                        JSONObject accountJson = arrayJson.getJSONObject(idx);
                        Account account = new AccountResponse(accountJson);
                        accounts.add(idx, account);
                    }
                } catch (JSONException e) {
                    // The response was not an array of JSON Objects. Try again,
                    // assuming it was an array of strings.
                    for (int idx = 0; idx < arrayJson.length(); idx++) {
                        String accountId = arrayJson.getString(idx);
                        Account account = new AccountResponse(accountId);
                        accounts.add(idx, account);
                    }
                }
                return accounts;
            } catch (IOException e) {
                try {
                    // Consume the entity to release HttpClient resources.
                    EntityUtils.consume(entity);
                } catch (IOException e1) {
                    // If we ever stop throwing an exception in the outside block,
                    // this needs to be handled.
                }
                throw new HttpProtocolException("IOException reading http response");
            } catch (JSONException e) {
                // It is not necessary to consume the entity because at the
                // first point where this exception can be thrown,
                // the entity has already been consumed by toString();
                throw new HttpProtocolException("JSONException reading response");
            }
        } else {
            // This situation cannot be handled.
            try {
                // Consume the entity to release HttpClient resources.
                EntityUtils.consume(entity);
            } catch (IOException e1) {
                // If we ever stop throwing an exception in the outside block,
                // this needs to be handled.
            }
            throw new HttpProtocolException("Non-Json response");
        }
    case SC_NOT_FOUND:
        try {
            // Consume the entity to release HttpClient resources.
            EntityUtils.consume(entity);
        } catch (IOException e1) {
            // If we ever stop throwing an exception in the outside block,
            // this needs to be handled.
        }
        throw new AccountNotFoundException("No accounts found");
    default:
        // This is probably an error.
        try {
            // Consume the entity to release HttpClient resources.
            EntityUtils.consume(entity);
        } catch (IOException e1) {
            // If we ever stop throwing an exception in the outside block,
            // this needs to be handled.
        }
        throw new HttpProtocolException("Unhandled http response code " + status.getStatusCode());
    }
}

From source file:org.wuspba.ctams.ws.ITSoloResultController.java

@Test
public void testListContest() throws Exception {
    CloseableHttpClient httpclient = HttpClients.createDefault();

    URI uri = new URIBuilder().setScheme(PROTOCOL).setHost(HOST).setPort(PORT).setPath(PATH)
            .setParameter("contest", TestFixture.INSTANCE.soloContest.getId()).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);

        assertEquals(doc.getSoloContestResults().size(), 1);
        testEquality(doc.getSoloContestResults().get(0), TestFixture.INSTANCE.soloResult);

        EntityUtils.consume(entity);
    }/*  ww w .jav a  2 s.  c o  m*/

    uri = new URIBuilder().setScheme(PROTOCOL).setHost(HOST).setPort(PORT).setPath(PATH)
            .setParameter("contest", TestFixture.INSTANCE.soloNonContest.getId()).build();

    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);

        assertEquals(doc.getSoloContestResults().size(), 0);

        EntityUtils.consume(entity);
    }
}

From source file:com.github.parisoft.resty.entity.EntityReaderImpl.java

@Override
public <T> T getEntityAs(TypeReference<T> reference) throws IOException {
    if (body != null) {
        return getEntityFromBodyAs(reference);
    }/*from w  ww  .  j  a v a  2  s. c o m*/

    final HttpEntity entity = httpResponse.getEntity();

    if (entity == null) {
        return null;
    }

    try {
        final HttpEntity entityWrapper = isGzipEncoding() ? new GzipDecompressingEntity(entity) : entity;

        return JacksonUtils.read(entityWrapper, reference, MediaTypeUtils.valueOf(getContentType()));
    } catch (Exception e) {
        throw new IOException("Cannot read response entity", e);
    } finally {
        EntityUtils.consume(entity);
    }
}

From source file:com.github.matthesrieke.simplebroker.AbstractConsumer.java

@Override
public synchronized void consume(String cotent, ContentType contentType, String origin) {
    for (String url : getTargetUrls()) {
        HttpPost post = new HttpPost(url);

        post.setEntity(createEntity(cotent, contentType));
        HttpResponse response = null;// ww w . j a  v a  2 s .c om
        try {
            response = this.client.execute(post);
            logger.info("Content posted to " + url);
        } catch (ClientProtocolException e) {
            logger.warn(e.getMessage(), e);
        } catch (IOException e) {
            logger.warn(e.getMessage(), e);
        } finally {
            if ((response != null) && (response.getEntity() != null))
                try {
                    EntityUtils.consume(response.getEntity());
                } catch (IOException e) {
                    logger.warn(e.getMessage(), e);
                }
        }
    }
}

From source file:org.wuspba.ctams.ws.ITBandController.java

@Test
public void testListName() throws Exception {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    URI uri = new URIBuilder().setScheme(PROTOCOL).setHost(HOST).setPort(PORT).setPath(PATH)
            .setParameter("name", SKYE.getName()).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);

        assertEquals(doc.getBands().size(), 1);
        assertTrue(doc.getBands().get(0).getName().equals(TestFixture.INSTANCE.skye.getName()));

        EntityUtils.consume(entity);
    }//from  w ww . j  a  v a  2  s .com

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

    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);

        assertEquals(doc.getBands().size(), 0);

        EntityUtils.consume(entity);
    }
}

From source file:de.bytefish.fcmjava.client.http.apache.DefaultHttpClient.java

private <TRequestMessage, TResponseMessage> TResponseMessage internalPost(TRequestMessage requestMessage,
        Class<TResponseMessage> responseType) throws IOException {

    // Execute the Request:
    try (CloseableHttpResponse response = client.execute(buildPostRequest(requestMessage))) {

        // Evaluate the Response:
        evaluateResponse(response);//w  w w  .  j a  va 2  s . co  m

        // Get the HttpEntity of the Response:
        HttpEntity entity = response.getEntity();

        // If we don't have a HttpEntity, we won't be able to convert it:
        if (entity == null) {
            // Simply return null (no response) in this case:
            return null;
        }

        // Get the JSON Body:
        String responseBody = EntityUtils.toString(entity);

        // Make Sure it is fully consumed:
        EntityUtils.consume(entity);

        // And finally return the Response Message:
        return serializer.deserialize(responseBody, responseType);
    }
}

From source file:org.wuspba.ctams.ws.ITBandRegistrationController.java

@Test
public void testListBand() throws Exception {
    CloseableHttpClient httpclient = HttpClients.createDefault();

    URI uri = new URIBuilder().setScheme(PROTOCOL).setHost(HOST).setPort(PORT).setPath(PATH)
            .setParameter("band", TestFixture.INSTANCE.skye.getId()).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);

        assertEquals(doc.getBandRegistrations().size(), 1);
        testEquality(doc.getBandRegistrations().get(0), TestFixture.INSTANCE.bandRegistration);

        EntityUtils.consume(entity);
    }/*from w w  w . ja  v a  2s  .c o m*/

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

    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);

        assertEquals(doc.getBandRegistrations().size(), 0);

        EntityUtils.consume(entity);
    }
}

From source file:org.wuspba.ctams.ws.ITSoloRegistrationController.java

@Test
public void testListPerson() throws Exception {
    CloseableHttpClient httpclient = HttpClients.createDefault();

    URI uri = new URIBuilder().setScheme(PROTOCOL).setHost(HOST).setPort(PORT).setPath(PATH)
            .setParameter("person", TestFixture.INSTANCE.elaine.getId()).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);

        assertEquals(doc.getSoloRegistrations().size(), 1);
        testEquality(doc.getSoloRegistrations().get(0), TestFixture.INSTANCE.soloRegistration);

        EntityUtils.consume(entity);
    }//w w  w.java2 s  . co m

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

    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);

        assertEquals(doc.getSoloRegistrations().size(), 0);

        EntityUtils.consume(entity);
    }
}

From source file:controller.NavigatorServlet.java

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    System.out.println(request.getParameterMap().toString());
    String page = request.getParameter("page");
    String type = request.getParameter("type");

    System.out.println(page);//from  www .  jav a  2s  .  c o  m
    System.out.println(type);
    CloseableHttpClient httpClient = HttpClients.createDefault();
    String address = "http://127.0.0.1:8080";
    HttpPost httpPost;
    List<NameValuePair> nvps = new ArrayList<NameValuePair>();
    if (type.equalsIgnoreCase("GetPage")) {
        switch (page) {

        case "LogIn":
            address += "/CloudChatUserManagerClient/loginPage.html";
            break;
        case "LogOut":
            address += "/CloudChatUserManagerClient/logoutConfirm.html";
            break;
        case "LogInSuccess":
            address += "/CloudChatUserManagerClient/loginSuccessPage.html";
            break;
        case "Register":
            System.out.println("Got here");
            address += "/CloudChatUserManagerClient/registrationPage.html";
            break;
        case "Edit":
            address += "/CloudChatServer/edit.jsp";
            break;
        case "Delete":
            address += "/CloudChatServer/delete.jsp";
            break;
        case "ChatHome":
            address += "/CloudChatServer/chat.jsp";
            break;
        default:
            address = "";
            break;
        }
    } else if (type.equalsIgnoreCase("UserManager")) {
        address += "/CloudChatUserManagerClient/CloudChatUserManagerServlet";
        nvps.add(new BasicNameValuePair("action", request.getParameter("action")));
        nvps.add(new BasicNameValuePair("userID", request.getParameter("userID")));
        nvps.add(new BasicNameValuePair("password", request.getParameter("password")));
    } else if (type.equalsIgnoreCase("Server")) {
        System.out.println("Got here");
        address += "/CloudChatServer/chat";
        nvps.add(new BasicNameValuePair("userID", request.getParameter("userID")));
        nvps.add(new BasicNameValuePair("action", request.getParameter("action")));
        nvps.add(new BasicNameValuePair("messageID", request.getParameter("messageID")));
        nvps.add(new BasicNameValuePair("message", request.getParameter("message")));
        nvps.add(new BasicNameValuePair("category", request.getParameter("category")));
    }
    httpPost = new HttpPost(address);
    httpPost.setEntity(new UrlEncodedFormEntity(nvps));
    CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
    try {
        System.out.println(httpResponse.getStatusLine());
        HttpEntity entity = httpResponse.getEntity();
        BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent()));
        String line;
        String res = "";
        while ((line = reader.readLine()) != null) {
            res += line;
        }
        EntityUtils.consume(entity);
        response.getWriter().write(res);
    } finally {
        httpResponse.close();
    }
}