Example usage for org.apache.http.entity ContentType APPLICATION_OCTET_STREAM

List of usage examples for org.apache.http.entity ContentType APPLICATION_OCTET_STREAM

Introduction

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

Prototype

ContentType APPLICATION_OCTET_STREAM

To view the source code for org.apache.http.entity ContentType APPLICATION_OCTET_STREAM.

Click Source Link

Usage

From source file:org.apache.olingo.server.example.TripPinServiceTest.java

@Test
public void testCreateStream2() throws Exception {
    // treating update and create as same for now, as there is details about
    // how entity payload and media payload can be sent at same time in request's body
    String editUrl = baseURL + "/Airlines('AA')/Picture";
    HttpPut request = new HttpPut(editUrl);
    request.setEntity(new ByteArrayEntity("bytecontents".getBytes(), ContentType.APPLICATION_OCTET_STREAM));
    HttpResponse response = httpSend(request, 204);
    EntityUtils.consumeQuietly(response.getEntity());
}

From source file:es.us.lsi.restest.engine.UnirestTest.java

@Test
public void testMultipartInputStreamContentType() throws JSONException, InterruptedException,
        ExecutionException, URISyntaxException, UnirestException, FileNotFoundException {
    HttpResponse<JsonNode> jsonResponse = Unirest.post("http://httpbin.org/post").field("name", "Mark")
            .field("file", new FileInputStream(new File(getClass().getResource("/image.jpg").toURI())),
                    ContentType.APPLICATION_OCTET_STREAM, "image.jpg")
            .asJson();//from  w  w  w  . j  a  v a2  s. co m
    assertTrue(jsonResponse.getHeaders().size() > 0);
    assertTrue(jsonResponse.getBody().toString().length() > 0);
    assertFalse(jsonResponse.getRawBody() == null);
    assertEquals(200, jsonResponse.getStatus());

    JsonNode json = jsonResponse.getBody();
    assertFalse(json.isArray());
    assertNotNull(json.getObject());
    assertNotNull(json.getArray());
    assertEquals(1, json.getArray().length());
    assertNotNull(json.getArray().get(0));
    assertNotNull(json.getObject().getJSONObject("files"));

    assertTrue(json.getObject().getJSONObject("files").getString("file")
            .contains("data:application/octet-stream"));
    assertEquals("Mark", json.getObject().getJSONObject("form").getString("name"));
}

From source file:com.gargoylesoftware.htmlunit.html.HtmlFileInputTest.java

/**
 * Test HttpClient for uploading a file with non-ASCII name, if it works it means HttpClient has fixed its bug.
 *
 * Test for http://issues.apache.org/jira/browse/HTTPCLIENT-293,
 * which is related to http://sourceforge.net/p/htmlunit/bugs/535/
 *
 * @throws Exception if the test fails/*  w w  w.  j  a v a  2 s .c  o m*/
 */
@Test
public void uploadFileWithNonASCIIName_HttpClient() throws Exception {
    final String filename = "\u6A94\u6848\uD30C\uC77C\u30D5\u30A1\u30A4\u30EB\u0645\u0644\u0641.txt";
    final String path = getClass().getClassLoader().getResource(filename).toExternalForm();
    final File file = new File(new URI(path));
    assertTrue(file.exists());

    final Map<String, Class<? extends Servlet>> servlets = new HashMap<>();
    servlets.put("/upload2", Upload2Servlet.class);

    startWebServer("./", null, servlets);
    final HttpPost filePost = new HttpPost("http://localhost:" + PORT + "/upload2");

    final MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE).setCharset(Charset.forName("UTF-8"));
    builder.addPart("myInput", new FileBody(file, ContentType.APPLICATION_OCTET_STREAM));

    filePost.setEntity(builder.build());

    final HttpClientBuilder clientBuilder = HttpClientBuilder.create();
    final HttpResponse httpResponse = clientBuilder.build().execute(filePost);

    InputStream content = null;
    try {
        content = httpResponse.getEntity().getContent();
        final String response = new String(IOUtils.toByteArray(content));
        //this is the value with ASCII encoding
        assertFalse("3F 3F 3F 3F 3F 3F 3F 3F 3F 3F 3F 2E 74 78 74 <br>myInput".equals(response));
    } finally {
        IOUtils.closeQuietly(content);
    }
}

From source file:com.ibm.ws.lars.rest.ApiTest.java

/**
 * Tests taking an attachment through create -> retrieve -> delete lifecycle.
 *//*from  w w w .j ava 2 s.  c  om*/
