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

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

Introduction

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

Prototype

public BasicHttpEntity() 

Source Link

Usage

From source file:common.net.volley.toolbox.HurlStack.java

/**
 * Initializes an {@link org.apache.http.HttpEntity} from the given {@link java.net.HttpURLConnection}.
 * @param connection//from   w  w w .j  a  v  a 2s . co  m
 * @return an HttpEntity populated with data from <code>connection</code>.
 */
private static HttpEntity entityFromConnection(HttpURLConnection connection) throws IOException {
    BasicHttpEntity entity = new BasicHttpEntity();

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    InputStream rawStream = null;
    try {
        rawStream = connection.getInputStream();

        rawStream = stethoManager.interpretResponseStream(rawStream);
        InputStream decompressedStream = applyDecompressionIfApplicable(connection, rawStream);
        if (decompressedStream != null) {
            copy(decompressedStream, out, new byte[1024]);
        }
        entity.setContent(new ByteArrayInputStream(out.toByteArray()));

    } catch (IOException ioe) {
        rawStream = connection.getErrorStream();
        entity.setContent(rawStream);

    } finally {
        //            if(rawStream != null) {
        //                rawStream.close();
        //            }
    }

    entity.setContentLength(connection.getContentLength());
    entity.setContentEncoding(connection.getContentEncoding());
    entity.setContentType(connection.getContentType());
    return entity;
}

From source file:org.apache.hadoop.gateway.dispatch.PartiallyRepeatableHttpEntityTest.java

@Test
public void testS_C1_FC_IB__C2_FC_IB() throws IOException {
    String data = "0123456789";
    BasicHttpEntity basic;//from w  w w.  ja va 2s  .c  o m
    PartiallyRepeatableHttpEntity replay;

    basic = new BasicHttpEntity();
    basic.setContent(new ByteArrayInputStream(data.getBytes("UTF-8")));
    replay = new PartiallyRepeatableHttpEntity(basic, 20);

    String output;

    output = byteRead(replay.getContent(), -1);
    assertThat(output, is(data));

    output = byteRead(replay.getContent(), -1);
    assertThat(output, is(data));
}

From source file:org.apache.hadoop.gateway.dispatch.CappedBufferHttpEntityTest.java

@Test
public void testS_C1_FC_IB__C2_FC_IB() throws IOException {
    String data = "0123456789";
    BasicHttpEntity basic;/*from ww  w.j a v  a 2 s. com*/
    CappedBufferHttpEntity replay;

    basic = new BasicHttpEntity();
    basic.setContent(new ByteArrayInputStream(data.getBytes("UTF-8")));
    replay = new CappedBufferHttpEntity(basic, 20);

    String output;

    output = byteRead(replay.getContent(), -1);
    assertThat(output, is(data));

    output = byteRead(replay.getContent(), -1);
    assertThat(output, is(data));
}

From source file:com.kubeiwu.commontool.khttp.toolbox.HurlStack.java

/**
 * Initializes an {@link HttpEntity} from the given {@link HttpURLConnection}.
 * /* w w w. j  a  va2s.  com*/
 * @param connection
 * @return an HttpEntity populated with data from <code>connection</code>.
 */
private static HttpEntity entityFromConnection(HttpURLConnection connection) {

    BasicHttpEntity entity = new BasicHttpEntity();
    InputStream inputStream;
    try {
        inputStream = connection.getInputStream();
    } catch (IOException ioe) {
        inputStream = connection.getErrorStream();
    }
    entity.setContent(inputStream);
    entity.setContentLength(connection.getContentLength());
    entity.setContentEncoding(connection.getContentEncoding());
    entity.setContentType(connection.getContentType());
    return entity;
}

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

