Example usage for org.apache.http.entity.mime FormBodyPartBuilder create

List of usage examples for org.apache.http.entity.mime FormBodyPartBuilder create

Introduction

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

Prototype

public static FormBodyPartBuilder create(final String name, final ContentBody body) 

Source Link

Usage

From source file:nl.nn.adapterframework.http.mime.MultipartEntityBuilder.java

public MultipartEntityBuilder addPart(String name, ContentBody contentBody) {
    Args.notNull(name, "Name");
    Args.notNull(contentBody, "Content body");
    return addPart(FormBodyPartBuilder.create(name, contentBody).build());
}

From source file:org.nuxeo.ecm.core.opencmis.impl.CmisSuiteSession2.java

protected HttpEntity getCreateDocumentHttpEntity(File file) {
    FormBodyPart cmisactionPart = FormBodyPartBuilder
            .create("cmisaction", new StringBody("createDocument", ContentType.TEXT_PLAIN)).build();
    FormBodyPart contentPart = FormBodyPartBuilder
            .create("content", new FileBody(file, ContentType.TEXT_PLAIN, "testfile.txt")).build();
    HttpEntity entity = MultipartEntityBuilder.create().addPart(cmisactionPart)
            .addTextBody("propertyId[0]", "cmis:name").addTextBody("propertyValue[0]", "testfile01")
            .addTextBody("propertyId[1]", "cmis:objectTypeId").addTextBody("propertyValue[1]", "File")
            .addPart(contentPart).build();
    return entity;
}

From source file:org.nuxeo.ecm.core.opencmis.impl.CmisSuiteSession2.java

protected HttpEntity getCheckInHttpEntity(File file) {
    FormBodyPart cmisactionPart = FormBodyPartBuilder
            .create("cmisaction", new StringBody("checkIn", ContentType.TEXT_PLAIN)).build();
    FormBodyPart contentPart = FormBodyPartBuilder
            .create("content", new FileBody(file, ContentType.TEXT_PLAIN, "testfile.txt")).build();
    HttpEntity entity = MultipartEntityBuilder.create().addPart(cmisactionPart).addPart(contentPart).build();
    return entity;
}

From source file:org.nuxeo.ecm.core.opencmis.impl.CmisSuiteSession2.java

protected HttpEntity getSetContentStreamHttpEntity(File file, String changeToken) {
    FormBodyPart cmisactionPart = FormBodyPartBuilder
            .create("cmisaction", new StringBody("setContent", ContentType.TEXT_PLAIN)).build();
    FormBodyPart contentPart = FormBodyPartBuilder
            .create("content", new FileBody(file, ContentType.TEXT_PLAIN, "testfile.txt")).build();
    HttpEntity entity = MultipartEntityBuilder.create().addPart(cmisactionPart)
            .addTextBody("changeToken", changeToken).addPart(contentPart).build();
    return entity;
}

From source file:it.greenvulcano.gvesb.virtual.gv_multipart.MultipartCallOperation.java

/**
 * Adds a Form Part on the Multipart call
 * /*from  w ww. jav a 2s. c  o m*/
 * @param nodeList
 * @param name
 */
private void createFormPart(NodeList nodeList, String name, String contentType) {

    this.contentType = getContentType(contentType);
    StringBody stringBody = new StringBody(name, this.contentType);
    formBodyBuilder = FormBodyPartBuilder.create(name, stringBody);

    IntStream.range(0, nodeList.getLength()).mapToObj(nodeList::item).forEach(node -> {
        try {
            if (!("Content-Type".equals(XMLConfig.get(node, "@name")))) {
                formBodyBuilder.addField(XMLConfig.get(node, "@name"), XMLConfig.get(node, "@value"));
            }
        } catch (XMLConfigException e) {
            e.printStackTrace();
        }
    });
    formBodyPart = formBodyBuilder.setName(name).build();
    multipartEntityBuilder.addPart(formBodyPart);
}

From source file:org.biouno.figshare.FigShareClient.java

/**
 * Upload a file to an article.//w ww  .j a v a 2 s  .  c  o  m
 *
 * @param articleId article ID
 * @param file java.io.File file
 * @return org.biouno.figshare.v1.model.File uploaded file, without the thumbnail URL
 */
public org.biouno.figshare.v1.model.File uploadFile(long articleId, File file) {
    HttpClient httpClient = null;
    try {
        final String method = String.format("my_data/articles/%d/files", articleId);
        // create an HTTP request to a protected resource
        final String url = getURL(endpoint, version, method);
        // create an HTTP request to a protected resource
        final HttpPut request = new HttpPut(url);

        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        ContentBody body = new FileBody(file);
        FormBodyPart part = FormBodyPartBuilder.create("filedata", body).build();
        builder.addPart(part);

        HttpEntity entity = builder.build();
        request.setEntity(entity);

        // sign the request
        consumer.sign(request);

        // send the request
        httpClient = HttpClientBuilder.create().build();
        HttpResponse response = httpClient.execute(request);
        HttpEntity responseEntity = response.getEntity();
        String json = EntityUtils.toString(responseEntity);
        org.biouno.figshare.v1.model.File uploadedFile = readFileFromJson(json);
        return uploadedFile;
    } catch (OAuthCommunicationException e) {
        throw new FigShareClientException("Failed to get articles: " + e.getMessage(), e);
    } catch (OAuthMessageSignerException e) {
        throw new FigShareClientException("Failed to get articles: " + e.getMessage(), e);
    } catch (OAuthExpectationFailedException e) {
        throw new FigShareClientException("Failed to get articles: " + e.getMessage(), e);
    } catch (ClientProtocolException e) {
        throw new FigShareClientException("Failed to get articles: " + e.getMessage(), e);
    } catch (IOException e) {
        throw new FigShareClientException("Failed to get articles: " + e.getMessage(), e);
    }
}

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 av  a 2  s. c o 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  v a  2s  . co 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);
}

