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

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

Introduction

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

Prototype

public ByteArrayEntity(byte[] bArr, ContentType contentType) 

Source Link

Usage

From source file:com.flipkart.flux.client.runtime.FluxRuntimeConnectorHttpImpl.java

private CloseableHttpResponse postOverHttp(Object dataToPost, String pathSuffix) {
    CloseableHttpResponse httpResponse = null;
    HttpPost httpPostRequest;//  w  w  w .j  a  v a  2  s.  c o  m
    httpPostRequest = new HttpPost(fluxEndpoint + pathSuffix);
    final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    try {
        objectMapper.writeValue(byteArrayOutputStream, dataToPost);
        httpPostRequest.setEntity(
                new ByteArrayEntity(byteArrayOutputStream.toByteArray(), ContentType.APPLICATION_JSON));
        httpResponse = closeableHttpClient.execute(httpPostRequest);
        final int statusCode = httpResponse.getStatusLine().getStatusCode();
        if (statusCode >= Response.Status.OK.getStatusCode()
                && statusCode < Response.Status.MOVED_PERMANENTLY.getStatusCode()) {
            // all is well, TODO write a trace level log
        } else {
            // TODO: log status line here
            throw new RuntimeCommunicationException("Did not receive a valid response from Flux core");
        }
    } catch (IOException e) {
        // TODO log exception here
        e.printStackTrace();
        throw new RuntimeCommunicationException("Could not communicate with Flux runtime");
    }
    return httpResponse;
}

From source file:com.seleritycorp.common.base.http.client.HttpResponseTest.java

private HttpResponse createHttpResponse(int status, byte[] body, Charset charset) throws Exception {
    StatusLine statusLine = new BasicStatusLine(HttpVersion.HTTP_1_1, status, "ReasonFoo");
    org.apache.http.HttpResponse backendResponse = new BasicHttpResponse(statusLine);
    if (body != null) {
        backendResponse.setEntity(new ByteArrayEntity(body, ContentType.create("foo", charset)));
    }/*  w  w w  .  j av a  2  s  .  co  m*/
    return new HttpResponse(backendResponse);
}

From source file:com.github.tomakehurst.wiremock.RequestQueryAcceptanceTest.java

@Test
public void requestBodyEncodingRemainsUtf8() {
    byte[] body = new byte[] { -38, -100 }; // UTF-8 bytes for 
    testClient.post("/encoding", new ByteArrayEntity(body, ContentType.TEXT_PLAIN));

    List<LoggedRequest> requests = findAll(postRequestedFor(urlEqualTo("/encoding")));
    LoggedRequest request = requests.get(0);
    assertThat(request.getBodyAsString(), is(""));
}

From source file:org.obm.sync.push.client.WBXMLOPClient.java

private ByteArrayEntity getRequestEntity(String namespace, Document doc) throws WBXmlException, IOException {
    byte[] wbxml = wbxmlTools.toWbxml(namespace, doc);
    return new ByteArrayEntity(wbxml, ContentType.create("application/vnd.ms-sync.wbxml"));
}

From source file:net.fischboeck.discogs.BaseOperations.java

<T> T doPostRequest(String url, Object body, Class<T> type) throws ClientException {

    log.debug("[doPostRequest] url={}", url);

    CloseableHttpResponse response = null;

    try {//from w  w w .ja  va2 s .  c  o m
        HttpPost request = new HttpPost(url);
        request.setEntity(new ByteArrayEntity(mapper.writeValueAsBytes(body), ContentType.APPLICATION_JSON));

        response = doHttpRequest(request);
        HttpEntity entity = response.getEntity();
        return mapper.readValue(entity.getContent(), type);

    } catch (JsonProcessingException jpe) {
        throw new ClientException(jpe.getMessage());
    } catch (IOException ioe) {
        throw new ClientException(ioe.getMessage());
    } catch (EntityNotFoundException enfe) {
        return null;
    } finally {
        closeSafe(response);
    }
}

From source file:eu.peppol.outbound.HttpPostTestIT.java

