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:com.ibm.ws.lars.rest.PermissionTest.java

@Before
public void setUp() throws IOException, InvalidJsonAssetException {
    testAsset = AssetUtils.getTestAsset();
    createdAsset = adminContext.addAssetNoAttachments(testAsset);

    assetWithAttachments = AssetUtils.getTestAsset();
    createAssetWithAttachments = adminContext.addAssetNoAttachments(assetWithAttachments);
    attachmentName = "nocontent.txt";
    attachmentContent = "I am the content.\nThere is not much content to be had.\n"
            .getBytes(StandardCharsets.UTF_8);
    attachment = AssetUtils.getTestAttachmentWithContent();
    createdAttachment = adminContext.doPostAttachmentWithContent(createAssetWithAttachments.get_id(),
            attachmentName, attachment, attachmentContent, ContentType.APPLICATION_OCTET_STREAM);
}

From source file:org.jboss.as.test.integration.management.http.HttpDeploymentUploadUnitTestCase.java

private HttpEntity createUploadEntity(final File archive) {
    return MultipartEntityBuilder.create().setContentType(ContentType.MULTIPART_FORM_DATA)
            .setBoundary(BOUNDARY_PARAM).addTextBody("test1", BOUNDARY_PARAM)
            .addTextBody("test2", BOUNDARY_PARAM)
            .addBinaryBody("file", archive, ContentType.APPLICATION_OCTET_STREAM, DEPLOYMENT_NAME).build();
}

From source file:com.activiti.service.activiti.AppService.java

protected void uploadAppDefinition(HttpServletResponse httpResponse, ServerConfig serverConfig, String name,
        byte[] bytes) throws IOException {
    HttpPost post = new HttpPost(clientUtil.getServerUrl(serverConfig, APP_IMPORT_AND_PUBLISH_URL));
    HttpEntity reqEntity = MultipartEntityBuilder.create()
            .addBinaryBody("file", bytes, ContentType.APPLICATION_OCTET_STREAM, name).build();
    post.setEntity(reqEntity);/*  ww w  .j av  a2s . c o m*/
    clientUtil.execute(post, httpResponse, serverConfig);
}

From source file:com.alibaba.shared.django.DjangoClient.java

protected void uploadFileChunks(InputStream is, int maxChunkSize, final String fileId, final int sequence,
        final String fillename, List<DjangoMessage> holder) throws IOException, URISyntaxException {
    final MessageDigest digest = Digests.defaultDigest();
    byte[] buf = new byte[8000];
    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    int len = is.read(buf), processCount = len;
    while (len >= 0 && processCount < maxChunkSize) {
        baos.write(buf, 0, len);/*from   ww  w . j av a2s.  c om*/
        digest.update(buf, 0, len);
        processCount += len;
        if (maxChunkSize <= processCount) {
            break;
        }
        len = is.read(buf);
    }
    if (processCount > 0) {
        holder.add(executeRequest(new Supplier<HttpUriRequest>() {
            public HttpUriRequest get() {
                MultipartEntityBuilder meb = MultipartEntityBuilder.create();
                meb.addTextBody(ACCESS_TOKEN_KEY, accessToken()).addTextBody("fileId", fileId)
                        .addTextBody("sequence", String.valueOf(sequence))
                        .addTextBody("md5", Digests.toHexDigest(digest.digest())).addBinaryBody(FILE_KEY,
                                baos.toByteArray(), ContentType.APPLICATION_OCTET_STREAM, fillename);
                HttpPost post = new HttpPost(chunkUrl);
                post.setEntity(meb.build());
                return post;
            }
        }));
        uploadFileChunks(is, maxChunkSize, fileId, sequence + 1, fillename, holder);
    }
}

From source file:org.apache.nifi.api.client.impl.AbstractNiFiAPIClient.java

public <U extends Entity> Object post(Class<? extends ApplicationResource> resourceClass, Method nifiApiMethod,
        U u, Map<String, String> pathParams, InputStream payloadData) {

    StringBuilder stringBuilder = new StringBuilder(this.baseUrl);
    stringBuilder.append(resourceClass.getAnnotation(Path.class).value());
    stringBuilder.append("/");
    stringBuilder.append(nifiApiMethod.getAnnotation(Path.class).value());

    String fullRequest = replaceUriWithPathParams(stringBuilder.toString(), pathParams);

    HttpPost request = new HttpPost(fullRequest);

    StringBuffer result = new StringBuffer();
    try {/*  w  ww  .  j a  v a2  s . co  m*/

        //Set the Accept and Content-Type headers appropriately.
        String produces = nifiApiMethod.getAnnotation(Produces.class).value()[0];
        String consumes = nifiApiMethod.getAnnotation(Consumes.class).value()[0];

        //Set POST request payload. Can only upload either Inputstream OR Object currently.
        if (u != null || payloadData != null) {
            if (u != null) {
                StringEntity input = new StringEntity(mapper.writeValueAsString(u));
                request.setEntity(input);
                request.setHeader("Content-type", consumes);
            } else {
                InputStreamEntity inputStreamEntity = new InputStreamEntity(payloadData);
                request.setEntity(inputStreamEntity);

                MultipartEntityBuilder builder = MultipartEntityBuilder.create();
                //builder.addTextBody("field1", "yes", ContentType.TEXT_PLAIN);

                // This attaches the file to the POST:
                builder.addBinaryBody("template", payloadData, ContentType.APPLICATION_OCTET_STREAM,
                        "SomethingTest.xml");

                HttpEntity multipart = builder.build();
                request.setEntity(multipart);
            }
        }

        request.addHeader("Accept", produces);

        HttpResponse response = client.execute(request);

        //Examine the return type and handle that data appropriately.
        Header rCT = response.getHeaders("Content-Type")[0];
        if (rCT.getValue().equalsIgnoreCase("application/xml")) {
            //                TemplateDTO templateDTO = TemplateDeserializer.deserialize(response.getEntity().getContent());
            //                return templateDTO;
            return null;
        } else {
            return mapper.readValue(response.getEntity().getContent(),
                    nifiApiMethod.getAnnotation(ApiOperation.class).response());
        }

    } catch (Exception ex) {
        logger.error("Unable to complete HTTP POST due to {}", ex.getMessage());
        return null;
    }
}

