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.brunocvcunha.instagram4j.requests.InstagramUploadPhotoRequest.java

/**
 * Creates required multipart entity with the image binary
 * @return HttpEntity to send on the post
 * @throws ClientProtocolException// www  .j  a v a  2 s .  com
 * @throws IOException
 */
protected HttpEntity createMultipartEntity() throws ClientProtocolException, IOException {
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.addTextBody("upload_id", uploadId);
    builder.addTextBody("_uuid", api.getUuid());
    builder.addTextBody("_csrftoken", api.getOrFetchCsrf());
    builder.addTextBody("image_compression",
            "{\"lib_name\":\"jt\",\"lib_version\":\"1.3.0\",\"quality\":\"87\"}");
    builder.addBinaryBody("photo", bufferedImageToByteArray(imageFile), ContentType.APPLICATION_OCTET_STREAM,
            "pending_media_" + uploadId + ".jpg");
    builder.setBoundary(api.getUuid());

    HttpEntity entity = builder.build();
    return entity;
}

From source file:com.haulmont.cuba.client.sys.FileLoaderClientImpl.java

protected void saveStreamWithServlet(FileDescriptor fd, Supplier<InputStream> inputStreamSupplier,
        @Nullable StreamingProgressListener streamingListener)
        throws FileStorageException, InterruptedException {

    Object context = serverSelector.initContext();
    String selectedUrl = serverSelector.getUrl(context);
    if (selectedUrl == null) {
        throw new FileStorageException(FileStorageException.Type.IO_EXCEPTION, fd.getName());
    }// w  w  w  . j a  va2  s . co  m

    ClientConfig clientConfig = configuration.getConfig(ClientConfig.class);
    String fileUploadContext = clientConfig.getFileUploadContext();

    while (true) {
        String url = selectedUrl + fileUploadContext + "?s=" + userSessionSource.getUserSession().getId()
                + "&f=" + fd.toUrlParam();

        try (InputStream inputStream = inputStreamSupplier.get()) {
            InputStreamProgressEntity.UploadProgressListener progressListener = null;
            if (streamingListener != null) {
                progressListener = streamingListener::onStreamingProgressChanged;
            }

            HttpPost method = new HttpPost(url);
            method.setEntity(new InputStreamProgressEntity(inputStream, ContentType.APPLICATION_OCTET_STREAM,
                    progressListener));

            HttpClientConnectionManager connectionManager = new BasicHttpClientConnectionManager();
            HttpClient client = HttpClientBuilder.create().setConnectionManager(connectionManager).build();
            try {
                HttpResponse response = client.execute(method);

                int statusCode = response.getStatusLine().getStatusCode();
                if (statusCode == HttpStatus.SC_OK) {
                    break;
                } else {
                    log.debug("Unable to upload file to {}\n{}", url, response.getStatusLine());
                    selectedUrl = failAndGetNextUrl(context);
                    if (selectedUrl == null) {
                        throw new FileStorageException(FileStorageException.Type.fromHttpStatus(statusCode),
                                fd.getName());
                    }
                }
            } catch (InterruptedIOException e) {
                log.trace("Uploading has been interrupted");
                throw new InterruptedException("File uploading is interrupted");
            } catch (IOException e) {
                log.debug("Unable to upload file to {}\n{}", url, e);
                selectedUrl = failAndGetNextUrl(context);
                if (selectedUrl == null) {
                    throw new FileStorageException(FileStorageException.Type.IO_EXCEPTION, fd.getName(), e);
                }
            } finally {
                connectionManager.shutdown();
            }
        } catch (IOException | RetryUnsupportedException e) {
            throw new FileStorageException(FileStorageException.Type.IO_EXCEPTION, fd.getName(), e);
        }
    }
}

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

@Override
public PART uploadPart(final UPLOAD upload, final int partNumber, final InputStream inputStream)
        throws IOException {
    Validate.notNull(inputStream, "InputStream must not be null");

    if (inputStream.getClass().equals(FileInputStream.class)) {
        final FileInputStream fin = (FileInputStream) inputStream;
        final long contentLength = fin.getChannel().size();
        return uploadPart(upload, partNumber, contentLength, inputStream);
    }//  w  w  w. ja  va 2 s. c om

    HttpEntity entity = new MantaInputStreamEntity(inputStream, ContentType.APPLICATION_OCTET_STREAM);

    return uploadPart(upload, partNumber, entity, null);
}

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