@Test
public void testPost() throws Exception {

    InputStream resourceAsStream = HttpPostTestIT.class.getClassLoader()
            .getResourceAsStream(PEPPOL_BIS_INVOICE_SBDH_XML);
    assertNotNull(resourceAsStream,/*  www.  ja  v a  2  s . co m*/
            "Unable to locate resource " + PEPPOL_BIS_INVOICE_SBDH_XML + " in class path");

    X509Certificate ourCertificate = keystoreManager.getOurCertificate();

    SMimeMessageFactory SMimeMessageFactory = new SMimeMessageFactory(keystoreManager.getOurPrivateKey(),
            ourCertificate);
    MimeMessage signedMimeMessage = SMimeMessageFactory.createSignedMimeMessage(resourceAsStream,
            new MimeType("application/xml"));

    signedMimeMessage.writeTo(System.out);

    CloseableHttpClient httpClient = createCloseableHttpClient();

    HttpPost httpPost = new HttpPost(OXALIS_AS2_URL);

    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    signedMimeMessage.writeTo(byteArrayOutputStream);

    X500Principal subjectX500Principal = ourCertificate.getSubjectX500Principal();
    CommonName commonNameOfSender = CommonName.valueOf(subjectX500Principal);
    PeppolAs2SystemIdentifier asFrom = PeppolAs2SystemIdentifier.valueOf(commonNameOfSender);

    httpPost.addHeader(As2Header.AS2_FROM.getHttpHeaderName(), asFrom.toString());
    httpPost.addHeader(As2Header.AS2_TO.getHttpHeaderName(),
            new PeppolAs2SystemIdentifier(PeppolAs2SystemIdentifier.AS2_SYSTEM_ID_PREFIX + "AS2-TEST")
                    .toString());
    httpPost.addHeader(As2Header.DISPOSITION_NOTIFICATION_OPTIONS.getHttpHeaderName(),
            As2DispositionNotificationOptions.getDefault().toString());
    httpPost.addHeader(As2Header.AS2_VERSION.getHttpHeaderName(), As2Header.VERSION);
    httpPost.addHeader(As2Header.SUBJECT.getHttpHeaderName(), "AS2 TEST MESSAGE");
    httpPost.addHeader(As2Header.MESSAGE_ID.getHttpHeaderName(), UUID.randomUUID().toString());
    httpPost.addHeader(As2Header.DATE.getHttpHeaderName(), As2DateUtil.format(new Date()));

    // Inserts the S/MIME message to be posted
    httpPost.setEntity(
            new ByteArrayEntity(byteArrayOutputStream.toByteArray(), ContentType.create("multipart/signed")));

    CloseableHttpResponse postResponse = null; // EXECUTE !!!!
    try {
        postResponse = httpClient.execute(httpPost);
    } catch (HttpHostConnectException e) {
        fail("The Oxalis server does not seem to be running at " + OXALIS_AS2_URL);
    }

    HttpEntity entity = postResponse.getEntity(); // Any results?
    Assert.assertEquals(postResponse.getStatusLine().getStatusCode(), 200);
    String contents = EntityUtils.toString(entity);

    assertNotNull(contents);
    if (log.isDebugEnabled()) {
        log.debug("Received: \n");
        Header[] allHeaders = postResponse.getAllHeaders();
        for (Header header : allHeaders) {
            log.debug("" + header.getName() + ": " + header.getValue());
        }
        log.debug("\n" + contents);
        log.debug("---------------------------");
    }

    try {

        MimeMessage mimeMessage = MimeMessageHelper.parseMultipart(contents);
        System.out.println("Received multipart MDN response decoded as type : " + mimeMessage.getContentType());

        // Make sure we set content type header for the multipart message (should be multipart/signed)
        String contentTypeFromHttpResponse = postResponse.getHeaders("Content-Type")[0].getValue(); // Oxalis always return only one
        mimeMessage.setHeader("Content-Type", contentTypeFromHttpResponse);
        Enumeration<String> headerlines = mimeMessage.getAllHeaderLines();
        while (headerlines.hasMoreElements()) {
            // Content-Type: multipart/signed;
            // protocol="application/pkcs7-signature";
            // micalg=sha-1;
            // boundary="----=_Part_3_520186210.1399207766925"
            System.out.println("HeaderLine : " + headerlines.nextElement());
        }

        MdnMimeMessageInspector mdnMimeMessageInspector = new MdnMimeMessageInspector(mimeMessage);
        String msg = mdnMimeMessageInspector.getPlainTextPartAsText();
        System.out.println(msg);

    } finally {
        postResponse.close();
    }
}

From source file:com.google.devtools.build.lib.remote.blobstore.RestBlobStore.java

@Override
public void putActionResult(String key, byte[] in) throws IOException, InterruptedException {
    put(ACTION_CACHE_PREFIX, key, new ByteArrayEntity(in, ContentType.APPLICATION_OCTET_STREAM));
}

From source file:io.github.kitarek.elasthttpd.server.consumers.HttpRequestPrimaryConsumer.java

private void fillEntityOfHttpResponseWithExceptionMessage(final HttpResponse httpResponse,
        final String message) {
    if (message != null) {
        httpResponse.setEntity(new ByteArrayEntity(getAsciiBytes(message), PLAIN_DEFAULT_CONTENT_TYPE));
    }/*from   w ww.  j a v  a2s  .  c  o  m*/
}