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:com.cloud.cluster.ClusterServiceServletHttpHandler.java

private void writeResponse(HttpResponse response, int statusCode, String content) {
    if (content == null) {
        content = "";
    }/*from  www  .  j  av a2 s  .co m*/
    response.setStatusCode(statusCode);
    BasicHttpEntity body = new BasicHttpEntity();
    body.setContentType("text/html; charset=UTF-8");

    byte[] bodyData = content.getBytes();
    body.setContent(new ByteArrayInputStream(bodyData));
    body.setContentLength(bodyData.length);
    response.setEntity(body);
}

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

@Test
public void testS__C1_FC_OB() throws IOException {
    String data = "0123456789";
    BasicHttpEntity basic;/*from   ww w.j  a v a 2 s.c o m*/
    PartiallyRepeatableHttpEntity replay;

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

    String output;

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

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

private void checkValidStatus(int status, boolean with404) throws ClientProtocolException {
    // given/*www .  j a v  a  2  s .c  o  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);
    Optional<HttpEntity> httpEntity;

    // test
    if (with404) {
        httpEntity = new ConsulReader(null).parseHttpResponseAccepting404(httpResponse, this::getHttpEntity);
    } else {
        httpEntity = new ConsulReader(null).parseHttpResponse(httpResponse, this::getHttpEntity);
    }

    // check
    if (with404 && status == 404) {
        assertThat(httpEntity).isNotNull();
        assertThat(httpEntity.isPresent()).isFalse();
    } else {
        assertThat(httpEntity.isPresent()).as("for status " + status).isTrue();
        assertThat(httpEntity.orElseGet(() -> null)).as("for status " + status).isEqualTo(givenHttpEntity);
    }
}

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

public HttpResponse postResourceMeta(String collectionsId, String resource, List<Header> headers)
        throws IOException {
    String finalURL = collectionServiceUrl + collectionsId;
    HttpPost request = new HttpPost(finalURL);

    //Add Headers
    for (Header header : headers) {
        request.setHeader(header);//from  w  w w . j av  a 2 s  .c  om
    }

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

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

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

From source file:com.ksc.http.KscHttpClientTest.java

@SuppressWarnings({ "unchecked", "deprecation" })
@Test/* w  w w  .j  a v a 2  s.com*/
public void testRetryIOExceptionFromHandler() throws Exception {
    final IOException exception = new IOException("BOOM");

    HttpResponseHandler<KscWebServiceResponse<Object>> handler = EasyMock.createMock(HttpResponseHandler.class);

    EasyMock.expect(handler.needsConnectionLeftOpen()).andReturn(false).anyTimes();

    EasyMock.expect(handler.handle(EasyMock.<HttpResponse>anyObject())).andThrow(exception).times(2);

    EasyMock.replay(handler);

    BasicHttpEntity entity = new BasicHttpEntity();
    entity.setContent(new ByteArrayInputStream(new byte[0]));

    BasicHttpResponse response = new BasicHttpResponse(new ProtocolVersion("http", 1, 1), 200, "OK");
    response.setEntity(entity);

    EasyMock.reset(httpClient);

    EasyMock.expect(httpClient.getConnectionManager()).andReturn(null).anyTimes();

    EasyMock.expect(httpClient.execute(EasyMock.<HttpUriRequest>anyObject(), EasyMock.<HttpContext>anyObject()))
            .andReturn(response).times(2);

    EasyMock.replay(httpClient);

    ExecutionContext context = new ExecutionContext();

    Request<?> request = new DefaultRequest<Object>(null, "testsvc");
    request.setEndpoint(java.net.URI.create("http://testsvc.region.amazonaws.com"));
    request.setContent(new java.io.ByteArrayInputStream(new byte[0]));

    try {

        client.execute(request, handler, null, context);
        Assert.fail("No exception when request repeatedly fails!");

    } catch (KscClientException e) {
        Assert.assertSame(exception, e.getCause());
    }

    // Verify that we called execute 4 times.
    EasyMock.verify(httpClient);
}

From source file:org.mobicents.slee.enabler.rest.client.RESTClientEnablerChildSbb.java

@Override
public void execute(RESTClientEnablerRequest request) throws Exception {

    // validate request
    if (request == null) {
        throw new NullPointerException("request is null");
    }/*  w  w  w  .j  a v a2s.  c o  m*/
    if (request.getType() == null) {
        throw new NullPointerException("request type is null");
    }
    if (request.getUri() == null) {
        throw new NullPointerException("request uri is null");
    }

    // create http request
    HttpUriRequest httpRequest = null;
    switch (request.getType()) {
    case DELETE:
        httpRequest = new HttpDelete(request.getUri());
        break;
    case GET:
        httpRequest = new HttpGet(request.getUri());
        break;
    case POST:
        httpRequest = new HttpPost(request.getUri());
        break;
    case PUT:
        httpRequest = new HttpPut(request.getUri());
        break;
    default:
        throw new IllegalArgumentException("unknown request type");
    }

    // add headers, if any
    if (request.getHeaders() != null) {
        for (Header h : request.getHeaders()) {
            httpRequest.addHeader(h);
        }
    }

    // sign request using oauth, if needed
    if (request.getOAuthConsumer() != null) {
        request.getOAuthConsumer().sign(httpRequest);
    }

    // add content, if any
    if (request.getContent() != null) {
        if (!(httpRequest instanceof HttpEntityEnclosingRequest)) {
            throw new IllegalArgumentException("request includes content but type does not allows content");
        }
        if (request.getContentType() == null) {
            throw new IllegalArgumentException("request includes content but no content type");
        }
        BasicHttpEntity entity = new BasicHttpEntity();
        entity.setContent(request.getContent());
        if (request.getContentEncoding() != null)
            entity.setContentEncoding(request.getContentEncoding());
        entity.setContentType(request.getContentType());
        ((HttpEntityEnclosingRequest) httpRequest).setEntity(entity);
    }

    // get http client activity and attach to related aci
    HttpClientActivity activity = httpProvider.createHttpClientActivity(true, null);
    ActivityContextInterface aci = httpClientActivityContextInterfaceFactory
            .getActivityContextInterface(activity);
    aci.attach(this.sbbContext.getSbbLocalObject());

    // execute request on the activity
    activity.execute(httpRequest, request);
}

From source file:com.joyent.manta.http.EncryptedHttpHelperTest.java

/**
 * Builds a fully mocked {@link EncryptionHttpHelper} that is setup to
 * be configured for one cipher/mode and executes requests in another
 * cipher/mode.//from ww  w  .j  a  va2 s . c  o m
 */
private static EncryptionHttpHelper fakeEncryptionHttpHelper(String path) throws Exception {
    MantaConnectionContext connectionContext = mock(MantaConnectionContext.class);

    StandardConfigContext config = new StandardConfigContext();

    SupportedCipherDetails cipherDetails = AesCbcCipherDetails.INSTANCE_192_BIT;

    config.setClientEncryptionEnabled(true)
            .setEncryptionPrivateKeyBytes(SecretKeyUtils.generate(cipherDetails).getEncoded())
            .setEncryptionAlgorithm(cipherDetails.getCipherId());

    EncryptionHttpHelper httpHelper = new EncryptionHttpHelper(connectionContext,
            new MantaHttpRequestFactory(UnitTestConstants.UNIT_TEST_URL), config);

    URI uri = URI.create(DEFAULT_MANTA_URL + "/" + path);

    CloseableHttpResponse fakeResponse = mock(CloseableHttpResponse.class);
    StatusLine statusLine = new BasicStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK");

    SupportedCipherDetails objectCipherDetails = AesGcmCipherDetails.INSTANCE_128_BIT;

    Header[] headers = new Header[] {
            // Notice this is a different cipher than the one set in config
            new BasicHeader(MantaHttpHeaders.ENCRYPTION_CIPHER, objectCipherDetails.getCipherId()) };

    when(fakeResponse.getAllHeaders()).thenReturn(headers);
    when(fakeResponse.getStatusLine()).thenReturn(statusLine);

    BasicHttpEntity fakeEntity = new BasicHttpEntity();
    InputStream source = IOUtils.toInputStream("I'm a stream", StandardCharsets.US_ASCII);
    EofSensorInputStream stream = new EofSensorInputStream(source, null);
    fakeEntity.setContent(stream);
    when(fakeResponse.getEntity()).thenReturn(fakeEntity);

    when(connectionContext.getHttpClient()).thenReturn(new FakeCloseableHttpClient(fakeResponse));

    return httpHelper;
}

From source file:org.zenoss.zep.rest.RestClient.java

private HttpEntity createProtobufEntity(Message msg) {
    BasicHttpEntity entity = new BasicHttpEntity();
    entity.setContentType(ProtobufConstants.CONTENT_TYPE_PROTOBUF);
    entity.setContentLength(msg.getSerializedSize());
    entity.setContent(new ByteArrayInputStream(msg.toByteArray()));
    return entity;
}