@Test
public void testCRUDAttachmentWithContent() throws Exception {
    Asset testAsset = AssetUtils.getTestAsset();
    Asset returnedAsset = repository.addAssetNoAttachments(testAsset);

    Attachment attachmentWithContent = AssetUtils.getTestAttachmentWithContent();

    AttachmentList attachments = repository.doGetAllAttachmentsForAsset(returnedAsset.get_id());
    assertTrue("Asset should have zero attachments before creating any attachments", attachments.isEmpty());

    String attachmentName = "attachment.txt";
    byte[] content = "This is the content.\nIt is quite short.".getBytes("UTF-8");

    Attachment createdAttachment = repository.doPostAttachmentWithContent(returnedAsset.get_id(),
            attachmentName, attachmentWithContent, content, ContentType.APPLICATION_OCTET_STREAM);

    Attachment returnedAttachment = repository.doGetOnlyAttachment(returnedAsset.get_id(),
            createdAttachment.get_id());

    AssetUtils.assertAttachmentMetadataEquivalent(repository,
            "Expected returned attachment to match the one that was uploaded", returnedAttachment,
            returnedAsset.get_id(), createdAttachment.get_id(), attachmentName, "application/octet-stream",
            content.length, attachmentWithContent);

    byte[] retrievedContent = repository.doGetAttachmentContent(returnedAsset.get_id(),
            createdAttachment.get_id(), attachmentName);
    assertTrue("retrieved attachment content should match created content",
            Arrays.equals(content, retrievedContent));

    repository.doDeleteAttachment(returnedAsset.get_id(), createdAttachment.get_id());

    AttachmentList attachmentsAfterDeletion = repository.doGetAllAttachmentsForAsset(returnedAsset.get_id());
    assertTrue("Asset should have zero attachments after deletion of only attachment",
            attachmentsAfterDeletion.isEmpty());
}

From source file:de.elomagic.carafile.client.CaraFileClient.java

/**
 * Don't call this method!/*from  ww  w  . j  a v  a  2 s .  c  o  m*/
 * <p/>
 * This method will be called usually by the server and this class.
 *
 * @param sp
 * @param md
 * @param out
 * @throws IOException
 */
public void downloadShunk(final PeerChunk sp, final MetaData md, final OutputStream out) throws IOException {
    if (out == null) {
        throw new IllegalArgumentException("Parameter 'out' must not be null!");
    }

    URI uri = CaraFileUtils.buildURI(sp.getPeerURI(), "peer", "leechChunk", sp.getChunkId());

    HttpResponse response = executeRequest(
            Request.Get(uri).addHeader(HttpHeaders.ACCEPT, ContentType.APPLICATION_OCTET_STREAM.toString()))
                    .returnResponse();

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    response.getEntity().writeTo(baos);

    String sha1 = DigestUtils.sha1Hex(baos.toByteArray());
    if (!sha1.equalsIgnoreCase(sp.getChunkId())) {
        throw new IOException("SHA1 validation failed. Expected " + sp.getChunkId() + " but was " + sha1);
    }

    out.write(baos.toByteArray());
}

From source file:es.us.lsi.restest.engine.UnirestTest.java

@Test
public void testMultipartInputStreamContentTypeAsync() throws JSONException, InterruptedException,
        ExecutionException, URISyntaxException, UnirestException, FileNotFoundException {
    Unirest.post("http://httpbin.org/post").field("name", "Mark")
            .field("file", new FileInputStream(new File(getClass().getResource("/test").toURI())),
                    ContentType.APPLICATION_OCTET_STREAM, "test")
            .asJsonAsync(new Callback<JsonNode>() {

                public void failed(UnirestException e) {
                    fail();//ww w .j  a v  a 2 s .  c o m
                }

                public void completed(HttpResponse<JsonNode> response) {
                    assertTrue(response.getHeaders().size() > 0);
                    assertTrue(response.getBody().toString().length() > 0);
                    assertFalse(response.getRawBody() == null);
                    assertEquals(200, response.getStatus());

                    JsonNode json = response.getBody();
                    assertFalse(json.isArray());
                    assertNotNull(json.getObject());
                    assertNotNull(json.getArray());
                    assertEquals(1, json.getArray().length());
                    assertNotNull(json.getArray().get(0));

                    assertEquals("This is a test file",
                            json.getObject().getJSONObject("files").getString("file"));
                    assertEquals("Mark", json.getObject().getJSONObject("form").getString("name"));

                    status = true;
                    lock.countDown();
                }

                public void cancelled() {
                    fail();
                }

            });

    lock.await(10, TimeUnit.SECONDS);
    assertTrue(status);
}

From source file:lucee.commons.net.http.httpclient.HTTPEngine4Impl.java

/**
 * convert input to HTTP Entity//from  ww w .  j  av  a 2s.  c  o  m
 * 
 * @param value
 * @param mimetype
 *            not used for binary input
 * @param charset
 *            not used for binary input
 * @return
 * @throws IOException
 */
