Example usage for org.apache.http.entity BasicHttpEntity setContent

List of usage examples for org.apache.http.entity BasicHttpEntity setContent

Introduction

In this page you can find the example usage for org.apache.http.entity BasicHttpEntity setContent.

Prototype

public void setContent(InputStream inputStream) 

Source Link

Usage

From source file:es.tid.fiware.rss.oauth.test.ResponseHandlerTest.java

/**
 * /*from w w w .  j  a v a 2 s  . c o  m*/
 */
@Test
public void handleResponseTest() throws Exception {
    ResponseHandler handler = new ResponseHandler();
    HttpResponseFactory factory = new DefaultHttpResponseFactory();
    HttpResponse responseSent = factory
            .newHttpResponse(new BasicStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "reason"), null);
    HttpResponse response = handler.handleResponse(responseSent);
    Assert.assertEquals(handler.getStatus(), HttpStatus.SC_OK);
    Assert.assertFalse(handler.hasContent());
    // response with content.
    BasicHttpEntity entity = new BasicHttpEntity();
    InputStream inputStream = new ByteArrayInputStream("new content".getBytes());
    entity.setContent(inputStream);
    entity.setContentLength("new content".length()); // sets the length
    response.setEntity(entity);
    response = handler.handleResponse(responseSent);
    Assert.assertEquals("new content", handler.getResponseContent());
}

From source file:com.vsct.dt.strowgr.admin.repository.consul.ConsulReaderTest.java

@Test
public void should_throw_exception_when_status_out_of_range_200_299() {
    for (int status = 100; status < 600; status++) {
        if (status >= 200 && status < 300)
            continue; // skip
        // given//  w w  w .  j  a  va 2s.co  m
        HttpResponse httpResponse = mock(HttpResponse.class);
        when(httpResponse.getStatusLine())
                .thenReturn(new BasicStatusLine(new ProtocolVersion("http1.1", 1, 1), status, ""));
        BasicHttpEntity givenHttpEntity = new BasicHttpEntity();
        givenHttpEntity.setContent(new ByteArrayInputStream("".getBytes(StandardCharsets.UTF_8)));
        when(httpResponse.getEntity()).thenReturn(givenHttpEntity);

        // test
        try {
            new ConsulReader(null).parseHttpResponse(httpResponse, this::getHttpEntity);
            // check
            fail("can't reach this point for status " + status);
        } catch (ClientProtocolException e) {
            // check
            assertThat(e.getMessage()).contains(String.valueOf(status));
        }
    }
}

From source file:com.aerofs.baseline.json.TestJSONHandling.java

@Test
public void shouldReceiveErrorOnMakingPostWithInvalidJsonObject()
        throws ExecutionException, InterruptedException, JsonProcessingException {
    // noinspection ConstantConditions
    String serialized = mapper.writeValueAsString(new JsonObject(null, "allen")); // yes; I know I'm using 'null'
    ByteArrayInputStream contentInputStream = new ByteArrayInputStream(serialized.getBytes(Charsets.US_ASCII));
    BasicHttpEntity entity = new BasicHttpEntity();
    entity.setContent(contentInputStream);

    HttpPost post = new HttpPost(ServiceConfiguration.SERVICE_URL + "/consumer");
    post.setHeader(new BasicHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON));
    post.setEntity(entity);/*from  w  w  w  .j  a v a 2 s. co  m*/

    Future<HttpResponse> future = client.getClient().execute(post, null);
    HttpResponse response = future.get();
    assertThat(response.getStatusLine().getStatusCode(), equalTo(HttpStatus.SC_BAD_REQUEST));
}

From source file:com.aerofs.baseline.json.TestJSONHandling.java

@Test
public void shouldSuccessfullyProcessJson() throws ExecutionException, InterruptedException, IOException {
    JsonObject value = new JsonObject("unhappy", "allen");

    String serialized = mapper.writeValueAsString(value);
    ByteArrayInputStream contentInputStream = new ByteArrayInputStream(serialized.getBytes(Charsets.US_ASCII));
    BasicHttpEntity entity = new BasicHttpEntity();
    entity.setContent(contentInputStream);

    HttpPost post = new HttpPost(ServiceConfiguration.SERVICE_URL + "/consumer");
    post.setHeader(new BasicHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON));
    post.setEntity(entity);//  w  w  w .  j av  a 2s. c  o  m

    Future<HttpResponse> future = client.getClient().execute(post, null);
    HttpResponse response = future.get();
    assertThat(response.getStatusLine().getStatusCode(), equalTo(HttpStatus.SC_OK));
    assertThat(HttpUtils.readStreamToString(response.getEntity().getContent()),
            equalTo(getResponseValue(value)));
}

From source file:org.aerogear.android.impl.core.HttpRestProvider.java

