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.SimplifiedQueryRdfXmlTests.java

protected void validateNonEmptyResponse(String query) throws IOException {
    String queryUrl = OSLCUtils.addQueryStringToURL(currentUrl, query);
    HttpResponse response = OSLCUtils.getResponseFromUrl(setupBaseUrl, queryUrl, basicCreds,
            OSLCConstants.CT_RDF, headers);
    assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());

    Model queryModel = ModelFactory.createDefaultModel();
    queryModel.read(response.getEntity().getContent(),
            OSLCUtils.absoluteUrlFromRelative(setupBaseUrl, currentUrl), OSLCConstants.JENA_RDF_XML);
    EntityUtils.consume(response.getEntity());
    RDFUtils.validateModel(queryModel);/*from w  ww  .  jav a  2s.co  m*/

    Resource resultsRes = queryModel.getResource(currentUrl);
    assertTrue("Expected a results resource with URI: " + currentUrl, queryModel.contains(resultsRes, null));

    // oslc:ResponseInfo if optional, validate it if one exists
    Resource respInfoType = queryModel.createResource(OSLCConstants.RESP_INFO_TYPE);
    ResIterator resIter = queryModel.listSubjectsWithProperty(RDF.type, respInfoType);
    while (resIter.hasNext()) {
        Resource responseInfoRes = resIter.nextResource();
        assertEquals("Response info URI should match the request URI (with query parameters)", queryUrl,
                responseInfoRes.getURI());

        Property countMember = queryModel.getProperty(OSLCConstants.TOTAL_COUNT_PROP);
        StmtIterator stmts = responseInfoRes.listProperties(countMember);
        List<?> stmtsList = stmts.toList();
        if (!stmtsList.isEmpty()) {
            Statement stmt = (Statement) stmtsList.get(0);
            assertTrue("Expected oslc:totalCount property", stmtsList.size() == 1);
            int totalCount = Integer.parseInt(stmt.getObject().toString());
            assertTrue("Expected oslc:totalCount > 0", totalCount > 0);
        }

        stmts = queryModel.listStatements(resultsRes, RDFS.member, (RDFNode) null);
        stmtsList = stmts.toList();
        assertNotNull("Expected > 1 rdfs:member(s)", stmtsList.size() > 0);
    }
}

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

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

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

    LOG.info("Connecting to " + uri.toString());

    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.getJudges().size(), 4);
        for (Judge j : doc.getJudges()) {
            if (j.getId().equals(TestFixture.INSTANCE.judgeAndy.getId())) {
                testEquality(j, TestFixture.INSTANCE.judgeAndy);
            } else if (j.getId().equals(TestFixture.INSTANCE.judgeBob.getId())) {
                testEquality(j, TestFixture.INSTANCE.judgeBob);
            } else if (j.getId().equals(TestFixture.INSTANCE.judgeEoin.getId())) {
                testEquality(j, TestFixture.INSTANCE.judgeEoin);
            } else if (j.getId().equals(TestFixture.INSTANCE.judgeJamie.getId())) {
                testEquality(j, TestFixture.INSTANCE.judgeJamie);
            } else {
                fail();/*from  w w  w. j  av  a 2s  .c  o m*/
            }
        }

        EntityUtils.consume(entity);
    }
}

From source file:brooklyn.networking.cloudstack.HttpUtil.java

public static HttpToolResponse httpGet(HttpClient httpClient, URI uri, Multimap<String, String> headers) {
    HttpGet httpGet = new HttpGet(uri);
    for (Map.Entry<String, String> entry : headers.entries()) {
        httpGet.addHeader(entry.getKey(), entry.getValue());
    }/*ww  w.  java  2 s  . c  om*/

    long startTime = System.currentTimeMillis();
    try {
        HttpResponse httpResponse = httpClient.execute(httpGet);
        try {
            return new HttpToolResponse(httpResponse, startTime);
        } finally {
            EntityUtils.consume(httpResponse.getEntity());
        }
    } catch (Exception e) {
        throw Exceptions.propagate(e);
    }
}

From source file:com.sap.dirigible.runtime.scripting.HttpUtils.java

public void consume(HttpEntity entity) throws IOException {
    EntityUtils.consume(entity);
}

From source file:org.jboss.as.test.integration.web.security.form.WebSecurityFORMTestCase.java