private static HttpEntity toHttpEntity(Object value, String mimetype, String charset) throws IOException {
    if (value instanceof HttpEntity)
        return (HttpEntity) value;

    // content type
    ContentType ct = HTTPEngine.toContentType(mimetype, charset);
    try {
        if (value instanceof TemporaryStream) {
            if (ct != null)
                return new TemporaryStreamHttpEntity((TemporaryStream) value, ct);
            return new TemporaryStreamHttpEntity((TemporaryStream) value, null);
        } else if (value instanceof InputStream) {
            if (ct != null)
                return new ByteArrayEntity(IOUtil.toBytes((InputStream) value), ct);
            return new ByteArrayEntity(IOUtil.toBytes((InputStream) value));
        } else if (Decision.isCastableToBinary(value, false)) {
            if (ct != null)
                return new ByteArrayEntity(Caster.toBinary(value), ct);
            return new ByteArrayEntity(Caster.toBinary(value));
        } else {
            boolean wasNull = false;
            if (ct == null) {
                wasNull = true;
                ct = ContentType.APPLICATION_OCTET_STREAM;
            }
            String str = Caster.toString(value);
            if (str.equals("<empty>")) {
                return new EmptyHttpEntity(ct);
            }
            if (wasNull && !StringUtil.isEmpty(charset, true))
                return new StringEntity(str, charset.trim());
            else
                return new StringEntity(str, ct);
        }
    } catch (Exception e) {
        throw ExceptionUtil.toIOException(e);
    }
}

From source file:org.geogig.geoserver.rest.GeoGigWebAPIIntegrationTest.java

@Test
public void testGeoPackageImport() throws Exception {

    URL url = getClass().getResource("places.gpkg");

    // create transaction
    final String beginTransactionUrl = BASE_URL + "/beginTransaction";

    Document dom = getAsDOM(beginTransactionUrl);
    assertXpathEvaluatesTo("true", "/response/success", dom);
    String transactionId = XMLUnit.newXpathEngine().evaluate("/response/Transaction/ID", dom);

    // import geopackage
    final String importUrl = BASE_URL + "/import?format=gpkg&message=Import%20GeoPackage&transactionId="
            + transactionId;//from  w w  w.ja  va2  s .c  o m
    final String endTransactionUrl = BASE_URL + "/endTransaction?transactionId=" + transactionId;

    // construct a multipart request with the fileUpload
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    File f = new File(url.getFile());
    builder.addBinaryBody("fileUpload", new FileInputStream(f), ContentType.APPLICATION_OCTET_STREAM,
            f.getName());

    HttpEntity multipart = builder.build();

    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    multipart.writeTo(outputStream);
    MockHttpServletResponse response = postAsServletResponse(importUrl, outputStream.toByteArray(),
            multipart.getContentType().getValue());

    assertEquals(200, response.getStatus());

    dom = dom(new ByteArrayInputStream(response.getContentAsString().getBytes()), true);
    String taskId = XMLUnit.newXpathEngine().evaluate("/task/id", dom);
    final String taskUrl = "/geogig/tasks/" + taskId + ".xml";
    while ("RUNNING".equals(XMLUnit.newXpathEngine().evaluate("/task/status", dom))) {
        Thread.sleep(100);
        dom = getAsDOM(taskUrl);
    }
    assertXpathEvaluatesTo("FINISHED", "/task/status", dom);
    String commitId = XMLUnit.newXpathEngine().evaluate("//commit/id", dom);

    // close transaction
    dom = getAsDOM(endTransactionUrl);
    assertXpathEvaluatesTo("true", "/response/success", dom);

    // verify the repo contains the import
    Repository repository = geogigData.getGeogig().getRepository();
    RevCommit head = repository.getCommit(repository.getHead().get().getObjectId());
    assertEquals(commitId, head.getId().toString());
    assertEquals("Import GeoPackage", head.getMessage());
}

From source file:com.joyent.manta.client.multipart.ServerSideMultipartManagerTest.java

private ServerSideMultipartUpload initiateUploadWithAllParams(final String path, final StatusLine statusLine,
        final String responseBody) throws IOException {
    final MantaHttpHeaders headers = new MantaHttpHeaders();

    headers.setDurabilityLevel(5);//from w  w w  . j a v  a 2  s  . c o  m
    headers.setContentLength(423534L);
    headers.setContentMD5("e59ff97941044f85df5297e1c302d260");
    headers.setContentType(ContentType.APPLICATION_OCTET_STREAM.toString());

    final Set<String> roles = new HashSet<>();
    roles.add("manta");
    roles.add("role2");
    headers.setRoles(roles);

    final MantaMetadata metadata = new MantaMetadata();
    metadata.put("m-mykey1", "key value 1");
    metadata.put("m-mykey2", "key value 2");
    metadata.put("e-mykey", "i should be ignored");

    ServerSideMultipartManager manager = buildMockManager(statusLine, responseBody);
    MantaMultipartUpload upload = manager.initiateUpload(path, metadata, headers);

    Assert.assertEquals(upload.getClass(), ServerSideMultipartUpload.class);

    return (ServerSideMultipartUpload) upload;
}