From source file:tech.sirwellington.alchemy.http.HttpVerbImplTest.java

@Test
public void testExecuteWhenContentTypeInvalid() throws IOException {
    List<ContentType> invalidContentTypes = Arrays.asList(ContentType.APPLICATION_ATOM_XML,
            ContentType.TEXT_HTML, ContentType.TEXT_XML, ContentType.APPLICATION_XML,
            ContentType.APPLICATION_OCTET_STREAM, ContentType.create(one(alphabeticString())));

    ContentType invalidContentType = Lists.oneOf(invalidContentTypes);

    String string = one(alphanumericString());
    entity = new StringEntity(string, invalidContentType);

    when(apacheResponse.getEntity()).thenReturn(entity);

    HttpResponse result = instance.execute(apacheClient, request);
    assertThat(result.bodyAsString(), is(string));
    verify(apacheResponse).close();/*from w ww.  ja v  a 2 s  .com*/
}

From source file:com.scoopit.weedfs.client.WeedFSClientImpl.java

private int write(WeedFSFile file, Location location, File fileToUpload, byte[] dataToUpload,
        InputStream inputToUpload, String fileName) throws IOException, WeedFSException {
    StringBuilder url = new StringBuilder();
    if (!location.publicUrl.contains("http")) {
        url.append("http://");
    }//from   w ww.  j av a2  s  . co  m
    url.append(location.publicUrl);
    url.append('/');
    url.append(file.fid);

    if (file.version > 0) {
        url.append('_');
        url.append(file.version);
    }

    HttpPost post = new HttpPost(url.toString());

    MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
    if (fileToUpload != null) {
        if (fileName == null) {
            fileName = fileToUpload.getName();
        }
        multipartEntityBuilder.addBinaryBody("file", fileToUpload, ContentType.APPLICATION_OCTET_STREAM,
                sanitizeFileName(fileName));
    } else if (dataToUpload != null) {
        multipartEntityBuilder.addBinaryBody("file", dataToUpload, ContentType.APPLICATION_OCTET_STREAM,
                sanitizeFileName(fileName));
    } else {
        multipartEntityBuilder.addBinaryBody("file", inputToUpload, ContentType.APPLICATION_OCTET_STREAM,
                sanitizeFileName(fileName));
    }
    post.setEntity(multipartEntityBuilder.build());

    try {
        HttpResponse response = httpClient.execute(post);

        String content = getContentOrNull(response);
        ObjectMapper mapper = new ObjectMapper();
        try {
            WriteResult result = mapper.readValue(content, WriteResult.class);

            if (result.error != null) {
                throw new WeedFSException(result.error);
            }

            return result.size;
        } catch (JsonMappingException | JsonParseException e) {
            throw new WeedFSException("Unable to parse JSON from weed-fs from: " + content, e);
        }
    } finally {
        post.abort();
    }
}

From source file:com.activiti.service.activiti.AppService.java

protected void uploadNewAppDefinitionVersion(HttpServletResponse httpResponse, ServerConfig serverConfig,
        String name, byte[] bytes, String appId) throws IOException {
    URIBuilder builder = clientUtil/*from  w  ww.  ja  va2  s.  com*/
            .createUriBuilder(MessageFormat.format(APP_IMPORT_AND_PUBLISH_AS_NEW_VERSION_URL, appId));
    HttpPost post = new HttpPost(clientUtil.getServerUrl(serverConfig, builder));
    HttpEntity reqEntity = MultipartEntityBuilder.create()
            .addBinaryBody("file", bytes, ContentType.APPLICATION_OCTET_STREAM, name).build();
    post.setEntity(reqEntity);
    clientUtil.execute(post, httpResponse, serverConfig);
}

From source file:com.jivesoftware.os.routing.bird.http.client.ApacheHttpClient441BackedHttpClient.java

@Override
public HttpResponse postBytes(String path, byte[] postBytes, Map<String, String> headers)
        throws HttpClientException {
    try {//from  w  w  w .  java 2  s.com
        HttpPost post = new HttpPost(toURI(path));

        setRequestHeaders(headers, post);

        post.setEntity(new ByteArrayEntity(postBytes, ContentType.APPLICATION_OCTET_STREAM));
        post.setHeader(CONTENT_TYPE_HEADER_NAME, APPLICATION_OCTET_STREAM_TYPE);
        return execute(post);
    } catch (IOException | OAuthCommunicationException | OAuthExpectationFailedException
            | OAuthMessageSignerException e) {
        throw new HttpClientException("Error executing POST request to: " + clientToString() + " path: " + path
                + " JSON body of length: " + postBytes.length, e);
    }
}