From source file:org.apache.jmeter.protocol.http.sampler.HTTPHC4Impl.java

/**
 * //from w  w w .j ava  2 s. c om
 * @param post {@link HttpPost}
 * @return String posted body if computable
 * @throws IOException if sending the data fails due to I/O
 */
protected String sendPostData(HttpPost post) throws IOException {
    // Buffer to hold the post body, except file content
    StringBuilder postedBody = new StringBuilder(1000);
    HTTPFileArg[] files = getHTTPFiles();

    final String contentEncoding = getContentEncodingOrNull();
    final boolean haveContentEncoding = contentEncoding != null;

    // Check if we should do a multipart/form-data or an
    // application/x-www-form-urlencoded post request
    if (getUseMultipartForPost()) {
        // If a content encoding is specified, we use that as the
        // encoding of any parameter values
        Charset charset = null;
        if (haveContentEncoding) {
            charset = Charset.forName(contentEncoding);
        } else {
            charset = MIME.DEFAULT_CHARSET;
        }

        if (log.isDebugEnabled()) {
            log.debug("Building multipart with:getDoBrowserCompatibleMultipart():"
                    + getDoBrowserCompatibleMultipart() + ", with charset:" + charset + ", haveContentEncoding:"
                    + haveContentEncoding);
        }
        // Write the request to our own stream
        MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create().setCharset(charset);
        if (getDoBrowserCompatibleMultipart()) {
            multipartEntityBuilder.setLaxMode();
        } else {
            multipartEntityBuilder.setStrictMode();
        }
        // Create the parts
        // Add any parameters
        for (JMeterProperty jMeterProperty : getArguments()) {
            HTTPArgument arg = (HTTPArgument) jMeterProperty.getObjectValue();
            String parameterName = arg.getName();
            if (arg.isSkippable(parameterName)) {
                continue;
            }
            StringBody stringBody = new StringBody(arg.getValue(), ContentType.create("text/plain", charset));
            FormBodyPart formPart = FormBodyPartBuilder.create(parameterName, stringBody).build();
            multipartEntityBuilder.addPart(formPart);
        }

        // Add any files
        // Cannot retrieve parts once added to the MultiPartEntity, so have to save them here.
        ViewableFileBody[] fileBodies = new ViewableFileBody[files.length];
        for (int i = 0; i < files.length; i++) {
            HTTPFileArg file = files[i];

            File reservedFile = FileServer.getFileServer().getResolvedFile(file.getPath());
            fileBodies[i] = new ViewableFileBody(reservedFile, file.getMimeType());
            multipartEntityBuilder.addPart(file.getParamName(), fileBodies[i]);
        }

        HttpEntity entity = multipartEntityBuilder.build();
        post.setEntity(entity);

        if (entity.isRepeatable()) {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            for (ViewableFileBody fileBody : fileBodies) {
                fileBody.hideFileData = true;
            }
            entity.writeTo(bos);
            for (ViewableFileBody fileBody : fileBodies) {
                fileBody.hideFileData = false;
            }
            bos.flush();
            // We get the posted bytes using the encoding used to create it
            postedBody.append(new String(bos.toByteArray(), contentEncoding == null ? "US-ASCII" // $NON-NLS-1$ this is the default used by HttpClient
                    : contentEncoding));
            bos.close();
        } else {
            postedBody.append("<Multipart was not repeatable, cannot view what was sent>"); // $NON-NLS-1$
        }

        //            // Set the content type TODO - needed?
        //            String multiPartContentType = multiPart.getContentType().getValue();
        //            post.setHeader(HEADER_CONTENT_TYPE, multiPartContentType);

    } else { // not multipart
        // Check if the header manager had a content type header
        // This allows the user to specify his own content-type for a POST request
        Header contentTypeHeader = post.getFirstHeader(HTTPConstants.HEADER_CONTENT_TYPE);
        boolean hasContentTypeHeader = contentTypeHeader != null && contentTypeHeader.getValue() != null
                && contentTypeHeader.getValue().length() > 0;
        // If there are no arguments, we can send a file as the body of the request
        // TODO: needs a multiple file upload scenerio
        if (!hasArguments() && getSendFileAsPostBody()) {
            // If getSendFileAsPostBody returned true, it's sure that file is not null
            HTTPFileArg file = files[0];
            if (!hasContentTypeHeader) {
                // Allow the mimetype of the file to control the content type
                if (file.getMimeType() != null && file.getMimeType().length() > 0) {
                    post.setHeader(HTTPConstants.HEADER_CONTENT_TYPE, file.getMimeType());
                } else {
                    post.setHeader(HTTPConstants.HEADER_CONTENT_TYPE,
                            HTTPConstants.APPLICATION_X_WWW_FORM_URLENCODED);
                }
            }

            FileEntity fileRequestEntity = new FileEntity(new File(file.getPath()), (ContentType) null);// TODO is null correct?
            post.setEntity(fileRequestEntity);

            // We just add placeholder text for file content
            postedBody.append("<actual file content, not shown here>");
        } else {
            // In a post request which is not multipart, we only support
            // parameters, no file upload is allowed

            // If a content encoding is specified, we set it as http parameter, so that
            // the post body will be encoded in the specified content encoding
            if (haveContentEncoding) {
                post.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, contentEncoding);
            }

            // If none of the arguments have a name specified, we
            // just send all the values as the post body
            if (getSendParameterValuesAsPostBody()) {
                // Allow the mimetype of the file to control the content type
                // This is not obvious in GUI if you are not uploading any files,
                // but just sending the content of nameless parameters
                // TODO: needs a multiple file upload scenerio
                if (!hasContentTypeHeader) {
                    HTTPFileArg file = files.length > 0 ? files[0] : null;
                    if (file != null && file.getMimeType() != null && file.getMimeType().length() > 0) {
                        post.setHeader(HTTPConstants.HEADER_CONTENT_TYPE, file.getMimeType());
                    } else {
                        // TODO - is this the correct default?
                        post.setHeader(HTTPConstants.HEADER_CONTENT_TYPE,
                                HTTPConstants.APPLICATION_X_WWW_FORM_URLENCODED);
                    }
                }

                // Just append all the parameter values, and use that as the post body
                StringBuilder postBody = new StringBuilder();
                for (JMeterProperty jMeterProperty : getArguments()) {
                    HTTPArgument arg = (HTTPArgument) jMeterProperty.getObjectValue();
                    // Note: if "Encoded?" is not selected, arg.getEncodedValue is equivalent to arg.getValue
                    if (haveContentEncoding) {
                        postBody.append(arg.getEncodedValue(contentEncoding));
                    } else {
                        postBody.append(arg.getEncodedValue());
                    }
                }
                // Let StringEntity perform the encoding
                StringEntity requestEntity = new StringEntity(postBody.toString(), contentEncoding);
                post.setEntity(requestEntity);
                postedBody.append(postBody.toString());
            } else {
                // It is a normal post request, with parameter names and values

                // Set the content type
                if (!hasContentTypeHeader) {
                    post.setHeader(HTTPConstants.HEADER_CONTENT_TYPE,
                            HTTPConstants.APPLICATION_X_WWW_FORM_URLENCODED);
                }
                // Add the parameters
                PropertyIterator args = getArguments().iterator();
                List<NameValuePair> nvps = new ArrayList<>();
                String urlContentEncoding = contentEncoding;
                if (urlContentEncoding == null || urlContentEncoding.length() == 0) {
                    // Use the default encoding for urls
                    urlContentEncoding = EncoderCache.URL_ARGUMENT_ENCODING;
                }
                while (args.hasNext()) {
                    HTTPArgument arg = (HTTPArgument) args.next().getObjectValue();
                    // The HTTPClient always urlencodes both name and value,
                    // so if the argument is already encoded, we have to decode
                    // it before adding it to the post request
                    String parameterName = arg.getName();
                    if (arg.isSkippable(parameterName)) {
                        continue;
                    }
                    String parameterValue = arg.getValue();
                    if (!arg.isAlwaysEncoded()) {
                        // The value is already encoded by the user
                        // Must decode the value now, so that when the
                        // httpclient encodes it, we end up with the same value
                        // as the user had entered.
                        parameterName = URLDecoder.decode(parameterName, urlContentEncoding);
                        parameterValue = URLDecoder.decode(parameterValue, urlContentEncoding);
                    }
                    // Add the parameter, httpclient will urlencode it
                    nvps.add(new BasicNameValuePair(parameterName, parameterValue));
                }
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(nvps, urlContentEncoding);
                post.setEntity(entity);
                if (entity.isRepeatable()) {
                    ByteArrayOutputStream bos = new ByteArrayOutputStream();
                    post.getEntity().writeTo(bos);
                    bos.flush();
                    // We get the posted bytes using the encoding used to create it
                    if (contentEncoding != null) {
                        postedBody.append(new String(bos.toByteArray(), contentEncoding));
                    } else {
                        postedBody.append(new String(bos.toByteArray(), SampleResult.DEFAULT_HTTP_ENCODING));
                    }
                    bos.close();
                } else {
                    postedBody.append("<RequestEntity was not repeatable, cannot view what was sent>");
                }
            }
        }
    }
    return postedBody.toString();
}