@Override
public MantaMultipartUploadPart uploadPart(TestMultipartUpload upload, int partNumber, InputStream inputStream)
        throws IOException {
    HttpEntity entity = new MantaInputStreamEntity(inputStream, ContentType.APPLICATION_OCTET_STREAM);

    return uploadPart(upload, partNumber, entity, null);
}

From source file:org.apache.calcite.avatica.remote.AvaticaCommonsHttpClientSpnegoImpl.java

@Override
public byte[] send(byte[] request) {
    HttpClientContext context = HttpClientContext.create();

    context.setTargetHost(host);//from ww  w . ja  v a2s  . c  om
    context.setCredentialsProvider(credentialsProvider);
    context.setAuthSchemeRegistry(authRegistry);
    context.setAuthCache(authCache);

    ByteArrayEntity entity = new ByteArrayEntity(request, ContentType.APPLICATION_OCTET_STREAM);

    // Create the client with the AuthSchemeRegistry and manager
    HttpPost post = new HttpPost(toURI(url));
    post.setEntity(entity);

    try (CloseableHttpResponse response = client.execute(post, context)) {
        final int statusCode = response.getStatusLine().getStatusCode();
        if (HttpURLConnection.HTTP_OK == statusCode || HttpURLConnection.HTTP_INTERNAL_ERROR == statusCode) {
            return EntityUtils.toByteArray(response.getEntity());
        }

        throw new RuntimeException("Failed to execute HTTP Request, got HTTP/" + statusCode);
    } catch (RuntimeException e) {
        throw e;
    } catch (Exception e) {
        LOG.debug("Failed to execute HTTP request", e);
        throw new RuntimeException(e);
    }
}

From source file:com.vaushell.superpipes.tools.scribe.twitter.TwitterClient.java

/**
 * Tweet picture.//from  ww  w  .  j  ava2 s  .c om
 *
 * @param message Tweet's content
 * @param is InputStream of the picture
 * @return Tweet's ID
 * @throws IOException
 * @throws OAuthException
 */
public long tweetPicture(final String message, final InputStream is) throws IOException, OAuthException {
    if (message == null || is == null) {
        throw new IllegalArgumentException();
    }

    if (LOGGER.isTraceEnabled()) {
        LOGGER.trace("[" + getClass().getSimpleName() + "] tweetPicture() : message=" + message);
    }

    final OAuthRequest request = new OAuthRequest(Verb.POST,
            "https://api.twitter.com/1.1/statuses/update_with_media.json");
    final HttpEntity entity = MultipartEntityBuilder.create().addBinaryBody("status", message.getBytes("UTF-8"))
            .addBinaryBody("media[]", is, ContentType.APPLICATION_OCTET_STREAM, "media").build();

    final Header contentType = entity.getContentType();
    request.addHeader(contentType.getName(), contentType.getValue());

    try (final ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
        entity.writeTo(bos);
        request.addPayload(bos.toByteArray());
    }

    final Response response = sendSignedRequest(request);

    final ObjectMapper mapper = new ObjectMapper();
    final JsonNode node = (JsonNode) mapper.readTree(response.getStream());

    checkErrors(response, node);

    return node.get("id").asLong();
}

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

@Override
public PART uploadPart(final UPLOAD upload, final int partNumber, final long contentLength,
        final InputStream inputStream) throws IOException {
    Validate.notNull(inputStream, "InputStream must not be null");

    HttpEntity entity;//ww w  .  j  ava 2  s . c o  m

    if (contentLength > -1) {
        entity = new MantaInputStreamEntity(inputStream, contentLength, ContentType.APPLICATION_OCTET_STREAM);
    } else {
        entity = new MantaInputStreamEntity(inputStream, ContentType.APPLICATION_OCTET_STREAM);
    }

    return uploadPart(upload, partNumber, entity, null);
}

From source file:org.apache.calcite.avatica.remote.AvaticaCommonsHttpClientImpl.java

