Example usage for org.apache.http.entity.mime.content AbstractContentBody AbstractContentBody

List of usage examples for org.apache.http.entity.mime.content AbstractContentBody AbstractContentBody

Introduction

In this page you can find the example usage for org.apache.http.entity.mime.content AbstractContentBody AbstractContentBody.

Prototype

public AbstractContentBody(final String mimeType) 

Source Link

Usage

From source file:org.datacleaner.actions.PublishFileToMonitorActionListener.java

@Override
protected Map<?, ?> doInBackground() throws Exception {

    final MonitorConnection monitorConnection = _userPreferences.getMonitorConnection();

    final String uploadUrl = getUploadUrl(monitorConnection);
    logger.debug("Upload url: {}", uploadUrl);

    final HttpPost request = new HttpPost(uploadUrl);

    final long expectedSize = getExpectedSize();

    publish(new Task() {
        @Override//w w  w  .  j  a v a 2 s  .  co  m
        public void execute() throws Exception {
            _progressWindow.setExpectedSize(getTransferredFilename(), expectedSize);
        }
    });

    final MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    final ContentBody uploadFilePart = new AbstractContentBody("application/octet-stream") {

        @Override
        public String getCharset() {
            return null;
        }

        @Override
        public String getTransferEncoding() {
            return MIME.ENC_BINARY;
        }

        @Override
        public long getContentLength() {
            return expectedSize;
        }

        @Override
        public void writeTo(OutputStream out) throws IOException {
            long progress = 0;
            try (final InputStream in = getTransferStream()) {
                byte[] tmp = new byte[4096];
                int length;
                while ((length = in.read(tmp)) != -1) {
                    out.write(tmp, 0, length);

                    // update the visual progress
                    progress = progress + length;

                    final long updatedProgress = progress;

                    publish(new Task() {
                        @Override
                        public void execute() throws Exception {
                            _progressWindow.setProgress(getTransferredFilename(), updatedProgress);
                        }
                    });
                }
                out.flush();
            }
        }

        @Override
        public String getFilename() {
            return getTransferredFilename();
        }
    };

    entity.addPart("file", uploadFilePart);
    request.setEntity(entity);

    try (final MonitorHttpClient monitorHttpClient = monitorConnection.getHttpClient()) {
        final HttpResponse response;
        try {
            response = monitorHttpClient.execute(request);
        } catch (Exception e) {
            throw new IllegalStateException(e);
        }
        final StatusLine statusLine = response.getStatusLine();

        if (statusLine.getStatusCode() == 200) {
            logger.info("Upload response status: {}", statusLine);

            // parse the response as a JSON map
            final InputStream content = response.getEntity().getContent();
            final String contentString;
            try {
                contentString = FileHelper.readInputStreamAsString(content, FileHelper.DEFAULT_ENCODING);
            } finally {
                FileHelper.safeClose(content);
            }

            final ObjectMapper objectMapper = new ObjectMapper();
            try {
                final Map<?, ?> responseMap = objectMapper.readValue(contentString, Map.class);

                return responseMap;
            } catch (Exception e) {
                logger.warn("Received non-JSON response:\n{}", contentString);
                logger.error("Failed to parse response as JSON", e);
                return null;
            }
        } else {
            logger.warn("Upload response status: {}", statusLine);
            final String reasonPhrase = statusLine.getReasonPhrase();
            WidgetUtils.showErrorMessage("Server reported error",
                    "Server replied with status " + statusLine.getStatusCode() + ":\n" + reasonPhrase);
            return null;
        }
    }
}

From source file:com.basistech.rosette.api.HttpRosetteAPI.java

private void setupMultipartRequest(final Request request, final ObjectWriter finalWriter, HttpPost post)
        throws IOException {
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMimeSubtype("mixed");
    builder.setMode(HttpMultipartMode.STRICT);

    FormBodyPartBuilder partBuilder = FormBodyPartBuilder.create("request",
            // Make sure we're not mislead by someone who puts a charset into the mime type.
            new AbstractContentBody(ContentType.parse(ContentType.APPLICATION_JSON.getMimeType())) {
                @Override//  w w  w  .j a  v a  2 s  . co m
                public String getFilename() {
                    return null;
                }

                @Override
                public void writeTo(OutputStream out) throws IOException {
                    finalWriter.writeValue(out, request);
                }

                @Override
                public String getTransferEncoding() {
                    return MIME.ENC_BINARY;
                }

                @Override
                public long getContentLength() {
                    return -1;
                }
            });

    // Either one of 'name=' or 'Content-ID' would be enough.
    partBuilder.setField(MIME.CONTENT_DISPOSITION, "inline;name=\"request\"");
    partBuilder.setField("Content-ID", "request");

    builder.addPart(partBuilder.build());

    AbstractContentBody insBody;
    if (request instanceof DocumentRequest) {
        DocumentRequest docReq = (DocumentRequest) request;
        insBody = new InputStreamBody(docReq.getContentBytes(), ContentType.parse(docReq.getContentType()));
    } else if (request instanceof AdmRequest) {
        //TODO: smile?
        AdmRequest admReq = (AdmRequest) request;
        ObjectWriter writer = mapper.writer().without(JsonGenerator.Feature.AUTO_CLOSE_TARGET);
        byte[] json = writer.writeValueAsBytes(admReq.getText());
        insBody = new ByteArrayBody(json, ContentType.parse(AdmRequest.ADM_CONTENT_TYPE), null);
    } else {
        throw new UnsupportedOperationException("Unsupported request type for multipart processing");
    }
    partBuilder = FormBodyPartBuilder.create("content", insBody);
    partBuilder.setField(MIME.CONTENT_DISPOSITION, "inline;name=\"content\"");
    partBuilder.setField("Content-ID", "content");
    builder.addPart(partBuilder.build());
    builder.setCharset(StandardCharsets.UTF_8);
    HttpEntity entity = builder.build();
    post.setEntity(entity);
}

From source file:com.basistech.rosette.api.RosetteAPI.java

private void setupMultipartRequest(final DocumentRequest request, final ObjectWriter finalWriter,
        HttpPost post) {/*from  w  w w.  j a  va2  s .c o  m*/

    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMimeSubtype("mixed");
    builder.setMode(HttpMultipartMode.STRICT);

    FormBodyPartBuilder partBuilder = FormBodyPartBuilder.create("request",
            // Make sure we're not mislead by someone who puts a charset into the mime type.
            new AbstractContentBody(ContentType.parse(ContentType.APPLICATION_JSON.getMimeType())) {
                @Override
                public String getFilename() {
                    return null;
                }

                @Override
                public void writeTo(OutputStream out) throws IOException {
                    finalWriter.writeValue(out, request);
                }

                @Override
                public String getTransferEncoding() {
                    return MIME.ENC_BINARY;
                }

                @Override
                public long getContentLength() {
                    return -1;
                }
            });

    // Either one of 'name=' or 'Content-ID' would be enough.
    partBuilder.setField(MIME.CONTENT_DISPOSITION, "inline;name=\"request\"");
    partBuilder.setField("Content-ID", "request");

    builder.addPart(partBuilder.build());

    partBuilder = FormBodyPartBuilder.create("content",
            new InputStreamBody(request.getContentBytes(), ContentType.parse(request.getContentType())));
    partBuilder.setField(MIME.CONTENT_DISPOSITION, "inline;name=\"content\"");
    partBuilder.setField("Content-ID", "content");
    builder.addPart(partBuilder.build());
    builder.setCharset(StandardCharsets.UTF_8);

    HttpEntity entity = builder.build();
    post.setEntity(entity);
}