protected void makeCall(String user, String pass, int expectedStatusCode) throws Exception {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    try {// ww  w. j  av a2s .c o m
        String req = url.toExternalForm() + "secured/";
        HttpGet httpget = new HttpGet(req);

        HttpResponse response = httpclient.execute(httpget);

        HttpEntity entity = response.getEntity();
        if (entity != null)
            EntityUtils.consume(entity);

        // We should get the Login Page
        StatusLine statusLine = response.getStatusLine();
        System.out.println("Login form get: " + statusLine);
        assertEquals(200, statusLine.getStatusCode());

        System.out.println("Initial set of cookies:");
        List<Cookie> cookies = httpclient.getCookieStore().getCookies();
        if (cookies.isEmpty()) {
            System.out.println("None");
        } else {
            for (int i = 0; i < cookies.size(); i++) {
                System.out.println("- " + cookies.get(i).toString());
            }
        }
        req = url.toExternalForm() + "secured/j_security_check";
        // We should now login with the user name and password
        HttpPost httpPost = new HttpPost(req);

        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("j_username", user));
        nvps.add(new BasicNameValuePair("j_password", pass));

        httpPost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));

        response = httpclient.execute(httpPost);
        entity = response.getEntity();
        if (entity != null)
            EntityUtils.consume(entity);

        statusLine = response.getStatusLine();

        // Post authentication - we have a 302
        assertEquals(302, statusLine.getStatusCode());
        Header locationHeader = response.getFirstHeader("Location");
        String location = locationHeader.getValue();

        HttpGet httpGet = new HttpGet(location);
        response = httpclient.execute(httpGet);

        entity = response.getEntity();
        if (entity != null)
            EntityUtils.consume(entity);

        System.out.println("Post logon cookies:");
        cookies = httpclient.getCookieStore().getCookies();
        if (cookies.isEmpty()) {
            System.out.println("None");
        } else {
            for (int i = 0; i < cookies.size(); i++) {
                System.out.println("- " + cookies.get(i).toString());
            }
        }

        // Either the authentication passed or failed based on the expected status code
        statusLine = response.getStatusLine();
        assertEquals(expectedStatusCode, statusLine.getStatusCode());
    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();
    }
}

From source file:cn.geowind.takeout.verify.JsonRestApi.java

public String sendCall(String accountSid, String authToken, String appId, String to, String verifyCode)
        throws KeyManagementException, NoSuchAlgorithmException {
    String result = "";
    CcopHttpClient chc = new CcopHttpClient();
    DefaultHttpClient httpclient = chc.registerSSL("sandboxapp.cloopen.com", "TLS", 8883, "https");
    try {//from w w w. j  a va  2  s  .c o m
        // URL
        String timestamp = DateUtil.dateToStr(new Date(), DateUtil.DATE_TIME_NO_SLASH);
        // md5(Id + ? + )
        String sig = accountSid + authToken + timestamp;
        // MD5
        EncryptUtil eu = new EncryptUtil();
        String signature = eu.md5Digest(sig);

        StringBuffer sb = new StringBuffer();
        String url = sb.append(TEST_SMS_BASE_URL).append(SMS_VERSION).append("/Accounts/").append(accountSid)
                .append("/Calls").append("/VoiceVerify").append("?sig=").append(signature).toString();
        // HttpPost
        HttpPost httppost = new HttpPost(url);
        setHttpHeader(httppost);
        String src = accountSid + ":" + timestamp;
        String auth = eu.base64Encoder(src);
        httppost.setHeader("Authorization", auth);// base64(Id + ? +
        // )
        JSONObject obj = new JSONObject();
        obj.put("to", to);
        obj.put("appId", appId);
        obj.put("verifyCode", verifyCode);
        obj.put("playTimes", "3");
        String data = obj.toString();

        System.out.println("---------------------------- SendSMS for JSON begin----------------------------");
        System.out.println("data: " + data);

        BasicHttpEntity requestBody = new BasicHttpEntity();
        requestBody.setContent(new ByteArrayInputStream(data.getBytes("UTF-8")));
        requestBody.setContentLength(data.getBytes("UTF-8").length);
        httppost.setEntity(requestBody);

        // 
        HttpResponse response = httpclient.execute(httppost);

        // ???
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            result = EntityUtils.toString(entity, "UTF-8");
        }
        // ?HTTP??
        EntityUtils.consume(entity);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        // 
        httpclient.getConnectionManager().shutdown();
    }
    // ???
    return result;
}

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

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

    URI uri = new URIBuilder().setScheme(PROTOCOL).setHost(HOST).setPort(PORT).setPath(PATH)
            .setParameter("season", Integer.toString(TestFixture.INSTANCE.roster1.getSeason())).build();

    LOG.info("Connecting to " + uri.toString());

    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.getRosters().size(), 2);
        for (Roster r : doc.getRosters()) {
            if (r.getVersion() == TestFixture.INSTANCE.roster1.getVersion()) {
                testEquality(r, TestFixture.INSTANCE.roster1);
            } else if (r.getVersion() == TestFixture.INSTANCE.roster2.getVersion()) {
                testEquality(r, TestFixture.INSTANCE.roster2);
            } else {
                fail();//from w  w  w  . ja  va  2  s  . c  om
            }
        }

        EntityUtils.consume(entity);
    }
}

From source file:com.vmware.gemfire.tools.pulse.tests.junit.MemberGatewayHubServiceTest.java

/**
 * Tests that service returns json object
 *
 *//*  ww  w.  j av  a 2s  .c  o  m*/