public byte[] send(byte[] request) {
    while (true) {
        HttpClientContext context = HttpClientContext.create();

        context.setTargetHost(host);//w  w  w.j a  v  a2 s.  c  o m

        // Set the credentials if they were provided.
        if (null != this.credentials) {
            context.setCredentialsProvider(credentialsProvider);
            context.setAuthSchemeRegistry(authRegistry);
            context.setAuthCache(authCache);
        }

        ByteArrayEntity entity = new ByteArrayEntity(request, ContentType.APPLICATION_OCTET_STREAM);

        // Create the client with the AuthSchemeRegistry and manager
        HttpPost post = new HttpPost(uri);
        post.setEntity(entity);

        try (CloseableHttpResponse response = execute(post, context)) {
            final int statusCode = response.getStatusLine().getStatusCode();
            if (HttpURLConnection.HTTP_OK == statusCode
                    || HttpURLConnection.HTTP_INTERNAL_ERROR == statusCode) {
                return EntityUtils.toByteArray(response.getEntity());
            } else if (HttpURLConnection.HTTP_UNAVAILABLE == statusCode) {
                LOG.debug("Failed to connect to server (HTTP/503), retrying");
                continue;
            }

            throw new RuntimeException("Failed to execute HTTP Request, got HTTP/" + statusCode);
        } catch (NoHttpResponseException e) {
            // This can happen when sitting behind a load balancer and a backend server dies
            LOG.debug("The server failed to issue an HTTP response, retrying");
            continue;
        } catch (RuntimeException e) {
            throw e;
        } catch (Exception e) {
            LOG.debug("Failed to execute HTTP request", e);
            throw new RuntimeException(e);
        }
    }
}

From source file:org.eclipse.jgit.lfs.server.fs.LfsServerTest.java

protected LongObjectId putContent(Path f) throws FileNotFoundException, IOException {
    try (CloseableHttpClient client = HttpClientBuilder.create().build()) {
        LongObjectId id1, id2;//  w ww  . jav  a 2 s  . c  o m
        String hexId1, hexId2;
        try (DigestInputStream in = new DigestInputStream(new BufferedInputStream(Files.newInputStream(f)),
                Constants.newMessageDigest())) {
            InputStreamEntity entity = new InputStreamEntity(in, Files.size(f),
                    ContentType.APPLICATION_OCTET_STREAM);
            id1 = LongObjectIdTestUtils.hash(f);
            hexId1 = id1.name();
            HttpPut request = new HttpPut(server.getURI() + "/lfs/objects/" + hexId1);
            request.setEntity(entity);
            HttpResponse response = client.execute(request);
            checkResponseStatus(response);
            id2 = LongObjectId.fromRaw(in.getMessageDigest().digest());
            hexId2 = id2.name();
            assertEquals(hexId1, hexId2);
        }
        return id1;
    }
}

From source file:org.apache.sling.replication.transport.impl.HttpTransportHandler.java

private void deliverPackage(Executor executor, ReplicationPackage replicationPackage,
        ReplicationEndpoint replicationEndpoint) throws IOException {
    String type = replicationPackage.getType();

    Request req = Request.Post(replicationEndpoint.getUri()).useExpectContinue();

    if (useCustomHeaders) {
        String[] customizedHeaders = getCustomizedHeaders(customHeaders, replicationPackage.getAction(),
                replicationPackage.getPaths());
        for (String header : customizedHeaders) {
            addHeader(req, header);//from  w  w w .j  a v a2  s  . c  o  m
        }
    } else {
        req.addHeader(ReplicationHeader.TYPE.toString(), type);
    }

    InputStream inputStream = null;
    Response response = null;
    try {
        if (useCustomBody) {
            String body = customBody == null ? "" : customBody;
            inputStream = new ByteArrayInputStream(body.getBytes());
        } else {
            inputStream = replicationPackage.createInputStream();
        }

        if (inputStream != null) {
            req = req.bodyStream(inputStream, ContentType.APPLICATION_OCTET_STREAM);
        }

        response = executor.execute(req);
    } finally {
        IOUtils.closeQuietly(inputStream);
    }

    if (response != null) {
        Content content = response.returnContent();
        if (log.isInfoEnabled()) {
            log.info("Replication content of type {} for {} delivered: {}",
                    new Object[] { type, Arrays.toString(replicationPackage.getPaths()), content });
        }
    } else {
        throw new IOException("response is empty");
    }
}