@Test
public void testParseResponse() throws Exception {
    HttpWrapper wrapper = new HttpWrapper();
    CreateCallMethod methodUnderTest = new CreateCallMethod(wrapper);

    HttpResponse stubResponse = new BasicHttpResponse(
            new BasicStatusLine(new ProtocolVersion("1.1", 1, 1), 200, "OK"));

    String json = " {\"uuid\":\"93137ee3-580e-45f7-a61a-e0b5716000ea\",\"status\":\"started\",\"direction\":\"outbound\",\"conversation_uuid\":\"aa17bd11-c895-4225-840d-30dc78c31e50\"}";
    InputStream jsonStream = new ByteArrayInputStream(json.getBytes(StandardCharsets.UTF_8));
    BasicHttpEntity entity = new BasicHttpEntity();
    entity.setContent(jsonStream);//from  w  ww . j  av  a 2 s  .c o m
    stubResponse.setEntity(entity);

    // Execute test call:
    CallEvent callEvent = methodUnderTest.parseResponse(stubResponse);
    assertEquals("93137ee3-580e-45f7-a61a-e0b5716000ea", callEvent.getUuid());
    assertEquals("aa17bd11-c895-4225-840d-30dc78c31e50", callEvent.getConversationUuid());
    assertEquals(CallStatus.STARTED, callEvent.getStatus());
    assertEquals(CallDirection.OUTBOUND, callEvent.getDirection());
}

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);/*  www.  ja 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_OK));
    assertThat(HttpUtils.readStreamToString(response.getEntity().getContent()),
            equalTo(getResponseValue(value)));
}

From source file:org.apache.nifi.processors.aws.wag.TestInvokeAmazonGatewayApiMock.java

@Test
public void testSendAttributes() throws Exception {

    HttpResponse resp = new BasicHttpResponse(new BasicStatusLine(HttpVersion.HTTP_1_1, 200, "OK"));
    BasicHttpEntity entity = new BasicHttpEntity();
    entity.setContent(new ByteArrayInputStream("test payload".getBytes()));
    resp.setEntity(entity);//from  w  w  w .  j a v a 2s . c  om
    Mockito.doReturn(resp).when(mockSdkClient).execute(any(HttpUriRequest.class), any(HttpContext.class));

    // add dynamic property
    runner.setProperty("dynamicHeader", "yes!");
    // set the regex
    runner.setProperty(InvokeAWSGatewayApi.PROP_ATTRIBUTES_TO_SEND, "F.*");

    final Map<String, String> attributes = new HashMap<>();
    attributes.put(CoreAttributes.MIME_TYPE.key(), "application/plain-text");
    attributes.put("Foo", "Bar");
    runner.enqueue("Hello".getBytes("UTF-8"), attributes);
    // execute
    runner.assertValid();
    runner.run(1);

    Mockito.verify(mockSdkClient, times(1)).execute(argThat(new RequestMatcher<HttpUriRequest>(x -> {
        return x.getMethod().equals("GET") && x.getFirstHeader("x-api-key").getValue().equals("abcd")
                && x.getFirstHeader("Authorization").getValue().startsWith("AWS4")
                && x.getFirstHeader("dynamicHeader").getValue().equals("yes!")
                && x.getFirstHeader("Foo").getValue().equals("Bar")
                && x.getURI().toString().equals("https://foobar.execute-api.us-east-1.amazonaws.com/TEST");
    })), any(HttpContext.class));
    // check
    runner.assertTransferCount(InvokeAWSGatewayApi.REL_SUCCESS_REQ, 1);
    runner.assertTransferCount(InvokeAWSGatewayApi.REL_RESPONSE, 1);
    runner.assertTransferCount(InvokeAWSGatewayApi.REL_RETRY, 0);
    runner.assertTransferCount(InvokeAWSGatewayApi.REL_NO_RETRY, 0);
    runner.assertTransferCount(InvokeAWSGatewayApi.REL_FAILURE, 0);

    final List<MockFlowFile> flowFiles = runner.getFlowFilesForRelationship(InvokeAWSGatewayApi.REL_RESPONSE);
    final MockFlowFile ff0 = flowFiles.get(0);

    ff0.assertAttributeEquals(InvokeAWSGatewayApi.STATUS_CODE, "200");
    ff0.assertContentEquals("test payload");
    ff0.assertAttributeExists(InvokeAWSGatewayApi.TRANSACTION_ID);
    ff0.assertAttributeEquals(InvokeAWSGatewayApi.RESOURCE_NAME_ATTR, "/TEST");
}

From source file:org.fiware.apps.repository.it.IntegrationTestHelper.java

public HttpResponse putResourceContent(String resourceId, String resourceContent, List<Header> headers)
        throws IOException {
    String finalURL = collectionServiceUrl + resourceId;
    HttpPut request = new HttpPut(finalURL);

    //Add Headers
    for (Header header : headers) {
        request.setHeader(header);/*ww w  .ja v  a2  s .c  o m*/
    }

    //Add Entity
    BasicHttpEntity entity = new BasicHttpEntity();
    InputStream stream = new ByteArrayInputStream(resourceContent.getBytes());

    entity.setContent(stream);
    request.setEntity(entity);

    HttpResponse response = client.execute(request);
    request.releaseConnection();
    return response;
}

From source file:org.qucosa.camel.component.sword.SwordConnection.java

public HttpResponse update(String pid, SwordDeposit deposit, Boolean noop, String onBehalfOfHeader)
        throws Exception {
    URIBuilder uriBuilder = new URIBuilder(url + "/" + deposit.getCollection() + "/" + pid);
    HttpPut httpPut = new HttpPut(uriBuilder.build());
    httpPut.setHeader("X-No-Op", String.valueOf(noop));
    httpPut.setHeader("Content-Type", deposit.getContentType());

    if (onBehalfOfHeader != null && !onBehalfOfHeader.isEmpty()) {
        httpPut.setHeader("X-On-Behalf-Of", onBehalfOfHeader);
    }/*from  ww  w . j av  a  2 s.c o  m*/

    BasicHttpEntity httpEntity = new BasicHttpEntity();
    httpEntity.setContent(toInputStream(deposit.getBody()));
    httpEntity.setContentType(deposit.getContentType());
    httpPut.setEntity(new BufferedHttpEntity(httpEntity));

    HttpResponse response = httpClient.execute(httpPut);
    EntityUtils.consume(response.getEntity());

    if (log.isDebugEnabled()) {
        if (noop) {
            log.debug("SWORD parameter 'X-No-Op' is '{}'", noop);
            log.debug("SWORD parameter 'X-On-Behalf-Of' is '{}'", onBehalfOfHeader);
            log.debug("Content type is '{}'", deposit.getContentType());
            log.debug("Posting to SWORD collection '{}'", deposit.getCollection());
        }
        log.debug(response.toString());
    }

    if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
        String reason = response.getStatusLine().getReasonPhrase();
        throw new Exception(reason);
    }

    return response;
}