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:ste.web.http.velocity.VelocityHandler.java

@Override
public void handle(HttpRequest request, HttpResponse response, HttpContext context)
        throws HttpException, IOException {
    String view = (String) context.getAttribute(ATTR_VIEW);
    if (view == null) {
        return;//from  w  ww.  jav a  2  s. co m
    }

    view = getViewPath(request.getRequestLine().getUri(), view);

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    Writer out = new OutputStreamWriter(baos);
    try {
        Template t = engine.getTemplate(view);
        t.merge(buildContext(request, (HttpSessionContext) context), out);
        out.flush();
    } catch (ResourceNotFoundException e) {
        response.setStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_NOT_FOUND, "View " + view + " not found.");
        return;
    } catch (ParseErrorException e) {
        throw new HttpException("Parse error evaluating " + view + ": " + e, e);
    } catch (MethodInvocationException e) {
        throw new HttpException("Method invocation error evaluating " + view + ": " + e, e);
    }

    BasicHttpEntity body = (BasicHttpEntity) response.getEntity();
    body.setContentLength(baos.size());
    body.setContent(new ByteArrayInputStream(baos.toByteArray()));
    if ((body.getContentType() == null) || StringUtils.isBlank(body.getContentType().getValue())) {
        body.setContentType(ContentType.TEXT_HTML.getMimeType());
    }
}

From source file:ru.apertum.qsystem.reports.model.QReportsList.java

public synchronized byte[] generate(QUser user, String uri, HashMap<String, String> params) {
    final HttpEntityEnclosingRequest r = new BasicHttpEntityEnclosingRequest("POST", uri);
    r.addHeader("Cookie", "username=" + user.getName() + "; password=" + user.getPassword());
    final StringBuilder sb = new StringBuilder();
    params.keySet().stream().forEach((st) -> {
        sb.append("&").append(st).append("=").append(params.get(st));
    });/*  w  w w.  j a v a2  s. c  o m*/
    final InputStream is = new ByteArrayInputStream(sb.substring(1).getBytes());
    final BasicHttpEntity b = new BasicHttpEntity();
    b.setContent(is);
    r.setEntity(b);
    sb.setLength(0);
    return generate(r).getData();
}

From source file:com.cloud.cluster.ClusterServiceServletHttpHandler.java

private void writeResponse(HttpResponse response, int statusCode, String content) {
    if (content == null) {
        content = "";
    }/*  www .ja  va 2  s . c  o  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:com.ksc.http.KscHttpClientTest.java

@SuppressWarnings({ "unchecked", "deprecation" })
@Test/*w ww.j a  v a 2s.c o  m*/
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.qucosa.camel.component.fcrepo3.Fcrepo3APIAccess.java

public void modifyDatastream(String pid, String dsid, Boolean versionable, InputStream content)
        throws IOException {
    HttpResponse response = null;//from ww w .  j a  v  a  2 s .c om
    try {
        BasicHttpEntity entity = new BasicHttpEntity();
        entity.setContent(content);
        // Entity needs to be buffered because Fedora might reply in a way
        // forces resubmitting the entity
        BufferedHttpEntity bufferedHttpEntity = new BufferedHttpEntity(entity);

        URIBuilder uriBuilder = new URIBuilder(
                format(FEDORA_DATASTREAM_MODIFICATION_URI_PATTERN, host, port, pid, dsid));
        if (versionable != null) {
            uriBuilder.addParameter("versionable", String.valueOf(versionable));
        }
        URI uri = uriBuilder.build();

        HttpPut put = new HttpPut(uri);
        put.setEntity(bufferedHttpEntity);
        response = httpClient.execute(put);

        if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            throw new IOException(format("Cannot modify datastream %s of object %s. Server responded: %s", dsid,
                    pid, response.getStatusLine()));
        }
    } catch (URISyntaxException e) {
        throw new IOException("Cannot ", e);
    } finally {
        consumeResponseEntity(response);
    }
}

From source file:org.wso2.carbon.apimgt.handlers.AuthenticationHandlerTest.java

private CloseableHttpResponse getInvalidResponse() throws UnsupportedEncodingException {
    CloseableHttpResponse mockDCRResponse = new MockHttpResponse();
    BasicHttpEntity responseEntity = new BasicHttpEntity();
    responseEntity
            .setContent(new ByteArrayInputStream("invalid response".getBytes(StandardCharsets.UTF_8.name())));
    responseEntity.setContentType(TestUtils.CONTENT_TYPE);
    mockDCRResponse.setEntity(responseEntity);
    mockDCRResponse.setStatusLine(new BasicStatusLine(new ProtocolVersion("http", 1, 0), 400, "Bad Request"));
    return mockDCRResponse;
}

From source file:org.wso2.carbon.apimgt.handlers.AuthenticationHandlerTest.java

private CloseableHttpResponse getDCRResponse() throws IOException {
    CloseableHttpResponse mockDCRResponse = new MockHttpResponse();
    String dcrResponseFile = TestUtils.getAbsolutePathOfConfig("dcr-response.json");
    BasicHttpEntity responseEntity = new BasicHttpEntity();
    responseEntity.setContent(
            new ByteArrayInputStream(getContent(dcrResponseFile).getBytes(StandardCharsets.UTF_8.name())));
    responseEntity.setContentType(TestUtils.CONTENT_TYPE);
    mockDCRResponse.setEntity(responseEntity);
    mockDCRResponse.setStatusLine(new BasicStatusLine(new ProtocolVersion("http", 1, 0), 200, "OK"));
    return mockDCRResponse;
}

From source file:org.wso2.carbon.apimgt.handlers.AuthenticationHandlerTest.java

private CloseableHttpResponse getAccessTokenReponse() throws IOException {
    CloseableHttpResponse mockDCRResponse = new MockHttpResponse();
    String dcrResponseFile = TestUtils.getAbsolutePathOfConfig("accesstoken-response.json");
    BasicHttpEntity responseEntity = new BasicHttpEntity();
    responseEntity.setContent(
            new ByteArrayInputStream(getContent(dcrResponseFile).getBytes(StandardCharsets.UTF_8.name())));
    responseEntity.setContentType(TestUtils.CONTENT_TYPE);
    mockDCRResponse.setEntity(responseEntity);
    mockDCRResponse.setStatusLine(new BasicStatusLine(new ProtocolVersion("http", 1, 0), 200, "OK"));
    return mockDCRResponse;
}

From source file:org.wso2.carbon.apimgt.handlers.AuthenticationHandlerTest.java

private CloseableHttpResponse getValidationResponse() throws UnsupportedEncodingException {
    ValidationResponce response = new ValidationResponce();
    response.setDeviceId("1234");
    response.setDeviceType("testdevice");
    response.setJWTToken("1234567788888888");
    response.setTenantId(-1234);/*from  ww  w. j a  v  a2  s .c  o m*/
    Gson gson = new Gson();
    String jsonReponse = gson.toJson(response);
    CloseableHttpResponse mockDCRResponse = new MockHttpResponse();
    BasicHttpEntity responseEntity = new BasicHttpEntity();
    responseEntity.setContent(new ByteArrayInputStream(jsonReponse.getBytes(StandardCharsets.UTF_8.name())));
    responseEntity.setContentType(TestUtils.CONTENT_TYPE);
    mockDCRResponse.setEntity(responseEntity);
    mockDCRResponse.setStatusLine(new BasicStatusLine(new ProtocolVersion("http", 1, 0), 200, "OK"));
    return mockDCRResponse;
}