private void addBodyRequest(HttpEntityEnclosingRequestBase requestBase, String data) {
    BasicHttpEntity entity = new BasicHttpEntity();
    entity.setContent(new ByteArrayInputStream(data.getBytes()));
    requestBase.setEntity(entity);/*from   ww  w.j a  v  a 2  s  .c  o  m*/
}

From source file:org.dataconservancy.dcs.ingest.client.impl.SwordClientManager.java

public DepositInfo deposit(InputStream content, String contentType, String packaging,
        Map<String, String> metadata) throws PackageException {

    if (metadata == null) {
        metadata = new HashMap<String, String>();
    }/*from w  w w  . j av  a  2s  .c  om*/

    HttpPost post = new HttpPost(collectionUrl);
    for (Map.Entry<String, String> val : metadata.entrySet()) {
        if (!val.getKey().equals(HttpHeaderUtil.CONTENT_LENGTH)) {
            post.setHeader(val.getKey(), val.getValue());
        }
    }

    post.setHeader(HttpHeaderUtil.CONTENT_TYPE, contentType);
    if (packaging != null) {
        post.setHeader(PACKAGING, packaging);
    }

    if (!metadata.containsKey(HttpHeaderUtil.CONTENT_LENGTH)) {
        BasicHttpEntity entity = new BasicHttpEntity();
        entity.setContent(content);
        post.setEntity(entity);
    } else {
        post.setEntity(new InputStreamEntity(content, new Long(metadata.get(HttpHeaderUtil.CONTENT_LENGTH))));
    }

    return execute(post);
}

From source file:com.nexmo.client.voice.endpoints.ListCallsMethodTest.java

@Test
public void parseResponse() throws Exception {
    HttpResponse stubResponse = new BasicHttpResponse(
            new BasicStatusLine(new ProtocolVersion("1.1", 1, 1), 200, "OK"));

    String json = "{\n" + "  \"page_size\": 10,\n" + "  \"record_index\": 0,\n" + "  \"count\": 2,\n"
            + "  \"_embedded\": {\n" + "    \"calls\": [\n" + "      {\n"
            + "        \"uuid\": \"93137ee3-580e-45f7-a61a-e0b5716000ef\",\n"
            + "        \"status\": \"completed\",\n" + "        \"direction\": \"outbound\",\n"
            + "        \"rate\": \"0.02400000\",\n" + "        \"price\": \"0.00280000\",\n"
            + "        \"duration\": \"7\",\n" + "        \"network\": \"23410\",\n"
            + "        \"conversation_uuid\": \"aa17bd11-c895-4225-840d-30dc38c31e50\",\n"
            + "        \"start_time\": \"2017-01-13T13:55:02.000Z\",\n"
            + "        \"end_time\": \"2017-01-13T13:55:09.000Z\",\n" + "        \"to\": {\n"
            + "          \"type\": \"phone\",\n" + "          \"number\": \"447700900104\"\n" + "        },\n"
            + "        \"from\": {\n" + "          \"type\": \"phone\",\n"
            + "          \"number\": \"447700900105\"\n" + "        },\n" + "        \"_links\": {\n"
            + "          \"self\": {\n"
            + "            \"href\": \"/v1/calls/93137ee3-580e-45f7-a61a-e0b5716000ef\"\n" + "          }\n"
            + "        }\n" + "      },\n" + "      {\n"
            + "        \"uuid\": \"105e02df-940a-466c-b28b-51ae015a9166\",\n"
            + "        \"status\": \"completed\",\n" + "        \"direction\": \"outbound\",\n"
            + "        \"rate\": \"0.02400000\",\n" + "        \"price\": \"0.00280000\",\n"
            + "        \"duration\": \"7\",\n" + "        \"network\": \"23410\",\n"
            + "        \"conversation_uuid\": \"1467b438-f5a8-4937-9a65-e1f946a2f664\",\n"
            + "        \"start_time\": \"2017-01-11T15:03:46.000Z\",\n"
            + "        \"end_time\": \"2017-01-11T15:03:53.000Z\",\n" + "        \"to\": {\n"
            + "          \"type\": \"phone\",\n" + "          \"number\": \"447700900104\"\n" + "        },\n"
            + "        \"from\": {\n" + "          \"type\": \"phone\",\n"
            + "          \"number\": \"447700900105\"\n" + "        },\n" + "        \"_links\": {\n"
            + "          \"self\": {\n"
            + "            \"href\": \"/v1/calls/105e02df-940a-466c-b28b-51ae015a9166\"\n" + "          }\n"
            + "        }\n" + "      }\n" + "    ]\n" + "  },\n" + "  \"_links\": {\n" + "    \"self\": {\n"
            + "      \"href\": \"/v1/calls?page_size=10&record_index=0\"\n" + "    },\n" + "    \"first\": {\n"
            + "      \"href\": \"/v1/calls?page_size=10\"\n" + "    },\n" + "    \"last\": {\n"
            + "      \"href\": \"/v1/calls?page_size=10\"\n" + "    }\n" + "  }\n" + "}\n";
    InputStream jsonStream = new ByteArrayInputStream(json.getBytes(StandardCharsets.UTF_8));
    BasicHttpEntity entity = new BasicHttpEntity();
    entity.setContent(jsonStream);
    stubResponse.setEntity(entity);/*w  w  w . j a  va  2 s  .c o  m*/

    CallInfoPage page = method.parseResponse(stubResponse);
    assertEquals(2, page.getCount());
    assertEquals(2, page.getEmbedded().getCallInfos().length);
    assertEquals("/v1/calls?page_size=10", page.getLinks().getFirst().getHref());
    assertEquals("/v1/calls?page_size=10", page.getLinks().getLast().getHref());
}