@Test
public void testResponseNotNull() {
    System.out.println(
            "MemberGatewayHubServiceTest ::  ------TESTCASE BEGIN : NULL RESPONSE CHECK FOR MEMBER GATEWAY HUB SERVICE --------");
    if (httpclient != null) {
        try {
            HttpUriRequest pulseupdate = RequestBuilder.post().setUri(new URI(PULSE_UPDATE_URL))
                    .addParameter(PULSE_UPDATE_PARAM, PULSE_UPDATE_5_VALUE).build();
            CloseableHttpResponse response = httpclient.execute(pulseupdate);
            try {
                HttpEntity entity = response.getEntity();

                System.out.println(
                        "MemberGatewayHubServiceTest :: HTTP request status : " + response.getStatusLine());
                BufferedReader respReader = new BufferedReader(new InputStreamReader(entity.getContent()));
                StringWriter sw = new StringWriter();
                PrintWriter pw = new PrintWriter(sw);
                String sz = null;
                while ((sz = respReader.readLine()) != null) {
                    pw.print(sz);
                }
                String jsonResp = sw.getBuffer().toString();
                System.out.println("MemberGatewayHubServiceTest :: JSON response returned : " + jsonResp);
                EntityUtils.consume(entity);

                JSONObject jsonObj = new JSONObject(jsonResp);
                Assert.assertNotNull(
                        "MemberGatewayHubServiceTest :: Server returned null response for MemberGatewayHub",
                        jsonObj.getJSONObject("MemberGatewayHub"));
            } finally {
                response.close();
            }
        } catch (Exception failed) {
            logException(failed);
            Assert.fail("Exception ! ");
        }
    } else {
        Assert.fail("MemberGatewayHubServiceTest :: No Http connection was established.");
    }
    System.out.println(
            "MemberGatewayHubServiceTest ::  ------TESTCASE END : NULL RESPONSE CHECK FOR MEMBER GATEWAY HUB SERVICE ------\n");
}

From source file:org.obiba.opal.rest.client.magma.RestDatasource.java

@NotNull
@Override/*from  w  w w . j a  v a  2  s.  c  o m*/
public ValueTableWriter createWriter(@NotNull String tableName, @NotNull String entityType) {
    if (!hasValueTable(tableName)) {
        URI tableUri = newReference("tables");
        try {
            HttpResponse response = getOpalClient().post(tableUri,
                    TableDto.newBuilder().setName(tableName).setEntityType(entityType).build());
            if (response.getStatusLine().getStatusCode() != HttpStatus.SC_CREATED) {
                throw new RuntimeException("cannot create table " + response.getStatusLine().getReasonPhrase());
            }
            addValueTable(tableName);
            EntityUtils.consume(response.getEntity());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    return new RestValueTableWriter((RestValueTable) getValueTable(tableName));
}

From source file:org.eclipse.lyo.testsuite.server.oslcv1tests.ServiceDescriptionTests.java

public static Collection<Object[]> getReferencedUrls(String base)
        throws IOException, XPathException, ParserConfigurationException, SAXException {
    Properties setupProps = SetupProperties.setup(null);
    String userId = setupProps.getProperty("userId");
    String pw = setupProps.getProperty("pw");

    HttpResponse resp = OSLCUtils.getResponseFromUrl(base, base, new UsernamePasswordCredentials(userId, pw),
            OSLCConstants.CT_DISC_CAT_XML + ", " + OSLCConstants.CT_DISC_DESC_XML);

    //If our 'base' is a ServiceDescription we don't need to recurse as this is the only one we can find
    if (resp.getEntity().getContentType().getValue().contains(OSLCConstants.CT_DISC_DESC_XML)) {
        Collection<Object[]> data = new ArrayList<Object[]>();
        data.add(new Object[] { base });
        EntityUtils.consume(resp.getEntity());
        return data;
    }/*w ww. j av a  2s  . c  o  m*/

    Document baseDoc = OSLCUtils.createXMLDocFromResponseBody(EntityUtils.toString(resp.getEntity()));

    //ArrayList to contain the urls from all SPCs
    Collection<Object[]> data = new ArrayList<Object[]>();

    //Get all the ServiceDescriptionDocuments from this ServiceProviderCatalog
    NodeList sDescs = (NodeList) OSLCUtils.getXPath().evaluate("//oslc_disc:services/@rdf:resource", baseDoc,
            XPathConstants.NODESET);
    for (int i = 0; i < sDescs.getLength(); i++) {
        String uri = sDescs.item(i).getNodeValue();
        uri = OSLCUtils.absoluteUrlFromRelative(base, uri);
        data.add(new Object[] { uri });
    }

    //Get all ServiceProviderCatalog urls from the base document in order to recursively add all the
    //description documents from them as well.
    NodeList spcs = (NodeList) OSLCUtils.getXPath().evaluate(
            "//oslc_disc:entry/oslc_disc:ServiceProviderCatalog/@rdf:about", baseDoc, XPathConstants.NODESET);
    for (int i = 0; i < spcs.getLength(); i++) {
        String uri = spcs.item(i).getNodeValue();
        uri = OSLCUtils.absoluteUrlFromRelative(base, uri);
        if (!uri.equals(base)) {
            Collection<Object[]> subCollection = getReferencedUrls(uri);
            Iterator<Object[]> iter = subCollection.iterator();
            while (iter.hasNext()) {
                data.add(iter.next());
            }
        }
    }
    return data;
}