From source file:org.apache.synapse.samples.framework.clients.BasicHttpClient.java

/**
 * Make a HTTP POST request on the specified URL.
 *
 * @param url A valid HTTP URL/*from   w w  w . j av a  2  s  .c o m*/
 * @param payload An array of bytes to be posted to the URL (message body)
 * @param contentType Content type of the message body
 * @param headers A map of HTTP headers to be set on the outgoing request
 * @return A HttpResponse object
 * @throws Exception If an error occurs while making the HTTP call
 */
public HttpResponse doPost(String url, byte[] payload, String contentType, Map<String, String> headers)
        throws Exception {
    CloseableHttpClient client = HttpClientBuilder.create().build();
    try {
        HttpPost post = new HttpPost(url);
        if (headers != null) {
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                post.setHeader(entry.getKey(), entry.getValue());
            }
        }
        BasicHttpEntity entity = new BasicHttpEntity();
        entity.setContentType(contentType);
        entity.setContent(new ByteArrayInputStream(payload));
        post.setEntity(entity);
        return new HttpResponse(client.execute(post));
    } finally {
        client.close();
    }
}

From source file:org.fcrepo.integration.generator.DublinCoreGeneratorIT.java

@Test
public void testJcrPropertiesBasedOaiDc() throws Exception {
    final int status = getStatus(postObjMethod("DublinCoreTest1"));
    assertEquals(201, status);/*  w  w  w  .j a  va  2s  .c  o m*/
    final HttpPatch post = new HttpPatch(serverAddress + "DublinCoreTest1");
    post.setHeader("Content-Type", "application/sparql-update");
    final BasicHttpEntity entity = new BasicHttpEntity();
    final String subjectURI = serverAddress + "DublinCoreTest1";
    entity.setContent(new ByteArrayInputStream(("INSERT { <" + subjectURI
            + "> <http://purl.org/dc/elements/1.1/identifier> \"this is an identifier\" } WHERE {}")
                    .getBytes()));
    post.setEntity(entity);
    assertEquals(204, getStatus(post));
    final HttpGet getWorstCaseOaiMethod = new HttpGet(serverOAIAddress + "DublinCoreTest1/oai:dc");
    getWorstCaseOaiMethod.setHeader("Accept", TEXT_XML);
    final HttpResponse response = client.execute(getWorstCaseOaiMethod);

    assertEquals(200, response.getStatusLine().getStatusCode());

    final String content = EntityUtils.toString(response.getEntity());
    logger.debug("Got content: {}", content);
    assertTrue("Didn't find oai_dc!", compile("oai_dc", DOTALL).matcher(content).find());

    assertTrue("Didn't find dc:identifier!", compile("dc:identifier", DOTALL).matcher(content).find());
}

From source file:org.fcrepo.integration.FedoraTransformIT.java

@Test
public void testLdpathWithProgramBody() throws Exception {

    final Session session = repo.login();
    objectService.createObject(session, "/ldpathTestObject");
    session.save();/*from  w ww  .ja v a 2  s.c  om*/
    session.logout();

    HttpPost postLdpathProgramRequest = new HttpPost(serverAddress + "/ldpathTestObject/fcr:transform");
    BasicHttpEntity e = new BasicHttpEntity();

    String s = "id      = . :: xsd:string ;\n";

    e.setContent(new ByteArrayInputStream(s.getBytes()));

    postLdpathProgramRequest.setEntity(e);
    postLdpathProgramRequest.setHeader("Content-Type", LDPathTransform.APPLICATION_RDF_LDPATH);
    HttpResponse response = client.execute(postLdpathProgramRequest);
    assertEquals(200, response.getStatusLine().getStatusCode());
    String content = EntityUtils.toString(response.getEntity());
    logger.debug("Retrieved ldpath feed:\n" + content);

    JsonFactory jsonFactory = new JsonFactory();

    ObjectMapper mapper = new ObjectMapper();
    final JsonParser jsonParser = jsonFactory.createJsonParser(content);

    JsonNode rootNode = mapper.readTree(jsonParser);

    assertEquals(serverAddress + "/ldpathTestObject", rootNode.get(0).get("id").getElements().next().asText());

}